diff --git a/.gitignore b/.gitignore deleted file mode 100644 index d4cfdf418..000000000 --- a/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -/classes -target -src/core/nbactions.xml -src/wmsservlet/src/main/webapp/WEB-INF/glassfish-web.xml -/ext -.settings -.java-version -nb-configuration.xml -.checkstyle diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 1759f946e..000000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,368 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.doc.comment.support=disabled -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=ignore -org.eclipse.jdt.core.compiler.problem.deprecation=ignore -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=ignore -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=ignore -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning -org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=disabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=public -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=ignore -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning -org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning -org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=ignore -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=ignore -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=ignore -org.eclipse.jdt.core.compiler.source=1.6 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=0 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=18 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=0 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=32 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=100 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=space -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index ba8814909..000000000 --- a/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,110 +0,0 @@ -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=false -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=true -cleanup.format_source_code=true -cleanup.format_source_code_changes_only=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=false -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_shapiro1 -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_OM -formatter_settings_version=12 -org.eclipse.jdt.ui.javadoc=true -org.eclipse.jdt.ui.text.custom_code_templates= -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -sp_cleanup.correct_indentation=false -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=false -sp_cleanup.organize_imports=false -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=false -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=false -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=false -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=false -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 87eb1f093..000000000 --- a/AUTHORS +++ /dev/null @@ -1,141 +0,0 @@ -$Source: /cvs/distapps/openmap/AUTHORS,v $ -$RCSfile: AUTHORS,v $ -$Revision: 1.21 $ -$Date: 2007/07/24 17:55:58 $ -$Author: dietrick $ - -People and organizations that have contributed to OpenMap ---------------------------------------------------------- - -OpenMap(tm) - The OpenMap group at BBN Technologies mailto:openmap@bbn.com - See the file LICENSE, OpenMap is a trademark of BBN Corporation - -Icon Collection - Dean Jones mailto:dean@gallant.com - Icons Copyright (C) 1998 by Dean S. Jones - http://www.gallant.com/icons.htm - -RPF Browse - The MITRE Corporation - Portions of the RPF Layer are derived with permission from - software provided by The MITRE Corporation. Those portions - are licensed by MITRE under one or more agreements to use - and, where authorized, sublicense the program, and are - copyright 1993 by The MITRE Corporation. - "Copyright (c) 1993 The MITRE Corporation. RPF Browse is - used with the permission of The MITRE Corporation." - -Erhard "ESchemainda" - Provided code fixing the SunPosition class to account for daylight - savings time correctly. - -Alexander Sokolov - Provided code fixing the DTEDFrameUtil class to correctly create the - DTED frame names for all latitudes and longitudes. - -Joe Warzecha - Provided changes to BufferedMapBean.java to speed up - refresh and fixed a NullPointerException when its used in a - JInternalFrame. - -Dan Schmitt (dan@computer.org) - of the Ranching Systems Group (http://cnrit.tamu.edu/rsg/) provided - the nexrad package, which displays nexrad rain data. He wrote the - LabelLayer, and subclassed the DateLayer to it. He also wrote the mapIt - example, which starts up the ImageServer to create an image. - -Michael Los - Provided the AbstractHandlerLocation idea, code and prodding. Also - submitted changes to the quadtree to make it serializable. - -Willie Macris - Provided a update which greatly lessoned the memory requirements of - the RpfCacheHandler, and helped out with the garbage collection. - -Ringo Wathelet (DSTO in Australia) - Provided the DistanceMouseMode. - -Paul Tomblin - Provided a fix for the quadtree rectangle test for bounds checking. - -David Gillespie (formerly from General Dynamics) - Provided fixes for a memory leak in the DTEDLayer and DTEDFrameCache. - -Colin Mummery - Ported the code from Chuck Gantz (chuck.gantz@globalstar.com) to -create the UTMPoint class, which translates UTM coordinates to decimal -degree lat/lons. Also created the DMSLatLonPoint, which represents -lat/lons in degrees, minutes, and seconds. Also contributed the mif -package that reads MIF files. - -Doug Van Auken - Provided a complete package that reads and writes ESRI Shape files (.shp, .ssx, and .dbf). - -Karl Stuempfle and Lonnie Goad working for OptiMetrics, Inc - Provided the code to convert OMGraphicList graphics to ESRI Shape files. - Provided EsriPlugIn GUI/selection modifications. - -Scott Nevin - Added code to the MIFLayer to allow to read more graphic types. - -Oliver Hinds - Added code to provide a preview panel in OMColorChooser, that lets you see what the color will look like with the current transparency setting. - -Eliot Lebsack - Provided a couple of new classes: -com.bbn.openmap.layer.shape.ShapeFileCrop, can create a new Shape file -with shapes from a certain area of another Shape file, and -com.bbn.openmap.gui.SaveAsVirtualImageMenuItem, which lets you set the -size of an image to create from the current map. - -Bart J. Geraci - Provided an update to the OMArrowHead, greatly improving the rendering/positioning of them. - -Thomas Paricaud - Provided the E00 Layer package, enabling the display of .e00 files. - -Eric Lepicier - Provided OMSpline classes and support for editing and decorating them. - -Bart Jourquin - Provided the MapBeanPrinter. - -David J. Ward - Provided the ScaleDisplayLayer. - -Uwe Baier - Provided the com.bbn.openmap.layer.mysql package. - -Simon Bowen - Added code to the MIFLayer package to speed up OMGraphicCreation, - and to handle scale filtering. Added support for TEXT and POINT - primatives. - -Dan Bitts - Provided the EditableOMScalingRaster classes. - -Land Software Engineering Centre for DND Canada - Provided extensive review and fixes for the MGRS Conversion algorithm. - -Sebastien Rosset of Cougaar Software - Provided several patchs to improve the roads package, add arrow support for OMPoly, J3D API updates. - -Tore Halset - Provided the WMS layer and servlet code and various improvements to support those additions, and continues to - provide valuable support to these packages. - -Todd Webb of L-3 Communications Titan Corporation - Provided updates to the SwingWorker, OMGraphicHandlerLayer and ProjectionSupport that greatly increased - the thread safety and interruptions due to rapid Projection changes. - -Carsten Madsen - Has provided many updates, updates and suggestions over the past years as a long-time user and supporter. - --------------------------------------- - -Thank you! - -If we've left you off this list - Sorry! Let us know - it's important -that we give credit where it's due. We really appreciate that people -take the time to submit code to us. diff --git a/CHANGELOG b/CHANGELOG deleted file mode 100644 index a95faa026..000000000 --- a/CHANGELOG +++ /dev/null @@ -1,4913 +0,0 @@ -2021-07-01 Donald Dietrick - - * Tagged OpenMap 6.0 - As you can see, 5 years worth of - significant modifications and architecture changes. - - * The project has been updated to be a maven project. You can - still use ant, but things go a lot smoother if you use Maven. - - * The directory class paths have been reorganized, significantly. - Classes have been moved. An IDE like NetBeans or Eclipse will - greatly assist you in fixing import statements if your project - depended on a previous version of OpenMap. - - * PlugIns have been removed. They have been replaced with Layer - classes that extend OMGraphicHandlerLayer. Plugins were removed - because they inserted a layer of unnecessary complexity to a - layer. - -2016-12-09 Don Dietrick - - * Tagged OpenMap 5.1.15 - - * MapBean internal listener support managers are final and - never get set to null, fixing a cleanup problem if listeners - try to disengage themselves from the MapBean after dispose() - has been called. - - * EditableOMPoly grab points now in synchronized list to - handle rapid clicks and repaints. - - * Updated MapTileLayer to have a property where the local file - cache can be saved or destroyed after use "saveCache". - - * BufferedImageHelper fixed issue where images weren't getting - reloaded from the file system, a cached version of the image was - being used instead. - - * MapTileCoordinateTransform has settable min/max zoom levels. - -2016-08-05 Don Dietrick - - * Tagged OpenMap 5.1.14 - - * MapTileLayer can be used in LayerAddPanel. - - * RPF modifications. Changed RpfProductInfo to be an enum instead - of a class, moved all defining information to it instead of being - listed in the RpfConstants class. Overhauled the RpfCoverage tool - used by RpfLayer, simplified it and the RpfCoverageManager. - Updated RpfFrameProvider to use List instead of Vector. Udpated - classes to use doubles instead of floats for coordinates. - - * Modified BasicMapPanel startup order to change when startup - projection settings are read and set on MapBean. - - * Update StandardMapMouseInterpreter to better handle events over - geometries. It also checks to see if the MouseEvent has been - consumed during mouseOver calls. - - * EsriGraphicList can return the EsriGraphic that has a certain - attribute in a specified column. - - * Removed shadow x and y and reference from ShapeLayer. - - * Modified OMScalingRaster to check h/w before trying to create - image warp object. - - * Added OMShape.PROJECTED class to represent shapes that are - defined in pixel space. Generation does nothing, rendering still - works. - - * Modified WebImagePlugin to warp images to match current OpenMap - projection. Also modified to make two separate queries when - crossing the dateline. - - * Added method in ProjMath to add distance between points in an - array of coordinates. OMDistance now uses this and the new - LineCoordinateGenerator class. LineCoordinateGenerator class will - create interpolated coordinates between two points, for great - circle or rhumb lines. - - * Updated RangeRingsMouseMode to take units property. - - * Modified NatCubicSpline to have an extended CLOSED inner class. - You create one or the other from static class methods. OMSpline - updated to use new design, and one is only created when it is - needed. - - * Added new app parts to OpenMapAppPartCollection, and created a - new standard OMGraphicHandlerLayer panel that can modify layer - transparency, bring up properties panel, and call doPrepare() on a - layer. - - * Modified methods in ColorFactory to handle 3 character color - definitions, and to return default value passed in if a - NumberFormatException is thrown. - - * Added VPFCoverageTrimmer, which will remove select tiles from - the dataset based on their location. - - * Changed Length class to enum. Updated other classes to use - getValues() when needed. - - * Modifcations to mapTile package. StandardMapTileFactory has an - overridable method to create desired file paths. Useful when - creating a factory with a unique naming convention for - tiles. Added TileGrabber, which will grab tiles from a server for - off-line use. - - * Added ALMOST_CLEAR to OMColor, to help with rendering some - OMGraphics against transparent backgrounds. - - * Modified classes to not use - OMGraphic.getAppObject()/setAppObject() methods, replaced - explicitly setting the OMGraphic.APP_OBJECT parameter in OMGraphic - attributes. - - * Modified files for javadoc cleanup, removing problem characters, etc. - - * Added new com.bbn.openmap.omGraphics.rule package, which is - taking the Rule objects from the - com.bbn.openmap.dataAccess.shp.DbfHandler and making them more - general. The DbfHandler Rules were modified to extend classes - from this package. - -2015-12-17 Don Dietrick - - * Tagged OpenMap 5.1.13 - - * Removed license language from several files that had been - inadvertently added due to IDE settings. - -2015-09-01 Don Dietrick - - * Merged fix to EsriPolylineList to return proper type - -2015-08-07 Don Dietrick - - * Tagged OpenMap 5.1.12 - - * Added the scaleOverCoverage property to the RpfLayer, and - modifying the RpfTocHandler to use it when determining the best - TOC entry for the current map query. It's true by default, but - when used for tiles (wmsservlet), the RpfLayer performs - better (fills in some empty tiles) with data it may have for - different scales. - - * Updated WMSPlugIn query to use correct CRS parameter for v1.3 - queries. - -2015-07-20 Don Dietrick - - * Tagged OpenMap 5.1.11 - - * Added flag (defaulting to true) to RpfTocHandler to tell it to - ignore zones of entries when evaluating coverage for projection. - This fix allows the layer to avoid choosing only entries that - match the projection zone, even though other options would provide - better coverage. Not a problem since subframes are scaled and - warped as necessary to match projection. This fixes the annoying - flipping coverage problem when panning N/S and crossing zone - boundaries, when you are zoomed out past the ideal scale for a - particular chart type. - -2015-03-12 Don Dietrick - - * Added bug fixes, including equalty check to avoid infinite loop - in EmbeddedScaleDisplayPanel, Moving to local variable in - OMPoly.generate for thread safety, updating WMSPlugIn to handle - WMS 1.3 requests. Updated OMRaster.computePixels length check. - -2015-02-06 Don Dietrick - - * Tagged OpenMap 5.1.10 - -2015-01-22 Don Dietrick - - * Updated ProjectionFactory to use getProjClassForName instead of - trying to make a class from a general string. This way, pretty - names can be used in the properties to set the default projection - type of the app. Updated to Logger. - -2015-01-21 Don Dietrick - - * Synchronization updates from Andrew Lloyd for OMGraphicList, - properly unsynchronizing on methods and synchronizing on - iterations. - -2015-01-07 Don Dietrick - - * Updated projections to pan using Rhumb calculations instead of - GreatCircle calculations, which was causing a slight skew to the - equator when going east-west. - -2014-12-18 Don Dietrick - - * Tagged OpenMap 5.1.9 - - * Fixed the OMScalingRaster, was drawing full-sized image when the - bounds said it should be totally off the map. - -2014-12-15 Don Dietrick - - * Tagged OpenMap 5.1.8 - - * Modified the OMGraphicHandlerLayer threading and locking code. - - * Added ImageWarp methods to make it easier to use as a standalone - object. - - * Updated precision for Planet NM constants. - - * Updated the MapBean and MapHandler listener handling code. - - * Removed the iis directory and WebService. It will no longer be - maintained or tested. - -2014-11-19 Don Dietrick - - * Tagged OpenMap 5.1.7 - - * Updated the MapBean, BufferedMapBean, BufferedLayerMapBean and - BufferedLayer to handle flashing better, especially with - background layers. Also fixed a problem in BufferedLayer where it - was resetting the rotation angle in the projection, causing all - the icons and labels to rotate with the map instead of staying - straight up. - - * Updated com.bbn.openmap.util.WebBrowser to be an abstract class - that the InformationDelegator uses to launch web pages. If no - WebBrowser implementation is specified, the InformationDelegator - uses the simple MiniBrowser in OpenMap. If the BrowserLauncher2 - jar file is in the classpath the new - com.bbn.openmap.util.BrowserLauncher2WebBrowser class can be - specified in the InforamtionDelegator properties to be used for - displaying websites. Removed the old BrowserLauncher code. - - * Updated import statements to remove unused classes. - - 2014-10-17 dietrick - - * Tagged OpenMap 5.1.6 - - * Modified Layer, BufferedLayer, BufferedLayerMapBean and MapBean - to eliminate the flashing effect caused when faster-responding - layers were paired with slower-responding layers, and the map - background would be seen briefly. Now, when the - BufferedLayerMapBean is used, its BufferedLayer is consulted to - make sure all 'background' layers are ready before repaint() - requests are forwarded to the AWT mechanism. Layers are ready - when repaint() is called on them. - -2014-10-16 dietrick - - * Tagged OpenMap 5.1.5 - - * Removed sinh from MoreMath, the standard Math function should be - used instead. Updated Mercator to use it. Updated - OMGraphicHandlerLayer threading model to handle workerComplete() - better. There were situations where a canceled worker could - result in two or more more threads locking up on prepare(). - OMList updated so that processAllGraphics is true by default, was - causing an extra loop through graphics to check visibility for - sublists. Updated iterator methods to iterate over shallow copy - of graphics. - - * Added check in OMWarpingImage.render() to check isRenderable(). - -2014-09-18 dietrick - - * Tagged OpenMap 5.1.4 - - * Updated OpenMapFrame to use Height, Width properties defined the - same way as in the Environment class. The OpenMapFrame no longer - looks for a PropertyHandler in the MapHandler, the OpenMap class - will provide the properties to it right after it's created. The - OpenMapFrame now consistently follows the height/width settings, - and the openmap.properties Height/Width properties have proper - capitalization. - - The PropertyHandler.Builder class has a build method, which is now - used by updated Main and OpenMap classes. OpenMap and Main now - have Logger member variables, moving away from Debug. - - * Updated OMGraphicAdapter to handle TexturePaint masks property - during Serialization. The SerializableTexturePaint was added to - help with this. - - * Modified OMScalingRaster so local handles to clipRect are used - for positioning, to help with multithreaded environment. The old - way was causing NPE to appear under certain conditions. Local - handles were also implemented in the NavMouseModes for the same - reason. - - * Updated BLMapBean has been updated to use an almost entirely - transparent background so that semi-transparent layers will render - property. Previously, semi-transparent layers would not appear. - - * Updated RPF catalog with entries from latest version of specification. - -2014-07-28 dietrick - - * Tagged OpenMap 5.1.3 - -2014-07-25 dietrick - - * Modified OMRasterObject/OMScalingRaster/OMScalingIcon image - handling. The projected image is no longer held in memory. - Instead, the transform, created in generate(), is saved and - applied when rendering. OMScalingIcon figures out when the image - doesn't need to be scaled and just draws it in that case. - - * Modified BufferedMapBean, BufferedLayer and MapBean, adjusting - the image buffers to be cleaned and reused when the size doesn't - change. - - * Some layers have been tweaked - OMGraphicHandlerLayer will print - out an information message if memory exceptions occur, - SimpleAnimationLayer moves the sprites a bit more. - -2014-07-07 dietrick - - * Tagged OpenMap 5.1.2 - - * AbstractProjectionChangePolicy.java change recent modifications - so that if a layer's previous and current OMGraphicList are null, - repaint isn't called on the layer. Previously, empty - OMGraphicLists prevented repaint from being called too, and that - has bad side-effects. - -2014-06-18 dietrick - - * Tagged OpenMap 5.1.1 - - * Made some memory usage improvements to the MapBean rotation - components, the rotated image buffer is reused under most - conditions. Added more cleanup to BufferedImageRenderPolicy. - - * Added comments/README to the WMS servlet components. - - * Modified the SpatialIndex to use a separate ArrayList for entry - traversal when responding to a projection change. - -2014-05-14 dietrick - - * Tagged OpenMap 5.1.0 - Since the API signatures have changed for - some components, the minor version number is being - increased. Details following. - - * Updated the MapBean (and subclasses) to handle rotation better. - When a rotation angle is set on the MapBean, it starts to use a - RotationHelper (inner class) to create a new image buffer for a - projection large enough to cover the corners of the map. The - RotationHelper handles the rotated map. The paintChildren() - method has been updated to only render layers. Rendering of the - PaintListeners and Border are handled by separate methods called - from the paint() method. To get the map to render fully when - rotated, the clip area is disabled when the map is rotated. - - The MapBean has new methods to use when working with rotation. - The MapBean inverse method gives you map coordinates taking into - account rotation. The getRotatedProjection provides the - projection being sent to the layers at any given time, while - getProjection always provides the original projection. The best - place to see how these methods are used is to check out the - listenerPaint methods in the MouseModes. - - OMText and OMScalingRaster OMGraphics pay attention to the - OMGraphicConstants.NO_ROTATE attribute. If that attribute is set, - they will always appear at their rotated angle relative to the - MapBean boundaries. OMTextLabelers always have that attribute - set, so they will automatically correct for rotation. - - * Updated Projections to have a rotationAngle member variable. - This member variable is only present to pass the setting from the - MapBean on to OMGraphics, in case they want to modify themselves - with regard to rotation. Projection objects themselves don't use - this member variable. The panning method in Projections was also - fixed. There was an issue with the pan command for directions - other than the 8 pre-defined directions. Now panning works for - all directions, and when the map is rotated. - - * Added AbstractProjectionChangePolicy to handle common projection - change policy functionality. IMPORTANT: The OMGraphicHandlerLayer - SwingWorker has been modified so it doesn't automatically call - repaint on the layer when the thread is complete. The - AbstractProjectionChangePolicy handles calling repaint() on the - layer, after determining the layer has something to paint. If a - layer (before a projection change had no OMGraphics to paint, and - after the projection change still doesn't have OMGraphics to - paint) isn't contributing to the map, repaint() will not be called - on it. You can override this behavior by setting a different - ProjectionChange policy on the layer. - - * Updated the OMGraphicAdapter (base class for all OMGraphics) - setLabelLocation method signatures so the projection is also - passed in. This allows OMTextLabelers to figure out how to not be - affected by map rotation. The old method signatures have been - deprecated. - - * Updated the MouseModes to handle rotation. They have been - modified to be PaintListeners and paint directly on top of the map - instead of using XOR drawing techniques. Their code has been - refactored and their API signatures have changed slightly. TODO: - There is a known issue with the PanMouseMode map rendering when - the map is rotated. The current work-around is to have the - AzimuithPanner enabled for all projections when the map is - rotated. I've also seen a issue with the - NavMouseModes/DistanceMouseMode rendering when the 1) map is - rotated 2) on a Mac and 3) the ToolBar is visible. The rendered - graphics are offset lower than they should be (height of ToolBar). - - * Modified the PaintListener interface so the source object is - also provided in the listenerPaint method signature. - - * Updated EditableOMPoly setGrabPoints methods to be safer when - dealing with poly coords and projections. - -2014-03-13 dietrick - - * Tagged OpenMap 5.0.4 - -2014-03-12 dietrick - - * Added a GUI button to the MapTileLayer to delete the tile cache - on disk for those layers using a ServerMapTileFactory. Disabled - for layers solely relying on a single map tile directory accessed - locally. - - * Improved the property handling of the ommaptileservlet so that - the web.xml specifies a property directory instead of the - properties files themselves. Moving a new properties file into - the directory (which specifies a new tile set) and reloading the - servlet will load the new tileset or any changes. Update the - MapTileMaker to implement EmptyTileHandler, which allows - ommaptileservlet to generate tiles on the fly when they are - needed, caching them for later requests. - - * Fix for Geo.azimuth(Geo) method, which provided incorrect - answsers moving away from the equator. Replaced with the - GreatCircle.sphericalAzimuth algorithm while taking advantage of - Geo's ellipsoid model. - - * The com.bbn.openmap.dataAccess.shape package has some bug fixes, - including some addition null pointer exception checks, a fix for - off-by-one problem with extents, polyline/polygon M types being - incorrectly sent to the Z methods. - - * WholeWorldTileHandler has improved source directory handling. - -2013-11-25 dietrick - - * Tagged OpenMap 5.0.3 - - * Added delete() method to FileUtils. - -2013-11-24 dietrick - - * OMGraphic interface has been updated with isRenderable, draw and - fill methods that take a Shape object as an argument. The old - implementation methods are no longer synchronized. For - BasicGeometry, the getShape() and setShape() methods are - synchronized and all instances of direct access to the shape - object have been replaced with calls to these methods. All render - methods in OMGraphic implementations have been updated to use one - getShape() call, and then use that handle to a shape for checks - and drawing. This greatly improves rendering performance. The - OMList implementations that build a single shape from parts have - been updated to have more efficient algorithms for building - shapes. - - * Updated the SimpleAnimationLayer for more control over the - sprites. You can set the number of sprites for a batch add, the - timer was changed to a java.util.Timer that uses a Task for - updating the sprites. The GUI was updated to use GridBagLayout - and has some new controls. Deleted the - com.bbn.openmap.graphicLoader.AnimationTester class, it was - outdated. - - * Updated LayersMenu to use an object lock for the layer with the - menu entries. - -2013-11-12 dietrick - - * Tagged OpenMap 5.0.2 - - * Created the MapTileRequester interface, which lets the - MapTileFactory ask it whether it should keep working. If - provided, the StandardMapTileFactory will use the requester as - tiles are fetched to determine if the tile group fetch is still - relevant. The MapTileRequester interface replaces the - MapTileFactory repaintCallback member variable. - - * Reverted the Geo.intersect method to use the former algorithm. - The newer algorithm was faulty and broke code. - - * Updated MapTileLayer to implement the mapTile MapTileRequestor - interface, which also uses the new wrapItUp flag discussed below. - The repaintCallback repaint() calls made in the MapTileFactory - were moved back into this layer, using the MapTileRequester - notifications. - - * Updated layer classes in the com.bbn.openmap.layer.test - package. The GeoIntersectionLayer was reformatted, and the - GeoTestLayer was restuctured to use more regular data. - - * Added a boolean flag, wrapItUp, to the OMGraphicHandlerLayer. - Means something slightly different than interruptable. WrapItUp - gets set to true if another SwingWorker is queued to run, due to - another doPrepare() call or projection change. If interruptable - is set to true, the current SwingWorker is killed, and the state - of some things might be in flux. If a layer is marked as - uninterruptable to avoid this state of flux (think loading image - files), the wrapItUp flag lets the layer decide when to stop - working if it wishes. - - * Added check to OMScalingRaster for lastProjection, so a clone of - the projection is only made if it changes. - - * Added threading to FileUtils chooser methods, so if they aren't - called in the event thread they will still appear. - -2013-08-19 dietrick - - * Added the GoogleMapTileFactory as an example of how to extend - the MapTileFactory to contact different services. Added the - ability for MapTileLayer to display map data attribution. - -2013-07-27 dietrick - - * Moved default LINETYPE for shape files from GREAT_CIRLCE to - STRAIGHT. That should speed things up a bit. - - * Added com.bbn.openmap.layer.learn.SimpleAnimationLayer, a little - tutorial example of doing animation on OpenMap. Borrows a lot for - the AnimationTester, which was also refreshed. - - * Added OMGraphicHandler to the interfaces that - OMGraphicHandlerLayer implements. It used to implement that - interface, and should have been, obviously. - - * Fixed off-by-one errors in the AreaHandler. - -2013-07-03 dietrick - - * Fixed some JavaDoc errors, added update to Gnomonic Projection. - -2013-07-03 dietrick - - * Released OpenMap 5.0.1 - -2013-06-19 dietrick - - * Added NPE checks to BufferedImageRenderPolicy and OMScalingRaster. - - * Added width acessors to OMText. Added Executor methods to - TaskService to allow customization and control for Layer - threading. - -2013-05-20 dietrick - - * Updates to OMScalingRaster to gracefully handle memory - exceptions if the scaled image is too big. Updated javadocs and - java comments in these classes, added Logger for ScaleFilterLayer. - - * Refactored the LayerHandler so it uses a List internally - to manage Layers. Created the LayerConfigurationListener interface - and LayerConfigurationListenerSupport object, both of which are - used by the LayerHandler to pre-notify components when the active - layers for the application are about to change. The - LayerConfigurationListener has the opportunity to make - modifications to the layer configuration, or change visibility of - other layers, etc. Added the BasicLayerConfigurationListener, an - example component that changes the projection of the MapBean to - CADRG if an RpfLayer is active. - -2013-04-13 dietrick - - * Cleaned up debugging. Updated LOS code API for better control. - Updated WMSPlugIn setProperties so the current values aren't - zeroed out of they aren't set. - -2013-04-23 dietrick - - * Moved the smarts for zoom levels out of the MapTileMaker class - and put them in the MapTileCoordinateTransform classes. Added - AbstractMapTileCoordinateTransform class to merge similar methods - and functionality for existing mtct classes. Updated other - classes to call mtc functions instead of MapTileMaker static - functions. - -2013-04-16 dietrick - - * Added RelayMapTileSet for MapTileServlet, which fetches tiles - from a remote server and caches them locally. Updated - TerrainLayer to eliminate some verbose error messages. - - * Added Kevin's (kpfarr) fix to RpfTocHandler for merging entry - coverages properly. - -2013-03-02 dietrick - - * Added the ClckOrDrgUndefinedState to the omGraphics.editable - package, which is now the super class of LineUndefinedState, - RectUndefinedState and CircleUndefined state. Lines, Rects and - Circles can now be defined with a click and mouse move to next - point, or with a press and drag to the next point, just like - polys. - -2013-03-01 dietrick - - * Fixed the ImageTile outline behavior on projection changes. - Fixed bug in GeoTIFF code introduced via a FindBugs modification, - and tweaked the ImageTileLayer GUI to handle list selection - better. - -2013-02-28 dietrick - - * Added some data/vpf vmaplv0 configuration files with more - instructions on how to use the VPFFeatureLayer. - - * Fixed the VPF attribute fetching with proper indexes. The VPF - package api changed in a deep section, to allow the proper feature - id to be passed to the place where it's needed to fetch - attributes. - - * Added intersets method to DataBounds. Can be tested with new - BoundsTestLayer in layer.test package. - - * Updated SwingWorker and PooledSwingWorker to use FutureTask - objects, reducing the number of threads that are created. Updated - OMGraphicHandlerLayer.workerComplete to take a ISwingWorker in its - signature. - - * Modified DemoLayer to have separate OMGraphicList for storage, - loading aux OMGraphicList for painting. - -2013-02-27 dietrick - - * Made a bunch of adjustments as recommended by FindBug, regarding - null pointer checks, equality checks, stuff like that. - - * Added AzimuthPanner abstract class with Standard and Shapefile - subclasses. This class is used by the PanMouseMode and - OMMouseMode for panning when the projection is Azimuthal. The - modes used to translate the map image, the new class renders - things instead. The AzimuthPanner.Standard is used if a shapefile - for the mousemode is not defined. - - * Modified how the DrawingToolLayer tool buttons react to - toggling. Toggling the tool button will deactivate the drawing - tool, returning mouse control to the application. - - * Updated the mapTile package, allowing the frames to be defined - by a regex that fits how to ask for tiles from a server or - directory location. Locations can include {x}{y}{z} where x,y,z - are x and y tile coordinates at z zoom level. This regex can be - defined as the rootDir of a MapTileLayer. - - * Fixed the BeanBox example, since it was moved. Updated the - manifest.txt to remove outdated beans. - -2012-01-27 dietrick - - * Added the maptileservlet package. This servlet package provide - map tiles and can be used with the MapTileLayer using the - ServerMapTileFactory, and can also be easily be used with Leaflet. - - * Misc updates to remove extra semi-colons and fixed some - compiling warnings. - - * Modified OMArc to take a Point2D object instead of a - LatLonPoint. This allows it to be used with the Cartesian - projection. - - * Modified WholeWorldTileHandler to have more control over how it - creates jar files holding map tiles. Can now create specific - subjars, control whether the master jar gets created, etc. - - * Added TileMillMapTileFactory to - com.bbn.openmap.dataAccess.mapTile package, and also added the - sqlite jar to the ext directory. This MapTileFactory can read the - output tile database files created using the TileMill application. - - * Tweaked the API, got rid of new Grey*TileFactory classes in the - com.bbn.openmap.dataAccess.mapTile package, created new - TileImagePreparer and added Grey and standard versions of that - instead. Now the StandardMapTileFactory and ServerMapTileFactory - can have different classes handing images, and those classes can - be swapped at runtime. - - * Fixed build problems when ext directory was missing. - -2011-12-23 Knox Rogers - - * OpenMap 5.0 released - -2011-12-06 dietrick - - This entry is a summary of the changes made to OpenMap between the - 4.6.5 release and the 5.0 release. The API has changed - significantly for the Projection classes, and that's the main - reason for the major version change. - - The Projection classes used to translate decimal degree lat/lon - point objects to java.awt.Point x/y pixel coordinates. The new - Projection classes make translations using Point2D objects. - LatLonPoint has been moved inside the com.bbn.openmap.proj.coords - package, and now extends Point2D. The pixel locations returned - from the Projection are also Point2D objects. If you've written - any code that calls Projection methods, you may have to modify - that code to work with the changes. - - Throughout the code, there have been changes to incorporate - Generic types, utilizing StringBuilder methods, moving from the - com.bbn.openmap.util.Debug class to the Java logging mechanism, - implementing equals() and hashcode() methods. - - OM5 requires the Java 5 runtime. - - * com.bbn.openmap - - Updated BufferedMapBean to handle panning better, shifting current - map image appropriately until the layers react to the projection - change. - - The Layer class has been updated to have a GeoCoordTransformation - member variable, for data that isn't stored in decimal degree - lat/lon coordinates. - - MapBean updated to have a handle on its ProjectionFactory. - - Update the MapHandler class with generified methods. - - Added the notion of isolation to the MapHandlerChild, so it will - ignore BeanContext events it receives from other BeanContext - objects that it doesn't know about. - - Updated PropertyHandler so it's not tied to the openmap.properties file name. - - * com.bbn.openmap.app - - Added a couple of new application-type classes. The Main - application represents the new OpenMap app look, and it utilizes - the new OverlayMapPanel. - - The TimeFrameApp uses the HotwashPanel and some of the new time - management components. - - * com.bbn.openmap.app.example - - Moved SimpleMap and SimpleMap2 here. - - * com.bbn.openmap.dataAccess.cgm - - Added components that all more sections of the CGM files to be - read, like constants, colormodel, colortable, marker - representation and marker size. - - * com.bbn.openmap.dataAccess.mapTile - - This new package deals with map image tiles, the kind that are - used in OpenStreetMap/Google/GDAL tiles, etc. - - The MapTileFactory classes read tile sets for the MapTileLayer and - creates images for display on the map. - - The StandardMapTileFactory reads tiles stored locally. - - The ServerMapTileFactory can fetch tiles from a URL (where tiles - are stored under a root location plus z/x/y.png type location). - - The ServerMapTileFactory will store the images it fetches locally - to reduce the load on the server. The - GreyStandard/ServerMapTileFactory classes convert the images to - greyscale. - - The EmptyTileHandler classes tell the factory classes how to - handle missing tiles, whether to do nothing, create new tiles or - use a default tile to fill the area in. - - The OpenStreetMap tiles are stored a little differently than tiles - that meet the TileMappingService configuration (like the tiles - GDAL creates). You can use the OSMMapTileCoordinateTransform for - OpenMap/OpenStreetMap tile sets, and the - TMSMapTileCoordinateTransform for GDAL image tile sets. - - The MapTileMaker can create map tile sets from OpenMap layers. - The MapTileMakerComponent can be added to the OpenMap application - to visualy define and launch MapTileMaker tile creation. - - * com.bbn.openmap.dataAccess.shape - - Added a DbfTableModelFactory class that helps create DbfTableModel - for an EsriGraphicList when the data is read in. - - Added ShapeGeoIndex, an ExtentIndex implementation created from a - shape file. This ExtentIndex can be used with the uses the - com.bbn.openmap.geo package components to discover intersections - with other extents (points, paths, regions, etc). - - * com.bbn.openmap.event - - Added two new sets of event objects. Added OMEvent class, which - is a object representing something that happens at a certain time. - The OMEvent class is accompanied by the OMEventComparator and - OMEventHandler, and some other components to aid in selection and - filtering of OMEvents. These component tie into the new - com.bbn.openmap.time components and TemporalOMGraphics. - - Added Undo classes (UndoEvent, UndoStack, UndoStackSupport and - UndoStackTrigger). These components are currently used by the - drawing tool undo/redo capability, but can be used by any - component that wants to save and restore state. - - Added the OMMouseMode, which is a combination of the PanMouseMode - and SelectionMouseMode. The behavior is similar to - standard/expected web map mouse behavior. - - * com.bbn.openmap.examples - - Removed this package. The beanbox example is now under - com.bbn.openmap.layer.beanbox. hello and crew packages were - obsolete, and the simple applications have been moved up to app. - - * com.bbn.openmap.gui - - Added the OverlayMapPanel, an extension of BasicMapPanel that - knows how to layer other components with the map so they appear as - if they are floating on it. The EmbeddedNavPanel and - EmbeddedScaleDisplayPanel are two components the OverlayMapPanel - uses. The DistQuickTool is used by the panel to quickly measure - distances on the map. - - The HotwashPanel is a new BasicMapPanel that has sliders built - into it. It was created to house the new time controls and event - lists on the bottom and to the left. - - The event subpackage contains components that manage and display - OMTime events. - - * com.bbn.openmap.image.wms incorporated many changes from Tore - Haslet that added compatibility with WMS 1.3, including - capabilities queries and projection translations. - - * com.bbn.openmap.layer.event - - Added the EventLayer and supporting components. The EventLayer - handles TemporalOMGraphics and uses the new com.bbn.openmap.time - management components. - - * com.bbn.openmap.layer.imageTile - - Added the MapTileLayer. The layer uses the new - com.bbn.openmap.dataAccess.mapTile components to render - OpenStreetMap/GDAL/Google map tiles. - - * com.bbn.openmap.layer - - Updated OMGraphicHandlerLayer to utilize the new ISwingWorker classes. - - * com.bbn.openmap.layer.policy - - Added NullProjectionChangePolicy that does nothing when the - projection changes, and added the PanningImageRenderPolicy, to be - used by layers that want to redraw what they have when the - projection changes. A buffered image is reprojected and reused - until the layer can update for the new projection. - - * com.bbn.openmap.layer.util - - Added DataPathWanderer class, extending Wanderer, that finds valid - data paths for a data user. Base class for creating a data auto-finder. - - * com.bbn.openmap.layer.vpf - - Added VPFFeatureLayer and supporting classes. This layer uses - priorty files and GeoSym information/cgm files to order and render - features from VPF. New files added to share/data/vpf directory to - support DNC. - - Added VPFFeatureInfoHandler that lets you get attribute - information for features. Configurable via properties. Can be - extended to display attribute in different ways. The - TTFeatureInfoHandler displays attributes in a tooltip. - - * com.bbn.openmap.omGraphics - - The OMGraphics have been updated to double precision. - - OMGraphic is now an interface, with OMGraphicAdapter being the base class. - - DrawingAttributes have new transfer methods that make it easier to - clone and copy settings. Added Builder class to make it easier to - make it more convenient to create and make settings on a new - instance. - - Added GraphicUndefinedEditState to the editable subpackage, for - OMGraphics in the process of being defined by the drawing tool. - It's a state that defines when an OMGraphic is only partially - defined. - - OMGraphicList and OMGeometryList extend OMList, which itself - implements the List interface. They are now iterable, and use - Generic Types to define what is held in them. - - Added OMWarpingImage, which is a raster OMGraphicClass that warps - its image to the current OpenMap projection (during generate). - - Added the time subpackage, which defines interfaces for OMGraphics - that change over time. TemporalOMPoint and TemporalOMScalingIcon - are two implementations of that interface. - - Added ImageWarp class to the util subpackage, which does the - heaving lifting work of the OMWarpingImage. - - Added RibbonMaker class to the util subpackage, which creates a - buffer area around a vector shape. - - * com.bbn.openmap.proj - - The proj package classes have undergone a significant API change, - as described in the summary above. For the top-level Proj class - and Projection interface, the Point references for projected - locations have been replaced with Point2D objects. The - LatLonPoint references have been replaced with Point2D references. - The old projection classes now extend the GeoProj class, and the - Point2D objects meant to indicate latitude/longitude points are - LatLonPoints. - - There is a Cartesian projection for standard X/Y drawing. You can - use the OMShape object for drawing things in a Cartiesian - projection. Other OMGraphics will work too, but the lat/lon - coordinates are interpreted as x/y coordinates. - - Deleted the ProjectionFactoryLoader and the View classes. The - ProjectionFactory is no longer a singleton, there's a different - ProjectionFactory for each MapBean, and each MapBean can have a - different set of Projections it can handle. - - * com.bbn.openmap.proj.coords - - All of the coordinate point classes and methods have been moved - here, including LatLonPoint and VHTransform. Updates to GCT - classes. - - LatLonPoint was rewritten to inherit from Point2D, and is modeled - after that class with Float and Double implementations. Note that - overridden Point2D methods have (x,y) signatures, while - LatLonPoint.setLocation(lat, lon) methods have (y, x) signatures. - - * com.bbn.openmap.time - - Created new time package, moved older time components here just to - make them more application-friendly. Added components that - understand the notion of time bounds and managing the notion of a - point in time. - - * com.bbn.openmap.tools.drawing - - Updated OMDrawingTool to use UndoStack and triggers to handle edit - undos and redos. - - * com.bbn.openmap.tools.symbology.milStd2525 - - Added SVGSourceFileReorganizer, a class that takes the - distribution package from DISA and flattens the files out into a - target directory, renaming them as needed for the - SymbolReferenceLibrary. - - * com.bbn.openmap.util package - - Added AbstractXMLParser class, a base class for XML parsing, wraps - the DefaultHandler java class. - - Added Attributable interface, describing classes that can handle - an attribute map. - - Added ClasspathHacker, which adds jars to classpath at runtime. - - Added MGRSCoordInfoFormatter, which formats coordinates into MGRS format. - - DataBounds updated to use Point2D objects, add method added. - - Added DeepCopyUtil, which handles cloning propery. OMGraphics updated to use it. - - FileUtils updated to have new zip writing algorithm, methods. - - Added HashCodeUtil to assist in creating proper hash code values. - - Added ISwingWorker interface and updated OMGraphicHandlerLayer to - use it, so other implementions could be used in the layer. Added - PooledSwingWorker, implementing a reuseable SwingWorker. Added - TaskService to manage SwingWorkers. - - PropUtils added methods to create objects from property - list (standard openmap.properties paradigm). parseColor method - returns a Paint object instead of a Color object. - - Updated Wanderer class to be able to handle exhaustive and - non-exhaustive searches. - - Moved former com.bbn.openmap.layer.util.http/html/stateMachine - packages to this util package. - -2009-03-26 Don Dietrick - - * Refined the DTED packages, removing duplicate classes in - com.bbn.openmap.layer.dted and having those classes refer to the - com.bbn.openmap.dataAccess.dted package contents. The - com.bbn.openmap.layer.dted.DTEDFrame has been changed to - DTEDSubframedFrame, and now extends the DTEDFrame class in - dataAccess.dted. The DTEDLayer is the main class in - com.bbn.openmap.layer.dted, and those classes use the - DTEDSubframedFrame. The - com.bbn.openmap.layer.dted.DTEDFrameCacheLayer uses the classes in - the com.bbn.openmap.dataAccess.dted package. The choice between - the two is memory usage (when DTED is used by other components it - can also be used by DTEDFrameCacheLayer) vs - speed (the DTEDLayer is faster). - -2009-03-24 Don Dietrick - - * Added com.bbn.openmap.omGraphics.util.ImageWarp, which takes an - image file and warps it to fit a given projection. Can be created - with a image path or BufferedImage, takes a DataBounds or - WorldFile object to specify where the image is, and also takes a - GeoCoordsTransformation to handle preprojected images. Also added - the com.bbn.openmap.omGraphic.OMWarpingImage that wraps around an - ImageWarp object to display the image on the map as an OMGraphic. - - * Modified the DataBounds object to provide height and width - calculations (deltas between max and mix), and can also have an - internal DataBounds object that serves as hard limits for added - values. The hard limits override any point values that may be - added. - - * Simplified the OMApplet.html file, with simple APPLET tags. - - * Removed com.bbn.openmap.LatLonPoint. The - com.bbn.openmap.proj.coords.LatLonPoint is the class to use now. - - * Fixed problem where the ProjectionSupport thread continued to - run, preventing garbage collection of the MapPanel and all its - contents. That thread gets interrupted when the MapBean is - disposed. Added dispose() methods on MapPanel, MapBean, - ProjectionSupport, OpenMapFrame that release objects. Dispose - should be called on the MapHandler, and when OMComponents detect - they have been removed from the MapHandler in their findAndUndo - method, they should call dispose() on themselves if they have that - method. - - * The ProjectionFactory is no longer a singleton. A - ProjectionFactory is expected to be placed in a MapHandler, where - it will attach itself to the MapBean and can be accessed through - the MapBean. If a ProjectionFactory is not set and requested from - the MapBean, the MapBean will create a ProjectionFactory with the - default set of ProjectionLoaders. The ProjectionFactoryLoader - class has been removed, and that functionality (creating - ProjectionLoaders from Properties) has been incorporated into the - ProjectionFactory. The ProjectionFactory should be created like - any other component added to the MapHandler, via the properties or - programmatically added to the MapHandler. - -2009-03-14 Don Dietrick - - * OpenMap 5.0 released as beta via SVN repository. All further - changes will apply to version 5.0. OpenMap 5.0 requires Java 5 - (jre 1.5.x). - - * The com.bbn.openmap.proj.coords.LatLonPoint has been created - and it extends java.awt.Point2D. You can instantiate - LatLonPoint.Double and LatLonPoint.Float classes, just like - Point2D. Note that the Point2D methods follow the x, y ordering - of arguments, but that the setLocation() methods of LatLonPoint - follow the lat, lon ordering. The old LatLonPoint currently - extends the new LatLonPoint.Float object. - - * The Proj/Projection class and interface are now based on - java.awt.Point2D objects. The GeoProj class extends Projection, - and Point2D objects in coordinate space are now LatLonPoints as - allowed with Generics. The Cartesian projection handles projected - data. - - * The OMShape object is added to handle cartesian shapes, taking - java.awt.Shape objects and managed as an OMGraphic. - -2009-03-05 Don Dietrick - - * OpenMap 4.6.5 released. - -2009-02-27 Don Dietrick - - * The CSVTokenizer was updated to properly handle empty fields in - front and end of lines. - - * The projection package was updated with the DatumShiftProjection - which wraps projections to provide datum shifting. The - CoordinateReferenceSystem has been updated to use new - GeoCoordTransformation objects for different projection types. - - * For OMGraphics, the EditableOMPoly, OMGraphicList and OMText all - had minor bug fixes. Polygons are now re-editable after colors - are modified, OMGraphicLists had selection problems patched, and - OMText FontSizer setter was fixed. - - * MapHandler was modified with an overriding remove method that - also checks to see if an object being removed was a - BeanContextMembershipListener. The parent class was adding such - objects to a special list when they were added, but not removing - them from that list when they were removed from the context. This - was causing a memory leak of sorts. - - * Added MapBean.dispose() method, which cleans up the projection - support thread and releases lingering handles on layer objects. - ProjectionSupport also has dispose() method that is called to - clean up. - - * Layer.setProperties() functionality was broken out to a - setLayerProperties() method so subclasses could override - setProperties() and still get to to the superclass functionality - if desired. - - * Updated the ShapeLayer and package. The SpatialIndex no longer - needs to be defined, it will be found or made next to the shape - file. The dbf file will automatically be used if found, and the - DbfFile rule handling was improved. All of the various Shape - layers in the com.bbn.openmap.layer.shape package were update to - work using the same EsriGraphicFactory mechanisms. - - * BinaryFile modified with improved name handling for - FileInputReader, separating absolute path and file name queries. - ByteArrayInputReader added to allow BinaryFile to contain entire - file in memory. - - * WMS package updated to have capabilies query handling, improved - layer control and new SRS handling. The WMSPlugIn was updated to - WMS version 1.1.1 and has better query handling. - - * Added method to ConvexHull to allow for tolerances when trying - to determine equal points to reduce the number of unnecessary - points in the resulting polygon. - - * Added the CoordInfoFormatter and CoordInfoFormatHandler to make - it easier to define how coordinates were displayed in the - InformationDelegator from CoordMouseModes. - - * Updated dbf attribute type handing and handling of null cells. - Padding with spaces instead of null characters. - -2008-02-29 Don Dietrick - - * OpenMap 4.6.4 released. - -2008-02-27 Don Dietrick - - * Updated the PropertyHandler to have its own property prefix. This - property prefix is used by the PropertyHandler when it looks for a - properties file, and when it looks inside the properties file for - application level properties, like the components list, include - files, and the configuration directory. Where the PropertyHandler - used to only be able to look for an openmap.properties file that - contained an openmap.components property, you can now define a - different prefix for the file and property. - - * The com.bbn.openmap.util.propertyEditor.Inspector was updated to - provide a simple GUI that can be inserted on behalf of a - PropertyConsumer, without providing window controls, etc. It can - be used just to provide the widgets for the PropertyConsumer - adjustments. - - The DrawingAttributesPropertyEditor was created as an example of - creating a property editor widget that can control multiple - properties in a single GUI widget. - - * The com.bbn.openmap.util.cacheHandler package was added, - allowing for a more generic caching mechanism than was provided by - the com.bbn.openmap.layer.util.cacheHandler package. - - * The GeoCoordTransformation interface was added, providing a - mechanism that allows transformations from pre-projected - coordinates into lat/lon space. The - com.bbn.openmap.dataAccess.shape classes can use the - GeoCoordTransformation objects in order to display pre-projected - shape data. Several GCTs have been implemented, including - LatLonGCT, MercatorGCT, UTMGCT. A CoordinateReferenceSystem - object also uses the GCTs, and assists the WMS server code in - handling requests. - - The MGRSPoint was updated to handle zone letters correctly, - instead of defaulting to UTM values. - - * UTMProjection added. - - * OMGraphic improvements: - - - OMEllipses with XY and OFFSET rendertypes were added. - - OMGraphicHash was added. - - OMTextLabeler was updated to handle different anchor locations. - - OMPoint.Image class was added, an OMPoint that uses an Image to - mark the location. The image does not change size with respect to - map scale, as the OMScalingIcon does. - - OMGraphicList findAll() method fixed when inner vague lists were - used. - - The EditableOMGraphic GUIs for Text and Range Rings were updated - to have better persistence across different OMGraphics. - - The DrawingAttributes GUI, including the color settings, was - moved into the pop-up menu, replacing all of the buttons. Just - the stroke button remains, and the colors on that button adjust - according to the DrawingAttributes settings. - - * The DrawingToolLauncher GUI was updated to handle the - DrawingAttributes GUI changes. - - * The VPFConfig class was modified to maintain knowledge of - current features set on a VPFLayer that it is modifying. - - * The RPF Layer code was improved. The RPFCacheHandler was - modified to reduce the number of bytes utilized in the cache - tracking mechanism, which greatly decreases memory usage for large - datasets. The RPFFrameEntry was modified to use fewer bytes for - file name storage, also saving memory for large datasets. - - The RPFLayer was modified to use the OMGraphicHandlerLayer's - transparency mechanism, replacing the colortable mechanism that - was in place. - - * The Link Protocol has been updated to version 0.5, with a - greatly reduced transmission footprint by making all of the field - headers one or two characters long. A cache mechanism was added - to the protocol and on the client Java code that allows values - sent previously to be reused for later graphics. - - * Added com.bbn.openmap.layer.learn package, to hold layers that - serve as examples for specific capabilities. BasicLayer and - InteractionLayer added. - - * OMGraphicHandlerLayer has improved SwingWorker threading - support, including the interruption mechanism and thread locking. - Transparency can now be set on any OMGraphicHandlerLayer, and - there is a GUI widget available that can be added to any palette. - - * The DrawingToolLayer has improved file support, including - reading from multiple shape files to reproduce previous savings. - - * The DeclutterMatrix has improved access to a java.awt.Graphics - object that prevents locking during multi-threaded access. - - * The com.bbn.openmap.io.FileInputReader handles reopening files - that have been closed. The BinaryFile and BinaryBufferedFile can - now read unsigned shorts upon request. - - * The com.bbn.openmap.image.wms package adds much better WMS - support, including handling GetCapabilities requests. - - * The com.bbn.openmap.image.ImageScaler class was added, providing - better image scaling performance in the AbstractImageFormatter and - OMScalingRasters. - - ImageFormatters now provide their content type for web delivery. - - The ColorReducer class provides support for color reduction in - images, and the PNG32ImageFormatter and PNG8ImageFormatter was - added. - - The WMS servlet was updated to handle the new web mapping server - support code. - - * WindowSupport windows no longer shrink when it they are - repeatedly brought up. This fix affects the OverviewMapHandler, - LayersPanel, CoordPanel, Layer palettes, etc. - - * The CoordPanel was updated to use WindowSupport, replacing the - CoordDialog and CoordInternalFrame. - - * The new GeoArray object was created to improve memory management - and performance for the com.bbn.openmap.geo package components. - The ConvexHull and RadialRegion classes were also added to the - package. - - * The ProjectionSupport threading model was improved, adding a - more robust threading lock mechanism during projection change - notifications. - - * The PanMouseMode image management and projection handling was - improved. - - * The AbstractMouseMode (affecting all mouse modes) has better - support for defining custom cursors and icons. Support for - specifying the zoom direction to mouse wheel relationship was - added. - - * The com.bbn.openmap.dataAccess.shape package was updated to add - support for all Shape types. The EsriGraphicFactory class now - creates EsriGraphics from files and streams, and both the - com.bbn.openmap.plugin.esri and com.bbn.openmap.layer.shape - componets use this com.bbn.openmap.dataAccess.shape package. The - DbfFile class was created to allow better handling of dbf files, - providing a way to limit what fields are read out of a file and - kept in memory. The DbfHandler class was created to manage - EsriGraphics and their rendering attributes/labels/tooltips/info - based on the dbf file contents. The DbfHandler class lets you set - rules for dbf file contents so you can draw map objects different - based on attribute values. The ShapeLayer was updated to use this - class. - - * iso8211 package had some bug fixes related to the DDFSubfields - and definitions. - - * MapBean was updated to support ProjectionChangeVetoExceptions, - so that layers or other components can now limit what a projection - can change to. - - * LayerHandler can now have it's own prefix to be used to define - layers in the properties file. Previously, the LayerHandler - looked for an 'openmap.layers' property for its layer list. While - 'openmap.layers' still works, it now looks for a - '.layers' property first, where is the - keyword used to define the LayerHandler object instance in the - 'openmap.components' property, or whatever Property prefix the - LayerHandler is given in the setProperties(...) method. - - The LayerHandler was also updated to handle background layers - better, so that background layers show up at the bottom of layer - lists. - - * Layer has hasGUI() can let component know if a GUI is available. - The LayerPanels use this to disable their palette icons if a GUI - is not available for a particular layer. - - * LatLonPoint has been updated to contain many more functions to - assist with determining relationships with other - LatLonPoints (distance, etc). - - * Added I18 supports for many more GUI components. This effort is - continuing. - - * Added support for GeoTIFF and geocoded images via the - com.bbn.openmap.dataAccess.image package. This support is for - images that are in a equal-arc WGS84 decimal degree projection. - Relies on the JAI package being available on the host system. The - ImageTile class is a subclass of OMScalingRaster that handles the - display of these files. GeoTIFFs with embedded projection - information are handled, as well as other image formats with world - files. The com.bbn.openmap.layer.imageTile.ImageTileLayer is a - layer that handles the display of ImageTiles, and serves as an - example of how to use the new com.bbbn.openmap.dataAccess.image - package. - -2006-02-14 Don Dietrick - - * Updated LayerHandler to manage layers in the MapHandler better. - Layers will only be added to the MapHandler if they don't know - about it already. Also, calling LayerHandler.init(Layer[]) has - been updated to check to see if Layers are removable, and honors - that setting. Non-removable layers will be added to the bottom of - the layer stack as the new layers are added. These layers will - also be added to the MapHandler as needed, where they previously - weren't. This fixes the bug where layers added to the application - as a result of loading a new properties file weren't being added - to the MapHandler. - - * Updated BeanContextPlugIn to remove itself from the - BeanContext/MapHandler when it sees its own PlugIn layer being - removed. Made EsriPlugIn extend BeanContextPlugIn instead of - AbstractPlugIn. Cleaned up how DataBoundsProviders were handled - as they were removed from the MapHandler. PlugIns weren't being - removed properly. - - * Added an attribute Hashtable to Layer. - - * Updated the MapRequestHandler and ImageServer classes to handle - background Paints better. Map requests coming through the - MapRequestHandler no longer set the default background color, and - the ImageServer API has createImage(...) methods added to allow - the passing in of background Paint objects to be used for an - image. The background color can be set in the properties. - - * Updated WindowSupport to have WSDisplay inner classes that - handle the differences between showing components in JFrames, - JDialogs and JInternalFrames. Components can specify which kind - of WSDisplay they wish to use when the create their WindowSupport - object, or they can let the WindowSupport object create the - default version for them. If the Environment.useInternalFrames - flag is set, then JDialogs will be used for components that don't - specify which WSDisplays to use. If the Environment flag is not - set, then the WindowSupport.defaultWindowSupportDisplayType static - member variable dictates what kind of window will be created. - Although the JFrame class is the default, there are accessors to - change that setting (WindowSupport.Frm.class, - WindowSupport.Dlg.class or WindowSupport.IntrnlFrm.class) - to suit your application. - -2006-02-01 Bill Mackiewicz - * OpenMap 4.6.3 released. - -2006-01-24 Don Dietrick - - * Updated the ElevationBandGenerator in the - com.bbn.openmap.omGraphics.grid package, adding the loader and - ColorGeneratorLoader for it. - - * Updated the CSVTiledImagePlugIn to use - FileCacheImageInputStreams to create BufferedImages, instead of - ImageIcons. This is in an effort to reduce memory usage for tiled - images. - - * Updated the com.bbn.openmap.util.FileUtils object for better - options presented to the user, as well as methods that copy files - and zip/unzip files. - - * Updated the Directory and File property editors to provide - better control over the options offered to the user. - - * Added com.bbn.openmap.omGraphics.OMAbstractLine, which is now - the superclass of OMLine and OMPoly. Arrowheads were moved up to - this class, so polylines can now have arrowheads attached. - There's an editable version as well. - - * EditableOMRangeRings were updated to estimate how may rings they - should have when changing units in the GUI. It used to maintain - the number it had, which could result in it being overwhelmed with - the new settings. Now it behaves as expected. - - * Added bold and italic buttons to EditableOMText GUI. - - * OMArrowHead was updated to allow more parameters to be chosen by - subclasses, making it easier to customize. - - * Updated the OMGraphic serialization methods to handle strokes - better. - - * OMGraphicList.findAll(...) method lets you give an x,y pixel point on - the map, and retrieve all of the OMGraphics under that point - within the provided pixel range. - - * Added a Text Matte Color and Stroke, which, if set, will outline - the text characters with a matting rendered with that stroke. - - * Updated the com.bbn.openmap.layer.vpf.VMAP2Shape class to use - the com.bbn.openmap.dataAccess.shape components to create shape - files. - - * Set LayerUtils to be deprecated, you should use PropUtils - instead. The OpenMap components have been so updated. PropUtils - was updated to have all the same methods as LayerUtils did, with - some new ones including one that will set the proper - internationalized strings (setI18NPropertyInfo(...)) for the - getPropertyInfo() call of a PropertyConsumer. - - * Added the RpfUtil class, which allows you to modify - (copy/delete/move) RPF data from RPF directories with filters that - let you specify scale, chart type, or location. - - * Added Composites to the RenderPolicy API in - com.bbn.openmap.layer.policy. This allows the addition of - Composites to be added to a render policy to modify the rendering - process for that layer. You can add an AlphaComposite to a layer - this way in order to get it rendered with transparency. - - * Updated AbstractLocationHandler to hold DrawingAttributes object - for names and location markers, instead of just holding a Color - for each. The Property GUI hasn't been updated yet, so the old - Color GUI still works. Added LocationHandler.NamePropertyPrefix - and LocationHandler.LocationPropertyPrefix to allow scoping for - properties. - - "Fixed" the CSVLinkHandler, meaning that it works, but still needs - more work to be fully functional with property settings and - different rendering effects for lines and endpoints. - - Updated CSVLocationHandler to have methods that can be overridden - when dealing with tokens and newly read info from the CSV file. - - * Updated the DTEDLayer minScale property code to set the new - Layer maxScale member variable, keeping with the meaning of the - Layer's version. Removed the DTEDLayer's minScale property and - supporting methods. - - * Added OMGraphicHandlerLayer.createLayerWorker() method to make - it easier to override and set customized LayerWorkers (threading - mechanism for layer work). - - * Removed restriction from BinaryFile that caused it to check for - an "http://" lead on URLs. - - * Added the MagicPlanetImageComponent to the com.bbn.openmap.image - package. The MagicPlanet is a spherical display system (get more - information at http://www.globalimagination.com). By adding this - component to an OpenMap application, images suitable for display - on the MagicPlanet can be created, at varing intervals and - resolution settings. The MagicPlanet's StoryTeller software can - then be told where the images are stored, and can then manage the - images. - - * Updated the AbstractImageFormatter to reset an existing - projection back on a layer after the formatter has used it to - create a image. This should help for situations where an active - map window wasn't behaving properly after being saved to a file. - Removed the AcmeJPEG* code, it didn't work and the Sun version - should be used instead. - - * Updated the ScenarioGraphicLoader so that the mode settings are - more obvious, instead of being changing depending on the clock - setting. - - * Updated the com.bbn.openmap.geo package, which now has the - capability to do spatial intersection and proximity analysis in - lat/lon space. The ExtentIndex (and ExtentIndexImpl) contain - collections of GeoExtents which may be queried for intersection by - other GeoExtents. The Ribbon object is an attempt at rendering - spatial areas around GeoExtents. - - The com.bbn.openmap.layer.test.GeoIntersectionLayer is an example - of how to use the ExtentIndex. That layer loads shape files into - the ExtentIndex, and then lets you draw on the map to test how the - drawn objects intersect with the shape file objects. - -2006-01-23 Don Dietrick - - * Updated the com.bbn.openmap.dataAccess.shape package so its - components use the attributes of OMGraphics instead of using the - OMGraphic appObject directly. The DbfTableModel might be stored - in the EsriGraphicList's DBF_ATTRIBUTE key. In each of the - EsriGraphics, the index is stored under that EsriGraphic's - SHAPE_INDEX_ATTRIBUTE. Updated DBF output to put numbers in - English locale number format. - - * Added the DTEDFrameACC object to the - com.bbn.openmap.dataAccess.dted package and DTEDFrame, to hold - DTED accuracy attribute information. This class was submitted by - Matt Revelle. - - * Made the MouseModes MouseWheelListeners, and made the default - action for the OpenMap MapMouseModes to control zooming over the - map. - - * Added minScale and maxScale properties for layers, which hold - onto scale settings that the layer can use to determine if it - should react to a projection or not. Also added an Icon member - variable to the Layer. Note that the Layer doesn't actually use - the minScale and maxScale parameters, that's up to the Layer - subclass authors. - - * Removed Makefiles, now that ant is the official build mechanism. - -2005-05-24 Don Dietrick - - * Refactored the FilePropertyEditor so it includes an uneditable - text area, and added callback methods for settings that all the - other file-related PropertyEditors use now. Justified the - ColorPropertyEditor and choice PropertyEditor widgets to the left - instead of centered. - -2005-05-23 Don Dietrick - - * ComponentFactory updated to contain a singleton instance, and - the static methods have been updated to use that singleton - instance. This makes it possible to change the behavior of the - ComponentFactory by setting a subclass as the singleton. The - PropUtils.createObjectFromProperties(...) method now calls the - ComponentFactory.create(...) method. - - * Fixed the BasicGeometry attribute handling where the first - attribute being set was being stomped on and deleted when - subsequent attributes were added. - - * Updated DrawingAttributes so it doesn't create a - BasicStrokeEditor when the stroke is being set, for those times - when a display is not available. Property output for colors now - in hex strings. OMGraphic uses static BASIC_STROKE object for - default strokes, instead of creating new object. - - * Updated VPF FeatureDrawingAttributes to set String constants - when display type is set, added null checks when GUI is reset. - Fixed problem for initial settings for attribute display via - properties file. - - * Added null check in ESRIPolygonRecor/ESRIPointRectord for - DrawingAttributes being set, made SpatialIndex a Closable object. - Added the connectParts() call to OMAreaList for handing holes, but - that code section still isn't active by default due to problems - with OMAreaList and very large objects. - - * Updated MIFLayer to be able to read files specified as - resources, files or URLs. - - * Updated Location object to have more specific - shouldRenderName(...) and shouldRenderLocation(...) methods, these - methods make it easier for subclasses to determine/control when - those parts should be drawn. - - * Updated the DrawingToolLayer to have an option-filled GUI that - allows the saving and loading of a serialized OMGraphicList - to/from a file, as well as saving the properties for the layer. - Shape layer creation is also an option. - - * Updated the layer ordering in the Crew and SimpleMap2 examples. - - * Updated DTEDFrame and RpfFrame to call close on its file handle. - - * Updated InformationDelegator to use the Environment Desktop for - internal frames. - -2005-02-15 Donald Dietrick - - * Released OpenMap 4.6.2 - -2005-02-15 Donald Dietrick - - * Added the cntry02 world boundary shape files to the package and - made them the default files used in the OpenMap application. - They're bigger files, and the application runs a little slower, - but they are much more accurate than the dcwpo-browse files. The - dcwpo-browse files are still available if the old data is desired. - -2005-02-11 Donald Dietrick - - * Updated many classes for internationalization, with help from - Piotr Kaminski and Jesper Berglund. - - * Updated the RpfLayer so the opaque slider works on the coverage - rectangles as well as the images. Updated the palette to enable - the modification of preference settings. Updated the MakeToc to - better check for non-RPF image files to skip them when appropriate. - - * Updated FileUtils to have separate save and open methods, - updated different classes in the package to call them - appropriately. - - * Updated the BasicI8n class so it can provide a set of - ResourceBundle properties files that can be used to - internationalize an application. If the 'i18n.create' Debug flag - is set (with a -Ddebug.i18n.create OpenMap application flag, or - by calling Debug.put("i18n.create") somewhere at the very - beginning of an application), the BasicI18n class will log all - the resource bundle properties files accessed or attempted to be - accessed, and will track the retrieved strings or their defaults - provided to the application GUI. If requested, the BasicI8n - class can create a hierarchy of I18N_.properties files in - the correct directory structure of the requesting application, - filled with key-value pairs where the values can be replaced with - language-appropriate translations for the given locale. If the - application is run with the 'i18n.default' flag also set, then - I18N.properties files will be created without the locale - setting. Added the I18nFileCreateMenuItem that will tell the - BasicI18n class to create the new files. The openmap.properties - file was updated to show how to load the menu item to a generic - OMBasicMenu in order to temporarily add this class. - -2005-01-10 Donald Dietrick - - * Updated the com.bbn.openmap.tools.symbology.milStd2525 - package, specifically, the SymbolReferenceLibrary and the - SymbolChooser, which can now create icon symbols given the - proper data source. The SymbolChooser now updates the symbol - code based on option settings, and the SymbolReferenceLibrary - uses a SymbolImageMaker to decide how to make a image based on - that code. The SVGSymbolImageMaker can use the SVG symbol - library available from DISA, and also requires the Batik - package from http://xml.apache.org/batik. The - PNGSymbolImageMaker and GIFSymbolImageMaker - will create scaled icons from a gif file selection. - - * Added labeling capabilties to OMGraphics, handled by their - attribute capabilities. If the OMGraphicConstants.LABEL attribute - is set with an OMLabel object (the OMTextLabel is one - implementation), labels will appear on the map for an OMGraphic. - Added OMGraphicConstants.TOOLTIP and OMGraphicConstants.INFOLINE - constants, too, that can be used by layers to look up these kind - of attributes in an OMGraphic. The VPFLayer now looks for these - attributes for it's display. - - * Updated the StandardMapMouseInterpreter to handle right mouse - button clicks better, by trapping the popup trigger. - - * Updated VPF package components to provide access to feature - attribute information, which can be displayed via tooltip, - information line, or label on the map. The choice of display - type and attribute type can be specified in the layer's palette - and/or properties. The VPFLayer's 'searchByFeatures' property - must be set to true for this capability. - - * Added ImageIOFormatter class, a super class for creating image - files via the java imageio package. Added GIF and PNG - implementations. - - * Moved the LayerHandler threading support to the LayerSupport - object that also performs some queueing capability, so that the - threads lauched form layers changes are performed in order to - preserve stability. - -2004-11-25 Donald Dietrick - - * Modified the ProjectionSupport and LayerHandler to launch - threads for projection notifications to the layers and for layer - reordering, to prevent the application from getting hung up for - some of the more extensive notification event reactions. - - * Updated VMAP2Shape to use EsriShapeExport class, instead of - using the Shape package stuff. Updated VPFConfig to check for - backslashes and replace them with Java-friendly forward slashes. - - * Modified the ESRIPolygonRecord to include the donated code to - handle polygon holes using OMAreaList. This code is disabled, - however, because OMAreaList doesn't really handle shapes that go - around the earth yet, and having this modification breaks - world-level shapefile display. OMAreaList needs to be fixed - before this code is enabled full-time. - - * Updated BasicGeometry to have the option of connecting shapes - that are appended, instead of automatically not doing that. - Updated OMAreaList to make that BasicGeometry append call with - the connect parameter. - -2004-11-01 Donald Dietrick - - * Released OpenMap 4.6.1 - -2004-10-15 Donald Dietrick - - * Changed OMGrid to extend OMGraphicList instead of OMGraphic. - This provides better access to the OMGraphics that the - OMGridGenerator creates. If that access is not wanted, just set - the OMGrid (OMGraphicList) to be vague. - -2004-10-05 Donald Dietrick - - * Updated the SwingWorker to match the latest version from Sun. - - * Added LambertConformalConic projection, along with it's loader - that has properties to let it describe the LCC attributes it will - create. You create a loader in the properties for a specific - state plane or other LCC definition, and that shows up as an - option to the ProjectionFactory. - - * Updated the decorated OMGraphic parts, adding a circle - decoration and some weather notations. Added editable - OMScalingRaster code, submitted by Dan Bitts. Fixed FontSizer. - Added callouts to FilterSupport to handle actions on OMGraphics - that pass and fail the filter. Fixed transparency handling in - OMRaster. Updated rotation handling in OMRasterObject. Added - accessors to OMScalingRaster to get display corners. Updated - OMText so rotated text factored into distance() correctly. - - * Modified LayerHandler to add layers to top of stack, if their - position is undefined. - - * Update VPF components. Added feature type sublists to - warehouse support, to better control display of different feature - types. - - * Fixed MakeToc from the RPF package, it was writing bad A.TOC - files. Updated RPF coverage tools. Modified RpfFrame to check - for lower case file names if upper case isn't found, and also to - check for full pathnames when the frame is actually loaded, - instead of when the layer was created, which was really expensive. - - * Modifed BufferedImageRenderPolicy to extend - RenderingHintsRenderPolicy, so buffered image could be - anti-aliased if needed. - - * Modified how the OMGraphicHandlerLayer handles/locks the - SwingWorker during updates, and how it cleans up if the - SwingWorker gets interrupted. Removed synchronization notation - from some methods. Added new GRP capability to handle events - over the map. - - * Fixed Location bug with label rendering. - - * Modified DTEDCoverageLayer to extend OMGraphicHandlerLayer. - - * Updated BufferedLayer to properly handle BeanContext with its - sub-layers, as well as responding to getProperties(). Updated - ScaleFilterLayer as well. - - * Added methods to LatLonPoint that call GreatCircle class to - calculate distance/azimuth to another LatLonPoint, or to find a - LatLonPont a distance and azimuth away from the current point. - - * Updated the LayersPanel initialization with the - LayerControlButtonPanel. - - * Added method to ProjectionFactory to let it provide the default - projection set with the Environment projection parameters. - Updated the BasicMapPanel and ImageServer/MapRequestHandler to - use that method. - - * Added the com.bbn.openmap.util.FileUtils class that has a - static method for asking for a file from the user, using a JFileChooser. - - * Added a save capability - com.bbn.openmap.dataAccess.shape.DbfTableModel when it's run - directly on a .dbf file. The save option was also added, enabled - with a behavior mask setting. - - * Updated the com.bbn.openmap.dataAccess.dted components to be - able to handle .dt2 files. - -2004-05-24 Donald Dietrick - - * Added the OptionPropertyEditor, a base class used for - presenting properties with a limited number of choices. These - options are defined in properties, which is why the - PropertyConsumerPropertyEditor was written as the superclass. - The ComboBoxPropertyEditor is the first implementation of the - OptionPropertyEditor, using a JComboBox to display the choices. - The ColorPropertyEditor was modified to use the DrawingAttributes - fill paint button to display the color choice in addition to - showing the hex representation. The Inspector was modified to - handle PropertyConsumerPropertyEditors. - -2004-05-14 Donald Dietrick - - * Modified the ProjectionFactory to dynamically manage - projections. This involved changing the ProjectionFactory from a - class containing static methods that accessed hard-coded classes - to a singleton instance that uses the MapHandler to gather - ProjectionLoaders that it uses to create Projection objects. A - BasicProjectionLoader class has been written implementing the - ProjectionLoader interface, and 5 ProjectionLoader classes have - been written extending BasicProjectionLoader that create the - Mercator, CADRG, Orthographic, LLXY and Gnomonic projections. - - The ProjectionFactoryLoader class has been written to be added to - the openmap.components property in order to put the - ProjectionFactory instance into the MapHandler. It can also be - used to define the properties for ProjectionLoaders, although - ProjectionLoaders can also be added directly to the MapHandler as - well. - - Because the change to openmap.properties might catch some people - by surprise, particularly those who use their own - openmap.properties file, the BasicMapPanel has been modified to - check the MapHandler to see if a ProjectionFactory has been added - to it. If a ProjectionFactory cannot be found, the singleton - instance is automatically added with the default set of - ProjectionLoaders. - - Lastly, the Projection property defined in the openmap.properties - file has to be a class name, instead of a nickname of one of the - projection classes. Some available class names have been added to - the openmap.properties comments next to that property, and the - BasicMapPanel has been configured to complain about using the old - style. - - * Added methods to ComponentFactory so that those methods that - created components from a list of marker names and a set of - properties could be provided a prefix to place in front of the - marker name and its properties. - - * Moved/Added I18n handle to OMComponent, OMComponentPanel and - AbstractOpenMapMenu, to make I18n easier to implement. - - * Modified when/how tooltips are cleared and reset in the - InformationDelegator. - -2004-05-10 Donald Dietrick - - * Modified the StandardPCPolicy so that has the option to be told - to always spawn a thread when a projection is received. It used - to use the number of OMGraphics on it's current list to determine - if that should happen, but that caused problems if the one - OMGraphic created took a while to create. You can pass the new - flag in a constructor, or set it later. - - * Modified how PlugInLayer handles plugin with the BeanContext, - so PlugIns added to the layer at a later time still get to work - with the BeanContext. - - * Added the com.bbn.openmap.dataAccess.iso8211 package that - provides support for reading ISO 8211 data files. Also added the - com.bbn.openmap.dataAccess.asrp package that reads ASRP image - data. ASRP images can be displayed using the - com.bbn.openmap.layer.asrp.ASRPLayer. - - * Added attribute mechanism to OMGeometry/OMGraphic objects. The - attributes are stored in a hashtable in the app object of the - OMGeometry/OMGraphic and can be retrieved with new methods. The - code has been written to work with the possibility of other code - still using the setAppObject and getAppObject methods, as the app - object set as in older versions of OpenMap is now stored as an - attribute when other attributes are added. This should be - seamless to anybody that is currently using the app object. - - * Created MapBeanPrinterMenuItem and added it to the FileMenu. - - * Modified the BasicMapPanel so the empty constructor doesn't - create a PropertyHandler that will search for an - openmap.properties file and fill the application with it. The - basic BasicMapHandler will create a MapHandler and - BufferedLayerMapBean, and an empty PropertyHandler. To create a - BasicMapPanel that does look for an openmap.properties file, - create a PropertyHandler with an empty constructor and pass it to - the BasicMapPanel. - - * Added I18 contributions to gui package from Mirek Pawlowski. - - * Modified the GestureResponsePolicy interface, adding the - receivesMapEvents(), mouseOver() and leftClick() methods so the - policy could receive information about mouse events that were - occuring over the background map and not over its OMGraphics. The - latter two methods only get called when the first returns true. - Modified the StandardMapMouseInterpreter to use these methods. - Modified the OMGraphicHandlerLayer to not do anything when these - methods were called. - - * Added Piotr Kaminski's RhumbCalculator class that computes the - lengths of Rhumb lines. - -2004-04-16 Bill Mackiewicz - * Replaced ext/jakarta-ant-1.5.1/ with ext/apache-ant-1.6.1/ - -2004-02-13 Don Dietrick - - * Added Gordon Vidaver's route calculation package (originally - derived from Ray Tomlinson's code) - (com.bbn.openmap.tools.roads), along with two layers that - provide routes based on the OMGraphics created from their data - sources (com.bbn.openmap.layer.shape.MultiRoadLayer and - com.bbn.openmap.layer.vpf.VPFRoadLayer). - -2004-02-11 Bill Mackiewicz - - * OpenMap 4.6 released. - -2004-02-09 Don Dietrick - - * Fixed the problem in OMColorChooser where the preview panel - wasn't showing up in jdk 1.4.2. - - * Added properties in DrawingAttributes that set the pixel radius - and oval settings of OMPoints when setTo(OMPoint) is called. - - * Modified the MapHandler to contain a mechanism for handing the - addition of new components while the membership list is being - iterated over by another component. If a component using the - membership iterator adds something to the MapHandler as a result - of finding something in it, the new addition will be saved by - the MapHandler and added later, preventing a - ConcurrentModificationException from being thrown. - - * Modified the MapBeans to set the clipping area (if null), and - drawing buffers, to the size of the projection, instead of the - MapBean. Usually these are the same, but just in case someone - wants to try to do something with the projection definitions, it - should work better. Since JComponents (Layer superclass) will set - clipping areas to the size of the component if they are set to be - larger, you may have to set the FullProjectionRenderPolicy in the - layers in order to get them to draw fully into the projection - area if it's bigger than the MapBean. - - * The I18n interface was added, replacing an I18n class that - wasn't used. This interface describes a object that provides - localized strings based on the requesting class, component - descriptor with optional modifier, and a default string. The - BasicI18n class, which implements the I18n interface, was added - as the base implementation of localization in OpenMap. The - Environment class was modified to provide the current I18n - application instance to components at runtime. Several - properties files for different packages were added to the - distribution, as well as some Polish localized properties files. - Many thanks to Piotr Kaminski and Mirek Pawlowski for helping us - work out the Internationalization mechanism and providing - modified classes and Polish property files. - - * Modified the com.bbn.openmap.SoloMapComponent interface so it - has a canAdd() method, to be asked if a component can be added. - This makes it easier to change the behavior of SoloMapComponent - objects by overriding one method. - - * Upgraded the PropertyHandler so it writes out properties that - are more accurate. The original properties are used, and then - overwritten by the current components. If a component doesn't - provide its current properties, its original properties are - written. Before, no properties would have been written for that - component. - - * Added the mac source directory, which has the capability to - create a clickable Mac application. Use the 'mac' target in the - ant build file. - - * Added the com.bbn.openmap.MapBeanRepaintPolicy interface, which - handles the layer's requests for repaints as well as modifying - the java.awt.Graphics object for painting. The - StandardMapBeanRepaintPolicy was added to implement the default - behavior. The HintsMapBeanRepaintPolicy was added to the package - to allow RenderingHints to be set on the MapBean. - - * Added the com.bbn.openmap.proj.EqualArc interface to designate - those projections that are Equal Arc (constant degree changes in - both directions). Modified those layers that required the CADRG - projection to be use any EqualArc projection, including LLXY. - - * Modified the ToolPanel so it can be told (in its properties) - which Tools to include in its interface. It also has the - capability to be told which tools to ignore and not include. - This lets you place more than one Tool in the MapHandler, and it - will show up in the right place. The ToolPanel will also make - itself invisible if all of its components are made invisible, and - reappear if any of them are made visible. - - * The OpenMapFrame has been modified to set its root pane as the - root pane of the Environment if the Environment has been told to - use internal windows and the root pane hasn't been set in the - Environment yet. - - * Modified the OpenMap application to have a method which assigns - a WindowListener to the application frame. The default action is - to exit the application, but this method can be overridden to - change this behavior. The OpenMap application also schedules the - Frame to be shown in the event-dispatching thread, which makes - the frame appear much more consistently. - - * Modified the WindowSupport object to use JDialogs to keep the - windows floating on top of the map. The WindowSupport also now - has code that tries to make the window appear centered on the - owner window (thanks to Laura Paterson). - - * Added the com.bbn.openmap.gui.ScrollPaneWindowSupport, which is - an extended WindowSupport that wraps content in a JScrollPane. - - * Added the com.bbn.openmap.gui.GridBagToolBar, which is a - JToolBar with a GridBagLayout to have a more compressed look. - - * Added the com.bbn.openmap.gui.dock package, which supports the - new com.bbn.openmap.gui.BasicDockPanel. This is a new MapPanel - that allows components to stack up against each other, in - addition to layering themselves within the panel. - - * Added the VPFConfig class to the com.bbn.openmap.layer.vpf - package, a utility that helps configure VPFLayers. When run in - standalone mode it displays the coverages and features available - in the designated VPF library and allows the user to designate - the DrawingAttributes desired for each feature chosen. There is - an option for printing those properties so they can easily be - added to an openmap.properties file. The VPFConfig can be - launched from a running VPFLayer palette to change the features - the layer is displaying. It can also be run from within the - application to create a new layer and provide that layer to the - LayerHandler, although this functionality hasn't been introduced - yet. - - * The EsriGraphicList and DbfTableModel classes in the - com.bbn.openmap.dataAccess.shape package have static methods - included that create an instance of themselves from URLs. - - * Layers now have a removeable flag that can be set in them, that - lets GUI widgets know that they shouldn't be removed, and the - LayerHandler pays attention to that flag to prevent unremoveable - layers from being deleted from the application. Fixed bug in - palette component status events so that palette hide events get - dispersed properly. - - * Added modifications to the RPF package by Kimberly Hamilton - (NGC) which added the capability to use frames from other zones - when zoomed out, to prevent that confusing lack of coverage - effect at zone boundaries. - - * The com.bbn.openmap.dataAccess.dted package was greatly enhanced - with a central DTEDFrameCache that can be shared across layers and - tools. The DTEDFrame in that package provides OMGrid objects - which can use OMGridGenerators to create representations of the - data. This updated frame cache can be used by the - com.bbn.openmap.layer.dted.DTEDFrameCacheLayer, and the different - GeneratorLoaders used to display the data can be configured and - modified in the properties file. The DTEDDirectoryHandler was - added to load the DTEDFrameCache with a DTED directory, and it - also handles the configuration of a DTEDNameTranslator, which - translates how frame files are named in relation to their file - structure. This used to be hard-coded, now new classes can be - written and included in the properties. - - * The com.bbn.openmap.dataAccess.dted.DTEDAdmin class can move - DTED files from one directory to another, filtering the move based - on file location and dted level. - - * The Link package (com.bbn.openmap.layer.link) was modifed to run - in asynchronous mode, allowing servers to push OMGraphics to the - client layer on their schedule. Properties were added for stroke - patterns, fill patterns, and projection changes so the server can - control the application's projection. The LinkArc was added to - the package as well. - - * A TimerLocationLayer was added to the - com.bbn.openmap.layer.location package, which includes a timer to - have the LocationHandlers reload their source data at specified - intervals. - - * Simon Bowen provided updates to the MIF package - (com.bbn.openmap.layer.mif), including support for text and point - objects. - - * Uwe Baier provided the MySQL layer package, - com.bbn.openmap.layer.mysql. - - * The RenderingHintsRenderPolicy was added, which lets layers - independently set java.awt.RenderingHints on the - java.awt.Graphics that its OMGraphics are painted into. The lets - the layer set anti-aliasing, etc. - - * The FullProjectionRenderPolicy was added to allow the clipping - area of the java.awt.Graphics a layer is painting into be the same - as the current Projection. The JComponent code limited this to - the visible size of the Layer, this allows the layer to paint - into a bigger image buffer. - - * The VPFFeatureCacheGraphicWarehouse was created to provide a - feature-based tile cache. This cache is shareable across - different layers, accessed through the LibraryBean. Each layer - gets their own copy of the feature OMGraphics so they can be - rendered independently from other layers. - - * Added the VPF servlet to the package, at openmap/src/vpfservlet. - This servlet is for programmers looking to gain an understanding - of VPF data, as it provides an in-depth view into the structure - and organization of VPF databases, as well as a direct look into - the data files. It's a servlet intended to be run within Tomcat. - There's a README included in the package that describes what - files to modify to configure it for your VPF data and Tomcat - installation. - - * The DrawingAttributes GUI was completely overhauled to have - dynamic color icon generated to reflect the current colors. The - BasicStrokeEditorMenu was created to compress Stroke parameter - selection, and the EditableOMGraphics now have a standard - interface to add options to the GUI, so different parameters - specific to the OMGraphic type can be modified. - - * The com.bbn.openmap.omGraphics.event package was enhanced with - the addition of the MapMouseInterpreter interface and the - GestureResponsePolicy. The MapMouseInterpreter is an object that - knows how to interpret MouseEvents over OMGraphics, and calls a - GestureResponsePolicy for information on how to respond. This - elevates MouseEvent interpretation to a different level, where - the programmer only has to receive queries about what to display - for certain OMGraphics, notifications of OMGraphic selection. - This capability has been integrated into the - OMGraphicHandlerLayer. - - * The FontSizer object was added to the package, which is used by - the OMText object to resize the font based on scale. - - * The OMAreaList was added, which takes different types of - OMGraphics and links them together to make one shape. - - * The OMArc was added, a superclass to the OMCircle. It can be - rendered as an open arc, a chorded arc, or a pie arc. - - * The OMEllipse was added, which creates a ellipse in lat/lon - space with distance axis. The EditableOMCircle can be used to - move the OMEllipse, but the axis cannot be modified yet. - - * The EditableOMText object was added, a contribution from Piotr - Kaminski. - - * OMGrids now use GridData objects to represent their values, - which is a type wrapper. GeneratorLoaders were added to the - package as well. GeneratorLoaders are factories that create and - manipulate OMGridGenerators, using properties for configuration - as well as providing a GUI for runtime manipulation. Added new - SlopeGeneration capabilities to the - com.bbn.openmap.omGraphic.grid package. Colored and Greyscale - colors can be used by the SlopeGenerator. - - * The InformationDelegator was modified to handle the dispersion - of messages to several information lines, with two now - incorporated into the InformationDelegator. The CoordMouseModes - use one (on the left) and layers generally use the one on the - right. The right one gets used when the caller doesn't specify a - location. Other locations can be added to the - InformationDelegator list of available lines, and the caller can - specify when line its information should appear on. - - * Added the com.bbn.openmap.event.ListenerSupport class, which - provides superclass support for other event notification - classes. - - * Added the MapBeanKeyListener and ProjMapBeanKeyListener classes - to the com.bbn.openmap.event package, which distribute key event - that occur when the MapBean has focus. - - * MapMouseModes can now have prettyNames, which are the names that - appear in the GUI as opposed to using the modeID, which was the - previous case. The GUI components have been updated to use the - pretty name in the right cases, and to continue to use the modeID - for programmatic purposes. - - * The proxy action of the AbstractMouseMode was modified so that a - mask can be provided to allow certain types of events to pass to - its targets even if it is acting as a proxy for another - MouseMode. This lets the Gestures mouse mode update the - coordinate display on the InformationDelegator while it acts as a - proxy for the OMDrawingToolMouseMode, for instance, but letting - only the mouseMoved MouseEvents pass on in a regular fashion. - Also, if you hold the shift key down while generating - MouseEvents, the proxy action is bypassed entirely. - - * Added a method to the DistanceMouseMode that makes it easy to - subclass it and change the format of the string displayed in the - InformationDelegator. Thanks to Piotr Kamiski. - - * The MapBeanPrinter object was added by Bart Jourquin, allowing - the MapBean to be printed and scaled directly to the Java printer - interface. - - * Modified the propertyEditors that deal with file and directory - selection to check to see of a File Chooser has included "\\" in - the path, replacing them with "/" to make the work correctly if - they are written out to a properties file. - - * Modified the OMDrawingToolLauncher so there are properties that - define whether to use buttons for different OMGraphic selection or - a pop-up, and if buttons are chosen the number of buttons to - display in a single row can be specified. The order of the - OMGraphic choices are now the same as they are added to the - MapHandler (in the openmap.components property or - programmatically). - - * The OMDrawingTool was modified to be able to handle movement of - multiple OMGraphics. It uses the DrawingToolRequestorList to - notify the owners of all the OMGraphics when movement is completed. - - * Added the IconFactory package (com.bbn.openmap.tools.icon), - which creates ImageIcons from vector data and DrawingAttributes - information. You provide the factory an IconPart (or IconPartList) - which contain DrawingAttributes per part, and the size you want - the icon to be, and the factory creates the image for you. The - DrawingAttributes GUI icons are created using the OMIconFactory. - - * Added the beginnings of a MIL-STD-2525 Symbology factory. It - doesn't work yet. Soon. The - com.bbn.openmap.tools.symbology.SymbolChooser does show the symbol - hierarchy, though, and the symbol organization is in place. The - last bit, actually building the symbols from cgm files, needs to - be completed. The com.bbn.openmap.dataAccess.cgm package was - added to OpenMap for this purpose. The CGM package was acquired - from BBN's Cougaar code base. - -2003-12-30 Bill Euerle - - * Cleaned up numerous javadoc warnings. - - * Updated the VPF layer to more fully use the Java2 Collections - API. Removed one (formerly deprecated) method from DcwRecordFile. - -2003-06-26 Don Dietrick - - * Added the com.bbn.openmap.gui.time package, which has standard - GUI controls for controlling time on the map, and - mapping time rates (real time to some other scenario time). - - * Added the com.bbn.openmap.graphicLoader.scenario package, which - uses location data and activity data to manage movement, against - time, over the map. The ScenarioGraphicLoader uses a time slider - and several time control buttons. - - * Misc changes and bug fixes: Added getters/setters for - AreaHandler in AreaShapeLayer. Fixed recursion bug in - com.bbn.openmap.omGraphics.FilterSupport. - - * Added the com.bbn.openmap.tools.icon package, containing new - classes that can be used to create images with pre-packaged scaleable - geometries. The application icons will be moving to use - ImageIcons created from the OMIconFactory and - IconPartCollections, instead of holding gif and png files in the - package. In support of this package, more capabilities were - added to the com.bbn.openmap.omGraphics.DrawingAttributes class, - including the ability to render a java.awt.Shape object into a - java.awt.Graphics object using its parameters. - - * Moved the GraphicLoader classes in - com.bbn.openmap.plugin.graphicLoader to their own package, in - com.bbn.openmap.graphicLoader. The - com.bbn.openmap.plugin.graphicLoader package remains, for the - GraphicLoaderPlugIn and GraphicLoaderConnector, two classes that - use PlugIns and GraphicLoaders. But the new package contains - just GraphicLoader stuff, and several implementations and superclasses. - -2003-04-25 Don Dietrick - - * Heavy modifications to the CORBA classes. The build.xml file - was modified to use the jdk 1.4.1 corba tools and classes instead of - relying on VisiBroker. The idl components have been changed to - work with POA instead of BOA. Created the - com.bbn.openmap.util.corba.CORBASupport object to handle the - client-server startup and resolution functions. This code used - to be duplicated across three packages, now they all use this - class. - - * Added getToolBarGUI to EditableOMGraphic, with first - implemention in EditableOMPoly. Will be used for small GUI - accessories that can be used to modify OMGraphics. - - * Moved DMSLatLonPoint, UTMPoint and MGRSPoint to - com.bbn.openmap.proj.coords, added UPSPoint, NEDFrame and - EnuFrame there too as a contribution from Robert Hayes. - -2003-04-23 Don Dietrick - - * Modified the OpenMapApplet to look for a PROPERTIES parameter - in case the properties file to use to configure the applet should - be different than the standard openmap.properties file. The - properties file can be specified as a resource, file or URL, but - the applet rules apply. - - * Added the ScaleDisplayLayer, contributed by David Ward. Modified - it to extend OMGraphicHandlerLayer. - - * Misc bug fixes - the add/delete node states for the - EditableOMPoly only change to edit cursors when over a node, it's - now consistent with actual editing behavior. The equator - distance for NM in the Planet class was modified to be 2160. - Modified CSVTokenizer to ignore quotation marks, although a - quotation mark at the start of a field forces the field to be - interpreted as a String, and escape characters force inclusion of - the next charater in a String field. RpfTocHandler ignores - commas while checking scale fields. - -2003-04-16 Don Dietrick - - * Created the CombinedCoordPanel made from the contents of the - improved CoordDialog, and modified the CoordDialog and - CoordInternalFrame to use that instead of creating their own - content. Created a CoordsMenuItem that brings up the - CombinedCoordPanel in a WindowSupport object instead of using the - CoordDialog and CoordInternalFrame. Removed support in the - NavigateMenu for the CenterListener setup of the MapBean and - specific support for the CoordDialog/CoordInternalFrame, since - that moved to the CombinedCoordPanel and setup is now supported - by the menu item. - -2003-04-14 Don Dietrick - - * Added the com.bbn.openmap.gui.menu.MenuList component, which - can create a set of menus from properties, and can provide a - JMenuBar or JMenu containing those menus. Maintains order of the - menus. - - * Changed MapPanel to be an interface to a component that can - provide its MapBean, MapHandler and menu information(MenuBar - or single Menu with appropriate sub-menus). Created the - BasicMapPanel to implement the MapPanel interface. Modified - OpenMapApplet and OpenMapFrame to find a MapPanel, add it to - their content pane, and ask it for it's JMenuBar. - - * Added a librarian function in the PropertyHandler so you can ask - it for objects that were created with a particular property - prefix. Applies to those components created via the - openmap.components property. - - * Added the com.bbn.openmap.gui.dock package, which provides a - multi-layer layout for OpenMap components. - - * Misc changes: Fixed the area calculation in LabeledOMPoly, - Location now uses an OMPoint instead of an OMRect. - - * Added the com.bbn.openmap.gui.MiniBrowser component, which - displays HTML content for the InformationDelegator. It has a - back button, and a button to launch current content in the - default browser if the content is from a URL. Uses a JEditorPane - to display HTML. - - * Changed the WebBrowser temporary file extension from .tmp to - .html. - - * Added the com.bbn.openmap.plugin.graphicLoader.scenario package, - which is a csv-loaded chain-of-events displayed on the map. - -2003-04-05 Don Dietrick - - * Created the MapPanel component, which is now the central - OpenMap application/applet component. It takes a - PropertyHandler, or creates one if it isn't given one, and - creates and MapBean and MapHandler. It then uses the - PropertyHandler to get properties to create all of the components - for the application. The MapPanelChild interface is for - top-level components that should be added directly to the - MapPanel, and it allows the MapPanel to ask where the component - should be added in its BorderLayout. The MapPanel can be used on - any application as a regular Swing widget, basically embedding - OpenMap into an application or applet. - - * Modified the OpenMapFrame so that it applies to applications - only, instead of having it be responsible for figuring out when - it was being used in an applet and have it do the layout for an - applet. The OpenMapFrame now looks for the MapPanel and adds it - to its content pane. It also looks for a JMenuBar to add to - itself. The OpenMap class creates a MapPanel, PropertyHandler - and OpenMap frame to start the OpenMap application. The - OpenMapApplet is now a BeanContextMembershipListener, so it can - use the MapHandler to find components it needs. It also creates - a MapPanel and PropertyHandler, and does its own layout of - components. - - * Added the OMControlPanel, a little all-in-one component - containing a overview map, all of the projection control widgets, - and a layers panel. By default, it likes to be added to the left - side of the MapPanel. Also added the ControlPanelToggleMenuItem, - which locates the OMControlPanel in the MapHandler and can be - used to hide/show the panel. - - * Added the com.bbn.openmap.gui.WindowSupport, which provides - manangement functionality over JFrame/JInternalFrame for - components that want to emebed themselves or other components in - a window. The WindowSupport disposes windows when they are - dismissed or hidden to save memory and to prevent their existance - from keeping the jre thread active when parent components are - removed. The WindowSupport keeps track of positioning and - resizing changes and applies them to windows that are re-created - later for the same component. - - * Misc: Modifed the LayerUtils.getResourceOrFileOrURL method so it can - better locate resources for applets in the code base. Fixed the - problem with the OMRasterObjects for distance triggers, making - them think they are always filled so they respond to any query - within their limits. - -2003-03-25 Don Dietrick - - * Added the com.bbn.openmap.util.DataBounds and - com.bbn.openmap.util.DataBoundsProvider interface, and modified - the GoToMenu to use the - com.bbn.openmap.gui.menu.DataBoundsViewMenuItem to enable the - capability to focus the map on a particular data set. For - instance, if a ShapeLayer is added to the MapHandler, it will be - picked up by the DataBoundsViewMenuItem and a menu item for that - data set will be added to the submenu, allowing the map to be - recentered and zoomed directly over the area covered by the data. - - * Modified the LayersPanel and LayerPane classes, and added the - LayerControlButtonPanel. The LayerControlButtonPanel is a - configurable OMComponentPanel that contains the buttons to change - the layer order. These buttons used to be integrated into the - LayersPanel, and have been moved into their own panel that is - configurable via properties (horizontal, vertical, top, bottom, - right, left, and include/omit add/remove layer buttons). This - panel can be added to the LayersPanel in several different ways, - all configurations available via the properties, but if you don't - specifiy anything the LayersPanel will appear as before. The - LayerPane now notifies the LayersPanel when a layer entry has been - selected for movement, and that notification gets passed to the - LayersPanel and on to the LayerControlButtonPanel, and anything - else that is listening for PropertyChangeEvents. Notifications of - layer order changes also pass from the LayerControlButtonPanel to - the LayersPanel via PropertyChangeEvents. - -2003-03-13 Don Dietrick - - * The directory structure of the OpenMap package has been changed - in order to make it easier to add external code packages that - OpenMap classes rely on. The new structure of the package is: - -ANT_ENV.bat - environment configuration for Ant for Windows machines. -AUTHORS - People who have contributed to OpenMap. -CHANGELOG - List of changes between versions. -INSTALL - Installation instructions for compiling. -LICENSE - OpenMap License. -Makefile - Makefile for compiling code, forwards targets to Ant. -README - Start here, information about using OpenMap. -README.win32 - additional information for Windows users. -bin - scripts for building, starting the OpenMap application. -build.xml - Ant build file for compiling code. -classes - created when code is compiled, not present by default. -doc - Java API and architecture documentation. -ext - Externally available packages that OpenMap packages rely on. -iis - .NET webpages -lib - jar files used by OpenMap, including jars created from OpenMap - code. -openmap.properties - default configuration file for the OpenMap application. -share - misc information, applet pages, map data. -src - the OpenMap code packages. - -src/openmap - the OpenMap code base, compiles with Java 2. -src/ext - external code integrated into OpenMap package, compiled into - openmap.jar file. -src/svg - OpenMap code that relies on Apache Batik SVG - package. -src/j3d - OpenMap code that relies on Java 3D package. -src/corba - OpenMap CORBA client-server code that relies on - Inprise Visibroker package. - - - * OpenMap GUI components have been overhauled. Previously, most - of them created the Swing components they needed to provide their - GUIs. Now they have been written to extend the Swing classes they - used to use. Components that created many Swing objects and - managed their configuration have been broken into several new - components that can each use the MapHandler to configure - themselves. - - - The OMComponentPanel is a new OpenMap base class that - extends JPanel. This class implements the methods of the - MapHandlerChild (it knows how to work with the MapHandler) - and has methods that let it act as a PropertyConsumer. - - - The OMToolComponent is a OMComponentPanel extension that - can provide a GUI face to let it act like an OpenMap Tool. - The OpenMap Tool behavior can be controlled through - properties that can be set on the component. - - - The InformationDelegator is now an OMComponentPanel, now - uses the StatusLightPanel instead of creating and managing - the status icons itself. - - - The OverviewMapHandler is an OMToolComponent, and can - now beused as a JPanel. - - - The JPanel components in the OMToolSet have been - separated from the OMToolSet and made into - OMComponentPanels - the NavigatePanel, the ZoomPanel, the - ScaleTextPanel. All can be used individually. The - ProjectionStackTool can be used the same way. - - The Menus have been changed, too. The AbstractOpenMapMenu is the - base class for all menus, and is capable of being configured via - properties. The menu items for all of the menus have been - converted into JMenuItems that can use the MapHandler to connect - to other components (LightMapHandlerChild objects). These - JMenuItems are stored in the new gui/menu package, and all of the - old Menus - FileMenu, ControlMenu, NavigateMenu - have been - updated to use them. The com.bbn.openmap.gui.menu.OMBasicMenu is a - menu that can be configured through the properties. - - * The MapHandler has new methods that let you ask for components - using Class objects. Also, there are methods that let you receive - a Collection of objects as a result of queries if more than one - object meets the query. - - The methods for the components that use the MapHandler have been - standardized to the familiar ones defined in the MapHandlerChild - class. Most OpenMap components now inherit most of the - MapHandlerChild methods from a superclass, and override the - findAndInit(Object) and findAndUndo(Object) methods. A new - interface, the com.bbn.openmap.LightMapHandlerChild, specifies - these two methods as a component that can hook up to other - components it needs. - - * The MapBean now uses a MapBeanRepaintPolicy object to determine - how it will react to layer repaint requests. The - StandardMapBeaRepaintPolicy, used by default, simply forwards all - requests normally. The MapBean also forwards projection changes - in PropertyChangeEvents. - - * The Layer class has changed. All references to the AWTAvailable - variable have been removed. The ImageGenerator, which used this - variable to try to track Layer threads, has been removed. The - Layer.repaint() method now calls MapBean.repaint(layer) if its - parent is a MapBean. This is to allow the MapBeanRepaintPolicy to - take effect. - - * A MGRSPoint has been implemented, allowing conversions between - decimal degree lat/lon, UTM and MGRS coordinates. The UTM and - MGRS panels have been added to the CoordDialog component. The - CoordDialog, in addition to recentering the map on the entered - coordinates, also converts the coordinates to the other - representations in the different panels of the dialog. - - The com.bbn.openmap.plugin.UTMGridPlugIn has been added, which - draws the UTM zones on the map, labeled below certain scales. It - also has the capability of drawing distance grid squares around - the center point of the projection. These grids are labeled with - MGRS grid lables when zoomed in. - - * Thomas Paricaud contributed the e00 layer package, enabling the - reading of ArcView export formatted files. - - * MouseModes now have a notion of being invisible to the GUI - (their presence is expected to be noted by another component or - tool), and also have the ability to act as a proxy for another - MouseMode. When a MapMouseMode acts as a proxy for another - MapMouseMode, it sends all its events to the hidden MapMouseMode. - This functionality has been built into the AbstractMapMouseMode. - - MouseEvents are now wrapped within a MapMouseEvent by the - AbstractMapMouseMode. The MapMouseEvent provides information - about what MapMouseMode sent the event, provides a handle to the - MapBean and has a method to provide the latitude/longitude of the - MouseEvent location. - - The CoordMouseMode now calls a method for setting up the text - that gets presented in the GUI for the coordinates of the mouse. - This lets you easily extend the CoordMouseMode to specify the - units and format of the string. - - - * The OMGraphicHandlerLayer has become the uber-layer for - OpenMap. The methods for creating and rendering OMGraphics and - handing projection changes have been standardized in the - OMGraphicHandlerLayer, and a SwingWorker added to it. Almost all - of the other OpenMap layers are now based on the OMGraphicHandler - layer, with their SwingWorkers deleted and using the one from the - super class. - - The OMGraphicHandlerLayer now uses two different policy objects, - one that determines the behavior of the layer when the projection - changes (should the layer clear out the current OMGraphicList with - each projection change because it needs to repopulate it based on - the new projection or reuse all OMGraphics, and should a - SwingWorker thread be launched) and the behavior for rendering - OMGraphics. The prepare() method for an OMGraphicHandlerLayer - returns the OMGraphicList to be used for a projection, and can be - called in any thread. The doPrepare() method launches a - SwingWorker to call the prepare() method. Different OpenMap - layers set different ProjectionChangePolicy and RenderPolicy - objects depending on the behavior desired and how they gather - their OMGraphics. - - The StandardRenderPolicy forwards paint() requests to the render - method of the OMGraphicList. The BufferedImageRenderPolicy keeps - track of how long it takes to paint the OMGraphicList, and if it - exceeds a threshold it will create a BufferedImage to paint the - OMGraphicList into. If paint times decrease, the buffer is - discarded automatically. - - * Added many OMGraphic package improvements: - - - OMGraphicList has a 'vague' variable added that controls - certain behaviors. If an OMGraphicList is vague, it acts - as a whole OMGraphic, with any child OMGraphics - contributing to the whole group. The group gets treated as - the OMGraphic for find/select requests. If an - OMGraphicList is not vague, which is the default, the - OMGraphicList acts as a pass-through, an organizational - container for the child OMGraphics. Methods that also - modify the internal List have been synchronized on the - List to avoid ConcurrentModificationExceptions. - - - OMDistance has been added, an OMPolygon with labels at - each node specifying segment and total distance from the - first node. - - - OMSpline, OMDecoratedSpline have been contributed by - Eric Lepicier, along with their decorations and supporting - Editable classes. - - - Bart Geraci contributed new OMArrowHeads, much improved - look. - - - OMGraphics now have a getDescription() method, returning - a String that describes what they are. When called on an - OMGraphicList, you get a huge printout of the structure of - the OMGraphicList and its contents, including the contents - of any child OMGraphicLists. - - - OMText now have a setUseMaxWidthForBounds() method, - which let the background area for Multi-line text appear - as a bounding box, instead of a form-fitting polygon. - - - * Modified the OMDrawingTool by adding a behavior mask, which - dictates how the OMDrawingTool acts. There are behavior options - for deactivating when the mouse is clicked off the edited - OMGraphic instead of using the pop-up menu or palette Done button, - presenting the palette, presenting the pop-up menu, presenting the - pop-up menu on a ctrl-click or right mouse click. This makes - using the OMDrawingTool much easier to use for the user. The - OMDrawingTool now has a canEdit() method, which lets you ask if it - can edit a particular Class of OMGraphic without invoking the - tool. - - * Modified the DrawingToolLayer to have methods that ask whether - an OMGraphic should be edited (handed to the OMDrawingTool), and - what the tool tip should be for an OMGraphic. This makes it - easier to customize behavior for mouse events in layer subclasses. - - * The BufferedImageHelper will use JAI if it is available to - create a BufferedImage. It uses reflection to figure this out, so - it will compile and run if the JAI is not installed. - - * Added an OMGraphicDeleteTool, a button component that sits in - the tool panel and listens for events from any other component, - like the OMDrawingTool, for OMGraphics that have been selected. - If the button is pressed, the OMGraphicDeleteTool deletes the - selected OMGraphic by notifying the DrawingToolRequestor to - delete the OMGraphic. If the source of the selection is the - OMDrawingTool, the OMGraphicDeleteTool will tell the - OMDrawingTool to delete the OMGraphic, which it does by notifying - the DrawingToolRequestor when the drawing tool deactivates. - - * Added the com.bbn.openmap.layer.editor package, which contains - an EditorLayer that extends the DrawingToolLayer. The EditorLayer - uses an EditTool to make modifications to its OMGraphics. Unlike - the DrawingToolLayer, the EditorTool presents a GUI in the tool - panel that controls tools specifically for that layer, with uses - and meanings designated for interaction with that layer. There - have been three EditorTools implemented - a superclass - AbstractDrawingEditorTool that creates an internal OMDrawingTool, - and two subclasses. The DrawingEditorTool loads different - EditToolLoaders into the OMDrawingTool - creating the drawing - layer that most people were expected before the drawing tool came - out, with any graphics created going directly to the layer. The - DistanceEditorTool has a button to create OMDistance objects, - which, unlike the DistanceMouseMode, creates distance lines that - are persistant. The AbstractDrawingEditorTools use the - SelectMouseMode to modify OMGraphics that are on the map. If an - OMGraphic is being edited, the SelectMouseMode is used as a proxy - for the internal OMDrawingTool, so the modifications look like - they are being managed from the Gestures mouse mode. - - * ScaleFilterLayer now presents palettes for layers, forwards - MapMouseModes to active layer, status event for active layer. - - * The EsriGraphicList and DbfTableModel have static methods that - take a URL to a file and provide an instance of themselves. - EsriPoint and EsriPolys are cloneable. - - * VPFLayer can be told to get features from a particular library. - - * New icons for the MouseModeButtonPanel. - - * The com.bbn.openmap.plugin.graphicLoader package documentation - has been improved, and the GraphicLoaderConnector problem caused - by adding GraphicLoaderPlugIn/PlugInLayers to the MapHandler when - the GraphicLoader was given a handle to the LayerHandler. This - caused a concurrent modification exception. Now a list of new - PlugInLayers is maintained, and added to the MapHandler after the - iteration. - - * The projections have been modified to help out the - ProjUtils.getScale() method, returning the proper scale for the - particular projection type. - - * ArgParser can now be told to expect '-' in arguments (for - negative numbers) instead of automatically assuming that those - arguments are command arguments. - - * The ComponentFactory can now use reflection to create Objects - with arguments in their constructors. - -2002-12-20 Donald Dietrick - - * Moved the CHANGELOG to the top-level directory, in order to help - people find it. - - * Added a method to the ComponentFactory that lets you ask it to - create Objects using an Object[] that serves as a set of arguments - to the constructor. The method uses reflection to figure out if - the Object[] contents make sense for the new Object type, and will - create the new Object if it can. - - * Modified how com.bbn.openmap.proj.ProjUtil.getScale() works, in - order to get a better scale value. The calculation has been moved - back into the Projection objects, and the getScale() method now - queries the projection for the scale value that is appropriate for - the situation. - - * Modified how the PlugInLayer works between the MapHandler and - its PlugIn. The PlugInLayer used to forward all communication to the - PlugIn, now it simply adds the PlugIn to the MapHandler and steps - out of the way. - - * The VPFLayer components have been modified to read data from a - URL, and the bug that prevented data from being read from a jar - file by an applet running 1.4.1 has been fixed. The API for the - VPF components changed, so that components no longer take a File - object for the paths, but instead take a String. Also, code was - added to prevent multiple File separator characters from appearing - in file paths. - - * The DrawingTool has been modified to have a notion of behaviors, - which can be set via an integer mask. The pop-up menu that used - to be required to complete modifications to an OMGraphic is no - longer needed, but remains a behavior option. By default, it - still appears with a right-click or ctrl-click. See java docs for - details. - - * Added the com.bbn.openmap.layer.editor package, which contains - the EditorLayer. The EditorLayer uses EditorTools to create a - more application-centric layer, one that needs to capture - MouseEvents exclusively, and also place a GUI in the ToolPanel - when the EditorLayer is active. A DrawingEditorTool is provided, - which provides the action most likely expected from a drawing - layer, as opposed to the flexibility that the - OMDrawingToolLauncher provides. The DrawingToolEditor makes the - EditorLayer look like a drawing layer, with the controls and mouse - events acting on its own OMGraphics. - - * MapMouseModes now have a notion of not being visible, and the - OpenMap GUI components that display status of MapMouseModes honor that. - - * Misc bug fixes - Layer has correct setAsBackground flag set. The - ToolPanel correctly removes Tools that have been removed from the - MapHandler. The BinaryFile pays attention to a - -Ddebug.connection_problems flag, and if it is set it will let the - Thread sleep for a second. This is a fix, suggested by Sun, for - problems that may occur by the client unexpectedly closing down a - socket too soon before all the data has been read off the stream. - The LocationLayer GUI has tabs for multiple LayerHandlers again. - - * Modifed the build.xml file so compilations are performed with - debugging on. - -2002-11-08 Bill Mackiewicz - * OpenMap 4.5.4 released. - -2002-11-07 Don Dietrick - - * Modified the openmap lauch scripts so they pick up any changes - that may have been made to the version in the top level openmap - directory. In 4.5.3, the jar had to be rebuilt to contain the - modified properties file for the changes to take effect. - - * MapBean changes. Modified how the background color is handled - in a MapBean. If the background is not explicitly set in a - MapBean, the background color of the projection will be used. If - a background is set in a MapBean, that change now only affects - that particular MapBean. The OverviewMapHandler can now be set to - listen to property changes of its source MapBean in case it should - mimic background settings. The background can now be set to a - Paint object as well (use setBckgrnd() methods). - - * There is now a BufferedLayer that can act as a group layer, - buffering all of its layers into an image. There are settings - that can manage how often the buffer is recreated, and these - settings depend on if the image is transparent and how often the - group layers repaint themselves between projection changes. - - * There is a BufferedLayerMapBean, which uses a BufferedLayer to - contain all layers marked as background layers. This 'background' - setting has been added to Layer. When the BufferedLayerMapBean - receives a new stack of layers, it reads them and adds the - background layers to its BufferedLayer. This really helps to - decrease repaint times. This layer has not been added as the - default MapBean in penMap because there isn't a good way to manage - the layers and notify the user why the layer order may not appear - the same way as it does elsewhere in the GUI. A new LayersPanel - is needed. However, the BufferedLayerMapBean can be loaded into - the application by using the -Ddebug.blmb flag. Using the - -Ddebug.bllp puts checkboxes in the LayersPanel so you can mark - layers as background layers. - - * The com.bbn.openmap.tools.beanbox package was updated, and a new - example package (com.bbn.openmap.examples.beanbox) was added to - show how to configure and use the beanbox for drag and drop - additions to the map. - - * EsriPlugIn got many changes and fixes. The palette will return - after the first dismissal, the horizontal scroll will appear and - the table won't be compressed. If the shp file is the only one - specified, they the shx and dbf files are assumed to be next to - it. The files can be named as files, URLs or resources (relative - pathnames). EsriPlugIns can be created dynamically. - - * The Shape dataAccess package was modified. Exports are more - reliable and you can specify if the DBF file should be written. - Sublists are only created for multipart geometries. OMGraphics - created from Shape file records will be held directly in the top - level OMGraphicsList instead of being held in a sublist. Null - fields in the dbf file don't cause number exceptions. - - * The GraphicLoader concept was much refined, with the creation of - an AbstractGraphicLoader that has a pre-defined timer, etc. A - GraphicLoader is a component that creates OMGraphics on it's own - schedule, and then notifies a receiver to paint the - OMGraphicList. The GraphicLoaderConnector is a component that - lives in the MapHandler and looks for GraphicLoaders in the - MapHandler that do not have a component that is receiving its - OMGraphics. If it finds on, it creates a - PlugInLayer/GraphicLoaderPlugIn automatically to display objects - on the map. - - * OMGraphic modifications: - - OMGraphics now have a notion of a TextureMask variable that can be - used to hold a TexturePaint object. If the TexturePaint object as - some transparency in its image, the OMGraphic's fillPaint will - show through the fill pattern. - - The OMRasterObjects now correctly update their Java Shapes - correctly. This fixes the problem where icons were not responding - to gestures. - - OMScalingRaster now has access to the clipping rectangle, a Java - 2D rectangle that specified what part of the image is on the map. - - OMArrowHeads for OMLines have their wingtip and winglength - attributes exposed so they can be adjusted. Their rendering was - improved with relation to matting, filling. - - OMGraphics were modified so that fill color matters with regard to - distance. Clear shapes will be treated as lines, without - area. OMLines are never treated as being with area (affects great - circle lines) no matter what the fillPaint settings are. - - * MouseModes can now provide an Icon. The MouseModeButtonPanel - can be used with those icons. If a MouseMode doesn't provide an - icon, an name will be used instead. - - * Modified the SVGFormatter so it gets all the individual layer - graphics properly from a BufferedMapBean. - - * Eliot Lebsack from Mitre provided a couple of new classes - - com.bbn.openmap.layer.shape.ShapeFileCrop, can create a new Shape - file with shapes from a certain area of another Shape file, and - com.bbn.openmap.gui.SaveAsVirtualImageMenuItem, which lets you - set the size of an image to create from the current map. - - * The SaveAsMenuItems now add an image-appropriate suffix to file - names when an image is saved. They also check and confirm that a - duplicate image will be overwritten. - - * The MapRequestHandler can now be set to use Layer visibility - settings to determine what layers should be used for an image. - - * Misc layer improvements: Many Layers had properties renamed to - not have a '.' in the front of them, and their setProperties - methods have been modified to work with or without a property - prefix. GraticuleLayer has font size property. DTED file - components do better checking for null fields. ETOPOLayer updated - to read ETOPO2 data. LocationLayer has LayerHandlers access - exposed. The RpfProductInfo now has catalog static methods to - print out information on all of the various data types. - - * Fixed bug where gestures were not accessing information on - AreaShapeLayer graphics where the attributes were loaded via a dbf - file. - - * Fixed the OMDrawingToolLauncher so it receives its list of - EditToolLoaders from the OMDrawingTool, instead of finding them on - its own. - -2002-07-24 Bill Mackiewicz - * OpenMap 4.5.3 released. - -2002-07-24 Bill Mackiewicz - * OpenMap 4.5.2 released. - -2002-07-23 Bill Mackiewicz - - * OpenMap 4.5.1 released. - -2002-07-22 Donald Dietrick - - * Added the com.bbn.openmap.tools.dnd package that contains a - global application mechanism for handling Drag and Drop events. - -2002-07-21 Don Dietrick - - * Added Oliver Hinds' OMColorChooser preview panel, so you can see - what the color looks with the transparency setting before you hit - OK. - -2002-07-20 Don Dietrick - - * Incorporated Raj Singh's updates to the WMSPlugIn, which bring - it into compliance with WMS specification version 1.1.0, including - some error handling and JPEG image quality requests. - - * Incorporated Lonnie Goad's updates to the EsriPlugIn, which - improved GUI interaction, table interaction, and provided tool - tips over OMGraphics on the map that reflect the DBF contents for - that graphic. - - * Fixed problems in the com.bbn.openmap.dataAccess.shape package. - The ShpOutputStream was putting in the wrong record number - (started at 0 instead of 1), and fixed a couple of problems with - export, including a problem with handling embedded lists, and - translating DrawingAttributes from OMGraphics that were converted - to EsriPolygons and EsriPolylines. - -2002-07-18 Don Dietrick - - * Added ProgressEvent, ProgressListener and ProgressSupport - classes to the com.bbn.openmap.event package. These objects - provide a way for a component to let someone else know how much of - a task is done. This has been integrated into the MakeToc class - in the RPF package. - - * Added a 'matted' property in the OMGraphic object. If - setMatted(true), then the OMGraphic gets drawn with a thin, 1 - pixel black line around it. Makes it more distinctive, especially - in busy backgrounds. - - * Changed the graphicLoader package, making it much more - significant. The GraphicLoader is an interface, representing an - object that creates OMGraphics from some source and sending it to - a receiver that will rendering it on a map. The - AbstractGraphicLoader is an OMComponent that contains all the - basic GraphicLoader functionality, along with the basic ability to - use the MapHandler to find objects and being a PropertyConsumer, - so it's ready to be initialized with properties in the - openmap.properties file. The MMLGraphicLoader is additionally - prepared to receive MouseEvents. The LOSGraphicLoader is the old - GraphicLoader that lets things wander on the map, while keeping - track of what objects are in LOS of each other. - -2002-07-17 Don Dietrick - - * Made modifications to OMGraphics. Made the OMLine handle arrow - heads properly. Made arrow heads bigger. Made OMGrid more - consistant and fixed bugs in column and row handling. Added an - empty sort() method on OMGraphicList which can be extended with - customized sorting criteria. Added a sort action constant mask to - OMGraphicConstants. Added setSelected() and isSelected() methods - to OMGraphic. - - * Added better trapping for SVGFormatter errors in the FileMenu. - - * Added the OMComponent, which is a MapHandlerChild and a - PropertyConsumer, reflective of an object being added to the - openmap.components property of the openmap.properties file. - LayerHandler was changed to extend it. - - * Modified Environment.java to handle internal frames - independently of being in applet mode. - - * Modified the build.xml file. The OpenMap package builds things - differently, too. First, all compiled classes are placed in the - classes/openmap directory, except for the CORBA classes which are - placed in the classes/corba_vb directory. Second, all of the - openmap classes are placed in the openmap.jar file. omcontrib.jar - and omcore.jar are no longer created. All of the CORBA classes - are placed in the omcorba_vb.jar if the corba build target - (visibroker) is created. - - * Added Jakarta Ant 1.4.1 to the OpenMap package, making OpenMap - pretty much self-compiling. All of the infrastructure for the - original Makefiles have been removed, and replaced with Makefiles - that call ant. - -2002-06-21 Don Dietrick - - * Modifed the build.xml file to handle the corba classes better. - - * Created the MakeTocException, and the - com.bbn.openmap.layer.rpf.MakeToc class now throws that exception - instead of calling System.exit(), in case it is embedded into a GUI. - -2002-06-18 Don Dietrick - - * Misc bug fixes in several classes, fixing null pointer - exceptions, security access exceptions, etc. - -2002-06-13 Don Dietrick - - * Modified the EsriShapeExport class so that a GUI is not brought - up to save the files if a file path is provided. - - * Fixed a bug in OMPoly that prevented internal Shape objects from - being created if soShapes == false. - -2002-06-03 Bill Mackiewicz - * OpenMap 4.5 released. - -2002-05-29 Don Dietrick - - * Modified MIFLayer to be an OMGraphicHandlerLayer. - - * Modified the clone() method in Proj.java, so that the internal - Mercator projection used for complex lines gets deep cloned on - copies. This allowed removal of a synchronized block of code. - - * Added edit methods on the DrawingTool that take a MouseEvent. - These additional edit methods put the EditableOMGraphic directly - into edit mode instead of selected mode, so that mouse events have - an immediate effect on the OMGraphic. Makes for quicker editing - in some cases. Also, a setAllowGUIOption method was added to - OMDrawingTool so that the palette for an EditableOMGraphic can be - brought up from the pop-up menu, if the user wants it. - - * BufferedMapBean and MapBean have had their clipping restrictions - lifted, in order to provide a way to have smoother animation. Partial - maps may be drawn if another layer trys to render itself,xc not - knowing if there is a clipping rectangle set on the MapBean, so - just be aware of that if you set the clip rectangle on them. - -2002-05-28 Don Dietrick - - * Fixed that annoying NullPointerException in the - com.bbn.openmap.layer.shape.ShapeLayer.renderDataForProjection() - method. - - * Overhauled the com.bbn.openmap.omGraphics package. The changes - are extensive, but the use of OMGraphics is backward compatible. - - The biggest change is that internally, OMGraphics represent - themselves as java.awt.Shape objects (actually, GeneralPaths) - after they are projected/generated. After generation, the Shape - object can be retrieved by OMGraphic.getShape(). The Java Shape - interface provides different spatial operations you can perform on - other shapes - contains, intersects, getBounds. - - The first new thing to notice is the - com.bbn.openmap.omGraphics.OMGeometry interface, which is a basic - interface describing renderable shapes. The most basic - implementation of this interface is the abstract class - com.bbn.openmap.omGraphics.geom.BasicGeometry, which contains the - code that manages Shape creation. OMGraphic now extends - BasicGeometry, adding DrawingAttributes information to describe - how the Shape should be rendered (linePaint, fillPaint, Stroke). - - There is now an OMGeometryList, which extends OMGraphicList. The - difference between them is that OMGeometryList contains OMGeometry - objects, and when an OMGeometryList is generated, all of the - OMGeometry objects contribute to a single Shape object (disjointed - or not), with the DrawingAttributes of the OMGeometryList - dictating how the Shape is drawn. The - com.bbn.openmap.omGraphics.geom package contains these OMGeometry - objects, of which there are two currently implemented - - PolygonGeometry and PolylineGeometry. When rendering an list of - graphics that share the same color and stroke types, using an - OMGeometryList with a single Shape obejct is faster than using an - OMGraphicList with separate OMGraphics. - - Some other omGraphic package improvements: - - Moved the OMArrowHead calculations from OMLine to OMArrowHead. - - Removed dependency on java.awt.Toolkit from OMBitmap and - OMRaster in favor of BufferedImage. - - To add control over managing OMGraphics, the OMGraphicHandler - interface was created. This interface defines methods to interact - with a component that has OMGraphics, including spatial - filtering. The FilterSupport object helps objects implement this - interface. The abstract classes OMGraphicHandlerLayer and - OMGraphicHandlerPlugIn are OMGraphicHandlers that use FilterSupport. - - Layers that implement the OMGraphicHandler interface - - GraticuleLayer, DemoLayer, DrawingToolLayer, ShapeLayer. - - Other layer improvements that take advantage of the OMGeometry - changes: - - ShapeLayer2.java - A shape layer that uses the new OMGeometry - objects. BufferedShapeLayer uses the new OMGeometryList. The - com.bbn.openmap.layer.shape.EsriRecord components handle - OMGeometryLists and OMGeometry graphics. - - The com.bbn.openmap.layer.shape.areas.AreaHandler groups all - like areas together in a OMGeometryList. - - As a side note, OMRaster and OMBitmap create rectangles outlining - their shape. OMGrid hasn't been modified to do anything in - particular with it's Shape object pointer. - - * Created a com.bbn.openmap.dataAccess package, which is intended - to hold components that access particular data types. As an - example, the com.bbn.openmap.plugin.esri components that were - responsible for directly reading and writing shape files, were - moved to com.bbn.openmap.dataAccess.shape. The rpf, dted, mif, - etopo, and other data components will follow. Note that the - EsriPlugIn and EsriLayer classes in the - com.bbn.openmap.plugin.esri package still exist. - - * Incorporated a submission by Karl Stuempfle and Lonnie Goad - working for OptiMetrics, Inc. that provides a way to take an - OMGraphicList and export it to a (or up to three) Shape files. - The class that does this is - com.bbn.openmap.dataAccess.shape.EsriShapeExport. If a dbf file - isn't specified in the OMGraphicList.AppObject(), one will be - created for each .shp file, and it will contain the rendering - attributes for the OMGraphics. The - com.bbn.openmap.plugin.esri.EsriPlugIn reads the dbf file and - looks for these attributes in it. If they are there, they are - used, otherwise the default settings are used to render the shape - graphics. - - The DbfTableModel was modified, and augmented with the - MetaDbfTableModel, to allow direct editing and modification of the - Dbf files. - - The DrawingToolLayer was modified to use the EsriShapeExport class - to export its graphics when a button is clicked on its palette. - - * Added the com.bbn.openmap.tools.j3d package, which contains - components for creating a Java 3D scene, and creating and - controlling a viewer for that scene. This package requires that - the Java 3D extension package - (http://java.sun.com/products/java-media/3D/index.html) in order - to compile and run. - - There are some basic components to this package: - - The OM3DManager is the abstract object that creates a 3D scene - and loads it with objects. The MapContentManager is a basic - manager that creates a view window that is controlled by the arrow - keys. The ControlledManager creates a view window that is - controlled by an outside component, and the - com.bbn.openmap.plugin.pilot.PilotPath is an example of an object - that controls it. - - The OMKeyBehavior class is a behavior class that controls - movement of the camera over the scene. - - The MapContent class controls how components are added to the - scene. Map objects are added to the scene in different ways, - check the javadocs for more information. - - There is still work to do in this package. Give feedback, money - or code and guide where it goes. - - * Added the com.bbn.openmap.plugin.pilot package, which is - a demo package to show how to use the j3D package. The user can - add paths for a 'pilot' to follow, and then create a view into a - 3D scene that changes as the 'pilot' moves over the map. - - * New OpenMap .NET XML Web Services code has been written and included - in the openmap/iis directory. A demo of this code, which is a - html OpenMap client, will be set up at http://www.openmap.net (get - it?) eventually, but a link from the main OpenMap web page will - direct you to it as well. - - There are two directories in the OpenMap.net project: - ImageWebService and OpenMapWeb. - - ImageWebService contains the .NET XML Web Services. There are - three of them: ProperService.asmx, GetMapService.asmx, and - TimerService.asmx. - - ProperService is responsible for starting and killing Java Image - servers, updating user sessions, keeping information about layers - used. - - GetMapService service has three methods: GetMapImage, - RecenterMap, PanMap. It uses ProperService to start Java processes - as needed. - - TimerService is a utility that will call CleanServerProcs() - method in ProperService every certain number of minutes to check - whether it's time to kill some java servers. - - The section in web.config file in ImageWebService - folder is used to configure web services to point to the Java - OpenMap installation and openmap.properties file. - - The OpenMapWeb folder contains two ASP.NET files: WebMap.aspx and - MapImage.aspx. - - WebMap.aspx is the user interface to the project. - - MapImage.aspx is used to contact a web service to get raw image - data. - - To support this service, additional functionality was added to the - ImageServer class: - - - the PAN, AZIMUTH, X and Y arguments were added to the parsable - argument list, allowing the client to send the server panning and - centering commands (based on the current image projection). - - if the 'layers' property is not defined for the ImageServer - (including the MapRequestHandler) to use to configure the default - layers, then the 'openmap.layers' property will be used to create - the layers available to the ImageServer, and the - 'openmap.startUpLayers' property will define the default layer list. - - * Modified the build files and the build.xml ant file so that - source files that require other software packages will not be - included in the general build, but can be built with modifications - to some settings. There are three main groups of addition code - that are controlled this way: - - - the Java 3D components in the com.bbn.openmap.tools.j3d package, - which depend on the Java 3D package from Sun. - - the SVGFormatter in the com.bbn.openmap.image package, which depends - on Batik, see entry below regarding SVG creation. - - the CORBA components in com.bbn.openmap.layer.rpf.corba (existed), - com.bbn.openmap.layer.specialist (new) and - com.bbn.openmap.plugin.corbaImage (new) packages, which are all - configured to compile and run with the Visibroker CORBA - implementation. The are based on the BOA model, so if anyone - wants to translate that to POA and updated them to work with the - CORBA classes in the Java distributions, please do. - - * SVG creation is now supported. Added the SVGFormatter class to - the image package, created from code contributed by Sebastien - Prud'homme. This class requires the installation of the Batik - package (http://xml.apache.org) to compile and use. If the Batik - classes are found at runtime, the SVG option is added to the File - -> Save As menu. - - * Added the com.bbn.openmap.layer.specialist package. This - package has actually been around since OpenMap started. It's a - client-server package that transfers OMGraphic-like objects. - Doesn't transfer OMGrids or OMPoints graphics. There are - implemenations of servers for DTED, Shape and VPF data. All use - the CSpecLayer for the client. The Specialist.idl file needs to - be compiled (idl2java) to create the com.bbn.openmap.CSpecialist - package, which gets compiled and put into the cspec58.jar file. - All of the other classes get put into the specialist.jar file. To - used this package, these jars, along with the Visibroker jar - files, need to be added to the classpath using the -Xbootclasspath - java flag. The rt.jar java runtime jar needs to be added to the - bootclasspath as well, but after the Visibroker jars. - - * Added the com.bbn.openmap.plugin.corbaImage package, which is a - corba-based version of the SHISPlugIn/SimpleHttpImageServer - client-server setup. The package has a corba-based server that - creates image objects sent to the client plugin. - - * The Corba RPF package has been improved. The server now has - settings for the maximum number of caches to use, and a timer that - cleans them up after a certain amount of time. - - * Modified the examples (com.bbn.openmap.examples packages) to - show how to use the MapHandler for even simple applications. - Moved the examples away from connecting components manually. - - * Added the OMScalingRaster, created from a contribution from - Adrian Lumsden (and as I understand, with help from Steve - McDonald). It's an extension to the OMRaster object that takes an - upper left and lower right coordinate, and automatically scales - its source image according to the projection in generate(). It - does *not* warp the image to match the projection, it just does - straight scaling. - - Because of this class, the - com.bbn.openmap.plugin.CSVTiledImagePlugin was created to use - them. It uses a CSV file to list coverage coordinates and URLs of - images. This PlugIn does not do any real management of the images - other than to load them and use them - it doesn't drop images that - aren't used on the map, etc. Those are saved as improvements for - later. - - Also, the RpfLayer code (RpfSubframe) now uses the OMScalingRaster - for the Rpf subframe tiles. - - * Added some new functionality to the com.bbn.openmap.layer.shape - package. Created the MultiShapeLayer, which can display one or - more shape files. The palette for this layer provides controls - for adding buffering and rendering behaviors. The AreaHandler in - the com.bbn.openmap.layer.shape.areas now also uses dbf files, in - addition to csv files. - - * AppletDataNugget has been deprecated, it's not needed anymore. - BinaryFile has been fixed to be able to find files in jar files - from an applet as expected. - - * Modified the Layer parent class, adding a Projection variable - for all subclasses to use. Accessor methods that take projection - events and projections to get to the projection variable were also - added. Added Layer.projectionChanged() method that sets this - projection variable. Most layer subclasses will probably have - their own version of the projectionChanged() method, so it can be - called if desired. The OpenMap layers that used to save a copy of - the projection have been updated to use the new method and the - Layer.projection variable. - - * Added the Quantize.java class, written by Adam Doppelt, to the - contrib/doppelt directory. The Acme GIF creation code has been - modified to use Quanitize if the image being encoded has more than - 255 colors. Because of this improvement, the GIF option has been - added to the File -> Save As menu. - - * Added the com.bbn.openmap.plugin.graphicLoader package, which is - a demo package to show how to use the LOS code in the - com.bbn.openmap.tools.terrain package. The user can add points - over the map, some stationary, some wandering, some following a - path, and the components figure out if they can see each other, - drawing a dynamic network on the map. - - * Fixed a bug in the SoloMapComponentReplacePolicy where the - replaced SoloMapComponent wasn't actually removed before being - replaced. - - * Fixed a bug in LayerHandler where hasLayer() only checked the - first layer, instead if iterating through all of them. - - * Updated the Link package so that OMBitmap, OMCircle, OMGrid, - OMLine, OMPoint, OMRect, OMRaster, OMText and OMPoly objects are - able to be written to the link via the LinkGraphic.write() method. - - * OMDrawingTool now makes distinction between new graphics and - updated graphics when it notifies the DrawingToolRequestor. The - OMGraphicList properly handles the OMAction that reflects these - changes, adding updated graphics it doesn't currently have, adding - new graphics, and doing nothing for updated graphics it has. - - * ProjectionStack now picks up changes to Background color changes - to the MapBean. - - * Added a MouseModeButtonPanel to the gui package. This can be - used instead of the MouseModePanel (option menu). Right now, the - buttons display the MouseModeID text. If the .gif file is - found as a resource, that image would be used on the button - instead. We haven't designed images yet. - - * Misc changes: - - EarthquakeLayer default sites updated. - - Fixed layout of CoordPanel and DMSCoordPanel. - - Environment class adjusted so that for the Windows platform, the - XWindowsWorkaround for improved clipping performance is enabled. - - The Environment was also changed to handle internal windows - better. It now containes a JLayeredPane to use as a desktop. All - OpenMap components that consider using internal windows have been - updated to use the new setup. - - The DMSLatLonPoint has been updated to use floats for its - internal seconds representation, for better precision. - - app/RouteLayer was removed, it was redundant. - - Projections now use/return ArrayLists instead of Vectors. - -2001-12-11 William Euerle - - * Numerous changes to VPF layer code to make it more robust. A - few minor performance improvements. Some initial code to handle - "node" features - this code is not yet complete. - -2001-11-21 Donald Dietrick - - * Created the openmap/share/openmap.jnlp file, which demonstrates - how to set up a file to be used with Java WebStart. MacOS X users - and anyone else with Java WebStart installed can click on that - file and the openmap applet will launch and run on the desktop. - You can also use the WebStart file on our demo location at - http://dstl.bbn.com/openmap/openmap.jnlp - - * Added the com.bbn.openmap.omGraphics.labeled package, which will - be the future home of OMGraphics that have text labels attached to - them. Only the LabeledOMPoly was implemented. The LabeledOMPoly - lets you attach a text object to a specific node, or you can tell - it to center the text within the poly. The polygon parameters can - be modified with the OMDrawingTool, but the text attributes - cannot. The text can only be modified programmatically. - - * Added typing controls in the com.bbn.openmap.plugin.esri package - to scoped things a little better. Includes fixes for the - NullPointerExceptions found in the last version. The Tester.java - class was added as an example of how to use the shapefile creation - capabilities of the package. - - * Fixed a NullPointer bug in the OMToolSet. - - * Added the MapWindow, a simple JFrame widget that contains a - MapBean, MapHandler, MouseDelegator and LayerHandler. Easy to add - a map to your application. - - * Cleaned up how layers are deleted. Fixed MapBean bug where all - layers were receiving remove() calls in certain situations. - Cleaned up how the InformationDelegator was releasing listeners to - the palette triggers. The LayerSupport and other listeners were - adding duplicates to their lists in some situations, which - hampered clean up, too. - - * Fixed bug in DMSLatLonPoint where the lat/lons weren't being set - properly. - - * Modified the ANT_ENV.bat file with better support for - configuring the Windows environment for Ant. Also updated the - README.win32 with instructions to set up Ant to build OpenMap. - - * OpenMap 4.4.1 was released a day after 4.4, with some - modifications to the com.bbn.openmap.plugin.esri package. - -2001-11-01 Bill Mackiewicz - * OpenMap 4.4 released. - -2001-11-01 Donald Dietrick - - * PropertyConsumer handling has been very significantly improved, - thanks to a code submission from Bernhard Reiter and Kai Lessmann. - - First, there is a new package, called - com.bbn.openmap.util.propertyEditor. It contains generic - PropertyEditor classes, and an Inspector class that uses the - PropertyConsumer's methods to provide an interface to set and - modify properties. - - You can run the Inspector as an application on any - PropertyConsumer class to test out what that interface looks like, - and to see if there are any problems loading the Inspector with - the contents of the PropertyConsumer's properties. - - The Inspector exects that the properties returned in the - PropertyConsumer.getProperties() method will be scoped, i.e. that - if a property prefix is used, the properties will also have that - prefix in front of the properties. - - The Inspector uses the PropertyConsumer.getPropertyInfo() method - of classes to get information about the properties being - displayed. The Inspector does not expect that the properties - returned in this method will be scoped - Just the base properties - should be returned as keys, with their values being a short - explaination for what the property represents. This explaination - is used as a tool tip in the interface. Also in this method, - properties can be set with the key having a '.editor' suffix, with - the value of the property being the fully qualified class name of - the PropertyEditor to use to adjust that property. - - So, while a class might return a (prefix.lineColor, AARRGGBB) - property from the getProperties method, it would return a - (lineColor, "Color used for lines") property and a - (lineColor.editor, - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor") - property in the getPropertyInfo() method to use to adjust the - fillColor property. - - The PropertyConsumer now has a EditorProperty string 'editor' and - a ScopedEditorProperty string '.editor' which makes it easier to - define PropertyEditor properties on the fly. - - The submission also includes a com.bbn.openmap.gui.LayerAddPanel, - which can be brought up by the LayersMenu, or the LayersPanel. It - uses a property called openmap.addable to set a list of Layer and - PlugIn classes that can be created at runtime, and configured - using the Inspector. Each unique marker name (separate from the - marker names used in the openmap.layers list) needs to have a - .class property defined for it (what to instantiate), and a - .prettyName property (a generic GUI name for the layer). The - LayerAddPanel provides a place to actually name specific layer - instatiations, and the prefix for those layers are automatically - generated (see PropertyHandler changes). - - One more note on this - You'll notice that we've changed the - property definitions so that they *DON'T* include a scoping period - at the front of them. The PropertyConsumer interface has a - setProperties(Properties) method, so the PropertyConsumer can be - configured without a property prefix. - - This really applies to developers that configure their layers - programmically. If you define a Properties object that is only - used by one Layer (or other PropertyConsumer type) you don't have - to scope the properties. i.e. - - ShapeLayer shapelayer = new ShapeLayer(); - Properties shapeprops = new Properties(); - - shapeprops.put("shapeFile", shapefilepath); - shapeprops.put("lineColor", shapefilepath); - - // or - // shapeprops.put(ShapeLayer.shapeFileProperty, shapefilepath); - // shapeprops.put(ShapeLayer.lineColorProperty, shapefilepath); - - shapelayer.setProperties(shapeprops); - - You could do this: - - ShapeLayer shapelayer = new ShapeLayer(); - Properties shapeprops = new Properties(); - String shapeprefix = "uniqueshape"; - shapeprops.put(shapeprefix + ".shapeFile", shapefilepath); - shapeprops.put(shapeprefix + ".lineColor", shapefilepath); - - // or - // shapeprops.put(shapeprefix + "." + ShapeLayer.shapeFileProperty, shapefilepath); - // shapeprops.put(shapeprefix + "." + ShapeLayer.lineColorProperty, shapefilepath); - - shapelayer.setProperties(shapeprefix, shapeprops); - - But you don't have to if the shape layer is the only layer using - the Properties object. - - But, if you use the Properties object for all of your properties - definitions, then you have to use the prefix to ensure that the - layer picks up the properties meant for it. - - * The PropUtils had methods added that are really helpful to use - for the PropertyConsumer methods. - - String prefix = PropUtils.getScopedPropertyPrefix(PropertyConsumer ps); - String prefix = PropUtils.getScopedPropertyPrefix(String prefix); - - Either return an empty string ("") for null prefixes, or the - prefix with a period attached. Either way, the properties in - getProperties can be defined by calling the method above, and - simply putting it in front of the property name. - - * The PropertyHandler has been updated to keep track of - usedPrefixes, and can test and modify suggestions for new prefixes - if asked. The LayerAddPanel uses this when new layers are created - at runtime. - - The PropertyHandler has also been modified to take a PrintStream - and the MapHandler, and create a openmap.properties file. It can - also read in a openmap.properties file at runtime (which is - essentially loading a new map). The application components are - not affected by the contents of a newer openmap.components - property in the new file. Just the layer properties are used, and - the projection settings. - - When a new openmap.properties file is created, the - openmap.components property that was set in the lauched properties - file is reused. New components that may have been added at - runtime have not been added. This is a temporary workaround to - the problem that occurs when pulling objects out of the MapHandler - - they do not come out in any specific order, which really affects - the look of any application that may try to load components with - that order. That's also why the application ignores the - openmap.components property of any openmap.properties file loaded - later. - - The FileMenu was modified to have 'Load Map...' and 'Save Map...' - options, using the SavePropertiesMenuItem. - - * Modified for PropertyConsumer compliance. These are layers ready to - be created at runtime: - - - DrawingAttributes.java (just so you know for your layers) - - EarthquakeLayer.java GraticuleLayer.java (also uses Inspector for - runtime modifications via palette) - - com.bbn.openmap.layer.location - - com.bbn.openmap.layer.rpf - - com.bbn.openmap.layer.shape - The areas package has not been updated for PropertyConsumer - methods yet. However, the AreaHandler was reworked to provide - better access and control over the area definitions. - - * The PlugInLayer and PlugIn were updated to use the - PropertyConsumer interface, and they resolve between themselves - how to handle properties in the different situations where the - PlugInLayer was created and defined the PlugIn, or when the PlugIn - was created and the LayerAddPanel or LayerHandler created the - PlugInLayer for it. - - This makes a difference on how properties are represented in - openmap.properties files saved by the application. - - The WebImagePlugIn abstract class was created, which defines code - shared by the shis and wms plugin pacakges. This code really - affects the PropertyHandling, and the palettes, which take - advantage of the Inspector to allow modification of their - parameters at runtime. There is also a palette option to see what - the query to the web server looks like before it is actually sent. - - * The Layer class has been updated so that it contains the handle - to its palette, instead of having the LayerPane manage - it. Layer.showPalette() and Layer.hidePalette() methods have been - added, and the gui components have been modified as well. - ComponentListeners to the Layer will receive events about the - palette, too, telling them when the palette has been activated or - hidden. - - The Layer is now an ActionListener in order to receive commands to - show and hide its palette. It also can receive commands - (Layer.DisplayPropertiesCmd) to bring up the Inspector, which uses - the PropertyConsumer interface to set the layer's properties. - - The Layer.RedrawCmd has been defined, too, but individual layers - have to code how to specifically react to it. - - The Layer has a new property, autoPalette, which can be used to - tell if the palette for a layer should be turned on by default. - The MapBean has a new method, MapBean.showLayerPalettes(), that - calls Layer.showPalette() on all layers with this property set to - true. MapBean.hideLayerPalettes() turns them all off. - - The OpenMap application now calls this new MapBean method at - startup. The result - you can have certain layer palettes come up - automatically at application startup by setting a layer property. - - The Layer had a findAndInit(Object) method added, which is called - by findAndInit(Iterator) when objects are added to the MapHandler. - See comments on changes to MapHandlerChild on why this is good. - - Property handling in general for layers is improving. With the - addition of the Inspector, you should make sure that all the - PropertyConsumer methods in your layers are implemented, and that - calling setProperties() in your layer reconfigures it if needed. Not - all of the OpenMap layers have been modified yet to act properly in - this way, but many have. - - * The LayerHandler was updated to be able to create PlugIn - directly from the openmap.layers property list. If the - LayerHandler finds a PlugIn, it will automatically create a - PlugInLayer for it and hook it up to the PlugIn. Likewise, the - properties for the PlugIn can be scoped in the properties file - exactly like a layer: - - plugin_markername.class=com.bbn.openmap.plugin.PlugIn - plugin_markername.prettyName=Example - plugin_markername.= - - The former way to add PlugIns, within a PlugInLayer defined in the - openmap.layers list, still works as before. - - * The MapBean has been altered to provide an option to release - Layers that have been removed from it right away. Previously, the - MapBean actually held on to layers that were removed, in case they - were added again without the projection changing. This prevented - the layer from doing unnecessary work just by being toggled on and - off the map, but we got requests to make this an option. - - * Added a method to the MapHandler (BeanContext) called get(String - classname), that looks at its contents and returns an object of - that type. Handy for getting the MapBean, LayerHandler, etc. or - any SoloMapComponent from the MapHandler when it's actually - needed, without maintaining a constant handle to it. Kinda handy - for finding the first one of objects that may have sibling types, - but not so much. - - * MapHandlerChild class has the findAndInit(Object) and - findAndUndo(Object) method added. This lets you override the - findAndInit(Object) method in MapHandlerChild subclasses, and be - able to provide the super class with objects from the MapHandler, - too. Previously, this was not possible because using the iterator - clears it and it couldn't be used in different places. Likewise, - the findAndUndo(Object) method was added for objects being removed - from the MapHandler. - - * The OMCircle was modified to handle rotation! The rotation - angle, in radians, can defined with setRotationAngle(double), with - zero being due West. Positive and negative values can be used. - - The EditableOMGraphic doesn't really handle the rotation angle - completely. You can't modify the angle at all, and the grab - points for the OMCircle actually show up where they would be with - a rotation angle of zero. But, adjusting the position of the grab - points does modify the dimensions of the rotated OMCircle, and you - can move it around. The EditableOMGraphic has commented-out code - to render the points properly, but the MouseEvent locations have - to be translated in order for them to be effective. Releasing - this class as it is was the lessor evil of the alternatives. - - --- This part is important!! --- - - The rotation was accomplished by changing the internal - representation of the OMCircle to be based on java.awt.Shape - objects, and then using AffineTransforms on the shape during - generation. This actually made the render and distance methods - become very generic, not relying on rendertype or what kind of - shape was being rendered. This will be a change that all - OMGraphics will be headed toward very soon. - - Also, the OMCircle has a new Shape[] getShapes() method, which - lets you get the generated shape objects and then use them for - some spatial analysis operations that the java.awt.Shape interface - provides. This is really powerful, and look for this to become - part of the generic OMGraphic API. This method returns an array - of shapes because in some small world situations (really zoomed - out) there are multiple Shape objects that are used to represent - the graphic wrapping around the other side of the earth. - - * Added the GoToMenu, which lets you saved named Projections, - consisting of projection type, center location and scale. You can - add to the list dynamically, and the locations get saved to the - openmap.properties file when a map is saved. You can also add - locations by modifying the properties for the GoToMenu class. - - * Added the Esri plugin package, submitted by Doug Van Auken. - This package includes and EsriLayer and EsriPlugIn, and has - support for reading and writing shape files (shp) and their - supporting files (shx and dbf). The EsriPlugIn was added to take - advantage of the SwingWorker in PlugInLayer, and also has code - that displays the contents of the dbf attribute file in the layer - palette, and will highlight graphics on the map corresponding to - any selections in the table. Likewise, and graphics on the map - selected (in Gestures mouse mode) will hightlight entries in the - table. - - There will be more improvements coming to the package soon. Among - them, support for sorting the table, use of the BinaryBufferedFile - for buffered input, and increased support for distinctive coloring - for individual graphic. - - The package also contains a sample applet and application to - demonstrate how to use the different capabilities of the - components. - - * OMGraphic has the get*Color methods undeprecated. If the Paint - objects used are not Color objects, null is returned. This was - done to save casting trouble. - - * OMText was updated to paint the boundary rectangle correctly. - - * The DistanceMouseMode was modified to be a PropertyConsumer, and - it's parameters can be set in the openmap.properties file for - customized configuration - units, etc. - - * The ControlMenu was modified to let you toggle the ToolPanel on - and off. - - * Bill Huff submitted several memory cleanups in LayerPane and - LayersPanel, to help with GC'ing layers that were removed from the - application. - - * The NavigatePanel was updated to provide methods to set the - coordinates the map goes to when the center button of the rosette - is pressed. By default, it still goes to the starting - coordinates. - - * The OMToolSet has properties that can be used to set which - components are visible on the ToolPanel - the NavigatePanel, - ZoomPanel and ScalePanel are optional, but on by default. - - * The ImageServer now has a main method that lets you pass it an - openmap.properties file, and it kicks out an image file. You need - to have a couple of extra properties defined, like what formatter - to use, in the properties file. - - * DMSLatLonPoint longitude wrapping bug fixed. - - * The status lights of the InformationDelegator where made to be - buttons that bring up the palette of the corresponding layer's - palette. - - * The TerrainLayer's LOSGenerator algorithm was improved via a - submission from Mark Wigmore. - -2001-08-23 Bill Mackiewicz - - * Changed the WebBrowser class to use the File methods for - creating unique and temporary files for browser display. - - * Added the MIFLoader improvements submitted by Scott Nevin from - Agilent, which allows the loader to handle lines. - - * Made the Location showName and showLocation variables be true by - default, so that Locations will show up as expected. The - LayerHandlers have been updated to set these to be false so the - layer settings will work as expected. - - * Updated the raster Location objects to use the horizontal label - buffer, so that the text location gets updated properly when the - entire location changes. - - * Added a progress bar for the DTEDCoverageManager, so progress - can be seen when the DTEDCoverageLayer is bulding the coverage file. - - * Updated the DayNightLayer to be able to have the overlay time set. - - * Took out the supposed XWorkaround from windows and mac - environments. The coordinate clipping changed how the map was - being rendered at some large scales. - - * Added the OMDrawingToolLauncher, which calls the DrawingTool - with setting to create new OMGraphics. It's a Tool, so it can be - enabled by clicking on the pencil icon. - - It uses the BeanContext to find all the EditToolLoaders, which - know how to use EditableOMGraphics to manipulate OMGraphics. It - also finds all DrawingToolRequestors, which are components able to - receive OMGraphics. The OMDrawingToolLauncher lets you choose - which component will receive the finished graphic. - - Added the DrawingToolLayer as an example of how to catch graphics - from the OMDrawingToolLauncher. - - * Added support for creating and editing polygons and polylines. - -2001-07-27 Donald Dietrick - - * Added a workaround for Applets trying to access data that was - being stored in its own jar file. See the - com.bbn.openmap.io.AppletDataNugget class for more information. - - * Fixed a bug in the - com.bbn.openmap.layer.util.LayerUtils.getResourceOrFileOrURL - method, where files were not being handled properly for Windows - file systems. - - * Fixed a bug in the EarthImagePlugIn that was coloring space, in - the Orthographic projection, to the color of the center pixel. - - * Fixed a memory leak in the VPF package, started by the - FeatureClassInfo object. Thanks to Tom Peel for finding this and - reporting it. - -2001-07-12 Bill Mackiewicz - * OpenMap 4.2.1 released. - -2001-07-11 Donald Dietrick - - * Fixed problems with 'make install' with respect to the previous - changes in the share directory structure. - - * Updated the WMSPlugIn with changes submitted by Christof Krug, - with the proper TRANSPARENT request parameters and other changes. - - * Added statements to the PlugIn package that says that the PlugIn - is responsible for generating its OMGraphics. Updated some of the - PlugIns to do that. - - * Modifed MakeToc in the RPF package, and some of the other RPF - components to make MakeToc a little more robust with older files. - Added output statments to indicated when runtime options should be used. - - * Added an openmap.Debug property to the PropertyHandler, which - takes a list of debug tokens and adds them to the Debug - Hashtable. This turns those Debug statements on throughout the - code. It's the same thing as adding -Ddebug.*token* to the start - command, except now you can add an openmap.Debug=*token* in the properties. - -2001-06-19 Bill Mackiewicz - * OpenMap 4.2 released. - -2001-06-18 Donald Dietrick - - * Added the com.bbn.openmap.io package, and moved all the I/O - classes from com.bbn.openmap.util into it. BinaryFile was also - reworked. This is BIG news. BinaryFile now uses a new - InputReader class to access data files, instead of using a - RandomAccessFile object. There are three new InputReaders: - FileInputReader, JarInputReader, and StreamInputReader. A - BinaryFile (and the BinaryBufferedFile) can be used to access a - local file, a file contained in a jar file, or a URL. - - The constructor for a BinaryFile takes a string argument which can - be an absolute path to a file, a relative path to a file, or a - URL. The BinaryFile will use the CLASSPATH to find the file for a - relative path. If the file can be found on the local file system, - a FileInputReader (RandomAccessFile) will be used internally. If - the file is found in a jar file (the path from the internal root - of the jar should be used), the JarInputReader will be used. For - paths starting with 'http:', the StreamInputReader will be used. - - The Shape, RPF, VPF and DTED packages have all been modified to - use the BinaryFile, and this data can now be accessed in a variety - of ways. - - There are some issues: Windows users have to use forward slashes - in their paths (/), even for local files. We're still trying to - figure out how to get applets to use data stored in a separate jar - file in the codebase - but unpackaged data in the codebase works. - Some packages may need to be optimized for better network - performance - they were written for random access, so they may not - be so efficient when it comes to dealing with streams. - - * Added the com.bbn.openmap.plugin package, replacing the - com.bbn.openmap.layer.plugin package. Plugins have been - redefined, and are the easiest way to get data on the map. - Plugins must implement the com.bbn.openmap.plugin.PlugIn - interface, but classes that extend the AbstractPlugIn can provide - data with only one method being written - that method takes a - projection and provides an OMGraphicList. PlugIns are an object - that hook up to a PlugInLayer, or to a server, or any other object - that needs an OMGraphicList. PlugIns can be written - to receive MouseEvents and/or provide a GUI, and they can work - with the BeanContext to contact other objects in the application. - - * Modified the actions of the OMDrawingTool. When edits/creations - are completed on the graphic, clicking on the map brings up a - popup menu with options on what to do with the graphic. - - * Fixed the LLXY projection, which happens to be the SRS EPS 4326 - projection that can be used with a OGC Web Map Server. - - * Updated the LayerUtils.getResourceOrFileOrURL method, so it - doesn't break on Windows file URL pathnames. - - * ProfileGenerator in the TerrainLayer has been updated to display - the profile image in a JFrame, instead of trying to create a - temporary file to send to the browser. You loose the ability to - save the image this way, but it makes the layer compatible with - any environment OpenMap is running in. - - * Int the RPF package: Fixed bug in MakeToc that wouldn't let you - create a A.TOC from multiple RPF directories. Commented out the - code that checks for updated RPF directories. With the inclusion - of the new BinaryFile code, this gets to be really cumbersome. - This will be replaced soon with enchanced RPF directory - management. - - * Fixed a bug in the LocationLayer so that MouseMoved events get - passed through if they aren't consumed. - - * Added methods to DTEDFrame so you can ask it for an image of its - contents without the DTEDCacheHandler in the way. Also, if you - run DTEDFrame on a frame file, it will bring up a window with that - image of the data inside. - - * Created the com.bbn.openmap.proj.Length class, which provides a - class standard for Length units, and coversion methods between a - given unit type and radians. Modified the MouseModes, OMGraphics - and Link package to use the Length class. - - * Modified the PropertyHandler to look for the given properties - file in the CodeBase when running in an Applet environment. This - only happens if it hasn't found any properties elsewhere. - - * Modified the Windows environment to use the XWindowsWorkaround - algorithm for pre-clipping OMGraphics, which gets rid of the - zoom-in delay on vector graphics. - -2001-03-15 Bill Mackiewicz - - * OpenMap 4.1.1 released. - -2001-03-15 Donald Dietrick - - * Fixed memory leak within LayerHandler. Layers were being - referenced by the LayerPane after they were removed from the - LayerHandler, and not being gc'd. - - * Added getName() to the projection classes, which provides their ID. - - * Fixed link in OMPoly java doc. - - * Fixed bug for initial limits of bounding polygon. This was - causing more data than needed to be sent back by the LinkServer. - Thanks to Marc Bucciarelli for finding this and sending the fix. - - * Added the capability in the SimpleHttpImageServer and - ImageServerUtils to be able to handle a background color request - (BGCOLOR) and transparency settings (TRANSPARENCY) in SHIS - requests. These variables are in compliance with the OpenGIS - Consortium Web Mapping Server specification. Another compliance - change is the background color for the SHIS maps is now white - - you have to specify the color you want if you want it to be different. - - * Added methods to objects in the image package that let you set - the colormodel for BufferedImages. - - * Fixed bug in quadtree Rect and Node, where the distance - algorithm wasn't correct. - -2001-02-27 Bill Mackiewicz - - * OpenMap 4.1 released. - -2001-02-26 Donald Dietrick - - * Added a package name to the com.bbn.openmap.examples.crew - example. - - * Modified the PropertyHandler to use the openmap/share directory - by default to look for openmap.properties, and it adds the share - directory to the classpaths the Environment knows about. If you - are using the openmap directory in your classpath, then files and - other resources will be found in the share directory - automatically. If you are using the openmap.jar file, then - resources will be found in the share directory, but files need to - have share/ added in front of their names (for shape files, for - example). - - * Modified the Environment and projection objects to handle the - custom background color a little better. - -2001-02-23 Don Dietrick - - * Added a ToolTip display ability to the InformationDelegator. - The Layer has convience functions to show and hide tool tips on - the map, and the InfoDisplayListener interface had methods added - to accomidate tool tip requests. This was inspired by another - Colin Mummery submission, but slightly modified. - - * Modifed the DrawingTool API. Components are no longer passed in - a request to create or edit an OMGraphic. Instead, a - DrawingToolRequestor interface has been defined, where the - requstor will be notfied when an OMGraphic is completed. The - OMGraphic is provided at this time too, in addition to be provided - at request time. Methods were also added the DrawingTool - interface to supress the GUI from appearing, which will restrict - the modifications of the graphic attributes. - - * Added more improvements to the VPFLayer where, when - VPFLayer.searchByFeatures is set to true, different feature types - can be colored individually. The palette also provides an - interface to change those settings on a feature by feature basis. - - * Added an ETOPOJarLayer from John Watts from nextjet.com. Also - added his improvements to the Mercator and Orthographic projections. - - * Added the MapHandlerChild abstract class, which shows all the - methods and the BeanContextChildSupport object that are needed to - create an object that uses the MapHandler to find other objects. - - * Added Colin Mummery's MapInfo Layer, at com.bbn.openmap.layer.mif. - - * Added the build.xml file, which is a build file for the ant - package available at http://jakarta.apache.org/ant. Ant is - great. It is a cross-platform Java project build tool, and is - easy to install and use. Highly recommended. - -2001-02-06 Donald Dietrick - - * Fixed LocationLayer bug where search direction on the graphic - list was the same as rendering direction, when it should have been - opposite, so that graphics on top are found first. - - * Fixed the Makefile structure to include the drawing tool package. - - * The MouseDelegator had a bug fix installed to prevent a null - pointer exception when setActive was called without a current MouseMode. - - * Updated the VPFLayer and vpf package components with several - improvements. Multiple coverage types can be handled on a single - layer. With the VPFLayer.searchByFeatures property set to true, - the CoverageTable uses the Feature Tables and the Thematic Index - to find features, which avoids a problem exposed by the DNC - database where the tile data doesn't contain feature type - information. With searchByFeatures set to true, different feature - types can be rendered individually. The VPF components were also - tuned for better performance and memory management. Fixed a bug - with the old VPF paradigm where skip arrays in the warehouse were - not the same across VPF paths, and it affected rendering. - Resetting the warehouse skip arrays between paths fixed this. - -2001-01-08 Don Dietrick - - * Added the ProjectionStack, which is a projection listener that - remembers projections to reset to the MapBean when triggered. - Listens to ProjectionStackTriggers (ProjectionStackTool) to tell - it to go back and forth through the stack as applicable. - -2000-12-22 Bill Mackiewicz - - * Modified the ShapeLayer and ESRI graphic objects to use the - DrawingAttributes object for rendering parameters, and added the - DrawingAttributes GUI to the ShapeLayer palette. You can alter - the appearance of the ShapeLayer graphics at runtime. - -2000-12-18 Don Dietrick - - * Added the com.bbn.openmap.layer.terrain layer, which provides a - LOS mask and path elevation tool. This layer will be modified in - future versions of OpenMap. - - * Added a URLDecoder to the SimpleHttpImageServer, so it can - handle HTML encoding of a map request string. - - * Added a method (setAction(boolean)) to the MouseModes, which - lets it know when it has been made active or inactive. - - * Added the PaintListener interface to the com.bbn.openmap.event - package. The PaintListener interface can be used when a object - needs to know when another object has been painted. For instance, - the OMDrawingTool is a PaintListener to the MapBean, so it knows - when to update the edited Graphic in case it's about to be - over-painted. - - * Added the PropertyConsumer interface, which lets the - ComponentFactory know that an object should receive the properties - from the PropertyHandler when it is created. The PropertyConsumer - interface also a method that let an object describe what - properties can be received by it, and a method to get properties - from it to describe the current state of the object. This is in - anticipation of the creation of a editor that will allow for the - runtime creation and configuration of layers and other objects, - and for the creation of openmap.properties files, which will - essential be saving a map for later viewing. - - * Modified the VPFLayer to present the new DrawingAttributes GUI - in its palette. This lets you change the display parameters of - the layer graphics at runtime. - - * Added the com.bbn.openmap.tools.drawing package, which contains - the DrawingTool interface, and the OMDrawingTool implementation of - that interface. The OMDrawingTool is a mechanism that interprets - user gestures to create or modify OMGraphics. - - There are new objects in the com.bbn.openmap.omGraphics package to - help out with this process, centered on the EditableOMGraphic - class. An EditableOMGraphic is a wrapper class that knows how to - interpret MouseEvents to initialize or change the location - parameters of an OMGraphic that it contains. - - The EditableOMGraphic uses GrabPoints that can be moved or set. - When a GrabPoint is moved, the EditableOMGraphic knows how to - translate the GrabPoint location to a OMGraphic parameter. - GrabPoints come in different flavors - HorizontalGrabPoints can - only be moved left-right, VerticalGrabPoints can only be moved - up-down, and OffsetGrabPoints can maintain a constant distance - from other GrabPoints. GrabPoints can be shared between - EditableOMGraphics, in case you want the movement of a GrabPoint - to modify the parameters of more than one OMGraphic. - - The EditableOMGraphic also uses a state machine containing a - series of states that direct actions resulting from MouseEvents. - The com.bbn.openmap.omGraphics.editable contains the new - LineStateMachine and its states. This state machine is used by - the first instantiated class of the abstract EditableOMGraphic, the - EditableOMLine. Other EditableOMGraphic instances are - forthcoming, to manipulate other OMGraphic types. - - The OMDrawingTool uses EditToolLoaders, which provide information - to the DrawingTool on which EditableOMGraphic to use for a class - name, or OMGraphic. The OMDrawingTool has two main methods that a - layer or other component calls - create(classname), or - edit(OMGraphic). Both calls return an OMGraphic that is going to - be manipulated by the DrawingTool. The DrawingTool handles the - presentation of the OMGraphic as it's being modified, and becomes - the active MouseMode. When the DrawingTool is dismissed, the - calling layer or component already has the OMGraphic, so no - further action is required programmatically. - - The DemoLayer contains addition to its palette that demonstrate - the OMDrawingTool as it stands. - - The OMDrawingTool is not a DrawingLayer. A DrawingLayer will be - created for the next release using the OMDrawingTool. - - * Modified the DrawingAttributes object so that it contains a - simple GUI to modify its contents (line color, fill color, select - color, line width, and some line dash selections). Uses the - OMColorChooser, which extends the JColorChooser to allow - transparency adjustment for the color as well. Added the - LineChoice, LineChoiceComboBox and DashedLineComboBox to aid the - DrawingAttributes GUI interface. Also created the - GraphicAttributes object, which extends the DrawingAttributes - object to allow modification of line type and render type of an - OMGraphic. - - * Modifed the com.bbn.openmap.layer.rpf.RpfFrame so that it - contains the subframe decompression code that used to reside in - the RpfFrameCacheHandler. Also added an image viewer to the - RpfFrame that lets you see the image it contains - just run the - class. Removed the RpfLayer pop-up window that notifies the user - that the RPF layer requires the CADRG projection. The InfoLine of - the InformationDelegator displays the information instead. - - * Packaged OpenMap 3.7, which is an OpenMap 3.6.2 package with all - the code that requires jdk 1.2 removed. This package should - compile without modification with jdk 1.1.X. - -2000-10-23 Don Dietrick - - * Added the com.bbn.openmap.image.SimpleHttpImageServer, with the - MapRequestHandler object and a bunch of modifications to the - com.bbn.openmap.layer.util.http package. The - SimpleHttpImageServer responds to GET and POST commands, - requesting an image. The format for the request is the same as - the OpenGIS Web Mapping Server request, but we have additional - parameters to handle some OpenMap-specific parameters. This is a - work in progress, and will grow to become OGC compliant. For now, - it allows you to run a simple web server that kicks back images. - - * Added the PropertyHandler, which is a component responsible for - managing properties which affect the map. When told, it looks for - properties in three places, and overwrites the properties - accordingly - the Resources, the OpenMap config directory (passed - in as an argument), and in the user's home directory. - - The role of the PropertyHandler is important, especially in the - BeanContext world. It can be told to look for a property called - "openmap.components", where the value is a space separated list of - marker names, much like the openmap.properties model for the - layers. The PropertyHandler can take that list and use the - ComponentFactory to create objects (defined by the - markerName.class properties) to add to the Bean Context. If the - object created is a PropertyConsumer, the PropertyHandler will be - used to provide the new object with properties. - - The PropertyHandler also allows for an "openmap.include" property, - which allows you to define a list of marker names for URLs. These - URLs, defined by the markerName.URL property, provide a way to - have a property file read and its values loaded BEFORE the current - openmap.properties file is loaded. This lets the current - properties override anything in the include properties file. - - You'll notice these changes have a profound effect on the ease in - which you can create applications. If a component handles the - Bean Context correctly, and is wiring itself up to other objects - it needs via those methods, then you can add the component in the - properties file, and that change will be reflected within the - application without recompilation. The MouseDelegator looks for - MouseModes, the LayerHandler looks for layers, etc., so that these - additions are pretty simple. The ToolPanel looks for objects - implementing the Tool interface, so that its GUI will be added to - the panel below the MenuBar. The MenuBar looks for MenuBarMenus - to add to itself, so adding/changing menus is pretty easy, too. - - -2000-10-19 Prakash Manghwani - - * OpenMap components now use Bean Containment and Services - protocol, popularly know as BeanContext. The components look for - services and objects that it needs. - - * Modified OpenMap in com.bbn.openmap.app package so that it - demonstrates the ease of creating a reconfigurable Mapping - application from a properties file. - - * Added new context enabled GUI extensible widgets that can be - added to OpenMap Mapping application from properties file thereby - providing the user with a choice of selecting only the GUI widgets - it needs. - -2000-08-24 Bill Mackiewicz - - * OpenMap 3.6.2 released. - -2000-08-23 Don Dietrick - - * Included the upgraded DistanceMouseMode as submitted by Ringo Wathelet. - - * Added the UTMPoint and DMSLatLonPoint, as a contribution from - Colin Mummery. Also included the Ellipsoid class in the - projection package. - - * Added a redraw button to the VPFLayer. - -2000-08-22 Don Dietrick - - * Added the ArgParser class to the utils directory, which is a - very simple attempt at parsing String[] argv arguments and assigning - string values to certain option keywords. - - * Ported the code to create a A.TOC file to java, and it resides - in a class called com.bbn.openmap.layer.rpf.MakeToc. Lets you - create A.TOCs with absolute file paths, which allows you to create - a single A.TOC for multiple RPF directories without merging the - directories. - - * Fixed a couple bugs in the LayerHandler, that didn't update the - LayersPanel properly when a layer was deleted from the available - layers list. Now check for null edit button before trying to add - it to the LayersMenu. - -2000-08-08 Bill Mackiewicz - - * OpenMap 3.6.1 released. - -2000-08-03 Don Dietrick - - * Added the openmap.BackgroundColor property, which lets you set - the color of the "ocean" for the MapBean. If it's not set, then - the ol' default blue is used. - - * Added the DistanceMouseMode, which was a code submission from - Ringo Wathelet from the DSTO in Australia. - - * Fixed the quadtree rectangle test for bounds checking, thanks to - code supplied by Paul Tomblin. Michael Los sent in the changes to - make the quadtree classes serializable. - - * Added a RpfLayer redraw button on the palette, to redraw the - data with a transparancy change. - - * Created an OverviewMapHandler, which manages another MapBean - that listens to a source MapBean to show a map at a different - scale. The OverviewMapHandler lets you set it's layers, the - MouseMode to use (if desired) and a status layer that lets you - draw status graphics on the map. The default status layer simply - draws a box on the map reflecting the coverage of the main map. - - * Changed the appearance of the OpenMap application, with new - icons and buttons to bring up the LayersPanel and OverviewMap. - The mouse modes are now shown with a pop-up menu. - - * Created the com.bbn.openmap.layer.util.DrawingAttributes object, - which can read Properties to create colors and other Java2D - drawing attributes. OMGraphics parameters can be loaded directly - from a DrawingAttributes object. - - * Modified the VPFLayer so that you can specify how you want the - graphics represented. You can specify line, text, select, and - fill colors, as well as line dash patterns and images to use for - area fill patterns. - - * Further modified the inner workings of the RpfLayer. Fixed a - bug with the way cached subframes were allocated for new - subframes, and fixed a couple subtle memory leaks. - - * Overhauled the LayerHandler, making it the central object - managing all Layer objects. The LayersMenu and LayersPanel listen - to the LayerHandler for information about what layers are - available. The visibility of the layer now determines if the - layer is added to the MapBean to be part of the map, and the - LayersManu and LayersPanel components listen to the layer - Component visibility status to list if a layer is part of the map - or not. The Layer now has a slight hack in them that keep track - of ComponentListeners, and follow through to the listeners to let - them know if the layer has been hidden (setVisible(false)). - - * Added the etopo layer package, which was submitted from Joel - A. Rand. It displays the ETOPO world elevation data set, and - provides a really cool view of the world. - -2000-08-01 Bill Euerle - - * Fix a bug that prevented DTEDFrame objects from getting garbage - collected, limited the frame cache size, and fixed an off-by-one - bug that caused an extra row of frames to get loaded. The cache - memory changes were a result of a suggestion from Davis Gillespie, - formerly from General Dynamics. - -2000-07-05 Bill Euerle - - * Removed deprecated OMGraphic methods setGraphicType(int) and - getGraphicType. setGraphicType didn't make much sense, and (obj - instanceof OMBitmap) can be used in place of the second method. - Deprecated the OMGraphic constructors that took a graphictype, and - added new constructors that don't take a graphic type. Although - now unused, the GRAPHICTYPE_* constants in OMGraphic will stay - around for the forseeable future. - -2000-06-01 Don Dietrick - - * Released OpenMap 3.5 - -2000-06-01 Bill Mackiewicz - - * Added thinned VPF area and edge data to the share/ directory as - an alternative to the existing DCW shape files in that directory. - -2000-05-31 Don Dietrick - - * Added a palette option to the RpfLayer to limit the chart - selection to the one currently selected. If you find a chart type - you like, you can engage the lock, and only charts of that - particular type will be displayed. - -2000-05-25 Don Dietrick - - * Removed the csvLocation package. It has been replaced by the - location/csv package. - - * Updated the ImageGenerator code with bug fixes and hardened the - thread model. - - * Updated the ImageServer to have a method that uses the - ProjectionPainter interface. This will help with some of the - threading problems reported with the ImageServer. - - * Added the ProjectionPainter interface. The ProjectionPainter - takes a Projection and a java.awt.Graphics object, and renders the - applicable OMGraphics onto the java.awt.Graphics map. The layers - have been updated to implement this interface, providing a path to - avoid the Swing threading model that the Layers usually use. - - * Added a File->Save As->JPEG option to the MenuPanel. You can - save the current OpenMap image as a JPEG. You can also modify the - MenuPanel to use other ImageFormatters, too. - -2000-05-17 Don Dietrick - - * Modified the arrowhead output statements to be Debug statements, - instead of constant output. - - * Added border fix to OpenMap applet as suggested by Mark - Bucciarelli. - -2000-05-16 Don Dietrick - - * Modified the RpfLayer to not burn cpu cycles on the - RpfCoverageTool if the tool is not in use. Changed the coverage - property so that the tool is active by default, accessable via the - RpfLayer palette. - -2000-04-05 Don Dietrick - - * Added methods in the ImageServer that lets it act as the - ImageReceiver. This lets you ask it for an image directly, - instead of using it to load an ImageReceiver. - -2000-04-01 Don Dietrick - - * Fixed timing bug in ImageGenerator that caused it to hang when - the same projection was provided twice in a row. - -Thu Mar 30 12:38:32 2000 - - * omGraphics/OMText2D.java: added an OMGraphic that supports - rotated text. [Requires the Java2D API.] - -2000-03-30 Don Dietrick - - * Modified the OMGraphicList select() and deselect() method - behaviors - they now call selectAll() and deselectAll(). - - * Added the ArcCalc object to the com.bbn.openmap.omGraphics.util - package, which lets you add arcs to OMLines that are set with XY - coordinates. - - -Fri Mar 24 12:41:58 2000 - - * Deprecate OMGraphic.setGraphicType(int) and - OMGraphic.getGraphicType(). instanceof returns the same type of - information as getGraphicType(), and setGraphicType() doesn't - really change the type (OMPoly, OMCircle, ...) of a graphic, so - its somewhat useless. OMGraphic.graphicType was made private - (previously protected) so it can also go away when set/get go - away. - -2000-03-09 Don Dietrick - - * Modifed the RPF package. Fixed the transparancy problem, the - layer now responds correctly to transparancy changes and - settings. The RpfFrameCacheHandler now tests for colortable - reusability based on the TOC entry number, instead of the map - type, since there is the possibility, with MM map types, that the - chart designator may be inaccurate, especially with MM map charts - that represent several different map chart types. - - * Modified the OMRaster to handle transparancy correctly. - - * Modified the image package, namely the ImageMaster, the - ImageServer, and the ImageGenerator. The ImageMaster and the - ImageServer now reuse layers across ImageServers, when they can. - The ImageServer now reuses the ImageGenerator. In addition, the - ImageServer can have it's layer array modified, and requests can - be made with a bit mask representing which layers should be turned - on/off for the map image. - -2000-02-28 Don Dietrick - - * Released OpenMap 3.4 - -2000-02-25 Donald Dietrick - - * Added the mapIt example, a contribution that's pretty similar to - the ImageMaster class. - - * Added the nexrad/NextradLayer, which is a contribution that - draws the rainfall over an area as stored in a nexrad file. - -2000-02-24 Donald Dietrick - - * OMRasterObject was modified to trim unused pixels from itself - before upscaling itself, instead of relying on the windowing - system to clip the unused image. - - * Added the CSVInfoFile to the com.bbn.openmap.layer.shape - package, which can read in and parse a csv file created from a - shapefile's .dbf file. This CSVInfoFile is used by the areas - package. Also, the shape graphics have been modified to handle - Java 2D drawing attributes, and the SpatialIndex object can be - given an ImageIcon to use for Point graphics. - - * Modified the OMGraphic2D objects to handle fill patterns, using - TexturePaint objects. Also made them keep track of the - modifications they make to the java Graphics object so that non-2D - OMGraphics don't pick up those patterns and strokes by mistake. - - * Created the com.bbn.openmap.layer.location package, which takes - the place of the deprecated csvLocation package, and isolates how - the locations get created. Added the AbstractLocationHandler, - thanks to a suggestion from a user. This package was actually - included in the last OpenMap delivery, unannounced. The location - package has the option of working with the DeclutterMatrix. - - * Modified the DeclutterMatrix to work more accurately with text. - - * Added the com.bbn.openmap.image.BufferedImageHelper and - com.bbn.openmap.image.ImageHelper, which assist in creating and - manipulating image pixels, especially BufferedImages. Moved the - JPEGHelper to the image package from the util package. - - * Took out some funky alignment statements from some of the GUI - tools, making them align correctly. - - * Modified the RpfLayer to not query the RpfFrameProvider for - coverage tool information when the coverage tool was not being - used. Fixed a problem reading in CIB A.TOC files from NIMA. The - directory name lengths are incorrectly listed in the file, and the - files where not being found. Added the indexed image capability - to the RpfFrameProvider interface, which really helps speed in the - com.bbn.openmap.layer.rpf.corba implementation for LANS. - - * Added the capability for the OMGraphicList to be able to - read/write serialized graphics to/from streams. Helps the - CacheLayer. - - * Added the com.bbn.openmap.shape.areas package, which lets you - associate a key and a name from a column in a csv file to the - graphics in a shapefile. The AreaHandler allows you to ask for - all the graphics in the shapefile that have the same key, as well - as define special drawing attributes for specific graphics in the - openmap.properties file (or any other set of properties sent to - it). The AreaShapeLayer uses the AreaHandler, and can respond to - gestures by displaying the defined name of the graphic in the - information line when the mouse is passed over it. The drawing - attributes for the graphics can include using an image to set a - texture for the fill pattern of a graphic - this requires JDK 1.2. - - * Modified the com.bbn.openmap.util.Debug object to be able to - direct output and error statements to various places, including - log files. Modified several components and layers to write their - debug statements to the Debug.output() method, and their error - statements to the Debug.error() method. More changes of this type - to the source code is needed - just didn't get around to changing - it all. - - * Added the openmap/contrib directory, which holds code that - OpenMap components need that we didn't write. Added the Acme - (http://www.acme.com) image encoders for JPEG, GIF and PPM image - formats to this directory. Added the ImageFomatters to the - com.bbn.openmap.image package that use the Acme encoders. - - * Added the ImageServer and ImageMaster, which help create - specific images. The ImageServer manages the ImageGenerator and - the output of the image. The ImageMaster uses ImageServers to - define what you want on a map, the image format you want it in, - and where you want it written when it's done. - -1999-11-03 Bill Mackiewicz - - * Released OpenMap 3.3.5 - -1999-11-01 George Keith - - * Added CacheLayer.java to layers directory. CacheLayer.java will - read and display serialized omGraphics from a file specified in - the properties. - -1999-09-30 Bill Mackiewicz - - * Updated memory management for the RPF package. The subframe - caching works better in a memory-restrictive environment. - - * Added the com.bbn.openmap.image package. Includes the - ImageServer, which uses an openmap.properties file and a - projection to tell an ImageGenerator to create an image. This - image is in the format specified by the ImageFormatter. - - * Added the LayerHandler to the gui package. Layers can be added - and removed on the fly. - -1999-09-07 Donald Dietrick - - * Added the corba package for a RpfFrameProvider. Included is the - Corba RpfFrameProvider client, the Corba RpfFrameProvider server, - and the idl that defines their interface. The Rpf Subframe data is - transferred betweent the client and server in JPEG format. A - CorbaRpfLayer was created to add a palette widget that lets you - control the jpeg image quality, and thus size, during - client-server transfer. The JPEG encoding and Decoding requires - the com.sun.image.codec.jpeg package. Thie new package has only - been tested on jdk1.2 with Visibroker 3.3. The jdk1.2 rt.jar file - had the CORBA classes removed. - - * Overhauled RPF layer with a new separation of subframe caches - and frame caches. Introduced the RpfFrameProvider interface, - which isolates the RPF frame cache. The RpfFrameProvider can be a - local version of the RpfFrameCache handler, or can also be some - sort of server. All parts of the package have changed, and are - incompatable with past interfaces. - -1999-08-25 Bill Mackiewicz - - * Released OpenMap 3.3.3 - -1999-08-17 Bill Euerle - - * Added additional projections to that support views (projections - whose parameters are recalculated when panning the map) - -1999-08-06 Allan Doyle - - * Improved CSVLocationLayer to read values from a - URL. (file:/foo.csv or http://foo.com/foo.csv) - -1999-08-05 Allan Doyle - - * Incorporated BufferedMapBean changes to speed up refresh and - fixed a NullPointerException when it's used in a - JInternalFrame. Thanks to Joe Warzecha at LLNL. - -1999-07-29 Thomas Mitchell - - * Added share/omapplet.html as a sample html file for running - OpenMap as an applet via the Java Plug-in. - - * Added FAQ section 4, OpenMap as an Applet discussing the hows - and whys of running OpenMap as an Applet. - -1999-07-21 Allan Doyle - * Added .shadowX and .shadowY properties to ShapeLayer.java. - This allows you to make snazzy maps with an offset shadow - underneath. - -1999-07-20 Donald Dietrick - - * Added the OMgrid graphic object, which, like the other - OMGraphics, handles Lat/Lon grids, X/Y grids, and Lat/Lon offset - grids. Rendering to the screen depends on objects that implement - the OMGridGenerator interface. A couple of generators have been - added to the source tree - one assumes that the grid contents are - ARGB colors, and a couple others assume that the contents are - elevations. The grid can also hold other graphic objects. - -1999-04-19 Donald Dietrick - - * Fixed a bug in RpfTocHandler that caused the A.TOC file section - to be read incorrectly. - -1999-04-19 - - * Merged patches from various contributors (thanks!) to DTED - and DayNight code. - - * Fixed some problems with ScaleFilterLayer and DateLayer. - - * Added BufferedShapeLayer for nominal speed gain. - -1999-04-05 Donald Dietrick - - * Added the CSVLocationLayer. This layer lets you give it a - comma-separated value file, listing locations with their latitudes - and longitudes on each row. The latitude, longitude and location - name column locations have to be given to the layer via the - openmap.properties file. The layer can be extended to let the - locations display additional detailed information through a - browser when a locaiton is clicked upon. - -1999-04-05 Bill Euerle - - * Modified VPF code to move more of the rendering decisions into - the VPFGraphicWarehouse interface, to allow more flexibility to - choose what to draw, and how to draw it. - - * Modified VPF code to allow multiple paths to data directories. - -1999-04-05 - - * Updated the openmap.properties file. You will want to merge the - options in this file with the openmap.properties in your home - directory. - -1999-03-18 Donald Dietrick - - * Added the RPF layer to the openmap tree. RPF is the National - Imagery and Mapping Agency (NIMA) format for raster products, like - CADRG and CIB. The RPF layer handles these products, displaying - them in the OpenMap CADRG projection. - - * Added the DayNightlayer, which shades the part of the earth that - is experiencing nighttime. There are many parameters that can be - adjusted through the openmap.properties file. See the - DayNightLayer documentation for more information. - - * Modified the Graticule Layer to display latitude and longitude - line labels, draw one and five degree lines when the scale is - large enough to require them, and draws different line types in - different colors. These parameters are adjustable through the - openmap.properties file. See the GraticuleLayer documentation for - more information. - -1999-03-16 - - * Deprecated OMColor. Two constructors incorrectly override the - Java 2 java.awt.Color. OMColor was only useful to support - alpha-valued images under JDK 1.1. You shouldn't use it. Instead - use regular java.awt.Colors or use the Java version-neutral - com.bbn.openmap.util.ColorFactory to create colors. - -1999-02-22 Aaron Culliney - - * Added Java 2D API OMGraphics classes to the - com.bbn.openmap.omGraphics package. - - * The configure script now checks to see if you're using the Java - 2 platform. If so, it sets up the appropriate variables in the - Makefiles. - -1999-02-02 Donald Dietrick - - * Added the com.bbn.openmap.layer.util.LayerUtils class, which - provides a couple convenience functions for parsing properties for - layers. - - * Created the coverage managers for DTED and RPF, which broke the - data coverage generation functions out from the layer, so that a - specialist could be made without duplicating a bunch of code. - -1999-01-27 Donald Dietrick - - * Modified the DTED package to be able to produce indexed images - (images that use colormaps, as opposed to the direct colormodel). - - * Modified the RPF package to do the same thing. - - * Added methods to the OMRasterObject that let you add image - filters to manipulate the images when they are generated. - -1999-01-21 Donald Dietrick - - * Added the Tool object in the gui package, reflecting a change in - how the ToolPanel is used. The ToolPanel was also changed to - accept the addition of tools. The old ToolPanel is now the - OMToolSet, and is added to the ToolPanel in the OpenMap - application. - - * Changed the setWidgets() function in OpenMap.java. setWidgets - was the place to add customized derivations of the - MapBean,ToolPanel, InformationDelegator and MenuPanel to the - OpenMap application. If an object wasn't added, a default was, and - the default widgets were connected with the assumptions they - should be. Now, the interconnections should be made in - setWidgets(). If setWidgets is empty, a minimal functioning - version of OpenMap runs, without a ToolPanel or Gesturing. - -1999-01-20 - - * (OLD) Changed all Swing package names from the old - `com.sun.java.swing' to the new `javax.swing'. This will work - with the Java 2 platform or JDK1.1.X with Swing 1.1 - - * Added SimpleMap examples which show how to use OpenMap for very - simple Map displays. - -1999-01-15 - - * Spruced up the EarthquakeLayer. It has a GUI palette, and now - responds to gestures: click on an earthquake to get more - information. It also fetches its graphics in a SwingWorker thread - so it doesn't block the AWT thread. - -1999-01-12 Don Dietrick - - * Added methods to OMGraphicList to let you select all graphics, - and temporarily render all graphics in the list in their selected - state. Can be used by lists serving as composite OMGraphics. - - * Added a getMapMouseListener() m ethod to the dted layer, since - the Layer default for this method had changed to null. - - * Added the test in LayerPane, LayerMenu, and OpenMap to make the - LayerPanel and Layer Palettes use JFrames (instead of - JInternalFrames) if running as an application. If running as an - applet, do it the old way. - -1999-01-06 Tom Mitchell - - * Added box capability in OMText objects. setShowBounds(boolean) - and getShowBounds() are the accessors for this functionality. - -1999-01-05 Tom Mitchell - - * proj/Projection.java: added 'extends java.io.Serializable' per - patches send by slee@bbn.com. This enables the serialization of - projections for storing map settings. No testing has been done, - so this should go in the category of "untested and unsupported". - -1998-12-22 Tom Mitchell - - * gui/ToolPanel.java: Fixed a bug reported by slee@bbn.com. - Apparently a cut/paste induced problem in removeZoomListener(). - -1998-12-16 Aaron Culliney - - * Changed event/MapMouseListenerAdapter.java to - event/MapMouseAdapter.java to conform to the AWT/Event/Bean naming - convention. - -1998-12-14 Tom Mitchell - - * Converted to Swing 1.1. OpenMap(tm) is now JDK 1.2 ready, but - can still be used with JDK 1.1 by using the Swing 1.1 add-on - package. - -1998-12-11 - - * Added reference to www.opensource.org in the MapBean copyright - message. - - * Reformatted and improved comments in the files of the event/ - subdirectory. - - * Fixed the toplevel configure.in and configure to use full - pathnames for java executables. - - * Added fixes to NavMouseMode for the mouseClicked() trickle-down, - and dateline problems. In JDK1.1, mouseClicked() would get passed - down to components underneath the menu when making a selection. - This would cause the map to recenter in navigation mode. - -1998-12-04 - - * Add a bunch of comments following this one on the work done in - various main classes and APIs over the past several months. - - * Removed support for LatLon ellipses in OMGraphics and Projection - because code was not being used, and was incorrect. Need to - reimplement this functionality later. - - * Slimmed down the Projection.forwardPoly() method. Removed the - `connect' variable. If you want vertices connected, (polygons), - then you must do so yourself. This requirement also transfers to - OMPoly, and is documented in the javadocs. - - * Removed older `specialist' layer code from the OpenMap tree - because it requires CORBA (maybe the Visibroker variant) to build. - Since we can't supply this to developers, it's not part of the - core. - - * Removed dependency on `OverlayTable'. For the OpenMap viewer - application, Layers are now specified along with other variables - in the openmap.properties file. It is easier to develop different - applications using the MapBean without this relic dependency. - - * OMGraphicList now derives from OMGraphic. This means that you - can construct recursive lists and groupings of graphics. - -1998-10-19 - - * added "nsges" parameter to OMGraphics and proj library. Use - this to specify how many segments should be drawn between vertices - of your vector graphic (for circles, and rhumb/greatcircle lines). - -1998-08-03 - - * Added constructors to OMPoly() that allow you to specify that - the float[] rawllpts are in reverse order. - - * Constructors for OMPoly and setLocation() methods that take a - float[] rawllpts value now convert the array IN PLACE to lat/lon - order RADIANS. This is for more efficient use of the projection - code. If you need to access the original float[] values, then you - should send in a copy. This is FAST! - -1998-07-24 - - * changed OMPoly.setLocation() functions to take a units value - since we allow both radians and decimal degrees (default) for - coordinate units. - -1998-07-22 - - * Added an isPlotable() method to Projection.java. This is meant - to be used before projecting and rendering point objects like - bitmaps. In some projections (Orthographic), the forward() will - give you a valid point, but one that isn't on the visible - hemisphere, thus you should first check to see if isPlotable(). - NOTE that you DO NOT need to do this check for non-point objects, - (lines, polys, etc), they get normalized/clipped correctly - already. - - * override getInsets() in the MapBean to return Insets(0,0,0,0). - This fixes a problem of drawing graphics at a +2 x/y offset - because of a Border around the Bean (added by OpenMap.java). Note - that the border still gets drawn with this fix in place. - -1998-07-16 - - * Added a drawBackground() function to the Projection classes. - The BufferedMapBean now delegates background rendering to the - current projection. - - * Removed WhoPanel. The InformationDelegator now controls the - WhoLine screen real estate. Anything that used WhoPanel should - use the InformationDelegator. diff --git a/DeveloperHints.md b/DeveloperHints.md new file mode 100644 index 000000000..55901aa83 --- /dev/null +++ b/DeveloperHints.md @@ -0,0 +1,386 @@ +# Introduction # + +The OpenMap Developer's Guide is an in-depth resource for how OpenMap components work. This page is a summary of the high points, to give you a quick idea of what's what. + + +# Details # + +Consider OMGraphics... + +

+OMGraphics are important, because they are how you represent data as
+objects on a map. OMGraphics come in different flavors -
+OMBitmap, OMCircle, OMLine, OMPoint, OMPoly, OMRaster, OMRect,
+OMText. An OMGraphicList can be used to contain OMGraphics, and
+is also an OMGraphic itself. This allows you to nest
+OMGraphicLists.
+
+

+When considering how to represent your data as OMGraphics, there are a
+couple of things to think about:
+
+

+You can create customized OMGraphics by combining standard OMGraphics
+into a new object that contains an OMGraphicList, or extend
+OMGraphicList to contain the OMGraphics you need, adding methods you
+require. The com.bbn.openmap.layer.location.Location object is
+an example of creating an object to contain OMGraphics, combining a
+generic OMGraphic marking a location, and a OMText object for the
+location label.
+
+

+OMGraphics contain an attribute map that can contain any other objects you need to associate with the OMGraphic. You can access these attributes using the putAttribute(key, value) and getAttribute(key, value) methods. This can be really
+handy to use to store more information about the data you are
+representing with that OMGraphic (web page addresses, additional
+attributes, etc).
+
+

+OMGraphics can be rendered in three ways, which are
+represented by renderType.
+

    +
  • +RENDERTYPE_LATLON means that the object should be placed
    +on the map in its lat/lon location. You should expect the
    +OMGraphic to scale the object as the map scale changes, and the
    +object's location on the screen will change as the map location
    +changes.
  • + +
  • +RENDERTYPE_XY means the object should be placed at a
    +screen pixel location on the map. The OMGraphic does not move or
    +scale as the map projection changes.
  • + +
  • +RENDERTYPE_OFFSET means the object should be placed at
    +some screen pixel location offset from a lat/lon coordinate. The
    +object will move with the map location changes, but will not scale if
    +the map scale changes.
  • +
+ +There are three different line types associated with OMGraphics that
+have lines rendered in lat/lon space. These setting do not
+affect OMGraphics with RENDERTYPE_XY or RENDERTYPE_OFFSET:
+
+
    +
  • +LINETYPE_STRAIGHT means the lines will be straight on
    +the screen between points of the OMGraphic, regardless of the
    +projection type.
  • + +
  • +LINETYPE_GREATCIRCLE means that the lines drawn between
    +points of the OMGraphic will be the shortest geographical distance
    +between those points.
  • + +
  • +LINETYPE_RHUMB means that the line drawn between points
    +of the OMGraphics will be of constant bearing, or going in the same
    +direction.
  • +
+ +Most importantly, there is a paradigm you have to work
+in with OMGraphics. Once an OMGraphic is created, it MUST be
+projected, which means that its representation, in relation to the
+map, needs to be calculated. This is done by taking the
+Projection object that arrives in the ProjectionChanged event, and
+using it on the OMGraphic.generate(Projection) method. If the
+projection changes, the OMGraphics will need to be generated().
+If the position of the OMGraphic has changed, or certain attributes of
+the OMGraphic are changed, the OMGraphics needs to be generated.
+The OMGraphics are smart enough to know when a attribute change
+requires a generation, so go ahead an call it, and the OMGraphic will
+decide to do the work or not. If you try to render an OMGraphic
+that has not been generated, it will not appear on the map.
+After the OMGraphic is generated, the java.awt.Graphics object
+that arrives in the Layer.paint() method can be passed to the
+OMGraphic.render(java.awt.Graphics) method. See the layer section
+below for more information about managing the Projection object for
+use with your OMGraphics.
+
+

+and Layers... + +

+Layers can do anything they want to in order to render
+their data on the map. When a layer is added to a map, it
+becomes a Java Swing component, so its rendering in relation to other
+layers on the map is taken care of automatically.
+
+

+When a layer is added to the MapBean, it automatically
+gets added as a ProjectionListener to the MapBean. That means
+that when the map changes, the layer will receive a ProjectionChanged
+event, letting it know what the new map projection looks like.
+It's then up to the layer to decide what it wants to draw on the
+screen based on that projection, and then call repaint() on itself
+when it is ready to have its paint() method called. The Java
+AWT event thread will then call paint() on the layer at the proper
+time. paint() can also be called automatically by the AWT
+thread, for map window repaints and when another layer asks to be
+repainted. paint() methods should not do more than simply render
+graphics that are currently on the map, in order to take up as little
+time as necessary with that AWT thread.
+
+

+The OMGraphicHandlerLayer is a super-class implementation of Layer that does a lot of work for you. You should extend any layer you write from this class, and simply override the prepare() method to create and return OMGraphics to display on the map. The prepare() method is called whenever the projection changes (pan, zoom, window resize). The current projection can be retrieved in the prepare method by calling getProjection(), and this can be used to call generate(projection) on your OMGraphics before they are returned from this method. You must do this. Look at the com.bbn.openmap.layer.learn package to see best practices of creating layers to do different things. The OMGraphicHandlerLayers in that package are well commented, and each demonstrate a certain aspect of managing and interacting with OMGraphics.
+

+The OMGraphicHandlerLayer automatically launches a separate thread when it calls prepare(), and automatically calls repaint() on itself when prepare() returns. If you want to force a new thread to be created to call prepare() on the layer, call doPrepare().
+
+

+You can also use the OpenMap layers as examples of different ways to
+create and manage OMGraphics. The GraticuleLayer creates its
+OMGraphics internally, while the ShapeLayer reads data from a
+file. The DTED and RpfLayers have image caches. The
+CSVLocationLayer uses a quadtree to store OMGraphics. You can
+also access a spatial database to create OMGraphics. Any
+technique of managing graphics can be used within a layer.
+
+

+The LayerHandler object is used in the OpenMap
+application to manage layers - both those visible on the map, and
+those available for the map. The LayerHandler uses the
+Layer.isVisible() attribute to decide which layers are active on the
+map. It has methods to change the visibility of layers, add
+layers, remove layers, and change their order. It does not have
+a user interface, so it can be used with any application.
+
+

+For the OpenMap application, layers are added or removed
+by modifying the openmap.properties file. The property file
+contains instructions on how to do this. For OpenMap layers,
+their unique properties that can be set to initialize them should be
+listed in the layer's JavaDocs.
+
+

+The Layer.getGUI() method provides a way for a layer to
+create its user interface which can control its attributes. The
+getGUI() method should just return a java.awt.Component, which means
+you can customize it any way you want. The parent Layer class
+returns null by default if you decide not to provide a
+GUI.
+
+

+and Mouse Events.... + +

+MouseEvents can be managed by certain OpenMap
+components, directing them to layers and to OMGraphics.
+MouseModes describe how MouseEvents and MouseMotionEvents are
+interpreted and consumed.
+
+

+The MouseDelegator is the real MouseListener and
+MouseMotionListener on the MapBean. The MouseDelegator manages a
+list of MouseModes, and knows which one is 'active' at any given
+time. The MouseDelegator also asks the active Layers for their
+MapMouseListeners, and adds the ones that are interested in events
+from the active MouseMode as listeners to that mode.
+
+

+When a MouseEvent gets fired from the MapBean, it goes
+through the MouseDelegator to the active MouseMode, where the
+MouseMode starts providing the MouseEvent to its
+MapMouseListeners. Each listener is given the chance to consume
+the event. A MapMouseListener is free to act on an event and not
+consume it, so that it can continue to be passed on to other
+listeners.
+
+

+From the Layer point of view, it has a method where it
+can be asked for its MapMouseListener. The Layer can implement
+the MapMouseListener interface, or it can delegate that responsibility
+to another object, or can just return null if it's not interested in
+receiving events (the Layer default). The MapMouseListener
+provides a String array of all the MouseMode ID strings it is
+interested in receiving events from, and also has its own methods
+that the MouseEvents and MouseMotionEvents arrive in. The
+MapMouseListener can use these events, combined with the
+OMGraphicList, to find out if events have occurred over any OMGraphics,
+and respond if necessary. Remember, if something on the layer
+changes as a result of an event, the layer can call repaint() on
+itself.
+
+

+Once again, the OMGraphicHandlerLayer makes things easier for you" by handling MouseEvents over its OMGraphics. Look at thecom.bbn.openmap.layer.learn.InteractionLayerfor instructions on how to take advantage of this functionality. + +

+PlugIns can also provide and/or implement the
+MapMouseListener interface - the PlugInLayer passes the request
+through to the PlugIn.
+
+

+and the BeanContext, a.k.a. the MapHandler... + +

+Understanding the MapHandler is one of the most important aspects of
+customizing an OpenMap application if you want to make the whole
+process pretty trivial.
+
+

+The MapHandler is a Java BeanContext, which is a big bucket where you
+can add or remove objects. If an object is a
+BeanContextMembershipListener, it will receive events when other
+objects get added to or removed from the BeanContext.
+
+

+The reason that the MapHandler (as opposed to simply using the
+BeanContext) exists is that it is an extended BeanContext that keeps
+track of SoloMapComponents. SoloMapComponent is an interface,
+and can be used to say that there is only supposed to be one instance
+of a component type in the BeanContext at a time. For instance,
+the MapBean is a SoloMapComponent, and there can only be one MapBean
+in a MapHandler at a time. The SoloMapComponentPolicy is an
+object that tells the MapHandler what to do if another MapBean (or
+other duplicate SMC instance) is added to the MapHandler, either
+rejecting the second instance of the MapBean, or replacing the
+previous MapBean.
+
+

+So, a MapHandler can be thought of as a Map, complete with the
+MapBean, Layers, and other management components that are contained
+within.
+
+

+That said, the MapHandler is incredibly useful. It can be used
+by objects that need to get a hold of other objects and
+services. It can be used to add or remove components to the
+application, at runtime, and all the other objects added to the
+MapHandler get notified of the addition/removal automatically.
+
+

+In the OpenMap application, the openmap.properties file has an
+openmap.components property that lists all the components that make up
+the application. To change the components in the application,
+edit this list.
+
+

+If you want your component to be told of the BeanContext, make it a
+BeanContextChild. It will get added to the MapHandler so that
+other components can find it, if it is on the openmap.components
+property list. If you are creating your own components
+programmatically, simply add the BeanContextChild component to the
+MapHandler yourself.
+
+

+The com.bbn.openmap.MapHandlerChild is an abstract class that contains
+all the methods and fields necessary for an object to be a
+BeanContextChild and a BeanContextMembershipListener. If your
+object extends this class, you just have to implement the methods
+findAndInit() which is called whenever an object is added to the
+MapHandler, and childrenRemoved() which is called when objects are
+removed. You can use the Iterator that gets send to these
+methods to find other components that have been added to or removed
+from the application, and adjust your component accordingly.
+Make sure your component is stable if it doesn't find what it needs -
+you shouldn't assume that the other objects will be added in any
+particular order, or even added at all. Also, you should check
+that when objects are removed that the instance of the object is the
+same that is being used by your component before you disconnect from
+it (not just the same class type). As a MapHandlerChild, your
+component can be added to the OpenMap application without recompiling
+any OpenMap source code. You'll notice that the application
+class (com.bbn.openmap.app.OpenMap) is pretty basic, using the
+PropertyHandler to instantiate all the components and add them to the
+MapHandler.
+
+

+and the PropertyConsumer interface... + +

+The PropertyConsumer interface can be implemented by any component
+that wants to be able to configure itself with a java.awt.Properties
+object. It also has methods that let it provide information about the
+properties it can use, and what they mean.
+
+

+In general, Properties are a set of key-value pairs, each defined as
+Java Strings. The com.bbn.openmap.layer.util.LayerUtils class has
+methods that can be used to translate the value Java Strings into Java
+primitives and objects, like ints, floats, booleans, Color, etc.
+
+

+Several PropertyConsumers may have their properties defined in a
+single properties file, which is what happens when the OpenMap
+application uses the openmap.properties file. In order for each
+PropertyConsumer to be able to figure out which properties are
+intended for it, the PropertyConsumer can be given a unique scoping
+property prefix string. In the openmap.properties instructions, this
+scoping string is referred to as a marker name. If the property prefix
+is set in a PropertyConsumer, it should prepend that string to each
+property key, separating them with a period. For example a layer may
+have a property key called lineWidth, which tells it how thick to draw
+its line graphics. If it is given a property prefix of layer1, it
+should check its properties for a 'layer1.lineWidth' property. If the
+layer is given a null prefix (default), then it should look for a
+'lineWidth' property.
+
+

+The methods for the PropertyConsumer are:
+
+

    +
  • +setPropertyPrefix(String prefix) - set the scoping prefix.
  • +
  • +setProperties(Properties props) - provide the properties, with a null prefix.
  • +
  • +setProperties(String prefix, Properties props) - provide the
    +properties with a prefix.
  • +
  • +getProperties(Properties props) - set the current values of the
    +properties in the Properties object provided. If Properties is null,
    +create one to fill. The keys in this Properties object should be
    +scoped with a prefix if one is set.
  • +
  • +getPropertyInfo(Properties props) - set the metadata for the
    +properties in the Properties object. Again, if Properties is null,
    +create one and fill it. The keys in this Properties object should
    +NOT be scoped, and the values for the keys should be a short
    +explaination for what the property means. The PropertyConsumer may
    +also provide a 'key.editor' property here with the value a fully
    +qualified class name of the
    +com.bbn.openmap.util.propertyEditor.PropertyEditor to use to modify
    +the value in a GUI, if needed.
  • +
+ +

+PropertyConsumers can use the
+com.bbn.openmap.util.propertyEditor.Inspector to provide an interface
+to the user to configure it at runtime. It also allows the
+PropertyConsumer to provide its current state for properties files
+being saved for later use.
+
+

+Lastly, when the OpenMap application is creating objects from the
+openmap.components property, the marker name on that list becomes the
+property prefix for components. The ComponentFactory, which creates
+the components on behalf of the PropertyHandler, checks to see if the
+component is a PropertyConsumer, and if so it calls
+setProperties(prefix, properties) on it to let the component configure itself.
+
+

+and hints to help with certain application Design Patterns... + +

+The OpenMap application is really a framework. The application can
+be adjusted and components swapped in and out by modifying the
+openmap.components property to create the components you want. If
+you want to create your own application, it's likely that you can
+still use the OpenMap application for it and still completely
+customize it.
+
+

+You don't have to use Properties - feel free to create any object you want, programmatically, and simply add it to the MapHandler.
+
+

+If you want your layer to be driven by an external object, check out
+the com.bbn.openmap.plugin.graphicLoader package. A GraphicLoader is
+an object that is able to provide OMGraphics to an OMGraphicHandler
+(which can be thought of as a receiver). The graphicLoader package
+contains the AbstractGraphicLoader, an abstract GraphicLoader
+implementation that has a Swing Timer in it to trigger itself to
+deliver OMGraphic updates. You can extend this class to customize how
+and when these updates occur. If you place the GraphicLoaderConnector
+in the MapHandler along with your GraphicLoaders, the
+GraphicLoaderConnector will create a GraphicLoaderPlugIn/PlugInLayer
+combination to listen to each GraphicLoader if the GraphicLoader
+doesn't already have a receiver specified. \ No newline at end of file diff --git a/INSTALL b/INSTALL deleted file mode 100644 index 93ac009fa..000000000 --- a/INSTALL +++ /dev/null @@ -1,57 +0,0 @@ --*- Mode: text-mode -*- -$Source: /cvs/distapps/openmap/INSTALL,v $ -$RCSfile: INSTALL,v $ -$Revision: 1.17 $ -$Date: 2004/04/19 13:54:27 $ -$Author: bmackiew $ - -Prerequisites -============= - - You need to have a Java compiler and VM to build and run the - OpenMap software. You will also need the Apache Ant Java-based - build tool if you'd like to build OpenMap from scratch. Ant has - been included in our distribution, but we have omitted the - documentation package for the sake of space. If you would like - the complete Ant package, you may download it from: - - http://ant.apache.org - - NOTE: From OpenMap 4.0 onwards, OpenMap requires Java 2 to build and run. - If you need to use JDK 1.1, download OpenMap 3.7, the last - JDK 1.1-compatible release. This release is available at the OpenMap - web site, http://www.openmap.org - - From OpenMap 4.6 onwards, OpenMap requires JDK 1.4 or later. - As of OpenMap 5.1.14, jdk 1.6 is required. - -Installation -============ - - With Ant, the basic installation of OpenMap has become much easier. - - If you would like to build OpenMap, you only need to set your - OPENMAP_HOME and JAVA_HOME environment variables to point to your - OpenMap directory and location of your Java installation, and run - "ant". This will work through the different OpenMap directories, - compile OpenMap classes with Ant, and store the resulting jar file - in the lib/ directory of your OpenMap directory. - - To run OpenMap, whether you have compiled your own jar files or used - the precompiled jars that came withe distribution, you need only cd - to the bin/ directory in your OpenMap directory and run the "openmap" - script. - - The above directions cover use of OpenMap on Unix-based systems, such - as Linux, Solaris, and Mac OS X. For Windows-based systems, you'll - want to read the INSTALL.win32 file, found in the same directory as - this INSTALL file. - -Documentation -============= - - The OpenMap API is available at: http://openmap-java.org/api/ - - If you'd like to rebuild it, you can do it from the top-level - OpenMap directory with "ant docs". - diff --git a/INSTALL.win32 b/INSTALL.win32 deleted file mode 100644 index 5f13ee821..000000000 --- a/INSTALL.win32 +++ /dev/null @@ -1,61 +0,0 @@ -$Source: /cvs/distapps/openmap/INSTALL.win32,v $ -$RCSfile: INSTALL.win32,v $ -$Revision: 1.2 $ -$Date: 2004/04/19 13:54:27 $ -$Author: bmackiew $ - -Installation under Windows -========================== - -Quickstart -========== - -Check the prerequisites section of the INSTALL file, then come back -here. - -We have supplied pre-built JAR (Java ARchive) files of OpenMap, but -you will still need to edit the `openmap.bat' file in the bin/ -subdirectory to get OpenMap to run. - - * Load the openmap.bat file in your favorite editor. - - * Change the path to the Java VM to match your - local configuration. - - * Change the path to OpenMap to match your configuration. - - * Run the batch file. - -Compilation -=========== - -You may want to build OpenMap from the source code yourself. OpenMap includes -Ant, the Java-based build tool from Apache, available at -http://ant.apache.org - -If you'd like to build OpenMap using Ant, you'll need to: - - 1. Edit the ANT_ENV.BAT batch file in the OpenMap distribution: - - Set your OPENMAP_HOME variable to point to your - OpenMap directory. - - Set your JAVA_HOME variable to point to your Java - distribution. - - 2. Open an MS-DOS window and right-click on it to access the - properties. Set Memory -> Initial Environment to a value of at - least 768 or you'll see "Out of environment space" errors when you - run Ant. - - 3. Close and re-open the MS-DOS window to gain the benefit of the - updated initial environment settings. - - 4. Run the ANT_ENV.bat file to set your path and environment variables - correctly. - - 5. Run "ant" from the top level of the OpenMap distribution to - recompile the jar files. Run "ant clean" to clean out the - directories, analogous to "make clean". - -Another possibility for recompiling under Windows is using the Cygwin toolkit, -available from http://www.cygwin.com. This provides you with a Unix-like -shell, but isn't as simple to use as Ant. diff --git a/OpenMap.md b/OpenMap.md new file mode 100644 index 000000000..5fe9d1448 --- /dev/null +++ b/OpenMap.md @@ -0,0 +1,15 @@ +# What is OpenMap? # + +OpenMap is a Java Beans based toolkit for building applications and applets needing geographic information. Using OpenMap components, you can access data from legacy applications, in-place, in a distributed setting. At its core, OpenMap is a set of Swing components that understand geographic coordinates. These components help you show map data, and help you handle user input events to manipulate that data. + +# What are the license terms for using OpenMap? # + +Take a look at the OpenMapLicense. We want you to be able to do pretty much anything with it as long as we get credit for our work and as long as you offer your changes to us so we can possibly add them to the standard version we distribute. + +# OpenMap is a trademark # + +OpenMap is a trademark of BBN Technologies. + +# Please help out! # + +There's much room for improvement of the OpenMap sources. We are interested in any changes you make to the core source, or layers you develop, or other derivative works. \ No newline at end of file diff --git a/OpenMapApplications.md b/OpenMapApplications.md new file mode 100644 index 000000000..0d9d48b47 --- /dev/null +++ b/OpenMapApplications.md @@ -0,0 +1,53 @@ +# Introduction # + +The OpenMap package includes applications that demonstrate the capabilities of the toolkit. There are many layer examples that also demonstrate how to create custom layers for displaying your own data. + + +# Applications # + +The application classes in OpenMap are in the {{com.bbn.openmap.app}}} package. + +The `com.bbn.openmap.app.Main` class was introduced in OpenMap 5.0. It uses the openmap.properties file for configuration, with the `main.components` defining the application components. The `openmap.layers` property defines the layers used in the application. This is the application that gets started by the scripts in the bin directory. You can start this application at the command line by typing: + +`java -classpath ./lib/openmap.jar:./share com.bbn.openmap.app.Main -properties ./openmap.properties` + +The `com.bbn.openmap.app.OpenMap` class is the legacy application that uses the `openmap.properties` file to define the components in the application. The `openmap.components` property in `openmap.properties` lists the components that will be added to the application, and the `openmap.layers` property defines the layers in the application. + +`java -classpath ./lib/openmap.jar:./share com.bbn.openmap.app.OpenMap -properties ./openmap.properties` + +Both applications are the best way to start getting to know OpenMap, and the best starting point for your own application. You can add or remove components in the application using the {{openmap.properties}}} file, which contains instructions for how to modify the various properties within it. + +If you want to a deeper understanding on how the OpenMap application framework should be used, the `com.bbn.openmap.app.example` package contains `SimpleMap` and `SimpleMap2`. Both examples are heavily commented, and provide examples of how to programmatically configure OpenMap mapping components. + +`java -classpath ./lib/openmap.jar:./share com.bbn.openmap.app.example.SimpleMap` + +`java -classpath ./lib/openmap.jar:./share com.bbn.openmap.app.example.SimpleMap2` + +# Layers # + +OpenMap includes many layers that work with standard map data formats. These layers are under the `com.bbn.openmap.layers` package. The `openmap.properties` file contains examples of how to configure properties for some of them, and the javadocs for a layer class should contain property settings and instructions for configuring the layer. + +If you want to learn to write your own layer, look at the layers in the `com.bbn.openmap.layers.learn` package: + * `BasicLayer` shows how to make a layer where the data doesn't change depending on time or map projection. A good first layer. + * `ProjectionResponseLayer` shows how to make a layer that responds to the map projection to display map features for the current view. + * `InteractionLayer` shows how to make the layer react to user input. + * `SimpleAnimationLayer` shows how to move features around on a map. + +Also, the `com.bbn.openmap.layer.DemoLayer` is an excellent tool, demonstrating almost anything you may want to do with a layer. It is heavily commented, and studying that layer will reveal how to respond to user input, use the drawing tool to edit map features, create a Layer gui to change properties of the layer, use the MIL-STD-2525 symbology components, and display various OMGraphic map features with labels. This layer is also part of the standard `OpenMap` and `Main` application configuration, so you can see that layer in action by running those applications. + +# Servlets # + +OpenMap can be used to power servlets (using glassfish or tomcat) that provide map data to other applications. From the src directory: + + * `wmsservlet` provides a servlet that can be used to provide WMS images. In addition to whole map images, the wmsservlet can respond to request to create TMS (Tile Map Specification) sized images on the fly. + * `maptileservlet` provides a servlet that can handle requests for TMS (Tile Map Specification) layers, such as Leaflet, OpenLayers and Google Maps. These tile map sets are assumed to be pre-created using mapnik, TileMill, GDAL, or OpenMap's MapTileMaker. The OpenMap `MapTileLayer` can talk to this servlet (and any other TMS server). Also, when the `maptileservlet` is loaded with `MapTileSet` tiles, contacting the servlet at the top-level will bring up a Leaflet map allowing you to look at the tile sets. + +The `MapTileMaker` is a class that creates tile sets. It uses a properties file to define layers and lets zoom levels be defined to dictate which layers are active for different tile scales. The `MapTileMaker` has recently been updated to implement `EmptyTileHandler`, which means it can now be used by the `maptileservlet` to create tiles on the fly, and cache them for later use. + +The `vpfservlet` doesn't serve VPF data, it provides a way to explore VPF datasets. + +# Other # + +You can use OpenMap map components in any java application that supports Swing components (so mobile SDKs generally don't work with OpenMap). You can embed OpenMap into an existing application. Look at the `BasicMapPanel` and `OverlayMapPanel` as the main component to embed into another application. + +OpenMap runs as an applet. The share directory contains an omapplet.html page to get started. There is a jnlp file to run OpenMap as a Java WebStart application. \ No newline at end of file diff --git a/LICENSE b/OpenMapLicense.md similarity index 52% rename from LICENSE rename to OpenMapLicense.md index ef638d5cc..53a146ae9 100644 --- a/LICENSE +++ b/OpenMapLicense.md @@ -1,147 +1,153 @@ - OpenMap Software License Agreement - ---------------------------------- - -This Agreement sets forth the terms and conditions under which -the software known as OpenMap(tm) will be licensed by BBN -Technologies ("BBN") to you ("Licensee"), and by which Derivative -Works (as hereafter defined) of OpenMap will be licensed by you to BBN. - -Definitions: - - "Derivative Work(s)" shall mean any revision, enhancement, - modification, translation, abridgement, condensation or - expansion created by Licensee or BBN that is based upon the - Software or a portion thereof that would be a copyright - infringement if prepared without the authorization of the - copyright owners of the Software or portion thereof. - - "OpenMap" shall mean a programmer's toolkit for building map - based applications as originally created by BBN, and any - Derivative Works thereof as created by either BBN or Licensee, - but shall include only those Derivative Works BBN has approved - for inclusion into, and BBN has integrated into OpenMap. - - "Standard Version" shall mean OpenMap, as originally created by - BBN. - - "Software" shall mean OpenMap and the Derivative Works created - by Licensee and the collection of files distributed by the - Licensee with OpenMap, and the collection of files created - through textual modifications. - - "Copyright Holder" is whoever is named in the copyright or - copyrights for the Derivative Works. - - "Licensee" is you, only if you agree to be bound by the terms - and conditions set forth in this Agreement. - - "Reasonable copying fee" is whatever you can justify on the - basis of media cost, duplication charges, time of people - involved. - - "Freely Available" means that no fee is charged for the item - itself, though there may be fees involved in handling the item. - It also means that recipients of the item may redistribute it - under the same conditions that they received it. - -1. BBN maintains all rights, title and interest in and to -OpenMap, including all applicable copyrights, trade secrets, -patents and other intellectual rights therein. Licensee hereby -grants to BBN all right, title and interest into the compilation -of OpenMap. Licensee shall own all rights, title and interest -into the Derivative Works created by Licensee (subject to the -compilation ownership by BBN). - -2. BBN hereby grants to Licensee a royalty free, worldwide right -and license to use, copy, distribute and make Derivative Works of -OpenMap, and sublicensing rights of any of the foregoing in -accordance with the terms and conditions of this Agreement, -provided that you duplicate all of the original copyright notices -and associated disclaimers. - -3. Licensee hereby grants to BBN a royalty free, worldwide right -and license to use, copy, distribute and make Derivative Works of -Derivative Works created by Licensee and sublicensing rights of -any of the foregoing. - -4. Licensee's right to create Derivative Works in the Software is -subject to Licensee agreement to insert a prominent notice in -each changed file stating how and when you changed that file, and -provided that you do at least ONE of the following: - - a) place your modifications in the Public Domain or otherwise - make them Freely Available, such as by posting said - modifications to Usenet or an equivalent medium, or - placing the modifications on a major archive site and by - providing your modifications to the Copyright Holder. - - b) use the modified Package only within your corporation or - organization. - - c) rename any non-standard executables so the names do not - conflict with standard executables, which must also be - provided, and provide a separate manual page for each - non-standard executable that clearly documents how it - differs from OpenMap. - - d) make other distribution arrangements with the Copyright - Holder. - -5. Licensee may distribute the programs of this Software in -object code or executable form, provided that you do at least ONE -of the following: - - a) distribute an OpenMap version of the executables and - library files, together with instructions (in the manual - page or equivalent) on where to get OpenMap. - - b) accompany the distribution with the machine-readable - source code with your modifications. - - c) accompany any non-standard executables with their - corresponding OpenMap executables, giving the non-standard - executables non-standard names, and clearly documenting - the differences in manual pages (or equivalent), together - with instructions on where to get OpenMap. - - d) make other distribution arrangements with the Copyright - Holder. - -6. You may charge a reasonable copying fee for any distribution -of this Software. You may charge any fee you choose for support -of this Software. You may not charge a fee for this Software -itself. However, you may distribute this Software in aggregate -with other (possibly commercial) programs as part of a larger -(possibly commercial) software distribution provided that you do -not advertise this Software as a product of your own. - -7. The data and images supplied as input to or produced as output -from the Software do not automatically fall under the copyright -of this Software, but belong to whomever generated them, and may -be sold commercially, and may be aggregated with this Software. - -8. BBN makes no representation about the suitability of OpenMap -for any purposes. BBN shall have no duty or requirement to -include any Derivative Works into OpenMap. - -9. Each party hereto represents and warrants that they have the -full unrestricted right to grant all rights and licenses granted -to the other party herein. - -10. THIS PACKAGE IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY -KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) -ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, AND -WITHOUT ANY WARRANTIES AS TO NONINFRINGEMENT. - -11. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER RESULTING -FROM LOSS OF USE OF DATA OR PROFITS, WHETHER IN AN ACTION OF -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS CONDUCT, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS PACKAGE. - -12. Without limitation of the foregoing, You agree to commit no -act which, directly or indirectly, would violate any U.S. law, -regulation, or treaty, or any other international treaty or -agreement to which the United States adheres or with which the -United States complies, relating to the export or re-export of -any commodities, software, or technical data. +# OpenMap Software License Agreement # + +This Agreement sets forth the terms and conditions under which +the software known as OpenMap(tm) will be licensed by BBN +Technologies ("BBN") to you ("Licensee"), and by which Derivative +Works (as hereafter defined) of OpenMap will be licensed by you to BBN. + +## Definitions ## + +> "Derivative Work(s)" shall mean any revision, enhancement, +> modification, translation, abridgement, condensation or +> expansion created by Licensee or BBN that is based upon the +> Software or a portion thereof that would be a copyright +> infringement if prepared without the authorization of the +> copyright owners of the Software or portion thereof. + +> "OpenMap" shall mean a programmer's toolkit for building map +> based applications as originally created by BBN, and any +> Derivative Works thereof as created by either BBN or Licensee, +> but shall include only those Derivative Works BBN has approved +> for inclusion into, and BBN has integrated into OpenMap. + +> "Standard Version" shall mean OpenMap, as originally created by +> BBN. + +> "Software" shall mean OpenMap and the Derivative Works created +> by Licensee and the collection of files distributed by the +> Licensee with OpenMap, and the collection of files created +> through textual modifications. + +> "Copyright Holder" is whoever is named in the copyright or +> copyrights for the Derivative Works. + +> "Licensee" is you, only if you agree to be bound by the terms +> and conditions set forth in this Agreement. + +> "Reasonable copying fee" is whatever you can justify on the +> basis of media cost, duplication charges, time of people +> involved. + +> "Freely Available" means that no fee is charged for the item +> itself, though there may be fees involved in handling the item. +> It also means that recipients of the item may redistribute it +> under the same conditions that they received it. + +1. BBN maintains all rights, title and interest in and to +OpenMap, including all applicable copyrights, trade secrets, +patents and other intellectual rights therein. Licensee hereby +grants to BBN all right, title and interest into the compilation +of OpenMap. Licensee shall own all rights, title and interest +into the Derivative Works created by Licensee (subject to the +compilation ownership by BBN). + +2. BBN hereby grants to Licensee a royalty free, worldwide right +and license to use, copy, distribute and make Derivative Works of +OpenMap, and sublicensing rights of any of the foregoing in +accordance with the terms and conditions of this Agreement, +provided that you duplicate all of the original copyright notices +and associated disclaimers. + +3. Licensee hereby grants to BBN a royalty free, worldwide right +and license to use, copy, distribute and make Derivative Works of +Derivative Works created by Licensee and sublicensing rights of +any of the foregoing. + +4. Licensee's right to create Derivative Works in the Software is +subject to Licensee agreement to insert a prominent notice in +each changed file stating how and when you changed that file, and +provided that you do at least ONE of the following: + +> a) place your modifications in the Public Domain or otherwise +> > make them Freely Available, such as by posting said +> > modifications to Usenet or an equivalent medium, or +> > placing the modifications on a major archive site and by +> > providing your modifications to the Copyright Holder. + + +> b) use the modified Package only within your corporation or +> > organization. + + +> c) rename any non-standard executables so the names do not +> > conflict with standard executables, which must also be +> > provided, and provide a separate manual page for each +> > non-standard executable that clearly documents how it +> > differs from OpenMap. + + +> d) make other distribution arrangements with the Copyright +> > Holder. + +5. Licensee may distribute the programs of this Software in +object code or executable form, provided that you do at least ONE +of the following: + + +> a) distribute an OpenMap version of the executables and +> > library files, together with instructions (in the manual +> > page or equivalent) on where to get OpenMap. + + +> b) accompany the distribution with the machine-readable +> > source code with your modifications. + + +> c) accompany any non-standard executables with their +> > corresponding OpenMap executables, giving the non-standard +> > executables non-standard names, and clearly documenting +> > the differences in manual pages (or equivalent), together +> > with instructions on where to get OpenMap. + + +> d) make other distribution arrangements with the Copyright +> > Holder. + +6. You may charge a reasonable copying fee for any distribution +of this Software. You may charge any fee you choose for support +of this Software. You may not charge a fee for this Software +itself. However, you may distribute this Software in aggregate +with other (possibly commercial) programs as part of a larger +(possibly commercial) software distribution provided that you do +not advertise this Software as a product of your own. + +7. The data and images supplied as input to or produced as output +from the Software do not automatically fall under the copyright +of this Software, but belong to whomever generated them, and may +be sold commercially, and may be aggregated with this Software. + +8. BBN makes no representation about the suitability of OpenMap +for any purposes. BBN shall have no duty or requirement to +include any Derivative Works into OpenMap. + +9. Each party hereto represents and warrants that they have the +full unrestricted right to grant all rights and licenses granted +to the other party herein. + +10. THIS PACKAGE IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY +KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT LIMITED TO) +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, AND +WITHOUT ANY WARRANTIES AS TO NONINFRINGEMENT. + +11. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER RESULTING +FROM LOSS OF USE OF DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS CONDUCT, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS PACKAGE. + +12. Without limitation of the foregoing, You agree to commit no +act which, directly or indirectly, would violate any U.S. law, +regulation, or treaty, or any other international treaty or +agreement to which the United States adheres or with which the +United States complies, relating to the export or re-export of +any commodities, software, or technical data. \ No newline at end of file diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 000000000..d8c8162d0 --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,13 @@ +BBN Technologies' OpenMap TM package is an Open Source JavaBeans TM based programmer's toolkit. Using OpenMap, you can quickly build applications and applets that access data from legacy databases and applications. OpenMap provides the means to allow users to see and manipulate geospatial information. OpenMap is under constant development - the latest version is **OpenMap 5.1.11, released July 20, 2015**. Note that with v5.0, you need to be using Java 5 or later. A complete list of updates is maintained in the [CHANGELOG](http://code.google.com/p/openmap/source/browse/CHANGELOG) file in the package. + +You can [download](https://drive.google.com/folderview?id=0B-Y9CwNIsUOHenpDWGhBSk42b1E&usp=sharing) a copy for free, use it, and make changes to it. Be sure to read the [license](OpenMapLicense.md) before you do. + +Follow [OpenMap on Twitter](http://twitter.com/openmap) for announcements about new releases and updates to the code base. If you need help, you can post questions on the [Google OpenMap-Users Group](https://groups.google.com/forum/#!forum/openmap-users) forum. For a historical perspective, the [old BBN openmap-users mailing list archive](http://openmap.bbn.com/mailArchives/openmap-users/thread.html) is still available. + +Google Code has removed the ability to provide downloadable compressed release files in the Download tab (as of version 5.0.3). The latest download packages are available via the External Links -> [Downloads](https://drive.google.com/folderview?id=0B-Y9CwNIsUOHenpDWGhBSk42b1E&usp=sharing) link to the left. The current Java API documents can be found [here](http://dietricks.com/openmap/api) or they can be [downloaded](https://drive.google.com/folderview?id=0B-Y9CwNIsUOHenpDWGhBSk42b1E&usp=sharing) as a zip file. + +Developer documentation can be found on the [Wiki page](http://code.google.com/p/openmap/w/list) and in the [Downloads section](http://code.google.com/p/openmap/downloads/list). + +Since OpenMap is open source, we welcome additions and changes from the user community. We've incorporated a number of contributions, with plenty of submissions available to the user community separate from the official distribution. + +BBN Technologies is an innovative research and development company, providing both advanced research and custom, research-based solutions for our customers. We have over 50 years of experience in technological innovation, and provide expertise in a number of technology focus areas, including acoustic technologies, agent-based systems, logistics, planning, and decision support, and speech and language processing, among others. For a complete list of our offerings, be sure to visit our corporate site. \ No newline at end of file diff --git a/README b/README deleted file mode 100644 index d4508e7ae..000000000 --- a/README +++ /dev/null @@ -1,185 +0,0 @@ -$Source: /cvs/distapps/openmap/README,v $ -$RCSfile: README,v $ -$Revision: 1.11 $ -$Date: 2002/11/06 19:11:02 $ -$Author: bmackiew $ - - -OpenMap(tm) - -What is it? ------------ -OpenMap is a Java Beans based toolkit for building applications and -applets needing geographic information. Using OpenMap components, you -can access data from legacy applications, in-place, in a distributed -setting. At its core, OpenMap is a set of Swing components that -understand geographic coordinates. These components help you show map -data, and help you handle user input events to manipulate that data. - - -What are the license terms for using OpenMap? ---------------------------------------------- -Take a look at the file called LICENSE in the distribution. We want -you to be able to do pretty much anything with it as long as we get -credit for our work and as long as you offer your changes to us so we -can possibly add them to the standard version we distribute. - - -OpenMap is a trademark ----------------------- -OpenMap is a trademark of BBN Corporation. Just so you're not -confused, BBN Corporation is the legal entity, but we're actually part -of Verizon Communications. Technically, we do business as "BBN Technologies, -a part of Verizon". - -Downloads and home page ------------------------ -The homepage is at http://openmap-java.org/ - -Downloads of the current distribution are available from the homepage. - -Where to start? ------------------------- - -- OpenMap Viewer - -The com.bbn.openmap.app.Main.java example is the default "face" of -OpenMap. While it looks like a complex example to start with, it's -really a simple framework that uses the MapHandler to add and connect -the OpenMap components. See the old viewer User's Guide -(http://openmap.bbn.com/doc/user-guide.html) for more information. You -can check out the com.bbn.openmap.app.OpenMap application class for the older -version of the main example class. - -You can write your own components that can display your data in the -OpenMap Viewer. Once you've written the layer or plugin, all you need -to do is to add a reference to it in your openmap.properties file. -The OpenMap Viewer reads this file to get configuration information. -The properties file has instructions for adding layers and plugins to -the application. Check out the layers in com.bbn.openmap.layer.learn for -examples and explanations on how to create your own layers. - -Likewise, you can change the look of the application by modifying the -openmap.components property in the openmap.properties file. There are -instructions in the properties file for modifying this property, but -the main point is that changing the application does not require a -code change. The components are defined in the openmap.properties -file and are connected at runtime. - -If you want to get more into how the components interact with each -other, you should take a look at the example applications in the -com.bbn.openmap.app.example package, SimpleMap and SimpleMap2 - -- SimpleMap - -This class is a very simple example that shows how you use the MapBean and a -layer which shows a map of the world. This -com/bbn/openmap/app/example/SimpleMap.java uses the MapBean to -create a static political map in a window with these steps: - - 1. Create a JFrame window. - 2. Create a MapBean. - 3. Create the Political boundary Layer - 4. Add the Layer to the MapBean. - 5. Add the MapBean to the ContentPane of the JFrame. - 6. Show the JFrame window. - -- SimpleMap2 - -This com/bbn/openmap/app/example/SimpleMap2.java example is a -little more complicated than the previous one, but is more usable. It -shows the same political layer along with a background graticule layer -(com/bbn/openmap/layer/GraticuleLayer.java) and a simple foreground -layer (com/bbn/openmap/layer/learn/BasicLayer.java) which shows -hypothetical data features. - -The openmap.properties file ------------------------- - -The OpenMap application is configured at runtime by the contents of -the openmap.properties file. The openmap.properties file is located in -the openmap directory, and has guidance inside it on how to modify -various properties to change a) what components are part of the -OpenMap application, including what layers are available, b) how those -components are configured, and c) the initial map projection used by -the application. - -When the OpenMap application starts up, the PropertyHandler object -checks the CLASSPATH to find an openmap.properties file, and then -checks the user's home directory for one. If an openmap.properties -file was found in the home directory, all of its properties get added -to any properties created previously from a CLASSPATH -openmap.properties file. If there are duplicate properties, the last -version read (from the home directory) will be the version used. - -By default, there is an openmap.properties file located at the top -level of the openmap.jar file. When the jar file is created, the -openmap.properties file located in the top level openmap directory -gets copied to the classes/openmap directory, and then included into -the openmap.jar file. - -If you make modifications to the openmap.properties file, those -changes will not be reflected in the application unless: - -1. The top level openmap directory is included in the CLASSPATH of the - OpenMap application. This can be done by modifying the openmap - startup scripts located in the bin directory. - -2. The openmap.properties file is copied into your home directory. For - unix users, this directory is usually /home/. For Mac OS - X users, this directory is /Users/. For Windows users, - this directory is D:\Documents and Settings\, where D: is - the disk windows is installed on. If you are not sure where your - home directory is, you can compile this code into a HomeDir.java - file and run it: - - public class HomeDir { - public static void main(String[] argv) { - System.out.println("User home directory is " + - System.getProperties().getProperty("user.home")); - } - } - -3. You put the openmap.properties file in the top level of the - openmap.jar file, either by a) recompiling the openmap code, or b) - unpacking the jar file, replacing the openmap.properties file, and - repacking the jar file. - -The second option is usually the easiest, but your needs may require -one of the other options. - -External Dependencies ---------------------- - -The source code has been broken out into separate directories for code -that depends on other packages. - -- src/openmap and src/ext: This code should compile without any special packages. -- src/corba: The missing classes can be generated by building with ant. The idl files - are used to create the generated class files. -- src/j3d: This code will compile if the Java 3D package is installed. -- src/svg: This code will compile if Batik (v 1.7) is installed. - -If you check OpenMap out from svn (instructions on the download page on the website), these -external packages are included. - -Bugs and Problems ---------------------- -If you need some help, contact the mailing list at: - - https://groups.google.com/forum/#!forum/openmap-users - -The old mailing list at BBN is still available here: - - http://openmap.bbn.com/mailArchives/openmap-users/ - -You can also submit issues at the OpenMap home on github at: - - https://github.com/OpenMap-java/openmap - -Please help out! ----------------- -There's much room for improvement of the OpenMap sources. We are -interested in any changes you make to the core source, or layers you -develop, or other derivative works. - diff --git a/UsingMapTiles.md b/UsingMapTiles.md new file mode 100644 index 000000000..4d39cba1c --- /dev/null +++ b/UsingMapTiles.md @@ -0,0 +1,87 @@ +# Introduction # + +Map tiles are images stored in a directory structure, usually by zoom level, x coordinate and then named by their y coordinate (z/x/y.png). + +The _com.bbn.openmap.layer.imageTile.MapTileLayer_ can be used to display map tiles, stored locally on your computer or downloaded from a server. There are many options available for the MapTileLayer, and they can be set in the _openmap.properties_ file, or in a _tiles.omp_ file stored in the root directory of a tile set. + +# Configuration Options # + +The most basic configuration of a MapTileLayer simply define a **rootDir** property defining where the tiles are located and how they should be referenced. + +``` +class=com.bbn.openmap.layer.imageTile.MapTileLayer +prettyName=Map Tiles +rootDir=/data/tiles/MapTileSet1/{z}/{x}/{y}.png +``` + +Other options: + +**rootDir**: The rootDir can be a URL, absolute or relative path to the tile files. It can also be a jar file. If you use a jar file to hold the tiles, you should use a tiles.omp inside the jar to hold other properties, like another rootDir property for the relative path to the files within the jar. The **rootDir** can also point to a TileMill mbtiles file. If it does, you'll need to set the **tileFactory** to use the _com.bbn.openmap.dataAccess.mapTile.TileMillMapTileFactory_. You'll also need to include the sqlitejdbc jar file in the classpath to use the TileMillMapTileFactory. + +**localCacheRootDir**: If the **rootDir** is defined as a URL, you can also use a **localCacheRootDir** property to define local storage for the tiles. If the layer will check the **localCacheRootDir** first for tiles, and then move to the **rootDir** location if needed. This will drastically reduce the server load. + +**tileFactory**: The MapTileLayer uses a MapTileFactory to handle the fetching of tiles. For URLs and file paths, you generally don't have to set this, the layer will figure out which one to use. You can check out the _com.bbn.openmap.dataAccess.mapTile_ package for various MapTileFactory implementations, and look at their javadocs for more information about specific properties for those factory objects. + +**cacheSize**: the number of tiles to hold in memory for the layer, defaults to 50. + +**attribution**: if you aren't using your own tiles, this property can be used to display the tiles' owner's name in the lower left corner of the map. + +**mapTileTransform**: The default MapTileCoordinateTransform is the _com.bbn.openmap.dataAccess.mapTile.OSMMapTileTCoordinateTransform_ class, and that defines the tile coordinates from the upper left corner of the Mercator projection, with zoom levels starting at 0 and zooming into higher levels. If you are working with tiles defined differently, you can specify a different class to use for those tiles. For instance, if you use GDAL to create image tiles sets you may need to use the _com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform_. + +**tileImagePreparer**: defines a class that can be used to process the images before display. The _com.bbn.openmap.dataAccess.mapTile.GreyscaleImagePreparer_ will convert all tiles to greyscale. + +**emptyTileHandler**: defines a class that determines what to do when a tile is missing. The _com.bbn.openmap.dataAccess.mapTile.ShpFileEmptyTileHandler uses a shape file to draw a basic shape onto a temporarily used tile._ + +``` +emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.ShpFileEmptyTileHandler +shpFile=File, resource or URL to shape file for land representation. + + # Properties to set how the shp file contents are rendered. + land.fillColor=hex RGB color + land.lineColor=hex RGB color + land.fillPattern=path to resource, file or URL of pattern to use for tile fill. + + # From SimpleEmptyTileHandler superclass, handling the 'water' + # clear by default if not specified + background.fillColor=hex RGB color + background.lineColor=hex RGB color + background.fillPattern=path to resource, file or URL of pattern to use for tile fill. + + # Zoom level to start using noCoverage attributes. Is 0 by default if the shape file + # is not specified. If the shape file is specified and this isn't the zoom level + # will be set to 20. + noCoverageZoom=zoom level when you don't want empty tiles, you want no coverage tiles + + # How to render standard empty tiles, will be clear if not defined + noCoverage.fillColor=hex RGB color + noCoverage.lineColor=hex RGB color + noCoverage.fillPattern=path to resource, file or URL of pattern to use for tile fill. +``` + +# Adding a MapTileLayer to the Application # + +To add a MapTileLayer to the map, you can modify the _openmap.properties_ file. First, pick short word name for your layer, any little word, your choice. It should be unique compared to all of the other names listed in the _openmap.layers_ property. Next, add your name to that _openmap.layers_ list where you want your layer to be listed in the layer stack (first on the list is on top of the map). Then, add properties for your layer in the _openmap.properties_ file, using the name you picked for your layer as a scoping prefix for the properties. For example, let's say you chose 'osm\_tiles' for your name. + +``` +openmap.layers=... osm_tiles ... + +osm_tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer +osm_tiles.prettyName=OSM Tiles +osm_tiles.rootDir=http://c.tile.openstreetmap.org/ + +# Add other properties, starting with 'osm_tiles.', as needed for your configuration +``` + +If you want the layer to show up when the application is started, also add the **osm\_tiles** name to the _openmap.startupLayers_ list. + +To add a MapTileLayer to the SimpleMap2 example, you don't really need a property prefix for the properties: + +``` + // Just add this code + MapTileLayer mapTileLayer = new MapTileLayer(); + Properties tileProperties = new Properties(); + tileProperties.setProperty("rootDir", "http://c.tile.openstreetmap.org/"); + mapTileLayer.setProperties(tileProperties); + mapTileLayer.setVisible(true); + mapHandler.add(mapTileLayer); +``` \ No newline at end of file diff --git a/bin/openmap b/bin/openmap deleted file mode 100755 index 006127556..000000000 --- a/bin/openmap +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/sh - -# Modified from the ant startup script to start OpenMap instead. - -# Cygwin support. $cygwin _must_ be set to either true or false. -case "`uname`" in - CYGWIN*) cygwin=true ;; - *) cygwin=false ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$OPENMAP_HOME" ] && - OPENMAP_HOME=`cygpath --unix "$OPENMAP_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -if [ "$OPENMAP_HOME" = "" ] ; then - # try to find OPENMAP - if [ -d /usr/local/openmap ] ; then - OPENMAP_HOME=/usr/local/openmap - fi - - if [ -d ${HOME}/openmap ] ; then - OPENMAP_HOME=${HOME}/openmap - fi - - ## resolve links - $0 may be a link to openmap's home - PRG=$0 - progname=`basename $0` - - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '.*/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname $PRG`/$link" - fi - - done - - OPENMAP_HOME=`dirname "$PRG"`/.. - -fi - -if [ "$JAVA_HOME" != "" ] ; then - if [ "$JAVACMD" = "" ] ; then - JAVACMD=$JAVA_HOME/bin/java - fi -else - if [ "$JAVACMD" = "" ] ; then - JAVACMD=java - fi -fi - -# add in the dependency .jar files -DIRLIBS=${OPENMAP_HOME}/lib/*.jar - -# Change to match your installation - -# For SVG capabilities with the Batik package... -BATIK_HOME=/usr/local/java/batik-1.5 -DIRLIBS=${DIRLIBS}" "${BATIK_HOME}/lib/*.jar - -# For CORBA capabilities using Visibroker... -#VISIBROKER_HOME=/usr/local/openmap/vbroker-3.4 -#DIRLIBS=${DIRLIBS}" "${VISIBROKER_HOME}/lib/*.jar" "${JAVA_HOME}/jre/lib/rt.jar - -# For CORBA on Mac OS X -#DIRLIBS=${DIRLIBS}" "${VISIBROKER_HOME}/lib/*.jar" "/System/Library/Frameworks/JavaVM.framework/Classes/*.jar" - -for i in ${DIRLIBS} -do - # if the directory is empty, then it will return the input string - # this is stupid, so case for it - if [ "$i" != "${DIRLIBS}" ] ; then - if [ "$LOCALCLASSPATH" != "" ] ; then - LOCALCLASSPATH=$LOCALCLASSPATH:"$i" - else - LOCALCLASSPATH="$i" - fi - fi -done - -# Add OPENMAP_HOME to catch changes to openmap.properties file, and -# put the classes directories in front so that modified, compiled -# classes will be picked up even if the openmap.jar is not re-created. - -LOCALCLASSPATH=${OPENMAP_HOME}/classes/openmap:${OPENMAP_HOME}/classes/omcorba_vb:$LOCALCLASSPATH:${OPENMAP_HOME}:${OPENMAP_HOME}/share - -if [ "$CLASSPATH" != "" ] ; then - LOCALCLASSPATH=$CLASSPATH:$LOCALCLASSPATH -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - OPENMAP_HOME=`cygpath --path --windows "$OPENMAP_HOME"` - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"` -fi - -#$JAVACMD -version - -ARGS=$@ -OPENMAP_ARGS="" -JAVA_ARGS="" -for i in ${ARGS} -do -# if [ "$i" = "-D" ] ; then - JAVA_ARGS=$JAVA_ARGS" $i" -# else -# OPENMAP_ARGS=$OPENMAP_ARGS" $i" -# fi -done - -if [ "$VISIBROKER_HOME" = "" ] ; then -# echo $JAVACMD -Xmx256m -classpath "$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share $JAVA_ARGS com.bbn.openmap.app.OpenMap $OPENMAP_ARGS - $JAVACMD -Xmx512m -classpath "$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share -Ddebug.showprogress $JAVA_ARGS com.bbn.openmap.app.Main $OPENMAP_ARGS -else -# echo $JAVACMD -Xmx256m -Xbootclasspath:"$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share $JAVA_ARGS com.bbn.openmap.app.OpenMap $OPENMAP_ARGS - $JAVACMD -Xmx512m -Xbootclasspath:"$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share -Ddebug.showprogress $JAVA_ARGS com.bbn.openmap.app.Main $OPENMAP_ARGS -fi - - diff --git a/bin/openmap.bat b/bin/openmap.bat deleted file mode 100644 index 961cee7c4..000000000 --- a/bin/openmap.bat +++ /dev/null @@ -1,20 +0,0 @@ -@echo off - -rem This will launch the OpenMap application -rem YOU MUST EDIT THE SETTINGS IN THIS FILE TO MATCH YOUR CONFIGURATION - -rem Java Virtual Machine -rem CHANGE THIS TO POINT TO YOUR JAVA INSTALLATION IF JAVA ISN"T IN YOUR PATH -set JAVABIN=java.exe - -rem OpenMap top-level directory -rem THIS POINTS TO THE DIRECTORY ABOVE "BIN". CHANGE THIS IF YOU MOVE THE -rem BATCH FILE. -set OPENMAP_HOME=. - -rem CLASSPATH points to toplevel OpenMap directory and share -rem subdirectory. Add other jar files as available. -set CLASSPATH=%OPENMAP_HOME%;%OPENMAP_HOME%\classes\openmap;%OPENMAP_HOME%\share;%OPENMAP_HOME%\lib\milStd2525_png.jar;%OPENMAP_HOME%\lib\openmap.jar;%OPENMAP_HOME%\lib\omsvg.jar;%OPENMAP_HOME%\lib\omj3d.jar;%OPENMAP_HOME%\lib\omcorba_vb.jar; - -rem OK, now run OpenMap -%JAVABIN% -Xmx64m -Dopenmap.configDir=%OPENMAP_HOME%\share -Ddebug.showprogress com.bbn.openmap.app.Main diff --git a/bin/simple b/bin/simple deleted file mode 100644 index 8eec27a40..000000000 --- a/bin/simple +++ /dev/null @@ -1,91 +0,0 @@ -#! /bin/sh - -# Modified from the ant startup script to start HelloWorld instead. - -# Cygwin support. $cygwin _must_ be set to either true or false. -case "`uname`" in - CYGWIN*) cygwin=true ;; - *) cygwin=false ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$OPENMAP_HOME" ] && - OPENMAP_HOME=`cygpath --unix "$OPENMAP_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -if [ "$OPENMAP_HOME" = "" ] ; then - # try to find OPENMAP - if [ -d /usr/local/openmap ] ; then - OPENMAP_HOME=/usr/local/openmap - fi - - if [ -d ${HOME}/openmap ] ; then - OPENMAP_HOME=${HOME}/openmap - fi - - ## resolve links - $0 may be a link to ant's home - PRG=$0 - progname=`basename $0` - - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '.*/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname $PRG`/$link" - fi - - done - - OPENMAP_HOME=`dirname "$PRG"`/.. - -fi - -if [ "$JAVA_HOME" != "" ] ; then - if [ "$JAVACMD" = "" ] ; then - JAVACMD=$JAVA_HOME/bin/java - fi -else - if [ "$JAVACMD" = "" ] ; then - JAVACMD=java - fi -fi - -# add in the dependency .jar files -DIRLIBS=${OPENMAP_HOME}/lib/*.jar -# Change to match your installation -for i in ${DIRLIBS} -do - # if the directory is empty, then it will return the input string - # this is stupid, so case for it - if [ "$i" != "${DIRLIBS}" ] ; then - if [ "$LOCALCLASSPATH" != "" ] ; then - LOCALCLASSPATH=$LOCALCLASSPATH:"$i" - else - LOCALCLASSPATH="$i" - fi - fi -done - -LOCALCLASSPATH=$LOCALCLASSPATH:${OPENMAP_HOME}/share - -if [ "$CLASSPATH" != "" ] ; then - LOCALCLASSPATH=$CLASSPATH:${OPENMAP_HOME}/classes/openmap:${OPENMAP_HOME}/classes/corba_vb$LOCALCLASSPATH -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - OPENMAP_HOME=`cygpath --path --windows "$OPENMAP_HOME"` - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"` -fi - -$JAVACMD -Xmx256m -classpath "$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share com.bbn.openmap.app.example.SimpleMap - - diff --git a/bin/simple.bat b/bin/simple.bat deleted file mode 100644 index ab36e87c7..000000000 --- a/bin/simple.bat +++ /dev/null @@ -1,19 +0,0 @@ -@echo off - -rem This will launch the OpenMap application -rem YOU MUST EDIT THE SETTINGS IN THIS FILE TO MATCH YOUR CONFIGURATION - -rem Java Virtual Machine -rem CHANGE THIS TO POINT TO YOUR JAVA INSTALLATION IF JAVA ISN"T IN YOUR PATH -set JAVABIN=java.exe - -rem OpenMap top-level directory -rem THIS POINTS TO THE DIRECTORY ABOVE "BIN". CHANGE THIS IF YOU MOVE THE -rem BATCH FILE. -set OPENMAP_HOME=.. - -rem CLASSPATH points to toplevel OpenMap directory and share subdirectory -set CLASSPATH=%OPENMAP_HOME%\classes\openmap;%OPENMAP_HOME%\share;%OPENMAP_HOME%\lib\openmap.jar; - -rem OK, now run OpenMap -%JAVABIN% -mx64m -Dopenmap.configDir=%OPENMAP_HOME%\share com.bbn.openmap.app.example.SimpleMap diff --git a/bin/simple2 b/bin/simple2 deleted file mode 100644 index 48860813a..000000000 --- a/bin/simple2 +++ /dev/null @@ -1,91 +0,0 @@ -#! /bin/sh - -# Modified from the ant startup script to start HelloWorld instead. - -# Cygwin support. $cygwin _must_ be set to either true or false. -case "`uname`" in - CYGWIN*) cygwin=true ;; - *) cygwin=false ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$OPENMAP_HOME" ] && - OPENMAP_HOME=`cygpath --unix "$OPENMAP_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -if [ "$OPENMAP_HOME" = "" ] ; then - # try to find OPENMAP - if [ -d /usr/local/openmap ] ; then - OPENMAP_HOME=/usr/local/openmap - fi - - if [ -d ${HOME}/openmap ] ; then - OPENMAP_HOME=${HOME}/openmap - fi - - ## resolve links - $0 may be a link to ant's home - PRG=$0 - progname=`basename $0` - - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '.*/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname $PRG`/$link" - fi - - done - - OPENMAP_HOME=`dirname "$PRG"`/.. - -fi - -if [ "$JAVA_HOME" != "" ] ; then - if [ "$JAVACMD" = "" ] ; then - JAVACMD=$JAVA_HOME/bin/java - fi -else - if [ "$JAVACMD" = "" ] ; then - JAVACMD=java - fi -fi - -# add in the dependency .jar files -DIRLIBS=${OPENMAP_HOME}/lib/*.jar -# Change to match your installation -for i in ${DIRLIBS} -do - # if the directory is empty, then it will return the input string - # this is stupid, so case for it - if [ "$i" != "${DIRLIBS}" ] ; then - if [ "$LOCALCLASSPATH" != "" ] ; then - LOCALCLASSPATH=$LOCALCLASSPATH:"$i" - else - LOCALCLASSPATH="$i" - fi - fi -done - -LOCALCLASSPATH=$LOCALCLASSPATH:${OPENMAP_HOME}/share - -if [ "$CLASSPATH" != "" ] ; then - LOCALCLASSPATH=$CLASSPATH:${OPENMAP_HOME}/classes/openmap:${OPENMAP_HOME}/classes/corba_vb$LOCALCLASSPATH -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - OPENMAP_HOME=`cygpath --path --windows "$OPENMAP_HOME"` - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"` -fi - -$JAVACMD -Xmx256m -classpath "$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share com.bbn.openmap.app.example.SimpleMap2 - - diff --git a/bin/simple2.bat b/bin/simple2.bat deleted file mode 100644 index 4e8912881..000000000 --- a/bin/simple2.bat +++ /dev/null @@ -1,19 +0,0 @@ -@echo off - -rem This will launch the OpenMap application -rem YOU MUST EDIT THE SETTINGS IN THIS FILE TO MATCH YOUR CONFIGURATION - -rem Java Virtual Machine -rem CHANGE THIS TO POINT TO YOUR JAVA INSTALLATION IF JAVA ISN"T IN YOUR PATH -set JAVABIN=java.exe - -rem OpenMap top-level directory -rem THIS POINTS TO THE DIRECTORY ABOVE "BIN". CHANGE THIS IF YOU MOVE THE -rem BATCH FILE. -set OPENMAP_HOME=.. - -rem CLASSPATH points to toplevel OpenMap directory and share subdirectory -set CLASSPATH=%OPENMAP_HOME%\classes\openmap;%OPENMAP_HOME%\share;%OPENMAP_HOME%\lib\openmap.jar; - -rem OK, now run OpenMap -%JAVABIN% -mx64m -Dopenmap.configDir=%OPENMAP_HOME%\share com.bbn.openmap.app.example.SimpleMap2 diff --git a/build.xml b/build.xml deleted file mode 100644 index a6d5ca8fc..000000000 --- a/build.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/lib/.gitignore b/lib/.gitignore deleted file mode 100644 index b9c0b59e6..000000000 --- a/lib/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/omcorba.jar -/omj3d.jar -/omsvg.jar -/openmap.jar diff --git a/lib/milStd2525_png.jar b/lib/milStd2525_png.jar deleted file mode 100644 index 1f46e55d0..000000000 Binary files a/lib/milStd2525_png.jar and /dev/null differ diff --git a/logging.properties b/logging.properties deleted file mode 100644 index b44f74630..000000000 --- a/logging.properties +++ /dev/null @@ -1,63 +0,0 @@ -############################################################ -# Default Logging Configuration File -# -# You can use a different file by specifying a filename -# with the java.util.logging.config.file system property. -# For example java -Djava.util.logging.config.file=myfile -############################################################ - -############################################################ -# Global properties -############################################################ - -# "handlers" specifies a comma separated list of log Handler -# classes. These handlers will be installed during VM startup. -# Note that these classes must be on the system classpath. -# By default we only configure a ConsoleHandler, which will only -# show messages at the INFO and above levels. -handlers= java.util.logging.ConsoleHandler - -# To also add the FileHandler, use the following line instead. -handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler - -# Default global logging level. -# This specifies which kinds of events are logged across -# all loggers. For any given facility this global level -# can be overriden by a facility specific level -# Note that the ConsoleHandler also has a separate level -# setting to limit messages printed to the console. -.level= INFO - -############################################################ -# Handler specific properties. -# Describes specific configuration info for Handlers. -############################################################ - -# default file output is in user's home directory. -java.util.logging.FileHandler.pattern = %h/openmap-%u.log -#java.util.logging.FileHandler.limit = 50000 -java.util.logging.FileHandler.count = 1 - -# There are options for formatting logging output -#java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter -#java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter -java.util.logging.FileHandler.formatter = com.bbn.openmap.util.OMLoggingFormatter - -# Limit the message that are printed on the console to INFO and above. -java.util.logging.ConsoleHandler.level = FINER -#java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter -java.util.logging.ConsoleHandler.formatter = com.bbn.openmap.util.OMLoggingFormatter - - -############################################################ -# Facility specific properties. -# Provides extra control for each logger. -############################################################ - -# CONFIG, INFO, FINE, FINER, FINEST, WARN, SEVERE -# For example, set the com.bbn.openmap.MapBean logger to only log FINE -# messages: -#com.bbn.openmap.MapBean.level = FINE - -#Turns on map tile debugging -#MAPTILE_DEBUGGING.level = FINE \ No newline at end of file diff --git a/openmap.properties b/openmap.properties deleted file mode 100644 index abcc70af2..000000000 --- a/openmap.properties +++ /dev/null @@ -1,1038 +0,0 @@ -# ********************************************************************** -# -# -# -# BBN Technologies -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-8000 -# -# Copyright (C) BBNT Solutions LLC. All rights reserved. -# -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/openmap.properties,v $ -# $RCSfile: openmap.properties,v $ -# $Revision: 1.38.2.11 $ -# $Date: 2009/03/03 21:20:51 $ -# $Author: dietrick $ -# -# ********************************************************************** -# -# WHAT IS THIS FILE? -# -# This is a generic OpenMap properties file, which controls how -# components are loaded into the OpenMap application. It specifies -# the initial projection the map should have when OpenMap is started, -# the layers that should be available, which ones should be turned on, -# and lets you adjust all the layers' attributes for their startup -# configuration. Most importantly, this file also lets you add and -# remove different components from the application itself. You can -# modify it with any text editor you like. -# -# WHAT ARE PROPERTIES? -# -# Java properties are a set of key=value pairs. The key is the name -# of the thing you are setting, and the value is what you are setting -# it to. There are a couple of things to look for that we do with key -# values in this properties file. -# -# First, all the properties that can be set for a component are -# *hopefully* listed in the Javadocs (Java API documentation). If a -# component is specified as a com.bbn.openmap.PropertyConsumer, it -# will be given a chance to configure itself based on the settings -# within the properties file. Components can be layers or any other -# part of the OpenMap application. -# -# Secondly, the keys are scoped to focus the value to a specific -# instance of a components. If there are more that one layer of a -# specific type (say, two ShapeLayers, one for roads and one for -# rivers), the names of the keys will have a different prefix for the -# key. For instance, ShapeLayers have a lineColor attribute you can -# set in this file, and the value used is a hexadecimal value for an -# ARGB color (transparency (A), red (R), green (G), blue (B)): -# -# For a red, non-transparent color for the line. -# lineColor=FFFF0000 -# -# But there are two layers - to scope the property for different -# layers, a prefix must be added to the property, separated by a '.': -# -# roads.lineColor=FFFF0000 -# rivers.lineColor=FF0000FF -# -# In this case, the roads layer has a red line color and the rivers -# layer has a blue line color. The prefix 'roads' and 'rivers' is -# something picked to your liking and used only within this property -# file, and is referred to in OpenMap documentation as a marker name. -# Marker names are first used in a list - the openmap.layers property -# is a perfect example: -# -# openmap.layers=first second third -# -# In this example, I've chosen first, second and third to be marker -# names of three different layers. Later in the properties file, I -# would use these marker names to define the layers and each layer's -# attributes. For the 'first' layer, I'll define a ShapeLayer: -# -# # All layers require a class name that defines which one to use -# first.class=com.bbn.openmap.layer.shape.ShapeLayer -# -# # And a pretty name to use in the GUI -# first.prettyName=Roads -# -# # Now come properties that are particular to ShapeLayers: -# -# # These first two are mandatory for the ShapeLayer: -# first.shapeFile= -# first.spatialIndex= -# -# # These are optional, and override the defaults set in the ShapeLayer: -# first.lineColor=FFFF0000 -# first.lineWidth=2 -# -# You do this for each layer listed. To add a layer to the -# application, you make up a marker name, add it to the list, and then -# define a set of properties for it using the marker name as a prefix. -# - -# This marker name list paradigm is used throughout the properties -# file. It's an important concept to understand before modifying this -# file. -# -# HOW MANY PROPERTIES FILES ARE THERE? -# -# OpenMap looks for this file in several different places. When it -# finds one, it loads all the properties, and moves on. If two -# properties have the same key, the last version read wins. The most -# important place to keep a version of the openmap.properties file is -# a personalized one in your home directory or profile directory. -# This is the last one read. It also lets you personalize your -# application setup and not affect anyone else using the OpenMap -# installation. -# -# OK, lets define the map! -# -# ################################################### -# These properties define the starting projection of the map. -# These properties are listed in com.bbn.openmap.Environment.java, -# and affect the initialization of the application. -# ################################################### - -# MAP STARTUP PROJECTION PARAMETERS -# Latitude and longitude in decimal degrees -openmap.Latitude=20f -openmap.Longitude=-20f -# Scale: zoom level (1:scale) -openmap.Scale=3000000000f -# Projection type to start the map with. Use the class name of the -# projection, such as com.bbn.openmap.proj.Mercator, -# com.bbn.openmap.proj.CADRG, com.bbn.openmap.proj.Orthgraphic, -# com.bbn.openmap.proj.LLXY or com.bbn.openmap.proj.Gnomonic -openmap.Projection=com.bbn.openmap.proj.Mercator - -# APPLICATION WINDOW DIMENSIONS -# Width and Height of map, in pixels -openmap.Width=640 -openmap.Height=480 - -# APPLICATION WINDOW TITLE -# Change this for a different title in the main window. -openmap.Title=OpenMap(tm) - -# WINDOW STARTUP LOCATION -# pixel X/Y window position (if values < 0, then center the window on the screen) -openmap.x=-1 -openmap.y=-1 - -# MAP BACKGROUND -# The background color of the map, in hex AARRGGBB values (AA is -# transparency, RR, GG and BB are red, green and blue in hex values -# between 00-FF (0-255)). -openmap.BackgroundColor=99B3CC - -# Ironically, the "properties" property, which details where the -# PropertyHandler is looking for its properties, won't work here. - -# ################################################### -# These are miscellaneous variables for the OpenMap application. -# ################################################### -# How to launch a browser to display additional information. -# Windows example: openmap.WebBrowser=C:\\program files\\internet explorer\\iexplore.exe -openmap.WebBrowser=/usr/bin/netscape -install -# Used for creating web pages for the browser -openmap.TempDirectory=/tmp -# Help web pages -openmap.HelpURL=http://openmap.bbn.com/doc/user-guide.html -# Use internal frames as an application - used to be gui.UseInternalFrames -openmap.UseInternalFrames=false - -# DEBUGGING -# OpenMap has a Debug messaging mechanism that lets you set certain -# keywords as environment variables (-Ddebug.keyword) to enable -# printouts from different objects. The code contains these keywords, -# and by looking at a class's code, you can figure out what the -# keywords are (look for Debug.message("keyword", "message") and 'if -# (Debug.debugging("keyword")' statements). You can enable these -# messages by putting those keywords in a space-separated list in this -# property. If you don't want extra messages, you can ignore this -# property and leave it empty. -#openmap.Debug= - -# INTERNATIONALIZATION -# If you are interested in modifying OpenMap to display internationalized -# strings (or to change the strings that are used in the application GIU), -# These are the Debug flags that need to be set before the various components -# start asking the BasicI18n class for the displayed strings. The 'i18n.create' -# flag tells the BasicI8n class to track the strings in the locale set on the -# machine (for I18N_language_COUNTRY.properties files), and the 'i18n.default' -# flag tells the BasicI8n class to only track generic properties (for -# I18N.properties files). To actually create the properties files, you have -# to add the I18nFileCreateMenuItem to the application, look for that below. -#openmap.Debug=i18n.create i18n.default - -# OPENMAP COMPONENTS -# ################################################### -# These properties define the general components to use in the -# application, OTHER than layers. Notice the marker name list. You -# can add and remove parts of the application here, simply by -# adjusting this marker name list and adding properties for that -# marker name. Note the order in which menu objects are important, -# except helpMenu which is always adjusted to be the last menu item. -# -# If you want to remove components from the application, simply remove -# the marker name from the openmap.components list. You don't have to -# delete the class definition property, too. If you want to add a -# component to the list, add the marker name to the openmap.components -# list when you want it to be created and added relative to the other -# components, and then add a 'marker name'.class property for that -# component to this file. -# ################################################### - -openmap.components=informationDelegator projFactory mouseDelegator projectionstack addlayer glc menulist toolBar navpanel zoompanel scalepanel projectionstacktool mouseModePanel deleteButton omdtl overviewMapHandler layersPanel selectMouseMode navMouseMode distanceMouseMode panMouseMode omdrawingtool omlineloader omcircleloader omrectloader ompointloader omsplineloader ompolyloader omscalingrasterloader omdistloader layerHandler projkeys repaintPolicy srl - -# ### -# Applet components, also alternative component configuration -# with OMControlPanel on the left side of the applet. To enable this -# list, simply uncomment it. -# ### -#openmap.components=informationDelegator projFactory mouseDelegator projectionstack addlayer glc menulist toolBar mouseModePanel selectMouseMode navMouseMode distanceMouseMode omdtl deleteButton omdrawingtool omlineloader omcircleloader omrectloader ompointloader omsplineloader omdecsplineloader ompolyloader omscalingrasterloader omdistloader controlpanel layerHandler projkeys repaintPolicy srl - -main.components=informationDelegator projFactory mouseDelegator addlayer glc menulist toolBar deleteButton omdtl overviewMapHandler layersPanel mouseMode omdrawingtool omlineloader omcircleloader omrectloader ompointloader omsplineloader ompolyloader omscalingrasterloader omdistloader layerHandler projkeys repaintPolicy srl scalepanel -main.activeWidgets.fillColor=BBBBBB - -# ################################################### -# Menu configuration, defining the menu items listed in the -# openmap.components list. - -menulist.class=com.bbn.openmap.gui.menu.MenuList -menulist.menus=fileMenu controlMenu navigateMenu layersMenu gotoMenu helpMenu -fileMenu.class=com.bbn.openmap.gui.FileMenu -controlMenu.class=com.bbn.openmap.gui.ControlMenu - -# INTERNATIONALIZATION -# To get the BasicI18n class to create the internationalization property -# files after you have set the Debug statements described above, you can add this -# toolMenu to the menulist.menus list above: -toolMenu.class=com.bbn.openmap.gui.menu.OMBasicMenu -toolMenu.prettyName=Tools -toolMenu.mnemonic=T -toolMenu.items=i18ndump -i18ndump.class=com.bbn.openmap.gui.menu.I18nFileCreateMenuItem - -### -# Adding a menu item to toggle on/off the OMControlPanel if it is -# added to the openmap.components list. -controlMenu.items=controlPanelToggle -controlPanelToggle.class=com.bbn.openmap.gui.menu.ControlPanelToggleMenuItem -### - -navigateMenu.class=com.bbn.openmap.gui.NavigateMenu -layersMenu.class=com.bbn.openmap.gui.LayersMenu -gotoMenu.class=com.bbn.openmap.gui.GoToMenu -gotoMenu.addDefaults=true - -### Add your own views to the GoToMenu -#gotoMenu.views=Argentina India United_States -#Argentina.latitude=-39.760445 -#Argentina.longitude=-65.92294 -#Argentina.name=Argentina -#Argentina.projection=Mercator -#Argentina.scale=5.0E7 -#India.latitude=20.895763 -#India.longitude=80.437485 -#India.name=India -#India.projection=Mercator -#India.scale=3.86688E7 -#United_States.latitude=38.82259 -#United_States.longitude=-96.74999 -#United_States.name=United States -#United_States.projection=Mercator -#United_States.scale=5.186114E7 -### - -helpMenu.class=com.bbn.openmap.gui.DefaultHelpMenu -helpMenu.items=helpUserMenuItem -helpUserMenuItem.class=com.bbn.openmap.gui.UserGuideMenuItems -helpUserMenuItem.class=com.bbn.openmap.gui.menu.WebSiteHelpMenuItem - -# End menu item definitions -# ################################################### - -# ################################################### -# Defining the other components in the openmap.components list: - -# Key components, usually always want these. -mouseDelegator.class=com.bbn.openmap.MouseDelegator -informationDelegator.class=com.bbn.openmap.InformationDelegator -layerHandler.class=com.bbn.openmap.LayerHandler - -# General function additions -projkeys.class=com.bbn.openmap.event.ProjMapBeanKeyListener -repaintPolicy.class=com.bbn.openmap.HintsMapBeanRepaintPolicy -repaintPolicy.renderingHints=KEY_ANTIALIASING -repaintPolicy.KEY_ANTIALIASING=VALUE_ANTIALIAS_ON -repaintPolicy.KEY_RENDERING=VALUE_RENDER_SPEED -projectionstack.class=com.bbn.openmap.proj.ProjectionStack -layersPanel.class=com.bbn.openmap.gui.LayersPanel -menuPanel.class=com.bbn.openmap.gui.MenuPanel -dndCatcher.class=com.bbn.openmap.tools.dnd.DefaultDnDCatcher -dropSupport.class=com.bbn.openmap.tools.dnd.DropListenerSupport - -# Mouse handling components -mouseModePanel.class=com.bbn.openmap.gui.MouseModeButtonPanel -selectMouseMode.class=com.bbn.openmap.event.SelectMouseMode -distanceMouseMode.class=com.bbn.openmap.event.DistanceMouseMode -panMouseMode.class=com.bbn.openmap.event.PanMouseMode -panMouseMode.azPanningShapefile=data/shape/dcwpo-browse.shp -# Floating number between 0-1, with 1 being opaque, default .5 -panMouseMode.opaqueness=1 -# True/false, to leave old map up behind panned version. -panMouseMode.leaveShadow=false -# There's a NavMouseMode, too. This one defines boxes from center -navMouseMode.class=com.bbn.openmap.event.NavMouseMode2 -nullMouseMode.class=com.bbn.openmap.event.NullMouseMode -# Only mouse mode in "Main" application -mouseMode.class=com.bbn.openmap.event.OMMouseMode -mouseMode.azPanningShapefile=data/shape/dcwpo-browse.shp - -# Drawing tool parts -omdtl.class=com.bbn.openmap.tools.drawing.OMDrawingToolLauncher -omcircleloader.class=com.bbn.openmap.tools.drawing.OMCircleLoader -omdecsplineloader.class=com.bbn.openmap.tools.drawing.OMDecoratedSplineLoader -omdistloader.class=com.bbn.openmap.tools.drawing.OMDistanceLoader -omdrawingtool.class=com.bbn.openmap.tools.drawing.OMDrawingTool -omlineloader.class=com.bbn.openmap.tools.drawing.OMLineLoader -ompointloader.class=com.bbn.openmap.tools.drawing.OMPointLoader -ompolyloader.class=com.bbn.openmap.tools.drawing.OMPolyLoader -omrectloader.class=com.bbn.openmap.tools.drawing.OMRectLoader -omscalingrasterloader.class=com.bbn.openmap.tools.drawing.OMScalingRasterLoader -omsplineloader.class=com.bbn.openmap.tools.drawing.OMSplineLoader - -# ## -# ToolPanel definitions for the first ToolPanel 'toolbar' -toolBar.class=com.bbn.openmap.gui.ToolPanel -# Tell the first ToolPanel to avoid putting the DrawingToolLayer GUI -# in it: -#toolBar.avoid=dtlayer - -# ToolPanel definitions for the second ToolPanel 'toolbar2' -#toolBar2.class=com.bbn.openmap.gui.ToolPanel -# Tell the second ToolPanel that you only want it to put the -# DrawingToolLayer GUI in it: -#toolBar2.components=dtlayer - -# You can set the location, but it interferes with the -# InformationDelegator. Undefined, the ToolPanel goes North, but then -# it interferes with the first ToolPanel. - -#toolBar2.preferredLocation=SOUTH - -# Specific Tools -navpanel.class=com.bbn.openmap.gui.NavigatePanel -deleteButton.class=com.bbn.openmap.gui.OMGraphicDeleteTool -projectionstacktool.class=com.bbn.openmap.gui.ProjectionStackTool -scalepanel.class=com.bbn.openmap.gui.ScaleTextPanel -zoompanel.class=com.bbn.openmap.gui.ZoomPanel - -# ### - -projFactory.class=com.bbn.openmap.proj.ProjectionFactory -projFactory.projectionLoaders=mercatorloader cadrgloader ortholoader llxyloader gnomonicloader -projFactory.mercatorloader.class=com.bbn.openmap.proj.MercatorLoader -projFactory.cadrgloader.class=com.bbn.openmap.proj.CADRGLoader -projFactory.ortholoader.class=com.bbn.openmap.proj.OrthographicLoader -projFactory.llxyloader.class=com.bbn.openmap.proj.LLXYLoader -projFactory.gnomonicloader.class=com.bbn.openmap.proj.GnomonicLoader - -# Not used by default, in secondary openmap.components list, puts controls in panel left of map. -controlpanel.class=com.bbn.openmap.gui.OMControlPanel -controlpanel.OverviewMapHandler.overviewLayers=overviewLayer -controlpanel.OverviewMapHandler.isTool=false -controlpanel.OverviewMapHandler.overviewScaleFactor=30f -controlpanel.OverviewMapHandler.overviewMinScale=50000000f -controlpanel.OverviewMapHandler.overviewStatusLayer=com.bbn.openmap.layer.OverviewMapAreaLayer -controlpanel.OverviewMapHandler.lineColor=FFFF0000 -controlpanel.OverviewMapHandler.fillColor=33FF0000 -controlpanel.LayersPanel.controls=com.bbn.openmap.gui.LayerControlButtonPanel -controlpanel.LayersPanel.controls.orientation=horizontal -controlpanel.LayersPanel.controls.configuration=NORTH - -# ### -# BeanPanel properties - the BeanPanel isn't defined in the -# openmap.components list above, you would add 'beanpanel' to that -# list and uncomment these properties: -# ### -#beanpanel.class=com.bbn.openmap.tools.beanbox.BeanPanel -#beanpanel.beans.path=path to directory containing jar files -#beanpanel.tabs=tab1 tab2 tab3 -#beanpanel.tab1.name=Generic -#beanpanel.tab1.beans=com.bbn.openmap.examples.beanbox.SimpleBeanObject -#beanpanel.tab2.name=Container -#beanpanel.tab2.beans=com.bbn.openmap.examples.beanbox.SimpleBeanContainer -#beanpanel.tab3.name=Military -#beanpanel.tab3.beans=com.bbn.openmap.examples.beanbox.Fighter - -# ### -# MIL-STD-2525B SYMBOLOGY COMPONENT -# SymbolReferenceLibrary properties - the SymbolReferenceLibrary -# openmap.components list above, you would add 'srl' to that -# list and uncomment these properties: -# ### -srl.class=com.bbn.openmap.tools.symbology.milStd2525.SymbolReferenceLibrary -# Uncomment the one that fits the dataset you are using -#srl.imageMakerClass=com.bbn.openmap.tools.symbology.milStd2525.SVGSymbolImageMaker -srl.imageMakerClass=com.bbn.openmap.tools.symbology.milStd2525.PNGSymbolImageMaker -# Optional property: -#srl.path= - -# Defining the DTED frame cache. 'dtedframecache' needs to be added -# to the openmap.components list, and the path to a dted directory -# needs to be modified to fit your installation. -dtedframecache.class=com.bbn.openmap.dataAccess.dted.DTEDFrameCache -dtedframecache.directoryHandlers=dted1 -dtedframecache.dted1.path=/data/dted - -# Defining a VPF VMAP level 0 tile cache. 'vpfcache' needs to be -# added to the openmap.components list, and the path to your vmap level -# 0 needs to be modified to fit your installation. In the VPFLayer -# that uses this tile cache, the layer's libraryBean property would be -# set to VMAPLEVEL0, the name of this cache. -vpfcache.class=com.bbn.openmap.layer.vpf.LibraryBean -vpfcache.name=VMAPLEVEL0 -vpfcache.vpfPath=/data/vpf/vmaplv0/disk0;/data/vpf/vmaplv0/disk1 - -# ### -# Properties defined for the overview map handler. -# ### -overviewMapHandler.class=com.bbn.openmap.gui.OverviewMapHandler -# marker name list defining background layers used on overview map. -# The layers are defined as any other layer is below, look -# for 'overviewLayer' properties. This is a space-separated list of -# marker names. -overviewMapHandler.overviewLayers=overviewLayer -# how zoomed out to keep the overview map versus the main map -overviewMapHandler.overviewScaleFactor=10f -# when to stop zooming in -overviewMapHandler.overviewMinScale=10000000f -# the layer to use to render on top, showing where the main map covers. -overviewMapHandler.overviewStatusLayer=com.bbn.openmap.layer.OverviewMapAreaLayer -overviewMapHandler.lineColor=ffff0000 -overviewMapHandler.fillColor=66ff0000 -# ### - -# The AddLayerPanel allows certain layers to be added to the -# application dynamically. Only certain layers have been -# updated to be able to work with the Inspector to set their initial -# parameters. The 'addlayer' marker name was added to the -# openmap.components list, and this component looks for the -# openmap.addableLayers property to figure out what layers to make -# available for dynamic addition. To add a layer to this list, create -# a unique marker name for a generic instance of the layer, and then -# supply the .class field and .prettyName (see -# below) for that object. The class name will be the type of -# layer created by the LayerAddPanel, and this prettyName will -# be the generic description of the layer presented to the user. The -# user will have an opportunity to name the specific layer that gets -# created. - -# Define the class for the component listed in the openmap.components -# list: -addlayer.class=com.bbn.openmap.gui.LayerAddPanel - -# Define a list of addable layers: -openmap.addableLayers=mptle mptleutil shape grat utmgrid rpf shispi eipi wmsp epi - -# Define the properties of the addable layers: -shape.class=com.bbn.openmap.layer.shape.ShapeLayer -shape.prettyName=Shape Layer -grat.class=com.bbn.openmap.layer.GraticuleLayer -grat.prettyName=Graticule Layer -utmgrid.class=com.bbn.openmap.layer.UTMGridLayer -utmgrid.prettyName=UTM Grid Overlay -rpf.class=com.bbn.openmap.layer.rpf.RpfLayer -rpf.prettyName=RPF Layer -shispi.class=com.bbn.openmap.layer.image.SHISLayer -shispi.prettyName=Simple Http Image Server (SHIS) Layer -eipi.class=com.bbn.openmap.layer.image.EarthImageLayer -eipi.prettyName=Earth Image Layer -wmsp.class=com.bbn.openmap.layer.image.WMSLayer -wmsp.prettyName=WMS Layer -epi.class=com.bbn.openmap.layer.shape.EsriLayer -epi.prettyName=Shape Layer with Attributes -mptle.class=com.bbn.openmap.layer.imageTile.MapTileLayer -mptle.prettyName=Map Tile Layer -mptleutil.class=com.bbn.openmap.layer.imageTile.MapTileUtilLayer -mptleutil.prettyName=Map Tile Grid Layer - -# To test how fast your application redraws, use this and add anime to your -# components list. A layer will be created for it, and the palette for the layer -# controls the component. You can add sprites and adjust the redrawing timer. The -# GraphicLoaderConnector needs to be added to the components list as well. -anime.class=com.bbn.openmap.graphicLoader.AnimationTester - -# End component definitions -# ################################################### - -# IMAGE SERVER SETTINGS -# ################################################### -# These properties define the formatters the Simple Http -# Image Server uses. The default formatter is the first one -# in the list. -# The layers property can be used to override the -# openmap.startUpLayers property as the default layers. -# ################################################### - -formatters=gif jpeg png png8 png32 -gif.class =com.bbn.openmap.image.AcmeGifFormatter -jpeg.class=com.bbn.openmap.image.SunJPEGFormatter -png.class=com.bbn.openmap.image.PNGImageIOFormatter -png8.class=com.bbn.openmap.image.PNG8ImageFormatter -png32.class=com.bbn.openmap.image.PNG32ImageFormatter -#layers=date drawing daynight graticule shapePolitical - -# ################################################### -# You can refer to other properties files and have their properties -# loaded as well. This is good for defining a set of layers that work -# with a particular type of data, for instance, and then override some -# of those properties defined in those files to localize them for your -# setup. This works with a marker name list. By default, nothing defined. -# ################################################### - -#openmap.include=include1 include2 -#include1.URL= -#include2.URL= - -# OPENMAP LAYERS -# ################################################### -# Here is the list of layers to add to the map. The properties for -# each marker name are defined later. -# -# If you want to remove a layer from the application, remove its -# marker name from the openmap.layers property list. You do not have -# to delete all of its properties as well. -# -# If you want to add a layer to the application, add its marker name -# to the openmap.layers property list, and then add its properties to -# this file. As a minimum, Layers all need a 'marker name'.class -# property, and a 'marker name'.prettyName property (for the GUI -# components). Consult the JavaDocs for a layer to see what other -# properties can be set for that layer. -# ################################################### - -# Layers listed here appear on the Map in the order of their names. -openmap.layers=date dtlayer distlayer daynight cities test graticule demo tiles shapePolitical - -# If you get more data, you can add other layers defined in this file. -# You'll want to look at the properties for each layer and modify them -# as needed. Check the javadocs for definitions of the available -# properties for each layer. - -#openmap.layers=date daynight test graticule terrain demo dtedcov jdted jrpf shapePolitical ScaledPolitical ScaledFillPolitical - -# These layers are turned on when the map is first started. Order -# does not matter here... -openmap.startUpLayers=graticule shapePolitical - -# ################################################### -# These are the properties for individual layers. Consult the -# javadocs (Java API pages) for the individual layers for options. -# ################################################### - -### Drawing version of the EditorLayer. An EditorLayer, when active, -### places tools in the ToolPanel that creates/manipulates the -### OMGraphics on this particular layer. -dtlayer.class=com.bbn.openmap.layer.editor.EditorLayer -dtlayer.prettyName=Drawing Layer -dtlayer.editor=com.bbn.openmap.layer.editor.DrawingEditorTool -#dtlayer.showAttributes=false -dtlayer.loaders=lines polys rects circles points text -dtlayer.mouseModes=Gestures -dtlayer.distance.class=com.bbn.openmap.tools.drawing.OMDistanceLoader -dtlayer.lines.class=com.bbn.openmap.tools.drawing.OMLineLoader -dtlayer.polys.class=com.bbn.openmap.tools.drawing.OMPolyLoader -dtlayer.rects.class=com.bbn.openmap.tools.drawing.OMRectLoader -dtlayer.circles.class=com.bbn.openmap.tools.drawing.OMCircleLoader -dtlayer.points.class=com.bbn.openmap.tools.drawing.OMPointLoader -dtlayer.text.class=com.bbn.openmap.tools.drawing.OMTextLoader - -### Another Drawing version of the EditorLayer, with the editor set up -### to only create OMDistance objects. -distlayer.class=com.bbn.openmap.layer.editor.EditorLayer -distlayer.prettyName=Distance Layer -distlayer.showAttributes=false -distlayer.editor=com.bbn.openmap.layer.editor.DrawingEditorTool -distlayer.loaders=distance -distlayer.distance.class=com.bbn.openmap.tools.drawing.OMDistanceLoader -distlayer.distance.attributesClass=com.bbn.openmap.omGraphics.DrawingAttributes -distlayer.distance.lineColor=FFAA0000 -distlayer.distance.mattingColor=66333333 -distlayer.distance.matted=true - -### Layer to catch Drag and Drop events from the DefaultDnDCatcher and -### DropListenerSupport -simpleBeanLayer.class=com.bbn.openmap.examples.beanbox.SimpleBeanLayer -simpleBeanLayer.prettyName=Simple Bean Layer - -### Layer used by the overview handler -overviewLayer.class=com.bbn.openmap.layer.shape.ShapeLayer -overviewLayer.prettyName=Overview -overviewLayer.shapeFile=data/shape/dcwpo-browse.shp -overviewLayer.spatialIndex=data/shape/dcwpo-browse.ssx -overviewLayer.lineColor=ff000000 -overviewLayer.fillColor=DAD5CB - -### -# Demo layer - the layer's palette has a bunch of buttons to call -# the Drawing Tool. -demo.class=com.bbn.openmap.layer.DemoLayer -demo.prettyName=Demo - -### -# DrawingToolLayer - no palette, just a generic layer to catch -# graphics from the OMDrawingToolLauncher, and to call the OMDrawingTool -# to edit graphics already part of the layer. -drawing.class=com.bbn.openmap.layer.DrawingToolLayer -drawing.prettyName=Drawing Tool Layer -drawing.addToBeanContext=true - -### ShapeFile layers -shapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -shapePolitical.prettyName=Political Boundaries -# Specify shapefile and spatial-index file as a filename or pathname. -# If the former, you must reference the directory where this file -# lives in your CLASSPATH -#shapePolitical.shapeFile=data/shape/dcwpo-browse.shp -#shapePolitical.spatialIndex=data/shape/dcwpo-browse.ssx -shapePolitical.shapeFile=data/shape/cntry02/cntry02.shp -# Colors (32bit ARGB) -shapePolitical.lineColor=ff000000 -shapePolitical.fillColor=DAD5CB -shapePolitical.background=true -shapePolitical.rules=1 2 3 4 5 6 7 8 -# rule0 definition: -shapePolitical.1.key=COLOR_MAP -shapePolitical.1.op=equals -shapePolitical.1.val=1 -shapePolitical.1.fillColor=F0F0F0 -shapePolitical.1.render=true -shapePolitical.2.key=COLOR_MAP -shapePolitical.2.op=equals -shapePolitical.2.val=2 -shapePolitical.2.fillColor=e9e9e9 -shapePolitical.2.render=true -shapePolitical.3.key=COLOR_MAP -shapePolitical.3.op=equals -shapePolitical.3.val=3 -shapePolitical.3.fillColor=e0e0e0 -shapePolitical.3.render=true -shapePolitical.4.key=COLOR_MAP -shapePolitical.4.op=equals -shapePolitical.4.val=4 -shapePolitical.4.fillColor=d9d9d9 -shapePolitical.4.render=true -shapePolitical.5.key=COLOR_MAP -shapePolitical.5.op=equals -shapePolitical.5.val=5 -shapePolitical.5.fillColor=d0d0d0 -shapePolitical.5.render=true -shapePolitical.6.key=COLOR_MAP -shapePolitical.6.op=equals -shapePolitical.6.val=6 -shapePolitical.6.fillColor=c9c9c9 -shapePolitical.6.render=true -shapePolitical.7.key=COLOR_MAP -shapePolitical.7.op=equals -shapePolitical.7.val=7 -shapePolitical.7.fillColor=c0c0c0 -shapePolitical.7.render=true -shapePolitical.8.key=COLOR_MAP -shapePolitical.8.op=equals -shapePolitical.8.val=8 -shapePolitical.8.fillColor=b9b9b9 -shapePolitical.8.render=true - -# ScaleFilterLayer switches between the layers at the transisition scales. -ScaledPolitical.class=com.bbn.openmap.layer.ScaleFilterLayer -ScaledPolitical.prettyName=Political Boundaries -# List 2 or more layers -ScaledPolitical.layers=ThinShapePolitical ShapePolitical -# List the transition scales to switch between layers -ScaledPolitical.transitionScales=5000000 - -# ScaleFilterLayer switches between the layers at the transisition scales. -ScaledFillPolitical.class=com.bbn.openmap.layer.ScaleFilterLayer -ScaledFillPolitical.prettyName=Political Areas -# List 2 or more layers -ScaledFillPolitical.layers=ThinShapeFillPolitical ShapeFillPolitical -# List the transition scales to switch between layers -ScaledFillPolitical.transitionScales=5000000 - -### ShapeFile layer, full resolution converted vmap political boundaries -ShapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -ShapePolitical.prettyName=Political Edge -ShapePolitical.shapeFile=data/shape/vmap_edge.shp -ShapePolitical.spatialIndex=data/shape/vmap_edge.ssx - -### ShapeFile layer, thinned converted vmap political boundaries -ThinShapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -ThinShapePolitical.prettyName=Political Edge -ThinShapePolitical.shapeFile=data/shape/vmap_edge_thin.shp -ThinShapePolitical.spatialIndex=data/shape/vmap_edge_thin.ssx - -### ShapeFile layer, full resolution converted vmap political areas -ShapeFillPolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -ShapeFillPolitical.prettyName=Political Solid -ShapeFillPolitical.shapeFile=data/shape/vmap_area.shp -ShapeFillPolitical.spatialIndex=data/shape/vmap_area.ssx -ShapeFillPolitical.lineColor=BDDE83 -ShapeFillPolitical.fillColor=BDDE83 - -### ShapeFile layer, thinned converted vmap political areas -ThinShapeFillPolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -ThinShapeFillPolitical.prettyName=Political Solid -ThinShapeFillPolitical.shapeFile=data/shape/vmap_area_thin.shp -ThinShapeFillPolitical.spatialIndex=data/shape/vmap_area_thin.ssx -ThinShapeFillPolitical.lineColor=BDDE83 -ThinShapeFillPolitical.fillColor=BDDE83 - -### ShapeFile layer, thinned converted vmap political boundaries, -# muiltiple shape files on one layer... -politicalCombo.class=com.bbn.openmap.layer.shape.MultiShapeLayer -politicalCombo.prettyName=Political Boundaries 2 -politicalCombo.shapeFileList=pol_edges pol_fill - -politicalCombo.pol_edges.shapeFile=data/shape/vmap_edge_thin.shp -politicalCombo.pol_edges.prettyName=Borders -politicalCombo.pol_edges.buffered=false - -politicalCombo.pol_fill.shapeFile=data/shape/vmap_area_thin.shp -politicalCombo.pol_fill.prettyName=Areas -politicalCombo.pol_fill.lineColor=FFAAAA66 -politicalCombo.pol_fill.fillColor=FFAAAA66 -politicalCombo.pol_fill.buffered=false - -### Graticule layer -graticule.class=com.bbn.openmap.layer.GraticuleLayer -graticule.prettyName=Graticule -# Show lat / lon spacing labels -graticule.showRuler=true -graticule.show1And5Lines=true -# Controls when the five degree lines and one degree lines kick in -#- when there is less than the threshold of ten degree lat or lon -#lines, five degree lines are drawn. The same relationship is there -#for one to five degree lines. -graticule.threshold=2 -# the color of 10 degree spacing lines (ARGB) -graticule.10DegreeColor=99000000 -# the color of 5 degree spacing lines (ARGB) -graticule.5DegreeColor=99009900 -# the color of 1 degree spacing lines (ARGB) -graticule.1DegreeColor=99003300 -# the color of the equator (ARGB) -graticule.equatorColor=99FF0000 -# the color of the international dateline (ARGB) -graticule.dateLineColor=99000000 -# the color of the special lines (ARGB) -graticule.specialLineColor=99000000 -# the color of the labels (ARGB) -graticule.textColor=99000000 - -### Date & Time layer -date.class=com.bbn.openmap.layer.DateLayer -date.prettyName=Date & Time -# display font as a Java font string -date.font=SansSerif-Bold -# like XWindows geometry: [+-]X[+-]Y, `+' indicates relative to -# left edge or top edges, `-' indicates relative to right or bottom -# edges, XX is x coordinate, YY is y coordinate -date.geometry=+20+30 -# background rectangle color ARGB -date.color.bg=ff808080 -# foreground text color ARGB -date.color.fg=ff000000 -# date format (using java.text.SimpleDateFormat patterns) -date.date.format=EEE, d MMM yyyy HH:mm:ss z - - -### Day/Night shading layer properties -daynight.class=com.bbn.openmap.layer.daynight.DayNightLayer -daynight.prettyName=Day/Night Shading -# draw terminator as poly (faster calculation than image, defaults to -# true). -daynight.doPolyTerminator=true -# number of vertices for polygon terminator line. this is only valid -# if doPolyTerminator is true... -daynight.terminatorVerts=512 -# termFade - the distance of the transition of fade, as a percentage of PI. -daynight.termFade=.1 -# currentTime - true to display the shading at the computer's current time. -daynight.currentTime=true -# updateInterval - time in milliseconds between updates. currentTime has to be -# true for this to be used. 1000*60*5 = 300000 = 5min updates -daynight.updateInterval=300000 -# Shading Colors (32bit ARGB) -daynight.nighttimeColor=64000000 -daynight.daytimeColor=00FFFFFF - -### Test layer -test.prettyName=Test -test.class=com.bbn.openmap.layer.test.TestLayer -test.line.visible=true -test.circ.visible=true -test.rect.visible=true -test.text.visible=true -test.poly.visible=true -#test.poly.vertices=80 -180 80 -90 80 0 80 90 80 180 70 180 70 90 70 0 70 -90 70 -180 - -### VMAP Political layer - Run the com.bbn.openmap.layer.vpf.VPFConfig -### class to create properties for a set of features. -vmapPolitical.class=com.bbn.openmap.layer.vpf.VPFLayer -vmapPolitical.prettyName=VMAP Political -vmapPolitical.vpfPath=data/vmap/vmaplv0 -vmapPolitical.coverageType=bnd -vmapPolitical.featureTypes=edge area text -# just display coastlines and political boundaries -#vmapPolitical.edge= polbndl coastl depthl -vmapPolitical.edge= polbndl coastl -# just display political areas and not oceans -#vmapPolitical.area= oceansea polbnda -vmapPolitical.area= polbnda - -# Use this property for a better focus on feature types, especially -# for more fine-grained databases -#vmapPolitical.searchByFeature=true - -### VMAP Coastline layer -vmapCoast.class=com.bbn.openmap.layer.vpf.VPFLayer -vmapCoast.prettyName=VMAP Coastline Layer -vmapCoast.vpfPath=data/vmap/vmaplv0 -## a predefined layer from the VPF predefined layer set found in -## com/bbn/openmap/layer/vpf/defaultVPFLayers.properties -vmapCoast.defaultLayer=vmapCoastline - -# Basic political boundaries with DCW -dcwPolitical.class=com.bbn.openmap.layer.vpf.VPFLayer -dcwPolitical.prettyName=DCW Political Boundaries -dcwPolitical.vpfPath=path to DCW data -dcwPolitical.coverageType=po -dcwPolitical.featureTypes=edge area - -# For creating other VPF layer definitions, use the -# com.bbn.openmap.layer.vpf.VPFConfig class, running it directly on a -# VPF data directory. - -# For instance, for inland water, the following properties could be -# used, and 'vmapIW' would be added to the openmap.layers property. - -vmapIW.prettyName=VPF Inland Water -vmapIW.inwatera.selectColor=ff000000 -vmapIW.searchByFeature=true -vmapIW.inwatera.lineWidth=1.0 - -# If you are using a VPF tile cache, specify the library bean name -# here: -vmapIW.libraryBean=VMAPLEVEL0 -# Otherwise, you have to specify the path to the data (parent of the -# .lat file): -#vmapIW.vpfPath=/data/vpf/vmaplv0/disk0 -vmapIW.inwatera.lineColor=ff000000 -vmapIW.inwatera.dashPhase= -vmapIW.inwatera.textColor=ff000000 -vmapIW.coverageType=hydro -vmapIW.inwatera.fillPattern= -vmapIW.class=com.bbn.openmap.layer.vpf.VPFLayer -vmapIW.area=inwatera -vmapIW.inwatera.fillColor=FF0000FF -vmapIW.featureTypes=area -vmapIW.inwatera.dashPattern= -vmapIW.inwatera.matted=false - - -### Java RPF properties -jrpf.class=com.bbn.openmap.layer.rpf.RpfLayer -jrpf.prettyName=CADRG -# This property should reflect the paths to the RPF directories -jrpf.paths=data/RPF -# Number between 0-255: 0 is transparent, 255 is opaque -jrpf.opaque=255 -# Number of colors to use on the maps - 16, 32, 216 -jrpf.number.colors=216 -# Display maps on startup -jrpf.showmaps=true -# Display attribute information on startup -jrpf.showinfo=false -# Scale images to fit the map scale -jrpf.scaleImages=true -jrpf.coverage=true - -### Another Java RPF Layer - usually keep CADRG and CIB separate, -# although you don't have to. -jcib.class=com.bbn.openmap.layer.rpf.RpfLayer -jcib.prettyName=CIB -# This property should reflect the paths to the RPF directories -jcib.paths=data/CIB/RPF -# Number between 0-255: 0 is transparent, 255 is opaque -jcib.opaque=255 -# Number of colors to use on the maps - 16, 32, 216 -jcib.number.colors=216 -# Display maps on startup -jcib.showmaps=true -# Display attribute information on startup -jcib.showinfo=false -# Scale images to fit the map scale -jcib.scaleImages=true - - -### Java DTED Coverage properties -dtedcov.class=com.bbn.openmap.layer.dted.DTEDCoverageLayer -dtedcov.prettyName=DTED Coverage -# This property should reflect the paths to the DTED level 0 and 1 -# directories. These levels can be combined. -dtedcov.paths=data/dted -# DTED Level 2 data! -dtedcov.level2.paths=data/dted2 -# Number between 0-255: 0 is transparent, 255 is opaque -dtedcov.opaque=255 - -# *NOTE* This property needs to be changed to specify a DTED coverage file, -# or the location where you want one created if the layer doesn't find -# it here. If you add or remove coverage from your dted collection, -# you should delete this file so that an accurate one will be created. -dtedcov.coverageFile= - -# This is an optional property. You can substitute a URL for the -# coverage file instead. This is checked first before the coverage -# file, and if a valid file is found at the URL, then the coverage -# file is ignored. The layer does not try to create a file at this -# URL! -#dtedcov.coverageURL=http://dstl.bbn.com/openmap/data/dted/coverage.dat - -### Java DTED properties -jdted.class=com.bbn.openmap.layer.dted.DTEDLayer -jdted.prettyName=DTED -# This property should reflect the paths to the DTED level 0, 1 and 2 -# directories. These levels can be combined. -jdted.paths=data/dted -# Number between 0-255: 0 is transparent, 255 is opaque -jdted.opaque=255 -# Number of colors to use on the maps - 16, 32, 216 -jdted.number.colors=216 -# Level of DTED data to use on startup (0, 1, 2) -jdted.level=0 -# Type of display for the data on startup -# 0 = no shading at all -# 1 = greyscale slope shading -# 2 = band shading, in meters -# 3 = band shading, in feet -# 4 = subframe testing -# 5 = elevation, colored -jdted.view.type=5 -# Contrast setting on startup, 1-5 -jdted.contrast=3 -# height (meters or feet) between color changes in band shading on startup -jdted.band.height=25 -# Minimum scale to display images. Larger numbers mean smaller scale, -# and are more zoomed out. -jdted.min.scale=20000000 - -### -# Java DTED Layer that uses the central DTEDFrameCache. The -# DTEDFrameCache has to be added to the openmap.components list. -jdted2.class=com.bbn.openmap.layer.dted.DTEDFrameCacheLayer -jdted2.prettyName=DTED -# and are more zoomed out. -jdted2.min.scale=50000000 -jdted2.generators=greys colors band -jdted2.greys.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader -jdted2.greys.prettyName=Slope Shading -jdted2.greys.colorsClass=com.bbn.openmap.omGraphics.grid.GreyscaleSlopeColors -jdted2.colors.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader -jdted2.colors.prettyName=Elevation Shading -jdted2.colors.colorsClass=com.bbn.openmap.omGraphics.grid.ColoredShadingColors -jdted2.band.class=com.bbn.openmap.omGraphics.grid.ElevationBandGeneratorLoader -jdted2.band.prettyName=Elevation Bands -jdted2.band.colorsClass=com.bbn.openmap.omGraphics.grid.GreyscaleSlopeColors - -### -# Terrain layer. Requires the DTEDFrameCache being added to the -# openmap.components list. -terrain.class=com.bbn.openmap.layer.terrain.TerrainLayer -terrain.prettyName=Terrain Tools -# The default tool to use for the terrain layer. Can be PROFILE or LOS. -terrain.default.mode=PROFILE - -### -# LocationLayer that holds cities. The palette for this layer lets -# you turn on the names and declutter matrix, if you want. The -# declutter matrix can get expensive at small scales. -cities.class=com.bbn.openmap.layer.location.LocationLayer -cities.prettyName=World Cities -cities.locationHandlers=csvcities -cities.useDeclutter=false -cities.declutterMatrix=com.bbn.openmap.layer.DeclutterMatrix - -csvcities.class=com.bbn.openmap.layer.location.csv.CSVLocationHandler -csvcities.prettyName=World Cities -csvcities.locationFile=data/cities.csv -csvcities.csvFileHasHeader=true -csvcities.locationColor=FF0000 -csvcities.nameColor=008C54 -csvcities.showNames=false -csvcities.showLocations=true -csvcities.nameIndex=0 -csvcities.latIndex=5 -csvcities.lonIndex=4 -csvcities.csvFileHasHeader=true - -# Map Tile Layer, using OpenStreetMap tiles -tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer -tiles.prettyName=OpenStreetMap Tiles - -# Can define root directory of tiles, using absolute or relative path. -# This path example assumes z/x/y.png path to tiles from the root. -#tiles.rootDir=tiles - -# Can also define server, but don't abuse this server! This path definition example uses -# regex to specify format of tile query -tiles.rootDir=http://a.tile.openstreetmap.org/{z}/{x}/{y}.png - -# For remote server, you can also store tiles locally, to reduce load on server. -# You should update this with a valid path local to your machine. -#tiles.localCacheRootDir=./share/data/tiles/osmtiles - -# What to do about empty tiles for bottom-most layer? Set -# up an EmptyTileHandler. Saves disk space for tile storage. Usually -# only applies for homegrown tile sets. -tiles.emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.ShpFileEmptyTileHandler -# Define ocean/background colors for tiles -tiles.background.fillColor=FFFFFF -tiles.background.lineColor=FFFFFF -# Define land color for tiles (empty tiles on land, too) -tiles.land.fillColor=DECD8B -tiles.land.lineColor=DECD8B -# Define zoom level to limit handler response - zoom in past this provides empty coverage (clear) -tiles.noCoverageZoom=13 -# Use shape file to determine which tiles are over land. -tiles.shpFile=data/shape/cntry02/cntry02.shp \ No newline at end of file diff --git a/pom.xml b/pom.xml deleted file mode 100644 index ea4a3f320..000000000 --- a/pom.xml +++ /dev/null @@ -1,133 +0,0 @@ - - - 4.0.0 - org.openmap-java - openmap-all - pom - 6.0 - openmap-all - A Java Beans based toolkit for building applications and applets needing geographic information - http://openmap-java.org - - - - OpenMap Software License - https://github.com/OpenMap-java/openmap/blob/master/LICENSE - repo - - - - BBN Technologies - http://www.bbn.com - - - - Don Dietrick - dfdietrick@gmail.com - - - - scm:git:https://github.com/OpenMap-java/openmap.git - scm:git:https://github.com/OpenMap-java/openmap - https://github.com/OpenMap-java/openmap - - - - https://groups.google.com/forum/#!forum/openmap-users - - - http://openmap-java.org/openmap-users-archives/index.html - - - - - - thirdparty-releases - JBoss Thirdparty Releases - https://repository.jboss.org/nexus/content/repositories/thirdparty-releases - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-release-plugin - 2.4.1 - - true - - - - org.apache.maven.plugins - maven-source-plugin - 3.2.1 - - - attach-sources - install - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - false - private - - - - attach-javadocs - install - - jar - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.1.1 - - - copy-dependencies - package - - copy-dependencies - - - - - - - - - - src/core - - src/wmsservlet - src/maptileservlet - src/vpfbrowseservlet - - - - - - diff --git a/share/data/cities.csv b/share/data/cities.csv deleted file mode 100644 index 4a908371f..000000000 --- a/share/data/cities.csv +++ /dev/null @@ -1,607 +0,0 @@ -CITY_NAME,COUNTRY,POP,CAP,LONGITUDE,LATITUDE -Murmansk,Russia,468000,N,33.0860405,68.96354675 -Arkhangelsk,Russia,416000,N,40.64616013,64.52066803 -Saint Petersburg,Russia,5825000,N,30.45332718,59.95188904 -Magadan,Russia,152000,N,150.780014,59.57099915 -Perm',Russia,1160000,N,56.23246384,58.00023651 -Yekaterinburg,Russia,1620000,N,60.61013031,56.84654236 -Nizhniy Novgorod,Russia,2025000,N,43.94067001,56.28967667 -Glasgow,UK,1800000,N,-4.269947529,55.86280823 -Kazan',Russia,1140000,N,49.14546585,55.73300552 -Chelyabinsk,Russia,1325000,N,61.39261246,55.14500046 -Omsk,Russia,1175000,N,73.25028992,55.0633049 -Novosibirsk,Russia,1600000,N,82.94284821,55.03210068 -Ufa,Russia,1100000,N,56.09612656,54.82173538 -Vilnius,Lithuania,582000,Y,25.27596664,54.68856812 -Belfast,UK,685000,N,-5.909660339,54.58692551 -Gdansk,Poland,909000,N,18.62494278,54.36620331 -Minsk,Byelarus,1650000,Y,27.57556725,53.89993668 -Leeds,UK,1540000,N,-1.49752748,53.80871201 -Hamburg,Germany,2225000,N,10.02760601,53.57112122 -Manchester,UK,2775000,N,-2.261778593,53.47966385 -Sheffield,UK,710000,N,-1.462989211,53.37404251 -Dublin,Ireland,1140000,Y,-6.25734663,53.34156036 -Samara,Russia,1505000,N,50.09617996,53.13859558 -Bremen,Germany,800000,N,8.857625961,53.08010483 -Berlin,Germany,5061248,Y,13.32757282,52.5162735 -Birmingham,UK,2675000,N,-1.863347769,52.49275208 -Amsterdam,Netherlands,1860000,N,4.894833088,52.37304306 -Irkutsk,Russia,626000,N,104.2478333,52.3174324 -Warsaw,Poland,2323000,Y,21.01187897,52.24494553 -Rotterdam,Netherlands,1110000,N,4.485152245,51.92559433 -Lodz,Poland,1061000,N,19.47644043,51.77790833 -Dortmund,Germany,568164,N,7.466418266,51.51381302 -Duisburg,Germany,514628,N,6.775304317,51.48933792 -London,UK,11100000,Y,-0.177998126,51.48791122 -Essen,Germany,3867000,N,7.122435093,51.35404205 -Leipzig,Germany,700000,N,12.39807415,51.3493309 -Antwerpen,Belgium,1100000,N,4.426054478,51.20734787 -Wroclaw,Poland,640200,N,17.0381279,51.12181854 -Gent,Belgium,465000,N,3.73629117,51.04755402 -Dresden,Germany,670000,N,13.70535755,51.045681 -Calgary,Canada,671326,N,-114.0500031,51.02999878 -Koln,Germany,1760000,N,6.934871674,50.94234467 -Bruxelles,Belgium,2385000,Y,4.367612362,50.83704758 -Bonn,Germany,570000,N,7.099818707,50.73455811 -Lille,France,1020000,N,3.062901258,50.63208389 -Liege,Belgium,750000,N,5.569435596,50.62252808 -Kiev,Ukraine,2900000,Y,30.50211143,50.44815826 -Frankfurt am Main,Germany,1855000,N,8.668167114,50.12999725 -Praha,Czech Repub,1325000,Y,14.45652008,50.105896 -Krakow,Poland,828000,N,19.94505692,50.0622406 -Winnipeg,Canada,625304,N,-97.12444305,49.92116928 -Karaganda,Kazakhstan,614000,N,73.20263672,49.87920761 -Lvov,Ukraine,790000,N,24.0345211,49.83731079 -Brno,Czech Repub,450000,N,16.61624527,49.20298004 -Paris,France,9775000,Y,2.432832718,48.88155365 -Volgograd,Russia,1360000,N,44.48363113,48.71024704 -Strasbourg,France,400000,N,7.767994404,48.58343506 -Linz,Austria,335000,N,14.29390144,48.29759598 -Vienna,Austria,1875000,Y,16.32098579,48.20211792 -Munchen,Germany,1955000,N,11.54295349,48.14097595 -Donets'k,Ukraine,2200000,N,37.73705292,48.04014587 -Ulaanbaatar,Mongolia,548400,Y,106.9123535,47.9285965 -Budapest,Hungary,2565000,Y,19.09424973,47.51462555 -Qiqihar,China,1150000,N,123.9649658,47.34400558 -Innsbruck,Austria,185000,N,11.34998226,47.26546097 -Rostov-na-Donu,Russia,1165000,N,39.68803787,47.23209763 -Nantes,France,464857,N,-1.561561227,47.21943283 -Graz,Austria,325000,N,15.43110085,47.06492233 -Bern,Switzerland,298800,Y,7.445736408,46.94820786 -Quebec,Canada,603267,N,-71.24493408,46.80207443 -Odessa,Ukraine,1185000,N,30.68393707,46.57220078 -Harbin,China,2670000,N,126.6226349,45.75521851 -Lyon,France,1275000,N,4.855400562,45.74708176 -Montreal,Canada,2921357,N,-73.65353394,45.54101563 -Milano,Italy,3750000,N,9.19046402,45.47338104 -Venezia,Italy,420000,N,12.37071991,45.42477417 -Ottawa,Canada,819263,Y,-75.65074921,45.37421799 -Torino,Italy,1550000,N,7.666426182,45.07487488 -Minneapolis,US,2012400,N,-93.30779266,44.92418671 -Bordeaux,France,640012,N,-0.599498749,44.84147263 -Beograd,Serbia,1400000,Y,20.41255569,44.79968262 -Bucuresti,Romania,2250000,Y,26.1229763,44.43048477 -Changchung,China,1740000,N,125.3126526,43.88131714 -Jilin,China,1170000,N,126.5670624,43.85021591 -Urumqi,China,1040000,N,87.58651733,43.78266525 -Firenze,Italy,640000,N,11.20774555,43.78157425 -Toronto,Canada,3427168,N,-79.4126358,43.72076797 -Toulouse,France,541271,N,1.437983036,43.59996033 -Bilbao,Spain,985000,N,-2.973783255,43.2821579 -Almaty,Kazakhstan,1190000,Y,76.91262817,43.2550621 -Rochester,US,816200,N,-77.63561249,43.21046448 -Milwaukee,US,1374700,N,-87.99073792,43.06794739 -Sapporo,Japan,1900000,N,141.3454742,43.05525208 -Buffalo,US,1483000,N,-78.84843445,42.89866257 -Sofiya,Bulgaria,1205000,Y,23.33187103,42.70726395 -Detroit,US,4691900,N,-83.07892609,42.39431381 -Boston,US,3971700,N,-71.10258484,42.37529755 -Fushun,China,1270000,N,123.905571,41.85915756 -Chicago,US,7717100,N,-87.64130402,41.82654572 -Shenyang,China,3840000,N,123.3830566,41.80216217 -T'Bilisi,Georgia,1460000,Y,44.78312683,41.72180939 -Zaragoza,Spain,575317,N,-0.878205061,41.65126419 -Cleveland,US,2218400,N,-81.72750854,41.39071655 -Tirane,Albania,210800,Y,19.83180428,41.33165359 -Anshan,China,1300000,N,122.9770126,41.11524582 -Istanbul,Turkey,5750000,N,29.00606918,41.06595612 -Salt Lake City,US,682400,N,-111.8921738,40.69392014 -Pittsburgh,US,2218800,N,-79.99708557,40.49720383 -Madrid,Spain,4650000,Y,-3.690969467,40.44221878 -Baku,Azerbaijan,2020000,Y,49.8162384,40.32429886 -Yerevan,Armenia,1315000,Y,44.53266907,40.20802307 -Columbus,US,963600,N,-82.9927063,40.0446434 -Ankara,Turkey,2400000,Y,32.85327148,39.92932892 -Philadelphia,US,5208600,N,-75.21822357,39.92755127 -Beijing,China,6450000,Y,116.3880386,39.90619278 -Erzurum,Turkey,246053,N,41.29182434,39.90445328 -Samarkand,Uzbekistan,366000,N,66.94760132,39.65758133 -Tangshan,China,1060000,N,118.1802139,39.61544418 -Valencia,Spain,1270000,N,-0.367400944,39.47091675 -Baltimore,US,1960400,N,-76.61837769,39.32188416 -Cagliari,Italy,305000,N,9.108909607,39.22514343 -Cincinnati,US,1480100,N,-84.47702026,39.14801025 -Tianjin,China,4880000,N,117.1852264,39.12841415 -Pyongyang,Korea D P Rp,1600000,Y,125.757515,39.02851486 -Kansas City,US,1272400,N,-94.62656403,38.99411774 -Washington D.C.,US,3221400,Y,-76.95383453,38.8909111 -St. Louis,US,2203000,N,-90.34197998,38.6388855 -Sacramento,US,866400,N,-121.4227066,38.5670166 -Tabriz,Iran,971482,N,46.29011917,38.08097839 -Shijiazhuang,China,1190000,N,114.5597076,38.07709503 -Ashkhabad,Turkmenistan,398000,Y,58.3901329,37.95042038 -Taiyuan,China,1660000,N,112.5517044,37.89305496 -Seoul,Korea Rep,15850000,Y,126.9352493,37.54235077 -Sevilla,Spain,945000,N,-5.970831871,37.37264633 -Adana,Turkey,777554,N,35.32436371,36.99998093 -Norfolk,US,795600,N,-76.26856995,36.87929153 -Tunis,Tunisia,1225000,Y,10.16596031,36.81881332 -Zibo,China,830000,N,118.0620422,36.79149628 -Jinan,China,1460000,N,116.9670563,36.65553665 -Mosul,Iraq,570926,N,43.13712692,36.33556747 -Mashhad,Iran,1463508,N,59.59685135,36.29006958 -Aleppo,Syria,1216000,N,37.15928268,36.21554565 -Lanzhou,China,1270000,N,103.5995941,36.11343002 -Taegu,Korea Rep,2206000,N,128.5913849,35.86353683 -Tehran,Iran,6400000,Y,51.44765091,35.7744751 -Tokyo,Japan,23620000,Y,139.8091888,35.68305588 -Kawasaki,Japan,1088624,N,139.7272186,35.50457001 -Oklahoma City,US,742000,N,-97.53029633,35.48958969 -Yokohama,Japan,2992926,N,139.6196594,35.43738556 -Charlotte,US,479200,N,-80.83568573,35.20581436 -Pusan,Korea Rep,3800000,N,129.0546875,35.15786743 -Nagoya,Japan,4800000,N,136.9205933,35.15492249 -Memphis,US,852900,N,-90.00032806,35.11472702 -Kyoto,Japan,1479218,N,135.7548218,35.00912857 -Zhengzhou,China,1170000,N,113.641777,34.7576828 -Homs,Syria,431000,N,36.71817398,34.73387527 -Luoyang,China,740000,N,112.3612366,34.67134857 -Osaka,Japan,15040000,N,135.5191193,34.63552856 -Kabul,Afghanistan,1179000,Y,69.1367569,34.53090668 -Hiroshima,Japan,1575000,N,132.4447784,34.37755585 -Xian,China,2050000,N,108.8833618,34.26569748 -Fes,Morocco,535000,N,-4.995547771,34.04356766 -Atlanta,US,1962500,N,-84.34922791,33.79570007 -Islamabad,Pakistan,204364,Y,73.06054688,33.71815109 -Rawalpindi,Pakistan,836000,N,73.04374695,33.60580444 -Damascus,Syria,1850000,Y,36.31345367,33.51930237 -Phoenix,US,1482400,N,-112.11026,33.50902176 -Baghdad,Iraq,3841268,Y,44.39783478,33.33403778 -Dallas,US,2727300,N,-96.66368866,32.7637291 -Esfahan,Iran,986753,N,51.67918777,32.65139008 -Nanjing,China,2290000,N,118.7689056,32.04836655 -Amman,Jordan,1250000,Y,35.9329071,31.94938278 -Amritsar,India,594844,N,74.87155151,31.63088989 -Lahore,Pakistan,3025000,N,74.34067535,31.54505348 -Faisalabad,Pakistan,1104209,N,73.08345795,31.40895081 -Shanghai,China,9300000,N,121.4726563,31.24786949 -Chengdu,China,1810000,N,104.0712738,30.67006874 -Wuhan,China,3490000,N,114.2792206,30.57249832 -Al Basra,Iraq,616700,N,47.76086426,30.50349045 -Hangzhou,China,1270000,N,120.1650772,30.25262451 -Cairo,Egypt,9300000,Y,31.25079727,30.07791138 -New Orleans,US,1185000,N,-90.09868622,29.95637894 -Houston,US,2755100,N,-95.40711212,29.77182961 -Lhasa,China,84400,N,91.13208771,29.65070343 -Chongqing,China,2450000,N,106.5226898,29.54410362 -San Antonio,US,968200,N,-98.52457428,29.4299221 -Nanchang,China,1030000,N,115.8894119,28.67123985 -New Delhi,India,273036,Y,77.2167511,28.56872559 -Delhi,India,7200000,N,77.22437286,28.52645874 -Changsha,China,1190000,N,112.968483,28.19764137 -Kathmandu,Nepal,320000,Y,85.31295013,27.71201706 -Thimbu,Bhutan,12000,Y,89.66732788,27.44260597 -Jaipur,India,1025000,N,75.80127716,26.90511322 -Lucknow,India,1060000,N,80.91972351,26.84942818 -Guiyang,China,1010000,N,106.7003021,26.57194138 -Kanpur,India,1875000,N,80.31786346,26.45783043 -Fuzhou,China,890000,N,119.3035202,26.07101631 -Miami,US,2827300,N,-80.2702179,25.83213043 -Monterrey,Mexico,2015000,N,-100.3170853,25.67735291 -Patna,India,1025000,N,85.13534546,25.61389732 -Hyderabad,Pakistan,800000,N,68.36647034,25.38018608 -Benares,India,925000,N,82.95633698,25.28201103 -Doha,Qatar,310000,Y,51.49723434,25.20364189 -Kunming,China,1280000,N,102.7021255,25.05103302 -Taipei,Taiwan,6130000,Y,121.5067291,25.0350914 -T`ai-chung,Taiwan,715107,N,120.6702805,24.14364243 -Dhaka,Bangladesh,3430312,Y,90.40714264,23.70991898 -Guangzhou,China,3050000,N,113.2936096,23.09619522 -Ahmadabad,India,2400000,N,72.56686401,23.03979111 -Khulna,Bangladesh,648359,N,89.5582428,22.84264755 -Calcutta,India,11100000,N,88.33422089,22.54353714 -Tampico,Mexico,435000,N,-97.84262848,22.24323463 -Mandalay,Burma,532895,N,96.08415222,21.97594452 -Mecca,Saudi Arabia,550000,N,39.81483841,21.42738152 -Nagpur,India,1302066,N,79.08911133,21.1557579 -Hanoi,Vietnam,1500000,Y,105.8199081,21.03194809 -Haiphong,Vietnam,385210,N,106.6797943,20.86135864 -Merida,Mexico,400142,N,-89.55286407,20.8218689 -Guadalajara,Mexico,2325000,N,-103.3437958,20.67359161 -Bur Sudan,Sudan,206727,N,37.21968842,19.61571312 -Mexico City,Mexico,14100000,Y,-99.12757111,19.42704582 -Puebla de Zaragoza,Mexico,1055000,N,-98.19294739,19.04863167 -Pune,India,1775000,N,73.85227203,18.53574753 -Port-au-Prince,Haiti,880000,Y,-72.34310913,18.52661705 -San Juan,Puerto Rico,1775260,Y,-66.08175659,18.40061569 -Kingston,Jamaica,770000,Y,-76.79730225,18.01571274 -Hyderabad,India,2750000,N,78.48503113,17.39454651 -Rangoon,Burma,2800000,Y,96.12489319,16.8722229 -Sanaa,Yemen,427150,Y,44.20950317,15.36144447 -Guatemala,Guatemala,1400000,Y,-90.52490234,14.61800766 -Tegucigalpa,Honduras,551606,Y,-87.20309448,14.09905052 -Bangkok,Thailand,6450000,Y,100.5526657,13.74557114 -San Salvador,El Salvador,920000,Y,-89.20023346,13.7014122 -Niamey,Niger,398265,Y,2.083449841,13.60454369 -Madras,India,4475000,N,80.24782562,13.06150341 -Bangalore,India,2950000,N,77.58773041,12.97475052 -Bamako,Mali,646163,Y,-7.986481667,12.65295029 -Managua,Nicaragua,682000,Y,-86.27303314,12.15147305 -Phnom Penh,Cambodia,700000,Y,104.9131927,11.56473637 -Ho Chi Minh City,Vietnam,3100000,N,106.6624527,10.75918198 -Maracaibo,Venezuela,890643,N,-71.637146,10.64504337 -Caracas,Venezuela,3600000,Y,-66.89828491,10.49604893 -Barquisimeto,Venezuela,497635,N,-69.33919525,10.06566525 -San Jose,Costa Rica,670000,Y,-84.07861328,9.930476189 -Madurai,India,960000,N,78.12172699,9.913986206 -Ibadan,Nigeria,1144000,N,3.895278454,7.378840446 -Davao,Philippines,408775,N,125.613678,7.080080032 -Enugu,Nigeria,252500,N,7.492080212,6.450538635 -Medellin,Colombia,2095000,N,-75.59203339,6.241146564 -Accra,Ghana,1250000,Y,-0.200923637,5.558562756 -Abidjan,Ivory Coast,1950000,Y,-4.021886826,5.324857235 -Bogota,Colombia,4260000,Y,-74.080513,4.630219936 -Bangui,Cent Af Rep,473817,Y,18.56234169,4.365856171 -Yaounde,Cameroon,653670,Y,11.51364136,3.865123034 -Medan,Indonesia,1373747,N,98.67559814,3.585242033 -Cali,Colombia,1400000,N,-76.52243805,3.456855297 -Kuala Lumpur,Malaysia,1475000,Y,101.7076721,3.150210381 -Muqdisho,Somalia,600000,Y,45.34414291,2.041177511 -Kisangani,Zaire,282650,N,25.19614792,0.519284904 -Quito,Ecuador,1050000,Y,-78.52428436,-0.229498133 -Iquitos,Peru,178738,N,-73.19149017,-3.752895355 -Fortaleza,Brazil,1825000,N,-38.58890152,-3.783321857 -Brazzaville,Congo,585812,Y,15.28514862,-4.285186768 -Kananga,Zaire,290898,N,22.40277863,-5.89221096 -Dar es Salaam,Tanzania,1300000,Y,39.2533493,-6.817358971 -Bandung,Indonesia,1800000,N,107.6069031,-6.912430286 -Recife,Brazil,2625000,N,-34.91463852,-8.085167885 -Benguela,Angola,155000,N,13.46487999,-12.71773529 -Brasilia,Brazil,1567709,Y,-47.89774704,-15.79210949 -Arequipa,Peru,446942,N,-71.52274323,-16.39753914 -La Paz,Bolivia,992592,Y,-68.14624786,-16.49900627 -Goiania,Brazil,990000,N,-49.25481033,-16.72669983 -Santa Cruz de La Sierra,Bolivia,441717,N,-63.19741821,-17.78879166 -Sucre,Bolivia,86609,N,-65.25588226,-19.04213524 -Belo Horizonte,Brazil,2950000,N,-43.90906906,-19.85172081 -Rio de Janeiro,Brazil,10150000,N,-43.45517731,-22.72157288 -Sao Paulo,Brazil,15175000,N,-46.6228981,-23.58130455 -Santos,Brazil,1065000,N,-46.30949402,-23.95470047 -Gaborone,Botswana,95163,Y,25.79480171,-24.6614418 -Curitiba,Brazil,1700000,N,-49.28450775,-25.43047905 -Pretoria,South Africa,960000,Y,28.21837234,-25.73134613 -Maputo,Mozambique,1069727,Y,32.57369232,-25.96215439 -Johannesburg,South Africa,3650000,N,28.0043087,-26.17895699 -Brisbane,Australia,1149401,N,153.0264893,-27.45391273 -Durban,South Africa,1550000,N,30.94218826,-29.83637238 -Porto Alegre,Brazil,2600000,N,-51.20798874,-30.03953362 -Cordoba,Argentina,1070000,N,-64.17985535,-31.31627846 -Santa Fe,Argentina,292165,N,-60.69784164,-31.61689758 -Mendoza,Argentina,650000,N,-68.8297348,-32.89743805 -Rosario,Argentina,1045000,N,-60.66394043,-32.93773651 -Santiago,Chile,4100000,Y,-70.64751434,-33.47502518 -Port Elizabeth,South Africa,690000,N,25.48429871,-33.88157654 -Sydney,Australia,3364858,N,151.0281982,-33.88977432 -Buenos Aires,Argentina,10750000,Y,-58.40959167,-34.66540146 -Canberra,Australia,271362,Y,149.041626,-35.34992599 -Auckland,New Zealand,850000,N,174.8010559,-36.89325333 -Melbourne,Australia,2832893,N,145.0751038,-37.85295868 -Bahia Blanca,Argentina,223818,N,-62.27406693,-38.72527313 -Christchurch,New Zealand,320000,N,172.6836548,-43.54891586 -Helsinki,Finland,900000,Y,24.97669983,60.19642258 -Sfax,Tunisia,310000,N,10.75925827,34.74523163 -Kobe,Japan,1410834,N,135.181839,34.66384125 -Jerusalem,Israel,490000,N,35.22521973,31.77374649 -Valencia,Venezuela,616224,N,-68.00311279,10.17822075 -Guayaquil,Ecuador,1255000,N,-79.90939331,-2.203816175 -San Francisco,US,4053800,N,-122.308815,37.72751236 -Edinburgh,UK,630000,N,-3.298783302,55.87525177 -Trieste,Italy,239031,N,13.93283749,45.70028305 -Fukuoka,Japan,1750000,N,130.3171844,33.30990601 -Kita Kyushu,Japan,1525000,N,130.7974548,33.68186569 -N'Djamena,Chad,303000,Y,15.24082375,12.10413933 -Tripoli,Libya,990697,Y,13.21182251,32.75161743 -Izmir,Turkey,1550000,N,27.20576859,38.43891907 -Kinshasa,Zaire,3000000,Y,15.46929359,-4.388674736 -Adelaide,Australia,977721,N,138.8706818,-34.91853714 -Jakarta,Indonesia,8600000,Y,106.7624664,-6.293904305 -Semarang,Indonesia,1024940,N,110.4442596,-7.027844429 -Callao,Peru,264133,N,-76.83563232,-12.04354 -Belem,Brazil,1200000,N,-48.31627655,-1.605329037 -Qingdao,China,1270000,N,120.4341278,36.14835358 -Vientiane,Laos,377409,Y,102.6802368,18.00173187 -Salzburg,Austria,220000,N,13.09089851,47.80117035 -Zagreb,Croatia,697925,Y,15.96438599,45.8070755 -Bujumbura,Burundi,273000,Y,29.5335865,-3.269083738 -Nicosia,Cyprus,185000,Y,33.38516235,35.16506958 -Kigali,Rwanda,181600,Y,29.9914856,-2.117935181 -Ljubljana,Slovenia,233200,Y,14.6396122,46.06830215 -Maseru,Lesotho,109382,Y,27.89038849,-29.25671005 -Luxembourg,Luxembourg,133000,Y,6.273255825,49.74040604 -The Hague,Netherlands,770000,Y,4.300624371,51.90362167 -Bratislava,Slovakia,435499,Y,17.26980591,48.27450943 -Saskatoon,Canada,200665,N,-106.6299973,52.11000061 -Regina,Canada,186521,N,-104.6500015,50.40999985 -El Paso,US,1037700,N,-106.4499969,31.78000069 -Jacksonville,US,635900,N,-81.66000366,30.32999992 -Moosonee,Canada,-99,N,-80.73000336,51.33000183 -Schefferville,Canada,1997,N,-67.01000214,54.86000061 -Goose Bay,Canada,-99,N,-60.54999924,53.31000137 -Porto Velho,Brazil,202011,N,-63.90000153,-8.75 -Cuzco,Peru,184550,N,-71.86000061,-13.60000038 -Cuiaba,Brazil,279651,N,-56.04999924,-15.55000019 -Resistencia,Argentina,220104,N,-58.90000153,-27.39999962 -Tombouctoo,Mali,31925,N,-3.00999999,16.76000023 -Maiduguri,Niger,255100,N,13.26000023,11.88000011 -Matadi,Zaire,144742,N,13.44999981,-5.809999943 -Huambo,Angola,203000,N,15.77999973,-12.72999954 -Kimberley,South Africa,145000,N,24.82999992,-28.65999985 -East London,South Africa,320000,N,27.89999962,-33.02999878 -Kahemba,Zaire,-99,N,19,-7.329999924 -Dodoma,Tanzania,54000,N,35.75,-6.179999828 -Narvik,Norway,19080,N,17.29999924,68.34999847 -Herat,Afghanistan,160000,N,62.20999908,34.45999908 -Druzba,Russia,-99,N,37.75,55.88000107 -Kashi,China,146300,N,76,39.47999954 -Chingmei,Taiwan,-99,N,121.5299988,24.97999954 -Hue,Vietnam,165710,N,107.6999969,16.45999908 -Kuching,Malaysia,72555,N,110.4300003,1.5 -Balikpapan,Indonesia,208040,N,116.8600006,-1.210000038 -Chatanga,Russia,-99,N,110.75,50.33000183 -Chita,Russia,-99,N,113.5800018,52.04999924 -Verkhoyvensk,Russia,-99,N,133.4100037,67.58000183 -Yakutsk,Russia,187000,N,129.8300018,62.00999832 -Okhotsk,Russia,-99,N,143.25,59.33000183 -Nikolayevsk,Russia,-99,N,45.52999878,50.08000183 -Yuzhno-Sakhalinsk,Russia,-99,N,142.75,46.95999908 -Alice Springs,Australia,-99,N,133.9299927,-23.62999916 -Cairns,Australia,39096,N,145.7100067,-16.85000038 -Townsville,Australia,106416,N,146.8300018,-19.29999924 -Rockhampton,Australia,59056,N,150.4799957,-23.43000031 -Newcastle,Australia,405089,N,151.9100037,-33 -Hobart,Australia,175082,N,147.5,-43 -Dunedin,New Zealand,109000,N,170.5,-45.86000061 -Victoria,Canada,255547,N,-123.5691071,48.65456772 -Porto Novo,Benin,164000,Y,2.632502794,6.601096153 -Douala,Cameroon,1029731,N,9.706374168,4.136650085 -Vjuag Padang,Indonesia,708465,N,119.7227936,-5.190430164 -Ambon,Indonesia,111914,N,129.3129272,-3.386553288 -Inch`on,Korea Rep,1604000,N,126.7674408,37.58945084 -Dalian,China,1680000,N,121.5981979,39.03171539 -Portland,US,1227200,N,-122.6416779,45.44213104 -Manaus,Brazil,809914,N,-60.01461792,-3.122304916 -Santarem,Brazil,226618,N,-54.61000061,-2.460000038 -Invercargill,New Zealand,52807,N,168.4499969,-46.40999985 -Mtwara,Tanzania,48510,N,40.18000031,-10.26000023 -Toamasina,Madagascar,100000,N,49.40999985,-18.22999954 -Bloemfontein,South Africa,235000,N,26.26000023,-29.14999962 -Bulawayo,Zimbabwe,413814,N,28.70999908,-20.20000076 -Livingstone,Zambia,61296,N,25.87999916,-17.82999992 -Al Madinah,Saudi Arabia,290000,N,39.70000076,24.43000031 -Wadi Halfa,Sudan,-99,N,31.28000069,21.76000023 -Aswan,Egypt,191461,N,32.95000076,24.07999992 -Murzuq,Libya,-99,N,13.90999985,25.90999985 -Tindouf,Algeria,-99,N,-8.159999847,27.70000076 -Agadez,Niger,50164,N,7.980000019,16.95999908 -El Obeid,Sudan,140000,N,30.15999985,13.18000031 -Mbandaka,Zaire,125263,N,18.45999908,0.050000001 -Whitehorse,Canada,15199,N,-135.0099945,60.65000153 -Punte Arenas,Chile,95332,N,-70.80000305,-53.15000153 -Puerto Montt,Chile,84410,N,-73,-41.47999954 -Rio Gallegos,Argentina,-99,N,-69.41000366,-51.70999908 -Comodoro Rivadavia,Argentina,96817,N,-67.5,-45.83000183 -Suez,Egypt,326820,N,32.56000137,29.95999908 -Alexandria,Egypt,3350000,N,29.97780991,31.07460403 -Mocambique,Mozambique,-99,N,40.70000076,-15.05000019 -Bombay,India,9950000,N,73.17234802,19.04534721 -Algiers,Algeria,2547983,Y,2.993693113,36.59649277 -Kharkov,Ukraine,1940000,N,36.20831299,49.98967361 -Dnepropetrovsk,Ukraine,1600000,N,35.13789368,48.42288971 -Tallinn,Estonia,482000,Y,24.75205612,59.27757263 -Uliastay,Mongolia,-99,N,97,47.81000137 -Santo Domingo,Dominican Rp,1313172,Y,-69.91049194,18.49972916 -Bandar Seri Begawan,Brunei,64000,Y,114.9670029,4.933000088 -Banjul,Gambia,95000,Y,-16.49461555,13.44527245 -Port of Spain,Trinidad,370000,Y,-61.49006271,10.63973427 -Acapulco,Mexico,301902,N,-99.93149567,16.97438622 -Anadyr,Russia,-99,N,177.130188,64.40016174 -Angmagssalik,Greenland,2618,N,-37.31186676,65.66999817 -Antofagasta,Chile,185486,N,-70.22544861,-23.8325367 -Aomori,Japan,294045,N,140.6699982,40.75 -Banghazi,Libya,435886,N,20.30867577,32.04305267 -Birdum,Australia,-99,N,133.2200012,-15.75 -Boa Vista,Brazil,-99,N,-60.5,2.75 -Chiclayo,Peru,279527,N,-79.83000183,-6.619999886 -Chimbote,Peru,223341,N,-78.45314789,-8.930100441 -Churchill,Canada,1304,N,-94.18000031,58.71076584 -Cochin,India,685836,N,76.52178192,9.987988472 -Concepcion,Chile,675000,N,-72.85163879,-36.88329697 -Coquimbo,Chile,62186,N,-71.01999664,-31 -Darwin,Australia,72937,N,130.9945526,-12.70149994 -Djibouti,Djibouti,120000,Y,43.09999847,11.5 -Fremantle,Australia,22484,N,115.9345703,-32.04416656 -George Town,Malaysia,495000,N,100.547142,5.349999905 -Godhavn,Greenland,1012,N,-53.63000107,69.38314056 -Godthab,Greenland,12426,Y,-51.58000183,64.27118683 -Halifax,Canada,295990,N,-63.58000183,44.63000107 -Hammerfest,Norway,7208,N,23.90634155,70.3913269 -Igarka,Russia,-99,N,86.55000305,67.34999847 -In Salah,Algeria,18800,N,2.529999971,27.20000076 -Inuvik,Canada,-99,N,-133.6699982,68.26999664 -Kigoma,Tanzania,50044,N,30,-4.949999809 -Kotlas,Russia,69000,N,47,61.15000153 -Laayoune,W Sahara,93875,N,-13.18000031,27 -Manado,Indonesia,217091,N,124.8842392,1.420086145 -Mangalore,India,306078,N,75.16088104,12.94999981 -Marrakech,Morocco,535000,N,-8,31.14999962 -Mbabne,Swaziland,38290,Y,31.19129753,-26.30338097 -Nagasaki,Japan,449382,N,129.8574677,32.88274765 -Natal,Brazil,510106,N,-35.25,-5.78000021 -Nelson,New Zealand,33304,N,173.2700043,-41.29999924 -Nome,US,3500,N,-165.2700043,64.58628082 -Noril`sk,Russia,174000,N,88.09999847,69.33000183 -Nouadnibou,Mauritania,21961,N,-16.82564735,20.89999962 -Novokuznetsk,Russia,600000,N,87.16999817,53.70000076 -Olympia,US,97400,N,-122.8799973,46.91999817 -Padang,Indonesia,296675,N,100.4750595,-0.917578816 -Palembang,Indonesia,786607,N,104.8300018,-3 -Patrai,Greece,154596,N,21.88316917,38.14123917 -Petropavloski-Kamchatskiy,Russia,269000,N,158.7200012,53.20000076 -Podgorica,Montenegro,82500,Y,19.39999962,42.5 -Pointe Noire,Congo,294203,N,12.05809307,-4.638708115 -Port Gentil,Gabon,124400,N,9.153344154,-0.819999993 -Prince Rupert,Canada,16197,N,-130.0480804,54.42028046 -Saint John,Canada,121265,N,-65.64994812,45.33813477 -Saint Louis,Senegal,91485,N,-16.29783821,15.95121002 -Salekhard,Russia,-99,N,66.58000183,66.56999969 -Samsun,Turkey,240674,N,36.36999893,41.31999969 -Sao Luis,Brazil,600000,N,-44.43005753,-2.5 -Sarajevo,Bosnia/Herz,341200,Y,18.43000031,43.86999893 -Scoresbyund,Greenland,-99,N,-22.99632263,70.52857208 -Sept-Iles,Canada,29262,N,-66.40254211,50.282547 -Seward,US,2699,N,-149.4499969,60.11999893 -Skopje,Macedonia,444900,Y,21.53000069,42 -Tamanrasset,Algeria,-99,N,5.550000191,22.82999992 -Thule,Greenland,-99,N,-69,77.66999817 -Tiksi,Russia,-99,N,128.75,71.69999695 -Toliara,Madagascar,55000,N,44.01909256,-23.29015541 -Trujillo,Peru,354301,N,-79,-7.929999828 -Vishakhapatnam,India,603630,N,83.33000183,17.75 -Vorkuta,Russia,116000,N,64.33000183,67.80000305 -Yazd,Iran,230483,N,54.45000076,31.96999931 -Zahedan,Iran,281923,N,60.83000183,29.60000038 -Aden,Yemen,318000,N,45.18000031,12.86115932 -Adis Abeba,Ethiopia,1500000,Y,38.70000076,9.029999733 -Al Kuwayt,Kuwait,1375000,Y,48.0027771,29.19499016 -Antananarivo,Madagascar,663000,Y,47.5,-18.87000084 -Ar Riyad,Saudi Arabia,1250000,Y,46.77000046,24.64999962 -Asmara,Eritrea,275385,Y,38.97000122,15.32999992 -Asuncion,Paraguay,700000,Y,-57.66999817,-25.21999931 -Athinai,Greece,3027331,Y,23.65486336,38.1216011 -Baotou,China,1120000,N,109.9800034,40.65000153 -Barcelona,Spain,4040000,N,2.170000076,41.52999878 -Barranquilla,Colombia,1140000,N,-74.68000031,11.01429462 -Beira,Mozambique,291604,N,35.02317047,-19.76928329 -Beirut,Lebanon,1675000,Y,35.65794373,33.77999878 -Belmopan,Belize,4500,Y,-88.80000305,17.12000084 -Bergen,Norway,239000,N,5.49067831,60.34999847 -Bissau,GuineaBissau,109486,Y,-15.64999962,11.91098976 -Cape Town,South Africa,1790000,N,18.69043159,-33.80400848 -Cardiff,UK,625000,N,-3.150000095,51.5 -Casablanca,Morocco,2475000,N,-7.534091949,33.54441071 -Cayenne,Fr Guiana,38091,Y,-52.40000153,4.920000076 -Chittagong,Bangladesh,1391877,N,91.83279419,22.47999954 -Colombo,Sri Lanka,2050000,Y,80.08833313,7.019999981 -Conakry,Guinea,800000,Y,-12.80000019,9.520000458 -Dakar,Senegal,1428084,Y,-16.84809494,14.63000011 -Denver,US,1405300,N,-105.0699997,39.75 -Dushanfe,Tajikistan,595000,Y,68.90000153,38.63000107 -Edmonton,Canada,785465,N,-113.2699966,53.56999969 -El-Giza,Egypt,1870508,N,30.85000038,30.46999931 -Freetown,Sierra Leone,525000,Y,-12.91027641,8.382770538 -Frunze,Kyrgyzstan,616000,Y,74.76999664,42.88000107 -Genova,Italy,805000,N,8.92229557,44.45508957 -Georgetown,Guyana,188000,Y,-58.16999817,6.769999981 -Goteborg,Sweden,710894,N,12,57.75 -Harare,Zimbabwe,890000,Y,31.02000046,-17.82999992 -Havana,Cuba,2125000,Y,-82.4164505,23.0489521 -Jiddah,Saudi Arabia,1300000,N,39.37330627,21.62000084 -Kampala,Uganda,460000,Y,32.58000183,0.319999993 -Kano,Nigeria,538300,N,8.520000458,11.92000008 -Kao-Hsiung,Taiwan,1845000,N,120.3414841,22.67341614 -Karachi,Pakistan,5300000,N,67.02999878,24.85000038 -Khabarovsk,Russia,601000,N,135.0700073,48.52999878 -Khartoum,Sudan,924000,Y,32.52999878,15.55000019 -Kishinev,Moldova,665000,Y,28.82999992,47 -Kobenhavn,Denmark,1685000,Y,12.55000019,55.72000122 -Lagos,Nigeria,3800000,Y,3.299999952,6.449999809 -Le Havre,France,254595,N,0.219999999,49.32402039 -Libreville,Gabon,235700,Y,9.490456581,-0.504144549 -Lilongwe,Malawi,233973,Y,33.81999969,-13.92000008 -Lima,Peru,4344000,Y,-76.82355499,-12.06799603 -Lisboa,Portugal,2250000,Y,-9.130000114,38.72999954 -Liverpool,UK,1525000,N,-2.766836405,53.42268753 -Lome,Togo,400000,Y,1.350000024,6.28000021 -Los Angeles,US,9763600,N,-118.25,34 -Luanda,Angola,1459900,Y,13.46177864,-9 -Lumumbashi,Zaire,543268,N,27.54999924,-11.68000031 -Lusaka,Zambia,535830,Y,28.17000008,-15.43000031 -Malabo,Eq Guinea,30710,Y,8.819999695,3.644684792 -Manila,Philippines,5474000,Y,121.1734085,14.55000019 -Marseille,France,1225000,N,5.380000114,43.29999924 -Masqat,Oman,50000,Y,58.62747955,23.51663971 -Mazatlan,Mexico,199830,N,-106.2699966,23.36151123 -Mombasa,Kenya,442369,N,39.66999817,-4.019999981 -Monrovia,Liberia,465000,Y,-10.77000046,6.517439365 -Montevideo,Uruguay,1550000,Y,-56.16999817,-34.91999817 -Moskva,Russia,13100000,Y,37.70000076,55.75 -Nairobi,Kenya,1286200,Y,36.83000183,-1.169999957 -Napoli,Italy,2875000,N,14.27000046,40.83000183 -New York,US,16472000,N,-74.09999847,40.75 -Newark,US,329248,N,-74.19999695,40.72000122 -Nouakchott,Mauritania,285000,Y,-15.78286076,18.03000069 -Odense,Denmark,138400,N,9.902998924,55.57453537 -Omdurman,Sudan,526287,N,32.47999954,15.61999989 -Oran,Algeria,628558,N,-0.519999981,35.75 -Oslo,Norway,720000,Y,10.72000027,59.93000031 -Ouagadouou,Burkina Faso,441514,Y,-1.669999957,12.47999954 -Palermo,Italy,723732,N,13.39999962,38.13000107 -Panama,Panama,625000,Y,-79.40000153,8.949999809 -Paramaribo,Suriname,241000,Y,-55.22999954,5.929999828 -Perth,Australia,994472,N,115.9233704,-31.97586441 -Port Moresby,Papua N Guin,152100,Y,147.4145203,-9.550000191 -Porto,Portugal,1225000,N,-8.487948418,41.15000153 -Qandahar,Afghanistan,203000,N,65.5,31.60000038 -Quezon City,Philippines,1326035,N,121.0299988,14.64999962 -Rabat,Morocco,980000,Y,-6.748040676,33.92019653 -Reykjavik,Iceland,137941,Y,-21.3368206,64.31326294 -Riga,Latvia,1005000,Y,24.04999924,56.88000107 -Roma,Italy,3175000,Y,12.52000046,41.88000107 -Salvador,Brazil,2050000,N,-38.47999954,-12.60025692 -Shiraz,Iran,848289,N,52.56999969,29.62999916 -Stockholm,Sweden,1449972,Y,18.08426857,59.24463272 -Surabaja,Indonesia,2027913,N,112.6843719,-7.400000095 -T`ai-nan,Taiwan,656927,N,120.2300034,23.17000008 -Tampa,US,594500,N,-82.59302521,27.99735832 -Tel Aviv-Yafo,Israel,1670000,Y,34.85683441,31.91719818 -Thessaloniki,Greece,706180,N,22.79999924,40.63000107 -Toshkent,Uzbekistan,2325000,Y,69.34986877,41.24793243 -Tripoli,Lebanon,198000,N,36.00706863,34.34375763 -Valparaiso,Chile,675000,N,-71.29933929,-32.90000153 -Vancouver,Canada,1380729,N,-122.9630661,49.27429962 -Vladivostok,Russia,648000,N,131.960434,43.13000107 -Walvis Bay,South Africa,16607,N,14.61710453,-23.10186768 -Windhoek,Namibia,114500,Y,17.10000038,-22.56999969 -Wellington,New Zealand,350000,Y,175.1449432,-41.21039581 -Seattle,US,2077100,N,-122.3166504,47.58855438 -San Diego,US,2098500,N,-117.1254959,32.76145935 -Iquique,Chile,110153,N,-69.91326141,-20.26000023 -Abu Zaby,Untd Arab Em,242975,Y,54.61927032,24.23600769 -San Cristobal,Venezuela,198793,N,-72.00545502,7.576601028 -Astrakhan,Russia,509000,N,48,46.25 -Ghadamis,Libya,-99,N,9.818350792,30.13860321 -Salto,Uruguay,77400,N,-57.70877457,-31.30515289 -Yellowknife,Canada,11753,N,-114.0613632,62.52061462 -Hilo,US,43200,N,-155.0672913,19.71481514 -Honolulu,US,762600,N,-157.8061829,21.32117653 -Anchorage,US,184300,N,-149.1729736,61.18864822 -Fairbanks,US,39900,N,-147.6511841,64.83874512 -Juneau,US,19528,N,-134.1324768,58.39100647 -San Jose,US,629400,N,-121.8474579,37.30810547 -Chihuaha,Mexico,385603,N,-105.9666367,28.5581398 -Veracruz,Mexico,385000,N,-96.08406067,19.00967598 -Oaxaca,Mexico,154223,N,-96.94203949,16.92090607 -Longyearbyen,Norway,-99,N,15.65999985,78.19999695 -Hong Kong,UK,5395997,Y,114.1457062,22.42840576 -Kowloon,UK,774781,N,114.2301178,22.37989616 -Singapore,Singapore,3025000,N,104.1771164,1.229793549 diff --git a/share/data/scenario/org-activities.csv b/share/data/scenario/org-activities.csv deleted file mode 100755 index aff760e2c..000000000 --- a/share/data/scenario/org-activities.csv +++ /dev/null @@ -1,131 +0,0 @@ -org_row,org_id,org_name,phase_col,phase_id,phase_name,start_hour,time,vicinity_id,latitude,longitude,mode,activity,optempo,other,, -7,UA-HQ,UA-HQ,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,MARNEULI-AFLD,41.453,44.809,prepare,,low,,, -8,BIC,BIC,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,MARNEULI-AFLD,41.453,44.809,prepare,,low,,, -9,1-CABN,1-CABN,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,MARNEULI-AFLD,41.453,44.809,prepare,,low,,, -10,2-CABN,2-CABN,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,MARNEULI-AFLD,41.453,44.809,prepare,,low,,, -11,3-CABN,3-CABN,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -12,AVNDET,AVNDET,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -13,NLOS,NLOS,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -14,FSB,FSB,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -15,159-AVNCO,159-AVNCO,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -16,7-158-AVNCO,7-158-AVNCO,2,1,Early-Entry -Airfield,0.00,15-Jan-2005 00:00,VAZIANI-AFLD,41.614,45.048,prepare,,low,,, -7,UA-HQ,UA-HQ,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,MARNEULI-AFLD,41.453,44.809,move,,medium,,, -8,BIC,BIC,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,MARNEULI-AFLD,41.453,44.809,move,,medium,,, -9,1-CABN,1-CABN,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,MARNEULI-AFLD,41.453,44.809,move,,medium,,, -10,2-CABN,2-CABN,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,MARNEULI-AFLD,41.453,44.809,move,,medium,,, -11,3-CABN,3-CABN,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium,,, -12,AVNDET,AVNDET,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium -13,NLOS,NLOS,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium -14,FSB,FSB,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium -15,159-AVNCO,159-AVNCO,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium -16,7-158-AVNCO,7-158-AVNCO,3,2,Move-to-Border,1.00,15-Jan-2005 01:00,VAZIANI-AFLD,41.614,45.048,move,,medium -7,UA-HQ,UA-HQ,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -8,BIC,BIC,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -9,1-CABN,1-CABN,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -10,2-CABN,2-CABN,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -11,3-CABN,3-CABN,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -12,AVNDET,AVNDET,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -13,NLOS,NLOS,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -14,FSB,FSB,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -15,159-AVNCO,159-AVNCO,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -16,7-158-AVNCO,7-158-AVNCO,4,3,Tactical-High-Speed-Approach,3.00,15-Jan-2005 03:00,SHYKHLY,41.305,45.117,move,,high -7,UA-HQ,UA-HQ,5,3A,Defense-0,5.00,15-Jan-2005 05:00,KIROVABAD-ALFA,40.713,46.252,prepare,,low -8,BIC,BIC,5,3A,Defense-0,5.00,15-Jan-2005 05:00,KIROVABAD-BRAVO,40.736,46.219,prepare,,low -9,1-CABN,1-CABN,5,3A,Defense-0,5.00,15-Jan-2005 05:00,KIROVABAD-CHARLIE,40.964,46.323,prepare,,low -10,2-CABN,2-CABN,5,3A,Defense-0,5.00,15-Jan-2005 05:00,KIROVABAD-DELTA,40.673,46.313,prepare,,low -11,3-CABN,3-CABN,5,3A,Defense-0,5.00,15-Jan-2005 05:00,SAFARALIYEV,40.78,46.397,prepare,,low -12,AVNDET,AVNDET,5,3A,Defense-0,5.00,15-Jan-2005 05:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -13,NLOS,NLOS,5,3A,Defense-0,5.00,15-Jan-2005 05:00,SHAMKHOR,40.826,46.018,prepare,,low -14,FSB,FSB,5,3A,Defense-0,5.00,15-Jan-2005 05:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -15,159-AVNCO,159-AVNCO,5,3A,Defense-0,5.00,15-Jan-2005 05:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -16,7-158-AVNCO,7-158-AVNCO,5,3A,Defense-0,5.00,15-Jan-2005 05:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -7,UA-HQ,UA-HQ,6,4,Assault-COG,8.00,15-Jan-2005 08:00,KIROVABAD-ALFA,40.713,46.252,assault,,high -8,BIC,BIC,6,4,Assault-COG,8.00,15-Jan-2005 08:00,KIROVABAD-BRAVO,40.736,46.219,assault,,high -9,1-CABN,1-CABN,6,4,Assault-COG,8.00,15-Jan-2005 08:00,KIROVABAD-CHARLIE,40.964,46.323,assault,,high -10,2-CABN,2-CABN,6,4,Assault-COG,8.00,15-Jan-2005 08:00,KIROVABAD-DELTA,40.673,46.313,assault,,high -11,3-CABN,3-CABN,6,4,Assault-COG,8.00,15-Jan-2005 08:00,SAFARALIYEV,40.78,46.397,assault,,high -12,AVNDET,AVNDET,6,4,Assault-COG,8.00,15-Jan-2005 08:00,DALLYAR-AFLD,40.885,45.95,assault,,high -13,NLOS,NLOS,6,4,Assault-COG,8.00,15-Jan-2005 08:00,SHAMKHOR,40.826,46.018,assault,,high -14,FSB,FSB,6,4,Assault-COG,8.00,15-Jan-2005 08:00,DALLYAR-AFLD,40.885,45.95,assault,,high -15,159-AVNCO,159-AVNCO,6,4,Assault-COG,8.00,15-Jan-2005 08:00,DALLYAR-AFLD,40.885,45.95,assault,,high -16,7-158-AVNCO,7-158-AVNCO,6,4,Assault-COG,8.00,15-Jan-2005 08:00,DALLYAR-AFLD,40.885,45.95,assault,,high -7,UA-HQ,UA-HQ,7,5,Defense-1,18.00,15-Jan-2005 18:00,GYANDZHA-AFLD,40.734,46.319,prepare,,low -8,BIC,BIC,7,5,Defense-1,18.00,15-Jan-2005 18:00,GYANDZHA-AFLD,40.734,46.319,prepare,,low -9,1-CABN,1-CABN,7,5,Defense-1,18.00,15-Jan-2005 18:00,DALMAMEDLI,40.689,46.567,prepare,,low -10,2-CABN,2-CABN,7,5,Defense-1,18.00,15-Jan-2005 18:00,KHANLAR,40.578,46.328,prepare,,low -11,3-CABN,3-CABN,7,5,Defense-1,18.00,15-Jan-2005 18:00,SAFARALIYEV,40.78,46.397,prepare,,low -12,AVNDET,AVNDET,7,5,Defense-1,18.00,15-Jan-2005 18:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -13,NLOS,NLOS,7,5,Defense-1,18.00,15-Jan-2005 18:00,SHAMKHOR,40.826,46.018,prepare,,low -14,FSB,FSB,7,5,Defense-1,18.00,15-Jan-2005 18:00,GYANDZHA-AFLD,40.734,46.319,prepare,,low -15,159-AVNCO,159-AVNCO,7,5,Defense-1,18.00,15-Jan-2005 18:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -16,7-158-AVNCO,7-158-AVNCO,7,5,Defense-1,18.00,15-Jan-2005 18:00,DALLYAR-AFLD,40.885,45.95,prepare,,low -7,UA-HQ,UA-HQ,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,GYANDZHA-AFLD,40.734,46.319,pursuit,,high -8,BIC,BIC,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,GYANDZHA-AFLD,40.734,46.319,pursuit,,high -9,1-CABN,1-CABN,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,DALMAMEDLI,40.689,46.567,pursuit,,high -10,2-CABN,2-CABN,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,KHANLAR,40.578,46.328,pursuit,,high -11,3-CABN,3-CABN,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,KIROVABAD-E,40.673,46.313,pursuit,,high -12,AVNDET,AVNDET,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,DALLYAR-AFLD,40.885,45.95,pursuit,,high -13,NLOS,NLOS,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,SHAMKHOR,40.826,46.018,pursuit,,high -14,FSB,FSB,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,GYANDZHA-AFLD,40.734,46.319,pursuit,,high -15,159-AVNCO,159-AVNCO,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,DALLYAR-AFLD,40.885,45.95,pursuit,,high -16,7-158-AVNCO,7-158-AVNCO,8,6,Pursuit-Exploit,24.00,16-Jan-2005 00:00,DALLYAR-AFLD,40.885,45.95,pursuit,,high -7,UA-HQ,UA-HQ,9,7,Defense-2,34.00,16-Jan-2005 10:00,YEVLAKH-ALFA,40.536,47.143,prepare,,low -8,BIC,BIC,9,7,Defense-2,34.00,16-Jan-2005 10:00,YEVLAKH-BRAVO,40.561,47.145,prepare,,low -9,1-CABN,1-CABN,9,7,Defense-2,34.00,16-Jan-2005 10:00,BARDA-BRAVO,40.427,47.122,prepare,,low -10,2-CABN,2-CABN,9,7,Defense-2,34.00,16-Jan-2005 10:00,BARDA-CHARLIE,40.315,47.396,prepare,,low -11,3-CABN,3-CABN,9,7,Defense-2,34.00,16-Jan-2005 10:00,BARDA-ALFA,40.401,47.121,prepare,,low -12,AVNDET,AVNDET,9,7,Defense-2,34.00,16-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -13,NLOS,NLOS,9,7,Defense-2,34.00,16-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -14,FSB,FSB,9,7,Defense-2,34.00,16-Jan-2005 10:00,YEVLAKH-AFLD,40.628,47.141,prepare,,low -15,159-AVNCO,159-AVNCO,9,7,Defense-2,34.00,16-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -16,7-158-AVNCO,7-158-AVNCO,9,7,Defense-2,34.00,16-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -7,UA-HQ,UA-HQ,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,YEVLAKH-ALFA,40.536,47.143,assault,,high -8,BIC,BIC,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,YEVLAKH-BRAVO,40.561,47.145,assault,,high -9,1-CABN,1-CABN,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,BARDA-BRAVO,40.427,47.122,assault,,high -10,2-CABN,2-CABN,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,BARDA-CHARLIE,40.315,47.396,assault,,high -11,3-CABN,3-CABN,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,BARDA-ALFA,40.401,47.121,assault,,high -12,AVNDET,AVNDET,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,NAETALAN-AFLD,40.508,46.834,assault,,high -13,NLOS,NLOS,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,NAETALAN-AFLD,40.508,46.834,assault,,high -14,FSB,FSB,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,YEVLAKH-AFLD,40.628,47.141,assault,,high -15,159-AVNCO,159-AVNCO,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,NAETALAN-AFLD,40.508,46.834,assault,,high -16,7-158-AVNCO,7-158-AVNCO,10,8,Urban-Assault,40.00,16-Jan-2005 16:00,NAETALAN-AFLD,40.508,46.834,assault,,high -7,UA-HQ,UA-HQ,11,9,Defense-3,52.00,17-Jan-2005 04:00,YEVLAKH-ALFA,40.536,47.143,prepare,,low -8,BIC,BIC,11,9,Defense-3,52.00,17-Jan-2005 04:00,YEVLAKH-BRAVO,40.561,47.145,prepare,,low -9,1-CABN,1-CABN,11,9,Defense-3,52.00,17-Jan-2005 04:00,BARDA-BRAVO,40.427,47.122,prepare,,low -10,2-CABN,2-CABN,11,9,Defense-3,52.00,17-Jan-2005 04:00,BARDA-CHARLIE,40.315,47.396,prepare,,low -11,3-CABN,3-CABN,11,9,Defense-3,52.00,17-Jan-2005 04:00,BARDA-ALFA,40.401,47.121,prepare,,low -12,AVNDET,AVNDET,11,9,Defense-3,52.00,17-Jan-2005 04:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -13,NLOS,NLOS,11,9,Defense-3,52.00,17-Jan-2005 04:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -14,FSB,FSB,11,9,Defense-3,52.00,17-Jan-2005 04:00,YEVLAKH-AFLD,40.628,47.141,prepare,,low -15,159-AVNCO,159-AVNCO,11,9,Defense-3,52.00,17-Jan-2005 04:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -16,7-158-AVNCO,7-158-AVNCO,11,9,Defense-3,52.00,17-Jan-2005 04:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -7,UA-HQ,UA-HQ,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,BARDA-ALFA,40.401,47.121,assault,,high -8,BIC,BIC,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,BARDA-BRAVO,40.427,47.122,assault,,high -9,1-CABN,1-CABN,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,MIR-BASHIR,40.332,46.934,assault,,high -10,2-CABN,2-CABN,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,BARDA-CHARLIE,40.315,47.396,assault,,high -11,3-CABN,3-CABN,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,BARDA-DELTA,40.352,47.038,assault,,high -12,AVNDET,AVNDET,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,assault,,high -13,NLOS,NLOS,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,assault,,high -14,FSB,FSB,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,YEVLAKH-AFLD,40.628,47.141,assault,,high -15,159-AVNCO,159-AVNCO,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,assault,,high -16,7-158-AVNCO,7-158-AVNCO,12,10,Mech-Move-Air-Assault,58.00,17-Jan-2005 10:00,NAETALAN-AFLD,40.508,46.834,assault,,high -7,UA-HQ,UA-HQ,13,11,Reconstitution,70.00,17-Jan-2005 22:00,BARDA-ALFA,40.401,47.121,prepare,,low -8,BIC,BIC,13,11,Reconstitution,70.00,17-Jan-2005 22:00,BARDA-BRAVO,40.427,47.122,prepare,,low -9,1-CABN,1-CABN,13,11,Reconstitution,70.00,17-Jan-2005 22:00,MIR-BASHIR,40.332,46.934,prepare,,low -10,2-CABN,2-CABN,13,11,Reconstitution,70.00,17-Jan-2005 22:00,BARDA-CHARLIE,40.315,47.396,prepare,,low -11,3-CABN,3-CABN,13,11,Reconstitution,70.00,17-Jan-2005 22:00,BARDA-DELTA,40.352,47.038,prepare,,low -12,AVNDET,AVNDET,13,11,Reconstitution,70.00,17-Jan-2005 22:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -13,NLOS,NLOS,13,11,Reconstitution,70.00,17-Jan-2005 22:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -14,FSB,FSB,13,11,Reconstitution,70.00,17-Jan-2005 22:00,YEVLAKH-AFLD,40.628,47.141,prepare,,low -15,159-AVNCO,159-AVNCO,13,11,Reconstitution,70.00,17-Jan-2005 22:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -16,7-158-AVNCO,7-158-AVNCO,13,11,Reconstitution,70.00,17-Jan-2005 22:00,NAETALAN-AFLD,40.508,46.834,prepare,,low -7,UA-HQ,UA-HQ,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -8,BIC,BIC,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -9,1-CABN,1-CABN,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -10,2-CABN,2-CABN,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -11,3-CABN,3-CABN,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -12,AVNDET,AVNDET,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -13,NLOS,NLOS,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -14,FSB,FSB,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -15,159-AVNCO,159-AVNCO,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low -16,7-158-AVNCO,7-158-AVNCO,14,12,Redeploy,72.00,18-Jan-2005 00:00,TANRYKULULAR-AFLD,40.735,46.859,redeploy,,low diff --git a/share/data/scenario/org-list.csv b/share/data/scenario/org-list.csv deleted file mode 100755 index f14fa8703..000000000 --- a/share/data/scenario/org-list.csv +++ /dev/null @@ -1,11 +0,0 @@ -org_id,org_name,UIC,org_long_name,org_comment,icon_url -UA-HQ,UA-HQ,,UA Headquarters,,/Users/dietrick/Desktop/testicon.gif -BIC,BIC,,Brigade Intel and Comm,,/Users/dietrick/Desktop/testicon.gif -1-CABN,1-CABN,,1st Combined Arms Battalion,,/Users/dietrick/Desktop/testicon.gif -2-CABN,2-CABN,,2nd Combined Arms Battalion,,/Users/dietrick/Desktop/testicon.gif -3-CABN,3-CABN,,3rd Combined Arms Battalion,,/Users/dietrick/Desktop/testicon.gif -AVNDET,AVNDET,,Aviation detachment,,/Users/dietrick/Desktop/testicon.gif -NLOS,NLOS,,Non-Line of Sight Battalion,,/Users/dietrick/Desktop/testicon.gif -FSB,FSB,,Forward Support Battalion,,/Users/dietrick/Desktop/testicon.gif -159-AVNCO,159-AVNCO,WC5LAA,159th Av Co Hvy Hel,(CH-47s or Chinooks),/Users/dietrick/Desktop/testicon.gif -7-158-AVNCO,7-158-AVNCO,WC3EAA,7/158 AV Co Aslt Hel,(UH-60s or Blackhawks),/Users/dietrick/Desktop/testicon.gif diff --git a/share/data/shape/cntry02/cntry02.avl b/share/data/shape/cntry02/cntry02.avl deleted file mode 100755 index 0b7656250..000000000 --- a/share/data/shape/cntry02/cntry02.avl +++ /dev/null @@ -1,350 +0,0 @@ -/3.1 -(ODB.1 - FirstRootClassName: "Legend" - Roots: 2 - Version: 31 -) - -(Legend.2 - SymType: 0x02 - LegType: 0x08 - ClassType: 0x03 - FieldNames: 3 - Symbols: 4 - Class: 41 - Class: 42 - Class: 43 - Class: 44 - Class: 45 - Class: 46 - Class: 47 - Class: 48 - Class: 49 - StdDevs: 1.00000000000000 - NullSym: 50 - NullValues: 54 - StatValues: 55 - Precision: -3 -) - -(AVStr.3 - S: "Color_map" -) - -(SymList.4 - Child: 5 - Child: 9 - Child: 13 - Child: 17 - Child: 21 - Child: 25 - Child: 29 - Child: 33 - Child: 37 -) - -(BShSym.5 - Color: 6 - Outline: 1 - OutlineColor: 7 - OutlineWidth: 0.10000000000000 - BgColor: 8 -) - -(TClr.6 - Red: 0xd2d2 - Green: 0xd2d2 - Blue: 0xd2d2 -) - -(TClr.7 -) - -(TClr.8 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.9 - Color: 10 - Outline: 1 - OutlineColor: 11 - OutlineWidth: 0.10000000000000 - BgColor: 12 -) - -(TClr.10 - Red: 0x9d90 - Green: 0xc0ff - Blue: 0xc0fd -) - -(TClr.11 -) - -(TClr.12 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.13 - Color: 14 - Outline: 1 - OutlineColor: 15 - OutlineWidth: 0.10000000000000 - BgColor: 16 -) - -(TClr.14 - Red: 0xdfff - Green: 0xc765 - Blue: 0xaa9f -) - -(TClr.15 -) - -(TClr.16 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.17 - Color: 18 - Outline: 1 - OutlineColor: 19 - OutlineWidth: 0.10000000000000 - BgColor: 20 -) - -(TClr.18 - Red: 0xa1c6 - Green: 0xd1ff - Blue: 0x97c1 -) - -(TClr.19 -) - -(TClr.20 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.21 - Color: 22 - Outline: 1 - OutlineColor: 23 - OutlineWidth: 0.10000000000000 - BgColor: 24 -) - -(TClr.22 - Red: 0xe2ff - Green: 0xa6b3 - Blue: 0xa6b3 -) - -(TClr.23 -) - -(TClr.24 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.25 - Color: 26 - Outline: 1 - OutlineColor: 27 - OutlineWidth: 0.10000000000000 - BgColor: 28 -) - -(TClr.26 - Red: 0xcbb1 - Green: 0xa68b - Blue: 0xcbff -) - -(TClr.27 -) - -(TClr.28 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.29 - Color: 30 - Outline: 1 - OutlineColor: 31 - OutlineWidth: 0.10000000000000 - BgColor: 32 -) - -(TClr.30 - Red: 0xfeff - Green: 0xa45a - Blue: 0xa45a -) - -(TClr.31 -) - -(TClr.32 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.33 - Color: 34 - Outline: 1 - OutlineColor: 35 - OutlineWidth: 0.10000000000000 - BgColor: 36 -) - -(TClr.34 - Red: 0xa829 - Green: 0xacc0 - Blue: 0xd1ff -) - -(TClr.35 -) - -(TClr.36 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(BShSym.37 - Color: 38 - Outline: 1 - OutlineColor: 39 - OutlineWidth: 0.10000000000000 - BgColor: 40 -) - -(TClr.38 - Name: "Transparent" -) - -(TClr.39 - Name: "Transparent" -) - -(TClr.40 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(LClass.41 - IsText: 1 - Label: "1" - MinStr: "1" - MaxStr: "1" - Precision: -3 -) - -(LClass.42 - IsText: 1 - Label: "2" - MinStr: "2" - MaxStr: "2" - Precision: -3 -) - -(LClass.43 - IsText: 1 - Label: "3" - MinStr: "3" - MaxStr: "3" - Precision: -3 -) - -(LClass.44 - IsText: 1 - Label: "4" - MinStr: "4" - MaxStr: "4" - Precision: -3 -) - -(LClass.45 - IsText: 1 - Label: "5" - MinStr: "5" - MaxStr: "5" - Precision: -3 -) - -(LClass.46 - IsText: 1 - Label: "6" - MinStr: "6" - MaxStr: "6" - Precision: -3 -) - -(LClass.47 - IsText: 1 - Label: "7" - MinStr: "7" - MaxStr: "7" - Precision: -3 -) - -(LClass.48 - IsText: 1 - Label: "8" - MinStr: "8" - MaxStr: "8" - Precision: -3 -) - -(LClass.49 - IsNoData: 1 - IsText: 1 - Label: "No Data" - Precision: -3 -) - -(BShSym.50 - Color: 51 - Outline: 1 - OutlineColor: 52 - OutlineWidth: 0.10000000000000 - BgColor: 53 -) - -(TClr.51 - Name: "Transparent" -) - -(TClr.52 - Name: "Transparent" -) - -(TClr.53 - Red: 0xffff - Green: 0xffff - Blue: 0xffff -) - -(NameDict.54 -) - -(NameDict.55 -) - diff --git a/share/data/shape/cntry02/cntry02.dbf b/share/data/shape/cntry02/cntry02.dbf deleted file mode 100755 index e2780cec2..000000000 Binary files a/share/data/shape/cntry02/cntry02.dbf and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.prj b/share/data/shape/cntry02/cntry02.prj deleted file mode 100755 index c0c079216..000000000 Binary files a/share/data/shape/cntry02/cntry02.prj and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.sbn b/share/data/shape/cntry02/cntry02.sbn deleted file mode 100755 index 12d608f90..000000000 Binary files a/share/data/shape/cntry02/cntry02.sbn and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.sbx b/share/data/shape/cntry02/cntry02.sbx deleted file mode 100755 index dbe7f83c6..000000000 Binary files a/share/data/shape/cntry02/cntry02.sbx and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.shp b/share/data/shape/cntry02/cntry02.shp deleted file mode 100755 index cf5daa5f8..000000000 Binary files a/share/data/shape/cntry02/cntry02.shp and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.shp.xml b/share/data/shape/cntry02/cntry02.shp.xml deleted file mode 100755 index d53fde2c8..000000000 --- a/share/data/shape/cntry02/cntry02.shp.xml +++ /dev/null @@ -1,2180 +0,0 @@ - - - - - {1F7DDF21-BC01-4C20-8AA5-243B33ED0B1E} - 20000920 - 15021200 - 20020215 - 23045100 - 20020215 - 23045100 - FALSE - {77372682-270E-11D6-84B2-0080C7991770} - - Microsoft Windows 2000 Version 5.0 (Build 2195) Service Pack 2; ESRI ArcCatalog 8.1.3.679 - - en - World Countries 2002 represents the boundaries for the countries of the world, as they existed in 2002. - World Countries 2002 provides political boundaries for the world in 2002. To display World Political Organization Membership attributes or CountryWatch Demographics attributes, join these tables to this attribute table using Fips_cntry or Cntry_name as the common field. - Largest scale when displaying the data: 1:15,000,000. - - - - 20020401 - World Countries 2002 - cntry02 - vector digital data - 2002 - - ESRI Data & Maps - 2002 - - - Redlands, California, USA - Environmental Systems Research Institute, Inc. (ESRI) - - Location: ESRI Data & Maps 2002 (CD 1) \world - Environmental Systems Research Institute, Inc. (ESRI) - - - - publication date: 1996, 1998, Winter 1993/1994, 20000101, 20000225, 20010128, 20000612; ground condition: 1994 - - - - Complete - Matches software update releases - - - - -180.000000 - 180.000000 - 83.623596 - -90.000000 - - - -180.000000 - 180.000000 - -90.000000 - 83.623596 - - - - - None - polygon - countries - international boundaries - coastlines - area - international codes - currencies - sovereignties - population - landlocked information - boundaries - society - - - World - None - - - None - 1996 - 1998 - 1993/1994 - 2000 - 1994 - 2000 - 2001 - 2000 - - - Access granted to Licensee only. - The data are provided by multiple, third party data vendors under license to ESRI for inclusion on ESRI Data & Maps CD–ROMs for use with ESRI® software. Each data vendor has its own data licensing policies and may grant varying redistribution rights to end users. Please consult the redistribution rights below for this data set provided on ESRI Data & Maps CD–ROMs. As used herein, “Geodata†shall mean any digital data set consisting of geographic data coordinates and associated attributes. - -The redistribution rights for this data set: Redistribution rights are granted by the data vendor for hard-copy renditions or static, electronic map images (e.g. .gif, .jpeg, etc.) that are plotted, printed, or publicly displayed with proper metadata and source/copyright attribution to the respective data vendor(s). Geodata is redistributable with a Value-Added Software Application developed by ESRI Business Partners on a royalty-free basis with proper metadata and source/copyright attribution to the respective data vendor(s). Geodata is redistributable without a Value-Added Software Application (i.e., adding the sample data to an existing, [non]commercial data set for redistribution) with proper metadata and source/copyright attribution to the respective data vendor(s). - -The terms and conditions below apply to all the data sets provided on the ESRI Data & Maps CD–ROMs. - -Proprietary Rights and Copyright: Licensee acknowledges that the Data and Related Materials contain proprietary and confidential property of ESRI and its licensor(s). The Data and Related Materials are owned by ESRI and its licensor(s) and are protected by United States copyright laws and applicable international copyright treaties and/or conventions. - -Limited Warranty and Disclaimer: ESRI warrants that the media upon which the Data and Related Materials are provided will be free from defects in materials and workmanship under normal use and service for a period of ninety (90) days from the date of receipt. - -THE DATA AND RELATED MATERIALS ARE EXCLUDED FROM THE LIMITED WARRANTY, AND THE LICENSEE EXPRESSLY ACKNOWLEDGES THAT THE DATA CONTAINS SOME NONCONFORMITIES, DEFECTS, OR ERRORS. ESRI DOES NOT WARRANT THAT THE DATA WILL MEET LICENSEE'S NEEDS OR EXPECTATIONS; THAT THE USE OF THE DATA WILL BE UNINTERRUPTED; OR THAT ALL NONCONFORMITIES, DEFECTS, OR ERRORS CAN OR WILL BE CORRECTED. ESRI IS NOT INVITING RELIANCE ON THIS DATA, AND THE LICENSEE SHOULD ALWAYS VERIFY ACTUAL DATA. - -EXCEPT FOR THE LIMITED WARRANTY SET FORTH ABOVE, THE DATA AND RELATED MATERIALS CONTAINED THEREIN ARE PROVIDED "AS-IS," WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. - -Exclusive Remedy and Limitation of Liability: The entire liability of ESRI or its licensor(s) and Licensee's exclusive remedy shall be to terminate the Agreement upon Licensee returning the Data and Related Materials to ESRI with a copy of Licensee's invoice/receipt and ESRI returning the license fees paid to Licensee. - -IN NO EVENT SHALL ESRI AND/OR ITS LICENSOR(S) BE LIABLE FOR COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOST PROFITS, LOST SALES, OR BUSINESS EXPENDITURES, INVESTMENTS, OR COMMITMENTS IN CONNECTION WITH ANY BUSINESS; LOSS OF ANY GOODWILL; OR FOR ANY INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT OR USE OF THE DATA AND RELATED MATERIALS, HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, AND WHETHER OR NOT ESRI OR ITS LICENSOR(S) HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THESE LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF ANY EXCLUSIVE REMEDY. - -Third Party Beneficiary: ESRI's licensor(s) has (have) authorized ESRI to (sub)distribute and (sub)license its (their) data as incorporated into the Data and Related Materials. As an intended third party beneficiary to this Agreement, the ESRI licensor(s) is (are) entitled to directly enforce, in its own name, the rights and obligations undertaken by the Licensee and to seek all legal and equitable remedies as are afforded to ESRI. - -In the event that the data vendor(s) has (have) granted the end user permission to redistribute the Geodata, please use proper proprietary or copyright attribution for the various data vendor(s), and provide the associated metadata file(s) with the Geodata. In compliance with FGDC metadata standards, ESRI has attempted to practice proper metadata methodologies by providing any data source information, descriptions, and file names to assist in this effort. - Shapefile - - - - Environmental Systems Research Institute, Inc. (ESRI) - Data Team - - - mailing and physical address -

380 New York Street
- Redlands - California - 92373-8100 - USA - - 909-793-2853 - 909-793-5953 - info@esri.com - 8:00 a.m.–5:30 p.m. Pacific time, Monday–Friday - In the United States– -Please direct all inquiries regarding software/data pricing and consulting services to your local ESRI Regional Office. For support, you may contact Technical Support by telephone (voice) between 6:00 a.m. and 6:00 p.m. Pacific time, Monday through Friday, by dialing 909-793-3774; facsimile (fax) available at 909-792-0960; electronic mail (e-mail) support@esri.com; or visit http://support.esri.com; ESRI holidays excluded. - -Outside the United States– -Please direct all inquiries regarding software/data pricing, sales, support, and consulting services to your local ESRI International Distributor. This information can be found at http://gis.esri.com/intldist/contactint.cfm. - -For other questions or comments, you may contact ESRI headquarters by e-mail, telephone, or fax or write to us. - - - National Geographic Society - - - en - FGDC Content Standards for Digital Geospatial Metadata - FGDC-STD-001-1998 - local time - - - - Data Team - Environmental Systems Research Institute, Inc. (ESRI) - - - mailing and physical address - Redlands - California - 92373-8100 -
380 New York Street
- USA -
- 909-793-2853 - 909-793-5953 - info@esri.com - 8:00 a.m.–5:30 p.m. Pacific time, Monday–Friday -
-
- 20020215 - - http://www.esri.com/metadata/esriprof80.html - ESRI Metadata Profile - -
- - Vector - - - Simple - Polygon - FALSE - 251 - TRUE - FALSE - World Country (2002) - - - G-polygon - 251 - - - - - - - GCS_WGS_1984 - - - Decimal degrees - 0.000001 - 0.000001 - - - D_WGS_1984 - WGS_1984 - 6378137.000000 - 298.257224 - - - - - - - cntry02 - Feature Class - 251 - The polygons represent the boundaries for the countries of the world, as they existed in 2002. - ESRI - - - FID - FID - OID - 4 - 0 - 0 - Internal feature number. - ESRI - - Sequential unique whole numbers that are automatically generated. - - - - Shape - Shape - Geometry - 0 - 0 - 0 - Feature geometry. - ESRI - - Coordinates defining the features. - - - - FIPS_CNTRY - FIPS_CNTRY - String - 2 - The FIPS code (two-letter) for the country. - Department of Commerce, National Institute of Standards and Technology - - - Federal Information Processing Standards Publication 10-4 - National Institute of Standards and Technology - - - - - GMI_CNTRY - GMI_CNTRY - String - 3 - - - Global Mapping International Codes - Global Mapping International - - - The country code (three-letter) for the country from Global Mapping International. - Global Mapping International - - - ISO_2DIGIT - ISO_2DIGIT - String - 2 - - - ISO 3166-1 Alpha-2 codes - International Organization for Standardization - - - The country code (two-letter) for the country from the International Organization for Standardization. - International Organization for Standardization - - - ISO_3DIGIT - ISO_3DIGIT - String - 3 - - - ISO 3166-1 Alpha-3 codes - International Organization for Standardization - - - The country code (three-letter) for the country from the International Organization for Standardization. - International Organization for Standardization - - - CNTRY_NAME - CNTRY_NAME - String - 40 - - Names for the features. - - The country name. - ArcWorld Supplement, Geographic and Global Issues, CIA Factbook - - - LONG_NAME - LONG_NAME - String - 40 - The official country name. - - Names for the features. - - ArcWorld Supplement, Geographic and Global Issues, CIA Factbook - - - SOVEREIGN - SOVEREIGN - String - 40 - The name of the sovereign for the country. - ArcWorld Supplement, CIA Factbook - - Names for the features. - - - - POP_CNTRY - POP_CNTRY - Number - 10 - The 1994 estimated population of the country. - National Center for Geographic Information and Analysis - - - -99999 - No population data available. - ESRI - - - - - CURR_TYPE - CURR_TYPE - String - 16 - The type of currency for the country. - ArcWorld Supplement - - Names for the features. - - - - CURR_CODE - CURR_CODE - String - 4 - The abbreviation (three-letter) for the currency of the country. - ArcWorld Supplement - - Names for the features. - - - - LANDLOCKED - LANDLOCKED - String - 1 - Indicates if the country is landlocked. - - - Y - The country is landlocked. - ArcWorld Supplement - - - The country is not landlocked. - ArcWorld Supplement - N - - - ArcWorld Supplement - - - SQKM - SQKM - Number - 12 - 2 - The country area in square kilometers using an equal area projection. - ESRI - - Calculated areas for the features. - - - - SQMI - SQMI - Number - 12 - 2 - The country area in square miles using an equal area projection. - ESRI - - Calculated areas for the features. - - - - COLOR_MAP - COLOR_MAP - String - 1 - The number allows the country to be shaded unique from its neighbors. - ESRI - - - 1 - 8 - - - - - - - - - - 3.830 - 3.830 - SHP - no compression applied - The SHP file contains the geospatial data. The SHX file contains the index of the geospatial data. The DBF file contains the attribute data in dBASE format. The PRJ file contains the coordinate system information (optional). The AVL file contains the legend information (optional). The SBN and SBX files contain the spatial index of the geospatial data (optional). The XML file contains the metadata describing the data set <data set name>.shp.xml (optional). - - - - ESRI Data & Maps 2002 CD–ROM Set is available only as part of ESRI® software. - - 650 - MB (megabytes) - - ISO 9660 - - - - Software purchase price - - - - - Environmental Systems Research Institute, Inc. (ESRI); ESRI International Distributors - - In the United States, contact the ESRI Telesales staff at 800-447-9778 for more information about our software and data. - -Outside the United States, please direct all inquiries to your local ESRI International Distributor. This information can be found at http://gis.esri.com/intldist/contactint.cfm. - - mailing and physical address -
380 New York Street
- Redlands - California - 92373-8100 - USA -
- 800-447-9778 -
-
- To use this data requires software that supports ArcView® GIS shapefiles. - See use constraints. - Offline Data -
- - - - - - ArcWorld Supplement - Environmental Systems Research Institute, Inc. (ESRI) - 1996 - 1 - vector digital data - - - Environmental Systems Research Institute, Inc. (ESRI) - Redlands, California, USA - - - - 3000000 - CD–ROM - - - - 1996 - - - publication date - - ArcWorld Supplement - Attribute and geospatial data - - - The following steps were performed by ESRI for Data & Maps 2002: Updated Saudi Arabia - Yemen border. Updated attributes for East Timor, Yugoslavia, Saudi Arabia, and Yemen. Recalculated attributes based on area. Created ArcGIS™ layer file (.lyr) and ArcView legend file (.avl). Copied projection file (.prj) and created spatial indices. - -The following steps were performed by ESRI: Extracted the features from ESRI Data & Maps 1999 data set–cntry98.shp. Updated political boundaries and attributes for 2000 for Macau, Hong Kong, and East Timor. Extended political boundaries into the Caspian Sea and removed the shoreline. Created ArcGIS™ layer file (.lyr). Created ArcView legend file (.avl). Created projection file (.prj). Created spatial indices. - ArcInfo, ArcView 3.x, ArcGIS 8.x - ArcWorld Supplement - 20020212 - Geographic and Global Issues - CIA Factbook - World Demography Project - ESFN FIPS 10-4 20000225 - ESFN FIPS 10-4 20010128 - TREATY OF JEDDAH, 2000 - - - Geographic and Global Issues - Attribute data - - - United States Department of State, Bureau of Intelligence and Research - Winter 1993/1994 - Geographic and Global Issues Quarterly - Volume 3, Number 4 - - Geographic and Global Issues Quarterly - Volume 3, Number 4 - - - Washington, DC, USA - United States Department of State, Bureau of Intelligence and Research - - - - paper - - - - Winter 1993/1994 - - - publication date - - - - - - The World Factbook 2000 - United States Central Intelligence Agency - 20000101 - 2000 - - The World Factbook - 2000 - - - Washington, DC, USA - United States Central Intelligence Agency - - - - online - - - - 20000101 - - - publication date - - CIA Factbook - Attribute data - - - paper - NCGIA - - - National Center for Geographic Information and Analysis - 199504 - World Demography Project - - Santa Barbara, California, USA - National Center for Geographic Information and Analysis at University of California, Santa Barbara - - - - - - - 1994 - - - ground condition - - Attribute data - - - - - COUNTRIES, DEPENDENCIES, AREAS OF SPECIAL SOVEREIGNTY, AND THEIR PRINCIPAL ADMINISTRATIVE DIVISIONS - Executive Secretary for Foreign Names - US Board on Geographic Names - 20000225 - 4 - tabular digital data - - FIPS 10-4 - - - Bethesda, Maryland, USA - National Imagery and Mapping Agency - - - - ESFN FIPS 10-4 20000225 - Attribute data - - - - 20000225 - - - publication date - - - - Attribute data - ESFN FIPS 10-4 20010128 - - - COUNTRIES, DEPENDENCIES, AREAS OF SPECIAL SOVEREIGNTY, AND THEIR PRINCIPAL ADMINISTRATIVE DIVISIONS - Executive Secretary for Foreign Names - US Board on Geographic Names - 20010128 - 6 - tabular digital data - - FIPS 10-4 - - - Bethesda, Maryland, USA - National Imagery and Mapping Agency - - - - - - - 20010128 - - - publication date - - - - - - International Border Treaty between the Republic of Yemen and the Kingdom of Saudi Arabia - 20000612 - THE TREATY OF JEDDAH, 2000 - document - http://www.al-bab.com/yemen/pol/int5.htm - - online - Yemen Gateway - "BAB AL-YEMEN" - - - - online - Attribute and geospatial data - - - - 20000612 - - - publication date - - TREATY OF JEDDAH, 2000 - - - - - The geospatial part of this data set was originally extracted from the ArcWorld Supplement database and then generalized (tolerance unknown). The positional accuracy is unknown. - - - No duplicate features are present. The shapefile is created directly from a topologically correct ArcInfo™ coverage. - After processing, the data set is checked for drawing display and number of records and file sizes compared with source materials. - - - - Qk3uNwEAAAAAADYAAAAoAAAAyAAAAIUAAAABABgAAAAAALg3AQAAAAAAAAAAAAAAAAAAAAAA//// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -tL69wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O -wM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/OwM/O3t/e//////////////////////////// -////////////////////////////////////////s8/O1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//zs/O//////////////////////////////////////////////////////////////// -////s8/O1v//1v//1v//1v//1v//1v//yu/vs8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/O -s8/Os8/Os8/Oyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//zs/O//////////////////////// -////////////////////////////////////////////ub69zs/Ozs/Ozs/Ozs/Ozs/Ozs/Ozs/O -////////////////////3t/esL69s8/Os8/Os8/Os8/Os8/Os8/Oyu/v1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vs8/Op769sL69 -wM/OwM/OwM/O3t/e//////////////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/vvb69jI2Mm66ts8/Ovt/e -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -s8/Os8/Os8/OsL69wM/OtL69zs/Ozs/OtL69wM/OwM/OwM/OwM/OwM/OsL69s8/Os8/Oyu/v1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//s8/OsL69ub69zs/O7+/v//////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////3t/eub69nJ6c3t/e3t/evb69zs/Ozs/OmJ6cm66t1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//vt/ep769j56cj56cvb69vb69vb697+/vra6tnJ6cnJ6cd317////////zs/O -nJ6ck56cs8/Os8/Ok56c3t/e////////zs/OnJ6cnJ6cnJ6cg42Mvt/e1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vg42MnJ6c//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////3t/ezs/O7+/vnJ6ce317g42Ms8/Os8/O -s8/Ovt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//vt/em66ta21rj56cmJ6cnJ6c -zs/Ozs/Ozs/O7+/v////////////////////////////3t/etL69wM/OnJ6czs/Ozs/Ozs/O3t/e -tL69s8/Ovt/eyu/vvt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//s8/Op769jI2Me317zs/O//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////3t/e3t/e////////ra6tnJ6ce317m66ts8/Os8/O1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//s8/Os8/Os8/O1v//vt/es8/O1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//p769j56cs8/Os8/Op769wM/OwM/Ovb697+/v//////////// -////////////////////////////////////////////////3t/ezs/Oub69wM/OwM/OwM/Oj56c -yu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//nJ6c//////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////7+/vzs/Ozs/Ozs/OnJ6cvb69nJ6ca21ra21ra21ra21rjI2MnJ6cqK6t -ra6tra6t////7+/vnJ6ca21rd317s8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/OsL69p769s8/Oj56c -s8/Os8/Os8/Oyu/v1v//yu/vm66tra6t//////////////////////////////////////////// -////////////////////////////////nJ6c7+/vnJ6cg42Myu/v1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//s8/Om66tvb69zs/O//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////3t/era6tnJ6ce317nJ6c -zs/O3t/ezs/Ozs/O7+/v////////3t/enJ6cvb69a21ra21rg42Mg42Mt8/O1v//p769e317//// -//////////////////////////////////////////////////////////////////////////// -////////7+/vvb69j56cs8/Ovt/es8/Os8/Os8/Ovt/e1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//j56cwM/Ovt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -j56cra6t//////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -vb69jI2Me317p769d317s8/O1v//j56cvb69//////////////////////////////////////// -////////////////////////////////////////////////////////7+/v3t/ezs/Ozs/Ovb69 -7+/vzs/Ora6tzs/Ovb69wM/Oub69ub69wM/OwM/OwM/OwM/Oub69tL69wM/OwM/Op769s8/O1v// -s8/Om66tyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//j56cvb69ra6t -q769s8/Oyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//yu/vs8/Os8/OsL69qK6tyc/Ozs/O7+/v//////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////3t/e////////////////////////////////7+/vzs/Ozs/Og42Me317vb693t/e -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////7+/vub697+/v////vb69wM/OsL69s8/Os8/Oyu/v1v// -1v//1v//yu/vs8/Os8/Os8/Os8/Ot8/OqK6t////////////ub69wM/Op769yu/v1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//s8/Om66twM/Oub69vb69vb693t/e////////////3t/e -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////3t/era6td317mJ6czs/O7+/v//////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////3t/era6twM/Om66ttL69vb69//////////////////////// -////////////////////////zs/Ovb69vb69vb69mJ6cra6tvb69nJ6cmJ6csL69n66twM/OtL69 -vb69sL69t8/OwM/Ovb69zs/Ovb69vb69qK6tvb69ub69wM/OsL69n66twM/Ora6tzs/Ozs/Ozs/O -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////3t/ejI2M -jI2MjI2Mra6t3t/e//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////7+/v//////////////////////////////////////////// -////////////7+/v3t/e//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////3t/enJ6cvb69ra6tvb69//////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////zs/O////////////3t/evb69//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////zs/O3t/e -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////7+/vnJ6ca21rd317jI2Mvb69//////////////////////////////// -////////////////3t/era6t3t/e//////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////3t/e//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////e317a21rd317jI2M -////////////ra6tra6t7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////7+/va21rj56c1v//jI2M////////////3t/e3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////7+/vzs/O//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/v3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////3t/ea21rg42M1v// -yu/vpK6t//////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////3t/evb69//////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////3t/ea21rj56cyu/v1v//ra6t//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////mJ6csL69zs/O//// -//////////////////////////////////////////////////////////////////////////// -////////////3t/e3t/e//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////ra6ta21r -vt/e1v//p769zs/O//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////7+/v3t/e//////////// -////////////////////////zs/Op769q7693t/e//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////vb69a21r1v//1v//1v//a21r3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////mJ6cm66t3t/e////////////////////////////////////7+/vqK6t -p769vb69//////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////zs/O -m66tyu/v1v//1v//p769j56c//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////ra6tra6tzs/O//// -////////////////////////////////////////nJ6cd317ub69//////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////7+/vs8/Op7691v//1v//1v//p769s8/OwM/O3t/e -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////7+/vub69sL69mJ6ctL69zs/O//////////////////////////////////////// -////7+/vsL69m66tvb69//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -7+/vq769p7691v//1v//1v//1v//1v//1v//ra6t//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////zs/Ora6t1v//1v//1v//1v//s8/O -7+/v////////////////////////////////////////7+/va21r7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////vb69p7691v//1v//1v//1v//1v//m66t -n66tn66t3t/e//////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -vb69wM/Oyc/Ozs/Ozs/O//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////mJ6cp769ub69zs/Ozs/O//////////// -////////mJ6ce317s8/O1v//1v//1v//1v//1v//qK6t//////////////////////////////// -////////vb697+/v//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////7+/vd3171v//1v//1v//1v//1v//p7691v//vt/eh42M7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////j56c1v//1v//1v//yu/vn66t7+/v//////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////sL691v//1v//1v//yu/vsL69ub69zs/Ozs/Ora6tyu/vs8/O1v//1v//1v//1v//1v// -1v//s8/Ozs/O//////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////3t/eg42M1v//1v//1v//1v//1v// -vt/ej56cs8/Oyu/ve317//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -3t/eyu/v1v//1v//1v//vt/ep769n66t//////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////q7691v//1v//1v//1v//1v//1v// -1v//yu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//wM/O//////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////j56cvt/e1v//1v//1v//1v//1v//p769s8/O1v//yu/vqK6t//////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////e317p769vt/e1v//1v//yu/vm66tvt/eub69 -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////3t/evt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//m66t////////////////////////7+/v7+/v//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/v7+/v//////////////// -////////////////////////////////////////////////////////sL69m66t1v//1v//1v// -1v//p769p769g42Ms8/O1v//n66t//////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -vb691v//1v//g42Mp769s8/Oyu/v1v//s8/Od317//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////jI2M1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//sL69//////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////wM/Op769yu/v1v//1v//vt/em66tyu/vj56c1v//1v//vt/eub697+/v -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////tL691v//1v//m66tyu/vvt/ep7691v//1v// -j56cq7697+/v////////////n66tp7693t/e//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////pK6t1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//s8/Ovb69//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////ub69vt/em66tm66t -m66tyu/vyu/vs8/Ovt/e1v//1v//1v//1v//p769n66tzs/O//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////sL691v//1v//m66t1v//1v//yu/vm66tm66ts8/Ovt/ezs/O////////////s8/O1v//ub69 -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////qK6tyu/v1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//s8/Ora6t//////////////////// -////7+/vzs/O//////////////////////////////////////////////////////////////// -////////////////////////////////////////3t/e//////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////zs/Os8/O1v//1v//p7691v//s8/O1v//1v//1v//1v//1v//1v// -1v//1v//q769//////////////////////////////////////////////////////////////// -////////////////////////////////////////3t/eyu/v1v//1v//s8/O1v//1v//s8/Os8/O -1v//p769s8/O7+/v////////////q7691v//q769////////////zs/Ozs/O////////7+/v//// -//////////////////////////////////////////////////////////////////////////// -////////////////////vb69wM/Os8/Oyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//yu/vub69////////////////////////7+/vra6tnJ6c7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////3t/e////zs/O////////////////////////////////////3t/e//////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////qK6tp7691v// -1v//yu/vs8/Op769s8/O1v//1v//1v//1v//1v//1v//1v//1v//zs/O//////////////////// -//////////////////////////////////////////////////////////////////////////// -////q7691v//1v//vt/em66ts8/Op769j56c1v//1v//s8/Ovt/etL69////////////wM/O1v// -vt/e3t/e////////////////////////7+/v//////////////////////////////////////// -////////////////////////////////////////////////////////////////////////qK6t -1v//1v//1v//1v//1v//1v//1v//1v//yu/v1v//1v//yu/vra6t//////////////////////// -////////////////ra6t////////////7+/vvb69//////////////////////////////////// -////////////////////////////////////3t/e//////////////////////////////////// -////////////////3t/e3t/e//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////3t/epK6tvt/ep7691v//1v//1v//yu/vj56cyu/v1v//1v//1v//1v// -1v//1v//1v//1v//wM/O//////////////////////////////////////////////////////// -////////////////////////////////////////////j56cs8/Os8/Ovt/e1v//m66ts8/Oyu/v -m66tvt/em66tp769yu/vp769zs/O////tL69vt/e1v//nJ6c//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////3t/eh42Mvt/e1v//1v//1v//1v//1v//p769qK6t -sL691v//q769////////////////////////////////////////zs/O3t/e////////////7+/v -nJ6c3t/e//////////////////////////////////////////////////////////////////// -////////////////zs/O7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////zs/Os8/O1v//1v//p769 -1v//1v//1v//m66t1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//wM/O//////////////// -//////////////////////////////////////////////////////////////////////////// -////////q7691v//1v//1v//1v//s8/O1v//1v//1v//p769s8/Oj56cs8/O1v//m66t//////// -3t/em66tpK6t//////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////7+/vh42Mm66th42M1v//1v//p769vb69////nJ6cs8/Oub69//////////////////////// -////////////////nJ6c3t/e//////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/v7+/v//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////pK6t1v//1v//1v//j56c1v//p769p769vt/e1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//t8/O3t/e//////////////////////////////////////////////// -////////////////////////////////////////////////ub69yu/v1v//1v//1v//p769vt/e -s8/Oj56cs8/Os8/Oj56c1v//1v//sL69////3t/e7+/vvb69ub69//////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/vzs/Op769s8/Om66tvb69 -////vb69pK6t////////////////////////////////7+/v////////7+/v//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////7+/v7+/v//////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////vb69yu/v1v//yu/vp769 -m66tp769s8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//n66t7+/v//// -//////////////////////////////////////////////////////////////////////////// -////////////7+/vs8/O1v//1v//1v//m66tm66tvt/es8/O1v//s8/Od317s8/Os8/OjI2M7+/v -7+/v//////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////3t/e//////////////////////// -3t/evb69vb697+/v////7+/vzs/Ovb697+/v3t/e////zs/Ozs/O////3t/evb69vb69vb697+/v -////3t/era6t3t/e7+/v7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////zs/O7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////vM/O1v//yu/vm66tvt/e1v//yu/vyu/v1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//tL69//////////////////////////////////////// -////////////////////////////////////////////////////zs/O1v//yu/vs8/O1v//s8/O -1v//1v//p769p769p769vt/e1v//1v//zs/O//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////7+/vzs/Ora6tnJ6cnJ6ca21rjI2Me317a21rvb69zs/O3t/e//////// -7+/vzs/Ok56ch42M3t/en66tqK6tvb69zs/O////ra6tra6tjI2M//////////////////////// -////////3t/e//////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////qK6tyu/v1v//vt/evt/e -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//wM/O -//////////////////////////////////////////////////////////////////////////// -////////////////qK6ts8/Om66tyu/vm66tyu/v1v//1v//1v//p7691v//1v//1v//vt/ezs/O -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////7+/vjI2Mg42MqK6tsL69jI2M//// -////7+/v7+/v////7+/v7+/vvb69ra6tzs/O3t/e3t/em66tp769yu/vvt/eg42Mzs/O3t/e//// -ra6tra6t3t/e//////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////j56cs8/O1v//1v//m66ts8/O1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//yu/vsL69zs/O//////////////////////////////////// -////////////////////////////////////////////////////7+/va21rj56cyu/v1v//1v// -1v//1v//1v//vt/ep7691v//1v//1v//p769zs/O//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////7+/vsL69pK6t////////////7+/vzs/O////nJ6cnJ6cnJ6c////////////7+/vnJ6c -ra6tq769yu/vs8/O1v//n66tzs/Ovb69jI2Mra6tzs/O//////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////e317s8/Op7691v// -s8/Om66tyu/v1v//1v//1v//1v//1v//1v//1v//1v//s8/Os8/O1v//m66tn66twM/Ovb69//// -//////////////////////////////////////////////////////////////////////////// -////////////7+/vk56cm66tvt/ep7691v//1v//1v//1v//1v//s8/Od3171v//1v//p769vt/e -k56c7+/v//////////////////////////////////////////////////////////////////// -////////////////////////////////////////////ra6tn66tvt/ed317nJ6c3t/eq769m66t -m66t3t/eg42Mg42Mzs/Ora6tnJ6cjI2Mra6ta21rmJ6cvt/es8/OpK6tvb697+/v3t/e3t/era6t -3t/e//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -3t/era6t7+/v////////////k56c1v//vt/eg42Myu/vyu/vs8/O1v//1v//1v//1v//1v//1v// -1v//s8/Od317d317tL69vb69//////////////////////////////////////////////////// -////////////////////////////////////////////////7+/vvb691v//yu/vp769s8/Ovt/e -1v//1v//1v//1v//yu/vg42Ms8/Om66t1v//1v//vt/etL69//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////zs/OjI2Myu/vj56czs/O////k56c1v//1v//yu/vub69qK6te317ra6tzs/OnJ6cvb69a21r -n66tra6tvb697+/v////////////////////////////////////////////////////3t/e//// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////3t/e//////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////7+/v////////////////3t/ej56cs8/O -1v//1v//s8/Om66tg42Mm66t1v//yu/vm66ts8/O1v//1v//m66t7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////7+/vzs/Oj56cvt/eg42Myu/vs8/O1v//1v//1v//1v//1v//m66t1v//m66t1v// -1v//s8/Oyu/vqK6t7+/v//////////////////////////////////////////////////////// -////////////////////////////////////////////jI2Mp769m66ta21r7+/v////g42Mm66t -m66tyu/vq769vb69nJ6cnJ6cra6tnJ6czs/O//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////zs/Ovt/e1v//1v//1v//vt/es8/Op769s8/Os8/Os8/O -p769m66tp769pK6t//////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////zs/Om66ts8/Os8/Oj56c -m66t1v//1v//1v//1v//1v//p769s8/Om66t1v//vt/ej56cs8/O1v//n66t7+/v//////////// -////////////////////////////////////3t/e//////////////////////////////////// -////ra6tg42MpK6tj56cn66t////7+/v////ub69w9/ej56ck56c////////////ra6t3t/e7+/v -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -s8/O1v//1v//1v//s8/Oyu/vvt/evt/ej56cs8/Op769g42Mn66t7+/v//////////////////// -////////////////////////////////////////////////////////////qK6td317wM/OqK6t -pK6tzs/O////vb69j56cj56c1v//1v//p7691v//s8/Op769p769p769m66tp769vt/e1v//p769 -m66tyu/vvt/evt/es8/Os8/On66t////////////////////////////////////////////7+/v -zs/O////////3t/e////////////////////////////jI2Mub69zs/Op769ub69////7+/v//// -////7+/vh42Mj56cra6t3t/e////3t/e7+/v//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////zs/Ora6tzs/Op7691v//s8/Op769s8/Oyu/v1v//1v//j56c -k56c7+/v//////////////////////////////////////////////////////////////////// -////////////////zs/Oh42Mm66tvt/e1v//s8/O1v//g42Mj56cvt/e1v//yu/vm66ts8/Op769 -s8/Ovt/e1v//1v//vt/es8/O1v//1v//yu/vm66t1v//1v//1v//1v//1v//p769s8/Ozs/O//// -////////////////////////////////////////////////////wM/OtL69//////////////// -////zs/O////7+/vjI2Mra6t////////////////////////7+/vnJ6c////ra6tjI2Mm66t3t/e -////////////3t/e//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////7+/vra6te317mJ6c -e317mJ6c1v//j56cvt/e1v//1v//1v//vt/ejI2M7+/v//////////////////////////////// -////////////////////////////////////////////////////////mJ6cm66tvt/es8/Oyu/v -m66t1v//g42Mp7691v//1v//1v//1v//m66tj56cyu/vs8/Os8/O1v//j56c1v//1v//1v//yu/v -p7691v//1v//1v//yu/vm66ts8/O1v//q769//////////////////////////////////////// -////////zs/Oq769h42M3t/e////////////////7+/v3t/e////zs/Oe317////////jI2M7+/v -////////////////ra6t7+/v3t/ee317d3177+/v//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////vb69j56c7+/v////////7+/vpK6ta21rj56cn66tzs/Ora6tnJ6c -ra6t//////////////////////////////////////////////////////////////////////// -////////////3t/ejI2Mvt/eyu/vs8/Op769m66tvt/es8/Og42Mm66ts8/O1v//1v//1v//yu/v -g42Myu/v1v//yu/vg42Myu/v1v//1v//1v//1v//p7691v//1v//1v//g42MqK6ttL69wM/Oj56c -zs/O////////////////////////////////////////////pK6t1v//tL69//////////////// -////zs/O7+/v////zs/OnJ6c7+/vn66tg42Mk56czs/O////////3t/e////nJ6czs/Oa21re317 -//////////////////////////////////////////////////////////////////////////// -////////7+/v7+/v//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////zs/OnJ6cg42Ms8/O3t/e -////////////////7+/v3t/ezs/O////////7+/vvb693t/e//////////////////////////// -////////////////////////////////////////////////////zs/Od317j56cj56cs8/O1v// -vt/em66t1v//m66tp769m66tp769p769p769p769j56c1v//1v//1v//j56c1v//1v//1v//1v// -1v//1v//p7691v//yu/vd317k56cvb693t/e////////ra6t//////////////////////////// -////////3t/eyu/v1v//q769////////////////////7+/vzs/O////vb69a21rd317vt/evt/e -p769nJ6c////////////////3t/ea21ra21rzs/O//////////////////////////////////// -zs/O//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////7+/vzs/O7+/vh42Mvt/ej56cm66td3173t/e//////////////////////////////////// -////vb69//////////////////////////////////////////////////////////////////// -////vb69////////qK6t1v//m66tg42Ms8/Os8/Ovt/eyu/vs8/Om66ts8/Oyu/v1v//1v//1v// -yu/vp7691v//1v//1v//p769yu/v1v//1v//1v//1v//1v//m66tj56ce317nJ6c1v//yu/vvt/e -sL69zs/O////////////////////////////////////////qK6t1v//1v//n66t7+/v//////// -////////////7+/v3t/enJ6cyu/v1v//s8/Om66tj56cvb69////////////////vb69h42Mzs/O -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////3t/etL69p769yu/vs8/Ovt/eg42MjI2M7+/v7+/v -////////7+/vzs/O////7+/v7+/v////3t/e////vb693t/e//////////////////////////// -////////////////////////////////////////3t/evb69////////3t/ej56cvt/e1v//1v// -1v//s8/O1v//1v//1v//1v//s8/O1v//1v//1v//1v//vt/eyu/v1v//1v//1v//s8/O1v//1v// -1v//1v//1v//vt/ej56c7+/ve317s8/Op769vt/e1v//p769wM/Ozs/O//////////////////// -////////////s8/O1v//1v//1v//m66t7+/v////////////////zs/Op769h42Myu/vs8/Ovt/e -g42MnJ6c////////////////////vb69j56c7+/v//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////zs/O//////////////////////////// -////////////////////////////////////////////////////////////////////7+/vpK6t -s8/O1v//1v//t8/Ovb69ra6ts8/Oj56c7+/v////////////zs/Ovb69ra6ta21rg42Mra6tzs/O -zs/O3t/e//////////////////////////////////////////////////////////////////// -////////////////////3t/evt/e1v//1v//1v//1v//s8/O1v//1v//1v//vt/em66tvt/e1v// -1v//1v//1v//s8/O1v//1v//1v//s8/O1v//1v//1v//1v//1v//yu/vra6t3t/evt/e1v//1v// -yu/vs8/Op769yu/vs8/Ovb69////////////////////////zs/Os8/O1v//1v//1v//1v//s8/O -vb69////////////qK6t1v//m66tvt/ej56cj56cjI2M////g42M3t/e////////////////nJ6c -//////////////////////////////////////////////////////////////////////////// -////////////3t/e//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -3t/ezs/Ovb69//////////////////////////////////////////////////////////////// -////////////////////////////////ra6tvt/e1v//1v//vt/evb69////////xc/Op769ra6t -3t/e3t/e3t/enJ6ce317nJ6cra6t7+/v//////////////////////////////////////////// -////////////////////////////////////////////////////////////ra6ts8/Ovt/e1v// -1v//1v//s8/O1v//1v//p769s8/O1v//s8/Os8/O1v//1v//yu/vvt/e1v//s8/Os8/Om66t1v// -1v//1v//1v//1v//s8/Ozs/Os8/O1v//1v//1v//1v//1v//1v//s8/Oyu/vp7697+/v//////// -////////ub69mJ6cvt/e1v//1v//1v//1v//1v//yu/vra6tzs/Ora6tvt/e1v//1v//j56cp769 -m66ts8/Ora6tjI2Mra6t7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////zs/O//////////////////////////////// -////////////////////////////////////////////////////////////////ra6t////qK6t -1v//1v//1v//s8/O////////////////////////ra6tnJ6cqK6tnJ6c3t/enJ6czs/O//////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////zs/Ovt/ep769yu/v1v//vt/eyu/vyu/vp769yu/v1v//1v//1v// -yu/vs8/Op769p769s8/Op7691v//1v//s8/Os8/Os8/Os8/Os8/Os8/OnJ6cvb691v//1v//1v// -1v//1v//1v//vt/es8/Os8/Op769zs/O////////////ra6tm66tvt/e1v//1v//1v//1v//1v// -1v//1v//s8/Og42Ma21rm66t1v//yu/vj56cs8/Oj56cj56cs8/Oyu/vyu/vj56csL69zs/Ozs/O -ub69//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////nJ6cjI2MqK6tyu/v1v//1v//1v//s8/O7+/v//////////////// -////////////vb69nJ6cnJ6c7+/v//////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////qK6t1v// -s8/O1v//vt/em66ts8/O1v//1v//1v//1v//1v//1v//m66tyu/v1v//1v//1v//1v//1v//s8/O -1v//1v//1v//1v//p769zs/Os8/O1v//1v//1v//1v//1v//s8/Ora6tvb69e317vb69zs/OnJ6c -vb69vb69p769j56cvt/e1v//1v//1v//1v//1v//1v//1v//p769m66tg42Mm66tvt/em66tyu/v -1v//1v//1v//1v//1v//1v//1v//1v//s8/OjI2MjI2Mzs/O//////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////ub69e317mJ6cyu/v -1v//1v//1v//vt/ej56czs/O////////////////////////qK6tp769vb693t/e//////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////7+/v7+/vzs/On66tj56cg42Ms8/O1v//1v//1v//1v//1v//1v// -1v//yu/vs8/O1v//1v//1v//1v//1v//1v//s8/O1v//1v//1v//1v//qK6tn66t1v//1v//1v// -1v//1v//yu/vqK6tvb69sL69k56cvt/e1v//s8/Ovt/e1v//1v//j56cyu/v1v//1v//1v//1v// -yu/vp769p769a21rj56cm66t1v//m66tp769s8/O1v//1v//1v//1v//1v//1v//1v//1v//1v// -j56c7+/v////////zs/O7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////3t/e3t/ed317h42Mvt/e1v//1v//s8/Op769m66tyu/vq769vb69zs/Ora6t -3t/e////zs/On66txc/O//////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////ra6tvb69 -nJ6cqK6ts8/Op769yu/v1v//1v//1v//1v//1v//1v//yu/vs8/O1v//1v//1v//1v//1v//1v// -s8/O1v//1v//1v//m66tj56cs8/O1v//1v//1v//yu/vp769pK6tvb69vt/e1v//1v//1v//yu/v -g42Ms8/Ovt/e1v//vt/ep769vt/e1v//1v//s8/Os8/Op769p769s8/Os8/Os8/Om66tg42Mp769 -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//pK6t////////////vb69//////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////pK6tnJ6cm66ts8/O -s8/Op769vt/eyu/v1v//1v//1v//yu/vyu/vvt/ep769m66ts8/Oyu/vzs/O//////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////s8/O1v//s8/Op7691v//1v//1v// -1v//1v//s8/Om66t1v//yu/vp769ub69m66t1v//p769s8/OsL69p769j56cd317p769m66t1v// -p769vt/eyu/vg42Ms8/O1v//1v//1v//1v//vt/ep7691v//m66ts8/Oyu/v1v//m66t1v//yu/v -m66ts8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//yu/va21r////////////7+/vra6t//////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////nJ6cp769p769vt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//q769zs/O//////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////3t/e -////////////ub69vt/e1v//vt/em66t1v//1v//1v//yu/vm66tm66tpK6tub69////////ub69 -tL69zs/O////////////////zs/Od317g42Mp7691v//1v//p769s8/O1v//1v//1v//1v//1v// -s8/O1v//1v//1v//vt/em66t1v//p769vt/es8/Op7691v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//vt/enJ6c////7+/v7+/vnJ6ch42Mra6t -zs/O//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////7+/vn66tvt/e1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//s8/Ora6t7+/v -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////zs/Op769s8/Om66t1v// -1v//1v//yu/vp769g42M////////////////////////ra6tra6t////////vb69vb69m66t1v// -m66tyu/v1v//p7691v//1v//1v//1v//1v//1v//vt/ep769yu/v1v//1v//vt/ep769p769p769 -j56cyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//m66t////////zs/OpK6tnJ6cra6tg42Md317sL69nJ6c7+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////mJ6c1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//g42M7+/v//////////////////////////////////// -////////////////////////////////////////////////////////////3t/e//////////// -////////////////vb69ra6tn66twM/Ora6tub69wM/OwM/On66tpK6th42M3t/eub69//////// -3t/ejI2Mzs/OnJ6cg42Mq769q769q769j56cs8/Op769j56cj56cs8/O1v//1v//yu/vs8/O1v// -vt/ep769vt/em66ts8/Op769vt/ej56cj56cm66t1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//p769mJ6c3t/evb69s8/OtL69//// -////3t/eg42Myu/vub69//////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////zs/Os8/O1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//d317 -nJ6c//////////////////////////////////////////////////////////////////////// -////////////////zs/O7+/v3t/e////////////////////////////ub69s8/O1v//1v//s8/O -vb693t/e////////vb697+/v3t/ezs/Oe317////jI2Mg42Mra6ta21r1v//1v//1v//1v//1v// -1v//1v//1v//m66tj56cm66tp769m66tyu/vs8/Ovt/e1v//yu/vp769p769j56cj56cm66tm66t -yu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//j56czs/OnJ6c3t/eg42Mj56c3t/e////////////7+/vqK6tq769//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////wM/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//yu/v1v//1v//1v//m66tnJ6czs/O//////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////vb69m66tyu/v1v//1v//pK6tvb693t/e////mJ6c3t/e3t/epK6tg42M -jI2Mg42Md317a21rg42Md317p769vt/e1v//s8/On66tm66ts8/Od317j56cs8/Oyu/vp7691v// -s8/Oyu/vvt/ep7691v//yu/vj56ca21rg42Mp769m66tm66tyu/v1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//yu/vyu/v1v//1v//1v//1v//1v//1v//vt/ej56cvt/em66tm66tmJ6c -////////////////zs/Ok56c//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////n66t1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//g42Ms8/Op769 -vt/e1v//1v//h42M////7+/v7+/v//////////////////////////////////////////////// -////////////////////////////////////////////////////////////ra6tm66ts8/Os8/O -p769s8/Oj56czs/Ozs/Ovb69qK6ts8/OqK6te317mJ6cj56cj56cyu/vs8/Ovb69////3t/ezs/O -3t/e////vb69j56cs8/Op769yu/vp769vt/es8/Op769m66ts8/Ovt/es8/Op7691v//s8/Op769 -m66ts8/Os8/Og42M1v//1v//1v//1v//1v//1v//1v//s8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/O -s8/O1v//1v//1v//1v//1v//1v//1v//vt/em66tmJ6cqK6t3t/e////3t/eh42Mn66tra6t//// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////wM/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//p7691v//1v//vt/es8/Os8/Os8/Og42MjI2Md317nJ6czs/O -//////////////////////////////////////////////////////////////////////////// -////////////////////////////3t/e////////qK6t1v//1v//1v//m66tm66tvt/ek56cjI2M -g42Mj56cp769m66ts8/Os8/On66t3t/e3t/eqK6tra6tn66tyu/v1v//1v//1v//s8/Oyu/v1v// -1v//p769s8/Os8/Oyu/vyu/v1v//1v//1v//1v//1v//1v//1v//m66ts8/O1v//1v//1v//yu/v -s8/Op769s8/O1v//1v//1v//1v//1v//1v//1v//m66tm66ts8/O1v//1v//1v//1v//1v//1v// -1v//m66tvt/es8/Ozs/O////vb69qK6tra6tjI2Mzs/O//////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////qK6tvt/e1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//vt/em66tyu/v1v// -1v//1v//1v//1v//d317m66t1v//g42MjI2Me317zs/Ovb69ra6tvb69//////////////////// -//////////////////////////////////////////////////////////////////////////// -3t/eq7691v//1v//1v//g42Md317g42Mg42Mj56cj56cs8/Op769s8/O1v//yu/vg42Mk56cj56c -p769wM/Od317yu/v1v//1v//1v//p769s8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//vt/ej56cs8/O1v//vt/es8/O1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//yu/vp769m66t1v//1v//1v//1v//1v//1v//p769yu/vs8/Ozs/Ozs/OjI2M//// -////7+/vzs/O7+/v//////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////vb69a21rg42Ms8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/Os8/O -s8/Os8/Os8/Om66ts8/Op769yu/v1v//1v//1v//1v//1v//1v//1v//p769g42Mj56ch42Mzs/O -3t/eh42Mp769g42Mra6t//////////////////////////////////////////////////////// -////////////////////////////////////3t/enJ6cm66tvt/e1v//yu/vp769m66t1v//j56c -m66tm66tg42Mg42Mg42Ms8/Om66tp7691v//1v//1v//1v//vt/ej56c1v//1v//p769vt/e1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//j56cg42M -p7691v//1v//1v//1v//1v//1v//1v//1v//yu/vs8/Os8/Oyu/vm66tj56cvt/e1v//1v//1v// -yu/vp769p769p769vt/e1v//s8/Ora6tqK6t3t/e////////////7+/vzs/O//////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////7+/v//////////////////////////////////////// -////////////////////////////////////////////////////////jI2Ma21rj56c1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -s8/Os8/O1v//1v//1v//1v//1v//p769n66tj56cp769qK6ta21rvb69//////////////////// -////////////////////////////////////////////////////////////////////zs/O//// -nJ6cjI2Mn66td317m66tg42Mm66t1v//1v//m66tm66tm66tp7691v//yu/vp7691v//s8/Ovt/e -1v//vt/ej56cp769vt/e1v//1v//yu/vm66tp769vt/em66ts8/Oj56cp769vt/e1v//1v//1v// -1v//1v//1v//1v//1v//m66tp769m66tvt/eyu/vs8/Os8/Op769s8/Og42M1v//p769m66ts8/O -p7691v//1v//p769s8/Os8/Om66t1v//1v//1v//p7691v//1v//1v//1v//1v//1v//nJ6cm66t -////////////////////ra6tvb69////////////////////////////////////////3t/e//// -////////////////////////////////////////////////////////////////////////zs/O -zs/Ora6tzs/Ovb69zs/O7+/v//////////////////////////////////////////////////// -////////////nJ6cra6td317vt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//p769jI2Mj56c1v//1v//1v//1v//1v//1v//1v// -1v//vt/eyu/vj56czs/O//////////////////////////////////////////////////////// -////////////////////////////3t/ed317m66tnJ6cj56c1v//d3173t/ejI2Ma21rvt/eyu/v -1v//m66t1v//1v//1v//vt/em66ts8/Os8/Os8/Oa21rvt/e1v//1v//1v//1v//1v//1v//1v// -yu/vvt/e1v//1v//1v//s8/Os8/O1v//1v//1v//1v//1v//s8/O1v//s8/Oyu/v1v//1v//1v// -1v//1v//1v//1v//1v//yu/vs8/Oyu/v1v//1v//1v//1v//1v//1v//1v//1v//s8/Om66ts8/O -m66tyu/v1v//1v//1v//1v//vt/eyu/vd317tL69////////////////////7+/vp769nJ6c7+/v -////////////////////ra6t////////3t/e//////////////////////////////////////// -////////////////////////////////////////////////////////7+/vvb69nJ6cvb69vb69 -////////////////////////////////////////////////vb69a21ra21ryu/v1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vs8/O -pK6t7+/vm66tyu/v1v//1v//1v//1v//1v//1v//1v//m66td317vb69//////////////////// -////////////////////////////////////////////////////////////////////7+/vmJ6c -a21re317n66tq7697+/v////////7+/vjI2Ma21rd317jI2MtL69wM/Oj56cj56cp769m66t1v// -vt/evt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vs8/Om66ts8/O -p769s8/Og42Ms8/Om66tyu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//p769a21rnJ6c7+/v -zs/O////////////////////zs/O1v//yu/vpK6t7+/v7+/vvb697+/v//////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////zs/OnJ6cjI2Mvb69ra6t7+/v//////////////////// -////////zs/Oa21rd317s8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//s8/Os8/OtL69zs/O////////zs/Ovb69sL691v//1v//1v//1v//1v// -1v//p769ra6t//////////////////////////////////////////////////////////////// -////////////////////////////////////////ra6td317j56cvb69////////////////e317 -a21rh42Mvt/eh42M3t/ezs/Om66tj56cm66tj56cs8/O1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//p769vb69////////////////////////////3t/es8/O1v// -yu/vqK6t//////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////ra6t -nJ6ce317vt/ea21rnJ6c7+/v////////////////3t/era6ta21rd317yu/v1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//q769zs/O//////////// -////////7+/vvb69s8/O1v//1v//vt/ee317pK6ts8/OnJ6c7+/v//////////////////////// -//////////////////////////////////////////////////////////////////////////// -////vb69nJ6ce3177+/v////////3t/ek56cpK6tjI2Ms8/O1v//k56cnJ6c////e317h42Mp769 -p7691v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/v -pK6tzs/Ozs/Ozs/O3t/era6tzs/O3t/e3t/epK6tvt/eh42Mzs/O//////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////7+/v7+/v////vb69jI2Mg42Mp7691v//1v//1v//s8/Od317j56ca21rqK6tt8/O -m66tj56cvt/es8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//tL69////////////////////////3t/ezs/Op7691v//yu/vj56cra6t -////nJ6c////////////////////////////zs/OnJ6ch42MjI2M//////////////////////// -////////////////////////////////////////////7+/v////////ra6t////////ra6td317 -1v//yu/vp7691v//p769ra6tnJ6cg42Mp769j56cd317p7691v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//vt/evt/eyu/vsL697+/v -7+/va21rmJ6cm66tn66tsL69pK6tzs/O//////////////////////////////////////////// -////////////////////////////////////////////////////////3t/ezs/O////nJ6cp769 -vt/e1v//1v//1v//1v//1v//yu/v1v//1v//1v//s8/O1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vmJ6czs/O//// -7+/vra6tnJ6cra6tnJ6ck56ctL69ub69mJ6cqK6ta21rjI2M////////////////////////vb69 -j56c1v//1v//m66tzs/O////////////////////////////////////////3t/e//////////// -////////vb69////////////////////zs/OjI2Mm66ts8/Om66t1v//vt/enJ6cvb69s8/O1v// -1v//1v//j56cvt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//s8/Os8/Oyu/vm66tp7691v//1v//1v//yu/vp769 -qK6tqK6t//////////////////////////////////////////////////////////////////// -////3t/e////ra6ttL69vb693t/e3t/etL69sL69h42M1v//1v//1v//1v//1v//1v//1v//1v// -1v//s8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//vt/es8/Op769e317g42Mm66te317zs/Ovb69e317qK6tm66tyu/v -s8/Oj56ce3177+/v////////////////zs/Od317yu/v1v//1v//1v//d3177+/v//////////// -////////////////nJ6cg42Myu/vs8/OpK6tzs/O//////////////////////////////////// -////3t/ee317g42Mp7691v//yu/vm66tvb69n66tyu/v1v//j56c1v//s8/Oh42Mh42Mp7691v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//p769j56cpK6t7+/v//////////////////////// -////////////////////////////////////////////g42Mp769p769j56ch42Mvb69zs/OqK6t -mJ6cg42Myu/v1v//1v//1v//1v//1v//1v//1v//1v//s8/O1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//m66tvt/e1v//1v//1v//1v//s8/Oyu/vyu/vs8/O -s8/Od317a21rtL697+/v////vb69ra6tm66t1v//p769n66tg42Ma21r3t/e////////7+/va21r -j56c1v//1v//1v//1v//yu/vp769m66tpK6t3t/e////////////7+/vnJ6cra6tnJ6cnJ6cqK6t -7+/v////////////////////////////////////////////////nJ6cd317s8/O1v//1v//s8/O -m66t1v//vt/ep769p769j56cwM/Op769g42Mg42Mg42Mp769vt/e1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//m66tj56cs8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//zs/O//////////////////////////////////////////////////////////// -////////j56ctL69zs/O////////////7+/vh42Mm66t1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//s8/Oyu/vs8/Op769j56cp769yu/v1v//vt/es8/O1v//vt/es8/Om66ta21rj56cj56c -a21rg42Md317e317jI2Md317d317h42Mvt/em66tg42MjI2Mp769j56czs/Ovb69k56cd317s8/O -1v//m66th42Mvb69////////////////7+/ve317d3171v//1v//1v//1v//1v//1v//1v//1v// -s8/Oj56cwM/OtL69zs/O//////////////////////////////////////////////////////// -////////////////zs/Oe317a21rg42Mj56cj56cg42Myu/vm66tvt/eyu/vs8/Os8/OsL69vb69 -////nJ6cra6tnJ6cmJ6csL69j56cwM/Oj56cn66t1v//yu/vs8/Oj56cyu/vvt/ea21rp769g42M -yu/v1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//s8/O1v//1v//1v//s8/Ovt/e1v//1v//1v//vt/ezs/O//////////////////// -////////////////////////////////////////////////zs/O3t/e//////////////////// -////7+/vtL69n66ts8/Os8/Os8/OsL69wM/OwM/Oxc/Oub69vb69zs/O7+/v7+/vzs/Ozs/OnJ6c -ub69vb69nJ6cnJ6c3t/evb69g42Ms8/Os8/O1v//1v//vt/em66tnJ6czs/Ovb69jI2Ms8/Oh42M -zs/OnJ6ca21rj56cj56cm66tj56cs8/Os8/Om66ta21rjI2M3t/e////////////////////jI2M -a21rg42M1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//p769d317g42Mg42M3t/e//////// -////////////3t/e7+/v////////////////////////////////////////////7+/vra6tnJ6c -e317d317a21ra21rjI2Mzs/O7+/v////////////////////////7+/v7+/v3t/era6tnJ6cra6t -ra6tzs/Ozs/O3t/ep7691v//p769k56cs8/Os8/Oyu/vs8/Om66t1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//yu/vvt/ep769yu/v -yu/vvt/e1v//1v//1v//1v//1v//yu/vs8/Os8/Os8/Os8/Om66tnJ6czs/Ozs/Ozs/Ozs/Ora6t -zs/Ozs/Ozs/Ovb697+/v//////////////////////////////////////////////////////// -////////////zs/O7+/v//////////////////////////////////////////////////////// -////////////////////////////////////////////vb69m66tvt/em66td317j56cg42Mm66t -j56cd317p769ra6tra6th42Mm66ta21rd317ra6tvb69yu/vj56cg42M1v//d317a21rd317nJ6c -zs/O7+/v////////////////////////zs/Od317p769yu/v1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//vt/ed317d317d317zs/O//////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////e317j56cjI2M////////////////////vb69p769j56cnJ6ca21r -jI2Mg42Mj56cvt/evt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//s8/Os8/Oyu/v1v//m66t -1v//yu/vs8/Os8/Op769p769d317nJ6c7+/vzs/Ozs/Ozs/OnJ6cm66tn66tqK6ttL69nJ6c3t/e -////////////////////////////////////////////////////7+/v7+/v//////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////qK6twM/OtL69pK6tjI2MnJ6cnJ6cvb69ra6tnJ6cra6t7+/vnJ6ca21rjI2Mg42M -h42Md317h42Mj56cd317g42Md317vb697+/v////////////////////////////////3t/eh42M -vt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//vt/es8/Om66ta21rnJ6c -3t/e////////////////////////////////////////////////////////////////////3t/e -////////////////////////////////////////////////////////////////////vb69a21r -k56cra6t7+/v////////////3t/e7+/v////zs/O////vb69nJ6cnJ6ca21rj56c1v//1v//1v// -1v//1v//vt/e1v//1v//1v//s8/Oj56cd317jI2Mzs/Ozs/O7+/v////3t/ezs/Ozs/O//////// -////zs/Ozs/OjI2Me317ra6tzs/Ozs/Ozs/O3t/e//////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////nJ6ca21ra21ra21ra21r -qK6tnJ6ce317nJ6cjI2MnJ6ca21ra21re317a21rjI2Ma21ra21rd317d317a21ra21rjI2M//// -////7+/vvb69nJ6ce317wM/OwM/On66ts8/O1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//s8/Oa21ra21r3t/e//////////////////////////////// -////////////////////////////zs/Ora6t7+/v////3t/e7+/v3t/e//////////////////// -////////////////////////////////////7+/vzs/Ora6tnJ6cnJ6ce317nJ6c//////////// -////////////zs/O7+/v////7+/vra6tzs/OnJ6cd317h42MqK6tm66tyu/vp769j56cs8/On66t -ra6t////////////////////////////////////////3t/evb69ub69nJ6czs/O3t/ezs/Ora6t -////3t/e//////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////zs/Ozs/OnJ6cnJ6ca21r////zs/Oe317e317a21rjI2Me317 -e317jI2Md317h42Ma21ra21rg42Ms8/Og42Ma21rra6tra6th42Mj56cj56cyu/v1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//1v//h42M -jI2M3t/e////////////////////////////////////////////////////vb69qK6ta21ra21r -n66tjI2Ma21rnJ6czs/Ozs/O7+/v//////////////////////////////////////////////// -////////////////////////////////////////////////////3t/e//////////////////// -7+/vzs/Ozs/OjI2MjI2Ma21rjI2Mvb69//////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////7+/vzs/O////vb69zs/OjI2Ma21rj56cg42Mg42Ma21rd317d317a21rg42M -m66ts8/Om66tk56cra6tnJ6cd317s8/Ovt/e1v//1v//1v//1v//1v//1v//1v//1v//1v//1v// -1v//1v//1v//1v//1v//1v//1v//vt/ep769m66ta21rjI2Mvb697+/v//////////////////// -////////////////////////3t/ezs/Ozs/Ora6tnJ6ce317nJ6cqK6tnJ6c3t/e////zs/O7+/v -////////////////3t/enJ6cnJ6ce317ra6tnJ6cnJ6ce317e317ra6tzs/O7+/v//////////// -////3t/e3t/ezs/O////////////////3t/ea21ra21rj56ce317ub693t/e7+/v//////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////3t/ezs/Ozs/OnJ6cnJ6cqK6tn66tg42Mm66tg42Mp769s8/Os8/Oj56cj56cj56cnJ6cvb69 -nJ6cqK6ttL69nJ6cnJ6cpK6tg42Ma21rj56cj56cp769vt/es8/Om66ta21rg42Ma21ra21rd317 -e317nJ6czs/Ozs/Ozs/O7+/v//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -7+/vzs/Ozs/Ozs/Ozs/O3t/e//////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////3t/e -zs/Ozs/Ozs/Ozs/Ozs/Ozs/Ozs/Ozs/O7+/v//////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// - - - 20020215 - - Microsoft Windows 2000 Version 5.0 (Build 2195) Service Pack 2; ESRI ArcCatalog 8.1.3.679 - - - - - cntry02 - - - - - - - - - -180 - 180 - -90 - 83.6236 - 1 - - - -180 - 180 - -90 - 83.6236 - 1 - - - - - - ISO 19115 Geographic Information - Metadata - DIS_ESRI1.0 - {1F7DDF21-BC01-4C20-8AA5-243B33ED0B1E} - - - - - - - dataset - - - - - 002 - Local Area Network - - 3.830 - - - Shapefile - - - - - - - GCS_WGS_1984 - - - - - - - - - - - - - 251 - - - - diff --git a/share/data/shape/cntry02/cntry02.shx b/share/data/shape/cntry02/cntry02.shx deleted file mode 100755 index 64105f476..000000000 Binary files a/share/data/shape/cntry02/cntry02.shx and /dev/null differ diff --git a/share/data/shape/cntry02/cntry02.ssx b/share/data/shape/cntry02/cntry02.ssx deleted file mode 100755 index 72648e23c..000000000 Binary files a/share/data/shape/cntry02/cntry02.ssx and /dev/null differ diff --git a/share/data/shape/dcwpo-browse.shp b/share/data/shape/dcwpo-browse.shp deleted file mode 100644 index 57acabc86..000000000 Binary files a/share/data/shape/dcwpo-browse.shp and /dev/null differ diff --git a/share/data/shape/dcwpo-browse.ssx b/share/data/shape/dcwpo-browse.ssx deleted file mode 100644 index 362897182..000000000 Binary files a/share/data/shape/dcwpo-browse.ssx and /dev/null differ diff --git a/share/data/shape/vmap_area_thin.shp b/share/data/shape/vmap_area_thin.shp deleted file mode 100644 index b3a78678f..000000000 Binary files a/share/data/shape/vmap_area_thin.shp and /dev/null differ diff --git a/share/data/shape/vmap_area_thin.ssx b/share/data/shape/vmap_area_thin.ssx deleted file mode 100644 index 25187356d..000000000 Binary files a/share/data/shape/vmap_area_thin.ssx and /dev/null differ diff --git a/share/data/shape/vmap_edge_thin.shp b/share/data/shape/vmap_edge_thin.shp deleted file mode 100644 index 96025eb21..000000000 Binary files a/share/data/shape/vmap_edge_thin.shp and /dev/null differ diff --git a/share/data/shape/vmap_edge_thin.ssx b/share/data/shape/vmap_edge_thin.ssx deleted file mode 100644 index 7d83adb95..000000000 Binary files a/share/data/shape/vmap_edge_thin.ssx and /dev/null differ diff --git a/share/data/vpf/README b/share/data/vpf/README deleted file mode 100644 index 0914e2d53..000000000 --- a/share/data/vpf/README +++ /dev/null @@ -1,33 +0,0 @@ -This directory contains information that is used by the -VPFFeatureLayer and the VPFAutoFeatureGraphicWarehouse. The -symbol-lookup files are summaries of the MIL-PRF-89045 GeoSym standard -contents, that tie FACC codes, with certain parameter conditions, to -GeoSym symbol numbers. - -The dcw versions are pretty complete. The vmaplv0 version is not at -all, but they contain a sample for inland water that should get you -started. You'll need a copy of the 89045 doc to figure out the symbol -types you want to display. The VPFFeatureLayer uses the geosym cgm -files, you'll have to track those down (I'm not sure of the -releaseability). - - -The properties for a layer that uses these files are here: -vpf_water.class=com.bbn.openmap.layer.vpf.VPFFeatureLayer -vpf_water.prettyName=VMAPLV0 Inland Water -vpf_water.vpfPath=/Volumes/data/vpf/vmaplv0/v0noa/vmaplv0 -# VFPAutoFeatureGraphicWarehouse options: -vpf_water.cgmDirectory=data/geosym/cgm/ -vpf_water.faccLookupFile=data/vpf/vmaplv0-symbol-lookup.csv -# The priority file is the file to adjust to customize display... -vpf_water.priorityFile=data/vpf/vmaplv0-priority-iw.csv -vpf_water.featureInfoHandler=com.bbn.openmap.layer.vpf.TTFeatureInfoHandler - -The order of how different features are laid out are specified in the -priority file, and feature rendering is determined by the cgm files. - -Using this layer can be slower than the standard VPFLayer, especially -with a lot of FACC codes being rendered. I recommend that you -configure the layer, and then use it to make map image tiles with the -com.bbn.openmap.dataAccess.mapTile.MapTileMaker. You can then use the -tiles in the map using the com.bbn.openmap.layer.image.MapTileLayer. \ No newline at end of file diff --git a/share/data/vpf/dnc-priority-all.csv b/share/data/vpf/dnc-priority-all.csv deleted file mode 100644 index a3d83ec86..000000000 --- a/share/data/vpf/dnc-priority-all.csv +++ /dev/null @@ -1,513 +0,0 @@ -priority,type,facc,conditions,description -0,Area,BA040, -0,Area,BE010,cvl=99999 -0,Area,BE010,idsm=0 AND cvl>=msdcand<>99999 -0,Area,BE010,idsm=0 AND cvl>=ssdcand=msscand=msscand=ssdcand<>99999 -0,Area,BE010,idsm=1 AND isdm=0 AND cvl=msdc -1,Area,FC031,mac=2 AND idsm=0 AND hdp>=msscand=msscand=ssdcand0and0and=ssdc -1,Area,FC031,mac=2 AND idsm=1 AND hdp>0and0and7and<>13 AND mac=NULL -3,Line,FC021,mbl=7 AND mac=NULL -3,Area,AC030, -3,Area,AL020, -3,Area,AN060, -3,Area,BB010,mac<>12 -3,Area,BB180, -3,Area,BD060, -3,Area,BH050, -3,Area,BH095, -3,Area,BH155, -3,Area,BJ030, -3,Area,BJ030, -3,Area,BJ065, -3,Area,BJ065, -3,Area,BJ100, -3,Area,BJ100, -3,Area,DB090, -3,Area,DB170, -3,Area,EA030, -3,Area,EA040, -3,Area,EA050, -3,Area,EC030,veg<>19 -3,Area,EC030,veg=19 -3,Area,FC021,mac=0or999 -3,Area,FC021,mac=25or30or35 -3,Area,FC021,mac=26 -3,Area,FC021,mac=26 -3,Area,FC021,mac=26 -3,Area,FC021,mac=31 -3,Area,FC021,mac=49 -3,Area,FC021,mac=57 -3,Area,FC031,mac=0or9 -3,Area,FC036,mac=20 -3,Area,FC036,mac=21or23or61 -3,Area,FC036,mac=45or46 -3,Area,FC165,rtt=0 -4,Point,AF040, -4,Point,AH010, -4,Point,AH050, -4,Point,AL015,bfc<>7and<>81 -4,Point,AL200,loc=22 AND vrr=4 AND hdp=0 -4,Point,AL200,loc=22 AND vrr=4 AND hdp>0and<=20 -4,Point,AL200,loc=22 AND vrr=4 AND hdp>20 -4,Point,AL200,loc=22 AND vrr=8 -4,Point,AM020, -4,Point,AM030, -4,Point,AM070, -4,Point,AM080, -4,Point,AQ080, -4,Point,BA030, -4,Point,BB105, -4,Point,BB180, -4,Point,BC010,nst=1or4or5or17or41or51or53 -4,Point,BC020,nst=1or4or5or17or41or51or53 AND ssc<>10 -4,Point,BC020,nst=1or4or5or17or41or51or53 AND ssc=10 -4,Point,BC040,nst=1or4or5or17or41or51or53 -4,Point,BC070,nst=1or4or5or17or41or51or53 -4,Point,BC080, -4,Point,BD000,acc<>1 -4,Point,BD000,hdp=0 -4,Point,BD000,hdp>0and<=20 -4,Point,BD000,hdp>20 -4,Point,BD020,acc<>1 -4,Point,BD020,vrr=1 AND hdp=NULL -4,Point,BD020,vrr=4 AND hdp=0 -4,Point,BD020,vrr=4 AND hdp>0and<=20 -4,Point,BD020,vrr=4 AND hdp>20 -4,Point,BD020,vrr=8 AND hdp=NULL -4,Point,BD030, -4,Point,BD030,acc<>1 -4,Point,BD050, -4,Point,BD130,acc<>1 -4,Point,BD130,hdp=NULL -4,Point,BD130,vrr=4 AND hdp=0 -4,Point,BD130,vrr=4 AND hdp>0and<=20 -4,Point,BD130,vrr=4 AND hdp>20 -4,Point,BD140,acc<>1 -4,Point,BD140,vrr=1 AND hdp=NULL -4,Point,BD140,vrr=4 AND hdp=0 -4,Point,BD140,vrr=4 AND hdp>0and<=20 -4,Point,BD140,vrr=4 AND hdp>20 -4,Point,BD140,vrr=8 AND hdp=NULL -4,Point,BD180,acc<>1 -4,Point,BD180,hdp=NULL AND vrr=0 -4,Point,BD180,hdp=NULL AND vrr=1or2or8 -4,Point,BD180,loc<>4 AND hdp=NULL -4,Point,BD180,vrr=4 AND hdp>0and<=20 -4,Point,BD180,vrr=4 AND hdp>20 -4,Point,BD180,vrr=4 AND soh=1 AND hdp=0 -4,Point,BD180,vrr=4 AND soh=2 AND hdp=0 -4,Point,BF010,mcc=0 AND psc=0 -4,Point,BG010,cur=1 AND dof<>0 -4,Point,BG010,cur=2 AND dof<>0 -4,Point,BG030, -4,Point,BG040, -4,Point,CA030, -4,Point,EC030, -4,Point,FC021,mac<>48 -4,Point,FC031,mac=0 -4,Point,FC031,mac=2 -4,Point,FC165,dof<>0 -4,Point,FC165,dof=0 -4,Point,GA035, -4,Point,GB005, -4,Line,AK130, -4,Line,AN010, -4,Line,AP020, -4,Line,AP030, -4,Line,AQ070,fer=1 -4,Line,AQ070,fer=2 -4,Line,AQ130, -4,Line,BA020, -4,Line,BB010,mac<>12 -4,Line,BB100, -4,Line,BC100, -4,Line,BD010, -4,Line,CA010, -4,Line,DB090, -4,Line,FA000,use=23 -4,Line,FA000,use=32 -4,Line,FA020, -4,Line,FA040, -4,Line,FA060, -4,Line,FA110, -4,Line,FC021,mac=0or999 AND mbl=NULL -4,Line,FC021,mac=25 AND mbl=NULL -4,Line,FC021,mac=30or35 AND mbl=NULL -4,Line,FC021,mac=31 AND mbl=NULL -4,Line,FC021,mac=49 AND mbl=NULL -4,Line,FC021,mac=56 AND mbl=NULL -4,Line,FC021,mac=57 AND mbl=NULL -4,Line,FC021,mbl=13 AND mac=NULL -4,Line,FC031,mac=0or9 -4,Line,FC100, -4,Area,AA010, -4,Area,AB000, -4,Area,AB010, -4,Area,AC000, -4,Area,AD010, -4,Area,AD030, -4,Area,AH010, -4,Area,AH050, -4,Area,AK040, -4,Area,AK160, -4,Area,AL015, -4,Area,AL030, -4,Area,AL200,loc=22 AND vrr=1 -4,Area,AL200,loc=22 AND vrr=4 AND hdp=0 -4,Area,AL200,loc=22 AND vrr=4 AND hdp>0and<=20 -4,Area,AL200,loc=22 AND vrr=4 AND hdp>20 -4,Area,AL200,loc=22 AND vrr=8 -4,Area,AL200,loc=8 -4,Area,AM010, -4,Area,AM030, -4,Area,AM040, -4,Area,AM070, -4,Area,AQ116, -4,Area,AT020, -4,Area,BB090, -4,Area,BB110, -4,Area,BB150, -4,Area,BC080, -4,Area,BD000,acc<>1 -4,Area,BD000,hdp=0 -4,Area,BD000,hdp>0and<=20 -4,Area,BD000,hdp>20 -4,Area,BD010, -4,Area,BD020,acc<>1 -4,Area,BD020,vrr=1 AND hdp=NULL -4,Area,BD020,vrr=4 AND hdp=0 -4,Area,BD020,vrr=4 AND hdp>0and<=20 -4,Area,BD020,vrr=4 AND hdp>20 -4,Area,BD020,vrr=8 AND hdp=NULL -4,Area,BD030, -4,Area,BD030,acc<>1 -4,Area,BD040, -4,Area,BD050, -4,Area,BD080, -4,Area,BD100,acc<>1 -4,Area,BD100,vrr=1 -4,Area,BD100,vrr=4 -4,Area,BD100,vrr=8 -4,Area,BD120,vrr<>8 AND acc<>1 -4,Area,BD120,vrr<>8 AND hdp=0orNULL -4,Area,BD120,vrr=4 AND hdp>0and<=20 -4,Area,BD120,vrr=4 AND hdp>20 -4,Area,BD140,acc<>1 -4,Area,BD140,vrr=1 -4,Area,BD140,vrr=4 -4,Area,BD140,vrr=8 -4,Area,BD180,vrr=0or2 AND hdp=NULL -4,Area,BD180,vrr=1 AND hdp=NULL -4,Area,BD180,vrr=4 AND hdp=0 -4,Area,BD180,vrr=4 AND hdp>0and<=20 -4,Area,BD180,vrr=4 AND hdp>20 -4,Area,BD180,vrr=8 AND hdp=NULL -4,Area,FC021,mac=27or28or29 -4,Area,FC021,mac=32or33 -4,Area,FC021,mac=42 -4,Area,FC021,mac=48 -4,Area,FC021,mac=55 -4,Area,FC021,mac=56 -4,Area,FC041,tsp=3 -4,Area,FC165,rtt=11 -4,Area,FC165,rtt=4 -4,Area,FC177, -4,Area,GB070, -4,Area,ZC040, -5,Point,AT045,ssc=0or999 -5,Point,AT045,ssc=107 -5,Point,AT045,ssc=108 -5,Point,AT045,ssc=60 -5,Point,AT045,ssc=87 -5,Point,BB010,mac=12 -5,Point,BB020, -5,Point,BB150, -5,Point,BC010,nst=45 -5,Point,BC020,btc=35 -5,Point,BC020,nst=45 -5,Point,BC040, -5,Point,BC040,nst=45 -5,Point,BC070,nst=45 -5,Point,BD100, -5,Point,BD110, -5,Point,BG010,cur=0 OR dof=0 -5,Point,BG010,cur=3or5 AND dof<>0 -5,Line,BE010,acc=1 -5,Line,BE010,acc=2 -5,Line,FC021,mac=27or28or29 AND mbl=NULL -5,Line,FC021,mac=32or33 AND mbl=NULL -5,Line,FC021,mac=42 AND mbl=NULL -5,Line,FC021,mac=48 AND mbl=NULL -5,Line,FC021,mac=55 AND mbl=NULL -5,Line,FC177, -5,Line,GB070, -5,Area,AL005, -5,Area,BB010,mac=12 -5,Area,BB115, -5,Area,BB170, -5,Area,FC021,mac=24 -5,Area,FC021,mac=44 -5,Area,FC021,mac=58 -5,Area,FC031,mac=4 -5,Area,FC031,mac=41 -5,Area,FC036,mac=0or999 -5,Area,FC036,mac=37 -5,Area,GB055, -6,Point,AD030, -6,Point,AF010, -6,Point,AF030, -6,Point,AF070, -6,Point,AJ050, -6,Point,AK020, -6,Point,AK080, -6,Point,AK160, -6,Point,AL015,bfc=7 AND hwt=0or2or3or4or7or22 -6,Point,AL015,bfc=7 AND hwt=11or14or15or16or20or21 -6,Point,AL015,bfc=7 AND hwt=5or6or9 -6,Point,AL015,bfc=81 AND sta<>5 AND sst<>16 -6,Point,AL015,bfc=81 AND sta=0or2or3or6or11 -6,Point,AL015,bfc=81 AND sta=5 AND sst<>16 -6,Point,AL018, -6,Point,AL025, -6,Point,AL073, -6,Point,AL130, -6,Point,AL200,loc=22 AND vrr=1 -6,Point,AL200,loc=8 -6,Point,AL240, -6,Point,AQ060, -6,Point,AQ110, -6,Point,AQ116, -6,Point,AT010, -6,Point,AT050, -6,Point,AT080, -6,Point,BB010,mac<>12 -6,Point,BB030, -6,Point,BB050,df1<>0 AND df2=0 -6,Point,BB050,df1=0 -6,Point,BB050,df2<>0 AND df3=0 -6,Point,BB050,df3<>0 -6,Point,BB050,df3<>0 -6,Point,BB050,df3<>0 -6,Point,BB050,df4<>0 -6,Point,BB080, -6,Point,BB160, -6,Point,BC010,nst=10or54 -6,Point,BC010,ref=1 -6,Point,BC010,sst=1or2or3or4or6or9or14or15 -6,Point,BC010,tmc=0or32 -6,Point,BC010,tmc=1 -6,Point,BC010,tmc=15or27or28 -6,Point,BC010,tmc=16or21 -6,Point,BC010,tmc=17 -6,Point,BC010,tmc=18 -6,Point,BC010,tmc=19or31 -6,Point,BC010,tmc=2 -6,Point,BC010,tmc=22 -6,Point,BC010,tmc=23or30 -6,Point,BC010,tmc=25or26or29 -6,Point,BC010,tmc=3 -6,Point,BC010,tmc=6 -6,Point,BC010,tmc=8 -6,Point,BC010,tmc=9 -6,Point,BC020,nst=10or54 AND ssc<>10 -6,Point,BC020,nst=10or54 AND ssc=10 -6,Point,BC020,ref=1 -6,Point,BC020,sst=1or2or3or4or6or9or14or15 -6,Point,BC020,tmc=0or17or18or32 -6,Point,BC020,tmc=1 -6,Point,BC020,tmc=15or27or28 -6,Point,BC020,tmc=16or21 -6,Point,BC020,tmc=19or31 -6,Point,BC020,tmc=2 -6,Point,BC020,tmc=22 -6,Point,BC020,tmc=23or30 -6,Point,BC020,tmc=25or26or29 -6,Point,BC020,tmc=3 -6,Point,BC020,tmc=6 -6,Point,BC020,tmc=8 -6,Point,BC020,tmc=9 -6,Point,BC040,nst=10or54 -6,Point,BC040,ref=1 -6,Point,BC040,sst=1or2or3or4or6or9or14or15 -6,Point,BC040,tmc=0or32 -6,Point,BC040,tmc=1 -6,Point,BC040,tmc=15or27or28 -6,Point,BC040,tmc=16or21 -6,Point,BC040,tmc=17 -6,Point,BC040,tmc=18 -6,Point,BC040,tmc=19or31 -6,Point,BC040,tmc=2 -6,Point,BC040,tmc=22 -6,Point,BC040,tmc=23or30 -6,Point,BC040,tmc=25or26or29 -6,Point,BC040,tmc=3 -6,Point,BC040,tmc=6 -6,Point,BC040,tmc=8 -6,Point,BC040,tmc=9 -6,Point,BC070,nst=10or54 -6,Point,BC070,ref=1 -6,Point,BC070,sst=1or2or3or4or6or9or14or15 -6,Point,BD110,nst=10or54 -6,Point,BD110,sst<>16 -6,Point,BE020,acc<>1 -6,Point,BE020,hdh>=0 AND hdp=NULL -6,Point,FC021,mac=48 -6,Point,FC031,mac=4 -6,Point,FC036,mac=0or999 -6,Point,FC036,mac=37 -6,Line,AQ113,loc<>25 AND pro<>95and<>116 AND plt<>2and<>3 -6,Line,AQ113,loc<>25 AND pro=116 -6,Line,AQ113,loc<>25 AND pro=95 OR plt=2or3 -6,Line,BB010,mac=12 -6,Line,BB170, -6,Line,BC040, -6,Line,BH010,loc<>25 -6,Line,BI020, -6,Line,FC021,mac=24 AND mbl=NULL -6,Line,FC021,mac=44 AND mbl=NULL -6,Line,FC021,mac=58 AND mbl=NULL -6,Line,FC031,mac=4 -6,Line,FC036, -6,Line,FC130, -6,Line,FC165,atn=1 AND exs=22 AND rtt<>3 -6,Line,FC165,atn=1 AND exs=22 AND rtt=3 -6,Line,FC165,atn=1 AND exs=23 AND rtt<>3 -6,Line,FC165,atn=1 AND exs=23 AND rtt=3 -6,Line,FC165,atn=2 AND exs=22 AND rtt<>3 -6,Line,FC165,atn=2 AND exs=22 AND rtt=3 -6,Line,FC165,atn=2 AND exs=23 AND rtt<>3 -6,Line,FC165,atn=2 AND exs=23 AND rtt=3 -6,Line,FC165,exs=0 AND rtt<>3 -6,Line,FC165,exs=0 AND rtt=3 -6,Line,FC170, -6,Line,GB055, -6,Area,BB040,vrr=1 -6,Area,BB040,vrr=4or8 -6,Area,BB140,vrr=1 -6,Area,BB140,vrr=4or8 -6,Area,BB190, -6,Area,BB220,vrr=1 -6,Area,BB220,vrr=4or8 -6,Area,FC031,mac=40 -6,Area,FC031,mac=5 -6,Area,FC036,mac=15 -6,Area,FC036,mac=22 -6,Area,FC036,mac=43 -6,Area,FC041,tsp=6or7 -6,Area,FC170, -7,Point,AL015,bfc=81 AND sta<>0and<>1and<>2and<>3and<>5and<>6and<>11 -7,Point,AL015,bfc=81 AND sta=1 -7,Point,AL015,bfc=81 AND sta=5 -7,Point,BA020, -7,Point,BC055, -7,Point,BG020, -7,Point,FC031,mac=40 -7,Point,FC031,mac=5 -7,Point,FC036,mac=15 -7,Point,FC036,mac=22 -7,Point,FC036,mac=43 -7,Point,FC041, -7,Line,BA010,acc=1 AND slt<>6and<>8 -7,Line,BA010,acc=2 AND slt<>6and<>8 -7,Line,BA010,slt=6or8 -7,Line,BB040,vrr=1 -7,Line,BB040,vrr=4or8 -7,Line,BB140,vrr=1 -7,Line,BB140,vrr=4or8 -7,Line,BB190, -7,Line,BB220,vrr=1 -7,Line,BB220,vrr=4or8 -7,Line,BB230, -7,Line,BB240,vrr=1 -7,Line,BB240,vrr=4or8 -7,Line,FC031,mac=40or41 -7,Line,FC031,mac=5 -7,Line,FC041,tsp=2 -8,Point,AL050, -8,Point,AQ020, -8,Point,AT040, -8,Point,BB170, -8,Point,BB170,cha=21 -8,Point,BC010, -8,Point,BC020,btc=0 AND ssc=0or85or999 -8,Point,BC020,btc=0 AND ssc=1 -8,Point,BC020,btc=0 AND ssc=10 -8,Point,BC020,btc=0 AND ssc=16 -8,Point,BC020,btc=0 AND ssc=17 -8,Point,BC020,btc=0 AND ssc=6 -8,Point,BC020,btc=0 AND ssc=7 -8,Point,BC020,btc=0 AND ssc=73 -8,Point,BC020,btc=10 -8,Point,BC020,btc=4 -8,Point,BC020,btc=6 -8,Point,BC020,btc=7 AND ssc<>1and<>7 -8,Point,BC020,btc=7 AND ssc=1 -8,Point,BC020,btc=7 AND ssc=7 -8,Point,BC070, -8,Point,BD110,cha=21 -8,Point,GA020, -8,Point,GB010, -8,Line,AQ010, -8,Line,AQ040,bsc<>12 AND bot<>4and<>10and<>11 -8,Line,AQ040,bsc=12 OR bot=4or10or11 -8,Line,AQ045, -8,Line,AQ113,loc=25 -8,Line,AT030, -8,Line,AT060, -8,Line,BH010,loc=25 -8,Line,BI040, -8,Line,FC041,tsp=4 -8,Area,AQ040,bsc<>12 AND bot<>4and<>10and<>11 -8,Area,AQ040,bsc=12 OR bot=4or10or11 -8,Area,AQ045, -8,Area,BC060, diff --git a/share/data/vpf/dnc-priority-background.csv b/share/data/vpf/dnc-priority-background.csv deleted file mode 100644 index 0432f7eaf..000000000 --- a/share/data/vpf/dnc-priority-background.csv +++ /dev/null @@ -1,275 +0,0 @@ -priority,type,facc,conditions -0,Area,BA040, -0,Area,BE010,cvl=99999 -0,Area,BE010,idsm=0 AND cvl>=msdcand<>99999 -0,Area,BE010,idsm=0 AND cvl>=ssdcand=msscand=msscand=ssdcand<>99999 -0,Area,BE010,idsm=1 AND isdm=0 AND cvl=msdc -1,Area,FC031,mac=2 AND idsm=0 AND hdp>=msscand=msscand=ssdcand0and0and=ssdc -1,Area,FC031,mac=2 AND idsm=1 AND hdp>0and0and7and<>13 AND mac=NULL -3,Line,FC021,mbl=7 AND mac=NULL -3,Area,AC030, -3,Area,AL020, -3,Area,AN060, -3,Area,BB010,mac<>12 -3,Area,BB180, -3,Area,BD060, -3,Area,BH050, -3,Area,BH095, -3,Area,BH155, -3,Area,BJ030, -3,Area,BJ030, -3,Area,BJ065, -3,Area,BJ065, -3,Area,BJ100, -3,Area,BJ100, -3,Area,DB090, -3,Area,DB170, -3,Area,EA030, -3,Area,EA040, -3,Area,EA050, -3,Area,EC030,veg<>19 -3,Area,EC030,veg=19 -3,Area,FC021,mac=0or999 -3,Area,FC021,mac=25or30or35 -3,Area,FC021,mac=26 -3,Area,FC021,mac=26 -3,Area,FC021,mac=26 -3,Area,FC021,mac=31 -3,Area,FC021,mac=49 -3,Area,FC021,mac=57 -3,Area,FC031,mac=0or9 -3,Area,FC036,mac=20 -3,Area,FC036,mac=21or23or61 -3,Area,FC036,mac=45or46 -3,Area,FC165,rtt=0 -4,Line,AK130, -4,Line,AN010, -4,Line,AP020, -4,Line,AP030, -#4,Line,AQ070,fer=1 -#4,Line,AQ070,fer=2 -4,Line,AQ130, -4,Line,BA020, -4,Line,BB010,mac<>12 -4,Line,BB100, -4,Line,BC100, -4,Line,BD010, -4,Line,CA010, -4,Line,DB090, -4,Line,FA000,use=23 -4,Line,FA000,use=32 -4,Line,FA020, -4,Line,FA040, -4,Line,FA060, -4,Line,FA110, -4,Line,FC021,mac=0or999 AND mbl=NULL -4,Line,FC021,mac=25 AND mbl=NULL -4,Line,FC021,mac=30or35 AND mbl=NULL -4,Line,FC021,mac=31 AND mbl=NULL -4,Line,FC021,mac=49 AND mbl=NULL -4,Line,FC021,mac=56 AND mbl=NULL -4,Line,FC021,mac=57 AND mbl=NULL -4,Line,FC021,mbl=13 AND mac=NULL -4,Line,FC031,mac=0or9 -4,Line,FC100, -4,Area,AA010, -4,Area,AB000, -4,Area,AB010, -4,Area,AC000, -4,Area,AD010, -4,Area,AD030, -4,Area,AH010, -4,Area,AH050, -4,Area,AK040, -4,Area,AK160, -4,Area,AL015, -4,Area,AL030, -4,Area,AL200,loc=22 AND vrr=1 -4,Area,AL200,loc=22 AND vrr=4 AND hdp=0 -4,Area,AL200,loc=22 AND vrr=4 AND hdp>0and<=20 -4,Area,AL200,loc=22 AND vrr=4 AND hdp>20 -4,Area,AL200,loc=22 AND vrr=8 -4,Area,AL200,loc=8 -4,Area,AM010, -4,Area,AM030, -4,Area,AM040, -4,Area,AM070, -4,Area,AQ116, -4,Area,AT020, -4,Area,BB090, -4,Area,BB110, -4,Area,BB150, -4,Area,BC080, -4,Area,BD010, -4,Area,BD020,acc<>1 -4,Area,BD020,vrr=1 AND hdp=NULL -4,Area,BD020,vrr=4 AND hdp=0 -4,Area,BD020,vrr=4 AND hdp>0and<=20 -4,Area,BD020,vrr=4 AND hdp>20 -4,Area,BD020,vrr=8 AND hdp=NULL -4,Area,BD030, -4,Area,BD030,acc<>1 -4,Area,BD040, -4,Area,BD050, -4,Area,BD080, -4,Area,BD100,acc<>1 -4,Area,BD100,vrr=1 -4,Area,BD100,vrr=4 -4,Area,BD100,vrr=8 -4,Area,BD120,vrr<>8 AND acc<>1 -4,Area,BD120,vrr<>8 AND hdp=0orNULL -4,Area,BD120,vrr=4 AND hdp>0and<=20 -4,Area,BD120,vrr=4 AND hdp>20 -4,Area,BD140,acc<>1 -4,Area,BD140,vrr=1 -4,Area,BD140,vrr=4 -4,Area,BD140,vrr=8 -4,Area,BD180,vrr=0or2 AND hdp=NULL -4,Area,BD180,vrr=1 AND hdp=NULL -4,Area,BD180,vrr=4 AND hdp=0 -4,Area,BD180,vrr=4 AND hdp>0and<=20 -4,Area,BD180,vrr=4 AND hdp>20 -4,Area,BD180,vrr=8 AND hdp=NULL -4,Area,FC021,mac=27or28or29 -4,Area,FC021,mac=32or33 -4,Area,FC021,mac=42 -4,Area,FC021,mac=48 -4,Area,FC021,mac=55 -4,Area,FC021,mac=56 -4,Area,FC041,tsp=3 -4,Area,FC165,rtt=11 -4,Area,FC165,rtt=4 -4,Area,FC177, -4,Area,GB070, -4,Area,ZC040, -5,Line,FC021,mac=27or28or29 AND mbl=NULL -5,Line,FC021,mac=32or33 AND mbl=NULL -5,Line,FC021,mac=42 AND mbl=NULL -5,Line,FC021,mac=48 AND mbl=NULL -5,Line,FC021,mac=55 AND mbl=NULL -5,Line,FC177, -5,Line,GB070, -5,Area,AL005, -5,Area,BB010,mac=12 -5,Area,BB115, -5,Area,BB170, -5,Area,FC021,mac=24 -5,Area,FC021,mac=44 -5,Area,FC021,mac=58 -5,Area,FC031,mac=4 -5,Area,FC031,mac=41 -5,Area,FC036,mac=0or999 -5,Area,FC036,mac=37 -5,Area,GB055, -#6,Line,AQ113,loc<>25 AND pro<>95and<>116 AND plt<>2and<>3 -#6,Line,AQ113,loc<>25 AND pro=116 -#6,Line,AQ113,loc<>25 AND pro=95 OR plt=2or3 -6,Line,BB010,mac=12 -6,Line,BB170, -6,Line,BC040, -6,Line,BH010,loc<>25 -6,Line,BI020, -6,Line,FC021,mac=24 AND mbl=NULL -6,Line,FC021,mac=44 AND mbl=NULL -6,Line,FC021,mac=58 AND mbl=NULL -6,Line,FC031,mac=4 -6,Line,FC036, -6,Line,FC130, -6,Line,FC165,atn=1 AND exs=22 AND rtt<>3 -6,Line,FC165,atn=1 AND exs=22 AND rtt=3 -6,Line,FC165,atn=1 AND exs=23 AND rtt<>3 -6,Line,FC165,atn=1 AND exs=23 AND rtt=3 -6,Line,FC165,atn=2 AND exs=22 AND rtt<>3 -6,Line,FC165,atn=2 AND exs=22 AND rtt=3 -6,Line,FC165,atn=2 AND exs=23 AND rtt<>3 -6,Line,FC165,atn=2 AND exs=23 AND rtt=3 -6,Line,FC165,exs=0 AND rtt<>3 -6,Line,FC165,exs=0 AND rtt=3 -6,Line,FC170, -6,Line,GB055, -6,Area,BB040,vrr=1 -6,Area,BB040,vrr=4or8 -6,Area,BB140,vrr=1 -6,Area,BB140,vrr=4or8 -6,Area,BB190, -6,Area,BB220,vrr=1 -6,Area,BB220,vrr=4or8 -6,Area,FC031,mac=40 -6,Area,FC031,mac=5 -6,Area,FC036,mac=15 -6,Area,FC036,mac=22 -6,Area,FC036,mac=43 -6,Area,FC041,tsp=6or7 -6,Area,FC170, -7,Line,BA010,acc=1 AND slt<>6and<>8 -7,Line,BA010,acc=2 AND slt<>6and<>8 -7,Line,BA010,slt=6or8 -7,Line,BB040,vrr=1 -7,Line,BB040,vrr=4or8 -7,Line,BB140,vrr=1 -7,Line,BB140,vrr=4or8 -7,Line,BB190, -7,Line,BB220,vrr=1 -7,Line,BB220,vrr=4or8 -7,Line,BB230, -7,Line,BB240,vrr=1 -7,Line,BB240,vrr=4or8 -7,Line,FC031,mac=40or41 -7,Line,FC031,mac=5 -7,Line,FC041,tsp=2 -8,Line,AQ010, -8,Line,AQ040,bsc<>12 AND bot<>4and<>10and<>11 -8,Line,AQ040,bsc=12 OR bot=4or10or11 -8,Line,AQ045, -#8,Line,AQ113,loc=25 -8,Line,AT030, -8,Line,AT060, -8,Line,BH010,loc=25 -8,Line,BI040, -8,Line,FC041,tsp=4 -8,Area,AQ040,bsc<>12 AND bot<>4and<>10and<>11 -8,Area,AQ040,bsc=12 OR bot=4or10or11 -8,Area,AQ045, -8,Area,BC060, diff --git a/share/data/vpf/dnc-priority-depth-contours.csv b/share/data/vpf/dnc-priority-depth-contours.csv deleted file mode 100644 index f91a34d4a..000000000 --- a/share/data/vpf/dnc-priority-depth-contours.csv +++ /dev/null @@ -1,3 +0,0 @@ -priority,type,facc,conditions,description -5,Line,BE010,acc=1 -5,Line,BE010,acc=2 diff --git a/share/data/vpf/dnc-symbol-lookup.csv b/share/data/vpf/dnc-symbol-lookup.csv deleted file mode 100644 index 1f8957555..000000000 --- a/share/data/vpf/dnc-symbol-lookup.csv +++ /dev/null @@ -1,544 +0,0 @@ -facc,type,symbol,conditions,size,xoff,yoff -AA010,P,0001,,,, -AA010,A,0027 0624,,,, -AB000,A,0624,,,, -AB010,A,0624,,,, -AC000,A,0624,,,, -AC030,A,4077,,,, -AD010,A,0804,,,, -AD030,P,0002,,,, -AD030,A,0804,,,, -AF010,P,0003,,,, -AF030,P,0004,,,, -AF040,P,0005,,,, -AF070,P,0006,,,, -AH010,P,0007,,,, -AH010,A,0804,,,, -AH050,P,0007,,,, -AH050,A,0804,,,, -AJ050,P,0008,,,, -AK020,P,0024,,,, -AK020,L,0600,,,, -AK040,A,0804,,,, -AK080,P,0024,,,, -AK090,A,0822,,,, -AK130,L,0605,,,, -AK160,P,0002,,,, -AK160,A,0804,,,, -AL005,A,0081 0734,,,, -AL015,P,0002,bfc=81ANDsta=0or2or3or6or11,,, -AL015,P,0010,bfc=7ANDhwt=0or2or3or4or7or22,,, -AL015,P,0011,bfc=7ANDhwt=11or14or15or16or20or21,,, -AL015,P,0012,bfc=7ANDhwt=5or6or9,,, -AL015,P,0013,bfc=81ANDsta=1,,, -AL015,P,0014,bfc=81ANDsta=5,,, -AL015,P,0015,bfc=81ANDsta<>0and<>1and<>2and<>3and<>5and<>6and<>11,,, -AL015,P,0401,bfc=81ANDsta=5ANDsst<>16,.5,0,.5 -AL015,P,0402,bfc=81ANDsta<>5ANDsst<>16,,, -AL015,P,2036,bfc<>7and<>81,,, -AL015,A,0804,,,, -AL018,P,0002,,,, -AL020,P,0016,,,, -AL020,A,0804,,,, -AL025,P,0017,,,, -AL030,A,0804,,,, -AL050,P,0018,,,, -AL070,L,0600,,,, -AL073,P,0019,,,, -AL130,P,0020,,,, -AL200,P,0002,loc=22ANDvrr=1,,, -AL200,P,0002,loc=8,,, -AL200,P,0052,loc=22ANDvrr=4ANDhdp=0,,, -AL200,P,0053,loc=22ANDvrr=4ANDhdp>0and<=20,,, -AL200,P,0054,loc=22ANDvrr=4ANDhdp>20,,, -AL200,P,0055,loc=22ANDvrr=8,,, -AL200,A,0804,loc=22ANDvrr=1,,, -AL200,A,0804,loc=8,,, -AL200,A,0803,loc=22ANDvrr=8,,, -AL200,A,0629,loc=22ANDvrr=4ANDhdp>20,,, -AL200,A,0680,loc=22ANDvrr=4ANDhdp>0and<=20,,, -AL200,A,0810,loc=22ANDvrr=4ANDhdp=0,,, -AL240,P,0004,,,, -AL260,L,0600,,,, -AM010,A,0624,,,, -AM020,P,0021,,,, -AM030,P,0004,,,, -AM030,A,0804,,,, -AM040,A,0624,,,, -AM070,P,0022,,,, -AM070,A,0804,,,, -AM080,P,0023,,,, -AN010,L,0605,,,, -AN060,A,0802,,,, -AP020,L,0605,,,, -AP030,L,0605,,,, -AQ010,L,0657,,,, -AQ020,P,0024,,,, -AQ040,L,0627,bsc<>12ANDbot<>4and<>10and<>11,,, -AQ040,L,0753,bsc=12ORbot=4or10or11,,, -AQ040,A,0611,bsc<>12ANDbot<>4and<>10and<>11,,, -AQ040,A,0611,bsc=12ORbot=4or10or11,,, -AQ045,L,0627,,,, -AQ045,A,0611,,,, -AQ060,P,0004,,,, -AQ070,L,0700,fer=2,,, -AQ070,L,0701,fer=1,,, -AQ080,P,0096,,,, -AQ110,P,0026,,,, -AQ113,L,0610,loc=25,,, -AQ113,L,0704,loc<>25ANDpro=95ORplt=2or3,,, -AQ113,L,0704,loc<>25ANDpro=116,,, -AQ113,L,0705,loc<>25ANDpro<>95and<>116ANDplt<>2and<>3,,, -AQ116,P,0002,,,, -AQ116,A,0804,,,, -AQ130,L,0656,,,, -AT005,L,0708,,,, -AT010,P,2102,,,, -AT020,A,0804,,,, -AT030,L,0657,,,, -AT040,P,0024,,,, -AT045,P,0028,ssc=87,,, -AT045,P,0029,ssc=108,,, -AT045,P,0030,ssc=60,,, -AT045,P,0031,ssc=107,,, -AT045,P,0511,ssc=0or999,,, -AT050,P,0033,,,, -AT060,L,0657,,,, -AT080,P,0004,,,, -BA010,L,0632,slt=6or8,,, -BA010,L,0743,acc=2ANDslt<>6and<>8,,, -BA010,L,1573,acc=1ANDslt<>6and<>8,,, -BA020,P,0150,,,, -BA020,L,3082,,,, -BA020,A,0803,,,, -BA020,A,0949,,,, -BA030,P,0035,,,, -BA030,A,0822,,,, -BA040,A,0805,,,, -BB010,P,0036,mac<>12,,, -BB010,P,0037,mac=12,,, -BB010,L,0711,mac<>12,,, -BB010,L,3000,mac=12,,, -BB010,A,0037 3000,mac=12,,, -BB010,A,0902 0711,mac<>12,,, -BB020,P,0032,,,, -BB030,P,0051,,.35,, -BB040,L,0623,vrr=1,,, -BB040,L,0626,vrr=4or8,,, -BB040,A,0623,vrr=1,,, -BB040,A,0626,vrr=4or8,,, -BB050,P,0039,df3<>0,,, -BB050,P,0039,df3<>0,,, -BB050,P,0039,df3<>0,,, -BB050,P,0039,df4<>0,,, -BB050,P,0039,df1<>0ANDdf2=0,,, -BB050,P,0040,df2<>0ANDdf3=0,,, -BB050,P,0041,df1=0,,, -BB080,P,0038,,,, -BB090,A,1573 0822,,,, -BB100,L,0712,,,, -BB105,P,0042,,,, -BB110,A,0047 0716,,,, -BB115,A,0656,,,, -BB140,L,0623,vrr=1,,, -BB140,L,0626,vrr=4or8,,, -BB140,A,0623,vrr=1,,, -BB140,A,0626,vrr=4or8,,, -BB150,P,0043,,,, -BB150,A,0804,,,, -BB160,P,0038,,,, -BB170,P,0044,,,, -BB170,P,0500,cha=21,,, -BB170,L,0625,,,, -BB170,A,0804,,,, -BB180,P,0045,,,, -BB180,A,0904,,,, -BB190,L,0625,,,, -BB190,A,0625,,,, -BB220,L,0623,vrr=1,,, -BB220,L,0626,vrr=4or8,,, -BB220,A,0623,vrr=1,,, -BB220,A,0626,vrr=4or8,,, -BB230,L,0623,,,, -BB240,L,0623,vrr=1,,, -BB240,L,0626,vrr=4or8,,, -BC010,P,0009,nst=45,,, -BC010,P,0100,,,, -BC010,P,0114,tmc=19or31,,, -BC010,P,0122,tmc=16or21,,, -BC010,P,0124,tmc=22,,, -BC010,P,0125,tmc=3,,, -BC010,P,0126,tmc=8,,, -BC010,P,0127,tmc=1,,, -BC010,P,0128,tmc=9,,, -BC010,P,0130,tmc=15or27or28,,, -BC010,P,0132,tmc=2,,, -BC010,P,0133,tmc=25or26or29,,, -BC010,P,0185,tmc=6,,, -BC010,P,0186,tmc=23or30,,, -BC010,P,0187,tmc=18,,, -BC010,P,0188,tmc=17,,, -BC010,P,0199,tmc=0or32,,, -BC010,P,0401,sst=1or2or3or4or6or9or14or15,.5,0,.5 -BC010,P,0510,ref=1,,0,-.25 -BC010,P,0511,nst=1or4or5or17or41or51or53,,, -BC010,P,0512,nst=10or54,,, -BC020,P,0009,nst=45,,, -BC020,P,0051,btc=35,.35,, -BC020,P,0202,tmc=16or21,,, -BC020,P,0204,tmc=22,,, -BC020,P,0205,tmc=3,,, -BC020,P,0206,tmc=8,,, -BC020,P,0207,tmc=1,,, -BC020,P,0208,tmc=9,,, -BC020,P,0210,tmc=15or27or28,,, -BC020,P,0212,tmc=2,,, -BC020,P,0213,tmc=25or26or29,,, -BC020,P,0214,tmc=19or31,,, -BC020,P,0217,tmc=23or30,,, -BC020,P,0265,tmc=6,,, -BC020,P,0299,tmc=0or17or18or32,,, -BC020,P,0300,btc=0ANDssc=0or85or999,,, -BC020,P,0301,btc=0ANDssc=1,,, -BC020,P,0302,btc=0ANDssc=7,,, -BC020,P,0303,btc=0ANDssc=6,,, -BC020,P,0304,btc=7ANDssc=1,,, -BC020,P,0305,btc=7ANDssc=7,,, -BC020,P,0306,btc=0ANDssc=10,,, -BC020,P,0307,btc=0ANDssc=17,,, -BC020,P,0308,btc=0ANDssc=16,,, -BC020,P,0309,btc=10,,, -BC020,P,0309,btc=0ANDssc=73,,, -BC020,P,0310,btc=4,,, -BC020,P,0311,btc=7ANDssc<>1and<>7,,, -BC020,P,0401,sst=1or2or3or4or6or9or14or15,.5,0,.5 -BC020,P,0510,ref=1,,0,-.25 -BC020,P,0511,nst=1or4or5or17or41or51or53ANDssc<>10,,, -BC020,P,0512,nst=10or54ANDssc<>10,,, -BC020,P,0513,btc=6,,, -BC020,P,4325,nst=1or4or5or17or41or51or53ANDssc=10,,, -BC020,P,4326,nst=10or54ANDssc=10,,, -BC040,P,0009,nst=45,,, -BC040,P,0051,,.35,, -BC040,P,0114,tmc=19or31,,, -BC040,P,0122,tmc=16or21,,, -BC040,P,0124,tmc=22,,, -BC040,P,0125,tmc=3,,, -BC040,P,0126,tmc=8,,, -BC040,P,0127,tmc=1,,, -BC040,P,0128,tmc=9,,, -BC040,P,0130,tmc=15or27or28,,, -BC040,P,0132,tmc=2,,, -BC040,P,0133,tmc=25or26or29,,, -BC040,P,0185,tmc=6,,, -BC040,P,0186,tmc=23or30,,, -BC040,P,0187,tmc=18,,, -BC040,P,0188,tmc=17,,, -BC040,P,0199,tmc=0or32,,, -BC040,P,0401,sst=1or2or3or4or6or9or14or15,.5,0,.5 -BC040,P,0510,ref=1,,0,-.25 -BC040,P,0511,nst=1or4or5or17or41or51or53,,, -BC040,P,0512,nst=10or54,,, -BC040,L,0713,,,, -BC055,P,0151,,,, -BC060,A,3116,,,, -BC070,P,0009,nst=45,,, -BC070,P,0401,sst=1or2or3or4or6or9or14or15,.5,0,.5 -BC070,P,0510,ref=1,,0,-.25 -BC070,P,0511,nst=1or4or5or17or41or51or53,,, -BC070,P,0512,nst=10or54,,, -BC070,P,0514,,,, -BC080,P,0052,,,, -BC080,A,0810,,,, -BC100,L,0656,,,, -BD000,P,0052,hdp=0,,, -BD000,P,0053,hdp>0and<=20,,, -BD000,P,0054,hdp>20,,, -BD000,P,0058,acc<>1,,, -BD000,A,0629,hdp>20,,, -BD000,A,0680,hdp>0and<=20,,, -BD000,A,0810,hdp=0,,, -BD000,A,0058,acc<>1,,, -BD010,P,0056,,,, -BD010,L,0752,,,, -BD010,A,0656,,,, -BD020,P,0052,vrr=4ANDhdp=0,,, -BD020,P,0053,vrr=4ANDhdp>0and<=20,,, -BD020,P,0054,vrr=4ANDhdp>20,,, -BD020,P,0055,vrr=8ANDhdp=NULL,,, -BD020,P,0057,vrr=1ANDhdp=NULL,,, -BD020,P,0058,acc<>1,,, -BD020,A,0804,vrr=1ANDhdp=NULL,,, -BD020,A,0803,vrr=8ANDhdp=NULL,,, -BD020,A,0629,vrr=4ANDhdp>20,,, -BD020,A,0680,vrr=4ANDhdp>0and<=20,,, -BD020,A,0810,vrr=4ANDhdp=0,,, -BD020,A,0058,acc<>1,,, -BD030,P,0052,,,, -BD030,P,0058,acc<>1,,, -BD030,A,0810,,,, -BD030,A,0058,acc<>1,,, -BD040,P,0056,,,, -BD040,A,0656,,,, -BD050,P,0059,,,, -BD050,A,0059 0716,,,, -BD060,P,0060,,,, -BD060,A,3077,,,, -BD080,P,0056,,,, -BD080,A,0656,,,, -BD100,P,0051,,.35,, -BD100,A,0804,vrr=1,,, -BD100,A,0803,vrr=8,,, -BD100,A,0810,vrr=4,,, -BD100,A,0058,acc<>1,,, -BD110,P,0061,,,, -BD110,P,0402,sst<>16,,, -BD110,P,0500,cha=21,,, -BD110,P,0512,nst=10or54,,, -BD120,A,0803,vrr=8,,, -BD120,A,0949,vrr=8ANDisdm=1,,, -BD120,A,0629,vrr=4ANDhdp>20,,, -BD120,A,0680,vrr=4ANDhdp>0and<=20,,, -BD120,A,0810,vrr<>8ANDhdp=0orNULL,,, -BD120,A,0058,vrr<>8ANDacc<>1,,, -BD130,P,0053,vrr=4ANDhdp>0and<=20,,, -BD130,P,0054,vrr=4ANDhdp>20,,, -BD130,P,0058,acc<>1,,, -BD130,P,0062,vrr=4ANDhdp=0,,, -BD130,P,0063,hdp=NULL,,, -BD140,P,0052,vrr=4ANDhdp=0,,, -BD140,P,0053,vrr=4ANDhdp>0and<=20,,, -BD140,P,0054,vrr=4ANDhdp>20,,, -BD140,P,0055,vrr=8ANDhdp=NULL,,, -BD140,P,0057,vrr=1ANDhdp=NULL,,, -BD140,P,0058,acc<>1,,, -BD140,A,0804,vrr=1,,, -BD140,A,0803,vrr=8,,, -BD140,A,0810,vrr=4,,, -BD140,A,0058,acc<>1,,, -BD180,P,0053,vrr=4ANDhdp>0and<=20,,, -BD180,P,0054,vrr=4ANDhdp>20,,, -BD180,P,0058,acc<>1,,, -BD180,P,0064,hdp=NULLANDvrr=1or2or8,,, -BD180,P,0064,loc<>4ANDhdp=NULL,,, -BD180,P,0065,vrr=4ANDsoh=1ANDhdp=0,,, -BD180,P,0065,hdp=NULLANDvrr=0,,, -BD180,P,0066,vrr=4ANDsoh=2ANDhdp=0,,, -BD180,A,0804,vrr=1ANDhdp=NULL,,, -BD180,A,0803,vrr=8ANDhdp=NULL,,, -BD180,A,0810,vrr=4ANDhdp=0,,, -BD180,A,0810,vrr=0or2ANDhdp=NULL,,, -BD180,A,0680,vrr=4ANDhdp>0and<=20,,, -BD180,A,3117,vrr=4ANDhdp>20,,, -BE010,L,0608,acc=1,,, -BE010,L,0614,acc=2,,, -BE010,A,0805,idsm=1ANDcvl>=ssdcand<>99999,,, -BE010,A,0805,idsm=0ANDcvl>=msdcand<>99999,,, -BE010,A,0810,idsm=1ANDisdm=0ANDcvl=ssdcand=msscand=msscand=msscand1,,, -BE020,P,1256,hdh>=0ANDhdp=NULL,,, -BF010,P,1233,mcc=0ANDpsc=0,,, -BG010,P,0071,cur=0ORdof=0,,, -BG010,P,0072,cur=3or5ANDdof<>0,,, -BG010,P,0073,cur=1ANDdof<>0,,, -BG010,P,0074,cur=2ANDdof<>0,,, -BG020,P,0015,,,, -BG030,P,0076,,,, -BG040,P,0154,,,, -BH010,L,0610,loc=25,,, -BH010,L,0704,loc<>25,,, -BH020,L,0600,,,, -BH020,A,0810,,,, -BH050,A,0904,,,, -BH080,A,0810,,,, -BH090,A,6050,,,, -BH095,A,0910,,,, -BH120,L,0610,,,, -BH130,A,0810,,,, -BH140,L,0600,,,, -BH140,A,0810,,,, -BH155,A,0911,,,, -BH180,L,0615,,,, -BH210,L,0600,,,, -BI020,L,0607,,,, -BI030,A,0810,,,, -BI040,L,0623,,,, -BJ030,A,0823,,,, -BJ030,A,0912,,,, -BJ060,P,0077,,,, -BJ065,A,0823,,,, -BJ065,A,0912,,,, -BJ100,A,0823,,,, -BJ100,A,0912,,,, -BJ110,A,0822,,,, -CA010,L,0604,,,, -CA030,P,0078,,,, -DA010,A,0822,,,, -DB090,L,3082,,,, -DB090,A,0913,,,, -DB170,A,0913,,,, -EA030,A,0914,,,, -EA040,A,0915,,,, -EA050,A,0915,,,, -EC030,P,0079,,,, -EC030,A,0915,veg<>19,,, -EC030,A,0916,veg=19,,, -FA000,L,0680,use=32,,, -FA000,L,1310,use=23,,, -FA020,L,3119,,,, -FA040,L,3120,,,, -FA060,L,1310,,,, -FA110,L,3119,,,, -FC021,P,0080,mac=48,,, -FC021,P,0084,mac<>48,,, -FC021,L,0629,mac=56ANDmbl=NULL,,, -FC021,L,0629,mbl<>7and<>13ANDmac=NULL,,, -FC021,L,0631,mac=26ANDmbl=NULL,,, -FC021,L,0633,mac=57ANDmbl=NULL,,, -FC021,L,0634,mac=30or35ANDmbl=NULL,,, -FC021,L,0634,mac=25ANDmbl=NULL,,, -FC021,L,0635,mac=49ANDmbl=NULL,,, -FC021,L,0635,mac=31ANDmbl=NULL,,, -FC021,L,0656,mbl=13ANDmac=NULL,,, -FC021,L,0656,mac=55ANDmbl=NULL,,, -FC021,L,0663,mac=42ANDmbl=NULL,,, -FC021,L,0663,mac=0or999ANDmbl=NULL,,, -FC021,L,1651,mac=48ANDmbl=NULL,,, -FC021,L,3077,mbl=7ANDmac=NULL,,, -FC021,L,4186,mac=44ANDmbl=NULL,,, -FC021,L,4186,mac=58ANDmbl=NULL,,, -FC021,L,4186,mac=32or33ANDmbl=NULL,,, -FC021,L,4186,mac=27or28or29ANDmbl=NULL,,, -FC021,L,4186,mac=24ANDmbl=NULL,,, -FC021,A,0823,mac=26,,, -FC021,A,0933,mac=26,,, -FC021,A,0631,mac=26,,, -FC021,A,0716,mac=55,,, -FC021,A,0716 0904,mac=57,,, -FC021,A,0047 0716,mac=56,,, -FC021,A,0080 0734,mac=48,,, -FC021,A,0081 0734,mac=25or30or35,,, -FC021,A,0081 0734,mac=49,,, -FC021,A,0081 0734,mac=31,,, -FC021,A,0092 0738 0917,mac=42,,, -FC021,A,0093 0734,mac=44,,, -FC021,A,0093 0734,mac=58,,, -FC021,A,0093 0734,mac=32or33,,, -FC021,A,0093 0734,mac=27or28or29,,, -FC021,A,0093 0734,mac=24,,, -FC021,A,0097 0742,mac=0or999,,, -FC031,P,0082,mac=5,,, -FC031,P,0083,mac=40,,, -FC031,P,0084,mac=0,,, -FC031,P,0087,mac=2,,, -FC031,P,0093,mac=4,,, -FC031,L,0663,mac=0or9,,, -FC031,L,0665,mac=40or41,,, -FC031,L,3077,mac=2,,, -FC031,L,4186,mac=5,,, -FC031,L,4186,mac=4,,, -FC031,A,0803,mac=2ANDhdp=0ANDisdm=0,,, -FC031,A,0803,mac=2ANDhdp=0ANDisdm=1,,, -FC031,A,0805,mac=2ANDidsm=1ANDhdp>=ssdc,,, -FC031,A,0805,mac=2ANDidsm=0ANDhdp>=msdc,,, -FC031,A,0810,mac=2ANDidsm=1ANDhdp>0and0and0and0and=ssdcand=msscand=msscand=ssdc,,, -FC031,A,0919,mac=2ANDidsm=1ANDhdp>0and0and=msdc,,, -FC031,A,0919,mac=2ANDidsm=0ANDhdp>=msscand=msscand=ssdcand0and0and0and=msscand0and=ssdc,,, -FC031,A,3077,mac=2ANDidsm=1ANDhdp>0and0and=msdc,,, -FC031,A,3077,mac=2ANDidsm=0ANDhdp>=msscand=msscand=ssdcand0and0and0,,, -FC165,L,0723,atn=1ANDexs=22ANDrtt=3,,, -FC165,L,0724,atn=2ANDexs=22ANDrtt=3,,, -FC165,L,0725,atn=1ANDexs=23ANDrtt=3,,, -FC165,L,0726,atn=2ANDexs=23ANDrtt=3,,, -FC165,L,0727,exs=0ANDrtt=3,,, -FC165,L,0728,atn=1ANDexs=22ANDrtt<>3,,, -FC165,L,0729,atn=2ANDexs=22ANDrtt<>3,,, -FC165,L,0730,atn=1ANDexs=23ANDrtt<>3,,, -FC165,L,0731,atn=2ANDexs=23ANDrtt<>3,,, -FC165,L,0732,exs=0ANDrtt<>3,,, -FC165,A,0097 0742,rtt=0,,, -FC165,A,0098 0734,rtt=11,,, -FC165,A,1238 0741,rtt=4,,, -FC170,L,0732,,,, -FC170,A,0091 0716,,,, -FC177,L,0656,,,, -FC177,A,0095 0716,,,, -GA020,P,0501,,,, -GA035,P,0511,,,, -GB005,P,0090,,,, -GB005,A,0822,,,, -GB005,A,0600 0932,,,, -GB010,P,0503,,,, -GB055,L,0606,,,, -GB055,A,0804,,,, -GB070,L,0634,,,, -GB070,A,0734 0634,,,, -ZC040,A,0733 0716,,,, diff --git a/share/data/vpf/vmaplv0-priority-iw.csv b/share/data/vpf/vmaplv0-priority-iw.csv deleted file mode 100644 index 520296b51..000000000 --- a/share/data/vpf/vmaplv0-priority-iw.csv +++ /dev/null @@ -1,3 +0,0 @@ -priority,type,facc,conditions,description -2,Line,BH000,, -2,Area,BH000,, \ No newline at end of file diff --git a/share/data/vpf/vmaplv0-symbol-lookup.csv b/share/data/vpf/vmaplv0-symbol-lookup.csv deleted file mode 100644 index e9dc6072e..000000000 --- a/share/data/vpf/vmaplv0-symbol-lookup.csv +++ /dev/null @@ -1,3 +0,0 @@ -facc,type,symbol,conditions,size,xoff,yoff -BH000,L,0621,,,, -BH000,A,4152,,,, diff --git a/share/manifest.txt b/share/manifest.txt deleted file mode 100644 index 73b51ab65..000000000 --- a/share/manifest.txt +++ /dev/null @@ -1,374 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: com.bbn.openmap.app.OpenMap - -Name: com/bbn/openmap/BufferedLayerMapBean.class -Java-Bean: True - -Name: com/bbn/openmap/BufferedMapBean.class -Java-Bean: True - -Name: com/bbn/openmap/InformationDelegator.class -Java-Bean: True - -Name: com/bbn/openmap/LayerHandler.class -Java-Bean: True - -Name: com/bbn/openmap/MapBean.class -Java-Bean: True - -Name: com/bbn/openmap/MapHandler.class -Java-Bean: True - -Name: com/bbn/openmap/MouseDelegator.class -Java-Bean: True - -Name: com/bbn/openmap/PropertyHandler.class -Java-Bean: True - -Name: com/bbn/openmap/SoloMapComponentRejectPolicy.class -Java-Bean: True - -Name: com/bbn/openmap/SoloMapComponentReplacePolicy.class -Java-Bean: True - -Name: com/bbn/openmap/event/DistanceMouseMode.class -Java-Bean: True - -Name: com/bbn/openmap/event/NavMouseMode.class -Java-Bean: True - -Name: com/bbn/openmap/event/NavMouseMode2.class -Java-Bean: True - -Name: com/bbn/openmap/event/NullMouseMode.class -Java-Bean: True - -Name: com/bbn/openmap/event/SelectMouseMode.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ControlMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/CoordPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/DMSCoordPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/DefaultHelpMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/DMSCoordPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/FileMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/GoToMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/LayerAddPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/LayerControlButtonPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/LayersMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/LayersPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/MGRSCoordPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/MapWindow.class -Java-Bean: True - -Name: com/bbn/openmap/gui/MenuBar.class -Java-Bean: True - -Name: com/bbn/openmap/gui/MouseModeButtonPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/MouseModePanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/NavigateMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/NavigatePanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/OMGraphicDeleteTool.class -Java-Bean: True - -Name: com/bbn/openmap/gui/OMToolSet.class -Java-Bean: True - -Name: com/bbn/openmap/gui/OpenMapFrame.class -Java-Bean: True - -Name: com/bbn/openmap/gui/OverviewMapHandler.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ProgressListenerGauge.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ProjectionStackTool.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ScaleTextPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ToolPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/UTMCoordPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/UserGuideMenuItems.class -Java-Bean: True - -Name: com/bbn/openmap/gui/ZoomPanel.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/AboutMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/BackgroundColorMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/LoadPropertiesMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/MouseModeMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/ProjectionMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/QuitMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/SaveAsGifMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/SaveAsJpegMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/SaveAsMenu.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/SavePropertiesMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/ToolPanelToggleMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/gui/menu/WebSiteHelpMenuItem.class -Java-Bean: True - -Name: com/bbn/openmap/layer/BufferedLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/CacheLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/DateLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/daynight/DayNightLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/DemoLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/DrawingToolLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/dted/DTEDLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/editor/EditorLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/EarthquakeLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/etopo/ETOPOJarLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/etopo/ETOPOLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/GraticuleLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/LabelLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/link/amp/AmpLinkLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/link/BufferedLinkLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/link/LinkLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/location/LocationLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/mif/MIFLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/nexrad/NexradLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/OverviewMapAreaLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/plotLayer/PlotLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/rpf/RpfLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/ScaleFilterLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/shape/areas/AreaShapeLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/shape/BufferedShapeLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/shape/MultiShapeLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/shape/ShapeLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/terrain/TerrainLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/test/HelloWorldLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/test/TestLayer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/vpf/LibraryBean.class -Java-Bean: True - -Name: com/bbn/openmap/layer/vpf/VPFLayer.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/CSVTiledImagePlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/earthImage/EarthImagePlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/esri/EsriPlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/graphicLoader/AnimationTester.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/graphicLoader/GraphicLoaderConnector.class -Java-Bean: True - -Name: com/bbn/openmap/graphicLoader/LOSGraphicLoader.class -Java-Bean: True - -Name: com/bbn/openmap/graphicLoader/netmap/NetMapConnector.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/PlugInLayer.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/shis/SHISPlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/UTMGridPlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/plugin/wms/WMSPlugIn.class -Java-Bean: True - -Name: com/bbn/openmap/tools/dnd/DefaultDnDCatcher.class -Java-Bean: True - -Name: com/bbn/openmap/tools/dnd/DropListenerSupport.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMCircleLoader.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMDrawingTool.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMDrawingToolLauncher.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMDrawingToolMouseMode.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMLineLoader.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMPointLoader.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMPolyLoader.class -Java-Bean: True - -Name: com/bbn/openmap/tools/drawing/OMRectLoader.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/ColorPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/DirectoryPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/FDUPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/FilePropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/FUPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/Inspector.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/MultiDirectoryPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/NonEditablePropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/OnOffPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/TextPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/TrueFalsePropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/util/propertyEditor/YesNoPropertyEditor.class -Java-Bean: True - -Name: com/bbn/openmap/layer/beanbox/Fighter.class -Java-Bean: True - -Name: com/bbn/openmap/layer/beanbox/SimpleBeanContainer.class -Java-Bean: True - -Name: com/bbn/openmap/layer/beanbox/SimpleBeanObject.class -Java-Bean: True diff --git a/share/omapplet.html b/share/omapplet.html deleted file mode 100644 index 2f0cd30a1..000000000 --- a/share/omapplet.html +++ /dev/null @@ -1,12 +0,0 @@ - - - -OpenMap Applet - - - -
- - - - diff --git a/share/openmap.jnlp b/share/openmap.jnlp deleted file mode 100644 index 9bb0bb081..000000000 --- a/share/openmap.jnlp +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - OpenMap - BBN Technologies - - OpenMap - A mapping application that lets you visualize your data. - - - - - - - - - - - - - diff --git a/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPClient.java b/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPClient.java deleted file mode 100644 index d4c714e6b..000000000 --- a/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPClient.java +++ /dev/null @@ -1,606 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPClient.java,v $ -// $RCSfile: CRFPClient.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf.corba; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Vector; - -import javax.imageio.ImageIO; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.stream.MemoryCacheImageInputStream; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.layer.rpf.RpfCoverageBox; -import com.bbn.openmap.layer.rpf.RpfFrameProvider; -import com.bbn.openmap.layer.rpf.RpfIndexedImageData; -import com.bbn.openmap.layer.rpf.RpfViewAttributes; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPCADRGProjection; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPCoverageBox; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPViewAttributes; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.LLPoint; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.RawImage; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.Server; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.ServerHelper; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * An implementation of the RpfFrameProvider interface that uses CORBA to get - * the subframe data via a server. The image data is transmitted in jpeg format. - * This class requires the sunw package that handles jpeg encoding/decoding. - *

- * - * The client can connect to the server in two different ways. The client can - * locate the server using an IOR file that the server has written. This IOR - * file is read using an URL. The server can also be located using the CORBA - * naming service. The name should be in a three part fomat / - * / . The root name has to be known by the nameserver and the - * entire string has to be used by the server on startup. If both the IOR and - * name string are set, the IOR is the thing that gets used. - */ -public class CRFPClient - implements RpfFrameProvider { - - /** The property specifying the IOR URL. */ - public static final String iorUrlProperty = "ior"; - /** The name of the server, using the name service. */ - public static final String nameProperty = "name"; - /** The property specifying the initial JPEG quality. */ - public static final String JPEGQualityProperty = "jpegQuality"; - /** The CRFPServer. */ - protected transient Server server = null; - /** The string used for the CORBA naming service. */ - protected String naming = null; - /** The URL used for the IOR, to connect to the server that way. */ - protected URL iorURL = null; - private String clientID = Environment.generateUniqueString(); - /** - * The compression quality of the images. Lower quality images are smaller. - */ - public float jpegQuality = .8f; - - /** - * We'll set up the connection to the server when it's needed, but not here. - */ - public CRFPClient() { - } - - /** - * Set the JPEG quality parameter for subframe transfer. - * - * @param jq number between 0 and 1, should be between .4 and .8. Anything - * else is a waste. - */ - public void setJpegQuality(float jq) { - jpegQuality = jq; - } - - /** - * Get the quality setting for JPEG subframe retrieval. - * - * @return float reflecting JPEG quality. - */ - public float getJpegQuality() { - return jpegQuality; - } - - /** - * Set the name used for the CORBA naming service. - */ - public void setNaming(String CORBAName) { - naming = CORBAName; - } - - /** - * Get the name used for the CORBA naming service. - */ - public String getNaming() { - return naming; - } - - /** - * If you want to connect to the server using an ior, set the URL where it - * is located. - */ - public void setIorURL(URL iorurl) { - iorURL = iorurl; - } - - /** - * Get the URL for the ior. - */ - public URL getIorURL() { - return iorURL; - } - - /** - * Get the clientID string that is used by the server to keep track of - * clients. This string in internally generated. - */ - public String getClientID() { - return clientID; - } - - /** - * Set all the RPF properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - jpegQuality = PropUtils.floatFromProperties(properties, prefix + JPEGQualityProperty, .8f); - - String url = properties.getProperty(prefix + iorUrlProperty); - if (url != null) { - try { - iorURL = PropUtils.getResourceOrFileOrURL(url); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("\"" + url + "\"" + " is malformed."); - } - } - - naming = properties.getProperty(prefix + nameProperty); - } - - /** - * When the client is deleted, it should sign off from the server, so that - * it can free up it's cache for it. - */ - protected void dispose() { - if (Debug.debugging("crfp")) { - Debug.output("CRFPClient.finalize(): calling shutdown"); - } - try { - if (server != null) { - server.signoff(clientID); - } - server = null; - } catch (org.omg.CORBA.SystemException e) { - Debug.error("CRFPClient.finalize(): " + e); - } catch (Throwable t) { - Debug.error("CRFPClient.finalize(): " + t); - } - } - - /** - * Returns true because the view attributes should be set if they change at - * the RpfCacheHandler/RpfCacheManager. - */ - public boolean needViewAttributeUpdates() { - return true; - } - - /** - * Set the RpfViewAttribute object parameters, which describes alot about - * what you'll be asking for later. - * - * @param rva the view attributes. - */ - public void setViewAttributes(RpfViewAttributes rva) { - Server serv = getServer(); - if (serv == null || rva == null) { - return; - } - - try { - serv.setViewAttributes(new CRFPViewAttributes((short) rva.numberOfColors, (short) rva.opaqueness, rva.scaleImages, - rva.imageScaleFactor, rva.chartSeries), clientID); - Debug.message("crfp", "CRFPClient: setting attributes."); - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - } - } - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know how to locate and ask for - * RpfSubframes. - * - * @param ullat NW latitude. - * @param ullon NW longitude - * @param lrlat SE latitude - * @param lrlon SE longitude - * @param p a CADRG projection - */ - public Vector getCoverage(double ullat, double ullon, double lrlat, double lrlon, - Projection p) { - - CRFPCoverageBox[] boxes; - Server serv = getServer(); - - if (serv == null) - return new Vector(); - - Point2D center = p.getCenter(); - LLPoint llpoint = new LLPoint((float) center.getY(), (float) center.getX()); - - CADRG cadrg = CADRG.convertProjection(p); - CRFPCADRGProjection proj = - new CRFPCADRGProjection(llpoint, (short) cadrg.getHeight(), (short) cadrg.getWidth(), cadrg.getScale(), - (short) cadrg.getZone()); - - Debug.message("crfp", "CRFPClient: getting coverage from server."); - - try { - boxes = serv.getCoverage(ullat, ullon, lrlat, lrlon, proj, clientID); - return translateCRFPCoverageBoxes(boxes); - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - } - - return new Vector(); - } - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know what bounding boxes of data are - * available. - * - * @param ullat NW latitude. - * @param ullon NW longitude - * @param lrlat SE latitude - * @param lrlon SE longitude - * @param p a CADRG projection - */ - public Vector getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, - Projection p, String chartSeriesCode) { - CRFPCoverageBox[] boxes; - Server serv = getServer(); - - if (serv == null) - return new Vector(); - - Point2D center = p.getCenter(); - LLPoint llpoint = new LLPoint((float) center.getY(), (float) center.getX()); - - CADRG cadrg = CADRG.convertProjection(p); - CRFPCADRGProjection proj = - new CRFPCADRGProjection(llpoint, (short) cadrg.getHeight(), (short) cadrg.getWidth(), cadrg.getScale(), - (short) cadrg.getZone()); - - Debug.message("crfp", "CRFPClient: getting catalog coverage from server."); - try { - boxes = serv.getCatalogCoverage(ullat, ullon, lrlat, lrlon, proj, chartSeriesCode, clientID); - return translateCRFPCoverageBoxes(boxes); - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - } - - return new Vector(); - } - - /** - * Given an area and a two-letter chart series code, find the percentage of - * coverage on the map that that chart series can offer. If you want - * specific coverage information, use the getCatalogCoverage call. - * - * @see #getCatalogCoverage(float ullat, float ullon, float lrlat, float - * lrlon, Projection p, String chartSeriesCode) - */ - public float getCalculatedCoverage(double ullat, double ullon, double lrlat, double lrlon, - Projection p, String chartSeries) { - if (chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY)) { - return 0f; - } - - Vector results = getCatalogCoverage(ullat, ullon, lrlat, lrlon, p, chartSeries); - - int size = results.size(); - - if (size == 0) { - return 0f; - } - - // Now interpret the results and figure out the real total - // percentage coverage for the chartSeries. First need to - // figure out the current size of the subframes. Then create - // a boolean matrix of those subframes that let you figure out - // how many of them are available. Calculate the percentage - // off that. - // int pZone = p.getZone(); - int i, x, y; - - double frameLatInterval = Double.MAX_VALUE; - double frameLonInterval = Double.MAX_VALUE; - RpfCoverageBox rcb; - for (i = 0; i < size; i++) { - rcb = (RpfCoverageBox) results.elementAt(i); - if (rcb.subframeLatInterval < frameLatInterval) { - frameLatInterval = rcb.subframeLatInterval; - } - if (rcb.subframeLonInterval < frameLonInterval) { - frameLonInterval = rcb.subframeLonInterval; - } - } - - if (frameLatInterval == Double.MAX_VALUE || frameLonInterval == Double.MAX_VALUE) { - return 0.0f; - } - - int numHFrames = (int) Math.ceil((lrlon - ullon) / frameLonInterval); - int numVFrames = (int) Math.ceil((ullat - lrlat) / frameLatInterval); - - boolean[][] coverage = new boolean[numHFrames][numVFrames]; - for (i = 0; i < size; i++) { - - rcb = (RpfCoverageBox) results.elementAt(i); - if (rcb.percentCoverage == 100) { - return 1.0f; - } - - for (y = 0; y < numVFrames; y++) { - for (x = 0; x < numHFrames; x++) { - // degree location of indexs - float yFrameLoc = (float) (lrlat + (y * frameLatInterval)); - float xFrameLoc = (float) (ullon + (x * frameLonInterval)); - if (coverage[x][y] == false) { - if (rcb.within(yFrameLoc, xFrameLoc)) { - coverage[x][y] = true; - } - } - } - } - } - - float count = 0; - - for (y = 0; y < numVFrames; y++) { - for (x = 0; x < numHFrames; x++) { - if (coverage[x][y] == true) { - // System.out.print("X"); - count++; - } else { - // System.out.print("."); - } - } - // Debug.output(""); - } - - return count / (float) (numHFrames * numVFrames); - } - - /** - * Convert CRFPCoverageBox[] to vector of RpfCoverageBox. - * - * @param boxes CRFPCoverageBox[]. - * @return java.util.Vector - */ - protected Vector translateCRFPCoverageBoxes(CRFPCoverageBox[] boxes) { - - Vector vector = new Vector(); - for (int i = 0; i < boxes.length; i++) { - CRFPCoverageBox box = boxes[i]; - RpfCoverageBox rcb = new RpfCoverageBox(); - rcb.nw_lat = box.nw_lat; - rcb.nw_lon = box.nw_lon; - rcb.se_lat = box.se_lat; - rcb.se_lon = box.se_lon; - rcb.subframeLatInterval = box.subframeLatInterval; - rcb.subframeLonInterval = box.subframeLonInterval; - rcb.chartCode = box.chartCode; - rcb.startIndexes = new Point(box.startIndexes.x, box.startIndexes.y); - rcb.endIndexes = new Point(box.endIndexes.x, box.endIndexes.y); - rcb.tocNumber = (int) box.tocNumber; - rcb.entryNumber = (int) box.entryNumber; - rcb.scale = box.scale; - rcb.percentCoverage = box.percentCoverage; - rcb.zone = box.zone; - vector.addElement(rcb); - } - return vector; - } - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame/subframe data, decompress it, and return image pixels. The - * tocNumber and entryNumber are given within the RpfCoverageBox received - * from a getCoverage call. With the CORBA implementation, we are assuming - * that the byte array is an encoded jpeg image. - * - * @param tocNumber the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber the RpfTocEntry id for a RpfTocHandler for a - * particular frame provider. - * @param x the horizontal subframe index, from the left side of a boundary - * rectangle of the entry. - * @param y the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(float ullat, float ullon, float lrlat, float lrlon, - * CADRG p) - * @return integer pixel data. - */ - public int[] getSubframeData(int tocNumber, int entryNumber, int x, int y) { - Server serv = getServer(); - if (serv == null) - return null; - byte[] jpegData; - Debug.message("crfp", "CRFPClient: getting subframe data from server."); - - try { - jpegData = serv.getSubframeData((short) tocNumber, (short) entryNumber, (short) x, (short) y, jpegQuality, clientID); - if (Debug.debugging("crfpdetail")) { - Debug.output("CRFPClient: got subframe data length " + jpegData.length); - } - - // Need to check for the corba rendition of an allowable - // null image (length 0) - if (jpegData.length == 0) - return null; - - ImageInputStream iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(jpegData)); - BufferedImage bi = ImageIO.read(iis); - int height = bi.getHeight(); - int width = bi.getWidth(); - int[] pixels = bi.getRGB(0, 0, width, height, null, 0, width); - return pixels; - } catch (IOException ioe) { - Debug.error("CRFPClient: IOException decoding jpeg bytes"); - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - } - return null; - } - - public RpfIndexedImageData getRawSubframeData(int tocNumber, int entryNumber, int x, int y) { - Server serv = getServer(); - if (serv == null) - return null; - - Debug.message("crfp", "CRFPClient: getting raw subframe data from server."); - - try { - RawImage ri = serv.getRawSubframeData((short) tocNumber, (short) entryNumber, (short) x, (short) y, clientID); - - // Need to check for the corba rendition of an allowable - // null image (length 0) - if (ri.imagedata.length == 0 || ri.colortable.length == 0) { - return null; - } - - RpfIndexedImageData riid = new RpfIndexedImageData(); - riid.imageData = ri.imagedata; - riid.colortable = new OMColor[ri.colortable.length]; - - for (int i = 0; i < riid.colortable.length; i++) { - riid.colortable[i] = new OMColor(ri.colortable[i]); - } - return riid; - - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - return null; - } - } - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame and return the attribute information. The tocNumber and - * entryNumber are given within the RpfCoverageBox received from a - * getCoverage call. - * - * @param tocNumber the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber the RpfTocEntry id for a RpfTocHandler for a - * particular frame provider. - * @param x the horizontal subframe index, from the left side of a boundary - * rectangle of the entry. - * @param y the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(float ullat, float ullon, float lrlat, float lrlon, - * Projection p) - * @return string. - */ - public String getSubframeAttributes(int tocNumber, int entryNumber, int x, int y) { - - Server serv = getServer(); - if (serv == null) - return ""; - - Debug.message("crfp", "CRFPClient: getting subframe attributes from server."); - try { - return serv.getSubframeAttributes((short) tocNumber, (short) entryNumber, (short) x, (short) y, clientID); - } catch (org.omg.CORBA.SystemException e) { - handleCORBAError(e); - } - return ""; - } - - // ////////////// Corba management - - /** - * get the server proxy. - * - * @return Server server or null if error. - * - */ - public Server getServer() { - if (server == null) - initServer(); - return server; - } - - /** - * bind to the server. - * - */ - private void initServer() { - String ior = null; - org.omg.CORBA.Object object = null; - - com.bbn.openmap.util.corba.CORBASupport cs = new com.bbn.openmap.util.corba.CORBASupport(); - - try { - object = cs.readIOR(iorURL); - server = ServerHelper.narrow(object); - } catch (IOException ioe) { - if (Debug.debugging("crfp")) { - Debug.output("CRFPClient.initServer() IO Exception with ior: " + iorURL); - } - server = null; - return; - } - - if (server == null) { - object = cs.resolveName(naming); - - if (object != null) { - server = ServerHelper.narrow(object); - if (Debug.debugging("crfp")) { - Debug.output("Have a RPF server:"); - Debug.output("*** Server: is a " + server.getClass().getName() + "\n" + server); - } - } - } - - if (Debug.debugging("crfp")) { - if (server == null) { - Debug.error("CRFPClient.initServer: null server!\n IOR=" + ior + "\n Name = " + naming); - } else { - Debug.output("CRFPClient: server is golden."); - } - } - } - - protected void handleCORBAError(org.omg.CORBA.SystemException e) { - // don't freak out if we were only interrupted... - if (e.toString().indexOf("InterruptedIOException") != -1) { - Debug.error("CRFPClient server communication interrupted!"); - } else { - Debug.error("CRFPClient caught CORBA exception: " + e + "\n" + "CRFPClient Exception class: " + e.getClass().getName() - + "\n" + e.getMessage()); - e.printStackTrace(); - } - - server = null;// dontcha just love CORBA? reinit later - } - -} \ No newline at end of file diff --git a/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPServer.java b/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPServer.java deleted file mode 100644 index 1ab9d31ed..000000000 --- a/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPServer.java +++ /dev/null @@ -1,654 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/corba/com/bbn/openmap/layer/rpf/corba/CRFPServer.java,v $ -// $RCSfile: CRFPServer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/11 19:30:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf.corba; - -import java.awt.event.ActionListener; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.StringTokenizer; -import java.util.Vector; - -import javax.swing.Timer; - -import com.bbn.openmap.image.JPEGHelper; -import com.bbn.openmap.layer.rpf.RpfCacheHandler; -import com.bbn.openmap.layer.rpf.RpfColortable; -import com.bbn.openmap.layer.rpf.RpfCoverageBox; -import com.bbn.openmap.layer.rpf.RpfFrameCacheHandler; -import com.bbn.openmap.layer.rpf.RpfIndexedImageData; -import com.bbn.openmap.layer.rpf.RpfSubframe; -import com.bbn.openmap.layer.rpf.RpfTocHandler; -import com.bbn.openmap.layer.rpf.RpfViewAttributes; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPCADRGProjection; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPCoverageBox; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.CRFPViewAttributes; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.RawImage; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.ServerPOA; -import com.bbn.openmap.layer.rpf.corba.CRpfFrameProvider.XYPoint; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.corba.CORBASupport; - -/** - * The CRFPServer is a server implementation of the - * CorbaRpfFrameProvider.idl. It realy implements most of the fuctions - * of the RpfFrameProvider, but is not one. The CRFPClient is the - * RpfFrameProvider. - * - *

- * This server requires the com.sun.image.codec.jpeg package. - */ -public class CRFPServer extends ServerPOA implements ActionListener { - - protected static String iorfile = null; - protected static String naming = null; - /** A cache for every client. */ - Hashtable caches; - /** View Attributes for every client. */ - Hashtable viewAttributeLists; - /** The cache for the current client. */ - protected RpfFrameCacheHandler currentCache; - /** The view attrbutes for the current client. */ - protected RpfViewAttributes currentViewAttributes; - /** The paths to the RPF directories. */ - protected String[] rpfpaths; - /** The Rpf Table of Contents handlers for the data. */ - protected RpfTocHandler[] tocs; - /** Hashtable to keep track of how old certain caches are. */ - Hashtable timestamps; - /** - * Timer for clearing out caches from sloppy clients. It's only - * enabled when the -timewindow flag is used. - */ - Timer timer; - /** 10, or the default number of active caches kept. */ - public final static int DEFAULT_MAX_USERS = 10; - /** The number of caches kept by the server. */ - protected int maxUsers = DEFAULT_MAX_USERS; - /** 5 minutes. The default timer cycle. */ - public final static int DEFAULT_TIME_WINDOW = 1000 * 60 * 5; // 5 - // minutes - /** - * The amount of time (milliseconds) reflecting how long an - * inactive cache is kept - */ - protected long timeWindow = DEFAULT_TIME_WINDOW; - - /** - * Default Constructor. - */ - public CRFPServer() { - this("Default"); - } - - /** - * The constructor that you should use. - * - * @param name the identifying name for persistance. - */ - public CRFPServer(String name) { - super(); - caches = new Hashtable(); - viewAttributeLists = new Hashtable(); - timestamps = new Hashtable(); - } - - /** - * Get the current cache given a unique ID. If a cache is not - * here, create it. - * - * @param uniqueID a unique identifier. - */ - protected RpfFrameCacheHandler getCurrentCache(String uniqueID) { - RpfFrameCacheHandler cache = (RpfFrameCacheHandler) caches.get(uniqueID); - if (cache == null && tocs != null) { - Debug.message("crfp", "CRFPServer: Creating cache for new client"); - cache = new RpfFrameCacheHandler(tocs); - caches.put(uniqueID, cache); - } - - timestamps.put(uniqueID, new Long(System.currentTimeMillis())); - return cache; - } - - /** - * Get rid of any cache that is older than the time window. - */ - protected void cleanCache(long timeWindow) { - // OK, we need to get rid of one. - long currentTime = System.currentTimeMillis(); - Enumeration keys = timestamps.keys(); - - while (keys.hasMoreElements()) { - Object tester = keys.nextElement(); - Long time = (Long) timestamps.get(tester); - - if ((currentTime - time.longValue()) >= timeWindow) { - caches.remove(tester); - timestamps.remove(tester); - viewAttributeLists.remove(tester); - - if (Debug.debugging("crfp")) { - Debug.output("Expired cache, removing, have " - + caches.size() + " caches left."); - } - } - } - } - - /** - * Create a spot in the cache for a new entry. If something is - * removed from the cache, it is returned here. - */ - protected RpfCacheHandler sweepCaches() { - if (caches.size() < maxUsers) { - return null; - } - - // OK, we need to get rid of one. - long diff = Long.MAX_VALUE; - Enumeration keys = timestamps.keys(); - Object getRid = null; - - while (keys.hasMoreElements()) { - Object tester = keys.nextElement(); - Long time = (Long) timestamps.get(tester); - - if (time.longValue() < diff) { - getRid = tester; - diff = time.longValue(); - } - } - boolean DEBUG = false; - if (getRid != null) { - if (Debug.debugging("crfp")) { - DEBUG = true; - } - if (DEBUG) - Debug.output("Removing cache for new user, was " - + caches.size()); - - caches.remove(getRid); - timestamps.remove(getRid); - viewAttributeLists.remove(getRid); - - if (DEBUG) - Debug.output(" now " + caches.size()); - } - - if (caches.size() >= maxUsers) { - return sweepCaches(); - } else { - return (RpfCacheHandler) getRid; - } - } - - /** - * Get the current view attributes given a unique ID. If view - * attributes are not here, create them. - * - * @param uniqueID a client-unique identifier. - */ - protected RpfViewAttributes getCurrentViewAttributes(String uniqueID) { - RpfViewAttributes va = (RpfViewAttributes) viewAttributeLists.get(uniqueID); - if (va == null) { - Debug.message("crfp", - "CRFPServer: Creating attributes for new client"); - va = new RpfViewAttributes(); - viewAttributeLists.put(uniqueID, va); - } - return va; - } - - /** - * Set the view attributtes for the current client. - * - * @param va the view attribute settings. - * @param uniqueID a client-unique identifier. - */ - public void setViewAttributes(CRFPViewAttributes va, String uniqueID) { - - currentViewAttributes = getCurrentViewAttributes(uniqueID); - currentViewAttributes.numberOfColors = (int) va.numberOfColors; - currentViewAttributes.opaqueness = (int) va.opaqueness; - currentViewAttributes.scaleImages = va.scaleImages; - currentViewAttributes.imageScaleFactor = va.imageScaleFactor; - currentViewAttributes.chartSeries = va.chartSeries; - - if (Debug.debugging("crfp")) { - Debug.output("CRFPServer: Setting attributes for client:\n " - + currentViewAttributes); - } - } - - /** - * Get the Coverage Boxes that fit the geographical area given. - * - * @param ullat NW latitude. - * @param ullon NW longitude - * @param lrlat SE latitude - * @param lrlon SE longitude - * @param p a CADRG projection - * @param uniqueID a client-unique identifier. - */ - public CRFPCoverageBox[] getCoverage(double ullat, double ullon, double lrlat, double lrlon, - CRFPCADRGProjection p, - String uniqueID) { - - Debug.message("crfp", - "CRFPServer: Handling coverage request for client"); - - currentCache = getCurrentCache(uniqueID); - currentViewAttributes = getCurrentViewAttributes(uniqueID); - currentCache.setViewAttributes(currentViewAttributes); - - LatLonPoint llpoint = new LatLonPoint.Double(p.center.lat, p.center.lon); - CADRG proj = new CADRG(llpoint, p.scale, p.width, p.height); - - Vector vector = currentCache.getCoverage(ullat, - ullon, - lrlat, - lrlon, - proj); - - return vectorToCRFPCoverageBoxes(vector); - } - - /** - * Method that provides all the coverage boxes that could provide - * coverage over the given area. - * - * @param ullat NW latitude. - * @param ullon NW longitude - * @param lrlat SE latitude - * @param lrlon SE longitude - * @param p a CADRG projection - * @param uniqueID a client-unique identifier. - */ - public CRFPCoverageBox[] getCatalogCoverage(double ullat, double ullon, double lrlat, - double lrlon, - CRFPCADRGProjection p, - String chartSeriesCode, - String uniqueID) { - - Debug.message("crfp", "CRFPServer: handling catalog request for client"); - currentCache = getCurrentCache(uniqueID); - currentViewAttributes = getCurrentViewAttributes(uniqueID); - currentCache.setViewAttributes(currentViewAttributes); - - LatLonPoint llpoint = new LatLonPoint.Float(p.center.lat, p.center.lon); - CADRG proj = new CADRG(llpoint, p.scale, p.width, p.height); - Vector vector = currentCache.getCatalogCoverage(ullat, - ullon, - lrlat, - lrlon, - proj, - chartSeriesCode); - return vectorToCRFPCoverageBoxes(vector); - } - - /** - * Convert a Vector of RpfCoverageBox to a CRFPCoverageBox array. - * - * @param vector vector of RpfCoverageBox. - * @return array of CRFPCoverageBox. - */ - protected CRFPCoverageBox[] vectorToCRFPCoverageBoxes(Vector vector) { - int size = vector.size(); - CRFPCoverageBox[] rets = new CRFPCoverageBox[size]; - - for (int i = 0; i < size; i++) { - RpfCoverageBox box = (RpfCoverageBox) vector.elementAt(i); - if (box != null) { - rets[i] = new CRFPCoverageBox((float) box.nw_lat, (float) box.nw_lon, (float) box.se_lat, (float) box.se_lon, box.subframeLatInterval, box.subframeLonInterval, box.chartCode, (short) box.zone, new XYPoint((short) box.startIndexes.x, (short) box.startIndexes.y), new XYPoint((short) box.endIndexes.x, (short) box.endIndexes.y), (short) box.tocNumber, (short) box.entryNumber, box.scale, box.percentCoverage); - } - } - return rets; - } - - /** - * Retrieve the subframe data from the frame cache, decompress it, - * and convert it to a JPEG image. - * - * @param tocNumber the number of the RpfTocHandler for the - * currentCache to use. - * @param entryNumber the coverage box index that contains the - * subframe. - * @param x the horizontal location of the subframe. The - * RpfCacheHandler figures this out. - * @param y the vertical location of the subframe. The - * RpfCacheHandler figures this out. - * @param jpegQuality the compression parameter for the image. - * @param uniqueID a client-unique identifier. - * @return byte[] of jpeg image - */ - public byte[] getSubframeData(short tocNumber, short entryNumber, short x, - short y, float jpegQuality, String uniqueID) { - - Debug.message("crfpdetail", - "CRFPServer: handling subframe request for client"); - - try { - currentCache = getCurrentCache(uniqueID); - - int[] pixels = currentCache.getSubframeData((int) tocNumber, - (int) entryNumber, - (int) x, - (int) y); - if (pixels != null) { - byte[] compressed = null; - try { - compressed = JPEGHelper.encodeJPEG(RpfSubframe.PIXEL_EDGE_SIZE, - RpfSubframe.PIXEL_EDGE_SIZE, - pixels, - jpegQuality); - } catch (Exception e) { - Debug.error("CRFPServer: JPEG Compression error: " + e); - compressed = new byte[0]; - } - if (Debug.debugging("crfpdetail")) { - Debug.output("CRFPServer: subframe is " + compressed.length - + " bytes"); - } - return compressed; - } - } catch (OutOfMemoryError oome) { - handleMemoryShortage(); - } - - return new byte[0]; - } - - public RawImage getRawSubframeData(short tocNumber, short entryNumber, - short x, short y, String uniqueID) { - - Debug.message("crfpdetail", - "CRFPServer: handling raw subframe request for client"); - - RawImage ri = new RawImage(); - RpfIndexedImageData riid = null; - - try { - currentCache = getCurrentCache(uniqueID); - - riid = currentCache.getRawSubframeData((int) tocNumber, - (int) entryNumber, - (int) x, - (int) y); - } catch (OutOfMemoryError oome) { - handleMemoryShortage(); - riid = null; - } - - if (riid == null || riid.imageData == null) { - Debug.message("crfpdetail", "CRFPServer: null image data"); - ri.imagedata = new byte[0]; - ri.colortable = new int[0]; - } else { - ri.imagedata = riid.imageData; - - RpfColortable colortable = currentCache.getColortable(); - - ri.colortable = new int[colortable.colors.length]; - for (int i = 0; i < colortable.colors.length; i++) { - ri.colortable[i] = colortable.colors[i].getRGB(); - } - Debug.message("crfpdetail", "CRFPServer: GOOD image data"); - } - return ri; - } - - /** - * Get the subframe attributes for the identified subframe. - * Provided as a single string, with newline characters separating - * features. - * - * @param tocNumber the number of the RpfTocHandler for the - * currentCache to use. - * @param entryNumber the coverage box index that contains the - * subframe. - * @param x the horizontal location of the subframe. The - * RpfCacheHandler figures this out. - * @param y the vertical location of the subframe. The - * RpfCacheHandler figures this out. - * @param uniqueID a client-unique identifier. - * @return String with the subframe attributes. - */ - public String getSubframeAttributes(short tocNumber, short entryNumber, - short x, short y, String uniqueID) { - Debug.message("crfpdetail", - "CRFPServer: handling subframe attribute request for client"); - - try { - currentCache = getCurrentCache(uniqueID); - return currentCache.getSubframeAttributes((int) tocNumber, - (int) entryNumber, - (int) x, - (int) y); - } catch (OutOfMemoryError oome) { - handleMemoryShortage(); - } - return new String(); - } - - /** - * The signoff function lets the server know that a client is - * checking out. - * - * @param uniqueID a client-unique identifier. - */ - public void signoff(String uniqueID) { - Debug.message("crfp", "CRFPServer: Client" + uniqueID + " signing off!"); - caches.remove(uniqueID); - viewAttributeLists.remove(uniqueID); - timestamps.remove(uniqueID); - } - - protected void handleMemoryShortage() { - Debug.error("CRFPServer out of memory! Dumping all caches!"); - caches.clear(); - viewAttributeLists.clear(); - timestamps.clear(); - } - - /** - * Start the server. - * - * @param args command line arguments. - */ - public void start(String[] args) { - CORBASupport cs = new CORBASupport(); - - if (args != null) { - parseArgs(args); - } - - cs.start(this, args, iorfile, naming); - } - - /** - * Set the maximum number of caches to given number, represented - * in a string. If the string isn't a good number, - * DEFAULT_MAX_USERS will be used. - */ - public void setMaxUsers(String number) { - try { - setMaxUsers(Integer.parseInt(number)); - } catch (NumberFormatException nfe) { - setMaxUsers(DEFAULT_MAX_USERS); - } - } - - /** - * Set the maximum number of caches to given number. If the number - * isn't a good, DEFAULT_MAX_USERS will be used. - */ - public void setMaxUsers(int number) { - if (number >= 1) { - maxUsers = number; - } else { - Debug.output("Max users of " + number + " not supported, set to " - + DEFAULT_MAX_USERS); - maxUsers = DEFAULT_MAX_USERS; - } - } - - /** - * Get the maximum number of caches allowed in the server. One per - * user. Get it? - */ - public int getMaxUsers() { - return maxUsers; - } - - /** - * Set how long a user's cache will be kept around. - */ - public void setTimeWindow(String number) { - try { - setTimeWindow(Long.parseLong(number)); - } catch (NumberFormatException nfe) { - setTimeWindow(DEFAULT_TIME_WINDOW); - } - } - - /** - * Set how long a user's cache will be kept around. - */ - public void setTimeWindow(long number) { - if (timer == null) { - timer = new javax.swing.Timer((int) number, (ActionListener) this); - } - - if (number >= 1) { - timeWindow = number; - Debug.output("Timer enabled, set to " + (number / 1000) - + " seconds"); - } else if (number == 0) { - // stop timer - timer.stop(); - return; - } else { - timeWindow = DEFAULT_TIME_WINDOW; - Debug.output("Timer enabled, set to " - + (DEFAULT_TIME_WINDOW / 1000) + " seconds"); - } - - timer.start(); - } - - /** - * The the time window for how long users caches are kept around. - */ - public long getTimeWindow() { - return timeWindow; - } - - /** - * Handle an ActionEvent from the Timer. - * - * @param ae action event from the timer. - */ - public void actionPerformed(java.awt.event.ActionEvent ae) { - if (Debug.debugging("crfp")) { - Debug.output("Ping! checking cache..."); - } - cleanCache(getTimeWindow()); - } - - /** - */ - public void parseArgs(String[] args) { - rpfpaths = null; - - try { - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-ior")) { - iorfile = args[++i]; - } else if (args[i].equalsIgnoreCase("-name")) { - naming = args[++i]; - } else if (args[i].equalsIgnoreCase("-help")) { - printHelp(); - } else if (args[i].equalsIgnoreCase("-rpfpaths")) { - rpfpaths = getPaths(args[++i]); - } else if (args[i].equalsIgnoreCase("-maxusers")) { - setMaxUsers(args[++i]); - } else if (args[i].equalsIgnoreCase("-timewindow")) { - setTimeWindow(args[++i]); - } else if (args[i].equalsIgnoreCase("-verbose")) { - Debug.put("crfp"); - } else if (args[i].equalsIgnoreCase("-h")) { - printHelp(); - } - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - printHelp(); - } - - // if you didn't specify an iorfile - if (iorfile == null && naming == null) { - Debug.error("CRFPServer: IOR file and name service name are null! Use `-ior' or '-name' flag!"); - System.exit(-1); - } - - if (rpfpaths == null) { - Debug.error("CRFPServer: No RPF directory paths specified! Use `-rpfpaths' flag!"); - System.exit(-1); - } else { - tocs = RpfFrameCacheHandler.createTocHandlers(rpfpaths); - Debug.output("CRFPServer: CRFPServer! Running with paths => "); - for (int j = 0; j < rpfpaths.length; j++) { - Debug.output(" " + rpfpaths[j]); - } - } - } - - private String[] getPaths(String str) { - StringTokenizer tok = new StringTokenizer(str, ";"); - int len = tok.countTokens(); - String[] paths = new String[len]; - for (int j = 0; j < len; j++) { - paths[j] = tok.nextToken(); - } - return paths; - } - - /** - * printHelp should print a usage statement which reflects - * the command line needs of your specialist. - */ - public void printHelp() { - Debug.output("usage: java CRFPServer [-ior || -name ] -rpfpaths \";;<...>\" -maxusers -timewindow "); - System.exit(1); - } - - public static void main(String[] args) { - Debug.init(System.getProperties()); - - // Create the specialist server - CRFPServer srv = new CRFPServer("CRFPServer"); - srv.start(args); - } - -} \ No newline at end of file diff --git a/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfFrameProvider.idl b/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfFrameProvider.idl deleted file mode 100644 index fe2b6142b..000000000 --- a/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfFrameProvider.idl +++ /dev/null @@ -1,140 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfFrameProvider.idl,v $ -// $RCSfile: CorbaRpfFrameProvider.idl,v $ -// $Revision: 1.1.1.1 $ -// $Date: 2003/02/14 21:35:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - - -#ifndef CorbaRpfFrameProvider_idl -#define CorbaRpfFrameProvider_idl - -// ---------------------------------------------------------------------- -// The Server Definition. -// ---------------------------------------------------------------------- -module CRpfFrameProvider { - -// ---------------------------------------------------------------------- -// Basic Structures -// ---------------------------------------------------------------------- - const string Revision = "@(#)$Header: /cvs/distapps/openmap/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfFrameProvider.idl,v 1.1.1.1 2003/02/14 21:35:47 dietrick Exp $"; - - struct XYPoint { - short x; - short y; - }; - - struct LLPoint { - float lat; - float lon; - }; - - struct CRFPCADRGProjection { - LLPoint center; - unsigned short height; - unsigned short width; - float scale; - // Zone just for pixel spacing compatability - doesn't - // represent southern hemisphere zones A-H - unsigned short zone; - }; - - struct CRFPCoverageBox { - double nw_lat; - double nw_lon; - double se_lat; - double se_lon; - double subframeLatInterval; - double subframeLonInterval; - string chartCode; - unsigned short zone; - XYPoint startIndexes; - XYPoint endIndexes; - unsigned short tocNumber; - unsigned short entryNumber; - float scale; - float percentCoverage; - }; - - typedef sequence CRFPCoverageBoxSeq; - - struct CRFPViewAttributes { - unsigned short numberOfColors; - unsigned short opaqueness; - boolean scaleImages; - float imageScaleFactor; - string chartSeries; - }; - - typedef sequence data; - typedef sequence rawdata; - - struct RawImage { - rawdata colortable; - data imagedata; - }; - - //------------------------------------------------------------ - // Server methods - //------------------------------------------------------------ - - interface Server { - - void setViewAttributes(in CRFPViewAttributes va, - in string uniqueID); - - CRFPCoverageBoxSeq getCoverage( - in double ullat, in double ullon, - in double lrlat, in double lrlon, - in CRFPCADRGProjection p, - in string uniqueID); - - CRFPCoverageBoxSeq getCatalogCoverage( - in double ullat, in double ullon, - in double lrlat, in double lrlon, - in CRFPCADRGProjection p, - in string chartSeriesCode, - in string uniqueID); - - data getSubframeData( - in unsigned short tocNumber, - in unsigned short entryNumber, - in short x, - in short y, - in float jpegQuality, - in string uniqueID); - - RawImage getRawSubframeData( - in unsigned short tocNumber, - in unsigned short entryNumber, - in short x, - in short y, - in string uniqueID); - - string getSubframeAttributes( - in unsigned short tocNumber, - in unsigned short entryNumber, - in short x, - in short y, - in string uniqueID); - - oneway void signoff(in string uniqueID); - }; -}; - -#endif diff --git a/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfLayer.java b/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfLayer.java deleted file mode 100644 index 90ef91f7c..000000000 --- a/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfLayer.java +++ /dev/null @@ -1,291 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/corba/com/bbn/openmap/layer/rpf/corba/CorbaRpfLayer.java,v $ -// $RCSfile: CorbaRpfLayer.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 20:57:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf.corba; - -/* Java Core */ - -import java.util.Properties; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.layer.rpf.RpfFrameProvider; -import com.bbn.openmap.layer.rpf.RpfLayer; -import com.bbn.openmap.layer.rpf.RpfViewAttributes; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * An RpfLayer that uses a CORBA-based RpfFrameProvider. JDK 1.2 and - * the
- * com.sun.image.codec.jpeg package is required, as well as some
- * CORBA implementation. Tested with Visibroker 3.3. - * - *
- * #-----------------------------
- * # Additional Properties for RpfLayer
- * #-----------------------------
- * layer.jpegQuality= # ior | name - * property, ior takes precidence if both are listed. layer.ior= layer.name=
- */ -public class CorbaRpfLayer extends RpfLayer { - - private static final long serialVersionUID = 1L; - - /** Property to change the quickRedraw setting. T/F */ - public static final String QuickRedrawProperty = ".quickRedraw"; - - /** - * Flag to attempt to redraw the images already in the cache while - * waiting for new frames. Works better for slower servers. - * Default value is false. - */ - protected boolean quickRedraw = false; - - /** - * Keep a copy in case the frame provider goes away. It's - * happened. - */ - protected Properties props = null; - - /** - * The default constructor for the Layer. All of the attributes - * are set to their default values. Use this construct if you are - * going to use a standard properties file, which will set the - * paths. - */ - public CorbaRpfLayer() { - super(); - setFrameProvider((RpfFrameProvider) new CRFPClient()); - } - - /** - * Set all the RPF properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - props = properties; - - ((CRFPClient) frameProvider).setProperties(prefix, properties); - quickRedraw = PropUtils.booleanFromProperties(properties, prefix - + QuickRedrawProperty, false); - } - - public void removed(java.awt.Container cont) { - super.removed(cont); - dispose(); - } - - /** - * Clear the frame cache. - */ - public void clearCache() { - - if (this.cache != null) { - // This is bad, and is changed from the RpfLayer. Make - // sure this never happens. - // this.cache.setViewAttributes(null); - // this.cache.setFrameProvider(null); - - this.cache.clearCaches(); - } - - // This, too must never happen. - frameProvider = null; - - setList(null); - this.cache = null; - } - - /** - * When the layer is deleted, it should sign off from the server, - * so that it can free up it's cache for it. - */ - public void dispose() { - // Check just in case, although this should never happen. - if (frameProvider != null) { - ((CRFPClient) frameProvider).dispose(); - } - } - - /** - * Creates the RpfFrameProvider. If one is already here, nothing - * happens. - * - * @param pathsToRPFDirs Array of strings that list the paths to - * RPF directories. - */ - public void setPaths(String[] pathsToRPFDirs) { - RpfFrameProvider frameProvider = getFrameProvider(); - - if (!(frameProvider instanceof CRFPClient)) { - return; - } - - frameProvider = (RpfFrameProvider) new CRFPClient(); - setFrameProvider(frameProvider); - - if (props != null) { - // Set default settings... - ((CRFPClient) frameProvider).setProperties(getPropertyPrefix(), - props); - } - - this.cache = null; - } - - /** - * Prepares the graphics for the layer. The only thing this method - * does that is different than the RpfLayer is that if the current - * OMGraphicList is not null, then it is reprojected and redrawn. - * - * @return OMGraphicList of images and text. - */ - public OMGraphicList prepare() { - OMGraphicList oldList = getList(); - if (oldList != null) { - oldList.generate(getProjection()); - if (getCoverage() != null) { - getCoverage().generate(getProjection()); - } - repaint(); - } - return super.prepare(); - } - - /** - * Provides the palette widgets to control the options of showing - * maps, or attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - JCheckBox showMapsCheck, showInfoCheck, lockSeriesCheck; - - Box box = Box.createVerticalBox(); - - Box box1 = Box.createVerticalBox(); - Box box2 = Box.createVerticalBox(); - JPanel topbox = new JPanel(); - - showMapsCheck = new JCheckBox("Show Images", viewAttributes.showMaps); - showMapsCheck.setActionCommand(showMapsCommand); - showMapsCheck.addActionListener(this); - - showInfoCheck = new JCheckBox("Show Attributes", viewAttributes.showInfo); - showInfoCheck.setActionCommand(showInfoCommand); - showInfoCheck.addActionListener(this); - - boolean locked = viewAttributes.chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY) ? false - : true; - String lockedTitle = locked ? (lockedButtonTitle + " - " + viewAttributes.chartSeries) - : unlockedButtonTitle; - - lockSeriesCheck = new JCheckBox(lockedTitle, locked); - lockSeriesCheck.setActionCommand(lockSeriesCommand); - lockSeriesCheck.addActionListener(this); - - box1.add(showMapsCheck); - box1.add(showInfoCheck); - box1.add(lockSeriesCheck); - - if (coverage != null) { - JCheckBox showCoverageCheck = new JCheckBox("Show Coverage Tool", false); - showCoverageCheck.setActionCommand(showCoverageCommand); - showCoverageCheck.addActionListener(this); - box1.add(showCoverageCheck); - } - - topbox.add(box1); - topbox.add(box2); - box.add(topbox); - - JPanel opaquePanel = PaletteHelper.createPaletteJPanel("Map Opaqueness"); - JSlider opaqueSlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 255/* max */, viewAttributes.opaqueness/* inital */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(0), new JLabel("clear")); - dict.put(new Integer(255), new JLabel("opaque")); - opaqueSlide.setLabelTable(dict); - opaqueSlide.setPaintLabels(true); - opaqueSlide.setMajorTickSpacing(50); - opaqueSlide.setPaintTicks(true); - opaqueSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (!slider.getValueIsAdjusting()) { - getViewAttributes().opaqueness = slider.getValue(); - // Notify the server... - getFrameProvider().setViewAttributes(getViewAttributes()); - fireRequestInfoLine("RPF Opaqueness set to " - + getViewAttributes().opaqueness - + " for future requests."); - } - } - }); - opaquePanel.add(opaqueSlide); - box.add(opaquePanel); - - if (getViewAttributes().colorModel == com.bbn.openmap.omGraphics.OMRasterObject.COLORMODEL_DIRECT) { - - JPanel qualityPanel = PaletteHelper.createPaletteJPanel("Image JPEG Quality/Time"); - JSlider qualitySlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 100/* max */, (int) (((CRFPClient) frameProvider).jpegQuality * 100)/* inital */); - java.util.Hashtable dict2 = new java.util.Hashtable(); - dict2.put(new Integer(0), new JLabel("Less")); - dict2.put(new Integer(100), new JLabel("More")); - qualitySlide.setLabelTable(dict2); - qualitySlide.setPaintLabels(true); - qualitySlide.setMajorTickSpacing(20); - qualitySlide.setPaintTicks(true); - qualitySlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (!slider.getValueIsAdjusting()) { - ((CRFPClient) getFrameProvider()).jpegQuality = (float) (slider.getValue()) / 100f; - fireRequestInfoLine("RPF Image JPEG Quality set to " - + ((CRFPClient) getFrameProvider()).jpegQuality - + " for future requests."); - } - } - }); - qualityPanel.add(qualitySlide); - - box.add(qualityPanel); - } - - JPanel subbox2 = new JPanel(); - JButton redraw = new JButton("Redraw RPF Layer"); - redraw.addActionListener(this); - subbox2.add(redraw); - box.add(subbox2); - - return box; - } -} \ No newline at end of file diff --git a/src/core/.gitignore b/src/core/.gitignore deleted file mode 100644 index dc5353ef0..000000000 --- a/src/core/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/.classpath -/.settings/ diff --git a/src/core/.project b/src/core/.project deleted file mode 100644 index d76937231..000000000 --- a/src/core/.project +++ /dev/null @@ -1,36 +0,0 @@ - - - openmap - - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - - diff --git a/src/core/build.xml b/src/core/build.xml deleted file mode 100644 index e4e14b5ae..000000000 --- a/src/core/build.xml +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/core/pom.xml b/src/core/pom.xml deleted file mode 100644 index 0ead70227..000000000 --- a/src/core/pom.xml +++ /dev/null @@ -1,241 +0,0 @@ - - 4.0.0 - openmap - org.openmap-java - 6.0 - jar - openmap - OpenMap is a Java Beans based toolkit for building applications and applets needing geographic information. This project encapsulates the core components of the toolkit. - http://github.com/OpenMap-java/openmap - - UTF-8 - 1.7 - 1.7 - - - - - com.sun.media - jai-codec - 1.1.3 - - - xtiff-jai - xtiff-jai - beta-0.3 - - - - jai - jai-codec - - - jai - jai-core - - - - - edu.stanford.ejalbert - BrowserLauncher2 - 1.3 - - - junit - junit - 4.8.2 - test - - - com.fasterxml.jackson.core - jackson-core - 2.5.3 - - - com.fasterxml.jackson.core - jackson-annotations - 2.5.3 - - - com.fasterxml.jackson.core - jackson-databind - 2.5.3 - - - org.postgis - postgis-jdbc - 1.3.3 - - - org.postgis - postgis-stubs - - - - - org.ancoron.postgresql - org.postgresql - 9.1.901.jdbc4.1-rc9 - - - org.xerial - sqlite-jdbc - 3.8.11.2 - - - no.ecc.vectortile - java-vector-tile - 1.0.8 - - - java3d - j3d-core-utils - 1.3.1 - - - org.apache.xmlgraphics - batik-svg-dom - 1.7 - - - org.apache.xmlgraphics - batik-rasterizer - 1.7 - - - org.apache.xmlgraphics - batik-swing - 1.7 - - - - org.apache.xmlgraphics - batik-transcoder - 1.7 - - - - org.apache.xmlgraphics - batik-svggen - 1.7 - - - - org.apache.xmlgraphics - batik-util - 1.7 - - - - org.apache.xmlgraphics - batik-dom - 1.7 - - - - org.apache.xmlgraphics - batik-bridge - 1.7 - - - - org.apache.xmlgraphics - batik-css - 1.7 - - - - org.apache.xmlgraphics - batik-codec - 1.7 - - - - org.apache.xmlgraphics - batik-awt-util - 1.7 - - - - org.apache.xmlgraphics - batik-ext - 1.7 - - - - org.apache.xmlgraphics - batik-extension - 1.7 - - - xml-apis - xml-apis - 1.4.01 - - - - - - thirdparty-releases - JBoss Thirdparty Releases - https://repository.jboss.org/nexus/content/repositories/thirdparty-releases - - - ECC - https://github.com/ElectronicChartCentre/ecc-mvn-repo/raw/master/releases - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - - true - com.bbn.openmap.app.Main - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.2.1 - - - attach-sources - install - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - false - - - - attach-javadocs - install - - jar - - - - - - - - diff --git a/src/core/src/main/c/cserver/link/ActionRequest.c b/src/core/src/main/c/cserver/link/ActionRequest.c deleted file mode 100644 index b588746d0..000000000 --- a/src/core/src/main/c/cserver/link/ActionRequest.c +++ /dev/null @@ -1,155 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/ActionRequest.c,v $ - * $RCSfile: ActionRequest.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "ActionRequest.h" -#include "Link.h" -#include "GlobalConstants.h" - -/*for debugging*/ -#define DEBUG_ME "LINKSERVER" -#include "toolLib/debugging.h" -DebugVariable(LINK, "LINK", 0x01); /* setenv LINKSERVER "LINK"*/ - -/* - @param Link: The Object used for communication with client over socket -*/ -int ReadActionRequest(Link *link) -{ - int check = OK; /*OK if all read operations returned OK, NOK otherwise*/ - - ActionRequest *action = (ActionRequest *)malloc(sizeof(ActionRequest)); - if(action == NULL) - return -1; /* Memory allocation error */ - - action->mouseEvent = NULL; - action->keyboardEvent = NULL; - - if (Debug(LINK)) printf("ReadActionRequest: reading version\n"); - check = check || ReadFloat(link->socket,&(action->version)); - if (Debug(LINK)) printf("ReadActionRequest: version read %f\n", action->version); - - check = check || ReadDescriptor(link->socket, &(action->descriptor)); - if (Debug(LINK)) printf("ReadActionRequest: Descriptor Read %x\n", action->descriptor); - - /*check which event occured*/ - if(action->descriptor.MOUSE_CLICK || action->descriptor.MOUSE_PRESSED - || action->descriptor.MOUSE_RELEASED || action->descriptor.MOUSE_MOVE - || action->descriptor.MOUSE_ENTER || action->descriptor.MOUSE_EXIT - || action->descriptor.MOUSE_DRAGGED) - { - if (Debug(LINK)) printf("ReadActionRequest: Mouse event\n"); - - action->mouseEvent = (MouseEvent *)malloc(sizeof(MouseEvent)); - if (NULL == action->mouseEvent) - return -1; /* Memory allocation error */ - check = check || ReadMouseEvent(link->socket, action->mouseEvent); - } - else /*Either a mouse event will come or keyboard event...but not both*/ - { - if (Debug(LINK)) printf("ReadActionRequest: Key event\n"); - - if(action->descriptor.KEY_PRESSED || action->descriptor.KEY_RELEASED) - { - action->keyboardEvent = (KeyboardEvent *)malloc(sizeof(KeyboardEvent)); - if (NULL == action->keyboardEvent) - return -1; /* Memory allocation error */ - check = check || ReadKeyboardEvent(link->socket, action->keyboardEvent); - if (check == -1) - return -1; /* Memory allocation error */ - } - else - { - if (Debug(LINK)) printf("Error: Client broke Gesture contract\n"); - } - } - - if (Debug(LINK)) printf("ReadActionRequest: Reading Args.\n"); - check = check || ReadLinkArgs(link->socket, &action->linkargs); - if (check == -1) - return -1; /* Memory allocation error */ - - if (Debug(LINK)) printf("ReadActionRequest: Done Reading Args.\n"); - link->actionRequest = action; - return check; -} - -void FreeActionRequest(ActionRequest *actionrequest) -{ - - if(actionrequest->keyboardEvent) - { - free(actionrequest->keyboardEvent); - } - if(actionrequest->mouseEvent) - { - free(actionrequest->mouseEvent); - } - - FreeLinkArgs(&actionrequest->linkargs); -} - -int ReadMouseEvent(LinkSocket *linkSocket, MouseEvent *mouseEvent) -{ - int check = OK; - - check = check || ReadInteger(linkSocket,&(mouseEvent->x)); - check = check || ReadInteger(linkSocket,&(mouseEvent->y)); - check = check || ReadInteger(linkSocket,&(mouseEvent->clickcount)); - check = check || ReadModifier(linkSocket,&(mouseEvent->modifier)); - check = check || ReadFloat(linkSocket,&(mouseEvent->latitude)); - check = check || ReadFloat(linkSocket, &(mouseEvent->longitude)); - - return check; -} - -int ReadKeyboardEvent(LinkSocket *linkSocket, KeyboardEvent *keyboardEvent) -{ - int check = OK; - /*only 1 char*/ - check = check || ReadUnicodeChars(linkSocket,&(keyboardEvent->keypressed),1); - if (check == -1) - return -1; /* Memory allocation error */ - check = check || ReadModifier(linkSocket, &(keyboardEvent->modifier)); - return check; /* -1 if there was a memory allocation error */ -} - -int SendServerInterest(LinkSocket *linkSocket, Descriptor *descriptor) -{ - int des; - /** Write the ActionRequestHeader here... */ - if (Debug(LINK)) - printf("SendServerInterest: writing ACTION Request header %s\n", - GESTURE_RESPONSE_HEADER); - WriteChars(linkSocket, ACTION_REQUEST_HEADER, lACTION_REQUEST_HEADER); - - if (Debug(LINK)) - printf("SendServerInterest: writing version %f\n", VERSION); - WriteFloat(linkSocket, VERSION); /*writing version 0.2*/ - - des = *((int *)descriptor); - if (Debug(LINK)) printf("SendServerInterest: Sending %x Descriptor\n",des ); - return WriteInteger(linkSocket, des); -} diff --git a/src/core/src/main/c/cserver/link/LatLonPoint.c b/src/core/src/main/c/cserver/link/LatLonPoint.c deleted file mode 100644 index cf38a9630..000000000 --- a/src/core/src/main/c/cserver/link/LatLonPoint.c +++ /dev/null @@ -1,37 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LatLonPoint.c,v $ - * $RCSfile: LatLonPoint.c,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include "LatLonPoint.h" -#include "GlobalConstants.h" - -/* - @param LinkSocket: The socket object from where LatLon - Point values will be read. -*/ -int ReadLatLonPoint(LinkSocket *linkSocket, LatLonPoint *point) -{ - int check = OK; - check = check || ReadFloat(linkSocket, &(point->Lat)); - check = check || ReadFloat(linkSocket, &(point->Lon)); - return check; -} diff --git a/src/core/src/main/c/cserver/link/Link.c b/src/core/src/main/c/cserver/link/Link.c deleted file mode 100644 index bb1603961..000000000 --- a/src/core/src/main/c/cserver/link/Link.c +++ /dev/null @@ -1,181 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/Link.c,v $ - * $RCSfile: Link.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "Link.h" -#include "LinkSocket.h" -#include "MapRequest.h" -#include "GlobalConstants.h" -#include "ActionRequest.h" -#include "Response.h" - -/*Private method*/ -/* - @param Link: The Object used for communication with client over socket - @paran char*: Buffer in which header will be read. -*/ -static char ReadHeader(Link *link, char* header) -{ - int count = 0; - - ReadChars(link->socket, header, 1); - if (NOK == CheckSocket(link->socket)){ - return HEADERERROR; - } - - if(*header == END_TOTAL){ - return END_TOTAL; - } - if(*header == END_SECTION){ - return END_SECTION; - } - if(*header != '<'){ - return HEADERERROR; /*Error*/ - } - - - while(*header++ != '>' && count < MAX_HEADER_LENGTH){ - - ReadChars(link->socket, header,1); - if (NOK == CheckSocket(link->socket)){ - return HEADERERROR; - } - count++; - } - - *header = '\0'; - return HEADERSUCCESS; /*Success*/ -} - -/* - @param Link: The Object used for communication with client over socket -*/ -int CreateLink(Link *link) -{ - int check; - - check = InitSocket(link->socket); - if (check == OK) - { - link->closeLink = LINK_FALSE; /*Link is open*/ - return OK; /*socket succesfully created*/ - } - if (check == -1) - return -1; /* Memory allocation error */ - return NOK; -} - -/*test fucntion*/ -void printString(char *str) -{ - while(*str!=NULL) - printf("%c",*str++); -} - -/* - @param Link: The Object used for communication with client over socket -*/ -char ReadAndParseLink(Link *link) -{ - char header[MAX_HEADER_LENGTH]; - char check = END_SECTION; - - /** Clear out the old map request...*/ - if (link->mapRequest != NULL) - { - FreeMapRequest(link->mapRequest); /* FreeMapRequest-- free memory used - that was allocated while reading - a map request*/ - link->mapRequest = NULL; - } - - if(link->actionRequest != NULL) - { - FreeActionRequest(link->actionRequest); - link->actionRequest = NULL; - } - - while (check != END_TOTAL ) - { - check = ReadHeader(link, header); - if (HEADERSUCCESS == check) - { - if(0 == strcmp(header, MAP_REQUEST_HEADER)) - { - if (ReadMapRequest(link) == -1) - return MEMORYERROR; /* Memory allocation error */ - /* - if all is well..continue, checksocket would exit otherwise - */ - if (NOK == CheckSocket(link->socket)) { - return HEADERERROR; - } - } - if(0 == strcmp(header, ACTION_REQUEST_HEADER)) - { - ReadActionRequest(link); - /* - if all is well..continue, checksocket would exit otherwise - */ - CheckSocket(link->socket); - } - - } - else - { - return HEADERERROR; - } - check = ReadHeader(link, header); - } - return HEADERSUCCESS; -} - -/* - @param Link: The Object used for communication with client over socket -*/ -void FreeLink(Link *link) -{ - if(link->socket != NULL) - { - FreeSocket(link->socket); /*To free memory allocated from heap*/ - free(link->socket); /*to free memory allocated on stack*/ - } - if(link->mapRequest != NULL) - { - FreeMapRequest(link->mapRequest); - free(link->mapRequest); - } - if(link->actionRequest != NULL) - { - FreeActionRequest(link->actionRequest); - } -} - - -/** Send a dummy response that will evoke no wrath. */ -void SendHuh(Link *link){ - WriteChars(link->socket, HUH_HEADER, lHUH_HEADER); - EndTotal(link->socket); -} diff --git a/src/core/src/main/c/cserver/link/LinkArgs.c b/src/core/src/main/c/cserver/link/LinkArgs.c deleted file mode 100644 index a6aba7365..000000000 --- a/src/core/src/main/c/cserver/link/LinkArgs.c +++ /dev/null @@ -1,473 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkArgs.c,v $ - * $RCSfile: LinkArgs.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkArgs.h" -#include "Request.h" -#include "GlobalConstants.h" - -#define DEFAULT_BUFFER_SIZE 80 - -/*for debugging*/ -#define DEBUG_ME "LINKSERVER" -#include -DebugVariable(LINKARGS, "LINKARGS", 0x04); /* setenv LINKSERVER "LINKARGS"*/ - -LinkArgs *CreateLinkArgs(){ - LinkArgs *args = (LinkArgs*)malloc(sizeof(LinkArgs)); - if (NULL == args) - return NULL; /* Memory allocation error */ - - args->numberOfArgs = 0; - args->args = NULL; - return args; -} - -/* - * The args list given is assumed to be a list of key-value pairs in - * an array of LinkArgs, alternating key, value, etc. If the key - * matches one of the keys in the list, a pointer to the value for the - * key is returned. If a match is not found, a NULL is returned. - * - * Note that all key-value pairs are stored internally as Unicode for - * simpler transmission, as well as to allow users to send over Unicode - * on their own. Whenever we get a value for a key, we translate the - * user-supplied key from ASCII to Unicode and then perform the look-up. - */ - -char* GetValueForKey(LinkArgs *args, char* key) { - char *temp_key = ASCIIToEnglishUnicode(key); - - LinkString *ls = args->args; - - while (ls - (args->args) < args->numberOfArgs){ - if (unicodecmp(temp_key, ls->text, strlen(key) * 2)) { - return (++ls)->text; - } - ls+=2; - } - return (char*)NULL; -} - -int SetKeyIntegerPairInLinkArgs(LinkArgs *linkArgs, char *key, int value){ - char *buf = (char*)malloc(DEFAULT_BUFFER_SIZE); - if (buf == NULL) return -1; /* Memory allocation error */ - sprintf(buf, "%d", value); - SetKeyValuePairInLinkArgs(linkArgs, key, buf, 0, 0); - free(buf); - return OK; -} - -int SetKeyDoublePairInLinkArgs(LinkArgs *linkArgs, char *key, double value){ - char *buf = (char*)malloc(DEFAULT_BUFFER_SIZE); - if (buf == NULL) return -1; /* Memory allocation error */ - sprintf(buf, "%f", value); - SetKeyValuePairInLinkArgs(linkArgs, key, buf, 0, 0); - free(buf); - return OK; -} - -int SetKeyValuePairInLinkArgs(LinkArgs *linkArgs, char *key, char *value, - int is_unicode, int num_unicode_chars){ - int count, numberOfArgs; - LinkString *oldStrings; - int keyExists = 0; - char *temp_key, *temp_value; - int i; - - - /* - * First, check and make sure that the key doesn't exist for another - * value. If it does, replace the value for that key with the new - * value. - */ - - LinkString *ls = linkArgs->args; - numberOfArgs = linkArgs->numberOfArgs; - - /* - * Translate the key and value into Unicode for matching and storage. - */ - - temp_key = ASCIIToEnglishUnicode(key); - temp_value = is_unicode ? value : ASCIIToEnglishUnicode(value); - - while (ls - (linkArgs->args) < numberOfArgs){ - /* - * We use unicodecmp() here to compare two Unicode strings. - * See the comments in LinkSocket.c for more information. - */ - if (!unicodecmp(temp_key, ls->text, strlen(key) * 2)) { - keyExists = 1; - (++ls)->numberOfChars = strlen(value) * 2; - free(ls->text); /* Dump the old text */ - ls->text = (char*)malloc(ls->numberOfChars + 1); - if (ls->text == NULL) - return -1; /* Memory allocation error */ - - /* - * This was originally handled with a strcpy(ls->text, temp_value), - * and would have failed for any Unicode strings as values. - * Note that if Unicode chars are passed as values in the first - * place, we need to pass through the number of characters they - * take up; strlen() on that value would fail miserably. - */ - - for (i = 0; - i < (is_unicode ? num_unicode_chars : strlen(value) * 2); - i++) { - ls->text[0] = temp_value[i]; - } - } - else { - ls+=2; - } - } - - free(temp_key); /* Free up the memory used to translate into Unicode */ - free(temp_value); - - - /* - * If the key didn't exist in the link arguments, create storage for - * the new key-value pair. - */ - - - if (!keyExists){ - temp_key = ASCIIToEnglishUnicode(key); - temp_value = is_unicode ? value : ASCIIToEnglishUnicode(value); - - /*Keep track of the old strings.*/ - oldStrings = linkArgs->args; - - /*Allocate memory for the addition.*/ - linkArgs->args = (LinkString *)malloc(sizeof(LinkString) * (numberOfArgs + 2)); - - if (NULL == linkArgs->args) - return -1; /* Memory allocation error. */ - - /** Copy the old strings to the new memory.*/ - memcpy(linkArgs->args, oldStrings, sizeof(LinkString)*numberOfArgs); - - /** Save the new pair of in the linkArgs. First the key,*/ - - count = strlen(key) * 2; /* Unicode uses twice as many chars as ASCII */ - - linkArgs->args[numberOfArgs].numberOfChars = count; - linkArgs->args[numberOfArgs].text = (char *)malloc(count + 1); - - if (linkArgs->args[numberOfArgs].text == NULL) - return -1; /* Memory allocation error */ - - /* - * Ideally, we should be able to use strcpy() to copy the contents of - * temp_key into linkArgs->args[numberOfArgs].text. However, since the - * first character of our Unicoded key is 0x0, strcpy() will stop - * immediately. - */ - - for (i = 0; i < count; i++) - linkArgs->args[numberOfArgs].text[i] = temp_key[i]; - - /** And now the value. */ - numberOfArgs++; - - /* Unicode uses twice as many chars as ASCII*/ - count = is_unicode ? num_unicode_chars : strlen(value) * 2; - - linkArgs->args[numberOfArgs].numberOfChars = count; - linkArgs->args[numberOfArgs].text = (char *)malloc(count + 1); - - if (NULL == linkArgs->args[numberOfArgs].text) - return -1; /* Memory allocation error */ - - for (i = 0; i < count; i++) - linkArgs->args[numberOfArgs].text[i] = temp_value[i]; - - /** Modify the count to include the new key and value. */ - linkArgs->numberOfArgs+=2; - /** Free up the structure holding the old pointers.*/ - free(oldStrings); - - /* - * And free up the memory for the Unicode versions of the key-value - * pairs. - */ - - free(temp_key); - free(temp_value); - } - return OK; -} - -int RemoveKeyFromLinkArgs(LinkArgs *linkArgs, char *key){ - int numberOfArgs; - int keyExists = 0; - char *temp_key = ASCIIToEnglishUnicode(key); - - /* First, make sure the key actually exists in the arguments.*/ - LinkString *ls = linkArgs->args; - numberOfArgs = linkArgs->numberOfArgs; - - while (ls - (linkArgs->args) < numberOfArgs){ - if (!unicodecmp(temp_key, ls->text, strlen(key) * 2)) { - keyExists = 1; - break; - } - else { - ls+=2; - } - } - - if (keyExists){ - int i, k; - int j = 0; - LinkString *oldStrings; - - /*Keep track of the old strings.*/ - oldStrings = linkArgs->args; - /*Allocate memory for the newer, smaller array link arguments. */ - linkArgs->args = (LinkString *)malloc(sizeof(LinkString) * (numberOfArgs - 2)); - - if(NULL == linkArgs->args) - return -1; /* Memory allocation error */ - - j = 0; - for (i = 0; i < numberOfArgs; i++){ - if (!unicodecmp(oldStrings[i].text, temp_key, strlen(key) *2)) { - free(oldStrings[i++].text); - free(oldStrings[i++].text); - } - else { - /* Copy the good pair.... */ - linkArgs->args[j].numberOfChars = oldStrings[i].numberOfChars; - for (k = 0; k < oldStrings[i].numberOfChars; k++) { - linkArgs->args[j].text[k] = oldStrings[i].text[k]; - } - i++; - j++; - - linkArgs->args[j].numberOfChars = oldStrings[i].numberOfChars; - for (k = 0; k < oldStrings[i].numberOfChars; k++) { - linkArgs->args[j].text[k] = oldStrings[i].text[k]; - } - i++; - j++; - } - } - - /** Modify the count to remove the specified key and value. */ - linkArgs->numberOfArgs-=2; - /** Free up the structure holding the old pointers.*/ - free(oldStrings); - } - free(temp_key); - return OK; -} - -int WriteLinkArgString(LinkSocket *linkSocket, LinkString *str) -{ - int check = OK; - /*Write number of characters in string*/ - -/* if (Debug(LINKARGS)){ */ -/* printf("WriteLinkArgString: %d characters: %s\n", str->numberOfChars, str->text); */ -/* } */ - - check = check || WriteInteger(linkSocket, str->numberOfChars / 2 ); - check = check || WriteUnicodeChars(linkSocket, str->text, str->numberOfChars); - return check; /* Returns -1 if there was a memory allocation error */ -} - -int ReadLinkString(LinkSocket *linkSocket, LinkString *args) -{ - /* How many characters in a string*/ - int check = OK; - check = check || ReadInteger(linkSocket, &(args->numberOfChars)); - - /*Allocate memory. Keep space for NULL*/ - args->text = (char *)malloc(args->numberOfChars + 1); - if(NULL == args->text) - return -1; /* Memory allocation error */ - - /*Read them from socket. */ - if(args->numberOfChars > 0) - { - check = check || ReadChars(linkSocket, args->text, args->numberOfChars); - args->text[args->numberOfChars] = NULL; - } - - return check; -} - -int WriteLinkString(LinkSocket *linkSocket, LinkString *str) -{ - int check = OK; - /*Write number of characters in string*/ - check = check || WriteInteger(linkSocket, str->numberOfChars); - check = check || WriteChars(linkSocket, str->text, str->numberOfChars); - return check; -} - -int BufferedWriteLinkString(char *toBuffer, LinkString *str) -{ - int byteswritten = 0; - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - str->numberOfChars); - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - str->text, str->numberOfChars); - return byteswritten; -} - -void FreeLinkString(LinkString *string) -{ - free(string->text); - string->text = NULL; -} - -int ReadLinkArgs(LinkSocket *linkSocket, LinkArgs *linkargs) -{ - int i; - int check = OK; - - /* - * ### bmackiew: Remember that Unicode is being read in, not ASCII. - */ - - /* How many arguments are coming*/ - check = check || ReadInteger(linkSocket, &(linkargs->numberOfArgs)); - - if (Debug(LINKARGS)) printf ("ReadLinkArgs: reading %d args: \n", - linkargs->numberOfArgs); - - /*Allocate memory*/ - linkargs->args = (LinkString *)malloc(sizeof(LinkString) * - linkargs->numberOfArgs); - if(NULL == linkargs->args) - return -1; /* Memory allocation error */ - - /* Read arguments*/ - for(i=0; i < linkargs->numberOfArgs; i++ ) - { - - /* - though args is a string object, we do not use readlinkstring as below, - because readlinkstring reads only chars, where as we need unicode chars - - check = check & ReadLinkString(linkSocket, &linkargs->args[i]); - */ - check = check || ReadInteger(linkSocket, &(linkargs->args[i].numberOfChars)); - linkargs->args[i].text = (char *)malloc(linkargs->args[i].numberOfChars + 1); - if(NULL == linkargs->args[i].text) - return -1; /* Memory allocation error */ - - /*Read them from socket. */ - check = check || ReadUnicodeChars(linkSocket, linkargs->args[i].text, - linkargs->args[i].numberOfChars); - if (check == -1) - return -1; /* Memory allocation error */ - - linkargs->args[i].text[linkargs->args[i].numberOfChars] = '\0'; - if (Debug(LINKARGS)) printf ("ReadLinkArgs: reading arg %d|%s\n", i, - linkargs->args[i].text); - } - - return check; -} - -int WriteLinkArgs(LinkSocket *linkSocket, LinkArgs *linkArgs) -{ - int i; - int check = OK; - LinkString *ls; - - if (Debug(LINKARGS)){ - printf("WriteLinkArgs: Writing args %d\n", linkArgs->numberOfArgs); - } - - check = check || WriteInteger(linkSocket, linkArgs->numberOfArgs); - - for (i = 0; i < linkArgs->numberOfArgs; i++){ - ls = (linkArgs->args) + i; - check = check || WriteLinkArgString(linkSocket, ls); - if (check == -1) - return -1; /* Memory allocation error */ - } - return check; -} - -int BufferedWriteLinkArgs(char *toBuffer, LinkArgs *linkArgs) -{ - int i; - int byteswritten = 0; - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - linkArgs->numberOfArgs); - for (i = 0; i < linkArgs->numberOfArgs; i++){ - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - linkArgs->args[i].numberOfChars); - byteswritten += BufferedWriteUnicodeChars(&toBuffer[byteswritten], - linkArgs->args[i].text, - linkArgs->args[i].numberOfChars); - } - return byteswritten; -} - -int LinkSizeOfLinkArgs(LinkArgs *linkArgs) -{ - int i; - int size = 0; - - /* - * ### bmackiew: This should be updated for Unicodeness, too. - */ - - size += N_BYTES_PER_INTEGER; - for (i = 0; i < linkArgs->numberOfArgs; i++) - { - size += N_BYTES_PER_INTEGER; - - /* - * ### bmackiew: Now that this data is stored in Unicode, we need - * only count the number of characters stored. - */ -#if 0 - size += N_CHARS_PER_UNICODE_CHAR*linkArgs->args[i].numberOfChars; -#else - size += linkArgs->args[i].numberOfChars; -#endif - } - return size; -} - -void FreeLinkArgs(LinkArgs *linkargs) -{ - int i; - for(i=0; i < linkargs->numberOfArgs; i++){ - FreeLinkString(&linkargs->args[i]); - } - free(linkargs->args); -} - diff --git a/src/core/src/main/c/cserver/link/LinkBitmap.c b/src/core/src/main/c/cserver/link/LinkBitmap.c deleted file mode 100644 index 3dd63a094..000000000 --- a/src/core/src/main/c/cserver/link/LinkBitmap.c +++ /dev/null @@ -1,248 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkBitmap.c,v $ - * $RCSfile: LinkBitmap.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkBitmap.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteLinkBitmapHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, BITMAP_HEADER, lBITMAP_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_BITMAP); - return check; -} - -int BufferedWriteLinkBitmapHeader(char *toBuffer) -{ - int byteswritten = 0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - BITMAP_HEADER, - lBITMAP_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_BITMAP); - return byteswritten; -} - -/* - @param LinkSocket: the socket connection on which data is written -*/ -int BufferedWriteLinkBitmapLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfbytes*/ - numberOfbytes + /*Bytes used by bitmap*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkBitmapHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfbytes); - buffercount += BufferedWriteChars(&buffer[buffercount],bitmap, numberOfbytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - -int WriteLinkBitmapLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkBitmapHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteInteger(linkSocket, numberOfbytes); - check = check || WriteChars(linkSocket,bitmap, numberOfbytes); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* If -1, memory allocation error in WriteLinkArgs */ -} - -int BufferedWriteLinkBitmapXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfbytes*/ - numberOfbytes + /*Bytes used by bitmap*/ - LinkSizeOfLinkArgs(linkArgs); - - - buffer = (char *)malloc(sizeof(buffercount)); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkBitmapHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfbytes); - buffercount += BufferedWriteChars(&buffer[buffercount],bitmap, numberOfbytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - -int WriteLinkBitmapXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int check = OK; - - check = check || WriteLinkBitmapHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteInteger(linkSocket, numberOfbytes); - check = check || WriteChars(linkSocket,bitmap, numberOfbytes); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs*/ -} - -int BufferedWriteLinkBitmapOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfbytes*/ - numberOfbytes + /*Bytes used by bitmap*/ - LinkSizeOfLinkArgs(linkArgs); - - - buffer = (char *)malloc(sizeof(buffercount)); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkBitmapHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfbytes); - buffercount += BufferedWriteChars(&buffer[buffercount],bitmap, numberOfbytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int WriteLinkBitmapOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkBitmapHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteInteger(linkSocket, numberOfbytes); - check = check || WriteChars(linkSocket,bitmap, numberOfbytes); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error */ -} - - diff --git a/src/core/src/main/c/cserver/link/LinkCircle.c b/src/core/src/main/c/cserver/link/LinkCircle.c deleted file mode 100644 index 9c4db4bbd..000000000 --- a/src/core/src/main/c/cserver/link/LinkCircle.c +++ /dev/null @@ -1,219 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkCircle.c,v $ - * $RCSfile: LinkCircle.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkCircle.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteCircleHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, CIRCLE_HEADER, - lCIRCLE_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_CIRCLE); - return check; -} - -int BufferedWriteCircleHeader(char *toBuffer) -{ - int byteswritten =0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - CIRCLE_HEADER, - lCIRCLE_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_CIRCLE); - return byteswritten; -} - -int WriteLinkCircleLatLon(LinkSocket *linkSocket, - double lat, double lon, - double radius, int unit, - int nvertices, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteCircleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteFloat(linkSocket,(float)radius); - check = check || WriteInteger(linkSocket, unit); - check = check || WriteInteger(linkSocket, nvertices); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs*/ - -} - - -int WriteLinkCircleXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteCircleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs() */ - -} - - -int WriteLinkCircleOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteCircleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs() */ - -} - -int BufferedWriteLinkCircleLatLon(LinkSocket *linkSocket, - double lat, double lon, - double radius, int unit, - int nvertices, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lCIRCLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by rendertype identifier*/ - 3*N_BYTES_PER_FLOAT + /*Bytes used by lat,lon and radius*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by unit and vertices*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - buffercount=0; - - buffercount += BufferedWriteCircleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)radius); - buffercount += BufferedWriteInteger(&buffer[buffercount], unit); - buffercount += BufferedWriteInteger(&buffer[buffercount], nvertices); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkCircleXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lCIRCLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by rendertype identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - buffercount=0; - - buffercount += BufferedWriteCircleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkCircleOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lCIRCLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by rendertype identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - buffercount=0; - - buffercount += BufferedWriteCircleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} diff --git a/src/core/src/main/c/cserver/link/LinkEllipse.c b/src/core/src/main/c/cserver/link/LinkEllipse.c deleted file mode 100644 index 636ac63c7..000000000 --- a/src/core/src/main/c/cserver/link/LinkEllipse.c +++ /dev/null @@ -1,117 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkEllipse.c,v $ - * $RCSfile: LinkEllipse.c,v $ - * $Revision: 1.2 $ - * $Date: 2006/10/10 22:05:18 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkEllipse.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteEllipseHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, ELLIPSE_HEADER, - lELLIPSE_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_ELLIPSE); - return check; -} - -int BufferedWriteEllipseHeader(char *toBuffer) -{ - int byteswritten =0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - ELLIPSE_HEADER, - lELLIPSE_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_ELLIPSE); - return byteswritten; -} - -int WriteLinkEllipseLatLon(LinkSocket *linkSocket, - double lat, double lon, - double majorAxis, double minorAxis, int unit, - double rotationAngle, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteEllipseHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteFloat(linkSocket, (float)majorAxis); - check = check || WriteFloat(linkSocket, (float)minorAxis); - check = check || WriteInteger(linkSocket, unit); - check = check || WriteFloat(linkSocket, (float)rotationAngle); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs*/ - -} - - -int WriteLinkEllipseXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - double rotationAngle, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteEllipseHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteFloat(linkSocket, (float)rotationAngle); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs() */ - -} - - -int WriteLinkEllipseOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - double rotationAngle, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteEllipseHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteFloat(linkSocket, (float)rotationAngle); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; /* -1 if there was a memory allocation error in WriteLinkArgs() */ - -} - diff --git a/src/core/src/main/c/cserver/link/LinkGrid.c b/src/core/src/main/c/cserver/link/LinkGrid.c deleted file mode 100644 index 8d2b2d802..000000000 --- a/src/core/src/main/c/cserver/link/LinkGrid.c +++ /dev/null @@ -1,340 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkGrid.c,v $ - * $RCSfile: LinkGrid.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkGrid.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteLinkGridHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, GRID_HEADER, - lGRID_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_GRID); - return check; -} - -int BufferedWriteLinkGridHeader(char *toBuffer) -{ - int byteswritten = 0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - GRID_HEADER, - lGRID_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_GRID); - return byteswritten; -} - -/* - @param LinkSocket: the socket connection on which data is written -*/ -int BufferedWriteLinkGridLatLon(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - int numberOfBytes = rows*columns*N_BYTES_PER_INTEGER; - - buffercount = lGRID_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by rows and columns*/ - 3*N_BYTES_PER_FLOAT + /* bytes for orientation, vResolution, hResolution */ - N_BYTES_PER_INTEGER + /*Bytes used by major*/ - N_BYTES_PER_INTEGER + /*Bytes used by length of data*/ - numberOfBytes + /*Bytes used by grid*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - buffercount=0; - - buffercount += BufferedWriteLinkGridHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], rows); - buffercount += BufferedWriteInteger(&buffer[buffercount], columns); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)orientation); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)vResolution); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)hResolution); - buffercount += BufferedWriteInteger(&buffer[buffercount], major); - buffercount += BufferedWriteInteger(&buffer[buffercount], rows*columns); - buffercount += BufferedWriteChars(&buffer[buffercount], (char*)data, numberOfBytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int WriteLinkGridLatLon(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int i; - int numberOfInts; - int check = OK; - - check = check || WriteLinkGridHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, rows); - check = check || WriteInteger(linkSocket, columns); - check = check || WriteFloat(linkSocket,(float)orientation); - check = check || WriteFloat(linkSocket,(float)vResolution); - check = check || WriteFloat(linkSocket,(float)hResolution); - check = check || WriteInteger(linkSocket, major); - - numberOfInts = rows*columns; - check = check || WriteInteger(linkSocket, numberOfInts); - for (i = 0; i < numberOfInts; i++){ - check = check || WriteInteger(linkSocket, data[i]); - } - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkGridLatLonS(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, short *data, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - int sub; - int numberOfInts; - - check = check || WriteLinkGridHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, rows); - check = check || WriteInteger(linkSocket, columns); - check = check || WriteFloat(linkSocket,(float)orientation); - check = check || WriteFloat(linkSocket,(float)vResolution); - check = check || WriteFloat(linkSocket,(float)hResolution); - check = check || WriteInteger(linkSocket, major); - - numberOfInts = rows*columns; - check = check || WriteInteger(linkSocket, numberOfInts); - for (i = 0; i < numberOfInts; i++){ - sub = (int)data[i]; - check = check || WriteInteger(linkSocket, sub); - } - - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkGridXY(LinkSocket *linkSocket, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - int numberOfBytes = rows*columns*N_BYTES_PER_INTEGER; - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lGRID_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x, y, rows and columns*/ - 3*N_BYTES_PER_FLOAT + /* bytes for orientation, vResolution and hResolution */ - N_BYTES_PER_INTEGER + /*Bytes used by major*/ - N_BYTES_PER_INTEGER + /*Bytes used by length of data*/ - numberOfBytes + /*Bytes used by grid*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkGridHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], rows); - buffercount += BufferedWriteInteger(&buffer[buffercount], columns); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)orientation); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)vResolution); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)hResolution); - buffercount += BufferedWriteInteger(&buffer[buffercount], major); - buffercount += BufferedWriteInteger(&buffer[buffercount], rows*columns); - buffercount += BufferedWriteChars(&buffer[buffercount], (char*)data, numberOfBytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - -int WriteLinkGridXY(LinkSocket *linkSocket, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - int numberOfInts = rows*columns; - - check = check || WriteLinkGridHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, rows); - check = check || WriteInteger(linkSocket, columns); - check = check || WriteFloat(linkSocket,(float)orientation); - check = check || WriteFloat(linkSocket,(float)vResolution); - check = check || WriteFloat(linkSocket,(float)hResolution); - check = check || WriteInteger(linkSocket, major); - - check = check || WriteInteger(linkSocket, numberOfInts); - for (i = 0; i < numberOfInts; i++){ - check = check || WriteInteger(linkSocket, data[i]); - } - - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkGridOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - int numberOfBytes = rows*columns*N_BYTES_PER_INTEGER; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lGRID_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,rows and columns*/ - /*these are common to all*/ - 3*N_BYTES_PER_FLOAT + /* bytes for orientation, vResolution and hResolution */ - N_BYTES_PER_INTEGER + /*Bytes used by major*/ - N_BYTES_PER_INTEGER + /*Bytes used by length of data*/ - numberOfBytes + /*Bytes used by grid*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if (buffer == NULL) - return -1; /* Memory allocation error */ - buffercount=0; - - buffercount += BufferedWriteLinkGridHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], columns); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)orientation); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)vResolution); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)hResolution); - buffercount += BufferedWriteInteger(&buffer[buffercount], major); - buffercount += BufferedWriteInteger(&buffer[buffercount], rows*columns); - buffercount += BufferedWriteChars(&buffer[buffercount], (char*)data, numberOfBytes); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int WriteLinkGridOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int *data, - LinkArgs *linkArgs) -{ - int i; - int numberOfInts = rows*columns; - int check = OK; - - check = check || WriteLinkGridHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, rows); - check = check || WriteInteger(linkSocket, columns); - check = check || WriteFloat(linkSocket,(float)orientation); - check = check || WriteFloat(linkSocket,(float)vResolution); - check = check || WriteFloat(linkSocket,(float)hResolution); - check = check || WriteInteger(linkSocket, major); - - check = check || WriteInteger(linkSocket, numberOfInts); - for (i = 0; i < numberOfInts; i++){ - check = check || WriteInteger(linkSocket, data[i]); - } - - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - diff --git a/src/core/src/main/c/cserver/link/LinkImage.c b/src/core/src/main/c/cserver/link/LinkImage.c deleted file mode 100644 index bb3aa6034..000000000 --- a/src/core/src/main/c/cserver/link/LinkImage.c +++ /dev/null @@ -1,138 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkImage.c,v $ - * $RCSfile: LinkImage.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include "LinkImage.h" -#include "LinkSocket.h" -#include "GlobalConstants.h" - -int WriteDirectImage(LinkSocket *linkSocket, DirectImage *directimage) -{ - - int check= OK,i; - /*Write number of pixels a client is supposed to read*/ - check = check || WriteInteger(linkSocket, directimage->numberOfPixels); - - /*Write the values*/ - - /*An optimized version. Write the entire buffer instead of writing every integer*/ - /* check = check || WriteChars(linkSocket,(char *)directimage->image, - directimage->numberOfPixels*N_BYTES_PER_INTEGER); */ - for(i=0;inumberOfPixels;i++) - { - check = check || WriteInteger(linkSocket, directimage->image[i]); - } - return check; -} - -int BufferedWriteDirectImage(char *toBuffer, DirectImage *directimage) -{ - int byteswritten = 0,i; - /*Write number of pixels a client is supposed to read*/ - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - directimage->numberOfPixels); - - /*Write the values*/ - /*An optimized version. Write the entire buffer instead of writing every integer*/ - /*byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - (char *)directimage->image, - directimage->numberOfPixels*N_BYTES_PER_INTEGER);*/ - - for(i=0;inumberOfPixels;i++) - { - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - directimage->image[i]); - } - return byteswritten; -} - -int GetDirectImageSize(DirectImage *directimage) -{ - return N_BYTES_PER_INTEGER + /*Bytes used by nmberOfPixels(an Integer)*/ - N_BYTES_PER_INTEGER*directimage->numberOfPixels; /*Bytes used by pixels*/ -} - -int WriteIndexedImage(LinkSocket *linkSocket, IndexedImage *indexedimage) -{ - int check = OK,i; - /* Write number of pixels*/ - check = check || WriteInteger(linkSocket, indexedimage->numberOfPixels); - - /*Write image*/ - check = check || WriteChars(linkSocket, indexedimage->image, - indexedimage->numberOfPixels); - - /*Write color table size*/ - check = check || WriteInteger(linkSocket, indexedimage->colorTableSize); - /*Write Color table*/ - /*The optimized version*/ - /*check = check || WriteChars(linkSocket, indexedimage->colorTable, - indexedimage->colorTableSize*N_BYTES_PER_INTEGER);*/ - - for(i=0;icolorTableSize;i++) - { - check = check || WriteInteger(linkSocket, indexedimage->colorTable[i]); - } - return check; -} - - -int BufferedWriteIndexedImage(char *toBuffer, IndexedImage *indexedimage) -{ - int byteswritten = 0,i; - - /* Write number of pixels*/ - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - indexedimage->numberOfPixels); - /*Write image*/ - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - indexedimage->image, indexedimage->numberOfPixels); - /*Write color table size*/ - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - indexedimage->colorTableSize); - /*Write Color table*/ - /*The optimized version*/ - /*byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - (char *)indexedimage->colorTable, - indexedimage->colorTableSize*N_BYTES_PER_INTEGER);*/ - - for(i=0;icolorTableSize;i++) - { - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - indexedimage->colorTable[i]); - } - return byteswritten; -} - -int GetIndexedImageSize(IndexedImage *indexedimage) -{ - return N_BYTES_PER_INTEGER + /*Bytes used by numberOfPixels(an Integer)*/ - indexedimage->numberOfPixels + /*each pixel is 1 byte */ - N_BYTES_PER_INTEGER + /* Bytes used by colorTableSize */ - N_BYTES_PER_INTEGER*indexedimage->colorTableSize + - N_BYTES_PER_INTEGER; /*Bytes used by transparency(an integer)*/ -} - - - - - diff --git a/src/core/src/main/c/cserver/link/LinkLine.c b/src/core/src/main/c/cserver/link/LinkLine.c deleted file mode 100644 index 571c6005a..000000000 --- a/src/core/src/main/c/cserver/link/LinkLine.c +++ /dev/null @@ -1,226 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkLine.c,v $ - * $RCSfile: LinkLine.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkLine.h" -#include "LinkSocket.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteLinkLineLatLon(LinkSocket *linkSocket, - double lat_1, double lon_1, - double lat_2, double lon_2, - int lineType, int nsegs, - LinkArgs *linkArgs) -{ - int check = OK; - - check = check || WriteChars(linkSocket, LINE_HEADER, lLINE_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_LINE); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, lineType); - check = check || WriteFloat(linkSocket, (float)lat_1); - check = check || WriteFloat(linkSocket, (float)lon_1); - check = check || WriteFloat(linkSocket, (float)lat_2); - check = check || WriteFloat(linkSocket, (float)lon_2); - check = check || WriteInteger(linkSocket, nsegs); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkLineXY(LinkSocket *linkSocket, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteChars(linkSocket,LINE_HEADER, lLINE_HEADER); - check = check || WriteInteger(linkSocket,GRAPHICTYPE_LINE); - check = check || WriteInteger(linkSocket,RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x1); - check = check || WriteInteger(linkSocket, y1); - check = check || WriteInteger(linkSocket, x2); - check = check || WriteInteger(linkSocket, y2); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkLineOffset(LinkSocket *linkSocket, - double lat_1, double lon_1, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteChars(linkSocket, LINE_HEADER, lLINE_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_LINE); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket, (float)lat_1); - check = check || WriteFloat(linkSocket, (float)lon_1); - check = check || WriteInteger(linkSocket, x1); - check = check || WriteInteger(linkSocket, y1); - check = check || WriteInteger(linkSocket, x2); - check = check || WriteInteger(linkSocket, y2); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int BufferedWriteLinkLineLatLon(LinkSocket *linkSocket, - double lat_1, double lon_1, - double lat_2, double lon_2, - int lineType, int nsegs, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by lineType and nsegs*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteChars(&buffer[buffercount], - LINE_HEADER, lLINE_HEADER); - buffercount += BufferedWriteInteger(&buffer[buffercount], GRAPHICTYPE_LINE); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], lineType); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat_1); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon_1); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat_2); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon_2); - buffercount += BufferedWriteInteger(&buffer[buffercount], nsegs); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkLineXY(LinkSocket *linkSocket, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs) -{ - - int buffercount; - - char *buffer; - int retval; - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteChars(&buffer[buffercount], - LINE_HEADER, lLINE_HEADER); - buffercount += BufferedWriteInteger(&buffer[buffercount],GRAPHICTYPE_LINE); - buffercount += BufferedWriteInteger(&buffer[buffercount],RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], x1); - buffercount += BufferedWriteInteger(&buffer[buffercount], y1); - buffercount += BufferedWriteInteger(&buffer[buffercount], x2); - buffercount += BufferedWriteInteger(&buffer[buffercount], y2); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - - free(buffer); - return retval; -} - -int BufferedWriteLinkLineOffset(LinkSocket *linkSocket, - double lat_1, double lon_1, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lBITMAP_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteChars(&buffer[buffercount], - LINE_HEADER, lLINE_HEADER); - buffercount += BufferedWriteInteger(&buffer[buffercount], GRAPHICTYPE_LINE); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat_1); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon_1); - buffercount += BufferedWriteInteger(&buffer[buffercount], x1); - buffercount += BufferedWriteInteger(&buffer[buffercount], y1); - buffercount += BufferedWriteInteger(&buffer[buffercount], x2); - buffercount += BufferedWriteInteger(&buffer[buffercount], y2); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} diff --git a/src/core/src/main/c/cserver/link/LinkPoint.c b/src/core/src/main/c/cserver/link/LinkPoint.c deleted file mode 100644 index 1b023f4be..000000000 --- a/src/core/src/main/c/cserver/link/LinkPoint.c +++ /dev/null @@ -1,92 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkPoint.c,v $ - * $RCSfile: LinkPoint.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkPoint.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WritePointHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, POINT_HEADER, - lPOINT_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_POINT); - return check; -} - -int WriteLinkPointLatLon(LinkSocket *linkSocket, - double lat, double lon, - int radius, LinkArgs *linkArgs) -{ - int check = OK; - check = check || WritePointHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, radius); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkPointXY(LinkSocket *linkSocket, - int x, int y, int radius, LinkArgs *linkArgs) -{ - int check = OK; - check = check || WritePointHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, radius); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkPointOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, int radius, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WritePointHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, radius); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - diff --git a/src/core/src/main/c/cserver/link/LinkPoly.c b/src/core/src/main/c/cserver/link/LinkPoly.c deleted file mode 100644 index c3895cae7..000000000 --- a/src/core/src/main/c/cserver/link/LinkPoly.c +++ /dev/null @@ -1,496 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkPoly.c,v $ - * $RCSfile: LinkPoly.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkPoly.h" -#include "LinkSocket.h" -#include "Response.h" -#include "Link.h" -#include "GlobalConstants.h" - - -int WriteLinkPolyHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, POLY_HEADER, lPOLY_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_POLY); - return check; -} - -int WriteLinkPolyLatLon(LinkSocket *linkSocket, int ltype, - int numberOflatlon, double latlon[], - int unit, int nsegs, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, ltype); - check = check || WriteInteger(linkSocket, numberOflatlon); - - for(i=0;i < numberOflatlon; i++) - { - check = check || WriteFloat(linkSocket, (float)latlon[i]); - } - - check = check || WriteInteger(linkSocket, unit); - check = check || WriteInteger(linkSocket, nsegs); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyLatLon2D(LinkSocket *linkSocket, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - double lat[], double lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, ltype); - check = check || WriteInteger(linkSocket, numberOflatlon + numberOflatlon); - - for(i=0;i < numberOflatlon; i++) - { - check = check || WriteFloat(linkSocket, (float)lat[i]); - check = check || WriteFloat(linkSocket, (float)lon[i]); - } - - check = check || WriteInteger(linkSocket, unit); - check = check || WriteInteger(linkSocket, nsegs); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyLatLon2F(LinkSocket *linkSocket, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - float lat[], float lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, ltype); - check = check || WriteInteger(linkSocket, numberOflatlon + numberOflatlon); - - for(i=0;i < numberOflatlon; i++) - { - check = check || WriteFloat(linkSocket, (float)lat[i]); - check = check || WriteFloat(linkSocket, (float)lon[i]); - } - - check = check || WriteInteger(linkSocket, unit); - check = check || WriteInteger(linkSocket, nsegs); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyXY(LinkSocket *linkSocket, - int numberOfXY, int XY[], - LinkArgs *linkArgs) -{ - int i; - int check = OK; - - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, numberOfXY); - - for(i=0; i < numberOfXY; i++) - WriteInteger(linkSocket, XY[i]); - - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyXY2(LinkSocket *linkSocket, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], /* These 2 arrays are of equal size*/ - LinkArgs *linkArgs) -{ - int i; - int check = OK; - - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, numberOfXY + numberOfXY); - - for(i=0; i < numberOfXY; i++) - { - WriteInteger(linkSocket, X[i]); - WriteInteger(linkSocket, Y[i]); - } - - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyOffset(LinkSocket *linkSocket, - double lat, double lon, - int numberOfXY, int XY[], int CoordMode, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - - check = check || WriteFloat(linkSocket, lat); - check = check || WriteFloat(linkSocket, lon); - check = check || WriteInteger(linkSocket, numberOfXY); - - for(i=0; i < numberOfXY; i++) - WriteInteger(linkSocket, XY[i]); - - check = check || WriteInteger(linkSocket, CoordMode); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int WriteLinkPolyOffset2(LinkSocket *linkSocket, - double lat, double lon, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], - int CoordMode, - LinkArgs *linkArgs) -{ - int i; - int check = OK; - - check = check || WriteLinkPolyHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - - check = check || WriteFloat(linkSocket, lat); - check = check || WriteFloat(linkSocket, lon); - check = check || WriteInteger(linkSocket, numberOfXY + numberOfXY); - - for(i=0; i < numberOfXY; i++) - { - WriteInteger(linkSocket, X[i]); - WriteInteger(linkSocket, Y[i]); - } - - check = check || WriteInteger(linkSocket, CoordMode); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkPolyHeader(char *toBuffer) -{ - int byteswritten = 0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - POLY_HEADER, lPOLY_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], GRAPHICTYPE_POLY); - return byteswritten; -} - -int BufferedWriteLinkPolyLatLon(LinkSocket *linkSocket, int ltype, - int numberOflatlon, double latlon[], - int unit, int nsegs, - LinkArgs *linkArgs) -{ - int i; - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by numberOflatlon, unit, nsegs,ltype*/ - N_BYTES_PER_FLOAT*numberOflatlon + - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], ltype); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOflatlon); - - for(i=0;i < numberOflatlon; i++) - { - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)latlon[i]); - } - - buffercount += BufferedWriteInteger(&buffer[buffercount], unit); - buffercount += BufferedWriteInteger(&buffer[buffercount], nsegs); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int BufferedWriteLinkPolyLatLon2(LinkSocket *linkSocket, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - double lat[], double lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs) -{ - int i; - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by numberOflatlon, unit, nsegs,ltype*/ - N_BYTES_PER_FLOAT*numberOflatlon + - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], ltype); - buffercount += BufferedWriteInteger(&buffer[buffercount], - numberOflatlon + numberOflatlon); - - for(i=0;i < numberOflatlon; i++) - { - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat[i]); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon[i]); - } - - buffercount += BufferedWriteInteger(&buffer[buffercount], unit); - buffercount += BufferedWriteInteger(&buffer[buffercount], nsegs); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int BufferedWriteLinkPolyXY(LinkSocket *linkSocket, - int numberOfXY, int XY[], - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval,i; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - N_BYTES_PER_INTEGER + /*byts used by numberOfXY*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by numberofxy and coordmode*/ - numberOfXY*N_BYTES_PER_INTEGER + /*bytes used by xy points*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfXY); - for(i=0;i < numberOfXY; i++) - { - buffercount += BufferedWriteInteger(&buffer[buffercount], XY[i]); - } - - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int BufferedWriteLinkPolyXY2(LinkSocket *linkSocket, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], /* These 2 arrays are of equal size*/ - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval,i; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - N_BYTES_PER_INTEGER + /*byts used by numberOfXY*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by numberofxy and coordmode*/ - numberOfXY*N_BYTES_PER_INTEGER + /*bytes used by xy points*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfXY + numberOfXY); - - for(i=0;i < numberOfXY; i++) - { - buffercount += BufferedWriteInteger(&buffer[buffercount], X[i]); - buffercount += BufferedWriteInteger(&buffer[buffercount], Y[i]); - } - - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int BufferedWriteLinkPolyOffset(LinkSocket *linkSocket, - double lat, double lon, - int numberOfXY, int XY[], int CoordMode, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval,i; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by numberofxy and coordmode*/ - numberOfXY*N_BYTES_PER_INTEGER + /*bytes used by xy points*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount], lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfXY); - - for(i=0;i < numberOfXY; i++) - { - buffercount += BufferedWriteInteger(&buffer[buffercount], XY[i]); - } - - buffercount += BufferedWriteInteger(&buffer[buffercount], CoordMode); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int BufferedWriteLinkPolyOffset2(LinkSocket *linkSocket, - double lat, double lon, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], - int CoordMode, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval,i; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lPOLY_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by numberofxy and coordmode*/ - numberOfXY*N_BYTES_PER_INTEGER + /*bytes used by xy points*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteLinkPolyHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount], lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], numberOfXY + numberOfXY); - - for(i=0;i < numberOfXY; i++) - { - buffercount += BufferedWriteInteger(&buffer[buffercount], X[i]); - buffercount += BufferedWriteInteger(&buffer[buffercount], Y[i]); - } - - buffercount += BufferedWriteInteger(&buffer[buffercount], CoordMode); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - diff --git a/src/core/src/main/c/cserver/link/LinkRaster.c b/src/core/src/main/c/cserver/link/LinkRaster.c deleted file mode 100644 index 3bcfedfeb..000000000 --- a/src/core/src/main/c/cserver/link/LinkRaster.c +++ /dev/null @@ -1,663 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkRaster.c,v $ - * $RCSfile: LinkRaster.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkRaster.h" -#include "LinkSocket.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -#define DEBUG_ME "LINKSERVER" -#include -DebugVariable(LINKGRAPHICS, "LINKGRAPHICS", 0x02); /* setenv LINKSERVER "LINKGRAPHICS"*/ - -int WriteLinkRasterHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, RASTER_HEADER, - lRASTER_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_RASTER); - return check; -} - -int BufferedWriteLinkRasterHeader(char *toBuffer) -{ - int byteswritten = 0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - RASTER_HEADER, - lRASTER_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_RASTER); - return byteswritten; -} - - -/*Direct Images*/ -int WriteLinkRasterDirectLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, IMAGE_DIRECT_COLOR_MODEL); - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteDirectImage(linkSocket, directimage); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterDirectLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - - int buffercount; - char* buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfpixel(an integer) in directimage.*/ - directimage->numberOfPixels*N_BYTES_PER_INTEGER + - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if(NULL == buffer) - return -1; /* Memory allocation error */ - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_DIRECT_COLOR_MODEL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteDirectImage(&buffer[buffercount], directimage); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - - -int WriteLinkRasterDirectXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, IMAGE_DIRECT_COLOR_MODEL); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteDirectImage(linkSocket, directimage); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterDirectXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfpixel(an integer) in directimage.*/ - directimage->numberOfPixels*N_BYTES_PER_INTEGER + - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_DIRECT_COLOR_MODEL); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteDirectImage(&buffer[buffercount], directimage); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - -int WriteLinkRasterDirectOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - int check = OK; - - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteInteger(linkSocket, IMAGE_DIRECT_COLOR_MODEL); - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteDirectImage(linkSocket, directimage); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterDirectOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - N_BYTES_PER_INTEGER + /*Bytes used by numberOfpixel(an integer) in directimage.*/ - directimage->numberOfPixels*N_BYTES_PER_INTEGER + - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_DIRECT_COLOR_MODEL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteDirectImage(&buffer[buffercount], directimage); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - -/*----------------------------------------------------------*/ -/*Indexed Images*/ - -int WriteLinkRasterIndexedLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, IMAGE_INDEX_COLOR_MODEL); - - if (Debug(LINKGRAPHICS)) printf("LinkRaster: Writing indexed raster.\n\ -lat = %f\nlon = %f\n\ -width = %d\nheight = %d\nnumber of colors = %d\nnumber of pixels = %d\n", - lat, lon, width, height, - indexedimage->colorTableSize, - indexedimage->numberOfPixels); - - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteIndexedImage(linkSocket, indexedimage); - check = check || WriteInteger(linkSocket, transparency); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int BufferedWriteLinkRasterIndexedLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by width and height*/ - GetIndexedImageSize(indexedimage) + - N_BYTES_PER_INTEGER + /*transparency */ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if(NULL == buffer) - return -1; /* Memory allocation error */ - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_INDEX_COLOR_MODEL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteIndexedImage(&buffer[buffercount], indexedimage); - buffercount += BufferedWriteInteger(&buffer[buffercount], transparency); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - -int WriteLinkRasterIndexedXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, IMAGE_INDEX_COLOR_MODEL); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteIndexedImage(linkSocket, indexedimage); - check = check || WriteInteger(linkSocket, transparency); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterIndexedXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - GetIndexedImageSize(indexedimage) + - N_BYTES_PER_INTEGER + /*transparency */ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_INDEX_COLOR_MODEL); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteIndexedImage(&buffer[buffercount], indexedimage); - buffercount += BufferedWriteInteger(&buffer[buffercount], transparency); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - -int WriteLinkRasterIndexedOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteInteger(linkSocket, IMAGE_INDEX_COLOR_MODEL); - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, width); - check = check || WriteInteger(linkSocket, height); - check = check || WriteIndexedImage(linkSocket, indexedimage); - check = check || WriteInteger(linkSocket, transparency); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterIndexedOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indexedimage, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by x,y,width and height*/ - GetIndexedImageSize(indexedimage) + - N_BYTES_PER_INTEGER + /*transparency */ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_INDEX_COLOR_MODEL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], width); - buffercount += BufferedWriteInteger(&buffer[buffercount], height); - buffercount += BufferedWriteIndexedImage(&buffer[buffercount], indexedimage); - buffercount += BufferedWriteInteger(&buffer[buffercount], transparency); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} -/*-----------------------------------------------------------*/ - -/*UR: Images*/ - -int WriteLinkRasterImageURLLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *url, - LinkArgs *linkArgs) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, IMAGE_URL); - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterImageURLLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *url, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (retval == -1) - return -1; /* Memory allocation error */ - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by lat and lon*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_URL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int WriteLinkRasterImageURLXY(LinkSocket *linkSocket, - int x, int y, - char *url, - LinkArgs *linkArgs) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (check == -1) - return -1; /* Memory allocation error. */ - - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, IMAGE_URL); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterImageURLXY(LinkSocket *linkSocket, - int x, int y, - char *url, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (retval == -1) - return -1; /* Memory allocation error */ - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by x,y*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(sizeof(buffercount)); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_URL); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - -int WriteLinkRasterImageURLOffset(LinkSocket *linkSocket, - double lat, double lon, - int x , int y , - char *url, - LinkArgs *linkArgs) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || WriteLinkRasterHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteInteger(linkSocket, IMAGE_URL); - - check = check || WriteFloat(linkSocket, (float)lat); - check = check || WriteFloat(linkSocket, (float)lon); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteLinkRasterImageURLOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - char *url, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKRASTERIMAGEURL, url, 0, 0); - if (retval == -1) - return -1; /* Memory allocation error */ - - buffercount = lRASTER_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /* Bytes used by RENDERTYPE indentifier. It is an integer*/ - N_BYTES_PER_INTEGER + /*Bytes used bu Image format indentifier. It is an Integer*/ - 2*N_BYTES_PER_INTEGER + /*bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by x,y*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if(NULL == buffer) - return -1; /* Memory allocation error */ - - buffercount = 0; - - buffercount += BufferedWriteLinkRasterHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteInteger(&buffer[buffercount], IMAGE_URL); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount], (float)lon); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - - - - - diff --git a/src/core/src/main/c/cserver/link/LinkRectangle.c b/src/core/src/main/c/cserver/link/LinkRectangle.c deleted file mode 100644 index 3586cf0f8..000000000 --- a/src/core/src/main/c/cserver/link/LinkRectangle.c +++ /dev/null @@ -1,234 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkRectangle.c,v $ - * $RCSfile: LinkRectangle.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkRectangle.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" - -int WriteRectangleHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, RECTANGLE_HEADER, - lRECTANGLE_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_RECTANGLE); - return check; -} - -int WriteLinkRectangleLatLon(LinkSocket *linkSocket, int ltype, - double NWlat, double NWlon, /*NW = North West*/ - double SElat, double SElon, /*SE = South East*/ - int nsegs, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteRectangleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteInteger(linkSocket, ltype); - check = check || WriteFloat(linkSocket,(float)NWlat); - check = check || WriteFloat(linkSocket,(float)NWlon); - check = check || WriteFloat(linkSocket,(float)SElat); - check = check || WriteFloat(linkSocket,(float)SElon); - check = check || WriteInteger(linkSocket, nsegs); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkRectangleXY(LinkSocket *linkSocket, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteRectangleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, ulx); - check = check || WriteInteger(linkSocket, uly); - check = check || WriteInteger(linkSocket, lrx); - check = check || WriteInteger(linkSocket, lry); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkRectangleOffset(LinkSocket *linkSocket, - double lat, double lon, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs) -{ - int check = OK; - check = check || WriteRectangleHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, ulx); - check = check || WriteInteger(linkSocket, uly); - check = check || WriteInteger(linkSocket, lrx); - check = check || WriteInteger(linkSocket, lry); - check = check || WriteLinkArgs(linkSocket, linkArgs); - - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteRectangleHeader(char *toBuffer) -{ - int byteswritten = 0; - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - RECTANGLE_HEADER, - lRECTANGLE_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], - GRAPHICTYPE_RECTANGLE); - return byteswritten; -} - - -int BufferedWriteLinkRectangleLatLon(LinkSocket *linkSocket, int ltype, - double NWlat, double NWlon, /*NW = North West*/ - double SElat, double SElon, /*SE = South East*/ - int nsegs, - LinkArgs *linkArgs) -{ - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lRECTANGLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 2*N_BYTES_PER_INTEGER + /*Bytes used by ltype and nsegs*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteRectangleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteInteger(&buffer[buffercount], ltype); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)NWlat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)NWlon); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)SElat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)SElon); - buffercount += BufferedWriteInteger(&buffer[buffercount], nsegs); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkRectangleXY(LinkSocket *linkSocket, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lRECTANGLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by bounding co-ordinates of rectangle*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteRectangleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], ulx); - buffercount += BufferedWriteInteger(&buffer[buffercount], uly); - buffercount += BufferedWriteInteger(&buffer[buffercount], lrx); - buffercount += BufferedWriteInteger(&buffer[buffercount], lry); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkRectangleOffset(LinkSocket *linkSocket, - double lat, double lon, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs) -{ - - int buffercount; - char *buffer; - int retval; - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lRECTANGLE_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 4*N_BYTES_PER_INTEGER + /*Bytes used by bounding co-ordinates of rectangle*/ - LinkSizeOfLinkArgs(linkArgs); - - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteRectangleHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], ulx); - buffercount += BufferedWriteInteger(&buffer[buffercount], uly); - buffercount += BufferedWriteInteger(&buffer[buffercount], lrx); - buffercount += BufferedWriteInteger(&buffer[buffercount], lry); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer,buffercount); - free(buffer); - return retval; -} diff --git a/src/core/src/main/c/cserver/link/LinkSemantics.c b/src/core/src/main/c/cserver/link/LinkSemantics.c deleted file mode 100644 index ed8bee241..000000000 --- a/src/core/src/main/c/cserver/link/LinkSemantics.c +++ /dev/null @@ -1,83 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkSemantics.c,v $ - * $RCSfile: LinkSemantics.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include "LinkSemantics.h" -#include "LinkSocket.h" -#include "GlobalConstants.h" - -#define DEBUG_ME "LINKSERVER" -#include -DebugVariable(LINKGRAPHICS, "LINKGRAPHICS", 0x02); /* setenv LINKSERVER "LINKGRAPHICS"*/ - -void InitLinkSemantics(LinkSemantics *linksemantics) -{ - linksemantics->linecolor = COLORBLACK; - linksemantics->highlightcolor = COLORBLACK; - linksemantics->fillcolor =(int) 0x00000000; - linksemantics->linewidth = DEFAULT_LINE_WIDTH; -} - -void SetSemanticsLineColor(LinkSemantics *linksemantics, int linecolor) -{ - linksemantics->linecolor = linecolor; -} - -void SetSemanticsHighlightColor(LinkSemantics *linksemantics, int highlightcolor) -{ - linksemantics->highlightcolor = highlightcolor; -} - -void SetSemanticsFillColorLink(LinkSemantics *linksemantics, int fillColor) -{ - linksemantics->fillcolor = fillColor; -} - -void SetSemanticsLineWidth(LinkSemantics *linksemantics, int linewidth) -{ - linksemantics->linewidth = linewidth; -} - -int WriteLinkSemantics(LinkSocket *linkSocket, LinkSemantics *semantics) -{ - int check = OK; - check = check || WriteInteger(linkSocket, semantics->linecolor); - check = check || WriteInteger(linkSocket, semantics->highlightcolor); - check = check || WriteInteger(linkSocket, semantics->fillcolor); - check = check || WriteInteger(linkSocket, semantics->linewidth); - - if (Debug(LINKGRAPHICS)) printf("LinkSemantics: Writing:\nline color = %lx\n\ -hightlight color = %lx\nfillcolor = %lx\nlinewidth = %d\n", - semantics->linecolor, semantics->highlightcolor, - semantics->fillcolor, semantics->linewidth); - return check; -} - -int BufferedWriteLinkSemantics(char *toBuffer, LinkSemantics *semantics) -{ - int byteswritten = 0; - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], semantics->linecolor); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], semantics->highlightcolor); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], semantics->fillcolor); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], semantics->linewidth); - return byteswritten; -} diff --git a/src/core/src/main/c/cserver/link/LinkServer.c b/src/core/src/main/c/cserver/link/LinkServer.c deleted file mode 100644 index 3c7e457e9..000000000 --- a/src/core/src/main/c/cserver/link/LinkServer.c +++ /dev/null @@ -1,409 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkServer.c,v $ - * $RCSfile: LinkServer.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "Link.h" -#include "LinkSocket.h" -#include "MapRequest.h" -#include "Request.h" -#include "LinkLine.h" -#include "LinkRaster.h" -#include "GlobalConstants.h" -#include "LinkImage.h" -#include "LinkText.h" -#include "LinkRectangle.h" -#include "LinkPoint.h" -#include "LinkPoly.h" -#include "LinkCircle.h" -#include "LinkBitmap.h" -#include "LinkArgs.h" -#include "ActionRequest.h" -#include "Response.h" -#include - -/* - Test Server -*/ - -/*for debugging*/ -#define DEBUG_ME "LINKSERVER" -#include -DebugVariable(LINK, "LINK", 0x01); /* setenv LINKSERVER "LINK"*/ - -/* You should set this to 1 if you want the client to go - 'interactive'. This server doesn't maintain a list of objects that - it sends across to the client, so interactivity is overrated in - this example. You could receved the action events, though, and - change graphics, move them, provide information about them, etc. */ -#define CLIENT_NOTIFICATION_SENT 0 - -void HandleClient(Link *link); -void HandleMapRequest(Link* link); -void HandleActionRequest(Link* link); -void SendActionPreferences(Link* link); -void SendTestRaster(Link *link, LinkArgs*); -void SendTestLine(Link *link, LinkArgs*); -void SendTestText(Link *link, LinkArgs*); -void SendTestPoly(Link *link, LinkArgs*); -int MIN_ARGS_REQ = 2; - -int main(int argc, char **argv) -{ - Link *link; - LinkSocket *parentSocket; - - if(argc < MIN_ARGS_REQ) - { - printf("usage: filename port_number\n"); - exit(1); - } - - parentSocket = (LinkSocket*) malloc(sizeof(LinkSocket)); - parentSocket->port = atoi(argv[1]); - - if (Debug(LINK)) printf("LinkServerStarter\n"); - - if (Debug(LINK)) printf("Creating socket\n"); - InitSocket(parentSocket); - parentSocket->isBuffered = LINK_FALSE; - while (1) - { - LinkSocket *childSocket = (LinkSocket*) malloc(sizeof(LinkSocket)); - SocketCopyParentToChild(parentSocket,childSocket); - - if (Debug(LINK)) printf("accepting socket\n"); - accept_socket(parentSocket->mainsd, &(childSocket->sd)); - - /*if(0 == (forkresult = fork()))*/ - { - printf("\nChild process\n"); - link = (Link *) malloc(sizeof(Link)); - link->mapRequest = NULL; - link->actionRequest = NULL; - link->socket = childSocket; - - HandleClient(link); - } - /*waitpid(-1, - NULL, - WNOHANG);*/ - } -} - -void HandleClient(Link* link) -{ - - if(CLIENT_NOTIFICATION_SENT) - SendActionPreferences(link); - - while(1) - { - - if (Debug(LINK)) printf("Reading and parsing\n"); - if (ReadAndParseLink(link) == HEADERERROR){ - break; - } - if (link->mapRequest != NULL){ - - HandleMapRequest(link); - } - if(link->actionRequest != NULL) - { - printf("Handling Acton Request\n"); - HandleActionRequest(link); - } - } - printf("Child finished processing\nexiting\n"); - close_socket(link->socket->sd); - FreeLink(link); - free(link); - exit(0); -} - -void SendActionPreferences(Link* link) -{ - Descriptor *descriptor; - int des = 0; - printf("des before %x\n",des); - descriptor = (Descriptor *)&des; - - /* Just list the types of events that should be reacted upon. */ - descriptor->MOUSE_CLICK = 1; - descriptor->MOUSE_PRESSED = 1; - descriptor->MOUSE_RELEASED = 1; - descriptor->MOUSE_MOVE = 0; - descriptor->MOUSE_ENTER = 1; - descriptor->MOUSE_EXIT = 1; - descriptor->MOUSE_DRAGGED = 1; - descriptor->KEY_PRESSED = 1; - descriptor->KEY_RELEASED = 1; - - /* This just says that the client should note mouse events. Some - clients know how to handle things internally. */ - descriptor->CLIENT_NOTIFICATION = 1; - - /* You would set this if you want the server to be notified of - events. Setting this variable will cause the client to sent - action events to the server.*/ - /* descriptor->SERVER_NOTIFICATION = 1; */ - - printf("des after %x\n",des); - - /* This screws things up, the header for this section is written - in SendServerInterest. */ -/* WriteActionResponseHeader(link->socket, CreateLinkArgs()); */ - - SendServerInterest(link->socket, descriptor); - EndSection(link->socket); -} - - -void HandleActionRequest(Link* link) -{ - char *msg = "Wow this is working"; - - LinkArgs *args = CreateLinkArgs(); - SetKeyValuePairInLinkArgs(args, LPC_INFO, msg, 0, 0); - - WriteActionResponseHeader(link->socket, args); - - printf("writing infoline %s\n", msg); - - EndTotal(link->socket); - free(args); -} - -void HandleMapRequest(Link* link) -{ - char *result; - LinkArgs *la, *args; - MapRequest *map; - - map = link->mapRequest; - la = &(map->linkargs); - result = GetValueForKey(la, "datatype"); - - args = CreateLinkArgs(); - - if (result != NULL){ - printf("Found value for datatype => %s\n", result); - } else printf("No value found for datatype key.\n"); - - WriteMapResponseHeader(link->socket, args); - - if (Debug(LINK)) printf("Writing graphics\n"); - - SendTestLine(link,args); - SendTestPoly(link,args); - SendTestCircle(link,args); - SendTestRectangle(link,args); - - SendTestText(link, args); - /* SendTestRaster(link, args);*/ - - EndTotal(link->socket); - - FreeMapRequest(link->mapRequest); - free(link->mapRequest); - link->mapRequest = NULL; - FreeLinkArgs(args); /* Reduce memory leakage. */ - free(args); -} - -void SendTestText(Link *link, LinkArgs *args) -{ - char *text = "this is just a test"; - double lat = 20.0, lon = 10.0; - - WriteLinkTextLatLon(link->socket, lat, lon, text, "", JUSTIFY_LEFT, args, 0, 0); - WriteLinkTextXY(link->socket, (int)lat, (int)lon, text, "", JUSTIFY_LEFT, args, 0, 0); - WriteLinkTextOffset(link->socket, lat, lon, (int)lat, (int)lon, - text,"", JUSTIFY_LEFT, args, 0, 0); - -/* BufferedWriteLinkTextLatLon(link->socket, lat, lon, */ -/* text, "", JUSTIFY_LEFT, args); */ -/* BufferedWriteLinkTextXY(link->socket, (int)lat, (int)lon, */ -/* text, "", JUSTIFY_LEFT,args); */ -/* BufferedWriteLinkTextOffset(link->socket, lat, lon, (int)lat, (int)lon, */ -/* text, "", JUSTIFY_LEFT, args); */ -} - -void SendTestRectangle(Link *link, LinkArgs *args) -{ - double nwlat = 50.0, nwlon = -50.0, selat = -50.0, selon = 50.0; - int ulx = 128, uly = 137, lrx = 294, lry = 248; - - WriteLinkRectangleLatLon(link->socket,LGREATCIRCLE,nwlat,nwlon,selat, - selon,-1,args); - WriteLinkRectangleXY(link->socket,ulx,uly,lrx,lry,args); - WriteLinkRectangleOffset(link->socket,nwlat,nwlon,ulx,uly,lrx,lry,args); - -/* BufferedWriteLinkRectangleLatLon(link->socket,LGREATCIRCLE, */ -/* nwlat,nwlon,selat,selon,-1,args); */ -/* BufferedWriteLinkRectangleXY(link->socket,ulx,uly,lrx,lry,args); */ -/* BufferedWriteLinkRectangleOffset(link->socket,nwlat,nwlon, */ -/* ulx,uly,lrx,lry,args); */ -} - -void SendTestCircle(Link *link, LinkArgs *args) -{ - double center_lat = 0.0,center_lon = 0.0 ,radius = 10.0; - int x = 100, y = 100, w = 100, h = 200; - - WriteLinkCircleLatLon(link->socket,center_lat,center_lon,radius, - CIRCLE_DECIMAL_DEGREES,-1,args); - WriteLinkCircleXY(link->socket,x,y,w,h,args); - WriteLinkCircleOffset(link->socket,center_lat,center_lon,x,y,w,h,args); - -/* BufferedWriteLinkCircleLatLon(link->socket,center_lat,center_lon,radius, */ -/* CIRCLE_DECIMAL_DEGREES,-1,args); */ -/* BufferedWriteLinkCircleXY(link->socket,x,y,w,h,args); */ -/* BufferedWriteLinkCircleOffset(link->socket,center_lat,center_lon,x,y,w,h,args); */ - -} - -void SendTestPoly(Link *link, LinkArgs *args) -{ - int nlatlon = 6; - double latlon[6], lat[3],lon[3]; - int XY[6],X[3],Y[3]; - - lat[0] = latlon[0] = 10.0; - lon[0] = latlon[1] = 20.0; - lat[1] = latlon[2] = 50.0; - lon[1] = latlon[3] = 50.0; - lat[2] = latlon[4] = 70.0; - lon[2] = latlon[5] = 150.0; - - X[0] = XY[0] = 10; - Y[0] = XY[1] = 30; - X[1] = XY[2] = 60; - Y[1] = XY[3] = 100; - X[2] = XY[4] = 145; - Y[2] = XY[5] = 225; - - WriteLinkPolyLatLon(link->socket,LGREATCIRCLE, nlatlon, latlon, - DECIMAL_DEGREES,-1,args); - WriteLinkPolyXY(link->socket,nlatlon, XY ,args); - WriteLinkPolyOffset(link->socket,10.0,10.0,nlatlon, XY , - COORDMODE_ORIGIN,args); - -/* BufferedWriteLinkPolyLatLon(link->socket,LGREATCIRCLE, */ -/* nlatlon, latlon,DECIMAL_DEGREES,-1,args); */ -/* BufferedWriteLinkPolyXY(link->socket,nlatlon, XY ,args); */ -/* BufferedWriteLinkPolyOffset(link->socket,10.0,10.0,nlatlon, */ -/* XY ,COORDMODE_ORIGIN,args); */ - - WriteLinkPolyLatLon2D(link->socket,LGREATCIRCLE, nlatlon/2, - lat, lon,DECIMAL_DEGREES,-1,args); - WriteLinkPolyXY2(link->socket,nlatlon/2, X, Y ,args); - WriteLinkPolyOffset2(link->socket,10.0,10.0,nlatlon/2, - X, Y ,COORDMODE_ORIGIN,args); - -/* BufferedWriteLinkPolyLatLon2(link->socket,LGREATCIRCLE, */ -/* nlatlon/2, lat, lon,DECIMAL_DEGREES,-1,args); */ -/* BufferedWriteLinkPolyXY2(link->socket,nlatlon/2, X, Y ,args); */ -/* BufferedWriteLinkPolyOffset2(link->socket,10.0,10.0,nlatlon/2, */ -/* X, Y ,COORDMODE_ORIGIN,args); */ -} - -void SendTestLine(Link *link, LinkArgs *args) -{ - WriteLinkLineXY(link->socket,0,0,100,100, args); - WriteLinkLineLatLon(link->socket, 50, -60, 40, -80, - LSTRAIGHT,-1, args); - WriteLinkLineOffset(link->socket,30,20,50,75,200,150, args); -} - -void SendTestRaster(Link *link, LinkArgs *args) -{ - DirectImage *directimage; - IndexedImage *indexedimage; - double lat,lon; - int w,h; - int i; - int colortablesize = 256, trans = 100; - lat = 40.0; - lon = 70.0; - w = 40; h = 100; - - - /* allocate memory and create a raster*/ - directimage = (DirectImage*) malloc(sizeof(DirectImage)); - directimage->numberOfPixels = w*h; - directimage->image = (int *)malloc(sizeof(int)*w*h); - for(i=0;iimage[i] = rand(); - } - - indexedimage = (IndexedImage *)malloc(sizeof(IndexedImage)); - indexedimage->numberOfPixels = w*h; - indexedimage->image = (char *)malloc(w*h); - - for(i=0;iimage[i] = (char)(rand() % 256); - } - indexedimage->colorTableSize = colortablesize; - indexedimage->colorTable = (int *)malloc(sizeof(int)*colortablesize); - - for(i=0;icolorTable[i] = rand(); - } - - WriteLinkRasterDirectLatLon(link->socket, lat, lon, w, h, - directimage, args); - WriteLinkRasterDirectXY(link->socket, (int)lat, (int)lon, w, h, - directimage, args); - WriteLinkRasterDirectOffset(link->socket, lat, lon, lat, lon, w, h, - directimage, args); - - WriteLinkRasterIndexedLatLon(link->socket, lat, lon, w, h, trans, - indexedimage, args); - WriteLinkRasterIndexedXY(link->socket,(int)lat, (int)lon, w, h, trans, - indexedimage, args); - WriteLinkRasterIndexedOffset(link->socket, lat, lon, - lat, lon, w, h,trans, indexedimage, args); - -/* WriteLinkBitmapLatLon(link->socket,lat,lon,w,h, */ -/* indexedimage->numberOfPixels, */ -/* indexedimage->image, */ -/* args); */ - -/* WriteLinkBitmapXY(link->socket,(int)lat,(int)lon,w,h, */ -/* indexedimage->numberOfPixels, */ -/* indexedimage->image, */ -/* args); */ - -/* WriteLinkBitmapOffset(link->socket,lat,lon,(int)lat,(int)lon,w,h, */ -/* indexedimage->numberOfPixels, */ -/* indexedimage->image, */ -/* args); */ - - free(indexedimage->image); - free(indexedimage->colorTable); - free(indexedimage); - free(directimage->image); - free(directimage); -} diff --git a/src/core/src/main/c/cserver/link/LinkSocket.c b/src/core/src/main/c/cserver/link/LinkSocket.c deleted file mode 100644 index 28fc33fb0..000000000 --- a/src/core/src/main/c/cserver/link/LinkSocket.c +++ /dev/null @@ -1,554 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkSocket.c,v $ - * $RCSfile: LinkSocket.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkSocket.h" -#include "GlobalConstants.h" - -#define DEBUG_ME "LINKSERVER" -#include - -DebugVariable(LINK,"LINK",0x01); -DebugVariable(LINKSOCKET,"LINKSOCKET",0x04); -/* - flushes the socket's writebuffer. - returns OK if it successfully wrote the entire buffer to socket, - NOK otherwise. -*/ -int Socketflush(LinkSocket *socket){ - - if(socket->currentbuffer > 0){ - int nbyteswritten; - int nbytestowrite = socket->currentbuffer; - if (Debug(LINKSOCKET)) - printf("flushing socket writing %d bytes \n", nbytestowrite); - - nbyteswritten = socket_send(socket->sd, socket->writebuffer, nbytestowrite); - - if(nbytestowrite == nbyteswritten){ - socket->currentbuffer = 0; - } else { - socket->error = LINK_TRUE; - return NOK; - } - } - socket->error = LINK_FALSE; - return OK; -} - -/* - copies all from parent to child except sd, since it is new for every child. - */ -int SocketCopyParentToChild(LinkSocket *parent, LinkSocket *child){ - - child->host = parent->host; - child->mainsd = parent->mainsd; - child->port = parent->port; - child->error = LINK_FALSE; - child->maxbuffer = MAX_SOCKET_BUFFER_SIZE; - child->writebuffer = (char *)malloc(child->maxbuffer); - if (child->writebuffer == NULL) - return -1; /* Memory allocation error. */ - child->currentbuffer = 0; - child->isBuffered = parent->isBuffered; - return OK; -} - -int InitSocket(LinkSocket *socket){ - - set_socket_domain(AF_INET); - socket->host = NULL; /*Keep it Null for the time being*/ - if(-1 == open_socket_port(&socket->mainsd, socket->port, NULL, SERVER)) - { - socket->error = LINK_TRUE; - return NOK; - } - socket->error = LINK_FALSE; - socket->currentbuffer = 0; - socket->maxbuffer = MAX_SOCKET_BUFFER_SIZE; - socket->isBuffered = LINK_TRUE; - socket->writebuffer = (char *)malloc(socket->maxbuffer); - if (socket->writebuffer == NULL) - return -1; /* Memory allocation error */ - return OK; -} - -void FreeSocket(LinkSocket *socket){ - if(NULL != socket->host) - free(socket->host); - socket->host = NULL; - - if(NULL != socket->writebuffer) - free(socket->writebuffer); - socket->writebuffer = NULL; -} - -/*Checks if the error flag is set return OK or NOK*/ -int CheckSocket(LinkSocket* socket){ - if (socket->error){ - if (Debug(LINK)) printf("LinkSocket: problem with link socket...\n"); - } - return (socket->error); -} - -/* - returns NOK if datasize is more than maxbuffer and flushes the socket. - returns OK if datasize + socket->currentbuffer is less than maxbuffer - Flushes the buffer and returns OK, - if socket->currentbuffer + datasize(obviously < maxbuffer) is greater than maxbuffer -*/ -/*Used internally by WriteInteger etc*/ -static int WriteToBuffer(LinkSocket *socket, int datasize){ - if(datasize > socket->maxbuffer){ - Socketflush(socket); - return NOK; - } - - if((datasize + socket->currentbuffer) < socket->maxbuffer){ - return OK; - } else { - return Socketflush(socket); - } -} - -void IntegerToBytes(char *toBuffer, int ivalue){ - toBuffer[0] = (toBuffer[0] & 0x00) | (ivalue >> 24); /*MSB goes first*/ - toBuffer[1] = (toBuffer[1] & 0x00) | (ivalue >> 16); - toBuffer[2] = (toBuffer[2] & 0x00) | (ivalue >> 8); - toBuffer[3] = (toBuffer[3] & 0x00) | (ivalue); /*LSB goes last*/ -} - -void BytesToInteger(int *ptrIntegerBuffer, char *fromBuffer) -{ - *ptrIntegerBuffer = 0; - *ptrIntegerBuffer = ((fromBuffer[0] & 0xFF) << 24) | ((fromBuffer[1] & 0xFF) << 16 ) | - ((fromBuffer[2] & 0xFF) << 8) | ((fromBuffer[3] & 0xFF)); -} -/* - Read an integer value in to provided buffer -*/ -int ReadInteger(LinkSocket *socket, int *ptrIntegerBuffer){ - - char intbuff[N_BYTES_PER_INTEGER]; /*Read integer in buffer*/ - int bytesRead; - - /*socket_receive takes void* as 2nd paramater and its ok to pass a char* */ - bytesRead = socket_receive(socket->sd, intbuff, N_BYTES_PER_INTEGER); - - if(N_BYTES_PER_INTEGER == bytesRead) - { - /* All right, we got it*/ - BytesToInteger(ptrIntegerBuffer,intbuff); - - socket->error = LINK_FALSE; - return OK; - } - /* Oops..some error while receiving*/ - socket->error = LINK_TRUE; - return NOK; -} - -int WriteInteger(LinkSocket *socket, int iValue){ - char intbuff[N_BYTES_PER_INTEGER]; - int nbyteswritten; - - if(socket->isBuffered == LINK_TRUE && OK == WriteToBuffer(socket, N_BYTES_PER_INTEGER)){ - nbyteswritten = BufferedWriteInteger(&(socket->writebuffer[socket->currentbuffer]), - iValue); - socket->currentbuffer += nbyteswritten; - } else { - IntegerToBytes(intbuff,iValue); - nbyteswritten = socket_send(socket->sd, intbuff, N_BYTES_PER_INTEGER); - } - - if(N_BYTES_PER_INTEGER == nbyteswritten){ - socket->error = LINK_FALSE; - return OK; - } - - socket->error = LINK_TRUE; - return NOK; -} - -int BufferedWriteInteger(char *toBuffer, int iValue){ - IntegerToBytes(toBuffer, iValue); - return N_BYTES_PER_INTEGER; -} - -int ReadFloat(LinkSocket *socket, double *ptrDoubleBuffer){ - - char buff[N_BYTES_PER_FLOAT]; /*Read float in this buffer*/ - int bytesRead; - - /*socket_receive takes void* as 2nd paramater and its ok to pass char* */ - bytesRead = socket_receive(socket->sd, buff, N_BYTES_PER_FLOAT); - - if(N_BYTES_PER_FLOAT == bytesRead) - { - /* All right, we got it*/ - - float *f; - int i = 0; - /*do it on integer first. */ - BytesToInteger(&i,buff); - - /*type cast just the pointer*/ - f = (float *)&i; - - /*type cast the float value to double*/ - *ptrDoubleBuffer = (double)*f; - - socket->error = LINK_FALSE; - return OK; - } - /* Oops..some error while receiving*/ - socket->error = LINK_TRUE; - return NOK; -} - - -int WriteFloat(LinkSocket *socket, float fvalue){ - - char buff[N_BYTES_PER_FLOAT]; - int nbyteswritten; - int *iptr; - iptr = (int *)&fvalue; - - if(socket->isBuffered == LINK_TRUE && OK == WriteToBuffer(socket,N_BYTES_PER_FLOAT)){ - nbyteswritten = BufferedWriteFloat(&(socket->writebuffer[socket->currentbuffer]), fvalue); - socket->currentbuffer += nbyteswritten; - } else { - IntegerToBytes(buff, *iptr); - nbyteswritten = socket_send(socket->sd, buff, N_BYTES_PER_FLOAT); - } - - if(N_BYTES_PER_FLOAT == nbyteswritten){ - socket->error = LINK_FALSE; - return OK; - } - - socket->error = LINK_TRUE; - return NOK; -} - -int BufferedWriteFloat(char *toBuffer, float fvalue){ - int *iptr; - iptr = (int *)&fvalue; - IntegerToBytes(toBuffer, *iptr); - return N_BYTES_PER_FLOAT; -} - -int ReadChars(LinkSocket *socket, char buffer[], int nchartoread){ - - int nbytesread; - - nbytesread = socket_receive(socket->sd, buffer, nchartoread); - - if(nchartoread == nbytesread) - { - buffer[nchartoread] = '\0'; - socket->error = LINK_FALSE; - return OK; - } - /*system error. */ - socket->error = LINK_TRUE; - return NOK; -} - -int ReadChar(LinkSocket *socket, char *c){ - return ReadChars(socket, c, 1); -} - -int WriteChars(LinkSocket *socket, char buffer[], int nchartowrite){ - int nbyteswritten; - - if(Debug(LINKSOCKET)) - { - printf("LinkSocket.c WriteChars-- %s %d\n", buffer, nchartowrite); - } - - if (nchartowrite == 0){ - socket->error = LINK_FALSE; - return OK; - } - - if((LINK_TRUE == socket->isBuffered) && (OK == WriteToBuffer(socket, nchartowrite)) ) - { - nbyteswritten = BufferedWriteChars(&(socket->writebuffer[socket->currentbuffer]), - buffer, nchartowrite); - socket->currentbuffer += nbyteswritten; - } - else - nbyteswritten = socket_send(socket->sd, buffer, nchartowrite); - - if(nchartowrite == nbyteswritten) - { - socket->error = LINK_FALSE; - return OK; - } - /*system error */ - socket->error = LINK_TRUE; - return NOK; -} - -int WriteChar(LinkSocket *socket, char *c){ - return WriteChars(socket, c, 1); -} - -int BufferedWriteChars(char *toBuffer, char *fromBuffer, int nchartowrite){ - - memcpy(toBuffer,fromBuffer,nchartowrite); - /* - int i = 0; - while(i < nchartowrite) - { - toBuffer[i] = fromBuffer[i]; - i++; - } - */ - return nchartowrite; -} - -/* - * bmackiew: This function originally translated the Unicode characters - * to ASCII for use by the calling function. Since we deal with stored - * strings in Unicode only, there's no need to do the translation. - */ - -int ReadUnicodeChars(LinkSocket *socket, char *buffer, int nchartoread){ - int ncharread = 0; - int i; - char *inbuffer; - - /* - * ### bmackiew: Make sure we read in the proper number of characters! - */ - - /* bmackiew: The numbers of characters to read was originally multiplied - * by two since strings were stored in ASCII. We've stored them as - * Unicode already, so we know how many characters were needed for - * storage and readback. - */ - -#if 0 - nchartoread = nchartoread*2; -#endif - - inbuffer = (char *)malloc(sizeof(char) * nchartoread); - if (inbuffer == NULL) - return -1; /* Memory allocation error */ - - ncharread = socket_receive(socket->sd, inbuffer, nchartoread); - if(nchartoread == ncharread) - { - /* - * This was originally done by a strcpy(), but that fails with - * English Unicode characters. - */ - - for (i = 0; i < nchartoread; i++) { - buffer[i] = inbuffer[i]; - } - - buffer[ncharread] = '\0'; - free(inbuffer); - socket->error = LINK_FALSE; - return OK; - } - /*error condition */ - free(inbuffer); - socket->error = LINK_TRUE; - return NOK; -} - -/* - * bmackiew: Modified to not use ASCIIToUnicode(), as by the time - * characters are sent here, they are already in Unicode. - */ - -int WriteUnicodeChars(LinkSocket *socket, char buffer[], int nchartowrite){ - int ncharwritten = 0; - /*Internal buffer for holding unicode characters*/ - char *inbuffer; - - if (nchartowrite == 0){ - socket->error = LINK_FALSE; - return OK; - } - - inbuffer = (char *)malloc(nchartowrite); - - if (inbuffer == NULL) - return -1; /* Memory allocation error */ - - if((LINK_TRUE == socket->isBuffered) && (OK == WriteToBuffer(socket, nchartowrite)) ) { - ncharwritten = BufferedWriteUnicodeChars(&(socket->writebuffer[socket->currentbuffer]), - buffer, nchartowrite); - socket->currentbuffer += ncharwritten; - nchartowrite = N_CHARS_PER_UNICODE_CHAR * nchartowrite; - } - else { - ncharwritten = socket_send(socket->sd, buffer, nchartowrite); - } - - if(nchartowrite == ncharwritten){ - /*error condition */ - socket->error = LINK_FALSE; - free(inbuffer); - return OK; - } - - socket->error = LINK_TRUE; - free(inbuffer); - - return NOK; -} - -int BufferedWriteUnicodeChars(char *toBuffer, - char *fromBuffer, - int nchartowrite){ - - return ASCIIToUnicode(fromBuffer,toBuffer, nchartowrite); -} - - -/* - * Converts Unicode characters to _English_ ASCII characters by - * stripping them of their first byte. Note that this is not a - * comprehensive solution for other language stored in ASCII. - * - */ -char *EnglishUnicodeToASCII(char unicodechar[], int len) { - int i, length; - char *cchar; - - cchar = (char *)malloc(length/2); - for( i = 0; i< length/2;i++){ - cchar[i] = unicodechar[i*2 + 1]; - } - return cchar; -} - -/* - * Converts ASCII characters to Unicode Chars by prefixing them with 0x00; - */ - -char *ASCIIToEnglishUnicode(char cchar[]) { - - int i, length; - char *unicodechar; - - length = strlen(cchar); - unicodechar = (char *)malloc(length * 2); - - if(Debug(LINKSOCKET)) - printf("LinkSocket.c::ASCIITOUnicode \n"); - for(i=0;i - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/LinkText.c,v $ - * $RCSfile: LinkText.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "LinkText.h" -#include "Link.h" -#include "GlobalConstants.h" -#include "Response.h" -#include "Request.h" - -int WriteTextHeader(LinkSocket *linkSocket) -{ - int check = OK; - check = check || WriteChars(linkSocket, TEXT_HEADER, lTEXT_HEADER); - check = check || WriteInteger(linkSocket, GRAPHICTYPE_TEXT); - return check; -} - - -int WriteLinkTextLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *String, char *fontAsString, - int justification, - LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, is_unicode, num_unicode_chars); - if (check == -1) - return -1; /* Memory allocation error */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || WriteTextHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_LATLON); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, justification); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkTextXY(LinkSocket *linkSocket, - int x, int y, - char *String, char *fontAsString, - int justification, - LinkArgs *linkArgs, int is_unicode, int num_unicode_chars) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, is_unicode, num_unicode_chars); - if (check == -1) - return -1; /* Memory allocation error */ - - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || WriteTextHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_XY); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, justification); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - - -int WriteLinkTextOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - char *String, char *fontAsString, - int justification, - LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars) -{ - int check = OK; - - /** Add font and string to properties. */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, is_unicode, num_unicode_chars); - if (check == -1) - return -1; /* Memory allocation error */ - check = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || WriteTextHeader(linkSocket); - check = check || WriteInteger(linkSocket, RENDERTYPE_OFFSET); - check = check || WriteFloat(linkSocket,(float)lat); - check = check || WriteFloat(linkSocket,(float)lon); - check = check || WriteInteger(linkSocket, x); - check = check || WriteInteger(linkSocket, y); - check = check || WriteInteger(linkSocket, justification); - check = check || WriteLinkArgs(linkSocket, linkArgs); - return check; - /* Returns -1 if there was a memory allocation error in WriteLinkArgs() */ -} - -int BufferedWriteTextHeader(char *toBuffer) -{ - int byteswritten = 0; - - byteswritten += BufferedWriteChars(&toBuffer[byteswritten], - TEXT_HEADER, lTEXT_HEADER); - byteswritten += BufferedWriteInteger(&toBuffer[byteswritten], GRAPHICTYPE_TEXT); - return byteswritten; -} - - -int BufferedWriteLinkTextLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *String, char *fontAsString, - int justification, - LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, - is_unicode, num_unicode_chars); - if (retval == -1) - return -1; /* Memory allocation error */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (retval == -1) - return -1; /* Memory allocation error */ - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lTEXT_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - N_BYTES_PER_INTEGER + /*Bytes used by justification*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteTextHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_LATLON); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], justification); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkTextXY(LinkSocket *linkSocket, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, - int is_unicode, int num_unicode_chars) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, - is_unicode, num_unicode_chars); - if (retval == -1) - return -1; /* Memory allocation error */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (retval == -1) - return -1; /* Memory allocation error */ - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lTEXT_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 3*N_BYTES_PER_INTEGER + /*Bytes used by x,y,justification*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteTextHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_XY); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], justification); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} - - -int BufferedWriteLinkTextOffset(LinkSocket *linkSocket, - double lat, double lon, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, - int is_unicode, int num_unicode_chars) -{ - int buffercount; - char *buffer; - int retval; - - /** Add font and string to properties. */ - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTSTRING, String, is_unicode, num_unicode_chars); - if (retval == -1) - return -1; /* Memory allocation error */ - - retval = SetKeyValuePairInLinkArgs(linkArgs, LPC_LINKTEXTFONT, fontAsString, 0, 0); - if (retval == -1) - return -1; /*Memory allocation error */ - - /* - buffercount corresponds to data being written in bytes below. - */ - buffercount = lTEXT_HEADER + /* Bytes used by Header*/ - N_BYTES_PER_INTEGER + /*Bytes used by GRAPHIC_TYPE. It is an Integer*/ - N_BYTES_PER_INTEGER + /*Bytes used by RENDERTYPE identifier*/ - 2*N_BYTES_PER_FLOAT + /*Bytes used by lat and lon*/ - 3*N_BYTES_PER_INTEGER + /*Bytes used by x,y,justification*/ - LinkSizeOfLinkArgs(linkArgs); - - buffer = (char *)malloc(buffercount); - if (buffer == NULL) - return -1; /* Memory allocation error */ - - buffercount=0; - - buffercount += BufferedWriteTextHeader(&buffer[buffercount]); - buffercount += BufferedWriteInteger(&buffer[buffercount], RENDERTYPE_OFFSET); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lat); - buffercount += BufferedWriteFloat(&buffer[buffercount],(float)lon); - buffercount += BufferedWriteInteger(&buffer[buffercount], x); - buffercount += BufferedWriteInteger(&buffer[buffercount], y); - buffercount += BufferedWriteInteger(&buffer[buffercount], justification); - buffercount += BufferedWriteLinkArgs(&buffer[buffercount], linkArgs); - - retval = WriteChars(linkSocket, buffer, buffercount); - free(buffer); - return retval; -} diff --git a/src/core/src/main/c/cserver/link/MapRequest.c b/src/core/src/main/c/cserver/link/MapRequest.c deleted file mode 100644 index 8771a0c4d..000000000 --- a/src/core/src/main/c/cserver/link/MapRequest.c +++ /dev/null @@ -1,75 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/MapRequest.c,v $ - * $RCSfile: MapRequest.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "MapRequest.h" -#include "Link.h" -#include "GlobalConstants.h" -/*for debugging*/ -#define DEBUG_ME "LINKSERVER" -#include "toolLib/debugging.h" -DebugVariable(LINK, "LINK", 0x01); /* setenv LINKSERVER "LINK"*/ - -/*Reads MAP Object off socket */ -int ReadMapRequest(Link* link) -{ - int check = OK; - link->mapRequest = (MapRequest*) malloc(sizeof(MapRequest)); - - if(NULL == link->mapRequest){ - return -1; /* Memory allocation error */ - } - - check = check || ReadFloat(link->socket, &(link->mapRequest->version)); - check = check || ReadFloat(link->socket, &(link->mapRequest->centerlatitude)); - check = check || ReadFloat(link->socket, &(link->mapRequest->centerlongitude)); - check = check || ReadFloat(link->socket, &(link->mapRequest->scale)); - check = check || ReadInteger(link->socket, &(link->mapRequest->height)); - check = check || ReadInteger(link->socket, &(link->mapRequest->width)); - - if (Debug(LINK)){ - printf(" version read %f\n", link->mapRequest->version); - printf(" center latitude %f\n", link->mapRequest->centerlatitude); - printf(" center longitude %f\n", link->mapRequest->centerlongitude); - printf(" scale %f \n", link->mapRequest->scale); - printf(" height %d\n", link->mapRequest->height); - printf(" width %d\n", link->mapRequest->width); - } - - check = check || ReadBoundingPolygons(link->socket, - &(link->mapRequest->boundingPolygon)); - if (check == -1) - return -1; /* Memory allocation error */ - - check = check || ReadLinkArgs(link->socket, &(link->mapRequest->linkargs)); - return check; /* If -1, it's a memory allocation error */ - -} - -void FreeMapRequest(MapRequest *map) -{ - FreeBoundingPolygons(&map->boundingPolygon); - FreeLinkArgs(&map->linkargs); -} diff --git a/src/core/src/main/c/cserver/link/Request.c b/src/core/src/main/c/cserver/link/Request.c deleted file mode 100644 index 17b04d21a..000000000 --- a/src/core/src/main/c/cserver/link/Request.c +++ /dev/null @@ -1,110 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/Request.c,v $ - * $RCSfile: Request.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "Request.h" -#include "GlobalConstants.h" - -int ReadBoundingPolygons(LinkSocket *linkSocket, BoundingPolygon *bpoly) -{ - - int i; - int check = OK; - /*how many polygons are coming*/ - check = check || ReadInteger(linkSocket, &(bpoly->numberOfPolygons)); - - /*allocate memory */ - bpoly->polygons = (Polygon *)malloc(sizeof(Polygon) * bpoly->numberOfPolygons); - if(NULL == bpoly->polygons) - { - return -1; /* Memory allocation error */ - } - - /*Read them*/ - for(i=0; i < bpoly->numberOfPolygons; i++) - { - check = check || ReadPolygons(linkSocket, &bpoly->polygons[i]); - if (check == -1) - return -1; /* Memory allocation error */ - } - return check; -} - - -int ReadPolygons(LinkSocket *linkSocket, Polygon *poly) -{ - int i; - int check = OK; - - /* How many Lat Lon's are coming (nLat + nLon)*/ - check = check || ReadInteger(linkSocket, &(poly->numberOfPoints)); - poly->numberOfPoints = poly->numberOfPoints/2; /*a Lat and Lon make 1 point*/ - - /*Allocate memory*/ - poly->points = (LatLonPoint *)malloc(sizeof(LatLonPoint) * poly->numberOfPoints); - if(NULL == poly->points) - { - return -1; /* Memory allocation error */ - } - - /*Read Points*/ - for(i=0;i < poly->numberOfPoints; i++) - { - check = check || ReadLatLonPoint(linkSocket, &poly->points[i]); - } - - return check; -} - -void FreePolygons(Polygon *poly) -{ - free(poly->points); - poly->points = NULL; -} - -void FreeBoundingPolygons(BoundingPolygon *bpoly) -{ - int i; - for(i=0; i < bpoly->numberOfPolygons; i++ ) - { - FreePolygons(&bpoly->polygons[i]); - } - - free(bpoly->polygons); -} - -int ReadDescriptor(LinkSocket *linkSocket, Descriptor *descriptor) -{ - int *temp; - temp = (int *)descriptor; - return ReadInteger(linkSocket, temp); -} - -int ReadModifier(LinkSocket *linkSocket, Modifier *modifier) -{ - int *temp; - temp = (int *)modifier; - return ReadInteger(linkSocket, temp); -} diff --git a/src/core/src/main/c/cserver/link/Response.c b/src/core/src/main/c/cserver/link/Response.c deleted file mode 100644 index 6b49839fb..000000000 --- a/src/core/src/main/c/cserver/link/Response.c +++ /dev/null @@ -1,82 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/src/Response.c,v $ - * $RCSfile: Response.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include -#include - -#include "Response.h" -#include "Request.h" -#include "GlobalConstants.h" -#include "Link.h" - -/*for debugging*/ -#define DEBUG_ME "LINKSERVER" -#include -DebugVariable(LINK, "LINK", 0x01); /* setenv LINKSERVER "LINK"*/ - -int WriteMapResponseHeader(LinkSocket *link, LinkArgs *linkArgs){ - if (Debug(LINK)) - printf("WriteMapResponseHeader: writing MAP Response header %s\n", - GRAPHICS_RESPONSE_HEADER); - WriteChars(link, GRAPHICS_RESPONSE_HEADER, lGRAPHICS_RESPONSE_HEADER); - - if (Debug(LINK)) - printf("WriteMapResponseHeader: writing version %f\n", VERSION); - WriteFloat(link, VERSION); /*writing version 0.2*/ - if (WriteLinkArgs(link, linkArgs) == -1) - return -1; /* Memory allocation error */ - if (Debug(LINK)) - printf("WriteMapResponseHeader: All done writing header...\n"); - return OK; -} - -int WriteActionResponseHeader(LinkSocket *link, LinkArgs *linkArgs){ - if (Debug(LINK)) - printf("WriteActionResponseHeader: writing ACTION Response header %s\n", - GESTURE_RESPONSE_HEADER); - WriteChars(link, GESTURE_RESPONSE_HEADER, lGESTURE_RESPONSE_HEADER); - - if (Debug(LINK)) - printf("WriteActionResponseHeader: writing version %f\n", VERSION); - WriteFloat(link, VERSION); /*writing version 0.2*/ - if (WriteLinkArgs(link, linkArgs) == -1) - return -1; /* Memory allocation error */ - return OK; -} - -void EndSection(LinkSocket *link){ - WriteChars(link, END_SECTION_STRING, 1); /*nothing more for now*/ - Socketflush(link); - - if (Debug(LINK)) - printf("EndSection: Wrote section end symbol and flushed socket...\n"); -} - -void EndTotal(LinkSocket *link){ - WriteChars(link, END_TOTAL_STRING, 1); /*nothing more for now*/ - Socketflush(link); - - if (Debug(LINK)) - printf("EndSection: Wrote total end symbol and flushed socket...\n"); -} - diff --git a/src/core/src/main/c/cserver/link/makefile b/src/core/src/main/c/cserver/link/makefile deleted file mode 100644 index 7afcef1be..000000000 --- a/src/core/src/main/c/cserver/link/makefile +++ /dev/null @@ -1,92 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Use, duplication, or disclosure by the Government is subject to -# restricted rights as set forth in the DFARS. -# -# BBNT Solutions LLC -# A Part of -# GTE -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-3000 -# -# Copyright 1999-2000 by BBNT Solutions LLC, -# A part of GTE, all rights reserved. -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/cserver/link/src/makefile,v $ -# $RCSfile: makefile,v $ -# $Revision: 1.2 $ -# $Date: 2006/10/10 22:05:18 $ -# $Author: dietrick $ -# ------------------------------------------------------------------------ - -all: liblink.a linkserver - -SYSTEM_TYPE = solaris2 - -#COMPILER_HOME = /opt/SUNWspro -COMPILER_HOME = /usr/local/gnu -LDLIBS = -ltoolLib -lsocket -lnsl -CXX_AR = $(COMPILER_HOME)/bin/ar rcv - -# MAC OS X ------ -#COMPILER_HOME = /usr -#LDLIBS = -ltoolLib -#CXX_AR = $(COMPILER_HOME)/bin/ar -rsv -# ---------------- - -#CC = $(COMPILER_HOME)/bin/cc -CC = $(COMPILER_HOME)/bin/gcc -Wall - -CXXFLAGS = -I../../../include/cserver/link -I../../../include/cserver/toolLib -DSOLARIS=1 \ - -DMULTICAST=1 -DSTDC_HEADERS=1 -DHAVE_FCNTL_H=1 -DHAVE_ERRNO_H=1 \ - -DHAVE_STDLIB_H=1 -DHAVE_LIMITS_H=1 -DHAVE_UNISTD_H=1 \ - -DHAVE_SYS_STREAM_H=1 -DHAVE_SYS_UN_H=1 -DHAVE_SYS_TIME_H=1 \ - -DHAVE_TOLOWER=1 -DHAVE_STRING_H=1 -DTIME_WITH_SYS_TIME=1 - -LDFLAGS = -L../../lib -L$(COMPILER_HOME)/lib - -SERVERM.c = LinkServer.c -SERVERM.o = $(SERVERM.c:.c=.o) - -SERVER.c = LatLonPoint.c Response.c \ - LinkBitmap.c LinkCircle.c LinkEllipse.c LinkRectangle.c LinkText.c\ - LinkSocket.c LinkArgs.c LinkPoly.c LinkGrid.c\ - Request.c LinkLine.c LinkRaster.c LinkImage.c \ - MapRequest.c ActionRequest.c Link.c LinkPoint.c - -SERVER.o = $(SERVER.c:.c=.o) - -linkserver: $(SERVER.o) $(SERVERM.o) - $(CC) $(CXXFLAGS) $(LDFLAGS) -o $@ \ - $(SERVERM.o) $(SERVER.o) $(LDLIBS) - mkdir -p ../../bin - cp linkserver ../../bin - -liblink.a: $(SERVER.o) - $(CXX_AR) liblink.a $(SERVER.o) - mkdir -p ../../lib - cp liblink.a ../../lib - -# compile using Purify Software's profiler -linkserver.pure: $(SERVER.o) $(SERVERM.o) - purify -best-effort $(CC) $(CXXFLAGS) $(LDFLAGS) -o $@ \ - $(SERVERM.o) $(SERVER.o) $(LDLIBS) - -.c: - $(CC) -o $(LDFLAGS) $(CXXFLAGS) $* $*.c -.c.o: - $(CC) -c $(LDFLAGS) $(CXXFLAGS) $*.c - -# what gets removed on a "make clean" -CLEANUPS = linkserver *.o *.a *~ - -RM = /bin/rm -rf - -clean: - $(RM) $(CLEANUPS) - - - diff --git a/src/core/src/main/c/cserver/makefile b/src/core/src/main/c/cserver/makefile deleted file mode 100644 index 9e97362e5..000000000 --- a/src/core/src/main/c/cserver/makefile +++ /dev/null @@ -1,41 +0,0 @@ -# Generated automatically from Makefile.in by configure. -# ********************************************************************** -# -# Use, duplication, or disclosure by the Government is subject to -# restricted rights as set forth in the DFARS. -# -# BBNT Solutions LLC -# A Part of -# GTE -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-3000 -# -# Copyright 1998, 2000 by BBNT Solutions LLC, -# A part of GTE, all rights reserved. -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/cserver/makefile,v $ -# $Revision: 1.1.1.1 $ -# $Date: 2003/02/14 21:35:48 $ -# $Author: dietrick $ -# -# ********************************************************************** - - - -all: - cd toolLib && $(MAKE) $@ - cd link && $(MAKE) $@ - -linkserver.pure: - cd link && $(MAKE) linkserver.pure - -clean distclean:: - cd toolLib && $(MAKE) $@ - cd link && $(MAKE) $@ - cd ../include/link && rm -rf *~ - cd ../include/toolLib && rm -rf * - rm -rf bin include lib - diff --git a/src/core/src/main/c/cserver/toolLib/CTag.c b/src/core/src/main/c/cserver/toolLib/CTag.c deleted file mode 100644 index 2b977b635..000000000 --- a/src/core/src/main/c/cserver/toolLib/CTag.c +++ /dev/null @@ -1,24 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/CTag.c,v $ - * $RCSfile: CTag.c,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -char *cvs_tag_toolLib = "@(#)/nfs/amp/master/matt/toolLib/Makefile,v: (none)"; diff --git a/src/core/src/main/c/cserver/toolLib/Magic.c b/src/core/src/main/c/cserver/toolLib/Magic.c deleted file mode 100644 index 3ca45866f..000000000 --- a/src/core/src/main/c/cserver/toolLib/Magic.c +++ /dev/null @@ -1,41 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/Magic.c,v $ - * $RCSfile: Magic.c,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#include "Magic.h" - -/* ------------------------------------------------------------------------ - * - * NewMagicNumber - Returns the argument as a magic number. - * - * RETURNS: The argument given as a magic number. - * - * The intent is to give all structures a Magic element that is filled - * with a magic number unique to that structure type. Then during debugging, - * the structure can be verified to be what it claims to be. - * - * ------------------------------------------------------------------------ */ - -const Magic NewMagicNumber(const char *ident) -{ - return((Magic) ident); -} diff --git a/src/core/src/main/c/cserver/toolLib/auto_input.c b/src/core/src/main/c/cserver/toolLib/auto_input.c deleted file mode 100644 index 982e080fd..000000000 --- a/src/core/src/main/c/cserver/toolLib/auto_input.c +++ /dev/null @@ -1,487 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/auto_input.c,v $ - * $RCSfile: auto_input.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM HEADER FILES */ -#ifdef _AIX -#include -#endif -#include -#include -#include - -/* TOOL HEADER FILES */ -#include "compat.h" -#include "style.h" - -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" -#include "error_hand.h" - -/* LOCAL HEADER FILES */ -#include "plumbing.h" -#include "buffers.h" -#include "auto_input.h" -#include "sockets.h" - -DebugVariable(autoinput, "autoinput", 0x01); - -/* - * From sys/types.h - */ - -#define MaxFds FD_SETSIZE -#define LegalFd(fd) ((fd) >= 0 && (fd) < MaxFds) - -typedef enum _InputType -{ - InputType_Unknown = 0, - InputType_Count = 1, - InputType_Line = 2 -} InputType; - -typedef struct autoInputBuf -{ - char *data; - - int fd; - - InputType type; - int bytesNeeded; - int bytesInBuffer; - int bufSize; - int resumeFlag; - char *clientData; - - AutoInputBufCBProc callback; - const char *callbackName; -} AutoInputBuf; - -static AutoInputBuf ibufs[MaxFds]; -static int initialized = 0; - -static int AutoFill( -#if NeedFunctionPrototypes - int fd, - char *clientData -#endif -); - -int InitAutoInputBufs() -{ - int fd; - - if(initialized != 0) - return(NormalReturn); - - initialized = 1; - - for(fd = 0; fd < MaxFds; fd++) - { - ibufs[fd].fd = -1; - ibufs[fd].type = InputType_Unknown; - ibufs[fd].data = (char *) 0; - ibufs[fd].bytesNeeded = 0; - ibufs[fd].bytesInBuffer = 0; - ibufs[fd].bufSize = 0; - ibufs[fd].resumeFlag = 0; - ibufs[fd].clientData = (char *) 0; - ibufs[fd].callback = (AutoInputBufCBProc) 0; - ibufs[fd].callbackName = "No Input Callback"; - } - - return(NormalReturn); -} - -int CancelAutoInput(int fd) -{ - int bytesInBuffer; - - if(initialized == 0) InitAutoInputBufs(); - - if(Debug(autoinput)) - { - sprintf(msgBuf, "CancelAutoInput(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - bytesInBuffer = ibufs[fd].bytesInBuffer; - - DisconnectInputFd(fd); - - ibufs[fd].fd = -1; - - return(bytesInBuffer); -} - -void FlushAutoInput(int fd) -{ - CancelAutoInput(fd); - FreeBuffer(ibufs[fd].data); - ibufs[fd].data = (char *) 0; -} - - -int ResumeAutoInput( - int fd, - int bytesNeeded, - char *clientData, - AutoInputBufCBProc callback, - const char *callbackName) -{ - if(initialized == 0) InitAutoInputBufs(); - - if(Debug(autoinput)) - { - sprintf(msgBuf, "ResumeAutoInput(%d, %d, 0x%x, 0x%x, %s)", - fd, bytesNeeded, clientData, callback, - callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - if(ibufs[fd].fd == -1) - { - sprintf(msgBuf, "ResumeAutoInput fd % is not active", fd); - DEBUG_MESSAGE(msgBuf); - return(ErrorReturn); - } - - ibufs[fd].bytesNeeded = bytesNeeded; - ibufs[fd].clientData = clientData; - ibufs[fd].callback = callback; - ibufs[fd].callbackName = callbackName; - ibufs[fd].resumeFlag = 1; - - ConnectInputFd(fd, AutoFill, "AutoFill", (char *) 0); - - return(fd); -} - -int AutoInputLine( - int fd, - char *clientData, - AutoInputBufCBProc callback, - const char *callbackName) -{ - char *data; - int bytesNeeded = 1; - - if(initialized == 0) InitAutoInputBufs(); - - if(Debug(autoinput)) - { - sprintf(msgBuf, "AutoInputLine(%d, 0x%x, 0x%x, %s)", - fd, clientData, callback, callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - data = GetNewBufferAndSize(bytesNeeded, &(ibufs[fd].bufSize)); - if(data == (char *) 0) - { - NoMemory("StartAutoInput", bytesNeeded); - return(ErrorReturn); - } - - ibufs[fd].fd = fd; - ibufs[fd].type = InputType_Line; - ibufs[fd].data = data; - ibufs[fd].bytesNeeded = bytesNeeded; - ibufs[fd].bytesInBuffer = 0; - ibufs[fd].clientData = clientData; - ibufs[fd].callback = callback; - ibufs[fd].callbackName = callbackName; - ibufs[fd].resumeFlag = 0; - - ConnectInputFd(fd, AutoFill, "AutoFill", (char *) 0); - - return(NormalReturn); -} - -int StartAutoInput( - int fd, - int bytesNeeded, - char *clientData, - AutoInputBufCBProc callback, - const char *callbackName) -{ - char *data; - - if(initialized == 0) InitAutoInputBufs(); - - if(Debug(autoinput)) - { - sprintf(msgBuf, "StartAutoInput(%d, %d, 0x%x, 0x%x, %s)", - fd, bytesNeeded, clientData, callback, - callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - data = GetNewBufferAndSize(bytesNeeded, &(ibufs[fd].bufSize)); - if(data == (char *) 0) - { - NoMemory("StartAutoInput", bytesNeeded); - return(ErrorReturn); - } - - ibufs[fd].fd = fd; - ibufs[fd].type = InputType_Count; - ibufs[fd].data = data; - ibufs[fd].bytesNeeded = bytesNeeded; - ibufs[fd].bytesInBuffer = 0; - ibufs[fd].clientData = clientData; - ibufs[fd].callback = callback; - ibufs[fd].callbackName = callbackName; - ibufs[fd].resumeFlag = 0; - - ConnectInputFd(fd, AutoFill, "AutoFill", (char *) 0); - - return(NormalReturn); -} - -/* ARGSUSED */ -static int AutoFill( - int fd, - char *clientData) -{ - int status; - int result; - int bytesStillNeeded; - int bytesToRead; - int bytes_received; - - do - { - /* - * Make sure the buffer is big enough - */ - - if(ibufs[fd].bytesNeeded > ibufs[fd].bufSize) - { - ibufs[fd].data = IncreaseBufferSize(ibufs[fd].data, - ibufs[fd].bytesNeeded, - &(ibufs[fd].bufSize)); - if(ibufs[fd].data == (char *) 0) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, - "AutoFill(%d ...) NoMem for %d bytes, calling %s", - fd, ibufs[fd].bytesNeeded, ibufs[fd].callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(ibufs[fd].callback) - { - status = (* (ibufs[fd].callback))(ibufs[fd].clientData, - ibufs[fd].data, - ibufs[fd].bytesInBuffer, - ibufs[fd].bufSize, - False); - } - else - { - status = ErrorReturn; - } - - CancelAutoInput(fd); - - return(status); - } - } - - /* - * How much data do we still need to get? - */ - - bytesStillNeeded = (ibufs[fd].bytesNeeded - ibufs[fd].bytesInBuffer); - - /* - * Try to get it. - */ - - if(Debug(autoinput)) - { - result = socket_count(fd); - - sprintf(msgBuf, - "AutoFill(%d ...) want %d, have %d, need %d, %d available", - fd, ibufs[fd].bytesNeeded, ibufs[fd].bytesInBuffer, - bytesStillNeeded, result); - DEBUG_MESSAGE(msgBuf); - } - - bytesToRead = bytesStillNeeded; - bytes_received = 0; - - result = socket_nb_receive(fd, - &(ibufs[fd].data[ibufs[fd].bytesInBuffer]), - bytesToRead, - &bytes_received); - - if (result >= 0) - { - ibufs[fd].bytesInBuffer += bytes_received; - } - - /* - * Check for problems - */ - if (result <= 0) - { - /* 0 = EOF, negative = errors. */ - if(Debug(autoinput)) - { - if (result == 0) - sprintf(msgBuf, "AutoFill(%d ...) socket EOF, calling %s", - fd, ibufs[fd].callbackName); - else - sprintf(msgBuf, "AutoFill(%d ...) socket died, calling %s", - fd, ibufs[fd].callbackName); - - DEBUG_MESSAGE(msgBuf); - } - - if(ibufs[fd].callback) - { - status = (* (ibufs[fd].callback))(ibufs[fd].clientData, - ibufs[fd].data, - ibufs[fd].bytesInBuffer, - ibufs[fd].bufSize, - False); - } - else - { - status = ErrorReturn; - } - - CancelAutoInput(fd); - - return(status); - } - - - /* - * Is the buffer full yet? - */ - - if(ibufs[fd].type == InputType_Line) - { - if(ibufs[fd].data[ibufs[fd].bytesInBuffer-1] != '\n') - ibufs[fd].bytesNeeded++; - else - ibufs[fd].data[ibufs[fd].bytesInBuffer-1] = '\0'; - } - - do - { - if(ibufs[fd].bytesInBuffer >= ibufs[fd].bytesNeeded) - { - if(Debug(autoinput)) - { - sprintf(msgBuf, "AutoFill(%d ...) filled, calling %s", - fd, ibufs[fd].callbackName); - DEBUG_MESSAGE(msgBuf); - } - - bytesStillNeeded = 0; - - ibufs[fd].resumeFlag = 0; - - if(ibufs[fd].callback) - { - status = (* (ibufs[fd].callback))(ibufs[fd].clientData, - ibufs[fd].data, - ibufs[fd].bytesInBuffer, - ibufs[fd].bufSize, - True); - - if(status == ErrorReturn) - return(status); - } - - /* - * Check to see if the consumer has - * requested more data. If not, cancel this auto input. - */ - - } - } while(ibufs[fd].resumeFlag - && ibufs[fd].bytesInBuffer >= ibufs[fd].bytesNeeded); - - if(ibufs[fd].bytesInBuffer >= ibufs[fd].bytesNeeded) - CancelAutoInput(fd); - -#ifdef DEBUG - if(Debug(autoinput)) - fprintf(stderr, "%02d %d\n", fd, socket_count(fd)); -#endif - - } while(ibufs[fd].resumeFlag && - ibufs[fd].bytesInBuffer < ibufs[fd].bytesNeeded); - - return(NormalReturn); -} - diff --git a/src/core/src/main/c/cserver/toolLib/auto_output.c b/src/core/src/main/c/cserver/toolLib/auto_output.c deleted file mode 100644 index 2c49d30e6..000000000 --- a/src/core/src/main/c/cserver/toolLib/auto_output.c +++ /dev/null @@ -1,297 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/auto_output.c,v $ - * $RCSfile: auto_output.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM HEADER FILES */ -#ifdef _AIX -#include -#endif -#include -#include -#include - -/* TOOL HEADER FILES */ -#include "compat.h" - -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" -#include "style.h" -#include "error_hand.h" -#include "buffers.h" -#include "sockets.h" - -/* LOCAL HEADER FILES */ -#include "plumbing.h" -#include "auto_output.h" - -DebugVariable(autooutput, "autooutput", 0x01); - -/* - * From sys/types.h - */ - -#define MaxFds FD_SETSIZE -#define LegalFd(fd) ((fd) >= 0 && (fd) < MaxFds) - -static int initialized = 0; - -typedef struct autoOutputBuf -{ - char *data; - - int fd; - int bytesToSend; - int bytesAlreadySent; - int restartFlag; - - char *clientData; - - AutoOutputBufCBProc callback; - const char *callbackName; -} AutoOutputBuf; - -static AutoOutputBuf obufs[MaxFds]; - -static int AutoEmpty(int fd, char *clientData); - -char *obufinfo(int fd) -{ - static char foo[128]; - - if(initialized == 0) InitAutoOutputBufs(); - - sprintf(foo, "%d, %d, %d, %s", - obufs[fd].fd, - obufs[fd].bytesToSend, - obufs[fd].bytesAlreadySent, - obufs[fd].callbackName); - return(foo); -} - -int InitAutoOutputBufs() -{ - int fd; - - if(initialized != 0) - return(NormalReturn); - initialized = 1; - - for(fd = 0; fd < MaxFds; fd++) - { - obufs[fd].fd = -1; - obufs[fd].data = (char *) 0; - obufs[fd].bytesToSend = 0; - obufs[fd].bytesAlreadySent = 0; - obufs[fd].restartFlag = 0; - obufs[fd].clientData = (char *) 0; - obufs[fd].callback = (AutoOutputBufCBProc) 0; - obufs[fd].callbackName = "No Output Callback"; - } - - return(NormalReturn); -} - -int CancelAutoOutput(int fd) -{ - int bytesAlreadySent; - - if(initialized == 0) InitAutoOutputBufs(); - - if(Debug(autooutput)) - { - sprintf(msgBuf, "CancelAutoOutput(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autooutput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - bytesAlreadySent = obufs[fd].bytesAlreadySent; - - DisconnectOutputFd(fd); - - obufs[fd].fd = -1; - - return(bytesAlreadySent); -} - -void FlushAutoOutput(int fd) -{ - CancelAutoOutput(fd); - FreeBuffer(obufs[fd].data); - obufs[fd].data = (char *) 0; -} - - -int StartAutoOutput( - int fd, - char *data, - int bytesToSend, - char *clientData, - AutoOutputBufCBProc callback, - const char *callbackName) -{ - if(initialized == 0) InitAutoOutputBufs(); - - if(Debug(autooutput)) - { - sprintf(msgBuf, "StartAutoOutput(%d, 0x%x, %d, 0x%x, 0x%x, %s)", - fd, data, bytesToSend, clientData, callback, callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(!LegalFd(fd)) - { - if(Debug(autooutput)) - { - sprintf(msgBuf, "fd %d out of range (0, %d)", fd, MaxFds); - DEBUG_MESSAGE(msgBuf); - } - - return(ErrorReturn); - } - - if(obufs[fd].fd != -1) - obufs[fd].restartFlag = 1; - else - obufs[fd].restartFlag = 0; - - obufs[fd].fd = fd; - obufs[fd].data = data; - obufs[fd].bytesToSend = bytesToSend; - obufs[fd].bytesAlreadySent = 0; - obufs[fd].clientData = clientData; - obufs[fd].callback = callback; - obufs[fd].callbackName = callbackName; - - ConnectOutputFd(fd, AutoEmpty, "AutoEmpty", (char *) 0); - - /* - * Took this out 1/18/93 - * It causes mucho recursion if it's in - */ - /* AutoEmpty(fd, (char *) 0); */ - - return(fd); -} - -/* ARGSUSED */ -static int AutoEmpty(int fd, char *clientData) -{ - int status; - int result; - int bytesStillToSend; - - /* - * What's left to send out? - */ - - bytesStillToSend = (obufs[fd].bytesToSend - obufs[fd].bytesAlreadySent); - - /* - * Send as much as possible - */ - - result = socket_nb_send(fd, - &(obufs[fd].data[obufs[fd].bytesAlreadySent]), - bytesStillToSend); - - /* - * Check to make sure there was no grievous error - */ - - if(result < 0) - { - if(errno != EPIPE) - result = socket_test(fd); - - if(result < 0) - { - if(Debug(autooutput)) - { - sprintf(msgBuf, "AutoEmpty(%d ...) socket died, calling %s", - fd, obufs[fd].callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(obufs[fd].callback) - { - status = (* (obufs[fd].callback))(obufs[fd].clientData, - obufs[fd].bytesAlreadySent, - obufs[fd].data, - False); - } - else - { - status = ErrorReturn; - } - - if(obufs[fd].restartFlag == 0) - CancelAutoOutput(fd); - - return(status); - } - } - else - { - obufs[fd].bytesAlreadySent += result; - } - - /* - * Are we done yet? - */ - - if(obufs[fd].bytesAlreadySent >= obufs[fd].bytesToSend) - { - if(Debug(autooutput)) - { - sprintf(msgBuf, "AutoEmpty(%d ...) emptied, calling %s", - fd, obufs[fd].callbackName); - DEBUG_MESSAGE(msgBuf); - } - - if(obufs[fd].callback) - { - status = (* (obufs[fd].callback))(obufs[fd].clientData, - obufs[fd].bytesAlreadySent, - obufs[fd].data, - True); - - if(status == ErrorReturn) - return(status); - } - - if(obufs[fd].restartFlag == 0 - || obufs[fd].bytesAlreadySent >= obufs[fd].bytesToSend) - CancelAutoOutput(fd); - } - - return(NormalReturn); -} diff --git a/src/core/src/main/c/cserver/toolLib/buffers.c b/src/core/src/main/c/cserver/toolLib/buffers.c deleted file mode 100644 index 9b8f1603d..000000000 --- a/src/core/src/main/c/cserver/toolLib/buffers.c +++ /dev/null @@ -1,586 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/buffers.c,v $ - * $RCSfile: buffers.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM HEADER FILES */ -#include -#include - -/* #define MAC_OS_X */ - -#ifndef MAC_OS_X -#include -#endif - -/* TOOL HEADER FILES */ -#include "compat.h" -#include "style.h" -#include "error_hand.h" -#include "Magic.h" -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" - -#ifdef SVR4 -#include -#define bzero(addr, n) memset(addr, 0, n) -#define bcopy(from, to, n) memcpy(to, from, n) -#endif - -DebugVariable(buffers, "buffers", 0x01); - -/* LOCAL HEADER FILES */ -#define BuffersPrivate -#include "buffers.h" - -static int initialized = 0; - -/* - * NOTE: This struct should be kept to be a multiple of 4 bytes long to - * ensure decent memory alignment of the data portion that is returned - * to the user. Otherwise, bad things will happen. InitBuffers watches for - * that, and, thankfully (maybe) some compilers pad structs anyway. - * - */ - -typedef struct _BufHeader -{ - Magic magic1; - int size; - struct _BufHeader *next; - char *data; - Magic *magic3; - Magic magic2; -} BufHeader; - -static int seq = 0; - -static Magic bufMagic1; -static Magic bufMagic2; -static Magic bufMagic3; - -#define BufHeaderOk(b) ((b)->magic1 == bufMagic1 && (b)->magic2 == bufMagic2 \ - && *((b)->magic3) == bufMagic3) - -#define NoBufHeader ((BufHeader *) 0) - -static BufHeader *freeBufList = NoBufHeader; -static BufHeader *inUseList = NoBufHeader; - -/* - * Keep some stats that we can get at with saber or dbx - */ - -static int freeBufs = 0; -static int inUseBufs = 0; -static int freeBytes = 0; -static int inUseBytes = 0; - -char bufferMsg[1024]; - -void DumpBuffers() -{ - printf("Buffers: count %d/%d, size %d/%d\n", - inUseBufs, (freeBufs + inUseBufs), - inUseBytes,(freeBytes + inUseBytes)); -} - -/* ------------------------------------------------------------------------ - * - * PutBufOnFreeList() - * - * Given a BufHeader pointer, insert the buffer into the - * free list. Right now the free list is ordered in terms - * of increasing size but there is nothing saying that there - * should not be separate free lists for each buffer size or - * some other scheme which could be more efficient. - * - * RETURNS: Nothing. - * - * ------------------------------------------------------------------------ */ - -static void PutBufOnFreeList(BufHeader *buf) -{ - BufHeader **temp; - BufHeader *entry; - - if(initialized == 0) InitBuffers(); - - entry = freeBufList; - temp = &freeBufList; - - - freeBufs++; - inUseBufs--; - freeBytes += buf->size; - inUseBytes -= buf->size; - - if(Debug(buffers)) - { - seq++; - sprintf(msgBuf, - "Buffers %06d FREE 0x%08x %06d: F %02d, U %02d, Fb %05d, Ub %05d %s", - seq, buf, - buf->size, freeBufs, inUseBufs, freeBytes, inUseBytes, bufferMsg); - DEBUG_MESSAGE(msgBuf); - } - - while(entry) - { - if(entry->size >= buf->size) - { - *temp = buf; - buf->next = entry; - return; - } - temp = &(entry->next); - entry = entry->next; - } - - *temp = buf; - buf->next = NoBufHeader; -} - - -/* ------------------------------------------------------------------------ - * - * FreeBuffer() - * - * Given a buffer pointer, figure out if it really originated from - * this module and if so, put it back on the free list. - * - * RETURNS: -1 on error - * - * ------------------------------------------------------------------------ */ - -int DebugFreeBuffer( - char *buf, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(bufferMsg, "%14s, %04d", fileName, line); - return(FreeBuffer(buf)); -} - -/*------------------------------------------------------------------------ - * IsABuffer() - * - * Note that this is likely to return the right answer since three - * magic numbers get checked, each of which is a 32 bit unique number. - * Two of the numbers are at fixed locations above the buffer's storage, - * one is at the end of the storage. - * - * RETURN: - * False definitely not a buffer, ok to use free(2) on it - * assuming the choices where whether this was malloc'ed storage - * or buffer space. - * - * True Highly likely it's a buffer. - *------------------------------------------------------------------------*/ - -Bool IsABuffer(char *buf) -{ - BufHeader *thisBuf; - - if(initialized == 0) InitBuffers(); - - if(buf == (char *) 0) - { - return(False); - } - - /* - * buf points to the location inside the BufHeader struct. Back up - * to the beginning of the struct and then test to see that - * all the magic numbers are there. If they are not, then - * either 'buf' was not generated in this module or the user of buf - * trashed it by using more than was allowed. - */ - - thisBuf = (BufHeader *)((unsigned long) buf - sizeof(BufHeader)); - - if(!BufHeaderOk(thisBuf)) - return(False); - - return(True); -} - -int FreeBuffer(char *buf) -{ - BufHeader *thisBuf; - BufHeader **temp; - BufHeader *entry; - - if(initialized == 0) InitBuffers(); - - if(buf == (char *) 0) - { - return(0); - } - - /* - * buf points to the location inside the BufHeader struct. Back up - * to the beginning of the struct and then test to see that - * all the magic numbers are there. If they are not, then - * either 'buf' was not generated in this module or the user of buf - * trashed it by using more than was allowed. - */ - - thisBuf = (BufHeader *)((unsigned long) buf - sizeof(BufHeader)); - - if(!BufHeaderOk(thisBuf)) - { - sprintf(msgBuf, "FreeBuf(0x%x) corrupted buffer found", buf); - WARNING_MESSAGE(msgBuf); - return(-1); - } - - entry = inUseList; - temp = &inUseList; - - while(entry) - { - if(entry->data == buf) - { - *temp = entry->next; - PutBufOnFreeList(entry); - return(entry->size); - } - temp = &(entry->next); - entry = entry->next; - } - - return(0); -} - - -/* ------------------------------------------------------------------------ - * - * IncreaseBufferSize() - * - * Given a pointer to a buffer, and a new size request, decide - * whether the buffer really was big enough all along (in which case - * just hand it back to the caller) or whether a new one has to - * be found (in which case the old contents are copied into the - * new one) and handed back. - * - * RETURNS: The pointer to the new buffer and also the actual size if - * the actualSizePtr is non-null. - * - * ------------------------------------------------------------------------ */ - -char *DebugIncreaseBufferSize( - char *buf, - int size, - int *asp, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(bufferMsg, "%14s, %04d", fileName, line); - return(IncreaseBufferSize(buf, size, asp)); -} - -char *IncreaseBufferSize( - char *buffer, - int size, - int *actualSizePtr) -{ - BufHeader *thisBuf; - char *newBuffer; - - if(initialized == 0) InitBuffers(); - - /* - * Check to see if there is a real buffer here - */ - - if(buffer) - { - thisBuf = (BufHeader *)((unsigned long) buffer - sizeof(BufHeader)); - - if(!BufHeaderOk(thisBuf)) - { - sprintf(msgBuf, - "IncreaseBufferSize(0x%x) corrupted buffer found", buffer); - WARNING_MESSAGE(msgBuf); - return((char *) 0); - } - - /* - * It turns out that this one is big enough. - */ - if(thisBuf->size >= size) - { - if(actualSizePtr) - *actualSizePtr = thisBuf->size; - return(buffer); - } - } - - /* - * Either there was not original buffer or the original was too small - */ - - newBuffer = GetNewBufferAndSize(size, actualSizePtr); - - /* - * If we actually got a new one, and there actually was an old one, - * copy the contents of the old one into the new one. Free the old one. - * - * Note: Don't free the old one if we failed to get a new one. - * Our callers might get miffed it we don't give them back a new - * buffer AND we blow away their old data! - */ - - if(newBuffer && buffer) - { - bcopy(buffer, newBuffer, thisBuf->size); - FreeBuffer(buffer); - } - - /* - * return the new one. If it was bogus, this will return the - * NULL on up to the caller - */ - - return(newBuffer); -} - - -/* ------------------------------------------------------------------------ - * - * GetNewBufferAndSize() - * - * Note the companion macro in buffers.h called - * GetNewBuffer() which is the usual one to call. - * - * Looks for the first buffer that is at least big enough - * to handle the size needed and returns the data portion - * of that buffer. - * - * RETURNS: pointer to new buffer and size of buffer if actualSizePtr - * is non-null. - * - * ------------------------------------------------------------------------ */ - -char *DebugGetNewBufferAndSize( - int size, - int *asp, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(bufferMsg, "%14s, %04d", fileName, line); - return(GetNewBufferAndSize(size, asp)); -} - -char *GetNewBufferAndSize( - int size, - int *actualSizePtr) -{ - int allocSize; - - BufHeader **temp; - BufHeader *entry = NoBufHeader; - - if(initialized == 0) InitBuffers(); - - entry = freeBufList; - temp = &freeBufList; - - if(size > BufMaxAlloc) - { - sprintf(msgBuf, "GetNewBufferAndSize(%d) exceeds max of %d", - size, BufMaxAlloc); - return((char *) 0); - } - - while(entry) - { - if(entry->size >= size) - { - /* - * Let's make sure that we don't give a ridiculously - * large buffer out just because it's the next one - * available! - */ - - if(entry->size > BufMinAlloc && entry->size > size * OversizeLimit) - { - break; - } - - *temp = entry->next; - entry->next = inUseList; - inUseList = entry; - - if(actualSizePtr) - *actualSizePtr = entry->size; - - freeBufs--; - inUseBufs++; - freeBytes -= entry->size; - inUseBytes += entry->size; - - if(Debug(buffers)) - { - seq++; - sprintf(msgBuf, - "Buffers %06d GET 0x%08x %06d: F %02d, U %02d, Fb %05d, Ub %05d %s", - seq, entry, entry->size, - freeBufs, inUseBufs, freeBytes, inUseBytes, bufferMsg); - DEBUG_MESSAGE(msgBuf); - } - return(entry->data); - } - temp = &(entry->next); - entry = entry->next; - } - - /* - * Try to figure out the next power of 2 that will satisfy - * this size request. - */ - for(allocSize = BufMinAlloc; allocSize <= BufMaxAlloc; allocSize <<= 1) - { - if(allocSize >= size) - break; - } - - entry = (BufHeader *) malloc(sizeof(BufHeader) + sizeof(Magic) + - allocSize); - - if(entry == NoBufHeader) - { - NoMemory("GetNewBufferAndSize", - sizeof(BufHeader) + sizeof(Magic) + allocSize); - return((char *) 0); - } - - entry->size = allocSize; - entry->data = &((char *) entry)[sizeof(BufHeader)]; - entry->magic3 = (Magic *) &((char *) entry)[sizeof(BufHeader) + allocSize]; - - entry->magic1 = bufMagic1; - entry->magic2 = bufMagic2; - *(entry->magic3) = bufMagic3; - - entry->next = inUseList; - inUseList = entry; - - inUseBufs++; - inUseBytes += entry->size; - - if(actualSizePtr) - *actualSizePtr = entry->size; - - if(Debug(buffers)) - { - seq++; - sprintf(msgBuf, - "Buffers %06d GET 0x%08x %06d: F %02d, U %02d, Fb %05d, Ub %05d %s", - seq, entry, entry->size, - freeBufs, inUseBufs, freeBytes, inUseBytes, bufferMsg); - DEBUG_MESSAGE(msgBuf); - } - - return(entry->data); -} - - -/* ------------------------------------------------------------------------ - * - * InitBuffers() - * - * Call this first! - * - * RETURNS: -1 if failure for some reason. - * - * ------------------------------------------------------------------------ */ - -int InitBuffers() -{ - - if(initialized) - return(0); - - initialized = 1; - - /* - * This little test is here to warn against a compiler that - * does not automatically pad structs to a quad byte alignment. - */ - - /* SUPPRESS 558 *//* CodeCenter conditional expression always false */ - if(sizeof(BufHeader) % 4) - { - /* NOTREACHED *//* Since the compiler can figure this out */ - sprintf(msgBuf, "sizeof(BufHeader) is %d, it MUST be a multiple of 4", - sizeof(BufHeader)); - - FATAL_MESSAGE(msgBuf); - return(-1); - } - - bufMagic1 = NewMagicNumber("Buf Magic 1"); - bufMagic2 = NewMagicNumber("Buf Magic 2"); - bufMagic3 = NewMagicNumber("Buf Magic 3"); - - bufferMsg[0] = '\0'; - - return(0); -} - diff --git a/src/core/src/main/c/cserver/toolLib/compress.c b/src/core/src/main/c/cserver/toolLib/compress.c deleted file mode 100644 index 30c6a6692..000000000 --- a/src/core/src/main/c/cserver/toolLib/compress.c +++ /dev/null @@ -1,665 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/compress.c,v $ - * $RCSfile: compress.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* - * compress.c - * - * File compression code derived from compress 4.0, the public - * domain file compression utility. Modified to strip out variants - * we will not need, use Diamond style and throw exceptions - * instead of exiting on error. - */ - -#include -#include -#include -#include -#include - -#include "style.h" -#include "error_hand.h" - -extern int errno; - -/* #define MAC_OS_X */ - -#ifdef MAC_OS_X - extern __const int sys_nerr; /* perror(3) external variables */ - extern __const char *__const sys_errlist[]; -#else - extern char *sys_errlist[]; - extern int sys_nerr; -#endif - - -#ifndef min -#define min(a,b) ((a>b) ? b : a) -#endif - -/* - * Various defines taken from the sources to compress version 4.0; since - * we don't have to run on all the machines compress does, we have stripped - * all of the options that aren't required for our purposes. - */ - -#define BITS 16 -#define HSIZE 69001 -#define INIT_BITS 9 /* initial number of bits/code */ -#define MAXCODE(bits) ((1 << (bits)) - 1) -#define MAXMAXCODE (1L << BITS) /* should NEVER generate this */ -#define BIT_MASK 0x1f -#define BLOCK_MASK 0x80 -#define CHECK_GAP 10000 /* ratio check interval */ - -typedef long code_t; - -/* - * the next two codes should not be changed lightly, as they must not - * lie within the contiguous general code space. - */ - -#define FIRST 257 /* first free entry */ -#define CLEAR 256 /* table clear output code */ - -/* - * To save much memory, we overlay the table used by compress() with those - * used by decompress(). The tab_prefix table is the same size and type - * as the codetab. The tab_suffix table needs 2**BITS characters. We - * get this from the beginning of htab. The output stack uses the rest - * of htab, and contains characters. There is plenty of room for any - * possible stack (stack used to be 8000 characters). - */ - -#define htabof(i) htab[i] -#define codetabof(i) codetab[i] -#define tab_prefixof(i) codetabof(i) -#define tab_suffixof(i) ((u_char *)(htab))[i] -#define de_stack ((u_char *)&tab_suffixof(1<= 0; code--) - { - tab_prefixof(code) = 0; - tab_suffixof(code) = (u_char) code; - } - clear_flg = 0; - free_ent = FIRST; - - finchar = oldcode = getcode(); - if (oldcode == -1) /* EOF already? */ - return(0); /* Get out of here */ - - bytes_written++; - if (out_fp != NULL) { - putc((char)finchar, out_fp); /* first code must be 8 bits = char */ - /* t_ferror(out_fp); */ - } - else if (bytes_written < out_bytes) - { - *out_ptr++ = (unsigned char)finchar; - } - else - { - WARNING_MESSAGE("No more room to decompress into buffer, finchar."); - return -1; - } - - stackp = de_stack; - - while ((code = getcode()) > -1) - { - if ((code == CLEAR) && BLOCK_MASK) - { - for (code = 255; code >= 0; code--) - tab_prefixof(code) = 0; - clear_flg = 1; - free_ent = FIRST - 1; - if ((code = getcode()) == -1) /* O, untimely death! */ - break; - } - incode = code; - /* - * Special case for KwKwK string. - */ - if (code >= free_ent) - { - *stackp++ = finchar; - code = oldcode; - } - - /* - * Generate output characters in reverse order - */ - while (code >= 256) - { - *stackp++ = tab_suffixof(code); - code = tab_prefixof(code); - } - *stackp++ = finchar = tab_suffixof(code); - - /* - * And put them out in forward order - */ - if (out_fp != NULL) - { - do - { - putc(*--stackp, out_fp); - bytes_written++; - } while (stackp > de_stack); - } - else - { - do - { - if (++bytes_written > out_bytes) - { - WARNING_MESSAGE( - "No more room to decompress into buffer, stackp."); - } - *out_ptr++ = *--stackp; - } while (stackp > de_stack); - } - - /* - * Generate the new entry. - */ - if ((code = free_ent) < MAXMAXCODE) - { - tab_prefixof(code) = (u_short) oldcode; - tab_suffixof(code) = finchar; - free_ent = code + 1; - } - /* - * Remember previous code. - */ - oldcode = incode; - } - if (out_fp != NULL) - fflush(out_fp); /* Flush */ - return (bytes_written); -} - - -/****************************************************************************** - * getcode(): Read one code from input file pointer. If EOF, return -1. - */ - - -static char buf[BITS]; - -#ifndef vax -u_char lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00}; -u_char rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff}; -#endif /* vax */ - -static code_t getcode() -{ - /* - * On the VAX, it is important to have the register declarations in - * exactly the order given, or the asm will break. - */ - register code_t code; - static int gc_offset = 0, size = 0; - static u_char gc_buf[BITS]; - register int r_off, bits; - register u_char *bp = gc_buf; - - if (clear_flg > 0 || gc_offset >= size || free_ent > maxcode) - { - /* - * If the next entry will be too big for the current code size, then - * we must increase the size. This implies reading a new buffer - * full, too. - */ - if (free_ent > maxcode) - { - n_bits++; - if (n_bits == BITS) - maxcode = MAXMAXCODE; /* won't get any bigger now */ - else - maxcode = MAXCODE(n_bits); - } - if (clear_flg > 0) - { - maxcode = MAXCODE(n_bits = INIT_BITS); - clear_flg = 0; - } - size = fread((char *)gc_buf, 1, n_bits, in_fp); - if (size <= 0) - return -1; /* end of file */ - gc_offset = 0; - /* Round size down to integral number of codes */ - size = (size << 3) - (n_bits - 1); - } - r_off = gc_offset; - bits = n_bits; -#ifdef vax - asm("extzv r10,r9,(r8),r11"); -#else /* not a vax */ - /* - * Get to the first byte. - */ - bp += (r_off >> 3); - r_off &= 7; - /* Get first part (low order bits) */ - code = (*bp++ >> r_off); - bits -= (8 - r_off); - r_off = 8 - r_off; /* now, offset into code word */ - /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */ - if (bits >= 8) - { - code |= *bp++ << r_off; - r_off += 8; - bits -= 8; - } - /* high order bits. */ - code |= (*bp & rmask[bits]) << r_off; -#endif /* vax */ - gc_offset += n_bits; - - return code; -} - - -#ifdef DO_COMPRESS - -/***************************************************************************** - * output(): Output the supplied code to the supplied file pointer; - * Supplying a code of -1 means end of file. - * - * Assumptions: - * Chars are 8 bits long. - *****************************************************************************/ - -static void output(code) -code_t code; -{ - /* - * On the VAX, it is important to have the register declarations in - * exactly the order given, or the asm will break. - */ - register int r_off = offset, bits = n_bits; - register char *bp = buf; - - if (code >= 0) - { -#ifdef vax - /* - * VAX DEPENDENT!! Implementation on other machines is below. - * - * Translation: Insert BITS bits from the argument starting at offset - * bits from the beginning of buf. - */ - 0; /* Work around for pcc -O bug with asm and if stmt */ - asm("insv 4(ap),r11,r10,(r9)"); -#else /* not a vax */ - /* - * byte/bit numbering on the VAX is simulated by the following code - */ - - /* - * Get to the first byte. - */ - bp += (r_off >> 3); - r_off &= 7; - /* - * Since code is always >= 8 bits, only need to mask the first hunk - * on the left. - */ - *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off]; - bp++; - bits -= (8 - r_off); - code >>= 8 - r_off; - /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */ - if (bits >= 8) - { - *bp++ = code; - code >>= 8; - bits -= 8; - } - /* Last bits. */ - if (bits) - *bp = code; -#endif /* vax */ - offset += n_bits; - if (offset == (n_bits << 3)) - { - bp = buf; - bits = n_bits; - bytes_out += bits; - do - putc(*bp++, out_fp); - while (--bits); - offset = 0; - } - - /* - * If the next entry is going to be too big for the code size, then - * increase it, if possible. - */ - if (free_ent > maxcode || (clear_flg > 0)) - { - /* - * Write the whole buffer, because the input side won't discover - * the size increase until after it has read it. - */ - if (offset > 0) - { - if (fwrite(buf, 1, n_bits, out_fp) != n_bits) - t_write_error(); - bytes_out += n_bits; - } - offset = 0; - - if (clear_flg) - { - maxcode = MAXCODE(n_bits = INIT_BITS); - clear_flg = 0; - } - else - { - n_bits++; - if (n_bits == BITS) - maxcode = MAXMAXCODE; - else - maxcode = MAXCODE(n_bits); - } - } - } - else - { - /* - * At EOF, write the rest of the buffer. - */ - if (offset > 0) - fwrite(buf, 1, (offset + 7) / 8, out_fp); - bytes_out += (offset + 7) / 8; - offset = 0; - t_fflush(out_fp); /* Flush, and throw EX_WRITE on error */ - } -} - -/****************************************************************************** - * clear_block(): Clear hash table for block compression. - */ - -static void clear_block() /* table clear for block compress */ -{ - register long int rat; - - checkpoint = in_count + CHECK_GAP; - if (in_count > 0x007fffff) - { /* shift will overflow */ - rat = bytes_out >> 8; - if (rat == 0) - { /* Don't divide by zero */ - rat = 0x7fffffff; - } - else - { - rat = in_count / rat; - } - } - else - { - rat = (in_count << 8) / bytes_out; /* 8 fractional bits */ - } - if (rat > ratio) - { - ratio = rat; - } - else - { - ratio = 0; - clear_hash((long)HSIZE); - free_ent = FIRST; - clear_flg = 1; - output((code_t)CLEAR); - } -} - - -/****************************************************************************** - * clear_hash(): clear and reset the hash table for codes. - */ - -static void clear_hash(hsize) -register long hsize; -{ - register long *htab_p = htab + hsize; - register long i; - register long m1 = -1; - - i = hsize - 16; - do - { /* might use Sys V memset(3) here */ - *(htab_p - 16) = m1; - *(htab_p - 15) = m1; - *(htab_p - 14) = m1; - *(htab_p - 13) = m1; - *(htab_p - 12) = m1; - *(htab_p - 11) = m1; - *(htab_p - 10) = m1; - *(htab_p - 9) = m1; - *(htab_p - 8) = m1; - *(htab_p - 7) = m1; - *(htab_p - 6) = m1; - *(htab_p - 5) = m1; - *(htab_p - 4) = m1; - *(htab_p - 3) = m1; - *(htab_p - 2) = m1; - *(htab_p - 1) = m1; - htab_p -= 16; - } while ((i -= 16) >= 0); - for (i += 16; i > 0; i--) - *--htab_p = m1; -} - -/* - * compress(): compress input file pointer to output file pointer - * - * May throw EX_WRITE if write errors are encountered. - * - * Lifted almost completely from Compress 4.0 -- thanks to all those - * who wrote compress and put it in the public domain. - */ - -/* VARARGS 2 */ -void compress(in, out, in_ptr, in_bytes) -FILE *in; -FILE *out; -unsigned char *in_ptr; -int in_bytes; -{ - register long fcode; - register code_t i = 0; - register int c; - register code_t ent; - register int disp; - register int hshift; - - in_fp = in; - out_fp = out; - - putc(g_magic[0], out_fp); - putc(g_magic[1], out_fp); - putc((char)(BITS | BLOCK_MASK), out_fp); - t_ferror(out_fp); /* Throw EX_WRITE on error */ - - offset = 0; - bytes_out = 3; /* includes 3-byte header mojo */ - clear_flg = 0; - ratio = 0; - in_count = 1; - checkpoint = CHECK_GAP; - maxcode = MAXCODE(n_bits = INIT_BITS); - free_ent = FIRST; - - if (in_fp != NULL) - ent = getc(in_fp); - else if (--in_bytes >= 0) - ent = *in_ptr++; - else - throwv(EX_FAILURE, "Empty source buffer passed to compress."); - - hshift = 0; - for (fcode = (long)HSIZE; fcode < 65536L; fcode *= 2L) - hshift++; - hshift = 8 - hshift; /* set hash code range bound */ - - clear_hash((long)HSIZE); - - while (in_fp != NULL && (c = getc(in_fp)) != EOF - || --in_bytes >= 0 && ((c = *in_ptr++), TRUE)) - { - in_count++; - fcode = (long) (((long) c << BITS) + ent); - i = ((c << hshift) ^ ent); /* xor hashing */ - - if (htabof(i) == fcode) - { - ent = codetabof(i); - continue; - } - else if ((long) htabof(i) < 0) /* empty slot */ - goto nomatch; - disp = HSIZE - i; /* secondary hash (after G. Knott) */ - if (i == 0) - disp = 1; -probe: - if ((i -= disp) < 0) - i += HSIZE; - - if (htabof(i) == fcode) - { - ent = codetabof(i); - continue; - } - if ((long) htabof(i) > 0) - goto probe; -nomatch: - output((code_t)ent); - ent = c; - if (free_ent < MAXMAXCODE) - { - codetabof(i) = free_ent++; /* code -> hashtable */ - htabof(i) = fcode; - } - else if ((long) in_count >= checkpoint && BLOCK_MASK) - clear_block(); - } - /* - * Put out the final code. - */ - output((code_t) ent); - output((code_t) -1); -} -#endif diff --git a/src/core/src/main/c/cserver/toolLib/error_hand.c b/src/core/src/main/c/cserver/toolLib/error_hand.c deleted file mode 100644 index 161420404..000000000 --- a/src/core/src/main/c/cserver/toolLib/error_hand.c +++ /dev/null @@ -1,268 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/error_hand.c,v $ - * $RCSfile: error_hand.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM LEVEL HEADER FILES */ -#include -#include -#include -#include -#ifdef c_plusplus -#include -#endif - -/* OTHER HEADER FILES */ -#include "compat.h" -#include "error_hand.h" -#include "stringutil.h" - -char msgBuf[4096]; -static char errorString[4096]; - -static int messageSaveLevel = DefaultMessageLevel; -static const int *userInteger = (int *) 0; -static const char *userString = (char *) 0; -static const char *statusFile = (char *) 0; - -/*+------------------------------------------------------------------------ - * CustomizeErrorHandler() - * - * Allows the user to set options for the error handler - * - * RETURNS: - * Old save level - *________________________________________________________________________*/ - -int CustomizeErrorHandler(const char *string, - const int *integerPointer, - const char *fileName, - int saveLevel) -{ - int temp = messageSaveLevel; - - userString = string; - userInteger = integerPointer; - statusFile = fileName; - messageSaveLevel = saveLevel; - - return(temp); -} - -/*+------------------------------------------------------------------------ - * ErrorMessage() - * - * Builds a standard message of the form: - * - * 'xxx %d %s at Sat Mar 4 20:41:53 1989 - file:line %s\n' - * - * Where %s's are filled in with the strings given, - * and xxx is the string given with a call to set_error_ident(), - * and %d is the value in the int pointer given to - * set_error_int_ptr(). - * - * RETURNS: - * Nothing - *________________________________________________________________________*/ - -static StringList messageLevels[] = -{ - { SaveInfoMessages, "INFO"}, - { SaveDebugMessages, "DEBUG"}, - { SaveWarningMessages, "WARNING"}, - { SaveFatalMessages, "FATAL"}, - { SaveStatusMessages, "STATUS"}, -}; - -void HandleErrorMessage(int level, - const char *string, - const char *file, - int line, - int error) -{ - FILE *fp; - char *levelString; - const char *fileName; - -/* #define MAC_OS_X */ - -#ifdef MAC_OS_X - extern __const int sys_nerr; /* perror(3) external variables */ - extern __const char *__const sys_errlist[]; -#else - extern char *sys_errlist[]; - extern int sys_nerr; -#endif - -#ifdef USE_TIME - long now; - char *tempChar; - char timeString[80]; -#else - static int which = 0; -#endif - - /* - * Interpret the message level - */ - levelString = LookupString(level & SaveLevelBits, messageLevels, ""); - - /* - * Look up the error value in the system error list - */ - - if(error > 0 && error < sys_nerr) - { - sprintf(errorString, ": %s (%d)", sys_errlist[error], error); - } - else - { - errorString[0] = '\0'; - } - - /* - * Find the file name minus the preceding path name - */ - - fileName = Basename(file); - -#ifdef USE_TIME - /* - * Construct a nice, ascii time. The ctime function returns a string - * containing a newline. It has to be stripped out. - */ - - now = time(NULL); - strcpy(timeString, ctime(&now)); - tempChar = strrchr(timeString, '\n'); - if(tempChar) - *tempChar = '\0'; -#else - which++; -#endif - - if(!(messageSaveLevel & NoStderrOutput)) - { - /* - * Print the message to the console/stderr - */ - - if(userString != NULL) - { - fprintf(stderr, "%s ", userString); - } - - if(userInteger != NULL) - { - fprintf(stderr, "%d ", *userInteger); - } - -#ifdef USE_TIME - fprintf(stderr, - "%-*s at %s - %14s:%04d %s %s\n", - DefaultStatusStringLength, - levelString, - timeString, - fileName, - line, - string, - errorString); -#else - fprintf(stderr, - "%-*s %04d %14s:%04d %s %s\n", - DefaultStatusStringLength, - levelString, - which, - fileName, - line, - string, - errorString); -#endif - - } - - /* - * Decide whether to open the status file - */ - - if(statusFile == NULL) - return; - - /* - * Check the level to see if it's - * an INFO, DEBUG, FATAL, or WARNING message and whether to save - * the sucker to the file. - */ - - if((level & messageSaveLevel) == 0) - return; - - /* - * Open the report file for appending. - */ - - fp = fopen(statusFile, "a+"); - if(fp == NULL) - return; - - if(userString != NULL) - { - fprintf(fp, "%s ", userString); - } - - if(userInteger != NULL) - { - fprintf(fp, "%d ", *userInteger); - } - -#ifdef USE_TIME - fprintf(fp, - "%-*s at %s - %14s:%d %s %s\n", - DefaultStatusStringLength, - levelString, - timeString, - fileName, - line, - string, - errorString); -#else - fprintf(fp, - "%-*s %04d %14s:%d %s %s\n", - DefaultStatusStringLength, - levelString, - which, - fileName, - line, - string, - errorString); -#endif - - /* - * Close the file. - * Syncing depends on the mode bit in the message save level - */ - - if(messageSaveLevel & SyncAfterWritingError) - fsync(fileno(fp)); - - fclose(fp); -} - diff --git a/src/core/src/main/c/cserver/toolLib/free_mgr.c b/src/core/src/main/c/cserver/toolLib/free_mgr.c deleted file mode 100644 index 65ea7f998..000000000 --- a/src/core/src/main/c/cserver/toolLib/free_mgr.c +++ /dev/null @@ -1,571 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/free_mgr.c,v $ - * $RCSfile: free_mgr.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ -/* - * CodeCenter/ObjectCenter compile and runtime warning suppression - */ -/* SUPPRESS 112 *//* Retrieving a from ... */ -/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ - -/* System Header Files */ -#include -#include - -/* local header files */ -#include "compat.h" -#include "style.h" -#include "error_hand.h" -#define FreeListPrivate -#include "free_mgr.h" - -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" - -DebugVariable(freelist, "freelist", 0x01); - -static char freeListMagicNumber1[] = "FreeListMagic1"; -static char freeListMagicNumber2[] = "FreeListMagic2"; - -static FreeList freeLists = -{ - freeListMagicNumber1, /* magic1 */ - "MasterFreeList", /* name */ - (char *) 0, /* list */ - OffsetInStruct(FreeList, next), /* offsetToNext */ - 10, /* reallocSize */ - sizeof(FreeList), /* itemSize */ - 0, /* freeItems */ - 0, /* inUseItems */ - NoFreeList, /* next */ - freeListMagicNumber2 /* magic2 */ -}; - -static int ReallocateFreeList( -#if NeedFunctionPrototypes - FreeList * /* freeList */ -#endif -); - -static char errorString[256]; -static char debugMsg[256]; -static int seq = 0; -static int initialized = 0; -static int checkFree = 1; - -char *PrintFreeList(FreeList *freeList) -{ - static char buf[80]; - sprintf(buf, "%-20s free %-6d used %-6d size %-5d bytes %-6d", - freeList->name, freeList->freeItems, - freeList->inUseItems, freeList->itemSize, - freeList->inUseItems * freeList->itemSize); - return(buf); -} - -void DumpFreeLists() -{ - FreeList *list; - - for(list = &freeLists; list; list = list->next) - { - printf("%s\n", PrintFreeList(list)); - } -} - - -/*+------------------------------------------------------------------------ - * ManageFreeList() - * - * Tells the FreeList manager about a list type to manage. - * - * RETURNS: - * FreeList handle to use for later reference to the list if ok, - * NULL if not. - *________________________________________________________________________*/ - -FreeList *DebugManageFreeList( - unsigned long offsetToNext, - int reallocSize, - int itemSize, - const char *name, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - initialized = 1; - sprintf(debugMsg, "%14s, %04d", fileName, line); - return(ManageFreeList(offsetToNext, reallocSize, itemSize, name)); -} - - -FreeList *ManageFreeList( - unsigned long offsetToNext, - int reallocSize, - int itemSize, - const char *name) -{ - int result; - FreeList *freeList; - - if(!initialized) - debugMsg[0] = '\0'; - - if ( CorruptedFreeList(&freeLists) ) - { - FATAL_MESSAGE("Corrupted free list"); - return(NoFreeList); - } - - freeList = (FreeList *)GetFromFreeList(&freeLists); - if(freeList == NoFreeList) - { - FATAL_MESSAGE("Can't get item from master free list"); - return(NoFreeList); - } - - freeList->list = (char *) 0; - freeList->name = (char *) name; - freeList->offsetToNext = offsetToNext; - freeList->reallocSize = reallocSize; - freeList->itemSize = itemSize; - freeList->freeItems = 0; - freeList->inUseItems = 0; - freeList->next = freeLists.next; - freeList->magic1 = freeListMagicNumber1; - freeList->magic2 = freeListMagicNumber2; - freeLists.next = freeList; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, - "FreeList %06d MANAGE %20s %s", - seq, freeList->name, - debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - - result = ReallocateFreeList(freeList); - if(result == -1) - { - FATAL_MESSAGE("Can't get initial entry for new free list"); - return(NoFreeList); - } - - return(freeList); -} - -/*+--------------------------------------------------------------------- - * GetFromFreeList() - * - * RETURNS: - * Pointer to object of the right size for the type given - * NULL if there is an error - *---------------------------------------------------------------------*/ - -char *DebugGetFromFreeList( - FreeList *freeList, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(debugMsg, "%14s, %04d", fileName, line); - return(GetFromFreeList(freeList)); -} - -char *GetFromFreeList(FreeList *freeList) -{ - int result; - unsigned long base; - char **next; - - if(freeList == NoFreeList) - { - WARNING_MESSAGE("GetFromFreeList() -- Null freeList argument"); - return((char *) 0); - } - - if( CorruptedFreeList(freeList) ) - { - sprintf(errorString, "Corrupted free list at 0x%x", freeList); - FATAL_MESSAGE(errorString); - return((char *) 0); - } - - if (freeList->list == (char *) 0) - { - result = ReallocateFreeList(freeList); - if(result == -1) - { - WARNING_MESSAGE("Can't realloc free list"); - return((char *) 0); - } - } - - /* - * base will point to the base of an 'itemSize' chunk of the newly - * allocated memory area, - * next will point to the place where the structure element called - * 'next' would be if we were dealing with an actual user - * structure rather than a hunk of memory - */ - - base = (unsigned long)freeList->list; - next = (char **)(base + freeList->offsetToNext); - freeList->list = *next; - *next = (char *) 0; - - freeList->inUseItems++; - freeList->freeItems--; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, "FreeList %06d GET %20s 0x%08x %06d %06d %s", - seq, freeList->name, base, freeList->inUseItems, - freeList->freeItems, debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - return((char *)base); -} - -/*+------------------------------------------------------------------------ - * ReturnListToFreeList() - * - * Puts an item or list of items back onto the free list. - * The last item's next pointer must be NULL. - * - * RETURNS: - * 0 if all went ok - * -1 if the given type was not found or the list was NULL - *________________________________________________________________________*/ -int DebugReturnListToFreeList( - char *list, - FreeList *freeList, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(debugMsg, "%14s, %04d", fileName, line); - return(ReturnListToFreeList(list, freeList)); -} - -int ReturnListToFreeList(char *list, FreeList *freeList) -{ - unsigned long base; - char **next; - - if(freeList == NoFreeList) - return(-1); - - if( CorruptedFreeList(freeList) ) - { - sprintf(errorString, "Corrupted free list at 0x%x", freeList); - FATAL_MESSAGE(errorString); - return(-1); - } - - if(list == (char *) 0) - return(-1); - - /* - * base will point the the base of an 'itemSize' chunk of the - * returned list - * next will point to the place where the structure element called - * 'next' would be if we were dealing with an actual user - * structure rather than a hunk of memory - */ - - base = (unsigned long)list; - next = (char **)(base + freeList->offsetToNext); - - /* - * Find the end of the user's list - */ - - while(*next != (char *) 0) - { - if(checkFree && CheckIfAlreadyFree((char *) base, freeList)) - continue; - - freeList->inUseItems--; - freeList->freeItems++; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, - "FreeList %06d FREE %20s 0x%08x %06d %06d %s", - seq, freeList->name, base, freeList->inUseItems, - freeList->freeItems, debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - base = (unsigned long) *next; - next = (char **)(base + freeList->offsetToNext); - } - - if(!(checkFree && CheckIfAlreadyFree((char *) base, freeList))) - { - freeList->inUseItems--; - freeList->freeItems++; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, "FreeList %06d FREE %20s 0x%08x %06d %06d %s", - seq, freeList->name, base, freeList->inUseItems, - freeList->freeItems, debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - *next = freeList->list; - freeList->list = list; - } - return(0); -} - -int CheckIfAlreadyFree(char *element, FreeList *freeList) -{ - unsigned long base; - char **next; - - if(freeList == NoFreeList) - return(-1); - - if( CorruptedFreeList(freeList) ) - { - sprintf(errorString, "Corrupted free list at 0x%x", freeList); - FATAL_MESSAGE(errorString); - return(-1); - } - - if(element == (char *) 0) - return(-1); - - base = (unsigned long)(freeList->list); - next = (char **)(base + freeList->offsetToNext); - - /* - * Find the end of the user's list - */ - - while(base) - { - if((char *) base == element) - return(1); - - base = (unsigned long) *next; - next = (char **)(base + freeList->offsetToNext); - } - - return(0); -} - -/*+------------------------------------------------------------------------ - * ReturnToFreeList() - * - * Puts an item back onto the free list. - * - * RETURNS: - * 0 if all went ok - * -1 if the given type was not found or the list was NULL - *________________________________________________________________________*/ -int DebugReturnToFreeList( - char *listElement, - FreeList *freeList, - const char *file, - int line) -{ - char *fileName; - - /* - * Find the file name minus the preceding path name - */ - - fileName = strrchr(file, '/'); - if(fileName == NULL) - fileName = (char *) file; - else - fileName++; - - sprintf(debugMsg, "%14s, %04d", fileName, line); - return(ReturnToFreeList(listElement, freeList)); -} - -int ReturnToFreeList( - char *listElement, - FreeList *freeList) -{ - char **next; - - if(freeList == NoFreeList) - return(-1); - - if( CorruptedFreeList(freeList) ) - { - sprintf(errorString, "Corrupted free list at 0x%x", freeList); - FATAL_MESSAGE(errorString); - return(-1); - } - - if(listElement == (char *) 0) - return(-1); - - /* - * next will point to the place where the structure element called - * 'next' would be if we were dealing with an actual user - * structure rather than a hunk of memory - */ - - if(!(checkFree && CheckIfAlreadyFree(listElement, freeList))) - { - freeList->inUseItems--; - freeList->freeItems++; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, - "FreeList %06d FREE %20s 0x%08x %06d %06d %s", - seq, freeList->name, listElement, freeList->inUseItems, - freeList->freeItems, debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - - next = (char **)(listElement + freeList->offsetToNext); - *next = freeList->list; - freeList->list = listElement; - } - - return(0); -} - -/*+--------------------------------------------------------------------- - * ReallocateFreeList() - * - * RETURNS: - * 0 if successful - * -1 if unsuccessful - *---------------------------------------------------------------------*/ - -static int ReallocateFreeList(FreeList *freeList) -{ - int i; - unsigned long base; - char **next; - - if(freeList == NoFreeList) - return(-1); - - if( CorruptedFreeList(freeList) ) - { - sprintf(errorString, "Corrupted free list at 0x%x", freeList); - FATAL_MESSAGE(errorString); - return(-1); - } - - if (freeList->list == (char *) 0) - { - freeList->list = - malloc((int)(freeList->reallocSize) * - (int)(freeList->itemSize)); - if (freeList->list == (char *) 0) - { - sprintf(errorString, - "ReallocateFreeList: Failed to allocate for list 0x%x", - freeList); - FATAL_MESSAGE(errorString); - return(-1); - } - - /* - * base will point the the base of an 'itemSize' chunk of the newly - * allocated memory area, - * next will point to the place where the structure element called - * 'next' would be if we were dealing with an actual user - * structure rather than a hunk of memory - */ - - base = (unsigned long)freeList->list; - for (i = 0 ; i < freeList->reallocSize; i++) - { - freeList->freeItems++; - - if(Debug(freelist)) - { - seq++; - sprintf(msgBuf, - "FreeList %06d REALLOC %20s 0x%08x %06d %06d %s", - seq, freeList->name, base, freeList->inUseItems, - freeList->freeItems, debugMsg); - DEBUG_MESSAGE(msgBuf); - } - - next = (char **)(base + freeList->offsetToNext); - base = (base + freeList->itemSize); - *next = (char *) base; - } - *next = (char *) 0; - - return(0); - } - return(0); -} diff --git a/src/core/src/main/c/cserver/toolLib/makefile b/src/core/src/main/c/cserver/toolLib/makefile deleted file mode 100644 index 62e7090fb..000000000 --- a/src/core/src/main/c/cserver/toolLib/makefile +++ /dev/null @@ -1,87 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Use, duplication, or disclosure by the Government is subject to -# restricted rights as set forth in the DFARS. -# -# BBNT Solutions LLC -# A Part of -# GTE -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-3000 -# -# Copyright 1999-2000 by BBNT Solutions LLC, -# A part of GTE, all rights reserved. -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/makefile,v $ -# $RCSfile: makefile,v $ -# $Revision: 1.1.1.1 $ -# $Date: 2003/02/14 21:35:48 $ -# $Author: dietrick $ -# ------------------------------------------------------------------------ - -all: libtoolLib.a - -SYSTEM_TYPE = solaris2 - -#COMPILER_HOME = /opt/SUNWspro -COMPILER_HOME = /usr/local/gnu -LDLIBS = -Bstatic -lsocket -lnsl -CXX_AR = $(COMPILER_HOME)/bin/ar rcv - -# MAC OS X ------ -#COMPILER_HOME = /usr -#LDLIBS = -Bstatic -#CXX_AR = $(COMPILER_HOME)/bin/ar -rsv -# ---------------- - -#CC = $(COMPILER_HOME)/bin/cc -CC = $(COMPILER_HOME)/bin/gcc - -CXXFLAGS = -I../../../include/cserver/toolLib - -LDFLAGS = -L. -L$(COMPILER_HOME)/lib - -OS_CXXFLAGS = $(OS_CPPFLAGS) -DSOLARIS=1 -DMULTICAST=1 \ - -DSTDC_HEADERS=1 -DHAVE_FCNTL_H=1 -DHAVE_ERRNO_H=1 \ - -DHAVE_STDLIB_H=1 -DHAVE_LIMITS_H=1 -DHAVE_UNISTD_H=1 \ - -DHAVE_SYS_STREAM_H=1 -DHAVE_SYS_UN_H=1 -DHAVE_SYS_TIME_H=1 \ - -DHAVE_TOLOWER=1 -DHAVE_STRING_H=1 -DTIME_WITH_SYS_TIME=1 - -CXXFLAGS = -I../../../include/cserver/toolLib -I/usr/openwin/include $(OS_CXXFLAGS) - -LDFLAGS = -L. -L/usr/dt/lib -L/usr/openwin/lib - -TOOLLIB.c = auto_input.c auto_output.c buffers.c error_hand.c \ - free_mgr.c sockets.c stringutil.c \ - Magic.c mapped_files.c compress.c CTag.c - -TOOLLIB.h = auto_input.h auto_output.h buffers.h compat.h \ - debugging.h error_hand.h free_mgr.h listtools.h \ - plumbing.h sockets.h stringutil.h style.h \ - Magic.h mapped_files.h compress.h - -TOOLLIB.o = ${TOOLLIB.c:.c=.o} - -libtoolLib.a: $(TOOLLIB.o) - $(CXX_AR) libtoolLib.a $(TOOLLIB.o) - mkdir -p ../../lib - cp libtoolLib.a ../../lib - -.c: - $(CC) -o $(LDFLAGS) $(CXXFLAGS) $* $*.c -.c.o: - $(CC) -c $(LDFLAGS) $(CXXFLAGS) $*.c - -# what gets removed on a "make clean" -CLEANUPS = linkserver *.o - -RM = /bin/rm -rf - -clean: - $(RM) $(CLEANUPS) - - - diff --git a/src/core/src/main/c/cserver/toolLib/mapped_files.c b/src/core/src/main/c/cserver/toolLib/mapped_files.c deleted file mode 100644 index 73064dcc3..000000000 --- a/src/core/src/main/c/cserver/toolLib/mapped_files.c +++ /dev/null @@ -1,276 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/mapped_files.c,v $ - * $RCSfile: mapped_files.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM HEADER FILES */ -#include -#include -#include -#include -#include -#include -#include -#include - -/* #define MAC_OS_X */ - -#ifdef MAC_OS_X -#define MAXINT INT_MAX -#else -#include -#endif - - -/* TOOL HEADER FILES */ -#include "compat.h" -#include "style.h" -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" -#include "error_hand.h" - -/* MATT HEADER FILES */ -#include "mapped_files.h" - -DebugVariable(mappedFiles, "MappedFiles", 0x01); - -FileEntry lruTable[LRUEntries]; -static Bool mappedInitialized = False; -static int lruTime = 0; - -static int InitMappedFiles() -{ - int i; - if(mappedInitialized) - return(0); - - if(Debug(mappedFiles)) - { - sprintf(msgBuf, - "InitMappedFiles() LRU Table has %d entries", LRUEntries); - DEBUG_MESSAGE(msgBuf); - } - - for(i = 0; i < LRUEntries; i++) - { - lruTable[i].filename[0] = '\0'; - lruTable[i].address = (char*)0; - lruTable[i].time = 0; - } - mappedInitialized = True; - - return(0); -} - -Bool FileExists(char *name) -{ - struct stat statBuf; - int result; - - result = stat(name, &statBuf); - if(result < 0) - return(False); - else - return(True); -} - -void FlushMappedFileTable() -{ - int i; - - InitMappedFiles(); - - for(i = 0; i < LRUEntries; i++) - { - if(lruTable[i].address && (lruTable[i].time != -1)) - { - munmap(lruTable[i].address, lruTable[i].size); - lruTable[i].address = (char*)0; - lruTable[i].filename[0] = '\0'; - } - } -} - -int GetMappedFileSize(char *name) -{ - int i; - - InitMappedFiles(); - - for(i = 0; i < LRUEntries; i++) - { - if(strcmp(name, lruTable[i].filename) == 0) - { - if(Debug(mappedFiles)) - { - sprintf(msgBuf, "LRU Time %d Found %s in LRU cache %d bytes", - lruTime, name, lruTable[i].size); - DEBUG_MESSAGE(msgBuf); - } - - return(lruTable[i].size); - } - } - return(-1); -} - -void CloseMappedFile(FileEntry* fe) -{ - if (Debug(mappedFiles)) - { - sprintf(msgBuf, "Pretending to close %s in LRU cache %d bytes", - fe->filename, fe->size); - DEBUG_MESSAGE(msgBuf); - } - fe->time = 1; /* just make it eligible for reuse. might prevent us from - having to reopen the file had we really closed it*/ -} - -FileEntry *FEOpenMappedFile(char *name, int auto_closable) -{ - int i; - int fd; - int result; - struct stat statBuf; - int oldestTime = MAXINT; - int oldestIndex = -1; - char *address; - - InitMappedFiles(); - - lruTime++; - - for(i = 0; i < LRUEntries; i++) - { - if(strcmp(name, lruTable[i].filename) == 0) - { - if(Debug(mappedFiles)) - { - sprintf(msgBuf, "LRU Time %d Found %s in LRU cache", - lruTime, name); - DEBUG_MESSAGE(msgBuf); - } - - if (lruTable[i].time == -1) - { - sprintf(msgBuf, "File %s already opened!", name); - WARNING_MESSAGE(msgBuf); - } else - lruTable[i].time = (auto_closable) ? lruTime : -1; - lruTable[i].currOffset = 0; - return(&lruTable[i]); - } - - if ((lruTable[i].time < oldestTime) && (lruTable[i].time != -1)) - { - oldestTime = lruTable[i].time; - oldestIndex = i; - } - } - - if(Debug(mappedFiles)) - { - if(lruTable[oldestIndex].address == (char*)0) - { - sprintf(msgBuf, - "LRU Time %d Entering %s into LRU cache in new slot %d", - lruTime, name, oldestIndex); - } - else - { - sprintf(msgBuf, "LRU Time %d Replacing (t=%d) %s with %s", - lruTime, lruTable[oldestIndex].time, - lruTable[oldestIndex].filename, name); - } - - DEBUG_MESSAGE(msgBuf); - } - - if(lruTable[oldestIndex].address) - { - munmap(lruTable[oldestIndex].address, lruTable[oldestIndex].size); - lruTable[oldestIndex].address = (char*)0; - } - - fd = open(name, O_RDONLY); - if(fd < 0) - { - if (errno != ENOENT) { /* if we fail to access the file for a reason - other than that it doesn't exist */ - sprintf(msgBuf, "Error opening %s", name); - WARNING_PERROR(msgBuf); - } else if (Debug(mappedFiles)) { - sprintf(msgBuf, "Could not map %s", name); - WARNING_PERROR(msgBuf); - } - return((FileEntry *) 0); - } - - result = fstat(fd, &statBuf); - if(result < 0) - { - if(Debug(mappedFiles)) - { - sprintf(msgBuf, "Could not access %s", name); - WARNING_PERROR(msgBuf); - } - close(fd); - return((FileEntry *) 0); - } - - address = (char *) mmap((caddr_t) 0, (int) statBuf.st_size, - PROT_READ, MAP_SHARED, fd, (off_t) 0); - close(fd); - if((int) address == -1) - { - sprintf(msgBuf, "Failed to mmap %s, %d bytes", - name, (int)statBuf.st_size); - WARNING_PERROR(msgBuf); - return((FileEntry *) 0); - } - - lruTable[oldestIndex].size = (int) statBuf.st_size; - lruTable[oldestIndex].address = address; - lruTable[oldestIndex].currOffset = 0; - lruTable[oldestIndex].time = (auto_closable) ? lruTime : -1; - strcpy(lruTable[oldestIndex].filename, name); - - return(&lruTable[oldestIndex]); -} - -char *OpenMappedFile(char *name) -{ - FileEntry* mf = FEOpenMappedFile(name, 1); - if (mf) - return mf->address; - return (char*)0; -} - -int SeekMappedFile(FileEntry* mf, long offset, int ptrname) -{ - if (ptrname == SEEK_SET) - mf->currOffset = offset; - else if (ptrname == SEEK_CUR) - mf->currOffset += offset; - else - mf->currOffset = mf->size + offset; - return 0; -} diff --git a/src/core/src/main/c/cserver/toolLib/plumbing.c b/src/core/src/main/c/cserver/toolLib/plumbing.c deleted file mode 100644 index 49492bebd..000000000 --- a/src/core/src/main/c/cserver/toolLib/plumbing.c +++ /dev/null @@ -1,682 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/plumbing.c,v $ - * $RCSfile: plumbing.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM HEADER FILES */ -#ifdef _AIX -#include -#endif -#include -#include -#include -#include -#include - -#ifdef c_plusplus -#include -#endif - -/* TOOL HEADER FILES */ -#include "compat.h" -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" -#include "style.h" -#include "error_hand.h" -#include "free_mgr.h" -#include "sockets.h" - -/* LOCAL HEADER FILES */ -#include "plumbing.h" - -DebugVariable(plumbing, "plumbing", 0x01); - -#ifdef TK -#include -#endif -/*------------------------------------------------------------------------ - * - * Deal with another event loop... - * - *------------------------------------------------------------------------*/ - -typedef enum -{ - EventMode_Plumbing, - EventMode_Tk -} EventMode; - -/* Default the event mode to Normal */ -EventMode eventMode = EventMode_Plumbing; - -/*------------------------------------------------------------------------ - * - * File Descriptor support - * - * These functions take care of hooking callback functions up to - * file descriptor events. - * - *------------------------------------------------------------------------*/ - -/* - * From sys/types.h - */ - -#define MaxFds FD_SETSIZE -#define LegalFd(fd) ((fd) >= 0 && (fd) < MaxFds) - -static int nFds = 0; -static int maxFd = 0; - -static fd_set readFds; -static fd_set writeFds; - -static int initialized = 0; - -#define TraceData (0x01) - -typedef struct _fdSupport -{ - int fd; - FdCBProc callback; - const char *callbackName; - char *clientData; - int flag; -} FdSupport; - -static FdSupport ifds[MaxFds]; -static FdSupport ofds[MaxFds]; - -static char peekBuf[16 * 1024]; - -static Bool keepLooping = True; - -void StopLoopOnFds() -{ - keepLooping = False; -} - -/* ------------------------------------------------------------------------ - * - * LoopOnFds Continuously loops on select() of the active - * file descriptors - * - * RETURNS: -1 on failure - * 0 if someone called StopLoopOnFds() - * - * ------------------------------------------------------------------------ */ - -LoopOnFds() -{ - int result = 0; - int status; - int fd; - int nBytes; - int none_read; - struct rlimit rlimit; - - struct timeval *forEver = (struct timeval *) 0; - - fd_set rFds; - fd_set wFds; - - if(initialized == 0) - return(-1); - - /* - * Assuming that no one expands the dtable size within the program! - */ - -#ifdef RLIMIT_NOFILE - getrlimit(RLIMIT_NOFILE, &rlimit); -#else - rlimit.rlim_cur = getdtablesize(); -#endif - maxFd = rlimit.rlim_cur; - - /* - * Turn the keepLooping flag on. If someone calls StopLoopOnFds(), - * we'll stop looping and fall out of here. - */ - - keepLooping = True; - - - while(keepLooping && nFds > 0) - { - /* - * Copy the master set into the local set since select(2) - * will be modifying the ones we pass in to it. - */ - - rFds = readFds; - wFds = writeFds; - -#ifdef __hpux - result = select(maxFd, (int*)&rFds, (int*)&wFds, (int *) 0, forEver); -#else - result = select(maxFd, &rFds, &wFds, (fd_set *) 0, forEver); -#endif - - /* - * returning from select may be the result of an interrupted - * system call. - */ - - if(result < 0) - { - switch(errno) - { - case EINTR: - break; - - case EBADF: - WeedOutBadFds(); - break; - - default: - break; - } - continue; - } - - if(result < 0) - { - WARNING_PERROR("Error in select call"); - return(ErrorReturn); - } - - none_read = 1; - for(fd = 0; result > 0 && fd < maxFd; fd++) - { - if(FD_ISSET(fd, &rFds)) - { - none_read = 0; - if(ifds[fd].callback != (FdCBProc) 0) - { - if(Debug(plumbing)) - { - nBytes = socket_count(fd); - sprintf(msgBuf, "Calling %s(%d...) ( %05d bytes )", - ifds[fd].callbackName, fd, nBytes); - DEBUG_MESSAGE(msgBuf); - - if(ifds[fd].flag & TraceData) - { - if(nBytes > sizeof(peekBuf)) - nBytes = sizeof(peekBuf); - socket_peek(fd, peekBuf, nBytes); - PrintTrace(fd, peekBuf, nBytes, 'I'); - } - } - status = (*(ifds[fd].callback)) (fd, ifds[fd].clientData); - if(status == ErrorReturn) - { - DisconnectInputFd(fd); - DisconnectOutputFd(fd); - } - } - else - { - sprintf(msgBuf, "Uncaught Read Select on fd %d", fd); - WARNING_MESSAGE(msgBuf); - } - result--; - } - - if(FD_ISSET(fd, &wFds)) - { - if (none_read) - { - if(ofds[fd].callback != (FdCBProc) 0) - { - if(Debug(plumbing)) - { - sprintf(msgBuf, "Calling %s(%d...)", - ofds[fd].callbackName, fd); - DEBUG_MESSAGE(msgBuf); - } - status = (*(ofds[fd].callback)) - (fd, ofds[fd].clientData); - if(status == ErrorReturn) - { - DisconnectInputFd(fd); - DisconnectOutputFd(fd); - } - } - else - { - sprintf(msgBuf, "Uncaught Write Select on fd %d", fd); - WARNING_MESSAGE(msgBuf); - } - } - result--; - } - - } - } - - return(result); -} - -int PrintTrace( - int fd, - char *buf, - int nBytes, - char direction) -{ - int i; - - if(initialized == 0) InitFds(); - - printf("Trace (%c) fd %02d:", direction, fd); - for(i = 0; i < nBytes; i++) - { - /* SUPPRESS 112 *//* CodeCenter Retrieving x from y object is z */ - printf("%02x ", (buf[i] & 0xFF)); - } - printf("\n"); - return(nBytes); -} - - -/* ------------------------------------------------------------------------ - * - * InitFds Init the file descriptor handling stuff. - * - * RETURNS: -1 on failure - * - * ------------------------------------------------------------------------ */ - -int InitFds() -{ - int fd; - - if(initialized != 0) - return(NormalReturn); - initialized = 1; - - maxFd = 0; - nFds = 0; - - FD_ZERO(&readFds); - FD_ZERO(&writeFds); - - for(fd = 0; fd < MaxFds; fd++) - { - ifds[fd].fd = -1; - ifds[fd].callback = (FdCBProc) 0; - ifds[fd].callbackName = "No Callback Defined"; - ifds[fd].clientData = (char *) 0; - ifds[fd].flag = 0; - - ofds[fd].fd = -1; - ofds[fd].callback = (FdCBProc) 0; - ofds[fd].callbackName = "No Callback Defined"; - ofds[fd].clientData = (char *) 0; - ofds[fd].flag = 0; - } - - return(0); -} - -int InitTkFds () -{ - int result; - - result = InitFds(); -#ifdef TK - eventMode = EventMode_Tk; -#endif - return result; -} - -void WeedOutBadFds() -{ - int fd; - - if(initialized == 0) InitFds(); - - for(fd = 0; fd < MaxFds; fd++) - { - if(ifds[fd].fd == -1) - { - DisconnectInputFd(fd); - } - - if(ofds[fd].fd == -1) - { - DisconnectOutputFd(fd); - } - - if(socket_test(fd) < 0) - { - DisconnectOutputFd(fd); - DisconnectInputFd(fd); - } - } -} - -void Plumbing_TkInputEvent (ClientData data, int mask) -{ -#ifdef TK - int fd, nBytes, status; - - fd = (int)data; - if (Debug(plumbing)) - { - sprintf(msgBuf, "Tk Input Event on fd %d", fd); - DEBUG_MESSAGE(msgBuf); - } - - if(ifds[fd].callback != (FdCBProc) 0) - { - if(Debug(plumbing)) - { - nBytes = socket_count(fd); - sprintf(msgBuf, "Calling %s(%d...) ( %05d bytes )", - ifds[fd].callbackName, fd, nBytes); - DEBUG_MESSAGE(msgBuf); - - if(ifds[fd].flag & TraceData) - { - if(nBytes > sizeof(peekBuf)) - nBytes = sizeof(peekBuf); - socket_peek(fd, peekBuf, nBytes); - PrintTrace(fd, peekBuf, nBytes, 'I'); - } - } - status = (*(ifds[fd].callback)) (fd, ifds[fd].clientData); - if(status == ErrorReturn) - { - DisconnectInputFd(fd); - DisconnectOutputFd(fd); - } - } -#endif -} - -/* ------------------------------------------------------------------------ - * - * ConnectInputFd() Allows user to hook a callback to input ready - * events on a file descriptor. - * - * RETURNS: The file descriptor. - * - * NOTE: Clobbers the old input fd to callback association. - * This is how you change what the callback or clientdata - * that's hung off a fd is. - * ------------------------------------------------------------------------ */ - -int ConnectInputFd( - int fd, - FdCBProc callback, - const char *callbackName, - char *clientData) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "ConnectInputFd(%d, %s, 0x%08x)", - fd, callbackName, clientData); - DEBUG_MESSAGE(msgBuf); - } - - /* - * If it's a new slot, bump up the nFds counter. - * If it's an old slot, the old guy loses but nFds stays - * the same. - */ - - if(ifds[fd].fd == -1) - nFds++; - - /* - * Keep track of the biggest one we have on hand - */ - - if(fd > maxFd) - maxFd = fd; - - /* - * Init the various fields - */ - - ifds[fd].fd = fd; - ifds[fd].callback = callback; - ifds[fd].callbackName = callbackName; - ifds[fd].clientData = clientData; - - FD_SET(fd, &readFds); - -#ifdef TK - if (eventMode == EventMode_Tk) - { - if (Debug(plumbing)) - { - sprintf(msgBuf, "Adding fd %d to TK Event list", fd); - DEBUG_MESSAGE(msgBuf); - } - Tk_CreateFileHandler(fd, TK_READABLE, Plumbing_TkInputEvent, - (ClientData)fd); - } -#endif - - return(fd); -} - -/* ------------------------------------------------------------------------ - * - * ConnectOutputFd() Allows user to hook a callback to output ready - * events on a file descriptor. - * - * RETURNS: The file descriptor. - * - * NOTE: Clobbers the old output fd to callback association. - * This is how you change what the callback or clientdata - * that's hung off a fd is. - * ------------------------------------------------------------------------ */ - -int ConnectOutputFd( - int fd, - FdCBProc callback, - const char *callbackName, - char *clientData) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "ConnectOuputFd(%d, %s, 0x%08x)", - fd, callbackName, clientData); - DEBUG_MESSAGE(msgBuf); - } - - /* - * If it's a new slot, bump up the nFds counter. - * If it's an old slot, the old guy loses but nFds stays - * the same. - */ - - if(ofds[fd].fd == -1) - nFds++; - - /* - * Keep track of the biggest one we have on hand - */ - - if(fd > maxFd) - maxFd = fd; - - /* - * Init the various fields - */ - - ofds[fd].fd = fd; - ofds[fd].callback = callback; - ofds[fd].callbackName = callbackName; - ofds[fd].clientData = clientData; - - FD_SET(fd, &writeFds); - - return(fd); -} - -int SetTraceFd( - int fd, - int direction, - int flag) -{ - if(initialized == 0) InitFds(); - - if(flag == True) - { - if(direction) - ifds[fd].flag |= TraceData; - else - ofds[fd].flag |= TraceData; - } - else - { - if(direction) - ifds[fd].flag &= ~TraceData; - else - ofds[fd].flag &= ~TraceData; - } - - return(fd); -} - -int GetTraceFd( - int fd, - int direction) -{ - if(initialized == 0) InitFds(); - - if(direction) - return(ifds[fd].flag & TraceData); - else - return(ofds[fd].flag & TraceData); -} - - -/* ------------------------------------------------------------------------ - * - * DisconnectFd() Detaches the callback from a file descriptor. - * - * RETURNS: The file descriptor. - * - * ------------------------------------------------------------------------ */ - -void DisconnectInputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "DisconnectInputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - FD_CLR(fd, &readFds); - - ifds[fd].fd = -1; - ifds[fd].callback = (FdCBProc) 0; - -#ifdef TK - if (eventMode == EventMode_Tk) - { - if (Debug(plumbing)) - { - sprintf(msgBuf, "Removing fd %d from TK Event list", fd); - DEBUG_MESSAGE(msgBuf); - } - Tk_DeleteFileHandler(fd); - } -#endif - -} - -void DisconnectOutputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "DisconnectOutputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - - FD_CLR(fd, &writeFds); - - ofds[fd].fd = -1; - ofds[fd].callback = (FdCBProc) 0; -} - -void DisableInputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "DisableInputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - FD_CLR(fd, &readFds); -} - -void EnableInputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "EnableInputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - FD_SET(fd, &readFds); -} - -void DisableOutputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "DisableOutputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - FD_CLR(fd, &writeFds); -} - -void EnableOutputFd(int fd) -{ - if(initialized == 0) InitFds(); - - if(Debug(plumbing)) - { - sprintf(msgBuf, "EnableOutputFd(%d)", fd); - DEBUG_MESSAGE(msgBuf); - } - FD_SET(fd, &writeFds); -} - - diff --git a/src/core/src/main/c/cserver/toolLib/sockets.c b/src/core/src/main/c/cserver/toolLib/sockets.c deleted file mode 100644 index 039c07f62..000000000 --- a/src/core/src/main/c/cserver/toolLib/sockets.c +++ /dev/null @@ -1,1569 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/sockets.c,v $ - * $RCSfile: sockets.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM LEVEL HEADER FILES */ -#include -#include -#ifdef _AIX -#include -#else -#include -#endif -#include -#include /* Order of these matters under Solaris */ -#include /* Order of these matters under Solaris */ -#include -#include -#if defined(_AIX) || defined(ultrix) || defined(__hpux) -#include -#else -#include -#endif -#include -#include -#include -#include - -#ifdef SVR4 -#include -#define bzero(addr, n) memset(addr, 0, n) -#define bcopy(from, to, n) memcpy(to, from, n) -#endif - -#ifdef c_plusplus -#include -#endif - -/* OTHER HEADER FILES */ -#include "compat.h" -#define DEBUG_ME "DEBUG_TOOLLIB" -#include "debugging.h" -#include "style.h" -#include "sockets.h" -#include "error_hand.h" - -DebugVariable(sockets, "sockets", 0x01); - -/* LOCAL HEADER FILES */ - -/* LOCAL FUNCTIONS */ -static int open_client_socket( - int *, /* sock */ - const char *, /* service_name */ - const char *, /* host_name */ - int, /* domain */ - int /* port */ -); - -static int open_server_socket ( - int *, /* sock */ - const char *, /* service_name */ - int, /* domain */ - int /* port */ -); - -/* Global variables */ - -#define AF AF_INET -#define SOCK_TYPE SOCK_STREAM -#define MEDIUM "tcp" - -static int domain = AF_INET; -static char message[1024]; -static int hunt_mode = 0; -static int quiet_mode = 0; - - -/* - * Look for a server on the specified host - * - * Given a service name, hostname, unis port, internet port, and - * an int pointer to put the socket number into, try to connect - * to that service on the host, or on the local host if the - * hostname is not given, preferentially by the unix port, then - * by the inet port. - * - * RETURNS: - * -1 on failure, 0 on success - */ - -int LookForServer( - const char *service, - const char *hostname, - int unixPort, - int inetPort, - int *socketp) -{ - int result; - char localhost[MAXHOSTNAMELEN + 1]; - - if(socketp == (int *) 0) - { - WARNING_MESSAGE("LookForServer called with NULL socket pointer"); - return(-1); - } - - *socketp = -1; - - if(service == (char *) 0) - { - WARNING_MESSAGE("LookForServer called with NULL service name"); - return(-1); - } - - if(Debug(sockets)) - { - sprintf(message, "LookForServer(%s, %s, %d, %d, 0x%x)", - service, hostname, unixPort, inetPort, socketp); - DEBUG_MESSAGE(message); - } - - /* - * Algorithm: - * - * If no hostname is given, try to connect to the local host via - * unix port, otherwise connect via inetPort. - * - * If hostname is given, force connection via inetPort. - * - */ - - quiet_mode = 1; - - if(strlen(hostname) == 0) - { - result = ConnectToServer(service, hostname, AF_UNIX, - unixPort, socketp); - if(result < 0) - { - result = gethostname(localhost, MAXHOSTNAMELEN); - if(result < 0) - { - WARNING_PERROR - ("Couldn't get local hostname, using 'localhost'"); - strcpy(localhost, "localhost"); - } - - result = ConnectToServer(service, localhost, AF_INET, - inetPort, socketp); - if(result < 0) - { - sprintf(msgBuf, "Could not connect to %s anywhere!", - service); - WARNING_MESSAGE(msgBuf); - quiet_mode = 0; - return(-1); - } - } - } - else - { - result = ConnectToServer(service, hostname, AF_INET, - inetPort, socketp); - if(result < 0) - { - sprintf(msgBuf, "Could not connect to %s anywhere!", - service); - WARNING_MESSAGE(msgBuf); - quiet_mode = 0; - return(-1); - } - } - - quiet_mode = 0; - return(0); -} - - -int ConnectToServer( - const char *serviceName, - const char *hostName, - int type, - int port, - int *socketp) -{ - struct servent *serverEntry = (struct servent *) 0; - char thisHost[MAXHOSTNAMELEN + 1]; - char sockname[1024]; - int result; - - /* - * UNIX connection: - * - * Build a unix socket path - * using the service name and the port - */ - - if(type == AF_UNIX) - { - sprintf(sockname, "%s/%s.%d", UnixSocketPath, serviceName, port); - result = open_unix_port(socketp, sockname, CLIENT); - if(result < 0) - { - *socketp = -1; - return(-1); - } - return(0); - } - - /* - * INET connection: - * - * If the port number is 0, try to find the port in /etc/services, - * use given port otherwise - */ - - if(hostName == (char *) 0) - { - result = gethostname(thisHost, MAXHOSTNAMELEN); - if(result < 0) - { - sprintf(message, - "ConnectToServer: no host name for internet connection"); - WARNING_PERROR(message); - *socketp = -1; - return(-1); - } - } - else - { - strncpy(thisHost, hostName, MAXHOSTNAMELEN); - } - - if(serviceName != (char *) 0 && port == 0) - { - if ((serverEntry = getservbyname (serviceName, "tcp")) != NULL) - { - port = serverEntry->s_port; - } - } - - /* - * Either we got a port number or a port was passed in to this function - * as a fallback if port is > 0 here. - */ - - if(port > 0) - { - result = open_socket_port(socketp, port, hostName, CLIENT); - if(result < 0) - { - *socketp = -1; - return(-1); - } - } - - return(0); -} - -/* ------------------------------------------------------------------------ - * - * SetupSockets - Opens the sockets/ports that it will listen to and reports - * the result to stderr/stdout. - * - * RETURNS: - * - * ------------------------------------------------------------------------ */ - - -int SetupSockets( - const char *serviceName, - int inetPort, - int unixPort, - int *inetSocketp, - int *unixSocketp) -{ - struct servent *serverEntry = (struct servent *) 0; - char sockname[1024]; - int result; - Bool doInetSocket = False; - Bool doUnixSocket = False; - - if(inetSocketp != (int *) 0) - doInetSocket = True; - - if(unixSocketp != (int *) 0) - doUnixSocket = True; - - if(doInetSocket) - { - /* - * TCP connection: - * - * If the inetPort is 0, then look up the service name in - * /etc/services to try to get a port number, otherwise use the port - * number given. - */ - - *inetSocketp = -1; - if(serviceName != (char *) 0 && inetPort == 0) - { - if ((serverEntry = getservbyname (serviceName, "tcp")) != NULL) - { - inetPort = serverEntry->s_port; - } - } - - /* - * Either we got a port number or a port was passed in to this function - * as a fallback if inetPort is > 0 here. - */ - - if(inetPort > 0) - { - result = open_socket_port(inetSocketp, inetPort, - (char *) 0, SERVER); - if(result < 0) - { - sprintf(message, "Error opening internet port %d\n", - inetPort); - WARNING_MESSAGE(message); - return(-1); - } - } - sprintf(message, "Using TCP Port %d", inetPort); - INFO_MESSAGE(message); - } - - if(doUnixSocket) - { - /* - * UNIX connection: - * - * Build a unix socket path - * using the service name and the port - */ - - *unixSocketp = -1; - - sprintf(sockname, "%s/%s.%d", UnixSocketPath, serviceName, unixPort); - unlink(sockname); - - result = open_unix_port(unixSocketp, sockname, SERVER); - if(result < 0) - { - close_socket(*inetSocketp); - - sprintf(message, "Error opening unix socket %s\n", sockname); - WARNING_MESSAGE(message); - return(-1); - } - - sprintf(message, "Using UNIX Port '%s'", sockname); - INFO_MESSAGE(message); - } - return(0); -} - - -/* ------------------------------------------------------------------------ - * - * set_hunt_mode() - * - * Turns on or off error messages when a socket is being opened on - * a port that's busy. - * - * RETURNS: - * Nothing - * - * ------------------------------------------------------------------------ */ - -void set_hunt_mode(int flag) -{ - hunt_mode = flag; -} - -/* - * set_socket_domain() - * - * Sets the domain to either AF_INET or AF_UNIX. - * - * RETURNS: - * Old Domain. - */ - -int set_socket_domain( - int newDomain) /* New domain to use */ -{ - int old = domain; - - if(newDomain != AF_UNIX && newDomain != AF_INET) - return(old); - - domain = newDomain; - return(old); -} - -/* - * open_socket() - * - * Given a service and host name open a socket connection - * to that service protocol on that host. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - */ - -int open_socket ( - int *sock, /* handle to socket id to open */ - const char *service_name, /* find /etc/services */ - const char *host_name, /* String to use as host name */ - int mode) /* SERVER or CLIENT */ -{ - int result; - int optval = 1; - int optlen; - struct protoent *tcp_proto; - - if (mode == SERVER) - result = open_server_socket (sock, service_name, domain, 0); - else - result = open_client_socket (sock, service_name, host_name, domain, 0); - - if(result != -1 && domain == AF_INET) - { - tcp_proto = getprotobyname(MEDIUM); - if(tcp_proto != NULL) - { - optlen = sizeof(optval); - optval = 1; - if (setsockopt (*sock, tcp_proto->p_proto, - TCP_NODELAY, (char *) &optval, optlen) - < 0) - { - WARNING_PERROR("Error in TCP_NODELAY setsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } - } - - if(result != -1) - set_hunt_mode(0); - - return(result); -} - -/* - * open_socket_port() - * - * Given a port and host name open a socket connection - * to that service protocol on that host. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - */ - -int open_socket_port ( - int *sock, /* handle to socket id to open */ - int port, /* port id for service */ - const char *host_name, /* String to use as host name */ - int mode) /* SERVER or CLIENT */ -{ - int result; - int optval = 1; - int optlen; - struct protoent *tcp_proto; - - if (mode == SERVER) - { - result = open_server_socket (sock, (char *) 0, domain, port); - } - else - { - result = open_client_socket (sock, (char *) 0, host_name, - domain, port); - } - - if(result != -1 && domain == AF_INET) - { - tcp_proto = getprotobyname(MEDIUM); - if(tcp_proto != NULL) - { - optlen = sizeof(optval); - optval = 1; - if (setsockopt (*sock, tcp_proto->p_proto, - TCP_NODELAY, (char *) &optval, optlen) - < 0) - { - WARNING_PERROR("Error in TCP_NODELAY setsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } - } - - return(result); -} - - -/* - * open_unix_port() - * - * Given a port and host name open a socket connection - * to that service protocol on that host. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - */ -int open_unix_port ( - int *sock, /* handle to socket id to open */ - const char *sockname, /* pathname of port to open */ - int mode) /* SERVER or CLIENT */ -{ - int result; - - if (mode == SERVER) - result = open_server_socket (sock, sockname, AF_UNIX, 0); - else - result = open_client_socket (sock, sockname, "", AF_UNIX, 0); - - return(result); -} - -/*+------------------------------------------------------------------------ - * open_client_socket() - * - * Given a service and host name open a socket connection - * to that service protocol on that host as a client of the - * service. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - * - *________________________________________________________________________*/ - -static int -open_client_socket( - int *sock, /* handle to socket id to open */ - const char *service_name,/* find in /etc/services */ - const char *host_name, /* String containing host name */ - int domain, /* AF_UNIX or AF_INET */ - int port) /* Port # if service name is NULL */ -{ - int optval; - int optlen; - struct hostent *host_entry = (struct hostent *) 0; - struct servent *server_entry = (struct servent *) 0; - struct sockaddr_in connect_addr; - struct sockaddr_un unix_addr; - int result; - - if(sock == NULL) - { - WARNING_MESSAGE("open_client_socket called with NULL sock"); - return(-1); - } - - if(service_name == NULL && port == 0) - { - WARNING_MESSAGE("open_client_socket called with NULL service_name and bad port number"); - return(-1); - } - - if(host_name == NULL) - { - WARNING_MESSAGE("open_client_socket called with NULL host_name"); - return(-1); - } - - if(domain == AF_INET) - { - if(service_name != (char *) 0) - { - if ((server_entry = getservbyname (service_name, "tcp")) == NULL) - { - sprintf(message, - "Couldn't get service entry for %s", service_name); - WARNING_PERROR(message); - return (-1); - } - } - - if ((host_entry = gethostbyname (host_name)) == NULL) - { - sprintf(message, "Couldn't get host entry for %s", host_name); - WARNING_PERROR(message); - return (-1); - } - - /* Check the host entry for validity */ - if (host_entry->h_addrtype != AF_INET) - { - sprintf(message, - "Got unexpected address type %d in host entry.", - host_entry->h_addrtype); - WARNING_PERROR(message); - return (-1); - } - - - *sock = socket (domain, SOCK_TYPE, getprotobyname (MEDIUM)->p_proto); - - if (*sock < 0) - { - WARNING_PERROR("Error in socket call"); - return (-1); - } - - optlen = sizeof(optval); - if (getsockopt (*sock, SOL_SOCKET, SO_REUSEADDR, - (char *) &optval, &optlen) < 0) - { - WARNING_PERROR("Error in REUSEADDR getsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - - if(optval == 0) - { - optval = 1; - if (setsockopt (*sock, SOL_SOCKET, SO_REUSEADDR, - (char *) &optval, optlen) - < 0) - { - WARNING_PERROR("Error in REUSEASSR setsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } - - -#ifdef PLEASE_DONT_ROUTE - optlen = sizeof(optval); - if (getsockopt (*sock, SOL_SOCKET, SO_DONTROUTE, &optval, &optlen) < 0) - { - WARNING_PERROR("Error in DONTROUTE getsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - - if(optval == 0) - { - optval = 1; - if (setsockopt (*sock, SOL_SOCKET, SO_DONTROUTE, &optval, optlen) - < 0) - { - WARNING_PERROR("Error in DONTROUTE setsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } -#endif - - /* Get ready to establish the socket and bind to it */ - bzero ((char *) &connect_addr, sizeof (connect_addr)); - bcopy (host_entry->h_addr, (char *) &connect_addr.sin_addr, - host_entry->h_length); - connect_addr.sin_family = host_entry->h_addrtype; - if(server_entry != (struct servent *) 0) - { - /* Don't know if this is net or host order */ - connect_addr.sin_port = server_entry->s_port; - } - else - { - connect_addr.sin_port = htons((short)port); - } - - do - { - result = connect (*sock, - (struct sockaddr *) &connect_addr, - sizeof (connect_addr)); - } while(result == -1 && (errno == EINTR)); - - if(result == -1) - { - WARNING_PERROR("Error in connect call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } - else - { - *sock = socket (AF_UNIX, SOCK_STREAM, 0); - if (*sock < 0) - { - WARNING_PERROR("Error creating UNIX socket"); - return(-1); - } - - unix_addr.sun_family = AF_UNIX; - if(service_name == (char *) 0) - { - sprintf(unix_addr.sun_path, "%d", port); - } - else - { - strncpy(unix_addr.sun_path, service_name, - sizeof(unix_addr.sun_path) - 1); - unix_addr.sun_path[sizeof(unix_addr.sun_path) - 1] = '\0'; - } - - if(connect(*sock, (struct sockaddr *) &unix_addr, - sizeof(unix_addr)) < 0) - { - if(quiet_mode == 0) - WARNING_PERROR("Error connecting to socket"); - if(close(*sock) < 0 && quiet_mode == 0) - WARNING_PERROR("Error in socket close"); - return(-1); - } - } - - return (0); -} - -/*+------------------------------------------------------------------------ - * open_server_socket() - * - * Given a service and host name open a socket connection - * to that service protocol on that host as a provider of the - * service. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - * - *________________________________________________________________________*/ - -static int -open_server_socket ( - int *sock, /* handle to socket id to open */ - const char *service_name, /* find in /etc/services */ - int domain, /* AF_UNIX or AF_INET */ - int port) /* Port number */ -{ - int optval; - int optlen; - - struct servent *server_entry = (struct servent *) 0; - struct sockaddr_in connect_addr; - struct sockaddr_un unix_addr; - - if(sock == NULL) - { - WARNING_MESSAGE("open_server_socket called with NULL sock"); - return(-1); - } - - if(service_name == NULL && port == 0) - { - WARNING_MESSAGE("open_server_socket called with NULL service_name and bad port"); - return(-1); - } - - if(domain == AF_INET) - { - if(service_name != (char *) 0) - { - server_entry = getservbyname (service_name, "tcp"); - if (server_entry == NULL) - { - sprintf(message, - "Couldn't get service entry for %s", service_name); - WARNING_PERROR(message); - return (-1); - } - } - /* Get ready to establish the socket and bind to it */ - - /* Clear the structure first */ - bzero ((char *) &connect_addr, sizeof (connect_addr)); - - /* Fill in the port entry */ - if(server_entry == (struct servent *) 0) - { - connect_addr.sin_port = htons((short)port); - } - else - { - /* Don't know if this is host or net order */ - connect_addr.sin_port = server_entry->s_port; - } - - *sock = socket (domain, SOCK_TYPE, getprotobyname (MEDIUM)->p_proto); - - if (*sock < 0) - { - WARNING_PERROR("Error in socket call"); - return (-1); - } - - optlen = sizeof(optval); - if (getsockopt (*sock, SOL_SOCKET, SO_REUSEADDR, - (char *) &optval, &optlen) < 0) - { - WARNING_PERROR("Error in getsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - - if(optval == 0) - { - optval = 1; - if (setsockopt (*sock, SOL_SOCKET, SO_REUSEADDR, - (char *) &optval, optlen) - < 0) - { - WARNING_PERROR("Error in setsockopt call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - } - - if (bind (*sock, (struct sockaddr *) &connect_addr, - sizeof (connect_addr)) < 0) - { - if(!hunt_mode) - WARNING_PERROR("Error in bind call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return (-1); - } - - } - else - { - *sock = socket (AF_UNIX, SOCK_STREAM, 0); - if(*sock < 0) - { - WARNING_PERROR("Error opening UNIX socket"); - return(-1); - } - - unix_addr.sun_family = AF_UNIX; - if(service_name == (char *) 0) - { - sprintf(unix_addr.sun_path, "%d", port); - } - else - { - strncpy(unix_addr.sun_path, service_name, - sizeof(unix_addr.sun_path) - 1); - unix_addr.sun_path[sizeof(unix_addr.sun_path) - 1] = '\0'; - } - - if (bind (*sock, (struct sockaddr *) &unix_addr, - sizeof (unix_addr)) < 0) - { - if(!hunt_mode) - WARNING_PERROR("Error in bind call"); - if(close(*sock) < 0) - WARNING_PERROR("Error in socket close"); - return(-1); - } - } - - if (listen (*sock, 5) < 0) - { - WARNING_PERROR("Error in listen call"); - close_socket(*sock); - return (-1); - } - - return (0); -} - -/*+------------------------------------------------------------------------ - * close_socket() - * - * shut down a socket connection - * - * RETURNS: - * 0 if it closes OK - * -1 if not. - *________________________________________________________________________*/ - -int close_socket (int sock) /* Socket ID to close */ - -{ - int result; - - if (shutdown (sock, 2) < 0) - { - DEBUG_MESSAGE("Error in socket shutdown"); - /* This is ok, still has to be closed */ - } - - do - { - result = close(sock); - } while(result == -1 && errno == EINTR); - - if(result < 0) - { - WARNING_PERROR("Error in socket close"); - return(-1); - } - - return (0); -} - -/*+------------------------------------------------------------------------ - * accept_socket() - * - * Given a socket id, accept a connection to that socket and - * return a new socket id specific to that connection. - * - * RETURNS: - * 0 if all went ok - * -1 if not. - *________________________________________________________________________*/ - -static char lastHostAccepted[256]; -static int lastHostInitialized = 0; - -char *LastHostAccepted() -{ - if(lastHostInitialized) - return(lastHostAccepted); - else - return("NoConnectionAcceptedYet"); -} - -int accept_socket ( - int sock, /* Socket to accept from */ - int *new_socket) /* Put new socket number here */ -{ - struct sockaddr_in socket_address; - int socket_address_length; - struct hostent *connectingHost = (struct hostent *) 0; - - if(new_socket == NULL) - { - WARNING_MESSAGE("accept_socket called with NULL new_socket"); - return(-1); - } - - socket_address_length = sizeof (socket_address); - - do - { - *new_socket = accept (sock, - (struct sockaddr *) &socket_address, - &socket_address_length); - } while (*new_socket ==-1 && errno == EINTR); - - if (*new_socket < 0) - { - WARNING_PERROR("Accept failed on socket"); - return (-1); - } - - if(socket_address.sin_family == AF_INET) - { - connectingHost = gethostbyaddr((char *) &socket_address.sin_addr, - sizeof(struct in_addr), AF_INET); - - - if(connectingHost != (struct hostent *) 0) - { - if(connectingHost->h_name != (char *) 0) - { - strncpy(lastHostAccepted, connectingHost->h_name, - sizeof(lastHostAccepted) - 1); - lastHostAccepted[sizeof(lastHostAccepted) - 1] = '\0'; - lastHostInitialized = 1; - } - else - { - strcpy(lastHostAccepted, "UnknownHostName"); - lastHostInitialized = 1; - } - } - else - { - strcpy(lastHostAccepted, "UnknownInternetHost"); - lastHostInitialized = 1; - } - } - else if(socket_address.sin_family == AF_UNIX) - { - gethostname(lastHostAccepted, sizeof(lastHostAccepted) - 1); - lastHostAccepted[sizeof(lastHostAccepted) - 1] = '\0'; - lastHostInitialized = 1; - } - else - { - strcpy(lastHostAccepted, "UnknownNetwork/Host"); - lastHostInitialized = 1; - } - - return (0); -} - - -/*------------------------------------------------------------------------ - * socket_receive() - * - * Tries to receive a buffer full of stuff from a file descriptor - * - * RETURNS: - * -1 if error - * number of bytes received if no error - *________________________________________________________________________*/ - -int socket_receive( - int fd, /* File descriptor */ - void *buf, /* Data buffer to use */ - int nbytes) /* # of bytes to get */ -{ - int bytes_to_receive = nbytes; - int bytes_received = 0; - char *receive_pointer = buf; - int result; - - if(buf == NULL) - { - /* - * Fake an invalid address system error. - */ - errno = EINVAL; - WARNING_MESSAGE("socket_receive called with NULL buf"); - return(-1); - } - - do - { - do - { - result = read(fd, receive_pointer, bytes_to_receive); - } while(result == -1 && errno == EINTR); - - if(result != -1) - { - receive_pointer += result; - bytes_received += result; - bytes_to_receive -= result; - } - /* - * Why did I have this here??? - * - * if(result == -1 && errno == EINTR) - * fprintf(stderr, "receive_remote_data EINTR\n"); - */ - } while(bytes_received < nbytes && result > 0); - /* - * And why was this part of the while condition??? - * || (result == -1 && errno == EPIPE)); - */ - - if(result <= 0) - { - if (Debug(sockets)) - { - sprintf(message, - "Error trying to receive %d bytes, received %d, result was %d", - nbytes, bytes_received, result); - if(result == -1) - WARNING_PERROR(message); - else - WARNING_MESSAGE(message); - } - return(result); - } - return(bytes_received); -} - -/*------------------------------------------------------------------------ - * socket_nb_receive() - * - * Tries to receive a buffer full of stuff from a file descriptor - * - * RETURNS: - * negative if error, 0 if EOF, positive if success. - * - * AND, in bytes_received, the number of bytes read on the file. - *________________________________________________________________________*/ - -int socket_nb_receive( - int fd, /* File descriptor */ - void *buf, /* Data buffer to use */ - int nbytes, /* # of bytes to get */ - int *bytes_received) /* # of bytes read */ -{ - int bytes_to_receive = nbytes; - char *receive_pointer = buf; - int result; - - if (bytes_received == (int *)0) - { - /* Null pointer! Error! */ - errno = EINVAL; - WARNING_PERROR("socket_nb_receive called with bad bytes_recvd ptr."); - return(-1); - } - - (*bytes_received) = 0; - - if(buf == NULL) - { - /* - * Fake an invalid address system error. - */ - errno = EINVAL; - WARNING_PERROR("socket_nb_receive called with NULL buf"); - return(-1); - } - - do - { - do - { - result = read(fd, receive_pointer, bytes_to_receive); - } while(result == -1 && errno == EINTR); - - if(result > 0) - { - receive_pointer += result; - (*bytes_received) += result; - bytes_to_receive -= result; - } - - if (result == 0) - return 0; - - } while((*bytes_received) < nbytes && result > 0); - - if(result < 0 && errno != EWOULDBLOCK) - { - sprintf(message, - "Error trying to receive %d bytes, received %d, result was %d", - nbytes, (*bytes_received), result); - if(result == -1) - WARNING_PERROR(message); - else - WARNING_MESSAGE(message); - - return(result); - } - - return(1); -} - -/*------------------------------------------------------------------------ - * socket_peek() - * - * Tries to receive a buffer full of stuff from a client. - * Does not actually take the data off the socket. - * - * RETURNS: - * -1 if error - * number of bytes received if no error - *________________________________________________________________________*/ - -int socket_peek( - int fd, /* Socket to peek at */ - void *buf, /* Data buffer to use */ - int nbytes) /* # of bytes to get */ -{ - int result; - - if(buf == NULL) - { - /* - * Fake an invalid address system error. - */ - errno = EINVAL; - WARNING_PERROR("socket_peek called with NULL buf"); - return(-1); - } - - do - { - result = recv(fd, buf, nbytes, MSG_PEEK); - } while (result == -1 && errno == EINTR); - - if(result == -1) - { - sprintf(message, - "socket_peek(): socket connection error, fd = %d ", - fd); - WARNING_PERROR(message); - } - - return(result); -} - -/*------------------------------------------------------------------------ - * socket_test() - * - * Tries to see if the socket is still open - * Must have a SIGPIPE handler installed for this to work. - * - * RETURNS: - * 1 if socket is open - * -1 if error - *________________________________________________________________________*/ - -int socket_test( - int fd) /* Socket to test */ -{ - int result; - char dummy; - - do - { - result = recv(fd, &dummy, 1, MSG_PEEK); - } while(result == -1 && errno == EINTR); - - if(result > 0 || result == -1 && errno == EWOULDBLOCK) - return(1); - - - return(-1); -} - -/*------------------------------------------------------------------------ - * socket_count() - * - * Tries to return the number of bytes waiting at the socket. - * - * RETURNS: - * -1 if error - * number of bytes ready if no error - *________________________________________________________________________*/ - -int socket_count(int fd) /* Socket to count bytes on */ -{ - int result; - int nbytes; - - result = ioctl(fd, FIONREAD, &nbytes); - if(result == -1) - { - sprintf(message, - "socket_count(): ioctl FIONREAD error, fd = %d ", - fd); - WARNING_PERROR(message); - return(-1); - } - - return(nbytes); -} - -/*------------------------------------------------------------------------ - * socket_send() - * - * Tries to send a buffer full of stuff to a file descriptor - * If a SIGPIPE error occurs and there is no handler for it, - * the program exits without warning!!! - * - * RETURNS: - * -1 if error - * number of bytes sent if no error - *________________________________________________________________________*/ - -int socket_send( - int fd, /* File descriptor */ - void *buf, /* Data buffer to use */ - int nbytes) /* # of bytes to get */ -{ - int bytes_to_send = nbytes; - int bytes_sent = 0; - char *send_pointer = buf; - int result; - int chunk_size; - - if(buf == NULL) - { - /* - * Fake an invalid address system error. - */ - errno = EINVAL; - WARNING_PERROR("socket_send called with NULL buf"); - return(-1); - } - - do - { - if(bytes_to_send > 4096) - chunk_size = 4096; - else - chunk_size = bytes_to_send; - - do - { - result = write(fd, send_pointer, chunk_size); - } while(result == -1 && errno == EINTR); - - if(result != -1) - { - send_pointer += result; - bytes_sent += result; - bytes_to_send -= result; - } - - } while(bytes_sent < nbytes && result > 0 ); - - if(result <= 0) - { - sprintf(message, - "Error trying to send %d bytes, sent %d, result was %d", - nbytes, bytes_sent, result); - if(result == -1) - WARNING_PERROR(message); - else - WARNING_MESSAGE(message); - - return(result); - } - return(bytes_sent); -} - - -/*------------------------------------------------------------------------ - * socket_nb_send() - * - * Tries to send a buffer full of stuff to a file descriptor - * If a SIGPIPE error occurs and there is no handler for it, - * the program exits without warning!!! - * - * Non-blocking version of socket_send - * - * RETURNS: - * -1 if error - * number of bytes sent if no error - *________________________________________________________________________*/ - -int socket_nb_send( - int fd, /* File descriptor */ - void *buf, /* Data buffer to use */ - int nbytes) /* # of bytes to get */ -{ - int bytes_to_send = nbytes; - int bytes_sent = 0; - char *send_pointer = buf; - int result; - int chunk_size; - - if(buf == NULL) - { - /* - * Fake an invalid address system error. - */ - errno = EINVAL; - WARNING_PERROR("socket_send called with NULL buf"); - return(-1); - } - - do - { - if(bytes_to_send > 4096) - chunk_size = 4096; - else - chunk_size = bytes_to_send; - - do - { - result = write(fd, send_pointer, chunk_size); - } while(result == -1 && errno == EINTR); - - if(result != -1) - { - send_pointer += result; - bytes_sent += result; - bytes_to_send -= result; - if(result < chunk_size) - { - return(bytes_sent); - } - } - - if(result < 0 && errno == EWOULDBLOCK) - { - return(bytes_sent); - } - - } while(bytes_sent < nbytes && result > 0 ); - - if(result <= 0) - { - sprintf(message, - "Error trying to send %d bytes, sent %d, result was %d", - nbytes, bytes_sent, result); - if(result == -1) - WARNING_PERROR(message); - else - WARNING_MESSAGE(message); - - return(result); - } - return(bytes_sent); -} - - -/* ------------------------------------------------------------------------ - * - * socket_control() - * - * Set or clear the control flags available via the ioctl SETFL/GETFL - * calls - * - * RETURNS: -1 on error - * - * ------------------------------------------------------------------------ */ - -int socket_control( - int fd, /* Socket to control */ - int whichFlag, /* Which flag to set/clear */ - int what) /* True = set, False = clear */ -{ - int result; - int oldFlags; - - oldFlags = fcntl(fd, F_GETFL, 0); - - if(oldFlags < 0) - { - sprintf(message, "Error getting fcntl flags for fd %d", fd); - WARNING_PERROR(message); - return(oldFlags); - } - - if(what == True) - { - oldFlags |= whichFlag; - } - else - { - oldFlags &= ~whichFlag; - } - - result = fcntl(fd, F_SETFL, oldFlags); - if(result < 0) - { - sprintf(message, "Error setting fcntl flags for fd %d", fd); - WARNING_PERROR(message); - return(result); - } - - return(oldFlags); -} - -char *ConnectedInternetAddress(int fd) -{ - struct sockaddr_in name; - int namelen = sizeof(name); - char hostname[256]; - int result; - - result = getpeername(fd, (struct sockaddr *) &name, &namelen); - if(result < 0) - { - sprintf(msgBuf, "Error getting internet address of socket %d", fd); - WARNING_PERROR(msgBuf); - return((char *) 0); - } - - if(name.sin_family == AF_INET) - { - return(inet_ntoa(name.sin_addr)); - } - else - { -#if !defined(READY_FOR_PRIME_TIME) - return("127.0.0.1"); -#else - result = gethostname(hostname, sizeof(hostname)); - if(result < 0) - { - WARNING_PERROR("Error getting host name of local host"); - return((char *) 0); - } - - if ((host_entry = gethostbyname (hostname)) == NULL) - { - sprintf(message, "Couldn't get host entry for %s", hostname); - WARNING_PERROR(message); - return ((char *) 0); - } - - /* Check the host entry for validity */ - if (host_entry->h_addrtype != AF_INET) - { - sprintf(message, - "Got unexpected address type %d in host entry.", - host_entry->h_addrtype); - WARNING_PERROR(message); - return ((char *) 0); - } - - if(host_entry->h_addr_list && *(host_entry->h_addr_list)) - { - return(inet_ntoa(host_entry->h_addr_list[0].sin_addr)) - } -#endif - } -} - -char *ConnectedHostname(int fd) -{ - struct sockaddr_in name; - struct hostent *host_entry; - int namelen = sizeof(name); - int result; - - result = getpeername(fd, (struct sockaddr *) &name, &namelen); - if(result < 0) - { - sprintf(msgBuf, "Error getting internet address of socket %d", fd); - WARNING_PERROR(msgBuf); - return((char *) 0); - } - - if(name.sin_family == AF_INET) - { - host_entry = gethostbyaddr((char *) &name.sin_addr, - sizeof(struct in_addr), AF_INET); - if(host_entry) - { - return(host_entry->h_name); - } - else - { - sprintf(msgBuf, "Error getting internet name of socket %d", fd); - WARNING_MESSAGE(msgBuf); - return((char *) 0); - } - } - else - { - return("localhost"); - } -} diff --git a/src/core/src/main/c/cserver/toolLib/stringutil.c b/src/core/src/main/c/cserver/toolLib/stringutil.c deleted file mode 100644 index 1c94a0e59..000000000 --- a/src/core/src/main/c/cserver/toolLib/stringutil.c +++ /dev/null @@ -1,608 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/src/stringutil.c,v $ - * $RCSfile: stringutil.c,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* SYSTEM LEVEL HEADER FILES */ -#include -#include -#include -#include - -/* #define MAC_OS_X */ - -#ifndef MAC_OS_X -#include -#endif - -#include -#include - -/* OTHER HEADER FILES */ -#include "compat.h" -#include "stringutil.h" -#include "style.h" - -/* - * Find a string in a list given an index - * - * RETURNS: - * A pointer to a character string. - * If the list did not contain the - * index, it returns the third argument. - */ - -char *LookupString(int index, /* The integer to look up */ - StringList *list, /* The list to look it up in */ - char *defaultString) /* Return this if not found */ -{ - if(list == NoStringList) - return((char *) 0); - - while(list->string != (char *) 0) - { - if(list->index == index) - return(list->string); - list++; - } - return(defaultString); -} - - -/* - * Does the opposite of LookupString() - * - * RETURNS: - * The first index within the list where the string is found - */ -int LookupIndex( - char *s, /* Look up this string */ - StringList *list, /* Use this list */ - int notFound) /* Return this if not found */ -{ - while(list->string != (char *) 0) - { - if(strcmp(list->string, s) == 0) - return(list->index); - list++; - } - return(notFound); -} - -/* - * Find a string in a list given an index - * - * Format the output into a string - * - * RETURNS: - * a pointer to a character string. - * If the list did not contain the - * index, it returns the third argument. - */ -char *FLookupString(char *resultString, /* The place to format to */ - int index, /* The integer to look up */ - StringList *list, /* The list to look in */ - char *string, /* The default if not found */ - int width, /* How wide the field is */ - int justification) /* Left or right */ -{ - if(list == NoStringList - || resultString == (char *) 0 || string == (char *) 0) - return((char *) 0); - - while(list->string != (char *) 0) - { - if(list->index == index) - { - sprintf(resultString, - "%*s", - width * justification, - list->string); - - return(resultString); - } - list++; - } - - if(width > (int) strlen(string)) - width -= strlen(string); - - sprintf(resultString, - "%s%*d", - string, - width * justification, - index); - - return(resultString); -} - - -/* - * Print out an array of text strings. - * - * Newlines are appended to end of each line. - * Last string must be NULL - * - * RETURNS: - * Nothing - */ - -void PrintText(FILE *stream, /* Where to put the resulting text */ - char **text)/* The text, as a list of strings */ -{ - if(stream == (FILE *) 0 || text == (char **) 0 || *text == (char *) 0) - return; - - while((*text != (char *) 0) && (*text[0] != '\0')) - fprintf(stream, "%s\n", *text++); -} - - -/* - * Find the next non-blank character in a string - * - * Returns a pointer to the next non-blank character in the string - * where blank is defined as space or tab. - * - * RETURNS: - * Pointer to the first non-blank character, null pointer if - * none found - */ -char *NextNonblank(char *s) /* The string to look in */ -{ - int temp; - - if(s == (char *) 0) - return((char *) 0); - - temp = strspn(s, " \t"); - - if(temp > (int) strlen(s)) - return((char *) 0); - - return(&s[temp]); -} - - - -/* - * Do the equivalent of basename(1) - * - * Find the base name of the string (i.e. strip off the leading - * directory names in a pathname). - * - * RETURNS: - * pointer to the beginning of the base name. - */ -const char *Basename(const char *s) /* The string to look in */ -{ - const char *filePart; - - if(s == (char *) 0) - return((char *) 0); - - filePart = strrchr(s, '/'); - - if(filePart == (char *) 0) - return(s); - - return(filePart); -} - - - -/* - * Returns the length of the ascii string pointed to by "token". - * - * RETURNS: - * how many characters the token has - * 0 if the first char is whitespace or null - * or if the token ptr is null. - * - */ -int TokenLength(char *token) /* The token to look at */ -{ - int length = 0; - - if (token == (char *) 0) - return (0); - - while(*token && !isspace(*token) ) - { - length++; - token++; - } - return(length); -} - -/* - * Find a token - * - * The token is defined to begin with the first non-blank character - * in s, up through the last non-blank character in s that - * comes before the first occurrence of the separator or \n or \0 in s. - * - * RETURNS: - * Ptr to the token and sets whatever lengthp points to - * to the length of the token. - * .LP - * If lengthp is NULL, returns ptr to statically allocated "" - * If s is NULL, returns ptr to statically allocated "" - * If token is zero long, returns ptr. - * .LP - * separatorp gets set to point at the separator. - * - */ - -char *GetTokenFromString(char *s, /* The string to tokenize */ - char separator, /* The separator character (i.e. : or \t) */ - int *lengthp, /* Length of token returned through this */ - char **separatorp) /* Pointer to next separator found - * i.e. starting point for next call */ -{ - static char *nullToken = ""; - int done = FALSE; - char *first; - char *last; - char *sep; - int length = 0; - - /* - * Check the args for null pointers, - */ - - if(lengthp == (int *) 0) - { - if(separatorp) - *separatorp = s; - return (nullToken); - } - - if(s == (char *) 0 || *s == '\0') - { - *lengthp = 0; - if(separatorp) - *separatorp = s; - return(s); - } - - if(*lengthp == -1) - { - /* - * Figure out how long the token is, even the leading - * whitespace. We'll get to the whitespace later. - * If we try to strip whitespace now, and the separator - * character is ' ' or '\t', we do the wrong thing. - */ - - sep = s; - while(*sep && !done) - { - if(*sep == separator || *sep == '\n') - { - done = TRUE; - } - else - { - length++; - sep++; - } - } - } - else - { - length = *lengthp; - sep = s + length; - } - - /* - * sep points to the separator, - * Now move backwards to find the last real char of the token. - */ - - *separatorp = sep; - - /* - * If the separator was at the beginning, sep will be at s - */ - - if(sep == s) - { - *lengthp = 0; - return(s); - } - - /* - * If we get to here, then there was at least on character - * before the separator. Point 'first' at the beginning. - * Point 'last' at the end. - */ - - first = s; - last = sep - 1; - - /* - * Move first toward last, as long as they have not met - * and as long as first points to a piece of whitespace. - * - * Then back last up toward first... - */ - - while(first < last && isspace(*first)) - first++; - - while(first < last && isspace(*last)) - last--; - - /* - * If first and last point to the same spot, and that - * spot is no whitespace, then the length is 1. - * Otherwise the length is zero. - */ - - if(first == last) - { - if(isspace(*first)) - *lengthp = 0; - else - *lengthp = 1; - return(first); - } - - /* - * Compute the length from first and last and - * return the pointer to the beginning of the token. - * - * The length is (last - first) + 1 since if first is 1 - * and last is 2, then there are two characters in the string... - */ - - *lengthp = (last - first) + 1; - return(first); -} - - -/* - * Turn a string into its lowercase equivalent (in place). - * - * RETURNS - * Pointer to the same string, but now lower case letters - * - */ - -char *Lowercase(char *str) /* The string to convert */ -{ - char *temp = str; - - if(str) - { - while(*str) - { - *str = tolower(*str); - str++; - } - } - return(temp); -} - - -/* - * Looks for the occurrence of a word within a string - * - * RETURNS - * Null pointer if not found, pointer withing string if found. - * - */ - -char *FindWord(char *word, /* Look for this word */ - char *string) /* Look in this string */ -{ - char *temp = string; - int wlength; - int slength; - - if(string == (char *) 0 || word == (char *) 0) - return((char *) 0); - - if(*word == '\0' || *string == '\0') - return((char *) 0); - - wlength = strlen(word); - slength = strlen(string); - - while(*temp && slength >= wlength) - { - if(strncmp(temp, word, wlength) == 0) - return(temp); - - temp++; - slength--; - } - - return((char *) 0); -} - - -char *NormalizePath(char *path) -{ - int i, f, x; - char path0; - - if(path == (char *) 0) - return(path); - - path0 = path[0]; - - /* Collapse all the /./ and /.(null) combos */ - for(i = 0; i < (int) strlen(path); i++) - { - if(path[i] == '/' - && (path[i+1] && path[i+1] == '.') - && ((path[i+2] && path[i+2] == '/') - || path[i+2] == '\0')) - { - for(x=i, f = i+2, i=x-1; f <= (int) strlen(path); x++, f++) - path[x] = path[f]; - if(i < 0) i++; - } - } - - /* Collapse all the // and /(null) combos */ - for(i = 0; i < (int) strlen(path); i++) - { - if(path[i] == '/' - && ((path[i+1] && path[i+1] == '/') - || path[i+1] == '\0')) - { - for(x=i, f = i+1, i=x-1; f <= (int) strlen(path); x++, f++) - path[x] = path[f]; - if(i < 0) i++; - } - } - - /* Collapse all the /../ and /..(null) combos */ - for(i = 0; i < (int) strlen(path); i++) - { - if (path[i] == '/' - && (path[i+1] && path[i+1] == '.') - && (path[i+2] && path[i+2] == '.') - && ((path[i+3] && path[i+3] == '/') - || path[i+3] == '\0')) - { - for(x = i-1; x >= 0; x--) - { - if(path[x] == '/') - { - for(f = i+3,i=x-1; f <= (int) strlen(path); x++, f++) - path[x] = path[f]; - if(i < 0) i++; - break; - } - } - } - } - - if(path[0] == '\0' && path0 == '/' || strcmp(path, "/..") == 0) - strcpy(path, "/"); - - return (path); -} - - -char *ExecDir(char *path, - char *argv0) -{ - char *temp; - char *p; - int result; - char cwd[MAXPATHLEN]; - static char dirbuf[MAXPATHLEN]; - static char *dir; - struct stat statbuf; - - /* reset the pointer */ - dir = (char *) 0; - - /* If it starts with '/', then it's already an absolute path */ - if(argv0[0] == '/') - { - /* If it's too long to fit, then return error */ - if((int) strlen(argv0) < MAXPATHLEN) - { - strcpy(dirbuf, argv0); - dir = dirbuf; - } - return(dir); - } - - temp = strdup(path); - if(temp == (char *) 0) - return(dir); - - p = strtok(temp, ":"); - - while(p && dir == (char *) 0) - { - if((int) (strlen(p) + strlen(argv0)) + 2 > MAXPATHLEN) - return((char *) 0); - - sprintf(dirbuf, "%s/%s", p, argv0); - result = stat(dirbuf, &statbuf); - if(result >= 0) - { - if(S_ISREG(statbuf.st_mode) - && ((statbuf.st_mode & S_IXUSR) - || (statbuf.st_mode & S_IXGRP) - || (statbuf.st_mode & S_IXOTH))) - { - dir = dirbuf; - } - } - - p = strtok((char *) 0, ":"); - } - - if(temp) free(temp); - - if(dir && dirbuf[0] != '/') - { -#ifdef SVR4 - getcwd(cwd, sizeof(cwd) - 1); -#else - getwd(cwd); -#endif - - if((int) (strlen(dirbuf) + strlen(cwd)) + 2 > MAXPATHLEN) - { - dir = (char *) 0; - return(dir); - } - - strcat(cwd, "/"); - strcat(cwd, dirbuf); - strcpy(dirbuf, cwd); - } - - return(NormalizePath(dir)); -} - - -char *SetEnvVar(char *name, char *value) -{ - char *temp = (char *) 0; - int len; - - len = strlen(name) + strlen(value) + 2; - temp = malloc(len); - - if(temp != (char *) 0) - { - sprintf(temp, "%s=%s", name, value); - - if(putenv(temp) != 0) - { - return((char *) 0); - } - } - - return(temp); -} - diff --git a/src/core/src/main/include/cserver/link/ActionRequest.h b/src/core/src/main/include/cserver/link/ActionRequest.h deleted file mode 100644 index f993cea32..000000000 --- a/src/core/src/main/include/cserver/link/ActionRequest.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/ActionRequest.h,v $ - * $RCSfile: ActionRequest.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef ACTIONREQUEST_H -#define ACTIONREQUEST_H - -#include "Request.h" -#include "LinkArgs.h" -#include "LinkSocket.h" - -struct LinkString; - -/* - This Object provides structures and functions for reading - Action Objects from Link. -*/ - -/** - * The MouseEvent. - * - * @param x Horizontal location of the event on the map, measured from the top left corner, in pixels. - * @param y Vertical location of the event on the map, measured from the top left corner, in pixels. - * @param clickcount The number of times the mouse is clicked. - * @param modifier Modifiers associated with MouseEvents. - * @param latitude The latitude of the MouseEvent, in decimal degrees. - * @param longitude The longitude of the MouseEvent, in decimal degrees. - * @param linkargs The link arguments. - */ - -struct MouseEvent -{ - int x; /*Horizontal pixel location of event on map from top left corner*/ - int y; /*Vertical pixel location of event on map from top left corner*/ - int clickcount; /*number of times mouse is clicked*/ - Modifier modifier; /*Modifiers associated with Mouse events*/ - double latitude; /*in Decimal Degrees*/ - double longitude; /*in Decimal Degrees*/ -}; -typedef struct MouseEvent MouseEvent; - - -/** - * The KeyboardEvent. - * - * @param keypressed The key pressed. - * @param modifier Additional keys pressed (ctrl, meta, etc.) - */ - -struct KeyboardEvent -{ - char keypressed; - Modifier modifier; /*additional keys pressed Control, Meta etc..*/ -}; -typedef struct KeyboardEvent KeyboardEvent; - -/** - * The ActionRequest - * - * @param version The version of the incoming object. - * @param descriptor The descriptor. - * @param *mouseEvent The MouseEvent. - * @param *keyboardEvent The KeyboardEvent. - * @param linkargs A list of key value pairs for attribute passing. - */ - -struct ActionRequest -{ - double version; /*version of the incoming Object */ - Descriptor descriptor; /*An integer*/ - MouseEvent *mouseEvent; - KeyboardEvent *keyboardEvent; - LinkArgs linkargs; /*A list of key value pairs for attribute passing*/ -}; -typedef struct ActionRequest ActionRequest; - -struct Link; - -/** - * Reads an action event from the link socket. - * - * @param *link The link socket. - * @returns OK if all read operations return OK, NOK if it failed. - * @returns -1 if there was a memory allocation error. - */ - -int ReadActionRequest(struct Link *link); - -/** - * Frees the memory from an action request. - * - * @param *actionrequest The action request to free memory from. - */ - -void FreeActionRequest(ActionRequest *actionrequest); - -/** - * Reads mouse event-related information from the socket. - * - * @param *linkSocket The link socket. - * @param *mouseEvent The mouse event. - * @returns OK if successful. - */ - -int ReadMouseEvent(LinkSocket *linkSocket, MouseEvent *mouseEvent); - -/** - * Reads the keyboard event-related information from the socket. - * - * @param *linkSocket The link socket. - * @param *keyboardEvent The keyboard event. - * @returns OK if successful, -1 if there was a memory allocation error. -y */ - -int ReadKeyboardEvent(LinkSocket *linkSocket, KeyboardEvent *keyboardEvent); - -/** - * Sends a message to the client; the server is interested in receiving - * events described in the descriptor. - * - * @param *linkSocket The link socket. - * @param *descriptor The descriptor to receive events about. - */ -int SendServerInterest(LinkSocket *linkSocket, Descriptor *descriptor); - -#endif - - - - - - - - - - - - - diff --git a/src/core/src/main/include/cserver/link/GlobalConstants.h b/src/core/src/main/include/cserver/link/GlobalConstants.h deleted file mode 100644 index 86e2df821..000000000 --- a/src/core/src/main/include/cserver/link/GlobalConstants.h +++ /dev/null @@ -1,48 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/GlobalConstants.h,v $ - * $RCSfile: GlobalConstants.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef GLOBALCONSTANTS_H -#define GLOBALCONSTANTS_H - -/* - Definitions of Constants -*/ -#define LINK_TRUE 1 -#define LINK_FALSE 0 -#define OK 0 -#define NOK 1 - -#define N_CHARS_PER_UNICODE_CHAR 2 -#define N_BYTES_PER_INTEGER 4 -#define N_BYTES_PER_FLOAT 4 -#define N_BIT_PER_CHAR 8 - -#define COLORBLACK 0xFF000000 -#define DEFAULT_LINE_WIDTH 1 - -#define HEADERSUCCESS 'S' -#define HEADERERROR 'E' -#define MEMORYERROR 'M' -#define MAX_SOCKET_BUFFER_SIZE 4096 - -#endif diff --git a/src/core/src/main/include/cserver/link/Graphics.h b/src/core/src/main/include/cserver/link/Graphics.h deleted file mode 100644 index 06138c048..000000000 --- a/src/core/src/main/include/cserver/link/Graphics.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/Graphics.h,v $ - * $RCSfile: Graphics.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef GRAPHICS_H -#define GRAPHICS_H - -/*deprecated...use constants in link.h*/ - -/* - Constant definations for Graphics Objects -*/ -#define RENDERTYPE_UNKNOWN 0 -#define RENDERTYPE_LATLON 1 -#define RENDERTYPE_XY 2 -#define RENDERTYPE_OFFSET 3 - -#define GRAPHICTYPE_GRAPHIC 0 -#define GRAPHICTYPE_BITMAP 1 -#define GRAPHICTYPE_TEXT 2 -#define GRAPHICTYPE_POLY 3 -#define GRAPHICTYPE_LINE 4 -#define GRAPHICTYPE_RECTANGLE 5 -#define GRAPHICTYPE_CIRCLE 6 -#define GRAPHICTYPE_RASTER 7 -#define GRAPHICTYPE_GRID 8 - -#define DECIMAL_DEGREES 0 -#define RADIANS 1 - -#define KM 0 -#define MILES 1 -#define NMILES 2 - -#define COORDMODE_ORIGIN 0 -#define COORDMODE_PREVIOUS 1 - -#define JUSTIFY_LEFT 0 -#define JUSTIFY_CENTER 1 -#define JUSTIFY_RIGHT 2 - -/* For the Grid objects, defining the primary dimension of the data. */ -#define COLUMN_MAJOR 0 -#define ROW_MAJOR 1 - - -#endif diff --git a/src/core/src/main/include/cserver/link/LatLonPoint.h b/src/core/src/main/include/cserver/link/LatLonPoint.h deleted file mode 100644 index 9da104ceb..000000000 --- a/src/core/src/main/include/cserver/link/LatLonPoint.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LatLonPoint.h,v $ - * $RCSfile: LatLonPoint.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LATLONPOINT_H -#define LATLONPOINT_H - -/* - Definition of Geo(Latitude Longitude) Point Object -*/ -#include "LinkSocket.h" - -/** - * Defines latitudes and longitudes, generally in decimal degrees. - * - * @param Lat The latitude. - * @param Lon The longitude. - */ - -struct LatLonPoint{ - double Lat; - double Lon; -}; -typedef struct LatLonPoint LatLonPoint; - -/** - * Reads LatLon values from the socket. - * - * @param *linkSocket The link socket. - * @param *point The point to be read. - * @returns OK if successful. - */ - -int ReadLatLonPoint(LinkSocket *linkSocket, LatLonPoint *point); - -#endif - - - diff --git a/src/core/src/main/include/cserver/link/Link.h b/src/core/src/main/include/cserver/link/Link.h deleted file mode 100644 index 9e1843d2b..000000000 --- a/src/core/src/main/include/cserver/link/Link.h +++ /dev/null @@ -1,257 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/Link.h,v $ - * $RCSfile: Link.h,v $ - * $Revision: 1.4 $ - * $Date: 2007/06/21 21:43:44 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/** - * The Link object is the main mechanism for communications between a - * LinkClient (most liekly a LinkLayer) and a LinkServer. This object - * defines the communications that either side can make - * - * The server should remain connected until the client is finished. - * The server can request to be disconnected. - */ - -#ifndef LINK_H -#define LINK_H - -#define MAX_HEADER_LENGTH 80 - -/* Used when reading from the link and comparing symbols. */ -#define END_TOTAL '\r' -#define END_SECTION '\n' - -/* Used when writing to the link. */ -#define END_TOTAL_STRING "\r" -#define END_SECTION_STRING "\n" - -#define UNKNOWN -1 - -#define VERSION 0.6 - -/*see protocol*/ - -/** - * Line types. - * - * @param LUNKNOWN Unknown line type. - * @param LSTRAIGHT Straight line. - * @param LRHUMB Rhumb line. - * @param LGREATCIRCLE Great circle line. - */ - -enum LINETYPE {LUNKNOWN, LSTRAIGHT, LRHUMB, LGREATCIRCLE}; - -/** - * Raster image types. - */ - -enum RASTERIMAGE {IMAGE_DIRECT_COLOR_MODEL, IMAGE_INDEX_COLOR_MODEL, IMAGE_URL}; - -/** - * Render types. - */ -enum RENDERTYPE {RENDERTYPE_UNKNOWN, RENDERTYPE_LATLON, RENDERTYPE_XY, RENDERTYPE_OFFSET}; - -/** - * Graphic types. - */ - -enum GRAPHICTYPE {GRAPHICTYPE_GRAPHIC, GRAPHICTYPE_BITMAP, GRAPHICTYPE_TEXT, - GRAPHICTYPE_POLY, GRAPHICTYPE_LINE, GRAPHICTYPE_RECTANGLE, - GRAPHICTYPE_CIRCLE, GRAPHICTYPE_RASTER, - GRAPHICTYPE_GRID, GRAPHICTYPE_POINT, GRAPHICTYPE_ELLIPSE}; - -/** - * Geographic units. - */ - -enum GEOUNITS {DECIMAL_DEGREES, RADIANS}; - -/** - * Distance units. - */ - -enum DIST_UNITS {CIRCLE_DECIMAL_DEGREES = -1,KM,MILES,NMILES}; - -/** - * Coordinate mode. - */ - -enum COORDMODE {COORDMODE_ORIGIN, COORDMODE_PREVIOUS}; - -/** - * Justification when writing to the map. - */ -enum JUSTIFICATION {JUSTIFY_LEFT, JUSTIFY_CENTER, JUSTIFY_RIGHT}; - -/** - * The various action types. - */ - -enum ACTIONTYPE {ACTIONGRAPHIC, ACTIONGUI}; - -/* REQUEST HEADERS*/ -#define MAP_REQUEST_HEADER "" -#define lMAP_REQUEST_HEADER strlen(MAP_REQUEST_HEADER) -#define ACTION_REQUEST_HEADER "" -#define lACTION_REQUEST_HEADER strlen(ACTION_REQUEST_HEADER) -#define GUI_REQUEST_HEADER "" -#define lGUI_REQUEST_HEADER strlen(GUI_REQUEST_HEADER) - -/* RESPONSE HEADERS*/ -#define GRAPHICS_RESPONSE_HEADER "" -#define lGRAPHICS_RESPONSE_HEADER strlen(GRAPHICS_RESPONSE_HEADER) -#define GESTURE_RESPONSE_HEADER "" -#define lGESTURE_RESPONSE_HEADER strlen(GESTURE_RESPONSE_HEADER) -#define GUI_RESPONSE_HEADER "" -#define lGUI_RESPONSE_HEADER strlen(GUI_RESPONSE_HEADER) -#define CLOSE_LINK_HEADER "" -#define lCLOSE_LINK_HEADER strlen(CLOSE_LINK_HEADER) -#define HUH_HEADER "" -#define lHUH_HEADER strlen(HUH_HEADER) - -/* Graphic Headers*/ -#define BITMAP_HEADER "" -#define lBITMAP_HEADER strlen(BITMAP_HEADER) -#define CIRCLE_HEADER "" -#define lCIRCLE_HEADER strlen(CIRCLE_HEADER) -#define ELLIPSE_HEADER "" -#define lELLIPSE_HEADER strlen(ELLIPSE_HEADER) -#define GRID_HEADER "" -#define lGRID_HEADER strlen(GRID_HEADER) -#define LINE_HEADER "" -#define lLINE_HEADER strlen(LINE_HEADER) -#define POLY_HEADER "" -#define lPOLY_HEADER strlen(POLY_HEADER) -#define TEXT_HEADER "" -#define lTEXT_HEADER strlen(TEXT_HEADER) -#define RASTER_HEADER "" -#define lRASTER_HEADER strlen(RASTER_HEADER) -#define RECTANGLE_HEADER "" -#define lRECTANGLE_HEADER strlen(RECTANGLE_HEADER) -#define POINT_HEADER "" -#define lPOINT_HEADER strlen(POINT_HEADER) -#define GRAPHIC_HEADER "" -#define lGRAPHIC_HEADER strlen(GRAPHIC_HEADER) - -/* Gesture Response Headers*/ -#define UPDATE_GRAPHICS "" -#define lUPDATE_GRAPHICS strlen(UPDATE_GRAPHICS) -#define UPDATE_GUI "" -#define lUPDATE_GUI strlen(UPDATE_GUI) -#define UPDATE_MAP "" -#define lUPDATE_MAP strlen(UPDATE_MAP) - -/* - Predefined keys for key value pairs stored in the LinkArgs. -*/ - -/* For graphic attributes. */ -/** The line color attribute name. */ -#define LPC_LINECOLOR "lc" -/** The highlight color attribute name. */ -#define LPC_HIGHLIGHTCOLOR "hc" -/** The fill color attribute name. */ -#define LPC_FILLCOLOR "fc" -/** The line width attribute name. */ -#define LPC_LINEWIDTH "lw" -/** The text graphic contents attribute name. */ -#define LPC_LINKTEXTSTRING "ts" -/** The font representation attribute name. */ -#define LPC_LINKTEXTFONT "tf" -/** The attribute name for a URL for an image in LinkRaster. Only - used in some circumstances. */ -#define LPC_LINKRASTERIMAGEURL "riu" -/** The graphic identifier attribute name. */ -#define LPC_GRAPHICID "gid" - -/* Constants that can fire a information delegator action.*/ -/** The URL text attribute name. */ -#define LPC_URL "url" -/** The HTML text (displayed in a browser) attribute name. */ -#define LPC_HTML "html" -/** The Information Line (status line) attribute name. */ -#define LPC_INFO "info" -/** The Message text (in a pop-up window) attribute name. */ -#define LPC_MESSAGE "mess" - -struct MapRequest; -struct ActionRequest; -struct LinkSocket; -/** - * The link. - * - * @param *socket The link socket. - * @param *mapRequest The map request. - * @param *actionRequest The action request. - * @param closeLink LINK_TRUE if the link is closed. LINK_FALSE, otherwise. - */ - -struct Link { - struct LinkSocket *socket; - struct MapRequest *mapRequest; - struct ActionRequest *actionRequest; - int closeLink; /*LINK_TRUE if link is closed, LINK_FALSE otheriwse*/ -}; -typedef struct Link Link; - -/** - * Initializes the socket and makes it ready for communication. - * - * @param *link The link socket. - * @returns OK if the socket was successfully created, NOK if it failed. - * @returns -1 if there was a memory allocation error. - */ - -int CreateLink(Link *link); - -/** - * Reads the headers and creates corresponding objects. Fills data from the - * socket into Request Objects. - * - * @param *link The link object. - * @returns HEADERSUCCESS if successful, HEADERERROR if it fails. - * @returns MEMORYERROR if there was a memory allocation error. - - */ - -char ReadAndParseLink(Link *link); - -/** - * Deallocates the memory used internally by the link. - * Note: The user should still call free(link) to free other memory. - * - * @param *link The link object. - */ - -void FreeLink(Link *link); - -void SendHuh(Link *link); - -#endif - - - - - - - diff --git a/src/core/src/main/include/cserver/link/LinkArgs.h b/src/core/src/main/include/cserver/link/LinkArgs.h deleted file mode 100644 index 0a8c02c53..000000000 --- a/src/core/src/main/include/cserver/link/LinkArgs.h +++ /dev/null @@ -1,231 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkArgs.h,v $ - * $RCSfile: LinkArgs.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKARGS_H -#define LINKARGS_H - -#include "LinkSocket.h" -#include "Request.h" - -/* - This file defines structures and methods that are used in the - LinkArgs. LinkArgs are used in all requests and responses, and in - the graphic structures sent to the client. - */ - -/** - * The link string structure. - * - * @param numberOfChars The number of characters in the string. - * @param *text The string. - */ - -struct LinkString{ - int numberOfChars; - char *text; -}; -typedef struct LinkString LinkString; - -/** - * The link arguments. - * - * @param numberOfArgs The number of arguments. - * @param *args The arguments. - */ - -struct LinkArgs { - int numberOfArgs; - LinkString *args; -}; -typedef struct LinkArgs LinkArgs; - -/** - * Reads the link string off the link socket. - * - * @param *linkSocket The link socket. - * @param *string The string to read. - */ - -int ReadLinkString(LinkSocket *linkSocket, LinkString *string); - -/** - * Writes the link string to the link socket. - * - * @param *linkSocket The link socket. - * @param *string The string to write. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkString(LinkSocket *linkSocket, LinkString *string); - -/** - * Writes the link string to a buffer. - * - * @param *toBuffer Buffer to write to. - * @param *string Link string to write. - */ - -int BufferedWriteLinkString(char *toBuffer, LinkString *string); - -/** - * Frees the memory used by a link string. - * - * @param *string The link string to free memory from. - */ - -void FreeLinkString(LinkString *string); - -/** - * Reads link arguments from the socket. - * - * @param *linkSocket The link socket. - * @param * The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int ReadLinkArgs(LinkSocket *linkSocket, LinkArgs *); - -/** - * Writes link arguments to the socket. - * - * @param *linkSocket The link socket. - * @param * The link arguments. - * - */ - -int WriteLinkArgs(LinkSocket *linkSocket, LinkArgs *); - -/** - * Writes buffered link arguments. DEPRECATED - * - * Deprecated: Use WriteLinkArgs(). - * - * @param *toBuffer The buffer to write to. - * @param * The link arguments. - * - */ - -int BufferedWriteLinkArgs(char *toBuffer, LinkArgs *); - -/** - * Writes string link arguments to the socket. - * - * @param *linkSocket The link socket. - * @param * The string. - * @returns -1 if there was a memory allocation error - */ - -int WriteLinkArgString(LinkSocket *linkSocket, LinkString *string); - -/** - * Creates the link arguments. - * - * @returns NULL if there was a memory allocation error. - */ - -LinkArgs* CreateLinkArgs(); - -/** - * Gets the value for a given key. The argument list given is assumed - * to be a list of key-value pairs in an array of LinkArgs, alternating - * key, value, etc. If the key matches one of the keys in the list, a - * pointer to the value for the key is returned. - * - * @param *args The link arguments. - * @param *key The key to get a value for. - * @returns The value for the key, if found. Otherwise, NULL. - */ - -char* GetValueForKey(LinkArgs *args, char* key); - -/** - * Frees the memory from the link arguments. Does not free the - * pointer, in case the pointer to the strcuture was not allocated - * using malloc. So you'll still have to free linkArgs structure, but - * not the contents. - * - * @param *linkArgs The link arguments. - */ - -void FreeLinkArgs(LinkArgs *linkArgs); - -/** - * Sets a key/value pair in the link arguments, for where the value - * is a char. - * - * @param *linkArgs The link arguments. - * @param *key The key. - * @param *value The char value to set. - * @param is_unicode Set to 1 if the value you're passing is already in Unicode, and does not need to be translated. - * @param num_unicode_chars If Unicode is being passed, how many characters does the string take? - * @returns -1 if there was a memory allocation error. - */ - -int SetKeyValuePairInLinkArgs(LinkArgs *linkArgs, char *key, char *value, int is_unicode, int num_unicode_chars); - -/** - * Sets a key/value pair in the link arguments, for where the value is - * an int. - * - * @param *linkArgs The link arguments. - * @param *key The key. - * @param value The integer value to set. - * @returns -1 if there was a memory allocation error. - */ - -int SetKeyIntegerPairInLinkArgs(LinkArgs *linkArgs, char *key, int value); - -/** - * Sets a key/value pair in the link arguments, for where the value is - * a double. - * - * @param *linkArgs The link arguments. - * @param *key The key. - * @param value The double value to set. - * @returns -1 if there was a memory allocation error. - * - */ -int SetKeyDoublePairInLinkArgs(LinkArgs *linkArgs, char *key, double value); - -/** - * Removes a key/value pair from the link arguments. - * - * @param *linkArgs The link arguments. - * @param *key The key of the key/value pair to remove. - * @returns -1 if there was a memory allocation error. - */ - -int RemoveKeyFromLinkArgs(LinkArgs* linkArgs, char *key); - -/** - * Returns the number of bytes used by the link arguments. - * - * @param *linkArgs. - * @return The number of bytes used by the link arguments. - */ - -int LinkSizeOfLinkArgs(LinkArgs *linkArgs); - - -#endif - diff --git a/src/core/src/main/include/cserver/link/LinkBitmap.h b/src/core/src/main/include/cserver/link/LinkBitmap.h deleted file mode 100644 index 6e63b915c..000000000 --- a/src/core/src/main/include/cserver/link/LinkBitmap.h +++ /dev/null @@ -1,174 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkBitmap.h,v $ - * $RCSfile: LinkBitmap.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKBITMAP_H -#define LINKBITMAP_H - -#include "LinkArgs.h" - -/*Prototypes for Writing Bitmap Object*/ - -/* - Buffered objects write everything to a chunk of memory and - write the entire memory to socket at one short -*/ - -/** - * Writes a bitmap object to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (top left corner), in decimal degrees. - * @param lon The longitude of the image location (top left corner) in decimal degrees. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosing the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap object, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns OK if it succeeded, -1 if there was a memory allocation error. - */ - -int WriteLinkBitmapLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -/** - * Writes a buffered bitmap object to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkBitmapLatLon(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (top left corner), in decimal degrees. - * @param lon The longitude of the image location (top left corner) in decimal degrees. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosing the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap object, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkBitmapLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -/** - * Writes a bitmap object in X-Y space to the link socket. The X and Y - * points are offset from the upper left corner of the canvas. - * - * @param linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), in pixels. - * @param y The Y coordinate of the image location (upper left corner), in pixels. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosing the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap object, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkBitmapXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -/** - * Writes a buffered bitmap object in X-Y space to the link socket. The X - * and Y points are offset from the upper left corner of the canvas. - * DEPRECATED - * - * Deprecated: Use WriteLinkBitmapXY(). - * - * @param linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), in pixels. - * @param y The Y coordinate of the image location (upper left corner), in pixels. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosing the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap object, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkBitmapXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -/** - * Writes a bitmap object with an offset to the link socket. The X and Y - * coordinates are offset from the lat-long anchor point, in pixels. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosnig the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkBitmapOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -/** - * Writes a buffered bitmap object with an offset to the link socket. The X - * and Y coordinates are offset from the lat-long anchor point, in pixels. - * DEPRECATED - * - * Deprecated: Use WriteLinkBimapOffset(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param width The width of the rectangle enclosing the bitmap, in pixels. - * @param height The height of the rectangle enclosnig the bitmap, in pixels. - * @param numberOfbytes The size of the bitmap, in bytes. - * @param *bitmap The bitmap. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkBitmapOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int numberOfbytes, char *bitmap, - LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkCircle.h b/src/core/src/main/include/cserver/link/LinkCircle.h deleted file mode 100644 index b2af2ac37..000000000 --- a/src/core/src/main/include/cserver/link/LinkCircle.h +++ /dev/null @@ -1,168 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkCircle.h,v $ - * $RCSfile: LinkCircle.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKCIRCLE_H -#define LINKCIRCLE_H - -#include "LinkSocket.h" -#include "Request.h" -#include "LinkArgs.h" - -/*Prototypes for Writing Circle Object*/ - -/* - Buffered objects write everything to a chunk of memory and - write the entire memory to socket at one short -*/ - -/** - * Writes a circle to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of the center of the circle, in decimal degrees. - * @param lon The longitude of the center of the circle, in decimal degrees. - * @param radius The radius of the circle. - * @param unit The units of the radius of the circle, (KM, MILES, or NMILES). See Graphics.h. - * @param nvertices The number of vertices that should be used to approximate the circle. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkCircleLatLon(LinkSocket *link, - double lat, double lon, - double radius, int unit, - int nvertices, - LinkArgs *linkArgs); - -/** - * Writes a circle to the link socket in X-Y space. The X and Y coordinates - * are offset from the upper left corner of the canvas. - * - * @param *link The link socket. - * @param x The X coordinate of the center of the circle, in pixels. - * @param y the Y coordinate of the center of the circle, in pixels. - * @param width The width of the bounding rectangle of the circle, in pixels. - * @param height The height of the bounding rectangle of the circle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkCircleXY(LinkSocket *link, - int x, int y, - int width, int height, - LinkArgs *linkArgs); - -/** - * Writes a circle with an offset to the link socket. The X and Y points are - * offset from the lat-long anchor point. - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the center of the circle, offset from the anchor point, in pixels. - * @param y The Y coordinate of the center of the circle, offset from the anchor point, in pixels. - * @param width The width of the bounding rectangle of the circle, in pixels. - * @param height The height of the bounding rectangle of the circle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteLinkCircleOffset(LinkSocket *link, - double lat, double lon, - int x, int y, - int width, int height, - LinkArgs *linkArgs); - -/** - * Writes a buffered circle to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkCircleLatLon(). - * - * @param *link The link socket. - * @param lat The latitude of the center of the circle, in decimal degrees. - * @param lon The longitude of the center of the circle, in decimal degrees. - * @param radius The radius of the circle. - * @param unit The units of the radius of the circle, (KM, MILES, or NMILES). See Graphics.h. - * @param nvertices The number of vertices that should be used to approximate the circle. - * @param *linkArgs The link arguments. - * @returns -1 if there is a memory allocation error. - */ - -int BufferedWriteLinkCircleLatLon(LinkSocket *link, - double lat, double lon, - double radius, int unit, - int nvertices, - LinkArgs *linkArgs); - -/** - * Writes a buffered circle to the link socket in X-Y space. The X and Y - * coordinates are offset from the upper left corner of the canvas. - * DEPRECATED - * - * Deprecated: Use WriteLinkCircleXY(). - * - * @param *link The link socket. - * @param x The X coordinate of the center of the circle, in pixels. - * @param y the Y coordinate of the center of the circle, in pixels. - * @param width The width of the bounding rectangle of the circle, in pixels. - * @param height The height of the bounding rectangle of the circle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkCircleXY(LinkSocket *link, - int x, int y, - int width, int height, - LinkArgs *linkArgs); - -/** - * Writes a buffered circle with an offset to the link socket. The X and Y - * points are offset from the lat-long anchor point. DEPRECATED - * - * Deprecated: Use WriteLinkCircleOffset(). - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the center of the circle, offset from the anchor point, in pixels. - * @param y The Y coordinate of the center of the circle, offset from the anchor point, in pixels. - * @param width The width of the bounding rectangle of the circle, in pixels. - * @param height The height of the bounding rectangle of the circle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkCircleOffset(LinkSocket *link, - double lat, double lon, - int x, int y, - int width, int height, - LinkArgs *linkArgs); - -#endif - - - - - diff --git a/src/core/src/main/include/cserver/link/LinkEllipse.h b/src/core/src/main/include/cserver/link/LinkEllipse.h deleted file mode 100644 index f478143e2..000000000 --- a/src/core/src/main/include/cserver/link/LinkEllipse.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkEllipse.h,v $ - * $RCSfile: LinkEllipse.h,v $ - * $Revision: 1.2 $ - * $Date: 2006/10/10 22:05:18 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKELLIPSE_H -#define LINKELLIPSE_H - -#include "LinkSocket.h" -#include "Request.h" -#include "LinkArgs.h" - -/*Prototypes for Writing Ellipse Object*/ - -/* - Buffered objects write everything to a chunk of memory and - write the entire memory to socket at one short -*/ - -/** - * Writes a ellipse to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of the center of the ellipse, in decimal degrees. - * @param lon The longitude of the center of the ellipse, in decimal degrees. - * @param majorAxis The length of the major axis of the ellipse. - * @param minorAxis The length of the minor axis of the ellipse. - * @param unit The units of the radius of the ellipse, (KM, MILES, or NMILES). See Graphics.h. - * @param rotation the angle rotation applied to the ellipse. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkEllipseLatLon(LinkSocket *link, - double lat, double lon, - double majorAxis, double minorAxis, int unit, - double rotation, - LinkArgs *linkArgs); - -/** - * Writes a ellipse to the link socket in X-Y space. The X and Y coordinates - * are offset from the upper left corner of the canvas. - * - * @param *link The link socket. - * @param x The X coordinate of the center of the ellipse, in pixels. - * @param y the Y coordinate of the center of the ellipse, in pixels. - * @param majorAxis The length of the major axis of the ellipse, in pixels. - * @param minorAxis The length of the minor axis of the ellipse, in pixels. - * @param rotation the angle rotation applied to the ellipse. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkEllipseXY(LinkSocket *link, - int x, int y, - int majorAxis, int minorAxis, - double rotation, - LinkArgs *linkArgs); - -/** - * Writes a ellipse with an offset to the link socket. The X and Y points are - * offset from the lat-long anchor point. - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the center of the ellipse, offset from the anchor point, in pixels. - * @param y The Y coordinate of the center of the ellipse, offset from the anchor point, in pixels. - * @param majorAxis The length of the major axis of the ellipse, in pixels. - * @param minorAxis The length of the minor axis of the ellipse, in pixels. - * @param rotation the angle rotation applied to the ellipse. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkEllipseOffset(LinkSocket *link, - double lat, double lon, - int x, int y, - int majorAxis, int minorAxis, - double rotation, - LinkArgs *linkArgs); - -#endif - - - - - diff --git a/src/core/src/main/include/cserver/link/LinkGrid.h b/src/core/src/main/include/cserver/link/LinkGrid.h deleted file mode 100644 index 7fcee2b18..000000000 --- a/src/core/src/main/include/cserver/link/LinkGrid.h +++ /dev/null @@ -1,225 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkGrid.h,v $ - * $RCSfile: LinkGrid.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKGRID_H -#define LINKGRID_H - -#include "LinkArgs.h" -#include "LinkSocket.h" -#include "Request.h" - -/*Prototypes for Writing Grid Object*/ - -/* - Buffered objects write everything to a chunk of memory and - write the entire memory to socket at one short -*/ - -/** - * Writes a grid object in lat-long space to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param HResolution - * @param major - * @param data - * @param linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkGridLatLon(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); - -/** - * Writes a grid object in lat-long space with the data passed as a short - * to the link socket. - * - * @param *linkSocket The link socket. - * @param *lat The latitude of the anchor point, in degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param HResolution - * @param major - * @param data - * @param linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteLinkGridLatLonS(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, short* data, - LinkArgs *linkArgs); - -/** - * Writes a buffered grid object in lat-long space to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkGridLatLon(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param HResolution - * @param major - * @param data - * @param linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkGridLatLon(LinkSocket *linkSocket, - double lat, double lon, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); - -/** - * Writes a grid object in X-Y space to the link socket. - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the anchor point, in pixels from the top left corner of the canvas. - * @param y The Y coordinate of the anchor point, in pixels from the top left corner of the canvas. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param HResolution - * @param major - * @param data - * @param linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkGridXY(LinkSocket *linkSocket, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); - -/** - * Writes a buffered grid object in X-Y space to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkGridXY(). - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the anchor point, in pixels from the top left corner of the canvas. - * @param y The Y coordinate of the anchor point, in pixels from the top left corner of the canvas. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param HResolution - * @param major - * @param data - * @param linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkGridXY(LinkSocket *linkSocket, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); - - -/** - * Writes a grid object with an offset to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point. - * @param lon The longitude of the anchor point. - * @param x The X coordinate of the top left corner of the grid, offset from the anchor point, in pixels. - * @param y The Y coordinate of the top left corner of the grid, offset from the anchor point, in pixels. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param hResolution - * @param major - * @param data - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteLinkGridOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); -/** - * Writes a buffered grid object with an offset to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkGridOffset(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point. - * @param lon The longitude of the anchor point. - * @param x The X coordinate of the top left corner of the grid, offset from the anchor point, in pixels. - * @param y The Y coordinate of the top left corner of the grid, offset from the anchor point, in pixels. - * @param rows The number of rows in the grid. - * @param columns The number of columns in the grid. - * @param orientation - * @param vResolution - * @param hResolution - * @param major - * @param data - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkGridOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int rows, int columns, double orientation, - double vResolution, double hResolution, - int major, int* data, - LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkImage.h b/src/core/src/main/include/cserver/link/LinkImage.h deleted file mode 100644 index f8c29e341..000000000 --- a/src/core/src/main/include/cserver/link/LinkImage.h +++ /dev/null @@ -1,134 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkImage.h,v $ - * $RCSfile: LinkImage.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKIMAGE_H -#define LINKIMAGE_H - -#include "LinkSocket.h" - -/* - Definations of Objects for sending Images/pics in different ways to client -*/ - -/** - * A raw image object. - * - * @param numberOfPixels The number of pixels in the image. - * @param *image The image. - */ - -struct DirectImage -{ - int numberOfPixels; - int *image; -}; -typedef struct DirectImage DirectImage; - -/** - * Sends images (pixel values) directly as integers to the link socket. - * - * @param *linkSocket The link socket. - * @param *directimage The direct image. - */ - -int WriteDirectImage(LinkSocket *linkSocket, DirectImage *directimage); - -/** - * Sends buffered images (pixel values) directly as integers to the link - * socket. DEPRECATED - * - * Deprecated: Use WriteDirectImage(). - * - * @param *linkSocket The link socket. - * @param *directimage The direct image. - */ - -int BufferedWriteDirectImage(char *toBuffer, DirectImage *directimage); - -/** - * Returns the memory required to store this direct image, in bytes. - * - * @param *directimage The direct image. - * @returns Memory required to store the direct image, in bytes. - */ - -int GetDirectImageSize(DirectImage *directimage); - -/*---------------------------------------------------------------------------*/ -/* - Sends Pixel values in a color table and send image as a series of bytes, - each byte containing an index on color table that contains actual pixel value -*/ - -/** - * The indexed image object. - * - * @param numberOfPixels The number of pixels in the object. - * @param *image An array of bytes, each byte contains an index for a color table. - * @param colorTableSize Size of the color table. - * @param *colorTable The color table. - * @param transparency The transparency of the image. - */ - - -struct IndexedImage -{ - int numberOfPixels; - char *image; /*An array of bytes, each byte contains an index for color table*/ - - int colorTableSize; - int *colorTable; /*Each entry contains a pixel value*/ - - int transparency; -}; -typedef struct IndexedImage IndexedImage; - -/** - * Writes an indexed image to the link socket. - * - * @param *linkSocket The link socket. - * @param *indexedimage The indexed image. - */ -int WriteIndexedImage(LinkSocket *linkSocket, IndexedImage *indexedimage); - -/** - * Writes a buffered, indexed image to the link socket. DEPRECATED - * - * Deprecated: Use WriteIndexedImage(). - * - * @param *linkSocket The link socket. - * @param *indexedimage The indexed image. - */ - -int BufferedWriteIndexedImage(char *toBuffer, IndexedImage *indexedimage); - -/** - * Returns memory size in bytes required to store the direct image. - * - * @param *indexedimage The indexed image. - * @returns Memory required to store the direct image, in bytes. - */ - -int GetIndexedImageSize(IndexedImage *indexedimage); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkLine.h b/src/core/src/main/include/cserver/link/LinkLine.h deleted file mode 100644 index 89c4ddeea..000000000 --- a/src/core/src/main/include/cserver/link/LinkLine.h +++ /dev/null @@ -1,166 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkLine.h,v $ - * $RCSfile: LinkLine.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKLINE_H -#define LINKLINE_H - -#include "LinkSocket.h" -#include "LinkArgs.h" -#include "Request.h" - -/** - * Writes a line between two points in lat-long space to the link socket. - * - * @param *linkSocket The link socket. - * @param lat_1 The latitude of the first point, in decimal degrees. - * @param lon_1 The longitude of the first point, in decimal degrees. - * @param lat_2 The latitude of the second point, in decimal degrees. - * @param lat_2 The longitude of the second point, in decimal degrees. - * @param lineType The line type. - * @param nsegs The number of segments to approximate the line. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkLineLatLon(LinkSocket *linkSocket, - double lat_1, double lon_1, - double lat_2, double lon_2, - int lineType, int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a line between two points in X-Y space to the link socket. The - * X and Y values are offset from the upper left corner of the canvas. - * - * @param *linkSocket The link socket. - * @param x1 The X coordinate of the first point, in pixels. - * @param y1 The Y coordinate of the first point, in pixels. - * @param x2 The X coordinate of the second point, in pixels. - * @param y2 The Y coordinate of the second point, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkLineXY(LinkSocket *linkSocket, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs); - -/** - * Writes a line between two X-Y points, offset from a lat-long point, to - * the link socket. The X and Y values are offset from the lat-long point, - * in pixels. - * - * @param *linkSocket The link socket. - * @param lat_1 The latitude of the anchor point, in decimal degrees. - * @param lon_1 The longitude of the anchor point, in decimal degrees. - * @param x1 The X coordinate of the first point, offset from the anchor point, in pixels. - * @param y1 The Y coordinate of the first point, offset from the anchor point, in pixels. - * @param x2 The X coordinate of the second point, offset from the anchor point, in pixels. - * @param y2 The Y coordinate of the second point, offset from the anchor point, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkLineOffset(LinkSocket *linkSocket, - double lat_1, double lon_1, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs); - -/** - * Writes a buffered line between two points in lat-long space to the link - * socket. DEPRECATED - * - * Deprecated: Use WriteLinkLineLatLon(). - * - * @param *linkSocket The link socket. - * @param lat_1 The latitude of the first point, in decimal degrees. - * @param lon_1 The longitude of the first point, in decimal degrees. - * @param lat_2 The latitude of the second point, in decimal degrees. - * @param lat_2 The longitude of the second point, in decimal degrees. - * @param lineType The line type. - * @param nsegs The number of segments to approximate the line. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkLineLatLon(LinkSocket *linkSocket, - double lat_1, double lon_1, - double lat_2, double lon_2, - int lineType, int nsegs, - LinkArgs *linkArgs); -/** - * Writes a buffered line between two points in X-Y space to the link socket. - * The X and Y values are offset from the upper left corner of the canvas. - * DEPRECATED - * - * Deprecated: Use WriteLinkLineXY(). - * - * @param *linkSocket The link socket. - * @param x1 The X coordinate of the first point, in pixels. - * @param y1 The Y coordinate of the first point, in pixels. - * @param x2 The X coordinate of the second point, in pixels. - * @param y2 The Y coordinate of the second point, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkLineXY(LinkSocket *linkSocket, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs); - -/** - * Writes a buffered line between two X-Y points, offset from a lat-long - * point, to the link socket. The X and Y values are offset from the - * lat-long point, in pixels. DEPRECATED - * - * Deprecated: Use WriteLinkLineOffset(). - * - * @param *linkSocket The link socket. - * @param lat_1 The latitude of the anchor point, in decimal degrees. - * @param lon_1 The longitude of the anchor point, in decimal degrees. - * @param x1 The X coordinate of the first point, offset from the anchor point, in pixels. - * @param y1 The Y coordinate of the first point, offset from the anchor point, in pixels. - * @param x2 The X coordinate of the second point, offset from the anchor point, in pixels. - * @param y2 The Y coordinate of the second point, offset from the anchor point, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkLineOffset(LinkSocket *linkSocket, - double lat_1, double lon_1, - int x1, int y1, - int x2, int y2, - LinkArgs *linkArgs); - -#endif - - - - - - - - diff --git a/src/core/src/main/include/cserver/link/LinkPoint.h b/src/core/src/main/include/cserver/link/LinkPoint.h deleted file mode 100644 index 3869dc96a..000000000 --- a/src/core/src/main/include/cserver/link/LinkPoint.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkPoint.h,v $ - * $RCSfile: LinkPoint.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKPOINT_H -#define LINKPOINT_H - -#include "LinkSocket.h" -#include "Request.h" -#include "LinkArgs.h" - - -/*Prototypes for Writing Point Object*/ - -/** - * Writes a point object in lat-long space to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of the point, in decimal degrees. - * @param lon The longitude of the point, in decimal degrees. - * @param radius The pixel radius of the point. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPointLatLon(LinkSocket *link, double lat, double lon, int radius, - LinkArgs *linkArgs); - -/** - * Writes a point object in X-Y space to the link socket. X-Y values are - * from the top left corner of the canvas. - * - * @param link The link socket. - * @param x The X coordinate of the upper left corner of the point, in pixels. - * @param y The Y coordinate of the upper left corner of the point, in pixels. - * @param radius The pixel radius of the point. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPointXY(LinkSocket *link, int x, int y, int radius, - LinkArgs *linkArgs); - -/** - * Writes a point object with an offset to the link socket. X-Y values - * are offset from the lat-long anchor point, in pixels. - * - * @param link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the point, in pixels. - * @param y The Y coordinate of the point, in pixels. - * @param radius The pixel radius of the point. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPointOffset(LinkSocket *link, double lat, double lon, - int x, int y, int radius, LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkPoly.h b/src/core/src/main/include/cserver/link/LinkPoly.h deleted file mode 100644 index 593ffaf76..000000000 --- a/src/core/src/main/include/cserver/link/LinkPoly.h +++ /dev/null @@ -1,281 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkPoly.h,v $ - * $RCSfile: LinkPoly.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKPOLY_H -#define LINKPOLY_H - -#include "LinkSocket.h" -#include "LinkArgs.h" -#include "Request.h" - -/*Prototypes for Writing PolyGon Object*/ - -/** - * Writes a polygon to the link socket. - * - * @param *link The link socket. - * @param latlon[] The array of lat-long points defining the polygon - * @param unit The units of the lat-long points (either DECIMAL_DEGREES or RADIANS). See Graphics.h. - * @param nsegs The number of segments used to approximate the polygon. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyLatLon(LinkSocket *link, int ltype, - int numberOflatlon, double latlon[], - int unit, int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a polygon to the link socket. This function allows you to specify - * the latitude and longitude as floats in two separate arrays, of size - * numberOflatlon. - * - * @param *link The link socket. - * @param ltype The line type. - * @param numberOflatlon The number of points in the polygon. - * @param lat[] Array of latitudes for the points, of size numberOflatlon. - * @param lon[] Array of longitudes for the points, of size numberOflatlon. - * @param unit The units of the lat-long points (either DECIMAL_DEGREES or RADIANS). See Graphics.h. - * @param nsegs The number of segments used to approximate the polygon. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyLatLon2F(LinkSocket *link, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - float lat[], float lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs); - - -/** - * Writes a polygon to the link socket. This function allows you to specify - * the latitude and longitude as doubles in two separate arrays, of size - * numberOflatlon. - * - * @param *link The link socket. - * @param ltype The line type. - * @param numberOflatlon The number of points in the polygon. - * @param lat[] Array of latitudes for the points, of size numberOflatlon. - * @param lon[] Array of longitudes for the points, of size numberOflatlon. - * @param unit The units of the lat-long points (either DECIMAL_DEGREES or RADIANS). See Graphics.h. - * @param nsegs The number of segments used to approximate the polygon. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyLatLon2D(LinkSocket *link, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - double lat[], double lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a polygon in XY space to the link socket. - * - * @param *link The link socket. - * @param numberOfXY The number of points in the polygon. - * @param XY[] Array of X and Y points, offset from the upper left corner of the canvas, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyXY(LinkSocket *link, - int numberOfXY, int XY[], - LinkArgs *linkArgs); - -/** - * Writes a polygon in XY space to the link socket, allowing the X and Y - * coordinates to be sent in separate arrays. - * - * @param *link The link socket. - * @param numberOfXY The number of points in the polygon. - * @param X[] Array of X points, offset from the upper left corner of the canvas, in pixels. - * @param Y[] Array of Y points, offset from the upper left corner of the canvas, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyXY2(LinkSocket *link, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], /* These 2 arrays are of equal size*/ - LinkArgs *linkArgs); - -/** - * Writes a polygon with an offset to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param XY[] The array of X-Y points defining the polygon, offset from the anchor point, in pixels. - * @param CoordMode See the protocol for more information. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyOffset(LinkSocket *link, - double lat, double lon, - int numberOfXY, int XY[], int CoordMode, - LinkArgs *linkArgs); - -/** - * Writes a polygon with an offset to the link socket, using two arrays for the - * X and Y coordinates. - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param XY[] The array of X-Y points defining the polygon, offset from the anchor point, in pixels. - * @param CoordMode See the protocol for more information. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkPolyOffset2(LinkSocket *link, - double lat, double lon, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], - int CoordMode, - LinkArgs *linkArgs); -/** - * Writes a buffered polygon to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkPolyLatLon(). - * - * @param *link The link socket. - * @param latlon[] The array of lat-long points defining the polygon - * @param unit The units of the lat-long points (either DECIMAL_DEGREES or RADIANS). See Graphics.h. - * @param nsegs The number of segments used to approximate the polygon. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkPolyLatLon(LinkSocket *link, int ltype, - int numberOflatlon, double latlon[], - int unit, int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a buffered polygon to the link socket. This function allows you to - * specify the latitude and longitude as doubles in two separate arrays, of - * size numberOflatlon. DEPRECATED - * - * Deprecated: Use WriteLinkPolyLatLon2(). - * - * @param *link The link socket. - * @param ltype The line type. - * @param numberOflatlon The number of points in the polygon. - * @param lat[] Array of latitudes for the points, of size numberOflatlon. - * @param lon[] Array of longitudes for the points, of size numberOflatlon. - * @param unit The units of the lat-long points (either DECIMAL_DEGREES or RADIANS). See Graphics.h. - * @param nsegs The number of segments used to approximate the polygon. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkPolyLatLon2(LinkSocket *link, int ltype, - int numberOflatlon, /*size of lat or lon array*/ - double lat[], double lon[], /*These 2 arrays are of equal size*/ - int unit, int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a buffered polygon in XY space to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkPolyXY(). - * - * @param *link The link socket. - * @param numberOfXY The number of points in the polygon. - * @param XY[] Array of X and Y points, offset from the upper left corner of the canvas, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkPolyXY(LinkSocket *link, - int numberOfXY, int XY[], - LinkArgs *linkArgs); - -/** - * Writes a buffered polygon in XY space to the link socket, allowing the X - * and Y coordinates to be sent in separate arrays. DEPRECATED - * - * Deprecated: Use WriteLinkPolyXY2(). - * - * @param *link The link socket. - * @param numberOfXY The number of points in the polygon. - * @param X[] Array of X points, offset from the upper left corner of the canvas, in pixels. - * @param Y[] Array of Y points, offset from the upper left corner of the canvas, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int BufferedWriteLinkPolyXY2(LinkSocket *link, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], /* These 2 arrays are of equal size*/ - LinkArgs *linkArgs); -/** - * Writes a buffered polygon with an offset to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkPolyOffset(). - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param XY[] The array of X-Y points defining the polygon, offset from the anchor point, in pixels. - * @param CoordMode See the protocol for more information. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkPolyOffset(LinkSocket *link, - double lat, double lon, - int numberOfXY, int XY[], int CoordMode, - LinkArgs *linkArgs); - -/** - * Writes a buffered polygon with an offset to the link socket, using two - * arrays for the X and Y coordinates. DEPRECATED - * - * Deprecated: WriteLinkPolyOffset2(). - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param XY[] The array of X-Y points defining the polygon, offset from the anchor point, in pixels. - * @param CoordMode See the protocol for more information. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkPolyOffset2(LinkSocket *linkSocket, - double lat, double lon, - int numberOfXY, /*count of elements in X or Y array*/ - int X[], int Y[], - int CoordMode, - LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkRaster.h b/src/core/src/main/include/cserver/link/LinkRaster.h deleted file mode 100644 index 7fa7b88e7..000000000 --- a/src/core/src/main/include/cserver/link/LinkRaster.h +++ /dev/null @@ -1,422 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkRaster.h,v $ - * $RCSfile: LinkRaster.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKRASTER_H -#define LINKRASTER_H - -#include "LinkSocket.h" -#include "LinkImage.h" -#include "Request.h" -#include "LinkArgs.h" - -/* Prototypes for writing Direct model images */ - -/** - * Writes a direct model image to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there is a memory allocation error. - */ - -int WriteLinkRasterDirectLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - -/** - * Writes a buffered direct model image to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkRasterDirectLatLon(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterDirectLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - - -/** - * Writes a direct model image in X-Y space to the link socket. - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location from the left side of the canvas, in pixels. - * @param y The Y coordinate of the image location from the top of the canvas, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there is a memory allocation error. - */ - -int WriteLinkRasterDirectXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - -/** - * Writes a buffered direct model image in X-Y space to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRasterDirectXY(). - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location from the left side of the canvas, in pixels. - * @param y The Y coordinate of the image location from the top of the canvas, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterDirectXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - -/** - * Writes a direct model image with an offset to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point (upper left corner), in decimal degrees. - * @param lon The longitude of the anchor point (upper left corner), in decimal degrees. - * @param x The X coordinate of the image location, offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location, offset from the anchor point, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there is a memory allocation error. - */ - -int WriteLinkRasterDirectOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - -/** - * Writes a buffered direct model image with an offset to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRasterDirectOffset(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point (upper left corner), in decimal degrees. - * @param lon The longitude of the anchor point (upper left corner), in decimal degrees. - * @param x The X coordinate of the image location, offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location, offset from the anchor point, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *directimage The image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterDirectOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - DirectImage *directimage, - LinkArgs *linkArgs); - -/*-----------------------------------------------------------*/ -/*Prototypes for writing Indexed model images */ - -/** - * Writes an indexed model image to the link socket. - * - * @param *linkSocket The link socket - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param width The width of the image. - * @param height The height of the image. - * @param transparency The transparency of the image, in a range of 0-255. A transparency of 255 means an opaque image. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRasterIndexedLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - -/** - * Writes a buffered indexed model image to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkRasterIndexedLatLon(). - * - * @param *linkSocket The link socket - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param width The width of the image. - * @param height The height of the image. - * @param transparency The transparency of the image, in a range of 0-255. A transparency of 255 means an opaque image. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterIndexedLatLon(LinkSocket *linkSocket, - double lat, double lon, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - - -/** - * Writes an indexed model image in X-Y space to the link socket. - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), offset from the top left corner of the canvas, in pixels. - * @param y The Y coordinate of the image location, offset from the top left corner of the canvas, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param transparency The transparency of the image, in a range of 0-255. A transparency of 255 means an opaque image. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteLinkRasterIndexedXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - -/** - * Writes a buffered indexed model image in X-Y space to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRasterIndexedXY(). - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), offset from the top left corner of the canvas, in pixels. - * @param y The Y coordinate of the image location, offset from the top left corner of the canvas, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param transparency The transparency of the image, in a range of 0-255. A transparency of 255 means an opaque image. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterIndexedXY(LinkSocket *linkSocket, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - -/** - * Writes an indexed model image with an offset to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there's a memory allocation error. - */ - -int WriteLinkRasterIndexedOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - -/** - * Writes a buffered indexed model image with an offset to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRasterIndexedOffset(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param width The width of the image, in pixels. - * @param height The height of the image, in pixels. - * @param *indeximage The indexed image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterIndexedOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - int width, int height, - int transparency, - IndexedImage *indeximage, - LinkArgs *linkArgs); - -/*--------------------------------------------------------*/ - -/*Prototypes for writing Images that are refered as a URL*/ - -/** - * Writes an image that is referred as a URL to the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param *url URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteLinkRasterImageURLLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *url, - LinkArgs *linkArgs); - -/** - * Writes a buffered image that is referred as a URL to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRasterImageURLLatLon(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the image location (upper left corner), in decimal degrees. - * @param lon The longitude of the image location (upper left corner), in decimal degrees. - * @param *url URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterImageURLLatLon(LinkSocket *linkSocket, - double lat, double lon, - char *url, - LinkArgs *linkArgs); - -/** - * Writes an image in X-Y space that is referred as a URL, to the link socket. - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), offset from the upper left corner of the canvas, in pixels. - * @param y The Y coordinate of the image location, offset from the upper left corner of the canvas, in pixels. - * @param *url The URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRasterImageURLXY(LinkSocket *linkSocket, - int x, int y, - char *url, - LinkArgs *linkArgs); - -/** - * Writes a buffered image in X-Y space that is referred as a URL, to the - * link socket. DEPRECATED - * - * Deprecated: Use WriteLinkRasterImageURLXY(). - * - * @param *linkSocket The link socket. - * @param x The X coordinate of the image location (upper left corner), offset from the upper left corner of the canvas, in pixels. - * @param y The Y coordinate of the image location, offset from the upper left corner of the canvas, in pixels. - * @param *url The URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterImageURLXY(LinkSocket *linkSocket, - int x, int y, - char *url, - LinkArgs *linkArgs); -/** - * Writes an image with an offset that is referred as a URL, to - * the link socket. - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location, offset from the anchor point, in pixels. - * @param *url The URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRasterImageURLOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - char *url, - LinkArgs *linkArgs); - -/** - * Writes an image with an offset that is referred as a URL, to - * the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkRasterImageURLOffset(). - * - * @param *linkSocket The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of the image location (upper left corner), offset from the anchor point, in pixels. - * @param y The Y coordinate of the image location, offset from the anchor point, in pixels. - * @param *url The URL of the image. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRasterImageURLOffset(LinkSocket *linkSocket, - double lat, double lon, - int x, int y, - char *url, - LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkRectangle.h b/src/core/src/main/include/cserver/link/LinkRectangle.h deleted file mode 100644 index 74328a34d..000000000 --- a/src/core/src/main/include/cserver/link/LinkRectangle.h +++ /dev/null @@ -1,159 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkRectangle.h,v $ - * $RCSfile: LinkRectangle.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKRECTANGLE_H -#define LINKRECTANGLE_H - -#include "LinkSocket.h" -#include "Request.h" -#include "LinkArgs.h" - - -/*Prototypes for Writing Rectangle Object*/ - -/** - * Writes a rectangle object in lat-long space to the link socket. - * - * @param *link The link socket. - * @param ltype The line type. - * @param NWlat The latitude of the top left corner of the rectangle, in decimal degrees. - * @param NWlon The longitude of the top left corner of the rectangle, in decimal degrees. - * @param SElat The latitude of the lower right corner of the rectangle, in decimal degrees. - * @param SElon The longitude of the lower right corner of the rectangle, in decimal degrees. - * @param nsegs The number of segments used to approximate the rectangle. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRectangleLatLon(LinkSocket *link, int ltype, - double NWlat, double NWlon, /*NW = North West*/ - double SElat, double SElon, /*SE = South East*/ - int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a rectangle object in X-Y space to the link socket. X-Y values are - * from the top left corner of the canvas. - * - * @param link The link socket. - * @param ulx The X coordinate of the upper left corner of the rectangle, in pixels. - * @param uly The Y coordinate of the upper left corner of the rectangle, in pixels. - * @param lrx The X coordinate of the lower right corner of the rectangle, in pixels. - * @param lry The Y coordinate of the lower right corner of the rectangle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRectangleXY(LinkSocket *link, - int ulx, int uly, /*ul = upper left */ - int lrx, int lry, - LinkArgs *linkArgs); - -/** - * Writes a rectangle object with an offset to the link socket. X-Y values - * are offset from the lat-long anchor point, in pixels. - * - * @param link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param ulx The X coordinate of the upper left corner of the rectangle, in pixels. - * @param uly The Y coordinate of the upper left corner of the rectangle, in pixels. - * @param lrx The X coordinate of the lower right corner of the rectangle, in pixels. - * @param lry The Y coordinate of the lower right corner of the rectangle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkRectangleOffset(LinkSocket *link, - double lat, double lon, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs); - -/** - * Writes a buffered rectangle object in lat-long space to the link socket. - * DEPRECATED - * - * Deprecated: Use WriteLinkRectangleLatLon(). - * - * @param *link The link socket. - * @param ltype The line type. - * @param NWlat The latitude of the top left corner of the rectangle, in decimal degrees. - * @param NWlon The longitude of the top left corner of the rectangle, in decimal degrees. - * @param SElat The latitude of the lower right corner of the rectangle, in decimal degrees. - * @param SElon The longitude of the lower right corner of the rectangle, in decimal degrees. - * @param nsegs The number of segments used to approximate the rectangle. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRectangleLatLon(LinkSocket *link, int ltype, - double NWlat, double NWlon, /*NW = North West*/ - double SElat, double SElon, /*SE = South East*/ - int nsegs, - LinkArgs *linkArgs); - -/** - * Writes a buffered rectangle object in X-Y space to the link socket. X-Y - * values are from the top left corner of the canvas. DEPRECATED - * - * Deprecated: Use WriteLinkRectangleXY(). - * - * @param link The link socket. - * @param ulx The X coordinate of the upper left corner of the rectangle, in pixels. - * @param uly The Y coordinate of the upper left corner of the rectangle, in pixels. - * @param lrx The X coordinate of the lower right corner of the rectangle, in pixels. - * @param lry The Y coordinate of the lower right corner of the rectangle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRectangleXY(LinkSocket *link, - int ulx, int uly, /*ul = upper left */ - int lrx, int lry, - LinkArgs *linkArgs); - -/** - * Writes a buffered rectangle object with an offset to the link socket. X-Y - * values are offset from the lat-long anchor point, in pixels. DEPRECATED - * - * Deprecated: Use WriteLinkRectangleOffset(). - * - * @param link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param ulx The X coordinate of the upper left corner of the rectangle, in pixels. - * @param uly The Y coordinate of the upper left corner of the rectangle, in pixels. - * @param lrx The X coordinate of the lower right corner of the rectangle, in pixels. - * @param lry The Y coordinate of the lower right corner of the rectangle, in pixels. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkRectangleOffset(LinkSocket *link, - double lat, double lon, - int ulx, int uly, - int lrx, int lry, - LinkArgs *linkArgs); - -#endif diff --git a/src/core/src/main/include/cserver/link/LinkSocket.h b/src/core/src/main/include/cserver/link/LinkSocket.h deleted file mode 100644 index 0876e352d..000000000 --- a/src/core/src/main/include/cserver/link/LinkSocket.h +++ /dev/null @@ -1,320 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkSocket.h,v $ - * $RCSfile: LinkSocket.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKSOCKET_H -#define LINKSOCKET_H - -#include "toolLib/sockets.h" -#include - -/** - * The link socket. - * - * @param *host The host. - * @param mainsd The main socket descriptor required to accept connections. - * @param sd The socket descriptor returned when the connection is accepted. - * @param port The port on which the socket will listen. - * @param error Any errors. - * @param *writebuffer - * @param maxbuffer The maximum size of the buffer. - * @param currentbuffer The pointer to the buffer, from where data needs to be sent. - * @param isBuffered Boolean, indicating if the socket is buffered or not. By default, buffering is on. Write functions will attempt to write the entire data into the buffer. If it's not successful, write functions will flush the buffer first and write data directly to the socket. If successful, the data will remain in the buffer until the flush is called. This should be set to LINK_TRUE if unbuffered write functions are used. Set it to LINK_FALSE if buffered writes are used. WARNING: The buffered versions are deprecated, and will be removed in a future release. - */ - -struct LinkSocket{ - char *host; - int mainsd; /*main socket descriptor required to accept connections*/ - int sd; /*socket descriptor returned, when connection is accepted*/ - int port; /*number on which socket will listen to */ - int error; /*error if any*/ - /* - Buffering within the socket. - */ - char *writebuffer; - int maxbuffer; /*Maximum size of the buffer*/ - int currentbuffer; /*pointer to the buffer, from where data needs to be sent.*/ - int isBuffered; /*Boolean, indicating if socket is buffered or not*/ -}; -typedef struct LinkSocket LinkSocket; - -/* - Note: By Default Buffering is on. - Write functions will attempt to write entire data into the buffer. - ..if not succesful, write functions would flush the buffer first and - write data directly to the socket. - ..if successful, data would remain untill flush is called. -*/ - -/** - * Initializes the internet domain socket as a server. - * - * @param *socket The socket to initialize. - * @returns -1 if there was a memory allocation error. - */ - -int InitSocket(LinkSocket *socket); - -/** - * Check to see if the error flag is set. - * - * @param *socket The link socket. - */ - -int CheckSocket(LinkSocket* socket); - - -/** - * Frees the link socket. - * - * @param *socket The link socket. - */ - -void FreeSocket(LinkSocket *socket); - -/** - * Functions for interconversion between integer and char so that they - * can be sent and read over the socket. - * - * @param *toBuffer - * @param ivalue - */ - -void IntegerToBytes(char *toBuffer, int ivalue); - -/** - * Functions for interconversion between integer and char so that they - * can be sent and read over the socket. - * - * @param *ptrInteger - * @param *fromBuffer - */ - -void BytesToInteger(int *ptrInteger, char *fromBuffer); - -/* - Note:- User should allocate the required memory and pass pointers. -*/ - -/** - * Reads an integer off the socket in a user-provided buffer. - * - * @param *socket The link socket. - * @param *ptrIntegerBuffer The integer buffer to read into. - * @returns OK if successful. - */ - -int ReadInteger(LinkSocket *socket, int *ptrIntegerBuffer); - -/** - * Writes an integer to the socket. - * - * @param *socket The link socket. - * @param iValue The integer to write to the socket. - * @returns OK if successful, NOK if failure. - */ - -int WriteInteger(LinkSocket *socket, int iValue); - -/** - * Writes an integer to a buffer. DEPRECATED - * - * Deprecated: Use WriteInteger(). - * - * @param *tobuffer Buffer to write to. - * @param iValue Integer to write to the buffer. - */ - -int BufferedWriteInteger(char *tobuffer,int iValue); - -/** - * Reads Unicode characters from the socket and stores them in a buffer - * as ASCII characters. - * - * Returns OK and sets the socket's error flag to LINK_FALSE if it - * successfully wrote nchartoread. Otherwise, it returns NOK and - * sets the socket's error flag to LINK_TRUE. This function blocks - * until it reads nchartoread characters. - * @param *socket The link socket. - * @param *ptrBuffer Buffer to store the characters in. - * @param nchartoread Number of characters to read. - * @returns -1 if there was a memory allocation error. - */ - -int ReadUnicodeChars(LinkSocket *socket, char *ptrBuffer, int nchartoread); - -/** - * Writes ASCII characters in buffer as Unicode characters to the socket. - * - * Returns OK and sets the socket's error flag to LINK_FALSE if it successfully - * wrote nchartowrite characters. Otherwise, it returns NOK and sets the - * socket's error flag to LINK_TRUE. This function blocks util it writes - * nchartowrite characters. - * @param *socket The link socket. - * @param *ptrBuffer The buffer. - * @param nchartowrite The number of characters to write. - * @returns -1 if there was a memory allocation error. - */ - -int WriteUnicodeChars(LinkSocket *socket, char *ptrBuffer, int nchartowrite); - -/** - * Writes Unicode characters to a buffer instead of the socket.DEPRECATED - * - * Deprecated: Use WriteUnicodeChars(). - * - * @param *toBuffer Buffer to write to. - * @param *fromBuffer Buffer to read from. - * @param nchartowrite Number of characters to write. - */ - -int BufferedWriteUnicodeChars(char *toBuffer, char *fromBuffer, int nchartowrite); - -/** - * Reads nchartoread ASCII characters from the socket into a buffer. - * - * Returns OK and sets the socket's error flag to LINK_FALSE if it successfully - * read nchartoread characters. Otherwise, it returns NOK and sets the - * socket's error flag to LINK_TRUE. This function blocks until it reads - * nchartoread characters. - * @param *socket The link socket. - * @param *ptrBuffer Buffer to read into. - * @param nchartoread Number of characters o read. - */ - -int ReadChars(LinkSocket *socket, char *ptrBuffer, int nchartoread); - -/** - * Writes nchartowrite characters from a buffer to the socket. - * - * Returns OK and sets the socket's error flag to LINK_FALSE if it - * successfully wrote nchartowrite characters. Otherwise, it will - * return NOK and set the socket's error flag to LINK_TRUE. This - * function blocks util it writes nchartowrite characters. - * @param *socket The link socket. - * @param *fromBuffer The buffer to read from. - * @param nchartowrite The number of characters to write. - */ - -int WriteChars(LinkSocket *socket, char *fromBuffer, int nchartowrite); - -/** - * Writes characters to a buffer instead of the socket. DEPRECATED - * - * Deprecated: Use WriteChars(). - * - * @param *toBuffer Buffer to write to. - * @param *fromBuffer Buffer to read from. - * @param nchartowrite Number of characters to write. - */ - -int BufferedWriteChars(char *toBuffer, char *fromBuffer, int nchartowrite); - -/** - * Reads a 4-byte float value from a socket into a user-provided buffer. - * - * The float value read in will be typecasted into a double. - * @param *socket The link socket. - * @param *ptrDouble The float value to be read in. - * @returns OK if successful, NOK if it fails. - */ - -int ReadFloat(LinkSocket *socket, double *ptrDouble); - -/** - * Writes a float value to the socket. - * - * @param *socket The link socket. - * @param fvalue The float value to write. - * @returns OK if successful, NOK if it fails. - */ - -int WriteFloat(LinkSocket *socket, float fvalue); - -/** - * Writes a float to a buffer instead of a socket. DEPRECATED - * - * Deprecated: Use WriteFloat(). - * - * @param *toBuffer Buffer to write to. - * @param fvalue The float value to write. - */ - -int BufferedWriteFloat(char *toBuffer, float fvalue); - -/** - * Flushes the socket's write buffer. - * - * @param *socket The link socket. - * @returns OK if it successfully wrote the entire buffer to the socket. Returns NOK if it fails. - */ -int Socketflush(LinkSocket *socket); - -/** - * Copies all from the parent to the child except sd, since it is new for - * every child. - * - * @param *parent The parent link socket. - * @param *child The child link socket. - * @returns -1 if there was a memory allocation error. - */ - -int SocketCopyParentToChild(LinkSocket *parent, LinkSocket *child); - -/** - * Translates an English Unicode string to ASCII by stripping the first - * byte from each two-byte pair per character. This is NOT a comprehensive - * solution for translating from Unicode to ASCII. - * - * @param unicodechar[] The Unicode string to translate. - * @param length The length of the Unicode string, in characters - * @returns The translated ASCII string. - */ - -char *EnglishUnicodeToASCII(char unicodechar[], int length); - -/** - * Translates an ASCII string to Unicode by prefixing each ASCII character - * byte with 0x0; note that this does not work for any other language than - * English. - * - * @param cchar[] The ASCII string to translate. - * @returns The translated Unicode string. - */ - -char *ASCIIToEnglishUnicode(char cchar[]); - -#endif - -/** - * Compares two Unicode strings. Ordinarily, strcmp() would be used to - * handle the comparison of two strings, but it fails when faced with - * the first character of an English ASCII character in Unicode (\0). - * This is not as full-featured as strcmp(). - * - * @param *s1 The first string to compare. - * @param *s2 The second string to compare. - * @param length The length of the strings. (You need to know this ahead of time.) - * @returns 0 if the strings are equal. - */ - -int unicodecmp(const char *s1, const char *s2, int length); diff --git a/src/core/src/main/include/cserver/link/LinkText.h b/src/core/src/main/include/cserver/link/LinkText.h deleted file mode 100644 index bb0f9a9ab..000000000 --- a/src/core/src/main/include/cserver/link/LinkText.h +++ /dev/null @@ -1,174 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/LinkText.h,v $ - * $RCSfile: LinkText.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:09 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef LINKTEXT_H -#define LINKTEXT_H - -#include "LinkSocket.h" -#include "Request.h" -#include "LinkArgs.h" - -#define DEFAULT_FONT "-*-new century schoolbook-*-*-*-*-14-*-*-*-*-*-*-*" - -/*Prototypes for Writing Text Object*/ - -/** - * Writes text to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of where the text should be drawn, in decimal degrees. - * @param lon The longitude of where the text should be drawn, in decimal degrees. - * @param numberOfCharsInString The number of characters in the string. - * @param *string The string of text. - * @param *fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is in Unicode, the number of characters the string takes. - * @returns OK if successful. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkTextLatLon(LinkSocket *link, - double lat, double lon, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars); - -/** - * Writes text in X-Y space to the link socket. - * - * @param *link The link socket. - * @param x The X coordinate of where the text should be drawn, offset from the upper left corner of the canvas, in pixels. - * @param y The Y coordinate of where the text should be drawn, offset from the upper left corner of the canvas, in pixels. - * @param numberOfCharsInString The number of characters in the string. - * @param fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is Unicode, how many characters the string takes up. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkTextXY(LinkSocket *link, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars); - -/** - * Writes text with an offset to the link socket. - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of where the text should be drawn, offset from the anchor point, in pixels. - * @param y The Y coordinate of where the text should be drawn, offset from the anchor point, in pixels. - * @param numberOfCharsInString The number of characters in the string. - * @param *fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is in Unicode, the number of characters the string takes. - * @returns -1 if there was a memory allocation error. - */ - -int WriteLinkTextOffset(LinkSocket *link, - double lat, double lon, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, int is_unicode, - int num_unicode_chars); - -/** - * Writes buffered text to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkTextLatLon(). - * - * @param *link The link socket. - * @param lat The latitude of where the text should be drawn, in decimal degrees. - * @param lon The longitude of where the text should be drawn, in decimal degrees. - * @param numberOfCharsInString The number of characters in the string. - * @param *string The string of text. - * @param *fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is in Unicode, the number of characters the string takes. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkTextLatLon(LinkSocket *link, - double lat, double lon, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, - int is_unicode, int num_unicode_chars); - - -/** - * Writes buffered text in X-Y space to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkTextXY(). - * - * @param *link The link socket. - * @param x The X coordinate of where the text should be drawn, offset from the upper left corner of the canvas, in pixels. - * @param y The Y coordinate of where the text should be drawn, offset from the upper left corner of the canvas, in pixels. - * @param numberOfCharsInString The number of characters in the string. - * @param fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is in Unicode, the number of characters the string takes. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkTextXY(LinkSocket *link, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, - int is_unicode, int num_unicode_chars); - - -/** - * Writes buffered text with an offset to the link socket. DEPRECATED - * - * Deprecated: Use WriteLinkTextOffset(). - * - * @param *link The link socket. - * @param lat The latitude of the anchor point, in decimal degrees. - * @param lon The longitude of the anchor point, in decimal degrees. - * @param x The X coordinate of where the text should be drawn, offset from the anchor point, in pixels. - * @param y The Y coordinate of where the text should be drawn, offset from the anchor point, in pixels. - * @param numberOfCharsInString The number of characters in the string. - * @param *fontAsString - * @param justification The justification of the string. Possible values are JUSTIFY_LEFT, JUSTIFY_CENTER, and JUSTIFY_RIGHT. (See Link.h) - * @param *linkArgs The link arguments. - * @param is_unicode 1 if the string is already in Unicode. - * @param num_unicode_chars If the string is in Unicode, the number of characters it takes. - * @returns -1 if there was a memory allocation error. - */ - -int BufferedWriteLinkTextOffset(LinkSocket *link, - double lat, double lon, int x, int y, - char *String, char *fontAsString, - int justification, LinkArgs *linkArgs, - int is_unicode, int num_unicode_chars); - -#endif diff --git a/src/core/src/main/include/cserver/link/MapRequest.h b/src/core/src/main/include/cserver/link/MapRequest.h deleted file mode 100644 index beee77bfc..000000000 --- a/src/core/src/main/include/cserver/link/MapRequest.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/MapRequest.h,v $ - * $RCSfile: MapRequest.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef MAPREQUEST_H -#define MAPREQUEST_H - -#include "Request.h" -#include "LinkArgs.h" - -/*#include "Link.h"*/ - -/** - * The MapRequest, which holds the Map (graphics query) information sent by - * the client. - * - * @param version The version. - * @param centerlatitude In decimal degrees. - * @param centerlongitude In decimal degrees. - * @param scale - * @param height - * @param width - * @param boundingPolygon - * @param linkargs THe link arguments. - */ - -struct MapRequest { - double version; - double centerlatitude; /*in decimal degrees*/ - double centerlongitude; /* --"-- */ - double scale; - int height; - int width; - BoundingPolygon boundingPolygon; - LinkArgs linkargs; -}; -typedef struct MapRequest MapRequest; - -struct Link; - -/** - * Reads the map object off the socket. - * - * @param link The link. - * @returns -1 if there was a memory allocation error. - * - */ - -int ReadMapRequest(struct Link* link); - -/** - * Frees all of the memory from a map request object. - * - * @param *map The map request to free memory from. - */ - - -void FreeMapRequest(MapRequest *map); - -#endif - - diff --git a/src/core/src/main/include/cserver/link/Request.h b/src/core/src/main/include/cserver/link/Request.h deleted file mode 100644 index 175ec1463..000000000 --- a/src/core/src/main/include/cserver/link/Request.h +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef REQUEST_H -#define REQUEST_H - -/* -This file defines structures and methods that are common to MapRequest, -ActionRequest and GuiRequest -*/ - -#include "LatLonPoint.h" - -/** - * The polygon structure. - * - * @param numberOfPoints Number of points in the polygon. - * @param *points Array of lat-long point objects that describe the polygon. - */ - -struct Polygon { - int numberOfPoints; - LatLonPoint *points; -}; -typedef struct Polygon Polygon; - -/** - * The bounding polygon structure. - * - * @param numberOfPolygons The number of polygons. - * @param *polygons The polygons. - */ - -struct BoundingPolygon { - int numberOfPolygons; - Polygon *polygons; -}; -typedef struct BoundingPolygon BoundingPolygon; - -/** - * Reads the bounding polygon from a socket. - * - * @param *linkSocket The link socket. - * @param *bpoly The bounding polygon. - * @returns -1 if there was a memory allocation error. - */ - -int ReadBoundingPolygons(LinkSocket *linkSocket, BoundingPolygon *bpoly); - -/** - * Reads polygons off the socket. - * - * @param *linkSocket The link socket. - * @param *poly The polygon to be read. - * @returns -1 if there was a memory allocation error. - */ - -int ReadPolygons(LinkSocket *linkSocket, Polygon *poly); - -/** - * Frees the memory from a given bounding polygon. - * - * @param *bpoly The bounding polygon to free memory from. - */ - -void FreeBoundingPolygons(BoundingPolygon *bpoly); - -/** - * Frees the memory from a given polygon. - * - * @param *poly The polygon to free memory from. - */ - -void FreePolygons(Polygon *poly); - -/*--------------------------------------------------*/ - -/** - * The descriptor. - * - * @param :20 Unused bits. - * @param SERVER_NOTIFICATION Server should be notified even if the client acts on some property in a graphic during gesture handling. - * @param CLIENT_NOTIFICATION The server is interested only in messages whose bit value is set. - * @param IS_GRAPHIC_INVOLVED - * @param KEY_RELEASED On the keyboard. - * @param KEY_PRESSED On the keyboard. - * @param MOUSE_DRAGGED With the left button down. - * @param MOUSE_EXIT THe mouse exiting the area of interest (map). - * @param MOUSE_ENTER The mouse entering the area of interest. - * @param MOUSE_MOVE A simple move over the area of interest. - * @param MOUSE_RELEASED The mouse button is released (second half of a click). - * @param MOUSE_PRESSED The mouse button is pressed (first half of a click). - * @param MOUSE_CLICK The mouse button is pressed and released. - */ - -struct Descriptor -{ -/**@#-*/ - unsigned :20; /*unused bits*/ -/**@#+*/ - unsigned SERVER_NOTIFICATION :1; /*Server should be notified even - if the client acts on some - property in a graphic during - gesture handling. */ - unsigned CLIENT_NOTIFICATION :1; /*server is interested only in - messages whose bit value is set*/ - unsigned IS_GRAPHIC_INVOLVED :1; - unsigned KEY_RELEASED :1; /*ON KEYBOARD*/ - unsigned KEY_PRESSED :1; /*ON KEYBOARD*/ - unsigned MOUSE_DRAGGED :1; /*WITH LEFT BUTTON DOWN*/ - unsigned MOUSE_EXIT :1; /*Mouse Exit area of interest (MAP)*/ - unsigned MOUSE_ENTER :1; /*Mouse Enter area of interest (MAP)*/ - unsigned MOUSE_MOVE :1; /* Simple move over area of interest(MAP) */ - unsigned MOUSE_RELEASED :1; /*mouse button released .. 2nd half of click*/ - unsigned MOUSE_PRESSED :1; /*mouse button pressed..half click */ - unsigned MOUSE_CLICK :1;/*mouse button pressed and released*/ -}; -typedef struct Descriptor Descriptor; - -/** - * The modifier - * - * @param :27 Unused bits. - * @param KEY_SHIFT_PRESSED - * @param KEY_CONTROL_PRESSED - * @param META_CHANGE The meta key is pressed OR the mouse's third button changed its state. - * @param ALT_CHANGE The alt key is pressed OR the mouse's second button changed its state. - * @param KEY_ALT_GRAPH_PRESSED The alt graph key's state changed. - * - */ - -struct Modifier -{ -/**@#-*/ - unsigned :27; /*unused bits....*/ -/**@#+*/ - unsigned KEY_SHIFT_PRESSED :1; - unsigned KEY_CONTROL_PRESSED :1; - unsigned META_CHANGE :1; /*Meta key pressed OR Mouse's 3rd button - changed its state*/ - unsigned ALT_CHANGE :1; /*Alt key down OR Mosue's 2nd button - changed its state*/ - unsigned KEY_ALT_GRAPH_PRESSED :1; /*State changed of alt graph key*/ -}; -typedef struct Modifier Modifier; - -/** - * Reads the descriptor from the socket. - * - * @param *linkSocket The link socket. - * @param *descriptor The descriptor to read. - */ - -int ReadDescriptor(LinkSocket *linkSocket, Descriptor *descriptor); - -/** - * Reads the modifier from the socket. - * - * @param *linkSocket The link socket. - * @param *modifier The modifier to read. - */ - -int ReadModifier(LinkSocket *linkSocket, Modifier *modifier); - -/*---------------------------------------------------------*/ -#endif - diff --git a/src/core/src/main/include/cserver/link/Response.h b/src/core/src/main/include/cserver/link/Response.h deleted file mode 100644 index a31e61043..000000000 --- a/src/core/src/main/include/cserver/link/Response.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/link/include/Response.h,v $ - * $RCSfile: Response.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef RESPONSE_H -#define RESPONSE_H - -#include "Request.h" -#include "LinkArgs.h" - -/** - * Writes the graphics response header to the link socket. - * - * @param *link The link socket. - * @param *linkArgs The link arguments. - * @returns -1 if there was a memory allocation error. - */ - - -int WriteMapResponseHeader(LinkSocket *link, LinkArgs *linkArgs); - -/** - * Writes the action response header to the link socket. - * - * @param *link The link socket. - * @param *linkArgs the link arguments. - * @returns -1 if there was a memory allocation error. - */ - -int WriteActionResponseHeader(LinkSocket *link, LinkArgs *linkArgs); - -/** - * Signals the end of a section. - * - * @param *link The link socket. - * - */ - - -void EndSection(LinkSocket *link); - -/** - * Signals the end of the transmission. - * - * @param *link The link socket. - * - */ - -void EndTotal(LinkSocket *link); - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/Magic.h b/src/core/src/main/include/cserver/toolLib/Magic.h deleted file mode 100644 index 6c1798da6..000000000 --- a/src/core/src/main/include/cserver/toolLib/Magic.h +++ /dev/null @@ -1,39 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/Magic.h,v $ - * $RCSfile: Magic.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef MagicInclude -#define MagicInclude - -#include "compat.h" - -typedef char *Magic; -BEGIN_extern_C - -extern const Magic NewMagicNumber( -#if NeedFunctionPrototypes - const char *ident -#endif -); - -END_extern_C -#endif diff --git a/src/core/src/main/include/cserver/toolLib/auto_input.h b/src/core/src/main/include/cserver/toolLib/auto_input.h deleted file mode 100644 index 59c556b67..000000000 --- a/src/core/src/main/include/cserver/toolLib/auto_input.h +++ /dev/null @@ -1,109 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/auto_input.h,v $ - * $RCSfile: auto_input.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - - -/* - * This module provides an automated socket input facility. - * - * Callers specify how much data they want to get and what - * callback function to call when that amount of data has been - * gotten for them. - * - * These functions allocate the data buffers with the xxbufs - * module but DO NOT FREE the data buffers. - * - * It is up to the client to free the buffers. There will always - * only be one buffer per input file descriptor, and its address - * is always passed to the callback functions. - * - * Callback functions are called with a success flag so they - * can figure out if there was a socket error or not. - * - * ------------------------------------------------------------------------ */ - -#ifndef _auto_input_include -#define _auto_input_include - -#include "compat.h" - - -typedef int (*AutoInputBufCBProc)( -#if NeedFunctionPrototypes - char *, /* clientData */ - char *, /* data */ - int, /* bytesInBuffer */ - int, /* bufferSize */ - int /* Success */ -#endif -); /* pointer to a procedure */ - -BEGIN_extern_C - -extern int InitAutoInputBufs( -#if NeedFunctionPrototypes -#endif -); - -extern int CancelAutoInput( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern int ResumeAutoInput( -#if NeedFunctionPrototypes - int, /* fd */ - int, /* bytesNeeded */ - char *, /* clientData */ - AutoInputBufCBProc, /* callback */ - const char * /* callbackName */ -#endif -); - -extern int AutoInputLine( -#if NeedFunctionPrototypes - int, /* fd */ - char *, /* clientData */ - AutoInputBufCBProc, /* callback */ - const char * /* callbackName */ -#endif -); - -extern int StartAutoInput( -#if NeedFunctionPrototypes - int, /* fd */ - int, /* bytesNeeded */ - char *, /* clientData */ - AutoInputBufCBProc, /* callback */ - const char * /* callbackName */ -#endif -); - -extern void FlushAutoInput( -#if NeedFunctionPrototypes - int fd -#endif -); - -END_extern_C -#endif diff --git a/src/core/src/main/include/cserver/toolLib/auto_output.h b/src/core/src/main/include/cserver/toolLib/auto_output.h deleted file mode 100644 index f6bf36f8a..000000000 --- a/src/core/src/main/include/cserver/toolLib/auto_output.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/auto_output.h,v $ - * $RCSfile: auto_output.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef _auto_output_include -#define _auto_output_include - -#include "compat.h" - - -typedef int (*AutoOutputBufCBProc)( -#if NeedFunctionPrototypes - char *, /* clientData */ - int, /* bytesAlreadySent */ - char *, /* data */ - int /* Success */ -#endif -); /* pointer to a procedure */ - -BEGIN_extern_C - -extern int InitAutoOutputBufs( -#if NeedFunctionPrototypes -#endif -); - -extern int CancelAutoOutput( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern int StartAutoOutput( -#if NeedFunctionPrototypes - int, /* fd */ - char *, /* data */ - int, /* bytesToSend */ - char *, /* clientData */ - AutoOutputBufCBProc, /* callback */ - const char * /* callbackName */ -#endif -); - -extern void FlushAutoOutput( -#if NeedFunctionPrototypes - int fd -#endif -); - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/buffers.h b/src/core/src/main/include/cserver/toolLib/buffers.h deleted file mode 100644 index e0af06ba3..000000000 --- a/src/core/src/main/include/cserver/toolLib/buffers.h +++ /dev/null @@ -1,153 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/buffers.h,v $ - * $RCSfile: buffers.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - - -/* - * This module handles memory buffer pools where the buffers are - * always sized in powers of 2. - * - * GetNewBufferAndSize() returns a pointer to a buffer of at least - * the requested size and returns also the - * actual size of the buffer. - * - * FreeBuffer() Takes a buffer that was created by - * GetNewBufferAndSize and returns it back to - * the buffer pool. - * - * GetNewBuffer() Is a macro in buffers.h that simply calls - * GetNewBufferAndSize without requiring the - * actual size argument for convenience. - * - * This module will use malloc() to get more memory to put into - * the buffer pool but will never call free(). It always tries to - * satisfy new buffer requests from its pool of free buffers. - * The constraints are set up so that the buffers are always - * between BufMinAlloc and BufMaxAlloc and that a given buffer is - * never more than OversizeLimit bigger than the requested size. - * - * That is so that a usefule sized buffer is created even when a tiny - * one is requested. In the world of the X Protocol, 32 bytes is - * the best minimum size since events and a lot of requests and replies - * fit into that size. - * - * The OversizeLimit prevents a small request from chewing up a large - * buffer since that could cause a lot of large buffers to be created - * and then be underutilized. - * - * ------------------------------------------------------------------------ */ - -#ifndef buffers_include -#define buffers_include - -#include "compat.h" -#include "style.h" - -#define BufMinAlloc 32 /* Must be power of 2 */ -#define BufMaxAlloc 1024 * 1024 /* Must be power of 2 */ - -/* - * The OversizeLimit is a multiplier used to limit the magnitude of - * the returned buffer size. If a buffer of size N is requested, - * the returned buffer will be at most - * (first power of 2 >= min(N, BufMinAlloc)) * OversizeLimit - * bytes long. e.g if you request a buffer of 500 bytes, - * the biggest you'll get back is 1024 bytes. - */ - -#define OversizeLimit 2 /* Must be power of 2 that's >= 2 */ - -#define GetNewBuffer(size) GetNewBufferAndSize((size), 0) - - -BEGIN_extern_C - -Bool IsABuffer( -#if NeedFunctionPrototypes - char * /* buf */ -#endif -); - -int FreeBuffer( -#if NeedFunctionPrototypes - char * /* buf */ -#endif -); - -char *GetNewBufferAndSize( -#if NeedFunctionPrototypes - int, /* size */ - int * /* actual size */ -#endif -); - -char *IncreaseBufferSize( -#if NeedFunctionPrototypes - char *, /* buffer */ - int, /* size */ - int * /* actual size */ -#endif -); - -int DebugFreeBuffer( -#if NeedFunctionPrototypes - char *, /* buf */ - const char *, /* file */ - int /* line */ -#endif -); - -char *DebugGetNewBufferAndSize( -#if NeedFunctionPrototypes - int, /* size */ - int *, /* actual size */ - const char *, /* file */ - int /* line */ -#endif -); - -char *DebugIncreaseBufferSize( -#if NeedFunctionPrototypes - char *, /* buffer */ - int, /* size */ - int *, /* actual size */ - const char *, /* file */ - int /* line */ -#endif -); - -int InitBuffers( -#if NeedFunctionPrototypes -#endif -); - -#ifndef BuffersPrivate -#ifdef DebugBufferPrintout -#define FreeBuffer(a) DebugFreeBuffer((a), __FILE__, __LINE__) -#define GetNewBufferAndSize(a, b) DebugGetNewBufferAndSize((a), (b), __FILE__, __LINE__) -#define IncreaseBufferSize(a, b, c) DebugIncreaseBufferSize((a), (b), (c), __FILE__, __LINE__) -#endif -#endif - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/compat.h b/src/core/src/main/include/cserver/toolLib/compat.h deleted file mode 100644 index 6338cab25..000000000 --- a/src/core/src/main/include/cserver/toolLib/compat.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/compat.h,v $ - * $RCSfile: compat.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef compatInclude -#define compatInclude - -#ifndef NeedFunctionPrototypes -# if defined(__STDC__) || defined(__cplusplus) -# define NeedFunctionPrototypes 1 -# else -# define NeedFunctionPrototypes 0 -# endif -#endif /* NeedFunctionPrototypes */ - -/* - * Traditional C compilers tend to replace the string consisting - * of begin comment/endcomment with nothing, other C compilers replace - * it with a single space. Luckily, those seem to use the ## as a non-spacing - * concatenation operator. - */ - -#if !defined(__OBJY_DDL__) && (defined(__GNUC__) || defined(__STDC__) || defined(__cplusplus)) -#define STRCAT(A,B) A##B -#else -#define STRCAT(A,B) A/**/B -#endif - -/* - * This is to allow the use of const in both ansi/C++ and non-ansi C - */ - -#if defined(__GNUC__) || defined(__STDC__) || defined(__cplusplus) - -#else -#define const -#endif - -#if defined(__cplusplus) -#define BEGIN_extern_C extern "C" { -#define END_extern_C } -#else -#define BEGIN_extern_C -#define END_extern_C -#endif - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/compress.h b/src/core/src/main/include/cserver/toolLib/compress.h deleted file mode 100644 index 1f614ee31..000000000 --- a/src/core/src/main/include/cserver/toolLib/compress.h +++ /dev/null @@ -1,35 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/compress.h,v $ - * $RCSfile: compress.h,v $ - * $Revision: 1.1.1.1 $ - * $Date: 2003/02/14 21:35:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef compress_include -#define compress_include -#include - -#include "compat.h" -BEGIN_extern_C - -extern int decompress(FILE *, FILE *, unsigned char *, int); - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/debugging.h b/src/core/src/main/include/cserver/toolLib/debugging.h deleted file mode 100644 index b47437651..000000000 --- a/src/core/src/main/include/cserver/toolLib/debugging.h +++ /dev/null @@ -1,142 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/debugging.h,v $ - * $RCSfile: debugging.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - - -/* - * debugging.h - Header file to use in aid of debugging - * - * Allows debugging printout to be controlled from environment - * with minimal overhead to program. - * - * - * Basic usage: - * - * - * #define DEBUG_ME "DEBUG_ME" - * #include "debugging.h" - * - * - * DebugVariable(x, "X", 0x01); - * DebugVariable(y, "Y", 0x02); - * ... - * - * if(Debug(x)) - * { - * ... - * some debugging code here - * ... - * - * } - * - * - * In the environment, if "DEBUG_ME" is set properly, - * it will cause the debug code to run. - * Otherwise, it will not. Different source files can - * use different environment variables. - * - * E.g. - * setenv DEBUG_ME "X Y" - * would cause Debug(x) and Debug(y) both to evaluate to true. - * setenv DEBUG_ME "X" - * would cause only Debug(x) to evaluate to true. - * - * - * The overhead consists of a getenv() and some test code for - * the first occurrence of a Debug(x) test and then if - * the environment contains the variable, a single test - * otherwise two tests per subsequent occurrence. The key is that - * the getenv() section does not run more than once per variable. - * - * - * For extra speed, bracket the if(Debug(x)) blocks with - * #ifdef DEBUG_ME - * ... - * #endif - * - * ------------------------------------------------------------------------ */ - - -#ifndef _debugging -#define _debugging - -#include - -#include "compat.h" -#include "stringutil.h" - -BEGIN_extern_C - -#if defined(SABER) || defined(__CENTERLINE__) -/*SUPPRESS 592*//*Saber Empty body for 'if' statement */ -#endif - - -#ifdef DEBUG_ME - -static unsigned int ___init = 0; -static unsigned int ___debug = 0; - -#if defined(__GNUC__) || defined(__STDC__) || defined(__cplusplus) -#define DebugVariable(x, s, bits) \ -static unsigned int __##x = bits; \ -static char *x##__str = s - -#define Debug(x) \ -( \ - (___debug & __##x) \ - || \ - ( \ - !(___init & __##x) \ - && \ - ( (FindWord(x##__str, getenv(DEBUG_ME)) == (char *) 0) ? \ - (___init |= __##x)?0:1 : (___init |= __##x, ___debug |= __##x)) \ - ) \ - ) -#else - -#define DebugVariable(x, s, bits) \ -static unsigned int __/**/x = bits; \ -static char *x/**/__str = s - -#define Debug(x) \ -( \ - (___debug & __/**/x) \ - || \ - ( \ - !(___init & __/**/x) \ - && \ - ( (FindWord(x/**/__str, getenv(DEBUG_ME)) == (char *) 0) ? \ - (___init |= __/**/x)?0:1 : (___init |= __/**/x, ___debug |= __/**/x)) \ - ) \ - ) -#endif - -#else - -#define Debug(x) 0 - -#endif /* ifdef DEBUG_ME */ - -END_extern_C - -#endif /* ifndef _debugging */ diff --git a/src/core/src/main/include/cserver/toolLib/error_hand.h b/src/core/src/main/include/cserver/toolLib/error_hand.h deleted file mode 100644 index 519685595..000000000 --- a/src/core/src/main/include/cserver/toolLib/error_hand.h +++ /dev/null @@ -1,109 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/error_hand.h,v $ - * $RCSfile: error_hand.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef error_hand_include -#define error_hand_include - -#include "compat.h" - -/* Include errno.h if EPERM (errno of 1) is not defined yet. */ -#ifndef EPERM -#include -#endif - - -extern char msgBuf[]; - -#define SaveLevelBits 0x00FF -#define SaveModeBits 0xFF00 - -#define SaveInfoMessages 0x01 -#define SaveDebugMessages 0x02 -#define SaveWarningMessages 0x04 -#define SaveFatalMessages 0x08 -#define SaveStatusMessages 0x10 - -#define SyncAfterWritingError 0x8000 -#define NoStderrOutput 0x4000 - -#define DefaultMessageLevel (SaveWarningMessages \ - | SaveStatusMessages \ - | SaveFatalMessages) - -#define DefaultStatusStringLength 10 - -#define EH_Error(l, s) HandleErrorMessage(l, s, __FILE__, __LINE__, 0) -#define EH_PError(l, s) HandleErrorMessage(l, s, __FILE__, __LINE__, errno) - -#define INFO_MESSAGE(s) EH_Error(SaveInfoMessages, s) -#define DEBUG_MESSAGE(s) EH_Error(SaveDebugMessages, s) -#define WARNING_MESSAGE(s) EH_Error(SaveWarningMessages, s) -#define FATAL_MESSAGE(s) EH_Error(SaveFatalMessages, s) -#define STATUS_MESSAGE(s) EH_Error(SaveStatusMessages, s) - -#define INFO_PERROR(s) EH_PError(SaveInfoMessages, s) -#define DEBUG_PERROR(s) EH_PError(SaveDebugMessages, s) -#define WARNING_PERROR(s) EH_PError(SaveWarningMessages, s) -#define FATAL_PERROR(s) EH_PError(SaveFatalMessages, s) - -BEGIN_extern_C - -extern int CustomizeErrorHandler( -#if NeedFunctionPrototypes - const char *, /* string */ - const int *, /* integerPointer */ - const char *, /* fileName */ - int /* saveLevel */ -#endif -); - -extern void HandleErrorMessage( -#if NeedFunctionPrototypes - int, /* level */ - const char *, /* string */ - const char *, /* file */ - int, /* line */ - int /* error */ -#endif -); - -#define BadMagic(func) \ - { \ - sprintf(msgBuf, "Corrupted data structure in %s()", func); \ - WARNING_MESSAGE(msgBuf); \ - } - - -#define customize_error_handler CustomizeErrorHandler -#define handle_error_message HandleErrorMessage - -#define NoMemory(func, size) \ - { \ - sprintf(msgBuf, "Not enough memory in %s(), needed %d bytes", \ - func, size); \ - WARNING_PERROR(msgBuf); \ - } - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/free_mgr.h b/src/core/src/main/include/cserver/toolLib/free_mgr.h deleted file mode 100644 index 4ffc2f66b..000000000 --- a/src/core/src/main/include/cserver/toolLib/free_mgr.h +++ /dev/null @@ -1,226 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/free_mgr.h,v $ - * $RCSfile: free_mgr.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* - * General Purpose free list management functions. This module - * takes care of pre-allocating a block of memory and then handing - * it out in the size chunks specified. This allows more efficient use - * of malloc and prevents memory fragmentation. The drawback is that - * the memory involved is never freed again. When items are handed - * back to the free list, they are made available to be used again. - * - * - * Functions consist of - * - * FreeList *ManageFreeList(offsetToNext, reallocSize, itemSize, name) - * unsigned long offsetToNext; - * int reallocSize; - * int itemSize; - * char *name; - * - * Tells the free list manager to manage a pool of memory to be - * parcelled out in 'itemSize' chunks. The pool will contain - * 'reallocSize' elements and when the pool runs out, that many - * more elements will be allocated. The 'offsetToNext' argument - * is used if you have linked lists of structures and want to return - * a list rather than single elements using ReturnListToFreeList() - * - * - * char *GetFromFreeList(freeList) - * FreeList *freeList; - * - * Returns a pointer to a properly sized element. The element is not - * zeroed before you get it. - * - * - * int ReturnToFreeList(listElement, freeList) - * char *listElement; - * FreeList *freeList; - * - * Hand a single element back to the free list pool. - * - * - * int ReturnListToFreeList(list, freeList) - * char *list; - * FreeList *freeList; - * - * Hand a list of elements back to the free list pool. This only - * works if you specified a valid 'offsetToNext' in the - * ManageFreeList() call. The last pointer must be NULL! - * - * Macros consist of - * - * OffsetInStruct(cast, element) - * cast is any 'typedef' or structure tag - * element is a member of the structure. - * - * ------------------------------------------------------------------------ */ - -#ifndef free_mgr_include -#define free_mgr_include - -#include "compat.h" - -BEGIN_extern_C - -#ifndef OffsetInStruct -#define OffsetInStruct(cast, element) \ - ((unsigned long)(&(((cast *)(0))->element))) -#endif - -#define CorruptedFreeList(listp) ((listp)->magic1 != freeListMagicNumber1 \ - ||(listp)->magic2 != freeListMagicNumber2) - -typedef struct freeListStruct -{ - char *magic1; - char *name; - char *list; - unsigned long offsetToNext; - int reallocSize; - int itemSize; - int freeItems; - int inUseItems; - struct freeListStruct *next; - char *magic2; -} FreeList; -#define NoFreeList ((FreeList *) 0) - -extern FreeList *DebugManageFreeList( -#if NeedFunctionPrototypes - unsigned long, /* offsetToNext */ - int, /* reallocSize */ - int, /* itemSize */ - const char *, /* name */ - const char *, /* file */ - int /* line */ -#endif -); - -extern FreeList *ManageFreeList( -#if NeedFunctionPrototypes - unsigned long, /* offsetToNext */ - int, /* reallocSize */ - int, /* itemSize */ - const char * /* name */ -#endif -); - -extern char *DebugGetFromFreeList( -#if NeedFunctionPrototypes - FreeList *, /* freeList */ - const char *, /* file */ - int /* line */ -#endif -); - -extern char *GetFromFreeList( -#if NeedFunctionPrototypes - FreeList * /* freeList */ -#endif -); - -extern int DebugReturnListToFreeList( -#if NeedFunctionPrototypes - char *, /* list */ - FreeList *, /* freeList */ - const char *, /* file */ - int /* line */ -#endif -); - -extern int ReturnListToFreeList( -#if NeedFunctionPrototypes - char *, /* list */ - FreeList * /* freeList */ -#endif -); - -extern int DebugReturnToFreeList( -#if NeedFunctionPrototypes - char *, /* listElement */ - FreeList *, /* freeList */ - const char *, /* file */ - int /* line */ -#endif -); - -extern int ReturnToFreeList( -#if NeedFunctionPrototypes - char *, /* listElement */ - FreeList * /* freeList */ -#endif -); - -extern int CheckIfAlreadyFree( -#if NeedFunctionPrototypes - char *element, - FreeList *freeList -#endif -); - - -/* - * - * Always name free lists by prepending the type name to _FreeList - * for these macros to work. E.g. - * - * FreeList *Foo_FreeList; for free lists with Foo type elements. - */ - - -#ifndef FreeListPrivate -#ifdef DebugFreeListPrintout -#define NewListPool(type, n, next) \ - DebugManageFreeList(OffsetInStruct(type, next), (n), sizeof(type), \ - "type", __FILE__, __LINE__); -#define NewPool(type, n) \ - DebugManageFreeList(0L, (n), sizeof(type), "type", __FILE__, __LINE__); -#define New(type) \ - (type *) DebugGetFromFreeList(STRCAT(type,_FreeList), __FILE__, __LINE__); -#define Delete(elt, type) \ - DebugReturnToFreeList((char *) elt, STRCAT(type,_FreeList), \ - __FILE__, __LINE__); -#define DeleteList(elt, type) \ - DebugReturnListToFreeList((char *) elt, STRCAT(type,_FreeList), \ - __FILE__, __LINE__); -#else - -#define NewListPool(type, n, next) \ - ManageFreeList(OffsetInStruct(type, next), (n), sizeof(type), "type"); -#define NewPool(type, n) ManageFreeList(0L, (n), sizeof(type), "type"); - -#define New(type) \ - (type *) GetFromFreeList(STRCAT(type,_FreeList)) -#define Delete(elt, type) \ - ReturnToFreeList((char *) elt, STRCAT(type,_FreeList)) -#define DeleteList(elt, type) \ - ReturnListToFreeList((char *) elt, STRCAT(type,_FreeList)) - -#endif -#endif - -END_extern_C - -#endif - diff --git a/src/core/src/main/include/cserver/toolLib/listtools.h b/src/core/src/main/include/cserver/toolLib/listtools.h deleted file mode 100644 index 10ee27a97..000000000 --- a/src/core/src/main/include/cserver/toolLib/listtools.h +++ /dev/null @@ -1,147 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/listtools.h,v $ - * $RCSfile: listtools.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* - * Macros to manage a singly linked list. - * - * First off define a structure that contains a "next" pointer. It - * need not be called 'next'. The structure type is always the 1st - * argument of the macro. - * - * Then you can make any number of lists. You hand in the name as the - * second argument of each macro. - * - * These examples use the following structure and the single instance - * of it. - * - * typedef struct _foobar - * { - * int x; - * struct _foobar *nextPtr; - * } FooBar; - * - * FooBar myFooBar; - * - *====> To Declare a list: - * - * ListOf(FooBar, fooBarList, nextPtr); - * - * This will set up a list called fooBarList, which will - * keep track of its elements using the "nextPtr" element of - * the FooBar typedef. - * - * - *====> To add an element to the head of the list: - * - * AddToHead(FooBar, fooBarList, &myFooBar); - * - *====> To remove an element: - * - * RemoveFromList(FooBar, fooBarList, &myFooBar); - * - *====> To get the # of elements on the list (assuming no one else has - * mucked with it without using these macros: - * - * GetListCount(FooBar, fooBarList) - * - *====> To make sure the count is right, in case someone did muck with it: - * - * ConfirmListCount(FooBar, fooBarList) - * - * ------------------------------------------------------------------------ */ - -#ifndef list_include -#define list_include - -#include "compat.h" - -BEGIN_extern_C - -#ifndef OffsetInStruct -#define OffsetInStruct(cast, element) \ - ((unsigned long)(&(((cast *)(0))->element))) -#endif - -#define NextPtr(t, name, x) (*(t **)((unsigned long)(x) + STRCAT(name,Offset))) - -#define ListOf(t, name, next) \ - t *name = 0; \ - int STRCAT(count,name) = 0; \ - static unsigned long STRCAT(name,Offset) = OffsetInStruct(t, next) - -#define AddToHead(t, name, p) \ - NextPtr(t, name, p) = name; \ - name = p; \ - STRCAT(count,name)++ - -#define AddBefore(t, name, p, c) \ -{ \ - t **prev = &name; \ - while(*prev) \ - { \ - if(NextPtr(t, name, (*prev)) == c) \ - { \ - NextPtr(t, name, (p)) = NextPtr(t, name, ((*prev))); \ - *prev = p; \ - break; \ - } \ - } \ -} - -#define RemoveFromList(t, name, p) \ -{ \ - t *temp = name; \ - if(name == p) \ - { \ - name = NextPtr(t, name, p); \ - STRCAT(count,name)--; \ - } \ - else \ - { \ - while(temp) \ - { \ - if(NextPtr(t, name, temp) == p) \ - { \ - NextPtr(t, name, temp) = NextPtr(t, name, p); \ - STRCAT(count,name)--; \ - break; \ - } \ - } \ - } \ -} - -#define GetListCount(t, name) (STRCAT(count,name)) -#define ConfirmListCount(t, name) \ -{ \ - t *temp = name; \ - STRCAT(count,name) = 0; \ - while(temp) \ - { \ - STRCAT(count,name)++; \ - temp = NextPtr(t, name, temp); \ - } \ -} - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/mapped_files.h b/src/core/src/main/include/cserver/toolLib/mapped_files.h deleted file mode 100644 index 57cd41ff0..000000000 --- a/src/core/src/main/include/cserver/toolLib/mapped_files.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/mapped_files.h,v $ - * $RCSfile: mapped_files.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef mapped_files_include -#define mapped_files_include - -#include "compat.h" - -BEGIN_extern_C - -typedef struct fileEntry -{ - int size; - int currOffset; - int time; - char *address; - char filename[1024]; -} FileEntry; - -#define LRUEntries 25 - -#define NoIndexEntry ((IndexEntry *) 0) - - -extern Bool FileExists( -#if NeedFunctionPrototypes - char *name -#endif -); - -int SeekMappedFile( -#if NeedFunctionPrototypes - FileEntry*, long offset, int ptrname -#endif - ); - -extern char* OpenMappedFile( -#if NeedFunctionPrototypes - char *name -#endif - ); - -extern FileEntry* FEOpenMappedFile( -#if NeedFunctionPrototypes - char *name, int auto_closable -#endif -); - -void CloseMappedFile( -#if NeedFunctionPrototypes - FileEntry *name -#endif -); - -extern void FlushMappedFileTable( -#if NeedFunctionPrototypes -#endif -); - -extern int GetMappedFileSize( -#if NeedFunctionPrototypes - char *name -#endif -); - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/plumbing.h b/src/core/src/main/include/cserver/toolLib/plumbing.h deleted file mode 100644 index 7b7301ab8..000000000 --- a/src/core/src/main/include/cserver/toolLib/plumbing.h +++ /dev/null @@ -1,144 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/plumbing.h,v $ - * $RCSfile: plumbing.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef _plumbing_h -#define _plumbing_h - -#include "compat.h" - -BEGIN_extern_C - -typedef int (*FdCBProc)( -#if NeedFunctionPrototypes - int, /* fd */ - char * /* client_data */ -#endif -); /* pointer to a procedure */ -#define NoFdCBProc ((FdCBProc) 0) - -extern void StopLoopOnFds( -#if NeedFunctionPrototypes -#endif -); - -extern int LoopOnFds( -#if NeedFunctionPrototypes -#endif -); - -extern int PrintTrace( -#if NeedFunctionPrototypes - int, /* fd */ - char *, /* buf */ - int, /* nBytes */ - char /* direction */ -#endif -); - -extern int InitFds( -#if NeedFunctionPrototypes -#endif -); - -extern int InitTkFds( -#if NeedFunctionPrototypes -#endif -); - -extern void WeedOutBadFds( -#if NeedFunctionPrototypes -#endif -); - -extern int ConnectInputFd( -#if NeedFunctionPrototypes - int, /* fd */ - FdCBProc, /* callback */ - const char *, /* callbackName */ - char * /* clientData */ -#endif -); - -extern int ConnectOutputFd( -#if NeedFunctionPrototypes - int, /* fd */ - FdCBProc, /* callback */ - const char *, /* callbackName */ - char * /* clientData */ -#endif -); - -extern int SetTraceFd( -#if NeedFunctionPrototypes - int, /* fd */ - int, /* flag */ - int /* direction */ -#endif -); - -extern int GetTraceFd( -#if NeedFunctionPrototypes - int, /* fd */ - int /* direction */ -#endif -); - -extern void DisconnectInputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern void DisableInputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern void EnableInputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern void DisconnectOutputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern void DisableOutputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern void EnableOutputFd( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -END_extern_C - -#endif diff --git a/src/core/src/main/include/cserver/toolLib/sockets.h b/src/core/src/main/include/cserver/toolLib/sockets.h deleted file mode 100644 index c6e9d0987..000000000 --- a/src/core/src/main/include/cserver/toolLib/sockets.h +++ /dev/null @@ -1,228 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/sockets.h,v $ - * $RCSfile: sockets.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* - * sockets.c - general-purpose routines for opening and using sockets - * as server or client. - * - * Functions are: - * - * open_socket() Open a socket connection - * open_socket_port() Open a socket connection - * close_socket() Close a socket connection - * accept_socket() Accept a connection on a socket - * - * Usage: - * Servers call open_socket() as servers and then call accept_socket() - * to get connections from clients. - * - * Clients call open_socket() and use that socket id to talk to servers. - * - * Both servers and clients call close_socket() to terminate. - * - * ------------------------------------------------------------------------ */ - -#ifndef SOCKETS_INCLUDE -#define SOCKETS_INCLUDE - -#include -#include - -#include "compat.h" - -BEGIN_extern_C - -/* Mode variables for open_socket() */ -#define SERVER 1 -#define CLIENT 2 - -#define UnixSocketPath "/tmp" - -#ifndef __C2MAN__ - -extern int LookForServer( -#if NeedFunctionPrototypes - const char *, /* service */ - const char *, /* hostname */ - int, /* unixPort */ - int, /* inetPort */ - int * /* socketp */ -#endif -); - -extern int ConnectToServer( -#if NeedFunctionPrototypes - const char *serviceName, - const char *hostName, - int type, - int port, - int *socketp -#endif -); - -extern int SetupSockets( -#if NeedFunctionPrototypes - const char *, /* serviceName */ - int, /* tcpPort */ - int, /* unixPort */ - int *, /* tcpSocketp */ - int * /* unixSocketp */ -#endif -); - - -extern void set_hunt_mode( -#if NeedFunctionPrototypes - int /* flag */ -#endif -); - -extern int set_socket_domain( -#if NeedFunctionPrototypes - int /* new */ -#endif -); - -extern int open_socket( -#if NeedFunctionPrototypes - int *, /* sock */ - const char *, /* service_name */ - const char *, /* host_name */ - int /* mode */ -#endif -); - -extern int open_socket_port( -#if NeedFunctionPrototypes - int *, /* sock */ - int, /* port */ - const char *, /* host_name */ - int /* mode */ -#endif -); - -extern int open_unix_port( -#if NeedFunctionPrototypes - int *, /* sock */ - const char *, /* sockname */ - int /* mode */ -#endif -); - -extern int close_socket( -#if NeedFunctionPrototypes - int /* sock */ -#endif -); - -extern char *LastHostAccepted( -#if NeedFunctionPrototypes -#endif -); - -extern int accept_socket( -#if NeedFunctionPrototypes - int, /* sock */ - int * /* new_socket */ -#endif -); - -extern int socket_receive( -#if NeedFunctionPrototypes - int, /* fd */ - void *, /* buf */ - int /* nbytes */ -#endif -); - -extern int socket_nb_receive( -#if NeedFunctionPrototypes - int, /* fd */ - void *, /* buf */ - int, /* nbytes */ - int * /* bytes_received */ -#endif -); - -extern int socket_peek( -#if NeedFunctionPrototypes - int, /* fd */ - void *, /* buf */ - int /* nbytes */ -#endif -); - -extern int socket_test( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern int socket_count( -#if NeedFunctionPrototypes - int /* fd */ -#endif -); - -extern int socket_send( -#if NeedFunctionPrototypes - int, /* fd */ - void *, /* buf */ - int /* nbytes */ -#endif -); - -extern int socket_nb_send( -#if NeedFunctionPrototypes - int, /* fd */ - void *, /* buf */ - int /* nbytes */ -#endif -); - -extern int socket_control( -#if NeedFunctionPrototypes - int, /* fd */ - int, /* whichFlag */ - int /* what */ -#endif -); - -extern char *ConnectedInternetAddress( -#if NeedFunctionPrototypes - int fd -#endif -); - -extern char *ConnectedHostname( -#if NeedFunctionPrototypes - int fd -#endif -); - -#endif /* ifndef __C2MAN__ */ - -END_extern_C - -#endif - diff --git a/src/core/src/main/include/cserver/toolLib/stringutil.h b/src/core/src/main/include/cserver/toolLib/stringutil.h deleted file mode 100644 index e38836c80..000000000 --- a/src/core/src/main/include/cserver/toolLib/stringutil.h +++ /dev/null @@ -1,173 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/stringutil.h,v $ - * $RCSfile: stringutil.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -#ifndef stringutil_include -#define stringutil_include - -#include - -#include "compat.h" -BEGIN_extern_C - -typedef struct _stringList -{ - int index; - char *string; -} StringList; -#define NoStringList ((StringList *) 0) - -#define EmptyStringListEntry { 0, (char *) 0 } - -#define EndOfText ((char *) 0) - -#define RightJustify 1 -#define LeftJustify -1 - -#ifndef Min -#define Min(x,y) (((x)>(y))? (y) : (x)) -#endif - -#define LeftJustified RightJustify -#define RightJustified LeftJustify - -#define lookup_string LookupString -#define flookup_string FLookupString -#define print_text PrintText -#define next_nonblank NextNonblank -#define basename Basename -#define token_length TokenLength -#define get_token GetTokenFromString -#define lowercase Lowercase - -/* Note: the comma operator evaluates left to right, (K&R C, ANSI C, C++) */ -#define nstrncpy(to, from, l) (strncpy((to), (from), (l) - 1), \ - (to)[(l) - 1] = '\0', (to)) - -extern char *LookupString( -#if NeedFunctionPrototypes - int, /* index */ - StringList *, /* list */ - char * /* defaultString */ -#endif -); - -extern int LookupIndex( -#if NeedFunctionPrototypes - char *, /* string */ - StringList *, /* list */ - int /* notFound */ -#endif -); - -extern char *FLookupString( -#if NeedFunctionPrototypes - char *, /* resultString */ - int, /* index */ - StringList *, /* list */ - char *, /* string */ - int, /* width */ - int /* justification */ -#endif -); - -extern char *NextNonblank( -#if NeedFunctionPrototypes - char * /* s */ -#endif -); - -/* - * Do the equivalent of basename(1) - * - * Find the base name of the string (i.e. strip off the leading - * directory names in a pathname). - * - * RETURNS: - * pointer to the beginning of the base name. - */ - -extern const char *Basename( -#if NeedFunctionPrototypes - const char * /* s */ -#endif -); - -extern void PrintText( -#if NeedFunctionPrototypes - FILE *, /* stream */ - char ** /* text */ -#endif -); - -extern int TokenLength( -#if NeedFunctionPrototypes - char * /* token */ -#endif -); - -extern char *GetTokenFromString( -#if NeedFunctionPrototypes - char *, /* s */ - char, /* separator */ - int *, /* lengthp */ - char ** /* separatorp */ -#endif -); - -extern char *Lowercase( -#if NeedFunctionPrototypes - char * /* str */ -#endif -); - -extern char *FindWord( -#if NeedFunctionPrototypes - char *, /* word */ - char * /* string */ -#endif -); - -extern char *NormalizePath( -#if NeedFunctionPrototypes - char * /* path */ -#endif -); - -extern char *ExecDir( -#if NeedFunctionPrototypes - char *, /* path */ - char * /* argv0 */ -#endif -); - -char *SetEnvVar( -#if NeedFunctionPrototypes - char *, /* name */ - char * /* value */ -#endif -); - -END_extern_C - -#endif - diff --git a/src/core/src/main/include/cserver/toolLib/style.h b/src/core/src/main/include/cserver/toolLib/style.h deleted file mode 100644 index 9fbac6340..000000000 --- a/src/core/src/main/include/cserver/toolLib/style.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ********************************************************************** - * - * - * - * BBN Technologies, a Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-8000 - * - * Copyright (C) BBNT Solutions LLC. All rights reserved. - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/cserver/toolLib/include/style.h,v $ - * $RCSfile: style.h,v $ - * $Revision: 1.2 $ - * $Date: 2004/01/26 19:07:10 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -/* cosmetic C definitions, "complex" */ - -#ifndef STYLE_H -#define STYLE_H 1 - -#ifdef __CENTERLINE__ -#ifndef SABER -#define SABER 1 -#endif -#endif - -#define NormalReturn 0 -#define ErrorReturn -1 - -#ifndef NULL -#define NULL 0 -#endif - -#ifndef TRUE -#define TRUE 1 -#define FALSE 0 -#endif - -#ifndef True -#define True 1 -#define False 0 -#endif - -#define TrueString(i) ((i) IS True ? "T" : "F") -#define plural(i) ((i) IS 1 ? "" : "s") - -#define endof(a) ((a) + strlen (a)) - -#define bitset(w,b) ((w) |= (b)) -#define bitclear(w,b) ((w) &= ~(b)) - -#define STREQ(a,b) (strcmp ((a), (b)) IS 0) - -#define Max2(a,b) ((a) > (b) ? (a) : (b)) -#define Min2(a,b) ((a) < (b) ? (a) : (b)) - -struct complex - { - float real; - float imag; - }; - -typedef struct complex complex; - -#ifndef Bool -#define Bool int -#endif - -#endif diff --git a/src/core/src/main/java/Acme/IntHashtable.java b/src/core/src/main/java/Acme/IntHashtable.java deleted file mode 100644 index 92b969068..000000000 --- a/src/core/src/main/java/Acme/IntHashtable.java +++ /dev/null @@ -1,368 +0,0 @@ -// IntHashtable - a Hashtable that uses ints as the keys -// -// This is 90% based on JavaSoft's java.util.Hashtable. -// -// Visit the ACME Labs Java page for up-to-date versions of this and -// other -// fine Java utilities: http://www.acme.com/java/ - -package Acme; - -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.NoSuchElementException; - -/// A Hashtable that uses ints as the keys. -//

-// Use just like java.util.Hashtable, except that the keys must be -// ints. -// This is much faster than creating a new Integer for each access. -//

-// Fetch the -// software.
-// Fetch the entire Acme -// package. -//

-// @see java.util.Hashtable - -public class IntHashtable extends Dictionary implements Cloneable { - // / The hash table data. - private IntHashtableEntry table[]; - - // / The total number of entries in the hash table. - private int count; - - // / Rehashes the table when count exceeds this threshold. - private int threshold; - - // / The load factor for the hashtable. - private float loadFactor; - - // / Constructs a new, empty hashtable with the specified initial - // capacity and the specified load factor. - // @param initialCapacity the initial number of buckets - // @param loadFactor a number between 0.0 and 1.0, it defines - // the threshold for rehashing the hashtable into - // a bigger one. - // @exception IllegalArgumentException If the initial capacity - // is less than or equal to zero. - // @exception IllegalArgumentException If the load factor is - // less than or equal to zero. - public IntHashtable(int initialCapacity, float loadFactor) { - if (initialCapacity <= 0 || loadFactor <= 0.0) - throw new IllegalArgumentException(); - this.loadFactor = loadFactor; - table = new IntHashtableEntry[initialCapacity]; - threshold = (int) (initialCapacity * loadFactor); - } - - // / Constructs a new, empty hashtable with the specified initial - // capacity. - // @param initialCapacity the initial number of buckets - public IntHashtable(int initialCapacity) { - this(initialCapacity, 0.75f); - } - - // / Constructs a new, empty hashtable. A default capacity and - // load factor - // is used. Note that the hashtable will automatically grow when - // it gets - // full. - public IntHashtable() { - this(101, 0.75f); - } - - // / Returns the number of elements contained in the hashtable. - public int size() { - return count; - } - - // / Returns true if the hashtable contains no elements. - public boolean isEmpty() { - return count == 0; - } - - // / Returns an enumeration of the hashtable's keys. - // @see IntHashtable#elements - public synchronized Enumeration keys() { - return new IntHashtableEnumerator(table, true); - } - - // / Returns an enumeration of the elements. Use the Enumeration - // methods - // on the returned object to fetch the elements sequentially. - // @see IntHashtable#keys - public synchronized Enumeration elements() { - return new IntHashtableEnumerator(table, false); - } - - // / Returns true if the specified object is an element of the - // hashtable. - // This operation is more expensive than the containsKey() method. - // @param value the value that we are looking for - // @exception NullPointerException If the value being searched - // for is equal to null. - // @see IntHashtable#containsKey - public synchronized boolean contains(Object value) { - if (value == null) - throw new NullPointerException(); - IntHashtableEntry tab[] = table; - for (int i = tab.length; i-- > 0;) { - for (IntHashtableEntry e = tab[i]; e != null; e = e.next) { - if (e.value.equals(value)) - return true; - } - } - return false; - } - - // / Returns true if the collection contains an element for the - // key. - // @param key the key that we are looking for - // @see IntHashtable#contains - public synchronized boolean containsKey(int key) { - IntHashtableEntry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (IntHashtableEntry e = tab[index]; e != null; e = e.next) { - if (e.hash == hash && e.key == key) - return true; - } - return false; - } - - // / Gets the object associated with the specified key in the - // hashtable. - // @param key the specified key - // @returns the element for the key or null if the key - // is not defined in the hash table. - // @see IntHashtable#put - public synchronized Object get(int key) { - IntHashtableEntry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (IntHashtableEntry e = tab[index]; e != null; e = e.next) { - if (e.hash == hash && e.key == key) - return e.value; - } - return null; - } - - // / A get method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object get(Object okey) { - if (!(okey instanceof Integer)) - throw new InternalError("key is not an Integer"); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return get(key); - } - - // / Rehashes the content of the table into a bigger table. - // This method is called automatically when the hashtable's - // size exceeds the threshold. - protected void rehash() { - int oldCapacity = table.length; - IntHashtableEntry oldTable[] = table; - - int newCapacity = oldCapacity * 2 + 1; - IntHashtableEntry newTable[] = new IntHashtableEntry[newCapacity]; - - threshold = (int) (newCapacity * loadFactor); - table = newTable; - - for (int i = oldCapacity; i-- > 0;) { - for (IntHashtableEntry old = oldTable[i]; old != null;) { - IntHashtableEntry e = old; - old = old.next; - - int index = (e.hash & 0x7FFFFFFF) % newCapacity; - e.next = newTable[index]; - newTable[index] = e; - } - } - } - - // / Puts the specified element into the hashtable, using the - // specified - // key. The element may be retrieved by doing a get() with the - // same key. - // The key and the element cannot be null. - // @param key the specified key in the hashtable - // @param value the specified element - // @exception NullPointerException If the value of the element - // is equal to null. - // @see IntHashtable#get - // @return the old value of the key, or null if it did not have - // one. - public synchronized Object put(int key, Object value) { - // Make sure the value is not null. - if (value == null) - throw new NullPointerException(); - - // Makes sure the key is not already in the hashtable. - IntHashtableEntry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (IntHashtableEntry e = tab[index]; e != null; e = e.next) { - if (e.hash == hash && e.key == key) { - Object old = e.value; - e.value = value; - return old; - } - } - - if (count >= threshold) { - // Rehash the table if the threshold is exceeded. - rehash(); - return put(key, value); - } - - // Creates the new entry. - IntHashtableEntry e = new IntHashtableEntry(); - e.hash = hash; - e.key = key; - e.value = value; - e.next = tab[index]; - tab[index] = e; - ++count; - return null; - } - - // / A put method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object put(Object okey, Object value) { - if (!(okey instanceof Integer)) - throw new InternalError("key is not an Integer"); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return put(key, value); - } - - // / Removes the element corresponding to the key. Does nothing if - // the - // key is not present. - // @param key the key that needs to be removed - // @return the value of key, or null if the key was not found. - public synchronized Object remove(int key) { - IntHashtableEntry tab[] = table; - int hash = key; - int index = (hash & 0x7FFFFFFF) % tab.length; - for (IntHashtableEntry e = tab[index], prev = null; e != null; prev = e, e = e.next) { - if (e.hash == hash && e.key == key) { - if (prev != null) - prev.next = e.next; - else - tab[index] = e.next; - --count; - return e.value; - } - } - return null; - } - - // / A remove method that takes an Object, for compatibility with - // java.util.Dictionary. The Object must be an Integer. - public Object remove(Object okey) { - if (!(okey instanceof Integer)) - throw new InternalError("key is not an Integer"); - Integer ikey = (Integer) okey; - int key = ikey.intValue(); - return remove(key); - } - - // / Clears the hash table so that it has no more elements in it. - public synchronized void clear() { - IntHashtableEntry tab[] = table; - for (int index = tab.length; --index >= 0;) - tab[index] = null; - count = 0; - } - - // / Creates a clone of the hashtable. A shallow copy is made, - // the keys and elements themselves are NOT cloned. This is a - // relatively expensive operation. - public synchronized Object clone() { - try { - IntHashtable t = (IntHashtable) super.clone(); - t.table = new IntHashtableEntry[table.length]; - for (int i = table.length; i-- > 0;) - t.table[i] = (table[i] != null) ? (IntHashtableEntry) table[i].clone() : null; - return t; - } catch (CloneNotSupportedException e) { - // This shouldn't happen, since we are Cloneable. - throw new InternalError(); - } - } - - // / Converts to a rather lengthy String. - public synchronized String toString() { - int max = size() - 1; - StringBuffer buf = new StringBuffer(); - Enumeration k = keys(); - Enumeration e = elements(); - buf.append("{"); - - for (int i = 0; i <= max; ++i) { - String s1 = k.nextElement().toString(); - String s2 = e.nextElement().toString(); - buf.append(s1).append("=").append(s2); - if (i < max) - buf.append(", "); - } - buf.append("}"); - return buf.toString(); - } -} - -class IntHashtableEntry { - int hash; - int key; - Object value; - IntHashtableEntry next; - - protected Object clone() { - IntHashtableEntry entry = new IntHashtableEntry(); - entry.hash = hash; - entry.key = key; - entry.value = value; - entry.next = (next != null) ? (IntHashtableEntry) next.clone() : null; - return entry; - } -} - -class IntHashtableEnumerator implements Enumeration { - boolean keys; - int index; - IntHashtableEntry table[]; - IntHashtableEntry entry; - - IntHashtableEnumerator(IntHashtableEntry table[], boolean keys) { - this.table = table; - this.keys = keys; - this.index = table.length; - } - - public boolean hasMoreElements() { - if (entry != null) - return true; - while (index-- > 0) - if ((entry = table[index]) != null) - return true; - return false; - } - - public Object nextElement() { - if (entry == null) - while ((index-- > 0) && ((entry = table[index]) == null)) { - // NO-OP, just skip over empties - } - - if (entry != null) { - IntHashtableEntry e = entry; - entry = e.next; - return keys ? new Integer(e.key) : e.value; - } - throw new NoSuchElementException("IntHashtableEnumerator"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/Acme/JPM/Encoders/GifEncoder.java b/src/core/src/main/java/Acme/JPM/Encoders/GifEncoder.java deleted file mode 100644 index 70e1834e6..000000000 --- a/src/core/src/main/java/Acme/JPM/Encoders/GifEncoder.java +++ /dev/null @@ -1,725 +0,0 @@ -/** - * GifEncoder - write out an image as a GIF - * - * Transparency handling and variable bit size courtesy of Jack Palevich. - * - * Copyright (C)1996,1998 by Jef Poskanzer . All rights reserved. - * Modified by Don Dietrick (dietrick@bbn.com) to use Adam Doppelt's - * Quantize class for color reduction, if needed. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * Visit the ACME Labs Java page for up-to-date versions of this and other - * fine Java utilities: http://www.acme.com/java/ - */ -package Acme.JPM.Encoders; - -import java.awt.Image; -import java.awt.image.ImageProducer; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Enumeration; - -/** - * Write out an image as a GIF. - *

- * Fetch - * the software.
- * Fetch the entire Acme - * package. - *

- */ -public class GifEncoder extends ImageEncoder { - - private boolean interlace = false; - - /** - * Constructor from Image. - * - * @param img The image to encode. - * @param out The stream to write the GIF to. - */ - public GifEncoder(Image img, OutputStream out) throws IOException { - super(img, out); - } - - /** - * Constructor from Image with interlace setting. - * - * @param img The image to encode. - * @param out The stream to write the GIF to. - * @param interlace Whether to interlace. - */ - public GifEncoder(Image img, OutputStream out, boolean interlace) - throws IOException { - - super(img, out); - this.interlace = interlace; - } - - /** - * Constructor from ImageProducer. - * - * @param prod The ImageProducer to encode. - * @param out The stream to write the GIF to. - */ - public GifEncoder(ImageProducer prod, OutputStream out) throws IOException { - - super(prod, out); - } - - /** - * Constructor from ImageProducer with interlace setting. - * - * @param prod The ImageProducer to encode. - * @param out The stream to write the GIF to. - */ - public GifEncoder(ImageProducer prod, OutputStream out, boolean interlace) - throws IOException { - - super(prod, out); - this.interlace = interlace; - } - - int width, height; - int[][] rgbPixels; - - void encodeStart(int width, int height) throws IOException { - - this.width = width; - this.height = height; - rgbPixels = new int[height][width]; - } - - void encodePixels(int x, int y, int w, int h, int[] rgbPixels, int off, - int scansize) - - throws IOException { - - // Save the pixels. - for (int row = 0; row < h; ++row) { - System.arraycopy(rgbPixels, row * scansize + off, this.rgbPixels[y - + row], x, w); - } - } - - Acme.IntHashtable colorHash; - - /** - * Original encodeDone method. Calls new encodeDone method with a - * quanitized palette. - */ - void encodeDone() throws IOException { - encodeDone(null); - } - - /** - * Modified encodeDone that takes a palette of reduced colors. If - * the palette exists, it expects that the internal rgbPixels[][] - * contains indexes into the palette. If the palette is null, then - * it assumes that the rgbPixels[][] contains colors. If more than - * 255 colors are needed (which should only happen when the - * palette is null), this method gets called again internally - * after the rgbPixels are quantized. - */ - void encodeDone(int[] palette) throws IOException { - - int transparentIndex = -1; - int transparentRgb = -1; - // Put all the pixels into a hash table. - colorHash = new Acme.IntHashtable(); - int index = 0; - - for (int row = 0; row < height; ++row) { -// int rowOffset = row * width; - for (int col = 0; col < width; ++col) { - int rgb; - if (palette != null) { - rgb = palette[rgbPixels[row][col]]; - } else { - rgb = rgbPixels[row][col]; - } - boolean isTransparent = ((rgb >>> 24) < 0x80); - if (isTransparent) { - if (transparentIndex < 0) { - // First transparent color; remember it. - transparentIndex = index; - transparentRgb = rgb; - } else if (rgb != transparentRgb) { - // A second transparent color; replace it with - // the first one. - rgbPixels[row][col] = rgb = transparentRgb; - } - } - - GifEncoderHashitem item = (GifEncoderHashitem) colorHash.get(rgb); - - if (item == null) { - if (index >= 256) { - // Added to quantify the image, to make sure - // there aren't more than 255 colors. Uses - // Adam Doppelt's Quantize class. DFDietrick - // (OpenMap) - // com.bbn.openmap.util.Debug.message("saveimage", - // "Need to quantize image"); - encodeDone(doppelt.Quantize.quantizeImage(rgbPixels, - 255)); - return; - // throw new IOException("too many colors for - // a GIF"); - } - - item = new GifEncoderHashitem(rgb, 1, index, isTransparent); - ++index; - colorHash.put(rgb, item); - } else { - ++item.count; - } - - // Doesn't matter if there isn't a palette created - // from quanitize - rgbPixels[row][col] = rgb; - } - } - - // Figure out how many bits to use. - int logColors; - if (index <= 2) - logColors = 1; - else if (index <= 4) - logColors = 2; - else if (index <= 16) - logColors = 4; - else - logColors = 8; - - // Turn colors into colormap entries. - int mapSize = 1 << logColors; - byte[] reds = new byte[mapSize]; - byte[] grns = new byte[mapSize]; - byte[] blus = new byte[mapSize]; - for (Enumeration e = colorHash.elements(); e.hasMoreElements();) { - GifEncoderHashitem item = (GifEncoderHashitem) e.nextElement(); - reds[item.index] = (byte) ((item.rgb >> 16) & 0xff); - grns[item.index] = (byte) ((item.rgb >> 8) & 0xff); - blus[item.index] = (byte) (item.rgb & 0xff); - } - - GIFEncode(out, - width, - height, - interlace, - (byte) 0, - transparentIndex, - logColors, - reds, - grns, - blus); - } - - byte GetPixel(int x, int y) throws IOException { - GifEncoderHashitem item = (GifEncoderHashitem) colorHash.get(rgbPixels[y][x]); - - if (item == null) - throw new IOException("color not found"); - - return (byte) item.index; - } - - static void writeString(OutputStream out, String str) throws IOException { - - byte[] buf = str.getBytes(); - out.write(buf); - } - - // Adapted from ppmtogif, which is based on GIFENCOD by David - // Rowley . Lempel-Zim compression - // based on "compress". - - int Width, Height; - boolean Interlace; - int curx, cury; - int CountDown; - int Pass = 0; - - void GIFEncode(OutputStream outs, int Width, int Height, boolean Interlace, - byte Background, int Transparent, int BitsPerPixel, - byte[] Red, byte[] Green, byte[] Blue) - - throws IOException { - - byte B; - int LeftOfs, TopOfs; - int ColorMapSize; - int InitCodeSize; - int i; - - this.Width = Width; - this.Height = Height; - this.Interlace = Interlace; - ColorMapSize = 1 << BitsPerPixel; - LeftOfs = TopOfs = 0; - - // Calculate number of bits we are expecting - CountDown = Width * Height; - - // Indicate which pass we are on (if interlace) - Pass = 0; - - // The initial code size - if (BitsPerPixel <= 1) { - InitCodeSize = 2; - } else { - InitCodeSize = BitsPerPixel; - } - - // Set up the current x and y position - curx = 0; - cury = 0; - - // Write the Magic header - writeString(outs, "GIF89a"); - - // Write out the screen width and height - Putword(Width, outs); - Putword(Height, outs); - - // Indicate that there is a global colour map - B = (byte) 0x80; // Yes, there is a color map - // OR in the resolution - B |= (byte) ((8 - 1) << 4); - // Not sorted - // OR in the Bits per Pixel - B |= (byte) ((BitsPerPixel - 1)); - - // Write it out - Putbyte(B, outs); - - // Write out the Background colour - Putbyte(Background, outs); - - // Pixel aspect ratio - 1:1. - //Putbyte((byte) 49, outs); - // Java's GIF reader currently has a bug, if the aspect ratio - // byte is - // not zero it throws an ImageFormatException. It doesn't know - // that - // 49 means a 1:1 aspect ratio. Well, whatever, zero works - // with all - // the other decoders I've tried so it probably doesn't hurt. - Putbyte((byte) 0, outs); - - // Write out the Global Colour Map - for (i = 0; i < ColorMapSize; ++i) { - Putbyte(Red[i], outs); - Putbyte(Green[i], outs); - Putbyte(Blue[i], outs); - } - - // Write out extension for transparent colour index, if - // necessary. - if (Transparent != -1) { - Putbyte((byte) '!', outs); - Putbyte((byte) 0xf9, outs); - Putbyte((byte) 4, outs); - Putbyte((byte) 1, outs); - Putbyte((byte) 0, outs); - Putbyte((byte) 0, outs); - Putbyte((byte) Transparent, outs); - Putbyte((byte) 0, outs); - } - - // Write an Image separator - Putbyte((byte) ',', outs); - - // Write the Image header - Putword(LeftOfs, outs); - Putword(TopOfs, outs); - Putword(Width, outs); - Putword(Height, outs); - - // Write out whether or not the image is interlaced - if (Interlace) - Putbyte((byte) 0x40, outs); - else - Putbyte((byte) 0x00, outs); - - // Write out the initial code size - Putbyte((byte) InitCodeSize, outs); - - // Go and actually compress the data - compress(InitCodeSize + 1, outs); - - // Write out a Zero-length packet (to end the series) - Putbyte((byte) 0, outs); - - // Write the GIF file terminator - Putbyte((byte) ';', outs); - } - - // Bump the 'curx' and 'cury' to point to the next pixel - void BumpPixel() { - // Bump the current X position - ++curx; - - // If we are at the end of a scan line, set curx back to the - // beginning - // If we are interlaced, bump the cury to the appropriate - // spot, - // otherwise, just increment it. - if (curx == Width) { - curx = 0; - - if (!Interlace) { - ++cury; - - } else { - switch (Pass) { - case 0: - cury += 8; - if (cury >= Height) { - ++Pass; - cury = 4; - } - break; - - case 1: - cury += 8; - if (cury >= Height) { - ++Pass; - cury = 2; - } - break; - - case 2: - cury += 4; - if (cury >= Height) { - ++Pass; - cury = 1; - } - break; - - case 3: - cury += 2; - break; - } - } - } - } - - static final int EOF = -1; - - // Return the next pixel from the image - int GIFNextPixel() throws IOException { - byte r; - - if (CountDown == 0) { - return EOF; - } - - --CountDown; - - r = GetPixel(curx, cury); - - BumpPixel(); - - return r & 0xff; - } - - // Write out a word to the GIF file - void Putword(int w, OutputStream outs) throws IOException { - Putbyte((byte) (w & 0xff), outs); - Putbyte((byte) ((w >> 8) & 0xff), outs); - } - - // Write out a byte to the GIF file - void Putbyte(byte b, OutputStream outs) throws IOException { - outs.write(b); - } - - // GIFCOMPR.C - GIF Image compression routines - // - // Lempel-Ziv compression based on 'compress'. GIF modifications - // by - // David Rowley (mgardi@watdcsu.waterloo.edu) - - // General DEFINEs - - static final int BITS = 12; - static final int HSIZE = 5003; // 80% occupancy - - // GIF Image compression - modified 'compress' - // - // Based on: compress.c - File compression ala IEEE Computer, June - // 1984. - // - // By Authors: Spencer W. Thomas - // (decvax!harpo!utah-cs!utah-gr!thomas) - // Jim McKie (decvax!mcvax!jim) - // Steve Davies (decvax!vax135!petsd!peora!srd) - // Ken Turkowski (decvax!decwrl!turtlevax!ken) - // James A. Woods (decvax!ihnp4!ames!jaw) - // Joe Orost (decvax!vax135!petsd!joe) - - int n_bits; // number of bits/code - int maxbits = BITS; // user settable max # bits/code - int maxcode; // maximum code, given n_bits - int maxmaxcode = 1 << BITS; // should NEVER generate this code - - final int MAXCODE(int n_bits) { - return (1 << n_bits) - 1; - } - - int[] htab = new int[HSIZE]; - int[] codetab = new int[HSIZE]; - - int hsize = HSIZE; // for dynamic table sizing - - int free_ent = 0; // first unused entry - - // block compression parameters -- after all codes are used up, - // and compression rate changes, start over. - boolean clear_flg = false; - - // Algorithm: use open addressing double hashing (no chaining) on - // the prefix code / next character combination. We do a variant - // of Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's - // relatively-prime secondary probe. Here, the modular division - // first probe is gives way to a faster exclusive-or manipulation. - // Also do block compression with an adaptive reset, whereby the - // code table is cleared when the compression ratio decreases, but - // after the table fills. The variable-length output codes are - // re-sized at this point, and a special CLEAR code is generated - // for the decompressor. Late addition: construct the table - // according to file size for noticeable speed improvement on - // small files. Please direct questions about this implementation - // to ames!jaw. - - int g_init_bits; - - int ClearCode; - int EOFCode; - - void compress(int init_bits, OutputStream outs) throws IOException { - int fcode; - int i /* = 0 */; - int c; - int ent; - int disp; - int hsize_reg; - int hshift; - - // Set up the globals: g_init_bits - initial number of bits - g_init_bits = init_bits; - - // Set up the necessary values - clear_flg = false; - n_bits = g_init_bits; - maxcode = MAXCODE(n_bits); - - ClearCode = 1 << (init_bits - 1); - EOFCode = ClearCode + 1; - free_ent = ClearCode + 2; - - char_init(); - - ent = GIFNextPixel(); - - hshift = 0; - for (fcode = hsize; fcode < 65536; fcode *= 2) - ++hshift; - hshift = 8 - hshift; // set hash code range bound - - hsize_reg = hsize; - cl_hash(hsize_reg); // clear hash table - - output(ClearCode, outs); - - outer_loop: while ((c = GIFNextPixel()) != EOF) { - fcode = (c << maxbits) + ent; - i = (c << hshift) ^ ent; // xor hashing - - if (htab[i] == fcode) { - ent = codetab[i]; - continue; - } else if (htab[i] >= 0) { // non-empty slot - - disp = hsize_reg - i; // secondary hash (after G. - // Knott) - if (i == 0) - disp = 1; - do { - if ((i -= disp) < 0) - i += hsize_reg; - - if (htab[i] == fcode) { - ent = codetab[i]; - continue outer_loop; - } - } while (htab[i] >= 0); - } - output(ent, outs); - ent = c; - if (free_ent < maxmaxcode) { - codetab[i] = free_ent++; // code -> hashtable - htab[i] = fcode; - } else { - cl_block(outs); - } - } - // Put out the final code. - output(ent, outs); - output(EOFCode, outs); - } - - // output - // - // Output the given code. - // Inputs: - // code: A n_bits-bit integer. If == -1, then EOF. This assumes - // that n_bits =< wordsize - 1. - // Outputs: - // Outputs code to the file. - // Assumptions: - // Chars are 8 bits long. - // Algorithm: - // Maintain a BITS character long buffer (so that 8 codes will - // fit in it exactly). Use the VAX insv instruction to insert each - // code in turn. When the buffer fills up empty it and start over. - - int cur_accum = 0; - int cur_bits = 0; - - int masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, - 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, - 0x7FFF, 0xFFFF }; - - void output(int code, OutputStream outs) throws IOException { - cur_accum &= masks[cur_bits]; - - if (cur_bits > 0) - cur_accum |= (code << cur_bits); - else - cur_accum = code; - - cur_bits += n_bits; - - while (cur_bits >= 8) { - char_out((byte) (cur_accum & 0xff), outs); - cur_accum >>= 8; - cur_bits -= 8; - } - - // If the next entry is going to be too big for the code size, - // then increase it, if possible. - if (free_ent > maxcode || clear_flg) { - if (clear_flg) { - maxcode = MAXCODE(n_bits = g_init_bits); - clear_flg = false; - } else { - ++n_bits; - if (n_bits == maxbits) - maxcode = maxmaxcode; - else - maxcode = MAXCODE(n_bits); - } - } - - if (code == EOFCode) { - // At EOF, write the rest of the buffer. - while (cur_bits > 0) { - char_out((byte) (cur_accum & 0xff), outs); - cur_accum >>= 8; - cur_bits -= 8; - } - - flush_char(outs); - } - } - - // Clear out the hash table - - // table clear for block compress - void cl_block(OutputStream outs) throws IOException { - cl_hash(hsize); - free_ent = ClearCode + 2; - clear_flg = true; - - output(ClearCode, outs); - } - - // reset code table - void cl_hash(int hsize) { - for (int i = 0; i < hsize; ++i) - htab[i] = -1; - } - - // GIF Specific routines - - // Number of characters so far in this 'packet' - int a_count; - - // Set up the 'byte output' routine - void char_init() { - a_count = 0; - } - - // Define the storage for the packet accumulator - byte[] accum = new byte[256]; - - // Add a character to the end of the current packet, and if it is - // 254 - // characters, flush the packet to disk. - void char_out(byte c, OutputStream outs) throws IOException { - accum[a_count++] = c; - if (a_count >= 254) - flush_char(outs); - } - - // Flush the packet to disk, and reset the accumulator - void flush_char(OutputStream outs) throws IOException { - if (a_count > 0) { - outs.write(a_count); - outs.write(accum, 0, a_count); - a_count = 0; - } - } - -} - -class GifEncoderHashitem { - - public int rgb; - public int count; - public int index; - public boolean isTransparent; - - public GifEncoderHashitem(int rgb, int count, int index, - boolean isTransparent) { - this.rgb = rgb; - this.count = count; - this.index = index; - this.isTransparent = isTransparent; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/Acme/JPM/Encoders/ImageEncoder.java b/src/core/src/main/java/Acme/JPM/Encoders/ImageEncoder.java deleted file mode 100644 index 7c8a4feda..000000000 --- a/src/core/src/main/java/Acme/JPM/Encoders/ImageEncoder.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * ImageEncoder - abstract class for writing out an image - * - * Copyright (C) 1996 by Jef Poskanzer . All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * Visit the ACME Labs Java page for up-to-date versions of this and other - * fine Java utilities: http://www.acme.com/java/ - */ - -package Acme.JPM.Encoders; - -import java.awt.Image; -import java.awt.image.ColorModel; -import java.awt.image.ImageConsumer; -import java.awt.image.ImageProducer; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Hashtable; - -/** - * Abstract class for writing out an image. - *

- * A framework for classes that encode and write out an image in a - * particular file format. - *

- * This provides a simplified rendition of the ImageConsumer - * interface. It always delivers the pixels as ints in the RGBdefault - * color model. It always provides them in top-down left-right order. - * If you want more flexibility you can always implement ImageConsumer - * directly. - *

- * Fetch - * the software.
- * Fetch the entire Acme - * package. - *

- * - * @see GifEncoder - * @see PpmEncoder - */ -public abstract class ImageEncoder implements ImageConsumer { - - protected OutputStream out; - - private ImageProducer producer; - private int width = -1; - private int height = -1; - private int hintflags = 0; - private boolean started = false; - private boolean encoding; - private IOException iox; - private static final ColorModel rgbModel = ColorModel.getRGBdefault(); - private Hashtable props = null; - - /// Constructor. - // @param img The image to encode. - // @param out The stream to write the bytes to. - public ImageEncoder(Image img, OutputStream out) throws IOException { - this(img.getSource(), out); - } - - /// Constructor. - // @param producer The ImageProducer to encode. - // @param out The stream to write the bytes to. - public ImageEncoder(ImageProducer producer, OutputStream out) - throws IOException { - this.producer = producer; - this.out = out; - } - - // Methods that subclasses implement. - - /// Subclasses implement this to initialize an encoding. - abstract void encodeStart(int w, int h) throws IOException; - - /// Subclasses implement this to actually write out some bits. - // They - // are guaranteed to be delivered in top-down-left-right order. - // One int per pixel, index is row * scansize + off + col, - // RGBdefault (AARRGGBB) color model. - abstract void encodePixels(int x, int y, int w, int h, int[] rgbPixels, - int off, int scansize) throws IOException; - - /// Subclasses implement this to finish an encoding. - abstract void encodeDone() throws IOException; - - // Our own methods. - - /// Call this after initialization to get things going. - public synchronized void encode() throws IOException { - encoding = true; - iox = null; - producer.startProduction(this); - while (encoding) - try { - wait(); - } catch (InterruptedException e) { - } - if (iox != null) - throw iox; - } - - private boolean accumulate = false; - private int[] accumulator; - - private void encodePixelsWrapper(int x, int y, int w, int h, - int[] rgbPixels, int off, int scansize) - throws IOException { - if (!started) { - started = true; - encodeStart(width, height); - if ((hintflags & TOPDOWNLEFTRIGHT) == 0) { - accumulate = true; - accumulator = new int[width * height]; - } - } - if (accumulate) - for (int row = 0; row < h; ++row) - System.arraycopy(rgbPixels, - row * scansize + off, - accumulator, - (y + row) * width + x, - w); - else - encodePixels(x, y, w, h, rgbPixels, off, scansize); - } - - private void encodeFinish() throws IOException { - if (accumulate) { - encodePixels(0, 0, width, height, accumulator, 0, width); - accumulator = null; - accumulate = false; - } - } - - private synchronized void stop() { - encoding = false; - notifyAll(); - } - - // Methods from ImageConsumer. - - public void setDimensions(int width, int height) { - this.width = width; - this.height = height; - } - - public void setProperties(Hashtable props) { - this.props = props; - } - - public Hashtable getProperties() { - return this.props; - } - - public void setColorModel(ColorModel model) { - // Ignore. - } - - public void setHints(int hintflags) { - this.hintflags = hintflags; - } - - public void setPixels(int x, int y, int w, int h, ColorModel model, - byte[] pixels, int off, int scansize) { - int[] rgbPixels = new int[w]; - for (int row = 0; row < h; ++row) { - int rowOff = off + row * scansize; - for (int col = 0; col < w; ++col) - rgbPixels[col] = model.getRGB(pixels[rowOff + col] & 0xff); - try { - encodePixelsWrapper(x, y + row, w, 1, rgbPixels, 0, w); - } catch (IOException e) { - iox = e; - stop(); - return; - } - } - } - - public void setPixels(int x, int y, int w, int h, ColorModel model, - int[] pixels, int off, int scansize) { - if (model == rgbModel) { - try { - encodePixelsWrapper(x, y, w, h, pixels, off, scansize); - } catch (IOException e) { - iox = e; - stop(); - return; - } - } else { - int[] rgbPixels = new int[w]; - for (int row = 0; row < h; ++row) { - int rowOff = off + row * scansize; - for (int col = 0; col < w; ++col) - rgbPixels[col] = model.getRGB(pixels[rowOff + col]); - try { - encodePixelsWrapper(x, y + row, w, 1, rgbPixels, 0, w); - } catch (IOException e) { - iox = e; - stop(); - return; - } - } - } - } - - public void imageComplete(int status) { - producer.removeConsumer(this); - if (status == ImageConsumer.IMAGEABORTED) - iox = new IOException("image aborted"); - else { - try { - encodeFinish(); - encodeDone(); - } catch (IOException e) { - iox = e; - } - } - stop(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/Acme/JPM/Encoders/PpmEncoder.java b/src/core/src/main/java/Acme/JPM/Encoders/PpmEncoder.java deleted file mode 100644 index 95a633c62..000000000 --- a/src/core/src/main/java/Acme/JPM/Encoders/PpmEncoder.java +++ /dev/null @@ -1,100 +0,0 @@ -// PpmEncoder - write out an image as a PPM -// -// Copyright (C)1996,1998 by Jef Poskanzer . All rights -// reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above -// copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the -// distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// SUCH DAMAGE. -// -// Visit the ACME Labs Java page for up-to-date versions of this and -// other -// fine Java utilities: http://www.acme.com/java/ - -package Acme.JPM.Encoders; - -import java.awt.Image; -import java.awt.image.ImageProducer; -import java.io.IOException; -import java.io.OutputStream; - -/// Write out an image as a PPM. -//

-// Writes an image onto a specified OutputStream in the PPM file -// format. -//

-// Fetch -// the software.
-// Fetch the entire Acme -// package. -//

-// @see ToPpm - -public class PpmEncoder extends ImageEncoder { - - /// Constructor. - // @param img The image to encode. - // @param out The stream to write the PPM to. - public PpmEncoder(Image img, OutputStream out) throws IOException { - super(img, out); - } - - /// Constructor. - // @param prod The ImageProducer to encode. - // @param out The stream to write the PPM to. - public PpmEncoder(ImageProducer prod, OutputStream out) throws IOException { - super(prod, out); - } - - void encodeStart(int width, int height) throws IOException { - writeString(out, "P6\n"); - writeString(out, width + " " + height + "\n"); - writeString(out, "255\n"); - } - - static void writeString(OutputStream out, String str) throws IOException { - byte[] buf = str.getBytes(); - out.write(buf); - } - - void encodePixels(int x, int y, int w, int h, int[] rgbPixels, int off, - int scansize) throws IOException { - byte[] ppmPixels = new byte[w * 3]; - for (int row = 0; row < h; ++row) { - int rowOff = off + row * scansize; - for (int col = 0; col < w; ++col) { - int i = rowOff + col; - int j = col * 3; - ppmPixels[j] = (byte) ((rgbPixels[i] & 0xff0000) >> 16); - ppmPixels[j + 1] = (byte) ((rgbPixels[i] & 0x00ff00) >> 8); - ppmPixels[j + 2] = (byte) (rgbPixels[i] & 0x0000ff); - } - out.write(ppmPixels); - } - } - - void encodeDone() throws IOException { - // Nothing. - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/BufferedLayerMapBean.java b/src/core/src/main/java/com/bbn/openmap/BufferedLayerMapBean.java deleted file mode 100644 index 9e91849cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/BufferedLayerMapBean.java +++ /dev/null @@ -1,312 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/BufferedLayerMapBean.java,v $ -// $RCSfile: BufferedLayerMapBean.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Component; -import java.awt.event.ContainerEvent; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.layer.BufferedLayer; - -/** - * The BufferedLayerMapBean is a BufferedMapBean with an additional image buffer - * that holds Layers designated as background layers. The additional image - * buffer is a BufferedLayer that this MapBean manages, and all background - * layers are added to the BufferedLayer, which is automatically added to the - * bottom of the map. When layers are added to the MapBean via the setLayers() - * method, the Layer.getAddAsBackground() flag is checked, and if that is true - * for a layer, it is added to the BufferedLayer. The background layers do not - * receive mouse events. - *

- * - * It should be cautioned that the appearance of the map may not match the layer - * stack as it is delivered to the MapBean because of this flag. If, for - * example, layers 1 and 4 are marked as background layers, while layers 2 and 3 - * are not (in a 4 layer stack), then the map will show layers 2, 3, 1, 4, with - * layers 1 and 4 being displayed from the BufferedLayer. Something to think - * about when it comes to designing GUI elements. - */ -public class BufferedLayerMapBean extends BufferedMapBean { - - private static final long serialVersionUID = 1L; - private static Logger logger = Logger.getLogger(BufferedLayerMapBean.class.getName()); - protected BufferedLayer bufferedLayer; - - protected boolean DEBUG = false; - - /** - * Construct a MapBean. - */ - public BufferedLayerMapBean() { - super(); - DEBUG = logger.isLoggable(Level.FINE); - } - - public BufferedLayerMapBean(boolean useThreadedNotification) { - super(useThreadedNotification); - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Set the background color of the map. Actually sets the background color - * of the projection, and calls repaint(). - */ - /* - * public void setBackgroundColor(Color color) { super.setBackground(color); - * getBufferedLayer().setBackground(color); } public void setBckgrnd(Paint - * paint) { super.setBckgrnd(paint); getBufferedLayer().setBckgrnd(paint); } - */ - public synchronized void setBufferedLayer(BufferedLayer bl) { - bufferedLayer = bl; - } - - public synchronized BufferedLayer getBufferedLayer() { - if (bufferedLayer == null) { - bufferedLayer = new BufferedLayer(); - addPropertyChangeListener(bufferedLayer); - bufferedLayer.setName("Background Layers"); - } - - return bufferedLayer; - } - - /** - * Set the MapBeanRepaintPolicy used by the MapBean. This method is - * overridden in order to pass the policy on to the MapBean stored in the - * internal BufferedLayer. - */ - public void setMapBeanRepaintPolicy(MapBeanRepaintPolicy mbrp) { - super.setMapBeanRepaintPolicy(mbrp); - - MapBean mb = getBufferedLayer().getMapBean(); - if (mb != null) { - if (mbrp == null) { - mb.setMapBeanRepaintPolicy(mbrp); - } else { - MapBeanRepaintPolicy mbrp2 = (MapBeanRepaintPolicy) mbrp.clone(); - mb.setMapBeanRepaintPolicy(mbrp2); - mbrp2.setMap(mb); - } - } - } - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. - * - * @param evt a LayerEvent - */ - public void setLayers(LayerEvent evt) { - setBufferDirty(true); - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - // Don't care about these at all... - return; - } - - // @HACK is this cool?: - if (layers == null) { - logger.warning("layer[] is null!"); - return; - } - - boolean oldChange = getDoContainerChange(); - setDoContainerChange(false); - - BufferedLayer bufLayer; - - synchronized (this) { - bufLayer = getBufferedLayer(); - } - - // use LayerEvent.REPLACE when you want to remove all current - // layers add a new set - if (type == LayerEvent.REPLACE) { - if (DEBUG) { - debugmsg("Replacing all layers"); - } - - removeAll(); - bufLayer.clearLayers(); - bufLayer.setProjection(getRotatedProjection()); - - for (Layer layer : layers) { - // @HACK is this cool?: - if (layer == null) { - logger.warning("skipping null layer in layer array passed to MapBean"); - continue; - } - - if (DEBUG) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - - if (layer.getAddAsBackground()) { - if (DEBUG) { - logger.fine("Adding layer[" + layer.getName() + "] to background"); - } - - bufLayer.addLayer(layer); - } else { - add(layer); - } - - layer.setVisible(true); - } - - if (bufLayer.hasLayers()) { - add(bufLayer); - } - } - - // use LayerEvent.ADD when adding and/or reshuffling layers - else if (type == LayerEvent.ADD) { - - remove(bufLayer); - - if (DEBUG) { - debugmsg("Adding new layers"); - } - for (Layer layer : layers) { - if (DEBUG) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - - layer.setVisible(true); - - if (layer.getAddAsBackground()) { - if (DEBUG) { - debugmsg("Adding layer[" + layer.getName() + "] to background"); - } - bufLayer.addLayer(layer); - } else { - add(layer); - } - } - - if (bufLayer.hasLayers()) { - add(bufLayer); - } - } - - // use LayerEvent.REMOVE when you want to delete layers from - // the map - else if (type == LayerEvent.REMOVE) { - if (DEBUG) { - debugmsg("Removing layers"); - } - for (Layer layer : layers) { - if (DEBUG) { - debugmsg("Removing layer[" + layer.getName() + "]"); - } - remove(layer); - bufLayer.removeLayer(layer); - } - } - - if (!layerRemovalDelayed) { - purgeAndNotifyRemovedLayers(); - } - - setDoContainerChange(oldChange); - revalidate(); - repaint(); - } - - /** - * In an effort to limit map flashing, the BufferedLayerMapBean consults the - * BufferedLayer to check that all background layers are ready to be painted - * after a projection change, before forwarding on all repaint requests. - */ - public void repaint(Layer layer) { - if (bufferedLayer == null || bufferedLayer.isReadyToPaint()) { - super.repaint(layer); - } - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param e ContainerEvent - */ - protected void changeLayers(ContainerEvent e) { - // Container Changes can be disabled to speed adding/removing - // multiple layers - if (!doContainerChange) { - return; - } - - Component[] comps = this.getComponents(); - int ncomponents = comps.length; - int nBufLayerComponents = 0; - - BufferedLayer bufLayer; - synchronized (this) { - bufLayer = getBufferedLayer(); - } - - if (ncomponents == 0 || comps[ncomponents - 1] != bufLayer) { - super.changeLayers(e); - return; - } - - Component[] bufLayers = bufLayer.getLayers(); - nBufLayerComponents = bufLayers.length; - - // Take 1 off for the bufLayer - Layer[] newLayers = new Layer[ncomponents + nBufLayerComponents - 1]; - System.arraycopy(comps, 0, newLayers, 0, ncomponents - 1); - System.arraycopy(bufLayers, 0, newLayers, ncomponents - 1, nBufLayerComponents); - - if (DEBUG) { - debugmsg("changeLayers() - firing change"); - } - - firePropertyChange(LayersProperty, currentLayers, newLayers); - - // Tell the new layers that they have been added - for (Layer layer : addedLayers) { - layer.added(this); - } - addedLayers.removeAllElements(); - - currentLayers = newLayers; - } - - /** - * Call when getting rid of the MapBean, it releases pointers to all - * listeners and kills the ProjectionSupport thread. - */ - public void dispose() { - if (bufferedLayer != null) { - bufferedLayer.dispose(); - } - super.dispose(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/BufferedMapBean.java b/src/core/src/main/java/com/bbn/openmap/BufferedMapBean.java deleted file mode 100644 index 25d86b308..000000000 --- a/src/core/src/main/java/com/bbn/openmap/BufferedMapBean.java +++ /dev/null @@ -1,315 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/BufferedMapBean.java,v $ -// $RCSfile: BufferedMapBean.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.AlphaComposite; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.event.ComponentEvent; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.Projection; - -/** - * The BufferedMapBean extends the MapBean by adding (you guessed it) buffering. - *

- * Specifically, the layers are stored in a java.awt.Image so that the frequent - * painting done by Swing on lightweight components will not cause the layers to - * do unnecessary work re-rendering themselves each time. - *

- * Changing the default clipping area may cause some Layers to not be drawn - * completely, depending on what the clipping area is set to and when the layer - * is trying to get itself painted. When manually adjusting clipping area, make - * sure that when restricted clipping is over that a full repaint occurs if - * there is a chance that another layer may be trying to paint itself. - */ -public class BufferedMapBean extends MapBean { - - private static final long serialVersionUID = 1L; - private static Logger logger = Logger.getLogger(BufferedMapBean.class - .getName()); - protected boolean bufferDirty = true; - protected BufferedImage drawingBuffer = null; - - protected PanHelper panningTransform = null; - - public BufferedMapBean() { - super(); - } - - public BufferedMapBean(boolean useThreadedNotification) { - super(useThreadedNotification); - } - - /** - * Invoked when component has been resized. Layer buffer is nullified. and - * super.componentResized(e) is called. - * - * @param e - * ComponentEvent - */ - public void componentResized(ComponentEvent e) { - setBufferDirty(true); - - super.componentResized(e); - } - - /** - * Provide a drawing buffer for the layers based on the projection - * parameters. If the currentImageBuffer is the right size, the pixels will - * be cleared. - * - * @param currentImageBuffer - * the buffer to reuse and return, if the size is appropriate. - * Flushed if another BufferedImage is returned. - * @param proj - * the current projection of the map - * @return BufferedImage to be used for image buffer. - */ - protected BufferedImage resetDrawingBuffer( - BufferedImage currentImageBuffer, Projection proj) { - try { - - int w = proj.getWidth(); - int h = proj.getHeight(); - - if (currentImageBuffer != null) { - int cibWidth = currentImageBuffer.getWidth(); - int cibHeight = currentImageBuffer.getHeight(); - - if (cibWidth == w && cibHeight == h) { - Graphics2D graphics = (Graphics2D) currentImageBuffer - .getGraphics(); - graphics.setComposite(AlphaComposite.Clear); - graphics.fillRect(0, 0, w, h); - graphics.setComposite(AlphaComposite.SrcOver); - return currentImageBuffer; - } else { - currentImageBuffer.flush(); - } - } - - return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - - } catch (java.lang.NegativeArraySizeException nae) { - } catch (java.lang.IllegalArgumentException iae) { - } - - return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); - } - - /** - * Same as paintChildren, but allows you to set a clipping area to paint. Be - * careful with this, because if the clipping area is set while some layer - * decides to paint itself, that layer may not have all it's objects - * painted. Same warnings apply. - */ - public void paintChildren(Graphics g, Rectangle clip) { - - // if a layer has requested a render, then we render all of - // them into a drawing buffer - BufferedImage localDrawingBuffer = drawingBuffer; - - if (panningTransform == null && bufferDirty) { - bufferDirty = false; - - localDrawingBuffer = resetDrawingBuffer(localDrawingBuffer, - getProjection()); - // In case it's been resized - drawingBuffer = localDrawingBuffer; - - // draw the old image - Graphics gr = getMapBeanRepaintPolicy().modifyGraphicsForPainting( - localDrawingBuffer.getGraphics()); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("BufferedMapBean rendering layers to buffer."); - } - - super.paintLayers(gr); - gr.dispose(); - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("BufferedMapBean rendering buffer."); - } - - if (panningTransform != null) { - - panningTransform.render((Graphics2D) g); - return; - - } else if (localDrawingBuffer != null) { - BufferedMapBean.super.drawProjectionBackground(g); - - RotationHelper rotHelper = getRotHelper(); - - if (rotHelper != null) { - rotHelper.paintChildren(g, clip); - rotHelper.paintPainters(g); - } else { - g.drawImage(localDrawingBuffer, 0, 0, null); - // Let the ProjectionPainters do their thing... - painters.paint(g); - } - } - } - - /** - * We don't want to be drawing the background here. We want to draw - * background separately, and then draw layers on top. Buffer without the - * background, helps with textured and gradient backgrounds. - */ - protected void drawProjectionBackground(Graphics g) { - /* if (g instanceof Graphics2D) { - projection.drawBackground((Graphics2D) g, OMColor.ALMOST_CLEAR); - } else { - g.setColor(OMColor.ALMOST_CLEAR); - projection.drawBackground(g); - }*/ - } - - /** - * Interface-like method to query if the MapBean is buffered, so you can - * control behavior better. Allows the removal of specific instance-like - * queries for, say, BufferedMapBean, when all you really want to know is if - * you have the data is buffered, and if so, should be buffer be cleared. - * For the BufferedMapBean, always true. - */ - public boolean isBuffered() { - return true; - } - - /** - * Marks the image buffer as dirty if value is true. On the next - * paintChildren(), we will call paint() on all - * Layer components. - * - * @param value - * boolean - */ - public void setBufferDirty(boolean value) { - bufferDirty = value; - } - - /** - * Checks whether the image buffer should be repainted. - * - * @return boolean whether the layer buffer is dirty - */ - public boolean isBufferDirty() { - return bufferDirty; - } - - /** - * Clear out resources for the current drawing buffer. - */ - protected void disposeDrawingBuffer() { - Image localDrawingBuffer = drawingBuffer; - drawingBuffer = null; - if (localDrawingBuffer != null) { - localDrawingBuffer.flush(); - } - } - - public void dispose() { - disposeDrawingBuffer(); - super.dispose(); - } - - public AffineTransform getPanningTransform() { - return panningTransform; - } - - /** - * Set a panning transform on the buffer for rendering in a different place, - * quickly. Sets the buffer to be dirty, so when the panning transform is - * removed, it will be recreated. - * - * @param transform - */ - public void setPanningTransform(AffineTransform transform) { - if (transform != null) { - if (panningTransform == null) { - panningTransform = new PanHelper(transform); - setBufferDirty(true); - } else { - panningTransform.update(transform); - } - } else { - if (panningTransform != null) { - panningTransform.dispose(); - } - panningTransform = null; - } - } - - protected class PanHelper extends AffineTransform { - /** - * - */ - private static final long serialVersionUID = 1L; - protected Image buffer; - - protected PanHelper(AffineTransform aft) { - super(aft); - - BufferedImage localHandleOnBuffer = drawingBuffer; - if (!bufferDirty && localHandleOnBuffer != null) { - this.buffer = localHandleOnBuffer; - } else { - this.buffer = new BufferedImage(getWidth(), getHeight(), - BufferedImage.TYPE_INT_ARGB); - paintLayers(this.buffer.getGraphics()); - } - } - - protected void update(AffineTransform aft) { - super.setTransform(aft); - } - - protected void render(Graphics2D g) { - BufferedMapBean.super.drawProjectionBackground(g); - ((Graphics2D) g).setTransform(this); - if (buffer != null) { - g.drawImage(buffer, 0, 0, null); - } - - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper == null) { - painters.paint(g); - } - } - - protected void dispose() { - if (buffer != null) { - buffer.flush(); - buffer = null; - } - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/Environment.java b/src/core/src/main/java/com/bbn/openmap/Environment.java deleted file mode 100644 index 8f2b63a2f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/Environment.java +++ /dev/null @@ -1,809 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/Environment.java,v $ -// $RCSfile: Environment.java,v $ -// $Revision: 1.9 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.applet.Applet; -import java.awt.Color; -import java.io.File; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; - -import javax.swing.JApplet; -import javax.swing.JLayeredPane; -import javax.swing.JRootPane; - -import com.bbn.openmap.util.BasicI18n; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * An Environment is a set of property lists that together specify the runtime - * environment for this process. - *

- * There is only one Environment, and it is accessed through static member - * functions. - *

- * The environment is comprised of at least three property lists: - *

    - *
  • System properties form the basis of the environment. For applications, - * This can be the System.getProperties(), or something else. In the case of - * applets, this is a list of the ten system properties that applets are allowed - * to access plus any applet parameters. - *

    - *

  • Runtime properties are checked next. These are properties that exist only - * while the process is running. They are calculated during Environment - * initialization and are not persistent. - *

    - *

  • Hardcoded properties form the last level. These properties are hardcoded - * default values that are specified in the code of this file. They are meant to - * be used as a last resort. - *

    - *

- * When Environment.get() is called, all lists are searched until - * the property is found. System properties are searched first, then runtime - * properties, and then hardcoded properties. - *

- * This search pattern allows system properties and properties specified as - * applet parameters or command line properties (using -DProperty=value Java - * flag) to override more hardcoded properties specified elsewhere, say in a - * user preferences file. - * - * @see java.util.Properties - * - *

- * 
- * 
- * 
- *    # metanames of the names of the variables used in the OpenMap
- *    # system to configure the Environment class from the properties.
- *    openmap.Title - String for title of application window.
- *    openmap.Version - Version number of application.
- *    openmap.BuildDate - Build data of code base.
- *    openmap.WebBrowser - The launch command to launch a browser.
- *    openmap.TempDirectory - A path to a directory to use for temporary files.
- *    openmap.UseInternalFrames - For an application, to direct it to use InternalFrames for other windows.
- *    openmap.Latitude - Starting latitude for map projection.
- *    openmap.Longitude - Starting longitude for map projection.
- *    openmap.Scale - Starting scale for map projection.
- *    openmap.Projection - Starting projection type for map projection.
- *    openmap.Width - Pixel width for map.
- *    openmap.Height - Pixel height for map.
- *    openmap.HelpURL - The URL to use for OpenMap/Application help pages.
- *    openmap.BackgroundColor - An ARGB integer to use for the background (sea) color.
- *    openmap.Debug - Debug tokens to activate for printout.  @see com.bbn.openmap.util.Debug
- *   
- *    openmap.UniqueID String for unique identification of OpenMap instance (calculated)
- * 
- * 
- * 
- *      
- */ -public class Environment extends Properties { - - /*-------------------------------------------------- - * To Do: - * - * Save user properties - * - * User properties editor - * - *--------------------------------------------------*/ - - private static final long serialVersionUID = 1L; - protected static Environment env; - protected Properties hardcodedProps; - protected Properties runtimeProps; - protected JLayeredPane desktop = null; - protected Applet applet; - List extraPaths = new ArrayList<>(); - - private static int counter = 0; - - // user preferences file (used for later references) - public static transient final String OpenMapPrefix = "openmap"; - public static transient final String PreferencesURL = OpenMapPrefix + ".PreferencesURL"; - // metanames of the names of the variables used in the OpenMap - // system - public static transient final String Title = OpenMapPrefix + ".Title"; - public static transient final String Version = OpenMapPrefix + ".Version"; - public static transient final String BuildDate = OpenMapPrefix + ".BuildDate"; - public static transient final String UniqueID = OpenMapPrefix + ".UniqueID"; - public static transient final String WebBrowser = OpenMapPrefix + ".WebBrowser"; - public static transient final String TmpDir = OpenMapPrefix + ".TempDirectory"; - public static transient final String UseInternalFrames = OpenMapPrefix + ".UseInternalFrames"; - public static transient final String Latitude = OpenMapPrefix + ".Latitude"; - public static transient final String Longitude = OpenMapPrefix + ".Longitude"; - public static transient final String Scale = OpenMapPrefix + ".Scale"; - public static transient final String Projection = OpenMapPrefix + ".Projection"; - public static transient final String Width = OpenMapPrefix + ".Width"; - public static transient final String Height = OpenMapPrefix + ".Height"; - public static transient final String HelpURL = OpenMapPrefix + ".HelpURL"; - public static transient final String BackgroundColor = OpenMapPrefix + ".BackgroundColor"; - public static transient final String DebugList = OpenMapPrefix + ".Debug"; - // default to false - private transient boolean isXWindows = false; - // Will do it if isXWindows - public transient boolean doingXWindowsWorkaround = false; - public final transient String title = "$$Title=" + MapBean.title; - public final transient String version = "$$Version=" + MapBean.version; - // autobuild should set this. - public final transient String build = "$$BuildDate="; - - public final transient String ThreadPool = OpenMapPrefix + ".ThreadPool"; - - static { - env = new Environment(); - } - - /** - * Hardcoded default properties. - *

- * These should be edited before each new version/installation of OpenMap. They - * are declared in such a way that they can be easily edited from a build - * script. - * - * @param p Properties - */ - protected final void initHardCodedProperties(Properties p) { - - StringTokenizer tokenizer; - tokenizer = new StringTokenizer(title, "="); - tokenizer.nextToken(); - p.put(Title, tokenizer.nextToken()); - - tokenizer = new StringTokenizer(version, "="); - tokenizer.nextToken(); - p.put(Version, tokenizer.nextToken()); - - tokenizer = new StringTokenizer(build, "="); - tokenizer.nextToken(); - try { - p.put(BuildDate, tokenizer.nextToken()); - } catch (NoSuchElementException e) { - } // no BuildDate - } - - /** - * Initializes the environment of an applet. - * - * @param applet An applet - * @see java.applet.Applet - */ - public static void init(Applet applt) { - // overwrite properties - Debug.output("Reinitializing Applet Environment!"); - init(System.getProperties()); - setApplet(applt); - - if (Debug.debugging("env")) { - env.list(System.out); - } - } - - /** - * Initializes, or re-initializes the environment of an application. - * - * @param sysProps Runtime/System Properties (Top-level) - */ - public static void init(Properties sysProps) { - if (env != null) { - // Debug.output("Reinitializing Environment!"); - // overwrite properties - env.installProps(sysProps); - } else { - new Environment(sysProps); - if (Debug.debugging("env")) { - env.list(System.out); - } - } - } - - /** - * Initializes the OpenMap environment. Installs the default System Properties - * into the Environment. - */ - public static void init() { - init(System.getProperties()); - } - - protected Environment() { - - } - - /** - * Creates an Environment based on applet properties. - * - * @param applet an Applet - */ - protected Environment(Applet applet) { - env = this; - setApplet(applet); - commonInit(); - } - - /** - * Creates an Environment with the specified system properties. - * - * @param sysProps system properties - */ - protected Environment(Properties sysProps) { - env = this; - installProps(sysProps); - commonInit(); - } - - /** - * install Properties directly into the top-level Environment list. - * - * @param sysProps system properties - * - */ - private void installProps(Properties sysProps) { - // Copy the specified property list - for (String key : sysProps.stringPropertyNames()) { - try { - this.put(key, sysProps.getProperty(key)); - } catch (NullPointerException ex) { - // Key or Value must have been null. C'est la vie. - } - } - } - - /** - * Adds runtime, user, and base properties to the Environment. - */ - protected void commonInit() { - hardcodedProps = new Properties(); - runtimeProps = new Properties(hardcodedProps); - - // the Environment defaults are the properties lists just - // constructed - defaults = runtimeProps; - - initHardCodedProperties(hardcodedProps); - initRuntimeProperties(runtimeProps); - } - - /** - * Populates the system properties for an applet. Currently this property list - * contains the ten system properties available to applets and any applet - * parameters specified in Applet.getParameterInfo(). - * - * @param applet the applet - * @see java.applet.Applet#getParameterInfo - */ - protected void setAppletProperties(Applet applet) { - /* - * These are the ten properties available to applets. - */ - final String[] appletProps = { "java.version", "java.vendor", "java.vendor.url", "java.class.version", - "os.name", "os.arch", "os.version", "file.separator", "path.separator", "line.separator" }; - - int i; - - for (i = 0; i < appletProps.length; i++) { - String prop = appletProps[i]; - put(prop, System.getProperty(prop)); - } - - String[][] pinfo = applet.getParameterInfo(); - if (pinfo == null) - return; - for (i = 0; i < pinfo.length; i++) { - try { - String key = pinfo[i][0]; - String value = applet.getParameter(key); - Debug.message("env", "Applet Parameter " + key + " has value " + value); - put(key, value); - } catch (NullPointerException e) { - } - } - } - - /** - * Initializes the runtime properties list. Runtime properties are those - * properties that exist only while the program is running. They are not - * persistent. Persistent properties should be stored in the user properties - * list. - * - * @param p The runtime properties list - */ - protected void initRuntimeProperties(Properties p) { - if (isApplet()) { - p.put("user.name", "appletUser");// for convenience - } - - java.net.InetAddress addr = null; - try { - addr = java.net.InetAddress.getLocalHost(); - } catch (NullPointerException npe) { - // Linux threw a npe when unconnected. - Debug.output("Environment.init: Can't get hostname from InetAddress!"); - } catch (java.net.UnknownHostException e) { - Debug.output("Environment.init: I don't know my hostname!"); - } catch (IndexOutOfBoundsException ioobe) { - // Caught something weird here a couple of times when - // running unconnected. - Debug.output("Environment.init: network may not be available"); - } - - // the UniqueID is generated from other runtime values. This - // should - // be unique for this Java VM. Note that for security reasons, - // you - // might not want to ship around this value on a network - // because it - // details some interesting tidbits about the running - // application. - p.put(UniqueID, - "_" + get("user.name") + "_" + get(Version) + "_" + get("os.arch") + "_" - + get("os.name") + "_" + ((addr != null) ? addr.getHostName() : "nohost") + "_" - + timestamp() + "_"); - - // determine window system (for HACKing around - // Java-under-XWindows - // polygon wraparound bug. - String osname = get("os.name"); - - if (osname == null) { - isXWindows = false; - doingXWindowsWorkaround = false; - Debug.message("env", "Environment: is applet, Web Start."); - return; - } - - if (osname.equalsIgnoreCase("solaris") || osname.equalsIgnoreCase("SunOS")) { - isXWindows = true; - doingXWindowsWorkaround = true; - Debug.message("env", "Environment: is X Windows!"); - } else if (osname.equalsIgnoreCase("linux")) { - isXWindows = true; - doingXWindowsWorkaround = true; - Debug.message("env", "Environment: is X Windows!"); - } else if (osname.startsWith("Windows")) { - isXWindows = false; - doingXWindowsWorkaround = false; - isXWindows = true; - doingXWindowsWorkaround = true; - Debug.message("env", "Environment: is MS Windows!"); - } else if (osname.equalsIgnoreCase("Mac OS")) { - isXWindows = false; - doingXWindowsWorkaround = false; - Debug.message("env", "Environment: is Mac OS!"); - } else if (osname.equalsIgnoreCase("Mac OS X")) { - isXWindows = true; - doingXWindowsWorkaround = true; - // isXWindows = false; - // doingXWindowsWorkaround = false; - com.bbn.openmap.omGraphics.DrawingAttributes.alwaysSetTextToBlack = true; - Debug.message("env", "Environment: Excellent! Mac OS X!"); - } else { - System.err.println("Environment.initRuntimeProperties(): " + "running on unknown/untested OS: " + osname); - } - - // should have initialized user properties already - if (get(OpenMapPrefix + ".noXWindowsWorkaround") != null) { - Debug.message("env", "Environment.initRuntimeProperties(): " + "not working around XWindows clipping bug."); - doingXWindowsWorkaround = false; - } - } - - /** - * Indicates whether the current process is an applet. - * - * @return true if process is an applet; false - * otherwise. - */ - public static boolean isApplet() { - return (env.applet != null); - } - - protected static void setApplet(Applet applet) { - env.applet = applet; - if (applet instanceof JApplet) { - useInternalFrames(((JApplet) applet).getRootPane()); - } - env.setAppletProperties(applet); - } - - /** - * Indicates whether the current process is an application. - * - * @return true if process is an application; false - * otherwise. - */ - public static boolean isApplication() { - return (env.applet == null); - } - - /** - * Store a value in the Environment. - * - * @param propertyKey - * @param value - */ - public static void set(String propertyKey, Object value) { - env.put(propertyKey, value); - } - - /** - * Searches for the named property in the environment. If the key is not found, - * null is returned. All three property lists, runtime, user, and system are - * searched in that order. - * - * @param key the property key - * @return the value of the property with the specified key or null - * if there is no property with that key. - */ - public static String get(String key) { - return env.getProperty(key, null); - } - - /** - * Searches for a named property in the environment. - * - * @param key the key for the property - * @param dflt the default value returned if the key is not found - * @return the value for the key or the default. - */ - public static String get(String key, String dflt) { - return env.getProperty(key, dflt); - } - - /** - * Gets a boolean value out of the Environment. - * - * @param key the property key - * @return the boolean value of the property or false if there is no property - * with that key - * - */ - public static boolean getBoolean(String key) { - return getBoolean(key, false); - } - - /** - * Gets a boolean value out of the Environment. - * - * @param key the property key - * @param defaultValue a default value - * @return the boolean value of the property or defaultValue if there is no - * property with that key - * - */ - public static boolean getBoolean(String key, boolean defaultValue) { - String str = env.getProperty(key, null); - if (str == null) { - return defaultValue; - } - - return (Boolean.valueOf(str)).booleanValue(); - } - - /** - * Gets an integer value out of the Environment. - * - * @param key the property key - * @return the integer value of the property or defaultValue if there is no - * property with that key - * - */ - public static int getInteger(String key) { - return getInteger(key, Integer.MIN_VALUE, 10); - } - - /** - * Gets an integer value out of the Environment. - * - * @param key the property key - * @param defaultValue a default value - * @return the integer value of the property or defaultValue if there is no - * property with that key - * - */ - public static int getInteger(String key, int defaultValue) { - return getInteger(key, defaultValue, 10); - } - - /** - * Gets an integer value out of the Environment. - * - * @param key the property key - * @param defaultValue a default value - * @param radix base value - * @return the integer value of the property or defaultValue if there is no - * property with that key - * - */ - public static int getInteger(String key, int defaultValue, int radix) { - String str = env.getProperty(key, null); - if (str == null) { - return defaultValue; - } - - try { - return Integer.parseInt(str, radix); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Gets a float value out of the Environment. - * - * @param key the property key - * @return the float value of the property or defaultValue if there is no - * property with that key - * - */ - public static float getFloat(String key) { - return getFloat(key, Float.NaN); - } - - /** - * Gets a float value out of the Environment. - * - * @param key the property key - * @param defaultValue a default value - * @return the float value of the property or defaultValue if there is no - * property with that key - * - */ - public static float getFloat(String key, float defaultValue) { - String str = env.getProperty(key, null); - if (str == null) { - return defaultValue; - } - - try { - return Float.valueOf(str).floatValue(); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Gets a double value out of the Environment. - * - * @param key the property key - * @return the double value of the property or defaultValue if there is no - * property with that key - * - */ - public double getDouble(String key) { - return getDouble(key, Double.NaN); - } - - /** - * Gets a double value out of the Environment. - * - * @param key the property key - * @param defaultValue a default value - * @return the double value of the property or defaultValue if there is no - * property with that key - * - */ - public static double getDouble(String key, double defaultValue) { - String str = env.getProperty(key, null); - if (str == null) { - return defaultValue; - } - - try { - return Double.valueOf(str).doubleValue(); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Gets the applet associated with this process. - * - * @return the applet, or null if process is an application - */ - public static Applet getApplet() { - return env.applet; - } - - /** - * Adds a key/value pair to the Environment's system properties list. - * - * @param key the key, used later for retrieval - * @param value the associate value - * @see Environment#get - */ - public static void addSystemProperty(String key, String value) { - env.put(key, value); - } - - /** - * Adds a key/value pair to the Environment's runtime properties list. - * - * @param key the key, used later for retrieval - * @param value the associate value - * @see Environment#get - */ - public static void addRuntimeProperty(String key, String value) { - env.runtimeProps.put(key, value); - } - - /** - * Returns the toplevel Properties list of the Environment. - * - * @return Properties system properties - * - */ - public static Properties getProperties() { - return env; - } - - /** - * Returns a stringified value of the current time. - *

- * Note: you probably don't want to call this in a tight loop. - * - * @return String timestamp YYYYMMDDhhmmss - * - */ - public static String timestamp() { - Calendar calendar = Calendar.getInstance(); - return "" + calendar.get(Calendar.YEAR) + calendar.get(Calendar.MONTH) + calendar.get(Calendar.DAY_OF_MONTH) - + calendar.get(Calendar.HOUR) + calendar.get(Calendar.MINUTE) + calendar.get(Calendar.SECOND); - } - - /** - * Check if this is an XWindows-based VM. - *

- * Note: this only returns a valid result if the Environment has been - * initialized. - *

- * - * @return boolean - * - */ - public static final boolean isXWindowSystem() { - return env.isXWindows; - } - - /** - * Generate a unique string. This should be unique compared to other strings - * generated this way. - * - * @return String - * @see Environment#timestamp - */ - public static String generateUniqueString() { - return get(UniqueID) + (counter++); - } - - /** - * Returns elements of the CLASSPATH that are directories. CLASSPATH elements - * that are not directories are not returned. - * - * @return Vector of Strings - */ - public static final List getClasspathDirs() { - List v = new ArrayList<>(); - try { - String classPath = System.getProperty("java.class.path"); - StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator); - - while (st.hasMoreTokens()) { - String path = st.nextToken(); - if ((new File(path)).isDirectory()) { - v.add(path); - } - } - } catch (java.security.AccessControlException ace) { - // Running as an applet?!? - } - - v.addAll(env.extraPaths); - return v; - } - - /** - * Add a resource path to internal Vector. This path will get added to the - * classpath, if the Environment is asked for classpaths. - */ - public static void addPathToClasspaths(String path) { - env.extraPaths.add(path); - } - - /** - * Checks the Environment to see if a BackgroundColor string, set as a hex ARGB - * string, has been set. If it hasn't or if it doesn't represent a valid color - * number, then null is returned, which should be interpreted as an excuse to - * use the default pretty blue embedded in the projection. - */ - public static Color getCustomBackgroundColor() { - String colorRep = get(BackgroundColor); - if (colorRep == null) { - return null; - } else { - try { - return PropUtils.parseColor(colorRep); - } catch (NumberFormatException nfe) { - return null; - } - } - } - - /** - * A method to set the Environment to be able to tell other components to - * InternalFrames. - * - * @param rootPane to use for the internal frames - the method gets the - * LayeredPane from the rootPane. - */ - public static void useInternalFrames(JRootPane rootPane) { - if (rootPane != null) { - env.useInternalFrames(rootPane.getLayeredPane()); - } else { - env.useInternalFrames((JLayeredPane) null); - } - } - - /** - * A method to set the Environment to be able to tell other components to - * InternalFrames. - * - * @param layeredPane to use for the internal frames. - */ - public void useInternalFrames(JLayeredPane layeredPane) { - if (layeredPane != null) { - desktop = layeredPane; - desktop.setOpaque(true); - put(UseInternalFrames, "true"); - } else { - desktop = null; - put(UseInternalFrames, "false"); - } - } - - public static boolean doingXWindowsWorkaround() { - return env.doingXWindowsWorkaround; - } - - /** - * Get the JLayeredPane to use for Internal Frames. May be null if the - * Environment hasn't be set with the root pane. - */ - public static JLayeredPane getInternalFrameDesktop() { - return env.desktop; - } - - private I18n i18n = new BasicI18n(); - - /** - * Get the Internationalization instance. - */ - public static I18n getI18n() { - return env.i18n; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/HintsMapBeanRepaintPolicy.java b/src/core/src/main/java/com/bbn/openmap/HintsMapBeanRepaintPolicy.java deleted file mode 100644 index 388d47513..000000000 --- a/src/core/src/main/java/com/bbn/openmap/HintsMapBeanRepaintPolicy.java +++ /dev/null @@ -1,113 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/HintsMapBeanRepaintPolicy.java,v $ -// $RCSfile: HintsMapBeanRepaintPolicy.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Graphics; -import java.util.Properties; - -import com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy; - -/** - * The class lets you set RenderingHints on the MapBean, to set anti-aliasing, - * etc. This class can be added to the OpenMap application via the - * openmap.components property in the openmap.properties file. - */ -public class HintsMapBeanRepaintPolicy - extends StandardMapBeanRepaintPolicy - implements Cloneable { - - protected RenderingHintsRenderPolicy hints; - - public HintsMapBeanRepaintPolicy() { - super(); - setHints(new RenderingHintsRenderPolicy()); - } - - public HintsMapBeanRepaintPolicy(MapBean mb) { - super(mb); - setHints(new RenderingHintsRenderPolicy()); - } - - public void setHints(RenderingHintsRenderPolicy rhrp) { - hints = rhrp; - } - - public RenderingHintsRenderPolicy getHints() { - return hints; - } - - /** - * Set RenderingHint on this object. - * - * @param key RenderingHint KEY - * @param value RenderingHint VALUE - */ - public void put(Object key, Object value) { - if (hints != null) { - hints.put(key, value); - } - } - - /** - * A hook for the RepaintPolicy to make any adjustments to the - * java.awt.Graphics object before sending the Graphics object to the layers - * for painting. Gives the policy a chance to make rendering hint changes on - * Graphic2D objects, setting anti-aliasing configurations, etc. No - * modifications are made. - */ - public Graphics modifyGraphicsForPainting(Graphics graphics) { - if (hints != null) { - hints.setRenderingHints(graphics); - } - return graphics; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - if (hints != null) { - hints.setProperties(prefix, props); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - if (hints != null) { - props = hints.getProperties(props); - } - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - if (hints != null) { - props = hints.getPropertyInfo(props); - } - return props; - } - - public Object clone() { - HintsMapBeanRepaintPolicy bmbrp = new HintsMapBeanRepaintPolicy(); - bmbrp.setHints(getHints()); - return bmbrp; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/InformationDelegator.java b/src/core/src/main/java/com/bbn/openmap/InformationDelegator.java deleted file mode 100644 index ce51a3a3d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/InformationDelegator.java +++ /dev/null @@ -1,797 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/InformationDelegator.java,v $ -// $RCSfile: InformationDelegator.java,v $ -// $Revision: 1.17 $ -// $Date: 2006/02/27 23:16:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Cursor; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.net.URL; -import java.util.ArrayList; -import java.util.Properties; - -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.SwingConstants; -import javax.swing.ToolTipManager; - -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressListener; -import com.bbn.openmap.gui.MapPanelChild; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.gui.StatusLightPanel; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.WebBrowser; - -/** - * The InformationDelegator manages the display of information requested by - * Layers and other map components. It can bring up a web browser to display web - * pages and files, and pop up a message window to provide status information to - * the user. It also has a visible status window that contains a layer status - * indicator, and an information line that can display short messages. - *

- * InformationDelegators are added to layers, and the layer fires events through - * the InfoDisplayListener interface. The InformationDelegator has a method - * called listenToLayers() that lets you give it an array of layers, and it adds - * itself as a InfoDisplayListener to those layers. - *

- * The InformationDelegator lets you alter its behavior with property settings: - * - *

- * 
- *     # Make the status lights buttons that bring up layer palettes.
- *     infoDelegator.triggers=true
- *     # Show the layer status lights.
- *     infoDelegator.showLights=true
- *     # Show the text line for map object information
- *     infoDelegator.showInfoLine=true
- *     # Show the text line for coordinate information
- *     infoDelegator.showCoordsInfoLine=true
- * 
- * 
- */ -public class InformationDelegator extends OMComponentPanel implements InfoDisplayListener, - PropertyChangeListener, ProgressListener, MapPanelChild { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected JLabel infoLineHolder; - protected JLabel infoLineHolder2; - - protected WebBrowser browser; - protected StatusLightPanel statusBar; - - protected JProgressBar progressBar; - - protected MapBean map; - - protected ToolTipManager ttmanager; - protected String propertyPrefix; - - private String fudgeString = " "; - /** - * Used to remember what the MouseModeCursor is, which is the base cursor - * setting for the MapBean. The gesture modes set this cursor, and it gets - * used when the currentMapBeanCursor is null. - */ - protected Cursor fallbackMapBeanCursor = Cursor.getDefaultCursor(); - /** - * Used to remember any cursor that may bave been requested by a layer. This - * is usually null, unless a layer has requested a cursor. The MapBean - * gesture modes set the fallbackMapBeanCursor instead. - */ - protected Cursor currentMapBeanCursor = null; - protected boolean waitingForLayers = false; - protected boolean showWaitCursor = false; - - /** - * Flag to show the status lights. - */ - protected boolean showLights = true; - public final static String ShowLightsProperty = "showLights"; - public final static String ShowInfoLineProperty = "showInfoLine"; - public final static String ShowCoordsInfoLineProperty = "showCoordsInfoLine"; - public final static String WebBrowserClassProperty = "webBrowserClass"; - - public final static int MAP_OBJECT_INFO_LINE = 0; // Default - public final static int COORDINATE_INFO_LINE = 1; - - protected ArrayList infoLineOrganizer = new ArrayList<>(); - - public InformationDelegator() { - super(); - - initInfoWidgets(); - } - - /** - * If you want to subclass the InformationDelegator and have it handle - * messages differently, you can override this method to set the widgets you - * want. - */ - public void initInfoWidgets() { - - Debug.message("info", "InformationDelegator.initInfoWidgets"); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - setFont(new Font("Helvetica", Font.PLAIN, 9)); - setLayout(gridbag); - - progressBar = new JProgressBar(); - gridbag.setConstraints(progressBar, c); - add(progressBar); - progressBar.setVisible(false); - - JPanel infoLinePanel = new JPanel(); - c.weightx = 1; - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - gridbag.setConstraints(infoLinePanel, c); - - GridBagLayout gridbag2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - infoLinePanel.setLayout(gridbag2); - - infoLineHolder = new JLabel(fudgeString); - c2.weightx = .9; - c2.fill = GridBagConstraints.HORIZONTAL; - c2.anchor = GridBagConstraints.WEST; - c2.insets = new Insets(3, 10, 3, 10); - gridbag2.setConstraints(infoLineHolder, c2); - infoLinePanel.add(infoLineHolder); - - infoLineHolder2 = new JLabel(fudgeString, SwingConstants.RIGHT); - c2.weightx = .1; - c2.anchor = GridBagConstraints.EAST; - gridbag2.setConstraints(infoLineHolder2, c2); - infoLinePanel.add(infoLineHolder2); - - addInfoLine(COORDINATE_INFO_LINE, infoLineHolder); - addInfoLine(MAP_OBJECT_INFO_LINE, infoLineHolder2); - - add(infoLinePanel); - - c.weightx = 0; - c.anchor = GridBagConstraints.EAST; - statusBar = new StatusLightPanel(); - gridbag.setConstraints(statusBar, c); - add(statusBar); - statusBar.setVisible(showLights); - } - - /** - * Set the MapBean so that when the mouse mode changes, the cursor can - * change. This gets called from findAndInit if a MapHandler is involved - * with the application. - */ - public void setMap(MapBean map) { - if (this.map != null) { - this.map.removePropertyChangeListener(this); - } - - this.map = map; - if (map != null) { - map.addPropertyChangeListener(this); - fallbackMapBeanCursor = map.getCursor(); - } - } - - /** - * Listen for changes to the active mouse mode and for any changes to the - * list of available mouse modes. If the active mouse mode is "gestures", - * then the lat lon updates to the status line are deactivated. - */ - public void propertyChange(PropertyChangeEvent evt) { - String propName = evt.getPropertyName(); - if (propName == MapBean.CursorProperty) { - fallbackMapBeanCursor = ((Cursor) evt.getNewValue()); - } else { - if (propName == MouseDelegator.ActiveModeProperty) { - MapMouseMode mmm = (MapMouseMode) evt.getNewValue(); - setResetCursor(mmm.getModeCursor()); - } else if (propName == MapBean.LayersProperty) { - resetForLayers((Layer[]) evt.getNewValue(), (Layer[]) evt.getOldValue()); - } else if (propName != MapBean.ProjectionProperty) { - // For stuff we don't care about, just return from - // here. Otherwise, reset the GUI below... - return; - } - - // Clear out all the information lines, resetting the GUI - setAllLabels(fudgeString); - } - - initToolTip(); - } - - /** - * Set the InformationDelegator on Layers. Usually called because the layers - * changed on the map, and we need to add the InformationDelegator as an - * InfoDisplayListener for the new layers, and remove it from the old - * layers. - */ - public void resetForLayers(Layer[] connectToLayers, Layer[] removeFromLayers) { - - int i = 0; - if (removeFromLayers != null && removeFromLayers.length != 0) { - int removeLength = removeFromLayers.length; - for (i = 0; i < removeLength; i++) { - removeFromLayers[i].removeInfoDisplayListener(this); - } - } - - if (connectToLayers != null && connectToLayers.length != 0) { - int removeLength = connectToLayers.length; - for (i = 0; i < removeLength; i++) { - connectToLayers[i].addInfoDisplayListener(this); - } - } - } - - /** - * Receive a ProgressEvent, and use it if possible. - */ - public void updateProgress(ProgressEvent evt) { - if (progressBar != null) { - int type = evt.getType(); - if (type == ProgressEvent.START || type == ProgressEvent.UPDATE) { - - progressBar.setVisible(true); - progressBar.setValue(evt.getPercentComplete()); - setLabel(evt.getTaskDescription()); - } else { - progressBar.setVisible(false); - } - } - } - - public void addInfoLine(int refIndex, JLabel iLine) { - try { - infoLineOrganizer.set(refIndex, iLine); - } catch (IndexOutOfBoundsException ioobe) { - while (refIndex > 0 && infoLineOrganizer.size() <= refIndex + 1) { - infoLineOrganizer.add(iLine); - } - } - } - - public void removeInfoLine(int refIndex) { - try { - infoLineOrganizer.set(refIndex, null); - } catch (IndexOutOfBoundsException iiobe) { - } - } - - /** - * Set the information line label. - * - * @param str String - */ - public void setLabel(String str) { - setLabel(str, MAP_OBJECT_INFO_LINE); - } - - public void setAllLabels(String str) { - for (int i = 0; i < infoLineOrganizer.size(); i++) { - setLabel(str, i); - } - } - - /** - * Set the information line label. - * - * @param str String - * @param infoLineDesignator the designator used to specify which - * information line to use to display the string. - */ - public void setLabel(String str, int infoLineDesignator) { - JLabel iLine; - try { - iLine = (JLabel) infoLineOrganizer.get(infoLineDesignator); - } catch (IndexOutOfBoundsException ioobe) { - // This should be OK. - iLine = (JLabel) infoLineOrganizer.get(MAP_OBJECT_INFO_LINE); - } - - if (iLine != null) { - iLine.setText(str); - } - } - - /** - * The method that updates the InformationDelegator display window with the - * correct layer representation. A status light reset method. - */ - protected void setStatusBar() { - statusBar.reset(); - } - - public void setBrowser(WebBrowser wb) { - browser = wb; - browser.setInfoDelegator(this); - } - - public WebBrowser getBrowser() { - return browser; - } - - /** - * Try to display a URL in a web browser. - */ - public void displayURL(String url) { - - WebBrowser wb = getBrowser(); - if (wb == null) { - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - try { - com.bbn.openmap.gui.MiniBrowser.display(frame, new URL(url)); - } catch (java.net.MalformedURLException murle) { - Debug.error("InformationDelegator can't launch " + url); - } - } else { - wb.launch(url); - } - } - - /** - * Display a html String in a window. - */ - public void displayBrowserContent(String content) { - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - com.bbn.openmap.gui.MiniBrowser.display(frame, "text/html", content); - } - - /** - * Display a line of text in a info line. - */ - public void displayInfoLine(String infoLine) { - displayInfoLine(infoLine, MAP_OBJECT_INFO_LINE); - } - - /** - * Display a line of text in a designated info line. - */ - public void displayInfoLine(String infoLine, int labelDesignator) { - if (infoLineHolder != null) { - setLabel((infoLine != null && infoLine.length() > 0) ? infoLine : fudgeString, labelDesignator); - } - } - - /** - * Display a message in a pop-up window. - */ - public void displayMessage(String title, String message) { - if (Environment.getBoolean(Environment.UseInternalFrames)) { - JOptionPane.showInternalMessageDialog(Environment.getInternalFrameDesktop(), message, title, JOptionPane.INFORMATION_MESSAGE); - } else { - JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE); - } - } - - // ///////////////////////////////////////// - // InfoDisplayListener interface - - /** - * Handle layer requests to have a URL displayed in a Browser. - * - * @param event InfoDisplayEvent - */ - public void requestURL(InfoDisplayEvent event) { - displayURL(event.getInformation()); - } - - /** - * Handle layer requests to have a message displayed in a dialog window. - * - * @param event InfoDisplayEvent - */ - public void requestMessage(InfoDisplayEvent event) { - Layer l = event.getLayer(); - String layername = (l == null) ? null : l.getName(); - displayMessage("Message from " + layername + " layer:", event.getInformation()); - } - - /** - * Handle layer requests to have an information line displayed in an - * application status window. - * - * @param event InfoDisplayEvent - */ - public void requestInfoLine(InfoDisplayEvent event) { - displayInfoLine(event.getInformation(), event.getPreferredLocation()); - } - - /** - * Handle layer requests that plain text or html text be displayed in a - * browser. - * - * @param event InfoDisplayEvent - */ - public void requestBrowserContent(InfoDisplayEvent event) { - displayBrowserContent(event.getInformation()); - } - - /** - * If a tooltip is required over a spot on the map then a - * MouseMapListener should pass a MouseEvent to this method. - * The Swing ToolTipManager is used to achieve this. A call to this method - * should always be followed by a call to hideToolTip - * - * @param me A MouseEvent from a MapMouseListener which - * indicates where the tooltip is to appear (unused) - * @param event an event containing the ToolTip to show - * @deprecated use requestShowToolTip(InfoDisplayEvent) instead. - */ - public void requestShowToolTip(MouseEvent me, InfoDisplayEvent event) { - requestShowToolTip(event); - } - - /** - * If a tooltip is required over a spot on the map then a - * MouseMapListener should pass a MouseEvent to this method. - * The Swing ToolTipManager is used to achieve this. A call to this method - * should always be followed by a call to hideToolTip - * - * @param event an event containing the ToolTip to show - */ - public void requestShowToolTip(InfoDisplayEvent event) { - // shows a tooltip over the map - if (map != null) { - if (ttmanager == null) { - initToolTip(); - } - map.setToolTipText(event.getInformation()); - } - } - - /** - * This method should follow a call to showToolTip in order to indicate that - * the tooltip should no longer be displayed. This method should always - * follow a call to showToolTip - * - * @param me A MouseEvent which passes from a MapMouseListener to indicate - * that a tooltip should disappear - * @deprecated call requestHideToolTip() instead. - */ - public void requestHideToolTip(MouseEvent me) { - requestHideToolTip(); - } - - /** - * This method should follow a call to showToolTip in order to indicate that - * the tooltip should no longer be displayed. This method should always - * follow a call to showToolTip - */ - public void requestHideToolTip() { - initToolTip(); - } - - /** - * This method should be called to initialize the tooltip status so that an - * old tooltip doesn't remain when a layer starts listening to mouse events. - */ - public void initToolTip() { - if (ttmanager == null) { - // make sure the MapBean is registered first - ttmanager = ToolTipManager.sharedInstance(); - ttmanager.registerComponent(map); - ttmanager.setEnabled(true); - return; - } - - // If it already exists, clear out the current tip - if (map != null) { - map.setToolTipText(null); - } - } - - /** - * Change the cursor for the MapBean. If the MapBean hasn't been set, then - * nothing will happen on the screen. If a null value is passed in, the - * cursor is reset to the MouseMode value. If the InformationDelegator is - * allowed to show the wait cursor, and the layers are busy, the wait cursor - * will take precedence. The requested cursor from a layer will be set if - * the layers finish. - * - * @param cursor java.awt.Cursor to change the cursor to. - */ - public void requestCursor(java.awt.Cursor cursor) { - // This is interpreted as a release from a requester - if (cursor == null) { - // If we're not supposed to be showing the wait cursor... - if (showWaitCursor && !waitingForLayers) - resetCursor(); - // Set this to null, so that when we're done waiting for - // the layers, we'll just reset. - currentMapBeanCursor = null; - } else if (this.map != null) { - Cursor newCursor; - // If we're supposed to be showing the watch, do it, but - // save the request for when the layers are done. - if (showWaitCursor && waitingForLayers) { - newCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); - currentMapBeanCursor = cursor; - } else - newCursor = cursor; - - map.setCursor(newCursor); - } - } - - /** - * Set the cursor to use when the waiting is done, if a layer hasn't asked - * for one to be displayed. For the MouseMode changes, this is automatically - * called. - */ - public void setResetCursor(java.awt.Cursor cursor) { - fallbackMapBeanCursor = cursor; - } - - /** - * Sets the cursor over the mapbean to the assigned default, or whatever has - * been set by the MouseMode. - */ - public void resetCursor() { - if (this.map != null) - map.setCursor(fallbackMapBeanCursor); - } - - /** - * If the value passed in is true, the cursor over the MapBean will be the - * waiting cursor layers are off working. The status lights will work, too, - * no matter what the value is. If false, the cursor won't change if the - * layers are working. - */ - public void setShowWaitCursor(boolean value) { - showWaitCursor = value; - } - - /** - * Returns whether the wait cursor will be shown if the layers are working. - */ - public boolean isShowWaitCursor() { - return showWaitCursor; - } - - // ////////// MapHandlerChild methods overridden from - // OMComponentPanel - - /** - * Called when an object has been added to the BeanContext. The - * InformationDelegator will look for certain objects it needs. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setMap((MapBean) someObj); - } - if (someObj instanceof MouseDelegator) { - MouseDelegator md = (MouseDelegator) someObj; - md.addPropertyChangeListener(this); - } - - statusBar.findAndInit(someObj); - } - - /** - * Called when an object is being removed from the BeanContext. Will cause - * the object to be disconnected from the InformationDelegator if it is - * being used. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - setMap(null); - } - if (someObj instanceof MouseDelegator) { - MouseDelegator md = (MouseDelegator) someObj; - md.removePropertyChangeListener(this); - } - - statusBar.findAndUndo(someObj); - } - - // ///// PropertyConsumer methods overridden from OMComponentPanel - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - statusBar.setProperties(prefix, props); - setShowLights(PropUtils.booleanFromProperties(props, prefix + ShowLightsProperty, showLights)); - setShowInfoLine(PropUtils.booleanFromProperties(props, prefix + ShowInfoLineProperty, getShowInfoLine())); - setShowCoordsInfoLine(PropUtils.booleanFromProperties(props, prefix - + ShowCoordsInfoLineProperty, getShowCoordsInfoLine())); - String pl = props.getProperty(prefix + PreferredLocationProperty); - if (pl != null) { - setPreferredLocation(pl); - } - - Object webBrowserObj = PropUtils.objectFromProperties(props, prefix - + WebBrowserClassProperty); - if (webBrowserObj instanceof WebBrowser) { - setBrowser((WebBrowser) webBrowserObj); - } - - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - statusBar.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + ShowLightsProperty, new Boolean(showLights).toString()); - props.put(prefix + ShowInfoLineProperty, new Boolean(getShowInfoLine()).toString()); - props.put(prefix + ShowCoordsInfoLineProperty, new Boolean(getShowCoordsInfoLine()).toString()); - props.put(prefix + PreferredLocationProperty, getPreferredLocation()); - - WebBrowser wb = getBrowser(); - if (wb != null) { - props.put(prefix + WebBrowserClassProperty, wb.getClass().getName()); - } - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - statusBar.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, props, InformationDelegator.class, ShowLightsProperty, "Show Layer Status", "Show the layer status lights.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, InformationDelegator.class, ShowInfoLineProperty, "Show Map Information", "Show the text line containing map object information.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, InformationDelegator.class, ShowCoordsInfoLineProperty, "Show Coordinate Information", "Show the text line containing coordinate information.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, InformationDelegator.class, PreferredLocationProperty, "Preferred Location", "Set the preferred location of the information lines (default under the map).", null); - PropUtils.setI18NPropertyInfo(i18n, props, InformationDelegator.class, WebBrowserClassProperty, "WebBrowser Class", "Set an object to be used to handle displaying web pages (default is null).", null); - - return props; - } - - // ///// Setters and Getters - - public void setInfoLineHolder(JLabel ilh) { - infoLineHolder = ilh; - } - - public JLabel getInfoLineHolder() { - return infoLineHolder; - } - - public void setProgressBar(JProgressBar progressBar) { - this.progressBar = progressBar; - } - - public JProgressBar getProgressBar() { - return progressBar; - } - - public void setShowLights(boolean set) { - showLights = set; - statusBar.setVisible(set); - } - - public boolean getShowLights() { - return showLights; - } - - /** - * This only holds if the MAP_OBJECT_INFO_LINE has been created. - * - * @param set sets the visibility of the information line for map object - * information. - */ - public void setShowInfoLine(boolean set) { - if (infoLineHolder2 != null) { - infoLineHolder2.setVisible(set); - } - } - - public boolean getShowInfoLine() { - boolean ret = true; - if (infoLineHolder2 != null) { - ret = infoLineHolder2.isVisible(); - } - return ret; - } - - /** - * This only holds if the COORDINATE_INFO_LINE has been created. - * - * @param set sets the visibility of the information line for coordinate - * information. - */ - public void setShowCoordsInfoLine(boolean set) { - if (infoLineHolder != null) { - infoLineHolder.setVisible(set); - } - } - - public boolean getShowCoordsInfoLine() { - boolean ret = true; - if (infoLineHolder != null) { - ret = infoLineHolder.isVisible(); - } - return ret; - } - - public void setLightTriggers(boolean set) { - statusBar.setLightTriggers(set); - } - - public boolean getLightTriggers() { - return statusBar.getLightTriggers(); - } - - public void setFloatable(boolean value) { - } - - /** - * BorderLayout.SOUTH by default for this class. - */ - protected String preferredLocation = java.awt.BorderLayout.SOUTH; - - /** - * MapPanelChild method. - */ - public void setPreferredLocation(String value) { - preferredLocation = value; - } - - /** - * MapPanelChild method. - */ - public String getPreferredLocation() { - return preferredLocation; - } - - public String getParentName() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/Layer.java b/src/core/src/main/java/com/bbn/openmap/Layer.java deleted file mode 100644 index 25e4effff..000000000 --- a/src/core/src/main/java/com/bbn/openmap/Layer.java +++ /dev/null @@ -1,1635 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/Layer.java,v $ -// $RCSfile: Layer.java,v $ -// $Revision: 1.34 $ -// $Date: 2008/09/28 19:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.MouseListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.lang.reflect.Method; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.swing.Icon; -import javax.swing.JComponent; - -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.gui.ScrollPaneWindowSupport; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * Layer objects are components which can be added to the MapBean to make a map. - *

- * - * Layers implement the ProjectionListener interface to listen for - * ProjectionEvents. When the projection changes, they may need to refetch, - * regenerate their graphics, and then repaint themselves into the new view. - *

- * - * When the Layer is added to the MapBean, it will start receiving - * ProjectionEvents via the ProjectionListener.projectionChanged() method it has - * to implement. There is a setProjection(ProjectionEvent) methods that should - * be called from there if you want to save the projection for later use - * (handling MouseEvents, etc). If you call getProjection() before calling - * setProjection(), getProjection() will return null, and your OMGraphics will - * complain and probably freak out at some point. - * - *

- * // // SAMPLE handling of the ProjectionListener interface.
- * 
- * public void projectionChanged(com.bbn.openmap.event.ProjectionEvent pe) {
- * 	Projection proj = setProjection(pe);
- * 	if (proj != null) {
- * 		// Use the projection to gather OMGraphics in the layer,
- * 		// and prepare the layer so that in the paint() method,
- * 		// the OMGraphics get rendered.
- * 
- * 		// Call any methods that kick off work to build graphics
- * 		// here...
- * 
- * 		// You get the paint() methods called by calling
- * 		// repaint():
- * 		repaint();
- * 	}
- * 
- * 	fireStatusUpdate(LayerStatusEvent.FINISH_WORKING);
- * }
- * 
- * - * @see com.bbn.openmap.event.ProjectionListener - * @see com.bbn.openmap.event.ProjectionEvent - * @see com.bbn.openmap.PropertyConsumer - */ -public abstract class Layer extends JComponent implements ProjectionListener, ProjectionPainter, BeanContextChild, - BeanContextMembershipListener, PropertyConsumer, ActionListener { - - private static final long serialVersionUID = 1L; - - /** - * Pre-caches the swing package. Computed based on the package of - * JComponent. - */ - protected static final String SWING_PACKAGE = getPackage(JComponent.class); - - /** - * The String to use for a key lookup in a Properties object to find the - * name to use in a GUI relating to this layer. - */ - public static final String PrettyNameProperty = "prettyName"; - - /** - * The property to set to add the layer to the BeanContext - * "addToBeanContext". This probably needs be set by the layer itself, - * because it knows whether it needs other components or not. However, this - * property is defined in case an option can be given to the user. If a - * Layer doesn't want this option given, it should reset the - * addToBeanContext variable after setProperties() is called. The - * Layer.setProperties() methods maintain the current state of the variable - * if undefined, which is true by default. - */ - public static final String AddToBeanContextProperty = "addToBeanContext"; - - /** - * Property 'background' to designate this layer as a background layer, - * which will cause extra buffering to occur if the application can handle - * it. False by default. - */ - public static final String AddAsBackgroundProperty = "background"; - - /** - * Property 'removable' to designate this layer as removable from the - * application, or able to be deleted. True by default. - */ - public static final String RemovableProperty = "removable"; - - /** - * The property for designating the minimum projection scale value that the - * layer will respond to. This Layer class doesn't limit how subclasses will - * react to projections with scale values smaller than the specified value. - */ - public static final String MinScaleProperty = "minScale"; - /** - * The property for designating the maximum projection scale value that the - * layer will respond to. This Layer class doesn't limit how subclasses will - * react to projections with scale values greater than the specified value. - */ - public static final String MaxScaleProperty = "maxScale"; - - /** - * The property to show the palette when the layer is created - or, more - * accurately, when the properties are set. - */ - public static final String AutoPaletteProperty = "autoPalette"; - /** Layer-defined action event command to display the palette. */ - public static final String DisplayPaletteCmd = "displayPaletteCmd"; - /** Layer-defined action event command to hide the palette. */ - public static final String HidePaletteCmd = "hidePaletteCmd"; - /** - * Layer-defined action event command to display the properties using an - * Inspector. - */ - public static final String DisplayPropertiesCmd = "displayPropertiesCmd"; - /** - * Layer-defined action event command to force a redraw on the layer. The - * Layer class does not respond to this command, it's provided as a - * convenience. - */ - public static final String RedrawCmd = "redrawCmd"; - /** - * Generic property that may be set for a layer to let it know at runtime - * that a path prefix needs to be added to a relative data path. This - * property should be set in the attributes of a layer after being read from - * properties. - */ - public static final String DataPathPrefixProperty = "dataPathPrefix"; - /** - * The property used to name a class providing translation services - * (optional, depends on input data). - */ - public final static String TransformProperty = "transform"; - /** - * Tooltip to use by components listing layer in GUI components, like - * LayersMenu and LayersPanel. - */ - public final static String ToolTipProperty = OMGraphicConstants.TOOLTIP.toLowerCase(); - - /** - * The listeners to the Layer that respond to requests for information - * displays, like messages, requests for URL displays, etc. - */ - private final ListenerSupport IDListeners = new ListenerSupport(this); - - /** - * List of LayerStatusListeners. - */ - private final ListenerSupport lsListeners = new ListenerSupport(this); - - /** - * Token uniquely identifying this layer in the application properties. - */ - protected String propertyPrefix = null; - - /** - * Used by the LayerHandler to check if the layer should be added to the - * MapHandler BeanContext. See the comments under the - * AddToBeanContextProperty. True by default. - */ - protected boolean addToBeanContext = true; - - /** - * Flag used by the layer to indicate that it should be treated as a - * background layer, indicating that any cache mechanism available can - * enable extra buffering. This may prevent mouse events from being received - * by the layer. - */ - protected boolean addAsBackground = false; - - /** - * Flag to designate the layer as removable or not. - */ - protected boolean removable = true; - - /** - * A flag to have the layer display it's palette when the properties are - * set. If you are creating a layer manually, just call showPalette() - * instead. - */ - protected boolean autoPalette = false; - - /** - * A minimum projection scale value that the layer will respond to. Using - * this value for reacting to the projection depends on the Layer - * implementation, the Layer class doesn't limit subclasses from doing their - * own thing in response to the scale setting on a projection. - */ - protected float minScale = Float.MIN_VALUE; - - /** - * A maximum projection scale value that the layer will respond to. Using - * this value for reacting to the projection depends on the Layer - * implementation, the Layer class doesn't limit subclasses from doing their - * own thing in response to the scale setting on a projection. - */ - protected float maxScale = Float.MAX_VALUE; - - /** - * This is a convenience copy of the latest projection received from the - * MapBean, when the Layer is added to the map. If you need it, use the - * accessor!. - */ - private Projection projection = null; - - /** - * Support class that now handles palette windows. - */ - protected transient WindowSupport windowSupport; - - /** - * A helper component listener that is paying attention to the visibility of - * the palette. - */ - protected transient ComponentListener paletteListener; - - /** - * A pointer to the JDialog or JInternalFrame. May be used by the layer's - * ComponentListeners to figure out if a component event is for the layer or - * for the palette. - */ - protected transient Container palette; - - /** - * The BeanContext allows Layers to find other components, and other - * components to find the layer, if the layer is added to it. - */ - protected transient BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * All layers have access to an I18n object, which is provided by the - * Environment. - */ - protected transient I18n i18n = Environment.getI18n(); - - /** - * Icon associated with layer. - */ - private Icon icon = null; - - /** - * Map containing attribute information for the layer. For serialized - * layers, we're not really going out of our way to make sure that keys and - * values are serializable. - */ - protected Map attributes; - - /** - * A translator that can be set to convert pre-projected coordinates from - * the file into decimal degree lat/lon, and for saving data to a file in - * pre-projected coordinates. - */ - protected GeoCoordTransformation coordTransform; - - /** - * New variable to describe when a layer has responded to a projection - * change and is ready to be painted. Used by the BufferedLayerMapBean, - * which limits repaint calls to only be passed on when all background - * layers are ready to be painted. This eliminates the flashing effect - * caused when some layers call for a repaint before background layers do, - * causing the map background to be displayed for a second. - */ - protected AtomicBoolean readyToPaint = new AtomicBoolean(true); - - /** - * Returns the package of the given class as a string. - * - * @param c a class - */ - protected static String getPackage(Class c) { - String className = c.getName(); - int lastDot = className.lastIndexOf('.'); - return className.substring(0, lastDot); - } - - /** - * Override to only allow swing package listeners. If Listeners get added to - * the Layers, the mouse events don't make it to the map. Ever. - *

- * Swing popup menus, like JPopupMenu grab the JComponent by - * adding themselves as MouseListener s. So this method allows - * instances of classes in the xxx.swing package to be added as - * MouseListeners, and no one else. - * - * @param l a mouse listener. - */ - public final void addMouseListener(MouseListener l) { - String pkg = getPackage(l.getClass()); - if (java.beans.Beans.isDesignTime() || pkg.equals(SWING_PACKAGE) || pkg.startsWith(SWING_PACKAGE) - || pkg.startsWith("com.sun.java.accessibility.util")) { - - // Used to do nothing for the equals and startsWith - // comparison, but that breaks the menus from being - // recinded when something else is clicked on. Thanks to - // Tom Peel for pointing this out, 11/29/00. - super.addMouseListener(l); - } else { - throw new IllegalArgumentException("This operation is disallowed because the package \"" - + getPackage(l.getClass()) + "\" is not in the swing package (\"" + SWING_PACKAGE + "\")."); - } - } - - /** - * Sets the properties for the Layer. This particular method - * assumes that the marker name is not needed, because all of the contents - * of this Properties object are to be used for this layer, and scoping the - * properties with a prefix is unnecessary. - * - * @param props the Properties object. - */ - public void setProperties(Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the Layer. Part of the - * PropertyConsumer interface. Layers which override this method should do - * something like: - * - *

-	 * public void setProperties(String prefix, Properties props) {
-	 * 	super.setProperties(prefix, props);
-	 * 	// do local stuff
-	 * }
-	 * 
- * - * If the addToBeanContext property is not defined, it maintains the same - * state. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - setLayerProperties(prefix, props); - } - - /** - * Called by setProperties. Allows subclasses to avoid super.setProperties() - * while still having basic Layer settings taken care of. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - protected void setLayerProperties(String prefix, Properties props) { - String prettyName = PrettyNameProperty; - setPropertyPrefix(prefix); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - prettyName = realPrefix + PrettyNameProperty; - - String defaultName = getName(); - if (defaultName == null) { - defaultName = "Anonymous"; - } - - setName(props.getProperty(prettyName, defaultName)); - - setAddToBeanContext( - PropUtils.booleanFromProperties(props, realPrefix + AddToBeanContextProperty, addToBeanContext)); - - setAddAsBackground( - PropUtils.booleanFromProperties(props, realPrefix + AddAsBackgroundProperty, addAsBackground)); - - setRemovable(PropUtils.booleanFromProperties(props, realPrefix + RemovableProperty, removable)); - - autoPalette = PropUtils.booleanFromProperties(props, realPrefix + AutoPaletteProperty, autoPalette); - - setMinScale(PropUtils.floatFromProperties(props, realPrefix + MinScaleProperty, getMinScale())); - setMaxScale(PropUtils.floatFromProperties(props, realPrefix + MaxScaleProperty, getMaxScale())); - - String dataPathPrefix = props.getProperty(realPrefix + DataPathPrefixProperty, ""); - if (dataPathPrefix.length() > 0) { - putAttribute(DataPathPrefixProperty, dataPathPrefix); - } - - String transClassName = props.getProperty(realPrefix + TransformProperty); - if (transClassName != null) { - try { - coordTransform = (GeoCoordTransformation) ComponentFactory.create(transClassName, - realPrefix + TransformProperty, props); - } catch (ClassCastException cce) { - - } - } - - String tooltipString = props.getProperty(realPrefix + ToolTipProperty); - if (tooltipString != null && !tooltipString.trim().isEmpty()) { - putAttribute(ToolTipProperty, tooltipString); - } - - } - - public void setName(String name) { - super.setName(name); - - BeanContext bc = getBeanContext(); - if (bc instanceof MapHandler) { - LayerHandler lh = (LayerHandler) ((MapHandler) bc).get("com.bbn.openmap.LayerHandler"); - - if (lh != null) { - lh.setLayers(); - } - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - props.put(prefix + "class", this.getClass().getName()); - - PropUtils.putIfNotDefault(props, prefix + PrettyNameProperty, getName()); - PropUtils.putIfNotDefault(props, prefix + AutoPaletteProperty, new Boolean(autoPalette).toString(), Boolean.FALSE); - PropUtils.putIfNotDefault(props, prefix + AddAsBackgroundProperty, new Boolean(addAsBackground).toString(), Boolean.FALSE); - PropUtils.putIfNotDefault(props, prefix + RemovableProperty, new Boolean(removable).toString(), Boolean.TRUE); - PropUtils.putIfNotDefault(props, prefix + AddToBeanContextProperty, new Boolean(addToBeanContext).toString(), Boolean.TRUE); - PropUtils.putIfNotDefault(props, prefix + ToolTipProperty, getAttribute(ToolTipProperty)); - PropUtils.putIfNotDefault(props, prefix + MinScaleProperty, Float.toString(getMinScale()), Float.MIN_VALUE); - PropUtils.putIfNotDefault(props, prefix + MaxScaleProperty, Float.toString(getMaxScale()), Float.MAX_VALUE); - PropUtils.putIfNotDefault(props, prefix + DataPathPrefixProperty, getAttribute(DataPathPrefixProperty)); - - if (coordTransform instanceof PropertyConsumer) { - ((PropertyConsumer) coordTransform).getProperties(props); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put("class", "Class Name used for Layer."); - list.put("class.editor", "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - - String internString = i18n.get(Layer.class, PrettyNameProperty, I18n.TOOLTIP, "Presentable name for Layer"); - list.put(PrettyNameProperty, internString); - internString = i18n.get(Layer.class, PrettyNameProperty, "Layer Name"); - list.put(PrettyNameProperty + LabelEditorProperty, internString); - list.put(PrettyNameProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - - internString = i18n.get(Layer.class, AutoPaletteProperty, I18n.TOOLTIP, - "Flag to automatically display palette when properties are set"); - list.put(AutoPaletteProperty, internString); - internString = i18n.get(Layer.class, AutoPaletteProperty, "Open Palette At Start"); - list.put(AutoPaletteProperty + LabelEditorProperty, internString); - list.put(AutoPaletteProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, AddAsBackgroundProperty, I18n.TOOLTIP, - "Flag to use the layer as a background layer"); - list.put(AddAsBackgroundProperty, internString); - internString = i18n.get(Layer.class, AddAsBackgroundProperty, "Background"); - list.put(AddAsBackgroundProperty + LabelEditorProperty, internString); - list.put(AddAsBackgroundProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, RemovableProperty, I18n.TOOLTIP, "Flag to allow layer to be deleted."); - list.put(RemovableProperty, internString); - internString = i18n.get(Layer.class, RemovableProperty, "Removable"); - list.put(RemovableProperty + LabelEditorProperty, internString); - list.put(RemovableProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, AddToBeanContextProperty, I18n.TOOLTIP, - "Flag to give the layer access to all of the other application components."); - list.put(AddToBeanContextProperty, internString); - internString = i18n.get(Layer.class, AddToBeanContextProperty, "Add to MapHandler"); - list.put(AddToBeanContextProperty + LabelEditorProperty, internString); - list.put(AddToBeanContextProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, MinScaleProperty, I18n.TOOLTIP, - "Minimum projection scale value that the layer will respond to."); - list.put(MinScaleProperty, internString); - internString = i18n.get(Layer.class, MinScaleProperty, "Minimum Scale Value"); - list.put(MinScaleProperty + LabelEditorProperty, internString); - - internString = i18n.get(Layer.class, MaxScaleProperty, I18n.TOOLTIP, - "Maximum projection scale value that the layer will respond to."); - list.put(MaxScaleProperty, internString); - internString = i18n.get(Layer.class, MaxScaleProperty, "Maximum Scale Value"); - list.put(MaxScaleProperty + LabelEditorProperty, internString); - - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix for the layer - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * Set the projection the layer should use for calculations. You probably - * don't need this if you are wondering if you do. Call - * setProjection(projEvent) instead. - */ - public void setProjection(Projection proj) { - projection = proj; - } - - /** - * This method lets you take the ProjectionEvent received from the MapBean, - * and lets you know if you should do something with it. MUST to be called - * in the projectionChanged() method of your layer, if you want to refer to - * the projection later. If this methods returns null, you probably just - * want to call repaint() if your layer.paint() method is ready to paint - * what it should. - * - * @param projEvent the ProjectionEvent from the ProjectionListener method. - * @return The new Projection if it is different from the one we already - * have, null if is the same as the current one. - */ - public Projection setProjection(ProjectionEvent projEvent) { - Projection newProjection = projEvent.getProjection(); - - if (!newProjection.equals(getProjection())) { - Projection clone = newProjection.makeClone(); - setProjection(clone); - return clone; - } else { - return null; - } - } - - /** - * Get the latest projection. - */ - public Projection getProjection() { - return projection; - } - - /** - * Returns the MapMouseListener object that handles the mouse events. This - * method is IGNORED in this class: it returns null. Derived Layers should - * return the appropriate object if they desire to receive MouseEvents. The - * easiest thing for a Layer to do in order to receive MouseEvents is to - * implement the MapMouseListener interface and return itself. A code - * snippet: - *

- * - *

-	 * public MapMouseListener getMapMouseListener() {
-	 * 	return this;
-	 * }
-	 * 
-	 * public String[] getMouseModeServiceList() {
-	 * 	return new String[] { SelectMouseMode.modeID };
-	 * }
-	 * 
- * - * @return null for the default, method can be overridden to return - * something interested in mouse events. - */ - public MapMouseListener getMapMouseListener() { - return null; - } - - /** - * A GUI query method for other components to use to display whether gui - * controls are available for this layer. If your layer provides gui - * controls and the LayersPanel is being used in your application, you - * should override this method in your layer to return true. This will allow - * the other gui components to know that your layer has controls, while - * still not actually building those controls until they are needed by the - * user. - * - * @return true if there is a GUI for controlling the layer settings, false - * if not or if the getGUI() method hasn't been overridden. - */ - public boolean hasGUI() { - boolean hasGUI = false; - - try { - Method guiMethod = getClass().getMethod("getGUI", (Class[]) null); - hasGUI = (guiMethod.getDeclaringClass() != Layer.class); - } catch (Exception ex) { - hasGUI = getGUI() != null; - } - - return hasGUI; - } - - /** - * Gets the gui controls associated with the layer. This default - * implementation returns null indicating that the layer has no gui - * controls. - * - * @return java.awt.Component or null, null by default. - */ - public Component getGUI() { - return null; - } - - // ///////////////////////////////////////////////// - // InfoDisplay Handling Setup and Firing - - /** - * Adds a listener for InfoDisplayEvents. - * - * @param aInfoDisplayListener the listener to add - */ - public void addInfoDisplayListener(InfoDisplayListener aInfoDisplayListener) { - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.add(aInfoDisplayListener); - // } - } - - /** - * Removes an InfoDisplayListener from this Layer. - * - * @param aInfoDisplayListener the listener to remove - */ - public void removeInfoDisplayListener(InfoDisplayListener aInfoDisplayListener) { - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.remove(aInfoDisplayListener); - // } - } - - /** - * Sends a request to the InfoDisplayListener to show the information in the - * InfoDisplay event on an single line display facility. - * - * @param evt the InfoDisplay event carrying the string. - */ - public void fireRequestInfoLine(InfoDisplayEvent evt) { - // synchronized (IDListeners) { // //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestInfoLine(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplay listener to display the information on - * an single line display facility. The InfoDisplayEvent is created inside - * this function. - * - * @param infoLine the string to put in the InfoDisplayEvent. - */ - public void fireRequestInfoLine(String infoLine) { - fireRequestInfoLine(new InfoDisplayEvent(this, infoLine)); - } - - /** - * Sends a request to the InfoDisplay listener to display the information on - * an single line display facility at preferred location. The - * InfoDisplayEvent is created inside this function. - * - * @param infoLine the string to put in the InfoDisplayEvent. - * @param loc the index of a preferred location, starting at 0. - */ - public void fireRequestInfoLine(String infoLine, int loc) { - fireRequestInfoLine(new InfoDisplayEvent(this, infoLine, loc)); - } - - /** - * Sends a request to the InfoDisplay listener to display the information in - * the InfoDisplay event in a Browser. - * - * @param evt the InfoDisplayEvent holding the contents to put in the - * Browser. - */ - public void fireRequestBrowserContent(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestBrowserContent(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display the information in - * a Browser. The InfoDisplayEvent is created here holding the - * browserContent - * - * @param browserContent the contents to put in the Browser. - */ - public void fireRequestBrowserContent(String browserContent) { - fireRequestBrowserContent(new InfoDisplayEvent(this, browserContent)); - } - - /** - * Sends a request to the InfoDisplayListener to display a URL given in the - * InfoDisplay event in a Browser. - * - * @param evt the InfoDisplayEvent holding the url location to give to the - * Browser. - */ - public void fireRequestURL(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestURL(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display a URL in a browser. - * The InfoDisplayEvent is created here, and the URL location is put inside - * it. - * - * @param url the url location to give to the Browser. - */ - public void fireRequestURL(String url) { - fireRequestURL(new InfoDisplayEvent(this, url)); - } - - /** - * Sends a request to the InfoDisplayListener to show a specific cursor over - * its component area. - * - * @param cursor the cursor to use. - */ - public void fireRequestCursor(java.awt.Cursor cursor) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestCursor(cursor); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to put the information in the - * InfoDisplay event in a dialog window. - * - * @param evt the InfoDisplayEvent holding the message to put into the - * dialog window. - */ - public void fireRequestMessage(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestMessage(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display the information in - * a dialog window. The InfoDisplayEvent is created here, and the URL - * location is put inside it. - * - * @param message the message to put in the dialog window. - */ - public void fireRequestMessage(String message) { - fireRequestMessage(new InfoDisplayEvent(this, message)); - } - - /** - * Request to show the tool tips on the map. - * - * @param tip string to display. - */ - public void fireRequestToolTip(String tip) { - fireRequestToolTip(new InfoDisplayEvent(this, tip)); - } - - /** - * Request to hide the tool tips on the map. - */ - public void fireHideToolTip() { - fireRequestToolTip((InfoDisplayEvent) null); - } - - /** - * Fire off a Tool Tip request to the InfoDisplayListeners. If the - * InfoDisplayEvent is null, then a requestHideToolTip will be fired. - */ - public void fireRequestToolTip(InfoDisplayEvent event) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - if (event != null) { - listener.requestShowToolTip(event); - } else { - listener.requestHideToolTip(); - } - } - // } - } - - // ///////////////////////////////////////////////// - // LayerStatus Handling Setup and Firing - - /** - * Adds a listener for LayerStatusEvents. - * - * @param aLayerStatusListener LayerStatusListener - */ - public void addLayerStatusListener(LayerStatusListener aLayerStatusListener) { - // synchronized (lsListeners) { //2012.06.15 TAW - lsListeners.add(aLayerStatusListener); - // } - } - - /** - * Removes a LayerStatusListene from this Layer. - * - * @param aLayerStatusListener the listener to remove - */ - public void removeLayerStatusListener(LayerStatusListener aLayerStatusListener) { - // synchronized (lsListeners) { //2012.06.15 TAW - lsListeners.remove(aLayerStatusListener); - // } - } - - /** - * Sends a status update to the LayerStatusListener. - * - * @param evt LayerStatusEvent - */ - public void fireStatusUpdate(LayerStatusEvent evt) { - // synchronized (lsListeners) { //2012.06.15 TAW - // AWTAvailable conditional removed, not used, not useful. - for (LayerStatusListener listener : lsListeners) { - listener.updateLayerStatus(evt); - } - // } - } - - /** - * Sends a status update to the LayerStatusListener. - * - * @param status the new status - */ - public void fireStatusUpdate(int status) { - fireStatusUpdate(new LayerStatusEvent(this, status)); - } - - /** - * Repaint the layer. If you are using BufferedMapBean for your application, - * WE STRONGLY RECOMMEND THAT YOU DO NOT OVERRIDE THIS METHOD. This method - * marks the layer buffer so that it will be refreshed. If you override this - * method, and don't call super.repaint(), the layers will not be repainted. - */ - public void repaint(long tm, int x, int y, int width, int height) { - readyToPaint.set(true); - Component p = getParent(); - if (p instanceof MapBean) { - ((MapBean) p).setBufferDirty(true); - if (Debug.debugging("basic")) { - Debug.output(getName() + "|Layer: repaint(tm=" + tm + ", x=" + x + ", y=" + y + ", width=" + width - + ", height=" + height + ")"); - } - - // How dangerous is this? Let the MapBean manage the - // repaint call? Seems to work OK, and lets the buffered - // MapBeans work better when they are embedded in other - // components. It's this call here that makes the - // BufferedLayer work right. - - // This repaint request has been changed to call a - // specific - // method on the MapBean, which includes the layer making - // the request. This is a hook for a policy object in the - // MapBean to make a decision on whether to honor the - // request, or to handle it in a different way if the - // environment dictates that should happen. - - // ((MapBean)p).repaint(); to -> - ((MapBean) p).repaint(this); - } else if (p != null) { - p.repaint(tm, x, y, width, height); - } else { - super.repaint(tm, x, y, width, height); - } - } - - /** - * This method is here to provide a default action for Layers as they act as - * a ProjectionPainter. Normally, ProjectionPainters are expected to receive - * the projection, gather/create OMGraphics that apply to the projection, - * and render them into the Graphics provided. This is supposed to be done - * in the same thread that calls this function, so the caller knows that - * when this method returns, everything that the ProjectionPainter needed to - * do is complete. - *

- * If the layer doesn't override this method, then the paint(Graphics) - * method will be called. - * - * @param proj Projection of the map. - * @param g java.awt.Graphics to draw into. - */ - public void renderDataForProjection(Projection proj, Graphics g) { - if (isProjectionOK(proj)) { - paint(g); - } - } - - /** - * Method that responds whether the Layer should render on the map, given a - * particular projection. The method currently just tests the projection's - * scale against the min and max values set on the layer. - * - * @param proj The projection to test against. - * @return true if OK. - */ - public boolean isProjectionOK(Projection proj) { - return (proj != null && proj.getScale() >= minScale && proj.getScale() <= maxScale); - } - - /** - * This method is called when the layer is added to the MapBean - * - * @param cont Container - */ - public void added(Container cont) { - } - - /** - * This method is called after the layer is removed from the MapBean and - * when the projection changes. We recommend that Layers override this - * method and nullify memory-intensive variables. - * - * @param cont Container - */ - public void removed(Container cont) { - } - - /** - * Method called when layer detects that it has been removed from - * MapHandler, assumes it's being thrown away. Use this method to let go of - * everything and to make any calls necessary to remove from listener lists - * that might not get picked up via MapHandler calls. - */ - public void dispose() { - clearListeners(); - if (attributes != null) { - attributes.clear(); - } - removed(null); - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - protected ListenerSupport localHackList; - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. Set to false to test. - */ - protected boolean doHack = true; - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void setVisible(boolean show) { - super.setVisible(show); - if (doHack && !show) { - notifyHideHack(); - } - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void addComponentListener(ComponentListener cl) { - super.addComponentListener(cl); - if (localHackList == null) { - localHackList = new ListenerSupport(this); - } - localHackList.add(cl); - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void removeComponentListener(ComponentListener cl) { - super.removeComponentListener(cl); - if (localHackList != null) { - localHackList.remove(cl); - } - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void notifyHideHack() { - if (localHackList == null) { - return; - } - - ComponentEvent ce = new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); - - for (ComponentListener listener : localHackList) { - listener.componentHidden(ce); - } - } - - /** - * Set whether the Layer should be added to the BeanContext. - */ - public void setAddToBeanContext(boolean set) { - addToBeanContext = set; - } - - /** - * Set whether the Layer should be added to the BeanContext. - */ - public boolean getAddToBeanContext() { - return addToBeanContext; - } - - /** - * Mark the layer as one that should be considered a background layer. What - * that means is up to the MapBean or application. - */ - public void setAddAsBackground(boolean set) { - addAsBackground = set; - } - - /** - * Check to see if the layer is marked as one that should be considered a - * background layer. What that means is up to the MapBean or application. - * - * @return true if layer is a background layer, meaning that it should be - * dropped to the bottom of the map and incorporated into a - * background layer image buffer if one is available. - */ - public boolean getAddAsBackground() { - return addAsBackground; - } - - /** - * @return the readyToPaint - */ - public boolean isReadyToPaint() { - return readyToPaint.get(); - } - - /** - * @param readyToPaint the readyToPaint to set - */ - public void setReadyToPaint(boolean readyToPaint) { - this.readyToPaint.set(readyToPaint); - } - - /** - * Mark the layer as removable, or one that can be deleted from the - * application. What that means is up to the LayerHandler or other - * application components. - */ - public void setRemovable(boolean set) { - removable = set; - } - - /** - * Check to see if the layer is marked as one that can be removed from an - * application. - * - * @return true if layer should be allowed to be deleted. - */ - public boolean isRemovable() { - return removable; - } - - /** - * Check to see if the removable layer can be removed now. - * - * @return true if layer should be allowed to be deleted. - */ - public boolean removeConfirmed() { - return true; - } - - /** - * This is the method that your layer can use to find other objects within - * the MapHandler (BeanContext). This method gets called when the Layer gets - * added to the MapHandler, or when another object gets added to the - * MapHandler after the Layer is a member. If the LayerHandler creates the - * Layer from properties, the LayerHandler will add the Layer to the - * BeanContext if Layer.addToBeanContext is true. It is false by default. - * - * For Layers, this method doesn't do anything by default. If you need your - * layer to get ahold of another object, then you can use the Iterator to go - * through the objects to look for the one you need. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * This method is called by the findAndInit(Iterator) method, once for every - * object inside the iterator. It's here to allow subclasses a way to - * receive objects and still let the super classes have a shot at the - * object. So, you can override this method can call super.findAndInit(obj), - * or override the findAndInit(Iterator) method and call - * super.findAndInit(obj). Whatever. - */ - public void findAndInit(Object obj) { - } - - /** - * BeanContextMembershipListener method. Called when a new object is added - * to the BeanContext of this object. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * This is the method that does the opposite as the findAndInit(Object). - * Lets you call super classes with objects that need to be removed. At this - * level, if the layer detects that it is being removed from the MapHandler, - * it calls dispose on itself. - */ - public void findAndUndo(Object obj) { - if (obj == this) { - this.dispose(); - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Gets an iterator from the - * BeanContext to call findAndInit() over. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - connectToBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** - * Layer method to just connect to the BeanContext, without grabbing the - * iterator as in setBeanContext(). Good for protected sub-layers where you - * want to optimize the calling of the findAndInit() method over them. - */ - public void connectToBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - } - } - - /** - * Layer method to just disconnect from the BeanContext, without grabbing - * the iterator as in setBeanContext(). Good for protected sub-layers where - * you want to optimize the calling of the findAndUndo() method over them. - */ - public void disconnectFromBeanContext() throws PropertyVetoException { - - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.removeBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(null); - } - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to add a listener to this object's property. This listener wants to have - * the right to veto a property change. - */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to remove a listener to this object's property. The listener has the - * power to veto property changes. - */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) throws PropertyVetoException { - super.fireVetoableChange(name, oldValue, newValue); - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - public void clearListeners() { - if (localHackList != null) { - localHackList.clear(); - } - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.clear(); - // } - // synchronized (lsListeners) { - lsListeners.clear(); - // } - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.removeBeanContextMembershipListener(this); - } - } - - protected void finalize() { - if (Debug.debugging("gc")) { - Debug.output("Layer |" + getName() + " |: getting GC'd"); - } - } - - /** - * Fire a component event to the Layer component listeners, with the palette - * as the component, letting them know if it's visible or not. - */ - public void firePaletteEvent(ComponentEvent event) { - if (localHackList == null) { - return; - } - - palette = (Container) event.getSource(); - int eventType = event.getID(); - for (ComponentListener listener : localHackList) { - if (eventType == ComponentEvent.COMPONENT_HIDDEN) { - listener.componentHidden(event); - } else if (eventType == ComponentEvent.COMPONENT_SHOWN) { - listener.componentShown(event); - } - } - - if (eventType == ComponentEvent.COMPONENT_HIDDEN) { - palette = null; - } - } - - /** - * Return the JDialog, or JInternalFrame, that serves as the palette for the - * layer. May be null. - */ - public Container getPalette() { - return palette; - } - - /** - * Called when something about the layer has changed that would require the - * palette to be reconfigured. Will cause getGUI() to be called again. You - * should take steps before calling this method to make sure that the - * getGUI() method is ready to recreate the palette components from scratch - * if needed. - */ - protected void resetPalette() { - java.awt.Container pal = getPalette(); - boolean putUp = false; - if (pal != null && pal.isVisible()) { - putUp = true; - setPaletteVisible(false); - } - - if (putUp) { - setPaletteVisible(true); - } - } - - /** - * Make the palette visible or not, destroy if invisible. - */ - public void setPaletteVisible(boolean visible) { - if (visible) { - showPalette(); - } else { - hidePalette(); - } - } - - /** - * Set the WindowSupport object handling the palette. - */ - public void setWindowSupport(WindowSupport ws) { - windowSupport = ws; - } - - /** - * Get the WindowSupport object handling the palette. - */ - public WindowSupport getWindowSupport() { - return windowSupport; - } - - /** - * Callback method to override how window support is created. - * - * @return WindowSupport object for layer palette. - */ - protected WindowSupport createWindowSupport() { - return new ScrollPaneWindowSupport(getGUI(), getName()); - } - - /** - * Make the palette visible. Will automatically determine if we're running - * in an applet environment and will use a JInternalFrame over a JFrame if - * necessary. - */ - public void showPalette() { - - WindowSupport ws = getWindowSupport(); - if (ws == null) { - ws = createWindowSupport(); - paletteListener = new ComponentAdapter() { - public void componentShown(ComponentEvent e) { - firePaletteEvent(e); - } - - public void componentHidden(ComponentEvent e) { - firePaletteEvent(e); - } - }; - setWindowSupport(ws); - } else { - ws.setTitle(getName()); - ws.setContent(getGUI()); - } - - if (ws != null) { - MapHandler mh = (MapHandler) getBeanContext(); - // Window frame = null; // java 5 incompatibility - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - - if (frame == null) { - MapBean mapBean = (MapBean) mh.get("com.bbn.openmap.MapBean"); - if (mapBean == null) { - Debug.message("layer", "Layer.showPalette: Warning...mapBean = null"); - } else { - try { - java.awt.Component parent = mapBean.getParent(); - while (parent.getParent() != null && !(parent instanceof java.awt.Window)) { - parent = parent.getParent(); - } - - /* java 5 incompatibility */ - /* - * if (parent instanceof java.awt.Window) { frame = - * (java.awt.Window) parent; } - */ - - if (parent instanceof java.awt.Frame) { - frame = (java.awt.Frame) parent; - } - - } catch (Exception e) { - e.printStackTrace(); - } // ignore any problems here - } - } - } - - if (paletteListener != null) { - ws.addComponentListener(paletteListener); - } - ws.displayInWindow(frame); - } - } - - /** - * Hide the layer's palette. - */ - public void hidePalette() { - WindowSupport ws = getWindowSupport(); - if (ws != null) { - ws.killWindow(); - } - } - - /** - * The default actionPerformed method for Layer. Make sure you call - * super.actionPerformed if you care about receiving palette show/hide - * commands. This method is also set up to receive the DisplayPropertiesCmd, - * and will bring up the Inspector for the layer. - */ - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - if (command == DisplayPaletteCmd) { - if (Debug.debugging("layer")) { - Debug.output(getName() + " displaying palette"); - } - showPalette(); - } else if (command == HidePaletteCmd) { - if (Debug.debugging("layer")) { - Debug.output(getName() + " hiding palette"); - } - hidePalette(); - } else if (command == DisplayPropertiesCmd) { - Inspector inspector = new Inspector(); - inspector.inspectPropertyConsumer(this); - } - } - - /** - * Handle Serialization a little bit better, replacing the I18n and - * BeanContextChildSupport. - * - * @param in - * @throws IOException - * @throws ClassNotFoundException - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - i18n = Environment.getI18n(); - beanContextChildSupport = new BeanContextChildSupport(this); - } - - public Icon getIcon() { - return icon; - } - - public void setIcon(Icon icon) { - this.icon = icon; - } - - public boolean isAutoPalette() { - return autoPalette; - } - - public void setAutoPalette(boolean autoPalette) { - this.autoPalette = autoPalette; - } - - public float getMaxScale() { - return maxScale; - } - - public void setMaxScale(float maxScale) { - this.maxScale = maxScale; - } - - public float getMinScale() { - return minScale; - } - - public void setMinScale(float minScale) { - this.minScale = minScale; - } - - public void putAttribute(Object key, Object value) { - if (attributes == null) { - attributes = new Hashtable(); - } - attributes.put(key, value); - } - - public Object getAttribute(Object key) { - Object ret = null; - if (key != null && attributes != null) { - ret = attributes.get(key); - } - return ret; - } - - public GeoCoordTransformation getCoordTransform() { - return coordTransform; - } - - public void setCoordTransform(GeoCoordTransformation coordTranslator) { - this.coordTransform = coordTranslator; - } - - /** - * The dataPathPrefix layer attribute lets you append a path to a relative - * path at runtime. This method tells the layer to check for that layer - * attribute for such a prefix path, and prepends it to the given string - * separating them with a '/'. - * - * @param fileName to prepend the attribute to - */ - protected String prependDataPathPrefix(String fileName) { - String dataPathPrefix = (String) getAttribute(Layer.DataPathPrefixProperty); - if (dataPathPrefix != null && dataPathPrefix.length() > 0) { - fileName = dataPathPrefix + "/" + fileName; - } - return fileName; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/LayerHandler.java b/src/core/src/main/java/com/bbn/openmap/LayerHandler.java deleted file mode 100644 index a6f6dce2f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/LayerHandler.java +++ /dev/null @@ -1,1119 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/LayerHandler.java,v $ -// $RCSfile: LayerHandler.java,v $ -// $Revision: 1.16 $ -// $Date: 2006/08/09 21:08:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.LayerConfigurationListener; -import com.bbn.openmap.event.LayerConfigurationListenerSupport; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.LayerSupport; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The LayerHandler is a component that keeps track of all Layers for the - * MapBean, whether or not they are currently part of the map or not. It is able - * to dynamically add and remove layers from the list of available layers. - * Whether a layer is added to the MapBean depends on the visibility setting of - * the layer. If Layer.isVisible() is true, the layer will be added to the - * MapBean. There are methods within the LayerHandler that let you change the - * visibility setting of a layer. - *

- * The LayerHandler is able to take a Properties object, and create layers that - * are defined within it. The key property is "layers", which may or may not - * have a prefix for it. If that property does have a prefix (prefix.layers, - * i.e. openmap.layers), then that prefix has to be known and passed in to the - * constructor or init method. This layers property should fit the general - * openmap marker list paradigm, where the marker names are listed in a space - * separated list, and then each marker name is used as a prefix for the - * properties for a particular layer. As a minimum, each layer needs to have the - * class and prettyName properties defined. The class property should define the - * class name to use for the layer, and the prettyName property needs to be a - * name for the layer to be used in the GUI. Any other property that the - * particular layer can use should be listed in the Properties, with the - * applicable marker name as a prefix. Each layer should have its available - * properties defined in its documentation. For example: - *

- *

- * - *

- *           <p/>
- *             openmap.layers=marker1 marker2 (etc)
- *             marker1.class=com.bbn.openmap.layer.GraticuleLayer
- *             marker1.prettyName=Graticule Layer
- *             # false is default
- *             marker1.addToBeanContext=false
- *           <p/>
- *             marker2.class=com.bbn.openmap.layer.shape.ShapeLayer
- *             marker2.prettyName=Political Boundaries
- *             marker2.shapeFile=pathToShapeFile
- *             marker2.spatialIndex=pathToSpatialIndexFile
- *             marker2.lineColor=FFFFFFFF
- *             marker2.fillColor=FFFF0000
- *           <p/>
- * 
- * - *

- * The LayerHandler is a SoloMapComponent, which means that for a particular - * map, there should only be one of them. When a LayerHandler is added to a - * BeanContext, it will look for a MapBean to connect to itself as a - * LayerListener so that the MapBean will receive LayerEvents - this is the - * mechanism that adds and removes layers on the map. If more than one MapBean - * is added to the BeanContext, then the last MapBean added will be added as a - * LayerListener, with any prior MapBeans added as a LayerListener removed from - * the LayerHandler. The MapHandler controls the behavior of multiple - * SoloMapComponent addition to the BeanContext. - */ -public class LayerHandler extends OMComponent implements SoloMapComponent, Serializable { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.LayerHandler"); - - /** - * Property for space separated layers. If a prefix is needed, just use the - * methods that let you use the prefix - don't worry about the period, it - * will be added automatically. - */ - public static final String layersProperty = "layers"; - /** - * Property for space separated layers to be displayed at startup. If a - * prefix is needed, just use the methods that let you use the prefix - - * don't worry about the period, it will be added automatically. - */ - public static final String startUpLayersProperty = "startUpLayers"; - /** - * Flag to set synchronous threading on the LayerHandler, telling it to - * react to layer order changes and layer visibility requests within the - * calling thread. By default, this action is true. Setting it to false may - * eliminate pauses in GUI reactions by off-loading work done by layers - * being added to the MapBean, but there have been reports that the - * asynchronous nature of the threading queue may be causing an unexpected - * state in layer order and/or availability under certain intense layer - * management conditions (created by automated processes, for example). - */ - public static final String SynchronousThreadingProperty = "synchronousThreading"; - /** - * The object holding on to all LayerListeners interested in the layer - * arrangement and availability. Not expected to be null. - */ - protected transient LayerSupport listeners = new LayerSupport(this); - /** - * LayerConfigurationListenerSupport for LayerConfigurationListeners. - */ - protected transient LayerConfigurationListenerSupport layerConfigListeners = new LayerConfigurationListenerSupport( - this); - /** - * The list of all layers, even the ones that are not part of the map. - */ - protected List allLayers = new ArrayList(); - /** - * This handle is only here to keep it appraised of layer prefix names. - */ - protected PropertyHandler propertyHandler; - - /** - * If you use this constructor, the LayerHandler expects that the layers - * will be created and added later, either by addLayer() or init(). - */ - public LayerHandler() { - } - - /** - * Start the LayerHandler, and have it create all the layers as defined in a - * properties file. - * - * @param props properties as defined in an openmap.properties file. - */ - public LayerHandler(Properties props) { - init(null, props); - } - - /** - * Start the LayerHandler, and have it create all the layers as defined in a - * properties file. - * - * @param prefix the prefix for the layers and startUpLayers properties, as - * if they are listed as prefix.layers, and prefix.startUpLayers. - * @param props properties as defined in an openmap.properties file. - */ - public LayerHandler(String prefix, Properties props) { - init(prefix, props); - } - - /** - * Start the LayerHandler with configured layers. - */ - public LayerHandler(Layer[] layers) { - init(layers); - } - - /** - * Extension of the OMComponent. If the LayerHandler is created by the - * ComponentFactory (via the PropertyHandler), this method will be called - * automatically. For the OpenMap applications, this method is rigged to - * handle the openmap.layers property by calling init("openmap", props). If - * you are using the LayerHandler in a different setting, then you might - * want to just call init() directly, or extend this class and have - * setProperties do what you want. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - // Whoa! We used to replace the prefix provided to this method with - // 'openmap', - // AKA Environment.OpenMapPrefix, but that seems rude and hackish. We're - // going to have the getLayers(prefix, props) method use the prefix - // passed in, and if the layerHandler prefix.layers can't be found, - // we'll revert to looking for the openmap.layers property, just to be - // backward compatible. - // init(Environment.OpenMapPrefix, props); - init(prefix, props); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a - * properties object. The properties should be created from an - * openmap.properties file. - * - * @param prefix the prefix to use for the layers and startUpLayers - * properties. - * @param props properties as defined in an openmap.properties file. - */ - public void init(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - init(getLayers(prefix, props)); - - getListeners().setSynchronous(PropUtils.booleanFromProperties(props, prefix + SynchronousThreadingProperty, - getListeners().isSynchronous())); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a URL - * containing an openmap.properties file. - * - * @param url a url for a properties file. - */ - public void init(java.net.URL url) { - init(null, url); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a URL - * containing an openmap.properties file. - * - * @param prefix the prefix to use for the layers and startUpLayers - * properties. - * @param url a url for a properties file. - */ - public void init(String prefix, java.net.URL url) { - try { - java.io.InputStream in = url.openStream(); - Properties props = new Properties(); - props.load(in); - init(getLayers(prefix, props)); - } catch (java.net.MalformedURLException murle) { - logger.warning("LayerHandler.init(URL): " + url + " is not a valid URL"); - } catch (java.io.IOException e) { - logger.warning("LayerHandler.init(URL): Caught an IOException"); - } - } - - /** - * Initialize from an array of layers. This will cause the LayerListeners, - * if they exist, to update themselves with the current list of layers. This - * will check to add layers to the MapHandler. - * - * @param layers the initial array of layers. - */ - public void init(Layer[] layers) { - init(Arrays.asList(layers)); - } - - public void init(List layers) { - // Should get rid of the old layers properly, holding onto - // non-removeable layers. - removeAll(); - - // OK, we need to check the allLayers array, because at this point it - // could still be holding non-removable layers. If we just replace them, - // we've broken the contract of non-removal. Move the non-removable - // layers to the bottom and put the new layers on top. We also need to - // check to make sure that any duplicate layers on either list are - // parsed down to one layer. We use the Vector.contains() method for - // that check. - List currentLayers = getLayerList(); - - if (layers == null) { - layers = new ArrayList(); - } - - // Go through the list of old-non-removable layers, if they are not on - // the new layer list, add them to the end. - for (Layer layer : currentLayers) { - if (!layers.contains(layer) || !layer.isRemovable()) { - layers.add(layer); - } - } - - setLayerList(layers); - - // This should work for layers being reloaded from the PropertyHandler, - // it's better than doing it in the getLayers(...) method below - // (getLayers() is called before init()). For the - // initial LayerHandler construction and Layer creation in an - // application, the BeanContext should be null at this point, so this - // method call will do nothing. But for resetting the layers with new - // ones, they will get dumped into the BeanContext/MapHandler. - addLayersToBeanContext(layers); - } - - public void setPropertyHandler(PropertyHandler ph) { - propertyHandler = ph; - } - - public PropertyHandler getPropertyHandler() { - return propertyHandler; - } - - /** - * This is the method that gets used to parse the layer properties from an - * openmap.properties file, where the layer marker names are listed under a - * layers property, and each layer is then represented by a marker.class - * property, and a maker.prettyName property. - * - * @param p properties containing layers property, the startupLayers - * property listing the layers to make visible immediately, and - * the layer properties as well. - * @return Layer[] of layers created from the properties. - */ - protected Layer[] getLayers(Properties p) { - return getLayers(null, p); - } - - /** - * This is the method that gets used to parse the layer properties from an - * openmap.properties file, where the layer marker names are listed under a - * prefix.layers property, and each layer is then represented by a - * marker.class property, and a maker.prettyName property. - * - * @param prefix the prefix to use to use for the layer list (layers) - * property and the startUpLayers property. If it is not null, - * this will cause the method to look for prefix.layers and - * prefix.startUpLayers. - * @param p the properties to build the layers from. - * @return Layer[] - */ - protected Layer[] getLayers(String prefix, Properties p) { - logger.fine("Getting new layers from properties..."); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String layersValueString = p.getProperty(prefix + layersProperty); - - String startupLayersValueString = p.getProperty(prefix + startUpLayersProperty); - - if (layersValueString == null) { - layersValueString = p - .getProperty(PropUtils.getScopedPropertyPrefix(Environment.OpenMapPrefix) + layersProperty); - } - - if (startupLayersValueString == null) { - startupLayersValueString = p - .getProperty(PropUtils.getScopedPropertyPrefix(Environment.OpenMapPrefix) + startUpLayersProperty); - } - - List startuplayers = PropUtils.parseSpacedMarkers(startupLayersValueString); - List layersValue = PropUtils.parseSpacedMarkers(layersValueString); - - if (startuplayers.isEmpty()) { - logger.info("No layers on startup list"); - } - - if (layersValue.isEmpty()) { - logger.info("No property \"" + layersProperty + "\" found in properties."); - return new Layer[0]; - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer markers found = " + layersValue); - } - } - - Layer[] layers = getLayers(layersValue, startuplayers, p); - - // You don't want to call addLayersToBeanContext here, it sets up a - // cycle. The layers are not yet set in the LayerHandler, so the - // LayerHandle won't know to ignore them when they show up in - // findAndInit(). The one thing this call did, however, is get the - // BeanContext to the layers before the startup layers were added to the - // MapBean. It's possible that without this call, layers that build - // their OMGraphicLists once may not have the BeanContext resources they - // need in order to build that list. - - // addLayersToBeanContext(layers); - - return layers; - } - - /** - * A static method that lets you pass in a Properties object, along with two - * Vectors of strings, each Vector representing marker names for layers - * contained in the Properties. - *

- * If a PlugIn is listed in the properties, the LayerHandler will create a - * PlugInLayer for it and set the PlugIn in that layer. - * - * @param layerList Vector of marker names to use to inspect the properties - * with. - * @param visibleLayerList Vector of marker names representing the layers - * that should initially be set to visible when created, so that - * those layers are initially added to the map. - * @param p Properties object containing the layers properties. - * @return Layer[] - */ - public static Layer[] getLayers(List layerList, List visibleLayerList, Properties p) { - - int nLayerNames = layerList.size(); - Vector layers = new Vector(nLayerNames); - - for (String layerName : layerList) { - String classProperty = layerName + ".class"; - String className = p.getProperty(classProperty); - if (className == null) { - logger.info( - "Failed to locate property \"" + classProperty + "\"\n Skipping layer \"" + layerName + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, layerName, p); - Layer l; - - if (obj instanceof Layer) { - l = (Layer) obj; - } else { - logger.info("Skipped \"" + layerName + "\" " + (obj == null ? " - unable to create " - : ", type " + obj.getClass().getName() + " is not a layer or plugin")); - continue; - } - - // Figure out of the layer is on the startup list, - // and make it visible if it is... - l.setVisible(visibleLayerList.contains(layerName)); - // The ComponentFactory does this now - // l.setProperties(layerName, p); - - layers.addElement(l); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + l.getName() + (l.isVisible() ? " is visible" : " is not visible")); - } - } - - int nLayers = layers.size(); - if (nLayers == 0) { - return new Layer[0]; - } else { - Layer[] value = new Layer[nLayers]; - layers.copyInto(value); - return value; - } - } - - /** - * Add a LayerListener to the LayerHandler, in order to be told about layers - * that need to be added to the map. The new LayerListener will receive two - * events, one telling it all the layers available, and one telling it which - * layers are active (visible). - * - * @param ll LayerListener, usually the MapBean or other GUI components - * interested in providing layer controls. - */ - public void addLayerListener(LayerListener ll) { - logger.fine("adding layer listener"); - listeners.add(ll); - // Usually, the listeners are interested in one type of event - // or the other. So fire both, and let the listener hash it - // out. - ll.setLayers(new LayerEvent(this, LayerEvent.ALL, getLayers())); - ll.setLayers(new LayerEvent(this, LayerEvent.ADD, getMapLayers())); - } - - /** - * Add a LayerConfigurationListener, so a component can make adjustments to - * new layer configurations before they get sent to the map. - * - * @param lcl LayerConfigurationListener - */ - public void addLayerConfigurationListener(LayerConfigurationListener lcl) { - layerConfigListeners.add(lcl); - } - - /** - * Add a LayerListener to the LayerHandler, in order to be told about layers - * that need to be added to the map. - * - * @param ll LayerListener, usually the MapBean or other GUI components - * interested in providing layer controls. - */ - public void removeLayerListener(LayerListener ll) { - if (listeners != null) { - listeners.remove(ll); - } - } - - /** - * Remove a LayerConfigurationListener. - * - * @param lcl LayerConfigurationListener - */ - public void removeLayerConfigurationListener(LayerConfigurationListener lcl) { - layerConfigListeners.remove(lcl); - } - - /** - * Set all the layers held by the LayerHandler. The visible layers will be - * sent to listeners interested in visible layers (LayerEvent.REPLACE), and - * the list of all layers will be sent to listeners interested in - * LayerEvent.ALL events. Calling this method from other GUI components - * could break the non-removable contract that previous layers had. The - * previous layers aren't checked against this list to insure that - * non-removable layers are still on this list and visible. GUI components - * that may call this need to set up their GUI controls to not allow - * non-removable layers to be eliminated from the application. - *

- * This method will not add the layers to the MapHandler, so you can call - * this if you know the layers are already in the MapHandler or don't need - * to be. If you want layers to be added to the MapHandler (if the - * LayerHandler knows about it), call init(Layer[]) instead. - *

- * Also, this method will disregard layer non-removable status for any - * layers currently held, and will simply replace all layers with the ones - * provided. If you want the non-removable flag to be adhered to, call - * init(Layers[]). - * - * @param layers Layer array of all the layers to be held by the - * LayerHandler. - */ - public synchronized void setLayers(Layer[] layers) { - setLayerList(Arrays.asList(layers)); - } - - public synchronized void setLayerList(List layers) { - List localAllLayers = organizeBackgroundLayers(layers); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("setting layers: " + getLayerNamesFromArray(layers)); - } - - // I think this is where we need to make the call to - // LayerConfigurationListeners to check the status of the layer cake, so - // they can make appropriate changes before the LayerListeners get da - // layers. - - List checkedList = layerConfigListeners.checkLayerConfiguration(new ArrayList(localAllLayers)); - if (checkedList != null) { - localAllLayers = organizeBackgroundLayers(checkedList); - } - - allLayers = localAllLayers; - - getListeners().pushLayerEvent(LayerEvent.ALL, getLayers()); - getListeners().pushLayerEvent(LayerEvent.REPLACE, getMapLayers()); - } - - protected String getLayerNamesFromArray(List lArray) { - StringBuilder buf = new StringBuilder(); - if (lArray != null) { - for (Layer l : lArray) { - if (buf.length() > 0) { - buf.append(" "); - } - buf.append(l.getName()); - } - } - return buf.toString(); - } - - /** - * Checks to see if there are background layers on top of foreground layers. - * - * @param layers - * @return true if background layers need to be pushed down - */ - protected boolean isForegroundUnderBackgroundLayer(List layers) { - boolean foundBackgroundLayer = false; - if (layers != null) { - for (Layer layer : layers) { - if (layer != null) { - if (layer.getAddAsBackground()) { - foundBackgroundLayer = true; - } else if (foundBackgroundLayer) { - return true; - } - } - } - } - - return false; - } - - /** - * Does the check to see of foreground layers are below background layers, - * and then iterates through the Layer[] switching layers around until they - * are in the appropriate order. - * - * @param layers - * @return Layer[] of layers with background layers moved to back. - */ - protected List organizeBackgroundLayers(List layers) { - if (isForegroundUnderBackgroundLayer(layers)) { - - List fLayers = new ArrayList(layers.size()); - List bLayers = new ArrayList(layers.size()); - - for (Layer layer : layers) { - if (layer != null) { - if (layer.getAddAsBackground()) { - bLayers.add(layer); - } else { - fLayers.add(layer); - } - } - } - - // Append all background layers behind foreground layers. - fLayers.addAll(bLayers); - return fLayers; - - } else { - return layers; - } - } - - /** - * Returns the object responsible for holding on to objects listening to - * layer changes. - * - * @return LayerSupport containing pointers to all objects interested in the - * status (order, visibility) of the available layers. - */ - protected LayerSupport getListeners() { - return listeners; - } - - /** - * If you are futzing with the layer visibility outside the purview of the - * LayerHandler (not using the turnLayerOn() methods) then you can call this - * to get all the listeners using the current set of visible layers. - */ - public void setLayers() { - setLayerList(getLayerList()); - } - - /** - * Get a layer array, of potential layers that CAN be added to the map, not - * the ones that are active on the map. A new array is returned, containing - * the current layers. - * - * @return new Layer[] containing new layers. - */ - public synchronized Layer[] getLayers() { - List layers = getLayerList(); - return layers.toArray(new Layer[layers.size()]); - } - - /** - * Returns a copy of the List of all the available layers. - * - * @return List of Layers - */ - public synchronized List getLayerList() { - if (allLayers == null) { - return new ArrayList(); - } else { - return new ArrayList(allLayers); - } - } - - /** - * Get the layers that are currently part of the Map - the ones that are - * visible. - * - * @return an Layer[] of visible Layers. - */ - public Layer[] getMapLayers() { - - List activeLayers = new ArrayList(); - - for (Layer layer : getLayers()) { - if (layer != null && layer.isVisible()) { - activeLayers.add(layer); - } - } - - Layer[] cake = activeLayers.toArray(new Layer[activeLayers.size()]); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("providing map layers: " + getLayerNamesFromArray(activeLayers)); - } - - return cake; - } - - /** - * Move a layer to a certain position. Returns true if the layer exists in - * the LayerHandler, false if is doesn't. No action is taken if the layer - * isn't already added to the LayerHandler stack. If the position is 0 or - * less the layer is moved on top. If the position is greater or equal to - * the number of layers, the layer is moved to the bottom of the pile. - * - * @param layer the layer to move. - * @param toPosition the array index to place it, shifting the other layers - * up or down, depending on where the layer is originally. - * @return true if the layer is already contained in the LayerHandler, false - * if not. - */ - public boolean moveLayer(Layer layer, int toPosition) { - boolean found = getLayerList().contains(layer); - addLayer(layer, toPosition); - - return found; - } - - /** - * Add a layer to the bottom of the layer stack. If the layer is already - * part of the layer stack, nothing is done. - * - * @param layer the layer to add. - */ - public void addLayer(Layer layer) { - if (allLayers == null) { - addLayer(layer, 0); - return; - } - - if (!allLayers.contains(layer)) { - allLayers.add(layer); - } - } - - /** - * Add a layer to a certain position in the layer array. If the position is - * 0 or less, the layer is put up front (on top). If the position is greater - * than the length of the current array, the layer is put at the end, (on - * the bottom). A Layer can only be added once. If you add a layer that is - * already added to the LayerHandler, it will be moved to the requested - * position. - * - * @param layer the layer to add. - * @param position the array index to place it. - */ - @SuppressWarnings("unchecked") - public void addLayer(Layer layer, int position) { - // Working copy - List currentLayers = getLayerList(); - - // If it is already part of the list, we're going to move it to the new - // position. Remove it from the current position. If it's not on the - // list this call is a NO-OP. - currentLayers.remove(layer); - - if (position > allLayers.size()) { - currentLayers.add(layer); - } else { - if (position < 0) { - position = 0; - } - currentLayers.add(position, layer); - } - - if (propertyHandler != null) { - String pre = layer.getPropertyPrefix(); - if (pre != null && pre.length() > 0) { - propertyHandler.addUsedPrefix(pre); - } - } - - // Need to make this call before thinking about adding the Layer to the - // BeanContext, so when the Layer shows up in the findAndInit() method, - // it's already a part of the Layer list. One potential problem that may - // occur is that the Layer might not be ready to be added to the map and - // to other application components that get LayerEvents from the - // LayerHandler, and they will all know about the layer being in the - // stack after the setLayers() call. - setLayerList(currentLayers); - - // Add the layer to the BeanContext, if it wants to be and it's not - // already in a BeanContext. Thought about making the BC check look for - // the same BC as the LayerHandler is a part of, but it's probably - // better just to do a null check in case the Layer is a member of a - // more restricted BeanContext with limited access. - BeanContext bc = getBeanContext(); - if (bc != null && layer.getAddToBeanContext() && layer.getBeanContext() == null) { - bc.add(layer); - } - } - - /** - * Remove a layer from the list of potentials. - * - * @param layer to remove. - */ - public void removeLayer(Layer layer) { - if (layer != null && layer.isRemovable()) { - List currentLayers = getLayerList(); - currentLayers.remove(layer); - setLayerList(currentLayers); - } else { - if (layer != null) { - logger.warning("received command to remove " + layer.getName() - + ", which has been designated as *NOT* removeable"); - throw new com.bbn.openmap.util.HandleError( - "LayerHandler commanded to delete a layer (" + layer.getName() + ") that is not removeable"); - } - } - } - - /** - * Remove a layer from the list of potentials. - * - * @param index of layer in the layer array. Top-most is first. - */ - public void removeLayer(int index) { - List currentLayers = getLayerList(); - try { - currentLayers.remove(index); - setLayerList(currentLayers); - } catch (IndexOutOfBoundsException ioobe) { - // ignore it. - } - } - - public boolean hasLayer(Layer l) { - return getLayerList().contains(l); - } - - /** - * Remove all the layers (that are marked as removable). - */ - public void removeAll() { - List oldLayers = getLayerList(); - if (allLayers == null || allLayers.isEmpty()) { - return; - } - - BeanContext bc = getBeanContext(); - List nonRemoveableLayers = new ArrayList(); - - for (Layer layer : oldLayers) { - if (layer != null) { - if (layer.isRemovable()) { - turnLayerOn(false, layer); - layer.clearListeners(); - if (bc != null) { - // Remove the layer from the BeanContext - bc.remove(layer); - } - } else { - nonRemoveableLayers.add(layer); - } - } - } - - setLayerList(nonRemoveableLayers); - - // I know this is bad but it seems to work, forcing the - // memory from old, deleted layers to be freed. With such a - // drastic method call as removeAll, this should be OK. - System.gc(); - } - - /** - * The version that does the work. The other two functions do sanity checks. - * Calls setLayers(), and removes the layer from the BeanContext. - * - * @param currentLayers the current layers handled in the LayersMenu. - * @param index the validated index of the layer to remove. - */ - protected void removeLayer(Layer[] currentLayers, int index) { - Layer rLayer = currentLayers[index]; - - if (!rLayer.isRemovable()) { - logger.warning("received command to remove " + rLayer.getName() - + ", which has been designated as *NOT* removeable"); - return; - } - - rLayer.setVisible(false); - - Layer[] newLayers = new Layer[currentLayers.length - 1]; - System.arraycopy(currentLayers, 0, newLayers, 0, index); - System.arraycopy(currentLayers, index + 1, newLayers, index, currentLayers.length - index - 1); - - // Remove the layer to the BeanContext, if it wants to be. - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.remove(rLayer); - } - turnLayerOn(false, rLayer); - rLayer.clearListeners(); - rLayer = null; - - // Shouldn't call this, but it's the only thing that seems to - // make it work... - // if (Debug.debugging("helpgc")) { - // System.gc(); - // } - - setLayers(newLayers); - } - - /** - * Take a layer that the LayersMenu knows about, that may or may not be a - * part of the map, and change its visibility by adding/removing it from the - * MapBean. - * - * @param setting true to add layer to the map. - * @param index the index of the layer to turn on/off. - * @return true of index represented a layer, false if not or if something - * went wrong. - */ - public boolean turnLayerOn(boolean setting, int index) { - try { - return turnLayerOn(setting, getLayerList().get(index)); - } catch (ArrayIndexOutOfBoundsException aoobe) { - // Do nothing... - } catch (NullPointerException npe) { - // Do nothing... - } - return false; - } - - /** - * Take a layer that the LayersMenu knows about, that may or may not be a - * part of the map, and change its visibility by adding/removing it from the - * MapBean. If the layer is not found, it's added and the visibility depends - * on the setting parameter. - * - * @param setting true to add layer to the map. - * @param layer the layer to turn on. - * @return true if the layer was found, false if not or if something went - * wrong. - */ - public boolean turnLayerOn(boolean setting, Layer layer) { - - if ((setting && !layer.isVisible()) || (!setting && layer.isVisible())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("turning " + layer.getName() + (setting ? " on" : " off")); - } - - layer.setVisible(setting); - - List newList = layerConfigListeners.checkLayerConfiguration(getLayerList()); - if (newList != null) { - allLayers = organizeBackgroundLayers(newList); - } - - getListeners().pushLayerEvent(LayerEvent.REPLACE, getMapLayers()); - return true; - } - return false; - } - - /** - * Called from childrenAdded(), when a new component is added to the - * BeanContext, and from setBeanContext() when the LayerHandler is initially - * added to the BeanContext. This method takes the iterator provided when - * those methods are called, and looks for the objects that the LayerHandler - * is interested in, namely, the MapBean, the PropertyHandler, or any other - * LayerListeners. The LayerHandler handles multiple LayerListeners, and if - * one is found, it is added to the LayerListener list. If a PropertyHandler - * is found, then init() is called, effectively resetting the layers held by - * the LayerHandler. - * - * @param someObj an Object being added to the MapHandler/BeanContext. - */ - public void findAndInit(Object someObj) { - - if (someObj instanceof LayerListener) { - logger.fine("LayerHandler found a LayerListener."); - addLayerListener((LayerListener) someObj); - } - - if (someObj instanceof LayerConfigurationListener) { - logger.fine("LayerHandler found a LayerConfigurationListener."); - addLayerConfigurationListener((LayerConfigurationListener) someObj); - } - - if (someObj instanceof Layer) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerHandler found a Layer |" + ((Layer) someObj).getName() + "|" - + someObj.getClass().getName()); - } - if (!hasLayer((Layer) someObj)) { - addLayer((Layer) someObj, 0); - } - } - - if (someObj instanceof PropertyHandler) { - // Used to notify the PropertyHandler of used property - // prefix names. - setPropertyHandler((PropertyHandler) someObj); - } - } - - /** - * A BeanContextMembershipListener interface method, which is called when - * new objects are removed from the BeanContext. If a LayerListener or Layer - * is found on this list, it is removed from the list of LayerListeners. - * - * @param someObj an Object being removed from the MapHandler/BeanContext. - */ - public void findAndUndo(Object someObj) { - - if (someObj instanceof LayerListener) { - logger.fine("LayerListener object is being removed"); - removeLayerListener((LayerListener) someObj); - } - - if (someObj instanceof LayerConfigurationListener) { - logger.fine("LayerConfigurationListener is being removed."); - removeLayerConfigurationListener((LayerConfigurationListener) someObj); - } - - if (someObj instanceof Layer) { - removeLayer((Layer) someObj); - } - - if (someObj instanceof PropertyHandler && someObj == getPropertyHandler()) { - setPropertyHandler(null); - } - } - - /** - * Add layers to the BeanContext, if they want to be. Since the BeanContext - * is a Collection, it doesn't matter if a layer is already there because - * duplicates aren't allowed. - * - * @param layers layers to add, if they want to be. - */ - @SuppressWarnings("unchecked") - public void addLayersToBeanContext(List layers) { - BeanContext bc = getBeanContext(); - if (bc == null || layers == null) { - return; - } - - for (Layer layer : layers) { - if (layer.getAddToBeanContext() && layer.getBeanContext() == null) { - bc.add(layer); - } - } - } - - /** - * Add layers to the BeanContext, if they want to be. Since the BeanContext - * is a Collection, it doesn't matter if a layer is already there because - * duplicates aren't allowed. - * - * @param layers layers to add, if they want to be. - */ - public void removeLayersFromBeanContext(List layers) { - BeanContext bc = getBeanContext(); - if (bc == null || layers == null) { - return; - } - - for (Layer layer : layers) { - bc.remove(layer); - } - } - - /** - * Called when the LayerHandler is added to a BeanContext. This method calls - * findAndInit() to hook up with any objects that may already be added to - * the BeanContext. A BeanContextChild method. - * - * @param in_bc BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - if (in_bc != null) { - logger.fine("setting bean context"); - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - - // This will cause findAndInit to be called on the layers and - // plugins after they are added to the MapHandler, so they can find - // the components they need before they get added to the - // map (if they are to be added at startup). - addLayersToBeanContext(getLayerList()); - - // Calling this here may (will) cause the MapBean to get - // loaded with its initial layers, since it is a - // LayerListener. - findAndInit(in_bc.iterator()); - } - } - - public void setSynchronousThreading(boolean s) { - getListeners().setSynchronous(s); - } - - public boolean isSynchronousThreading() { - return getListeners().isSynchronous(); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - props.put(PropUtils.getScopedPropertyPrefix(this) + SynchronousThreadingProperty, - Boolean.toString(getListeners().isSynchronous())); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String internString = i18n.get(LayerHandler.class, SynchronousThreadingProperty, I18n.TOOLTIP, - "Launch new threads to do work."); - props.put(SynchronousThreadingProperty, internString); - internString = i18n.get(LayerHandler.class, SynchronousThreadingProperty, "Synchronous Threading"); - props.put(SynchronousThreadingProperty + LabelEditorProperty, internString); - props.put(SynchronousThreadingProperty + EditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/LightMapHandlerChild.java b/src/core/src/main/java/com/bbn/openmap/LightMapHandlerChild.java deleted file mode 100644 index 4d702c2b8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/LightMapHandlerChild.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/LightMapHandlerChild.java,v $ -// $RCSfile: LightMapHandlerChild.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -/** - * The LightMapHandlerChild is an interface for an object that can be - * managed by a MapHandlerChild, and notified of changes in the - * MapHandler via that managing object. The two methods are intended - * to called when the LightMapHandlerChild should be given an - * opportunity to connect to an object or disconnect from an object. - * The LightMapHandlerChild doesn't have to do anything, this - * interface is really for the benefit of the managing MapHandlerChild - * to figure out if some of its child components may want to know - * about MapHandler events. - */ -public interface LightMapHandlerChild { - - public void findAndInit(Object someObj); - - public void findAndUndo(Object someObj); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/Manifest.txt b/src/core/src/main/java/com/bbn/openmap/Manifest.txt deleted file mode 100644 index f06dbf544..000000000 --- a/src/core/src/main/java/com/bbn/openmap/Manifest.txt +++ /dev/null @@ -1,2 +0,0 @@ -Name: com/bbn/openmap/MapBean.class -Java-Bean: True diff --git a/src/core/src/main/java/com/bbn/openmap/MapBean.java b/src/core/src/main/java/com/bbn/openmap/MapBean.java deleted file mode 100644 index 107046f97..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapBean.java +++ /dev/null @@ -1,1805 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MapBean.java,v $ -// $RCSfile: MapBean.java,v $ -// $Revision: 1.23 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.ContainerEvent; -import java.awt.event.ContainerListener; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JComponent; -import javax.swing.OverlayLayout; - -import com.bbn.openmap.event.CenterEvent; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.PaintListener; -import com.bbn.openmap.event.PaintListenerSupport; -import com.bbn.openmap.event.PanEvent; -import com.bbn.openmap.event.PanListener; -import com.bbn.openmap.event.ProjectionChangeVetoException; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.ProjectionSupport; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The MapBean is the main component of the OpenMap Development Kit. It is a - * Java Bean that manages and displays a map. A map is comprised of a projection - * and a list of layers, and this class has methods that allow you to control - * the projection parameters and to add and remove layers. Layers that are part - * of the map receive dynamic notifications of changes to the underlying view - * and projection. - *

- * Most of the methods in the MapBean are called from the Java AWT and Swing - * code. These methods make the MapBean a good "Swing citizen" to its parent - * components, and you should not need to invoke them. In general there are only - * two reasons to call MapBean methods: controlling the projection, and adding - * or removing layers. - *

- * When controlling the MapBean projection, simply call the method that applies - * - setCenter, pan, zoom, etc. NOTE: If you are setting more than one parameter - * of the projection, it's more efficient to getProjection(), directly set the - * parameters of the projection object, and then call setProjection() with the - * modified projection. That way, each ProjectionListener of the MapBean (each - * layer) will only receive one projectionChanged() method call, as opposed to - * receiving one for each projection adjustment. - *

- * To add or remove layers, use the add() and remove() methods that the MapBean - * inherits from java.awt.Container. The add() method can be called with an - * integer that indicates its desired position in the layer list. - *

- * Changing the default clipping area may cause some Layers to not be drawn - * completely, depending on what the clipping area is set to and when the layer - * is trying to get itself painted. When manually adjusting clipping area, make - * sure that when restricted clipping is over that a full repaint occurs if - * there is a chance that another layer may be trying to paint itself. - *

- * PropertyChangeListeners and ProjectionListeners both receive notifications of - * the projection changes, but the PropertyChangeListeners receive them first. - * If you want to have a component that limits the MapBean's projection - * parameters, it should be a PropertyChangeListener on the MapBean, and throw a - * ProjectionChangeVetoException whenever a Projection setting falls outside of - * the limits. The ProjectionChangeVetoException should hold the alternate - * settings allowed by the listener. When a ProjectionChangeVetoException is - * thrown, all of the PropertyChangeListeners will receive another - * PropertyChangeEvent notification, under the MapBean.projectionVetoed property - * name. The old value for that property will be the rejected Projection object, - * and the new value will be the ProjectionChangeVetoException containing the - * new suggestions. The MapBean will then apply the suggestions and launch - * another round of projection change notifications. The ProjectionListeners - * only receive notification of Projections that have passed through the - * PropertyChangeListeners. - * - * @see Layer - */ -public class MapBean extends JComponent implements ComponentListener, ContainerListener, ProjectionListener, - PanListener, ZoomListener, LayerListener, CenterListener, SoloMapComponent { - - private static final long serialVersionUID = 1L; - - private static Logger logger = Logger.getLogger(MapBean.class.getName()); - - public static final String LayersProperty = "MapBean.layers"; - - public static final String CursorProperty = "MapBean.cursor"; - - public static final String BackgroundProperty = "MapBean.background"; - - public static final String ProjectionProperty = "MapBean.projection"; - - public static final String ProjectionVetoedProperty = "MapBean.projectionVetoed"; - - /** - * OpenMap title. - */ - public static final String title = "OpenMap(tm)"; - - /** - * OpenMap version. - */ - public static final String version = "6.0"; - - /** - * Suppress the copyright message on initialization. - */ - public static boolean suppressCopyright = false; - - private static boolean DEBUG_TIMESTAMP = false; - - private static boolean DEBUG_THREAD = true; - - private static final String copyrightNotice = "OpenMap(tm) Version " + version + "\r\n" - + " Copyright (C) BBNT Solutions LLC. All rights reserved.\r\n" - + " See http://openmap-java.org/ for details.\r\n"; - - public final static float DEFAULT_CENTER_LAT = 0.0f; - - public final static float DEFAULT_CENTER_LON = 0.0f; - - // zoomed all the way out - public final static float DEFAULT_SCALE = Float.MAX_VALUE; - - public final static int DEFAULT_WIDTH = 640; - - public final static int DEFAULT_HEIGHT = 480; - - protected int minHeight = 100; - - protected int minWidth = 100; - - protected Proj projection = new Mercator(new LatLonPoint.Double(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON), - DEFAULT_SCALE, DEFAULT_WIDTH, DEFAULT_HEIGHT); - - protected final ProjectionSupport projectionSupport; - - /** - * Layers that are removed from the MapBean are held until the next - * projection change. When the projection changes, they are notified that - * they have been removed from the map. This list is kept so that toggling a - * layer on and off won't cause them to get rid of their resources, in case - * the user is just creating different views of the map. - */ - protected final Vector removedLayers = new Vector(0); - - /** - * Some users may want the layers deleted immediately when they are removed - * from the map. This flag controls that. The default behavior is to hold a - * reference to a layer and actually release it when the projection changes - * (default = true). Set to false if you want the MapBean to tell a Layer it - * has been removed immediately when it happens. - */ - protected boolean layerRemovalDelayed = true; - - /** - * This vector is to let the layers know when they have been added to the - * map. - */ - protected final Vector addedLayers = new Vector(0); - - /** - * The PaintListeners want to know when the map has been repainted. - */ - protected final PaintListenerSupport painters; - - /** - * The background color for this particular MapBean. If null, the setting - * for the projection, which in turn is set in the Environment class, will - * be used. - */ - protected Paint background = null; - - /** - * The MapBeanRepaintPolicy to use to handler/filter/pace layer repaint() - * requests. If not set, a StandardMapBeanRepaintPolicy will be used, which - * forwards repaint requests to Swing normally. - */ - protected MapBeanRepaintPolicy repaintPolicy = null; - /** - * The MapBeanBackgroundPolicy is used to manipulate/manage the background - * paint. - */ - protected MapBeanBackgroundPolicy backgroundPolicy = null; - /** - * The angle, in radians, to rotate the map. 0.0 is north-up, clockwise is - * positive. - */ - protected double rotationAngle = 0; - - public final static Color DEFAULT_BACKGROUND_COLOR = new Color(191, 239, 255); - - /** - * Return the OpenMap Copyright message. - * - * @return String Copyright - */ - public static String getCopyrightMessage() { - return copyrightNotice; - } - - /** - * Construct a MapBean. - */ - public MapBean() { - this(true); - } - - @SuppressWarnings("serial") - public MapBean(boolean useThreadedNotification) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean()"); - } - if (!suppressCopyright) { - Debug.output(copyrightNotice); - } - - background = DEFAULT_BACKGROUND_COLOR; - - // Don't need one for every MapBean, just the first one. - suppressCopyright = true; - - super.setLayout(new OverlayLayout(this)); - projectionSupport = new ProjectionSupport(this, useThreadedNotification); - addComponentListener(this); - addContainerListener(this); - - painters = new PaintListenerSupport(this); - - // ---------------------------------------- - // In a builder tool it seems that the OverlayLayout - // makes the MapBean fail to resize. And since it has - // no children by default, it has no size. So I add - // a null Layer here to give it a default size. - // ---------------------------------------- - if (java.beans.Beans.isDesignTime()) { - add(new Layer() { - public void projectionChanged(ProjectionEvent e) { - } - - public Dimension getPreferredSize() { - return new Dimension(100, 100); - } - }); - } - - setPreferredSize(new Dimension(projection.getWidth(), projection.getHeight())); - - DEBUG_TIMESTAMP = logger.isLoggable(Level.FINER); - DEBUG_THREAD = logger.isLoggable(Level.FINER); - } - - /** - * Return a string-ified representation of the MapBean. - * - * @return String representing mapbean. - */ - public String toString() { - return getClass().getName() + "@" + Integer.toHexString(hashCode()); - } - - /** - * Call when getting rid of the MapBean, it releases pointers to all - * listeners and kills the ProjectionSupport thread. - */ - public void dispose() { - setLayerRemovalDelayed(false); - - projectionSupport.dispose(); - painters.clear(); - addedLayers.removeAllElements(); - - currentLayers = null; - projectionFactory = null; - - removeComponentListener(this); - removeContainerListener(this); - removeAll(); - purgeAndNotifyRemovedLayers(); - } - - /*---------------------------------------------------------------------- - * Window System overrides - *----------------------------------------------------------------------*/ - - /** - * Adds additional constraints on possible children components. The new - * component must be a Layer. This method included as a good container - * citizen, and should not be called directly. Use the add() methods - * inherited from java.awt.Container instead. - * - * @param comp Component - * @param constraints Object - * @param index int location - */ - protected final void addImpl(Component comp, Object constraints, int index) { - if (comp instanceof Layer) { - super.addImpl(comp, constraints, index); - } else { - throw new IllegalArgumentException("only Layers can be added to a MapBean"); - } - } - - /** - * Prevents changing the LayoutManager. Don't let anyone change the - * LayoutManager! This is called by the parent component and should not be - * called directly. - */ - public final void setLayout(LayoutManager mgr) { - throw new IllegalArgumentException("cannot change layout of Map"); - } - - /** - * Return the minimum size of the MapBean window. Included here to be a good - * citizen. - */ - public Dimension getMinimumSize() { - return new Dimension(minWidth, minHeight); - } - - /** - * Set the minimum size of the MapBean window. Included here to be a good - * citizen. - */ - public void setMinimumSize(Dimension dim) { - minWidth = (int) dim.getWidth(); - minHeight = (int) dim.getHeight(); - } - - /** - * Get the Insets of the MapBean. This returns 0-length Insets. - *

- * This makes sure that there will be no +x,+y offset when drawing graphics. - * This is ok since any borders around the MapBean will get drawn afterwards - * on top. - * - * @return Insets 0-length Insets - */ - public final Insets getInsets() { - return insets; - } - - private final transient static Insets insets = new Insets(0, 0, 0, 0); - - /*---------------------------------------------------------------------- - * ComponentListener implementation - *----------------------------------------------------------------------*/ - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been resized, and kicks off a projection - * change. - * - * @param e ComponentEvent - */ - public void componentResized(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Size changed: " + getWidth() + " x " + getHeight()); - } - - projection.setWidth(getWidth()); - projection.setHeight(getHeight()); - fireProjectionChanged(); - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been moved. - * - * @param e ComponentEvent - */ - public void componentMoved(ComponentEvent e) { - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been shown. - * - * @param e ComponentEvent - */ - public void componentShown(ComponentEvent e) { - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been hidden. - * - * @param e ComponentEvent - */ - public void componentHidden(ComponentEvent e) { - } - - /*---------------------------------------------------------------------- - * - *----------------------------------------------------------------------*/ - - /** - * Add a ProjectionListener to the MapBean. You do not need to call this - * method to add layers as ProjectionListeners. This method is called for - * the layer when it is added to the MapBean. Use this method for other - * objects that you want to know about the MapBean's projection. - * - * @param l ProjectionListener - */ - public synchronized void addProjectionListener(ProjectionListener l) { - projectionSupport.add(l); - - // Assume the listener wants the current projection - try { - l.projectionChanged(new ProjectionEvent(this, getRotatedProjection())); - } catch (Exception e) { - if (logger.isLoggable(Level.FINER)) { - logger.fine("ProjectionListener not handling projection well: " + l.getClass().getName() + " : " - + e.getClass().getName() + " : " + e.getMessage()); - e.printStackTrace(); - } - } - } - - /** - * Remove a ProjectionListener from the MapBean. You do not need to call - * this method to remove layers that are ProjectionListeners. This method is - * called for the layer when it is removed from the MapBean. Use this method - * for other objects that you want to remove from receiving projection - * events. - * - * @param l ProjectionListener - */ - public synchronized void removeProjectionListener(ProjectionListener l) { - projectionSupport.remove(l); - } - - /** - * Called from within the MapBean when its projection listeners need to know - * about a projection change. - */ - protected void fireProjectionChanged() { - - // This handles setting up the RotationHelper if it's needed. - Projection proj = getRotatedProjection(); - - // Fire the property change, so the messages get cleared out. - // Then, if any of the layers have a problem with their new - // projection, their messages will be displayed. - if (logger.isLoggable(Level.FINE)) { - logger.fine("MapBean firing projection property change, vetoable: " + proj); - } - try { - firePropertyChange(ProjectionProperty, null, proj); - } catch (ProjectionChangeVetoException pcve) { - firePropertyChange(ProjectionVetoedProperty, proj, pcve); - pcve.updateWithParameters(this); - return; - } - - // Mark the layers as dirty, as a group, before notifying them of a - // projection change. They will mark themselves clean when they call - // repaint. - for (Component c : getComponents()) { - Layer l = (Layer) c; - if (l != null) { - // Weird, I know, but I've seen c be null and throw an - // exception here. - l.setReadyToPaint(false); - } - } - - projectionSupport.fireProjectionChanged(proj); - purgeAndNotifyRemovedLayers(); - } - - /** - * Clear the vector containing all of the removed layers, and let those - * layers know they have been removed from the map. - */ - public void purgeAndNotifyRemovedLayers() { - // Tell any layers that have been removed that they have - // been removed - - ArrayList rLayers = new ArrayList(removedLayers); - removedLayers.clear(); - - if (rLayers.isEmpty()) { - return; - } - for (Layer layer : rLayers) { - layer.removed(this); - } - - // Shouldn't call this, but it's the only thing - // that seems to make it work... - // Seems to help gc'ing layers in a timely manner. - if (Debug.debugging("helpgc")) { - System.gc(); - } - } - - /*---------------------------------------------------------------------- - * Properties - *----------------------------------------------------------------------*/ - - /** - * Gets the scale of the map. - * - * @return float the current scale of the map - * @see Projection#getScale - */ - public float getScale() { - return projection.getScale(); - } - - /** - * Sets the scale of the map. The Projection may silently disregard this - * setting, setting it to a maxscale or minscale - * value. - * - * @param newScale the new scale - * @see Proj#setScale - */ - public void setScale(float newScale) { - projection.setScale(newScale); - fireProjectionChanged(); - } - - /** - * Gets the center of the map in the form of a LatLonPoint. - * - * @return the center point of the map - * @see Projection#getCenter - */ - public Point2D getCenter() { - return projection.getCenter(); - } - - /** - * Sets the center of the map. - * - * @param newCenter the center point of the map - * @see Proj#setCenter(Point2D) - */ - public void setCenter(Point2D newCenter) { - projection.setCenter(newCenter); - fireProjectionChanged(); - } - - /** - * Sets the center of the map. - * - * @param lat the latitude of center point of the map in decimal degrees - * @param lon the longitude of center point of the map in decimal degrees - * @see Proj#setCenter(double, double) - */ - public void setCenter(double lat, double lon) { - projection.setCenter(new Point2D.Double(lon, lat)); - fireProjectionChanged(); - } - - /** - * Sets the center of the map. - * - * @param lat the latitude of center point of the map in decimal degrees - * @param lon the longitude of center point of the map in decimal degrees - * @see Proj#setCenter(double, double) - */ - public void setCenter(float lat, float lon) { - setCenter((double) lat, (double) lon); - } - - /** - * Set the background color of the map. If the background for this MapBean - * is not null, the background of the projection will be used. - * - * @param color java.awt.Color. - */ - public void setBackgroundColor(Color color) { - setBackground(color); - } - - public void setBackground(Color color) { - super.setBackground(color); - setBckgrnd((Paint) color); - } - - /** - * We override this to set the paint mode on the Graphics before the border - * is painted, otherwise we get an XOR effect in the border. - */ - public void paintBorder(Graphics g) { - g.setPaintMode(); - super.paintBorder(g); - } - - /** - * Set the background of the map. If the background for this MapBean is not - * null, the background of the projection will be used. - * - * @param paint java.awt.Paint. - */ - public void setBckgrnd(Paint paint) { - setBufferDirty(true); - - // Instead, do this. - Paint oldBackground = background; - background = paint; - firePropertyChange(BackgroundProperty, oldBackground, background); - - repaint(); - } - - /** - * Get the background color of the map. If the background color for this - * MapBean has been explicitly set, that value will be returned. Otherwise, - * the background color of the projection will be returned. If the - * background is not a color (as opposed to Paint) this method will return - * null. - * - * @return color java.awt.Color. - */ - public Color getBackground() { - Paint ret = getBckgrnd(); - if (ret instanceof Color) { - return (Color) ret; - } - - return super.getBackground(); - } - - /** - * Get the background of the map. If the background for this MapBean has - * been explicitly set, that value will be returned. Otherwise, the - * background of the projection will be returned. - * - * @return color java.awt.Color. - */ - public Paint getBckgrnd() { - Paint ret = background; - - MapBeanBackgroundPolicy mbbp = backgroundPolicy; - if (mbbp != null) { - ret = mbbp.getBckgrnd(); - } - - if (ret == null) { - ret = super.getBackground(); - } - - return ret; - } - - /** - * Get the projection property, reflects the projection with no rotation. - * - * @return current Projection of map. - */ - public Projection getProjection() { - return projection; - } - - /** - * @return the expanded rotated projection if map rotated, normal projection - * if not rotated. The rotated projection is larger than the MapBean - * and has extra offsets. - */ - public Projection getRotatedProjection() { - RotationHelper rotation = getUpdatedRotHelper(); - Projection proj = rotation != null ? rotation.getProjection() : projection; - // Double check - ((Proj) proj).setRotationAngle(getRotationAngle()); - return proj; - } - - /** - * Set the projection. Shouldn't be null, and won't do anything if it is. - * - * @param aProjection Projection - */ - public void setProjection(Projection aProjection) { - if (aProjection != null && !aProjection.getProjectionID().contains("NaN")) { - setBufferDirty(true); - projection = (Proj) aProjection; - setPreferredSize(new Dimension(projection.getWidth(), projection.getHeight())); - fireProjectionChanged(); - } - } - - // ------------------------------------------------------------ - // CenterListener interface - // ------------------------------------------------------------ - - /** - * Handles incoming CenterEvents. - * - * @param evt the incoming center event - */ - public void center(CenterEvent evt) { - setCenter(evt.getLatitude(), evt.getLongitude()); - } - - // ------------------------------------------------------------ - // PanListener interface - // ------------------------------------------------------------ - - /** - * Handles incoming PanEvents. - * - * @param evt the incoming pan event - */ - public void pan(PanEvent evt) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("PanEvent: " + evt); - } - float az = evt.getAzimuth() - (float) Math.toDegrees(rotationAngle); - float c = evt.getArcDistance(); - if (Float.isNaN(c)) { - projection.pan(az); - } else { - projection.pan(az, c); - } - - fireProjectionChanged(); - } - - // ------------------------------------------------------------ - // ZoomListener interface - // ------------------------------------------------------------ - - /** - * Zoom the Map. Part of the ZoomListener interface. Sets the scale of the - * MapBean projection, based on a relative or absolute amount. - * - * @param evt the ZoomEvent describing the new scale. - */ - public void zoom(ZoomEvent evt) { - float newScale; - if (evt.isAbsolute()) { - newScale = evt.getAmount(); - } else if (evt.isRelative()) { - newScale = getScale() * evt.getAmount(); - } else { - return; - } - setScale(newScale); - } - - // ------------------------------------------------------------ - // ContainerListener interface - // ------------------------------------------------------------ - - protected transient Layer[] currentLayers = new Layer[0]; - - protected transient boolean doContainerChange = true; - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param value boolean - */ - public void setDoContainerChange(boolean value) { - // if changing from false to true, call changeLayers() - if (!doContainerChange && value) { - doContainerChange = value; - changeLayers(null); - } else { - doContainerChange = value; - } - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @return boolean - */ - public boolean getDoContainerChange() { - return doContainerChange; - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param e ContainerEvent - */ - public void componentAdded(ContainerEvent e) { - // Blindly cast. addImpl has already checked to be - // sure the child is a Layer. - Layer childLayer = (Layer) e.getChild(); - addProjectionListener(childLayer); - - // If the new layer is in the queue to have removed() called - // on it take it off the queue, and don't add it to the - // added() queue (it doesn't know that it was removed, yet). - // Otherwise, add it to the queue to have added() called on - // it. - if (!removedLayers.removeElement(childLayer)) { - addedLayers.addElement(childLayer); - } - changeLayers(e); - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. Layers that are removed are added to a list, - * which is cleared when the projection changes. If they are added to the - * MapBean again before the projection changes, they are taken off the list, - * added back to the MapBean, and are simply repainted. This prevents layers - * from doing unnecessary work if they are toggled on and off without - * projection changes. - * - * @param e ContainerEvent - * @see com.bbn.openmap.MapBean#purgeAndNotifyRemovedLayers - */ - public void componentRemoved(ContainerEvent e) { - // Blindly cast. addImpl has already checked to be - // sure the child is a Layer. - Layer childLayer = (Layer) e.getChild(); - removeProjectionListener(childLayer); - removedLayers.addElement(childLayer); - changeLayers(e); - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param e ContainerEvent - */ - protected void changeLayers(ContainerEvent e) { - // Container Changes can be disabled to speed adding/removing - // multiple layers - if (!doContainerChange) { - return; - } - Component[] comps = this.getComponents(); - int ncomponents = comps.length; - Layer[] newLayers = new Layer[ncomponents]; - System.arraycopy(comps, 0, newLayers, 0, ncomponents); - if (logger.isLoggable(Level.FINE)) { - debugmsg("changeLayers() - firing change"); - } - firePropertyChange(LayersProperty, currentLayers, newLayers); - - // Tell the new layers that they have been added - for (Layer layer : addedLayers) { - layer.added(this); - } - addedLayers.removeAllElements(); - - currentLayers = newLayers; - - } - - // ------------------------------------------------------------ - // ProjectionListener interface - // ------------------------------------------------------------ - - /** - * ProjectionListener interface method. Should not be called directly. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - Projection newProj = e.getProjection(); - if (!projection.equals(newProj)) { - setProjection(newProj); - } - } - - /** - * Set the Mouse cursor over the MapBean component. - * - * @param newCursor Cursor - */ - public void setCursor(Cursor newCursor) { - firePropertyChange(CursorProperty, this.getCursor(), newCursor); - super.setCursor(newCursor); - } - - /** - * In addition to adding the PropertyChangeListener as the JComponent method - * does, this method also provides the listener with the initial version of - * the Layer and Cursor properties. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl) { - super.addPropertyChangeListener(pcl); - pcl.propertyChange(new PropertyChangeEvent(this, LayersProperty, currentLayers, currentLayers)); - pcl.propertyChange(new PropertyChangeEvent(this, CursorProperty, this.getCursor(), this.getCursor())); - pcl.propertyChange(new PropertyChangeEvent(this, BackgroundProperty, this.getBckgrnd(), this.getBckgrnd())); - } - - protected final void debugmsg(String msg) { - logger.fine(this.toString() + (DEBUG_TIMESTAMP ? (" [" + System.currentTimeMillis() + "]") : "") - + (DEBUG_THREAD ? (" [" + Thread.currentThread() + "]") : "") + ": " + msg); - } - - /** - * Same as JComponent.paint(), except if there are no children (Layers), the - * projection still paints the background and the border is painted. - */ - public void paint(Graphics g) { - if (projection != null) { - drawProjectionBackground(g); - } - - if (this.getComponentCount() > 0) { - paintChildren(g, null); - } - - paintPainters(g); - - // Border gets painted over by printChildren with special layer - // handling. - paintBorder(g); - } - - /** - * Convenience method to test if Graphics is Graphics2D object, and to try - * to do the right thing. - */ - protected void drawProjectionBackground(Graphics g) { - if (g instanceof Graphics2D) { - projection.drawBackground((Graphics2D) g, getBckgrnd()); - } else { - g.setColor(getBackground()); - projection.drawBackground(g); - } - } - - /** - * Same as JComponent.paintChildren() except any PaintListeners are notified - * and the border is painted over the children. - */ - public void paintChildren(Graphics g) { - paintChildren(g, null); - paintPainters(g); - } - - public void paintPainters(Graphics g) { - // Just want a quick, non-changing handle on the helper. Don't need to - // configure it. - RotationHelper rotationHelper = getRotHelper(); - - if (rotationHelper != null) { - rotationHelper.paintPainters(g); - } else { - painters.paint(g); - } - } - - /** - * Same as paintChildren, but allows you to set a clipping area to paint. Be - * careful with this, because if the clipping area is set while some layer - * decides to paint itself, that layer may not have all it's objects - * painted. - */ - public void paintChildren(Graphics g, Rectangle clip) { - - g = getMapBeanRepaintPolicy().modifyGraphicsForPainting(g); - - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - rotationHelper.paintChildren(g, clip); - } else { - // Normal painting - super.paintChildren(g); - } - } - - /** - * A method that grabs the component list of the MapBean, and renders just - * the layers from back to front. No clipping is set, other than what is set - * on the Graphics object. - * - * @param g Graphics - */ - protected void paintLayers(Graphics g) { - synchronized (getTreeLock()) { - int i = getComponentCount() - 1; - if (i < 0) { - return; - } - - for (; i >= 0; i--) { - Component comp = getComponent(i); - - final boolean isLayer = comp instanceof Layer; - - if (isLayer && comp.isVisible()) { - comp.paint(g); - } - } - } - } - - public Graphics getGraphics(boolean rotateIfSet) { - RotationHelper rotationHelper = getRotHelper(); - if (rotateIfSet && rotationHelper != null) { - return rotationHelper.getGraphics(); - } - - return super.getGraphics(); - } - - /** - * Method that provides an option of whether or not to draw the border when - * painting. Usually called from another object trying to control the Map - * appearance when events are flying around. - */ - public void paintChildrenWithBorder(Graphics g, boolean drawBorder) { - paintChildren(g); - if (drawBorder) { - paintBorder(g); - } - } - - /** - * Add a PaintListener. - * - * @param l PaintListener - */ - public synchronized void addPaintListener(PaintListener l) { - painters.add(l); - } - - /** - * Remove a PaintListener. - * - * @param l PaintListener - */ - public synchronized void removePaintListener(PaintListener l) { - painters.remove(l); - } - - // ------------------------------------------------------------ - // LayerListener interface - // ------------------------------------------------------------ - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. - * - * @param evt a LayerEvent - */ - public void setLayers(LayerEvent evt) { - setBufferDirty(true); - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - // Don't care about these at all... - return; - } - - // @HACK is this cool?: - if (layers == null) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean.setLayers(): layers is null!"); - } - return; - } - - boolean oldChange = getDoContainerChange(); - setDoContainerChange(false); - - // use LayerEvent.REPLACE when you want to remove all current - // layers add a new set - if (type == LayerEvent.REPLACE) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Replacing all layers"); - } - removeAll(); - - for (Layer layer : layers) { - - if (layer == null) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean.setLayers(): skipping null layer from being added to MapBean"); - } - continue; - } - - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - add(layer); - layer.setVisible(true); - } - - } - - // use LayerEvent.ADD when adding and/or reshuffling layers - else if (type == LayerEvent.ADD) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding new layers"); - } - for (Layer layer : layers) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - add(layer); - layer.setVisible(true); - } - } - - // use LayerEvent.REMOVE when you want to delete layers from - // the map - else if (type == LayerEvent.REMOVE) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Removing layers"); - } - for (Layer layer : layers) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Removing layer[" + layer.getName() + "]"); - } - remove(layer); - } - } - - if (!layerRemovalDelayed) { - purgeAndNotifyRemovedLayers(); - } - - setDoContainerChange(oldChange); - revalidate(); - repaint(); - } - - /** - * A call to try and get the MapBean to reduce flashing by controlling when - * repaints happen, waiting for lower layers to call for a repaint(), too. - * Calls shouldForwardRepaint(Layer), which acts as a policy for whether to - * forward the repaint up the Swing tree. - */ - public void repaint(Layer layer) { - setBufferDirty(true); - if (logger.isLoggable(Level.FINER)) { - String name = layer.getName(); - logger.finer((name == null ? layer.getClass().getName() : name) + " - wants a repaint()"); - } - getMapBeanRepaintPolicy().repaint(layer); - } - - /** - * Set the MapBeanRepaintPolicy used by the MapBean. This policy can be used - * to pace/filter layer repaint() requests. - */ - public void setMapBeanRepaintPolicy(MapBeanRepaintPolicy mbrp) { - repaintPolicy = mbrp; - } - - /** - * Get the MapBeanRepaintPolicy used by the MapBean. This policy can be used - * to pace/filter layer repaint() requests. If no policy has been set, a - * StandardMapBeanRepaintPolicy will be created, which simply forwards all - * requests. - */ - public MapBeanRepaintPolicy getMapBeanRepaintPolicy() { - if (repaintPolicy == null) { - repaintPolicy = new StandardMapBeanRepaintPolicy(this); - } - return repaintPolicy; - } - - /** - * Get the MapBeanBackgroundPolicy set on this MapBean. - * - * @return the backgroundPolicy - */ - public MapBeanBackgroundPolicy getBackgroundPolicy() { - return backgroundPolicy; - } - - /** - * @param backgroundPolicy the backgroundPolicy to set - */ - public void setBackgroundPolicy(MapBeanBackgroundPolicy backgroundPolicy) { - this.backgroundPolicy = backgroundPolicy; - } - - /** - * Convenience function to get the LatLonPoint representing a screen - * location from a MouseEvent. Returns null if the event is null, or if the - * projection is not set in the MapBean. Allocates new LatLonPoint with - * coordinates. Takes rotation set on MapBean into account. - */ - public Point2D getCoordinates(MouseEvent event) { - return getCoordinates(event, null); - } - - /** - * Convenience function to get the LatLonPoint representing a screen - * location from a MouseEvent. Returns null if the event is null, or if the - * projection is not set in the MapBean. Save on memory allocation by - * sending in the LatLonPoint to fill. Takes rotation set on MapBean into - * account. - */ - public T getCoordinates(MouseEvent event, T llp) { - Projection proj = getProjection(); - if (proj == null || event == null) { - return null; - } - - return inverse(event.getX(), event.getY(), llp); - } - - /** - * Convenience function to get the pixel Point2D representing a screen - * location from a MouseEvent in the projection space (as if there is no - * rotation set). Returns null if the event is null. This is used to talk to - * the OMGraphics, since they don't know about the map rotation. - */ - public Point2D getNonRotatedLocation(MouseEvent event) { - return getNonRotatedLocation(event, null); - } - - /** - * Convenience function to get the pixel Point2D representing a screen - * location from a MouseEvent in the projection space (as if there is no - * rotation set). Returns null if the event is null. This is used to talk to - * the OMGraphics, since they don't know about the map rotation. - */ - public Point2D getNonRotatedLocation(MouseEvent event, Point2D pnt) { - if (event == null) { - return null; - } - - if (pnt == null) { - pnt = new Point2D.Double(event.getX(), event.getY()); - } else { - pnt.setLocation(event.getX(), event.getY()); - } - - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - pnt = rotationHelper.inverseTransform(pnt, pnt); - } - - return pnt; - } - - /** - * If the map has been rotated, get a shape that has been transformed into - * the pixel space of the unrotated maps (the space the projected OMGraphics - * know about). - * - * @param shape input shape - * @return GeneralPath for transform shape if map is rotated, the input - * shape if the map is not rotated. - */ - public Shape getNonRotatedShape(Shape shape) { - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - return rotationHelper.inverseTransform(shape); - } - return shape; - } - - /** - * Checks the rotation set on the MapBean and accounts for it before calling - * inverse on the projection. - * - * @param x horizontal window pixel from left side - * @param y vertical window pixel from top - * @param ret Point2D object returned with coordinates suitable for - * projection where mouse event is. - * @return the provided T ret object, or new Point2D object from projection - * if ret is null. - */ - public T inverse(double x, double y, T ret) { - RotationHelper rotationHelper = getRotHelper(); - return (rotationHelper == null) ? getProjection().inverse(x, y, ret) : rotationHelper.inverse(x, y, ret); - } - - /** - * Interface-like method to query if the MapBean is buffered, so you can - * control behavior better. Allows the removal of specific instance-like - * queries for, say, BufferedMapBean, when all you really want to know is if - * you have the data is buffered, and if so, should be buffer be cleared. - * For the MapBean, always false. - */ - public boolean isBuffered() { - return false; - } - - /** - * Interface-like method to set a buffer dirty, if there is one. In MapBean, - * there isn't. - * - * @param value boolean - */ - public void setBufferDirty(boolean value) { - } - - /** - * Checks whether the image buffer should be repainted. - * - * @return boolean whether the layer buffer is dirty. Always true for - * MapBean, because a paint is always gonna need to happen. - */ - public boolean isBufferDirty() { - return true; - } - - /** - * If true (default) layers are held when they are removed, and then - * released and notified of removal when the projection changes. This saves - * the layers from releasing resources if the layer is simply being toggled - * on/off for different map views. - * - * @param set the setting - */ - public void setLayerRemovalDelayed(boolean set) { - layerRemovalDelayed = set; - } - - /** - * @return the flag for delayed layer removal. - */ - public boolean isLayerRemovalDelayed() { - return layerRemovalDelayed; - } - - /** - * Go through the layers, and for all of them that have the autoPalette - * variable turned on, show their palettes. - */ - public void showLayerPalettes() { - for (Component comp : getComponents()) { - // they have to be layers - Layer l = (Layer) comp; - if (l.autoPalette) { - l.showPalette(); - } - } - } - - /** - * Turn off all layer palettes. - */ - public void hideLayerPalettes() { - for (Component comp : getComponents()) { - // they have to be layers - ((Layer) comp).hidePalette(); - } - } - - protected ProjectionFactory projectionFactory; - - public ProjectionFactory getProjectionFactory() { - if (projectionFactory == null) { - projectionFactory = ProjectionFactory.loadDefaultProjections(); - } - - return projectionFactory; - } - - public void setProjectionFactory(ProjectionFactory projFactory) { - projectionFactory = projFactory; - } - - protected RotationHelper rotHelper; - - /** - * Handles all of the updating of the RotationHelper if needed, based on the - * current rotation settings on the MapBean. - * - * @return the locRotHelper, null if not needed. - */ - protected RotationHelper getUpdatedRotHelper() { - double rotAngle = getRotationAngle(); - Projection proj = getProjection(); - RotationHelper rotationHelper = getRotHelper(); - - if (rotAngle != 0.0) { - if (rotationHelper == null) { - rotationHelper = new RotationHelper(rotAngle, proj); - setRotHelper(rotationHelper); - } else { - rotationHelper.updateForBufferDimensions(proj); - rotationHelper.updateAngle(rotAngle); - } - } else if (rotationHelper != null) { - /* - * Just because the angle is zero, let's check with the - * rotationHelper. If the map is just passing through zero rotation, - * keep it around. If we get a couple of projection changes with the - * az set to zero, then get rid of the rotation helper. - */ - if (rotationHelper.isStillNeeded(rotAngle)) { - rotationHelper.updateForBufferDimensions(proj); - rotationHelper.updateAngle(rotAngle); - } else { - setRotHelper(null); - rotationHelper = null; - } - } // else return null rotationHelper - - return rotationHelper; - } - - /** - * Get the RotationHelper that assists with rotated maps. - * - * @return RotationHelper, may be null if map isn't rotated. - */ - protected RotationHelper getRotHelper() { - return rotHelper; - } - - /** - * @param nRotHelper the locRotHelper to set as the current one. Disposes of - * the old one. - */ - protected void setRotHelper(RotationHelper nRotHelper) { - RotationHelper rotationHelper = this.rotHelper; - if (rotationHelper != null) { - rotationHelper.dispose(); - } - - this.rotHelper = nRotHelper; - } - - /** - * Set the rotation of the map in RADIANS. - * - * @param angle radians of rotation, increasing clockwise. - */ - public void setRotationAngle(double angle) { - setRotationAngle(angle, false); - } - - /** - * Set the rotation of the map in RADIANS. - * - * @param angle radians of rotation, increasing clockwise. - * @param fastRotation if true, fireProjectionChange will not be called, and - * the RotationHelper will be used to spin image buffer. - */ - public void setRotationAngle(double angle, boolean fastRotation) { - if (this.rotationAngle != angle) { - this.rotationAngle = angle; - - /* - * moving into this block makes rotation work faster, and smooth. - * However, it doesn't give the non-rotating OMGraphics a chance to - * counteract the rotation. - */ - if (fastRotation && angle != 0) { - /* - * If only the angle changes, we can just update the - * locRotHelper angle, and reuse all of the other settings. If - * the angle changes and zero is involved,either way, get the - * rotation helper set up in fireProjectionChanged. The - * RotationHelper needs to be redefined for any other projection - * changes anyway. - */ - RotationHelper locRotHelper = getRotHelper(); - if (locRotHelper != null) { - locRotHelper.updateAngle(angle); - repaint(); - return; - } - } - - fireProjectionChanged(); - } - } - - /** - * Get the rotation of the map in RADIANS. - * - * @return the angle the map has been rotated, in RADIANS, clockwise is - * positive. - */ - public double getRotationAngle() { - return rotationAngle; - } - - protected class RotationHelper { - - Image rotImage; - - double angle; - Point2D rotCenter; - int rotBufferHeight; - int rotBufferWidth; - int rotXOffset; - int rotYOffset; - Projection rotProjection; - AffineTransform rotTransform; - - private RotationHelper(double angle, Projection currentProjection) { - updateForBufferDimensions(currentProjection); - updateAngle(angle); - } - - /** - * We're going to try to do buffering with a image that will cover all - * of the corners when the map is rotated. We'll measure the ground - * distance from the center of the projection/map to each corner, and - * take the longest to create a bounding circle. The NSEW of that - * bounding circle (as a bounding box) Makes up the buffered image pixel - * bounds, and the inverse projected coordinates of that box should be - * returned as upper left and lower right coordinates when those methods - * are called. The projection of that box should be the same as the - * current projection, except for the new width and height. - * - * Because the height and width are different for the buffered image, - * we're going to have to translate it before it is rotated. We can - * probably just tack on an additional translate to the rot. That - * difference will be 1/2 the difference of the height and width between - * the rot image and the original projection (mapbean dimensions). - * - * @param proj the projection to use to create the current image buffer - * @return boolean true if the rotBufferHeight and/or rotBufferWidth - * have changed, indicating that the image buffer was recreated - * for new dimensions. - */ - protected boolean updateForBufferDimensions(Projection proj) { - - int currentRotBufferWidth = rotBufferWidth; - int currentRotBufferHeight = rotBufferHeight; - - Point2D center = proj.getCenter(); - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - - /* - * Woooooow, we're really going to have to work it, aren't we? We - * need to handle GeoProj differently than Cartesian coords. That - * seems to lend itself to moving this kind of calculations to the - * super classes of the projection classes. *sigh* For now, let's - * try assuming that GeoProj - */ - Geo centerGeo = new Geo(center.getY(), center.getX()); - Geo ulGeo = new Geo(ul.getY(), ul.getX()); - Geo lrGeo = new Geo(lr.getY(), lr.getX()); - - // Comparing the UL and LR corners for distance, get the greatest. - double dist = Math.max(centerGeo.distance(ulGeo), centerGeo.distance(lrGeo)); - - // Now calculate the bounds of that distance in 4 directions - Geo N = Geo.offset(centerGeo, dist, 0); - Geo S = Geo.offset(centerGeo, dist, Math.PI); - Geo E = Geo.offset(centerGeo, dist, Math.PI / 2.0); - Geo W = Geo.offset(centerGeo, dist, -Math.PI / 2); - - // Calculate the coordinates of new bounds for that distance from - // center. - Point2D newUL = new Point2D.Double(W.getLongitude(), N.getLatitude()); - Point2D newLR = new Point2D.Double(E.getLongitude(), S.getLatitude()); - - // Calculate the pixel bounds of the new bounding box to get new - // projection h, w - Point2D newULPix = proj.forward(newUL); - Point2D newLRPix = proj.forward(newLR); - - int reqRotBufferHeight = (int) Math.abs(newLRPix.getY() - newULPix.getY()); - int reqRotBufferWidth = (int) Math.abs(newLRPix.getX() - newULPix.getX()); - - // If the image is a little bigger than we need, we can reuse. Only - // replace it if it is significantly bigger, or at all smaller. - boolean needNewHeightImage = reqRotBufferHeight > currentRotBufferHeight - || reqRotBufferHeight < .9 * currentRotBufferHeight; - boolean needNewWidthImage = reqRotBufferWidth > currentRotBufferWidth - || currentRotBufferWidth < .9 * currentRotBufferWidth; - - boolean bufferImageResized = false; - - if (needNewHeightImage || needNewWidthImage) { - this.rotImage = new BufferedImage(reqRotBufferWidth, reqRotBufferHeight, BufferedImage.TYPE_INT_ARGB); - rotBufferWidth = reqRotBufferWidth; - rotBufferHeight = reqRotBufferHeight; - bufferImageResized = true; - } - - rotProjection = projectionFactory.makeProjection(proj.getClass(), center, proj.getScale(), rotBufferWidth, - rotBufferHeight); - this.rotCenter = rotProjection.forward(center); - - /* - * Now calculate the different in size between the current - * projection and the buffered image projection, and the offset - * needed for translation for proper painting. - */ - this.rotXOffset = (rotProjection.getWidth() - proj.getWidth()) / 2; - this.rotYOffset = (rotProjection.getHeight() - proj.getHeight()) / 2; - - return bufferImageResized; - } - - public void updateAngle(double angle) { - this.angle = angle; - this.rotTransform = AffineTransform.getRotateInstance(angle, rotCenter.getX(), rotCenter.getY()); - } - - /** - * @param az angle to test against - * @return true if current angle or new angle is not zero. Two zero - * angles in a row is an indication that the RotationHelper is - * no longer needed. - */ - public boolean isStillNeeded(double az) { - return !(az == 0.0 && angle == 0.0); - } - - /** - * @return the projection of the image buffer that is big enough for - * rotated areas. - */ - public Projection getProjection() { - return rotProjection; - } - - public void paintChildren(Graphics g, Rectangle clip) { - - if (rotProjection == null) { - // We're not properly prepared for rotation, return; - return; - } - - Graphics2D g2 = (Graphics2D) rotImage.getGraphics(); - ((Proj) rotProjection).drawBackground(g2, getBckgrnd()); - g2.setTransform(rotTransform); - paintLayers(g2); - g.drawImage(rotImage, -rotXOffset, -rotYOffset, null); - g2.dispose(); - } - - public void paintPainters(Graphics g) { - Graphics2D g2 = (Graphics2D) g.create(); - AffineTransform transform = AffineTransform.getTranslateInstance(-rotXOffset + getX(), - -rotYOffset + getY()); - transform.concatenate(rotTransform); - g2.setTransform(transform); - - painters.paint(g2); - g2.dispose(); - } - - /** - * @return a Graphics object from the MapBean with the rotation - * transform applied. - */ - public Graphics getGraphics() { - Graphics2D g = (Graphics2D) MapBean.super.getGraphics().create(); - g.setTransform(rotTransform); - return g; - } - - /** - * Performs a projection.inverse operation that also takes into account - * rotation. - * - * @param x pixel x - * @param y pixel y - * @param ret T in the coordinate space of projection. - * @return T, either ret or a new object. - */ - public T inverse(double x, double y, T ret) { - - Point2D pnt = new Point2D.Double(x + rotXOffset, y + rotYOffset); - - try { - pnt = rotTransform.inverseTransform(pnt, pnt); - return getProjection().inverse(pnt, ret); - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, e.getMessage(), e); - } - - return ret; - } - - /** - * Returns dst, the unrotated pixel location of the map. - * - * @param src the pixel point - * @param dst - * @return see above. - */ - public Point2D inverseTransform(Point2D src, Point2D dst) { - try { - src.setLocation(src.getX() + rotXOffset, src.getY() + rotYOffset); - dst = rotTransform.inverseTransform(src, dst); - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, e.getMessage(), e); - } - return dst; - } - - /** - * Returns a transformed version of the Shape, unrotated into the - * projected pixel space of the layer OMGraphics. - * - * @param shape to transform - * @return the transformed shape. - */ - public Shape inverseTransform(Shape shape) { - - float[] coords = new float[6]; - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - PathIterator pi = shape.getPathIterator(getInverseRotationTransform()); - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(coords[0], coords[1]); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(coords[0], coords[1]); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(coords[0], coords[1], coords[2], coords[3]); - } else if (type == PathIterator.SEG_CUBICTO) { - path.curveTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); - } - } - - pi.next(); - } - - return path; - } - - public AffineTransform getInverseRotationTransform() { - try { - AffineTransform translateOffset = AffineTransform.getTranslateInstance(rotXOffset, rotYOffset); - AffineTransform transform = rotTransform.createInverse(); - translateOffset.preConcatenate(transform); - return translateOffset; - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, "AffineTransform problem", e); - } - - return new AffineTransform(); - } - - public void dispose() { - if (rotImage != null) { - rotImage.flush(); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/MapBeanBackgroundPolicy.java b/src/core/src/main/java/com/bbn/openmap/MapBeanBackgroundPolicy.java deleted file mode 100644 index 822e10127..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapBeanBackgroundPolicy.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.bbn.openmap; - -import java.awt.Paint; -import java.beans.PropertyChangeListener; - -/** - * This interface describes objects that help the MapBean do special stuff with - * the background paint, dynamically. It was originally created to help set - * GradientPaint on the map, given a color. One of the side effects of having a - * gradient paint or image pattern set on the MapBean as a background is - * apparent when the map is panned - you don't really want that background - * shifting with the rest of the map, it looks weird and is jarring when the map - * updates to the new location, as the background goes back to were it - * originally was. The proper effect is having the background just stay in one - * place, and have the other layers float on top when the map is panned. Anyway, - * MapBeanBackgroundPolicy objects are supposed to help with that. - *

- * - * If the MapBeanBackgroundPolicy is required to modify any Paint object set on - * the MapBean as its Bckgrnd, the policy should add itself to the MapBean as a - * PropertyChangeLister for background paint change updates, and projection - * changes if they are needed. - * - * @author dietrick - * - */ -public interface MapBeanBackgroundPolicy extends PropertyChangeListener { - - /** - * Get the modified background paint to use for the MapBean during paint. - * - * @return Paint - */ - Paint getBckgrnd(); - - /** - * Indicates whether the background should be included in image when the map - * is panned. - * - * @return - */ - boolean includeInPan(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/MapBeanGradientBackgroundPolicy.java b/src/core/src/main/java/com/bbn/openmap/MapBeanGradientBackgroundPolicy.java deleted file mode 100644 index 06a94d111..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapBeanGradientBackgroundPolicy.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.bbn.openmap; - -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The MapBeanGradientBackgroundPolicy adds a delicate touch to the background - * of the map, a slight gradient paint from one point on the map to another. - * Those points are defined as a percentage of the height and width of the map. - * This class can be defined in the properties as; - * - *

- * mapBeanGradientBackgroundPolicy.class=com.bbn.openmap.MapBeanGradientBackgroundPolicy
- * # bright x bright y dark x dark y as percentage of window location
- * mapBeanGradientBackgroundPolicy.brightDarkPercentage=.3 .3 .95 .95
- * # how many times to make brighter than original color.
- * mapBeanGradientBackgroundPolicy.howBright=1
- * # how many times to make darker than original color.
- * mapBeanGradientBackgroundPolicy.howDark=2
- * 
- * - * @author dietrick - * - */ -public class MapBeanGradientBackgroundPolicy extends OMComponent implements - MapBeanBackgroundPolicy, PropertyChangeListener { - - /** - * A property that describes the location of the bright point and dark point - * of the gradient paint, defined as a percentage of the window width and - * height. This should be a space separated list of 4 numbers between 0 and - * 1, reflecting bright x, bright y, dark x, dark y. i.e. .3 .3 .95 .95 will - * give you brightness in the upper left area of the map, and darkness in - * the lower right. - */ - public final static String BRIGHT_DARK_PERCENTAGE_PROPERTY = "brightDarkPercentage"; - public final static String HOW_BRIGHT_PROPERTY = "howBright"; - public final static String HOW_DARK_PROPERTY = "howDark"; - - /** - * bright x, bright y, dark x, dark y, in percentages of window measurement. - */ - protected final double[] brightPointDarkPoint = new double[] { .3, .3, .95, - .95 }; - protected int howBright = 1; - protected int howDark = 1; - protected Paint originalPaint; // the original Paint - protected Projection proj; // the current background - protected Paint gradientPaint; // to return for background - protected MapBean mapBean; // handle to know if it's removed from MapHandler - - protected void updatePaint() { - // Gradient paint in MapBean. Needs to be handled in Pan mode. - Projection projection = proj; // local copy - if (originalPaint instanceof Color && projection != null) { - Color baseColor = (Color) originalPaint; - Point2D p1 = new Point2D.Double(projection.getWidth() - * brightPointDarkPoint[0], projection.getHeight() - * brightPointDarkPoint[1]); - Point2D p2 = new Point2D.Double(projection.getWidth() - * brightPointDarkPoint[2], projection.getHeight() - * brightPointDarkPoint[3]); - gradientPaint = new GradientPaint(p1, - brighten(baseColor, howBright), p2, darken(baseColor, - howDark), false); - } else { - // Since it's something else like a gradient paint or maybe image, - // just return it. - gradientPaint = originalPaint; - } - } - - protected Color darken(Color color, int times) { - for (int i = 0; i < times; i++) { - color = color.darker(); - } - return color; - } - - protected Color brighten(Color color, int times) { - for (int i = 0; i < times; i++) { - color = color.brighter(); - } - return color; - } - - public boolean includeInPan() { - return false; - } - - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - Object obj = evt.getNewValue(); - if (MapBean.BackgroundProperty.equals(propertyName) - && obj instanceof Paint) { - setOriginalPaint((Paint) obj); - } else if (MapBean.ProjectionProperty.equals(propertyName) - && obj instanceof Projection) { - setProjection((Projection) obj); - } - } - - protected void setOriginalPaint(Paint p) { - originalPaint = p; - updatePaint(); - } - - public Paint getOriginalPaint() { - return originalPaint; - } - - public void setProjection(Projection p) { - proj = p; - updatePaint(); - } - - public Projection getProjection() { - return proj; - } - - public Paint getBckgrnd() { - return gradientPaint; - } - - public void findAndInit(Object obj) { - if (obj instanceof MapBean) { - mapBean = (MapBean) obj; - mapBean.addPropertyChangeListener(this); - mapBean.setBackgroundPolicy(this); - } - } - - public void findAndUndo(Object obj) { - if (obj == mapBean) { - mapBean.removePropertyChangeListener(this); - mapBean.setBackgroundPolicy(null); - mapBean = null; - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - howBright = PropUtils.intFromProperties(props, prefix - + HOW_BRIGHT_PROPERTY, howBright); - howDark = PropUtils.intFromProperties(props, - prefix + HOW_DARK_PROPERTY, howDark); - - String[] stringValues = PropUtils.stringArrayFromProperties(props, - prefix + BRIGHT_DARK_PERCENTAGE_PROPERTY, " "); - - if (stringValues != null && stringValues.length == 4) { - try { - double[] values = new double[4]; - values[0] = Double.parseDouble(stringValues[0]); - values[1] = Double.parseDouble(stringValues[1]); - values[2] = Double.parseDouble(stringValues[2]); - values[3] = Double.parseDouble(stringValues[3]); - - System.arraycopy(values, 0, brightPointDarkPoint, 0, 4); - } catch (NumberFormatException nfe) { - // if anything goes wrong, just boot! Too bad, pilot error! - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.setProperty(prefix + HOW_BRIGHT_PROPERTY, Double.toString(howBright)); - props.setProperty(prefix + HOW_DARK_PROPERTY, Double.toString(howDark)); - - StringBuilder buf = new StringBuilder(); - buf.append(Double.toString(brightPointDarkPoint[0])).append(" "); - buf.append(Double.toString(brightPointDarkPoint[1])).append(" "); - buf.append(Double.toString(brightPointDarkPoint[2])).append(" "); - buf.append(Double.toString(brightPointDarkPoint[3])); - props.setProperty(prefix + BRIGHT_DARK_PERCENTAGE_PROPERTY, buf.toString()); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, props, MapBeanGradientBackgroundPolicy.class, HOW_BRIGHT_PROPERTY, "Brightness", "How many times brighter than the source color is the bright point", null); - PropUtils.setI18NPropertyInfo(i18n, props, MapBeanGradientBackgroundPolicy.class, HOW_DARK_PROPERTY, "Darkness", "How many times darker than the source color is the dark point", null); - PropUtils.setI18NPropertyInfo(i18n, props, MapBeanGradientBackgroundPolicy.class, BRIGHT_DARK_PERCENTAGE_PROPERTY, "Location", "The location of the bright/dark points in percentage (bright x, bright y, dark x, dark y)", null); - return props; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/MapBeanRepaintPolicy.java b/src/core/src/main/java/com/bbn/openmap/MapBeanRepaintPolicy.java deleted file mode 100644 index 53caaa1e7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapBeanRepaintPolicy.java +++ /dev/null @@ -1,59 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MapBeanRepaintPolicy.java,v $ -// $RCSfile: MapBeanRepaintPolicy.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Graphics; - -/** - * A MapBeanRepaintPolicy is a policy object that makes decisions on - * how a MapBean handles repaint requests from a layer. It can forward - * them on to the Swing thread by calling MapBean.repaint(), or ignore - * them until conditions that it considers valuable are met. - */ -public interface MapBeanRepaintPolicy extends Cloneable { - - /** - * Set the MapBean to call repaint on when a layer requests it. - */ - public void setMap(MapBean mb); - - /** - * Take some action based on a repaint request from this - * particular layer. - */ - public void repaint(Layer layer); - - /** - * A hook for the RepaintPolicy to make any adjustments to the - * java.awt.Graphics object before sending the Graphics object to - * the layers for painting. Gives the policy a chance to make - * rendering hint changes on Graphic2D objects, setting - * anti-aliasing configurations, etc. - */ - public Graphics modifyGraphicsForPainting(Graphics graphics); - - /** - * Provide a configured copy (except for the MapBean). - */ - public Object clone(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/MapHandler.java b/src/core/src/main/java/com/bbn/openmap/MapHandler.java deleted file mode 100644 index 226f285dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapHandler.java +++ /dev/null @@ -1,334 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MapHandler.java,v $ -// $RCSfile: MapHandler.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/09/28 19:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.beancontext.BeanContextMembershipListener; -import java.beans.beancontext.BeanContextServicesSupport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The MapHandler is an extension of the BeanContextServicesSupport, with the - * added capability of being able to set the policy on handling - * SoloMapComponents. The MapHandler can be thought of as a generic map - * container, that contains the MapBean, all the layers that may be part of the - * map, and all the gesture handling components for that map. Given that - * definition, there are some OpenMap components that need to have a one-to-one - * relationship with a MapHandler. For instance, a MapHandler should only - * contain one MapBean, LayerHandler, MouseDelegator and PropertyHandler. - * Objects that have this one-to-one relationship with the MapHandler should - * implement the SoloMapComponent interface, so the MapHandler can control what - * happens when more than one instance of a particular SoloMapComponent type is - * added to the MapBean. Other objects that get added to the MapHandler that - * hook up with SoloMapComponents should expect that only one version of those - * components should be used - if another instance gets added to the MapHandler, - * the objects should disconnect from the SoloMapComponent that they are using, - * and connect to the new object added. With this behavior, these objects can - * gracefully adapt to the SoloMapComponent policies that are set in the - * MapHandler: - * - *
    - * - *
  • You can set the MapHandler with the policy to let duplicate - * SoloMapComponents be added to the MapHandler. If a duplicate SoloMapComponent - * is added, then all objects using that type of SoloMapComponent should - * gracefully use the latest version added. - * - *
  • The MapHandler can have to policy to limit the addition of duplicate - * SoloMapComponents. If a duplicate is added, and exception is thrown. In this - * case, the original SoloMapComponent must be removed from the MapHandler - * before the second instance is added. - * - *
- */ -public class MapHandler extends BeanContextServicesSupport { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.MapHandler"); - - protected SoloMapComponentPolicy policy; - protected boolean DEBUG = false; - protected boolean addInProgress = false; - protected List addLaterVector = null; - - public MapHandler() { - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Set the policy of behavior for the MapHandler on how it should act when - * multiple instances of a certain SoloMapComponents are added to it. - * - * @see SoloMapComponentReplacePolicy - * @see SoloMapComponentRejectPolicy - */ - public void setPolicy(SoloMapComponentPolicy smcp) { - policy = smcp; - } - - /** - * Get the policy that sets the behavior of the MapHandler when it - * encounters the situation of multiple instances of a particular - * SoloMapComponent. - */ - public SoloMapComponentPolicy getPolicy() { - if (policy == null) { - policy = new SoloMapComponentRejectPolicy(); - } - return policy; - } - - protected synchronized void setAddInProgress(boolean value) { - addInProgress = value; - } - - protected synchronized boolean isAddInProgress() { - return addInProgress; - } - - /** - * Call made from the add() method for objects that added when another - * object was being added, setting up a ConcurrentModificationException - * condition. This is a coping mechanism. - */ - protected synchronized void addLater(Object obj) { - if (addLaterVector == null) { - addLaterVector = new ArrayList(); - } - if (DEBUG) { - logger.fine("=== Adding " + obj.getClass().getName() + " to list for later addition"); - } - addLaterVector.add(obj); - } - - /** - * Call to add any objects on the addLaterVector to the MapHandler. These - * are objects that were previously added which another object was being - * added, setting up a ConcurrentModificationException condition. Part of - * the coping mechanism. - */ - protected synchronized void purgeLaterList() { - if (addLaterVector != null && !addInProgress) { - - Object[] objs = addLaterVector.toArray(); - // Nulling out before the iteration avoids a stack overflow loop - addLaterVector = null; - - for (Object obj : objs) { - if (DEBUG) { - logger.fine("+++ Adding " + obj.getClass().getName() - + " to MapHandler from later list."); - } - add(obj); - } - } - } - - /** - * Add an object to the MapHandler BeanContextSupport. Uses the current - * SoloMapComponentPolicy to handle the SoloMapComponents added. May throw - * MultipleSoloMapComponentException if the policy is a - * SoloMapComponentRejectPolicy and the SoloMapComponent is a duplicate type - * of another component already added. - * - * @param obj the map component to nest within this BeanContext. - * @return true if addition is successful, false if not. - */ - public synchronized boolean add(Object obj) { - try { - boolean passedSoloMapComponentTest = true; - if (obj instanceof SoloMapComponent) { - try { - passedSoloMapComponentTest = getPolicy().canAdd(this, obj); - } catch (MultipleSoloMapComponentException msmce) { - logger.fine(msmce.getMessage()); - return false; - } - } - - if (obj != null && passedSoloMapComponentTest) { - - if (addInProgress) { - if (DEBUG) { - logger.fine("MapHandler: Attempting to add while add in progress, adding [" - + obj.getClass().getName() + "]object to list"); - } - addLater(obj); - } else { - addInProgress = true; - boolean ret = super.add(obj); - addInProgress = false; - purgeLaterList(); - return ret; - } - } - - } catch (java.util.ConcurrentModificationException cme) { - if (obj != null) { - logger.info("MapHandler caught ConcurrentModificationException when adding [" - + obj.getClass().getName() - + "]. The addition of this component to the MapHandler is causing some other component to attempt to be added as well, and the coping mechanism in the MapHandler is not handling it well."); - if (DEBUG) { - cme.printStackTrace(); - } - addLater(obj); - addInProgress = false; - } - } - return false; - } - - public String toString() { - return getClass().getName(); - } - - /** - * Given a class name, find the object in the MapHandler. If the class is - * not a SoloMapComponent and there are more than one of them in the - * MapHandler, you will get the first one found. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Object get(String classname) { - Class someClass = null; - try { - someClass = Class.forName(classname); - } catch (ClassNotFoundException cnfe) { - } - - return get(someClass); - } - - /** - * Given a Class, find the object in the MapHandler. If the class is not a - * SoloMapComponent and there are more than one of them in the MapHandler, - * you will get the first one found. - */ - public T get(Class someClass) { - Collection collection = getAll(someClass); - - for (T first : collection) { - return first; - } - - return null; - } - - /** - * Given a Class name, find all the objects in the MapHandler that are - * assignment-compatible object of that Class. A Collection is always - * returned, although it may be empty. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Collection getAll(String classname) { - Class someClass = null; - try { - someClass = Class.forName(classname); - } catch (ClassNotFoundException cnfe) { - } - - return getAll(someClass); - } - - /** - * Given a Class, find all the objects in the MapHandler that are - * assignment-compatible with that Class. A Collection is always returned, - * although it may be empty. - */ - public Collection getAll(Class someClass) { - Collection collection = new LinkedList(); - - if (someClass != null) { - for (Object someObj : this.copyChildren()) { - if (someClass.isInstance(someObj)) { - collection.add(someClass.cast(someObj)); - } - } - } - - return collection; - } - - /** - * Added because apparently, the BeanContext doesn't check to see if the - * object is also a membership listener to remove it from that list. This - * method removes the object from that list, too, if it is a - * BeanContextMembershipListener. - */ - public boolean remove(Object obj) { - boolean ret = super.remove(obj); - if (obj instanceof BeanContextMembershipListener) { - super.removeBeanContextMembershipListener((BeanContextMembershipListener) obj); - } - return ret; - } - - /** - * Method to call with an object you don't want to add to this MapHandler, - * but you want to make it available to all the MapHandlerChildren in it. - * - * @param obj - */ - public void present(Object obj) { - for (Object someObj : this.toArray()) { - if (someObj instanceof MapHandlerChild) { - ((MapHandlerChild) someObj).findAndInit(obj); - } - } - } - - /** - * Create an iterator copy, to avoid ConcurrentModificationExceptions in the - * MapHandler if one of the components wants to add more components when the - * MapHandler is set as the BeanContext on them. - */ - @SuppressWarnings("unchecked") - public Iterator iterator() { - return new ArrayList<>(this).iterator(); - } - - /** - * Calls dispose() on the contained MapBean and removes all objects from - * BeanContext. - */ - public void dispose() { - addLaterVector = null; - - MapBean mb = (MapBean) get(com.bbn.openmap.MapBean.class); - if (mb != null) { - remove(mb); - mb.dispose(); - } - - for (Object obj : this.copyChildren()) { - remove(obj); - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/MapHandlerChild.java b/src/core/src/main/java/com/bbn/openmap/MapHandlerChild.java deleted file mode 100644 index 786e7398c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MapHandlerChild.java +++ /dev/null @@ -1,256 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MapHandlerChild.java,v $ -// $RCSfile: MapHandlerChild.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; - -/** - * MapHandlerChild shows you all the methods you need to add to an object for it - * be a good member of the MapHandler. The MapHandler is actually a BeanContext - * object, which is simply a container for a bunch of objects that may be - * interested in other objects. If you are using this object as a model to - * figure out what methods to add to other objects, there are a couple of things - * to notice. First, java.awt.Components already have a PropertyChangeSupport - * object in it, so you don't need to implement the methods that deal with - * property changes. For javax.swing.JComponents, they have - * VetoablePropertySupport build in, but that object doesn't handle certain - * methods needed by the BeanContextChild, most notably the - * (add/remove)VetoableChangeListener() methods with a specific property as an - * argument. - *

- * - * When you design a MapHandlerChild, you should make it comfortable running - * without references to objects it depends on. It should wait patiently for the - * other objects to be added to the MapHandler, and then do the work itself to - * hook up. It should also listen for those objects to be removed from the - * MapHandler, disengage gracefully, and wait patiently until it finds something - * else to hook up to. - *

- * - * An object does not have to be a MapHandlerChild to be added to the - * MapHandler, but it does need to be one to be able to use it. If you override - * and use the findAndInit(Iterator) method to look for objects, you'll find it - * is called on two different conditions. It's called when this MapHandlerChild - * is added to the MapHandler, and it then receives a list of all the objects - * currently contained in the MapHandler. It is also called when other objects - * are added to the MapHandler. The list then contains objects that have just - * been added. The findAndInit(Object) method has been added to allow subclassed - * objects to call super.findAndInit(Object) to let the super classes handles - * the objects they care about. You don't call the findAndInit(Object) method. - * You override it and implement the method so that you can look for the objects - * you need. - *

- * - * When objects are removed from the BeanContext, the childrenRemoved() method - * is called with a list of objects being removed. Likewise, the - * findAndUndo(Object) method has been added for the benefit of subclasses. - *

- * - * MapHandlerChild objects expect to be added to only one BeanContext. The - * BeanContextChildSupport object detects when it has a different BeanContext - * added to it, and it will fire property change notifications to get itself - * removed from the first BeanContext. - */ -public class MapHandlerChild - implements BeanContextChild, BeanContextMembershipListener, LightMapHandlerChild { - - /** - * A boolean that prevents the BeanContextChild from looking at events from - * BeanContext other than the one it was originally added to. Set to false - * by default. - */ - protected boolean isolated = false; - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(this); - - /** - * This is the method that your object can use to find other objects within - * the MapHandler (BeanContext). This method gets called when the object - * gets added to the MapHandler, or when another object gets added to the - * MapHandler after the object is a member. It's probably better to not - * override this method, just override the findAndUndo(Object) method - * instead. - * - * @param it Iterator to use to go through a list of objects. Find the ones - * you need, and hook yourself up. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * The findAndInit method has been made non-abstract, because it now calls - * this method for every object that is in the iterator it receives. This - * lets subclasses call a method on super classes so they can handle their - * needs as well. - */ - public void findAndInit(Object obj) { - } - - /** - * BeanContextMembershipListener method. Called when a new object is added - * to the BeanContext of this object. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - if (!isolated || bcme.getBeanContext().equals(getBeanContext())) { - findAndInit(bcme.iterator()); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * The childrenRemoved has been changed to go through its iterator to call - * this method with every object. This lets subclasses call this method on - * their super class, so it can handle what it needs to with objects it may - * be interested in. - */ - public void findAndUndo(Object obj) { - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Adds this object as a - * BeanContextMembership listener, set the BeanContext in this objects - * BeanContextSupport, and receives the initial list of objects currently - * contained in the BeanContext. - */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - - if (in_bc != null) { - if (!isolated || beanContextChildSupport.getBeanContext() == null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } else { - beanContextChildSupport.setBeanContext(in_bc); - } - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to add a listener to this object's property. You don't need this function - * for objects that extend java.awt.Component. - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to remove a listener to this object's property. You don't need this - * function for objects that extend java.awt.Component. - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to add a listener to this object's property. This listener wants to have - * the right to veto a property change. - */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to remove a listener to this object's property. The listener has the - * power to veto property changes. - */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to fire a property change. You don't need this function for objects that - * extend java.awt.Component. - */ - public void firePropertyChange(String name, Object oldValue, Object newValue) { - beanContextChildSupport.firePropertyChange(name, oldValue, newValue); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - public boolean isIsolated() { - return isolated; - } - - public void setIsolated(boolean isolated) { - this.isolated = isolated; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/MouseDelegator.java b/src/core/src/main/java/com/bbn/openmap/MouseDelegator.java deleted file mode 100644 index f27fc29ab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MouseDelegator.java +++ /dev/null @@ -1,673 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MouseDelegator.java,v $ -// $RCSfile: MouseDelegator.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/12/16 14:14:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.NavMouseMode; -import com.bbn.openmap.event.NullMouseMode; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.util.Debug; - -/** - * The MouseDelegator manages the MapMouseModes that handle MouseEvents on the - * map. There should only be one MouseDelegator within a MapHandler. - * - * @see com.bbn.openmap.event.MapMouseMode - * @see com.bbn.openmap.event.AbstractMouseMode - * @see com.bbn.openmap.event.NavMouseMode - * @see com.bbn.openmap.event.SelectMouseMode - */ -public class MouseDelegator - implements PropertyChangeListener, java.io.Serializable, BeanContextChild, BeanContextMembershipListener, SoloMapComponent { - - private static final long serialVersionUID = 1L; - public final static transient String ActiveModeProperty = "NewActiveMouseMode"; - public final static transient String MouseModesProperty = "NewListOfMouseModes"; - /** - * A property string used when firing PropertyChangeSupport notifications - * when the mouse mode is acting as proxy for another mouse mode. - */ - public static final String ProxyMouseModeProperty = "MouseModeProxy"; - - /** - * The active MapMouseMode. - */ - protected transient MapMouseMode activeMouseMode = null; - - /** - * The registered MapMouseModes. - */ - protected transient Vector mouseModes = new Vector(0); - - /** - * The MapBean. - */ - protected transient MapBean map; - - /** - * Need to keep a safe copy of the current layers that are part of the - * MapBean in case a MouseMode gets added before the MapBean is set in the - * MouseDelegator. Without this, you can get into a situation where new - * MapMouseModes don't know about layers until the MouseDelegator receives a - * property change event from the MapBean. - */ - protected Layer[] currentLayers = null; - - /** - * PropertyChangeSupport for handling listeners. - */ - protected PropertyChangeSupport pcSupport = new PropertyChangeSupport(this); - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Construct a MouseDelegator with an associated MapBean. - * - * @param map MapBean - */ - public MouseDelegator(MapBean map) { - setMap(map); - } - - /** - * Construct a MouseDelegator without an associated MapBean. You will need to - * set the MapBean via setMap(). - * - * @see #setMap - */ - public MouseDelegator() { - this(null); - } - - /** - * Set the associated MapBean. - * - * @param mapbean MapBean - */ - public void setMap(MapBean mapbean) { - if (map != null) { - map.removePropertyChangeListener(this); - setInactive(activeMouseMode); - } - - map = mapbean; - if (map != null) { - map.addPropertyChangeListener(this); - setActive(activeMouseMode); - } - } - - /** - * Get the associated MapBean. - * - * @return MapBean - */ - public MapBean getMap() { - return map; - } - - // ---------------------------------------------------------------------- - // - // Mouse Event handling support - // - // ---------------------------------------------------------------------- - - /** - * Returns the ID string for the active Mouse Mode. - * - * @return String ID of the active mouse mode. - */ - public String getActiveMouseModeID() { - if (activeMouseMode != null) - return activeMouseMode.getID(); - else - return null; - } - - /** - * Sets the mouse mode to the mode with the same ID string. If none of the - * MouseEventDelagates have a matching ID string, the mode is not changed.
- * The map mouse cursor is set to the recommended cursor retrieved from the - * active mouseMode. - * - * @param MouseModeID the string ID of the mode to set active. - */ - public void setActiveMouseModeWithID(String MouseModeID) { - if (MouseModeID == null) { - Debug.error("MouseDelegator:setActiveMouseModeWithID() - null value"); - return; - } - - MapMouseMode oldActive = activeMouseMode; - setInactive(activeMouseMode); - - for (MapMouseMode med : mouseModes) { - if (MouseModeID.equals(med.getID())) { - setActive(med); - if (Debug.debugging("mousemode")) { - Debug.output("MouseDelegator.setActiveMouseModeWithID() setting new mode to mode " + med.getID()); - } - break; - } - } - - firePropertyChange(ActiveModeProperty, oldActive, activeMouseMode); - } - - /** - * Returns the mouse mode delegate that is active at the moment. - * - * @return MapMouseMode the active mouse mode - */ - public MapMouseMode getActiveMouseMode() { - return activeMouseMode; - } - - /** - * Sets the active mouse mode. If the MapMouseMode is not a member of the - * current mouse modes, it is added to the list.
- * The map mouse cursor is set to the recommended cursor retrieved from the - * active mouseMode. - * - * @param aMed a MapMouseMode to make active. - */ - public void setActiveMouseMode(MapMouseMode aMed) { - if (aMed == null) { - Debug.error("MouseDelegator:setActiveMouseMode() - null value"); - return; - } - MapMouseMode oldActive = activeMouseMode; - boolean isAlreadyAMode = false; - - for (MapMouseMode med : mouseModes) { - // Need to go through the modes, turn off the other active - // mode, and turn on this one. - if (aMed.getID().equals(med.getID())) { - isAlreadyAMode = true; - } - } - - if (!isAlreadyAMode) { - addMouseMode(aMed); - } - - setActive(aMed); - - firePropertyChange(ActiveModeProperty, oldActive, activeMouseMode); - } - - /** - * Returns an array of MapMouseModes that are available to the MapBean. - * - * @return an array of MapMouseModes. - */ - public MapMouseMode[] getMouseModes() { - int nMouseModes = mouseModes.size(); - if (nMouseModes == 0) - return (new MapMouseMode[0]); - MapMouseMode[] result = new MapMouseMode[nMouseModes]; - for (int i = 0; i < nMouseModes; i++) { - result[i] = (MapMouseMode) mouseModes.elementAt(i); - } - return result; - } - - /** - * Used to set the mouseModes available to the MapBean. The Delegator drops - * all references to any mouseModes it knew about previously. It also sets - * the index of the array to be the active mouse mode.
- * The map mouse cursor is set to the recommended cursor retrieved from the - * active mouseMode. - * - * @param meds an array of MapMouseModes - * @param activeIndex which mouse mode to make active - */ - public void setMouseModes(MapMouseMode[] meds, int activeIndex) { - mouseModes.clear(); - MapMouseMode oldActive = activeMouseMode; - for (int i = 0; i < meds.length; i++) { - mouseModes.add(meds[i]); - - if (i == activeIndex) { // activate the right mode - setActive(meds[i]); - } - } - - firePropertyChange(MouseModesProperty, null, mouseModes); - firePropertyChange(ActiveModeProperty, oldActive, activeMouseMode); - } - - /** - * Used to set the mouseModes available to the MapBean. The MapBean drops all - * references to any mouseModes it knew about previously. The meds[0] mode is - * made active, by default. - * - * @param meds an array of MapMouseModes - */ - public void setMouseModes(MapMouseMode[] meds) { - setMouseModes(meds, 0); - } - - /** - * Adds a MapMouseMode to the MouseMode list. Does not make it the active - * mode. - * - * @param med the MouseEvent Delegate to add. - */ - public void addMouseMode(MapMouseMode med) { - - if (med != null) { - mouseModes.addElement(med); - // All of the MouseModes will think they are active, but - // the Delegator will only pass events to the one it - // thinks is... - if (mouseModes.size() == 1) { - setActive(med); - } - - if (currentLayers != null) { - setupMouseModeWithLayers(med, currentLayers); - } - - firePropertyChange(MouseModesProperty, null, mouseModes); - } - } - - /** - * Removes a particular MapMouseMode from the MouseMode list. - * - * @param med the MapMouseMode that should be removed. - */ - public void removeMouseMode(MapMouseMode med) { - boolean needToAdjustActiveMode = false; - - if (med == null) { - return; - } - - if (med.equals(activeMouseMode)) { - needToAdjustActiveMode = true; - setInactive(med); - } - - for (MapMouseMode checkMM : mouseModes) { - if (med.equals(checkMM)) { - med.removeAllMapMouseListeners(); - - } - // Set the first mode to the active one, if deleting the - // active one. - else if (needToAdjustActiveMode) { - setActive(checkMM); - needToAdjustActiveMode = false; - } - } - - mouseModes.remove(med); - - firePropertyChange(MouseModesProperty, null, mouseModes); - } - - /** - * Removes a particular MapMouseMode from the MouseMode list, with the ID - * given. - * - * @param id the ID of the MapMouseMode that should be removed - */ - public void removeMouseMode(String id) { - for (MapMouseMode med : mouseModes) { - if (id.equals(med.getID())) { - removeMouseMode(med); - break; - } - } - } - - /** - * Sets the three default OpenMap mouse modes. These modes are: NavMouseMode - * (Map Navigation), the SelectMouseMode (MouseEvents go to Layers), and - * NullMouseMode (MouseEvents are ignored). - */ - public void setDefaultMouseModes() { - MapMouseMode[] modes = new MapMouseMode[3]; - modes[0] = new NavMouseMode(true); - modes[1] = new SelectMouseMode(true); - modes[2] = new NullMouseMode(); - - setMouseModes(modes); - } - - /** - * PropertyChangeListenter Interface method. - * - * @param evt PropertyChangeEvent - */ - public void propertyChange(PropertyChangeEvent evt) { - String property = evt.getPropertyName(); - if (property == MapBean.LayersProperty) { - // make a safe copy of the layers that are part of the - // MapBean - Layer[] layers = (Layer[]) evt.getNewValue(); - currentLayers = new Layer[layers.length]; - System.arraycopy(layers, 0, currentLayers, 0, layers.length); - - setupMouseModesWithLayers(currentLayers); - } - - if (property.equals(ProxyMouseModeProperty)) { - - Object newObj = evt.getNewValue(); - if (newObj instanceof MapMouseMode) { - map.setCursor(((MapMouseMode) newObj).getModeCursor()); - } else { - map.setCursor(getActiveMouseMode().getModeCursor()); - } - - firePropertyChange(ProxyMouseModeProperty, evt.getOldValue(), newObj); - } - } - - /** - * Does the work putting the layers given on each mouse mode's list of layers - * to notify if it becomes active. - */ - public void setupMouseModesWithLayers(Layer[] layers) { - for (int j = 0; j < mouseModes.size(); j++) { - // Clear out the old listeners first - MapMouseMode mmm = (MapMouseMode) mouseModes.elementAt(j); - setupMouseModeWithLayers(mmm, layers); - } - } - - /** - * Gives a MapMouseMode access to a Layer[], and it will find the layers that - * want to listen to it and will forward events to them if it is added to the - * MapBean as a MouseListener or a MouseMotionListener. - * - * @param mmm MapMouseMode - * @param layers Layer[] - */ - public void setupMouseModeWithLayers(MapMouseMode mmm, Layer[] layers) { - mmm.removeAllMapMouseListeners(); - for (int i = 0; i < layers.length; i++) { - // Add the listeners from each layer to the mouse mode. - MapMouseListener tempmml = null; - - if (layers[i] != null) { - tempmml = layers[i].getMapMouseListener(); - } - - if (tempmml == null) { - continue; - } - String[] services = tempmml.getMouseModeServiceList(); - if (services != null) { - for (int k = 0; k < services.length; k++) { - if (mmm.getID().equals(services[k])) { - mmm.addMapMouseListener(tempmml); - if (Debug.debugging("mousemode")) { - Debug.output("MouseDelegator.setupMouseModeWithLayers():" + " layer = " + layers[i].getName() + " service = " - + mmm.getID()); - } - break; - } - } - } - } - } - - /** - * Set the active MapMouseMode. This sets the MapMouseMode of the associated - * MapBean. - * - * @param mm MapMouseMode - */ - public void setActive(MapMouseMode mm) { - if (activeMouseMode != null) { - setInactive(activeMouseMode); - } - - activeMouseMode = mm; - - if (map != null && activeMouseMode != null) { - if (Debug.debugging("mousemode")) { - Debug.output("MouseDelegator.setActive(): " + mm.getID()); - } - map.addMouseListener(mm); - map.addMouseMotionListener(mm); - map.addMouseWheelListener(mm); - map.addPaintListener(mm); - map.setCursor(activeMouseMode.getModeCursor()); - if (mm instanceof ProjectionListener) { - map.addProjectionListener((ProjectionListener) mm); - } - activeMouseMode.setActive(true); - activeMouseMode.addPropertyChangeListener(this); - } - } - - /** - * Deactivate the MapMouseMode. - * - * @param mm MapMouseMode. - */ - public void setInactive(MapMouseMode mm) { - if (map != null) { - map.removeMouseListener(mm); - map.removeMouseMotionListener(mm); - map.removeMouseWheelListener(mm); - map.removePaintListener(mm); - // should set map's cursor to some default value?? - if (mm instanceof ProjectionListener) { - map.removeProjectionListener((ProjectionListener) mm); - } - } - if (activeMouseMode == mm) { - activeMouseMode = null; - } - if (mm != null) { - mm.setActive(false); - mm.removePropertyChangeListener(this); - } - } - - /** - * Eventually gets called when the MouseDelegator is added to the - * BeanContext, and when other objects are added to the BeanContext anytime - * after that. The MouseDelegator looks for a MapBean to manage MouseEvents - * for, and MouseModes to use to manage those events. If a MapBean is added - * to the BeanContext while another already is in use, the second MapBean - * will take the place of the first. - * - * @param it iterator to use to go through the new objects in the - * BeanContext. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Called when an object should be evaluated by the MouseDelegator to see if - * it is needed. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - Debug.message("mousedelegator", "MouseDelegator found a map."); - setMap((MapBean) someObj); - } - if (someObj instanceof MapMouseMode) { - Debug.message("mousedelegator", "MouseDelegator found a MapMouseMode."); - addMouseMode((MapMouseMode) someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when new objects are added to - * the parent BeanContext. - * - * @param bcme event that contains an iterator that can be used to go through - * the new objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when objects have been - * removed from the parent BeanContext. The MouseDelegator looks for the - * MapBean it is managing MouseEvents for, and any MouseModes that may be - * removed. - * - * @param bcme event that contains an iterator that can be used to go through - * the removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * Called by childrenRemoved. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - if (getMap() == (MapBean) someObj) { - Debug.message("mousedelegator", "MouseDelegator: removing the map."); - setMap(null); - } - } - if (someObj instanceof MapMouseMode) { - Debug.message("mousedelegator", "MouseDelegator: removing a MapMouseMode."); - removeMouseMode((MapMouseMode) someObj); - } - - if (someObj == this) { - dispose(); - } - } - - public void dispose() { - if (mouseModes != null) { - mouseModes.clear(); - } - currentLayers = null; - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** Method for BeanContextChild interface. */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - pcSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - pcSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - // This function is why we don't use the - // BeanContextChildSupport PropertyChangeSupport object. - pcSupport.addPropertyChangeListener(listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - // This function is why we don't use the - // BeanContextChildSupport PropertyChangeSupport object. - pcSupport.removePropertyChangeListener(listener); - } - - public void firePropertyChange(String property, Object oldObj, Object newObj) { - - pcSupport.firePropertyChange(property, oldObj, newObj); - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/MultipleSoloMapComponentException.java b/src/core/src/main/java/com/bbn/openmap/MultipleSoloMapComponentException.java deleted file mode 100644 index 5ed0b9471..000000000 --- a/src/core/src/main/java/com/bbn/openmap/MultipleSoloMapComponentException.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MultipleSoloMapComponentException.java,v $ -// $RCSfile: MultipleSoloMapComponentException.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -/** - * An Exception indicating that an attempt was made to add a duplicate - * SoloMapComponent to BeanContext. - */ -public class MultipleSoloMapComponentException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Construct an exception without a reason. - */ - public MultipleSoloMapComponentException() { - super(); - } - - /** - * Construct an exception with a reason string. - * - * @param s the reason for the exception - */ - public MultipleSoloMapComponentException(String s) { - super(s); - } - - /** - * Construct an exception, generating a reason from the - * conflicting classes. - * - * @param c1 the class that was being added - * @param c2 the class that already exists in the BeanContext - */ - public MultipleSoloMapComponentException(Class c1, Class c2) { - super("Class " + c1 + " conflicts with Class " + c2); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/OMComponent.java b/src/core/src/main/java/com/bbn/openmap/OMComponent.java deleted file mode 100644 index 78251918b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/OMComponent.java +++ /dev/null @@ -1,144 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/OMComponent.java,v $ -// $RCSfile: OMComponent.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.util.Properties; - -import com.bbn.openmap.util.I18n; - -/** - * A OMComponent is an OpenMap component that does two basic things: it is a - * MapHandlerChild, so it knows how to use the MapHandler to find other - * components it needs, and it is a PropertyConsumer, so it can be configured by - * a set of Properties. An OMComponent is a perfect candidate to be created by - * being listed in the openmap.components property of the openmap.properties - * file. Override the findAndInit() and findAndUndo() methods to test for and - * connect to other components added to the MapHandler. - */ -public class OMComponent - extends MapHandlerChild - implements PropertyConsumer { - - /** - * All OMComponents have access to an I18n object, which is provided by the - * Environment. - */ - protected I18n i18n = Environment.getI18n(); - - /** - * Token uniquely identifying this component in the application properties. - */ - protected String propertyPrefix = null; - - /** - * Sets the properties for the OMComponent. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the OMComponent. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - setPropertyPrefix(prefix); - - // In a subclass, you can use this to get "" if the prefix - // isn't defined, or "prefix." if it is. Either way, you can - // then append the realPrefix with wild abandon... - // String realPrefix = - // PropUtils.getScopedPropertyPrefix(prefix); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the OMComponent. If the component has a propertyPrefix - * set, the property keys should have that prefix plus a separating '.' - * prepended to each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - // String prefix = PropUtils.getScopedPropertyPrefix(this); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix string - */ - public String getPropertyPrefix() { - return propertyPrefix; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/ProjectionPainter.java b/src/core/src/main/java/com/bbn/openmap/ProjectionPainter.java deleted file mode 100644 index 19c537cc0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/ProjectionPainter.java +++ /dev/null @@ -1,66 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/ProjectionPainter.java,v $ -// $RCSfile: ProjectionPainter.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Graphics; - -import com.bbn.openmap.proj.Projection; - -/** - * The ProjectionPainter interface is intended for objects that can - * manage graphics and draw them into a Java Graphics object. The idea - * is that the ProjectionPainter, all within one thread, gathers the - * graphics that reside within the projection, and render them into - * the Graphics that has been set up for that projection. The height - * and width of the projection should match the Graphics height and - * width, in case some of the graphics from the ProjectionPainter - * depend on them to place themselves within the Graphics. - *

- * This is different from the usual paradigm of OpenMap components. - * Since OpenMap components are Swing components, they usually ready - * themselves, call repaint() on themselves, and then wait for the - * Swing thread to call paint and supply a Graphics object. This leads - * to uncertainty as to when the painting is actually completed, which - * can be an issue if you are trying to create an image, or something - * like that. - *

- * Some layers kick off a SwingWorker thread to do the work. If a - * layer is modified to implement this interface, the layer should do - * all the graphics collection work and rendering in the calling - * thread, so the caller knows that the contribution to the map from - * this ProjectionPainter is complete. - */ -public interface ProjectionPainter { - - /** - * Given a projection and Graphics, paint graphic objects inside - * the Graphics. When this function returns, everything should be - * all set. - * - * @param proj a com.bbn.openmap.proj.Projection that describes a - * map. - * @param g a java.awt.Graphics to draw into. - */ - public void renderDataForProjection(Projection proj, Graphics g); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/PropertyConsumer.java b/src/core/src/main/java/com/bbn/openmap/PropertyConsumer.java deleted file mode 100644 index 6a44ee726..000000000 --- a/src/core/src/main/java/com/bbn/openmap/PropertyConsumer.java +++ /dev/null @@ -1,143 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/PropertyConsumer.java,v $ -// $RCSfile: PropertyConsumer.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.util.Properties; - -/** - * A PropertyConsumer is an interface defining an object that is - * configured by a Properties object, containing property keys and - * values that is expected by it. - */ -public interface PropertyConsumer { - - /** - * Key in the associated propertyInfo object. Holds a list of - * property names, which should be displayed and editable when - * configuring a PropertyConsumer object interactively. List is - * space separated and the order is the order in which the - * properties will appear (initProperties). - */ - public static final String initPropertiesProperty = "initProperties"; - - /** - * Keyword for PropertyEditor class from PropertyInfo Property - * object (editor). - */ - public static final String EditorProperty = "editor"; - /** - * Scoped keyword for PropertyEditor class from PropertyInfo - * Property object, same as EditorProperty with a period in front - * (.editor). - */ - public static final String ScopedEditorProperty = ".editor"; - /** - * Scoped keyword for PropertyEditor class from PropertyInfo - * Property object, to scope the label for the property as - * displayed in the Inspector (label). - */ - public static final String LabelEditorProperty = ".label"; - - /** - * Method to set the properties in the PropertyConsumer. It is - * assumed that the properties do not have a prefix associated - * with them, or that the prefix has already been set. - * - * @param setList a properties object that the PropertyConsumer - * can use to retrieve expected properties it can use for - * configuration. - */ - public void setProperties(Properties setList); - - /** - * Method to set the properties in the PropertyConsumer. The - * prefix is a string that should be prepended to each property - * key (in addition to a separating '.') in order for the - * PropertyConsumer to uniquely identify properties meant for it, - * in the midst of of Properties meant for several objects. - * - * @param prefix a String used by the PropertyConsumer to prepend - * to each property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix - * had already been set, then the prefix passed in should - * replace that previous value. - * @param setList a Properties object that the PropertyConsumer - * can use to retrieve expected properties it can use for - * configuration. - */ - public void setProperties(String prefix, Properties setList); - - /** - * Method to fill in a Properties object, reflecting the current - * values of the PropertyConsumer. If the PropertyConsumer has a - * prefix set, the property keys should have that prefix plus a - * separating '.' prepended to each property key it uses for - * configuration. - * - * @param getList a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getProperties(Properties getList); - - /** - * Method to fill in a Properties object with values reflecting - * the properties able to be set on this PropertyConsumer. The key - * for each property should be the raw property name (without a - * prefix) with a value that is a String that describes what the - * property key represents, along with any other information about - * the property that would be helpful (range, default value, - * etc.). - * - * @param list a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list); - - /** - * Set the property key prefix that should be used by the - * PropertyConsumer. The prefix, along with a '.', should be - * prepended to the property keys known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix); - - /** - * Get the property key prefix that is being used to prepend to - * the property keys for Properties lookups. - * - * @return the prefix string - */ - public String getPropertyPrefix(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/PropertyHandler.java b/src/core/src/main/java/com/bbn/openmap/PropertyHandler.java deleted file mode 100644 index 0ad03281f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/PropertyHandler.java +++ /dev/null @@ -1,1680 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/PropertyHandler.java,v $ -// $RCSfile: PropertyHandler.java,v $ -// $Revision: 1.29 $ -// $Date: 2008/02/28 23:36:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.geom.Point2D; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.TreeSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressListener; -import com.bbn.openmap.event.ProgressSupport; -import com.bbn.openmap.gui.ProgressListenerGauge; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The PropertyHandler object is the organizer of properties, looking for - * settings on how to configure OpenMap components. It is designed to look - * through a series of locations to find properties files, loading them in - * order. If there is a name conflict for a property, the last version of the - * property set is the one that gets used. This object isn't really interested - * in hooking up with other objects. It's assumed that many objects will want to - * contact this object, and find the properties that apply to them. There is one - * exception this: When components start implementing the PropertyProvider - * interface, and the PropertyHandler becomes capable of creating an properties - * file, then the PropertyHandler will be able to use the BeanContext to query - * PropertyProviders to get their properties to put in the properties file. - *

- * - * The PropertyHandler looks in several places for an openmap.properties file: - *

    - *
  • as a resource in the code base. - *
  • in the configDir set as a system property at runtime. - *
  • in the user's home directory. - *
- * - * For each properties file, a check is performed to look within for an include - * property containing a marker name list. That list is parsed, and each item is - * checked (markerName.URL) for an URL to another properties file. - *

- * - * Also significant, the PropertyHandler can be given a BeanContext to load - * components. For this, the openmap.components property contains a marker name - * list for openmap objects. Each member of the list is then used to look for - * another property (markername.class) which specifies which class names are to - * be instantiated and added to the BeanContext. Intelligent components are - * smart enough to wire themselves together. Order does matter for the - * openmap.components property, especially for components that get added to - * lists and menus. Place the components in the list in the order that you want - * components added to the MapHandler. - *

- * - * If the debug.showprogress environment variable is set, the PropertyHandler - * will display a progress bar when it is creating components. If the - * debug.properties file is set, the steps that the PropertyHandler takes in - * looking for property files will be displayed. - *

- * - * If the PropertyHandler is created with an empty constructor or with a null - * Properties object, it will do the search for an openmap.properties file. If - * you don't want it to do that search, create it with an empty Properties - * object. - */ -public class PropertyHandler - extends MapHandlerChild - implements SoloMapComponent { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.PropertyHandler"); - - /** - * All components can have access to an I18n object, which is provided by - * the Environment. - */ - protected transient I18n i18n = Environment.getI18n(); - - /** - * The propertyPrefix can be set to reflect a particular set of properties, - * or for an application. If this variable is not set, 'openmap' will be - * used. This prefix will be placed in front of the default properties file - * that will be sought if a specific properties file is not specified, and - * will also be placed in front of the standard application component - * properties. - */ - protected String propertyPrefix; - - /** - * The appendix for the name of the properties file to read. The - * propertyPrefix will be prepended to this string for the default property - * file search. - */ - public final static String propsFileName = "properties"; - - /** - * The name of the system directory containing a properties file. The - * propertyPrefix.configDir property will be checked for a possible location - * for properties. - */ - public final static String configDirProperty = "configDir"; - - /** - * The property name used to hold a list of marker names. Each marker name - * is used to create another property to look for to create a component to - * add to a BeanContext. For example: - *

- * - *

-     * # if 'openmap' is the PropertyHandler property prefix...
-     * openmap.components=name1 name2 name3
-     * name1.class=com.bbn.openmap.InformationDelegator
-     * name2.class=com.bbn.openmap.MouseDelegator
-     * name3.class=com.bbn.openmap.LayerHandler
-     * 
-     * 
- */ - public final static String componentProperty = "components"; - - /** - * The property name used to hold a list of marker names. Each marker name - * is used to create another property to look for to connect to a URL to - * load a properties file. For example: - *

- * - *

-     * 
-     * openmap.include=name1 name2
-     * name1.URL=http://openmap.bbn.com/props/link.properties
-     * name2.URL=file:///usr/local/openmap/props/shape.properties
-     * 
-     * 
- */ - public final static String includeProperty = "include"; - - /** - * The property name used to hold a file, resource or URL of a file to use - * containing localized properties, like layer names. This is optional, if - * it's not in the openmap.properties file or the properties file being read - * in, an openmap_<localization string>.properties file will be searched - * for in the classpath (i.e. openmap.localized=openmap_en_US.properties). - */ - public final static String localizedProperty = "localized"; - - /** Final openmap properties object. */ - protected Properties properties = new Properties(); - - /** - * Container to hold prefixes for components that have been created, in - * order to determine if duplicates might have been made. Important if - * properties are going to be written out, so that property scoping can - * occur properly. This collection holds prefixes of objects that have been - * created by this PropertyHandler, and also prefixes that have been given - * out on request. - */ - protected Set usedPrefixes = Collections.synchronizedSet(new HashSet()); - - protected ProgressSupport progressSupport; - - /** - * Flag to set whether the PropertyHandler should provide status updates to - * any progress listeners, when it is building components. - */ - protected boolean updateProgress = false; - - /** - * A hashtable to keep track of property prefixes and the objects that were - * created for them. - */ - protected Hashtable prefixLibrarian = new Hashtable<>(); - - protected boolean DEBUG = false; - - /** - * Create a PropertyHandler object that checks in the default order for - * openmap.properties files. It checks for the openmap.properties file as a - * resource, in the configDir if specified as a system property, and lastly, - * in the user's home directory. If you want an empty PropertyHandler that - * doesn't do the search, use the constructor that takes a - * java.util.Properties object and provide it with empty Properties. - */ - public PropertyHandler() { - this(new Builder()); - } - - /** - * Create a PropertyHandler object that checks in the default order for - * openmap.properties files. It checks for the openmap.properties file as a - * resource, in the configDir if specified as a system property, and lastly, - * in the user's home directory. - * - * @param provideProgressUpdates if true, a progress bar will be displayed - * to show the progress of building components. - */ - public PropertyHandler(boolean provideProgressUpdates) { - this(new Builder().setProgressUpdates(provideProgressUpdates)); - } - - /** - * Constructor to take resource name, file path or URL string as argument, - * to create context for a particular map. - */ - public PropertyHandler(String urlString) - throws MalformedURLException, IOException { - this(new Builder().setPropertiesFile(urlString)); - } - - /** - * Constructor to take path (URL) as argument, to create context for a - * particular map. - */ - public PropertyHandler(URL url) - throws IOException { - this(new Builder().setPropertiesFile(url)); - } - - /** - * Constructor to take Properties for configuration, using the default - * "openmap" property prefix for configuration. - * - * @param props - */ - public PropertyHandler(Properties props) { - this(new Builder().setProperties(props)); - } - - public PropertyHandler(Builder builder) { - DEBUG = logger.isLoggable(Level.FINE); - - setPropertyPrefix(builder.propertyPrefix); - setUpdateProgress(builder.update); - - Properties properties = builder.properties; - - if (properties == null) { - searchForAndLoadProperties(); - } else { - init(properties, "URL"); - Environment.init(getProperties()); - } - } - - /** - * Provides this class with the default properties file name to look for. - * Can be overridden by subclasses to return custom file names. - * - * @return String of properties file to search for in classpath, configDir - * and user's home directory. - */ - public String getDefaultPropertyFileName() { - return PropUtils.getScopedPropertyPrefix(Environment.OpenMapPrefix) + PropertyHandler.propsFileName; - } - - /** - * Look for an openmap.properties file in the classpath, configDirectory and - * user home directory, in that order. If any property is duplicated in any - * file found in those locations, the last one in wins. - */ - protected void searchForAndLoadProperties() { - searchForAndLoadProperties(getDefaultPropertyFileName()); - } - - /** - * Look for a properties file as a resource in the classpath, in the config - * directory, and in the user's home directory, in that order. If any - * property is duplicated in any version, last one wins. - * - * @param propsFileName to search for - */ - protected void searchForAndLoadProperties(String propsFileName) { - - Properties tmpProperties = new Properties(); - Properties includeProperties; - Properties localizedProperties; - boolean foundProperties = false; - - if (Debug.debugging("locale")) { - java.util.Locale.setDefault(new java.util.Locale("pl", "PL")); - } - - if (Debug.debugging("showprogress")) { - updateProgress = true; - } - - logger.fine("***** Searching for properties ****"); - - String propertyPrefix = PropUtils.getScopedPropertyPrefix(getPropertyPrefix()); - - // look for openmap.properties file in jar archive(of course - // only in same package as this class) or wherever this - // object's class file lives. - if (DEBUG) { - logger.fine("Looking for " + propsFileName + " in Resources"); - } - - InputStream propsIn = getClass().getResourceAsStream(propsFileName); - // Look in the codebase for applets... - if (propsIn == null && Environment.isApplet()) { - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - - URLClassLoader ucl = URLClassLoader.newInstance(cba); - propsIn = ucl.getResourceAsStream(propsFileName); - } - - if (propsIn == null) { - propsIn = ClassLoader.getSystemResourceAsStream(propsFileName); - - if (propsIn != null && DEBUG) { - logger.fine("Loading properties from System Resources: " + propsFileName); - } - } else { - if (DEBUG) { - logger.fine("Loading properties from file " + propsFileName + " from package of class " + getClass()); - } - } - - if (propsIn != null) { - foundProperties = PropUtils.loadProperties(tmpProperties, propsIn); - init(tmpProperties, "resources"); - tmpProperties.clear(); - } - - if (!foundProperties && (Environment.isApplet() || DEBUG)) { - logger.fine("Unable to locate as resource: " + propsFileName); - } - - // Seems like we can kick out here in event of Applet... - if (Environment.isApplet()) { - Environment.init(getProperties()); - return; - } - - Properties systemProperties; - - try { - systemProperties = System.getProperties(); - } catch (java.security.AccessControlException ace) { - systemProperties = new Properties(); - } - - String configDirProperty = propertyPrefix + PropertyHandler.configDirProperty; - - String openmapConfigDirectory = systemProperties.getProperty(configDirProperty); - - if (openmapConfigDirectory == null) { - List cps = Environment.getClasspathDirs(); - String defaultExtraDir = "share"; - for (String searchLoc : cps) { - File shareDir = new File(searchLoc, defaultExtraDir); - if (shareDir.exists()) { - // Debug.output("Found share directory: " + - // shareDir.getPath()); - openmapConfigDirectory = shareDir.getPath(); - break; - // } else { - // Debug.output("No share directory in: " + - // shareDir.getPath()); - } - } - } - - Environment.addPathToClasspaths(openmapConfigDirectory); - - // in OpenMap config directory - if (DEBUG) { - logger.fine("PropertyHandler: Looking for " + propsFileName + " in configuration directory: " - + (openmapConfigDirectory == null ? "not set" : openmapConfigDirectory)); - } - - // We want foundProperties to reflect if properties have ever - // been found. - foundProperties |= PropUtils.loadProperties(tmpProperties, openmapConfigDirectory, propsFileName); - - // Include properties from config file properties. - includeProperties = getIncludeProperties(tmpProperties.getProperty(propertyPrefix + includeProperty), tmpProperties); - merge(includeProperties, "include file properties", openmapConfigDirectory); - - // OK, now merge the config file properties into the main - // properties - merge(tmpProperties, propsFileName, openmapConfigDirectory); - // Clear out the tmp - tmpProperties.clear(); - - // Let system properties take precedence over resource and - // config dir properties. - merge(systemProperties, "system properties", "system"); - - // in user's home directory, most precedence. - String userHomeDirectory = systemProperties.getProperty("user.home"); - if (DEBUG) { - logger.fine("Looking for " + propsFileName + " in user's home directory: " + userHomeDirectory); - } - - // We want foundProperties to reflect if properties have ever - // been found. - foundProperties |= PropUtils.loadProperties(tmpProperties, userHomeDirectory, propsFileName); - if (DEBUG) { - logger.fine("***** Done with property search ****"); - } - - if (!foundProperties && !Environment.isApplet()) { - PropUtils.copyProperties(PropUtils.promptUserForProperties(), properties); - } - - // Before we the user properties into the overall properties, - // need to check for the include properties URLs, and load - // those first. - includeProperties = getIncludeProperties(tmpProperties.getProperty(propertyPrefix + includeProperty), tmpProperties); - merge(includeProperties, "include file properties", userHomeDirectory); - - // Now, load the user home preferences last, since they take - // the highest precedence. - merge(tmpProperties, propsFileName, userHomeDirectory); - - // Well, they used to take the highest precedence. Now, we - // look for a localized property file, and write those - // properties on top. - localizedProperties = - getLocalizedProperties(tmpProperties.getProperty(propertyPrefix + localizedProperty), userHomeDirectory); - merge(localizedProperties, "localized properties", null); - - Environment.init(getProperties()); - } - - /** - * Load the localized properties that will take precedence over all other - * properties. If the localizedPropertyFile is null, a localized version of - * the openmap.properties file will be searched for in the classpath and in - * the user home directory (if that isn't null as well). - */ - protected Properties getLocalizedProperties(String localizedPropertyFile, String userHomeDirectory) { - Properties props = null; - if (localizedPropertyFile == null) { - java.util.Locale loc = java.util.Locale.getDefault(); - localizedPropertyFile = "openmap_" + loc.toString() + ".properties"; - } - - boolean tryHomeDirectory = false; - if (DEBUG) { - logger.fine("Looking for localized file: " + localizedPropertyFile); - } - - try { - URL propsURL = PropUtils.getResourceOrFileOrURL(localizedPropertyFile); - if (propsURL == null) { - tryHomeDirectory = true; - } else { - if (DEBUG) { - logger.fine("Found localized properties in classpath"); - } - props = fetchProperties(propsURL); - } - } catch (MalformedURLException murle) { - logger.warning("PropertyHandler can't find localized property file: " + localizedPropertyFile); - tryHomeDirectory = true; - } - - if (tryHomeDirectory) { - props = new Properties(); - if (!PropUtils.loadProperties(props, userHomeDirectory, localizedPropertyFile)) { - props = null; - } else { - if (DEBUG) { - logger.fine("Found localized properties in home directory"); - } - } - } - - if (props == null) { - props = new Properties(); - } - - return props; - } - - /** - * Initialize internal properties from Properties object. Appends all the - * properties it finds, overwriting the ones with the same key. Called by - * the two constructors where a Properties object is passed in, or when a - * URL for a Properties file is provided. This is not called by the - * constructor that has to go looking for the properties to use. - * - * @param props the properties to merge into the properties held by the - * PropertyHandler. - * @param howString a string describing where the properties come from. Just - * used for debugging purposes, so passing in a null value is no big - * deal. - */ - protected void init(Properties props, String howString) { - - // Include properties noted in resources properties. - String prefix = PropUtils.getScopedPropertyPrefix(getPropertyPrefix()); - Properties includeProperties = getIncludeProperties(props.getProperty(prefix + includeProperty), props); - merge(includeProperties, "include file properties", howString); - - if (!Environment.isApplet()) { - Properties systemProperties = System.getProperties(); - merge(systemProperties, props); - } - - merge(props, "loaded", howString); - - if (DEBUG) { - logger.fine("loaded properties"); - } - } - - /** - * Take a marker name list (space separated names), and open the properties - * files listed in the property with keys of marker.URL. - * - * @param markerList space separated marker names in a single string that - * needs to be parsed. - * @param props the properties that the markerList comes from, in order to - * get the marker.URL properties. - * @return an allocated Properties object containing all the properties from - * the include files. If no include files are listed, the Properties - * object is empty, not null. - */ - protected Properties getIncludeProperties(String markerList, Properties props) { - Properties newProps = new Properties(); - Properties tmpProps = new Properties(); - List includes = PropUtils.parseSpacedMarkers(markerList); - int size = includes.size(); - if (size > 0) { - - if (logger.isLoggable(Level.FINER)) { - logger.finer("handling include files: " + includes); - } - - for (String includeName : includes) { - String includeProperty = includeName + ".URL"; - - String include = props.getProperty(includeProperty); - if (logger.isLoggable(Level.FINER)) { - logger.finer("checking " + includeProperty + ", getting: " + include); - } - - if (include == null) { - logger.warning("PropertyHandler.getIncludeProperties(): Failed to locate include file \"" + includeName - + "\" with URL \"" + includeProperty + "\"\n Skipping include file \"" + include + "\""); - continue; - } - try { - tmpProps.clear(); - // Open URL to read in properties - URL tmpInclude = PropUtils.getResourceOrFileOrURL(null, include); - - if (tmpInclude == null) { - logger.fine("Can't locate URL trying to find included properties: " + include); - continue; - } - - InputStream is = tmpInclude.openStream(); - tmpProps.load(is); - if (DEBUG) { - logger.fine("PropertyHandler.getIncludeProperties(): located include properties file URL: " + include); - } - // Include properties noted in resources - // properties - a little recursive action, - // here. - Properties includeProperties = getIncludeProperties(tmpProps.getProperty(includeProperty), tmpProps); - merge(includeProperties, newProps, "include file properties", "within " + include); - - merge(tmpProps, newProps, "include file properties", include); - - } catch (MalformedURLException e) { - logger.warning("malformed URL for include file: |" + include + "| for " + includeName); - } catch (IOException ioe) { - logger.warning("IOException processing " + include + "| for " + includeName); - } - } - } else { - logger.fine("no include files found."); - } - return newProps; - } - - /** - * Take the from properties, copy them into the internal PropertyHandler - * properties. - * - * @param from the source properties. - */ - protected void merge(Properties from) { - merge(from, getProperties(), null, null); - } - - /** - * Take the from properties, copy them into the to properties. - * - * @param from the source properties. - * @param to the destination properties. - */ - protected void merge(Properties from, Properties to) { - merge(from, to, null, null); - } - - /** - * Take the from properties, copy them into the internal PropertyHandler - * properties. The what and where are simple for a more clearly defined - * logging statement. The what and where are only used for debugging - * statements when there are no properties found, so don't put too much work - * into creating them, like adding strings together before passing them in. - * The what and where fit into a debug output statement like: - * PropertyHandler.merge(): no _what_ found in _where_. - * - * @param from the source properties. - * @param what a description of what the from properties represent. - * @param where a description of where the properties were read from. - */ - protected void merge(Properties from, String what, String where) { - merge(from, getProperties(), what, where); - } - - /** - * Take the from properties, copy them into the to properties. The what and - * where are simple for a more clearly defined logging statement. The what - * and where are only used for debugging statements when there are no - * properties found, so don't put too much work into creating them, like - * adding strings together before passing them in. The what and where fit - * into a debug output statement like: PropertyHandler.merge(): no _what_ - * found in _where_. - * - * @param from the source properties. - * @param to the destination properties. - * @param what a description of what the from properties represent. - * @param where a description of where the properties were read from. - */ - protected void merge(Properties from, Properties to, String what, String where) { - if (!from.isEmpty()) { - - if (to == null) { - to = getProperties(); - } - PropUtils.copyProperties(from, to); - } else { - if (what != null && DEBUG) { - logger.fine("no " + what + " found" + (where == null ? "." : (" in " + where))); - } - } - } - - /** - * Merges the properties to the overall properties held by the - * PropertyHandler. - */ - public void setProperties(Properties props) { - init(props, null); - } - - /** - * Get the current properties set within this handler. - */ - public Properties getProperties() { - if (properties == null) { - properties = new Properties(); - } - return properties; - } - - /** - * Given a property prefix, or markername, from the properties file, get the - * object that was created for it. This method uses the prefix librarian. - */ - public Object get(String markername) { - return prefixLibrarian.get(markername.intern()); - } - - /** - * Get a properties object containing all the properties with the given - * prefix. - */ - public Properties getProperties(String prefix) { - Properties prefixProperties = new Properties(); - Properties props = getProperties(); - if (prefix != null) { - String scopedPrefix = prefix + "."; - for (Enumeration e = props.keys(); e.hasMoreElements();) { - String key = e.nextElement().toString(); - if (key.startsWith(scopedPrefix)) { - prefixProperties.put(key, props.get(key)); - } - } - } - return prefixProperties; - } - - /** - * Register an object with the prefix librarian against a specific marker - * name. - */ - public void put(String markername, Object obj) { - prefixLibrarian.put(markername.intern(), obj); - } - - /** - * Remove an object from the prefix librarian register, returning that - * object if it has been found. - */ - public Object remove(String markername) { - return prefixLibrarian.remove(markername); - } - - /** - * Get the Hashtable being held that matches property prefix strings with - * components. - */ - public Hashtable getPrefixLibrarian() { - return prefixLibrarian; - } - - /** - * Given a BeanContext (actually a MapHandler, to handle SoloMapComponents), - * look for the openmap.components property in the current properties, and - * parse the list given as that property. From that list of marker names, - * look for the marker.class properties and create those Java objects. Those - * objects will be added to the BeanContext given. - * - * @param mapHandler BeanContext. - */ - public void createComponents(MapHandler mapHandler) { - int i; // default counter - - if (mapHandler == null) { - logger.fine("no MapHandler to use to handle created components, skipping creation."); - return; - } - - ProgressListenerGauge plg = null; - - if (updateProgress) { - try { - String internString = i18n.get(this.getClass(), "progressTitle", "Progress"); - plg = new ProgressListenerGauge(internString); - plg.setWindowSupport(new WindowSupport(plg, new WindowSupport.Frm("", true))); - addProgressListener(plg); - } catch (Exception e) { - // Since ProgressListenerGauge is a Swing component, catch - // any exception that would be tossed if it can't be - // created, like if the PropertyHandler is being used on a - // unix system without a DISPLAY. - // plg = null; - } - } - - List debugList = PropUtils.parseSpacedMarkers(properties.getProperty(Environment.DebugList)); - int size = debugList.size(); - - for (String debugMarker : debugList) { - Debug.put(debugMarker); - if (DEBUG) { - logger.fine("adding " + debugMarker + " to Debug list."); - } - } - - String propPrefix = PropUtils.getScopedPropertyPrefix(getPropertyPrefix()); - String componentProperty = propPrefix + PropertyHandler.componentProperty; - List componentList = PropUtils.parseSpacedMarkers(properties.getProperty(componentProperty)); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("creating components from " + componentList); - } - - if (updateProgress) { - fireProgressUpdate(ProgressEvent.START, - i18n.get(this.getClass(), "creatingComponentsProgressMessage", "Creating Components"), 0, 100); - } - - List components = - ComponentFactory.create(componentList, properties, (updateProgress ? getProgressSupport() : null), true); - - size = components.size(); - - for (i = 0; i < size; i++) { - Object obj = components.get(i); - try { - if (obj instanceof String) { - logger.warning("finding out that the " + obj + " wasn't created"); - continue; - } - - // mapHandler.add(obj); - - // The call to add(obj) above was replaced by the call to - // addLayer() below. This seems to speed up the startup process, - // but if some other component calls mapHandler.add(obj), then - // this list will be purged. - mapHandler.addLater(obj); - - String markerName = componentList.get(i).intern(); - prefixLibrarian.put(markerName, obj); - addUsedPrefix(markerName); - - } catch (MultipleSoloMapComponentException msmce) { - logger.warning("PropertyHandler.createComponents(): " + "tried to add multiple components of the same " - + "type when only one is allowed! - " + msmce); - } - } - - // Added as a result of the addLater(obj) call above... - mapHandler.purgeLaterList(); - - if (updateProgress) { - fireProgressUpdate(ProgressEvent.DONE, - i18n.get(this.getClass(), "completedProgressMessage", "Created all components, ready..."), size, - size); - removeProgressListener(plg); - } - } - - public String getPropertyPrefix() { - String propertyPrefix = this.propertyPrefix; - if (propertyPrefix == null) { - propertyPrefix = Environment.OpenMapPrefix; - } - - return propertyPrefix; - } - - public void setPropertyPrefix(String propertyPrefix) { - this.propertyPrefix = propertyPrefix; - } - - /** - * Creates a Properties object containing the current settings as defined by - * OpenMap components held by the MapHandler. If the MapHandler contains a - * PropertyHandler, that property handler will be consulted for properties - * for different objects in case those objects don't know how to provide - * their settings correctly. - * - * @param mapHandler MapHandler containing components to use for Properties. - * @param ps PrintStream to write properties to, may be null if you just - * want the Properties object that is returned. - * @return Properties object containing everything written (or that would - * have been written, if the PrintStream is null) to PrintStream. - */ - public static Properties createOpenMapProperties(MapHandler mapHandler, PrintStream ps) { - - Properties createdProperties = new Properties(); - - // First, get all the components in the MapHandler. Create - // the openmap.components list, with the .class properties - // listing all the class names. Ignore the layers for now, - // and if the class is a PropertyConsumer, get its properties - // too. - if (mapHandler == null) { - logger.warning("can't create properties with null MapHandler"); - return null; - } - - logger.fine("Looking for objects in MapHandler"); - - MapBean mapBean = null; - LayerHandler layerHandler = null; - PropertyHandler propertyHandler = null; - InformationDelegator infoDelegator = null; - List otherComponents = new ArrayList<>(); - - for (Object someObj : mapHandler) { - //someObj = it.next(); - logger.fine("found " + someObj.getClass().getName()); - - if (someObj instanceof MapBean) { - mapBean = (MapBean) someObj; - } else if (someObj instanceof LayerHandler) { - layerHandler = (LayerHandler) someObj; - } else if (someObj instanceof Layer) { - // do nothing, layerhandler will handle - } else if (someObj instanceof PropertyHandler) { - propertyHandler = (PropertyHandler) someObj; - if (infoDelegator != null) { - propertyHandler.addProgressListener(infoDelegator); - } - } else if (someObj instanceof InformationDelegator) { - infoDelegator = (InformationDelegator) someObj; - if (propertyHandler != null) { - propertyHandler.addProgressListener((ProgressListener) someObj); - } - } else { - // Add the rest to a component vector thingy. - otherComponents.add(someObj); - } - } - - // if the MapBean and/or the LayerHandler are null, what's the - // point? - if (mapBean == null || layerHandler == null) { - logger.warning("no MapBean(" + mapBean + ") or LayerHandler(" + layerHandler + ") to use to write properties"); - return null; - } - - // First, print the Map parameters... - - ps.println("###### OpenMap properties file ######"); - ps.println("## Refer to original openmap.properties file\n## for instructions on how to modify this file."); - ps.println("######################################"); - - printMapProperties(mapBean, ps, createdProperties); - printComponentProperties(otherComponents, propertyHandler, ps, createdProperties); - printLayerProperties(layerHandler, propertyHandler, ps, createdProperties); - - if (logger.isLoggable(Level.FINE) && createdProperties != null) { - System.out.println(createdProperties); - } - - return createdProperties; - } - - /** - * A simple helper method that writes key-value pairs to a print stream or - * Properties, whatever is not null. - */ - protected static void printProperties(String key, String value, PrintStream ps, Properties createdProperties) { - if (ps != null) { - ps.println(key + "=" + value); - } - if (createdProperties != null) { - createdProperties.put(key, value); - } - } - - /** - * A helper function to createOpenMapProperties that gets the current - * properties of the MapBean and prints them out to the PrintStream and the - * provided Properties object. - * - * @param mapBean MapBean to get parameters from. - * @param ps PrintStream to write properties to, may be null. - * @param createdProperties Properties object to store properties in, may be - * null. - */ - protected static void printMapProperties(MapBean mapBean, PrintStream ps, Properties createdProperties) { - - // warning...hackish... - com.bbn.openmap.proj.Proj proj = mapBean.projection; - - ps.println("\n### OpenMap initial Map Settings ###"); - Point2D llp = proj.getCenter(); - - printProperties(Environment.Latitude, Double.toString(llp.getY()), ps, createdProperties); - - printProperties(Environment.Longitude, Double.toString(llp.getX()), ps, createdProperties); - - printProperties(Environment.Scale, Float.toString(proj.getScale()), ps, createdProperties); - - printProperties(Environment.Projection, proj.getName(), ps, createdProperties); - - printProperties(Environment.BackgroundColor, Integer.toHexString(mapBean.getBackground().getRGB()), ps, createdProperties); - - // Height and Width are in the OpenMapFrame properties, or - // whatever other component contains everything. - } - - /** - * A helper function to createOpenMapProperties that gets the current - * properties of the given components and prints them out to the PrintStream - * and the provided Properties object. - * - * @param components Vector of components to get parameters from. - * @param ph PropertyHandler that may have properties to use as a foundation - * for the properties for the components. If the component can't - * provide properties reflecting its settings, the property handler - * will be consulted for properties it knows about for that - * component. - * @param ps PrintStream to write properties to, may be null. - * @param createdProperties Properties object to store properties in, may be - * null. - */ - protected static void printComponentProperties(List components, PropertyHandler ph, PrintStream ps, - Properties createdProperties) { - - // this section looks at the components and tries to create - // the openmap.components list and then write out all the - // properties for them. - - // Since order is important to the look of the application, we - // need to do work here to maintain the current loaded order - // of the application components. Until then, just swipe the - // openmap.components property to get the list of current - // components. - - boolean buildConfiguredApplication = true; - boolean componentListBuilt = false; - int numComponents = 0; - String componentProperty = PropertyHandler.componentProperty; - StringBuffer componentMarkerString = new StringBuffer(componentProperty).append("="); - if (ph != null) { - String phPrefix = PropUtils.getScopedPropertyPrefix(ph.getPropertyPrefix()); - componentProperty = phPrefix + PropertyHandler.componentProperty; - componentMarkerString = new StringBuffer(componentProperty).append("="); - } - - StringBuffer componentPropsString = new StringBuffer(); - - if (ph != null && buildConfiguredApplication) { - Properties phProps = ph.getProperties(); - // Ahh, phProps'l never be null, right? - - // Let's build them from the current properties file. - componentMarkerString.append(phProps.getProperty(componentProperty)); - - List componentList = PropUtils.parseSpacedMarkers(phProps.getProperty(componentProperty)); - - for (String markerName : componentList) { - String markerNameClassKey = markerName + ".class"; - String markerNameClass = phProps.getProperty(markerNameClassKey); - componentPropsString.append(markerNameClassKey).append("=").append(markerNameClass).append("\n"); - if (createdProperties != null) { - createdProperties.put(markerNameClassKey, markerNameClass); - } - } - componentListBuilt = true; - - } - - // We're still going through the objects, but only adding the - // .class properties if the list wasn't built above. - // Otherwise, the components will be checked to see of they - // are PropertyConsumers, in order to get their properties - // written to the file. - - Properties componentProperties = new Properties(); - - for (Object component : components) { - - if (component instanceof PropertyConsumer) { - logger.fine("Getting Property Info for" + component.getClass().getName()); - - PropertyConsumer pc = (PropertyConsumer) component; - componentProperties.clear(); - String markerName = pc.getPropertyPrefix(); - - if (ph != null && markerName != null && !markerName.equals("openmap")) { - // Gets the properties for the prefix that the - // property handler was set with. This should - // handle components that aren't good - // PropertyConsumers. - componentProperties = ph.getProperties(markerName); - } else { - componentProperties.clear(); - } - - if (!componentListBuilt) { - if (markerName != null) { - componentMarkerString.append(" ").append(markerName); - } else { - markerName = "component" + (numComponents++); - componentMarkerString.append(" ").append(markerName); - pc.setPropertyPrefix(markerName); - } - - String componentClassName = component.getClass().getName(); - componentPropsString.append(markerName).append(".class=").append(componentClassName).append("\n"); - - if (createdProperties != null) { - createdProperties.put(markerName, componentClassName); - } - } - - pc.getProperties(componentProperties); - - TreeSet orderedProperties = new TreeSet<>(componentProperties.stringPropertyNames()); - if (!componentProperties.isEmpty()) { - componentPropsString.append("####\n"); - for (String key : orderedProperties) { - String value = componentProperties.getProperty(key); - - if (value != null) { - componentPropsString.append(key).append("=").append(value).append("\n"); - } - - if (createdProperties != null && value != null) { - createdProperties.put(key, value); - } - } - } - } else if (!componentListBuilt) { - String markerName = "component" + (numComponents++); - componentMarkerString.append(" ").append(markerName); - String componentClassName = component.getClass().getName(); - componentPropsString.append(markerName).append(".class=").append(componentClassName).append("\n"); - if (createdProperties != null) { - createdProperties.put(markerName, componentClassName); - } - } - } - - if (ps != null) { - ps.println("\n\n### OpenMap Components ###"); - ps.println(componentMarkerString.toString()); - - ps.println("\n### OpenMap Component Properties ###"); - // list created, add the actual component properties - ps.println(componentPropsString.toString()); - ps.println("### End Component Properties ###"); - } - - if (createdProperties != null) { - createdProperties.put(PropertyHandler.componentProperty, - componentMarkerString.substring(PropertyHandler.componentProperty.length() + 1)); - } - } - - /** - * A helper function to createOpenMapProperties that gets the current - * properties of the layers in the LayerHandler and prints them out to the - * PrintStream and the provided Properties object. - * - * @param layerHandler LayerHandler to get layers from. - * @param ph PropertyHandler that may have properties to use as a foundation - * for the properties for the components. If the component can't - * provide properties reflecting its settings, the property handler - * will be consulted for properties it knows about for that - * component. - * @param ps PrintStream to write properties to, may be null. - * @param createdProperties Properties object to store properties in, may be - * null. - */ - protected static void printLayerProperties(LayerHandler layerHandler, PropertyHandler ph, PrintStream ps, - Properties createdProperties) { - - // Keep track of the LayerHandler. Use it to get the layers, - // which can be used to get all the marker names for the - // openmap.layers property. The visible layers go to the - // openmap.startUpLayers property. Then, cycle through all - // the layers to get their properties, since they all are - // PropertyConsumers. - - String layerMarkerStringKey = Environment.OpenMapPrefix + "." + LayerHandler.layersProperty; - StringBuffer layerMarkerString = new StringBuffer(layerMarkerStringKey).append("="); - String startUpLayerMarkerStringKey = Environment.OpenMapPrefix + "." + LayerHandler.startUpLayersProperty; - StringBuffer startUpLayerMarkerString = new StringBuffer(startUpLayerMarkerStringKey).append("="); - StringBuffer layerPropertiesString = new StringBuffer(); - - Properties layerProperties = new Properties(); - - Layer[] layers = layerHandler.getLayers(); - int numLayers = 0; - - for (Layer layer : layers) { - - String markerName = layer.getPropertyPrefix(); - - if (markerName == null) { - markerName = "layer" + (numLayers++); - layer.setPropertyPrefix(markerName); - } - - if (ph != null) { - // Gets the properties for the prefix that the - // property handler was set with. This should - // handle components that aren't good - // PropertyConsumers. - layerProperties = ph.getProperties(markerName); - } else { - layerProperties.clear(); - } - - layerMarkerString.append(" ").append(markerName); - - if (layer.isVisible()) { - startUpLayerMarkerString.append(" ").append(markerName); - } - - layer.getProperties(layerProperties); - layerPropertiesString.append("### -").append(markerName).append("- layer properties\n"); - - TreeSet orderedPropertyKeys = new TreeSet<>(layerProperties.stringPropertyNames()); - for (String key : orderedPropertyKeys) { - - // Could add .replace("\\", "/") to the end of this - // line to prevent \\ from appearing in the properties - // file. - String value = layerProperties.getProperty(key); - - if (value != null) { - layerPropertiesString.append(key).append("=").append(value).append("\n"); - } - - if (createdProperties != null && value != null) { - createdProperties.put(key, value); - } - } - - layerPropertiesString.append("### end of -").append(markerName).append("- properties\n\n"); - } - - if (ps != null) { - ps.println("\n### OpenMap Layers ###"); - ps.println(layerMarkerString.toString()); - ps.println(startUpLayerMarkerString.toString()); - ps.println(layerPropertiesString.toString()); - } - - if (createdProperties != null) { - createdProperties.put(layerMarkerStringKey, layerMarkerString.substring(layerMarkerStringKey.length() + 1)); - createdProperties.put(startUpLayerMarkerStringKey, - startUpLayerMarkerString.substring(startUpLayerMarkerStringKey.length() + 1)); - } - } - - /** - * Given a MapHandler and a Java Properties object, the LayerHandler will be - * cleared of it's current layers, and reloaded with the layers in the - * properties. The MapBean will be set to the projection settings listed in - * the properties. - */ - public void loadProjectionAndLayers(MapHandler mapHandler, Properties props) { - - MapBean mapBean = (MapBean) mapHandler.get("com.bbn.openmap.MapBean"); - LayerHandler layerHandler = (LayerHandler) mapHandler.get("com.bbn.openmap.LayerHandler"); - // InformationDelegator id = (InformationDelegator) - // mapHandler.get("com.bbn.openmap.InformationDelegator"); - - // if (id != null) { - // id.requestCursor(new Cursor(Cursor.WAIT_CURSOR)); - // } - - if (layerHandler != null) { - layerHandler.removeAll(); - layerHandler.init(Environment.OpenMapPrefix, props); - } else { - logger.warning("Can't load new layers - can't find LayerHandler"); - } - - if (mapBean != null) { - mapBean.setProjection(mapBean.getProjectionFactory().getDefaultProjectionFromEnvironment(mapBean.getWidth(), - mapBean.getHeight())); - } else { - logger.warning("Can't load new projection - can't find MapBean"); - } - - // if (id != null) { - // id.requestCursor(null); - // } - } - - /** - * If you are creating a new object, it's important to get a unique prefix - * for its properties. This function takes a prefix string and checks it - * against all others it knows about. If there is a conflict, it adds a - * number to the end until it becomes unique. This prefix will be logged by - * the PropertyHandler as a name given out, so duplicate instances of that - * string will not be given out later. It doesn't, however, log that name in - * the prefixLibrarian. That only occurs when the object is programmatically - * registered with the prefixLibrarian or when the PropertyHandler finds - * that object in the MapHandler (and even then that object must be a - * PropertyConsumer to be registered this way). - */ - public String getUniquePrefix(String prefix) { - prefix = prefix.replace(' ', '_'); - - if (!addUsedPrefix(prefix)) { - int count = 2; - String nextTry = prefix + (count); - while (!addUsedPrefix(nextTry)) { - nextTry = prefix + (++count); - } - return nextTry; - } else { - return prefix; - } - } - - /** - * Changes ' ' characters to '_', and then tries to add it to the used - * prefix list. Returns true if successful. - */ - public boolean addUsedPrefix(String prefix) { - prefix = prefix.replace(' ', '_'); - - return usedPrefixes.add(prefix.intern()); - } - - /** - * Changes ' ' characters to '_', and then tries to remove it to the used - * prefix list. Returns true if successful. - */ - public boolean removeUsedPrefix(String prefix) { - prefix = prefix.replace(' ', '_'); - - return usedPrefixes.remove(prefix.intern()); - } - - /** - * Add a ProgressListener that will display build progress. - */ - public void addProgressListener(ProgressListener list) { - getProgressSupport().add(list); - } - - /** - * Remove a ProgressListener that displayed build progress. - */ - public void removeProgressListener(ProgressListener list) { - getProgressSupport().remove(list); - } - - /** - * Clear all progress listeners. - */ - public void clearProgressListeners() { - getProgressSupport().clear(); - } - - /** - * Get progress support if needed. - */ - protected ProgressSupport getProgressSupport() { - if (progressSupport == null) { - progressSupport = new ProgressSupport(this); - } - return progressSupport; - } - - /** - * Fire an build update to progress listeners. - * - * @param frameNumber the current frame count - * @param totalFrames the total number of frames. - */ - protected void fireProgressUpdate(int type, String task, int frameNumber, int totalFrames) { - if (updateProgress) { - getProgressSupport().fireUpdate(type, task, totalFrames, frameNumber); - } else if (type == ProgressEvent.DONE) { - // At least turn off progress listeners if they are up. - getProgressSupport().fireUpdate(ProgressEvent.DONE, task, totalFrames, frameNumber); - } - } - - /** - * Set a flag that will trigger the PropertyHandler to fire progress events - * when it is going through the creation process. - */ - public void setUpdateProgress(boolean set) { - updateProgress = set; - } - - public boolean getUpdateProgress() { - return updateProgress; - } - - // Property Functions: - // /////////////////// - - /** - * Remove an existing property if it exists. - * - * @return true if a property was actually removed. - */ - public boolean removeProperty(String property) { - return getProperties().remove(property) != null; - } - - /** - * Add (or overwrite) a property to the current properties - */ - public void addProperty(String property, String value) { - getProperties().setProperty(property, value); - } - - /** - * Add in the properties from the given URL. Any existing properties will be - * overwritten except for openmap.components, openmap.layers and - * openmap.startUpLayers which will be appended. - */ - public void addProperties(URL urlToProperties) { - addProperties(fetchProperties(urlToProperties)); - } - - /** - * Add in the properties from the given source, which can be a resource, - * file or URL. Any existing properties will be overwritten except for - * openmap.components, openmap.layers and openmap.startUpLayers which will - * be appended. - * - * @throws MalformedURLException if propFile doesn't resolve properly. - */ - public void addProperties(String propFile) - throws MalformedURLException { - addProperties(fetchProperties(PropUtils.getResourceOrFileOrURL(propFile))); - } - - /** - * Add in the properties from the given Properties object. Any existing - * properties will be overwritten except for openmap.components, - * openmap.layers and openmap.startUpLayers where values will be prepended - * to any existing lists. - */ - public void addProperties(Properties p) { - String[] specialProps = new String[] { - Environment.OpenMapPrefix + "." + LayerHandler.layersProperty, - Environment.OpenMapPrefix + "." + LayerHandler.startUpLayersProperty, - componentProperty - }; - - Properties tmp = new Properties(); - tmp.putAll(p); - - for (int i = 0; i < specialProps.length; i++) { - prependProperty(specialProps[i], tmp); - tmp.remove(specialProps[i]); - } - - getProperties().putAll(tmp); - } - - /** - * remove a marker from a space delimited set of properties. - */ - public void removeMarker(String property, String marker) { - // Requires jdk 1.4 - // StringBuffer sb = - // new StringBuffer(getProperties().getProperty(property, - // "")); - // int idx = sb.indexOf(marker); - - // jdk 1.3 version - String propertyString = getProperties().getProperty(property, ""); - int idx = propertyString.indexOf(marker); - if (idx != -1) { - StringBuffer sb = new StringBuffer(propertyString); - sb.delete(idx, idx + marker.length()); - getProperties().setProperty(property, sb.toString()); - } - } - - /** - * Append the given property into the current properties - */ - public void appendProperty(String property, Properties src) { - appendProperty(property, src.getProperty(property, "")); - } - - /** - * Append the given property into the current properties - */ - public void appendProperty(String property, String value) { - String curVal = getProperties().getProperty(property, ""); - getProperties().setProperty(property, curVal + " " + value); - } - - /** - * Prepend the given property into the current properties - */ - public void prependProperty(String property, Properties src) { - prependProperty(property, src.getProperty(property, "")); - } - - /** - * Prepend the given property into the current properties - */ - public void prependProperty(String property, String value) { - String curVal = getProperties().getProperty(property, ""); - getProperties().setProperty(property, value + " " + curVal); - } - - /** - * Load a Properties object from the classpath. The method always returns a - * Properties object. If there was an error loading the - * properties from propsURL, an empty Properties - * object is returned. - * - * @param propsURL the URL of the properties to be loaded - * @return the loaded properties, or an empty Properties object if there was - * an error. - */ - public static Properties fetchProperties(URL propsURL) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("checking (" + propsURL + ")"); - } - Properties p = new Properties(); - if (propsURL != null) { - try { - InputStream is = propsURL.openStream(); - p.load(is); - is.close(); - } catch (IOException e) { - logger.warning("Exception reading map properties at " + propsURL + ": " + e); - } - } - return p; - } - - /** - * All the PropertyHandler does with the MapHandler is look for - * PropertyConsumers and register their prefixes with the prefixLibarian. - */ - public void findAndInit(Object obj) { - if (obj instanceof PropertyConsumer) { - PropertyConsumer pc = (PropertyConsumer) obj; - String prefix = pc.getPropertyPrefix(); - if (prefix != null) { - getPrefixLibrarian().put(prefix, pc); - } - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof PropertyConsumer) { - String prefix = ((PropertyConsumer) obj).getPropertyPrefix(); - if (prefix != null) { - getPrefixLibrarian().remove(prefix); - } - } - if (obj == this) { - dispose(); - } - } - - public void dispose() { - if (prefixLibrarian != null) { - prefixLibrarian.clear(); - } - if (properties != null) { - properties.clear(); - } - if (usedPrefixes != null) { - usedPrefixes.clear(); - } - } - - /** - * - * This Builder class lets you have more control over how a PropertyHandler - * is constructed. If a properties file location or a properties file is not - * provided, the PropertyHandler will look for an "openmap.properties" file - * in the classpath, config directory or user home directory. If you don't - * want the PropertyHandler to search for a properties file, set an empty - * Properties object in the Builder. - * - * @author ddietrick - */ - public static class Builder { - - protected boolean update = false; - protected Properties properties = null; - protected String propertyPrefix = null; - - public Builder() { - } - - /** - * Have the builder look for a resource, file or URL at the location. - * - * @param location of the properties file - * @return this Builder, so settings can be stacked. - * @throws MalformedURLException - * @throws IOException - */ - public Builder setPropertiesFile(String location) - throws MalformedURLException, IOException { - if (location != null) { - this.properties = createProperties(PropUtils.getResourceOrFileOrURL(location)); - } - return this; - } - - /** - * Have the builder look for properties file at URL location. - * - * @param url - * @return this Builder for stacking. - * @throws IOException - */ - public Builder setPropertiesFile(URL url) - throws IOException { - if (url != null) { - this.properties = createProperties(url); - } - return this; - } - - /** - * Have the builder use the provided properties. - * - * @param props Properties to use. - * @return this Builder for stacking - */ - public Builder setProperties(Properties props) { - this.properties = props; - return this; - } - - /** - * Set the property prefix used for general settings in the properties - * in configuration of application. If not set "openmap" will be used as - * the default. - * - * @param prefix Set the property prefix for the PropertyHandler - * @return this builder for stacking - */ - public Builder setPropertyPrefix(String prefix) { - this.propertyPrefix = prefix; - return this; - } - - /** - * - * @param update flag for providing progress updates - * @return This builder for stacking - */ - public Builder setProgressUpdates(boolean update) { - this.update = update; - return this; - } - - /** - * Reads the file at the given location and creates a Properties file - * from the contents. - * - * @param location URL of file - * @return Properties - * @throws IOException if something goes wrong reading the file. - */ - protected Properties createProperties(URL location) - throws IOException { - InputStream is = null; - - if (location != null) { - // Open URL to read in properties - is = location.openStream(); - } - - Properties tmpProperties = new Properties(); - if (is != null) { - tmpProperties.load(is); - } - - return tmpProperties; - } - - /** - * Build the property handler. - * - * @return new property handler with builder settings. - */ - public PropertyHandler build() { - return new PropertyHandler(this); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/SoloMapComponent.java b/src/core/src/main/java/com/bbn/openmap/SoloMapComponent.java deleted file mode 100644 index 658a30f99..000000000 --- a/src/core/src/main/java/com/bbn/openmap/SoloMapComponent.java +++ /dev/null @@ -1,34 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/SoloMapComponent.java,v $ -// $RCSfile: SoloMapComponent.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -/** - * This interface is simply a way to mark a class as something that - * should only exist once within a MapHandler. When map components are - * added to the MapHandler, the MapHandler will check to see if 1) the - * component is a SoloMapComponent, and 2) if it is, depending on the - * policy set in the MapHandler, that no other classes of the same - * type are already added to the BeanContext. - */ -public interface SoloMapComponent { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentPolicy.java b/src/core/src/main/java/com/bbn/openmap/SoloMapComponentPolicy.java deleted file mode 100644 index ab511107b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentPolicy.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/SoloMapComponentPolicy.java,v $ -// $RCSfile: SoloMapComponentPolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.beancontext.BeanContextSupport; - -/** - * An interface to control the behavior of the BeanContext when - * duplicate SoloMapComponents are added to it. - */ -public interface SoloMapComponentPolicy { - - /** - * Ask whether an object can be added to the to the context. - * - * @param bc the context to add to - * @param obj the object to add - * @return true if the object can be added. - * @throws MultipleSoloMapComponentException describing the - * conflict if there is one and the object can't be added. - */ - public boolean canAdd(BeanContextSupport bc, Object obj) - throws MultipleSoloMapComponentException; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentRejectPolicy.java b/src/core/src/main/java/com/bbn/openmap/SoloMapComponentRejectPolicy.java deleted file mode 100644 index 403444568..000000000 --- a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentRejectPolicy.java +++ /dev/null @@ -1,61 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/SoloMapComponentRejectPolicy.java,v $ -// $RCSfile: SoloMapComponentRejectPolicy.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.beancontext.BeanContextSupport; -import java.util.Iterator; - -/** - * A SoloMapComponentPolicy that rejects attempts to add a duplicate - * SoloMapComponent to the BeanContext. - */ -public class SoloMapComponentRejectPolicy implements SoloMapComponentPolicy { - - /** - * @param bc BeanContext, or MapHandler - * @param obj the object to check before adding to MapHandler - * @throws MultipleSoloMapComponentException if a duplicate - * instance of SoloMapComponent exists. - * @return true if the object can be added to the MapHandler. - */ - public boolean canAdd(BeanContextSupport bc, Object obj) - throws MultipleSoloMapComponentException { - if (obj instanceof SoloMapComponent) { - Class firstClass = obj.getClass(); - for (Iterator it = bc.iterator(); it.hasNext();) { - Object someObj = it.next(); - if (someObj instanceof SoloMapComponent) { - Class secondClass = someObj.getClass(); - - if (firstClass == secondClass - || firstClass.isAssignableFrom(secondClass) - || secondClass.isAssignableFrom(firstClass)) { - - throw new MultipleSoloMapComponentException(firstClass, secondClass); - } - } - } - } - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentReplacePolicy.java b/src/core/src/main/java/com/bbn/openmap/SoloMapComponentReplacePolicy.java deleted file mode 100644 index 161f51e32..000000000 --- a/src/core/src/main/java/com/bbn/openmap/SoloMapComponentReplacePolicy.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/SoloMapComponentReplacePolicy.java,v $ -// $RCSfile: SoloMapComponentReplacePolicy.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.beans.beancontext.BeanContextSupport; -import java.util.Iterator; - -/** - * A SoloMapComponentPolicy that senses duplicate SoloMapComponents - * compared to the new object, removing the previous object before - * advising addition. - */ -public class SoloMapComponentReplacePolicy implements SoloMapComponentPolicy { - - /** - * @return true if the object can be added to the MapHandler, and - * will have removed the previous duplicate from the - * MapHandler. - */ - public boolean canAdd(BeanContextSupport bc, Object obj) - throws MultipleSoloMapComponentException { - - if (obj == null) { - return false; - } - - // At first we just added the new item, but we should remove - // the previous one, too. - if (obj instanceof SoloMapComponent) { - Class firstClass = obj.getClass(); - for (Iterator it = bc.iterator(); it.hasNext();) { - Object someObj = it.next(); - if (someObj instanceof SoloMapComponent) { - Class secondClass = someObj.getClass(); - - if (firstClass == secondClass - || firstClass.isAssignableFrom(secondClass) - || secondClass.isAssignableFrom(firstClass)) { - - bc.remove(someObj); - break; - } - } - } - } - - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/StandardMapBeanRepaintPolicy.java b/src/core/src/main/java/com/bbn/openmap/StandardMapBeanRepaintPolicy.java deleted file mode 100644 index 7dd50f0ac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/StandardMapBeanRepaintPolicy.java +++ /dev/null @@ -1,126 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/StandardMapBeanRepaintPolicy.java,v $ -// $RCSfile: StandardMapBeanRepaintPolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Graphics; - -import com.bbn.openmap.util.Debug; - -/** - * A MapBeanRepaintPolicy that just forwards layer repaint requests normally, - * and does nothing for java.awt.Graphics before painting. If this class or any - * subclass of it is added to the MapHandler, it will find the MapBean and set - * itself on it. - * - *

- * A StandardMapBeanRepaintPolicy is automatically set in the MapBean, so you - * don't have to add one of these to the MapHandler. The OMComponent inheritance - * is here to make it easier for subclasses to be added and for properties to be - * set. - */ -public class StandardMapBeanRepaintPolicy extends OMComponent implements MapBeanRepaintPolicy, - SoloMapComponent, Cloneable { - - protected MapBean map; - - protected boolean DEBUG = false; - - public StandardMapBeanRepaintPolicy() { - DEBUG = Debug.debugging("policy"); - } - - public StandardMapBeanRepaintPolicy(MapBean mb) { - super(); - setMap(mb); - } - - public void setMap(MapBean mb) { - map = mb; - } - - public MapBean getMap() { - return map; - } - - /** - * Take some action based on a repaint request from this particular layer. - * The StandardMapBeanRepaintPolicy just forwards requests on. - */ - public void repaint(Layer layer) { - // No decisions, just forward the repaint() request; - if (map != null) { - if (DEBUG) { - Debug.output("SMBRP: forwarding repaint request for " + layer.getName()); - } - map.repaint(); - } else { - Debug.error("SMBRP: MapBean is null in repaint(" + layer.getName() + ")"); - } - } - - /** - * A hook for the RepaintPolicy to make any adjustments to the - * java.awt.Graphics object before sending the Graphics object to the layers - * for painting. Gives the policy a chance to make rendering hint changes on - * Graphic2D objects, setting anti-aliasing configurations, etc. No - * modifications are made. - */ - public Graphics modifyGraphicsForPainting(Graphics graphics) { - return graphics; - } - - /** - * If a MapBean is passed to this StandardMapBeanRepaintPolicy, it will set - * itself on it. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - ((MapBean) someObj).setMapBeanRepaintPolicy(this); - setMap((MapBean) someObj); - if (DEBUG) { - Debug.output(getClass().getName() + " found MapBean"); - } - } - } - - /** - * If a MapBean is passed to this StandardMapBeanRepaintPolicy, it will - * check if it is the repaint policy set on the MapBean and if so, remove - * itself from it. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean && ((MapBean) someObj).getMapBeanRepaintPolicy() == this) { - ((MapBean) someObj).setMapBeanRepaintPolicy(null); - setMap(null); - } - } - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/app/Main.java b/src/core/src/main/java/com/bbn/openmap/app/Main.java deleted file mode 100644 index 401515a94..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/Main.java +++ /dev/null @@ -1,169 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/app/OpenMap.java,v $ -// $RCSfile: OpenMap.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.app; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.gui.OverlayMapPanel; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * A Main application class using the OpenMap framework. This class is like the - * OpenMap application class except it uses the new OverlayMapPanel instead of - * the BasicMapPanel. The property prefix used for the properties is "main", so - * this application is configured based on the main.components property list. - */ -public class Main extends OpenMap { - - /** - * Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame, - * and brings up the layer palettes that are being told to be open at - * startup. The MapPanel will create a PropertiesHandler that will search - * for an openmap.properties file. - */ - public Main() { - this(null); - } - - /** - * Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame, - * and brings up the layer palettes that are being told to be open at - * startup. The properties in the PropertyHandler will be used to configure - * the application. PropertyHandler may be null. - */ - public Main(PropertyHandler propertyHandler) { - super(propertyHandler); - } - - protected void configureMapPanel(PropertyHandler propertyHandler) { - OverlayMapPanel mapPanel = new OverlayMapPanel(propertyHandler, true); - // Creates the components in the main application thread. If any of - // these components need to update their GUI, they should hand a - // Runnable object to the SwingUtilities.invokeLater(Runnable) method, - // and it will be updated accordingly. - mapPanel.create(); - this.mapPanel = mapPanel; - } - - /** - * Given a path to a properties file, try to configure a PropertyHandler - * with it. If the properties file is not valid, the returned - * PropertyHandler will look for the openmap.properties file in the - * classpath and the user's home directory. - * - * @param propertiesFile path to properties file - * @return new PropertyHandler - */ - public static PropertyHandler configurePropertyHandler(String propertiesFile) { - - try { - return new PropertyHandler.Builder().setPropertiesFile(propertiesFile).setPropertyPrefix("main").build(); - } catch (MalformedURLException murle) { - getLogger().log(Level.WARNING, murle.getMessage(), murle); - } catch (IOException ioe) { - getLogger().log(Level.WARNING, ioe.getMessage(), ioe); - } - - return new PropertyHandler(); - } - - /** - * Create and return an OpenMap object that uses a standard PropertyHandler - * to configure itself. The OpenMap object has a MapHandler that you can use - * to gain access to all the components. - * - * @return Main, extending OpenMap - * @see #getMapHandler - */ - public static Main create() { - return new Main(null); - } - - /** - * Create and return an OpenMap object that uses a standard PropertyHandler - * to configure itself. The OpenMap object has a MapHandler that you can use - * to gain access to all the components. - * - * @param propertiesFile path to properties file - * @return Main, extending OpenMap - * @see #getMapHandler - */ - public static Main create(String propertiesFile) { - Debug.init(); - return new Main(configurePropertyHandler(propertiesFile)); - } - - /** - * A Main OpenMap application. - */ - static public void main(String args[]) { - - ArgParser ap = new ArgParser("Main"); - String propArgs = null; - ap.add("properties", "A resource, file path or URL to properties file\n Ex: http://myhost.com/xyz.props or file:/myhome/abc.pro\n See Java Documentation for java.net.URL class for more details", 1); - - ap.parse(args); - - String[] arg = ap.getArgValues("properties"); - if (arg != null) { - propArgs = arg[0]; - } - - Main.create(propArgs); - } - - // - /** - * get the logger - * - * @return Logger for Main. - */ - protected static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - /** - * Holder for this class Logger. This allows for lazy initialization of the - * logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Main.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - // -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/app/OpenMap.java b/src/core/src/main/java/com/bbn/openmap/app/OpenMap.java deleted file mode 100644 index 972aaa3ae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/OpenMap.java +++ /dev/null @@ -1,247 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/app/OpenMap.java,v $ -// $RCSfile: OpenMap.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.app; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.gui.MapPanel; -import com.bbn.openmap.gui.OpenMapFrame; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * The OpenMap application framework. This class creates a PropertyHandler that - * searches the classpath, config directory and user's home directory for an - * openmap.properties file, and creates the application based on the contents of - * the properties files. It also creates an MapPanel and an OpenMapFrame to be - * used for the application and adds them to the MapHandler contained in the - * MapPanel. All other components are added to that MapHandler as well, and they - * use the MapHandler to locate, connect and communicate with each other. - */ -public class OpenMap { - - protected MapPanel mapPanel; - - /** - * Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame, - * and brings up the layer palettes that are being told to be open at - * startup. The MapPanel will create a PropertiesHandler that will search - * for an openmap.properties file. - */ - public OpenMap() { - this((PropertyHandler) null); - } - - /** - * Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame, - * and brings up the layer palettes that are being told to be open at - * startup. The properties in the PropertyHandler will be used to configure - * the application. PropertyHandler may be null. - */ - public OpenMap(PropertyHandler propertyHandler) { - configureMapPanel(propertyHandler); - - // Schedule a job for the event-dispatching thread: - // creating and showing this application's GUI. - javax.swing.SwingUtilities.invokeLater(new Runnable() { - public void run() { - // TODO There's something going on here with the progress - // reporter and the swing thread that is causing the app to hang - // in Leopard. - showInFrame(); - } - }); - } - - protected void configureMapPanel(PropertyHandler propertyHandler) { - BasicMapPanel basicMapPanel = new BasicMapPanel(propertyHandler, true); - // Creates the components in the main application thread. If any of - // these components need to update their GUI, they should hand a - // Runnable object to the SwingUtilities.invokeLater(Runnable) method, - // and it will be updated accordingly. - basicMapPanel.create(); - mapPanel = basicMapPanel; - } - - protected void showInFrame() { - - MapHandler mapHandler = getMapHandler(); - - OpenMapFrame omf = (OpenMapFrame) mapHandler.get(com.bbn.openmap.gui.OpenMapFrame.class); - - if (omf == null) { - /* - * If there is no OpenMapFrame specified in the properties file, we - * need to create one and configure it from the current properties. - */ - omf = new OpenMapFrame(Environment.get(Environment.Title)); - - PropertyHandler propertyHandler = (PropertyHandler) mapHandler.get(com.bbn.openmap.PropertyHandler.class); - if (propertyHandler != null) { - // Use the default property prefix for the default window - // property settings. - omf.setProperties("openmap", propertyHandler.getProperties()); - } - - getMapHandler().add(omf); - } - - setWindowListenerOnFrame(omf); - - omf.setVisible(true); - mapPanel.getMapBean().showLayerPalettes(); - getLogger().fine("OpenMap: READY"); - } - - /** - * A method called internally to set the WindowListener behavior on an - * OpenMapFrame used for the OpenMap application. By default, this method - * adds a WindowAdapter that calls System.exit(0), killing java. You can - * extend this to add a WindowListener to the OpenMapFrame that does nothing - * or something else. - */ - protected void setWindowListenerOnFrame(OpenMapFrame omf) { - omf.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - } - - /** - * Get the MapHandler used for the OpenMap object. - */ - public MapHandler getMapHandler() { - return mapPanel.getMapHandler(); - } - - /** - * Get the MapPanel, the container for the OpenMap components. - */ - public MapPanel getMapPanel() { - return mapPanel; - } - - /** - * Create and return an OpenMap object that uses a standard PropertyHandler - * to configure itself. The OpenMap object has a MapHandler that you can use - * to gain access to all the components. - * - * @return OpenMap - * @see #getMapHandler - */ - public static OpenMap create() { - return new OpenMap(null); - } - - /** - * Create and return an OpenMap object that uses a standard PropertyHandler - * to configure itself. The OpenMap object has a MapHandler that you can use - * to gain access to all the components. - * - * @return OpenMap - * @see #getMapHandler - */ - public static OpenMap create(String propertiesFile) { - Debug.init(); - return new OpenMap(configurePropertyHandler(propertiesFile)); - } - - /** - * Given a path to a properties file, try to configure a PropertyHandler - * with it. If the properties file is not valid, the returned - * PropertyHandler will look for the openmap.properties file in the - * classpath and the user's home directory. - */ - public static PropertyHandler configurePropertyHandler(String propertiesFile) { - - try { - return new PropertyHandler.Builder().setPropertiesFile(propertiesFile).build(); - } catch (MalformedURLException murle) { - getLogger().log(Level.WARNING, murle.getMessage(), murle); - } catch (IOException ioe) { - getLogger().log(Level.WARNING, ioe.getMessage(), ioe); - } - - return new PropertyHandler(); - } - - /** - * The main OpenMap application. - */ - static public void main(String args[]) { - - ArgParser ap = new ArgParser("OpenMap"); - String propArgs = null; - ap.add("properties", "A resource, file path or URL to properties file\n Ex: http://myhost.com/xyz.props or file:/myhome/abc.pro\n See Java Documentation for java.net.URL class for more details", 1); - - ap.parse(args); - - String[] arg = ap.getArgValues("properties"); - if (arg != null) { - propArgs = arg[0]; - } - - OpenMap.create(propArgs); - } - - // - /** - * get the logger - * - * @return Logger for OpenMap class. - */ - protected static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - /** - * Holder for this class Logger. This allows for lazy initialization of the - * logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(OpenMap.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - // - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/app/OpenMapApplet.java b/src/core/src/main/java/com/bbn/openmap/app/OpenMapApplet.java deleted file mode 100644 index 6aef9af03..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/OpenMapApplet.java +++ /dev/null @@ -1,377 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/app/OpenMapApplet.java,v $ -// $RCSfile: OpenMapApplet.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/07/29 19:17:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.app; - -import java.awt.Container; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Iterator; - -import javax.swing.JApplet; -import javax.swing.JMenuBar; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.gui.MapPanel; -import com.bbn.openmap.util.Debug; - -/** - * OpenMap Applet. Uses the MapHandler, via BeanContextMembershipListener - * methods to lay out the MapPanel and JMenuBar. Creates a PropertyHandler that - * will look for the openmap.properties file in the codebase. If the - * - *

- * PROPERTIES
- * 
- * - * applet parameter is specified with a different properties file, that file - * will be used instead. - */ -public class OpenMapApplet - extends JApplet - implements BeanContextMembershipListener, BeanContextChild { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public final static String PropertiesProperty = "PROPERTIES"; - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - private BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - // pinfo used to have these parameters, too, but that doesn't - // seem right to include visibroker arguments in the generic - // applet parameter info. - // {"ORBdisableLocator", "boolean", "disable Visiborker - // Gatekeeper"}, - // {"ORBgatekeeperIOR", "boolean", "URL to gatekeeper IOR."}, - - protected final String pinfo[][] = { - { - Environment.Latitude, - "float", - "Starting center latitude" - }, - { - Environment.Longitude, - "float", - "Starting center longitude" - }, - { - Environment.Scale, - "float", - "Starting Scale" - }, - { - Environment.Projection, - "String", - "Default projection type" - }, - { - "debug.basic", - "none", - "enable basic debugging" - }, - { - Environment.HelpURL, - "String", - "URL location of OpenMap help pages" - } - }; - - /** - * Returns information about this applet. - *

- * - * @return a string containing information about the author, version, and - * copyright of the applet. - * @since JDK1.0 - */ - public String getAppletInfo() { - return MapBean.getCopyrightMessage(); - } - - /** - * Returns information about the parameters that are understood by this - * applet. - *

- * Each element of the array should be a set of three Strings - * containing the name, the type, and a description. For example: - *

- *

- * - *
-     * String pinfo[][] = {
-     *     {
-     *         "fps",
-     *         "1-10",
-     *         "frames per second"
-     *     },
-     *     {
-     *         "repeat",
-     *         "boolean",
-     *         "repeat image loop"
-     *     },
-     *     {
-     *         "imgs",
-     *         "url",
-     *         "images directory"
-     *     }
-     * };
-     * 
- * - *
- *

- * - * @return an array describing the parameters this applet looks for. - * @since JDK1.0 - */ - public String[][] getParameterInfo() { - return pinfo; - } - - /** - * Called by the browser or applet viewer to inform this applet that it has - * been loaded into the system. It is always called before the first time - * that the start method is called. - *

- * The implementation of this method provided by the Applet - * class does nothing. - * - * @see java.applet.Applet#destroy() - * @see java.applet.Applet#start() - * @see java.applet.Applet#stop() - * @since JDK1.0 - */ - public void init() { - // Initialize as an applet - Environment.init(this); - Debug.init(this, new String[] { - "debug.basic", - "debug.cspec", - "debug.layer", - "debug.mapbean", - "debug.plugin" - }); - - String propValue = getParameter(PropertiesProperty); - PropertyHandler propHandler = null; - - try { - if (propValue != null) { - PropertyHandler.Builder builder = new PropertyHandler.Builder().setPropertiesFile(propValue); - propHandler = new PropertyHandler(builder); - if (Debug.debugging("app")) { - Debug.output("OpenMapApplet: Using properties from " + propValue); - } - } - } catch (MalformedURLException murle) { - Debug.error("OpenMap: property file specified: " + propValue - + " doesn't exist, searching for default openmap.properties file..."); - } catch (IOException ioe) { - Debug.error("OpenMap: There is a problem using the property file specified: " + propValue - + ", searching for default openmap.properties file..."); - } - - if (propHandler == null) { - propHandler = new PropertyHandler(); - } - - MapPanel mapPanel = new BasicMapPanel(propHandler); - mapPanel.getMapHandler().add(this); - Debug.message("app", "OpenMapApplet.init()"); - } - - /** - * Called by the browser or applet viewer to inform this applet that it - * should start its execution. It is called after the init - * method and each time the applet is revisited in a Web page. - *

- * - * @see java.applet.Applet#destroy() - * @see java.applet.Applet#init() - * @see java.applet.Applet#stop() - * @since JDK1.0 - */ - public void start() { - Debug.message("app", "OpenMapApplet.start()"); - super.start(); - } - - /** - * Called by the browser or applet viewer to inform this applet that it - * should stop its execution. It is called when the Web page that contains - * this applet has been replaced by another page, and also just before the - * applet is to be destroyed. - *

- * - * @see java.applet.Applet#destroy() - * @see java.applet.Applet#init() - * @since JDK1.0 - */ - public void stop() { - Debug.message("app", "OpenMapApplet.stop()"); - super.stop(); - } - - /** - * Called by the browser or applet viewer to inform this applet that it is - * being reclaimed and that it should destroy any resources that it has - * allocated. The stop method will always be called before - * destroy. - *

- * - * @see java.applet.Applet#init() - * @see java.applet.Applet#start() - * @see java.applet.Applet#stop() - * @since JDK1.0 - */ - public void destroy() { - Debug.message("app", "OpenMapApplet.destroy()"); - super.destroy(); - } - - /** - * The method called by BeanContextMembershipListener methods to find - * components in the MapHandler. - */ - @SuppressWarnings("rawtypes") - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Called when an object is added to the MapHandler. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapPanel && someObj instanceof Container) { - getContentPane().add((Container) someObj); - - JMenuBar jmb = ((MapPanel) someObj).getMapMenuBar(); - if (jmb != null) { - Debug.message("basic", "OpenMapApplet: Got MenuBar from MapPanel"); - getRootPane().setJMenuBar(jmb); - } - - invalidate(); - } - - if (someObj instanceof JMenuBar) { - getRootPane().setJMenuBar((JMenuBar) someObj); - invalidate(); - } - } - - /** - * BeanContextMembership interface method. Called when objects are added to - * the BeanContext. - * - * @param bcme contains an Iterator that lets you go through the new - * objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembership interface method. Called by BeanContext when - * children are being removed. Unhooks itself from the objects that are - * being removed if they are contained within the Frame. - * - * @param bcme event that contains an Iterator to use to go through the - * removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - for (@SuppressWarnings("rawtypes") - Iterator it = bcme.iterator(); it.hasNext();) { - findAndUndo(it.next()); - } - } - - /** - * Called when an object is removed from the MapHandler. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapPanel && someObj instanceof Container) { - Debug.message("basic", "OpenMapApplet: MapPanel is being removed from applet"); - getContentPane().remove((Container) someObj); - - if (getJMenuBar() == ((MapPanel) someObj).getMapMenuBar()) { - Debug.message("basic", "OpenMapApplet: Menu Bar is being removed"); - setJMenuBar(null); - } - } - - if (someObj instanceof JMenuBar) { - if (getJMenuBar() == (JMenuBar) someObj) { - Debug.message("basic", "OpenMapApplet: MenuBar is being removed from applet"); - setJMenuBar(null); - } - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. - * - * @param in_bc The context to which this object is being added - */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/app/TimeFrameApp.java b/src/core/src/main/java/com/bbn/openmap/app/TimeFrameApp.java deleted file mode 100644 index 6e0cef7d1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/TimeFrameApp.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.bbn.openmap.app; - -import java.awt.Component; - -import javax.swing.JMenuBar; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.event.OMEventSelectionCoordinator; -import com.bbn.openmap.gui.HotwashPanel; -import com.bbn.openmap.gui.MapPanel; -import com.bbn.openmap.gui.OpenMapFrame; -import com.bbn.openmap.gui.event.EventListPresenter; -import com.bbn.openmap.gui.event.EventPanel; -import com.bbn.openmap.gui.time.TimePanel; -import com.bbn.openmap.time.Clock; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -/** - * An application that demonstrates the use of temporal GUI widgets and - * infrastructure components. The OpenMapFrame contains a HotwashPanel, which - * itself contains slider panes for various components. The standard OpenMap - * MapPanel is in the center of the application. The TimePanel, for controlling - * the current time displayed, goes on the bottom, and the event panel showing a - * list of events goes to the west. - */ -public class TimeFrameApp extends Main { - - public TimeFrameApp() {} - - public TimeFrameApp(PropertyHandler propertyHandler) { - super(propertyHandler); - } - - /** - * A method that lets you control what gets added to the application - * programmatically. These components are required for handling an - * OMEventHandler, which would be added to the MapHandler. If you wanted to - * use the standard OpenMap application, you could add these components to - * the MapHandler, instead. - */ - protected void configureMapPanel(PropertyHandler propertyHandler) { - super.configureMapPanel(propertyHandler); - MapHandler mapHandler = mapPanel.getMapHandler(); - - HotwashPanel hotwashPanel = new HotwashPanel(); - String hotwash = "hotwash"; - // This is important - the property prefix is checked against parent - // names of MapPanelChildren, so the HotwashPanel can figure out what - // goes to itself vs. the BasicMapPanel holding the map. - hotwashPanel.setPropertyPrefix(hotwash); - mapHandler.add(hotwashPanel); - - mapHandler.add(new OMEventSelectionCoordinator()); - - TimePanel timePanel = new TimePanel(); - timePanel.setParentName(hotwash); - mapHandler.add(timePanel); - - EventPanel eventPanel = new EventPanel(); - eventPanel.setParentName(hotwash); - mapHandler.add(eventPanel); - - EventListPresenter eventListPresenter = new EventListPresenter(); - mapHandler.add(eventListPresenter); - - mapHandler.add(new Clock()); - } - - @SuppressWarnings("serial") - protected void showInFrame() { - OpenMapFrame omf = (OpenMapFrame) getMapHandler().get(OpenMapFrame.class); - - if (omf == null) { - omf = new OpenMapFrame() { - public void considerForContent(Object someObj) { - if (someObj instanceof HotwashPanel) { - setContent((Component) someObj); - } - - if (someObj instanceof MapPanel) { - JMenuBar jmb = ((MapPanel) someObj).getMapMenuBar(); - if (jmb != null) { - getRootPane().setJMenuBar(jmb); - } - } - } - }; - omf.setTitle("TimeFrame"); - getMapHandler().add(omf); - setWindowListenerOnFrame(omf); - } - - omf.setVisible(true); - mapPanel.getMapBean().showLayerPalettes(); - Debug.message("basic", "OpenMap: READY"); - } - - /** - * The main OpenMap application. - */ - static public void main(String args[]) { - Debug.init(); - ArgParser ap = new ArgParser("TimeFrameApp"); - ap.add("properties", - "A resource, file path or URL to properties file\n Ex: http://myhost.com/xyz.props or file:/myhome/abc.pro\n See Java Documentation for java.net.URL class for more details", - 1); - - ap.parse(args); - - String propArgs = null; - String[] arg = ap.getArgValues("properties"); - if (arg != null) { - propArgs = arg[0]; - } - - new TimeFrameApp(configurePropertyHandler(propArgs)); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap.java b/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap.java deleted file mode 100644 index 306e3d90d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/examples/simple/SimpleMap.java,v $ -// $RCSfile: SimpleMap.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.app.example; - -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.layer.shape.ShapeLayer; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Properties; -import javax.swing.JFrame; - -/** - * This is a simple application that uses the OpenMap MapBean to show a map. - * This sample application is just provided to show the simplest way to put a - * map in a java application. If you want a the best example to use for a simple - * application to play with OpenMap components, use SimpleMap2! Use a MapPanel! - *

- * This example shows: - *

    - *
  • MapBean - *
  • ShapeLayer with political data - *
- */ -public class SimpleMap { - - public static void main(String args[]) { - - BasicMapPanel mapPanel = new BasicMapPanel(); - - // Create a ShapeLayer to show world political boundaries. - // Set the properties of the layer. This assumes that the - // "data" directory containing the files "dcwpo-browse.shp" - // and "dcwpo-browse.ssx" are in a path specified in the - // CLASSPATH variable. These files are distributed with - // OpenMap and reside in the toplevel "share" subdirectory. - ShapeLayer shapeLayer = new ShapeLayer(); - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "data/shape/dcwpo-browse.shp"); - shapeLayerProps.put("spatialIndex", "data/shape/dcwpo-browse.ssx"); - shapeLayer.setProperties(shapeLayerProps); - - // Add the political layer to the map - mapPanel.getMapBean().add(shapeLayer); - - // Create a Swing frame - JFrame frame = new JFrame("Simple Map"); - // Size the frame appropriately - frame.setSize(640, 480); - // Add the map to the frame - frame.getContentPane().add(mapPanel); - - // If you close the frame, exit the app. - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - // Display the frame - frame.setVisible(true); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap2.java b/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap2.java deleted file mode 100644 index a34fc5fef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/example/SimpleMap2.java +++ /dev/null @@ -1,162 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/examples/simple/SimpleMap2.java,v $ -// $RCSfile: SimpleMap2.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/05/23 19:46:57 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.app.example; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Properties; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MultipleSoloMapComponentException; -import com.bbn.openmap.gui.LayersPanel; -import com.bbn.openmap.gui.MapPanel; -import com.bbn.openmap.gui.OpenMapFrame; -import com.bbn.openmap.gui.OverlayMapPanel; -import com.bbn.openmap.gui.ToolPanel; -import com.bbn.openmap.layer.GraticuleLayer; -import com.bbn.openmap.layer.learn.BasicLayer; -import com.bbn.openmap.layer.shape.BufferedShapeLayer; -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * This is a simple application that uses the OpenMap MapBean to show a map. - * This is the model you should follow if you are starting to use OpenMap and - * want to create your own application. Use a MapPanel! Use the MapHandler - * inside it! - *

- * This example shows: - *

    - *
  • MapBean - *
  • MapHandler - *
  • LayerHandler - *
  • LayersPanel - *
  • ShapeLayer with political data - *
  • GraticuleLayer - *
  • BasicLayer with some random data - *
  • Tools to navigate around on the map - *
- */ -public class SimpleMap2 { - - public SimpleMap2() { - - try { - - /* - * The OverlayMapPanel automatically creates many default - * components, including the MapBean and the MapHandler. You can - * extend the BasicMapPanel/Overlay class if you like to add - * different functionality or different types of objects. The - * OverlayMapPanel has navigation widgets built on top of the map. - * Using the standard configuration adds a LayerHandler, - * MouseDelegator and OMMouseMode to the OverlayMapPanel. - */ - MapPanel mapPanel = OverlayMapPanel.standardConfig(); - - /* - * The MapHandler is central to this application, although you never - * really see it. It's in the MapPanel. Calling addMapComponent(obj) - * is the same as calling mapPanel.getMapHandler().add(obj). - */ - - // Add a ToolPanel for widgets on the north side of the map. - mapPanel.addMapComponent(new ToolPanel()); - // Add a LayersPanel, which lets you control layers. - // addLayerControls() - // returns the LayersPanel. - mapPanel.addMapComponent(new LayersPanel().addLayerControls()); - - /* - * Create a ShapeLayer to show world political boundaries. Set the - * properties of the layer. This assumes that the datafile - * "cntry02.shp" is in a path specified in the CLASSPATH variable. - * These files are distributed with OpenMap and reside in the top - * level "share" sub-directory. - */ - ShapeLayer shapeLayer = new BufferedShapeLayer(); - - // Since this Properties object is being used just for - // this layer, the properties do not have to be scoped - // with marker name. - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "data/shape/cntry02/cntry02.shp"); - shapeLayer.setProperties(shapeLayerProps); - shapeLayer.setVisible(true); - - // Last on top. - mapPanel.addMapComponent(shapeLayer); - mapPanel.addMapComponent(new GraticuleLayer()); - mapPanel.addMapComponent(new BasicLayer()); - - // Create a Swing frame. The OpenMapFrame knows how to use - // the MapHandler to locate and place certain objects. - OpenMapFrame frame = new OpenMapFrame("Simple Map 2"); - // Size the frame appropriately - frame.setSize(640, 480); - - mapPanel.addMapComponent(frame); - - // If you close the frame, exit the app - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - // Display the frame - frame.setVisible(true); - - // Set the map to a location and scale. Get the default MapBean that - // the BasicMapPanel created. - MapBean mapBean = mapPanel.getMapBean(); - // Set the map's center - mapBean.setCenter(new LatLonPoint.Double(43.0, -95.0)); - // Set the map's scale 1:120 million - mapBean.setScale(120000000f); - - } catch (MultipleSoloMapComponentException msmce) { - // The MapHandler is only allowed to have one of certain - // items. These items implement the SoloMapComponent - // interface. The MapHandler can have a policy that - // determines what to do when duplicate instances of the - // same type of object are added - replace or ignore. - - // In this example, this will never happen, since we are - // controlling that one MapBean, LayerHandler, - // MouseDelegator, etc is being added to the MapHandler. - } - } - - public static void main(String[] args) { - // Schedule a job for the event-dispatching thread: - // creating and showing this application's GUI. - javax.swing.SwingUtilities.invokeLater(new Runnable() { - public void run() { - new SimpleMap2(); - } - }); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/app/example/package.html b/src/core/src/main/java/com/bbn/openmap/app/example/package.html deleted file mode 100644 index d40d8df99..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/example/package.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Example applications that use OpenMap components. SimpleMap2 is the example you should -focus on if you want to build up an application using basic components. You'll want to -use the MapPanel, which will include an MapHandler and a MapBean. The MapBean is the -main map window. The MapHandler is the application glue, the component that presents -all components to all others. OpenMap components have been written to find each other -using the MapHandler. -

-The SimpleMap application is just a bare-bones application of using a MapBean -and a layer to create a map in a frame. It seems like this is a good starting point, -but trust me, SimpleMap2 is the better starting point. -

-The Main and OpenMap applications are simple expansions of SimpleMap2, using the -PropertyHandler to specify components in a properties file. - - diff --git a/src/core/src/main/java/com/bbn/openmap/app/package.html b/src/core/src/main/java/com/bbn/openmap/app/package.html deleted file mode 100644 index 065b573ec..000000000 --- a/src/core/src/main/java/com/bbn/openmap/app/package.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides the basic OpenMap applet and application classes. The -OpenMap application framework can be used to create any type of -application, simply by modifying the openmap.properties file. By -changing what components and layers that are added to the application, -you can control the look and functionality of it. - - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPConstants.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPConstants.java deleted file mode 100644 index 4f63adeb4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPConstants.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/ASRPConstants.java,v -// $ -// $RCSfile: ASRPConstants.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -public interface ASRPConstants { - - /** File suffix for General Information File. */ - public final static String GEN_NAME = "GEN"; - /** File suffix for Geo Reference File. */ - public final static String GER_NAME = "GER"; - /** File suffix for Source File. */ - public final static String SOURCE_NAME = "SOU"; - /** File suffix for Quality File. */ - public final static String QAL_NAME = "QAL"; - /** Transmitter header file name. Always. */ - public final static String TRANS = "TRANSH01.THF"; - /** File suffix for Main Raster Image. */ - public final static String IMAGE_NAME = "IMG"; - - // The Raster legend image is Lcc, where 'cc' is the number - // assigned to the image's source graphic. - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectory.java deleted file mode 100644 index d6a2f482d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectory.java +++ /dev/null @@ -1,594 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/ASRPDirectory.java,v $ -// $RCSfile: ASRPDirectory.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/12/09 21:09:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.awt.Color; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.geom.Point2D; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import com.bbn.openmap.dataAccess.iso8211.DDFField; -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFSubfield; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * An ASRP directory contains information needed to view images. It contains - * multiple files, each containing complementary information about the image. - * The GeneralInformationFile (GEN) contains information about the image such as - * coverage and location. The QualityFile (QAL) contains accuracy and color - * information. The GeoReferenceFile (GER) contains projection information, the - * SourceFile (SOU) contains information about the map that was used to create - * the images. The RasterGeoDataFile (IMG) contains the actual pixel - * information. - *

- * - * This class knows how to use all of these files to create images, which are - * made up of subframe tiles called blocks. - */ -public class ASRPDirectory extends CacheHandler implements ASRPConstants { - - protected GeneralInformationFile gen; - protected QualityFile qal; - protected RasterGeoDataFile img; - protected GeoReferenceFile ger; - protected SourceFile sou; - - /** List of tile indexes. */ - protected List tsi; - /** Number of horizontal blocks. */ - protected int numHorBlocks_N; - /** Number of vertical blocks. */ - protected int numVerBlocks_M; - /** Number of horizontal pixels per block. */ - protected int numHorPixels_Q; - /** Number of vertical pixels per block. */ - protected int numVerPixels_P; - /** - * When reading image bytes, the number of bits that represent the number of - * pixels the next color index stands for. - */ - protected int pixelCountBits; - /** - * When reading image bytes, the number of bits that represent the color - * index. - */ - protected int pixelValueBits; - - /* Bounding coordinates for coverage. */ - protected float swo, nea, neo, swa; // west lon, north lat, east - // lon, south lat - /* Upper left latitude/longitude for top left tile. */ - protected float lso, pso; // padded longitude, latitude of upper - // left image corner - /** Number of pixels 360 degrees east - west. */ - protected int arv; - /** Number of pixels 360 degrees north - south. */ - protected int brv; - /** - * Calculated number of degrees per block in the horizontal direction. - */ - protected float degPerHorBlock; - /** - * Calculated number of degrees per block in the vertical direction. - */ - protected float degPerVerBlock; - /** Byte offset into the IMG file where tile data starts. */ - protected int tileDataOffset; - /** The colors from the QAL file. */ - protected Color[] colors; - /** The OMRect used to track coverage boundaries. */ - protected OMRect bounds; - - protected File dir; - - /** - * Protective mechanism, doesn't display data that has images with a base - * scale that is more than a factor of the scaleFactor away from the scale - * of the map. - */ - protected double scaleFactor = 4; - - /** - * Create a new ASRP directory for the given path. Calls initialize() which - * will read in the different files to find out the attribute information - * about the data. - */ - public ASRPDirectory(String path) { - - dir = new File(path); - - if (dir.exists()) { - try { - initialize(dir.getPath(), dir.getName(), "01"); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - ioe.printStackTrace(); - return; - } - } else { - Debug.error("ASRPDirectory (" + path + ") doesn't exist"); - } - - } - - public String getPath() { - if (dir != null) { - return dir.getPath(); - } - return null; - } - - /** - * Get the OMRect used for calculating coverage area. - */ - public OMRect getBounds() { - if (bounds == null) { - bounds = new OMRect(pso, lso, pso - degPerVerBlock * numVerBlocks_M, lso - + degPerHorBlock * numHorBlocks_N, OMGraphic.LINETYPE_GREATCIRCLE); - } - - return bounds; - } - - public void setScaleFactor(double scaleFactorIn) { - scaleFactor = scaleFactorIn; - } - - public double getScaleFactor() { - return scaleFactor; - } - - /** - * Return true of current bounds covers the projection area. - */ - public boolean isOnMap(Projection proj) { - OMRect bds = getBounds(); - bds.generate(proj); - Shape s = bds.getShape(); - return s.intersects(0, 0, proj.getWidth(), proj.getHeight()); - } - - public boolean validScale(Projection proj) { - if (proj instanceof EqualArc) { - EqualArc ea = (EqualArc) proj; - double xPixConstant = ea.getXPixConstant(); - - double scale = xPixConstant / arv; - - boolean result = (scale < scaleFactor) && (scale > 1 / scaleFactor); - if (Debug.debugging("asrp")) { - Debug.output("Scale comparing arv = " + arv + ", " - + xPixConstant + ", result: " + result); - } - return result; - } - return false; - } - - /** - * Get an OMGraphicList of files that cover the projection. Returns an empty - * list if the coverage isn't over the map. - */ - public OMGraphicList checkProjAndGetTiledImages(Projection proj) - throws IOException { - - if (!isOnMap(proj) || !validScale(proj)) { - // off the map - return new OMGraphicList(); - } - - return getTiledImages(proj); - } - - /** - * Assumes that the projection checks have occurred, have passed, and just - * fetches the image tiles. - */ - public OMGraphicList getTiledImages(Projection proj) throws IOException { - - float ullat = pso; - float ullon = lso; - float lrlat = ullat - (degPerVerBlock * numVerBlocks_M); - float lrlon = ullon + (degPerHorBlock * numHorBlocks_N); - - Point2D llp1 = proj.getUpperLeft(); - Point2D llp2 = proj.getLowerRight(); - - int startX = (int) Math.floor((llp1.getX() - ullon) / degPerHorBlock); - int startY = (int) Math.floor((ullat - llp1.getY()) / degPerVerBlock); - - int endX = numHorBlocks_N - - (int) Math.floor((lrlon - llp2.getX()) / degPerHorBlock); - int endY = numVerBlocks_M - - (int) Math.floor((llp2.getY() - lrlat) / degPerVerBlock); - - if (startX < 0) - startX = 0; - if (startY < 0) - startY = 0; - - if (endX > numHorBlocks_N) - endX = numHorBlocks_N; - if (endY > numVerBlocks_M) - endY = numVerBlocks_M; - - return getTiledImages(new Rectangle(startX, startY, endX - startX, endY - - startY), proj); - } - - /** - * Provide an OMGraphicList containing the tile blocks described by the - * rectangle. - * - * @param rect rectangle defining the tile blocks to get. rect.x and rect.y - * describe the starting upper left block to get, rect.getWidth and - * rect.getHeight describe the number of tiles to the right and down - * from the first block to collect. - */ - protected OMGraphicList getTiledImages(Rectangle rect, Projection proj) - throws IOException { - - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirectory: fielding request for " + rect); - } - - OMGraphicList list = new OMGraphicList(); - - int startX = (int) rect.getX(); - int startY = (int) rect.getY(); - int endX = startX + (int) rect.getWidth(); - int endY = startY + (int) rect.getHeight(); - - for (int x = startX; x < endX; x++) { - for (int y = startY; y < endY; y++) { - OMGraphic omg = (OMGraphic) get(new String(x + "," + y).intern()); - if (omg != null) { - omg.generate(proj); - list.add(omg); - } - } - } - - return list; - } - - /** - * Fetch the subframe tile block from the IMG file. - */ - public OMScalingRaster getBlock(int x, int y) throws IOException { - float ullat = pso - y * degPerVerBlock; - float ullon = lso + x * degPerHorBlock; - float lrlat = ullat - degPerVerBlock; - float lrlon = ullon + degPerHorBlock; - - // Get image data. - if (tsi != null) { - - int index = y * numHorBlocks_N + x; - - // Check for not blowing the list end... - if (index >= tsi.size()) { - return null; - } - - // Subtracting one because the values look like they start - // with 1. - int blockOffset = ((DDFSubfield) tsi.get(index)).intValue() - 1; - - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirectory.getBlock: index of (" + x + ", " - + y + ") is " + blockOffset); - } - - if (blockOffset < 0) { - // Can't have a negative offset... - if (Debug.debugging("asrp")) { - Debug.output(" skipping..."); - } - - return null; - } - - DDFModule mod = img.getInfo(); - mod.seek(tileDataOffset + blockOffset); - - int byteCount = 0; // Which data byte is being set - int numBlockPixels = numHorPixels_Q * numVerPixels_P; - byte[] data = new byte[numBlockPixels]; // image byte data - - int rowCount = 0; // the per row count, should equal 128 ( - // numHorPixels_Q) at the end of every - // row - int cpc = 0; // current pixel count for file pointer - int cpv = 0; // current pixel value for file pointer - while (byteCount < numBlockPixels) { - switch (pixelCountBits) { - case 8: - cpc = mod.read(); - break; - case 4: - cpc = mod.read() >> 4; - // need to back pointer up 4 bits before reading - // cpv?? - Debug.output("CAUTION: 4 bit count"); - break; - default: - cpc = 1; - } - - cpv = mod.read(); - - // OK, cpv has value, cpc says how many pixels that - // goes in. - - try { - for (int c = 0; c < cpc; c++) { - rowCount++; - if (colors != null && cpv > colors.length) { - if (Debug.debugging("asrpdetail")) { - Debug.output("Got value that is too big for colortable"); - } - } - data[byteCount + c] = (byte) cpv; - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirectory.getBlock(): bad index for setting byte value: " - + aioobe.getMessage()); - } - // This try/catch block is really for the data[] - // array indexing. - - // if byteCount + x was greater than - // numBlockPixels, - // we should be at the end of the image bytes, so - // we - // shouldn't have to worry about rowCount not - // being - // properly updated. - } - - byteCount += cpc; - if (rowCount == numHorPixels_Q) { - rowCount = 0; - } - } - - if (Debug.debugging("asrpdetail")) { - Debug.output("ASRPDirectory creating image covering (" + ullat - + ", " + ullon + "), (" + lrlat + ", " + lrlon + ")"); - } - - return new OMScalingRaster(ullat, ullon, lrlat, lrlon, numHorPixels_Q, numVerPixels_P, data, getColors(), 255); - } - - return null; - } - - /** - * Get the colors from the QAL file. - */ - protected Color[] getColors() { - if (colors == null) { - DDFField col = qal.getField(QualityFile.COLOUR_CODE_ID); - - List reds = col.getSubfields("NSR"); - List greens = col.getSubfields("NSG"); - List blues = col.getSubfields("NSB"); - - int numColors = reds.size(); - colors = new Color[numColors]; - - for (int count = 0; count < numColors; count++) { - int red = ((DDFSubfield) reds.get(count)).intValue(); - int green = ((DDFSubfield) greens.get(count)).intValue(); - int blue = ((DDFSubfield) blues.get(count)).intValue(); - // Debug.output("Created color " + count + " with " + - // red + ", " + green + ", " + blue); - // The zero color is supposed to tbe null color, and - // clear. Doesn't seem to be working. - colors[count] = new Color(red, green, blue, (count == 0 ? 0 - : 255)); - } - - } - return colors; - } - - /** - * Read in the attribute information about the data. - * - * @param dirPath path to the ASRP directory. - * @param root name of all of the files, usually the same as the ASRP - * directory itself. - * @param DD the occurrence number, usually '01' of the files. - */ - protected void initialize(String dirPath, String root, String DD) - throws IOException { - String rootPath = dirPath + "/" + root + DD + "."; - - gen = new GeneralInformationFile(rootPath + GEN_NAME); - ger = new GeoReferenceFile(rootPath + GER_NAME); - qal = new QualityFile(rootPath + QAL_NAME); - sou = new SourceFile(rootPath + SOURCE_NAME); - img = new RasterGeoDataFile(rootPath + IMAGE_NAME); - - DDFField sprInfo = gen.getField(GeneralInformationFile.DATA_SET_PARAMETERS); - numHorBlocks_N = sprInfo.getSubfield("NFC").intValue(); - numVerBlocks_M = sprInfo.getSubfield("NFL").intValue(); - numHorPixels_Q = sprInfo.getSubfield("PNC").intValue(); - numVerPixels_P = sprInfo.getSubfield("PNL").intValue(); - pixelCountBits = sprInfo.getSubfield("PCB").intValue(); - pixelValueBits = sprInfo.getSubfield("PVB").intValue(); - - // assume there is a tile index map - - DDFField genInfo = gen.getField(GeneralInformationFile.GENERAL_INFORMATION); - swo = genInfo.getSubfield("SWO").floatValue() / 3600f; - neo = genInfo.getSubfield("NEO").floatValue() / 3600f; - nea = genInfo.getSubfield("NEA").floatValue() / 3600f; - swa = genInfo.getSubfield("SWA").floatValue() / 3600f; - lso = genInfo.getSubfield("LSO").floatValue() / 3600f; - pso = genInfo.getSubfield("PSO").floatValue() / 3600f; - - arv = genInfo.getSubfield("ARV").intValue(); - brv = genInfo.getSubfield("BRV").intValue(); - - DDFField timInfo = gen.getField(GeneralInformationFile.TILE_INDEX_MAP); - tsi = timInfo.getSubfields("TSI"); - - DDFField pixelInfo = img.getField(RasterGeoDataFile.PIXEL); - // Finding this out lets you use the tile index map to access - // pixel data. This offset points to the start of the tile - // data. - tileDataOffset = pixelInfo.getHeaderOffset() - + pixelInfo.getDataPosition(); - - degPerHorBlock = 360f / (float) arv * (float) numHorPixels_Q; - degPerVerBlock = 360f / (float) brv * (float) numVerPixels_P; - - if (Debug.debugging("asrp")) { - Debug.output("For " + rootPath + "\n\thave blocks (" - + numHorBlocks_N + ", " + numVerBlocks_M - + ")\n\twith pixels (" + numHorPixels_Q + ", " - + numVerPixels_P + ")"); - Debug.output("\tCoverage from (" + nea + ", " + swo + ") to (" - + swa + ", " + neo + ")"); - Debug.output("\tPadded coverage starting at (" + pso + ", " + lso - + ")"); - Debug.output("\tNumber of pixels 360 e-w (" + arv + ") , n-s (" - + brv + ")"); - Debug.output("\tdegrees per horizontal block: " + degPerHorBlock - + ", vertical: " + degPerVerBlock); - Debug.output("\tImage Data made up of count bits: " - + pixelCountBits + ", value bits: " + pixelValueBits); - - if (Debug.debugging("asrpdetail")) { - Debug.output("Checking..."); - - float latdiff = nea - swa; - float londiff = neo - swo; - - float horPixels = arv * (londiff / 360f); - float verPixels = brv * (latdiff / 360f); - - Debug.output("\tCalculating " + (horPixels / numHorPixels_Q) - + " hor blocks"); - Debug.output("\tCalculating " + (verPixels / numVerPixels_P) - + " hor blocks"); - Debug.output("\tCalculating " - + (lso + degPerHorBlock * numHorBlocks_N) - + " end latitude"); - Debug.output("\tCalculating " - + (pso - degPerVerBlock * numVerBlocks_M) - + " end latitude"); - } - - } - - getColors(); - - gen.close(); - ger.close(); - qal.close(); - sou.close(); - img.close(); - } - - /** - * A private class to store cached images. - */ - private static class ASRPBlockCacheObject extends CacheObject { - /** - * @param id passed to superclass - * @param obj passed to superclass - */ - public ASRPBlockCacheObject(String id, OMGraphic obj) { - super(id, obj); - } - - /** - * Calls dispose() on the contained frame, to make it eligible for - * garbage collection. - */ - //protected void finalize() {} - } - - /** - * Load a block image into the cache, based on the relative coordinates of - * the block as a key. - * - * @param key String of form 'x,y' identifying the relative location of - * the subframe image. - * @return Block image, hidden as a CacheObject. - */ - public CacheObject load(Object key) { - if (key != null) { - String xAndY = key.toString(); - int commaIndex = xAndY.indexOf(','); - int x = Integer.parseInt(xAndY.substring(0, commaIndex)); - int y = Integer.parseInt(xAndY.substring(commaIndex + 1)); - - if (Debug.debugging("asrpdetail")) { - Debug.output("Getting tiled image " + x + ", " + y + " (from " - + xAndY + ")"); - } - - try { - OMGraphic block = getBlock(x, y); - if (block != null) { - return new ASRPBlockCacheObject(xAndY.intern(), block); - } - } catch (IOException ioe) { - Debug.error("ASRPDirectory caught exception creating tiled image for " - + xAndY); - } - } - return null; - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: ASRPDirectory dir_pathname"); - } else { - new ASRPDirectory(argv[0]); - } - - System.exit(0); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectoryHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectoryHandler.java deleted file mode 100644 index 58a36ad40..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/ASRPDirectoryHandler.java +++ /dev/null @@ -1,237 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/ASRPDirectoryHandler.java,v $ -// $RCSfile: ASRPDirectoryHandler.java,v $ -// $Revision: 1.3 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.Debug; - -/** - * The ASRPDirectoryHandler is the main object a layer would use when - * trying to deal with a bunch of ASRP image directories and/or a THF - * file that refers to many ASRP image directories. This object will - * make decisions, based on the coverage of the imagery of a certain - * ASRP directory image and its "scale" (determined by the number of - * pixels E-W of the projection of the image) what images are suitable - * for a given EqualArc projection. - */ -public class ASRPDirectoryHandler { - - protected List asrpDirs; - - public ASRPDirectoryHandler() {} - - public OMGraphicList getCoverageBounds(Projection proj, DrawingAttributes da) { - OMGraphicList list = new OMGraphicList(); - List asrps = getASRPDirs(); - - for (Iterator it = asrps.iterator(); it.hasNext();) { - OMRect rect = ((ASRPDirectory) it.next()).getBounds(); - da.setTo(rect); - rect.generate(proj); - - list.add(rect); - } - return list; - } - - public OMGraphicList getImagesForProjection(EqualArc proj) - throws IOException { - OMGraphicList ret = new OMGraphicList(); - - if (proj == null) { - return null; - } - - List asrps = getASRPDirs(); - List currentBestASRPs = new LinkedList(); - double bestScaleDiff = Double.MAX_VALUE; - Iterator it; - ASRPDirectory current; - - for (it = asrps.iterator(); it.hasNext();) { - try { - current = (ASRPDirectory) it.next(); - } catch (ClassCastException cce) { - Debug.message("asrp", - "ASRPDirectoryHandler.getImagesForProjection: ASRP directory list contains something other than ASRPDirectory objects"); - continue; - } - - if (current.isOnMap(proj) && current.validScale(proj)) { - // Need to check to see if the ASRP Directory is the - // best fit for the current projection scale, since - // it's on the map and within the scale limits. - - double scaleDiff = Math.abs(proj.getXPixConstant() - - current.arv); - - if (scaleDiff < bestScaleDiff) { - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirHandler: SETTING new diff (" - + scaleDiff + ") adding ASRPDirectory " - + current.dir); - } - bestScaleDiff = scaleDiff; - currentBestASRPs.clear(); - currentBestASRPs.add(current); - } else if (scaleDiff == bestScaleDiff) { - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirHandler: USING current diff (" - + scaleDiff + ") adding ASRPDirectory " - + current.dir); - } - currentBestASRPs.add(current); - } - } - } - - // OK, now currentBestASRPs should contain the ASRPDirectories - // that best fit the current projection. If its empty, we - // just return an empty list. - for (it = currentBestASRPs.iterator(); it.hasNext();) { - current = (ASRPDirectory) it.next(); - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirHandler: getting images from " - + current.dir); - } - - OMGraphicList subList = current.getTiledImages(proj); - - if (!subList.isEmpty()) { - ret.add(subList); - } else { - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirHandler: no images retrieved (" - + subList.size() + ")"); - } - } - } - - if (ret.isEmpty()) - ret = null; - - return ret; - } - - public void add(TransmittalHeaderFile thf) { - if (thf != null) { - getASRPDirs().addAll(thf.getASRPDirectories()); - } - } - - public void add(ASRPDirectory asrpDir) { - getASRPDirs().add(asrpDir); - } - - public void remove(TransmittalHeaderFile thf) { - if (thf != null) { - getASRPDirs().removeAll(thf.getASRPDirectories()); - } - } - - public void remove(ASRPDirectory asrpDir) { - getASRPDirs().remove(asrpDir); - } - - public void clear() { - getASRPDirs().clear(); - } - - public List getASRPDirs() { - if (asrpDirs == null) { - asrpDirs = new LinkedList(); - } - return asrpDirs; - } - - public void setASRPDirs(List list) { - asrpDirs = list; - } - - /** - * DataBounds interface method, although this object doesn't - * implement the complete interface because it doesn't have a - * name. - */ - public DataBounds getDataBounds() { - DataBounds box = null; - - double minx = 180; - double miny = 90; - double maxx = -180; - double maxy = -90; - - boolean set = false; - - List asrps = getASRPDirs(); - - for (Iterator it = asrps.iterator(); it.hasNext();) { - OMRect rect = ((ASRPDirectory) it.next()).getBounds(); - double n = rect.getNorthLat(); - double s = rect.getSouthLat(); - double w = rect.getWestLon(); - double e = rect.getEastLon(); - - if (n < miny) - miny = n; - if (n > maxy) - maxy = n; - if (s < miny) - miny = s; - if (s > maxy) - maxy = s; - if (w < minx) - minx = w; - if (w > maxx) - maxx = w; - if (e < minx) - minx = e; - if (e > maxx) - maxx = e; - - set = true; - } - - if (set) { - box = new DataBounds(minx, miny, maxx, maxy); - - if (Debug.debugging("asrp")) { - Debug.output("ASRPDirectoryHandler.getDataBounds(): " - + box.toString()); - } - } - - return box; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralASRPFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralASRPFile.java deleted file mode 100644 index 2a4cdd424..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralASRPFile.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/GeneralASRPFile.java,v -// $ -// $RCSfile: GeneralASRPFile.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.dataAccess.iso8211.DDFField; -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class GeneralASRPFile { - - protected DDFModule info; - protected Hashtable fields = new Hashtable(); - - protected DDFModule load(String fileName) throws IOException { - info = new DDFModule(fileName); - return info; - } - - /** - * If a field has not been loaded, load it from the DDFRecord if - * it exists and add it to the master field hashtable. - */ - protected boolean loadField(DDFRecord record, String tagName, int fieldIndex) { - if (fields.get(tagName) == null) { - DDFField ddf = record.findField(tagName, fieldIndex); - if (ddf != null) { - fields.put(tagName, ddf); - ddf.toString(); - return true; - } - } - return false; - } - - /** - * Add a field to the field list. If a field already exists in the - * hashtable, the DDFField is replaced by a list of the fields - * with the same name. Some types of files need this, like the THF - * file. Others don't seem to. - */ - protected void addField(DDFField ddf) { - - String fName = ddf.getFieldDefn().getName().trim().intern(); - if (Debug.debugging("asrp")) { - Debug.output("GeneralASRPFile.addField(" + fName + ")"); - } - - Object f = fields.get(fName); - - if (f == null) { - fields.put(fName, ddf); - } else { - if (f instanceof List) { - ((List) f).add(ddf); - } else { - Vector subList = new Vector(); - subList.add(f); - subList.add(ddf); - fields.put(fName, subList); - } - } - } - - public List getFields(String tag) { - Object obj = fields.get(tag); - if (obj instanceof List) { - return (List) obj; - } else { - LinkedList ll = new LinkedList(); - ll.add(obj); - return ll; - } - } - - public DDFField getField(String tag) { - Object obj = fields.get(tag); - if (obj instanceof List) { - return (DDFField) ((List) obj).get(0); - } else { - return (DDFField) obj; - } - } - - public void dumpFields() { - for (Iterator it = fields.keySet().iterator(); it.hasNext(); Debug.output(fields.get(it.next()) - .toString())) { - } - } - - protected DDFModule getInfo() { - return info; - } - - protected void close() { - if (info != null) { - info.close(); - } - } - - public void dump() { - if (info != null) { - Debug.output(info.dump()); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralInformationFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralInformationFile.java deleted file mode 100644 index bdd916a8d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeneralInformationFile.java +++ /dev/null @@ -1,77 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/GeneralInformationFile.java,v -// $ -// $RCSfile: GeneralInformationFile.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.awt.Dimension; -import java.io.IOException; - -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class GeneralInformationFile extends GeneralASRPFile { - - public final static String RECORD_ID = "001"; - public final static String DATA_SET_ID = "DSI"; - public final static String GENERAL_INFORMATION = "GEN"; - public final static String DATA_SET_PARAMETERS = "SPR"; - public final static String BAND_ID = "BDF"; - public final static String TILE_INDEX_MAP = "TIM"; - public final static String DATASET_DESCRIPTION = "DRF"; - - protected Dimension subframeDimensions; - - public GeneralInformationFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - loadField(record, DATA_SET_ID, 0); - loadField(record, GENERAL_INFORMATION, 0); - loadField(record, DATA_SET_PARAMETERS, 0); - loadField(record, BAND_ID, 0); - loadField(record, TILE_INDEX_MAP, 0); - loadField(record, DATASET_DESCRIPTION, 0); - } - } - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: GeneralInformationFile filename"); - } - - try { - GeneralInformationFile gen = new GeneralInformationFile(argv[0]); - gen.dumpFields(); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeoReferenceFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeoReferenceFile.java deleted file mode 100644 index d7a1c5402..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/GeoReferenceFile.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/GeoReferenceFile.java,v -// $ -// $RCSfile: GeoReferenceFile.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class GeoReferenceFile extends GeneralASRPFile { - - public final static String GEO_PARAMETERS = "GEP"; - - public GeoReferenceFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - loadField(record, GEO_PARAMETERS, 0); - } - } - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: GeoReferenceFile filename"); - } - - try { - GeoReferenceFile thf = new GeoReferenceFile(argv[0]); - thf.dumpFields(); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/QualityFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/QualityFile.java deleted file mode 100644 index d00367473..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/QualityFile.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/QualityFile.java,v -// $ -// $RCSfile: QualityFile.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class QualityFile extends GeneralASRPFile { - - public final static String SECURITY_AND_RELEASE = "QSR"; - public final static String UP_TO_DATENESS = "QUV"; - public final static String COLOUR_CODE_ID = "COL"; - public final static String OTHER_QUALITY_INFORMATION = "QOI"; - public final static String HORIZONTAL_ACCURACY = "ASH"; - public final static String BOUNDING_POLYGON_COORDINATES = "RCI"; - public final static String VERTICAL_ACCURACY = "ASV"; - - public QualityFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - loadField(record, SECURITY_AND_RELEASE, 0); - loadField(record, UP_TO_DATENESS, 0); - loadField(record, COLOUR_CODE_ID, 0); - loadField(record, OTHER_QUALITY_INFORMATION, 0); - loadField(record, HORIZONTAL_ACCURACY, 0); - loadField(record, BOUNDING_POLYGON_COORDINATES, 0); - loadField(record, VERTICAL_ACCURACY, 0); - } - } - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: QualityFile filename"); - } - - try { - QualityFile thf = new QualityFile(argv[0]); - thf.dumpFields(); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/RasterGeoDataFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/RasterGeoDataFile.java deleted file mode 100644 index b5f32042a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/RasterGeoDataFile.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/RasterGeoDataFile.java,v -// $ -// $RCSfile: RasterGeoDataFile.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class RasterGeoDataFile extends GeneralASRPFile { - - public final static String PADDING = "PAD"; - public final static String PIXEL = "SCN"; - - public RasterGeoDataFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - loadField(record, PADDING, 0); - loadField(record, PIXEL, 0); - } - } - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: RasterGeoDataFile filename"); - } - - try { - RasterGeoDataFile thf = new RasterGeoDataFile(argv[0]); - Debug.output(thf.getField(PIXEL).toString()); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/SourceFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/SourceFile.java deleted file mode 100644 index 10d00dc9e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/SourceFile.java +++ /dev/null @@ -1,91 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/SourceFile.java,v -// $ -// $RCSfile: SourceFile.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.util.Debug; - -public class SourceFile extends GeneralASRPFile { - - public final static String SOURCE_SUMMARY = "SGF"; - public final static String SOURCE = "SOR"; - public final static String MAGNETIC_INFORMATION = "MAG"; - public final static String BOUNDING_POLYGON_COORDINATES = "RCI"; - public final static String PROJECTION_FIELD = "PRR"; - public final static String SECURITY_AND_RELEASE = "QSR"; - public final static String INSET = "INS"; - public final static String COPYRIGHT = "CPY"; - public final static String LEGEND = "LGI"; - public final static String DATA_SET_PARAMETERS = "SPR"; - public final static String TILE_INDEX_MAP = "TIM"; - public final static String NORMALIZATION_CONSTANTS = "NCD"; - public final static String SOURCE_DATUM_COEFFICIENTS_DATA = "SDC"; - public final static String MAP_PROJECTIONS_COEFFICIENTS_DATA = "MPC"; - public final static String SUPPLEMENTARY_TEXT = "SUP"; - - public SourceFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - loadField(record, SOURCE_SUMMARY, 0); - loadField(record, SOURCE, 0); - loadField(record, MAGNETIC_INFORMATION, 0); - loadField(record, BOUNDING_POLYGON_COORDINATES, 0); - loadField(record, PROJECTION_FIELD, 0); - loadField(record, SECURITY_AND_RELEASE, 0); - loadField(record, INSET, 0); - loadField(record, COPYRIGHT, 0); - loadField(record, LEGEND, 0); - loadField(record, DATA_SET_PARAMETERS, 0); - loadField(record, TILE_INDEX_MAP, 0); - loadField(record, NORMALIZATION_CONSTANTS, 0); - loadField(record, SOURCE_DATUM_COEFFICIENTS_DATA, 0); - loadField(record, MAP_PROJECTIONS_COEFFICIENTS_DATA, 0); - loadField(record, SUPPLEMENTARY_TEXT, 0); - } - } - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: SourceFile filename"); - } - - try { - SourceFile thf = new SourceFile(argv[0]); - thf.dumpFields(); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/TransmittalHeaderFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/TransmittalHeaderFile.java deleted file mode 100644 index db932bdf7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/asrp/TransmittalHeaderFile.java +++ /dev/null @@ -1,114 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/asrp/TransmittalHeaderFile.java,v $ -// $RCSfile: TransmittalHeaderFile.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.asrp; - -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.dataAccess.iso8211.DDFField; -import com.bbn.openmap.dataAccess.iso8211.DDFModule; -import com.bbn.openmap.dataAccess.iso8211.DDFRecord; -import com.bbn.openmap.dataAccess.iso8211.DDFSubfield; -import com.bbn.openmap.util.Debug; - -/** - * The transmitter header file contains information about various ASRP - * directories, their names and coverages. This object can be used to - * coordinate the display of ASRP images from different directories. - */ -public class TransmittalHeaderFile extends GeneralASRPFile implements - ASRPConstants { - - public final static String TRANSMITTAL_RECORD = "VDR"; - public final static String DATA_SET_DESCRIPTION = "FDR"; - public final static String SECURITY_AND_RELEASE = "QSR"; - public final static String UP_TO_DATENESS = "QUV"; - - protected String rootDir; - - public TransmittalHeaderFile(String fileName) throws IOException { - DDFModule mod = load(fileName); - rootDir = fileName.substring(0, fileName.indexOf(TRANS)); - - if (mod != null) { - DDFRecord record; - while ((record = mod.readRecord()) != null) { - for (Iterator it = record.iterator(); it.hasNext(); addField((DDFField) it.next())) { - } - } - } - } - - /** - * Returns the root directory of the ASRP data, with the trailing - * file separator still attached. - */ - public String getRootDir() { - return rootDir; - } - - /** - * Return a java.util.List of ASRPDirectories known by this THF - * file. - */ - public List getASRPDirectories() { - LinkedList asrpDirs = new LinkedList(); - List fields = getFields(TransmittalHeaderFile.DATA_SET_DESCRIPTION); - for (Iterator it = fields.iterator(); it.hasNext();) { - DDFField ddf = (DDFField) it.next(); - if (ddf.getFieldDefn().getName().equals("FDR")) { - List datasets = ddf.getSubfields("NAM"); - - for (Iterator it2 = datasets.iterator(); it2.hasNext();) { - DDFSubfield ddfs = (DDFSubfield) it2.next(); - String asrpdString = rootDir + "ASRP/" + ddfs.stringValue(); - if (Debug.debugging("asrp")) { - Debug.output("TransmittalHeaderFile creating " - + asrpdString + " from " + rootDir + TRANS); - } - asrpDirs.add(new ASRPDirectory(asrpdString)); - } - } - } - - return asrpDirs; - } - - public static void main(String[] argv) { - Debug.init(); - - if (argv.length < 1) { - Debug.output("Usage: TransmittalHeaderFile filename"); - } - - try { - TransmittalHeaderFile thf = new TransmittalHeaderFile(argv[0]); - thf.dumpFields(); - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ApplicationStructureAttribute.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ApplicationStructureAttribute.java deleted file mode 100644 index bf471c636..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ApplicationStructureAttribute.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -/** - * Application Structure Attribute - * - * @author dietrick - */ -public class ApplicationStructureAttribute - extends Command { - - String S; - - public ApplicationStructureAttribute(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - S = makeString(0); - } - - public String toString() { - return "Application Structure Attribute " + S; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginMetafile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginMetafile.java deleted file mode 100644 index 3301549c1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginMetafile.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class BeginMetafile extends Command { - String S; - - public BeginMetafile(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - S = makeString(); - } - - public String toString() { - return "Begin Metafile " + S; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPicture.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPicture.java deleted file mode 100644 index 677ab616f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPicture.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class BeginPicture extends Command { - String S; - - public BeginPicture(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - S = makeString(); - } - - public String toString() { - return "Begin Picture " + S; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPictureBody.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPictureBody.java deleted file mode 100644 index 8bad2c2dc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/BeginPictureBody.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class BeginPictureBody extends Command { - String S; - - public BeginPictureBody(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "Begin Picture Body"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGM.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGM.java deleted file mode 100644 index 551c8eadc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGM.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Color; -import java.awt.Graphics; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Vector; -import java.util.logging.Logger; - -public class CGM - implements Cloneable { - protected Vector commandList; - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.cgm.CGM"); - - public CGM() { - - } - - public CGM(String path) - throws IOException { - DataInputStream in = new DataInputStream(new FileInputStream(path)); - read(in); - in.close(); - } - - public void read(DataInputStream in) - throws IOException { - commandList = new Vector(); - while (true) { - Command c = Command.read(in); - if (c == null) - break; - commandList.addElement(c); - } - - sortColors(); - } - - /** - * The paint call managed by the CGMDisplay object, which holds changes to - * the Graphics object based on different Commands held by this CGM. - * - * @param d - */ - protected void paint(CGMDisplay d) { - for (Command c : commandList) { - c.paint(d); - } - } - - /** - * A direct call to paint on the CGM file, creates a CGMDisplay that marches - * through the CGM commands and renders into the provided Graphics object. - * - * @param g java Graphics object - * @param width the pixel width of image to render into. - * @param height the pixel height of image to render info. - */ - public void paint(Graphics g, int width, int height) { - CGMDisplay cgmDisplay = new CGMDisplay(this); - cgmDisplay.scale(width, height); - cgmDisplay.paint(g); - } - - /** - * Allows color commands to look up indexes in ColorTable to find real - * values. - */ - protected void sortColors() { - ColorTable ct = null; - boolean indexed = false; - for (Command c : commandList) { - if (c instanceof ColorSelectionMode) { - if (((ColorSelectionMode) c).selectionMode == 0) { - // indexed - indexed = true; - } - } else if (c instanceof ColorTable) { - ct = (ColorTable) c; - } else if (c instanceof ColorModel) { - logger.fine("Not handling other colormodels than rgb (indexed and direct)"); - } - } - - if (indexed && ct != null) { - for (Command c : commandList) { - if (c instanceof ColorCommand) { - ((ColorCommand) c).setColorFromColorTable(ct); - } - } - } - } - - public void scale(CGMDisplay d) { - for (Command c : commandList) { - c.scale(d); - } - } - - public int[] extent() { - for (Command c : commandList) { - if (c instanceof VDCExtent) - return ((VDCExtent) c).extent(); - } - return null; - } - - public ColorTable getColorTable() { - for (Command c : commandList) { - if (c instanceof ColorTable) - return (ColorTable) c; - } - return null; - } - - public static void main(String args[]) - throws IOException { - DataInputStream in = new DataInputStream(new FileInputStream(args[0])); - CGM cgm = new CGM(); - cgm.read(in); - in.close(); - } - - public Object clone() { - CGM newOne = new CGM(); - // System.out.println("in cgm.clone"); - newOne.commandList = new Vector(); - for (int i = 0; i < this.commandList.size(); i++) { - newOne.commandList.addElement((Command) (this.commandList.elementAt(i)).clone()); - // System.out.println("Command: " + - // (Command)newOne.V.elementAt(i)); - } - return newOne; - } - - public void showCGMCommands() { - for (Command c : commandList) { - System.out.println("Command: " + c); - } - } - - public void changeColor(Color oldc, Color newc) { - // actually changes the color in the cgm commands having this - // oldc, replacing it with newc find each color command whose - // color matches oldc, and substitute newc - Command temp; - Color currcolor; - - for (int i = 0; i < commandList.size(); i++) { - temp = (Command) commandList.elementAt(i); - if (temp instanceof ColorCommand) {// compare color to - // oldc - currcolor = ((ColorCommand) temp).C; - if (currcolor.equals(oldc)) { - ((ColorCommand) temp).C = new Color(newc.getRed(), newc.getGreen(), newc.getBlue()); - } - } - } - } - - public String toString() { - if (commandList != null) { - StringBuffer buf = new StringBuffer(); - int count = 0; - for (Command c : commandList) { - buf.append("Command ").append(count++).append(": ").append(c.toString()).append("\n"); - } - return buf.toString(); - } else { - return "CGM: not read yet?"; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMApplet.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMApplet.java deleted file mode 100644 index 9121b061b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMApplet.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.applet.Applet; -import java.awt.BorderLayout; -import java.awt.Color; -import java.io.DataInputStream; -import java.net.URL; - -public class CGMApplet extends Applet { - public void init() { - String file = getParameter("File"); - if (file == null) - return; - setBackground(new Color(244, 244, 242)); - try { - URL url = new URL(getCodeBase(), file); - DataInputStream in = new DataInputStream(url.openStream()); - CGM cgm = new CGM(); - cgm.read(in); - in.close(); - setLayout(new BorderLayout()); - CGMDisplay d = new CGMDisplay(cgm); - CGMPanel p = new CGMPanel(d); - add("Center", p); - } catch (Exception e) { - System.out.println(e); - return; - } - repaint(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMConstants.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMConstants.java deleted file mode 100644 index 859a77818..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMConstants.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -/** - * Constants used for CGM Commands. - * - * @author dietrick - */ -public interface CGMConstants { - - public final static int CGM_SPEC_MODE_ABSOLUTE = 0; - public final static int CGM_SPEC_MODE_SCALED = 1; - public final static int CGM_SPEC_MODE_FRACTIONAL = 2; - public final static int CGM_SPEC_MODE_MM = 3; - - public final static int CGM_MARKER_TYPE_DOT = 1; - public final static int CGM_MARKER_TYPE_PLUS = 2; - public final static int CGM_MARKER_TYPE_ASTERISK = 3; - public final static int CGM_MARKER_TYPE_CIRCLE = 4; - public final static int CGM_MARKER_TYPE_CROSS = 5; - - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMDisplay.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMDisplay.java deleted file mode 100644 index 24e97a0f2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMDisplay.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import com.bbn.openmap.omGraphics.OMColor; - -public class CGMDisplay { - Graphics G; - - protected double X = 0, Y = 0; - protected double DX = 1, DY = 1; - protected int W, H; - protected CGM Cgm; - Color FillColor = OMColor.clear, EdgeColor = Color.black, LineColor = Color.black, TextColor = Color.black; - boolean Filled = true, Edge = true; - int TextSize = 10; - protected int Extent[] = { - -30000, - -30000, - 30000, - 30000 - }; - - public CGMDisplay(CGM cgm) { - load(cgm); - } - - public void load(CGM cgm) { - Cgm = cgm; - int extent[] = cgm.extent(); - if (extent != null) - Extent = extent; - } - - public void paint(Graphics g) { - G = g; - Cgm.paint(this); - } - - public int x(int x) { - return W + (int) (X + x * DX); - } - - public int y(int y) { - return H - (int) (Y + y * DY); - } - - public Graphics graphics() { - return G; - } - - public void setFillColor(Color c) { - FillColor = c; - } - - public Color getFillColor() { - return FillColor; - } - - public void setFilled(boolean flag) { - Filled = flag; - } - - public boolean getFilled() { - return Filled; - } - - public void setEdgeColor(Color c) { - EdgeColor = c; - } - - public Color getEdgeColor() { - return EdgeColor; - } - - public void setEdge(boolean flag) { - Edge = flag; - } - - public boolean getEdge() { - return Edge; - } - - public void setLineColor(Color c) { - LineColor = c; - } - - public Color getLineColor() { - return LineColor; - } - - public void setTextColor(Color c) { - TextColor = c; - } - - public Color getTextColor() { - return TextColor; - } - - public void setTextSize(int h) { - TextSize = h; - } - - public int getTextSize() { - return TextSize; - } - - public double factorX() { - return DX; - } - - public double factorY() { - return DY; - } - - public void scale(int w, int h) { - if (Extent == null) - return; - double fx = (double) w / (Extent[2] - Extent[0]); - if (fx * (Extent[3] - Extent[1]) > h) { - fx = (double) h / (Extent[3] - Extent[1]); - } - fx *= 1.0; // 0.9; - DX = fx; - DY = fx; - X = -Extent[0] * fx; - Y = -Extent[1] * fx; - W = (int) (w - fx * (Extent[2] - Extent[0])) / 2; - H = (int) (h - (h - fx * (Extent[3] - Extent[1])) / 2); - Cgm.scale(this); - } - - public BufferedImage getBufferedImage(int w, int h) { - BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - Graphics g = image.getGraphics(); - scale(w, h); - paint(g); - return image; - } - - public void frame(Graphics g) { - if (Extent == null) - return; - g.setColor(Color.black); - g.drawRect(x(Extent[0]) - 1, y(Extent[3]) - 1, (int) Math.abs((Extent[2] - Extent[0]) * DX) + 1, - (int) Math.abs((Extent[3] - Extent[1]) * DY) + 1); - } - - public static void main(String args[]) - throws IOException { - if (args.length == 0) { - System.out.println("Need a path to a cgm file or directory containing cgm files."); - System.exit(-1); - } - - File file = new File(args[0]); - File cgmFile; - if (!file.exists()) { - System.out.println("Can't find file: " + args[0]); - } - - JPanel choicePanel = null; - JComboBox comboBox = null; - JButton nextButton = null; - JButton prevButton = null; - - String[] files = null; - if (file.isDirectory()) { - - files = file.list(); - cgmFile = new File(file, files[0]); - choicePanel = new JPanel(); - comboBox = new JComboBox(files); - nextButton = new JButton("Next"); - nextButton.setName("Next"); - prevButton = new JButton("Previous"); - prevButton.setName("Previous"); - choicePanel.add(prevButton); - choicePanel.add(comboBox); - choicePanel.add(nextButton); - - } else { - cgmFile = file; - } - - DataInputStream in = new DataInputStream(new FileInputStream(cgmFile)); - CGM cgm = new CGM(); - cgm.read(in); - in.close(); - CGMDisplay d = new CGMDisplay(cgm); - CGMPanel p = new CGMPanel(d); - Frame f = new Frame(); - f.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - f.setSize(600, 450); - f.setLayout(new BorderLayout()); - f.add("Center", p); - - if (choicePanel != null) { - f.add("North", choicePanel); - } - - if (comboBox != null && nextButton != null && prevButton != null) { - ServeChoice sc = new ServeChoice(file, comboBox, d); - comboBox.addActionListener(sc); - nextButton.addActionListener(sc); - prevButton.addActionListener(sc); - sc.setRepainter(p); - } - - f.setVisible(true); - } - - protected static class ServeChoice - implements ActionListener { - - JButton label; - File parent; - CGMDisplay d; - JComboBox jcb; - - Component repainter; - - public ServeChoice(File parent, JComboBox jcb, CGMDisplay d) { - this.parent = parent; - this.d = d; - this.jcb = jcb; - } - - /* - * (non-Javadoc) - * - * @see - * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent - * ) - */ - public void actionPerformed(ActionEvent e) { - Object source = e.getSource(); - if (source instanceof JButton) { - String name = ((JButton) source).getName(); - if (name.equals("Next")) { - if (jcb != null) { - int index = jcb.getSelectedIndex(); - if (index < jcb.getItemCount() - 1) { - jcb.setSelectedIndex(index + 1); - } - } - } else if (name.equals("Previous")) { - if (jcb != null) { - int index = jcb.getSelectedIndex(); - if (index > 1) { - jcb.setSelectedIndex(index - 1); - } - } - } - } else if (source instanceof JComboBox) { - JComboBox jcb = (JComboBox) source; - - String newName = (String) jcb.getSelectedItem(); - File cgmFile = new File(parent, newName); - DataInputStream in; - try { - in = new DataInputStream(new FileInputStream(cgmFile)); - CGM cgm = new CGM(); - cgm.read(in); - in.close(); - - System.out.println("*********************"); - System.out.println(cgm.toString()); - System.out.println("*********************"); - - d.load(cgm); - - Component repainter = getRepainter(); - if (repainter != null) { - repainter.repaint(); - } - - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - } - - public Component getRepainter() { - return repainter; - } - - public void setRepainter(Component repainter) { - this.repainter = repainter; - } - - } - - public void changeColor(Color oldc, Color newc) {// actually - // changes the - // color in the - // cgm commands - // having this - // oldc, - // replacing - // it with newc - Cgm.changeColor(oldc, newc); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMPanel.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMPanel.java deleted file mode 100644 index fe1295440..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CGMPanel.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Graphics; -import java.awt.Panel; - -/** - * A simple Panel that manages and renders a CGMDisplay object (which contains a - * CGM). - * - * @author dietrick - */ -public class CGMPanel - extends Panel { - - private static final long serialVersionUID = 1L; - CGMDisplay D; - int W = 0, H = 0; - - public CGMPanel(CGMDisplay d) { - D = d; - } - - public void paint(Graphics g) { - int W0 = getSize().width, H0 = getSize().height; -// if (W0 != W || H0 != H) { - W = W0; - H = H0; - D.scale(W, H); -// } - D.frame(g); - D.paint(g); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CharacterHeight.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CharacterHeight.java deleted file mode 100644 index 7309a1d34..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CharacterHeight.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class CharacterHeight extends Command { - int X; - - public CharacterHeight(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Character Height " + X; - } - - public void scale(CGMDisplay d) { - d.setTextSize((int) (d.factorY() * X)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircleElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircleElement.java deleted file mode 100644 index 0a49022cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircleElement.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class CircleElement extends Command { - int X1, Y1, R1; - int X, Y, R; - - public CircleElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X1 = makeInt(0); - Y1 = makeInt(1); - R1 = makeInt(2); - } - - public String toString() { - return "Circle [" + X1 + "," + Y1 + "] " + R; - } - - public void scale(CGMDisplay d) { - X = d.x(X1); - Y = d.y(Y1); - R = (int) (d.factorX() * R1); - X -= R; - Y -= R; - R = 2 * R - 1; - } - - public void paint(CGMDisplay d) { - if (d.getFilled()) { - d.graphics().setColor(d.getFillColor()); - d.graphics().fillOval(X, Y, R, R); - } else { - d.graphics().setColor(d.getFillColor()); - if (!d.getEdge()) - d.graphics().drawOval(X, Y, R, R); - } - if (d.getEdge()) { - d.graphics().setColor(d.getEdgeColor()); - d.graphics().drawOval(X, Y, R, R); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcClosedElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcClosedElement.java deleted file mode 100644 index e1757c3ac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcClosedElement.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class CircularArcClosedElement extends Command { - int X, Y, SX1, SY1, SX2, SY2, R; - boolean Closed; - - public CircularArcClosedElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - Y = makeInt(1); - SX1 = makeInt(2); - SY1 = makeInt(3); - SX2 = makeInt(4); - SY2 = makeInt(5); - R = makeInt(6); - Closed = (makeInt(7) == 1); - } - - public String toString() { - return "Circle [" + X + "," + Y + "] [" + SX1 + "," + SY1 + "] [" + SX2 - + "," + SY2 + "] " + R + " " + (Closed ? "Closed" : "Pie"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcElement.java deleted file mode 100644 index 80333e95f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/CircularArcElement.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class CircularArcElement extends Command { - int X, Y, SX1, SY1, SX2, SY2, R; - - public CircularArcElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - Y = makeInt(1); - SX1 = makeInt(2); - SY1 = makeInt(3); - SX2 = makeInt(4); - SY2 = makeInt(5); - R = makeInt(6); - } - - public String toString() { - return "Circle [" + X + "," + Y + "] [" + SX1 + "," + SY1 + "] [" + SX2 - + "," + SY2 + "] " + R; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorCommand.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorCommand.java deleted file mode 100644 index 7bf331368..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Color; -import java.io.DataInputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMColor; - -public class ColorCommand - extends Command { - int R, G, B; - Color C; - Color Colors[] = { - Color.black, - Color.white, - Color.green, - Color.yellow, - Color.blue, - Color.magenta, - Color.cyan, - Color.red, - Color.black.brighter(), - Color.white.darker(), - Color.green.darker(), - Color.yellow.darker(), - Color.blue.darker(), - Color.magenta.darker(), - Color.cyan.darker(), - Color.red.darker(), - }; - int index = -1; - - public ColorCommand(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - - if (args.length >= 3) { - R = args[0]; - G = args[1]; - B = args[2]; - C = new Color(R, G, B); - } else if (args.length > 0 && args[0] >= 1 && args[0] <= Colors.length) { - C = Colors[args[0] - 1]; - } else if (args.length == 1) { - index = args[0]; - logger.fine("index set for color: " + index); - } else { - C = new Color(128, 128, 128); - } - } - - public String toString() { - return "Fill Color Input " + R + "," + G + "," + B; - } - - public void paint(CGMDisplay d) { - d.setFillColor(C); - } - - /** - * @param ct - */ - public void setColorFromColorTable(ColorTable ct) { - if (index != -1) { - C = ct.get(index); - if (C != null) { - R = C.getRed(); - G = C.getGreen(); - B = C.getBlue(); - } else { - C = OMColor.clear; - R = 0; - G = 0; - B = 0; - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorModel.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorModel.java deleted file mode 100644 index f5574219f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorModel.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -/** - * FIXME: Enter the description of this type here - * - * @author dietrick - */ -public class ColorModel - extends Command { - - protected int model; - - public final static int RGB = 1; - public final static int CIELAB = 2; - public final static int CIELUV = 3; - public final static int CMYK = 4; - public final static int RGB_related = 5; - - /** - * @param ec - * @param eid - * @param l - * @param in - * @throws IOException - */ - public ColorModel(int ec, int eid, int l, DataInputStream in) - throws IOException { - - super(ec, eid, l, in); - - model = args[0]; - } - - public int getModel() { - return model; - } - - public String toString() { - return "ColorModel is " + model; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorSelectionMode.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorSelectionMode.java deleted file mode 100644 index 4cdb3c46c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorSelectionMode.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class ColorSelectionMode extends Command { - int selectionMode; - - public ColorSelectionMode(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - selectionMode = makeInt(0); - } - - public String toString() { - return "Color Selection Mode " + selectionMode; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorTable.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorTable.java deleted file mode 100644 index d2226291c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ColorTable.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Color; -import java.io.DataInputStream; -import java.io.IOException; -import java.util.logging.Level; - -/** - * A color table for indexed colors. - * - * @author dietrick - */ -public class ColorTable extends Command { - - protected Color[] colors; - protected boolean drawColorTable = false; - int startingIndex = 0; - - public ColorTable(int ec, int eid, int l, DataInputStream in) throws IOException { - super(ec, eid, l, in); - - if (args != null) { - - startingIndex = args[0]; - - logger.fine("starting table index: " + startingIndex); - - // Assuming RGB! - // Subtracting one because the first argument is starting index. - - colors = new Color[args.length - 1 / 3]; - for (int i = 1; i < args.length - 3; i += 3) { - int index = i / 3; - int r = args[i]; - int g = args[i + 1]; - int b = args[i + 2]; - - logger.fine("Color[" + index + "] r: " + r + ", g: " + g + ", b: " + b); - - colors[index] = new Color(r, g, b); - } - } - } - - public String toString() { - return "ColorTable has " + args.length + " colors"; - } - - public Color get(int index) { - index -= startingIndex; // Not sure what starting index means - the - // number - // of colors to get to 0th color or something to - // subtract from provided index to get to front - // of - // actual array. I think second. - if (colors != null && index < colors.length) { - return colors[index]; - } else { - return Color.GRAY; - } - } - - public void paint(CGMDisplay d) { - - if (logger.isLoggable(Level.FINE)) { - int dim = 30; - int x = 0; - int y = 0; - int width = dim; - int height = dim; - - int count = 0; - - for (Color c : colors) { - - if (count > 4) { - count = 0; - y += height; - x = 0; - } - - d.graphics().setColor(c); - d.graphics().fillRect(x, y, width, height); - - x += width; - count++; - } - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/Command.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/Command.java deleted file mode 100644 index 34c6c04d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/Command.java +++ /dev/null @@ -1,505 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class Command implements Cloneable { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.cgm.Command"); - - int args[]; - int ElementClass; - int ElementId; - - public Command(int ec, int eid, int l, DataInputStream in) throws IOException { - - ElementClass = ec; - ElementId = eid; - if (l != 31) { - args = new int[l]; - for (int i = 0; i < l; i++) - args[i] = in.read(); - if (l % 2 != 0) - in.read(); - - } else { - l = read16(in); - args = new int[l]; - for (int i = 0; i < l; i++) - args[i] = in.read(); - if (l % 2 != 0) - in.read(); - } - } - - public int read16(DataInputStream in) throws IOException { - return (in.read() << 8) | in.read(); - } - - public String toString() { - return ElementClass + "," + ElementId + " (" + args.length + ")"; - } - - public String makeString() { - if (args.length <= 0) - return ""; - char a[] = new char[args.length - 1]; - for (int i = 0; i < a.length; i++) - a[i] = (char) args[i + 1]; - return new String(a); - } - - public String makeString(int k) { - char a[] = new char[args[k]]; - for (int i = 0; i < a.length; i++) - a[i] = (char) args[k + i + 1]; - return new String(a); - } - - public int makeInt(int i) { - return (int) ((short) (args[2 * i] << 8) + args[2 * i + 1]); - } - - public void paint(CGMDisplay d) { - } - - public void scale(CGMDisplay d) { - } - - public static Command read(DataInputStream in) throws IOException { - - int k = in.read(); - if (k == -1) - return null; - k = (k << 8) | in.read(); - int ec = k >> 12; - int eid = (k >> 5) & 127; - int l = k & 31; - - switch (ec) { - // Delimiter elements - case 0: - switch (eid) { - case 0: - // NOOP - break; - case 1: - return new BeginMetafile(ec, eid, l, in); - case 2: - return new EndMetafile(ec, eid, l, in); - case 3: - return new BeginPicture(ec, eid, l, in); - case 4: - return new BeginPictureBody(ec, eid, l, in); - case 5: - return new EndPicture(ec, eid, l, in); - case 6: - return new DummyCommand(ec, eid, l, in, "Begin Segment"); - case 7: - return new DummyCommand(ec, eid, l, in, "End Segment"); - case 8: - return new DummyCommand(ec, eid, l, in, "Begin Figure"); - case 9: - return new DummyCommand(ec, eid, l, in, "End Figure"); - case 13: - return new DummyCommand(ec, eid, l, in, "Being Protection Region"); - case 14: - return new DummyCommand(ec, eid, l, in, "End Protection Region"); - case 15: - return new DummyCommand(ec, eid, l, in, "Begin Compound Line"); - case 16: - return new DummyCommand(ec, eid, l, in, "End Compound Line"); - case 17: - return new DummyCommand(ec, eid, l, in, "Begin Compound Text Path"); - case 18: - return new DummyCommand(ec, eid, l, in, "End Compound Text Path"); - case 19: - return new DummyCommand(ec, eid, l, in, "Begin Tile Array"); - case 20: - return new DummyCommand(ec, eid, l, in, "End Tile Array"); - case 21: - return new DummyCommand(ec, eid, l, in, "Begin Application Structure"); - case 22: - return new DummyCommand(ec, eid, l, in, "Begin Application Structure Body"); - case 23: - return new DummyCommand(ec, eid, l, in, "End Application Structure"); - default: - break; - } - break; - // Metafile descriptor elements - case 1: - switch (eid) { - case 1: - return new MetafileVersion(ec, eid, l, in); - case 2: - return new MetafileDescription(ec, eid, l, in); - case 3: - return new DummyCommand(ec, eid, l, in, "VDC Type"); - case 4: - return new DummyCommand(ec, eid, l, in, "Integer Precision"); - case 5: - return new DummyCommand(ec, eid, l, in, "Real Precision"); - case 6: - return new DummyCommand(ec, eid, l, in, "Index Precision"); - case 7: - return new DummyCommand(ec, eid, l, in, "Color Precision"); - case 8: - return new DummyCommand(ec, eid, l, in, "Color Index Precision"); - case 9: - return new DummyCommand(ec, eid, l, in, "Maximum Color Index"); - case 10: - return new DummyCommand(ec, eid, l, in, "Color Value Extent"); - case 11: - return new MetafileElementList(ec, eid, l, in); - case 12: - return new DummyCommand(ec, eid, l, in, "Metafile Defaults Replacement"); - case 13: - return new FontList(ec, eid, l, in); - case 14: - return new DummyCommand(ec, eid, l, in, "Character Set List"); - case 15: - return new DummyCommand(ec, eid, l, in, "Character Coding Announcer"); - case 16: - return new DummyCommand(ec, eid, l, in, "Name Precision"); - case 17: - return new DummyCommand(ec, eid, l, in, "Maximum VDC Extent"); - case 18: - return new DummyCommand(ec, eid, l, in, "Segment Priority Extent"); - case 19: - return new ColorModel(ec, eid, l, in); - case 20: - return new DummyCommand(ec, eid, l, in, "Color Calibration"); - case 21: - return new DummyCommand(ec, eid, l, in, "Font Properties"); - case 22: - return new DummyCommand(ec, eid, l, in, "Glyph Mapping"); - case 23: - return new DummyCommand(ec, eid, l, in, "Symbol Library List"); - case 24: - return new DummyCommand(ec, eid, l, in, "Picture Directory"); - default: - break; - } - break; - // Picture Descriptor Elements - case 2: - switch (eid) { - case 1: - return new DummyCommand(ec, eid, l, in, "Scaling Mode"); - case 2: - return new ColorSelectionMode(ec, eid, l, in); - case 3: - return new LineWidthMode(ec, eid, l, in); - case 4: - return new DummyCommand(ec, eid, l, in, "Marker Size Specification Mode"); - case 5: - return new EdgeWidthMode(ec, eid, l, in); - case 6: - return new VDCExtent(ec, eid, l, in); - case 7: - return new DummyCommand(ec, eid, l, in, "Background Color"); - case 8: - return new DummyCommand(ec, eid, l, in, "Device Viewport"); - case 9: - return new DummyCommand(ec, eid, l, in, "Device Viewport Specification Mode"); - case 10: - return new DummyCommand(ec, eid, l, in, "Device Viewport Mapping"); - case 11: - return new DummyCommand(ec, eid, l, in, "Line Representation"); - case 12: - return new DummyCommand(ec, eid, l, in, "Marker Representation"); - case 13: - return new DummyCommand(ec, eid, l, in, "Text Representation"); - case 14: - return new DummyCommand(ec, eid, l, in, "Fill Representation"); - case 15: - return new DummyCommand(ec, eid, l, in, "Edge Representation"); - case 16: - return new DummyCommand(ec, eid, l, in, "Interior Style Specification Mode"); - case 17: - return new DummyCommand(ec, eid, l, in, "Line and Edge Type Definition"); - case 18: - return new DummyCommand(ec, eid, l, in, "Hatch Style Definition"); - case 19: - return new DummyCommand(ec, eid, l, in, "Geometric Pattern Definition"); - case 20: - return new DummyCommand(ec, eid, l, in, "Application Structure Directory"); - default: - break; - } - break; - // Control Elements - case 3: - switch (eid) { - case 1: - return new DummyCommand(ec, eid, l, in, "VDC Integer Precision"); - case 2: - return new DummyCommand(ec, eid, l, in, "VDC Real Precision"); - case 3: - return new DummyCommand(ec, eid, l, in, "Auxiliary Color"); - case 4: - return new DummyCommand(ec, eid, l, in, "Transparency"); - case 5: - return new DummyCommand(ec, eid, l, in, "Clip Rectangle"); - case 6: - return new DummyCommand(ec, eid, l, in, "Clip Indicator"); - case 7: - return new DummyCommand(ec, eid, l, in, "Line Clipping Mode"); - case 8: - return new DummyCommand(ec, eid, l, in, "Marker Clipping Mode"); - case 9: - return new DummyCommand(ec, eid, l, in, "Edge Clipping Mode"); - case 10: - return new DummyCommand(ec, eid, l, in, "New Region"); - case 11: - return new DummyCommand(ec, eid, l, in, "Save Primitive Context"); - case 12: - return new DummyCommand(ec, eid, l, in, "Restore Primitive Context"); - case 17: - return new DummyCommand(ec, eid, l, in, "Protection Region Indicator"); - case 18: - return new DummyCommand(ec, eid, l, in, "Generalized Text Path Mode"); - case 19: - return new DummyCommand(ec, eid, l, in, "Mitre Limit"); - case 20: - return new DummyCommand(ec, eid, l, in, "Transparent Cell Color"); - default: - break; - } - break; - // Graphical Primitive Elements - case 4: - switch (eid) { - case 1: - return new PolylineElement(ec, eid, l, in); - case 2: - return new DummyCommand(ec, eid, l, in, "Disjoint Polyline"); - case 3: - return new DummyCommand(ec, eid, l, in, "Polymarker"); - case 4: - return new TextElement(ec, eid, l, in); - case 5: - return new DummyCommand(ec, eid, l, in, "Text"); - case 6: - return new DummyCommand(ec, eid, l, in, "Restricted Text"); - case 7: - return new PolygonElement(ec, eid, l, in); - case 8: - return new DummyCommand(ec, eid, l, in, "Append Text"); - case 9: - return new DummyCommand(ec, eid, l, in, "Cell Array"); - case 10: - return new DummyCommand(ec, eid, l, in, "Generalized Drawing Primitive"); - case 11: - return new RectangleElement(ec, eid, l, in); - case 12: - return new CircleElement(ec, eid, l, in); - case 13: - return new DummyCommand(ec, eid, l, in, "Circular Arc Point"); - case 14: - return new DummyCommand(ec, eid, l, in, "Circular Arc 3 Point Close"); - case 15: - return new CircularArcElement(ec, eid, l, in); - case 16: - return new CircularArcClosedElement(ec, eid, l, in); - case 17: - return new EllipseElement(ec, eid, l, in); - case 18: - return new EllipticalArcElement(ec, eid, l, in); - case 19: - return new EllipticalArcClosedElement(ec, eid, l, in); - case 20: - return new DummyCommand(ec, eid, l, in, "Circular Arc Center Reversed"); - case 21: - return new DummyCommand(ec, eid, l, in, "Connecting Edge"); - case 22: - return new DummyCommand(ec, eid, l, in, "Hyperbolic Arc"); - case 23: - return new DummyCommand(ec, eid, l, in, "Parabolic Arc"); - case 24: - return new DummyCommand(ec, eid, l, in, "Non-Uniform B-Spline"); - case 25: - return new DummyCommand(ec, eid, l, in, "Non-Uniform Rational B-Spline"); - case 26: - return new DummyCommand(ec, eid, l, in, "Polybezier"); - case 27: - return new DummyCommand(ec, eid, l, in, "Polysymbol"); - case 28: - return new DummyCommand(ec, eid, l, in, "Bitonal Tile"); - case 29: - return new DummyCommand(ec, eid, l, in, "Tile"); - default: - break; - } - break; - // Attribute Elements - case 5: - switch (eid) { - case 1: - return new DummyCommand(ec, eid, l, in, "Line Bundle Index"); - case 2: - return new LineType(ec, eid, l, in); - case 3: - return new LineWidth(ec, eid, l, in); - case 4: - return new LineColor(ec, eid, l, in); - case 5: - return new DummyCommand(ec, eid, l, in, "Marker Bundle Index"); - case 6: - return new DummyCommand(ec, eid, l, in, "Marker Type"); - case 7: - return new DummyCommand(ec, eid, l, in, "Marker Size"); - case 8: - return new DummyCommand(ec, eid, l, in, "Marker Color"); - case 9: - return new DummyCommand(ec, eid, l, in, "Text Bundle Index"); - case 10: - return new TextFontIndex(ec, eid, l, in); - case 11: - return new DummyCommand(ec, eid, l, in, "Text Precision"); - case 12: - return new DummyCommand(ec, eid, l, in, "Character Expansion Factor"); - case 13: - return new DummyCommand(ec, eid, l, in, "Character Spacing"); - case 14: - return new TextColor(ec, eid, l, in); - case 15: - return new CharacterHeight(ec, eid, l, in); - case 16: - return new DummyCommand(ec, eid, l, in, "Character Orientation"); - case 17: - return new DummyCommand(ec, eid, l, in, "Text Path"); - case 18: - return new DummyCommand(ec, eid, l, in, "Text Alignment"); - case 19: - return new DummyCommand(ec, eid, l, in, "Character Set Index"); - case 20: - return new DummyCommand(ec, eid, l, in, "Alternate Character Set Index"); - case 21: - return new DummyCommand(ec, eid, l, in, "Fill Bundle Index"); - case 22: - return new InteriorStyle(ec, eid, l, in); - case 23: - return new FillColor(ec, eid, l, in); - case 24: - return new DummyCommand(ec, eid, l, in, "Hatch Index"); - case 25: - return new DummyCommand(ec, eid, l, in, "Pattern Index"); - case 26: - return new DummyCommand(ec, eid, l, in, "Edge Bundle Index"); - case 27: - return new EdgeType(ec, eid, l, in); - case 28: - return new EdgeWidth(ec, eid, l, in); - case 29: - return new EdgeColor(ec, eid, l, in); - case 30: - return new EdgeVisibility(ec, eid, l, in); - case 31: - return new DummyCommand(ec, eid, l, in, "Fill Reference Point"); - case 32: - return new DummyCommand(ec, eid, l, in, "Pattern Table"); - case 33: - return new DummyCommand(ec, eid, l, in, "Pattern Size"); - case 34: - return new ColorTable(ec, eid, l, in); - case 35: - return new DummyCommand(ec, eid, l, in, "Aspect Source Flags"); - case 36: - return new DummyCommand(ec, eid, l, in, "Pick Indentifier"); - case 37: - return new DummyCommand(ec, eid, l, in, "Line Cap"); - case 38: - return new DummyCommand(ec, eid, l, in, "Line Join"); - case 39: - return new DummyCommand(ec, eid, l, in, "Line Type Continuation"); - case 40: - return new DummyCommand(ec, eid, l, in, "Line Type Initial Offset"); - case 41: - return new DummyCommand(ec, eid, l, in, "Text Score Type"); - case 42: - return new DummyCommand(ec, eid, l, in, "Restricted Text Type"); - case 43: - return new DummyCommand(ec, eid, l, in, "Interpolated Interior"); - case 44: - return new DummyCommand(ec, eid, l, in, "Edge Cap"); - case 45: - return new DummyCommand(ec, eid, l, in, "Edge Join"); - case 46: - return new DummyCommand(ec, eid, l, in, "Edge Type Continuation"); - case 47: - return new DummyCommand(ec, eid, l, in, "Edge Type Initial Offset"); - case 48: - return new DummyCommand(ec, eid, l, in, "Symbol Library Index"); - case 49: - return new DummyCommand(ec, eid, l, in, "Symbol Color"); - case 50: - return new DummyCommand(ec, eid, l, in, "Symbol Size"); - case 51: - return new DummyCommand(ec, eid, l, in, "Symbol Orientation"); - default: - break; - } - break; - // Escape Element - case 6: - break; - // External Elements - case 7: - break; - // Segment Control and Segment Attribute Elements - case 8: - break; - // Application Structure Descriptor Elements - case 9: - switch (eid) { - case 1: - return new ApplicationStructureAttribute(ec, eid, l, in); - default: - break; - } - break; - default: - break; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Ignored Opcode: " + ec + "/" + eid); - } - - return new Command(ec, eid, l, in); - } - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return null; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/DummyCommand.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/DummyCommand.java deleted file mode 100644 index 50cd1818d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/DummyCommand.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -/** - * Filler object for Commands not yet implemented, in order to be able to see - * what's going on. - * - * @author dietrick - */ -public class DummyCommand - extends Command { - - String commandDescription; - - public DummyCommand(int ec, int eid, int l, DataInputStream in, String desc) - throws IOException { - super(ec, eid, l, in); - commandDescription = desc; - } - - public String toString() { - return "Unimplemented (" + ElementClass + "/" + ElementId + "): " + commandDescription; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeColor.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeColor.java deleted file mode 100644 index 1cfef3511..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeColor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EdgeColor extends ColorCommand { - public EdgeColor(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "Edge Color Input " + R + "," + G + "," + B; - } - - public void paint(CGMDisplay d) { - d.setEdgeColor(C); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeType.java deleted file mode 100644 index 8e037cf97..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeType.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EdgeType extends Command { - int X; - final int SOLID = 1, DASHED = 2; - - public EdgeType(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - if (X == SOLID) - return "Edge Type SOLID"; - else if (X == DASHED) - return "Edge Type DASHED"; - else - return "Edge Type " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeVisibility.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeVisibility.java deleted file mode 100644 index 046873dbc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeVisibility.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EdgeVisibility extends Command { - boolean Visibel; - - public EdgeVisibility(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - Visibel = (makeInt(0) != 0); - } - - public String toString() { - return "Edge Visibility " + (Visibel ? "On" : "Off"); - } - - public void paint(CGMDisplay d) { - d.setEdge(Visibel); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidth.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidth.java deleted file mode 100644 index 43cff3332..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidth.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EdgeWidth extends Command { - int X; - - public EdgeWidth(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Edge Width " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidthMode.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidthMode.java deleted file mode 100644 index 11b605956..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EdgeWidthMode.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EdgeWidthMode extends Command { - int X; - - public EdgeWidthMode(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Edge Width " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipseElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipseElement.java deleted file mode 100644 index 096bdad6c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipseElement.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.io.DataInputStream; -import java.io.IOException; - -import com.bbn.openmap.util.MoreMath; - -/** - * These are defined as a center point and two conjugate diameter points. - */ -public class EllipseElement - extends Command { - int centerX, centerY, endX1, endY1, endX2, endY2; - int centerXS, centerYS, endXS1, endYS1, endXS2, endYS2; - - public EllipseElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - centerX = makeInt(0); - centerY = makeInt(1); - endX1 = makeInt(2); - endY1 = makeInt(3); - endX2 = makeInt(4); - endY2 = makeInt(5); - } - - public String toString() { - return "Ellipse [" + centerX + "," + centerY + "] [" + endX1 + "," + endY1 + "] [" + endX2 + "," + endY2 + "]"; - } - - public void scale(CGMDisplay d) { - centerXS = d.x(centerX); - centerYS = d.y(centerY); - endXS1 = d.x(endX1); - endYS1 = d.y(endY1); - endXS2 = d.x(endX2); - endYS2 = d.y(endY2); - } - - public void paint(CGMDisplay d) { - - int x1 = endXS1 - centerXS; - int x2 = endYS1 - centerYS; - int y1 = endXS2 - centerXS; - int y2 = endYS2 - centerYS; - - // Hypotenuse (Pythagorean theorem) - double radiusX = Math.sqrt(x1 * x1 + x2 * x2); - double radiusY = Math.sqrt(y1 * y1 + y2 * y2); - - // Angle (Trigonometric ratios in right triangles) - double angle; - if (x1 != 0) { - angle = Math.toDegrees(Math.tan(x2 / x1)); - } else { - angle = MoreMath.HALF_PI_D; - } - - AffineTransform at = AffineTransform.getRotateInstance(angle, centerXS, centerYS); - - Graphics2D g2 = (Graphics2D) d.graphics().create(); - g2.setTransform(at); - - if (d.getFilled()) { - g2.setColor(d.getFillColor()); - g2.fillOval((int) (centerXS - radiusX), (int) (centerYS - radiusY), (int) (2 * radiusX), (int) (2 * radiusY)); - } else { - g2.setColor(d.getFillColor()); - if (!d.getEdge()) - d.graphics().drawOval((int) (centerXS - radiusX), (int) (centerYS - radiusY), (int) (2 * radiusX), (int) (2 * radiusY)); - } - if (d.getEdge()) { - g2.setColor(d.getEdgeColor()); - g2.drawOval((int) (centerXS - radiusX), (int) (centerYS - radiusY), (int) (2 * radiusX), (int) (2 * radiusY)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcClosedElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcClosedElement.java deleted file mode 100644 index 15e0679a4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcClosedElement.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EllipticalArcClosedElement extends Command { - int X, Y, X1, Y1, X2, Y2, SX1, SY1, SX2, SY2; - boolean Closed; - - public EllipticalArcClosedElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - Y = makeInt(1); - X1 = makeInt(2); - Y1 = makeInt(3); - X2 = makeInt(4); - Y2 = makeInt(5); - SX1 = makeInt(6); - SY1 = makeInt(7); - SX2 = makeInt(8); - SY2 = makeInt(9); - Closed = (makeInt(10) == 1); - } - - public String toString() { - return "Ellipse [" + X + "," + Y + "] [" + X1 + "," + Y1 + "] [" + X2 - + "," + Y2 + "] [" + SX1 + "," + SY1 + "] [" + SX2 + "," + SY2 - + "] " + (Closed ? "Closed" : "Pie"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcElement.java deleted file mode 100644 index 19fd22220..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EllipticalArcElement.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EllipticalArcElement extends Command { - int X, Y, X1, Y1, X2, Y2, SX1, SY1, SX2, SY2; - - public EllipticalArcElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - Y = makeInt(1); - X1 = makeInt(2); - Y1 = makeInt(3); - X2 = makeInt(4); - Y2 = makeInt(5); - SX1 = makeInt(6); - SY1 = makeInt(7); - SX2 = makeInt(8); - SY2 = makeInt(9); - } - - public String toString() { - return "Ellipse [" + X + "," + Y + "] [" + X1 + "," + Y1 + "] [" + X2 - + "," + Y2 + "] [" + SX1 + "," + SY1 + "] [" + SX2 + "," + SY2 - + "]"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndMetafile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndMetafile.java deleted file mode 100644 index aaf3b5c45..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndMetafile.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EndMetafile extends Command { - String S; - - public EndMetafile(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "End Metafile"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndPicture.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndPicture.java deleted file mode 100644 index 80e443137..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/EndPicture.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class EndPicture extends Command { - String S; - - public EndPicture(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "End Picture"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FillColor.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FillColor.java deleted file mode 100644 index 235501ab4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FillColor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class FillColor extends ColorCommand { - public FillColor(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "Fill Color Input " + R + "," + G + "," + B; - } - - public void paint(CGMDisplay d) { - d.setFillColor(C); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FontList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FontList.java deleted file mode 100644 index 0c985313e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/FontList.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class FontList extends Command { - String S[]; - - public FontList(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - int count = 0, i = 0; - while (i < args.length) { - count++; - i += args[i] + 1; - } - S = new String[count]; - count = 0; - i = 0; - while (i < args.length) { - char a[] = new char[args[i]]; - for (int j = 0; j < args[i]; j++) - a[j] = (char) args[i + j + 1]; - S[count] = new String(a); - count++; - i += args[i] + 1; - } - } - - public String toString() { - StringBuffer s = new StringBuffer("Font List: "); - for (int i = 0; i < S.length - 1; i++) - s.append(S[i]).append(", "); - s.append(S[S.length - 1]); - return s.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/InteriorStyle.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/InteriorStyle.java deleted file mode 100644 index f80ddbe4d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/InteriorStyle.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class InteriorStyle extends Command { - int X; - final int SOLID = 1, EMPTY = 2; - - public InteriorStyle(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - if (X == SOLID) - return "Interior Style SOLID"; - else if (X == EMPTY) - return "Interior Style EMPTY"; - else - return "Line Type " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineColor.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineColor.java deleted file mode 100644 index b5053d101..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineColor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class LineColor extends ColorCommand { - public LineColor(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "Line Color Input " + R + "," + G + "," + B; - } - - public void paint(CGMDisplay d) { - d.setLineColor(C); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineType.java deleted file mode 100644 index 59d602516..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineType.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class LineType extends Command { - int X; - final int SOLID = 1, DASHED = 2; - - public LineType(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - if (X == SOLID) - return "Line Type SOLID"; - else if (X == DASHED) - return "Line Type DASHED"; - else - return "Line Type " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidth.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidth.java deleted file mode 100644 index 782b90f5d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidth.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class LineWidth extends Command { - int X; - - public LineWidth(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Line Width " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidthMode.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidthMode.java deleted file mode 100644 index 88ef90198..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/LineWidthMode.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class LineWidthMode extends Command { - int X; - - public LineWidthMode(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Line Width Specification Mode " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerRepresentation.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerRepresentation.java deleted file mode 100644 index 605c0e0f0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerRepresentation.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Color; -import java.io.DataInputStream; -import java.io.IOException; - -/** - * Filler object for Commands not yet implemented, in order to be able to kinda - * see what's going on. - * - * @author dietrick - */ -public class MarkerRepresentation - extends Command { - - int bundleIndex; - int type; - int size; - Color color; - - public MarkerRepresentation(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - bundleIndex = makeInt(0); - type = makeInt(1); - size = makeInt(2); - - } - - public String toString() { - return "MarkerRepresentation (" + bundleIndex + "," + type + "," + size + ")"; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerSizeSpecMode.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerSizeSpecMode.java deleted file mode 100644 index 107b94141..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MarkerSizeSpecMode.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -/** - * Filler object for Commands not yet implemented, in order to be able to kinda - * see what's going on. - * - * @author dietrick - */ -public class MarkerSizeSpecMode - extends Command { - - int mode; - - public MarkerSizeSpecMode(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - mode = makeInt(0); - } - - public String toString() { - return "MarkerSizeSpecMode (" + mode + ")"; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileDescription.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileDescription.java deleted file mode 100644 index f5003c42d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileDescription.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class MetafileDescription extends Command { - String S; - - public MetafileDescription(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - S = makeString(); - } - - public String toString() { - return "Metafile Description: " + S; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileElementList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileElementList.java deleted file mode 100644 index 457fe82ef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileElementList.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class MetafileElementList extends Command { - int X1, X2, X3; - - public MetafileElementList(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X1 = makeInt(0); - X2 = makeInt(1); - X3 = makeInt(2); - } - - public String toString() { - return "Metafile Element List " + X1 + "," + X2 + "," + X3; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileVersion.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileVersion.java deleted file mode 100644 index 9535379fb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/MetafileVersion.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class MetafileVersion extends Command { - int X; - - public MetafileVersion(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Metafile Version " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolygonElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolygonElement.java deleted file mode 100644 index ef8af504b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolygonElement.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Polygon; -import java.io.DataInputStream; -import java.io.IOException; - -public class PolygonElement extends Command { - int X[], Y[]; - Polygon P; - - public PolygonElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - - super(ec, eid, l, in); - int n = args.length / 4; - X = new int[n]; - Y = new int[n]; - for (int i = 0; i < n; i++) { - X[i] = makeInt(2 * i); - Y[i] = makeInt(2 * i + 1); - } - } - - public String toString() { - StringBuffer s = new StringBuffer("Polygon"); - for (int i = 0; i < X.length; i++) - s.append(" [").append(X[i]).append(",").append(Y[i]).append("]"); - return s.toString(); - } - - public void scale(CGMDisplay d) { - P = new Polygon(); - for (int i = 0; i < X.length; i++) { - P.addPoint(d.x(X[i]), d.y(Y[i])); - } - } - - public void paint(CGMDisplay d) { - if (d.getFilled()) { - d.graphics().setColor(d.getFillColor()); - d.graphics().fillPolygon(P); - } else { - d.graphics().setColor(d.getFillColor()); - if (!d.getEdge()) - d.graphics().drawPolygon(P); - } - - if (d.getEdge()) { - d.graphics().setColor(d.getEdgeColor()); - d.graphics().drawPolygon(P); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolylineElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolylineElement.java deleted file mode 100644 index dfdfd3ba9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/PolylineElement.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class PolylineElement extends Command { - int X[], Y[]; - int X0[], Y0[]; - - public PolylineElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - int n = args.length / 4; - X = new int[n]; - Y = new int[n]; - for (int i = 0; i < n; i++) { - X[i] = makeInt(2 * i); - Y[i] = makeInt(2 * i + 1); - } - } - - public String toString() { - StringBuffer s = new StringBuffer("Polyline"); - for (int i = 0; i < X.length; i++) - s.append(" [").append(X[i]).append(",").append(Y[i]).append("]"); - return s.toString(); - } - - public void scale(CGMDisplay d) { - X0 = new int[X.length]; - Y0 = new int[X.length]; - for (int i = 0; i < X.length; i++) { - X0[i] = d.x(X[i]); - Y0[i] = d.y(Y[i]); - } - } - - public void paint(CGMDisplay d) { - d.graphics().setColor(d.getLineColor()); - d.graphics().drawPolyline(X0, Y0, X0.length); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ReadCGM.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ReadCGM.java deleted file mode 100644 index 39a966428..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/ReadCGM.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.IOException; - -public class ReadCGM { - public static void main(String args[]) throws IOException { - DataInputStream in = new DataInputStream(new FileInputStream(args[0])); - while (true) { - Command c = Command.read(in); - if (c == null) - break; - System.out.println(c); - } - in.close(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/RectangleElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/RectangleElement.java deleted file mode 100644 index c8ed4f420..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/RectangleElement.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class RectangleElement extends Command { - int X1, Y1, X2, Y2; - int X, Y, W, H; - - public RectangleElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X1 = makeInt(0); - Y1 = makeInt(1); - X2 = makeInt(2); - Y2 = makeInt(3); - } - - public String toString() { - return "Rectangle [" + X1 + "," + Y1 + "] [" + X2 + "," + Y2 + "]"; - } - - public void scale(CGMDisplay d) { - X = d.x(X1); - Y = d.y(Y1); - W = d.x(X2) - X - 1; - H = d.y(Y2) - Y - 1; - } - - public void paint(CGMDisplay d) { - if (d.getFilled()) { - d.graphics().setColor(d.getFillColor()); - d.graphics().fillRect(X, Y, W, H); - } else { - d.graphics().setColor(d.getFillColor()); - if (!d.getEdge()) - d.graphics().drawRect(X, Y, W, H); - } - if (d.getEdge()) { - d.graphics().setColor(d.getEdgeColor()); - d.graphics().drawRect(X, Y, W, H); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextColor.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextColor.java deleted file mode 100644 index e20a93a2e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextColor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class TextColor extends ColorCommand { - public TextColor(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - } - - public String toString() { - return "Text Color Input " + R + "," + G + "," + B; - } - - public void paint(CGMDisplay d) { - d.setTextColor(C); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextElement.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextElement.java deleted file mode 100644 index dc77442d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextElement.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.awt.Font; -import java.io.DataInputStream; -import java.io.IOException; - -public class TextElement extends Command { - int X, Y; - String S; - Font F; - - public TextElement(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - Y = makeInt(1); - S = makeString(6); - } - - public String toString() { - return "Text Element " + X + "," + Y + ": " + S; - } - - public void scale(CGMDisplay d) { - F = new Font("Dialog", Font.PLAIN, d.getTextSize()); - System.out.println(d.getTextSize()); - } - - public void paint(CGMDisplay d) { - d.graphics().setFont(F); - d.graphics().drawString(S, d.x(X), d.y(Y)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextFontIndex.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextFontIndex.java deleted file mode 100644 index 95531da6c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/TextFontIndex.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class TextFontIndex extends Command { - int X; - - public TextFontIndex(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X = makeInt(0); - } - - public String toString() { - return "Text Font Index Input " + X; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/VDCExtent.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/VDCExtent.java deleted file mode 100644 index 38744104e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/cgm/VDCExtent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 1997-2003 BBNT Solutions, LLC under - * sponsorship of the Defense Advanced Research Projects Agency - * (DARPA). - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the Cougaar Open Source License as - * published by DARPA on the Cougaar Open Source Website - * (www.cougaar.org). - * - * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS - * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR - * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT - * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT - * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL - * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, - * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THE COUGAAR SOFTWARE. - */ -package com.bbn.openmap.dataAccess.cgm; - -import java.io.DataInputStream; -import java.io.IOException; - -public class VDCExtent extends Command { - int X1, X2, Y1, Y2; - - public VDCExtent(int ec, int eid, int l, DataInputStream in) - throws IOException { - super(ec, eid, l, in); - X1 = makeInt(0); - Y1 = makeInt(1); - X2 = makeInt(2); - Y2 = makeInt(3); - } - - public String toString() { - return "VDC Extent [" + X1 + "," + Y1 + "] [" + X2 + "," + Y2 + "]"; - } - - public int[] extent() { - int x[] = new int[4]; - x[0] = X1; - x[1] = Y1; - x[2] = X2; - x[3] = Y2; - return x; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDAdmin.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDAdmin.java deleted file mode 100644 index ad509d244..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDAdmin.java +++ /dev/null @@ -1,528 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDAdmin.java,v $ -// $RCSfile: DTEDAdmin.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/04 18:08:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Iterator; -import java.util.LinkedList; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * DTEDAdmin is a utility class that finds DTED frame files in order - * to copy or delete them. You can specify coordinate boundaries and - * DTED level as filters. Usage: - *

- * - *

- * 
- *   -help       Print usage statement, with arguments. (0 arguments expected)
- *   -boundary   upper lat, left lon, lower lat, right lon (4 arguments expected)
- *   -copy       Copy files to DTED directory. (1 argument expected)
- *   -level      DTED level to consider (0, 1, 2). (1 argument expected)
- *   -outside    Use files outside boundary. (0 arguments expected)
- *   -query      Print out files that meet parameters. (0 arguments expected)
- *   -remove     Delete DTED files. (0 arguments expected)
- *   -source     The source DTED directory path. (1 argument expected)
- *   -verbose    Print out progress. (0 arguments expected)
- *  
- * 
- */ -public class DTEDAdmin { - - protected boolean framesPrepped = false; - protected int level_; - protected double ullat_; - protected double ullon_; - protected double lrlat_; - protected double lrlon_; - protected boolean inside_; - protected int equal_; - - protected LinkedList frameList = null; - protected DTEDLocator locator = null; - - public final static int MAXLEVELS = 3; - public final static int DTED_LARGER_LEVELS = 0; - public final static int DTED_SMALLER_LEVELS = 1; - public final static int DTED_NOTEQUAL_LEVELS = 2; - public final static int DTED_EQUAL_LEVELS = 3; - - /** - * Create a DTEDAdmin object, with file filter parameters to be - * specified later. - */ - public DTEDAdmin() {} - - /** - * Create a DTEDAdmin with the following parameters. - * - * @param dtedDir the source dted directory - * @param ullat the upper latitude of the boundary box to use. - * @param ullon the western latitude of the boundary box to use, - * greater than -180. - * @param lrlat the lower latitude of the boundary box to use. - * @param lrlon the eastern latitude of the boundary box to use, - * less than 180. - * @param level the dted level to consider. - * @param inside if true, files inside the boundary box will be - * considered. If false, files outside the box will be. - * @param equal filter for the level - Possible values are - * DTED_LARGER_LEVELS (any file with a level greater than - * the one specified) , DTED_SMALLER_LEVELS (any file with - * a level less than the one specified), - * DTED_NOTEQUAL_LEVELS (any file with a level not equal to - * the one specified), and DTED_EQUAL_LEVELS (any file with - * the level specified). - */ - public DTEDAdmin(String dtedDir, double ullat, double ullon, double lrlat, - double lrlon, int level, boolean inside, int equal) { - setFrameList(dtedDir, ullat, ullon, lrlat, lrlon, level, inside, equal); - } - - /** - * Create the internal list of frame files based on the following - * parameters. - * - * @param dtedDir the source dted directory - * @param ullat the upper latitude of the boundary box to use. - * @param ullon the western latitude of the boundary box to use, - * greater than -180. - * @param lrlat the lower latitude of the boundary box to use. - * @param lrlon the eastern latitude of the boundary box to use, - * less than 180. - * @param level the dted level to consider. - * @param inside if true, files inside the boundary box will be - * considered. If false, files outside the box will be. - * @param equal filter for the level - Possible values are - * DTED_LARGER_LEVELS (any file with a level greater than - * the one specified) , DTED_SMALLER_LEVELS (any file with - * a level less than the one specified), - * DTED_NOTEQUAL_LEVELS (any file with a level not equal to - * the one specified), and DTED_EQUAL_LEVELS (any file with - * the level specified). - */ - protected LinkedList organizeFrames(String dtedDir, double ullat, - double ullon, double lrlat, - double lrlon, int level, - boolean inside, int equal) { - - framesPrepped = false; - - if (Debug.debugging("dted")) { - Debug.output("DTEDAdmin: Checking for directory " + dtedDir); - } - - LinkedList frames = null; - - if (true/* (new File(dtedDir)).exists() */) { // not - level_ = level; - ullat_ = ullat; - ullon_ = ullon; - lrlat_ = lrlat; - lrlon_ = lrlon; - inside_ = inside; - equal_ = equal; - - Debug.output("DTEDAdmin: Figuring out which frames fit the criteria..."); - frames = getFrameList(dtedDir); - framesPrepped = true; - } - return frames; - } - - /** - * Create the internal list of frame files based on the following - * parameters. - * - * @param dtedDir the source dted directory - * @param ullat the upper latitude of the boundary box to use. - * @param ullon the western latitude of the boundary box to use, - * greater than -180. - * @param lrlat the lower latitude of the boundary box to use. - * @param lrlon the eastern latitude of the boundary box to use, - * less than 180. - * @param level the dted level to consider. - * @param inside if true, files inside the boundary box will be - * considered. If false, files outside the box will be. - * @param equal filter for the level - Possible values are - * DTED_LARGER_LEVELS (any file with a level greater than - * the one specified) , DTED_SMALLER_LEVELS (any file with - * a level less than the one specified), - * DTED_NOTEQUAL_LEVELS (any file with a level not equal to - * the one specified), and DTED_EQUAL_LEVELS (any file with - * the level specified). - */ - public void setFrameList(String dtedDir, double ullat, double ullon, - double lrlat, double lrlon, int level, - boolean inside, int equal) { - setFrameList(organizeFrames(dtedDir, - ullat, - ullon, - lrlat, - lrlon, - level, - inside, - equal)); - } - - /** - * Set the internal frame list, a LinkedList expected to hold File - * objects. - */ - protected void setFrameList(LinkedList ll) { - frameList = ll; - } - - /** - * Get the internal frame list, a LinkedList expected to hold File - * objects. - */ - protected LinkedList getFrameList() { - return frameList; - } - - /** - * Figure out the frames with the current parameters for the - * source directory provided. - */ - protected LinkedList getFrameList(String dtedDir) { - int lev; - boolean dothisone; - int leftx = (int) Math.floor(ullon_); - int rightx = (int) Math.ceil(lrlon_); - int bottomy = (int) Math.floor(lrlat_); - int topy = (int) Math.ceil(ullat_); - - LinkedList frames = new LinkedList(); - - locator = new DTEDLocator(dtedDir); - locator.organize(); - - for (int hor = leftx; hor < rightx; hor++) { - for (int ver = bottomy; ver < topy; ver++) { - for (lev = 0; lev < MAXLEVELS; lev++) { - dothisone = false; - switch (equal_) { - case DTED_LARGER_LEVELS: - if (lev > level_) - dothisone = true; - break; - case DTED_SMALLER_LEVELS: - if (lev < level_) - dothisone = true; - break; - case DTED_NOTEQUAL_LEVELS: - if (lev != level_) - dothisone = true; - break; - case DTED_EQUAL_LEVELS: - default: - if (lev == level_) - dothisone = true; - break; - } - - if (dothisone) { - File file = locator.get(ver, hor, lev); - - if (file != null) { - if (Debug.debugging("dted")) { - Debug.output("DTEDAdmin adding " - + file.getAbsolutePath() + " to list"); - } - frames.add(file); - } - } - } - } - } - - return frames; - } - - /** - * Get the internal frame list and copy those frames to the given - * directory. - * - * @return true if everything went OK, false if not enough - * information is available to create a source file list. - */ - public boolean copyTo(String todteddir) { - return copyTo(getFrameList(), todteddir); - } - - /** - * Get the internal frame list and copy those frames to the given - * directory. - * - * @param files a LinkedList of Files to copy. - * @param todteddir a dted directory to copy files into. - * @return true if everything went OK, false if not enough - * information is available to create a source file list. - */ - protected boolean copyTo(LinkedList files, String todteddir) { - if (files == null) { - Debug.error("No files configured for copying!"); - return false; - } - - Iterator it = files.iterator(); - - while (it.hasNext()) { - - File file = (File) it.next(); - DTEDNameTranslator dnt = locator.getTranslator(); - - try { - dnt.set(file.getAbsolutePath()); - - String dsd = dnt.getSubDirs(); - if (dsd != null && dsd.length() > 0) { - dsd = "/" + dsd; - } - - File toDir = new File(todteddir + dsd); - if (!toDir.exists()) { - toDir.mkdirs(); - } - - File outputFile = new File(toDir, dnt.getFileName()); - - if (Debug.debugging("dted")) { - Debug.output("DTEDAdmin copying " + file.getAbsolutePath() - + " to " + outputFile.getAbsolutePath()); - } - - BinaryBufferedFile input = new BinaryBufferedFile(file); - RandomAccessFile output = new RandomAccessFile(outputFile, "rw"); - byte[] bytes = new byte[4096]; - int numBytes = input.read(bytes); - while (numBytes > 0) { - output.write(bytes, 0, numBytes); - numBytes = input.read(bytes); - } - - input.close(); - output.close(); - - } catch (FormatException fe) { - continue; - } catch (IOException ioe) { - continue; - } - } - return true; - } - - /** - * Delete the DTED files that meet the internal file list - * parameters. - * - * @return true if everything went OK, false if not enough - * information is available to create a source file list. - */ - public boolean remove() { - return remove(getFrameList()); - } - - /** - * Delete the DTED files that meet the internal file list - * parameters. - * - * @param files the LinkedList of File objects representing DTED - * frame files. - * @return true if everything went OK, false if not enough - * information is available to create a source file list. - */ - protected boolean remove(LinkedList files) { - if (files == null) { - Debug.error("No files configured for removal!"); - return false; - } - - Iterator it = files.iterator(); - while (it.hasNext()) { - File file = (File) it.next(); - Debug.output("DTEDAdmin deleting " + file.getAbsolutePath()); - file.delete(); - } - return true; - } - - /** - * Print out a list of DTED files that meet the current internal - * parameters. - */ - public boolean query() { - return query(getFrameList()); - } - - /** - * Print out a list of DTED files that are on the provided list of - * File objects. - */ - protected boolean query(LinkedList files) { - if (files == null) { - Debug.error("No files configured for query!"); - return false; - } - - Iterator it = files.iterator(); - while (it.hasNext()) { - File file = (File) it.next(); - Debug.output(" " + file.getAbsolutePath()); - } - return true; - } - - /** - * Run DTEDAdmin from the command line. - */ - public static void main(String[] argv) { - Debug.init(); - - ArgParser ap = new ArgParser("DTEDAdmin"); - ap.add("boundary", "upper lat, left lon, lower lat, right lon", 4, true); - ap.add("copy", "Copy files to DTED directory.", 1); - ap.add("level", - "DTED level to consider (0, 1, 2), 0 is default. Needs to be set for other levels.", - 1); - ap.add("outside", "Use files outside boundary."); - ap.add("query", "Print out files that meet parameters."); - ap.add("remove", "Delete DTED files."); - ap.add("source", "The source DTED directory path.", 1); - ap.add("verbose", "Print out progress."); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String arg[]; - String sourceDir = null; - - arg = ap.getArgValues("source"); - if (arg != null) { - sourceDir = arg[0]; - } - - boolean inside = true; - arg = ap.getArgValues("outside"); - if (arg != null) { - inside = false; - } - - int level = 0; - arg = ap.getArgValues("level"); - if (arg != null) { - try { - level = Integer.parseInt(arg[0]); - } catch (NumberFormatException nfe) { - level = 0; - } - } - - arg = ap.getArgValues("verbose"); - if (arg != null) { - Debug.put("dted"); - } - - DTEDAdmin admin = null; - double ullat = 89; - double ullon = -180; - double lrlat = -90; - double lrlon = 179; - - arg = ap.getArgValues("boundary"); - if (arg != null) { - try { - ullat = Double.parseDouble(arg[0]); - ullon = Double.parseDouble(arg[1]); - lrlat = Double.parseDouble(arg[2]); - lrlon = Double.parseDouble(arg[3]); - } catch (NumberFormatException nfe1) { - Debug.error("DTEDAdmin: boundary coordinates not valid:\n" - + " " + arg[0] + "\n " + arg[1] + "\n " + arg[2] - + "\n " + arg[3]); - System.exit(0); - } - } - - if (sourceDir != null) { - admin = new DTEDAdmin(sourceDir, ullat, ullon, lrlat, lrlon, level, inside, DTEDAdmin.DTED_EQUAL_LEVELS); - } - - arg = ap.getArgValues("copy"); - if (arg != null) { - if (admin != null) { - admin.copyTo(arg[0]); - } else { - Debug.error("DTEDAdmin: frame parameters not set for copy. Need source directory"); - System.exit(0); - } - } - - arg = ap.getArgValues("query"); - if (arg != null) { - if (admin != null) { - Debug.output("DTED frame files found:"); - admin.query(); - } else { - Debug.error("DTEDAdmin: frame parameters not set for query. Need source directory"); - System.exit(0); - } - } - - arg = ap.getArgValues("remove"); - if (arg != null) { - if (admin != null) { - Debug.output("These files will be deleted:"); - admin.query(); - Debug.output("Are you sure you want to delete them? [y/N]"); - int answer = 'n'; - try { - answer = System.in.read(); - } catch (IOException ioe) { - } - - if (answer == 'Y' || answer == 'y') { - admin.remove(); - } else { - Debug.output("File removal aborted."); - } - } else { - Debug.error("DTEDAdmin: frame parameters not set for copy. Need source directory"); - System.exit(0); - } - - } - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDConstants.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDConstants.java deleted file mode 100644 index f8f84a897..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDConstants.java +++ /dev/null @@ -1,55 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDConstants.java,v $ -// $RCSfile: DTEDConstants.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -/** - * An interface that contains constants used by various classes in the - * package. - */ -public interface DTEDConstants { - // Types of slope shading - /** Empty image. */ - public static final int NOSHADING = 0; - /** Gray scale slope shading, sun from the Northwest. */ - public static final int SLOPESHADING = 1; - /** Banded contour coloring, contour based on meters. */ - public static final int BANDSHADING = 2; - /** Test markings, for the boundary of the subframe. */ - public static final int BOUNDARYSHADING = 4; - /** - * Colorized slope shading. Color bands are based on elevation, - * and are accented by shaded indications. - */ - public static final int COLOREDSHADING = 5; - /** DTED LEVEL 0, 1km posts. */ - public static final int LEVEL_0 = 0; - /** DTED LEVEL 1, 100m posts. */ - public static final int LEVEL_1 = 1; - /** DTED LEVEL 2, 30m posts. */ - public static final int LEVEL_2 = 2; - /** Default height between bands in band views. */ - public static final int DEFAULT_BANDHEIGHT = 25; - /** Default contrast setting for slope shading. */ - public static final int DEFAULT_SLOPE_ADJUST = 3; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDDirectoryHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDDirectoryHandler.java deleted file mode 100644 index c04a1832d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDDirectoryHandler.java +++ /dev/null @@ -1,184 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDDirectoryHandler.java,v $ -// $RCSfile: DTEDDirectoryHandler.java,v $ -// $Revision: 1.3 $ -// $Date: 2007/02/26 16:41:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.util.Properties; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * DTEDDirectoryHandler is a wrapper for a DTEDNameTranslator used for a DTED - * directory. The DTEDNameTranslator has the intelligence to know how file names - * and paths are represented for different lat/lon/level combinations for DTED - * files within a directory. - */ -public class DTEDDirectoryHandler implements PropertyConsumer { - - /** - * The property for the path to the DTED directory. - */ - public final static String PathProperty = "path"; - - /** - * The class name for the DTEDNameTranslator to be used for this path. If - * none is provided, the StandardDTEDNameTranslator will be used, which - * follows the DTED specification. - */ - public final static String TranslatorClassProperty = "translator"; - - /** - * Property prefix for properties, used as a scoping mechanism. - */ - protected String prefix; - - /** - * The DTEDNameTranslator for this handler, which knows how to match up - * lat/lons with a DTED file name. A StandardDTEDNameTranslator is set - * initially, but the actual object can be reset programmatically or with - * properties. - */ - protected DTEDNameTranslator translator = new StandardDTEDNameTranslator(); - - public DTEDDirectoryHandler() {} - - /** - * Create a DTEDDirectoryHandler with a StandardDTEDNameTranslator, looking - * at the provided dted directory. - * - * @param dtedDirectory - */ - public DTEDDirectoryHandler(String dtedDirectory) { - setDirectoryPath(dtedDirectory); - } - - /** - * Set the DTEDNameTranslator for this DTEDDirectoryHandler. - */ - public void setTranslator(DTEDNameTranslator dnt) { - translator = dnt; - } - - /** - * Get the translator for this DTEDDirectoryHandler. - */ - public DTEDNameTranslator getTranslator() { - return translator; - } - - /** - * Sets the DTED directory path on the translator if it isn't null. If the - * translator is null, this method does nothing. - */ - public void setDirectoryPath(String path) { - if (translator != null) { - translator.setDTEDDir(path); - } - } - - /** - * Gets the directory path from the translator. Will return null if the - * translator is null. - */ - public String getDirectoryPath() { - if (translator != null) { - return translator.getDTEDDir(); - } - return null; - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - String scopedPrefix = PropUtils.getScopedPropertyPrefix(prefix); - String path = props.getProperty(scopedPrefix + PathProperty); - String translatorClassName = props.getProperty(scopedPrefix - + TranslatorClassProperty); - - if (translatorClassName != null) { - Object obj = ComponentFactory.create(translatorClassName, - prefix, - props); - if (obj instanceof DTEDNameTranslator) { - translator = (DTEDNameTranslator) obj; - } - } else if (translator == null) { - translator = new StandardDTEDNameTranslator(); - } - - if (Debug.debugging("dtedfile")) { - Debug.output("DTEDDirectoryHandler|" + prefix + ": " - + translator.getClass().getName() + " using " + path); - } - - setDirectoryPath(path); - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + PathProperty, PropUtils.unnull(getDirectoryPath())); - if (translator != null) { - props.put(prefix + PathProperty, translator.getClass().getName()); - if (translator instanceof PropertyConsumer) { - ((PropertyConsumer) translator).getProperties(props); - } - } - - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - props.put(PathProperty, "Path to DTED directory"); - props.put(TranslatorClassProperty, - "Class name of DTEDNameTranslator to use for directory"); - if (translator instanceof PropertyConsumer) { - ((PropertyConsumer) translator).getPropertyInfo(props); - } - - return props; - } - - public void setPropertyPrefix(String propertyPrefix) { - prefix = propertyPrefix; - } - - public String getPropertyPrefix() { - return prefix; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrame.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrame.java deleted file mode 100644 index 200ff970e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrame.java +++ /dev/null @@ -1,579 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrame.java,v $ -// $RCSfile: DTEDFrame.java,v $ -// $Revision: 1.7 $ -// $Date: 2008/02/29 00:51:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.Closable; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.grid.OMGridData; -import com.bbn.openmap.omGraphics.grid.SlopeGenerator; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The DTEDFrame is the representation of the DTED (Digital Terrain Elevation - * Data) data from a single dted data file. It keeps track of all the attribute - * information of its data. It can return an OMGrid object that can be - * configured to create a visual representation of the data, depending on what - * OMGridGenerators are used on the OMGrid object. - */ -public class DTEDFrame - implements Closable { - - public final static int UHL_SIZE = 80; - public final static int DSI_SIZE = 648; - public final static int ACC_SIZE = 2700; - public final static int ACC_SR_SIZE = 284; - /** The binary buffered file to read the data from the file. */ - protected BinaryFile binFile; - /** The path to the frame, including the frame name. */ - protected String path; - /** - * The array of elevation posts. Note: the 0 index of the array in both - * directions is in the lower left corner of the matrix. As you increase - * indexes in both dimensions, you go up-right. - */ - protected short[][] elevations; // elevation posts - - /** Data set identification section of the file. */ - public DTEDFrameDSI dsi; - /** User header label section of the file. */ - public DTEDFrameUHL uhl; - /** Accuracy description section of the file. */ - public DTEDFrameACC acc; - /** Validity flag for the quality of the data file. */ - public boolean frame_is_valid = false; - - // //////////////// - // Administrative methods - // //////////////// - - /** - * Simplest constructor. - * - * @param filePath complete path to the DTED frame. - */ - public DTEDFrame(String filePath) { - this(filePath, false); - } - - /** - * Constructor with colortable and presentation information. - * - * @param filePath complete path to the DTED frame. - * @param readWholeFile If true, all of the elevation data will be read at - * load time. If false, elevation post data will be read in per - * longitude column depending on the need. False is recommended for - * DTEd level 1 and 2. - */ - public DTEDFrame(String filePath, boolean readWholeFile) { - try { - binFile = new BinaryBufferedFile(filePath); - - read(binFile, readWholeFile); - if (readWholeFile) - close(true); - else - BinaryFile.addClosable(this); - - } catch (FileNotFoundException e) { - Debug.error("DTEDFrame: file " + filePath + " not found"); - } catch (IOException e) { - Debug.error("DTEDFrame: File IO Error!\n" + e.toString()); - } - - path = filePath; - } - - /** - * Reads the DTED frame file. Assumes that the File f is valid/exists. - * - * @param binFile the binary buffered file opened on the DTED frame file - * @param readWholeFile flag controlling whether all the row data is read at - * this time. Otherwise, the rows are read as needed. - */ - protected void read(BinaryFile binFile, boolean readWholeFile) { - binFile.byteOrder(true); // boolean msbfirst - dsi = new DTEDFrameDSI(binFile); - uhl = new DTEDFrameUHL(binFile); - acc = new DTEDFrameACC(binFile); - // Allocate just the columns now - we'll do the rows as - // needed... - elevations = new short[uhl.num_lon_lines][]; - if (readWholeFile) - readDataRecords(); - frame_is_valid = true; - } - - /** - * This must get called to break a reference cycle that prevents the garbage - * collection of frames. - */ - public void dispose() { - // System.out.println("DTED Frame Disposed " + me); - this.close(true); - BinaryFile.removeClosable(this); - } - - /** - * Part of the Closable interface. Closes the BinaryFile pointer, because - * someone else needs another file open, and the system needs a file - * pointer. Sets the binFile variable to null. - */ - public boolean close(boolean done) { - try { - if (binFile != null) { - binFile.close(); - binFile = null; - } - return true; - } catch (IOException e) { - Debug.error("DTEDFrame close(): File IO Error!\n" + e.toString()); - return false; - } - } - - /** - * If the BinaryBufferedFile was closed, this method attempts to reopen it. - * - * @return true if the opening was successful. - */ - protected boolean reopen() { - try { - binFile = new BinaryBufferedFile(path); - return true; - } catch (FileNotFoundException e) { - Debug.error("DTEDFrame reopen(): file " + path + " not found"); - return false; - } catch (IOException e) { - Debug.error("DTEDFrame close(): File IO Error!\n" + e.toString()); - return false; - } - } - - // //////////////// - // These functions can be called from the outside, - // as queries about the data - // //////////////// - - /** - * The elevation at the closest SW post to the given lat/lon. This is just a - * go-to-the-closest-post solution. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - * @return elevation at lat/lon in meters. - */ - public int elevationAt(float lat, float lon) { - if (frame_is_valid == true) { - if (lat >= dsi.sw_lat && lat <= dsi.ne_lat && lon >= dsi.sw_lon && lon <= dsi.ne_lon) { - - // lat/lon_post_intervals are *10 too big - - // extra 0 in 36000 to counteract - int lat_index = Math.round((lat - dsi.sw_lat) * 36000 / uhl.lat_post_interval); - int lon_index = Math.round((lon - dsi.sw_lon) * 36000 / uhl.lon_post_interval); - - if (elevations[lon_index] == null) - readDataRecord(lon_index); - - return (int) elevations[lon_index][lat_index]; - } - } - return -32767; // Considered a null elevation value - } - - /** - * Interpolated elevation at a given lat/lon - should be more precise than - * elevationAt(), but that depends on the resolution of the data. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - * @return elevation at lat/lon in meters. - */ - public int interpElevationAt(float lat, float lon) { - if (frame_is_valid == true) { - if (lat >= dsi.sw_lat && lat <= dsi.ne_lat && lon >= dsi.sw_lon && lon <= dsi.ne_lon) { - - // lat/lon_post_intervals are *10 too big - - // extra 0 in 36000 to counteract - float lat_index = (lat - dsi.sw_lat) * 36000F / uhl.lat_post_interval; - float lon_index = (lon - dsi.sw_lon) * 36000F / uhl.lon_post_interval; - - int lflon_index = (int) Math.floor(lon_index); - int lclon_index = (int) Math.ceil(lon_index); - /* int lflat_index = (int) Math.floor(lat_index); */ - int lclat_index = (int) Math.ceil(lat_index); - - if (elevations[lflon_index] == null) - readDataRecord(lflon_index); - if (elevations[lclon_index] == null) - readDataRecord(lclon_index); - - // //////////////////////////////////////////////////// - // Print out grid of 20x20 elevations with - // the "asked for" point being in the middle - // System.out.println("***Elevation Map***"); - // for(int l = lclat_index + 5; l > lflat_index - 5; - // l--) { - // System.out.println(); - // for(int k = lflon_index - 5; k < lclon_index + 5; - // k++) { - // if (elevations[k]==null) readDataRecord(k); - // System.out.print(elevations[k][l] + " "); - // } - // } - // System.out.println();System.out.println(); - // //////////////////////////////////////////////////// - - int ul = elevations[lflon_index][lclat_index]; - int ur = elevations[lclon_index][lclat_index]; - int ll = elevations[lflon_index][lclat_index]; - int lr = elevations[lclon_index][lclat_index]; - - float answer = resolveFourPoints(ul, ur, lr, ll, lat_index, lon_index); - return Math.round(answer); - } - } - return -32767; // Considered a null elevation value - } - - /** - * Return an index of ints representing the starting x, y and ending x, y of - * elevation posts given a lat lon box. It does check to make sure that the - * upper lat is larger than the lower, and left lon is less than the right. - * - * @param ullat upper latitude in decimal degrees. - * @param ullon left longitude in decimal degrees. - * @param lrlat lower latitude in decimal degrees. - * @param lrlon right longitude in decimal degrees. - * @return int[4] array of start x, start y, end x, and end y. - */ - public int[] getIndexesFromLatLons(float ullat, float ullon, float lrlat, float lrlon) { - float upper = ullat; - float lower = lrlat; - float right = lrlon; - float left = ullon; - - // Since matrix indexes depend on these being in the right - // order, we'll double check and flip values, just to make - // sure lower is lower, and higher is higher. - if (ullon > lrlon) { - right = ullon; - left = lrlon; - } - - if (lrlat > ullat) { - upper = lrlat; - lower = ullat; - } - - int[] ret = new int[4]; - float ullat_index = (upper - dsi.sw_lat) * 36000F / uhl.lat_post_interval; - float ullon_index = (left - dsi.sw_lon) * 36000F / uhl.lon_post_interval; - float lrlat_index = (lower - dsi.sw_lat) * 36000F / uhl.lat_post_interval; - float lrlon_index = (right - dsi.sw_lon) * 36000F / uhl.lon_post_interval; - - ret[0] = (int) Math.round(ullon_index); - ret[1] = (int) Math.round(lrlat_index); - ret[2] = (int) Math.round(lrlon_index); - ret[3] = (int) Math.round(ullat_index); - - if (ret[0] < 0) - ret[0] = 0; - if (ret[0] > uhl.num_lon_lines - 2) - ret[0] = uhl.num_lon_lines - 2; - if (ret[1] < 0) - ret[1] = 0; - if (ret[1] > uhl.num_lat_points - 2) - ret[1] = uhl.num_lat_points - 2; - if (ret[2] < 0) - ret[2] = 0; - if (ret[2] > uhl.num_lon_lines - 2) - ret[2] = uhl.num_lon_lines - 2; - if (ret[3] < 0) - ret[3] = 0; - if (ret[3] > uhl.num_lat_points - 2) - ret[3] = uhl.num_lat_points - 2; - return ret; - - } - - /** - * Return a two dimensional array of posts between lat lons. - * - * @param ullat upper latitude in decimal degrees. - * @param ullon left longitude in decimal degrees. - * @param lrlat lower latitude in decimal degrees. - * @param lrlon right longitude in decimal degrees. - * @return array of elevations in meters. The spacing of the posts depends - * on the DTED level. - */ - public short[][] getElevations(float ullat, float ullon, float lrlat, float lrlon) { - int[] indexes = getIndexesFromLatLons(ullat, ullon, lrlat, lrlon); - return getElevations(indexes[0], indexes[1], indexes[2], indexes[3]); - } - - /** - * Return a two dimensional array of posts between lat lons. Assumes that - * the indexes are checked to not exceed their bounds as defined in the - * file. getIndexesFromLatLons() checks this. - * - * @param startx starting index (left) of the greater matrix to make the - * left side of the returned matrix. - * @param starty starting index (lower) of the greater matrix to make the - * bottom side of the returned matrix. - * @param endx ending index (right) of the greater matrix to make the left - * side of the returned matrix. - * @param endy ending index (top) of the greater matrix to make the top side - * of the returned matrix. - * @return array of elevations in meters. The spacing of the posts depends - * on the DTED level. - */ - public short[][] getElevations(int startx, int starty, int endx, int endy) { - int upper = endy; - int lower = starty; - int right = endx; - int left = startx; - - // Since matrix indexes depend on these being in the right - // order, we'll double check and flip values, just to make - // sure lower is lower, and higher is higher. - if (startx > endx) { - right = startx; - left = endx; - } - - if (starty > endy) { - upper = starty; - lower = endy; - } - - short[][] matrix = new short[right - left + 1][upper - lower + 1]; - int matrixColumn = 0; - for (int x = left; x <= right; x++) { - if (elevations[x] == null) - readDataRecord(x); - System.arraycopy(elevations[x], lower, matrix[matrixColumn], 0, (upper - lower + 1)); - matrixColumn++; - } - return matrix; - } - - // //////////////// - // Internal methods - // //////////////// - - /** - * A try at interpolating the corners of the surrounding posts, given a lat - * lon. Called from a function where the data for the lon has been read in. - */ - private float resolveFourPoints(int ul, int ur, int lr, int ll, float lat_index, float lon_index) { - float top_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (float) (ur - ul)) + ul; - float bottom_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (float) (lr - ll)) + ll; - float right_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (float) (ur - lr)) + lr; - float left_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (float) (ul - ll)) / 100.0F + ll; - - float lon_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (top_avg - bottom_avg)) + bottom_avg; - float lat_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (right_avg - left_avg)) + left_avg; - - float result = (lon_avg + lat_avg) / 2.0F; - return result; - } - - /** - * Reads one longitude line of posts. Assumes that the binFile is valid. - * - * @return true if the column of data was successfully read - */ - protected boolean readDataRecord(int lon_index) { - try { - if (binFile == null) { - if (!reopen()) { - return false; - } - } - - // Set to beginning of file section, then skip to index - // data - // 12 = 1+3+2+2+4 = counts and checksum - // 2*uhl....size of elevation post space - binFile.seek(UHL_SIZE + DSI_SIZE + ACC_SIZE + (lon_index * (12 + (2 * uhl.num_lat_points)))); - binFile.read(); // sent byte - binFile.skipBytes(3); // 3 byte data_block_count - binFile.readShort(); // longitude count - binFile.readShort(); // latitude count - // Allocate the rows of the row - elevations[lon_index] = new short[uhl.num_lat_points]; - for (int j = 0; j < uhl.num_lat_points; j++) { - elevations[lon_index][j] = binFile.readShortData(); - } - - } catch (IOException e3) { - Debug.error("DTEDFrame.RDR: Error reading file."); - e3.printStackTrace(); - elevations[lon_index] = null; - return false; - } catch (FormatException f) { - Debug.error("DTEDFrame.RDR: File IO Format error!"); - elevations[lon_index] = null; - return false; - } - return true; - } - - /** - * Read all the elevation posts, at one time. Assumes that the file is open - * and ready. - * - * @return true if the elevation columns were read. - */ - protected boolean readDataRecords() { - boolean ret = true; - for (int lon_index = 0; lon_index < uhl.num_lon_lines; lon_index++) { - if (readDataRecord(lon_index) == false) { - ret = false; - } - } - return ret; - } - - public OMGrid getOMGrid() { - // vResolution decimal degrees per row - double vResolution = (double) dsi.lat_post_interval / 36000.0; // Tenths - // of - // seconds - // between - // data - // rows - // hResolution decimal degrees per column - double hResolution = (double) dsi.lon_post_interval / 36000.0; // Tenths - // of - // seconds - // between - // data - // columns. - - if (Debug.debugging("grid")) { - Debug.output("DTEDFrame creating OMGrid with vResolution: " + vResolution + ", hResolution: " + hResolution - + ", created from:" + "\n\tNE LAT: " + dsi.ne_lat + "\n\tSW LAT: " + dsi.sw_lat + "\n\tNE LON: " + dsi.ne_lon - + "\n\tSW LON: " + dsi.sw_lon + "\n\tlat lines: " + dsi.num_lat_lines + "\n\tlon points: " + dsi.num_lon_points); - } - - OMDTEDGrid omg = - new OMDTEDGrid(dsi.lat_origin, dsi.lon_origin, dsi.ne_lat, dsi.ne_lon, (float) vResolution, (float) hResolution, - new OMGridData.Short(elevations)); - omg.setUnits(Length.METER); - return omg; - } - - /** - * If you just want to get an image for the DTEDFrame, then call this. One - * image in an OMGraphic for the entire DTEDFrame will be returned, with the - * default rendering parameters (Colored shading) and the default - * colortable. Use the other getImage method if you want something - * different. This method actually calls that other method, so read the - * documentation for that as well. - * - * @param proj EqualArc projection to use to create image. - * @return raster image OMGraphic to display in OpenMap. - */ - public OMGraphic getImage(Projection proj) { - OMGrid grid = getOMGrid(); - grid.generate(proj); - SlopeGenerator sg = new SlopeGenerator(); - return sg.generateRasterForProjection(grid, proj); - } - - public static void main(String args[]) { - Debug.init(); - if (args.length < 1) { - System.out.println("DTEDFrame: Need a path/filename"); - System.exit(0); - } - - System.out.println("DTEDFrame: " + args[0]); - DTEDFrame df = new DTEDFrame(args[0], true); - if (df.frame_is_valid) { - System.out.println(df.uhl); - System.out.println(df.dsi); - System.out.println(df.acc); - - // int startx = 5; - // int starty = 6; - // int endx = 10; - // int endy = 30; - - // short[][] e = df.getElevations(startx, starty, endx, - // endy); - // for (int i = e[0].length-1; i >= 0; i--) { - // for (int j = 0; j < e.length; j++) { - // System.out.print(e[j][i] + " "); - // } - // System.out.println(); - // } - } - float lat = df.dsi.lat_origin + .5f; - float lon = df.dsi.lon_origin + .5f; - - CADRG crg = new CADRG(new LatLonPoint.Double(lat, lon), 1500000, 600, 600); - - final com.bbn.openmap.omGraphics.OMGraphic ras = df.getImage(crg); - - java.awt.Frame window = new java.awt.Frame(args[0]) { - public void paint(java.awt.Graphics g) { - if (ras instanceof OMRaster) { - OMRaster raster = (OMRaster) ras; - g.translate(-300 + raster.getWidth() / 2, -300 + raster.getHeight() / 2); - ras.render(g); - } - } - }; - - window.addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent e) { - // need a shutdown event to notify other gui beans and - // then exit. - System.exit(0); - } - }); - - if (ras instanceof OMRaster) { - OMRaster raster = (OMRaster) ras; - window.setSize(raster.getWidth(), raster.getHeight()); - } else { - window.setSize(250, 250); - } - window.setVisible(true); - window.repaint(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameACC.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameACC.java deleted file mode 100644 index 417be4f29..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameACC.java +++ /dev/null @@ -1,134 +0,0 @@ -// ********************************************************************** -// -// -// -// Integrity Applications Incorporated -// 5180 Parkstone Dr. -// Chantilly, VA 20151 -// (703) 378 8672 -// -// Copyright (C) Integrity Applications Incorporated. All rights reserved. -// -// -// ********************************************************************** -/* Author: Matt Revelle - Description: Class to handle ACC records in DTED. - History: Created on 2004.07.18. (based on DTEDFrameUHL.java) - */ - -package com.bbn.openmap.dataAccess.dted; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -public class DTEDFrameACC { - public int abs_horz_acc = -1; // in meters - public int abs_vert_acc = -1; // in meters - public int rel_horz_acc = -1; // in meters - public int rel_vert_acc = -1; // in meters - - // Ignore all reserved fields and accuracy of sub regions. - - public DTEDFrameACC(BinaryFile binFile) { - try { - binFile.seek(DTEDFrame.UHL_SIZE + DTEDFrame.DSI_SIZE); - /* String checkACC = */binFile.readFixedLengthString(3); - - String s_abs_horz_acc = binFile.readFixedLengthString(4); - try { - if ((s_abs_horz_acc.indexOf("NA") == -1) - && (s_abs_horz_acc.indexOf("N/A") == -1)) { - abs_horz_acc = Integer.parseInt(s_abs_horz_acc, 10); - } - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameACC: abs_horz_acc number bad, using 0"); - abs_horz_acc = 0; - } - - String s_abs_vert_acc = binFile.readFixedLengthString(4); - try { - if ((s_abs_vert_acc.indexOf("NA") == -1) - && (s_abs_vert_acc.indexOf("N/A") == -1)) { - abs_vert_acc = Integer.parseInt(s_abs_vert_acc, 10); - } - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameACC: abs_vert_acc number bad, using 0"); - abs_vert_acc = 0; - } - - String s_rel_horz_acc = binFile.readFixedLengthString(4); - try { - if ((s_rel_horz_acc.indexOf("NA") == -1) - && (s_rel_horz_acc.indexOf("N/A") == -1)) { - rel_horz_acc = Integer.parseInt(s_rel_horz_acc, 10); - } - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameACC: rel_horz_acc number bad, using 0"); - rel_horz_acc = 0; - } - - String s_rel_vert_acc = binFile.readFixedLengthString(4); - try { - if ((s_rel_vert_acc.indexOf("NA") == -1) - && (s_rel_vert_acc.indexOf("N/A") == -1)) { - rel_vert_acc = Integer.parseInt(s_rel_vert_acc, 10); - } - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameACC: rel_vert_acc number bad, using 0"); - rel_vert_acc = 0; - } - - } catch (IOException e) { - Debug.error("DTEDFrameACC: File IO Error!\n" + e.toString()); - } catch (FormatException f) { - Debug.error("DTEDFrameACC: File IO Format error!\n" + f.toString()); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - - s.append("***ACC***").append("\n"); - s.append(" abs_horz_acc: ").append(abs_horz_acc).append("\n"); - s.append(" abs_vert_acc: ").append(abs_vert_acc).append("\n"); - s.append(" rel_horz_acc: ").append(rel_horz_acc).append("\n"); - s.append(" rel_vert_acc: ").append(rel_vert_acc).append("\n"); - return s.toString(); - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - Debug.output("dtedframe_acc: Need a path/filename"); - System.exit(0); - } - - Debug.output("DTEDFrameACC: using frame " + args[0]); - - java.io.File file = new java.io.File(args[0]); - - try { - BinaryFile binFile = new BinaryBufferedFile(file); - - // BinaryFile binFile = new BinaryFile(file); - DTEDFrameACC dfa = new DTEDFrameACC(binFile); - - Debug.output(dfa.toString()); - - } catch (FileNotFoundException e) { - Debug.error("DTEDFrameACC: file " + args[0] + " not found"); - System.exit(-1); - } catch (IOException e) { - Debug.error("DTEDFrameACC: File IO Error!\n" + e.toString()); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCache.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCache.java deleted file mode 100644 index 83a55c53d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCache.java +++ /dev/null @@ -1,706 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrameCache.java,v $ -// $RCSfile: DTEDFrameCache.java,v $ -// $Revision: 1.8 $ -// $Date: 2007/02/26 16:41:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The DTEDFrameCache is an object that retrieves DTED paths, frames or - * elevation values, given a latitude, longitude and dted level. It maintains a - * collection of the frames it has already used for quicker access later. The - * size of the cache is determined by startup settings. - *

- * - * The DTEDFrameCache can be placed in the MapHandler, where other objects can - * share it in order to all use the same DTED data. It can be configured with - * properties: - *

- * - *

- * 
- * 
- *         frameCache.cacheSize=40
- *         frameCache.directoryHandlers=dteddir1 dteddir2
- *         frameCache.dteddir1.translator=com.bbn.openmap.dataAccess.dted.StandardDTEDNameTranslator
- *         frameCache.dteddir1.path=/data/dted
- *         frameCache.dteddir2.translator=com.bbn.openmap.dataAccess.dted.StandardDTEDNameTranslator
- *         frameCache.dteddir2.path=/data/dted
- * 
- * 
- * 
- * - * A DTEDDirectoryHandler needs to be specified for each DTED directory you want - * to use. If a translator isn't specified in the properties for a directory - * handler, the StandardDTEDNameTranslator will be used. If you have DTED data - * that doesn't conform to the naming conventions specified in the Military - * Standard, you can use a different DTEDNameTranslator instead for your - * particular directory handler. - */ -public class DTEDFrameCache extends CacheHandler implements PropertyConsumer { - /** - * The elevation value returned if there is no data at a lat/lon (-32767). - */ - public final static int NO_DATA = -32767; - - public static final String DTEDDirectoryHandlerProperty = "directoryHandlers"; - public static final String DTEDFrameCacheSizeProperty = "cacheSize"; - - public int DEFAULT_CACHE_SIZE = 20; - - protected String propertyPrefix = null; - - protected List directories = new ArrayList<>(); - - protected int highestResLevel = 2; - - public DTEDFrameCache() { - super(); - } - - /** - * Create the cache with paths to search for frames, and the maximum number - * of frames to keep on hand. Assumes the paths given are for level 0 and 1 - * data. - * - * @param max_size max number of frames to keep in the cache.. - */ - public DTEDFrameCache(int max_size) { - super(max_size); - } - - /** - * Add a DTED DirectoryHandler to be used for the DTEDFrameCache. - */ - public void addDTEDDirectoryHandler(DTEDDirectoryHandler handler) { - directories.add(handler); - } - - /** - * Remove a DTED DirectoryHandler from the list used for the DTEDFrameCache. - */ - public void removeDTEDDirectoryHandler(DTEDDirectoryHandler handler) { - directories.remove(handler); - } - - /** - * Get the Vector of DTEDDirectoryHandlers used by the DTEDFrameCache. - */ - public List getDTEDDirectoryHandlers() { - return directories; - } - - /** - * Set the Vector of DTEDDirectoryHandlers used by the DTEDFrameCache. You - * might want to use this to set the order of directories that are searched - * for a DTED frame. - */ - public void setDTEDDirectoryHandlers(List handlers) { - directories = handlers; - } - - /** - * A utility to find the path to a dted file, given a lat, lon and a dted - * level. Assumes that paths have been given to the cache. Lat/lons in - * decimal degrees. - * - * @param lat latitude of point - * @param lon longitude of point - * @param level the dted level wanted (0, 1) - * @return complete path to file with lat/lon. - */ - public String findFileName(double lat, double lon, int level) { - - if (directories != null) { - for (DTEDDirectoryHandler ddh : directories) { - DTEDNameTranslator dnt = ddh.getTranslator(); - dnt.set(lat, lon, level); - String dtedFileName = dnt.getName(); - if (Debug.debugging("dtedfile")) { - Debug.output("DTEDFrameCache translator returns " - + dtedFileName + " for " + lat + ", " + lon - + ", level " + level); - } - if (BinaryFile.exists(dtedFileName)) { - return dtedFileName; - } - } - } - - return null; - } - - /** - * Return The DTED Frame, Given A Lat, Lon And DTED Level. - * - * @param lat latitude of point - * @param lon longitude of point - * @param level the dted level wanted (0, 1, 2) - * @return DTED frame. - */ - public DTEDFrame get(double lat, double lon, int level) { - String name = findFileName(lat, lon, level); - if (name != null) { - if (Debug.debugging("dtedfile")) { - Debug.output("DTEDFrameCache: returning " + name + " for " - + lat + ", " + lon + ", level " + level); - } - return (DTEDFrame) get(name); - } else { - if (Debug.debugging("dtedfile")) { - Debug.output("DTEDFrameCache: couldn't find frame for " + lat - + ", " + lon + ", level " + level); - } - } - return null; - } - - /** - * A private class that makes sure that cached frames get disposed properly. - */ - private static class DTEDCacheObject extends CacheObject { - /** - * Construct a DTEDCacheObject, just calls superclass constructor - * - * @param id passed to superclass - * @param obj passed to superclass - */ - public DTEDCacheObject(String id, DTEDFrame obj) { - super(id, obj); - } - - /** - * Calls dispose() on the contained frame, to make it eligible for - * garbage collection. - */ - protected void finalize() { - ((DTEDFrame) obj).dispose(); - } - } - - /** - * Load a dted frame into the cache, based on the path of the frame as a - * key. - * - * @param key complete path to the frame, String. - * @return DTED frame, hidden as a CacheObject. - */ - public CacheObject load(Object key) { - if (key != null) { - String dtedFramePath = key.toString(); - DTEDFrame frame = new DTEDFrame(dtedFramePath, true); - if (frame.frame_is_valid) { - return new DTEDCacheObject(dtedFramePath, frame); - } - } - return null; - } - - /** - * This version of resizeCache is for screen size changes, where the number - * of frames kept on hand in the cache must change, but the images - * themselves don't have to because the pixel/posting spacing hasn't changed - * in the projection. The frames already in the cache are re-added to the - * new cache, if the cache size is increasing. If the cache size is - * shrinking, then as many as will fit are added to the new cache. - * - * @param max_size the new size of the cache. - */ - public void resizeCache(int max_size) { - - CacheObject[] oldObjs = objs; - - if (max_size != objs.length && max_size > 0) { - objs = new CacheObject[max_size]; - } - - for (int i = 0; i < objs.length; i++) { - - if (i >= oldObjs.length) { - break; - } - - DTEDCacheObject dco = (DTEDCacheObject) oldObjs[i]; - - if (dco == null) { - // We load from the front to the back 0 -> length - 1; - // Once you hit a null, the rest should be null, too. - objs[i] = null; - continue; - } - - DTEDFrame frame = (DTEDFrame) (dco.obj); - dco.cachedTime = 0; - - if (frame == null) { - Debug.output("DTEDFrameCache: No Frame for key!"); - continue; - } - - if (oldObjs == objs) { - continue; - } - - if (i < oldObjs.length) { - objs[i] = oldObjs[i]; - } else { - objs[i] = null; - } - } - - oldObjs = null; - } - - public int getHighestResLevel() { - return highestResLevel; - } - - public void setHighestResLevel(int highestResLevel) { - this.highestResLevel = highestResLevel; - } - - /** - * Return the elevation of a lat/lon point, in meters. Will look for frames - * starting at the highest resolution specified in this DTEDFrameCache, and - * work up to level 0, searching for a frame to provide an answer. Will - * return NO_DATA if a frame is not found, or if there is no data in the - * frame file that is found. The default highest resolution DTED level is 2. - * - * @return elevation in meters. - * @param lat in decimal degrees. - * @param lon in decimal degrees. - */ - public int getElevation(float lat, float lon) { - for (int i = /* dted level */highestResLevel; i >= /* dted level */0; i--) { - String dtedFileName = findFileName((double) lat, (double) lon, i); - - if (dtedFileName != null) { - DTEDFrame frame = (DTEDFrame) get(dtedFileName); - - if (frame != null) { - return (int) frame.elevationAt(lat, lon); - } - } - } - - return NO_DATA; - } - - /** - * Return the elevation of a lat/lon point, in meters. - * - * @return elevation in meters. - * @param lat in decimal degrees. - * @param lon in decimal degrees. - * @param level the dted level. - */ - public int getElevation(float lat, float lon, int level) { - String dtedFileName = findFileName((double) lat, (double) lon, level); - - if (dtedFileName != null) { - DTEDFrame frame = (DTEDFrame) get(dtedFileName); - - if (frame != null) { - return (int) frame.elevationAt(lat, lon); - } - } - - return NO_DATA; - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection, and that's why the - * rectangle is defined by the projection parameters. - * - * @param proj the projection describing the wanted area - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - * @return array of elevations, in meters. Spacing depends on the DTED - * level. - */ - public short[][] getElevations(EqualArc proj, int dtedLevel) { - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - - return getElevations((float) ul.getY(), - (float) ul.getX(), - (float) lr.getY(), - (float) lr.getX(), - dtedLevel); - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection. Doesn't handle - * projections which cross the dateline - You must handle that yourself by - * making two inquiries. - * - * @param ullat upper latitude, in decimal degrees - * @param ullon left longitude, in decimal degrees - * @param lrlat lower latitude, in decimal degrees - * @param lrlon right longitude, in decimal degrees - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - */ - public short[][] getElevations(float ullat, float ullon, float lrlat, - float lrlon, int dtedLevel) { - return getElevations(ullat, ullon, lrlat, lrlon, dtedLevel, null); - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection. Doesn't handle - * projections which cross the dateline - You must handle that yourself by - * making two inquiries. - *

- * This method is slightly different that the one above, because it includes - * a input variable DTEDFrame. There is an inherent problem in the algorithm - * if some of the DTED frames are missing. It's too difficult to calculate - * the size of the return array if you don't know that any frames are - * available. So, you should always use the method above, which calls this - * method with a null refFrame. If some of the DTED frames are missing, then - * this method is called recursively, with a frame to use for calculating - * post spacings at the right time. - * - * @param ullat upper latitude, in decimal degrees - * @param ullon left longitude, in decimal degrees - * @param lrlat lower latitude, in decimal degrees - * @param lrlon right longitude, in decimal degrees - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - * @param refFrame DTEDFrame used to calculate measurements. - * @return array of elevations, in meters. Spacing depends on the DTED - * level. - */ - protected short[][] getElevations(float ullat, float ullon, float lrlat, - float lrlon, int dtedLevel, - DTEDFrame refFrame) { - - float upper = ullat; - float lower = lrlat; - float right = lrlon; - float left = ullon; - - // Since matrix indexes depend on these being in the right - // order, we'll double check and flip values, just to make - // sure lower is lower, and higher is higher. - if (ullon > lrlon) { - if (ullon > 0 && lrlon < 0) { - Debug.error("DTEDFrameCache: getElevations: Stradling dateline not handled!"); - return null; - } - right = ullon; - left = lrlon; - } - - if (lrlat > ullat) { - upper = lrlat; - lower = ullat; - } - - // These are the limits of the lat/lons per frame searched - float upperlat = 0; - float upperlon = 0; - float lowerlat = 0; - float lowerlon = 0; - - int xSize = (int) (Math.ceil(right) - Math.floor(left)); - int ySize = (int) (Math.ceil(upper) - Math.floor(lower)); - - // System.out.println("Going with size = " + xSize + "x" + - // ySize); - - int[] xLengths = new int[xSize]; - int[] yLengths = new int[ySize]; - - short[][][][] es = new short[xSize][ySize][][]; - int x, y; - DTEDFrame frame = null; - boolean needCalc = false; - // Let's march through the frames, bottom to top, left to - // right. - for (x = 0; x < xSize; x++) { - - if (x == 0) - lowerlon = left; - else - lowerlon = (float) Math.floor(left) + (float) x; - - if (x == xSize - 1) - upperlon = right; - else - upperlon = (float) Math.floor(left) + (float) (x + 1); - - for (y = 0; y < ySize; y++) { - - if (y == 0) - lowerlat = lower; - else - lowerlat = (float) Math.floor(lower) + (float) y; - - if (y == ySize - 1) - upperlat = upper; - else - upperlat = (float) Math.floor(lower) + (float) (y + 1); - - DTEDFrame thisFrame = get(lowerlat, lowerlon, dtedLevel); - - if (thisFrame != null) { - // System.out.println("Getting elev for " + - // upperlat + ", " + - // lowerlon + ", " + - // lowerlat+ ", " + upperlon); - es[x][y] = thisFrame.getElevations(upperlat, - lowerlon, - lowerlat, - upperlon); - xLengths[x] = es[x][y].length; - yLengths[y] = es[x][y][0].length; - frame = thisFrame; - } else { - if (refFrame != null) { - Debug.output("DTEDFrameCache: Missing frames, going to use reference frame"); - // calculate these lengths, since the refFrame - // was set... - int[] indexes = refFrame.getIndexesFromLatLons(upperlat, - lowerlon, - lowerlat, - upperlon); - xLengths[x] = indexes[2] - indexes[0] + 1; - yLengths[y] = indexes[3] - indexes[1] + 1; - - } else { - if (frame != null) { - // Well, we have a frame to do - // calculations on, and we know we need - // to do at least one calculation, so - // might as well go and do this right... - return getElevations(ullat, - ullon, - lrlat, - lrlon, - dtedLevel, - frame); - } else { - needCalc = true; - } - } - } - } - } - - // refFrame == null, and all the empty frames were found - // before the good ones... - if (needCalc == true && frame != null) - return getElevations(ullat, ullon, lrlat, lrlon, dtedLevel, frame); - - int xLength = 0; - int yLength = 0; - - // Need to figure out how big the returned matrix is! This - // only works if all the frames come back.... - for (x = 0; x < xLengths.length; x++) - xLength += xLengths[x]; - for (y = 0; y < yLengths.length; y++) - yLength += yLengths[y]; - - // System.out.println("Creating a matrix: " + xLength + "x" + - // yLength); - short[][] matrix = new short[xLength][yLength]; - - // Now copy all the little matrixes into the big matrix - int xspacer = 0; - // Through each little matrix in the x direction - for (x = 0; x < es.length; x++) { - int yspacer = 0; - // Through each little matrix in the y direction - for (y = 0; y < es[x].length; y++) { - - // Make sure the frame exists and is found... - if (es[x][y] != null) { - // Through each lon row in each little matrix - for (int i = 0; i < es[x][y].length; i++) { - System.arraycopy(es[x][y][i], - 0, - matrix[i + xspacer], - yspacer, - es[x][y][i].length); - } - // On the last one lon column, increase the spacer - // for the - // next little matrix above this one. - yspacer += yLengths[y]; - } else - yspacer += xLengths[y]; - } - // On the last little matrix in the column, increase the - // xspacer for the little matrixes in the next column. - xspacer += xLengths[x]; - } - - return matrix; - } - - /** - * PropertyConsumer method. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * PropertyConsumer method. - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * PropertyConsumer method. - */ - public void setProperties(Properties props) { - setProperties(null, props); - } - - /** - * PropertyConsumer method. - */ - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(this); - - // Space-separated list of marker names for different - // DTEDDirectoryHandlers - List directoryHandlerList = PropUtils.parseSpacedMarkers(props.getProperty(prefix - + DTEDDirectoryHandlerProperty)); - - for (String handlerPrefix : directoryHandlerList) { - DTEDDirectoryHandler handler = new DTEDDirectoryHandler(); - handler.setProperties(prefix + handlerPrefix, props); - addDTEDDirectoryHandler(handler); - } - - resetCache(PropUtils.intFromProperties(props, prefix - + DTEDFrameCacheSizeProperty, DEFAULT_CACHE_SIZE)); - } - - /** - * PropertyConsumer method. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + DTEDFrameCacheSizeProperty, - Integer.toString(getCacheSize())); - - // Directory handler properties... - if (directories != null) { - StringBuffer dhPrefixes = new StringBuffer(); - - for (DTEDDirectoryHandler ddh : directories) { - String dhPrefix = ddh.getPropertyPrefix(); - if (dhPrefix != null) { - int index = dhPrefix.indexOf(prefix); - if (index != -1) { - dhPrefixes.append(dhPrefix.substring(index - + prefix.length())).append(" "); - } - ddh.getProperties(props); - } - } - props.put(prefix + DTEDDirectoryHandlerProperty, - dhPrefixes.toString()); - } - - return props; - } - - /** - * PropertyConsumer method. - */ - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - props.put(DTEDFrameCacheSizeProperty, "Size of the frame cache"); - - // Not sure how to handle setting up a DTEDDirectoryHandler - // yet. - - return props; - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - Debug.output("DTEDFrameCache: Need a path/filename"); - System.exit(0); - } - - Debug.output("DTEDFrameCache: " + args[0]); - DTEDFrameCache dfc = new DTEDFrameCache(10); - - // 35.965065 -121.198715 - // 35.998 36.002 lon -121.002 -120.998 - float ullat = 37.002f; - float ullon = -121.002f; - float lrlat = 35.998f; - float lrlon = -119.998f; - - // System.out.println("Getting elevations for " + - // ullat + ", " + ullon + ", " + - // lrlat + ", " + lrlon); - short[][] e = dfc.getElevations(ullat, ullon, lrlat, lrlon, 0); - if (e != null) { - for (int i = e[0].length - 1; i >= 0; i--) { - int col = 0; - System.out.print("r" + i + "-"); - for (int j = 0; j < e.length; j++) { - System.out.print(e[j][i] + " "); - col++; - } - System.out.println(" - " + col); - } - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCacheHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCacheHandler.java deleted file mode 100644 index 243f5e4b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameCacheHandler.java +++ /dev/null @@ -1,729 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrameCacheHandler.java,v $ -// $RCSfile: DTEDFrameCacheHandler.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/01/13 22:05:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Component; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.GeneratorLoader; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.omGraphics.grid.SinkGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The DTEDFrameCacheHandler is a cache for objects being rendered on the map as - * a result of reading in DTED data. It communicates with a DTEDFrameCache to - * get OMGrid data from the actual DTED data files, and then sets - * OMGridGenerators on those OMGrids to create representations of the DTED. - *

- * - * The DTEDFrameCacheHandler uses GeneratorLoaders to create OMGridGenerators - * for its OMGrids. The GeneratorLoaders provide a GUI for controlling those - * OMGridGenerator parameters. The list of GeneratorLoaders can be set via - * Properties. In general, properties being set for a DTEDFrameCacheHandler: - *

- * - *

- * 
- * 
- *    markerName.generators=greys colors
- *    markerName.greys.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader
- *    markerName.greys.prettyName=Slope Shading
- *    markerName.greys.colorsClass=com.bbn.openmap.omGraphics.grid.GreyscaleSlopeColors
- *    markerName.colors.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader
- *    markerName.colors.prettyName=Elevation Shading
- *    markerName.colors.colorsClass=com.bbn.openmap.omGraphics.grid.ColoredShadingColors
- * 
- * 
- * 
- * - * The only properties that are required for the DTEDFrameCacheHandler are the - * generators property, and then the .class properties for the generator loader - * class names. All of the other generator loader properties are sent to the - * generator loader for interpretation. - *

- * - * The markerName is generally provided by the parent component of the - * DTEDFrameCacheHandler, like the DTEDFrameCacheLayer. - */ -public class DTEDFrameCacheHandler extends CacheHandler implements DTEDConstants, PropertyConsumer, - PropertyChangeListener { - - public final static String GeneratorLoadersProperty = "generators"; - - /** The real frame cache. */ - protected DTEDFrameCache frameCache; - - // Setting up the screen... - protected double frameUp, frameDown, frameLeft, frameRight; - - // Returning the images... - protected boolean firstImageReturned = true; - protected double frameLon = 0.0; - protected double frameLat = 0.0; - protected boolean newframe = false; - - protected int dtedLevel = LEVEL_0; - /** - * The active GeneratorLoader providing OMGridGenerators to the OMGrids. - */ - protected GeneratorLoader activeGeneratorLoader = null; - /** - * The list of GeneratorLoaders. - */ - protected List generatorLoaders = new ArrayList(); - - /** - * The DTEDFrameCache must be set at some point. - */ - protected DTEDFrameCacheHandler() { - this(null); - } - - /** - * Create a handler for the DTEDFrameCache. - */ - public DTEDFrameCacheHandler(DTEDFrameCache dfc) { - setFrameCache(dfc); - } - - /** - * Set the DTEDFrameCache. - */ - public void setFrameCache(DTEDFrameCache dfc) { - frameCache = dfc; - resetCache(); - } - - /** - * Get the DTEDFrameCache. - */ - public DTEDFrameCache getFrameCache() { - return frameCache; - } - - /** - * Get an elevation at a point. Always uses the cache to load the frame and - * get the data. DTED data is in meters. - */ - public int getElevation(float lat, float lon) { - if (frameCache != null) { - return frameCache.getElevation(lat, lon); - } else { - return DTEDFrameCache.NO_DATA; - } - } - - /** - * Set the DTED level to get from the DTEDFrameCache. - */ - public void setDtedLevel(int level) { - dtedLevel = level; - } - - /** - * Get the DTED level being retrieved from the DTEDFrameCache. - */ - public int getDtedLevel() { - return dtedLevel; - } - - /** - * Set the active GeneratorLoader based on a pretty name from one of the - * loaders. - */ - public void setActiveGeneratorLoader(String active) { - for (GeneratorLoader gl : generatorLoaders) { - if (active.equals(gl.getPrettyName()) && gl != activeGeneratorLoader) { - activeGeneratorLoader = gl; - resetCache(); - } - } - } - - /** - * Get a new OMGridGenerator from the active GeneratorLoader. - */ - public OMGridGenerator getGenerator() { - if (activeGeneratorLoader != null) { - return activeGeneratorLoader.getGenerator(); - } else if (generatorLoaders != null && generatorLoaders.size() > 0) { - activeGeneratorLoader = generatorLoaders.get(0); - return activeGeneratorLoader.getGenerator(); - } else { - return new SinkGenerator(); - } - } - - /** - * GUI Panel holding the GeneratorLoader GUIs. - */ - final JPanel cards = new JPanel(new CardLayout()); - - /** - * Get the GUI for the GeneratorLoaders. - */ - public Component getGUI() { - JPanel pane = new JPanel(new BorderLayout()); - - int numLoaders = generatorLoaders.size(); - String comboBoxItems[] = new String[numLoaders]; - int count = 0; - - for (GeneratorLoader gl : generatorLoaders) { - String prettyName = gl.getPrettyName(); - comboBoxItems[count++] = prettyName; - - Component glGui = gl.getGUI(); - if (glGui == null) { - glGui = new JLabel("No options available."); - } - - cards.add(glGui, prettyName); - } - - JComboBox cb = new JComboBox<>(comboBoxItems); - cb.setEditable(false); - cb.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent evt) { - CardLayout cl = (CardLayout) (cards.getLayout()); - String active = (String) evt.getItem(); - cl.show(cards, active); - setActiveGeneratorLoader(active); - } - }); - // Put the JComboBox in a JPanel to get a nicer look. - JPanel comboBoxPane = new JPanel(); // use FlowLayout - comboBoxPane.add(cb); - - pane.add(comboBoxPane, BorderLayout.NORTH); - pane.add(cards, BorderLayout.CENTER); - return pane; - } - - /** - * The call to the cache that lets you choose what kind of information is - * returned. This function also figures out what part of the earth is - * covered on the screen, and creates auxillary cache handlers as needed. - * - * @param proj The projection of the screen (CADRG). - * @return List of rasters to display. - */ - public OMGraphicList getRectangle(Projection proj) { - - double[] lat = new double[3]; - double[] lon = new double[3]; - - // This next bit of mumbo jumbo is to handle the equator and - // dateline: Worst case, crossing both, treat each area - // separately, so it is the same as handling four requests for - // data - above and below the equator, and left and right of - // the dateline. Normal case, there is only one box. Two - // boxes if crossing only one of the boundaries. - - int xa = 2; - int ya = 2; - int lat_minus = 2; - int lon_minus = 2; - // Set up checks for equator and dateline - Point2D ll1 = proj.getUpperLeft(); - Point2D ll2 = proj.getLowerRight(); - - lat[0] = ll1.getY(); - lon[0] = ll1.getX(); - lat[1] = ll2.getY(); - lon[1] = ll2.getX(); - lat[2] = ll2.getY(); - lon[2] = ll2.getX(); - - if (lon[0] > 0 && lon[2] < 0) { - lon[1] = -179.999; // put a little breather on the - // dateline - lon_minus = 1; - } - if (lat[0] > 0 && lat[2] < 0) { - lat[1] = -0.0001; // put a little breather on the - // equator - lat_minus = 1; - } - - if (Debug.debugging("dteddetail")) { - Debug.output("For :"); - Debug.output("lat[0] " + lat[0]); - Debug.output("lon[0] " + lon[0]); - Debug.output("lat[1] " + lat[1]); - Debug.output("lon[1] " + lon[1]); - Debug.output("lat[2] " + lat[2]); - Debug.output("lon[2] " + lon[2]); - Debug.output("lat_minus = " + lat_minus); - Debug.output("lon_minus = " + lon_minus); - } - - /* - * Look at all the paths if needed. Worst case, there are four boxes on - * the screen. Best case, there is one. The things that create boxes and - * dictates how large they are are the equator and the dateline. When - * the screen straddles one or both of these lat/lon lines, lon_minus - * and lat_minus get adjusted, causing two or four different calls to - * the tochandler to get the data above/below the equator, and - * left/right of the dateline. Plus, each path gets checked until the - * required boxes are filled. - */ - - if (Debug.debugging("dted")) { - Debug.output("--- DTEDFrameCacheHandler: getting images: ---"); - } - - setProjection(proj, lat[ya - lat_minus], lon[xa - lon_minus], lat[ya], lon[xa]); - - OMGraphicList list = loadListFromHandler(null); - - // Dateline split - if (lon_minus == 1) { - setProjection(proj, lat[ya - lat_minus], lon[0], lat[ya], -1f * lon[1]); // -1 - // to - // make - // it - // 180 - list = loadListFromHandler(list); - } - - // Equator Split - if (lat_minus == 1) { - setProjection(proj, lat[0], lon[xa - lon_minus], -1f * lat[1], // flip - // breather - lon[xa]); - list = loadListFromHandler(list); - } - - // Both!! - if (lon_minus == 1 && lat_minus == 1) { - setProjection(proj, lat[0], lon[0], -1f * lat[1],// flip - // breather - -1f * lon[1]);// -1 to make it 180, not -180 - list = loadListFromHandler(list); - } - - if (Debug.debugging("dted")) { - Debug.output("--- DTEDFrameCacheHandler: finished getting images ---"); - } - - return list; - } - - /** - * Method that pings the cache for images based on the projection that has - * been set on it. If the cache returns null from getNextImage(), it's done. - * Method creates and returns a graphics list if the one passed in is null, - * otherwise it returns the one passed in. - */ - protected OMGraphicList loadListFromHandler(OMGraphicList graphics) { - if (graphics == null) { - graphics = new OMGraphicList(); - } - - OMGraphic image = getNextImage(); - - while (image != null) { - graphics.add(image); - image = getNextImage(); - } - - return graphics; - } - - /** - * The method to call to let the cache handler know what the projection - * looks like so it can figure out which frames (and subframes) will be - * needed. - * - * @param proj the projection of the screen. - */ - public void setProjection(Projection proj) { - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - setProjection(proj, ul.getY(), ul.getX(), lr.getY(), lr.getX()); - } - - /** - * The method to call to let the cache handler know what the projection - * looks like so it can figure out which frames (and subframes) will be - * needed. Should be called when the CacheHandler is dealing with just a - * part of the map, such as when the map covers the dateline or equator. - * - * @param proj the projection of the screen. - * @param lat1 latitude of the upper left corner of the window, in decimal - * degrees. - * @param lon1 longitude of the upper left corner of the window, in decimal - * degrees. - * @param lat2 latitude of the lower right corner of the window, in decimal - * degrees. - * @param lon2 longitude of the lower right corner of the window, in decimal - * degrees. - */ - public void setProjection(Projection proj, double lat1, double lon1, double lat2, double lon2) { - - firstImageReturned = true; - - // upper lat of top frame of the screen - // lower lat of bottom frame of the screen - // left lon of left frame of the screen - // upper lon of right frame of the screen - frameUp = Math.floor(lat1); - frameDown = Math.floor(lat2); - frameLeft = Math.floor(lon1); - frameRight = Math.ceil(lon2); - - if (Debug.debugging("dted")) - Debug.output("frameUp = " + frameUp + ", frameDown = " + frameDown + ", frameLeft = " - + frameLeft + ", frameRight = " + frameRight); - } - - /** - * Returns the next OMGraphic image. When setProjection() is called, the - * cache sets the projection parameters it needs, and also resets this - * popping mechanism. When this mechanism is reset, you can keep calling - * this method to get another subframe image. When it returns a null value, - * it is done. It will automatically skip over window frames it doesn't - * have, and return the next one it does have. It traverses from the top - * left to right frames, and top to bottom for each column of frames. It - * handles all the subframes for a frame at one time. - * - * @return OMGraphic image. - */ - public OMGraphic getNextImage() { - - if (Debug.debugging("dted")) - Debug.output("--- DTEDFrameCacheHandler: getNextImage:"); - - while (true) { - - if (firstImageReturned == true) { - frameLon = frameLeft; - frameLat = frameDown; - newframe = true; - firstImageReturned = false; - } else if (frameLon < frameRight) { - // update statics to look for next frame - if (frameLat < frameUp) { - frameLat++; - } else { - frameLat = frameDown; - frameLon++; - } - newframe = true; - } else { // bounds exceeded, all done - return (OMGraphic) null; - } - - if (newframe && frameLon < frameRight) { - if (Debug.debugging("dted")) { - Debug.output(" gni: Getting new frame Lat = " + frameLat + " Lon = " + frameLon); - } - - OMGraphic omg = get(frameLat, frameLon, dtedLevel); - if (omg != null) { - return omg; - } - } - } - } - - /** - * Return an OMGraphic for the Dted Frame, given A lat, lon and dted level. - * - * @param lat latitude of point - * @param lon longitude of point - * @param level the dted level wanted (0, 1, 2) - * @return OMGraphic, most likely an OMGrid. - */ - public OMGraphic get(double lat, double lon, int level) { - // First, put together a key from the above info, and then - // look for it in the local cache. If it's not there, then go - // to the DTEDFrameCache. - - String key = new String(lat + ":" + lon + ":" + level); - - CacheObject ret = searchCache(key); - if (ret != null) { - if (Debug.debugging("dted")) { - Debug.output("DTEDFrameCacheHandler.get(): retrieving frame from cache (" + lat - + ":" + lon + ":" + level + ")"); - } - return (OMGraphic) ret.obj; - } - - ret = load(key, lat, lon, level); - if (ret == null) { - return null; - } - - replaceLeastUsed(ret); - if (Debug.debugging("dted")) { - Debug.output("DTEDFrameCacheHandler.get(): loading new frame into cache (" + lat + ":" - + lon + ":" + level + ")"); - } - return (OMGraphic) ret.obj; - } - - /** - * Load a dted frame into the cache, based on the path of the frame as a - * key. Implements abstract CacheHandler method. - * - * @param key key to remember raster created for DTED frame. - * @return DTED frame, hidden as a CacheObject. - */ - public CacheObject load(String key, double lat, double lon, int level) { - if (frameCache != null) { - - DTEDFrame frame = frameCache.get(lat, lon, level); - if (frame != null) { - OMGrid omgrid = frame.getOMGrid(); - - // Need to create a unique generator for each OMGrid. - omgrid.setGenerator(getGenerator()); - return new DTEDCacheObject(key, omgrid); - } - } - - return null; - } - - public CacheObject load(Object key) { - // Do nothing, because this implementation doesn't use it. - // The get() method has been overridden to c all the other - // load method with addition needed information to better call - // the DTEDFrameCache. - return null; - } - - /** - * A private class that makes sure that cached frames get disposed properly. - */ - private static class DTEDCacheObject extends CacheObject { - /** - * Construct a DTEDCacheObject, just calls superclass constructor - * - * @param id passed to superclass - * @param obj passed to superclass - */ - public DTEDCacheObject(String id, OMGraphic omg) { - super(id, omg); - } - } - - // //// PropertyConsumer Interface Methods - - /** - * Token uniquely identifying this component in the application properties. - */ - protected String propertyPrefix = null; - - /** - * Sets the properties for the OMComponent. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the OMComponent. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - setPropertyPrefix(prefix); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - String generatorList = props.getProperty(realPrefix + GeneratorLoadersProperty); - if (generatorList != null) { - List generatorMarkers = PropUtils.parseSpacedMarkers(generatorList); - for (String gmString : generatorMarkers) { - String loaderPrefix = realPrefix + gmString; - String loaderClassnameProperty = loaderPrefix + ".class"; - String classname = props.getProperty(loaderClassnameProperty); - - try { - GeneratorLoader loader = (GeneratorLoader) ComponentFactory.create(classname); - loader.setProperties(loaderPrefix, props); - - generatorLoaders.add(loader); - loader.addPropertyChangeListener(this); - // Initialize - if (activeGeneratorLoader == null) { - activeGeneratorLoader = loader; - } - } catch (ClassCastException cce) { - Debug.output("DTEDFrameCacheHandler created " + classname - + ", but it's not a GeneratorLoader"); - } catch (NullPointerException npe) { - Debug.error("DTEDFrameCacheHandler: problem creating generator loader: " - + classname + " from " + loaderClassnameProperty); - } - } - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the OMComponent. If the component has a propertyPrefix - * set, the property keys should have that prefix plus a separating '.' - * prepended to each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer sb = new StringBuffer(); - for (GeneratorLoader gl : generatorLoaders) { - String pref = gl.getPropertyPrefix(); - props.put(pref + ".class", gl.getClass().getName()); - gl.getProperties(props); - - int index = pref.indexOf(prefix); - if (index != -1) { - pref = pref.substring(index + prefix.length()); - } - sb.append(pref).append(" "); - } - - props.put(prefix + GeneratorLoadersProperty, sb.toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - // Not sure how to set up an inspector to create child classes - // yet. - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix string - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * The DTEDFrameCacheHandler needs to sign up as a PropertyChangeListener so - * if anything on the GeneratorLoader GUI changes, it knows to dump the - * current representations so they can be rebuild with the current GUI - * settings. - */ - public void propertyChange(PropertyChangeEvent pce) { - clear(); - } - - public List getGeneratorLoaders() { - if (generatorLoaders == null) { - generatorLoaders = new ArrayList(); - } - return generatorLoaders; - } - - public void setGeneratorLoaders(List generatorLoaders) { - this.generatorLoaders = generatorLoaders; - } - - public void clearGeneratorLoaders() { - getGeneratorLoaders().clear(); - } - - public void addGeneratorLoader(GeneratorLoader gl) { - getGeneratorLoaders().add(gl); - } - - public boolean removeGeneratorLoader(GeneratorLoader gl) { - return getGeneratorLoaders().remove(gl); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameDSI.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameDSI.java deleted file mode 100644 index 392c95fe8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameDSI.java +++ /dev/null @@ -1,244 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrameDSI.java,v -// $ -// $RCSfile: DTEDFrameDSI.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -public class DTEDFrameDSI { - - //DSI fields in order of appearance - filler has been left out. - public char sec_code; - public String sec_rel; - public String sec_handling; - public String sec_res; - public String series; - public String ser_ref_num; - public String ser_res; - public int data_ed; - public char merge_version; - public String maint_date; - public String merge_date; - public String maint_desc; - public String prod_code; - public String prod_res; - public String spec; - public int spec_amen; - public String product_date; - public String vert_datum; - public String horiz_datum; - public String dc_system; - public String compilation_date; - public String date_res; - public float lat_origin; - public float lon_origin; - public float sw_lat; - public float sw_lon; - public float nw_lat; - public float nw_lon; - public float ne_lat; - public float ne_lon; - public float se_lat; - public float se_lon; - public float orient_ang; - public int lat_post_interval; - public int lon_post_interval; - public int num_lat_lines; - public int num_lon_points; - public int part_cell; - - public DTEDFrameDSI(BinaryFile binFile) { - - try { - binFile.seek(DTEDFrame.UHL_SIZE); - - // For now, this is not error checking, just marking space - binFile.skipBytes(3); - - sec_code = binFile.readChar(); - sec_rel = binFile.readFixedLengthString(2); - sec_handling = binFile.readFixedLengthString(27); - sec_res = binFile.readFixedLengthString(26); - series = binFile.readFixedLengthString(5); - ser_ref_num = binFile.readFixedLengthString(15); - ser_res = binFile.readFixedLengthString(8); - String test; - try { - test = binFile.readFixedLengthString(2); - data_ed = Integer.parseInt(test, 10); - } catch (NumberFormatException nfe) { - Debug.message("dted", - "DTEDFrameDSI: Data Edition number bad, using 0"); - data_ed = 0; - } - - merge_version = binFile.readChar(); - maint_date = binFile.readFixedLengthString(4); - merge_date = binFile.readFixedLengthString(4); - maint_desc = binFile.readFixedLengthString(4); - prod_code = binFile.readFixedLengthString(8); - prod_res = binFile.readFixedLengthString(16); - spec = binFile.readFixedLengthString(9); - - try { - test = binFile.readFixedLengthString(2); - spec_amen = Integer.parseInt(test, 10); - } catch (NumberFormatException nfe) { - Debug.message("dted", - "DTEDFrameDSI: Spec Amendment number bad, using 0"); - spec_amen = 0; - } - - product_date = binFile.readFixedLengthString(4); - vert_datum = binFile.readFixedLengthString(3); - horiz_datum = binFile.readFixedLengthString(5); - dc_system = binFile.readFixedLengthString(10); - compilation_date = binFile.readFixedLengthString(4); - date_res = binFile.readFixedLengthString(22); - lat_origin = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(9)); - lon_origin = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(10)); - sw_lat = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(7)); - sw_lon = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(8)); - nw_lat = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(7)); - nw_lon = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(8)); - ne_lat = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(7)); - ne_lon = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(8)); - se_lat = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(7)); - se_lon = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(8)); - - try { - test = binFile.readFixedLengthString(9); - orient_ang = Float.valueOf(test).floatValue(); - } catch (NumberFormatException nfe) { - Debug.message("dted", - "DTEDFrameDSI: orient angle number bad, using 0"); - orient_ang = 0f; - } - - lat_post_interval = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - lon_post_interval = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - num_lat_lines = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - num_lon_points = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - - try { - test = binFile.readFixedLengthString(2); - part_cell = Integer.parseInt(test, 10); - } catch (NumberFormatException nfe) { - Debug.message("dted", - "DTEDFrameDSI: partial cell number bad, using 0"); - part_cell = 0; - } - } catch (IOException e) { - Debug.error("DTEDFrameDSI: File IO Error!\n" + e.toString()); - } catch (FormatException f) { - Debug.error("DTEDFrameDSI: File IO Format error!\n" + f.toString()); - } catch (NumberFormatException nfe) { - // If we catch a number format exception here, too bad. - // The producer should have filled in those values, since - // they reflect the location of the frame and should be - // filled in. - Debug.error("DTEDFrameDSI: Number format error!\n" + nfe.toString()); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("***DSI***").append("\n"); - s.append(" sec_code: ").append(sec_code); - s.append(" sec_rel: ").append(sec_rel).append("\n"); - s.append(" sec_handling: ").append(sec_handling).append("\n"); - s.append(" sec_res: ").append(sec_res).append("\n"); - s.append(" series: ").append(series).append("\n"); - s.append(" ser_ref_num: ").append(ser_ref_num).append("\n"); - s.append(" ser_res: ").append(ser_res).append("\n"); - s.append(" data_ed: ").append(data_ed).append("\n"); - s.append(" merge_version: ").append(merge_version).append("\n"); - s.append(" maint_date: ").append(maint_date).append("\n"); - s.append(" merge_date: ").append(merge_date).append("\n"); - s.append(" maint_desc: ").append(maint_desc).append("\n"); - s.append(" prod_code: ").append(prod_code).append("\n"); - s.append(" prod_res: ").append(prod_res).append("\n"); - s.append(" spec: ").append(spec).append("\n"); - s.append(" spec_amen: ").append(spec_amen).append("\n"); - s.append(" product_date: ").append(product_date).append("\n"); - s.append(" vert_datum: ").append(vert_datum).append("\n"); - s.append(" horiz_datum: ").append(horiz_datum).append("\n"); - s.append(" dc_system: ").append(dc_system).append("\n"); - s.append(" compilation_date: ").append(compilation_date).append("\n"); - s.append(" date_res: ").append(date_res).append("\n"); - s.append(" lat_origin: ").append(lat_origin).append("\n"); - s.append(" lon_origin: ").append(lon_origin).append("\n"); - s.append(" sw_lat: ").append(sw_lat).append("\n"); - s.append(" sw_lon: ").append(sw_lon).append("\n"); - s.append(" nw_lat: ").append(nw_lat).append("\n"); - s.append(" nw_lon: ").append(nw_lon).append("\n"); - s.append(" ne_lat: ").append(ne_lat).append("\n"); - s.append(" ne_lon: ").append(ne_lon).append("\n"); - s.append(" se_lat: ").append(se_lat).append("\n"); - s.append(" se_lon: ").append(se_lon).append("\n"); - s.append(" orient_ang: ").append(orient_ang).append("\n"); - s.append(" lat_post_interval: ").append(lat_post_interval).append("\n"); - s.append(" lon_post_interval: ").append(lon_post_interval).append("\n"); - s.append(" num_lat_lines: ").append(num_lat_lines).append("\n"); - s.append(" num_lon_points: ").append(num_lon_points).append("\n"); - s.append(" part_cell: ").append(part_cell).append("\n"); - return s.toString(); - } - - public static void main(String args[]) { - Debug.init(); - if (args.length < 1) { - Debug.output("dtedframe_dsi: Need a path/filename"); - System.exit(0); - } - - Debug.output("DTEDFrameDSI: using frame " + args[0]); - - java.io.File file = new java.io.File(args[0]); - - try { - - BinaryFile binFile = new BinaryBufferedFile(file); - // BinaryFile binFile = new BinaryFile(file); - DTEDFrameDSI dfd = new DTEDFrameDSI(binFile); - Debug.output(dfd.toString()); - - } catch (java.io.FileNotFoundException e) { - Debug.error("DTEDFrameDSI: file " + args[0] + " not found"); - System.exit(-1); - } catch (IOException e) { - Debug.error("DTEDFrameDSI: File IO Error!\n" + e.toString()); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUHL.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUHL.java deleted file mode 100644 index ee6c152b2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUHL.java +++ /dev/null @@ -1,152 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrameUHL.java,v -// $ -// $RCSfile: DTEDFrameUHL.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/04 18:08:12 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.dataAccess.dted; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -public class DTEDFrameUHL { - public int abs_vert_acc = -1; // in meters - public float lat_origin; // lower left, in degrees - public int lat_post_interval; // in tenths of seconds - - //UHL fields in order of appearance - filler has been left out. - public float lon_origin; // lower left, in degrees - public int lon_post_interval; // in tenths of seconds - public int num_lat_points; - public int num_lon_lines; - public String sec_code; - public String u_ref; - - public DTEDFrameUHL(BinaryFile binFile) { - try { - binFile.seek(0); - binFile.readFixedLengthString(3); // checkUHL - - binFile.skipBytes(1); - lon_origin = DTEDFrameUtil.stringToLon(binFile.readFixedLengthString(8)); - lat_origin = DTEDFrameUtil.stringToLat(binFile.readFixedLengthString(8)); - try { - lon_post_interval = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameUHL: lon_post_interval number bad, using 0"); - lon_post_interval = 0; - } - try { - lat_post_interval = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameUHL: lat_post_interval number bad, using 0"); - lat_post_interval = 0; - } - String s_abs_vert_acc = binFile.readFixedLengthString(4); - - try { - if ((s_abs_vert_acc.indexOf("NA") == -1) - && (s_abs_vert_acc.indexOf("N/A") == -1)) { - abs_vert_acc = Integer.parseInt(s_abs_vert_acc, 10); - } - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameUHL: abs_vert_acc number bad, using 0"); - abs_vert_acc = 0; - } - - sec_code = binFile.readFixedLengthString(3); - u_ref = binFile.readFixedLengthString(12); - try { - num_lon_lines = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameUHL: num_lon_lines number bad, using 0"); - num_lon_lines = 0; - } - try { - num_lat_points = Integer.parseInt(binFile.readFixedLengthString(4), - 10); - } catch (NumberFormatException pExp) { - Debug.message("dted", - "DTEDFrameUHL: num_lat_points number bad, using 0"); - num_lat_points = 0; - } - } catch (IOException e) { - Debug.error("DTEDFrameUHL: File IO Error!\n" + e.toString()); - } catch (FormatException f) { - Debug.error("DTEDFrameUHL: File IO Format error!\n" + f.toString()); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - - s.append("***UHL***").append("\n"); - s.append(" lon_origin: ").append(lon_origin).append("\n"); - s.append(" lat_origin: ").append(lat_origin).append("\n"); - s.append(" lon_post_interval: ").append(lon_post_interval).append("\n"); - s.append(" lat_post_interval: ").append(lat_post_interval).append("\n"); - s.append(" abs_vert_acc: ").append(abs_vert_acc).append("\n"); - s.append(" sec_code: ").append(sec_code).append("\n"); - s.append(" u_ref: ").append(u_ref).append("\n"); - s.append(" num_lon_lines: ").append(num_lon_lines).append("\n"); - s.append(" num_lat_points: ").append(num_lat_points).append("\n"); - return s.toString(); - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - Debug.output("dtedframe_uhl: Need a path/filename"); - System.exit(0); - } - - Debug.output("DTEDFrameUHL: using frame " + args[0]); - - java.io.File file = new java.io.File(args[0]); - - try { - BinaryFile binFile = new BinaryBufferedFile(file); - - // BinaryFile binFile = new BinaryFile(file); - DTEDFrameUHL dfu = new DTEDFrameUHL(binFile); - - Debug.output(dfu.toString()); - - } catch (FileNotFoundException e) { - Debug.error("DTEDFrameUHL: file " + args[0] + " not found"); - System.exit(-1); - } catch (IOException e) { - Debug.error("DTEDFrameUHL: File IO Error!\n" + e.toString()); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUtil.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUtil.java deleted file mode 100644 index 96dd48ac9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDFrameUtil.java +++ /dev/null @@ -1,169 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDFrameUtil.java,v $ -// $RCSfile: DTEDFrameUtil.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -/** - * This class does the conversions that are required for converting - * latitudes and longitudes into filenames, and from string values of - * latitudes and longitudes from within a DTED file to float values. - */ -public class DTEDFrameUtil { - - /** - * Conversion of string found in DTED file to float value. - * - * @param text_lat the String representation of the latitude, from - * the file. - * @return the latitude in decimal degrees. - */ - public static float stringToLat(String text_lat) { - int offset = 0; - int hemisphere = 1; - String s_seconds; - - if (text_lat.length() > 7 && text_lat.charAt(6) != '.') - offset = 1; - char[] contents = text_lat.toCharArray(); - String s_degrees = String.valueOf(contents, offset, 2); - String s_minutes = String.valueOf(contents, 2 + offset, 2); - - if (text_lat.charAt(6 + offset) == '.') { - s_seconds = String.valueOf(contents, 4 + offset, 4); - if (text_lat.charAt(8 + offset) == 'S') - hemisphere = -1; - } else { - s_seconds = String.valueOf(contents, 4 + offset, 2); - if (text_lat.charAt(6 + offset) == 'S') - hemisphere = -1; - } - - float result = Float.valueOf(s_degrees).floatValue() - + (Float.valueOf(s_minutes).floatValue() / 60.0F) - + (Float.valueOf(s_seconds).floatValue() / 3600.0F); - result *= hemisphere; - return result; - } - - /** - * Conversion of a string value of a longitude to a float. - * - * @param text_lon the longitude String representation, out of a - * DTED file. - * @return the longitude in decimal degrees. - */ - public static float stringToLon(String text_lon) { - int hemisphere = 1; - String s_seconds; - - char[] contents = text_lon.toCharArray(); - String s_degrees = String.valueOf(contents, 0, 3); - String s_minutes = String.valueOf(contents, 3, 2); - - if (text_lon.charAt(7) == '.') { - s_seconds = String.valueOf(contents, 5, 4); - if (text_lon.charAt(9) == 'W') - hemisphere = -1; - } else { - s_seconds = String.valueOf(contents, 5, 2); - if (text_lon.charAt(7) == 'W') - hemisphere = -1; - } - - float result = Float.valueOf(s_degrees).floatValue() - + (Float.valueOf(s_minutes).floatValue() / 60.0F) - + (Float.valueOf(s_seconds).floatValue() / 3600.0F); - result *= hemisphere; - return result; - } - - /** - * Conversion of a float latitude value and DTED level to a DTED - * filename. DTED filenames are based on these two factors -<n/s> - * <value>.dt{0,1} DTED Level 0 files are named .dt0. Level 1 and - * higher are named .dt1, rather than .dt{level} - * - * @param lat latitude in decimal degrees. - * @param level the DTED level. - * @return part of the DTED directory path that longitude - * contributes to. - */ - public static String latToFileString(float lat, int level) { - String direction; - if (lat >= 0) { - direction = "n"; - lat = (float) Math.floor(lat); - } else { - direction = "s"; - lat = (float) Math.ceil(lat * -1); - } - - // int ilat = new Float(lat).intValue(); - // result = new String(direction + ilat + ".dt" + level); - - // The two lines above wrongly manages lat < 10. It generates - // n5.dt0 instead of n05.dt0 - sokolov@system.ecology.su.se - - // 14 - // April 1999 - - java.text.DecimalFormat fd = new java.text.DecimalFormat("00"); - String result = direction + fd.format(lat) + ".dt" + level; - - return result; - } - - /** - * Conversion of a float longitude value to a DTED parent - * directory of frame files. DTED parent directories are based on - * latitude -<w/e><value>. - * - * @param lon longitude in decimal degrees. - * @return part of the DTED directory path that longitude - * contributes to. - */ - public static String lonToFileString(float lon) { - String result, direction; - if (lon >= 0) { - direction = "e"; - lon = (float) Math.floor(lon); - } else { - direction = "w"; - lon = (float) Math.ceil(lon * -1); - } - - // int ilon = new Float(lon).intValue(); - // if (ilon > 100) result = new String(direction + ilon); - // else result = new String(direction + "0" + ilon); - - // The three lines above wrongly manages lon < 10. It - // generates e05 instead of e005 - - // sokolov@system.ecology.su.se - // - 14 April 1999 - - java.text.DecimalFormat fd = new java.text.DecimalFormat("000"); - result = direction + fd.format(lon); - - return result; - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDLocator.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDLocator.java deleted file mode 100644 index 377a7847a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDLocator.java +++ /dev/null @@ -1,213 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDLocator.java,v $ -// $RCSfile: DTEDLocator.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/04 18:08:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import java.io.File; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.wanderer.Wanderer; -import com.bbn.openmap.util.wanderer.WandererCallback; - -/** - * DTEDLocator finds DTED frame files, and organizes them by level, longitude - * and latitude. - *

- * - *

- * 
- *  Usage: java com.bbn.openmap.dataAccess.dted.DTEDLocator (dir path) ...
- * 
- * 
- */ -public class DTEDLocator - extends Wanderer - implements WandererCallback { - - static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.dted.DTEDLocator"); - - boolean DEBUG = false; - - protected DTEDNameTranslator translator; - - protected LinkedList filenames = new LinkedList(); - - protected File[][][] files = null; - protected int numLevels = 3; - - /** - * Create a DTEDLocator, expect to set the top level DTED directory later. - */ - public DTEDLocator() { - super(); - if (logger.isLoggable(Level.FINE)) { - DEBUG = true; - } - setCallback(this); - } - - /** - * Create the DTEDLocator and start searching from the directory specificed. - */ - public DTEDLocator(String directory) { - this(new File(directory)); - } - - /** - * Create the DTEDLocator and start searching from the directory specificed. - */ - public DTEDLocator(File dtedDir) { - this(); - handleEntry(dtedDir); - } - - /** - * Initialize the holding arrays. - */ - protected void initFileHolder() { - files = new File[numLevels][180][360]; // level,lat, lon - } - - /** - * Does nothing, nothing is done for directories. - */ - public boolean handleDirectory(File directory) { - if (DEBUG) { - logger.fine("skipping: " + directory.getAbsolutePath()); - } - // Do nothing to directories - return true; - } - - /** - * When a file is found, add it. - */ - public boolean handleFile(File file) { - if (DEBUG) { - logger.fine("searching finds: " + file.getAbsolutePath()); - } - filenames.add(file); - return true; - } - - /** - * Get the DTEDNameTranslator that knows how to interpret where a DTED file - * covers based on its name. - */ - public DTEDNameTranslator getTranslator() { - if (translator == null) { - translator = new StandardDTEDNameTranslator(); - } - - return translator; - } - - /** - * Set the DTEDNameTranslator that knows how to interpret where a DTED file - * covers based on its name. - */ - public void setTranslator(DTEDNameTranslator dnt) { - translator = dnt; - } - - /** - * After all the files have been located, organized them spatially in the 3D - * array. - */ - public void organize() { - if (DEBUG) { - logger.fine("organizing frames..."); - } - initFileHolder(); - Iterator it = filenames.iterator(); - DTEDNameTranslator dnt = getTranslator(); - - while (it.hasNext()) { - File file = (File) it.next(); - String filename = file.getAbsolutePath(); - try { - dnt.set(filename); - - int l = dnt.getLevel(); - int lt = (int) (dnt.getLat() + 90); - int ln = (int) (dnt.getLon() + 180); - - if (DEBUG) { - logger.fine(" placing " + filename + " at files[" + l + "][" + lt + "][" + ln + "]"); - } - - files[l][lt][ln] = file; - - } catch (FormatException fe) { - continue; - } catch (ArrayIndexOutOfBoundsException aioobe) { - continue; - } - } - } - - /** - * Get the File object for a latitude, longitude and level. - */ - public File get(float lat, float lon, int level) { - // Need to offset lat/lon to indexes. - - try { - return files[level][(int) (lat + 90)][(int) (lon + 180)]; - } catch (NullPointerException npe) { - organize(); - return get(lat, lon, level); - } catch (ArrayIndexOutOfBoundsException aioobe) { - - } - return null; - } - - /** - * Given a set of files or directories, parade through them to find files - * that end with '`', or files that start with '.#', and delete them. - * - * @param argv paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("DTEDLocator"); - - if (argv.length == 0) { - ap.bail("", true); - } - - DTEDLocator locator = new DTEDLocator(); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < argv.length; i++) { - locator.handleEntry(new File(argv[i])); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDNameTranslator.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDNameTranslator.java deleted file mode 100644 index fa1379aa2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDNameTranslator.java +++ /dev/null @@ -1,144 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDNameTranslator.java,v $ -// $RCSfile: DTEDNameTranslator.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import com.bbn.openmap.io.FormatException; - -/** - * An interface that defines a object that knows how to define the - * name of a DTED file from a set of coordinates and dted level, and - * also knows how to translate the name of a DTED file to it's - * coverage coordinates and level. Keeps track of the file name, the - * sub-directory path from the top level dted directory to the file, - * and the location of the dted directory if it is specified. It's - * intended that a single DTEDNameTranslator be used for a single DTED - * directory containing a set of directories and files. For objects - * that want to manage a set of DTED directories, a set of - * DTEDNameTranslators are needed. This is required to allow the - * translator the ability to take a lat/lon and provide a String - * representation of what a file would be called if it were stored - * under the specified DTED directory. The translator makes no - * guarantees on whether the file actually exists. - */ -public interface DTEDNameTranslator { - - /** - * Set the internal parameters based on the given file path. - * - * @param filePath a path to a dted frame file. - */ - public void set(String filePath) throws FormatException; - - /** - * Sets the internal parameters given a parent DTED directory, - * latitude, longitude and level. getName can be called to fetch - * a file name for these parameters. - * - * @param dtedDir the path to the top DTED directory. - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public void set(String dtedDir, double lat, double lon, int level); - - /** - * Assuming that the DTED directory is set, set the other - * parameters to reveal a path to a file name, which would be - * retrieved by calling getName(). - * - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public void set(double lat, double lon, int level); - - /** - * Set the latitude in the translator. - * - * @param lat the desired latitude, in decimal degrees. - */ - public void setLat(double lat); - - /** - * Get the latitude. - */ - public double getLat(); - - /** - * Set the longitude in the translator. - * - * @param lon the desired longitude, in decimal degrees. - */ - public void setLon(double lon); - - /** - * Get the longitude. - */ - public double getLon(); - - /** - * Set the DTED level in the translator. - * - * @param level the DTED level (0, 1, 2). - */ - public void setLevel(int level); - - /** - * Get the DTED level set in the translator. - */ - public int getLevel(); - - /** - * Get the complete path to the DTED frame file based on the - * current internal settings. - */ - public String getName(); - - /** - * Configure the internal settings based on a path to a DTED frame - * file. - */ - public void setName(String fileName) throws FormatException; - - /** - * Get the relative part of the path to the DTED frame file, from - * just under the top-level dted directory to just above the frame - * file. - */ - public String getSubDirs(); - - /** - * Get the file name. - */ - public String getFileName(); - - /** - * Set the top-level DTED directory. - */ - public void setDTEDDir(String dtedDirectory); - - /** - * Get the path to the top-level DTED directory. - */ - public String getDTEDDir(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDSlopeGenerator.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDSlopeGenerator.java deleted file mode 100644 index 17e53e3de..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/DTEDSlopeGenerator.java +++ /dev/null @@ -1,111 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/DTEDSlopeGenerator.java,v $ -// $RCSfile: DTEDSlopeGenerator.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.grid.ElevationColors; -import com.bbn.openmap.omGraphics.grid.SlopeGenerator; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; - -/** - * The DTEDSlopeGenerator is an extension to the SlopeGenerator that - * uses OMScalingRasters for images created from the DTED data. It - * caches the image and will reuse it if the projection parameters - * allow it. It's needed because it assumes that the OMGrid used is a - * OMDTEDGrid, which has the lat/lons of the lower left and upper - * right corners of the DTED frame. - */ -public class DTEDSlopeGenerator extends SlopeGenerator { - - public DTEDSlopeGenerator() {} - - public DTEDSlopeGenerator(ElevationColors elevColors) { - super(elevColors); - } - - /** - * Called from within generate to create an OMRaster object for - * the OMGrid. This method exists to make it easier to extend this - * class to create an OMRaster as needed. - */ - protected OMRaster getRaster(OMGrid grid) { - if (grid instanceof OMDTEDGrid) { - OMDTEDGrid dGrid = (OMDTEDGrid) grid; - - // This is probably too expensive for our tastes, since it - // could be keeping two images around. One for the - // created image, and one for the scaled image. - // raster = new OMScalingRaster(dGrid.getUpperLat(), - // dGrid.getLeftLon(), - // dGrid.getLowerLat(), dGrid.getRightLon(), - // dGrid.width, dGrid.height, - // new int[dGrid.width*dGrid.height]); - - raster = new OMRaster(dGrid.getUpperLat(), dGrid.getLeftLon(), dGrid.width, dGrid.height, new int[dGrid.width - * dGrid.height]); - return raster; - } else { - raster = null; - return super.getRaster(grid); - } - } - - /** - * The cached OMScalingRaster, which can be reused instead of - * regenerated in some projection circumstances. - */ - protected OMRaster raster; - - /** - * The scale at which the cached raster was generated. - */ - protected float generatedScale = Float.MAX_VALUE; - - /** - * Called from the OMGrid.generate() method to tell the generator - * to create something to represent the grid contents. - */ - public OMGraphic generate(OMGrid grid, Projection proj) { - // Make a decision based on the last projection to see if we - // should generate a new raster from the data with better - // detail. - - // We used to keep the same OMScalingRaster here if the scale - // number was larger, but I think that might be too much - // memory usage, more so if the scales are pretty close and - // you have two images pretty much the same size for each dted - // frame. So we reuse if the scales match. - if (raster != null && proj instanceof EqualArc - && proj.getScale() == generatedScale && !isIncompleteImage()) { - raster.generate(proj); - return raster; - } else { - generatedScale = proj.getScale(); - return super.generate(grid, proj); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/OMDTEDGrid.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/OMDTEDGrid.java deleted file mode 100644 index 0733e0cab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/OMDTEDGrid.java +++ /dev/null @@ -1,145 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/OMDTEDGrid.java,v $ -// $RCSfile: OMDTEDGrid.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.GridData; - -/** - * The OMDTEDGrid is an extended OMGrid with information about the - * lat/lons of the corners of the grids, so the generators can use - * OMScalingRasters for precise alignment. - */ -public class OMDTEDGrid extends OMGrid { - - /** - * The starting latitude point of the grid. Only relevant when the - * data points are laid out in a lat/lon grid, or when an x/y grid - * is anchored to a lat/lon location. DOES NOT follow the OpenMap - * convention where area object locations are defined by the upper - * left location - the location of the grid is noted by the lower - * left corner, because grid data is usually defined by the lower - * left location. Makes it easier to deal with overlap rows and - * columns, and to calculate the locations of the rows and - * columns. - */ - protected double latitude1; - /** - * The starting longitude point of the grid. Only relevant when - * the data points are laid out in a lat/lon grid, or when an x/y - * grid is anchored to a lat/lon location. DOES NOT follow the - * OpenMap convention where area object locations are defined by - * the upper left location - the location of the grid is noted by - * the lower left corner, because grid data is usually defined by - * the lower left location. Makes it easier to deal with overlap - * rows and columns, and to calculate the locations of the rows - * and columns. - */ - protected double longitude1; - - public OMDTEDGrid(double lllat, double lllon, double urlat, double urlon, - double vResolution, double hResolution, GridData.Short data) { - super(lllat, lllon, vResolution, hResolution, data); - latitude1 = urlat; - longitude1 = urlon; - } - - /** - * Change the upper latitude attribute. - * - * @param value latitude in decimal degrees. - */ - public void setLowerLat(double value) { - setLatitude(value); - } - - /** - * Get the upper latitude. - * - * @return the latitude in decimal degrees. - */ - public double getLowerLat() { - return getLatitude(); - } - - /** - * Change the western longitude attribute. - * - * @param value the longitude in decimal degrees. - */ - public void setLeftLon(double value) { - setLongitude(value); - } - - /** - * Get the western longitude. - * - * @return longitude in decimal degrees. - */ - public double getLeftLon() { - return getLongitude(); - } - - /** - * Change the southern latitude attribute. - * - * @param value latitude in decimal degrees. - */ - public void setUpperLat(double value) { - if (latitude1 == value) - return; - latitude1 = value; - setNeedToRegenerate(true); - } - - /** - * Get the southern latitude. - * - * @return the latitude in decimal degrees. - */ - public double getUpperLat() { - return latitude1; - } - - /** - * Change the eastern longitude attribute. - * - * @param value the longitude in decimal degrees. - */ - public void setRightLon(double value) { - if (longitude1 == value) - return; - longitude1 = value; - setNeedToRegenerate(true); - } - - /** - * Get the eastern longitude. - * - * @return longitude in decimal degrees. - */ - public double getRightLon() { - return longitude1; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/StandardDTEDNameTranslator.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/StandardDTEDNameTranslator.java deleted file mode 100644 index 001843287..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/dted/StandardDTEDNameTranslator.java +++ /dev/null @@ -1,328 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/dted/StandardDTEDNameTranslator.java,v $ -// $RCSfile: StandardDTEDNameTranslator.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.dted; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * A class implementing the DTEDNameTranslator interface that handles - * DTED file names as specified in the DTED specification. These file - * names follow this naming convention: - *

- * - *

- * 
- * 
- *  dted/[e|w]xxx/[n|s]yy.dt[level]
- * 
- *  
- * 
- */ -public class StandardDTEDNameTranslator implements DTEDNameTranslator { - protected boolean DEBUG = Debug.debugging("dtedfile"); - - protected String filename = null; - protected String subDirs = null; - protected String dtedDir = ""; - protected double lat; - protected double lon; - protected int level; - - /** - * Constructor for object to use for multiple translations. - */ - public StandardDTEDNameTranslator() {} - - /** - * Set the internal parameters given a parent DTED directory, - * latitude, longitude and level. getName can be called to fetch - * a file name for these parameters. - * - * @param dtedDir the path to the top DTED directory. - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public StandardDTEDNameTranslator(String dtedDir, double lat, double lon, - int level) { - set(dtedDir, lat, lon, level); - } - - /** - * Assuming that the DTED directory will be set, set the other - * parameters to reveal a path to a file name, which would be - * retrieved by calling getName(). - * - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public StandardDTEDNameTranslator(double lat, double lon, int level) { - set(null, lat, lon, level); - } - - /** - * Set the internal parameters based on the given file path. - * - * @param filePath a path to a dted frame file. - */ - public void set(String filePath) throws FormatException { - evaluate(filePath); - } - - /** - * Set the internal parameters given a parent DTED directory, - * latitude, longitude and level. getName can be called to fetch - * a file name for these parameters. - * - * @param dtedDir the path to the top DTED directory. - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public void set(String dtedDir, double lat, double lon, int level) { - setDTEDDir(dtedDir); - filename = evaluate(lat, lon, level); - } - - /** - * Assuming that the DTED directory is set, set the other - * parameters to reveal a path to a file name, which would be - * retrieved by calling getName(). - * - * @param lat the desired latitude, in decimal degrees. - * @param lon the desired longitude, in decimal degrees. - * @param level the DTED level (0, 1, 2). - */ - public void set(double lat, double lon, int level) { - set(getDTEDDir(), lat, lon, level); - } - - /** - * Set the latitude in the translator. - * - * @param latitude the desired latitude, in decimal degrees. - */ - public void setLat(double latitude) { - filename = evaluate(latitude, getLon(), getLevel()); - } - - /** - * Get the latitude. - */ - public double getLat() { - return lat; - } - - /** - * Set the longitude in the translator. - * - * @param longitude the desired longitude, in decimal degrees. - */ - public void setLon(double longitude) { - filename = evaluate(getLat(), longitude, getLevel()); - } - - /** - * Get the longitude. - */ - public double getLon() { - return lon; - } - - /** - * Set the DTED level in the translator. - * - * @param level the DTED level (0, 1, 2). - */ - public void setLevel(int level) { - filename = evaluate(getLat(), getLon(), level); - } - - /** - * Get the DTED level set in the translator. - */ - public int getLevel() { - return level; - } - - /** - * Get the relative part of the path to the DTED frame file, from - * just under the top-level dted directory to just above the frame - * file. - */ - public String getSubDirs() { - return subDirs; - } - - /** - * Get the file name. - */ - public String getFileName() { - return filename; - } - - /** - * Get the complete path to the DTED frame file based on the - * current internal settings. - */ - public String getName() { - return dtedDir + "/" + filename; - } - - /** - * Configure the internal settings based on a path to a DTED frame - * file. - */ - public void setName(String fileName) throws FormatException { - evaluate(fileName); - } - - /** - * Set the top-level DTED directory. - */ - public void setDTEDDir(String dtedDirectory) { - if (dtedDirectory == null) { - dtedDir = ""; - } - dtedDir = dtedDirectory; - } - - /** - * Get the path to the top-level DTED directory. - */ - public String getDTEDDir() { - return dtedDir; - } - - /** - * Update all the other settings based on these. - */ - protected String evaluate(double lat, double lon, int level) { - this.lat = Math.floor(lat); - this.lon = Math.floor(lon); - this.level = level; - return DTEDFrameUtil.lonToFileString((float) lon) + "/" - + DTEDFrameUtil.latToFileString((float) lat, level); - } - - /** - * Update all the other settings based on these. - */ - protected void evaluate(String filePath) throws FormatException { - - try { - int latSlash = filePath.lastIndexOf("/"); - if (latSlash > 1) { - if (DEBUG) { - Debug.output("Have lat index of " + latSlash); - } - String lonSearch = filePath.substring(0, latSlash); - - if (DEBUG) { - Debug.output("Searching for lon index in " + lonSearch); - } - int lonSlash = lonSearch.lastIndexOf("/"); - if (lonSlash > 1) { - filename = filePath.substring(latSlash + 1); - String latString = filename.toUpperCase(); - - if (DEBUG) { - Debug.output("have lat " + latString); - } - - int dotIndex = latString.indexOf("."); - if (dotIndex > 0) { - - lat = Double.parseDouble(latString.substring(1, - dotIndex)); - if (latString.charAt(0) == 'S') { - lat *= -1; - } - - subDirs = filePath.substring(lonSlash + 1, latSlash); - String dd = filePath.substring(0, lonSlash + 1); - if (dd.length() > 0) { - dtedDir = dd; - } - - String lonString = subDirs.toUpperCase(); - - if (DEBUG) { - Debug.output("have lon " + lonString); - } - - lon = Double.parseDouble(lonString.substring(1)); - if (lonString.charAt(0) == 'W') { - lon *= -1; - } - - level = (int) Integer.parseInt(filePath.substring(filePath.length() - 1)); - if (DEBUG) { - Debug.output("have level " + level); - } - return; - } - } - } - } catch (NumberFormatException nfe) { - - } - - throw new FormatException("StandardDTEDNameTranslator couldn't convert " - + filePath + " to valid parameters"); - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("For file: ").append(filename).append("\n"); - sb.append(" lat = ").append(lat).append("\n"); - sb.append(" lon = ").append(lon).append("\n"); - sb.append(" level = ").append(level).append("\n"); - String dd = getDTEDDir(); - if (dd.length() > 0) { - dd += "/"; - } - sb.append(" path = ").append(dd).append(getSubDirs()) - .append("/").append(getName()).append("\n"); - return sb.toString(); - } - - public static void main(String[] argv) { - Debug.init(); - if (argv.length == 0) { - Debug.output("Usage: StandardDTEDNameTranslator "); - System.exit(0); - } - - StandardDTEDNameTranslator sdnt = new StandardDTEDNameTranslator(); - try { - sdnt.set(argv[0]); - Debug.output(sdnt.toString()); - } catch (FormatException fe) { - Debug.output(fe.getMessage()); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Crs.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Crs.java deleted file mode 100755 index 9180d73ad..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Crs.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.HashMap; -import java.util.Map; - -public class Crs { - - private String type = "name"; - private Map properties = new HashMap(); - - public String getType() { - return type; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Feature.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Feature.java deleted file mode 100755 index c19f798a1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Feature.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import com.bbn.openmap.omGraphics.OMGraphic; - -public class Feature extends GeoJsonObject { - - private GeoJsonObject geometry; - private String id; - - public GeoJsonObject getGeometry() { - return geometry; - } - - public void setGeometry(GeoJsonObject geometry) { - this.geometry = geometry; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public OMGraphic convert() { - OMGraphic omg = getGeometry().convert(); - omg.getAttributes().putAll(getProperties()); - return omg; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/FeatureCollection.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/FeatureCollection.java deleted file mode 100755 index ff33d6e82..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/FeatureCollection.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; - -public class FeatureCollection extends GeoJsonObject implements Iterable { - - private List features = new ArrayList(); - - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - public FeatureCollection add(Feature feature) { - features.add(feature); - return this; - } - - public void addAll(Collection features) { - this.features.addAll(features); - } - - public Iterator iterator() { - return features.iterator(); - } - - public OMGraphic convert() { - OMGraphicList omgl = new OMGraphicList(); - for (Feature feature : this) { - omgl.add(feature.convert()); - } - omgl.getAttributes().putAll(getProperties()); - return omgl; - } - - public void add(Geometry geometry, OMGraphic omg) { - Feature ret = new Feature(); - ret.setGeometry(geometry); - ret.setProperties(OMGeoJSONUtil.convert(omg.getAttributes())); - add(ret); - } - - public void add(Point point, OMGraphic omg) { - Feature ret = new Feature(); - ret.setGeometry(point); - ret.setProperties(OMGeoJSONUtil.convert(omg.getAttributes())); - add(ret); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeoJsonObject.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeoJsonObject.java deleted file mode 100755 index e9b0c1cb8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeoJsonObject.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.HashMap; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonSubTypes.Type; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; - -@JsonTypeInfo(property = "type", use = Id.NAME) -@JsonSubTypes({ @Type(Feature.class), @Type(Polygon.class), @Type(MultiPolygon.class), - @Type(FeatureCollection.class), @Type(Point.class), @Type(MultiPoint.class), - @Type(MultiLineString.class), @Type(LineString.class) }) -@JsonInclude(Include.NON_NULL) -public abstract class GeoJsonObject { - - private Crs crs; - private double[] bbox; - @JsonInclude(Include.NON_EMPTY) - private Map properties = new HashMap(); - @JsonInclude(Include.NON_EMPTY) - private Map metadata = new HashMap(); - - public Crs getCrs() { - return crs; - } - - public void setCrs(Crs crs) { - this.crs = crs; - } - - public double[] getBbox() { - return bbox; - } - - public void setBbox(double[] bbox) { - this.bbox = bbox; - } - - public void setProperty(String key, Object value) { - properties.put(key, value); - } - - @SuppressWarnings("unchecked") - public T getProperty(String key) { - return (T) properties.get(key); - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } - - /** - * @return the metadata - */ - public Map getMetadata() { - return metadata; - } - - /** - * @param metadata the metadata to set - */ - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - public abstract OMGraphic convert(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Geometry.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Geometry.java deleted file mode 100755 index 239d60bbc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Geometry.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.ArrayList; -import java.util.List; - -public abstract class Geometry extends GeoJsonObject { - - protected List coordinates = new ArrayList(); - - public Geometry() { - } - - public Geometry(T... elements) { - for (T coordinate : elements) { - coordinates.add(coordinate); - } - } - - public Geometry add(T elements) { - coordinates.add(elements); - return this; - } - - public List getCoordinates() { - return coordinates; - } - - public void setCoordinates(List coordinates) { - this.coordinates = coordinates; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeometryCollection.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeometryCollection.java deleted file mode 100755 index 0d3caf36a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/GeometryCollection.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; - -public class GeometryCollection extends GeoJsonObject implements Iterable { - - private List geometries = new ArrayList(); - - public List getGeometries() { - return geometries; - } - - public void setGeometries(List geometries) { - this.geometries = geometries; - } - - public Iterator iterator() { - return geometries.iterator(); - } - - public GeometryCollection add(GeoJsonObject geometry) { - geometries.add(geometry); - return this; - } - - public OMGraphic convert() { - OMGraphicList ret = new OMGraphicList(); - for (GeoJsonObject jgo : getGeometries()) { - ret.add(jgo.convert()); - } - ret.getAttributes().putAll(getProperties()); - return ret; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LICENSE b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LICENSE deleted file mode 100755 index 37ec93a14..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LineString.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LineString.java deleted file mode 100755 index 036855726..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LineString.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoly; - -public class LineString extends MultiPoint { - - public LineString() { - } - - public LineString(LngLatAlt... points) { - super(points); - } - - public LineString(OMPoly poly) { - for (LngLatAlt lla : OMGeoJSONUtil.convertToJSON(poly.getRawllpts(), true)) { - add(lla); - } - } - - public LineString(OMLine line) { - double[] ll = line.getLL(); - add(new LngLatAlt(ll[1], ll[0])); - add(new LngLatAlt(ll[3], ll[2])); - } - - public OMGraphic convert() { - OMPoly poly = new OMPoly(OMGeoJSONUtil.convertToRadians(getCoordinates()), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - poly.getAttributes().putAll(getProperties()); - return poly; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LngLatAlt.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LngLatAlt.java deleted file mode 100755 index 8c85ab202..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/LngLatAlt.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import com.bbn.openmap.dataAccess.geojson.jackson.LngLatAltDeserializer; -import com.bbn.openmap.dataAccess.geojson.jackson.LngLatAltSerializer; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonDeserialize(using = LngLatAltDeserializer.class) -@JsonSerialize(using = LngLatAltSerializer.class) -public class LngLatAlt { - - private double longitude; - private double latitude; - private double altitude = Double.NaN; - - public LngLatAlt() { - } - - public LngLatAlt(double longitude, double latitude) { - this.longitude = longitude; - this.latitude = latitude; - } - - public LngLatAlt(double longitude, double latitude, double altitude) { - this.longitude = longitude; - this.latitude = latitude; - this.altitude = altitude; - } - - public boolean hasAltitude() { - return !Double.isNaN(altitude); - } - - public double getLongitude() { - return longitude; - } - - public void setLongitude(double longitude) { - this.longitude = longitude; - } - - public double getLatitude() { - return latitude; - } - - public void setLatitude(double latitude) { - this.latitude = latitude; - } - - public double getAltitude() { - return altitude; - } - - public void setAltitude(double altitude) { - this.altitude = altitude; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiLineString.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiLineString.java deleted file mode 100755 index 3dc0887af..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiLineString.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoly; - -public class MultiLineString extends Geometry> { - - public MultiLineString() { - } - - public MultiLineString(List line) { - add(line); - } - - public MultiLineString(OMGraphicList omgl) { - for (OMGraphic omg : omgl) { - if (omg instanceof OMLine) { - List llaList = new ArrayList(); - double[] ll = ((OMLine) omg).getLL(); - llaList.add(new LngLatAlt(ll[1], ll[0])); - llaList.add(new LngLatAlt(ll[3], ll[2])); - add(llaList); - } else if (omg instanceof OMPoly) { - List llaList = new ArrayList(); - for (LngLatAlt lla : OMGeoJSONUtil.convertToJSON(((OMPoly) omg).getRawllpts(), true)) { - llaList.add(lla); - } - add(llaList); - } - } - } - - public OMGraphic convert() { - OMGraphicList ret = new OMGraphicList(); - ret.setVague(true); - for (List line : getCoordinates()) { - OMPoly poly = new OMPoly(OMGeoJSONUtil.convertToRadians(line), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - ret.add(poly); - } - ret.getAttributes().putAll(getProperties()); - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPoint.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPoint.java deleted file mode 100755 index 8ca9643dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPoint.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; - - -public class MultiPoint extends Geometry { - - public MultiPoint() { - } - - public MultiPoint(LngLatAlt... points) { - super(points); - } - - public MultiPoint(OMGraphicList omgl) { - for (OMGraphic omg : omgl) { - if (omg instanceof OMPoint) { - add(new LngLatAlt(((OMPoint) omg).getLon(), ((OMPoint) omg).getLat())); - } - } - } - - public OMGraphic convert() { - OMGraphicList omgl = new OMGraphicList(); - omgl.setVague(true); - for (LngLatAlt pnt : getCoordinates()) { - omgl.add(new OMPoint(pnt.getLatitude(), pnt.getLongitude())); - } - omgl.getAttributes().putAll(getProperties()); - return omgl; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPolygon.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPolygon.java deleted file mode 100755 index 7b1164ea4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/MultiPolygon.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.List; - -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; - -public class MultiPolygon extends Geometry>> { - - public MultiPolygon() { - } - - public MultiPolygon(Polygon polygon) { - add(polygon); - } - - public MultiPolygon(OMGraphicList omgl) { - - } - - public MultiPolygon add(Polygon polygon) { - coordinates.add(polygon.getCoordinates()); - return this; - } - - public OMGraphic convert() { - OMGraphicList omgl = new OMGraphicList(); - omgl.setVague(true); - for (List> polyPnts : coordinates) { - - if (polyPnts.size() > 1) { - OMAreaList omal = new OMAreaList(); - for (List innerPolyPnts : polyPnts) { - omgl.add(new OMPoly(OMGeoJSONUtil.convertToRadians(innerPolyPnts), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE)); - } - - omgl.add(omal); - } else { - omgl.add(new OMPoly(OMGeoJSONUtil.convertToRadians(polyPnts.get(0)), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE)); - } - - } - omgl.getAttributes().putAll(getProperties()); - return omgl; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/OMGeoJSONUtil.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/OMGeoJSONUtil.java deleted file mode 100644 index 564b6e1d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/OMGeoJSONUtil.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * - */ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRangeRings; -import com.bbn.openmap.omGraphics.OMRect; - -/** - * Conversion methods for GeoJSON to OpenMap. - * - * @author dietrick - */ -public class OMGeoJSONUtil { - - /** - * Convert a List of LngLatAlt objects to an array alternating lat/lon radian values. - * @param lla List of LngLatAlt - * @return double array radians - */ - public static double[] convertToRadians(List lla) { - - double[] ret = new double[lla.size() * 2]; - int index = 0; - for (LngLatAlt coord : lla) { - ret[index++] = Math.toRadians(coord.getLatitude()); - ret[index++] = Math.toRadians(coord.getLongitude()); - } - - return ret; - } - - /** - * Convert a List of LngLatAlt objects to an array alternating lat/lon decimal degree values. - * @param lla List of LngLatAlt - * @return double array decimal degrees - */ - public static double[] convertToDegrees(List lla) { - - double[] ret = new double[lla.size() * 2]; - int index = 0; - for (LngLatAlt coord : lla) { - ret[index++] = coord.getLatitude(); - ret[index++] = coord.getLongitude(); - } - - return ret; - } - - /** - * Convert coord double[] to list of LngLatAlt. - * - * @param coords lat, lon order - * @param isRadians true if radians, false for degrees. - * @return List of LngLatAlt - */ - public static List convertToJSON(double[] coords, boolean isRadians) { - List ret = new ArrayList(coords.length / 2); - for (int index = 0; index < coords.length - 1; index += 2) { - double lat = coords[index]; - double lon = coords[index + 1]; - - if (isRadians) { - lat = Math.toDegrees(lat); - lon = Math.toDegrees(lon); - } - - ret.add(new LngLatAlt(lon, lat)); - } - - return ret; - } - - /** - * Method to call if you have an OMGraphic/OMGraphicList and want to convert - * it to GeoJSON. There are restrictions to what can be converted. OMPolys - * are converted to Polygons, OMLine and OMPolys that are open are converted - * to LineStrings, OMPoints are converted to Points. OMCircles and OMRects - * are converted to Polygons. Vague OMGraphicLists containing OMPolys or - * open OMPolys or OMLines or OMPoints are converted to MultiPolygon, - * MultiLineString or MultiPoint respectively. Anything that can't be - * handled is ignored. - *

- * - * From here, all you need to do to write out JSON is this: - * - *

-     * String json = new ObjectMapper().writeValueAsString(fCollection);
-     * 
- * - * @param omg OMGraphic to convert - * @return FeatureCollection. - */ - public static FeatureCollection convert(OMGraphic omg) { - - FeatureCollection featureCollection = new FeatureCollection(); - - if (omg instanceof OMGraphicList) { - Map properties = convert(omg.getAttributes()); - featureCollection.setProperties(properties); - } - convert(omg, featureCollection); - - return featureCollection; - } - - /** - * Used to convert the OMGraphics attribute table to the properties JSON - * wants. - * - * @param attributes Map<Object, Object> - * @return Map<String, Object> - */ - public static Map convert(Map attributes) { - Map ret = new HashMap(); - for (Object key : attributes.keySet()) { - ret.put(key.toString(), attributes.get(key)); - } - return ret; - } - - /** - * Method to call if you have an OMGraphic/OMGraphicList and want to add - * contents to a particular FeatureCollection as GeoJSON. - * - * @param omg OMGraphic to convert. - * @param featureCollection the collection to add new Features to. - */ - public static void convert(OMGraphic omg, FeatureCollection featureCollection) { - - if (omg instanceof OMAreaList) { - // Is a polygon with interior rings - } else if (omg instanceof OMGraphicList) { - OMGraphicList omgl = (OMGraphicList) omg; - if (omgl.isVague() && omgl.size() > 0) { - OMGraphic vomg = omgl.get(0); - if (vomg instanceof OMPoly) { - if (((OMPoly) vomg).isPolygon()) { - featureCollection.add(new MultiPolygon(omgl), omgl); - } else { - featureCollection.add(new MultiLineString(omgl), omgl); - } - } else if (vomg instanceof OMLine) { - featureCollection.add(new MultiLineString(omgl), omgl); - } else if (vomg instanceof OMPoint) { - featureCollection.add(new MultiPoint(omgl), omgl); - } - - } else { - // Each OMGraphic needs to be made into a Feature and added to - // main list. - for (OMGraphic omg1 : (OMGraphicList) omgl) { - convert(omg1, featureCollection); - } - } - } else { - // Create the Feature from the OMGraphic and add it to the - // collection - if (omg instanceof OMPoly) { - if (((OMPoly) omg).isPolygon()) { - featureCollection.add(new Polygon((OMPoly) omg), omg); - } else { - featureCollection.add(new LineString((OMPoly) omg), omg); - } - } else if (omg instanceof OMPoint) { - featureCollection.add(new Point((OMPoint) omg), omg); - } else if (omg instanceof OMLine) { - featureCollection.add(new LineString((OMLine) omg), omg); - } else if (omg instanceof OMRangeRings) { - - } else if (omg instanceof OMCircle) { - - } else if (omg instanceof OMRect) { - - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Point.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Point.java deleted file mode 100755 index cf88deb34..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Point.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoint; - -public class Point extends GeoJsonObject { - - private LngLatAlt coordinates; - - public Point() { - } - - public Point(LngLatAlt coordinates) { - this.coordinates = coordinates; - } - - public Point(double longitude, double latitude) { - coordinates = new LngLatAlt(longitude, latitude); - } - - public Point(double longitude, double latitude, double altitude) { - coordinates = new LngLatAlt(longitude, latitude, altitude); - } - - public Point(OMPoint omPoint) { - this(omPoint.getLon(), omPoint.getLat()); - } - - public LngLatAlt getCoordinates() { - return coordinates; - } - - public void setCoordinates(LngLatAlt coordinates) { - this.coordinates = coordinates; - } - - public OMGraphic convert() { - double lat = coordinates.getLatitude(); - double lon = coordinates.getLongitude(); - OMPoint point = new OMPoint(lat, lon); - point.getAttributes().putAll(getProperties()); - return point; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Polygon.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Polygon.java deleted file mode 100755 index 79bb610ac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/Polygon.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson; - -import java.util.Arrays; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class Polygon extends Geometry> { - - public Polygon() { - } - - public Polygon(List polygon) { - add(polygon); - } - - public Polygon(LngLatAlt... polygon) { - add(Arrays.asList(polygon)); - } - - public Polygon(OMPoly poly) { - setExteriorRing(OMGeoJSONUtil.convertToJSON(poly.getRawllpts(), true)); - } - - public void setExteriorRing(List points) { - coordinates.add(0, points); - } - - @JsonIgnore - public List getExteriorRing() { - assertExteriorRing(); - return coordinates.get(0); - } - - @JsonIgnore - public List> getInteriorRings() { - assertExteriorRing(); - return coordinates.subList(1, coordinates.size()); - } - - public List getInteriorRing(int index) { - assertExteriorRing(); - return coordinates.get(1 + index); - } - - public void addInteriorRing(List points) { - assertExteriorRing(); - coordinates.add(points); - } - - public void addInteriorRing(LngLatAlt... points) { - assertExteriorRing(); - coordinates.add(Arrays.asList(points)); - } - - private void assertExteriorRing() { - if (coordinates.isEmpty()) - throw new RuntimeException("No exterior ring definied"); - } - - public OMGraphic convert() { - List outer = getExteriorRing(); - List> inners = getInteriorRings(); - - OMPoly outerPoly = new OMPoly(OMGeoJSONUtil.convertToRadians(outer), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - - if (!(inners == null || inners.isEmpty())) { - OMAreaList areaList = new OMAreaList(); - - areaList.add(outerPoly); - - for (List polyPnts : inners) { - areaList.add(new OMPoly(OMGeoJSONUtil.convertToRadians(polyPnts), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE)); - } - areaList.getAttributes().putAll(getProperties()); - return areaList; - } - outerPoly.getAttributes().putAll(getProperties()); - return outerPoly; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltDeserializer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltDeserializer.java deleted file mode 100755 index 1fb26092c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltDeserializer.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson.jackson; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.geojson.LngLatAlt; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; - -public class LngLatAltDeserializer extends JsonDeserializer { - - @Override - public LngLatAlt deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { - if (jp.isExpectedStartArrayToken()) { - return deserializeArray(jp, ctxt); - } - throw ctxt.mappingException(LngLatAlt.class); - } - - protected LngLatAlt deserializeArray(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { - LngLatAlt node = new LngLatAlt(); - node.setLongitude(extractDouble(jp, ctxt, false)); - node.setLatitude(extractDouble(jp, ctxt, false)); - node.setAltitude(extractDouble(jp, ctxt, true)); - if (jp.hasCurrentToken() && jp.getCurrentToken() != JsonToken.END_ARRAY) - jp.nextToken(); - return node; - } - - private double extractDouble(JsonParser jp, DeserializationContext ctxt, boolean optional) - throws JsonParseException, IOException { - JsonToken token = jp.nextToken(); - if (token == null) { - if (optional) - return Double.NaN; - else - throw ctxt.mappingException("Unexpected end-of-input when binding data into LngLatAlt"); - } - else { - switch (token) { - case END_ARRAY: - if (optional) - return Double.NaN; - else - throw ctxt.mappingException("Unexpected end-of-input when binding data into LngLatAlt"); - case VALUE_NUMBER_FLOAT: - return jp.getDoubleValue(); - case VALUE_NUMBER_INT: - return jp.getLongValue(); - default: - throw ctxt.mappingException("Unexpected token (" + token.name() - + ") when binding data into LngLatAlt "); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltSerializer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltSerializer.java deleted file mode 100755 index b1a595a58..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/jackson/LngLatAltSerializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.bbn.openmap.dataAccess.geojson.jackson; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.geojson.LngLatAlt; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -public class LngLatAltSerializer extends JsonSerializer { - - @Override - public void serialize(LngLatAlt value, JsonGenerator jgen, SerializerProvider provider) throws IOException, - JsonProcessingException { - jgen.writeStartArray(); - jgen.writeNumber(value.getLongitude()); - jgen.writeNumber(value.getLatitude()); - if (value.hasAltitude()) - jgen.writeNumber(value.getAltitude()); - jgen.writeEndArray(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/package.html deleted file mode 100644 index 30b445098..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/geojson/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - -The geojson layer package contains components used to display geojson files in OpenMap. The -main geojson decoding files are derivative works frome the GeoJSON Jackson project available at: -https://github.com/opendatalab-de/geojson-jackson. -

-The GeoJSONObject and subclasses from that package have been modified to include a convert() method that -makes it easier to convert GeoJSONObjects to OMGraphics. There was also a modification to GeoJSONObject -to make 'metadata' tags optional. -

-The GeoJSON jackson classes have also been repackaged into the com.bbn.openmap.layer.geojson package for -organizational purposes. - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrImageTile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrImageTile.java deleted file mode 100644 index f09c3403b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrImageTile.java +++ /dev/null @@ -1,61 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ErrImageTile.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:35 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import com.bbn.openmap.proj.Projection; - -/** - * An ErrImageTile is an ImageTile that can't be displayed due to projection - * incompatibilities or some other problem. It's a space-holder that can be - * queried for information about the file and also provide a GUI-component-like - * list object that can be used to represent a file that was decoded but not - * able to be displayed for some reason. - * - * @author dietrick - */ -public class ErrImageTile extends ImageTile { - - protected String problemMessage; - - public ErrImageTile(String problemMessage) { - this.problemMessage = problemMessage; - } - - public String getProblemMessage() { - return problemMessage; - } - - public void setProblemMessage(String problemMessage) { - this.problemMessage = problemMessage; - } - - public boolean isVisible() { - return false; - } - - public boolean generate(Projection proj) { - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrWorldFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrWorldFile.java deleted file mode 100644 index 9e5a55fda..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ErrWorldFile.java +++ /dev/null @@ -1,48 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ErrWorldFile.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:36 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -/** - * An ErrWorldFile is a World File that can't be handled for some reason. This - * class is used as a placeholder to let an ImageReader know there is some - * problem figuring out where or how to locate the associated image file. - * - * @author dietrick - */ -public class ErrWorldFile extends WorldFile { - protected String problemMessage; - - public ErrWorldFile(String problemMessage) { - this.problemMessage = problemMessage; - } - - public String getProblemMessage() { - return problemMessage; - } - - public void setProblemMessage(String problemMessage) { - this.problemMessage = problemMessage; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReader.java deleted file mode 100644 index e888e766f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReader.java +++ /dev/null @@ -1,53 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ImageReader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:35 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.awt.image.BufferedImage; - -public interface ImageReader { - /** - * Should be called by the the object managing the ImageTiles. - * - * @return ImageTile, null if there is a problem. - */ - ImageTile getImageTile(); - - /** - * Should be called by the object managing the ImageTiles. - * - * @param cache The CacheHandler that should be used by the ImageTile for - * dynamic image loading. - * @return ImageTile, null if there is a problem. - */ - ImageTile getImageTile(ImageTile.Cache cache); - - /** - * Will be called by the Image cache by the ImageTile to replenish the image - * data as it is needed when the ImageTile is on the map. - * - * @return BufferedImage of image. - */ - BufferedImage getBufferedImage(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReaderLoader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReaderLoader.java deleted file mode 100644 index 88b3ad414..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageReaderLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ImageReaderLoader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:34 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.net.URL; - -/** - * An ImageReaderLoader is an object used to determine if a particular - * ImageReader can be used for a particular image file. It can also provide the - * ImageReader loaded with the contents of that file. - * - * @author dietrick - */ -public interface ImageReaderLoader { - /** - * @param fileURL a URL for an image file. - * @return an ImageReader loaded with the image file contents, or null if - * the image can't be handled. - */ - ImageReader getImageReader(URL fileURL); - - /** - * A query method used to ask the ImageReaderLoader if an image can be - * handled by the ImageReader it represents. - * - * @param fileName path to image file. - * @return true if yes. - */ - boolean isLoadable(String fileName); - - /** - * A query method used to ask the ImageReaderLoader if an image can be - * handled by the ImageReader it represents. - * - * @param fileURL URL of image file. - * @return true if yes. - */ - boolean isLoadable(URL fileURL); -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageTile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageTile.java deleted file mode 100644 index ab5720b46..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/ImageTile.java +++ /dev/null @@ -1,262 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/image/ImageTile.java,v $ -// $RCSfile: ImageTile.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.awt.Color; -import java.awt.Image; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.Serializable; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * This is an extension to OMRaster that automatically scales itself to match - * the current projection. It is only lat/lon based, and takes the coordinates - * of the upper left and lower right corners of the image. It does straight - * scaling - it does not force the image projection to match the map projection! - * So, your mileage may vary - you have to understand the projection of the - * image, and know how it fits the projection type of the map. Of course, at - * larger scales, it might not matter so much. - * - * This class was inspired by, and created from parts of the ImageLayer - * submission from Adrian Lumsden@sss, on 25-Jan-2002. Used the scaling and - * trimming code from that submission. That code was also developed with - * assistance from Steve McDonald at SiliconSpaceships.com. - * - * @see com.bbn.openmap.omGraphics.OMRaster - * @see com.bbn.openmap.omGraphics.OMRasterObject - */ -public class ImageTile extends OMScalingRaster implements Serializable { - - protected ImageReader imageDecoder; - protected CacheHandler cache; - - /** - * Construct a blank OMRaster, to be filled in with set calls. Make sure you - * set either a source image or ImageDecoder that knows how to get the - * image. - */ - public ImageTile() { - super(); - } - - // //////////////////////////////////// IMAGEICON - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param imageDecoder ImageReader for Image. - * @param cache CacheHandler holding cached images. - */ - public ImageTile(double ullat, double ullon, double lrlat, double lrlon, - ImageReader imageDecoder, CacheHandler cache) { - super(); - setRenderType(OMGraphic.RENDERTYPE_LATLON); - setColorModel(COLORMODEL_IMAGEICON); - - lat = ullat; - lon = ullon; - lat2 = lrlat; - lon2 = lrlon; - - this.imageDecoder = imageDecoder; - this.cache = cache; - } - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param image BufferedImage used for the image. - */ - public ImageTile(double ullat, double ullon, double lrlat, double lrlon, BufferedImage image) { - super(ullat, ullon, lrlat, lrlon, image); - } - - protected Boolean realSelection = null; - public static Color DEFAULT_NON_CLEAR_FILL_PAINT = new Color(200, 200, 200, 100); - - public void setSelected(boolean setting) { - if (realSelection != null) { - realSelection = Boolean.valueOf(setting); - - if (setting) { - displayPaint = getSelectPaint(); - } else { - displayPaint = getLinePaint(); - } - - } else { - super.setSelected(setting); - } - } - - /** - * Checking to see of the image needs to be updated for the projection - * parameters, namely scale. - * - * @param proj current projection - * @return true if the image scale, as projected, isn't being shrunk down - * too much, and the image should be displayed. - */ - protected boolean shouldFetchForProjection(Projection proj) { - Point2D anchor1 = new Point2D.Double(lat, lon); - Point2D anchor2 = new Point2D.Double(lat2, lon2); - - float imageScale = com.bbn.openmap.proj.ProjMath.getScale(anchor1, anchor2, proj); - - float scaleRatio = Cache.DEFAULT_SCALE_RATIO; // Something somewhat - // reasonable, a default. - if (cache instanceof Cache) { - scaleRatio = ((Cache) cache).getCutoffScaleRatio(); - } - - return (imageScale * scaleRatio) <= proj.getScale(); - } - - /** - * Called from within generate. - * - * @param proj current projection. - * @return false if the rest of generate() should be skipped, if the image - * doesn't need to be formed for the current projection. - */ - protected boolean updateImageForProjection(Projection proj) { - // point1 and point2 are not yet set for a changed projection - position(proj); - - if (imageDecoder != null) { - if (!isOnMap(proj)) { - setNeedToRegenerate(true); - return false; - } - - // Check the scale against the cache to see if we should do - // anything. - if (shouldFetchForProjection(proj)) { - - if (realSelection == null) { - if (getFillPaint() == com.bbn.openmap.omGraphics.OMColor.clear) { - setFillPaint(DEFAULT_NON_CLEAR_FILL_PAINT); - } - realSelection = Boolean.valueOf(selected); - } - selected = true; - setShape(); - setNeedToRegenerate(false); - return false; - } else if (realSelection != null) { - if (getFillPaint() == DEFAULT_NON_CLEAR_FILL_PAINT) { - setFillPaint(com.bbn.openmap.omGraphics.OMColor.clear); - } - setFillPaint(com.bbn.openmap.omGraphics.OMColor.clear); - selected = realSelection.booleanValue(); - realSelection = null; - } - - if (bitmap == null) { - if (cache != null) { - setImage((Image) cache.get(imageDecoder)); - } else { - setImage(imageDecoder.getBufferedImage()); - } - } - } - return true; - } - - public boolean regenerate(Projection p) { - return generate(p); - } - - public ImageReader getImageDecoder() { - return imageDecoder; - } - - public void setImageDecoder(ImageReader imageDecoder) { - this.imageDecoder = imageDecoder; - } - - public static class Cache extends CacheHandler { - - public final static float DEFAULT_SCALE_RATIO = 5f; - - protected float cutoffScaleRatio = DEFAULT_SCALE_RATIO; - - public Cache() { - super(10); - } - - public Cache(int maxSize) { - super(maxSize); - } - - public void setCutoffScaleRatio(float scale) { - cutoffScaleRatio = scale; - } - - public float getCutoffScaleRatio() { - return cutoffScaleRatio; - } - - /** - * Returns a CacheObject that will be loaded into the cache. The key - * should be an ImageDecoder, and the object in the cache object will be - * the BufferedImage that will get inserted into the ImageTile. - */ - public CacheObject load(Object key) { - - try { - if (key instanceof ImageReader) { - // URL imageURL = PropUtils.getResourceOrFileOrURL(key); - // - // FileCacheImageInputStream fciis = new - // FileCacheImageInputStream(imageURL.openStream(), null); - // BufferedImage fileImage = ImageIO.read(fciis); - - BufferedImage fileImage = ((ImageReader) key).getBufferedImage(); - - return new CacheObject(key, fileImage); - } - - } catch (Exception e) { - } // Catch errors - - return null; - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFile.java deleted file mode 100644 index 86d45d058..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFile.java +++ /dev/null @@ -1,274 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: WorldFile.java,v $ -//$Revision: 1.3 $ -//$Date: 2007/01/22 16:39:14 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A world file is a small text file that describes the geographic location of - * an image on a map. It looks like this: - * - *

- *            20.154 <the dimension of a pixel in map units in the x direction>
- *            0.000 <rotation term for row>
- *            0.000 <rotation term for column>
- *            -20.154 <the dimension of a pixel in map units in the y direction>
- *            424178 <the x coordinate of the center of pixel 1,1 (upper-left pixel)>
- *            4313415 <the y coordinate of the center of pixel 1,1 (upper-left pixel)>
- * 
- * - * The naming convention of the world file is that it should have the same name - * as the file it represents, with a modified extension. The extension should be - * the extension of the image file with a w attached to it, or the first and - * third letters of the image file extension with a w appended to it. It can - * also have a .wld extension. - * - * @author dietrick - */ -public class WorldFile { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.image.WorldFile"); - - /** - * The dimension of a pixel in map units in the x direction. - */ - protected double xDim; - /** - * The dimension of a pixel in map units in the y direction. - */ - protected double yDim; - /** - * The rotation term for row. - */ - protected double rowRot; - /** - * The rotation term for column. - */ - protected double colRot; - /** - * The x coordinate of the center of pixel 1,1 (upper-left pixel). - */ - protected double x; - /** - * The y coordinate of the center of pixel 1,1 (upper-left pixel). - */ - protected double y; - - protected WorldFile() { - // For subclasses. - } - - public WorldFile(double xDim, double yDim, double rowRot, double colRot, double x, double y) { - this.xDim = xDim; - this.yDim = yDim; - this.rowRot = rowRot; - this.colRot =colRot; - this.x = x; - this.y = y; - } - - public WorldFile(URL fileURL) throws MalformedURLException, IOException { - read(fileURL.openStream()); - } - - public WorldFile(InputStream is) throws MalformedURLException, IOException { - read(is); - } - - public void read(InputStream is) throws IOException { - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - - xDim = Double.parseDouble(br.readLine()); - rowRot = Double.parseDouble(br.readLine()); - colRot = Double.parseDouble(br.readLine()); - yDim = Double.parseDouble(br.readLine()); - x = Double.parseDouble(br.readLine()); - y = Double.parseDouble(br.readLine()); - - logger.fine(this.toString()); - } - - public void write(OutputStream os) throws IOException { - OutputStreamWriter osr = new OutputStreamWriter(os); - osr.write(Double.toString(xDim) + "\n"); - osr.write(Double.toString(rowRot) + "\n"); - osr.write(Double.toString(colRot) + "\n"); - osr.write(Double.toString(yDim) + "\n"); - osr.write(Double.toString(x) + "\n"); - osr.write(Double.toString(y) + "\n"); - osr.close(); - } - - public String toString() { - return "WorldFile[x(" + x + "), y(" + y + "), xDim(" + xDim - + "), yDim(" + yDim + "), colRot(" + colRot + "), rowRot(" - + rowRot + ")]"; - } - - /** - * Given a path to a image file, discover the world file which should be - * next to it. - * - * @param imageFileURL the path to the image file, not the world file. - * @return WorldFile object for the image. - */ - public static WorldFile get(URL imageFileURL) { - WorldFile wf = null; - try { - String startingString = imageFileURL.toString(); - - int extensionIndex = startingString.lastIndexOf('.'); - String worldFileNameBase = startingString; - String extension = null; - InputStream is = null; - - if (extensionIndex != -1) { - - extension = startingString.substring(extensionIndex); - worldFileNameBase = startingString.substring(0, extensionIndex); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("base name for image: " + worldFileNameBase); - logger.fine("image extension: " + extension); - } - - // Try adding w to extension and seeing if that file is there. - is = checkValidityAndGetStream(worldFileNameBase + extension - + "w"); - - if (is == null && extension.length() >= 4) { - is = checkValidityAndGetStream(worldFileNameBase + "." - + extension.charAt(1) + extension.charAt(3) + "w"); - } - - } - - if (is == null) { - // Try world file extension if nothing else has worked, or if - // their isn't an extension on the image file. - extension = ".wld"; - is = checkValidityAndGetStream(worldFileNameBase + extension); - } - - if (is != null) { - wf = new WorldFile(is); - - // Check for coordinates of pixel to see if they make sense. If - // they are greater than 180, then they are probably meters, and - // we can't handle them right now. - - double x = wf.getX(); - double y = wf.getY(); - - if (x < -180 || x > 180 || y > 90 || y < -90) { - logger.warning("Looks like an unsupported projection: " - + wf.toString()); - wf = new ErrWorldFile("World File (" + worldFileNameBase - + extension - + ") doesn't contain decimal degree coordinates"); - } - } - - } catch (MalformedURLException murle) { - - } catch (IOException ioe) { - - } - - return wf; - } - - protected static InputStream checkValidityAndGetStream(String wfURLString) { - try { - logger.fine("checking for world file: " + wfURLString); - URL wfURL = new URL(wfURLString); - return wfURL.openStream(); - } catch (MalformedURLException murle) { - logger.fine("MalformedURLException for " + wfURLString); - } catch (IOException ioe) { - logger.fine("IOException for " + wfURLString); - } - return null; - - } - - public double getColRot() { - return colRot; - } - - public void setColRot(double colRot) { - this.colRot = colRot; - } - - public double getRowRot() { - return rowRot; - } - - public void setRowRot(double rowRot) { - this.rowRot = rowRot; - } - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getXDim() { - return xDim; - } - - public void setXDim(double dim) { - xDim = dim; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public double getYDim() { - return yDim; - } - - public void setYDim(double dim) { - yDim = dim; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReader.java deleted file mode 100644 index 8f91ad9c6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReader.java +++ /dev/null @@ -1,183 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: WorldFileImageReader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:34 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.imageio.ImageIO; -import javax.imageio.stream.FileCacheImageInputStream; - -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -public class WorldFileImageReader implements ImageReader { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.image.WorldFileImageReader"); - protected WorldFile worldFile; - protected URL fileURL; - - public WorldFileImageReader(URL fileURL) throws MalformedURLException, - IOException { - this.fileURL = fileURL; - worldFile = WorldFile.get(fileURL); - } - - public BufferedImage getBufferedImage() { - try { - BufferedImage bi = getJAIImage(fileURL); - if (bi == null && worldFile != null) { - // This means that the world file was found, and that the image - // wasn't loaded. The most likely problem that causes this - // situation is that JAI isn't installed on the system. So, - // let's try using ImageIO. - bi = getImageIOImage(fileURL); - } - - return bi; - } catch (IOException ioe) { - logger.info("problem reading " + fileURL + ", IOException"); - ioe.printStackTrace(); - } - return null; - } - - public static BufferedImage getImageIOImage(URL fileURL) throws IOException { - FileCacheImageInputStream fciis = new FileCacheImageInputStream(fileURL.openStream(), null); - BufferedImage fileImage = ImageIO.read(fciis); - return fileImage; - } - - public static BufferedImage getJAIImage(URL fileURL) throws IOException { - return BufferedImageHelper.getJAIBufferedImage("url", fileURL); - } - - public ImageTile getImageTile(ImageTile.Cache cache) { - try { - if (worldFile instanceof ErrWorldFile) { - return new ErrImageTile(((ErrWorldFile) worldFile).getProblemMessage()); - } else if (worldFile != null) { - BufferedImage bi = getBufferedImage(); - if (bi != null) { - - double ulat = worldFile.getY(); - double llon = worldFile.getX(); - double llat = ulat + worldFile.getYDim() * bi.getHeight(); - double rlon = llon + worldFile.getXDim() * bi.getWidth(); - - if (logger.isLoggable(Level.FINE)) { - logger.info("Image should be at: " + ulat + ", " + llon - + " - to - " + llat + ", " + rlon); - } - - return new ImageTile((float) ulat, (float) llon, (float) llat, (float) rlon, this, cache); - } - } else { - logger.info("World file for " + fileURL + " can't be found."); - } - - } catch (NullPointerException npe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem creating image (NullPointerException) from " - + fileURL); - npe.printStackTrace(); - } - } - - return null; - } - - public ImageTile getImageTile() { - return getImageTile(null); - } - - public static void main(String[] args) { - - if (args.length < 1) { - System.out.println("WorldFileImageReader: Need a path/filename"); - System.exit(0); - } - - logger.info("WorldFileImageReader: " + args[0]); - - String filePath = null; - - if (args.length > 0) { - filePath = args[0]; - } - - if (filePath != null) { - try { - URL fileURL = PropUtils.getResourceOrFileOrURL(filePath); - if (fileURL != null) { - - WorldFileImageReader wfir = new WorldFileImageReader(fileURL); - - BufferedImage bi = wfir.getBufferedImage(); - - CADRG crg = new CADRG(new LatLonPoint.Double(0, 0), 1500000, 600, 600); - - final OMRaster omsr = new OMRaster(0, 0, bi); - omsr.generate(crg); - - java.awt.Frame window = new java.awt.Frame(filePath) { - public void paint(java.awt.Graphics g) { - if (omsr != null) { - omsr.render(g); - } - } - }; - - window.addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent e) { - // need a shutdown event to notify other gui beans - // and - // then exit. - System.exit(0); - } - }); - - window.setSize(omsr.getWidth(), omsr.getHeight()); - window.setVisible(true); - window.repaint(); - - } - - } catch (MalformedURLException murle) { - - } catch (IOException ioe) { - - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReaderLoader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReaderLoader.java deleted file mode 100644 index 9ca3306b0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/WorldFileImageReaderLoader.java +++ /dev/null @@ -1,69 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: WorldFileImageReaderLoader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:35 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -/** - * An ImageReaderLoader that answers queries on behalf of a - * WorldFileImageReader. Will answer yes for image files with .tif, .png, .jpg, - * .jpeg and .gif extensions. - * - * @author dietrick - */ -public class WorldFileImageReaderLoader - implements ImageReaderLoader { - public WorldFileImageReaderLoader() { - } - - public ImageReader getImageReader(URL fileURL) { - WorldFileImageReader wfid = null; - try { - wfid = new WorldFileImageReader(fileURL); - } catch (MalformedURLException murle) { - - } catch (IOException ioe) { - - } - return wfid; - } - - public boolean isLoadable(String fileName) { - if (fileName != null) { - fileName = fileName.toLowerCase(); - return (fileName.endsWith(".tif") || fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".jpg") - || fileName.endsWith(".gif") || fileName.endsWith(".bmp")); - } - - return false; - } - - public boolean isLoadable(URL fileURL) { - return isLoadable(fileURL.getPath()); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFFile.java deleted file mode 100644 index 16547f12c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFFile.java +++ /dev/null @@ -1,612 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoTIFFFile.java,v $ -//$Revision: 1.3 $ -//$Date: 2007/01/22 15:47:37 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image.geotiff; - -import java.awt.image.BufferedImage; -import java.awt.image.RenderedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Hashtable; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.geotiff.image.KeyRegistry; -import org.geotiff.image.jai.GeoTIFFDescriptor; -import org.geotiff.image.jai.GeoTIFFDirectory; -import org.geotiff.image.jai.GeoTIFFFactory; -import org.libtiff.jai.codec.XTIFFDecodeParam; -import org.libtiff.jai.codec.XTIFFField; -import org.libtiff.jai.codecimpl.XTIFFImageDecoder; - -import com.bbn.openmap.dataAccess.image.ImageTile; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; -import com.sun.media.jai.codec.SeekableStream; - -/** - * GeoTIFFFile is the main object for loading a GeoTIFF image file. Relies on - * JAI being installed on the machine, because it needs the TIFF capabilities of - * that package. You can ask for the BufferedImage representing the image in the - * file, or ask for specific tag information. The GeoTIFFModelFactory can be - * used to create specific geo-referenced ImageTile objects for display in - * OpenMap. - * - * @author dietrick - */ -public class GeoTIFFFile { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFFile"); - - protected GeoTIFFDirectory gtfDirectory; - protected XTIFFField[] geoKeys; - protected URL fileURL; - - public GeoTIFFFile(String filePath) - throws MalformedURLException, IOException, IllegalArgumentException { - this(PropUtils.getResourceOrFileOrURL(filePath)); - } - - public GeoTIFFFile(URL fileURL) - throws MalformedURLException, IOException, IllegalArgumentException { - if (fileURL == null) { - throw new MalformedURLException("Null file provided as URL"); - } - init(fileURL); - } - - public void init(URL fileURL) - throws IOException, IllegalArgumentException { - this.fileURL = fileURL; - SeekableStream ss = SeekableStream.wrapInputStream(fileURL.openStream(), true); - GeoTIFFDescriptor.register(); - GeoTIFFFactory gtFactory = new GeoTIFFFactory(); - gtfDirectory = (GeoTIFFDirectory) gtFactory.createDirectory(ss, 0); - geoKeys = gtfDirectory.getGeoKeys(); - ss.close(); - } - - /** - * Uses the XTIFF Image Decoder to decode as rendered image, creating a new - * Buffered Image. This is expensive, so if you need the image again, keep - * it around. Unless it's really huge, I guess. - * - * @return BufferedImage from GeoTIFF - * @throws IOException if the file URL is null, or if there's a problem - * reading the file. - */ - public BufferedImage getBufferedImage() - throws IOException { - if (fileURL == null) { - throw new IOException("Image Decoder not created for retrieving image, need to init() GeoTIFFFile."); - } - - SeekableStream ss = SeekableStream.wrapInputStream(fileURL.openStream(), true); - XTIFFImageDecoder xtffImageDecoder = new XTIFFImageDecoder(ss, new XTIFFDecodeParam()); - RenderedImage ri = xtffImageDecoder.decodeAsRenderedImage(); - BufferedImage bi = new BufferedImage(ri.getColorModel(), ri.copyData(null), false, new Hashtable()); - ss.close(); - return bi; - } - - /** - * Helper function designed to make it easier to get the XTIFF field for a - * given tag number. The easiest way to use this is to ask the KeyRegistry - * for the code of a tag from a specific map, i.e. - * - *
-     * int tagNumber = KeyRegistry.getCode(KeyRegistry.GEOKEY, "GTModelTypeGeoKey");
-     * 
-     * 
- * - * Once you have the XTIFFField, you can figure out what type it is, and - * then ask for its values as that type. - * - * @param tagNumber - * @return XTIFFField, or null if not found in file. - */ - public XTIFFField getFieldWithTag(int tagNumber) { - XTIFFField ret = null; - XTIFFField[] gtfFields = gtfDirectory.getFields(); - for (int i = 0; i < gtfFields.length; i++) { - XTIFFField xtff = gtfFields[i]; - int tag = xtff.getTag(); - if (tag == tagNumber) { - ret = xtff; - break; - } - } - return ret; - } - - /** - * Very handy class from the file. Contains all the XTIFFFields with the tag - * information. - * - * @return GeoTIFFDirectory that holds GeoTIFF fields. - */ - public GeoTIFFDirectory getGtfDirectory() { - return gtfDirectory; - } - - /** - * Ask specifically for the array of XTIFFFields pertaining to - * georeferencing. - * - * @return XTIFFField array for keys. - */ - public XTIFFField[] getGeoKeys() { - return geoKeys; - } - - /** - * Searches for tag in geo keys. Doesn't go through all of the tags in the - * file like the getFieldWithTag function, just the fields that have been - * pre-fetched as geotags. - * - * @return XTIFFField, or null if not found in file. - */ - protected XTIFFField getGeoFieldForCode(int code) { - if (geoKeys != null) { - for (int i = 0; i < geoKeys.length; i++) { - XTIFFField f = geoKeys[i]; - if (f.getTag() == code) { - return f; - } - } - } - return null; - } - - /** - * Pixels derived from scanners or other optical devices represent areas, - * and most commonly will use the RasterPixelIsArea coordinate system. Pixel - * data such as digital elevation models represent points, and will probably - * use RasterPixelIsPoint coordinates. - * - * @return RasterPixelIsArea = 1, RasterPixelIsPoint = 2 - */ - public int getRasterType() { - return getGeoKeyIntValue(KeyRegistry.getCode(KeyRegistry.GEOKEY, "GTRasterTypeGeoKey")); - } - - /** - * Determine which class of model space coordinates are most natural for - * this dataset:Geographic, Geocentric, or Projected Coordinate System. - * Usually this will be PCS. - * - * @return ModelTypeProjected = 1 (Projection Coordinate System) - * ModelTypeGeographic = 2 Geographic latitude-longitude System) - * ModelTypeGeocentric = 3 (Geocentric (X,Y,Z) Coordinate System) - */ - public int getModelType() { - return getGeoKeyIntValue(KeyRegistry.getCode(KeyRegistry.GEOKEY, "GTModelTypeGeoKey")); - } - - /** - *
-     *                     Here is a summary of the index ranges for the various coding systems used by EPSG in their tables. A copy of this index may be acquired at the FTP sites mentioned in the references in section 5. The "value" table entries below describe how values from one table are related to codes from another table.
-     *                    
-     *                         Summary
-     *                         --------
-     *                         Entity                        digit   Range
-     *                         ----------------------------  ------- -------------- 
-     *                         Prime Meridian                8       8000 thru 8999
-     *                         Ellipsoid                     7       7000 thru 7999
-     *                         Geodetic Datum                6       6000 thru 6999
-     *                         Vertical datum                5       5000 thru 5999
-     *                         Geographic Coordinate System  4       4000 thru 4999
-     *                         Projected Coordinate Systems  2 or 3  20000 thru 32760
-     *                         Map Projection                1       10000 - 19999
-     *                         Geodetic Datum Codes
-     *                         --------------------
-     *                         Datum Type                 Value     Range            Currently Defined
-     *                         -------------------------- --------- --------------   -----------------
-     *                         Unspecified Geodetic Datum [EC-1000] 6000 thru 6099   6001 thru 6035
-     *                         Geodetic Datum                       6100 thru 6321   6200 thru 6315
-     *                         WGS 72; WGS 72BE and WGS84           6322 thru 6327   6322 thru 6327
-     *                         Geodetic Datum (ancient)             6900 thru 6999   6901 thru 6902
-     *                         Note for Values: EC = corresponding Ellipsoid Code.
-     *                         Vertical Datum Codes
-     *                         --------------------
-     *                         Datum Type                 Value     Range            Currently Defined
-     *                         -------------------------- --------- --------------   -----------------     
-     *                         Ellipsoidal                [EC-1000] 5000 thru 5099   5001 thru 5035
-     *                         Orthometric                          5100 thru 5899   5101 thru 5106
-     *                         Note for Values: EC = corresponding Ellipsoid Code.
-     *                         Geographic Coordinate System Codes    
-     *                         ----------------------------------
-     *                         GCS Type                    Value      Range           Currently Defined
-     *                         -----------------------     ---------- --------------  -----------------        
-     *                         Unknown geodetic datum      [GDC-2000] 4000 thru 4099  4001 thru 4045
-     *                         Known datum (Greenwich)     [GDC-2000] 4100 thru 4321  4200 thru 4315
-     *                         WGS 72; WGS 72BE and WGS84             4322 thru 4327  4322 thru 4327
-     *                         Known datum (not Greenwich)            4800 thru 4899  4801 thru 4812
-     *                         Known datum (ancient)       [GDC-2000] 4900 thru 4999  4901 thru 4902
-     *                         Note for Values: GDC = corresponding Geodetic Datum Code
-     *                         Map Projection System Codes
-     *                         ---------------------------
-     *                         US State Plane  ( 10000-15999 )
-     *                         Format:     1sszz            
-     *                         where ss is USC&GS State code  01 thru 59  
-     *                         zz is (USC&GS zone code)      for NAD27 zones               
-     *                         zz is (USC&GS zone code + 30) for NAD83 zones
-     *                         
-     *                         Larger zoned systems ( 16000-17999 ) 
-     *                         System                            Format  zz Range
-     *                         --------------------------------  ------- -------
-     *                         UTM (North)                       160zz   01   60   
-     *                         UTM (South)                       161zz   01   60   
-     *                         zoned Universal Gauss-Kruger      162zz   04   32
-     *                         Universal Gauss-Kruger (unzoned)  163zz   04   3                  
-     *                         Australian Map Grid               174zz   48   58   
-     *                         Southern African STM              175zz   13   35 
-     *                         Smaller zoned systems  ( 18000-18999 ) 
-     *                         Format:  18ssz           
-     *                         where ss is sequential system number  01   18   
-     *                         z is zone code               
-     *                         
-     *                         Single zone projections ( 19900-19999 )
-     *                         Format:   199ss          
-     *                         where ss is sequential system number  00   25
-     *                         Projected Coordinate Systems
-     *                         ----------------------------      
-     *                         For PCS utilizing GeogCS with code in range 4201 through 4321 
-     *                         (i.e. geodetic datum code 6201 through 6319):
-     *                         As far as is possible the PCS code will be of the format 
-     *                         gggzz where ggg is (geodetic datum code -6000) and zz is zone.               
-     *                         
-     *                         For PCS utilizing GeogCS with code out of range 4201 through 4321
-     *                         (i.e.geodetic datum code 6201 through 6319):
-     *                         PCS code 20xxx where xxx is a sequential number               
-     *                         WGS72 / UTM North     322zz where zz is UTM zone number   32201   32260   
-     *                         WGS72 / UTM South     323zz where zz is UTM zone number   32301   32360
-     *                         WGS72BE / UTM North   324zz where zz is UTM zone number   32401   32460
-     *                         WGS72BE / UTM South   325zz where zz is UTM zone number   32501   32560
-     *                         WGS84 / UTM North     326zz where zz is UTM zone number   32601   32660
-     *                         WGS84 / UTM South     327zz where zz is UTM zone number   32701   32760
-     *                         US State Plane (NAD27)   267xx or 320xx where xx is a sequential number            
-     *                         US State Plane (NAD83)   269xx or 321xx where xx is a sequential number
-     * 
-     * 
- * - * @return type code for coordinate system - */ - public int getProjectedCSType() { - return getGeoKeyIntValue(KeyRegistry.getCode(KeyRegistry.GEOKEY, "ProjectedCSTypeGeoKey")); - } - - /** - * @return type code for geographic type - */ - public int getGeographicType() { - return getGeoKeyIntValue(KeyRegistry.getCode(KeyRegistry.GEOKEY, "GeographicTypeGeoKey")); - } - - /** - * Helper function for taking a code from the Geo KeyRegistry, and getting - * the field value as a single int. Should be called for codes that have - * only one int value, you should read the GeoTIFF spec to know what they - * are. - * - * @param codeFromKeyRegistry - * @return the code value, or -1 if not found. - */ - protected int getGeoKeyIntValue(int codeFromKeyRegistry) { - XTIFFField field = getGeoFieldForCode(codeFromKeyRegistry); - - if (field != null) { - int type = field.getType(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("field type is " + getStringOfType(type)); - } - if (type == XTIFFField.TIFF_SHORT) { - return field.getAsInt(0); - } - } - return -1; - } - - /** - * Helper function for taking a code from the TIFF spec, and getting the - * field value as a single int. Should be called for codes that have only - * one int value, you should read the TIFF spec to know what they are. - * - * @param tiffCode - * @return the code value, or -1 if not found. - */ - protected int getFieldIntValue(int tiffCode) { - XTIFFField field = getFieldWithTag(tiffCode); - - if (field != null) { - int type = field.getType(); - if (type == XTIFFField.TIFF_SHORT) { - return field.getAsInt(0); - } - } - return -1; - } - - /** - * Prints out the values of the XTIFF Fields provided to it. - * - * @param gtfFields You can get all of the XTIFFFields from the directory - * object, or ask this class for the geokeys. - */ - public void dumpTags(XTIFFField[] gtfFields) { - - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < gtfFields.length; i++) { - XTIFFField xtff = gtfFields[i]; - - int type = xtff.getType(); - int tag = xtff.getTag(); - buf.append("\n\tfield (").append(i).append(") - ").append(tag).append(" (") - .append(KeyRegistry.getKey(KeyRegistry.GEOKEY, tag)).append("): ["); - - switch (type) { - case XTIFFField.TIFF_ASCII: - String[] fieldStrings = xtff.getAsStrings(); - for (int j = 0; j < fieldStrings.length; j++) { - buf.append(fieldStrings[j]); - if (j < fieldStrings.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_DOUBLE: - double[] fieldDoubles = xtff.getAsDoubles(); - for (int j = 0; j < fieldDoubles.length; j++) { - buf.append(fieldDoubles[j]); - if (j < fieldDoubles.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_FLOAT: - double[] fieldFloats = xtff.getAsDoubles(); - for (int j = 0; j < fieldFloats.length; j++) { - buf.append(fieldFloats[j]); - if (j < fieldFloats.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_BYTE: - case XTIFFField.TIFF_SBYTE: - byte[] fieldBytes = xtff.getAsBytes(); - for (int j = 0; j < fieldBytes.length; j++) { - buf.append(fieldBytes[j]); - if (j < fieldBytes.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_SSHORT: - short[] fieldShorts = xtff.getAsShorts(); - for (int j = 0; j < fieldShorts.length; j++) { - buf.append(fieldShorts[j]); - if (j < fieldShorts.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_LONG: - case XTIFFField.TIFF_SHORT: - long[] fieldLongs = xtff.getAsLongs(); - for (int j = 0; j < fieldLongs.length; j++) { - buf.append(fieldLongs[j]); - if (j < fieldLongs.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_SLONG: - int[] fieldInts = xtff.getAsInts(); - for (int j = 0; j < fieldInts.length; j++) { - buf.append(fieldInts[j]); - if (j < fieldInts.length - 1) { - buf.append(", "); - } - } - buf.append("]"); - break; - case XTIFFField.TIFF_RATIONAL: - long[][] fieldRationals = xtff.getAsRationals(); - for (int k = 0; k < fieldRationals.length; k++) { - buf.append("\n\t"); - for (int j = 0; j < fieldRationals[0].length; j++) { - buf.append(fieldRationals[k][j]); - if (j < fieldRationals[k].length - 1) { - buf.append(", "); - } - } - } - buf.append("\n]"); - break; - case XTIFFField.TIFF_SRATIONAL: - int[][] fieldSRationals = xtff.getAsSRationals(); - for (int k = 0; k < fieldSRationals.length; k++) { - buf.append("\n\t"); - for (int j = 0; j < fieldSRationals[0].length; j++) { - buf.append(fieldSRationals[k][j]); - if (j < fieldSRationals[k].length - 1) { - buf.append(", "); - } - } - } - buf.append("\n]"); - break; - default: - // TIFF_UNDEFINED - buf.append("Can't handle ").append(type).append(" type.]"); - } - } - logger.info(buf.toString()); - } - - /** - * Helper function that coverts type codes to string representation. - * - * @param type code from XTIFFField. - * @return String interpretation of type code. - */ - public String getStringOfType(int type) { - switch (type) { - case XTIFFField.TIFF_ASCII: - return "ASCII"; - case XTIFFField.TIFF_DOUBLE: - return "double"; - case XTIFFField.TIFF_FLOAT: - return "float"; - case XTIFFField.TIFF_BYTE: - return "byte"; - case XTIFFField.TIFF_SBYTE: - return "sbyte"; - case XTIFFField.TIFF_SSHORT: - return "sshort"; - case XTIFFField.TIFF_LONG: - return "long"; - case XTIFFField.TIFF_SHORT: - return "short"; - case XTIFFField.TIFF_SLONG: - return "slong"; - case XTIFFField.TIFF_RATIONAL: - return "rational"; - case XTIFFField.TIFF_SRATIONAL: - return "srational"; - default: - return "unknown"; - } - } - - /** - * Uses a GeoTIFFModelFactory to create a georeferenced ImageTile image. - * Only handles 4326 projection right now (WGS84). - * - * @return ImageTile from file - * @throws IOException - */ - public ImageTile getImageTile() - throws IOException { - GeoTIFFModelFactory gtmf = new GeoTIFFModelFactory(this); - return gtmf.getImageTile(); - } - - public ImageTile getImageTile(GeoTIFFImageReader id, ImageTile.Cache cache) - throws IOException { - GeoTIFFModelFactory gtmf = new GeoTIFFModelFactory(this); - return gtmf.getImageTile(id, cache); - } - - public static void main(String[] args) { - - if (args.length < 1) { - System.out.println("GeoTIFFFile: Need a path/filename"); - System.exit(0); - } - - logger.info("GeoTIFFFile: " + args[0]); - - String filePath = null; - - if (args.length > 0) { - filePath = args[0]; - } - - if (filePath != null) { - try { - URL fileURL = PropUtils.getResourceOrFileOrURL(filePath); - if (fileURL != null) { - - GeoTIFFFile gtfFile = new GeoTIFFFile(fileURL); - BufferedImage bi = gtfFile.getBufferedImage(); - GeoTIFFDirectory gtfd = gtfFile.getGtfDirectory(); - double[] tiePoints = gtfd.getTiepoints(); - - System.out.println("------ Tie Point Values ------"); - for (int i = 0; i < tiePoints.length; i++) { - System.out.println(tiePoints[i]); - } - - double[] scaleMatrix = gtfd.getPixelScale(); - System.out.println("------ Pixel Scale Values ------"); - for (int i = 0; i < scaleMatrix.length; i++) { - System.out.println(scaleMatrix[i]); - } - - System.out.println("----- Geo Keys -------"); - gtfFile.dumpTags(gtfFile.getGeoKeys()); - System.out.println("------------"); - - System.out.println("----- All Keys -------"); - gtfFile.dumpTags(gtfFile.getGtfDirectory().getFields()); - System.out.println("------------"); - - CADRG crg = new CADRG(new LatLonPoint.Double(0f, 0f), 1500000, 600, 600); - - final OMRaster omsr = new OMRaster(0, 0, bi); - omsr.generate(crg); - - java.awt.Frame window = new java.awt.Frame(filePath) { - public void paint(java.awt.Graphics g) { - if (omsr != null) { - omsr.render(g); - } - } - }; - - window.addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent e) { - // need a shutdown event to notify other gui beans - // and - // then exit. - System.exit(0); - } - }); - - window.setSize(omsr.getWidth(), omsr.getHeight()); - window.setVisible(true); - window.repaint(); - - } - - } catch (MalformedURLException murle) { - - } catch (IOException ioe) { - - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReader.java deleted file mode 100644 index 6e003c4da..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReader.java +++ /dev/null @@ -1,102 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoTIFFImageReader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:37 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image.geotiff; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.image.ImageReader; -import com.bbn.openmap.dataAccess.image.ImageTile; - -/** - * An ImageReader that handles GeoTIFFs. - * - * @author dietrick - */ -public class GeoTIFFImageReader implements ImageReader { - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFImageReader"); - GeoTIFFFile gtfFile; - - public GeoTIFFImageReader(URL fileURL) { - try { - gtfFile = new GeoTIFFFile(fileURL); - } catch (IllegalArgumentException iae) { - logger.warning("Problem creating GeoTIFF from " + fileURL); - iae.printStackTrace(); - } catch (MalformedURLException murle) { - - } catch (IOException ioe) { - - } - } - - public ImageTile getImageTile(ImageTile.Cache cache) { - try { - return gtfFile.getImageTile(this, cache); - } catch (NullPointerException npe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem creating GeoTIFF image (NullPointerException) from " - + gtfFile); - npe.printStackTrace(); - } - } catch (IOException ioe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem creating GeoTIFF image (IOException) from " - + gtfFile); - ioe.printStackTrace(); - } - } - - return null; - } - - public ImageTile getImageTile() { - return getImageTile(null); - } - - public BufferedImage getBufferedImage() { - try { - return gtfFile.getBufferedImage(); - } catch (NullPointerException npe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem retrieving BufferedImage (NullPointerException) from " - + gtfFile); - npe.printStackTrace(); - } - } catch (IOException ioe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem retrieving BufferedImage (IOException) from " - + gtfFile); - ioe.printStackTrace(); - } - } - - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReaderLoader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReaderLoader.java deleted file mode 100644 index 9c366915c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFImageReaderLoader.java +++ /dev/null @@ -1,52 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoTIFFImageReaderLoader.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/01/22 15:47:36 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image.geotiff; - -import java.net.URL; - -import com.bbn.openmap.dataAccess.image.ImageReader; -import com.bbn.openmap.dataAccess.image.ImageReaderLoader; - -/** - * An ImageReaderLoader that looks for GeoTIFF images to pass to GeoTIFFImageReaders. - * - * @author dietrick - */ -public class GeoTIFFImageReaderLoader implements ImageReaderLoader { - public GeoTIFFImageReaderLoader() {} - - public ImageReader getImageReader(URL fileURL) { - return new GeoTIFFImageReader(fileURL); - } - - public boolean isLoadable(String fileName) { - return (fileName != null && fileName.toLowerCase().endsWith(".tif")); - } - - public boolean isLoadable(URL fileURL) { - return isLoadable(fileURL.getPath()); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFModelFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFModelFactory.java deleted file mode 100644 index cb8440008..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/image/geotiff/GeoTIFFModelFactory.java +++ /dev/null @@ -1,135 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoTIFFModelFactory.java,v $ -//$Revision: 1.3 $ -//$Date: 2007/01/22 15:47:36 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.image.geotiff; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.geotiff.image.KeyRegistry; -import org.geotiff.image.jai.GeoTIFFDirectory; - -import com.bbn.openmap.dataAccess.image.ErrImageTile; -import com.bbn.openmap.dataAccess.image.ImageTile; - -public class GeoTIFFModelFactory { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFModelFactory"); - - protected GeoTIFFFile gtfFile; - - public GeoTIFFModelFactory(GeoTIFFFile gtf) { - gtfFile = gtf; - } - - public ImageTile getImageTile() throws IOException { - return getImageTile(null, null); - } - - public ImageTile getImageTile(GeoTIFFImageReader gtid, - ImageTile.Cache cache) throws IOException { - - int modelType = gtfFile.getModelType(); - ImageTile ret = null; - String errorMessage = null; - /* - * ModelTypeProjected = 1 (Projection Coordinate System) - * ModelTypeGeographic = 2 Geographic latitude-longitude System) - * ModelTypeGeocentric = 3 (Geocentric (X,Y,Z) Coordinate System) - */ - int modelID = -1; - switch (modelType) { - case 1: - modelID = gtfFile.getProjectedCSType(); - errorMessage = "Projection Model type (" + modelID + ", " - + KeyRegistry.getKey(KeyRegistry.EPSG_PCS, modelID) - + ") not handled yet"; - - if (logger.isLoggable(Level.FINE)) { - logger.info(errorMessage); - } - - ret = new ErrImageTile("Image can't be positioned: " - + errorMessage); - break; - case 2: - case 3: - modelID = gtfFile.getGeographicType(); - if (logger.isLoggable(Level.FINE)) { - logger.info("GeoModel type (" + modelID + "): " - + KeyRegistry.getKey(KeyRegistry.EPSG_GCS, modelID)); - } - - switch (modelID) { - case 4326: - ret = get4326(gtid, cache); - break; - default: - errorMessage = "GeoModel type (" + modelID + ", " - + KeyRegistry.getKey(KeyRegistry.EPSG_GCS, modelID) - + ") not handled yet"; - logger.info(errorMessage); - ret = new ErrImageTile("Image can't be positioned: " - + errorMessage); - } - } - - return ret; - } - - protected ImageTile get4326(GeoTIFFImageReader gtid, ImageTile.Cache cache) - throws IOException { - // GCS_WGS_84 - GeoTIFFDirectory gtfd = gtfFile.getGtfDirectory(); - // There's got to be a way to figure out the pixel height and width of - // the image without having to create the BufferedImage. We need those - // for georeferencing the lower right corner right now, but it would be - // good to only create the image if an ImageDecoder and cache weren't - // provided. - double[] tiePoints = gtfd.getTiepoints(); - double[] scaleMatrix = gtfd.getPixelScale(); - - int imageWidth = gtfFile.getFieldIntValue(256); - int imageHeight = gtfFile.getFieldIntValue(257); - - double ulat = tiePoints[4] + tiePoints[1] * scaleMatrix[1]; - double llon = tiePoints[3] - tiePoints[0] * scaleMatrix[0]; - double llat = tiePoints[4] - imageHeight * scaleMatrix[1]; - double rlon = tiePoints[3] + imageWidth * scaleMatrix[0]; - - if (logger.isLoggable(Level.FINE)) { - logger.info("Image should be at: " + ulat + ", " + llon - + " - to - " + llat + ", " + rlon); - } - - if (gtid == null) { - BufferedImage bi = gtfFile.getBufferedImage(); - return new ImageTile((float) ulat, (float) llon, (float) llat, (float) rlon, bi); - } else { - return new ImageTile((float) ulat, (float) llon, (float) llat, (float) rlon, gtid, cache); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFConstants.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFConstants.java deleted file mode 100644 index 905df545a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/iso8211/DDFConstants.java,v -// $ -// $RCSfile: DDFConstants.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.iso8211; - -public interface DDFConstants { - - public final static char DDF_LEADER_SIZE = 24; - public final static char DDF_FIELD_TERMINATOR = 30; - public final static char DDF_UNIT_TERMINATOR = 31; - public final static char DDF_FOOTER_SIZE = 53; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFDataType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFDataType.java deleted file mode 100644 index d5fabddf8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFDataType.java +++ /dev/null @@ -1,35 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/iso8211/DDFDataType.java,v -// $ -// $RCSfile: DDFDataType.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.iso8211; - -public class DDFDataType { - - public final static DDFDataType DDFInt = new DDFDataType(); - public final static DDFDataType DDFFloat = new DDFDataType(); - public final static DDFDataType DDFString = new DDFDataType(); - public final static DDFDataType DDFBinaryString = new DDFDataType(); - - protected DDFDataType() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFField.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFField.java deleted file mode 100644 index 4c6dfd0f8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFField.java +++ /dev/null @@ -1,463 +0,0 @@ -/****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ******************************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.layer.vpf.MutableInt; -import com.bbn.openmap.util.Debug; - -/** - * This object represents one field in a DDFRecord. This models an - * instance of the fields data, rather than it's data definition which - * is handled by the DDFFieldDefn class. Note that a DDFField doesn't - * have DDFSubfield children as you would expect. To extract subfield - * values use GetSubfieldData() to find the right data pointer and - * then use ExtractIntData(), ExtractFloatData() or - * ExtractStringData(). - */ -public class DDFField { - - protected DDFFieldDefinition poDefn; - protected byte[] pachData; - protected Hashtable subfields; - protected int dataPosition; - protected int dataLength; - protected int headerOffset; - - public DDFField() {} - - public DDFField(DDFFieldDefinition poDefnIn, int dataPositionIn, - int dataLengthIn) { - initialize(poDefnIn, null); - dataPosition = dataPositionIn; - dataLength = dataLengthIn; - } - - public DDFField(DDFFieldDefinition poDefnIn, byte[] pachDataIn) { - this(poDefnIn, pachDataIn, true); - } - - public DDFField(DDFFieldDefinition poDefnIn, byte[] pachDataIn, - boolean doSubfields) { - initialize(poDefnIn, pachDataIn); - if (doSubfields) { - buildSubfields(); - } - } - - public void initialize(DDFFieldDefinition poDefnIn, byte[] pachDataIn) { - pachData = pachDataIn; - poDefn = poDefnIn; - subfields = new Hashtable(); - } - - /** - * Set how many bytes to add to the data position for absolute - * position in the data file for the field data. - */ - protected void setHeaderOffset(int headerOffsetIn) { - headerOffset = headerOffsetIn; - } - - /** - * Get how many bytes to add to the data position for absolute - * position in the data file for the field data. - */ - public int getHeaderOffset() { - return headerOffset; - } - - /** - * Return the pointer to the entire data block for this record. - * This is an internal copy, and shouldn't be freed by the - * application. If null, then check the dataPosition and - * daataLength for byte offsets for the data in the file, and go - * get it yourself. This is done for really large files where it - * doesn't make sense to load the data. - */ - public byte[] getData() { - return pachData; - } - - /** - * Return the number of bytes in the data block returned by - * GetData(). - */ - public int getDataSize() { - if (pachData != null) { - return pachData.length; - } else - return 0; - } - - /** Fetch the corresponding DDFFieldDefn. */ - public DDFFieldDefinition getFieldDefn() { - return poDefn; - } - - /** - * If getData() returns null, it'll be your responsibilty to go - * after the data you need for this field. - * - * @return the byte offset into the source file to start reading - * this field. - */ - public int getDataPosition() { - return dataPosition; - } - - /** - * If getData() returns null, it'll be your responsibilty to go - * after the data you need for this field. - * - * @return the number of bytes contained in the source file for - * this field. - */ - public int getDataLength() { - return dataLength; - } - - /** - * Creates a string with variety of information about this field, - * and all it's subfields is written to the given debugging file - * handle. Note that field definition information (ala - * DDFFieldDefn) isn't written. - * - * @return String containing info. - */ - public String toString() { - StringBuffer buf = new StringBuffer(" DDFField:\n"); - buf.append("\tTag = ").append(poDefn.getName()).append("\n"); - buf.append("\tDescription = ").append(poDefn.getDescription()).append("\n"); - int size = getDataSize(); - buf.append("\tDataSize = ").append(size).append("\n"); - - if (pachData == null) { - buf.append("\tHeader offset = ").append(headerOffset).append("\n"); - buf.append("\tData position = ").append(dataPosition).append("\n"); - buf.append("\tData length = ").append(dataLength).append("\n"); - return buf.toString(); - } - - buf.append("\tData = "); - for (int i = 0; i < Math.min(size, 40); i++) { - if (pachData[i] < 32 || pachData[i] > 126) { - buf.append(" | ").append((char) pachData[i]); - } else { - buf.append(pachData[i]); - } - } - - if (size > 40) - buf.append("..."); - buf.append("\n"); - - /* -------------------------------------------------------------------- */ - /* dump the data of the subfields. */ - /* -------------------------------------------------------------------- */ - if (Debug.debugging("iso8211.raw")) { - int iOffset = 0; - MutableInt nBytesConsumed = new MutableInt(0); - - for (int nLoopCount = 0; nLoopCount < getRepeatCount(); nLoopCount++) { - if (nLoopCount > 8) { - buf.append(" ...\n"); - break; - } - - for (int i = 0; i < poDefn.getSubfieldCount(); i++) { - byte[] subPachData = new byte[pachData.length - iOffset]; - System.arraycopy(pachData, - iOffset, - subPachData, - 0, - subPachData.length); - - buf.append(poDefn.getSubfieldDefn(i).dumpData(subPachData, - subPachData.length)); - - poDefn.getSubfieldDefn(i).getDataLength(subPachData, - subPachData.length, - nBytesConsumed); - iOffset += nBytesConsumed.value; - } - } - } else { - buf.append(" Subfields:\n"); - - for (Enumeration enumeration = subfields.keys(); enumeration.hasMoreElements();) { - Object obj = subfields.get(enumeration.nextElement()); - - if (obj instanceof List) { - for (Iterator it = ((List) obj).iterator(); it.hasNext();) { - DDFSubfield ddfs = (DDFSubfield) it.next(); - buf.append(" ").append(ddfs.toString()).append("\n"); - } - } else { - buf.append(" ").append(obj.toString()).append("\n"); - } - } - } - - return buf.toString(); - } - - /** - * Will return an ordered list of DDFSubfield objects. If the - * subfield wasn't repeated, it will provide a list containing one - * object. Will return null if the subfield doesn't exist. - */ - public List getSubfields(String subfieldName) { - Object obj = subfields.get(subfieldName); - if (obj instanceof List) { - return (List) obj; - } else if (obj != null) { - LinkedList ll = new LinkedList(); - ll.add(obj); - return ll; - } - - return null; - } - - /** - * Will return a DDFSubfield object with the given name, or the - * first one off the list for a repeating subfield. Will return - * null if the subfield doesn't exist. - */ - public DDFSubfield getSubfield(String subfieldName) { - Object obj = subfields.get(subfieldName); - if (obj instanceof List) { - List l = (List) obj; - if (!l.isEmpty()) { - return (DDFSubfield) (l.get(0)); - } - obj = null; - } - - // May be null if subfield list above is empty. Not sure if - // that's possible. - return (DDFSubfield) obj; - } - - /** - * Fetch raw data pointer for a particular subfield of this field. - * - * The passed DDFSubfieldDefn (poSFDefn) should be acquired from - * the DDFFieldDefn corresponding with this field. This is - * normally done once before reading any records. This method - * involves a series of calls to DDFSubfield::GetDataLength() in - * order to track through the DDFField data to that belonging to - * the requested subfield. This can be relatively expensive. - *

- * - * @param poSFDefn The definition of the subfield for which the - * raw data pointer is desired. - * @param pnMaxBytes The maximum number of bytes that can be - * accessed from the returned data pointer is placed in - * this int, unless it is null. - * @param iSubfieldIndex The instance of this subfield to fetch. - * Use zero (the default) for the first instance. - * - * @return A pointer into the DDFField's data that belongs to the - * subfield. This returned pointer is invalidated by the - * next record read (DDFRecord::ReadRecord()) and the - * returned pointer should not be freed by the - * application. - */ - public byte[] getSubfieldData(DDFSubfieldDefinition poSFDefn, - MutableInt pnMaxBytes, int iSubfieldIndex) { - int iOffset = 0; - - if (poSFDefn == null) - return null; - - if (iSubfieldIndex > 0 && poDefn.getFixedWidth() > 0) { - iOffset = poDefn.getFixedWidth() * iSubfieldIndex; - iSubfieldIndex = 0; - } - - MutableInt nBytesConsumed = new MutableInt(0); - while (iSubfieldIndex >= 0) { - for (int iSF = 0; iSF < poDefn.getSubfieldCount(); iSF++) { - DDFSubfieldDefinition poThisSFDefn = poDefn.getSubfieldDefn(iSF); - - byte[] subPachData = new byte[pachData.length - iOffset]; - System.arraycopy(pachData, - iOffset, - subPachData, - 0, - subPachData.length); - - if (poThisSFDefn == poSFDefn && iSubfieldIndex == 0) { - - if (pnMaxBytes != null) { - pnMaxBytes.value = pachData.length - iOffset; - } - - return subPachData; - } - - poThisSFDefn.getDataLength(subPachData, - subPachData.length, - nBytesConsumed); - - iOffset += nBytesConsumed.value; - } - - iSubfieldIndex--; - } - - // We didn't find our target subfield or instance! - return null; - } - - public void buildSubfields() { - byte[] pachFieldData = pachData; - int nBytesRemaining = pachData.length; - - for (int iRepeat = 0; iRepeat < getRepeatCount(); iRepeat++) { - - /* -------------------------------------------------------- */ - /* Loop over all the subfields of this field, advancing */ - /* the data pointer as we consume data. */ - /* -------------------------------------------------------- */ - for (int iSF = 0; iSF < poDefn.getSubfieldCount(); iSF++) { - - DDFSubfield ddfs = new DDFSubfield(poDefn.getSubfieldDefn(iSF), pachFieldData, nBytesRemaining); - - addSubfield(ddfs); - - // Reset data for next subfield; - int nBytesConsumed = ddfs.getByteSize(); - nBytesRemaining -= nBytesConsumed; - byte[] tempData = new byte[pachFieldData.length - - nBytesConsumed]; - System.arraycopy(pachFieldData, - nBytesConsumed, - tempData, - 0, - tempData.length); - pachFieldData = tempData; - } - } - - } - - protected void addSubfield(DDFSubfield ddfs) { - if (Debug.debugging("iso8211")) { - Debug.output("DDFField(" + getFieldDefn().getName() - + ").addSubfield(" + ddfs + ")"); - } - - String sfName = ddfs.getDefn().getName().trim().intern(); - Object sf = subfields.get(sfName); - if (sf == null) { - subfields.put(sfName, ddfs); - } else { - if (sf instanceof List) { - ((List) sf).add(ddfs); - } else { - Vector subList = new Vector(); - subList.add(sf); - subList.add(ddfs); - subfields.put(sfName, subList); - } - } - } - - /** - * How many times do the subfields of this record repeat? This - * will always be one for non-repeating fields. - * - * @return The number of times that the subfields of this record - * occur in this record. This will be one for - * non-repeating fields. - */ - public int getRepeatCount() { - if (!poDefn.isRepeating()) { - return 1; - } - - /* -------------------------------------------------------------------- */ - /* The occurrence count depends on how many copies of this */ - /* field's list of subfields can fit into the data space. */ - /* -------------------------------------------------------------------- */ - if (poDefn.getFixedWidth() != 0) { - return pachData.length / poDefn.getFixedWidth(); - } - - /* -------------------------------------------------------------------- */ - /* Note that it may be legal to have repeating variable width */ - /* subfields, but I don't have any samples, so I ignore it for */ - /* now. */ - /* */ - /* - * The file data/cape_royal_AZ_DEM/1183XREF.DDF has a - * repeating - */ - /* variable length field, but the count is one, so it isn't */ - /* much value for testing. */ - /* -------------------------------------------------------------------- */ - int iOffset = 0; - int iRepeatCount = 1; - MutableInt nBytesConsumed = new MutableInt(0); - - while (true) { - for (int iSF = 0; iSF < poDefn.getSubfieldCount(); iSF++) { - DDFSubfieldDefinition poThisSFDefn = poDefn.getSubfieldDefn(iSF); - - if (poThisSFDefn.getWidth() > pachData.length - iOffset) { - nBytesConsumed.value = poThisSFDefn.getWidth(); - } else { - byte[] tempData = new byte[pachData.length - iOffset]; - System.arraycopy(pachData, - iOffset, - tempData, - 0, - tempData.length); - poThisSFDefn.getDataLength(tempData, - tempData.length, - nBytesConsumed); - } - - iOffset += nBytesConsumed.value; - if (iOffset > pachData.length) { - return iRepeatCount - 1; - } - } - - if (iOffset > pachData.length - 2) - return iRepeatCount; - - iRepeatCount++; - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFFieldDefinition.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFFieldDefinition.java deleted file mode 100644 index 825c12959..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFFieldDefinition.java +++ /dev/null @@ -1,604 +0,0 @@ -/****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ******************************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.layer.vpf.MutableInt; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Information from the DDR defining one field. Note that just because - * a field is defined for a DDFModule doesn't mean that it actually - * occurs on any records in the module. DDFFieldDefns are normally - * just significant as containers of the DDFSubfieldDefinitions. - */ -public class DDFFieldDefinition implements DDFConstants { - - protected DDFModule poModule; - protected String pszTag; - - protected String _fieldName; - protected String _arrayDescr; - protected String _formatControls; - - protected boolean bRepeatingSubfields; - protected int nFixedWidth; // zero if variable. - - protected DataStructCode _data_struct_code; - protected DataTypeCode _data_type_code; - - protected List paoSubfieldDefns; - - /** - * Fetch a pointer to the field name (tag). - * - * @return this is an internal copy and shouldn't be freed. - */ - public String getName() { - return pszTag; - } - - /** - * Fetch a longer descriptio of this field. - * - * @return this is an internal copy and shouldn't be freed. - */ - public String getDescription() { - return _fieldName; - } - - /** - * Get the number of subfields. - */ - public int getSubfieldCount() { - if (paoSubfieldDefns != null) { - return paoSubfieldDefns.size(); - } - return 0; - } - - /** - * Get the width of this field. This function isn't normally used - * by applications. - * - * @return The width of the field in bytes, or zero if the field - * is not apparently of a fixed width. - */ - public int getFixedWidth() { - return nFixedWidth; - } - - /** - * Fetch repeating flag. - * - * @return true if the field is marked as repeating. - */ - public boolean isRepeating() { - return bRepeatingSubfields; - } - - /** this is just for an S-57 hack for swedish data */ - public void setRepeating(boolean val) { - bRepeatingSubfields = val; - } - - /** ********************************************************************* */ - /* DDFFieldDefn() */ - /** ********************************************************************* */ - - public DDFFieldDefinition() { - poModule = null; - pszTag = null; - _fieldName = null; - _arrayDescr = null; - _formatControls = null; - paoSubfieldDefns = null; - bRepeatingSubfields = false; - } - - public DDFFieldDefinition(DDFModule poModuleIn, String pszTagIn, - byte[] pachFieldArea) { - - initialize(poModuleIn, pszTagIn, pachFieldArea); - } - - /** - * Initialize the field definition from the information in the DDR - * record. This is called by DDFModule.open(). - * - * @param poModuleIn DDFModule representing file being read. - * @param pszTagIn the name of this field. - * @param pachFieldArea the data bytes in the file representing - * the field from the header. - */ - public boolean initialize(DDFModule poModuleIn, String pszTagIn, - byte[] pachFieldArea) { - - /// pachFieldArea needs to be specified better. It's an - /// offset into a character array, and we need to know what - // it - /// is to scope it better in Java. - - int iFDOffset = poModuleIn._fieldControlLength; - - poModule = poModuleIn; - pszTag = pszTagIn; - - /* -------------------------------------------------------------------- */ - /* Set the data struct and type codes. */ - /* -------------------------------------------------------------------- */ - _data_struct_code = DataStructCode.get((char) pachFieldArea[0]); - _data_type_code = DataTypeCode.get((char) pachFieldArea[1]); - - if (Debug.debugging("iso8211")) { - Debug.output("DDFFieldDefinition.initialize(" + pszTagIn - + "):\n\t\t data_struct_code = " + _data_struct_code - + "\n\t\t data_type_code = " + _data_type_code - + "\n\t\t iFDOffset = " + iFDOffset); - } - - /* -------------------------------------------------------------------- */ - /* Capture the field name, description (sub field names), and */ - /* format statements. */ - /* -------------------------------------------------------------------- */ - - byte[] tempData = new byte[pachFieldArea.length - iFDOffset]; - System.arraycopy(pachFieldArea, - iFDOffset, - tempData, - 0, - pachFieldArea.length - iFDOffset); - - MutableInt nCharsConsumed = new MutableInt(); - - _fieldName = DDFUtils.fetchVariable(tempData, - tempData.length, - DDF_UNIT_TERMINATOR, - DDF_FIELD_TERMINATOR, - nCharsConsumed); - if (Debug.debugging("iso8211")) { - Debug.output("DDFFieldDefinition.initialize(" + pszTagIn - + "): created field name " + _fieldName); - } - - iFDOffset += nCharsConsumed.value; - - tempData = new byte[pachFieldArea.length - iFDOffset]; - System.arraycopy(pachFieldArea, - iFDOffset, - tempData, - 0, - pachFieldArea.length - iFDOffset); - _arrayDescr = DDFUtils.fetchVariable(tempData, - tempData.length, - DDF_UNIT_TERMINATOR, - DDF_FIELD_TERMINATOR, - nCharsConsumed); - iFDOffset += nCharsConsumed.value; - - tempData = new byte[pachFieldArea.length - iFDOffset]; - System.arraycopy(pachFieldArea, - iFDOffset, - tempData, - 0, - pachFieldArea.length - iFDOffset); - - _formatControls = DDFUtils.fetchVariable(tempData, - tempData.length, - DDF_UNIT_TERMINATOR, - DDF_FIELD_TERMINATOR, - nCharsConsumed); - - /* -------------------------------------------------------------------- */ - /* Parse the subfield info. */ - /* -------------------------------------------------------------------- */ - if (_data_struct_code != DataStructCode.ELEMENTARY) { - if (!buildSubfieldDefns(_arrayDescr)) { - return false; - } - - if (!applyFormats(_formatControls)) { - return false; - } - } - - return true; - } - - /** - * Write out field definition info. - * - * A variety of information about this field definition, and all - * its subfields are written out too. - */ - public String toString() { - StringBuffer buf = new StringBuffer(" DDFFieldDefn:\n"); - buf.append(" Tag = ").append(pszTag).append("\n"); - buf.append(" _fieldName = ").append(_fieldName).append("\n"); - buf.append(" _arrayDescr = ").append(_arrayDescr).append("\n"); - buf.append(" _formatControls = ").append(_formatControls).append("\n"); - buf.append(" _data_struct_code = ").append(_data_struct_code).append("\n"); - buf.append(" _data_type_code = ").append(_data_type_code).append("\n"); - - if (paoSubfieldDefns != null) { - for (DDFSubfieldDefinition ddsfd : paoSubfieldDefns) { - buf.append(ddsfd); - } - } - - return buf.toString(); - } - - /** - * Based on the list contained in the string, build a set of - * subfield definitions. - */ - protected boolean buildSubfieldDefns(String pszSublist) { - - if (pszSublist.charAt(0) == '*') { - bRepeatingSubfields = true; - pszSublist = pszSublist.substring(1); - } - - List papszSubfieldNames = PropUtils.parseMarkers(pszSublist, "!"); - - paoSubfieldDefns = new ArrayList<>(); - - for (String ddfsdName : papszSubfieldNames) { - DDFSubfieldDefinition ddfsd = new DDFSubfieldDefinition(); - ddfsd.setName(ddfsdName); - paoSubfieldDefns.add(ddfsd); - } - - return true; - } - - /** - * Extract a substring terminated by a comma (or end of string). - * Commas in brackets are ignored as terminated with bracket - * nesting understood gracefully. If the returned string would - * being and end with a bracket then strip off the brackets. - *

- * Given a string like "(A,3(B,C),D),X,Y)" return "A,3(B,C),D". - * Give a string like "3A,2C" return "3A". - */ - protected String extractSubstring(String pszSrc) { - int nBracket = 0; - int i; - String pszReturn; - - for (i = 0; i < pszSrc.length() - && (nBracket > 0 || pszSrc.charAt(i) != ','); i++) { - if (pszSrc.charAt(i) == '(') { - nBracket++; - } else if (pszSrc.charAt(i) == ')') { - nBracket--; - } - } - - if (pszSrc.charAt(0) == '(') { - pszReturn = pszSrc.substring(1, i - 2); - } else { - pszReturn = pszSrc.substring(0, i); - } - - return pszReturn; - } - - /** - * Given a string that contains a coded size symbol, expand it - * out. - */ - protected String expandFormat(String pszSrc) { - StringBuffer szDest = new StringBuffer(); - int iSrc = 0; - int nRepeat = 0; - - while (iSrc < pszSrc.length()) { - /* - * This is presumably an extra level of brackets around - * some binary stuff related to rescanning which we don't - * care to do (see 6.4.3.3 of the standard. We just strip - * off the extra layer of brackets - */ - if ((iSrc == 0 || pszSrc.charAt(iSrc - 1) == ',') - && pszSrc.charAt(iSrc) == '(') { - String pszContents = extractSubstring(pszSrc + iSrc); - String pszExpandedContents = expandFormat(pszContents); - - szDest.append(pszExpandedContents); - iSrc = iSrc + pszContents.length() + 2; - - } else if ((iSrc == 0 || pszSrc.charAt(iSrc - 1) == ',') /* - * this - * is a - * repeated - * subclause - */ - && Character.isDigit(pszSrc.charAt(iSrc))) { - - int orig_iSrc = iSrc; - - // skip over repeat count. - for (; Character.isDigit(pszSrc.charAt(iSrc)); iSrc++) { - } - String nRepeatString = pszSrc.substring(orig_iSrc, iSrc); - nRepeat = Integer.parseInt(nRepeatString); - - String pszContents = extractSubstring(pszSrc.substring(iSrc)); - String pszExpandedContents = expandFormat(pszContents); - - for (int i = 0; i < nRepeat; i++) { - szDest.append(pszExpandedContents); - if (i < nRepeat - 1) { - szDest.append(","); - } - } - - if (iSrc == '(') { - iSrc += pszContents.length() + 2; - } else { - iSrc += pszContents.length(); - } - - } else { - szDest.append(pszSrc.charAt(iSrc++)); - } - } - - return szDest.toString(); - } - - /** - * This method parses the format string partially, and then - * applies a subfield format string to each subfield object. It in - * turn does final parsing of the subfield formats. - */ - protected boolean applyFormats(String _formatControls) { - - /* -------------------------------------------------------------------- */ - /* Verify that the format string is contained within brackets. */ - /* -------------------------------------------------------------------- */ - if (_formatControls.length() < 2 || !_formatControls.startsWith("(") - || !_formatControls.endsWith(")")) { - - Debug.error("DDFFieldDefinition: Format controls for " + pszTag - + " field missing brackets {" + _formatControls - + "} : length = " + _formatControls.length() - + ", starts with {" + _formatControls.charAt(0) - + "}, ends with {" - + _formatControls.charAt(_formatControls.length() - 1) - + "}"); - - return false; - } - - /* -------------------------------------------------------------------- */ - /* Duplicate the string, and strip off the brackets. */ - /* -------------------------------------------------------------------- */ - - String pszFormatList = expandFormat(_formatControls); - - if (Debug.debugging("iso8211")) { - Debug.output("DDFFieldDefinition.applyFormats{" + _formatControls - + "} expanded to {" + pszFormatList + "} "); - } - - /* -------------------------------------------------------------------- */ - /* Tokenize based on commas. */ - /* -------------------------------------------------------------------- */ - List papszFormatItems = PropUtils.parseMarkers(pszFormatList, ","); - - /* -------------------------------------------------------------------- */ - /* Apply the format items to subfields. */ - /* -------------------------------------------------------------------- */ - - int iFormatItem = 0; - for (String pszPastPrefix : papszFormatItems) { - - int pppIndex = 0; - // Skip over digits... - for (; Character.isDigit(pszPastPrefix.charAt(pppIndex)); pppIndex++) { - } - pszPastPrefix = pszPastPrefix.substring(pppIndex); - - /////////////////////////////////////////////////////////////// - // Did we get too many formats for the subfields created - // by names? This may be legal by the 8211 specification, - // but - // isn't encountered in any formats we care about so we - // just - // blow. - - if (iFormatItem > paoSubfieldDefns.size()) { - Debug.error("DDFFieldDefinition: Got more formats than subfields for field " - + pszTag); - break; - } - - if (! paoSubfieldDefns.get(iFormatItem).setFormat(pszPastPrefix)) { - Debug.output("DDFFieldDefinition had problem setting format for " + pszPastPrefix); - return false; - } - - iFormatItem++; - } - - /* -------------------------------------------------------------------- */ - /* Verify that we got enough formats, cleanup and return. */ - /* -------------------------------------------------------------------- */ - if (iFormatItem < paoSubfieldDefns.size()) { - Debug.error("DDFFieldDefinition: Got fewer formats than subfields for field " - + pszTag - + " got (" - + iFormatItem - + ", should have " - + paoSubfieldDefns.size() + ")"); - return false; - } - - /* -------------------------------------------------------------------- */ - /* If all the fields are fixed width, then we are fixed width */ - /* too. This is important for repeating fields. */ - /* -------------------------------------------------------------------- */ - nFixedWidth = 0; - for (int i = 0; i < paoSubfieldDefns.size(); i++) { - DDFSubfieldDefinition ddfsd = paoSubfieldDefns.get(i); - if (ddfsd.getWidth() == 0) { - nFixedWidth = 0; - break; - } else { - nFixedWidth += ddfsd.getWidth(); - } - } - - return true; - } - - /** - * Find a subfield definition by it's mnemonic tag. - * - * @param pszMnemonic The name of the field. - * - * @return The subfield pointer, or null if there isn't any such - * subfield. - */ - public DDFSubfieldDefinition findSubfieldDefn(String pszMnemonic) { - if (paoSubfieldDefns != null && pszMnemonic != null) { - for (DDFSubfieldDefinition ddfsd : paoSubfieldDefns) { - if (pszMnemonic.equalsIgnoreCase(ddfsd.getName())) { - return ddfsd; - } - } - } - - return null; - } - - /** - * Fetch a subfield by index. - * - * @param i The index subfield index. (Between 0 and - * GetSubfieldCount()-1) - * @return The subfield pointer, or null if the index is out of - * range. - */ - public DDFSubfieldDefinition getSubfieldDefn(int i) { - if (paoSubfieldDefns == null || i < 0 || i >= paoSubfieldDefns.size()) { - return null; - } - - return paoSubfieldDefns.get(i); - } - - public static class DataStructCode { - public final static DataStructCode ELEMENTARY = new DataStructCode('0', "elementary"); - public final static DataStructCode VECTOR = new DataStructCode('1', "vector"); - public final static DataStructCode ARRAY = new DataStructCode('2', "array"); - public final static DataStructCode CONCATENATED = new DataStructCode('3', "concatenated"); - - char code = '0'; - String prettyName; - - public DataStructCode(char structCode, String name) { - code = structCode; - prettyName = name; - } - - public char getCode() { - return code; - } - - public String toString() { - return prettyName; - } - - public static DataStructCode get(char c) { - if (c == CONCATENATED.getCode()) - return CONCATENATED; - if (c == VECTOR.getCode()) - return VECTOR; - if (c == ARRAY.getCode()) - return ARRAY; - if (c == ELEMENTARY.getCode()) - return ELEMENTARY; - - if (Debug.debugging("iso8211")) { - Debug.output("DDFFieldDefinition tested for unknown code: " + c); - } - return ELEMENTARY; - } - } - - public static class DataTypeCode { - public final static DataTypeCode CHAR_STRING = new DataTypeCode('0', "character string"); - public final static DataTypeCode IMPLICIT_POINT = new DataTypeCode('1', "implicit point"); - public final static DataTypeCode EXPLICIT_POINT = new DataTypeCode('2', "explicit point"); - public final static DataTypeCode EXPLICIT_POINT_SCALED = new DataTypeCode('3', "explicit point scaled"); - public final static DataTypeCode CHAR_BIT_STRING = new DataTypeCode('4', "character bit string"); - public final static DataTypeCode BIT_STRING = new DataTypeCode('5', "bit string"); - public final static DataTypeCode MIXED_DATA_TYPE = new DataTypeCode('6', "mixed data type"); - - char code = '0'; - String prettyName; - - public DataTypeCode(char structCode, String desc) { - code = structCode; - prettyName = desc; - } - - public char getCode() { - return code; - } - - public String toString() { - return prettyName; - } - - public static DataTypeCode get(char c) { - if (c == IMPLICIT_POINT.getCode()) - return IMPLICIT_POINT; - if (c == EXPLICIT_POINT.getCode()) - return EXPLICIT_POINT; - if (c == EXPLICIT_POINT_SCALED.getCode()) - return EXPLICIT_POINT_SCALED; - if (c == CHAR_BIT_STRING.getCode()) - return CHAR_BIT_STRING; - if (c == BIT_STRING.getCode()) - return BIT_STRING; - if (c == MIXED_DATA_TYPE.getCode()) - return MIXED_DATA_TYPE; - if (c == CHAR_STRING.getCode()) - return CHAR_STRING; - - if (Debug.debugging("iso8211")) { - Debug.output("DDFFieldDefinition tested for unknown data type code: " - + c); - } - return CHAR_STRING; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFModule.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFModule.java deleted file mode 100644 index d2cd779dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFModule.java +++ /dev/null @@ -1,501 +0,0 @@ -/****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ******************************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.util.Debug; - -/** - * The class that represents a ISO 8211 file. - */ -public class DDFModule implements DDFConstants { - - protected BinaryFile fpDDF; - protected String fileName; - protected long nFirstRecordOffset; - - protected byte _interchangeLevel; - protected byte _inlineCodeExtensionIndicator; - protected byte _versionNumber; - protected byte _appIndicator; - protected int _fieldControlLength; - protected String _extendedCharSet; // 4 characters - - protected int _recLength; - protected byte _leaderIden; - protected int _fieldAreaStart; - protected int _sizeFieldLength; - protected int _sizeFieldPos; - protected int _sizeFieldTag; - - protected Vector paoFieldDefns; //DDFFieldDefinitions - protected DDFRecord poRecord; - - /** - * The constructor. Need to call open() if this constructor is - * used. - */ - public DDFModule() { - paoFieldDefns = null; - poRecord = null; - fpDDF = null; - } - - public DDFModule(String ddfName) throws IOException { - open(ddfName); - } - - /** - * Close an ISO 8211 file. Just close the file pointer to the - * file. - */ - public void close() { - - if (fpDDF != null) { - try { - fpDDF.close(); - } catch (IOException ioe) { - Debug.error("DDFModule IOException when closing DDFModule file"); - } - fpDDF = null; - } - } - - /** - * Clean up, get rid of data and close file pointer. - */ - public void destroy() { - close(); - - // Cleanup the working record. - poRecord = null; - // Cleanup the field definitions. - paoFieldDefns = null; - } - - /** - * Open a ISO 8211 (DDF) file for reading, and read the DDR record - * to build the field definitions. - * - * If the open succeeds the data descriptive record (DDR) will - * have been read, and all the field and subfield definitions will - * be available. - * - * @param pszFilename The name of the file to open. - */ - public BinaryFile open(String pszFilename) throws IOException { - - fileName = pszFilename; - - fpDDF = new BinaryBufferedFile(pszFilename); - - // Read the 24 byte leader. - byte[] achLeader = new byte[DDF_LEADER_SIZE]; - - if (fpDDF.read(achLeader) != DDF_LEADER_SIZE) { - destroy(); - if (Debug.debugging("iso8211")) { - Debug.output("DDFModule: Leader is short on DDF file " - + pszFilename); - } - return null; - } - - // Verify that this appears to be a valid DDF file. - int i; - boolean bValid = true; - - for (i = 0; i < (int) DDF_LEADER_SIZE; i++) { - if (achLeader[i] < 32 || achLeader[i] > 126) { - bValid = false; - } - } - - if (achLeader[5] != '1' && achLeader[5] != '2' && achLeader[5] != '3') { - bValid = false; - } - - if (achLeader[6] != 'L') { - bValid = false; - } - - if (achLeader[8] != '1' && achLeader[8] != ' ') { - bValid = false; - } - - // Extract information from leader. - if (bValid) { - _recLength = Integer.parseInt(new String(achLeader, 0, 5)); - _interchangeLevel = achLeader[5]; - _leaderIden = achLeader[6]; - _inlineCodeExtensionIndicator = achLeader[7]; - _versionNumber = achLeader[8]; - _appIndicator = achLeader[9]; - _fieldControlLength = Integer.parseInt(new String(achLeader, 10, 2)); - _fieldAreaStart = Integer.parseInt(new String(achLeader, 12, 5)); - _extendedCharSet = new String((char) achLeader[17] + "" - + (char) achLeader[18] + "" + (char) achLeader[19]); - _sizeFieldLength = Integer.parseInt(new String(achLeader, 20, 1)); - _sizeFieldPos = Integer.parseInt(new String(achLeader, 21, 1)); - _sizeFieldTag = Integer.parseInt(new String(achLeader, 23, 1)); - - if (_recLength < 12 || _fieldControlLength == 0 - || _fieldAreaStart < 24 || _sizeFieldLength == 0 - || _sizeFieldPos == 0 || _sizeFieldTag == 0) { - bValid = false; - } - - if (Debug.debugging("iso8211")) { - Debug.output("bValid = " + bValid + ", from " - + new String(achLeader)); - Debug.output(toString()); - } - } - - // If the header is invalid, then clean up, report the error - // and return. - if (!bValid) { - destroy(); - - if (Debug.debugging("iso8211")) { - Debug.error("DDFModule: File " + pszFilename - + " does not appear to have a valid ISO 8211 header."); - } - return null; - } - - if (Debug.debugging("iso8211")) { - Debug.output("DDFModule: header parsed successfully"); - - } - - /* -------------------------------------------------------------------- */ - /* Read the whole record into memory. */ - /* -------------------------------------------------------------------- */ - byte[] pachRecord = new byte[_recLength]; - - System.arraycopy(achLeader, 0, pachRecord, 0, achLeader.length); - int numNewRead = pachRecord.length - achLeader.length; - - if (fpDDF.read(pachRecord, achLeader.length, numNewRead) != numNewRead) { - if (Debug.debugging("iso8211")) { - Debug.error("DDFModule: Header record is short on DDF file " - + pszFilename); - } - - return null; - } - - /* First make a pass counting the directory entries. */ - int nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; - - int nFieldDefnCount = 0; - for (i = DDF_LEADER_SIZE; i < _recLength; i += nFieldEntryWidth) { - if (pachRecord[i] == DDF_FIELD_TERMINATOR) - break; - - nFieldDefnCount++; - } - - /* Allocate, and read field definitions. */ - paoFieldDefns = new Vector(); - - for (i = 0; i < nFieldDefnCount; i++) { - if (Debug.debugging("iso8211")) { - Debug.output("DDFModule.open: Reading field " + i); - } - - byte[] szTag = new byte[128]; - int nEntryOffset = DDF_LEADER_SIZE + i * nFieldEntryWidth; - int nFieldLength, nFieldPos; - - System.arraycopy(pachRecord, nEntryOffset, szTag, 0, _sizeFieldTag); - - nEntryOffset += _sizeFieldTag; - nFieldLength = Integer.parseInt(new String(pachRecord, nEntryOffset, _sizeFieldLength)); - - nEntryOffset += _sizeFieldLength; - nFieldPos = Integer.parseInt(new String(pachRecord, nEntryOffset, _sizeFieldPos)); - - byte[] subPachRecord = new byte[nFieldLength]; - System.arraycopy(pachRecord, - _fieldAreaStart + nFieldPos, - subPachRecord, - 0, - nFieldLength); - - paoFieldDefns.add(new DDFFieldDefinition(this, new String(szTag, 0, _sizeFieldTag), subPachRecord)); - } - - // Free the memory... - achLeader = null; - pachRecord = null; - - // Record the current file offset, the beginning of the first - // data record. - nFirstRecordOffset = fpDDF.getFilePointer(); - - return fpDDF; - } - - public long getFileLength() throws IOException { - return fpDDF.length(); - } - - public int getRecordLength() throws IOException { - return _recLength; - } - - /** - * Write out module info to debugging file. - * - * A variety of information about the module is written to the - * debugging file. This includes all the field and subfield - * definitions read from the header. - */ - public String toString() { - StringBuffer buf = new StringBuffer("DDFModule:\n"); - buf.append(" _recLength = ").append(_recLength).append("\n"); - buf.append(" _interchangeLevel = ").append(_interchangeLevel).append("\n"); - buf.append(" _leaderIden = ").append((char) _leaderIden).append("\n"); - buf.append(" _inlineCodeExtensionIndicator = ") - .append(_inlineCodeExtensionIndicator).append("\n"); - buf.append(" _versionNumber = ").append(_versionNumber).append("\n"); - buf.append(" _appIndicator = ").append(_appIndicator).append("\n"); - buf.append(" _extendedCharSet = ").append(_extendedCharSet).append("\n"); - buf.append(" _fieldControlLength = ").append(_fieldControlLength).append("\n"); - buf.append(" _fieldAreaStart = ").append(_fieldAreaStart).append("\n"); - buf.append(" _sizeFieldLength = ").append(_sizeFieldLength).append("\n"); - buf.append(" _sizeFieldPos = ").append(_sizeFieldPos).append("\n"); - buf.append(" _sizeFieldTag = ").append(_sizeFieldTag).append("\n"); - return buf.toString(); - } - - public String dump() { - StringBuffer buf = new StringBuffer(toString()); - - DDFRecord poRecord; - int iRecord = 0; - while ((poRecord = readRecord()) != null) { - buf.append(" Record ").append((iRecord++)).append("(") - .append(poRecord.getDataSize()).append(" bytes)\n"); - - for (Iterator it = poRecord.iterator(); it.hasNext(); buf.append(((DDFField) it.next()).toString())) { - } - } - return buf.toString(); - } - - /** - * Fetch the definition of the named field. - * - * This function will scan the DDFFieldDefn's on this module, to - * find one with the indicated field name. - * - * @param pszFieldName The name of the field to search for. The - * comparison is case insensitive. - * - * @return A pointer to the request DDFFieldDefn object is - * returned, or null if none matching the name are found. - * The return object remains owned by the DDFModule, and - * should not be deleted by application code. - */ - public DDFFieldDefinition findFieldDefn(String pszFieldName) { - - for (Iterator it = paoFieldDefns.iterator(); it.hasNext();) { - DDFFieldDefinition ddffd = (DDFFieldDefinition) it.next(); - String pszThisName = ddffd.getName(); - - if (Debug.debugging("iso8211detail")) { - Debug.output("DDFModule.findFieldDefn(" + pszFieldName + ":" - + pszFieldName.length() + ") checking against [" - + pszThisName + ":" + pszThisName.length() + "]"); - } - - if (pszFieldName.equalsIgnoreCase(pszThisName)) { - return ddffd; - } - } - - return null; - } - - /** - * Read one record from the file, and return to the application. - * The returned record is owned by the module, and is reused from - * call to call in order to preserve headers when they aren't - * being re-read from record to record. - * - * @return A pointer to a DDFRecord object is returned, or null if - * a read error, or end of file occurs. The returned - * record is owned by the module, and should not be - * deleted by the application. The record is only valid - * until the next ReadRecord() at which point it is - * overwritten. - */ - public DDFRecord readRecord() { - if (poRecord == null) { - poRecord = new DDFRecord(this); - } - - if (poRecord.read()) { - return poRecord; - } else { - return null; - } - } - - /** - * Method for other components to call to get the DDFModule to - * read bytes into the provided array. - * - * @param toData the bytes to put data into. - * @param offset the byte offset to start reading from, whereever - * the pointer currently is. - * @param length the number of bytes to read. - * @return the number of bytes read. - */ - public int read(byte[] toData, int offset, int length) { - if (fpDDF == null) { - reopen(); - } - - if (fpDDF != null) { - try { - return fpDDF.read(toData, offset, length); - } catch (IOException ioe) { - Debug.error("DDFModule.read(): IOException caught"); - } catch (ArrayIndexOutOfBoundsException aioobe) { - Debug.error("DDFModule.read(): " - + aioobe.getMessage() - + " reading from " - + offset - + " to " - + length - + " into " - + (toData == null ? "null byte[]" : "byte[" - + toData.length + "]")); - aioobe.printStackTrace(); - } - } - return 0; - } - - /** - * Convenience method to read a byte from the data file. Assumes - * that you know what you are doing based on the parameters read - * in the data file. For DDFFields that haven't loaded their - * subfields. - */ - public int read() { - if (fpDDF == null) { - reopen(); - } - - if (fpDDF != null) { - try { - return fpDDF.read(); - } catch (IOException ioe) { - Debug.error("DDFModule.read(): IOException caught"); - } - } - return 0; - } - - /** - * Convenience method to seek to a location in the data file. - * Assumes that you know what you are doing based on the - * parameters read in the data file. For DDFFields that haven't - * loaded their subfields. - * - * @param pos the byte position to reposition the file pointer to. - */ - public void seek(long pos) throws IOException { - if (fpDDF == null) { - reopen(); - } - - if (fpDDF != null) { - fpDDF.seek(pos); - } else { - throw new IOException("DDFModule doesn't have a pointer to a file"); - } - } - - /** - * Fetch a field definition by index. - * - * @param i (from 0 to GetFieldCount() - 1. - * @return the returned field pointer or null if the index is out - * of range. - */ - public DDFFieldDefinition getField(int i) { - if (i >= 0 || i < paoFieldDefns.size()) { - return (DDFFieldDefinition) paoFieldDefns.elementAt(i); - } - - return null; - } - - /** - * Return to first record. - * - * The next call to ReadRecord() will read the first data record - * in the file. - * - * @param nOffset the offset in the file to return to. By default - * this is -1, a special value indicating that reading - * should return to the first data record. Otherwise it is - * an absolute byte offset in the file. - */ - public void rewind(long nOffset) throws IOException { - if (nOffset == -1) { - nOffset = nFirstRecordOffset; - } - - if (fpDDF != null) { - fpDDF.seek(nOffset); - - // Don't know what this has to do with anything... - if (nOffset == nFirstRecordOffset && poRecord != null) { - poRecord.clear(); - } - } - - } - - public void reopen() { - try { - if (fpDDF == null) { - fpDDF = new BinaryBufferedFile(fileName); - } - } catch (IOException ioe) { - - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFRecord.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFRecord.java deleted file mode 100644 index 57ce90084..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFRecord.java +++ /dev/null @@ -1,598 +0,0 @@ -/****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ******************************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.layer.vpf.MutableInt; -import com.bbn.openmap.util.Debug; - -/** - * Contains instance data from one data record (DR). The data is - * contained as a list of DDFField instances partitioning the raw data - * into fields. Class contains one DR record from a file. We read into - * the same record object repeatedly to ensure that repeated leaders - * can be easily preserved. - */ -public class DDFRecord implements DDFConstants { - - protected DDFModule poModule; - protected boolean nReuseHeader; - protected int nFieldOffset; // field data area, not dir entries. - protected int nDataSize; // Whole record except leader with header - protected byte[] pachData; - - protected int nFieldCount; - protected Vector paoFields; // Vector of DDFFields - - protected boolean bIsClone = false; - - public DDFRecord(DDFModule poModuleIn) { - poModule = poModuleIn; - nReuseHeader = false; - nFieldOffset = -1; - nDataSize = 0; - pachData = null; - nFieldCount = 0; - paoFields = null; - bIsClone = false; - } - - /** Get the number of DDFFields on this record. */ - public int getFieldCount() { - return nFieldCount; - } - - /** Fetch size of records raw data (GetData()) in bytes. */ - public int getDataSize() { - return nDataSize; - } - - /** - * Fetch the raw data for this record. The returned pointer is - * effectively to the data for the first field of the record, and - * is of size GetDataSize(). - */ - public byte[] getData() { - return pachData; - } - - /** - * Fetch the DDFModule with which this record is associated. - */ - public DDFModule getModule() { - return poModule; - } - - /** - * Write out record contents to debugging file. - * - * A variety of information about this record, and all it's fields - * and subfields is written to the given debugging file handle. - * Note that field definition information (ala DDFFieldDefn) isn't - * written. - */ - public String toString() { - StringBuffer buf = new StringBuffer("DDFRecord:\n"); - buf.append(" ReuseHeader = ").append(nReuseHeader).append("\n"); - buf.append(" DataSize = ").append(nDataSize).append("\n"); - - if (paoFields != null) { - for (Iterator it = paoFields.iterator(); it.hasNext();) { - buf.append((DDFField) it.next()); - } - } - return buf.toString(); - } - - /** - * Read a record of data from the file, and parse the header to - * build a field list for the record (or reuse the existing one if - * reusing headers). It is expected that the file pointer will be - * positioned at the beginning of a data record. It is the - * DDFModule's responsibility to do so. - * - * This method should only be called by the DDFModule class. - */ - protected boolean read() { - /* -------------------------------------------------------------------- */ - /* Redefine the record on the basis of the header if needed. */ - /* - * As a side effect this will read the data for the record as - * well. - */ - /* -------------------------------------------------------------------- */ - if (!nReuseHeader) { - Debug.message("iso8211", - "DDFRecord reusing header, calling readHeader()"); - return readHeader(); - } - - /* -------------------------------------------------------------------- */ - /* Otherwise we read just the data and carefully overlay it on */ - /* - * the previous records data without disturbing the rest of - * the - */ - /* record. */ - /* -------------------------------------------------------------------- */ - - byte[] tempData = new byte[nDataSize - nFieldOffset]; - int nReadBytes = poModule.read(tempData, 0, tempData.length); - System.arraycopy(pachData, nFieldOffset, tempData, 0, tempData.length); - - if (nReadBytes != (int) (nDataSize - nFieldOffset) && nReadBytes == -1) { - - return false; - } else if (nReadBytes != (int) (nDataSize - nFieldOffset)) { - Debug.error("DDFRecord: Data record is short on DDF file."); - return false; - } - - // notdef: eventually we may have to do something at this - // point to - // notify the DDFField's that their data values have changed. - return true; - } - - /** - * Clear any information associated with the last header in - * preparation for reading a new header. - */ - public void clear() { - if (paoFields != null) { - paoFields = null; - } - - paoFields = null; - nFieldCount = 0; - - pachData = null; - nDataSize = 0; - nReuseHeader = false; - } - - /** - * This perform the header reading and parsing job for the read() - * method. It reads the header, and builds a field list. - */ - protected boolean readHeader() { - - /* -------------------------------------------------------------------- */ - /* Clear any existing information. */ - /* -------------------------------------------------------------------- */ - clear(); - - /* -------------------------------------------------------------------- */ - /* Read the 24 byte leader. */ - /* -------------------------------------------------------------------- */ - byte[] achLeader = new byte[DDF_LEADER_SIZE]; - - int nReadBytes = poModule.read(achLeader, 0, DDF_LEADER_SIZE); - if (nReadBytes == -1) { - return false; - } else if (nReadBytes != (int) DDF_LEADER_SIZE) { - Debug.error("DDFRecord.readHeader(): Leader is short on DDF file."); - return false; - } - - /* -------------------------------------------------------------------- */ - /* Extract information from leader. */ - /* -------------------------------------------------------------------- */ - int _recLength, _fieldAreaStart, _sizeFieldLength; - int _sizeFieldPos, _sizeFieldTag; - byte _leaderIden; - - try { - String recLength = new String(achLeader, 0, 5); - String fieldAreaStart = new String(achLeader, 12, 5); - _recLength = controlValidFileLength(Integer.valueOf(recLength).intValue()); - _fieldAreaStart = Integer.valueOf(fieldAreaStart).intValue(); - } catch (NumberFormatException nfe) { - - // Turns out, this usually indicates the end of the header - // information, - // with "^^^^^^^" being in the file. This is filler. - if (Debug.debugging("iso8211")) { - Debug.output("Finished reading headers"); - } - if (Debug.debugging("iso8211detail")) { - Debug.error("DDFRecord.readHeader(): " + nfe.getMessage()); - nfe.printStackTrace(); - } else { - // Debug.output("Data record appears to be corrupt on - // DDF file.\n -- ensure that the files were - // uncompressed without modifying\n carriage - // return/linefeeds (by default WINZIP does this)."); - } - - return false; - } - - _leaderIden = achLeader[6]; - _sizeFieldLength = achLeader[20] - '0'; - _sizeFieldPos = achLeader[21] - '0'; - _sizeFieldTag = achLeader[23] - '0'; - - if (_leaderIden == 'R') { - nReuseHeader = true; - } - - nFieldOffset = _fieldAreaStart - DDF_LEADER_SIZE; - - if (Debug.debugging("iso8211")) { - Debug.output("\trecord length [0,5] = " + _recLength); - Debug.output("\tfield area start [12,5]= " + _fieldAreaStart); - Debug.output("\tleader id [6] = " + (char) _leaderIden - + ", reuse header = " + nReuseHeader); - Debug.output("\tfield length [20] = " + _sizeFieldLength); - Debug.output("\tfield position [21] = " + _sizeFieldPos); - Debug.output("\tfield tag [23] = " + _sizeFieldTag); - } - - boolean readSubfields = false; - - /* -------------------------------------------------------------------- */ - /* Is there anything seemly screwy about this record? */ - /* -------------------------------------------------------------------- */ - if (_recLength == 0) { - // Looks like for record lengths of zero, we really want - // to consult the size of the fields before we try to read - // in all of the data for this record. Most likely, we - // don't, and want to access the data later only when we - // need it. - - nDataSize = _fieldAreaStart - DDF_LEADER_SIZE; - } else if (_recLength < 24 || _recLength > 100000000 - || _fieldAreaStart < 24 || _fieldAreaStart > 100000) { - - Debug.error("DDFRecord: Data record appears to be corrupt on DDF file.\n -- ensure that the files were uncompressed without modifying\n carriage return/linefeeds (by default WINZIP does this)."); - return false; - } else { - /* -------------------------------------------------------------------- */ - /* Read the remainder of the record. */ - /* -------------------------------------------------------------------- */ - nDataSize = _recLength - DDF_LEADER_SIZE; - readSubfields = true; - } - - pachData = new byte[nDataSize]; - - if (poModule.read(pachData, 0, nDataSize) != nDataSize) { - Debug.error("DDFRecord: Data record is short on DDF file."); - return false; - } - - /* -------------------------------------------------------------------- */ - /* - * Loop over the directory entries, making a pass counting - * them. - */ - /* -------------------------------------------------------------------- */ - int i; - int nFieldEntryWidth; - - nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; - nFieldCount = 0; - for (i = 0; i < nDataSize; i += nFieldEntryWidth) { - if (pachData[i] == DDF_FIELD_TERMINATOR) - break; - - nFieldCount++; - } - - /* ==================================================================== */ - /* Allocate, and read field definitions. */ - /* ==================================================================== */ - paoFields = new Vector(nFieldCount); - - for (i = 0; i < nFieldCount; i++) { - String szTag; - int nEntryOffset = i * nFieldEntryWidth; - int nFieldLength, nFieldPos; - - /* -------------------------------------------------------------------- */ - /* Read the position information and tag. */ - /* -------------------------------------------------------------------- */ - szTag = new String(pachData, nEntryOffset, _sizeFieldTag); - - nEntryOffset += _sizeFieldTag; - nFieldLength = Integer.valueOf(new String(pachData, nEntryOffset, _sizeFieldLength)) - .intValue(); - - nEntryOffset += _sizeFieldLength; - nFieldPos = Integer.valueOf(new String(pachData, nEntryOffset, _sizeFieldPos)) - .intValue(); - - /* -------------------------------------------------------------------- */ - /* Find the corresponding field in the module directory. */ - /* -------------------------------------------------------------------- */ - DDFFieldDefinition poFieldDefn = poModule.findFieldDefn(szTag); - - if (poFieldDefn == null) { - Debug.error("DDFRecord: Undefined field " + szTag - + " encountered in data record."); - return false; - } - - DDFField ddff = null; - - if (readSubfields) { - - /* -------------------------------------------------------------------- */ - /* Assign info the DDFField. */ - /* -------------------------------------------------------------------- */ - byte[] tempData = new byte[nFieldLength]; - System.arraycopy(pachData, _fieldAreaStart + nFieldPos - - DDF_LEADER_SIZE, tempData, 0, tempData.length); - - ddff = new DDFField(poFieldDefn, tempData, readSubfields); - - } else { - - // Save the info for reading later directly out of the - // field. - ddff = new DDFField(poFieldDefn, nFieldPos, nFieldLength); - ddff.setHeaderOffset(poModule._recLength + _fieldAreaStart); - } - paoFields.add(ddff); - } - - return true; - } - - private int controlValidFileLength(int fileLength) { - return fileLength == 0 ? computeAwaitingFileLength(fileLength) : fileLength; - } - - private int computeAwaitingFileLength(int fileLength) { - int _awaiting_file_length = 0; - try { - int _src_file_length = (int)this.poModule.getFileLength(); - int _current_record_length = this.poModule.getRecordLength(); - _awaiting_file_length = (_src_file_length - (_current_record_length + DDFConstants.DDF_FOOTER_SIZE)); - - } catch (IOException e) { - e.printStackTrace(); - return fileLength; - } - - return _awaiting_file_length; - } - - /** - * Find the named field within this record. - * - * @param pszName The name of the field to fetch. The comparison - * is case insensitive. - * @param iFieldIndex The instance of this field to fetch. Use - * zero (the default) for the first instance. - * - * @return Pointer to the requested DDFField. This pointer is to - * an internal object, and should not be freed. It remains - * valid until the next record read. - */ - public DDFField findField(String pszName, int iFieldIndex) { - for (Iterator it = paoFields.iterator(); it.hasNext();) { - DDFField ddff = (DDFField) it.next(); - if (pszName.equalsIgnoreCase(ddff.getFieldDefn().getName())) { - if (iFieldIndex == 0) { - return ddff; - } else { - iFieldIndex--; - } - } - } - return null; - } - - /** - * Fetch field object based on index. - * - * @param i The index of the field to fetch. Between 0 and - * GetFieldCount()-1. - * - * @return A DDFField pointer, or null if the index is out of - * range. - */ - public DDFField getField(int i) { - try { - return (DDFField) paoFields.elementAt(i); - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } - } - - /** - * Get an iterator over the fields. - */ - public Iterator iterator() { - if (paoFields != null) { - return paoFields.iterator(); - } - return null; - } - - /** - * Fetch value of a subfield as an integer. This is a convenience - * function for fetching a subfield of a field within this record. - * - * @param pszField The name of the field containing the subfield. - * @param iFieldIndex The instance of this field within the - * record. Use zero for the first instance of this field. - * @param pszSubfield The name of the subfield within the selected - * field. - * @param iSubfieldIndex The instance of this subfield within the - * record. Use zero for the first instance. - * @return The value of the subfield, or zero if it failed for - * some reason. - */ - public int getIntSubfield(String pszField, int iFieldIndex, - String pszSubfield, int iSubfieldIndex) { - DDFField poField; - - /* -------------------------------------------------------------------- */ - /* Fetch the field. If this fails, return zero. */ - /* -------------------------------------------------------------------- */ - poField = findField(pszField, iFieldIndex); - if (poField == null) { - return 0; - } - - /* -------------------------------------------------------------------- */ - /* Get the subfield definition */ - /* -------------------------------------------------------------------- */ - - DDFSubfieldDefinition poSFDefn = poField.getFieldDefn() - .findSubfieldDefn(pszSubfield); - - if (poSFDefn == null) { - return 0; - } - - /* -------------------------------------------------------------------- */ - /* Get a pointer to the data. */ - /* -------------------------------------------------------------------- */ - MutableInt nBytesRemaining = new MutableInt(); - - byte[] pachData = poField.getSubfieldData(poSFDefn, - nBytesRemaining, - iSubfieldIndex); - - /* -------------------------------------------------------------------- */ - /* Return the extracted value. */ - /* -------------------------------------------------------------------- */ - - return poSFDefn.extractIntData(pachData, nBytesRemaining.value, null); - } - - /** - * Fetch value of a subfield as a float (double). This is a - * convenience function for fetching a subfield of a field within - * this record. - * - * @param pszField The name of the field containing the subfield. - * @param iFieldIndex The instance of this field within the - * record. Use zero for the first instance of this field. - * @param pszSubfield The name of the subfield within the selected - * field. - * @param iSubfieldIndex The instance of this subfield within the - * record. Use zero for the first instance. - * @return The value of the subfield, or zero if it failed for - * some reason. - */ - public double getFloatSubfield(String pszField, int iFieldIndex, - String pszSubfield, int iSubfieldIndex) { - DDFField poField; - - /* -------------------------------------------------------------------- */ - /* Fetch the field. If this fails, return zero. */ - /* -------------------------------------------------------------------- */ - poField = findField(pszField, iFieldIndex); - if (poField == null) { - return 0; - } - - /* -------------------------------------------------------------------- */ - /* Get the subfield definition */ - /* -------------------------------------------------------------------- */ - DDFSubfieldDefinition poSFDefn = poField.getFieldDefn() - .findSubfieldDefn(pszSubfield); - - if (poSFDefn == null) { - return 0; - } - - /* -------------------------------------------------------------------- */ - /* Get a pointer to the data. */ - /* -------------------------------------------------------------------- */ - MutableInt nBytesRemaining = new MutableInt(); - - byte[] pachData = poField.getSubfieldData(poSFDefn, - nBytesRemaining, - iSubfieldIndex); - - /* -------------------------------------------------------------------- */ - /* Return the extracted value. */ - /* -------------------------------------------------------------------- */ - return poSFDefn.extractFloatData(pachData, nBytesRemaining.value, null); - } - - /** - * Fetch value of a subfield as a string. This is a convenience - * function for fetching a subfield of a field within this record. - * - * @param pszField The name of the field containing the subfield. - * @param iFieldIndex The instance of this field within the - * record. Use zero for the first instance of this field. - * @param pszSubfield The name of the subfield within the selected - * field. - * @param iSubfieldIndex The instance of this subfield within the - * record. Use zero for the first instance. - * @return The value of the subfield, or null if it failed for - * some reason. The returned pointer is to internal data - * and should not be modified or freed by the application. - */ - - String getStringSubfield(String pszField, int iFieldIndex, - String pszSubfield, int iSubfieldIndex) { - - DDFField poField; - - /* -------------------------------------------------------------------- */ - /* Fetch the field. If this fails, return zero. */ - /* -------------------------------------------------------------------- */ - poField = findField(pszField, iFieldIndex); - if (poField == null) { - return null; - } - - /* -------------------------------------------------------------------- */ - /* Get the subfield definition */ - /* -------------------------------------------------------------------- */ - DDFSubfieldDefinition poSFDefn = poField.getFieldDefn() - .findSubfieldDefn(pszSubfield); - - if (poSFDefn == null) { - return null; - } - - /* -------------------------------------------------------------------- */ - /* Get a pointer to the data. */ - /* -------------------------------------------------------------------- */ - MutableInt nBytesRemaining = new MutableInt(); - - byte[] pachData = poField.getSubfieldData(poSFDefn, - nBytesRemaining, - iSubfieldIndex); - - /* -------------------------------------------------------------------- */ - /* Return the extracted value. */ - /* -------------------------------------------------------------------- */ - - return poSFDefn.extractStringData(pachData, nBytesRemaining.value, null); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfield.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfield.java deleted file mode 100644 index f518b6033..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfield.java +++ /dev/null @@ -1,156 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/iso8211/DDFSubfield.java,v $ -// $RCSfile: DDFSubfield.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:43 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.iso8211; - -import com.bbn.openmap.layer.vpf.MutableInt; - -/** - * Class containing subfield information for a DDFField object. - */ -public class DDFSubfield { - - /** - * A DDFSubfieldDefinition defining the admin part of the file - * that contains the subfield data. - */ - protected DDFSubfieldDefinition defn; - /** - * The object containing the value of the field. - */ - protected Object value; - /** - * The number of bytes the field took up in the data file. - */ - protected int byteSize; - - protected DDFSubfield() {} - - /** - * Create a subfield with a definition and a value. - */ - public DDFSubfield(DDFSubfieldDefinition ddfsd, Object value) { - setDefn(ddfsd); - setValue(value); - } - - /** - * Create a subfield with a definition and the bytes containing - * the information for the value. The definition parameters will - * tell the DDFSubfield what kind of object to create for the - * data. - */ - public DDFSubfield(DDFSubfieldDefinition poSFDefn, byte[] pachFieldData, - int nBytesRemaining) { - defn = poSFDefn; - MutableInt nBytesConsumed = new MutableInt(); - DDFDataType ddfdt = poSFDefn.getType(); - - if (ddfdt == DDFDataType.DDFInt) { - setValue(new Integer(defn.extractIntData(pachFieldData, - nBytesRemaining, - nBytesConsumed))); - } else if (ddfdt == DDFDataType.DDFFloat) { - setValue(new Double(defn.extractFloatData(pachFieldData, - nBytesRemaining, - nBytesConsumed))); - } else if (ddfdt == DDFDataType.DDFString - || ddfdt == DDFDataType.DDFBinaryString) { - setValue(defn.extractStringData(pachFieldData, - nBytesRemaining, - nBytesConsumed)); - } - - byteSize = nBytesConsumed.value; - } - - public int getByteSize() { - return byteSize; - } - - public void setDefn(DDFSubfieldDefinition ddsfd) { - defn = ddsfd; - } - - public DDFSubfieldDefinition getDefn() { - return defn; - } - - /** - * Set the value of the subfield. - */ - public void setValue(Object o) { - value = o; - } - - /** - * Get the value of the subfield. - */ - public Object getValue() { - return value; - } - - /** - * Get the value of the subfield as an int. Returns 0 if the value - * is 0 or isn't a number. - */ - public int intValue() { - Object obj = getValue(); - if (obj instanceof Number) { - return ((Number) obj).intValue(); - } - return 0; - } - - /** - * Get the value of the subfield as a float. Returns 0f if the - * value is 0 or isn't a number. - */ - public float floatValue() { - Object obj = getValue(); - if (obj instanceof Number) { - return ((Number) obj).floatValue(); - } - return 0f; - } - - public String stringValue() { - Object obj = getValue(); - - if (obj != null) { - return obj.toString(); - } - - return ""; - } - - /** - * Return a string 'key = value', describing the field and its - * value. - */ - public String toString() { - if (defn != null) { - return defn.getName() + " = " + value; - } - return ""; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfieldDefinition.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfieldDefinition.java deleted file mode 100644 index 837d3c596..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFSubfieldDefinition.java +++ /dev/null @@ -1,679 +0,0 @@ -/****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ******************************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import com.bbn.openmap.layer.vpf.MutableInt; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Information from the DDR record describing one subfield of a DDFFieldDefn. - * All subfields of a field will occur in each occurrence of that field (as a - * DDFField) in a DDFRecord. Subfield's actually contain formatted data (as - * instances within a record). - * - * @author Guillaume Pelletier provided fix for Big Endian support (important - * for S-57) - */ -public class DDFSubfieldDefinition implements DDFConstants { - - protected String pszName; // a.k.a. subfield mnemonic - protected String pszFormatString; - protected DDFDataType eType; - protected int eBinaryFormat; - - /** - * bIsVariable determines whether we using the chFormatDelimeter (true), or - * the fixed width (false). - */ - protected boolean bIsVariable; - - protected char chFormatDelimeter; - protected int nFormatWidth; - - public interface DDFBinaryFormat { - public final static int NotBinary = 0; - public final static int UInt = 1; - public final static int SInt = 2; - public final static int FPReal = 3; - public final static int FloatReal = 4; - public final static int FloatComplex = 5; - } - - public int getWidth() { - return nFormatWidth; - } - - /** Get pointer to subfield name. */ - public String getName() { - return pszName; - } - - /** Get pointer to subfield format string */ - public String getFormat() { - return pszFormatString; - } - - /** - * Get the general type of the subfield. This can be used to determine which - * of ExtractFloatData(), ExtractIntData() or ExtractStringData() should be - * used. - * - * @return The subfield type. One of DDFInt, DDFFloat, DDFString or - * DDFBinaryString. - */ - public DDFDataType getType() { - return eType; - } - - public DDFSubfieldDefinition() { - pszName = null; - - bIsVariable = true; - nFormatWidth = 0; - chFormatDelimeter = DDF_UNIT_TERMINATOR; - eBinaryFormat = DDFBinaryFormat.NotBinary; - eType = DDFDataType.DDFString; - - pszFormatString = new String(""); - } - - /** - * Set the name of the subfield. - */ - public void setName(String pszNewName) { - pszName = pszNewName.trim(); - } - - /** - * While interpreting the format string we don't support: - *

    - *
  • Passing an explicit terminator for variable length field. - *
  • 'X' for unused data ... this should really be filtered - *
  • out by DDFFieldDefinition.applyFormats(), but isn't. - *
  • 'B' bitstrings that aren't a multiple of eight. - *
- */ - public boolean setFormat(String pszFormat) { - pszFormatString = pszFormat; - - if (Debug.debugging("iso8211")) { - Debug.output("DDFSubfieldDefinition.setFormat(" + pszFormat + ")"); - } - - /* -------------------------------------------------------------------- */ - /* These values will likely be used. */ - /* -------------------------------------------------------------------- */ - if (pszFormatString.length() > 1 && pszFormatString.charAt(1) == '(') { - - // Need to loop through characters to grab digits, and - // then get integer version. If we look a the atoi code, - // it checks for non-digit characters and then stops. - int i = 3; - for (; i < pszFormat.length() - && Character.isDigit(pszFormat.charAt(i)); i++) { - } - - nFormatWidth = Integer.parseInt(pszFormat.substring(2, i)); - bIsVariable = (nFormatWidth == 0); - } else { - bIsVariable = true; - } - - /* -------------------------------------------------------------------- */ - /* Interpret the format string. */ - /* -------------------------------------------------------------------- */ - switch (pszFormatString.charAt(0)) { - - case 'A': - case 'C': // It isn't clear to me how this is different than - // 'A' - eType = DDFDataType.DDFString; - break; - - case 'R': - eType = DDFDataType.DDFFloat; - break; - - case 'I': - case 'S': - eType = DDFDataType.DDFInt; - break; - - case 'B': - case 'b': - // Is the width expressed in bits? (is it a bitstring) - bIsVariable = false; - if (pszFormatString.charAt(1) == '(') { - - int numEndIndex = 2; - for (; numEndIndex < pszFormatString.length() - && Character.isDigit(pszFormatString - .charAt(numEndIndex)); numEndIndex++) { - } - - String numberString = pszFormatString.substring(2, numEndIndex); - nFormatWidth = Integer.valueOf(numberString).intValue(); - - if (nFormatWidth % 8 != 0) { - Debug - .error("DDFSubfieldDefinition.setFormat() problem with " - + pszFormatString.charAt(0) - + " not being modded with 8 evenly"); - return false; - } - - nFormatWidth = Integer.parseInt(numberString) / 8; - - eBinaryFormat = DDFBinaryFormat.SInt; // good - // default, - // works for - // SDTS. - - if (nFormatWidth < 5) { - eType = DDFDataType.DDFInt; - } else { - eType = DDFDataType.DDFBinaryString; - } - - } else { // or do we have a binary type indicator? (is it binary) - - eBinaryFormat = (int) (pszFormatString.charAt(1) - '0'); - - int numEndIndex = 2; - for (; numEndIndex < pszFormatString.length() - && Character.isDigit(pszFormatString - .charAt(numEndIndex)); numEndIndex++) { - } - - nFormatWidth = Integer.valueOf( - pszFormatString - .substring(2, - numEndIndex)) - .intValue(); - - if (eBinaryFormat == DDFBinaryFormat.SInt - || eBinaryFormat == DDFBinaryFormat.UInt) { - - eType = DDFDataType.DDFInt; - } else { - eType = DDFDataType.DDFFloat; - } - } - break; - - case 'X': - // 'X' is extra space, and shouldn't be directly assigned - // to a - // subfield ... I haven't encountered it in use yet - // though. - Debug.error("DDFSubfieldDefinition: Format type of " - + pszFormatString.charAt(0) + " not supported."); - - return false; - default: - Debug.error("DDFSubfieldDefinition: Format type of " - + pszFormatString.charAt(0) + " not recognised."); - return false; - } - - return true; - } - - /** - * Write out subfield definition info. A variety of information about this - * field definition is written to the give debugging file handle. - */ - public String toString() { - StringBuffer buf = new StringBuffer(" DDFSubfieldDefn:\n"); - buf.append(" Label = ").append(pszName).append("\n"); - buf.append(" FormatString = ").append(pszFormatString).append("\n"); - return buf.toString(); - } - - /** - * Scan for the end of variable length data. Given a pointer to the data for - * this subfield (from within a DDFRecord) this method will return the - * number of bytes which are data for this subfield. The number of bytes - * consumed as part of this field can also be fetched. This number may be - * one longer than the length if there is a terminator character used. - *

- * - * This method is mainly for internal use, or for applications which want - * the raw binary data to interpret themselves. Otherwise use one of - * ExtractStringData(), ExtractIntData() or ExtractFloatData(). - * - * @param pachSourceData - * The pointer to the raw data for this field. This may have come - * from DDFRecord::GetData(), taking into account skip factors - * over previous subfields data. - * @param nMaxBytes - * The maximum number of bytes that are accessible after - * pachSourceData. - * @param pnConsumedBytes - * the number of bytes used. - * - * @return The number of bytes at pachSourceData which are actual data for - * this record (not including unit, or field terminator). - */ - public int getDataLength(byte[] pachSourceData, int nMaxBytes, - MutableInt pnConsumedBytes) { - if (!bIsVariable) { - if (nFormatWidth > nMaxBytes) { - Debug.error("DDFSubfieldDefinition: Only " + nMaxBytes - + " bytes available for subfield " + pszName - + " with format string " + pszFormatString - + " ... returning shortened data."); - - if (pnConsumedBytes != null) { - pnConsumedBytes.value = nMaxBytes; - } - - return nMaxBytes; - } else { - - if (pnConsumedBytes != null) { - pnConsumedBytes.value = nFormatWidth; - } - - return nFormatWidth; - } - - } else { - - int nLength = 0; - boolean bCheckFieldTerminator = true; - - /* - * We only check for the field terminator because of some buggy - * datasets with missing format terminators. However, we have found - * the field terminator is a legal character within the fields of - * some extended datasets (such as JP34NC94.000). So we don't check - * for the field terminator if the field appears to be multi-byte - * which we established by the first character being out of the - * ASCII printable range (32-127). - */ - - if (pachSourceData[0] < 32 || pachSourceData[0] >= 127) { - bCheckFieldTerminator = false; - } - - while (nLength < nMaxBytes - && pachSourceData[nLength] != chFormatDelimeter) { - - if (bCheckFieldTerminator - && pachSourceData[nLength] == DDF_FIELD_TERMINATOR) - break; - - nLength++; - } - - if (pnConsumedBytes != null) { - if (nMaxBytes == 0) { - pnConsumedBytes.value = nLength; - } else { - pnConsumedBytes.value = nLength + 1; - } - } - - return nLength; - } - } - - /** - * Extract a zero terminated string containing the data for this subfield. - * Given a pointer to the data for this subfield (from within a DDFRecord) - * this method will return the data for this subfield. The number of bytes - * consumed as part of this field can also be fetched. This number may be - * one longer than the string length if there is a terminator character - * used. - *

- * - * This function will return the raw binary data of a subfield for types - * other than DDFString, including data past zero chars. This is the - * standard way of extracting DDFBinaryString subfields for instance. - *

- * - * @param pachSourceData - * The pointer to the raw data for this field. This may have come - * from DDFRecord::GetData(), taking into account skip factors - * over previous subfields data. - * @param nMaxBytes - * The maximum number of bytes that are accessible after - * pachSourceData. - * @param pnConsumedBytes - * Pointer to an integer into which the number of bytes consumed - * by this field should be written. May be null to ignore. This - * is used as a skip factor to increment pachSourceData to point - * to the next subfields data. - * - * @return A pointer to a buffer containing the data for this field. The - * returned pointer is to an internal buffer which is invalidated on - * the next ExtractStringData() call on this DDFSubfieldDefn(). It - * should not be freed by the application. - */ - String extractStringData(byte[] pachSourceData, int nMaxBytes, - MutableInt pnConsumedBytes) { - int oldConsumed = 0; - if (pnConsumedBytes != null) { - oldConsumed = pnConsumedBytes.value; - } - - int nLength = getDataLength(pachSourceData, nMaxBytes, pnConsumedBytes); - String ns = new String(pachSourceData, 0, nLength); - - if (Debug.debugging("iso8211detail") && pnConsumedBytes != null) { - Debug.output(" extracting string data from " + nLength - + " bytes of " + pachSourceData.length + ": " + ns - + ": consumed " + pnConsumedBytes.value + " vs. " - + oldConsumed + ", max = " + nMaxBytes); - } - - return ns; - } - - /** - * Extract a subfield value as a float. Given a pointer to the data for this - * subfield (from within a DDFRecord) this method will return the floating - * point data for this subfield. The number of bytes consumed as part of - * this field can also be fetched. This method may be called for any type of - * subfield, and will return zero if the subfield is not numeric. - * - * @param pachSourceData - * The pointer to the raw data for this field. This may have come - * from DDFRecord::GetData(), taking into account skip factors - * over previous subfields data. - * @param nMaxBytes - * The maximum number of bytes that are accessible after - * pachSourceData. - * @param pnConsumedBytes - * Pointer to an integer into which the number of bytes consumed - * by this field should be written. May be null to ignore. This - * is used as a skip factor to increment pachSourceData to point - * to the next subfields data. - * - * @return The subfield's numeric value (or zero if it isn't numeric). - */ - public double extractFloatData(byte[] pachSourceData, int nMaxBytes, - MutableInt pnConsumedBytes) { - - switch (pszFormatString.charAt(0)) { - case 'A': - case 'I': - case 'R': - case 'S': - case 'C': - String dataString = extractStringData(pachSourceData, nMaxBytes, - pnConsumedBytes); - - if (dataString.length() == 0) { - return 0; - } - - try { - return Double.parseDouble(dataString); - } catch (NumberFormatException nfe) { - if (Debug.debugging("iso8211")) { - Debug - .output("DDFSubfieldDefinition.extractFloatData: number format problem: " - + dataString); - } - return 0; - } - - case 'B': - case 'b': - byte[] abyData = new byte[8]; - - if (pnConsumedBytes != null) { - pnConsumedBytes.value = nFormatWidth; - } - - if (nFormatWidth > nMaxBytes) { - Debug - .error("DDFSubfieldDefinition: format width is greater than max bytes for float"); - return 0.0; - } - - // Byte swap the data if it isn't in machine native - // format. In any event we copy it into our buffer to - // ensure it is word aligned. - // - // DFD - don't think this applies to Java, since it's - // always big endian - - // if (pszFormatString.charAt(0) == 'B') || - // (pszFormatString.charAt(0) == 'b') { - // for (int i = 0; i < nFormatWidth; i++) { - // abyData[nFormatWidth-i-1] = pachSourceData[i]; - // } - // } else { - // System.arraycopy(pachSourceData, 0, abyData, 8-nFormatWidth, - // nFormatWidth); - System.arraycopy(pachSourceData, 0, abyData, 0, nFormatWidth); - // } - - // Interpret the bytes of data. - switch (eBinaryFormat) { - case DDFBinaryFormat.UInt: - case DDFBinaryFormat.SInt: - case DDFBinaryFormat.FloatReal: - return (int) pszFormatString.charAt(0) == 'B' ? MoreMath - .BuildIntegerBE(abyData) : MoreMath - .BuildIntegerLE(abyData); - - // if (nFormatWidth == 1) - // return(abyData[0]); - // else if (nFormatWidth == 2) - // return(*((GUInt16 *) abyData)); - // else if (nFormatWidth == 4) - // return(*((GUInt32 *) abyData)); - // else { - // return 0.0; - // } - - // case DDFBinaryFormat.SInt: - // if (nFormatWidth == 1) - // return(*((signed char *) abyData)); - // else if (nFormatWidth == 2) - // return(*((GInt16 *) abyData)); - // else if (nFormatWidth == 4) - // return(*((GInt32 *) abyData)); - // else { - // return 0.0; - // } - - // case DDFBinaryFormat.FloatReal: - // if (nFormatWidth == 4) - // return(*((float *) abyData)); - // else if (nFormatWidth == 8) - // return(*((double *) abyData)); - // else { - // return 0.0; - // } - - case DDFBinaryFormat.NotBinary: - case DDFBinaryFormat.FPReal: - case DDFBinaryFormat.FloatComplex: - return 0.0; - } - break; - // end of 'b'/'B' case. - - default: - - } - - return 0.0; - } - - /** - * Extract a subfield value as an integer. Given a pointer to the data for - * this subfield (from within a DDFRecord) this method will return the int - * data for this subfield. The number of bytes consumed as part of this - * field can also be fetched. This method may be called for any type of - * subfield, and will return zero if the subfield is not numeric. - * - * @param pachSourceData - * The pointer to the raw data for this field. This may have come - * from DDFRecord::GetData(), taking into account skip factors - * over previous subfields data. - * @param nMaxBytes - * The maximum number of bytes that are accessible after - * pachSourceData. - * @param pnConsumedBytes - * Pointer to an integer into which the number of bytes consumed - * by this field should be written. May be null to ignore. This - * is used as a skip factor to increment pachSourceData to point - * to the next subfields data. - * - * @return The subfield's numeric value (or zero if it isn't numeric). - */ - public int extractIntData(byte[] pachSourceData, int nMaxBytes, - MutableInt pnConsumedBytes) { - - switch (pszFormatString.charAt(0)) { - case 'A': - case 'I': - case 'R': - case 'S': - case 'C': - String dataString = extractStringData(pachSourceData, nMaxBytes, - pnConsumedBytes); - if (dataString.length() == 0) { - return 0; - } - - try { - return Double.valueOf(dataString).intValue(); - } catch (NumberFormatException nfe) { - if (Debug.debugging("iso8211")) { - Debug - .output("DDFSubfieldDefinition.extractIntData: number format problem: " - + dataString); - } - return 0; - } - - case 'B': - case 'b': - byte[] abyData = new byte[4]; - if (nFormatWidth > nMaxBytes) { - Debug - .error("DDFSubfieldDefinition: format width is greater than max bytes for int"); - return 0; - } - - if (pnConsumedBytes != null) { - pnConsumedBytes.value = nFormatWidth; - } - - // System.arraycopy(pachSourceData, 0, abyData, 4-nFormatWidth, - // nFormatWidth); - System.arraycopy(pachSourceData, 0, abyData, 0, nFormatWidth); - - // Interpret the bytes of data. - switch (eBinaryFormat) { - case DDFBinaryFormat.UInt: - case DDFBinaryFormat.SInt: - case DDFBinaryFormat.FloatReal: - return (int) pszFormatString.charAt(0) == 'B' ? MoreMath - .BuildIntegerBE(abyData) : MoreMath - .BuildIntegerLE(abyData); - - // case DDFBinaryFormat.UInt: - // if (nFormatWidth == 4) - // return((int) *((GUInt32 *) abyData)); - // else if (nFormatWidth == 1) - // return(abyData[0]); - // else if (nFormatWidth == 2) - // return(*((GUInt16 *) abyData)); - // else { - // CPLAssert(false); - // return 0; - // } - - // case DDFBinaryFormat.SInt: - // if (nFormatWidth == 4) - // return(*((GInt32 *) abyData)); - // else if (nFormatWidth == 1) - // return(*((signed char *) abyData)); - // else if (nFormatWidth == 2) - // return(*((GInt16 *) abyData)); - // else { - // CPLAssert(false); - // return 0; - // } - - // case DDFBinaryFormat.FloatReal: - // if (nFormatWidth == 4) - // return((int) *((float *) abyData)); - // else if (nFormatWidth == 8) - // return((int) *((double *) abyData)); - // else { - // CPLAssert(false); - // return 0; - // } - - case DDFBinaryFormat.NotBinary: - case DDFBinaryFormat.FPReal: - case DDFBinaryFormat.FloatComplex: - return 0; - } - break; - // end of 'b'/'B' case. - - default: - return 0; - } - - return 0; - } - - /** - * Dump subfield value to debugging file. - * - * @param pachData - * Pointer to data for this subfield. - * @param nMaxBytes - * Maximum number of bytes available in pachData. - */ - public String dumpData(byte[] pachData, int nMaxBytes) { - StringBuffer sb = new StringBuffer(); - if (eType == DDFDataType.DDFFloat) { - sb.append(" Subfield ").append(pszName).append("=") - .append(extractFloatData(pachData, nMaxBytes, null)).append("\n"); - } else if (eType == DDFDataType.DDFInt) { - sb.append(" Subfield ").append(pszName).append("=") - .append(extractIntData(pachData, nMaxBytes, null)).append("\n"); - } else if (eType == DDFDataType.DDFBinaryString) { - sb.append(" Subfield ").append(pszName).append("=") - .append(extractStringData(pachData, nMaxBytes, null)).append("\n"); - } else { - sb.append(" Subfield ").append(pszName).append("=") - .append(extractStringData(pachData, nMaxBytes, null)).append("\n"); - } - return sb.toString(); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFUtils.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFUtils.java deleted file mode 100644 index cf83c5fae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/DDFUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/********************************************************************* - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - ********************************************************************/ - -package com.bbn.openmap.dataAccess.iso8211; - -import com.bbn.openmap.layer.vpf.MutableInt; - -public class DDFUtils { - /** ********************************************************************* */ - /* DDFScanVariable() */ - /* */ - /* Establish the length of a variable length string in a */ - /* record. */ - /** ********************************************************************* */ - - public static int scanVariable(byte[] pszRecord, int nMaxChars, - char nDelimChar) { - int i; - for (i = 0; i < nMaxChars - 1 && pszRecord[i] != nDelimChar; i++) { - } - return i; - } - - /** ********************************************************************* */ - /* DDFFetchVariable() */ - /* */ - /* Fetch a variable length string from a record, and allocate */ - /* it as a new string (with CPLStrdup()). */ - /** ********************************************************************* */ - - public static String fetchVariable(byte[] pszRecord, int nMaxChars, - char nDelimChar1, char nDelimChar2, - MutableInt pnConsumedChars) { - int i; - - for (i = 0; i < nMaxChars - 1 && pszRecord[i] != nDelimChar1 - && pszRecord[i] != nDelimChar2; i++) { - } - - pnConsumedChars.value = i; - if (i < nMaxChars - && (pszRecord[i] == nDelimChar1 || pszRecord[i] == nDelimChar2)) { - pnConsumedChars.value++; - } - - byte[] pszReturnBytes = new byte[i]; - System.arraycopy(pszRecord, 0, pszReturnBytes, 0, i); - - return new String(pszReturnBytes); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/View8211.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/View8211.java deleted file mode 100644 index 3dfbfffd6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/View8211.java +++ /dev/null @@ -1,183 +0,0 @@ -/* **************************************************************************** - * $Id: View8211.java,v 1.5 2005/08/04 18:12:00 dietrick Exp $ - * - * Project: SDTS Translator - * Purpose: Example program dumping data in 8211 data to stdout. - * Author: Frank Warmerdam, warmerda@home.com - * - ****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ****************************************************************************** - */ - -package com.bbn.openmap.dataAccess.iso8211; - -import java.io.IOException; -import java.util.Iterator; - -import com.bbn.openmap.layer.vpf.MutableInt; -import com.bbn.openmap.util.Debug; - -/** - * Class that uses the DDF* classes to read an 8211 file and print out the - * contents. - */ -public class View8211 { - - protected boolean bFSPTHack = false; - protected String pszFilename = null; - - public View8211(String filename, boolean fspt_repeating) { - pszFilename = filename; - bFSPTHack = fspt_repeating; - - view(); - } - - protected void view() { - DDFModule oModule; - - try { - - oModule = new DDFModule(pszFilename); - - if (bFSPTHack) { - DDFFieldDefinition poFSPT = oModule.findFieldDefn("FSPT"); - - if (poFSPT == null) - Debug.error("View8211: unable to find FSPT field to set repeating flag."); - else - poFSPT.setRepeating(true); - } - - /* -------------------------------------------------------------------- */ - /* Loop reading records till there are none left. */ - /* -------------------------------------------------------------------- */ - DDFRecord poRecord; - int iRecord = 1; - - while ((poRecord = oModule.readRecord()) != null) { - Debug.output("Record " + (iRecord++) + "(" + poRecord.getDataSize() + " bytes)"); - - /* ------------------------------------------------------------ */ - /* Loop over each field in this particular record. */ - /* ------------------------------------------------------------ */ - for (Iterator it = poRecord.iterator(); it != null && it.hasNext();) { - // Debug.output(((DDFField)it.next()).toString())); - viewRecordField(((DDFField) it.next())); - } - } - - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - ioe.printStackTrace(); - } - } - - /** - * Dump the contents of a field instance in a record. - */ - protected void viewRecordField(DDFField poField) { - DDFFieldDefinition poFieldDefn = poField.getFieldDefn(); - - // Report general information about the field. - Debug.output(" Field " + poFieldDefn.getName() + ": " + poFieldDefn.getDescription()); - - // Get pointer to this fields raw data. We will move through - // it consuming data as we report subfield values. - - byte[] pachFieldData = poField.getData(); - int nBytesRemaining = poField.getDataSize(); - - /* -------------------------------------------------------- */ - /* Loop over the repeat count for this fields */ - /* subfields. The repeat count will almost */ - /* always be one. */ - /* -------------------------------------------------------- */ - for (int iRepeat = 0; iRepeat < poField.getRepeatCount(); iRepeat++) { - if (iRepeat > 0) { - Debug.output("Repeating (" + iRepeat + ")..."); - } - /* -------------------------------------------------------- */ - /* Loop over all the subfields of this field, advancing */ - /* the data pointer as we consume data. */ - /* -------------------------------------------------------- */ - for (int iSF = 0; iSF < poFieldDefn.getSubfieldCount(); iSF++) { - - DDFSubfieldDefinition poSFDefn = poFieldDefn.getSubfieldDefn(iSF); - int nBytesConsumed = viewSubfield(poSFDefn, pachFieldData, nBytesRemaining); - nBytesRemaining -= nBytesConsumed; - byte[] tempData = new byte[pachFieldData.length - nBytesConsumed]; - System.arraycopy(pachFieldData, nBytesConsumed, tempData, 0, tempData.length); - pachFieldData = tempData; - } - } - } - - protected int viewSubfield(DDFSubfieldDefinition poSFDefn, byte[] pachFieldData, int nBytesRemaining) { - - MutableInt nBytesConsumed = new MutableInt(); - - DDFDataType ddfdt = poSFDefn.getType(); - - if (ddfdt == DDFDataType.DDFInt) { - Debug.output(" " + poSFDefn.getName() + " = " - + poSFDefn.extractIntData(pachFieldData, nBytesRemaining, nBytesConsumed)); - } else if (ddfdt == DDFDataType.DDFFloat) { - Debug.output(" " + poSFDefn.getName() + " = " - + poSFDefn.extractFloatData(pachFieldData, nBytesRemaining, nBytesConsumed)); - } else if (ddfdt == DDFDataType.DDFString) { - Debug.output(" " + poSFDefn.getName() + " = " - + poSFDefn.extractStringData(pachFieldData, nBytesRemaining, nBytesConsumed)); - } else if (ddfdt == DDFDataType.DDFBinaryString) { - poSFDefn.extractStringData(pachFieldData, nBytesRemaining, nBytesConsumed); // pabyBString - - Debug.output(" " + poSFDefn.getName()); - } - - return nBytesConsumed.value; - } - - public static void main(String[] argv) { - - Debug.init(); - - String pszFilename = null; - boolean bFSPTHack = false; - - for (int iArg = 0; iArg < argv.length; iArg++) { - if (argv[iArg].equals("-fspt_repeating")) { - bFSPTHack = true; - } else { - pszFilename = argv[iArg]; - } - } - - if (pszFilename == null) { - Debug.output("Usage: View8211 filename\n"); - System.exit(1); - } - - new View8211(pszFilename, bFSPTHack); - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/package.html deleted file mode 100644 index f98b7501c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/iso8211/package.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - -This is a package containing classes that parse ISO 8211 files. This -code was ported from the iso8211lib-1.1 package created by Frank -Warmerdam, with the following copyright notice:

-
-
-/******************************************************************************
- * Copyright (c) 1999, Frank Warmerdam
- *
- * 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.
- ******************************************************************************/
-
- - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/AbstractMapTileCoordinateTransform.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/AbstractMapTileCoordinateTransform.java deleted file mode 100644 index 4ce1ca65f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/AbstractMapTileCoordinateTransform.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * An abstraction of MapTileCoordinateTransform that combines the identical - * methods of OSM and TMS MapTileCoordinateTransforms. - * - * @author dietrick - */ -public abstract class AbstractMapTileCoordinateTransform implements MapTileCoordinateTransform { - - int tileSize = TILE_SIZE; - /** - * The zoom level tile size is used by the factory to determine when it - * needs to get tiles for a different zoom level. The default value is 350. - * That is, when the factory is figuring out what zoom level to use, if the - * pixel size of a tile is greater than or equal to 350 x 350, it decides to - * check the next zoom level for retrieving tiles. This is used instead of - * just comparing projection scales. - */ - int DEFAULT_ZOOM_LEVEL_TILE_SIZE = 350; - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform#latLonToTileUV - * (java.awt.geom.Point2D, int) - */ - public Point2D latLonToTileUV(Point2D latlon, int zoom) { - return latLonToTileUV(latlon, zoom, null); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform#tileUVToLatLon - * (java.awt.geom.Point2D, int) - */ - public Point2D tileUVToLatLon(Point2D tileUV, int zoom) { - return tileUVToLatLon(tileUV, zoom, null); - } - - /** - * Return a scale value for the transforming projection, given a discrete - * zoom level. - * - * @param zoom level - * @return scale value. - */ - public float getScaleForZoom(int zoom) { - Projection proj = new Mercator(new LatLonPoint.Double(), 1000000, TILE_SIZE, TILE_SIZE); - return getScaleForZoomAndProjection(proj, zoom); - } - - /** - * Get the scale value for a Projection and discrete zoom level. - * - * @param proj the projection to use for scale calculations. - * @param zoom the discrete zoom level. - * @return scale value for the given projection. - */ - public float getScaleForZoomAndProjection(Projection proj, int zoom) { - MapTileCoordinateTransform mtct = new OSMMapTileCoordinateTransform(); - Point2D originLLUL = mtct.tileUVToLatLon(new Point2D.Double(0.0, 0.0), zoom); - Point2D originLLLR = mtct.tileUVToLatLon(new Point2D.Double(1.0, 1.0), zoom); - return proj.getScale(originLLUL, originLLLR, UVUL, UVLR); - } - - /** - * Given a projection, figure out the appropriate zoom level for it. Right - * now, 0 is totally zoomed with one tile for the entire earth. But we don't - * return 0, we start at 1. OM can't handle one tile that covers the entire - * earth because of the restriction for handling OMGraphics to less than - * half of the earth. - * - * @param proj - * @return the zoom level. - */ - public int getZoomLevelForProj(Projection proj) { - return getZoomLevelForProj(proj, DEFAULT_ZOOM_LEVEL_TILE_SIZE); - } - - /** - * Given a projection, figure out the appropriate zoom level for it. Right - * now, 0 is totally zoomed with one tile for the entire earth. But we don't - * return 0, we start at 1. OM can't handle one tile that covers the entire - * earth because of the restriction for handling OMGraphics to less than - * half of the earth. - * - * @param proj - * @param zoomLevelTileSize used for determining zoom levels, a kind of - * buffer around true zoom levels since the OpenMap layers scale - * images. - * @return the zoom level. - */ - public int getZoomLevelForProj(Projection proj, int zoomLevelTileSize) { - int low = getMinZoomLevelForProj(); - int high = getMaxZoomLevelForProj(); - - int ret = low; - for (int currentZoom = low; currentZoom <= high; currentZoom++) { - // nearest tile to center - Point2D nttc = latLonToTileUV(proj.getCenter(), currentZoom); - - double nttcX = Math.floor(nttc.getX()); - double nttcY = Math.floor(nttc.getY()); - Point2D originLLUL = tileUVToLatLon(new Point2D.Double(nttcX, nttcY), currentZoom); - Point2D originLLLR = tileUVToLatLon(new Point2D.Double(nttcX + 1, nttcY + 1), currentZoom); - - Point2D projUVUL = proj.forward(originLLUL); - Point2D projLLLR = proj.forward(originLLLR); - - if (Math.abs(projUVUL.getX() - projLLLR.getX()) <= zoomLevelTileSize) { - return currentZoom; - } - - /* - * Used to try to do this with scale comparisons, now just look at - * tile sizes. float diff = currentScale - scales[currentZoom]; if - * (diff > 0) { return currentZoom + 1; } - */ - } - - return ret; - } - - /** - * Returns the minimum zoom level for calculating the appropriate zoom - * level. - * - */ - protected int getMinZoomLevelForProj() { - return 1; - } - - /** - * Returns the maximum zoom level for calculating the appropriate zoom - * level. - * - */ - protected int getMaxZoomLevelForProj() { - return 20; - } - - /** - * Creates an array of scale values for different zoom levels. Make sure you - * don't reference the array outside of 0 and high zoom levels. There will - * be a high zoom level number of items in the array. - * - * @param proj - * @param highZoomLevel - * @return array, initialized for the low zoom level index to the high zoom - * level index. - */ - public float[] getScalesForZoomLevels(Projection proj, int highZoomLevel) { - float[] ret = new float[highZoomLevel + 1]; - for (int i = 0; i <= highZoomLevel; i++) { - ret[i] = getScaleForZoomAndProjection(proj, i); - } - return ret; - } - - /** - * Returns the tile size of the transform. - */ - public int getTileSize() { - return tileSize; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/DebugMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/DebugMapTileFactory.java deleted file mode 100644 index 530eb570d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/DebugMapTileFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.image.BufferedImage; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * A simple MapTileFactory that returns empty tiles with labels showing zoom - * level and x, y coords, and borders. This does the same thing as enabling the - * MAPTILE_DEBUGGING logger flag, but can be attached to a MapTileLayer which - * can be turned off and on. - *

- * The properties for the layer looke like this (with tileDebug as an example prefix): - * - *

- * tileDebug.class=com.bbn.openmap.layer.imageTile.MapTileLayer
- * tileDebug.prettyName=Map Tile Information
- * tileDebug.tileFactory=com.bbn.openmap.dataAccess.mapTile.DebugMapTileFactory
- * 
- * - * @author dietrick - */ -public class DebugMapTileFactory extends StandardMapTileFactory { - - public DebugMapTileFactory() { - rootDir = "EMPTYANDUNIMPORTANT"; - } - - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - String imagePath = (String) key; - BufferedImage bi = new BufferedImage(MapTileCoordinateTransform.TILE_SIZE, MapTileCoordinateTransform.TILE_SIZE, BufferedImage.TYPE_INT_ARGB); - OMGraphic raster; - try { - raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - - raster.putAttribute(OMGraphic.LABEL, new OMTextLabeler("Tile: " + zoomLevel + "|" - + x + "|" + y, OMText.JUSTIFY_CENTER)); - raster.setSelected(true); - - return new CacheObject(imagePath, raster); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/EmptyTileHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/EmptyTileHandler.java deleted file mode 100644 index 6d16a45bb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/EmptyTileHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.image.BufferedImage; - -import com.bbn.openmap.proj.Projection; - -/** - * An EmptyTileHandler is a class that helps the MapTileFactory figure out what - * to do with non-existent map tiles. - * - * @author ddietrick - */ -public interface EmptyTileHandler { - - /** - * The main call from the MapTileFactory to return something for the given - * missing tile. - * - * @param imagePath the path of the missing tile that is going to be used as - * cache lookup later. - * @param x the uv x coordinate of the tile. - * @param y the uv y coordinate of the tile. - * @param zoomLevel the zoom level of the tile. - * @param mtcTransform the transform that converts x,y coordinates to - * lat/lon and describes the layout of the uv tile coordinates. - * @param proj the map projection, in case that matters what should be - * returned for the empty tile. - * @return BufferedImage for image tile - */ - BufferedImage getImageForEmptyTile(String imagePath, int x, int y, int zoomLevel, MapTileCoordinateTransform mtcTransform, - Projection proj); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GoogleMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GoogleMapTileFactory.java deleted file mode 100644 index 9febd3aac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GoogleMapTileFactory.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.Properties; - -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * The GoogleMapTileFactory is a simple example of how to customize a - * MapTileFactory to contact other services. This MTF is set up to contact the - * Google static map server through the static maps API. If you don't provide - * your API key you will be shut off. See the documentation at - * https://developers.google.com/maps/documentation/staticmaps/, and read the - * usage agreement. - * - * Set the attribution property on the MapTileLayer, so the copyright shows up - * when the data is displayed. - * - * The additional properties of this class, which are added to the layer properties: - *
- * 
- * key=google_api_key
- * mapType=roadmap, terrain, satellite or hybrid
- * 
- * 
- * @author dietrick - */ -public class GoogleMapTileFactory extends ServerMapTileFactory { - - /** - * Set the api key to use for tracking/billing in the properties. - */ - public final static String API_KEY_PROPERTY = "key"; - /** - * Set the map type displayed in the properties. - */ - public final static String MAPTYPE_PROPERTY = "mapType"; - - String apiKey = null; - /* MapType options for Google are: roadmap, satellite, hybrid and terrain */ - String mapType = null; - - /** - * The imageEdgeBuffer is used to fetch a slightly bigger image (N-S) so we - * can clip it later. - */ - int imageEdgeBuffer = 30; - - public GoogleMapTileFactory() { - this.rootDir = "http://maps.googleapis.com/maps/api/staticmap?"; - } - - public String buildFilePath(int x, int y, int z, String fileExt) { - StringBuilder ret = new StringBuilder(rootDir); - int dim = 256 + imageEdgeBuffer * 2; - LatLonPoint uLcoord = mtcTransform.tileUVToLatLon(new Point2D.Double(x, y), z, new LatLonPoint.Double()); - Mercator m = new Mercator(uLcoord, mtcTransform.getScaleForZoom(z), 256, 256); - LatLonPoint nCenter = m.inverse(256, 256 + imageEdgeBuffer); - - ret.append("zoom=").append(z); - ret.append("¢er=").append(nCenter.getLatitude()).append(",").append(nCenter.getLongitude()); - ret.append("&size=").append(256).append("x").append(dim); - if (mapType != null) { - ret.append("&maptype=").append(mapType); - } - ret.append("&sensor=false"); - - if (apiKey != null) { - ret.append("&key=").append(apiKey); - } - - return ret.toString(); - } - - protected BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - return BufferedImageHelper.getBufferedImage(origImage, 0, 0, 256, 256, BufferedImage.TYPE_INT_ARGB); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - apiKey = props.getProperty(prefix + API_KEY_PROPERTY, apiKey); - mapType = props.getProperty(prefix + MAPTYPE_PROPERTY, mapType); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + API_KEY_PROPERTY, PropUtils.unnull(apiKey)); - props.put(prefix + MAPTYPE_PROPERTY, PropUtils.unnull(mapType)); - - return props; - } - - /** - * @return the apiKey - */ - public String getApiKey() { - return apiKey; - } - - /** - * @param apiKey the apiKey to set - */ - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - /** - * @return the mapType - */ - public String getMapType() { - return mapType; - } - - /** - * @param mapType the mapType to set - */ - public void setMapType(String mapType) { - this.mapType = mapType; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GreyscaleImagePreparer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GreyscaleImagePreparer.java deleted file mode 100644 index f644a1d67..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/GreyscaleImagePreparer.java +++ /dev/null @@ -1,41 +0,0 @@ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Graphics; -import java.awt.Image; -import java.awt.image.BufferedImage; - -/** - * Creates Grey-scale map tile images. - * - * @author dietrick - */ -public class GreyscaleImagePreparer - implements TileImagePreparer { - - /** - * Overriding the method that creates empty tiles for places with no - * coverage. We need to set the no-coverage attributes for the - * EmptyTileHandler (if it's a SimpleEmptyTileHandler) to null, so it - * doesn't create empty tiles when it's beyond the coverage zoom level - * limit. Those tiles are normally returned as clear, but in the conversion - * to greyscale they turn black. - * @param factory callback object to find EmptyTileHandler. - */ - public void prepareForEmptyTile(MapTileFactory factory) { - EmptyTileHandler empTileHandler = factory.getEmptyTileHandler(); - if (empTileHandler instanceof SimpleEmptyTileHandler) { - ((SimpleEmptyTileHandler) empTileHandler).setNoCoverageAtts(null); - } - } - - public BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_BYTE_GRAY); - Graphics g = image.getGraphics(); - g.drawImage(origImage, 0, 0, null); - g.dispose(); - return image; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/KMLTileGridMaker.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/KMLTileGridMaker.java deleted file mode 100644 index 0f684deb4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/KMLTileGridMaker.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Color; -import java.awt.geom.Point2D; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.util.FileUtils; - -/** - * Creates a KML grid file for import into Google Earth. This file shows the - * tile boundaries for a specified tile zoom level. - * - * @author ddietrick - */ -public class KMLTileGridMaker { - protected String docTitle; - protected int level; - protected List tiles; - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - /** - * @param builder - */ - protected KMLTileGridMaker(Builder builder) { - this.level = builder.zoomLevel; - tiles = makeTiles(level); - this.docTitle = builder.docTitle; - - drawingAttributes.setLinePaint(builder.lineColor); - drawingAttributes.setFillPaint(builder.fillColor); - drawingAttributes.setSelectPaint(builder.labelColor); - } - - protected List makeTiles(int level) { - List ret = new ArrayList(); - ZoomLevelInfo zli = new ZoomLevelInfo(); - zli.setZoomLevel(level); - int edgeTileCount = zli.getEdgeTileCount(); - OSMMapTileCoordinateTransform transform = new OSMMapTileCoordinateTransform(); - zli.setScale(transform.getScaleForZoom(level)); - for (int x = 0; x < edgeTileCount; x++) { - for (int y = 0; y < edgeTileCount; y++) { - Point2D ulllp = transform.tileUVToLatLon(new Point2D.Double(x, y), level); - Point2D lrllp = transform.tileUVToLatLon(new Point2D.Double(x + 1, y + 1), level); - - ret.add(new Tile(x, y, ulllp, lrllp)); - } - } - return ret; - } - - protected void writeDoc(OutputStream output) - throws ParserConfigurationException, TransformerException { - - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder; - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - - Element kmlElement = appendChild(document, document, createKMLElement(document)); - Element docElement = appendChild(document, kmlElement, "Document", null); - appendChild(document, docElement, createStyle(document)); - appendChild(document, docElement, createTiles(document)); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - DOMSource source = new DOMSource(document); - - StreamResult result = new StreamResult(output); - transformer.transform(source, result); - } - - protected Element createKMLElement(Document doc) { - Element rootElement = doc.createElement("kml"); - rootElement.setAttribute("xmlns", "http://www.opengis.net/kml/2.2"); - rootElement.setAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2"); - rootElement.setAttribute("xmlns:kml", "http://www.opengis.net/kml/2.2"); - rootElement.setAttribute("xmlns:atom", "http://www.w3.org/2005/Atom"); - return rootElement; - } - - protected Element createTiles(Document doc) { - Element folderElement = doc.createElement("Folder"); - appendChild(doc, folderElement, "name", "Tile Layout for Zoom Level " + level); - appendChild(doc, folderElement, "open", "1"); - - List tiles = makeTiles(level); - - for (Tile tile : tiles) { - Point2D ul = tile.ul; - Point2D lr = tile.lr; - - StringBuilder buf = new StringBuilder(); - - buf.append(ul.getX() + "," + ul.getY() + ",0 "); - buf.append(lr.getX() + "," + ul.getY() + ",0 "); - buf.append(lr.getX() + "," + lr.getY() + ",0 "); - buf.append(ul.getX() + "," + lr.getY() + ",0 "); - buf.append(ul.getX() + "," + ul.getY() + ",0 "); - - // Polygon representing tile - Element placemark = appendChild(doc, folderElement, "Placemark", null); - - appendChild(doc, placemark, "name", tile.title); - appendChild(doc, placemark, "styleUrl", "#" + styleString); - - Element polygon = appendChild(doc, placemark, "Polygon", null); - appendChild(doc, polygon, "tessellate", "1"); - - Element obiElement = appendChild(doc, polygon, "outerBoundaryIs", null); - Element lrElement = appendChild(doc, obiElement, "LinearRing", null); - /*Element coordElement = */appendChild(doc, lrElement, "coordinates", buf.toString()); - - // Label for tile - Element placemark2 = appendChild(doc, folderElement, "Placemark", null); - appendChild(doc, placemark2, "name", tile.title); - appendChild(doc, placemark2, "styleUrl", "#" + styleString); - Element point = appendChild(doc, placemark2, "Point", null); - appendChild(doc, point, "coordinates", ((lr.getX() + ul.getX()) / 2) + "," + ((ul.getY() + lr.getY()) / 2) + ",0"); - } - - return folderElement; - } - - String styleString = "tileborderstyle"; - - protected Element createStyle(Document doc) { - Element style = doc.createElement("Style"); - style.setAttribute("id", styleString); - Element label = appendChild(doc, style, "LabelStyle", null); - // Element icon = appendChild(doc, style, "IconStyle", null); - Element line = appendChild(doc, style, "LineStyle", null); - Element poly = appendChild(doc, style, "PolyStyle", null); - - String labelColorString = Integer.toHexString(((Color) drawingAttributes.getSelectPaint()).getRGB()); - String lineColorString = Integer.toHexString(((Color) drawingAttributes.getLinePaint()).getRGB()); - String fillColorString = Integer.toHexString(((Color) drawingAttributes.getFillPaint()).getRGB()); - - appendChild(doc, label, "color", labelColorString); - appendChild(doc, line, "color", lineColorString); - appendChild(doc, poly, "color", fillColorString); - - return style; - } - - protected Element appendChild(Document doc, Node parent, String childField, String value) { - Element element = (Element) parent.appendChild(doc.createElement(childField)); - if (value != null) { - element.setTextContent(value); - } - return element; - } - - protected Element appendChild(Document doc, Node parent, Element child) { - parent.appendChild(child); - return child; - } - - /** - * @param args - */ - public static void main(String[] args) { - Color fillColor = new Color(0x3300FF00, true); - Color lineColor = new Color(0xFF00FF00); - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("KMLTileGridMaker"); - - ap.add("level", "Tile Zoom Level to create grid for.", 1); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String[] arg = ap.getArgValues("level"); - if (arg != null) { - - try { - int level = Integer.parseInt(arg[0]); - new Builder(level).setLineColor(lineColor).setFillColor(fillColor).setLabelColor(lineColor).go(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (TransformerException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - } - } - } - - protected class Tile { - protected int uvx; - protected int uvy; - protected Point2D ul; - protected Point2D lr; - protected String title; - - protected Tile(int uvx, int uvy, Point2D ul, Point2D lr) { - this.uvx = uvx; - this.uvy = uvy; - this.ul = ul; - this.lr = lr; - - title = uvx + "_" + uvy; - } - } - - /** - * Use this class to run the KMLTileGridMake. Create a builder, add any - * customization you want, call go() when you want to create the file. - * - * @author ddietrick - */ - public static class Builder { - int zoomLevel; - Color lineColor = Color.WHITE; - Color fillColor = Color.WHITE; - Color labelColor = Color.WHITE; - String docTitle; - String fileName; - OutputStream output; - boolean closeOutput = false; - - public Builder() { - this(5); - } - - public Builder(int tileZoomLevel) { - zoomLevel = tileZoomLevel; - docTitle = "Tile Boundaries for Zoom Level " + zoomLevel; - } - - public Builder setLineColor(Color lineColor) { - this.lineColor = lineColor; - return this; - } - - public Builder setFillColor(Color fillColor) { - this.fillColor = fillColor; - return this; - } - - public Builder setLabelColor(Color labelColor) { - this.labelColor = labelColor; - return this; - } - - public Builder setDocTitle(String docTitle) { - this.docTitle = docTitle; - return this; - } - - public Builder setFileName(String fileName) - throws FileNotFoundException { - this.fileName = fileName; - - File file = null; - if (fileName != null) { - file = new File(fileName); - } - - if (file == null) { - String filePath = FileUtils.getFilePathToSaveFromUser("Choose location and name of KML file"); - if (filePath != null) { - file = new File(filePath); - } - } - - if (file != null) { - output = new FileOutputStream(file); - closeOutput = true; - } - - return this; - } - - /** - * If you provide an OutputStream, you're responsible for closing it. - * - * @param out - * @return this Builder - */ - public Builder setOutputStream(OutputStream out) { - this.output = out; - return this; - } - - public void go() - throws ParserConfigurationException, TransformerException, IOException { - KMLTileGridMaker kml = new KMLTileGridMaker(Builder.this); - - if (output == null) { - setFileName(null); - } - - if (output != null) { - kml.writeDoc(output); - if (closeOutput) { - output.close(); - } - } else { - throw new IOException("No output specified"); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileCoordinateTransform.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileCoordinateTransform.java deleted file mode 100644 index 2d3dc31bd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileCoordinateTransform.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * The TileCoordinateTransform is an object that knows how to translate lat/lon - * coordinates to UV tile coordinates for map tiles. Its an interface because - * there seem to be two accepted ways to divide up frames over the Earth. The - * Tile Map Service (TMS) tile system divide the Earth with the origin at the - * bottom left, OpenStreetMap has the origin at the top left. - * - * @author dietrick - */ -public interface MapTileCoordinateTransform { - - public final static int TILE_SIZE = 256; - public final static Point2D UVUL = new Point2D.Double(0, 0); - public final static Point2D UVLR = new Point2D.Double(TILE_SIZE, TILE_SIZE); - - Point2D latLonToTileUV(Point2D latlon, int zoom); - - Point2D latLonToTileUV(Point2D latlon, int zoom, Point2D ret); - - /** - * @param tileUV a Point2D whose x,y coordinates represent the distance in - * number of tiles (each 256x256) from the origin (where the origin - * is 90lat,-180lon) - * @param zoom Tile Map Service (TMS) style zoom level (0-19 usually) - * @return a Point2D whose x coordinate is the longitude and y coordinate is - * the latitude - */ - Point2D tileUVToLatLon(Point2D tileUV, int zoom); - - LatLonPoint tileUVToLatLon(Point2D tileUV, int zoom, LatLonPoint ret); - - /** - * Given a projection, provide the upper, lower, left and right tile - * coordinates that cover the projection area. - * - * @param upperLeft lat/lon coordinate of upper left corner of bounding box. - * @param lowerRight lat/lon coordinate of lower right corner of bounding - * box. - * @param zoomLevel zoom level of desired tiles. - * @return int[], in top, left, bottom and right order. - */ - int[] getTileBoundsForProjection(Point2D upperLeft, Point2D lowerRight, int zoomLevel); - - /** - * @return if y coordinates for tiles increase as pixel values increase. - */ - boolean isYDirectionUp(); - - /** - * The coordinate transformation object used for lat/lon uv conversions. - * - * @return transform appropriate for a particular zoom level. - */ - GeoCoordTransformation getTransform(int zoomLevel); - - /** - * Return a scale value for the transforming projection, given a discrete - * zoom level. - * - * @param zoom level - * @return scale value. - */ - float getScaleForZoom(int zoom); - - /** - * Get the scale value for a Projection and discrete zoom level. - * - * @param proj the projection to use for scale calculations. - * @param zoom the discrete zoom level. - * @return scale value for the given projection. - */ - float getScaleForZoomAndProjection(Projection proj, int zoom); - - /** - * Given a projection, figure out the appropriate zoom level for it. Right - * now, 0 is totally zoomed with one tile for the entire earth. But we don't - * return 0, we start at 1. OM can't handle one tile that covers the entire - * earth because of the restriction for handling OMGraphics to less than - * half of the earth. Uses the default zoomLevelTileSize of 350. - * - * @param proj - * @return the zoom level. - */ - int getZoomLevelForProj(Projection proj); - - /** - * Given a projection, figure out the appropriate zoom level for it. Right - * now, 0 is totally zoomed with one tile for the entire earth. But we don't - * return 0, we start at 1. OM can't handle one tile that covers the entire - * earth because of the restriction for handling OMGraphics to less than - * half of the earth. - * - * @param proj - * @param zoomLevelTileSize the pixel edge size of a tile before the zoom - * level changes. - * @return the zoom level. - */ - int getZoomLevelForProj(Projection proj, int zoomLevelTileSize); - - /** - * Creates an array of scale values for different zoom levels. Make sure you - * don't reference the array outside of 0 and high zoom levels. There will - * be a high zoom level number of items in the array. - * - * @param proj - * @param highZoomLevel - * @return array, initialized for the 0 zoom level index to the high zoom - * level index. - */ - float[] getScalesForZoomLevels(Projection proj, int highZoomLevel); - - /** - * @return the pixel size for tiles for this transform. - */ - int getTileSize(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java deleted file mode 100644 index 08976546a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java +++ /dev/null @@ -1,91 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * An object that fetches tiles for a given projection. It could cache the - * tiles, it can get them from anywhere it might want to. - * - * @author dietrick - */ -public interface MapTileFactory { - /** - * Create an OMGraphicList with a set of tiles on it. - * - * @param proj - * @return OMGraphicList that was created. - */ - OMGraphicList getTiles(Projection proj); - - /** - * Create an OMGraphicList that covers the projection with tiles that suit - * the specified zoom level. - */ - OMGraphicList getTiles(Projection proj, int zoomLevel); - - /** - * Add tiles to OMGraphicList provided that suit the given projection. - * - * @param proj - * @param list - * @return the OMGraphicList provided. - */ - OMGraphicList getTiles(Projection proj, int zoomLevel, OMGraphicList list); - - /** - * Set a MapTileRequestor in the tile factory that should be told to repaint - * when new tiles become available, and to check with during the tile fetch - * whether to keep going or not. listUpdate will be called when a new tile - * has been added to the OMGraphicList passed in the getTiles method, and - * shouldContinue will be called during stable times during the getTiles - * fetch. - * - * @param requestor - * callback MapTileRequestor to ask status questions. - */ - void setMapTileRequester(MapTileRequester requestor); - - /** - * Tell the factory to clean up resources. - */ - void reset(); - - /** - * Get object that handles empty tiles. - * - * @return EmptyTileHandler used by the factory. - */ - EmptyTileHandler getEmptyTileHandler(); - - /** - * @return space-separated property names that should be displayed to the - * property inspector. - */ - String getInitPropertiesOrder(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMaker.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMaker.java deleted file mode 100644 index 9efdae358..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMaker.java +++ /dev/null @@ -1,709 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsEnvironment; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; -import java.util.logging.Level; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.image.ImageFormatter; -import com.bbn.openmap.image.ImageServer; -import com.bbn.openmap.image.PNG32ImageFormatter; -import com.bbn.openmap.image.SunJPEGFormatter; -import com.bbn.openmap.layer.image.MapTileLayer; -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The MapTileMaker is an ImageServer extension that knows how to create image - * tile sets, like the kind of tiles used by Google Maps and OpenStreetMap, Tile - * Map Service (TMS). It uses ZoomLayerMarker objects to define how tiles are - * created for different zoom levels. You can run this class as an application. - * With the -create option, it will create a sample properties file to - * demonstrate what properties are needed to run it. - *

- * - * The properties look much like the ImageServer properties, with a couple of - * additional values: - *

- * - *

- * ### MapTileMaker/ImageServer properties ###
- * antialiasing=false
- * # Image formatter definition
- * formatters=formatter1
- * # Layer definitions for layers that are available for zoom levels
- * layers=layer1 layer2 ...
- * rootDir=Path to top level directory for tiles
- * zoomLevels=zoom1 zoom2
- * 
- * formatter1=.class=com.bbn.openmap.image.PNGImageIOFormatter
- * layer1.class=com.bbn.openmap.layer.shape.ShapeLayer
- * # ... layer1 properties follow, see layer docs for specific properties for that layer
- * 
- * # Then, for each zoom level
- * zoom1.class=com.bbn.openmap.image.ZoomLevelInfo
- * #Optional, to limit tile areas created, in sets of 4, must be in lat,lon order
- * zoom1.bounds=lat lon lat lon
- * zoom1.description=Tiles for zoom level 4
- * #Marker names for layers to be rendered, the property prefixes for the layers held by TileMaker
- * zoom1.layers=layer1 layer2
- * zoom1.name=ZoomLayerInfo 4
- * zoom1.zoomLevel=4
- * # If defined, copies of zoomLevel tiles will be scaled through range level.
- * zoom1.range=0
- * 
- * # and repeat for every zoomLevel defined
- * 
- * - * @author dietrick - */ -public class MapTileMaker extends ImageServer implements EmptyTileHandler { - - public final static String ROOT_DIRECTORY_PROPERTY = "rootDir"; - public final static String ZOOM_LEVELS_PROPERTY = "zoomLevels"; - - protected String rootDir; - protected List zoomLevels; - protected MapTileCoordinateTransform mtcTransform = new OSMMapTileCoordinateTransform(); - protected int TILE_SIZE = mtcTransform.getTileSize(); - - /** - * Empty constructor that expects to be configured later. - */ - public MapTileMaker() { - } - - /** - * To create the TileMaker, you hand it a set of properties that let it - * create an array of layers, and also to set the properties for those - * layers. The properties file for the ImageServer looks strikingly similar - * to the openmap.properties file. So, all the layers get set up here... - */ - public MapTileMaker(Properties props) { - super(props); - } - - /** - * Same as the other constructor, except that the properties can have a - * prefix in front of them. The format of the prefix has to match how the - * property is specified the the properties file, which may include the - * period - i.e server1.imageServer.layers, the server1. is the prefix that - * should get passed in. The ImageMaster does this. - */ - public MapTileMaker(String prefix, Properties props) { - super(prefix, props, null); - } - - /** - * Create an TileMaker that should be configured with a Properties file. The - * prefix given is to scope the ImageServer properties to this instance. The - * Hashtable is for reusing any layers that may already be instantiated. - */ - public MapTileMaker(String prefix, Properties props, - Map instantiatedLayers) { - super(prefix, props, instantiatedLayers); - } - - /** - * Create an TileMaker from an array of Layers and an ImageFormatter. It's - * assumed that the layers are already configured. - * - * @param layers - * the array of layers. - * @param formatter - * the ImageFormatter to use for the output image format. - */ - public MapTileMaker(Layer[] layers, ImageFormatter formatter) { - super(layers, formatter); - } - - @SuppressWarnings("unchecked") - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - rootDir = props.getProperty(prefix + ROOT_DIRECTORY_PROPERTY, rootDir); - List zoomLevels = (List) PropUtils - .objectsFromProperties(props, prefix + ZOOM_LEVELS_PROPERTY, - ComponentFactory.ClassNameProperty); - getZoomLevels().addAll(zoomLevels); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + ROOT_DIRECTORY_PROPERTY, PropUtils.unnull(rootDir)); - - StringBuffer buf = new StringBuffer(); - for (ZoomLevelMaker zfi : getZoomLevels()) { - buf.append(zfi.getPropertyPrefix()).append(" "); - zfi.getProperties(props); - } - - if (buf.length() > 0) { - props.put(prefix + ZOOM_LEVELS_PROPERTY, buf.toString().trim()); - } - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(Environment.getI18n(), props, - com.bbn.openmap.dataAccess.mapTile.MapTileMaker.class, - ROOT_DIRECTORY_PROPERTY, "Tile Directory", - "Root directory for holding tile files.", - "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - return props; - } - - /** - * Creating the tile using the ImageServer methodology, knowing that the - * MapTileMaker has been configured with an openmap.properties.file and - * knows about layers and their marker names. - * - * @param uvx - * uv x pixel coordinate - * @param uvy - * uv y pixel coordinate - * @param zoomInfo - * zoom level for image tile - * @param proj - * projection for tile - * @return byte[] for raw image bytes - */ - public byte[] makeTile(double uvx, double uvy, ZoomLevelMaker zoomInfo, - Proj proj) { - Point2D center = tileUVToLatLon(new Point2D.Double(uvx + .5, uvy + .5), - zoomInfo.getZoomLevel()); - proj.setScale(mtcTransform.getScaleForZoom(zoomInfo.getZoomLevel())); - proj.setCenter(center); - proj.setHeight(TILE_SIZE); - proj.setWidth(TILE_SIZE); - - return createImage(proj, -1, -1, zoomInfo.getLayers()); - } - - /** - * Creating a tile more freely, when you have a set of layers you want to - * draw into the tile. - * - * @param uvx - * uv x pixel coordinate - * @param uvy - * uv y pixel coordinate - * @param zoomLevel - * zoom level for tile - * @param layers - * layers to include in image - * @param proj - * projection for tile - * @param background - * the paint to use for the background of the image. - * @return byte[] for raw image bytes - */ - public byte[] makeTile(double uvx, double uvy, int zoomLevel, - List layers, Proj proj, Paint background) { - Point2D center = tileUVToLatLon(new Point2D.Double(uvx + .5, uvy + .5), - zoomLevel); - proj.setScale(mtcTransform.getScaleForZoom(zoomLevel)); - proj.setCenter(center); - proj.setHeight(TILE_SIZE); - proj.setWidth(TILE_SIZE); - - return createImageFromLayers(proj, -1, -1, layers, background); - } - - /** - * The main call to make for a tile to be created. This method will cause - * the correct mapTile method to be called, depending on the configuration - * of the ZoomLevelMakers. - * - * @param uvx - * @param uvy - * @param zoomInfo - * @param proj - * @return the final file path used, with any extensions added. - * @throws IOException - */ - public String makeTileFile(double uvx, double uvy, ZoomLevelMaker zoomInfo, - Proj proj) throws IOException { - - byte[] imageBytes = zoomInfo.makeTile(uvx, uvy, this, proj); - - String filePath = zoomInfo.formatImageFilePath(getRootDir(), (int) uvx, - (int) uvy); - return writeImageFile(imageBytes, filePath, true); - } - - /** - * EmptyTileHandler method, called when a MapTileFactory needs to create and - * return a missing tile. - * - * @param imagePath - * the path of the missing tile that is going to be used as cache - * lookup later. - * @param x - * the uv x coordinate of the tile. - * @param y - * the uv y coordinate of the tile. - * @param zoomLevel - * the zoom level of the tile. - * @param mtcTransform - * the transform that converts x,y coordinates to lat/lon and - * describes the layout of the uv tile coordinates. - * @param proj - * the map projection, in case that matters what should be - * returned for the empty tile. - * @return BufferedImage for image tile, or null if there's a problem - */ - public BufferedImage getImageForEmptyTile(String imagePath, int x, int y, - int zoomLevel, MapTileCoordinateTransform mtcTransform, - Projection proj) { - - Layer[] layers = null; - - List zoomLevels = getZoomLevels(); - if (zoomLevels != null && !zoomLevels.isEmpty()) { - for (ZoomLevelMaker zoomLevelMaker : zoomLevels) { - if (zoomLevelMaker.getZoomLevel() == zoomLevel) { - List layerList = zoomLevelMaker.getLayerList(); - if (layerList != null) { - layers = layerList.toArray(new Layer[layerList.size()]); - } else { - // The zoom level was defined, but layers for the zoom - // level weren't, use top-level layers. - layers = getLayers(); - } - break; - } - } - } else { - // particular layer configurations for zoom levels aren't defined, - // use all layers. - layers = getLayers(); - } - - // Either layers weren't defined at all, or a particular zoom level - // wasn't defined. - if (layers == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("There are no layers defined for zoom level" - + zoomLevel + " in MapTileMaker, can't create image"); - } - return null; - } - - LatLonPoint center = tileUVToLatLon(new Point2D.Double(x + .5, y + .5), - zoomLevel); - Mercator m = new Mercator(center, - mtcTransform.getScaleForZoom(zoomLevel), TILE_SIZE, TILE_SIZE); - - BufferedImage bufferedImage = new BufferedImage(TILE_SIZE, TILE_SIZE, - BufferedImage.TYPE_INT_ARGB); - - GraphicsEnvironment ge = GraphicsEnvironment - .getLocalGraphicsEnvironment(); - Graphics graphics = ge.createGraphics(bufferedImage); - graphics.setClip(0, 0, TILE_SIZE, TILE_SIZE); - - m.drawBackground((Graphics2D) graphics, background); - - if (layers != null) { - for (int i = layers.length - 1; i >= 0; i--) { - try { - layers[i].renderDataForProjection(proj, graphics); - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem rendering layer " + i); - } - } - } - - } - - graphics.dispose(); - - return bufferedImage; - } - - /** - * Main call to make a set of tiles. The ZoomLevelMaker objects have to be - * configured correctly. Each ZoomLevelMaker has to have its zoom levels set - * (initial and range), the bounds of the areas where tiles are desired, and - * the layers desired on those tiles. For the layers, the ZoomLevelInfo can - * have a List of Strings corresponding to the property prefixes of the - * layers already set on the MapTileMaker, or it can have a List of Layer - * objects to use. The root output directory has to be set in the - * MapTileMaker. The image formatter also needs to be set. - */ - public void makeTiles() { - - if (rootDir != null) { - File rd = new File(rootDir); - if (!rd.exists()) { - rd.mkdir(); - } - } - - Proj proj = new Mercator(new LatLonPoint.Double(), 10000, - MapTileCoordinateTransform.TILE_SIZE, - MapTileCoordinateTransform.TILE_SIZE); - - List zoomLevels = getZoomLevels(); - for (ZoomLevelMaker zfi : zoomLevels) { - logger.info("writing zoom level " + zfi.getName() + " tiles..."); - int zoomLevel = zfi.getZoomLevel(); - for (Rectangle2D bounds : zfi.getUVBounds(mtcTransform, zoomLevel)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(" creating tiles " + bounds); - } - int startx = (int) bounds.getX(); - int starty = (int) bounds.getY(); - int xofflimit = (int) bounds.getWidth(); - int yofflimit = (int) bounds.getHeight(); - - for (int xoff = 0; xoff < xofflimit; xoff++) { - int x = startx + xoff; - - // Reset every x loop for first time check through y loop - String parentDirPath = null; - - for (int yoff = 0; yoff < yofflimit; yoff++) { - int y = starty + yoff; - - if (parentDirPath == null) { - parentDirPath = zfi.formatParentDirectoryName( - getRootDir(), x, y); - File parentDir = new File(parentDirPath); - if (!parentDir.exists()) { - parentDir.mkdirs(); - } - } - - try { - String outputFile = makeTileFile(x, y, zfi, proj); - if (logger.isLoggable(Level.FINER)) { - logger.finer("wrote: " + outputFile); - } - } catch (IOException ioe) { - logger.warning("Caught IOException writing " + x - + ", " + y + ", " + zfi); - } - } - - } - } - - // At this point, for a specific ZoomLevelInfo, the basic tiles for - // it have been created. Now we can check the range and create tiles - // for the range out of the new tiles. - int range = zfi.getRange(); - if (range < zoomLevel) { - MapTileLayer tileLayer = new MapTileLayer(); - StandardMapTileFactory tileFactory = new StandardMapTileFactory(); - tileFactory.setRootDir(getRootDir()); - tileFactory.setFileExt(getFormatter().getFormatLabel()); - tileLayer.setTileFactory(tileFactory); - - List subLayers = new ArrayList(); - subLayers.add(tileLayer); - - for (int rangeZoomLevel = zoomLevel - 1; rangeZoomLevel >= range; rangeZoomLevel--) { - tileLayer.setZoomLevel(rangeZoomLevel); - ZoomLevelInfo rangeZFI = new ZoomLevelInfo(); - rangeZFI.setZoomLevel(rangeZoomLevel); - rangeZFI.setScale(mtcTransform - .getScaleForZoom(rangeZoomLevel)); - // Create new tiles from the tiles one zoom level up - tileLayer.setZoomLevel(rangeZoomLevel + 1); - - for (Rectangle2D rawBounds : zfi.getBounds()) { - Rectangle2D bounds = rangeZFI.getUVBounds(rawBounds, - mtcTransform, rangeZoomLevel); - if (logger.isLoggable(Level.INFO)) { - logger.fine(" creating subtiles " + bounds); - } - int startx = (int) bounds.getX(); - int starty = (int) bounds.getY(); - int xofflimit = (int) bounds.getWidth(); - int yofflimit = (int) bounds.getHeight(); - - for (int xoff = 0; xoff < xofflimit; xoff++) { - int x = startx + xoff; - - // Reset every x loop for first time check through y - // loop - String parentDirPath = null; - - for (int yoff = 0; yoff < yofflimit; yoff++) { - int y = starty + yoff; - - if (parentDirPath == null) { - parentDirPath = rangeZFI - .formatParentDirectoryName( - getRootDir(), x, y); - File parentDir = new File(parentDirPath); - if (!parentDir.exists()) { - parentDir.mkdirs(); - } - } - - try { - - byte[] imageBytes = makeTile(x, y, - rangeZoomLevel, subLayers, proj, - OMColor.clear); - - String filePath = rangeZFI - .formatImageFilePath(getRootDir(), - (int) x, (int) y); - String outputFile = writeImageFile( - imageBytes, filePath, true); - - if (logger.isLoggable(Level.INFO)) { - logger.finer("wrote: " + outputFile); - } - } catch (IOException ioe) { - logger.warning("Caught IOException writing " - + x + ", " + y + ", " + zfi); - } - } - - } - - } - } - - } - } - - logger.info("done writing tiles"); - } - - public String getRootDir() { - return rootDir; - } - - public void setRootDir(String rootDir) { - this.rootDir = rootDir; - } - - public List getZoomLevels() { - if (zoomLevels == null) { - zoomLevels = new LinkedList(); - } - return zoomLevels; - } - - public void setZoomLevels(List zoomLevels) { - this.zoomLevels = zoomLevels; - } - - public void createDefaultZoomLevels(int maxZoomLevel) { - Layer[] layers = getLayers(); - List zoomLevels = getZoomLevels(); - List layerNames = new LinkedList(); - for (int i = 0; i < layers.length; i++) { - String layerName = layers[i].getPropertyPrefix(); - if (layerName != null) { - layerNames.add(layerName); - } else { - logger.info("no name for layer[" + i + "]"); - } - } - - zoomLevels.clear(); - - for (int i = 0; i <= maxZoomLevel; i++) { - ZoomLevelMaker zfi = new ZoomLevelMaker("ZoomLayerInfo " + i, - "Tiles for zoom level " + i, i); - zfi.setLayers(layerNames); - zfi.setPropertyPrefix("zoom" + i); - zoomLevels.add(zfi); - } - } - - /** - * @param latlon - * a Point2D whose x component is the longitude and y component - * is the latitude - * @param zoom - * Tile Map Service (TMS) style zoom level (0-19 usually) - * @return The "tile number" whose x and y components each are floating - * point numbers that represent the distance in number of tiles from - * the origin of the whole map at this zoom level. At zoom=0, the - * lat,lon point of 0,0 maps to 0.5,0.5 since there is only one tile - * at zoom level 0. - */ - public Point2D latLonToTileUV(Point2D latlon, int zoom) { - return mtcTransform.latLonToTileUV(latlon, zoom, null); - } - - public Point2D latLonToTileUV(Point2D latlon, int zoom, Point2D ret) { - return mtcTransform.latLonToTileUV(latlon, zoom, ret); - } - - /** - * @param tileUV - * a Point2D whose x,y coordinates represent the distance in - * number of tiles (each 256x256) from the origin (where the - * origin is 90lat,-180lon) - * @param zoom - * Tile Map Service (TMS) style zoom level (0-19 usually) - * @return a LatLonPoint whose x coordinate is the longitude and y - * coordinate is the latitude, decimal degrees. - */ - public LatLonPoint tileUVToLatLon(Point2D tileUV, int zoom) { - return mtcTransform.tileUVToLatLon(tileUV, zoom, null); - } - - public LatLonPoint tileUVToLatLon(Point2D tileUV, int zoom, LatLonPoint ret) { - return mtcTransform.tileUVToLatLon(tileUV, zoom, ret); - } - - public static void main(String[] args) { - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser( - "MapTileMaker"); - - ap.add("properties", "The properties file to use for image tiles.", 1); - ap.add("create", "Create a sample properties file at a path", 1); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String arg[]; - - Properties props = null; - arg = ap.getArgValues("properties"); - if (arg != null) { - String ps = arg[0]; - try { - - URL url = PropUtils.getResourceOrFileOrURL(null, ps); - InputStream inputStream = url.openStream(); - - props = new Properties(); - props.load(inputStream); - - MapTileMaker tim = new MapTileMaker(props); - tim.makeTiles(); - - } catch (MalformedURLException murle) { - Debug.error("TileMaker can't find properties file: " + arg[0]); - } catch (IOException ioe) { - Debug.error("TileMaker can't create images: IOException"); - } - } - - arg = ap.getArgValues("create"); - if (arg != null) { - String outputFile = arg[0]; - MapTileMaker tim; - if (props == null) { - ShapeLayer shapeLayer = new ShapeLayer(); - props = new Properties(); - props.put("shape.prettyName", "Countries"); - props.put("shape.shapeFile", - "data/shape/world/cntry02/cntry02.shp"); - props.put("shape.fillColor", "FFBBBBBB"); - shapeLayer.setProperties("shape", props); - - tim = new MapTileMaker(new Layer[] { shapeLayer }, - new SunJPEGFormatter()); - tim.createDefaultZoomLevels(4); - - tim.setRootDir(""); - tim.setFormatter(new PNG32ImageFormatter()); - - } else { - tim = new MapTileMaker(props); - } - - Properties configurationProps = new Properties(); - configurationProps = tim.getProperties(configurationProps); - - StringBuilder sb = new StringBuilder( - "#### MapTileMaker Properties ####\n"); - - if (!configurationProps.isEmpty()) { - TreeMap orderedProperties = new TreeMap(configurationProps); - - for (Object key : orderedProperties.keySet()) { - String value = configurationProps.getProperty((String) key); - - if (value != null) { - sb.append(key).append("=").append(value).append("\n"); - } - } - } - - try { - FileOutputStream fos = new FileOutputStream(outputFile); - PrintStream ps = new PrintStream(fos); - ps.println(sb.toString()); - ps.close(); - } catch (IOException ioe) { - logger.warning("caught IOException writing property file: " - + ioe.getMessage()); - } - - } - - System.exit(0); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMakerComponent.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMakerComponent.java deleted file mode 100644 index 095c802f7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileMakerComponent.java +++ /dev/null @@ -1,850 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Cursor; -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.TreeSet; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.Future; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.dataAccess.mapTile.ZoomLevelMakerFace.BoundsObject; -import com.bbn.openmap.dataAccess.mapTile.ZoomLevelMakerFace.LayerObject; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.MapMouseSupport; -import com.bbn.openmap.event.PaintListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.gui.MapPanelChild; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.image.ImageServer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.tools.drawing.OMRectLoader; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.TaskService; - -/** - * The MapTileMakerComponent is a GUI for creating properties that the - * MapTileMaker uses to create tiles. You can add it to the MapHandler - * (programmatically or via the openmap.components list in the - * openmap.properties file) and it will attach itself to the left of the map. It - * takes some properties itself: - *

- * - *

- * # the class definition, assuming that tileMakerComp was used as the marker name in the properties file.
- * tileMakerComp.class=com.bbn.openmap.dataAccess.mapTile.MapTileMakerComponent
- * # the path to the directory where tiles should be created.
- * tileMakerComp.rootDir=/dev/openmap/tiles
- * # a path to a file where the properties that the gui creates should be written.
- * tileMakerComp.file=/dev/openmap/tilemaker.properties
- * 
- * - *

- * There are some things left to do. - *

    - *
  • The component should read the file and set all the components to the last - * settings contained in it. - *
  • It should allow you to choose where the tiles should go instead of having - * that location only defined in the properties file. - *
  • It should let you choose image tile formats, right now it's defaulting to - * png. - *
  • Canceling the worker thread doesn't seem to be working, the thread isn't - * responding to being canceled. - *
- * - * @author dietrick - */ -public class MapTileMakerComponent - extends OMComponentPanel - implements MapPanelChild, LayerListener, DrawingToolRequestor, PaintListener, ProjectionListener { - - protected Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile.MapTileMakerComponent"); - - public final static String TILE_MAKER_PROPERTIES_FILE = "file"; - - private static final long serialVersionUID = 1L; - protected String preferredLocation = BorderLayout.WEST; - protected String parentName = null; - protected String fileName = null; - protected String rootDir = null; - protected boolean transparentTiles = false; - - protected LayerHandler layerHandler; - - protected List faces = new ArrayList(); - protected ZoomLevelMakerFace activeFace; - - protected OMDrawingTool drawingTool; - protected DrawingAttributes rectDA = DrawingAttributes.getDefaultClone(); - - public MapTileMakerComponent() { - init(); - } - - protected void init() { - - drawingTool = new OMDrawingTool(); - drawingTool.getMouseMode().setVisible(false); - drawingTool.getMouseMode().setModeCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - drawingTool.addLoader(new OMRectLoader()); - - GridBagLayout selfLayout = new GridBagLayout(); - setLayout(selfLayout); - GridBagLayout outerLayout = new GridBagLayout(); - JPanel mainPanel = new JPanel(outerLayout); - String map_tile_maker = i18n.get(MapTileMakerComponent.class, "map_tile_maker", "Map Tile Maker"); - mainPanel.setBorder(BorderFactory.createTitledBorder(map_tile_maker)); - GridBagConstraints outerC = new GridBagConstraints(); - outerC.insets = new Insets(0, 5, 5, 5); - outerC.gridx = GridBagConstraints.REMAINDER; - outerC.fill = GridBagConstraints.BOTH; - outerC.weightx = 1.0f; - outerC.weighty = 1.0f; - - String zoom_level = i18n.get(MapTileMakerComponent.class, "zoom_level", "Zoom Level"); - - ZoomLevelMakerFace zlif = new ZoomLevelMakerFace(new ZoomLevelMaker(zoom_level + " " + 0, "", 0), this); - faces.add(zlif); - mainPanel.add(zlif, outerC); - - JPanel masterOptions = new JPanel(new GridBagLayout()); - String use_transparent_background = - i18n.get(MapTileMakerComponent.class, "use_transparent_background", "Use transparent background for tiles"); - JCheckBox transparentButton = new JCheckBox(use_transparent_background, transparentTiles); - transparentButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - transparentTiles = ((JCheckBox) ae.getSource()).isSelected(); - } - }); - - GridBagConstraints optC = new GridBagConstraints(); - optC.anchor = GridBagConstraints.WEST; - optC.fill = GridBagConstraints.HORIZONTAL; - optC.weightx = 1f; - optC.gridx = GridBagConstraints.RELATIVE; - - masterOptions.add(transparentButton, optC); - outerC.weighty = 0f; - mainPanel.add(masterOptions, outerC); - - String make_tiles = i18n.get(MapTileMakerComponent.class, "make_tiles", "Make Tiles"); - JButton launchButton = new JButton(make_tiles); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - confirmLaunchTileMaker(); - } - }); - - outerC.fill = GridBagConstraints.NONE; - outerC.weightx = 0f; - outerC.weighty = 0f; - mainPanel.add(launchButton, outerC); - outerC.fill = GridBagConstraints.BOTH; - outerC.weightx = 1.0f; - outerC.weighty = 1.0f; - add(mainPanel, outerC); - - resetActive(faces.get(0)); - - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - rootDir = props.getProperty(prefix + MapTileMaker.ROOT_DIRECTORY_PROPERTY); - fileName = props.getProperty(prefix + TILE_MAKER_PROPERTIES_FILE); - } - - /** - * - */ - protected void confirmLaunchTileMaker() { - Frame frame = JOptionPane.getFrameForComponent(this); - String confirm_configuration = i18n.get(MapTileMakerComponent.class, "confirm_configuration", "Confirm Configuration"); - JDialog dialog = new ConfirmationDialog(frame, null, confirm_configuration, this); - dialog.setVisible(true); - } - - protected void launchTileMaker(Properties props) { - - TreeSet sortedKeys = new TreeSet(props.keySet()); - if (fileName != null) { - - try { - BufferedWriter bWriter = new BufferedWriter(new FileWriter(fileName)); - for (Object key : sortedKeys) { - bWriter.write(key + "=" + props.get(key) + "\n"); - } - - bWriter.flush(); - bWriter.close(); - } catch (IOException e) { - logger.warning("caught exception writing out properties file"); - e.printStackTrace(); - } - } - - final TileRunnable runner = new TileRunnable(props); - Thread runnerThread = new Thread(runner); - runnerThread.start(); - - Frame frame = JOptionPane.getFrameForComponent(MapTileMakerComponent.this); - - JButton[] buttons = new JButton[1]; - JButton button1 = new JButton("Cancel"); - button1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - runner.cancel(); - } - }); - - buttons[0] = button1; - String creating_map_tiles = i18n.get(MapTileMakerComponent.class, "creating_map_tiles", "Creating Map Tiles..."); - JOptionPane pane = - new JOptionPane(creating_map_tiles, JOptionPane.INFORMATION_MESSAGE, JOptionPane.CANCEL_OPTION, null, buttons, button1); - - cancelDialog = pane.createDialog(frame, "MapTileMaker Running"); - // cancelDialog.setModalityType(ModalityType.APPLICATION_MODAL); - cancelDialog.setModal(true); - cancelDialog.setVisible(true); - } - - protected Dialog cancelDialog; - - /** - * Called when a new tab is selected and a new ZLIF is active. - * - * @param activeZlif - */ - protected void resetActive(ZoomLevelMakerFace activeZlif) { - activeFace = activeZlif; - for (ZoomLevelMakerFace zlif : faces) { - zlif.setActive(zlif.equals(activeZlif)); - } - - shuffleLayers(activeZlif); - activeFace.enableBoundaryButtons(!drawingTool.isActivated()); - // Needed in case there aren't layers active in the new ZLIF and the - // drawing tool is active. - - MapHandler mHandler = (MapHandler) getBeanContext(); - if (mHandler != null) { - mHandler.get(MapBean.class).repaint(); - } - } - - protected void shuffleLayers(ZoomLevelMakerFace activeZlif) { - if (layerHandler != null) { - Layer[] layers = layerHandler.getLayers(); - for (Layer layer : layers) { - for (LayerObject lo : activeZlif.layerList) { - - if (lo.getLayer().equals(layer)) { - layer.setVisible(lo.isSelected()); - } - } - } - layerHandler.setLayers(); - } - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof LayerHandler) { - layerHandler = (LayerHandler) someObj; - layerHandler.addLayerListener(this); - } - - if (drawingTool != null) { - drawingTool.findAndInit(someObj); - } - - if (someObj instanceof MapBean) { - MapBean map = (MapBean) someObj; - map.addProjectionListener(this); - map.addPaintListener(this); - } - } - - /** - * Set the parent name that the MapPanelChild should attach itself too. - * - * @param name - */ - public void setParentName(String name) { - this.parentName = name; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.gui.MapPanelChild#getParentName() - */ - public String getParentName() { - return parentName; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.gui.MapPanelChild#getPreferredLocation() - */ - public String getPreferredLocation() { - return preferredLocation; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.gui.MapPanelChild#setPreferredLocation(java.lang.String) - */ - public void setPreferredLocation(String string) { - this.preferredLocation = string; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.event.LayerListener#setLayers(com.bbn.openmap.event.LayerEvent - * ) - */ - public void setLayers(LayerEvent evt) { - if (evt.getType() == LayerEvent.ALL) { - Layer[] layers = evt.getLayers(); - - for (ZoomLevelMakerFace zlif : faces) { - zlif.setLayers(layers); - } - } - } - - /** - * @param layerObjects - */ - protected void pushLayerSettingsToAll(List layerObjects) { - for (ZoomLevelMakerFace zlif : faces) { - zlif.matchObjects(layerObjects); - } - } - - /** - * @param boundsList - */ - protected void pushBoundarySettingsToAll(List boundsList) { - List copy = new ArrayList(); - copy.addAll(boundsList); - - for (ZoomLevelMakerFace zlif : faces) { - zlif.matchBounds(copy); - } - } - - /** - * Create a boundary rectangle from scratch, expecting the user to draw the - * rectangle. - */ - public void createRectangle() { - GraphicAttributes ga = new GraphicAttributes(); - rectDA.setTo(ga); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - ga.setLineType(OMGraphic.LINETYPE_RHUMB); - - EditableOMRect eomr = new EditableOMRect(ga); - - eomr.setXorRendering(false); - create(eomr); - } - - /** - * Called when the OMGraphic should be edited by the drawing tool. For - * existing OMGraphics that have been clicked on, to start the editing - * process. - * - * @param omg OMGraphic to edit - * @param mevent the last MouseEvent that caused the edit to occur, can be - * null. - */ - public void edit(OMGraphic omg, MouseEvent mevent) { - - OMDrawingTool dt = getDrawingTool(); - - if (dt != null && dt.canEdit(omg.getClass())) { - - dt.resetBehaviorMask(); - - MouseDelegator mDelegator = dt.getMouseDelegator(); - MapMouseMode omdtmm = dt.getMouseMode(); - if (!omdtmm.isVisible()) { - dt.setMask(OMDrawingTool.PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK); - } - - if (dt.select(omg, this, mevent)) { - - if (activeFace != null) { - activeFace.enableBoundaryButtons(!drawingTool.isActivated()); - } - - // OK, means we're editing - let's lock up the - // MouseMode - dt.getCurrentEditable().getStateMachine().setSelected(); - // Check to see if the DrawingToolMouseMode wants to - // be invisible. If it does, ask the current - // active MouseMode to be the proxy for it... - if (!omdtmm.isVisible() && mDelegator != null) { - MapMouseMode mmm = mDelegator.getActiveMouseMode(); - if (mmm.actAsProxyFor(omdtmm, MapMouseSupport.PROXY_DISTRIB_MOUSE_MOVED - & MapMouseSupport.PROXY_DISTRIB_MOUSE_DRAGGED & MapMouseSupport.PROXY_DISTRIB_MOUSE_CLICKED)) { - setProxyMouseMode(mmm); - } else { - // WHOA, couldn't get proxy lock - bail - dt.deactivate(); - } - } - } - } - } - - /** - * Launch the drawing tool to create a new EditableOMGraphic, which is - * undefined at this point. - * - * @param omg EditableOMGraphic in an undefiend state. - * @return OMGraphic created for drawing tool. - */ - protected OMGraphic create(EditableOMGraphic omg) { - - OMDrawingTool dt = getDrawingTool(); - OMGraphic ret = null; - if (dt != null) { - - dt.resetBehaviorMask(); - - MapMouseMode omdtmm = dt.getMouseMode(); - MouseDelegator mDelegator = dt.getMouseDelegator(); - if (!omdtmm.isVisible()) { - dt.setMask(OMDrawingTool.PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK); - } - - ret = dt.edit(omg, this, null); - - if (ret != null) { - - if (activeFace != null) { - activeFace.enableBoundaryButtons(!drawingTool.isActivated()); - } - - // OK, means we're editing - let's lock up the - // MouseMode - dt.getCurrentEditable().getStateMachine().setUndefined(); - - // Check to see if the DrawingToolMouseMode wants to - // be invisible. If it does, ask the current - // active MouseMode to be the proxy for it... - if (!omdtmm.isVisible() && mDelegator != null) { - MapMouseMode mmm = mDelegator.getActiveMouseMode(); - if (mmm.actAsProxyFor(omdtmm, MapMouseSupport.PROXY_DISTRIB_MOUSE_MOVED - & MapMouseSupport.PROXY_DISTRIB_MOUSE_DRAGGED & MapMouseSupport.PROXY_DISTRIB_MOUSE_CLICKED)) { - setProxyMouseMode(mmm); - } else { - // WHOA, couldn't get proxy lock - bail - dt.deactivate(); - } - } - } - } - - return ret; - } - - /** - * Called by the drawing tool when editing is complete. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - releaseProxyMouseMode(); - if (activeFace != null) { - activeFace.handleBoundary(omg, action); - if (activeFace != null) { - activeFace.enableBoundaryButtons(!drawingTool.isActivated()); - } - } - } - - protected MapMouseMode proxyMMM = null; - - /** - * Set the ProxyMouseMode for the internal drawing tool, if there is one. Can - * be null. Used to reset the mouse mode when drawing's complete. This is the - * mouse mode that the drawing tool mouse mode is hiding behind. - */ - protected synchronized void setProxyMouseMode(MapMouseMode mmm) { - proxyMMM = mmm; - } - - /** - * Get the ProxyMouseMode for the internal drawing tool, if there is one. May - * be null. Used to reset the mouse mode when drawing's complete. This is the - * mouse mode that the drawing tool mouse mode is hiding behind. - */ - protected synchronized MapMouseMode getProxyMouseMode() { - return proxyMMM; - } - - /** - * If the DrawingToolLayer is using a hidden OMDrawingTool, release the proxy - * lock on the active MapMouseMode. - */ - public void releaseProxyMouseMode() { - MapMouseMode pmmm = getProxyMouseMode(); - OMDrawingTool dt = getDrawingTool(); - if (pmmm != null && dt != null) { - if (pmmm.isProxyFor(dt.getMouseMode())) { - - pmmm.releaseProxy(); - setProxyMouseMode(null); - } - - if (dt.isActivated()) { - dt.deactivate(); - } - } - } - - String getFileName() { - return fileName; - } - - void setFileName(String fileName) { - this.fileName = fileName; - } - - OMDrawingTool getDrawingTool() { - return drawingTool; - } - - void setDrawingTool(OMDrawingTool drawingTool) { - this.drawingTool = drawingTool; - } - - DrawingAttributes getRectDA() { - return rectDA; - } - - void setRectDA(DrawingAttributes rectDA) { - this.rectDA = rectDA; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.PaintListener#listenerPaint(Object source, java.awt.Graphics) - */ - public void listenerPaint(Object source, Graphics graphics) { - if (activeFace != null) { - activeFace.paintBoundaries(graphics); - } - } - - protected Projection proj; - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.event.ProjectionListener#projectionChanged(com.bbn.openmap - * .event.ProjectionEvent) - */ - public void projectionChanged(ProjectionEvent e) { - proj = e.getProjection(); - - for (ZoomLevelMakerFace face : faces) { - face.generate(proj); - } - } - - protected class ConfirmationDialog - extends JDialog { - private static final long serialVersionUID = 1L; - Properties launchProps = new Properties(); - - /** - * @param frame - * @param locationComp - * @param title - * @param mapTileMakerComponent - */ - public ConfirmationDialog(Frame frame, Component locationComp, String title, MapTileMakerComponent mapTileMakerComponent) { - super(frame, title, true); - Container contentPane = getContentPane(); - - JLabel info = new JLabel(); - - StringBuffer content = new StringBuffer(); - - int faceCount = 0; - for (ZoomLevelMakerFace face : faces) { - if (face.isInclude()) { - faceCount++; - } - } - - if (faceCount == 0) { - String no_zoom_levels_were_included = - i18n.get(MapTileMakerComponent.class, "no_zoom_levels_were_included", - "No zoom levels were included for tile creation"); - content.append("

").append(no_zoom_levels_were_included).append(".

"); - // Don't need scroll pane for this message. - contentPane.add(info); - } else { - setPreferredSize(new Dimension(600, 500)); - - // For the list, add scroll pane and set size - JScrollPane scrollPane = - new JScrollPane(info, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - - contentPane.add(scrollPane, BorderLayout.CENTER); - - content.append(""); - String launching_maptilemaker = - i18n.get(MapTileMakerComponent.class, "launching_maptilemaker", "Launching MapTileMaker with these settings"); - content.append("

").append(launching_maptilemaker).append(":

"); - StringBuffer zoomLevelList = new StringBuffer(); - StringBuffer totalLayers = null; - - for (ZoomLevelMakerFace face : faces) { - if (face.isInclude()) { - ZoomLevelMaker zli = face.getZoomLevelMaker(); - - zli.setPropertyPrefix("zoom" + zli.getZoomLevel()); - zoomLevelList.append(" ").append(zli.getPropertyPrefix()); - String zoom_level = i18n.get(MapTileMakerComponent.class, "zoom_level", "Zoom Level"); - zli.name = zoom_level + " " + zli.getZoomLevel(); - - int rangeVal = zli.getRange(); - if (rangeVal < zli.getZoomLevel()) { - zli.name += " to " + rangeVal; - } - - String configuration_for = i18n.get(MapTileMakerComponent.class, "configuration_for", "Configuration for"); - zli.description = configuration_for + " " + zli.name; - zli.layers = new ArrayList(); - zli.bounds = new ArrayList(); - - boolean buildLayerList = false; - - content.append("


").append(zoom_level).append(" ").append(zli.name) - .append(""); - String layers_string = i18n.get(MapTileMakerComponent.class, "layers_string", "Layers"); - content.append("
    ").append(layers_string).append(":"); - for (LayerObject lo : face.layerList) { - - if (totalLayers == null) { - totalLayers = new StringBuffer(); - buildLayerList = true; - } - - if (lo.isSelected()) { - content.append("
  • ").append(lo.layer.getName()); - zli.layers.add(lo.layer.getPropertyPrefix()); - } - - if (buildLayerList) { - totalLayers.append(lo.layer.getPropertyPrefix()).append(" "); - lo.layer.getProperties(launchProps); - } - } - content.append("
"); - String coverage_string = i18n.get(MapTileMakerComponent.class, "coverage_string", "Coverage"); - content.append("
    ").append(coverage_string).append(":"); - - if (face.boundsObjectList == null || face.boundsObjectList.isEmpty()) { - int edgeTileCount = face.zfi.getEdgeTileCount(); - String entire_earth = i18n.get(MapTileMakerComponent.class, "entire_earth", "Entire Earth"); - content.append("
  • ").append(entire_earth).append(" (").append(edgeTileCount).append("x") - .append(edgeTileCount).append(" tiles)"); - } else { - for (BoundsObject bo : face.boundsObjectList) { - OMRect rect = bo.bounds; - content.append("
  • (").append(rect.getNorthLat()).append(", ").append(rect.getWestLon()).append(", ") - .append(rect.getSouthLat()).append(", ").append(rect.getEastLon()).append(")"); - - zli.bounds.add(zli.createProperBounds(rect.getWestLon(), rect.getNorthLat(), rect.getEastLon(), - rect.getSouthLat())); - } - } - content.append("
"); - - zli.getProperties(launchProps); - } - } - - launchProps.put(MapTileMaker.ZOOM_LEVELS_PROPERTY, zoomLevelList.toString().trim()); - if (totalLayers != null) { - launchProps.put(ImageServer.ImageServerLayersProperty, totalLayers.toString().trim()); - } - if (transparentTiles) { - launchProps.put(ImageServer.BackgroundProperty, "00000000"); - } else { - MapHandler mh = (MapHandler) getBeanContext(); - MapBean mb = mh.get(MapBean.class); - Color background = mb.getBackground(); - String colorString = Integer.toHexString(background.getRGB()); - launchProps.put(ImageServer.BackgroundProperty, colorString); - } - - // TODO - make all of these options in the GUI - launchProps.put(ImageServer.AntiAliasingProperty, "true"); - launchProps.put(MapTileMaker.ROOT_DIRECTORY_PROPERTY, rootDir); - launchProps.put("formatters", "png"); - launchProps.put("png.class", "com.bbn.openmap.image.PNGImageIOFormatter"); - - content.append(""); - } - - info.setText(content.toString()); - info.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - - JPanel buttonPanel = new JPanel(); - - String create_map_tiles = i18n.get(MapTileMakerComponent.class, "create_map_tiles", "Create Map Tiles"); - JButton confirm = new JButton(create_map_tiles); - confirm.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - ConfirmationDialog.this.setVisible(false); - launchTileMaker(getLaunchProps()); - } - }); - - if (faceCount > 0) { - buttonPanel.add(confirm); - } - - String cancel_string = i18n.get(MapTileMakerComponent.class, "cancel_string", "Cancel"); - JButton cancel = new JButton(cancel_string); - cancel.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - ConfirmationDialog.this.setVisible(false); - } - }); - buttonPanel.add(cancel); - - contentPane.add(buttonPanel, BorderLayout.PAGE_END); - - pack(); - setLocationRelativeTo(locationComp); - } - - Properties getLaunchProps() { - return launchProps; - } - - } - - protected class TileWorker - implements Callable { - - Properties props; - - protected TileWorker(Properties properties) { - props = properties; - - } - - public Boolean call() { - MapTileMaker tileMaker = new MapTileMaker(props); - tileMaker.makeTiles(); - - return Boolean.TRUE; - } - } - - protected class TileRunnable - implements Runnable { - - Properties props; - boolean cancel = false; - Future work = null; - - protected TileRunnable(Properties properties) { - props = properties; - } - - public synchronized void cancel() { - cancel = true; - } - - public void run() { - - work = TaskService.singleton().spawn(new TileWorker(props)); - try { - while (!work.isDone()) { - if (cancel) { - work.cancel(true); - } - } - } catch (CancellationException ce) { - } - - if (cancelDialog != null) { - cancelDialog.setVisible(false); - cancelDialog.dispose(); - cancelDialog = null; - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileRequester.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileRequester.java deleted file mode 100644 index a54f1a2a6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileRequester.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -/** - * An interface for a Class that makes requests from a MapTileFactory, and may - * provide intermittent status updates on whether to continue work or update the - * current fetched tiles. - * - * @author dietrick - */ -public interface MapTileRequester { - - /** - * Called when the provided OMGraphicList has another tile added to it, so - * the list can be repainted if the caller is interested in incremental - * updates. - */ - void listUpdated(); - - /** - * Asked by the MapTileFactory if the tile fetching should continue. Called - * during stable times, just to make sure that the currently fetched tile - * set is still wanted. Safe to always return true, but if you want the - * TileFactory to forget what it's doing (like the projection changed), then - * return false; - * - * @return true of the MapTileFactory should keep collecting tiles for the - * current request. - */ - boolean shouldContinue(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileUtil.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileUtil.java deleted file mode 100644 index bf6aa23c6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/MapTileUtil.java +++ /dev/null @@ -1,455 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.ZipOutputStream; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.FileUtils; - -/** - * A utility class to help manage tile trees. Use the builders to configure and - * launch the MapTileUtil. - * - * @author dietrick - */ -public class MapTileUtil { - - static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile"); - - public final static String SOURCE_PROPERTY = "source"; - public final static String BOUNDS_PROPERTY = "bounds"; - public final static String DESTINATION_PROPERTY = "destination"; - public final static String IMAGEFORMAT_PROPERTY = "format"; - public final static String ZOOMLEVEL_PROPERTY = "zoom"; - - public final static int ZOOM_LEVELS = 21; - - MapTileCoordinateTransform mtcTransform; - List boundsList; - boolean[] zoomLevels; - - public MapTileUtil(Action builder) { - boundsList = builder.boundsList; - zoomLevels = builder.zoomLevels; - mtcTransform = builder.mtcTransform; - } - - /** - * Figure out which tiles need action, based on settings. Calls - * Action.action() for each tile on the builder. Designed to be called from - * Action.go(). - * - * @param builder - */ - public void grabTiles(Action builder) { - - if (boundsList == null) { - boundsList = new ArrayList(); - boundsList.add(new double[] { - 80, - -180, - -80, - 180 - }); - } - - for (int i = 0; i < ZOOM_LEVELS; i++) { - - // Check the zoom level. If they aren't specified, only do 0-14 - if (zoomLevels == null) { - if (i > 14) - continue; - } else { - if (!zoomLevels[i]) { - continue; - } - } - - for (double[] bounds : boundsList) { - - int[] uvBounds = - mtcTransform.getTileBoundsForProjection(new LatLonPoint.Double(bounds[0], bounds[1]), - new LatLonPoint.Double(bounds[2], bounds[3]), i); - int uvup = uvBounds[0]; - int uvleft = uvBounds[1]; - int uvbottom = uvBounds[2]; - int uvright = uvBounds[3]; - - int uvleftM = (int) Math.min(uvleft, uvright); - int uvrightM = (int) Math.max(uvleft, uvright); - int uvupM = (int) Math.min(uvbottom, uvup); - int uvbottomM = (int) Math.max(uvbottom, uvup); - - for (int x = uvleftM; x < uvrightM; x++) { - for (int y = uvupM; y < uvbottomM; y++) { - builder.action(x, y, i, this); - } - } - } - } - } - - /** - * For instance... - * - * @param args - */ - public static void main(String[] args) { - - // new URLGrabber("http://tah.openstreetmap.org/Tiles/tile", "/data/tiles").addZoomRange(0, 5).go(); - - // new Copy("/data/sourcetiles", "/data/desttiles").addZoom(17).addBounds(7.8696, 2.324, 2.899, 9.053).go(); - - new Jar("/data/sourcetiles", "/data/dest.jar").addZoomRange(0,17).addBounds(14.042,2.498,.809,15.215).go(); - } - - /** - * A generic builder Action that handles most configuration issues for the - * MapTileUtil. Extend to make MTU do what you want by overriding go and - * action. - * - * @author dietrick - */ - public abstract static class Action { - String source; - String destination; - - // Optional - String format = "png"; - List boundsList; - boolean[] zoomLevels; // 0-20 - MapTileCoordinateTransform mtcTransform = new OSMMapTileCoordinateTransform(); - - public Action(String source, String destination) { - this.source = source; - this.destination = destination; - } - - public Action addBounds(double ulat, double llon, double llat, double rlon) { - if (boundsList == null) { - boundsList = new ArrayList(); - } - - double[] bnds = new double[] { - ulat, - llon, - llat, - rlon - }; - - boundsList.add(bnds); - return this; - } - - public Action addZoom(int zoom) { - if (zoomLevels == null) { - zoomLevels = new boolean[ZOOM_LEVELS]; - } - - try { - zoomLevels[zoom] = true; - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.warning("zoom level invalid, ignoring: " + zoom); - } - return this; - } - - public Action addZoomRange(int zoom1, int zoom2) { - int min = Math.min(zoom1, zoom2); - int max = Math.max(zoom1, zoom2); - for (int z = min; z <= max; z++) { - addZoom(z); - } - return this; - } - - public Action format(String format) { - this.format = format; - return this; - } - - public Action transform(MapTileCoordinateTransform transform) { - mtcTransform = transform; - return this; - } - - public abstract void go(); - - /** - * Called from within grabTiles, with the tile info. You can use this - * information to make a method call on mtu. - * - * @param x tile coordinate - * @param y tile coordinate - * @param zoomLevel tile zoom level - * @param mtu callback - */ - public abstract void action(int x, int y, int zoomLevel, MapTileUtil mtu); - - public String getSource() { - return source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getDestination() { - return destination; - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public List getBoundsList() { - return boundsList; - } - - public void setBoundsList(List boundsList) { - this.boundsList = boundsList; - } - - public boolean[] getZoomLevels() { - return zoomLevels; - } - - public void setZoomLevels(boolean[] zoomLevels) { - this.zoomLevels = zoomLevels; - } - - public MapTileCoordinateTransform getMtcTransform() { - return mtcTransform; - } - - public void setMtcTransform(MapTileCoordinateTransform mtcTransform) { - this.mtcTransform = mtcTransform; - } - } - - /** - * Action that copies tiles from one directory to another. - * - * @author dietrick - */ - public static class Copy - extends Action { - - public Copy(String source, String destination) { - super(source, destination); - } - - public void go() { - if (source != null && destination != null) { - new MapTileUtil(this).grabTiles(this); - } else { - logger.warning("Need a source and destination for tile locations"); - } - } - - public void action(int x, int y, int zoomLevel, MapTileUtil mtu) { - File sourceFile = new File(getSource() + "/" + zoomLevel + "/" + x + "/" + y + "." + format); - File destDir = new File(getDestination() + "/" + zoomLevel + "/" + x); - destDir.mkdirs(); - - File destFile = new File(destDir, y + "." + format); - - try { - if (sourceFile.exists()) { - FileUtils.copy(sourceFile, destFile, 1024); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - /** - * Action that creates a jar file containing the specified files. - * - * @author dietrick - */ - public static class Jar - extends Action { - - /** Will get instantiated if needed */ - ZipOutputStream zoStream = null; - File destinationFile = null; - long fileCount = 0; - int zipTrim = 0; - - public Jar(String source, String destination) { - super(source, destination); - } - - public void go() { - if (source != null && destination != null) { - new MapTileUtil(this).grabTiles(this); - - if (zoStream != null) { - try { - zoStream.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - logger.info("Created " + getDestination() + " with " + fileCount + " files."); - - } else { - logger.warning("Need a source and destination for tile locations"); - } - } - - public void action(int x, int y, int zoomLevel, MapTileUtil mtu) { - File tile = new File(getSource() + "/" + zoomLevel + "/" + x + "/" + y + "." + format); - - if (tile.exists()) { - try { - if (zoStream == null) { - /* - * We need to do this because we need to make sure a zip - * output stream is created only when a file is going to - * be written to it. you can't create a zip file and - * then put nothing into it. - */ - destinationFile = new File(getDestination()); - FileOutputStream fos = new FileOutputStream(destinationFile); - zoStream = new ZipOutputStream(fos); - zipTrim = destinationFile.getParent().length() + 1; - - logger.info("creating " + destinationFile); - - File sourceParentFile = new File(getSource()).getParentFile(); - if (sourceParentFile.exists()) { - File tileDescription = new File(sourceParentFile, StandardMapTileFactory.TILE_PROPERTIES); - if (tileDescription.exists()) { - FileUtils.writeZipEntry(tileDescription, zoStream, zipTrim); - fileCount++; - logger.info("adding " + tileDescription); - } - } - } - - FileUtils.writeZipEntry(tile, zoStream, zipTrim); - fileCount++; - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - } - } - - /** - * A Builder that knows how to download files from a website. - * - * @author dietrick - */ - public static class URLGrabber - extends Action { - - public URLGrabber(String source, String destination) { - super(source, destination); - } - - public void go() { - if (source != null && destination != null) { - new MapTileUtil(this).grabTiles(this); - } else { - logger.warning("Need a source and destination for tile locations"); - } - } - - public void action(int x, int y, int zoomLevel, MapTileUtil mtu) { - grabURLTile(x, y, zoomLevel); - } - - /** - * An action method that will fetch a tile from a URL and copy it to the - * destination directory. - * - * @param x - * @param y - * @param zoomLevel - */ - public void grabURLTile(int x, int y, int zoomLevel) { - - java.net.URL url = null; - - String imagePath = source + "/" + zoomLevel + "/" + x + "/" + y + (format.startsWith(".") ? format : "." + format); - - try { - - url = new java.net.URL(imagePath); - java.net.HttpURLConnection urlc = (java.net.HttpURLConnection) url.openConnection(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("url content type: " + urlc.getContentType()); - } - - if (urlc == null) { - logger.warning("unable to connect to " + imagePath); - return; - } - - if (urlc.getContentType().startsWith("image")) { - - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - - byte[] imageBytes = out.toByteArray(); - - if (destination != null) { - File localFile = - new File(destination + "/" + zoomLevel + "/" + x + "/" + y - + (format.startsWith(".") ? format : "." + format)); - - File parentDir = localFile.getParentFile(); - parentDir.mkdirs(); - - FileOutputStream fos = new FileOutputStream(localFile); - fos.write(imageBytes); - fos.flush(); - fos.close(); - } - - } // end if image - } catch (java.net.MalformedURLException murle) { - logger.warning("WebImagePlugIn: URL \"" + imagePath + "\" is malformed."); - } catch (java.io.IOException ioe) { - logger.warning("Couldn't connect to " + imagePath + "Connection Problem"); - } - - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/OSMMapTileCoordinateTransform.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/OSMMapTileCoordinateTransform.java deleted file mode 100644 index b92532405..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/OSMMapTileCoordinateTransform.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.MercatorUVGCT; - -/** - * The implementation of TileCoordinateTransformation for OpenStreetMap tile - * coordinate layout. - * - * @author dietrick - */ -public class OSMMapTileCoordinateTransform extends AbstractMapTileCoordinateTransform { - - /** - * @param latlon a Point2D whose x component is the longitude and y - * component is the latitude - * @param zoom Tile Map Service (TMS) style zoom level (0-19 usually) - * @param ret LatLonPoint to fill and return, to avoid allocating return - * object. - * @return The "tile number" whose x and y components each are floating - * point numbers that represent the distance in number of tiles from - * the origin of the whole map at this zoom level. At zoom=0, the - * lat,lon point of 0,0 maps to 0.5,0.5 since there is only one tile - * at zoom level 0. - */ - public Point2D latLonToTileUV(Point2D latlon, int zoom, Point2D ret) { - if (ret == null) { - ret = new Point2D.Double(); - } - - ret.setLocation(((latlon.getX() + 180.0) / 360.0 * Math.pow(2.0, zoom)), ((1.0 - Math.log(Math.tan(latlon.getY() - * Math.PI / 180.0) - + (1.0 / Math.cos(latlon.getY() * Math.PI / 180.0))) - / Math.PI) / 2.0 * (Math.pow(2, zoom)))); - return ret; - - // Much slower! - // transform.setZoomLevel(zoom); - // return transform.forward(latlon.getY(), latlon.getX(), ret); - } - - /** - * @param tileUV a Point2D whose x,y coordinates represent the distance in - * number of tiles (each 256x256) from the origin (where the origin - * is 90lat,-180lon) - * @param zoom Tile Map Service (TMS) style zoom level (0-19 usually) - * @param ret LatLonPoint to fill and return, to avoid allocating return - * object. - * @return a Point2D whose x coordinate is the longitude and y coordinate is - * the latitude - */ - public LatLonPoint tileUVToLatLon(Point2D tileUV, int zoom, LatLonPoint ret) { - if (ret == null) { - ret = new LatLonPoint.Double(); - } - - ret.setLocation(360.0 / Math.pow(2.0, zoom) * tileUV.getX() - 180.0, -90.0 - + 360.0 - / Math.PI - * Math.atan(Math.exp((-2.0 * Math.PI * tileUV.getY()) / Math.pow(2.0, zoom) - + Math.PI))); - return ret; - - // Much slower! - // transform.setZoomLevel(zoom); - // return transform.inverse(tileUV.getX(), tileUV.getY(), ret); - } - - /** - * Given a projection, provide the upper, lower, left and right tile - * coordinates that cover the projection area. - * - * @param upperLeft lat/lon coordinate of upper left corner of bounding box. - * @param lowerRight lat/lon coordinate of lower right corner of bounding - * box. - * @param zoomLevel zoom level of desired tiles. - * @return int[], in top, left, bottom and right order. - */ - public int[] getTileBoundsForProjection(Point2D upperLeft, Point2D lowerRight, int zoomLevel) { - - Point2D uvul = latLonToTileUV(upperLeft, zoomLevel); - Point2D uvlr = latLonToTileUV(lowerRight, zoomLevel); - - int[] ret = new int[4]; - - int uvleft = (int) Math.floor(uvul.getX()); - int uvright = (int) Math.ceil(uvlr.getX()); - int uvup = (int) Math.floor(uvul.getY()); - if (uvup < 0) { - uvup = 0; - } - int uvbottom = (int) Math.ceil(uvlr.getY()); - - ret[0] = uvup; - ret[1] = uvleft; - ret[2] = uvbottom; - ret[3] = uvright; - - return ret; - } - - /** - * @return if y coordinates for tiles increase as pixel values increase. - */ - public boolean isYDirectionUp() { - return false; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform#getTransform - * () - */ - public GeoCoordTransformation getTransform(int zoomLevel) { - return new MercatorUVGCT.OSM(zoomLevel); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java deleted file mode 100644 index ca591e15f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java +++ /dev/null @@ -1,366 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The ServerMapTileFactory is an extension to the StandardMapTileFactory that - * can go to a http server to retrieve image tiles. You provide it with a root - * URL that points to the parent directory of the tiles, and then this component - * will add on the zoom/x/y.extension to that directory path to make the call - * for a specific tile. Please make sure you have the permission of the server's - * owner before hammering away at retrieving tiles from it. - * - * This component can be configured using properties: - *

- * - *

- * # Inherited from StandardMapTileFactory
- * rootDir=the URL to the parent directory of the tiles on a server. The factory will construct specific file paths that are appended to this value. 
- * fileExt=the file extension to append to the tile names, should have a period.
- * cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * 
- * # Additional properties
- * localCacheRootDir=if specified, the factory will store tiles locally at this root directory.  This directory is checked before going to the server, too.
- * 
- * - * @author dietrick - */ -public class ServerMapTileFactory extends StandardMapTileFactory implements MapTileFactory, PropertyConsumer { - - public final static String LOCAL_CACHE_ROOT_DIR_PROPERTY = "localCacheRootDir"; - - protected String localCacheDir = null; - - public ServerMapTileFactory() { - this(null); - } - - public ServerMapTileFactory(String rootDir) { - this.rootDir = rootDir; - this.fileExt = ".png"; - verbose = logger.isLoggable(Level.FINE); - } - - /** - * An auxiliary call to retrieve something from the cache, modified to allow - * load method to do some projection calculations to initialize tile - * parameters. If the object is not found in the cache, null is returned. - */ - public Object getFromCache(Object key, int x, int y, int zoomLevel) { - - if (localCacheDir != null && zoomLevelInfo != null) { - String localLoc = buildLocalFilePath(x, y, zoomLevel, getFileExt()); - /** - * If a local cache is defined, then the cache will always use the - * string for the local file as the key. - */ - CacheObject ret = searchCache(localLoc); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "found tile ({0}, {1}) in cache", new Object[] {x, y}); - } - return ret.obj; - } - /** - * Return null if the localized version isn't found in cache when - * local version is defined. - */ - return null; - } - - // Assuming that the localCacheDir is not defined, so the cache objects - // will be using the server location as key - - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - return null; - } - - /** - * Checks the local directory first for a locally cached version of the tile - * before going off to the server. If a local directory is listed as a - * cache, any retrieved files will be stored there for future use. We are - * using the local name of the file as the cache key for all tiles for - * consistency - all tiles are looked up with local cache locations. - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - - if (verbose) { - logger.log(Level.FINE, "fetching file for cache: {0}", key); - } - - byte[] imageBytes = null; - - CacheObject localVersion = super.load(key, x, y, zoomLevel, proj); - - if (localVersion != null) { - logger.log(Level.FINE, "found version of tile in local cache: {0}", key); - return localVersion; - } - - // build file path here uses rootDir, which is the URL. - String imagePath = buildFilePath(x, y, zoomLevel, getFileExt()); - - imageBytes = getImageBytes(imagePath, (String) key); - - if (imageBytes != null && imageBytes.length > 0) { - // image found - ImageIcon ii = new ImageIcon(imageBytes); - - try { - BufferedImage rasterImage = preprocessImage(ii.getImage(), ii.getIconWidth(), ii.getIconHeight()); - OMGraphic raster = createOMGraphicFromBufferedImage(rasterImage, x, y, zoomLevel, proj); - - /* - * Again, create a CacheObject based on the local name if - * the local dir is defined. - */ - if (raster != null) { - return new CacheObject(key, raster); - } - - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "factory interrupted fetching {0}", imagePath); - } - } - - } - - /* - * At this point, nothing was found for this location, so it's an - * empty tile. - */ - return getEmptyTile(key, x, y, zoomLevel, proj); - } - - return null; - } - - /** - * Tries to get the image bytes from imagePath URL. If image found, will - * write it locally to localFilePath for caching. - * - * @param imagePath - * the source URL image path. - * @param localFilePath - * the caching local file path - * @return byte[] of image - */ - public byte[] getImageBytes(String imagePath, String localFilePath) { - byte[] imageBytes = null; - - try { - java.net.URL url = new java.net.URL(imagePath); - java.net.URLConnection urlc = url.openConnection(); - urlc.setConnectTimeout(800); - - if (logger.isLoggable(Level.FINER)) { - logger.log(Level.FINER, "url content type: {0}", urlc.getContentType()); - } - - if (urlc.getContentType() == null) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "unable to connect to (tile might be unavailable): {0}", imagePath); - } - - // text - } else if (urlc.getContentType().startsWith("text")) { - java.io.BufferedReader bin = new java.io.BufferedReader( - new java.io.InputStreamReader(urlc.getInputStream())); - String st; - StringBuilder message = new StringBuilder(); - while ((st = bin.readLine()) != null) { - message.append(st); - } - - // Debug.error(message.toString()); - // How about we toss the message out to the user - // instead? - logger.fine(message.toString()); - - // image - } else if (urlc.getContentType().startsWith("image")) { - - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - - imageBytes = out.toByteArray(); - - if (localFilePath != null && localCacheDir != null) { - File localFile = new File(localFilePath); - - File parentDir = localFile.getParentFile(); - parentDir.mkdirs(); - - FileOutputStream fos = new FileOutputStream(localFile); - fos.write(imageBytes); - fos.flush(); - fos.close(); - } - - } // end if image - } catch (java.net.MalformedURLException murle) { - logger.log(Level.WARNING, "ServerMapTileFactory: URL \"{0}\" is malformed.", imagePath); - } catch (java.io.IOException ioe) { - logger.log(Level.FINE, "Couldn't connect to {0}, connection problem", imagePath); - } - - return imageBytes; - - } - - /** - * Acts the same as the buildFilePath method, but works for a local - * directory specified in the properties. - * - * @param x - * tile coordinate - * @param y - * tile coordinate - * @param z - * zoom level - * @param fileExt - * file extension for image tiles. - * @return new path for tile file - */ - public String buildLocalFilePath(int x, int y, int z, String fileExt) { - if (localTilePathBuilder == null) { - localTilePathBuilder = new TilePathBuilder(localCacheDir); - } - - return localTilePathBuilder.buildTilePath(x, y, z, fileExt); - } - - private TilePathBuilder localTilePathBuilder = null; - - /** - * Creates a unique cache key for this tile based on zoom, x, y. This method - * was created so the ServerMapTileFactory could override it and use local - * cache names for keys if a local cache was being used. - * - * @param x - * tile coord. - * @param y - * tile coord. - * @param z - * zoomLevel. - * @param fileExt - * file extension. - * @return String used in cache. - */ - protected String buildCacheKey(int x, int y, int z, String fileExt) { - if (localCacheDir != null) { - return buildLocalFilePath(x, y, z, fileExt); - } - return super.buildCacheKey(x, y, z, fileExt); - } - - public Properties getProperties(Properties getList) { - getList = super.getProperties(getList); - getList.put(prefix + LOCAL_CACHE_ROOT_DIR_PROPERTY, PropUtils.unnull(localCacheDir)); - return getList; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - LOCAL_CACHE_ROOT_DIR_PROPERTY, "Local Cache Tile Directory", - "Root directory containing image tiles retrieved from image server.", - "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - return list; - } - - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - localCacheDir = setList.getProperty(prefix + LOCAL_CACHE_ROOT_DIR_PROPERTY, localCacheDir); - - if (localCacheDir != null && localCacheDir.trim().isEmpty()) { - localCacheDir = null; - } - } - - public String getInitPropertiesOrder() { - return super.getInitPropertiesOrder() + " " + LOCAL_CACHE_ROOT_DIR_PROPERTY; - } - - /** - * Tell the factory to dump the cache. For the ServerMapTileFactory, this - * also includes the local file cache dir. - */ - public void reset() { - super.reset(); - if (localCacheDir != null) { - File localCacheDirFile = new File(localCacheDir); - if (localCacheDirFile.exists()) { - try { - FileUtils.deleteFile(localCacheDirFile); - } catch (IOException e) { - logger.log(Level.FINE, "There's a problem deleting local cache directory: {0}", e.getMessage()); - } - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ShpFileEmptyTileHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ShpFileEmptyTileHandler.java deleted file mode 100644 index 5baf37166..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ShpFileEmptyTileHandler.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.Properties; - -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * Uses a Shape file to figure out if a tile is over water or over land, so the - * proper color is used for an empty tile. In addition to all of the properties - * listed in the SimpleEmptyTileHandler, there are other properties to set up a - * shape layer to render into empty tiles in an attempt to fill in empty tiles - * on the fly. - *

- * - *

- * emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.ShpFileEmptyTileHandler
- * shpFile=File, resource or URL to shape file for land representation.
- * 
- * # Properties to set how the shp file contents are rendered.
- * land.fillColor=hex RGB color
- * land.lineColor=hex RGB color
- * land.fillPattern=path to resource, file or URL of pattern to use for tile fill.
- * 
- * # From SimpleEmptyTileHandler superclass, handling the 'water'
- * # clear by default if not specified
- * background.fillColor=hex RGB color
- * background.lineColor=hex RGB color
- * background.fillPattern=path to resource, file or URL of pattern to use for tile fill.
- * 
- * # Zoom level to start using noCoverage attributes.  Is 0 by default if the shape file 
- * # is not specified.  If the shape file is specified and this isn't the zoom level 
- * # will be set to 20.
- * noCoverageZoom=zoom level when you don't want empty tiles, you want no coverage tiles
- * 
- * # How to render standard empty tiles, will be clear if not defined
- * noCoverage.fillColor=hex RGB color
- * noCoverage.lineColor=hex RGB color
- * noCoverage.fillPattern=path to resource, file or URL of pattern to use for tile fill.
- * 
- * - * - * @author ddietrick - */ -public class ShpFileEmptyTileHandler extends SimpleEmptyTileHandler { - public final static String LAND_ATTRIBUTES_PROPERTY = "land"; - public final static String SHP_FILE_PROPERTY = "shpFile"; - protected ShapeLayer shapeStuff; - protected DrawingAttributes landAttributes = DrawingAttributes.getDefaultClone(); - - public ShpFileEmptyTileHandler() { - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.dataAccess.mapTile.EmptyTileHandler#getOMGraphicForEmptyTile - * (java.lang.String, int, int, int, - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform, - * com.bbn.openmap.proj.Projection) - */ - public BufferedImage getImageForEmptyTile(String imagePath, int x, int y, int zoomLevel, - MapTileCoordinateTransform mtcTransform, - Projection proj) { - - if (shapeStuff != null && zoomLevel < noCoverageZoom) { - - BufferedImage bi = new BufferedImage(TILE_SIZE, TILE_SIZE, BufferedImage.TYPE_INT_ARGB); - Graphics g = bi.getGraphics(); - - LatLonPoint center = mtcTransform.tileUVToLatLon(new Point2D.Double(x + .5, y + .5), zoomLevel, new LatLonPoint.Double()); - Mercator merc = new Mercator(center, mtcTransform.getScaleForZoom(zoomLevel), TILE_SIZE, TILE_SIZE); - - ((Graphics2D) g).setPaint(backgroundAtts.getFillPaint()); - g.fillRect(0, 0, TILE_SIZE, TILE_SIZE); - - if (shapeStuff != null) { - shapeStuff.setDrawingAttributes(landAttributes); - shapeStuff.renderDataForProjection(merc, g); - } - - g.dispose(); - return bi; - - } else { - return super.getImageForEmptyTile(imagePath, x, y, zoomLevel, mtcTransform, proj); - } - } - - public ShapeLayer getShapeStuff() { - return shapeStuff; - } - - public void setShapeStuff(ShapeLayer shapeStuff) { - this.shapeStuff = shapeStuff; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - landAttributes.setProperties(prefix + LAND_ATTRIBUTES_PROPERTY, props); - - String shapeFileName = props.getProperty(prefix + SHP_FILE_PROPERTY); - if (shapeFileName != null) { - shapeStuff = new ShapeLayer(shapeFileName); - shapeStuff.setDrawingAttributes(landAttributes); - - // If noCoverageZoom property is not set and the shape file is, then - // make the default action to show the shape file. - if (props.getProperty(prefix + NO_COVERAGE_ZOOM_PROPERTY) == null) { - noCoverageZoom = 20; - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - landAttributes.getProperties(props); - return props; - } - - /** - * @return the landAttributes - */ - public DrawingAttributes getLandAttributes() { - return landAttributes; - } - - /** - * @param landAttributes the landAttributes to set - */ - public void setLandAttributes(DrawingAttributes landAttributes) { - this.landAttributes = landAttributes; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/SimpleEmptyTileHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/SimpleEmptyTileHandler.java deleted file mode 100644 index e01bf62f8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/SimpleEmptyTileHandler.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Graphics; -import java.awt.image.BufferedImage; -import java.util.Properties; -import java.util.logging.Logger; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * An EmptyTileHandler that uses DrawingAttributes to create a rectangle to fill in for empty tiles. You can set one of - * these up using the properties for a MapTileLayer, and those properties will trickle down through the MapTileServer, - * which will in turn create one of these.

- * - *

- * emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.SimpleEmptyTileHandler
- *
- * # The zoom level to start using the no coverage parameters. O by default, so that the
- * # noCoverage parameters are used to create what is sent back by default.
- * noCoverageZoom=zoom level when you don't want empty tiles, you want no coverage tiles
- *
- * # If an image is not defined, these colors will be used to create no coverage
- * # tiles.  If not specified, nothing will be sent back.
- * noCoverage.fillColor=hex RGB color
- * noCoverage.lineColor=hex RGB color
- * noCoverage.fillPattern=path to resource, file or URL of pattern to use for tile fill.
- *
- * # If not specified, no image will be returned if zoom level less than noCoverageZoom.  If you
- * # want to use these parameters to set up on-the-fly filled tile images, make sure you also adjust
- * # the noCoverageZoom level.
- * background.fillColor=hex RGB color
- * background.lineColor=hex RGB color
- * background.fillPattern=path to resource, file or URL of pattern to use for tile fill.
- *
- * 
- * - * @author ddietrick - */ -public class SimpleEmptyTileHandler - implements EmptyTileHandler, PropertyConsumer { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile.EmptyTileHandler"); - public final static String BACKGROUND_PROPERTY = "background"; - public final static String NO_COVERAGE_PROPERTY = "noCoverage"; - public final static String NO_COVERAGE_ZOOM_PROPERTY = "noCoverageZoom"; - public final static int TILE_SIZE = 256; - protected DrawingAttributes backgroundAtts = DrawingAttributes.getDefaultClone(); - protected DrawingAttributes noCoverageAtts = DrawingAttributes.getDefaultClone(); - // Property prefix - protected String prefix; - protected BufferedImage emptyTileImage; - protected BufferedImage backgroundTileImage; - /** - * The zoom level at which point the EmptyTileHandler will create no-coverage tiles, if defined. - */ - protected int noCoverageZoom = 0; - - // Needed for ComponentFactory construction - public SimpleEmptyTileHandler() { - noCoverageAtts.setLinePaint(OMColor.clear); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.EmptyTileHandler#getOMGraphicForEmptyTile (java.lang.String, int, int, - * int, com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform, com.bbn.openmap.proj.Projection) - */ - public BufferedImage getImageForEmptyTile(String imagePath, int x, int y, int zoomLevel, - MapTileCoordinateTransform mtcTransform, Projection proj) { - if (zoomLevel < noCoverageZoom) { - return backgroundTileImage; - } else { - logger.fine("returning emptyTileImage: " + emptyTileImage); - return emptyTileImage; - } - } - - public void setPropertyPrefix(String pref) { - prefix = pref; - } - - public String getPropertyPrefix() { - return prefix; - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - DrawingAttributes backgroundDA = DrawingAttributes.getDefaultClone(); - DrawingAttributes noCoverageDA = DrawingAttributes.getDefaultClone(); - - backgroundDA.setProperties(prefix + BACKGROUND_PROPERTY, props); - noCoverageDA.setProperties(prefix + NO_COVERAGE_PROPERTY, props); - - setBackgroundAtts(backgroundDA); - setNoCoverageAtts(noCoverageDA); - - noCoverageZoom = PropUtils.intFromProperties(props, prefix + NO_COVERAGE_ZOOM_PROPERTY, noCoverageZoom); - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - getBackgroundAtts().getProperties(props); - getNoCoverageAtts().getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - getBackgroundAtts().getPropertyInfo(props); - getNoCoverageAtts().getPropertyInfo(props); - return props; - } - - /** - * Create a BufferedImage from the provided DrawingAttributes. - * - * @param da DrawingAttributes - * @return BudderedImage with TYPE_INT_ARGB - */ - protected BufferedImage createTileImageFromDrawingAttributes(DrawingAttributes da) { - BufferedImage bi = null; - - if (da != null) { - OMRect rect = new OMRect(0, 0, TILE_SIZE, TILE_SIZE); - da.setTo(rect); - rect.generate(new com.bbn.openmap.proj.Mercator(new LatLonPoint.Double(), 100000, TILE_SIZE, TILE_SIZE)); - - bi = new BufferedImage(TILE_SIZE, TILE_SIZE, BufferedImage.TYPE_INT_ARGB); - Graphics g = bi.getGraphics(); - rect.render(g); - g.dispose(); - } - - return bi; - } - - /** - * @return the backgroundAtts - */ - public DrawingAttributes getBackgroundAtts() { - return backgroundAtts; - } - - /** - * Set the background drawing attributes and create the cached backgroundTileImage if the drawing attributes provided - * doesn't match what's there. If backgroundAtts never gets set or is set to the default DrawingAttributes object, - * the backgroundTileImage won't get created and no background images will be returned. - * - * @param backgroundAtts the backgroundAtts to set - */ - public void setBackgroundAtts(DrawingAttributes backgroundAtts) { - if (backgroundAtts != null && !backgroundAtts.equals(this.backgroundAtts)) { - backgroundTileImage = createTileImageFromDrawingAttributes(backgroundAtts); - this.backgroundAtts = backgroundAtts; - } - - if (this.backgroundAtts == null) { - this.backgroundAtts = DrawingAttributes.getDefaultClone(); - } - } - - /** - * @return the noCoverageAtts - */ - public DrawingAttributes getNoCoverageAtts() { - return noCoverageAtts; - } - - /** - * Set the no-coverage drawing attributes and create the cached emptyTileImage if the drawing attributes provided - * doesn't match what's there. If noCoverageAtts never gets set or is set to the default DrawingAttributes object, - * the emptyTileImage won't get created and no no-coverage images will be returned. - * - * @param noCoverageAtts the noCoverageAtts to set - */ - public void setNoCoverageAtts(DrawingAttributes noCoverageAtts) { - if (noCoverageAtts != null && !noCoverageAtts.equals(this.noCoverageAtts)) { - logger.fine("the no coverage atts are not standard, creating a new emptyTileImage"); - emptyTileImage = createTileImageFromDrawingAttributes(noCoverageAtts); - this.noCoverageAtts = noCoverageAtts; - } else { - logger.fine("++++++++ " + noCoverageAtts + " vs " + this.noCoverageAtts); - } - - if (this.noCoverageAtts == null) { - this.noCoverageAtts = DrawingAttributes.getDefaultClone(); - } - } - - /** - * @return the noCoverageZoom - */ - public int getNoCoverageZoom() { - return noCoverageZoom; - } - - /** - * @param noCoverageZoom the noCoverageZoom to set - */ - public void setNoCoverageZoom(int noCoverageZoom) { - this.noCoverageZoom = noCoverageZoom; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardImagePreparer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardImagePreparer.java deleted file mode 100644 index c1612a4fc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardImagePreparer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.image.BufferedImage; - -import com.bbn.openmap.image.BufferedImageHelper; - -/** - * This is the standard map tile preparer, setting up the factory with ARGB - * images. - * - * @author dietrick - */ -public class StandardImagePreparer - implements TileImagePreparer { - - public void prepareForEmptyTile(MapTileFactory factory) { - // Noop - } - - public BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - if (origImage instanceof BufferedImage) { - return (BufferedImage) origImage; - } else { - return BufferedImageHelper.getBufferedImage(origImage, 0, 0, imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java deleted file mode 100644 index f9fb07287..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java +++ /dev/null @@ -1,1259 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ClasspathHacker; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The StandardImageTileFactory is a TileFactory implementation that retrieves - * image tiles from local storage. These tiles are assumed to be stored in the - * local file system, at some root directory, and then in some hierarchy like - * zoom-level/x coord/y coord.file-extension. This class can be extended to - * allow different tile naming/storing conventions to be used. - *

- * - * This component can be configured using properties: - *

- * - *

- * rootDir=the path to the parent directory of the tiles. The factory will construct specific file paths that are appended to this value.
- * fileExt=the file extension to append to the tile names
- * cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TSMMapTileCoordinateTransform
- * # what to do about missing tiles?
- * emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.SimpleEmptyTileHandler
- * # Set a tile image preparer, if you want to change how images are rendered (greyscale, for instance)
- * tileImagePreparer=com.bbn.openmap.dataAccess.mapTile.StandardImagePreparer
- * # or
- * tileImagePreparer=com.bbn.openmap.dataAccess.mapTile.GreyscaleImagePreparer
- * 
- * - * @author dietrick - */ -public class StandardMapTileFactory extends CacheHandler implements MapTileFactory, PropertyConsumer { - protected String prefix = null; - protected final static Logger logger = Logger - .getLogger("com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory"); - protected final static Logger mapTileLogger = Logger.getLogger("MAPTILE_DEBUGGING"); - public final static String ROOT_DIR_PROPERTY = "rootDir"; - public final static String FILE_EXT_PROPERTY = "fileExt"; - public final static String CACHE_SIZE_PROPERTY = "cacheSize"; - public final static String MTCTRANSFORM_PROPERTY = "mapTileTransform"; - public final static String EMPTY_TILE_HANDLER_PROPERTY = "emptyTileHandler"; - public final static String ZOOM_LEVEL_INFO_PROPERTY = "zoomLevelInfo"; - public final static String ZOOM_LEVEL_TILE_SIZE_PROPERTY = "zoomLevelTileSize"; - public final static String TILE_IMAGE_PREPARER_PROPERTY = "tileImagePreparer"; - /** - * Inserted into properties loaded via tiles.omp, so that the EmptyTileHandler - * can know where the tile set is located, in case it needs to know the absolute - * path. Will contain the root directory path specified in the factory - * properties, as opposed to any rootDir property set in the tiles.omp file that - * would specify a relative root directory path. - */ - public final static String ROOT_DIR_PATH_PROPERTY = "rootDirPath"; - /** - * The name of the properties file that the factory looks for in the root - * directory of the data (tiles.omp). - */ - public final static String TILE_PROPERTIES = "tiles.omp"; - protected ZoomLevelInfo zoomLevelInfo = new ZoomLevelInfo(); - protected String rootDir; - protected String fileExt = ".png"; - protected String rootDirProperty; // For writing out later, if necessary - protected EmptyTileHandler emptyTileHandler = null; - protected boolean verbose = false; - /** - * The zoom level tile size is used by the factory to determine when it needs to - * get tiles for a different zoom level. The default value is 350. That is, when - * the factory is figuring out what zoom level to use, if the pixel size of a - * tile is greater than or equal to 350 x 350, it decides to check the next zoom - * level for retrieving tiles. This is used instead of just comparing projection - * scales. - */ - protected int zoomLevelTileSize = 350; - protected TileImagePreparer tileImagePreparer; - - /** - * If set, the MapTileRequester will be notified when the list provided in - * getTiles() has been updated, and asked if it should continue with the - * getTiles() request at opportune times, when tile fetching is stable. - */ - protected MapTileRequester mapTileRequester; - /** - * Flag to tell the factory to create the extra tiles off-map. Tends to cause - * the layer to do more work than necessary, so it's not used. - */ - private boolean doExtraTiles = false; - /** - * Coordinate transform for the uv coordinates of the tiles. Different sources - * have different origins for tile coordinates. - */ - protected MapTileCoordinateTransform mtcTransform = new OSMMapTileCoordinateTransform(); - - public StandardMapTileFactory() { - super(100); - verbose = logger.isLoggable(Level.FINE); - } - - public StandardMapTileFactory(MapTileRequester layer, String rootDir, String tileFileExt) { - super(100); - setRootDir(rootDir); - setFileExt(tileFileExt); - verbose = logger.isLoggable(Level.FINE); - this.mapTileRequester = layer; - } - - @Override - public CacheObject load(Object key) { - return null; - } - - /** - * Tell the factory to dump the cache. - */ - public void reset() { - clear(); - } - - /** - * Called to load cache object from data source, when not found in cache. - * - * @param key cache key - * @param x uv x coordinate - * @param y uv y coordinate - * @param zoomLevel zoom level for tile to load - * @param proj passed solely to enable checking if the projection of the - * tiles matches the rendered projection. - * @return CacheObject returned from cache, null if not found - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - String imagePath = (String) key; - if (verbose) { - logger.log(Level.FINE, "fetching file for cache: {0}", imagePath); - } - - try { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - if (imageURL != null) { - - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - OMGraphic raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - - if (raster != null) { - return new CacheObject(imagePath, raster); - } - - } else { - logger.log(Level.FINE, "Can't find resource located at {0}", imagePath); - } - } catch (MalformedURLException e) { - logger.log(Level.FINE, "Can't find resource located at {0}", imagePath); - } catch (InterruptedException e) { - logger.log(Level.FINE, "Reading the image file was interrupted: {0}", imagePath); - } catch (Exception fnfe) { - logger.log(Level.FINE, "file not found: {0}", imagePath); - } - } - return null; - } - - /** - * Creates an OMRaster appropriate for projection and other parameters from a - * buffered image. - * - * @param bi BufferedImage to use for tile. - * @param x x uv coordinate for tile. - * @param y y uv coordinate for tile. - * @param zoomLevel zoom level for tile. - * @param proj the current map projection - * @return OMGraphic (OMScalingRaster or OMWarpingImage, most likely) - * @throws InterruptedException - */ - protected OMGraphic createOMGraphicFromBufferedImage(BufferedImage bi, int x, int y, int zoomLevel, Projection proj) - throws InterruptedException { - - OMGraphic raster = null; - - if (bi != null) { - BufferedImage rasterImage = preprocessImage(bi, bi.getWidth(), bi.getHeight()); - - if (proj instanceof Mercator) { - raster = getTileMatchingProjectionType(rasterImage, x, y, zoomLevel); - } else { - raster = getTileNotMatchingProjectionType(rasterImage, x, y, zoomLevel); - } - - if (mapTileLogger.isLoggable(Level.FINE)) { - raster.putAttribute(OMGraphic.LABEL, - new OMTextLabeler("Tile: " + zoomLevel + "|" + x + "|" + y, OMText.JUSTIFY_CENTER)); - raster.setSelected(true); - } - } - - return raster; - } - - /** - * Create an OMScalingRaster that matches the basic projection of the current - * map. Only scales evenly for the opposite corner points. - * - * @param image BufferedImage created from tile file - * @param x uv x coordinate - * @param y uv y coordinate - * @param zoomLevel zoom level for tile retrieval - * @return OMGraphic, but really an OMScalingRaster. - */ - protected OMGraphic getTileMatchingProjectionType(BufferedImage image, int x, int y, int zoomLevel) { - - Point2D pnt = new Point2D.Double(); - pnt.setLocation(x, y); - Point2D tileUL = mtcTransform.tileUVToLatLon(pnt, zoomLevel); - pnt.setLocation(x + 1, y + 1); - Point2D tileLR = mtcTransform.tileUVToLatLon(pnt, zoomLevel); - if (verbose) { - logger.fine("tile coords: " + tileUL + ", " + tileLR); - } - - double x1 = Math.min(tileUL.getX(), tileLR.getX()); - double x2 = Math.max(tileUL.getX(), tileLR.getX()); - double y1 = Math.min(tileUL.getY(), tileLR.getY()); - double y2 = Math.max(tileUL.getY(), tileLR.getY()); - - return new OMScalingRaster(y2, x1, y1, x2, image); - } - - /** - * Create an OMWarpingImage that knows how to re-project itself for different - * projections. The base projection is going to be defined for the mtc transform - * set on the factory. Warping images are slower to generate for a map - * projection than scaling rasters. - * - * @param image - * @param x - * @param y - * @param zoomLevel - * @return OMGraphic, but really an OMWarpingImage - */ - protected OMGraphic getTileNotMatchingProjectionType(BufferedImage image, int x, int y, int zoomLevel) { - - DataBounds dataBounds = new DataBounds(new Point(x, y), new Point(x + 1, y + 1)); - dataBounds.setyDirUp(mtcTransform.isYDirectionUp()); - - return new OMWarpingImage(image, mtcTransform.getTransform(zoomLevel), dataBounds); - } - - /** - * Method that allows subclasses to modify the image as necessary before it is - * passed into an OMGraphic. - * - * @param origImage Any java Image - * @param imageWidth pixel width - * @param imageHeight pixel height - * @return BufferedImage with any changes necessary. - * @throws InterruptedException - */ - protected BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - return getTileImagePreparer().preprocessImage(origImage, imageWidth, imageHeight); - } - - /** - * The main call to retrieve something from the cache, modified to allow load - * method to do some projection calculations to initialize tile parameters. If - * the object is not found in the cache, then load is called to get it from the - * data source. - * - * @param key cache key, usually string of location of a tile - * @param x uv x location of tile - * @param y uv y location of tile - * @param zoomLevel zoom level of tile - * @param proj passed solely to enable checking if the projection of the - * tiles matches the rendered projection. - * @return object from cache. - */ - public Object get(Object key, int x, int y, int zoomLevel, Projection proj) { - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - ret = load(key, x, y, zoomLevel, proj); - if (ret == null) { - return null; - } - - replaceLeastUsed(ret); - return ret.obj; - } - - /** - * An auxiliary call to retrieve something from the cache, modified to allow - * load method to do some projection calculations to initialize tile parameters. - * If the object is not found in the cache, null is returned. - * - * @param key cache key, usually string of location of a tile - * @param x uv x location of tile - * @param y uv y location of tile - * @param zoomLevel zoom level of tile - * @return cache object if found, null if not. - */ - public Object getFromCache(Object key, int x, int y, int zoomLevel) { - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - return null; - } - - /** - * Call to make when you want the tile factory to create some empty tile - * representation for the given location. You can return any type of OMGraphic - * embedded in a CacheObject. - * - * @param key the cache key for this object - * @param x the uv x coordinate of the tile - * @param y the uv y coordinate of the tile - * @param zoomLevel the zoom level for the tile - * @param proj the projection being used for the map. - * @return CacheObject, or null if the empty tile should be blank. - */ - public CacheObject getEmptyTile(Object key, int x, int y, int zoomLevel, Projection proj) { - - getTileImagePreparer().prepareForEmptyTile(this); - - EmptyTileHandler empTileHandler = getEmptyTileHandler(); - if (empTileHandler != null) { - - BufferedImage bi = empTileHandler.getImageForEmptyTile((String) key, x, y, zoomLevel, mtcTransform, proj); - - OMGraphic raster; - try { - raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - if (raster != null) { - - if (mapTileLogger.isLoggable(Level.FINE)) { - Object labelObj = raster.getAttribute(OMGraphic.LABEL); - if (labelObj instanceof OMTextLabeler) { - OMTextLabeler label = (OMTextLabeler) labelObj; - label.setData("EMPTY " + label.getData()); - } - } - - return new CacheObject(key, raster); - } - - } catch (InterruptedException e) { - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - } - } - return null; - } - - /** - * Returns projected tiles for the given projection. - * - * @param proj the projection to fetch tiles for. - * @return OMGraphicList containing projected OMGraphics. - */ - public OMGraphicList getTiles(Projection proj) { - return getTiles(proj, -1, new OMGraphicList()); - } - - /** - * Returns projected tiles for given projection at specified zoom level. - * - * @param proj projection for query - * @param zoomLevel zoom level 1-20 for tiles to be returned, -1 for code to - * figure out appropriate zoom level. - * @return OMGraphicList with tiles. - */ - public OMGraphicList getTiles(Projection proj, int zoomLevel) { - return getTiles(proj, zoomLevel, new OMGraphicList()); - } - - protected Projection lastProj; - - /** - * Returns projected tiles for given projection at specified zoom level. Use - * this call if you are providing a repaint callback component to the factory, - * so you will have a handle on the OMGraphicList to render to. - * - * @param proj projection for query - * @param zoomLevel zoom level 1-20 for tiles to be returned, -1 for code to - * figure out appropriate zoom level. - * @param list OMGraphicList that is returned, that will also have tiles - * added to it. - * @return OMGraphicList with tiles. - */ - public OMGraphicList getTiles(Projection proj, int zoomLevel, OMGraphicList list) { - String fExt = getFileExt(); - if (fExt == null || rootDir == null) { - logger.warning( - "No path to tile files provided (" + rootDir + "), or file extension (" + fExt + ") not specified"); - return list; - } - - if (lastProj == null || !proj.getClass().isAssignableFrom(lastProj.getClass())) { - logger.fine("Clearing out cache for new projection type"); - clear(); // empty the cache to rebuild OMGraphics for different type - // projection. - } - - lastProj = proj; - - /** - * Given a projection, a couple of things have to happen. - * - * - First, we need to figure out what zoom level fits us best if it is not - * specified. - * - * - Second, we need to figure out the uv bounds that fit the projection. - * - * - Third, we need to grab the images for uv grid, by cycling through the - * limits in both directions. - * - * The TileMaker static methods let us convert uv to lat/lon and back, a - * ZoomLevelInfo object can be used to figure out what the file path looks like. - */ - if (zoomLevel < 0) { - zoomLevel = mtcTransform.getZoomLevelForProj(proj, zoomLevelTileSize); - if (verbose) { - logger.fine("Best zoom level calculated at: " + zoomLevel); - } - } - - if (zoomLevel >= 0) { - - if (zoomLevel == 0) { - zoomLevel++; - } - - zoomLevelInfo.setZoomLevel(zoomLevel); - - Point2D upperLeft = proj.getUpperLeft(); - Point2D lowerRight = proj.getLowerRight(); - - int[] uvBounds = mtcTransform.getTileBoundsForProjection(upperLeft, lowerRight, zoomLevel); - int uvup = uvBounds[0]; - int uvleft = uvBounds[1]; - int uvbottom = uvBounds[2]; - int uvright = uvBounds[3]; - - if (verbose) { - logger.fine("for " + proj + ", fetching tiles between x(" + uvleft + ", " + uvright + ") y(" + uvup - + ", " + uvbottom + ")"); - } - - // dateline test - Point2D datelinePnt = proj.forward(new LatLonPoint.Double(upperLeft.getY(), 180d)); - double dlx = datelinePnt.getX(); - boolean dateline = dlx > 0 & dlx < proj.getWidth(); - logger.fine("Long(180) located at " + dlx); - - if (!dateline) { - getTiles(uvleft, uvright, uvup, uvbottom, zoomLevelInfo, proj, list); - } else { - logger.fine("handling DATELINE"); - getTiles(uvleft, (int) Math.pow(2, zoomLevel), uvup, uvbottom, zoomLevelInfo, proj, list); - getTiles(0, uvright, uvup, uvbottom, zoomLevelInfo, proj, list); - } - - } - return list; - } - - /** - * A temporary object used to store information about map tiles that are not - * found in the cache. The caching mechanism has been modified to search for - * cached tiles first, and using this object to hold information about map tiles - * that need to be loaded. The cached tiles will be immediately displayed, and - * then these tiles will be displayed after that as they are loaded. - * - * @author dietrick - */ - class LoadObj { - String imagePath; - int x; - int y; - int zoomLevel; - - LoadObj(String p, int x, int y, int z) { - this.imagePath = p; - this.x = x; - this.y = y; - this.zoomLevel = z; - } - } - - protected void getTiles(int uvleft, int uvright, int uvup, int uvbottom, ZoomLevelInfo zoomLevelInfo, - Projection proj, OMGraphicList list) { - if (verbose) { - logger.fine("for zoom level: " + zoomLevelInfo.getZoomLevel() + ", screen covers uv coords [t:" + uvup - + ", l:" + uvleft + ", b:" + uvbottom + ", r:" + uvright + "]"); - } - - if (zoomLevelInfo.getZoomLevel() == 0) { - logger.fine("got one tile, OM can't draw a single tile covering the earth. Sorry."); - } - - List reloads = new ArrayList(); - int zoomLevel = zoomLevelInfo.getZoomLevel(); - - int uvleftM = (int) Math.min(uvleft, uvright); - int uvrightM = (int) Math.max(uvleft, uvright); - int uvupM = (int) Math.min(uvbottom, uvup); - int uvbottomM = (int) Math.max(uvbottom, uvup); - - for (int x = uvleftM; x < uvrightM; x++) { - for (int y = uvupM; y < uvbottomM; y++) { - - if (mapTileRequester != null && !mapTileRequester.shouldContinue()) { - return; - } - - String imagePath = buildCacheKey(x, y, zoomLevel, getFileExt()); - - /** - * Need to modify the action of the cache a little to make the map appear more - * responsive. So, we cycle through the desired tiles, gathering all of the - * tiles that are immediately available. Generate them, add them to list, and - * call repaint when they are set. - * - * Keep track of the ones that are not there, and load those one-by-one after, - * calling repaint as they are added to the list. - */ - OMGraphic tileGraphic = (OMGraphic) getFromCache(imagePath, x, y, zoomLevel); - - if (tileGraphic != null) { - - if (mapTileLogger.isLoggable(Level.FINE)) { - tileGraphic.putAttribute(OMGraphic.LABEL, - new OMTextLabeler("Tile: " + zoomLevel + "|" + x + "|" + y, OMText.JUSTIFY_CENTER)); - tileGraphic.setSelected(true); - } - - tileGraphic.generate(proj); - list.add(tileGraphic); - } else { - reloads.add(new LoadObj(imagePath, x, y, zoomLevel)); - } - } - } - - if (verbose) { - logger.fine("found " + list.size() + " frames in cache, loading " + reloads.size() + " others now..."); - } - - if (mapTileRequester != null) { - mapTileRequester.listUpdated(); - } - - /* - * Load the tiles that are not already in the cache, that need to be fetched - * from the source. - */ - for (LoadObj reload : reloads) { - // Check and see of we should bother fetching the new tile. - if (mapTileRequester != null && !mapTileRequester.shouldContinue()) { - return; - } - - loadTile(reload.imagePath, reload.x, reload.y, reload.zoomLevel, proj, list); - - // OK, got it, notify requester the list has been updated. - if (mapTileRequester != null) { - mapTileRequester.listUpdated(); - } - } - - if (verbose) { - logger.fine("finished loading " + reloads.size() + " frames from source for screen" - + (doExtraTiles ? ", moving to off-screen frames..." : "")); - } - - if (!doExtraTiles) { - return; - } - - // Just for giggles, lets go ahead and walk around the edge of the area - // and prefetch tiles to load them into memory... - - // int uvleft, int uvright, int uvup, int uvbottom - int x1 = uvleft; - int y1 = uvup; - int x2 = uvright; - int y2 = uvbottom; - boolean top = false; - boolean left = false; - boolean right = false; - boolean bottom = false; - if (x1 > 0) { - x1--; - left = true; - } - if (y1 > 0) { - y1--; - top = true; - } - int edgeTileCount = zoomLevelInfo.getEdgeTileCount(); - if (x2 < edgeTileCount - 1) { - x2++; - right = true; - } - if (y2 < edgeTileCount - 1) { - y2++; - bottom = true; - } - - // Get the corners - if (top && left) { - loadTile(x1, y1, zoomLevel, proj, list); - } - if (bottom && left) { - loadTile(x1, y2, zoomLevel, proj, list); - } - if (bottom && right) { - loadTile(x2, y2, zoomLevel, proj, list); - } - if (top && right) { - loadTile(x2, y1, zoomLevel, proj, list); - } - // Now go along the sides - if (top) { - for (int x = uvleft; x < uvright; x++) { - loadTile(x, y1, zoomLevel, proj, list); - } - } - - if (bottom) { - for (int x = uvleft; x < uvright; x++) { - loadTile(x, y2, zoomLevel, proj, list); - } - } - - if (right) { - for (int y = uvup; y < uvbottom; y++) { - loadTile(x2, y, zoomLevel, proj, list); - } - } - - if (left) { - for (int y = uvup; y < uvbottom; y++) { - loadTile(x1, y, zoomLevel, proj, list); - } - } - - if (verbose) { - logger.fine("finished loading all tiles (" + list.size() + ")"); - } - } - - /** - * Handles going to the cache, getting the cache to load the tile, and then - * manage the resulting OMRaster tile. Adds the tile to the list after - * generating it with the projection, and calls the repaintCallback if there is - * one. - * - * @param imagePath the image path for the tile - * @param x the x uv coordinate of the tile - * @param y the y uv coordinate of the tile - * @param zoomLevel the zoomLevel of the tile - * @param proj the current projection. - * @param list the OMGraphicList to add the tile to. - * @throws InterruptedException - */ - private void loadTile(String imagePath, int x, int y, int zoomLevel, Projection proj, OMGraphicList list) { - - CacheObject ret = load(imagePath, x, y, zoomLevel, proj); - if (ret == null) { - - // Check if the factory wants to do anything for empty tiles. - ret = getEmptyTile(imagePath, x, y, zoomLevel, proj); - } - - if (ret != null) { - replaceLeastUsed(ret); - OMGraphic raster = (OMGraphic) ret.obj; - - if (raster != null) { - - raster.generate(proj); - list.add(raster); - - if (logger.isLoggable(Level.FINE)) { - raster.putAttribute(OMGraphic.TOOLTIP, imagePath); - } - } - } - } - - /** - * Handles going to the cache, getting the cache to load the tile, and then - * manage the resulting OMRaster tile. Adds the tile to the list after - * generating it with the projection, and calls the repaintCallback if there is - * one. Handles creating the image file path given the other info. - * - * @param x the x uv coordinate of the tile - * @param y the y uv coordinate of the tile - * @param zoomLevel the zoomLevel of the tile - * @param proj the current projection. - * @param list the OMGraphicList to add the tile to. - * @throws InterruptedException - */ - private void loadTile(int x, int y, int zoomLevel, Projection proj, OMGraphicList list) { - // String imagePath = zoomLevelInfo.formatImageFilePath(rootDir, x, y) + - // fileExt; - String imagePath = buildFilePath(x, y, zoomLevel, getFileExt()); - loadTile(imagePath, x, y, zoomLevel, proj, list); - } - - /** - * Build an image path to load, based on specified tile coordinates, zoom level - * and file extension settings. - * - * Look at the root directory definition and determine if the x,y,z values of - * the path are specified as the holder values {z}, {x} and {y}. - * - * If they aren't specified, the provided values will be appended to the rootDir - * as z/x/y.fileExt. - * - * If {z}, {x} or {y} are found in the root dir path, then it's assumed that the - * rootDir contains all the information needed to specify the path and regular - * expressions will be used to replace those value holders with the values - * specified. The file extension in this case will not be appended to the - * rootDir. - * - * @param x the x tile coordinate - * @param y the y tile coordinate - * @param z the zoom level - * @param fileExt the file extension to use for the path. - */ - public String buildFilePath(int x, int y, int z, String fileExt) { - TilePathBuilder pathBuilder = getTilePathBuilder(); - if (pathBuilder == null) { - pathBuilder = new TilePathBuilder(rootDir); - setTilePathBuilder(pathBuilder); - } - - return pathBuilder.buildTilePath(x, y, z, fileExt); - } - - private TilePathBuilder tilePathBuilder = null; - - protected void setTilePathBuilder(TilePathBuilder tpb) { - tilePathBuilder = tpb; - } - - protected TilePathBuilder getTilePathBuilder() { - return tilePathBuilder; - } - - /** - * Creates a unique cache key for this tile based on zoom, x, y. This method was - * created so the ServerMapTileFactory could override it and use local cache - * names for keys if a local cache was being used. - * - * @param x tile coord. - * @param y tile coord. - * @param z zoomLevel. - * @param fileExt file extension. - * @return String used in cache. - */ - protected String buildCacheKey(int x, int y, int z, String fileExt) { - return buildFilePath(x, y, z, fileExt); - } - - public static class TilePathBuilder { - String rez = "(\\{z\\})"; // Curly Braces 1 - String rex = "(\\{x\\})"; // Curly Braces 2 - String rey = "(\\{y\\})"; // Curly Braces 3 - - Pattern pz = Pattern.compile(rez, Pattern.CASE_INSENSITIVE); - Pattern px = Pattern.compile(rex, Pattern.CASE_INSENSITIVE); - Pattern py = Pattern.compile(rey, Pattern.CASE_INSENSITIVE); - - String startingPath; - boolean patternsUsed = false; - boolean patternUseChecked = false; - - public TilePathBuilder(String rootDir) { - startingPath = rootDir; - } - - public boolean isPatternsUsed() { - return patternsUsed; - } - - public String buildTilePath(int x, int y, int z, String fileExt) { - String ret = startingPath; - if (((!patternUseChecked) || (patternUseChecked && patternsUsed)) && startingPath != null - && startingPath.length() != 0) { - ret = updatePath(ret, pz, Integer.toString(z)); - ret = updatePath(ret, px, Integer.toString(x)); - ret = updatePath(ret, py, Integer.toString(y)); - patternUseChecked = true; - } - - if (!patternsUsed) { - // No pattern matching, need to build from scratch, with fileExt - return buildDefaultTilePath(x, y, z, fileExt); - } - - return ret; - } - - private String buildDefaultTilePath(int x, int y, int z, String fileExt) { - return startingPath + "/" + z + "/" + x + "/" + y + fileExt; - } - - private String updatePath(String currentPath, Pattern p, String replaceWith) { - Matcher m = p.matcher(currentPath); - if (m.find()) { - patternsUsed = true; - return m.replaceAll(replaceWith); - } - return currentPath; - } - } - - public MapTileRequester getMapTileRequester() { - return mapTileRequester; - } - - public void setMapTileRequester(MapTileRequester mtRequestor) { - this.mapTileRequester = mtRequestor; - } - - public Properties getProperties(Properties getList) { - String prefix = PropUtils.getScopedPropertyPrefix(this); - getList.put(prefix + ROOT_DIR_PROPERTY, PropUtils.unnull(rootDirProperty)); - getList.put(prefix + FILE_EXT_PROPERTY, PropUtils.unnull(getFileExt())); - getList.put(prefix + CACHE_SIZE_PROPERTY, Integer.toString(getCacheSize())); - getList.put(prefix + MTCTRANSFORM_PROPERTY, mtcTransform.getClass().toString()); - if (emptyTileHandler != null) { - getList.put(prefix + EMPTY_TILE_HANDLER_PROPERTY, emptyTileHandler.getClass().toString()); - if (emptyTileHandler instanceof PropertyConsumer) { - ((PropertyConsumer) emptyTileHandler).getProperties(getList); - } - } - - // Only save the zoomLevelInfo property if it's not the default. - if (zoomLevelInfo != null && !zoomLevelInfo.getClass().equals(ZoomLevelInfo.class)) { - getList.put(prefix + ZOOM_LEVEL_INFO_PROPERTY, zoomLevelInfo.getClass().getName()); - } - - getList.put(prefix + ZOOM_LEVEL_TILE_SIZE_PROPERTY, Integer.toString(zoomLevelTileSize)); - TileImagePreparer tip = getTileImagePreparer(); - if (!(tip instanceof StandardImagePreparer)) { - getList.put(prefix + TILE_IMAGE_PREPARER_PROPERTY, tip.getClass().getName()); - if (tip instanceof PropertyConsumer) { - ((PropertyConsumer) tip).getProperties(getList); - } - } - - return getList; - } - - public Properties getPropertyInfo(Properties list) { - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - ROOT_DIR_PROPERTY, "Tile URL or Path", - "Root directory containing image tiles, or URL (http://tileserver/{z}/{x}/{y}.png)", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - FILE_EXT_PROPERTY, "Image File Extension", "Extension of image files (.jpg, .png, etc)", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - CACHE_SIZE_PROPERTY, "Cache Size", "Number of tile images held in memory", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - ZOOM_LEVEL_TILE_SIZE_PROPERTY, "Zoom Level Tile Size", - "The maximum pixel size of a tile before switching to a higher zoom level (350 is default)", null); - return list; - } - - public String getInitPropertiesOrder() { - return ROOT_DIR_PROPERTY + " " + FILE_EXT_PROPERTY; - } - - public String getPropertyPrefix() { - return prefix; - } - - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String rootDirectory = setList.getProperty(prefix + ROOT_DIR_PROPERTY); - if (rootDirectory != null) { - setRootDir(rootDirectory); - } - - String tmpFileExt = setList.getProperty(prefix + FILE_EXT_PROPERTY, getFileExt()); - - // Add a period if it doesn't exist. - if (tmpFileExt != null) { - setFileExt(tmpFileExt); - } - - String mapTileCoordinateTransform = setList.getProperty(prefix + MTCTRANSFORM_PROPERTY); - if (mapTileCoordinateTransform != null) { - Object obj = ComponentFactory.create(mapTileCoordinateTransform); - - if (obj instanceof MapTileCoordinateTransform) { - setMtcTransform((MapTileCoordinateTransform) obj); - } - } - - String emptyTileHandlerString = setList.getProperty(prefix + EMPTY_TILE_HANDLER_PROPERTY); - if (emptyTileHandlerString != null) { - Object obj = ComponentFactory.create(emptyTileHandlerString, prefix, setList); - - if (obj instanceof EmptyTileHandler) { - setEmptyTileHandler((EmptyTileHandler) obj); - } - } - - String zoomLevelInfoString = setList.getProperty(prefix + ZOOM_LEVEL_INFO_PROPERTY); - if (zoomLevelInfoString != null) { - Object obj = ComponentFactory.create(zoomLevelInfoString, prefix, setList); - - if (obj instanceof ZoomLevelInfo) { - setZoomLevelInfo((ZoomLevelInfo) obj); - } - } - - String tileImagePreparerString = setList.getProperty(prefix + TILE_IMAGE_PREPARER_PROPERTY); - if (tileImagePreparerString != null) { - Object obj = ComponentFactory.create(tileImagePreparerString, prefix, setList); - if (obj instanceof TileImagePreparer) { - setTileImagePreparer((TileImagePreparer) obj); - } - } - - super.resetCache(PropUtils.intFromProperties(setList, prefix + CACHE_SIZE_PROPERTY, getCacheSize())); - - zoomLevelTileSize = PropUtils.intFromProperties(setList, prefix + ZOOM_LEVEL_TILE_SIZE_PROPERTY, - zoomLevelTileSize); - } - - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - public String getRootDir() { - return rootDir; - } - - public void setRootDir(String rootDirectory) { - - if (rootDirectory != null) { - if (rootDirectory.endsWith("jar")) { - - rootDirProperty = rootDirectory; - String jarFileNames = rootDirectory; - // Only use the tiles.omp file in the first file found. - boolean tilesFileFound = false; - - List jarNames = PropUtils.parseMarkers(jarFileNames, ";"); - for (String jarName : jarNames) { - - boolean jarFileFound = false; - - try { - - if (!tilesFileFound) { - URL jarURL = PropUtils.getResourceOrFileOrURL(jarName); - - if (jarURL != null) { - jarFileFound = true; - JarInputStream jarStream = new JarInputStream(jarURL.openStream()); - JarEntry jarEntry = null; - - while ((jarEntry = jarStream.getNextJarEntry()) != null) { - String entryName = jarEntry.getName(); - if (entryName.equals(TILE_PROPERTIES)) { - byte[] readBytes = new byte[100]; - byte[] contentBytes = new byte[0]; - - int numRead = 0; - while ((numRead = jarStream.read(readBytes, 0, readBytes.length)) > 0) { - byte[] tmpBytes = new byte[numRead + contentBytes.length]; - System.arraycopy(contentBytes, 0, tmpBytes, 0, contentBytes.length); - System.arraycopy(readBytes, 0, tmpBytes, contentBytes.length, numRead); - - contentBytes = tmpBytes; - } - - ByteArrayInputStream bais = new ByteArrayInputStream(contentBytes); - configureFromProperties(bais, rootDirectory); - bais.close(); - - jarStream.closeEntry(); - tilesFileFound = true; - break; - } - } - - jarStream.close(); - } - } - - if (jarFileFound) { - logger.fine("adding " + jarName + " to classpath"); - ClasspathHacker.addFile(jarName); - } else { - logger.fine("can't find " + jarName + ", not adding to classpath"); - } - - // JarFile jarFile = new JarFile(jarName); - // JarEntry jarPropertyFile = (JarEntry) - // jarFile.getEntry(TILE_PROPERTIES); - // - // if (jarPropertyFile != null) { - // InputStream is = - // jarFile.getInputStream(jarPropertyFile); - // configureFromProperties(is, rootDirectory); - // } - - } catch (IOException ioe) { - logger.warning("couldn't add map data jar file: " + jarName); - } - - } - - // You might notice that we didn't set the rootDir here if a jar - // file is being used. That's because we just want to use - // whatever - // the tile file says, and this method will be called again if - // needed when the properties get written. - - } else { - // check for tile.omp file that may describe how to read tiles. - File tileProps = new File(rootDirectory, TILE_PROPERTIES); - - // Keep track of what the root directory was before we read - // tiles.omp - String currentRootDirectory = this.rootDir; - String currentRootDirProperty = rootDirProperty; - if (tileProps.exists()) { - try { - // Do this in case other properties are set for the tile - // set, file ext, transform. - configureFromProperties(tileProps.toURI().toURL().openStream(), rootDirectory); - } catch (MalformedURLException murle) { - logger.warning( - "tile file for " + rootDirectory + " couldn't be read: " + tileProps.getAbsolutePath()); - } catch (IOException ioe) { - logger.warning("tile file for " + rootDirectory + " couldn't be read"); - } - } - - /* - * OK, things look a little crazy here, because there is a bit of recursion - * going on. The configure call above may cause a setRootDir call with a - * relative path stored in a jar file. These rules below make sure the relative - * root dir from the inner loop sets the rootDir, while preserving the - * rootDirProperty from the outer loop. - */ - - if (currentRootDirectory == null && this.rootDir == null) { - // the tiles.omp file didn't change the root directory, so - // lets go with the directory given. - this.rootDir = rootDirectory; - } - - if (currentRootDirProperty == null) { - // Assuming a file path being set, not as a result of a jar - // file - rootDirProperty = rootDirectory; - } - } - - } else { - // nulled out - this.rootDir = rootDirectory; - rootDirProperty = rootDirectory; - } - - // Reset for new path - tilePathBuilder = null; - - } - - public TileImagePreparer getTileImagePreparer() { - if (tileImagePreparer == null) { - tileImagePreparer = new StandardImagePreparer(); - } - return tileImagePreparer; - } - - public void setTileImagePreparer(TileImagePreparer tileImagePreparer) { - this.tileImagePreparer = tileImagePreparer; - } - - /** - * Called with an input stream for a properties file, used for reading tiles.omp - * files. - * - * @param is input stream for tiles.omp file. - * @param rootDirectory original path to what was specified as root directory - * @throws IOException - */ - protected void configureFromProperties(InputStream is, String rootDirectory) throws IOException { - - Properties props = new Properties(); - props.load(is); - - props.put(ROOT_DIR_PATH_PROPERTY, rootDirectory); - - String oldPrefix = getPropertyPrefix(); - setProperties(null, props); - setPropertyPrefix(oldPrefix); - } - - public String getFileExt() { - return fileExt; - } - - public void setFileExt(String fileExt) { - this.fileExt = (fileExt != null && fileExt.startsWith(".")) ? fileExt : "." + fileExt; - } - - /** - * Get the ZoomLevelInfo set on the factory. The ZoomLevelInfo has basic layout - * information about tiles for a particular zoom level, including how tiles are - * named and how the factory should go about loading them. The default - * ZoomLevelInfo is based on the OpenStreetMap tile layout, zoom levels 0-20 - * (where level 0 is all the way zoomed out), and the tiles are stored - * zoomLevel/x/y.(fileExt). - * - * @return the zoomLevelInfo - */ - public ZoomLevelInfo getZoomLevelInfo() { - return zoomLevelInfo; - } - - /** - * Get the ZoomLevelInfo set on the factory. The ZoomLevelInfo has basic layout - * information about tiles for a particular zoom level, including how tiles are - * named and how the factory should go about loading them. The default - * ZoomLevelInfo is based on the OpenStreetMap tile layout, zoom levels 0-20 - * (where level 0 is all the way zoomed out), and the tiles are stored - * zoomLevel/x/y.(fileExt). You can set a different zoom level info if you want - * to work with a tile set that is stored/defined differently than OSM. - *

- * Won't allow itself to be set to null. - * - * @param zoomLevelInfo the zoomLevelInfo to set - */ - public void setZoomLevelInfo(ZoomLevelInfo zoomLevelInfo) { - if (zoomLevelInfo != null) { - this.zoomLevelInfo = zoomLevelInfo; - } - } - - public MapTileCoordinateTransform getMtcTransform() { - return mtcTransform; - } - - /** - * Set the map tile coordinate transformed used to figure out lat/lon to tile - * coordinates. Can't be null, if you set it to null an OSMMapTileCoordTransform - * will be created instead. - * - * @param mtcTransform - */ - public void setMtcTransform(MapTileCoordinateTransform mtcTransform) { - if (mtcTransform == null) { - mtcTransform = new OSMMapTileCoordinateTransform(); - } - this.mtcTransform = mtcTransform; - } - - /** - * @return the emptyTileHandler - */ - public EmptyTileHandler getEmptyTileHandler() { - return emptyTileHandler; - } - - /** - * @param emptyTileHandler the emptyTileHandler to set - */ - public void setEmptyTileHandler(EmptyTileHandler emptyTileHandler) { - this.emptyTileHandler = emptyTileHandler; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TMSMapTileCoordinateTransform.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TMSMapTileCoordinateTransform.java deleted file mode 100644 index 3c27b4f1a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TMSMapTileCoordinateTransform.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.MercatorUVGCT; - -/** - * The implementation of TileCoordinateTransformation for Tile Map Service (TMS) - * tile coordinate notations. - * - * @author dietrick - */ -public class TMSMapTileCoordinateTransform extends AbstractMapTileCoordinateTransform { - - /** - * @param latlon a Point2D whose x component is the longitude and y - * component is the latitude - * @param zoom Tile Map Service (TMS) style zoom level (0-19 usually) - * @param ret LatLonPoint to fill and return, to avoid allocating return - * object. - * @return The "tile number" whose x and y components each are floating - * point numbers that represent the distance in number of tiles from - * the origin of the whole map at this zoom level. At zoom=0, the - * lat,lon point of 0,0 maps to 0.5,0.5 since there is only one tile - * at zoom level 0. - */ - public Point2D latLonToTileUV(Point2D latlon, int zoom, Point2D ret) { - if (ret == null) { - ret = new Point2D.Double(); - } - - ret.setLocation(((latlon.getX() + 180.0) / 360.0 * Math.pow(2.0, zoom)), Math.pow(2.0, zoom) - - ((1.0 - Math.log(Math.tan(latlon.getY() * Math.PI / 180.0) - + (1.0 / Math.cos(latlon.getY() * Math.PI / 180.0))) - / Math.PI) / 2.0 * (Math.pow(2.0, zoom)))); - - return ret; - // Much slower! - // transform.setZoomLevel(zoom); - // return transform.forward(latlon.getY(), latlon.getX(), ret); - } - - /** - * @param tileUV a Point2D whose x,y coordinates represent the distance in - * number of tiles (each 256x256) from the origin (where the origin - * is -90lat,-180lon) - * @param zoom Tile Map Service (TMS) style zoom level (0-19 usually) - * @param ret LatLonPoint to fill and return, to avoid allocating return - * object. - * @return a Point2D whose x coordinate is the longitude and y coordinate is - * the latitude - */ - public LatLonPoint tileUVToLatLon(Point2D tileUV, int zoom, LatLonPoint ret) { - if (ret == null) { - ret = new LatLonPoint.Double(); - } - - ret.setLocation(360.0 / Math.pow(2.0, zoom) * tileUV.getX() - 180.0, -90.0 - + 360.0 - / Math.PI - * Math.atan(Math.exp((-2.0 * Math.PI * (-(tileUV.getY() - Math.pow(2.0, zoom)))) - / Math.pow(2.0, zoom) + Math.PI))); - - return ret; - - // Much slower! - // transform.setZoomLevel(zoom); - // return transform.inverse(tileUV.getX(), tileUV.getY(), ret); - } - - /** - * Given a projection, provide the upper, lower, left and right tile - * coordinates that cover the projection area. - * - * @param upperLeft lat/lon coordinate of upper left corner of bounding box. - * @param lowerRight lat/lon coordinate of lower right corner of bounding - * box. - * @param zoomLevel zoom level of desired tiles. - * @return int[], in top, left, bottom and right order. - */ - public int[] getTileBoundsForProjection(Point2D upperLeft, Point2D lowerRight, int zoomLevel) { - - Point2D uvul = latLonToTileUV(upperLeft, zoomLevel); - Point2D uvlr = latLonToTileUV(lowerRight, zoomLevel); - - int[] ret = new int[4]; - - int uvleft = (int) Math.floor(uvul.getX()); - int uvright = (int) Math.ceil(uvlr.getX()); - int uvbottom = (int) Math.floor(uvlr.getY()) - 1; - if (uvbottom < 0) { - uvbottom = 0; - } - int uvup = (int) Math.ceil(uvul.getY()) + 1; - - ret[0] = uvup; - ret[1] = uvleft; - ret[2] = uvbottom; - ret[3] = uvright; - - return ret; - } - - public static void main(String[] args) { - for (int i = 9; i < 15; i++) { - System.out.println("Zoom Level " + i); - TMSMapTileCoordinateTransform tms = new TMSMapTileCoordinateTransform(); - - LatLonPoint llp = new LatLonPoint.Double(0.0, 0.0); - Point2D uv = tms.latLonToTileUV(llp, i); - System.out.println(" " + llp + " transformed to " + uv); - llp = tms.tileUVToLatLon(uv, i, llp); - System.out.println(" " + uv + " transformed to " + llp); - - llp = new LatLonPoint.Double(41.389, 2.169); - uv = tms.latLonToTileUV(llp, i); - System.out.println(" " + llp + " transformed to " + uv); - llp = tms.tileUVToLatLon(uv, i, llp); - System.out.println(" " + uv + " transformed to " + llp); - } - - } - - /** - * @return if y coordinates for tiles increase as pixel values increase. - */ - public boolean isYDirectionUp() { - return true; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform#getTransform - * () - */ - public GeoCoordTransformation getTransform(int zoomLevel) { - return new MercatorUVGCT.TMS(zoomLevel); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileGrabber.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileGrabber.java deleted file mode 100644 index ed4f12b0f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileGrabber.java +++ /dev/null @@ -1,488 +0,0 @@ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform; -import com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform; -import com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.TilePathBuilder; -import com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform; -import com.bbn.openmap.dataAccess.mapTile.ZoomLevelInfo; -import com.bbn.openmap.dataAccess.shape.EsriGraphic; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * Utility class that fetches tiles from a http source. Runs as an application. - * Prints out a usage statement that describes options. - * - * @author dietrick - */ -public class TileGrabber { - - public TileGrabber() { - - } - - /** - * @author ddietrick - */ - public static class Builder { - protected String source; - protected String target = ""; - - protected int fromZoom = 0; - protected int toZoom = 0; - - protected int minx = 0; - protected int miny = 0; - protected int maxx = -1; - protected int maxy = -1; - - protected double minlon = -180.0; - protected double minlat = -85.0; - protected double maxlon = 180.0; - protected double maxlat = 85.0; - - protected boolean fill = false; - protected boolean verbose = false; - protected boolean extraVerbose = false; - protected boolean tileBoundsSet = false; - - MapTileCoordinateTransform transform = new OSMMapTileCoordinateTransform(); - - public Builder(String source) throws FileNotFoundException { - - if (source == null) { - throw new FileNotFoundException("Source file invalid"); - } - - this.source = source; - } - - public Builder targetFile(String targetFile) { - this.target = targetFile; - - return this; - } - - public Builder fromZoom(int zoomLevel) throws NumberFormatException { - if (checkZoomLevel(zoomLevel)) { - this.fromZoom = zoomLevel; - } - - if (this.fromZoom > this.toZoom) { - this.toZoom = this.fromZoom; - } - - return this; - } - - public Builder toZoom(int zoomLevel) throws NumberFormatException { - if (checkZoomLevel(zoomLevel)) { - this.toZoom = zoomLevel; - - if (this.fromZoom > this.toZoom) { - this.fromZoom = this.toZoom; - } - } - return this; - } - - protected boolean checkZoomLevel(int zoomLevel) { - if (zoomLevel < 0 || zoomLevel > 20) { - throw new NumberFormatException("Zoom level needs to be > 0 and < 20"); - } - return true; - } - - public String toString() { - StringBuilder sb = new StringBuilder("WholeWorldTileHandler["); - sb.append("source:").append(source).append(','); - sb.append("target:").append(target).append(','); - sb.append("fromZoom:").append(fromZoom).append(','); - sb.append("toZoom:").append(toZoom).append(','); - if (minx != 0) { - sb.append(",").append("minx:").append(minx); - } - if (miny != 0) { - sb.append(",").append("miny:").append(miny); - } - if (maxx >= 0) { - sb.append(",").append("maxx:").append(maxx); - } - if (maxy >= 0) { - sb.append(",").append("maxy:").append(maxy); - } - - sb.append(']'); - - return sb.toString(); - } - - protected int[] getTileBoundsForProjection(LatLonPoint ul, LatLonPoint lr, int z) { - if (fromZoom == toZoom && tileBoundsSet) { - ZoomLevelInfo zoomInfo = new ZoomLevelInfo(); - zoomInfo.setZoomLevel(z); - int maxDim = zoomInfo.getEdgeTileCount(); - - if (maxx == -1) { - maxx = maxDim; - } - - if (maxy == -1) { - maxy = maxDim; - } - - return new int[] { miny, minx, maxy, maxx }; - } - - return transform.getTileBoundsForProjection(ul, lr, z); - } - - /** - * source: - * "http://192.168.99.100:32771/mapbox-studio-osm-bright/{z}/{x}/{y}.png" - * target: "/Users/dietrick/Downloads/st_osm_tiles" - * - * @throws FileNotFoundException - * @throws IOException - */ - - public void go() throws FileNotFoundException, IOException { - - LatLonPoint ul = new LatLonPoint.Double(maxlat, minlon); - LatLonPoint lr = new LatLonPoint.Double(minlat, maxlon); - - ServerMapTileFactory tileServer = new ServerMapTileFactory(); - TilePathBuilder serverPathBuilder = new TilePathBuilder(source); - TilePathBuilder localPathBuilder = new TilePathBuilder(target); - tileServer.localCacheDir = target; - - ZoomLevelInfo zoomInfo = new ZoomLevelInfo(); - - for (int z = fromZoom; z <= toZoom; z++) { - - int[] uv = getTileBoundsForProjection(ul, lr, z); - - int startX = uv[1]; - int endX = uv[3]; - int startY = uv[0]; - int endY = uv[2]; - - if (verbose) { - System.out.println("fetching tiles for zoom level " + z + " between " + startY + ", " + startX - + " and " + endY + ", " + endX); - } - - zoomInfo.setZoomLevel(z); - int maxDim = zoomInfo.getEdgeTileCount(); - for (int x = startX; x <= endX && x <= maxDim - 1; x++) { - for (int y = startY; y <= endY && y <= maxDim - 1; y++) { - - String serverImagePath = serverPathBuilder.buildTilePath(x, y, z, ".png"); - String localFilePath = localPathBuilder.buildTilePath(x, y, z, ".png"); - - if (fill) { - File localFile = new File(localFilePath); - if (localFile.exists()) { - if (extraVerbose) { - System.out.println("--- skipping " + localFilePath + ", aready got it"); - } - continue; - } - } - - if (extraVerbose) { - System.out.println("<<< fetching " + serverImagePath); - } - tileServer.getImageBytes(serverImagePath, localFilePath); - } - } - } - } - - public void go(String shapefile) throws FileNotFoundException, IOException { - try { - if (verbose) { - System.out.println("fetching tiles covering " + shapefile); - } - URL shp = PropUtils.getResourceOrFileOrURL(shapefile); - EsriGraphicList egl = EsriGraphicList.getEsriGraphicList(shp, null, null); - - fetchTilesForEsriGraphicList(egl); - - } catch (MalformedURLException murle) { - throw new FileNotFoundException(murle.getMessage()); - } - } - - protected void fetchTilesForEsriGraphicList(EsriGraphicList egl) throws FileNotFoundException, IOException { - for (OMGraphic omg : egl) { - if (omg instanceof EsriGraphicList) { - fetchTilesForEsriGraphicList((EsriGraphicList) omg); - } else if (omg instanceof EsriGraphic) { - fetchTilesForEsriGraphic((EsriGraphic) omg); - } - } - } - - protected void fetchTilesForEsriGraphic(EsriGraphic eg) throws FileNotFoundException, IOException { - // miny, minx, maxy maxx - double[] coords = eg.getExtents(); - minlat = coords[0]; - minlon = coords[1]; - maxlat = coords[2]; - maxlon = coords[3]; - - go(); - } - - /** - * Set the starting x number of the subjar file to create. Depends on the subjar - * zoom to figure out what that means. - * - * @param parseInt - */ - public void minx(int parseInt) { - minx = parseInt; - tileBoundsSet = true; - } - - /** - * Set the starting y number of the subjar file to create. Depends on the subjar - * zoom to figure out what that means. - * - * @param parseInt - */ - public void miny(int parseInt) { - miny = parseInt; - tileBoundsSet = true; - } - - /** - * Set the ending y number of the subjar file to create. Depends on the subjar - * zoom to figure out what that means. - * - * @param parseInt - */ - public void maxx(int parseInt) { - maxx = parseInt; - tileBoundsSet = true; - } - - /** - * Set the ending y number of the subjar file to create. Depends on the subjar - * zoom to figure out what that means. - * - * @param parseInt - */ - public void maxy(int parseInt) { - maxy = parseInt; - tileBoundsSet = true; - } - - /** - * set lower longitude of fetching - * - * @param parsed - */ - public void minlon(double parsed) { - minlon = parsed; - } - - /** - * set lower latitude of fetching - * - * @param parsed - */ - public void minlat(double parsed) { - minlat = parsed; - } - - /** - * set upper longitude of fetching - * - * @param parsed - */ - public void maxlon(double parsed) { - maxlon = parsed; - } - - /** - * set upper latitude of fetching - * - * @param parsed - */ - public void maxlat(double parsed) { - maxlat = parsed; - } - - /** - * Check whether the build process will only fetch tiles that don't exist. - */ - public boolean isFill() { - return fill; - } - - /** - * Set whether the build process will only fetch tiles that don't exist. - * - * @param fill - */ - public void setFill(boolean fill) { - this.fill = fill; - } - } - - /** - * Takes arguments for source tile directory, target directory, and option - * sub-jar zoom level, and creates jars in the right place with expected tiles. - * Prints usage statement. - * - * @param args - */ - public static void main(String[] args) { - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("TileGrabber"); - - ap.add("source", "Path to fetch tiles from, should be http://path/{z}/{x}/{y}.png form", 1); - ap.add("target", "Path to the output directory for fetched tiles", 1); - ap.add("fromZoom", "Starting zoom level", 1); - ap.add("toZoom", "Ending zoom level", 1); - ap.add("minx", "min x tile (only used if fromZoom and toZoom match)", 1); - ap.add("miny", "min y tile (only used if fromZoom and toZoom match)", 1); - ap.add("maxx", "max x tile (only used if fromZoom and toZoom match)", 1); - ap.add("maxy", "max y tile (only used if fromZoom and toZoom match)", 1); - - ap.add("minlon", "min longitude", 1, true); - ap.add("minlat", "min latitude", 1, true); - ap.add("maxlon", "max longitude", 1, true); - ap.add("maxlat", "max latitude", 1, true); - - ap.add("shapefile", "fetch coverage over shapes in shapefile", 1); - - ap.add("verbose", "Describe what's going on."); - ap.add("extraVerbose", "Really describe what's going on."); - ap.add("fill", "Only fetch tiles that don't exist."); - ap.add("TMS", "Specify that the tile numbering scheme matches TMS (OSM is default)"); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String[] arg = ap.getArgValues("source"); - if (arg != null) { - try { - Builder wwthBuilder = new Builder(arg[0]); - - arg = ap.getArgValues("target"); - if (arg != null) { - wwthBuilder.targetFile(arg[0]); - } - - arg = ap.getArgValues("fromZoom"); - if (arg != null) { - wwthBuilder.fromZoom(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("toZoom"); - if (arg != null) { - wwthBuilder.toZoom(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("minx"); - if (arg != null) { - wwthBuilder.minx(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("miny"); - if (arg != null) { - wwthBuilder.miny(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("maxx"); - if (arg != null) { - wwthBuilder.maxx(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("maxy"); - if (arg != null) { - wwthBuilder.maxy(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues("minlon"); - if (arg != null) { - wwthBuilder.minlon(Double.parseDouble(arg[0])); - } - - arg = ap.getArgValues("minlat"); - if (arg != null) { - wwthBuilder.minlat(Double.parseDouble(arg[0])); - } - - arg = ap.getArgValues("maxlon"); - if (arg != null) { - wwthBuilder.maxlon(Double.parseDouble(arg[0])); - } - - arg = ap.getArgValues("maxlat"); - if (arg != null) { - wwthBuilder.maxlat(Double.parseDouble(arg[0])); - } - arg = ap.getArgValues("verbose"); - if (arg != null) { - wwthBuilder.verbose = true; - } - arg = ap.getArgValues("extraVerbose"); - if (arg != null) { - wwthBuilder.verbose = true; - wwthBuilder.extraVerbose = true; - } - - arg = ap.getArgValues("fill"); - if (arg != null) { - wwthBuilder.setFill(true); - } - - arg = ap.getArgValues("TMS"); - if (arg != null) { - wwthBuilder.transform = new TMSMapTileCoordinateTransform(); - } - - arg = ap.getArgValues("shapefile"); - if (arg != null) { - - wwthBuilder.go(arg[0]); - - } else { - - System.out.println(wwthBuilder.toString()); - wwthBuilder.go(); - } - - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - System.out.println(nfe.getMessage()); - } catch (FileNotFoundException fnfe) { - fnfe.printStackTrace(); - System.out.println(fnfe.getMessage()); - } catch (IOException ioe) { - ioe.printStackTrace(); - System.out.println(ioe.getMessage()); - } - } else { - ap.bail("Need a source directory.", true); - } - - System.exit(0); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java deleted file mode 100644 index b0c51db4c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * TileImagePreparer.java Jan 10, 2012 9:37:01 PM - */ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.image.BufferedImage; - -/** - * TODO: Describe the TileImagePreparer interface class here. - * - * @author dietrick - */ -public interface TileImagePreparer { - - /** - * Sometimes, based on the color handling of the preparer, empty tiles need to be handled differently. - * - * @param factory used to make calls on the factory to prepare for empty tile fetch. - */ - void prepareForEmptyTile(MapTileFactory factory); - - /** - * Method called to manipulate provided image in some way, returning modified image. - * - * @param origImage Any java Image - * @param imageWidth pixel width - * @param imageHeight pixel height - * @return BufferedImage with any changes necessary. - * @throws InterruptedException - */ - BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException; -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/WholeWorldTileHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/WholeWorldTileHandler.java deleted file mode 100644 index 945834cea..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/WholeWorldTileHandler.java +++ /dev/null @@ -1,921 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.logging.Level; -import java.util.zip.Adler32; -import java.util.zip.CheckedOutputStream; -import java.util.zip.ZipOutputStream; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ClasspathHacker; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; - -/** - * The WholeWorldTileHandler is a special EmptyTileHandler that manages a - * special set of jar files containing tiles that cover the entire earth. If you - * put all of the tiles from zoom levels 0-12 into a jar file, you end up with a - * 5Gb jar, and java doesn't handle it. Having zoom levels 0-14 on disk takes up - * 30Gb without being compressed. - *

- * - * This class, run as an application, organizes tiles into several jar files, - * depending on their zoom level and location. All tiles for the world in zoom - * levels 0-10 are placed in a single jar file. For all other zoom levels, they - * are placed together geographically, based on the tile boundaries of some - * higher level (zoom level 3 is the default, higher numbers might be chosen if - * tiles are created for higher zoom levels than 15). - *

- * - * This class is consulted when the MapTileFactory can't find a map tile. Since - * this class is an EmptyTileHandler, it is given free reign to return a tile - * for the missing one. Instead of assuming that the tiles don't exist and a - * quick replacement needs to be created, this EmtpyTileHandler assumes that the - * proper jar file hasn't been loaded yet, which is why the tile wasn't found as - * a resource. It uses the ux, uv, and zoom level for the tile to figure out - * what jar it would have been in, and checks to see if that jar has been added - * to the classpath. If the jar has been added, then the tile doesn't exist. If - * the jar needs to be added, it is and then the tile retrieval starts. - *

- * - * The properties for the tile set are a little different when using this - * EmptyTileHandler: - * - *

- * # specify this empty tile handler
- * emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.WholeWorldTileHandler
- * # instead of the root directory to the jars, specify the root directory of the tiles 
- * # inside the jars.  All of the jars within a set should share the root directory name 
- * # within them.  Each set of jars should have a unique root directory name for that dataset.
- * rootDir=main_tiles
- * # The name of the jar containing world-level coverage.  All of the sub-jars should be 
- * # named based on this jar name.  If this class is run to build the tile jars, 
- * # it should have done this automatically.
- * parentJarName=main_tiles.jar
- * # This is the grid that defines how the subjars are divided.  It matches the tile boundaries 
- * # of a certain zoom level. Level 3 is the default.
- * subJarZoomLevel=9
- * # This is the highest level of tiles held in the part jar name.  Tells the layer when it should
- * # start looking in subjars for tiles at higher zoom levels.
- * worldWideZoomLevel=10
- * # Tells the layer when to stop trying to fill tile orders.
- * noCoverageZoom=15
- * # optional, png is default.
- * fileExt=.png
- * # You can also specify how empty tiles are handled, using the ShpFileEmptyTileHandler.
- * shpFile=/Users/dietrick/dev/openmap/share/data/shape/cntry02/cntry02.shp
- * land.fillColor=DECD8B
- * background.fillColor=EAFFF4
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform
- * land.lineColor=DECD8B
- * background.lineColor=EAFFF4
- * 
- * 
- * - * NOTE: If you create a set of tile jars to use with a Windows jre, and you're - * having problems when the jars are added to the classpath, it's because there - * are too many tiles in the jars. The number for files in this case can't - * exceed 262144. So you have to increase the zoom level used for the layout of - * the subjar files. - * - * @author ddietrick - */ -public class WholeWorldTileHandler extends ShpFileEmptyTileHandler { - public final static String SUBJAR_ZOOMLEVEL_PROPERTY = "subJarZoomLevel"; - public final static String WORLDWIDE_ZOOMLEVEL_PROPERTY = "worldWideZoomLevel"; - public final static String PARENT_JAR_NAME_PROPERTY = "parentJarName"; - public final static int DEFAULT_SUBJAR_DEF_ZOOMLEVEL = 3; - public final static int DEFAULT_WORLDWIDE_ZOOMLEVEL = 10; - protected int subFrameDefZoomLevel = DEFAULT_SUBJAR_DEF_ZOOMLEVEL; - protected int worldWideZoomLevel = DEFAULT_WORLDWIDE_ZOOMLEVEL; - protected String parentJarName; - protected Set loadedJars; - protected String rootDirForJars; - - final static String SOURCE = "source"; - final static String TARGET = "target"; - final static String SUB_JAR_ZOOM = "subJarZoom"; - final static String MAX_ZOOM_IN_SUBJARS = "maxZoomInSubJars"; - final static String WORLD_WIDE_ZOOM_LEVEL = "worldWideZoomLevel"; - final static String TILE_EXT = "tileExt"; - final static String MINX = "minx"; - final static String MINY = "miny"; - final static String MAXX = "maxx"; - final static String MAXY = "maxy"; - final static String NO_WORLD_JAR = "noWorldJar"; - final static String VERBOSE = "verbose"; - final static String FILL = "fill"; - - /** - * Turns out that the Windows JRE won't add jar files with more than 262144 - * tiles in them. - */ - public final static int WIN_MAX_FILES_IN_JAR = 262144; - - public WholeWorldTileHandler() { - loadedJars = Collections.synchronizedSet(new HashSet()); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.EmptyTileHandler# - * getOMGraphicForEmptyTile (java.lang.String, int, int, int, - * com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform, - * com.bbn.openmap.proj.Projection) - */ - public BufferedImage getImageForEmptyTile(String imagePath, int x, int y, int zoomLevel, - MapTileCoordinateTransform mtcTransform, - Projection proj) { - - BufferedImage bi = null; - - if (parentJarName != null) { - - /** - * OK, the thing to remember here is that if this method has been - * called, the tile has not been found. So our job here is to - * determine if a jar file needs to be loaded, and if it does, load - * it and see if the missing tile is in it. If a jar doesn't need to - * be loaded, then we push the action up to the superclass - it's a - * non-created tile. - */ - Point2D pnt = new Point2D.Double(x, y); - Point2D tileUL = mtcTransform.tileUVToLatLon(pnt, zoomLevel); - - StringBuilder jarFilePath = new StringBuilder("jar:file:").append(rootDirForJars).append("/"); - - if (zoomLevel <= worldWideZoomLevel) { - /* - * Need to load the primary jar that has worldwide coverage. - */ - jarFilePath.append(parentJarName); - - } else { - /* - * Need to figure out what the subjar name is, given the lat/lon - * coordinate of the tile. - */ - - Point2D subframeUVPnt = mtcTransform.latLonToTileUV(tileUL, subFrameDefZoomLevel); - jarFilePath.append(buildSubJarName(parentJarName, subframeUVPnt.getX(), subframeUVPnt.getY())); - } - - jarFilePath.append("!/").append(imagePath); - - byte[] imageBytes = getImageBytes(jarFilePath.toString()); - - if (imageBytes != null && imageBytes.length > 0) { - // image found - - try { - ImageIcon ii = new ImageIcon(imageBytes); - Image origImage = ii.getImage(); - int imageWidth = ii.getIconWidth(); - int imageHeight = ii.getIconHeight(); - - if (origImage instanceof BufferedImage) { - return (BufferedImage) origImage; - } else { - return BufferedImageHelper.getBufferedImage(origImage, 0, 0, imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); - } - - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("WholeWorldTileHandler interrupted fetching " + imagePath); - } - } - - } - - } else { - logger.fine("parent jar name not set, can't figure out how to load tile jars."); - } - - // If no image is found, do the default action for an empty tile. - if (bi == null) { - bi = super.getImageForEmptyTile(imagePath, x, y, zoomLevel, mtcTransform, proj); - } - - return bi; - } - - public static String buildSubJarName(String parentJarNme, double x, double y) { - int dotIndex = parentJarNme.length(); - if (parentJarNme.endsWith(".jar")) { - dotIndex = parentJarNme.lastIndexOf('.'); - } - - StringBuilder sBuilder = new StringBuilder(parentJarNme.substring(0, dotIndex)); - sBuilder.append("_" + ((int) x) + "_" + ((int) y) + parentJarNme.substring(dotIndex)); - - return sBuilder.toString(); - } - - /** - * Tries to get the image bytes from imagePath URL. If image found, will - * write it locally to localFilePath for caching. - * - * @param imagePath the source URL image path. - * @return byte[] of image - */ - public byte[] getImageBytes(String imagePath) { - byte[] imageBytes = null; - - try { - java.net.URL url = new java.net.URL(imagePath); - java.net.URLConnection urlc = url.openConnection(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("url content type: " + urlc.getContentType()); - } - - if (urlc == null || urlc.getContentType() == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("unable to connect to (tile might be unavailable): " + imagePath); - } - - // text - } else if (urlc.getContentType().startsWith("text")) { - java.io.BufferedReader bin = new java.io.BufferedReader(new java.io.InputStreamReader(urlc.getInputStream())); - String st; - StringBuffer message = new StringBuffer(); - while ((st = bin.readLine()) != null) { - message.append(st); - } - - // Debug.error(message.toString()); - // How about we toss the message out to the user - // instead? - logger.fine(message.toString()); - - // image - } else if (urlc.getContentType().startsWith("image")) { - - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - - imageBytes = out.toByteArray(); - - } // end if image - } catch (java.net.MalformedURLException murle) { - logger.warning("WholeWorldTileHandler: URL \"" + imagePath + "\" is malformed."); - } catch (java.io.IOException ioe) { - logger.fine("Couldn't connect to " + imagePath + ", connection problem"); - } - - return imageBytes; - - } - - /** - * Load the jar if necessary. Not called anymore, but left here as a note on - * how to dynamically modify the classpath to add a jar at runtime. - * - * @param jarFileName the absolute path to the jar. - * @return true if the jar was loaded, false if it was added before and no - * attempt made. - */ - protected synchronized boolean loadJar(String jarFileName) { - - boolean ret = loadedJars.contains(jarFileName); - - if (!ret) { - try { - logger.fine("adding " + jarFileName + " to classpath"); - ClasspathHacker.addFile(jarFileName); - } catch (IOException ioe) { - logger.warning("couldn't add map data jar file: " + jarFileName); - } - - /* - * We're going to add the jarFileName to the list regardless of - * whether it was successful or not, to avoid having repeated - * failures on subsequent jar loads. - */ - loadedJars.add(jarFileName); - } - - return !ret; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - subFrameDefZoomLevel = PropUtils.intFromProperties(props, prefix - + SUBJAR_ZOOMLEVEL_PROPERTY, subFrameDefZoomLevel); - worldWideZoomLevel = PropUtils.intFromProperties(props, prefix - + WORLDWIDE_ZOOMLEVEL_PROPERTY, worldWideZoomLevel); - rootDirForJars = props.getProperty(prefix - + StandardMapTileFactory.ROOT_DIR_PATH_PROPERTY, rootDirForJars); - - String jarBaseName = props.getProperty(prefix + PARENT_JAR_NAME_PROPERTY); - if (jarBaseName != null) { - setParentJarName(jarBaseName); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + SUBJAR_ZOOMLEVEL_PROPERTY, Integer.toString(subFrameDefZoomLevel)); - props.put(prefix + WORLDWIDE_ZOOMLEVEL_PROPERTY, Integer.toString(worldWideZoomLevel)); - props.put(prefix + PARENT_JAR_NAME_PROPERTY, PropUtils.unnull(getParentJarName())); - - return props; - } - - /** - * Get the tile zoom level that the subjar borders are based on. - * - * @return the subFrameDefZoomLevel - */ - public int getSubFrameDefZoomLevel() { - return subFrameDefZoomLevel; - } - - /** - * Set the tile zoom level that the subjar borders will be based on. - * - * @param subFrameZoomLevel the subFrameDefZoomLevel to set - */ - public void setSubFrameDefZoomLevel(int subFrameZoomLevel) { - this.subFrameDefZoomLevel = subFrameZoomLevel; - } - - /** - * Get the name of the jar with worldwide coverage, for zoom levels - * 0-worldWideZoomLevel. - * - * @return the parentJarName - */ - public String getParentJarName() { - return parentJarName; - } - - /** - * Set the name of the jar with worldwide coverage, for tiles with zoom - * levels 0-worldWideZoomLevel. - * - * @param parentJarName the parentJarName to set - */ - public void setParentJarName(String parentJarName) { - this.parentJarName = parentJarName; - } - - /** - * Get the maximum tile zoom level that is contained in the worldwide jar. - * - * @return the worldWideZoomLevel - */ - public int getWorldWideZoomLevel() { - return worldWideZoomLevel; - } - - /** - * Set the maximum tile zoom level that is contained in the worldwide jar. - * - * @param worldWideZoomLevel the worldWideZoomLevel to set - */ - public void setWorldWideZoomLevel(int worldWideZoomLevel) { - this.worldWideZoomLevel = worldWideZoomLevel; - } - - /** - * The builder class takes a map tile directory and creates a set of jars - * from it, divided so that the WholeWorldTileHandler can deal with it. It - * will create one jar file that holds the tiles that cover the world for a - * selected set of tiles. It then creates jar files (sub-jars) that contain - * tiles for the other zoom levels. These sub-jars are organized by - * geographic zone as defined by tiles from a lower zoom level. The default - * level is 3. For instance, subjar_0_0.jar contains all the tiles for zoom - * levels 11-20 that fit in the geographic area covered by tile 0, 0 for - * zoom level 3. - *

- * There are options to control the geographic area definition zoom level, - * the zoom level for the tiles stored in the world-wide jar, and the - * maximum zoom level inserted in to the sub-jars. - * - * @author ddietrick - */ - public static class Builder { - protected File sourceFile; - protected File targetFile; - protected int subJarZoomDef = WholeWorldTileHandler.DEFAULT_SUBJAR_DEF_ZOOMLEVEL; - protected int worldWideZoomLevel = 10; - protected int maxZoomLevelInSubJars = 20; - protected String tileExt = ".png"; - protected int minx = 0; - protected int miny = 0; - protected int maxx = -1; - protected int maxy = -1; - protected boolean doWorldJar = true; - protected boolean fill = false; - protected Level logLevel = Level.FINE; - - public Builder(File source) throws FileNotFoundException { - - if (source == null || !source.exists()) { - throw new FileNotFoundException("Source file invalid"); - } - - this.sourceFile = source; - } - - public Builder targetFile(File targetFile) { - this.targetFile = targetFile; - - return this; - } - - public Builder tileExt(String tileExtension) { - if (!tileExtension.startsWith(".")) { - tileExtension = "." + tileExtension; - } - this.tileExt = tileExtension; - return this; - } - - public Builder subJarZoomDef(int zoomLevel) throws NumberFormatException { - if (checkZoomLevel(zoomLevel)) { - this.subJarZoomDef = zoomLevel; - } - return this; - } - - public Builder worldWideZoomLevel(int zoomLevel) throws NumberFormatException { - if (checkZoomLevel(zoomLevel)) { - this.worldWideZoomLevel = zoomLevel; - } - return this; - } - - public Builder maxZoomLevelInSubJars(int zoomLevel) throws NumberFormatException { - if (checkZoomLevel(zoomLevel)) { - this.maxZoomLevelInSubJars = zoomLevel; - } - return this; - } - - protected boolean checkZoomLevel(int zoomLevel) { - if (zoomLevel < 0 || zoomLevel > 20) { - throw new NumberFormatException("Zoom level needs to be > 0 and < 20"); - } - return true; - } - - public String toString() { - StringBuilder sb = new StringBuilder("WholeWorldTileHandler["); - sb.append("source:").append(sourceFile).append(','); - sb.append("target:").append(targetFile).append(','); - sb.append("subJarZoomDef:").append(subJarZoomDef).append(','); - sb.append("worldWideZoomLevel:").append(worldWideZoomLevel).append(','); - sb.append("maxZoomLevelInSubJars:").append(maxZoomLevelInSubJars).append(','); - sb.append("tileExt:").append(tileExt); - if (minx != 0) { - sb.append(",").append("minx:").append(minx); - } - if (miny != 0) { - sb.append(",").append("miny:").append(miny); - } - if (maxx >= 0) { - sb.append(",").append("maxx:").append(maxx); - } - if (maxy >= 0) { - sb.append(",").append("maxy:").append(maxy); - } - - sb.append(']'); - - return sb.toString(); - } - - protected void copyAndUpdateProperties(File sourceDir, File targetDir) { - File propertiesFile = new File(sourceDir, StandardMapTileFactory.TILE_PROPERTIES); - if (propertiesFile.exists()) { - try { - URL propertiesURL = propertiesFile.toURI().toURL(); - - Properties props = new Properties(); - props.load(propertiesURL.openStream()); - - props.put(StandardMapTileFactory.EMPTY_TILE_HANDLER_PROPERTY, WholeWorldTileHandler.class.getName()); - props.put(SUBJAR_ZOOMLEVEL_PROPERTY, Integer.toString(subJarZoomDef)); - props.put(WORLDWIDE_ZOOMLEVEL_PROPERTY, Integer.toString(worldWideZoomLevel)); - props.put(PARENT_JAR_NAME_PROPERTY, sourceDir.getName() + ".jar"); - props.put(StandardMapTileFactory.ROOT_DIR_PROPERTY, sourceDir.getName()); - - FileOutputStream fos = new FileOutputStream(new File(targetDir, StandardMapTileFactory.TILE_PROPERTIES)); - props.store(fos, "Properties for " + targetDir + " tile set"); - fos.close(); - - } catch (MalformedURLException e) { - e.printStackTrace(); - logger.warning("can't find/read properties file for tile set"); - } catch (IOException e) { - e.printStackTrace(); - logger.warning("exception reading/copying properties file for tile set"); - } - } - } - - public void go() throws FileNotFoundException, IOException { - - if (targetFile == null) { - targetFile = new File(sourceFile, sourceFile.getName()); - } - - if (!targetFile.exists()) { - targetFile.mkdirs(); - } - - File parentOfSourceFile = sourceFile.getParentFile(); - int numCharsTrimmedOffNameInZip = 0; - if (parentOfSourceFile != null) { - numCharsTrimmedOffNameInZip = parentOfSourceFile.getAbsolutePath().length() + 1; - } - - logger.log(Level.INFO, "inspecting files in " + sourceFile + " (" - + (parentOfSourceFile == null ? "CAUTION: nothing" - : parentOfSourceFile.getAbsolutePath()) - + " removed from names in jars)."); - - copyAndUpdateProperties(sourceFile, targetFile); - - // Create the top-level worldwide jar - if (doWorldJar) { - List jarDirs = new ArrayList(); - - for (int zoomLevel = 0; zoomLevel <= worldWideZoomLevel; zoomLevel++) { - File zoomLevelDir = new File(sourceFile, Integer.toString(zoomLevel)); - if (zoomLevelDir.exists()) { - jarDirs.add(zoomLevelDir); - } - } - - if (!jarDirs.isEmpty() && sourceFile != null) { - String worldWideJarFile = targetFile + File.separator + sourceFile.getName() - + ".jar"; - logger.log(logLevel, "writing :" + worldWideJarFile); - - if (fill) { - File fileCheck = new File(worldWideJarFile); - if (fileCheck.exists()) { - doWorldJar = false; - } - } - - // after the fill check, check this again. - if (doWorldJar) { - - FileOutputStream fos = new FileOutputStream(worldWideJarFile); - CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32()); - ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(checksum)); - - // ZipOutputStream zoStream = new ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.DEFLATED); - for (File file : jarDirs) { - FileUtils.writeZipEntry(file, zoStream, numCharsTrimmedOffNameInZip); - } - zoStream.close(); - - } else { - logger.log(logLevel, worldWideJarFile + " already exists, skipping"); - } - } - } else { - logger.log(logLevel, "skipping world file"); - } - // Worldwide jar created. - - // Now create subjars - int dimensionForZoom = (int) Math.pow(2, subJarZoomDef); - MapTileCoordinateTransform transform = new OSMMapTileCoordinateTransform(); - - int startx = 0; - int starty = 0; - int endx = dimensionForZoom; - int endy = dimensionForZoom; - - // OK, look at the minx, miny, maxx, maxy to figure out the jar - // files to create. - if (minx >= 0) { - startx = minx; - } - - if (maxx >= 0) { - endx = Math.min(maxx + 1, dimensionForZoom); - } - - if (miny >= 0) { - starty = miny; - } - - if (maxy >= 0) { - endy = Math.min(maxy + 1, dimensionForZoom); - } - - // x, y tile coordinates for subjar files. - for (int x = startx; x < endx; x++) { - for (int y = starty; y < endy; y++) { - - // Calculate the lat/lon limits of the current tile - Point2D llp1 = transform.tileUVToLatLon(new Point2D.Double(x, y), subJarZoomDef); - Point2D llp2 = transform.tileUVToLatLon(new Point2D.Double(x + 1, y - + 2), subJarZoomDef); - - File subJarFile = new File(targetFile, sourceFile.getName() + "_" + x + "_" + y - + ".jar"); - - if (fill && subJarFile.exists()) { - logger.log(logLevel, subJarFile + " already exists, skipping"); - continue; - } - - logger.log(logLevel, "Creating: " + subJarFile); - long fileCount = 0; - ZipOutputStream zoStream = null; - - for (int zoomLevel = worldWideZoomLevel - + 1; zoomLevel <= maxZoomLevelInSubJars; zoomLevel++) { - - File checkZoomLevelDir = new File(sourceFile, Integer.toString(zoomLevel)); - if (checkZoomLevelDir.exists()) { - - // These are the tile coordinate bounds for this - // subjar for this zoom level - Point2D uv1 = transform.latLonToTileUV(llp1, zoomLevel); - Point2D uv2 = transform.latLonToTileUV(llp2, zoomLevel); - - logger.log(logLevel, "adding zoom level " + zoomLevel + " tiles to " - + subJarFile.getName() + ": " + uv1 + "|" + uv2); - - for (int u = (int) uv1.getX(); u < uv2.getX(); u++) { - for (int v = (int) uv1.getY(); v < uv2.getY(); v++) { - // add file to subjar stream - File tile = new File(sourceFile, zoomLevel + "/" + u + "/" + v - + tileExt); - if (tile.exists()) { - - if (zoStream == null) { - /* - * We need to do this because we - * need to make sure a zip output - * stream is created only when a - * file is going to be written to - * it. you can't create a zip file - * and then put nothing into it. - */ - @SuppressWarnings("resource") - FileOutputStream fos = new FileOutputStream(subJarFile); - - CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32()); - zoStream = new ZipOutputStream(new BufferedOutputStream(checksum)); - - // zoStream = new - // ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.DEFLATED); - } - - if (tile.getAbsolutePath().length() - - numCharsTrimmedOffNameInZip > 0) { - FileUtils.writeZipEntry(tile, zoStream, numCharsTrimmedOffNameInZip); - fileCount++; - } else { - logger.info("Problem, there's something wrong with tile name: " - + tile.getAbsolutePath()); - } - } - } - } - } - } - - if (zoStream != null) { - zoStream.close(); - zoStream = null; - logger.log(logLevel, "closing zip file (" + subJarFile.getPath() - + "), added " + fileCount + " files to jar"); - } - } - } - } - - /** - * Set the starting x number of the subjar file to create. Depends on - * the subjar zoom to figure out what that means. - * - * @param parseInt - */ - public void minx(int parseInt) { - minx = parseInt; - } - - /** - * Set the starting y number of the subjar file to create. Depends on - * the subjar zoom to figure out what that means. - * - * @param parseInt - */ - public void miny(int parseInt) { - miny = parseInt; - } - - /** - * Set the ending y number of the subjar file to create. Depends on the - * subjar zoom to figure out what that means. - * - * @param parseInt - */ - public void maxx(int parseInt) { - maxx = parseInt; - } - - /** - * Set the ending y number of the subjar file to create. Depends on the - * subjar zoom to figure out what that means. - * - * @param parseInt - */ - public void maxy(int parseInt) { - maxy = parseInt; - } - - public void setDoWorldJar(boolean dwj) { - doWorldJar = dwj; - } - - /** - * Check whether the build process will only create jars that don't - * exist. - */ - public boolean isFill() { - return fill; - } - - /** - * Set whether the build process will only create jars that don't exist. - * - * @param fill - */ - public void setFill(boolean fill) { - this.fill = fill; - } - } - - /** - * Takes arguments for source tile directory, target directory, and option - * sub-jar zoom level, and creates jars in the right place with expected - * tiles. Prints usage statement. - * - * @param args - */ - public static void main(String[] args) { - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("WholeWorldTileHandler"); - - ap.add(SOURCE, "Path to the tile root directory.", 1); - ap.add(TARGET, "Path to the tile root directory for the jarred tile files.", 1); - ap.add(SUB_JAR_ZOOM, "Zoom level tiles that subjar boundaries are based on (3 is default).", 1); - ap.add(MAX_ZOOM_IN_SUBJARS, "Maximum tile zoom level added to sub jars (20 is default).", 1); - ap.add(WORLD_WIDE_ZOOM_LEVEL, "Maximum tile zoom level to add to world wide jar (10 is default).", 1); - ap.add(TILE_EXT, "Tile extension (.png is default).", 1); - ap.add(MINX, "Subjar x minimum to create", 1); - ap.add(MINY, "Subjar y minimum to create", 1); - ap.add(MAXX, "Subjar x maximum to create", 1); - ap.add(MAXY, "Subjar y maximum to create", 1); - ap.add(NO_WORLD_JAR, "Don't create world level jar file"); - ap.add(VERBOSE, "Comment on what's going on"); - ap.add(FILL, "Just create jars that don't exist."); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String[] arg = ap.getArgValues(SOURCE); - if (arg != null) { - try { - Builder wwthBuilder = new Builder(new File(arg[0])); - - arg = ap.getArgValues(TARGET); - if (arg != null) { - wwthBuilder.targetFile(new File(arg[0])); - } - - arg = ap.getArgValues(SUB_JAR_ZOOM); - if (arg != null) { - wwthBuilder.subJarZoomDef(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(MAX_ZOOM_IN_SUBJARS); - if (arg != null) { - wwthBuilder.maxZoomLevelInSubJars(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(WORLD_WIDE_ZOOM_LEVEL); - if (arg != null) { - wwthBuilder.worldWideZoomLevel(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(TILE_EXT); - if (arg != null) { - wwthBuilder.tileExt(arg[0]); - } - - arg = ap.getArgValues(MINX); - if (arg != null) { - wwthBuilder.minx(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(MINY); - if (arg != null) { - wwthBuilder.miny(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(MAXX); - if (arg != null) { - wwthBuilder.maxx(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(MAXY); - if (arg != null) { - wwthBuilder.maxy(Integer.parseInt(arg[0])); - } - - arg = ap.getArgValues(VERBOSE); - if (arg != null) { - wwthBuilder.logLevel = Level.INFO; - } - - arg = ap.getArgValues(FILL); - if (arg != null) { - wwthBuilder.setFill(true); - } - - arg = ap.getArgValues(NO_WORLD_JAR); - if (arg != null) { - logger.log(wwthBuilder.logLevel, "setting build world file to false"); - wwthBuilder.setDoWorldJar(false); - } - - System.out.println(wwthBuilder.toString()); - - wwthBuilder.go(); - - } catch (NumberFormatException nfe) { - nfe.printStackTrace(); - logger.warning(nfe.getMessage()); - } catch (FileNotFoundException fnfe) { - fnfe.printStackTrace(); - logger.warning(fnfe.getMessage()); - } catch (IOException ioe) { - ioe.printStackTrace(); - logger.warning(ioe.getMessage()); - } - } else { - ap.bail("Need a source directory.", true); - } - - System.exit(0); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelInfo.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelInfo.java deleted file mode 100644 index 1fe21edad..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelInfo.java +++ /dev/null @@ -1,147 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import com.bbn.openmap.OMComponent; - -/** - * The ZoomLevelInfo class is used by the TileMaker and handles how tiles are - * defined and created for a particular zoom level. It handles any bounds - * restrictions, what layers should be rendered at this zoom level, and the path - * to the tiles from the root directory. - *

- * The ZoomLevelMaker class has the properties used to create ZoomLevelInfo - * objects. - * - * @author dietrick - */ -public class ZoomLevelInfo extends OMComponent { - - protected int zoomLevel = 0; - protected float scale = -1f; - - /** - * Default constructor. - */ - public ZoomLevelInfo() { - } - - /** - * @return the current zoom level. - */ - public int getZoomLevel() { - return zoomLevel; - } - - /** - * @param zoomLevel the current zoom level. - */ - public void setZoomLevel(int zoomLevel) { - this.zoomLevel = zoomLevel; - } - - /** - * Return the current scale set in this object. - * - * @return scale setting for zoom level - */ - public float getScale() { - return scale; - } - - /** - * Set the current scale to use for calculating the zoom level. - * - * @param scale to set - */ - public void setScale(float scale) { - this.scale = scale; - } - - /** - * @return the number of tiles across or down for the current zoom level. - */ - public int getEdgeTileCount() { - return (int) Math.pow(2, zoomLevel); - } - - /** - * Given a bounds containing a lat/lon box (x, y, w, h in decimal degrees) and a - * transform for the MapTileCoordinates being used for the tiles (OpenStreetMap - * or Google (MTS)), provide the UV tile coordinates for the the bounding box. - * - * @param bounds decimal degree bounds - * @param mtct MapTileCoordinateTransform (OSMMapTileCoordinateTransform or - * TMSMapTileCoordinateTransform). - * @return UV tile coordinates for bounds. - */ - public Rectangle2D getUVBounds(Rectangle2D bounds, MapTileCoordinateTransform mtct, int zoomLevel) { - double x = bounds.getX(); - double y = bounds.getY(); - double h = bounds.getHeight(); - double w = bounds.getWidth(); - Point2D point1 = new Point2D.Double(x, y + h); - Point2D point2 = new Point2D.Double(x + w, y); - Point2D uluv = mtct.latLonToTileUV(point1, zoomLevel); - Point2D lruv = mtct.latLonToTileUV(point2, zoomLevel); - x = Math.floor(uluv.getX()); - y = Math.floor(uluv.getY()); - w = Math.ceil(lruv.getX() - x); - h = Math.ceil(lruv.getY() - y); - - return new Rectangle2D.Double(x, y, w, h); - } - - /** - * Creates the parent directory of the file with the current zoom level set in - * the ZoomLevelInfo. - * - * @param rootDir path to root of dir structire, with no file separator at the - * end. - * @param uvx uv x coordinate of map tile. - * @param uvy uv y coordinate of map tile. - * @return path of parent directory of the file (no y coordinate). - */ - public String formatParentDirectoryName(String rootDir, int uvx, int uvy) { - return rootDir + "/" + getZoomLevel() + "/" + uvx; - } - - /** - * Creates file path given a root directory plus current zoom level, x, and y. - * Ready for file extension, which should have a period on it. - * - * @param rootDir path to root of dir structure, with no file separator at the - * end. - * @param uvx uv x coordinate of the map tile. - * @param uvy uv y coordinate of the map tile - * @return a file path, sans file extension. - */ - public String formatImageFilePath(String rootDir, int uvx, int uvy) { - return rootDir + "/" + getZoomLevel() + "/" + uvx + "/" + uvy; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMaker.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMaker.java deleted file mode 100644 index c9c4a44a8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMaker.java +++ /dev/null @@ -1,372 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.geom.Rectangle2D; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The ZoomLevelMaker class uses properties to create and define ZoomLevelInfo - * classes used by the TileMaker. - *

- * - *

- * #Needed for property file creation of TileMaker
- * zoomMarker.class=com.bbn.openmap.image.ZoomLevelInfo
- * #Optional, upper left and lower right coordinates to limit tile areas created, in sets of 4 values. Must be in lat,lon order.
- * zoomMarker.bounds=lat lon lat lon
- * zoomMarker.description=Tiles for zoom level 4
- * #Marker names for layers to be rendered, the property prefixes for the layers held by TileMaker
- * zoomMarker.layers=lakes shape
- * zoomMarker.name=ZoomLayerInfo 4
- * #Zoom level to start making tiles with this definition.
- * zoomMarker.zoomLevel=4O
- * #How many zoom levels should be supported.
- * zoomMarker.range=0
- * 
- * 
- * - * Note that the zoomMarker keyword should be stored in the TileMaker zoomLevels - * property list. - * - * @author dietrick - */ -public class ZoomLevelMaker extends ZoomLevelInfo { - - public final static String BOUNDS_PROPERTY = "bounds"; - public final static String NAME_PROPERTY = "name"; - public final static String DESCRIPTION_PROPERTY = "description"; - public final static String ZOOM_LEVEL_PROPERTY = "zoomLevel"; - public final static String LAYERS_PROPERTY = "layers"; - public final static String RANGE_PROPERTY = "range"; - - public final static int RANGE_NOT_SET = -1; - - protected String name; - protected String description; - protected List layers; - protected List layerList; - - /** - * The range should be equal or smaller than the zoom level, describing how many - * other zoom levels should be created from the tiles created for this zoom - * level (scaling). If the range is -1, then it hasn't been set and the zoom - * level will be returned for this value. - */ - protected int range = RANGE_NOT_SET; - protected List bounds = new LinkedList(); - - /** - * Need this to create it from properties - */ - public ZoomLevelMaker() { - } - - /** - * Create a ZoomLevelInfo object that contains information about what map tiles - * should be created for this zoom level. - * - * @param name - * @param desc - * @param zoomLevel - */ - public ZoomLevelMaker(String name, String desc, int zoomLevel) { - this.name = name; - this.description = desc; - this.zoomLevel = zoomLevel; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - name = props.getProperty(prefix + NAME_PROPERTY, name); - description = props.getProperty(prefix + DESCRIPTION_PROPERTY, description); - zoomLevel = PropUtils.intFromProperties(props, prefix + ZOOM_LEVEL_PROPERTY, zoomLevel); - range = PropUtils.intFromProperties(props, prefix + RANGE_PROPERTY, range); - - String boundsPropertyStrings = props.getProperty(prefix + BOUNDS_PROPERTY); - if (boundsPropertyStrings != null) { - List boundsStrings = PropUtils.parseSpacedMarkers(boundsPropertyStrings); - int count = 0; - while (boundsStrings != null && !boundsStrings.isEmpty() && boundsStrings.size() >= count + 4) { - double lat1 = Double.parseDouble(boundsStrings.get(count)); - double lon1 = Double.parseDouble(boundsStrings.get(count + 1)); - double lat2 = Double.parseDouble(boundsStrings.get(count + 2)); - double lon2 = Double.parseDouble(boundsStrings.get(count + 3)); - - bounds.add(createProperBounds(lon1, lat1, lon2, lat2)); - count += 4; - } - } - - String layerPropertyStrings = props.getProperty(prefix + LAYERS_PROPERTY); - if (layerPropertyStrings != null) { - List layerStrings = PropUtils.parseSpacedMarkers(layerPropertyStrings); - if (layerStrings != null && !layerStrings.isEmpty()) { - getLayers().addAll(layerStrings); - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + ComponentFactory.ClassNameProperty, getClass().getName()); - props.put(prefix + NAME_PROPERTY, PropUtils.unnull(name)); - props.put(prefix + DESCRIPTION_PROPERTY, PropUtils.unnull(description)); - props.put(prefix + ZOOM_LEVEL_PROPERTY, Integer.toString(zoomLevel)); - - if (range != RANGE_NOT_SET) { - props.put(prefix + RANGE_PROPERTY, Integer.toString(range)); - } - - StringBuffer buf = new StringBuffer(); - for (String layerMarkerName : layers) { - buf.append(layerMarkerName).append(" "); - } - props.put(prefix + LAYERS_PROPERTY, buf.toString().trim()); - - buf = new StringBuffer(); - for (Rectangle2D bound : getBounds()) { - double x = bound.getX(); - double y = bound.getY(); - buf.append(y).append(" ").append(x).append(" ").append((y + bound.getHeight())).append(" ") - .append((x + bound.getWidth())).append(" "); - } - props.put(prefix + BOUNDS_PROPERTY, buf.toString().trim()); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - I18n i18n = Environment.getI18n(); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - NAME_PROPERTY, "Name", "Name for zoom level tiles", null); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - DESCRIPTION_PROPERTY, "Descroption", "Description for zoom level tiles", null); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - ZOOM_LEVEL_PROPERTY, "Zoom Level (1-20)", "Number for zoom level", null); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - BOUNDS_PROPERTY, "Bounds", "Bounds for tile creation (lat lon lat lon)", null); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - LAYERS_PROPERTY, "Layers", "Space separated marker names for layers used in tiles.", null); - - PropUtils.setI18NPropertyInfo(i18n, props, com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker.class, - RANGE_PROPERTY, "Range", - "Zoom level to create tiles down to, using the tiles created at this zoom level.", null); - - return props; - } - - /** - * @return the name of this zoom level info. - */ - public String getName() { - return name; - } - - /** - * Set the name of this zoom level info. - * - * @param name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Get the description of this zoom level. - * - * @return string description of zoom level - */ - public String getDescription() { - return description; - } - - /** - * Set the description for this zoom level. - * - * @param description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Get the current marker name (property prefix) for layers considered for this - * zoom level. - * - * @return layers used for zoom level - */ - public List getLayers() { - if (layers == null) { - layers = new LinkedList(); - } - return layers; - } - - /** - * Set the marker names (property prefixes) for the layers that should be - * considered for this zoom level. - * - * @param layers - */ - public void setLayers(List layers) { - this.layers = layers; - } - - /** - * Get the List of Layer Objects, if it's been set. - * - * @return List of Layers - */ - public List getLayerList() { - return layerList; - } - - /** - * Set a List of Layer objects. If this is set, the layer marker names won't be - * used. This is a more programmatic approach, rather than using properties and - * property prefixes of the layers to set them for this zoom level. - * - * @param layerList - */ - public void setLayerList(List layerList) { - this.layerList = layerList; - } - - public void setZoomLevel(int zoomLevel) { - super.setZoomLevel(zoomLevel); - scale = -1; - } - - /** - * Get bounds, defined as world coordinates (i.e. lat/lon). Does not cross over - * date line. - * - * @return the bounds for this zoom level - */ - public List getBounds() { - return bounds; - } - - /** - * Set world coordinate bounds for tiles to be created. Should not cross over - * date line. - * - * @param bounds No checks performed - x, y have to be the min, height and width - * must not exceed boundary limits (lat +/- 85, lon +/- 180) when - * added to x, y. - */ - public void addBounds(Rectangle2D bounds) { - this.bounds.add(bounds); - } - - /** - * Get the bounds as defined as UV tile limits. - * - * @return a List of Rectangle2D of uv bounds for this zoom level - */ - public List getUVBounds(MapTileCoordinateTransform mtct, int zoomLevel) { - List ret = new LinkedList(); - for (Rectangle2D bounds : getBounds()) { - ret.add(getUVBounds(bounds, mtct, zoomLevel)); - } - - if (ret.isEmpty()) { - int etc = getEdgeTileCount(); - ret.add(new Rectangle2D.Double(0, 0, etc, etc)); - } - - return ret; - } - - /** - * Create a bounding rectangle given the four coordinates, where the upper left - * corner of the rectangle is the minimum x, y values and the width and height - * are the difference between xs and ys. - * - * @param x1 - * @param y1 - * @param x2 - * @param y2 - * @return Rect2D, properly constructed from coordinates - */ - public Rectangle2D createProperBounds(double x1, double y1, double x2, double y2) { - double x = Math.min(x1, x2); - double y = Math.min(y1, y2); - double w = Math.abs(x1 - x2); - double h = Math.abs(y1 - y2); - return new Rectangle2D.Double(x, y, w, h); - } - - /** - * Get the range of this ZoomLevelMaker. - * - * @return the range set for this zlm, or the current zoom level if the range - * has not been set. - */ - public int getRange() { - if (range <= RANGE_NOT_SET) { - return getZoomLevel(); - } - - return range; - } - - public void setRange(int range) { - this.range = range; - } - - /** - * @param uvx - * @param uvy - * @param mapTileMaker - * @param proj - * @return byte array of the tile image, raw image bytes. - */ - public byte[] makeTile(double uvx, double uvy, MapTileMaker mapTileMaker, Proj proj) { - if (layerList != null) { - return mapTileMaker.makeTile(uvx, uvy, getZoomLevel(), layerList, proj, mapTileMaker.getBackground()); - } - return mapTileMaker.makeTile(uvx, uvy, this, proj); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java deleted file mode 100644 index a2f80399a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java +++ /dev/null @@ -1,700 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.net.URL; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - -import javax.swing.AbstractListModel; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.ListSelectionModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; - -/** - * A class that visually manages the settings for a ZoomLevelInfo object. Works - * inside the MapTileMakerComponent. - * - * @author dietrick - */ -public class ZoomLevelMakerFace extends OMComponentPanel { - - protected static Logger logger = Logger - .getLogger("com.bbn.openmap.dataAccess.mapTile.ZoomLevelMakerFace"); - - private static final long serialVersionUID = 1L; - protected ZoomLevelMaker zfi; - boolean active = false; - boolean include = false; - - protected JList boundsList; - protected List boundsObjectList; - protected BoundsListModel boundsModel; - protected OMGraphicList boundaries = new OMGraphicList(); - - protected List layerList = new ArrayList(); - protected MapTileMakerComponent organizer; - - protected JPanel layerPanel; - protected JButton createBoundaryButton; - protected JButton editBoundaryButton; - protected JButton deleteBoundaryButton; - protected JLabel intro; - protected JLabel tileDimensions; - protected JButton scaleButton; - JSpinner rangeLevelChoice; - - @SuppressWarnings("serial") - public ZoomLevelMakerFace(ZoomLevelMaker zfi, MapTileMakerComponent mtmc) { - - this.zfi = zfi; - this.organizer = mtmc; - setLayout(new GridBagLayout()); - - JPanel introPanel = new JPanel(new GridBagLayout()); - - JLabel intro = new JLabel(i18n.get(ZoomLevelMakerFace.class, - "zoom_level", "Make tiles for zoom levels")); - JLabel tileDimLabel = new JLabel(i18n.get(ZoomLevelMakerFace.class, - "tile_dim", "Tile Dimensions")); - JLabel baseScaleLabel = new JLabel(i18n.get(ZoomLevelMakerFace.class, - "base_scale", "Base Scale for Zoom Level")); - - JSpinner zoomLevelChoice = new JSpinner(new SpinnerNumberModel(0, 0, - 20, 1.0)) { - public void setValue(Object value) { - if (value instanceof Number) { - value = new Double(((Number) value).intValue()); - } - super.setValue(value); - - updateZoomLevel(((Double) getValue()).intValue()); - } - }; - String upperZoomLevelTT = i18n.get(ZoomLevelMakerFace.class, - "upper_zoom_level", I18n.TOOLTIP, "Upper zoom level"); - String lowerZoomLevelTT = i18n.get(ZoomLevelMakerFace.class, - "lower_zoom_level", I18n.TOOLTIP, "Lower zoom level"); - zoomLevelChoice.setToolTipText(upperZoomLevelTT); - - tileDimensions = new JLabel(); - scaleButton = new JButton(); - scaleButton.setBorder(BorderFactory.createLineBorder(Color.GRAY)); - scaleButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - MapHandler mHandler = (MapHandler) organizer.getBeanContext(); - MapBean map = mHandler.get(MapBean.class); - map.setScale(getZoomLevelMaker().getScale()); - } - }); - - rangeLevelChoice = new JSpinner(new SpinnerNumberModel(0, 0, 20, 1.0)) { - public void setValue(Object value) { - if (value instanceof Number) { - int newVal = ((Number) value).intValue(); - int limit = getZoomLevelMaker().getZoomLevel(); - if (newVal > limit) { - newVal = limit; - } - value = new Double(newVal); - - getZoomLevelMaker().setRange(newVal); - } - super.setValue(value); - } - }; - rangeLevelChoice.setToolTipText(lowerZoomLevelTT); - - GridBagConstraints c = new GridBagConstraints(); - c.gridx = GridBagConstraints.REMAINDER; - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(0, 0, 0, 0); - - JPanel zoomHolder = new JPanel(); - zoomHolder.add(zoomLevelChoice, c); - zoomHolder.add(new JLabel(" to "), c); - zoomHolder.add(rangeLevelChoice, c); - - addIntroEntry(introPanel, intro, zoomHolder, 0, new Insets(0, 0, 0, 0)); - addIntroEntry(introPanel, tileDimLabel, tileDimensions, 1, new Insets( - 0, 0, 5, 0)); - addIntroEntry(introPanel, baseScaleLabel, scaleButton, 2, new Insets(0, - 0, 5, 0)); - - updateZoomLevel(0); - add(introPanel, c); - - c.gridx = GridBagConstraints.REMAINDER; - c.anchor = GridBagConstraints.WEST; - - include = true; - - c.fill = GridBagConstraints.BOTH; - c.weightx = 1.0f; - - layerPanel = new JPanel(new GridBagLayout()); - setLayers(layerList); - - JPanel outerLayerPanel = new JPanel(new GridBagLayout()); - String layers_for_title = i18n.get(ZoomLevelMakerFace.class, - "layers_for_title", "Layers"); - outerLayerPanel.setBorder(BorderFactory - .createTitledBorder(layers_for_title)); - JScrollPane jsp = new JScrollPane(layerPanel, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - c.weighty = 1.0f; - c.insets = new Insets(0, 0, 0, 0); - outerLayerPanel.add(jsp, c); - c.weighty = .8f; - c.insets = new Insets(3, 0, 3, 0); - add(outerLayerPanel, c); - - JPanel boundsPanel = new JPanel(new BorderLayout()); - String boundaries_for_title = i18n.get(ZoomLevelMakerFace.class, - "boundaries_for_title", "Boundaries"); - boundsPanel.setBorder(BorderFactory - .createTitledBorder(boundaries_for_title)); - boundsObjectList = new ArrayList(); - boundsModel = new BoundsListModel(); - boundsList = new JList(boundsModel); - boundsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - boundsList.setLayoutOrientation(JList.VERTICAL); - boundsList.setVisibleRowCount(4); - boundsList.addListSelectionListener(new SelectionListener()); - boundsList.addMouseListener(new ListMouseListener()); - - JScrollPane scrollableBoundsList = new JScrollPane(boundsList, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - boundsPanel.add(scrollableBoundsList, BorderLayout.CENTER); - - JPanel boundsButtonPanel = new JPanel(); - - ImageIcon ii = createImageIcon("add_16x16.png"); - createBoundaryButton = new JButton(ii); - String create_a_boundary_rectangle = i18n.get(ZoomLevelMakerFace.class, - "create_a_boundary_rectangle", "Create a boundary rectangle"); - createBoundaryButton.setToolTipText(create_a_boundary_rectangle); - createBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - organizer.createRectangle(); - } - }); - boundsButtonPanel.add(createBoundaryButton); - - ii = createImageIcon("edit_16x16.png"); - editBoundaryButton = new JButton(ii); - String edit_a_selected_boundary_rectangle = i18n.get( - ZoomLevelMakerFace.class, "edit_a_selected_boundary_rectangle", - "Edit a selected boundary rectangle"); - editBoundaryButton.setToolTipText(edit_a_selected_boundary_rectangle); - editBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (boundsList.getSelectedIndex() != -1) { - BoundsObject selected = (BoundsObject) boundsList - .getSelectedValue(); - organizer.edit(selected.bounds, null); - } - } - }); - boundsButtonPanel.add(editBoundaryButton); - - ii = createImageIcon("remov_16x16.png"); - deleteBoundaryButton = new JButton(ii); - String delete_a_selected_boundary_rectangle = i18n.get( - ZoomLevelMakerFace.class, - "delete_a_selected_boundary_rectangle", - "Delete a selected boundary rectangle"); - deleteBoundaryButton - .setToolTipText(delete_a_selected_boundary_rectangle); - deleteBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (boundsList.getSelectedIndex() != -1) { - BoundsObject selected = (BoundsObject) boundsList - .getSelectedValue(); - boundaries.remove(selected.bounds); - boundsObjectList.remove(selected); - boundsList.repaint(); - - if (organizer.drawingTool.isActivated()) { - organizer.drawingTool - .deactivate(OMAction.DELETE_GRAPHIC_MASK); - } - - ((MapHandler) organizer.getBeanContext()) - .get(MapBean.class).repaint(); - } - } - }); - boundsButtonPanel.add(deleteBoundaryButton); - boundsPanel.add(boundsButtonPanel, BorderLayout.SOUTH); - c.weighty = .8f; - add(boundsPanel, c); - } - - protected void addIntroEntry(JPanel panel, JComponent left, - JComponent right, int y, Insets i) { - GridBagConstraints c = new GridBagConstraints(); - - c.gridx = 0; - c.gridy = y; - c.weightx = 0; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.WEST; - c.insets = i; - - panel.add(left, c); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - panel.add(Box.createHorizontalGlue(), c); - - c.gridx = 1; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.anchor = GridBagConstraints.EAST; - panel.add(right, c); - } - - public void updateZoomLevel(int zoomLevel) { - DecimalFormat df = new DecimalFormat("000,000"); - zfi.setZoomLevel(zoomLevel); - - zfi.setScale(new OSMMapTileCoordinateTransform() - .getScaleForZoom(zoomLevel)); - - int etc = zfi.getEdgeTileCount(); - - tileDimensions.setText(etc + " x " + etc); - - String scale = "1:" + df.format(zfi.getScale()); - - scaleButton.setText(scale); - String tooltip = i18n.get(ZoomLevelMakerFace.class, "set_map_scale_to", - I18n.TOOLTIP, "Set map scale to"); - scaleButton.setToolTipText(tooltip + " " + scale); - - Object obj = rangeLevelChoice.getValue(); - if (obj instanceof Number) { - int rangeVal = ((Number) obj).intValue(); - if (rangeVal > zoomLevel) { - rangeVal = zoomLevel; - rangeLevelChoice.setValue(new Integer(zoomLevel)); - zfi.setRange(rangeVal); - } - } - - } - - protected void enableBoundaryButtons(boolean setting) { - createBoundaryButton.setEnabled(setting); - - boolean somethingSelected = boundsList.getSelectedIndex() != -1; - - editBoundaryButton.setEnabled(setting && somethingSelected); - deleteBoundaryButton.setEnabled(setting && somethingSelected); - } - - /** - * Given a set of Layers, look at the internal list and make sure there are - * layer objects that match. Purges LayerObjects that don't represent - * layers, and adds LayerObjects as needed. Calls setLayers with - * LayerObjects. - * - * @param layers - */ - protected void setLayers(Layer[] layers) { - - List layerObjects = new ArrayList(); - - for (Layer layer : layers) { - boolean foundOne = false; - for (LayerObject lo : layerList) { - if (lo.getLayer().equals(layer)) { - foundOne = true; - layerObjects.add(lo); - break; - } - } - - if (!foundOne) { - layerObjects.add(new LayerObject(layer)); - } - } - - setLayers(layerObjects); - } - - /** - * Update the layer panel to have buttons for the layer objects. Doesn't do - * any checking, just adds them to the layerPanel, and adds the button that - * pushes this ZLIF's layer settings to all other layers. - * - * @param layerObjects - */ - protected void setLayers(List layerObjects) { - this.layerList = layerObjects; - - if (layerPanel == null) { - return; - } - - layerPanel.removeAll(); - GridBagConstraints c = new GridBagConstraints(); - c.gridx = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.anchor = GridBagConstraints.WEST; - - for (LayerObject lo : layerObjects) { - - String layerMarker = lo.getLayer().getPropertyPrefix(); - if (layerMarker != null) { - lo.setSelected(zfi.getLayers().contains(layerMarker)); - } - - layerPanel.add(lo, c); - } - - c.fill = GridBagConstraints.BOTH; - c.weighty = 1.0f; - layerPanel.add(Box.createGlue(), c); - } - - /** - * Given a list of LayerObjects, make the visibility of the internal layers - * match the list. - * - * @param layerObjects - */ - protected void matchObjects(List layerObjects) { - - for (LayerObject lo : layerList) { - for (LayerObject toMatch : layerObjects) { - Layer matchedLayer = toMatch.getLayer(); - if (lo.getLayer().equals(matchedLayer)) { - - boolean turnOn = toMatch.isSelected(); - String layerMarker = matchedLayer.getPropertyPrefix(); - - lo.setSelected(turnOn); - - if (turnOn) { - if (!zfi.getLayers().contains(layerMarker)) { - zfi.getLayers().add(layerMarker); - } - } else { - zfi.getLayers().remove(layerMarker); - } - } - } - - setInclude(!zfi.getLayers().isEmpty()); - } - } - - public void matchBounds(List bounds) { - boundsModel.clear(); - boundaries.clear(); - - for (BoundsObject bo : bounds) { - BoundsObject copy = bo.clone(); - boundsModel.addElement(copy); - boundaries.add(bo.bounds); - } - } - - /** - * Whether this ZLIF is the active tab in the MapTileMakerComponent. - * - * @return true if face is active - */ - protected boolean isActive() { - return active; - } - - /** - * Set this as the active ZLIF in MapTileMakerComponent. - * - * @param active - */ - protected void setActive(boolean active) { - this.active = active; - } - - /** - * Whether this ZoomLevel should be used in the tile creation or skipped. - * - * @return if zoom level should be included in tile creation. - */ - public boolean isInclude() { - return include; - } - - /** - * Set whether this ZoomLevel should be used in the tile creation. - * - * @param include - */ - public void setInclude(boolean include) { - this.include = include; - // includeButton.setSelected(include); - } - - ZoomLevelMaker getZoomLevelMaker() { - return zfi; - } - - void setZoomLevelMaker(ZoomLevelMaker zfi) { - this.zfi = zfi; - } - - /** - * Called from MapTileMakerComponent if this is the active ZLIF when the - * drawing tool completes, assigning the boundary to this ZLIF (or whatever - * action is provided). - * - * @param omg - * @param action - */ - public void handleBoundary(OMGraphic omg, OMAction action) { - boundaries.doAction(omg, action); - - boundsModel.clear(); - int count = 1; - for (OMGraphic omr : boundaries) { - if (omr instanceof OMRect) { - String bounding_rectangle = i18n.get(ZoomLevelMakerFace.class, - "bounding_rectangle", "Bounding Rectangle"); - boundsModel.addElement(new BoundsObject((OMRect) omr, - bounding_rectangle + " " + (count++))); - } - } - - } - - /** - * Called from the MapTileMakerComponent, so this ZLIF is ready to paint its - * boundaries if it is activated. - * - * @param proj - * Projection to use to render boundaries. - * @return true if boundaries can be generated for given projection - */ - protected boolean generate(Projection proj) { - if (boundaries != null) { - return boundaries.generate(proj); - } - return false; - } - - /** - * Called from the MapTileMakerComponent, when this is the active ZLIF so - * the current boundaries are painted on top of the map. - * - * @param graphics - */ - protected void paintBoundaries(Graphics graphics) { - if (boundaries != null) { - boundaries.render(graphics); - } - } - - /** - * Bounds list model for boundary JList. - * - * @author dietrick - */ - private final class BoundsListModel extends AbstractListModel { - private static final long serialVersionUID = 1L; - - public int getSize() { - return boundsObjectList.size(); - } - - public BoundsObject getElementAt(int index) { - return boundsObjectList.get(index); - } - - @SuppressWarnings("unused") - public void editElement(int index) { - fireContentsChanged(this, index, index); - } - - @SuppressWarnings("unused") - public void insertElement(BoundsObject obj, int index) { - boundsObjectList.add(index, obj); - fireIntervalAdded(this, index, index); - } - - public void addElement(BoundsObject obj) { - int index = getSize(); - boundsObjectList.add(obj); - fireIntervalAdded(this, index, index); - } - - @SuppressWarnings("unused") - public BoundsObject removeElementAt(int index) { - BoundsObject obj = boundsObjectList.remove(index); - fireIntervalRemoved(this, index, index); - return obj; - } - - public void clear() { - int size = boundsObjectList.size(); - boundsObjectList.clear(); - fireIntervalRemoved(this, 0, size); - } - } - - /** - * The list object used to represent a boundary. - * - * @author dietrick - */ - public class BoundsObject implements Cloneable { - protected OMRect bounds; - protected String name; - - public BoundsObject(OMRect rect, String displayName) { - bounds = rect; - name = displayName; - } - - public String toString() { - return name; - } - - public BoundsObject clone() { - OMRect copy = new OMRect(bounds.getNorthLat(), bounds.getWestLon(), - bounds.getSouthLat(), bounds.getEastLon(), - OMGraphic.LINETYPE_RHUMB); - DrawingAttributes atts = DrawingAttributes.getDefaultClone(); - atts.setFrom(bounds); - atts.setTo(copy); - return new BoundsObject(bounds, name); - } - } - - /** - * A component used to represent a layer/layer setting in the face. - * - * @author dietrick - */ - public class LayerObject extends JCheckBox { - private static final long serialVersionUID = 1L; - protected Layer layer; - - public LayerObject(Layer layer) { - super(layer.getName(), layer.isVisible()); - this.layer = layer; - addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String pp = getLayer().getPropertyPrefix(); - if (((JCheckBox) ae.getSource()).isSelected()) { - if (!zfi.getLayers().contains(pp)) { - zfi.getLayers().add(pp); - } - } else { - zfi.getLayers().remove(pp); - } - - if (active /* duh */&& organizer != null) { - organizer.shuffleLayers(ZoomLevelMakerFace.this); - setInclude(zfi.getLayers() != null - && !zfi.getLayers().isEmpty()); - } - } - }); - } - - Layer getLayer() { - return layer; - } - - public String toString() { - return layer.getName(); - } - } - - /** - * A class that listens for selections on the boundary list. - * - * @author dietrick - */ - private final class SelectionListener implements ListSelectionListener { - - public void valueChanged(ListSelectionEvent e) { - if (!e.getValueIsAdjusting()) { - boolean somethingSelected = boundsList.getSelectedIndex() != -1; - editBoundaryButton.setEnabled(somethingSelected); - deleteBoundaryButton.setEnabled(somethingSelected); - } - } - } - - /** - * A class that listens for double-clicks on the boundary list, launching an - * editor for that rectangle. - * - * @author dietrick - */ - private class ListMouseListener extends MouseAdapter { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - int index = boundsList.locationToIndex(e.getPoint()); - if (index != -1) { - BoundsObject selected = (BoundsObject) boundsList - .getSelectedValue(); - organizer.edit(selected.bounds, null); - } - } - } - } - - public ImageIcon createImageIcon(String path) { - URL imgURL = ZoomLevelMakerFace.class.getClassLoader().getResource( - "com/bbn/openmap/dataAccess/mapTile/" + path); - if (imgURL != null) { - return new ImageIcon(imgURL); - } else { - System.err.println("Couldn't find file: " + path); - return null; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/FeatureGeometryType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/FeatureGeometryType.java deleted file mode 100644 index 6d1279eb7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/FeatureGeometryType.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -public enum FeatureGeometryType { - - POINT("Point"), - MULTI_POINT("MultiPoint"), - LINEAR_RING("LinearRing"), - LINE_STRING("LineString"), - MULTI_LINE_STRING("MultiLineString"), - POLYGON("Polygon"), - MULTI_POLYGON("MultiPolygon"), - UNKNOWN("Unknown"); - - private String featureType; - - private FeatureGeometryType(String featureTypeName) { - this.featureType = featureTypeName; - } - - public static FeatureGeometryType get(String type) { - for (FeatureGeometryType fgt : FeatureGeometryType.values()) { - if (fgt.featureType.equalsIgnoreCase(type)) { - return fgt; - } - } - return UNKNOWN; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/MVTMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/MVTMapTileFactory.java deleted file mode 100644 index a35d15a9b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/MVTMapTileFactory.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The MVTMapTileFactory can fetch vector tile data from a URL. It can handle - * pbf data, too, just set compressed to false and change the rootDir - * appropriately. - * - *
- * 
- * mvtLayer.class=com.bbn.openmap.layer.image.MapTileLayer
- * mvtLayer.tileFactory=com.bbn.openmap.dataAccess.mapTile.mb.MVTMapTileFactory
- * mvtLayer.prettyName=MVT Server
- * mvtLayer.rootDir=http://sample_server/osm/water/{z}/{x}/{y}.mvt?api_key={api-key}
- * 
- * #optional - mbtiles and mvt files have compressed data, pbf data is not compressed.
- * mvtLayer.compressed=true
- * 
- */ - -public class MVTMapTileFactory extends VectorMapTileFactory { - - public MVTMapTileFactory() { - - } - - public String getFileExt() { - return ""; - } - - /** - * Fetch tile data. Uses the key as the path to the file. - * - * @param key - * the path to the tile built up from rootDir and the - * TilePathBuilder source location. - * @param x - * horizontal tile column - * @param y - * vertical tile row - * @param zoomLevel - * tile zoom level - * @return uncompressed tile data, ready for decoding - */ - public byte[] getTileData(Object key, int x, int y, int zoomLevel) throws Exception { - - String tilePath = (String) key; - - try { - java.net.URL url = new java.net.URL(tilePath); - java.net.HttpURLConnection urlc = (java.net.HttpURLConnection) url.openConnection(); - - if (getLogger().isLoggable(Level.FINER)) { - getLogger().finer("url content type: " + urlc.getContentType()); - } - - if (urlc == null || urlc.getContentType() == null) { - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine("unable to connect to (tile might be unavailable): " + tilePath); - } - - // text - } else if (urlc.getContentType().startsWith("text")) { - java.io.BufferedReader bin = new java.io.BufferedReader( - new java.io.InputStreamReader(urlc.getInputStream())); - String st; - StringBuffer message = new StringBuffer(); - while ((st = bin.readLine()) != null) { - message.append(st); - } - - // Debug.error(message.toString()); - // How about we toss the message out to the user - // instead? - getLogger().fine(message.toString()); - - // image - } else { - - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - - if (compressed) { - return inflate(out.toByteArray()); - } else { - return out.toByteArray(); - } - - } // end if image - } catch (java.net.MalformedURLException murle) { - getLogger().warning("URL \"" + tilePath + "\" is malformed."); - } catch (java.io.IOException ioe) { - getLogger().fine("Couldn't connect to " + tilePath + ", connection problem"); - } - - return null; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(MVTMapTileFactory.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/RasterMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/RasterMapTileFactory.java deleted file mode 100644 index 3c6523c1e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/RasterMapTileFactory.java +++ /dev/null @@ -1,169 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.image.BufferedImage; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.mapTile.MapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The RasterMapTileFactory is an extension to the StandardMapTileFactory that - * can read image tiles stored in a mbtiles file, which is the export format - * from the TileMill/MapBox Studio application. The mbtiles file is a sqlite - * database, so this factory requires the sqlitejdbc package be used to read - * those data files. You can find that package at - * http://www.zentus.com/sqlitejdbc. - * - * This component can be configured using properties: - *

- * - *

- * # Inherited from StandardMapTileFactory
- * rootDir=the jdbc driver/path string to use for the database file, "jdbc:sqlite:path to file"
- * cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- *
- * #optional:
- * # The class used to test for the existance of jdbc components.  Assumes sqlitejdbc, but the code fetching the tiles
- * # is pretty standard SQL - so you should be able to use any jdbc driver library.
- * testClass=org.sqlite.JDBC
- *
- * 
- * - * @author dietrick - */ -public class RasterMapTileFactory extends StandardMapTileFactory implements MapTileFactory, PropertyConsumer { - public final static String DEFAULT_TEST_CLASS = "org.sqlite.JDBC"; - public final static String TEST_CLASS_PROPERTY = "testClass"; - /** - * Test class to use for existence of JDBC drivers. - */ - protected String testClass = DEFAULT_TEST_CLASS; - protected boolean jdbcLoaded = false; - - public RasterMapTileFactory() { - this(null); - } - - public RasterMapTileFactory(String rootDir) { - this.rootDir = rootDir; - this.fileExt = ".png"; - verbose = logger.isLoggable(Level.FINE); - - try { - Class.forName(testClass); - jdbcLoaded = true; - } catch (Exception e) { - logger.warning("can't locate sqlite JDBC components"); - } - } - - /** - * Fetches a new tile from the database. - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - - if (!jdbcLoaded) { - return null; - } - - try { - Connection conn = DriverManager.getConnection(rootDir); - Statement stat = conn.createStatement(); - - // "select zoom_level, tile_column, tile_row, tile_data from map, - // images where map.tile_id = images.tile_id"; - StringBuilder statement = new StringBuilder("select tile_data from map, images where"); - statement.append(" zoom_level = ").append(zoomLevel); - statement.append(" and tile_column = ").append(x); - statement.append(" and tile_row = ").append(Math.pow(2, zoomLevel) - y - 1); - statement.append(" and map.tile_id = images.tile_id;"); - - ResultSet rs = stat.executeQuery(statement.toString()); - while (rs.next()) { - byte[] imageBytes = rs.getBytes("tile_data"); - - ImageIcon ii = new ImageIcon(imageBytes); - - BufferedImage bi = BufferedImageHelper.getBufferedImage(ii.getImage(), 0, 0, -1, -1); - - OMGraphic raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - - if (raster != null) { - return new CacheObject((String) key, raster); - } - - } - rs.close(); - conn.close(); - } catch (Exception e) { - logger.warning("something went wrong fetching image from database: " + e.getMessage()); - e.printStackTrace(); - } - - return null; - } - - public Properties getProperties(Properties getList) { - getList = super.getProperties(getList); - if (testClass != null && !testClass.equals(DEFAULT_TEST_CLASS)) { - getList.put(prefix + TEST_CLASS_PROPERTY, PropUtils.unnull(testClass)); - } - return getList; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, - TEST_CLASS_PROPERTY, "JDBC Availability Test Class", - "A class in the JDBC driver package to use to test for JDBC driver configuration (any class in package).", - null); - return list; - } - - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - testClass = setList.getProperty(prefix + TEST_CLASS_PROPERTY, testClass); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleDrawingAttributes.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleDrawingAttributes.java deleted file mode 100644 index 77ad1a47a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleDrawingAttributes.java +++ /dev/null @@ -1,888 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Paint; -import java.awt.Stroke; -import java.awt.geom.GeneralPath; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMShape; -import com.fasterxml.jackson.databind.JsonNode; - -public class StyleDrawingAttributes extends DrawingAttributes { - - private static final long serialVersionUID = 1L; - static String LAYOUT = "layout"; - static String PAINT = "paint"; - - final static Stroke DEFAULT_STROKE = new BasicStroke(1); - - final static StyleFunction DEFAULT_OPACITY = new StyleFunction(1.0); - final static StyleFunction BLACK = new StyleFunction(Color.black); - final static StyleFunction CLEAR = new StyleFunction(OMColor.clear); - - // LAYOUT - StyleFunction visible = null; - // PAINT - final StyleFunction renderers = new StyleFunction( - DrawingAttributes.getDefaultClone()); - - StyleDrawingAttributes refRenderer = null; - String layerID; - - JsonNode constants; - - static StyleDrawingAttributes EMPTY = new LINE(null, null); - - public static StyleDrawingAttributes getForType(JsonNode node, JsonNode constants) { - return get(StyleLayerType.getFromLayerNode(node), node, constants); - } - - /** - * We just need to grab any layout properties from the reference if one is - * provided. Each attributes type will pull out different layout properties, - * because each type has different layout properties. - * - * @param reference - * a StyleDrawingAttributes from a layer that is a refernce layer - * to our layer. - */ - void configureFromReference(StyleDrawingAttributes reference) { - this.refRenderer = reference; - /* - * This may stomp on any settings that were there. - */ - if (reference != null && visible == null) { - visible = reference.visible; - } - } - - public static StyleDrawingAttributes get(StyleLayerType slt, JsonNode node, JsonNode constants) { - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine("getting style for " + slt.name); - } - - switch (slt) { - case BACKGROUND: - return new StyleDrawingAttributes.BACKGROUND(node, constants); - case FILL: - return new StyleDrawingAttributes.FILL(node, constants); - case LINE: - return new StyleDrawingAttributes.LINE(node, constants); - case SYMBOL: - return new StyleDrawingAttributes.SYMBOL(node, constants); - case RASTER: - return new StyleDrawingAttributes.RASTER(node, constants); - case CIRCLE: - return new StyleDrawingAttributes.CIRCLE(node, constants); - default: - return null; - } - } - - private StyleDrawingAttributes(JsonNode node, JsonNode constants) { - - this.constants = constants; - - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.add(zoomLevel, DrawingAttributes.getDefaultClone()); - } - - if (node != null) { - JsonNode layout = node.get(LAYOUT); - if (layout != null) { - configureLayout(layout); - } - - JsonNode paint = node.get(PAINT); - if (paint != null) { - configurePaint(paint); - } - } - } - - OMGraphic getOMGraphic(GeneralPath gp, int zoomLevel) { - OMShape oms = new OMShape.PROJECTED(gp); - renderers.get(zoomLevel).setTo(oms); - // oms.setVisible(visible.get(zoomLevel).isVisible()); - return oms; - } - - /** - * Called when constructed, layout properties will be overwritten by - * reference layer values if one is provided. - * - * @param layout - */ - void configureLayout(JsonNode layout) { - visible = StyleVisibility.getFunction(layout); - } - - void configurePaint(JsonNode node) { - // Noop, each subclass does it differently. Should this be abstract? - } - - void setLinePaint(StyleFunction linePaints) { - if (linePaints != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setLinePaint(linePaints.get(zoomLevel)); - } - } - } - - void setLinePaint(StyleDrawingAttributes ref) { - if (ref != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setLinePaint(ref.getRenderer(zoomLevel).getLinePaint()); - } - } - } - - void setFillPaint(StyleFunction fillPaints) { - if (fillPaints != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setFillPaint(fillPaints.get(zoomLevel)); - } - } - } - - void setFillPaint(StyleDrawingAttributes ref) { - if (ref != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setFillPaint(ref.getRenderer(zoomLevel).getFillPaint()); - } - } - } - - void setStroke(StyleFunction strokes) { - if (strokes != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setStroke(strokes.get(zoomLevel)); - } - } - } - - void setStroke(StyleDrawingAttributes ref) { - if (ref != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - renderers.get(zoomLevel).setStroke(ref.getRenderer(zoomLevel).getStroke()); - } - } - } - - void setMatting(boolean isMatted, StyleFunction mattingPaints) { - if (mattingPaints != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - DrawingAttributes da = renderers.get(zoomLevel); - da.setMatted(isMatted); - da.setMattingPaint(mattingPaints.get(zoomLevel)); - } - } - } - - void setMatting(StyleDrawingAttributes ref) { - if (ref != null) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - - DrawingAttributes da1 = renderers.get(zoomLevel); - DrawingAttributes da2 = ref.getRenderer(zoomLevel); - - da1.setMatted(da2.isMatted()); - da1.setMattingPaint(da2.getMattingPaint()); - - renderers.get(zoomLevel).setStroke(ref.getRenderer(zoomLevel).getStroke()); - } - } - } - - DrawingAttributes getRenderer(int zoomLevel) { - return renderers.get(zoomLevel); - } - - boolean isVisible(int zoomLevel) { - return visible == null || visible.get(zoomLevel).isVisible(); - } - - public static class BACKGROUND extends StyleDrawingAttributes { - private static final long serialVersionUID = 1L; - // PAINT - /** - * Optional color. Defaults to #000000. Disabled by background-pattern. - * The color with which the background will be drawn. - */ - static String BACKGROUND_COLOR = "background-color"; - /** - * Optional string. Name of image in sprite to use for drawing an image - * background. For seamless patterns, image width and height must be a - * factor of two (2, 4, 8, …, 512). - */ - static String BACKGROUND_PATTERN = "background-pattern"; - /** - * Optional number. Defaults to 1. The opacity at which the background - * will be drawn. - */ - static String BACKGROUND_OPACITY = "background-opacity"; - - public BACKGROUND(JsonNode node, JsonNode constants) { - super(node, constants); - } - - void configurePaint(JsonNode paint) { - StyleFunction opacity = StyleFunction.getDoubleFunction(paint.get(BACKGROUND_OPACITY), 1.0, constants); - StyleFunction backgroundPaints = StyleFunction.getPaintFunction(paint.get(BACKGROUND_COLOR), opacity, BLACK, constants); - - setFillPaint(backgroundPaints); - setLinePaint(CLEAR); - - } - - } - - public static class FILL extends StyleDrawingAttributes { - private static final long serialVersionUID = 1L; - // PAINT - /** - * Optional boolean. Defaults to true. Whether or not the fill should be - * antialiased. - */ - static String FILL_ANTIALIAS = "fill-antialias"; - /** - * Optional number. Defaults to 1. The opacity given to the fill color. - */ - static String FILL_OPACITY = "fill-opacity"; - /** - * Optional color. Defaults to #000000. Disabled by fill-pattern. The - * color of the fill. - */ - static String FILL_COLOR = "fill-color"; - /** - * Optional color. Disabled by fill-pattern. Requires fill-antialias = - * true. The outline color of the fill. Matches the value of fill-color - * if unspecified. - */ - static String FILL_OUTLINE_COLOR = "fill-outline-color"; - /** - * Optional array. Units in pixels. Defaults to 0,0. The geometry’s - * offset. Values are [x, y] where negatives indicate left and up, - * respectively. - */ - static String FILL_TRANSLATE = "fill-translate"; - /** - * Optional enum. One of map, viewport. Defaults to map. Requires - * fill-translate. Control whether the translation is relative to the - * map (north) or viewport (screen) - */ - static String FILL_TRANSLATE_ANCHOR = "fill-translate-anchor"; - /** - * Optional string. Name of image in sprite to use for drawing image - * fills. For seamless patterns, image width and height must be a factor - * of two (2, 4, 8, …, 512). - */ - static String FILL_PATTERN = "fill-pattern"; - - public FILL(JsonNode node, JsonNode constants) { - super(node, constants); - } - - void configurePaint(JsonNode paint) { - StyleFunction opacity = StyleFunction.getDoubleFunction(paint.get(FILL_OPACITY), 1.0, constants); - StyleFunction fillPaints = StyleFunction.getPaintFunction(paint.get(FILL_COLOR), opacity, BLACK, constants); - - StyleFunction outlinePaints = CLEAR; - if (StyleNode.getAsBoolean(paint, FILL_ANTIALIAS, true)) { - outlinePaints = StyleFunction.getPaintFunction(paint.get(FILL_OUTLINE_COLOR), opacity, outlinePaints, constants); - } - - setFillPaint(refRenderer); - setLinePaint(refRenderer); - - setFillPaint(fillPaints); - setLinePaint(outlinePaints); - } - - OMGraphic getOMGraphic(GeneralPath gp, int zoomLevel) { - OMShape oms = new OMShape.PROJECTED(gp); - renderers.get(zoomLevel).setTo(oms); - // oms.setVisible(visible.get(zoomLevel).isVisible()); - return oms; - } - } - - public static class LINE extends StyleDrawingAttributes { - - private static final long serialVersionUID = 1L; - // LAYOUT - /** - * Optional enum. One of butt, round, square. Defaults to butt. The - * display of line endings. - */ - static String LINE_CAP = "line-cap"; - /** - * Optional enum. One of bevel, round, miter. Defaults to miter. The - * display of lines when joining. - */ - static String LINE_JOIN = "line-join"; - /** - * Optional number. Defaults to 2. Requires line-join = miter. Used to - * automatically convert miter joins to bevel joins for sharp angles. - */ - static String LINE_MITER_LIMIT = "line-miter-limit"; - /** - * Optional number. Defaults to 1.05. Requires line-join = round. Used - * to automatically convert round joins to miter joins for shallow - * angles. - */ - static String LINE_ROUND_LIMIT = "line-round-limit"; - // PAINT - /** - * Optional number. Defaults to 1. The opacity at which the line will be - * drawn. - */ - static String LINE_OPACITY = "line-opacity"; - /** - * Optional color. Defaults to #000000. Disabled by line-pattern. The - * color with which the line will be drawn. - */ - static String LINE_COLOR = "line-color"; - /** - * Optional array. Units in pixels. Defaults to 0,0. The geometry’s - * offset. Values are [x, y] where negatives indicate left and up, - * respectively. - */ - static String LINE_TRANSLATE = "line-translate"; - /** - * Optional enum. One of map, viewport. Defaults to map. Requires - * line-translate. Control whether the translation is relative to the - * map (north) or viewport (screen) - */ - static String LINE_TRANSLATE_ANCHOR = "line-translate-anchor"; - /** - * Optional number. Units in pixels. Defaults to 1. Stroke thickness. - */ - static String LINE_WIDTH = "line-width"; - /** - * Optional number. Units in pixels. Defaults to 0. Draws a line casing - * outside of a line’s actual path. Value indicates the width of the - * inner gap. - */ - static String LINE_GAP_WIDTH = "line-gap-width"; - /** - * Optional number. Units in pixels. Defaults to 0. The line’s offset - * perpendicular to its direction. Values may be positive or negative, - * where positive indicates “rightwards†(if you were moving in the - * direction of the line) and negative indicates “leftwards.†- */ - static String LINE_OFFSET = "line-offset"; - /** - * Optional number. Units in pixels. Defaults to 0. Blur applied to the - * line, in pixels. - */ - static String LINE_BLUR = "line-blur"; - /** - * Optional array. Units in line widths. Disabled by line-pattern. - * Specifies the lengths of the alternating dashes and gaps that form - * the dash pattern. The lengths are later scaled by the line width. To - * convert a dash length to pixels, multiply the length by the current - * line width. - */ - static String LINE_DASHARRAY = "line-dasharray"; - /** - * Optional string. Name of image in sprite to use for drawing image - * lines. For seamless patterns, image width must be a factor of two (2, - * 4, 8, …, 512). - */ - static String LINE_PATTERN = "line-pattern"; - - public LINE(JsonNode node, JsonNode constants) { - super(node, constants); - } - - void configurePaint(JsonNode paint) { - StyleFunction opacity = StyleFunction.getDoubleFunction(paint.get(LINE_OPACITY), 1.0, constants); - StyleFunction linePaints = StyleFunction.getPaintFunction(paint.get(LINE_COLOR), opacity, BLACK, constants); - - configureStroke(paint); - - setLinePaint(refRenderer); - setLinePaint(linePaints); - } - - void configureStroke(JsonNode paint) { - - StyleFunction lineWidths = StyleFunction.getDoubleFunction(paint.get(LINE_WIDTH), 1.0, constants); - StyleFunction lineGaps = StyleFunction.getDoubleFunction(paint.get(LINE_GAP_WIDTH), 0.0, constants); - StyleFunction dashArrays = StyleFunction.getFloatArrayFunction(paint.get(LINE_DASHARRAY), constants); - StyleFunction lineCaps = StyleLineCap.getFunction(paint.get(LINE_CAP)); - StyleFunction lineJoins = StyleLineJoin.getFunction(paint.get(LINE_JOIN)); - - StyleFunction strokes = new StyleFunction(DEFAULT_STROKE); - - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - float lineWidth = safeLineWidth(lineWidths, zoomLevel); - int lineCap = lineCaps.get(zoomLevel).val; - int lineJoin = lineJoins.get(zoomLevel).val; - float[] dashArray = safeDashArray(dashArrays, zoomLevel); - - Stroke stroke = new BasicStroke(lineWidth, lineCap, lineJoin, 2, dashArray, 0f); - - // ref renderer might hold cap, join, miter-limit, round-limit. - // All other aspects of stroke are in feature definition. - - /* - * if (refRenderer != null) { Stroke refStroke = - * refRenderer.getRenderer(zoomLevel).getStroke(); if (refStroke - * != DEFAULT_STROKE) { - * - * } } - */ - - renderers.get(zoomLevel).setStroke(stroke); - } - } - - float[] safeDashArray(StyleFunction dashArrays, int zoomLevel) { - float[] dashArray = null; - if (dashArrays != null) { - float[] da = dashArrays.get(zoomLevel); - float sum = 0; - for (float f : da) { - sum += f; - } - if (sum > 0) { - dashArray = da; - } - } - return dashArray; - } - - float safeLineWidth(StyleFunction lineWidths, int zoomLevel) { - float lineWidth = lineWidths.get(zoomLevel).floatValue(); - if (lineWidth < 0f) { - lineWidth = 0f; - } - return lineWidth; - } - - /** - */ - void configureFromReference(StyleDrawingAttributes reference) { - super.configureFromReference(reference); - - /** - * if (reference instanceof LINE) { LINE lineRef = (LINE) reference; - * if (lineRef.lineGapFunction != null) { - * setMattingPaint(getLinePaint()); - * setLinePaint(lineRef.getLinePaint()); setMatted(true); } } - */ - } - } - - public static class SYMBOL extends StyleDrawingAttributes { - private static final long serialVersionUID = 1L; - // LAYOUT - /** - * Optional enum. One of point, line. Defaults to point. Label placement - * relative to its geometry. line can only be used on LineStrings and - * Polygons. - */ - static String SYMBOL_PLACEMENT = "symbol-placement"; - /** - * Optional number. Units in pixels. Defaults to 250. Requires - * symbol-placement = line. Distance between two symbol anchors. - */ - static String SYMBOL_SPACING = "symbol-spacing"; - /** - * Optional boolean. Defaults to false. If true, the symbols will )not - * cross tile edges to avoid mutual collisions. Recommended in layers - * that don’t have enough padding in the vector tile to prevent - * collisions, or if it is a point symbol layer placed after a line - * symbol layer. - */ - static String SYMBOL_AVOID_EDGES = "symbol-avoid-edges"; - /** - * Optional boolean. Defaults to false. Requires icon-image. If true, - * the icon will be visible even if it collides with other previously - * drawn symbols. - */ - static String ICON_ALLOW_OVERLAP = "icon-allow-overlap"; - /** - * Optional boolean. Defaults to false. Requires icon-image. If true, - * other symbols can be visible even if they collide with the icon. - */ - static String ICON_IGNORE_PLACEMENT = "icon-ignore-placement"; - /** - * Optional boolean. Defaults to false. Requires icon-image. Requires - * text-field. If true, text will display without their corresponding - * icons when the icon collides with other symbols and the text does - * not. - */ - static String ICON_OPTIONAL = "icon-optional"; - /** - * Optional enum. One of map, viewport. Defaults to viewport. Requires - * icon-image. Orientation of icon when map is rotated. - */ - static String ICON_ROATION_ALIGNMENT = "icon-rotation-alignment"; - /** - * Optional number. Defaults to 1. Requires icon-image. Scale factor for - * icon. 1 is original size, 3 triples the size. - */ - static String ICON_SIZE = "icon-size"; - /** - * Optional string. A string with {tokens} replaced, referencing the - * data property to pull from. - */ - static String ICON_IMAGE = "icon-image"; - /** - * Optional number. Units in degrees. Defaults to 0. Requires - * icon-image. Rotates the icon clockwise. - */ - static String ICON_ROTATE = "icon-rotate"; - /** - * Optional number. Units in pixels. Defaults to 2. Requires icon-image. - * Size of the additional area around the icon bounding box used for - * detecting symbol collisions. - */ - static String ICON_PADDING = "icon-padding"; - /** - * Optional boolean. Defaults to false. Requires icon-image. Requires - * icon-rotation-alignment = map. Requires symbol-placement = line. If - * true, the icon may be flipped to prevent it from being rendered - * upside-down. - */ - static String ICON_KEEP_UPRIGHT = "icon-keep-upright"; - /** - * Optional array. Defaults to 0,0. Requires icon-image. Offset distance - * of icon from its anchor. Positive values indicate right and down, - * while negative values indicate left and up. - */ - static String ICON_OFFSET = "icon-offset"; - /** - * Optional enum. One of map, viewport. Defaults to viewport. Requires - * text-field. Orientation of text when map is rotated. - */ - static String TEXT_ROTATION_ALIGNMENT = "text-rotation-alignment"; - /** - * Optional string. Value to use for a text label. Feature properties - * are specified using tokens like {field_name}. - */ - static String TEXT_FIELD = "text-field"; - /** - * Optional array. Defaults to Open Sans Regular,Arial Unicode MS - * Regular. Requires text-field. Font stack to use for displaying text. - */ - static String TEXT_FONT = "text-font"; - /** - * Optional number. Units in pixels. Defaults to 16. Requires - * text-field. Font size. - */ - static String TEXT_SIZE = "text-size"; - /** - * Optional number. Units in em. Defaults to 10. Requires text-field. - * The maximum line width for text wrapping. - */ - static String TEXT_MAX_WIDTH = "text-max-width"; - /** - * Optional number. Units in em. Defaults to 1.2. Requires text-field. - * Text leading value for multi-line text. - */ - static String TEXT_LINE_HEIGHT = "text-line-height"; - /** - * Optional number. Units in em. Defaults to 0. Requires text-field. - * Text tracking amount. - */ - static String TEXT_LETTER_SPACING = "text-letter-spacing"; - /** - * Optional enum. One of left, center, right. Defaults to center. - * Requires text-field. Text justification options. - */ - static String TEXT_JUSTIFY = "text-justify"; - /** - * Optional enum. One of center, left, right, top, bottom, top-left, - * top-right, bottom-left, bottom-right. Defaults to center. Requires - * text-field. Part of the text placed closest to the anchor. - */ - static String TEXT_ANCHOR = "text-anchor"; - /** - * Optional number. Units in degrees. Defaults to 45. Requires - * text-field. Requires symbol-placement = line. Maximum angle change - * between adjacent characters. - */ - static String TEXT_MAX_ANGLE = "text-max-angle"; - /** - * Optional number. Units in degrees. Defaults to 0. Requires - * text-field. Rotates the text clockwise. - */ - static String TEXT_ROTATE = "text-rotate"; - /** - * Optional number. Units in pixels. Defaults to 2. Requires text-field. - * Size of the additional area around the text bounding box used for - * detecting symbol collisions. - */ - static String TEXT_PADDING = "text-padding"; - /** - * Optional boolean. Defaults to true. Requires text-field. Requires - * text-rotation-alignment = map. Requires symbol-placement = line. If - * true, the text may be flipped vertically to prevent it from being - * rendered upside-down. - */ - static String TEXT_KEEP_UPRIGHT = "text-keep-upright"; - /** - * Optional enum. One of none, uppercase, lowercase. Defaults to none. - * Requires text-field. Specifies how to capitalize text, similar to the - * CSS text-transform property. - */ - static String TEXT_TRANSFORM = "text-transform"; - /** - * Optional array. Units in ems. Defaults to 0,0. Requires text-field. - * Offset distance of text from its anchor. Positive values indicate - * right and down, while negative values indicate left and up. - */ - static String TEXT_OFFSET = "text-offset"; - /** - * Optional boolean. Defaults to false. Requires text-field. If true, - * the text will be visible even if it collides with other previously - * drawn symbols. - */ - static String TEXT_ALLOW_OVERLAP = "text-allow-overlap"; - /** - * Optional boolean. Defaults to false. Requires text-field. If true, - * other symbols can be visible even if they collide with the text. - */ - static String TEXT_IGNORE_PLACEMENT = "text-ignore-placement"; - /** - * Optional boolean. Defaults to false. Requires text-field. Requires - * icon-image. If true, icons will display without their corresponding - * text when the text collides with other symbols and the icon does not. - */ - static String TEXT_OPTIONAL = "text-optional"; - // PAINT - /** - * Optional number. Defaults to 1. Requires icon-image. The opacity at - * which the icon will be drawn. - */ - static String ICON_OPACITY = "icon-opacity"; - /** - * Optional color. Defaults to #000000. Requires icon-image. The color - * of the icon. This can only be used with sdf icons. - */ - static String ICON_COLOR = "icon-color"; - /** - * Optional color. Defaults to rgba(0, 0, 0, 0). Requires icon-image. - * The color of the icon’s halo. Icon halos can only be used with sdf - * icons. - */ - static String ICON_HALO_COLOR = "icon-halo-color"; - /** - * Optional number. Units in pixels. Defaults to 0. Requires icon-image. - * Distance of halo to the icon outline. - */ - static String ICON_HALO_WIDTH = "icon-halo-width"; - /** - * Optional number. Units in pixels. Defaults to 0. Requires icon-image. - * Fade out the halo towards the outside. - */ - static String ICON_HALO_BLUR = "icon-halo-blur"; - /** - * Optional array. Units in pixels. Defaults to 0,0. Requires - * icon-image. Distance that the icon’s anchor is moved from its - * original placement. Positive values indicate right and down, while - * negative values indicate left and up. - */ - static String ICON_TRANSLATE = "icon-translate"; - /** - * Optional enum. One of map, viewport. Defaults to map. Requires - * icon-image. Requires icon-translate. Control whether the translation - * is relative to the map (north) or viewport (screen). - */ - static String ICON_TRANSLATE_ANCHOR = "icon-translate-anchor"; - /** - * Optional number. Defaults to 1. Requires text-field. The opacity at - * which the text will be drawn. - */ - static String TEXT_OPACITY = "text-opacity"; - /** - * Optional color. Defaults to #000000. Requires text-field. The color - * with which the text will be drawn. - */ - static String TEXT_COLOR = "text-color"; - /** - * Optional color. Defaults to rgba(0, 0, 0, 0). Requires text-field. - * The color of the text’s halo, which helps it stand out from - * backgrounds. - */ - static String TEXT_HALO_COLOR = "text-halo-color"; - /** - * Optional number. Units in pixels. Defaults to 0. Requires text-field. - * Distance of halo to the font outline. Max text halo width is 1/4 of - * the font-size. - */ - static String TEXT_HALO_WIDTH = "text-halo-width"; - /** - * Optional number. Units in pixels. Defaults to 0. Requires text-field. - * The halo’s fadeout distance towards the outside. - */ - static String TEXT_HALO_BLUR = "text-halo-blur"; - /** - * Optional array. Units in pixels. Defaults to 0,0. Requires - * text-field. Distance that the text’s anchor is moved from its - * original placement. Positive values indicate right and down, while - * negative values indicate left and up. - */ - static String TEXT_TRANSLATE = "text-translate"; - /** - * Optional enum. One of map, viewport. Defaults to map. Requires - * text-field. Requires text-translate. Control whether the translation - * is relative to the map (north) or viewport (screen). - */ - static String TEXT_TRANSLATE_ANCHOR = "text-translate-anchor"; - - public SYMBOL(JsonNode node, JsonNode constants) { - super(node, constants); - visible = null; - } - - boolean isVisible(int zoomLevel) { - return false; - } - } - - public static class RASTER extends StyleDrawingAttributes { - private static final long serialVersionUID = 1L; - // PAINT - /** - * Optional number. Defaults to 1. The opacity at which the image will - * be drawn. - */ - static String RASTER_OPACITY = "raster-opacity"; - /** - * Optional number. Units in degrees. Defaults to 0. Rotates hues around - * the color wheel. - */ - static String RASTER_HUE_ROTATE = "raster-hue-rotate"; - /** - * Optional number. Defaults to 0. Increase or reduce the brightness of - * the image. The value is the minimum brightness. - */ - static String RASTER_BRIGHTNESS_MIN = "raster-brightness-min"; - /** - * Optional number. Defaults to 1. Increase or reduce the brightness of - * the image. The value is the maximum brightness. - */ - static String RASTER_BRIGHTNESS_MAX = "raster-brightness-max"; - /** - * Optional number. Defaults to 0. Increase or reduce the saturation of - * the image. - */ - static String RASTER_SATURATION = "raster-saturation"; - /** - * Optional number. Defaults to 0. Increase or reduce the contrast of - * the image. - */ - static String RASTER_CONTRAST = "raster-contrast"; - /** - * Optional number. Units in milliseconds. Defaults to 300. Fade - * duration when a new tile is added. - */ - static String RASTER_FADE_DURATION = "raster-fade-duration"; - - public RASTER(JsonNode node, JsonNode constants) { - super(node, constants); - visible = null; - } - - boolean isVisible(int zoomLevel) { - return false; - } - } - - public static class CIRCLE extends StyleDrawingAttributes { - private static final long serialVersionUID = 1L; - // PAINT - /** Optional number. Units in pixels. Defaults to 5. Circle radius. */ - static String CIRCLE_RADIUS = "circle-radius"; - /** Optional color. Defaults to #000000. The color of the circle. */ - static String CIRCLE_COLOR = "circle-color"; - /** - * Optional number. Defaults to 0. Amount to blur the circle. 1 blurs - * the circle such that only the centerpoint is full opacity. - */ - static String CIRCLE_BLUR = "circle-blur"; - /** - * Optional number. Defaults to 1. The opacity at which the circle will - * be drawn. - */ - static String CIRCLE_OPACITY = "circle-opacity"; - /** - * Optional array. Units in pixels. Defaults to 0,0. The geometry’s - * offset. Values are [x, y] where negatives indicate left and up, - * respectively. - */ - static String CIRCLE_TRANSLATE = "circle-translate"; - /** - * Optional enum. One of map, viewport. Defaults to map. Requires - * circle-translate. Control whether the translation is relative to the - * map (north) or viewport (screen) - */ - static String CIRCLE_TRANSLATE_ANCHOR = "circle-translate-anchor"; - - public CIRCLE(JsonNode node, JsonNode constants) { - super(node, constants); - visible = null; - } - - void configurePaint(JsonNode paint) { - StyleFunction opacity = StyleFunction.getDoubleFunction(paint.get(CIRCLE_OPACITY), 1.0, constants); - StyleFunction circlePaints = StyleFunction.getPaintFunction(paint.get(CIRCLE_COLOR), opacity, BLACK, constants); - StyleFunction radius = StyleFunction.getDoubleFunction(paint.get(CIRCLE_RADIUS), 5.0, constants); - - setFillPaint(circlePaints); - setLinePaint(CLEAR); - setCircleStuff(true, radius); - - } - - void setCircleStuff(boolean pointOval, StyleFunction radius) { - for (int zoomLevel = StyleFunction.MIN_ZOOM_LEVEL; zoomLevel < StyleFunction.NUM_ZOOM_LEVELS; zoomLevel++) { - DrawingAttributes da = renderers.get(zoomLevel); - da.setPointOval(pointOval); - da.setPointRadius(radius.get(zoomLevel).intValue()); - } - } - - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleDrawingAttributes.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilter.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilter.java deleted file mode 100644 index 290fd564a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilter.java +++ /dev/null @@ -1,214 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.fasterxml.jackson.databind.JsonNode; - -import no.ecc.vectortile.VectorTileDecoder.Feature; - -public class StyleFilter { - /** - * Optional filter. A expression specifying conditions on source features. - * Only features that match the filter are displayed. - */ - static String FILTER = "filter"; - static boolean fineLogging = getLogger().isLoggable(Level.FINE); - - /** - * Filter key to check feature geometry type. - */ - static String SPECIAL_CLASS_KEY = "$type"; - - StyleFilterOperation op; - - StyleFilter(StyleFilterOperation op) { - this.op = op; - } - - public static StyleFilter getForLayerNode(JsonNode layerNode) { - JsonNode filterNode = layerNode.get(FILTER); - if (filterNode != null) { - return getForFilterNode(filterNode); - } - return new StyleFilter(StyleFilterOperation.NOTHING); - } - - public static StyleFilter getForFilterNode(JsonNode filterNode) { - JsonNode opNode = filterNode.get(0); - if (fineLogging) { - getLogger().fine("eval " + filterNode + ", have first: " + opNode); - } - StyleFilterOperation op = StyleFilterOperation.getForFilterNode(opNode); - - switch (op) { - case EQUALS: - case NOT_EQUALS: - case GREATER_THAN: - case GREATER_THAN_EQUALS: - case LESS_THAN: - case LESS_THAN_EQUALS: - return new StyleFilter.KEY_VALUE(op, filterNode); - case IN: - case NOT_IN: - return new StyleFilter.KEY_LIST(op, filterNode); - case ALL: - case ANY: - case NONE: - return new StyleFilter.COMPOUND(op, filterNode); - default: - } - return new StyleFilter(StyleFilterOperation.NOTHING); - } - - public boolean passes(Feature feature) { - return true; - } - - public static class KEY_VALUE extends StyleFilter { - String key; - Object value; - - public KEY_VALUE(StyleFilterOperation op, JsonNode filterNode) { - super(op); - key = filterNode.get(1).asText(); - - JsonNode valNode = filterNode.get(2); - if (valNode.isBoolean()) { - value = valNode.asBoolean(); - } else if (valNode.isInt()) { - value = valNode.asInt(); - } else if (valNode.isDouble() || valNode.isNumber()) { - value = valNode.asDouble(); - } else { - value = valNode.asText(); - } - } - - public boolean passes(Feature feature) { - Object featureVal; - if (key.equals(SPECIAL_CLASS_KEY)) { - featureVal = feature.getGeometry().getGeometryType(); - } else { - featureVal = feature.getAttributes().get(key); - } - - // If one side or the other doesn't exist, we're going to fail the test - boolean ret = false; - if (featureVal != null && value != null) { - ret = op.passes(featureVal, value); - } - - if (fineLogging) { - getLogger().fine("checking " + featureVal + " vs " + value + ":" + ret); - } - - return ret; - } - - } - - public static class KEY_LIST extends StyleFilter { - String key; - HashSet values; - - public KEY_LIST(StyleFilterOperation op, JsonNode filterNode) { - super(op); - - values = new HashSet(); - - if (filterNode.isArray()) { - Iterator listStuff = filterNode.elements(); - // The original op is the first thing, skip it. - listStuff.next(); - key = listStuff.next().asText(); - while (listStuff.hasNext()) { - String listThing = listStuff.next().asText(); - if (fineLogging) { - getLogger().fine("KEYLIST: adding " + listThing); - } - values.add(listThing); - } - } - } - - public boolean passes(Feature feature) { - Object featureVal; - if (key.equals(SPECIAL_CLASS_KEY)) { - featureVal = feature.getGeometry().getGeometryType(); - } else { - featureVal = feature.getAttributes().get(key); - } - - boolean ret = op.passes(featureVal, values); - - if (fineLogging) { - getLogger().fine("checking " + featureVal + " in " + values + ": " + ret); - } - - return ret; - } - } - - public static class COMPOUND extends StyleFilter { - Collection filters; - - public COMPOUND(StyleFilterOperation op, JsonNode filterNode) { - super(op); - if (fineLogging) { - getLogger().fine("COMPOUND " + op + ", " + filterNode); - } - filters = new ArrayList(); - - if (filterNode.isArray()) { - Iterator subFilters = filterNode.elements(); - // The original op is the first thing, skip it. - subFilters.next(); - while (subFilters.hasNext()) { - JsonNode subFilter = subFilters.next(); - if (fineLogging) { - getLogger().fine(subFilter.toString()); - } - filters.add(getForFilterNode(subFilter)); - } - } - } - - public boolean passes(Feature feature) { - return op.passes(feature, filters); - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleFilter.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilterOperation.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilterOperation.java deleted file mode 100644 index 68af4df63..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFilterOperation.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.Collection; -import java.util.logging.Logger; - -import com.fasterxml.jackson.databind.JsonNode; - -import no.ecc.vectortile.VectorTileDecoder.Feature; - -public enum StyleFilterOperation { - - EQUALS("==") { - public boolean passes(Object ths, Object tht) { - return (ths == null && tht == null) || (ths != null && ths.equals(tht)); - } - }, - NOT_EQUALS("!=") { - public boolean passes(Object ths, Object tht) { - return (ths == null && tht != null) || (ths != null && tht == null) || (!ths.equals(tht)); - } - }, - GREATER_THAN(">") { - public boolean passes(Object number1, Object number2) { - try { - return ((Number) number1).doubleValue() > ((Number) number2).doubleValue(); - } catch (ClassCastException cce) { - getLogger().warning("Non-numerical classes used as input"); - return false; - } - } - }, - GREATER_THAN_EQUALS(">=") { - public boolean passes(Object ths, Object tht) { - return GREATER_THAN.passes(ths, tht) || EQUALS.passes(ths, tht); - } - }, - LESS_THAN("<") { - public boolean passes(Object number1, Object number2) { - try { - return ((Number) number1).doubleValue() < ((Number) number2).doubleValue(); - } catch (ClassCastException cce) { - getLogger().warning("Non-numerical classes used as input"); - return false; - } - } - }, - LESS_THAN_EQUALS("<=") { - public boolean passes(Object ths, Object tht) { - return LESS_THAN.passes(ths, tht) || EQUALS.passes(ths, tht); - } - }, - IN("in") { - public boolean passes(Object ths, Object tht) { - try { - return tht != null && ((Collection) tht).contains(ths); - } catch (ClassCastException cce) { - getLogger().warning("Non-collection classes used as input"); - return false; - } - } - }, - NOT_IN("!in") { - public boolean passes(Object ths, Object tht) { - try { - return tht == null || (ths != null && !((Collection) tht).contains(ths)); - } catch (ClassCastException cce) { - getLogger().warning("Non-collection classes used as input"); - return true; - } - } - }, - ALL("all") { - public boolean passes(Object feature, Object collectionOfStyleFeatures) { - try { - boolean pass = true; - Collection lsf = (Collection) collectionOfStyleFeatures; - for (StyleFilter op : lsf) { - pass &= op.passes(((Feature) feature)); - } - return pass; - } catch (ClassCastException cce) { - getLogger().warning("Non-collection classes used as input"); - } catch (NullPointerException npe) { - getLogger().warning("trying to test null feature: " + feature); - } - return false; - } - }, - ANY("any") { - public boolean passes(Object feature, Object collectionOfStyleFeatures) { - try { - boolean pass = false; - Collection lsf = (Collection) collectionOfStyleFeatures; - for (StyleFilter op : lsf) { - pass |= op.passes(((Feature) feature)); - } - return pass; - } catch (ClassCastException cce) { - getLogger().warning("Non-collection classes used as input"); - return false; - } - } - }, - NONE("none") { - public boolean passes(Object feature, Object listOfStyleFeatures) { - return !ANY.passes(feature, listOfStyleFeatures); - } - }, - NOTHING("") { - public boolean passes(Object ths, Object tht) { - return true; - } - }; - - private String name; - - private StyleFilterOperation(String name) { - this.name = name; - } - - protected static StyleFilterOperation getForFilterNode(JsonNode filterNode) { - return getForOpString(filterNode.asText()); - } - - protected static StyleFilterOperation getForOpString(String nm) { - for (StyleFilterOperation st : StyleFilterOperation.values()) { - if (st.name.equalsIgnoreCase(nm)) { - return st; - } - } - return NOTHING; - } - - public String getName() { - return name; - } - - protected abstract boolean passes(Object ths, Object tht); - - /* - * ["==",key,value]equality:key=value["!=",key,value]inequality:key≠value[ - * ">",key,value] - * - * greater than:key>value[">=",key,value] greater than or - * equal:key≥value["<",key,value] less than:key - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleFilterOperation.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFunction.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFunction.java deleted file mode 100644 index 2b3f6fd33..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleFunction.java +++ /dev/null @@ -1,622 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.Color; -import java.awt.Paint; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.ColorFactory; -import com.fasterxml.jackson.databind.JsonNode; - -/** - * Builds up an array of values to use at various zoom levels, based on a node - * with a base value and step values. Set the base when you make it, add step - * values. Then just call get to retrieve value for zoom level. - * - * @author dietrick - * - */ -public class StyleFunction { - public final static int MIN_ZOOM_LEVEL = 0; - public final static int MAX_ZOOM_LEVEL = 20; - public final static int NUM_ZOOM_LEVELS = 21; - - T base; - T[] levels; - T DEFAULT; - boolean loaded = false; - - /** - * Constructor where base and default are the same. - * - * @param basedflt - */ - public StyleFunction(T basedflt) { - this(basedflt, basedflt); - } - - /** - * Constructor with different values for base and default. - * - * @param base - * value used for calculated level values. - * @param dflt - * value used for null level values. - */ - public StyleFunction(T base, T dflt) { - this.base = base; - this.DEFAULT = dflt; - } - - public T get(int zoomLevel) { - if (!loaded) { - load(); - } - - if (levels == null) { - return base; - } - - if (zoomLevel <= MIN_ZOOM_LEVEL) { - return levels[MIN_ZOOM_LEVEL]; - } else if (zoomLevel >= MAX_ZOOM_LEVEL) { - return levels[MAX_ZOOM_LEVEL]; - } - return levels[zoomLevel]; - } - - public void add(int zoomLevel, T val) { - if (levels == null) { - levels = initLevels(); - } - - loaded = false; - - if (zoomLevel <= MIN_ZOOM_LEVEL) { - levels[MIN_ZOOM_LEVEL] = val; - } else if (zoomLevel >= MAX_ZOOM_LEVEL) { - levels[MAX_ZOOM_LEVEL] = val; - } else { - levels[zoomLevel] = val; - } - } - - public T[] initLevels() { - List ret = new ArrayList(); - for (int i = 0; i < NUM_ZOOM_LEVELS; i++) { - ret.add(DEFAULT); - } - return (T[]) ret.toArray(); - } - - public boolean isConstant() { - return levels == null; - } - - public void load() { - - if (levels == null) { - loaded = true; - return; - } - - T levelVal = null; - int bottom = MIN_ZOOM_LEVEL; - int top = MIN_ZOOM_LEVEL; - - for (int i = MIN_ZOOM_LEVEL; i < NUM_ZOOM_LEVELS; i++) { - if (levels[i] != DEFAULT) { - levelVal = levels[i]; - bottom = i; - break; - } - } - - for (int i = MAX_ZOOM_LEVEL; i > bottom; i--) { - if (levels[i] != DEFAULT) { - top = i; - break; - } - } - - for (int i = MIN_ZOOM_LEVEL; i < NUM_ZOOM_LEVELS; i++) { - if (levels[i] == DEFAULT) { - if (i < bottom || i > top) { - levels[i] = levelVal; - } else { - levels[i] = levelVal; - } - } else { - levelVal = levels[i]; - } - } - - loaded = true; - } - - public String toString() { - - if (levels == null) { - return "base: " + base; - } else { - if (!loaded) { - load(); - } - - StringBuilder sb = new StringBuilder("levels["); - for (int i = MIN_ZOOM_LEVEL; i < MAX_ZOOM_LEVEL; i++) { - sb.append(levels[i]).append(","); - } - sb.append(levels[MAX_ZOOM_LEVEL]).append("]"); - return sb.toString(); - } - } - - /** - * Get the StyleFunction class built from the node resulting from a key get - * query. - * - * @param node - * the value node is passed in. - * @param dflt - * the default value. - * @param constants - * the constants node. - * @return If null passed in, null will be passed out. This can indicate - * that the key wasn't used. - */ - public static StyleFunction getDoubleFunction(JsonNode node, Double dflt, JsonNode constants) { - if (node != null) { - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - double base = StyleNode.getAsDouble(node, "base", 1.0); - StyleFunction styleFunction = new StyleFunction.EXP(base); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - double val = stop.get(1).asDouble(); - - styleFunction.add(zoomLevel, val); - } - } - return styleFunction; - } - } - } else if (node.isDouble()) { - Double val = new Double(node.asDouble()); - return new StyleFunction(val); - } else if (node.isTextual()) { - - String valString = node.asText(); - - if (constants != null && refersToConstant(valString, constants)) { - return getDoubleFunction(constants.get(valString), dflt, null); - } - } - } - - if (dflt != null) { - return new StyleFunction(dflt); - } - - return null; - } - - /** - * Get a StyleFunction holding float[]. - * - * @param node - * the value node from a key query. - * @param constants - * the constants node. - * @return null if node null or node isn't an array. - */ - public static StyleFunction getFloatArrayFunction(JsonNode node, JsonNode constants) { - if (node != null) { - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - - StyleFunction styleFunction = new StyleFunction(new float[1]); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - - JsonNode arrayNode = stop.get(1); - if (arrayNode.isArray()) { - styleFunction.add(zoomLevel, getFloats(arrayNode)); - } - - } - } - return styleFunction; - } - } - } else if (node.isArray()) { - return new StyleFunction(getFloats(node)); - } else if (node.isTextual()) { - - String valString = node.asText(); - - if (constants != null && refersToConstant(valString, constants)) { - return getFloatArrayFunction(constants.get(valString), null); - } - } - } - - return null; - } - - /** - * Parsing function that assumes node is an array of floats. - * - * @param node - * array of numbers - * @return float array - */ - static float[] getFloats(JsonNode node) { - int size = node.size(); - float[] fArray = new float[size]; - for (int i = 0; i < size; i++) { - fArray[i] = node.get(i).floatValue(); - } - return fArray; - } - - /** - * Check if the value starts with apersand, signifying a constant value - * link. - * - * @param val - * value string to test for key into constants list - * @param constants - * constants list as JsonNode. - * @return true if value is found in constants. - */ - static boolean refersToConstant(String val, JsonNode constants) { - boolean ret = constants != null && val != null && val.startsWith("@"); - - if (ret && getLogger().isLoggable(Level.FINE)) { - getLogger().fine("found constant " + val + ", " + constants.get(val).toString()); - } - - return ret; - } - - /** - * Create a Paint StyleFunction. - * - * @param node - * The value node from a color key query, holding the color value - * or step definition. - * @param opacity - * the opacity StyleFunction to be applied to Paint StyleFunction - * values. - * @param dflt - * the default base color in case a color isn't defined. - * @param constants - * A constants definition node. - * @return the Paint StyleFunction defined by the value node provided, dflt. - * The colors have been modified with opacity settings. - */ - public static StyleFunction getPaintFunction(JsonNode node, StyleFunction opacity, - StyleFunction dflt, JsonNode constants) { - - if (opacity == null) { - opacity = StyleDrawingAttributes.DEFAULT_OPACITY; - } - - if (node != null) { - - // Test for step-wise color definitions. - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - Color base = applyOpacity(parseColor(node, "base", constants), opacity.base); - StyleFunction styleFunction = new StyleFunction(base); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - Color val = parseColor(stop.get(1).asText()); - if (val != null) { - styleFunction.add(zoomLevel, applyOpacity(val, opacity.get(zoomLevel))); - } - } - } - - return styleFunction; - } - } - } else { - - // The color is defined directly for all zoom levels. - String valString = node.asText(); - - if (constants != null && refersToConstant(valString, constants)) { - return getPaintFunction(constants.get(valString), opacity, dflt, null); - } - - Color val = parseColor(valString); - if (val != null) { - if (opacity.isConstant()) { - val = applyOpacity(val, opacity.base); - } - return new StyleFunction(val); - } - - } - } - - return dflt; - } - - /** - * Applies opacity to the base color, returning an appropriate Paint - * StyleFunction. - * - * @param baseColor - * starting color - * @param opacity - * opaqueness from 0 to 1.0 - * @return new color with opacity applied. - */ - static StyleFunction applyOpacity(Color baseColor, StyleFunction opacity) { - if (opacity == null) { - opacity = StyleDrawingAttributes.DEFAULT_OPACITY; - } - - if (!opacity.isConstant()) { - StyleFunction ret = new StyleFunction(baseColor); - for (int i = 0; i < 20; i++) { - ret.add(i, applyOpacity(baseColor, opacity.get(i))); - } - return ret; - } - - return new StyleFunction(applyOpacity(baseColor, opacity.base)); - } - - /** - * @param baseColor - * starting color - * @param opacity - * opaqueness from 0 to 1.0 - * @return new color with opacity applied. - */ - static Color applyOpacity(Color baseColor, double opacity) { - if (baseColor != null) { - return new Color(baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), (int) (opacity * 255)); - } - - return baseColor; - } - - /** - * Parse the color given the paint node. The value will be from the prop key - * of the provided node. - * - * @param node - * node holding key and value. - * @param prop - * the key for the color value - * @param constants - * node holding constant values. - * @return Color - */ - public static Color parseColor(JsonNode node, String prop, JsonNode constants) { - return parseColor(node.get(prop), constants); - } - - /** - * Parse the Color given the color value node. - * - * @param node - * color value node. - * @param constants - * node holding constant values. - * @return Color - */ - public static Color parseColor(JsonNode node, JsonNode constants) { - Color baseColor = null; - if (node != null) { - String valString = node.asText(); - - if (constants != null && refersToConstant(valString, constants)) { - return parseColor(constants.get(valString), null); - } - - baseColor = parseColor(node.asText()); - } - - return baseColor; - } - - /** - * Given value string, check various formats to determine a color. - * - * @param colorString - * rgb, rgba, #, color name - * @return Color if it can be determined, null otherwise. - */ - public static Color parseColor(String colorString) { - Color baseColor = null; - - if (colorString != null) { - - if (colorString.startsWith("#")) { - baseColor = ColorFactory.parseColor(colorString.substring(1), true); - } else if (colorString.startsWith("rgba")) { - String tokens = colorString.substring(5, colorString.length() - 1); // parans - String[] values = tokens.split(","); - - if (values.length == 4) { - try { - baseColor = ColorFactory.createColor(Integer.parseInt(values[0]), Integer.parseInt(values[1]), - Integer.parseInt(values[2]), Integer.parseInt(values[3])); - } catch (NumberFormatException nfe) { - - } - } - } else if (colorString.startsWith("rgb")) { - String tokens = colorString.substring(4, colorString.length() - 1); // parans - String[] values = tokens.split(","); - if (values.length == 3) { - try { - baseColor = ColorFactory.createColor(Integer.parseInt(values[0]), Integer.parseInt(values[1]), - Integer.parseInt(values[2]), 255); - } catch (NumberFormatException nfe) { - - } - } - } else { - baseColor = ColorFactory.getNamedColor(colorString, null); - } - } - - return baseColor; - } - - /** - * Class used by StyleFunction Double to interpolate values between defined - * values. A regular Double StyleFunction will create stepped values. - * - * @author dietrick - * - */ - public static class EXP extends StyleFunction { - - public EXP(Double base) { - super(base, Double.NaN); - } - - @Override - public Double[] initLevels() { - Double[] ret = new Double[NUM_ZOOM_LEVELS]; - for (int i = MIN_ZOOM_LEVEL; i < NUM_ZOOM_LEVELS; i++) { - ret[i] = DEFAULT; - } - return ret; - } - - @Override - public void load() { - - if (levels == null) { - return; - } - - double levelVal = Double.NaN; - int bottom = MIN_ZOOM_LEVEL; - int top = MIN_ZOOM_LEVEL; - double maxVal = Double.MAX_VALUE; - - for (int i = MIN_ZOOM_LEVEL; i < NUM_ZOOM_LEVELS; i++) { - if (!Double.isNaN(levels[i])) { - levelVal = levels[i]; - bottom = i; - maxVal = levelVal; - break; - } - } - - for (int i = MAX_ZOOM_LEVEL; i > bottom; i--) { - if (!Double.isNaN(levels[i])) { - top = i; - maxVal = levels[i]; - break; - } - } - - int indexForLevelVal = MIN_ZOOM_LEVEL; - for (int i = MIN_ZOOM_LEVEL; i < NUM_ZOOM_LEVELS; i++) { - if (Double.isNaN(levels[i])) { - if (i < bottom || i > top) { - levels[i] = levelVal; - indexForLevelVal = i; - } else { - // we have to figure out this level. - int nextValidIndex = top; - - for (int j = i; j < top; j++) { - if (!Double.isNaN(levels[j])) { - nextValidIndex = j; - break; - } - } - - double nextLevelVal = levels[nextValidIndex]; - - int zoomDiff = nextValidIndex - indexForLevelVal; - double valueDiff = nextLevelVal - levelVal; - double slope = valueDiff / zoomDiff; - - double val = Math.pow(base, i - indexForLevelVal) * slope + levels[i - 1]; - - if (val > maxVal) { - val = maxVal; - } - - levels[i] = val; - } - } else { - levelVal = levels[i]; - indexForLevelVal = i; - } - } - - loaded = true; - } - - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleFunction.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayer.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayer.java deleted file mode 100644 index 006825bd9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayer.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.fasterxml.jackson.databind.JsonNode; - -import no.ecc.vectortile.VectorTileDecoder.Feature; - -public class StyleLayer { - - /** Required string. Unique layer name. */ - static String ID = "id"; - - /** - * Optional Arbitrary properties useful to track with the layer, but do not - * influence rendering. Properties should be prefixed to avoid collisions, - * like ‘mapbox:’. - */ - static String METADATA = "metadata"; - /** - * Optional string. References another layer to copy type, source, - * source-layer, minzoom, maxzoom, filter, and layout properties from. This - * allows the layers to share processing and be more efficient. - */ - static String REF = "ref"; - /** - * Optional string. Name of a source description to be used for this layer. - */ - static String SOURCE = "source"; - /** - * Optional string. Layer to use from a vector tile source. Required if the - * source supports multiple layers. - */ - static String SOURCE_LAYER = "source-layer"; - /** - * Optional number. The minimum zoom level on which the layer gets parsed - * and appears on. - */ - static String MIN_ZOOM = "minzoom"; - /** - * Optional number. The maximum zoom level on which the layer gets parsed - * and appears on. - */ - static String MAX_ZOOM = "maxzoom"; - /** - * Optional boolean. Defaults to false. Enable querying of feature data from - * this layer for interactivity. - */ - static String INTERACTIVE = "interactive"; - /** - * Optional paint. Class-specific paint properties for this layer. The class - * name is the part after the first dot. - */ - static String PAINT_DOT = "paint."; - - String id; - StyleLayerType type; - Map metadata; - String ref; - String source; - String sourceLayer; - double minZoom; - double maxZoom; - boolean interactive; - StyleFilter filter; - StyleDrawingAttributes renderer; - StyleLayer refLayer = null; - - public StyleLayer(JsonNode layerNode, List currentLayers, JsonNode constants) { - id = layerNode.get(ID).asText(); - - // This is handy for debugging, when you want to trap the thread on a - // desired entry. Look for the layer id here, as defined in the style - // file. - /* - * if (id.equals("water_offset")) { System.out.println("water_pattern"); - * } - */ - - ref = StyleNode.getAsText(layerNode, REF, null); - if (ref != null && currentLayers != null) { - refLayer = resolveRef(currentLayers); - } - - if (refLayer != null) { - renderer = StyleDrawingAttributes.get(type, layerNode, constants); - // And also layout parameters. - if (renderer != null && refLayer.renderer != null) { - renderer.configureFromReference(refLayer.renderer); - } else { - System.out.println("StyleLayer " + id + " can't configure renderer this:" - + (renderer != null ? "OK" : "NOPE") + " that:" + (refLayer.renderer != null ? "OK" : "NOPE")); - } - } else { - type = StyleLayerType.getFromLayerNode(layerNode); - source = StyleNode.getAsText(layerNode, SOURCE, null); - sourceLayer = StyleNode.getAsText(layerNode, SOURCE_LAYER, null); - filter = StyleFilter.getForLayerNode(layerNode); - minZoom = StyleNode.getAsDouble(layerNode, MIN_ZOOM, Double.NaN); - maxZoom = StyleNode.getAsDouble(layerNode, MAX_ZOOM, Double.NaN); - renderer = StyleDrawingAttributes.getForType(layerNode, constants); - } - - renderer.layerID = this.id; - - interactive = StyleNode.getAsBoolean(layerNode, INTERACTIVE, false); - - if (ref != null) { - getLogger().warning(id + ": REF linked: " + ref); - } - - if (layerNode.get(METADATA) != null) { - getLogger().warning(id + ": metadata is being ignored for now."); - } - - } - - StyleLayer resolveRef(List layers) { - for (StyleLayer layer : layers) { - if (layer.id.equals(ref)) { - if (getLogger().isLoggable(Level.INFO)) { - getLogger().info("StyleLayer (" + id + ") found referenced layer: " + layer.id); - } - return configureFromReference(layer); - } - } - return null; - } - - StyleLayer configureFromReference(StyleLayer reference) { - // According to the specification, this is what gets copied from the - // reference. - this.type = reference.type; - this.source = reference.source; - this.sourceLayer = reference.sourceLayer; - this.minZoom = reference.minZoom; - this.maxZoom = reference.maxZoom; - this.filter = reference.filter; - - // and layout, but we hook that up explicitly in the constructor after - // this method is called. - - return reference; - } - - public boolean passes(Feature feature, int zoomLevel) { - - if ((!Double.isNaN(minZoom) && zoomLevel < minZoom) || (!Double.isNaN(maxZoom) && zoomLevel > maxZoom)) { - return false; - } - - if (filter != null) { - return filter.passes(feature); - } - return true; - } - - public static List getLayerArray(JsonNode node, JsonNode constants) { - List layers = new ArrayList(); - Iterator layerNodes = node.elements(); - while (layerNodes.hasNext()) { - layers.add(new StyleLayer(layerNodes.next(), new ArrayList(layers), constants)); - } - return layers; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleLayer.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayerType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayerType.java deleted file mode 100644 index 1ac5aac9c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLayerType.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import com.fasterxml.jackson.databind.JsonNode; - -public enum StyleLayerType { - - FILL("fill"), - LINE("line"), - SYMBOL("symbol"), - CIRCLE("circle"), - RASTER("raster"), - BACKGROUND("background"), - UNKNOWN("unknown"); - - private static String TYPE = "type"; - - String name; - - private StyleLayerType(String name) { - this.name = name; - } - - public static StyleLayerType getFromLayerNode(JsonNode layerNode) { - return getForType(StyleNode.getAsText(layerNode, TYPE, "")); - } - - public static StyleLayerType getForType(String nm) { - for (StyleLayerType slt : StyleLayerType.values()) { - if (nm.contains(slt.name)) { - return slt; - } - } - return UNKNOWN; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineCap.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineCap.java deleted file mode 100644 index 80ced1f9d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineCap.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.BasicStroke; -import java.util.Iterator; - -import com.fasterxml.jackson.databind.JsonNode; - -public enum StyleLineCap { - - BUTT("butt", BasicStroke.CAP_BUTT), ROUND("round", BasicStroke.CAP_ROUND), SQUARE("square", BasicStroke.CAP_SQUARE); - - String name; - int val; - - private StyleLineCap(String name, int basicStrokeVal) { - this.name = name; - this.val = basicStrokeVal; - } - - public static StyleLineCap getForNode(JsonNode node) { - JsonNode slp = node.get(StyleDrawingAttributes.LINE.LINE_CAP); - if (slp != null) { - return getForName(slp.asText()); - } - return null; - } - - public static StyleLineCap getForName(String nm) { - for (StyleLineCap st : StyleLineCap.values()) { - if (nm.contains(st.name)) { - return st; - } - } - return null; - } - - public static StyleFunction getFunction(JsonNode node) { - StyleLineCap dflt = BUTT; - if (node != null) { - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - StyleLineCap base = getForName(StyleNode.getAsText(node, "base", "butt")); - StyleFunction styleFunction = new StyleFunction(base, dflt); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - StyleLineCap val = getForName(stop.get(1).asText()); - - styleFunction.add(zoomLevel, val); - } - } - return styleFunction; - } - } - } else { - StyleLineCap val = getForNode(node); - if (val != null) { - return new StyleFunction(val); - } - } - } - - return new StyleFunction(dflt); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineJoin.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineJoin.java deleted file mode 100644 index ab71b1259..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleLineJoin.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.BasicStroke; -import java.util.Iterator; - -import com.fasterxml.jackson.databind.JsonNode; - -public enum StyleLineJoin { - - BEVEL("bevel", BasicStroke.JOIN_BEVEL), - ROUND("round", BasicStroke.JOIN_ROUND), - MITER("miter", BasicStroke.JOIN_MITER); - - String name; - int val; - - private StyleLineJoin(String name, int basicStrokeVal) { - this.name = name; - this.val = basicStrokeVal; - } - - public static StyleLineJoin getForNode(JsonNode node) { - JsonNode slp = node.get(StyleDrawingAttributes.LINE.LINE_JOIN); - if (slp != null) { - return getForName(slp.asText()); - } - return null; - } - - public static StyleLineJoin getForName(String nm) { - for (StyleLineJoin st : StyleLineJoin.values()) { - if (nm.contains(st.name)) { - return st; - } - } - return null; - } - - public static StyleFunction getFunction(JsonNode node) { - StyleLineJoin dflt = MITER; - if (node != null) { - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - StyleLineJoin base = getForName(StyleNode.getAsText(node, "base", "butt")); - StyleFunction styleFunction = new StyleFunction(base, dflt); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - StyleLineJoin val = getForName(stop.get(1).asText()); - - styleFunction.add(zoomLevel, val); - } - } - return styleFunction; - } - } - } else { - StyleLineJoin val = getForNode(node); - if (val != null) { - return new StyleFunction(val); - } - } - } - - return new StyleFunction(dflt); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleNode.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleNode.java deleted file mode 100644 index abdb30d27..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleNode.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.logging.Logger; - -import com.fasterxml.jackson.databind.JsonNode; - -/** - * Helper functions for dealing with nodes. - * - * @author dietrick - * - */ -public class StyleNode { - - public static String getAsText(JsonNode node, String fieldName, String dflt) { - try { - return node.get(fieldName).asText(); - } catch (NullPointerException npe) { - return dflt; - } - } - - public static int getAsInt(JsonNode node, String fieldName, int dflt) { - try { - return node.get(fieldName).asInt(); - } catch (NullPointerException npe) { - return dflt; - } - } - - public static double getAsDouble(JsonNode node, String fieldName, double dflt) { - try { - return node.get(fieldName).asDouble(); - } catch (NullPointerException npe) { - return dflt; - } - } - - public static boolean getAsBoolean(JsonNode node, String fieldName, boolean dflt) { - try { - return node.get(fieldName).asBoolean(); - } catch (NullPointerException npe) { - return dflt; - } - } - - public static long getAsLong(JsonNode node, String fieldName, long dflt) { - try { - return node.get(fieldName).asLong(); - } catch (NullPointerException npe) { - return dflt; - } - } - - public static void prettyOut(JsonNode node, String prefix) { - Iterator> fields = node.fields(); - while (fields.hasNext()) { - Entry field = fields.next(); - String key = field.getKey(); - if (key.equalsIgnoreCase("id")) { - System.out.println(""); - } - - JsonNode value = field.getValue(); - System.out.println(prefix + key + ": " + value); - if (value.isArray()) { - prettyOutArray(value, prefix + " "); - } else { - prettyOut(value, prefix + " "); - } - } - } - - public static void prettyOutArray(JsonNode node, String prefix) { - Iterator children = node.elements(); - while (children.hasNext()) { - JsonNode child = children.next(); - if (child.isArray()) { - prettyOutArray(child, prefix + " "); - } else { - prettyOut(child, prefix + " "); - } - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleNode.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleRoot.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleRoot.java deleted file mode 100644 index b240e7b44..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleRoot.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.fasterxml.jackson.databind.JsonNode; - -import no.ecc.vectortile.VectorTileDecoder.Feature; - -/** - * The root node of the style document. From here, you can get to all info. - * - * @author dietrick - */ -public class StyleRoot { - - static String VERSION = "version"; - static String NAME = "name"; - static String METADATA = "metadata"; - static String CONSTANTS = "constants"; - static String CENTER = "center"; - static String ZOOM = "zoom"; - static String BEARING = "bearing"; - static String PITCH = "pitch"; - static String SOURCES = "sources"; - static String SPRITE = "sprite"; - static String GLYPHS = "glyphs"; - static String LAYERS = "layers"; - - double version; - String name; - Map metadata; - JsonNode constants; - LatLonPoint center; - double zoom; - double bearing; - double pitch; - StyleSource sources; - String sprites; - String glyphs; - List layers; - - final HashMap> layerGroupsByType = new HashMap>(); - final HashMap> layerGroupsBySourceLayer = new HashMap>(); - List visibleLayers = new ArrayList(); - - private StyleRoot() { - - } - - public StyleRoot(JsonNode rootNode) { - version = rootNode.get(VERSION).asDouble(); - name = rootNode.get(NAME).asText(); - zoom = StyleNode.getAsDouble(rootNode, ZOOM, Double.NaN); - bearing = StyleNode.getAsDouble(rootNode, BEARING, Double.NaN); - pitch = StyleNode.getAsDouble(rootNode, PITCH, Double.NaN); - - // sprites = rootNode.get(SPRITE).asText(); - JsonNode spriteNode = rootNode.get(SPRITE); - if (spriteNode != null) { - sprites = spriteNode.asText(); - } - - // glyphs = rootNode.get(GLYPHS).asText(); - JsonNode glyphNode = rootNode.get(GLYPHS); - if (glyphNode != null) { - glyphs = glyphNode.asText(); - } - - JsonNode metadataNode = rootNode.get(METADATA); - if (metadataNode != null) { - - } - JsonNode sourceNode = rootNode.get(SOURCES); - if (sourceNode != null) { - - } - - constants = rootNode.get(CONSTANTS); - if (getLogger().isLoggable(Level.FINE)) { - StringBuilder sBuilder = new StringBuilder("\n------- Constants ----------"); - if (constants != null) { - Iterator fieldNameIterator = constants.fieldNames(); - while (fieldNameIterator.hasNext()) { - sBuilder.append("\n").append(fieldNameIterator.next()); - } - } - sBuilder.append("\n----------------------------"); - getLogger().fine(sBuilder.toString()); - } - - JsonNode layerNode = rootNode.get(LAYERS); - if (layerNode != null) { - layers = StyleLayer.getLayerArray(layerNode, constants); - resetLayerGroups(layers); - - if (getLogger().isLoggable(Level.FINE)) { - StringBuilder sb = new StringBuilder("StyleLayer ID, SOURCELAYER"); - for (StyleLayer sl : layers) { - sb.append(sl.id).append(", ").append(sl.sourceLayer); - } - getLogger().fine(sb.toString()); - } - } - - } - - /** - * Assumes styleLayers isn't null. - * @param styleLayers - */ - void resetLayerGroups(List styleLayers) { - layerGroupsByType.clear(); - layerGroupsBySourceLayer.clear(); - visibleLayers.clear(); - - for (StyleLayer styleLayer : styleLayers) { - List styleLayerList = layerGroupsByType.get(styleLayer.type); - if (styleLayerList == null) { - styleLayerList = new ArrayList(); - layerGroupsByType.put(styleLayer.type, styleLayerList); - } - styleLayerList.add(styleLayer); - - if (styleLayer.sourceLayer != null) { - styleLayerList = layerGroupsBySourceLayer.get(styleLayer.sourceLayer); - if (styleLayerList == null) { - styleLayerList = new ArrayList(); - layerGroupsBySourceLayer.put(styleLayer.sourceLayer, styleLayerList); - } - styleLayerList.add(styleLayer); - } - - visibleLayers.add(styleLayer.id); - } - } - - public StyleDrawingAttributes getBackgroundRenderer() { - List backgroundLayers = layerGroupsByType.get(StyleLayerType.BACKGROUND); - if (backgroundLayers != null && !backgroundLayers.isEmpty()) { - return backgroundLayers.get(0).renderer; - } - return StyleDrawingAttributes.EMPTY; - } - - public List getRenderers(Feature feature, int zoomLevel) { - String featureSourceLayer = feature.getLayerName(); - List ret = new ArrayList(); - List matchingSourceLayers = layerGroupsBySourceLayer.get(featureSourceLayer); - if (matchingSourceLayers != null && !matchingSourceLayers.isEmpty()) { - for (StyleLayer sLayer : matchingSourceLayers) { - - if (feature.getLayerName().equals("water_offset")) { - System.out.println("here"); - } - - if (sLayer.passes(feature, zoomLevel)) { - StyleDrawingAttributes sda = sLayer.renderer; - if (sda.isVisible(zoomLevel)) { - ret.add(sda); - } - } - } - } - - return ret; - } - - /** - * Basic styling just to see features. - * - * @author dietrick - * - */ - public static class DEFAULT extends StyleRoot { - - StyleDrawingAttributes area = StyleDrawingAttributes.get(StyleLayerType.FILL, null, null); - StyleDrawingAttributes line = StyleDrawingAttributes.get(StyleLayerType.LINE, null, null); - - public DEFAULT() { - version = 1.0; - name = "OpenMap DEFAULT"; - zoom = Double.NaN; - bearing = Double.NaN; - pitch = Double.NaN; - sprites = ""; - glyphs = ""; - - area.setFillPaint(Color.lightGray); - area.setFillPaint(Color.lightGray); - line.setLinePaint(Color.darkGray); - } - - public StyleDrawingAttributes getRenderer(Feature feature) { - switch (FeatureGeometryType.get(feature.getGeometry().getGeometryType())) { - case POINT: - case MULTI_POINT: - case LINEAR_RING: - case LINE_STRING: - case MULTI_LINE_STRING: - return line; - case POLYGON: - case MULTI_POLYGON: - return area; - default: - } - return null; - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleRoot.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSource.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSource.java deleted file mode 100644 index 8e36b2494..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSource.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.logging.Logger; - -import com.fasterxml.jackson.databind.JsonNode; - -public class StyleSource { - - StyleSourceType type; - String url; - - public StyleSource(JsonNode sourceNode) { - - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StyleSource.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSourceType.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSourceType.java deleted file mode 100644 index 976b4ad53..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleSourceType.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import com.fasterxml.jackson.databind.JsonNode; - -public enum StyleSourceType { - VECTOR("vector"), RASTER("raster"), GEOJSON("geojson"), IMAGE("image"), VIDEO("video"), UNKNOWN("unknown"); - - private static String TYPE = "type"; - - private String name; - - private StyleSourceType(String name) { - this.name = name; - } - - public static StyleSourceType getForNode(JsonNode node) { - return getForName(node.get(TYPE).toString()); - } - - public static StyleSourceType getForName(String nm) { - for (StyleSourceType st : StyleSourceType.values()) { - if (st.name.equalsIgnoreCase(nm)) { - return st; - } - } - return UNKNOWN; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleVisibility.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleVisibility.java deleted file mode 100644 index 148177d1b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/StyleVisibility.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.util.Iterator; - -import com.fasterxml.jackson.databind.JsonNode; - -public enum StyleVisibility { - VISIBLE("visible", true), NONE("none", false); - - static String VISIBILITY = "visibility"; - final String name; - final boolean visible; - - private StyleVisibility(String name, boolean visible) { - this.name = name; - this.visible = visible; - } - - public static StyleVisibility getForNode(JsonNode node) { - JsonNode vis = node.get(VISIBILITY); - if (vis != null) { - return getForName(vis.asText()); - } - return null; - } - - public static StyleVisibility getForName(String nm) { - for (StyleVisibility st : StyleVisibility.values()) { - if (nm.contains(st.name)) { - return st; - } - } - return null; - } - - public boolean isVisible() { - return visible; - } - - public static StyleFunction getFunction(JsonNode node) { - StyleVisibility dflt = VISIBLE; - if (node != null) { - if (node.has("stops")) { - - JsonNode stopsNode = node.withArray("stops"); - if (stopsNode != null) { - // System.out.println(node); - Iterator stops = stopsNode.iterator(); - if (stops != null) { - StyleVisibility base = getForName(StyleNode.getAsText(node, "base", "visible")); - StyleFunction styleFunction = new StyleFunction(base, dflt); - while (stops.hasNext()) { - JsonNode stop = stops.next(); - - if (stop.isArray()) { - int zoomLevel = stop.get(0).asInt(); - StyleVisibility val = getForName(stop.get(1).asText()); - - styleFunction.add(zoomLevel, val); - } - } - return styleFunction; - } - } - } else { - StyleVisibility val = getForNode(node); - if (val != null) { - return new StyleFunction(val); - } - } - } - - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorMapTileFactory.java deleted file mode 100644 index fc09478aa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorMapTileFactory.java +++ /dev/null @@ -1,590 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -import no.ecc.vectortile.VectorTileDecoder; -import no.ecc.vectortile.VectorTileDecoder.Feature; -import no.ecc.vectortile.VectorTileDecoder.FeatureIterable; - -/** - * MapTileFactory that handles mbtiles files containing vector data - * (http://osm2vectortiles.org), in the MapBox format. Requires JTS and the - * java-vector-tile project (see maven dependencies). Uses MapBox GL JSON files - * for styling (https://www.mapbox.com/mapbox-gl-style-spec/). - * - *
- *  
- * vectorTileLayer.class=com.bbn.openmap.layer.image.MapTileLayer
- * vectorTileLayer.prettyName=Vector Tiles (USA)
- * vectorTileLayer.tileFactory=com.bbn.openmap.dataAccess.mapTile.mb.VectorMapTileFactory
- * vectorTileLayer.style=styles/basic-v8.json
- * vectorTileLayer.rootDir=jdbc:sqlite:/data/tiles/united_states_of_america.mbtiles
- * 
- * #optional - mbtiles and mvt files have compressed data, pbf data is not compressed.
- * vectorTileLayer.compressed=true
- * #optional - use parent tiles to fill missing tiles.
- * vectorTileLayer.useParentTiles=true
- * 
- * - * @author dietrick - */ -public class VectorMapTileFactory extends RasterMapTileFactory { - - public final static String COMPRESSED_PROPERTY = "compressed"; - public final static String FILL_MISSING_TILES_FROM_PARENTS_PROPERTY = "useParentTiles"; - - VectorOMGraphicFactory omGraphicFactory; - StyleRoot renderStyle; - /** mvt is compressed, pbf is not. */ - boolean compressed = true; - boolean useParentTiles = true; - - public VectorMapTileFactory() { - getLogger().fine("Using VectorTileMapTileFactory"); - } - - /** - * @return the omGraphicFactory - */ - public VectorOMGraphicFactory getOMGraphicFactory() { - return omGraphicFactory; - } - - /** - * Set the VectorOMGraphicFactory. Assumes that the styling is set for it. - * Resets the cache so new tiles need to be generated with the new style. - * - * @param omGraphicFactory - * the omGraphicFactory to set - */ - public void setOMGraphicFactory(VectorOMGraphicFactory omGraphicFactory) { - this.omGraphicFactory = omGraphicFactory; - reset(); - } - - /** - * @return the compressed - */ - public boolean isCompressed() { - return compressed; - } - - /** - * @param compressed - * the compressed to set - */ - public void setCompressed(boolean compressed) { - this.compressed = compressed; - } - - /** - * @return the useParentTiles - */ - public boolean isUseParentTiles() { - return useParentTiles; - } - - /** - * @param useParentTiles - * the useParentTiles to set - */ - public void setUseParentTiles(boolean useParentTiles) { - this.useParentTiles = useParentTiles; - } - - /** - * @return the renderStyle - */ - public StyleRoot getRenderStyle() { - return renderStyle; - } - - /** - * Causes a new VectoryOMGraphicFactory to be created with the new - * renderStyle, and the cache is cleared to force new tiles to be created. - * - * @param renderStyle - * the renderStyle to set - */ - public void setRenderStyle(StyleRoot renderStyle) { - this.renderStyle = renderStyle; - if (renderStyle != null) { - setOMGraphicFactory(new VectorOMGraphicFactory(renderStyle)); - } else { - setOMGraphicFactory(null); - } - - createGUIFilters(); - } - - boolean disabled = false; - - /** - * Fetches a new tile from the database. - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - - if (!jdbcLoaded || disabled) { - if (!disabled) { - logger.log(Level.INFO, "jbdc not loaded, disabling VectorMapTileFactory"); - disabled = true; - } - return null; - } - - if (rootDir == null) { - getLogger().warning("Tile location (rootDir) not set"); - return null; - } - - if (omGraphicFactory == null) { - - if (renderStyle == null) { - renderStyle = new StyleRoot.DEFAULT(); - } - - omGraphicFactory = new VectorOMGraphicFactory(renderStyle); - } - - VectorTileDecoder decoder = new VectorTileDecoder(); - BufferedImage rasterImage = new BufferedImage(MapTileCoordinateTransform.TILE_SIZE, - MapTileCoordinateTransform.TILE_SIZE, BufferedImage.TYPE_INT_ARGB); - java.awt.Graphics2D g2 = rasterImage.createGraphics(); - RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - g2.addRenderingHints(renderingHints); - - try { - - // What to do if the tile isn't there? We can check smaller zoom - // levels to see if parent tiles exist. If they do, we can read - // those and set an AffineTransform on the Graphics object to adjust - // zoom and offset. The result should look fine, this is vector - // data. - - TileDataLoader tileDataLoader = new TileDataLoader(key, x, y, zoomLevel); - byte[] tileData = tileDataLoader.tileData; - if (tileData != null) { - FeatureIterable fi = decoder.decode(tileData); - - Map featureLists = omGraphicFactory.getFeatureMap(); - - omGraphicFactory.setCoordTransform(tileDataLoader.transform); - for (Feature feature : fi.asList()) { - omGraphicFactory.createAndSort(feature, zoomLevel, featureLists); - } - - omGraphicFactory.render(g2, zoomLevel, featureLists); - filterPanel.revalidate(); - - } else { - if (getLogger().isLoggable(Level.FINER)) { - getLogger().finer("tile for " + zoomLevel + "|" + x + "|" + y + " is missing."); - } - } - } catch (Exception e) { - getLogger().warning("something went wrong fetching image from database: " + e.getMessage()); - e.printStackTrace(); - } - - /** - * At this point, we have a image of rendered tile data. Prepare it for - * OpenMap layer. - */ - - try { - - OMGraphic raster = createOMGraphicFromBufferedImage(rasterImage, x, y, zoomLevel, proj); - - /* - * Again, create a CacheObject based on the local name if the local - * dir is defined. - */ - if (raster != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("building" + key); - } - - return new CacheObject(key, raster); - } - - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("factory interrupted fetching " + key); - } - } - - return null; - } - - protected BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - return BufferedImageHelper.getBufferedImage(origImage, 0, 0, 256, 256, BufferedImage.TYPE_INT_ARGB); - } - - /** - * Fetch tile data. Creates a SQL statement matching the MBTiles file schema - * and pulls gzipped binary data from the tile_data. If you want to fetch - * vector tiles differently, override this method! - * - * @param key - * the path to the tile built up from rootDir and the - * TilePathBuilder. source location - * @param x - * horizontal tile column - * @param y - * vertical tile row - * @param zoomLevel - * tile zoom level - * @return uncompressed tile data, ready for decoding - */ - public byte[] getTileData(Object key, int x, int y, int zoomLevel) throws Exception { - - // For the default implementation of this class, the rootDir should - // point at the mbtiles file. That's what we use to establish a - // connection. - Connection conn = DriverManager.getConnection(rootDir); - Statement stat = conn.createStatement(); - - // "select zoom_level, tile_column, tile_row, tile_data from map, - // images where map.tile_id = images.tile_id"; - StringBuilder statement = new StringBuilder("select tile_data from images, map where"); - statement.append(" zoom_level = ").append(zoomLevel); - statement.append(" and tile_column = ").append(x); - statement.append(" and tile_row = ").append(Math.pow(2, zoomLevel) - y - 1); - statement.append(" and map.tile_id = images.tile_id;"); - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine(statement.toString()); - } - - ResultSet rs = stat.executeQuery(statement.toString()); - byte[] tileData = null; - if (rs.next()) { - tileData = rs.getBytes("tile_data"); - rs.close(); - conn.close(); - } - - if (tileData != null) { - if (compressed) { - return inflate(tileData); - } else { - return tileData; - } - } - - return null; - } - - /** - * Decompressed the tile data (un-gzip) - * - * @param tileData - * @return tile data, uncompressed. - * @throws IOException - */ - protected byte[] inflate(byte[] tileData) throws IOException { - byte[] inflateBuffer = new byte[4096]; - ByteArrayOutputStream inflateBufStream = new ByteArrayOutputStream(inflateBuffer.length); - - ///////// unGZIP the byte data /// - ByteArrayInputStream bais = new ByteArrayInputStream(tileData); - GZIPInputStream gzipIS = new GZIPInputStream(bais); - while (gzipIS.available() > 0) { - int readCount = gzipIS.read(inflateBuffer); - if (readCount > 0) { - inflateBufStream.write(inflateBuffer, 0, readCount); - } - } - gzipIS.close(); - inflateBufStream.close(); - return inflateBufStream.toByteArray(); - /////////////////////////////////////////////////////////// - } - - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - compressed = PropUtils.booleanFromProperties(setList, prefix + COMPRESSED_PROPERTY, compressed); - useParentTiles = PropUtils.booleanFromProperties(setList, prefix + FILL_MISSING_TILES_FROM_PARENTS_PROPERTY, - useParentTiles); - } - - public Properties getProperties(Properties getList) { - getList = super.getProperties(getList); - String prefix = PropUtils.getScopedPropertyPrefix(this); - getList.put(prefix + COMPRESSED_PROPERTY, Boolean.toString(compressed)); - getList.put(prefix + FILL_MISSING_TILES_FROM_PARENTS_PROPERTY, Boolean.toString(useParentTiles)); - return getList; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, VectorMapTileFactory.class, COMPRESSED_PROPERTY, "Compressed", - "True if tile data is compressed", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VectorMapTileFactory.class, FILL_MISSING_TILES_FROM_PARENTS_PROPERTY, - "Use Parent Tiles", "Will use parent data for missing tiles.", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - return list; - } - - public String getInitPropertiesOrder() { - return ROOT_DIR_PROPERTY; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(VectorMapTileFactory.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - - List filterCheckBoxes = new ArrayList(); - JPanel filterPanel = new JPanel(); - - public JComponent getFilterPanel() { - filterPanel.removeAll(); - JComponent guiPanel = createGUIFilters(); - filterPanel.add(guiPanel); - return filterPanel; - } - - protected JComponent createGUIFilters() { - filterCheckBoxes.clear(); - - JPanel panel = new JPanel(); - JScrollPane jsp = new JScrollPane(panel); - jsp.setMaximumSize(new Dimension(900, 500)); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - panel.setLayout(gridbag); - if (renderStyle != null) { - int countForColumn = 0; - int countForRow = 0; - - int numColumns = renderStyle.layers.size() / 10; - if (numColumns > 4) { - numColumns = 4; - } else if (numColumns <= 0) { - numColumns = 1; - } - - for (StyleLayer layer : renderStyle.layers) { - JCheckBox jcb = new JCheckBox(layer.id, renderStyle.visibleLayers.contains(layer.id)); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - updateVisibilityList(); - } - }); - filterCheckBoxes.add(jcb); - c.gridx = countForColumn++ % numColumns; - c.gridy = countForRow++ / numColumns; - gridbag.setConstraints(jcb, c); - panel.add(jcb); - } - } - - JButton selectAllButton = new JButton("Select All"); - selectAllButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - updateVisibilityList(true); - } - }); - JButton selectNoneButton = new JButton("Select None"); - selectNoneButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - updateVisibilityList(false); - } - }); - - JPanel parent = new JPanel(); - gridbag = new GridBagLayout(); - c = new GridBagConstraints(); - c.gridwidth = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.BOTH; - c.weightx = 1.0; - c.weighty = 1.0; - parent.setLayout(gridbag); - gridbag.setConstraints(jsp, c); - parent.add(jsp); - - c.gridwidth = GridBagConstraints.RELATIVE; - c.fill = GridBagConstraints.NONE; - c.weightx = 0; - c.weighty = 0; - c.anchor = GridBagConstraints.EAST; - gridbag.setConstraints(selectAllButton, c); - parent.add(selectAllButton); - c.anchor = GridBagConstraints.WEST; - gridbag.setConstraints(selectNoneButton, c); - parent.add(selectNoneButton); - return parent; - } - - protected void updateVisibilityList(boolean setAllTo) { - for (JCheckBox jcb : filterCheckBoxes) { - jcb.setSelected(setAllTo); - } - updateVisibilityList(); - } - - protected void updateVisibilityList() { - List visibleLayers = new ArrayList(); - for (JCheckBox jcb : filterCheckBoxes) { - if (jcb.isSelected()) { - visibleLayers.add(jcb.getText()); - } - } - renderStyle.visibleLayers = visibleLayers; - - reset(); - if (mapTileRequester instanceof OMGraphicHandlerLayer) { - ((OMGraphicHandlerLayer) mapTileRequester).doPrepare(); - - } - } - - /** - * This class loads parent tile data if a tile isn't found. The transform - * will handle how to change the projection of the points of the parent to - * make them work for the desired tile location and zoom level. - * - *

- * NOTE: this class assumes that the tiles are laid out in MapBox OSM - * notation, where 0,0 is upper left for tile location, and zooming out - * lowers the zoom level. It does not take into account the - * MapTileCoordinateTransform the layer may be using. - * - * @author dietrick - * - */ - class TileDataLoader { - /** - * The transform that might have to be made on the tile data to get it - * to work for the requested tile location. - */ - AffineTransform transform; - /** - * The tile data to use. - */ - byte[] tileData; - /** - * This is the zoom level where a tile was found that covers the - * original tile area. - */ - int foundDataZoomLevel; - - TileDataLoader(Object key, int x, int y, int zoomLevel) throws Exception { - tileData = findTileData(key, x, y, zoomLevel); - if (tileData == null) { - foundDataZoomLevel = zoomLevel; - } - - double zoomLevelMultiplier = Math.pow(2.0, zoomLevel - foundDataZoomLevel); - - double xoffset = (x % zoomLevelMultiplier) * MapTileCoordinateTransform.TILE_SIZE; - double yoffset = (y % zoomLevelMultiplier) * MapTileCoordinateTransform.TILE_SIZE; - - this.transform = AffineTransform.getTranslateInstance(-xoffset, -yoffset); - this.transform.concatenate(AffineTransform.getScaleInstance(zoomLevelMultiplier, zoomLevelMultiplier)); - } - - /** - * Recursive tile search, until the zoom levels run out. - * - * @param key - * @param x - * @param y - * @param zoomLevel - * @return - * @throws Exception - */ - byte[] findTileData(Object key, int x, int y, int zoomLevel) throws Exception { - byte[] tileDataBytes = getTileData(key, x, y, zoomLevel); - if (tileDataBytes != null || !useParentTiles) { - foundDataZoomLevel = zoomLevel; - return tileDataBytes; - } - - if (zoomLevel == 0) { - return null; - } - - // to check parent, divide x, y by 2 and get an integer, chop off - // the remainder. - zoomLevel--; - x = x / 2; - y = y / 2; - - return findTileData(key, x, y, zoomLevel); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorOMGraphicFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorOMGraphicFactory.java deleted file mode 100644 index 87d47b242..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/mb/VectorOMGraphicFactory.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.mb; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Rectangle2D; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMShape; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.LineString; -import com.vividsolutions.jts.geom.LinearRing; -import com.vividsolutions.jts.geom.MultiLineString; -import com.vividsolutions.jts.geom.MultiPolygon; -import com.vividsolutions.jts.geom.Polygon; - -import no.ecc.vectortile.VectorTileDecoder.Feature; - -public class VectorOMGraphicFactory { - - StyleRoot styles; - AffineTransform coordTransform; - - public VectorOMGraphicFactory(StyleRoot styles) { - this.styles = styles; - } - - public HashMap getFeatureMap() { - HashMap mapLists = new HashMap(); - if (styles != null) { - for (StyleLayer layer : styles.layers) { - mapLists.put(layer.id, new OMGraphicList()); - } - } - return mapLists; - } - - public OMGraphic getBackground(int zoomLevel) { - OMGraphic omg = new OMShape.PROJECTED(new Rectangle2D.Double(0, 0, 256, 256)); - styles.getBackgroundRenderer().getRenderer(zoomLevel).setTo(omg); - return omg; - } - - /** - * @return the coordTransform - */ - public AffineTransform getCoordTransform() { - return coordTransform; - } - - /** - * @param coordTransform - * the coordTransform to set - */ - public void setCoordTransform(AffineTransform coordTransform) { - this.coordTransform = coordTransform; - } - - public void createAndSort(Feature feature, int currentZoomLevel, Map featureLists) { - Geometry geometry = feature.getGeometry(); - - List renderers = styles.getRenderers(feature, currentZoomLevel); - - // OK, since we know the renderer here, we can determine if we need - // OMShape.PROJECTED or OMShape.GAPPED at this point when we evaluate - // the geometry type. - - if (renderers != null && !renderers.isEmpty()) { - for (StyleDrawingAttributes renderer : renderers) { - OMGraphicList featureList = featureLists.get(renderer.layerID); - - OMGraphic omg = null; - - switch (FeatureGeometryType.get(geometry.getGeometryType())) { - case POINT: - case MULTI_POINT: - break; - case LINEAR_RING: - omg = transformPolyline((LinearRing) geometry, renderer, currentZoomLevel); - break; - case LINE_STRING: - omg = transformLineString((LineString) geometry, renderer, currentZoomLevel); - break; - case MULTI_LINE_STRING: - omg = transformMultiLineString((MultiLineString) geometry, renderer, currentZoomLevel); - break; - case POLYGON: - omg = transformPolygon((Polygon) geometry, renderer, currentZoomLevel); - break; - case MULTI_POLYGON: - omg = transformMultiPolygon((MultiPolygon) geometry, renderer, currentZoomLevel); - break; - default: - System.out.println("unsure of handing " + geometry.getGeometryType()); - } - - if (omg != null) { - featureList.add(omg); - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine("++ " + omg.getClass().getName()); - } - } - } - } - } - - public void render(Graphics2D g2, int zoomLevel, Map featureLists) { - StringBuilder sBuilder = new StringBuilder("\n========= New tile\n"); - if (styles != null) { - - for (StyleLayer layer : styles.layers) { - - if (layer.type.equals(StyleLayerType.BACKGROUND)) { - if (styles.visibleLayers.contains(layer.id)) { - getBackground(zoomLevel).render(g2); - sBuilder.append(" rendering ").append(layer.id).append("\n"); - } - continue; - } - - OMGraphicList omgl = featureLists.get(layer.id); - if (omgl != null && styles.visibleLayers.contains(layer.id)) { - sBuilder.append(" rendering ").append(layer.id).append(" ").append(omgl.size()).append("\n"); - omgl.render(g2); - } - } - - } - sBuilder.append("========= End tile").append("\n"); - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine(sBuilder.toString()); - } - } - - OMGraphic getOMGraphic(Coordinate[] coords, boolean connect, StyleDrawingAttributes renderer, int zoomLevel) { - return renderer.getOMGraphic(convertCoords(coords, connect), zoomLevel); - } - - protected OMGraphic transformPolygon(Polygon polygon, StyleDrawingAttributes renderer, int zoomLevel) { - int numInteriorRings = polygon.getNumInteriorRing(); - OMGraphic shell = getOMGraphic(polygon.getExteriorRing().getCoordinates(), true, renderer, zoomLevel); - - if (numInteriorRings == 0) { - return shell; - } else { - OMGraphicList omgl = new OMGraphicList(); - omgl.add(shell); - for (int i = 0; i < numInteriorRings; i++) { - omgl.add(getOMGraphic(polygon.getInteriorRingN(i).getCoordinates(), true, renderer, zoomLevel)); - } - - return omgl; - } - } - - protected OMGraphic transformMultiPolygon(MultiPolygon mPolygon, StyleDrawingAttributes renderer, int zoomLevel) { - int numGeometries = mPolygon.getNumGeometries(); - OMGraphicList omgl = new OMGraphicList(); - for (int i = 0; i < numGeometries; i++) { - omgl.add(getOMGraphic(((Polygon) mPolygon.getGeometryN(i)).getCoordinates(), true, renderer, zoomLevel)); - } - - return omgl; - } - - protected OMGraphic transformPolyline(LinearRing linearRing, StyleDrawingAttributes renderer, int zoomLevel) { - int numGeometries = linearRing.getNumGeometries(); - if (numGeometries == 1) { - return getOMGraphic(linearRing.getCoordinates(), false, renderer, zoomLevel); - } else { - OMGraphicList omgl = new OMGraphicList(); - for (int i = 0; i < numGeometries; i++) { - omgl.add(getOMGraphic(linearRing.getGeometryN(i).getCoordinates(), false, renderer, zoomLevel)); - } - - return omgl; - } - - } - - protected OMGraphic transformLineString(LineString lineString, StyleDrawingAttributes renderer, int zoomLevel) { - return getOMGraphic(lineString.getCoordinates(), false, renderer, zoomLevel); - } - - protected OMGraphic transformMultiLineString(MultiLineString mlineString, StyleDrawingAttributes renderer, - int zoomLevel) { - int numGeometries = mlineString.getNumGeometries(); - if (numGeometries == 1) { - return getOMGraphic(mlineString.getCoordinates(), false, renderer, zoomLevel); - } else { - OMGraphicList omgl = new OMGraphicList(); - for (int i = 0; i < numGeometries; i++) { - omgl.add(getOMGraphic(mlineString.getGeometryN(i).getCoordinates(), false, renderer, zoomLevel)); - } - - return omgl; - } - } - - protected GeneralPath convertCoords(Coordinate[] coords, boolean isPolygon) { - GeneralPath path = null; - for (Coordinate c : coords) { - if (path == null) { - path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, coords.length); - path.moveTo(c.x, c.y); - } else { - path.lineTo(c.x, c.y); - } - } - - if (isPolygon) { - path.closePath(); - } - - if (coordTransform != null) { - path.transform(coordTransform); - } - - return path; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(VectorOMGraphicFactory.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/BundleX.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/BundleX.java deleted file mode 100644 index 2d0e6ef9d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/BundleX.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.tpk; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.MoreMath; - -/** - * Reads the tpk bundlex file and gathers the indexes for the tiles. You can ask - * this object for the indexes for images, from 0-128, 0-128 range. These - * indexes are column major, and modulo (%128) from the whole earth index for a - * particular zoom level as contained in a compacted bundle file. Open file, - * read, close, then ask for indexes. - * - * @author dietrick - */ -public class BundleX { - - int[][] offsets = new int[128][128]; - - public BundleX(InputStream stream) throws FormatException, IOException { - readFile(stream); - } - - public void readFile(InputStream stream) throws FormatException, EOFException, IOException { - - /* byte[16] header */ stream.skip(16); - - int nextFilePos = -1; - - byte[] bytevec = new byte[5]; - stream.read(bytevec); - int currentFilePos = MoreMath.BuildIntegerLE(bytevec, 0); - - // The images are stored in row major order - for (int x = 0; x < 128; x++) { - for (int y = 0; y < 128; y++) { - stream.read(bytevec); - nextFilePos = MoreMath.BuildIntegerLE(bytevec, 0); - int storedVal = -1; - - if (nextFilePos != currentFilePos + 4) { - storedVal = currentFilePos; - } - - offsets[x][y] = storedVal; - - /* - * if (storedVal != -1) { System.out.println("tile in " + x + - * ", " + y + " " + (storedVal)); } - */ - - currentFilePos = nextFilePos; - - } - } - } - - /** - * Return offset for tile. If the tile doesn't exist in the bundle, return - * -1. - * - * @param x - * column of tile in bundle - * @param y - * row of tile in bundle - * @return int offset into bundle file - */ - public int getOffset(int x, int y) { - return offsets[x][y]; - } - - /** - * This class should display the tiled image from a bundle file as indexed - * in the bundlx file. Just for testing, and it's kinda sloppy. But helpful. - * - * @param args - * the path to a bundlx or bundle file. - */ - public static void main(String[] args) { - try { - - int dotIndex = args[0].indexOf('.'); - if (dotIndex < 0) { - System.out.println("can't figure out the proper extension (bundlx) from the given path"); - System.exit(-1); - } - - String loc = args[0].substring(0, dotIndex); - FileInputStream fis = new FileInputStream(new File(loc + ".bundlx")); - BundleX bx = new BundleX(fis); - fis.close(); - - BinaryBufferedFile bbf = new BinaryBufferedFile(loc + ".bundle"); - - JFrame jFrame = new JFrame(loc); - JPanel top = new JPanel(); - JScrollPane scrollPane = new JScrollPane(top, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - jFrame.getContentPane().add(scrollPane); - - GridBagLayout gridBag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - top.setLayout(gridBag); - - for (int x = 0; x < 128; x++) { - for (int y = 0; y < 128; y++) { - - int i = bx.getOffset(x, y); - if (i > 0) { - - bbf.seek(i); - int length = bbf.readInteger(); - - byte[] imageBytes = bbf.readBytes(length, false); - - ImageIcon ii = new ImageIcon(imageBytes); - JLabel holder = new JLabel(ii); - if (length > 2000) { - c.gridx = x; - c.gridy = y; - - gridBag.setConstraints(holder, c); - - top.add(holder); - } - - } - } - } - - jFrame.setSize(256, 256); - jFrame.validate(); - jFrame.setVisible(true); - - } catch (IOException ioe) { - System.out.println("caught IOException trying to read bundlx file"); - } catch (FormatException fe) { - System.out.println("caught FormatException trying to read bundlx file"); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/MapServerDescription.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/MapServerDescription.java deleted file mode 100644 index 2bc1b1c9f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/MapServerDescription.java +++ /dev/null @@ -1,541 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.tpk; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Parser object for the MapServer json description in a tpk file. Created using - * https://timboudreau.com/blog/json/read, based on an example json document - * downloaded from esri (the ImageryTPK packge). - * - * @author dietrick - * - */ -public final class MapServerDescription { - public final String name; - public final Contents contents; - public final ResourceInfo resourceInfo; - public final Resource resources[]; - - @JsonCreator - public MapServerDescription(@JsonProperty("name") String name, @JsonProperty("contents") Contents contents, - @JsonProperty("resourceInfo") ResourceInfo resourceInfo, - @JsonProperty(value = "resources", required = false) Resource[] resources) { - this.name = name; - this.contents = contents; - this.resourceInfo = resourceInfo; - this.resources = resources; - } - - public String getPathToTiles() { - String[] versionStringArray = Double.toString(contents.currentVersion).replace('.', ':').split(":"); - StringBuilder v = new StringBuilder(); - for (String vs : versionStringArray) { - v.append(vs); - } - return new StringBuilder("v").append(v).append("/").append(contents.mapName).append("/_alllayers").toString(); - } - - public String toString() { - StringBuilder sb = new StringBuilder("MapServerDescription["); - sb.append("mapName:").append(contents.mapName).append(","); - sb.append("version:").append(contents.currentVersion).append(","); - sb.append("singleFusedMapCache:").append(contents.singleFusedMapCache); - sb.append("]"); - return sb.toString(); - } - - public static final class Contents { - public final double currentVersion; - public final String serviceDescription; - public final String mapName; - public final String description; - public final String copyrightText; - public final boolean supportsDynamicLayers; - public final Layer layers[]; - public final Table tables[]; - public final SpatialReference spatialReference; - public final boolean singleFusedMapCache; - public final InitialExtent initialExtent; - public final FullExtent fullExtent; - public final long minScale; - public final long maxScale; - public final String units; - public final String supportedImageFormatTypes; - public final DocumentInfo documentInfo; - public final String capabilities; - public final String supportedQueryFormats; - public final long maxRecordCount; - public final long maxImageHeight; - public final long maxImageWidth; - - @JsonCreator - public Contents(@JsonProperty("currentVersion") double currentVersion, - @JsonProperty("serviceDescription") String serviceDescription, @JsonProperty("mapName") String mapName, - @JsonProperty("description") String description, @JsonProperty("copyrightText") String copyrightText, - @JsonProperty("supportsDynamicLayers") boolean supportsDynamicLayers, - @JsonProperty("layers") Layer[] layers, @JsonProperty("tables") Table[] tables, - @JsonProperty("spatialReference") SpatialReference spatialReference, - @JsonProperty("singleFusedMapCache") boolean singleFusedMapCache, - @JsonProperty("initialExtent") InitialExtent initialExtent, - @JsonProperty("fullExtent") FullExtent fullExtent, @JsonProperty("minScale") long minScale, - @JsonProperty("maxScale") long maxScale, @JsonProperty("units") String units, - @JsonProperty("supportedImageFormatTypes") String supportedImageFormatTypes, - @JsonProperty("documentInfo") DocumentInfo documentInfo, - @JsonProperty("capabilities") String capabilities, - @JsonProperty("supportedQueryFormats") String supportedQueryFormats, - @JsonProperty("maxRecordCount") long maxRecordCount, - @JsonProperty("maxImageHeight") long maxImageHeight, - @JsonProperty("maxImageWidth") long maxImageWidth) { - this.currentVersion = currentVersion; - this.serviceDescription = serviceDescription; - this.mapName = mapName; - this.description = description; - this.copyrightText = copyrightText; - this.supportsDynamicLayers = supportsDynamicLayers; - this.layers = layers; - this.tables = tables; - this.spatialReference = spatialReference; - this.singleFusedMapCache = singleFusedMapCache; - this.initialExtent = initialExtent; - this.fullExtent = fullExtent; - this.minScale = minScale; - this.maxScale = maxScale; - this.units = units; - this.supportedImageFormatTypes = supportedImageFormatTypes; - this.documentInfo = documentInfo; - this.capabilities = capabilities; - this.supportedQueryFormats = supportedQueryFormats; - this.maxRecordCount = maxRecordCount; - this.maxImageHeight = maxImageHeight; - this.maxImageWidth = maxImageWidth; - } - - public static final class Layer { - public final long id; - public final String name; - public final long parentLayerId; - public final boolean defaultVisibility; - public final Object subLayerIds; - public final long minScale; - public final long maxScale; - - @JsonCreator - public Layer(@JsonProperty("id") long id, @JsonProperty("name") String name, - @JsonProperty("parentLayerId") long parentLayerId, - @JsonProperty("defaultVisibility") boolean defaultVisibility, - @JsonProperty("subLayerIds") Object subLayerIds, @JsonProperty("minScale") long minScale, - @JsonProperty("maxScale") long maxScale) { - this.id = id; - this.name = name; - this.parentLayerId = parentLayerId; - this.defaultVisibility = defaultVisibility; - this.subLayerIds = subLayerIds; - this.minScale = minScale; - this.maxScale = maxScale; - } - } - - public static final class Table { - - @JsonCreator - public Table() { - } - } - - public static final class SpatialReference { - public final long wkid; - public final long latestWkid; - - @JsonCreator - public SpatialReference(@JsonProperty("wkid") long wkid, @JsonProperty("latestWkid") long latestWkid) { - this.wkid = wkid; - this.latestWkid = latestWkid; - } - } - - public static final class InitialExtent { - public final double xmin; - public final double ymin; - public final double xmax; - public final double ymax; - public final SpatialReference spatialReference; - - @JsonCreator - public InitialExtent(@JsonProperty("xmin") double xmin, @JsonProperty("ymin") double ymin, - @JsonProperty("xmax") double xmax, @JsonProperty("ymax") double ymax, - @JsonProperty("spatialReference") SpatialReference spatialReference) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - this.spatialReference = spatialReference; - } - - public static final class SpatialReference { - public final long wkid; - public final long latestWkid; - - @JsonCreator - public SpatialReference(@JsonProperty("wkid") long wkid, @JsonProperty("latestWkid") long latestWkid) { - this.wkid = wkid; - this.latestWkid = latestWkid; - } - } - } - - public static final class FullExtent { - public final double xmin; - public final double ymin; - public final double xmax; - public final double ymax; - public final SpatialReference spatialReference; - - @JsonCreator - public FullExtent(@JsonProperty("xmin") double xmin, @JsonProperty("ymin") double ymin, - @JsonProperty("xmax") double xmax, @JsonProperty("ymax") double ymax, - @JsonProperty("spatialReference") SpatialReference spatialReference) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - this.spatialReference = spatialReference; - } - - public static final class SpatialReference { - public final long wkid; - public final long latestWkid; - - @JsonCreator - public SpatialReference(@JsonProperty("wkid") long wkid, @JsonProperty("latestWkid") long latestWkid) { - this.wkid = wkid; - this.latestWkid = latestWkid; - } - } - } - - public static final class DocumentInfo { - public final String title; - public final String author; - public final String comments; - public final String subject; - public final String category; - public final String antialiasingMode; - public final String textAntialiasingMode; - public final String keywords; - - @JsonCreator - public DocumentInfo(@JsonProperty("Title") String title, @JsonProperty("Author") String author, - @JsonProperty("Comments") String comments, @JsonProperty("Subject") String subject, - @JsonProperty("Category") String category, - @JsonProperty("AntialiasingMode") String antialiasingMode, - @JsonProperty("TextAntialiasingMode") String textAntialiasingMode, - @JsonProperty("Keywords") String keywords) { - this.title = title; - this.author = author; - this.comments = comments; - this.subject = subject; - this.category = category; - this.antialiasingMode = antialiasingMode; - this.textAntialiasingMode = textAntialiasingMode; - this.keywords = keywords; - } - } - } - - public static final class ResourceInfo { - public final GeoFullExtent geoFullExtent; - public final SpatialReferenceDomain spatialReferenceDomain; - public final GeoInitialExtent geoInitialExtent; - - @JsonCreator - public ResourceInfo(@JsonProperty("geoFullExtent") GeoFullExtent geoFullExtent, - @JsonProperty("spatialReferenceDomain") SpatialReferenceDomain spatialReferenceDomain, - @JsonProperty("geoInitialExtent") GeoInitialExtent geoInitialExtent) { - this.geoFullExtent = geoFullExtent; - this.spatialReferenceDomain = spatialReferenceDomain; - this.geoInitialExtent = geoInitialExtent; - } - - public static final class GeoFullExtent { - public final double xmin; - public final double ymin; - public final double xmax; - public final double ymax; - - @JsonCreator - public GeoFullExtent(@JsonProperty("xmin") double xmin, @JsonProperty("ymin") double ymin, - @JsonProperty("xmax") double xmax, @JsonProperty("ymax") double ymax) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - } - } - - public static final class SpatialReferenceDomain { - public final long xmin; - public final long ymin; - public final long xmax; - public final long ymax; - - @JsonCreator - public SpatialReferenceDomain(@JsonProperty("xmin") long xmin, @JsonProperty("ymin") long ymin, - @JsonProperty("xmax") long xmax, @JsonProperty("ymax") long ymax) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - } - } - - public static final class GeoInitialExtent { - public final double xmin; - public final double ymin; - public final double xmax; - public final double ymax; - - @JsonCreator - public GeoInitialExtent(@JsonProperty("xmin") double xmin, @JsonProperty("ymin") double ymin, - @JsonProperty("xmax") double xmax, @JsonProperty("ymax") double ymax) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - } - } - } - - public static final class Resource { - public final String name; - public final RResource resources[]; - public final Contents contents; - - @JsonCreator - public Resource(@JsonProperty("name") String name, @JsonProperty("resources") RResource[] resource, - @JsonProperty("contents") Contents contents) { - this.name = name; - this.resources = resource; - this.contents = contents; - } - - public static final class RResource { - public final String name; - public final Contents contents; - - @JsonCreator - public RResource(@JsonProperty("name") String name, @JsonProperty("contents") Contents contents) { - this.name = name; - this.contents = contents; - } - - public static final class Contents { - public final double currentVersion; - public final long id; - public final String name; - public final String type; - public final String description; - public final String definitionExpression; - public final GeometryType geometryType; - public final String copyrightText; - public final ParentLayer parentLayer; - public final SubLayer subLayers[]; - public final long minScale; - public final long maxScale; - public final boolean defaultVisibility; - public final Extent extent; - public final boolean hasAttachments; - public final HtmlPopupType htmlPopupType; - public final String displayField; - public final TypeIdField typeIdField; - public final Fields fields; - public final Relationship relationships[]; - public final boolean canModifyLayer; - public final boolean canScaleSymbols; - public final boolean hasLabels; - public final String capabilities; - public final boolean supportsStatistics; - public final boolean supportsAdvancedQueries; - public final String supportedQueryFormats; - - @JsonCreator - public Contents(@JsonProperty("currentVersion") double currentVersion, @JsonProperty("id") long id, - @JsonProperty("name") String name, @JsonProperty("type") String type, - @JsonProperty("description") String description, - @JsonProperty("definitionExpression") String definitionExpression, - @JsonProperty("geometryType") GeometryType geometryType, - @JsonProperty("copyrightText") String copyrightText, - @JsonProperty("parentLayer") ParentLayer parentLayer, - @JsonProperty("subLayers") SubLayer[] subLayers, @JsonProperty("minScale") long minScale, - @JsonProperty("maxScale") long maxScale, - @JsonProperty("defaultVisibility") boolean defaultVisibility, - @JsonProperty("extent") Extent extent, @JsonProperty("hasAttachments") boolean hasAttachments, - @JsonProperty("htmlPopupType") HtmlPopupType htmlPopupType, - @JsonProperty("displayField") String displayField, - @JsonProperty("typeIdField") TypeIdField typeIdField, @JsonProperty("fields") Fields fields, - @JsonProperty("relationships") Relationship[] relationships, - @JsonProperty("canModifyLayer") boolean canModifyLayer, - @JsonProperty("canScaleSymbols") boolean canScaleSymbols, - @JsonProperty("hasLabels") boolean hasLabels, @JsonProperty("capabilities") String capabilities, - @JsonProperty("supportsStatistics") boolean supportsStatistics, - @JsonProperty("supportsAdvancedQueries") boolean supportsAdvancedQueries, - @JsonProperty("supportedQueryFormats") String supportedQueryFormats) { - this.currentVersion = currentVersion; - this.id = id; - this.name = name; - this.type = type; - this.description = description; - this.definitionExpression = definitionExpression; - this.geometryType = geometryType; - this.copyrightText = copyrightText; - this.parentLayer = parentLayer; - this.subLayers = subLayers; - this.minScale = minScale; - this.maxScale = maxScale; - this.defaultVisibility = defaultVisibility; - this.extent = extent; - this.hasAttachments = hasAttachments; - this.htmlPopupType = htmlPopupType; - this.displayField = displayField; - this.typeIdField = typeIdField; - this.fields = fields; - this.relationships = relationships; - this.canModifyLayer = canModifyLayer; - this.canScaleSymbols = canScaleSymbols; - this.hasLabels = hasLabels; - this.capabilities = capabilities; - this.supportsStatistics = supportsStatistics; - this.supportsAdvancedQueries = supportsAdvancedQueries; - this.supportedQueryFormats = supportedQueryFormats; - } - - public static final class GeometryType { - - @JsonCreator - public GeometryType() { - } - } - - public static final class ParentLayer { - - @JsonCreator - public ParentLayer() { - } - } - - public static final class SubLayer { - - @JsonCreator - public SubLayer() { - } - } - - public static final class Extent { - public final double xmin; - public final double ymin; - public final double xmax; - public final double ymax; - public final SpatialReference spatialReference; - - @JsonCreator - public Extent(@JsonProperty("xmin") double xmin, @JsonProperty("ymin") double ymin, - @JsonProperty("xmax") double xmax, @JsonProperty("ymax") double ymax, - @JsonProperty("spatialReference") SpatialReference spatialReference) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - this.spatialReference = spatialReference; - } - - public static final class SpatialReference { - public final long wkid; - public final long latestWkid; - - @JsonCreator - public SpatialReference(@JsonProperty("wkid") long wkid, - @JsonProperty("latestWkid") long latestWkid) { - this.wkid = wkid; - this.latestWkid = latestWkid; - } - } - } - - public static final class HtmlPopupType { - - @JsonCreator - public HtmlPopupType() { - } - } - - public static final class TypeIdField { - - @JsonCreator - public TypeIdField() { - } - } - - public static final class Fields { - - @JsonCreator - public Fields() { - } - } - - public static final class Relationship { - - @JsonCreator - public Relationship() { - } - } - } - } - - public static final class Contents { - public final Layer layers[]; - - @JsonCreator - public Contents(@JsonProperty("layers") Layer[] layers) { - this.layers = layers; - } - - public static final class Layer { - public final long layerId; - public final String layerName; - public final String layerType; - public final long minScale; - public final long maxScale; - public final Legend legend[]; - - @JsonCreator - public Layer(@JsonProperty("layerId") long layerId, @JsonProperty("layerName") String layerName, - @JsonProperty("layerType") String layerType, @JsonProperty("minScale") long minScale, - @JsonProperty("maxScale") long maxScale, @JsonProperty("legend") Legend[] legend) { - this.layerId = layerId; - this.layerName = layerName; - this.layerType = layerType; - this.minScale = minScale; - this.maxScale = maxScale; - this.legend = legend; - } - - public static final class Legend { - public final String label; - public final String url; - public final String imageData; - public final String contentType; - - @JsonCreator - public Legend(@JsonProperty("label") String label, @JsonProperty("url") String url, - @JsonProperty("imageData") String imageData, - @JsonProperty("contentType") String contentType) { - this.label = label; - this.url = url; - this.imageData = imageData; - this.contentType = contentType; - } - } - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkMapTileFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkMapTileFactory.java deleted file mode 100644 index 638acae80..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkMapTileFactory.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.tpk; - -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * MapTileFactory that tries to pull images from a TPK package. TPKs are - * actually zip files containing a bunch of stuff. - * - * @author dietrick - * - */ -public class TpkMapTileFactory extends StandardMapTileFactory { - - public final static String TPK_FILE_PROPERTY = "tpk"; - - protected String tpkLocation; - protected TpkReader tpkReader; - - public TpkMapTileFactory() { - logger.fine("Using TpkMapTileFactory"); - setRootDir("TPK"); - } - - /** - * Loads the tile from the bundle file, after consulting the tpkReader where - * it might be and what bundle file to check. - * - * @param key - * the cache key for this tile - * @param x - * the world x index for tile - * @param y - * the world y index for tile - * @param zoomLevel - * the zoom level of current projection - * @param proj - * the current map projection - * @return a CacheObject that contains the tile. - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - if (tpkReader != null) { - String pathToTiles = tpkReader.getPathToTiles(); - - StringBuilder bundleName = new StringBuilder(pathToTiles).append("/L"); - if (zoomLevel < 10) { - bundleName.append("0"); - } - bundleName.append(zoomLevel).append("/"); - - // Does packetsize from conf.xml make a difference here? For - // now, assume 128 - int row = (y / 128) * 128; - int col = (x / 128) * 128; - - String rowPart = Integer.toHexString(row); - String colPart = Integer.toHexString(col); - - while (rowPart.length() < 4) { - rowPart = "0" + rowPart; - } - while (colPart.length() < 4) { - colPart = "0" + colPart; - } - - bundleName.append("R").append(rowPart).append("C").append(colPart); - String bundlxName = new StringBuilder(bundleName).append(".bundlx").toString(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("looking for tile in " + bundleName.toString()); - } - - try { - InputStream is = tpkReader.getStream(bundlxName); - BundleX bundlex = new BundleX(is); - is.close(); - - int rowIndex = y % 128; - int colIndex = x % 128; - - int offset = bundlex.getOffset(colIndex, rowIndex); - - if (offset != -1) { - InputStream bundleStream = tpkReader.getStream(bundleName.append(".bundle").toString()); - bundleStream.skip(offset); - - // int length = bbf.readInteger(); - byte[] lengthVec = new byte[4]; - bundleStream.read(lengthVec); - int length = MoreMath.BuildIntegerLE(lengthVec, 0); - - byte[] imageBytes = new byte[length]; - read(bundleStream, imageBytes, 0, imageBytes.length); - bundleStream.close(); - - if (imageBytes != null && imageBytes.length > 2000) { - // image found - ImageIcon ii = new ImageIcon(imageBytes); - - try { - BufferedImage rasterImage = preprocessImage(ii.getImage(), ii.getIconWidth(), - ii.getIconHeight()); - OMGraphic raster = createOMGraphicFromBufferedImage(rasterImage, x, y, zoomLevel, proj); - - /* - * Again, create a CacheObject based on the - * local name if the local dir is defined. - */ - if (raster != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("building" + key); - } - - return new CacheObject(key, raster); - } - - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("factory interrupted fetching " + key); - } - } - - } - } - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (FormatException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } else { - if (!warningIssued) { - logger.warning("TpkMapTileFactory: tpkReader is not configured properly."); - warningIssued = true; - } - } - - } - return null; - } - - private boolean warningIssued = false; - - public int read(InputStream inputStream, byte b[], int off, int len) throws IOException { - - if (inputStream == null) { - throw new IOException("Stream closed"); - } - - int gotsofar = 0; - while (gotsofar < len) { - int read = inputStream.read(b, off + gotsofar, len - gotsofar); - if (read == -1) { - if (gotsofar > 0) { - // Hit the EOF in the middle of the loop. - return gotsofar; - } else { - return read; - } - } else { - gotsofar += read; - } - } - - return gotsofar; - } - - protected BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - return BufferedImageHelper.getBufferedImage(origImage, 0, 0, 256, 256, BufferedImage.TYPE_INT_ARGB); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String tpkLoc = props.getProperty(prefix + TPK_FILE_PROPERTY); - if (tpkLoc != null) { - loadTpk(tpkLoc); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + TPK_FILE_PROPERTY, PropUtils.unnull(tpkLocation)); - - return props; - } - - protected void loadTpk(String tpkLoc) { - try { - - this.tpkReader = new TpkReader(tpkLoc); - this.tpkLocation = tpkLoc; - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoClassDefFoundError ncdfe) { - logger.warning("TPK package requires the Jackson JSON package, ObjectMapper not found."); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkReader.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkReader.java deleted file mode 100644 index 239c35d6a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/mapTile/tpk/TpkReader.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile.tpk; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.logging.Logger; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import com.bbn.openmap.util.PropUtils; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Simple TPK reader that loads the mapserver.json in the tpk package to get the - * imagery path. Uses the MapServerDescription object to parse the json file. - * - * @author dietrick - */ -public class TpkReader { - - public final String SERVICE_DESCRIPTION_LOCATION = "servicedescriptions/mapserver/mapserver.json"; - - protected String pathToTiles; - protected ZipFile tpkFile; - - private Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile.tpk.TpkReader"); - - public TpkReader(String tpkLocation) throws IOException, NoClassDefFoundError { - - tpkFile = new ZipFile(tpkLocation); - - ZipEntry descriptionEntry = tpkFile.getEntry(SERVICE_DESCRIPTION_LOCATION); - - if (descriptionEntry != null) { - InputStream zipStream = tpkFile.getInputStream(descriptionEntry); - MapServerDescription mapServerDescription = loadJSON(zipStream); - zipStream.close(); - - pathToTiles = mapServerDescription.getPathToTiles(); - } - - } - - /** - * Get an input stream for an entry that should be there. - * - * @param entryString entry path, relative to internal root of zip file - * @throws IOException - */ - public InputStream getStream(String entryString) throws IOException { - if (tpkFile != null) { - ZipEntry ze = tpkFile.getEntry(entryString); - if (ze != null) { - return tpkFile.getInputStream(ze); - } - } - return null; - } - - /** - * Returns the parent directory of the Level directories. From here you can - * find the Lzz directories that contains the bundle and bundlx files - * containing the images. - * - * @return path to Lzz directories - */ - public String getPathToTiles() { - return pathToTiles; - } - - /** - * Load the JSON file describing the tpk contents. - * - * @param urlString path to json file. - * @return MapServerDescription with json contents. - */ - public MapServerDescription loadJSON(String urlString) { - if (urlString != null) { - URL input; - try { - input = PropUtils.getResourceOrFileOrURL(urlString); - - InputStream inputStream = input.openStream(); - return loadJSON(inputStream); - - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoClassDefFoundError ncdfe) { - logger.warning("The TPK reading code needs Jackson JSON package in the classpath"); - } - } - - return null; - } - - /** - * Load the JSON file describing the tpk contents, given an input stream. - * - * @param jsonStream stream for the json file - * @return MapServerDescription with json contents, or null of something wh - */ - public MapServerDescription loadJSON(InputStream jsonStream) throws IOException { - return new ObjectMapper().readValue(jsonStream, MapServerDescription.class); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/package.html deleted file mode 100644 index 3af060495..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -Packages that provide read and/or write access to different data types. - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfFile.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfFile.java deleted file mode 100644 index 949d54eb4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfFile.java +++ /dev/null @@ -1,566 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/DbfFile.java,v $ -// $RCSfile: DbfFile.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.EOFException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URL; -import java.text.DecimalFormatSymbols; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import com.bbn.openmap.dataAccess.shape.output.DbfOutputStream; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; - -/** - * An extension to DbfTableModel that handles reading only certain records when - * needed, in conjunction with some spatial indexing mechanism. Can be told to - * which columns to read and which to skip, so unnecessary/unused information - * isn't held in memory. - * - * @author dietrick - */ -public class DbfFile - extends DbfTableModel { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected int _rowCount; - protected int _recordLength; - protected int _headerLength; - /** - * This _columnMask variable is an array that either contains a Boolean.TRUE - * for the indexes for columns that should be read, or a Integer object that - * contains the byte length of the column entry, so the reader will know how - * many bytes to skip for columns being ignored. The _length array contents - * were modified to reflect the lengths of only the columns being read when - * the column mask was set, as was the _names, _types, and _decimalCount - * arrays. The order and length of those arrays match the order of the - * Boolean.TRUE objects in the _columnMask array. - */ - protected Object[] _columnMask = null; - protected java.text.DecimalFormat df; - protected BinaryFile bf; - - protected DbfFile() { - df = new java.text.DecimalFormat(); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH); - df.setDecimalFormatSymbols(dfs); - } - - /** - * Creates a blank DbfTableModel - * - * @param columnCount The number of columns this model will manage - */ - public DbfFile(int columnCount) { - this(); - _columnCount = columnCount; - _records = new ArrayList>(); - _lengths = new int[columnCount]; - _decimalCounts = new byte[columnCount]; - _types = new byte[columnCount]; - _names = new String[columnCount]; - } - - public DbfFile(BinaryFile bf) - throws EOFException, FormatException, IOException { - this(); - setBinaryFile(bf); - } - - public void readHeader(BinaryFile bf) - throws FormatException, IOException { - try { - bf.seek(0); - bf.byteOrder(false); - /* byte description = */bf.read(); - /* byte year = */bf.read(); - /* byte month = */bf.read(); - /* byte day = */bf.read(); - _rowCount = bf.readInteger(); - _headerLength = bf.readShort(); - _recordLength = bf.readShort(); - _columnCount = (_headerLength - 32 - 1) / 32; - bf.skipBytes(20); - - _names = new String[_columnCount]; - _types = new byte[_columnCount]; - _lengths = new int[_columnCount]; - _decimalCounts = new byte[_columnCount]; - - for (int n = 0; n <= _columnCount - 1; n++) { - // 32 bytes for each column - - _names[n] = bf.readFixedLengthString(11); - // - // Some TIGER dbf files from ESRI have nulls - // in the column names. Delete them. - // - int ix = _names[n].indexOf((char) 0); - if (ix > 0) { - _names[n] = _names[n].substring(0, ix); - } - _types[n] = (byte) bf.read(); - bf.skipBytes(4); - _lengths[n] = bf.readUnsigned(); - _decimalCounts[n] = (byte) bf.read(); - bf.skipBytes(14); - } - - if (DEBUG && _headerLength != bf.getFilePointer()) { - Debug.output("DbfFile: Header length specified in file doesn't match current pointer location"); - } - - } catch (EOFException eofe) { - throw new FormatException(eofe.getMessage()); - } - } - - /** - * Tells the BinaryFile input reader to close, releasing the file pointer. - * Will automatically reopen if necessary. - */ - public void close() { - if (bf != null) { - try { - bf.close(); - } catch (IOException e) { - if (Debug.debugging("shape")) { - e.printStackTrace(); - } - } - } - } - - /** - * Reads the data and puts data in an ArrayList of records. - */ - public void readData() - throws IOException, FormatException { - readData(0, _rowCount); - } - - /** - * Read in a set of records from the dbf file, starting at the provided - * index and continuing for the provided count. - * - * @param startingRecordIndex , 0 is the first record index. - * @param numRecordsToRead - * @throws IOException - * @throws FormatException - */ - public void readData(int startingRecordIndex, int numRecordsToRead) - throws IOException, FormatException { - if (startingRecordIndex < 0) { - startingRecordIndex = 0; - } - - if (numRecordsToRead < 0 || numRecordsToRead > _rowCount - startingRecordIndex) { - numRecordsToRead = _rowCount - startingRecordIndex; - } - - _records = new ArrayList>(numRecordsToRead); - for (int r = startingRecordIndex; r <= numRecordsToRead - 1; r++) { - List record = getRecordData(r); - _records.add(record); - } - } - - /** - * Fetches the record data for the given index. - * - * @param index the index of the data, starting at 0 for the first record. - * @return List containing Strings and Numbers for the dbf entry for the - * record. - * @throws IOException - * @throws FormatException - */ - public List getRecordData(int index) - throws IOException, FormatException { - if (bf == null) { - throw new IOException("DbfFile not set with valid BinaryFile."); - } - - bf.seek(_headerLength + index * _recordLength); - - /* int deleteFlag = */bf.read(); - int columnCount = _columnCount; - if (_columnMask != null) { - columnCount = _columnMask.length; - } - - // Here, even with the columnMask, the _columnCount is the target number - // of columns to be stored out of the dbf file. The _columnMask.length - // is the number of columns actually in the file (if that array is not - // null). - ArrayList record = new ArrayList(_columnCount); - int targetColumnIndex = 0; - for (int c = 0; c <= columnCount - 1; c++) { - - if (_columnMask == null || _columnMask[c] == Boolean.TRUE) { - int length = _lengths[targetColumnIndex]; - if (length == -1) - length = 255; - int type = _types[targetColumnIndex]; - int numDecSpaces = _decimalCounts[targetColumnIndex]; - df.setMaximumFractionDigits(numDecSpaces); - String cell = bf.readFixedLengthString(length).trim(); - Object obj = cell; - try { - obj = getObjectForType(cell, type, df, length); - } catch (ParseException pe) { - // Don't need to do anything, obj == cell; - } - record.add(targetColumnIndex, obj); - targetColumnIndex++; - } else { - bf.skipBytes(((Integer) _columnMask[c]).intValue()); - } - } - return record; - } - - /** - * Clear the record information from memory. - * - */ - public void clearRecords() { - if (_records != null) { - _records.clear(); - } - } - - /** - * Create another DbfTableModel with the same structure as this one (number - * of columns, column names, lengths and decimal counts). - */ - public DbfTableModel headerClone() { - int size = getColumnCount(); - DbfFile dtm = new DbfFile(size); - for (int i = 0; i < size; i++) { - dtm.setColumnName(i, this.getColumnName(i)); - dtm.setDecimalCount(i, this.getDecimalCount(i)); - dtm.setLength(i, this.getLength(i)); - dtm.setType(i, this.getType(i)); - } - return dtm; - } - - /** - * Creates a DbfTableModel for a given .dbf file - * - * @param dbf The url of the file to retrieve. - * @return The DbfTableModel, null if there is a problem. - */ - public static DbfTableModel getDbfTableModel(URL dbf) { - return getDbfTableModel(dbf.toString()); - } - - /** - * Creates a DbfTableModel for a given .dbf file - * - * @param dbf The path of the file to retrieve. - * @return The DbfTableModel, null if there is a problem. - */ - public static DbfTableModel getDbfTableModel(String dbf) { - DbfFile model = null; - try { - BinaryBufferedFile bbf = new BinaryBufferedFile(dbf); - model = new DbfFile(bbf); - model.close(); - } catch (Exception exception) { - if (Debug.debugging("shape")) { - Debug.error("problem loading DBF file" + exception.getMessage()); - } - } - return model; - } - - public static void main(String[] args) { - Debug.init(); - ArgParser ap = new ArgParser("DbfFile"); - ap.add("columns", "Print field header information."); - ap.add("mask", "Only show listed columns", -1); - ap.add("source", "The dbf file to read.", 1); - ap.add("target", "The dbf file to write, use with mask to remove columns into new dbf file.", 1); - ap.add("num", "Specify the number of records to read and display (handy for large dbf files)", 1); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String source = null; - String target = null; - double num = Double.MAX_VALUE; - - String[] ags = ap.getArgValues("source"); - if (ags != null) { - source = ags[0]; - } else { - source = FileUtils.getFilePathToOpenFromUser("Choose DBF file"); - if (source == null) { - System.exit(0); - } - } - - ags = ap.getArgValues("target"); - if (ags != null) { - target = ags[0]; - } - - boolean readData = ap.getArgValues("columns") == null; - - if (!readData) { - num = 0; - } else { - ags = ap.getArgValues("num"); - if (ags != null) { - try { - num = Double.parseDouble(ags[0]); - } catch (NumberFormatException nfe) { - } - } - } - - String[] columnMask = ap.getArgValues("mask"); - String[] columns = ap.getArgValues("columns"); - - try { - - DbfFile dtm = (DbfFile) DbfFile.getDbfTableModel(source); - - if (dtm == null) { - System.out.println("Problem reading " + source); - System.exit(-1); - } else { - - if (columns != null) { - dtm.setColumnMask(columnMask); - } - - dtm.readData(0, (int) num); - - if (target != null) { - OutputStream os = new FileOutputStream(target); - DbfOutputStream dos = new DbfOutputStream(os); - dos.writeModel(dtm); - } else { - dtm.setWritable(true); - dtm.exitOnClose = true; - dtm.showGUI(args[0], MODIFY_ROW_MASK | MODIFY_COLUMN_MASK | SAVE_MASK); - } - } - - } catch (Exception e) { - Debug.error(e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Checks the _columnMask Object[] and looks for Boolean.TRUE objects, - * indicating a column that should be used. Returns a boolean[] with trues - * in the indexes for those columns. - * - * @return boolean[] representing columns, true values should be used. - */ - public boolean[] getColumnMask() { - boolean[] columnMask = new boolean[_columnMask.length]; - for (int i = 0; i < _columnMask.length; i++) { - columnMask[i] = _columnMask[i] == Boolean.TRUE; - } - return columnMask; - } - - /** - * Given a boolean[] where trues mark columns to keep, a _columnMask - * Object[] is set on this object with Boolean.TRUE objects in that array - * for the trues, and Integer objects representing the lengths of the false - * columns. The lengths are used when reading the dbf file, so it's known - * how many bytes to skip for that column. - * - * @param mask - */ - protected void createColumnMaskArray(boolean[] mask) { - if (mask != null && mask.length <= _columnCount) { - _columnMask = new Object[mask.length]; - for (int i = 0; i < mask.length; i++) { - if (mask[i] == true) { - _columnMask[i] = Boolean.TRUE; - } else { - _columnMask[i] = new Integer(_lengths[i]); - } - } - resolveColumns(); - } - } - - /** - * Limit which columns are read from the dbf file using a boolean array - * corresponding to the columns. For indexes in the array marked true, those - * columns will be read. If the column mask has already been set, the dbf - * file header will be re-read to reset the metadata for the file. - * - * @param mask - */ - public void setColumnMask(boolean[] mask) { - try { - if (_columnMask != null) { - readHeader(bf); - } - } catch (Exception e) { - Debug.error("problem setting column mask for DbfFile" + e.getMessage()); - } - createColumnMaskArray(mask); - } - - /** - * Limit which columns are read from the dbf file using the column names. If - * the column mask has already been set, the dbf file header will be re-read - * to reset the metadata for the file. - * - * @param columnNames - */ - public void setColumnMask(String[] columnNames) { - try { - if (_columnMask != null) { - readHeader(bf); - } - } catch (Exception e) { - Debug.error("problem setting column mask for DbfFile" + e.getMessage()); - } - if (columnNames != null && _names != null) { - boolean[] mask = new boolean[_names.length]; - for (int j = 0; j < _names.length; j++) { - for (int i = 0; i < columnNames.length; i++) { - if (_names[j].equalsIgnoreCase(columnNames[i])) { - mask[j] = true; - break; - } - } - } - createColumnMaskArray(mask); - } - } - - /** - * Sets the metadata for the dbf file to match the current _columnMask - * settings. - */ - protected void resolveColumns() { - if (_columnMask != null && _columnMask.length == _columnCount) { - int newColumnCount = 0; - - for (int i = 0; i < _columnMask.length; i++) { - if (_columnMask[i] == Boolean.TRUE) { - newColumnCount++; - } - } - - ArrayList> records = null; - if (_records != null) { - records = new ArrayList>(_rowCount); - } - int[] lengths = new int[newColumnCount]; - byte[] decimalCounts = new byte[newColumnCount]; - byte[] types = new byte[newColumnCount]; - String[] names = new String[newColumnCount]; - int newIndex = 0; - for (int i = 0; i < _columnMask.length; i++) { - if (_columnMask[i] == Boolean.TRUE) { - lengths[newIndex] = _lengths[i]; - decimalCounts[newIndex] = _decimalCounts[i]; - types[newIndex] = _types[i]; - names[newIndex] = _names[i]; - if (records != null) { - records.add(_records.get(i)); - } - newIndex++; - } - } - - _lengths = lengths; - _decimalCounts = decimalCounts; - _types = types; - _names = names; - _columnCount = newColumnCount; - if (records != null) { - _records = records; - } - } - } - - public int getHeaderLength() { - return _headerLength; - } - - public void setHeaderLength(int length) { - _headerLength = length; - } - - public int getRecordLength() { - return _recordLength; - } - - public void setRecordLength(int length) { - _recordLength = length; - } - - public int getRowCount() { - return _rowCount; - } - - public void setRowCount(int count) { - _rowCount = count; - } - - public BinaryFile getBinaryFile() { - return bf; - } - - public void setBinaryFile(BinaryFile bf) - throws EOFException, FormatException, IOException { this.bf = bf; - readHeader(bf); - } - - public java.text.DecimalFormat getDecimalFormat() { - return df; - } - - public void setDecimalFormat(java.text.DecimalFormat df) { - this.df = df; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfHandler.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfHandler.java deleted file mode 100644 index fae38d594..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfHandler.java +++ /dev/null @@ -1,218 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: DbfHandler.java,v $ -//$Revision: 1.7 $ -//$Date: 2008/11/11 00:35:52 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.rule.IndexRule; -import com.bbn.openmap.omGraphics.rule.Rule; -import com.bbn.openmap.omGraphics.rule.RuleHandler; -import com.bbn.openmap.util.PropUtils; - -/** - * The DbfHandler manages OMGraphics based on DBF file settings. It uses Rules - * to evaluate DBF record information for each OMGraphic that is given to it, - * and can set rendering settings, labels, visibility and information text based - * on those rules. If rules aren't defined, then the dbf file won't be read for - * each entry and any evaluation attempt will just return the OMGraphic as it - * was provided. - * - *

- * Properties as an example used within the ShapeLayer: - * - *

- * 
- * neroads.class=com.bbn.openmap.layer.shape.ShapeLayer
- * neroads.prettyName=Roads
- * neroads.shapeFile=roads.shp
- * neroads.mouseModes=Gestures
- * # Rule marker names specified in space-separated list
- * neroads.rules=rule0 rule1
- * # global scale settings can be used so work is only performed within scale range of minScale/maxScale
- * neroads.maxScale=1000000f
- * 
- * # rule0 definition:
- * # CLASS_RTE is a DBF column name
- * neroads.rule0.key=CLASS_RTE
- * # operation, if key value is less than 2
- * neroads.rule0.op=lt
- * neroads.rule0.val=2
- * # If rule is met, then actions can be performed:
- * # Column names can be added together in a label by specifying them in a space-separated list
- * neroads.rule0.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * # Labels can have scale limits imposed, so they don't appear if map scale is 
- * # greater than maxScale or less than minScale
- * neroads.rule0.label.maxScale=1000000
- * # Visibility can be controlled with respect to scale as well
- * neroads.rule0.render=true
- * neroads.rule0.render.maxScale=1000000
- * # Rendering attributes can be specified.
- * neroads.rule0.lineColor=FFFA73
- * neroads.rule0.lineWidth=4
- * neroads.rule0.mattingColor=55AAAAAA
- * 
- * # rule1 definition:
- * neroads.rule1.key=CLASS_RTE
- * neroads.rule1.op=all
- * neroads.rule1.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * neroads.rule1.label.maxScale=200000
- * neroads.rule1.render=true
- * neroads.rule1.render.maxScale=500000
- * neroads.rule1.lineColor=FFFFFF
- * neroads.rule1.lineWidth=3
- * neroads.rule1.mattingColor=55AAAAAA
- * 
- * 
- * - * @author dietrick - */ -public class DbfHandler extends RuleHandler> { - - protected DbfFile dbf; - protected List> rules; - protected DrawingAttributes defaultDA; - - protected DbfHandler() { - defaultDA = new DrawingAttributes(); - } - - public DbfHandler(String dbfFilePath) throws IOException, FormatException { - this(new BinaryFile(dbfFilePath)); - } - - public DbfHandler(BinaryFile bf) throws IOException, FormatException { - this(); - dbf = new DbfFile(bf); - dbf.close(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - defaultDA.setProperties(prefix, props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - defaultDA.getProperties(props); - - return props; - } - - public DbfFile getDbf() { - return dbf; - } - - public void setDbf(DbfFile dbf) { - this.dbf = dbf; - } - - public DrawingAttributes getDefaultDA() { - return defaultDA; - } - - public void setDefaultDA(DrawingAttributes defaultDA) { - this.defaultDA = defaultDA; - } - - /** - * Tells the DbfFile to close the file pointer to the data. Will reopen if - * needed. - */ - public void close() { - if (dbf != null) { - dbf.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.omGraphics.RuleHandler#createRule() - */ - @Override - public Rule> createRule() { - return new DbfRule(dbf); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.omGraphics.RuleHandler#getRecordDataForOMGraphic(com. - * bbn.openmap.omGraphics.OMGraphic) - */ - @Override - public List getRecordDataForOMGraphic(OMGraphic omg) { - try { - return (List) dbf.getRecordData((Integer) omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - } catch (IOException ioe) { - - } catch (FormatException fe) { - - } - return null; - } - - public class DbfRule extends IndexRule { - DbfFile dbf; - - public DbfRule(DbfFile dbf) { - this.dbf = dbf; - } - - /** - * A record List for the attributes of an OMGraphic might have a name - * for each entry. Given a name, provide the index into the List to get - * that attribute value. - * - * @param columnName name of a attribute in a List, like a column name - * of a list of lists. - * @return the int index of the entry in the record List. - */ - public int getRecordColumnIndexForName(String columnName) { - return dbf.getColumnIndexForName(columnName); - } - - /** - * Provide the title of the attribute at a specific entry. - * - * @param index into the record List. - * @return the record List name for that index. - */ - public String getRecordColumnName(int index) { - return dbf.getColumnName(index); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModel.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModel.java deleted file mode 100644 index 05255617e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModel.java +++ /dev/null @@ -1,1222 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/openmap/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/DbfTableModel.java,v $ -// $RCSfile: DbfTableModel.java,v $ -// $Revision: 1.18 $ -// $Date: 2009/02/05 18:47:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListSelectionModel; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableCellRenderer; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.dataAccess.shape.input.DbfInputStream; -import com.bbn.openmap.dataAccess.shape.output.DbfOutputStream; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * An implementation of TableModel that manages tabular data read from a dbf - * file and enables the user to stored data store herein to be saved to a file - * conforming to the DBF III file format specification. - * - * To create a three one column model: - * - *
- * DbfTableModel model = new DbfTableModel(1);
- * 
- * model.setDecimalCount(0, (byte) 0);
- * model.setLength(0, (byte) 10);
- * model.setColumnName(0, "Column1");
- * model.setType(0, (byte) DbfTableModel.TYPE_CHARACTER);
- * 
- * model.setDecimalCount(1, (byte) 0);
- * model.setLength(1, (byte) 10);
- * model.setColumnName(1, "Column1");
- * model.setType(1, (byte) DbfTableModel.TYPE_NUMERIC);
- * 
- * model.setDecimalCount(2, (byte) 0);
- * model.setLength(2, (byte) 10);
- * model.setColumnName(2, "Column1");
- * model.setType(2, (byte) DbfTableModel.TYPE_CHARACTER);
- * 
- * esriLayer.setModel(model);
- * 
- * - * @author Doug Van Auken - */ -public class DbfTableModel extends AbstractTableModel - implements ShapeConstants, TableModelListener, Iterable> { - - /* - * Binary, Memo, OLE Fields and .DBT Files Binary, memo, and OLE fields - * store data in .DBT files consisting of blocks numbered sequentially (0, - * 1, 2, etc.). SET BLOCKSIZE determines the size of each block. The first - * block in the .DBT file, block 0, is the .DBT file header. Each binary, - * memo, or OLE field of each record in the .DBF file contains the number of - * the block (in OEM code page values) where the field's data actually - * begins. If a field contains no data, the .DBF file contains blanks (0x20) - * rather than a number. When data is changed in a field, the block numbers - * may also change and the number in the .DBF may be changed to reflect the - * new location. - */ - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.DbfTableModel"); - - private static final long serialVersionUID = 1L; - /** - * 10 digits representing a .DBT block number. The number is stored as a - * string, right justified and padded with blanks. - */ - public static final byte TYPE_BINARY = 'B'; - /** - * All OEM code page characters - padded with blanks to the width of the - * field. - */ - public static final byte TYPE_CHARACTER = 'C'; - /** 8 bytes - date stored as a string in the format YYYYMMDD. */ - public static final byte TYPE_DATE = 'D'; - /** - * Number stored as a string, right justified, and padded with blanks to the - * width of the field. - */ - public static final byte TYPE_NUMERIC = 'N'; - /** 1 byte - initialized to 0x20 (space) otherwise T or F. */ - public static final byte TYPE_LOGICAL = 'L'; - /** - * 10 digits (bytes) representing a .DBT block number. The number is stored - * as a string, right justified and padded with blanks. - */ - public static final byte TYPE_MEMO = 'M'; - /** - * 8 bytes - two longs, first for date, second for time. The date is the - * number of days since 01/01/4713 BC. Time is hours * 3600000L + minutes * - * 60000L + Seconds * 1000L - */ - public static final byte TYPE_TIMESTAMP = '@'; - /** 4 bytes. Leftmost bit used to indicate sign, 0 negative. */ - public static final byte TYPE_LONG = 'I'; - /** Same as a Long */ - public static final byte TYPE_AUTOINCREMENT = '+'; - /** - * Number stored as a string, right justified, and padded with blanks to the - * width of the field. - */ - public static final byte TYPE_FLOAT = 'F'; - /** 8 bytes - no conversions, stored as a double. */ - public static final byte TYPE_DOUBLE = 'O'; - /** - * 10 digits (bytes) representing a .DBT block number. The number is stored - * as a string, right justified and padded with blanks. - */ - public static final byte TYPE_OLE = 'G'; - - /** - * Edit button mask, to allow adding/removing rows. Be very careful with - * this option if you plan on using this file with a shape file - the number - * of records has to match the number of graphics in a shape file, so if you - * add or delete, you should add/delete the graphic in the shape file, too. - */ - public static final int MODIFY_ROW_MASK = 1 << 0; - /** - * Edit button mask, to allow adding/removing columns in the attribute - * table. - */ - public static final int MODIFY_COLUMN_MASK = 1 << 1; - /** - * Button mask to drop the frame quietly, with the modifications to the - * table complete. - */ - public static final int DONE_MASK = 1 << 3; - - /** - * Button mask to show a save button to write out any changes. - */ - public static final int SAVE_MASK = 1 << 4; - - /** - * Old Object value held for every NUMERIC cell that had a problem - * importing. Now, those cells are filled with whitespace. - */ - public final static Double ZERO = new Double(0); - - /** - * An array of bytes that contain the character lengths for each column - */ - protected int[] _lengths = null; - - /** - * An array of bytes that contain the number of decimal places for each - * column - */ - protected byte[] _decimalCounts = null; - - /** An array of bytes that contain the column types for each column */ - protected byte[] _types = null; - - /** An array of bytes that contain the names for each column */ - protected String[] _names = null; - - /** Class scope reference to a list of data formatted by row */ - protected List> _records = null; - - /** - * Class scope variable for the number of columns that exist in the model - */ - protected int _columnCount = -1; - - protected boolean writable = false; - - protected JTable table; - protected final DbfTableModel parent; - - protected boolean dirty = false; - protected boolean exitOnClose = false; - - protected boolean DEBUG = false; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - protected DbfTableModel() { - parent = this; - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Creates a blank DbfTableModel - * - * @param columnCount The number of columns this model will manage - */ - public DbfTableModel(int columnCount) { - this(); - _columnCount = columnCount; - _records = new ArrayList>(); - _lengths = new int[columnCount]; - _decimalCounts = new byte[columnCount]; - _types = new byte[columnCount]; - _names = new String[columnCount]; - } - - /** - * Creates a DbfTableModel based on an InputStream - * - * @param is The dbf file - */ - public DbfTableModel(DbfInputStream is) { - this(); - _lengths = is.getLengths(); - _decimalCounts = is.getDecimalCounts(); - _names = is.getColumnNames(); - _types = is.getTypes(); - _records = is.getRecords(); - _columnCount = is.getColumnCount(); - } - - /** - * Adds a row of data to the the model. An exception is thrown if the number - * of elements in the passed in collection does not match the number of - * columns in the model. - * - * @param columns A collection of columns that comprise the row of data - */ - public void addRecord(List columns) { - if (columns.size() != _columnCount) { - throw new RuntimeException("DbfTableModel: Mismatched Column Count"); - } - _records.add(columns); - } - - /** - * Remove the record at the index. - */ - public List remove(int index) { - return _records.remove(index); - } - - public void addBlankRecord() { - addRecord(getBlankRecord()); - } - - public List getBlankRecord() { - ArrayList record = new ArrayList(); - - for (int i = 0; i < _columnCount; i++) { - record.add(getEmptyDefaultForType(getType(i))); - } - return record; - } - - public Object getEmptyDefaultForType(byte type) { - // May need to be updated to provide real values. - if (isNumericalType(type)) { - return new Double(0); - } else if (type == DBF_TYPE_LOGICAL.byteValue()) { - return new Boolean(false); - } else { - return ""; - } - } - - public static boolean isNumericalType(byte type) { - return type == DbfTableModel.TYPE_NUMERIC || type == DbfTableModel.TYPE_LONG || type == DbfTableModel.TYPE_FLOAT - || type == DbfTableModel.TYPE_DOUBLE || type == DbfTableModel.TYPE_AUTOINCREMENT; - } - - public static boolean isValidType(byte type) { - return type == DbfTableModel.TYPE_NUMERIC || type == DbfTableModel.TYPE_LONG || type == DbfTableModel.TYPE_FLOAT - || type == DbfTableModel.TYPE_DOUBLE || type == DbfTableModel.TYPE_BINARY - || type == DbfTableModel.TYPE_CHARACTER || type == DbfTableModel.TYPE_DATE - || type == DbfTableModel.TYPE_LOGICAL || type == DbfTableModel.TYPE_MEMO - || type == DbfTableModel.TYPE_TIMESTAMP || type == DbfTableModel.TYPE_AUTOINCREMENT - || type == DbfTableModel.TYPE_OLE; - } - - /** - * Retrieves the record array list for the passed record number. In OpenMap, - * Shape file records start their indexes at 0. This is the number attribute - * stored in the EsriGraphic. Note: The Shape Specification and Shape files - * contain indexes starting at 0. Make sure you don't get bit by an - * off-by-one situation. - * - * @param recordnumber The record number - * @return An ArrayList for the given record number - */ - public List getRecord(int recordnumber) { - try { - return _records.get(recordnumber); - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } - } - - /** - * Get an iterator over the records. - */ - public Iterator> getRecords() { - return _records.iterator(); - } - - /** - * Iterable method for the records. - */ - public Iterator> iterator() { - return _records.iterator(); - } - - /** - * Retrieves the column class for the passed in column index - * - * @param c The column index - * @return The column class for the given column index - */ - public Class getColumnClass(int c) { - return getValueAt(0, c).getClass(); - } - - /** - * Retrieves the number of columns that exist in the model - * - * @return The number of columns that exist in the model - */ - public int getColumnCount() { - return _columnCount; - } - - /** - * Retrieves the number of decimal places for the passed in column index - * - * @param column The column index - * @return The number of decimal places for the given column index - */ - public byte getDecimalCount(int column) { - return _decimalCounts[column]; - } - - /** - * Retrieves the column name for the passed in column index - * - * @param column The column index - * @return The column name for the given column index - */ - public String getColumnName(int column) { - return _names[column]; - } - - /** - * Find the column index of the column with the given name. - * - * @param columnName - * @return If the columnName is valid, some number between 0-column count. - * Otherwise, -1 for non-valid names. - */ - public int getColumnIndexForName(String columnName) { - if (_names != null) { - for (int i = 0; i < _names.length; i++) { - if (_names[i].equalsIgnoreCase(columnName)) { - return i; - } - } - } - return -1; - } - - /** - * Retrieves the character length for the passed in column index - * - * @param column The column index - * @return The character length for the given column index - */ - public int getLength(int column) { - return _lengths[column]; - } - - /** - * Retrieves the number of columns that exist in the model - * - * @return The number column that exist in the model - */ - public int getRowCount() { - if (_records == null) { - return 0; - } else { - return _records.size(); - } - } - - /** - * Retrieves the column type for the passed in column index - * - * @param column The column index - * @return The column type for the given column index - */ - public byte getType(int column) { - return _types[column]; - } - - /** - * Retrieves a value for a specific column and row index - * - * @return Object A value for a specific column and row index - */ - public Object getValueAt(int row, int column) { - List cells = _records.get(row); - Object cell = cells.get(column); - return cell; - } - - /** - * Sets the column name for the passed-in field index - * - * @param column The column index - * @param name The name to assign for the passed-in column index - */ - public void setColumnName(int column, String name) { - _names[column] = name; - } - - /** - * Sets the decimal count for the passed in field index - * - * @param column The index to the column - * @param decimalCount The number of decimals places to assign to the passed - * in column - */ - public void setDecimalCount(int column, byte decimalCount) { - _decimalCounts[column] = decimalCount; - } - - /** - * Set the character length for the passed-in field index - * - * @param column The column index - * @param length The character length to assign for the passed-in column - * index - */ - public void setLength(int column, int length) { - _lengths[column] = length; - } - - /** - * Sets the column type for the passed-in field index - * - * @param column The column index - * @param type The type of column to assign for the passed-in column index - */ - public void setType(int column, byte type) { - _types[column] = type; - } - - public void setValueAt(Object object, int row, int column) { - List columns = _records.get(row); - columns.set(column, object); - } - - public boolean isCellEditable(int rowIndex, int columnIndex) { - return writable; - } - - public void setWritable(boolean set) { - writable = set; - } - - public boolean getWritable() { - return writable; - } - - /** - * Needs to be called before displaying the DbfTableModel. - */ - public JTable getTable(ListSelectionModel lsm) { - JTable t = getTable(); - t.setModel(this); - t.setSelectionModel(lsm); - t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); - return t; - } - - protected JTable getTable() { - if (table == null) { - table = new DbfJTable(this); - } - return table; - } - - // In case you want to add options to modify the table. - JPanel controlPanel = null; - - public Component getGUI(String filename, int actionMask) { - - JPanel panel = new JPanel(); - - if (filename != null) { - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), filename)); - } else { - panel.setBorder(BorderFactory.createEtchedBorder()); - } - - panel.setLayout(new BorderLayout()); - - JScrollPane pane = new JScrollPane(getTable(new DefaultListSelectionModel())); - panel.add(pane, BorderLayout.CENTER); - - controlPanel = new JPanel(); - panel.add(controlPanel, BorderLayout.SOUTH); - - if ((actionMask & MODIFY_ROW_MASK) != 0) { - JButton addButton = new JButton(i18n.get(DbfTableModel.class, "Add", "Add")); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - addBlankRecord(); - fireTableDataChanged(); - } - }); - - JButton deleteButton = new JButton(i18n.get(DbfTableModel.class, "Delete", "Delete")); - deleteButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - int[] index = getTable().getSelectedRows(); - - if (index.length > 0) { - - // Ask to make sure... - - int check = JOptionPane.showConfirmDialog(null, - (i18n.get(DbfTableModel.class, "Are_you_sure_you_want_to_delete", - "Are you sure you want to delete") - + " " - + (index.length > 1 ? i18n.get(DbfTableModel.class, "these_rows", "these rows?") - : i18n.get(DbfTableModel.class, "this_row", "this row?"))), - i18n.get(DbfTableModel.class, "Confirm_Delete", "Confirm Delete"), - JOptionPane.OK_CANCEL_OPTION); - - if (check == JOptionPane.YES_OPTION) { - - for (int i = index.length - 1; i >= 0; i--) { - if (DEBUG) - logger.fine("Deleting record " + index[i]); - List removed = remove(index[i]); - if (DEBUG) - logger.fine("Deleted records: " + removed); - } - fireTableDataChanged(); - } - } - } - }); - - controlPanel.add(addButton); - controlPanel.add(deleteButton); - } - - if ((actionMask & MODIFY_COLUMN_MASK) != 0) { - JButton editTableButton = new JButton( - i18n.get(DbfTableModel.class, "Edit_Table_Format", "Edit Table Format")); - editTableButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - MetaDbfTableModel mdtm = new MetaDbfTableModel(parent); - mdtm.addTableModelListener(parent); - mdtm.showGUI(filePath.toString()); - } - }); - - controlPanel.add(editTableButton); - } - - if ((actionMask & SAVE_MASK) != 0) { - JButton saveButton = new JButton(i18n.get(DbfTableModel.class, "Save", "Save")); - saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - try { - write(parent, null); - } catch (FileNotFoundException fnfe) { - } catch (IOException ioe) { - } - } - }); - controlPanel.add(saveButton); - } - - if ((actionMask & DONE_MASK) != 0) { - JButton doneButton = new JButton(i18n.get(DbfTableModel.class, "Done", "Done")); - doneButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - frame.dispose(); - } - }); - controlPanel.add(doneButton); - } - - return panel; - } - - protected final StringBuffer filePath = new StringBuffer(); - protected JFrame frame = null; - - public void hideGUI() { - if (frame != null) { - frame.setVisible(false); - } - } - - public void showGUI(String filename, int actionMask) { - - if (frame == null) { - frame = new JFrame(filename); - - filePath.replace(0, filePath.capacity(), filename); - - frame.getContentPane().add(getGUI(null, actionMask), BorderLayout.CENTER); - - frame.setSize(400, 300); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - // need a shutdown event to notify other gui beans - // and - // then exit. - exitWindowClosed(); - } - }); - } - - frame.setVisible(true); - } - - public void exitWindowClosed() { - if (exitOnClose) { - System.exit(0); - } - } - - public void tableChanged(TableModelEvent e) { - dirty = true; - if (DEBUG) - logger.fine("DbfTableModel sensing change"); - - int row = e.getFirstRow(); - // Of course, the only thing we're listening to here is the - // MetaDbfTableModel changes, and if we get a HEADER_ROW - // change it's telling us to modify *OUR* headers, to commit - // all the changes that were made to it. Otherwise, we should - // just track the events and make them happen when we get - // this. - if (row == TableModelEvent.HEADER_ROW) { - commitEvents((DbfTableModel) e.getSource()); - } - } - - protected void commitEvents(DbfTableModel model) { - - if (DEBUG) - logger.fine("Committing changes"); - - Iterator> modelRecords = model.getRecords(); - int index = -1; - - while (modelRecords.hasNext()) { - List modelRecord = modelRecords.next(); - - String modelColumnName = (String) modelRecord.get(0); - Byte modelType = (Byte) modelRecord.get(1); - Integer modelLengthOfField = (Integer) modelRecord.get(2); - Integer modelNumDecPlaces = (Integer) modelRecord.get(3); - - index++; - if (index < _columnCount) { - String columnName = _names[index]; - if (DEBUG) - logger.fine(columnName + ", " + modelColumnName); - while (!columnName.equalsIgnoreCase(modelColumnName)) { - deleteColumn(index); - if (index >= _columnCount) { - addColumn(modelRecord); - break; - } - columnName = _names[index]; - } - - if (columnName.equalsIgnoreCase(modelColumnName)) { - _types[index] = modelType.byteValue(); - _lengths[index] = modelLengthOfField.intValue(); - _decimalCounts[index] = modelNumDecPlaces.byteValue(); - } - - } else { - // Add Column - if (DEBUG) - logger.fine("Add column " + modelColumnName); - addColumn(modelRecord); - } - } - - while (++index < _columnCount) { - if (DEBUG) - logger.fine("Deleting extra column"); - deleteColumn(index); - } - - if (DEBUG) { - logger.fine("New Table:"); - for (int j = 0; j < _names.length; j++) { - logger.fine(" " + _names[j]); - } - } - fireTableStructureChanged(); - dirty = false; - } - - /** - * Delete a column, iterating through all the records and deleting that part - * of each record. - */ - protected void deleteColumn(int columnIndex) { - Iterator> rows = getRecords(); - while (rows.hasNext()) { - rows.next().remove(columnIndex); - } - - _columnCount -= 1; - - _lengths = remove(_lengths, columnIndex); - _decimalCounts = remove(_decimalCounts, columnIndex); - _types = remove(_types, columnIndex); - _names = remove(_names, columnIndex); - } - - /** - */ - protected int[] remove(int[] current, int index) { - - int[] newBytes = new int[current.length - 1]; - System.arraycopy(current, 0, newBytes, 0, index); - System.arraycopy(current, index + 1, newBytes, index, current.length - index - 1); - return newBytes; - } - - /** - */ - protected byte[] remove(byte[] current, int index) { - - byte[] newBytes = new byte[current.length - 1]; - System.arraycopy(current, 0, newBytes, 0, index); - System.arraycopy(current, index + 1, newBytes, index, current.length - index - 1); - return newBytes; - } - - /** - */ - protected String[] remove(String[] current, int index) { - - String[] newStrings = new String[current.length - 1]; - System.arraycopy(current, 0, newStrings, 0, index); - System.arraycopy(current, index + 1, newStrings, index, current.length - index - 1); - return newStrings; - } - - /** - * The types in the ArrayList are set - String, Byte, Integer, Integer - to - * match the format of the header. - */ - protected void addColumn(List recordColumn) { - - Iterator> rows = getRecords(); - while (rows.hasNext()) { - rows.next().add(""); - } - - _columnCount++; - - _names = add(_names, ((String) recordColumn.get(0))); - _types = add(_types, ((Byte) recordColumn.get(1)).byteValue()); - _lengths = add(_lengths, ((Integer) recordColumn.get(2)).byteValue()); - _decimalCounts = add(_decimalCounts, ((Integer) recordColumn.get(3)).byteValue()); - } - - /** - */ - protected int[] add(int[] current, byte nb) { - int[] newBytes = new int[current.length + 1]; - System.arraycopy(current, 0, newBytes, 0, current.length); - newBytes[current.length] = nb; - return newBytes; - } - - /** - */ - protected byte[] add(byte[] current, byte nb) { - byte[] newBytes = new byte[current.length + 1]; - System.arraycopy(current, 0, newBytes, 0, current.length); - newBytes[current.length] = nb; - return newBytes; - } - - protected String[] add(String[] current, String string) { - String[] newStrings = new String[current.length + 1]; - System.arraycopy(current, 0, newStrings, 0, current.length); - newStrings[current.length] = string; - return newStrings; - } - - public void cleanupChanges() { - if (DEBUG) - Debug.output("DbfTableModel cleaning up changes."); - dirty = false; - } - - /** - * Create another DbfTableModel with the same structure as this one (number - * of columns, column names, lengths and decimal counts). - */ - public DbfTableModel headerClone() { - int size = getColumnCount(); - DbfTableModel dtm = new DbfTableModel(size); - for (int i = 0; i < size; i++) { - dtm.setColumnName(i, this.getColumnName(i)); - dtm.setDecimalCount(i, this.getDecimalCount(i)); - dtm.setLength(i, this.getLength(i)); - dtm.setType(i, this.getType(i)); - } - return dtm; - } - - /** - * Creates a DbfTableModel for a given .dbf file - * - * @param dbf The url of the file to retrieve. - * @return The DbfTableModel, null if there is a problem. - */ - public static DbfTableModel getDbfTableModel(URL dbf) { - try { - return read(dbf); - } catch (Exception exception) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("problem loading DBF file" + exception.getMessage()); - } - return null; - } - } - - public static DbfTableModel read(URL dbf) throws Exception { - InputStream is = dbf.openStream(); - DbfTableModel model = new DbfTableModel(new DbfInputStream(is)); - is.close(); - return model; - } - - public static String write(DbfTableModel model, String location) throws FileNotFoundException, IOException { - if (location == null) { - - location = FileUtils.getFilePathToSaveFromUser( - i18n.get(DbfTableModel.class, "Select_DBF_Name", "Select DBF file name...")); - if (location != null && !location.endsWith(".dbf")) { - location = location + ".dbf"; - } - } - if (location != null) { - DbfOutputStream dos = new DbfOutputStream(new FileOutputStream(new File(location))); - dos.writeModel(model); - } - - return location; - } - - /** - * Takes the object and converts it to a String for output. - * - * @param obj - * @param type - * @param df - * @param columnLength the length of the column entries, so whitespace can - * be added if needed. - * @return a string value representing the object. If the object is null, a - * whitespace string will be returned. - */ - public static String getStringForType(Object obj, byte type, DecimalFormat df, int columnLength) { - String ret = ""; - - if (obj != null) { - - if (isNumericalType(type)) { - try { - ret = df.format(((Double) obj).doubleValue()); - } catch (Exception e) { - ret = ""; - } - - } else if (obj instanceof String) { - ret = (String) obj; - } - } - - if (ret.length() != columnLength) { - ret = appendWhitespaceOrTrim(ret, columnLength); - } - - return ret; - } - - /** - * A method that looks at the length of String s and returns a copy of it - * with whitespace appended to the end to allow it to have the provided - * length. - * - * @param s - * @param length - * @return String with whitespace added if needed. - */ - public static String appendWhitespaceOrTrim(String s, int length) { - if (s == null) { - s = new String(""); - } - - int retLength = s.length(); - if (retLength < length) { - StringBuffer sb = new StringBuffer(s); - int numWhites = length - retLength; - for (int i = 0; i < numWhites; i++) { - sb.append(" "); - } - s = sb.toString(); - } else if (retLength > length) { - s = s.substring(0, length); - } - - return s; - } - - public static Object getObjectForType(String cellContents, int type, DecimalFormat df, int columnLength) - throws java.text.ParseException { - Object ret = cellContents; - if (isNumericalType((byte) type)) { - if (cellContents.length() > 0) { - try { - ret = new Double(cellContents); - } catch (NumberFormatException nfe) { - // Shouldn't get here, but thought it might help. DFD - ret = new Double(df.parse(cellContents).doubleValue()); - } - } else { - // If we come across a numerical cell that doesn't contain data, - // we should create an empty whitespace string in that cell - // instead of setting it to ZERO. ZERO has a very different - // meaning. - - ret = appendWhitespaceOrTrim(null, columnLength); - } - } else if (type == DbfTableModel.TYPE_BINARY || type == DbfTableModel.TYPE_MEMO - || type == DbfTableModel.TYPE_OLE) { - if (cellContents.length() < 10) { - cellContents = cellContents.trim(); - // prepending whitespace. - StringBuffer bu = new StringBuffer(); - int numSpaces = 10 - cellContents.length(); - for (int i = 0; i < numSpaces; i++) { - bu.append(" "); - } - bu.append(cellContents); - ret = bu.toString(); - } - } else if (type == DbfTableModel.TYPE_TIMESTAMP) { - // uhhhhhh.... - } - - return ret; - } - - public boolean isExitOnClose() { - return exitOnClose; - } - - public void setExitOnClose(boolean exitOnClose) { - this.exitOnClose = exitOnClose; - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - test(); - } else { - - try { - - URL dbf = PropUtils.getResourceOrFileOrURL(args[0]); - InputStream is = dbf.openStream(); - DbfInputStream dis = new DbfInputStream(is); - DbfTableModel dtm = new DbfTableModel(dis); - dtm.setWritable(true); - dtm.exitOnClose = true; - dtm.showGUI(args[0], MODIFY_ROW_MASK | MODIFY_COLUMN_MASK | SAVE_MASK); - is.close(); - } catch (Exception e) { - Debug.error(e.getMessage()); - e.printStackTrace(); - } - } - } - - public static void test() { - DbfTableModel dtm = new DbfTableModel(2); - dtm.setColumnName(0, "NAME"); - dtm.setColumnName(1, "VALUE"); - - dtm.setDecimalCount(0, (byte) 0); - dtm.setDecimalCount(1, (byte) 3); - - dtm.setLength(0, 20); - dtm.setLength(1, 10); - - dtm.setType(0, TYPE_CHARACTER); - dtm.setType(1, TYPE_DOUBLE); - - ArrayList record = new ArrayList(); - record.add("ok"); - record.add(new Double(345.3)); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("null"); - record.add(null); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("blank"); - record.add(""); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("zero"); - record.add(new Double(0)); - dtm.addRecord(record); - - try { - write(dtm, "./test.dbf"); - - dtm = read(new File("./test.dbf").toURI().toURL()); - - dtm.showGUI("test.dbf", MODIFY_ROW_MASK | MODIFY_COLUMN_MASK | SAVE_MASK); - - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - class DbfJTable extends JTable { - private static final long serialVersionUID = 1L; - DbfTableModel dbfTableModel; - DoubleRenderer dRenderer = new DoubleRenderer(); - - public DbfJTable(DbfTableModel model) { - super(model); - dbfTableModel = model; - } - - public TableCellRenderer getCellRenderer(int row, int column) { - if (isNumericalType(_types[column])) { - dRenderer.formatter.setMaximumFractionDigits(_decimalCounts[column]); - return dRenderer; - } - return super.getCellRenderer(row, column); - } - } - - static class DoubleRenderer extends DefaultTableCellRenderer { - private static final long serialVersionUID = 1L; - NumberFormat formatter = NumberFormat.getInstance(); - - public DoubleRenderer() { - super(); - setHorizontalAlignment(JLabel.RIGHT); - } - - public void setValue(Object value) { - try { - setText(formatter.format(value)); - return; - } catch (Exception e) { - - } - setText(""); - } - } - - public boolean matches(DbfTableModel dbf) { - boolean columnsMatch = false; - - if (dbf != null) { - int columnCount = getColumnCount(); - columnsMatch = dbf.getColumnCount() == columnCount; - - int i = 0; - while (columnsMatch && i < columnCount) { - columnsMatch = columnsMatch && dbf.getColumnName(i).equals(getColumnName(i)); - i++; - } - } - return columnsMatch; - } - - public void append(DbfTableModel dbf) { - if (matches(dbf)) { - Iterator> it = dbf.getRecords(); - while (it.hasNext()) { - addRecord(it.next()); - } - } - } - - /** - * - */ - @SuppressWarnings("unchecked") - public void doAction(OMGraphicList list, OMGraphic graphic, OMAction action, DbfTableModelFactory dbfFactory) { - - if (list == null || graphic == null) { - return; - } - - if (list.size() != getRowCount()) { - logger.warning("DBF rows don't match list contents"); - return; - } - - // Take the contents (rows) of the DbfTableModel, store them in the - // OMGraphics, do the action on the list, then reset the DbfTableModel. - // Reset the indexes in the OMGraphics. - int indexCount = 0; - for (OMGraphic omg : list) { - Integer index = (Integer) omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - if (index != null) { - if (index != indexCount) { - // ooh jeez. - logger.warning( - "the indexes in the list are off, (counted) " + indexCount + " vs (record) " + index); - } - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getRecord(index)); - } else { - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getRecord(indexCount)); - } - indexCount++; - } - - if (graphic.getAttribute(SHAPE_DBF_INFO_ATTRIBUTE) == null) { - - if (dbfFactory != null) { - graphic.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, dbfFactory.getNewDefaultRow()); - } else { - graphic.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getBlankRecord()); - } - } - - list.doAction(graphic, action); - - _records.clear(); - - indexCount = 0; - for (OMGraphic omg : list) { - _records.add((List) omg.getAttribute(SHAPE_DBF_INFO_ATTRIBUTE)); - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, null); - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(indexCount++)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModelFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModelFactory.java deleted file mode 100644 index b3c92ab2a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DbfTableModelFactory.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.bbn.openmap.dataAccess.shape; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.PropUtils; - -public class DbfTableModelFactory extends OMComponent implements ShapeConstants { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.DbfTableModelFactory"); - - public final static String ColumnsProperty = "columns"; - /** - * Spreadsheet format for column, as - * name,type,length,decimal_places(optional) - */ - public final static String DefinitionProperty = "definition"; - public final static String DefaultValueProperty = "default"; - - protected ArrayList columns; - - public class Column { - protected String name; - protected byte type; - protected byte decimalCount; - protected int length; - protected Object defaultValue; - - public Column(String definition) throws FormatException { - StringTokenizer tok = new StringTokenizer(definition, ","); - try { - // Name - name = tok.nextToken().trim(); - // Type - type = (byte) tok.nextToken().trim().toUpperCase().charAt(0); - if (!DbfTableModel.isValidType(type)) { - throw new FormatException("Type is not valid: " + type); - } - // Length - length = Integer.parseInt(tok.nextToken().trim()); - - if (DbfTableModel.isNumericalType(type)) { - decimalCount = Byte.parseByte(tok.nextToken().trim()); - } - } catch (Exception e) { - throw new FormatException(e.getMessage()); - } - } - - public Column(String n, byte t, byte dc, int l, Object dv) { - name = n; - type = t; - decimalCount = dc; - length = l; - defaultValue = dv; - } - - public String getName() { - return name; - } - - public byte getType() { - return type; - } - - public byte getDecimalCount() { - return decimalCount; - } - - public int getLength() { - return length; - } - - public void setDefaultValue(String defaultVal) { - if (DbfTableModel.isNumericalType(type)) { - try { - this.defaultValue = new Double(defaultVal); - } catch (NumberFormatException nfe) { - logger.warning("can't parse default value for " + name - + ", setting to 0"); - this.defaultValue = new Double(0); - } - } else { - this.defaultValue = defaultVal; - } - } - - public Object getDefaultValue() { - return defaultValue; - } - - public String toString() { - return name + "," + ((char) type) + "," + length - + (DbfTableModel.isNumericalType(type) ? "," + decimalCount : "") - + ", dv: " + defaultValue; - } - } - - public DbfTableModelFactory() { - - } - - public void setColumns(ArrayList cols) { - columns = cols; - } - - public ArrayList getColumns() { - return columns; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - logger.fine("parsing properties"); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String markerList = props.getProperty(prefix + ColumnsProperty); - List colStrings = PropUtils.parseSpacedMarkers(markerList); - columns = new ArrayList(colStrings.size()); - for (String colString : colStrings) { - String colDef = props.getProperty(prefix + colString + "." - + DefinitionProperty); - - if (colDef != null) { - try { - Column col = new Column(colDef); - col.setDefaultValue(props.getProperty(prefix + colString + "." - + DefaultValueProperty, "")); - - columns.add(col); - - logger.fine("parsed: " + col); - } catch (FormatException fe) { - logger.warning("For column: " + colString + ", def: " + colDef + ": " - + fe.getMessage()); - } - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - return props; - } - - public DbfTableModel createDbfTableModel() { - DbfTableModel dbf = null; - - if (columns != null) { - dbf = new DbfTableModel(getNumColumns()); - int i = 0; - for (Column col : columns) { - dbf.setColumnName(i, col.name); - dbf.setDecimalCount(i, col.decimalCount); - dbf.setLength(i, col.length); - dbf.setType(i, col.type); - i++; - } - } - return dbf; - } - - public ArrayList getNewDefaultRow() { - ArrayList row = new ArrayList(getNumColumns()); - if (columns != null) { - for (Column col : columns) { - row.add(col.defaultValue); - } - } - return row; - } - - public int getNumColumns() { - return columns != null ? columns.size() : 0; - } - - public DbfTableModel createDbf(OMGraphicList omgl) { - DbfTableModel dbf = createDbfTableModel(); - if (dbf != null) { - omgl.putAttribute(DBF_ATTRIBUTE, dbf); - for (int i = 0; i < omgl.size(); i++) { - dbf.addRecord(getNewDefaultRow()); - } - } - return dbf; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingAttributesUtility.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingAttributesUtility.java deleted file mode 100644 index 2e83a4c14..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingAttributesUtility.java +++ /dev/null @@ -1,213 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/DrawingAttributesUtility.java,v $ -// $RCSfile: DrawingAttributesUtility.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/08/25 15:36:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.util.Hashtable; -import java.util.List; - -import com.bbn.openmap.omGraphics.BasicStrokeEditor; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.ColorFactory; - -/** - * A class to help out with looking in a DBF file, and setting OMGraphics with - * DrawingAttributes settings that may reside in the DBF. The DBF column header - * names should be the same as the DrawingAttributes property strings. - */ -public class DrawingAttributesUtility implements ShapeConstants { - - protected DrawingAttributes da = new DrawingAttributes(); - - protected int desColumn = -1; - protected int lineColorColumn = -1; - protected int fillColorColumn = -1; - protected int selectColorColumn = -1; - protected int lineWidthColumn = -1; - protected int dashPatternColumn = -1; - protected int dashPhaseColumn = -1; - - protected DbfTableModel model = null; - - protected DrawingAttributes defaultDA = DrawingAttributes.DEFAULT; - - protected DrawingAttributesUtility(DbfTableModel model) { - - this.model = model; - - Hashtable columnNames = new Hashtable(); - int numColumns = model.getColumnCount(); - for (int i = 0; i < numColumns; i++) { - String colName = model.getColumnName(i); - columnNames.put(colName, new Integer(i)); - } - - Integer value; - - value = (Integer) columnNames.get(SHAPE_DBF_DESCRIPTION); - if (value != null) - desColumn = value.intValue(); - - value = (Integer) columnNames.get(SHAPE_DBF_LINECOLOR); - if (value != null) - lineColorColumn = value.intValue(); - value = (Integer) columnNames.get(SHAPE_DBF_FILLCOLOR); - if (value != null) - fillColorColumn = value.intValue(); - value = (Integer) columnNames.get(SHAPE_DBF_SELECTCOLOR); - if (value != null) - selectColorColumn = value.intValue(); - value = (Integer) columnNames.get(SHAPE_DBF_LINEWIDTH); - if (value != null) - lineWidthColumn = value.intValue(); - value = (Integer) columnNames.get(SHAPE_DBF_DASHPATTERN); - if (value != null) - dashPatternColumn = value.intValue(); - value = (Integer) columnNames.get(SHAPE_DBF_DASHPHASE); - if (value != null) - dashPhaseColumn = value.intValue(); - - // OK, the column names should be known; - } - - protected Color parseColor(String colorString, Color def) { - Color ret; - try { - ret = ColorFactory.parseColor(colorString, true); - } catch (NumberFormatException nfe) { - ret = def; - } - return ret; - } - - public void setDefaultAttributes(DrawingAttributes dda) { - if (dda != null) { - defaultDA = dda; - } else { - defaultDA = DrawingAttributes.DEFAULT; - } - } - - public DrawingAttributes getDefaultAttributes() { - return defaultDA; - } - - protected void configureForRecord(OMGraphic graphic, List record) { - if (desColumn != -1) { - String ret = (String) record.get(desColumn); - graphic.putAttribute(SHAPE_DBF_DESCRIPTION, ret); - } - - getDefaultAttributes().setTo(da); - - if (lineColorColumn != -1) { - da.setLinePaint(parseColor((String) record.get(lineColorColumn), - (Color) defaultDA.getLinePaint())); - } - - if (fillColorColumn != -1) { - da.setFillPaint(parseColor((String) record.get(fillColorColumn), - (Color) defaultDA.getFillPaint())); - } - - if (selectColorColumn != -1) { - da.setSelectPaint(parseColor((String) record.get(selectColorColumn), - (Color) defaultDA.getSelectPaint())); - } - - int lineWidth = 1; - float[] dashPattern = null; - float dashPhase = 0f; - - if (lineWidthColumn != -1) { - lineWidth = ((Double) record.get(lineWidthColumn)).intValue(); - } - - if (dashPatternColumn != -1) { - String dp = (String) record.get(dashPatternColumn); - if (dp == null || dp.intern().length() == 0) { - dp = BasicStrokeEditor.NONE; - } - dashPattern = BasicStrokeEditor.stringToDashArray(dp); - } - - if (dashPhaseColumn != -1) { - dashPhase = ((Double) record.get(lineWidthColumn)).floatValue(); - } - - da.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, - BasicStroke.JOIN_MITER, 10.0f, dashPattern, dashPhase)); - da.setTo(graphic); - } - - /** - * Sets the drawing attributes on the record index provided. Remember, the - * index starts at 0 for the list when you refer to record indexes when you - * are dealing with OpenMap code. The Shape files start their indexes at 1, - * it's converted at import to match java convention. - * - * @param graphic - * @param index - */ - protected void setDrawingAttributes(OMGraphic graphic, int index) { - - if (model != null) { - List record = model.getRecord(index); - if (record != null) { - configureForRecord(graphic, record); - } - } - } - - /** - * Iterate through the list, and look in the DbfTableModel for - * DrawingAttributes parameters, setting the DrawingAttributes on the list - * contents with anything found in the DBF file. Otherwise, use the - * DrawingAttributes.DEFAULT settings if no attribute parameters found. - */ - public static void setDrawingAttributes(EsriGraphicList list, DbfTableModel model) { - setDrawingAttributes(list, model, DrawingAttributes.DEFAULT); - } - - /** - * Iterate through the list, and look in the DbfTableModel for - * DrawingAttributes parameters, setting the DrawingAttributes on the list - * contents with anything found in the DBF file. Otherwise, use the default - * DrawingAttributes settings if no attribute parameters found. - */ - public static void setDrawingAttributes(EsriGraphicList list, DbfTableModel model, - DrawingAttributes defaultDA) { - // Set it up; - if (list == null || model == null) { - return; - } - DrawingAttributesUtility dau = new DrawingAttributesUtility(model); - dau.setDefaultAttributes(defaultDA); - int index = 0; - for (OMGraphic graphic : list) { - dau.setDrawingAttributes(graphic, index++); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingToolRenderException.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingToolRenderException.java deleted file mode 100644 index 4b1924812..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/DrawingToolRenderException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * File: DrawingToolRenderException.java - * OptiMetrics, Inc. - * 2107 Laurel Bush Road - Suite 209 - * Bel Air, MD 21015 - * (410)569 - 6081 - */ -package com.bbn.openmap.dataAccess.shape; - -import javax.swing.JOptionPane; - -/** - * Used to throw an exception when OMGraphics are not rendered as - * OMGraphicConstants.RENDERTYPE_LATLON in EsriShapeExport and its - * subclasses. - */ -public class DrawingToolRenderException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Displays a JOtionPane Message Dialog informing the user that - * any Drawing Tool graphics not rendered in LAT/LON will not be - * exported. - */ - public static void notifyUserOfNonLatLonGraphics(int count) { - String errMsg = "All Drawing Tool Graphics must be rendered as LAT/LON \nto be exported as ESRI shape files. \n\n" - + count - + " graphic" - + (count > 1 ? "s" : "") - + " not rendered in LAT/LON will not be exported."; - String title = "Exporting Error"; - JOptionPane.showMessageDialog(null, - errMsg, - title, - JOptionPane.ERROR_MESSAGE); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphic.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphic.java deleted file mode 100644 index 48f74c5f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphic.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphic.java,v $ -// $RCSfile: EsriGraphic.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -/** - * An interface to typecast OMGraphics. - * - * @author Doug Van Auken - */ -public interface EsriGraphic extends ShapeConstants { - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, minx, - * maxy maxx in order of the array. - */ - public void setExtents(double[] extents); - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, maxy maxx - * in order of the array. - */ - public double[] getExtents(); - - /** - * Shallow copy this graphic. The contract is that the cloned object should - * be capable of being placed on a different layer. - */ - public EsriGraphic shallowCopy(); - - /** - * EsriGraphics can hold attributes. - * - * @param key the key to use for an attribute - * @param value the attribute value - */ - public void putAttribute(Object key, Object value); - - /** - * EsriGraphics can hold attributes. - * - * @param key the key to use for an attribute return the attribute value, - * null if the attribute doesn't exist. - */ - public Object getAttribute(Object key); - - /** - * Set the type for the EsriGraphic. - * @param type - */ - public void setType(int type); - - /** - * Get the graphic type in ESRI type number form - */ - public int getType(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicFactory.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicFactory.java deleted file mode 100644 index 6f02f1a77..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicFactory.java +++ /dev/null @@ -1,1572 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: EsriGraphicFactory.java,v $ -//$Revision: 1.10 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.geom.Point2D; -import java.io.EOFException; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.dataAccess.shape.input.LittleEndianInputStream; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.DataBounds; - -/** - * EsriGraphicFactory creates OMGraphics/EsriGraphics from a shape file. - * - * @author ddietrick - */ -public class EsriGraphicFactory implements ShapeConstants { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.EsriGraphicFactory"); - - protected int lineType = OMGraphic.LINETYPE_STRAIGHT; - protected GeoCoordTransformation dataTransformation = null; - protected Class precision = Float.TYPE; - - protected static boolean verbose = false; - - /** - * Will create shapes with straight line types (faster for rendering) and no - * data transformation). - */ - public EsriGraphicFactory() { - } - - /** - * Create a factory - * - * @param lineType the line type to use for polys - * @param dataTransformation the transformation to use on data to convert it - * to lat/lon decimal degrees. - */ - public EsriGraphicFactory(int lineType, GeoCoordTransformation dataTransformation) { - this.lineType = lineType; - this.dataTransformation = dataTransformation; - } - - /** - * Create an OMGraphicList containing OMGraphics representing shape file - * contents. - * - * @param shp BinaryFile from shp file. - * @param drawingAttributes DrawingAttribute dictating rendering. - * @param pointRepresentation what to use for point object rendering. - * @param mapProj current map projection, if not null will be used to - * position OMGraphics. - * @param list The OMGraphicList to add OMGraphics to, returned. OK if null. - * @return OMGraphicList containing OMGraphics for shapes. - * @throws IOException - * @throws FormatException - */ - public OMGraphicList getEsriGraphics(BinaryFile shp, DrawingAttributes drawingAttributes, - Object pointRepresentation, Projection mapProj, - OMGraphicList list) throws IOException, FormatException { - shp.seek(0); - verbose = logger.isLoggable(Level.FINER); - Header header = new Header(shp, dataTransformation); - if (logger.isLoggable(Level.FINE)) { - logger.fine(header.toString()); - } - if (list == null) { - list = createEsriGraphicList(header.shapeType); - } - int offset = 100; // next byte past header; - // BAJ 20070604 Stop here for empty shape files - if (header.fileLength == offset) { - if (verbose) { - logger.finer("Header file length doesn't == 100: " + header.fileLength); - } - return list; - } - // Put a flag in here to force the file to be read until EOF - boolean ignoreFileLength = logger.isLoggable(Level.FINE); - - EsriGraphicFactory.ReadByteTracker byteTracker = new EsriGraphicFactory.ReadByteTracker(); - try { - OMGraphic eg = makeEsriGraphicFromRecord(offset, shp, drawingAttributes, pointRepresentation, byteTracker); - // 8 for shape type and record length - offset += byteTracker.currentCount + 8; - - while (offset != header.fileLength || ignoreFileLength) { - projGraphicAndAdd(eg, list, mapProj); - try { - eg = makeEsriGraphicFromRecord(offset, shp, drawingAttributes, pointRepresentation, byteTracker); - } catch (EOFException eof) { - logger.fine("File length (" + header.fileLength - + " bytes) is incorrect, file was read as much as possible (" + offset - + " bytes)."); - eg = null; - break; - } - // 8 for shape type and record length - offset += byteTracker.currentCount + 8; - } - - if (eg != null) { - projGraphicAndAdd(eg, list, mapProj); - } - - } catch (FormatException fe) { - fe.printStackTrace(); - } - - return list; - } - - /** - * Create OMGraphics from input stream from shp file. - * - * @param iStream stream created from shp file - * @param drawingAttributes DrawingAttributes for rendering - * @param pointRepresentation representation of point object rendering - * @param mapProj current map projection - * @param list list to add OMGraphics to, OK if null. - * @return OMGraphicList containing shapes. - * @throws IOException - * @throws FormatException - */ - public OMGraphicList getEsriGraphics(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - Object pointRepresentation, Projection mapProj, - OMGraphicList list) throws IOException, FormatException { - Header header = new Header(iStream, dataTransformation); - verbose = logger.isLoggable(Level.FINER); - if (logger.isLoggable(Level.FINE)) { - logger.fine(header.toString()); - } - if (list == null) { - list = createEsriGraphicList(header.shapeType); - } - int offset = 100; // next byte past header; - // BAJ 20070604 Stop here for empty shape files - if (header.fileLength == offset) { - if (verbose) { - logger.info("Header file length doesn't == 100: " + header.fileLength); - } - return list; - } - // Put a flag in here to force the file to be read until EOF - boolean ignoreFileLength = logger.isLoggable(Level.FINE); - - EsriGraphicFactory.ReadByteTracker byteTracker = new EsriGraphicFactory.ReadByteTracker(); - try { - OMGraphic eg = makeEsriGraphicFromRecord(offset, iStream, drawingAttributes, pointRepresentation, byteTracker); - // 8 for shape type and record length - offset += byteTracker.currentCount + 8; - - while (offset != header.fileLength || ignoreFileLength) { - projGraphicAndAdd(eg, list, mapProj); - try { - eg = makeEsriGraphicFromRecord(offset, iStream, drawingAttributes, pointRepresentation, byteTracker); - } catch (EOFException eof) { - logger.fine("File length (" + header.fileLength - + " bytes) is incorrect, file was read as much as possible (" + offset - + " bytes)."); - eg = null; - break; - } - // 8 for shape type and record length - offset += byteTracker.currentCount + 8; - } - - if (eg != null) { - projGraphicAndAdd(eg, list, mapProj); - } - - } catch (FormatException fe) { - fe.printStackTrace(); - } - - return list; - } - - protected void projGraphicAndAdd(OMGraphic eg, OMGraphicList list, Projection mapProj) { - if (eg != null) { - if (mapProj != null) { - eg.generate(mapProj); - } - - list.add((OMGraphic) eg); - } - } - - public OMGraphic makeEsriGraphicFromRecord(int byteOffset, BinaryFile shp, - DrawingAttributes drawingAttributes, - Object pointRepresentation, - ReadByteTracker byteTracker) - throws IOException, FormatException { - - OMGraphic omg = null; - if (shp != null) { - shp.seek(byteOffset); - shp.byteOrder(true); - - int recordNumber = shp.readInteger(); - int recordContentLength = shp.readInteger() * 2; - byteTracker.reset(recordContentLength); - - omg = makeEsriGraphic(shp, drawingAttributes, pointRepresentation, byteTracker); - if (omg != null) { - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(recordNumber - 1)); - } - } - - return omg; - } - - public OMGraphic makeEsriGraphicFromRecord(int byteOffset, LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - Object pointRepresentation, - ReadByteTracker byteTracker) - throws IOException, FormatException { - OMGraphic omg = null; - if (iStream != null) { - int recordNumber = iStream.readInt(); - int recordContentLength = iStream.readInt() * 2; - byteTracker.reset(recordContentLength); - - omg = makeEsriGraphic(iStream, drawingAttributes, pointRepresentation, byteTracker); - if (omg != null) { - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(recordNumber - 1)); - } - } - - return omg; - } - - /** - * Creates a OMGraphic from the shape file data. - * - * @param shpFile BinaryFile positioned for this record - * @param drawingAttributes rendering attributes for OMGraphic - * @param pointRepresentation object to use for representing point data - * @param byteTracker keeps track of how many bytes were used for this - * record. - * @return OMGraphic for record - * @exception IOException if something goes wrong reading the file - * @exception FormatException - */ - protected OMGraphic makeEsriGraphic(BinaryFile shpFile, DrawingAttributes drawingAttributes, - Object pointRepresentation, ReadByteTracker byteTracker) - throws IOException, FormatException { - /* - * SHAPE_TYPE_NULL = 0; SHAPE_TYPE_POINT = 1; SHAPE_TYPE_ARC = 3; - * SHAPE_TYPE_POLYLINE = 3; SHAPE_TYPE_POLYGON = 5; - * SHAPE_TYPE_MULTIPOINT = 8; SHAPE_TYPE_POINTZ = 11; - * SHAPE_TYPE_POLYLINEZ = 13; SHAPE_TYPE_POLYGONZ = 15; - * SHAPE_TYPE_MUILTIPOINTZ = 18; SHAPE_TYPE_POINTM = 21; - * SHAPE_TYPE_POLYLINEM = 23; SHAPE_TYPE_POLYGONM = 25; - * SHAPE_TYPE_MULTIPOINTM = 28; SHAPE_TYPE_MULTIPATCH = 31; - */ - EsriGraphic eg = null; - shpFile.byteOrder(false); - - int shapeType = shpFile.readInteger(); - byteTracker.addRead(4); - - if (verbose) { - logger.info("reading shape type: " + shapeType + ", " - + ShapeUtils.getStringForType(shapeType)); - } - - switch (shapeType) { - - case SHAPE_TYPE_NULL: - break; - case SHAPE_TYPE_POINT: - eg = createPointGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINE: - eg = createPolylineGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGON: - eg = createPolygonGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINT: - eg = createMultiPointGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POINTZ: - eg = createPointZGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINEZ: - eg = createPolylineZGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGONZ: - eg = createPolygonZGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINTZ: - eg = createMultiPointZGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POINTM: - eg = createPointMGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINEM: - eg = createPolylineMGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGONM: - eg = createPolygonMGraphic(shpFile, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINTM: - eg = createMultiPointMGraphic(shpFile, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPATCH: - - default: - - } - - return (OMGraphic) eg; - - } - - /** - * Create OMGraphic from next record - * - * @param iStream stream to read from, positioned at next record - * @param drawingAttributes rendering attributes - * @param pointRepresentation point rendering representation - * @param byteTracker keeps track of how many bytes are used for this - * record. - * @return OMGraphic for record - * @throws IOException - * @throws FormatException - */ - protected OMGraphic makeEsriGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - Object pointRepresentation, ReadByteTracker byteTracker) - throws IOException, FormatException { - /* - * SHAPE_TYPE_NULL = 0; SHAPE_TYPE_POINT = 1; SHAPE_TYPE_ARC = 3; - * SHAPE_TYPE_POLYLINE = 3; SHAPE_TYPE_POLYGON = 5; - * SHAPE_TYPE_MULTIPOINT = 8; SHAPE_TYPE_POINTZ = 11; - * SHAPE_TYPE_POLYLINEZ = 13; SHAPE_TYPE_POLYGONZ = 15; - * SHAPE_TYPE_MUILTIPOINTZ = 18; SHAPE_TYPE_POINTM = 21; - * SHAPE_TYPE_POLYLINEM = 23; SHAPE_TYPE_POLYGONM = 25; - * SHAPE_TYPE_MULTIPOINTM = 28; SHAPE_TYPE_MULTIPATCH = 31; - */ - EsriGraphic eg = null; - - int shapeType = iStream.readLEInt(); - byteTracker.addRead(4); - - if (verbose) { - logger.info("reading shape type: " + shapeType + ", " - + ShapeUtils.getStringForType(shapeType)); - } - - switch (shapeType) { - - case SHAPE_TYPE_NULL: - break; - case SHAPE_TYPE_POINT: - eg = createPointGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINE: - eg = createPolylineGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGON: - eg = createPolygonGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINT: - eg = createMultiPointGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POINTZ: - eg = createPointZGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINEZ: - eg = createPolylineZGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGONZ: - eg = createPolygonZGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINTZ: - eg = createMultiPointZGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POINTM: - eg = createPointMGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYLINEM: - eg = createPolylineMGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_POLYGONM: - eg = createPolygonMGraphic(iStream, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPOINTM: - eg = createMultiPointMGraphic(iStream, pointRepresentation, drawingAttributes, byteTracker); - break; - case SHAPE_TYPE_MULTIPATCH: - - default: - - } - - return (OMGraphic) eg; - - } - - // ///////// Point and Multi-Point Shapes - - protected EsriGraphic createPointGraphic(double x, double y, Object representation, - DrawingAttributes drawingAttributes) { - - if (dataTransformation != null) { - Point2D llp = dataTransformation.inverse(x, y); - - if (verbose) { - logger.info("point: " + x + ", " + y + " converted to " + llp); - } - - x = llp.getX(); - y = llp.getY(); - } else if (verbose) { - logger.info("point: " + x + ", " + y); - } - - EsriGraphic ret = null; - - if (representation == null) { - ret = new EsriPoint((float) y, (float) x); - } else if (representation instanceof ImageIcon) { - ret = new EsriIconPoint((float) y, (float) x, (ImageIcon) representation); - } else if (representation instanceof String) { - ret = new EsriTextPoint((float) y, (float) x, (String) representation, OMText.JUSTIFY_CENTER); - } - - if (drawingAttributes != null && ret != null) { - drawingAttributes.setTo((OMGraphic) ret); - } - return ret; - } - - /** - * Reads the ShapeFile and creates a OMPoint/OMRaster/OMText from the point - * object. - * - * @param shpFile with the file pointer right after the shape record shape - * type bytes. It's assumed that the shape type has been read to - * determine that the shapeType for this record is a Point record. - * @param representation The object to use for representing the Point. If - * the object is an ImageIcon, that image is used for a scaling icon - * at this point. If it's a String, and OMText will be created for - * that Point (center-justified). If it's null, the drawing - * attributes values will be used for an OMPoint. - * @param drawingAttributes the attributes for the OMGraphic. - * @param byteTracker - * @return OMPoint or OMScalingRaster or OMText - * @throws IOException - */ - protected EsriGraphic createPointGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - - double x = shpFile.readDouble(); - double y = shpFile.readDouble(); - byteTracker.addRead(2 * 8); - return createPointGraphic(x, y, representation, drawingAttributes); - } - - protected EsriGraphic createPointGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - - double x = iStream.readLEDouble(); - double y = iStream.readLEDouble(); - byteTracker.addRead(2 * 8); - return createPointGraphic(x, y, representation, drawingAttributes); - } - - protected EsriGraphic createMultiPointGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - // Skip reading the bounding box, 4 doubles - shpFile.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - int numParts = shpFile.readInteger(); - EsriPointList multiPart = new EsriPointList(); - multiPart.setVague(true); - - for (int i = 0; i < numParts; i++) { - EsriGraphic part = createPointGraphic(shpFile, representation, drawingAttributes, byteTracker); - if (part != null) { - multiPart.add((OMGraphic) part); - } - } - - return multiPart; - } - - protected EsriGraphic createMultiPointGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - // Skip reading the bounding box, 4 doubles - iStream.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - int numParts = iStream.readLEInt(); - EsriPointList multiPart = new EsriPointList(); - multiPart.setVague(true); - - for (int i = 0; i < numParts; i++) { - EsriGraphic part = createPointGraphic(iStream, representation, drawingAttributes, byteTracker); - if (part != null) { - multiPart.add((OMGraphic) part); - } - } - - return multiPart; - } - - protected EsriGraphic createPointZGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - double x = shpFile.readDouble(); - double y = shpFile.readDouble(); - double z = shpFile.readDouble(); - double m = shpFile.readDouble(); - byteTracker.addRead(4 * 8); - - EsriGraphic ret = createPointGraphic(x, y, representation, drawingAttributes); - ret.setType(SHAPE_TYPE_POINTZ); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, new Double(m)); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, new Double(z)); - return ret; - } - - protected EsriGraphic createPointZGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - double x = iStream.readLEDouble(); - double y = iStream.readLEDouble(); - double z = iStream.readLEDouble(); - double m = iStream.readLEDouble(); - byteTracker.addRead(4 * 8); - - EsriGraphic ret = createPointGraphic(x, y, representation, drawingAttributes); - ret.setType(SHAPE_TYPE_POINTZ); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, new Double(m)); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, new Double(z)); - return ret; - } - - protected EsriGraphic createMultiPointZGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic multiPart = createMultiPointGraphic(shpFile, representation, drawingAttributes, byteTracker); - - if (multiPart instanceof EsriGraphicList) { - ((EsriGraphicList) multiPart).setType(SHAPE_TYPE_MULTIPOINTZ); - int numPoints = ((EsriGraphicList) multiPart).size(); - - double minZ = shpFile.readDouble(); - double maxZ = shpFile.readDouble(); - double[] zs = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - zs[i] = shpFile.readDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_Z_ATTRIBUTE, new Double(minZ)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_Z_ATTRIBUTE, new Double(maxZ)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, zs); - - byteTracker.addRead((2 + numPoints) * 8); - - if (byteTracker.numLeft() > 0) { - double minM = shpFile.readDouble(); - double maxM = shpFile.readDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = shpFile.readDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - - return multiPart; - } - - protected EsriGraphic createMultiPointZGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic multiPart = createMultiPointGraphic(iStream, representation, drawingAttributes, byteTracker); - - if (multiPart instanceof EsriGraphicList) { - ((EsriGraphicList) multiPart).setType(SHAPE_TYPE_MULTIPOINTZ); - int numPoints = ((EsriGraphicList) multiPart).size(); - - double minZ = iStream.readLEDouble(); - double maxZ = iStream.readLEDouble(); - double[] zs = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - zs[i] = iStream.readLEDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_Z_ATTRIBUTE, new Double(minZ)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_Z_ATTRIBUTE, new Double(maxZ)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, zs); - - byteTracker.addRead((2 + numPoints) * 8); - - if (byteTracker.numLeft() > 0) { - double minM = iStream.readLEDouble(); - double maxM = iStream.readLEDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = iStream.readLEDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - - return multiPart; - } - - protected EsriGraphic createPointMGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - double x = shpFile.readDouble(); - double y = shpFile.readDouble(); - double m = shpFile.readDouble(); - byteTracker.addRead(3 * 8); - - EsriGraphic ret = createPointGraphic(x, y, representation, drawingAttributes); - ret.setType(SHAPE_TYPE_POINTM); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, new Double(m)); - return ret; - } - - protected EsriGraphic createPointMGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - double x = iStream.readLEDouble(); - double y = iStream.readLEDouble(); - double m = iStream.readLEDouble(); - byteTracker.addRead(3 * 8); - - EsriGraphic ret = createPointGraphic(x, y, representation, drawingAttributes); - ret.setType(SHAPE_TYPE_POINTM); - ((OMGraphic) ret).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, new Double(m)); - return ret; - } - - protected EsriGraphic createMultiPointMGraphic(BinaryFile shpFile, Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic multiPart = createMultiPointGraphic(shpFile, representation, drawingAttributes, byteTracker); - - if (multiPart instanceof EsriGraphicList) { - ((EsriGraphicList) multiPart).setType(SHAPE_TYPE_MULTIPOINTM); - int numPoints = ((EsriGraphicList) multiPart).size(); - - if (byteTracker.numLeft() > 0) { - double minM = shpFile.readDouble(); - double maxM = shpFile.readDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = shpFile.readDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - - return multiPart; - } - - protected EsriGraphic createMultiPointMGraphic(LittleEndianInputStream iStream, - Object representation, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic multiPart = createMultiPointGraphic(iStream, representation, drawingAttributes, byteTracker); - - if (multiPart instanceof EsriGraphicList) { - ((EsriGraphicList) multiPart).setType(SHAPE_TYPE_MULTIPOINTM); - int numPoints = ((EsriGraphicList) multiPart).size(); - - if (byteTracker.numLeft() > 0) { - double minM = iStream.readLEDouble(); - double maxM = iStream.readLEDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = iStream.readLEDouble(); - } - - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - ((OMGraphic) multiPart).putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - - return multiPart; - } - - // ///////// Polygon Shapes - - protected EsriGraphic createPolygonGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyGraphic(shpFile, SHAPE_TYPE_POLYGON, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolygonGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyGraphic(iStream, SHAPE_TYPE_POLYGON, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyGraphic(shpFile, SHAPE_TYPE_POLYLINE, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyGraphic(iStream, SHAPE_TYPE_POLYLINE, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolyGraphic(BinaryFile shpFile, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - shpFile.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = shpFile.readInteger(); - int numPoints = shpFile.readInteger(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(shpFile, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - } - return ret; - } - - protected EsriGraphic createPolyGraphic(LittleEndianInputStream iStream, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - iStream.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = iStream.readLEInt(); - int numPoints = iStream.readLEInt(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(iStream, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - } - return ret; - } - - protected EsriGraphic createPolygonZGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyZGraphic(shpFile, SHAPE_TYPE_POLYGONZ, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolygonZGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyZGraphic(iStream, SHAPE_TYPE_POLYGONZ, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineZGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyZGraphic(shpFile, SHAPE_TYPE_POLYLINEZ, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineZGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyZGraphic(iStream, SHAPE_TYPE_POLYLINEZ, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolyZGraphic(BinaryFile shpFile, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - shpFile.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = shpFile.readInteger(); - int numPoints = shpFile.readInteger(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(shpFile, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - } - - double minZ = shpFile.readDouble(); - double maxZ = shpFile.readDouble(); - double[] zs = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - zs[i] = shpFile.readDouble(); - } - - OMGraphic omg = (OMGraphic) ret; - if (omg != null) { - omg.putAttribute(ShapeConstants.SHAPE_MIN_Z_ATTRIBUTE, new Double(minZ)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_Z_ATTRIBUTE, new Double(maxZ)); - omg.putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, zs); - } - byteTracker.addRead((2 + numPoints) * 8); - - if (byteTracker.numLeft() > 0) { - double minM = shpFile.readDouble(); - double maxM = shpFile.readDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = shpFile.readDouble(); - } - - if (omg != null) { - omg.putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - omg.putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - - return ret; - } - - protected EsriGraphic createPolyZGraphic(LittleEndianInputStream iStream, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - iStream.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = iStream.readLEInt(); - int numPoints = iStream.readLEInt(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(iStream, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - } - - double minZ = iStream.readLEDouble(); - double maxZ = iStream.readLEDouble(); - double[] zs = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - zs[i] = iStream.readLEDouble(); - } - - OMGraphic omg = (OMGraphic) ret; - if (omg != null) { - omg.putAttribute(ShapeConstants.SHAPE_MIN_Z_ATTRIBUTE, new Double(minZ)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_Z_ATTRIBUTE, new Double(maxZ)); - omg.putAttribute(ShapeConstants.SHAPE_Z_ATTRIBUTE, zs); - } - byteTracker.addRead((2 + numPoints) * 8); - - if (byteTracker.numLeft() > 0) { - double minM = iStream.readLEDouble(); - double maxM = iStream.readLEDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = iStream.readLEDouble(); - } - - if (omg != null) { - omg.putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - omg.putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - } - byteTracker.addRead((2 + numPoints) * 8); - } - - return ret; - } - - protected EsriGraphic createPolygonMGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyMGraphic(shpFile, SHAPE_TYPE_POLYGONM, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolygonMGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyMGraphic(iStream, SHAPE_TYPE_POLYGONM, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineMGraphic(BinaryFile shpFile, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyMGraphic(shpFile, SHAPE_TYPE_POLYLINEM, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolylineMGraphic(LittleEndianInputStream iStream, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - return createPolyMGraphic(iStream, SHAPE_TYPE_POLYLINEM, drawingAttributes, byteTracker); - } - - protected EsriGraphic createPolyMGraphic(BinaryFile shpFile, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - shpFile.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = shpFile.readInteger(); - int numPoints = shpFile.readInteger(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(shpFile, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - - if (byteTracker.numLeft() > 0) { - double minM = shpFile.readDouble(); - double maxM = shpFile.readDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = shpFile.readDouble(); - } - - OMGraphic omg = (OMGraphic) ret; - omg.putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - omg.putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - return ret; - } - - protected EsriGraphic createPolyMGraphic(LittleEndianInputStream iStream, int shapeType, - DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - - // Skip reading the bounding box, 4 doubles - iStream.skipBytes(4 * 8); - byteTracker.addRead(4 * 8); - - int numParts = iStream.readLEInt(); - int numPoints = iStream.readLEInt(); - byteTracker.addRead(2 * 4); - - if (numParts > 0) { - ret = getPolys(iStream, numParts, numPoints, shapeType, drawingAttributes, byteTracker); - - if (byteTracker.numLeft() > 0) { - double minM = iStream.readLEDouble(); - double maxM = iStream.readLEDouble(); - double[] ms = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - ms[i] = iStream.readLEDouble(); - } - - OMGraphic omg = (OMGraphic) ret; - omg.putAttribute(ShapeConstants.SHAPE_MIN_MEASURE_ATTRIBUTE, new Double(minM)); - omg.putAttribute(ShapeConstants.SHAPE_MAX_MEASURE_ATTRIBUTE, new Double(maxM)); - omg.putAttribute(ShapeConstants.SHAPE_MEASURE_ATTRIBUTE, ms); - byteTracker.addRead((2 + numPoints) * 8); - } - } - return ret; - } - - protected EsriGraphic getPolys(BinaryFile shpFile, int numParts, int numPoints, int shapeType, - DrawingAttributes drawingAttributes, ReadByteTracker byteTracker) - throws IOException, FormatException { - EsriGraphic ret = null; - if (verbose) { - logger.info("creating polygon for entry, parts(" + numParts + ") numPoints(" - + numPoints + ")"); - } - if (numParts > 1) { - ret = createEsriGraphicList(shapeType); - if (ret != null) { - ((EsriGraphicList) ret).setVague(true); - } - } - - int[] parts = new int[numParts]; - for (int i = 0; i < numParts; i++) { - parts[i] = shpFile.readInteger(); - } - byteTracker.addRead(numParts * 4); - - int origin = parts[0]; - int length = 0; - double[] coords; - for (int i = 1; i < numParts; i++) { - int nextOrigin = parts[i]; - length = nextOrigin - origin; - - coords = getCoords(shpFile, length, isPolygon(shapeType), dataTransformation, byteTracker); - - if (verbose) { - logger.info("creating " + ShapeUtils.getStringForType(shapeType) + "(" + i - + ") with coords[" + getCoordString(coords) + "]"); - } - - EsriGraphic omp = createEsriPoly(shapeType, coords, lineType, drawingAttributes); - if (ret != null) { - ((EsriGraphicList) ret).add((OMGraphic) omp); - } - - origin = nextOrigin; - } - - length = numPoints - origin; - - coords = getCoords(shpFile, length, isPolygon(shapeType), dataTransformation, byteTracker); - - if (verbose) { - logger.info("creating " + ShapeUtils.getStringForType(shapeType) + " with coords[" - + getCoordString(coords) + "]"); - } - - EsriGraphic omp = createEsriPoly(shapeType, coords, lineType, drawingAttributes); - - if (ret != null) { - ((EsriGraphicList) ret).add((OMGraphic) omp); - } else { - ret = (EsriGraphic) omp; - } - return ret; - } - - protected String getCoordString(double[] coords) { - StringBuffer coordString = new StringBuffer(); - for (int j = 0; j < coords.length; j += 2) { - coordString.append((j > 0 ? ":" : "")).append(coords[j]).append(",").append(coords[j + 1]); - } - return coordString.toString(); - } - - protected EsriGraphic getPolys(LittleEndianInputStream iStream, int numParts, int numPoints, - int shapeType, DrawingAttributes drawingAttributes, - ReadByteTracker byteTracker) throws IOException, FormatException { - EsriGraphic ret = null; - - if (numParts > 1) { - ret = createEsriGraphicList(shapeType); - if (ret != null) { - ((EsriGraphicList) ret).setVague(true); - } - } - - int[] parts = new int[numParts]; - for (int i = 0; i < numParts; i++) { - parts[i] = iStream.readLEInt(); - } - byteTracker.addRead(numParts * 4); - - int origin = parts[0]; - int length = 0; - double[] coords; - for (int i = 1; i < numParts; i++) { - int nextOrigin = parts[i]; - length = nextOrigin - origin; - - coords = getCoords(iStream, length, isPolygon(shapeType), dataTransformation, byteTracker); - - if (verbose) { - logger.info("creating " + ShapeUtils.getStringForType(shapeType) + "(" + i - + ") with coords[" + getCoordString(coords) + "]"); - } - - EsriGraphic omp = createEsriPoly(shapeType, coords, lineType, drawingAttributes); - if (ret != null) { - ((EsriGraphicList) ret).add((OMGraphic) omp); - } - - origin = nextOrigin; - } - - length = numPoints - origin; - - coords = getCoords(iStream, length, isPolygon(shapeType), dataTransformation, byteTracker); - - if (verbose) { - logger.info("creating " + ShapeUtils.getStringForType(shapeType) + " with coords[" - + getCoordString(coords) + "]"); - } - - EsriGraphic omp = createEsriPoly(shapeType, coords, lineType, drawingAttributes); - - if (ret != null) { - ((EsriGraphicList) ret).add((OMGraphic) omp); - } else { - ret = (EsriGraphic) omp; - } - return ret; - } - - protected float[] getFloatCoords(BinaryFile shpFile, int length, boolean isPolygon, - GeoCoordTransformation dataTrans, ReadByteTracker bitTracker) - throws IOException, FormatException { - - float[] coords = new float[isPolygon ? length * 2 + 2 : length * 2]; - int j = 0; - - // Create the llp here and reuse it for coordinate transformations. - LatLonPoint llp = null; - if (dataTrans != null) { - llp = new LatLonPoint.Double(); - } - - for (j = 0; j < length; j++) { - double x = shpFile.readDouble(); - double y = shpFile.readDouble(); - bitTracker.addRead(2 * 8); - - if (dataTrans != null) { - llp = dataTrans.inverse(x, y, llp); - x = llp.getRadLon(); - y = llp.getRadLat(); - } else { - x = ProjMath.degToRad(x); - y = ProjMath.degToRad(y); - } - - coords[j * 2] = (float) y; - coords[j * 2 + 1] = (float) x; - } - - if (isPolygon) { - coords[j * 2] = coords[0]; - coords[j * 2 + 1] = coords[1]; - } - return coords; - } - - protected float[] getFloatCoords(LittleEndianInputStream iStream, int length, - boolean isPolygon, GeoCoordTransformation dataTrans, - ReadByteTracker bitTracker) - throws IOException, FormatException { - - float[] coords = new float[isPolygon ? length * 2 + 2 : length * 2]; - int j = 0; - - // Create the llp here and reuse it for coordinate transformations. - LatLonPoint llp = null; - if (dataTrans != null) { - llp = new LatLonPoint.Double(); - } - - for (j = 0; j < length; j++) { - double x = iStream.readLEDouble(); - double y = iStream.readLEDouble(); - bitTracker.addRead(2 * 8); - - if (dataTrans != null) { - llp = dataTrans.inverse(x, y, llp); - x = llp.getRadLon(); - y = llp.getRadLat(); - } else { - x = ProjMath.degToRad(x); - y = ProjMath.degToRad(y); - } - - coords[j * 2] = (float) y; - coords[j * 2 + 1] = (float) x; - } - - if (isPolygon) { - coords[j * 2] = coords[0]; - coords[j * 2 + 1] = coords[1]; - } - return coords; - } - - protected double[] getCoords(BinaryFile shpFile, int length, boolean isPolygon, - GeoCoordTransformation dataTrans, ReadByteTracker bitTracker) - throws IOException, FormatException { - - double[] coords = new double[isPolygon ? length * 2 + 2 : length * 2]; - int j = 0; - - // Create the llp here and reuse it for coordinate transformations. - LatLonPoint llp = null; - if (dataTrans != null) { - llp = new LatLonPoint.Double(); - } - - for (j = 0; j < length; j++) { - double x = shpFile.readDouble(); - double y = shpFile.readDouble(); - bitTracker.addRead(2 * 8); - - if (dataTrans != null) { - llp = dataTrans.inverse(x, y, llp); - x = llp.getRadLon(); - y = llp.getRadLat(); - } else { - x = ProjMath.degToRad(x); - y = ProjMath.degToRad(y); - } - - coords[j * 2] = y; - coords[j * 2 + 1] = x; - } - - if (isPolygon) { - coords[j * 2] = coords[0]; - coords[j * 2 + 1] = coords[1]; - } - return coords; - } - - protected double[] getCoords(LittleEndianInputStream iStream, int length, boolean isPolygon, - GeoCoordTransformation dataTrans, ReadByteTracker bitTracker) - throws IOException, FormatException { - - double[] coords = new double[isPolygon ? length * 2 + 2 : length * 2]; - int j = 0; - - // Create the llp here and reuse it for coordinate transformations. - LatLonPoint llp = null; - if (dataTrans != null) { - llp = new LatLonPoint.Double(); - } - - for (j = 0; j < length; j++) { - double x = iStream.readLEDouble(); - double y = iStream.readLEDouble(); - bitTracker.addRead(2 * 8); - - if (dataTrans != null) { - llp = dataTrans.inverse(x, y, llp); - x = llp.getRadLon(); - y = llp.getRadLat(); - } else { - x = ProjMath.degToRad(x); - y = ProjMath.degToRad(y); - } - - coords[j * 2] = y; - coords[j * 2 + 1] = x; - } - - if (isPolygon) { - coords[j * 2] = coords[0]; - coords[j * 2 + 1] = coords[1]; - } - return coords; - } - - public static boolean isPolygon(int shapeType) { - return shapeType == SHAPE_TYPE_POLYGON || shapeType == SHAPE_TYPE_POLYGONZ - || shapeType == SHAPE_TYPE_POLYGONM; - } - - public static EsriGraphic createEsriPoly(int shapeType, double[] coords, int lineType, - DrawingAttributes da) { - - if (da == null) { - da = DrawingAttributes.DEFAULT; - } - - EsriGraphic ret = null; - switch (shapeType) { - case SHAPE_TYPE_POLYGON: - ret = new EsriPolygon(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - break; - case SHAPE_TYPE_POLYLINE: - ret = new EsriPolyline(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - ((OMGraphic) ret).setFillPaint(OMColor.clear); - break; - case SHAPE_TYPE_POLYGONM: - ret = new EsriPolygonM(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - break; - case SHAPE_TYPE_POLYGONZ: - ret = new EsriPolygonZ(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - break; - case SHAPE_TYPE_POLYLINEM: - ret = new EsriPolylineM(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - ((OMGraphic) ret).setFillPaint(OMColor.clear); - break; - case SHAPE_TYPE_POLYLINEZ: - ret = new EsriPolylineZ(coords, OMPoly.RADIANS, lineType); - da.setTo((OMGraphic) ret); - ((OMGraphic) ret).setFillPaint(OMColor.clear); - break; - } - return ret; - } - - public static EsriGraphicList createEsriGraphicList(int shapeType) { - EsriGraphicList ret = null; - switch (shapeType) { - case SHAPE_TYPE_NULL: - break; - case SHAPE_TYPE_POINT: - case SHAPE_TYPE_MULTIPOINT: - case SHAPE_TYPE_POINTZ: - case SHAPE_TYPE_MULTIPOINTZ: - case SHAPE_TYPE_POINTM: - case SHAPE_TYPE_MULTIPOINTM: - ret = new EsriPointList(); - ret.setType(shapeType); - break; - case SHAPE_TYPE_POLYGON: - ret = new EsriPolygonList(); - break; - case SHAPE_TYPE_POLYLINE: - ret = new EsriPolylineList(); - break; - case SHAPE_TYPE_POLYGONM: - ret = new EsriPolygonMList(); - break; - case SHAPE_TYPE_POLYGONZ: - ret = new EsriPolygonZList(); - break; - case SHAPE_TYPE_POLYLINEM: - ret = new EsriPolylineMList(); - break; - case SHAPE_TYPE_POLYLINEZ: - ret = new EsriPolylineZList(); - break; - } - return ret; - } - - public GeoCoordTransformation getDataCoordTransformation() { - return dataTransformation; - } - - public void setDataCoordTransformation(GeoCoordTransformation dataTrans) { - this.dataTransformation = dataTrans; - } - - public int getLineType() { - return lineType; - } - - public void setLineType(int lineType) { - this.lineType = lineType; - } - - public Class getPrecision() { - return precision; - } - - public void setPrecision(Class precision) { - this.precision = precision; - } - - public static class ReadByteTracker { - int totalCount; - int currentCount; - - public ReadByteTracker() { - - } - - public ReadByteTracker(int tc) { - totalCount = tc; - } - - public int numLeft() { - return totalCount - currentCount; - } - - public int addRead(int num) { - currentCount += num; - return currentCount; - } - - public void reset(int newTotal) { - totalCount = newTotal; - currentCount = 0; - } - - public String toString() { - return "ReadByteTracker has noted " + currentCount + " of " + totalCount - + " bytes read"; - } - } - - public static class Header { - public int fileCode; - public int fileLength; - public int version; - public int shapeType; - public double xMin; - public double yMin; - public double xMax; - public double yMax; - public double zMin; - public double zMax; - public double mMin; - public double mMax; - - public Header(BinaryFile shp) throws IOException, FormatException { - this(shp, null); - } - - public Header(BinaryFile shp, GeoCoordTransformation dataTransformation) - throws IOException, FormatException { - shp.byteOrder(true); - shp.seek(0); - fileCode = shp.readInteger(); - shp.skipBytes(20); // unused - fileLength = shp.readInteger() * 2; - shp.byteOrder(false); - version = shp.readInteger(); - shapeType = shp.readInteger(); - xMin = shp.readDouble(); - yMin = shp.readDouble(); - xMax = shp.readDouble(); - yMax = shp.readDouble(); - zMin = shp.readDouble(); - zMax = shp.readDouble(); - mMin = shp.readDouble(); - mMax = shp.readDouble(); - - if (dataTransformation != null) { - LatLonPoint llpmin = dataTransformation.inverse(xMin, yMin); - xMin = llpmin.getX(); - yMin = llpmin.getY(); - LatLonPoint llpmax = dataTransformation.inverse(xMax, yMax); - xMax = llpmax.getX(); - yMax = llpmax.getY(); - } - } - - public Header(LittleEndianInputStream iStream) throws IOException { - this(iStream, null); - } - - public Header(LittleEndianInputStream iStream, GeoCoordTransformation dataTransformation) - throws IOException { - fileCode = iStream.readInt(); - iStream.skipBytes(20); // unused - fileLength = iStream.readInt() * 2; - version = iStream.readLEInt(); - shapeType = iStream.readLEInt(); - xMin = iStream.readLEDouble(); - yMin = iStream.readLEDouble(); - xMax = iStream.readLEDouble(); - yMax = iStream.readLEDouble(); - zMin = iStream.readLEDouble(); - zMax = iStream.readLEDouble(); - mMin = iStream.readLEDouble(); - mMax = iStream.readLEDouble(); - - if (dataTransformation != null) { - LatLonPoint llpmin = dataTransformation.inverse(xMin, yMin); - xMin = llpmin.getX(); - yMin = llpmin.getY(); - LatLonPoint llpmax = dataTransformation.inverse(xMax, yMax); - xMax = llpmax.getX(); - yMax = llpmax.getY(); - } - } - - public DataBounds getDataBounds() { - return new DataBounds(xMin, yMin, xMax, yMax); - } - - public String toString() { - return "header[fc=" + fileCode + ",len=" + fileLength + ",ver=" + version + ",type=" - + shapeType + "]"; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java deleted file mode 100644 index 2a3079318..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java +++ /dev/null @@ -1,411 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java,v $ -// $RCSfile: EsriGraphicList.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.shape.input.ShpInputStream; -import com.bbn.openmap.dataAccess.shape.input.ShxInputStream; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.PropUtils; - -/** - * EsriGraphicList ensures that only supported geometry types are added to its - * list. Each subclass of this EsriGraphicList list will hold polyline, polygon, - * or point geometry -- other types of geometry are not supported. As shapes are - * added to the list, EsriGraphicList will ensure that the type of geometry - * being added is the same type of geometry as specified by the subclass list - * type. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public abstract class EsriGraphicList extends OMGraphicList implements ShapeConstants, EsriGraphic { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.EsriGraphicList"); - protected double[] extents; - protected int type; - - /** - * Over-ride the add( ) method to trap for inconsistent shape geometry. If - * you are adding a OMGraphic that is not a list, make sure this list is a - * sub-list containing multiple geometry parts. Only add another list to a - * top level EsriGraphicList. - * - * @param shape the non-null OMGraphic to add - */ - public boolean add(OMGraphic shape) { - return super.add(shape); - } - - /** - * Add an OMGraphic to the GraphicList. The OMGraphic must not be null. - * - * @param g the non-null OMGraphic to add - * @return true if addition is successful. - * @exception IllegalArgumentException if OMGraphic is null - */ - public boolean addOMGraphic(OMGraphic g) { - return add(g); - } - - public void setType(int type) { - this.type = type; - } - - /** - * Get the list type in ESRI type number form - */ - public int getType() { - return type; - } - - /** - * Construct an EsriGraphicList. - */ - public EsriGraphicList() { - super(); - } - - /** - * Construct an EsriGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriGraphicList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an EsriGraphicList with an initial capacity and a standard - * increment value. - * - * @param initialCapacity the initial capacity of the list - * @param capacityIncrement the capacityIncrement for resizing - * @deprecated capacityIncrement doesn't do anything. - */ - public EsriGraphicList(int initialCapacity, int capacityIncrement) { - super(initialCapacity); - } - - /** - * The lat/lon extent of the EsriGraphicList contents, assumed to contain - * miny, minx, maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - this.extents = extents; - } - - /** - * The lat/lon extent of the EsriGraphicList contents, returned as miny, - * minx, maxy maxx in order of the array. - */ - public double[] getExtents() { - if (extents == null) { - // These are set to their opposites to guarantee some - // movement. - extents = new double[] { 90f, 180f, -90f, -180f }; - } - - return extents; - } - - public void addExtents(double[] graphicExtents) { - double[] ex = getExtents(); - - // Check both graphic extents in case they are inadvertently - // switched. - for (int i = 0; i < graphicExtents.length; i += 2) { - if (ex[0] > graphicExtents[i]) - ex[0] = graphicExtents[i]; - if (ex[1] > graphicExtents[i + 1]) - ex[1] = graphicExtents[i + 1]; - if (ex[2] < graphicExtents[i]) - ex[2] = graphicExtents[i]; - if (ex[3] < graphicExtents[i + 1]) - ex[3] = graphicExtents[i + 1]; - } - - // System.out.println("extents of list: " + - // ex[1] + ", " + - // ex[0] + ", " + - // ex[3] + ", " + - // ex[2]); - - } - - /** - * Set the DbfTableModel in the AppObject of this list that holds the - * attribute information about this list's objects. - */ - public void setTable(DbfTableModel dtm) { - if (dtm != null) { - putAttribute(DBF_ATTRIBUTE, dtm); - } else { - removeAttribute(DBF_ATTRIBUTE); - } - } - - /** - * Get the DbfTableModel object from the AppObject of this list. - */ - public DbfTableModel getTable() { - Object obj = getAttribute(DBF_ATTRIBUTE); - if (obj instanceof DbfTableModel) { - return (DbfTableModel) obj; - } else { - return null; - } - } - - /** - * Create a generic DbfTableModel for the contents of this list, where the - * attributes hold rendering properties for the list contents. The table is - * stored in the AppObject member variable of the list. - */ - public void createTable() { - // lineWidth, lineColor, fillColor, selectColor We could do - // stroke info. Toss space in there for name, or general - // attribute for later. - // this.setAppObject(EsriShapeExport.createDefaultModel(this)); - putAttribute(DBF_ATTRIBUTE, EsriShapeExport.createDefaultModel(this)); - } - - /** - * Reads the contents of the SHX and SHP files. The SHX file will be read - * first by utilizing the ShapeIndex.open method. This method will return a - * list of offsets, which the AbstractSupport.open method will use to - * iterate through the contents of the SHP file. - * - * @param shp The url of the SHP file - * @param shx The url of the SHX file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if - * this is null. - * @param dbf a DbfTableModel, if you want each row of objects from the - * table (an array), inserted into their associated OMGraphic's - * appObject. The dbf will be added to the list appObject, so you - * can ask it questions later. If null, no problem. If the number - * of records doesn't match the OMGraphic list length, nothing - * will be done. - * @return A new EsriGraphicList, null if there is a problem. - * - * @deprecated use getGraphicList(URL, DrawingAttributes, DbfTableModel) - */ - public static EsriGraphicList getEsriGraphicList(URL shp, URL shx, DrawingAttributes drawingAttributes, - DbfTableModel dbf) { - return getEsriGraphicList(shp, drawingAttributes, dbf, null); - } - - /** - * Reads the contents of the SHP files. - * - * @param shp The url of the SHP file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if - * this is null. - * @param dbf a DbfTableModel. The dbf will be added to the list appObject, - * so you can ask it questions later. If null, no problem. If the - * number of records doesn't match the OMGraphic list length, - * nothing will be done. - * @param coordTranslator a GeoCoordTransformation to use to convert - * coordinates to decimal degree lat/lon data. - * @return A new EsriGraphicList, null if there is a problem. - */ - public static EsriGraphicList getEsriGraphicList(URL shp, DrawingAttributes drawingAttributes, DbfTableModel dbf, - GeoCoordTransformation coordTranslator) { - EsriGraphicList list = null; - - // Open and stream shp file - try { - InputStream is = shp.openStream(); - ShpInputStream pis = new ShpInputStream(is); - if (drawingAttributes != null) { - pis.setDrawingAttributes(drawingAttributes); - } - EsriGraphicFactory egf = new EsriGraphicFactory(OMGraphic.LINETYPE_GREATCIRCLE, coordTranslator); - list = pis.getGeometry(egf); - is.close(); - } catch (Exception e) { - logger.warning("Not able to stream SHP file"); - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - return null; - } - - if (list != null && dbf != null && dbf.getRowCount() == list.size()) { - list.setTable(dbf); - } - - return list; - } - - /** - * Reads the contents of the SHP files, including the DBF file, based on the - * location of the shape file. The dbf will be added to the list appObject, - * so you can ask it questions later. If null, no problem. If the number of - * records doesn't match the OMGraphic list length, the dbf information - * won't be added to the list. - * - * @param shp The url of the SHP file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if - * this is null. - * @param coordTranslator used to transform coordinates to lat/lon decimal - * degrees for OpenMap. - * @return A new EsriGraphicList, null if there is a problem. - */ - public static EsriGraphicList getEsriGraphicList(URL shp, DrawingAttributes drawingAttributes, - GeoCoordTransformation coordTranslator) { - DbfTableModel dbf = null; - - if (shp != null) { - String shpPath = shp.getFile(); - String protocol = shp.getProtocol(); - String host = shp.getHost(); - - if (shpPath != null && shpPath.endsWith(".shp")) { - String dbfPath = shpPath.replace(".shp", ".dbf"); - URL dbfURL; - try { - dbfURL = new URL(protocol, host, dbfPath); - dbf = DbfTableModel.getDbfTableModel(dbfURL); - dbfURL = null; - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - } - - return getEsriGraphicList(shp, drawingAttributes, dbf, coordTranslator); - } - - /** - * Find EsriGraphics with a certain attribute - * - * @param value the value of the desired attribute. - * @param columnName the columnName in the dbf - * @return new List of EsriGraphic shapes with value in column - * @throws FormatException thrown if columnName isn't found. - */ - public List getGraphicsWithValueInColumn(Object value, String columnName) throws FormatException { - List ret = new ArrayList(); - DbfTableModel dbf = getTable(); - int colIndex = dbf.findColumn(columnName); - if (colIndex != -1) { - for (OMGraphic eg : this) { - Integer index = (Integer) eg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - List atts = dbf.getRecord(index); - - if (atts.get(colIndex).equals(value)) { - ret.add((EsriGraphic) eg); - } - } - } else { - throw new FormatException("Column " + columnName + " not found"); - } - - return ret; - } - - public static void main(String[] args) { - - ArgParser ap = new ArgParser("EsriGraphicList"); - ap.add("fixcl", "Check and fix content length of Shape file", 1); - ap.add("print", "Display text structure of shapes in Shape file", 1); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String[] fixit = ap.getArgValues("fixcl"); - if (fixit != null) { - String shape = fixit[0]; - if (shape.endsWith(".shp")) { - shape = shape.substring(0, shape.length() - 4); - - try { - URL shx = PropUtils.getResourceOrFileOrURL(shape + ".shx"); - InputStream is = shx.openStream(); - ShxInputStream pis = new ShxInputStream(is); - int[][] index = pis.getIndex(); - is.close(); - - RandomAccessFile raf = new RandomAccessFile(shape + ".shp", "rw"); - raf.seek(24); - int contentLength = raf.readInt(); - - int indexedContentLength = index[0][index[0].length - 1] + index[1][index[1].length - 1]; - - if (contentLength != indexedContentLength) { - System.out.println( - shape + " content length - shp: " + contentLength + ", shx: " + indexedContentLength); - raf.seek(24); - raf.writeInt(indexedContentLength); - } - raf.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - } else { - System.out.println("Shape " + shape + " doesn't look like a shape file"); - } - } - - String[] printit = ap.getArgValues("print"); - if (printit != null) { - try { - EsriGraphicList.logger.setLevel(Level.FINER); - EsriGraphicFactory.logger.setLevel(Level.FINER); - URL eglURL = PropUtils.getResourceOrFileOrURL(printit[0]); - EsriGraphicList egl = EsriGraphicList.getEsriGraphicList(eglURL, null, null); - if (egl != null) { - System.out.println(egl.getDescription()); - } - - } catch (Exception e) { - logger.warning(e.getMessage()); - e.printStackTrace(); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriIconPoint.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriIconPoint.java deleted file mode 100644 index 1e331f85e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriIconPoint.java +++ /dev/null @@ -1,106 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriIconPoint.java,v $ -// $RCSfile: EsriIconPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.Image; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMScalingIcon; - -/** - * An extension to OMPoint that typecasts a specific Esri graphic type. Used to - * ensure that all OMGraphics added to a EsriGraphicList is of the same type. - * - * @author Doug Van Auken - */ -public class EsriIconPoint extends OMScalingIcon implements Cloneable, - EsriGraphic, OMGraphicConstants { - - protected int type = SHAPE_TYPE_POINT; - - public EsriIconPoint(double lat, double lon, ImageIcon imageIcon) { - super(lat, lon, imageIcon); - } - - public EsriIconPoint(double lat, double lon, Image image) { - super(lat, lon, image); - } - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, minx, - * maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - // we know what it is. - } - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, maxy maxx - * in order of the array. - */ - public double[] getExtents() { - double[] ex = new double[4]; - ex[0] = getLat(); - ex[1] = getLon(); - ex[2] = getLat(); - ex[3] = getLon(); - return ex; - } - - public void setType(int t) { - type = t; - } - - public int getType() { - return type; - } - - public static EsriIconPoint convert(OMScalingIcon omscalingicon) { - if (omscalingicon.getRenderType() == RENDERTYPE_LATLON) { - EsriIconPoint eip = new EsriIconPoint(omscalingicon.getLat(), omscalingicon.getLon(), omscalingicon.getImage()); - eip.setBaseScale(omscalingicon.getBaseScale()); - eip.setMaxScale(omscalingicon.getMaxScale()); - eip.setMinScale(omscalingicon.getMinScale()); - eip.setAttributes(omscalingicon.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(omscalingicon); - attributes.setTo(eip); - - return eip; - } else { - return null; - } - } - - public EsriGraphic shallowCopy() { - return shallowCopyPoint(); - } - - public EsriIconPoint shallowCopyPoint() { - return (EsriIconPoint) super.clone(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPoint.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPoint.java deleted file mode 100644 index d2784d0be..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPoint.java +++ /dev/null @@ -1,102 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPoint.java,v $ -// $RCSfile: EsriPoint.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMPoint; - -/** - * An extension to OMPoint that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList - * is of the same type. - * - * @author Doug Van Auken - */ -public class EsriPoint extends OMPoint implements Cloneable, EsriGraphic, - OMGraphicConstants { - - protected int type = SHAPE_TYPE_POINT; - - public EsriPoint(double lat, double lon) { - super(lat, lon); - } - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, - * minx, maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - // we know what it is. - } - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, - * maxy maxx in order of the array. - */ - public double[] getExtents() { - double[] ex = new double[4]; - ex[0] = getLat(); - ex[1] = getLon(); - ex[2] = getLat(); - ex[3] = getLon(); - return ex; - } - - public void setType(int t) { - type = t; - } - - public int getType() { - return type; - } - - public static EsriPoint convert(OMPoint ompoint) { - if (ompoint.getRenderType() == RENDERTYPE_LATLON) { - EsriPoint ePoint = new EsriPoint(ompoint.getLat(), ompoint.getLon()); - ePoint.setAttributes(ompoint.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoint); - attributes.setTo(ePoint); - - // Hmmm. looses drawing information, like Oval, etc. - // That's not even kept in the shape file, so it might be - // something for the drawing attributes. Better save it - // in case someone looks for it later. - ePoint.setOval(ompoint.isOval()); - ePoint.setRadius(ompoint.getRadius()); - return ePoint; - } else { - return null; - } - } - - public EsriGraphic shallowCopy() { - return shallowCopyPoint(); - } - - public EsriPoint shallowCopyPoint() { - return (EsriPoint) super.clone(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPointList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPointList.java deleted file mode 100644 index d8670fec0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPointList.java +++ /dev/null @@ -1,128 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPointList.java,v $ -// $RCSfile: EsriPointList.java,v $ -// $Revision: 1.9 $ -// $Date: 2007/01/30 18:39:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.Debug; - -/** - * An EsriGraphicList ensures that only EsriPoints are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPointList extends EsriGraphicList { - - /** - * Over-ride the add( ) method to trap for inconsistent shape geometry. - * - * @param shape the non-null OMGraphic to add - */ - public boolean add(OMGraphic shape) { - try { - - if (typeMatches(shape)) { - addExtents(((EsriGraphic) shape).getExtents()); - return graphics.add(shape); - } else if (shape instanceof OMPoint) { - shape = EsriPoint.convert((OMPoint) shape); - // test for null in next if statement. - } else if (shape instanceof OMText) { - shape = EsriTextPoint.convert((OMText) shape); - } else if (shape instanceof OMScalingIcon) { - shape = EsriIconPoint.convert((OMScalingIcon) shape); - } else if (shape instanceof OMGraphicList - && !((OMGraphicList) shape).isVague()) { - for (Iterator it = ((OMGraphicList) shape).iterator(); it.hasNext();) { - add((OMGraphic) it.next()); - } - - return true; - - } else { - Debug.message("esri", - "EsriPointList.add()- graphic isn't an EsriGraphic with matching type, can't add."); - return false; - } - - // Test for and add shapes for point, text and scaling icon instances. - if (shape instanceof EsriGraphic) { - graphics.add(shape); - addExtents(((EsriGraphic) shape).getExtents()); - } - - } catch (ClassCastException cce) { - } - return false; - } - - public boolean typeMatches(OMGraphic omg) { - return omg instanceof EsriGraphic - && ((EsriGraphic) omg).getType() == getType(); - } - - /** - * Construct an EsriPointList. - */ - public EsriPointList() { - super(); - setType(SHAPE_TYPE_POINT); - } - - /** - * Construct an EsriPointList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPointList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an EsriPointList with an initial capacity and a standard - * increment value. - * - * @param initialCapacity the initial capacity of the list - * @param capacityIncrement the capacityIncrement for resizing - * @deprecated capacityIncrement doesn't do anything. - */ - public EsriPointList(int initialCapacity, int capacityIncrement) { - super(initialCapacity); - } - - public EsriGraphic shallowCopy() { - EsriPointList ret = new EsriPointList(size()); - ret.setAttributes(getAttributes()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygon.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygon.java deleted file mode 100644 index ab180a3e5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygon.java +++ /dev/null @@ -1,127 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygon.java,v $ -// $RCSfile: EsriPolygon.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.ProjMath; - -/** - * An extension to OMPoly for polygons that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolygon extends OMPoly implements Cloneable, EsriGraphic { - - protected double[] extents; - - public EsriPolygon(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, minx, - * maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - this.extents = extents; - } - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, maxy maxx - * in order of the array. - */ - public double[] getExtents() { - if (extents == null) { - // These are set to their opposites to guarantee some - // movement. - extents = new double[] { 90f, 180f, -90f, -180f }; - - double[] points = super.getLatLonArray(); - double[] degreePoints = new double[points.length]; - System.arraycopy(points, 0, degreePoints, 0, points.length); - addExtents(ProjMath.arrayRadToDeg(degreePoints)); - } - return extents; - } - - /** No-op. */ - public void setType(int t) {} - - public int getType() { - return SHAPE_TYPE_POLYGON; - } - - public void addExtents(double[] graphicExtents) { - double[] ex = getExtents(); - - // Check both graphic extents in case they are inadvertently - // switched. - for (int i = 0; i < graphicExtents.length - 1; i += 2) { - if (ex[0] > graphicExtents[i]) - ex[0] = graphicExtents[i]; - if (ex[1] > graphicExtents[i + 1]) - ex[1] = graphicExtents[i + 1]; - if (ex[2] < graphicExtents[i]) - ex[2] = graphicExtents[i]; - if (ex[3] < graphicExtents[i + 1]) - ex[3] = graphicExtents[i + 1]; - } - - // System.out.println("extents of Polygon: " + - // ex[1] + ", " + - // ex[0] + ", " + - // ex[3] + ", " + - // ex[2]); - } - - public static EsriPolygon convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolygon ePoly = new EsriPolygon(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - ePoly.setAttributes(ompoly.getAttributes()); - ePoly.setIsPolygon(true); - return ePoly; - } else { - return null; - } - } - - public EsriGraphic shallowCopy() { - return shallowCopyPolygon(); - } - - public EsriPolygon shallowCopyPolygon() { - return (EsriPolygon) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonList.java deleted file mode 100644 index cbe450f2f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonList.java +++ /dev/null @@ -1,271 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygonList.java,v $ -// $RCSfile: EsriPolygonList.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRangeRings; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * An EsriGraphicList ensures that only EsriPolygons are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolygonList extends EsriGraphicList { - - /** - * Over-ride the add( ) method to trap for inconsistent shape geometry. If - * you are adding a OMGraphic that is not a list, make sure this list is a - * sub-list containing multiple geometry parts. Only add another list to a - * top level EsriGraphicList. - * - * @param shape the non-null OMGraphic to add - */ - public boolean add(OMGraphic shape) { - boolean ret = false; - try { - - if (typeMatches(shape)) { - ret = graphics.add(shape); - addExtents(((EsriGraphic) shape).getExtents()); - } else if (shape instanceof OMPoly) { - EsriPolygon eg = convert((OMPoly) shape); - if (typeMatches(eg)) { - ret = graphics.add(eg); - addExtents(eg.getExtents()); - } - } else if (shape instanceof OMGraphicList - && !((OMGraphicList) shape).isVague()) { - for (Iterator it = ((OMGraphicList) shape).iterator(); it.hasNext();) { - add((OMGraphic) it.next()); - } - ret = true; - } else { - Debug.message("esri", - "EsriPolygonList.add()- graphic isn't a EsriPoly or OMPoly, can't add."); - } - } catch (ClassCastException cce) { - } - return ret; - } - - public EsriPolygon convert(OMPoly ompoly) { - return EsriPolygon.convert(ompoly); - } - - public boolean typeMatches(OMGraphic omg) { - return (omg instanceof EsriGraphic && ((EsriGraphic) omg).getType() == getType()); - } - - /** - * Get the list type in ESRI type number form - 5. - */ - public int getType() { - return SHAPE_TYPE_POLYGON; - } - - /** - * Construct an EsriPolygonList. - */ - public EsriPolygonList() { - super(); - } - - /** - * Construct an EsriPolygonList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolygonList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an EsriPolygonList with an initial capacity and a standard - * increment value. - * - * @param initialCapacity the initial capacity of the list - * @param capacityIncrement the capacityIncrement for resizing - * @deprecated capacityIncrement doesn't do anything. - */ - public EsriPolygonList(int initialCapacity, int capacityIncrement) { - super(initialCapacity); - } - - // converts rectangles into polygons - public static OMPoly convert(OMRect omRect) { - double[] rectPoints = new double[10]; - - // get the northwest corner - rectPoints[0] = (omRect.getNorthLat()); - rectPoints[1] = (omRect.getWestLon()); - // get the southwest corner - rectPoints[2] = (omRect.getSouthLat()); - rectPoints[3] = (omRect.getWestLon()); - // get the southeast corner - rectPoints[4] = (omRect.getSouthLat()); - rectPoints[5] = (omRect.getEastLon()); - // get the northeast corner - rectPoints[6] = (omRect.getNorthLat()); - rectPoints[7] = (omRect.getEastLon()); - // get the northwest corner again to close the polygon - rectPoints[8] = (omRect.getNorthLat()); - rectPoints[9] = (omRect.getWestLon()); - - // using the OMRect data create an OMPoly - OMPoly poly = new OMPoly(rectPoints, OMGraphic.DECIMAL_DEGREES, omRect.getLineType()); - poly.setAttributes(omRect.getAttributes()); - DrawingAttributes da = new DrawingAttributes(); - da.setFrom(omRect); - da.setTo(poly); - return poly; - } - - // converts circles into polygons - public static OMPoly convert(OMCircle omCircle, Projection proj) { - GeneralPath shape = omCircle.getShape(); - - // get the PathIterator that defines the outline of the circle - PathIterator circle = shape.getPathIterator(null); - Vector initialPoints = new Vector(); - double[] segPoints = new double[2]; - - while (!circle.isDone()) { - // by passing segpoints the array is filled with each x\y - // point iterated by the circle - int segType = circle.currentSegment(segPoints); - initialPoints.add(new Float(segPoints[0])); - initialPoints.add(new Float(segPoints[1])); - circle.next(); - } - - double[] circlePoints = new double[initialPoints.size()]; - - if (proj == null) { - return null; - } - - LatLonPoint.Double llp = new LatLonPoint.Double(); - // convert the x/y points to lat/lon points - for (int p = 0; p < initialPoints.size(); p += 2) { - proj.inverse(((Float) initialPoints.elementAt(p)).doubleValue(), - ((Float) initialPoints.elementAt(p + 1)).doubleValue(), - llp); - - circlePoints[p] = (float) llp.getRadLat(); - circlePoints[p + 1] = (float) llp.getRadLon(); - } - - // using the circle data create an OMPoly - OMPoly poly = new OMPoly(circlePoints, OMGraphic.RADIANS, omCircle.getLineType()); - poly.setAttributes(omCircle.getAttributes()); - DrawingAttributes da = new DrawingAttributes(); - da.setFrom(omCircle); - da.setTo(poly); - return poly; - } - - // converts range rings to circles which are passed to the - // convertCircles() method to be converted to OMPolys - public static OMGraphicList convert(OMRangeRings omRR, Projection proj) { - // get the array of circles - OMCircle[] circles = omRR.createCircles(); - OMGraphicList circleList = new OMGraphicList(); - circleList.setAttributes(omRR.getAttributes()); - - // get the line color and fill color that are to be passed - // with - // the dbf info - // Color lineColor = - // getColorString(dtlGraphic.getLineColor()); - // Color fillColor = - // getColorString(dtlGraphic.getFillColor()); - - if (proj == null) { - return circleList; - } - - for (int i = 0; i < circles.length; i++) { - // information passed to the dbflist includes the interval - // units and the interval - // dbfList = getDbfList("RangeRings(" + - // omRR.getIntervalUnits().toString() + "s)", - // omRR.getInterval() * (i + 1), lineColor, fillColor); - - // have to re-generate each circle in the range ring array - if (circles[i].generate(proj)) { - // call convertCircles to convert each ring to an - // OMPoly - OMPoly poly = convert((OMCircle) circles[i], proj); - // call the method to add this ring to the EsriLayer - if (poly != null) { - circleList.add(poly); - } - } else { - System.out.println("Could not generate circle from RangeRing"); - return null; - } - } - - // the RangeRings.createCircles() method used above only - // creates the inner circles, therefore the RangeRing object - // provides the outer ring that must be added to the layer - - // information passed to the dbflist includes the interval - // units and the interval since we don't know the exact - // interval of the last ring the string "less than" is applied - // to the last rings interval - // dbfList = getDbfList("RangeRings(" + - // omRR.getIntervalUnits().toString() + ")less than", - // omRR.getInterval() * (i + 1), lineColor, fillColor); - - DrawingAttributes da = new DrawingAttributes(); - da.setFrom(omRR); - da.setTo(circleList); - - return circleList; - } - - public EsriGraphic shallowCopy() { - EsriPolygonList ret = new EsriPolygonList(size()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - ret.setAttributes(getAttributes()); - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonM.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonM.java deleted file mode 100644 index bdaa5c1ed..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonM.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygonM.java,v $ -// $RCSfile: EsriPolygonM.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An extension to OMPoly for polygons that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolygonM extends EsriPolygon implements Cloneable, EsriGraphic { - - public EsriPolygonM(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - public static EsriPolygon convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolygonM ePoly = new EsriPolygonM(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - ePoly.setAttributes(ompoly.getAttributes()); - ePoly.setIsPolygon(true); - return ePoly; - } else { - return null; - } - } - - public int getType() { - return SHAPE_TYPE_POLYGONM; - } - - public EsriPolygon shallowCopyPolygon() { - return (EsriPolygonM) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonMList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonMList.java deleted file mode 100644 index 52403c519..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonMList.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygonMList.java,v $ -// $RCSfile: EsriPolygonMList.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/08/25 15:36:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An EsriGraphicList ensures that only EsriPolygonMs are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolygonMList extends EsriPolygonList { - - /** - * Construct an EsriPolygonList. - */ - public EsriPolygonMList() { - super(); - } - - /** - * Construct an EsriPolygonList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolygonMList(int initialCapacity) { - super(initialCapacity); - } - - public EsriPolygon convert(OMPoly ompoly) { - return EsriPolygonM.convert(ompoly); - } - - /** - * Get the list type in ESRI type number form - 25. - */ - public int getType() { - return SHAPE_TYPE_POLYGONM; - } - - public EsriGraphic shallowCopy() { - EsriPolygonMList ret = new EsriPolygonMList(size()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - ret.setAttributes(getAttributes()); - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZ.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZ.java deleted file mode 100644 index b1163fa3e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZ.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygonZ.java,v $ -// $RCSfile: EsriPolygonZ.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An extension to OMPoly for polygons that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolygonZ extends EsriPolygon implements Cloneable, EsriGraphic { - - public EsriPolygonZ(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - public static EsriPolygon convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolygonZ ePoly = new EsriPolygonZ(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - ePoly.setAttributes(ompoly.getAttributes()); - return ePoly; - } else { - return null; - } - } - - public int getType() { - return SHAPE_TYPE_POLYGONZ; - } - - public EsriPolygon shallowCopyPolygon() { - return (EsriPolygonZ) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZList.java deleted file mode 100644 index 13f68803a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolygonZList.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolygonZList.java,v $ -// $RCSfile: EsriPolygonZList.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/08/25 15:36:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An EsriGraphicList ensures that only EsriPolygons are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolygonZList extends EsriPolygonList { - - /** - * Construct an EsriPolygonList. - */ - public EsriPolygonZList() { - super(); - } - - /** - * Construct an EsriPolygonList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolygonZList(int initialCapacity) { - super(initialCapacity); - } - - public EsriPolygon convert(OMPoly ompoly) { - return EsriPolygonZ.convert(ompoly); - } - - /** - * Get the list type in ESRI type number form - 5. - */ - public int getType() { - return SHAPE_TYPE_POLYGONZ; - } - - public EsriGraphic shallowCopy() { - EsriPolygonZList ret = new EsriPolygonZList(size()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - ret.setAttributes(getAttributes()); - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolyline.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolyline.java deleted file mode 100644 index 83c625a41..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolyline.java +++ /dev/null @@ -1,134 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolyline.java,v $ -// $RCSfile: EsriPolyline.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.ProjMath; - -/** - * An extension to OMPoly for polylines that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolyline extends OMPoly implements EsriGraphic, Cloneable { - - double[] extents; - - public EsriPolyline(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, minx, - * maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - this.extents = extents; - } - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, maxy maxx - * in order of the array. - */ - public double[] getExtents() { - if (extents == null) { - // These are set to their opposites to guarantee some - // movement. - extents = new double[] { 90f, 180f, -90f, -180f }; - double[] points = super.getLatLonArray(); - double[] degreePoints = new double[points.length]; - System.arraycopy(points, 0, degreePoints, 0, points.length); - addExtents(ProjMath.arrayRadToDeg(degreePoints)); - } - return extents; - } - - /** No-op. */ - public void setType(int t) {} - - public int getType() { - return SHAPE_TYPE_POLYLINE; - } - - public void addExtents(double[] graphicExtents) { - double[] ex = getExtents(); - - // Check both graphic extents in case they are inadvertently - // switched. - for (int i = 0; i < graphicExtents.length - 1; i += 2) { - if (ex[0] > graphicExtents[i]) - ex[0] = graphicExtents[i]; - if (ex[1] > graphicExtents[i + 1]) - ex[1] = graphicExtents[i + 1]; - if (ex[2] < graphicExtents[i]) - ex[2] = graphicExtents[i]; - if (ex[3] < graphicExtents[i + 1]) - ex[3] = graphicExtents[i + 1]; - } - - // System.out.println("extents of Polyline: " + - // ex[1] + ", " + - // ex[0] + ", " + - // ex[3] + ", " + - // ex[2]); - } - - public static EsriPolyline convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolyline ePoly = new EsriPolyline(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - ePoly.setAttributes(ompoly.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - ePoly.setIsPolygon(false); - - return ePoly; - } else { - return null; - } - } - - /** - * Override OMPoly method, so there's no doubt. - */ - public boolean isPolygon() { - return false; - } - - public EsriGraphic shallowCopy() { - return shallowCopyPolyline(); - } - - public EsriPolyline shallowCopyPolyline() { - return (EsriPolyline) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineList.java deleted file mode 100644 index b0f9b4a8d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineList.java +++ /dev/null @@ -1,153 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolylineList.java,v $ -// $RCSfile: EsriPolylineList.java,v $ -// $Revision: 1.10 $ -// $Date: 2007/01/30 18:39:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * An EsriGraphicList ensures that only EsriPolygons are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolylineList extends EsriGraphicList { - - /** - * Over-ride the add( ) method to trap for inconsistent shape geometry. If - * you are adding a OMGraphic that is not a list, make sure this list is a - * sub-list containing multiple geometry parts. Only add another list to a - * top level EsriGraphicList. - * - * @param shape the non-null OMGraphic to add - */ - public boolean add(OMGraphic shape) { - boolean ret = false; - try { - if (typeMatches(shape)) { - ret = graphics.add(shape); - addExtents(((EsriGraphic) shape).getExtents()); - } else if (shape instanceof OMPoly) { - EsriPolyline eg = convert((OMPoly) shape); - if (typeMatches(eg)) { - ret = graphics.add(eg); - addExtents(eg.getExtents()); - } - } else if (shape instanceof OMLine) { - OMPoly omp = EsriPolylineList.convert((OMLine) shape); - if (omp != null) { - EsriPolyline eg = convert(omp); - if (typeMatches(eg)) { - ret = graphics.add(eg); - addExtents(eg.getExtents()); - } - } - } else if (shape instanceof OMGraphicList - && !((OMGraphicList) shape).isVague()) { - for (Iterator it = ((OMGraphicList) shape).iterator(); it.hasNext();) { - add((OMGraphic) it.next()); - } - ret = true; - } else { - Debug.message("esri", - "EsriPolygonList.add()- graphic isn't a EsriPoly or OMPoly, can't add."); - } - } catch (ClassCastException cce) { - } - - return ret; - } - - public EsriPolyline convert(OMPoly ompoly) { - return EsriPolyline.convert(ompoly); - } - - public boolean typeMatches(OMGraphic omg) { - return (omg instanceof EsriGraphic && ((EsriGraphic) omg).getType() == getType()); - } - - /** - * Get the list type in ESRI type number form - 3. - */ - public int getType() { - return SHAPE_TYPE_POLYLINE; - } - - /** - * Construct an EsriPolylineList. - */ - public EsriPolylineList() { - super(); - } - - /** - * Construct an EsriPolylineList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolylineList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an EsriPolylineList with an initial capacity and a standard - * increment value. - * - * @param initialCapacity the initial capacity of the list - * @param capacityIncrement the capacityIncrement for resizing - * @deprecated - capacityIncrement doesn't do anything. - */ - public EsriPolylineList(int initialCapacity, int capacityIncrement) { - super(initialCapacity); - } - - public static OMPoly convert(OMLine omLine) { - if (omLine.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - // Yikes, if we just give omLine LL to OMPoly, they change to radians right under our feet! - OMPoly poly = new OMPoly(DeepCopyUtil.deepCopy(omLine.getLL()), OMGraphic.DECIMAL_DEGREES, omLine.getLineType()); - poly.setAttributes(omLine.getAttributes()); - DrawingAttributes da = new DrawingAttributes(); - da.setFrom(omLine); - da.setTo(poly); - return poly; - } else - return null; - } - - public EsriGraphic shallowCopy() { - EsriPolylineList ret = new EsriPolylineList(size()); - ret.setAttributes(getAttributes()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineM.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineM.java deleted file mode 100644 index ff2adeebf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineM.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolylineM.java,v $ -// $RCSfile: EsriPolylineM.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An extension to OMPoly for polylines that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolylineM extends EsriPolyline implements EsriGraphic, - Cloneable { - - public EsriPolylineM(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - public static EsriPolyline convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolylineM ePoly = new EsriPolylineM(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - ePoly.setAttributes(ompoly.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - - return ePoly; - } else { - return null; - } - } - - public int getType() { - return SHAPE_TYPE_POLYLINEM; - } - - public EsriPolyline shallowCopyPolyline() { - return (EsriPolylineM) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineMList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineMList.java deleted file mode 100644 index 158924b18..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineMList.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolylineMList.java,v $ -// $RCSfile: EsriPolylineMList.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/08/25 15:36:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An EsriGraphicList ensures that only EsriPolygonMs are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolylineMList extends EsriPolylineList { - - /** - * Construct an EsriPolylineList. - */ - public EsriPolylineMList() { - super(); - } - - /** - * Construct an EsriPolylineList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolylineMList(int initialCapacity) { - super(initialCapacity); - } - - public EsriPolyline convert(OMPoly ompoly) { - return EsriPolylineM.convert(ompoly); - } - - /** - * Get the list type in ESRI type number form - 23. - */ - public int getType() { - return SHAPE_TYPE_POLYLINEM; - } - - public EsriGraphic shallowCopy() { - EsriPolylineMList ret = new EsriPolylineMList(size()); - ret.setAttributes(getAttributes()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZ.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZ.java deleted file mode 100644 index 5dca91e84..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZ.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolylineZ.java,v $ -// $RCSfile: EsriPolylineZ.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An extension to OMPoly for polylines that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList is of the - * same type. - * - * @author Doug Van Auken - */ -public class EsriPolylineZ extends EsriPolyline implements EsriGraphic, - Cloneable { - - public EsriPolylineZ(double[] points, int units, int lineType) { - super(points, units, lineType); - } - - public static EsriPolyline convert(OMPoly ompoly) { - if (ompoly.getRenderType() == RENDERTYPE_LATLON) { - - double[] rawLL = ompoly.getLatLonArray(); - double[] degreePoints = new double[rawLL.length]; - System.arraycopy(rawLL, 0, degreePoints, 0, rawLL.length); - - EsriPolylineZ ePoly = new EsriPolylineZ(degreePoints, OMGraphic.RADIANS, ompoly.getLineType()); - ePoly.setAttributes(ompoly.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(ompoly); - attributes.setTo(ePoly); - - return ePoly; - } else { - return null; - } - } - - public int getType() { - return SHAPE_TYPE_POLYLINEZ; - } - - public EsriPolyline shallowCopyPolyline() { - return (EsriPolylineZ) clone(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZList.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZList.java deleted file mode 100644 index 04854a0e4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriPolylineZList.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriPolylineZList.java,v $ -// $RCSfile: EsriPolylineZList.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/08/25 15:36:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * An EsriGraphicList ensures that only EsriPolygons are added to its list. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public class EsriPolylineZList extends EsriPolylineList { - - /** - * Construct an EsriPolylineList. - */ - public EsriPolylineZList() { - super(); - } - - /** - * Construct an EsriPolylineList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriPolylineZList(int initialCapacity) { - super(initialCapacity); - } - - public EsriPolyline convert(OMPoly ompoly) { - return EsriPolylineZ.convert(ompoly); - } - - /** - * Get the list type in ESRI type number form - 13. - */ - public int getType() { - return SHAPE_TYPE_POLYLINEZ; - } - - public EsriGraphic shallowCopy() { - EsriPolylineZList ret = new EsriPolylineZList(size()); - ret.setAttributes(getAttributes()); - for (Iterator iter = iterator(); iter.hasNext();) { - EsriGraphic g = (EsriGraphic) iter.next(); - ret.add((OMGraphic) g.shallowCopy()); - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriShapeExport.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriShapeExport.java deleted file mode 100644 index 61a6f2df5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriShapeExport.java +++ /dev/null @@ -1,1235 +0,0 @@ -/* - * File: EsriShapeExport.java - * OptiMetrics, Inc. - * 2107 Laurel Bush Road - Suite 209 - * Bel Air, MD 21015 - * (410)569 - 6081 - */ -package com.bbn.openmap.dataAccess.shape; - -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import com.bbn.openmap.dataAccess.shape.output.DbfOutputStream; -import com.bbn.openmap.dataAccess.shape.output.ShpOutputStream; -import com.bbn.openmap.dataAccess.shape.output.ShxOutputStream; -import com.bbn.openmap.omGraphics.BasicStrokeEditor; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRangeRings; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; - -/** - * Provides methods for saving OMGraphicLists as ShapeFiles. This code was - * originally submitted by Karl Stuempfle of OptiMetrics, and I modified it a - * little to add a user interface to modify the DBF files if the user wants to. - *

- * - * Since Shape files can only hold one type of graphic, this class will create - * one to three different lists as needed, for points, lines and polygons. - *

- * - * If the OMGraphicList's AppObject holds a DbfTableModel, it will be used for - * the shape file database file. - */ -public class EsriShapeExport implements ShapeConstants, OMGraphicConstants { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.EsriShapeExport"); - - /** - * The source graphics to write to a shape file. - */ - protected OMGraphicList graphicList = null; - - /** - * The optional DbfTableModel that describes properties for the OMGraphics. - * This should be set as the DBF_ATTRIBUTE attribute of the OMGraphicList. - */ - protected DbfTableModel masterDBF = null; - - /** - * The projection needed to convert other OMGraphicTypes to polygons. - */ - protected Projection projection; - - /** - * The path where the shape files should be written. - */ - protected String filePath; - - /** - * Gets set automatically if Logger.isLoggable(Level.INFO); - */ - protected boolean DEBUG = false; - - /** - * A list of ESEInterface classes, holding information for different type - * ESRIGraphicLists created from the OMGraphicList. - */ - protected ArrayList eseInterfaces = new ArrayList(); - - /** - * Flag for whether the DBF file should be written when the OMGraphicList is - * exported to a .shp/.shx file. The .dbf file will be created if set to - * true, and this is true by default. - */ - protected boolean writeDBF = true; - - /** - * Flad to note whether, if a DbfTableModel is set, to add the rendering - * information (DrawingAttributes contents) about the OMGraphics to the - * contents of the DbfTableModel. False by default. Doesn't do anything yet. - */ - protected boolean dbfHasRenderingInfo = false; - - /** - * A GeoCoordTransform to use to convert Lat/Lon values in EsriGraphics to - * projected coordinates. - */ - protected GeoCoordTransformation transform; - - /** - * Create an EsriShapeExport object. - * - * @param list the OMGraphicList to export. - * @param proj the Projection of the map, needed to convert some OMGraphic - * types to OMPolys. - * @param pathToFile the file path of the shape file to save to. If null, - * the user will be queried. If not null, the files will be saved - * without any GUI confirmation. - */ - public EsriShapeExport(OMGraphicList list, Projection proj, String pathToFile) { - - setGraphicList(list); - projection = proj; - filePath = pathToFile; - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Create an EsriShapeExport object. - * - * @param list the EsriGraphicList to export. - * @param dbf the DbfTableModel holding the attributes for the list objects. - * @param pathToFile the file path of the shape file to save to. If null, - * the user will be queried. If not null, the files will be saved - * without any GUI confirmation. - */ - public EsriShapeExport(EsriGraphicList list, DbfTableModel dbf, String pathToFile) { - - setGraphicList(list); - setMasterDBF(dbf); - filePath = pathToFile; - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Set the OMGraphicList to use for export. If the AppObject in the - * OMGraphicList holds a DbfTableModel, it will be used in the export. - */ - public void setGraphicList(OMGraphicList list) { - graphicList = list; - - if (list != null) { - Object obj = list.getAttribute(DBF_ATTRIBUTE); - if (obj instanceof DbfTableModel) { - masterDBF = (DbfTableModel) obj; - logger.fine("Setting master DBF in ESE"); - } - } - } - - public OMGraphicList getGraphicList() { - return graphicList; - } - - public void setProjection(Projection proj) { - projection = proj; - } - - public Projection getProjection() { - return projection; - } - - public void setFilePath(String pathToFile) { - filePath = pathToFile; - } - - public String getFilePath() { - return filePath; - } - - public GeoCoordTransformation getTransform() { - return transform; - } - - public void setTransform(GeoCoordTransformation transform) { - this.transform = transform; - } - - protected EsriPolygonList polyList = null; - protected EsriPolylineList lineList = null; - protected EsriPointList pointList = null; - - /** - * Return the polygon list, create it if needed. - */ - protected EsriPolygonList getPolyList() { - if (polyList == null) { - polyList = new EsriPolygonList(); - polyList.setTable(getMasterDBFHeaderClone()); - } - return polyList; - } - - /** - * Return the line list, create it if needed. - */ - protected EsriPolylineList getLineList() { - if (lineList == null) { - lineList = new EsriPolylineList(); - lineList.setTable(getMasterDBFHeaderClone()); - } - return lineList; - } - - /** - * Return the point list, create it if needed. If the masterDBF object - * exists, then a new one is created, which matching structure, and put in - * the AppObject of the new list that is returned. If there isn't a - * masterDBF object, then the AppObject is set to null, and a default one - * will be created. - */ - protected EsriPointList getPointList() { - if (pointList == null) { - pointList = new EsriPointList(); - pointList.setTable(getMasterDBFHeaderClone()); - } - return pointList; - } - - /** - * Add a graphic to the list, and add the record to the list's DbfTableModel - * if both exist. - */ - protected void addGraphic(EsriGraphicList egl, OMGraphic graphic, List record) { - egl.add(graphic); - DbfTableModel dtm = egl.getTable(); - if (dtm != null && record != null) { - dtm.addRecord(record); - } - } - - /** Scoping method to call addGraphic with the right list. */ - protected void addPolygon(OMGraphic graphic, List record) { - addGraphic(getPolyList(), graphic, record); - } - - /** Scoping method to call addGraphic with the right list. */ - protected void addLine(OMGraphic graphic, List record) { - addGraphic(getLineList(), graphic, record); - } - - /** Scoping method to call addGraphic with the right list. */ - protected void addPoint(OMGraphic graphic, List record) { - addGraphic(getPointList(), graphic, record); - } - - /** - * Scoping method to call addGraphic with contents of OMAreaList. Since - * OpenMap can handle polylines as polygons, and this isn't a concept that - * other apps can really handle, we're just going to export polylines from - * this method. - */ - protected void addAreaList(OMAreaList omal, List record) { - double[] coords = gatherCoords(omal, null); - if (coords != null) { - addLine(new OMPoly(coords, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT), record); - } - } - - /** - * Walk through OMGeometry, that may be a OMList of Geometries (OMAreaList) - * and concatentate the coordinates to make one big poly. Called - * recursively. - * - * @param omg current OMGeometry - * @param current the current coord list. - * @return new/current coord array. - */ - protected double[] gatherCoords(OMGeometry omg, double[] current) { - - if (omg instanceof OMList) { - OMList oml = (OMList) omg; - for (OMGeometry omgy : oml) { - current = gatherCoords(omgy, current); - } - return current; - } else if (omg.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - if (omg instanceof OMPoly) { - current = combineCoords(current, ProjMath.arrayRadToDeg(((OMPoly) omg).getLatLonArrayCopy())); - } else if (omg instanceof OMLine) { - current = combineCoords(current, ((OMLine) omg).getLL()); - } else if (omg instanceof OMPoint) { - OMPoint omp = (OMPoint) omg; - double lat = omp.getLat(); - double lon = omp.getLon(); - current = combineCoords(current, new double[] { lat, lon }); - } - } - return current; - } - - /** - * Utility method to concatenate coordinate arrays. Handles nulls. - * - * @param orig - * @param addCoords - * @return orig + addCoords - */ - protected double[] combineCoords(double[] orig, double[] addCoords) { - if (orig != null && addCoords != null) { - System.out.println("creating double array size " + (orig.length + addCoords.length)); - double[] newCoords = new double[orig.length + addCoords.length]; - System.arraycopy(orig, 0, newCoords, 0, orig.length); - System.arraycopy(addCoords, 0, newCoords, orig.length, addCoords.length); - return newCoords; - } else if (orig == null && addCoords == null) { - return new double[] {}; - } else if (orig != null) { - return orig; - } else { - return addCoords; - } - } - - /** - * Set the DbfTableModel representing the dbf file for the main - * OMGraphicList. Can also be passed to this object as an attribute in the - * EsriGraphicList under the DBF_ATTRIBUTE key. - */ - public void setMasterDBF(DbfTableModel dbf) { - masterDBF = dbf; - } - - /** - * Get the DbfTableModel representing the dbf file for the main - * OMGraphicList. - */ - public DbfTableModel getMasterDBF() { - return masterDBF; - } - - /** - * Set whether the DBF file should be written when the OMGraphicList is - * exported to a .shp/.shx file. The .dbf file will be created if set to - * true, and this is true by default. - */ - public void setWriteDBF(boolean value) { - writeDBF = value; - } - - /** - * Get whether the DBF file should be written when the OMGraphicList is - * exported to a .shp/.shx file. - */ - public boolean getWriteDBF() { - return writeDBF; - } - - /** - * Get whether the DBF file should have the DrawingAttributes information - * added to the DbfTableModel if it isn't already there. - */ - public void setDBFHasRenderingInfo(boolean value) { - dbfHasRenderingInfo = value; - } - - /** - * Get whether the DBF file should have the DrawingAttributes information - * added to the DbfTableModel if it isn't already there. - */ - public boolean getDBFHasRenderingInfo() { - return dbfHasRenderingInfo; - } - - /** - * If the OMGraphicList has a DbfTableModel in its AppObject slot, a new - * DbfTableModel is created that has the same structure. - * - * @return DbfTableModel that matches the structure that is in the - * OMGraphicList AppObject. - */ - protected DbfTableModel getMasterDBFHeaderClone() { - if (masterDBF != null) { - return masterDBF.headerClone(); - } - return null; - } - - /** - * Gets the DbfTableModel record at the index. Used when the OMGraphicList - * contents are being split up into different type EsriGraphicLists, and the - * records are being split into different tables, too. Remember, the index - * array starts at 0 for the first row. - */ - protected List getMasterDBFRecord(int index) { - try { - if (masterDBF != null) { - return masterDBF.getRecord(index); - } - } catch (IndexOutOfBoundsException ioobe) { - } - return null; - } - - /** - * Separates the graphics from the OMGraphicList into Polygon, Polyline and - * Point lists, then passes the desired shape lists to their respective - * export functions to be added to an EsriLayer of the same type and - * prepared for export. OMGraphics that are on sublists within the top-level - * OMGraphicList will be simply written to the appropriate list at the top - * level of that list. They will be handled as multi-part geometries. - *

- * - * Separating the graphics into the three types is necessary due to shape - * file specification limitations which will only allow shape files to be of - * one type. - *

- * - * For OMGraphicLists that are actually EsriGraphicLists, this export method - * will be redirected to a different method that will handle - * sub-OMGraphicLists as multi-part geometries. - *

- * - * If you want to write out multi-part geometries and have a regular - * OMGraphicList, you have to convert them to EsriGraphicLists first (and - * OMGraphics to EsriGraphics), which forces you to group shapes into like - * types (points, polylines and polygons). - */ - public void export() { - OMGraphicList list = getGraphicList(); - if (list == null) { - logger.warning("no graphic list to export!"); - return; - } - - export(list, null, true); - } - - /** - * A counter for graphics that are not RENDERTYPE_LATLON. - */ - int badGraphics; - - /** - * This method is intended to allow embedded OMGraphicLists to be handled. - * The record should be set if the list is an embedded list, reusing a - * record from the top level iteration. Set the record to null at the top - * level iteration to cause the method to fetch the record from the - * masterDBF, if it exists. - * - * @param list the OMGraphicList to write - * @param record the record for the current list, used if the list is - * actually a multipart geometry for the overall list. May be null - * anyway, though. - * @deprecated use export(OMGraphicList, ArrayList, boolean) instead. - * @see #export(OMGraphicList list, List masterRecord, boolean writeFiles) - */ - protected void export(OMGraphicList list, List record) { - export(list, record, true); - } - - /** - * This method is intended to allow embedded OMGraphicLists to be handled. - * The record should be set if the list is an embedded list, reusing a - * record from the top level iteration. Set the record to null at the top - * level iteration to cause the method to fetch the record from the - * masterDBF, if it exists. If the list is an EsriGraphicList, then the - * export for EsriGraphicLists will be called. The DbfTableModel for the - * list should be stored as an attribute in the EsriGraphicList under the - * DBF_ATTRIBUTE key. - * - * @param list the OMGraphicList to write. - * @param masterRecord the record for the current list, used if the list is - * actually a multipart geometry for the overall list. May be null - * anyway, though. - * @param writeFiles Flag to note when this method is being called - * iteratively, which is when record is not null. If it is iterative, - * then the writing of the files should not be performed on this - * round of the method call. - */ - protected void export(OMGraphicList list, List masterRecord, boolean writeFiles) { - badGraphics = 0; - - if (list == null) { - return; - } else if (list instanceof EsriGraphicList) { - export((EsriGraphicList) list); - return; - } - - int dbfIndex = 0; - - // parse the graphic list and fill the individual lists with - // the appropriate shape types - for (OMGraphic dtlGraphic : list) { - - // Reset the record to the master flag record, which will - // cause a new record to be read for the top level list - // contents, but duplicate the current masterRecord for - // iterative contents. - List record = masterRecord; - - // We're trying to be cute here. We'll ask the shape if it knows - // what index it is. If it doesn't, we'll tell it. They should be - // the same anyway. - Integer recIndex = (Integer) dtlGraphic.getAttribute(SHAPE_INDEX_ATTRIBUTE); - if (recIndex == null) { - recIndex = dbfIndex; - } - - if (record == null) { - record = getMasterDBFRecord(recIndex); - } - dbfIndex++; // increment for the next round. - - // If we have an OMGraphicList, iterate through that one - // as well. We're not handling multi-part geometries yet. - if (dtlGraphic instanceof OMGraphicList) { - if (DEBUG) - logger.fine("ESE: handling OMGraphicList"); - export((OMGraphicList) dtlGraphic, record, false); - continue; - } - - // check to be sure the graphic is rendered in LAT/LON - if (dtlGraphic.getRenderType() != RENDERTYPE_LATLON) { - badGraphics++; - continue; - } - - // OMAreaList needs to be marked as RENDERTYPE_LATLON - if (dtlGraphic instanceof OMAreaList) { - if (DEBUG) { - logger.fine("ESE: handling OMAreaList"); - } - addAreaList((OMAreaList) dtlGraphic, record); - } - - if (dtlGraphic instanceof OMPoly) { - OMPoly omPoly = (OMPoly) dtlGraphic; - // verify that this instance of OMPoly is a polygon - if (isPolygon(omPoly)) { - if (DEBUG) - logger.fine("ESE: handling OMPoly polygon"); - addPolygon(dtlGraphic, record); - } - // if it is not it must be a polyline and therefore - // added to the line list - else { - if (DEBUG) - logger.fine("ESE: handling OMPoly line"); - addLine(dtlGraphic, record); - } - } - // (end)if (dtlGraphic instanceof OMPoly) - // add all other fully enclosed graphics to the polyList - else if (dtlGraphic instanceof OMRect) { - if (DEBUG) - logger.fine("ESE: handling OMRect"); - addPolygon((OMGraphic) EsriPolygonList.convert((OMRect) dtlGraphic), record); - } else if (dtlGraphic instanceof OMCircle) { - if (DEBUG) - logger.fine("ESE: handling OMCircle"); - addPolygon((OMGraphic) EsriPolygonList.convert((OMCircle) dtlGraphic, projection), record); - - } else if (dtlGraphic instanceof OMRangeRings) { - if (DEBUG) - logger.fine("ESE: handling OMRangeRings"); - export(EsriPolygonList.convert((OMRangeRings) dtlGraphic, projection), record, false); - - } - - // add lines to the lineList - else if (dtlGraphic instanceof OMLine) { - if (DEBUG) - logger.fine("ESE: handling OMLine"); - addLine((OMGraphic) EsriPolylineList.convert((OMLine) dtlGraphic), record); - } - // add points to the pointList - else if (dtlGraphic instanceof OMPoint) { - if (DEBUG) - logger.fine("ESE: handling OMPoint"); - addPoint(dtlGraphic, record); - } - } - // (end)for (int i = 0; i < dtlGraphicList.size(); i++) - - if (badGraphics > 0) { - // Information popup provider, it's OK that this gets - // dropped. - DrawingToolRenderException.notifyUserOfNonLatLonGraphics(badGraphics); - } - - if (!writeFiles) { - // Punch the stack back up so that the initial call will - // write the files. - return; - } - - boolean needConfirmation = false; - // call the file chooser if no path is given - if (filePath == null) { - filePath = getFilePathFromUser(); - - if (filePath == null) { - return; // User canceled. - } - - needConfirmation = true; - } - - if (DEBUG) - logger.fine("ESE: writing files..."); - - boolean needTypeSuffix = false; - - // (end)if (filePath == null) call the appropriate methods to - // set up the shape files of their respective types - if (polyList != null) { - eseInterfaces.add(new ESEInterface(polyList, filePath, null)); - needTypeSuffix = true; - } - - if (lineList != null) { - eseInterfaces.add(new ESEInterface(lineList, filePath, (needTypeSuffix ? LineSuffix - : null))); - needTypeSuffix = true; - } - - if (pointList != null) { - eseInterfaces.add(new ESEInterface(pointList, filePath, (needTypeSuffix ? PointSuffix - : null))); - } - - if (needConfirmation) { - showGUI(); - } else { - writeFiles(); - } - } - - public final static String LineSuffix = "Lines"; - public final static String PointSuffix = "Pts"; - - /** - * Writes out EsriGraphicLists as shape files, assumes that the - * DbfTableModel representing the attribute data for the list objects is - * stored as an attribute in the EsriGraphicList under the DBF_ATTRIBUTE - * key. This export handles multi-part geometries, because it's assumed that - * the sorting of the graphic types have been handled and that any sub-lists - * are meant to be multi-part geometries. If the filePath hasn't been set in - * the EsriShapeExport class, the user will be asked to provide it. - */ - protected void export(EsriGraphicList egList) { - - Object obj = egList.getAttribute(DBF_ATTRIBUTE); - if (obj == null) { - egList.putAttribute(DBF_ATTRIBUTE, getMasterDBF()); - // egList.setAppObject(getMasterDBF()); - } - - eseInterfaces.add(new ESEInterface(egList, filePath, null)); - writeFiles(); - } - - /** - * The the Iterator of ESEIterators. - */ - protected Iterator getInterfaces() { - return eseInterfaces.iterator(); - } - - /** - * Just write the files from the ESEInterfaces. - */ - protected void writeFiles() { - for (ESEInterface eseInterface : eseInterfaces) { - eseInterface.write(); - } - } - - protected JFrame frame = null; - - /** - * Show the GUI for saving the Shape files. - */ - public void showGUI() { - - if (frame == null) { - frame = new JFrame("Saving Shape Files"); - - frame.getContentPane().add(getGUI(), BorderLayout.CENTER); - // frame.setSize(400, 300); - frame.pack(); - } - - frame.setVisible(true); - } - - /** - * Hide the Frame holding the GUI. - */ - public void hideGUI() { - if (frame != null) { - frame.setVisible(false); - } - } - - /** - * Create the GUI for managing the different ESEIterators. - */ - public Component getGUI() { - - JPanel panel = new JPanel(); - panel.setLayout(new BorderLayout()); - - JPanel interfacePanel = new JPanel(); - interfacePanel.setLayout(new GridLayout(0, 1)); - - int count = 0; - for (ESEInterface eseInterface : eseInterfaces) { - interfacePanel.add(eseInterface.getGUI()); - count++; - } - panel.add(interfacePanel, BorderLayout.CENTER); - - if (count > 1) { - JLabel notification = new JLabel(" " + count + " Shape file sets needed:"); - panel.add(notification, BorderLayout.NORTH); - } - - JButton saveButton = new JButton("Save"); - saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - writeFiles(); - hideGUI(); - } - }); - - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - hideGUI(); - } - }); - JPanel controlPanel = new JPanel(); - controlPanel.add(saveButton); - controlPanel.add(cancelButton); - panel.add(controlPanel, BorderLayout.SOUTH); - return panel; - } - - /** - * Prepares and returns a 7 column DbfTableModel to accept input for columns - * of TYPE_CHARACTER.
- *
- * The default model used holds most of the DrawingAttributes of the - * OMGraphics. - * - * - * @param list the EsriGraphicList to create a DbfTableModel from. - * @return The completed DbfTableModel. - */ - public static DbfTableModel createDefaultModel(EsriGraphicList list) { - if (logger.isLoggable(Level.FINE)) - logger.fine("ESE: creating DbfTableModel"); - - DbfTableModel _model = new DbfTableModel(7); - // Setup table structure - // column 0 - // The first parameter, 0, represents the first column - _model.setLength(0, (byte) 50); - _model.setColumnName(0, SHAPE_DBF_DESCRIPTION); - _model.setType(0, (byte) DbfTableModel.TYPE_CHARACTER); - _model.setDecimalCount(0, (byte) 0); - // column 1 - // The first parameter, 1, represents the second column - _model.setLength(1, (byte) 10); - _model.setColumnName(1, SHAPE_DBF_LINECOLOR); - _model.setType(1, (byte) DbfTableModel.TYPE_CHARACTER); - _model.setDecimalCount(1, (byte) 0); - // column2 - // The first parameter, 2, represents the third column - _model.setLength(2, (byte) 10); - _model.setColumnName(2, SHAPE_DBF_FILLCOLOR); - _model.setType(2, (byte) DbfTableModel.TYPE_CHARACTER); - _model.setDecimalCount(2, (byte) 0); - // column3 - // The first parameter, 3, represents the fourth column - _model.setLength(3, (byte) 10); - _model.setColumnName(3, SHAPE_DBF_SELECTCOLOR); - _model.setType(3, (byte) DbfTableModel.TYPE_CHARACTER); - _model.setDecimalCount(3, (byte) 0); - // column4 - // The first parameter, 4, represents the fifth column - _model.setLength(4, (byte) 4); - _model.setColumnName(4, SHAPE_DBF_LINEWIDTH); - _model.setType(4, (byte) DbfTableModel.TYPE_NUMERIC); - _model.setDecimalCount(4, (byte) 0); - // column5 - // The first parameter, 5, represents the sixth column - _model.setLength(5, (byte) 20); - _model.setColumnName(5, SHAPE_DBF_DASHPATTERN); - _model.setType(5, (byte) DbfTableModel.TYPE_CHARACTER); - _model.setDecimalCount(5, (byte) 0); - // column6 - // The first parameter, 6, represents the seventh column - _model.setLength(6, (byte) 10); - _model.setColumnName(6, SHAPE_DBF_DASHPHASE); - _model.setType(6, (byte) DbfTableModel.TYPE_NUMERIC); - _model.setDecimalCount(6, (byte) 4); - - // At a later time, more stroke parameters can be added, like - // dash phase, end cap, line joins, and dash pattern. - // While we're here, add index attribute into OMGraphics if they don't - // have them. - int count = 0; - for (OMGraphic omg : list) { - Object index = omg.getAttribute(SHAPE_INDEX_ATTRIBUTE); - if (index == null) { - index = new Integer(count); - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, index); - } - count++; - - List record = new ArrayList(); - - // Description - Object obj = omg.getAttribute(SHAPE_DBF_DESCRIPTION); - if (obj instanceof String) { - record.add(obj); - } else { - record.add(""); - } - - record.add(ColorFactory.getHexColorString(omg.getLineColor())); - record.add(ColorFactory.getHexColorString(omg.getFillColor())); - record.add(ColorFactory.getHexColorString(omg.getSelectColor())); - BasicStroke bs = (BasicStroke) omg.getStroke(); - record.add(new Double(bs.getLineWidth())); - String dp = BasicStrokeEditor.dashArrayToString(bs.getDashArray()); - if (dp == BasicStrokeEditor.NONE) { - dp = ""; - } - record.add(dp); - record.add(new Double(bs.getDashPhase())); - _model.addRecord(record); - if (logger.isLoggable(Level.FINER)) - logger.finer("ESE: adding record: " + record); - } - - return _model; - } - - public static void syncDrawingAttributesToTableModel(DbfTableModel model, OMGraphicList list, - boolean clearUpdatedStatus) { - - int count = 0; - - for (OMGraphic omg : list) { - Object indexObj = omg.getAttribute(SHAPE_INDEX_ATTRIBUTE); - if (indexObj == null || !(indexObj instanceof Integer)) { - indexObj = new Integer(count); - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, indexObj); - } - count++; - int index = ((Integer) indexObj).intValue(); - Object updatedStatus = omg.getAttribute(OMGraphicConstants.UPDATED); - if (updatedStatus == Boolean.TRUE) { - List record = model.getRecord(index); - - index = model.getColumnIndexForName(SHAPE_DBF_LINECOLOR); - if (index >= 0) { - record.set(index, ColorFactory.getHexColorString(omg.getLineColor())); - } - index = model.getColumnIndexForName(SHAPE_DBF_FILLCOLOR); - if (index >= 0) { - record.set(index, ColorFactory.getHexColorString(omg.getFillColor())); - } - index = model.getColumnIndexForName(SHAPE_DBF_SELECTCOLOR); - if (index >= 0) { - record.set(index, ColorFactory.getHexColorString(omg.getSelectColor())); - } - - BasicStroke bs = (BasicStroke) omg.getStroke(); - index = model.getColumnIndexForName(SHAPE_DBF_LINEWIDTH); - if (index >= 0) { - record.set(index, new Double(bs.getLineWidth())); - } - String dp = BasicStrokeEditor.dashArrayToString(bs.getDashArray()); - if (dp == BasicStrokeEditor.NONE) { - dp = ""; - } - index = model.getColumnIndexForName(SHAPE_DBF_DASHPATTERN); - if (index >= 0) { - record.set(index, dp); - } - index = model.getColumnIndexForName(SHAPE_DBF_DASHPHASE); - if (index >= 0) { - record.set(index, new Double(bs.getDashPhase())); - } - - if (logger.isLoggable(Level.FINER)) - logger.finer("ESE: updating record for OMGraphic: " + indexObj); - - if (clearUpdatedStatus) { - omg.removeAttribute(OMGraphicConstants.UPDATED); - } - } - } - } - - /** - * Takes an OMPoly as the parameter and checks whether or not it is a - * polygon or polyline.
- *
- * This method incorporates the OMPoly.isPolygon() method which returns true - * if the fill color is not clear, but also checks the first set and last - * set of lat/lon points of the float[] defined by OMPoly.getLatLonArray(). - * Returns true for a polygon and false for a polyline. - * - * @param omPoly the OMPoly object to be verified - * @return The polygon value - */ - public static boolean isPolygon(OMPoly omPoly) { - // get the array of lat/lon points - double[] points = omPoly.getLatLonArray(); - int i = points.length; - - boolean isPolygon = false; - // Do we have at least 3 lat/lon coordinates? - if (points != null && i > 5) { - // compare the first and last set of points, equal points - // verifies a polygon. - isPolygon = points[0] == points[i - 2] && points[1] == points[i - 1]; - - // check OMPoly's definition of a polygon. If you want to force - // polygon you can set the fill color or set the isPolyon flag. If - // you want to force polyline you can set isPolygon flag to false - // after color parameters have been set. - isPolygon = isPolygon && omPoly.isPolygon(); - } - - return isPolygon; - } - - /** - * Generic error handling, puts up an error window. - */ - protected void handleException(Exception e) { - // System.out.println(e); - StringBuffer sb = new StringBuffer("ShapeFile Export Error:"); - sb.append("\nProblem with creating the shapefile set."); - sb.append("\n").append(e.toString()); - - JOptionPane.showMessageDialog(null, sb.toString(), "ESRI Shape Export to File", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); - } - - /** - * Fetches a file path from the user, via a JFileChooser. Returns null if - * the user cancels. - * - * @see com.bbn.openmap.util.FileUtils#getFilePathToSaveFromUser(String) - */ - public String getFilePathFromUser() { - return FileUtils.getFilePathToSaveFromUser("Select Name for Shape File Set..."); - } - - /** - * The main function is a test, reads in a Shape file (with the .shx and - * .dbf files) and writes them back out. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("EsriShapeExport"); - ap.add("shp", "A URL to a shape file (.shp).", 1); - - if (argv.length < 1) { - ap.bail("", true); - } - - ap.parse(argv); - - String[] files = ap.getArgValues("shp"); - if (files != null && files[0] != null) { - String shp = files[0]; - String dbf = null; - - try { - dbf = shp.substring(0, shp.lastIndexOf('.') + 1) + PARAM_DBF; - - DbfTableModel model = DbfTableModel.getDbfTableModel(PropUtils.getResourceOrFileOrURL(dbf)); - EsriGraphicList list = EsriGraphicList.getEsriGraphicList(PropUtils.getResourceOrFileOrURL(shp), null, null); - - logger.info(list.getDescription()); - - EsriShapeExport ese = new EsriShapeExport(list, model, null); - ese.export(); - - } catch (MalformedURLException murle) { - logger.warning("EsriShapeExport: Malformed URL Exception\n" + murle.getMessage()); - } catch (NullPointerException npe) { - logger.warning("EsriShapeExport: Path to shape file isn't good enough to find .dbf file and .shx file."); - } catch (Exception exception) { - logger.warning("EsriShapeExport: Exception\n" + exception.getMessage()); - exception.printStackTrace(); - } - - } else { - ap.bail("Need a path to a Shape file (.shp)", true); - } - System.exit(0); - } - - public static OMGraphicList read(URL shpFileURL, DrawingAttributes drawingAttributes, - GeoCoordTransformation coordTransform) { - OMGraphicList ret = null; - - if (shpFileURL != null) { - EsriGraphicList regList = EsriGraphicList.getEsriGraphicList(shpFileURL, drawingAttributes, coordTransform); - ret = new OMGraphicList(); - ret.addAll(regList); - - DbfTableModel regDbf = (DbfTableModel) regList.getAttribute(DBF_ATTRIBUTE); - ret.putAttribute(DBF_ATTRIBUTE, regDbf); - - // Now check for lines and pnts files - String shpFilePath = shpFileURL.getPath(); - if (shpFilePath.endsWith(".shp")) { - String linesPath = shpFilePath.replace(".shp", "_" + LineSuffix + ".shp"); - String pntsPath = shpFilePath.replace(".shp", "_" + PointSuffix + ".shp"); - - logger.fine("looking for " + linesPath + " and " + pntsPath); - - try { - URL linesURL = PropUtils.getResourceOrFileOrURL(linesPath); - if (linesURL != null) { - EsriGraphicList lineList = EsriGraphicList.getEsriGraphicList(linesURL, drawingAttributes, coordTransform); - if (lineList != null) { - DbfTableModel dbf = (DbfTableModel) lineList.getAttribute(DBF_ATTRIBUTE); - if (regDbf != null && dbf != null && regDbf.matches(dbf)) { - regDbf.append(dbf); - ret.addAll(lineList); - } - } - } - URL pntsURL = PropUtils.getResourceOrFileOrURL(pntsPath); - if (pntsURL != null) { - EsriGraphicList pntsList = EsriGraphicList.getEsriGraphicList(pntsURL, drawingAttributes, coordTransform); - if (pntsList != null) { - DbfTableModel dbf = (DbfTableModel) pntsList.getAttribute(DBF_ATTRIBUTE); - if (regDbf != null && dbf != null && regDbf.matches(dbf)) { - regDbf.append(dbf); - ret.addAll(pntsList); - } - } - } - - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - } - - return ret; - } - - /** - * A helper class to manage a specific instance of a EsriGraphicList, it's - * data model, etc. Provides a GUI to display and change the name of the - * file, and the DbfTableModel GUI, and also writes the files out. - */ - public class ESEInterface { - - protected EsriGraphicList list; - protected DbfTableModel model; - protected String suffix; - protected String filePath; - - File shpFile = null; - File shxFile = null; - File dbfFile = null; - - protected JTextField filePathField; - - public ESEInterface(EsriGraphicList eglist, String filePathString, String fileNameSuffix) { - list = eglist; - filePath = filePathString; - - model = eglist.getTable(); - - if (model == null) { - model = createDefaultModel(list); - } else { - syncDrawingAttributesToTableModel(model, list, true); - } - model.setWritable(true); - - suffix = (fileNameSuffix == null ? "" : "_" + fileNameSuffix); - if (DEBUG) { - logger.fine("suffix being used for " + filePathString + ": " + suffix); - } - } - - public Component getGUI() { - JPanel panel = new JPanel(); - - int type = list.getType(); - String sectionTitle; - switch (type) { - case (SHAPE_TYPE_POINT): - sectionTitle = "Point Shape File"; - break; - case (SHAPE_TYPE_POLYLINE): - sectionTitle = "Line Shape File"; - break; - case (SHAPE_TYPE_POLYGON): - sectionTitle = "Polygon Shape File"; - break; - default: - sectionTitle = "Shape File"; - } - - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), sectionTitle)); - - panel.setLayout(new GridLayout(0, 1)); - JPanel pathPanel = new JPanel(); - filePathField = new JTextField(20); - filePathField.setText(filePath + suffix); - JButton filePathChooserLauncher = new JButton("Change Path"); - filePathChooserLauncher.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setFilePath(getFilePathFromUser()); - } - }); - - panel.add(filePathField); - - JButton editDBFButton = new JButton("Edit the Attribute File..."); - editDBFButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - model.showGUI(getFilePath() + " Attributes", DbfTableModel.DONE_MASK - | DbfTableModel.MODIFY_COLUMN_MASK); - } - }); - - pathPanel.add(editDBFButton); - pathPanel.add(filePathChooserLauncher); - - panel.add(pathPanel); - - return panel; - } - - protected void setFilePath(String path) { - filePath = path; - } - - public void write() { - - if (filePathField != null) { - filePath = filePathField.getText(); - } - - if (filePath == null) { - filePath = getFilePathFromUser(); - if (filePath == null) { - return; - } - } - - // This helps when a file chooser has been used to pick a file to be - // replaced. - if (filePath.endsWith(".shp") || filePath.endsWith(".shx") || filePath.endsWith(".dbf")) { - filePath = filePath.substring(0, filePath.length() - 4); - } - - filePath += suffix; - - shpFile = new File(filePath + ".shp"); - shxFile = new File(filePath + ".shx"); - dbfFile = new File(filePath + ".dbf"); - - try { - - // create an esriGraphicList and export it to the - // shapefile set - if (DEBUG) - logger.fine("ESE writing: " + list.size() + " elements in " - + shpFile.getAbsolutePath()); - - ShpOutputStream pos = new ShpOutputStream(new FileOutputStream(shpFile)); - - if (transform != null) { - pos.setTransform(transform); - } - - int[][] indexData = pos.writeGeometry(list); - - ShxOutputStream xos = new ShxOutputStream(new FileOutputStream(shxFile)); - xos.writeIndex(indexData, list.getType()); - - if (getWriteDBF()) { - FileOutputStream fos = new FileOutputStream(dbfFile); - DbfOutputStream dos = new DbfOutputStream(fos); - dos.writeModel(model); - fos.close(); - } - - } catch (Exception e) { - handleException(e); - } - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriTextPoint.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriTextPoint.java deleted file mode 100644 index dff72de6f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/EsriTextPoint.java +++ /dev/null @@ -1,96 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriTextPoint.java,v $ -// $RCSfile: EsriTextPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMText; - -/** - * An extension to OMPoint that typecasts a specific Esri graphic - * type. Used to ensure that all OMGraphics added to a EsriGraphicList - * is of the same type. - * - * @author Doug Van Auken - */ -public class EsriTextPoint extends OMText implements Cloneable, EsriGraphic, - OMGraphicConstants { - - protected int type = SHAPE_TYPE_POINT; - - public EsriTextPoint(double lat, double lon, String stuff, int justification) { - super(lat, lon, stuff, justification); - } - - /** - * The lat/lon extent of the EsriGraphic, assumed to contain miny, - * minx, maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - // we know what it is. - } - - /** - * The lat/lon extent of the EsriGraphic, returned as miny, minx, - * maxy maxx in order of the array. - */ - public double[] getExtents() { - double[] ex = new double[4]; - ex[0] = getLat(); - ex[1] = getLon(); - ex[2] = getLat(); - ex[3] = getLon(); - return ex; - } - - public void setType(int t) { - type = t; - } - - public int getType() { - return type; - } - - public static EsriTextPoint convert(OMText omtext) { - if (omtext.getRenderType() == RENDERTYPE_LATLON) { - EsriTextPoint etp = new EsriTextPoint(omtext.getLat(), omtext.getLon(), omtext.getData(), omtext.getJustify()); - etp.setAttributes(omtext.getAttributes()); - DrawingAttributes attributes = new DrawingAttributes(); - attributes.setFrom(omtext); - attributes.setTo(etp); - - return etp; - } else { - return null; - } - } - - public EsriGraphic shallowCopy() { - return shallowCopyPoint(); - } - - public EsriTextPoint shallowCopyPoint() { - return (EsriTextPoint) super.clone(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/MetaDbfTableModel.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/MetaDbfTableModel.java deleted file mode 100644 index fe383dd61..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/MetaDbfTableModel.java +++ /dev/null @@ -1,344 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/dataAccess/shape/MetaDbfTableModel.java,v $ -// $RCSfile: MetaDbfTableModel.java,v $ -// $Revision: 1.3 $ -// $Date: 2007-06-27 16:29:06 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JOptionPane; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.dataAccess.shape.input.DbfInputStream; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * An extension of the DbfTableModel that allows editing of the format of the - * TbfTableModel, allowing addition and deletion of columns of the - * DbfTableModel. The original DbfTableModel column headers are scanned and put - * into records, and edited as rows. Be careful with this. - */ -public class MetaDbfTableModel extends DbfTableModel implements ShapeConstants { - - /** - * - */ - private static final long serialVersionUID = -8408741750134029139L; - public final static int META_RECORDNAME_COLUMN_NUMBER = 0; - public final static int META_TYPE_COLUMN_NUMBER = 1; - public final static int META_LENGTH_COLUMN_NUMBER = 2; - public final static int META_PLACES_COLUMN_NUMBER = 3; - - protected DbfTableModel source = null; - /** - * Keeps track of the original columns. If a name is changed the row will be - * deleted in all the records. - */ - protected int originalColumnNumber = 0; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - /** - * Creates a blank DbfTableModel from the source DbfTableModel. - * - * @param source the DbfTableModel to be modified. - */ - @SuppressWarnings("unchecked") - public MetaDbfTableModel(DbfTableModel source) { - super(4); // these are the number of columns for Metadata - init(); - setWritable(true); - this.source = source; - - int numColumnCount = source.getColumnCount(); - - originalColumnNumber = numColumnCount; - - for (int i = 0; i < numColumnCount; i++) { - List record = new ArrayList(); - record.add(source.getColumnName(i)); - record.add(new Byte(source.getType(i))); - record.add(new Integer(source.getLength(i))); - record.add(new Integer(source.getDecimalCount(i))); - addRecord(record); - if (DEBUG) - Debug.output("Adding record: " + record); - } - } - - /** - * Set up the columns of this DbfTableModel, so the parameters of the source - * header rows are listed. - */ - protected void init() { - _names[META_RECORDNAME_COLUMN_NUMBER] = i18n.get(MetaDbfTableModel.class, "Column_Name", "Column Name"); - _names[META_TYPE_COLUMN_NUMBER] = i18n.get(MetaDbfTableModel.class, "Type_of_Data", "Type of Data"); - _names[META_LENGTH_COLUMN_NUMBER] = i18n.get(MetaDbfTableModel.class, "Length_of_Field", "Length of Field"); - _names[META_PLACES_COLUMN_NUMBER] = i18n.get(MetaDbfTableModel.class, "Decimal_Places", "Decimal Places"); - - - for (int i = 0; i < 4; i++) { - - _lengths[i] = (byte) 12; - _decimalCounts[i] = (byte) 0; - - byte type; - if (i < 2) { - type = DBF_TYPE_CHARACTER.byteValue(); - } else { - type = DBF_TYPE_NUMERIC.byteValue(); - } - - _types[i] = type; - } - } - - /** - * Remove the record at the index. This extension decreases the - * originalColumnNumber which controls which rows[0] can be edited. - */ - @Override - public List remove(int columnIndex) { - List ret = super.remove(columnIndex); - if (columnIndex < originalColumnNumber) { - originalColumnNumber--; - } - return ret; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - if (columnIndex == 0 && rowIndex < originalColumnNumber) { - return false; - } else { - return writable; - } - } - - /** - * Sets an object at a certain location. The type is translated from integer - * values to names for easier use. - */ - @Override - public void setValueAt(Object object, int row, int column) { - - if (column == META_TYPE_COLUMN_NUMBER) { - if (DBF_BINARY.equals(object) || DBF_TYPE_BINARY.equals(object)) { - object = DBF_TYPE_BINARY; - } else if (DBF_CHARACTER.equals(object) - || DBF_TYPE_CHARACTER.equals(object)) { - object = DBF_TYPE_CHARACTER; - } else if (DBF_DATE.equals(object) || DBF_TYPE_DATE.equals(object)) { - object = DBF_TYPE_DATE; - } else if (DBF_NUMERIC.equals(object) - || DBF_TYPE_NUMERIC.equals(object)) { - object = DBF_TYPE_NUMERIC; - } else if (DBF_LOGICAL.equals(object) - || DBF_TYPE_LOGICAL.equals(object)) { - object = DBF_TYPE_LOGICAL; - } else if (DBF_MEMO.equals(object) || DBF_TYPE_MEMO.equals(object)) { - object = DBF_TYPE_MEMO; - } else if (DBF_TIMESTAMP.equals(object) - || DBF_TYPE_TIMESTAMP.equals(object)) { - object = DBF_TYPE_TIMESTAMP; - } else if (DBF_LONG.equals(object) || DBF_TYPE_LONG.equals(object)) { - object = DBF_TYPE_LONG; - } else if (DBF_AUTOINCREMENT.equals(object) - || DBF_TYPE_AUTOINCREMENT.equals(object)) { - object = DBF_TYPE_AUTOINCREMENT; - } else if (DBF_FLOAT.equals(object) - || DBF_TYPE_FLOAT.equals(object)) { - object = DBF_TYPE_FLOAT; - } else if (DBF_DOUBLE.equals(object) - || DBF_TYPE_DOUBLE.equals(object)) { - object = DBF_TYPE_DOUBLE; - } else if (DBF_OLE.equals(object) || DBF_TYPE_OLE.equals(object)) { - object = DBF_TYPE_OLE; - } else { - Debug.error("Rejected " - + object - + " as input. Use: \n binary, character, date, boolean, memo, timestamp, long, autoincrement, float, double or OLE"); - return; - } - - if (DEBUG) { - Debug.output("New value set to " + object); - } - } - - super.setValueAt(object, row, column); - } - - /** - * Retrieves a value for a specific column and row index - * - * @return Object A value for a specific column and row index - */ - @Override - public Object getValueAt(int row, int column) { - Object cell = super.getValueAt(row, column); - - if (column == META_TYPE_COLUMN_NUMBER) { - if (DBF_TYPE_CHARACTER.equals(cell)) { - cell = DBF_CHARACTER; - } else if (DBF_TYPE_DATE.equals(cell)) { - cell = DBF_DATE; - } else if (DBF_TYPE_NUMERIC.equals(cell)) { - return DBF_NUMERIC; - } else if (DBF_TYPE_LOGICAL.equals(cell)) { - cell = DBF_LOGICAL; - } else if (DBF_TYPE_MEMO.equals(cell)) { - cell = DBF_MEMO; - } else if (DBF_TYPE_BINARY.equals(cell)) { - cell = DBF_BINARY; - } else if (DBF_TYPE_TIMESTAMP.equals(cell)) { - cell = DBF_TIMESTAMP; - } else if (DBF_TYPE_FLOAT.equals(cell)) { - cell = DBF_FLOAT; - } else if (DBF_TYPE_DOUBLE.equals(cell)) { - cell = DBF_DOUBLE; - } else if (DBF_TYPE_LONG.equals(cell)) { - cell = DBF_LONG; - } else if (DBF_TYPE_AUTOINCREMENT.equals(cell)) { - cell = DBF_AUTOINCREMENT; - } else if (DBF_TYPE_OLE.equals(cell)) { - cell = DBF_OLE; - } - // Else just keep it what it is. - } - return cell; - } - - /** - * Create a new record, corresponding to a new column in the source - * DbfTableModel. Filled in with standard things that can be edited. - */ - @SuppressWarnings("unchecked") - @Override - public void addBlankRecord() { - List record = new ArrayList(); - record.add(i18n.get(MetaDbfTableModel.class, "New_Column", "New Column")); - record.add(DBF_TYPE_CHARACTER); - record.add(new Integer(12)); - record.add(new Integer(0)); - addRecord(record); - if (DEBUG) { - Debug.output("Adding record: " + record); - } - } - - /** - * Decide what to do when the window closes. - */ - @Override - public void exitWindowClosed() { - if (source != null && source.dirty) { - int check = JOptionPane.showConfirmDialog(null, - i18n.get(MetaDbfTableModel.class, "Do_you_want_to_save_your_changes", "Do you want to save your changes?"), - i18n.get(MetaDbfTableModel.class, "Confirm_Close", "Confirm Close"), - JOptionPane.YES_NO_OPTION); - - - if (check == JOptionPane.YES_OPTION) { - fireTableStructureChanged(); - } else { - source.cleanupChanges(); - } - } - - super.exitWindowClosed(); - } - - public void showGUI(String filename) { - if (frame == null) { - frame = new JFrame(i18n.get(MetaDbfTableModel.class, "Editing_Attribute_File_Structure", "Editing Attribute File Structure")); - - frame.getContentPane().add(getGUI(filename, MODIFY_ROW_MASK - | DONE_MASK), - BorderLayout.CENTER); - - JButton saveButton = new JButton(i18n.get(MetaDbfTableModel.class, "Save Changes", "Save Changes")); - saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - int check = JOptionPane.showConfirmDialog(null, - i18n.get(MetaDbfTableModel.class, "Are_you_sure_you_want_to_modify_the_table_format", - "Are you sure you want to modify the table format?"), - i18n.get(MetaDbfTableModel.class, "Confirm_Save", "Confirm Save"), - JOptionPane.OK_CANCEL_OPTION); - - if (check == JOptionPane.YES_OPTION) { - fireTableStructureChanged(); - } - } - }); - - controlPanel.add(saveButton); - frame.validate(); - - frame.setSize(500, 300); - frame.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - // need a shutdown event to notify other gui beans - // and - // then exit. - exitWindowClosed(); - } - }); - } - frame.setVisible(true); - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - System.exit(0); - } - - try { - - URL dbf = new URL(args[0]); - DbfInputStream dis = new DbfInputStream(dbf.openStream()); - DbfTableModel dtm = new DbfTableModel(dis); - - MetaDbfTableModel mdtm = new MetaDbfTableModel(dtm); - mdtm.showGUI(args[0]); - mdtm.exitOnClose = true; - - } catch (Exception e) { - Debug.error(e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeConstants.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeConstants.java deleted file mode 100644 index cd1b7a76e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeConstants.java +++ /dev/null @@ -1,170 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/ShapeConstants.java,v -// $ -// $RCSfile: ShapeConstants.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/09/17 20:47:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/* - * Constants used in reading shape files. - */ -public interface ShapeConstants { - - /** The length of a shape file header in bytes, value of 100. */ - public static final int SHAPE_FILE_HEADER_LENGTH = 100; - - /** The length of a shape file record header in bytes, value of 8. */ - public static final int SHAPE_FILE_RECORD_HEADER_LENGTH = 8; - - /** The indicator for a null shape type, value of 0 */ - public static final int SHAPE_TYPE_NULL = 0; - - /** The indicator for a point shape type, value of 1. */ - public static final int SHAPE_TYPE_POINT = 1; - - /** The indicator for an arc (polyline) shape type, value of 3. */ - public static final int SHAPE_TYPE_ARC = 3; - - /** - * The indicator for a polyline (arc) shape type, value of 3. NOTE: ESRI - * decided to rename the `arc' type as the `polyline' type as of their July - * 1998 Shapefile Technical Description paper. Maybe they should rename - * Arc/Info as Polyline/Info?... - */ - public static final int SHAPE_TYPE_POLYLINE = 3; - - /** The indicator for a polygon shape type, value of 5. */ - public static final int SHAPE_TYPE_POLYGON = 5; - - /** The indicator for a multipoint shape type, value of 8. */ - public static final int SHAPE_TYPE_MULTIPOINT = 8; - - public static final int SHAPE_TYPE_POINTZ = 11; - public static final int SHAPE_TYPE_POLYLINEZ = 13; - public static final int SHAPE_TYPE_POLYGONZ = 15; - public static final int SHAPE_TYPE_MULTIPOINTZ = 18; - public static final int SHAPE_TYPE_POINTM = 21; - public static final int SHAPE_TYPE_POLYLINEM = 23; - public static final int SHAPE_TYPE_POLYGONM = 25; - public static final int SHAPE_TYPE_MULTIPOINTM = 28; - public static final int SHAPE_TYPE_MULTIPATCH = 31; - - public static final Byte DBF_TYPE_BINARY = new Byte((byte) 'B'); - public static final String DBF_BINARY = "binary"; - public static final Byte DBF_TYPE_CHARACTER = new Byte((byte) 'C'); - public static final String DBF_CHARACTER = "character"; - public static final Byte DBF_TYPE_DATE = new Byte((byte) 'D'); - public static final String DBF_DATE = "date"; - public static final Byte DBF_TYPE_NUMERIC = new Byte((byte) 'N'); - public static final String DBF_NUMERIC = "numeric"; - public static final Byte DBF_TYPE_LOGICAL = new Byte((byte) 'L'); - public static final String DBF_LOGICAL = "boolean"; - public static final Byte DBF_TYPE_MEMO = new Byte((byte) 'M'); - public static final String DBF_MEMO = "Memo"; - public static final Byte DBF_TYPE_TIMESTAMP = new Byte((byte) '@'); - public static final String DBF_TIMESTAMP = "timestamp"; - public static final Byte DBF_TYPE_LONG = new Byte((byte) 'I'); - public static final String DBF_LONG = "long"; - public static final Byte DBF_TYPE_AUTOINCREMENT = new Byte((byte) '+'); - public static final String DBF_AUTOINCREMENT = "autoincrement"; - public static final Byte DBF_TYPE_FLOAT = new Byte((byte) 'F'); - public static final String DBF_FLOAT = "float"; - public static final Byte DBF_TYPE_DOUBLE = new Byte((byte) 'O'); - public static final String DBF_DOUBLE = "double"; - public static final Byte DBF_TYPE_OLE = new Byte((byte) 'G'); - public static final String DBF_OLE = "OLE"; - - public static final String PARAM_DBF = "dbf"; - public static final String PARAM_SHX = "shx"; - public static final String PARAM_SHP = "shp"; - - public static final String SHAPE_DBF_DESCRIPTION = "Description"; - public static final String SHAPE_DBF_LINECOLOR = DrawingAttributes.linePaintProperty; - public static final String SHAPE_DBF_FILLCOLOR = DrawingAttributes.fillPaintProperty; - public static final String SHAPE_DBF_SELECTCOLOR = DrawingAttributes.selectPaintProperty; - public static final String SHAPE_DBF_LINEWIDTH = DrawingAttributes.lineWidthProperty; - public static final String SHAPE_DBF_DASHPATTERN = DrawingAttributes.dashPatternProperty; - public static final String SHAPE_DBF_DASHPHASE = DrawingAttributes.dashPhaseProperty; - - /** - * Attribute Key for DbfTableModel stored in an EsriGraphicList. or for a - * row of attribute information (ArrayList) from the DBF file on a Shape - * feature. - */ - public static final String DBF_ATTRIBUTE = "DBF_ATTRIBUTE"; - /** - * Attribute key for row of attribute information (ArrayList) from the DBF - * file on a Shape feature. - */ - public static final String SHAPE_DBF_INFO_ATTRIBUTE = "SHAPE_DBF_INFO_ATTRIBUTE"; - /** - * Attribute key for index Integer for a shape feature, indicating the shape - * index into the file for the feature. Caution! Shape indexes start at 1, - * not zero! - */ - public static final String SHAPE_INDEX_ATTRIBUTE = "SHAPE_INDEX_ATTRIBUTE"; - - /** - * For Z and M shape types, the measure value will be stored as a Double in - * the attribute table in the EsriGraphic under this key. - */ - public static final String SHAPE_MEASURE_ATTRIBUTE = "SMA"; - /** - * For multi-part Z and M shape types, the minimum SHAPE_MEASURE_ATTRIBUTE - * value will be stored under this key in the multi-part graphic attribute - * table, as a Double. - */ - public static final String SHAPE_MIN_MEASURE_ATTRIBUTE = "MIN_SMA"; - /** - * For multi-part Z and M shape types, the maximum SHAPE_MEASURE_ATTRIBUTE - * value will be stored under this key in the multi-part graphic attribute - * table, as a Double. - */ - public static final String SHAPE_MAX_MEASURE_ATTRIBUTE = "MAX_SMA"; - - /** - * For Z shape types, the z value will be stored as a Double in the - * attribute table in the EsriGraphic under this key. - */ - public static final String SHAPE_Z_ATTRIBUTE = "SZA"; - /** - * For multi-part Z shape types, the minimum SHAPE_Z_ATTRIBUTE value will be - * stored under this key in the multi-part graphic attribute table, as a - * Double. - */ - public static final String SHAPE_MIN_Z_ATTRIBUTE = "MIN_Z"; - /** - * For multi-part Z shape types, the maximum SHAPE_Z_ATTRIBUTE value will be - * stored under this key in the multi-part graphic attribute table, as a - * Double. - */ - public static final String SHAPE_MAX_Z_ATTRIBUTE = "MAX_Z"; - - /** - * Attribute key for storing a bounding box in an attribute map for a - * record. - */ - public static final String SHAPE_BOUNDS_ATTRIBUTE = "BOUNDS"; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeGeoIndex.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeGeoIndex.java deleted file mode 100644 index 0e30bbd21..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeGeoIndex.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ - -package com.bbn.openmap.dataAccess.shape; - -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; - -import com.bbn.openmap.geo.ExtentIndex; -import com.bbn.openmap.geo.ExtentIndex.ArrayListExtentIndexImpl; -import com.bbn.openmap.geo.GeoExtent; -import com.bbn.openmap.geo.GeoPath; -import com.bbn.openmap.geo.GeoPoint; -import com.bbn.openmap.geo.GeoRegion; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.geo.MatchCollector; -import com.bbn.openmap.geo.MatchFilter; -import com.bbn.openmap.geo.MatchParameters; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; - -/** - * A GeoExtentIndex that knows how to work with Shape files. Plots the shape - * file contents in memory in lat/lon space, can then be used with the - * Intersection class to do spatial analysis on the shape file contents. - * - * @author ddietrick - */ -public class ShapeGeoIndex - extends ArrayListExtentIndexImpl { - protected HashMap omgraphics; - - private ShapeGeoIndex(Builder builder) { - super(builder.numberOfBuckets, builder.margin); - omgraphics = new HashMap(); - EsriGraphicList graphicList = EsriGraphicList.getEsriGraphicList(builder.shapeFile, null, - builder.geoCoordTransform); - - if (graphicList != null) { - load(graphicList); - } - } - - /** - * After you test for intersections with some GeoExtent, you get an iterator of GeoExtents. You can get the ID - * from each of those, which will in turn allow you to ask for the OMGraphic representing the shape from the given - * file. The ID is an integer index into the shape file and attribute dbf file, btw. - * - * @param id The id provided by the extent in the intersection test. - * @return OMGraphic or null (if not found). - */ - public OMGraphic getForID(Object id) { - if (omgraphics != null) { - return omgraphics.get(id); - } - return null; - } - - public void load(EsriGraphicList list) { - if (list != null) { - int type = list.getType(); - - switch (type) { - case ShapeConstants.SHAPE_TYPE_POINT: - case ShapeConstants.SHAPE_TYPE_POINTM: - case ShapeConstants.SHAPE_TYPE_POINTZ: - loadPoints(list); - break; - case ShapeConstants.SHAPE_TYPE_POLYGON: - case ShapeConstants.SHAPE_TYPE_POLYGONM: - case ShapeConstants.SHAPE_TYPE_POLYGONZ: - loadPolygons(list); - break; - case ShapeConstants.SHAPE_TYPE_POLYLINE: - case ShapeConstants.SHAPE_TYPE_POLYLINEM: - case ShapeConstants.SHAPE_TYPE_POLYLINEZ: - loadPolylines(list); - break; - default: - // case ShapeConstants.SHAPE_TYPE_NULL: - } - } - } - - /** - * @param list assuming list is not null, and has two levels at most - - * points, or lists of points. - */ - private void loadPoints(EsriGraphicList list) { - for (OMGraphic omg : list) { - if (omg instanceof OMGraphicList) { - - Object recNum = ((OMGraphicList) omg).getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - for (OMGraphic pnt : (OMGraphicList) omg) { - addPoint((OMPoint) pnt, recNum); - } - - } else { - addPoint((OMPoint) omg, omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - } - } - - } - - private void addPoint(OMPoint omp, Object id) { - double latitude = omp.getLat(); - double longitude = omp.getLon(); - - GeoPoint.Impl geoPoint = new GeoPoint.Impl(latitude, longitude); - geoPoint.setID(id); - addExtent(geoPoint); - omgraphics.put(id, omp); - } - - /** - * @param list assuming list is not null - */ - private void loadPolygons(EsriGraphicList list) { - for (OMGraphic omg : list) { - if (omg instanceof OMGraphicList) { - - Object recNum = ((OMGraphicList) omg).getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - for (OMGraphic poly : (OMGraphicList) omg) { - addPolygon((OMPoly) poly, recNum); - } - - } else { - addPolygon((OMPoly) omg, omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - } - } - } - - private void addPolygon(OMPoly omp, Object id) { - double[] latlonArray = omp.getLatLonArray(); - - GeoRegion.Impl region = new GeoRegion.Impl(latlonArray, false); - region.setID(id); - addExtent(region); - omgraphics.put(id, omp); - } - - /** - * @param list assuming list is not null - */ - private void loadPolylines(EsriGraphicList list) { - for (OMGraphic omg : list) { - if (omg instanceof OMGraphicList) { - - Object recNum = ((OMGraphicList) omg).getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - for (OMGraphic pnt : (OMGraphicList) omg) { - addPolyline((OMPoly) pnt, recNum); - } - - } else { - addPolyline((OMPoly) omg, omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - } - } - } - - private void addPolyline(OMPoly omp, Object id) { - double[] latlonArray = omp.getLatLonArray(); - - GeoPath.Impl region = new GeoPath.Impl(latlonArray); - region.setID(id); - addExtent(region); - omgraphics.put(id, omp); - } - - /** - * Get an iterator with all of the objects in this ShapeGeoIndex that - * intersect with the given extent. - * - * @param extent GeoExtent (GeoPoint, GeoPath, GeoRegion) to test against. - * @return Iterator over intersecting shape objects. - */ - public Iterator getIntersections(GeoExtent extent) { - return getIntersections(extent, new MatchFilter.MatchParametersMF(MatchParameters.STRICT), - new MatchCollector.SetMatchCollector()); - } - - /** - * Get an iterator with all of the objects in this ShapeGeoIndex that - * intersect with the given extent. - * - * @param extent GeoExtext (GeoPoint, GeoPath, GeoRegion) to test against. - * @param filter MatchFilter a MatchFilter can eliminate - * @param collector - * @return Iterator over intersecting shape objects. - */ - public Iterator getIntersections(GeoExtent extent, MatchFilter filter, MatchCollector collector) { - Intersection intersection = Intersection.intersector(); - - intersection.consider(extent, this); - collector = intersection.getCollector(); - - return collector.iterator(); - } - - /** - * Use this class to create a ShapeGeoIndex. - * - * @author ddietrick - */ - public static class Builder { - private URL shapeFile; - private GeoCoordTransformation geoCoordTransform; - private int numberOfBuckets = ExtentIndex.AbstractExtentIndex.D_NBUCKETS; - private double margin = ExtentIndex.AbstractExtentIndex.D_MARGIN; - - public Builder(URL shape) { - this.shapeFile = shape; - } - - public Builder setGeoCoordTransformation(GeoCoordTransformation geoCoordTransformation) { - this.geoCoordTransform = geoCoordTransformation; - return this; - } - - public Builder setNumberOfBuckets(int nBuckets) { - this.numberOfBuckets = nBuckets; - return this; - } - - public Builder setMargin(double mar) { - this.margin = mar; - return this; - } - - public ShapeGeoIndex create() { - return new ShapeGeoIndex(this); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeUtils.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeUtils.java deleted file mode 100644 index 216e3d163..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/ShapeUtils.java +++ /dev/null @@ -1,280 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ShapeUtils.java,v $ -// $RCSfile: ShapeUtils.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.EOFException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.layer.shape.ESRIBoundingBox; -import com.bbn.openmap.layer.shape.ESRIPoint; - -/** - * Utilities for reading and writing the components of shape files. - * - * @author Tom Mitchell - * @version $Revision: 1.5 $ $Date: 2005/12/09 21:09:09 $ - */ -public class ShapeUtils implements ShapeConstants { - - /** A buffer for reading/writing little endian ints. */ - private static byte leiBuffer[] = new byte[4]; - - /** - * Reads a big endian integer. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the int resides - * @return the int read from the buffer at the offset location - */ - public static int readBEInt(byte[] b, int off) { - return (((b[off + 0] & 0xff) << 24) | ((b[off + 1] & 0xff) << 16) - | ((b[off + 2] & 0xff) << 8) | ((b[off + 3] & 0xff))); - } - - /** - * Reads a little endian integer. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the int resides - * @return the int read from the buffer at the offset location - */ - public static int readLEInt(byte[] b, int off) { - return (((b[off + 3] & 0xff) << 24) | ((b[off + 2] & 0xff) << 16) - | ((b[off + 1] & 0xff) << 8) | ((b[off + 0] & 0xff))); - } - - /** - * Reads a little endian int from the current location of the given file. - * Synchronized for thread-safe access to leiBuffer. - * - * @param in an input file - * @return the int read from the file - */ - public static synchronized int readLEInt(BinaryBufferedFile in) - throws IOException { - int result = in.read(leiBuffer, 0, 4); - if (result < 4) { - throw new EOFException(); - } else { - return readLEInt(leiBuffer, 0); - } - } - - /** - * Reads a little endian 8 byte integer. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the long resides - * @return the long read from the buffer at the offset location - */ - public static long readLELong(byte[] b, int off) { - return (((b[off + 0] & 0xffL)) | ((b[off + 1] & 0xffL) << 8) - | ((b[off + 2] & 0xffL) << 16) | ((b[off + 3] & 0xffL) << 24) - | ((b[off + 4] & 0xffL) << 32) | ((b[off + 5] & 0xffL) << 40) - | ((b[off + 6] & 0xffL) << 48) | ((b[off + 7] & 0xffL) << 56)); - } - - /** - * Reads a little endian double. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the double resides - * @return the double read from the buffer at the offset location - */ - public static double readLEDouble(byte[] b, int off) { - double result = Double.longBitsToDouble(readLELong(b, off)); - return result; - } - - /** - * Reads a point record. A point record is a double representing the x value - * and a double representing a y value. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the int resides - * @return the point read from the buffer at the offset location - */ - public static ESRIPoint readPoint(byte[] b, int off) { - ESRIPoint point = new ESRIPoint(); - point.x = readLEDouble(b, off); - point.y = readLEDouble(b, off + 8); - return point; - } - - /** - * Reads a bounding box record. A bounding box is four double representing, - * in order, xmin, ymin, xmax, ymax. - * - * @param b the raw data buffer - * @param off the offset into the buffer where the int resides - * @return the point read from the buffer at the offset location - */ - public static ESRIBoundingBox readBox(byte[] b, int off) { - ESRIBoundingBox bb = new ESRIBoundingBox(); - bb.min = readPoint(b, off); - bb.max = readPoint(b, off + 16); - return bb; - } - - /** - * Writes the given integer to the given buffer at the given location in big - * endian format. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param val the integer to write - * @return the number of bytes written - */ - public static int writeBEInt(byte[] b, int off, int val) { - b[off + 0] = (byte) ((val >> 24) & 0xff); - b[off + 1] = (byte) ((val >> 16) & 0xff); - b[off + 2] = (byte) ((val >> 8) & 0xff); - b[off + 3] = (byte) ((val) & 0xff); - return 4; - } - - /** - * Writes the given integer to the given buffer at the given location in - * little endian format. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param val the integer to write - * @return the number of bytes written - */ - public static int writeLEInt(byte[] b, int off, int val) { - b[off + 0] = (byte) ((val) & 0xff); - b[off + 1] = (byte) ((val >> 8) & 0xff); - b[off + 2] = (byte) ((val >> 16) & 0xff); - b[off + 3] = (byte) ((val >> 24) & 0xff); - return 4; - } - - /** - * Writes the given long to the given buffer at the given location in little - * endian format. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param val the long to write - * @return the number of bytes written - */ - public static int writeLELong(byte[] b, int off, long val) { - b[off + 0] = (byte) ((val) & 0xff); - b[off + 1] = (byte) ((val >> 8) & 0xff); - b[off + 2] = (byte) ((val >> 16) & 0xff); - b[off + 3] = (byte) ((val >> 24) & 0xff); - b[off + 4] = (byte) ((val >> 32) & 0xff); - b[off + 5] = (byte) ((val >> 40) & 0xff); - b[off + 6] = (byte) ((val >> 48) & 0xff); - b[off + 7] = (byte) ((val >> 56) & 0xff); - return 8; - } - - /** - * Writes the given double to the given buffer at the given location in - * little endian format. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param val the double to write - * @return the number of bytes written - */ - public static int writeLEDouble(byte[] b, int off, double val) { - return writeLELong(b, off, Double.doubleToLongBits(val)); - } - - /** - * Writes the given point to the given buffer at the given location. The - * point is written as a double representing x followed by a double - * representing y. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param point the point to write - * @return the number of bytes written - */ - public static int writePoint(byte[] b, int off, ESRIPoint point) { - int nBytes = writeLEDouble(b, off, point.x); - nBytes += writeLEDouble(b, off + nBytes, point.y); - return nBytes; - } - - /** - * Writes the given bounding box to the given buffer at the given location. - * The bounding box is written as four doubles representing, in order, xmin, - * ymin, xmax, ymax. - * - * @param b the data buffer - * @param off the offset into the buffer where writing should occur - * @param box the bounding box to write - * @return the number of bytes written - */ - public static int writeBox(byte[] b, int off, ESRIBoundingBox box) { - int nBytes = writePoint(b, off, box.min); - nBytes += writePoint(b, off + nBytes, box.max); - return nBytes; - } - - /** - * Return a readable string for a shape int type. - * @param shapeType - * @return String - */ - public static String getStringForType(int shapeType) { - switch (shapeType) { - - case SHAPE_TYPE_NULL: - return "NULL"; - case SHAPE_TYPE_POINT: - return "POINT"; - case SHAPE_TYPE_POLYLINE: - return "POLYLINE"; - case SHAPE_TYPE_POLYGON: - return "POLYGON"; - case SHAPE_TYPE_MULTIPOINT: - return "MULTIPOINT"; - case SHAPE_TYPE_POINTZ: - return "POINTZ"; - case SHAPE_TYPE_POLYLINEZ: - return "POLYLINEZ"; - case SHAPE_TYPE_POLYGONZ: - return "POLYGONZ"; - case SHAPE_TYPE_MULTIPOINTZ: - return "MULTIPOINTZ"; - case SHAPE_TYPE_POINTM: - return "POINTM"; - case SHAPE_TYPE_POLYLINEM: - return "POLYLINEM"; - case SHAPE_TYPE_POLYGONM: - return "POLYGONM"; - case SHAPE_TYPE_MULTIPOINTM: - return "MULTIPOINTM"; - case SHAPE_TYPE_MULTIPATCH: - return "MULTIPATCH"; - default: - return "UNKNOWN"; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/DbfInputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/DbfInputStream.java deleted file mode 100644 index ea2b32d27..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/DbfInputStream.java +++ /dev/null @@ -1,250 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/input/DbfInputStream.java,v $ -// $RCSfile: DbfInputStream.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.input; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.util.Debug; - -/** - * Reads the contents of a DBF file and provides access to what it has read - * through several get methods - * - * @author Doug Van Auken - */ -public class DbfInputStream { - /** - * An input stream to process primitives in Little Endian or Big Endian - */ - private LittleEndianInputStream _leis = null; - - /** - * An array of column names, as read from the field descripter array - */ - private String[] _columnNames = null; - - /** - * An array of column lengths, as read from the field descripter array - */ - private int[] _lengths = null; - - /** - * An array of decimal counts, as read from the field descripter array - */ - private byte[] _decimalCounts = null; - - /** - * An array of column types, as read from the field descripter array - */ - private byte[] _types = null; - - /** The number of columns */ - private int _columnCount = -1; - - /** The number of rows */ - private int _rowCount = -1; - - /** The header length */ - private short _headerLength = -1; - - /** The record length */ - // private short _recordLength = -1; // Unused - /** - * An ArrayList with each element representing a record, which itself is an - * ArrayList - */ - private List> _records = null; - - /** - * Creates a LittleEndianInputStream then uses it to read the contents of the - * DBF file - * - * @param is An InputStream used to create a LittleEndianInputStream - */ - public DbfInputStream(InputStream is) - throws Exception { - BufferedInputStream bis = new BufferedInputStream(is); - _leis = new LittleEndianInputStream(bis); - readHeader(); - readFieldDescripters(); - readData(); - } - - /** - * Returns an array of column names - * - * @return An array of column names - */ - public String[] getColumnNames() { - return _columnNames; - } - - /** - * Returns an array of character lengths - * - * @return An array of character lengths - */ - public int[] getLengths() { - return _lengths; - } - - /** - * Returns an array of decimal counts - * - * @return An array of decimal counts - */ - public byte[] getDecimalCounts() { - return _decimalCounts; - } - - /** - * Returns an array of field types - * - * @return An array of field types - */ - public byte[] getTypes() { - return _types; - } - - /** - * Returns an ArrayList of records - * - * @return An ArrayList of records - */ - public List> getRecords() { - return _records; - } - - /** - * Returns the number of columns - * - * @return The number of columns - */ - public int getColumnCount() { - return _columnCount; - } - - /** - * Returns the number of rows - * - * @return The number of rows - */ - public int getRowCount() { - return _rowCount; - - } - - /** - * Reads the header - */ - private void readHeader() - throws IOException { - /* byte description = */_leis.readByte(); - /* byte year = */_leis.readByte(); - /* byte month = */_leis.readByte(); - /* byte day = */_leis.readByte(); - _rowCount = _leis.readLEInt(); - _headerLength = _leis.readLEShort(); - /* _recordLength = */_leis.readLEShort(); - _columnCount = (_headerLength - 32 - 1) / 32; - _leis.skipBytes(20); - } - - /** - * Initializes arrays that hold column names, column types, character - * lengths, and decimal counts, then populates them - */ - private void readFieldDescripters() - throws IOException { - _columnNames = new String[_columnCount]; - _types = new byte[_columnCount]; - _lengths = new int[_columnCount]; - _decimalCounts = new byte[_columnCount]; - - for (int n = 0; n <= _columnCount - 1; n++) { - _columnNames[n] = _leis.readString(11).trim(); - // - // Some TIGER dbf files from ESRI have nulls - // in the column names. Delete them. - // - int ix = _columnNames[n].indexOf((char) 0); - if (ix > 0) { - _columnNames[n] = _columnNames[n].substring(0, ix); - } - _types[n] = (byte) _leis.readByte(); - _leis.skipBytes(4); - _lengths[n] = _leis.readUnsignedByte(); - _decimalCounts[n] = _leis.readByte(); - _leis.skipBytes(14); - } - } - - /** - * Reads the data and places data in a class scope ArrayList of records - */ - public void readData() - throws IOException { - - // Thanks to Bart Jourquin for the heads-up that some locales - // may try to read this data incorrectly. DBF files have to - // have '.' as decimal markers, not ',' - DecimalFormat df = new DecimalFormat(); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH); - df.setDecimalFormatSymbols(dfs); - - _leis.skipBytes(2); - _records = new ArrayList>(_rowCount); - for (int r = 0; r <= _rowCount - 1; r++) { - ArrayList record = new ArrayList(_columnCount); - for (int c = 0; c <= _columnCount - 1; c++) { - int length = _lengths[c]; - if (length == -1) - length = 255; - int type = _types[c]; - int numDecSpaces = _decimalCounts[c]; - df.setMaximumFractionDigits(numDecSpaces); - String cell = _leis.readString(length); - try { - record.add(c, DbfTableModel.getObjectForType(cell, type, df, length)); - } catch (ParseException pe) { - if (Debug.debugging("shape")) { - Debug.error("DbfInputStream: error parsing column " + c + ", row " + r + ", expected number and got " + cell); - } - record.add(c, DbfTableModel.appendWhitespaceOrTrim(null, length)); - } - } - _records.add(record); - _leis.skipBytes(1); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/LittleEndianInputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/LittleEndianInputStream.java deleted file mode 100644 index db1f886c4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/LittleEndianInputStream.java +++ /dev/null @@ -1,213 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/input/LittleEndianInputStream.java,v $ -// $RCSfile: LittleEndianInputStream.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/08/25 15:36:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.input; - -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UTFDataFormatException; - -/** - * Provides methods for reading data streams in Little Endian and Big Endian. - * Adapted from the book, Java IO, Elliotte Rusty Harold, Ch. 7. - * - * @author Doug Van Auken - */ -public class LittleEndianInputStream - extends DataInputStream { - DataInputStream in; - - /** - * Constructor - * - * @param in An input stream that this is chained to. - */ - public LittleEndianInputStream(InputStream in) { - super(in); - this.in = new DataInputStream(in); - } - - /** - * Constructs a string from the underlying input stream - * - * @param length The length of bytes to read - */ - public String readString(int length) - throws IOException { - byte[] array = new byte[length]; - readFully(array); - String s = new String(array); - return s.trim(); - } - - /** - * Translates little endian short to big endian short - * - * @return short A big endian short - */ - public short readLEShort() - throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) - throw new EOFException(); - return (short) ((byte2 << 8) + byte1); - } - - /** - * Translates a little endian unsigned short to big endian int - * - * @return int A big endian short - */ - public int readLEUnsignedShort() - throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) - throw new EOFException(); - return (byte2 << 8) + byte1; - } - - /** - * Translates a little endian char into a big endian char - * - * @return char A big endian char - */ - public char readLEChar() - throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) - throw new EOFException(); - return (char) ((byte2 << 8) + byte1); - } - - /** - * Translates a little endian int into a big endian int - * - * @return int A big endian int - */ - public int readLEInt() - throws IOException { - int byte1, byte2, byte3, byte4; - synchronized (this) { - byte1 = in.read(); - byte2 = in.read(); - byte3 = in.read(); - byte4 = in.read(); - } - if (byte4 == -1) { - throw new EOFException(); - } - return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; - } - - /** - * Translates a little endian long into a big endian long - * - * @return long A big endian long - */ - public long readLELong() - throws IOException { - long byte1 = in.read(); - long byte2 = in.read(); - long byte3 = in.read(); - long byte4 = in.read(); - long byte5 = in.read(); - long byte6 = in.read(); - long byte7 = in.read(); - long byte8 = in.read(); - if (byte8 == -1) { - throw new EOFException(); - } - return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32) + (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; - } - - public String readLEUTF() - throws IOException { - int byte1 = in.read(); - int byte2 = in.read(); - if (byte2 == -1) - throw new EOFException(); - int numbytes = (byte1 << 8) + byte2; - - char result[] = new char[numbytes]; - int numread = 0; - int numchars = 0; - - while (numread < numbytes) { - int c1 = readUnsignedByte(); - int c2, c3; - - // look at the first four bits of c1 to determine how many - // bytes in this char - int test = c1 >> 4; - if (test < 8) { // one byte - numread++; - result[numchars++] = (char) c1; - } else if (test == 12 || test == 13) { // two bytes - numread += 2; - if (numread > numbytes) - throw new UTFDataFormatException(); - c2 = readUnsignedByte(); - if ((c2 & 0xC0) != 0x80) - throw new UTFDataFormatException(); - result[numchars++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F)); - } else if (test == 14) { // three bytes - numread += 3; - if (numread > numbytes) - throw new UTFDataFormatException(); - c2 = readUnsignedByte(); - c3 = readUnsignedByte(); - if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) { - throw new UTFDataFormatException(); - } - result[numchars++] = (char) (((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); - } else { // malformed - throw new UTFDataFormatException(); - } - } // end while - return new String(result, 0, numchars); - } - - /** - * Reads a little endian double into a big endian double - * - * @return double A big endian double - */ - public final double readLEDouble() - throws IOException { - return Double.longBitsToDouble(this.readLELong()); - } - - /** - * Reads a little endian float into a big endian float - * - * @return float A big endian float - */ - public final float readLEFloat() - throws IOException { - return Float.intBitsToFloat(this.readLEInt()); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShpInputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShpInputStream.java deleted file mode 100644 index 31937c0c6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShpInputStream.java +++ /dev/null @@ -1,373 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/input/ShpInputStream.java,v $ -// $RCSfile: ShpInputStream.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.input; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -import com.bbn.openmap.dataAccess.shape.EsriGraphic; -import com.bbn.openmap.dataAccess.shape.EsriGraphicFactory; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.dataAccess.shape.EsriPoint; -import com.bbn.openmap.dataAccess.shape.EsriPointList; -import com.bbn.openmap.dataAccess.shape.EsriPolygon; -import com.bbn.openmap.dataAccess.shape.EsriPolygonList; -import com.bbn.openmap.dataAccess.shape.EsriPolyline; -import com.bbn.openmap.dataAccess.shape.EsriPolylineList; -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * Reads geometry data from a .shp file. - * - * @author Doug Van Auken - */ -public class ShpInputStream - implements ShapeConstants { - /** - * An input stream to process primitives in Little Endian or Big Endian - */ - private LittleEndianInputStream _leis = null; - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Constructor - * - * @param is An inputstream to chain with LittleEndianInputStream - */ - public ShpInputStream(InputStream is) { - BufferedInputStream bis = new BufferedInputStream(is); - _leis = new LittleEndianInputStream(bis); - } - - /** - * Set the DrawingAttributes to use for drawing the graphics. - */ - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - } - - /** - * Get the DrawingAttributes used for drawing the graphics. - */ - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - /** - * Reads geometry from a .shp file - * - * @param indexData The index data retrieved from the .shx file - * @return EsriGraphicList A list of geometry - * @deprecated use getGeometry() instead, indexData isn't used. - */ - public EsriGraphicList getGeometry(int[][] indexData) - throws Exception { - return getGeometry(); - } - - /** - * Reads geometry from a .shp file. This method will create an - * EsriGraphicFactory with the default settings (LINETYPE_STRAIGHT and no - * data projection available). - * - * @return EsriGraphicList A list of geometry - */ - public EsriGraphicList getGeometry() - throws Exception { - return getGeometry(new EsriGraphicFactory()); - } - - /** - * Reads geometry from a .shp file. This method will use the provided - * EsriGraphicFactory. - * - * @param factory an EsriGraphicFactory to be used to read from the internal - * stream. - * @return EsriGraphicList A list of geometry - */ - public EsriGraphicList getGeometry(EsriGraphicFactory factory) - throws Exception { - return (EsriGraphicList) factory.getEsriGraphics(_leis, drawingAttributes, (Object) null, (Projection) null, - (OMGraphicList) null); - } - - /** - * Creates an array that specifies at what index a parts geometry begins with - * - * @return An array whose elements denote the position where a part begins - * witin an array of point data for a given shape - * @deprecated not used. - */ - protected int[] getPartOffsets(OMGraphicList sublist) { - int pos = 0; - int[] offsets = new int[sublist.size()]; - for (int j = 0; j < sublist.size(); j++) { - OMPoly poly = (OMPoly) sublist.getOMGraphicAt(j); - double[] data = poly.getLatLonArray(); - offsets[j] = pos / 2; - pos += data.length; - } - return offsets; - } - - /** - * Iterates through the given input stream to construct geometry objects - * - * @param indexData A list of offsets obtained by iterating through the - * associated SHX file - * @return list An OMGraphicList that contains the collection of objects - * created by iterating through this input stream * - * @deprecated not used. - */ - public EsriGraphicList getPointGeometry(int[][] indexData) - throws Exception { - - EsriGraphicList list = new EsriPointList(); - int numShapes = indexData[1].length; - - EsriPoint point; - for (int i = 0; i < numShapes; i++) { - int shpRecord = _leis.readInt(); - /* int shpContentLength = */_leis.readInt(); - int shpType = _leis.readLEInt(); - if (shpType != SHAPE_TYPE_NULL) { - - double lambda = _leis.readLEDouble(); - double phi = _leis.readLEDouble(); - - float f1 = (float) lambda; - float f2 = (float) phi; - - point = new EsriPoint(f2, f1); - // We reset the index to be based at 0 instead of 1, following Java - // convention. - point.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(shpRecord - 1)); - if (drawingAttributes != null) { - drawingAttributes.setTo(point); - } else { - DrawingAttributes.DEFAULT.setTo(point); - } - list.add(point); - } - } - return list; - } - - /** - * Iterates through each part of shape to obtain the total number of points - * - * @param sublist A list that contains multiple parts - * @return The total number of points for a given shape - * @deprecated not used. - */ - protected int getPointsPerShape(OMGraphicList sublist) { - int numPoints = 0; - for (int i = 0; i < sublist.size(); i++) { - OMPoly poly = (OMPoly) sublist.getOMGraphicAt(i); - double[] data = poly.getLatLonArray(); - numPoints += data.length; - } - numPoints /= 2; - return numPoints; - } - - /** - * Iterates through the given input stream to construct geometry objects - * - * @param shapeType the type of shape to read - * @param indexData A list of offsets obtained by iterating through the - * associated SHX file - * @return list An OMGraphicList that contains the collection of objects - * created by iterating through this input stream * - * @deprecated not used. - */ - public EsriGraphicList getPolyGeometry(int[][] indexData, int shapeType) - throws Exception { - - EsriGraphicList list = null; - if (shapeType == SHAPE_TYPE_POLYLINE) { - list = new EsriPolylineList(); - } else if (shapeType == SHAPE_TYPE_POLYGON) { - list = new EsriPolygonList(); - } - - int numVertices; - - int numShapes = indexData[1].length; - - for (int t = 0; t < numShapes; t++) { - // Resetting the index to be based on 0 instead of 1, following Java - // convention. - Integer shpRecordIndex = new Integer(_leis.readInt() - 1); - /* int shpContentLength = */_leis.readInt(); - int shpType = _leis.readLEInt(); - - if (shpType != SHAPE_TYPE_NULL) { - - /* double xLeft = */_leis.readLEDouble(); - /* double xBottom = */_leis.readLEDouble(); - /* double xRight = */_leis.readLEDouble(); - /* double xTop = */_leis.readLEDouble(); - int numParts = _leis.readLEInt(); - int numPoints = _leis.readLEInt(); - - int[] offsets = new int[numParts]; - - // OK, we don't want to create a sublist unless the poly - // has multiple parts. Remember that. sublist will only - // be created if there is more than one part. - - for (int n = 0; n < numParts; n++) { - offsets[n] = _leis.readLEInt(); - } - - double[] points; - OMGraphic poly = null; - EsriGraphicList sublist = null; - - if (numParts > 1) { - if (shapeType == SHAPE_TYPE_POLYLINE) { - sublist = new EsriPolylineList(); - } else if (shapeType == SHAPE_TYPE_POLYGON) { - sublist = new EsriPolygonList(); - } - - if (sublist != null) { - sublist.setVague(true); // Treat sublist as one - // OMGraphic. - sublist.putAttribute(SHAPE_INDEX_ATTRIBUTE, shpRecordIndex); - } - } - - for (int j = 0; j < numParts; j++) { - int i = 0; - if (j != numParts - 1) { - numVertices = (offsets[j + 1]) - offsets[j]; - points = new double[numVertices * 2]; - } else { - numVertices = (numPoints - offsets[j]); - points = new double[numVertices * 2]; - } - for (int n = 0; n < numVertices; n++) { - double lambda = _leis.readLEDouble(); - double phi = _leis.readLEDouble(); - - points[i++] = (float) Math.toRadians(phi); - points[i++] = (float) Math.toRadians(lambda); - } - - if (shapeType == SHAPE_TYPE_POLYLINE) { - poly = new EsriPolyline(points, OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - } else if (shapeType == SHAPE_TYPE_POLYGON) { - poly = new EsriPolygon(points, OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(poly); - } else { - DrawingAttributes.DEFAULT.setTo(poly); - } - - if (poly instanceof EsriPolyline) { - // Just to make sure it gets rendered as a - // polyline. The OMPoly code will render it as a - // polygon if the fill color is not clear. - poly.setFillPaint(OMColor.clear); - } - - // sublist is null for non multi-part geometries. - if (sublist != null) { - sublist.addOMGraphic(poly); - } else if (poly != null) { - - poly.putAttribute(SHAPE_INDEX_ATTRIBUTE, shpRecordIndex); - } - } - - // sublist is null for non multi-part geometries. - if (list != null) { - if (sublist != null) { - list.add(sublist); - } else { - list.add(poly); - } - - if (Debug.debugging("esri")) { - EsriGraphic eg = null; - if (sublist == null) { - eg = (EsriGraphic) poly; - } else { - eg = sublist; - } - - if (eg != null) { - double[] ex1 = eg.getExtents(); - Debug.output("extents of list: xmin=" + ex1[1] + ", ymin=" + ex1[0] + ", xmax=" + ex1[3] + ", ymax=" + ex1[2]); - Debug.output("list.size=" + list.size()); - } - } - } - } - } - - if (Debug.debugging("esri") && list != null) { - double[] ex = list.getExtents(); - Debug.output("extents of list: xmin=" + ex[1] + ", ymin=" + ex[0] + ", xmax=" + ex[3] + ", ymax=" + ex[2]); - } - - return list; - } - - /** - * Reads the header section of a .shp file - * - * @return the shape type - * @deprecated not used. - */ - public int readHeader() - throws IOException { - /* int fileCode = */_leis.readInt(); - _leis.skipBytes(20); - /* int fileLength = */_leis.readInt(); - /* int version = */_leis.readLEInt(); - int shapeType = _leis.readLEInt(); - /* double xMin = */_leis.readLEDouble(); - /* double yMin = */_leis.readLEDouble(); - /* double xMax = */_leis.readLEDouble(); - /* double yMax = */_leis.readLEDouble(); - /* double zMin = */_leis.readLEDouble(); - /* double zMax = */_leis.readLEDouble(); - /* double mMin = */_leis.readLEDouble(); - /* double mMax = */_leis.readLEDouble(); - return shapeType; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShxInputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShxInputStream.java deleted file mode 100644 index 48d7a44c4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/ShxInputStream.java +++ /dev/null @@ -1,82 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/input/ShxInputStream.java,v $ -// $RCSfile: ShxInputStream.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/08/25 15:36:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.input; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Reads index data from a .shx file - * - * @author Doug Van Auken - */ -public class ShxInputStream { - - /** - * An input stream to process primitives in Little Endian or Big Endian - */ - private LittleEndianInputStream _leis = null; - - /** - * Chains an input stream with a Little EndianInputStream - */ - public ShxInputStream(InputStream is) { - BufferedInputStream bis = new BufferedInputStream(is); - _leis = new LittleEndianInputStream(bis); - } - - /** - * Processes the SHX file to obtain a list of offsets, which classes derived - * from AbstractSupport will use to iterate through the associated SHP file - * - * @return an array of offsets, which will be passed into the open method of - * classes which extend AbstractSupport. - */ - public int[][] getIndex() { - int[][] indexData = null; - try { - /* int fileCode = */_leis.readInt(); - _leis.skipBytes(20); - int fileLength = _leis.readInt(); - int numShapes = (fileLength - 50) / 4; - indexData = new int[2][numShapes]; - _leis.skipBytes(4); - /* _type = */_leis.readLEInt(); - _leis.skip(64); - for (int i = 0; i <= numShapes - 1; i++) { - indexData[0][i] = _leis.readInt(); - indexData[1][i] = _leis.readInt(); - } - } catch (IOException e) { - e.printStackTrace(); - return null; - } - return indexData; - } - - public void close() - throws IOException { - _leis.close(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/package.html deleted file mode 100644 index f13e8bfc8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/input/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package provides InputStreams for .shp, .dbf and .shx files that -make up the ESRI Shape file format. - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/DbfOutputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/DbfOutputStream.java deleted file mode 100644 index 3c0620154..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/DbfOutputStream.java +++ /dev/null @@ -1,238 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/output/DbfOutputStream.java,v $ -// $RCSfile: DbfOutputStream.java,v $ -// $Revision: 1.18 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.output; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -import com.bbn.openmap.dataAccess.shape.DbfTableModel; - -/** - * Writes date in a DbfTableModel to a file, conforming to the DBF III file - * format specification - * - * @author Doug Van Auken - */ -public class DbfOutputStream { - /** - * An outputstream that writes primitive data types in little endian or big - * endian - */ - private LittleEndianOutputStream _leos; - - /** - * Creates a DbfOutputStream - */ - public DbfOutputStream(OutputStream os) { - BufferedOutputStream bos = new BufferedOutputStream(os); - _leos = new LittleEndianOutputStream(bos); - } - - /** - * Writes the model out on the stream. The stream is closed automatically - * after the write. - * - * @param model the tablemodel to write - */ - public void writeModel(DbfTableModel model) throws IOException { - int rowCount = model.getRowCount(); - short headerLength = calcHeaderLength(model); - short recordLength = calcRecordLength(model); - - writeHeader(rowCount, headerLength, recordLength); - writeFieldDescriptors(model); - writeRecords(model); - - close(); - } - - /** - * Calculates the length of the record by aggregating the length of each - * field - * - * @param model The DbfTableModel for which to calculate the record length - * @return The length of a record - */ - public short calcRecordLength(DbfTableModel model) { - int length = 0; - int columnCount = model.getColumnCount(); - for (int i = 0; i <= columnCount - 1; i++) { - length += model.getLength(i); - } - length += 1; - Integer integer = new Integer(length); - return integer.shortValue(); - } - - /** - * Calculates the length of the header in terms of bytes - * - * @param model The DbfTableModel for which to calculate header length - * @return The header length - */ - public short calcHeaderLength(DbfTableModel model) { - int length = 0; - length += model.getColumnCount() * 32; // 32 bytest for each - // record - length += 32; // 32 bytes for the record - length += 1; // 1 byte for header terminator - Integer integer = new Integer(length); - return integer.shortValue(); - } - - /** - * Writes the header to the class scope LittleEndianOutputStream - * - * @param rowCount The number of records - * @param headerLength The length, in terms of bytes, of the header section - * @param recordLength The length, in terms of bytes, of each records - */ - private void writeHeader(int rowCount, short headerLength, - short recordLength) throws IOException { - - _leos.writeByte(3); // byte 0 - _leos.writeByte(96); // Byte 1 - Year - _leos.writeByte(4); // Byte 2 - Month - _leos.writeByte(30); // Byte 3 - Day - _leos.writeLEInt(rowCount); // Byte 4 Number of records in the - // table - _leos.writeLEShort(headerLength); // byte 8 Number of bytes in - // the header - _leos.writeLEShort(recordLength); // byte 10 Number of bytes - // in the record - _leos.writeByte(0); // Byte 12 - _leos.writeByte(0); // Byte 13 - _leos.writeByte(0); // Byte 14 - _leos.writeByte(0); // Byte 15 - _leos.writeByte(0); // Byte 16 - _leos.writeByte(0); // Byte 17 - _leos.writeByte(0); // Byte 18 - _leos.writeByte(0); // Byte 19 - _leos.writeByte(0); // Byte 20 - _leos.writeByte(0); // Byte 21 - _leos.writeByte(0); // Byte 22 - _leos.writeByte(0); // Byte 23 - _leos.writeByte(0); // Byte 24 - _leos.writeByte(0); // Byte 25 - _leos.writeByte(0); // Byte 26 - _leos.writeByte(0); // Byte 27 - _leos.writeByte(0); // Byte 28 - _leos.writeByte(0); // Byte 29 - _leos.writeByte(0); // Byte 30 - _leos.writeByte(0); // Byte 31 - } - - /** - * Iterates through the DbfTableModel's collection of columns and calls the - * writeFieldDescriptor method for each column - * - * @param model The DbfTableModel - */ - private void writeFieldDescriptors(DbfTableModel model) throws IOException { - int columnCount = model.getColumnCount(); - for (int i = 0; i <= columnCount - 1; i++) { - String name = model.getColumnName(i); - int length = model.getLength(i); - byte decimalCount = model.getDecimalCount(i); - byte type = model.getType(i); - writeFieldDescriptor(name, type, length, decimalCount); - } - _leos.writeByte(13); - } - - /** - * Writes records to the LittleEndianOutputStream - * - * @param name The field name - * @param type The field type - * @param length The field length - * @param decimalPlaces The number of decimal places for each field - */ - private void writeFieldDescriptor(String name, byte type, int length, - byte decimalPlaces) throws IOException { - _leos.writeString(name, 11); // Byte 0-10 - _leos.writeByte(type); // Byte 11 - _leos.writeByte(0); // Byte 12 Field data address(0) - _leos.writeByte(0); // Byte 13 Field data address(1) - _leos.writeByte(0); // Byte 14 Field data address(2) - _leos.writeByte(0); // Byte 15 Field data address(3) - _leos.writeByte(length); // Byte 16 Field length in bytes - _leos.writeByte(decimalPlaces); // Byte 17 Field decimal - // places - _leos.writeByte(0); // Byte 18 Reserved for dBASE III PLUS on - // a LAN(0) - _leos.writeByte(0); // Byte 19 Reserved for dBASE III PLUS on - // a LAN(1) - _leos.writeByte(0); // Byte 20 Work area 1D - _leos.writeByte(0); // Byte 21 Reserved for dBASE III PLUS on - // a LAN(0) - _leos.writeByte(0); // Byte 22 Reserved for dBASE III PLUS on - // a LAN(1) - _leos.writeByte(0); // Byte 23 SET FIELDS Flag - _leos.writeByte(0); // Byte 24 Reserved Bytes(0) #24 - _leos.writeByte(0); // Byte 25 Reserved Bytes(0) #25 - _leos.writeByte(0); // Byte 26 Reserved Bytes(0) #26 - _leos.writeByte(0); // Byte 27 Reserved Bytes(0) #27 - _leos.writeByte(0); // Byte 28 Reserved Bytes(0) #28 - _leos.writeByte(0); // Byte 29 Reserved Bytes(0) #29 - _leos.writeByte(0); // Byte 30 Reserved Bytes(0) #30 - _leos.writeByte(0); // Byte 31 Reserved Bytes(0) #31 - } - - public void writeRecords(DbfTableModel model) throws IOException { - - DecimalFormat df = new DecimalFormat(); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH); - df.setDecimalFormatSymbols(dfs); - df.setGroupingUsed(false); - - int rowCount = model.getRowCount(); - int columnCount = model.getColumnCount(); - for (int r = 0; r <= rowCount - 1; r++) { - _leos.writeByte(32); - for (int c = 0; c <= columnCount - 1; c++) { - byte type = model.getType(c); - int columnLength = model.getLength(c); - int numDecSpaces = model.getDecimalCount(c); - df.setMaximumFractionDigits(numDecSpaces); - df.setGroupingUsed(false); - String value = DbfTableModel.getStringForType(model.getValueAt(r, c), - type, - df, columnLength); - - int length = model.getLength(c); - _leos.writeString(value, length); - } - } - } - - public void close() throws IOException { - _leos.writeByte(26); - _leos.flush(); - _leos.close(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/LittleEndianOutputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/LittleEndianOutputStream.java deleted file mode 100644 index ba92a781b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/LittleEndianOutputStream.java +++ /dev/null @@ -1,196 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/output/LittleEndianOutputStream.java,v $ -// $RCSfile: LittleEndianOutputStream.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.output; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UTFDataFormatException; - -/** - * Provides methods for writing data to an output stream in - * LittleEndian and BigEndian. Adapted from the book, Java IO, - * Elliotte Rusty Harold, Ch. 7. - * - * @author Doug Van Auken - */ -public class LittleEndianOutputStream extends DataOutputStream { - - public void writeString(String string, int length) throws IOException { - if (string.length() < length) { - String newstring = zeroFill(string, length); - byte[] bytes = newstring.getBytes(); - // if(length==11){ - // System.out.println("bytes.length=" + bytes.length); - // } - out.write(bytes); - } else { - String newstring = string.substring(0, length); - byte[] bytes = newstring.getBytes(); - // if(length==11){ - // System.out.println("bytes.length=" + bytes.length); - // } - out.write(bytes); - } - } - - private String zeroFill(String string, int length) { - char[] oldchars = string.toCharArray(); - char[] newchars = new char[length]; - for (int i = 0; i <= newchars.length - 1; i++) { - if (i <= oldchars.length - 1) { - newchars[i] = oldchars[i]; - } else { - newchars[i] = 0; - } - } - return new String(newchars); - } - - /** - * Constructor out The output stream to chain this one to. - */ - public LittleEndianOutputStream(OutputStream out) { - super(out); - } - - /** - * Writes a number of type short in little endian - * - * @param s A number of type short - */ - public void writeLEShort(short s) throws IOException { - out.write(s & 0xFF); - out.write((s >>> 8) & 0xFF); - written += 2; - } - - /** - * Writes a number of type char in little endian param c An - * integer that is upcast from a Char data type. - */ - public void writeLEChar(int c) throws IOException { - out.write(c & 0xFF); - out.write((c >>> 8) & 0xFF); - written += 2; - } - - /** - * Writes a number of type int in little endian - * - * @param i A number of type int - */ - public void writeLEInt(int i) throws IOException { - out.write(i & 0xFF); - out.write((i >>> 8) & 0xFF); - out.write((i >>> 16) & 0xFF); - out.write((i >>> 24) & 0xFF); - written += 4; - } - - /** - * Writes a number of type long in little endian - * - * @param l A number of type long - */ - public void writeLELong(long l) throws IOException { - out.write((int) l & 0xFF); - out.write((int) (l >>> 8) & 0xFF); - out.write((int) (l >>> 16) & 0xFF); - out.write((int) (l >>> 24) & 0xFF); - out.write((int) (l >>> 32) & 0xFF); - out.write((int) (l >>> 40) & 0xFF); - out.write((int) (l >>> 48) & 0xFF); - out.write((int) (l >>> 56) & 0xFF); - written += 8; - } - - /** - * Writes a number of type float in little endian - * - * @param f A number of type float. - */ - public final void writeLEFloat(float f) throws IOException { - this.writeLEInt(Float.floatToIntBits(f)); - } - - /** - * Writes a number a number of type double in little endian - * - * @param d A number of type double - */ - public final void writeLEDouble(double d) throws IOException { - this.writeLELong(Double.doubleToLongBits(d)); - } - - /** - * Writes a String in little endian - * - * @param s A string - */ - public void writeLEChars(String s) throws IOException { - int length = s.length(); - for (int i = 0; i < length; i++) { - int c = s.charAt(i); - out.write(c & 0xFF); - out.write((c >>> 8) & 0xFF); - } - written += length * 2; - } - - public void writeLEUTF(String s) throws IOException { - int numchars = s.length(); - int numbytes = 0; - for (int i = 0; i < numchars; i++) { - int c = s.charAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) - numbytes++; - else if (c > 0x07FF) - numbytes += 3; - else - numbytes += 2; - } - - if (numbytes > 65535) - throw new UTFDataFormatException(); - - out.write((numbytes >>> 8) & 0xFF); - out.write(numbytes & 0xFF); - for (int i = 0; i < numchars; i++) { - int c = s.charAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) { - out.write(c); - } else if (c > 0x07FF) { - out.write(0xE0 | ((c >> 12) & 0x0F)); - out.write(0x80 | ((c >> 6) & 0x3F)); - out.write(0x80 | (c & 0x3F)); - written += 2; - } else { - out.write(0xC0 | ((c >> 6) & 0x1F)); - out.write(0x80 | (c & 0x3F)); - written += 1; - } - } - written += numchars + 2; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShpOutputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShpOutputStream.java deleted file mode 100644 index d343dc272..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShpOutputStream.java +++ /dev/null @@ -1,521 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/output/ShpOutputStream.java,v $ -// $RCSfile: ShpOutputStream.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.output; - -import java.awt.geom.Point2D; -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.shape.EsriGraphic; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.dataAccess.shape.EsriPointList; -import com.bbn.openmap.dataAccess.shape.EsriPolygonList; -import com.bbn.openmap.dataAccess.shape.EsriPolylineList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Writes data to a .shp file - * - * @author Doug Van Auken - */ -public class ShpOutputStream { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.output.ShpOutputStream"); - public final static int ESRI_RECORD_HEADER_LENGTH = 4; // length in 16-bit - // words - /** - * A GeoCoordTransform to use to convert Lat/Lon values in EsriGraphics to - * projected coordinates. - */ - protected GeoCoordTransformation transform; - - /** - * An outputstream that writes primitive data types in little endian or big - * endian - */ - private LittleEndianOutputStream _leos = null; - - /** - * Creates an outputstream to write to - * - * @param os The output stream to write to - */ - public ShpOutputStream(OutputStream os) { - BufferedOutputStream bos = new BufferedOutputStream(os); - _leos = new LittleEndianOutputStream(bos); - } - - /** - * Get the transform being used on the coordinates of the EsriGraphics as - * they are written to the stream. - * - * @return GeoCoordTransform if used, may be null for no transformation. - */ - public GeoCoordTransformation getTransform() { - return transform; - } - - /** - * Set the GeoCoordTransform for the stream, so that the EsriGraphics will - * have their coordinates transformed as they are written to the stream. If - * null, the coordinates will be unchanged. - * - * @param transform - */ - public void setTransform(GeoCoordTransformation transform) { - this.transform = transform; - } - - /** - * Determine what type of list is given and write it out. - * - * @param list The EsriGraphicList to write - * @return The index data that is used to create the .shx file - */ - public int[][] writeGeometry(EsriGraphicList list) - throws IOException { - if (list instanceof EsriPolygonList || list instanceof EsriPolylineList) { - return writePolyGeometry(list); - } else if (list instanceof EsriPointList) { - return writePointGeometry(list); - } - return null; - } - - /** - * Calculates the content length for each record, in terms of words as - * defined by ESRI documentation. A word is 16 bits, so a double is 4 words - * and an int is 2 words. - * - * @param list The EsriGraphicList to write - * @return The index data that is used to create the .shx file - */ - protected int[][] createPointIndex(OMGraphicList list) { - int[][] indexData = new int[2][list.size()]; - - int pos = 50; - for (int i = 0; i < list.size(); i++) { - // OMGraphicList sublist = - // (OMGraphicList)list.getOMGraphicAt(i); - int contentLength = 0; - contentLength += 2; // Shape Type - - OMGraphic graphic = list.getOMGraphicAt(i); - if (graphic instanceof EsriGraphicList) { - EsriGraphicList sublist = (EsriGraphicList) graphic; - contentLength += (4 * 4); // bounding box, 4 doubles - contentLength += 2; // number of points, 1 int - contentLength += (sublist.size() * (2 + 4)); // points, 2 doubles - // each - } else { - contentLength += 4; // X - contentLength += 4; // Y - } - indexData[1][i] = contentLength; - indexData[0][i] = pos; - pos += contentLength + 4; - } - return indexData; - } - - /** - * Creates a two dimensional array holding a list of shape content lengths - * and shape content length offsets, as defined in Esri shape file - * documentation. This array is used to create the .shx file - * - * @param list The list from which to create the respective array - * @return The index data that is used to create the .shx file - */ - protected int[][] createPolyIndex(EsriGraphicList list) { - double[] data; - - int[][] indexData = new int[2][list.size()]; - int pos = 50; - - for (int i = 0; i < list.size(); i++) { - int contentLength = 0; - OMGraphic graphic = (OMGraphic) list.getOMGraphicAt(i); - - contentLength += 2; // Shape Type - contentLength += 16; // Box - contentLength += 2; // NumParts - contentLength += 2; // NumPoints - - if (graphic instanceof OMGraphicList) { - OMGraphicList sublist = (OMGraphicList) graphic; - contentLength += sublist.size() * 2; // offsets? - - for (int j = 0; j < sublist.size(); j++) { - OMPoly poly = (OMPoly) sublist.getOMGraphicAt(j); - data = poly.getLatLonArray(); - - // each value equals 4 words - contentLength += data.length * 4; - } - } else { - contentLength += 2; // offset? - - // Should be an EsriPolyline - data = ((OMPoly) graphic).getLatLonArray(); - // each value equals 4 words - contentLength += data.length * 4; - } - - indexData[1][i] = contentLength; - indexData[0][i] = pos; - pos += contentLength + 4; - } - return indexData; - } - - /** - * Creates an array whose elements specify at what index a shapes geometry - * begins - * - * @param contentLengths The array for which to get offsets from - * @return An array of record offsets - */ - protected int[] getRecordOffsets(int[] contentLengths) { - int[] offsets = new int[contentLengths.length]; - int pos = 50; - for (int i = 0; i < contentLengths.length; i++) { - offsets[i] = pos; - pos += contentLengths[i] + 4; - } - return offsets; - } - - /** - * Creates an array whose elements specifies at what index a parts geometry - * begins - * - * @param sublist A list of shapes - * @return An array of part offsets - */ - protected int[] getPartOffsets(OMGraphicList sublist) { - int pos = 0; - int[] offsets = new int[sublist.size()]; - for (int j = 0; j < sublist.size(); j++) { - OMPoly poly = (OMPoly) sublist.getOMGraphicAt(j); - double[] data = poly.getLatLonArray(); - offsets[j] = pos / 2; - pos += data.length; - } - return offsets; - } - - /** - * Iterates through a list of shapes, summing the points per part to - * determine the number of points per shape - * - * @param sublist A list of shapes - * @return The number of points for a given shape - */ - protected int getPointsPerShape(OMGraphicList sublist) { - int numPoints = 0; - for (int i = 0; i < sublist.size(); i++) { - OMPoly poly = (OMPoly) sublist.getOMGraphicAt(i); - double[] data = poly.getLatLonArray(); - numPoints += data.length; - } - numPoints /= 2; - return numPoints; - } - - protected void writeExtents(double[] extents) - throws IOException { - - if (_leos == null) { - return; - } - - if (extents[0] == 90f && extents[1] == 180f && extents[2] == -90f && extents[3] == -180f) { - - // Whoa! not set from defaults correctly! - // use old, hardcoded way. - _leos.writeLEDouble(-180.0); - _leos.writeLEDouble(-90.0); - _leos.writeLEDouble(180.0); - _leos.writeLEDouble(90.0); - - } else { - if (transform == null) { - _leos.writeLEDouble(extents[1]); - _leos.writeLEDouble(extents[0]); - _leos.writeLEDouble(extents[3]); - _leos.writeLEDouble(extents[2]); - } else { - Point2D pnt = transform.forward(extents[0], extents[1]); - // extents are written out x, y - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - pnt = transform.forward(extents[2], extents[3], pnt); - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - } - } - } - - /** - * Writes polygon geometry to the class scope LittleEndianInputStream. - * - * @param list The list of geometry objects to save - * @return A two dimensional array containing shape offsets and content - * lengths - */ - public int[][] writePolyGeometry(EsriGraphicList list) - throws IOException { - - OMPoly poly; - - _leos.writeInt(9994); // Byte 0 File Code - _leos.writeInt(0); // Byte 4 Unused - _leos.writeInt(0); // Byte 8 Unused - _leos.writeInt(0); // Byte 12 Unused - _leos.writeInt(0); // Byte 16 Unused - _leos.writeInt(0); // Byte 20 Unused - - int[][] indexData = createPolyIndex(list); - int contentLength = 50; - - if (!list.isEmpty()) { - contentLength = indexData[0][indexData[0].length - 1] + indexData[1][indexData[0].length - 1] + ESRI_RECORD_HEADER_LENGTH; - } - - _leos.writeInt(contentLength); // Byte 24 File Length - _leos.writeLEInt(1000); // Byte 28 Version - _leos.writeLEInt(list.getType()); // Byte 32 Shape Type - - // Writes bounding box. - double[] extents = list.getExtents(); - writeExtents(extents); - - _leos.writeDouble(0.0); // Byte 68 - _leos.writeDouble(0.0); // Byte 76 - _leos.writeDouble(0.0); // Byte 84 - _leos.writeDouble(0.0); // Byte 92 - - // Temporary point used for transformations - Point2D pnt = new Point2D.Double(); - - // Iterate through the list - for (int i = 0; i < list.size(); i++) { - - OMGraphic graphic = list.getOMGraphicAt(i); - - // Record header - _leos.writeInt(i + 1); // Record numbers start with 1 - _leos.writeInt(indexData[1][i]); - - // Beginning of Geometry data - _leos.writeLEInt(list.getType()); // Little endian - - // More stuff needs to be written out for just the OMPoly - // case... - // Single part, etc. - - if (graphic instanceof EsriGraphicList) { - - // Assumes that the elements of the top level list are - // EsriGraphicLists, too. This will probably be - // changing. - EsriGraphicList sublist = (EsriGraphicList) graphic; - - // Writes bounding box. - extents = sublist.getExtents(); - writeExtents(extents); - - // Writes number of parts - int numParts = sublist.size(); - _leos.writeLEInt(numParts); - - // Write number of points per shape - int numPoints = getPointsPerShape(sublist); - _leos.writeLEInt(numPoints); - - // Write the offsets to each part for a given shape - int[] offsets = getPartOffsets(sublist); - - for (int j = 0; j < offsets.length; j++) { - _leos.writeLEInt(offsets[j]); - } - - // Write the geometry for each part - for (int j = 0; j < sublist.size(); j++) { - poly = (OMPoly) sublist.getOMGraphicAt(j); - double[] data = poly.getLatLonArray(); - int n = 0; - while (n < data.length) { - double lat = Math.toDegrees(data[n++]); - double lon = Math.toDegrees(data[n++]); - if (transform == null) { - _leos.writeLEDouble(lon); - _leos.writeLEDouble(lat); - } else { - transform.forward(lat, lon, pnt); - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - } - } - } - } else { - extents = ((EsriGraphic) graphic).getExtents(); - writeExtents(extents); - - // Writes number of parts for shape (1) - _leos.writeLEInt(1); - - poly = (OMPoly) graphic; - double[] data = poly.getLatLonArray(); - - // Write number of points for shape - _leos.writeLEInt(data.length / 2); - - // Write the offsets to this shape - _leos.writeLEInt(0); - - int n = 0; - while (n < data.length) { - double lat = Math.toDegrees(data[n++]); - double lon = Math.toDegrees(data[n++]); - if (transform == null) { - _leos.writeLEDouble(lon); - _leos.writeLEDouble(lat); - } else { - transform.forward(lat, lon, pnt); - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - } - } - } - } - _leos.flush(); - _leos.close(); - return indexData; - } - - /** - * Writes point geometry to the class scope LittleEndianOutputStream. - * - * @param list An EsriGraphicList of points - * @return A two dimensional array containing shape offsets and content - * lengths - */ - public int[][] writePointGeometry(EsriGraphicList list) - throws IOException { - _leos.writeInt(9994); // Big - _leos.writeInt(0); // Big - _leos.writeInt(0); // Big - _leos.writeInt(0); // Big - _leos.writeInt(0); // Big - _leos.writeInt(0); // Big - - int[][] indexData = createPointIndex(list); - int contentLength = 50; - - if (!list.isEmpty()) { - contentLength = indexData[0][indexData[0].length - 1] + indexData[1][indexData[0].length - 1] + ESRI_RECORD_HEADER_LENGTH; - } - - _leos.writeInt(contentLength); // Big - _leos.writeLEInt(1000); // Little - _leos.writeLEInt(list.getType()); - - // Writes bounding box. - double[] extents = list.getExtents(); - writeExtents(extents); - - _leos.writeDouble(0.0); - _leos.writeDouble(0.0); - _leos.writeDouble(0.0); - _leos.writeDouble(0.0); - - // For coordinate transformations - Point2D pnt = new Point2D.Double(); - OMPoint point = null; - for (int i = 0; i < list.size(); i++) { - OMGraphic graphic = list.get(i); - - // Record header... - _leos.writeInt(i + 1); // Record numbers start with 1 - _leos.writeInt(indexData[1][i]); - - // Beginning of Geometry data - _leos.writeLEInt(list.getType()); - - if (graphic instanceof OMGraphicList) { - EsriGraphicList sublist = (EsriGraphicList) graphic; - - // Writes bounding box. - extents = sublist.getExtents(); - writeExtents(extents); - - // Write number of points per shape - _leos.writeLEInt(sublist.size()); - - // Write the geometry for each part - for (int j = 0; j < sublist.size(); j++) { - point = (OMPoint) sublist.getOMGraphicAt(j); - LatLonPoint pt = new LatLonPoint.Double(point.getLat(), point.getLon()); - - double lat = pt.getY(); - double lon = pt.getX(); - - if (transform == null) { - _leos.writeLEDouble(lon); - _leos.writeLEDouble(lat); - } else { - transform.forward(lat, lon, pnt); - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - } - } - } else { - point = (OMPoint) graphic; - LatLonPoint pt = new LatLonPoint.Double(point.getLat(), point.getLon()); - double lat = pt.getY(); - double lon = pt.getX(); - - if (transform == null) { - _leos.writeLEDouble(lon); - _leos.writeLEDouble(lat); - } else { - transform.forward(lat, lon, pnt); - _leos.writeLEDouble(pnt.getX()); - _leos.writeLEDouble(pnt.getY()); - } - } - } - _leos.flush(); - _leos.close(); - - return indexData; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShxOutputStream.java b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShxOutputStream.java deleted file mode 100644 index c032c9ac6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/ShxOutputStream.java +++ /dev/null @@ -1,124 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/output/ShxOutputStream.java,v $ -// $RCSfile: ShxOutputStream.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape.output; - -import java.io.BufferedOutputStream; -import java.io.OutputStream; - -/** - * Writes the .shx file - * - * @author Doug Van Auken - */ -public class ShxOutputStream { - /** - * An outputstream that writes primitive data types in little endian or big - * endian - */ - private LittleEndianOutputStream _leos = null; - - /** - * Chains an output stream to a LittleEndianOutputStream - * - * @param os An outputstream to chain a LittleEndianOutputStream to - */ - public ShxOutputStream(OutputStream os) { - BufferedOutputStream bos = new BufferedOutputStream(os); - _leos = new LittleEndianOutputStream(bos); - } - - /** - * Writes the index, with the default extents of the graphics being the - * entire earth. - * - * @param indexData The index data to write - * @param layerType Tye type of layer being written - * @return True if no exceptions occur - */ - public boolean writeIndex(int[][] indexData, int layerType) { - return writeIndex(indexData, layerType, new double[] { -90, -180, 90, - 180 }); - } - - /** - * Writes the index, with the default extents of the graphics being the - * entire earth. - * - * @param indexData The index data to write - * @param layerType Tye type of layer being written - * @param extents an array of floats describing, in order, miny, minx, maxy, - * maxx for the area that the graphics in the shape file cover. - * @return True if no exceptions occur - */ - public boolean writeIndex(int[][] indexData, int layerType, double[] extents) { - - try { - _leos.writeInt(9994); - _leos.writeInt(0); - _leos.writeInt(0); - _leos.writeInt(0); - _leos.writeInt(0); - _leos.writeInt(0); - _leos.writeInt(indexData[0].length * 4 + 50); - _leos.writeLEInt(1000); - _leos.writeLEInt(layerType); - - if (extents[0] == 90f && extents[1] == 180f && extents[2] == -90f - && extents[3] == -180f) { - - // Whoa! not set from defaults correctly! - // use old, hardcoded way. - _leos.writeLEDouble(-180.0); // Hard-coding extents. - _leos.writeLEDouble(-90.0); // When viewed through - // ArcView, this will - _leos.writeLEDouble(180.0); // cause window to zoom to - // world extents - _leos.writeLEDouble(90.0); // instead of layer - // extents. - - } else { - _leos.writeLEDouble((float) extents[1]); - _leos.writeLEDouble((float) extents[0]); - _leos.writeLEDouble((float) extents[3]); - _leos.writeLEDouble((float) extents[2]); - } - - _leos.writeLEDouble(0.0); - _leos.writeLEDouble(0.0); - _leos.writeLEDouble(0.0); - _leos.writeLEDouble(0.0); - - for (int i = 0; i <= indexData[0].length - 1; i++) { - _leos.writeInt(indexData[0][i]); - _leos.writeInt(indexData[1][i]); - } - _leos.flush(); - _leos.close(); - } catch (Exception e) { - System.out.println("exception=" + e.toString()); - return false; - } - return true; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/package.html deleted file mode 100644 index e626976cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/output/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package provides OutputStreams for .shp, .dbf and .shx files that -make up the ESRI Shape file format. - diff --git a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/package.html b/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/package.html deleted file mode 100644 index 14b94a66a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/dataAccess/shape/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package provides read and write access to ESRI shape files, -including the .shp, .dbf and .shx files. - diff --git a/src/core/src/main/java/com/bbn/openmap/event/AbstractMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/AbstractMouseMode.java deleted file mode 100644 index da3d0a2f7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/AbstractMouseMode.java +++ /dev/null @@ -1,879 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/AbstractMouseMode.java,v $ -// $RCSfile: AbstractMouseMode.java,v $ -// $Revision: 1.15 $ -// $Date: 2008/10/16 19:33:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.net.MalformedURLException; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.Timer; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.OptionPropertyEditor; - -/** - * Base class of the MouseModes. It takes care of the administrative aspects of - * being a mouse mode, but does not respond to MouseEvents. - *

- * The ID and pretty name can be set in the properties file. - * - *

- * 
- * 
- *    # Name that layers use to get events from this mode
- *    mousemode.id=ID
- *    # Tooltip and Menu name for mode
- *    mousemode.prettyName=Display Name
- * 
- * 
- * 
- * 
- * 
- * - * This class delegates much of the work of managing its listeners to a - * MapMouseSupport object. - * - * @see MapMouseSupport - */ -public class AbstractMouseMode - extends OMComponent - implements MapMouseMode, Serializable { - - private static final long serialVersionUID = 1L; - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.event.MapMouseMode"); - - /** - * The identifier for the mode, which is also the name that will be used in a - * used interface describing the mode to a user. - */ - protected String ID = null; - - /** - * The object used to handle the listeners and to pass out the event to the - * layers interested in it. - */ - protected MapMouseSupport mouseSupport; - - /** - * The cursor that appears on the map when this Mouse Mode is active. - */ - protected Cursor cursor = Cursor.getDefaultCursor(); - - /** - * The Icon that can be used in a GUI. Can be null. The class will look for a - * resource gif file that has the same ID string - Navigation.gif for the - * NavMouseMode, for instance. - */ - protected transient Icon guiIcon = null; - - protected transient boolean visible = true; - - protected boolean mouseWheelListener = true; - - protected boolean noMouseWheelListenerTimer = false; - - protected String prettyName; - - protected String iconName; - - protected boolean zoomWhenMouseWheelUp = ZOOM_IN; - - protected PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); - - /** - * Zoom direction in when mouse wheel rotated up. - */ - public static final boolean ZOOM_IN = true; - /** - * Zoom direction out when mouse wheel rotated up. - */ - public static final boolean ZOOM_OUT = false; - - /** - * The MouseModeID to use for a particular instance of a MapMouseMode. If not - * set, the default mouse mode ID of the MapMouseMode will be used. - */ - public static final String IDProperty = "id"; - - /** - * The String to use for a key lookup in a Properties object to find the name - * to use in a GUI relating to this Mouse Mode. - */ - public static final String PrettyNameProperty = "prettyName"; - - /** - * The java.awt.Cursor id that should be used for the mouse mode. - * - * @see java.awt.Cursor - */ - public static final String CursorIDProperty = "cursorID"; - - /** - * A property that lets you specify the resource to use for the icon for the - * MouseMode. - */ - public static final String IconProperty = "icon"; - - /** - * A property that lets you specify if the mode zooms in or out when the - * mouse wheel is rotated up. Appropriate values are ZOOM_IN or ZOOM_OUT. - */ - public static final String MouseWheelZoomProperty = "mouseWheelUp"; - - /** - * A property that lets you turn off the mouse wheel listening functionality. - * If enabled, the mouse wheel changes the scale of the map. - */ - public static final String MouseWheelListenerProperty = "mouseWheelListener"; - - /** - * A property that lets you turn off the mouse wheel timer. - * If disabled, a timer is used for dealing with the mouse wheel changes. - */ - public static final String NoMouseWheelListenerTimerProperty = "noMouseWheelListenerTimer"; - - /** - * A property that lets you set the wait interval before a mouse wheel event - * gets triggered. - */ - public static final String MouseWheelTimerIntervalProperty = "mouseWheelTimerInterval"; - - /** - * Construct an AbstractMouseMode. Default constructor, allocates the mouse - * support object. - */ - public AbstractMouseMode() { - this("Unnamed Mode", true); - } - - /** - * Construct an AbstractMouseMode. - * - * @param name the ID of the mode. - * @param shouldConsumeEvents if true, events are propagated to the first - * MapMouseListener that successfully processes the event, if false, - * events are propagated to all MapMouseListeners - */ - public AbstractMouseMode(String name, boolean shouldConsumeEvents) { - mouseSupport = new MapMouseSupport(this, shouldConsumeEvents); - ID = name; - setIconName(name + ".gif"); - } - - /** - * Internal callback method that lets subclasses override a class to use as a - * resource point for icon image retrieval. - * - * @return Class that has icon image file next to it in classpath. - */ - protected Class getClassToUseForIconRetrieval() { - return getClass(); - } - - /** - * Sets the GUI icon based on the name of the resource provided. The resource - * will be checked against the classpath, and if it isn't found, the mouse - * mode will be asked for the class to use for icon retrieval. - * - * @param iName - */ - public void setIconName(String iName) { - iconName = iName; - java.net.URL url = null; - - try { - url = PropUtils.getResourceOrFileOrURL(iName); - } catch (MalformedURLException murle) { - - } - - if (url == null) { - url = getClassToUseForIconRetrieval().getResource(iconName); - } - - if (url != null) { - guiIcon = new ImageIcon(url); - } - } - - public String getIconName() { - return iconName; - } - - /** - * Returns the id (mode name). - * - * @return String ID - */ - public String getID() { - return ID; - } - - /** - * Set the id (mode name). - * - * @param id string that identifies the delegate. - */ - public void setID(String id) { - ID = id; - } - - public void setPrettyName(String pn) { - prettyName = pn; - } - - /** - * Return a pretty name, suitable for the GUI. If set, is independent of the - * mode ID. If not set, is the same as the mode ID. - */ - public String getPrettyName() { - if (prettyName == null) { - return i18n.get(this.getClass(), PrettyNameProperty, ID); - } else { - return prettyName; - } - } - - /** - * Gets the mouse cursor recommended for use when this mouse mode is active. - * - * @return Cursor the mouse cursor recommended for use when this mouse mode - * is active. - */ - public Cursor getModeCursor() { - return cursor; - } - - /** - * Sets the cursor that is recommended for use on the map when this mouse - * mode is active. - * - * @param curs the cursor that is recommended for use on the map when this - * mouse mode is active. - */ - public void setModeCursor(Cursor curs) { - cursor = curs; - } - - /** - * Sets the cursor that is recommended for use on the map when this mouse - * mode is active. - * - * @param cursorID the cursor ID member variable string, i.e. DEFAULT_CURSOR - * @see java.awt.Cursor - */ - public void setModeCursor(String cursorID) { - if (cursorID != null) { - - try { - int cid = java.awt.Cursor.class.getField(cursorID).getInt(null); - - setModeCursor(Cursor.getPredefinedCursor(cid)); - - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - } - } - - /** - * Gets the Icon to represent the Mouse Mode in a GUI. May be null. - */ - public Icon getGUIIcon() { - return guiIcon; - } - - /** - * Set the icon that should be used for this Mouse Mode in a GUI. - */ - public void setGUIIcon(Icon icon) { - guiIcon = icon; - } - - /** - * Sets how the delegate passes out events. If the value passed in is true, - * the delegate will only pass the event to the first listener that can - * respond to the event. If false, the delegate will pass the event on to all - * its listeners. - * - * @param value true for limited distribution. - */ - public void setConsumeEvents(boolean value) { - mouseSupport.setConsumeEvents(value); - } - - /** - * Returns how the delegate (and it's mouse support) is set up to distribute - * events. - * - * @return true if only one listener gets to act on an event. - */ - public boolean isConsumeEvents() { - return mouseSupport.isConsumeEvents(); - } - - public boolean isZoomWhenMouseWheelUp() { - return zoomWhenMouseWheelUp; - } - - public void setZoomWhenMouseWheelUp(boolean zoomWhenMouseWheelUp) { - this.zoomWhenMouseWheelUp = zoomWhenMouseWheelUp; - } - - /** - * Add a MapMouseListener to the MouseMode. The listener will then get events - * from the delegator if the delegator is active. - * - * @param l the MapMouseListener to add. - */ - public void addMapMouseListener(MapMouseListener l) { - mouseSupport.add(l); - } - - /** - * Remove a MapMouseListener from the MouseMode. - * - * @param l the MapMouseListener to remove. - */ - public void removeMapMouseListener(MapMouseListener l) { - mouseSupport.remove(l); - } - - /** - * Remove all MapMouseListeners from the mode. - */ - public void removeAllMapMouseListeners() { - mouseSupport.clear(); - } - - /** - * Invoked when the mouse has been clicked on a component. Calls - * fireMapMouseClicked on MouseSupport. - * - * @param e MouseEvent - */ - public void mouseClicked(MouseEvent e) { - mouseSupport.fireMapMouseClicked(e); - } - - /** - * Invoked when a mouse button has been pressed on a component. Calls - * fiewMapMousePressed on the MouseSupport. Also requests focus on the source - * of the MouseEvent, so that key events can be processed. - * - * @param e MouseEvent - */ - public void mousePressed(MouseEvent e) { - e.getComponent().requestFocus(); - mouseSupport.fireMapMousePressed(e); - } - - /** - * Invoked when a mouse button has been released on a component. Calls - * fireMapMouseReleased on the MouseSupport. - * - * @param e MouseEvent - */ - public void mouseReleased(MouseEvent e) { - mouseSupport.fireMapMouseReleased(e); - } - - /** - * Invoked when the mouse enters a component. Calls fireMapMouseEntered on - * the MouseSupport. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - mouseSupport.fireMapMouseEntered(e); - } - - /** - * Invoked when the mouse exits a component. This does nothing. Extend this - * class to add functionality. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - mouseSupport.fireMapMouseExited(e); - } - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * Calls fireMapMouseDragged on the MouseSupport. - * - * @param e MouseEvent - */ - public void mouseDragged(MouseEvent e) { - mouseSupport.fireMapMouseDragged(e); - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons no down). Calls fireMapMouseMoved on the MouseSupport. - * - * @param e MouseEvent - */ - public void mouseMoved(MouseEvent e) { - mouseSupport.fireMapMouseMoved(e); - } - - /** - * Invoked from the MouseWheelListener interface. - */ - public void mouseWheelMoved(MouseWheelEvent e) { - if (mouseWheelListener) { - int rot = e.getWheelRotation(); - if (e.getSource() instanceof MapBean) { - MapBean mb = (MapBean) e.getSource(); - boolean direction = isZoomWhenMouseWheelUp(); - - float zoomIn = 1.1f; - float zoomOut = .9f; - - float amount = zoomIn; - - if ((direction && rot < 0) || (!direction && rot > 0)) { - amount = zoomOut; - } - - if (noMouseWheelListenerTimer) { - updateMouseWheelMoved(mb, mb.getScale() * amount); - } else { - if (mouseTimer == null) { - mouseTimer = new Timer(mouseWheelTimerInterval, mouseWheelTimerListener); - mouseTimer.setRepeats(false); - } - - mouseWheelTimerListener.addAmount(mb, amount); - mouseTimer.restart(); - } - } - } - } - - /** - * Invoked from the MouseWheelListener interface. - */ - public void updateMouseWheelMoved(MapBean mb, float value) { - if (mb != null) { - mb.zoom(new ZoomEvent(mb, ZoomEvent.ABSOLUTE, value)); - } - } - - /** - * Check setting for whether MouseMode responds to mouse wheel events. - * - * @return true if mouse mode is interested in mouse wheel events. - */ - public boolean isMouseWheelListener() { - return mouseWheelListener; - } - - /** - * Set whether MouseMode responds to mouse wheel events. - * - * @param mouseWheelListener - */ - public void setMouseWheelListener(boolean mouseWheelListener) { - this.mouseWheelListener = mouseWheelListener; - } - - /** - * Part of the MapMouseMode interface. Called when the MouseMode is made - * active or inactive. - * - * @param active true if the mode has been made active, false if it has been - * made inactive. - */ - public void setActive(boolean active) { - } - - /** - * Set a MouseSupport explicitly. - * - * @param support The new MapMouseSupport instance - */ - public void setMouseSupport(MapMouseSupport support) { - mouseSupport = support; - } - - /** - * Get the MouseSupport. - * - * @return the MapMouseSupport used by the MouseMode. - */ - public MapMouseSupport getMouseSupport() { - return mouseSupport; - } - - /** - * Method to let the MouseDelegator know if the MapMouseMode should be - * visible, as opposed to a MapMouseMode that is being provided and - * controlled by another tool. True by default. - */ - public boolean isVisible() { - return visible; - } - - /** - * Method to set if the MapMouseMode should be visible, as opposed to a - * MapMouseMode that is being provided and controlled by another tool. - */ - public void setVisible(boolean value) { - visible = value; - } - - /** - * Request to have the parent MapMouseMode act as a proxy for a MapMouseMode - * that wants to remain hidden. Can be useful for directing events to one - * object. This version sets the proxy distribution mask to zero, which means - * that none of this support objects targets will be notified of events. - * - * @param mmm the hidden MapMouseMode for this MapMouseMode to send events - * to. - * @return true if the proxy setup (essentially a lock) is successful, false - * if the proxy is already set up for another listener. - */ - public boolean actAsProxyFor(MapMouseMode mmm) { - return actAsProxyFor(mmm, 0); - } - - /** - * Request to have the MapMouseMode act as a proxy for a MapMouseMode that - * wants to remain hidden. Can be useful for directing events to one object. - * - * @param mmm the hidden MapMouseMode for this MapMouseMode to send events - * to. - * @param pdm the proxy distribution mask to use, which lets this support - * object notify its targets of events if the parent is acting as a - * proxy. - * @return true if the proxy setup (essentially a lock) is successful, false - * if the proxy is already set up for another listener. - */ - public boolean actAsProxyFor(MapMouseMode mmm, int pdm) { - MapMouseMode omm = mouseSupport.getProxied(); - boolean ret = false; - if (mmm != null && !mmm.equals(omm)) { - ret = mouseSupport.setProxyFor(mmm, pdm); - propertyChangeSupport.firePropertyChange(MouseDelegator.ProxyMouseModeProperty, omm, mmm); - } - - return ret; - } - - /** - * Can check if the MapMouseMode is acting as a proxy for another - * MapMouseMode. - */ - public boolean isProxyFor(MapMouseMode mmm) { - return mouseSupport.isProxyFor(mmm); - } - - /** - * Release the proxy lock on the MapMouseMode. - */ - public void releaseProxy() { - MapMouseMode mmm = mouseSupport.getProxied(); - if (mmm != null) { - mouseSupport.releaseProxy(); - propertyChangeSupport.firePropertyChange(MouseDelegator.ProxyMouseModeProperty, mmm, null); - } - } - - /** - * Set the mask that dictates which events get sent to this support object's - * targets even if the parent mouse mode is acting as a proxy. - */ - public void setProxyDistributionMask(int mask) { - mouseSupport.setProxyDistributionMask(mask); - } - - /** - * Returns the MapMouseMode being held inside this mouse mode. - */ - public MapMouseMode getProxied() { - return mouseSupport.getProxied(); - } - - /** - * Get the mask that dictates which events get sent to this support object's - * targets even if the parent mouse mode is acting as a proxy. - */ - public int getProxyDistributionMask() { - return mouseSupport.getProxyDistributionMask(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String prettyNameString = props.getProperty(prefix + PrettyNameProperty); - if (prettyNameString != null) { - setPrettyName(prettyNameString); - } - - String idString = props.getProperty(prefix + IDProperty); - if (idString != null) { - setID(idString); - } - - setModeCursor(props.getProperty(prefix + CursorIDProperty)); - - String iconString = props.getProperty(prefix + IconProperty); - if (iconString != null) { - setIconName(iconString); - } - - mouseWheelListener = PropUtils.booleanFromProperties(props, prefix + MouseWheelListenerProperty, mouseWheelListener); - - zoomWhenMouseWheelUp = PropUtils.booleanFromProperties(props, prefix + MouseWheelZoomProperty, zoomWhenMouseWheelUp); - - String zwmwu = props.getProperty(prefix + MouseWheelZoomProperty); - if (zwmwu != null) { - try { - boolean zSetting = getClass().getField(zwmwu).getBoolean(null); - setZoomWhenMouseWheelUp(zSetting); - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - } - - noMouseWheelListenerTimer = PropUtils.booleanFromProperties(props, prefix + NoMouseWheelListenerTimerProperty, noMouseWheelListenerTimer); - mouseWheelTimerInterval = PropUtils.intFromProperties(props, prefix + MouseWheelTimerIntervalProperty, mouseWheelTimerInterval); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - if (prettyName != null) { - props.put(prefix + PrettyNameProperty, prettyName); - } - - props.put(prefix + IDProperty, getID()); - - int cursorType = getModeCursor().getType(); - - Field[] cFields = Cursor.class.getFields(); - for (int i = 0; i < cFields.length; i++) { - Field f = cFields[i]; - - String name = f.getName(); - if (name.endsWith("_CURSOR")) { - try { - int testType = f.getInt(null); - if (testType == cursorType) { - props.put(prefix + CursorIDProperty, name); - break; - } - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } - } - } - - if (zoomWhenMouseWheelUp) { - props.put(prefix + MouseWheelZoomProperty, "ZOOM_IN"); - } else { - props.put(prefix + MouseWheelZoomProperty, "ZOOM_OUT"); - } - - props.put(prefix + MouseWheelListenerProperty, Boolean.toString(mouseWheelListener)); - - props.put(prefix + IconProperty, PropUtils.unnull(getIconName())); - - props.put(prefix + NoMouseWheelListenerTimerProperty, Boolean.toString(noMouseWheelListenerTimer)); - props.put(prefix + MouseWheelTimerIntervalProperty, Integer.toString(mouseWheelTimerInterval)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - Class thisClass = getClass(); - String internString = i18n.get(thisClass, PrettyNameProperty, I18n.TOOLTIP, "Presentable name for Mouse Mode."); - props.put(Layer.AddToBeanContextProperty, internString); - internString = i18n.get(thisClass, PrettyNameProperty, "Name"); - props.put(PrettyNameProperty + LabelEditorProperty, internString); - - internString = i18n.get(thisClass, IDProperty, I18n.TOOLTIP, "Internal ID for Mouse Mode, used by Layers."); - props.put(Layer.AddToBeanContextProperty, internString); - internString = i18n.get(thisClass, IDProperty, "ID"); - props.put(IDProperty + LabelEditorProperty, internString); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, IconProperty, "Icon", "Icon to use for mouse mode.", null); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, MouseWheelZoomProperty, "Mouse Wheel Zoom Direction", - "Action to take when the mouse wheel is rolled up.", - "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - props.put(MouseWheelZoomProperty + OptionPropertyEditor.ScopedOptionsProperty, "zoomin zoomout"); - props.put(MouseWheelZoomProperty + ".zoomin", "ZOOM_IN"); - props.put(MouseWheelZoomProperty + ".zoomout", "ZOOM_OUT"); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, MouseWheelListenerProperty, "Mouse Wheel Zoom", - "Setting for whether mouse wheel controls map zoom", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, CursorIDProperty, "Cursor", "Cursor to use for this mouse mode.", - "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, NoMouseWheelListenerTimerProperty, "No Mouse Wheel Listener Timer", - "Setting for whether a timer is used with the mouse wheel controller", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, props, thisClass, MouseWheelTimerIntervalProperty, "Mouse Wheel Timer Interval", - "Setting for the wait interval for the mouse wheel timer", - null); - - StringBuffer cOptions = new StringBuffer(); - Field[] cFields = Cursor.class.getFields(); - for (int i = 0; i < cFields.length; i++) { - Field f = cFields[i]; - - String name = f.getName(); - if (name.endsWith("_CURSOR")) { - String cName = f.getName(); - props.put(CursorIDProperty + "." + cName, cName); - cOptions.append(" ").append(cName); - } - } - - props.put(CursorIDProperty + OptionPropertyEditor.ScopedOptionsProperty, cOptions.toString().trim()); - - return props; - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - propertyChangeSupport.addPropertyChangeListener(listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - propertyChangeSupport.removePropertyChangeListener(listener); - } - - /** - * PaintListener interface, notifying the MouseMode that the MapBean has - * repainted itself. Useful if the MouseMode is drawing stuff. - */ - public void listenerPaint(Object source, Graphics g) { - } - - - public void setNoMouseWheelListener(boolean val) { - noMouseWheelListenerTimer = val; - } - - /** - * - */ - public boolean getNoMouseWheelListener() { - return noMouseWheelListenerTimer; - } - - /** - * The wait interval before a mouse wheel event gets triggered. - */ - protected int mouseWheelTimerInterval = 60; - - /** - * Set the time interval that the mouse timer waits before calling - * upateMouseMoved. A negative number or zero will disable the timer. - */ - public void setMouseWheelTimerInterval(int interval) { - mouseWheelTimerInterval = interval; - if (mouseTimer != null) { - mouseTimer.setInitialDelay(mouseWheelTimerInterval); - } - } - - public int getMouseWheelTimerInterval() { - return mouseWheelTimerInterval; - } - - /** - * The timer used to track the wait interval. - */ - protected Timer mouseTimer = null; - - /** - * The timer listener that calls updateMouseMoved. - */ - protected MouseWheelTimerListener mouseWheelTimerListener = new MouseWheelTimerListener(); - - /** - * The definition of the listener that calls updateMouseMoved when the timer - * goes off. - */ - protected class MouseWheelTimerListener - implements ActionListener { - - float newScale = 0f; - MapBean mapBean; - - public synchronized void addAmount(MapBean map, float amount) { - mapBean = map; - - if (newScale == 0f) { - newScale = map.getScale() * amount; - } else { - newScale *= amount; - } - } - - public synchronized void actionPerformed(ActionEvent ae) { - if (newScale != 0f) { - updateMouseWheelMoved(mapBean, newScale); - newScale = 0f; - } - } - } - - public boolean isNoMouseWheelListenerTimer() { - return noMouseWheelListenerTimer; - } - - public void setNoMouseWheelListenerTimer(boolean noMouseWheelListenerTimer) { - this.noMouseWheelListenerTimer = noMouseWheelListenerTimer; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/AzimuthPanner.java b/src/core/src/main/java/com/bbn/openmap/event/AzimuthPanner.java deleted file mode 100644 index 7d6ae9700..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/AzimuthPanner.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.event; - -import java.awt.Graphics; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.net.URL; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; - -/** - * AzPanner is an abstract class that handles panning effects for Azimuth - * projections. - * - * @author dietrick - */ -public abstract class AzimuthPanner { - OMGraphicList omGraphics; - int oX, oY; - DrawingAttributes azDrawing; - - private AzimuthPanner(int oX, int oY, DrawingAttributes azDrawing) { - this.oX = oX; - this.oY = oY; - this.azDrawing = azDrawing; - } - - public abstract void handlePan(MapBean map, MouseEvent me); - - public abstract void handleUnpan(MouseEvent me); - - public void render(Graphics g) { - if (omGraphics != null) { - omGraphics.render(g); - } - } - - /** - * @return the azDrawing - */ - public DrawingAttributes getAzDrawing() { - return azDrawing; - } - - /** - * @param azDrawing the azDrawing to set - */ - public void setAzDrawing(DrawingAttributes azDrawing) { - this.azDrawing = azDrawing; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.PaintListener#listenerPaint(Object source, - * java.awt.Graphics) - */ - public void listenerPaint(Object source, Graphics graphics) { - if (omGraphics != null) { - omGraphics.render(graphics); - } - } - - public static class Standard extends AzimuthPanner { - - public Standard(int oX, int oY, DrawingAttributes azDrawing) { - super(oX, oY, azDrawing); - } - - public void handlePan(MapBean mapBean, MouseEvent me) { - - Point2D pnt0 = mapBean.inverse(oX, oY, null); - Point2D llp = mapBean.inverse(me.getX(), me.getY(), null); - - if (llp != null && !llp.equals(pnt0)) { - OMGraphicList list = new OMGraphicList(); - OMLine line1 = new OMLine(89.9, llp.getX(), llp.getY(), llp.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - OMLine line2 = new OMLine(llp.getY(), llp.getX(), -89.9, llp.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - list.add(line1); - list.add(line2); - if (llp.getX() < 0) { - OMLine line3 = new OMLine(llp.getY(), -180, llp.getY(), llp.getX(), OMGraphic.LINETYPE_RHUMB); - OMLine line4 = new OMLine(llp.getY(), llp.getX(), llp.getY(), 0, OMGraphic.LINETYPE_RHUMB); - OMLine line5 = new OMLine(llp.getY(), 0, llp.getY(), 179.9, OMGraphic.LINETYPE_RHUMB); - list.add(line3); - list.add(line4); - list.add(line5); - } else { - OMLine line3 = new OMLine(llp.getY(), 0, llp.getY(), llp.getX(), OMGraphic.LINETYPE_RHUMB); - OMLine line4 = new OMLine(llp.getY(), llp.getX(), llp.getY(), 180, OMGraphic.LINETYPE_RHUMB); - OMLine line5 = new OMLine(llp.getY(), -179, llp.getY(), 0, OMGraphic.LINETYPE_RHUMB); - list.add(line3); - list.add(line4); - list.add(line5); - } - - OMLine line6 = new OMLine(pnt0.getY(), pnt0.getX(), llp.getY(), llp.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - line6.addArrowHead(true); - list.add(line6); - - getAzDrawing().setTo(list); - omGraphics = list; - - list.generate(mapBean.getRotatedProjection()); - - mapBean.repaint(); - } - } - - public void handleUnpan(MouseEvent me) { - omGraphics = null; - } - - } - - public static class Shapefile extends Standard { - EsriGraphicList list = null; - - public Shapefile(int oX, int oY, DrawingAttributes azDrawing, URL shapefile) { - super(oX, oY, azDrawing); - list = EsriGraphicList.getEsriGraphicList(shapefile, getAzDrawing(), null); - } - - public void handlePan(MapBean mapBean, MouseEvent me) { - - Projection proj = mapBean.getRotatedProjection(); - Point2D pnt0 = mapBean.inverse(oX, oY, null); - Point2D pnt = mapBean.inverse(me.getX(), me.getY(), null); - - Geo g0 = new Geo(pnt0.getY(), pnt0.getX()); - Geo g = new Geo(pnt.getY(), pnt.getX()); - - double distance = g0.distance(g); - double az = g.azimuth(g0); - - Point2D c = proj.getCenter(); - Geo ngc = new Geo(c.getY(), c.getX()).offset(distance, az); - - Proj newProj = (Proj) mapBean.getProjectionFactory().makeProjection(proj.getClass().getName(), proj); - newProj.setRotationAngle(proj.getRotationAngle()); - newProj.setCenter(ngc.getLatitude(), ngc.getLongitude()); - - if (list != null) { - OMGraphicList newList = new OMGraphicList(list); - newList.generate(newProj); - omGraphics = newList; - mapBean.repaint(); - } - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/BasicLayerConfigurationListener.java b/src/core/src/main/java/com/bbn/openmap/event/BasicLayerConfigurationListener.java deleted file mode 100644 index e31956243..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/BasicLayerConfigurationListener.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.event; - -import java.util.List; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.layer.rpf.RpfLayer; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; - -/** - * A LayerToggleConfigurationListener is a LayerConfigurationListener - * implementation that demonstrates how to create a component that might make - * adjustments to a List of layers being changed in a LayerHandler, before the - * changes hit the map. Right now, the only this component does is change the - * current projection to CADRG if an RPF layer is made active. - * - * You can add this component to the components property in the - * openmap.properties file, or simply add it to the MapHandler. The LayerHandler - * will find it and add it as a listener, and then start making calls to the - * checkLayerConfiguration method. - * - * If you want to adjust the visibility of layers, so that layers turn off or on - * based on other layers being activated, you can just set the visibility of the - * layer in this method without returning anything from the - * checkLayerConfiguration method. You only have to return a new List if you - * want to change the order, add or remove layers from the application. - * - * @author dietrick - */ -public class BasicLayerConfigurationListener extends OMComponent implements - LayerConfigurationListener { - - public BasicLayerConfigurationListener() { - } - - /* - * (non-Javadoc) - * - * @see java.beans.VetoableChangeListener#vetoableChange(java.beans. - * PropertyChangeEvent) - */ - public List checkLayerConfiguration(List layers) { - // Let's say, whenever an RpfLayer is made active, I want to change the - // projection on the map to the CADRG projection. - for (Layer layer : layers) { - if (layer instanceof RpfLayer && layer.isVisible()) { - MapBean mapBean = ((MapHandler) getBeanContext()).get(com.bbn.openmap.MapBean.class); - if (mapBean != null) { - Projection proj = mapBean.getProjection(); - if (!(proj instanceof CADRG)) { - ProjectionFactory pFactory = mapBean.getProjectionFactory(); - if (pFactory != null) { - Projection newProj = pFactory.makeProjection("com.bbn.openmap.proj.CADRG", proj); - if (newProj != null) { - mapBean.setProjection(newProj); - } - } - } - } - } - } - - return null; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/CenterEvent.java b/src/core/src/main/java/com/bbn/openmap/event/CenterEvent.java deleted file mode 100644 index 322c0336c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/CenterEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/CenterEvent.java,v $ -// $RCSfile: CenterEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * An event to request the map should recenter to a new latitude and - * longitude. - */ -public class CenterEvent extends java.util.EventObject { - - private transient double latitude; - private transient double longitude; - - /** - * Construct a CenterEvent. - * - * @param source the source bean - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - */ - public CenterEvent(Object source, double lat, double lon) { - super(source); - latitude = lat; - longitude = lon; - } - - /** - * Get the latitude of the center. - * - * @return float latitude in decimal degrees - */ - public double getLatitude() { - return latitude; - } - - /** - * Get the latitude of the center. - * - * @return float latitude in decimal degrees - */ - public double getLongitude() { - return longitude; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/CenterListener.java b/src/core/src/main/java/com/bbn/openmap/event/CenterListener.java deleted file mode 100644 index f510d9d34..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/CenterListener.java +++ /dev/null @@ -1,30 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/CenterListener.java,v $ -// $RCSfile: CenterListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for requests to recenter the map. - */ -public interface CenterListener extends java.util.EventListener { - public void center(CenterEvent evt); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/CenterSupport.java b/src/core/src/main/java/com/bbn/openmap/event/CenterSupport.java deleted file mode 100644 index a7ac1aa07..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/CenterSupport.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/CenterSupport.java,v $ -// $RCSfile: CenterSupport.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - - -/** - * This is a utility class that can be used by beans that need support - * for handling CenterListeners and firing CenterEvents You can use an - * instance of this class as a member field of your bean and delegate - * work to it. - *

- * A center event is one that sets the center of a map by specifying - * latitude and longitude. - */ -public class CenterSupport extends ListenerSupport { - - /** - * @param sourceBean The bean to be given as the source for any - * events - */ - public CenterSupport(Object sourceBean) { - super(sourceBean); - } - - /** - * Send a center event to all registered listeners. - * - * @param latitude the latitude - * @param longitude the longitude - * @see CenterEvent - */ - public synchronized void fireCenter(double latitude, double longitude) { - if (size() == 0) - return; - - CenterEvent evt = new CenterEvent(source, latitude, longitude); - - for (CenterListener listener : this) { - listener.center(evt); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/event/CoordMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/CoordMouseMode.java deleted file mode 100644 index 150126b8d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/CoordMouseMode.java +++ /dev/null @@ -1,292 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/CoordMouseMode.java,v $ -// $RCSfile: CoordMouseMode.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/10/10 00:57:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.coordFormatter.BasicCoordInfoFormatter; -import com.bbn.openmap.util.coordFormatter.CoordInfoFormatter; -import com.bbn.openmap.util.coordFormatter.CoordInfoFormatterHandler; - -/** - * The CoordMouseMode is an abstract MouseMode extension to AbstractMouseMode - * that can be used for Modes that want to use the BeanContext to hook up with - * the InformationDelegator, and to send coordinate updates to be displayed in - * the infoline. - *

- * - * The CoordMouseMode has been updated to use CoordInfoFormatters to allow more - * flexibility in how coordinates are displayed in the InformationDelegator. You - * can use the 'coordFormatter' property to set a particular CoordInfoFormatter - * for this mouse mode. If you add a CoordInfoFormatterHandler to the - * MapHandler, the mouse mode will use whatever formatter is active in that - * CoordInfoFormatterHandler instead of what's specified in the properties. - */ -public abstract class CoordMouseMode extends AbstractMouseMode implements - PropertyChangeListener { - - /** - * The info delegator that will display the distance information - */ - public InformationDelegator infoDelegator = null; - - /** - * 'coordFormatter' property for setting the class of the coordinate - * formatter. - */ - public final static String CoordFormatterProperty = "coordFormatter"; - - protected CoordInfoFormatter coordFormatter = new BasicCoordInfoFormatter(); - protected CoordInfoFormatterHandler coordFormatterHandler = null; - - public CoordMouseMode() {} - - /** - * @param modeID the id for the mouse mode. - * @param shouldConsumeEvents the mode setting, where the mousemode should - * pass the events on to other listeners or not, depending if one of - * the listeners used it or not. - */ - public CoordMouseMode(String modeID, boolean shouldConsumeEvents) { - super(modeID, shouldConsumeEvents); - } - - /** - * Set the information delegator. - * - * @param id the information delegator that displays the distance values. - */ - public void setInfoDelegator(InformationDelegator id) { - infoDelegator = id; - } - - /** - * Return the information delegator. - */ - public InformationDelegator getInfoDelegator() { - return infoDelegator; - } - - /** - * Fires a mouse location to the InformationDelegator, and then calls the - * super class method which calls the MouseSupport method. - * - * @param e MouseEvent to be handled - */ - public void mouseMoved(MouseEvent e) { - fireMouseLocation(e); - super.mouseMoved(e); - } - - /** - * Fires a mouse location to the InformationDelegator, and then calls the - * super class method which calls the MouseSupport method. - * - * @param e mouse event. - */ - public void mouseDragged(MouseEvent e) { - fireMouseLocation(e); - super.mouseDragged(e); - } - - /** - * If the MouseMode has been made inactive, clean out any input that might - * have been made to the info line. - */ - public void setActive(boolean active) { - if (Debug.debugging("mousemode")) { - Debug.output("CoordMouseMode(" + getPrettyName() - + "): made active (" + active + ")"); - } - if (!active && infoDelegator != null) { - infoDelegator.requestInfoLine(new InfoDisplayEvent(this, "", InformationDelegator.COORDINATE_INFO_LINE)); - } - } - - /** - * Sends the mouse event location, x/y and lat/lon, to the - * InformationDelegator. - */ - public void fireMouseLocation(MouseEvent e) { - int x = e.getX(); - int y = e.getY(); - Point2D llp = null; - Debug.message("mousemodedetail", - "CoordMouseMode: firing mouse location"); - - if (infoDelegator != null) { - if (e.getSource() instanceof MapBean) { - llp = ((MapBean) e.getSource()).getCoordinates(e); - } - String infoLine; - infoLine = coordFormatter.createCoordinateInformationLine(x, - y, - llp, - this); - - // setup the info event - InfoDisplayEvent info = new InfoDisplayEvent(this, infoLine, InformationDelegator.COORDINATE_INFO_LINE); - // ask the infoDelegator to display the info - infoDelegator.requestInfoLine(info); - } - } - - /** - * Called when a CoordMouseMode is added to a BeanContext, or when another - * object is added to the BeanContext after that. The CoordMouseMode looks - * for an InformationDelegator to use to fire the coordinate updates. If - * another InforationDelegator is added when one is already set, the later - * one will replace the current one. - * - * @param someObj an object being added to the BeanContext. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof InformationDelegator) { - Debug.message("mousemode", - "NavMouseMode: found InformationDelegator"); - setInfoDelegator((InformationDelegator) someObj); - } - - if (someObj instanceof CoordInfoFormatterHandler) { - setCoordFormatterHandler((CoordInfoFormatterHandler) someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when objects have been - * removed from the parent BeanContext. If an InformationDelegator is - * removed from the BeanContext, and it's the same one that is currently - * held, it will be removed. - * - * @param someObj an object being removed from the BeanContext. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof InformationDelegator) { - if (getInfoDelegator() == (InformationDelegator) someObj) { - setInfoDelegator(null); - } - } - - if (someObj instanceof CoordInfoFormatterHandler - && someObj == getCoordFormatterHandler()) { - setCoordFormatterHandler(null); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - String coordFormatterClassString = props.getProperty(realPrefix - + CoordFormatterProperty); - - if (coordFormatterClassString != null) { - Object obj = ComponentFactory.create(coordFormatterClassString, - prefix, - props); - if (obj instanceof CoordInfoFormatter) { - setCoordFormatter((CoordInfoFormatter) obj); - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - /** - * Only act on behalf of coordFormatter if there's no - * CoordInfoFormatterHandler. If there is, that object will take care of - * the formatter's properties. - */ - if (coordFormatter != null && coordFormatterHandler == null) { - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + CoordFormatterProperty, - coordFormatter.getClass().getName()); - coordFormatter.getProperties(props); - } - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - /** - * Only act on behalf of coordFormatter if there's no - * CoordInfoFormatterHandler. If there is, that object will take care of - * the formatter's properties. - */ - if (coordFormatter != null && coordFormatterHandler == null) { - coordFormatter.getPropertyInfo(props); - } - - return props; - } - - public CoordInfoFormatter getCoordFormatter() { - return coordFormatter; - } - - public void setCoordFormatter(CoordInfoFormatter coordFormatter) { - if (coordFormatter == null) { - coordFormatter = new BasicCoordInfoFormatter(); - } - this.coordFormatter = coordFormatter; - } - - public CoordInfoFormatterHandler getCoordFormatterHandler() { - return coordFormatterHandler; - } - - public void setCoordFormatterHandler( - CoordInfoFormatterHandler coordFormatterHandler) { - if (this.coordFormatterHandler != null) { - this.coordFormatterHandler.removePropertyChangeListener(CoordInfoFormatterHandler.FORMATTER_PROPERTY, - this); - } - - this.coordFormatterHandler = coordFormatterHandler; - - if (coordFormatterHandler != null) { - coordFormatterHandler.addPropertyChangeListener(CoordInfoFormatterHandler.FORMATTER_PROPERTY, - this); - } - } - - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - CoordInfoFormatter newFormatter = (CoordInfoFormatter) evt.getNewValue(); - if (propertyName.equals(CoordInfoFormatterHandler.FORMATTER_PROPERTY)) { - setCoordFormatter(newFormatter); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/DefaultOverviewMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/DefaultOverviewMouseMode.java deleted file mode 100644 index 5a3262cd3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/DefaultOverviewMouseMode.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/DefaultOverviewMouseMode.java,v $ -// $RCSfile: DefaultOverviewMouseMode.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.gui.OverviewMapHandler; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * A MouseMode that handles drawing a box, or clicking on a point, but directs - * the updates to the ControlledMapSupport of the overview map handler, instead - * of the overview MapBean, which would have been the normal behavior. - */ -public class DefaultOverviewMouseMode - extends NavMouseMode2 { - - OverviewMapHandler overviewMapHandler; - - /** - * Construct a OverviewMouseMode. Sets the ID of the mode to the modeID, the - * consume mode to true, and the cursor to the crosshair. - */ - public DefaultOverviewMouseMode(OverviewMapHandler omh) { - super(true); - overviewMapHandler = omh; - } - - /** - * Handle a mouseReleased MouseListener event. If there was no drag events, - * or if there was only a small amount of dragging between the occurrence of - * the mousePressed and this event, then recenter the source map. Otherwise - * we get the second corner of the navigation rectangle and try to figure out - * the best scale and location to zoom in to based on that rectangle. - * - * @param e MouseEvent to be handled - */ - public void mouseReleased(MouseEvent e) { - if (Debug.debugging("mousemode")) { - System.out.println(getID() + "|DefaultOverviewMouseMode.mouseReleased()"); - } - Object obj = e.getSource(); - if (!mouseSupport.fireMapMouseReleased(e)) { - - if (!(obj == theMap) || !autoZoom || point1 == null) { - return; - } - - Projection projection = theMap.getProjection(); - - synchronized (this) { - point2 = getRatioPoint(theMap, point1, e.getPoint()); - int dx = Math.abs(point2.x - point1.x); - int dy = Math.abs(point2.y - point1.y); - - // Don't bother redrawing if the rectangle is too small - if ((dx < 5) || (dy < 5)) { - - // If rectangle is too small in both x and y then - // recenter the map - if ((dx < 5) && (dy < 5)) { - Point2D llp = projection.inverse(e.getPoint()); - overviewMapHandler.getControlledMapListeners().setCenter(llp); - } - - theMap.repaint(); - - return; - } - - // Figure out the new scale - Point2D ll1 = projection.inverse(point1); - Point2D ll2 = projection.inverse(point2); - - float deltaDegrees; - int deltaPix; - dx = Math.abs(point2.x - point1.x); - dy = Math.abs(point2.y - point1.y); - - if (dx < dy) { - float dlat = (float) Math.abs(ll1.getY() - ll2.getY()); - deltaDegrees = dlat * 2; - deltaPix = overviewMapHandler.getSourceMap().getProjection().getHeight(); - } else { - float dlon; - float lat1, lon1, lon2; - - // point1 is to the right of point2. switch the - // LatLonPoints so that ll1 is west (left) of ll2. - if (point1.x > point2.x) { - lat1 = (float) ll1.getY(); - lon1 = (float) ll1.getX(); - ll1.setLocation(ll2); - ll2.setLocation(lon1, lat1); - } - - lon1 = (float) ll1.getX(); - lon2 = (float) ll2.getX(); - - // allow for crossing dateline - if (lon1 > lon2) { - dlon = (180f - lon1) + (180f + lon2); - } else { - dlon = lon2 - lon1; - } - - deltaDegrees = dlon * 2; - deltaPix = overviewMapHandler.getSourceMap().getProjection().getWidth(); - } - - if (projection instanceof GeoProj) { - double pixPerDegree = ((GeoProj) projection).getPlanetPixelCircumference() / 360.0; - double newScale = pixPerDegree / (deltaPix / deltaDegrees); - overviewMapHandler.getControlledMapListeners().setScale((float) newScale); - } // else what??? TODO - - // Figure out the center of the rectangle - Point2D center = projection.inverse(point1.x, point1.y); - - // Set the parameters of the projection and then set - // the projection of the map. This way we save having - // the MapBean fire two ProjectionEvents. - - overviewMapHandler.getControlledMapListeners().setCenter(center); - } - - cleanUp(); - } - } - - /** - * Get the projection of the source map and the starting point of - * a box (pt1), look at pt2 to see if it represents the ratio of the - * projection map size. If it doesn't, provide a point that does. - */ - protected Point getRatioPoint(MapBean map, Point pt1, Point pt2) { - return ProjMath.getRatioPoint(overviewMapHandler.getSourceMap().getProjection(), pt1, pt2); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/DistanceMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/DistanceMouseMode.java deleted file mode 100644 index 1e8832a3e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/DistanceMouseMode.java +++ /dev/null @@ -1,760 +0,0 @@ -//Title: DistanceMouseMode. -//Version: 2.0 -//Copyright: -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR -// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR DSTO BE LIABLE FOR -// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT -// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -//Author: R. Wathelet -//Company: Theatre Operations Branch, Defence Science & Technology -//Organisation (DSTO) - -package com.bbn.openmap.event; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.text.DecimalFormat; -import java.util.Properties; -import java.util.Vector; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; - -/** - * This mouse mode draws a rubberband line and circle between each mouse click - * as the mouse is moved and displays the cumulative distance in nautical miles - * (nm), kilometers (km), statute miles (miles) and the azimuth angle in decimal - * degrees from north on the status bar. Several distance segments are allowed. - * To erase (terminate) double click the mouse. - *

- * The mode creates lines and circles, and then calls map.repaint(). As a - * PaintListener to the MapBean, those lines and circles get painted whenever - * the map is painted. - *

- * To use this mouse mode in the OpenMap demo (in setWidgets): create the mouse - * mode, such as - *

- * DistanceMouseMode distMode = new DistanceMouseMode(true, id, - * DistanceMouseMode.DISTANCE_ALL); - *

- * Add the distance mouse mode to the mouse delegator md.addMouseMode(distMode); - *

- * This class can easily be extended, for example to create waypoints for - * objects. - *

- * NOTE: If some lines are not properly erased (because the mouse went outside - * the map for example), just use the redraw from the menu. - *

- * - * You can set the units used for measurements by setting the property: - * - *

- *
- *      prefix.units= &lt name for Length.java (km, miles, meters, nm, all) &gt
- *
- * 
- * - * Note that "all" will display nm, km, and miles. - * - */ -public class DistanceMouseMode extends CoordMouseMode implements PaintListener { - - /** - * Mouse mode identifier, is "Distance". This is returned on getID() - */ - public final static transient String modeID = "Distance"; - public final static String UnitProperty = "units"; - public final static String ShowCircleProperty = "showCircle"; - public final static String ShowAngleProperty = "showAngle"; - public final static String RepaintToCleanProperty = "repaintToClean"; - - public transient DecimalFormat df = new DecimalFormat("0.###"); - - /** - * Special units value for displaying all units ... use only in properties - * file - */ - public final static String AllUnitsPropertyValue = "all"; - - /** - * rPoint1 is the anchor point of a line segment - */ - protected Point2D rPoint1; - /** - * rPoint2 is the new (current) point of a line segment - */ - protected Point2D rPoint2; - /** - * Flag, true if the mouse has already been pressed - */ - protected boolean drawDistanceObjects = false; - /** - * Vector to store all distance segments, first point and last point pairs - */ - protected Vector segments = new Vector(); - /** - * Distance of the current segment - */ - protected double distance = 0; - /** - * The cumulative distance from the first mouse click - */ - protected double totalDistance = 0; - - /** - * The line type to be displayed, see OMGraphic. LINETYPE_GREATCIRCLE, - * LINETYPE_RHUMB, LINETYPE_STRAIGHT default LINETYPE_GREATCIRCLE - */ - int lineType = OMGraphic.LINETYPE_GREATCIRCLE; - - /** - * To display the rubberband circle, default true - */ - boolean displayCircle = true; - - // The unit type, default mile - Length unit = Length.MILE; - - // Flag to display the azimuth angle. Default true - boolean showAngle = true; - /** - * Rendering attributes for lines and circles. - */ - protected DrawingAttributes renderAttributes = DrawingAttributes.getDefaultClone(); - - // The map bean - transient MapBean theMap; - - /** - * Construct a DistanceMouseMode. Default constructor. Sets the ID to the - * modeID, and the consume mode to true. You need to setInfoDelegator, - * setUnit and setLineType if you use this constructor. - */ - public DistanceMouseMode() { - this(true); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - renderAttributes.setLinePaint(Color.GRAY); - renderAttributes.setMattingPaint(Color.LIGHT_GRAY); - renderAttributes.setMatted(true); - } - - /** - * Construct a DistanceMouseMode. Lets you set the consume mode. If the - * events are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. You - * need to setInfoDelegator, setUnit and setLineType if you use this - * constructor. - * - * @param consumeEvents the mode setting. - */ - public DistanceMouseMode(boolean consumeEvents) { - super(modeID, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - } - - /** - * Construct an DistanceMouseMode. For convenience for derived classes. - * - * @param name the ID of the mode. - * @param consumeEvents if true, events are propagated to the first - * MapMouseListener that successfully processes the event, if false, - * events are propagated to all MapMouseListeners. You need to - * setInfoDelegator, setUnit and setLineType if you use this - * constructor. - */ - public DistanceMouseMode(String name, boolean consumeEvents) { - super(name, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - } - - /** - * Construct a DistanceMouseMode. Lets you set the consume mode. If the - * events are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. You - * need to the setLineType if you use this constructor. - * - * @param consumeEvents the mode setting. - * @param id the calling object's info delegator. - * @param units the unit of distance that will be displayed, such as - * Length.NM, Length.KM or Length.MILE. If null, display all of them. - */ - public DistanceMouseMode(boolean consumeEvents, InformationDelegator id, Length units) { - super(modeID, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - infoDelegator = id; - unit = units; - } - - /** - * Construct a DistanceMouseMode. Lets you set the consume mode. If the - * events are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. You - * need to the setLineType if you use this constructor. - * - * @param consumeEvents the mode setting. - * @param id the calling object's info delegator. - * @param units the unit of distance that will be displayed, such as - * Length.NM, Length.KM or Length.MILE. If null, display all of them. - * @param lType the line type that will be displayed such as - * LINETYPE_GREATCIRCLE, LINETYPE_RHUMB, LINETYPE_STRAIGHT - */ - public DistanceMouseMode(boolean consumeEvents, InformationDelegator id, Length units, int lType) { - super(modeID, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - infoDelegator = id; - unit = units; - lineType = lType; - } - - /** - * Construct a DistanceMouseMode. Lets you set the consume mode. If the - * events are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. - * - * @param consumeEvents the mode setting. - * @param id the calling object's info delegator. - */ - public DistanceMouseMode(boolean consumeEvents, InformationDelegator id) { - super(modeID, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - infoDelegator = id; - } - - /** - * Construct a DistanceMouseMode. For convenience for derived classes. Lets - * you set the consume mode. If the events are consumed, then a MouseEvent - * is sent only to the first MapMouseListener that successfully processes - * the event. If they are not consumed, then all of the listeners get a - * chance to act on the event. - * - * @param name the ID of the mode. - * @param consumeEvents the mode setting. - * @param id the calling object's info delegator. - */ - public DistanceMouseMode(String name, boolean consumeEvents, InformationDelegator id) { - super(name, consumeEvents); - // if you really want to change the cursor shape - // setModeCursor(cursor.getPredefinedCursor(cursor.CROSSHAIR_CURSOR)); - infoDelegator = id; - } - - /** - * Process a mouseClicked event. Erase all drawn lines and circles upon a - * double mouse click - * - * @param e mouse event. - */ - public void mouseClicked(MouseEvent e) { - - mouseSupport.fireMapMouseClicked(e); - - if (e.getSource() instanceof MapBean) { - // if double (or more) mouse clicked - if (e.getClickCount() >= 2) { - // end of distance path - drawDistanceObjects = false; - cleanUp(); - ((MapBean) e.getSource()).repaint(); - } - } - } - - /** - * Process a mouse pressed event. Add the mouse location to the segment - * vector. Calculate the cumulative total distance. - * - * @param e mouse event. - */ - public void mousePressed(MouseEvent e) { - mouseSupport.fireMapMousePressed(e); - e.getComponent().requestFocus(); - - if (e.getSource() instanceof MapBean) { - // mouse has now been pressed - drawDistanceObjects = true; - // erase the old circle if any - // eraseCircle(); - - if (theMap == null) { - theMap = (MapBean) e.getSource(); - theMap.addPaintListener(this); - } - - // anchor the new first point of the line - rPoint1 = theMap.getCoordinates(e); - // ensure the second point is not yet set. - rPoint2 = null; - // add the anchor point to the list of line segments - segments.addElement(rPoint1); - // add the distance to the total distance - totalDistance += distance; - - theMap.repaint(); - } - } - - /** - * Get the line and circle ready for the map repaint based on where the - * mouse is, distance and azimuth angle as the mouse moves. Display distance - * and azimuth angle in on the infoDelegator. - * - * @param e mouse event. - */ - public void mouseMoved(MouseEvent e) { - mouseSupport.fireMapMouseMoved(e); - if (e.getSource() instanceof MapBean) { - // only when the mouse has already been pressed - if (drawDistanceObjects && theMap != null) { - double lat1, lat2, long1, long2; - // set the map bean - // theMap = (MapBean) (e.getSource()); - // erase the old line and circle first - // paintRubberband(rPoint1, rPoint2); - // get the current mouse location in latlon - rPoint2 = theMap.getCoordinates(e); - // paint the new line and circle up to the current - // mouse location - // paintRubberband(rPoint1, rPoint2); - theMap.repaint(); - - if (infoDelegator != null) { - Debug.message("mousemodedetail", "DistanceMouseMode: firing mouse location"); - // lat, lon of anchor point - lat1 = rPoint1.getY(); - long1 = rPoint1.getX(); - // lat, lon of current mouse position - lat2 = rPoint2.getY(); - long2 = rPoint2.getX(); - distance = GreatCircle.sphericalDistance(ProjMath.degToRad(lat1), ProjMath.degToRad(long1), ProjMath.degToRad(lat2), ProjMath.degToRad(long2)); - - // calculate azimuth angle dec deg - double azimuth = getSphericalAzimuth(lat1, long1, lat2, long2); - double tmpDistance = totalDistance + distance; - String infoLine = createDistanceInformationLine(rPoint2, tmpDistance, azimuth); - // setup the info event - InfoDisplayEvent info = new InfoDisplayEvent(this, infoLine, InformationDelegator.COORDINATE_INFO_LINE); - // ask the infoDelegator to display the info - infoDelegator.requestInfoLine(info); - } - - } else { - fireMouseLocation(e); - } - } - } - - /** - * Create the contents of the information line, based on user inputs. - * - * @param llp current lat/lon of the mouse - * @param distance current distance in radians - * @param azimuth direction of last line - * @return String to put in information line. - */ - protected String createDistanceInformationLine(Point2D llp, double distance, double azimuth) { - // setup the distance info to be displayed - String unitInfo = null; - // what unit is asked for - if (unit == null) { - unitInfo = df.format(Length.NM.fromRadians((float) distance)) + Length.NM.getAbbr() - + ", " + df.format(Length.KM.fromRadians((float) distance)) - + Length.KM.getAbbr() + ", " - + df.format(Length.MILE.fromRadians((float) distance)) + Length.MILE.getAbbr() - + " "; - } else { - unitInfo = unit.fromRadians((float) distance) + " " + unit.getAbbr(); - } - - // add the mouse lat, lon - StringBuffer infoLine = new StringBuffer(); - infoLine.append("Lat, Lon (").append(df.format(llp.getY())).append(", ").append(df.format(llp.getX())).append("), distance ("); - - // add the units - infoLine.append(unitInfo).append(")"); - // add the azimuth angle if need be - if (showAngle) { - infoLine.append(", angle (").append(df.format(azimuth)).append(")"); - } - return infoLine.toString(); - } - - /** - * Process a mouseExited event. If a line is being drawn (and mouse go off - * the map), it will be erased. The anchor point rPoint1 is kept in case the - * mouse comes back on the screen. Then, a new line will be drawn with the - * original mouse press position. - * - * @param e mouse event. - */ - public void mouseExited(MouseEvent e) { - mouseSupport.fireMapMouseExited(e); - if (e.getSource() instanceof MapBean) { - // Stop the last moving segment and circle from being rendered. - rPoint2 = null; - } - } - - public void setActive(boolean active) { - if (!active) { - cleanUp(); - } - } - - /** - * Called by the MapBean when it repaints, to let the MouseMode know when to - * update itself on the map. PaintListener interface. - */ - public void listenerPaint(Object source, java.awt.Graphics g) { - if (drawDistanceObjects) { - for (int i = 0; i < segments.size() - 1; i++) { - paintLine((LatLonPoint) (segments.elementAt(i)), (LatLonPoint) (segments.elementAt(i + 1)), g); - } - if (rPoint1 != null && rPoint2 != null) { - paintRubberband(rPoint1, rPoint2, g); - } - } - } - - /** - * Draw a rubberband line between two points into the Graphics object. - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - * @param graphics a java.awt.Graphics object to render into. - */ - public void paintLine(Point2D pt1, Point2D pt2, Graphics graphics) { - Graphics2D g = (Graphics2D) graphics; - if (pt1 != null && pt2 != null && theMap != null) { - // the line connecting the segments - OMLine cLine = new OMLine(pt1.getY(), pt1.getX(), pt2.getY(), pt2.getX(), lineType); - renderAttributes.setTo(cLine); - // get the map projection - Projection proj = theMap.getRotatedProjection(); - // prepare the line for rendering - cLine.generate(proj); - // render the line graphic - cLine.render(g); - } - } - - /** - * Draw a rubberband circle between two points - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - * @param graphics a java.awt.Graphics object to render into. - */ - public void paintCircle(Point2D pt1, Point2D pt2, Graphics graphics) { - // do all this only if want to display the rubberband circle - if (displayCircle && theMap != null) { - Graphics2D g = (Graphics2D) graphics; - if (pt1 != null && pt2 != null) { - // first convert degrees to radians - double radphi1 = ProjMath.degToRad(pt1.getY()); - double radlambda0 = ProjMath.degToRad(pt1.getX()); - double radphi = ProjMath.degToRad(pt2.getY()); - double radlambda = ProjMath.degToRad(pt2.getX()); - // calculate the circle radius - double dRad = GreatCircle.sphericalDistance(radphi1, radlambda0, radphi, radlambda); - // convert into decimal degrees - double rad = ProjMath.radToDeg(dRad); - // make the circle - OMCircle circle = new OMCircle(pt1.getY(), pt1.getX(), rad); - renderAttributes.setTo(circle); - // get the map projection - Projection proj = theMap.getRotatedProjection(); - // prepare the circle for rendering - circle.generate(proj); - // render the circle graphic - circle.render(g); - } - } // end if(displayCircle) - } - - /** - * Draw a rubberband line and circle between two points - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - * @param g a java.awt.Graphics object to render into. - */ - public void paintRubberband(Point2D pt1, Point2D pt2, Graphics g) { - paintLine(pt1, pt2, g); - paintCircle(pt1, pt2, g); - } - - /** - * Reset the segments and distances - */ - public void cleanUp() { - // a quick way to clean the vector - segments = new Vector(); - // reset the total distance - totalDistance = 0.0; - distance = 0.0; - - if (theMap != null) { - theMap.removePaintListener(this); - theMap.repaint(); - theMap = null; - } - } - - /** - * Return the distance in the chosen unit between two points (in decimal - * degrees). Based on spherical arc distance between two points. See class - * GreatCircle.java - * - * @param phi1 latitude in decimal degrees of start point - * @param lambda0 longitude in decimal degrees of start point - * @param phi latitude in decimal degrees of end point - * @param lambda longitude in decimal degrees of end point - * @param units the unit of distance, DISTANCE_NM, DISTANCE_KM, - * DISTANCE_MILE or all 3 types DISTANCE_ALL - * @return double distance in chosen unit - */ - public double getGreatCircleDist(double phi1, double lambda0, double phi, double lambda, - int units) { - double dist = 0; - // convert arguments to radians - double radphi1 = ProjMath.degToRad(phi1); - double radlambda0 = ProjMath.degToRad(lambda0); - double radphi = ProjMath.degToRad(phi); - double radlambda = ProjMath.degToRad(lambda); - // get the spherical distance in radians between the two - // points - double distRad = (double) GreatCircle.sphericalDistance(radphi1, radlambda0, radphi, radlambda); - // in the chosen unit - if (units == 0) - dist = distRad * Planet.wgs84_earthEquatorialCircumferenceNMiles / MoreMath.TWO_PI; - if (units == 1) - dist = distRad * Planet.wgs84_earthEquatorialCircumferenceKM / MoreMath.TWO_PI; - if (units == 2) - dist = distRad * Planet.wgs84_earthEquatorialCircumferenceMiles / MoreMath.TWO_PI; - - return dist; - } - - /** - * Return the azimuth angle in decimal degrees from north. Based on - * spherical_azimuth. See class GreatCircle.java - * - * @param phi1 latitude in decimal degrees of start point - * @param lambda0 longitude in decimal degrees of start point - * @param phi latitude in decimal degrees of end point - * @param lambda longitude in decimal degrees of end point - * @return float azimuth angle in degrees - */ - public double getSphericalAzimuth(double phi1, double lambda0, double phi, double lambda) { - // convert arguments to radians - double radphi1 = ProjMath.degToRad(phi1); - double radlambda0 = ProjMath.degToRad(lambda0); - double radphi = ProjMath.degToRad(phi); - double radlambda = ProjMath.degToRad(lambda); - // get the spherical azimuth in radians between the two points - double az = GreatCircle.sphericalAzimuth(radphi1, radlambda0, radphi, radlambda); - return ProjMath.radToDeg(az); - } - - /** - * Set the map bean. - * - * @param aMap a map bean - */ - protected void setMapBean(MapBean aMap) { - theMap = aMap; - } - - /** - * Return the map bean. - */ - protected MapBean getMapBean() { - return theMap; - } - - /** - * Set the unit of distance to be displayed: Length.NM, Length.KM or - * Length.MILE. If null, displays all of them. - */ - public void setUnit(Length units) { - unit = units; - } - - /** - * Return the unit of distance being displayed: Length.NM, Length.KM or - * Length.MILE. If null, displays all of them. - */ - public Length getUnit() { - return unit; - } - - /** - * Switch the display of the azimuth angle on or off. - * - * @param onOff true to display the azimuth angle, false to turn off - */ - public void showAzimuth(boolean onOff) { - showAngle = onOff; - } - - /** - * Whether the display of the azimuth angle on or off. - */ - public boolean getShowAzimuth() { - return showAngle; - } - - /** - * Set the line type to be drawn see also OMGraphic - * - * @param lype either LINETYPE_GREATCIRCLE, LINETYPE_RHUMB, - * LINETYPE_STRAIGHT - */ - public void setLineType(int lype) { - lineType = lype; - } - - /** - * Return the line type either LINETYPE_GREATCIRCLE, LINETYPE_RHUMB, - * LINETYPE_STRAIGHT - */ - public int getLineType() { - return lineType; - } - - /** - * Set the drawing of the rubberband circle on/off. - * - * @param onOff true or false - */ - public void showCircle(boolean onOff) { - displayCircle = onOff; - } - - /** - * Get whether the drawing of the rubberband circle on/off. - */ - public boolean getShowCircle() { - return displayCircle; - } - - public boolean isDisplayCircle() { - return displayCircle; - } - - public void setDisplayCircle(boolean displayCircle) { - this.displayCircle = displayCircle; - } - - public boolean isShowAngle() { - return showAngle; - } - - public void setShowAngle(boolean showAngle) { - this.showAngle = showAngle; - } - - public double getTotalDistance() { - return totalDistance; - } - - public void setTotalDistance(double totalDistance) { - this.totalDistance = totalDistance; - } - - /** - * PropertyConsumer interface method. - */ - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - - renderAttributes.setProperties(prefix, setList); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String name = setList.getProperty(prefix + UnitProperty); - if (name != null) { - Length length = Length.get(name); - if (length != null) { - setUnit(length); - } else if (name.equals(AllUnitsPropertyValue)) { - setUnit(null); - } - } - - showCircle(PropUtils.booleanFromProperties(setList, prefix + ShowCircleProperty, true)); - showAzimuth(PropUtils.booleanFromProperties(setList, prefix + ShowAngleProperty, true)); - } - - /** - * PropertyConsumer interface method. - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - String unitValue = (unit != null ? unit.toString() : AllUnitsPropertyValue); - getList.put(prefix + UnitProperty, unitValue); - getList.put(prefix + ShowCircleProperty, new Boolean(getShowCircle()).toString()); - getList.put(prefix + ShowAngleProperty, new Boolean(getShowAzimuth()).toString()); - - renderAttributes.getProperties(getList); - return getList; - } - - /** - * PropertyConsumer interface method. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - list.put(UnitProperty, "Units to use for measurements, from Length.name possibilities."); - list.put(ShowCircleProperty, "Flag to set whether the range circle is drawn at the end of the line (true/false)."); - list.put(ShowAngleProperty, "Flag to note the azimuth angle of the line in the information line (true/false)."); - - renderAttributes.getPropertyInfo(list); - - list.put(initPropertiesProperty, UnitProperty + " " + ShowCircleProperty + " " - + ShowAngleProperty + " " + DrawingAttributes.linePaintProperty + " " - + DrawingAttributes.mattingPaintProperty + " " + DrawingAttributes.mattedProperty); - return list; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayEvent.java b/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayEvent.java deleted file mode 100644 index e17ef991a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayEvent.java +++ /dev/null @@ -1,125 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/InfoDisplayEvent.java,v $ -// $RCSfile: InfoDisplayEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.Layer; - -/** - * An event to request that information be displayed. - */ -public class InfoDisplayEvent extends java.util.EventObject { - - /** - * The requester may send information along with the event if the - * event represents an information display request from the layer, - * this variable contains the information needed to process the - * event. - */ - protected String information = null; - - /** - * A preferred location index for which info line, if there is - * more than one, should display the requested information. The - * default is 0. - */ - protected int preferredLocation = 0; - - /** - * Construct an InfoDisplayEvent. - * - * @param source Object - */ - public InfoDisplayEvent(Object source) { - this(source, null); - } - - /** - * Construct an InfoDisplayEvent. - * - * @param source Object - * @param info String information - */ - public InfoDisplayEvent(Object source, String info) { - super(source); - information = info; - } - - /** - * Construct an InfoDisplayEvent. - * - * @param source Object - * @param info String information - * @param loc the location index for which info line should - * display the information. - */ - public InfoDisplayEvent(Object source, String info, int loc) { - super(source); - information = info; - preferredLocation = loc; - } - - /** - * Get the associated Layer or null. Returns a Layer, if the Layer - * is the source of the event, otherwise null. - * - * @return Layer or null - */ - public Layer getLayer() { - Object obj = getSource(); - return (obj instanceof Layer) ? (Layer) obj : null; - } - - /** - * Get the information. - * - * @return String information - */ - public String getInformation() { - return information; - } - - /** - * Set the information. - * - * @param info String - */ - public void setInformation(String info) { - information = info; - } - - /** - * Get the preferred location index where the information should - * be displayed. - */ - public int getPreferredLocation() { - return preferredLocation; - } - - /** - * Set the preferred location index where the information should - * be displayed. - */ - public void setPreferredLocation(int pl) { - preferredLocation = pl; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayListener.java b/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayListener.java deleted file mode 100644 index d39f380f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/InfoDisplayListener.java +++ /dev/null @@ -1,79 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/InfoDisplayListener.java,v $ -// $RCSfile: InfoDisplayListener.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for requests to display information. - */ -public interface InfoDisplayListener extends java.util.EventListener { - - /** - * Request to have a URL displayed in a Browser. - * - * @param event InfoDisplayEvent - */ - public void requestURL(InfoDisplayEvent event); - - /** - * Request to have a message displayed in a dialog window. - * - * @param event InfoDisplayEvent - */ - public void requestMessage(InfoDisplayEvent event); - - /** - * Request to have an information line displayed in an application - * status window. - * - * @param event InfoDisplayEvent - */ - public void requestInfoLine(InfoDisplayEvent event); - - /** - * Request that plain text or html text be displayed in a browser. - * - * @param event InfoDisplayEvent - */ - public void requestBrowserContent(InfoDisplayEvent event); - - /** - * Request that the MapBean cursor be set to a certain type. - * - * @param cursor java.awt.Cursor to set over the MapBean. - */ - public void requestCursor(java.awt.Cursor cursor); - - /** - * Request a tool tip be shown. - * - * @param event The InfoDisplayEvent containing the text and - * requestor. - */ - public void requestShowToolTip(InfoDisplayEvent event); - - /** - * Request a tool tip be hidden. - */ - public void requestHideToolTip(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListener.java b/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListener.java deleted file mode 100644 index 712fa1aa2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.event; - -import java.util.List; - -import com.bbn.openmap.Layer; - -/** - * A LayerConfigurationListener is a component that receives LayerEvents from - * the LayerHandler before changes are implemented, so conditions can be - * implemented to the layer list. These conditions may include controlling which - * layers are enabled at the same time, or controlling the projection used when - * certain layers are activated. - * - * You can add this component to the components property in the - * openmap.properties file, or simply add it to the MapHandler. The LayerHandler - * will find it and add it as a listener, and then start making calls to the - * checkLayerConfiguration method. - * - * The LayerConfiguratListener.checkLayerConfiguration(List layers) is called - * before new changes are applied to the layer cake in the application. If - * changes are desired, they should be returned from this method. If no changes - * are required, then null should be returned. You should only return something - * from this method if the layer order is modified, or layers should be added or - * removed from the LayerHandler. If you add or remove layers here, they will - * not be added to the MapHandler. - * - * @author dietrick - */ -public interface LayerConfigurationListener { - /** - * The LayerConfiguratListener.checkLayerConfiguration(List layers) is - * called before new changes are applied to the layer cake in the - * application. If changes are desired, they should be returned from this - * method. If no changes are required, then null should be returned. - * - * @param layers a List of layers - * @return the layers as they should be modified. If you just want to change - * which layers will be visible on the map, you can toggle the - * visibility of the layer directory (setVisible(boolean)), and you - * don't have to return anything. Anything you return will be set as - * the available Layer list in the LayerHandler. Use with care. - */ - List checkLayerConfiguration(List layers); -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListenerSupport.java deleted file mode 100644 index ec29b3331..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerConfigurationListenerSupport.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.event; - -import java.util.List; - -import com.bbn.openmap.Layer; - -/** - * ListenerSupport for the LayerHandler to use for managing LayerConfigurationListeners. - * - * @author dietrick - */ -public class LayerConfigurationListenerSupport extends ListenerSupport { - - /** - * @param sourceBean The bean to be given as the source for any events - */ - public LayerConfigurationListenerSupport(Object sourceBean) { - super(sourceBean); - } - - /** - * Check the list of layers, make changes as required. - * - * @param layerList the list of layers to check. - */ - public synchronized List checkLayerConfiguration(List layerList) { - if (size() == 0) - return null; - - List newList = null; - - for (LayerConfigurationListener listener : this) { - newList = listener.checkLayerConfiguration(layerList); - - // We'll see how this works out. Changes made to the list are passed - // to the next listener. Otherwise we pass the original list. If, at - // the end, newList is null, we don't bother telling the - // LayerHandler about the changes. - if (newList != null) { - layerList = newList; - } - } - - return newList; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerEvent.java b/src/core/src/main/java/com/bbn/openmap/event/LayerEvent.java deleted file mode 100644 index 3c3815231..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerEvent.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/LayerEvent.java,v $ -// $RCSfile: LayerEvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.Layer; - -/** - * An event to request that layers be added, removed, or shuffled - * around. - */ -public class LayerEvent extends java.util.EventObject { - - public transient static final int ADD = 400; - public transient static final int REMOVE = 401; - public transient static final int REPLACE = 402; - public transient static final int ALL = 403; - - private transient Layer[] layers; - private transient int type; - - /** - * Construct a LayerEvent. - * - * @param source Object - * @param type type of LayerEvent - * @param layers Layer[] - */ - public LayerEvent(Object source, int type, Layer[] layers) { - super(source); - this.layers = layers; - this.type = type; - } - - /** - * Get the Layers affected by this event. - * - * @return Layer[] - */ - public Layer[] getLayers() { - return layers; - } - - /** - * Get the type of LayerEvent. - * - * @return int type - */ - public int getType() { - return type; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerListener.java b/src/core/src/main/java/com/bbn/openmap/event/LayerListener.java deleted file mode 100644 index f3bd60c1d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerListener.java +++ /dev/null @@ -1,31 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/LayerListener.java,v $ -// $RCSfile: LayerListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for requests to add, remove, or shuffle layers of the map. - */ -public interface LayerListener extends java.util.EventListener { - public void setLayers(LayerEvent evt); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerStatusEvent.java b/src/core/src/main/java/com/bbn/openmap/event/LayerStatusEvent.java deleted file mode 100644 index 114440081..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerStatusEvent.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/LayerStatusEvent.java,v $ -// $RCSfile: LayerStatusEvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.Layer; - -/** - * An event to describe the computational status of a Layer. - */ -public class LayerStatusEvent extends java.util.EventObject { - - public final static transient int START_WORKING = 8342; - public final static transient int STATUS_UPDATE = 8350; - public final static transient int FINISH_WORKING = 8359; - public final static transient int DISTRESS = 8360; - - protected int status = -1; - - // unused for the time - protected int percentageComplete = -1; - protected int timeRemaining = -1; - - /** - * Construct a LayerStatusEvent with a status. - * - * @param source Source Object - * @param status the working status - * - */ - public LayerStatusEvent(Layer source, int status) { - super(source); - this.status = status; - } - - /** - * Get the status of the layer. - * - * @return int status - */ - public int getStatus() { - return status; - } - - /** - * Get the associated Layer. - * - * @return Layer - */ - public Layer getLayer() { - return (Layer) getSource(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerStatusListener.java b/src/core/src/main/java/com/bbn/openmap/event/LayerStatusListener.java deleted file mode 100644 index e29dbdecd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerStatusListener.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/LayerStatusListener.java,v $ -// $RCSfile: LayerStatusListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for the computational status of layers. - */ -public interface LayerStatusListener extends java.util.EventListener { - - /** - * Update the Layer status. - * - * @param evt LayerStatusEvent - */ - public void updateLayerStatus(LayerStatusEvent evt); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/LayerSupport.java b/src/core/src/main/java/com/bbn/openmap/event/LayerSupport.java deleted file mode 100644 index 6ff153bff..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/LayerSupport.java +++ /dev/null @@ -1,166 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/LayerSupport.java,v $ -// $RCSfile: LayerSupport.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/10/16 19:33:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Layer; - -/** - * This is a utility class that can be used by beans that need support for - * handling LayerListeners and firing LayerEvents. You can use an instance of - * this class as a member field of your bean and delegate work to it. - */ -public class LayerSupport - extends ListenerSupport { - - static Logger logger = Logger.getLogger("com.bbn.openmap.event.LayerSupport"); - protected boolean synchronous = true; - - /** - * Construct a LayerSupport. - * - * @param sourceBean The bean to be given as the source for any events. - */ - public LayerSupport(Object sourceBean) { - super(sourceBean); - logger.fine("LayerSupport created"); - } - - /** - * Send a layer event to all registered listeners. - * - * @param type the event type: one of ADD, REMOVE, REPLACE - * @param layers the list of layers - * @see LayerEvent - */ - public void fireLayer(int type, Layer[] layers) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("calling setLayers on " + size() + " objects"); - } - - if (isEmpty()) - return; - - LayerEvent evt = new LayerEvent(source, type, layers); - for (LayerListener listener : this) { - listener.setLayers(evt); - } - } - - /** - * Used to see if another Thread object needs to be created. - */ - protected Thread t; - /** - * Event information stack. - */ - protected Vector events = new Vector(); - - /** - * Pushed the information onto a Vector stack to get executed by a separate - * thread. Any thread launched is held on to, and if that thread is is null - * or not active, a new thread is kicked off. The dying thread checks the - * Vector stack and fires another event if it can. - * - * @param layerEventType - * @param layers - */ - public synchronized void pushLayerEvent(int layerEventType, Layer[] layers) { - - if (synchronous) { - fireLayer(layerEventType, layers); - } else { - - events.add(new SetLayerRunnable(layerEventType, layers)); - - if (t == null || !t.isAlive()) { - SetLayerRunnable runnable = popLayerEvent(); - if (runnable != null) { - t = new Thread(runnable); - t.start(); - } - } - } - } - - /** - * Return the first event on the stack, may be null if there is nothing to - * do. - */ - public synchronized SetLayerRunnable popLayerEvent() { - try { - return events.remove(0); - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } - } - - /** - * A reusable Runnable used by a thread to notify listeners when layers are - * turned on/off or shuffled. - */ - protected class SetLayerRunnable - implements Runnable { - protected int layerEventType; - protected Layer[] layers; - - public SetLayerRunnable(int let, Layer[] lrs) { - layerEventType = let; - layers = lrs; - } - - public int getEventType() { - return layerEventType; - } - - public Layer[] getLayers() { - return layers; - } - - public void run() { - doIt(getEventType(), getLayers()); - SetLayerRunnable runnable = popLayerEvent(); - while (runnable != null) { - doIt(runnable.getEventType(), runnable.getLayers()); - runnable = popLayerEvent(); - } - } - - public void doIt(int eventType, Layer[] layers) { - logger.fine("firing LayerEvent on LayerListeners"); - fireLayer(eventType, layers); - } - } - - public boolean isSynchronous() { - return synchronous; - } - - public void setSynchronous(boolean synchronous) { - this.synchronous = synchronous; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/event/ListenerSupport.java deleted file mode 100644 index 1cc819d51..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ListenerSupport.java +++ /dev/null @@ -1,154 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ListenerSupport.java,v $ -// $RCSfile: ListenerSupport.java,v $ -// $Revision: 1.6 $ -// $Date: 2008/10/16 19:33:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.ListIterator; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * This is an utility class that can be used by beans that need support for - * handling listeners and firing events. You can use an subclass of this class - * as a member field of your bean and delegate work to it. It handles the work - * for a listener support subclass managing the Vector of listeners. It knows - * nothing about firing events to the listeners. - */ -public class ListenerSupport extends CopyOnWriteArrayList // ArrayList // 2012.06.15 TAW JRE-7999 - implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - protected Object source; - - /** - * Construct a ListenerSupport object. - * - * @param sourceBean The bean to be given as the source for any events. - */ - public ListenerSupport(Object sourceBean) { - setSource(sourceBean); - } - - /** - * Set the source of the events. - */ - protected void setSource(Object src) { - source = src; - } - - /** - * Get the source of the events. - */ - protected Object getSource() { - return source; - } - - /** - * Return an iterator over a clone of the listeners. - */ - public synchronized Iterator iterator() { - ArrayList v = new ArrayList(this); - return v.iterator(); - } - - /** - * Return an ListIterator over a clone of the listeners, initialized to the - * end of the list. - */ - public synchronized ListIterator listIterator() { - ArrayList v = new ArrayList(this); - return v.listIterator(this.size()); - } - - /** - * Write the listeners to a stream. - */ - private void writeObject(ObjectOutputStream s) - throws IOException { - s.defaultWriteObject(); - - for (E e : this) { - if (e instanceof Serializable) { - s.writeObject(e); - } - } - - s.writeObject(null); - } - - /** - * Read the listeners from a stream. - */ - @SuppressWarnings("unchecked") - private void readObject(ObjectInputStream s) - throws ClassNotFoundException, IOException { - - s.defaultReadObject(); - - Object listenerOrNull; - while (null != (listenerOrNull = s.readObject())) { - add((E) listenerOrNull); - } - } - - /** - * Wrapper functions to make the iterator methods' synchronization work. - */ - - public synchronized boolean add(E o) { - return super.add(o); - } - - public synchronized void add(int i, E o) { - super.add(i, o); - } - - public synchronized boolean addAll(int index, Collection c) { - return super.addAll(index, c); - } - - public synchronized void clear() { - super.clear(); - } - - public synchronized E remove(int index) { - return super.remove(index); - } - - public synchronized boolean remove(Object o) { - return super.remove(o); - } - - public synchronized E set(int index, E element) { - return super.set(index, element); - } - - public synchronized int size() { - return super.size(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapBeanKeyListener.java b/src/core/src/main/java/com/bbn/openmap/event/MapBeanKeyListener.java deleted file mode 100644 index 1cd0042de..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapBeanKeyListener.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapBeanKeyListener.java,v -// $ -// $RCSfile: MapBeanKeyListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.OMComponent; - -public class MapBeanKeyListener extends OMComponent implements KeyListener { - - protected MapBean mapBean; - - public MapBeanKeyListener() {} - - public void keyPressed(KeyEvent e) {} - - public void keyReleased(KeyEvent e) {} - - public void keyTyped(KeyEvent e) {} - - public void setMapBean(MapBean map) { - if (mapBean != null) { - mapBean.removeKeyListener(this); - } - - mapBean = map; - - if (mapBean != null) { - ((MapBean) map).addKeyListener(this); - } - } - - public MapBean getMapBean() { - return mapBean; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setMapBean((MapBean) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj == getMapBean()) { - setMapBean(null); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapMouseAdapter.java b/src/core/src/main/java/com/bbn/openmap/event/MapMouseAdapter.java deleted file mode 100644 index a3e6a7945..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapMouseAdapter.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapMouseAdapter.java,v $ -// $RCSfile: MapMouseAdapter.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.MouseEvent; - -/** - * Basic implementation of the MapMouseListener interface provided as - * a convenience. If you extend an object from this adapter, you just - * have to implement the methods that you want to deal with. - */ -public class MapMouseAdapter implements MapMouseListener { - - /** - * Return a list of the modes that are interesting to the - * MapMouseListener. You MUST override this with the modes you're - * interested in. - */ - public String[] getMouseModeServiceList() { - return null; - } - - // Mouse Listener events - //////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mousePressed(MouseEvent e) { - return false; // did not handle the event - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse has been clicked on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseClicked(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) {} - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) {} - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. The listener will receive these events if it - * - * @param e MouseEvent - * @return false - */ - public boolean mouseDragged(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons down). - * - * @param e MouseEvent - * @return false - */ - public boolean mouseMoved(MouseEvent e) { - return false; - } - - /** - * Handle a mouse cursor moving without the button being pressed. - * Another layer has consumed the event. - */ - public void mouseMoved() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapMouseEvent.java b/src/core/src/main/java/com/bbn/openmap/event/MapMouseEvent.java deleted file mode 100644 index e0c3169b7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapMouseEvent.java +++ /dev/null @@ -1,115 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapMouseEvent.java,v $ -// $RCSfile: MapMouseEvent.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Component; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.MapBean; - -/** - * MouseEvent extension and wrapper that provides the additional capability to - * get a lat/lon translation for the x,y location for the MouseEvent if the - * source is a MapBean, and also to get a handle to the MapMouseMode that is - * currently active and distributing the MouseEvents. - */ -public class MapMouseEvent extends MouseEvent { - - protected MapMouseMode mapMouseMode = null; - protected MapBean map = null; - - /** - * Create a MapMouseEvent from a MapMouseMode that is distributing the event - * and the original MouseEvent delivered from a source component, most - * likely a MapBean. - */ - public MapMouseEvent(MapMouseMode mode, MouseEvent me) { - super((Component) me.getSource(), - me.getID(), - me.getWhen(), - me.getModifiers(), - me.getX(), - me.getY(), - me.getClickCount(), - me.isPopupTrigger()); - if (me.getSource() instanceof MapBean) { - map = (MapBean) me.getSource(); - } - mapMouseMode = mode; - } - - /** - * Get the Lat/Lon for the x/y point, in the current projection of the - * MapBean that sent the MouseEvent. Could be null if the MouseEvent did not - * originate from a MapBean. - */ - public Point2D getLatLon() { - if (map != null) { - return map.getCoordinates(this); - } else - return null; - } - - /** - * If the map isn't rotated, this provides the same coordinates as the - * getX() and getY() methods would. If the map is rotated, this method - * provides the projected coordinates of the MouseEvent, i.e. the location - * of the MouseEvent in the non-rotated pixel space of the projection. - * - * @return Point2D coordinates of location of mouse position - */ - public Point2D getProjectedLocation() { - if (map != null) { - return map.getNonRotatedLocation(this); - } else { - return new Point2D.Double(getX(), getY()); - } - } - - /** - * Get the MapMouseMode that sent this event. This is different than the - * source of the Event - the MapMouseMode is simply controlling the - * distribution of the events. May be null if there isn't a MapMouseMode - * delivering the MapMouseMode. - */ - public MapMouseMode getMapMouseMode() { - return mapMouseMode; - } - - /** - * Returns a String representation of this object. - */ - public String paramString() { - return super.paramString() + " " + getLatLon(); - } - - public MapBean getMap() { - return map; - } - - public boolean mapIsRotated() { - return (map != null && map.getRotationAngle() != 0.0); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapMouseListener.java b/src/core/src/main/java/com/bbn/openmap/event/MapMouseListener.java deleted file mode 100644 index d42f46212..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapMouseListener.java +++ /dev/null @@ -1,155 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapMouseListener.java,v $ -// $RCSfile: MapMouseListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.MouseEvent; - -/** - * The MapMouseListener interface is for use by a layer interested in - * getting mouse events when the mouse cursor is over the MapBean. - * These events will be coming from an event delegate object, that - * distributes events based on the current "mouse mode" of the map. - *

- * - * NOTE: It is very important that if a MapMouseListener is being - * implemented for a Layer object, the Layer.getMapMouseListener() - * method be modified for the layer to return the MapMouseListener. - * The layer returns null by default, and this will result in the - * MapMouseListener NEVER receiving events. - * - * @see SelectMouseMode - * @see NavMouseMode - */ -public interface MapMouseListener { - - /** - * Return a list of the modes that are interesting to the - * MapMouseListener. The source MouseEvents will only get sent to - * the MapMouseListener if the mode is set to one that the - * listener is interested in. Layers interested in receiving - * events should register for receiving events in "select" mode: - * - *

-     * return new String[] { SelectMouseMode.modeID };
-     * 
- * - * @return String[] of modeID's - * @see NavMouseMode#modeID - * @see SelectMouseMode#modeID - * @see NullMouseMode#modeID - */ - public String[] getMouseModeServiceList(); - - // Mouse Listener events - //////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e); - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e); - - /** - * Invoked when the mouse has been clicked on a component. The - * listener will receive this event if it successfully processed - * mousePressed(), or if no other listener - * processes the event. If the listener successfully processes - * mouseClicked(), then it will receive the next - * mouseClicked() notifications that have a click - * count greater than one. - *

- * NOTE: We have noticed that this method can sometimes be - * erroneously invoked. It seems to occur when a light-weight AWT - * component (like an internal window or menu) closes (removes - * itself from the window hierarchy). A specific OpenMap example - * is when you make a menu selection when the MenuItem you select - * is above the MapBean canvas. After making the selection, the - * mouseClicked() gets invoked on the MouseDelegator, which passes - * it to the appropriate listeners depending on the MouseMode. The - * best way to avoid this problem is to not implement anything - * crucial in this method. Use a combination of - * mousePressed() and mouseReleased() - * instead. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e); - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e); - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e); - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. The listener will receive these events if it - * successfully processes mousePressed(), or if no other listener - * processes the event. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e); - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e); - - /** - * Handle a mouse cursor moving without the button being pressed. - * This event is intended to tell the listener that there was a - * mouse movement, but that the event was consumed by another - * layer. This will allow a mouse listener to clean up actions - * that might have happened because of another motion event - * response. - */ - public void mouseMoved(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/MapMouseMode.java deleted file mode 100644 index 6aebadc03..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapMouseMode.java +++ /dev/null @@ -1,176 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapMouseMode.java,v $ -// $RCSfile: MapMouseMode.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/12/16 14:14:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Cursor; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelListener; -import java.beans.PropertyChangeListener; - -import javax.swing.Icon; - -/** - * Interface for handling mouse behavior while the mouse is operating over the - * MapBean. A "MouseMode" object exists to interpret the meaning of mouse - * events. For instance, you could have a mode where mouse events (click, - * drag-select) are interpreted as navigation commands, (recenter, - * zoom-and-recenter). There may be other modes depending on how your - * application wants to interpret MouseEvents. - * - * @see AbstractMouseMode - * @see NavMouseMode - * @see SelectMouseMode - * @see NullMouseMode - */ -public interface MapMouseMode - extends MouseListener, MouseMotionListener, MouseWheelListener, PaintListener { - - /** - * Returns the id (MapMouseMode name). This name should be unique for each - * MapMouseMode. - * - * @return String ID - */ - public String getID(); - - /** - * Return a pretty name, suitable for the GUI. - */ - public String getPrettyName(); - - /** - * Gets the mouse cursor recommended for use when this mouse mode is active. - * - * @return Cursor the mouse cursor recommended for use when this mouse mode - * is active. - */ - public Cursor getModeCursor(); - - /** - * Gets the Icon to represent the Mouse Mode in a GUI. - */ - public Icon getGUIIcon(); - - /** - * Add a MapMouseListener to the MouseMode. - * - * @param l the MapMouseListener to add. - */ - public void addMapMouseListener(MapMouseListener l); - - /** - * Remove a MapMouseListener from the MouseMode. - * - * @param l the MapMouseListener to remove. - */ - public void removeMapMouseListener(MapMouseListener l); - - /** - * Remove all MapMouseListeners from the mode. - */ - public void removeAllMapMouseListeners(); - - /** - * Let the MapMouseMode know if it is active or not. Called by the - * MouseDelegator. - * - * @param active true if the MapMouseMode has been made the active one, false - * if it has been set inactive. - */ - public void setActive(boolean active); - - /** - * Lets the MouseDelegator know if the MapMouseMode should be visible in the - * GUI, in order to create certain mouse modes that may be controlled by - * other tools. - */ - public boolean isVisible(); - - /** - * Request to have the MapMouseMode act as a proxy for a MapMouseMode that - * wants to remain hidden. Can be useful for directing events to one object. - * With this call, no events will be forwarded to the proxy's target. - * - * @param mmm the hidden MapMouseMode for this MapMouseMode to send events - * to. - * @return true if the proxy setup (essentially a lock) is successful, false - * if the proxy is already set up for another listener. - */ - public boolean actAsProxyFor(MapMouseMode mmm); - - /** - * Request to have the MapMouseMode act as a proxy for a MapMouseMode that - * wants to remain hidden. Can be useful for directing events to one object. - * - * @param mmm the hidden MapMouseMode for this MapMouseMode to send events - * to. - * @param pdm the proxy distribution mask to use, which lets this proxy - * notify its targets of events. - * @return true if the proxy setup (essentially a lock) is successful, false - * if the proxy is already set up for another listener. - */ - public boolean actAsProxyFor(MapMouseMode mmm, int pdm); - - /** - * Can check if the MapMouseMode is acting as a proxy for a MapMouseMode. - */ - public boolean isProxyFor(MapMouseMode mmm); - - /** - * Release the proxy lock on the MapMouseMode. - */ - public void releaseProxy(); - - /** - * @return the mouse mode being proxied. - */ - public MapMouseMode getProxied(); - - /** - * Set the mask that dictates which events get sent to this support object's - * targets even if the parent mouse mode is acting as a proxy. - * - * @see MapMouseSupport for definitions of mask bits. - */ - public void setProxyDistributionMask(int mask); - - /** - * Get the mask that dictates which events get sent to this support object's - * targets even if the parent mouse mode is acting as a proxy. - * - * @see MapMouseSupport for definitions of mask bits. - */ - public int getProxyDistributionMask(); - - /** - * The MapMouseMode should send out notifications when a proxy is added or - * removed. - * - * @param pcl listener to notify. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl); - - public void removePropertyChangeListener(PropertyChangeListener pcl); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/MapMouseSupport.java b/src/core/src/main/java/com/bbn/openmap/event/MapMouseSupport.java deleted file mode 100644 index 50551739d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/MapMouseSupport.java +++ /dev/null @@ -1,507 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/MapMouseSupport.java,v $ -// $RCSfile: MapMouseSupport.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/10/16 19:33:08 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.event; - -import java.awt.event.MouseEvent; -import java.util.Iterator; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This is a utility class that can be used by beans that need support for handling MapMouseListeners and firing - * MapMouseEvents. You can use an instance of this class as a member field of your bean and delegate work to it. - *

- * You can set the behavior of how MouseEvents are propagated by setting whether to "consume" events. If the MouseMode - * is consuming events, then the event is not propagated further than the first listener to successfully process it. - * Otherwise the event is propagated to all listeners. The default is to consume events. - */ -public class MapMouseSupport - extends ListenerSupport { - - private static final long serialVersionUID = 1L; - - protected final static Logger logger = Logger.getLogger("com.bbn.openmap.event.MapMouseSupport"); - - /** - * The flag that dictates whether the events should be passed to all the listeners or just limited to the first - * listener that can deal with it. The default value is set to true, which means the event will be consumed by the - * first layer that can handle it. - */ - protected boolean consumeEvents = true; - - /** - * The priority MapMouseListener will be guaranteed to receive events that go hand in hand (pressed - released, - * etc.). - */ - protected MapMouseListener priorityListener = null; - - /** - * Used to determine whether a release should reset the priorityListener on a mouse release. - */ - protected boolean clickHappened = false; - - /** - * A MapMouseMode that may be using the parent of this support object as a proxy. - */ - protected transient MapMouseMode proxy = null; - - protected transient int proxyDistributionMask = 0; - - public final static int PROXY_DISTRIB_MOUSE_PRESSED = 1 << 0; - public final static int PROXY_ACK_CONSUMED_MOUSE_PRESSED = 1 << 1; - public final static int PROXY_DISTRIB_MOUSE_RELEASED = 1 << 2; - public final static int PROXY_ACK_CONSUMED_MOUSE_RELEASED = 1 << 3; - public final static int PROXY_DISTRIB_MOUSE_CLICKED = 1 << 4; - public final static int PROXY_ACK_CONSUMED_MOUSE_CLICKED = 1 << 5; - public final static int PROXY_DISTRIB_MOUSE_MOVED = 1 << 6; - public final static int PROXY_ACK_CONSUMED_MOUSE_MOVED = 1 << 7; - public final static int PROXY_DISTRIB_MOUSE_DRAGGED = 1 << 8; - public final static int PROXY_ACK_CONSUMED_MOUSE_DRAGGED = 1 << 9; - public final static int PROXY_DISTRIB_MOUSE_ENTERED = 1 << 10; - public final static int PROXY_DISTRIB_MOUSE_EXITED = 1 << 11; - - protected boolean DEBUG = false; - protected boolean DEBUG_DETAIL = false; - - /** - * Construct a default MapMouseSupport. The default value of consumeEvents is set to true. - */ - public MapMouseSupport() { - this(null, true); - } - - /** - * Construct a default MapMouseSupport. The default value of consumeEvents is set to true. - * - * @param mode the parent MapMouseMode to use with creating the MapMouseEvent. - */ - public MapMouseSupport(MapMouseMode mode) { - this(mode, true); - } - - /** - * Construct a MapMouseSupport. - * - * @param shouldConsumeEvents if true, events are propagated to the first MapMouseListener that successfully - * processes the event, if false, events are propagated to all MapMouseListeners - */ - public MapMouseSupport(boolean shouldConsumeEvents) { - this(null, shouldConsumeEvents); - } - - /** - * Construct a MapMouseSupport. - * - * @param mode the parent MapMouseMode to use with creating the MapMouseEvent. - * @param shouldConsumeEvents if true, events are propagated to the first MapMouseListener that successfully - * processes the event, if false, events are propagated to all MapMouseListeners - */ - public MapMouseSupport(MapMouseMode mode, boolean shouldConsumeEvents) { - super(mode); - - consumeEvents = shouldConsumeEvents; - DEBUG = logger.isLoggable(Level.FINE); - DEBUG_DETAIL = logger.isLoggable(Level.FINER); - } - - /** - * Set the parent MapMouseMode to use in constructing MapMouseEvents. - * - * @param mode MapMouseMode parent mode this class is supporting. - */ - public void setParentMode(MapMouseMode mode) { - setSource(mode); - } - - public MapMouseMode getParentMode() { - return (MapMouseMode) getSource(); - } - - /** - * Sets how the mouse support passes out events. If the value passed in is true, the mouse support will only pass - * the event to the first listener that can respond to the event. If false, the mouse support will pass the event on - * to all its listeners. - * - * @param shouldConsumeEvents true for limited distribution. - */ - public void setConsumeEvents(boolean shouldConsumeEvents) { - consumeEvents = shouldConsumeEvents; - } - - /** - * Returns how the mouse support is set up to distribute events. - * - * @return true if only one listener gets to act on an event. - */ - public boolean isConsumeEvents() { - return consumeEvents; - } - - /** - * Handle a mousePressed MouseListener event. - * - * @param evt MouseEvent to be handled. - * @return true if event consumed. - */ - public boolean fireMapMousePressed(MouseEvent evt) { - if (DEBUG) { - logger.fine("MapMouseSupport.fireMapMousePressed()"); - } - - boolean consumed = false; - - if (DEBUG) { - logger.fine(" -- has proxy (" + (proxy != null) + ") -- shift used (" + evt.isShiftDown() + ")"); - } - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_PRESSED) > 0) { - - evt = new MapMouseEvent(getParentMode(), evt); - - if (DEBUG && proxy != null && evt.isShiftDown()) { - logger.fine( - "MMS.fireMapMousePressed(): proxy enabled, but side stepping to send event to primary listeners"); - } - - Iterator it = iterator(); - while (it.hasNext() && !consumed) { - MapMouseListener target = it.next(); - consumed = target.mousePressed(evt) && consumeEvents; - - if (consumed) { - priorityListener = target; - } - } - } - - boolean ignoreConsumed = !consumed || (consumed && ((proxyDistributionMask & PROXY_ACK_CONSUMED_MOUSE_PRESSED) - == 0)); - - if (proxy != null && ignoreConsumed && !evt.isShiftDown()) { - proxy.mousePressed(evt); - consumed = true; - } else { - if (DEBUG && evt.isShiftDown()) { - logger.fine("MMS.fireMapMousePressed(): side-stepped proxy"); - } - } - - return consumed; - } - - /** - * Handle a mouseReleased MouseListener event. Checks to see if there is a priorityListener, and will direct the - * event to that listener. The priorityListener variable will be reset to null. If there is not a priorityListener, - * the event is passed through the listeners, subject to the consumeEvents mode. - * - * @param evt MouseEvent to be handled. - * @return true if event consumed. - */ - public boolean fireMapMouseReleased(MouseEvent evt) { - if (DEBUG) { - logger.fine("MapMouseSupport: fireMapMouseReleased"); - } - - boolean consumed = false; - - evt = new MapMouseEvent(getParentMode(), evt); - - if (priorityListener != null) { - priorityListener.mouseReleased(evt); - if (!clickHappened) { - priorityListener = null; - } - consumed = true; - } - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_RELEASED) > 0) { - - Iterator it = iterator(); - while (it.hasNext() && !consumed) { - consumed = it.next().mouseReleased(evt) && consumeEvents; - } - } - - boolean ignoreConsumed = !consumed || (consumed && ((proxyDistributionMask & PROXY_ACK_CONSUMED_MOUSE_RELEASED) - == 0)); - - if (proxy != null && ignoreConsumed && !evt.isShiftDown()) { - proxy.mouseReleased(evt); - consumed = true; - } - - return consumed; - } - - /** - * Handle a mouseClicked MouseListener event. If the priorityListener is set, it automatically gets the clicked - * event. If it is not set, the other listeners get a shot at the event according to the consumeEvent mode. - * - * @param evt MouseEvent to be handled. - * @return true if event consumed. - */ - public boolean fireMapMouseClicked(MouseEvent evt) { - if (DEBUG) { - logger.fine("MapMouseSupport: fireMapMouseClicked"); - } - - clickHappened = true; - boolean consumed = false; - - evt = new MapMouseEvent(getParentMode(), evt); - - if (priorityListener != null && evt.getClickCount() > 1) { - priorityListener.mouseClicked(evt); - consumed = true; - } - - priorityListener = null; - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_CLICKED) > 0) { - - Iterator it = iterator(); - - while (it.hasNext() && !consumed) { - MapMouseListener target = it.next(); - consumed = target.mouseClicked(evt) && consumeEvents; - - if (consumed) { - priorityListener = target; - } - } - } - - boolean ignoreConsumed = !consumed || (consumed && ((proxyDistributionMask & PROXY_ACK_CONSUMED_MOUSE_CLICKED) - == 0)); - - if (proxy != null && ignoreConsumed && !evt.isShiftDown()) { - proxy.mouseClicked(evt); - consumed = true; - } - - return consumed; - } - - /** - * Handle a mouseEntered MouseListener event. - * - * @param evt MouseEvent to be handled - * @return true if event consumed. - */ - public boolean fireMapMouseEntered(MouseEvent evt) { - if (DEBUG) { - logger.fine("MapMouseSupport: fireMapMouseEntered"); - } - - boolean consumed = false; - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_ENTERED) > 0) { - - evt = new MapMouseEvent(getParentMode(), evt); - - for (MapMouseListener listener : this) { - listener.mouseEntered(evt); - consumed = true; - } - } - - if (proxy != null && !evt.isShiftDown()) { - proxy.mouseEntered(evt); - consumed = true; - } - - return consumed; - } - - /** - * Handle a mouseExited MouseListener event. - * - * @param evt MouseEvent to be handled - * @return true if event consumed. - */ - public boolean fireMapMouseExited(MouseEvent evt) { - if (DEBUG) { - logger.fine("MapMouseSupport: fireMapMouseExited"); - } - - boolean consumed = false; - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_EXITED) > 0) { - - evt = new MapMouseEvent(getParentMode(), evt); - - for (MapMouseListener listener : this) { - listener.mouseExited(evt); - consumed = true; - } - } - - if (proxy != null && !evt.isShiftDown()) { - proxy.mouseExited(evt); - consumed = true; - } - - return consumed; - } - - /** - * Handle a mouseDragged MouseListener event. - * - * @param evt MouseEvent to be handled - * @return false. - */ - public boolean fireMapMouseDragged(MouseEvent evt) { - if (DEBUG_DETAIL) { - logger.finer("MapMouseSupport: fireMapMouseDragged"); - } - - clickHappened = false; - boolean consumed = false; - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_DRAGGED) > 0) { - - evt = new MapMouseEvent(getParentMode(), evt); - - Iterator it = iterator(); - - while (it.hasNext() && !consumed) { - consumed = it.next().mouseDragged(evt) && consumeEvents; - } - } - - boolean ignoreConsumed = !consumed || (consumed && ((proxyDistributionMask & PROXY_ACK_CONSUMED_MOUSE_DRAGGED) - == 0)); - - if (proxy != null && ignoreConsumed && !evt.isShiftDown()) { - proxy.mouseDragged(evt); - consumed = true; - } - - return consumed; - } - - /** - * Handle a mouseMoved MouseListener event. If the moved event is consumed, the rest of the listeners that didn't - * have a chance to respond get called in the mouse moved method without arguments. - * - * @param evt MouseEvent to be handled - * @return true if the event was consumed. - */ - public boolean fireMapMouseMoved(MouseEvent evt) { - if (DEBUG_DETAIL) { - logger.fine("MapMouseSupport: fireMapMouseMoved"); - } - - boolean consumed = false; - - if (proxy == null || evt.isShiftDown() || (proxyDistributionMask & PROXY_DISTRIB_MOUSE_MOVED) > 0) { - - evt = new MapMouseEvent(getParentMode(), evt); - - Iterator it = iterator(); - - while (it.hasNext()) { - MapMouseListener target = it.next(); - if (consumed) { - target.mouseMoved(); - } else { - consumed = target.mouseMoved(evt); - } - } - } - - // consumed was used above to figure out whether to send - // mouseMoved(evt) or mouseMoved(), now we have to set it - // based on whether the MouseMode should be consuming events. - consumed &= consumeEvents; - - boolean ignoreConsumed = !consumed || (consumed && ((proxyDistributionMask & PROXY_ACK_CONSUMED_MOUSE_MOVED) - == 0)); - - if (proxy != null && ignoreConsumed && !evt.isShiftDown()) { - proxy.mouseMoved(evt); - consumed = true; - } - - return consumed; - } - - /** - * Request to have the parent MapMouseMode act as a proxy for a MapMouseMode that wants to remain hidden. Can be - * useful for directing events to one object. - * - * @param mmm the hidden MapMouseMode for this MapMouseMode to send events to. - * @param pdm the proxy distribution mask to use, which lets this support object notify its targets of events if the - * parent is acting as a proxy. - * @return true if the proxy setup (essentially a lock) is successful, false if the proxy is already set up for - * another listener. - */ - protected synchronized boolean setProxyFor(MapMouseMode mmm, int pdm) { - proxyDistributionMask = pdm; - if (proxy == null || proxy == mmm) { - proxy = mmm; - return true; - } - return false; - } - - /** - * Can check if the MapMouseMode is acting as a proxy for another MapMouseMode. - * - * @param mmm MapMouseMode for proxy check. - * @return true if mmm is proxy for the parent mouse mode. - */ - public synchronized boolean isProxyFor(MapMouseMode mmm) { - return proxy == mmm; - } - - /** - * Release the proxy lock on the MapMouseMode. Resets the proxy distribution mask. - */ - protected synchronized void releaseProxy() { - proxy = null; - proxyDistributionMask = 0; - } - - /** - * @return MapMouseMode being proxied (the hidden MapMouseMode that the parent mode is providing events to). - */ - public synchronized MapMouseMode getProxied() { - return proxy; - } - - /** - * Set the mask that dictates which events get sent to this support object's targets even if the parent mouse mode - * is acting as a proxy. - */ - protected void setProxyDistributionMask(int mask) { - proxyDistributionMask = mask; - } - - /** - * Get the mask that dictates which events get sent to this support object's targets even if the parent mouse mode - * is acting as a proxy. - */ - protected int getProxyDistributionMask() { - return proxyDistributionMask; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode.java deleted file mode 100644 index d7ba19279..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode.java +++ /dev/null @@ -1,451 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/NavMouseMode.java,v $ -// $RCSfile: NavMouseMode.java,v $ -// $Revision: 1.12 $ -// $Date: 2007/02/12 17:36:26 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.event; - -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.Properties; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The Navigation Mouse Mode interprets mouse clicks and mouse drags to recenter - * and rescale the map. The map is centered on the location where a click - * occurs. If a box is drawn by clicking down and dragging the mouse, the map is - * centered on the dot in the center of the box, and the scale is adjusted so - * the screen fills the area designated by the box. - *

- * You MUST add this MouseMode as a ProjectionListener to the MapBean to get it - * to work. If you use a MouseDelegator with the bean, it will take care of that - * for you. - */ -public class NavMouseMode extends CoordMouseMode { - - /** - * Mouse Mode identifier, which is "Navigation". - */ - public final static transient String modeID = "Navigation"; - protected Point point1, point2; - protected boolean autoZoom = false; - MapBean theMap = null; - - /** - * DrawingAttributes to use for drawn rectangle. Fill paint will be used for - * XOR color, line paint will be used for paint color. - */ - protected DrawingAttributes rectAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Construct a NavMouseMode. Sets the ID of the mode to the modeID, the - * consume mode to true, and the cursor to the crosshair. - */ - public NavMouseMode() { - this(true); - rectAttributes.setLinePaint(Color.GRAY); - rectAttributes.setMattingPaint(Color.LIGHT_GRAY); - rectAttributes.setMatted(true); - } - - /** - * Construct a NavMouseMode. Lets you set the consume mode. If the events - * are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. - * - * @param shouldConsumeEvents the mode setting. - */ - public NavMouseMode(boolean shouldConsumeEvents) { - super(modeID, shouldConsumeEvents); - // override the default cursor - setModeCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - rectAttributes.setLinePaint(Color.GRAY); - rectAttributes.setMattingPaint(Color.LIGHT_GRAY); - rectAttributes.setMatted(true); - } - - /** - * Handle a mousePressed MouseListener event. Erases the old navigation - * rectangle if there is one, and then keeps the press point for reference - * later. - * - * @param e MouseEvent to be handled - */ - public void mousePressed(MouseEvent e) { - if (Debug.debugging("mousemode")) { - Debug.output(getID() + "|NavMouseMode.mousePressed()"); - } - e.getComponent().requestFocus(); - - if (!mouseSupport.fireMapMousePressed(e) && e.getSource() instanceof MapBean) { - // set the new first point - point1 = e.getPoint(); - // ensure the second point isn't set. - point2 = null; - autoZoom = true; - } - } - - public void mouseClicked(MouseEvent e) { - Object obj = e.getSource(); - - super.mouseClicked(e); - - if (!(obj instanceof MapBean) || point1 == null) { - return; - } - - MapBean map = (MapBean) obj; - Projection projection = map.getProjection(); - Proj p = (Proj) projection; - - Point2D llp = map.getCoordinates(e); - - boolean shift = e.isShiftDown(); - boolean control = e.isControlDown(); - - if (control) { - if (shift) { - p.setScale(p.getScale() * 2.0f); - } else { - p.setScale(p.getScale() / 2.0f); - } - } - - cleanUp(); - - p.setCenter(llp); - map.setProjection(p); - } - - public void mouseMoved(MouseEvent e) { - super.mouseMoved(e); - if (theMap != null) { - cleanUp(); - } - } - - /** - * Handle a mouseReleased MouseListener event. If there was no drag events, - * or if there was only a small amount of dragging between the occurrence of - * the mousePressed and this event, then recenter the map. Otherwise we get - * the second corner of the navigation rectangle and try to figure out the - * best scale and location to zoom in to based on that rectangle. - * - * @param e MouseEvent to be handled - */ - public void mouseReleased(MouseEvent e) { - if (Debug.debugging("mousemode")) { - Debug.output(getID() + "|NavMouseMode.mouseReleased()"); - } - - if (!mouseSupport.fireMapMouseReleased(e)) { - handleMouseReleased(e); - } - } - - /** - * Override this method to change what happens when the mouse is released. - * - * @param e MouseEvent - */ - protected void handleMouseReleased(MouseEvent e) { - Object obj = e.getSource(); - - MapBean map = (MapBean) theMap; - Point firstPoint = this.point1; - Point secondPoint = this.point2; - - // point2 is always going to be null for a click. - if (!(obj == map) || !autoZoom || firstPoint == null || secondPoint == null) { - return; - } - - Projection projection = map.getProjection(); - Proj p = (Proj) projection; - - synchronized (this) { - - point2 = getRatioPoint((MapBean) e.getSource(), firstPoint, e.getPoint()); - secondPoint = point2; - int dx = Math.abs(secondPoint.x - firstPoint.x); - int dy = Math.abs(secondPoint.y - firstPoint.y); - - // Don't bother redrawing if the rectangle is too small - if ((dx < 5) || (dy < 5)) { - - // If rectangle is too small in both x and y then - // recenter the map - if ((dx < 5) && (dy < 5)) { - Point2D llp = map.getCoordinates(e); - - boolean shift = e.isShiftDown(); - boolean control = e.isControlDown(); - - if (control) { - if (shift) { - p.setScale(p.getScale() * 2.0f); - } else { - p.setScale(p.getScale() / 2.0f); - } - } - - cleanUp(); - - p.setCenter(llp); - map.setProjection(p); - } else { - cleanUp(); - map.repaint(); - } - return; - } - - // Figure out the new scale - float newScale = com.bbn.openmap.proj.ProjMath.getScale(firstPoint, secondPoint, projection); - - // Figure out the center of the rectangle - int centerx = Math.min(firstPoint.x, secondPoint.x) + dx / 2; - int centery = Math.min(firstPoint.y, secondPoint.y) + dy / 2; - Point2D center = map.inverse(centerx, centery, null); - - // Fire events on main map to change view to match rect1 - // Debug.output("point1: " +point1); - // Debug.output("point2: " +point2); - // Debug.output("Centerx: " +centerx + - // " Centery: " + centery); - // Debug.output("New Scale: " + newScale); - // Debug.output("New Center: " +center); - - // Set the parameters of the projection and then set - // the projection of the map. This way we save having - // the MapBean fire two ProjectionEvents. - p.setScale(newScale); - p.setCenter(center); - - cleanUp(); - - map.setProjection(p); - } - } - - /** - * Handle a mouseEntered MouseListener event. The boolean autoZoom is set to - * true, which will make the delegate ask the map to zoom in to a box that - * is drawn. - * - * @param e MouseEvent to be handled - */ - public void mouseEntered(MouseEvent e) { - if (Debug.debugging("mousemodedetail")) { - Debug.output(getID() + "|NavMouseMode.mouseEntered()"); - } - super.mouseEntered(e); - autoZoom = true; - } - - /** - * Handle a mouseExited MouseListener event. The boolean autoZoom is set to - * false, which will cause the delegate to NOT ask the map to zoom in on a - * box. If a box is being drawn, it will be erased. The point1 is kept in - * case the mouse comes back on the screen with the button still down. Then, - * a new box will be drawn with the original mouse press position. - * - * @param e MouseEvent to be handled - */ - public void mouseExited(MouseEvent e) { - if (Debug.debugging("mousemodedetail")) { - Debug.output(getID() + "|NavMouseMode.mouseExited()"); - } - - super.mouseExited(e); - - if (theMap == e.getSource()) { - // don't zoom in, because the mouse is off the window. - autoZoom = false; - // set the second point to null so that a new box will be - // drawn if the mouse comes back, and the box will use the - // old starting point, if the mouse button is still down. - point2 = null; - theMap.repaint(); - - } - } - - // Mouse Motion Listener events - // ///////////////////////////// - /** - * Handle a mouseDragged MouseMotionListener event. A rectangle is drawn - * from the mousePressed point, since I'm assuming that I'm drawing a box to - * zoom the map to. If a previous box was drawn, it is erased. - * - * @param e MouseEvent to be handled - */ - public void mouseDragged(MouseEvent e) { - if (Debug.debugging("mousemodedetail")) { - Debug.output(getID() + "|NavMouseMode.mouseDragged()"); - } - - super.mouseDragged(e); - - Object obj = e.getSource(); - - if (obj instanceof MapBean && theMap == null) { - theMap = (MapBean) obj; - theMap.addPaintListener(this); - } - - MapBean map = this.theMap; - Point firstPoint = this.point1; - - if (map != null) { - if (!autoZoom) { - return; - } - - point2 = getRatioPoint(map, firstPoint, e.getPoint()); - map.repaint(); - } - } - - protected void cleanUp() { - if (theMap != null) { - theMap.removePaintListener(this); - theMap = null; - } - point1 = null; - point2 = null; - } - - /** - * Given a MapBean, which provides the projection, and the starting point of - * a box (pt1), look at pt2 to see if it represents the ratio of the - * projection map size. If it doesn't, provide a point that does. This - * method signature is provided for backwards compatibility. - */ - protected Point getRatioPoint(MapBean map, Point pt1, Point pt2) { - return ProjMath.getRatioPoint(map.getProjection(), pt1, pt2); - } - - /** - * Draws or erases boxes between two screen pixel points. The graphics from - * the map is set to XOR mode, and this method uses two colors to make the - * box disappear if on has been drawn at these coordinates, and the box to - * appear if it hasn't. - * - * @param pt1 one corner of the box to drawn, in window pixel coordinates. - * @param pt2 the opposite corner of the box. - */ - protected void paintRectangle(Graphics g, Point pt1, Point pt2) { - - if (pt1 != null && pt2 != null) { - - int width = Math.abs(pt2.x - pt1.x); - int height = Math.abs(pt2.y - pt1.y); - - if (width == 0) { - width++; - } - if (height == 0) { - height++; - } - - Rectangle2D rect1 = new Rectangle2D.Double(pt1.x < pt2.x ? pt1.x : pt2.x, pt1.y < pt2.y ? pt1.y - : pt2.y, width, height); - Rectangle2D rect2 = new Rectangle2D.Double(pt1.x < pt2.x ? pt1.x + (pt2.x - pt1.x) / 2 - - 1 : pt2.x + (pt1.x - pt2.x) / 2 - 1, pt1.y < pt2.y ? pt1.y + (pt2.y - pt1.y) - / 2 - 1 : pt2.y + (pt1.y - pt2.y) / 2 - 1, 2, 2); - - if (theMap != null) { - rectAttributes.render((Graphics2D) g, theMap.getNonRotatedShape(rect1)); - rectAttributes.render((Graphics2D) g, theMap.getNonRotatedShape(rect2)); - } - - } - } - - /** - * Called by the MapBean when it repaints, to let the MouseMode know when to - * update itself on the map. PaintListener interface. - */ - public void listenerPaint(Object obj, java.awt.Graphics g) { - - if (theMap == null && obj instanceof MapBean) { - ((MapBean) obj).removePaintListener(this); - return; - } - - Graphics2D graphics = (Graphics2D) g.create(); - if (point1 != null && point2 != null) { - paintRectangle(graphics, point1, point2); - } - graphics.dispose(); - } - - public DrawingAttributes getRectAttributes() { - return rectAttributes; - } - - public void setRectAttributes(DrawingAttributes rectAttributes) { - this.rectAttributes = rectAttributes; - } - - /** - * PropertyConsumer interface method. - */ - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - - rectAttributes.setProperties(prefix, setList); - } - - /** - * PropertyConsumer interface method. - */ - public Properties getProperties(Properties getList) { - return rectAttributes.getProperties(getList); - } - - /** - * PropertyConsumer interface method. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - rectAttributes.getPropertyInfo(list); - - list.put(initPropertiesProperty, DrawingAttributes.linePaintProperty + " " - + DrawingAttributes.mattingPaintProperty + " " + DrawingAttributes.mattedProperty); - return list; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode2.java b/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode2.java deleted file mode 100644 index 48fc16bb8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/NavMouseMode2.java +++ /dev/null @@ -1,192 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/NavMouseMode2.java,v $ -// $RCSfile: NavMouseMode2.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/12/18 20:39:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The Navigation Mouse Mode interprets mouse clicks and mouse drags to recenter - * and rescale the map. The map is centered on the location where a click - * occurs. The difference between this MouseMode and the original NavMouseMode - * is that the box drawn is interpreted differently. The point where the mouse - * is pressed is interpreted to be the center of the new zoom area (instead of - * one of the corners), and the dragged mouse point is the edge of the box, - * reflected equally on the other side of the center point. - * - *

- * You MUST add this MouseMode as a ProjectionListener to the MapBean to get it - * to work. If you use a MouseDelegator with the bean, it will take care of that - * for you. - */ -public class NavMouseMode2 extends NavMouseMode { - - /** - * Construct a NavMouseMode2. Sets the ID of the mode to the modeID, the - * consume mode to true, and the cursor to the crosshair. - */ - public NavMouseMode2() { - this(true); - } - - /** - * Construct a NavMouseMode2. Lets you set the consume mode. If the events - * are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. - * - * @param shouldConsumeEvents the mode setting. - */ - public NavMouseMode2(boolean shouldConsumeEvents) { - super(shouldConsumeEvents); - } - - /** - * Handle a mouseReleased MouseListener event. If there was no drag events, - * or if there was only a small amount of dragging between the occurrence of - * the mousePressed and this event, then recenter the map. Otherwise we get - * the second corner of the navigation rectangle and try to figure out the - * best scale and location to zoom in to based on that rectangle. - * - * @param e MouseEvent to be handled - */ - public void handleMouseReleased(MouseEvent e) { - if (Debug.debugging("mousemode")) { - Debug.output(getID() + "|NavMouseMode2.mouseReleased()"); - } - - Object obj = e.getSource(); - - Point firstPoint = this.point1; - Point secondPoint = this.point2; - MapBean map = this.theMap; - - if (!(map == obj) || !autoZoom || firstPoint == null || secondPoint == null) { - return; - } - - Projection projection = map.getProjection(); - Proj p = (Proj) projection; - - synchronized (this) { - point2 = getRatioPoint(map, firstPoint, e.getPoint()); - secondPoint = point2; - - int dx = Math.abs(secondPoint.x - firstPoint.x); - int dy = Math.abs(secondPoint.y - firstPoint.y); - - // Don't bother redrawing if the rectangle is too small - if ((dx < 5) || (dy < 5)) { - - // If rectangle is too small in both x and y then - // re-center the map - if ((dx < 5) && (dy < 5)) { - Point2D llp = map.getCoordinates(e); - - boolean shift = e.isShiftDown(); - boolean control = e.isControlDown(); - - if (control) { - if (shift) { - p.setScale(p.getScale() * 2.0f); - } else { - p.setScale(p.getScale() / 2.0f); - } - } - - cleanUp(); - - p.setCenter(llp); - map.setProjection(p); - } - return; - } - - // Figure out the new scale - dx = Math.abs(secondPoint.x - firstPoint.x); - dy = Math.abs(secondPoint.y - firstPoint.y); - - // cornerPoint 1 should be the upper left. - Point cornerPoint1 = new Point(secondPoint.x < firstPoint.x ? secondPoint.x - : firstPoint.x, secondPoint.y < firstPoint.y ? secondPoint.y : firstPoint.y); - Point cornerPoint2 = new Point(cornerPoint1.x + 2 * dx, cornerPoint1.y + 2 * dy); - - float newScale = com.bbn.openmap.proj.ProjMath.getScale(cornerPoint1, cornerPoint2, projection); - - // Figure out the center of the rectangle - Point2D center = map.inverse(firstPoint.x, firstPoint.y, null); - - // Set the parameters of the projection and then set - // the projection of the map. This way we save having - // the MapBean fire two ProjectionEvents. - p.setScale(newScale); - p.setCenter(center); - cleanUp(); - map.setProjection(p); - } - - } - - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Draws or erases boxes between two screen pixel points. The graphics from - * the map is set to XOR mode, and this method uses two colors to make the - * box disappear if on has been drawn at these coordinates, and the box to - * appear if it hasn't. - * - * @param pt1 one corner of the box to drawn, in window pixel coordinates. - * @param pt2 the opposite corner of the box. - */ - protected void paintRectangle(Graphics g, Point pt1, Point pt2) { - - if (pt1 != null && pt2 != null) { - - int width = Math.abs(pt2.x - pt1.x); - int height = Math.abs(pt2.y - pt1.y); - - if (width == 0) - width++; - if (height == 0) - height++; - - Rectangle2D rect1 = new Rectangle2D.Double(pt1.x - width, pt1.y - height, width * 2, height * 2); - Rectangle2D rect2 = new Rectangle2D.Double(pt1.x - 1, pt1.y - 1, 3, 3); - - if (theMap != null) { - rectAttributes.render((Graphics2D) g, theMap.getNonRotatedShape(rect1)); - rectAttributes.render((Graphics2D) g, theMap.getNonRotatedShape(rect2)); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/NullMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/NullMouseMode.java deleted file mode 100644 index 0d36129c9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/NullMouseMode.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/NullMouseMode.java,v $ -// $RCSfile: NullMouseMode.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * The NullMouseMode takes no action on mouse events and does not keep - * a list of map mouse listeners. It is intended to be used when you - * need a mouse mode that does nothing as an alternative to one that - * does something. If you don't have one that does something you don't - * need any MouseModes at all. - */ -public class NullMouseMode extends AbstractMouseMode { - - /** - * Mouse Mode identifier, which is "None". - */ - public final static transient String modeID = "None"; - - /** - * Construct a NullMouseMode. Default constructor sets the ID to - * the modeID string and the consume events parameter to true. - */ - public NullMouseMode() { - this(modeID, true); - } - - /** - * Construct a NullMouseMode. Constructor that lets you set the - * name and the consume mode. - * - * @param id the ID name. - * @param consumeEvents the consume mode. - */ - public NullMouseMode(String id, boolean consumeEvents) { - super(id, consumeEvents); - } - - /** - * IGNORED. - */ - public void addMapMouseListener(MapMouseListener mml) {} - - /** - * IGNORED. - */ - public void removeMapMouseListener(MapMouseListener mml) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEvent.java b/src/core/src/main/java/com/bbn/openmap/event/OMEvent.java deleted file mode 100644 index 0a8267558..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEvent.java +++ /dev/null @@ -1,239 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/darwars/ambush/aar/src/com/bbn/hotwash/event/AAREvent.java,v $ -// $RCSfile: AAREvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2008/11/10 23:57:53 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Rectangle; -import java.awt.geom.Point2D; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import com.bbn.openmap.util.Attributable; - -/** - * An OMEvent represents an event that occurs at a certain time. The time is - * maintained as an offset from the UNIX epoch marker. - * - * @author dietrick - */ -public class OMEvent implements Attributable { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.event.OMEvent"); - - public final static String ATT_KEY_DETAILED_INFORMATION = "DETAILS"; - public final static String ATT_KEY_SELECTED = "SELECTED"; - public final static String ATT_KEY_PLAY_FILTER = "PLAY_FILTER"; - public final static String ATT_KEY_RATING = "RATING"; - - public final static String ATT_VAL_GOOD_RATING = "+"; - public final static String ATT_VAL_BAD_RATING = "-"; - public final static String ATT_VAL_SELECTED_START_RANGE = "AVSSR"; - public final static String ATT_VAL_SELECTED_END_RANGE = "AVSER"; - public final static String ATT_VAL_SELECTED = "SELECTED"; - - protected String description = ""; - /** Absolute time, milliseconds from the UNIX epoch. */ - protected long timeStamp; - /** - * Value to assist the OMEventComparator to order OMEvents with the same - * timeStamp. - */ - protected short timeStampComparator = 0; - protected boolean sorted = false; - - protected Point2D location; - protected Rectangle range; - protected Object source; - - protected boolean atCurrentTime = false; - protected boolean selected = false; - - protected Map attributes; - - public OMEvent(Object src, String desc, long tStamp) { - this(src, desc, tStamp, null, null); - } - - public OMEvent(Object src, String desc, long tStamp, Point2D loc) { - this(src, desc, tStamp, loc, null); - } - - @SuppressWarnings("unchecked") - public OMEvent(Object src, String desc, long tStamp, Point2D loc, - Rectangle rect) { - description = desc; - timeStamp = tStamp; - location = loc; - range = rect; - source = src; - - if (src instanceof Attributable) { - attributes = ((Attributable) src).getAttributes(); - } - } - - /** - * Assumed to be an offset time (millis) from the initial system time. - */ - public void setTimeStamp(long tStamp) { - timeStamp = tStamp; - } - - public long getTimeStamp() { - return timeStamp; - } - - public void setDescription(String desc) { - description = desc; - } - - public String getDescription() { - return toString(); - } - - public String toString() { - return description; - } - - public void setLocation(Point2D loc) { - location = loc; - } - - public Point2D getLocation() { - return location; - } - - public void setRange(Rectangle rect) { - range = rect; - } - - public Rectangle getRange() { - return range; - } - - public Object getSource() { - return source; - } - - public void setSource(Object src) { - source = src; - } - - public String getDetailedInformation() { - return (String) getAttribute(ATT_KEY_DETAILED_INFORMATION); - } - - public void setDetailedInformation(String di) { - putAttribute(ATT_KEY_DETAILED_INFORMATION, di); - } - - public boolean isAtCurrentTime() { - return atCurrentTime; - } - - public void setAtCurrentTime(boolean atCurrentTime) { - this.atCurrentTime = atCurrentTime; - } - - public boolean isSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } - - /** - * Test whether this event should be displayed, given the provided filter - * list. The filter list are those that are turned on, meaning that things - * contained in the list should be displayed, and should cause this method - * to return true. This method should be overridden by subclasses. If it - * isn't then the event will always be shown. - * - * @param filters - * @return true if this event passes filters - */ - public boolean passesMacroFilters(List filters) { - return true; - } - - public void putAttribute(Object key, Object value) { - if (key == null) { - return; - } - - if (attributes == null) { - attributes = new Hashtable(); - } - - if (value != null) { - attributes.put(key, value); - } else { - attributes.remove(key); - } - } - - public Object getAttribute(Object key) { - Object ret = null; - if (attributes != null && key != null) { - ret = attributes.get(key); - } - return ret; - } - - public void clearAttributes() { - if (attributes != null) { - attributes.clear(); - } - } - - public Map getAttributes() { - return attributes; - } - - /** - * Doesn't set the attribute map on the source, if the source if - * Attributable. Just sets the attribute Map on the OMEvent. - */ - public void setAttributes(Map map) { - attributes = map; - } - - public short getTimeStampComparator() { - return timeStampComparator; - } - - public void setTimeStampComparator(short timeStampComparator) { - this.timeStampComparator = timeStampComparator; - } - - protected boolean isSorted() { - return sorted; - } - - protected void setSorted(boolean sorted) { - this.sorted = sorted; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventComparator.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventComparator.java deleted file mode 100644 index 16d96f2b6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventComparator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - */ -package com.bbn.openmap.event; - -import java.util.Comparator; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.HashCodeUtil; - -/** - */ -public class OMEventComparator - implements Comparator { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.event.OMEventComparator"); - - /** - * - */ - public OMEventComparator() { - super(); - } - - public int compare(OMEvent obj1, OMEvent obj2) { - int ret = 0; - - long ts1 = obj1.getTimeStamp(); - short tsc1 = obj1.getTimeStampComparator(); - - long ts2 = obj2.getTimeStamp(); - short tsc2 = obj2.getTimeStampComparator(); - - // ts1 is the one being tested/added to the TreeSet, so we - // want later items with the same time being added after - // previous items in the file with the same time. - - if (ts1 < ts2) { - ret = -1; - obj1.setSorted(true); - } else if (ts1 > ts2) { - ret = 1; - } else { - - boolean logging = false; - String id1 = null, id2 = null; - - if (logger.isLoggable(Level.FINE)) { - id1 = obj1.getDescription(); - id2 = obj2.getDescription(); - - logging = true; - } - - if (tsc1 == 0) { - tsc1 = tsc2; - if (logging) { - logger.info("new event..." + id1); - } - } else { - obj1.setSorted(true); - } - - if (logging) { - logger.info("comparing [" + id1 + "] at " + tsc1 + " to [" + id2 + "] at " + tsc2); - } - - // Since time stamps are equal, go to the time stamp comparator - // settings. - if (tsc1 < tsc2 && obj1.isSorted()) { - ret = -1; - if (logging) { - logger.info("-----"); - } - } else if (tsc1 > tsc2) { - ret = 1; - if (logging) { - logger.info("+++++"); - } - } else { - // If they have the same setting, the second time stamp - // comparator will get bumped up. If there has already been more - // than one record with the same time, then this should keep - // happening until the last one in has the highest tsc value; - tsc1 = (short) (tsc2 + 1); - obj2.setTimeStampComparator(tsc1); - ret = 1; - if (logging) { - logger.info("^^^^^ " + ts1 + ", upping [" + id1 + "] to " + tsc1 + " over [" + id2 + "]"); - } - } - } - - return ret; - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - return obj.hashCode() == this.hashCode(); - } - - public int hashCode() { - int result = HashCodeUtil.SEED; - result = HashCodeUtil.hash(result, getClass().getName()); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventHandler.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventHandler.java deleted file mode 100644 index a2e7f7d24..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventHandler.java +++ /dev/null @@ -1,78 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionEventHandler.java,v -// $ -// $RCSfile: AAREventHandler.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.util.Collection; -import java.util.List; - -/** - * An OMEventHandler manages OMEvents, creating them from TemporalRecords. - * - * @author dietrick - */ -public interface OMEventHandler { - - List getEventList(); - - /** - * This is the main call to return OMEvents based on filters set in the GUI. - * In subclasses, you can make the call to getMacroFilterList(Collection) - * from here to check against other filters that are being set across all - * OMEventhandlers. - * - * @param filters A List of Strings. If your OMEventHandler provides entries - * into the filterList, you should check the entries on that list - * to see if they are in this provided list. If they are, you - * should return the OMEvents that fall under that filter - * String's jurisdiction. - * @return List of OMEvents that pass filters - */ - List getEventList(List filters); - - List getMacroFilteredList(Collection eventCollection); - - /** - * @return List of Strings that serve as pretty names for the gui, and as - * filters. OK to return null. - */ - List getFilters(); - - /** - * Query to find out if a filter should be enabled, based on EventHandler - * settings and history. - * - * @param filterName the filter string. - * @return Boolean.TRUE for things that should be display, Boolean.FALSE for - * things that shouldn't be displayed, and null for things that - * aren't known about. - */ - Boolean getFilterState(String filterName); - - /** - * @param filterName - * @param state - */ - void setFilterState(String filterName, Boolean state); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventHandlerAdapter.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventHandlerAdapter.java deleted file mode 100644 index 5d5d0e587..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventHandlerAdapter.java +++ /dev/null @@ -1,169 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionEventHandler.java,v -// $ -// $RCSfile: AAREventHandler.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.util.Collection; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.OMComponent; - -/** - * OMEventHandler subclasses look for the things that create OMEvents. - * - * @author dietrick - */ -public abstract class OMEventHandlerAdapter extends OMComponent implements OMEventHandler { - - protected LinkedList events; - protected List filterList; - protected List macroFilters; - protected Hashtable filterStates; - - public final static String ShowEventsAtStartupProperty = "showEvents"; - - public OMEventHandlerAdapter() { - events = new LinkedList(); - filterList = new LinkedList(); - macroFilters = new LinkedList(); - filterStates = new Hashtable(); - } - - public void addEvent(OMEvent me) { - events.add(me); - } - - public void removeEvent(OMEvent me) { - events.remove(me); - } - - public void clearEvents() { - events.clear(); - } - - public List getEventList() { - return getEventList(null); - } - - /** - * This is the main call to return OMEvents based on filters set in the GUI. - * In subclasses, you can make the call to getMacroFilterList(Collection) - * from here to check against other filters that are being set across all - * OMEventhandlers. - * - * @param filters A List of Strings. If your OMEventHandler provides entries - * into the filterList, you should check the entries on that list - * to see if they are in this provided list. If they are, you - * should return the OMEvents that fall under that filter - * String's jurisdiction. - * @return List of OMEvents that past filters - */ - public List getEventList(List filters) { - // At this level, we just want to return all events. Let - // subclasses worry about macro-filtered events... - // return getMacroFilteredList(events); - - return events; - } - - public void addMacroFilter(OMEventMacroFilter mf) { - macroFilters.add(mf); - } - - public void removeMacroFilter(OMEventMacroFilter mf) { - macroFilters.remove(mf); - } - - public void clearMacroFilters() { - macroFilters.clear(); - } - - public List getMacroFilteredList(Collection eventCollection) { - List ret = new LinkedList(); - // If there are no macro filters, return a list with all - // mission events. - ret.addAll(eventCollection); - - if (macroFilters != null) { - for (OMEventMacroFilter mf : macroFilters) { - // Should get whittled down to a list passing macro filters. - ret = mf.getMacroFilteredList(ret); - } - } - - return ret; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof OMEventMacroFilter) { - addMacroFilter((OMEventMacroFilter) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof OMEventMacroFilter) { - removeMacroFilter((OMEventMacroFilter) someObj); - } - } - - /** - * @return List of Strings that serve as pretty names for the gui, and as - * filters. OK to return null. - */ - public List getFilters() { - return filterList; - } - - /** - * Query to find out if a filter should be enabled, based on EventHandler - * settings and history. - * - * @param filterName the filter string. - * @return Boolean.TRUE for things that should be display, Boolean.FALSE for - * things that shouldn't be displayed, and null for things that - * aren't known about. - */ - public Boolean getFilterState(String filterName) { - return (Boolean) filterStates.get(filterName); - } - - /** - * Called by EventListPresenter to reset state. Should only execute if the - * filter state is already known. - * - * @param filterName - * @param state - */ - public void setFilterState(String filterName, Boolean state) { - // We only want to set this if we already know about it, otherwise - // ignore it. This is being called by a presenter, and it doesn't know - // who owns it. So it calls this method on all handlers to catch the - // owner. - if (filterStates.get(filterName) != null) { - filterStates.put(filterName, state); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventMacroFilter.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventMacroFilter.java deleted file mode 100644 index 4fed82c91..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventMacroFilter.java +++ /dev/null @@ -1,45 +0,0 @@ - //********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MacroFilter.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:20 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.event; - -import java.util.List; - -/** - * A macro filter knows how to take a Collection of objects and return a list of - * them that pass its filters. This object is generally created to be used for - * by multiple OMEventHandlers to further filter events based on other - * parameters that the OMEventHandler may not know about. - * - * @author dietrick - */ -public interface OMEventMacroFilter { - /** - * @param listOfEvents a list of events that are currently going to be - * displayed in the GUI. - * @return a filtered list of events that pass the criteria set by this - * filter. - */ - public List getMacroFilteredList(List listOfEvents); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionCoordinator.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionCoordinator.java deleted file mode 100644 index a23b0ca74..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionCoordinator.java +++ /dev/null @@ -1,56 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: AAREventSelectionCoordinator.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.event; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.util.List; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; - -public class OMEventSelectionCoordinator extends OMComponent { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.event.OMEventSelectionCoordinator"); - public final static String EventsSelectedProperty = "eventsSelected"; - - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - public OMEventSelectionCoordinator() { - } - - public void addPropertyChangeListener(PropertyChangeListener pcl) { - pcs.addPropertyChangeListener(EventsSelectedProperty, pcl); - } - - public void removePropertyChangeListener(PropertyChangeListener pcl) { - pcs.removePropertyChangeListener(EventsSelectedProperty, pcl); - } - - public void eventsSelected(List selectedEvents) { - pcs.firePropertyChange(EventsSelectedProperty, null, selectedEvents); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionListener.java b/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionListener.java deleted file mode 100644 index 5c21826d2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMEventSelectionListener.java +++ /dev/null @@ -1,30 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: AAREventSelectionListener.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.event; - - -public interface OMEventSelectionListener { - public void selected(OMEvent omEvent); -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/OMMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/OMMouseMode.java deleted file mode 100644 index 605982c31..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OMMouseMode.java +++ /dev/null @@ -1,428 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import javax.swing.ImageIcon; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.image.ImageScaler; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.proj.Cartesian; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * OMMouseMode is a combination of the PanMouseMode, NavMouseMode and - * SelectMouseMode. Press and drag to pan. Double click to re-center, CTRL - * double click to re-center and zoom. Shift-CTRL-Double click to center and - * zoom out. Double click to select OMGraphics. Right click for pop-up menu. - */ -public class OMMouseMode extends CoordMouseMode { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public final static String OPAQUENESS_PROPERTY = "opaqueness"; - public final static String LEAVE_SHADOW_PROPERTY = "leaveShadow"; - public final static String USE_CURSOR_PROPERTY = "useCursor"; - public final static String AZ_PANNING_SHAPEFILE_PROPERTY = "azPanningShapefile"; - public final static String AZ_PANNING_PROPERTY = "azPanning"; - public final static float DEFAULT_OPAQUENESS = 1.0f; - - public final static transient String modeID = "Gestures"; - - private boolean isPanning = false; - private int oX, oY; - private float opaqueness = DEFAULT_OPAQUENESS; - private boolean leaveShadow = false; - private boolean useCursor; - private AzimuthPanner azPanner = null; - private String azPanningShapefile = null; - private DrawingAttributes azDrawing = null; - - /** - * rPoint1 is the anchor point of a line segment - */ - public Point2D rPoint1; - /** - * rPoint2 is the new (current) point of a line segment - */ - public Point2D rPoint2; - - protected BufferedMapBean theMap = null; - protected String coordString = null; - - public OMMouseMode() { - super(modeID, true); - setUseCursor(false); - setLeaveShadow(true); - setOpaqueness(DEFAULT_OPAQUENESS); - - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setMatted(true); - da.setMattingPaint(Color.LIGHT_GRAY); - - setAzDrawing(da); - } - - /** - * @return Returns the useCursor. - */ - public boolean isUseCursor() { - return useCursor; - } - - /** - * @param useCursor The useCursor to set. - */ - public void setUseCursor(boolean useCursor) { - this.useCursor = useCursor; - if (useCursor) { - /* - * For who like make his CustomCursor - */ - try { - Toolkit tk = Toolkit.getDefaultToolkit(); - ImageIcon pointer = new ImageIcon(getClass().getResource("Gestures.gif")); - Dimension bestSize = tk.getBestCursorSize(pointer.getIconWidth(), pointer.getIconHeight()); - Image pointerImage = ImageScaler.getOptimalScalingImage(pointer.getImage(), (int) bestSize.getWidth(), (int) bestSize.getHeight()); - Cursor cursor = tk.createCustomCursor(pointerImage, new Point(0, 0), "PP"); - setModeCursor(cursor); - return; - } catch (Exception e) { - // Problem finding image probably, just move on. - } - } - - setModeCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - opaqueness = PropUtils.floatFromProperties(props, prefix + OPAQUENESS_PROPERTY, opaqueness); - leaveShadow = PropUtils.booleanFromProperties(props, prefix + LEAVE_SHADOW_PROPERTY, leaveShadow); - azPanningShapefile = props.getProperty(prefix + AZ_PANNING_SHAPEFILE_PROPERTY, azPanningShapefile); - setUseCursor(PropUtils.booleanFromProperties(props, prefix + USE_CURSOR_PROPERTY, isUseCursor())); - - azDrawing.setProperties(prefix + AZ_PANNING_PROPERTY, props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + OPAQUENESS_PROPERTY, Float.toString(getOpaqueness())); - props.put(prefix + LEAVE_SHADOW_PROPERTY, Boolean.toString(isLeaveShadow())); - props.put(prefix + USE_CURSOR_PROPERTY, Boolean.toString(isUseCursor())); - props.put(prefix + AZ_PANNING_SHAPEFILE_PROPERTY, PropUtils.unnull(azPanningShapefile)); - - azDrawing.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, props, OMMouseMode.class, OPAQUENESS_PROPERTY, "Transparency", "Transparency level for moving map, between 0 (clear) and 1 (opaque).", null); - PropUtils.setI18NPropertyInfo(i18n, props, OMMouseMode.class, LEAVE_SHADOW_PROPERTY, "Leave Shadow", "Display current map in background while panning.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, OMMouseMode.class, USE_CURSOR_PROPERTY, "Use Cursor", "Use hand cursor for mouse mode.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, OMMouseMode.class, AZ_PANNING_SHAPEFILE_PROPERTY, "Az Projection Panning Shapefile", "Use a shapefile for azimuthal projection panning.", "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - azDrawing.getPropertyInfo(props); - return props; - } - - /** - * Checks the MouseEvent to see if a BufferedMapBean can be found. - * - * @param evt MouseEvent, or a MapMouseEvent - * @return BufferedMapBean, or null if source is not a BufferedMapBean. - */ - protected BufferedMapBean getBufferedMapBean(MouseEvent evt) { - if (evt instanceof MapMouseEvent) { - MapBean mb = ((MapMouseEvent) evt).getMap(); - if (mb instanceof BufferedMapBean) { - return (BufferedMapBean) mb; - } - } else { - Object src = evt.getSource(); - if (src instanceof BufferedMapBean) { - return (BufferedMapBean) src; - } - } - - return null; - } - - /** - * PaintListener method. - * - * @param source the source object, most likely the MapBean - * @param g java.awt.Graphics - */ - public void listenerPaint(Object source, Graphics g) { - MapBean mapBean = source instanceof MapBean ? (MapBean) source : null; - - if (azPanner != null) { - azPanner.render(g); - } else if (mapBean != null) { - mapBean.removePaintListener(this); - } - } - - /** - * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) - * The first click for drag, the image is generated. This image is - * redrawing when the mouse is move, but, I need to repain the original - * image. - */ - public void mouseDragged(MouseEvent arg0) { - super.mouseDragged(arg0); - - if (mouseSupport.proxy == null) { - - BufferedMapBean mapBean = getBufferedMapBean(arg0); - if (mapBean == null) { - // OMMouseMode needs a BufferedMapBean - return; - } - - Projection proj = mapBean.getProjection(); - - // Left mouse click, pan - if (SwingUtilities.isLeftMouseButton(arg0)) { - - int x = arg0.getX(); - int y = arg0.getY(); - - if (!isPanning) { - oX = x; - oY = y; - isPanning = true; - - } else if (proj instanceof Cylindrical || proj instanceof Cartesian) { - // oX and oY set for this case. Not used for Azimuth - // projections. - mapBean.setPanningTransform(AffineTransform.getTranslateInstance(x - oX, y - oY)); - mapBean.repaint(); - - } else { - - if (azPanner == null) { - URL url = null; - try { - url = PropUtils.getResourceOrFileOrURL(azPanningShapefile); - } catch (MalformedURLException murle) { - } - - if (url != null) { - azPanner = new AzimuthPanner.Shapefile(oX, oY, getAzDrawing(), url); - } else { - azPanner = new AzimuthPanner.Standard(oX, oY, getAzDrawing()); - } - mapBean.addPaintListener(this); - } - - // Azimuth projection - if (azPanner != null) { - azPanner.handlePan(mapBean, arg0); - } - mapBean.repaint(); - } - } - } - } - - /** - * Process a mouse pressed event. Add the mouse location to the segment - * vector. Calculate the cumulative total distance. - * - * @param e mouse event. - */ - public void mousePressed(MouseEvent e) { - mouseSupport.fireMapMousePressed(e); - e.getComponent().requestFocus(); - - if (mouseSupport.proxy == null) { - - if (SwingUtilities.isRightMouseButton(e)) { - // mouse has now been pressed - // mousePressed = true; - - MapBean mb = theMap; - if (mb == null && e.getSource() instanceof MapBean) { - mb = (MapBean) e.getSource(); - } - - if (mb != null) { - // anchor the new first point of the line - rPoint1 = mb.getCoordinates(e); - // ensure the second point is not yet set. - rPoint2 = null; - } - } - } - } - - public void mouseClicked(MouseEvent e) { - Object obj = e.getSource(); - - boolean consumed = mouseSupport.fireMapMouseClicked(e); - - if (consumed || !(obj instanceof MapBean) || e.getClickCount() < 2) - return; - - MapBean map = (MapBean) obj; - Projection projection = map.getProjection(); - Proj p = (Proj) projection; - - Point2D llp = map.getCoordinates(e); - - boolean shift = e.isShiftDown(); - - if (shift) { - p.setScale(p.getScale() * 2.0f); - } else { - p.setScale(p.getScale() / 2.0f); - } - - p.setCenter(llp); - map.setProjection(p); - } - - /** - * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) - * Make Pan event for the map. - */ - public void mouseReleased(MouseEvent arg0) { - - if (mouseSupport.proxy == null && isPanning) { - - BufferedMapBean mb = getBufferedMapBean(arg0); - if (mb == null) { - return; - } - - Projection proj = mb.getProjection(); - Point2D center = proj.forward(proj.getCenter()); - - int x = arg0.getX(); - int y = arg0.getY(); - - center.setLocation(center.getX() - x + oX, center.getY() - y + oY); - /* - * OK, center now holds the pixel location of the new center pnt. To - * figure out the lat/lon of it, we can do a straight inverse - * projection operation. We will need to take rotation into account - * if needed. - */ - mb.setCenter(mb.inverse(center.getX(), center.getY(), null)); - - mb.setPanningTransform(null); - - isPanning = false; - - if (azPanner != null) { - azPanner.handleUnpan(arg0); - azPanner = null; - } - } - - super.mouseReleased(arg0); - } - - public boolean isLeaveShadow() { - return leaveShadow; - } - - public void setLeaveShadow(boolean leaveShadow) { - this.leaveShadow = leaveShadow; - } - - public float getOpaqueness() { - return opaqueness; - } - - public void setOpaqueness(float opaqueness) { - this.opaqueness = opaqueness; - } - - public boolean isPanning() { - return isPanning; - } - - /** - * @return the starting x pixel location of a drag. - */ - public int getOX() { - return oX; - } - - /** - * @return the starting y pixel location of a drag. - */ - public int getOY() { - return oY; - } - - /** - * @return the azPanningShapefile - */ - public String getAzPanningShapefile() { - return azPanningShapefile; - } - - /** - * @param azPanningShapefile the azPanningShapefile to set - */ - public void setAzPanningShapefile(String azPanningShapefile) { - this.azPanningShapefile = azPanningShapefile; - } - - /** - * @return the azDrawing - */ - public DrawingAttributes getAzDrawing() { - return azDrawing; - } - - /** - * @param azDrawing the azDrawing to set - */ - public void setAzDrawing(DrawingAttributes azDrawing) { - this.azDrawing = azDrawing; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/OverviewMapStatusListener.java b/src/core/src/main/java/com/bbn/openmap/event/OverviewMapStatusListener.java deleted file mode 100644 index 0d1ed575d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/OverviewMapStatusListener.java +++ /dev/null @@ -1,32 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/OverviewMapStatusListener.java,v -// $ -// $RCSfile: OverviewMapStatusListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.proj.Projection; - -public interface OverviewMapStatusListener { - public void setSourceMapProjection(Projection proj); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/event/PaintListener.java b/src/core/src/main/java/com/bbn/openmap/event/PaintListener.java deleted file mode 100644 index 9d7c5398a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PaintListener.java +++ /dev/null @@ -1,40 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/PaintListener.java,v $ -// $RCSfile: PaintListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Graphics; - -/** - * A PaintListener is an object that wants to know when another object - * is painted with a java.awt.Graphics object. - */ -public interface PaintListener { - - /** - * Method called when the source object is painted. - * @param source the source object, may be null, you need to check. - * @param graphics the graphics to paint into. - */ - public void listenerPaint(Object source, Graphics graphics); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/PaintListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/event/PaintListenerSupport.java deleted file mode 100644 index b00021e04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PaintListenerSupport.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/PaintListenerSupport.java,v $ -// $RCSfile: PaintListenerSupport.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.Graphics; - -import com.bbn.openmap.util.Debug; - -/** - * This is a utility class that can be used by beans that need support - * for handling PaintListeners and calling the PaintListener.paint() - * method. You can use an instance of this class as a member field of - * your bean and delegate work to it. - */ -public class PaintListenerSupport extends ListenerSupport { - - /** - * Construct a PaintListenerSupport. - */ - public PaintListenerSupport() { - this(null); - } - - /** - * Construct a PaintListenerSupport. - * - * @param source source Object - */ - public PaintListenerSupport(Object source) { - super(source); - } - - /** - * Send a Paint event to all registered listeners. - * - * @param graphics PaintEvent - */ - public void paint(Graphics graphics) { - - if (isEmpty()) - return; - - for (PaintListener target : this) { - if (Debug.debugging("paint")) { - Debug.output("PaintListenerSupport.paint(): target is: " - + target); - } - target.listenerPaint(getSource(), graphics); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/PanEvent.java b/src/core/src/main/java/com/bbn/openmap/event/PanEvent.java deleted file mode 100644 index d8a41c976..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PanEvent.java +++ /dev/null @@ -1,190 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/PanEvent.java,v $ -// $RCSfile: PanEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2006/02/27 23:19:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * An event to request the map to pan. Event designates the direction - * and magnitude (relative to map dimensions) to pan the map. - */ -public class PanEvent extends java.util.EventObject { - /** - * Marks the first integer id for the range of pan event - * directions. - */ - public static final int PAN_FIRST = 1300; - - /** - * Marks the last integer id for the range of pan event - * directions. - */ - public static final int PAN_LAST = 1307; - - /** - * The possible pan directions - */ - public static final int NORTH = 1300; - public static final int NORTH_EAST = 1301; - public static final int EAST = 1302; - public static final int SOUTH_EAST = 1303; - public static final int SOUTH = 1304; - public static final int SOUTH_WEST = 1305; - public static final int WEST = 1306; - public static final int NORTH_WEST = 1307; - - protected float Az; - protected float c; - - /** - * Create a PanEvent with source Object and direction. - *

- * - * @param source Object - * @param direction N, NE, E, SE, S, SW, W, NW - * @deprecated use new panning semantics - */ - public PanEvent(Object source, int direction) { - this(source, dir2Az(direction), Float.NaN); - } - - /** - * Create a PanEvent with source Object and direction. - *

- * - * @param source Object - * @param direction N, NE, E, SE, S, SW, W, NW - * @param amount 0.0 <= x <= 1.0 - * @deprecated use new panning semantics - */ - public PanEvent(Object source, int direction, float amount) { - this(source, dir2Az(direction), Float.NaN); - } - - /** - * Create a PanEvent. - *

    - *
  • pan(-180) pan south - *
  • pan(-90) pan west - *
  • pan(0) pan north - *
  • pan(90) pan east - *
- * - * @param source Object - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - public PanEvent(Object source, float Az) { - this(source, Az, Float.NaN); - } - - /** - * Create a PanEvent. - *
    - *
  • pan(-180, c) pan south `c' degrees - *
  • pan(-90, c) pan west `c' degrees - *
  • pan(0, c) pan north `c' degrees - *
  • pan(90, c) pan east `c' degrees - *
- * - * @param source Object - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees - */ - public PanEvent(Object source, float Az, float c) { - super(source); - this.Az = Az; - this.c = c; - } - - // convert from old style to new - final static float dir2Az(int direction) { - switch (direction) { - case NORTH_WEST: - return -45f; - case NORTH: - return 0f; - case NORTH_EAST: - return 45f; - case EAST: - return 90f; - case SOUTH_EAST: - return 135f; - case SOUTH: - return 180f; - case SOUTH_WEST: - return -135f; - case WEST: - return -90f; - default: - return 0f; - } - } - - /** - * Get azimuth of pan. - * - * @return float decimal degrees - */ - public float getAzimuth() { - return Az; - } - - /** - * Get arc distance of pan. - * - * @return float decimal degrees - */ - public float getArcDistance() { - return c; - } - - /** - * Get the direction of pan. - * - * @return int direction - * @deprecated use getAzimuth() - */ - public int getDirection() { - return -1; - } - - /** - * Get the amount of pan. - * - * @return float 0.0 <= amount <= 1.0 - * @deprecated use getArcDistance() - */ - public float getAmount() { - return Float.NaN; - } - - /** - * Return stringified object. - * - * @return String - */ - public String toString() { - return getClass().getName() + "[Az = " + Az + ", c=" + c + ", source=" - + source + "]"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/PanListener.java b/src/core/src/main/java/com/bbn/openmap/event/PanListener.java deleted file mode 100644 index 2eecbc1b8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PanListener.java +++ /dev/null @@ -1,30 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/PanListener.java,v $ -// $RCSfile: PanListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for requests to pan the map. - */ -public interface PanListener extends java.util.EventListener { - public void pan(PanEvent evt); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/PanMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/PanMouseMode.java deleted file mode 100644 index dcc3707db..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PanMouseMode.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * - * Copyright (C) SISDEF Ltda. All rights reserved. - * - * Created on 25-feb-2005 - */ -package com.bbn.openmap.event; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.image.ImageScaler; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Cartesian; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; - -/** - * PanMouseMode it is a class for Pan operation on the visible map. This class - * show actual map in transparent mode. 25-feb-2005. There are a couple of - * properties that can be set in this mouse mode: - * - *
- *           # Floating number between 0-1, with 1 being opaque, default .5
- *           panmm.opaqueness=.5f
- *           # True/false, to leave old map up behind panned version.
- *           panmm.leaveShadow=true
- * 
- * - * @author cursor - * @author Stephane Wasserhardt - */ -public class PanMouseMode extends CoordMouseMode implements ProjectionListener { - - public final static String OPAQUENESS_PROPERTY = "opaqueness"; - public final static String LEAVE_SHADOW_PROPERTY = "leaveShadow"; - public final static String USE_CURSOR_PROPERTY = "useCursor"; - public final static String AZ_PANNING_SHAPEFILE_PROPERTY = "azPanningShapefile"; - public final static String AZ_PANNING_PROPERTY = "azPanning"; - - public final static float DEFAULT_OPAQUENESS = 0.5f; - - public final static transient String modeID = "Pan"; - private boolean isPanning = false; - private BufferedImage bufferedMapImage = null; - private OMRaster paintedImage = null; - private int beanBufferWidth = 0; - private int beanBufferHeight = 0; - private int oX, oY; - private MouseEvent lastMouseEvent; - private float opaqueness; - private boolean leaveShadow; - private boolean useCursor; - private AzimuthPanner azPanner = null; - private String azPanningShapefile = null; - private DrawingAttributes azDrawing = null; - - public PanMouseMode() { - super(modeID, true); - setUseCursor(true); - setLeaveShadow(false); - setOpaqueness(DEFAULT_OPAQUENESS); - - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setMatted(true); - da.setMattingPaint(Color.LIGHT_GRAY); - - setAzDrawing(da); - } - - public void setActive(boolean val) { - if (!val) { - if (bufferedMapImage != null) { - bufferedMapImage.flush(); - } - beanBufferWidth = 0; - beanBufferHeight = 0; - bufferedMapImage = null; - } - } - - /** - * @return Returns the useCursor. - */ - public boolean isUseCursor() { - return useCursor; - } - - /** - * @param useCursor The useCursor to set. - */ - public void setUseCursor(boolean useCursor) { - this.useCursor = useCursor; - if (useCursor) { - /* - * For who like make his CustomCursor - */ - try { - Toolkit tk = Toolkit.getDefaultToolkit(); - ImageIcon pointer = new ImageIcon(getClass().getResource("pan.gif")); - Dimension bestSize = tk.getBestCursorSize(pointer.getIconWidth(), pointer.getIconHeight()); - Image pointerImage = ImageScaler.getOptimalScalingImage(pointer.getImage(), (int) bestSize.getWidth(), (int) bestSize.getHeight()); - Cursor cursor = tk.createCustomCursor(pointerImage, new Point(0, 0), "PP"); - setModeCursor(cursor); - return; - } catch (Exception e) { - // Problem finding image probably, just move on. - } - } - - setModeCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - opaqueness = PropUtils.floatFromProperties(props, prefix + OPAQUENESS_PROPERTY, opaqueness); - leaveShadow = PropUtils.booleanFromProperties(props, prefix + LEAVE_SHADOW_PROPERTY, leaveShadow); - - azPanningShapefile = props.getProperty(prefix + AZ_PANNING_SHAPEFILE_PROPERTY, azPanningShapefile); - setUseCursor(PropUtils.booleanFromProperties(props, prefix + USE_CURSOR_PROPERTY, isUseCursor())); - - azDrawing.setProperties(prefix + AZ_PANNING_PROPERTY, props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + OPAQUENESS_PROPERTY, Float.toString(getOpaqueness())); - props.put(prefix + LEAVE_SHADOW_PROPERTY, Boolean.toString(isLeaveShadow())); - props.put(prefix + USE_CURSOR_PROPERTY, Boolean.toString(isUseCursor())); - props.put(prefix + AZ_PANNING_SHAPEFILE_PROPERTY, PropUtils.unnull(azPanningShapefile)); - - azDrawing.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, props, PanMouseMode.class, OPAQUENESS_PROPERTY, "Transparency", "Transparency level for moving map, between 0 (clear) and 1 (opaque).", null); - PropUtils.setI18NPropertyInfo(i18n, props, PanMouseMode.class, LEAVE_SHADOW_PROPERTY, "Leave Shadow", "Display current map in background while panning.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, PanMouseMode.class, USE_CURSOR_PROPERTY, "Use Cursor", "Use hand cursor for mouse mode.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, props, OMMouseMode.class, AZ_PANNING_SHAPEFILE_PROPERTY, "Az Projection Panning Shapefile", "Use a shapefile for azimuthal projection panning.", "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - azDrawing.getPropertyInfo(props); - return props; - } - - /** - * PaintListener method. - * - * @param source the source object, most likely the MapBean - * @param g java.awt.Graphics - */ - public void listenerPaint(Object source, Graphics g) { - MapBean mapBean = source instanceof MapBean ? (MapBean) source : null; - - if (azPanner != null) { - azPanner.render(g); - } else if (mapBean != null) { - if (isPanning && lastMouseEvent != null && bufferedMapImage != null) { - - /** - * TODO: This doesn't work for rotated images, can't quite get the - * buffered image to render in the right location and not be - * rotated as well. So for now, if rotated, handle as if for - * azimuth. - DFD - */ - - Graphics2D gr2d = (Graphics2D) g.create(); - Projection proj = mapBean.getRotatedProjection(); - - if (!leaveShadow) { - gr2d.setPaint(mapBean.getBckgrnd()); - // Takes care of rotated dimensions, too. - gr2d.fillRect(0, 0, proj.getWidth(), proj.getHeight()); - } - - Point2D pnt0 = proj.forward(mapBean.inverse(oX, oY, null)); - int startX = (int) pnt0.getX(); - int startY = (int) pnt0.getY(); - - Point2D pnt = mapBean.getNonRotatedLocation(lastMouseEvent); - int x = (int) pnt.getX(); - int y = (int) pnt.getY(); - - /* - * Drawing image with transparency and in the mouse position - * minus original mouse click position - */ - gr2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opaqueness)); - - paintedImage.setX(x - startX); - paintedImage.setY(y - startY); - paintedImage.setRotationAngle(-proj.getRotationAngle()); - - paintedImage.generate(proj); - paintedImage.render(gr2d); - - } else { - mapBean.removePaintListener(this); - } - } - } - - public void mousePressed(MouseEvent arg0) { - MapBean mapBean = arg0.getSource() instanceof MapBean ? (MapBean) arg0.getSource() : null; - - if (mapBean != null) { - - lastMouseEvent = arg0; - oX = (int) arg0.getX(); - oY = (int) arg0.getY(); - // If the map is rotated, the size of the projection will be bigger - // than - // the size of the MapBean. - Projection proj = mapBean.getRotatedProjection(); - int w = proj.getWidth(); - int h = proj.getHeight(); - - if ((proj instanceof Cylindrical || proj instanceof Cartesian) - && proj.getRotationAngle() == 0.0) { - - if (bufferedMapImage == null) { - createBuffer(w, h); - } - - Graphics2D g = (Graphics2D) bufferedMapImage.getGraphics(); - mapBean.paintChildren(g, null); - - Point2D ul = mapBean.inverse(0.0, 0.0, null); - paintedImage = new OMRaster(MoreMath.latJLT90(ul.getY()), ul.getX(), 0, 0, bufferedMapImage); - paintedImage.putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - - } else { - URL url = null; - try { - url = PropUtils.getResourceOrFileOrURL(azPanningShapefile); - } catch (MalformedURLException murle) { - } - - if (url != null) { - azPanner = new AzimuthPanner.Shapefile(oX, oY, getAzDrawing(), url); - } else { - azPanner = new AzimuthPanner.Standard(oX, oY, getAzDrawing()); - } - } - - isPanning = true; - mapBean.addPaintListener(this); - } - } - - /** - * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) - * The first click for drag, the image is generated. This image is - * redrawing when the mouse is move, but, I need to repaint the - * original image. - */ - public void mouseDragged(MouseEvent arg0) { - - MapBean mapBean = arg0.getSource() instanceof MapBean ? (MapBean) arg0.getSource() : null; - lastMouseEvent = arg0; - - if (mapBean != null) { - - if (azPanner != null) { - azPanner.handlePan(mapBean, arg0); - } - - mapBean.repaint(); - } - super.mouseDragged(arg0); - } - - /** - * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) - * Make Pan event for the map. - */ - public void mouseReleased(MouseEvent arg0) { - - MapBean mapBean = arg0.getSource() instanceof MapBean ? (MapBean) arg0.getSource() : null; - - if (azPanner != null) { - azPanner.handleUnpan(arg0); - azPanner = null; - } - - if (isPanning && mapBean != null) { - Projection proj = mapBean.getProjection(); - Point2D center = proj.forward(proj.getCenter()); - int x = (int) arg0.getX(); - int y = (int) arg0.getY(); - - center.setLocation(center.getX() - x + oX, center.getY() - y + oY); - - isPanning = false; // needs to be here too so paintlistener doesn't - // get triggered - mapBean.setCenter(mapBean.inverse(center.getX(), center.getY(), null)); - } - - oX = 0; - oY = 0; - isPanning = false; - - super.mouseReleased(arg0); - } - - public boolean isLeaveShadow() { - return leaveShadow; - } - - public void setLeaveShadow(boolean leaveShadow) { - this.leaveShadow = leaveShadow; - } - - public float getOpaqueness() { - return opaqueness; - } - - public void setOpaqueness(float opaqueness) { - this.opaqueness = opaqueness; - } - - public boolean isPanning() { - return isPanning; - } - - public int getOX() { - return oX; - } - - public int getOY() { - return oY; - } - - /** - * @return the azPanningShapefile - */ - public String getAzPanningShapefile() { - return azPanningShapefile; - } - - /** - * @param azPanningShapefile the azPanningShapefile to set - */ - public void setAzPanningShapefile(String azPanningShapefile) { - this.azPanningShapefile = azPanningShapefile; - } - - /** - * @return the azDrawing - */ - public DrawingAttributes getAzDrawing() { - return azDrawing; - } - - /** - * @param azDrawing the azDrawing to set - */ - public void setAzDrawing(DrawingAttributes azDrawing) { - this.azDrawing = azDrawing; - } - - public void projectionChanged(ProjectionEvent e) { - Object obj = e.getSource(); - if (obj instanceof MapBean) { - MapBean mb = (MapBean) obj; - int w = mb.getWidth(); - int h = mb.getHeight(); - createBuffer(w, h); - } - } - - /** - * Instantiates new image buffers if needed.
- * This method is synchronized to avoid creating the images multiple times - * if width and height doesn't change. - * - * @param w mapBean's width. - * @param h mapBean's height. - */ - public synchronized void createBuffer(int w, int h) { - if (w > 0 && h > 0 && (w != beanBufferWidth || h != beanBufferHeight)) { - beanBufferWidth = w; - beanBufferHeight = h; - createBufferImpl(w, h); - } - } - - /** - * Instantiates new image buffers. - * - * @param w Non-zero mapBean's width. - * @param h Non-zero mapBean's height. - */ - protected void createBufferImpl(int w, int h) { - // Release system resources used by previous images... - if (bufferedMapImage != null) { - bufferedMapImage.flush(); - } - // New image... - bufferedMapImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/PanSupport.java b/src/core/src/main/java/com/bbn/openmap/event/PanSupport.java deleted file mode 100644 index c28544f05..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/PanSupport.java +++ /dev/null @@ -1,97 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/PanSupport.java,v $ -// $RCSfile: PanSupport.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - - -/** - * This is a utility class that can be used by beans that need support - * for handling PanListeners and firing PanEvents. You can use an - * instance of this class as a member field of your bean and delegate - * work to it. - */ -public class PanSupport extends ListenerSupport { - - /** - * Construct a PanSupport. - * - * @param sourceBean The bean to be given as the source for any - * events. - */ - public PanSupport(Object sourceBean) { - super(sourceBean); - } - - /** - * Send a pan event to all registered listeners. - * - * @param direction PanEvent.NORTH ... PanEvent.NORTH_WEST - * @see PanEvent - * @deprecated use firePan(azimuth) - */ - public void firePan(int direction) { - firePan(direction, 1f); - } - - /** - * Send a pan event to all registered listeners. - * - * @param direction PanEvent.NORTH ... PanEvent.NORTH_WEST - * @param amount (0.0 <= amount) in decimal degrees. - * @see PanEvent - * @deprecated use firePan(azimuth, arc) - */ - public void firePan(int direction, float amount) { - - if (direction < PanEvent.PAN_FIRST || direction > PanEvent.PAN_LAST) { - throw new IllegalArgumentException("Bad value, " + direction - + " for direction in " + "PanSupport.firePan()"); - } - - float az = PanEvent.dir2Az(direction); - firePan(az); - } - - public void firePan(float Az) { - firePan(Az, Float.NaN); - } - - /** - * Fire a pan event. - * - * @param az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees. - */ - public synchronized void firePan(float az, float c) { - - if (isEmpty()) - return; - - PanEvent evt = new PanEvent(source, az, c); - - for (PanListener listener : this) { - listener.pan(evt); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProgressEvent.java b/src/core/src/main/java/com/bbn/openmap/event/ProgressEvent.java deleted file mode 100644 index 02053b840..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProgressEvent.java +++ /dev/null @@ -1,105 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProgressEvent.java,v $ -// $RCSfile: ProgressEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * An event that provides information on progress on a certain task. - */ -public class ProgressEvent extends java.util.EventObject { - - /** - * Progress event type, start process. - */ - public static final int START = 0; - /** - * Progress event type, update of current process. - */ - public static final int UPDATE = 1; - /** - * Progress event type, notification of process completion. - */ - public static final int DONE = 2; - - protected float finishedValue = 0; - protected float currentValue = 0; - protected String taskDescription = ""; - protected int type = 0; - - /** - * Construct a ProgressEvent. - * - * @param source Object - * @param finishValue the ending value - * @param currentValue the current value - */ - public ProgressEvent(Object source, int type, String taskDescription, - float finishValue, float currentValue) { - super(source); - this.finishedValue = finishValue; - this.currentValue = currentValue; - this.taskDescription = taskDescription; - this.type = type; - } - - /** - * Get the value that current will have to get to to be finished. - * - * @return finished. - */ - public float getFinishedValue() { - return finishedValue; - } - - /** - * Get the current value representing progress. - */ - public float getCurrentValue() { - return currentValue; - } - - /** - * Get a string describing what the task is. - */ - public String getTaskDescription() { - return taskDescription; - } - - /** - * Provide a percentage of progress completed, or -1 if no - * finished value has been provided. - */ - public int getPercentComplete() { - if (finishedValue != 0) { - int ret = (int) (currentValue / finishedValue * 100f); - // com.bbn.openmap.util.Debug.output("pe.percentComplete: - // " + currentValue + "/" + finishedValue + " = " + ret); - return ret; - } else { - return -1; - } - } - - public int getType() { - return type; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProgressListener.java b/src/core/src/main/java/com/bbn/openmap/event/ProgressListener.java deleted file mode 100644 index c5e12aa83..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProgressListener.java +++ /dev/null @@ -1,35 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProgressListener.java,v $ -// $RCSfile: ProgressListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for ProgressEvents from something doing some work. - */ -public interface ProgressListener extends java.util.EventListener { - /** - * Intermediate updates. - */ - public void updateProgress(ProgressEvent evt); - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProgressSupport.java b/src/core/src/main/java/com/bbn/openmap/event/ProgressSupport.java deleted file mode 100644 index d79b8ba64..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProgressSupport.java +++ /dev/null @@ -1,73 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProgressSupport.java,v $ -// $RCSfile: ProgressSupport.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.util.Debug; - -/** - * This is a utility class that can be used by beans that need support - * for handling ProgressListeners and firing ProgressEvents. You can - * use an instance of this class as a member field of your bean and - * delegate work to it. - */ -public class ProgressSupport extends ListenerSupport { - - /** - * Construct a ProgressSupport. - * - * @param sourceBean The bean to be given as the source for any - * events. - */ - public ProgressSupport(Object sourceBean) { - super(sourceBean); - Debug.message("progresssupport", "ProgressSupport | ProgressSupport"); - } - - /** - * Send a layer event to all registered listeners. - * - * @param taskname the description of the task - * @param finishedValue the completed value - * @param currentValue the currentValue - */ - public void fireUpdate(int type, String taskname, float finishedValue, - float currentValue) { - Debug.message("progresssupport", "ProgressSupport | fireUpdate"); - - boolean DEBUG = Debug.debugging("progresssupport"); - - if (DEBUG) { - Debug.output("ProgressSupport | fireUpdate has " + size() - + " listeners"); - } - - if (isEmpty()) - return; - - ProgressEvent evt = new ProgressEvent(source, type, taskname, finishedValue, currentValue); - - for (ProgressListener listener : this) { - listener.updateProgress(evt); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProjMapBeanKeyListener.java b/src/core/src/main/java/com/bbn/openmap/event/ProjMapBeanKeyListener.java deleted file mode 100644 index cd71ce8f3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProjMapBeanKeyListener.java +++ /dev/null @@ -1,191 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProjMapBeanKeyListener.java,v $ -// $RCSfile: ProjMapBeanKeyListener.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/02/27 23:19:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.ProjectionStack; -import com.bbn.openmap.proj.ProjectionStackTrigger; - -/** - * The ProjMapBeanKeyListener is a KeyListener that gets events when - * the MapBean has focus, and responds to certain keys by changing the - * projection. The arrow keys pan the map, and 'z' zooms in. Shift-z - * zooms out. The less than/comma key tells a projection stack to go - * back to the last projection, and the greater than/period tells it - * to go to the next projection. The MapBean has to have focus for - * these to work which is usually gained by clicking on the map. - */ -public class ProjMapBeanKeyListener extends MapBeanKeyListener implements - ProjectionStackTrigger { - - /** - * Default Zoom In Factor is 2, meaning that the scale number will - * be cut in half to zoom in and doubled to zoom out. - */ - protected transient float zoomFactor = 2f; - - protected PanSupport panners; - protected ZoomSupport zoomers; - protected ListenerSupport projListeners; - - public ProjMapBeanKeyListener() { - panners = new PanSupport(this); - zoomers = new ZoomSupport(this); - projListeners = new ListenerSupport(this); - } - - public void keyReleased(KeyEvent e) { - - int keyCode = e.getKeyCode(); - - // When we can control rates, we'll use shift for double pan, - // and ctrl for half pan - // int modifiers = e.getModifiers(); - - switch (keyCode) { - case KeyEvent.VK_UP: - case KeyEvent.VK_KP_UP: - panners.firePan(0f/* PanEvent.NORTH */); - break; - case KeyEvent.VK_DOWN: - case KeyEvent.VK_KP_DOWN: - panners.firePan(180f/* PanEvent.SOUTH */); - break; - case KeyEvent.VK_LEFT: - case KeyEvent.VK_KP_LEFT: - panners.firePan(-90f/* PanEvent.WEST */); - break; - case KeyEvent.VK_RIGHT: - case KeyEvent.VK_KP_RIGHT: - panners.firePan(90f/* PanEvent.EAST */); - break; - case KeyEvent.VK_Z: - if (e.isShiftDown()) { - zoomers.fireZoom(ZoomEvent.RELATIVE, zoomFactor); - } else { - zoomers.fireZoom(ZoomEvent.RELATIVE, 1f / zoomFactor); - } - - break; - // VK_PLUS doesn't react on '+' events... - case KeyEvent.VK_EQUALS: - zoomers.fireZoom(ZoomEvent.RELATIVE, 1f / zoomFactor); - break; - case KeyEvent.VK_MINUS: - zoomers.fireZoom(ZoomEvent.RELATIVE, zoomFactor); - break; - case KeyEvent.VK_COMMA: - fireProjectionStackEvent(ProjectionStack.BackProjCmd); - break; - case KeyEvent.VK_PERIOD: - fireProjectionStackEvent(ProjectionStack.ForwardProjCmd); - break; - } - } - - /** - * In addition to the super.setMapBean() method, also sets the - * MapBean as a zoom and pan listener. - */ - public void setMapBean(MapBean map) { - if (mapBean != null) { - panners.remove(map); - zoomers.remove(map); - } - - super.setMapBean(map); - - if (mapBean != null) { - panners.add(map); - zoomers.add(map); - } - } - - /** - * Called by keyReleased when the period/comma keys are pressed. - */ - protected void fireProjectionStackEvent(String command) { - if (projListeners.isEmpty()) { - return; - } - - ActionEvent event = new ActionEvent(this, 0, command); - for (ActionListener listener : projListeners) { - listener.actionPerformed(event); - } - - } - - /** - * Add an ActionListener for events that trigger events to shift - * the Projection stack. - */ - public void addActionListener(ActionListener al) { - projListeners.add(al); - } - - /** - * Remove an ActionListener that receives events that trigger - * events to shift the Projection stack. - */ - public void removeActionListener(ActionListener al) { - projListeners.remove(al); - } - - /** - * To receive a status to let the trigger know if any projections - * in the forward or backward stacks exist, possibly to disable - * any gui widgets. Does nothing, we don't care here. - * - * @param containsBackProjections there is at least one past - * projection in the back cache. - * @param containsForwardProjections there is at least one future - * projection in the forward cache. Used when a past - * projection is being used. - */ - public void updateProjectionStackStatus(boolean containsBackProjections, - boolean containsForwardProjections) {} - - /** - * In addition to the MapBean, find a projection stack so the less - * than/greater than works on that. - */ - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof ProjectionStack) { - addActionListener((ActionListener) someObj); - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof ProjectionStack) { - removeActionListener((ActionListener) someObj); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProjectionChangeVetoException.java b/src/core/src/main/java/com/bbn/openmap/event/ProjectionChangeVetoException.java deleted file mode 100644 index e1b566f39..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProjectionChangeVetoException.java +++ /dev/null @@ -1,194 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ProjectionChangeVetoException.java,v $ -//$Revision: 1.1 $ -//$Date: 2006/09/12 17:46:47 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; - -/** - * An exception used by PropertyChangeListeners on the MapBean to veto a - * projection change on the MapBean. Should be used by components that want to - * limit the range of projection changes allowed in a application, or during - * certain application conditions. These exceptions should be used by - * PropertyChangeListeners on the MapBean listening for - * MapBean.ProjectionProperty changes, because the MapBean notifies the - * PropertyChangeListeners of projection changes before it notifies the - * ProjectionListeners (the layers). If the MapBean catches one of these - * exceptions from a PropertyChangeListener, the projection parameters will be - * changed to the values provided, all of the PropertyChangeListeners will be - * notified again, and the layers will be finally be notified when the - * PropertyChangeListeners are happy. Only projection changes relating to scale, - * center and type can be vetoed. The size of the projection (pixel width and - * height) is dictated by the MapBean's parent. - * - * @author dietrick - */ -public class ProjectionChangeVetoException extends RuntimeException { - - protected Properties parameters; - - public final static String CENTER = "center"; - public final static String SCALE = "scale"; - public final static String PROJECTION_TYPE = "projType"; - - /** - * Constructs a new projection change veto exception with null - * as its detail message and no suggested changes. The cause is not - * initialized, and may subsequently be initialized by a call to - * {@link #initCause}. - */ - public ProjectionChangeVetoException() { - super(); - } - - /** - * Constructs a new projection change veto exception with the specified - * detail message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - * - * @param message the detail message, with no suggested changes. - */ - public ProjectionChangeVetoException(String message) { - super(message); - } - - /** - * Constructs a new projection change veto exception with the specified - * detail message and common parameter objects for OpenMap projections that - * can be cause for veto. The Throwable cause object is not initialized, and - * may subsequently be initialized by a call to {@link #initCause}. The - * objects provided as arguments will be added to a Properties object set in - * the exception. - * - * @param message the detail message. - * @param projectionType set to null if the new projection class type is OK, - * otherwise set the projection class that should be used. - * @param center set to null of the new projection center is OK, otherwise - * set to the new center point of the projection. - * @param scale set to null if the new projection scale is OK, otherwise - * provide a new scale value. - */ - public ProjectionChangeVetoException(String message, - Class projectionType, Point2D center, Number scale) { - super(message); - parameters = new Properties(); - - if (projectionType != null) { - parameters.put(PROJECTION_TYPE, projectionType); - } - if (center != null) { - parameters.put(CENTER, center); - } - if (scale != null) { - parameters.put(SCALE, scale); - } - } - - /** - * Constructs a new projection change veto exception with the specified - * detail message and a Properties object containing parameter objects - * representing new settings for the rejected projection. The Throwable - * cause object is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - * - * @param message the detail message. - * @param suggestedChanges A Properties object holding CENTER, SCALE, - * PROJECTION_TYPE changes, or any other parameters that can be used - * by the event in the updateWithParameters method. - */ - public ProjectionChangeVetoException(String message, - Properties suggestedChanges) { - parameters = suggestedChanges; - } - - /** - * @param parameter the key for the projection parameter. - * @return the Object for the given key. - */ - public Object getSuggested(String parameter) { - return parameters.get(parameter); - } - - /** - * Remove a suggested parameter from the event. - * - * @param parameter - */ - public void removeSuggested(String parameter) { - parameters.remove(parameter); - } - - /** - * A helper function for the MapBean. The Exception object can update the - * projection for a MapBean, and then call MapBean.setProjection() with the - * new settings. This method was intended to be called from the - * MapBean.fireProjectionChange() method after this Exception has been - * caught, and can be overridden for new/updated Projection types and for - * different suggestion parameters that may be contained in the Exception - * properties. - * - * @param mapBean - */ - public void updateWithParameters(MapBean mapBean) { - Proj projection = (Proj) mapBean.getProjection(); - Object suggested = getSuggested(PROJECTION_TYPE); - if (suggested instanceof Class && suggested != projection.getClass()) { - - projection = (Proj) mapBean.getProjectionFactory() - .makeProjection((Class) suggested, - projection.getCenter(), - projection.getScale(), - projection.getWidth(), - projection.getHeight()); - } - - suggested = getSuggested(CENTER); - if (suggested instanceof Point2D) { - projection.setCenter((Point2D) suggested); - } - - suggested = getSuggested(SCALE); - if (suggested instanceof Number) { - projection.setScale(((Number) suggested).floatValue()); - } - - mapBean.setProjection(projection); - } - - public String toString() { - String message = getMessage(); - if (message == null) { - message = "[no message]"; - } - - return "ProjectionChangeVetoException: " + message - + ", suggested parameters: " + parameters; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProjectionEvent.java b/src/core/src/main/java/com/bbn/openmap/event/ProjectionEvent.java deleted file mode 100644 index a1eedd04a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProjectionEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProjectionEvent.java,v $ -// $RCSfile: ProjectionEvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import com.bbn.openmap.proj.Projection; - -/** - * An event with an updated MapBean projection. - */ -public class ProjectionEvent extends java.util.EventObject { - - protected Projection projection; - - /** - * Construct a ProjectionEvent. - * - * @param source Object - * @param aProj Projection - */ - public ProjectionEvent(Object source, Projection aProj) { - super(source); - projection = aProj; - } - - /** - * Get the Projection. - * - * @return Projection - */ - public Projection getProjection() { - return projection; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProjectionListener.java b/src/core/src/main/java/com/bbn/openmap/event/ProjectionListener.java deleted file mode 100644 index fc3b8a046..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProjectionListener.java +++ /dev/null @@ -1,43 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProjectionListener.java,v $ -// $RCSfile: ProjectionListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Interface for listening to ProjectionEvents. - *

- * ProjectionEvent is fired when something fundamental about the - * MapBean changes (e.g. when width, height, scale, type, center, etc - * changes). - */ -public interface ProjectionListener extends java.util.EventListener { - - /** - * Invoked when there has been a fundamental change to the Map. - *

- * Layers are expected to recompute their graphics (if this makes - * sense), and then repaint() themselves. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ProjectionSupport.java b/src/core/src/main/java/com/bbn/openmap/event/ProjectionSupport.java deleted file mode 100644 index 507cafc89..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ProjectionSupport.java +++ /dev/null @@ -1,216 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ProjectionSupport.java,v $ -// $RCSfile: ProjectionSupport.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.util.ListIterator; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.Projection; - -/** - * This is a utility class that can be used by beans that need support for - * handling ProjectionListeners and firing ProjectionEvents. You can use an - * instance of this class as a member field of your bean and delegate work to - * it. - */ -public class ProjectionSupport extends ListenerSupport { - - static Logger logger = Logger.getLogger("com.bbn.openmap.event.ProjectionSupport"); - private static final long serialVersionUID = 1L; - protected ProjectionChangeNotifier pcNotifier; - protected boolean useNotifier; - - /** - * Construct a ProjectionSupport. - */ - public ProjectionSupport(boolean useNotifier) { - this(null, useNotifier); - } - - /** - * Construct a ProjectionSupport. - * - * @param aSource source Object - */ - public ProjectionSupport(Object aSource, boolean useNotifier) { - super(aSource); - this.useNotifier = useNotifier; - } - - /** - * Send a center event to all registered listeners. - * - * @param proj Projection - */ - public void fireProjectionChanged(Projection proj) { - if (proj == null || isEmpty()) - return; // no event or no listeners - - if (useNotifier && pcNotifier == null) { - pcNotifier = new ProjectionChangeNotifier(); - pcNotifier.start(); - } - - ProjectionEvent event = new ProjectionEvent(getSource(), proj); - - if (pcNotifier != null) { - pcNotifier.fireProjectionEvent(event); - } else { - for (ProjectionListener listener : this) { - listener.projectionChanged(event); - } - } - } - - /** - * Call when getting rid of the ProjectionSupport, it kills the - * ProjectionSupport thread. (from CJS) - */ - public void dispose() { - super.clear(); - if (pcNotifier != null) { - pcNotifier.setTerminated(true); - pcNotifier.fireProjectionEvent(null); - pcNotifier.interrupt(); - pcNotifier = null; - } - } - - /** - * A thread that disperses the projection event, instead of letting the - * Swing thread do it. A new one is created for every projection change, so - * the current ProjectionEvent object is getting delivered with it. - */ - protected class ProjectionChangeNotifier extends Thread { - - private final Object lock = new Object(); - - /* current projection event */ - protected ProjectionEvent projEvent; - - /* next projection event */ - protected ProjectionEvent nextEvent; - - /* a flag to know if we are terminated. */ - protected boolean terminated = false; - - public ProjectionChangeNotifier() { - setName("ProjectionSupportThread " + getName()); - } - - public boolean isTerminated() { - return terminated; - } - - public void setTerminated(boolean terminated) { - this.terminated = terminated; - } - - protected boolean isEventInProgress() { - // synchronized(lock){ - return projEvent != null; - // } - } - - public void fireProjectionEvent(ProjectionEvent event) { - synchronized (lock) { - nextEvent = event; - lock.notifyAll(); // wakes up thread if sleeping - } - } - - public void run() { - while (!terminated) { // run while parent mapbean exists - synchronized (lock) { - if (nextEvent != null) { - projEvent = nextEvent; - nextEvent = null; - } - } - - if (projEvent != null && !isEmpty()) { - - // Instead of going top of map to bottom, go bottom to top: - - /* - * Use this try/catch to deal with any problems getting - * clone of listeners, in case listener list is being - * changed while clone is being made, etc. - */ - try { - - ListIterator li = ProjectionSupport.this.listIterator(); - while (li.hasPrevious()) { - ProjectionListener listener = li.previous(); - - if (nextEvent != null) { - break; // new event has been posted, bail out - } - - /* - * Use this try/catch to eliminate problems from - * individual layers - just blow them off. - */ - try { - synchronized (lock) { - listener.projectionChanged(projEvent); - } - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - logger.info("ProjectionListener not handling projection well: " - + listener.getClass().getName() + " : " - + e.getClass().getName() + " : " + e.getMessage()); - e.printStackTrace(); - } - } - } - - } catch (Exception e) { - logger.fine("caught exception: " + e.getClass().getName() + " : " - + e.getMessage()); - } - - // notification is complete - synchronized (lock) { - projEvent = null; - } - } else { // there is no event - // just wait until we are awakened for the next event - try { - synchronized (lock) { - while (nextEvent == null) { - lock.wait(); - } - } - } catch (InterruptedException x) { - // do nothing, just reenter loop - } - } - } - - logger.fine("Projection notifier thread " + getName() + " done running"); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/RangeRings.gif b/src/core/src/main/java/com/bbn/openmap/event/RangeRings.gif deleted file mode 100644 index 2c164c515..000000000 Binary files a/src/core/src/main/java/com/bbn/openmap/event/RangeRings.gif and /dev/null differ diff --git a/src/core/src/main/java/com/bbn/openmap/event/RangeRingsMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/RangeRingsMouseMode.java deleted file mode 100644 index 7c4fc7f93..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/RangeRingsMouseMode.java +++ /dev/null @@ -1,454 +0,0 @@ -package com.bbn.openmap.event; - -import static com.bbn.openmap.event.DistanceMouseMode.ShowAngleProperty; -import static com.bbn.openmap.event.DistanceMouseMode.ShowCircleProperty; -import static com.bbn.openmap.event.DistanceMouseMode.UnitProperty; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.text.DecimalFormat; -import java.text.Format; -import java.util.Properties; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * Mouse mode for drawing temporary range rings on a map bean.
- * The whole map bean is repainted each time the range rings needs to be - * repainted. The map bean needs to use a mouseDelegator to repaint properly. - *
- * - * @author Stephane Wasserhardt - * - */ -public class RangeRingsMouseMode extends CoordMouseMode { - - private static final long serialVersionUID = 6208201699394207932L; - public final static transient String modeID = "RangeRings"; - /** - * The property string used to set the numRings member variable. - */ - public static final String NUM_RINGS_PROPERTY = "numRings"; - public static final String UNITS_PROPERTY = "units"; - public transient DecimalFormat df = new DecimalFormat("0.###"); - /** - * Format used to draw distances. - */ - protected Format distanceFormat = new DecimalFormat("0.###"); - /** - * Number of rings to draw. Must be a positive integer, or else the value 1 - * will be used. Default value is 3.
- */ - protected int numRings = 3; - /** - * Origin point of the range rings to be drawn. - */ - protected Point2D origin = null; - /** - * Temporary destination point of the range rings to be drawn. - */ - protected Point2D intermediateDest = null; - /** - * Destination point of the range rings to be drawn. - */ - protected Point2D destination = null; - - protected DrawingAttributes rrAttributes = DrawingAttributes.getDefaultClone(); - /** - * Distance units for label. - */ - protected Length units = Length.MILE; - - public RangeRingsMouseMode() { - this(true); - } - - public RangeRingsMouseMode(boolean shouldConsumeEvents) { - super(modeID, shouldConsumeEvents); - init(); - } - - public RangeRingsMouseMode(String name, boolean shouldConsumeEvents) { - super(name, shouldConsumeEvents); - init(); - } - - protected void init() { - setModeCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - rrAttributes.setLinePaint(Color.GRAY); - rrAttributes.setMattingPaint(Color.LIGHT_GRAY); - rrAttributes.setMatted(true); - } - - /** - * Give the Format object used to display distances. - * - * @return Format. - */ - public Format getDistanceFormat() { - return distanceFormat; - } - - /** - * Sets the Format object used to display distances. - * - * @param distanceFormat Format. - */ - public void setDistanceFormat(Format distanceFormat) { - this.distanceFormat = distanceFormat; - } - - /** - * Returns the number of rings to display. - * - * @return the number of rings to display. - */ - public int getNumRings() { - return numRings; - } - - /** - * Sets the number of rings to display. - * - * @param numRings the number of rings to display. - */ - public void setNumRings(int numRings) { - this.numRings = numRings; - } - - public void setActive(boolean active) { - if (!active) { - cleanUp(); - } - } - - public void mouseClicked(MouseEvent e) { - MapBean theMap = e.getSource() instanceof MapBean ? (MapBean) e.getSource() : null; - if (theMap != null) { - // if double (or more) mouse clicked - if (e.getClickCount() >= 2) { - // Clean the range rings - cleanUp(); - theMap.repaint(); - } - } - } - - public void mousePressed(MouseEvent e) { - Object obj = e.getSource(); - if (obj instanceof MapBean) { - MapBean theMap = (MapBean) obj; - if (origin == null) { - Point pnt = e.getPoint(); - origin = theMap.inverse(pnt.getX(), pnt.getY(), new LatLonPoint.Double()); - theMap.addPaintListener(this); - } - } - } - - public void mouseReleased(MouseEvent e) { - Object obj = e.getSource(); - if (obj instanceof MapBean) { - MapBean theMap = (MapBean) obj; - - if (origin != null && destination == null) { - Point pnt = e.getPoint(); - Point2D originPnt = theMap.getProjection().forward(origin); - if (Math.abs(originPnt.getX() - pnt.getX()) > 5 - && Math.abs(originPnt.getY() - pnt.getY()) > 5) { - destination = theMap.inverse(pnt.getX(), pnt.getY(), new LatLonPoint.Double()); - intermediateDest = null; - } - } - - theMap.repaint(); - } - } - - public void mouseDragged(MouseEvent e) { - mouseMoved(e); - } - - public void mouseMoved(MouseEvent e) { - Object obj = e.getSource(); - if (obj instanceof MapBean) { - MapBean theMap = (MapBean) obj; - if (origin != null && destination == null) { - Point pnt = e.getPoint(); - intermediateDest = theMap.inverse(pnt.getX(), pnt.getY(), new LatLonPoint.Double()); - fireMouseLocation(e); - theMap.repaint(); - } else { - fireMouseLocation(e); - } - } - } - - /** - * PaintListener method. - * - * @param source the source object, most likely the MapBean - * @param g java.awt.Graphics - */ - public void listenerPaint(Object source, Graphics g) { - MapBean theMap = source instanceof MapBean ? (MapBean) source : null; - if (theMap != null) { - if (origin != null) { - paintOrigin(origin, g, theMap); - // ... and we paint the rings if we know either destination or - // intermediateDest - if (destination != null) { - paintRangeRings(origin, destination, g, theMap); - } else if (intermediateDest != null) { - paintRangeRings(origin, intermediateDest, g, theMap); - } - } else { - theMap.removePaintListener(this); - } - } - } - - /** - * Paints the origin point of the range rings and its label on the given - * Graphics. - * - * @param llp the location of the origin. - * @param graphics The Graphics to paint on. - */ - protected void paintOrigin(Point2D llp, Graphics graphics, MapBean theMap) { - paintOriginPoint(llp, graphics, theMap); - paintOriginLabel(llp, graphics, theMap); - } - - /** - * Paints the origin point of the range rings on the given Graphics. - * - * @param originPnt the origin point - * @param graphics The Graphics to paint on. - */ - protected void paintOriginPoint(Point2D originPnt, Graphics graphics, MapBean theMap) { - if (theMap != null && originPnt != null) { - OMPoint pt = new OMPoint(originPnt.getY(), originPnt.getX()); - preparePoint(pt); - pt.generate(theMap.getRotatedProjection()); - pt.render(graphics); - } - } - - /** - * Paints the origin label of the range rings on the given Graphics. - * - * @param originPnt the origin point - * @param graphics The Graphics to paint on. - */ - protected void paintOriginLabel(Point2D originPnt, Graphics graphics, MapBean theMap) { - if (theMap != null && originPnt != null) { - OMText text = new OMText(originPnt.getY(), originPnt.getX(), getOriginLabel(), OMText.JUSTIFY_CENTER); - text.setBaseline(OMText.BASELINE_BOTTOM); - text.putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - prepareLabel(text); - text.generate(theMap.getRotatedProjection()); - text.render(graphics); - } - } - - /** - * Paints the circles and their labels on the given Graphics. - * - * @param originPnt the origin location - * @param dest the location of the inner ring. - * @param graphics The Graphics to paint on. - */ - protected void paintRangeRings(Point2D originPnt, Point2D dest, Graphics graphics, - MapBean theMap) { - Geo originGeo = new Geo(originPnt.getY(), originPnt.getX(), true); - Geo destGeo = new Geo(dest.getY(), dest.getX(), true); - double distance = originGeo.distance(destGeo); // radians - - for (int i = 1; i <= Math.max(1, numRings); i++) { - double ringDist = distance * (double) i; - - paintCircle(originGeo, ringDist, graphics, theMap); - paintLabel(originGeo, ringDist, graphics, theMap); - } - } - - /** - * Paints a unique circle centered on origin and which crosses - * dest on the given Graphics. - * - * @param originGeo the origin location - * @param distance the distance of the circle from the origin, in radians - * @param graphics The Graphics to paint on. - */ - protected void paintCircle(Geo originGeo, double distance, Graphics graphics, MapBean theMap) { - OMCircle circle = new OMCircle(originGeo.getLatitude(), originGeo.getLongitude(), Length.DECIMAL_DEGREE.fromRadians(distance)); - prepareCircle(circle); - circle.generate(theMap.getRotatedProjection()); - circle.render(graphics); - } - - /** - * Paints a label for the circle drawn using dest on the given - * Graphics. - * - * @param originGeo the Geo for the origin location - * @param distance the distance of circle in radians. - * @param graphics The Graphics to paint in. - */ - protected void paintLabel(Geo originGeo, double distance, Graphics graphics, MapBean theMap) { - Geo ringGeo = originGeo.offset(distance, Math.PI); - OMText text = new OMText(ringGeo.getLatitude(), ringGeo.getLongitude(), getLabelFor(distance), OMText.JUSTIFY_CENTER); - text.putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - text.setBaseline(OMText.BASELINE_BOTTOM); - prepareLabel(text); - text.generate(theMap.getRotatedProjection()); - text.render(graphics); - } - - /** - * Customizes the given OMPoint before it is rendered. - * - * @param point OMPoint. - */ - protected void preparePoint(OMPoint point) { - rrAttributes.setTo(point); - } - - /** - * Customizes the given OMCicle before it is rendered. - * - * @param circle OMCircle. - */ - protected void prepareCircle(OMCircle circle) { - rrAttributes.setTo(circle); - } - - /** - * Customizes the given OMText before it is rendered. - * - * @param text OMText. - */ - protected void prepareLabel(OMText text) { - rrAttributes.setTo(text); - - text.setLinePaint(rrAttributes.getLinePaint()); - text.setTextMatteColor((Color) rrAttributes.getMattingPaint()); - text.setTextMatteStroke(new BasicStroke(4)); - } - - /** - * Returns the String to be used as a labeler for the origin point of the - * range rings. - * - * @return label String. - */ - protected String getOriginLabel() { - return "(" + df.format(origin.getY()) + ", " + df.format(origin.getX()) + ")"; - } - - /** - * Returns the String to be used as a labeler for the circle drawn using - * dest. - * - * @param distance The distance from the origin for the label, in radians. - * @return label String. - */ - protected String getLabelFor(double distance) { - - Format distFormat = getDistanceFormat(); - - if (distFormat == null) { - return Double.toString(distance); - } - return distFormat.format(new Double(units.fromRadians(distance))) + " " + units.getAbbr(); - } - - /** - * Called when the range rings must be cleared, before repainting a clean - * map. - */ - protected void cleanUp() { - origin = null; - intermediateDest = null; - destination = null; - } - - private AffineTransform getTranslation(Point2D pt1, Point2D pt2, Projection proj) { - Point2D p1 = proj.forward(pt1); - Point2D p2 = proj.forward(pt2); - return AffineTransform.getTranslateInstance(p2.getX() - p1.getX(), p2.getY() - p1.getY()); - } - - private LatLonPoint translate(Point2D pt, AffineTransform xyTranslation, Projection proj) { - Point2D p = proj.forward(pt); - xyTranslation.transform(p, p); - return (LatLonPoint) proj.inverse(p, new LatLonPoint.Double()); - } - - /** - * Set properties for this mouse mode - * - * @param prefix property prefix that should be prepended to property keys. - * @param props the properties containing key-values. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - rrAttributes.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - units = Length.get(props.getProperty(prefix + UNITS_PROPERTY, units.getAbbr())); - numRings = PropUtils.intFromProperties(props, prefix + NUM_RINGS_PROPERTY, numRings); - } - - /** - * Get the current Properties for this mouse mode. - * - * @param props The Properties object to add props to. A Properties object - * will be created if null. - * @return props - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - rrAttributes.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(getPropertyPrefix()); - props.setProperty(prefix + NUM_RINGS_PROPERTY, Integer.toString(numRings)); - props.setProperty(prefix + UNITS_PROPERTY, units.getAbbr()); - - return props; - } - - /** - * Return property info metadata for this PropertyConsumer. - * - * @param list Properties to add to, may be null. - * @return Properties for this object. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list = rrAttributes.getPropertyInfo(list); - list.setProperty(NUM_RINGS_PROPERTY, "Number of range rings to be drawn (minimum=1; default=3)."); - list.setProperty(UNITS_PROPERTY, "Units of ring distance"); - list.setProperty(initPropertiesProperty, UNITS_PROPERTY + " " + NUM_RINGS_PROPERTY); - - return list; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/SelectMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/SelectMouseMode.java deleted file mode 100644 index 53d25b884..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/SelectMouseMode.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/SelectMouseMode.java,v $ -// $RCSfile: SelectMouseMode.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * The SelectMouseMode delegates handling of mouse events to the - * listeners. This MouseMode type is ideal for Layers that want to - * receive MouseEvents. The simplest way to set this up is for the - * Layer to implement the MapMouseListener interface, and indicate - * that it wants to receive events when the mouse mode is the - * SelectMouseMode. Here's a code snippet for a Layer that would do - * this:

- * - *

- * public MapMouseListener getMapMouseListener() {
- *     return this;
- * }
- * 
- * public String[] getMouseModeServiceList() {
- *     return new String[] { SelectMouseMode.modeID };
- * }
- * 
- *

- * This class is functionally the same as the AbstractMouseMode, - * except that it actually calls the fire methods in the - * MapMouseSupport object to propagate the events. - */ -public class SelectMouseMode extends CoordMouseMode { - - /** - * Mouse Mode identifier, which is "Gestures". This is returned on - * getID() - */ - public final static transient String modeID = "Gestures"; - - /** - * Construct a SelectMouseMode. Default constructor. Sets the ID - * to the modeID, and the consume mode to true. - */ - public SelectMouseMode() { - this(true); - } - - /** - * Construct a SelectMouseMode. The constructor that lets you set - * the consume mode. - * - * @param consumeEvents the consume mode setting. - */ - public SelectMouseMode(boolean consumeEvents) { - this(modeID, consumeEvents); - } - - /** - * Construct a SelectMouseMode. The constructor that lets you set - * the consume mode. - * - * @param id the id for the mouse mode. - * @param consumeEvents the consume mode setting. - */ - public SelectMouseMode(String id, boolean consumeEvents) { - super(id, consumeEvents); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/UndoEvent.java b/src/core/src/main/java/com/bbn/openmap/event/UndoEvent.java deleted file mode 100644 index f780f2ef4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/UndoEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ -package com.bbn.openmap.event; - -/** - * An UndoEvent is an object that contains everything needed to reset its source - * back to a specific state. Used by the UndoStack. This event is used by the - * UndoStack to tell other objects to undo/redo - go to a certain state. The - * events that tell the UndoStack to make these notifications are regular - * ActionEvents, not these. - * - * @author ddietrick - */ -public interface UndoEvent { - - /** - * @return a short description of what will happen when setState() is - * invoked. - */ - String getDescription(); - - /** - * Tell the UndoEvent to set its source object back to the state described by - * this object. - */ - void setState(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/UndoStack.java b/src/core/src/main/java/com/bbn/openmap/event/UndoStack.java deleted file mode 100644 index e8938dbab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/UndoStack.java +++ /dev/null @@ -1,272 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStack.java,v $ -// $RCSfile: ProjectionStack.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.EmptyStackException; -import java.util.Stack; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; - -/** - * Provides a stack of actions that can be undone/redone. The UndoEvent objects - * contain the information needed to implement the actions. The UndoStack is - * told to push UndoEvents on their source objects by UndoStackTriggers using a - * regular ActionListener/ActionEvent mechanism. The UndoStack is an - * ActionListener to the triggers (GUI buttons/menu items that say Undo or - * Redo). - */ -public class UndoStack - extends OMComponent - implements ActionListener { - - private final static Logger logger = Logger.getLogger("com.bbn.openmap.event.UndoStack"); - - public final static int DEFAULT_MAX_SIZE = 10; - public final static int REMEMBER_ALL = -1; - - /** - * The notion of the current state is important. When the user does - * something, a component that is interested in undo/redo should push a - * current state to this stack. This current state reflects the state of - * some object at the current time. If another state gets set, then the old - * state is now put on the undo stack. If the undo command is given to this - * stack, then an event is popped off the undo stack, set to be the current - * state. The old state gets pushed to the redo stack. - */ - protected transient UndoEvent currentState; - - protected int stackSize = DEFAULT_MAX_SIZE; - - public final static transient String UndoCmd = "undo"; - public final static transient String RedoCmd = "redo"; - public final static transient String ClearUndoCmd = "clearUndoStack"; - public final static transient String ClearRedoCmd = "clearRedoStack"; - public final static transient String ClearCmd = "clearStacks"; - - protected final Stack undoStack; - protected final Stack redoStack; - - protected final UndoStackSupport triggers; - - /** - */ - public UndoStack() { - redoStack = new Stack(); - undoStack = new Stack(); - triggers = new UndoStackSupport(); - } - - /** - * Sets the current state of some object on the stack. The stack doesn't - * care what that event/state represents, since it has all the info needed - * to tell components how to get back to this state later. Anyway, this - * current state kinda hangs out in limbo. If another event/state comes in, - * the current state gets pushed on the undo stack. The redo stack gets - * cleared, since a new state path forward has been established. - * - * @param event - */ - public void setTheWayThingsAre(UndoEvent event) { - if (currentState != null) { - rememberLastThing(currentState); - } - currentState = event; - if (logger.isLoggable(Level.FINE)) { - logger.fine("making (" + currentState.getDescription() + ") current state"); - } - - // We have a new path forward, undefined, so clear out old path forward - redoStack.clear(); - fireStackStatus(); - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand().intern(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Received command: " + command); - } - - if (UndoCmd.equalsIgnoreCase(command) && undoStack != null && !undoStack.empty()) { - - undo(); - - } else if (RedoCmd.equalsIgnoreCase(command) && redoStack != null && !redoStack.empty()) { - - redo(); - - } else { - clearStacks((ClearUndoCmd.equalsIgnoreCase(command) || ClearCmd.equalsIgnoreCase(command)), - (ClearRedoCmd.equalsIgnoreCase(command) || ClearCmd.equalsIgnoreCase(command))); - } - } - - /** - * Put a new UndoEvent on the backStack, to remember for later in case we - * need to back up. - * - * @param event UndoEvent. - */ - protected synchronized void rememberLastThing(UndoEvent event) { - - if (undoStack.size() >= stackSize) { - undoStack.removeElementAt(0); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("remembering (" + event.getDescription() + ")"); - } - - undoStack.push(event); - } - - /** - * Take a UndoEvent off the backStack, and push it on the forward stack, and - * invoke the new currentState so the source component gets modified. - */ - protected synchronized void undo() { - if (currentState != null) { - while (redoStack.size() >= stackSize) { - redoStack.removeElementAt(0); - logger.info("making room for " + currentState.getDescription()); - } - - redoStack.push(currentState); - if (logger.isLoggable(Level.FINE)) { - logger.fine("making last current state (" + currentState.getDescription() + ") on redo stack"); - } - } - - currentState = undoStack.pop(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("making top undo state (" + currentState.getDescription() + ") current state"); - } - - if (currentState != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("calling setState on " + currentState.getDescription()); - } - currentState.setState(); - } - - fireStackStatus(); - } - - /** - * Take a UndoEvent off the forwardStack, and push it on the backStack. - */ - protected synchronized void redo() { - if (currentState != null) { - while (undoStack.size() >= stackSize) { - undoStack.removeElementAt(0); - } - - undoStack.push(currentState); - } - - currentState = redoStack.pop(); - - if (currentState != null) { - currentState.setState(); - } - - fireStackStatus(); - } - - /** - * Clear out the chosen undo stacks and fire an event to update the triggers - * on stack status. Also sets the current state, which isn't held by either - * stack, to null. - * - * @param clearUndoStack clear out the undo stack. - * @param clearRedoStack clear out the redo stack. - */ - public synchronized void clearStacks(boolean clearUndoStack, boolean clearRedoStack) { - - if (clearUndoStack && undoStack != null) { - undoStack.clear(); - } - - if (clearRedoStack && redoStack != null) { - redoStack.clear(); - } - - currentState = null; - - fireStackStatus(); - } - - public void fireStackStatus() { - if (triggers != null) { - UndoEvent undoEvent = getWhatWillHappenNextFromStack(undoStack); - UndoEvent redoEvent = getWhatWillHappenNextFromStack(redoStack); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("back enabled: " + (undoEvent != null) + ", forward enabled: " + (redoEvent != null)); - } - triggers.fireStackStatus(undoEvent, redoEvent); - } - } - - protected UndoEvent getWhatWillHappenNextFromStack(Stack stack) { - UndoEvent nextThing = null; - try { - nextThing = stack.peek(); - } catch (EmptyStackException ese) { - // Noop, event will stay null, that's OK and acceptable. - } - return nextThing; - } - - /** - * UndoStackTriggers should call this method to add themselves for stack - * notifications, and all will be well. - */ - public void addUndoStackTrigger(UndoStackTrigger trigger) { - trigger.addActionListener(this); - - UndoEvent undoEvent = getWhatWillHappenNextFromStack(undoStack); - UndoEvent redoEvent = getWhatWillHappenNextFromStack(redoStack); - - triggers.add(trigger); - - trigger.updateUndoStackStatus(undoEvent, redoEvent); - } - - /** - * UndoStackTriggers should call this method to remove themselves from stack - * notifications, and all will be well. - */ - public void removeUndoStackTrigger(UndoStackTrigger trigger) { - trigger.removeActionListener(this); - if (triggers != null) { - triggers.remove(trigger); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/UndoStackSupport.java b/src/core/src/main/java/com/bbn/openmap/event/UndoStackSupport.java deleted file mode 100644 index 25682f36d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/UndoStackSupport.java +++ /dev/null @@ -1,118 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStackSupport.java,v $ -// $RCSfile: ProjectionStackSupport.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.event; - -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This is a utility class that can be used by beans that need support for - * notifying gui components that undo/redo actions are available. Use an - * instance of this class as a member field of your bean and delegate work to - * it. Used by the UndoStack. - */ -public class UndoStackSupport - implements java.io.Serializable { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.event.UndoStackSupport"); - transient private ArrayList triggers; - - /** - * Construct a ProjectionStackSupport. - */ - public UndoStackSupport() { - } - - /** - * Add a ProjectionStackTrigger. - * - * @param pt ProjectionStackTrigger - */ - public synchronized void add(UndoStackTrigger pt) { - if (triggers == null) { - triggers = new ArrayList(); - } - - if (!triggers.contains(pt)) { - triggers.add(pt); - } - } - - /** - * Remove a ProjectionStackTrigger. - * - * @param pt ProjectionStackTrigger - */ - public synchronized void remove(UndoStackTrigger pt) { - if (triggers == null) { - return; - } - triggers.remove(pt); - } - - /** - * Return a cloned list of Triggers. - * - * @return Vector of triggers, null if none have been added. - */ - public synchronized ArrayList getTriggers() { - if (triggers == null) { - return null; - } - - return (ArrayList) triggers.clone(); - } - - public int size() { - if (triggers == null) { - return 0; - } - return triggers.size(); - } - - /** - * Send a status to all registered triggers. - * - * @param undoEvent the next event for undo, so the GUI can be updated with - * what will happen on undo. - * @param redoEvent the next event for redo, so the GUI can be updated with - * what will happen on redo. - */ - public void fireStackStatus(UndoEvent undoEvent, UndoEvent redoEvent) { - - ArrayList targets = getTriggers(); - - if (triggers == null) { - return; - } - - for (UndoStackTrigger target : targets) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("target is: " + target); - } - - target.updateUndoStackStatus(undoEvent, redoEvent); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/UndoStackTrigger.java b/src/core/src/main/java/com/bbn/openmap/event/UndoStackTrigger.java deleted file mode 100644 index b3d0b38c9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/UndoStackTrigger.java +++ /dev/null @@ -1,53 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStackTrigger.java,v $ -// $RCSfile: ProjectionStackTrigger.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:23 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -import java.awt.event.ActionListener; - -/** - * Provides Stack input by firing UndoCmd and RedoCmd commands, which cause - * updates to whatever component described by the UndoEvent. - */ -public interface UndoStackTrigger { - - /** - * Add an ActionListener for events that trigger events to shift the - * undo/redo stack. - */ - public void addActionListener(ActionListener al); - - /** - * Remove an ActionListener that receives events that trigger events to shift - * the undo/redo stack. - */ - public void removeActionListener(ActionListener al); - - /** - * To receive a status to let the trigger know if any projections in the - * forward or backward stacks exist, possibly to disable any gui widgets. - * - * @param undoEvent there is at least one event to undo. - * @param redoEvent there is at least one event to redo. - */ - public void updateUndoStackStatus(UndoEvent undoEvent, UndoEvent redoEvent); -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/ZoomEvent.java b/src/core/src/main/java/com/bbn/openmap/event/ZoomEvent.java deleted file mode 100644 index ad6539e37..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ZoomEvent.java +++ /dev/null @@ -1,109 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ZoomEvent.java,v $ -// $RCSfile: ZoomEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 17:37:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * An event to request that the map zoom in or out. Event specifies - * the type and amount of zoom of the map. - */ -public class ZoomEvent extends java.util.EventObject implements - java.io.Serializable { - /** - * Type that specifies that the amount should be used as a multiplier to the - * current scale. - */ - public transient static final int RELATIVE = 301; - - /** - * Type that specifies that the amount should be used as the new scale. - */ - public transient static final int ABSOLUTE = 302; - - /** - * The type of zooming. - */ - protected int type; - - /** - * The zoom factor. - */ - protected float amount; - - /** - * Construct a ZoomEvent. - * - * @param source the creator of the ZoomEvent. - * @param type the type of the event, referring to how to use the - * amount. - * @param amount the value of the ZoomEvent. - */ - public ZoomEvent(Object source, int type, float amount) { - super(source); - switch (type) { - case RELATIVE: - case ABSOLUTE: - break; - default: - throw new IllegalArgumentException("Invalid type: " + type); - } - this.type = type; - this.amount = amount; - } - - /** - * Check if the type is RELATIVE. - * - * @return boolean - */ - public boolean isRelative() { - return (type == RELATIVE); - } - - /** - * Check if the type is ABSOLUTE. - * - * @return boolean - */ - public boolean isAbsolute() { - return (type == ABSOLUTE); - } - - /** - * Get the amount of zoom. - * - * @return float - */ - public float getAmount() { - return amount; - } - - /** - * Stringify the object. - * - * @return String - */ - public String toString() { - return "#"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ZoomListener.java b/src/core/src/main/java/com/bbn/openmap/event/ZoomListener.java deleted file mode 100644 index 0b6c6e871..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ZoomListener.java +++ /dev/null @@ -1,30 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ZoomListener.java,v $ -// $RCSfile: ZoomListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - -/** - * Listens for requests to zoom the map in and out. - */ -public interface ZoomListener extends java.util.EventListener { - public void zoom(ZoomEvent evt); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/ZoomMouseMode.java b/src/core/src/main/java/com/bbn/openmap/event/ZoomMouseMode.java deleted file mode 100644 index 225f6a277..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ZoomMouseMode.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Booz|Allen|Hamilton - * 8283 Greensboro Dr. - * McLean, VA 22102-3888 - * - * This software was developed by Booz | Allen | Hamilton. - * - * @author Richard B. Lane - */ -package com.bbn.openmap.event; - -import java.awt.Color; -import java.awt.Transparency; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * This mouse mode responds to a double click with an animation effect of - * zooming in the map. - */ -public class ZoomMouseMode - extends CoordMouseMode { - protected double squareWidth = 50; - public final static transient String modeID = "Zoom"; - protected MapBean theMap = null; - - public ZoomMouseMode() { - super(modeID, true); - } - - /** - * Process a mouseClicked event. - * - * @param e mouse event. - */ - public void mouseClicked(MouseEvent e) { - if (e.getSource() instanceof MapBean) { - final int currX = e.getX(); - final int currY = e.getY(); - theMap = (MapBean) e.getSource(); - if (e.getClickCount() == 2) { - if (e.getButton() == 1) { - int squareCenterX = currX; - int squareCenterY = currY; - - double aspect = (double) theMap.getHeight() / (double) theMap.getWidth(); - double squareWidth = this.squareWidth; - double squareHeight = this.squareWidth; - if (aspect > 1) { - squareHeight *= aspect; - } else { - squareWidth /= aspect; - } - int squareUpperLeftX = squareCenterX - ((int) squareWidth / 2); - int squareUpperLeftY = squareCenterY - ((int) squareHeight / 2); - - if (squareUpperLeftX < 1) { - squareUpperLeftX = 1; - squareCenterX = (int) (squareUpperLeftX + squareWidth / 2); - } else if (squareUpperLeftX + squareWidth >= theMap.getWidth()) { - squareUpperLeftX = (int) (theMap.getWidth() - squareWidth - 1); - squareCenterX = (int) (squareUpperLeftX + squareWidth / 2); - } - if (squareUpperLeftY < 1) { - squareUpperLeftY = 1; - squareCenterY = (int) (squareUpperLeftY + squareHeight / 2); - } else if (squareUpperLeftY + squareHeight >= theMap.getHeight()) { - squareUpperLeftY = (int) (theMap.getHeight() - squareHeight - 1); - squareCenterY = (int) (squareUpperLeftY + squareHeight / 2); - } - Projection proj = theMap.getProjection(); - Point2D upperLeft = proj.inverse(squareUpperLeftX, squareUpperLeftY, new LatLonPoint.Double()); - Point2D lowerRight = - proj.inverse(squareUpperLeftX + (int) (squareWidth), squareUpperLeftY + (int) (squareHeight), - new LatLonPoint.Double()); - Point2D center = proj.inverse(squareCenterX, squareCenterY); - double necessaryScale = proj.getScale(upperLeft, lowerRight, proj.forward(upperLeft), proj.forward(lowerRight)); - final Projection newProj = - theMap.getProjectionFactory().makeProjection(proj.getClass(), center, (float) necessaryScale, - theMap.getWidth(), theMap.getHeight()); - - Thread delayThread = new Thread() { - public void run() { - theMap.setProjection(newProj); - } - }; - - java.awt.image.BufferedImage bi = - theMap.getGraphicsConfiguration().createCompatibleImage(theMap.getWidth(), theMap.getHeight(), - Transparency.OPAQUE); - theMap.paintAll(bi.getGraphics()); - java.awt.image.BufferedImage bi2 = - bi.getSubimage(squareUpperLeftX, squareUpperLeftY, (int) squareWidth, (int) squareHeight); - java.awt.image.BufferedImage square = - new java.awt.image.BufferedImage((int) squareWidth, (int) squareHeight, - java.awt.image.BufferedImage.TYPE_INT_RGB); - square.getGraphics().drawImage(bi2, 0, 0, (int) squareWidth, (int) squareHeight, null); - square.getGraphics().setColor(new Color(0, 255, 0, 255)); - square.getGraphics().drawRect(0, 0, square.getWidth() - 1, square.getHeight() - 1); - delayThread.start(); - double iterations = 10; - double widthIncrease = theMap.getWidth() - squareWidth; - double heightIncrease = theMap.getHeight() - squareHeight; - double widthInc = widthIncrease / iterations; - double heightInc = heightIncrease / iterations; - double leftInc = squareUpperLeftX / iterations; - double upInc = squareUpperLeftY / iterations; - - for (int i = 0; i < iterations + 1; i++) { - theMap.getGraphics(true).drawImage(square, squareUpperLeftX - (int) (leftInc * i), - squareUpperLeftY - (int) (upInc * i), - (int) squareWidth + (int) (widthInc * i), - (int) squareHeight + (int) (heightInc * i), null); - try { - Thread.sleep(50); - } catch (Exception ex) { - } - } - } - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/event/ZoomSupport.java b/src/core/src/main/java/com/bbn/openmap/event/ZoomSupport.java deleted file mode 100644 index dbb064e4a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/ZoomSupport.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/event/ZoomSupport.java,v $ -// $RCSfile: ZoomSupport.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.event; - - -/** - * This is a utility class that can be used by beans that need support - * for handling ZoomListeners and firing ZoomEvents. You can use an - * instance of this class as a member field of your bean and delegate - * work to it. - */ -public class ZoomSupport extends ListenerSupport { - - /** - * Construct a ZoomSupport. - * - * @param sourceBean The bean to be given as the source for any - * events. - */ - public ZoomSupport(Object sourceBean) { - super(sourceBean); - } - - /** - * Send a zoom event to all registered listeners. - * - * @param zoomType Either ZoomEvent.RELATIVE or ZoomEvent.ABSOLUTE - * @param amount The new scale if ABSOLUTE, the multiplier if - * RELATIVE - */ - public void fireZoom(int zoomType, float amount) { - - if (!((zoomType == ZoomEvent.RELATIVE) || (zoomType == ZoomEvent.ABSOLUTE))) { - throw new IllegalArgumentException("Bad value, " + zoomType - + " for zoomType in " + "ZoomSupport.fireZoom()"); - } - - if (isEmpty()) - return; - - ZoomEvent evt = new ZoomEvent(source, zoomType, amount); - - for (ZoomListener listener : this) { - listener.zoom(evt); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/event/package.html b/src/core/src/main/java/com/bbn/openmap/event/package.html deleted file mode 100644 index aa59f674e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/event/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides the various event object and listener interfaces for using - the MapBean. - - diff --git a/src/core/src/main/java/com/bbn/openmap/geo/BoundaryCrossing.java b/src/core/src/main/java/com/bbn/openmap/geo/BoundaryCrossing.java deleted file mode 100644 index d0f611407..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/BoundaryCrossing.java +++ /dev/null @@ -1,315 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: BoundaryCrossing.java,v $ -//$Revision: 1.5 $ -//$Date: 2007/02/13 20:02:13 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * The BoundaryCrossing class represents a location where a path - * crosses a region. Since a location can represent a region being - * left and a region being entered, you can ask it for the out - * GeoRegion and the in GeoRegion. Both won't be null at the same - * time, but either may be. - * - * @author dietrick - */ -public class BoundaryCrossing { - - /** - * The Geo location of the crossing. - */ - protected Geo geo; - /** - * The GeoRegion that is being entered. - */ - protected GeoRegion in; - /** - * The GeoRegion that is being exited. - */ - protected GeoRegion out; - - /** - * Creates the BoundaryCrossing. The getCrossings() factory method - * will result in BoundaryCrossings being created. - * - * @param p The Geo location - * @param r the GeoRegion being entered/exited - * @param goinin whether the path is goin' in to the region. - */ - protected BoundaryCrossing(Geo p, GeoRegion r, boolean goinin) { - geo = p; - if (goinin) { - in = r; - } else { - out = r; - } - } - - public Geo getGeo() { - return geo; - } - - public GeoRegion getIn() { - return in; - } - - public GeoRegion getOut() { - return out; - } - - /** - * The main factory method to create BoundaryCrossings. Provides a - * BoundaryCrossing.Collector so that crossing points can be - * retrieved, as well as an iterator over regions intersected. - * - * @param path GeoPath to travel over - * @param regions An ExtentIndex filled with GeoRegions. - * @return BoundaryCrossing.Collector - */ - public static Collector getCrossings(GeoPath path, Collection regions) { - Collector collector = new Collector(); - CrossingIntersection crossings = new CrossingIntersection(collector); - crossings.consider(path, regions); - return collector; - } - - /** - * A Collector is an object that organizes boundary crossings, as - * discovered by CrossingIntersection class. - * - * @author dietrick - */ - public static class Collector extends MatchCollector.SetMatchCollector { - - List crossings = new ArrayList(10); - List lastSegmentCrossingList; - Geo lastSegmentStartingPoint; - - public Collector() {} - - /** - * Add a BoundaryCrossing to the collection of crossings. - * - * @param bc - */ - protected void addCrossing(BoundaryCrossing bc) { - crossings.add(bc); - } - - /** - * Add a BoundaryCrossing associated with a segment and - * region. This is the main thinkin' method, called by the - * CrossingInspector with lists of crossings. This method - * organizes and orders BorderCrossings according to the - * segment order of the path that caused the crossings. - * - * @param c A list of Geos that a segement intersects with a - * region. - * @param segment GeoSegment - * @param region GeoRegion - */ - protected void addCrossing(Collection c, GeoSegment segment, - GeoRegion region) { - - // We need to get all the BorderCrossings from the current - // segment all together, across regions and place them in - // order. So if the segments matches with the previous - // segment, we need to hold off add them to the crossings - // list until a segment is complete. - - // Compact will probably have to look a the - // currentSegmentList to add any leftovers. - Geo start = segment.getSeg()[0]; - - if (lastSegmentCrossingList != null - && lastSegmentStartingPoint.distance(start) > 0) { - // The last segment is complete, need to order the BC - // on the list and add them to the crossings. - crossings.addAll(lastSegmentCrossingList); - lastSegmentCrossingList.clear(); - } else if (lastSegmentCrossingList == null) { - lastSegmentCrossingList = new ArrayList(10); - } - - // The ordered list is for temporarily holding points for - // the current segment as they are placed in the right - // order. - LinkedList orderedList = new LinkedList(); - // Everything in the lastSegmentCrossingList has already - // be ordered relative to what's already been searched, so - // we can just add them now to place the new points around - // them accordingly. Also, the lastSegmentCrossingList - // holds BoundaryCrossing objects, and the collection - // passed into this function doesn't have those yet. - orderedList.addAll(lastSegmentCrossingList); - // Clear out the lastSegmetnCrossingList, we'll replenish - // it with the ordered list at the end, so it will be - // ready for the next cycle. - lastSegmentCrossingList.clear(); - - for (Geo current : c) { - double curDist = start.distance(current); - // We just assume that crossing point is going into - // the current region, we'll check later to make sure. - BoundaryCrossing currentBC = new BoundaryCrossing(current, region, true); - - int lastCheckedIndex = 0; - BoundaryCrossing lastChecked = null; - for (BoundaryCrossing bcToBeChecked : orderedList) { - if (curDist < start.distance(bcToBeChecked.geo)) { - lastChecked = bcToBeChecked; - break; - } - lastCheckedIndex++; - } - - if (lastChecked != null) { - orderedList.add(lastCheckedIndex, currentBC); - } else { - orderedList.add(currentBC); - } - } - - boolean goinin = !Intersection.isPointInPolygon(start, - region.getPoints()); - for (BoundaryCrossing bc : orderedList) { - boolean sameRegion = (bc.in == region); - - if (sameRegion) { - if (!goinin) - bc.out = bc.in; - goinin = !goinin; - } - - lastSegmentCrossingList.add(bc); - } - - // OK, remember at this point that the BoundaryCrossing - // Objects have be.in set to their region, and some have - // region.out set if the boundary reflects an outward - // motion. We're going to resolve this in compact(); - - lastSegmentStartingPoint = start; - } - - /** - * An important method that cleans up the segment/region - * BoundaryCrossing order, and also resolves the - * BoundaryCrossing.in/out settings for regions. Must be - * called before the crossing iterator is retrieved, but the - * BoundaryCrossing method does that. - */ - protected void compact() { - if (lastSegmentCrossingList != null - && !lastSegmentCrossingList.isEmpty()) { - crossings.addAll(lastSegmentCrossingList); - lastSegmentCrossingList.clear(); - lastSegmentCrossingList = null; - } - - Object[] bc = crossings.toArray(); - crossings = new ArrayList(bc.length); - - BoundaryCrossing current, previous = null; - - for (int i = 0; i < bc.length; i++) { - current = (BoundaryCrossing) bc[i]; - - if (previous != null - && previous.geo.distance(current.geo) == 0.0) { - // If the distances between points are zero, it's - // a border crossing and we want to merge these - // into one point, with the bc.out pointer marking - // the region being left, and the bc.in marking - // the receiving region. - if (previous.out != null) - previous.in = current.in; - if (current.out != null) { - previous.out = current.out; - } - - continue; - } else { - // First point or if the distance between points - // is not zero, if the bc.out is set, then we - // should set the bc.in to null, just to indicate - // that the point reflects a crossing from outside - // any other region into that particular region. - if (current.out != null) { - current.in = null; - } - } - - crossings.add(current); - previous = current; - } - } - - public Iterator getCrossings() { - compact(); - return crossings.iterator(); - } - - } - - /** - * A Intersection class that knows how to call - * BoundaryCrossing.Collector to keep track of the path's - * relationship with the regions. - */ - public static class CrossingIntersection extends Intersection { - - public CrossingIntersection(Collector collector) { - super(new MatchFilter.ExactMF(), collector); - } - - /** - * Calls Intersection.isSegmentNearRegion() to see if segment - * is near the region. We're going to assume that this is - * going to be called with segments ordered as they appear in - * the path, in case the path is kinda crazy, and then we can - * keep track of the crossings in the right order. - */ - public boolean considerSegmentXRegion(GeoSegment segment, - GeoRegion region) { - List hits = Intersection.segmentNearPoly(segment, - region.getPoints(), - 0.0); - - if (hits != null) { - ((Collector) collector).addCrossing(hits, segment, region); - return true; - } - - return false; - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/BoundingCircle.java b/src/core/src/main/java/com/bbn/openmap/geo/BoundingCircle.java deleted file mode 100644 index 9b66b1793..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/BoundingCircle.java +++ /dev/null @@ -1,161 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: BoundingCircle.java,v $ -//$Revision: 1.10 $ -//$Date: 2008/07/20 05:46:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - - -/** - * Interface that describes a bounding circle around a given point on - * a sphere. - */ -public interface BoundingCircle { - - /** - * Returns a Geo representing the center of the circle. - * - * @return Geo - */ - public Geo getCenter(); - - /** - * @return the radius of the bounding circle in radians. - */ - public double getRadius(); - - /** - * @return whether this bounding circle intersects with another. - */ - public boolean intersects(BoundingCircle bc); - - /** - * @return whether this bounding circle intersects with a Geo with a radius (radians) around it. - */ - public boolean intersects(Geo g, double radius); - - /** - * A simple implementation of BoundingCircle, storing the center - * and radius as data members. - */ - public static class Impl implements BoundingCircle { - private Geo center; // center of circle - private double radius; // angle (in radians) to edge - - public Impl(Geo center, double radius) { - init(center, radius); - } - - public Impl(GeoArray arrayPoints) { - init(arrayPoints); - } - - public Impl(GeoPath path) { - init(path.getPoints()); - } - - public Impl(Geo[] gs) { - init(gs); - } - - /** - * Works by computing the centroid, then finding the - * largest radius. This will not, in general, produce the - * minimal bounding circle. - */ - protected void init(Geo[] region) { - Geo c = Intersection.center(region); // centroid - - double r = 0.0; - int length = region.length; - for (int i = 0; i < length; i++) { - double pr = c.distance(region[i]); - if (pr > r) { - r = pr; - } - } - - init(c, r); - } - - /** - * Works by computing the centroid, then finding the - * largest radius. This will not, in general, produce the - * minimal bounding circle. - */ - protected void init(GeoArray region) { - Geo c = Intersection.center(region, new Geo()); // centroid - Geo storage = new Geo(); - double r = 0.0; - int length = region.getSize(); - for (int i = 0; i < length; i++) { - double pr = c.distance(region.get(i, storage)); - if (pr > r) { - r = pr; - } - } - - init(c, r); - } - - protected void init(Geo center, double radius) { - this.center = center; - this.radius = radius; - } - - public final Geo getCenter() { - return center; - } - - public final double getRadius() { - return radius; - } - - public boolean intersects(BoundingCircle bc) { - return intersects(bc.getCenter(), bc.getRadius()); - } - - public boolean intersects(Geo g, double r) { - return this.center.distance(g) <= (getRadius() + r); - } - - public String toString() { - return "BoundingCircle: center(" + center + ") with radius (" + radius + ")"; - } - - public static BoundingCircle createFromLatLonDegrees(double[] latlons) { - return new BoundingCircle.Impl(GeoArray.Double.createFromLatLonDegrees(latlons)); - } - - public static BoundingCircle createFromLatLonDegrees(float[] latlons) { - return new BoundingCircle.Impl(GeoArray.Float.createFromLatLonDegrees(latlons)); - } - - public static BoundingCircle createFromLatLonRadians(double[] latlons) { - return new BoundingCircle.Impl(GeoArray.Double.createFromLatLonRadians(latlons)); - } - - public static BoundingCircle createFromLatLonRadians(float[] latlons) { - return new BoundingCircle.Impl(GeoArray.Float.createFromLatLonRadians(latlons)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/geo/ConvexHull.java b/src/core/src/main/java/com/bbn/openmap/geo/ConvexHull.java deleted file mode 100644 index ffeac7e0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/ConvexHull.java +++ /dev/null @@ -1,248 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ConvexHull.java,v $ -//$Revision: 1.5 $ -//$Date: 2008/04/15 21:51:01 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Stack; -import java.util.TreeSet; - -/** - * This class contains static methods that can be used to create convex hull - * GeoRegions from arrays of Geos. The only algorithm implemented is Graham's, - * where the highest point is selected (called the pivot), the other points are - * sorted according to their relative azimuths from the pivot, and then a path - * is created around the other points. Any right turn encountered traversing the - * points means that point should be skipped when creating the convex hull. - * - * @author dietrick - */ -public class ConvexHull { - private ConvexHull() {} - - /** - * Using Graham's scan. - * - * @param geos - * @return GeoRegion outlining the convex hull of the geos - */ - public static final GeoRegion getRegion(Geo[] geos) { - Geo[] regionGeos = hull(geos); - return new GeoRegion.Impl(regionGeos); - } - - /** - * Using Graham's scan. - * - * @param geos - * @return a convex hull of the geos - */ - public static final Geo[] hull(Geo[] geos) { - return hull(geos, 0); - } - - /** - * Using Graham's scan. - * - * @param geos - * @param tolerance the distance between points where they would be - * considered equals, in radians. - * @return a convex hull of the geos - */ - public static final Geo[] hull(Geo[] geos, double tolerance) { - Geo pivot = findHighest(geos); - TreeSet sortedGeos = new TreeSet(new PivotAngleComparator(pivot)); - for (int i = 0; i < geos.length; i++) { - Geo g = geos[i]; - if (g != pivot) { - sortedGeos.add(g); - } - } - - Stack hullStack = new Stack(); - hullStack.push(pivot); - - Geo gCross, midCross = null; - Geo geo = null, endGeo = null, midGeo = null; - - Iterator sortedGeoIt = sortedGeos.iterator(); - if (sortedGeoIt.hasNext()) { - midGeo = (Geo) sortedGeoIt.next(); - - while (midGeo.distance(pivot) == 0 && sortedGeoIt.hasNext()) { - midGeo = (Geo) sortedGeoIt.next(); - } - } - - Geo lastGeoRead = midGeo; - - while (sortedGeoIt.hasNext() && midGeo != null) { - geo = (Geo) sortedGeoIt.next(); - double dist = geo.distance(lastGeoRead); - if (dist <= tolerance) { - // Debug.output("Skipping duplicate geo"); - continue; - } - - endGeo = (Geo) hullStack.peek(); - - midCross = endGeo.crossNormalize(midGeo); - gCross = midGeo.crossNormalize(geo); - Geo i = gCross.crossNormalize(midCross).antipode(); - - // Debug.output("Evaluating:\n\tendGeo: " + endGeo + "\n\tmidGeo: " - // + midGeo + "\n\tto " + geo - // + "\n ****** intersection point: " + i); - - if (midGeo.distance(i) < Math.PI / 2) { - // Debug.output("+++++++++++++ midGeo to hull"); - - // left turn, OK for hull - hullStack.push(midGeo); - endGeo = midGeo; - midGeo = geo; - - } else { - - // right turn, need to backtrack - while (hullStack.size() > 1) { - - // Debug.output("-------- midGeo dropped"); - - midGeo = (Geo) hullStack.pop(); - endGeo = (Geo) hullStack.peek(); - - midCross = endGeo.crossNormalize(midGeo); - gCross = midGeo.crossNormalize(geo); - i = gCross.crossNormalize(midCross).antipode(); - - // Debug.output("Evaluating:\n\tendGeo: " + endGeo - // + "\n\tmidGeo: " + midGeo + "\n\tto " + geo - // + "\n ****** intersection point: " + i); - - if (midGeo.distance(i) < Math.PI / 2) { - - // Debug.output("+++++++++++++ midGeo to hull"); - - hullStack.push(midGeo); - midGeo = geo; - break; - } - } - } - - lastGeoRead = geo; - } - - if (midGeo != null) { - hullStack.push(midGeo); - } - - hullStack.push(pivot); - - Geo[] regionGeos = new Geo[hullStack.size()]; - - int i = 0; - // Need to reverse order to get inside of poly on the right side of - // line. - while (!hullStack.isEmpty()) { - regionGeos[i++] = (Geo) hullStack.pop(); - } - - return regionGeos; - } - - protected static Geo findHighest(Geo[] geos) { - Geo ret = null; - double highest = Double.NEGATIVE_INFINITY; - for (int i = 0; i < geos.length; i++) { - double lat = geos[i].getLatitude(); - if (lat > highest) { - highest = lat; - ret = geos[i]; - } - } - return ret; - } - - // XXX: does this need to be serializable? - protected static final class PivotAngleComparator implements Comparator, - Serializable { - private Geo pivot; - - public PivotAngleComparator(Geo pivot) { - this.pivot = pivot; - } - - public int compare(Object obj1, Object obj2) { - double ang1 = Double.MAX_VALUE, ang2 = Double.MAX_VALUE; - int ret = 0; - - if (obj1 instanceof Geo) { - ang1 = Math.toDegrees(pivot.azimuth((Geo) obj1)); - } - - if (obj2 instanceof Geo) { - ang2 = Math.toDegrees(pivot.azimuth((Geo) obj2)); - } - - // ts1 is the one being tested/added to the TreeSet, so we - // want later items with the same time being added after - // previous items in the file with the same time. - - if (ang1 < ang2) { - ret = 1; - } else if (ang1 >= ang2) { - ret = -1; - } - - return ret; - } - - public Geo getPivot() { - return pivot; - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - if (obj instanceof PivotAngleComparator) { - return pivot.equals(((PivotAngleComparator) obj).pivot); - } else { - return false; - } - } - - public int hashCode() { - return pivot.hashCode(); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndex.java b/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndex.java deleted file mode 100644 index 0f6decc4d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndex.java +++ /dev/null @@ -1,577 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ExtentIndex.java,v $ -//$Revision: 1.4 $ -//$Date: 2007/02/13 20:02:09 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; - -/** - * A Collection of Regions that supports indexed subsets. That is, in addition - * to acting like a normal collection, it also allows getting an iterator that - * will return a superset of all intersecting regions that is a subset of the - * whole collection. - * - * @author mthome@bbn.com - */ -public interface ExtentIndex extends java.util.Collection { - /** - * report on the maximum horizontalRange supported by this index. - */ - double indexHorizontalRange(); - - /** - * Add a extent to the index. - * - * @param region - * @return true if Region successfully added, false if not. - */ - boolean addExtent(GeoExtent region); - - /** - * Remove a region from the index. - * - * @param region - * @return true if the region was found and removed. - */ - boolean removeExtent(GeoExtent region); - - /** - * Resets the index to an empty state. - */ - void clear(); - - /** - * return an iterator listing a subset of the whole collection that is a - * superset of the actual matches. A valid (but inefficient) implementation - * would return an iterator over the whole collection. - * - * Implementation should match anything that is likely to match - this will - * generally include, for instance, additional space around the actual - * segment to accommodate buffer zones around the segment. - */ - Iterator iterator(GeoExtent extent); - - /** - * A basic implementation of ExtentIndex that uses Collection-typed buckets. - * Extending classes must implement #makeBucket(int) to specify an - * alternative Collection implementation. - */ - abstract class AbstractExtentIndex extends java.util.AbstractCollection - implements ExtentIndex { - - /** - * Default value for #nbuckets if not specified in the call to the - * constructor. - */ - public static final int D_NBUCKETS = 360; - - /** - * Default value for #margin if not specified in the call to the - * constructor. - */ - public static final double D_MARGIN = 0.0; - - /** - * how many buckets in the longitudinal index - 360 means 1 bucket per - * degree of longitude. More than 360 doesn't seem to add much search - * speed, less than 180 makes it slower. The sweet spot on current - * datasets is somewhere in between. - * - * If unspecified, defaults to #D_NBUCKETS - */ - public final int nbuckets; - - /** - * how much of a margin to put around regions for indexing purposes, in - * nautical miles. This must be at least the largest margin searched for - * by route (currently 50nmiles) - the larger this value, the larger the - * average entries/bucket and so, the slower the search. - * - * If unspecified, defaults to #D_MARGIN - */ - public final double margin; - - protected final Collection buckets[]; - - /** all is a collection of everything successfully indexed. */ - protected final Collection all; - /** - * polar is a bucket for anything that is near enough to either pole to - * cover more than 1/2 the buckets. - */ - protected final Collection polar; - - protected final Collection discarded; - - public AbstractExtentIndex() { - this(D_NBUCKETS, D_MARGIN); - } - - public AbstractExtentIndex(int nb) { - this(nb, D_MARGIN); - } - - public AbstractExtentIndex(double m) { - this(D_NBUCKETS, m); - } - - public AbstractExtentIndex(int nb, double m) { - nbuckets = nb; - margin = m; - buckets = new Collection[nbuckets]; - all = makeBucket(2000); - polar = makeBucket(); - discarded = makeBucket(); - } - - protected final Collection makeBucket() { - return makeBucket(0); - } - - /** - * implement to specify the factory to use to create Bucket storage. - * - * @param sizeHint a guess at the number of elements that are likely to - * be stored in this bucket or 0 if unknown. - * @return A Collection instance suitable for use as a bucket - * - */ - abstract protected Collection makeBucket(int sizeHint); - - /** - * Add an object to the index. - * - * @return true if object is a GeoExtent and was added. - */ - public boolean add(GeoExtent o) { - if (o instanceof GeoExtent) { - return addExtent((GeoExtent) o); - } else { - return false; - } - } - - /** - * Method to call to add Region object with BoundingCircle to Collection - * and organize it for later retrieval. - * - * @param extent Region to index - * @return true if object added, false if it's been discarded. - */ - public boolean addExtent(GeoExtent extent) { - boolean ret = false; - try { - - BoundingCircle bc = extent.getBoundingCircle(); - if (bc == null) { - discarded.add(extent); - return false; - } - - Geo center = bc.getCenter(); - double clon = center.getLongitude(); - double clat = center.getLatitude(); - double rnm = Geo.nm(bc.getRadius()); - - if ((clat == 90.0 && clon == -180.0) || rnm >= 90 * 60) { - discarded.add(extent); - } else { - all.add(extent); // add to the everything list - - // we need to project the radius away from the - // center at the latitude, NOT at the equator! - double latfactor = Geo.npdAtLat(clat); - if (latfactor == 0) { - polar.add(extent); - ret = true; - } else { - double xd = (rnm + margin) / latfactor; - /* - * margin = xd "extra degrees" at the center's latitude - */ - if (xd >= 45) { - polar.add(extent); - ret = true; - } else { - double[] lons = normalizeLons(new double[] { - clon - xd, clon + xd }); - int lb = bucketFor(lons[0]); - int rb = bucketFor(lons[1]); - if (rb < lb) - rb += nbuckets; - for (int i = lb; i <= rb; i++) { - int x = i % nbuckets; - Collection b = buckets[x]; - if (b == null) { - b = makeBucket(5); - buckets[x] = b; - } - b.add(extent); - ret = true; - } - } - } - } - } catch (Exception e) { - } - return ret; - } - - /** normalize longitude to be at least 0.0 and less than 360 * */ - protected static final double normalizeLon(double lon) { - // put it into the range of [-360.0, +360.0] - double n = lon % 360; - return (n < 0.0) ? n + 360.0 : n; - // now n is (0.0,+360] - } - - /** - * figure out what bucket a particular longitude goes in. - */ - protected final int bucketFor(double lon) { - return (int) Math.floor(normalizeLon(lon) / 360.0 - * (double) nbuckets); - } - - /* - * Normalize and sort the argument two element array so that on a - * north-up globe, a great-circle arc between the points is headed - * eastward and is less than half-way around the world. @param lons - * two-element array on longitudes @return the mutated argument. - */ - protected final static double[] normalizeLons(double[] lons) { - double a = normalizeLon(lons[0]); - double b = normalizeLon(lons[1]); - // if wide and east or narrow and west, swap - if ((Math.abs(b - a) > 180.0) == (b > a)) { - lons[0] = b; - lons[1] = a; - } else { - lons[0] = a; - lons[1] = b; - } - return lons; - } - - /** - * Called when you want everything in each bucket between the - * coordinates. - * - * @param left left-most (west) bucket value. - * @param right right-most (east) bucket value. - * @return Iterator over regions in buckets that cover range provided. - */ - protected Iterator lookup(double left, double right) { - return lookup(left, right, null); - } - - /** - * Called when you want to get the regions in the buckets, but you want - * to further filter on objects that can intersect based on the bounding - * circle provided. - * - * @param left left-most (west) bucket value. - * @param right right-most (east) bucket value. - * @param bc Bounding circle to do another filter check, if null, - * everything in a bucket will be returned. - * @return Iterator over regions in buckets that cover range provided - * that intersect with the BoundingCircle (if one is provided). - */ - protected Iterator lookup(double left, double right, BoundingCircle bc) { - Collection s = null; - int lb = bucketFor(left); - int rb = bucketFor(right); - if (rb < lb) - rb += nbuckets; - for (int i = lb; i <= rb; i++) { - Collection b = buckets[i % nbuckets]; - if (b != null) { - if (bc == null) { - if (s == null) { - s = new HashSet(); - } - s.addAll(b); - } else { - for (GeoExtent region : b) { - if (bc.intersects(region.getBoundingCircle())) { - if (s == null) { - s = new HashSet(); - } - s.add(region); - } - } - } - } - } - if (!polar.isEmpty()) { - if (s == null) { - s = new HashSet(); - } - s.addAll(polar); // add all the polar regions, just in case - } - if (s == null) { - return new HashSet().iterator(); - } else { - return s.iterator(); - } - } - - /** - * Method to call to remove a region from the index. - * - * @return true if the region was found and removed. - */ - public boolean removeExtent(GeoExtent region) { - boolean ret = false; - BoundingCircle bc = region.getBoundingCircle(); - if (bc == null) { - return discarded.remove(region); - } - - Geo center = bc.getCenter(); - double clon = center.getLongitude(); - double clat = center.getLatitude(); - double rnm = Geo.nm(bc.getRadius()); - - if ((clat == 90.0 && clon == -180.0) || rnm >= 90 * 60) { - discarded.remove(region); - } else { - all.remove(region); // remove from the everything list - - // we need to project the radius away from the - // center at the latitude, NOT at the equator! - double latfactor = Geo.npdAtLat(clat); - if (latfactor == 0) { - ret = ret || polar.remove(region); - } else { - double xd = (rnm + margin) / latfactor; - /* - * margin = xd "extra degrees" at the center's latitude - */ - if (xd >= 45) { - ret = ret || polar.remove(region); - } else { - double[] lons = normalizeLons(new double[] { clon - xd, - clon + xd }); - int lb = bucketFor(lons[0]); - int rb = bucketFor(lons[1]); - if (rb < lb) - rb += nbuckets; - for (int i = lb; i <= rb; i++) { - int x = i % nbuckets; - Collection b = buckets[x]; - if (b != null) { - ret = ret || b.remove(region); - if (b.isEmpty()) { - buckets[x] = null; - } - } - } - } - } - } - return ret; - } - - /** - * Method to call to clear out the index. - */ - public void clear() { - all.clear(); - polar.clear(); - discarded.clear(); - for (int i = 0; i < buckets.length; i++) { - if (buckets[i] != null) { - buckets[i].clear(); - } - } - } - - /** - * RegionIndex parameter method. - * - * @return horizontal range in nautical miles for matches. - */ - public double indexHorizontalRange() { - return margin; - } - - public Iterator lookupBySegment(GeoSegment segment) { - Geo[] pts = segment.getSeg(); - double[] lons = normalizeLons(new double[] { pts[0].getLongitude(), - pts[1].getLongitude() }); - return lookup(lons[0], lons[1], segment.getBoundingCircle()); - } - - public Iterator lookupByPath(GeoPath path) { - Collection results = null; - Iterator pit = path.segmentIterator(); - while (pit.hasNext()) { - GeoSegment seg = pit.next(); - for (Iterator it = lookupBySegment(seg); it.hasNext();) { - if (results == null) { - results = new HashSet(); - } - results.add(it.next()); - } - } - if (results == null) { - return new HashSet().iterator(); - } else { - return results.iterator(); - } - } - - public Iterator lookupByBoundingCircle(BoundingCircle bc) { - double cLon = bc.getCenter().getLongitude(); - double rNM = Geo.nm(bc.getRadius()); // radius in nm at - // equator - double npd = Geo.npdAtLat(bc.getCenter().getLatitude()); - if (npd == 0) { // avoid divide by zero - polar region - return iterator(); - } else { - double rdeg = rNM / npd; - if (rdeg >= 180) { - return iterator(); // radius covers the whole world - } else { - return lookup(cLon - rdeg, cLon + rdeg, bc); - } - } - } - - /** - * @return an Iterator over BoundingCircle objects in the Collection - * where the GExtent may be related to them. - */ - public Iterator iterator(GeoExtent o) { - if (o instanceof GeoSegment) { - return lookupBySegment((GeoSegment) o); - } else if (o instanceof GeoRegion) { - // It's important that GeoRegion be tested before GeoPath, - // because the GeoPath will catch GeoRegions, and doing the - // lookup by path for a region may cause the lookup to fail for - // extents near the center of the region (outside of the - // bounding circles of the region's segments). - return lookupByBoundingCircle(o.getBoundingCircle()); - } else if (o instanceof GeoPath) { - return lookupByPath((GeoPath) o); - } else if (o instanceof GeoPoint) { - return lookupByBoundingCircle(new BoundingCircle.Impl(((GeoPoint) o).getPoint(), 0)); - } else { - return lookupByBoundingCircle(o.getBoundingCircle()); - } - } - - /** - * @return Iterator over all entries in Collection. - */ - public Iterator iterator() { - return all.iterator(); - } - - /** - * @return number of all entries in Collection. - */ - public int size() { - return all.size(); - } - - // - // metrics - // - - public String toString() { - int entc = 0; - int empties = 0; - for (int i = 0; i < nbuckets; i++) { - Collection l = buckets[i]; - if (l != null) { - entc += l.size(); - } else { - empties++; - } - } - - return this.getClass().getName() + "[" + size() + " -" - + discarded.size() + " E" + (entc / ((float) nbuckets)) - + "] e(" + empties + ")"; - } - } - - class HashSetExtentIndexImpl extends AbstractExtentIndex { - public HashSetExtentIndexImpl() { - this(D_NBUCKETS, D_MARGIN); - } - - public HashSetExtentIndexImpl(int nb) { - this(nb, D_MARGIN); - } - - public HashSetExtentIndexImpl(double m) { - this(D_NBUCKETS, m); - } - - public HashSetExtentIndexImpl(int nb, double m) { - super(nb, m); - } - - protected Collection makeBucket(int sizeHint) { - if (sizeHint != 0) { - return new HashSet(); - } else { - return new HashSet(sizeHint); - } - } - } - - class ArrayListExtentIndexImpl extends AbstractExtentIndex { - public ArrayListExtentIndexImpl() { - this(D_NBUCKETS, D_MARGIN); - } - - public ArrayListExtentIndexImpl(int nb) { - this(nb, D_MARGIN); - } - - public ArrayListExtentIndexImpl(double m) { - this(D_NBUCKETS, m); - } - - public ArrayListExtentIndexImpl(int nb, double m) { - super(nb, m); - } - - protected Collection makeBucket(int sizeHint) { - if (sizeHint != 0) { - return new ArrayList(); - } else { - return new ArrayList(sizeHint); - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndexImpl.java b/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndexImpl.java deleted file mode 100644 index e2671ba10..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/ExtentIndexImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ExtentIndexImpl.java,v $ -//$Revision: 1.5 $ -//$Date: 2006/08/22 16:42:54 $ -//$Author: mthome $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -/** - * Separable indexed database for Regional BoundingCircles. This is - * currently a simple longitude coverage map of the world, broken into - * buckets covering 1 degrees. A given BoundingCircle will show up in - * every bucket that it touches or comes within the margin. - *

- * This class is now a trivial extension of ExtentIndex.ArrayListExtentIndexImpl, which - * should probably be used instead. - */ -public class ExtentIndexImpl extends ExtentIndex.ArrayListExtentIndexImpl { - public ExtentIndexImpl() { - this(D_NBUCKETS, D_MARGIN); - } - - public ExtentIndexImpl(int nb) { - this(nb, D_MARGIN); - } - - public ExtentIndexImpl(double m) { - this(D_NBUCKETS, m); - } - - public ExtentIndexImpl(int nb, double m) { - super(nb, m); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/geo/Geo.java b/src/core/src/main/java/com/bbn/openmap/geo/Geo.java deleted file mode 100644 index 033c365b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/Geo.java +++ /dev/null @@ -1,1253 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; - -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.MoreMath; - -/** - * A class that represents a point on the Earth as a three dimensional unit - * length vector, rather than latitude and longitude. For the theory and an - * efficient implementation using partial evaluation see: - * http://openmap.bbn.com/~kanderso/lisp/performing-lisp/essence.ps - * - * This implementation matches the theory carefully, but does not use partial - * evaluation. - * - *

- * For the area calculation see: http://math.rice.edu/~pcmi/sphere/ - * - * @author Ken Anderson - * @author Sachin Date - * @author Ben Lubin - * @author Michael Thome - * @version $Revision: 1.30 $ on $Date: 2007/02/13 20:02:14 $ - */ -@SuppressWarnings("serial") -public class Geo implements Serializable { - - /*************************************************************************** - * Constants for the shape of the earth. see - * http://www.gfy.ku.dk/%7Eiag/HB2000/part4/groten.htm - **************************************************************************/ - // Replaced by Length constants. - // public static final double radiusKM = 6378.13662; // in KM. - // public static final double radiusNM = 3443.9182; // in NM. - // Replaced with WGS 84 constants - // public static final double flattening = 1.0/298.25642; - public static final double flattening = 1.0 / 298.257223563; - public static final double FLATTENING_C = (1.0 - flattening) * (1.0 - flattening); - - public static final double METERS_PER_NM = 1852; - private static final double NPD_LTERM1 = 111412.84 / METERS_PER_NM; - private static final double NPD_LTERM2 = -93.5 / METERS_PER_NM; - private static final double NPD_LTERM3 = 0.118 / METERS_PER_NM; - - private double x; - private double y; - private double z; - - /** - * Compute nautical miles per degree at a specified latitude (in degrees). - * Calculation from NIMA: http://pollux.nss.nima.mil/calc/degree.html - */ - public final static double npdAtLat(double latdeg) { - double lat = Math.toRadians(latdeg); - return (NPD_LTERM1 * Math.cos(lat) + NPD_LTERM2 * Math.cos(3 * lat) + NPD_LTERM3 - * Math.cos(5 * lat)); - } - - /** Convert from geographic to geocentric latitude (radians) */ - public static double geocentricLatitude(double geographicLatitude) { - return Math.atan((Math.tan(geographicLatitude) * FLATTENING_C)); - } - - /** Convert from geocentric to geographic latitude (radians) */ - public static double geographicLatitude(double geocentricLatitude) { - return Math.atan(Math.tan(geocentricLatitude) / FLATTENING_C); - } - - /** Convert from degrees to radians. */ - public static double radians(double degrees) { - return Length.DECIMAL_DEGREE.toRadians(degrees); - } - - /** Convert from radians to degrees. */ - public static double degrees(double radians) { - return Length.DECIMAL_DEGREE.fromRadians(radians); - } - - /** Convert radians to kilometers. * */ - public static double km(double radians) { - return Length.KM.fromRadians(radians); - } - - /** Convert kilometers to radians. * */ - public static double kmToAngle(double km) { - return Length.KM.toRadians(km); - } - - /** Convert radians to nauticalMiles. * */ - public static double nm(double radians) { - return Length.NM.fromRadians(radians); - } - - /** Convert nautical miles to radians. * */ - public static double nmToAngle(double nm) { - return Length.NM.toRadians(nm); - } - - public Geo() { - } - - /** - * Construct a Geo from its latitude and longitude. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - */ - public Geo(double lat, double lon) { - initialize(lat, lon); - } - - /** - * Construct a Geo from its latitude and longitude. - * - * @param lat latitude. - * @param lon longitude. - * @param isDegrees should be true if the lat/lon are specified in decimal - * degrees, false if they are radians. - */ - public Geo(double lat, double lon, boolean isDegrees) { - if (isDegrees) { - initialize(lat, lon); - } else { - initializeRadians(lat, lon); - } - } - - /** Construct a Geo from its parts. */ - public Geo(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - /** Construct a Geo from another Geo. */ - public Geo(Geo geo) { - this(geo.x, geo.y, geo.z); - } - - public static final Geo makeGeoRadians(double latr, double lonr) { - double rlat = geocentricLatitude(latr); - double c = Math.cos(rlat); - return new Geo(c * Math.cos(lonr), c * Math.sin(lonr), Math.sin(rlat)); - } - - public static final Geo makeGeoDegrees(double latd, double lond) { - return makeGeoRadians(radians(latd), radians(lond)); - } - - public static final Geo makeGeo(double x, double y, double z) { - return new Geo(x, y, z); - } - - public static final Geo makeGeo(Geo p) { - return new Geo(p.x, p.y, p.z); - } - - /** - * Initialize this Geo to match another. - * - * @param g - */ - public void initialize(Geo g) { - x = g.x; - y = g.y; - z = g.z; - } - - /** - * Initialize this Geo with new parameters. - * - * @param x - * @param y - * @param z - */ - public void initialize(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - /** - * Initialize this Geo with to represent coordinates. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - */ - public void initialize(double lat, double lon) { - initializeRadians(radians(lat), radians(lon)); - } - - /** - * Initialize this Geo with to represent coordinates. - * - * @param lat latitude in radians. - * @param lon longitude in radians. - */ - public void initializeRadians(double lat, double lon) { - double rlat = geocentricLatitude(lat); - double c = Math.cos(rlat); - x = c * Math.cos(lon); - y = c * Math.sin(lon); - z = Math.sin(rlat); - } - - /** - * Find the midpoint Geo between this one and another on a Great Circle line - * between the two. The result is undefined of the two points are antipodes. - * - * @param g2 - * @return midpoint Geo. - */ - public Geo midPoint(Geo g2) { - return add(g2).normalize(); - } - - /** - * Find the midpoint Geo between this one and another on a Great Circle line - * between the two. The result is undefined of the two points are antipodes. - * - * @param g2 - * @param ret a Geo value to set returned values in. Do not pass in a null - * value. - * @return midpoint Geo. - */ - public Geo midPoint(Geo g2, Geo ret) { - return add(g2).normalize(ret); - } - - public Geo interpolate(Geo g2, double x) { - return scale(x).add(g2.scale(1 - x)).normalize(); - } - - /** - * - * @param g2 - * @param x - * @param ret Do not pass in a null value. - * @return ret, or new Geo set at distance between g2 and this one. - */ - public Geo interpolate(Geo g2, double x, Geo ret) { - return scale(x).add(g2.scale(1 - x, ret), ret).normalize(ret); - } - - public String toString() { - return "Geo[" + getLatitude() + "," + getLongitude() + "]"; - } - - public double getLatitude() { - return degrees(geographicLatitude(Math.atan2(z, Math.sqrt(x * x + y * y)))); - } - - public double getLongitude() { - return degrees(Math.atan2(y, x)); - } - - public double getLatitudeRadians() { - return geographicLatitude(Math.atan2(z, Math.sqrt(x * x + y * y))); - } - - public double getLongitudeRadians() { - return Math.atan2(y, x); - } - - /** - * Reader for x, in internal axis representation (positive to the right side - * of screen). - * - * @return x - */ - public final double x() { - return this.x; - } - - /** - * Reader for y in internal axis representation (positive into screen). - * - * @return y - */ - public final double y() { - return this.y; - } - - /** - * Reader for z in internal axis representation (positive going to top of - * screen). - * - * @return z - */ - public final double z() { - return this.z; - } - - public void setLength(double r) { - // It's tempting to call getLatitudeRadians() here, but it changes the - // angle. I think we want to keep the angles the same, and just extend - // x, y, z, and then let the latitudes get refigured out for the - // ellipsoid when they are asked for. - double rlat = Math.atan2(z, Math.sqrt(x * x + y * y)); - double rlon = getLongitudeRadians(); - - double c = r * Math.cos(rlat); - x = c * Math.cos(rlon); - y = c * Math.sin(rlon); - z = r * Math.sin(rlat); - } - - /** North pole. */ - public static final Geo north = new Geo(0.0, 0.0, 1.0); - - /** Dot product. Gives you the cos of the angle between this point and b. */ - public double dot(Geo b) { - return (this.x() * b.x() + this.y() * b.y() + this.z() * b.z()); - } - - /** Dot product. Gives you the cos of the angle between the two points. */ - public static double dot(Geo a, Geo b) { - return (a.x() * b.x() + a.y() * b.y() + a.z() * b.z()); - } - - /** Euclidian length. */ - public double length() { - return Math.sqrt(this.dot(this)); - } - - /** Multiply this by s. * */ - public Geo scale(double s) { - return scale(s, new Geo()); - } - - /** - * Multiply this by s. - * - * @return ret that was passed in, filled in with scaled values. Do not pass - * in a null value. - */ - public Geo scale(double s, Geo ret) { - ret.initialize(this.x() * s, this.y() * s, this.z() * s); - return ret; - } - - /** Returns a unit length vector parallel to this. */ - public Geo normalize() { - return this.scale(1.0 / this.length()); - } - - /** - * Returns a unit length vector parallel to this. - * - * @return ret with normalized values. Do not pass in a null value. - */ - public Geo normalize(Geo ret) { - return this.scale(1.0 / this.length(), ret); - } - - /** Vector cross product. */ - public Geo cross(Geo b) { - return cross(b, new Geo()); - } - - /** - * Vector cross product. Gives you the point 90 degrees from the great - * circle line between this point and b. The side of the line depends on the - * right hand rule. - * - * @return ret Do not pass in a null value. - */ - public Geo cross(Geo b, Geo ret) { - ret.initialize(this.y() * b.z() - this.z() * b.y(), this.z() * b.x() - this.x() * b.z(), this.x() - * b.y() - this.y() * b.x()); - return ret; - } - - /** Equivalent to this.cross(b).length(). */ - public double crossLength(Geo b) { - double x = this.y() * b.z() - this.z() * b.y(); - double y = this.z() * b.x() - this.x() * b.z(); - double z = this.x() * b.y() - this.y() * b.x(); - return Math.sqrt(x * x + y * y + z * z); - } - - /** Equivalent to this.cross(b).normalize(). */ - public Geo crossNormalize(Geo b) { - return crossNormalize(b, new Geo()); - } - - /** - * Equivalent to this.cross(b).normalize(). - * - * @return ret Do not pass in a null value. - */ - public Geo crossNormalize(Geo b, Geo ret) { - double x = this.y() * b.z() - this.z() * b.y(); - double y = this.z() * b.x() - this.x() * b.z(); - double z = this.x() * b.y() - this.y() * b.x(); - double L = Math.sqrt(x * x + y * y + z * z); - - ret.initialize(x / L, y / L, z / L); - return ret; - } - - /** - * Equivalent to this.cross(b).normalize(). - * - * @return ret Do not pass in a null value. - */ - public static Geo crossNormalize(Geo a, Geo b, Geo ret) { - return a.crossNormalize(b, ret); - } - - /** Returns this + b. */ - public Geo add(Geo b) { - return add(b, new Geo()); - } - - /** - * @return ret Do not pass in a null value. - */ - public Geo add(Geo b, Geo ret) { - ret.initialize(this.x() + b.x(), this.y() + b.y(), this.z() + b.z()); - return ret; - } - - /** Returns this - b. */ - public Geo subtract(Geo b) { - return subtract(b, new Geo()); - } - - /** - * Returns this - b. * - * - * @return ret Do not pass in a null value. - */ - public Geo subtract(Geo b, Geo ret) { - ret.initialize(this.x() - b.x(), this.y() - b.y(), this.z() - b.z()); - return ret; - } - - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof Geo)) { - return false; - } - - Geo v2 = (Geo) obj; - return MoreMath.approximately_equal(this.x, v2.x) - && MoreMath.approximately_equal(this.y, v2.y) - && MoreMath.approximately_equal(this.z, v2.z); - } - - /** Angular distance, in radians between this and v2. */ - public double distance(Geo v2) { - return Math.atan2(v2.crossLength(this), v2.dot(this)); - } - - /** Angular distance, in radians between v1 and v2. */ - public static double distance(Geo v1, Geo v2) { - return v1.distance(v2); - } - - /** Angular distance, in radians between the two lat lon points. */ - public static double distance(double lat1, double lon1, double lat2, double lon2) { - return Geo.distance(new Geo(lat1, lon1), new Geo(lat2, lon2)); - } - - /** Distance in kilometers. * */ - public double distanceKM(Geo v2) { - return km(distance(v2)); - } - - /** Distance in kilometers. * */ - public static double distanceKM(Geo v1, Geo v2) { - return v1.distanceKM(v2); - } - - /** Distance in kilometers. * */ - public static double distanceKM(double lat1, double lon1, double lat2, double lon2) { - return Geo.distanceKM(new Geo(lat1, lon1), new Geo(lat2, lon2)); - } - - /** Distance in nautical miles. * */ - public double distanceNM(Geo v2) { - return nm(distance(v2)); - } - - /** Distance in nautical miles. * */ - public static double distanceNM(Geo v1, Geo v2) { - return v1.distanceNM(v2); - } - - /** Distance in nautical miles. * */ - public static double distanceNM(double lat1, double lon1, double lat2, double lon2) { - return Geo.distanceNM(new Geo(lat1, lon1), new Geo(lat2, lon2)); - } - - /** - * Azimuth in radians from v2 to this. - * - * @param v2 other Geo - * @return radian angle between this and v2. Will also return NaN for - * identical points, or other Math conventions for resulting math - * results. - */ - public double strictAzimuth(Geo v2) { - /* - * n1 is the great circle representing the meridian of this. n2 is the - * great circle between this and v2. The azimuth is the angle between - * them but we specialized the cross product. - */ - // Geo n1 = north.cross(this); - // Geo n2 = v2.cross(this); - // crossNormalization is needed to geos of different length. - /* - * Geo n1 = north.crossNormalize(this); Geo n2 = - * v2.crossNormalize(this); double az = Math.atan2(-north.dot(n2), - * n1.dot(n2)); return (az > 0.0) ? az : 2.0 * Math.PI + az; - */ - - /** - * Not sure why the above algorithm doesn't work, although it seems like - * it doesn't. It's a off when the latitudes are further away from the - * equator. I've worked through the math, and it looks like it should - * work, but tests at 50 deg N reveal severe departure from results from - * other toolkits. -DFD - */ - - // Even though the GreatCircle class is based on the spherical model, - // this result is based on the ellipsoidal model because the latitudes - // have already been corrected for and flattened. - - // Taking the algorithm from the GreatCircle.sphericalAzimuth method - // directly, so that the omgeo.jar file won't depend on openmap.jar. - - double phi1 = this.getLatitudeRadians(); - double lambda0 = this.getLongitudeRadians(); - double phi = v2.getLatitudeRadians(); - double lambda = v2.getLongitudeRadians(); - - double ldiff = lambda - lambda0; - double cosphi = Math.cos(phi); - - double az = Math.atan2(cosphi * Math.sin(ldiff), (Math.cos(phi1) * Math.sin(phi) - Math.sin(phi1) - * cosphi * Math.cos(ldiff))); - - return (az >= 0.0) ? az : MoreMath.TWO_PI_D + az; - } - - /** - * Azimuth in radians from v2 to this. - * - * @param v2 other Geo - * @return radian angle between v2 and this, and zero instead of NaN if the - * two geos are identical. - */ - public double azimuth(Geo v2) { - double ret = strictAzimuth(v2); - if (Double.isNaN(ret)) { - return 0; - } - return ret; - } - - /** - * Given 3 points on a sphere, p0, p1, p2, return the angle between them in - * radians. - */ - public static double angle(Geo p0, Geo p1, Geo p2) { - return Math.PI - p0.cross(p1).distance(p1.cross(p2)); - } - - /** - * Computes the area of a polygon on the surface of a unit sphere given an - * enumeration of its point. For a non unit sphere, multiply this by the - * radius of sphere squared. Make sure the first point doesn't equal the - * last. - */ - public static double area(Enumeration vs) { - int count = 0; - double area = 0; - Geo v0 = vs.nextElement(); - Geo v1 = vs.nextElement(); - Geo p0 = v0; - Geo p1 = v1; - Geo p2 = null; - while (vs.hasMoreElements()) { - count++; - p2 = (Geo) vs.nextElement(); - area += angle(p0, p1, p2); - p0 = p1; - p1 = p2; - } - - count++; - p2 = v0; - area += angle(p0, p1, p2); - p0 = p1; - p1 = p2; - - count++; - p2 = v1; - area += angle(p0, p1, p2); - - return area - (count - 2) * Math.PI; - } - - /** - * Is the point, p, within radius radians of the great circle segment - * between this and v2? - */ - public boolean isInside(Geo v2, double radius, Geo p) { - // Allocate a Geo to be reused for all of these calculations, instead of - // creating 3 of them that are just thrown away. There's one more we - // still need to allocate, for dp below. - Geo tmp = new Geo(); - - /* - * gc is a unit vector perpendicular to the plane defined by v1 and v2 - */ - Geo gc = this.crossNormalize(v2, tmp); - - /* - * |gc . p| is the size of the projection of p onto gc (the normal of - * v1,v2) cos(pi/2-r) is effectively the size of the projection of a - * vector along gc of the radius length. If the former is larger than - * the latter, than p is further than radius from arc, so must not be - * isInside - */ - if (Math.abs(gc.dot(p)) > Math.cos((Math.PI / 2.0) - radius)) - return false; - - /* - * If p is within radius of either endpoint, then we know it isInside - */ - if (this.distance(p) <= radius || v2.distance(p) <= radius) - return true; - - /* d is the vector from the v2 to v1 */ - Geo d = v2.subtract(this, tmp); - - /* L is the length of the vector d */ - double L = d.length(); - - /* n is the d normalized to length=1 */ - Geo n = d.normalize(tmp); - - /* dp is the vector from p to v1 */ - Geo dp = p.subtract(this, new Geo()); - - /* size is the size of the projection of dp onto n */ - double size = n.dot(dp); - - /* p is inside iff size>=0 and size <= L */ - return (0 <= size && size <= L); - } - - /** - * do the segments v1-v2 and p1-p2 come within radius (radians) of each - * other? - */ - public static boolean isInside(Geo v1, Geo v2, double radius, Geo p1, Geo p2) { - return v1.isInside(v2, radius, p1) || v1.isInside(v2, radius, p2) - || p1.isInside(p2, radius, v1) || p1.isInside(p2, radius, v2); - } - - /** - * Static version of isInside uses conventional (decimal degree) - * coordinates. - */ - public static boolean isInside(double lat1, double lon1, double lat2, double lon2, - double radius, double lat3, double lon3) { - return (new Geo(lat1, lon1)).isInside(new Geo(lat2, lon2), radius, new Geo(lat3, lon3)); - } - - /** - * Is Geo p inside the time bubble along the great circle segment from this - * to v2 looking forward forwardRadius and backward backwardRadius. - */ - public boolean inBubble(Geo v2, double forwardRadius, double backRadius, Geo p) { - return distance(p) <= ((v2.subtract(this).normalize().dot(p.subtract(this)) > 0.0) ? forwardRadius - : backRadius); - } - - /** Returns the point opposite this point on the earth. */ - public Geo antipode() { - return this.scale(-1.0, new Geo()); - } - - /** - * Returns the point opposite this point on the earth. * - * - * @return ret Do not pass in a null value. - */ - public Geo antipode(Geo ret) { - return this.scale(-1.0, ret); - } - - /** - * Find the intersection of the great circle between this and q and the - * great circle normal to r. - *

- * - * That is, find the point, y, lying between this and q such that - * - *

-     * 
-     *  y = [x*this + (1-x)*q]*c
-     *  where c = 1/y.dot(y) is a factor for normalizing y.
-     *  y.dot(r) = 0
-     *  substituting:
-     *  [x*this + (1-x)*q]*c.dot(r) = 0 or
-     *  [x*this + (1-x)*q].dot(r) = 0
-     *  x*this.dot(r) + (1-x)*q.dot(r) = 0
-     *  x*a + (1-x)*b = 0
-     *  x = -b/(a - b)
-     * 
-     * 
- * - * We assume that this and q are less than 180 degrees appart. When this and - * q are 180 degrees appart, the point -y is also a valid intersection. - *

- * Alternatively the intersection point, y, satisfies y.dot(r) = 0 - * y.dot(this.crossNormalize(q)) = 0 which is satisfied by y = - * r.crossNormalize(this.crossNormalize(q)); - * - */ - public Geo intersect(Geo q, Geo r) { - return intersect(q, r, new Geo()); - } - - /** - * Find the intersection of the great circle between this and q and the - * great circle normal to r. - *

- * - * That is, find the point, y, lying between this and q such that - * - *

-     * 
-     *  y = [x*this + (1-x)*q]*c
-     *  where c = 1/y.dot(y) is a factor for normalizing y.
-     *  y.dot(r) = 0
-     *  substituting:
-     *  [x*this + (1-x)*q]*c.dot(r) = 0 or
-     *  [x*this + (1-x)*q].dot(r) = 0
-     *  x*this.dot(r) + (1-x)*q.dot(r) = 0
-     *  x*a + (1-x)*b = 0
-     *  x = -b/(a - b)
-     * 
-     * 
- * - * We assume that this and q are less than 180 degrees apart. When this and - * q are 180 degrees apart, the point -y is also a valid intersection. - *

- * Alternatively the intersection point, y, satisfies y.dot(r) = 0 - * y.dot(this.crossNormalize(q)) = 0 which is satisfied by y = - * r.crossNormalize(this.crossNormalize(q)); - * - * @return ret Do not pass in a null value. - */ - public Geo intersect(Geo q, Geo r, Geo ret) { - - // There used to be code in here that broke the intersection code. It - // was inserted into the 5.1 code, but I can't find a record of why. - // Reverting to the old code that still works, at least for the test - // cases we have. - - double a = this.dot(r); - double b = q.dot(r); - double x = -b / (a - b); - // This still results in one Geo being allocated and lost, in the - // q.scale call. - return this.scale(x, ret).add(q.scale(1.0 - x), ret).normalize(ret); - - } - - /** alias for computeCorridor(path, radius, radians(10), true) * */ - public static Geo[] computeCorridor(Geo[] path, double radius) { - return computeCorridor(path, radius, radians(10.0), true); - } - - /** - * Wrap a fixed-distance corridor around an (open) path, as specified by an - * array of Geo. - * - * @param path Open path, must not have repeated points or consecutive - * antipodes. - * @param radius Distance from path to widen corridor, in angular radians. - * @param err maximum angle of rounded edges, in radians. If 0, will - * directly cut outside bends. - * @param capp iff true, will round end caps - * @return a closed polygon representing the specified corridor around the - * path. - * - */ - public static Geo[] computeCorridor(Geo[] path, double radius, double err, boolean capp) { - if (path == null || radius <= 0.0) { - return new Geo[] {}; - } - // assert path!=null; - // assert radius > 0.0; - - int pl = path.length; - if (pl < 2) - return null; - - // final polygon will be right[0],...,right[n],left[m],...,left[0] - ArrayList right = new ArrayList((int) (pl * 1.5)); - ArrayList left = new ArrayList((int) (pl * 1.5)); - - Geo g0 = null; // previous point - Geo n0 = null; // previous normal vector - Geo l0 = null; - Geo r0 = null; - - Geo g1 = path[0]; // current point - - for (int i = 1; i < pl; i++) { - Geo g2 = path[i]; // next point - Geo n1 = g1.crossNormalize(g2); // n is perpendicular to the vector - // from g1 to g2 - n1 = n1.scale(radius); // normalize to radius - // these are the offsets on the g2 side at g1 - Geo r1b = g1.add(n1); - Geo l1b = g1.subtract(n1); - - if (n0 == null || g0 == null) { - if (capp && err > 0) { - // start cap - Geo[] arc = approximateArc(g1, l1b, r1b, err); - for (int j = arc.length - 1; j >= 0; j--) { - right.add(arc[j]); - } - } else { - // no previous point - we'll just be square - right.add(l1b); - left.add(r1b); - } - // advance normals - l0 = l1b; - r0 = r1b; - } else { - // otherwise, compute a more complex shape - - // these are the right and left on the g0 side of g1 - Geo r1a = g1.add(n0); - Geo l1a = g1.subtract(n0); - - double handed = g0.cross(g1).dot(g2); // right or left handed - // divergence - if (handed > 0) { // left needs two points, right needs 1 - if (err > 0) { - Geo[] arc = approximateArc(g1, l1b, l1a, err); - for (int j = arc.length - 1; j >= 0; j--) { - right.add(arc[j]); - } - } else { - right.add(l1a); - right.add(l1b); - } - l0 = l1b; - - Geo ip = Intersection.segmentsIntersect(r0, r1a, r1b, g2.add(n1)); - // if they intersect, take the intersection, else use the - // points and punt - if (ip != null) { - left.add(ip); - } else { - left.add(r1a); - left.add(r1b); - } - r0 = ip; - } else { - Geo ip = Intersection.segmentsIntersect(l0, l1a, l1b, g2.subtract(n1)); - // if they intersect, take the intersection, else use the - // points and punt - if (ip != null) { - right.add(ip); - } else { - right.add(l1a); - right.add(l1b); - } - l0 = ip; - if (err > 0) { - Geo[] arc = approximateArc(g1, r1a, r1b, err); - for (int j = 0; j < arc.length; j++) { - left.add(arc[j]); - } - } else { - left.add(r1a); - left.add(r1b); - } - r0 = r1b; - } - } - - // advance points - g0 = g1; - n0 = n1; - g1 = g2; - } - - // finish it off - Geo rn = g1.subtract(n0); - Geo ln = g1.add(n0); - if (capp && err > 0) { - // end cap - Geo[] arc = approximateArc(g1, ln, rn, err); - for (int j = arc.length - 1; j >= 0; j--) { - right.add(arc[j]); - } - } else { - right.add(rn); - left.add(ln); - } - - int ll = right.size(); - int rl = left.size(); - Geo[] result = new Geo[ll + rl]; - for (int i = 0; i < ll; i++) { - result[i] = (Geo) right.get(i); - } - int j = ll; - for (int i = rl - 1; i >= 0; i--) { - result[j++] = (Geo) left.get(i); - } - return result; - } - - /** simple vector angle (not geocentric!) */ - static double simpleAngle(Geo p1, Geo p2) { - return Math.acos(p1.dot(p2) / (p1.length() * p2.length())); - } - - /** - * compute a polygonal approximation of an arc centered at pc, beginning at - * p0 and ending at p1, going clockwise and including the two end points. - * - * @param pc center point - * @param p0 starting point - * @param p1 ending point - * @param err The maximum angle between approximates allowed, in radians. - * Smaller values will look better but will result in more returned - * points. - * @return Geo array of arc points - */ - public static final Geo[] approximateArc(Geo pc, Geo p0, Geo p1, double err) { - - double theta = angle(p0, pc, p1); - // if the rest of the code is undefined in this situation, just skip it. - if (Double.isNaN(theta)) { - return new Geo[] { p0, p1 }; - } - - int n = (int) (2.0 + Math.abs(theta / err)); // number of points - // (counting the end - // points) - Geo[] result = new Geo[n]; - result[0] = p0; - double dtheta = theta / (n - 1); - - double rho = 0.0; // angle starts at 0 (directly at p0) - - for (int i = 1; i < n - 1; i++) { - rho += dtheta; - // Rotate p0 around this so it has the right azimuth. - result[i] = Rotation.rotate(pc, 2.0 * Math.PI - rho, p0, new Geo()); - } - result[n - 1] = p1; - - return result; - } - - public final Geo[] approximateArc(Geo p0, Geo p1, double err) { - return approximateArc(this, p0, p1, err); - } - - /** @deprecated use #offset(double, double) */ - public Geo geoAt(double distance, double azimuth) { - return offset(distance, azimuth); - } - - /** - * Returns a Geo that is distance (radians), and azimuth (radians) away from - * this. this is undefined at the north pole, at which point "azimuth" is - * undefined. - * - * @param distance distance of this to the target point in radians. - * @param azimuth Direction of target point from this, in radians, clockwise - * from north. - * @return Geo at distance - */ - public Geo offset(double distance, double azimuth) { - return offset(distance, azimuth, new Geo()); - } - - /** - * Returns a Geo that is distance (radians), and azimuth (radians) away from - * this. This is undefined at the north pole, at which point "azimuth" is - * undefined. - * - * @param distance distance of this to the target point in radians. - * @param azimuth Direction of target point from this, in radians, clockwise - * from north. - * @return ret Do not pass in a null value. - */ - public Geo offset(double distance, double azimuth, Geo ret) { - // m is normal the the meridian through this. - Geo m = this.crossNormalize(north, ret); - // p is a point on the meridian distance distance from this. - // Geo p = (new Rotation(m, distance)).rotate(this); - Geo p = Rotation.rotate(m, distance, this, ret); - // Rotate p around this so it has the right azimuth. - return Rotation.rotate(this, 2.0 * Math.PI - azimuth, p, ret); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = 17; - long lx = Double.doubleToLongBits(x); - long ly = Double.doubleToLongBits(y); - long lz = Double.doubleToLongBits(z); - result = 31 * result + (int) (lx ^ (lx >>> 32)); - result = 31 * result + (int) (ly ^ (ly >>> 32)); - result = 31 * result + (int) (lz ^ (lz >>> 32)); - return result; - } - - public static Geo offset(Geo origin, double distance, double azimuth) { - return origin.offset(distance, azimuth); - } - - /** - * - * @param origin - * @param distance - * @param azimuth - * @param ret - * @return ret Do not pass in a null value. - */ - public static Geo offset(Geo origin, double distance, double azimuth, Geo ret) { - return origin.offset(distance, azimuth, ret); - } - - /* - * //same as offset, except using trig instead of vector mathematics public - * Geo trig_offset(double distance, double azimuth) { double latr = - * getLatitudeRadians(); double lonr = getLongitudeRadians(); - * - * double coslat = Math.cos(latr); double sinlat = Math.sin(latr); double - * cosaz = Math.cos(azimuth); double sinaz = Math.sin(azimuth); double sind - * = Math.sin(distance); double cosd = Math.cos(distance); - * - * return makeGeoRadians(Math.asin(sinlat * cosd + coslat * sind * cosaz), - * Math.atan2(sind * sinaz, coslat * cosd - sinlat * sind * cosaz) + lonr); - * } - */ - - // - // Follows are a series of Geo array operations as useful utilities - // - /** - * convert a String containing space-separated pairs of comma-separated - * decimal lat-lon pairs into a Geo array. - */ - public static Geo[] posToGa(String coords) { - return posToGa(coords.split(" ")); - } - - /** - * Convert an array of strings with comma-separated decimal lat,lon pairs - * into a Geo array - */ - public static Geo[] posToGa(String[] coords) { - // convert to floating lat/lon degrees - Geo[] ga = new Geo[coords.length]; - for (int i = 0; i < coords.length; i++) { - String[] ll = coords[i].split(","); - ga[i] = Geo.makeGeoDegrees(Double.parseDouble(ll[0]), Double.parseDouble(ll[1])); - } - return ga; - } - - /** - * Convert a Geo array into a floating point lat lon array (alternating lat - * and lon values). - * - * @return the ll array provided, or a new array of lla is null. - */ - public static double[] GaToLLa(Geo[] ga, double[] lla) { - if (lla == null) { - lla = new double[2 * ga.length]; - } - - for (int i = 0; i < ga.length; i++) { - Geo g = ga[i]; - lla[i * 2] = g.getLatitude(); - lla[i * 2 + 1] = g.getLongitude(); - } - return lla; - } - - /** - * Convert a Geo array into a floating point lat lon array (alternating lat - * and lon values). - * - * @return the ll array provided, or a new array of lla is null. - */ - public static float[] GaToLLa(Geo[] ga, float[] lla) { - if (lla == null) { - lla = new float[2 * ga.length]; - } - - for (int i = 0; i < ga.length; i++) { - Geo g = ga[i]; - lla[i * 2] = (float) g.getLatitude(); - lla[i * 2 + 1] = (float) g.getLongitude(); - } - return lla; - } - - /** - * Convert a Geo array into a floating point lat lon array (alternating lat - * and lon values) - */ - public static float[] GaToLLa(Geo[] ga) { - return GaToLLa(ga, new float[2 * ga.length]); - } - - /** - * Return a Geo array with the duplicates removed. May arbitrarily mutate - * the input array. - */ - public static Geo[] removeDups(Geo[] ga) { - Geo[] r = new Geo[ga.length]; - int p = 0; - for (int i = 0; i < ga.length; i++) { - if (p == 0 || !(r[p - 1].equals(ga[i]))) { - r[p] = ga[i]; - p++; - } - } - if (p != ga.length) { - Geo[] x = new Geo[p]; - System.arraycopy(r, 0, x, 0, p); - return x; - } else { - return ga; - } - } - - /** - * Convert a float array of alternating lat and lon pairs into a Geo array. - */ - public static Geo[] LLaToGa(float[] lla) { - return LLaToGa(lla, true); - } - - /** - * Convert a float array of alternating lat and lon pairs into a Geo array. - */ - public static Geo[] LLaToGa(float[] lla, boolean isDegrees) { - Geo[] r = new Geo[lla.length / 2]; - for (int i = 0; i < lla.length / 2; i++) { - if (isDegrees) { - r[i] = Geo.makeGeoDegrees(lla[i * 2], lla[i * 2 + 1]); - } else { - r[i] = Geo.makeGeoRadians(lla[i * 2], lla[i * 2 + 1]); - } - } - return r; - } - - /** - * Convert a double array of alternating lat and lon pairs into a Geo array. - */ - public static Geo[] LLaToGa(double[] lla) { - return LLaToGa(lla, true); - } - - /** - * Convert a double array of alternating lat and lon pairs into a Geo array. - */ - public static Geo[] LLaToGa(double[] lla, boolean isDegrees) { - Geo[] r = new Geo[lla.length / 2]; - for (int i = 0; i < lla.length / 2; i++) { - if (isDegrees) { - r[i] = Geo.makeGeoDegrees(lla[i * 2], lla[i * 2 + 1]); - } else { - r[i] = Geo.makeGeoRadians(lla[i * 2], lla[i * 2 + 1]); - } - } - return r; - } - - /** - * return a float array of alternating lat lon pairs where the first and - * last pair are the same, thus closing the path, by adding a point if - * needed. Does not mutate the input. - */ - public static float[] closeLLa(float[] lla) { - int l = lla.length; - int s = (l / 2) - 1; - if (lla[0] == lla[s * 2] && lla[1] == lla[s * 2 + 1]) { - return lla; - } else { - float[] llx = new float[l + 2]; - System.arraycopy(lla, 0, llx, 0, l); - llx[l] = lla[0]; - llx[l + 1] = lla[1]; - return llx; - } - } - - /** - * return a Geo array where the first and last elements are the same, thus - * closing the path, by adding a point if needed. Does not mutate the input. - */ - public static Geo[] closeGa(Geo[] ga) { - int l = ga.length; - if (ga[0].equals(ga[l - 1])) { - return ga; - } else { - Geo[] x = new Geo[l + 1]; - System.arraycopy(ga, 0, x, 0, l); - x[l] = ga[0]; - return x; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoArray.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoArray.java deleted file mode 100644 index 201df09d0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoArray.java +++ /dev/null @@ -1,682 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoArray.java,v $ -//$Revision: 1.2 $ -//$Date: 2007/02/13 20:02:10 $ -//$Author: dietrick $ -// -//********************************************************************** -package com.bbn.openmap.geo; - - -/** - * A GeoArray is a interface that represents a set of Geo information. Rather - * than keeping a set of Geo[] around and managing the memory for all of those - * objects, the GeoArray provides an object that just holds onto the coordinates - * of those points. - * - * @author dietrick - */ -public interface GeoArray { - - /** - * Get a Geo represented by the index i. - * - * @param i - * @return Geo at index i - */ - Geo get(int i); - - /** - * Load the values for Geo at index i into ret. - * - * @param i - * @param ret - * @return ret filled in with values at index i - */ - Geo get(int i, Geo ret); - - /** - * Get the number of Geo points represented by this array. - * - * @return number of geo points - */ - int getSize(); - - /** - * Convert the GeoArray to an array of Geos. - * - * @return Geo array from values - */ - Geo[] toPointArray(); - - /** - * Convert the GeoArray to an array of decimal degree values, alternating - * lat, lon, lat, lon. - * - * @return lat,lon array representing decimal degrees of points. - */ - double[] toLLDegrees(); - - /** - * Convert the GeoArray to an array of radian values, alternating lat, lon, - * lat, lon. - * - * @return lat, lon array representing radians for points. - */ - double[] toLLRadians(); - - /** - * @param index the index of the Geo in the GeoArray to compare. - * @param comp the Geo to compare to the indexed value. - * @return true of x, y, and z of the Geos match. - */ - boolean equals(int index, Geo comp); - - /** - * Returns the perpendicular distance to the closest point on the edge of the - * polygon. - * - * @param geo the point to test against the poly - * @param closestPoint will be filled with location of poly edge point closest to geo. - * @return the distance in radians - */ - double distance(Geo geo, Geo closestPoint); - - /** - * Compute the area of the GeoArray polygon on the surface of a unit sphere - * given an enumeration of its point. For a non unit sphere, multiply this by - * the radius of sphere squared. - * - * @return area value. - */ - double area(); - - /** - * Ensure that the Geo array starts and ends with the same values. Will - * replace the current coord array with one three floats longer if needed. - */ - void closeArray(); - - /** - * Modify, if needed, the Geo array with the duplicates removed. - */ - void removeDups(); - - /** - * A Mutable GeoArray is one where the points can be modified. - * - * @author dietrick - */ - public static interface Mutable - extends GeoArray { - - /** - * Set the values for the provided index to the values represented by g. - * - * @param i - * @param g - */ - void set(int i, Geo g); - - /** - * Set the values for the provided index to the values x, y, z, which are - * vector Geo values, *not* lat, lon and height. - * - * @param i - * @param x - * @param y - * @param z - */ - void set(int i, double x, double y, double z); - - /** - * Set the values for the provided index to the latitude, longitude. - * - * @param i - * @param lat - * @param lon - * @param isDegrees true if lat/lon in decimal degrees. - */ - void set(int i, double lat, double lon, boolean isDegrees); - } - - /** - * An abstract parent implementation class of GeoArray that handles common - * methods. - * - * @author dietrick - */ - public static abstract class Adapter - implements GeoArray { - - /** - * Convert the GeoArray to an array of Geos. - * - * @return Geo[] - */ - public Geo[] toPointArray() { - int size = getSize(); - Geo[] geos = new Geo[size]; - for (int i = 0; i < size; i++) { - geos[i] = get(i, new Geo()); - } - return geos; - } - - /** - * Convert the GeoArray to an array of decimal degree values, alternating - * lat, lon, lat, lon. - * - * @return lat/lon double[] of decimal degrees - */ - public double[] toLLDegrees() { - int size = getSize(); - double[] coords = new double[size * 2]; - Geo storage = new Geo(); - for (int i = 0; i < size; i++) { - get(i, storage); - int loc = i * 2; - coords[loc] = storage.getLatitude(); - coords[loc + 1] = storage.getLongitude(); - } - return coords; - } - - /** - * Convert the GeoArray to an array of radian values, alternating lat, - * lon, lat, lon. - * - * @return lat/lon double[] of radians - */ - public double[] toLLRadians() { - int size = getSize(); - double[] coords = new double[size * 2]; - Geo storage = new Geo(); - for (int i = 0; i < size; i++) { - get(i, storage); - int loc = i * 2; - coords[loc] = storage.getLatitudeRadians(); - coords[loc + 1] = storage.getLongitudeRadians(); - } - return coords; - } - - /** - * Computes the area of a polygon on the surface of a unit sphere. For a - * non unit sphere, multiply this by the radius of sphere squared. The - * value might be negative based on the counter-clockwise order of the - * coordinates, but the absolute value is valid. This method will test for - * closed polygon coordinates and handle that situation. - */ - public double area() { - int count = 0; - double area = 0; - Geo v0 = get(0, new Geo()); - Geo v1 = get(1, new Geo()); - Geo p0 = new Geo(v0); - Geo p1 = new Geo(v1); - Geo p2 = get(getSize() - 1, new Geo()); - // Having the first and last points the same messes up the - // algorithm. - // So skip the last point if it equals the first. - boolean closed = p0.equals(p2); - int size = getSize() - (closed ? 1 : 0); - for (int i = 2; i < size; i++) { - count++; - get(i, p2); - area += Geo.angle(p0, p1, p2); - p0.initialize(p1); - p1.initialize(p2); - } - - count++; - p2.initialize(v0); - area += Geo.angle(p0, p1, p2); - p0.initialize(p1); - p1.initialize(p2); - - count++; - p2.initialize(v1); - area += Geo.angle(p0, p1, p2); - - return area - ((count - 2) * Math.PI); - } - - /** - * Returns the perpendicular distance to the closest point on the edge of - * the polygon. - * - * @param pnt the point to test against the poly - * @param closestPoint if not null, will be set with the location of the - * point on the poly closest to pnt, you can read this object after - * this method call to get coordinates. - * @return the distance in radians, or Double.POSITIVE_INFINITY if - * something weird happens. - */ - public double distance(Geo pnt, Geo closestPoint) { - double ret = java.lang.Double.POSITIVE_INFINITY; - double testDist = ret; - int size = getSize(); - Geo p0 = get(0, new Geo()); - Geo p1 = new Geo(); - Geo intersect = new Geo(); - - for (int i = 1; i < size; i++) { - get(i, p1); - - // Don't want to do distance test if end points are the same. - if (p0.equals(p1)) { - continue; - } - - // The test needs to check two things - the distance between pnt and - // the great circle line between p1 and p2. It should also check to - // make sure that the perpendicular line intersects that great - // circle line between p0 and p1. We'll calculate the distance - // first, and then if the distance is the shortest seen so far, - // we'll test the distance between that intersection point and make - // sure that it's less than the distance between the two points. - - testDist = Intersection.pointCircleDistance(p0, p1, pnt); - System.out.println("testing " + p0 + ", " + p1 + ", getting distance of " + testDist); - - if (testDist < ret) { - // Find the point where the perpendicular line intersects the - // great circle - intersect = p0.intersect(p1, pnt, intersect); - System.out.println("candidate received, gc intersected at " + intersect); - - if (Intersection.isOnSegment(p0, p1, intersect)) { - // Shortest distance, and between points - ret = testDist; - if (closestPoint != null) { - closestPoint.initialize(intersect); - } - } - } - - // Move to next point in array. - p0.initialize(p1); - } - - return ret; - } - } - - /** - * An implementation of GeoArray and GeoArray.Mutable that contains - * float-precision values. Holds the coordinates in a float array of x, y, z, - * x, y, z values. - * - * @author dietrick - */ - public static class Float - extends Adapter - implements Mutable { - - private float[] coords; - - public Float(Geo[] geos) { - coords = new float[geos.length * 3]; - for (int i = 0; i < geos.length; i++) { - int loc = i * 3; - Geo geo = geos[i]; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - } - - public Float(GeoArray ga) { - int size = ga.getSize(); - coords = new float[size * 3]; - Geo geo = new Geo(); - for (int i = 0; i < size; i++) { - int loc = i * 3; - ga.get(i, geo); - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - } - - protected Float(float[] coords) { - this.coords = coords; - } - - public static Float createFromLatLonDegrees(float[] latlondeg) { - int numCoordSets = latlondeg.length / 2; - float[] coords = new float[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initialize(latlondeg[i * 2], latlondeg[i * 2 + 1]); - int loc = i * 3; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - - return new Float(coords); - } - - public static Float createFromLatLonDegrees(double[] latlondeg) { - int numCoordSets = latlondeg.length / 2; - float[] coords = new float[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initialize(latlondeg[i * 2], latlondeg[i * 2 + 1]); - int loc = i * 3; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - - return new Float(coords); - } - - public static Float createFromLatLonRadians(float[] latlonrad) { - int numCoordSets = latlonrad.length / 2; - float[] coords = new float[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initializeRadians(latlonrad[i * 2], latlonrad[i * 2 + 1]); - int loc = i * 3; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - - return new Float(coords); - } - - public static Float createFromLatLonRadians(double[] latlonrad) { - int numCoordSets = latlonrad.length / 2; - float[] coords = new float[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initializeRadians(latlonrad[i * 2], latlonrad[i * 2 + 1]); - int loc = i * 3; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - - return new Float(coords); - } - - public static Float createFromGeoCoords(float[] xyz) { - return new Float(xyz); - } - - public int getSize() { - if (coords != null) { - return coords.length / 3; - } - - return 0; - } - - public void set(int i, double x, double y, double z) { - int loc = i * 3; - coords[loc] = (float) x; - coords[loc + 1] = (float) y; - coords[loc + 2] = (float) z; - } - - public void set(int i, Geo g) { - set(i, g.x(), g.y(), g.z()); - } - - public void set(int i, double lat, double lon, boolean isDegrees) { - set(i, new Geo(lat, lon, isDegrees)); - } - - public Geo get(int i) { - return get(i, new Geo()); - } - - public Geo get(int i, Geo ret) { - int loc = i * 3; - double x = coords[loc]; - double y = coords[loc + 1]; - double z = coords[loc + 2]; - ret.initialize(x, y, z); - return ret; - } - - public boolean equals(int index, Geo comp) { - int loc = index * 3; - double x = coords[loc]; - double y = coords[loc + 1]; - double z = coords[loc + 2]; - return x == comp.x() && y == comp.y() && z == comp.z(); - } - - /** - * Ensure that the Geo array starts and ends with the same values. Will - * replace the current coord array with one three floats longer if needed. - */ - public void closeArray() { - int l = coords.length; - int i = l - 3; - if (coords[0] != coords[i] || coords[1] != coords[i + 1] || coords[2] != coords[i + 2]) { - float[] newCoords = new float[l + 3]; - System.arraycopy(coords, 0, newCoords, 0, l); - newCoords[l] = coords[0]; - newCoords[l + 1] = coords[1]; - newCoords[l + 2] = coords[2]; - coords = newCoords; - } - } - - /** - * Modify, if needed, the Geo array with the duplicates removed. - */ - public void removeDups() { - Geo[] ga = toPointArray(); - Geo[] r = new Geo[ga.length]; - int p = 0; - for (int i = 0; i < ga.length; i++) { - if (p == 0 || !(r[p - 1].equals(ga[i]))) { - r[p] = ga[i]; - p++; - } - } - - if (p != ga.length) { - coords = new float[p * 3]; - for (int i = 0; i < p; i++) { - int loc = i * 3; - Geo geo = r[i]; - coords[loc] = (float) geo.x(); - coords[loc + 1] = (float) geo.y(); - coords[loc + 2] = (float) geo.z(); - } - } - } - } - - /** - * An implementation of GeoArray and GeoArray.Mutable that contains - * double-precision values. Holds the coordinates in a double array of x, y, - * z, x, y, z values. - * - * @author dietrick - */ - public static class Double - extends Adapter - implements Mutable { - - private double[] coords; - - public Double(Geo[] geos) { - coords = new double[geos.length * 3]; - for (int i = 0; i < geos.length; i++) { - int loc = i * 3; - Geo geo = geos[i]; - coords[loc] = geo.x(); - coords[loc + 1] = geo.y(); - coords[loc + 2] = geo.z(); - } - } - - public Double(GeoArray ga) { - int size = ga.getSize(); - coords = new double[size * 3]; - Geo geo = new Geo(); - for (int i = 0; i < size; i++) { - int loc = i * 3; - ga.get(i, geo); - coords[loc] = geo.x(); - coords[loc + 1] = geo.y(); - coords[loc + 2] = geo.z(); - } - } - - protected Double(double[] coords) { - this.coords = coords; - } - - public static Double createFromLatLonDegrees(double[] latlondeg) { - int numCoordSets = latlondeg.length / 2; - double[] coords = new double[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initialize(latlondeg[i * 2], latlondeg[i * 2 + 1]); - int loc = i * 3; - coords[loc] = geo.x(); - coords[loc + 1] = geo.y(); - coords[loc + 2] = geo.z(); - } - - return new Double(coords); - } - - public static Double createFromLatLonRadians(double[] latlonrad) { - int numCoordSets = latlonrad.length / 2; - double[] coords = new double[numCoordSets * 3]; - Geo geo = new Geo(); - for (int i = 0; i < numCoordSets; i++) { - geo.initializeRadians(latlonrad[i * 2], latlonrad[i * 2 + 1]); - int loc = i * 3; - coords[loc] = geo.x(); - coords[loc + 1] = geo.y(); - coords[loc + 2] = geo.z(); - } - - return new Double(coords); - } - - public static Double createFromGeoCoords(double[] xyz) { - return new Double(xyz); - } - - public int getSize() { - if (coords != null) { - return coords.length / 3; - } - - return 0; - } - - public void set(int i, double x, double y, double z) { - int loc = i * 3; - coords[loc] = x; - coords[loc + 1] = y; - coords[loc + 2] = z; - } - - public void set(int i, Geo g) { - set(i, g.x(), g.y(), g.z()); - } - - public void set(int i, double lat, double lon, boolean isDegrees) { - set(i, new Geo(lat, lon, isDegrees)); - } - - public Geo get(int i) { - return get(i, new Geo()); - } - - public Geo get(int i, Geo ret) { - - if (ret == null) { - ret = new Geo(); - } - - int loc = i * 3; - double x = coords[loc]; - double y = coords[loc + 1]; - double z = coords[loc + 2]; - ret.initialize(x, y, z); - return ret; - } - - public boolean equals(int index, Geo comp) { - int loc = index * 3; - double x = coords[loc]; - double y = coords[loc + 1]; - double z = coords[loc + 2]; - return x == comp.x() && y == comp.y() && z == comp.z(); - } - - /** - * Ensure that the Geo array starts and ends with the same values. Will - * replace the current coord array with one three double longer if needed. - */ - public void closeArray() { - int l = coords.length; - int i = l - 3; - if (coords[0] != coords[i] || coords[1] != coords[i + 1] || coords[2] != coords[i + 2]) { - double[] newCoords = new double[l + 3]; - System.arraycopy(coords, 0, newCoords, 0, l); - newCoords[l] = coords[0]; - newCoords[l + 1] = coords[1]; - newCoords[l + 2] = coords[2]; - coords = newCoords; - } - } - - /** - * Modify, if needed, the Geo array with the duplicates removed. - */ - public void removeDups() { - Geo[] ga = toPointArray(); - Geo[] r = new Geo[ga.length]; - int p = 0; - for (int i = 0; i < ga.length; i++) { - if (p == 0 || !(r[p - 1].equals(ga[i]))) { - r[p] = ga[i]; - p++; - } - } - - if (p != ga.length) { - coords = new double[p * 3]; - for (int i = 0; i < p; i++) { - int loc = i * 3; - Geo geo = r[i]; - coords[loc] = geo.x(); - coords[loc + 1] = geo.y(); - coords[loc + 2] = geo.z(); - } - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoExtent.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoExtent.java deleted file mode 100644 index b30bddc48..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoExtent.java +++ /dev/null @@ -1,37 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoExtent.java,v $ -//$Revision: 1.3 $ -//$Date: 2007/01/30 20:37:04 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -/** - * An object with some geographical representation on the earth. Can - * be a point, line or area-type thing, i.e. anything that could be - * plotted on a map. - */ -public interface GeoExtent { - /** compute a point and radius around the extent. */ - BoundingCircle getBoundingCircle(); - /** return an object that this extent represents. */ - Object getID(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoPath.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoPath.java deleted file mode 100644 index 8f75ca30a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoPath.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2005 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -import java.util.Iterator; - -/** - * An abstraction of an arbitrary geographic path. A path is assumed to mean a - * chain of points that although it may share a common starting and end point, - * it will not not represent an area in that case. - * - * @author mthome@bbn.com - */ -public interface GeoPath extends GeoExtent { - /** @return an iterator over the segments of the path * */ - Iterator segmentIterator(); - - /** @return an iterator over the points of the path * */ - Iterator pointIterator(); - - /** Does the segment s come within epsilon (in radians) of us? */ - boolean isSegmentNear(GeoSegment s, double epsilon); - - /** - * Return the points that make up the path as an array of Geo object. Closed - * paths are not specially marked. Specifically, closed paths do not have - * equal first and last Geo points in the returned array. - * - * @return the Geo points of the Path - */ - // Geo[] toPointArray(); - GeoArray getPoints(); - - /** - * @return the number of points in the path. - */ - int length(); - - /** - * An implementation of Path that takes an alternating lat/lon array and - * (optionally) an array of altitudes. - */ - public static class Impl implements GeoPath { - protected GeoArray pts; - protected int length; - protected Object id = GeoPath.Impl.this; - - protected Impl() {} - - /** - * Create a path of LatLon pairs. - * - * @param lls alternating lat/lon in decimal degrees. - */ - public Impl(double[] lls) { - this(lls, true); - } - - /** - * Create a path of LatLon pairs. - * - * @param lls alternating lat/lon values. - * @param isDegrees true if lat/lon are in degrees, false if in radians. - */ - public Impl(double[] lls, boolean isDegrees) { - if (isDegrees) { - setPoints(GeoArray.Double.createFromLatLonDegrees(lls)); - } else { - setPoints(GeoArray.Double.createFromLatLonRadians(lls)); - } - } - - /** - * Create a path from a GeoArray. - * @param pnts - */ - public Impl(GeoArray pnts) { - setPoints(pnts); - } - - /** - * Create a path from Geos. - * - * @param geos - */ - public Impl(Geo[] geos) { - setPoints(geos); - } - - public void setPoints(GeoArray ga) { - pts = ga; - if (pts != null) { - length = pts.getSize(); - } else { - length = 0; - } - } - - public GeoArray getPoints() { - return pts; - } - - /** - * Method for subclasses to set pts and length of Geos. - * - * @param points - */ - protected void setPoints(Geo[] points) { - pts = new GeoArray.Double(points); - if (pts != null) { - length = pts.getSize(); - } else { - length = 0; - } - } - - // public Geo[] toPointArray() { - // return pts.toPointArray(); - // } - - public boolean isSegmentNear(GeoSegment s, double epsilon) { - return Intersection.isSegmentNearPoly(s, getPoints(), epsilon) != null; - } - - protected transient BoundingCircle bc = null; - - public synchronized BoundingCircle getBoundingCircle() { - if (bc == null) - bc = new BoundingCircle.Impl(this); - - return bc; - } - - public int length() { - return length; - } - - public Iterator segmentIterator() { - return new SegIt(); - } - - public Iterator pointIterator() { - return new PointIt(); - } - - /** - * Callback for the SegIt to find out how the GeoPath wants the segment - * IDed. - * - * @param i The index of the segment in question. - * @return Object that IDs the segment, could be this path, too. Depends - * on what the Intersection Algorithm wants to do in consider(). - */ - protected Object getSegID(int i) { - return new Integer(i); - } - - /** - * Callback for the PointIt to find out how the GeoPath wants the points - * IDed. - * - * @param i The index of the point in question. - * @return Object that IDs the point, could be this path, too. Depends - * on what the Intersection Algorithm wants to do in consider(). - */ - protected Object getPointID(int i) { - return new Integer(i); - } - - protected class SegIt implements Iterator, GeoSegment { - int i = -1; - Geo[] seg = new Geo[] { new Geo(), new Geo() }; - - public SegIt() { - pts.get(0, seg[1]); - } - - /** Constructs a new bounding circle instance each call. * */ - public BoundingCircle getBoundingCircle() { - Geo c = Intersection.center(seg); - return new BoundingCircle.Impl(c, c.distance(seg[0])); - } - - public boolean hasNext() { - return i < (length - 2); - } - - public GeoSegment next() { - return nextSegment(); - } - - public GeoSegment nextSegment() { - i++; - seg[0].initialize(seg[1]); - pts.get(i + 1, seg[1]); - return this; - } - - public void remove() { - throw new UnsupportedOperationException("Path.SegmentIterator doesn't support remove"); - } - - /** - * GSegment method. - * - * @return the current segment as a two-element array of Geo The - * first point is the "current point" and the second is the - * next. TODO If there isn't another point available, will - * throw an indexOutOfBounds exception. - */ - public Geo[] getSeg() { - return seg; - } - - /** - * @return the current segment as a double[]. The first point is the - * "current point" and the second is the next. TODO If there - * isn't another point available, will throw an - * indexOutOfBounds exception. - */ - public double[] getSegArray() { - return new double[] { seg[0].getLatitude(), - seg[0].getLongitude(), seg[1].getLatitude(), - seg[1].getLongitude() }; - } - - /** - * Return Object ID for current segment. - * - * @deprecated - */ - public Object getSegId() { - return GeoPath.Impl.this.getSegID(i); - } - - /** - * GeoExtent method - * - * @return Object ID for current segment. - */ - public Object getID() { - return GeoPath.Impl.this.getSegID(i); - } - - } - - protected class PointIt implements Iterator, GeoPoint { - int i = -1; - Geo pt = new Geo(); - - public PointIt() {} - - public boolean hasNext() { - return i < (length - 1); // need -1, because of the i++ in - // nextPoint. - } - - public GeoPoint next() { - i++; - return this; - } - - public void remove() { - throw new UnsupportedOperationException("Path.Iterator doesn't support remove"); - } - - public Geo getPoint() { - return pts.get(i, pt); - } - - /** - * @deprecated use getID() instead. - */ - public Object getPointId() { - return GeoPath.Impl.this.getPointID(i); - } - - /** - * GeoExtent method - * - * @return Object ID for current point. - */ - public Object getID() { - return GeoPath.Impl.this.getPointID(i); - } - - public BoundingCircle getBoundingCircle() { - return new BoundingCircle.Impl(pts.get(i), 0.0); - } - } - - /** - * @deprecated use getID() instead. - */ - public Object getPathID() { - return id; - } - - public Object getID() { - return id; - } - - public void setID(Object id) { - this.id = id; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoPoint.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoPoint.java deleted file mode 100644 index fadce6092..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoPoint.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2005 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * A geographic Point in space. Used in Path Iterators. - * - * @author mthome@bbn.com - */ -public interface GeoPoint extends GeoExtent { - /** return the current point as a Geo object */ - Geo getPoint(); - - /** - * A standard implementation of GeoPoint. - * - * @author dietrick - */ - public static class Impl implements GeoPoint { - protected Geo point; - protected Object id = GeoPoint.Impl.this; - - public Impl(Geo p) { - point = p; - } - - /** - * Create a Impl from decimal degrees lat/lon coordinates. - * - * @param lat - * @param lon - */ - public Impl(double lat, double lon) { - point = new Geo(lat, lon); - } - - /** - * Create a Impl from decimal degrees lat/lon coordinates. - * - * @param lat - * @param lon - * @param isDegrees flag to specify decimal degrees (true) or radians. - */ - public Impl(double lat, double lon, boolean isDegrees) { - point = new Geo(lat, lon, isDegrees); - } - - public Geo getPoint() { - return point; - } - - /** - * @deprecated use setID() instead. - */ - public void setPointId(Object pid) { - id = pid; - } - - /** - * @deprecated use getID() instead. - */ - public Object getPointId() { - return id; - } - - public void setID(Object pid) { - id = pid; - } - - public Object getID() { - return id; - } - - public BoundingCircle getBoundingCircle() { - return new BoundingCircle.Impl(point, 0.0); - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoRegion.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoRegion.java deleted file mode 100644 index d85db98c1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoRegion.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * An arbitrary space described in terms of Geo objects. GeoRegions are assumed - * to be closed paths representing areas. - */ -public interface GeoRegion extends GeoPath { - - /** - * Is the Geo inside the region? - * - * @param point - * @return true if point is inside region. - */ - boolean isPointInside(Geo point); - - // ------------------------------ - // Basic Implementation - // ------------------------------ - - public static class Impl extends GeoPath.Impl implements GeoRegion { - - public Impl(Geo[] coords) { - super(coords); - } - - /** - * Create a region of LatLon pairs. - * - * @param lls alternating lat/lon in decimal degrees. - */ - public Impl(double[] lls) { - this(lls, true); - } - - /** - * Create a region of LatLon pairs. - * - * @param lls alternating lat/lon values. - * @param isDegrees true if lat/lon are in degrees, false if in radians. - */ - public Impl(double[] lls, boolean isDegrees) { - super(lls, isDegrees); - } - - /** - * Create a region from a GeoArray. - * @param points - */ - public Impl(GeoArray points) { - super(points); - } - - /** - * @deprecated use getID() instead. - */ - public void setRegionId(Object rid) { - id = rid; - } - - /** - * @deprecated use getID() instead. - */ - public Object getRegionId() { - return id; - } - - public boolean isSegmentNear(GeoSegment s, double epsilon) { - return Intersection.isSegmentNearPolyRegion(s, - getPoints(), -// toPointArray(), - epsilon); - } - - public boolean isPointInside(Geo p) { - return Intersection.isPointInPolygon(p, getPoints()/*toPointArray()*/); - } - - public BoundingCircle getBoundingCircle() { - if (bc == null) { - return new BoundingCircle.Impl(this); - } - return bc; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/GeoSegment.java b/src/core/src/main/java/com/bbn/openmap/geo/GeoSegment.java deleted file mode 100644 index 37f51c063..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/GeoSegment.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2005 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * A geographic (great circle) line segment. Used in Path Iterators. - * - * @author mthome@bbn.com - */ - -public interface GeoSegment extends GeoExtent { - /** - * @return the current segment as a two-element array of Geo The first point - * is the "current point" and the second is the next. If there isn't - * another point available, will throw an indexOutOfBounds - * exception. - */ - Geo[] getSeg(); - - /** - * @return the current segment as a float[]. The first point is the "current - * point" and the second is the next. If there isn't another point - * available, will throw an indexOutOfBounds exception. - */ - double[] getSegArray(); - - public static class Impl implements GeoSegment { - protected Geo[] seg; - protected Object id = GeoSegment.Impl.this; - - /** - * Create a GeoSegment.Impl with an array of 2 Geos. - * - * @param segment Geo[2]. - */ - public Impl(Geo[] segment) { - seg = segment; - } - - public Geo[] getSeg() { - return seg; - } - - public double[] getSegArray() { - return new double[] { seg[0].getLatitude(), seg[0].getLongitude(), - seg[1].getLatitude(), seg[1].getLongitude() }; - } - - public BoundingCircle getBoundingCircle() { - return new BoundingCircle.Impl(seg); - } - - /** - * @deprecated use getID() instead. - */ - public void setSegId(Object segId) { - id = segId; - } - - /** - * @deprecated use getID() instead. - */ - public Object getSegId() { - return id; - } - - public void setID(Object pid) { - id = pid; - } - - public Object getID() { - return id; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/Intersection.java b/src/core/src/main/java/com/bbn/openmap/geo/Intersection.java deleted file mode 100644 index 09271097a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/Intersection.java +++ /dev/null @@ -1,1623 +0,0 @@ -/** - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * Contains great circle intersection algorithms and helper methods. Sources: - * http://williams.best.vwh.net/intersect.htm - * http://mathforum.org/library/drmath/view/60711.html - *

- * The Intersection class has been updated to manage query intersections of - * GeoExtents over other GeoExtents. MatchCollectors and MatchFilters can be - * used to help optimize the search and manage the results. - * - * @author Sachin Date - * @author Ken Anderson - * @version $Revision: 1.20 $ on $Date: 2009/01/21 01:24:42 $ - */ -public class Intersection { - - protected final MatchFilter filter; - protected final MatchCollector collector; - - /** - * Create an Intersection class that will use the provided MatchFilter and - * MatchCollector. - * - * @param filter - * @param collector - */ - public Intersection(MatchFilter filter, MatchCollector collector) { - this.filter = filter; - this.collector = collector; - } - - /** - * Create an Intersection class that will use the - * MatchFilter.MatchParameters class with STRICT settings, and a - * MatchCollector.SetMatchCollector. - */ - public static Intersection intersector() { - return new Intersection(new MatchFilter.MatchParametersMF(MatchParameters.STRICT), new MatchCollector.SetMatchCollector()); - } - - /** - * Create an Intersection class that will use the - * MatchFilter.MatchParameters class with provided settings, and a - * MatchCollector.SetMatchCollector. - */ - public static Intersection intersector(MatchParameters params) { - return new Intersection(new MatchFilter.MatchParametersMF(params), new MatchCollector.SetMatchCollector()); - - } - - /** - * Create an Intersection class that will use the - * MatchFilter.MatchParameters class with provided settings, and a - * MatchCollector.CollectionMatchCollector with the provided collector. - */ - public static Intersection intersector(MatchParameters params, final Collection c) { - return new Intersection(new MatchFilter.MatchParametersMF(params), new MatchCollector.CollectionMatchCollector(c)); - } - - /** - * Create an Intersection class that will use the provided MatchFilter class - * and the provided MatchCollector. - */ - public static Intersection intersector(MatchFilter filter, MatchCollector collector) { - return new Intersection(filter, collector); - } - - /** - * Retrieve the MatchCollector that contains the results from the - * Intersection query. - * - * @return MatchCollector that can be used to retrieve intersection results. - */ - public MatchCollector getCollector() { - return collector; - } - - /** - * Retrieve the MatchFilter that can be used to control which GeoExtents are - * considered for Intersection queries. - * - * @return The MatchFilter used to process intersection results. - */ - public MatchFilter getFilter() { - return filter; - } - - /** - * Asks the Intersection class to calculate the relationships between object - * a and b. Calls the other consider methods, depending on what a and b are. - * Consult the MatchCollector for the results. - * - * @param a A GeoExtent object, generally. - * @param b A ExtentImpl object or GeoExtent object, generally. - */ - @SuppressWarnings("unchecked") - public void consider(Object a, Object b) { - if (b instanceof Collection) { - if (a instanceof GeoRegion) { - considerRegionXRegions((GeoRegion) a, (Collection) b); - } else if (a instanceof GeoPath) { - considerPathXRegions((GeoPath) a, (Collection) b); - } else if (a instanceof GeoPoint) { - considerPointXRegions((GeoPoint) a, (Collection) b); - } - } else if (b instanceof GeoRegion) { - if (a instanceof GeoRegion) { - considerRegionXRegion((GeoRegion) a, (GeoRegion) b); - } else if (a instanceof GeoPath) { - considerPathXRegion((GeoPath) a, (GeoRegion) b); - } else if (a instanceof GeoPoint) { - considerPointXRegion((GeoPoint) a, (GeoRegion) b); - } - } - } - - /** - * Loads the collector with regions from the Collection that intersect with - * r. - * - * @param r the region in question - * @param regions a Collection of GeoRegions. - */ - public void considerRegionXRegions(GeoRegion r, Collection regions) { - - /* - * since the path is closed we'll check the region index for the whole - * thing instead of segment-by-segment - */ - Iterator possibles; - - if (regions instanceof ExtentIndex) { - // if we've got an index, narrow the set down - possibles = ((ExtentIndex) regions).iterator(r); - } else { - possibles = regions.iterator(); - } - - while (possibles.hasNext()) { - GeoExtent extent = possibles.next(); - if (extent instanceof GeoRegion) { - considerRegionXRegion(r, (GeoRegion) extent); - } else if (extent instanceof GeoPath) { - // This body used to be the following: - // considerPathXRegion((GeoPath) extent, r); - // but this reverses the match order and leads to "r" getting - // collected - // instead of extent. I've inlined the essential body and left - // it here - for (Iterator pit = ((GeoPath) extent).segmentIterator(); pit.hasNext();) { - GeoSegment seg = pit.next(); - if (filter.preConsider(seg, r) && considerSegmentXRegion(seg, r)) { - collector.collect(seg, extent); - } - } - } else { - // usually, getting here means poly region vs radial region - BoundingCircle bc = extent.getBoundingCircle(); - BoundingCircle rbc = r.getBoundingCircle(); - // first pass check - the bounding circles intersect - if (rbc.intersects(bc.getCenter(), bc.getRadius() + filter.getHRange())) { - GeoArray pts = r.getPoints(); - if (isPointInPolygon(bc.getCenter(), pts)) { - // the center of extent is inside r - collector.collect(r, extent); - } else if (isPointNearPoly(bc.getCenter(), pts, bc.getRadius() + filter.getHRange())) { - // Center+radius of extent is within range an edge of - // the r - collector.collect(r, extent); - } // else no intersection - } - } - } - } - - /** - * Puts the region in the Collector if r intersects with it. - * - * @param r - * @param region - */ - public void considerRegionXRegion(GeoRegion r, GeoRegion region) { - /* these must be cheap! */ - GeoArray rBoundary = r.getPoints(); - /* get the first path point */ - Geo rPoint = rBoundary.get(0, new Geo()); - GeoArray regionBoundary = region.getPoints(); - Geo regionPoint = regionBoundary.get(0, new Geo()); - - // check for total containment - if (Intersection.isPointInPolygon(rPoint, regionBoundary) || Intersection.isPointInPolygon(regionPoint, rBoundary) - // || Intersection.isPointInPolygon(region.getBoundingCircle() - // .getCenter(), rBoundary) - // || Intersection.isPointInPolygon(r.getBoundingCircle() - // .getCenter(), regionBoundary) - ) { - collector.collect(r, region); - } else { - // gotta try harder, so we fall back to segment-by-segment - // intersections - for (Iterator pit = r.segmentIterator(); pit.hasNext();) { - GeoSegment seg = pit.next(); - if (filter.preConsider(seg, region) && considerSegmentXRegion(seg, region)) { - collector.collect(seg, region); - // For the default implementation, we just care - // about first hit. - return; - } - } - } - } - - /** - * Puts regions in the Collector if they intersect the path. - * - * @param path - * @param regions - */ - public void considerPathXRegions(GeoPath path, Collection regions) { - /* - * Since the path is open, then our best bet is to check each segment - * separately - */ - for (Iterator pit = path.segmentIterator(); pit.hasNext();) { - GeoSegment seg = pit.next(); - Iterator rit; - if (regions instanceof ExtentIndex) { - rit = ((ExtentIndex) regions).iterator(seg); - } else { - rit = regions.iterator(); - } - - while (rit.hasNext()) { - GeoExtent extent = rit.next(); - if (filter.preConsider(path, extent)) { - if (extent instanceof GeoRegion) { - GeoRegion region = (GeoRegion) extent; - if (considerSegmentXRegion(seg, region)) { - collector.collect(seg, region); - } - } else if (extent instanceof GeoPath) { - GeoPath p = (GeoPath) extent; - if (isSegmentNearPoly(seg, p.getPoints(), filter.getHRange()) != null) { - collector.collect(seg, p); - } - } else { - BoundingCircle bc = extent.getBoundingCircle(); - if (isSegmentNearRadialRegion(seg, bc.getCenter(), bc.getRadius(), filter.getHRange())) { - collector.collect(seg, extent); - } - } - } - - } - } - } - - /** - * Puts the region in the Collector if it intersects with the path. - * - * @param path - * @param region - */ - public void considerPathXRegion(GeoPath path, GeoRegion region) { - for (Iterator pit = path.segmentIterator(); pit.hasNext();) { - GeoSegment seg = pit.next(); - - if (filter.preConsider(seg, region) && considerSegmentXRegion(seg, region)) { - collector.collect(seg, region); - // For the default implementation, we just care about - // the first contact. - return; - } - } - } - - /** - * Returns true if the segment intersects with the region. The range of the - * query is determined by the filter set on this Intersection object. - * - * @param seg - * @param region - * @return true if segment intersects region - */ - public boolean considerSegmentXRegion(GeoSegment seg, GeoRegion region) { - return region.isSegmentNear(seg, filter.getHRange()); - } - - /** - * Adds regions to the Collector if the GeoPoint p is on or in the regions - * of the Collection. - * - * @param p - * @param regions - */ - public void considerPointXRegions(GeoPoint p, Collection regions) { - Iterator rit; - if (regions instanceof ExtentIndex) { - rit = ((ExtentIndex) regions).iterator(p); - } else { - rit = regions.iterator(); - } - - while (rit.hasNext()) { - GeoExtent extent = (GeoExtent) rit.next(); - if (filter.preConsider(p, extent)) { - if (extent instanceof GeoRegion) { - GeoRegion region = (GeoRegion) extent; - if (considerPointXRegion(p, region)) { - collector.collect(p, region); - } - } else if (extent instanceof GeoPath) { - GeoPath path = (GeoPath) extent; - if (isPointNearPoly(p.getPoint(), path.getPoints(), filter.getHRange())) { - collector.collect(p, path); - } - } else { - BoundingCircle bc = extent.getBoundingCircle(); - if (p.getPoint().distance(bc.getCenter()) <= bc.getRadius() + filter.getHRange()) { - collector.collect(p, extent); - } - } - } - } - } - - /** - * @param p - * @param region - * @return true if p is in region. - */ - public boolean considerPointXRegion(GeoPoint p, GeoRegion region) { - return isPointInPolygon(p.getPoint(), region.getPoints()); - } - - // - // Static versions of intersection methods - // - - /** - * Simplified version of #intersect(Path, Collection, Algorithm) for old - * code, using the default match algorithm, and returning the identifiers of - * the regions that intersect with the path. - * - * @param path - * @param regions - * @return an iterator over list of the intersecting regions. - */ - public static Iterator intersect(Object path, Object regions) { - MatchCollector.SetMatchCollector c = new MatchCollector.SetMatchCollector(); - Intersection ix = new Intersection(new MatchFilter.MatchParametersMF(MatchParameters.STRICT), c); - ix.consider(path, regions); - return c.iterator(); - } - - // - // Utility methods (The Mathematics) - // - - /** - * Returns the two antipodal points of intersection of two great circles - * defined by the arcs (lat1, lon1) to (lat2, lon2) and (lat2, lon2) to - * (lat4, lon4). All lat-lon values are in degrees. - * - * @return an array of two lat-lon points arranged as lat, lon, lat, lon - */ - public static float[] getIntersection(float lat1, float lon1, float lat2, float lon2, float lat3, float lon3, float lat4, - float lon4) { - - Geo geoCross1 = (new Geo(lat1, lon1)).crossNormalize(new Geo(lat2, lon2)); - Geo geoCross2 = (new Geo(lat3, lon3)).crossNormalize(new Geo(lat4, lon4)); - - Geo geo = geoCross1.crossNormalize(geoCross2); - Geo anti = geo.antipode(); - - return new float[] { - ((float) geo.getLatitude()), - ((float) geo.getLongitude()), - ((float) anti.getLatitude()), - ((float) anti.getLongitude()) - }; - } - - /** - * Returns the two antipodal points of intersection of two great circles - * defined by the arcs (lat1, lon1) to (lat2, lon2) and (lat2, lon2) to - * (lat4, lon4). All lat-lon values are in degrees. - * - * @return an array of two lat-lon points arranged as lat, lon, lat, lon - */ - public static double[] getIntersection(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3, - double lat4, double lon4) { - - Geo geoCross1 = (new Geo(lat1, lon1)).crossNormalize(new Geo(lat2, lon2)); - Geo geoCross2 = (new Geo(lat3, lon3)).crossNormalize(new Geo(lat4, lon4)); - - Geo geo = geoCross1.crossNormalize(geoCross2); - Geo anti = geo.antipode(); - - return new double[] { - geo.getLatitude(), - geo.getLongitude(), - anti.getLatitude(), - anti.getLongitude() - }; - } - - /** - * Returns a Geo representing the intersection of two great circles defined - * by the arcs (lat1, lon1) to (lat2, lon2) and (lat2, lon2) to (lat4, - * lon4). All lat-lon values are in degrees. - * - * @return Geo containing intersection, might have to check antipode of Geo - * for actual intersection. - */ - public static Geo getIntersectionGeo(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3, double lat4, - double lon4) { - - Geo geoCross1 = (new Geo(lat1, lon1)).crossNormalize(new Geo(lat2, lon2)); - Geo geoCross2 = (new Geo(lat3, lon3)).crossNormalize(new Geo(lat4, lon4)); - - // geoCross memory is reused for answer. - return geoCross1.crossNormalize(geoCross2, geoCross1); - } - - /** - * Returns true if the two segs intersect in at least one point. All lat-lon - * values are in degrees. lat1,lon1-lat2,lon2 make up one segment, - * lat3,lon3-lat4,lon4 make up the other segment. - */ - public static boolean intersects(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3, double lat4, - double lon4) { - - double[] llp = getSegIntersection(lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4); - - return (llp[0] != Double.MAX_VALUE && llp[1] != Double.MAX_VALUE) - || (llp[2] != Double.MAX_VALUE && llp[3] != Double.MAX_VALUE); - } - - /** - * Checks if the two polygonal areas intersect. The two polygonal regions - * are represented by two lat-lon arrays in the lat1, lon1, lat2, lon2,... - * format. For closed polygons the last pair of points in the array should - * be the same as the first pair. All lat-lon values are in degrees. - */ - public static boolean polyIntersect(float[] polyPoints1, float[] polyPoints2) { - - // go through each side of poly1 and test to see if it - // intersects with any side of poly2 - - for (int i = 0; i < polyPoints1.length / 2 - 1; i++) { - - for (int j = 0; j < polyPoints2.length / 2 - 1; j++) { - - if (intersects(polyPoints1[2 * i], polyPoints1[2 * i + 1], polyPoints1[2 * i + 2], polyPoints1[2 * i + 3], - polyPoints2[2 * j], polyPoints2[2 * j + 1], polyPoints2[2 * j + 2], polyPoints2[2 * j + 3])) - return true; - } - } - - return false; - } - - /** - * Checks if the two polygonal areas intersect. The two polygonal regions - * are represented by two lat-lon arrays in the lat1, lon1, lat2, lon2,... - * format. For closed polygons the last pair of points in the array should - * be the same as the first pair. All lat-lon values are in degrees. - */ - public static boolean polyIntersect(double[] polyPoints1, double[] polyPoints2) { - - // go through each side of poly1 and test to see if it - // intersects with any side of poly2 - - for (int i = 0; i < polyPoints1.length / 2 - 1; i++) { - - for (int j = 0; j < polyPoints2.length / 2 - 1; j++) { - - if (intersects(polyPoints1[2 * i], polyPoints1[2 * i + 1], polyPoints1[2 * i + 2], polyPoints1[2 * i + 3], - polyPoints2[2 * j], polyPoints2[2 * j + 1], polyPoints2[2 * j + 2], polyPoints2[2 * j + 3])) - return true; - } - } - - return false; - } - - /** - * Checks if the two polygonal areas intersect. The two polygonal regions - * are represented by two lat-lon arrays in the lat1, lon1, lat2, lon2,... - * format. For closed polygons the last pair of points in the array should - * be the same as the first pair. All lat-lon values are in degrees. KM - * optimized to create each Geo only once. (TODO consider optimizing the - * other paths.) - */ - public static boolean polyIntersect_optimized(double[] polyPoints1, double[] polyPoints2) { - - // go through each side of poly1 and test to see if it - // intersects with any side of poly2 - - Geo geos1[] = new Geo[polyPoints1.length / 2]; - Geo geos2[] = new Geo[polyPoints2.length / 2]; - - for (int i = 0; i < geos1.length; i++) { - geos1[i] = new Geo(polyPoints1[2 * i], polyPoints1[2 * i + 1]); - } - for (int i = 0; i < geos2.length; i++) { - geos2[i] = new Geo(polyPoints2[2 * i], polyPoints2[2 * i + 1]); - } - - for (int i = 0; i < geos1.length - 1; i++) { - - for (int j = 0; j < geos2.length - 1; j++) { - Geo p1 = geos1[i]; - Geo p2 = geos1[i + 1]; - Geo p3 = geos2[j]; - Geo p4 = geos2[j + 1]; - - Geo[] results = getSegIntersection(p1, p2, p3, p4); - - if (results[0] != null || results[1] != null) { - return true; - } - } - } - - return false; - } - - /** - * checks if the polygon or polyline represented by the polypoints contains - * any lines that intersect each other. All lat-lon values are in degrees. - */ - public static boolean isSelfIntersectingPoly(float[] polyPoints) { - - for (int i = 0; i < polyPoints.length / 2 - 1; i++) { - - for (int j = i + 1; j < polyPoints.length / 2 - 1; j++) { - - float lat1 = polyPoints[2 * i]; - float lon1 = polyPoints[2 * i + 1]; - float lat2 = polyPoints[2 * i + 2]; - float lon2 = polyPoints[2 * i + 3]; - - float lat3 = polyPoints[2 * j]; - float lon3 = polyPoints[2 * j + 1]; - float lat4 = polyPoints[2 * j + 2]; - float lon4 = polyPoints[2 * j + 3]; - - // ignore adjacent segments - if ((lat1 == lat4 && lon1 == lon4) || (lat2 == lat3 && lon2 == lon3)) - continue; - - if (intersects(lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4)) - return true; - - } - } - - return false; - - } - - /** - * checks if the polygon or polyline represented by the polypoints contains - * any lines that intersect each other. All lat-lon values are in degrees. - */ - public static boolean isSelfIntersectingPoly(double[] polyPoints) { - - for (int i = 0; i < polyPoints.length / 2 - 1; i++) { - - for (int j = i + 1; j < polyPoints.length / 2 - 1; j++) { - - double lat1 = polyPoints[2 * i]; - double lon1 = polyPoints[2 * i + 1]; - double lat2 = polyPoints[2 * i + 2]; - double lon2 = polyPoints[2 * i + 3]; - - double lat3 = polyPoints[2 * j]; - double lon3 = polyPoints[2 * j + 1]; - double lat4 = polyPoints[2 * j + 2]; - double lon4 = polyPoints[2 * j + 3]; - - // ignore adjacent segments - if ((lat1 == lat4 && lon1 == lon4) || (lat2 == lat3 && lon2 == lon3)) - continue; - - if (intersects(lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4)) - return true; - - } - } - - return false; - - } - - /** - * Calculates the great circle distance from the point (lat, lon) to the - * great circle containing the points (lat1, lon1) and (lat2, lon2). - * - * @return nautical miles - */ - public static double pointCircleDistanceNM(Geo p1, Geo p2, Geo center) { - return Geo.nm(pointCircleDistance(p1, p2, center)); - } - - /** - * Calculates the great circle distance from the point (center) to the - * great circle containing the points (p1) and (p2). - * - * @return radians - */ - public static double pointCircleDistance(Geo p1, Geo p2, Geo center) { - Geo n = Geo.crossNormalize(p1, p2, new Geo()); - Geo c = center.normalize(new Geo()); - double cosTheta = Geo.dot(n, c); - double theta = Math.acos(cosTheta); - - return Math.abs(Math.PI / 2 - theta); - } - - /** - * Point i is on the great circle defined by the points a and b. Returns - * true if i is between a and b, false otherwise. NOTE: i is assumed to be - * on the great circle line. - */ - public static boolean isOnSegment(Geo a, Geo b, Geo i) { - - // assert (< (Math.abs (.dot (.crossNormalize a b) i)) - // 1.e-15)) - - return ((a.distance(i) < a.distance(b)) && (b.distance(i) < b.distance(a))); - } - - /** - * Returns true if i is on the great circle between a and b and between - * them, false otherwise. In other words, this method does the great circle - * test for you, too. - */ - public static boolean isOnSegment(Geo a, Geo b, Geo i, double withinRad) { - - // assert (< (Math.abs (.dot (.crossNormalize a b) i)) - // 1.e-15)) - - return ((Math.abs(a.crossNormalize(b).dot(i)) <= withinRad) && (a.distance(i) < a.distance(b)) && (b.distance(i) < b.distance(a))); - } - - /** - * @return the Geo point i, which is on the great circle segment between Geo - * points a and b and which is closest to Geo point c. Returns null - * if there is no such point. - */ - public static Geo segIntersection(Geo a, Geo b, Geo c) { - // Normal to great circle between a and b - Geo g = a.crossNormalize(b); - // Normal to the great circle between c and g - Geo f = c.crossNormalize(g); - // The intersection is normal to both, reusing g object for it's memory. - Geo i = f.crossNormalize(g, g); - if (isOnSegment(a, b, i)) { - return i; - } else { - // reuse i object memory - Geo ai = i.antipode(i); - if (isOnSegment(a, b, ai)) { - return ai; - } else { - return null; - } - } - } - - /** - * Test if [p1-p2] and [p3-p4] intersect - */ - public static final boolean segIntersects(Geo p1, Geo p2, Geo p3, Geo p4) { - Geo[] r = getSegIntersection(p1, p2, p3, p4); - return (r[0] != null || r[1] != null); - } - - /** - * returns the distance in NM between the point (lat, lon) and the point of - * intersection of the great circle passing through (lat, lon) and - * perpendicular to great circle segment (lat1, lon1, lat2, lon2). returns - * -1 if point of intersection of the two great circle segs is not on the - * great circle segment (lat1, lon1, lat2, lon2). - */ - public static double pointSegDistanceNM(double lat1, double lon1, double lat2, double lon2, double lat, double lon) { - double ret = pointSegDistance(new Geo(lat1, lon1), new Geo(lat2, lon2), new Geo(lat, lon)); - - return (ret == -1 ? ret : Geo.nm(ret)); - } - - /** - * Returns the distance in radians between the point c and the point of - * intersection of the great circle passing through c and perpendicular to - * great circle segment between a and b. Returns -1 if point of intersection - * of the two great circle segs is not on the great circle segment a-b. - */ - public static double pointSegDistance(Geo a, Geo b, Geo c) { - Geo i = segIntersection(a, b, c); - return (i == null) ? -1 : c.distance(i); - } - - /** - * Returns true or false depending on whether the great circle seg from - * point p1 to point p2 intersects the circle of radius (radians) around - * center. - */ - public static boolean intersectsCircle(Geo p1, Geo p2, Geo center, double radius) { - - // check if either of the end points of the seg are inside the - // circle - double d1 = Geo.distance(p1, center); - if (d1 < radius) - return true; - - double d2 = Geo.distance(p2, center); - if (d2 < radius) - return true; - - double dist = pointCircleDistance(p1, p2, center); - - if (dist > radius) - return false; - - // calculate point of intersection of great circle containing - // (lat, lon) and perpendicular to great circle containing - // (lat1, lon1) and (lat2, lon2) - - Geo g = p1.cross(p2); - Geo f = center.cross(g); - // Reusing g object for i - Geo i = f.crossNormalize(g, g); - - // check if point of intersection lies on the segment - // length of seg - double d = Geo.distance(p1, p2); - - // Make sure the intersection point is inside the exclusion - // zone - if (center.distance(i) < radius) { - // between seg endpoints and first point of intersection - double d11 = Geo.distance(p1, i); - double d12 = Geo.distance(p2, i); - // Check the distance of the intersection point and either - // endpoint to see if it falls between them. Add a second - // test to make sure that we are on the shorter of the two - // segments between the endpoints. - return (d11 <= d && d12 <= d && Math.abs(d11 + d12 - d) < 0.01f); - } - - // Make sure the intersection point is inside the exclusion - // zone, reusing i object for i2 - Geo i2 = i.antipode(i); - if (center.distance(i2) < radius) { - // between seg1 endpoints and second point of intersection - double d21 = Geo.distance(p1, i2); - double d22 = Geo.distance(p2, i2); - // Check the distance of the intersection point and either - // endpoint to see if it falls between them. Add a second - // test to make sure that we are on the shorter of the two - // segments between the endpoints. - return (d21 <= d && d22 <= d && Math.abs(d21 + d22 - d) < 0.01f); - } - - return false; - - } - - /** - * returns true if the specified poly path intersects the circle centered at - * (lat, lon). All lat-lon values are in degrees. radius is in radians. - */ - public static boolean intersectsCircle(float[] polyPoints, double lat, double lon, double radius) { - - Geo a = new Geo(polyPoints[0], polyPoints[1]); - Geo b = new Geo(); - Geo c = new Geo(lat, lon); - - int numCoords = polyPoints.length / 2 - 1; - for (int i = 1; i < numCoords; i++) { - - float lat2 = polyPoints[2 * i]; - float lon2 = polyPoints[2 * i + 1]; - - b.initialize(lat2, lon2); - - if (intersectsCircle(a, b, c, radius)) - return true; - - a.initialize(b); - } - - return false; - } - - /** - * returns true if the specified poly path intersects the circle centered at - * (lat, lon). All lat-lon values are in degrees. radius is in radians. - */ - public static boolean intersectsCircle(double[] polyPoints, double lat, double lon, double radius) { - - Geo a = new Geo(polyPoints[0], polyPoints[1]); - Geo b = new Geo(); - Geo c = new Geo(lat, lon); - - int numCoords = polyPoints.length / 2 - 1; - for (int i = 1; i < numCoords; i++) { - - double lat2 = polyPoints[2 * i]; - double lon2 = polyPoints[2 * i + 1]; - - b.initialize(lat2, lon2); - - if (intersectsCircle(a, b, c, radius)) - return true; - - a.initialize(b); - } - - return false; - } - - /** - * Returns the center of the polygon poly. - */ - public static Geo center(Geo[] poly) { - return center(poly, new Geo()); - } - - /** - * Returns the center of the polygon poly. - */ - public static Geo center(Geo[] poly, Geo ret) { - Geo c = new Geo(poly[0]); - for (int i = 1; i < poly.length; i++) { - ret.initialize(poly[i]); - c = c.add(poly[i], c); - } - return c.normalize(ret); - } - - /** - * Returns the center of the polygon poly. - */ - public static Geo center(GeoArray poly) { - return center(poly, new Geo()); - } - - /** - * Returns the center of the polygon poly. - * - * @param poly the GeoArray of the polygon - * @param ret a Geo to use for the return values. - * @return ret. - */ - public static Geo center(GeoArray poly, Geo ret) { - Geo c = poly.get(0, new Geo()); - int size = poly.getSize(); - for (int i = 1; i < size; i++) { - poly.get(i, ret); - c = c.add(ret, c); - } - return c.normalize(ret); - } - - /** - * Determines whether x is inside poly. - * - *

- * N.B.
- *

    - *
  • poly must be a closed polygon. In other words, the first - * and last point must be the same. - *
  • It is recommended that a bounds check is run before this method. This - * method will return true if either x or the antipode (the - * point on the opposite side of the planet) of x are inside - * poly. - *
- * - *

- * poly is an array of latitude/longitude points where: - *
- *

-     *                                                        
-     *                                                                                               
-     *                 poly[0] = latitude 1
-     *                 poly[1] = longitude 1
-     *                 poly[2] = latitude 2
-     *                 poly[3] = longitude 2
-     *                 .
-     *                 .
-     *                 .
-     *                 poly[n-1] = latitude 1
-     *                 poly[n] = longitude 1
-     *                                                                                                
-     * 
- * - * @param x a geographic coordinate - * @param poly an array of lat/lons describing a closed polygon - * @return true iff x or antipode(x) is inside - * poly - */ - public static boolean isPointInPolygon(Geo x, GeoArray poly) { - Geo c = center(poly, new Geo()); - - // bail out if the point is more than 90 degrees off the - // centroid - double d = x.distance(c); - if (d >= (Math.PI / 2)) { - return false; - } - // ray is normal to the great circle from c to x. reusing c to hold ray - // info - Geo ray = c.crossNormalize(x, c); - /* - * side is a point on the great circle between c and x. It is used to - * choose a direction. - */ - Geo side = x.crossNormalize(ray, new Geo()); - boolean in = false; - // Why do we need to allocate new Geos? - // Geo p1 = new Geo(poly[0]); - // Geo p2 = new Geo(poly[0]); - Geo p1 = poly.get(0, new Geo()); - Geo p2 = poly.get(0, new Geo()); - Geo tmp = new Geo(); - int polySize = poly.getSize(); - for (int i = 1; i < polySize; i++) { - // p2.initialize(poly[i]); - p2 = poly.get(i, p2); - /* - * p1 and p2 are on different sides of the ray, and the great - * acircle between p1 and p2 is on the side that counts; - */ - if ((p1.dot(ray) < 0.0) != (p2.dot(ray) < 0.0) && p1.intersect(p2, ray, tmp).dot(side) > 0.0) { - in = !in; - } - p1.initialize(p2); - } - - // Check for unclosed polygons, if the polygon isn't closed, - // do the calculation for the last point to the starting - // point. - if (!poly.equals(0, p1)) { - poly.get(0, p2); - if ((p1.dot(ray) < 0.0) != (p2.dot(ray) < 0.0) && p1.intersect(p2, ray, tmp).dot(side) > 0.0) { - in = !in; - } - } - - return in; - } - - public static boolean isPointInPolygon(Geo x, GeoArray poly, Geo internal) { - Geo c = Geo.makeGeo(internal); - - // bail out if the point is more than 90 degrees off the - // centroid - double d = x.distance(c); - if (d >= (Math.PI / 2)) { - return false; - } - - if (internal.equals(c)) - return true; - // ray is normal to the great circle from c to x. reusing c to hold ray - // info - Geo ray = c.crossNormalize(x, c); - - /* - * side is a point on the great circle between c and x. It is used to - * choose a direction. - */ - Geo side = x.crossNormalize(ray, new Geo()); - boolean in = false; - // Why do we need to allocate new Geos? - // Geo p1 = new Geo(poly[0]); - // Geo p2 = new Geo(poly[0]); - Geo p1 = poly.get(0, new Geo()); - Geo p2 = poly.get(0, new Geo()); - Geo tmp = new Geo(); - int polySize = poly.getSize(); - for (int i = 1; i < polySize; i++) { - // p2.initialize(poly[i]); - p2 = poly.get(i, p2); - /* - * p1 and p2 are on different sides of the ray, and the great - * acircle between p1 and p2 is on the side that counts; - */ - if ((p1.dot(ray) < 0.0) != (p2.dot(ray) < 0.0) && p1.intersect(p2, ray, tmp).dot(side) > 0.0) - in = !in; - - p1.initialize(p2); - } - - // Check for unclosed polygons, if the polygon isn't closed, - // do the calculation for the last point to the starting - // point. - if (!poly.equals(0, p1)) { - poly.get(0, p2); - if ((p1.dot(ray) < 0.0) != (p2.dot(ray) < 0.0) && p1.intersect(p2, ray, tmp).dot(side) > 0.0) { - in = !in; - } - } - - return in; - } - - /** - * Ask if a Geo point is in a polygon. - * - * @param x - * @param poly double array where [lat, lon, lat, lon,...] - * @param polyInDegrees true of poly floats represent decimal degrees. - * @return true for Geo in poly - */ - public static boolean isPointInPolygon(Geo x, double[] poly, boolean polyInDegrees) { - if (polyInDegrees) { - return isPointInPolygon(x, GeoArray.Float.createFromLatLonDegrees(poly)); - } else { - return isPointInPolygon(x, GeoArray.Float.createFromLatLonRadians(poly)); - } - } - - /** - * Ask if a Geo point is in a polygon. - * - * @param x - * @param poly float array where [lat, lon, lat, lon,...] - * @param polyInDegrees true of poly floats represent decimal degrees. - * @return true for Geo in poly - */ - public static boolean isPointInPolygon(Geo x, float[] poly, boolean polyInDegrees) { - if (polyInDegrees) { - return isPointInPolygon(x, GeoArray.Float.createFromLatLonDegrees(poly)); - } else { - return isPointInPolygon(x, GeoArray.Float.createFromLatLonRadians(poly)); - } - } - - /** - * return true IFF some point of the first argument is inside the region - * specified by the closed polygon specified by the second argument - */ - public static boolean isPolylineInsidePolygon(GeoArray poly, GeoArray region) { - int polySize = poly.getSize(); - Geo testPoint = new Geo(); - for (int i = 0; i < polySize; i++) { - poly.get(i, testPoint); - if (isPointInPolygon(testPoint, region)) { - return true; - } - } - return false; - } - - /** - * Returns the point of intersection of two great circle segments defined by - * the segments. (lat1, lon1) to (lat2, lon2) and (lat2, lon2) to (lat4, - * lon4). All lat-lon values are in degrees. - * - * @return a float array of length 4 containing upto 2 valid lat-lon points - * of intersection that lie on both segments. Positions in the array - * not containing a valid lat/lon value are initialized to - * Float.MAX_VALUE. - */ - public static double[] getSegIntersection(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3, - double lat4, double lon4) { - // KRA 03SEP03: The original version of this consed 26+ Geo's. - // This one conses 8+. WAIT! Now it uses 6 - - Geo p1 = new Geo(lat1, lon1); - Geo p2 = new Geo(lat2, lon2); - Geo p3 = new Geo(lat3, lon3); - Geo p4 = new Geo(lat4, lon4); - - Geo[] results = getSegIntersection(p1, p2, p3, p4); - Geo i1 = results[0]; - Geo i2 = results[1]; - - double[] llp = new double[] { - Double.MAX_VALUE, - Double.MAX_VALUE, - Double.MAX_VALUE, - Double.MAX_VALUE - }; - - // check if first point of intersection lies on both segments - if (i1 != null) { - llp[0] = i1.getLatitude(); - llp[1] = i1.getLongitude(); - } - // check if second point of intersection lies on both segments - if (i2 != null) { - llp[2] = i2.getLatitude(); - llp[3] = i2.getLongitude(); - } - return llp; - } - - /** - * Find the intersection(s) between [p1-p2] and [p3-p4] - */ - public static final Geo[] getSegIntersection(Geo p1, Geo p2, Geo p3, Geo p4) { - - Geo geoCross1 = p1.crossNormalize(p2); - Geo geoCross2 = p3.crossNormalize(p4); - - // i1 is really geoCross1, i2 is really geoCross2, memory-wise. - Geo i1 = geoCross1.crossNormalize(geoCross2, geoCross1); - Geo i2 = i1.antipode(geoCross2); - - // check if the point of intersection lies on both segs - // length of seg1 - double d1 = p1.distance(p2); - // length of seg2 - double d2 = p3.distance(p4); - - // between seg1 endpoints and first point of intersection - double d111 = p1.distance(i1); - double d121 = p2.distance(i1); - - // between seg1 endpoints and second point of intersection - double d112 = p1.distance(i2); - double d122 = p2.distance(i2); - - // between seg2 endpoints and first point of intersection - double d211 = p3.distance(i1); - double d221 = p4.distance(i1); - - // between seg2 endpoints and second point of intersection - double d212 = p3.distance(i2); - double d222 = p4.distance(i2); - - Geo[] result = new Geo[] { - null, - null - }; - - // check if first point of intersection lies on both segments - if (d1 >= d111 && d1 >= d121 && d2 >= d211 && d2 >= d221) { - result[0] = i1; - } - // check if second point of intersection lies on both segments - if (d1 >= d112 && d1 >= d122 && d2 >= d212 && d2 >= d222) { - result[1] = i2; - } - return result; - } - - // /** - // * returns the point of intersection of two great circle segments - // * defined by the segments. (lat1, lon1) to (lat2, lon2) and - // * (lat2, lon2) to (lat4, lon4). All lat-lon values are in - // * degrees. - // * - // * @return a float array of length 4 containing upto 2 valid - // * lat-lon points of intersection that lie on both - // * segments. Positions in the array not containing a valid - // * lat/lon value are initialized to Float.MAX_VALUE. - // */ - // public static float[] getSegIntersectionOrig(float lat1, float - // lon1, - // float lat2, float lon2, - // float lat3, float lon3, - // float lat4, float lon4) { - // // KRA 03SEP03: We can do better than this. - // - // float[] ll = getIntersection(lat1, - // lon1, - // lat2, - // lon2, - // lat3, - // lon3, - // lat4, - // lon4); - // - // // check if the point of intersection lies on both segs - // - // // length of seg1 - // double d1 = Geo.distance(lat1, lon1, lat2, lon2); - // // length of seg2 - // double d2 = Geo.distance(lat3, lon3, lat4, lon4); - // - // // between seg1 endpoints and first point of intersection - // double d111 = Geo.distance(lat1, lon1, ll[0], ll[1]); - // double d121 = Geo.distance(lat2, lon2, ll[0], ll[1]); - // - // // between seg1 endpoints and second point of intersection - // double d112 = Geo.distance(lat1, lon1, ll[2], ll[3]); - // double d122 = Geo.distance(lat2, lon2, ll[2], ll[3]); - // - // // between seg2 endpoints and first point of intersection - // double d211 = Geo.distance(lat3, lon3, ll[0], ll[1]); - // double d221 = Geo.distance(lat4, lon4, ll[0], ll[1]); - // - // // between seg2 endpoints and second point of intersection - // double d212 = Geo.distance(lat3, lon3, ll[2], ll[3]); - // double d222 = Geo.distance(lat4, lon4, ll[2], ll[3]); - // - // float[] llp = new float[] { Float.MAX_VALUE, Float.MAX_VALUE, - // Float.MAX_VALUE, Float.MAX_VALUE }; - // - // // check if first point of intersection lies on both segments - // if (d1 >= d111 && d1 >= d121 && d2 >= d211 && d2 >= d221) { - // llp[0] = ll[0]; - // llp[1] = ll[1]; - // } - // - // // check if second point of intersection lies on both segments - // if (d1 >= d112 && d1 >= d122 && d2 >= d212 && d2 >= d222) { - // llp[2] = ll[2]; - // llp[3] = ll[3]; - // } - // - // return llp; - // } - - /** - * Does the segment come within near radians of the region defined by - * rCenter at rRadius? - */ - public static final boolean isSegmentNearRadialRegion(GeoSegment segment, Geo rCenter, double rRadius, double near) { - Geo[] s = segment.getSeg(); - if (s != null && s.length == 2) { - return isSegmentNearRadialRegion(s[0], s[1], rCenter, rRadius, near); - } - return false; - } - - /** - * Does the segment come within near radians of the region defined by - * rCenter at rRadius? - */ - public static final boolean isSegmentNearRadialRegion(Geo s1, Geo s2, Geo rCenter, double rRadius, double near) { - return s1.isInside(s2, near + rRadius, rCenter); - } - - /** Is a segment horizontally within range of a Region region? */ - public static final boolean isSegmentNearRegion(GeoSegment segment, double hrange, GeoRegion region) { - // Need to be careful here - calling - // region.isSegmentNear(segment, hrange) can result in - // circular code if the region just calls this method, which - // may seem reasonable, if you look at the API. - return isSegmentNearPolyRegion(segment, region.getPoints(), hrange); - } - - /** - * Does the segment come within near radians of the region defined by the - * polygon in r[*]? Catches segments within poly region and returns after - * first hit, which is why it returns boolean. - */ - public static final boolean isSegmentNearPolyRegion(GeoSegment segment, GeoArray r, double near) { - Geo[] s = segment.getSeg(); - if (s != null && s.length == 2) { - return isSegmentNearPolyRegion(s[0], s[1], r, near); - } - return false; - } - - /** - * Does the segment s1-s2 come within near radians of the region defined by - * the polygon in r[*]? Catches segments within poly region and returns - * after first hit, which is why it returns boolean. - */ - public static final boolean isSegmentNearPolyRegion(Geo s1, Geo s2, GeoArray r, double near) { - - return isSegmentNearPoly(s1, s2, r, near) != null || isPointInPolygon(s1, r); - } - - /** - * Where is a segment within range of a region? - */ - public static final Geo isSegmentNearPoly(GeoSegment segment, GeoArray r, double near) { - Geo[] s = segment.getSeg(); - if (s != null && s.length == 2) { - return isSegmentNearPoly(s[0], s[1], r, near); - } - return null; - } - - /** - * Is a segment, represented by endpoints 's1' and 's2', withing a range - * 'near' of region 'r'? - * - * @param s1 Endpoint of segment - * @param s2 Endpoint of segment - * @param r Region of interest - * @param near acceptable range between the segment and region, in radians. - * @return Geo location where the condition was initially met (yes), null if - * conditions weren't met (no). - */ - public static final Geo isSegmentNearPoly(Geo s1, Geo s2, GeoArray r, double near) { - - int rlen = r.getSize(); - Geo pl0 = r.get(rlen - 1, new Geo()); - Geo pl1 = new Geo(); - // check will be returned as ret, but we only allocate one per this - // method call, instead of one per loop, since we are returning if ret - // is not null. - Geo check = new Geo(); - for (int j = 0; j < rlen; j++) { - pl1 = r.get(j, pl1); - Geo ret = segmentsIntersectOrNear(s1, s2, pl0, pl1, near, check); - - if (ret != null) { - return ret; - } - - pl0.initialize(pl1); - } - return null; - } - - /** - * Where is a segment within range of a region? - */ - public static final List segmentNearPoly(GeoSegment segment, GeoArray r, double near) { - Geo[] s = segment.getSeg(); - List list = null; - if (s != null && s.length == 2) { - list = segmentNearPoly(s[0], s[1], r, near); - } - return list; - } - - /** - * Where is a segment, represented by endpoints 's1' and 's2', withing a - * range 'near' of region 'r'? - * - * @param s1 Endpoint of segment - * @param s2 Endpoint of segment - * @param r Region of interest - * @param near acceptable range between the segment and region, in radians. - * @return Geo location where the condition was met (yes), null if - * conditions weren't met (no). - */ - public static final List segmentNearPoly(Geo s1, Geo s2, GeoArray r, double near) { - int rlen = r.getSize(); - Geo pl0 = r.get(rlen - 1, new Geo()); - Geo pl1 = new Geo(); - List list = null; - Geo check = new Geo(); - for (int j = 0; j < rlen; j++) { - r.get(j, pl1); - Geo ret = segmentsIntersectOrNear(s1, s2, pl0, pl1, near, check); - - if (ret != null) { - if (list == null) { - list = new LinkedList(); - } - - list.add(ret); - // ret is actually the last created check. This mechanism limits - // the creation of Geos to only hits + 1. - check = new Geo(); - } - - pl0.initialize(pl1); - } - return list; - } - - /** - * Does the point s come within 'near' radians of the boarder of the region - * defined by the polygon in r[*]? - */ - public static final boolean isPointNearPoly(Geo s, GeoArray r, double near) { - int rlen = r.getSize(); - Geo pl0 = r.get(rlen - 1, new Geo()); - Geo pl1 = new Geo(); - for (int j = 0; j < rlen; j++) { - r.get(j, pl1); - if (pl0.isInside(pl1, near, s)) { - return true; // near enough to a region edge - } - pl0.initialize(pl1); - } - return false; - } - - /** - * Is one region's boundary within 'near' range of a region? Note: good - * practice is s describes a smaller area than r. - * - * @return the Geo location where the condition was first met, null if the - * condition wasn't met. - */ - public static final Geo isPolyNearPoly(GeoArray s, GeoArray r, double near) { - int rlen = r.getSize(); - int slen = s.getSize(); - Geo pl0 = r.get(rlen - 1); - Geo pl1 = new Geo(); - Geo sl0 = s.get(slen - 1); - Geo sl1 = new Geo(); - for (int j = 0; j < rlen; j++) { - pl1 = r.get(j, pl1); - for (int i = 0; i < slen; i++) { - sl1 = s.get(i, sl1); - Geo ret = segmentsIntersectOrNear(sl0, sl1, pl0, pl1, near); - - if (ret != null) { - return ret; - } - sl0 = sl1; - } - pl0 = pl1; - } - return null; - } - - /** - * Is one region's boundary within 'near' range of a region? Note: good - * practice is s describes a smaller area than r. - * - * @return a List where the polys intersect within the range, null if the - * condition wasn't met. - */ - public static final List polyNearPoly(GeoArray s, GeoArray r, double near) { - int rlen = r.getSize(); - int slen = s.getSize(); - Geo pl0 = r.get(rlen - 1); - Geo pl1 = new Geo(); - Geo sl0 = s.get(slen - 1); - Geo sl1 = new Geo(); - List list = null; - for (int j = 0; j < rlen; j++) { - pl1 = r.get(j, pl1); - for (int i = 0; i < slen; i++) { - sl1 = s.get(i, sl1); - Geo ret = segmentsIntersectOrNear(sl0, sl1, pl0, pl1, near); - - if (ret != null) { - if (list == null) { - list = new LinkedList(); - } - list.add(ret); - } - sl0 = sl1; - } - pl0 = pl1; - } - - return list; - } - - /** - * @return a Geo location iff the great circle segments defined by a1-a2 and - * b1-b2 intersect. the angles between the segments must be < PI or - * the results are ambiguous.Returns null if the segments don't - * intersect within the range. - */ - public static Geo segmentsIntersect(Geo a1, Geo a2, Geo b1, Geo b2) { - return segmentsIntersectOrNear(a1, a2, b1, b2, 0); - } - - /** - * @return a Geo location iff the great circle segments defined by a1-a2 and - * b1-b2 come within the range (r, radians) of each other. The - * angles between the segments must be < PI or the results are - * ambiguous. Returns null if the segments don't intersect within the - * range. - */ - public static Geo segmentsIntersectOrNear(Geo a1, Geo a2, Geo b1, Geo b2, double r) { - - if (a1 == null || a2 == null || b1 == null || b2 == null) { - return null; - } - - // ac and bc are the unit vectors normal to the two great - // circles defined by the segments - Geo ac = a1.crossNormalize(a2); - Geo bc = b1.crossNormalize(b2); - - // aL and bL are the lengths (in radians) of the segments - double aL = a1.distance(a2) + r; - double bL = b1.distance(b2) + r; - - // i is one of the two points where the two great circles - // intersect. Since we don't use bc anymore, let's reuse it for i, gets - // passed back from crossNormalize as the second argument. - Geo i = ac.crossNormalize(bc, bc); - - // if i is not on A - if (!(i.distance(a1) <= aL && i.distance(a2) <= aL)) { - i = i.antipode(i); // switch to the antipode instead, reuse i - // object for new values. - if (!(i.distance(a1) <= aL && i.distance(a2) <= aL)) { // check - // again - // nope - neither i nor i' is on A, so we'll bail out - return null; - } - } - // i is intersection or anti-intersection point now. - - // Now see if it intersects with b - if (i.distance(b1) <= bL && i.distance(b2) <= bL) { - return i; - } else { - return null; - } - } - - /** - * @return a Geo location iff the great circle segments defined by a1-a2 and - * b1-b2 come within the range (r, radians) of each other. The - * angles between the segments must be < PI or the results are - * ambiguous. Returns null if the segments don't intersect within the - * range. - */ - public static Geo segmentsIntersectOrNear(Geo a1, Geo a2, Geo b1, Geo b2, double r, Geo ret) { - - if (a1 == null || a2 == null || b1 == null || b2 == null) { - return null; - } - - // ac and bc are the unit vectors normal to the two great - // circles defined by the segments. ret is returned from crossNormalize - // as bc. - Geo ac = a1.crossNormalize(a2); - Geo bc = b1.crossNormalize(b2, ret); - - // aL and bL are the lengths (in radians) of the segments - double aL = a1.distance(a2) + r; - double bL = b1.distance(b2) + r; - - // i is one of the two points where the two great circles - // intersect. Since we don't use bc anymore, let's reuse it for i, gets - // passed back from crossNormalize as the second argument. - Geo i = ac.crossNormalize(bc, bc); - - // if i is not on A - if (!(i.distance(a1) <= aL && i.distance(a2) <= aL)) { - i = i.antipode(ret); // switch to the antipode instead, reuse ret - // yet again. - if (!(i.distance(a1) <= aL && i.distance(a2) <= aL)) { // check - // again - // nope - neither i nor i' is on A, so we'll bail out - return null; - } - } - // i is intersection or anti-intersection point now. - - // Now see if it intersects with b - if (i.distance(b1) <= bL && i.distance(b2) <= bL) { - // remember ret -> bc -> i, so i == ret - return i; - } else { - return null; - } - } - - public static void main(String[] args) { - /** - * Produces output: (1)=53.130104, -100.0 (2)=3.4028235E38, - * -3.4028235E38 intersects=true polyIntersect=true dist=655.4312 - * b3=true - */ - - double lat1 = 60; - double lon1 = -130; - double lat2 = 30; - double lon2 = -70; - - double lat3 = 60; - double lon3 = -70; - double lat4 = 30; - double lon4 = -130; - - double[] ll = getSegIntersection(lat1, -lon1, lat2, -lon2, lat3, -lon3, lat4, -lon4); - - System.out.println("(1)=" + ll[0] + ", " + (-ll[1])); - System.out.println("(2)=" + ll[2] + ", " + (-ll[3])); - - boolean b1 = intersects(lat1, -lon1, lat2, -lon2, lat3, -lon3, lat4, -lon4); - - System.out.println("intersects=" + b1); - - double[] polypoints1 = new double[] { - 38, - -27, - -46, - 165 - }; - - double[] polypoints2 = new double[] { - 51, - -42, - 55, - -17, - 11, - -23, - 51, - -42 - }; - - boolean b2 = polyIntersect(polypoints1, polypoints2); - - System.out.println("polyIntersect=" + b2); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/geo/MatchCollector.java b/src/core/src/main/java/com/bbn/openmap/geo/MatchCollector.java deleted file mode 100644 index afc7c08b1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/MatchCollector.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * - */ -package com.bbn.openmap.geo; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -public interface MatchCollector { - /** - * collect an indication that the query object a (or some part of it) - * matches object b in some way, presumably by intersection. - * - * @param a - * @param b - */ - void collect(T a, T b); - - /** @return an iterator over the previously collected elements * */ - Iterator iterator(); - - /** - * A MatchCollector that collects a list of pairs of the matching objects - */ - public static class PairArrayMatchCollector implements MatchCollector { - protected final List> result = new ArrayList>(); - - public void collect(T a, T b) { - result.add(new MatchCollector.Pair(a, b)); - } - - /** - * This returns an iterator over a List of Pair - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Iterator iterator() { - return result.iterator(); - } - } - - public static class Pair { - private T a; - private T b; - - public Pair(T a, T b) { - this.a = a; - this.b = b; - } - - public T getA() { - return a; - } - - public T getB() { - return b; - } - } - - public static class SetMatchCollector implements MatchCollector { - protected final Set result = new HashSet(); - - public void collect(T a, T b) { - result.add(b); - } - - public Iterator iterator() { - return result.iterator(); - } - } - - public static class CollectionMatchCollector implements MatchCollector { - protected final Collection c; - - public CollectionMatchCollector(Collection c) { - this.c = c; - } - - public void collect(T a, T b) { - c.add(b); - } - - public Iterator iterator() { - return c.iterator(); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/geo/MatchFilter.java b/src/core/src/main/java/com/bbn/openmap/geo/MatchFilter.java deleted file mode 100644 index e6c061efd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/MatchFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * - */ -package com.bbn.openmap.geo; - -public interface MatchFilter { - - /** - * do inexpensive comparisons to determine if the two elements might - * intersect. - * - * @return true iff further checks might yield intersection. - */ - boolean preConsider(GeoExtent seg, GeoExtent region); - - /** - * the distance (in radians) to consider two objects to be interacting, that - * is, intersecting for our purposes. - * - * @return the maximum distance to consider touching. Must be non-negative. - */ - double getHRange(); - - // - // implementations - // - - public static class MatchParametersMF - implements MatchFilter { - protected double hrange = 0.0; - - public MatchParametersMF(MatchParameters params) { - // initialize search parameters from method calls - hrange = params.horizontalRange(); - } - - public MatchParametersMF(double hrange, int[] vrange, long[] trange) { - this.hrange = hrange; - } - - public double getHRange() { - return hrange; - } - - public boolean preConsider(GeoExtent seg, GeoExtent region) { - return true; - } - } - - public static class ExactMF - implements MatchFilter { - public double getHRange() { - return 0.0; - } - - public boolean preConsider(GeoExtent seg, GeoExtent region) { - return true; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/geo/MatchParameters.java b/src/core/src/main/java/com/bbn/openmap/geo/MatchParameters.java deleted file mode 100644 index badbcb8b5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/MatchParameters.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * The terms that describe how matches between Geo objects are to be - * performed. - */ -public interface MatchParameters { - - /** - * return the horizontal deviation (range) to consider matching. - * The value is in radians. 0.0 implies strict intersection. Note - * that if a RegionIndex is being used, then this value probably - * must be no larger than the index's margin to avoid missing - * regions that are near index boundaries. - */ - double horizontalRange(); - - public class Standard implements MatchParameters { - double hr; - - public Standard(double hr) { - this.hr = hr; - } - - public double horizontalRange() { - return hr; - } - - } - - /** - * A set of parameters that matches radius of 10 nmiles. - */ - MatchParameters ROUTE_DEFAULT = new Standard(Geo.nmToAngle(10)); - /** - * A set of parameters for strict intersections, 0 nmiles. - */ - MatchParameters STRICT = new Standard(0.0); -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/OMGeo.java b/src/core/src/main/java/com/bbn/openmap/geo/OMGeo.java deleted file mode 100644 index 0df81b23b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/OMGeo.java +++ /dev/null @@ -1,428 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: OMGeo.java,v $ -//$Revision: 1.6 $ -//$Date: 2009/01/21 01:24:42 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -import java.awt.Point; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicAdapter; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * This is a class (or set of classes) that map GeoExtents to OMGraphics. They - * can be used directly in a ExtentIndex and will render within OpenMap. This - * class is not considered to be part of the omgeo.jar package because of its - * dependencies on OpenMap, but resides in this package because of it's - * knowledge of it. - * - * @author dietrick - */ -@SuppressWarnings("serial") -public abstract class OMGeo extends OMGraphicAdapter implements GeoExtent { - - protected GeoExtent extent; - protected Object id = OMGeo.this; - - protected OMGeo() { - setRenderType(RENDERTYPE_LATLON); - setLineType(LINETYPE_GREATCIRCLE); - } - - protected OMGeo(GeoExtent ge) { - this(); - setExtent(ge); - } - - public GeoExtent getExtent() { - return extent; - } - - public void setExtent(GeoExtent ge) { - extent = ge; - } - - public BoundingCircle getBoundingCircle() { - return getExtent().getBoundingCircle(); - } - - public Object getID() { - return id; - } - - public void setID(Object id) { - this.id = id; - } - - public static class Pt extends OMGeo implements GeoPoint { - - protected int radius = OMPoint.DEFAULT_RADIUS; - protected boolean isOval = true; - - public Pt(GeoPoint gp) { - super(gp); - } - - public Pt(Geo g) { - super(new GeoPoint.Impl(g)); - } - - public Pt(double lat, double lon, boolean isDegrees) { - super(new GeoPoint.Impl(lat, lon, isDegrees)); - } - - public Pt(OMPoint pnt) { - this(pnt.getLat(), pnt.getLon(), true); - setAttributes(pnt.getAttributes()); - } - - public Geo getGeo() { - return ((GeoPoint) getExtent()).getPoint(); - } - - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "GeoOMGraphic.Point: null projection in generate!"); - return false; - } - - Geo geo = getPoint(); - double lat = geo.getLatitude(); - double lon = geo.getLongitude(); - - if (!proj.isPlotable(lat, lon)) { - setNeedToRegenerate(true);// HMMM not the best flag - return false; - } - - Point2D p1 = new Point2D.Double(); - proj.forward(lat, lon, p1); - - double x1 = p1.getX() - radius; - double y1 = p1.getY() - radius; - double x2 = p1.getX() + radius; - double y2 = p1.getY() + radius; - - if (isOval) { - setShape(new GeneralPath(new Ellipse2D.Float((float) Math.min(x2, x1), (float) Math.min(y2, y1), - (float) Math.abs(x2 - x1), (float) Math.abs(y2 - y1)))); - } else { - setShape(createBoxShape((int) Math.min(x2, x1), (int) Math.min(y2, y1), (int) Math.abs(x2 - x1), - (int) Math.abs(y2 - y1))); - } - - initLabelingDuringGenerate(); - setLabelLocation(new Point((int) x2, (int) y1), proj); - - setNeedToRegenerate(false); - return true; - } - - public boolean isOval() { - return isOval; - } - - public void setOval(boolean isOval) { - this.isOval = isOval; - } - - public int getRadius() { - return radius; - } - - public void setRadius(int radius) { - this.radius = radius; - } - - public Geo getPoint() { - return ((GeoPoint) getExtent()).getPoint(); - } - } - - public static class Line extends OMGeo implements GeoSegment { - - public Line(GeoSegment gs) { - super(gs); - } - - public Line(Geo[] gs) { - super(new GeoSegment.Impl(gs)); - } - - public Line(OMLine line) { - this(new Geo[] { new Geo(line.getLL()[0], line.getLL()[1]), new Geo(line.getLL()[2], line.getLL()[3]) }); - setAttributes(line.getAttributes()); - } - - public Geo[] getGeoArray() { - return ((GeoSegment) getExtent()).getSeg(); - } - - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "GeoOMGraphic.Line: null projection in generate!"); - return false; - } - - // reset the internals - initLabelingDuringGenerate(); - - double[] latlons = getSegArray(); - - ArrayList lines = null; - if (proj instanceof GeoProj) { - lines = ((GeoProj) proj).forwardLine(new LatLonPoint.Double(latlons[0], latlons[1]), - new LatLonPoint.Double(latlons[2], latlons[3]), lineType, -1); - } else { - lines = proj.forwardLine(new Point2D.Double(latlons[1], latlons[0]), - new Point2D.Double(latlons[3], latlons[2])); - } - - int size = lines.size(); - - float[][] xpoints = new float[(int) (size / 2)][0]; - float[][] ypoints = new float[xpoints.length][0]; - - GeneralPath projectedShape = null; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - float[] xps = (float[]) lines.get(i); - float[] yps = (float[]) lines.get(i + 1); - - xpoints[j] = xps; - ypoints[j] = yps; - - GeneralPath gp = createShape(xps, yps, false); - if (projectedShape == null) { - projectedShape = gp; - } else { - projectedShape.append(gp, false); - } - } - - setShape(projectedShape); - setLabelLocation(projectedShape, proj); - setNeedToRegenerate(false); - return true; - } - - public Geo[] getSeg() { - return ((GeoSegment) getExtent()).getSeg(); - } - - public double[] getSegArray() { - return ((GeoSegment) getExtent()).getSegArray(); - } - - } - - public static class Polyline extends OMGeo implements GeoPath { - - public Polyline(GeoPath gp) { - super(gp); - } - - public Polyline(Geo[] gs) { - super(new GeoPath.Impl(gs)); - } - - public Polyline(GeoArray points) { - super(new GeoPath.Impl(points)); - } - - public Polyline(OMPoly poly) { - this(GeoArray.Double.createFromLatLonRadians(poly.getLatLonArray())); - setAttributes(poly.getAttributes()); - } - - public GeoArray getPoints() { - return ((GeoPath) getExtent()).getPoints(); - } - - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - boolean isPolygon = isGeometryClosed(); - - if (proj == null) { - Debug.message("omgraphic", "GeoOMGraphic.Poly: null projection in generate!"); - return false; - } - - // answer the question now, saving calculation for future - // calculations. The set method forces the calculation for - // the query. - - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians. - - // We might want to cache the latlon points retrieved from the - // GeoArray at some point. - ArrayList vector; - if (proj instanceof GeoProj) { - vector = ((GeoProj) proj).forwardPoly(getPoints().toLLRadians(), lineType, -1, isPolygon); - } else { - vector = proj.forwardPoly(getPoints().toLLDegrees(), isPolygon); - } - - int size = vector.size(); - - float[][] xpoints = new float[(int) (size / 2)][0]; - float[][] ypoints = new float[xpoints.length][0]; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - xpoints[j] = (float[]) vector.get(i); - ypoints[j] = (float[]) vector.get(i + 1); - } - - initLabelingDuringGenerate(); - - size = xpoints.length; - GeneralPath projectedShape = null; - for (int i = 0; i < size; i++) { - GeneralPath gp = createShape(xpoints[i], ypoints[i], isPolygon); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - setShape(projectedShape); - setLabelLocation(xpoints[0], ypoints[0], proj); - - setNeedToRegenerate(false); - return true; - } - - protected boolean isGeometryClosed() { - return false; - } - - protected boolean isGeometryClosed(float[] rawllpts) { - boolean geometryClosed = false; - - if (rawllpts != null) { - int l = rawllpts.length; - if (l > 4) { - geometryClosed = (MoreMath.approximately_equal(rawllpts[0], rawllpts[l - 2]) - && MoreMath.approximately_equal(rawllpts[1], rawllpts[l - 1])); - } - } - - return geometryClosed; - } - - public boolean isSegmentNear(GeoSegment s, double epsilon) { - return ((GeoPath) getExtent()).isSegmentNear(s, epsilon); - } - - public int length() { - return ((GeoPath) getExtent()).length(); - } - - public Iterator pointIterator() { - return ((GeoPath) getExtent()).pointIterator(); - } - - public Iterator segmentIterator() { - return ((GeoPath) getExtent()).segmentIterator(); - } - } - - public static class Polygon extends Polyline implements GeoRegion { - - public Polygon(GeoPath gp) { - super(gp); - } - - public Polygon(Geo[] gs) { - super(new GeoRegion.Impl(gs)); - } - - public Polygon(GeoArray points) { - super(new GeoRegion.Impl(points)); - } - - public Polygon(OMPoly poly) { - this(GeoArray.Double.createFromLatLonRadians(poly.getLatLonArray())); - setAttributes(poly.getAttributes()); - } - - public boolean isPointInside(Geo point) { - return ((GeoRegion) getExtent()).isPointInside(point); - } - - protected boolean isGeometryClosed() { - return true; - } - } - - public static OMGeo create(GeoExtent extent) { - if (extent instanceof GeoPoint) { - return new OMGeo.Pt((GeoPoint) extent); - } else if (extent instanceof GeoRegion) { - return new OMGeo.Polygon((GeoRegion) extent); - } else if (extent instanceof GeoSegment) { - return new OMGeo.Line((GeoSegment) extent); - } else if (extent instanceof GeoPath) { - return new OMGeo.Polyline((GeoPath) extent); - } - return new OMGeo.Pt(extent.getBoundingCircle().getCenter()); - } - - public static OMGeo create(OMGraphic omg) { - if (omg instanceof OMPoint) { - return new OMGeo.Pt((OMPoint) omg); - } else if (omg instanceof OMLine) { - return new OMGeo.Line((OMLine) omg); - } else if (omg instanceof OMPoly){ - OMPoly poly = (OMPoly) omg; - if (poly.isPolygon()) { - return new OMGeo.Polygon(poly); - } else { - return new OMGeo.Polyline(poly); - } - } - - return null; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/Quadratic.java b/src/core/src/main/java/com/bbn/openmap/geo/Quadratic.java deleted file mode 100644 index 7d1a591ca..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/Quadratic.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (C) BBNT Solutions LLC. All Rights Reserved - * $Id: Quadratic.java,v 1.1 2005/11/18 14:57:46 mthome Exp $ - */ - -package com.bbn.openmap.geo; - -/** - * Computes 0 to 2 real roots of the quadratic: - * - *
- *    a*x^2 + b*x + c = 0
- * 
- * - * See http://web.cs.mun.ca/courses/cs2710-w02/lab5/assignment/assign5.html. - * http://www.1728.com/quadratc.htm - *

- * Access the roots as a double iterator with methods hasNext() and next(). - */ - -public class Quadratic { - double a, b, c; - double[] solution; - int index = 0; - - public Quadratic(double a, double b, double c) { - this.a = a; - this.b = b; - this.c = c; - solve(); - } - - /** Returns the solution, x, to the equation a*x+b = 0 **/ - public static double linear(double a, double b) { - return -b / a; - } - - /** - * Solve a*x^2 + b*x + c = 0 for x for real values of x. - *

- * - * See Winston and Horn, LISP p. 167-169. - */ - public void solve() { - if (a == 0.0 && b == 0.0) - values(); - else if (a == 0.0 && b != 0.0) - values(linear(b, c)); - else if (a != 0.0 && c == 0.0) - values(0.0, linear(a, b)); - else { - double d = b * b - 4.0 * a * c; - if (d < 0.0) - values(); // Complex roots. - else if (d == 0.0) - values(-b / (2.0 * a)); - else - values((-b + Math.sqrt(d)) / (2.0 * a), (-b - Math.sqrt(d)) / (2.0 * a)); - } - } - - /** Evaluate the Quadratic at x. **/ - public double eval(double x) { - return (a * x + b) * x + c; - } - - public boolean hasNext() { - return index < solution.length; - } - - public double next() { - if (this.hasNext()) - return solution[index++]; - else - throw new java.util.NoSuchElementException(); - } - - public String toString() { - return "{" + a + "*x^2 + " + b + "*x + " + c + " = 0 [" + solutionToString() + "]}"; - } - - private String solutionToString() { - switch (solution.length) { - case 0: - return ""; - case 1: - return String.valueOf(solution[0]); - case 2: - return String.valueOf(solution[0]) + " " + String.valueOf(solution[1]); - default: - return ""; // Can't happen. - } - } - - private void values() { - solution = new double[0]; - } - - private void values(double s1) { - solution = new double[] { - s1 - }; - } - - private void values(double s1, double s2) { - solution = new double[] { - s1, - s2 - }; - } - - public String test() { - String s = this + " test: "; - switch (solution.length) { - case 0: - return ""; - case 1: - return s + this.eval(solution[0]); - case 2: - return s + this.eval(solution[0]) + " " + this.eval(solution[1]); - default: - return ""; // Can't happen. - } - } - - static private void p(double a, double b, double c) { - System.out.println((new Quadratic(a, b, c)).test()); - } - - public static void main(String[] args) { - p(0.0, 0.0, -30.0); - p(0.0, 4.0, 0.0); - p(0.0, 4.0, -30.0); - p(2.0, 4.0, 0.0); - p(2.0, 4.0, -30.0); - p(1.0, 4.0, 1.0); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/RadialRegion.java b/src/core/src/main/java/com/bbn/openmap/geo/RadialRegion.java deleted file mode 100644 index 4c58de164..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/RadialRegion.java +++ /dev/null @@ -1,50 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: RadialRegion.java,v $ -//$Revision: 1.2 $ -//$Date: 2007/01/30 20:37:01 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -public class RadialRegion extends BoundingCircle.Impl implements GeoExtent { - - protected Object id = RadialRegion.this; - - public RadialRegion(Geo center, double radius) { - super(center, radius); - } - - public RadialRegion(Geo[] region) { - super(region); - } - - public BoundingCircle getBoundingCircle() { - return this; - } - - public Object getID() { - return id; - } - - public void setID(Object id) { - this.id = id; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/Ribbon.java b/src/core/src/main/java/com/bbn/openmap/geo/Ribbon.java deleted file mode 100644 index eb28ef2dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/Ribbon.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * Represents 3 points across great circle, see RibbonIterator. - *

- * The three points, are - *

    - *
  • LEFT, a point radius radians to the left of the great circle. - *
  • CENTER, a point on the great circle. - *
  • RIGHT, a point radius radians to the right of the great circle. - *
- */ -public class Ribbon { - - public static final int LEFT = 0; - public static final int CENTER = 1; - public static final int RIGHT = 2; - - private Geo[] point; - - /** - * Get the Geo for the Ribbon. - * - * @param which LEFT, RIGHT or CENTER - * @return Geo - */ - public Geo get(int which) { - return point[which]; - } - - /** - * @param which LEFT, RIGHT or CENTER - * @return latitude of Geo. - */ - public double getLatitude(int which) { - return point[which].getLatitude(); - } - - /** - * @param which LEFT, RIGHT or CENTER - * @return longitude of Geo - */ - public double getLongitude(int which) { - return point[which].getLongitude(); - } - - /** - * Create a Ribbon at the point x along the great circle who's normal is gc, - * and radius is the distance apart in radians. - */ - public Ribbon(Geo x, Geo gc, double radius) { - Geo v = x.crossNormalize(gc); - Rotation r = new Rotation(v, radius); - Geo left = r.rotate(x); - point = new Geo[] { left, x, x.add(x.subtract(left)) }; - } - - /** - * Call for RibbonIterator to create empty Ribbon when weird parameters are - * passed in. - * - * @return empty Ribbon. - */ - public static Ribbon getEmpty() { - return new Ribbon(new Object()); - } - - /** - * For EMPTY Ribbon. - * - * @param dummy - */ - private Ribbon(Object dummy) { - point = new Geo[] {}; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/RibbonIterator.java b/src/core/src/main/java/com/bbn/openmap/geo/RibbonIterator.java deleted file mode 100644 index 4cc99a7f2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/RibbonIterator.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ -package com.bbn.openmap.geo; - -import java.util.Iterator; - -/** - * Iterate along a sequence of Ribbons. A Ribbon is a three Geo set, with a - * RIGHT, CENTER and LEFT Geo in the Ribbon. The location of the LEFT and RIGHT - * Geo are perpendicular to the great circle path that the CENTER Geo resides - * on. - */ -public class RibbonIterator implements Iterator, Iterable { - - protected Geo v1; - protected Geo v2; - protected double radius; - protected Geo gc; - protected Rotation rotator; - protected Geo point; - protected double distance; - - /** - * Return an iterator that returns Ribbons along the great circle between v1 - * and v2. The Ribbon points are radius radians apart, and each Ribbon is - * 2*radius apart. - */ - public RibbonIterator(Geo v1, Geo v2, double radius) { - this(v1, v2, radius, 2.0 * radius); - } - - /** - * Return an iterator that returns Ribbons along the great circle between v1 - * and v2. The Ribbon points are radius radians apart, and each Ribbon is - * rotationIntervalDist apart. - * - * @param v1 from this Geo - * @param v2 to this Geo - * @param radius distance away from great circle lines between geos, in - * radians. - * @param rotationIntervalDist interval distance between ribbons, in - * radians. You want this to be smaller than the distance between the - * geos, obviously. - */ - public RibbonIterator(Geo v1, Geo v2, double radius, double rotationIntervalDist) { - this.v1 = v1; - this.v2 = v2; - - if (v1 == null || v2 == null || v1.equals(v2)) { - // hasNext should fail - this.point = v2; - } else { - this.distance = v1.distance(v2); - this.radius = radius; - this.gc = v1.crossNormalize(v2); - this.rotator = new Rotation(gc, rotationIntervalDist); - this.point = v1; - } - } - - /** - * Call after hasNext() returns true. - * - * @return next Ribbon containing points at offset from v1 and v2. - */ - public Ribbon next() { - if (!hasNext()) { - return Ribbon.getEmpty(); - } - - if (point != v2 && v1.distance(point) < distance) { - Ribbon result = new Ribbon(point, gc, radius); - point = rotator.rotate(point); - return result; - } else { - point = v2; - return new Ribbon(point, gc, radius); - } - } - - /** - * Are there more Ribbons in the iterator? - * - * @return true if there are, then call next(). - */ - public boolean hasNext() { - return point != v2; - } - - public void remove() { - } - - public Iterator iterator() { - return this; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/Rotation.java b/src/core/src/main/java/com/bbn/openmap/geo/Rotation.java deleted file mode 100644 index 5f868ef0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/Rotation.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * RESTRICTED RIGHTS LEGEND - * - * BBNT Solutions LLC - * A Verizon Company - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright BBNT Solutions LLC 2001, 2002 All Rights Reserved - * - */ - -package com.bbn.openmap.geo; - -/** - * Defines a 3-D rotation, M, such that the matrix multiplication, Mv, rotates - * vector v an angle ,angle, counter clockwise about the Geo, g. See Newman and - * Sproull, 1973, Principles of Interactive Computer Garaphics, McGraw-Hill, New - * York, 463-465. - */ -public class Rotation { - - protected Geo g; - double m00, m11, m22, m01, m10, m12, m21, m02, m20; - - public Rotation(Geo g, double angle) { - this.g = g; - this.setAngle(angle); - } - - private void setAngle(double angle) { - double x = g.x(); - double y = g.y(); - double z = g.z(); - double c = Math.cos(angle); - double s = Math.sin(angle); - double b = 1.0 - c; - double bx = b * x; - double by = b * y; - double bz = b * z; - double bxx = bx * x; - double bxy = bx * y; - double bxz = bx * z; - double byy = by * y; - double byz = by * z; - double bzz = bz * z; - double sx = s * x; - double sy = s * y; - double sz = s * z; - m00 = c + bxx; - m11 = c + byy; - m22 = c + bzz; - m01 = (-sz) + bxy; - m10 = sz + bxy; - m12 = (-sx) + byz; - m21 = sx + byz; - m02 = sy + bxz; - m20 = (-sy) + bxz; - - /** - * System.out.println (" Rotation " + m00 + " " + m11 + " " + m22 + "\n" + - * m01 + " " + m10 + " " + m12 + "\n" + m21 + " " + m02 + " " + m20); - */ - } - - public Geo rotate(Geo v) { - double x = v.x(), y = v.y(), z = v.z(); - return new Geo(m00 * x + m01 * y + m02 * z, m10 * x + m11 * y + m12 * z, m20 - * x + m21 * y + m22 * z); - } - - /** - * Static method that does what creating a Rotation object can calling - * rotate() on it does. Rotates vector v2 an angle counter clockwise about - * the Geo, v1. - * - * @param v1 - * @param angle - * @param v2 - * @param ret The Geo to load the results in, may be null which will cause - * the method to allocate a new Geo object. - * @return the ret Geo passed in, or a new one if ret was null. - */ - public final static Geo rotate(Geo v1, double angle, Geo v2, Geo ret) { - double x = v1.x(); - double y = v1.y(); - double z = v1.z(); - double c = Math.cos(angle); - double s = Math.sin(angle); - double b = 1.0 - c; - double bx = b * x; - double by = b * y; - double bz = b * z; - double bxx = bx * x; - double bxy = bx * y; - double bxz = bx * z; - double byy = by * y; - double byz = by * z; - double bzz = bz * z; - double sx = s * x; - double sy = s * y; - double sz = s * z; - double m00 = c + bxx; - double m11 = c + byy; - double m22 = c + bzz; - double m01 = (-sz) + bxy; - double m10 = sz + bxy; - double m12 = (-sx) + byz; - double m21 = sx + byz; - double m02 = sy + bxz; - double m20 = (-sy) + bxz; - - /** - * System.out.println (" Rotation " + m00 + " " + m11 + " " + m22 + "\n" + - * m01 + " " + m10 + " " + m12 + "\n" + m21 + " " + m02 + " " + m20); - */ - double x2 = v2.x(); - double y2 = v2.y(); - double z2 = v2.z(); - - if (ret == null) { - return new Geo(m00 * x2 + m01 * y2 + m02 * z2, m10 * x2 + m11 * y2 - + m12 * z2, m20 * x2 + m21 * y2 + m22 * z2); - } - - ret.initialize(m00 * x2 + m01 * y2 + m02 * z2, m10 * x2 + m11 * y2 - + m12 * z2, m20 * x2 + m21 * y2 + m22 * z2); - - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/geo/package.html b/src/core/src/main/java/com/bbn/openmap/geo/package.html deleted file mode 100644 index c803c1fb3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/geo/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Package that contains classes to do calculations in lat/lon space. - - diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/AbstractGraphicLoader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/AbstractGraphicLoader.java deleted file mode 100644 index b77a1640e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/AbstractGraphicLoader.java +++ /dev/null @@ -1,219 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/AbstractGraphicLoader.java,v $ -// $RCSfile: AbstractGraphicLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:44:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.Timer; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The abstract AbstractGraphicLoader class is an OMGraphic managing - * object. It can talk to any source it wants to for configuring its - * OMGraphicList, and then notifies its OMGraphicHandler with the - * changes. The AbstractGraphicLoader comes with a built-in timer, in - * case you want to check back with the graphic source within certain - * intervals in order to update the graphics in an animated fashion. - * This class also extends MapHandlerChild so if you want to add it to - * the MapHandler to find other objects, you can override the - * findAndInit() method. - *

- * - * This object is really intended to be used with the - * GraphicLoaderPlugIn, but it doesn't really have to be. If you have - * a GraphicLoaderConnector in the MapHandler and then add a - * GraphicLoader to the MapHandler, the GraphicLoaderConnector will - * check to see if the GraphicLoader has a receiver. If there isn't a - * receiver, the GraphicLoaderConnetor will create a - * GraphicLoaderPlugIn for you, connect the GraphicLoader to it, and - * then add the GraphicLoaderPlugIn to the LayerHandler. Then, the - * GraphicLoader will have its graphics on the map. - */ -public abstract class AbstractGraphicLoader extends OMComponent implements - GraphicLoader, ActionListener { - - protected Timer timer; - protected int DO_NOT_UPDATE_TIMER = -1; - protected OMGraphicHandler receiver = null; - protected Projection proj; // last projection - protected String name = ""; - - public final static String TimerCmd = "TimerCommand"; - public final static String NameProperty = "prettyName"; - - public AbstractGraphicLoader() { - createTimer(); - } - - public AbstractGraphicLoader(OMGraphicHandler receiver) { - super(); - setReceiver(receiver); - manageGraphics(); - } - - /** - * The method where the AbstractGraphicLoader is expected to tell - * the receiver what the OMGraphics are. This gets called by - * default by the actionPerformed() method, which is called by - * default by the built-in timer when it is running. - * - * @see com.bbn.openmap.omGraphics.OMGraphicHandler#setList(OMGraphicList) - */ - public abstract void manageGraphics(); - - /** - * Provide a GUI for controlling the GraphicLoader. It's OK if - * it's null. - */ - public Component getGUI() { - return null; - } - - /** - * Calls manageGraphics() if projection is different(). - */ - public void setProjection(Projection p) { - if (!p.equals(getProjection())) { - proj = p; - manageGraphics(); - } - } - - public Projection getProjection() { - return proj; - } - - public void setReceiver(OMGraphicHandler r) { - receiver = r; - } - - public OMGraphicHandler getReceiver() { - return receiver; - } - - /** - * Get the timer being used for automatic updates. May be null if - * a timer is not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, - * you can set the timer to do that. Set it to null to disable it. - * If the current timer is not null, the graphic loader is removed - * as an ActionListener. If the new one is not null, the graphic - * loader is added as an ActionListener. - */ - public void setTimer(Timer t) { - if (timer != null) { - timer.stop(); - timer.removeActionListener(this); - } - - timer = t; - if (timer != null) { - timer.addActionListener(this); - } - } - - /** - * Creates a timer with the current updateInterval and calls - * setTimer(). - */ - public void createTimer() { - Timer t = new Timer(updateInterval, null); - t.setInitialDelay(0); - setTimer(t); - } - - /** - * The delay between timer pulses, in milliseconds. - */ - protected int updateInterval = 3000; - - public void setUpdateInterval(int delay) { - updateInterval = delay; - if (timer != null) { - timer.setDelay(updateInterval); - if (timer.isRunning()) { - timer.restart(); - } - } - } - - public int getUpdateInterval() { - return updateInterval; - } - - /** - * Method gets called by the timer if it's running. Will also get - * called if any other component is using this class as an - * ActionListener. By default, calls manageGraphics(); - */ - public void actionPerformed(ActionEvent ae) { - manageGraphics(); - } - - /** - * Return a pretty name for the GUI to let folks know what the - * loader does. - */ - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - name = props.getProperty(prefix + NameProperty, name); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + NameProperty, getName()); - return props; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - list.put(NameProperty, - "A short name description for what this GraphicLoader does."); - return list; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/GLPoint.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/GLPoint.java deleted file mode 100644 index 466c24d74..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/GLPoint.java +++ /dev/null @@ -1,268 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/GLPoint.java,v $ -// $RCSfile: GLPoint.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.Color; -import java.awt.GridLayout; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; - -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.InternalFrameAdapter; -import javax.swing.event.InternalFrameEvent; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * A GLPoint is a location on the map. It can move around randomly if - * it's not set to be stationary, and will change color if it can see - * any other point. - */ -public class GLPoint extends OMPoint implements ActionListener, FocusListener { - - private static final long serialVersionUID = 1L; - public static Color CONNECTED_COLOR = Color.green; - public static Color DISCONNECTED_COLOR = Color.red; - protected boolean stationary = true; - protected String name; - protected int height = 0;// meters. - - public GLPoint(double lat, double lon, int radius, boolean isOval) { - super(lat, lon, radius); - setOval(isOval); - } - - public void resetConnected() { - setFillPaint(DISCONNECTED_COLOR); - } - - public void connected(boolean connected) { - if (connected) { - setFillPaint(CONNECTED_COLOR); - } - } - - protected void moveRandomly(float factor) { - double hor = Math.random() - .5; - double vert = Math.random() - .5; - - setLat(getLat() + (float) vert * factor); - setLon(getLon() + (float) hor * factor); - } - - public void move(float factor) { - if (!stationary) { - moveRandomly(factor); - } - } - - public void move(int distance, Length units, float Az) { - LatLonPoint newLocation = GreatCircle.sphericalBetween(ProjMath.degToRad(getLat()), - ProjMath.degToRad(getLon()), - units.toRadians(distance), - Az); - - setLat(newLocation.getY()); - setLon(newLocation.getX()); - } - - public void setStationary(boolean set) { - stationary = set; - if (movementButton != null) { - movementButton.setSelected(set); - } - } - - public boolean getStationary() { - return stationary; - } - - public void setName(String set) { - name = set; - } - - public String getName() { - return name; - } - - public void setHeight(int h) { - height = h; - if (heightField != null) { - heightField.setText(Integer.toString(h)); - } - if (Debug.debugging("graphicloader")) { - Debug.output("GLPoint: " + getName() + " setting height to : " + h); - } - } - - public int getHeight() { - return height; - } - - protected transient java.awt.Container palette = null; - - /** - * Make the palette visible. Will automatically determine if we're - * running in an applet environment and will use a JInternalFrame - * over a JFrame if necessary. - */ - public void showPalette() { - if (Environment.getBoolean(Environment.UseInternalFrames)) { - - final JLayeredPane desktop = Environment.getInternalFrameDesktop(); - - // get the window - palette = PaletteHelper.getPaletteInternalWindow(getGUI(), - getName(), - new InternalFrameAdapter() { - public void internalFrameClosed(InternalFrameEvent e) { - if (desktop != null) { - desktop.remove((JInternalFrame) palette); - desktop.repaint(); - } - palette = null; - } - }); - // add the window to the desktop - if (desktop != null) { - desktop.add(palette); - palette.setVisible(true); - } - } else { - if (palette == null) { - palette = PaletteHelper.getPaletteWindow(getGUI(), - getName(), - new ComponentAdapter() { - public void componentHidden(ComponentEvent e) { - // firePaletteEvent(false); - } - }); - } - palette.setVisible(true); - ((JFrame) palette).setState(java.awt.Frame.NORMAL); - } - } - - /** - * Hide the GLPoint's palette. - */ - public void hidePalette() { - if (palette == null) { - return; - } - - if (Environment.getBoolean(Environment.UseInternalFrames)) { - // close the palette - try { - ((JInternalFrame) palette).setClosed(true); - } catch (java.beans.PropertyVetoException evt) { - com.bbn.openmap.util.Assert.assertExp(false, - "GLPoint.hidePalette(): internal error!"); - } - } else { - palette.setVisible(false); - } - } - - JCheckBox movementButton = null; - JTextField heightField = null; - - /** - * Gets the gui controls associated with the GLPoint. This default - * implementation returns null indicating that the GLPoint has no - * gui controls. - * - * @return java.awt.Component or null - */ - public java.awt.Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - - // Only want to do this once... - if (movementButton == null) { - movementButton = new JCheckBox("Stationary", getStationary()); - movementButton.addActionListener(this); - movementButton.setActionCommand(MoveCmd); - } - - panel.add(movementButton); - - JPanel heightPanel = new JPanel(new GridLayout(0, 3)); - - heightPanel.add(new JLabel("Object height: ")); - if (heightField == null) { - heightField = new JTextField(Integer.toString(height), 10); - heightField.setHorizontalAlignment(JTextField.RIGHT); - heightField.addActionListener(this); - heightField.addFocusListener(this); - } - heightPanel.add(heightField); - heightPanel.add(new JLabel(" meters")); - - panel.add(heightPanel); - - return panel; - } - - public final static String MoveCmd = "MoveCommand"; - - public void actionPerformed(java.awt.event.ActionEvent ae) { - String cmd = ae.getActionCommand(); - if (cmd == MoveCmd) { - JCheckBox check = (JCheckBox) ae.getSource(); - setStationary(check.isSelected()); - } else { - try { - setHeight(Integer.parseInt(cmd)); - } catch (NumberFormatException nfe) { - setHeight(getHeight()); - } - } - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) { - try { - setHeight(Integer.parseInt(((JTextField) (e.getSource())).getText())); - } catch (NumberFormatException nfe) { - setHeight(0); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/GraphicLoader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/GraphicLoader.java deleted file mode 100644 index 50c5d3bb7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/GraphicLoader.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/GraphicLoader.java,v $ -// $RCSfile: GraphicLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.Component; - -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.proj.Projection; - -/** - * The interface that describes an object that supplies updates to - * OMGraphics presented by the GraphicLoaderPlugIn. - */ -public interface GraphicLoader { - /** - * The method that calls the GUI that controls the GraphicLoader. - */ - public Component getGUI(); - - /** - * Let the GraphicLoader know what the projection is. - */ - public void setProjection(Projection p); - - /** - * Set the OMGraphicHandler that will receive OMGraphic updates - * from the GraphicLoader. - */ - public void setReceiver(OMGraphicHandler r); - - /** - * Get the OMGraphicHandler that will receive OMGraphic updates - * from the GraphicLoader. - */ - public OMGraphicHandler getReceiver(); - - /** - * Get a pretty name for GUI representation that lets folks know - * what the GraphicLoader does. - */ - public String getName(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/LOSGraphicLoader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/LOSGraphicLoader.java deleted file mode 100644 index e0fa3762d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/LOSGraphicLoader.java +++ /dev/null @@ -1,366 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/LOSGraphicLoader.java,v $ -// $RCSfile: LOSGraphicLoader.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/02/16 16:22:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.HashMap; -import java.util.Iterator; -import java.util.logging.Logger; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.dataAccess.dted.DTEDFrameCache; -import com.bbn.openmap.omGraphics.BasicStrokeEditor; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.tools.terrain.LOSGenerator; - -/** - * A managing object of GLPoints and PathGLPoints. Has a timer to move - * them around and uses the DTED data to figure out which GLPoints can - * see each other. - */ -public class LOSGraphicLoader extends MMLGraphicLoader implements - ActionListener, DrawingToolRequestor { - - protected DTEDFrameCache dfc = null; - protected LOSGenerator los; - protected OMDrawingTool dt = null; - - public final static String AddNodeCmd = "AddNodeCommand"; - public final static String AddPathCmd = "AddPathCommand"; - - HashMap points = new HashMap(); - - public static Logger logger = Logger.getLogger("com.bbn.openmap.graphicLoader.LOSGraphicLoader"); - - public LOSGraphicLoader() { - super(); - setName("LOS Demo"); - } - - public LOSGraphicLoader(OMGraphicHandler receiver) { - super(); - setReceiver(receiver); - } - - public LOSGraphicLoader(DTEDFrameCache dfc, OMGraphicHandler receiver) { - this(receiver); - - setDTEDFrameCache(dfc); - - // GLPoint mp1 = new GLPoint(42f, -72.5f, 5, true); - // mp1.setName("First"); - // mp1.setHeight(100); - // points.put(mp1.getName(), mp1); - - // GLPoint mp2 = new GLPoint(42f, -72.5f, 5, true); - // mp2.setName("Second"); - // mp2.setStationary(false); - // points.put(mp2.getName(), mp2); - - // GLPoint mp3 = new GLPoint(42f, -72.5f, 5, true); - // mp3.setName("Third"); - // mp3.setStationary(false); - // points.put(mp3.getName(), mp3); - - manageGraphics(); - } - - public void manageGraphics() { - OMGraphicList list = new OMGraphicList(); - - Iterator it = points.values().iterator(); - GLPoint mp; - - while (it.hasNext()) { - mp = (GLPoint) it.next(); - mp.move(40f); - mp.resetConnected(); - list.add(mp); - } - - it = points.keySet().iterator(); - while (it.hasNext()) { - String mpName = (String) it.next(); - mp = (GLPoint) points.get(mpName); - - Iterator it2 = points.values().iterator(); - while (it2.hasNext()) { - GLPoint mp2 = (GLPoint) it2.next(); - if (mp2 != mp) { - isLOS(mp, mp2, list); - } - } - } - - if (receiver != null) { - logger.fine("Updating graphics."); - receiver.setList(list); - } else { - logger.fine("no receiver to notify."); - } - - } - - public boolean isLOS(GLPoint pt1, GLPoint pt2, OMGraphicList list) { - boolean ret = false; - if (los != null) { - int numPoints = 2; - if (proj != null) { - Point2D p1 = proj.forward(pt1.getLat(), pt1.getLon()); - Point2D p2 = proj.forward(pt2.getLat(), pt2.getLon()); - numPoints = (int) DrawUtil.distance(p1.getX(), p1.getY(), p2.getX(), p2.getY()) / 2; - } - - boolean isLOS = los.isLOS(new LatLonPoint.Double(pt1.getLat(), pt1.getLon()), - pt1.getHeight(), true, - new LatLonPoint.Double(pt2.getLat(), pt2.getLon()), - pt2.getHeight(), - numPoints); - - if (isLOS) { - OMLine line = new OMLine(pt1.getLat(), pt1.getLon(), pt2.getLat(), pt2.getLon(), OMGraphic.LINETYPE_GREATCIRCLE); - - line.setLinePaint(GLPoint.CONNECTED_COLOR); - list.add(line); - - ret = isLOS; - } - } else { - logger.fine("LOSGraphicLoader doesn't have a LOSGenerator"); - } - pt1.connected(ret); - pt2.connected(ret); - return ret; - } - - public void actionPerformed(java.awt.event.ActionEvent ae) { - String cmd = ae.getActionCommand(); - if (cmd == TimerCmd) { - JCheckBox check = (JCheckBox) ae.getSource(); - if (check.isSelected()) { - timer.restart(); - } else { - timer.stop(); - } - } else if (cmd == AddNodeCmd) { - if (dt != null) { - GraphicAttributes ga = new GraphicAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - OMPoint pt = (OMPoint) dt.create("com.bbn.openmap.omGraphics.OMPoint", - ga, - this, - false); - if (pt != null) { - getTimer().stop(); - pt.setRadius(5); - pt.setOval(true); - pt.setFillPaint(Color.red); - addNodeButton.setEnabled(false); - addPathButton.setEnabled(false); - } - } - } else if (cmd == AddPathCmd) { - if (dt != null) { - GraphicAttributes ga = new GraphicAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - OMPoly poly = (OMPoly) dt.create("com.bbn.openmap.omGraphics.OMPoly", - ga, - this, - true); - if (poly != null) { - getTimer().stop(); - BasicStrokeEditor bse = new BasicStrokeEditor(); - bse.setDash(new float[] { 5, 5 }); - ga.setStroke(bse.getBasicStroke()); - ga.setLinePaint(Color.yellow); - - addNodeButton.setEnabled(false); - addPathButton.setEnabled(false); - } - } - } else { - manageGraphics(); - } - - } - - public void setDrawingTool(OMDrawingTool drawingTool) { - dt = drawingTool; - if (addNodeButton != null) { - addNodeButton.setEnabled(drawingTool != null); - } - if (addPathButton != null) { - addPathButton.setEnabled(drawingTool != null); - } - } - - public OMDrawingTool getDrawingTool() { - return dt; - } - - public void setDTEDFrameCache(DTEDFrameCache cache) { - dfc = cache; - if (cache != null) { - getTimer().start(); - logger.fine("LOSGraphicLoader starting timer"); - if (los == null) { - los = new LOSGenerator(dfc); - } else { - los.setDtedCache(dfc); - } - } - } - - public DTEDFrameCache getDTEDFrameCache() { - return dfc; - } - - JCheckBox timerButton = null; - JButton addNodeButton = null; - JButton addPathButton = null; - - public Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - - if (addNodeButton == null) { - addNodeButton = new JButton("Add Node..."); - addNodeButton.addActionListener(this); - addNodeButton.setActionCommand(AddNodeCmd); - } - - addNodeButton.setEnabled(getDrawingTool() != null); - - if (addPathButton == null) { - addPathButton = new JButton("Add Path for Node..."); - addPathButton.addActionListener(this); - addPathButton.setActionCommand(AddPathCmd); - } - - addPathButton.setEnabled(getDrawingTool() != null); - - panel.add(addNodeButton); - panel.add(addPathButton); - - // Only want to do this once... - if (timerButton == null && getTimer() != null) { - timerButton = new JCheckBox("Run Timer", getTimer().isRunning()); - timerButton.addActionListener(this); - timerButton.setActionCommand(TimerCmd); - } - - panel.add(timerButton); - - return panel; - } - - public static int pointCount = 1; - - /** - * The method where a graphic, and an action to take on the - * graphic, arrives. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - if (timerButton.isSelected()) { - timer.restart(); - } - - if (omg instanceof OMPoint) { - - OMPoint p = (OMPoint) omg; - - GLPoint mp = new GLPoint(p.getLat(), p.getLon(), p.getRadius(), true); - mp.setName("Added Node " + (pointCount++)); - mp.setStationary(true); - mp.showPalette(); - points.put(mp.getName(), mp); - manageGraphics(); - } else if (omg instanceof OMPoly) { - OMPoly poly = (OMPoly) omg; - PathGLPoint pmp = new PathGLPoint(poly, 5, true); - pmp.setName("Added Node " + (pointCount++)); - pmp.showPalette(); - points.put(pmp.getName(), pmp); - manageGraphics(); - } - - addNodeButton.setEnabled(true); - addPathButton.setEnabled(true); - } - - /** - * MapHandlerChild methods modified to look for the DTEDFrameCache - * and OMDrawingTool. - */ - public void findAndInit(Object obj) { - if (obj instanceof DTEDFrameCache) { - logger.fine("LOSGraphicLoader: found DTEDFrameCache"); - setDTEDFrameCache((DTEDFrameCache) obj); - } - if (obj instanceof OMDrawingTool) { - logger.fine("LOSGraphicLoader: found OMDrawingTool"); - setDrawingTool((OMDrawingTool) obj); - } - } - - /** - * MapHandlerChild methods modified to look for the DTEDFrameCache - * and OMDrawingTool. - */ - public void findAndUndo(Object obj) { - if (obj instanceof DTEDFrameCache) { - logger.fine("removing DTEDFrameCache"); - DTEDFrameCache dfc = getDTEDFrameCache(); - if (dfc == obj) { // Check to see if they are the same - // object - setDTEDFrameCache(null); - } - } - if (obj instanceof OMDrawingTool) { - logger.fine("removing OMDrawingTool"); - OMDrawingTool odt = getDrawingTool(); - if (odt == obj) { - setDrawingTool(null); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/MMLGraphicLoader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/MMLGraphicLoader.java deleted file mode 100644 index 438c8325d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/MMLGraphicLoader.java +++ /dev/null @@ -1,174 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/MMLGraphicLoader.java,v $ -// $RCSfile: MMLGraphicLoader.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.OMGraphicHandler; - -/** - * The MMLGraphicLoader is an abstract GraphicLoader class that - * implements the MapMouseListener interface. It extends the - * AbstractGraphicLoader, so all of those features are included as - * well. These MapMouseListener methods are provided here as a - * convenience, so you don't have to write them all if you don't use - * them. - */ -public abstract class MMLGraphicLoader extends AbstractGraphicLoader implements - MapMouseListener { - - public MMLGraphicLoader() { - super(); - } - - public MMLGraphicLoader(OMGraphicHandler receiver) { - super(receiver); - } - - ///////// MapMouseListener interface methods - - /** - * Return a list of the modes that are interesting to the - * MapMouseListener. The source MouseEvents will only get sent to - * the MapMouseListener if the mode is set to one that the - * listener is interested in. Layers interested in receiving - * events should register for receiving events in "select" mode: - * - *

-     * return new String[] { SelectMouseMode.modeID };
-     * 
- * - * @return String[] of modeID's - * @see com.bbn.openmap.event.NavMouseMode#modeID - * @see com.bbn.openmap.event.SelectMouseMode#modeID - * @see com.bbn.openmap.event.NullMouseMode#modeID - */ - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - // Mouse Listener events - //////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e) { - return false; - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse has been clicked on a component. The - * listener will receive this event if it successfully processed - * mousePressed(), or if no other listener - * processes the event. If the listener successfully processes - * mouseClicked(), then it will receive the next - * mouseClicked() notifications that have a click - * count greater than one. - *

- * NOTE: We have noticed that this method can sometimes be - * erroneously invoked. It seems to occur when a light-weight AWT - * component (like an internal window or menu) closes (removes - * itself from the window hierarchy). A specific OpenMap example - * is when you make a menu selection when the MenuItem you select - * is above the MapBean canvas. After making the selection, the - * mouseClicked() gets invoked on the MouseDelegator, which passes - * it to the appropriate listeners depending on the MouseMode. The - * best way to avoid this problem is to not implement anything - * crucial in this method. Use a combination of - * mousePressed() and mouseReleased() - * instead. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) {} - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) {} - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. The listener will receive these events if it - * successfully processes mousePressed(), or if no other listener - * processes the event. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e) { - return false; - } - - /** - * Handle a mouse cursor moving without the button being pressed. - * This event is intended to tell the listener that there was a - * mouse movement, but that the event was consumed by another - * layer. This will allow a mouse listener to clean up actions - * that might have happened because of another motion event - * response. - */ - public void mouseMoved() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/PathGLPoint.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/PathGLPoint.java deleted file mode 100644 index 7453b8e2d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/PathGLPoint.java +++ /dev/null @@ -1,205 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/PathGLPoint.java,v $ -// $RCSfile: PathGLPoint.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader; - -import java.awt.Graphics; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The PathGLPoint is a GLPoint that follows a certain path, as - * opposed to just wandering around randomly. - */ -public class PathGLPoint extends GLPoint { - - double[] pathPoints = null; - OMPoly poly = null; - int pathIndex = 0; - double currentSegDist = 0; - double nextSegOffset = 0f; - double rate = Length.METER.toRadians(10000); - - public PathGLPoint(OMPoly path, int radius, boolean isOval) { - super(0f, 0f, radius, isOval); - setPoly(path); - } - - public void move(float factor) { - if (!stationary) { - moveAlong(); - } - } - - public double[] getSegmentCoordinates(int currentPathIndex) { - double[] latlons = new double[4]; - - if (pathIndex > pathPoints.length - 2 || pathIndex < 0) { - pathIndex = 0; - } - - if (pathPoints.length >= 4) { - - int la1 = pathIndex; - int lo1 = pathIndex + 1; - - int la2 = pathIndex + 2; - int lo2 = pathIndex + 3; - - if (lo2 >= pathPoints.length) { - if (poly.isPolygon()) { - Debug.message("graphicloader", - "PathGLPoint.moveAlong(): index to big, wrapping... "); - la2 = 0; - lo2 = 1; - } else { - pathIndex = 0; - Debug.message("graphicloader", - "PathGLPoint.moveAlong(): index to big, no wrapping, starting over... "); - return getSegmentCoordinates(pathIndex); - } - } - - latlons[0] = pathPoints[la1]; - latlons[1] = pathPoints[lo1]; - latlons[2] = pathPoints[la2]; - latlons[3] = pathPoints[lo2]; - } - - return latlons; - } - - public void moveAlong() { - if (Debug.debugging("graphicloader")) { - Debug.output("PathGLPoint.moveAlong(): segment " + (pathIndex / 2) - + " of " + (pathPoints.length / 2)); - } - double azimuth; - LatLonPoint newPoint; - - double[] latlons = getSegmentCoordinates(pathIndex); - - double segLength = GreatCircle.sphericalDistance(latlons[0], - latlons[1], - latlons[2], - latlons[3]); - if (Debug.debugging("graphicloader")) { - Debug.output("PathGLPoint.moveAlong(): segment Length " + segLength - + ", and already have " + currentSegDist + " of it."); - } - double needToTravel = rate; - int originalPathIndex = pathIndex; - int loopingTimes = 0; - while (needToTravel >= segLength - currentSegDist) { - - needToTravel -= (segLength - currentSegDist); - currentSegDist = 0f; - - pathIndex += 2; // Move to the next segment of the poly - - if (Debug.debugging("graphicloader")) { - Debug.output("PathGLPoint to next segment(" + (pathIndex / 2) - + "), need to travel " + needToTravel); - } - latlons = getSegmentCoordinates(pathIndex); - - if (pathIndex == originalPathIndex) { - loopingTimes++; - if (loopingTimes > 1) { - Debug.output("PathGLPoint looping on itself, setting to stationary"); - setStationary(true); - return; - } - } - - segLength = GreatCircle.sphericalDistance(latlons[0], - latlons[1], - latlons[2], - latlons[3]); - } - - if (Debug.debugging("graphicloader")) { - Debug.output("Moving PathGLPoint within current(" + (pathIndex / 2) - + ") segment, segLength: " + segLength + ", ntt: " - + needToTravel); - } - - // Staying on this segment, just calculate where the - // next point on the segment is. - azimuth = GreatCircle.sphericalAzimuth(latlons[0], - latlons[1], - latlons[2], - latlons[3]); - - newPoint = GreatCircle.sphericalBetween(latlons[0], - latlons[1], - currentSegDist + needToTravel, - azimuth); - - setLat(newPoint.getY()); - setLon(newPoint.getX()); - - currentSegDist = GreatCircle.sphericalDistance(latlons[0], - latlons[1], - (float)newPoint.getRadLat(), - (float)newPoint.getRadLon()); - } - - public boolean generate(Projection p) { - boolean ret = super.generate(p); - if (poly != null) { - poly.generate(p); - } - return ret; - } - - public void render(Graphics g) { - if (poly != null) { - poly.render(g); - } - super.render(g); - } - - public void setPoly(OMPoly p) { - poly = p; - - if (poly.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - pathPoints = poly.getLatLonArray(); - setLat(ProjMath.radToDeg(pathPoints[0])); - setLon(ProjMath.radToDeg(pathPoints[1])); - setStationary(false); - } else { - setStationary(true); - } - } - - public OMPoly getPoly() { - return poly; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceItem.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceItem.java deleted file mode 100644 index f2be24f78..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceItem.java +++ /dev/null @@ -1,58 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/ChoiceItem.java,v -// $ -// $RCSfile: ChoiceItem.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -public class ChoiceItem { - - private String label = null; - private Object value = null; - - public ChoiceItem() { - label = null; - value = null; - } - - public ChoiceItem(String label, Object value) { - this.label = label; - this.value = value; - } - - public Object value() { - return this.value; - } - - public String label() { - return this.label; - } - - public void set(String label, Object value) { - this.label = label; - this.value = value; - } - - public void set(Object value) { - this.value = value; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceList.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceList.java deleted file mode 100644 index a1e6f8307..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/ChoiceList.java +++ /dev/null @@ -1,75 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/ChoiceList.java,v -// $ -// $RCSfile: ChoiceList.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - - -package com.bbn.openmap.graphicLoader.netmap; - -import java.util.Vector; - -public class ChoiceList extends Vector { - - public ChoiceList() { - super(); - } - - public void add(String label, Object value) { - ChoiceItem it = null; - - if ((it = this.get(label)) != null) { - it.set(value); - return; - } - - it = new ChoiceItem(label, value); - super.addElement((Object)it); - } - - public String labelAt(int index) { - if (index >= this.size()) { - return null; - } - - return (((ChoiceItem)super.elementAt(index)).label()); - } - - public Object valueAt(int index) { - if (index >= this.size()) { - return null; - } - - return (((ChoiceItem)super.elementAt(index)).value()); - } - - public ChoiceItem get(String label) { - for (int i = 0; i < this.size(); i++) { - ChoiceItem item = (ChoiceItem)super.elementAt(i); - - if (item.label().equals(label)) { - return item; - } - } - - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/JIcon.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/JIcon.java deleted file mode 100644 index c07c67f4e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/JIcon.java +++ /dev/null @@ -1,40 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/JIcon.java,v $ -//$RCSfile: JIcon.java,v $ -//$Revision: 1.4 $ -//$Date: 2004/10/14 18:05:46 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Image; - -/** - * Structure definition for an image icon - */ -class JIcon { - public String name; - public Image icon; - public Image[] cicon; - - public JIcon(String name) { - this.name = name; - icon = null; - cicon = new Image[8]; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Line.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Line.java deleted file mode 100644 index 029ddc8b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Line.java +++ /dev/null @@ -1,138 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/Line.java,v $ -// $RCSfile: Line.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Color; -import java.awt.event.FocusEvent; - -import com.bbn.openmap.omGraphics.OMLine; - -/** - * Object that represents a NetMap link on the map. - */ -public class Line extends OMLine { - - protected String label = null; - protected Color color = null; - protected Node node1 = null; - protected Node node2 = null; - protected int shape = 0; - protected int index = 0; - protected double[] ll = null; - - public Line(String label, int index, int shape, int color, Node node1, - Node node2) { - super(); - - this.index = index; - this.shape = shape; - this.node1 = node1; - this.node2 = node2; - this.label = label; - this.color = NodeColor.colorOf(color); - - this.ll = new double[4]; - - setPos(node1); - setPos(node2); - - initOM(); - } - - private void initOM() { - setRenderType(RENDERTYPE_LATLON); - setLineType(LINETYPE_GREATCIRCLE); - setLinePaint(this.color); - } - - public String getName() { - return ""; - } - - public String getLabel() { - return label; - } - - public Node getNode1() { - return this.node1; - } - - public Node getNode2() { - return this.node2; - } - - public int getIndex() { - return this.index; - } - - public Color getColor() { - return this.color; - } - - public void setColor(int color) { - setStatus(color); - } - - public void setStatus(int color) { - this.color = NodeColor.colorOf(color); - setLinePaint(this.color); - } - - public int getStatus() { - return NodeColor.valueOf(this.color); - } - - public void setPos(double lat1, double lon1, double lat2, double lon2) { - ll[0] = lat1; - ll[1] = lon1; - ll[2] = lat2; - ll[3] = lon2; - - setLL(ll); - } - - public void setPos(Node atNode) { - if (this.node1 == atNode) { - ll[0] = atNode.getLat(); - ll[1] = atNode.getLon(); - } else { - ll[2] = atNode.getLat(); - ll[3] = atNode.getLon(); - } - - setLL(ll); - } - - public void setPos() { - setPos(node1); - setPos(node2); - } - - public double[] getPos() { - return ll; - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/LineCache.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/LineCache.java deleted file mode 100644 index 5b76955e1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/LineCache.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/LineCache.java,v $ -// $RCSfile: LineCache.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.util.Enumeration; -import java.util.Hashtable; - -/** - * The holder for Lines on the map. This cache is smart enough to - * add/delete/modify Lines as needed based on line labels and nodes. - */ -public class LineCache { - private Hashtable lineTable = null; - - public LineCache() { - this.lineTable = new Hashtable(); - } - - public LineCache(int initialCapacity) { - this.lineTable = new Hashtable(initialCapacity); - } - - public void flush() { - for (Enumeration list = elements(); list.hasMoreElements();) - delete((Line) list.nextElement()); - } - - public Enumeration elements() { - return lineTable.elements(); - } - - public Line add(String label, int index, int shape, int color, Node node1, - Node node2) { - del(index); - - Line line = new Line(label, index, shape, color, node1, node2); - lineTable.put(label, (Object) line); - - return line; - } - - public void move(Node atNode) { - Line[] lines = get(atNode); - if (lines == null) - return; - - for (int i = 0; i < lines.length; i++) - lines[i].setPos(atNode); - } - - public void move(Node atNode1, Node atNode2) { - move(atNode1); - move(atNode2); - } - - public Line[] get(Node atNode) { - int count = 0; - Line[] lines = null; - - Enumeration list = lineTable.elements(); - if (list == null) - return null; - - while (list.hasMoreElements()) { - Line line = (Line) list.nextElement(); - - if ((line.getNode1() == atNode) || (line.getNode2() == atNode)) { - if (lines == null) - lines = new Line[1]; - else { - Line[] newLines = new Line[lines.length + 1]; - - System.arraycopy(lines, 0, newLines, 0, lines.length); - lines = newLines; - } - - lines[count++] = line; - } - } - - return lines; - } - - public Line get(Node atNode1, Node atNode2) { - Enumeration list = lineTable.elements(); - if (list == null) - return null; - - while (list.hasMoreElements()) { - Line line = (Line) list.nextElement(); - - if (((line.getNode1() == atNode1) || (line.getNode2() == atNode1)) - && ((line.getNode1() == atNode2) || (line.getNode2() == atNode2))) { - return line; - } - } - - return null; - } - - public Line get(String label) { - return ((Line) lineTable.get(label)); - } - - public Line get(int index) { - Enumeration list = lineTable.elements(); - if (list == null) - return null; - - while (list.hasMoreElements()) { - Line line = (Line) list.nextElement(); - - if (line.getIndex() == index) - return line; - } - - return null; - } - - public void del(Node atNode) { - Line[] lines = get(atNode); - if (lines == null) - return; - - for (int i = 0; i < lines.length; i++) - delete(lines[i]); - } - - public void del(Line[] lines) { - for (int i = 0; i < lines.length; i++) - delete(lines[i]); - } - - public void del(Node atNode1, Node atNode2) { - delete(get(atNode1, atNode2)); - } - - public void del(int index) { - delete(get(index)); - } - - public void del(String label) { - delete(get(label)); - } - - private void delete(Line line) { - if (line == null) - return; - - lineTable.remove(line.getLabel()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnectionHandler.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnectionHandler.java deleted file mode 100644 index def0cafa9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnectionHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapConnectionHandler.java,v $ -// $RCSfile: NetMapConnectionHandler.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import com.bbn.openmap.layer.graphicLoader.GraphicLoaderConnector; - -/** - * The NetMapConnectionHandler is an extension to the - * GraphicLoaderConnector that looks for a NetMapConnector object in - * the MapHandler. If it finds one, it creates a NetMapGraphicLoader - * for it, connects the two, and then starts acting like a - * GraphicLoaderConnector to merge the NetMapGraphicLoader with a - * GraphicLoaderPlugIn/PlugInLayer. It uses the same properties as the - * GraphicLoaderConnector, and the properties refer to how to handle - * the PlugInLayer that will eventually get created if a - * NetMapConnector is found. - */ -public class NetMapConnectionHandler extends GraphicLoaderConnector { - - public NetMapConnectionHandler() {} - - /** - * Find GraphicLoaders and LayerHandler in the MapHandler. - */ - public void findAndInit(Object obj) { - if (obj instanceof NetMapConnector) { - checkGraphicLoader(new NetMapGraphicLoader((NetMapConnector) obj)); - } else { - super.findAndInit(obj); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnector.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnector.java deleted file mode 100644 index e2cc6a736..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConnector.java +++ /dev/null @@ -1,565 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapConnector.java,v $ -// $RCSfile: NetMapConnector.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 17:46:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Choice; -import java.awt.Color; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.util.Properties; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The NetMapConnector is the bridge between the parser from the - * output of the NetMap server (NetMapReader), and whoever wants the - * OMGraphicList that is being managed. It forwards the list on to - * the NetMapListReceiver that wants the list. The NetMapConnector - * will create it's NetMapReader to control and use. If you have a - * component that wants to receive updates from the reader, then you - * can register as an NetMapListener with the NetMapConnector. - * - * The NetMapConnector can be used in conjunction with the - * NetMapConnectionHandler. The NetMapConnectionHandler will look for - * NetMapConnectors in the BeanContext (MapHandler), and create a - * NetMapGraphicLoader for it. That will set off the GraphicLoader -%gt; - * GraphicLoaderConnector -%gt; GraphicLoaderPlugIn -%gt; PlugInLayer - * creation chain, if the GraphicLoaderConnector is also in the - * MapHandler. - * - * The following properties can be set: - * - *

- * 
- * 
- *  server=hostname of the NetMap server
- *  port=port of NetMap server
- *  defaultView=default view for NetMap server stream
- *  
- * 
- */ -public class NetMapConnector implements ActionListener, NetMapConstants, - PropertyConsumer { - - public final static String ServerConnectCmd = "Connect"; - public final static String ServerDisconnectCmd = "Disconnect"; - public final static String LoadViewCmd = "Load View"; - public final static String GetViewsCmd = "Get Network Views"; - public final static String ServerProperty = "server"; - public final static String PortProperty = "port"; - public final static String DefaultViewProperty = "defaultView"; - - public final static String STATUS_CONNECTING = " Connecting "; - public final static String STATUS_CONNECTED = " Connected "; - public final static String STATUS_IDLE = " Idle "; - - private JPanel serverPanel = null; - - private JTextField serverAddrField = null; - private JTextField serverPortField = null; - - private JLabel connectedStatus = null; - - private Choice viewChoice = null; - private ChoiceList viewList = null; - private JButton controlButton = null; - - protected String server = DEFAULT_SERVER; - protected String port = DEFAULT_PORT; - - /** - * The NetMap server has a notion of views that represent nodes - * and links, and these are names. If using a GUI, the view names - * will show up because they are received from the NetMap server. - * Programmatically, you can set what the default view should be. - */ - protected String defaultView = null; - - protected String propertyPrefix = null; - - /** - * The component that listens to the NetMap server and parses the - * stream. - */ - NetMapReader reader = null; - - /** - * Support for sending new NetMap events to listeners. - */ - NetMapListenerSupport listenerSupport = null; - - public NetMapConnector() { - listenerSupport = new NetMapListenerSupport(this); - } - - /** - * Set the hostname or IP address to use to contact the NetMap - * server. - */ - public void setServer(String sName) { - server = sName; - } - - /** - * Get the hostname or IP address of the NetMap server. - */ - public String getServer() { - return server; - } - - /** - * Set the port that the NetMap server is running on. - */ - public void setPort(String port) { - this.port = port; - } - - /** - * Get the port that the NetMap server is running on. - */ - public String getPort() { - return port; - } - - /** - * Set the defaultView to use for NetMap server queries. - */ - public void setDefaultView(String view) { - defaultView = view; - } - - /** - * Get the defaultView to use for NetMap server queries. - */ - public String getDefaultView() { - return defaultView; - } - - /** - * Add a NetMapListener to receive NetMapEvents. - */ - public void addNetMapListener(NetMapListener nml) { - listenerSupport.addNetMapListener(nml); - } - - /** - * Remove a NetMapListener from the list to receive NetMapEvents. - */ - public void removeNetMapListener(NetMapListener nml) { - listenerSupport.removeNetMapListener(nml); - } - - /** - * Clear all NetMapListeners from receiving NetMapEvents. - */ - public void clearNetMapListeners() { - listenerSupport.clearNetMapListeners(); - } - - /** - * Called by the NetMapReader so a parsed line, representing an - * event, can be dispersed to the listeners. - */ - protected void distributeEvent(Properties netmapProps) { - listenerSupport.fireNetMapEvent(netmapProps); - } - - /** Act on GUI commands controlling the NetMapReader. */ - public void actionPerformed(java.awt.event.ActionEvent ae) { - String cmd = ae.getActionCommand(); - - server = serverAddrField.getText(); - port = serverPortField.getText(); - - if (cmd == GetViewsCmd) { - connectedStatus.setText(STATUS_CONNECTING); - - viewList = getViews(); - - if (viewList == null) { - Debug.message("netmap", "Can't get view list from " + server - + ":" + port); - disconnect(); - } - - } else if (cmd == ServerDisconnectCmd) { - - Debug.message("netmap", "Disconnecting from server " + server + ":" - + port); - disconnect(); - - } else if (cmd == LoadViewCmd) { - - ChoiceItem ci = viewList.get(viewChoice.getSelectedItem()); - - if (ci == null) { - disconnect(); - return; - } - - String view = ((String) ci.value()).trim(); - - Debug.message("netmap", "Loading view " + view); - connect(view); - } - } - - /** - * Callback for the NetMapReader to let it provide the connector - * with connection status. - */ - protected void connectionUp() { - if (connectedStatus != null) { - connectedStatus.setText(STATUS_CONNECTED); - connectedStatus.setBackground(Color.green); - } - } - - /** - * Callback for the NetMapReader to let it provide the connector - * with connection status. - */ - protected void connectionDown() { - if (connectedStatus != null) { - connectedStatus.setText(STATUS_IDLE); - connectedStatus.setBackground(Color.red); - } - } - - /** - * Resets the controls to the disconnected mode. - */ - public void disconnect() { - if (reader != null) { - reader.shutdown(); - } - - reader = null; - - if (serverPanel != null) { - serverAddrField.setEnabled(true); - serverPortField.setEnabled(true); - - viewChoice.setEnabled(false); - - controlButton.setText(GetViewsCmd); - controlButton.setActionCommand(GetViewsCmd); - connectedStatus.setText(STATUS_IDLE); - } - } - - /** - * Gets a list of possible views. - * - * @return ChoiceList of possible views retrieved from the NetMap - * server. - */ - public ChoiceList getViews() { - - ChoiceList views = null; - try { - reader = new NetMapReader(server, port, this); - } catch (IOException e) { - Debug.message("netmap", "Can't start reader: " + e); - } - - Debug.message("netmap", "Checking for views..."); - - // reader will be null if server or port is bad... - if (reader != null) { - views = reader.getViewList(server, port); - } - - if (serverPanel != null) { - viewChoice.removeAll(); - - if (views != null) { - for (int i = 0; i < views.size(); i++) { - if (Debug.debugging("netmap")) { - Debug.output("Adding view: " + views.labelAt(i)); - } - viewChoice.add(views.labelAt(i)); - } - - serverAddrField.setEnabled(false); - serverPortField.setEnabled(false); - - viewChoice.setEnabled(true); - - controlButton.setText(LoadViewCmd); - controlButton.setActionCommand(LoadViewCmd); - } - } - - return views; - } - - /** - * Connects to the NetMap server to get messages about the given - * view. - */ - public void connect(String view) { - try { - - reader = new NetMapReader(server, port, this, view); - reader.start(); - - if (serverPanel != null) { - serverAddrField.setEnabled(false); - serverPortField.setEnabled(false); - - controlButton.setText(ServerDisconnectCmd); - controlButton.setActionCommand(ServerDisconnectCmd); - } - - } catch (IOException e) { - Debug.message("netmap", "Can't start reader: " + e); - disconnect(); - } - } - - /** - * Complete disconnect, sends clear command to NetMapListeners, - * resets GUI if it's being used. - */ - public void reset() { - disconnect(); - - Properties rp = new Properties(); - rp.setProperty(COMMAND_FIELD, CLEAR); - distributeEvent(rp); - - if (serverPanel != null) { - viewChoice.removeAll(); - connectedStatus.setText(STATUS_IDLE); - } - } - - /** - * Gets the GUI control for the NetMapReader, creates it if it - * doesn't exist. - */ - public Component getGUI() { - if (serverPanel != null) { - return serverPanel; - } - - serverAddrField = new JTextField(server); - serverPortField = new JTextField(port); - - /* - * Make the NETMAP Server address entry field - */ - JPanel serverAddrPanel = new JPanel(new GridLayout(0, 2)); - serverAddrPanel.add(new JLabel("Name or IP Addr: ")); - serverAddrPanel.add(serverAddrField); - /* - * Make the NETMAP Server port entry field - */ - JPanel serverPortPanel = new JPanel(new GridLayout(0, 2)); - serverPortPanel.add(new JLabel("Port: ")); - serverPortPanel.add(serverPortField); - - /* - */ - JPanel statusPanel = PaletteHelper.createHorizontalPanel("Server Connection"); - connectedStatus = new JLabel(STATUS_IDLE); - JButton resetButton = new JButton("Reset"); - resetButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - reset(); - } - }); - - statusPanel.add(connectedStatus); - statusPanel.add(resetButton); - - /* - * Make the toplevel input panel - */ - // JPanel netmapPanel = new JPanel(new GridLayout(0, 1)); - JPanel netmapPanel = PaletteHelper.createVerticalPanel("Server Settings"); - - netmapPanel.add(serverAddrPanel); - netmapPanel.add(serverPortPanel); - - /* - * Make the "Load View" panel - */ - viewChoice = new Choice(); - viewList = new ChoiceList(); - viewChoice.setEnabled(false); - - controlButton = new JButton(GetViewsCmd); - controlButton.setActionCommand(GetViewsCmd); - controlButton.addActionListener(this); - - // JPanel viewPanel = new JPanel(new GridLayout(0, 1)); - JPanel viewPanel = PaletteHelper.createVerticalPanel(null); - - viewPanel.add(new JLabel("Available Views")); - viewPanel.add(viewChoice); - viewPanel.add(controlButton); - - serverPanel = new JPanel(); - Box box = Box.createVerticalBox(); - box.add(netmapPanel); - box.add(statusPanel); - box.add(viewPanel); - serverPanel.add(box); - - return serverPanel; - } - - /** - * Method to set the properties in the PropertyConsumer. It is - * assumed that the properties do not have a prefix associated - * with them, or that the prefix has already been set. - * - * @param setList a properties object that the PropertyConsumer - * can use to retrieve expected properties it can use for - * configuration. - */ - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - /** - * Method to set the properties in the PropertyConsumer. The - * prefix is a string that should be prepended to each property - * key (in addition to a separating '.') in order for the - * PropertyConsumer to uniquely identify properties meant for it, - * in the midst of of Properties meant for several objects. - * - * @param prefix a String used by the PropertyConsumer to prepend - * to each property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix - * had already been set, then the prefix passed in should - * replace that previous value. - * @param setList a Properties object that the PropertyConsumer - * can use to retrieve expected properties it can use for - * configuration. - */ - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - server = setList.getProperty(prefix + ServerProperty); - if (server == null) { - server = DEFAULT_SERVER; - } - - port = setList.getProperty(prefix + PortProperty); - if (port == null) { - port = DEFAULT_PORT; - } - } - - /** - * Method to fill in a Properties object, reflecting the current - * values of the PropertyConsumer. If the PropertyConsumer has a - * prefix set, the property keys should have that prefix plus a - * separating '.' prepended to each property key it uses for - * configuration. - * - * @param list a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getProperties(Properties list) { - if (list == null) { - list = new Properties(); - } - String prefix = PropUtils.getScopedPropertyPrefix(this); - - list.put(prefix + ServerProperty, server); - list.put(prefix + PortProperty, port); - return list; - } - - /** - * Method to fill in a Properties object with values reflecting - * the properties able to be set on this PropertyConsumer. The key - * for each property should be the raw property name (without a - * prefix) with a value that is a String that describes what the - * property key represents, along with any other information about - * the property that would be helpful (range, default value, - * etc.). - * - * @param list a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(ServerProperty, "The hostname or IP for NetMap server"); - list.put(PortProperty, "The port number for NetMap server"); - return list; - } - - /** - * Set the property key prefix that should be used by the - * PropertyConsumer. The prefix, along with a '.', should be - * prepended to the property keys known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to - * the property keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConstants.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConstants.java deleted file mode 100644 index a7c9521ae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapConstants.java +++ /dev/null @@ -1,79 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapConstants.java,v $ -// $RCSfile: NetMapConstants.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -/** - * This interface describes the different constant settings used for - * the NetMapEvent properties. If you implement this class, you have - * direct access to the constants. - */ -public interface NetMapConstants { - - public static final String DEFAULT_SERVER = "localhost"; - public static final String DEFAULT_PORT = "5554"; - - public static final int ERROR_VALUE_INT = Integer.MIN_VALUE; - public static final float ERROR_VALUE_FLOAT = Float.MIN_VALUE; - public static final double ERROR_VALUE_DOUBLE = Double.MIN_VALUE; - - // Actions - public static final int NODE_MOVE = 0; - public static final int NODE_DELETE = -1; - public static final int LINE_DELETE = NODE_DELETE; - public static final String NODE_MOVE_STRING = "0"; - public static final String NODE_DELETE_STRING = "-1"; - public static final String LINE_DELETE_STRING = NODE_DELETE_STRING; - public static final String JMAP_VIEW_CMD = "shc cat jmap.views"; - - // Command Types - public static final String NODE_OBJECT = "nobj"; - public static final String NODE_OBJECT_STATUS = "nobjstat"; - public static final String LINK_OBJECT = "lobj"; - public static final String LINK_OBJECT_STATUS = "lobjstat"; - public static final String REFRESH = "refresh"; - public static final String UPDATE = "update"; - public static final String CLEAR = "clear"; - - // Properties Fields - public static final String COMMAND_FIELD = "cmd"; - public static final String INDEX_FIELD = "index"; - public static final String SHAPE_FIELD = "shape"; - public static final String STATUS_FIELD = "status"; - public static final String ICON_FIELD = "icon"; - public static final String LAT_FIELD = "lat"; - public static final String LON_FIELD = "lon"; - public static final String TIME_FIELD = "time"; - public static final String POSX_FIELD = "posx"; - public static final String POSY_FIELD = "posy"; - public static final String HEIGHT_FIELD = "height"; - public static final String WIDTH_FIELD = "width"; - public static final String MENU_FIELD = "menu"; - public static final String LABEL_FIELD = "label"; - public static final String JOFFSET_FIELD = "joffset"; - public static final String LINK_NODE1_FIELD = "lnode1"; - public static final String LINK_NODE2_FIELD = "lnode2"; - public static final String ELEVATION_FIELD = "elev"; - public static final String IP_FIELD = "ip"; - public static final String DATABASE_TAG_FIELD = "dt"; - public static final String NAME_FIELD = "name"; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapEvent.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapEvent.java deleted file mode 100644 index 8d805b29d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapEvent.java,v $ -// $RCSfile: NetMapEvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.util.Properties; - -/** - * Event that represents a status update from a NetMap server. The - * NetMap output is provided in lines that contain a bunch of fields. - * The line is parsed, with each token interpreted by the NetMapReader - * and put into a Properties object. The NetMapEvent can be examined - * to get fields - the field names are listed in the NetMapConstants - * interface, you can query for a field and use it if it's there. - */ -public class NetMapEvent { - - protected Properties properties; - protected Object source; - - public NetMapEvent(Object source, Properties eventProps) { - this.source = source; - this.properties = eventProps; - } - - public Properties getProperties() { - return properties; - } - - public Object getSource() { - return source; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapGraphicLoader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapGraphicLoader.java deleted file mode 100644 index cedf88454..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapGraphicLoader.java +++ /dev/null @@ -1,486 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapGraphicLoader.java,v $ -// $RCSfile: NetMapGraphicLoader.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/08/09 19:09:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Component; -import java.net.InetAddress; -import java.util.Enumeration; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.graphicLoader.MMLGraphicLoader; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The NetMapGraphicLoader is a component that can listen to a NetMapConnector, - * receive and interpret NetMapEvents, and draw the resulting network on the - * map. The NetMapConnector does all the heavy work, the NetMapGraphicLoader - * serves as an interface to get OMGraphics on the map. - *

- * - * The easiest way to use this class is to create it with the NetMapConnector - * and add it to the LayerHandler or MapHandler. If the NetMapConnector is going - * to be created by another object for application design reasons, just create a - * NetMapConnectionHandler and add it to the MapHandler, and then add the - * NetMapConnector to the MapHandler, too. The NetMapConnectionHandler will - * create a NetMapGraphicLoader for the NetMapConnector. Make sure a - * GraphicLoaderConnector is also in the MapHandler, too, because it will create - * a GraphicLoaderPlugIn/PlugInLayer for the NetMapGraphicLoader. - */ -public class NetMapGraphicLoader extends MMLGraphicLoader implements NetMapListener, - NetMapConstants { - - /** The list that gets sent to the GraphicLoaderPlugIn. */ - protected OMGraphicList omList = null; - - /** - * The component that provides controls to the NetMapReader, which in turn - * reads the server stream. - */ - private NetMapConnector connector = null; - - /** - * The cached list of nodes, created from the event properties. - */ - private NodeCache nodeList = new NodeCache(); - - /** - * The cached list of links between nodes, created from the event - * properties. - */ - private LineCache lineList = new LineCache(); - - protected boolean DEBUG = false; - - protected String localhostIP = null; - - /** - * Constructor for the NetMapGraphicLoader, you still have to set the - * NetMapConnector. - */ - public NetMapGraphicLoader() { - DEBUG = Debug.debugging("netmap"); - - this.nodeList = new NodeCache(); - this.lineList = new LineCache(); - - try { - localhostIP = InetAddress.getLocalHost().getHostAddress(); - if (DEBUG) { - Debug.output("NetMapGraphicLoader running on: " + localhostIP); - } - } catch (java.net.UnknownHostException uhe) { - localhostIP = null; - } - } - - /** - * Constructor for the NetMapGraphicLoader that sets the NetMapConnector. - * - * @param nmc the NetMapConnector to listen to. - */ - public NetMapGraphicLoader(NetMapConnector nmc) { - this(); - setNetMapConnector(nmc); - } - - /** - * Set the NetMapConnector to listen to. This method will add the - * NetMapGraphicLoader to the NetMapConnector as a NetMapListener. If there - * is already a NetMapConnector set in this NetMapGraphicLoader, then this - * method will disconnect from the current NetMapConnector, and reconnect - * with the new one if it isn't null. - */ - public void setNetMapConnector(NetMapConnector nmc) { - if (connector != null) { - connector.removeNetMapListener(this); - } - - connector = nmc; - if (connector != null) { - connector.addNetMapListener(this); - } - } - - /** - * Get the current NetMapConnector. - */ - public NetMapConnector getNetMapConnector() { - return connector; - } - - /** - * NetMapListener method, called by the NetMapConnector. - */ - public void catchEvent(NetMapEvent nme) { - // for now, print to debug, later, create OMGraphics out of - // it. - if (DEBUG) { - Debug.output(nme.getProperties().toString()); - } - processEventProperties(nme.getProperties()); - } - - private void setNodePositionFromEventProps(Node node, Properties eventProps) { - - String geo = eventProps.getProperty(LAT_FIELD); - if (geo != null) { - try { - node.setLat(Float.parseFloat(geo)); - node.posLat = geo; - } catch (Exception e) { - Debug.error("NetMapGraphicLoader: " + geo + " is not a valid latitude value."); - } - } - - geo = eventProps.getProperty(LON_FIELD); - - if (geo != null) { - try { - node.setLon(Float.parseFloat(geo)); - node.posLon = geo; - } catch (Exception e) { - Debug.error("NetMapGraphicLoader: " + geo + " is not a valid longitude value."); - } - } - } - - /** - * Process a NetMapEvent Properties object, which means that a Properties - * object, representing an event from the NetMap server, is evaluated and - * used to modify the NodeCache and LineCache accordingly. - * - * @param eventProps the properties from a NetMapEvent. - */ - protected void processEventProperties(Properties eventProps) { - int status; - Node node; - Line line; - String cmd = eventProps.getProperty(COMMAND_FIELD); - - // Used for many (if not all commands, might as well do this - // here. - int index = PropUtils.intFromProperties(eventProps, INDEX_FIELD, ERROR_VALUE_INT); - if (cmd.equals(NODE_OBJECT)) { - - int shape = PropUtils.intFromProperties(eventProps, SHAPE_FIELD, ERROR_VALUE_INT); - - if (index == ERROR_VALUE_INT) { - Debug.error("NMGL: error parsing object index for node."); - return; - } - - node = nodeList.get(index); - - if (shape == 11) { - String icon = eventProps.getProperty(ICON_FIELD); - if (DEBUG) - Debug.output("NetMapReader: jimage " + icon); - } - - if (shape == NODE_DELETE) { // Delete - - // While we're at it, we might as well delete all the - // "Line" entries that terminate on this node as - // well... - if (node != null) { - lineList.del(node); - nodeList.del(node); - } - - } else if (shape == NODE_MOVE && node != null) { // move - - setNodePositionFromEventProps(node, eventProps); - lineList.move(node); - node.setTime(Double.parseDouble(eventProps.getProperty(TIME_FIELD, "0"))); - - } else { - - // Define a new entry if "shape" is anything else, - // including NODE_MOVE without a valid node. - - /* - * int posX = LayerUtils.intFromProperties(eventProps, - * POSX_FIELD, ERROR_VALUE_INT); - * - * int posY = LayerUtils.intFromProperties(eventProps, - * POSY_FIELD, ERROR_VALUE_INT); - * - * int width = LayerUtils.intFromProperties(eventProps, - * WIDTH_FIELD, ERROR_VALUE_INT); - * - * int height = LayerUtils.intFromProperties(eventProps, - * HEIGHT_FIELD, ERROR_VALUE_INT); - */ - status = PropUtils.intFromProperties(eventProps, STATUS_FIELD, 0); - int menu = PropUtils.intFromProperties(eventProps, MENU_FIELD, 0); - /* - * int joffset = LayerUtils.intFromProperties(eventProps, - * JOFFSET_FIELD, ERROR_VALUE_INT); - */ - - String label = eventProps.getProperty(LABEL_FIELD); - if (label == null) { - // This label misdirection is temporary... - label = eventProps.getProperty(INDEX_FIELD); - } - - String ip = eventProps.getProperty(IP_FIELD); - - /* - * float elevation = LayerUtils.floatFromProperties(eventProps, - * ELEVATION_FIELD, 0f); - */ - - boolean isLocalhost = false; - if (ip != null && localhostIP != null) { - isLocalhost = localhostIP.equals(ip); - if (DEBUG) { - Debug.output("NetMapGraphicLoader displaying a node running on the localhost: " - + localhostIP); - } - } - - if (DEBUG) { - Debug.output("Creating node (" + label + ")"); - } - - try { - if (shape != ERROR_VALUE_INT) { - node = nodeList.add(label, index, shape, menu, status); - node.setLocalhost(isLocalhost); - } - } catch (Exception e) { - Debug.error("NMGL: error creating node"); - } - setNodePositionFromEventProps(node, eventProps); - } - - } else if (cmd.equals(NODE_OBJECT_STATUS)) { - - if (index == ERROR_VALUE_INT) { - Debug.error("NMGL: error parsing object index for status update."); - return; - } - - node = nodeList.get(index); - - if (node != null) { - status = PropUtils.intFromProperties(eventProps, STATUS_FIELD, ERROR_VALUE_INT); - if (status != ERROR_VALUE_INT) { - node.setStatus(status); - } - } - - } else if (cmd.equals(LINK_OBJECT_STATUS)) { - - if (index == ERROR_VALUE_INT) { - Debug.error("NMGL: error parsing line index for status update."); - return; - } - - line = lineList.get(index); - - if (line != null) { - status = PropUtils.intFromProperties(eventProps, STATUS_FIELD, ERROR_VALUE_INT); - if (status != ERROR_VALUE_INT) { - line.setStatus(status); - } - } - - } else if (cmd.equals(LINK_OBJECT)) { - - if (index == ERROR_VALUE_INT) { - Debug.error("NMGL: error parsing line index for link."); - return; - } - - line = lineList.get(index); - - int shape = PropUtils.intFromProperties(eventProps, SHAPE_FIELD, ERROR_VALUE_INT); - - if (shape == NODE_DELETE) { - lineList.del(index); - } else { - status = PropUtils.intFromProperties(eventProps, STATUS_FIELD, 0); - int node1 = PropUtils.intFromProperties(eventProps, LINK_NODE1_FIELD, ERROR_VALUE_INT); - int node2 = PropUtils.intFromProperties(eventProps, LINK_NODE2_FIELD, ERROR_VALUE_INT); - - if (node1 == ERROR_VALUE_INT || node2 == ERROR_VALUE_INT) { - Debug.error("NMGL: error parsing node indexes for link"); - return; - } - - Node n1 = nodeList.get(node1); - Node n2 = nodeList.get(node2); - - if (n1 != null && n2 != null) { - lineList.add(String.valueOf(index), index, shape, status, n1, n2); - } else { - if (DEBUG) { - Debug.output("NetMapGraphicLoader: can't create lobj, nodes are undefined"); - } - } - } - - } else if (cmd.equals(REFRESH) || cmd.equals(UPDATE)) { - // manageGraphics(); - } else if (cmd.equals(CLEAR)) { - if (nodeList != null) { - nodeList.flush(); - } - if (lineList != null) { - lineList.flush(); - } - // manageGraphics(); - } else { - if (DEBUG) { - Debug.output("NMGL: received unused event: " + eventProps.toString()); - } - } - manageGraphics(); - } - - /** - * Internal method used to create a single OMGraphicList from the NodeCache - * and the LineCache. - */ - protected OMGraphicList getOMList() { - - /* - * By creating a new list, we avoid ConcurrentModificationExceptions - * within the PlugInLayer, and within the GraphicLoaderPlugIn during - * generate(). - */ - omList = new OMGraphicList(); - - if (nodeList != null) { - Enumeration list = nodeList.elements(); - - while ((list != null) && list.hasMoreElements()) { - Node point = (Node) list.nextElement(); - point.setMatted(point.isLocalhost()); - omList.add(point); - } - } - - if (lineList != null) { - Enumeration list = lineList.elements(); - while ((list != null) && list.hasMoreElements()) { - Line line = (Line) list.nextElement(); - - if (line == null) - continue; - line.setPos(); - - omList.add((OMLine) line); - } - } - - if (DEBUG) { - int size = omList.size(); - Debug.output("NMGL.getOMList(): created list with " + size - + (size == 1 ? " graphic." : " graphics.")); - } - - return omList; - } - - /** - * Called by the GraphicLoaderPlugIn, the GUI is provided from the - * NetMapConnector. - */ - public Component getGUI() { - if (connector != null) { - return connector.getGUI(); - } else - return null; - } - - /** - * Needed to fill in a GUI with a receiver's name, to enable the user to - * send a graphic to a specific object. Should be a pretty name, suitable to - * let a user know what it is. - */ - public String getName() { - return "NetMap"; - } - - /** - * The inherited AbstractGraphicLoader method, that sends the current - * OMGrapicList to the receiver. - */ - public void manageGraphics() { - // receiver is inherited from - // com.bbn.openmap.graphicLoader.MMLGraphicLoader/AbstractGraphicLoader. - - if (receiver != null) { - if (DEBUG) { - Debug.output("NetMapConnector.update: Updating graphics."); - } - receiver.setList(getOMList()); - } else { - if (DEBUG) { - Debug.output("NetMapConnector.update: no receiver to notify."); - } - } - } - - protected boolean toolTipUp = false; - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(java.awt.event.MouseEvent e) { - if (receiver instanceof Layer && omList != null) { - OMGraphic graphic = omList.getContains(e.getX(), e.getY()); - String label = null; - if (graphic instanceof Node) { - label = ((Node) graphic).getLabel(); - // } else if (graphic instanceof Line) { - // label = ((Line)graphic).getLabel(); - } - - if (receiver instanceof Layer) { - if (graphic != null && label != null) { - ((Layer) receiver).fireRequestToolTip("Node " + label); - toolTipUp = true; - } else if (toolTipUp) { - ((Layer) receiver).fireHideToolTip(); - toolTipUp = false; - } - return true; - } - } - return false; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListener.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListener.java deleted file mode 100644 index baa4d677c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListener.java +++ /dev/null @@ -1,31 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapGraphicLoader.java,v -// $ -//$RCSfile: NetMapListener.java,v $ -//$Revision: 1.2 $ -//$Date: 2004/10/14 18:05:47 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -public interface NetMapListener { - - public void catchEvent(NetMapEvent event); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListenerSupport.java deleted file mode 100644 index ac6bb20e2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapListenerSupport.java +++ /dev/null @@ -1,150 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapListenerSupport.java,v $ -// $RCSfile: NetMapListenerSupport.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.util.Properties; -import java.util.Vector; - -import com.bbn.openmap.util.Debug; - -/** - * NetMapListenerSupport is used to manage NetMapListeners, and to - * distribute NetMapEvents to them. - */ -public class NetMapListenerSupport implements java.io.Serializable { - - transient private Vector listeners; - transient private Object source; - - /** - * Construct a NetMapListenerSupport. - */ - public NetMapListenerSupport() { - this(null); - } - - /** - * Construct a NetMapListenerSupport. - * - * @param aSource source Object - */ - public NetMapListenerSupport(Object aSource) { - source = aSource; - } - - /** - * Set the source object. - * - * @param aSource source Object - */ - public synchronized void setSource(Object aSource) { - source = aSource; - } - - /** - * Get the source object. - * - * @return Object source - */ - public synchronized Object getSource() { - return source; - } - - /** - * Add a NetMapListener. - * - * @param l NetMapListener - */ - public synchronized void addNetMapListener(NetMapListener l) { - if (listeners == null) { - listeners = new java.util.Vector(); - } - if (!listeners.contains(l)) { - listeners.addElement(l); - } - } - - /** - * Remove a NetMapListener. - * - * @param l NetMapListener - */ - public synchronized void removeNetMapListener(NetMapListener l) { - if (listeners == null) { - return; - } - listeners.removeElement(l); - } - - /** - * Return a cloned list of Listeners. - * - * @return Vector of listeners, null if none have been added. - */ - public synchronized java.util.Vector getListeners() { - if (listeners == null) { - return null; - } - - return (java.util.Vector) listeners.clone(); - } - - /** - * Remove all listeners. - */ - public void clearNetMapListeners() { - listeners.clear(); - } - - /** - * Send a center event to all registered listeners. - */ - public void fireNetMapEvent(Properties eventProperties) { - java.util.Vector targets; - NetMapListener target; - Object theSource = getSource(); - - targets = getListeners(); - - if (listeners == null) { - return; - } - - int nTargets = targets.size(); - - if (nTargets == 0) - return; - - NetMapEvent evt = new NetMapEvent(theSource, eventProperties); - - for (int i = 0; i < nTargets; i++) { - target = (NetMapListener) targets.elementAt(i); - if (Debug.debugging("mapbean")) { - Debug.output("NetMapListenerSupport.fireNetMapEvent(): " - + "target is: " + target); - } - - target.catchEvent(evt); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapReader.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapReader.java deleted file mode 100644 index 39edc0f95..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NetMapReader.java +++ /dev/null @@ -1,744 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NetMapReader.java,v $ -// $RCSfile: NetMapReader.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:46:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.InterruptedIOException; -import java.io.PrintWriter; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.net.Socket; -import java.util.Properties; -import java.util.Vector; - -import com.bbn.openmap.util.Debug; - -/** - * The NetMapReader is the class that makes actual contact with the - * NetMap server and maintains the connection to it. It is controlled - * by the NetMapConnector, and is created by it as well. The - * NetMapReader understands that the NetMap server maintains a notion - * of views, and that to get information from the server, it has to - * request information about a particular view. Luckily, a list of - * views can be requested from the server as well. - *

- * - * The NetMap server will provide a text output stream of lines, with - * each line representing an event. The NetMapReader has an implicit - * understanding of the format of different line types, and creates a - * java Properties object for each line, categorizing each field, and - * putting it in the Properties object as (Field Header key, Field - * value). This Properties object is sent to the NetMapConnector, - * where it is distributed to the NetMapEventListeners. Each - * NetMapEventListener is free to peruse the Properties object in the - * event, and get information it needs from each one by asking for - * specific field values. Some fields may not be present in all - * Properties objects, but the fields should be consistent for the - * same event type. At some point, we'll include a description of the - * events and the fields that can be expected. - * - * In general, there are two things you can do. First, you can create - * a NetMapReader without a view, and then call getViewList() on it to - * get a list of possible views. The NetMapReader will disconnect - * itself after that request. Second, you can create a NetMapReader - * with a specific view (or set the view later), and then call start() - * on it to begin receiving events about that view. Call disconnect() - * when you want it to stop. - *

- */ -public class NetMapReader extends Thread implements NetMapConstants { - - private static Object EOF = new Object(); - private static Object LP = new Object(); - private static Object RP = new Object(); - - StreamTokenizer st = null; - boolean shutdown = false; - String viewName = null; - Socket s = null; - - /** - * This is the component that is organizing the dispersal of the - * events as a result of reading stuff off the NetMap connection. - */ - NetMapConnector netmapConn; - - boolean DEBUG = false; - boolean DEBUG_VERBOSE = false; - - /** - * Create a NetMapReader to listen to a host on a port, with a - * NetMapConnector to get back in touch with. This method just - * connects, finds out the views, and closes the connection to the - * server. - */ - public NetMapReader(String host, String port, NetMapConnector connector) - throws IOException { - - this(host, port, connector, null); - } - - /** - * Create a NetMapReader to listen to a NetMapServer running on a - * port, and parse the stream relating information about the given - * view. If the view is null, then the NetMapReader will get a - * view list and disconnect. - */ - public NetMapReader(String host, String port, NetMapConnector connector, - String view) throws IOException { - - netmapConn = connector; - - if (view != null) { - setView(view); - } - - DEBUG = Debug.debugging("netmap"); - DEBUG_VERBOSE = Debug.debugging("netmap_verbose"); - - try { - s = connect(host, port); - } catch (IOException e) { - throw e; - } - } - - /** - * Set the view that will be requested when the reader is started, - * via reader.start(). - */ - public void setView(String view) { - this.viewName = view; - } - - /** - * A general connection method that returns a socket for a host - * and port. - */ - private Socket connect(String host, String portString) throws IOException { - - int port = 0; - Socket sock = null; - - boolean DEBUG = Debug.debugging("netmap"); - - try { - port = Integer.parseInt(portString, 10); - } catch (NumberFormatException e) { - if (DEBUG) - Debug.output("Illegal name " + host + ":" + portString); - throw new IOException("Illegal port: " + portString); - } - - if (DEBUG) - Debug.output("Connecting to server " + host + ":" + port); - - try { - sock = new Socket(host, port); - } catch (IOException e) { - if (sock != null) - sock.close(); - - if (DEBUG) { - Debug.output("Can't connect to " + host + ":" + port + "\n " - + e); - } - - throw e; - } - - return sock; - } - - /** - * For an established NetMapReader, get the list of views that the - * NetMapReader knows about. The NetMapReader will disconnect - * after this query. - */ - public ChoiceList getViewList(String host, String port) { - BufferedReader in = null; - PrintWriter out = null; - ChoiceList viewList = null; - Socket sock = null; - - boolean DEBUG = Debug.debugging("netmap"); - - try { - sock = connect(host, port); - - in = new BufferedReader(new InputStreamReader(sock.getInputStream())); - out = new PrintWriter(sock.getOutputStream(), true); - - // Now load the views from the server - out.println(JMAP_VIEW_CMD); - } catch (IOException e) { - Debug.error("NetMapReader: " + e); - return null; - } - - viewList = new ChoiceList(); - - try { - String line = null; - - while ((line = in.readLine()) != null) { - line = line.trim(); - - int labelStart = line.indexOf("\'"); - int labelEnd = line.lastIndexOf("\'"); - - String viewLabel = null; - String viewLine = null; - - if (DEBUG) - Debug.output("View definition: " + line); - - if (labelStart < 0) { - viewLine = line; - viewLabel = line; - - } else { - - viewLine = line.substring(0, labelStart) + " " - + line.substring(labelEnd + 1); - - viewLabel = line.substring((labelStart + 1), labelEnd); - } - - viewList.add(viewLabel.trim(), viewLine.trim()); - } - } catch (IOException e) { - Debug.error("NetMapReader: Input error: " + e); - - viewList.removeAllElements(); - viewList = null; - } - - try { - sock.close(); - netmapConn.connectionDown(); - } catch (IOException e) { - } - - return viewList; - } - - /** - * A queue command that lets the NetMapReader know to disconnect - * when it has the opportunity to. - */ - public void shutdown() { - this.shutdown = true; - } - - /** - * Called when NetMapReader.start() is called. This makes the - * NetMapReader call the NetMap server to get information about - * the view that is set. This assumes that the view has been set. - * The NetMapConnector will be called back with Properties objects - * describing events received. - */ - public void run() { - BufferedReader tdin = null; - PrintWriter tdout = null; - - if (viewName == null) { - Debug.error("NetMapReader not given a view name to request from the NETMAP server."); - return; - } - - while (!this.shutdown) { - if (DEBUG) - Debug.output("NetMapReader attempting connection"); - - try { - tdin = new BufferedReader(new InputStreamReader(s.getInputStream())); - tdout = new PrintWriter(s.getOutputStream(), true); - - if (DEBUG) - Debug.output("Loading view: " + viewName); - tdout.println("jmap '" + viewName + "' 768"); - - s.setSoTimeout(500); - } catch (InterruptedIOException eConnectInterrupted) { - continue; - } catch (IOException eConnect) { - Debug.error("NetMapReader: " + eConnect.getMessage() - + "; NetMapReader sleeping"); - - try { - Thread.sleep(40000); - } catch (Exception eSleep) { - } - - continue; - } - - if (netmapConn == null) { - continue; - } - - netmapConn.connectionUp(); - - while (!this.shutdown) { - try { - String line = null; - - if ((line = tdin.readLine()) == null) - break; - - if (DEBUG_VERBOSE) - Debug.output(" read: " + line); - Properties eventProps = procline(line); - if (DEBUG_VERBOSE) - Debug.output(" processed..."); - if (!eventProps.isEmpty()) { - netmapConn.distributeEvent(eventProps); - if (DEBUG_VERBOSE) - Debug.output(" distributed..."); - } else { - if (DEBUG_VERBOSE) - Debug.output(" ignored..."); - } - } catch (InterruptedIOException eReadInterrupted) { - continue; - } catch (Exception e) { - Debug.error("NetMapReader exception: " + e.getMessage() - + "; in NetMapReader run. "); - - // Which is better? - // break; - continue; - } - - } - - try { - s.close(); - netmapConn.connectionDown(); - } catch (Exception eShutdown) { - } - } - } - - /** - * Used to represent Double values read off the stream, converted - * from the tokenized vector. - */ - int[] nargs = new int[60]; - - /** Process a line from NetMap input stream. */ - protected Properties procline(String cmdline) { - - Vector v = tokenize(cmdline); - - // Right now, nargs[] gets set in tokenize() with values - // gleamed off Doubles in v. - - if (DEBUG_VERBOSE) - Debug.output(" parsed: " + v.toString()); - - Properties eventProps = new Properties(); - - String cmd = v.firstElement().toString(); - int shape = nargs[4]; - - if (cmd.equals(NODE_OBJECT)) { - eventProps.put(COMMAND_FIELD, NODE_OBJECT); - eventProps.put(INDEX_FIELD, Integer.toString(nargs[1])); - eventProps.put(SHAPE_FIELD, Integer.toString(nargs[4])); - - if (v.elementAt(4) instanceof String) { - String icon = (String) v.elementAt(4); - - eventProps.put(SHAPE_FIELD, "11"); - eventProps.put(ICON_FIELD, icon); - - if (DEBUG) - Debug.output("NetMapReader: jimage " + icon); - } - - if (shape == NODE_DELETE) { // Delete - - eventProps.put(SHAPE_FIELD, NODE_DELETE_STRING); - - } else { - - if (shape == NODE_MOVE) { // move - - // nobj 13 342 432 0 lat=42.3876343 - // lon=-71.1457977 elev=0.00 1038000904 - // cmd, index, posx, posy, node_move, lat, lon, - // elevation, time - - eventProps.put(SHAPE_FIELD, NODE_MOVE_STRING); - eventProps.put(TIME_FIELD, Integer.toString(nargs[8])); - - } else { - - // nobj 1 13 12 50 10 10 1 5 '11' 0 'NODE_11_' - // lat=40.0295830 lon=-74.3184204 ip=10.0.0.11 - // cmd, index, posx, posy, icon, width, height, - // status (color), menu, label, joffset, name, - // lat, lon - - // Define a new entry if "shape" is anything - // else... - eventProps.put(WIDTH_FIELD, Integer.toString(nargs[5])); - eventProps.put(HEIGHT_FIELD, Integer.toString(nargs[6])); - eventProps.put(STATUS_FIELD, Integer.toString(nargs[7])); - eventProps.put(MENU_FIELD, Integer.toString(nargs[8])); - eventProps.put(LABEL_FIELD, (String) v.elementAt(9)); - eventProps.put(NAME_FIELD, (String) v.elementAt(11)); - eventProps.put(JOFFSET_FIELD, Integer.toString(nargs[10])); - } - - eventProps.put(POSX_FIELD, Integer.toString(nargs[2])); - eventProps.put(POSY_FIELD, Integer.toString(nargs[3])); - - String elev = null; - if ((elev = getVal("elev=", cmdline)) != null) { - eventProps.put(ELEVATION_FIELD, elev); - } - - String geo = null; - - if ((geo = getVal("lat=", cmdline)) != null) { - eventProps.put(LAT_FIELD, geo); - } - - if ((geo = getVal("lon=", cmdline)) != null) { - eventProps.put(LON_FIELD, geo); - } - - if ((geo = getVal("ip=", cmdline)) != null) { - eventProps.put(IP_FIELD, geo); - } - - } - - } else if (cmd.equals(NODE_OBJECT_STATUS)) { - - eventProps.put(COMMAND_FIELD, NODE_OBJECT_STATUS); - eventProps.put(INDEX_FIELD, Integer.toString(nargs[1])); - eventProps.put(STATUS_FIELD, Integer.toString(nargs[2])); - - } else if (cmd.equals(LINK_OBJECT_STATUS)) { - - eventProps.put(COMMAND_FIELD, LINK_OBJECT_STATUS); - eventProps.put(INDEX_FIELD, Integer.toString(nargs[1])); - eventProps.put(STATUS_FIELD, Integer.toString(nargs[2])); - - } else if (cmd.equals(LINK_OBJECT)) { - - eventProps.put(COMMAND_FIELD, LINK_OBJECT); - eventProps.put(INDEX_FIELD, Integer.toString(nargs[1])); - eventProps.put(SHAPE_FIELD, Integer.toString(nargs[2])); - - if (shape != -1) { - eventProps.put(STATUS_FIELD, Integer.toString(nargs[5])); - eventProps.put(LINK_NODE1_FIELD, Integer.toString(nargs[3])); - eventProps.put(LINK_NODE2_FIELD, Integer.toString(nargs[4])); - } - } else if (cmd.equals(REFRESH)) { - eventProps.put(COMMAND_FIELD, REFRESH); - } else if (cmd.equals(UPDATE)) { - eventProps.put(COMMAND_FIELD, UPDATE); - } - - return eventProps; - } - - /** - * Given a line, break it up into a Vector representing the String - * parts, and the int[] containing the number parts. The Vector - * will contain String representations of the numbers. Should be - * called before procline() is called, and in fact is called from - * within procline(). - */ - protected Vector tokenize(String line) { - Object ob; - - Vector v = new Vector(12, 10); - - unitInit(new StringReader(line)); - - int cnt = 0; - while ((ob = unit()) != EOF) { - v.addElement(ob); - - if (ob instanceof Double) - nargs[cnt] = ((Number) ob).intValue(); - else - nargs[cnt] = 0; - - cnt++; - } - return v; - } - - /** - * Initialize the StringTokenizer. - */ - protected void unitInit(StringReader rdr) { - st = new StreamTokenizer(rdr); - - st.commentChar('%'); - st.slashSlashComments(true); - st.slashStarComments(true); - - st.wordChars('/', '/'); // disable default special handling - st.wordChars('=', '='); // disable default special handling - st.wordChars(':', ':'); // disable default special handling - } - - /** - * Break the next token into an Object, with some addition - * semantic functionality to interpret EOF and parenthesis. - */ - protected Object unit() { - Object p = next(); - if (p == EOF) - return EOF; - - if (p == LP) { - Object r; - Vector l = new Vector(2, 4); - - while (true) { - r = unit(); - - if (r == RP) - return l; - - if (r == EOF) - return EOF; - - l.addElement(r); - } - } - - return p; - } - - /** - * Break the next token into an Object. - */ - protected Object next() { - int i = 0; - char[] c; - - try { - i = st.nextToken(); - } catch (IOException e) { - Debug.error("NetMapReader: " + e.toString() + " in toktest\n"); - } - - if ((i == StreamTokenizer.TT_EOF) || (i == 0)) - return EOF; - - if (i == StreamTokenizer.TT_WORD) - return new Symbol(st.sval, 1); - - if ((i == '\'') || (i == '\"')) - return st.sval; - - if (i == StreamTokenizer.TT_NUMBER) - return new Double(st.nval); - - if ((i == '(') || (i == '[') || (i == '{')) - return LP; - - if ((i == ')') || (i == ']') || (i == '}')) - return RP; - - c = new char[1]; - c[0] = (char) i; - - return new Symbol(new String(c), 2); - } - - protected String getVal(String marker, String line) { - int sTok = 0; - int eTok = 0; - - if ((sTok = line.toLowerCase().indexOf(marker)) < 0) - return null; - - if (((eTok = line.indexOf(" ", sTok)) < 0) - && ((eTok = line.indexOf("\t", sTok)) < 0)) { - eTok = line.length(); - } - - return (line.substring(sTok + marker.length(), eTok)); - } - - // All this stuff below may be used later for more JMAP - // integration... - - // jicon jget(String name) { - // jicon x = (jicon)jicons.get(name); - - // if (x == null) { - // x = new jicon(name); - // jicons.put(name, x); - - // x.icon = can.loadImage("images/"+name); - - // if (jmap.on && jmap.dbgmode) - // System.err.println("new jicon " + name + " " + x.icon); - // } - - // return x; - // } - - /** - * Got a response from our cexec request - */ - // private void cexec(String a) { - // f.status("exec " + a); // show message in status line - // try { - // Runtime.getRuntime().exec(a); - // } catch(IOException err) { - // if (jmap.on) - // System.err.println(err.toString()); - // } - // } - /** - * Got a response from our cshow request - */ - // public void cshow(String url) { - // // show message in status line - // f.status("show " + url); - // try { - // AppletContext apcon = jmap.getAppletContext(); - - // if (url.substring(0, 2).equals("r ")) { // relative - // apcon.showDocument(new URL(jmap.getDocumentBase(), - // url.substring(2))); - // } - // else - // apcon.showDocument(new URL(url)); - // } catch (java.net.MalformedURLException err) { - // if (jmap.on) - // System.err.println(err.toString()); - // } - // } - /** - * We got a popup menu from NetMap that we had requested a bit - * ago. jmenu 2 SNMP (('show name' MCMD 'echo $NAME') ('ping' MCMD - * 'pingf $NAME')) - */ - // private void jmenu(String line) { - // PopupMenu tmenuh; - // int type = nargs[ 1 ]; - // if (jmap.on && jmap.dbgmode) - // System.err.println("Got jmenu type " + type); - // Vector l; - // Vector r = new Vector(4, 4); - - // if (f.pmenu[ type ] == null) { // if not already saved - // // create menu; store it in our global array - // l = (Vector)v.elementAt(3); - // tmenuh = new PopupMenu(v.elementAt(2).toString()); - // popupButtons(tmenuh, l, r); - // f.pmenu[ type ] = tmenuh; - // f.pmenuV[ type ] = r; - // can.add(tmenuh); - // } - // if (f.tmenutypeDesired == type) { // if still desired - // // install menu in ourjmap window - // f.tmenu = f.pmenu[ type ]; - // f.tmenutype = type; - // f.tmenutypeDesired = 0; - // f.tmenu.show(can, f.tmenux, f.tmenuy); - // } - // } - // private void jpulldowns(String line) { - // if (pulldowns) - // return; // already have pulldowns; skip this - // pulldowns = true; - // Menu tmenuh; - // int type = nargs[1 ]; - // Vector l; - // Vector r= new Vector(4, 4); - // Vector g = (Vector)v.elementAt(1); - // Enumeration e = g.elements(); - // while (e.hasMoreElements()) { - // tmenuh = new Menu(e.nextElement().toString()); - // l = (Vector)e.nextElement(); - // popupButtons(tmenuh, l, r); - // f.mb.add(tmenuh); - // } - // f.pulldownV = r; // save action data for menu operations - // } - /** - * Recursively create menu from list specification Vector r is - * result lookup list to correlate MenuItem with details - */ - // private void popupButtons(Menu menu, Vector l, Vector r) { - // Object ob, ob2; - // int i; - // Vector m; - // Menu submenu; - // MenuItem mi; - // for (i = 0; i < l.size(); i++) { - // m = (Vector)l.elementAt(i); - // ob = m.elementAt(0); - // ob2 = m.elementAt(1); - // if (ob2 instanceof Symbol) { - // mi = new MenuItem((String)ob); - // m.setElementAt(mi, 0); - // // replace first element with MenuItem - // menu.add(mi); - // // save for use by jmapFrame event handler - // r.addElement(m); - // } - // else if (ob2 instanceof Vector) { - // submenu = new Menu((String)ob); - // menu.add(submenu); - // m.removeElementAt(0); - // popupButtons(submenu, m, r); - // } - // else if (jmap.on && jmap.dbgmode) - // System.err.println("Invalid menu item " + m); - // } - // menu.addActionListener(f); - // } - // // got a response from our mcmd request - // private void mcmd(String a) { - // // f.status(a); // show message in status line - // if ((v.size() > 4) && - // (v.elementAt(1).toString().equals("host"))) { - // String b = v.elementAt(5).toString(); - // /* - // if (b.equals("Up")) - // new jmapSoundPlayer(f.jmap, "up.au"); - // else if (b.equals("not")) - // new jmapSoundPlayer(f.jmap, "noanswer.au"); - // */ - // } - // } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Node.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Node.java deleted file mode 100644 index 185ca8854..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Node.java +++ /dev/null @@ -1,159 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/Node.java,v $ -// $RCSfile: Node.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 17:46:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoint; - -/** - * Object that represents a NetMap node on the map. - */ -public class Node extends OMPoint implements ActionListener, FocusListener { - - public static final int DEFAULT_LENGTH = 10; - public static final int DEFAULT_WIDTH = 10; - public static final int DEFAULT_RADIUS = 5; - - public static Color STATUS_UP = Color.green; - public static Color STATUS_DOWN = Color.red; - public static Color STATUS_UNKNOWN = Color.yellow; - - protected String label; - protected int index; - protected Color color = null; - - protected int posX = 0; - protected int posY = 0; - protected String posLat = null; - protected String posLon = null; - protected double gpsTime = 0; - - protected int length = 0; - protected int width = 0; - - protected int menu = 0; - protected int shapeValue = 0; - - protected boolean localhost = false; - - public Node(String label, int index, int shapeval, int menu, int color) { - super(); - - this.label = label; - this.index = index; - - this.shapeValue = shapeval; - - this.menu = menu; - - this.color = NodeColor.colorOf(color); - - initOM(); - } - - private void initOM() { - setOval(true); - setRadius(DEFAULT_RADIUS); - setRenderType(RENDERTYPE_LATLON); - setFillPaint(this.color); - } - - public String getLabel() { - return this.label; - } - - public String getName() { - return getLabel(); - } - - public void setIndex(int index) { - this.index = index; - } - - public int getIndex() { - return this.index; - } - - public Color getColor() { - return this.color; - } - - public void setStatus(int color) { - this.color = NodeColor.colorOf(color); - setFillPaint(this.color); - } - - public int getStatus() { - return NodeColor.valueOf(this.color); - } - - public void setTime(double time) { - this.gpsTime = time; - } - - public double getTime() { - return this.gpsTime; - } - - public void setShape(int shapeval) { - this.shapeValue = shapeval; - } - - public void moveTo(int newX, int newY) { - if (getRenderType() == OMGraphic.RENDERTYPE_XY) { - setX(newX); - setY(newY); - } - } - - public void moveTo(float newLat, float newLon) { - if (getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - setLat(newLat); - setLon(newLon); - } - } - - /** - * Set this node as the one reflecting the localhost. - */ - public void setLocalhost(boolean value) { - localhost = value; - } - - public boolean isLocalhost() { - return localhost; - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) {} - - public void actionPerformed(ActionEvent ae) {} -} - diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeCache.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeCache.java deleted file mode 100644 index 43f53dfb1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeCache.java +++ /dev/null @@ -1,105 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NodeCache.java,v $ -// $RCSfile: NodeCache.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.util.Enumeration; -import java.util.Hashtable; - -/** - * A holder for all the nodes on the map. Cache is smart enough to - * modify or add a node based on a description. - */ -public class NodeCache { - - private Hashtable nodeTable = null; - - NodeCache() { - nodeTable = new Hashtable(); - } - - NodeCache(int initialCapacity) { - nodeTable = new Hashtable(initialCapacity); - } - - public void flush() { - for (Enumeration list = elements(); list.hasMoreElements();) - delete((Node) list.nextElement()); - } - - public Enumeration elements() { - return nodeTable.elements(); - } - - public Node add(String label, int index, int shape, int menu, int color) { - Node node = null; - - if ((node = get(label)) != null) - return node; - - node = new Node(label, index, shape, menu, color); - nodeTable.put(label, (Object) node); - - return node; - } - - public Node get(int index) { - Enumeration list = nodeTable.elements(); - - if (list == null) - return null; - while (list.hasMoreElements()) { - Node node = (Node) list.nextElement(); - - if (node.getIndex() == index) { - return (node); - } - } - - return null; - } - - public Node get(String label) { - return (Node) nodeTable.get((Object) label); - } - - public void del(String label) { - delete(get(label)); - } - - public void del(int index) { - delete(get(index)); - } - - public void del(Node node) { - delete(node); - } - - // Delete a node from the internal cache - // - private void delete(Node node) { - if (node == null) - return; - - nodeTable.remove(node.getLabel()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeColor.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeColor.java deleted file mode 100644 index 7d7b3975a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/NodeColor.java +++ /dev/null @@ -1,94 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/NodeColor.java,v $ -// $RCSfile: NodeColor.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:46:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -import java.awt.Color; - -/** - * A utility class that contains pre-determined node colors that mean - * something in the NetMap world. - */ -public class NodeColor { - - private static final Color colorPurple = new Color(160, 32, 240); - private static final Color colorRosyBrown = new Color(188, 143, 143); - - private static final Color[] nodeColors = { Color.cyan, Color.green, - Color.red, Color.blue, Color.yellow, colorRosyBrown, Color.gray, - colorPurple, }; - - public static Color colorOf(int color) { - return nodeColors[maptocolor(color)]; - } - - public static int valueOf(Color color) { - int rgb = color.getRGB(); - for (int i = 0; i < nodeColors.length; i++) { - if (nodeColors[i].getRGB() == rgb) - return (colortomap(i)); - } - - return 0; - } - - private static int colortomap(int i) { - if (i == 0) - return 0; - if (i == 1) - return 1; - if (i == 2) - return 2; - if (i == 3) - return 3; - if (i == 4) - return 4; - if (i == 5) - return 12; - if (i == 6) - return 13; - if (i == 7) - return 14; - - return 0; - } - - private static int maptocolor(int i) { - if (i == 1) - return 1; - if (i == 2) - return 2; - if (i == 3) - return 3; - if (i == 4) - return 4; - if (i == 12) - return 5; - if (i == 13) - return 6; - if (i == 14) - return 7; - - return 0; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Symbol.java b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Symbol.java deleted file mode 100644 index e082099be..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/Symbol.java +++ /dev/null @@ -1,39 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/netmap/Symbol.java,v -// $ -// $RCSfile: Symbol.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.graphicLoader.netmap; - -public class Symbol { /* Symbol for sexp */ - String str; - int type; - - Symbol(String s, int type) { - this.str = s; - this.type = type; - } - - public String toString() { - return this.str; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/package.html b/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/package.html deleted file mode 100644 index f1e814cd4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/netmap/package.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The netmap plugin package provides the capability to receive output -from a NetMap server. NetMap is a BBN product that can provide -network topology information. Using the topology output from the -NetMap server, connectivity between network components can be -visualized over the map.

- -The main component is the NetMapConnector, which manages the -connection to the NetMapServer. It uses the NetMapReader to parse -the NetMap server stream, creating NetMapEvents for each line of -output. These NetMapEvents are distributed to NetMapListeners that -have registered themselves with the NetMapConnector.

- -The NetMapGraphicLoader is a NetMapListener that uses the -NetMapEvents to create an OMGraphicList that dipicts the network -topology. The NetMapConnectionHandler is an extension of the -GraphicLoaderConnector, and is a component that looks in the -MapHandler for NetMapConnectors. If a NetMapConnector is found, the -NetMapConnectionHandler creates a NetMapGraphicLoader, -GraphicLoaderPlugIn, and eventually a PlugInLayer to use to display -the network on the map.

- -For general OpenMap use, the NetMapConnectionHandler and -NetMapConnector are the only two objects that need to be created and -added to the openmap.properties file in the openmap.components -property. The other components will be automatically created as needed. - - diff --git a/src/core/src/main/java/com/bbn/openmap/graphicLoader/package.html b/src/core/src/main/java/com/bbn/openmap/graphicLoader/package.html deleted file mode 100644 index 42e5d8d01..000000000 --- a/src/core/src/main/java/com/bbn/openmap/graphicLoader/package.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The GraphicLoader package is designed to provide support for -components that need to drive changes in OMGraphics over a map. The -GraphicLoader is an object that manages OMGraphics and their -positions, and sends an OMGraphicList to its receiver when they need -to be updated. The AbstractGraphicLoader contains a timer that can -be used to schedule updates to happen at regular updates.

- -The package consists of a GraphicLoader, the interface that describes -a component that controls OMGraphics. The GraphicLoader can have its -own timer that manages these location objects in a separate thread. -The MMLGraphicLoader is an abstract extension to the -AbstractGraphicLoader that can receive MouseEvents that occur over the -map, in order to react accordingly.

- -The LOSGraphicLoader is an example of a GraphicLoader. It manages -GLPoints and PathGLPoints, along with a DTEDFrameCache (found in the -MapHandler). The GLPoints are moved around the map, and links are -drawn between those points that have LOS between them.

- -To add a GraphicLoader to the OpenMap application, you can do it -several ways: -

    -
  • You can create a specific GraphicLoaderPlugIn that creates its - own GraphicLoader, and initializes it accordingly. You would add - the GraphicLoaderPlugIn to the openmap.layers property in the - openmap.properties file. -
  • You can create a - com.bbn.openmap.plugin.graphicLoader.GraphicLoaderPlugIn by adding - an entry to the openmap.layer property in the openmap.properties - file, and define what kind of GraphicLoader to create in the - properties for the GraphicLoaderPlugIn. -
  • You can add a - com.bbn.openmap.plugin.graphicLoader.GraphicLoaderConnector to the - openmap.components property, and then add the GraphicLoader to the - openmap.components property as well. The GraphicLoaderConnector - will find the GraphicLoader, and create a - GraphicLoaderPlugIn/PlugInLayer for the GraphicLoader and add it to - the LayerHandler on top of the map. -
- diff --git a/src/core/src/main/java/com/bbn/openmap/gui/AbstractOpenMapMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/AbstractOpenMapMenu.java deleted file mode 100644 index 6b734e649..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/AbstractOpenMapMenu.java +++ /dev/null @@ -1,414 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/AbstractOpenMapMenu.java,v $ -// $RCSfile: AbstractOpenMapMenu.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/02/13 16:58:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.JSeparator; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * Abstract Menu Object that takes care of common bean context-related - * functionality. Components on this Menu that implement the - * LightMapHandlerChild interface, that also are created via the constructor, or - * created when the properties are evaluated, will be given the MapHandler - * through the findAndInit(Object) method. These components will also receive - * findAndInit() and findAndUndo() calls when other components are added to the - * MapHandler (BeanContext). This makes the LightMapHandlerChild menu components - * invisible to MapHandler components, but able to connect to them. - *

- * - * If you have a component that needs to be added to the menu that should in the - * MapHandler, you should *NOT* make it a LightMapHandlerChild, but implement - * the same methods as the MapHandlerChild and add it to the MapHandler before - * adding it to this menu. If the component is a LightMapHandlerChild, added to - * this menu, and also added to the MapHandler, it will receive double - * membership notifications which may be confusing. - *

- * - * AbstractOpenMapMenus can be configure via properties. You can set, with - * 'menu' as a property prefix: - *

- * - *

- * 
- * 
- * 
- *   # Title used in the Menu Bar.
- *   menu.prettyName=Menu Title
- *   # The letter to use as Mnemonic
- *   menu.mnemonic=M
- *   # A marker name list of items to use in the menu. 'sep' inserts a
- *   # separator, property classname definition not needed.
- *   menu.items=first second sep third
- *   first.class=Classname of first menu item
- *   # You can add properties for Menu Item, if it is a PropertyConsumer.
- *   #first.property1=prop1
- *   second.class=classname
- *   third.class=classname
- * 
- * 
- * 
- * 
- * - * If no properties are set, the name, mnemonic and any items added in the - * constructor will be in the menu. Any items in the properties will be added to - * items created and added in the constructor - this really applies to any - * subclasses to this class. - */ -abstract public class AbstractOpenMapMenu extends JMenu implements BeanContextChild, - BeanContextMembershipListener, PropertyConsumer, MenuBarMenu, LightMapHandlerChild { - - private static final long serialVersionUID = 1L; - - /** - * All AbstractOpenMapMenus have access to an I18n object, which is provided - * by the Environment. - */ - protected I18n i18n = Environment.getI18n(); - - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Token uniquely identifying this component in the application properties. - */ - protected String propertyPrefix = null; - /** - * A hashtable to keep track of item prefixes and their components, for - * restructuring properties later. Only created if menu uses properties to - * create items. - */ - protected Map items = null; - - public final static String ItemsProperty = "items"; - public final static String SeparatorProperty = "sep"; - public final static String PrettyNameProperty = Layer.PrettyNameProperty; - public final static String MnemonicProperty = "mnemonic"; - - protected String itemsPropertyContents = null; - protected Properties itemsProperties = null; - - public AbstractOpenMapMenu() { - super(); - } - - public AbstractOpenMapMenu(String title) { - super(title); - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** Method for BeanContextChild interface. */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - beanContextChildSupport.setBeanContext(in_bc); - if (in_bc == null) { - return; - } - in_bc.addBeanContextMembershipListener(this); - - // let MenuItems find it if they want to look for - // it there, or if they want to add themselves. Not sure what - // the ConcurrentModificationException ramifications will be, - // though. - findAndInit((Object) in_bc); - findAndInit(in_bc.iterator()); - } - - /** Method for BeanContextMembership interface. */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** Method for BeanContextMembership interface. */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - findAndUndo(bcme.iterator()); - } - - /** - * Subclasses should no longer implement this method. Use the - * findAndUndo(Object) instead, so subclasses and superclasses can be given - * the opportunity to use the object, too. - */ - public void findAndUndo(Iterator it) { - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * Method called when an object is removed from the MapHandler. Called to - * let menu objects disconnect from it. - */ - public void findAndUndo(Object someObj) { - Component menuItems[] = getMenuComponents(); - - for (int i = 0; i < menuItems.length; i++) { - Component item = menuItems[i]; - if (item instanceof LightMapHandlerChild) { - ((LightMapHandlerChild) item).findAndUndo(someObj); - } - } - } - - /** - * Subclasses should no longer implement this method. Use the - * findAndInit(Object) instead, so subclasses and superclasses can be given - * the opportunity to use the object, too. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Method called when an object is added from the MapHandler. Called to let - * menu objects connect to it. - */ - public void findAndInit(Object someObj) { - Component menuItems[] = getMenuComponents(); - - for (int i = 0; i < menuItems.length; i++) { - Component item = menuItems[i]; - if (item instanceof LightMapHandlerChild) { - ((LightMapHandlerChild) item).findAndInit(someObj); - } - } - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - /** - * Return the MapHandler, if it's been set. May be null if the Menu hasn't - * been added to the MapHandler. - */ - public MapHandler getMapHandler() { - return (MapHandler) beanContextChildSupport.getBeanContext(); - } - - /** - * Sets the properties for the OMComponent. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the OMComponent. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - setPropertyPrefix(prefix); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String prettyName = props.getProperty(realPrefix + PrettyNameProperty); - if (prettyName != null) { - setText(prettyName); - } - - // We need to update this, as requested by the Javadocs, to use VK_XXX - // ints. - // String mnemonicString = props.getProperty(realPrefix + - // MnemonicProperty); - // if (mnemonicString != null) { - // setMnemonic((int) mnemonicString.charAt(0)); - // } - - itemsPropertyContents = props.getProperty(realPrefix + ItemsProperty); - List menuItems = PropUtils.parseSpacedMarkers(itemsPropertyContents); - - if (!menuItems.isEmpty()) { - - int nMenuItems = menuItems.size(); - - if (Debug.debugging("menu")) { - Debug.output("Menu " + getText() + " created with " + nMenuItems + " item" - + (nMenuItems == 1 ? "" : "s") + " in properties"); - } - - for (String itemPrefix : menuItems) { - if (itemPrefix.equals(SeparatorProperty)) { - add(new JSeparator()); - continue; - } - - String classProperty = itemPrefix + ".class"; - String className = props.getProperty(classProperty); - if (className == null) { - Debug.error("Menu " + getText() - + ".setProperties(): Failed to locate property \"" + classProperty - + "\"\n Skipping menu item \"" + itemPrefix + "\""); - continue; - } - - if (itemsProperties == null) { - itemsProperties = new Properties(); - } - - itemsProperties.put(classProperty, className); - - Object obj = ComponentFactory.create(className, itemPrefix, props); - if (obj instanceof Component) { - add((Component) obj); - } else if (obj instanceof JMenuItem) { - add((JMenuItem) obj); - } - } - } else { - if (Debug.debugging("menu")) { - Debug.output("Menu " + getText() + " created without items in properties"); - } - } - - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the OMComponent. If the component has a propertyPrefix - * set, the property keys should have that prefix plus a separating '.' - * prepended to each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - - props.put(prefix + PrettyNameProperty, getText()); - - // Mnemonics are handled differently now, needs to be updated to use - // VK_XXX - // props.put(prefix + MnemonicProperty, "" + ((char) getMnemonic())); - - if (itemsPropertyContents != null) { - props.put(prefix + ItemsProperty, itemsPropertyContents); - } - - if (itemsProperties != null) { - props.putAll(itemsProperties); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix for the menu - */ - public String getPropertyPrefix() { - return propertyPrefix; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/BasicMapPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/BasicMapPanel.java deleted file mode 100644 index bf83cfcc1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/BasicMapPanel.java +++ /dev/null @@ -1,617 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/BasicMapPanel.java,v $ -// $RCSfile: BasicMapPanel.java,v $ -// $Revision: 1.17 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.LayoutManager; -import java.awt.Toolkit; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.border.BevelBorder; -import javax.swing.border.Border; - -import com.bbn.openmap.BufferedLayerMapBean; -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MultipleSoloMapComponentException; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.gui.menu.MenuList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The BasicMapPanel is a MapPanel and OMComponentPanel that is the heart of the - * OpenMap application framework. It can be used in a application or applet. The - * Panel has a BorderLayout, and creates a MapBean for its center area. It - * creates a MapHandler to use to hold all of its OpenMap components, and uses - * the PropertyHandler given to it in its constructor to create and configure - * all of the application components. The best way to add components to the - * MapPanel is to get the MapHandler from it and add components to that. The - * BasicMapPanel also adds itself to its MapHandler, so when the PropertyHandler - * adds MapPanelChildren components to the MapHandler, the BasicMapPanel is able - * to find them via the findAndInit method. By default, the BasicMapPanel looks - * for MapPanelChildren and asks them for where they would prefer to be located - * (BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, - * BorderLayout.WEST). If you extend this component, though, other components - * could be found via that same findAndInit method. - *

- * If a property prefix is set on this MapPanel, that property prefix can be - * used to designate MapPanelChild objects for this MapPanel. The setName - * variable should be set to true, and the children's parent name should match - * whatever property prefix is given to the panel. - * - */ -public class BasicMapPanel extends MapPanel { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.MapPanel"); - - public final static String SET_NAME_PROPERTY = "setName"; - - protected MapHandler mapHandler; - protected MapBean mapBean; - protected PropertyHandler propertyHandler; - protected MenuList menuList; - protected boolean setName = false; - - /** - * Creates an empty MapPanel that creates its own empty PropertyHandler. The - * MapPanel will contain a MapBean, a MapHandler, and a PropertyHandler with - * no properties. The constructor to use to create a blank map framework to - * add components to. - */ - public BasicMapPanel() { - this(new PropertyHandler(new Properties()), false); - } - - /** - * Create a MapPanel with the option of delaying the search for properties - * until the create() call is made. - * - * @param delayCreation true to let the MapPanel know that the artful - * programmer will call create() - */ - public BasicMapPanel(boolean delayCreation) { - this(null, delayCreation); - } - - /** - * Create a MapPanel that configures itself with the properties contained in - * the PropertyHandler provided. If the PropertyHandler is null, a new one - * will be created. - */ - public BasicMapPanel(PropertyHandler propertyHandler) { - this(propertyHandler, false); - } - - /** - * Create a MapPanel that configures itself with properties contained in the - * PropertyHandler provided, and with the option of delaying the search for - * properties until the create() call is made. - * - * @param delayCreation true to let the MapPanel know that the artful - * programmer will call create() - */ - public BasicMapPanel(PropertyHandler propertyHandler, boolean delayCreation) { - MapHandler mh = getMapHandler(); - mh.add(this); - - setPropertyHandler(propertyHandler); - if (!delayCreation) { - create(); - } - } - - /** - * Sets the properties in the PropertyHandler managed by this BasicMapPanel. - * This method is intended to be called when the PropertyHandler is set on - * the panel, in order for configuration parameters to be set on this panel - * before configuration. - * - * @param prefix property prefix for scoping properties for this panel - * @param props the properties to search for properties in. - */ - public void setProperties(String prefix, Properties props) { - String scopedPrefix = PropUtils.getScopedPropertyPrefix(prefix); - setSetName(PropUtils.booleanFromProperties(props, scopedPrefix - + SET_NAME_PROPERTY, isSetName())); - if (isSetName()) { - super.setProperties(prefix, props); - } - } - - /** - * The method that triggers setLayout() and createComponents() to be called. - * If you've told the BasicMapPanel to delay creation, you should call this - * method to trigger the PropertyHandler to create components based on the - * contents of its properties. - */ - public void create() { - setLayout(createLayoutManager()); - createComponents(); - } - - /** - * The constructor calls this method that sets the LayoutManager for this - * MapPanel. It returns a BorderLayout by default, but this method can be - * overridden to change how the MapPanel places components. If you change - * what this method returns, you should also change how components are added - * in the findAndInit() method. - */ - protected LayoutManager createLayoutManager() { - return new BorderLayout(); - } - - /** - * Position the map bean in this panel according to the layout manger. - * Defaults to BorderLayout.CENTER. - */ - protected void addMapBeanToPanel(MapBean map) { - add(map, BorderLayout.CENTER); - } - - /** - * The constructor calls this method that creates the MapHandler and - * MapBean, and then tells the PropertyHandler to create the components - * described in its properties. This method calls getMapHandler() and - * getMapBean(). If the PropertyHandler is not null, it will be called to - * created components based on its properties, and those components will be - * added to the MapHandler in this MapPanel. - */ - protected void createComponents() { - // Make this call first to load the properties into - // Environment, before the MapBean gets created. - PropertyHandler ph = getPropertyHandler(); - // Make sure the MapBean is created and added to the - // MapHandler. - MapBean mb = getMapBean(); - MapHandler mh = getMapHandler(); - ph.createComponents(getMapHandler()); - - // At this point, check the MapHandler to see if a - // ProjectionFactory has been added. If it hasn't, create one - // with the default ProjectionLoaders. We might want to - // remove this at some point, but not having it here will - // catch some people by surprise when 4.6.1 comes out. - Object obj = mh.get(com.bbn.openmap.proj.ProjectionFactory.class); - if (obj == null) { - Debug.message("basic", "BasicMapPanel adding ProjectionFactory and projections to MapHandler since there are none to be found."); - mh.add(ProjectionFactory.loadDefaultProjections()); - } - - // Environment will only get loaded after the property file is - // read. - mb.setBckgrnd(Environment.getCustomBackgroundColor()); - - Projection proj = mb.getProjectionFactory().getDefaultProjectionFromEnvironment(); - - if (Debug.debugging("mappanel")) { - Debug.output("MapPanel: creating MapBean with initial projection " + proj); - } - - mb.setProjection(proj); - } - - /** - * MapPanel method. Get the MapBean used for the MapPanel. If the MapBean is - * null, calls createMapBean() which will create a BufferedLayerMapBean and - * add it to the MapHandler via a setMapBean call. If you want something - * different, override this method. - */ - public MapBean getMapBean() { - if (mapBean == null) { - setMapBean(BasicMapPanel.createMapBean()); - } - return mapBean; - } - - /** - * Set the map bean used in this map panel, replace the map bean in the - * MapHandler if there isn't already one, or if the policy allows - * replacement. The MapHandler will be created if it doesn't exist via a - * getMapHandler() method call. - * - * @throws MultipleSoloMapComponentException if there is already a map bean - * in the map handler and the policy is to reject duplicates (since - * the MapBean is a SoloMapComponent). - */ - public void setMapBean(MapBean bean) { - if (bean == null && mapBean != null) { - // remove the current MapBean from the application... - getMapHandler().remove(mapBean); - } - - mapBean = bean; - - if (mapBean != null) { - getMapHandler().add(mapBean); - addMapBeanToPanel(mapBean); - } - } - - /** - * Get the PropertyHandler containing properties used to configure the - * panel, creating it if it doesn't exist. - */ - public PropertyHandler getPropertyHandler() { - if (propertyHandler == null) { - setPropertyHandler(new PropertyHandler()); - } - return propertyHandler; - } - - /** - * Set the PropertyHandler containing the properties used to configure this - * panel. Adds the PropertyHandler to the MapHandler. If the MapHandler - * isn't set at this point, it will be created via a getMapHandler() call. - */ - public void setPropertyHandler(PropertyHandler handler) { - propertyHandler = handler; - if (handler != null) { - getMapHandler().add(handler); - - setProperties(handler.getPropertyPrefix(), handler.getProperties()); - } - } - - /** - * MapPanel method. Get the MapHandler used for the MapPanel. Creates a - * standard MapHandler if it hasn't been created yet. - */ - public MapHandler getMapHandler() { - if (mapHandler == null) { - mapHandler = new MapHandler(); - } - return mapHandler; - } - - /** - * MapPanel method. Get a JMenuBar containing menus created from properties. - */ - public JMenuBar getMapMenuBar() { - if (menuList != null) { - return menuList.getMenuBar(); - } else { - return null; - } - } - - /** - * MapPanel method. Get a JMenu containing sub-menus created from - * properties. - */ - public JMenu getMapMenu() { - if (menuList != null) { - return menuList.getMenu(); - } else { - return null; - } - } - - // Map Component Methods: - // ////////////////////// - - /** - * Adds a component to the map bean context. This makes the - * mapComponent available to the map layers and other - * components. - * - * @param mapComponent a component to be added to the map bean context - * @throws com.bbn.openmap.MultipleSoloMapComponentException if mapComponent is a - * SoloMapComponent and another instance already exists and the - * policy is a reject policy. - */ - public void addMapComponent(Object mapComponent) { - if (mapComponent != null) { - getMapHandler().add(mapComponent); - } - } - - /** - * Remove a component from the map bean context. - * - * @param mapComponent a component to be removed to the map bean context - * @return true if the mapComponent was removed. - */ - public boolean removeMapComponent(Object mapComponent) { - if (mapComponent != null) { - return getMapHandler().remove(mapComponent); - } - return true; - } - - /** - * Given a Class, find the object in the MapHandler. If the class is not a - * SoloMapComponent and there are more than one of them in the MapHandler, - * you will get the first one found. - */ - public Object getMapComponentByType(Class c) { - return getMapHandler().get(c); - } - - /** - * Get all of the mapComponents that are of the given class type. - */ - public Collection getMapComponentsByType(Class c) { - return getMapHandler().getAll(c); - } - - /** - * Find the object with the given prefix by looking it up in the prefix - * librarian in the MapHandler. - */ - public Object getMapComponent(String prefix) { - return getPropertyHandler().get(prefix); - } - - /** - * The BasicMapPanel looks for MapPanelChild components, finds out from them - * where they prefer to be placed, and adds them. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapPanelChild && someObj instanceof Component) { - - String parentName = ((MapPanelChild) someObj).getParentName(); - boolean hasNamedParent = parentName != null && parentName.trim().length() != 0; - - String myName = getPropertyPrefix(); - boolean hasName = myName != null && myName.trim().length() != 0; - - @SuppressWarnings("null") - boolean makeMyChild = (hasName && hasNamedParent && myName.equalsIgnoreCase(parentName)) - || (!hasName && !hasNamedParent); - - if (makeMyChild) { - - if (Debug.debugging("basic")) { - Debug.output("MapPanel: adding " + someObj.getClass().getName()); - } - MapPanelChild mpc = (MapPanelChild) someObj; - addMapPanelChild(mpc); - invalidate(); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("MapPanel with name: " + myName + " not adding child (" - + someObj.getClass().getName() + ") looking for: " + parentName); - } - } - } - - if (someObj instanceof MenuList) { - menuList = (MenuList) someObj; - } - } - - /** - * Add a child to the MapPanel. - */ - protected void addMapPanelChild(MapPanelChild mpc) { - add((Component) mpc, mpc.getPreferredLocation()); - } - - /** - * The MapPanel looks for MapPanelChild components and removes them from - * itself. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapPanelChild && someObj instanceof Component) { - if (Debug.debugging("basic")) { - Debug.output("MapPanel: removing " + someObj.getClass().getName()); - } - remove((Component) someObj); - invalidate(); - } - - if (someObj instanceof MenuList && menuList == someObj) { - menuList = null; - } - - if (this.equals(someObj)) { - dispose(); - } - } - - /** - * Sets the MapBean variable to null and removes all children. - */ - public void dispose() { - setMapBean(null); - setLayout(null); - removeAll(); - } - - // MapBean Methods: - // //////////////// - - /** - * A static method that creates a MapBean with it's projection set to the - * values set in the Environment. Also creates a BevelBorder.LOWERED border - * for the MapBean. - */ - public static MapBean createMapBean() { - int envWidth = Environment.getInteger(Environment.Width, MapBean.DEFAULT_WIDTH); - int envHeight = Environment.getInteger(Environment.Height, MapBean.DEFAULT_HEIGHT); - - if (envWidth <= 0 || envHeight <= 0) { - Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); - if (envWidth <= 0) { - envWidth = (int) d.getWidth(); - } - if (envHeight <= 0) { - envHeight = (int) d.getHeight(); - } - } - - return createMapBean(null, new BevelBorder(BevelBorder.LOWERED)); - } - - /** - * A static method that creates a MapBean and sets its projection and border - * to the values given. - */ - public static MapBean createMapBean(Projection proj, Border border) { - MapBean mapBeano = new BufferedLayerMapBean(); - mapBeano.setBorder(border); - - if (proj != null) { - mapBeano.setProjection(proj); - mapBeano.setPreferredSize(new Dimension(proj.getWidth(), proj.getHeight())); - } - return mapBeano; - } - - // Property Functions: - // /////////////////// - - /** - * Get the current properties. - */ - public Properties getProperties() { - return getPropertyHandler().getProperties(); - } - - /** - * Remove an existing property if it exists. - * - * @return true if a property was actually removed. - */ - public boolean removeProperty(String property) { - return getPropertyHandler().removeProperty(property); - } - - /** - * Add (or overwrite) a property to the current properties - */ - public void addProperty(String property, String value) { - getPropertyHandler().addProperty(property, value); - } - - /** - * Add in the properties from the given URL. Any existing properties will be - * overwritten except for openmap.components, openmap.layers and - * openmap.startUpLayers which will be appended. - */ - public void addProperties(URL urlToProperties) { - getPropertyHandler().addProperties(urlToProperties); - } - - /** - * Add in the properties from the given source, which can be a resource, - * file or URL. Any existing properties will be overwritten except for - * openmap.components, openmap.layers and openmap.startUpLayers which will - * be appended. - * - * @throws MalformedURLException if propFile doesn't resolve properly. - */ - public void addProperties(String propFile) throws java.net.MalformedURLException { - getPropertyHandler().addProperties(propFile); - } - - /** - * remove a marker from a space delimited set of properties. - */ - public void removeMarker(String property, String marker) { - getPropertyHandler().removeMarker(property, marker); - } - - /** - * Add in the properties from the given Properties object. Any existing - * properties will be overwritten except for openmap.components, - * openmap.layers and openmap.startUpLayers which will be appended. - */ - public void addProperties(Properties p) { - getPropertyHandler().addProperties(p); - } - - /** - * Append the given property into the current properties - */ - public void appendProperty(String property, Properties src) { - getPropertyHandler().appendProperty(property, src); - } - - /** - * Append the given property into the current properties - */ - public void appendProperty(String property, String value) { - getPropertyHandler().appendProperty(property, value); - } - - /** - * Prepend the given property into the current properties - */ - public void prependProperty(String property, Properties src) { - getPropertyHandler().prependProperty(property, src); - } - - /** - * Prepend the given property into the current properties - */ - public void prependProperty(String property, String value) { - getPropertyHandler().prependProperty(property, value); - } - - /** - * @return the setName setting, whether the property prefix will be set on - * the MapPanel when setProperties is called. - */ - public boolean isSetName() { - return setName; - } - - /** - * @param setName whether the property prefix provided in setProperties will - * be set on the MapPanel. If it is, then when MapPanelChild objects - * are found in the MapHandler, they will only be added if the names - * match. - */ - public void setSetName(boolean setName) { - this.setName = setName; - } - - /** - * Add object to MapHandler via addMapComponent(Object), then return this MapPanel. - * @param obj object to add to MapHandler - * @return this MapPanel - */ - public BasicMapPanel with(Object obj) { - addMapComponent(obj); - return this; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/CombinedCoordPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/CombinedCoordPanel.java deleted file mode 100644 index 5f7184cd9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/CombinedCoordPanel.java +++ /dev/null @@ -1,227 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/CombinedCoordPanel.java,v $ -// $RCSfile: CombinedCoordPanel.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/05/22 23:53:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.event.ActionListener; -import java.io.Serializable; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.event.CenterEvent; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * A JPanel containing a tabbed set of CoordPanels. Hitting the apply - * button not only notifies any CenterListeners of the coordinates - * stored in the active CoordPanel, it also causes the other - * CoordPanels to translate the active panel's values to their format. - * If the CombinedCoordPanel is given an ActionListener for the close - * button, a close button will be added to the panel. Otherwise, just - * the 'Apply' button will be added to the panel. - */ -public class CombinedCoordPanel extends OMComponentPanel implements - Serializable, ActionListener, CenterListener { - - protected transient JButton closebutton; - protected transient JButton applybutton; - protected transient JTabbedPane tabPane; - protected transient CoordPanel coordPanel; - protected transient DMSCoordPanel dmsPanel; - protected transient UTMCoordPanel utmPanel; - protected transient MGRSCoordPanel mgrsPanel; - - protected transient CenterSupport centerDelegate; - - public final static String CloseCmd = "Close"; - - /** - * Creates a CombinedCoordPanel with Apply button. - */ - public CombinedCoordPanel() { - this(null); - } - - /** - * Creates a CombinedCoordPanel with Apply button, and a Close - * button if the closeButtonListener is not null. - */ - public CombinedCoordPanel(ActionListener closeButtonListener) { - setup(i18n.get(CombinedCoordPanel.class, - "defaultComment", - "Set Center of Map to Coordinates:"), closeButtonListener); - } - - /** - * Creates a CombinedCoordPanel with Apply and Close buttons with - * a specified comment above the tabbed panel. - */ - public CombinedCoordPanel(String comment, ActionListener closeButtonListener) { - setup(comment, closeButtonListener); - } - - /** - * Create the panel and set up the listeners. Called from the - * constructor. - */ - protected void setup(String comment, ActionListener closeButtonListener) { - String locText; - - centerDelegate = new CenterSupport(this); - // We want to set all of the current tabs with the current - // center. - addCenterListener(this); - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - - JPanel titlePanel = new JPanel(); - titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.X_AXIS)); - JLabel clarification = new JLabel(comment); - titlePanel.add(clarification); - add(titlePanel); - - coordPanel = new CoordPanel(centerDelegate); - dmsPanel = new DMSCoordPanel(centerDelegate); - utmPanel = new UTMCoordPanel(centerDelegate); - mgrsPanel = new MGRSCoordPanel(centerDelegate); - - tabPane = new JTabbedPane(); - - locText = i18n.get(CombinedCoordPanel.class, - "tabPane.decdeg", - "Dec Deg"); - tabPane.addTab(locText, coordPanel); - locText = i18n.get(CombinedCoordPanel.class, "tabPane.dms", "DMS"); - tabPane.addTab(locText, dmsPanel); - locText = i18n.get(CombinedCoordPanel.class, "tabPane.utm", "UTM"); - tabPane.addTab(locText, utmPanel); - locText = i18n.get(CombinedCoordPanel.class, "tabPane.mgrs", "MGRS"); - tabPane.addTab(locText, mgrsPanel); - - add(tabPane); - - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); - locText = i18n.get(CombinedCoordPanel.class, "applybutton", "Apply"); - applybutton = new JButton(locText); - applybutton.addActionListener(this); - buttonPanel.add(applybutton); - - if (closeButtonListener != null) { - locText = i18n.get(CombinedCoordPanel.class, "closebutton", "Close"); - closebutton = new JButton(locText); - closebutton.setActionCommand(CloseCmd); - closebutton.addActionListener(closeButtonListener); - buttonPanel.add(closebutton); - } - - add(buttonPanel); - } - - /** - * @return the LatLonPoint represented by contents of the entry - * boxes in the CoordPanel - */ - public LatLonPoint getLatLon() { - return coordPanel.getLatLon(); - } - - /** - * Sets the contents of the latitude and longitude entry boxes in - * CoordPanel. - * - * @param llpoint the object contains the coordinates that should - * go in the boxes. - */ - public void setLatLon(LatLonPoint llpoint) { - coordPanel.setLatLon(llpoint); - dmsPanel.setLatLon(llpoint); - utmPanel.setLatLon(llpoint); - mgrsPanel.setLatLon(llpoint); - } - - /** - * Tells the active CoordPanel to set the center of the map, - * firing a center event to all listeners. - */ - public boolean setCenter() { - return ((CoordPanel) tabPane.getSelectedComponent()).setCenter(); - } - - public void actionPerformed(java.awt.event.ActionEvent e) { - if (e.getSource() == applybutton) { - boolean allOK = setCenter(); - if (!allOK) { - setLatLon(null); - } - } - } - - /** - * Add a CenterListener to the listener list. - * - * @param listener The CenterListener to be added - */ - public void addCenterListener(CenterListener listener) { - centerDelegate.add(listener); - } - - /** - * Remove a CenterListener from the listener list. - * - * @param listener The CenterListener to be removed - */ - public void removeCenterListener(CenterListener listener) { - centerDelegate.remove(listener); - } - - public void center(CenterEvent centerEvent) { - setLatLon(new LatLonPoint.Double(centerEvent.getLatitude(), centerEvent.getLongitude())); - } - - /** - * MapHandlerChild method. If the object is a MapBean, the - * CombinedCoordPanel will add it to itself as a CenterListener. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof CenterListener) { - addCenterListener((CenterListener) someObj); - } - } - - /** - * MapHandlerChild method. If the object is a MapBean, the - * CombinedCoordPanel will remove it from itself as a - * CenterListener. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof CenterListener) { - removeCenterListener((CenterListener) someObj); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ControlMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/ControlMenu.java deleted file mode 100644 index eb367824e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ControlMenu.java +++ /dev/null @@ -1,86 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ControlMenu.java,v $ -// $RCSfile: ControlMenu.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.gui.menu.BackgroundColorMenuItem; -import com.bbn.openmap.gui.menu.MouseModeMenu; -import com.bbn.openmap.gui.menu.ToolPanelToggleMenuItem; - -/** - * This Menu, by default, holds a menu option to control the mouse modes, change - * the background color of the map, and a button to toggle the ToolPanel on and - * off. - */ -public class ControlMenu extends AbstractOpenMapMenu { - - private String defaultText = "Control"; - - public ControlMenu() { - super(); - setText(defaultText); - // setMnemonic(defaultMnemonic); - - add(new MouseModeMenu()); - add(new BackgroundColorMenuItem()); - } - - public void findAndInit(Object obj) { - super.findAndInit(obj); - - if (obj instanceof ToolPanel) { - add(((ToolPanel) obj).getToggleMenu()); - } - } - - public void findAndUndo(Object obj) { - super.findAndUndo(obj); - - if (obj instanceof ToolPanel) { - ToolPanel tp = (ToolPanel) obj; - List removedItems = new ArrayList(); - int numItems = this.getItemCount(); - for (int i = 0; i < numItems; i++) { - JMenuItem jmi = this.getItem(i); - - if (jmi instanceof ToolPanelToggleMenuItem - && tp.checkToolPanelToggleMenuItem(((ToolPanelToggleMenuItem) jmi))) { - removedItems.add(((ToolPanelToggleMenuItem) jmi)); - } - } - - if (!removedItems.isEmpty()) { - for (ToolPanelToggleMenuItem jmi : removedItems) { - remove(jmi); - jmi.dispose(); - } - } - - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/CoordPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/CoordPanel.java deleted file mode 100644 index c4c6f2d56..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/CoordPanel.java +++ /dev/null @@ -1,209 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/CoordPanel.java,v $ -// $RCSfile: CoordPanel.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.Serializable; -import java.text.DecimalFormat; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * CoordPanel is a simple gui with entry boxes and labels for latitude - * and longitude. It sets the center of a map with the entered - * coordinates by firing CenterEvents. - */ -public class CoordPanel extends JPanel implements Serializable { - - protected transient JTextField latitude, longitude; - protected transient CenterSupport centerDelegate; - - protected I18n i18n = Environment.getI18n(); - - protected DecimalFormat df = new DecimalFormat("0.###"); - - /** - * Creates the panel. - */ - public CoordPanel() { - centerDelegate = new CenterSupport(this); - makeWidgets(); - } - - /** - * Creates the panel. - */ - public CoordPanel(CenterSupport support) { - centerDelegate = support; - makeWidgets(); - } - - /** - * Creates and adds the labels and entry fields for latitude and - * longitude - */ - protected void makeWidgets() { - String locText; - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - setLayout(gridbag); - locText = i18n.get(CoordPanel.class, "border", "Decimal Degrees"); - setBorder(new TitledBorder(new EtchedBorder(), locText)); - - Insets leftInsets = new Insets(0, 10, 0, 10); - Insets rightInsets = new Insets(0, 0, 0, 10); - - locText = i18n.get(CoordPanel.class, "latlabel", "Latitude: "); - JLabel latlabel = new JLabel(locText); - c.gridx = 0; - c.gridy = 0; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - c.anchor = GridBagConstraints.EAST; - gridbag.setConstraints(latlabel, c); - add(latlabel); - - latitude = new JTextField(10); - c.gridx = 1; - c.gridy = 0; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.insets = rightInsets; - gridbag.setConstraints(latitude, c); - add(latitude); - - locText = i18n.get(CoordPanel.class, "lonlabel", "Longitude: "); - JLabel lonlabel = new JLabel(locText); - c.gridx = 0; - c.gridy = 1; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - gridbag.setConstraints(lonlabel, c); - add(lonlabel); - - longitude = new JTextField(10); - c.gridx = 1; - c.gridy = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.insets = rightInsets; - gridbag.setConstraints(longitude, c); - add(longitude); - } - - /** - * @return the LatLonPoint represented by contents of the entry - * boxes - */ - public LatLonPoint getLatLon() { - double lat, lon; - try { - lat = Double.valueOf(latitude.getText()).doubleValue(); - lon = Double.valueOf(longitude.getText()).doubleValue(); - } catch (NumberFormatException except) { - Debug.error("CoordPanel.getLatLon(): " + except.toString()); - clearTextBoxes(); - return null; - } - - if (Debug.debugging("coordpanel")) { - Debug.output("CoordPanel.getLatLon(): lat= " + lat + ", lon= " - + lon); - } - - return (new LatLonPoint.Double(lat, lon)); - } - - /** - * Sets the contents of the latitude and longitude entry boxes. - * - * @param llpoint the object contains the coordinates that should - * go in the boxes. If null, text boxes will be cleared. - */ - public void setLatLon(LatLonPoint llpoint) { - if (llpoint == null) { - clearTextBoxes(); - } else { - latitude.setText("" + llpoint.getY()); - longitude.setText("" + llpoint.getX()); - } - } - - /** - * Sets the center of the map to be the coordinates in the - * latitude and longitude entry boxes - */ - public boolean setCenter() { - - LatLonPoint llp = getLatLon(); - if (llp == null) { - return false;// invalid number - } - - if (Debug.debugging("coordpanel")) { - Debug.output("CoordPanel.setCenter(): " + llp); - } - - centerDelegate.fireCenter(llp.getY(), llp.getX()); - return true; - } - - protected void clearTextBoxes() { - latitude.setText(""); - longitude.setText(""); - } - - /** - * Add a CenterListener to the listener list. - * - * @param listener The CenterListener to be added - */ - public void addCenterListener(CenterListener listener) { - centerDelegate.add(listener); - } - - /** - * Remove a CenterListener from the listener list. - * - * @param listener The CenterListener to be removed - */ - public void removeCenterListener(CenterListener listener) { - centerDelegate.remove(listener); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/DMSCoordPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/DMSCoordPanel.java deleted file mode 100644 index b9d4149f9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/DMSCoordPanel.java +++ /dev/null @@ -1,272 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/DMSCoordPanel.java,v $ -// $RCSfile: DMSCoordPanel.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.Serializable; - -import javax.swing.JLabel; -import javax.swing.JTextField; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * DMSCoordPanel is a simple gui with entry boxes and labels for - * Degree-Minute-Second representation of latitude and longitude. It - * sets the center of a map with the entered coordinates by firing - * CenterEvents. - */ -public class DMSCoordPanel extends CoordPanel implements Serializable { - - protected transient JTextField degLat, minLat, secLat, degLon, minLon, - secLon; - - /** - * Creates the panel. - */ - public DMSCoordPanel() { - super(); - } - - /** - * Creates the panel. - */ - public DMSCoordPanel(CenterSupport support) { - super(support); - } - - /** - * Creates and adds the labels and entry fields for latitude and - * longitude - */ - protected void makeWidgets() { - String locText; - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - Insets leftInsets = new Insets(0, 10, 0, 10); - Insets centerInsets = new Insets(0, 0, 0, 0); - Insets rightInsets = new Insets(0, 0, 0, 10); - - setLayout(gridbag); - locText = i18n.get(DMSCoordPanel.class, - "border", - "Degrees|Minutes|Seconds"); - setBorder(new TitledBorder(new EtchedBorder(), locText)); - - locText = i18n.get(DMSCoordPanel.class, "latlabel", "Latitude DMS: "); - JLabel latlabel = new JLabel(locText); - c.gridx = 0; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - c.anchor = GridBagConstraints.EAST; - gridbag.setConstraints(latlabel, c); - add(latlabel); - - c.gridx = GridBagConstraints.RELATIVE; - degLat = new JTextField(4); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = .33f; - c.insets = centerInsets; - gridbag.setConstraints(degLat, c); - add(degLat); - - minLat = new JTextField(4); - gridbag.setConstraints(minLat, c); - add(minLat); - - secLat = new JTextField(4); - c.insets = rightInsets; - gridbag.setConstraints(secLat, c); - add(secLat); - - locText = i18n.get(DMSCoordPanel.class, "lonlabel", "Longitude DMS: "); - JLabel lonlabel = new JLabel(locText); - c.gridx = 0; - c.gridy = 1; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - c.anchor = GridBagConstraints.EAST; - gridbag.setConstraints(lonlabel, c); - add(lonlabel); - - c.gridx = GridBagConstraints.RELATIVE; - degLon = new JTextField(4); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = .33f; - c.insets = centerInsets; - gridbag.setConstraints(degLon, c); - add(degLon); - - minLon = new JTextField(4); - gridbag.setConstraints(minLon, c); - add(minLon); - - secLon = new JTextField(4); - c.insets = rightInsets; - gridbag.setConstraints(secLon, c); - add(secLon); - } - - /** - * @return the LatLonPoint represented by contents of the entry - * boxes - */ - public LatLonPoint getLatLon() { - int deglat, minlat, deglon, minlon; - float seclat, seclon, lat, lon; - try { - // Allow blank minutes and seconds fields to represent - // zero - deglat = Float.valueOf(degLat.getText()).intValue(); - - // We just reset the text in the fields to pretty things - // up a little. Also lets the user know what we think we - // read. - - minlat = minLat.getText().length() == 0 ? 0 - : Float.valueOf(minLat.getText()).intValue(); - minLat.setText(Integer.toString(Math.abs(minlat))); - seclat = secLat.getText().length() == 0 ? 0.0f - : Float.valueOf(secLat.getText()).floatValue(); - secLat.setText(Float.toString(Math.abs(seclat))); - - deglon = Float.valueOf(degLon.getText()).intValue(); - - minlon = minLon.getText().length() == 0 ? 0 - : Float.valueOf(minLon.getText()).intValue(); - minLon.setText(Integer.toString(Math.abs(minlon))); - - seclon = secLon.getText().length() == 0 ? 0.0f - : Float.valueOf(secLon.getText()).floatValue(); - secLon.setText(Float.toString(Math.abs(seclon))); - - } catch (NumberFormatException except) { - // System.out.println(except.toString()); - clearTextBoxes(); - return null; - } - - degLat.setText(Integer.toString(deglat)); - degLon.setText(Integer.toString(deglon)); - - // I don't this gives the right behavior. The sign given to - // the minutes and seconds should be ignored, giving way to - // the sign of the degree value. - // lat = (float)(deglat + ((minlat * 60.0) + seclat)/3600); - // lon = (float)(deglon + ((minlon * 60.0) + seclon)/3600); - - // So, I'm going to keep track of the degree behavior, and the - // minutes and seconds will just build on it. So for a - // negative degree value, positive minutes make the overall - // value more negative. Negative minutes will be abs'ed. - - float direction = 1f; - if (deglat < 0f) - direction = -1f; - - lat = (float) (deglat + (Math.abs(minlat * 60.0f) + Math.abs(seclat)) - / 3600f * direction); - - direction = 1f; - if (deglon < 0f) - direction = -1f; - lon = (float) (deglon + (Math.abs(minlon * 60.0f) + Math.abs(seclon)) - / 3600f * direction); - // System.out.println("lat: " +lat + " lon: "+lon); - - return (new LatLonPoint.Double(lat, lon)); - } - - /** - * Sets the contents of the latitude and longitude entry boxes - * - * @param llpoint the object containing the coordinates that - * should go in the boxes. - */ - public void setLatLon(LatLonPoint llpoint) { - - if (llpoint == null) { - clearTextBoxes(); - return; - } - - double lat = llpoint.getY(); - double lon = llpoint.getX(); - - double direction = 1; - if (lat < 0) - direction = -1; - - lat = Math.abs(lat); - double fractLat = lat - Math.floor(lat); - - degLat.setText(Integer.toString((int) (Math.floor(lat) * direction))); - minLat.setText(Integer.toString((int) Math.floor(fractLat * 60))); - secLat.setText(df.format((float) Math.floor((fractLat * 60) % 1 * 60))); - - direction = 1; - if (lon < 0) - direction = -1; - - lon = Math.abs(lon); - double fractLon = lon - Math.floor(lon); - - degLon.setText(Integer.toString((int) (Math.floor(lon) * direction))); - minLon.setText(Integer.toString((int) Math.floor(fractLon * 60))); - secLon.setText(df.format((float) Math.floor((fractLon * 60) % 1 * 60))); - - if (Debug.debugging("coordpanel")) { - Debug.output("DMSCoordPanel.setLatLon(): setting " + llpoint - + " to " + degLat.getText() + ", " + minLat.getText() - + ", " + secLat.getText() + " and " + degLon.getText() - + ", " + minLon.getText() + ", " + secLon.getText() - + " : backcheck = " + getLatLon()); - } - - } - - protected void clearTextBoxes() { - degLat.setText(""); - minLat.setText(""); - secLat.setText(""); - degLon.setText(""); - minLon.setText(""); - secLon.setText(""); - } - - public static void main(String[] argv) { - Debug.init(); - Debug.put("coordpanel"); - DMSCoordPanel dms = new DMSCoordPanel(); - dms.setLatLon(new LatLonPoint.Double(40.8000000000f, -75.200000000000f)); - System.exit(0); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/DefaultHelpMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/DefaultHelpMenu.java deleted file mode 100644 index 44e6a9bbd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/DefaultHelpMenu.java +++ /dev/null @@ -1,83 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/DefaultHelpMenu.java,v $ -// $RCSfile: DefaultHelpMenu.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.util.Iterator; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.util.Debug; - -/** - * HelpMenu is instance of JMenu. When added to beancontext it looks - * for objects that implements HelpMenuItem interface. When objects - * implementing HelpMenuItems interface are found, it simply retrieves - * the menu items and adds them to itself. Note: It is the - * responsibility of the MenuItems themselves to respond to clicks on - * them. - */ -public class DefaultHelpMenu extends AbstractOpenMapMenu implements HelpMenu { - - private String defaultText = "Help"; - private int defaultMnemonic = 'H'; - - public DefaultHelpMenu() { - setText(defaultText); -// setMnemonic(defaultMnemonic); - } - - public DefaultHelpMenu(String in_text) { - super(); - setText(in_text); - } - - /** - * Look for objects that implement HelpMenuItems interface and add - * them to itself. - */ - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof HelpMenuItems) { - if (Debug.debugging("menu")) { - Debug.output("DefaultHelpMenu found HelpMenuItems"); - } - Iterator hmiit = ((HelpMenuItems) someObj).iterator(); - while (hmiit.hasNext()) { - add((JMenuItem) hmiit.next()); - } - } - } - - /** - * If an object implementing helpMenuItemsI is found, remove it. - */ - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof HelpMenuItems) { - Iterator hmiit = ((HelpMenuItems) someObj).iterator(); - while (hmiit.hasNext()) { - remove((JMenuItem) hmiit.next()); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/DimensionQueryPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/DimensionQueryPanel.java deleted file mode 100644 index 6c6e50b27..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/DimensionQueryPanel.java +++ /dev/null @@ -1,209 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: DimensionQueryPanel.java,v $ -//$Revision: 1.6 $ -//$Date: 2006-10-25 12:21:51 $ -//$Author: jourquin $ -// -//********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.text.MessageFormat; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -public class DimensionQueryPanel extends JPanel { - - /** - * - */ - private static final long serialVersionUID = 9129280747489252728L; - private JTextField hfield; - private JTextField vfield; - private JLabel htext; - private JLabel vtext; - private JLabel ptext1; - private JLabel ptext2; - public static final String HEIGHT_CMD = "DQP_HEIGHT_CMD"; - public static final String WIDTH_CMD = "DQP_WIDTH_CMD"; - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - public DimensionQueryPanel() { - this(0, 0); - } - - public DimensionQueryPanel(Dimension d) { - this((int)d.getWidth(), (int)d.getHeight()); - } - - public DimensionQueryPanel(int width, int height) { - - htext = new JLabel(MessageFormat.format("{0}:",i18n.get(DimensionQueryPanel.class, "Width", "Width"))); - htext.setHorizontalAlignment(SwingConstants.RIGHT); - vtext = new JLabel(MessageFormat.format("{0}:",i18n.get(DimensionQueryPanel.class, "Height", "Height"))); - vtext.setHorizontalAlignment(SwingConstants.RIGHT); - hfield = new DimensionQueryField(Integer.toString(width), 5); - hfield.setActionCommand(WIDTH_CMD); - vfield = new DimensionQueryField(Integer.toString(height), 5); - vfield.setActionCommand(HEIGHT_CMD); - ptext1 = new JLabel(MessageFormat.format(" {0}", i18n.get(DimensionQueryPanel.class, "pixels", "pixels"))); - ptext2 = new JLabel(MessageFormat.format(" {0}", i18n.get(DimensionQueryPanel.class, "pixels", "pixels"))); - layoutPanel(); - } - - public void setFieldWidth(int width) { - hfield.setText(Integer.toString(width)); - } - - public int getFieldWidth() { - return Integer.parseInt(hfield.getText()); - } - - public void setFieldHeight(int height) { - vfield.setText(Integer.toString(height)); - } - - public int getFieldHeight() { - return Integer.parseInt(vfield.getText()); - } - - public void addActionListener(ActionListener al) { - hfield.addActionListener(al); - vfield.addActionListener(al); - } - - public void removeActionListener(ActionListener al) { - hfield.removeActionListener(al); - vfield.removeActionListener(al); - } - - public void layoutPanel() { - - GridBagLayout gb = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gb); - - c.insets = new Insets(3, 3, 3, 3); - c.gridx = 0; - c.gridy = 0; - c.fill = GridBagConstraints.NONE; - c.weightx = 0; - c.anchor = GridBagConstraints.EAST; - - gb.setConstraints(htext, c); - add(htext); - - c.gridx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - c.anchor = GridBagConstraints.WEST; - - gb.setConstraints(hfield, c); - add(hfield); - - c.gridx = 2; - c.fill = GridBagConstraints.NONE; - c.weightx = 0; - gb.setConstraints(ptext1, c); - add(ptext1); - - // Next row - - c.gridx = 0; - c.gridy = 1; - c.fill = GridBagConstraints.NONE; - c.weightx = 0; - c.anchor = GridBagConstraints.EAST; - - gb.setConstraints(vtext, c); - add(vtext); - - c.gridx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - c.anchor = GridBagConstraints.WEST; - - gb.setConstraints(vfield, c); - add(vfield); - - c.gridx = 2; - c.fill = GridBagConstraints.NONE; - c.weightx = 0; - gb.setConstraints(ptext2, c); - add(ptext2); - } - - /** - * @param d - */ - public void setDimension(Dimension d) { - setFieldWidth((int)d.getWidth()); - setFieldHeight((int)d.getHeight()); - } - - /** - * @return Dimension of panel. - */ - public Dimension getDimension() { - return new Dimension(getFieldWidth(), getFieldHeight()); - } - - /** - * Customized text field that sends an action event when focus is lost (in - * addition to when the user hits "enter"). Fixes situations where listeners - * were not getting dimension updates when user failed to hit enter (a - * common occurrence). - */ - private class DimensionQueryField extends JTextField implements FocusListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - - private DimensionQueryField(String text, int columns) { - super(text, columns); - this.addFocusListener(this); - } - - public void focusGained(FocusEvent e) { - } - - public void focusLost(FocusEvent e) { - fireActionPerformed(); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/DistQuickTool.java b/src/core/src/main/java/com/bbn/openmap/gui/DistQuickTool.java deleted file mode 100644 index 19939fa77..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/DistQuickTool.java +++ /dev/null @@ -1,636 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.net.MalformedURLException; -import java.net.URL; -import java.text.DecimalFormat; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.CoordMouseMode; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.OMMouseMode; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The distance quicktool is a Tool object that uses an embedded mouse mode to - * measure distance on the map. It's intended to be used with the OMMouseMode, - * using it as a proxy, and listens to the MouseDelegator to make sure the - * OMMouseMode is the active one while the dist quicktool button is enabled. - */ -public class DistQuickTool - extends OMToolComponent - implements Tool, PropertyChangeListener { - - private static final long serialVersionUID = 1L; - protected Logger logger = Logger.getLogger("com.bbn.openmap.gui.DistQuickTool"); - - protected MouseMode mouseMode = null; - protected JButton launchButton = null; - protected boolean ommmActive = false; - - public DistQuickTool() { - mouseMode = getMouseMode(); - try { - setOpaque(false); - URL url = PropUtils.getResourceOrFileOrURL("com/bbn/openmap/tools/drawing/distance.png"); - ImageIcon ii = new ImageIcon(url); - launchButton = new JButton(ii); - launchButton.setPreferredSize(new Dimension(25, 25)); - launchButton.setToolTipText("Measure Distance"); - launchButton.setFocusable(false); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - go(); - } - }); - - add(launchButton); - } catch (MalformedURLException e) { - - e.printStackTrace(); - } - } - - protected void go() { - MouseDelegator mouseDelegator = ((MapHandler) getBeanContext()).get(MouseDelegator.class); - if (mouseDelegator != null) { - MapMouseMode proxyParent = mouseDelegator.getActiveMouseMode(); - if (proxyParent instanceof OMMouseMode) { - ommmActive = true; - mouseMode.go(proxyParent); - launchButton.setEnabled(false); - } - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - mouseMode.setProperties(prefix, props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - mouseMode.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - mouseMode.getPropertyInfo(props); - return props; - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof MouseDelegator) { - ((MouseDelegator) someObj).addPropertyChangeListener(this); - - ommmActive = ((MouseDelegator)someObj).getActiveMouseMode() instanceof OMMouseMode; - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - - if (someObj instanceof MouseDelegator) { - ((MouseDelegator) someObj).removePropertyChangeListener(this); - } - } - - public MouseMode getMouseMode() { - if (mouseMode == null) { - mouseMode = new MouseMode(); - } - return mouseMode; - } - - public class MouseMode - extends CoordMouseMode - implements ProjectionListener { - - private static final long serialVersionUID = 1L; - - public final static String UnitProperty = "units"; - public final static String ShowCircleProperty = "showCircle"; - public final static String ShowAngleProperty = "showAngle"; - - public final static transient String modeID = "Distance"; - - public transient DecimalFormat df = new DecimalFormat("0"); - // The unit type, default mile - private Length unit = Length.MILE; - // Flag to display the azimuth angle. Default true - boolean showAngle = true; - - /** - * rPoint1 is the anchor point of a line segment - */ - public Point2D rPoint1; - /** - * rPoint2 is the new (current) point of a line segment - */ - public Point2D rPoint2; - /** - * Flag, true if the mouse has already been pressed - */ - public boolean mousePressed = false; - /** - * Vector to store all distance segments, first point and last point pairs - */ - public Vector segments = new Vector(); - /** - * Distance of the current segment - */ - public double distance = 0; - /** - * The cumulative distance from the first mouse click - */ - public double totalDistance = 0; - /** - * To display the rubberband circle, default true - */ - private boolean displayCircle = true; - /** - * Special units value for displaying all units ... use only in properties - * file - */ - public final static String AllUnitsPropertyValue = "all"; - protected BufferedMapBean theMap = null; - protected String coordString = null; - - protected OMGraphicList distanceList; - - protected MapMouseMode proxyParent = null; - - public MouseMode() { - super(modeID, true); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String name = props.getProperty(prefix + UnitProperty); - if (name != null) { - Length length = Length.get(name); - if (length != null) { - setUnit(length); - } else if (name.equals(AllUnitsPropertyValue)) { - setUnit(null); - } - } - - setDisplayCircle(PropUtils.booleanFromProperties(props, prefix + ShowCircleProperty, isDisplayCircle())); - setShowAngle(PropUtils.booleanFromProperties(props, prefix + ShowAngleProperty, isShowAngle())); - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - String unitValue = (unit != null ? unit.toString() : AllUnitsPropertyValue); - props.put(prefix + UnitProperty, unitValue); - props.put(prefix + ShowCircleProperty, new Boolean(isDisplayCircle()).toString()); - props.put(prefix + ShowAngleProperty, new Boolean(isShowAngle()).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, props, DistQuickTool.class, UnitProperty, "Units", - "Units to use for measurements, from Length.name possibilities.", null); - - PropUtils.setI18NPropertyInfo(i18n, props, DistQuickTool.class, ShowCircleProperty, "Show Distance Circle", - "Flag to set whether the range circle is drawn at the end of the line (true/false).", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, props, DistQuickTool.class, ShowAngleProperty, "Show Angle", - "Flag to note the azimuth angle of the line in the information line (true/false).", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } - - /** - * Checks the MouseEvent to see if a BufferedMapBean can be found. - * - * @param evt MouseEvent, or a MapMouseEvent - * @return BufferedMapBean, or null if source is not a BufferedMapBean. - */ - protected BufferedMapBean getBufferedMapBean(MouseEvent evt) { - if (evt instanceof MapMouseEvent) { - MapBean mb = ((MapMouseEvent) evt).getMap(); - if (mb instanceof BufferedMapBean) { - return (BufferedMapBean) mb; - } - } else { - Object src = evt.getSource(); - if (src instanceof BufferedMapBean) { - return (BufferedMapBean) src; - } - } - - return null; - } - - /** - * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) - * The first click for drag, the image is generated. This image is - * redrawing when the mouse is move, but, I need to repain the - * original image. - */ - public void mouseDragged(MouseEvent arg0) { - - if (theMap == null) { - // OMMouseMode needs a BufferedMapBean - return; - } - - if (rPoint1 == null) { - rPoint1 = theMap.getCoordinates(arg0); - - } else { - // right mouse click, measure - double lat1, lat2, long1, long2; - // erase the old line and circle first - // paintRubberband(rPoint1, rPoint2, coordString); - // get the current mouse location in latlon - rPoint2 = theMap.getCoordinates(arg0); - - lat1 = rPoint1.getY(); - long1 = rPoint1.getX(); - // lat, lon of current mouse position - lat2 = rPoint2.getY(); - long2 = rPoint2.getX(); - // calculate great circle distance in nm - // distance = getGreatCircleDist(lat1, long1, - // lat2, long2, Length.NM); - distance = - GreatCircle.sphericalDistance(ProjMath.degToRad(lat1), ProjMath.degToRad(long1), ProjMath.degToRad(lat2), - ProjMath.degToRad(long2)); - - // calculate azimuth angle dec deg - double azimuth = getSphericalAzimuth(lat1, long1, lat2, long2); - coordString = createDistanceInformationLine(rPoint2, distance, azimuth); - - // paint the new line and circle up to the current - // mouse location - paintRubberband(rPoint1, rPoint2, coordString); - theMap.repaint(); - } - } - - /** - * Process a mouse pressed event. Add the mouse location to the segment - * vector. Calculate the cumulative total distance. - * - * @param e mouse event. - */ - public void mousePressed(MouseEvent e) { - e.getComponent().requestFocus(); - - mousePressed = true; - - BufferedMapBean mb = getBufferedMapBean(e); - if (mb == null) { - // OMMouseMode needs a BufferedMapBean - return; - } - - theMap = mb; - theMap.addPaintListener(this); - - if (mb != null) { - // anchor the new first point of the line - rPoint1 = theMap.getCoordinates(e); - // ensure the second point is not yet set. - rPoint2 = null; - // add the distance to the total distance - totalDistance = 0; - } - - } - - public void mouseClicked(MouseEvent e) { - } - - /** - * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) - * Make Pan event for the map. - */ - public void mouseReleased(MouseEvent arg0) { - - reset(); - } - - public void go(MapMouseMode proxyParent) { - proxyParent.actAsProxyFor(this); - this.proxyParent = proxyParent; - } - - protected void reset() { - - if (theMap != null) { - distanceList = null; - // cleanup the drawing OMGraphics - cleanUp(); - theMap.removePaintListener(this); - theMap = null; - } - - if (proxyParent != null && proxyParent.isProxyFor(mouseMode)) { - proxyParent.releaseProxy(); - proxyParent = null; - } - - launchButton.setEnabled(ommmActive); - } - - /** - * PaintListener interface, notifying the MouseMode that the MapBean has - * repainted itself. Useful if the MouseMode is drawing stuff. - */ - public void listenerPaint(Object source, Graphics g) { - if (distanceList != null) { - distanceList.render(g); - } - } - - public void projectionChanged(ProjectionEvent e) { - Projection p = e.getProjection(); - if (p != null && distanceList != null) { - distanceList.generate(p); - } - } - - /** - * Draw a rubberband line and circle between two points - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - */ - @SuppressWarnings("serial") - public void paintRubberband(Point2D pt1, Point2D pt2, String coordString) { - if (distanceList == null) { - distanceList = new OMGraphicList() { - public void render(Graphics g) { - Graphics g2 = g.create(); - g2.setXORMode(java.awt.Color.lightGray); - - for (OMGraphic omg : this) { - if (omg instanceof OMText) { - omg.render(g); - } else { - omg.render(g2); - } - } - - g2.dispose(); - } - }; - } - - distanceList.clear(); - - paintLine(pt1, pt2); - paintCircle(pt1, pt2); - paintText(pt1, pt2, coordString); - } - - /** - * Draw a rubberband line between two points - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - */ - public void paintLine(Point2D pt1, Point2D pt2) { - if (pt1 != null && pt2 != null) { - // the line connecting the segments - OMLine cLine = new OMLine(pt1.getY(), pt1.getX(), pt2.getY(), pt2.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - // get the map projection - Projection proj = theMap.getProjection(); - // prepare the line for rendering - cLine.generate(proj); - - distanceList.add(cLine); - } - } - - public void paintText(Point2D base, Point2D pt1, String coordString) { - if (coordString != null) { - - base = theMap.getProjection().forward(base); - pt1 = theMap.getProjection().forward(pt1); - - if (base.distance(pt1) > 3) { - // g.drawString(coordString, (int) pt1.getX() + 5, (int) pt1 - // .getY() - 5); - - OMText text = new OMText((int) pt1.getX() + 5, (int) pt1.getY() - 5, coordString, OMText.JUSTIFY_LEFT); - - Font font = text.getFont(); - text.setFont(font.deriveFont(Font.BOLD, font.getSize() + 4)); - - text.setLinePaint(Color.BLACK); - - text.setTextMatteColor(Color.WHITE); - text.setTextMatteStroke(new BasicStroke(5)); - text.setMattingPaint(OMColor.clear); - - text.generate(theMap.getProjection()); - distanceList.add(text); - } - - } - } - - /** - * Draw a rubberband circle between two points - * - * @param pt1 the anchor point. - * @param pt2 the current (mouse) position. - */ - public void paintCircle(Point2D pt1, Point2D pt2) { - // do all this only if want to display the rubberband circle - if (displayCircle) { - if (pt1 != null && pt2 != null) { - // first convert degrees to radians - double radphi1 = ProjMath.degToRad(pt1.getY()); - double radlambda0 = ProjMath.degToRad(pt1.getX()); - double radphi = ProjMath.degToRad(pt2.getY()); - double radlambda = ProjMath.degToRad(pt2.getX()); - // calculate the circle radius - double dRad = GreatCircle.sphericalDistance(radphi1, radlambda0, radphi, radlambda); - // convert into decimal degrees - double rad = ProjMath.radToDeg(dRad); - // make the circle - OMCircle circle = new OMCircle(pt1.getY(), pt1.getX(), rad); - // get the map projection - Projection proj = theMap.getProjection(); - // prepare the circle for rendering - circle.generate(proj); - distanceList.add(circle); - } - } // end if(displayCircle) - } - - /** - * Reset the segments and distances - */ - public void cleanUp() { - // a quick way to clean the vector - segments = new Vector(); - // reset the total distance - totalDistance = 0.0; - distance = 0.0; - coordString = null; - } - - /** - * Return the azimuth angle in decimal degrees from north. Based on - * spherical_azimuth. See class GreatCircle.java - * - * @param phi1 latitude in decimal degrees of start point - * @param lambda0 longitude in decimal degrees of start point - * @param phi latitude in decimal degrees of end point - * @param lambda longitude in decimal degrees of end point - * @return float azimuth angle in degrees - */ - public double getSphericalAzimuth(double phi1, double lambda0, double phi, double lambda) { - // convert arguments to radians - double radphi1 = ProjMath.degToRad(phi1); - double radlambda0 = ProjMath.degToRad(lambda0); - double radphi = ProjMath.degToRad(phi); - double radlambda = ProjMath.degToRad(lambda); - // get the spherical azimuth in radians between the two points - double az = GreatCircle.sphericalAzimuth(radphi1, radlambda0, radphi, radlambda); - return ProjMath.radToDeg(az); - } - - protected String createDistanceInformationLine(Point2D llp, double distance, double azimuth) { - // setup the distance info to be displayed - String unitInfo = null; - // what unit is asked for - if (unit == null) { - unitInfo = - df.format(Length.NM.fromRadians((float) distance)) + Length.NM.getAbbr() + ", " - + df.format(Length.KM.fromRadians((float) distance)) + Length.KM.getAbbr() + ", " - + df.format(Length.MILE.fromRadians((float) distance)) + Length.MILE.getAbbr() + " "; - } else { - unitInfo = df.format(unit.fromRadians(distance)) + " " + unit.getAbbr(); - } - - return unitInfo; - } - - /** - * Set the unit of distance to be displayed: Length.NM, Length.KM or - * Length.MILE. If null, displays all of them. - */ - public void setUnit(Length units) { - unit = units; - } - - public boolean isShowAngle() { - return showAngle; - } - - public void setShowAngle(boolean showAngle) { - this.showAngle = showAngle; - } - - public boolean isDisplayCircle() { - return displayCircle; - } - - public void setDisplayCircle(boolean displayCircle) { - this.displayCircle = displayCircle; - } - - /** - * Return the unit of distance being displayed: Length.NM, Length.KM or - * Length.MILE. If null, displays all of them. - */ - public Length getUnit() { - return unit; - } - } - - /* - * (non-Javadoc) - * - * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - Object obj = evt.getSource(); - if (obj instanceof MouseDelegator) { - String propName = evt.getPropertyName(); - if (propName.equals(MouseDelegator.ActiveModeProperty)) { - - Object newVal = evt.getNewValue(); - ommmActive = newVal instanceof OMMouseMode; - launchButton.setEnabled(ommmActive); - - if (mouseMode != null) { - mouseMode.reset(); - } - } else if (propName.equals(MouseDelegator.ProxyMouseModeProperty)) { - if (!this.equals(evt.getNewValue())) { - mouseMode.reset(); - } - - ommmActive = ((MouseDelegator)obj).getActiveMouseMode() instanceof OMMouseMode; - launchButton.setEnabled(evt.getNewValue() == null && ommmActive); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/DockMapPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/DockMapPanel.java deleted file mode 100644 index 12ed771e1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/DockMapPanel.java +++ /dev/null @@ -1,287 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/DockMapPanel.java,v $ -// $RCSfile: DockMapPanel.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.LayoutManager; - -import javax.swing.JComponent; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.gui.dock.BasicDockPanel; -import com.bbn.openmap.gui.dock.DockConstraint; -import com.bbn.openmap.gui.dock.DockPanel; - -/** - * The DockMapPanel is a MapPanel that uses a DockPanel for its - * layout. - *

- * Like BasicMapPanel, the Panel creates a MapBean for its center - * area. It creates a MapHandler to use to hold all of its OpenMap - * components, and uses the PropertyHandler given to it in its - * constructor to create and configure all of the application - * components. The best way to add components to the MapPanel is to - * get the MapHandler from it and add the component to that. The - * DockMapPanel also adds itself to its MapHandler - */ -public class DockMapPanel extends BasicMapPanel implements DockPanel { - - protected BasicDockPanel dockPanel; - - /** - * Create a MapPanel that creates its own PropertyHandler, which - * will then search the classpath, config directory and user home - * directory for the openmap.properties file to configure - * components for the MapPanel. - */ - public DockMapPanel() { - this(false); - } - - /** - * Create a MapPanel with the option of delaying the search for - * properties until the create() call is made. - * - * @param delayCreation true to let the MapPanel know that the - * artful programmer will call create() - */ - public DockMapPanel(boolean delayCreation) { - this(null, delayCreation); - } - - /** - * Create a MapPanel that configures itself with the properties - * contained in the PropertyHandler provided. If the - * PropertyHandler is null, a new one will be created. - */ - public DockMapPanel(PropertyHandler propertyHandler) { - this(propertyHandler, false); - } - - /** - * Create a MapPanel that configures itself with properties - * contained in the PropertyHandler provided, and with the option - * of delaying the search for properties until the - * create() call is made. - * - * @param delayCreation true to let the MapPanel know that the - * artful programmer will call create() - */ - public DockMapPanel(PropertyHandler propertyHandler, boolean delayCreation) { - super(propertyHandler, delayCreation); - } - - //From BasicMapPanel: - ///////////////////// - - protected final LayoutManager createLayoutManager() { - return new BorderLayout(); - } - - protected final void addMapBeanToPanel(MapBean map) { - setBackgroundComponent(map); - } - - protected void createComponents() { - dockPanel = new BasicDockPanel(); - super.add(dockPanel, BorderLayout.CENTER); - super.createComponents(); - } - - /** - * Add a child to the MapPanel. - */ - protected void addMapPanelChild(MapPanelChild mpc) { - //For now, just dock it somewhere... really we need to - //determine constraints for it some how (maybe by asking it - // for them? - //mps.getPreferredLocation() - //Debug.output("Adding MapPanelChild: " + mpc); - dockPanel.add((JComponent) mpc); - dockPanel.dockSomewhere((JComponent) mpc); - } - - //From DockablePanel: - ///////////////////// - - public JComponent getBackgroundComponent() { - return dockPanel.getBackgroundComponent(); - } - - public void setBackgroundComponent(JComponent back) { - dockPanel.setBackgroundComponent(back); - } - - public void setConstraint(JComponent child, DockConstraint c) { - dockPanel.setConstraint(child, c); - } - - public DockConstraint getConstraint(JComponent child) { - return dockPanel.getConstraint(child); - } - - public void removeConstraint(JComponent child) { - dockPanel.removeConstraint(child); - } - - public void setPreferredHeight(JComponent child, int i) { - dockPanel.setPreferredHeight(child, i); - } - - public void setPreferredWidth(JComponent child, int i) { - dockPanel.setPreferredWidth(child, i); - } - - public void setCanOcclude(JComponent child, boolean b) { - dockPanel.setCanOcclude(child, b); - } - - public void setCanTransparent(JComponent child, boolean b) { - dockPanel.setCanTransparent(child, b); - } - - public void setCanResize(JComponent child, boolean b) { - dockPanel.setCanResize(child, b); - } - - public void setCanTab(JComponent child, boolean b) { - dockPanel.setCanTab(child, b); - } - - public void setTabName(JComponent child, String tabName) { - dockPanel.setTabName(child, tabName); - } - - public void setCanExternalFrame(JComponent child, boolean b) { - dockPanel.setCanExternalFrame(child, b); - } - - public void setCanInternalFrame(JComponent child, boolean b) { - dockPanel.setCanInternalFrame(child, b); - } - - public void setCanClose(JComponent child, boolean b) { - dockPanel.setCanClose(child, b); - } - - public void setCanDockNorth(JComponent child, boolean b) { - dockPanel.setCanDockNorth(child, b); - } - - public void setCanDockSouth(JComponent child, boolean b) { - dockPanel.setCanDockSouth(child, b); - } - - public void setCanDockEast(JComponent child, boolean b) { - dockPanel.setCanDockEast(child, b); - } - - public void setCanDockWest(JComponent child, boolean b) { - dockPanel.setCanDockWest(child, b); - } - - public void dockNorth(JComponent child) { - dockPanel.dockNorth(child); - } - - public void dockNorth(JComponent child, int idx) { - dockPanel.dockNorth(child, idx); - } - - public void dockSouth(JComponent child) { - dockPanel.dockSouth(child); - } - - public void dockSouth(JComponent child, int idx) { - dockPanel.dockSouth(child, idx); - } - - public void dockEast(JComponent child) { - dockPanel.dockEast(child); - } - - public void dockEast(JComponent child, int idx) { - dockPanel.dockEast(child, idx); - } - - public void dockWest(JComponent child) { - dockPanel.dockWest(child); - } - - public void dockWest(JComponent child, int idx) { - dockPanel.dockWest(child, idx); - } - - public void dockSomewhere(JComponent child) { - dockPanel.dockSomewhere(child); - } - - public void dock(JComponent outter, JComponent inner) { - dockPanel.dock(outter, inner); - } - - public void dock(JComponent outter, JComponent inner, int idx) { - dockPanel.dock(outter, inner, idx); - } - - public void internalFrame(JComponent child) { - dockPanel.internalFrame(child); - } - - public void externalFrame(JComponent child) { - dockPanel.externalFrame(child); - } - - //Overwrite from Component: - /////////////////////////// - - /** - * We need to handle adding the component specially. - */ - public Component add(Component comp) { - return dockPanel.add(comp); - } - - /** - * We need to handle adding the component specially. - */ - public void add(Component comp, Object constraints) { - dockPanel.add(comp, constraints); - } - - /** - * We need to handle removing the component specially. - */ - public void remove(Component comp) { - dockPanel.remove(comp); - } - - /** - * We need to handle removing all components specially. - */ - public void removeAll() { - dockPanel.removeAll(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedNavPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedNavPanel.java deleted file mode 100644 index 512375019..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedNavPanel.java +++ /dev/null @@ -1,803 +0,0 @@ -/* ***************************************************************************** - * - * - * ========================================================================= - * LEGEND - * - * Use, duplication, or disclosure by the Government is as set forth in the - * Rights in technical data noncommercial items clause DFAR 252.227-7013 and - * Rights in noncommercial computer software and noncommercial computer - * software documentation clause DFAR 252.227-7014, with the exception of - * third party software known as Sun Microsystems' Java Runtime Environment - * (JRE), Quest Software's JClass, Oracle's JDBC, and JGoodies which are - * separately governed under their commercial licenses. Refer to the - * license directory for information regarding the open source packages used - * by this software. - * - * Copyright 2009 by BBN Technologies Corporation. - * ========================================================================= - * - * - * $Id: NavigationPanel.java 29356 2009-04-21 02:35:27Z rmacinty $ - * - * ****************************************************************************/ - -package com.bbn.openmap.gui; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.SwingConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.plaf.basic.BasicSliderUI; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.SoloMapComponent; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.event.PanListener; -import com.bbn.openmap.event.PanSupport; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.event.ZoomSupport; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionStack; -import com.bbn.openmap.proj.ProjectionStackTrigger; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.IconPartList; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.tools.icon.OpenMapAppPartCollection; -import com.bbn.openmap.util.PropUtils; - -/** - * A panel with map navigation widgets. - *

- * Portions of the implementation were ripped from - * com.bbn.openmap.gui.NavigatePanel, com.bbn.openmap.gui.ProjectionStackTool, - * and com.bbn.openmap.gui.ZoomPanel. - *

- */ -public class EmbeddedNavPanel extends OMComponentPanel implements - ProjectionListener, ProjectionStackTrigger, SoloMapComponent { - public static Logger logger = Logger - .getLogger("com.bbn.openmap.gui.EmbeddedNavPanel"); - - private static final long serialVersionUID = 1L; - - public static final int SLIDER_MAX = 17; - public final static String FADE_ATTRIBUTES_PROPERTY = "fade"; - public final static String LIVE_ATTRIBUTES_PROPERTY = "live"; - public static final String PanDistanceProperty = "panDistance"; - public static final String ZoomFactorProperty = "zoomFactor"; - - public final static int DEFAULT_BUTTON_SIZE = 15; - - protected final static float defaultPanDistance = Float.NaN; - protected final static float defaultZoomFactor = 2.0f; - - protected static Color CONTROL_BACKGROUND = OMGraphicConstants.clear; - protected DrawingAttributes fadeAttributes; - protected DrawingAttributes liveAttributes; - protected int buttonSize = DEFAULT_BUTTON_SIZE; - protected ImageIcon backIcon; - protected ImageIcon backDimIcon; - protected ImageIcon forwardIcon; - protected ImageIcon forwardDimIcon; - - protected MapBean map; - protected CenterSupport centerDelegate; - protected PanSupport panDelegate; - protected ZoomSupport zoomDelegate; - protected JButton forwardProjectionButton; - protected JButton backProjectionButton; - protected JSlider slider; - - private float panDistance = defaultPanDistance; - private float zoomFactor = defaultZoomFactor; - - protected float MIN_TRANSPARENCY = .25f; - protected float SEMI_TRANSPARENCY = .65f; - protected float MAX_TRANSPARENCY = 1.0f; - protected boolean fade = false; - - protected Point2D recenterPoint; - - protected AlphaComposite ac = AlphaComposite.getInstance( - AlphaComposite.SRC_ATOP, MAX_TRANSPARENCY); - - public EmbeddedNavPanel() { - this(null, null, DEFAULT_BUTTON_SIZE); - } - - /** - * Make one. - * - * @param buttonColors - * The live button colors when active. - * @param fadeColors - * The faded button colors, when inactive. - * @param buttonSize - * The relative pixel button sizes. - */ - public EmbeddedNavPanel(DrawingAttributes buttonColors, - DrawingAttributes fadeColors, int buttonSize) { - super(); - centerDelegate = new CenterSupport(this); - panDelegate = new PanSupport(this); - zoomDelegate = new ZoomSupport(this); - // the two commands required to make this panel transparent - setBackground(OMGraphicConstants.clear); - setOpaque(false); - - initColors(buttonColors, fadeColors, buttonSize); - - // Checks the openmap.Latitude and openmap.Longitude properties, and - // initializes the re-center point to that. - float lat = Environment.getFloat(Environment.Latitude, 0f); - float lon = Environment.getFloat(Environment.Longitude, 0f); - setRecenterPoint(new Point2D.Float(lon, lat)); - - layoutPanel(); - } - - protected void initColors(DrawingAttributes buttonColors, - DrawingAttributes fadeColors, int buttonSize) { - - fadeAttributes = fadeColors; - liveAttributes = buttonColors; - - if (buttonSize >= 10) { - this.buttonSize = buttonSize; - } - - if (fadeAttributes == null) { - fadeAttributes = DrawingAttributes.getDefaultClone(); - Color fadeColor = new Color(0xffaaaaaa); - fadeAttributes.setFillPaint(fadeColor); - fadeAttributes.setLinePaint(fadeColor.darker()); - } - - if (buttonColors == null) { - liveAttributes = DrawingAttributes.getDefaultClone(); - Color liveColor = new Color(0xDDF3F3F3); - liveAttributes.setFillPaint(liveColor); - liveAttributes.setMattingPaint(liveColor); - liveAttributes.setMatted(true); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - fadeAttributes.setProperties(prefix + FADE_ATTRIBUTES_PROPERTY, props); - liveAttributes.setProperties(prefix + LIVE_ATTRIBUTES_PROPERTY, props); - - panDistance = PropUtils.floatFromProperties(props, prefix - + PanDistanceProperty, defaultPanDistance); - - zoomFactor = PropUtils.floatFromProperties(props, prefix - + ZoomFactorProperty, defaultZoomFactor); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - fadeAttributes.getProperties(props); - liveAttributes.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + PanDistanceProperty, String.valueOf(panDistance)); - props.put(prefix + ZoomFactorProperty, String.valueOf(zoomFactor)); - - return props; - } - - /** - * TODO: This is not complete, the drawing attributes need to be separated - * out and scoped, so they can be set individually. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - // fadeAttributes.getPropertyInfo(props); - // liveAttributes.getPropertyInfo(props); - - String interString; - props.put(initPropertiesProperty, - PanDistanceProperty + " " + ZoomFactorProperty); - - interString = i18n.get(EmbeddedNavPanel.class, - PanDistanceProperty, - com.bbn.openmap.util.I18n.TOOLTIP, - "Panning Distance."); - props.put(PanDistanceProperty, interString); - interString = i18n.get(EmbeddedNavPanel.class, - PanDistanceProperty, - "Panning Distance"); - props.put(PanDistanceProperty + LabelEditorProperty, - interString); - props.put(PanDistanceProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.TextPropertyEditor"); - - interString = i18n.get(EmbeddedNavPanel.class, - ZoomFactorProperty, - com.bbn.openmap.util.I18n.TOOLTIP, - "Zoom Factor."); - props.put(ZoomFactorProperty, interString); - interString = i18n.get(EmbeddedNavPanel.class, - ZoomFactorProperty, - "Zoom Factor"); - props.put(ZoomFactorProperty + LabelEditorProperty, - interString); - props.put(ZoomFactorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.TextPropertyEditor"); - - return props; - } - - protected void layoutPanel() { - - removeAll(); - int projStackButtonSize = (int) (buttonSize * 1.25); - int rosetteButtonSize = buttonSize; - int zoomButtonSize = buttonSize; - setLayout(new GridBagLayout()); - - GridBagConstraints layoutConstraints = new GridBagConstraints(); - int baseY = 0; - - IconPart bigArrow = OpenMapAppPartCollection.BIG_ARROW.getIconPart(); - bigArrow.setRenderingAttributes(fadeAttributes); - backDimIcon = OMIconFactory.getIcon(projStackButtonSize, - projStackButtonSize, bigArrow, null, Length.DECIMAL_DEGREE - .toRadians(270.0)); - bigArrow.setRenderingAttributes(liveAttributes); - backIcon = OMIconFactory.getIcon(projStackButtonSize, - projStackButtonSize, bigArrow, null, Length.DECIMAL_DEGREE - .toRadians(270.0)); - backProjectionButton = makeButton(backDimIcon, - "Show Previous Projection"); - backProjectionButton.setActionCommand(ProjectionStack.BackProjCmd); - - bigArrow.setRenderingAttributes(fadeAttributes); - forwardDimIcon = OMIconFactory.getIcon(projStackButtonSize, - projStackButtonSize, bigArrow, null, Length.DECIMAL_DEGREE - .toRadians(90.0)); - bigArrow.setRenderingAttributes(liveAttributes); - forwardIcon = OMIconFactory.getIcon(projStackButtonSize, - projStackButtonSize, bigArrow, null, Length.DECIMAL_DEGREE - .toRadians(90.0)); - forwardProjectionButton = makeButton(forwardDimIcon, - "Show Next Projection"); - forwardProjectionButton - .setActionCommand(ProjectionStack.ForwardProjCmd); - - JPanel projStackButtonPanel = new JPanel(); - projStackButtonPanel.setOpaque(false); - projStackButtonPanel.setBackground(CONTROL_BACKGROUND); - projStackButtonPanel.add(backProjectionButton); - projStackButtonPanel.add(forwardProjectionButton); - - layoutConstraints.anchor = GridBagConstraints.CENTER; - layoutConstraints.gridwidth = GridBagConstraints.REMAINDER; - layoutConstraints.gridy = baseY++; - - add(projStackButtonPanel, layoutConstraints); - - JPanel rosette = new JPanel(); - GridBagLayout internalGridbag = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - rosette.setLayout(internalGridbag); - - rosette.setOpaque(false); - rosette.setBackground(CONTROL_BACKGROUND); - - c2.gridx = 0; - c2.gridy = 0; - rosette.add(makeButton(OpenMapAppPartCollection.OPP_CORNER_TRI - .getIconPart(), liveAttributes, rosetteButtonSize, 0.0, - "Pan Northwest", new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(-45f, panDistance); - } - }), c2); - c2.gridx = 1; - rosette.add(makeButton( - OpenMapAppPartCollection.MED_ARROW.getIconPart(), - liveAttributes, rosetteButtonSize, 0.0, "Pan North", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(0f, panDistance); - } - })); - c2.gridx = 2; - rosette.add(makeButton(OpenMapAppPartCollection.OPP_CORNER_TRI - .getIconPart(), liveAttributes, rosetteButtonSize, 90.0, - "Pan Northeast", new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(45f, panDistance); - } - }), c2); - - c2.gridx = 0; - c2.gridy = 1; - rosette.add(makeButton( - OpenMapAppPartCollection.MED_ARROW.getIconPart(), - liveAttributes, rosetteButtonSize, 270.0, "Pan West", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(-90f, panDistance); - } - }), c2); - c2.gridx = 1; - IconPartList ipl = new IconPartList(); - ipl.add(OpenMapAppPartCollection.CIRCLE.getIconPart()); - ipl.add(OpenMapAppPartCollection.DOT.getIconPart()); - rosette.add(makeButton(ipl, liveAttributes, rosetteButtonSize, 0.0, - "Center Map", new ActionListener() { - public void actionPerformed(ActionEvent event) { - Point2D centerPnt = getRecenterPoint(); - if (centerPnt == null) { - centerDelegate.fireCenter(0, 0); - } else { - centerDelegate.fireCenter(centerPnt.getY(), - centerPnt.getX()); - } - } - }), c2); - c2.gridx = 2; - rosette.add(makeButton( - OpenMapAppPartCollection.MED_ARROW.getIconPart(), - liveAttributes, rosetteButtonSize, 90.0, "Pan East", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(90f, panDistance); - } - }), c2); - - c2.gridx = 0; - c2.gridy = 2; - rosette.add(makeButton(OpenMapAppPartCollection.OPP_CORNER_TRI - .getIconPart(), liveAttributes, rosetteButtonSize, 270.0, - "Pan Southwest", new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(-135f, panDistance); - } - }), c2); - c2.gridx = 1; - rosette.add(makeButton( - OpenMapAppPartCollection.MED_ARROW.getIconPart(), - liveAttributes, rosetteButtonSize, 180.0, "Pan South", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(180f, panDistance); - } - }), c2); - c2.gridx = 2; - rosette.add(makeButton(OpenMapAppPartCollection.OPP_CORNER_TRI - .getIconPart(), liveAttributes, rosetteButtonSize, 180.0, - "Pan Southeast", new ActionListener() { - public void actionPerformed(ActionEvent event) { - panDelegate.firePan(135f, panDistance); - } - }), c2); - - layoutConstraints.gridy = baseY++; - add(rosette, layoutConstraints); - - layoutConstraints.gridy = baseY++; - layoutConstraints.insets = new Insets(6, 0, 6, 0); - ipl = new IconPartList(); - // ipl.add(OpenMapAppPartCollection.CIRCLE.getIconPart()); - ipl.add(OpenMapAppPartCollection.PLUS.getIconPart()); - add(makeButton(ipl, liveAttributes, zoomButtonSize, 0.0, "Zoom In", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - zoomDelegate.fireZoom(ZoomEvent.RELATIVE, 1.0f / zoomFactor); - } - }), layoutConstraints); - - layoutConstraints.gridy = baseY++; - layoutConstraints.insets = new Insets(0, 0, 0, 0); - add(makeScaleSlider(liveAttributes), layoutConstraints); - - layoutConstraints.gridy = baseY++; - layoutConstraints.insets = new Insets(6, 0, 6, 0); - ipl = new IconPartList(); - // ipl.add(OpenMapAppPartCollection.CIRCLE.getIconPart()); - ipl.add(OpenMapAppPartCollection.MINUS.getIconPart()); - add(makeButton(ipl, liveAttributes, zoomButtonSize, 0.0, "Zoom Out", - new ActionListener() { - public void actionPerformed(ActionEvent event) { - zoomDelegate.fireZoom(ZoomEvent.RELATIVE, zoomFactor); - } - }), layoutConstraints); - - // We could drop this, but I think it's needed to play well with other - // containers when needed. - layoutConstraints.fill = GridBagConstraints.VERTICAL; - layoutConstraints.gridy = baseY++; - layoutConstraints.weighty = 1; - JPanel filler = new JPanel(); - filler.setOpaque(false); - filler.setBackground(OMGraphicConstants.clear); - add(filler, layoutConstraints); - - setMinimumSize(new Dimension(75, (projStackButtonSize + 3 - * rosetteButtonSize + 2 * zoomButtonSize + 24 + 200))); - } - - public Point2D getRecenterPoint() { - return recenterPoint; - } - - public void setRecenterPoint(Point2D recenterPoint) { - this.recenterPoint = recenterPoint; - } - - public float getPanDistance() { - return panDistance; - } - - public void setPanDistance(float panDistance) { - this.panDistance = panDistance; - } - - public float getZoomFactor() { - return zoomFactor; - } - - public void setZoomFactor(float zoomFactor) { - this.zoomFactor = zoomFactor; - } - - protected JButton makeButton(IconPart iconPart, DrawingAttributes da, - int size, double ddRot, String tooltip, ActionListener ac) { - iconPart.setRenderingAttributes(da); - return makeButton(OMIconFactory.getIcon(size, size, iconPart, null, - Length.DECIMAL_DEGREE.toRadians(ddRot)), tooltip, ac); - } - - protected JButton makeButton(ImageIcon icon, String toolTip, - ActionListener listener) { - JButton button = makeButton(icon, toolTip); - button.addActionListener(listener); - // KNOX -- don't let buttons get focus and add transparency listener - button.setFocusable(false); - button.addMouseListener(new NavPanelMouseListener()); - return button; - } - - protected JButton makeButton(ImageIcon icon, String toolTip) { - JButton button = new JButton(icon); - // MAGIC: required to make background transparent! - button.setBackground(CONTROL_BACKGROUND); - button.setBorder(null); - button.setMargin(new Insets(0, 0, 0, 0)); - // No surprise: also required to make background transparent. - button.setOpaque(false); - button.setBorderPainted(false); - button.setPreferredSize(new Dimension(icon.getIconWidth(), icon - .getIconHeight())); - button.setToolTipText(toolTip); - // KNOX -- don't let buttons get focus and add transparency listener - button.setFocusable(false); - button.addMouseListener(new NavPanelMouseListener()); - return button; - } - - protected JComponent makeScaleSlider(DrawingAttributes da) { - slider = new JSlider(SwingConstants.VERTICAL, 0, SLIDER_MAX, SLIDER_MAX); - slider.setUI(new NavPanelSliderUI(slider, (Color) da.getFillPaint())); - // MAGIC: required to make background transparent! - slider.setBackground((Color) da.getFillPaint()); - slider.setBorder(BorderFactory.createLineBorder((Color) da - .getFillPaint(), 1)); - slider.setForeground((Color) da.getFillPaint()); - slider.setInverted(true); - slider.setMinorTickSpacing(1); - // No surprise: also required to make background transparent. - slider.setOpaque(false); - slider.setPaintTicks(true); - slider.setSnapToTicks(true); - slider.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent event) { - // Need the check to avoid resetting the map scale if the window - // is - // resized. Only want this to happen of someone is moving the - // slider - // lever. - if (slider.getValueIsAdjusting()) { - changeMapScale(slider.getValue()); - } - } - }); - // KNOX -- don't let slider get focus and add transparency listener - slider.setFocusable(false); - slider.addMouseListener(new NavPanelMouseListener()); - return slider; - } - - protected void changeMapScale(int sliderValue) { - float newScale = sliderToScale(sliderValue); - - if (map.getScale() != newScale) { - map.setScale(newScale); - } - } - - protected void changeSliderValue(Projection projection) { - int newValue = scaleToSlider(projection.getScale()); - - if (slider.getValue() != newValue) { - slider.setValue(newValue); - } - } - - protected float sliderToScale(int sliderValue) { - return (float) (getMapMaxScale() / Math.pow(2, - (SLIDER_MAX - sliderValue))); - } - - protected int scaleToSlider(float mapScale) { - return (SLIDER_MAX - logBase2(getMapMaxScale() / mapScale)); - } - - /** Returns the largest integer n, such that 2^n <= the specified number. */ - public final static int logBase2(double number) { - int log = 0; - - while (number > 1) { - number = Math.floor(number / 2); - ++log; - } - - return log; - } - - public Color getScaleSliderBackground() { - return slider.getBackground(); - } - - public void setScaleSliderBackground(Color sliderBackground) { - slider.setBackground(sliderBackground); - } - - public Color getScaleSliderForeground() { - return slider.getForeground(); - } - - public void setScaleSliderForeground(Color sliderForeground) { - slider.setForeground(sliderForeground); - } - - private final float getMapMaxScale() { - return map.getProjection().getMaxScale(); - } - - // OMComponentPanel - public void findAndInit(Object someObject) { - if (someObject instanceof MapBean) { - map = (MapBean) someObject; - map.addProjectionListener(this); - } - if (someObject instanceof PanListener) { - addPanListener((PanListener) someObject); - } - if (someObject instanceof CenterListener) { - addCenterListener((CenterListener) someObject); - } - if (someObject instanceof ZoomListener) { - addZoomListener((ZoomListener) someObject); - } - if (someObject instanceof ProjectionStack) { - ((ProjectionStack) someObject).addProjectionStackTrigger(this); - } - } - - // OMComponentPanel - public void findAndUndo(Object someObject) { - if (someObject instanceof MapBean) { - map.removeProjectionListener(this); - } - if (someObject instanceof PanListener) { - removePanListener((PanListener) someObject); - } - if (someObject instanceof CenterListener) { - removeCenterListener((CenterListener) someObject); - } - if (someObject instanceof ZoomListener) { - removeZoomListener((ZoomListener) someObject); - } - if (someObject instanceof ProjectionStack) { - ((ProjectionStack) someObject).removeProjectionStackTrigger(this); - } - } - - public synchronized void addCenterListener(CenterListener listener) { - centerDelegate.add(listener); - } - - public synchronized void removeCenterListener(CenterListener listener) { - centerDelegate.remove(listener); - } - - public synchronized void addPanListener(PanListener listener) { - panDelegate.add(listener); - } - - public synchronized void removePanListener(PanListener listener) { - panDelegate.remove(listener); - } - - public synchronized void addZoomListener(ZoomListener listener) { - zoomDelegate.add(listener); - } - - public synchronized void removeZoomListener(ZoomListener listener) { - zoomDelegate.remove(listener); - } - - // ProjectionListener - public void projectionChanged(ProjectionEvent event) { - changeSliderValue(event.getProjection()); - } - - /** Adds a listener for events that shift the Projection stack. */ - // ProjectionStackTrigger - public void addActionListener(ActionListener listener) { - forwardProjectionButton.addActionListener(listener); - backProjectionButton.addActionListener(listener); - } - - /** Removes the listener for events that shift the Projection stack. */ - // ProjectionStackTrigger - public void removeActionListener(ActionListener listener) { - forwardProjectionButton.addActionListener(listener); - backProjectionButton.addActionListener(listener); - } - - /** - * Respond to changes in the contents of the forward and back projection - * stacks. - * - * @param haveBackProjections - * true if there is at least one back projection available - * @param haveForwardProjections - * true if there is at least one forward projection available - */ - // ProjectionStackTrigger - public void updateProjectionStackStatus(boolean haveBackProjections, - boolean haveForwardProjections) { - forwardProjectionButton.setIcon(haveForwardProjections ? forwardIcon - : forwardDimIcon); - backProjectionButton.setIcon(haveBackProjections ? backIcon - : backDimIcon); - forwardProjectionButton.setEnabled(haveForwardProjections); - backProjectionButton.setEnabled(haveBackProjections); - } - - public void paint(Graphics g) { - if (ac != null) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setComposite(ac); - super.paint(g2); - g2.dispose(); - } else { - super.paint(g); - } - } - - public void setTransparency(float transparency) { - if (ac != null) { - if (transparency > MAX_TRANSPARENCY) { - transparency = MAX_TRANSPARENCY; - } - - ac = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, - transparency); - repaint(); - } - } - - public void setMinimumTransparency(float minTransparency) { - MIN_TRANSPARENCY = minTransparency; - } - - public void setSemiTransparency(float semiTransparency) { - SEMI_TRANSPARENCY = semiTransparency; - } - - public DrawingAttributes getFadeAttributes() { - return fadeAttributes; - } - - public void setFadeAttributes(DrawingAttributes fadeAttributes) { - this.fadeAttributes = fadeAttributes; - } - - public DrawingAttributes getLiveAttributes() { - return liveAttributes; - } - - public void setLiveAttributes(DrawingAttributes liveAttributes) { - this.liveAttributes = liveAttributes; - } - - public AlphaComposite getAc() { - return ac; - } - - public void setAc(AlphaComposite ac) { - this.ac = ac; - } - - public MapBean getMap() { - return map; - } - - // KNOX -- using this to paint ticks on slider - private class NavPanelSliderUI extends BasicSliderUI { - Color sliderTickColor = Color.white; - - public NavPanelSliderUI(JSlider slider, Color tickColor) { - super(slider); - sliderTickColor = tickColor; - } - - @Override - protected void paintMinorTickForVertSlider(Graphics g, - Rectangle tickBounds, int y) { - g.setColor(sliderTickColor); - super.paintMinorTickForVertSlider(g, tickBounds, y); - } - - } - - // KNOX -- using this to change level of transparency when mousing over - // buttons/slider - private class NavPanelMouseListener extends MouseAdapter { - @Override - public void mouseEntered(MouseEvent e) { - if (ac.getAlpha() < SEMI_TRANSPARENCY) { - setTransparency(SEMI_TRANSPARENCY); - getTopLevelAncestor().repaint(); - } - } - - @Override - public void mouseExited(MouseEvent e) { - if (ac.getAlpha() > MIN_TRANSPARENCY) { - setTransparency(MIN_TRANSPARENCY); - getTopLevelAncestor().repaint(); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedScaleDisplayPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedScaleDisplayPanel.java deleted file mode 100644 index 6ccd33818..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/EmbeddedScaleDisplayPanel.java +++ /dev/null @@ -1,459 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -package com.bbn.openmap.gui; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; - -/** - * A panel that listens for projection changes and draws a little legend line on - * itself with a distance. Can be modified with Properties. - * - *
- * 
- * unitOfMeasure=km (or any value from the Length class)
- * locationXoffset=-10 (value off the edge of the component to have legend)
- * locationYoffset=-10 
- * width=pixel width of component
- * height=pixel height of component
- * 
- */ -public class EmbeddedScaleDisplayPanel extends OMComponentPanel implements ProjectionListener { - - public EmbeddedScaleDisplayPanel() { - super(); - setOpaque(false); - setBackground(OMColor.clear); - setPreferredSize(new Dimension(350, 100)); - - dAttributes.setMattingPaint(new Color(0xffcccccc)); - dAttributes.setMatted(true); - - } - - public EmbeddedScaleDisplayPanel(DrawingAttributes dAtts, Length units) { - this(); - setUnitOfMeasure(units.getAbbr()); - dAttributes = dAtts; - } - - // Default colors to use, if not specified in the properties. - protected String defaultLineColorString = "FFFFFF"; - protected String defaultTextColorString = "FFFFFF"; - protected String defaultUnitOfMeasureString = "km"; - protected int defaultLocationXoffset = -10; - protected int defaultLocationYoffset = -10; - protected int defaultWidth = 150; - protected int defaultHeight = 10; - - // property text values - public static final String UnitOfMeasureProperty = "unitOfMeasure"; - public static final String LocationXOffsetProperty = "locationXoffset"; - public static final String LocationYOffsetProperty = "locationYoffset"; - public static final String WidthProperty = "width"; - public static final String HeightProperty = "height"; - - protected Length uom = Length.get(defaultUnitOfMeasureString); - protected int locationXoffset = defaultLocationXoffset; - protected int locationYoffset = defaultLocationYoffset; - protected int width = defaultWidth; - protected int height = defaultHeight; - - protected DrawingAttributes dAttributes = DrawingAttributes.getDefaultClone(); - private static final long serialVersionUID = 1L; - static final float RADIANS_270 = Length.DECIMAL_DEGREE.toRadians(270); - protected OMGraphicList legend; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.EmbedddedScaleDisplayPanel"); - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than the - * setArgs method. - * - * @param prefix the token to prefix the property names - * @param properties the Properties object - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - prefix = com.bbn.openmap.util.PropUtils.getScopedPropertyPrefix(prefix); - - dAttributes.setProperties(prefix, properties); - - String unitOfMeasure = properties.getProperty(prefix + UnitOfMeasureProperty); - setUnitOfMeasure(unitOfMeasure); - - locationXoffset = PropUtils.intFromProperties(properties, prefix + LocationXOffsetProperty, defaultLocationXoffset); - - locationYoffset = PropUtils.intFromProperties(properties, prefix + LocationYOffsetProperty, defaultLocationYoffset); - - width = PropUtils.intFromProperties(properties, prefix + WidthProperty, defaultWidth); - - height = PropUtils.intFromProperties(properties, prefix + HeightProperty, defaultHeight); - } - - /** - * Getter for property unitOfMeasure. - * - * @return Value of property unitOfMeasure. - */ - public String getUnitOfMeasure() { - return this.uom.toString(); - } - - /** - * Setter for property unitOfMeasure. - * - * @param unitOfMeasure New value of property unitOfMeasure. - */ - public void setUnitOfMeasure(String unitOfMeasure) { - if (unitOfMeasure == null) - unitOfMeasure = Length.KM.toString(); - - // There is a bug in the Length.get() method that will not - // return - // the correct (or any value) for a requested uom. - // This does not work: - // uom = com.bbn.openmap.proj.Length.get(unitOfMeasure); - - // Therefore, The following code correctly obtains the proper - // Length object. - - Length[] choices = Length.values(); - uom = null; - for (int i = 0; i < choices.length; i++) { - if (unitOfMeasure.equalsIgnoreCase(choices[i].toString()) - || unitOfMeasure.equalsIgnoreCase(choices[i].getAbbr())) { - uom = choices[i]; - break; - } - } - - // of no uom is found assign Kilometers as the default. - if (uom == null) - uom = Length.KM; - } - - JPanel palette; - Vector buttons = new Vector(); - ButtonGroup uomButtonGroup; - - /** Creates the interface palette. */ - public java.awt.Component getGUI() { - if (palette == null) { - - logger.fine("creating palette."); - - palette = new JPanel(); - uomButtonGroup = new ButtonGroup(); - - palette.setLayout(new javax.swing.BoxLayout(palette, javax.swing.BoxLayout.Y_AXIS)); - palette.setBorder(new javax.swing.border.TitledBorder("Unit Of Measure")); - - ActionListener al = new ActionListener() { - // We don't have to check for action commands or anything like - // that. - // We know this listener is going to be added to JRadioButtons - // that - // are labeled with abbreviations for length. - public void actionPerformed(ActionEvent e) { - JRadioButton jrb = (JRadioButton) e.getSource(); - setUnitOfMeasure(jrb.getText()); - } - }; - - for (Length lengthType : Length.values()) { - JRadioButton jrb = new JRadioButton(); - jrb.setText(lengthType.getAbbr()); - jrb.setToolTipText(lengthType.toString()); - uomButtonGroup.add(jrb); - palette.add(jrb); - - jrb.addActionListener(al); - - jrb.setSelected(uom.getAbbr().equalsIgnoreCase(lengthType.getAbbr())); - buttons.add(jrb); - } - - } else { - for (JRadioButton button : buttons) { - button.setSelected(uom.getAbbr().equalsIgnoreCase(button.getText())); - } - } - - return palette; - } - - public void projectionChanged(ProjectionEvent e) { - int w, h, left_x = 0, right_x = 0, lower_y = 0, upper_y = 0; - Projection projection = e.getProjection(); - OMGraphicList graphics = new OMGraphicList(); - - w = projection.getWidth(); - h = projection.getHeight(); - // FIXME: Use the center since it's always real - - /** - * Since the pixel space for the component has nothing to do with the - * pixel space of the projection, we'll just use the projection pixel - * space to find out how long the line should be. Then, we'll move that - * length into component pixel space. - */ - - lower_y = h / 2; - right_x = w / 2; - left_x = right_x - width; - - LatLonPoint loc1 = projection.inverse(left_x, lower_y, new LatLonPoint.Double()); - LatLonPoint loc2 = projection.inverse(right_x, lower_y, new LatLonPoint.Double()); - - double dist = GreatCircle.sphericalDistance(loc1.getRadLat(), loc1.getRadLon(), loc2.getRadLat(), loc2.getRadLon()); - - // Round the distance to one of the preferred values. - dist = uom.fromRadians(dist); - double new_dist = scopeDistance(dist); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("modifying " + dist + " to new distance: " + new_dist); - } - - left_x = getPtAtDistanceFromLatLon(loc2, new_dist, projection, uom); - - int lineLength = right_x - left_x; - - // If the length of the distance line is longer than the width of the - // panel, divide it in half. - int maxWidth = Math.max(getWidth() - Math.abs(locationXoffset) * 2, 50); - while (lineLength > maxWidth) { - - lineLength /= 3; - new_dist /= 3.0; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("length of line too long, halving to " + lineLength); - } - double testDist = scopeDistance(new_dist); - if (!MoreMath.approximately_equal(testDist, new_dist) && !(new_dist <= .01)) { - lineLength = right_x - getPtAtDistanceFromLatLon(loc2, testDist, projection, uom); - if (logger.isLoggable(Level.FINE)) { - logger.fine("needed to rescope distance to " + testDist + " from " + new_dist); - } - new_dist = testDist; - } - - } - - // Now, check the units and try to avoid fractions - Length cur_uom = uom; - - if (new_dist < 1) { - if (uom.equals(Length.KM)) { - new_dist *= 1000; - cur_uom = Length.METER; - } else if (uom.equals(Length.MILE) || uom.equals(Length.DM) || uom.equals(Length.NM)) { - new_dist = Length.FEET.fromRadians(uom.toRadians(new_dist)); - cur_uom = Length.FEET; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("modified UOM to " + cur_uom.getAbbr() + ", value: " + new_dist); - } - - double testDist = scopeDistance(new_dist); - if (!MoreMath.approximately_equal(testDist, new_dist)) { - lineLength = right_x - - getPtAtDistanceFromLatLon(loc2, testDist, projection, cur_uom); - if (logger.isLoggable(Level.FINE)) { - logger.fine("needed to rescope distance to " + testDist + " from " + new_dist); - } - new_dist = testDist; - } - } - - /** - * Now, figure out where OMGraphics go in the component space. - */ - if (locationXoffset < 0) { - int cw = getWidth(); - left_x = cw + locationXoffset - lineLength; - right_x = cw + locationXoffset; - } else if (locationXoffset >= 0) { - left_x = locationXoffset; - right_x = locationXoffset + lineLength; - } - if (locationYoffset < 0) { - int ch = getHeight(); - upper_y = ch + locationYoffset - height; - lower_y = ch + locationYoffset; - } else if (locationYoffset >= 0) { - upper_y = locationYoffset; - lower_y = locationYoffset + height; - } - - // Draw the lines and the rounded distance string. - OMLine line = new OMLine(left_x, lower_y, right_x, lower_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(left_x, lower_y, left_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(right_x, lower_y, right_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - // String outtext; - // if (new_dist < 1.0f) { - // outtext = String.format("%.3f %s", new_dist, cur_uom.getAbbr()); - // } else if (new_dist < 10.0f) { - // outtext = String.format("%.2f %s", new_dist, cur_uom.getAbbr()); - // } else if (new_dist < 100.0f) { - // outtext = String.format("%.1f %s", new_dist, cur_uom.getAbbr()); - // } else { - String outtext = String.format("%.0f %s", new_dist, cur_uom.getAbbr()); - // } - - OMText text = new OMText(right_x, lower_y - 20, "" + outtext, OMText.JUSTIFY_RIGHT); - - Font font = text.getFont(); - text.setFont(font.deriveFont(Font.BOLD, font.getSize() + 4)); - - dAttributes.setTo(text); - text.setTextMatteColor((Color) dAttributes.getMattingPaint()); - text.setTextMatteStroke(new BasicStroke(5)); - text.setMattingPaint(OMColor.clear); - graphics.add(text); - graphics.generate(projection); - - setLegend(graphics); - - } - - protected int getPtAtDistanceFromLatLon(LatLonPoint loc2, double unitDist, - Projection projection, Length uom) { - double lineWidthInRadians = uom.toRadians(unitDist); - LatLonPoint newX = GreatCircle.sphericalBetween(loc2.getRadLat(), loc2.getRadLon(), lineWidthInRadians, RADIANS_270); - Point2D newLoc1 = projection.forward(newX); - return (int) Math.round(newLoc1.getX()); - } - - /** - * Take a given distance and round it down to the nearest 1, 2, or 5 (or - * tens/hundreds version of those increments) multiple of that number. - * - * @param dist - * @return scoped value of distance, incremented properly - */ - protected double scopeDistance(double dist) { - double new_dist; - if (dist <= .01) { - new_dist = .01; - } else if (dist <= .02) { - new_dist = .02; - } else if (dist <= .05) { - new_dist = .05; - } else if (dist <= .1) { - new_dist = .1; - } else if (dist <= .2) { - new_dist = .2; - } else if (dist <= .5) { - new_dist = .5; - } else if (dist <= 1) { - new_dist = 1; - } else if (dist <= 2) { - new_dist = 2; - } else if (dist <= 5) { - new_dist = 5; - } else if (dist <= 10) { - new_dist = 10; - } else if (dist <= 20) { - new_dist = 20; - } else if (dist <= 50) { - new_dist = 50; - } else if (dist <= 100) { - new_dist = 100; - } else if (dist <= 200) { - new_dist = 200; - } else if (dist <= 500) { - new_dist = 500; - } else { - new_dist = 1000; - } - return new_dist; - } - - public OMGraphicList getLegend() { - return legend; - } - - public void setLegend(OMGraphicList legend) { - this.legend = legend; - } - - public void paint(Graphics g) { - if (legend != null) { - legend.render(g); - } - } - - protected MapBean mapBean; - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof MapBean) { - mapBean = (MapBean) someObj; - mapBean.addProjectionListener(this); - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - - if (someObj.equals(mapBean)) { - mapBean.removeProjectionListener(this); - mapBean = null; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/FileMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/FileMenu.java deleted file mode 100644 index 9cfedd34a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/FileMenu.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/FileMenu.java,v $ -// $RCSfile: FileMenu.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import javax.swing.JSeparator; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.gui.menu.AboutMenuItem; -import com.bbn.openmap.gui.menu.LoadPropertiesMenuItem; -import com.bbn.openmap.gui.menu.MapBeanPrinterMenuItem; -import com.bbn.openmap.gui.menu.QuitMenuItem; -import com.bbn.openmap.gui.menu.SaveAsMenu; -import com.bbn.openmap.gui.menu.SavePropertiesMenuItem; - -/** - * FileMenu creates AboutMenuItem, SavePropertiesMenuItem, - * SaveImageMenuItem, ExitMenuItem. It only adds AboutMenuItem if - * runing as an Applet, all otherwise. These menu items are added by - * default. - */ -public class FileMenu extends AbstractOpenMapMenu { - - /** - * - */ - private static final long serialVersionUID = -8780394246920152460L; - private String defaultText = "File"; - private int defaultMnemonic = 'F'; - - /** - * Create and add menuitems(About, SaveProperties, SaveAsImage and - * Exit) - */ - public FileMenu() { - super(); - setText(defaultText); -// setMnemonic(defaultMnemonic); - - add(new AboutMenuItem()); - - if (!Environment.isApplet()) { - add(new JSeparator()); - add(new SavePropertiesMenuItem()); - add(new LoadPropertiesMenuItem()); - add(new JSeparator()); - add(new SaveAsMenu()); - add(new MapBeanPrinterMenuItem()); - add(new JSeparator()); - add(new QuitMenuItem()); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/GoToMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/GoToMenu.java deleted file mode 100644 index 46cab162a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/GoToMenu.java +++ /dev/null @@ -1,531 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/GoToMenu.java,v $ -// $RCSfile: GoToMenu.java,v $ -// $Revision: 1.20 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JTextField; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.gui.menu.DataBoundsViewMenuItem; -import com.bbn.openmap.gui.menu.OMBasicMenu; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Menu that keeps track of different saved map views (lat/lon, scale and - * projection type), and provides a way to set the map projection to those - * views. There is a set of optional default views, but new views can be added. - * If these views are added to the properties file, they will be added to the - * menu automatically for later uses. This menu can understand a set of - * properties: - * - *
- * 
- * 
- *   gotoMenu.class=com.bbn.openmap.gui.GoToMenu
- *   #Add the default, world view option
- *   gotoMenu.addDefaults=true
- *   #Add the menu for DataBoundsProviders
- *   gotoMenu.addDataViews=true
- *   #Additional views
- *   goto.views=Argentina India United_States Caspian_Sea
- *   Argentina.latitude=-39.760445
- *   Argentina.longitude=-65.92294
- *   Argentina.name=Argentina
- *   Argentina.projection=Mercator
- *   Argentina.scale=5.0E7
- *   India.latitude=20.895763
- *   India.longitude=80.437485
- *   India.name=India
- *   India.projection=Mercator
- *   India.scale=3.86688E7
- *   United_States.latitude=38.82259
- *   United_States.longitude=-96.74999
- *   United_States.name=United States
- *   United_States.projection=Mercator
- *   United_States.scale=5.186114E7
- *   Caspian_Sea.name=Caspian Sea
- *   Caspian_Sea.latitude=40f
- *   Caspian_Sea.longitude=47f
- *   Caspian_Sea.scale=1000000
- *   Caspian_Sea.projection=CADRG
- * 
- * 
- * 
- */ -public class GoToMenu extends AbstractOpenMapMenu { - - private static final long serialVersionUID = 1L; - private String defaultText = "Views"; - private String defaultMnemonic = "V"; - - protected Map dataBoundsProviders = new HashMap<>(); - protected OMBasicMenu dataBoundsMenu; - protected MapBean map; - protected List customViews; - - /** - * A space separated list of marker names for the views to be loaded from - * the properties. - */ - public final static String ViewListProperty = "views"; - /** The name of the view to use in the GUI. */ - public final static String NameProperty = "name"; - /** The center latitude of the view projection. */ - public final static String LatProperty = "latitude"; - /** The center longitude of the view projection. */ - public final static String LonProperty = "longitude"; - /** The scale of the view projection. */ - public final static String ScaleProperty = "scale"; - /** The projection type of the view projection. */ - public final static String ProjectionTypeProperty = "projection"; - /** Flag to use to add default views (World, each continent. */ - public final static String AddDefaultListProperty = "addDefaults"; - /** - * Flag to use to enable/disable the gathering of DataBoundsProviders. - */ - public final static String AddDataViewsProperty = "addDataViews"; - - protected boolean addDefaults = true; - protected boolean addDataViews = true; - - public GoToMenu() { - super(); - setText(i18n.get(this, "goto", defaultText)); - // setMnemonic(i18n.get(this, "goto", I18n.MNEMONIC, defaultMnemonic) - // .charAt(0)); - - // dataBoundsMenu = new OMBasicMenu("Go Over Data"); - dataBoundsMenu = new OMBasicMenu(i18n.get(this, - "goOverData", - "Go Over Data")); - - // add(new AddNewViewButton("Add Saved View...")); - add(new AddNewViewButton(i18n.get(this, - "addSavedView", - "Add Saved View..."))); - add(dataBoundsMenu); - add(new JSeparator()); - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof MapBean) { - // do the initializing that need to be done here - if (getMap() == (MapBean) someObj) { - setMap(null); - } - } - - if (someObj instanceof DataBoundsProvider) { - removeDataBoundsProvider((DataBoundsProvider) someObj); - } - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof MapBean) { - // do the initializing that need to be done here - setMap((MapBean) someObj); - } - - if (someObj instanceof DataBoundsProvider) { - addDataBoundsProvider((DataBoundsProvider) someObj); - } - } - - /** Set the map to control. */ - public void setMap(MapBean mb) { - map = mb; - } - - public MapBean getMap() { - return map; - } - - /** PropertyConsumer interface method. */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - addDefaults = PropUtils.booleanFromProperties(props, prefix - + AddDefaultListProperty, addDefaults); - - addDataViews = PropUtils.booleanFromProperties(props, prefix - + AddDataViewsProperty, addDataViews); - - dataBoundsMenu.setVisible(addDataViews); - - if (addDefaults) { - addDefaultLocations(); - add(new JSeparator()); - } - - String locationList = props.getProperty(prefix + ViewListProperty); - - if (locationList != null) { - for (String viewPrefix : PropUtils.parseSpacedMarkers(locationList)) { - addLocationItem(viewPrefix, props); - } - } - } - - /** PropertyConsumer interface method. */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + AddDefaultListProperty, - new Boolean(addDefaults).toString()); - props.put(prefix + AddDataViewsProperty, - new Boolean(addDataViews).toString()); - - StringBuffer viewList = new StringBuffer(); - - for (GoToButton gtb : ensureCustomViews()) { - String sanitizedName = gtb.getText().replace(' ', '_'); - viewList.append(" ").append(sanitizedName); - - sanitizedName = PropUtils.getScopedPropertyPrefix(sanitizedName); - - props.put(sanitizedName + NameProperty, gtb.getText()); - props.put(sanitizedName + LatProperty, - new Float(gtb.latitude).toString()); - props.put(sanitizedName + LonProperty, - new Float(gtb.longitude).toString()); - props.put(sanitizedName + ScaleProperty, - new Float(gtb.scale).toString()); - props.put(sanitizedName + ProjectionTypeProperty, gtb.projectionID); - - } - - props.put(prefix + ViewListProperty, viewList.toString()); - - return props; - } - - /** PropertyConsumer interface method. */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - props.put(ViewListProperty, - "Space-separated marker list of different views"); - props.put(AddDefaultListProperty, - "Flag to add default views (true/false)."); - props.put(AddDefaultListProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - props.put(AddDataViewsProperty, - "Flag to add views from some data components."); - props.put(AddDataViewsProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - props.put(NameProperty, "The formal name of the view for the user."); - props.put(LatProperty, "The latitude of the center of the view."); - props.put(LonProperty, "The longitude of the center of the view."); - props.put(ScaleProperty, "The scale of the view."); - props.put(ProjectionTypeProperty, "The projection name of the view"); - - return props; - } - - /** Add the default views to the menu. */ - public void addDefaultLocations() { - add(new GoToButton(i18n.get(this, "world", "World"), 0, 0, Float.MAX_VALUE, Mercator.MercatorName)); - } - - /** - * An internal callback method that creates the custom views List object. - * Override to change what kind of object gets created (it's a Vector by - * default). - * - * @return List - */ - protected List createCustomViews() { - return new ArrayList(); - } - - public List getCustomViews() { - return customViews; - } - - /** - * Should call this when dealing with the custom views list, will always - * return a non-null answer. - * - * @return List - */ - public List ensureCustomViews() { - if (customViews == null) { - customViews = createCustomViews(); - } - return customViews; - } - - public void setCustomViews(List views) { - customViews = views; - } - - /** - * Parse and add the view from properties. - */ - public void addLocationItem(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String locationName = props.getProperty(prefix + NameProperty); - String latString = props.getProperty(prefix + LatProperty); - String lonString = props.getProperty(prefix + LonProperty); - String scaleString = props.getProperty(prefix + ScaleProperty); - String projID = props.getProperty(prefix + ProjectionTypeProperty); - - if (Debug.debugging("goto")) { - Debug.output("GoToMenu: adding view - " + locationName + ", " - + latString + ", " + lonString + ", " + scaleString + ", " - + projID); - } - - try { - float lat = new Float(latString).floatValue(); - float lon = new Float(lonString).floatValue(); - float scale = new Float(scaleString).floatValue(); - GoToButton gtb = new GoToButton(locationName, lat, lon, scale, projID); - ensureCustomViews().add(gtb); - add(gtb); - - } catch (NumberFormatException nfe) { - return; - } - } - - public void addDataBoundsProvider(DataBoundsProvider provider) { - if (!dataBoundsProviders.containsKey(provider)) { - DataBoundsViewMenuItem dbvmi = new DataBoundsViewMenuItem(provider); - dataBoundsProviders.put(provider, dbvmi); - dbvmi.findAndInit(getBeanContext()); - dataBoundsMenu.add(dbvmi); - } - } - - public void removeDataBoundsProvider(DataBoundsProvider provider) { - JMenuItem item = (DataBoundsViewMenuItem) dataBoundsProviders.remove(provider); - if (item != null) { - dataBoundsMenu.remove(item); - } - } - - /** - * Add a button to the menu that will set the map to a particular view. - */ - public void addView(GoToButton newOne) { - ensureCustomViews().add(newOne); - add(newOne); - revalidate(); - } - - /** - * This is the button that will bring up the dialog to actually name a new - * view being added. The new view will be the current projection of the map. - */ - public class AddNewViewButton extends JMenuItem implements ActionListener { - - private static final long serialVersionUID = 1L; - - public AddNewViewButton(String title) { - super(title); - this.addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - if (map != null) { - Projection proj = map.getProjection(); - Point2D llp = proj.getCenter(); - new GoToButton((float) llp.getY(), (float) llp.getX(), proj.getScale(), proj.getName()); - } - } - } - - /** - * This button contains the trigger for a saved view. - */ - public class GoToButton extends JMenuItem implements ActionListener { - - private static final long serialVersionUID = 1L; - public float latitude; - public float longitude; - public float scale; - public String projectionID; - - GoToMenu menu; - - public GoToButton(String title, float lat, float lon, float s, - String projID) { - super(title); - init(lat, lon, s, projID); - } - - public GoToButton(float lat, float lon, float s, String projID) { - init(lat, lon, s, projID); - NameFetcher nf = new NameFetcher(this); - if (map != null) { - Point p = map.getLocationOnScreen(); - int x = (int) p.getX(); - int y = (int) p.getY(); - int w = map.getWidth(); - int h = map.getHeight(); - nf.setLocation(x + (w - nf.getWidth()) / 2, y - + (h - nf.getHeight()) / 2); - } - nf.setVisible(true); - } - - public void init(float lat, float lon, float s, String projID) { - latitude = lat; - longitude = lon; - scale = s; - projectionID = projID; - this.addActionListener(this); - } - - /** - * Gets called when the NameFetcher successfully retrieves a name for the - * view. - * - * @param name new name for the button. - */ - public void setNameAndAdd(String name) { - this.setText(name); - GoToMenu.this.addView(this); - } - - public void actionPerformed(ActionEvent ae) { - if (map != null) { - Projection oldProj = map.getProjection(); - ProjectionFactory projFactory = map.getProjectionFactory(); - Class projClass = projFactory.getProjClassForName(projectionID); - - if (projClass == null) { - projClass = com.bbn.openmap.proj.Mercator.class; - } - - Projection newProj = projFactory.makeProjection(projClass, - new Point2D.Float(longitude, latitude), - scale, - oldProj.getWidth(), - oldProj.getHeight()); - - map.setProjection(newProj); - } - } - } - - /** - * Brings up a GUI to name a new view. - */ - public class NameFetcher extends JDialog implements ActionListener { - - private static final long serialVersionUID = 1L; - JTextField nameField; - JLabel label; - JButton closebutton, applybutton; - GoToButton notifyThis; - - public NameFetcher(GoToButton buttonToName) { - - notifyThis = buttonToName; - setTitle(i18n.get(GoToMenu.class, "addViewTitle", "Add View")); - JPanel palette = new JPanel(); - palette.setLayout(new BoxLayout(palette, BoxLayout.Y_AXIS)); - - JPanel namePanel = new JPanel(); - namePanel.setLayout(new FlowLayout()); - - label = new JLabel(i18n.get(GoToMenu.class, - "nameOfView", - "Name of View: ")); - nameField = new JTextField("", 20); - - namePanel.add(label); - namePanel.add(nameField); - - palette.add(namePanel); - - JPanel buttonPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - buttonPanel.setLayout(gridbag); - - applybutton = new JButton(i18n.get(GoToMenu.class, - "addView", - "Add View")); - applybutton.addActionListener(this); - gridbag.setConstraints(applybutton, c); - - closebutton = new JButton(i18n.get(GoToMenu.class, "close", "Close")); - closebutton.addActionListener(this); - c.gridx = GridBagConstraints.RELATIVE; - gridbag.setConstraints(closebutton, c); - - buttonPanel.add(applybutton); - buttonPanel.add(closebutton); - - palette.add(buttonPanel); - - this.getContentPane().add(palette); - this.pack(); - } - - public void actionPerformed(ActionEvent event) { - if (event.getSource() == applybutton) { - String newName = nameField.getText(); - if (newName != null && !(newName.length() == 0)) { - notifyThis.setNameAndAdd(newName); - } - } - this.setVisible(false); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/GridBagToolBar.java b/src/core/src/main/java/com/bbn/openmap/gui/GridBagToolBar.java deleted file mode 100644 index 4dd10c07a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/GridBagToolBar.java +++ /dev/null @@ -1,95 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/GridBagToolBar.java,v $ -// $RCSfile: GridBagToolBar.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/03/06 15:41:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; - -import javax.swing.BorderFactory; -import javax.swing.SwingConstants; - -import com.bbn.openmap.util.Debug; - -/** - * JToolBar with a GridBagLayout to have a more compressed look. - */ -public class GridBagToolBar extends javax.swing.JToolBar { - GridBagLayout gridbag; - GridBagConstraints c; - - public GridBagToolBar() { - gridbag = new GridBagLayout(); - c = new GridBagConstraints(); - setOrientation(SwingConstants.HORIZONTAL); - setLayout(gridbag); - setFloatable(false); - if (Debug.debugging("layout")) { - setBorder(BorderFactory.createLineBorder(Color.blue)); - } - } - - /** - */ - public void setOrientation(int orientation) { - super.setOrientation(orientation); - - // We need to remove and re-add the current components, they don't get - // their constraints redone to match the current orientation. - Component[] currentComps = getComponents(); - removeAll(); - - if (c == null) { - c = new GridBagConstraints(); - } - - if (getOrientation() == SwingConstants.HORIZONTAL) { - c.gridy = 0; - c.weightx = 0; - c.weighty = 1.0f; - c.fill = GridBagConstraints.VERTICAL; - c.anchor = GridBagConstraints.WEST; - } else { - c.gridwidth = GridBagConstraints.REMAINDER; - c.anchor = GridBagConstraints.NORTH; - c.weightx = 1.0f; - c.weighty = 0f; - c.fill = GridBagConstraints.HORIZONTAL; - } - - for (int i = 0; i < currentComps.length; i++) { - add(currentComps[i]); - } - - } - - public GridBagConstraints getConstraints() { - return c; - } - - public Component add(Component comp) { - gridbag.setConstraints(comp, c); - return super.add(comp); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/HelpMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/HelpMenu.java deleted file mode 100644 index cc3a4a39e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/HelpMenu.java +++ /dev/null @@ -1,32 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/HelpMenu.java,v $ -// $RCSfile: HelpMenu.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -/** - * This interface is to be used by objects added to the OpenMap - * BeanContext. An object implementing this interface would be added - * as HelpMenu in MenuBar. As of now, it will always be last menu in - * the MenuBar. - */ -public interface HelpMenu { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/HelpMenuItems.java b/src/core/src/main/java/com/bbn/openmap/gui/HelpMenuItems.java deleted file mode 100644 index 2842d54a9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/HelpMenuItems.java +++ /dev/null @@ -1,30 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/HelpMenuItems.java,v $ -// $RCSfile: HelpMenuItems.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -/** - * An object that has MenuItems which should be shown under HelpMenu - * should implement this interface. - */ -public interface HelpMenuItems extends MenuItems { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/HotwashPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/HotwashPanel.java deleted file mode 100755 index f107d1527..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/HotwashPanel.java +++ /dev/null @@ -1,184 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/darwars/ambush/aar/src/com/bbn/hotwash/gui/HotwashPanel.java,v $ -// $RCSfile: HotwashPanel.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:20 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.LayoutManager; -import java.util.logging.Logger; - -import javax.swing.JSplitPane; - -import com.bbn.openmap.util.Debug; - -/** - * The HotwashPanel is an OMComponentPanel that has a set of sliders built-in. - * By default, the HotwashPanel looks for MapPanelChildren and asks them for - * where they would prefer to be located (BorderLayout.NORTH, - * BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST). - */ -public class HotwashPanel extends OMComponentPanel { - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.HotwashPanel"); - protected JSplitPane leftSlider; - protected JSplitPane rightSlider; - protected JSplitPane bottomSlider; - - /** - * Create an empty HotwashPanel that creates its own empty PropertyHandler. - */ - public HotwashPanel() { - create(); - } - - /** - * The method that triggers setLayout() and createComponents() to be called. - * If you've told the HotwashPanel to delay creation, you should call this - * method to trigger the PropertyHandler to create components based on the - * contents of its properties. - */ - public void create() { - WindowSupport.setDefaultWindowSupportDisplayType(WindowSupport.Dlg.class); - setLayout(createLayoutManager()); - leftSlider = new JSplitPane(); - leftSlider.setBorder(null); - leftSlider.setResizeWeight(0); - leftSlider.setOneTouchExpandable(true); - - rightSlider = new JSplitPane(); - rightSlider.setBorder(null); - rightSlider.setResizeWeight(1); - rightSlider.setOneTouchExpandable(true); - - rightSlider.setLeftComponent(leftSlider); - rightSlider.setRightComponent(null); - - if (false) { - bottomSlider = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - bottomSlider.setBorder(null); - bottomSlider.setResizeWeight(1); - bottomSlider.setOneTouchExpandable(true); - leftSlider.setRightComponent(bottomSlider); - } - - super.add(rightSlider, BorderLayout.CENTER); - } - - public Component add(Component comp, String location) { - if (BorderLayout.EAST.equals(location)) { - rightSlider.setRightComponent(comp); - } else if (BorderLayout.WEST.equals(location)) { - leftSlider.setLeftComponent(comp); - } else if (BorderLayout.CENTER.equals(location)) { - if (bottomSlider != null) { - bottomSlider.setTopComponent(comp); - } else { - leftSlider.setRightComponent(comp); - } - } else if (BorderLayout.NORTH.equals(location) && bottomSlider != null) { - bottomSlider.setBottomComponent(comp); - } else { - super.add(comp, location); - } - return comp; - } - - /** - * The constructor calls this method that sets the LayoutManager for this - * HotwashPanel. It returns a BorderLayout by default, but this method can - * be overridden to change how the HotwashPanel places components. If you - * change what this method returns, you should also change how components - * are added in the findAndInit() method. - */ - protected LayoutManager createLayoutManager() { - return new BorderLayout(); - } - - // Map Component Methods: - // ////////////////////// - - /** - * The HotwashPanel looks for MapPanelChild components, finds out from them - * where they prefer to be placed, and adds them. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapPanelChild && someObj instanceof Component) { - String parentName = ((MapPanelChild) someObj).getParentName(); - String myName = getPropertyPrefix(); - - boolean makeMyChild = (myName != null && parentName != null && myName.equalsIgnoreCase(parentName)) - || (myName == null && parentName == null); - - if (makeMyChild) { - - logger.fine("HotwashPanel: adding " - + someObj.getClass().getName() + " to " - + ((MapPanelChild) someObj).getPreferredLocation()); - - MapPanelChild mpc = (MapPanelChild) someObj; - addMapPanelChild(mpc); - revalidate(); - } - } - - if (someObj instanceof MapPanel) { - add((Component) someObj, BorderLayout.CENTER); - } - - } - - /** - * Add a child to the HotwashPanel. - */ - protected void addMapPanelChild(MapPanelChild mpc) { - add((Component) mpc, mpc.getPreferredLocation()); - } - - /** - * The HotwashPanel looks for MapPanelChild components and removes them from - * iteself. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapPanelChild && someObj instanceof Component) { - if (Debug.debugging("basic")) { - Debug.output("HotwashPanel: removing " - + someObj.getClass().getName()); - } - remove((Component) someObj); - invalidate(); - } - - } - - public JSplitPane getBottomSlider() { - return bottomSlider; - } - - public JSplitPane getLeftSlider() { - return leftSlider; - } - - public JSplitPane getRightSlider() { - return rightSlider; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayerAddPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/LayerAddPanel.java deleted file mode 100644 index 8229d60a0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayerAddPanel.java +++ /dev/null @@ -1,486 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerAddPanel.java,v $ -// $RCSfile: LayerAddPanel.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/02/14 20:55:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTextField; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * Class to interactively add a Layer to the map. A LayerAddPanel utilizes the - * bean context mechanisms to keep up to date about the applications - * LayerHandler and PropertyHandler (see findAndInit method). A property is used - * to determine objects of which Layer subclasses can be instantiated (see - * static String layerTypes), for configuration of a layer-to-be an Inspector is - * invoked to inspect and configure a Layer object through the PropertyConsumer - * interface. - */ -public class LayerAddPanel extends OMComponentPanel implements Serializable, ActionListener { - - private static final long serialVersionUID = 1L; - - /** - * Constant field containing markers used in properties file for layers that - * can be created using the LayerAddPanel. - */ - public final static String layerTypes = "addableLayers"; - - /** - * Holds the PropertyHandler. - */ - protected PropertyHandler propertyHandler = null; - /** - * Holds the LayerHandler. - */ - protected LayerHandler layerHandler = null; - /** - * The list of available Layer classes. Is initiated with pretty names. - */ - protected JComboBox availableLayerClassNames = null; - /** - * Text field used to define new Layer class to create. - */ - protected JTextField classTextField = null; - /** The String to use as a prefix for the new Layer's properties. */ - protected JTextField prefixTextField = null; - /** Action command String for JButton. */ - protected final String configureActionCommand = "configureActionCommand"; - /** Contains Layer classes to be instantiated. */ - protected Map layerClasses = null; - /** The Inspector to handle the configuration of the new Layer. */ - protected Inspector inspector = null; - /** The layer to configure and add. */ - protected Object layer; - /** - * JButton to use to create new Layer. - */ - protected JButton configureButton; - - /** - * Creates the LayerPanel. - */ - public LayerAddPanel() { - super(); - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel()"); - } - inspector = new Inspector(); - inspector.addActionListener((ActionListener) this); - } - - /** - * Creates the LayerPanel. - * - * @param l the LayerHandler controlling the layers. - */ - public LayerAddPanel(PropertyHandler p, LayerHandler l) { - this(); - propertyHandler = p; - layerHandler = l; - } - - public void createLayerClasses(Layer[] layers) { - getLayerClasses().clear(); - - for (Layer l : layers) { - String name = l.getName(); - if (name == null) { - name = l.getClass().getName(); - int lastDotIndex = name.lastIndexOf('.'); - if (lastDotIndex >= 0) { - name = name.substring(lastDotIndex); - } - } - - addLayer(name, l.getClass().getName()); - } - } - - /** - * Produces a dialog panel to add a Layer, with the layers given. - */ - public void createPanel(Layer[] layers) { - createLayerClasses(layers); - createPanel(); - } - - public final static String DefaultLayerName = "Layer Name"; - - /** - * Produces a dialog panel to add a layer. If the layers haven't been - * manually added through createPanel(layers), then the PropertyHandler is - * consulted and the layer list is built from the layerTypes property. - */ - public void createPanel() { - removeAll(); - - configureButton = new JButton(i18n.get(LayerAddPanel.class, "configureButton", "Configure")); - configureButton.addActionListener(this); - configureButton.setActionCommand(configureActionCommand); - - String defaultLayerName = i18n.get(LayerAddPanel.class, "defaultLayerName", DefaultLayerName); - prefixTextField = new JTextField(defaultLayerName, 12); - - Set keys = getLayerClasses().keySet(); - String[] layerTypes = keys.toArray(new String[keys.size()]); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0; - c.gridwidth = GridBagConstraints.REMAINDER; - c.insets = new Insets(10, 10, 5, 10); - - if (layerTypes.length == 0) { - configureButton.setEnabled(false); - classTextField = new JTextField(30); - classTextField - .setToolTipText(i18n.get(LayerAddPanel.class, "classFieldToolTip", "Class name of layer to add")); - /* - * // Since there's no list provided, give a text box to let the - * user // specify which layer to create. String message = - * i18n.get(LayerAddPanel.class, "noLayersAvailableMessage", - * "No Layers available for creation."); JLabel label = new - * JLabel(message); - */ - - classTextField.setInputVerifier(new InputVerifier() { - - @Override - public boolean verify(JComponent input) { - JTextField tf = (JTextField) input; - String className = tf.getText(); - try { - ClassLoader.getSystemClassLoader().loadClass(className); - } catch (ClassNotFoundException cnfe) { - configureButton.setEnabled(false); - return false; - } - - configureButton.setEnabled(true); - return true; - } - - }); - - gridbag.setConstraints(classTextField, c); - add(classTextField); - - configureButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - String newClassName = (String) classTextField.getText(); - String prefix = prefixTextField.getText().trim(); - createLayer(newClassName, prefix); - } - }); - - } else { - availableLayerClassNames = new JComboBox<>(layerTypes); - gridbag.setConstraints(availableLayerClassNames, c); - add(availableLayerClassNames); - - configureButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - String prettyName = (String) availableLayerClassNames.getSelectedItem(); - String prefix = prefixTextField.getText().trim(); - - if (prettyName == null) { - return; - } - - String newClassName = layerClasses.get(prettyName); - - createLayer(newClassName, prefix); - } - }); - - } - - // Prefix/Name field - c.insets = new Insets(5, 10, 10, 10); - c.gridwidth = GridBagConstraints.RELATIVE; - gridbag.setConstraints(prefixTextField, c); - add(prefixTextField); - - // Add configure button - c.weightx = 0; - gridbag.setConstraints(configureButton, c); - add(configureButton); - - invalidate(); - } - - public Map getLayerClasses() { - if (layerClasses == null) { - layerClasses = new HashMap(); - } - return layerClasses; - } - - public void addLayer(String prettyName, String className) { - getLayerClasses().put(prettyName, className); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel.setProperties()"); - } - getLayerTypes(props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - int layerNumber = 1; - if (layerClasses != null) { - StringBuffer layerList = new StringBuffer(); - - for (String prettyName : layerClasses.keySet()) { - String className = (String) layerClasses.get(prettyName); - String markerName = "l" + (layerNumber++); - layerList.append(markerName).append(" "); - props.put(markerName + ".prettyName", prettyName); - props.put(markerName + ".class", className); - } - props.put(Environment.OpenMapPrefix + "." + layerTypes, layerList.toString()); - } - - return props; - } - - /** - * Gets Layer information from PropertyHandler. These layers are defined in - * the application properties under the openmap.layerTypes property. - * - * @return Map of prettyName String keys with classname values. Empty - * Map if no layers are available. - */ - protected Map getLayerTypes() { - return getLayerTypes(null); - } - - /** - * Gets Layer information from the given properties. These layers are - * defined in the application properties under the openmap.layerTypes - * property. If the given properties are null, then the property handler, if - * found, will be consulted directly. - * - * @return Map of prettyName String keys with classname values. Empty - * Map if no layers are available. - */ - protected Map getLayerTypes(Properties props) { - Map layerHash = getLayerClasses(); - layerHash.clear(); - - if (props == null) { - if (propertyHandler != null) { - props = propertyHandler.getProperties(); - } else { - return layerHash; - } - } - - String prefix = Environment.OpenMapPrefix; - String addableList = props.getProperty(prefix + "." + layerTypes); - - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel: " + addableList); - } - - List layerClassList = PropUtils.parseSpacedMarkers(addableList); - - if (layerClassList == null) { - return layerHash; - } - - // debug info: available layers - int unNamedCount = 1; - for (String layerClassString : layerClassList) { - String className = props.getProperty(layerClassString + ".class"); - String prettyName = props.getProperty(layerClassString + ".prettyName"); - - if (prettyName == null) { - prettyName = "Layer " + (unNamedCount++); - } - - if (className != null) { - if (Debug.debugging("addable")) { - Debug.output(" adding " + className + ", " + className); - } - layerHash.put(prettyName, className); - } - } - return layerHash; - } - - /** - * Create a layer given a class name and property prefix to be used as a - * name. - * - * @param className class of layer to create. - * @param prefix pretty name and property prefix. - */ - protected void createLayer(String className, String prefix) { - Object obj = ComponentFactory.create(className); - - if (obj instanceof Layer) { - layer = (Layer) obj; - // Set the pretty name to what the user chose. - ((Layer) layer).setName(prefix); - - prefixTextField.setText(""); - if (classTextField != null) { - classTextField.setText(""); - } - - WindowSupport ws = getWindowSupport(); - if (ws != null) { - ws.cleanUp(); - } - } - - if (obj instanceof PropertyConsumer) { - // Set the prefix to a modified version of the pretty name. - prefix = propertyHandler.getUniquePrefix(prefix); - ((PropertyConsumer) obj).setPropertyPrefix(prefix); - inspector.inspectPropertyConsumer((PropertyConsumer) obj); - } - } - - /** - * Method associated with the ActionListener interface. - */ - public void actionPerformed(ActionEvent e) { - - if (e.getActionCommand() == Inspector.doneCommand) { - // the confirmation button of the Inspector panel was - // pressed - // find the beancontext and add the layer at hand (var. - // layer) - if (layer != null && layerHandler != null) { - if (layer instanceof Layer) { - // Let's add it on top, so the user can find it - // easier, instead of adding it to the bottom and - // having it lost behind some other layers. - layerHandler.addLayer((Layer) layer, 0); - } - prefixTextField.setText(DefaultLayerName); - } else if (layerHandler != null) { - String message = i18n.get(LayerAddPanel.class, "noLayerHandlerMessage", - "Layer Handler not found.\nCan't find anything to add the layer to."); - JOptionPane.showMessageDialog(this, message); - } else { - String message = i18n.get(LayerAddPanel.class, "noLayerCreatedMessage", "No Layer instantiated."); - JOptionPane.showMessageDialog(this, message); - } - } else if (e.getActionCommand() == Inspector.cancelCommand) { - if (layer != null && propertyHandler != null) { - propertyHandler.removeUsedPrefix(((PropertyConsumer) layer).getPropertyPrefix()); - } - } - } - - /** - * Show the panel in a JFrame. - */ - public void showPanel() { - createPanel(); - prefixTextField.setText(DefaultLayerName); - - WindowSupport ws = getWindowSupport(); - - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - if (ws == null) { - ws = new WindowSupport(this, i18n.get(LayerAddPanel.class, "title", "Add Layer")); - setWindowSupport(ws); - } - - ws.displayInWindow(frame, -1, -1, -1, -1); - } - - /** - * Looks for PropertyHandler and LayerHandler. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof PropertyHandler) { - // do the initializing that need to be done here - Debug.message("layerspanel", "LayerAddPanel found a LayerHandler"); - propertyHandler = (PropertyHandler) someObj; - } - if (someObj instanceof LayerHandler) { - layerHandler = (LayerHandler) someObj; - } - } - - /** - * Disconnect from any objects that are removed from MapHandler. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof PropertyHandler && propertyHandler == someObj) { - // do the initializing that need to be done here - Debug.message("addable", "LayerAddPanel removing PropertyHandler"); - propertyHandler = null; - } - if (someObj instanceof LayerHandler && someObj == layerHandler) { - Debug.message("addable", "LayerAddPanel removing LayerHandler"); - layerHandler = null; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayerControlButtonPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/LayerControlButtonPanel.java deleted file mode 100644 index c97f34767..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayerControlButtonPanel.java +++ /dev/null @@ -1,559 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerControlButtonPanel.java,v $ -// $RCSfile: LayerControlButtonPanel.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/08/09 19:14:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.net.URL; -import java.util.Properties; - -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.OptionPropertyEditor; -import com.bbn.openmap.util.propertyEditor.OrientationPropertyEditor; - -/** - * A OMComponentPanel that provides controls to manupulate layer order - * in the LayersPanel, and to provide add layer and delete layer - * buttons. This panel can be embedded into the LayersPanel, or it can - * be positioned somewhere else in the application. The LayersPanel - * can be set to create one of these itself, in which case it will be - * embedded. If you don't want an embedded version, create one and add - * it to the MapHandler, it will hook up to the LayersPanel when it - * finds it. The LayerPanes, LayersPanel and LayerControlButtonPanel - * communicate with each other using PropertyChangeEvents. The - * LayerPanes notify the LayersPanelwhen one of them is selected, and - * that event gets passed to this panel. When a button on this panel - * is pressed, it fires a PropertyChangeEvent with the layer and - * command to take to all its PropertyChangeListeners. - *

- * - * The LayerControlButtonPanel takes these properties: - * - *

- * 
- *  
- *   
- *    
- *    
- *    
- *    
- *     # Direction buttons are laid out, vertical or horizontal (vertical is
- *     default).
- *     orientation=vertical
- *     # Flag on whether to insert buttons onto LayersPanel (true by default).
- *     embedded=true
- *     # Configuration setting when embedding into LayersPanel (WEST,
- *     # NORTH, EAST, SOUTH, NORTH_SOUTH) NORTH_SOUTH puts up button above
- *     # list, down button below list.
- *     configuration=WEST
- *     # Flag to put button that lets the user delete layers (true by default).
- *     delete=true
- *     # Flag to put button that lets the user add layers, if the
- *     # LayersAddPanel is discovered in the MapHandler (true by default)
- *     add=true
- *    
- *    
- *    
- *     
- *    
- *   
- *  
- * 
- */ -public class LayerControlButtonPanel extends OMComponentPanel implements - ActionListener, PropertyChangeListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - // Images - protected static transient URL urlup; - protected static transient ImageIcon upgif; - protected static transient URL urlupc; - protected static transient ImageIcon upclickedgif; - protected static transient URL urltop; - protected static transient ImageIcon topgif; - protected static transient URL urltopc; - protected static transient ImageIcon topclickedgif; - protected static transient URL urldown; - protected static transient ImageIcon downgif; - protected static transient URL urldownc; - protected static transient ImageIcon downclickedgif; - protected static transient URL urlbottom; - protected static transient ImageIcon bottomgif; - protected static transient URL urlbottomc; - protected static transient ImageIcon bottomclickedgif; - protected static transient URL urldelete; - protected static transient ImageIcon deletegif; - protected static transient URL urldeletec; - protected static transient ImageIcon deleteclickedgif; - protected static transient URL urladd; - protected static transient ImageIcon addgif; - protected static transient URL urladdc; - protected static transient ImageIcon addclickedgif; - - /** - * Static default initializations. - */ - static { - urlup = LayersPanel.class.getResource("Up.gif"); - upgif = new ImageIcon(urlup, "Up"); - - urlupc = LayersPanel.class.getResource("Up.gif"); - upclickedgif = new ImageIcon(urlupc, "Up (clicked)"); - - urltop = LayersPanel.class.getResource("DoubleUp.gif"); - topgif = new ImageIcon(urltop, "Top"); - - urltopc = LayersPanel.class.getResource("DoubleUp.gif"); - topclickedgif = new ImageIcon(urltopc, "Top (clicked)"); - - urldown = LayersPanel.class.getResource("Down.gif"); - downgif = new ImageIcon(urldown, "Down"); - - urldownc = LayersPanel.class.getResource("Down.gif"); - downclickedgif = new ImageIcon(urldownc, "Down (clicked)"); - - urlbottom = LayersPanel.class.getResource("DoubleDown.gif"); - bottomgif = new ImageIcon(urlbottom, "Bottom"); - - urlbottomc = LayersPanel.class.getResource("DoubleDown.gif"); - bottomclickedgif = new ImageIcon(urlbottomc, "Bottom (clicked)"); - - urldelete = LayersPanel.class.getResource("DeleteLayer.gif"); - deletegif = new ImageIcon(urldelete, "Delete"); - - urldeletec = LayersPanel.class.getResource("DeleteLayer.gif"); - deleteclickedgif = new ImageIcon(urldeletec, "Delete (clicked)"); - - urladd = LayersPanel.class.getResource("AddLayer.gif"); - addgif = new ImageIcon(urladd, "Add"); - - urladdc = LayersPanel.class.getResource("AddLayer.gif"); - addclickedgif = new ImageIcon(urladdc, "Add (clicked)"); - } - - protected JButton add = null; - protected JButton delete = null; - protected JButton top = null; - protected JButton up = null; - protected JButton down = null; - protected JButton bottom = null; - - protected LayerAddPanel layerAddPanel; - - public final static String OrientationProperty = "orientation"; - public final static String ConfigurationProperty = "configuration"; - public final static String EmbeddedProperty = "embedded"; - public final static String DeleteLayersProperty = "delete"; - public final static String AddLayersProperty = "add"; - - public final static String HORIZONTAL_CONFIG = OrientationPropertyEditor.HORIZONTAL; - public final static String VERTICAL_CONFIG = OrientationPropertyEditor.VERTICAL; - - public final static String WEST_CONFIG = "WEST"; - public final static String EAST_CONFIG = "EAST"; - public final static String NORTH_CONFIG = "NORTH"; - public final static String SOUTH_CONFIG = "SOUTH"; - public final static String NORTH_SOUTH_CONFIG = "NORTH_SOUTH"; - public final static String DefaultConfiguration = WEST_CONFIG; - - protected int boxOrientation = BoxLayout.Y_AXIS; // BoxLayout.X_AXIS - protected String configuration = DefaultConfiguration; - protected boolean embedded = true; - protected boolean deleteLayers = true; - protected boolean addLayers = true; - - public LayerControlButtonPanel() { - super(); - createInterface(); - } - - public LayerControlButtonPanel(LayersPanel panel) { - this(); - setLayersPanel(panel); - } - - public void removeLayersPanel(LayersPanel panel) { - if (panel != null) { - panel.setControls(null); - panel.removePropertyChangeListener(this); - removePropertyChangeListener(panel); - - if (embedded) { - if (configuration.equalsIgnoreCase(NORTH_SOUTH_CONFIG)) { - panel.remove(up); - panel.remove(down); - } else { - panel.remove(this); - } - } - } - } - - /** - * Sets this panel to control the LayersPanel. If you want to - * extend this class and change how the buttons are displayed in - * the LayersPanel, change this method. - */ - public void setLayersPanel(LayersPanel panel) { - if (panel != null) { - // Just in case it's already been added. - panel.removePropertyChangeListener(this); - - panel.addPropertyChangeListener(this); - addPropertyChangeListener(panel); - - if (embedded) { - createInterface(); // again, reset for new config - // values - - setLayout(new BoxLayout(this, boxOrientation)); - - if (panel.getLayout() instanceof BorderLayout) { - if (configuration.equalsIgnoreCase(WEST_CONFIG)) { - panel.add(this, BorderLayout.WEST); - } else if (configuration.equalsIgnoreCase(EAST_CONFIG)) { - panel.add(this, BorderLayout.EAST); - } else if (configuration.equalsIgnoreCase(NORTH_CONFIG)) { - panel.add(this, BorderLayout.NORTH); - } else if (configuration.equalsIgnoreCase(SOUTH_CONFIG)) { - panel.add(this, BorderLayout.SOUTH); - } else if (configuration.equalsIgnoreCase(NORTH_SOUTH_CONFIG)) { - panel.add(up, BorderLayout.NORTH); - panel.add(down, BorderLayout.SOUTH); - } - } else { - panel.add(this); - } - } - // Let the LayersPanel know who is controlling it. - //panel.setControls(this); - } - } - - protected void createInterface() { - removeAll(); - - setAlignmentX(LEFT_ALIGNMENT); - setAlignmentY(CENTER_ALIGNMENT); - setLayout(new BoxLayout(this, boxOrientation)); - - top = new JButton(topgif); - top.setActionCommand(LayersPanel.LayerTopCmd); - top.setPressedIcon(topclickedgif); - top.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "moveLayerToTop", - "Move selected layer to top")); - top.addActionListener(this); - add(top); - - up = new JButton(upgif); - up.setActionCommand(LayersPanel.LayerUpCmd); - up.setPressedIcon(upclickedgif); - up.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "moveLayerUpOne", - "Move selected layer up one")); - up.addActionListener(this); - add(up); - - down = new JButton(downgif); - down.setPressedIcon(downclickedgif); - down.setActionCommand(LayersPanel.LayerDownCmd); - down.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "moveLayerDownOne", - "Move selected layer down one")); - down.addActionListener(this); - add(down); - - bottom = new JButton(bottomgif); - bottom.setPressedIcon(bottomclickedgif); - bottom.setActionCommand(LayersPanel.LayerBottomCmd); - bottom.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "moveLayerToBottom", - "Move selected layer to bottom")); - bottom.addActionListener(this); - add(bottom); - - if (deleteLayers) { - JLabel blank = new JLabel(" "); - add(blank); - - delete = new JButton(deletegif); - delete.setActionCommand(LayersPanel.LayerRemoveCmd); - delete.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "removeLayer", - "Remove selected layer")); - delete.addActionListener(this); - delete.setEnabled(false); - add(delete); - } - - if (addLayers && add != null) { - add(add); - } - } - - /** - * Set the panel that brings up an interface to dynamically add - * layers. - */ - public void setLayerAddPanel(LayerAddPanel lap) { - layerAddPanel = lap; - - if (layerAddPanel != null) { - add = new JButton(addgif); - add.setActionCommand(LayersPanel.LayerAddCmd); - add.setToolTipText(i18n.get(LayerControlButtonPanel.class, - "addLayer", - "Add a layer")); - add.addActionListener(this); - if (addLayers) { - this.add(add); - } - } else if (add != null) { - this.remove(add); - } - - } - - /** - * Get the panel interface to dynamically add layers. - */ - public LayerAddPanel getLayerAddPanel() { - return layerAddPanel; - } - - /** - * Method associated with the ActionListener interface. This - * method listens for action events meant to change the order of - * the layers, as fired by the layer order buttons. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - - String command = e.getActionCommand(); - - if (Debug.debugging("layerbuttons")) { - Debug.output("LayersPanel.actionPerformed(): " + command); - } - - if (command == LayersPanel.LayerTopCmd - || command == LayersPanel.LayerBottomCmd - || command == LayersPanel.LayerUpCmd - || command == LayersPanel.LayerDownCmd - || command == LayersPanel.LayerRemoveCmd) { - if (selected != null) { - if (Debug.debugging("layercontrol")) { - Debug.output("LayerControlButtonPanel: button firing " - + command + " event for " + selected.getName()); - } - firePropertyChange(command, null, selected); - } else { - if (Debug.debugging("layercontrol")) { - Debug.output("LayerControlButtonPanel: button firing " - + command + " event with no layer selected"); - } - } - - if (command == LayersPanel.LayerRemoveCmd) { - // We are going to be deleting the layer we've selected. - selected = null; - delete.setEnabled(false); - } - - } else if (command.equals(LayersPanel.LayerAddCmd)) { - if (layerAddPanel != null) { - layerAddPanel.showPanel(); - } - } - } - - protected Layer selected = null; - - public void propertyChange(PropertyChangeEvent pce) { - String command = pce.getPropertyName(); - Object obj = pce.getNewValue(); - if (Debug.debugging("layercontrol")) { - Debug.output("LayerControlButtonPanel: receiving PropertyChangeEvent " - + pce.getPropertyName()); - } - - if (command == LayersPanel.LayerSelectedCmd && obj instanceof Layer) { - - selected = (Layer) obj; - - delete.setEnabled(selected.isRemovable()); - - if (Debug.debugging("layercontrol")) { - Debug.output("LayerControlButtonPanel: got notification that layer is selected: " - + selected.getName()); - } - } else if (command == LayersPanel.LayerDeselectedCmd && selected == obj) { - selected = null; - delete.setEnabled(false); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof LayerAddPanel) { - setLayerAddPanel((LayerAddPanel) someObj); - } - - if (someObj instanceof LayersPanel) { - setLayersPanel((LayersPanel) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerAddPanel) { - if (getLayerAddPanel() == someObj) { - setLayerAddPanel(null); - } - } - - if (someObj instanceof LayersPanel) { - removeLayersPanel((LayersPanel) someObj); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - configuration = props.getProperty(prefix + ConfigurationProperty); - - if (configuration == null) { - configuration = DefaultConfiguration; - } - - embedded = PropUtils.booleanFromProperties(props, prefix - + EmbeddedProperty, embedded); - deleteLayers = PropUtils.booleanFromProperties(props, prefix - + DeleteLayersProperty, deleteLayers); - addLayers = PropUtils.booleanFromProperties(props, prefix - + AddLayersProperty, addLayers); - - String orient = props.getProperty(prefix + OrientationProperty); - if (orient != null - && (orient.equalsIgnoreCase(HORIZONTAL_CONFIG) || (orient.equalsIgnoreCase("false")))) { - boxOrientation = BoxLayout.X_AXIS; - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ConfigurationProperty, configuration); - props.put(prefix + OrientationProperty, - (boxOrientation == BoxLayout.X_AXIS ? HORIZONTAL_CONFIG - : VERTICAL_CONFIG)); - props.put(prefix + EmbeddedProperty, new Boolean(embedded).toString()); - props.put(prefix + DeleteLayersProperty, - new Boolean(deleteLayers).toString()); - props.put(prefix + AddLayersProperty, new Boolean(addLayers).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String interString = i18n.get(LayerControlButtonPanel.class, - ConfigurationProperty, - I18n.TOOLTIP, - "Pre-Defined Configuration String (WEST, EAST, NORTH, SOUTH, NORTH_SOUTH)."); - props.put(ConfigurationProperty, interString); - props.put(ConfigurationProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - props.put(ConfigurationProperty + OptionPropertyEditor.ScopedOptionsProperty, - "west east north south northsouth"); - props.put(ConfigurationProperty + ".west", "WEST"); - props.put(ConfigurationProperty + ".east", "EAST"); - props.put(ConfigurationProperty + ".north", "NORTH"); - props.put(ConfigurationProperty + ".south", "SOUTH"); - props.put(ConfigurationProperty + ".northsouth", "NORTH_SOUTH"); - interString = i18n.get(LayerControlButtonPanel.class, ConfigurationProperty, "Configuration"); - props.put(ConfigurationProperty + LabelEditorProperty, interString); - - interString = i18n.get(LayerControlButtonPanel.class, - ConfigurationProperty, - I18n.TOOLTIP, - "Layout orientation for buttons."); - props.put(OrientationProperty, interString); - props.put(OrientationProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.OrientationPropertyEditor"); - interString = i18n.get(LayerControlButtonPanel.class, OrientationProperty, "Orientation"); - props.put(OrientationProperty + LabelEditorProperty, interString); - - interString = i18n.get(LayerControlButtonPanel.class, - EmbeddedProperty, - I18n.TOOLTIP, - "Insert itself into Layers panel."); - props.put(EmbeddedProperty, interString); - props.put(EmbeddedProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(LayerControlButtonPanel.class, EmbeddedProperty, "Embedded"); - props.put(EmbeddedProperty + LabelEditorProperty, interString); - - interString = i18n.get(LayerControlButtonPanel.class, - DeleteLayersProperty, - I18n.TOOLTIP, - "Include button to delete layers."); - props.put(DeleteLayersProperty, interString); - props.put(DeleteLayersProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(LayerControlButtonPanel.class, DeleteLayersProperty, "Add Remove Button"); - props.put(DeleteLayersProperty + LabelEditorProperty, interString); - - interString = i18n.get(LayerControlButtonPanel.class, - AddLayersProperty, - I18n.TOOLTIP, - "Include button to add layers."); - props.put(AddLayersProperty, interString); - props.put(AddLayersProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(LayerControlButtonPanel.class, AddLayersProperty, "Add Create Button"); - props.put(AddLayersProperty + LabelEditorProperty, interString); - - props.put(initPropertiesProperty, ConfigurationProperty + " " + - EmbeddedProperty + " " + - OrientationProperty + " " + - AddLayersProperty + " " + - DeleteLayersProperty); - - return props; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayerPane.java b/src/core/src/main/java/com/bbn/openmap/gui/LayerPane.java deleted file mode 100644 index d0f6525fc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayerPane.java +++ /dev/null @@ -1,468 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerPane.java,v $ -// $RCSfile: LayerPane.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/06/13 21:33:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.io.Serializable; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.util.I18n; - -/** - * A LayerPane is a single instance of how a layer represented in the - * LayersPanel. It contains three widgets: an on/off button; a palette button; - * and a toggle button with the layer name. - *

- */ -@SuppressWarnings("serial") -public class LayerPane extends JPanel implements Serializable, ActionListener, ComponentListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.LayerPane"); - - protected transient AbstractButton onoffButton; - protected transient AbstractButton paletteButton; - protected transient JToggleButton layerName; - protected transient boolean selected; - protected transient Layer layer; - - protected transient LayerHandler layerHandler; - - // the icons - protected static transient URL url1; - protected static transient ImageIcon paletteIcon; - protected static transient URL url2; - protected static transient ImageIcon paletteOnIcon; - protected static transient URL url3; - protected static transient ImageIcon layerOnIcon; - protected static transient URL url4; - protected static transient ImageIcon layerOffIcon; - - public transient final static String showPaletteCmd = "showPalette"; - public transient final static String toggleLayerCmd = "toggleLayerCmd"; - - protected Color offColor; - protected Color onColor = new Color(0xFF0066CC); - - protected I18n i18n = Environment.getI18n(); - - // default initializations - static { - url1 = LayerPane.class.getResource("PaletteOff.gif"); - paletteIcon = new ImageIcon(url1, "Palette"); - url2 = LayerPane.class.getResource("PaletteOn.gif"); - paletteOnIcon = new ImageIcon(url2, "Palette on"); - - url3 = LayerPane.class.getResource("BulbOn.gif"); - layerOnIcon = new ImageIcon(url3, "Layer selected"); - url4 = LayerPane.class.getResource("BulbOff.gif"); - layerOffIcon = new ImageIcon(url4, "Layer not selected"); - } - - /** - * @param layer the layer to be represented by the pane. - * @param bg the buttongroup for the layer - * @param layerHandler the LayerHandler that contains information about the - * Layers. - */ - public LayerPane(Layer layer, LayerHandler layerHandler, ButtonGroup bg) { - super(); - this.layer = layer; - setLayerHandler(layerHandler); - createGUI(bg); - layer.addComponentListener(this); - } - - protected void createGUI(ButtonGroup bg) { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - layerName = new JToggleButton(layer.getName()); - layerName.setBorderPainted(false); - layerName.addActionListener(this); - - offColor = layerName.getBackground(); - Object layerDescription = layer.getAttribute(Layer.ToolTipProperty); - if (layerDescription == null) { - layerDescription = i18n.get(LayerPane.class, "layerName.tooltip", "Click to select layer"); - } - layerName.setToolTipText(layerDescription.toString()); - layerName.setHorizontalAlignment(SwingConstants.LEFT); - bg.add(layerName); - - c.gridy = 0; - c.gridx = GridBagConstraints.RELATIVE; - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(0, 0, 0, 0); - - onoffButton = getOnOffButton(); - gridbag.setConstraints(onoffButton, c); - add(onoffButton); - - paletteButton = getPaletteButton(); - gridbag.setConstraints(paletteButton, c); - add(paletteButton); - - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(layerName, c); - add(layerName); - } - - /** - * Simply creates the AbstractButton object that turns the layer on/off. - * Override this if you want to change the kind of button used. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton createOnOffButton() { - return new JCheckBox(layerOffIcon); - } - - /** - * Calls createOnOFfButton to create the button, and then adds all the - * behavior settings to the button. Override this if you want to change - * everything about the button. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton getOnOffButton() { - AbstractButton onoffButton = createOnOffButton(); - onoffButton.setSelectedIcon(layerOnIcon); - onoffButton.setActionCommand(toggleLayerCmd); - onoffButton.addActionListener(this); - - String interString = i18n.get(LayerPane.class, "onoffButton.tooltip", "Turn \"{0}\" layer on/off", - layer.getName()); - onoffButton.setToolTipText(interString); - // Determine if this layer has already been activated - onoffButton.setSelected(layer.isVisible()); - onoffButton.setEnabled(layer.isRemovable()); - return onoffButton; - } - - /** - * Simply creates the AbstractButton object that turns the layer palette - * on/off. Override this if you want to change the kind of button used. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton createPaletteButton() { - return new JCheckBox(paletteIcon); - } - - /** - * Calls createPaletteButton to create the button, and then adds all the - * behavior settings to the button. Override this if you want to change - * everything about the button. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton getPaletteButton() { - AbstractButton paletteButton = createPaletteButton(); - paletteButton.setSelectedIcon(paletteOnIcon); - paletteButton.setBorderPainted(false); - - String interString; - if (!layer.hasGUI()) { - interString = i18n.get(LayerPane.class, "paletteButton.noPaletteAvailable.tooltip", - "No tools available for \"{0}\" layer", layer.getName()); - paletteButton.setEnabled(false); - } else { - interString = i18n.get(LayerPane.class, "paletteButton.paletteAvailable.tooltip", - "Display tools for \"{0}\" layer", layer.getName()); - } - paletteButton.setToolTipText(interString); - - paletteButton.setActionCommand(showPaletteCmd); - paletteButton.addActionListener(this); - return paletteButton; - } - - /** - * Used for the background LayerPanel marker. - */ - protected LayerPane(String title) { - super(); - // prevent null pointers somewhere... - this.layer = com.bbn.openmap.layer.SinkLayer.getSharedInstance(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - JSeparator sep = new JSeparator(); - sep.setToolTipText(title); - - c.anchor = GridBagConstraints.WEST; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(sep, c); - add(sep); - } - - public void setLayerHandler(LayerHandler in_layerHandler) { - layerHandler = in_layerHandler; - } - - /** - * @return LayerHandler if it has been found in the MapHandler or set. - */ - protected LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Same as cleanup, except the layer name toggle button gets removed from - * the given button group. - */ - public void cleanup(ButtonGroup bg) { - if (bg != null) { - bg.remove(layerName); - } - cleanup(); - } - - /** - * LayerPane disconnects from listeners, nulls out components, shuts down - * layer palette. - */ - public void cleanup() { - layerName.setSelected(false); - - if (layer != null) { - this.layer.setPaletteVisible(false); - this.layer.removeComponentListener(this); - } - if (onoffButton != null) { - onoffButton.removeActionListener(this); - } - if (paletteButton != null) { - paletteButton.removeActionListener(this); - } - layerName = null; - this.layer = null; - this.layerHandler = null; - this.removeAll(); - } - - public Dimension getPreferredSize() { - return new Dimension(200, 32); - } - - public Dimension getMinimumSize() { - return new Dimension(100, 20); - } - - /** - * @return whether the layer is on - */ - public boolean isLayerOn() { - return onoffButton.isSelected(); - } - - /** - * Turns the button on or off - */ - public void setLayerOn(boolean value) { - onoffButton.setSelected(value); - } - - /** - * @return whether the palette for this layer is on - */ - public boolean isPaletteOn() { - return paletteButton.isSelected(); - } - - /** - * Turns the palette button on or off - */ - public void setPaletteOn(boolean value) { - paletteButton.setSelected(value); - } - - /** - * @return the status of the layerName toggle button - */ - public boolean isSelected() { - return layerName.isSelected(); - } - - /** - * Highlights/de-highlights the panel border. - */ - public void setSelected(boolean select) { - String command = select ? LayersPanel.LayerSelectedCmd : LayersPanel.LayerDeselectedCmd; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerPane for " + getLayer().getName() + " " + command + ", firing event"); - } - - if (select) { - setBorder(BorderFactory.createLoweredBevelBorder()); - } else { - setBorder(null); - } - - firePropertyChange(command, null, getLayer()); - } - - /** - * @return the layer represented by this LayerPane - */ - public Layer getLayer() { - return layer; - } - - /** - * Tell the pane to check with the layer to get the current layer name for - * it's label. - */ - public void updateLayerLabel() { - layerName.setText(getLayer().getName()); - } - - protected void showPalette() { - layer.showPalette(); - // This is needed in case the palette button is pressed, and the palette - // is already visible. Without this, the button toggles off even though - // the palette remains up. - setPaletteOn(true); - } - - protected void hidePalette() { - layer.hidePalette(); - } - - /** - * ActionListener interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - - if (e.getSource().equals(paletteButton)) { - layerName.doClick(); - showPalette(); - } else if (e.getSource().equals(onoffButton)) { - layerName.doClick(); - // layer is selected, add it to or remove it from map - if (layerHandler != null) { - logger.fine("LayerPane|actionPerformed calling layerHandler.turnLayerOn()"); - layerHandler.turnLayerOn(onoffButton.isSelected(), layer); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + layer.getName() + (layer.isVisible() ? " is visible." : " is NOT visible")); - } - } else if (e.getSource().equals(layerName)) { - setSelected(layerName.isSelected()); - } - } - - /** - * Invoked when component has been resized. - */ - public void componentResized(ComponentEvent e) { - } - - /** - * Invoked when component has been moved. - */ - public void componentMoved(ComponentEvent e) { - } - - /** - * Invoked when component has been shown. - */ - public void componentShown(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer pane for " + layer.getName() + " receiving componentShown event"); - } - - Component comp = e.getComponent(); - if (comp == null) { - } else if (comp == layer) { - if (isLayerOn() != true) { - setLayerOn(true); - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now visible."); - } - } - } else if (comp == layer.getPalette()) { - setPaletteOn(true); - } - } - - /** - * Invoked when component has been hidden. - */ - public void componentHidden(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer pane for " + layer.getName() + " receiving componentHidden event"); - } - Component comp = e.getComponent(); - - if (comp == layer) { - if (isLayerOn() != false) { - setLayerOn(false); - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now hidden."); - } - } - } else if (comp == layer.getPalette()) { - setPaletteOn(false); - } else if (comp == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now hidden."); - } - } - } - - public static LayerPane getBackgroundLayerSeparator(String title) { - return new LayerPane(title); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayerStatusPane.java b/src/core/src/main/java/com/bbn/openmap/gui/LayerStatusPane.java deleted file mode 100644 index f30a1b043..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayerStatusPane.java +++ /dev/null @@ -1,92 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerStatusPane.java,v $ -// $RCSfile: LayerStatusPane.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/02/11 22:30:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.net.URL; - -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; - -/** - * A LayerStatusPane is an extension to the LayerPane, where it is a - * listener to the Layer and shows the layer status in the GUI. - */ -public class LayerStatusPane extends LayerPane implements LayerStatusListener { - - // the icons - protected static transient ImageIcon layerWorking; - protected static transient ImageIcon layerDone; - - // default initializations, extended from LayerPane... - static { - URL working = LayerStatusPane.class.getResource("BulbWorking.gif"); - layerWorking = new ImageIcon(working, "layer working"); - URL done = LayerStatusPane.class.getResource("BulbDone.gif"); - layerDone = new ImageIcon(done, "layer displayed"); - } - - /** - * @param layer the layer to be represented by the pane. - * @param bg the buttongroup for the layer - * @param layerHandler the LayerHandler that contains information - * about the Layers. - */ - public LayerStatusPane(Layer layer, LayerHandler layerHandler, - ButtonGroup bg) { - super(layer, layerHandler, bg); - getLayer().addLayerStatusListener(this); - } - - protected LayerStatusPane(String title) { - super(title); - } - - /** - * Update the Layer status. LayerStatusListener interface method. - * - * @param evt LayerStatusEvent - */ - public void updateLayerStatus(LayerStatusEvent evt) { - switch (evt.getStatus()) { - case LayerStatusEvent.START_WORKING: - onoffButton.setSelectedIcon(layerWorking); - break; - case LayerStatusEvent.FINISH_WORKING: - onoffButton.setSelectedIcon(layerDone); - break; - } - } - - public void cleanup() { - Layer l = getLayer(); - if (l != null) { - l.removeLayerStatusListener(this); - } - super.cleanup(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayersMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/LayersMenu.java deleted file mode 100644 index 170e07045..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayersMenu.java +++ /dev/null @@ -1,611 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayersMenu.java,v $ -// $RCSfile: LayersMenu.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.beans.PropertyVetoException; -import java.io.Serializable; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenuItem; -import javax.swing.JSeparator; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.util.Debug; - -/** - * The LayersMenu is a JMenu which is a list of the layers of the map. This - * LayersMenu expects to work with a LayerHandler containing all the possible - * layers that may be added to the map. This list defaults to being checkbuttons - * which add and remove the named layer to/from the Map. You can also use an - * instance of this object to show/hide layer palettes. - *

- * - * This object is interested in contacting a LayerHandler to find out all the - * layers available, and optionally, a LayersPanel in order to provide a menu - * item that will call up the GUI for the LayersPanel. If this LayersMenu is a - * member of a BeanContext, it expects that only one of each of these objects - * will be added, but if more than one per type is added, the last one added to - * be BeanContext will be the one hooked up to this LayersMenu. - */ -@SuppressWarnings("serial") -public class LayersMenu extends AbstractOpenMapMenu implements Serializable, LayerListener { - - /** - * Static value to set this menu to control layer visibility. - */ - public static final transient int LAYERS_ON_OFF = 1; - /** - * Static value to set this menu to control layer palette visibility. - */ - public static final transient int PALETTES_ON_OFF = 2; - /** - * The flag setting the behavior of the menu, whether it controls the layers - * or the layers palettes. - */ - protected int menuType = -1; - /** - * The LayerHandler to listen to for layers available for the map. - */ - protected transient LayerHandler layerHandler; - /** - * Used by the BeanContext methods to insure that the component we - * disconnect the edit button from is the same one being removed from the - * BeanContext. - */ - protected transient LayersPanel layersPanel; - /** A button on the bottom of the menu to bring up the layersPanel. */ - protected transient JMenuItem edit = null; - /** The default edit button title. */ - public final static String defaultEditLayersButtonTitle = "Edit Layers..."; - /** The actual edit button title. */ - protected transient String editLayersButtonTitle = defaultEditLayersButtonTitle; - /** The menu item to add a layer to the map. */ - protected transient JMenuItem add = null; - /** The default add button title. */ - protected transient String addLayersButtonTitle = "Add Layers..."; - - /** - * Construct LayersMenu. - */ - public LayersMenu() { - this(null); - } - - /** - * Construct LayersMenu. - * - * @param lHandler the handler for the layer - */ - public LayersMenu(LayerHandler lHandler) { - this(lHandler, "Layers", LAYERS_ON_OFF); - } - - /** - * Construct LayersMenu. - * - * @param lHandler the handler for the layer - * @param menuName the name of the menu - * @param menuType either LAYERS_ON_OFF, or PALETTES_ON_OFF - */ - public LayersMenu(LayerHandler lHandler, String menuName, int menuType) { - super(); - this.menuType = menuType; - setText(menuName); - // setMnemonic('L');// HMMMM - - layerHandler = lHandler; - - // Layers will be turned on by something else initially. - if (layerHandler != null) { - setLayers(layerHandler.getLayers()); - } - } - - /** - * Set the LayerHandler that the LayersPanel listens to. If the LayerHandler - * is not null, the LayersMenu will be added to the LayerHandler - * LayerListener list, and the LayersMenu will receive a LayerEvent with the - * current layers. - *

- * - * If there is a LayerHandler that is already being listened to, then the - * LayersPanel will remove itself from current LayerHandler as a - * LayerListener, before adding itself to the new LayerHandler. - *

- * - * Lastly, if the LayerHandler passed in is null, the LayersPanel will - * disconnect itself from any LayerHandler currently held, and reset itself - * with no layers. - * - * @param lh the LayerHandler containing the layers. - */ - public void setLayerHandler(LayerHandler lh) { - if (layerHandler != null) { - layerHandler.removeLayerListener(this); - } - - layerHandler = lh; - if (layerHandler != null) { - layerHandler.addLayerListener(this); - } else { - setLayers(new Layer[0]); - } - } - - /** - * Get the LayerHandler that the LayersPanel listens to. - */ - public LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Set the LayersPanel privately to keep track of what object is being used - * from the BeanContext. - */ - protected void setLayersPanel(LayersPanel lp) { - layersPanel = lp; - } - - /** - * Get the LayersPanel, privately held to keep track of what object is being - * used from the BeanContext. - */ - protected LayersPanel getLayersPanel() { - return layersPanel; - } - - /** - * Return the title of the menu option to call up LayersPanel. - */ - public void setEditLayersButtonTitle(String buttonTitle) { - editLayersButtonTitle = buttonTitle; - } - - /** - * Return the title of the menu option to call up LayersPanel. - */ - public String getEditLayersButtonTitle() { - return editLayersButtonTitle; - } - - /** - * Set the edit menu item that triggers the LayersPanel action listener. - * Assumes that it's already wired up. - */ - public void setEdit(JMenuItem e) { - edit = e; - - // This actually adds the edit button to the bottom of the - // LayerMenu when the menu is reconstructed. - if (getLayerHandler() != null) { - setLayers(getLayerHandler().getLayers()); - } - } - - /** - * Set the add menu item. - */ - public void setAdd(JMenuItem a) { - add = a; - if (getLayerHandler() != null) { - setLayers(getLayerHandler().getLayers()); - } - } - - /** - * Get the edit menu item that triggers the LayersPanel action listener. - */ - public JMenuItem getEdit() { - return edit; - } - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. - * - * @param evt a LayerEvent - */ - public void setLayers(LayerEvent evt) { - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - setLayers(layers); - } - } - - /** - * Set the layers that are on the menu. Calls for AWT thread to update - * layers - * - * @param inLayers the array of layers. - */ - public void setLayers(Layer[] inLayers) { - if (SwingUtilities.isEventDispatchThread()) { - setLayersFromEDT(inLayers); - } else { - SwingUtilities.invokeLater(new MyWorker(inLayers)); - } - } - - protected void setLayersFromEDT(Layer[] inLayers) { - removeAll(); - - // Set everything up for the new layers - if (inLayers == null) { - if (Debug.debugging("layersmenu")) { - Debug.error("LayersMenu.setLayers(): Layers are null."); - } - } else { - for (Layer layer : inLayers) { - LayerCheckBoxMenuItem cbs = new LayerCheckBoxMenuItem(layer); - cbs.setEnabled(layer.isRemovable()); - add(cbs); - } - } - - if (edit != null) { - add(new JSeparator()); - add(edit); - } - if (add != null) { - add(add); - } - } - - /** - * Remove all the components from the menu. Also calls cleanup() on all the - * LayerCheckBoxMenuItems, so they can remove themselves from their layers. - */ - public void removeAll() { - Component[] components = getMenuComponents(); - - if (components.length > 0) { - Debug.message("layersmenu", "LayersMenu.removeAll(): purging menu"); - } - - for (int i = 0; i < components.length; i++) { - if (components[i] instanceof LayerCheckBoxMenuItem) { - ((LayerCheckBoxMenuItem) components[i]).cleanup(); - } - } - super.removeAll(); - } - - /** - * Update the layer names. - */ - public synchronized void updateLayerLabels() { - if (layerHandler != null) { - setLayers(layerHandler.getLayers()); - } - } - - /** - * CheckBoxMenuItem that encapsulates a Layer. - */ - class LayerCheckBoxMenuItem extends JCheckBoxMenuItem implements ActionListener, ComponentListener { - /** The layer that the button triggers. */ - Layer layer; - /** - * Let's be safe - */ - Object LAYER_LOCK = new Object(); - - /** - * Construct the menu item, connected to the given layer. - */ - LayerCheckBoxMenuItem(Layer aLayer) { - if (aLayer == null) { - throw new IllegalArgumentException("null Layer"); - } - synchronized (LAYER_LOCK) { - layer = aLayer; - } - this.setText(layer.getName()); - setState(layer.isVisible()); - - Object tooltip = layer.getAttribute(Layer.ToolTipProperty); - if (tooltip != null) { - this.setToolTipText(tooltip.toString()); - } - - this.addActionListener(this); - layer.addComponentListener(this); - } - - /** Get the layer for this checkbox. */ - public Layer getLayer() { - synchronized (LAYER_LOCK) { - return layer; - } - } - - /** - * Disconnect all the listeners from the layer, clean up other - * references. - */ - public void cleanup() { - this.removeActionListener(this); - if (layer != null) { - layer.removeComponentListener(this); - } - - synchronized (LAYER_LOCK) { - layer = null; - } - } - - /** - * If this widget is being used for bringing up palettes, bring up the - * layer's palette. - */ - protected void showPalette() { - Layer layer = getLayer(); - if (layer != null) { - layer.showPalette(); - } - } - - /** - * If this widget is being used for bringing up palettes, hide the - * layer's palette. - */ - protected void hidePalette() { - Layer layer = getLayer(); - if (layer != null) { - layer.hidePalette(); - } - } - - /** This menu item listens to the status of its layer. */ - public void componentResized(ComponentEvent e) { - } - - /** This menu item listens to the status of its layer. */ - public void componentMoved(ComponentEvent e) { - } - - /** - * This menu item listens to the status of its layer. If the layer - * becomes visible, it makes the check box enabled. - */ - public void componentShown(ComponentEvent e) { - Layer layer = getLayer(); - if (layer != null) { - if (e.getComponent() == layer) { - if (getState() != true && menuType == LAYERS_ON_OFF) { - setState(true); - if (Debug.debugging("layersmenu")) { - Debug.output("layersmenu.LCBMI: layer " + layer.getName() + " is now visible."); - } - } - } else if (e.getComponent() == layer.getPalette() && menuType == PALETTES_ON_OFF) { - setState(true); - } - } - } - - /** - * This menu item listens to the status of its layer. If the layer - * becomes invisible, it disables the check box. - */ - public void componentHidden(ComponentEvent e) { - Layer layer = getLayer(); - if (layer != null) { - if (e.getComponent() == layer) { - if (getState() != false && menuType == LAYERS_ON_OFF) { - setState(false); - if (Debug.debugging("layersmenu")) { - Debug.output("layersmenu.LCBMI: layer " + layer.getName() + " is now hidden."); - } - } - } else if (e.getComponent() == layer.getPalette() && menuType == PALETTES_ON_OFF) { - setState(false); - } - } - } - - /** - * Triggered by the menu item check button. - * - * @param e ActionEvent fired by the button. - */ - public void actionPerformed(ActionEvent e) { - - if (!this.equals(e.getSource())) { - Debug.error("Wiring is hopelessly wrong in LayersMenu"); - } - switch (menuType) { - case LAYERS_ON_OFF: - layerHandler.turnLayerOn(getState(), getLayer()); - break; - case PALETTES_ON_OFF: - if (getState()) - showPalette(); - else - hidePalette(); - break; - default: - System.err.println("LayersMenu: unknown menuType!"); - } - } - } - - /** - * Given a LayersPanel, set up a JButton to add to the end of the LayersMenu - * that will trigger the action listener of the LayersPanel. - * - * @param lp the LayersPanel to ask for an ActionListener from. - */ - public void setupEditLayersButton(LayersPanel lp) { - // initialize the Edit Layers... button. - JMenuItem button = new JMenuItem(i18n.get(LayersMenu.class, "editLayersButtonTitle", editLayersButtonTitle)); - button.setActionCommand("edit"); - button.addActionListener(lp.getActionListener()); - setEdit(button); - setLayersPanel(lp); - } - - /** - * Constructs the menu item that will bring up the LayerAddPanel. - */ - public void setupLayerAddButton(final LayerAddPanel menu) { - final LayerAddPanel lap = menu; - - if (menu != null) { - JMenuItem button = new JMenuItem(i18n.get(LayersMenu.class, "addLayersButtonTitle", addLayersButtonTitle)); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - lap.showPanel(); - } - }); - - setAdd(button); - add(button); - } - } - - /** - * Called when the BeanContext membership changes with object from the - * BeanContext. This lets this object hook up with what it needs. It expects - * to find only one LayerHandler and LayersPanel in the BeanContext. If - * another LayerHandler/LayersPanel is somehow added to the BeanContext, - * however, it will drop the connection to the component it is set up to - * listen to, and rewire itself to reflect the status of the last version of - * the LayerHandler/LayersPanel found. - * - * @param someObj Object received in the BeanContext or - * BeanContextMembershipEvent. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu found a LayerHandler"); - setLayerHandler((LayerHandler) someObj); - } else if (someObj instanceof LayersPanel) { - setupEditLayersButton((LayersPanel) someObj); - } else if (someObj instanceof LayerAddPanel) { - // if a LayerAddPanel is present, do the necessary things - setupLayerAddButton((LayerAddPanel) someObj); - } - } - - /** - * Called when objects are removed from the BeanContext. Should be used to - * check for relevant objects that need to be disconnected from this object. - * This method does check to see if a LayerHandler or LayersPanel is being - * removed, that it is the same object currently being used by this - * LayersMenu. - * - * @param someObj the object being removed from the BeanContext - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerHandler) { - - LayerHandler lh = (LayerHandler) someObj; - // Need to check to see if this layerhandler is the - // same as the one we have !!!! - if (lh != getLayerHandler()) { - Debug.message("bc", - "LayersMenu asked to remove LayerHandler that is not the same as what is currently held - ignoring request."); - return; - } - - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu.childrenRemoved: removing LayerHandler"); - setLayerHandler(null); - setEdit(null); - } - if (someObj instanceof LayersPanel) { - LayersPanel lp = (LayersPanel) someObj; - // There's a problem here. We can't tell if the - // LayersPanel being removed is the owner of the - // action listener used by the edit button. If two - // LayersPanels have been added to the BeanContext, - // and we're now listening to the second one, then if - // the first one is removed, we are forced here to - // disconnect from the second and valid one. Looks - // like we need to maintain a handle on the - // LayersPanel being triggered. - if (lp != getLayersPanel()) { - Debug.message("bc", - "LayersMenu asked to remove LayersPanel that is not the same as what is currently held - ignoring request."); - return; - } - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu.childrenRemoved: removing LayersPanel"); - setLayersPanel(null); - setEdit(null); - } - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) throws PropertyVetoException { - super.fireVetoableChange(name, oldValue, newValue); - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - class MyWorker implements Runnable { - - private Layer[] layers; - - public MyWorker(Layer[] inLayers) { - layers = inLayers.clone(); - } - - public void run() { - try { - setLayersFromEDT(layers); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/LayersPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/LayersPanel.java deleted file mode 100644 index 3e2451ee8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/LayersPanel.java +++ /dev/null @@ -1,1105 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayersPanel.java,v $ -// $RCSfile: LayersPanel.java,v $ -// $Revision: 1.17 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.ButtonModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JScrollBar; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.BufferedLayerMapBean; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The LayersPanel displays the list of layers that OpenMap can display. The - * layer name is displayed accompanied by an on/off button and a tool palette - * button. Pressing the on/off button will cause the the map to display/remove - * the layer. Pressing the tool palette button will cause a window to be - * displayed containing widgets specific to that layer. - *

- * - * The order of the layers in the list reflects the order that the layers are - * displayed on the map, with the bottom-most layer listed on the panel - * underneath all the the other layers displayed on the map. The order of the - * layers is determined by their order in the Layer[] passed in the setLayers - * method. - *

- * - * The order of the layers can be changed by sending the LayersPanel an - * ActionEvent with one of the string commands in the class, or by sending a - * PropertyChangeEvent with a command and a Layer as the new value. - *

- * - * In the standard GUI, the order can be changed by selecting a layer by - * clicking on the layer's name (or on either of buttons), then clicking on one - * of the four buttons on the left side of the panel. The four buttons signify, - * from top to bottom: Move the selected layer to the top; Move the selected - * layer up one position; Move the selected layer down one position; Move the - * selected layer to the bottom. - *

- * - * The LayersPanel can be used within a BeanContext. If it is added to a - * BeanConext, it will look for a LayerHandler to add itself to as a - * LayerListener. The LayersPanel can only listen to one LayerHandler, so if - * more than one is found, only the last one found will be used. If another - * LayerHandler is added to the BeanContext later, the new LayerHandler will be - * used. The LayersPanel is also considered to be a Tool, which will cause a - * button that will bring up the LayersPanel to be automatically added to the - * ToolPanel if a ToolPanel is part of the BeanContext. - *

- * - * When the LayersPanel discovers a BufferedLayerMapBean is being used, it adds - * a special LayerPane to its LayerPane list that shows which layers are being - * buffered in the MapBean. This special LayerPane shows up as a line in the - * list, and all layers below that line are being specially buffered by the - * BufferedLayerMapBean. - *

- * - * The properties that can be set for the LayersPanel: - * - *

- * 
- * 
- * 
- *          # Use LayerStatusPanes for the layers if true, otherwise
- *          # LayerPanes.  LayerStatusPanes turn the on/off bulbs to green/red
- *          # bulbs when the layer is resting/working.  LayerPanes just show
- *          # yellow bulbs when the layer is part of the map.
- *          showStatus=true
- *          # When the BufferedLayerMapBean is used, a divider will be
- *          # displayed in the list of layers showing which layers are in the
- *          # MapBean buffer (below the line).  Commands to move layers, by
- *          # default, respect this divider, requiring more commands to have
- *          # layers cross it.
- *          boundary=true
- *          # Add control buttons - use "none" for no button.  If undefined,
- *          # the LayerControlButtonPanel will be created automatically.
- *          controls=com.bbn.openmap.gui.LayerControlButtonPanel
- *          # Any control properties added here, prepended by "controls"...
- *          controls.configuration=WEST
- * 
- * 
- * 
- * 
- */ -public class LayersPanel extends OMToolComponent - implements Serializable, ActionListener, LayerListener, PropertyChangeListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.LayersPanel"); - - /** Action command for the layer order buttons. */ - public final static String LayerTopCmd = "LayerTopCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerBottomCmd = "LayerBottomCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerUpCmd = "LayerUpCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerDownCmd = "LayerDownCmd"; - /** Action command removing a layer. */ - public final static String LayerRemoveCmd = "LayerRemoveCmd"; - /** Action command adding a layer. */ - public final static String LayerAddCmd = "LayerAddCmd"; - /** Action command for notification that a layer has been selected. */ - public final static String LayerSelectedCmd = "LayerSelected"; - /** - * Action command for notification that a layer has been deselected. Not so - * reliable. Usually a selection notification means that others are - * deselected. - */ - public final static String LayerDeselectedCmd = "LayerDeselected"; - - /** - * A property to set the class to create for layer order controls. If - * undefined, a LayerControlButtonPanel in its default configuration will be - * created. For no controls added, use (none) for this property. - */ - public final static String ControlButtonsProperty = "controls"; - /** - * A property that can be used for controlling how the to top and to bottom - * commands will be interpreted when a BufferedLayerMapBean is used. See the - * definition of bufferedBoundary. - */ - public final static String BufferedBoundaryProperty = "boundary"; - /** - * A property that can be used for controlling what type of LayerPanes are - * used. If true (default) a LayerStatusPane will be created for each layer. - * Otherwise, a LayerPane will be used. - */ - public final static String ShowStatusProperty = "showStatus"; - - /** - * A value for the (controls) property to not include control buttons in the - * interface. - */ - public final static String NO_CONTROLS = "none"; - - /** Default key for the LayersPanel Tool. */ - public final static String defaultKey = "layerspanel"; - - /** - * The LayerHandler to listen to for LayerEvents, and also to notify if the - * layer order should change. - */ - protected transient LayerHandler layerHandler = null; - /** - * Panel that lets you dynamically add and configure layers. - */ - protected transient LayerAddPanel layerAddPanel = null; - /** - * The components holding the layer name label, the on/off indicator and on - * button, and the palette on/off indicator and palette on button. - */ - protected transient List panes; - /** The internal component that holds the panes. */ - protected transient JPanel panesPanel; - /** The scroll pane to use for panes. */ - protected transient JScrollPane scrollPane; - /** The Layer order adjustment button group. */ - protected transient ButtonGroup bg; - /** The ActionListener that will bring up the LayersPanel. */ - protected ActionListener actionListener; - /** The set of buttons that control the layers. */ - protected LayerControlButtonPanel controls = null; - /** - * Hashtable that tracks LayerPanes for layers, with the layer as the key - * and LayerPane as the value. - */ - protected Hashtable paneLookUp = new Hashtable(); - /** - * A special LayerPane used when the LayersPanel senses that a - * BufferedLayerMapBean is being used. This LayersPanel is a separating line - * showing which layers are part of the MapBean's buffer, and which are not. - */ - protected LayerPane backgroundLayerSeparator = null; - /** - * Behavior flag so that if there is a background buffered layer on the - * MapBean, and a buffered layer divider in the LayersPanel, whether - * commands instructing a layer to the top or bottom of the list should - * honor the virtual boundary between buffered and unbuffered layers. That - * is, if a layer is on the bottom of the buffered list and is instructed to - * go to the top of the overall list, it will only first travel to the top - * of the buffered layers. On a subsequent top command, it will go to the - * top of the list. The same behavior applies for going down. True is - * default. If set to false, these commands will just send the selected - * layer to the top and bottom of the entire list. - */ - protected boolean bufferedBoundary = true; - - /** - * Behavior flag that determines what kind of LayerPane is used for the - * layers. If true (default) the LayerStatusPane will be used. Otherwise, - * the LayerPane will be used instead. - */ - protected boolean showStatus = true; - - /** - * Construct the LayersPanel. - */ - public LayersPanel() { - super(); - setKey(defaultKey); - setLayout(new BorderLayout()); - } - - /** - * Construct the LayersPanel. - * - * @param lHandler the LayerHandler controlling the layers. - */ - public LayersPanel(LayerHandler lHandler) { - this(); - setLayerHandler(lHandler); - } - - /** - * Construct the LayersPanel. - * - * @param lHandler the LayerHandler controlling the layers. - * @param addLayerControls if true, buttons that modify layer positions will - * be added. - */ - public LayersPanel(LayerHandler lHandler, boolean addLayerControls) { - this(lHandler); - if (addLayerControls) { - addLayerControls(); - } - } - - /** - * Set the LayerHandler that the LayersPanel listens to. If the LayerHandler - * passed in is not null, the LayersMenu will be added to the LayerHandler - * LayerListener list, and the LayersMenu will receive a LayerEvent with the - * current layers. - *

- * - * If there is a LayerHandler that is already being listened to, then the - * LayersPanel will remove itself from current LayerHandler as a - * LayerListener, before adding itself to the new LayerHandler. - *

- * - * Lastly, if the LayerHandler passed in is null, the LayersPanel will - * disconnect itself from any LayerHandler currently held, and reset itself - * with no layers. - * - * @param lh LayerHandler to listen to, and to use to reorder the layers. - */ - public void setLayerHandler(LayerHandler lh) { - if (layerHandler != null) { - layerHandler.removeLayerListener(this); - } - layerHandler = lh; - if (layerHandler != null) { - layerHandler.addLayerListener(this); - } else { - setLayers(new Layer[0]); - } - updateLayerPanes(layerHandler); - } - - /** - * Get the LayerHandler that the LayersPanel listens to and uses to reorder - * layers. - * - * @return LayerHandler. - */ - public LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Set the LayerPanes with the given LayerHandler. - * - * @param layerHandler The LayerHandler controlling the layers - */ - protected void updateLayerPanes(LayerHandler layerHandler) { - for (LayerPane pane : getPanes()) { - pane.setLayerHandler(layerHandler); - } - } - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. The LayersPanel only - * reacts to LayerEvent.ALL events, to reset the components in the - * LayersPanel. - * - * @param evt a LayerEvent. - */ - public void setLayers(LayerEvent evt) { - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - logger.fine("LayersPanel received layers update"); - setLayers(layers); - } - } - - /** - * Tool interface method. The retrieval tool's interface. This method - * creates a button that will bring up the LayersPanel. - * - * @return String The key for this tool. - */ - public Container getFace() { - JButton layerButton = null; - - if (getUseAsTool()) { - layerButton = new JButton(new ImageIcon(OMToolSet.class.getResource("layers.gif"), "Layer Controls")); - layerButton.setBorderPainted(false); - // layerButton.setToolTipText("Layer Controls"); - layerButton.setToolTipText(i18n.get(LayersPanel.class, "layerButton", I18n.TOOLTIP, "Layer Controls")); - layerButton.setMargin(new Insets(0, 0, 0, 0)); - layerButton.addActionListener(getActionListener()); - } - - return layerButton; - } - - /** - * Get the ActionListener that triggers the LayersPanel. Useful to have to - * provide an alternative way to bring up the LayersPanel. - * - * @return ActionListener - */ - public ActionListener getActionListener() { - return new ActionListener() { - public void actionPerformed(ActionEvent evt) { - WindowSupport ws = getWindowSupport(); - - if (ws == null) { - ws = new WindowSupport(LayersPanel.this, i18n.get(LayersPanel.class, "title", "Layers")); - setWindowSupport(ws); - } - - // Initial settings. - int w = 328; - int h = 300; - - Dimension dim = ws.getComponentSize(); - if (dim != null) { - w = (int) dim.getWidth(); - h = (int) dim.getHeight(); - } - - int x = -1; - int y = -1; - - Point loc = ws.getComponentLocation(); - if (loc != null) { - x = (int) loc.getX(); - y = (int) loc.getY(); - } - - MapHandler mh = (MapHandler) getBeanContext(); - // Window frame = null; // java 5 incompatibility - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - /* java 5 incompatibility */ - /* - * if (frame == null && evt.getSource() instanceof Component) { - * frame = SwingUtilities.getWindowAncestor((Component) - * evt.getSource()); } - */ - ws.displayInWindow(frame, x, y, w, h); - } - }; - } - - /** - * Set the layers that are on the menu. Calls for AWT thread to update - * layers - * - * @param inLayers the array of layers. - */ - public void setLayers(Layer[] inLayers) { - if (SwingUtilities.isEventDispatchThread()) { - setLayersFromEDT(inLayers); - } else { - SwingUtilities.invokeLater(new MyWorker(inLayers)); - } - } - - /** - * Set the layers that are in the LayersPanel. Make sure that the layer[] is - * the same as that passed to any other OpenMap component, like the - * LayersMenu. This method checks to see if the layer[] has actually - * changed, in order or in size. If it has, then createPanel() is called to - * rebuild the LayersPanel. Should be called within the Event Dispatch - * Thread. - * - * @param inLayers the array of layers. - */ - protected void setLayersFromEDT(Layer[] inLayers) { - Layer[] layers = inLayers; - - if (inLayers == null) { - layers = new Layer[0]; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayersPanel.setLayers() with " + layers.length + " layers."); - } - - List panes = getPanes(); - int separatorOffset = 0; - if (backgroundLayerSeparator != null && panes.contains(backgroundLayerSeparator)) { - separatorOffset = 1; - } - - if (panes.size() - separatorOffset != layers.length) { - // if the panel hasn't been created yet, or if someone has - // changed the layers on us, rebuild the panel. - createPanel(layers); - return; - } - - int i = 0; - Iterator it = panes.iterator(); - while (it.hasNext() && i < layers.length) { - LayerPane pane = (LayerPane) it.next(); - - if (pane == backgroundLayerSeparator) { - continue; - } - - if (pane.getLayer() != layers[i]) { - // If the layer order sways at all, then we start over - // and rebuild the panel - createPanel(layers); - return; - } else { - pane.updateLayerLabel(); - } - - // Do this just in case someone has changed something - // somewhere else... - pane.setLayerOn(layers[i].isVisible()); - i++; - } - - // One last check for a mismatch... - if (it.hasNext() || i < layers.length) { - createPanel(layers); - } - // If we get here, it means that what we had is what we - // wanted. - } - - protected List getPanes() { - if (panes == null) { - panes = new LinkedList(); - } - return panes; - } - - protected void setPanes(List lpa) { - panes = lpa; - } - - GridBagLayout panelGridbag; - GridBagConstraints pgbc; - - /** - * Create the panel that shows the LayerPanes. This method creates the - * on/off buttons, palette buttons, and layer labels, and adds them to the - * scrollPane used to display all the layers. - * - * @param inLayers the Layer[] that reflects all possible layers that can be - * added to the map. - */ - public void createPanel(Layer[] inLayers) { - logger.fine("creating panel"); - - Layer[] layers = inLayers; - if (layers == null) { - layers = new Layer[0]; - } - - if (panesPanel == null) { - panesPanel = new JPanel(); - panelGridbag = new GridBagLayout(); - pgbc = new GridBagConstraints(); - - panesPanel.setLayout(panelGridbag); - - pgbc.gridwidth = GridBagConstraints.REMAINDER; - pgbc.anchor = GridBagConstraints.NORTHWEST; - pgbc.fill = GridBagConstraints.HORIZONTAL; - pgbc.weightx = 1.0f; - - } else { - ((GridBagLayout) panesPanel.getLayout()).invalidateLayout(panesPanel); - panesPanel.removeAll(); - } - - if (bg == null) { - bg = new ButtonGroup() { - public void setSelected(ButtonModel m, boolean b) { - if (!b) { - for (LayerPane pane : getPanes()) { - pane.setSelected(false); - } - } - super.setSelected(m, b); - } - }; - } - - List panes = new LinkedList(); - List backgroundPanes = new LinkedList(); - - // populate the arrays of CheckBoxes and strings used to fill - // the JPanel for the panes - for (int i = 0; i < layers.length; i++) { - Layer layer = layers[i]; - if (layer == null) { - logger.fine("caught null layer, " + i + " out of " + layers.length); - continue; - } - - LayerPane lpane = (LayerPane) paneLookUp.get(layer); - - if (lpane == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating LayerPane for " + layer.getName()); - } - lpane = createLayerPaneForLayer(layer, layerHandler, bg); - lpane.addPropertyChangeListener(LayerSelectedCmd, this); - lpane.addPropertyChangeListener(LayerDeselectedCmd, this); - paneLookUp.put(layer, lpane); - } else { - // In case this has been modified elsewhere... - lpane.setLayerOn(layer.isVisible()); - } - - if (layer.getAddAsBackground() && backgroundLayerSeparator != null) { - backgroundPanes.add(lpane); - } else { - panes.add(lpane); - - panelGridbag.setConstraints(lpane, pgbc); - panesPanel.add(lpane); - } - } - - if (!backgroundPanes.isEmpty()) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Adding BackgroundLayerSeparator"); - } - panes.add(backgroundLayerSeparator); - panelGridbag.setConstraints(backgroundLayerSeparator, pgbc); - panesPanel.add(backgroundLayerSeparator); - panes.addAll(backgroundPanes); - - for (LayerPane lp : backgroundPanes) { - panelGridbag.setConstraints(lp, pgbc); - panesPanel.add(lp); - } - - } else if (backgroundLayerSeparator != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("No layers are background layers, adding separator"); - } - panes.add(backgroundLayerSeparator); - panelGridbag.setConstraints(backgroundLayerSeparator, pgbc); - panesPanel.add(backgroundLayerSeparator); - } - - addFillerToPanesPanel(); - - setPanes(panes); - - if (scrollPane == null) { - scrollPane = new JScrollPane(panesPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - add(scrollPane, BorderLayout.CENTER); - } - - revalidate(); - } - - protected void addFillerToPanesPanel() { - JPanel filler = new JPanel(); - pgbc.fill = GridBagConstraints.BOTH; - pgbc.weighty = 1.0f; - panelGridbag.setConstraints(filler, pgbc); - panesPanel.add(filler); - pgbc.fill = GridBagConstraints.HORIZONTAL; - pgbc.weighty = 0.0f; - } - - /** - * Called when a new LayerPane needs to be created for a layer. You can use - * this to extend LayerPane and return something else that fits your GUI. - */ - protected LayerPane createLayerPaneForLayer(Layer layer, LayerHandler layerHandler, ButtonGroup bg) { - if (showStatus) { - return new LayerStatusPane(layer, layerHandler, bg); - } else { - return new LayerPane(layer, layerHandler, bg); - } - } - - public void deletePanes(List dpanes) { - logger.fine("deleting panes"); - if (dpanes != null) { - paneLookUp.clear(); - - for (LayerPane pane : dpanes) { - if (pane != null && pane != backgroundLayerSeparator) { - pane.removePropertyChangeListener(this); - pane.cleanup(bg); - } - } - } - } - - /** - * Tell the LayersPanel to add layer control buttons. Does nothing if the - * controls are already set. - * @return this LayerPanel, as a Builder method. - */ - public LayersPanel addLayerControls() { - if (getControls() == null) { - setControls(createControlButtons()); - } - - return this; - } - - /** - * Set up the buttons used to move layers up and down, or add/remove layers. - * The button component should hook itself up to the LayersPanel, and assume - * that the LayersPanel has a BorderLayout with the list in the center spot. - */ - public LayerControlButtonPanel createControlButtons() { - return new LayerControlButtonPanel(this); - } - - /** - * Should be called internally, when the LayersPanel creates the - * LayerControlButtonPanel. If called from the LCBP, a loop will ensue. - * - * @param lcbp - */ - protected void setControlsAndNotify(LayerControlButtonPanel lcbp) { - setControls(lcbp); - if (lcbp != null) { - lcbp.setLayersPanel(this); - } - } - - /** - * Simply sets the controls. - * - * @param lcbp - */ - public void setControls(LayerControlButtonPanel lcbp) { - controls = lcbp; - } - - public LayerControlButtonPanel getControls() { - return controls; - } - - /** - * Method associated with the ActionListener interface. This method listens - * for action events meant to change the order of the layers, as fired by - * the layer order buttons. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(command); - } - - try { - LayerPane pane = findSelectedPane(); - if (pane != null) { - moveLayer(pane, command); - } - } catch (NullPointerException npe) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - } - - /** - * Change a layer's position. - */ - public void moveLayer(Layer layer, String command) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(command + " for " + layer.getName()); - } - - moveLayer((LayerPane) paneLookUp.get(layer), command); - } - - /** - * Change a layer's position, with the layer represented by a LayerPane. - */ - protected void moveLayer(LayerPane lp, String command) { - - if (lp == null) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerPane not represented on list"); - } - - if (command == LayerRemoveCmd) { - // OK, here's a hidden trick. If no layers are - // selected and the minus sign is clicked, then this is called. - System.gc(); - } - return; - } - - List panes = getPanes(); - int row = panes.indexOf(lp); - - boolean boundary = false; - int bls_row = -1; - if (backgroundLayerSeparator != null) { - bls_row = panes.indexOf(backgroundLayerSeparator); - boundary = bufferedBoundary; - } - - if (command.equals(LayerTopCmd)) { - // Move layer selected layer to top - panes.remove(lp); - if (boundary && bls_row > 0 && row > bls_row + 1) { - // If the backgroundLayerSeparator is more than one - // above it, move to just below it on the first top - // command. - panes.add(bls_row + 1, lp); - } else { - panes.add(0, lp); - } - - rejiggerMapLayers(); - } else if (command.equals(LayerBottomCmd)) { - // Move layer selected layer to bottom - panes.remove(lp); - - if (boundary && bls_row > 0 && row < bls_row - 1) { - // If the backgroundLayerSeparator is more than one - // below it, move to just above it on the first top - // command. - panes.add(bls_row - 1, lp); - } else { - panes.add(panes.size(), lp); - } - - rejiggerMapLayers(); - } else if (command.equals(LayerUpCmd)) { - // Move layer selected layer up one - if (row <= 0) - return; - panes.remove(row); - panes.add(row - 1, lp); - rejiggerMapLayers(); - } else if (command.equals(LayerDownCmd)) { - // Move layer selected layer up one - if (row < 0 || row == panes.size() - 1) - return; - panes.remove(row); - panes.add(row + 1, lp); - rejiggerMapLayers(); - } else if (command.equals(LayerRemoveCmd)) { - - if (layerHandler == null || !lp.getLayer().removeConfirmed()) { - return; - } - - // This order is somewhat important. lp.getLayer() will - // be null after lp.cleanup. lp.setSelected() will cause - // a series of property change notifications. - - layerHandler.removeLayer(lp.getLayer()); - lp.cleanup(bg); - - return; - - } else if (command.equals(LayerAddCmd)) { - if (layerAddPanel != null) { - layerAddPanel.showPanel(); - } - } - } - - /** - * Find the selected LayerPane in the current LayerPane list. Will return - * null if there isn't a selected pane. - */ - protected LayerPane findSelectedPane() { - for (LayerPane pane : getPanes()) { - if (pane.isSelected()) { - return pane; - } - } - return null; - } - - /** - * Makes a new layer cake of active layers to send to - * LayerHandler.setLayers(). - */ - protected void rejiggerMapLayers() { - logger.fine("jiggering......."); - - if (layerHandler == null) { - // Why bother doing anything?? - return; - } - - int selectedRow = -1; - - panesPanel.removeAll(); - panelGridbag.invalidateLayout(panesPanel); - - List panes = getPanes(); - List layerList = new LinkedList(); - - int bufferIndex = Integer.MAX_VALUE; - - int i = 0; // track layer index - - for (LayerPane pane : panes) { - - if (pane == backgroundLayerSeparator) { - panelGridbag.setConstraints(pane, pgbc); - panesPanel.add(backgroundLayerSeparator); - bufferIndex = i++; - continue; - } - - Layer layer = pane.getLayer(); - layer.setAddAsBackground(i > bufferIndex); - panelGridbag.setConstraints(pane, pgbc); - panesPanel.add(pane); - layerList.add(layer); - - if (pane.isSelected()) { - selectedRow = i; - } - i++; - } - - addFillerToPanesPanel(); - - scrollPane.revalidate(); - - // Scroll up or down as necessary to keep selected row - // viewable - if (selectedRow >= 0) { - int spheight = scrollPane.getHeight(); - JScrollBar sb = scrollPane.getVerticalScrollBar(); - int sv = sb.getValue(); - int paneheight = ((LayerPane) panes.get(selectedRow)).getHeight(); - int rowvalue = selectedRow * paneheight; - // Don't reset scrollBar unless the selected row - // is not in the viewable range - if (!((rowvalue > sv) && (rowvalue < spheight + sv))) { - sb.setValue(rowvalue); - } - } - - layerHandler.setLayerList(new LinkedList(layerList)); - } - - /** - * Update the layer names - if a layer name has changed, tell the LayerPanes - * to check with their layers to update their labels. - */ - public synchronized void updateLayerLabels() { - for (LayerPane pane : getPanes()) { - pane.updateLayerLabel(); - } - } - - public void propertyChange(PropertyChangeEvent pce) { - String command = pce.getPropertyName(); - Object obj = pce.getNewValue(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("receiving PropertyChangeEvent " + command + ", " + pce.toString()); - } - - if ((command == LayerSelectedCmd || command == LayerDeselectedCmd) && obj instanceof Layer) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer panel notification that layer is selected: " + ((Layer) obj).getName()); - } - firePropertyChange(command, null, ((Layer) obj)); - - } else if ((command == LayersPanel.LayerTopCmd || command == LayersPanel.LayerBottomCmd - || command == LayersPanel.LayerUpCmd || command == LayersPanel.LayerDownCmd - || command == LayersPanel.LayerRemoveCmd) && obj instanceof Layer) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer panel notification that layer should be raised: " + ((Layer) obj).getName()); - } - moveLayer((Layer) obj, command); - } - } - - /** - * Called when the LayersPanel is added the BeanContext, or when another - * object is added to the BeanContext after the LayerHandler has been added. - * This allows the LayersPanel to keep up-to-date with any objects that it - * may be interested in, namely, the LayerHandler. If a LayerHandler has - * already been added, the new LayerHandler will replace it. - * - * @param someObj the object being added to the BeanContext - */ - public void findAndInit(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - logger.fine("LayersPanel found a LayerHandler"); - setLayerHandler((LayerHandler) someObj); - } - - if (someObj instanceof BufferedLayerMapBean) { - logger.fine("LayersPanel found BufferedLayerMapBean, creating separator panel"); - backgroundLayerSeparator = LayerPane.getBackgroundLayerSeparator(" --- Background Layers --- "); - } - - // Don't want to forward ourselves on to controls, supposedly - // they already know. - if (controls != null && someObj != this) { - controls.findAndInit(someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when an object has been - * removed from the parent BeanContext. If a LayerHandler is removed, and - * it's the current one being listened to, then the layers in the panel will - * be wiped clean. - * - * @param someObj the object being removed from the BeanContext - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - logger.fine("LayersPanel removing LayerHandler"); - if (getLayerHandler() == (LayerHandler) someObj) { - setLayerHandler(null); - } - } - - // Don't want to forward ourselves on to controls, supposedly - // they already know. - if (controls != null && someObj != this) { - controls.findAndUndo(someObj); - } - - if (someObj instanceof Layer) { - paneLookUp.remove((Layer) someObj); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String controlString = props.getProperty(prefix + ControlButtonsProperty); - - if (controlString == null) { - setControls(createControlButtons()); - } else { - controlString = controlString.trim(); - - if (!NO_CONTROLS.equalsIgnoreCase(controlString)) { - Object obj = ComponentFactory.create(controlString, prefix + ControlButtonsProperty, props); - - if (obj instanceof LayerControlButtonPanel) { - setControlsAndNotify((LayerControlButtonPanel) obj); - } - } - } - - bufferedBoundary = PropUtils.booleanFromProperties(props, prefix + BufferedBoundaryProperty, bufferedBoundary); - showStatus = PropUtils.booleanFromProperties(props, prefix + ShowStatusProperty, showStatus); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - LayerControlButtonPanel controls = getControls(); - if (controls != null) { - props.put(prefix + ControlButtonsProperty, controls.getClass().getName()); - controls.getProperties(props); - } - props.put(prefix + BufferedBoundaryProperty, new Boolean(bufferedBoundary).toString()); - props.put(prefix + ShowStatusProperty, new Boolean(showStatus).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String interString = i18n.get(LayersPanel.class, ControlButtonsProperty, I18n.TOOLTIP, - "Class to use for layer control buttons (Optional)"); - props.put(ControlButtonsProperty, interString); - interString = i18n.get(LayersPanel.class, ControlButtonsProperty, "Button Panel Control"); - props.put(ControlButtonsProperty + LabelEditorProperty, interString); - - LayerControlButtonPanel controls = getControls(); - if (controls != null) { - controls.getPropertyInfo(props); - } - - interString = i18n.get(LayersPanel.class, BufferedBoundaryProperty, I18n.TOOLTIP, - "Force layer movement to respect background layer boundary."); - props.put(BufferedBoundaryProperty, interString); - interString = i18n.get(LayersPanel.class, BufferedBoundaryProperty, "Use Background Layers"); - props.put(BufferedBoundaryProperty + LabelEditorProperty, interString); - props.put(BufferedBoundaryProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(LayersPanel.class, ShowStatusProperty, I18n.TOOLTIP, - "Use Layer Panes that show layer status."); - props.put(ShowStatusProperty, interString); - interString = i18n.get(LayersPanel.class, ShowStatusProperty, "Show Layer Status"); - props.put(ShowStatusProperty + LabelEditorProperty, interString); - props.put(ShowStatusProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } - - class MyWorker implements Runnable { - - private Layer[] layers; - - public MyWorker(Layer[] inLayers) { - layers = inLayers.clone(); - } - - public void run() { - try { - setLayersFromEDT(layers); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MGRSCoordPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/MGRSCoordPanel.java deleted file mode 100644 index 718cf92a6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MGRSCoordPanel.java +++ /dev/null @@ -1,130 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MGRSCoordPanel.java,v $ -// $RCSfile: MGRSCoordPanel.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/05/22 23:53:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.Serializable; - -import javax.swing.JLabel; -import javax.swing.JTextField; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.MGRSPoint; - -/** - * MGRSCoordPanel is a simple gui with an entry box for a MGRS - * coordinate. It sets the center of a map by firing CenterEvents. - */ -public class MGRSCoordPanel extends CoordPanel implements Serializable { - - protected transient JTextField mgrs; - - /** - * Creates the panel. - */ - public MGRSCoordPanel() { - super(); - } - - /** - * Creates the panel. - */ - public MGRSCoordPanel(CenterSupport support) { - super(support); - } - - /** - * Creates and adds the labels and entry fields for latitude and - * longitude - */ - protected void makeWidgets() { - String locText; - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - Insets leftInsets = new Insets(0, 10, 0, 10); - Insets rightInsets = new Insets(0, 0, 0, 10); - - setLayout(gridbag); - locText = i18n.get(MGRSCoordPanel.class, "border", "MGRS Coordinate"); - setBorder(new TitledBorder(new EtchedBorder(), locText)); - - locText = i18n.get(MGRSCoordPanel.class, "mgrsLabel", "MGRS: "); - JLabel mgrsLabel = new JLabel(locText); - c.gridx = 0; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - gridbag.setConstraints(mgrsLabel, c); - add(mgrsLabel); - - mgrs = new JTextField(20); - c.gridx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.insets = rightInsets; - gridbag.setConstraints(mgrs, c); - add(mgrs); - } - - /** - * @return the LatLonPoint represented by contents of the entry - * boxes - */ - public LatLonPoint getLatLon() { - - try { - // Allow blank minutes and seconds fields to represent zero - return new MGRSPoint(mgrs.getText()).toLatLonPoint(); - - } catch (NumberFormatException except) { - // System.out.println(except.toString()); - clearTextBoxes(); - } - return null; - } - - /** - * Sets the contents of the latitude and longitude entry boxes - * - * @param llpoint the object containing the coordinates that - * should go in the boxes. - */ - public void setLatLon(LatLonPoint llpoint) { - if (llpoint == null) { - clearTextBoxes(); - return; - } - - MGRSPoint mgrsp = new MGRSPoint(llpoint); - mgrs.setText(mgrsp.getMGRS()); - } - - protected void clearTextBoxes() { - mgrs.setText(""); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MapPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/MapPanel.java deleted file mode 100644 index 2d3aeda5a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MapPanel.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MapPanel.java,v $ -// $RCSfile: MapPanel.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.gui; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import javax.swing.JMenu; -import javax.swing.JMenuBar; - -/** - * The MapPanel is a interface describing a component that contains a MapBean, - * MapHandler, menu widgets and all the other components connected to make an - * OpenMap map widget. A MapPanel is a self-contained OpenMap Swing component. - * It is expected that the MapPanel will extend from java.awt.Container. If it - * doesn't, it might not be automatically added to the OpenMapFrame or - * OpenMapApplet if it is found in the MapHandler. - */ -public abstract class MapPanel extends OMComponentPanel { - - /** - * Get the MapBean used for the MapPanel. - */ - public abstract MapBean getMapBean(); - - /** - * Get the MapHandler used for the MapPanel. You should be able to use the - * MapHandler to get to any component used in the MapPanel. - */ - public abstract MapHandler getMapHandler(); - - /** - * Get a JMenuBar containing menus to control the map. - */ - public abstract JMenuBar getMapMenuBar(); - - /** - * Get a JMenu containing sub-menus to control the map. - */ - public abstract JMenu getMapMenu(); - - /** - * Tell the panel to release components. - */ - public abstract void dispose(); - - /** - * Add an object to the MapHandler in this MapPanel. - * - * @param obj - */ - public abstract void addMapComponent(Object obj); -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MapPanelChild.java b/src/core/src/main/java/com/bbn/openmap/gui/MapPanelChild.java deleted file mode 100644 index 23bdf4a55..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MapPanelChild.java +++ /dev/null @@ -1,70 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MapPanelChild.java,v $ -// $RCSfile: MapPanelChild.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -/** - * A simple interface to let an object know it wants to be added to the - * MapPanel, and where it would like to be placed. The MapPanel can look for - * these components in the MapHandler. - */ -public interface MapPanelChild { - - /** - * The property a MapPanelChild would use to set its preferred location in - * its properties ("preferredLocation"). Property would be set to one of the - * following: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST or - * BorderLayout.WEST. - */ - public static final String PreferredLocationProperty = "preferredLocation"; - - /** - * The property a MapPanelChild would use to designate a parent component - * ("parent"). Should be set to the property prefix of the parent component. - */ - public static final String ParentNameProperty = "parent"; - - /** - * Should be provided with BorderLayout.NORTH, BorderLayout.SOUTH, - * BorderLayout.EAST or BorderLayout.WEST. BorderLayout.Center is generally - * reserved for the MapBean. - */ - public void setPreferredLocation(String string); - - /** - * Should return BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST - * or BorderLayout.WEST. BorderLayout.Center is generally reserved for the - * MapBean. - */ - public String getPreferredLocation(); - - /** - * Should return the name of the desired parent component. This method lets - * a MapPanel to ask a component if it should be added to the panel. Enables - * application components to configure themselves from property file - * information. - * - * @return the name of the parent component that the MapPanelChild should be - * added to, or null if it doesn't know. - */ - public String getParentName(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MapWindow.java b/src/core/src/main/java/com/bbn/openmap/gui/MapWindow.java deleted file mode 100644 index 0fefb575d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MapWindow.java +++ /dev/null @@ -1,135 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MapWindow.java,v $ -// $RCSfile: MapWindow.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; - -import javax.swing.JFrame; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.Environment; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.MultipleSoloMapComponentException; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The MapWindow is a window with the basics - MapBean, - * MouseDelegator, SelectMouseMode, LayerHandler. It can be used to - * draw stuff into if you add a layer to it that handles what you want - * to render. The SelectMouseMode will automatically direct mouse - * events to the layer if it is set up to receive "Gestures". - *

- * - * If you want to add an object that needs to set itself to a - * particular location on the frame, i.e. the ToolPanel or - * InformationDelegator, you have to do the layout management yourself - * with the MapWindow. The OpenMapFrame has an idea of where it wants - * those components to go, but the MapWindow doesn't. - */ -public class MapWindow extends JFrame { - - /** The MapHandler BeanContext. */ - protected MapHandler mapHandler = new MapHandler(); - /** The MapBean. */ - protected MapBean map; - - public MapWindow() { - super(); - } - - public MapWindow(String windowTitle) { - super(windowTitle); - try { - map = new BufferedMapBean(); - mapHandler.add(new MouseDelegator()); - mapHandler.add(new LayerHandler()); - mapHandler.add(map); - getContentPane().add(map, BorderLayout.CENTER); - } catch (MultipleSoloMapComponentException msmce) { - } - } - - /** Add an object to the internal MapHandler. */ - public void addTo(Object obj) throws MultipleSoloMapComponentException { - mapHandler.add(obj); - } - - /** Remove an object from the internal MapHandler. */ - public void removeFrom(Object obj) { - mapHandler.remove(obj); - } - - /** Get the MapHandler. */ - public MapHandler getMapHandler() { - return mapHandler; - } - - /** Get the map. */ - public MapBean getMap() { - return map; - } - - public void setProjection(Projection proj) { - map.setProjection(proj); - } - - public Projection getProjection() { - return map.getProjection(); - } - - public static void main(String[] argv) { - Environment.init(); - Debug.init(); - - MapBean.suppressCopyright = true; - MapWindow mw = new MapWindow("OpenMap's MapWindow"); - - mw.setSize(500, 500); - - try { - mw.addTo(new com.bbn.openmap.layer.shape.ShapeLayer("share/data/shape/dcwpo-browse.shp")); - mw.addTo(new com.bbn.openmap.event.NavMouseMode2()); - mw.addTo(new com.bbn.openmap.gui.ToolPanel()); - mw.addTo(new com.bbn.openmap.gui.OMToolSet()); - - // If you want to add a ToolPanel, or an - // InformationDelegator, or anything that needs to know - // about the layout of the MapWindow frame, then you have - // to do the layout management yourself. For example: - - // ToolPanel toolPanel = new ToolPanel(); - // toolPanel.setFloatable(false); - // mw.getContentPane().add(toolPanel, BorderLayout.NORTH); - - } catch (MultipleSoloMapComponentException memce) { - - } - - mw.setVisible(true); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MenuBar.java b/src/core/src/main/java/com/bbn/openmap/gui/MenuBar.java deleted file mode 100755 index 57dfc6c38..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MenuBar.java +++ /dev/null @@ -1,193 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MenuBar.java,v $ -// $RCSfile: MenuBar.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:49:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.Serializable; -import java.util.Iterator; - -import javax.swing.JMenu; -import javax.swing.JMenuBar; - -import com.bbn.openmap.util.Debug; - -/** - * The MenuList should create and load this with the menus it it has found. - * - * If added to the MapHandler, this Menubar looks for a JMenus and adds them to - * itself. if an object implements HelpMenu, it is then added as the last - * element. - */ -public class MenuBar extends JMenuBar implements Serializable, BeanContextMembershipListener, BeanContextChild { - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Default Constructor is required to create instances at runtime - */ - public MenuBar() { - } - - /** - * Called when the MenuBar is a part of a BeanContext, and it is added to - * the BeanContext, or while other objects are added to the BeanContext - * after that. - * - * @param it Iterator - */ - protected void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof JMenu) { - add((JMenu) someObj); - } - } - - public JMenu add(JMenu someMenu) { - int menuCount = getMenuCount(); - - JMenu lastMenu = getLastMenu(); - - // Check for HelpMenu first. - if (someMenu instanceof HelpMenu) { - - // We will use it when its implementation is available. - // get the last menu and see if it is helpmenu - if (lastMenu instanceof HelpMenu) { - if (Debug.debugging("menubar")) { - Debug.output("HelpMenu already exists in MenuBar..overriding it"); - } - remove(lastMenu); - } - - // make the help menu as the last menu - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: Adding help menu at " + menuCount); - } - - super.add(someMenu); - - } else if (someMenu instanceof MenuBarMenu) { - - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: Adding Menu " + someMenu + "to index " + menuCount); - } - - if (lastMenu instanceof HelpMenu) { - remove(lastMenu); - - super.add(someMenu); - super.add(lastMenu); - - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: last menu is HelpMenu\n moving helpMenu to " + menuCount); - } - } else { - super.add(someMenu); - } - } - - return someMenu; - } - - /** - * Get the last menu item on the menu bar. If there are no menu items, it - * returns null. - */ - public JMenu getLastMenu() { - int menuCount = getMenuCount(); - if (menuCount > 0) { - return getMenu(menuCount - 1); - } else { - return null; - } - } - - /** Method for BeanContextChild interface */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - beanContextChildSupport.setBeanContext(in_bc); - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** Method for BeanContextMembership interface */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - findAndInit(it); - } - - /** Method for BeanContextMembership interface */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - public void findAndUndo(Object someObj) { - // Check for HelpMenu first. - if (someObj instanceof HelpMenu) { - setHelpMenu(null); - } else if (someObj instanceof MenuBarMenu) { - remove((Component) someObj); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MenuBarMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/MenuBarMenu.java deleted file mode 100644 index 0c298be74..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MenuBarMenu.java +++ /dev/null @@ -1,31 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MenuBarMenu.java,v $ -// $RCSfile: MenuBarMenu.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -/** - * An empty interface, used to designate a JMenu that should be added - * to the MenuBar if found within the BeanContext. - */ -public interface MenuBarMenu { -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MenuItems.java b/src/core/src/main/java/com/bbn/openmap/gui/MenuItems.java deleted file mode 100644 index a9713a82b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MenuItems.java +++ /dev/null @@ -1,41 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MenuItems.java,v $ -// $RCSfile: MenuItems.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.util.Iterator; - -/** - * This interface should be used for objects representing a group of - * MenuItem(s) that should be added to a Menu. If a Menu comes in - * contact with a MenuItems object, it will use the iterator to go - * through all of the JMenuItem objects that are contained within the - * MenuItems. - */ -public interface MenuItems { - - /** - * Get the java.util.Iterator used to retrieve all of the - * JMenuItems held inside the MenuItems object. - */ - public Iterator iterator(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MiniBrowser.java b/src/core/src/main/java/com/bbn/openmap/gui/MiniBrowser.java deleted file mode 100644 index be774c3ea..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MiniBrowser.java +++ /dev/null @@ -1,315 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MiniBrowser.java,v -// $ -// $RCSfile: MiniBrowser.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.EmptyStackException; -import java.util.Stack; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JEditorPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; -import javax.swing.text.html.HTMLDocument; -import javax.swing.text.html.HTMLFrameHyperlinkEvent; - -import com.bbn.openmap.util.Debug; - -/* - import edu.stanford.ejalbert.BrowserLauncher; - import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException; - import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException; - */ - -public class MiniBrowser extends OMComponentPanel implements ActionListener { - - JEditorPane jep; - Stack stack; - // JButton browserLaunch = null; - JButton backButton = null; - JButton dismissButton = null; - - public final static String BackCmd = "back"; - public final static String LaunchBrowserCmd = "browser"; - - public MiniBrowser(String content) { - this("text/html", content); - } - - public MiniBrowser(String mimeType, String content) { - this(null, mimeType, content); - } - - public MiniBrowser(Frame owner, String mimeType, String content) { - WindowSupport ws = init(); - push(mimeType, content); - - ws.displayInWindow(owner, 200, 200, 300, 300); - } - - public MiniBrowser(URL url) { - this(null, url); - } - - public MiniBrowser(Frame owner, URL url) { - WindowSupport ws = init(); - push(url); - - ws.displayInWindow(owner, 200, 200, 300, 300); - } - - protected WindowSupport init() { - stack = new Stack(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - // Has to happen before first push - // browserLaunch = new JButton("Open in Browser"); - URL url = this.getClass().getResource("w.gif"); - ImageIcon imageIcon = new ImageIcon(url, "Go back"); - backButton = new JButton(imageIcon); - dismissButton = new JButton("Close"); - // //// - jep = new JEditorPane(); - jep.setEditable(false); - jep.addHyperlinkListener(new HyperlinkListener() { - public void hyperlinkUpdate(HyperlinkEvent e) { - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - JEditorPane pane = (JEditorPane) e.getSource(); - - if (e instanceof HTMLFrameHyperlinkEvent) { - Debug.message("minibrowser", "processing HTMLFrameHyperlinkEvent"); - HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; - HTMLDocument doc = (HTMLDocument) pane.getDocument(); - doc.processHTMLFrameHyperlinkEvent(evt); - } else { - Debug.message("minibrowser", "processing HyperlinkEvent"); - try { - push(e.getURL()); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - } - }); - - JScrollPane jsp = new JScrollPane(jep, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - - c.gridwidth = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.BOTH; - c.anchor = GridBagConstraints.NORTHWEST; - c.insets = new Insets(5, 5, 5, 5); - c.weightx = 1; - c.weighty = 1; - gridbag.setConstraints(jsp, c); - add(jsp); - - JPanel buttonPanel = new JPanel(); - GridBagLayout gridbag2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - buttonPanel.setLayout(gridbag2); - - c2.fill = GridBagConstraints.NONE; - c2.anchor = GridBagConstraints.WEST; - c2.weightx = 0; - c2.weighty = 0; - - backButton.setActionCommand(BackCmd); - backButton.addActionListener(this); - backButton.setEnabled(false); - gridbag2.setConstraints(backButton, c2); - buttonPanel.add(backButton); - - /** - * browserLaunch.setActionCommand(LaunchBrowserCmd); - * browserLaunch.addActionListener(this); - * browserLaunch.setVisible(false); - * gridbag2.setConstraints(browserLaunch, c2); - * buttonPanel.add(browserLaunch); - */ - WindowSupport ws = new WindowSupport(this, ""); - - c2.anchor = GridBagConstraints.EAST; - c2.weightx = 1; - dismissButton.setActionCommand(WindowSupport.KillWindowCmd); - dismissButton.addActionListener(ws); - gridbag2.setConstraints(dismissButton, c2); - buttonPanel.add(dismissButton); - - // ////////// - - c.fill = GridBagConstraints.HORIZONTAL; - c.anchor = GridBagConstraints.WEST; - c.weightx = 1; - c.weighty = 0; - c.gridy = 1; - - gridbag.setConstraints(buttonPanel, c); - add(buttonPanel); - - // Call displayInWindow on this. - return ws; - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - - try { - if (command == BackCmd) { - stack.pop(); - ((MiniBrowserPage) stack.peek()).loadInto(jep); - if (stack.size() <= 1) { - backButton.setEnabled(false); - } - }/* - * else if (command == LaunchBrowserCmd) { ((MiniBrowserPage) - * stack.peek()).launchInBrowser(); } - */ - } catch (EmptyStackException ese) { - backButton.setEnabled(false); - } catch (IOException ioe) { - } - } - - protected void push(URL newPage) { - Debug.message("minibrowser", "push(URL)"); - push(new MiniBrowserPage(newPage)); - } - - protected void push(String mimeType, String content) { - Debug.message("minibrowser", "push(String)"); - push(new MiniBrowserPage(mimeType, content)); - } - - protected void push(MiniBrowserPage mbp) { - try { - mbp.loadInto(jep); - stack.push(mbp); - if (stack.size() > 1) { - backButton.setEnabled(true); - } - } catch (IOException ioe) { - } - } - - /* - * protected void enableBrowserLaunch(boolean set) { - * browserLaunch.setVisible(set); invalidate(); } - */ - - protected void finalize() { - Debug.message("minibrowser", "MiniBrowser getting gc'd"); - } - - public static void display(String content) { - display("text/html", content); - } - - public static void display(String mimeType, String content) { - display(null, mimeType, content); - } - - public static void display(Frame owner, String mimeType, String content) { - new MiniBrowser(owner, mimeType, content); - } - - public static void display(URL url) { - display(null, url); - } - - public static void display(Frame owner, URL url) { - new MiniBrowser(owner, url); - } - - public static void main(String[] argv) { - if (argv.length > 0) { - try { - new MiniBrowser(new URL(argv[0])); - } catch (MalformedURLException murle) { - new MiniBrowser("text/html", argv[0]); - } - } else { - new MiniBrowser("text/html", "String link to the OpenMap web site"); - } - } - - public class MiniBrowserPage { - String content = null; - String mimeType = null; - URL url = null; - - // BrowserLauncher browserLauncher; - - public MiniBrowserPage(String mt, String stuff) { - mimeType = mt; - content = stuff; - } - - public MiniBrowserPage(URL page) { - url = page; - } - - public void loadInto(JEditorPane jep) throws IOException { - if (isURL()) { - Debug.message("minibrowser", "loadInto(URL)"); - jep.setPage(url); - // enableBrowserLaunch(true); - jep.updateUI(); - } else { - Debug.message("minibrowser", "loadInto(String)"); - jep.setContentType(mimeType); - jep.setText(content); - // enableBrowserLaunch(false); - jep.updateUI(); - } - } - - /** - * public void launchInBrowser() { if (isURL()) { try { browserLauncher - * = new BrowserLauncher(); - * browserLauncher.openURLinBrowser(url.toString()); } catch - * (BrowserLaunchingInitializingException e) { // TODO Auto-generated - * catch block e.printStackTrace(); } catch - * (UnsupportedOperatingSystemException e) { // TODO Auto-generated - * catch block e.printStackTrace(); } } } - */ - public boolean isURL() { - return url != null; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MouseModeButtonPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/MouseModeButtonPanel.java deleted file mode 100644 index d62e23586..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MouseModeButtonPanel.java +++ /dev/null @@ -1,174 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MouseModeButtonPanel.java,v $ -// $RCSfile: MouseModeButtonPanel.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.beans.PropertyChangeEvent; -import java.util.HashMap; - -import javax.swing.ButtonGroup; -import javax.swing.Icon; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.MapMouseMode; - -/** - * The MouseModeButtonPanel is an alternative to the MouseModePanel. Instead of - * providing an option menu listing all the MouseModes, a series of buttons for - * all the MouseModes is displayed. - * - * The MouseModeButtonPanel asks the MapMouseModes for their GUI icons. If they - * don't have one, their ID Strin will be used. - */ -public class MouseModeButtonPanel extends MouseModePanel { - - private JToolBar toolBar = null; - /** for initialization, false */ - protected boolean floatable = false; - /** - * to turn a button on when the active mouse mode changes behind the scenes. - */ - protected HashMap buttonSet = new HashMap(); - - protected JToggleButton enabledButton = null; - - public final static String defaultKey = "mousemodebuttonpanel"; - - public MouseModeButtonPanel() { - super(); - setKey(defaultKey); - } - - /** - * Method overrides MouseModePane.setPanel. Construct the toolbar buttons - * from the mouse modes that are handled by the delegator. - */ - protected void setPanel(MouseDelegator md) { - if (toolBar != null) { - remove(toolBar); // remove it - } - - reset(); - if (md == null) { - return; - } - - toolBar = new JToolBar(); // Create a new one - toolBar.setFloatable(floatable); - String activeMode = md.getActiveMouseModeID(); - - ButtonGroup bg = new ButtonGroup(); - - MapMouseMode[] modes = md.getMouseModes(); - for (int i = 0; i < modes.length; i++) { - String modeStr = modes[i].getID(); - boolean on = (modeStr == null && activeMode == null) - || (modeStr != null && modeStr.equals(activeMode)); - - JToggleButton btn; - Icon icon = modes[i].getGUIIcon(); - - if (icon != null) { - btn = new JToggleButton(icon, on); - } else { - btn = new JToggleButton(modeStr, on); - } - - if (on) { - enabledButton = btn; - } - - buttonSet.put(modeStr, btn); - - bg.add(btn); - btn.setToolTipText(modes[i].getPrettyName()); - toolBar.add(btn); - btn.setActionCommand(modeStr); - btn.addActionListener(this); - - btn.setVisible(modes[i].isVisible()); - } - - this.add(toolBar); - this.revalidate(); - } // End of setPanel() - - /** - * actionPerformed - Handle the mouse clicks on the button(s) - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - - if (mouseDelegator == null) { - return; - } else { - mouseDelegator.setActiveMouseModeWithID(e.getActionCommand()); - } - } - - /** - * Set whether the MouseModeButtonPanel can be detached. - */ - public void setFloatable(boolean floatable) { - this.floatable = floatable; - toolBar.setFloatable(floatable); - } - - /** - * Get whether the MouseModeButtonPanel can be detached. - */ - public boolean getFloatable() { - return toolBar.isFloatable(); - } - - // ////////////////////////////////////////////////////////////////////////// - /** - * propertyChange - Listen for changes to the active mouse mode and for any - * changes to the list of available mouse modes. - */ - public void propertyChange(PropertyChangeEvent evt) { - - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - String mmID = ((MapMouseMode) evt.getNewValue()).getID(); - - JToggleButton btn = (JToggleButton) buttonSet.get(mmID); - if (btn != null) { - btn.setSelected(true); - enabledButton = btn; - } - - } else if (evt.getPropertyName() == MouseDelegator.MouseModesProperty) { - toolBar.removeAll(); - setPanel(mouseDelegator); - } - } // End of propertyChange() - - public void reset() { - if (toolBar != null) { - remove(toolBar); - toolBar = null; - } - enabledButton = null; - buttonSet.clear(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/MouseModePanel.java b/src/core/src/main/java/com/bbn/openmap/gui/MouseModePanel.java deleted file mode 100644 index b92fc1fe0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/MouseModePanel.java +++ /dev/null @@ -1,257 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MouseModePanel.java,v $ -// $RCSfile: MouseModePanel.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - - -package com.bbn.openmap.gui; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.util.Debug; - - -/** - * MouseModePanel displays the mouse modes available to the map, as a - * popup option menu. - */ -public class MouseModePanel extends OMToolComponent - implements Serializable, ActionListener, PropertyChangeListener { - - public final static transient String mouseModeCmd = "setMouseMode"; - public final static transient String newMouseModeCmd = "newMouseMode"; - public final static transient String defaultKey = "mousemodepanel"; - - protected transient JButton titleButton; - protected transient JPopupMenu rbs = null; - protected transient MouseDelegator mouseDelegator; - protected transient TitledBorder border=null; - protected transient Dimension dim; - - /** - * For use with the MapHandler (BeanContext) object. The - * MouseDelegator will be found if it's added to the MapHandler, - * and will get set automatically. - */ - public MouseModePanel() { - super(); - setKey(defaultKey); - } - - /** - * @param md the map's MouseDelegator object. - */ - public MouseModePanel(MouseDelegator md) { - this(); - setMouseDelegator(md); - } - - /** - * Set the MouseDelegator used to hold the different MouseModes - * available to the map. - */ - public void setMouseDelegator(MouseDelegator md) { - - if (mouseDelegator != null) { - mouseDelegator.removePropertyChangeListener(this); - setPanel(null); - } - - mouseDelegator=md; - - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - - if (mouseDelegator == null) { - return; - } - - mouseDelegator.addPropertyChangeListener(this); - setPanel(mouseDelegator); - } - - /** - * Get the MouseDelegator used to control mouse gestures over the - * map. - */ - public MouseDelegator getMouseDelegator() { - return mouseDelegator; - } - - /** - * Given a MouseDelegator, set up the pop-up menu to reflect the - * MouseMode choices. - */ - protected void setPanel(MouseDelegator md) { - if (titleButton != null) { - remove(titleButton); - } - titleButton = new JButton(); - titleButton.addActionListener(this); - - String activeMode = md.getActiveMouseModeID(); - MapMouseMode[] modes = md.getMouseModes(); - - rbs = new JPopupMenu("Mouse Modes"); - dim = titleButton.getMinimumSize(); - for (int i=0; i 0) { - border = new TitledBorder(new EtchedBorder(), "Mouse Mode"); - setBorder(border); - } - - titleButton.setActionCommand(mouseModeCmd); - titleButton.setBorderPainted(false); - add(titleButton); - // HACK - the button keeps changing size depending on which - // choice is made. I'd like to set the size based on the - // size of the largest mouse mode name, but I can't figure out - // when that's available, before we actually have to present - // the button. - this.setPreferredSize(new Dimension(140, 45)); - this.revalidate(); - } - - - - public void actionPerformed(java.awt.event.ActionEvent e) { - - if (mouseDelegator == null) { - return; - } - - String command = e.getActionCommand(); - if (command.equals(mouseModeCmd)) { - Point loc = titleButton.getLocation(new Point(0,0)); - rbs.show(titleButton, loc.x, loc.y); - } else if (command.equals(newMouseModeCmd)) { - JMenuItem rb = (JMenuItem)(e.getSource()); - if (Debug.debugging("mousemode")){ - Debug.output("MouseModePanel.actionPerformed: " + rb.getName()); - } - mouseDelegator.setActiveMouseModeWithID(rb.getName()); - } - } - - /** - * Listen for changes to the active mouse mode and for any changes - * to the list of available mouse modes - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - String mmID = ((MapMouseMode)evt.getNewValue()).getPrettyName(); - if (Debug.debugging("mousemode")){ - Debug.output("propertyChange: action mode property " + mmID); - } - titleButton.setText(mmID); - } else if (evt.getPropertyName() == MouseDelegator.MouseModesProperty) { - // This won't work if prettyNames for the mouse modes are - // different than the ID. That's why the - // MouseModeButtonListener has been added to the class, - // and is used instead. - Debug.message("mousemode", "propertyChange: mouse modes property"); - rbs.removeAll(); - setPanel(mouseDelegator); - } - } - - /** - * Called when a component that is needed, and not available with - * an appropriate iterator from the BeanContext. This lets this - * object hook up with what it needs. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MouseDelegator) { - // do the initializing that need to be done here - Debug.message("mousemodepanel","MouseModePanel found a MouseDelegator."); - setMouseDelegator((MouseDelegator)someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when an object - * has been removed from the parent BeanContext. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MouseDelegator) { - // do the initializing that need to be done here - Debug.message("mousemodepanel","MouseModePanel removing MouseDelegator."); - if (someObj == getMouseDelegator()) { - setMouseDelegator(null); - } - } - } - - public static class MouseModeButtonListener implements ActionListener { - String mmid = null; - MouseModePanel mouseModePanel = null; - - public MouseModeButtonListener(String id, MouseModePanel mmp) { - mmid = id; - mouseModePanel = mmp; - } - - public void actionPerformed(ActionEvent ae) { - if (mouseModePanel != null) { - MouseDelegator md = mouseModePanel.getMouseDelegator(); - if (md != null) { - md.setActiveMouseModeWithID(mmid); - } - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/NavigateMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/NavigateMenu.java deleted file mode 100644 index 47ea9f81d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/NavigateMenu.java +++ /dev/null @@ -1,159 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/NavigateMenu.java,v $ -// $RCSfile: NavigateMenu.java,v $ -// $Revision: 1.10 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JMenu; -import javax.swing.JMenuItem; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.event.ZoomSupport; -import com.bbn.openmap.gui.menu.CoordsMenuItem; -import com.bbn.openmap.gui.menu.ProjectionMenu; -import com.bbn.openmap.util.Debug; - -/** - * Provides MenuItems that lets users control the projection. This - * includes providing a means to call up the Coordinate Window to let - * users enter coordinates to center the map, a projection choice - * menu, and zooming choices. - */ -public class NavigateMenu extends AbstractOpenMapMenu implements ActionListener { - - public static final String defaultText = "Navigate"; - public static final String defaultMnemonic = "N"; - - protected ZoomSupport zoomSupport = new ZoomSupport(this); - public final static transient String zoomIn2Cmd = "zoomIn2Cmd"; - public final static transient String zoomIn4Cmd = "zoomIn4Cmd"; - public final static transient String zoomOut2Cmd = "zoomOut2Cmd"; - public final static transient String zoomOut4Cmd = "zoomOut4Cmd"; - - /** - * This constructor automatically configures the Menu to have - * choices to bring up the Coordinates Window, the projection - * choice menu, and the zoom menus. - */ - public NavigateMenu() { - super(); - setText(i18n.get(this, "navigate", defaultText)); -// setMnemonic(i18n.get(this, "navigate", I18n.MNEMONIC, defaultMnemonic) -// .charAt(0)); - add(new CoordsMenuItem()); - - JMenuItem mi; - JMenu submenu = (JMenu) add(new JMenu(i18n.get(this, - "zoomIn", - "Zoom In"))); - mi = (JMenuItem) submenu.add(new JMenuItem(i18n.get(this, - "zoomIn2X", - "2X"))); - mi.setActionCommand(zoomIn2Cmd); - mi.addActionListener(this); - mi = (JMenuItem) submenu.add(new JMenuItem(i18n.get(this, - "zoomIn4X", - "4X"))); - mi.setActionCommand(zoomIn4Cmd); - mi.addActionListener(this); - - submenu = (JMenu) add(new JMenu(i18n.get(this, "zoomOut", "Zoom Out"))); - mi = (JMenuItem) submenu.add(new JMenuItem(i18n.get(this, - "zoomOut2X", - "2X"))); - mi.setActionCommand(zoomOut2Cmd); - mi.addActionListener(this); - mi = (JMenuItem) submenu.add(new JMenuItem(i18n.get(this, - "zoomOut4X", - "4X"))); - mi.setActionCommand(zoomOut4Cmd); - mi.addActionListener(this); - - add(new ProjectionMenu()); - } - - /** - * ActionListener interface, lets the Menu act on the actions of - * the MenuItems. - */ - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - - Debug.message("navigatemenu", "NavigateMenu.actionPerformed(): " - + command); - - if (command.equals(zoomIn2Cmd)) { - fireZoom(ZoomEvent.RELATIVE, 0.5f); - } else if (command.equals(zoomIn4Cmd)) { - fireZoom(ZoomEvent.RELATIVE, 0.25f); - } else if (command.equals(zoomOut2Cmd)) { - fireZoom(ZoomEvent.RELATIVE, 2.0f); - } else if (command.equals(zoomOut4Cmd)) { - fireZoom(ZoomEvent.RELATIVE, 4.0f); - } - } - - /*---------------------------------------------------------------------- - * Zoom Support - for broadcasting zoom events - *---------------------------------------------------------------------- - */ - - /** - * - */ - public synchronized void addZoomListener(ZoomListener l) { - zoomSupport.add(l); - } - - /** - * - */ - public synchronized void removeZoomListener(ZoomListener l) { - zoomSupport.remove(l); - } - - /** - * - */ - public void fireZoom(int zoomType, float amount) { - zoomSupport.fireZoom(zoomType, amount); - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof MapBean) { - addZoomListener((MapBean) someObj); - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof MapBean) { - removeZoomListener((MapBean) someObj); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/NavigatePanel.java b/src/core/src/main/java/com/bbn/openmap/gui/NavigatePanel.java deleted file mode 100644 index 0b98277d1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/NavigatePanel.java +++ /dev/null @@ -1,366 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/NavigatePanel.java,v $ -// $RCSfile: NavigatePanel.java,v $ -// $Revision: 1.11 $ -// $Date: 2005/08/10 21:30:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.net.URL; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.event.PanListener; -import com.bbn.openmap.event.PanSupport; -import com.bbn.openmap.util.Debug; - -/** - * A Navigation Rosette Bean. This bean is a source for PanEvents and - * CenterEvents. - */ -public class NavigatePanel extends OMToolComponent implements Serializable, - ActionListener { - - public final static String panNWCmd = "panNW"; - public final static String panNCmd = "panN"; - public final static String panNECmd = "panNE"; - public final static String panECmd = "panE"; - public final static String panSECmd = "panSE"; - public final static String panSCmd = "panS"; - public final static String panSWCmd = "panSW"; - public final static String panWCmd = "panW"; - public final static String centerCmd = "center"; - - protected transient JButton nwButton = null; - protected transient JButton nButton = null; - protected transient JButton neButton = null; - protected transient JButton eButton = null; - protected transient JButton seButton = null; - protected transient JButton sButton = null; - protected transient JButton swButton = null; - protected transient JButton wButton = null; - protected transient JButton cButton = null; - - // default icon names - protected static String nwName = "nw.gif"; - protected static String nName = "n.gif"; - protected static String neName = "ne.gif"; - protected static String eName = "e.gif"; - protected static String seName = "se.gif"; - protected static String sName = "s.gif"; - protected static String swName = "sw.gif"; - protected static String wName = "w.gif"; - protected static String cName = "center.gif"; - - protected PanSupport panDelegate; - protected CenterSupport centerDelegate; - protected boolean useTips = false; - protected float panFactor = 1f; - - // protected int height = 0; // calculated - // protected int width = 0; // calculated - - protected boolean useDefaultCenter = false; - protected float defaultCenterLat = 0; - protected float defaultCenterLon = 0; - - public final static String defaultKey = "navigatepanel"; - - /** - * Construct the NavigationPanel. - */ - public NavigatePanel() { - super(); - setKey(defaultKey); - panDelegate = new PanSupport(this); - centerDelegate = new CenterSupport(this); - - JPanel panel = new JPanel(); - GridBagLayout internalGridbag = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - panel.setLayout(internalGridbag); - - // begin top row - String info = i18n.get(NavigatePanel.class, - "panNW.tooltip", - "Pan Northwest"); - nwButton = getButton(nwName, info, panNWCmd); - c2.gridx = 0; - c2.gridy = 0; - internalGridbag.setConstraints(nwButton, c2); - panel.add(nwButton); - - info = i18n.get(NavigatePanel.class, "panN.tooltip", "Pan North"); - nButton = getButton(nName, info, panNCmd); - c2.gridx = 1; - c2.gridy = 0; - internalGridbag.setConstraints(nButton, c2); - panel.add(nButton); - - info = i18n.get(NavigatePanel.class, "panNE.tooltip", "Pan Northeast"); - neButton = getButton(neName, info, panNECmd); - c2.gridx = 2; - c2.gridy = 0; - internalGridbag.setConstraints(neButton, c2); - panel.add(neButton); - - // begin middle row - info = i18n.get(NavigatePanel.class, "panW.tooltip", "Pan West"); - wButton = getButton(wName, info, panWCmd); - c2.gridx = 0; - c2.gridy = 1; - internalGridbag.setConstraints(wButton, c2); - panel.add(wButton); - - info = i18n.get(NavigatePanel.class, - "center.tooltip", - "Center Map at Starting Coords"); - cButton = getButton(cName, info, centerCmd); - c2.gridx = 1; - c2.gridy = 1; - internalGridbag.setConstraints(cButton, c2); - panel.add(cButton); - - info = i18n.get(NavigatePanel.class, "panE.tooltip", "Pan East"); - eButton = getButton(eName, info, panECmd); - c2.gridx = 2; - c2.gridy = 1; - internalGridbag.setConstraints(eButton, c2); - panel.add(eButton); - - // begin bottom row - info = i18n.get(NavigatePanel.class, "panSW.tooltip", "Pan Southwest"); - swButton = getButton(swName, info, panSWCmd); - c2.gridx = 0; - c2.gridy = 2; - internalGridbag.setConstraints(swButton, c2); - panel.add(swButton); - - info = i18n.get(NavigatePanel.class, "panS.tooltip", "Pan South"); - sButton = getButton(sName, info, panSCmd); - c2.gridx = 1; - c2.gridy = 2; - internalGridbag.setConstraints(sButton, c2); - panel.add(sButton); - - info = i18n.get(NavigatePanel.class, "panSE.tooltip", "Pan Southeast"); - seButton = getButton(seName, info, panSECmd); - c2.gridx = 2; - c2.gridy = 2; - internalGridbag.setConstraints(seButton, c2); - panel.add(seButton); - - add(panel); - } - - /** - * Add the named button to the panel. - * - * @param name GIF image name - * @param info ToolTip text - * @param command String command name - * - */ - protected JButton getButton(String name, String info, String command) { - URL url = NavigatePanel.class.getResource(name); - ImageIcon icon = new ImageIcon(url, info); - JButton b = new JButton(icon); - b.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight())); - b.setToolTipText(info); - b.setMargin(new Insets(0, 0, 0, 0)); - b.setActionCommand(command); - b.addActionListener(this); - b.setBorderPainted(Debug.debugging("layout")); - b.setOpaque(false); - return b; - } - - /** - * Add a CenterListener. - * - * @param listener CenterListener - */ - public synchronized void addCenterListener(CenterListener listener) { - centerDelegate.add(listener); - } - - /** - * Remove a CenterListener - * - * @param listener CenterListener - */ - public synchronized void removeCenterListener(CenterListener listener) { - centerDelegate.remove(listener); - } - - /** - * Add a PanListener. - * - * @param listener PanListener - */ - public synchronized void addPanListener(PanListener listener) { - panDelegate.add(listener); - } - - /** - * Remove a PanListener - * - * @param listener PanListener - */ - public synchronized void removePanListener(PanListener listener) { - panDelegate.remove(listener); - } - - /** - * Fire a CenterEvent. - */ - protected synchronized void fireCenterEvent(float lat, float lon) { - centerDelegate.fireCenter(lat, lon); - } - - /** - * Fire a PanEvent. - * - * @param az azimuth east of north - */ - protected synchronized void firePanEvent(float az) { - panDelegate.firePan(az); - } - - /** - * Get the pan factor. - *

- * The panFactor is the amount of screen to shift when panning in - * a certain direction: 0=none, 1=half-screen shift. - * - * @return float panFactor (0.0 <= panFactor <= 1.0) - */ - public float getPanFactor() { - return panFactor; - } - - /** - * Set the pan factor. - *

- * This defaults to 1.0. The panFactor is the amount of screen to - * shift when panning in a certain direction: 0=none, - * 1=half-screen shift. - * - * @param panFactor (0.0 <= panFactor <= 1.0) - */ - public void setPanFactor(float panFactor) { - if ((panFactor < 0f) || (panFactor > 1f)) { - throw new IllegalArgumentException("should be: (0.0 <= panFactor <= 1.0)"); - } - this.panFactor = panFactor; - } - - /** - * Use this function to set where you want the map projection to - * pan to when the user clicks on "center" button on the - * navigation panel. The scale does not change. When you call this - * function, the projection does not change. - * - * @param passedLat float the center latitude (in degrees) - * @param passedLon float the center longitude (in degrees) - */ - public void setDefaultCenter(float passedLat, float passedLon) { - useDefaultCenter = true; - defaultCenterLat = passedLat; - defaultCenterLon = passedLon; - } - - /** - * ActionListener Interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - - String command = e.getActionCommand(); - - Debug.message("navpanel", "NavigatePanel.actionPerformed(): " + command); - if (command.equals(panNWCmd)) { - firePanEvent(-45f); - } else if (command.equals(panNCmd)) { - firePanEvent(0f); - } else if (command.equals(panNECmd)) { - firePanEvent(45f); - } else if (command.equals(panECmd)) { - firePanEvent(90f); - } else if (command.equals(panSECmd)) { - firePanEvent(135f); - } else if (command.equals(panSCmd)) { - firePanEvent(180f); - } else if (command.equals(panSWCmd)) { - firePanEvent(-135f); - } else if (command.equals(panWCmd)) { - firePanEvent(-90f); - } else if (command.equals(centerCmd)) { - // go back to the center point - - float lat; - float lon; - if (useDefaultCenter) { - lat = defaultCenterLat; - lon = defaultCenterLon; - } else { - lat = Environment.getFloat(Environment.Latitude, 0f); - lon = Environment.getFloat(Environment.Longitude, 0f); - } - fireCenterEvent(lat, lon); - } - } - - // ///////////////////////////////////////////////////////////////////////// - - // // OMComponentPanel methods to make the tool work with - // // the MapHandler to find objects it needs. - // ///////////////////////////////////////////////////////////////////////// - - public void findAndInit(Object obj) { - if (obj instanceof PanListener) { - addPanListener((PanListener) obj); - } - if (obj instanceof CenterListener) { - addCenterListener((CenterListener) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof PanListener) { - removePanListener((PanListener) obj); - } - if (obj instanceof CenterListener) { - removeCenterListener((CenterListener) obj); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OMComponentPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/OMComponentPanel.java deleted file mode 100644 index 7b46c0cad..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OMComponentPanel.java +++ /dev/null @@ -1,317 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OMComponentPanel.java,v $ -// $RCSfile: OMComponentPanel.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/03/06 15:41:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.Properties; - -import javax.swing.JPanel; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.I18n; - -/** - * The OMComponentPanel is a convenient super class intended to provide an easy - * way to extend JPanel while also implementing the common functions of an - * OMComponent (PropertyConsumer, BeanContextMembershipListener and - * BeanContextChild). The PropertyListener methods in the BeanContextChild - * aren't needed, because the java.awt.Component provides them. - */ -public abstract class OMComponentPanel extends JPanel implements - PropertyConsumer, BeanContextChild, BeanContextMembershipListener, - LightMapHandlerChild { - - /** - * All OMComponentPanels have access to an I18n object, which is provided by - * the Environment. - */ - protected I18n i18n = Environment.getI18n(); - - protected int orientation = SwingConstants.HORIZONTAL; - - /** - * A boolean that prevents the BeanContextChild from looking at events from - * BeanContext other than the one it was originally added to. Set to false - * by default. - */ - protected boolean isolated = false; - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(this); - - protected OMComponentPanel() { - super(); - } - - protected WindowSupport windowSupport; - - public void setWindowSupport(WindowSupport ws) { - windowSupport = ws; - } - - public WindowSupport getWindowSupport() { - return windowSupport; - } - - // ///////////////////////////////////////////////////////////////////////// - // // PropertyConsumer methods - // ///////////////////////////////////////////////////////////////////////// - - /** - * Token uniquely identifying this components in the application properties. - */ - protected String propertyPrefix = null; - - /** - * Sets the properties for the OMComponent. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the OMComponent. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - setPropertyPrefix(prefix); - - // String realPrefix = - // PropUtils.getScopedPropertyPrefix(prefix); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the OMComponent. If the component has a propertyPrefix - * set, the property keys should have that prefix plus a separating '.' - * prepended to each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - // String prefix = - // PropUtils.getScopedPropertyPrefix(propertyPrefix); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix for the panel - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - // ///////////////////////////////////////////////////////////////////////// - // // MapHandlerChild methods to make the tool work with - // // the MapHandler to find any SelectionProviders. - // ///////////////////////////////////////////////////////////////////////// - - public void findAndInit(Object obj) {} - - public void findAndUndo(Object obj) {} - - /** - * This is the method that your object can use to find other objects within - * the MapHandler (BeanContext). This method gets called when the object - * gets added to the MapHandler, or when another object gets added to the - * MapHandler after the object is a member. - * - * @param it Iterator to use to go through a list of objects. Find the ones - * you need, and hook yourself up. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is added - * to the BeanContext of this object. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - if (!isolated || bcme.getBeanContext().equals(getBeanContext())) { - findAndInit(bcme.iterator()); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Adds this object as a - * BeanContextMembership listener, set the BeanContext in this objects - * BeanContextSupport, and receives the initial list of objects currently - * contained in the BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - if (!isolated || beanContextChildSupport.getBeanContext() == null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to add a listener to this object's property. This listener wants to have - * the right to veto a property change. - */ - public void addVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to remove a listener to this object's property. The listener has the - * power to veto property changes. - */ - public void removeVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, - in_vcl); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - super.fireVetoableChange(name, oldValue, newValue); - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - public int getOrientation() { - return orientation; - } - - public void setOrientation(int orientation) { - this.orientation = orientation; - } - - public boolean isIsolated() { - return isolated; - } - - public void setIsolated(boolean isolated) { - this.isolated = isolated; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OMControlPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/OMControlPanel.java deleted file mode 100644 index 29e604ea7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OMControlPanel.java +++ /dev/null @@ -1,207 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OMControlPanel.java,v $ -// $RCSfile: OMControlPanel.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Properties; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JPanel; - -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMControlPanel is an all-in-one panel that holds an overview - * map, pan and zoom buttons, projection stack buttons, scale text - * field and a LayersPanel. All of the sub-components share the same - * property prefix as the OMControlPanel, all have access to - * components in the MapHandler. The sub-components are not given to - * the MapHandler themselves, however. - */ -public class OMControlPanel extends OMComponentPanel implements MapPanelChild { - - LinkedList children = new LinkedList(); - - public OMControlPanel() { - - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - - JPanel navBox = new JPanel(); - navBox.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); - navBox.setLayout(new BorderLayout()); - - OverviewMapHandler overviewMap = new OverviewMapHandler(); - overviewMap.setUseAsTool(false); - overviewMap.setPreferredSize(new Dimension(100, 100)); - overviewMap.setBorder(BorderFactory.createRaisedBevelBorder()); - overviewMap.setPropertyPrefix("OverviewMapHandler"); - children.add(overviewMap); - - NavigatePanel navPanel = new NavigatePanel(); - navPanel.setPropertyPrefix("NavigatePanel"); - ZoomPanel zoomPanel = new ZoomPanel(); - zoomPanel.setPropertyPrefix("ZoomPanel"); - ProjectionStackTool projStack = new ProjectionStackTool(); - projStack.setPropertyPrefix("ProjectionStackTool"); - ScaleTextPanel scalePanel = new ScaleTextPanel(); - scalePanel.setPropertyPrefix("ScaleTextPanel"); - scalePanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); - - JPanel navBoxRN = new JPanel(); - children.add(navPanel); - navBoxRN.add(navPanel); - navBoxRN.add(Box.createHorizontalGlue()); - children.add(zoomPanel); - navBoxRN.add(zoomPanel); - - JPanel navBoxRS = new JPanel(); - navBoxRS.setLayout(new BorderLayout()); - children.add(projStack); - children.add(scalePanel); - navBoxRS.add(projStack, BorderLayout.NORTH); - navBoxRS.add(scalePanel, BorderLayout.SOUTH); - - JPanel navBoxR = new JPanel(); - navBoxR.setLayout(new BorderLayout()); - navBoxR.add(navBoxRN, BorderLayout.NORTH); - navBoxR.add(navBoxRS, BorderLayout.SOUTH); - - navBox.add(overviewMap, BorderLayout.CENTER); - navBox.add(navBoxR, BorderLayout.EAST); - - add(navBox); - - LayersPanel layersPanel = new LayersPanel(); - layersPanel.setPropertyPrefix("LayersPanel"); - layersPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); - children.add(layersPanel); - add(layersPanel); - validate(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String pl = props.getProperty(prefix + PreferredLocationProperty); - if (pl != null) { - setPreferredLocation(pl); - } - - Iterator it = children.iterator(); - while (it.hasNext()) { - Object obj = it.next(); - if (obj instanceof PropertyConsumer) { - // Each property prefix will be set with the marker - // name for the OMControlPanel plus the class name - // already set as property prefix in the constructor. - String newPrefix = prefix - + ((PropertyConsumer) obj).getPropertyPrefix(); - ((PropertyConsumer) obj).setProperties(newPrefix, props); - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - props.put(PropUtils.getScopedPropertyPrefix(this) - + PreferredLocationProperty, getPreferredLocation()); - - Iterator it = children.iterator(); - while (it.hasNext()) { - Object obj = it.next(); - if (obj instanceof PropertyConsumer) { - ((PropertyConsumer) obj).getProperties(props); - } - } - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - props.put(PreferredLocationProperty, - "The preferred BorderLayout direction to place this component."); - - Iterator it = children.iterator(); - while (it.hasNext()) { - Object obj = it.next(); - if (obj instanceof PropertyConsumer) { - ((PropertyConsumer) obj).getPropertyInfo(props); - } - } - return props; - } - - public void findAndInit(Object someObj) { - Iterator it = children.iterator(); - while (it.hasNext()) { - Object obj = it.next(); - if (obj instanceof LightMapHandlerChild) { - ((LightMapHandlerChild) obj).findAndInit(someObj); - } - } - } - - public void findAndUndo(Object someObj) { - Iterator it = children.iterator(); - while (it.hasNext()) { - Object obj = it.next(); - if (obj instanceof LightMapHandlerChild) { - ((LightMapHandlerChild) obj).findAndUndo(someObj); - } - } - } - - /** - * BorderLayout.WEST by default for this class. - */ - protected String preferredLocation = java.awt.BorderLayout.WEST; - - /** - * MapPanelChild method. - */ - public void setPreferredLocation(String value) { - preferredLocation = value; - } - - /** - * MapPanelChild method. - */ - public String getPreferredLocation() { - return preferredLocation; - } - - public String getParentName() { - // TODO Auto-generated method stub - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OMGraphicDeleteTool.java b/src/core/src/main/java/com/bbn/openmap/gui/OMGraphicDeleteTool.java deleted file mode 100644 index cc54efe4a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OMGraphicDeleteTool.java +++ /dev/null @@ -1,207 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OMGraphicDeleteTool.java,v $ -// $RCSfile: OMGraphicDeleteTool.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.event.SelectionEvent; -import com.bbn.openmap.omGraphics.event.SelectionListener; -import com.bbn.openmap.omGraphics.event.SelectionProvider; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * The OMGraphicDeleteTool is a Swing component that contains a button that - * listens for notifications that tell it that an OMGraphic has been 'selected', - * and provides the capability to delete that OMGraphic from the component that - * manages it. The OMGraphicDeleteTool gathers SelectionEvents, which provide it - * information about the OMGraphic and the DrawingToolRequestor that can delete - * it from the map. If multiple events are received, pressing the button will - * cause notifications to be sent to all the DrawingToolRequestors to delete all - * the OMGraphics that are currently selected. This component is also a - * com.bbn.openmap.gui.Tool, so if the ToolPanel sees it in the MapHandler, the - * button will automatically be added to it. - *

- * To add the button to the OpenMap application, it just needs to be added to - * the openmap.components property in the openmap.properties file. - */ -public class OMGraphicDeleteTool extends OMToolComponent implements SelectionListener, - ActionListener, KeyListener { - - protected JButton deleteButton = null; - protected String defaultKey = "omgraphicdeletetool"; - - protected Hashtable deleteList; - protected List requestors; - protected JToolBar jToolBar; - - public OMGraphicDeleteTool() { - super(); - setKey(defaultKey); - Debug.message("deletebutton", "OMGTL()"); - - setLayout(new java.awt.GridLayout()); - jToolBar = new JToolBar(); - jToolBar.setFloatable(false); - - deleteList = new Hashtable(); - requestors = new ArrayList(); - - java.net.URL url = this.getClass().getResource("delete.gif"); - if (url != null) { - ImageIcon icon = new ImageIcon(url); - deleteButton = new JButton(icon); - } else { - deleteButton = new JButton("Delete"); - } - - deleteButton.addActionListener(this); - // deleteButton.setToolTipText("Delete selected map graphic"); - deleteButton.setToolTipText(i18n.get(OMGraphicDeleteTool.class, "deleteButton", I18n.TOOLTIP, "Delete selected map graphic")); - deleteButton.setEnabled(false); - - jToolBar.add(deleteButton); - add(jToolBar); - } - - public void keyPressed(KeyEvent e) { - } - - public void keyReleased(KeyEvent e) { - if ((e.getKeyCode() == KeyEvent.VK_BACK_SPACE) || (e.getKeyCode() == KeyEvent.VK_DELETE)) { - deleteSelected(); - } - } - - public void keyTyped(KeyEvent e) { - } - - public void actionPerformed(ActionEvent ae) { - Debug.message("deletebutton", "OMGDT.actionPerformed()"); - deleteSelected(); - } - - public void deleteSelected() { - - for (SelectionEvent item : deleteList.values()) { - Object itemSource = item.getSource(); - - // Too specific? - if (itemSource instanceof OMDrawingTool) { - // This should notify the requestor... - ((OMDrawingTool) itemSource).deactivate(OMGraphicConstants.DELETE_GRAPHIC_MASK); - - } else { - - DrawingToolRequestor requestor = item.getRequestor(); - OMGraphic omg = item.getOMGraphic(); - if (requestor != null) { - requestor.drawingComplete(omg, new OMAction(OMGraphicConstants.DELETE_GRAPHIC_MASK)); - } else { - // if there isn't a requestor specified, tell - // anyone who will listen. - for (DrawingToolRequestor reqstor : requestors) { - reqstor.drawingComplete(omg, new OMAction(OMGraphicConstants.DELETE_GRAPHIC_MASK)); - } - } - - } - } - - // Should we just clear the list now? - deleteList.clear(); - deleteButton.setEnabled(!deleteList.isEmpty()); - } - - public void selectionNotification(SelectionEvent event) { - if (event.isSelected() && event.getOMGraphic() != null) { - Debug.message("deletebutton", "OMGDT.selection notification: adding selected to list."); - deleteList.put(event.getOMGraphic(), event); - } else if (!event.isSelected()) { - Debug.message("deletebutton", "OMGDT.selection notification: removing selected from list."); - deleteList.remove(event.getOMGraphic()); - } else { - Debug.message("deletebutton", "OMGDT.selection notification: omgraphic missing from notification."); - } - - deleteButton.setEnabled(!deleteList.isEmpty()); - } - - // ///////////////////////////////////////////////////////////////////////// - // // MapHandlerChild methods to make the tool work with - // // the MapHandler to find any SelectionProviders. - // ///////////////////////////////////////////////////////////////////////// - - public void findAndInit(Object obj) { - if (obj instanceof SelectionProvider) { - Debug.message("deletebutton", "OMGDT.findAndInit() found selection provider"); - ((SelectionProvider) obj).addSelectionListener(this); - } - - if (obj instanceof DrawingToolRequestor) { - - // Keep track of them so if the requestor is not known, - // just - // tell everyone who may be listening to delete the - // OMGraphic in question and let them react accordingly. - // If they don't already have the OMGraphic, they should - // just ignore the request. - requestors.add((DrawingToolRequestor) obj); - } - - if (obj instanceof MapBean) { - ((MapBean) obj).addKeyListener(this); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof SelectionProvider) { - ((SelectionProvider) obj).removeSelectionListener(this); - } - - if (obj instanceof DrawingToolRequestor) { - requestors.remove((DrawingToolRequestor) obj); - } - - if (obj instanceof MapBean) { - ((MapBean) obj).removeKeyListener(this); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OMToolComponent.java b/src/core/src/main/java/com/bbn/openmap/gui/OMToolComponent.java deleted file mode 100644 index 9b8ec43bb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OMToolComponent.java +++ /dev/null @@ -1,204 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OMToolComponent.java,v $ -// $RCSfile: OMToolComponent.java,v $ -// $Revision: 1.9 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.util.Properties; - -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMToolComponent is an extension to OMComponentPanel that - * provides a little support for those components that are also - * OpenMap Tools. Those components may be used directly in the GUI, or - * provide a Tool widget that will let the component be brought up in - * a different window. This class provides some support for - * controlling what gets set in the ToolPanel, effectively providing - * more controls on how a component can be used. For instance, the - * LayersPanel may be used directly in the GUI, integrated into the - * main application window. If a ToolPanel is there as well, and both - * are tossed into the MapHandler, the ToolPanel will display the - * LayersPanel face even though it is unnecessary. The methods in this - * super class make it possible for the LayersPanel to not provide a - * Tool face in certain applications. - *

- * - * This class will handle the "isTool" property and set the useAsTool - * setting as a result of properties being set. - */ -public abstract class OMToolComponent extends OMComponentPanel implements Tool { - - public final static String UseAsToolProperty = "isTool"; - - public final static String defaultKey = "omtoolcomponent"; - protected String key = defaultKey; - - /** - * This setting should be used to control if the face for this - * tool is used. - */ - protected boolean useAsTool = true; - - /** - * Default gridbag layout. - */ - protected GridBagLayout gridbag; - /** - * Default gridbag layout constraints. - */ - protected GridBagConstraints c; - - public OMToolComponent() { - super(); - setLayout(createLayout()); - } - - /** - * Hook to allow subclasses to use a different layout than the - * GridBagLayout. Set the layout on this class in this method. - */ - protected LayoutManager createLayout() { - gridbag = new GridBagLayout(); - c = getGridBagConstraints(); - return gridbag; - } - - /** - * If the default setLayout() method is used with the - * GridBagLayout, this method will be called to get the - * GridBagConstraints for that layout. This method can be - * overridden to make general adjustments to the constraints, like - * inset settings, etc. - */ - protected GridBagConstraints getGridBagConstraints() { - GridBagConstraints constraints = new GridBagConstraints(); - constraints.insets = new Insets(0, 2, 0, 2); - return constraints; - } - - /** - * Overridden add method that takes care of GridBagLayout - * constraints. - */ - public Component add(Component component) { - gridbag.setConstraints(component, c); - return super.add(component); - } - - /** - * Tool interface method. The retrieval tool's interface. This is - * added to the tool bar. - * - * @return The container GUI for this tool, may be null. - */ - public Container getFace() { - if (getUseAsTool()) { - return this; - } else { - return null; - } - } - - /** - * The retrieval key for this tool - * - * @return String The key for this tool. - */ - public String getKey() { - return key; - } - - /** - * Set the retrieval key for this tool - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - key = aKey; - } - - /** - * Set whether the Tool's face should be used. The subclasses to - * this class should either remove all components from its face, - * or make its face invisible if this is set to false. - */ - public void setUseAsTool(boolean value) { - useAsTool = value; - } - - /** - * Find the setting to let the Tool know whether its tool - * interface should be used as well. - */ - public boolean getUseAsTool() { - return useAsTool; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - // Important for ToolPanel that controls what it is listening - // for, instead of grabbing any Tool. The prefix will be used - // as a discriminator. - if (prefix != null) { - setKey(prefix); - } - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - setUseAsTool(PropUtils.booleanFromProperties(props, prefix - + UseAsToolProperty, getUseAsTool())); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + UseAsToolProperty, new Boolean(useAsTool).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String internString = i18n.get(OMToolComponent.class, - UseAsToolProperty, - I18n.TOOLTIP, - "Whether this component should be added to the Tool Panel"); - props.put(UseAsToolProperty, internString); - - internString = i18n.get(OMToolComponent.class, - UseAsToolProperty, - "Add to Tool Panel"); - props.put(UseAsToolProperty + LabelEditorProperty, internString); - - props.put(UseAsToolProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - return props; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OMToolSet.java b/src/core/src/main/java/com/bbn/openmap/gui/OMToolSet.java deleted file mode 100644 index 4f2b98ae4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OMToolSet.java +++ /dev/null @@ -1,345 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OMToolSet.java,v $ -// $RCSfile: OMToolSet.java,v $ -// $Revision: 1.10 $ -// $Date: 2005/08/09 19:14:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Container; -import java.awt.FlowLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMToolSet bundles other control beans, and is a Tool used in - * the OpenMap application. - *

- * - * It contains a NavigatePanel, which is the directional rosette used - * to pan the MapBean, the ZoomPanel that has a zoom in and zoom out - * button, and a scale text window. To use the OMToolSet, create an - * instance of it, and then call setupListeners() with the MapBean. - * All the event handling is automatically set up. - *

- * - * If the OMToolSet is added to a BeanContext, it should be found by a - * ToolPanel. It looks for a MapBean add as listeners to the various - * widgets. If it doesn't get a MapBean, then the projection widgets - * will appear to be non-functioning. - */ -public class OMToolSet extends OMComponentPanel implements Serializable, Tool { - - public final static String defaultKey = "omtoolset"; - - protected String key = defaultKey; - - /** Navigation rosette */ - protected transient NavigatePanel navPanel = null; - /** Zoom buttons */ - protected transient ZoomPanel zoomPanel = null; - /** ScaleTextPanel for scale text. */ - protected transient ScaleTextPanel scaleField = null; - - public final static String AddZoomProperty = "addZoom"; - public final static String AddPanProperty = "addPan"; - public final static String AddScaleProperty = "addScale"; - - protected boolean addZoom = true; - protected boolean addPan = true; - protected boolean addScale = true; - - /** - * Create the OMToolSet. - */ - public OMToolSet() { - super(); - Debug.message("omtoolset", "OMToolSet()"); - - setLayout(new FlowLayout(FlowLayout.LEFT)); - - navPanel = new NavigatePanel(); - - zoomPanel = new ZoomPanel(); - - scaleField = new ScaleTextPanel(); - - add(navPanel); - add(zoomPanel); - add(scaleField); - - createFace(); - } - - /** - * Tool interface method. The retrieval tool's interface. This is - * added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - return this; - } - - /** - * Sets the visibility of the default components, based on their - * boolean settings. - */ - protected void createFace() { - zoomPanel.setVisible(addZoom); - navPanel.setVisible(addPan); - scaleField.setVisible(addScale); - } - - /** - * Tool interface method. The retrieval key for this tool. - * - * @return String The key for this tool. - */ - public String getKey() { - return key; - } - - /** - * Tool interface method. Set the retrieval key for this tool. - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - key = aKey; - } - - /** - * Get the ZoomPanel - * - * @return the ZoomPanel - */ - public ZoomPanel getZoomPanel() { - return zoomPanel; - } - - /** - * Get the NavigatePanel. - * - * @return the NaviationPanel (directional rosette) - */ - public NavigatePanel getNavigatePanel() { - return navPanel; - } - - /** - * Get the scale field widget. - * - * @return ScaleTextPanel that is rigged to set the scale for the - * map. - */ - public ScaleTextPanel getScaleField() { - return scaleField; - } - - /** - * Convenience function to set up listeners of the components. If - * you are hooking the MapBean up to the OMToolSet, this is what - * you need to call. - * - * @param aMapBean a map object. - */ - public void setupListeners(MapBean aMapBean) { - if (aMapBean != null) { - findAndInit(aMapBean); - } - } - - /** - * This function removes the mapBean object from its set of - * Listeners. An inverse of setupListeners() method. - * - * @param aMapBean a map object. - */ - public void removeFromAllListeners(MapBean aMapBean) { - if (aMapBean != null) { - findAndUndo(aMapBean); - } - } - - /** - * Add a button to the panel. Will attempt to create a URL from - * the name of the image file. - * - * @param name image filename - * @param info tool tip - * @param al ActionListener - */ - public void addButton(String name, String info, ActionListener al) { - try { - URL url = PropUtils.getResourceOrFileOrURL(null, name); - if (url != null) { - addButton(url, info, al); - } - } catch (MalformedURLException murle) { - Debug.error("OMToolSet.addButton: can't create button for " + info); - } - } - - /** - * Add a button to the panel. - * - * @param url URL for image - * @param info tool tip - * @param al ActionListener - */ - public void addButton(URL url, String info, ActionListener al) { - JButton b = new JButton(new ImageIcon(url, info)); - b.setToolTipText(info); - b.setMargin(new Insets(0, 0, 0, 0)); - b.addActionListener(al); - b.setBorderPainted(false); - add(b); - } - - /** - * MapHandlerChild method. - */ - public void findAndInit(Object someObj) { - navPanel.findAndInit(someObj); - zoomPanel.findAndInit(someObj); - scaleField.findAndInit(someObj); - } - - /** - * MapHandlerChild method. - */ - public void findAndUndo(Object someObj) { - navPanel.findAndUndo(someObj); - zoomPanel.findAndUndo(someObj); - scaleField.findAndUndo(someObj); - } - - /** - * Method to set the properties in the PropertyConsumer. The - * prefix is a string that should be prepended to each property - * key (in addition to a separating '.') in order for the - * PropertyConsumer to uniquely identify properties meant for it, - * in the midst of of Properties meant for several objects. - * - * @param prefix a String used by the PropertyConsumer to prepend - * to each property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix - * had already been set, then the prefix passed in should - * replace that previous value. - * @param setList a Properties object that the PropertyConsumer - * can use to retrieve expected properties it can use for - * configuration. - */ - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - - // Important for ToolPanel that controls what it is listening - // for, instead of grabbing any Tool. The prefix will be used - // as a discriminator. - if (prefix != null) { - setKey(prefix); - } - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - addZoom = PropUtils.booleanFromProperties(setList, prefix - + AddZoomProperty, addZoom); - addPan = PropUtils.booleanFromProperties(setList, prefix - + AddPanProperty, addPan); - addScale = PropUtils.booleanFromProperties(setList, prefix - + AddScaleProperty, addScale); - - createFace(); - } - - /** - * Method to fill in a Properties object, reflecting the current - * values of the PropertyConsumer. If the PropertyConsumer has a - * prefix set, the property keys should have that prefix plus a - * separating '.' prepended to each property key it uses for - * configuration. - * - * @param getList a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - getList.put(prefix + AddZoomProperty, new Boolean(addZoom).toString()); - getList.put(prefix + AddPanProperty, new Boolean(addPan).toString()); - getList.put(prefix + AddScaleProperty, new Boolean(addScale).toString()); - return getList; - } - - /** - * Method to fill in a Properties object with values reflecting - * the properties able to be set on this PropertyConsumer. The key - * for each property should be the raw property name (without a - * prefix) with a value that is a String that describes what the - * property key represents, along with any other information about - * the property that would be helpful (range, default value, - * etc.). - * - * @param list a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(AddZoomProperty, "Flag to add the Zoom buttons"); - list.put(AddZoomProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(AddPanProperty, "Flag to add the Pan buttons"); - list.put(AddPanProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(AddScaleProperty, "Flag to add the scale field"); - list.put(AddScaleProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return list; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OpenMapFrame.java b/src/core/src/main/java/com/bbn/openmap/gui/OpenMapFrame.java deleted file mode 100644 index 0be076574..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OpenMapFrame.java +++ /dev/null @@ -1,505 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OpenMapFrame.java,v $ -// $RCSfile: OpenMapFrame.java,v $ -// $Revision: 1.13 $ -// $Date: 2006/02/27 15:11:34 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JFrame; -import javax.swing.JMenuBar; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The OpenMapFrame is the application window frame that holds the MapPanel, and - * eventually the MapBean. It listens to the MapHandler for the addition of - * Beans to the MapHandler BeanContext, and then positions the widgets it can - * deal with within itself. The frame does not present itself until an MapPanel - * is found. - * - *

- * The OpenMapFrame is intended to be used in an application environment. The - * applet checks and code to handle the applet environment was moved to the - * OpenMapApplet class. - */ -public class OpenMapFrame - extends JFrame - implements BeanContextMembershipListener, BeanContextChild, PropertyConsumer { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.OpenMapFrame"); - - /** Starting X coordinate of window, x */ - public static final String xProperty = "x"; - - /** Starting Y coordinate of window, y */ - public static final String yProperty = "y"; - - /** - * The property to set the pixel width of the frame, width. - */ - public static final String WidthProperty = "Width"; - /** - * The property to set the pixel height of the frame, height. - */ - public static final String HeightProperty = "Height"; - - /** - * The property to set the title of the frame, title. - */ - public static final String TitleProperty = "Title"; - - /** - * useAsInternalFrameRootPaneIfNecessary will tell the OpenMapFrame to set - * its root pane as the Environment's desktop if the Environment has been - * told to use internal frames, and if a root pane hasn't been set. True by - * default. - */ - protected boolean useAsInternalFrameRootPaneIfNecessary = true; - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - private BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - protected String propertyPrefix; - protected int frameLocX = -1; - protected int frameLocY = -1; - protected int frameWidth = Integer.MAX_VALUE; - protected int frameHeight = Integer.MAX_VALUE; - - /** - * All OMComponentPanels have access to an I18n object, which is provided by - * the Environment. - */ - protected I18n i18n = Environment.getI18n(); - - /** - * Create the frame with "OpenMap <version>" in the title. - */ - public OpenMapFrame() { - this(""); - } - - /** - * @param useAsInternalFrameRootPaneIfNecessary will tell the OpenMapFrame - * to set its root pane as the Environment's desktop if the - * Environment has been told to use internal frames, and if a root - * pane hasn't been set. - */ - public OpenMapFrame(boolean useAsInternalFrameRootPaneIfNecessary) { - this(Environment.get(Environment.Title), useAsInternalFrameRootPaneIfNecessary); - } - - /** - * Create a OpenMap frame with a title. - * - * @param title The Frame title. - */ - public OpenMapFrame(String title) { - this(title, true); - } - - /** - * Create a OpenMap frame with a title, with a WindowListner that says what - * to do when the OpenMapFrame is closed. - * - * @param title The Frame title. - * @param useAsInternalFrameRootPaneIfNecessary will tell the OpenMapFrame - * to set its root pane as the Environment's desktop if the - * Environment has been told to use internal frames, and if a root - * pane hasn't been set. - */ - public OpenMapFrame(String title, boolean useAsInternalFrameRootPaneIfNecessary) { - super(title); - this.useAsInternalFrameRootPaneIfNecessary = useAsInternalFrameRootPaneIfNecessary; - } - - /** - * For applications, checks where the properties says the window should be - * placed, and then uses the packed height and width to make adjustments. - */ - protected void setPosition() { - setPosition(getWidth(), getHeight()); - } - - protected void setPosition(int w, int h) { - // get starting width and height - pack(); - - Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); - logger.fine("Screen dimensions are " + d); - - if (w > d.width) - w = d.width - d.width / 10; - if (h > d.height) - h = d.height - d.height / 10; - - if (frameLocX < 0) - frameLocX = d.width / 2 - w / 2; - if (frameLocY < 0) - frameLocY = d.height / 2 - h / 2; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Setting window bounds from " + frameLocX + ", " + frameLocY + " for size " + w + ", " + h); - } - - // compose the frame, but don't show it here - // contentPane.setBounds(x, y, w, h); - setBounds(frameLocX, frameLocY, w, h); - } - - /** - * Called when the OpenMapFrame is added to a BeanContext, and when other - * objects are added to the BeanContext. The OpenMapFrame looks for objects - * that it knows how to place upon itself (MapPanel, JMenuBar). The - * OpenMapFrame does not check to see if the objects looked for are already - * added to itself. It assumes that if some object type is getting added to - * it, the caller must know what they are doing - just like a regular - * JFrame. - * - * @param it Iterator to use to go through the BeanContext objects. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Called when an object is added to the MapHandler. - */ - public void findAndInit(Object someObj) { - - considerForContent(someObj); - - // We shouldn't find this if we've already defined one - // in the MapPanel, but we have this for backward - // compatibility. - if (someObj instanceof JMenuBar) { - logger.fine("OpenMapFrame: Found a MenuBar"); - getRootPane().setJMenuBar((JMenuBar) someObj); - invalidate(); - } - } - - /** - * Method used to determine if an object should be added as content. Method - * is here to make it easier for subclasses to override and add what they - * want to content pane. - * - * @param someObj - */ - public void considerForContent(Object someObj) { - if (someObj instanceof MapPanel && someObj instanceof Component && getContentPane().getComponentCount() == 0) { - logger.fine("Found a MapPanel"); - setContent((Component) someObj); - } - } - - /** - * Called with the MapPanel to be set in the Content Pane of this Frame. If - * a MapPanel, a JMenuBar will be retrieved and added as well. - * - * @param component component to be used as content. - */ - public void setContent(Component component) { - getContentPane().add(component); - - if (component instanceof MapPanel) { - MapPanel mapPanel = (MapPanel) component; - - JMenuBar jmb = mapPanel.getMapMenuBar(); - if (jmb != null) { - logger.fine("OpenMapFrame: Got MenuBar from MapPanel"); - getRootPane().setJMenuBar(jmb); - } - } - - setPosition(frameWidth, frameHeight); - invalidate(); - pack(); - setVisible(true); - } - - /** - * BeanContextMembership interface method. Called when objects are added to - * the BeanContext. - * - * @param bcme contains an Iterator that lets you go through the new - * objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembership interface method. Called by BeanContext when - * children are being removed. Unhooks itself from the objects that are - * being removed if they are contained within the Frame. - * - * @param bcme event that contains an Iterator to use to go through the - * removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * Called when an object is removed from the MapHandler. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapPanel && someObj instanceof Container) { - logger.fine("OpenMapFrame: MapBean is being removed from frame"); - getContentPane().remove((Container) someObj); - - if (getJMenuBar() == ((MapPanel) someObj).getMapMenuBar()) { - logger.fine("OpenMapFrame: Menu Bar is being removed"); - setJMenuBar(null); - } - } - - if (someObj instanceof JMenuBar) { - if (getJMenuBar() == (JMenuBar) someObj) { - logger.fine("OpenMapFrame: Menu Bar is being removed"); - setJMenuBar(null); - } - } - - if (this.equals(someObj)) { - dispose(); - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - if (beanContextChildSupport != null) { - return beanContextChildSupport.getBeanContext(); - } - - return null; - } - - /** - * Method for BeanContextChild interface. - * - * @param in_bc The context to which this object is being added - */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - // Implementation of PropertyConsumer Interface - /** - * Method to set the properties in the PropertyConsumer. It is assumed that - * the properties do not have a prefix associated with them, or that the - * prefix has already been set. - * - * @param setList a properties object that the PropertyConsumer can use to - * retrieve expected properties it can use for configuration. - */ - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - /** - * Method to set the properties in the PropertyConsumer. The prefix is a - * string that should be prepended to each property key (in addition to a - * separating '.') in order for the PropertyConsumer to uniquely identify - * properties meant for it, in the midst of of Properties meant for several - * objects. - * - * @param prefix a String used by the PropertyConsumer to prepend to each - * property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix had already - * been set, then the prefix passed in should replace that previous - * value. - * @param setList a Properties object that the PropertyConsumer can use to - * retrieve expected properties it can use for configuration. - */ - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - frameLocX = PropUtils.intFromProperties(setList, prefix + xProperty, frameLocX); - frameLocY = PropUtils.intFromProperties(setList, prefix + yProperty, frameLocY); - frameWidth = PropUtils.intFromProperties(setList, prefix + WidthProperty, frameWidth); - frameHeight = PropUtils.intFromProperties(setList, prefix + HeightProperty, frameHeight); - - setTitle(setList.getProperty(prefix + TitleProperty, getTitle())); - - if (getContentPane().getComponentCount() > 0) { - logger.fine("setting window dimensions"); - setPosition(frameWidth, frameHeight); - } - - if (useAsInternalFrameRootPaneIfNecessary) { - boolean useInternalFrames = PropUtils.booleanFromProperties(setList, Environment.UseInternalFrames, false); - - if (useInternalFrames && Environment.getInternalFrameDesktop() == null) { - logger.fine("Setting OpenMapFrame as internal pane."); - Environment.useInternalFrames(getRootPane()); - } - } - - } - - /** - * Method to fill in a Properties object, reflecting the current values of - * the PropertyConsumer. If the PropertyConsumer has a prefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param getList a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new Properties - * object should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - getList.setProperty(xProperty, "" + getBounds().x); - getList.setProperty(yProperty, "" + getBounds().y); - getList.setProperty(Environment.Width, Integer.toString(getWidth())); - getList.setProperty(Environment.Height, Integer.toString(getHeight())); - - return getList; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.setProperty("x", "Starting X coordinate of window"); - list.setProperty("y", "Starting Y coordinate of window"); - - return list; - } - - /** - * Doesn't do anything. The OpenMapFrame looks for properties set with the - * "openmap" property prefix. This method is part of the PropertyConsumer - * interface. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix for the frame - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - public void setUseAsInternalFrameRootPaneIfNecessary(boolean val) { - useAsInternalFrameRootPaneIfNecessary = true; - } - - public boolean getUseAsInternalFrameRootPaneIfNecessary() { - return useAsInternalFrameRootPaneIfNecessary; - } - - /** - * Calls dispose on the BeanContext (MapHandler) and then removes references - * to other children. - */ - public void dispose() { - - MapHandler mh = ((MapHandler) getBeanContext()); - if (mh != null) { - mh.dispose(); - } - - beanContextChildSupport = null; - - getContentPane().removeAll(); - JMenuBar jmb = getJMenuBar(); - if (jmb != null) { - jmb.removeAll(); - } - setJMenuBar(null); - getRootPane().remove(this); - super.dispose(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OverlayMapPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/OverlayMapPanel.java deleted file mode 100644 index 8cbee0800..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OverlayMapPanel.java +++ /dev/null @@ -1,371 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import javax.swing.BorderFactory; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.OverlayLayout; -import javax.swing.SwingUtilities; -import javax.swing.border.BevelBorder; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.proj.ProjectionStack; -import com.bbn.openmap.util.PropUtils; - -/** - * An extension of the BasicMapPanel that uses an OverlayLayout on the panel in - * the BorderLayout.CENTER position. Contains a transparent widgets JPanel for - * placing components floating on top of the map. The default implementation of - * layoutPanel() adds an EmbeddedNavPanel in the upper left position of the map, - * as well as a ProjectionStack for it to use. - *

- * If a property prefix is set on this MapPanel, that property prefix can be - * used to designate MapPanelChild objects for this MapPanel. The setName - * variable should be set to true, and the children's parent name should match - * whatever property prefix is given to the panel. - */ -public class OverlayMapPanel extends BasicMapPanel implements PropertyChangeListener { - - private static final long serialVersionUID = 1L; - - public final static String ACTIVE_WIDGET_COLOR_PROPERTY = "activeWidgets"; - public final static String INACTIVE_WIDGET_COLOR_PROPERTY = "inactiveWidgets"; - public final static String WIDGET_SIZE_PROPERTY = "widgetSize"; - protected int DEFAULT_WIDGET_BUTTON_SIZE = 15; - - /** - * May be null, in which case the widgets should decide. - */ - protected DrawingAttributes activeWidgetColors; - /** - * May be null, in which case the widgets should decide. - */ - protected DrawingAttributes inactiveWidgetColors; - /** - * Defaults to 15; - */ - protected int widgetButtonSize = DEFAULT_WIDGET_BUTTON_SIZE; - - /** - * A transparent JPanel with a border layout, residing on top of the - * MapBean. - */ - protected JPanel widgets; - - private JPanel centerContainer; - - /** - * Creates an empty OverlayMapPanel that creates its own empty - * PropertyHandler. The MapPanel will contain a MapBean, a MapHandler, - * EmbeddedNavPanel and a PropertyHandler with no properties. The - * constructor to use to create a blank map framework to add components to. - */ - public OverlayMapPanel() { - super(new PropertyHandler(new Properties()), false); - } - - /** - * Create a OverlayMapPanel with the option of delaying the search for - * properties until the create() call is made. - * - * @param delayCreation true to let the MapPanel know that the artful - * programmer will call create() - */ - public OverlayMapPanel(boolean delayCreation) { - super(null, delayCreation); - } - - /** - * Create a OverlayMapPanel that configures itself with the properties - * contained in the PropertyHandler provided. If the PropertyHandler is - * null, a new one will be created. - */ - public OverlayMapPanel(PropertyHandler propertyHandler) { - super(propertyHandler, false); - } - - /** - * Create a OverlayMapPanel that configures itself with properties contained - * in the PropertyHandler provided, and with the option of delaying the - * search for properties until the create() call is made. - * - * @param delayCreation true to let the MapPanel know that the artful - * programmer will call create() - */ - public OverlayMapPanel(PropertyHandler propertyHandler, boolean delayCreation) { - super(propertyHandler, delayCreation); - } - - /** - * Calls layoutPanel(MapBean), which configures the panel. - */ - protected void addMapBeanToPanel(MapBean map) { - layoutPanel(map); - map.addPropertyChangeListener(this); - } - - public DrawingAttributes getActiveWidgetColors() { - return activeWidgetColors; - } - - public void setActiveWidgetColors(DrawingAttributes activeWidgetColors) { - this.activeWidgetColors = activeWidgetColors; - } - - public DrawingAttributes getInactiveWidgetColors() { - return inactiveWidgetColors; - } - - public void setInactiveWidgetColors(DrawingAttributes inactiveWidgetColors) { - this.inactiveWidgetColors = inactiveWidgetColors; - } - - public int getWidgetButtonSize() { - return widgetButtonSize; - } - - public void setWidgetButtonSize(int widgetButtonSize) { - this.widgetButtonSize = widgetButtonSize; - } - - /** - * New method added, called from addMapBeanToPanel(MapBean). - * - * @param map - */ - protected void layoutPanel(MapBean map) { - - JPanel hackPanel = new JPanel(); - hackPanel.setLayout(new BorderLayout()); - hackPanel.setOpaque(false); - hackPanel.add(map, BorderLayout.CENTER); - - centerContainer = new JPanel(); - centerContainer.setLayout(new OverlayLayout(centerContainer)); - - addMapComponent(new ProjectionStack()); - widgets = getComponentsFloatingOnMap(map); - - setBorders(map, widgets); - - centerContainer.add(widgets); - centerContainer.add(hackPanel); - - add(centerContainer, BorderLayout.CENTER); - } - - /** - * Create the panel containing the components that will float over the map. - * Default is a nav panel and scale indicator. - * - * @param map The MapBean - * @return a JPanel with the layout and rendering attributes set for the - * area over the map. - */ - protected JPanel getComponentsFloatingOnMap(MapBean map) { - - JPanel floatingWidgets = new JPanel(); - floatingWidgets.setLayout(new BorderLayout()); - floatingWidgets.setBackground(OMGraphicConstants.clear); - floatingWidgets.setOpaque(false); - floatingWidgets.setBounds(0, 0, map.getWidth(), map.getHeight()); - floatingWidgets.setMinimumSize(new Dimension(MapBean.DEFAULT_WIDTH, MapBean.DEFAULT_HEIGHT)); - - // These may be null, but the EmbeddedNavPanel will choose it's own - // default colors if that is so. - DrawingAttributes activeWidgetColors = getActiveWidgetColors(); - DrawingAttributes inactiveWidgetColors = getInactiveWidgetColors(); - int widgetButtonSize = getWidgetButtonSize(); - - EmbeddedNavPanel navPanel = new EmbeddedNavPanel(activeWidgetColors, inactiveWidgetColors, widgetButtonSize); - navPanel.setBounds(12, 12, navPanel.getMinimumSize().width, navPanel.getMinimumSize().height); - addMapComponent(navPanel); - floatingWidgets.add(navPanel, BorderLayout.WEST); - - EmbeddedScaleDisplayPanel scaleDisplay = new EmbeddedScaleDisplayPanel(); - addMapComponent(scaleDisplay); - floatingWidgets.add(scaleDisplay, BorderLayout.EAST); - - return floatingWidgets; - } - - /** - * If you want different borders or color them differently, override this - * method. - * - * @param map - * @param widgets - */ - protected void setBorders(MapBean map, JPanel widgets) { - - if (map != null) { - map.setBorder(null); - } - - if (widgets != null) { - widgets.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.GRAY, Color.DARK_GRAY)); - } - } - - /** Include exit in the File menu. Call this before create(). */ - public void includeExitMenuItem() { - addProperty("quitMenu.class", "com.bbn.openmap.gui.map.QuitMenuItem"); - appendProperty("fileMenu.items", "quitMenu"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - DrawingAttributes awc = getActiveWidgetColors(); - if (awc == null) { - awc = DrawingAttributes.getDefaultClone(); - } - DrawingAttributes iwc = getInactiveWidgetColors(); - if (iwc == null) { - iwc = DrawingAttributes.getDefaultClone(); - } - - // If no properties have been set for them, reset to null so the - // EmbeddedNavPanel default colors are used. - awc.setProperties(prefix + ACTIVE_WIDGET_COLOR_PROPERTY, props); - if (awc.equals(DrawingAttributes.getDefaultClone())) { - awc = null; - } - - iwc.setProperties(prefix + INACTIVE_WIDGET_COLOR_PROPERTY, props); - if (iwc.equals(DrawingAttributes.getDefaultClone())) { - iwc = null; - } - - setActiveWidgetColors(awc); - setInactiveWidgetColors(iwc); - - setWidgetButtonSize(PropUtils.intFromProperties(props, prefix + WIDGET_SIZE_PROPERTY, getWidgetButtonSize())); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - DrawingAttributes awc = getActiveWidgetColors(); - if (awc != null) { - awc.setPropertyPrefix(PropUtils.getScopedPropertyPrefix(this) + ACTIVE_WIDGET_COLOR_PROPERTY); - awc.getProperties(props); - } - - DrawingAttributes iwc = getInactiveWidgetColors(); - if (iwc != null) { - iwc.setPropertyPrefix(PropUtils.getScopedPropertyPrefix(this) + INACTIVE_WIDGET_COLOR_PROPERTY); - iwc.getProperties(props); - } - - int widgetSize = getWidgetButtonSize(); - if (widgetSize != DEFAULT_WIDGET_BUTTON_SIZE) { - props.put(prefix + WIDGET_SIZE_PROPERTY, Integer.toString(widgetSize)); - } - - return props; - } - - /** - * Add object to MapHandler via addMapComponent(Object), then return this - * MapPanel. - * - * @param obj object to add to MapHandler - * @return this MapPanel - */ - public OverlayMapPanel with(Object obj) { - addMapComponent(obj); - return this; - } - - /** - * Create an OverlayMapPanel with a LayerHandler, MouseDelegator and - * OMMouseMode pre-added(). - * - * @return OverlayMapPanel - */ - public static OverlayMapPanel standardConfig() { - return new OverlayMapPanel().with(new com.bbn.openmap.LayerHandler()).with(new com.bbn.openmap.MouseDelegator()) - .with(new com.bbn.openmap.event.OMMouseMode()); - } - - /** A main() method that just brings up a JFrame containing the MapPanel. */ - public static void main(String argv[]) { - SwingUtilities.invokeLater(new Runnable() { - - public void run() { - - OverlayMapPanel map = OverlayMapPanel.standardConfig() - .with(new ShapeLayer("share/data/shape/cntry02/cntry02.shp")); - map.addMapComponent(new com.bbn.openmap.InformationDelegator()); - map.getMapBean().setBckgrnd(new Color(0x99b3cc)); - map.includeExitMenuItem(); - - JFrame f = new JFrame("Map"); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setJMenuBar(map.getMapMenuBar()); - f.getContentPane().add(map); - f.setSize(800, 600); - f.setVisible(true); - } - - }); - - } - - /* - * (non-Javadoc) - * @see java.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName().equals(MapBean.CursorProperty)) { - centerContainer.setCursor(((Cursor) evt.getNewValue())); - } - } - - /** - * If one of the widgets gets removed from the MapHandler, we'll remove it - * from the interface, too. - */ - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - - /* - * It's no harm to call this for every Component. Component checks to - * see if widgets is the Component's parent first. - */ - if (widgets != null && someObj instanceof Component) { - widgets.remove((Component) someObj); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/OverviewMapHandler.java b/src/core/src/main/java/com/bbn/openmap/gui/OverviewMapHandler.java deleted file mode 100644 index 8a3704621..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/OverviewMapHandler.java +++ /dev/null @@ -1,1035 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OverviewMapHandler.java,v $ -// $RCSfile: OverviewMapHandler.java,v $ -// $Revision: 1.15 $ -// $Date: 2006/08/09 21:08:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Insets; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.net.URL; -import java.util.List; -import java.util.Properties; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.DefaultOverviewMouseMode; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.OverviewMapStatusListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.layer.OverviewMapAreaLayer; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The OverviewMapHandler contains a MapBean that contains a projection that - * reflects another MapBean's projection. It manages the two MapBeans and the - * differences in the projections betwen them. The OverviewMapHandler can have a - * projection type independent of that of the source MapBean (the MapBean that - * the OverviewMapHandler's MapBean is paying attention to). It also contains a - * scale factor, which is a multiplier to use against the scale of the source - * MapBean's scale. - *

- * - * The OverviewMapHandler MapBean can also be used to control the source - * MapBean's projection center and scale. The source MapBean just needs to be - * added to the OverviewMapHandler by - * OverviewMapHandler.addControlledMap(MapBean). - *

- * - * The OverviewMapHandler needs to be added to the source MapBean as a - * ProjectionListener. Then, the overview MapBean can be added to the - * ContentPane of a Component by calling - * Component.setContentPane(OverviewMapHandler.getMap()); The OverviewMapHandler - * Should also be added as a ComponentListener to the Component. - *

- * - * After the first projectionChanged() call is received, the OverviewMapHandler - * knows about the source MapBean. Since the OverviewMapHandler is a - * ComponentListener and will therefore find out when it's parent is hidden, it - * will disengage and engage itself from the source MapBean as it's visibility - * changes. - *

- * - * To get the overview map to appear in the OpenMap application, add the - * following properties to your openmap.properties file: - * - *

- * 
- * 
- *       # First, add overviewMapHandler to the openmap.components marker name list.  Then, add:
- *     
- *       overviewMapHandler.class=com.bbn.opemap.gui.OverviewMapHandler
- *       overviewMapHandler.overviewLayers=overviewLayer
- *       overviewMapHandler.overviewScaleFactor=10f
- *       overviewMapHandler.overviewMinScale=100f
- *       # Set the Unit of Measure for the overviewMinScale property
- *       # Omission of  overviewMinScaleUom indicates that overviewMinScale
- *       # is an projection map scale instead of a distance.
- *       overviewMapHandler.overviewMinScaleUom=km
- *     
- *       # 'overviewStatusLayer' is a marker name for any attributes you may
- *       # want to pass to the overviewStatusLayer instance, in addition to
- *       # being used to define the class to use for that special layer.
- *       overviewMapHandler.overviewStatusLayer.class=com.bbn.openmap.layer.OverviewMapAreaLayer
- *       # Properties can be passed to the overview status layer by listing
- *       # them with the OverviewMapHandler prefix.
- *     
- *       # Set the line color for the coverage box outline...
- *       # overviewMapHandler.lineColor=FFFF0000
- *     
- *       # A sample overview map layer
- *       overviewLayer.class=com.bbn.openmap.layer.shape.ShapeLayer
- *       overviewLayer.prettyName=Overview
- *       overviewLayer.shapeFile=/home/dietrick/dev/openmap/share/dcwpo-browse.shp
- *       overviewLayer.spatialIndex=/home/dietrick/dev/openmap/share/dcwpo-browse.ssx
- *       overviewLayer.lineColor=ff000000
- *       overviewLayer.fillColor=ffbdde83
- * 
- * 
- * 
- * - *

- * - * If layers are not added to the overview map, then it won't show up in the - * application. - */ -public class OverviewMapHandler extends OMToolComponent - implements ProjectionListener, Serializable, PropertyConsumer, PropertyChangeListener, ComponentListener { - - private static final long serialVersionUID = 1L; - public final static String OverviewMapHandlerLayerProperty = "overviewLayers"; - public final static String ScaleFactorProperty = "overviewScaleFactor"; - public final static String ProjectionTypeProperty = "overviewProjectionType"; - public final static String MinScaleProperty = "overviewMinScale"; - public final static String MinScaleUomProperty = "overviewMinScaleUom"; - public final static String StatusLayerProperty = "overviewStatusLayer"; - public final static String ControlSourceMapProperty = "overviewControlSourceMap"; - public final static String BackgroundSlaveProperty = "backgroundSlave"; - public final static float defaultScaleFactor = 20f; - public final static float defaultMinScale = 500000f; - public final static Length defaultMinScaleUom = null; - - /** The multiplier to apply to the scale of the project received. */ - protected float scaleFactor; - /** - * The minimum scale to use for the window. If it gets too small with a general - * type layer, it won't be any use. - */ - protected float minScale; - - /** - * The minimum scale unit of measure to use for the window. Use during - * initialization to compute a projection scale from a distance. - */ - protected Length minScaleUom; - - /** The map of the overview panel. */ - protected transient MapBean map; - /** - * The source MapBean to show the overview of. Gets set when the first - * projectionChanged() gets called. Also used to disconnect from the MapBean - * when the component that this OverviewMapHandler is listening to is hidden, - * and to connect to the MapBean when the component is shown. - */ - protected transient MapBean sourceMap; - /** The projection of the overview map bean. */ - protected transient Proj projection; - /** - * A layer that can be set to constantly be on the top of the map. If the status - * layer is also a OverviewMapStatusListener, it also receives the source map - * projection when that changes, which gives it the capability to draw stuff - * based on that. - */ - protected Layer statusLayer; - /** - * The support to send the source MapBean setCenter and setScale commands if a - * controlled map is added - usually the source map bean. - */ - protected transient ControlledMapSupport controlledMaps; - /** The mouse mode to use for the overview map. */ - protected MapMouseMode mmm; - /** - * The thing listening for a request to bring up a JFrame or JInternalFrame. - */ - protected ActionListener overviewFrameActionListener = null; - /** Indicates if OverviewMap should be controlling sourceMap. */ - protected boolean controlSourceMap = true; - /** Default Frame title for OverviewMapHandler */ - public static final String defaultFrameTitle = "Overview Map"; - /** String The Frame Title */ - protected String frameTitle = defaultFrameTitle; - /** Default key for Tool */ - public static final String defaultKey = "overviewmaphandler"; - - /** - * Flag to change the background color to whatever the source map's is changed - * to. True by default. - */ - protected boolean backgroundSlave = true; - - public final static int INITIAL_WIDTH = 200; - public final static int INITIAL_HEIGHT = 100; - - /** - * Default constructor. make sure init(someProperties) is called before you - * attempt to use this object - */ - public OverviewMapHandler() { - super(); - setKey(defaultKey); - setLayout(new BorderLayout()); - createOverviewMap(); - - // Set up a default... - projection = createStartingProjection(null); - addComponentListener(this); - // Create this when we need it. - // setWindowSupport(new WindowSupport(this, new WindowSupport.Dlg(null, - // "Overview Map"))); - } - - /** - * Create an OverviewMapHandler with properties that do not contain a prefix. - * - * @param props properties object. - */ - public OverviewMapHandler(Properties props) throws Exception { - this(null, props); - } - - /** - * Create an OverviewMapHandler with properties that do contain a prefix. - * - * @param prefix the prefix for all the properties that apply to the - * OverviewMapHandler. - * @param props properties object. - */ - public OverviewMapHandler(String prefix, Properties props) throws Exception { - - this(); - setProperties(prefix, props); - } - - /** - * Create an OverviewMapHandler for given MapBean. - * - * @param srcMap srcMapBean - * @param prefix the prefix to place in front of each property - i.e., so that - * each property will be under prefix.propertyName. The period - * between the two will be added. - * @param props properties object. - */ - public OverviewMapHandler(MapBean srcMap, String prefix, Properties props) throws Exception { - this(prefix, props); - setSourceMap(srcMap); - } - - /** - * Create the MapBean used for the overview map, and suppress the copyright - * message at the same time. - */ - protected void createOverviewMap() { - // We don't need another copyright message, right? - MapBean.suppressCopyright = true; - map = new BufferedMapBean(); - this.add(map, BorderLayout.CENTER); - } - - /** - * Initialize based on properties, which will not have a prefix. - * - * @deprecated use setProperties(props). - */ - public void init(Properties props) throws Exception { - setProperties(null, props); - } - - /** - * Initialize an OverviewMapHandler with properties that do contain a prefix. - * - * @param prefix the prefix to place in front of each property - i.e., so that - * each property will be under prefix.propertyName. The period - * between the two will be added. - * @param props properties object. - * @deprecated use setProperties(prefix, props). - */ - public void init(String prefix, Properties props) throws Exception { - setProperties(prefix, props); - } - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than the - * setArgs method. Part of the PropertyConsumer interface. Layers - * which override this method should do something like: - *

- * - *

-	 * public void setProperties(String prefix, Properties props) {
-	 * 	super.setProperties(prefix, props);
-	 * 	// do local stuff
-	 * }
-	 * 
- *

- * If the addToBeanContext property is not defined, it is set to false here. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - propertyPrefix = prefix; - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - List overviewLayers = PropUtils - .parseSpacedMarkers(props.getProperty(prefix + OverviewMapHandlerLayerProperty)); - - if (overviewLayers.isEmpty()) { - Debug.message("overview", "OverviewMapHandler: created without layers!"); - } - - scaleFactor = PropUtils.floatFromProperties(props, prefix + ScaleFactorProperty, defaultScaleFactor); - - minScale = PropUtils.floatFromProperties(props, prefix + MinScaleProperty, defaultMinScale); - - String uom = props.getProperty(prefix + MinScaleUomProperty); - if (uom != null) { - minScaleUom = Length.get(uom); - setMinScale(minScale, minScaleUom); - } - - backgroundSlave = PropUtils.booleanFromProperties(props, prefix + BackgroundSlaveProperty, backgroundSlave); - - setControlSourceMap( - PropUtils.booleanFromProperties(props, prefix + ControlSourceMapProperty, controlSourceMap)); - - String statusLayerName = props.getProperty(prefix + StatusLayerProperty + ".class"); - if (statusLayerName != null) { - statusLayer = (Layer) ComponentFactory.create(statusLayerName, prefix + StatusLayerProperty, props); - if (statusLayer == null) { - Debug.error("OverviewMapHandler.setProperties: status layer not set."); - } - } else { - statusLayer = new OverviewMapAreaLayer(); - } - - statusLayer.setProperties(prefix, props); - - projection = createStartingProjection(props.getProperty(prefix + ProjectionTypeProperty)); - - setLayers(LayerHandler.getLayers(overviewLayers, overviewLayers, props)); - } - - protected ProjectionFactory getProjectionFactory() { - if (sourceMap != null) { - return sourceMap.getProjectionFactory(); - } - return ProjectionFactory.loadDefaultProjections(); - } - - private Proj createStartingProjection(String projName) { - - ProjectionFactory projectionFactory = getProjectionFactory(); - Class projClass = projectionFactory.getProjClassForName(projName); - - if (projClass == null) { - projClass = Mercator.class; - } - - // The scale, lat/lon and size shouldn't matter, because the - // size will get reset when it is added to a component, and - // the projection will change when it is added to a MapBean - // as a projection listener.p - return (Proj) projectionFactory.makeProjection(projClass, - new Point2D.Float(Environment.getFloat(Environment.Latitude, 0f), - Environment.getFloat(Environment.Longitude, 0f)), - Environment.getFloat(Environment.Scale, Float.POSITIVE_INFINITY) * scaleFactor, INITIAL_WIDTH, - INITIAL_HEIGHT); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to each - * property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it should - * be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - // Build marker list - StringBuffer layerList = new StringBuffer(); - Component[] comps = map.getComponents(); - int ncomponents = comps.length; - for (int i = 0; i < ncomponents; i++) { - Layer layer = (Layer) comps[i]; - if (layer != statusLayer) { // Take care of the - // statusLayer later. - layerList.append(" ").append(layer.getPropertyPrefix()); - layer.getProperties(props); - } - } - props.put(prefix + OverviewMapHandlerLayerProperty, layerList.toString()); - - props.put(prefix + ScaleFactorProperty, Float.toString(scaleFactor)); - props.put(prefix + ProjectionTypeProperty, map.getProjection().getName()); - props.put(prefix + MinScaleProperty, Float.toString(minScale)); - props.put(prefix + BackgroundSlaveProperty, new Boolean(backgroundSlave).toString()); - - if (statusLayer != null) { - props.put(prefix + StatusLayerProperty, statusLayer.getClass().getName()); - statusLayer.getProperties(props); - } - - props.put(prefix + ControlSourceMapProperty, new Boolean(controlSourceMap).toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the properties - * able to be set on this PropertyConsumer. The key for each property should be - * the raw property name (without a prefix) with a value that is a String that - * describes what the property key represents, along with any other information - * about the property that would be helpful (range, default value, etc.). For - * Layer, this method should at least return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties into. - * If getList equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it should - * be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(OverviewMapHandlerLayerProperty, - "Space separated list of marker names of layers to use as background on the overview map."); - list.put(ScaleFactorProperty, - "Multiplier reflecting the difference between the scale of the overview map and the source map (default is 20.0)."); - list.put(ProjectionTypeProperty, "Projection name to use for overview map (Default is mercator)."); - list.put(MinScaleProperty, "Minimum scale of overview map (Default is 500,000.0)."); - list.put(StatusLayerProperty, - "Class name of layer to use as the active layer on the overview map, receiving mouse events (Default is com.bbn.openmap.layer.OverviewMapAreaLayer)."); - list.put(ControlSourceMapProperty, - "Flag to have the source map controlled by gestures on the overview map (true/false, default is true)."); - list.put(ControlSourceMapProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - list.put(BackgroundSlaveProperty, - "Flag to have the map mimic any changes made to the source map's background (true/false, default is true)."); - list.put(BackgroundSlaveProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - - statusLayer.getPropertyInfo(list); - - return list; - } - - /** - * Sets the sourceMap associated with this OverviewMap. if controlSourceMap - * property is set, srcMap will also be controlled by this OverviewHandler - * Passing a null value will remove the current sourceMap from the list of Maps - * that this handler is controlling and set sourceMap to null. - * - * @param srcMap the master map. - */ - public void setSourceMap(MapBean srcMap) { - if (sourceMap != null) { - removeControlledMap(sourceMap); - sourceMap.removeProjectionListener(this); - sourceMap.removePropertyChangeListener(this); - } - - // Add the sourceMap to a set of listeners that wish to be - // controlled by this OverviewMapHandler - if (srcMap != null) { - if (controlSourceMap == true) { - addControlledMap(srcMap); - } - - // Check and see if the overview map window is up. If it - // is, we should add the overview map as a projection - // listener to it. Note: overview map windows went away - // due to window support, but not sure how it affected - // this statement. Keeping commented code here for - // reference in case behavior is weird. Seems to be - // working as expected, though. DFD - // if ((overviewWindowFrame != null && - // overviewWindowFrame.isShowing()) || - // (overviewWindow != null && overviewWindow.isShowing()) - // || - - // Turns out non-tool overview maps weren't becoming - // projection change listeners... - if (!getUseAsTool() && isVisible()) { - srcMap.addProjectionListener(this); - } - - srcMap.addPropertyChangeListener(this); - } - - sourceMap = srcMap; - } - - /** - * Get the map that the overview map is listening to. - */ - public MapBean getSourceMap() { - return sourceMap; - } - - /** - * Set the string used for the frame title of the overview map. - */ - public void setFrameTitle(String in_frameTitle) { - frameTitle = in_frameTitle; - } - - public String getFrameTitle() { - return frameTitle; - } - - /** - * Set whether the map's background mimics changes to the source map's - * background. - * - * @param set true to enable mimicking. - */ - public void setBackgroundSlave(boolean set) { - backgroundSlave = set; - } - - /** - * Get whether the map's background mimics changes to the source map's - * background. - */ - public boolean getBackgroundSlave() { - return backgroundSlave; - } - - /** - * Default value of this property is true. if you want your sourceMap to be - * controlled by this OverviewMapHandler, set the value of this property for - * this OverviewHandler. This will allow, for instance, clicking on the overview - * map to recenter the source map. That depends on the overview map mouse mode, - * however. - * - * @param value - */ - public void setControlSourceMap(boolean value) { - if (sourceMap != null) { - if (value == true && controlSourceMap == false) { - addControlledMap(sourceMap); - } - if (value == false && controlSourceMap == true) { - removeControlledMap(sourceMap); - } - } - controlSourceMap = value; - } - - public boolean getControlSourceMap() { - return controlSourceMap; - } - - /** - * Set the layers in the Overview MapBean. An AreaLayer is automatically added - * on top. - */ - public void setLayers(Layer[] layers) { - map.setLayers(new LayerEvent(this, LayerEvent.REPLACE, new Layer[0])); - if (statusLayer != null) { - map.add(statusLayer); - } - map.setLayers(new LayerEvent(this, LayerEvent.ADD, layers)); - } - - /** - * Part of the ProjectionListener interface. The new projections from the source - * MapBean arrive here. - * - * @param projEvent the projection event from the source MapBean. - */ - public void projectionChanged(ProjectionEvent projEvent) { - if (sourceMap == null) { - sourceMap = (MapBean) projEvent.getSource(); - map.setBckgrnd(sourceMap.getBckgrnd()); - } - - Projection proj = projEvent.getProjection(); - if (proj == null) { - return; - } - - if (statusLayer instanceof OverviewMapStatusListener) { - ((OverviewMapStatusListener) statusLayer).setSourceMapProjection(proj); - } - - float newScale = proj.getScale() * scaleFactor; - - // Adjust the newScale based on the ratio of the - // source projection width and the overview - // map projection width. - Projection sourceProj = sourceMap.getProjection(); - newScale *= (float) sourceProj.getWidth() / (float) projection.getWidth(); - - if (newScale < minScale) { - newScale = minScale; - } - - projection.setScale(newScale); - projection.setCenter(proj.getCenter()); - map.setProjection(projection); - } - - /** - * Set the MapMouseMode for the overview map. If you want the status layer to - * listen to the mouse mode, you have to get the layer and wire it up yourself. - */ - public void setMouseMode(MapMouseMode ammm) { - // If we're removing a mouse mode, disconnect it from the map. - if (ammm == null) { - deactivateMouseMode(); - } - mmm = ammm; - activateMouseMode(); - } - - /** - * Get the MapMouseMode used for the overview map. - */ - public MapMouseMode getMouseMode() { - return mmm; - } - - /** - * Adds the mouse mode as a listener to the overview map. If the mouse mode is - * null, the default is created. - */ - public void activateMouseMode() { - if (mmm == null) { - mmm = new DefaultOverviewMouseMode(this); - } - if (map != null) { - map.addMouseListener(mmm); - map.addMouseMotionListener(mmm); - } - } - - /** - * Disconnects the mouse mode from the overview map. - */ - public void deactivateMouseMode() { - if (mmm != null) { - map.removeMouseListener(mmm); - map.removeMouseMotionListener(mmm); - } - } - - /** - * Add a controlled MapBean to the OverviewMapHandler. Use this method to add - * another MapBean to the overview map in order to have its projection - * controlled by the overview panel. If the overview panel is clicked on, the - * listening MapBean will be recentered. If a box is drawn with a mouse drag, - * the scale of the controlled map will be modified. - * - * @param l MapBean. - */ - public void addControlledMap(MapBean l) { - if (l != null) { - if (controlledMaps == null) { - controlledMaps = new ControlledMapSupport(map); - // If nobody has been listening don't draw anything. - // Since someone is now being controlled, we'll do the - // drawing. - activateMouseMode(); - } - controlledMaps.add(l); - } - } - - /** - * Remove a controlled MapBean from the OverviewMapHandler. - * - * @param l a MapBean. - */ - public void removeControlledMap(MapBean l) { - if (controlledMaps != null) { - controlledMaps.remove(l); - - if (controlledMaps.isEmpty()) { - deactivateMouseMode(); - } - } - } - - /** - * Get the overview MapBean. - * - * @return overview MapBean. - */ - public MapBean getMap() { - return map; - } - - /** - * Set the overview MapBean. - */ - public void setMap(MapBean map) { - if (map != null) { - // get rid of any other MapBean that may have been added - // to the JPanel. - this.remove(map); - } - this.map = map; - this.add(map, BorderLayout.CENTER); - } - - /** - * Get the ControlledMapSupport, which usually contains the source map. - */ - public ControlledMapSupport getControlledMapListeners() { - return controlledMaps; - } - - /** - * Set the ControlledMapSupport, which usually contains the source map. - */ - public void setControlledMapListeners(ControlledMapSupport list) { - controlledMaps = list; - } - - /** - * Get the status layer, which is always drawn on top of the other layers, and - * maintained separately from other layers. - */ - public Layer getStatusLayer() { - return statusLayer; - } - - /** - * Get the status layer, which is always drawn on top of the other layers, and - * maintained separately from other layers. If the layer is also an - * OverviewMapStatusListener, it will receive source map projection changes, so - * it can draw stuff on itself representing what's going on the source map. - */ - public void setStatusLayer(Layer layer) { - statusLayer = layer; - } - - /** - * Set the scale factor to use between the source MapBean and the overview - * MapBean. It's a direct multiplier, so the overview MapBean can actually be a - * magnified map, too. The overview map scale = source MapBean scale * - * scaleFactor. - * - * @param setting scale factor - */ - public void setScaleFactor(float setting) { - scaleFactor = setting; - } - - /** - * Get the scale factor used for the overview MapBean. - */ - public float getScaleFactor() { - return scaleFactor; - } - - /** - * Set the projection of the overview MapBean. Lets you set the type, really. - * The scale and center will be reset when a projection event is received. - */ - public void setProjection(Proj proj) { - projection = proj; - } - - /** - * Get the current projection of the overview MapBean. - */ - public Proj getProjection() { - return projection; - } - - /** - * Set the minimum scale to use for the overview map. If this is set too small - * with a very general map layer, it won't be of any use, really, if it gets - * really zoomed in. - * - * @param setting the scale setting - 1:setting - */ - public void setMinScale(float setting) { - if (setting > 0) { - minScale = setting; - } - } - - /** - * Set the minimum scale to use for the overview map. If this is set too small - * with a very general map layer, it won't be of any use, really, if it gets - * really zoomed in. - * - * @param width setting the scale setting - 1:setting - * @param uom unit of measure for width - */ - public void setMinScale(float width, Length uom) { - if (width > 0) { - Projection p = map.getProjection(); - - Length projUom = p.getUcuom(); - - if (projUom == null) { - // We're going to assume meters, since this really only applies - // to pre-projected projections like Cartesian, and we might as - // well make it something. Not sure if it matters, as long as - // we're consistent. - projUom = Length.METER; - } - - // This is really not the radius but the half width in radians. - float radius = uom.toRadians(width) / 2; - - Point2D center = p.getCenter(); - Point2D left = new Point2D.Double(center.getX(), center.getY()); - Point2D right = new Point2D.Double(center.getX(), center.getY()); - - double newLeftX = projUom.fromRadians(projUom.toRadians(left.getX()) - radius); - double newRightX = projUom.fromRadians(projUom.toRadians(right.getX()) + radius); - - left.setLocation(newLeftX, left.getY()); - right.setLocation(newRightX, right.getY()); - - minScale = ProjMath.getScale(left, right, p); - } - } - - public float getMinScale() { - return minScale; - } - - /** - * Invoked when component has been shown. This component should be the component - * that contains the OverviewMapHandler. - */ - public void componentShown(ComponentEvent e) { - if (sourceMap != null) { - sourceMap.addProjectionListener(this); - } - } - - /** - * Invoked when component has been hidden. This component should be the - * component that contains the OverviewMapHandler. - */ - public void componentHidden(ComponentEvent e) { - if (sourceMap != null) { - sourceMap.removeProjectionListener(this); - } - } - - public void componentResized(ComponentEvent e) { - } - - public void componentMoved(ComponentEvent e) { - } - - /** - * Return an ActionListener that will bring up an independent window with an - * Overview Map. - * - * @return ActionListener that brings up a Window when an actionPerformed is - * called. - */ - public ActionListener getOverviewFrameActionListener() { - return new ActionListener() { - public void actionPerformed(ActionEvent evt) { - WindowSupport ws = getWindowSupport(); - - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - if (ws == null) { - ws = new WindowSupport(OverviewMapHandler.this, new WindowSupport.Dlg(frame, "Overview Map")); - setWindowSupport(ws); - } - - int w = INITIAL_WIDTH; - int h = INITIAL_HEIGHT; - Dimension dim = ws.getComponentSize(); - if (map != null && dim != null) { - w = (int) dim.getWidth(); - h = (int) dim.getHeight(); - } - - ws.displayInWindow(frame, -1, -1, w, h); - } - }; - } - - /** Tool interface method. */ - public Container getFace() { - JButton b = null; - if (getUseAsTool()) { - URL url = getClass().getResource("overview.gif"); - b = new JButton(new ImageIcon(url, frameTitle)); - b.setToolTipText(frameTitle); - b.setMargin(new Insets(0, 0, 0, 0)); - b.addActionListener(getOverviewFrameActionListener()); - b.setBorderPainted(false); - } - return b; - } - - /** - * Called when the OverviewMapHandler is added to the BeanContext, and whenever - * an object is added to the BeanContext after that. The OverviewMapHandler - * looks for a MapBean to use as a source map, and for a PropertiesHandler - * object to use to load itself with layers and other properties. If a source - * MapBean is already set and another MapBean is found, the last MapBean will be - * used as the source MapBean. Every time a PropertyHandler is found, the - * OverviewMapHandler will reinitialize itself. - * - * @param someObj the object being added to the BeanContext - */ - public void findAndInit(Object someObj) { - if (someObj instanceof com.bbn.openmap.MapBean) { - Debug.message("overview", "OverviewMapHandler found a MapBean object"); - setSourceMap((MapBean) someObj); - } - } - - /** - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - if (getSourceMap() == (MapBean) someObj) { - Debug.message("overview", "OverviewMapHandler: removing source MapBean"); - setSourceMap(null); - } - } - - if (someObj.equals(this)) { - dispose(); - } - } - - /** - * Support for directing the setCenter and setScale calls to any MapBeans that - * care to be listening. - */ - public class ControlledMapSupport extends ListenerSupport { - - private static final long serialVersionUID = 1L; - - /** - * Construct a ControlledMapSupport. - * - * @param aSource source Object - */ - public ControlledMapSupport(Object aSource) { - super(aSource); - } - - /** - * Set the center coordinates on all registered listeners. - * - * @param llp the new center point - */ - public void setCenter(Point2D llp) { - for (MapBean mapBean : this) { - mapBean.setCenter(llp); - } - } - - /** - * Set the scale on all registered listeners. - * - * @param scale the new scale - */ - public void setScale(float scale) { - for (MapBean mapBean : this) { - mapBean.setScale(scale); - } - } - } - - /** - * PropertyChangeListener method, to listen for the source map's background - * changes. Act on if necessary. - */ - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName() == MapBean.BackgroundProperty && backgroundSlave) { - map.setBckgrnd((Paint) pce.getNewValue()); - } - } - - public void dispose() { - controlledMaps.clear(); - map.dispose(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ProgressListenerGauge.java b/src/core/src/main/java/com/bbn/openmap/gui/ProgressListenerGauge.java deleted file mode 100644 index dc4c08e9a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ProgressListenerGauge.java +++ /dev/null @@ -1,143 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ProgressListenerGauge.java,v -// $ -// $RCSfile: ProgressListenerGauge.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.GridLayout; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressListener; - -public class ProgressListenerGauge extends JPanel implements ProgressListener { - - protected JLabel message; - protected JProgressBar jpb; - - protected boolean createWindowsForDisplay = false; - protected String title; - - protected WindowSupport windowSupport = null; - - public ProgressListenerGauge() { - init(); - } - - public ProgressListenerGauge(String windowTitle) { - createWindowsForDisplay = true; - title = windowTitle; - init(); - } - - protected synchronized void manageWindow(boolean visible) { - if (visible) { - if (windowSupport == null) { - windowSupport = new WindowSupport(this, title); - } - windowSupport.displayInWindow(); - } else { - if (windowSupport != null) { - windowSupport.killWindow(); - } - } - } - - protected synchronized void init() { - setLayout(new BorderLayout()); - add(new JLabel(" "), BorderLayout.EAST); - add(new JLabel(" "), BorderLayout.WEST); - add(new JLabel(" "), BorderLayout.NORTH); - add(new JLabel(" "), BorderLayout.SOUTH); - message = new JLabel(""); - jpb = new JProgressBar(0, 100); - JPanel cpanel = new JPanel(); - cpanel.setLayout(new GridLayout(0, 1)); - cpanel.add(jpb); - cpanel.add(message); - - add(cpanel, BorderLayout.CENTER); - - setPreferredSize(new Dimension(300, 75)); - } - - public synchronized void setVisible(boolean set) { - if (createWindowsForDisplay) { - manageWindow(set); - } else { - super.setVisible(set); - } - } - - public synchronized void updateProgress(ProgressEvent evt) { - if (SwingUtilities.isEventDispatchThread()) { - updateProgressFromEDT(evt); - } else { - SwingUtilities.invokeLater(new MyWorker(evt)); - } - } - - public synchronized void updateProgressFromEDT(ProgressEvent evt) { - int type = evt.getType(); - - if (type == ProgressEvent.START || type == ProgressEvent.UPDATE) { - setVisible(true); - message.setText(evt.getTaskDescription()); - jpb.setValue(evt.getPercentComplete()); - } else { - setVisible(false); - } - } - - public WindowSupport getWindowSupport() { - return windowSupport; - } - - public void setWindowSupport(WindowSupport windowSupport) { - this.windowSupport = windowSupport; - } - - class MyWorker implements Runnable { - - private ProgressEvent pe; - - public MyWorker(ProgressEvent pe) { - this.pe = pe; - } - - public void run() { - try { - updateProgressFromEDT(pe); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ProjectionStackTool.java b/src/core/src/main/java/com/bbn/openmap/gui/ProjectionStackTool.java deleted file mode 100644 index ba2c22b2e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ProjectionStackTool.java +++ /dev/null @@ -1,241 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ProjectionStackTool.java,v $ -// $RCSfile: ProjectionStackTool.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:49:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.util.Vector; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -import com.bbn.openmap.proj.ProjectionStack; -import com.bbn.openmap.proj.ProjectionStackTrigger; -import com.bbn.openmap.util.Debug; - -/** - * The ProjectionStackTool contains buttons that can trigger a - * ProjectionStack to change a projection of a MapBean to a previous - * projection, or to a later projection if the active projection is in - * the middle of the stack. The OpenMap ProjectionStack will look for - * one of these, and connect itself to it if it finds one. - */ -public class ProjectionStackTool extends OMToolComponent implements - ProjectionStackTrigger { - - protected Vector listeners; - - protected JButton backButton; - protected JButton forwardButton; - // protected JButton clearButton; - - protected static transient String backName = "backproj.gif"; - protected static transient String forwardName = "forwardproj.gif"; - protected static transient String dimBackName = "dimbackproj.gif"; - protected static transient String dimForwardName = "dimforwardproj.gif"; - - protected boolean dimBackButton = true; - protected boolean dimForwardButton = true; - - ImageIcon backIcon; - ImageIcon dimBackIcon; - ImageIcon forwardIcon; - ImageIcon dimForwardIcon; - - public ProjectionStackTool() { - super(); - setKey("projectionstacktool"); - resetButtons(!dimBackButton, !dimForwardButton); - add(backButton); - add(forwardButton); - // add(clearButton); - } - - /** - * Add an ActionListener for events that trigger events to shift - * the Projection stack. If you are hooking up a ProjectionStack, - * you don't need to call this. The ProjectionStack will call this - * when you can addProjectionStackTrigger on it. - */ - public void addActionListener(ActionListener al) { - if (backButton != null && forwardButton != null) { - backButton.addActionListener(al); - forwardButton.addActionListener(al); - // clearButton.addActionListener(al); - } else { - if (listeners == null) { - listeners = new Vector(); - } - listeners.add(al); - } - } - - /** - * Remove an ActionListener that receives events that trigger - * events to shift the Projection stack. If you are hooking up a - * ProjectionStack, you don't need to call this. The - * ProjectionStack will call this when you can - * removeProjectionStackTrigger on it. - */ - public void removeActionListener(ActionListener al) { - if (backButton != null && forwardButton != null) { - backButton.removeActionListener(al); - forwardButton.removeActionListener(al); - // clearButton.removeActionListener(al); - } else if (listeners != null) { - listeners.remove(al); - } - } - - /** - * To receive a status to let the trigger know if any projections - * in the forward or backward stacks exist, possibly to disable - * any gui widgets. - * - * @param containsBackProjections there is at least one past - * projection in the back cache. - * @param containsForwardProjections there is at least one future - * projection in the forward cache. Used when a past - * projection is being used. - */ - public void updateProjectionStackStatus(boolean containsBackProjections, - boolean containsForwardProjections) { - dimBackButton = !containsBackProjections; - dimForwardButton = !containsForwardProjections; - resetButtons(containsBackProjections, containsForwardProjections); - } - - public void resetButtons(boolean enableBackButton, - boolean enableForwardButton) { - - if (backIcon == null) { - backIcon = new ImageIcon(getClass().getResource(backName)); - } - - if (dimBackIcon == null) { - dimBackIcon = new ImageIcon(getClass().getResource(dimBackName)); - } - - if (forwardIcon == null) { - forwardIcon = new ImageIcon(getClass().getResource(forwardName)); - } - - if (dimForwardIcon == null) { - dimForwardIcon = new ImageIcon(getClass().getResource(dimForwardName)); - } - - ImageIcon active; - String toolTip; - String disabled = " (" - + i18n.get(ProjectionStackTool.class, "disabled", "disabled") - + ")"; - int size; - - toolTip = i18n.get(ProjectionStackTool.class, - "backTip", - "Go back to previous projection"); - if (enableBackButton) { - active = backIcon; - } else { - active = dimBackIcon; - toolTip += " " + disabled; - } - - if (backButton == null) { - backButton = new JButton(active); - backButton.setMargin(new Insets(0, 0, 0, 0)); - backButton.setBorderPainted(false); - backButton.setActionCommand(ProjectionStack.BackProjCmd); - if (listeners != null) { - size = listeners.size(); - for (int i = 0; i < size; i++) { - backButton.addActionListener((ActionListener) listeners.elementAt(i)); - - } - } - - } else { - backButton.setIcon(active); - } - backButton.setToolTipText(toolTip); - - toolTip = i18n.get(ProjectionStackTool.class, - "forwardTip", - "Go forward to next projection"); - if (enableForwardButton) { - active = forwardIcon; - } else { - active = dimForwardIcon; - toolTip += " " + disabled; - } - - if (forwardButton == null) { - forwardButton = new JButton(active); - forwardButton.setMargin(new Insets(0, 0, 0, 0)); - forwardButton.setBorderPainted(false); - forwardButton.setActionCommand(ProjectionStack.ForwardProjCmd); - - if (listeners != null) { - size = listeners.size(); - for (int i = 0; i < size; i++) { - forwardButton.addActionListener((ActionListener) listeners.elementAt(i)); - - } - } - } else { - forwardButton.setIcon(active); - } - forwardButton.setToolTipText(toolTip); - - // if (clearButton == null) { - // clearButton = new JButton("Clear Stack"); - // clearButton.setMargin(new Insets(0,0,0,0)); - // clearButton.setBorderPainted(false); - // clearButton.setActionCommand(ProjectionStack.ClearStacksCmd); - - // if (listeners != null) { - // size = listeners.size(); - // for (int i = 0; i < size; i++) { - // clearButton.addActionListener((ActionListener)listeners.elementAt(i)); - // } - // } - // } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof ProjectionStack) { - Debug.message("projectionstacktrigger", - "ProjectionStackTrigger adding a ProjectionStack"); - ((ProjectionStack) someObj).addProjectionStackTrigger(this); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof ProjectionStack) { - Debug.message("projectionstacktrigger", - "ProjectionStackTrigger removing a ProjectionStack"); - ((ProjectionStack) someObj).removeProjectionStackTrigger(this); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/RotTool.java b/src/core/src/main/java/com/bbn/openmap/gui/RotTool.java deleted file mode 100644 index 1c8c7331e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/RotTool.java +++ /dev/null @@ -1,81 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui; - -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.Length; - -public class RotTool extends OMToolComponent { - - protected MapBean map; - - public RotTool() { - JSlider slider = new JSlider(-180, 180, 0); - slider.addChangeListener(new ChangeListener() { - - public void stateChanged(ChangeEvent e) { - JSlider slider = (JSlider) e.getSource(); - int value = slider.getValue(); - - setRotation(Length.DECIMAL_DEGREE.toRadians(value)); - } - }); - this.add(slider); - } - - public void setRotation(double rot) { - if (map != null) { - map.setRotationAngle(rot); - } - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof MapBean) { - setMapBean((MapBean) someObj); - } - - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (getMapBean() == someObj) { - setMapBean(null); - } - } - - public void setMapBean(MapBean mb) { - map = mb; - } - - public MapBean getMapBean() { - return map; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ScaleTextPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/ScaleTextPanel.java deleted file mode 100644 index 67eae4af8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ScaleTextPanel.java +++ /dev/null @@ -1,272 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ScaleTextPanel.java,v $ -// $RCSfile: ScaleTextPanel.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/02/02 13:14:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.io.Serializable; - -import javax.swing.JTextField; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.event.ZoomSupport; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * The ScaleTextPanel is a JPanel holding a JTextField that controls - * and responds to the scale setting of a MapBean's projection. It is - * also a Tool, so it can be added to the ToolPanel. - */ -public class ScaleTextPanel extends OMToolComponent implements Serializable, - ActionListener, ProjectionListener { - - public final static String defaultScaleTextPanelKey = "scaletext"; - public transient final static String setScaleCmd = "setScale"; - - protected transient JTextField scaleField = null; - /** Support for zooming when text field is used. */ - protected transient ZoomSupport zoomDelegate = null; - /** - * The last projection received from the MapBean, so it can be - * used to compare it to any more that come in. The ScaleTextPanel - * listens to the MapBean for projection changes so it can keep up - * with any scale changes later. - */ - protected Projection projection; - - protected transient java.text.DecimalFormat df = new java.text.DecimalFormat("###,###,###"); - - /** - * Create the ScaleTextPanel - */ - public ScaleTextPanel() { - super(); - setKey(defaultScaleTextPanelKey); - - zoomDelegate = new ZoomSupport(this); - - String entry = ""; - String info = "Scale"; - String command = setScaleCmd; - - scaleField = new JTextField(entry, 10); - // scaleField.setToolTipText(info); - scaleField.setToolTipText(i18n.get(ScaleTextPanel.class, - command, - I18n.TOOLTIP, - info)); - scaleField.setMargin(new Insets(0, 0, 0, 0)); - scaleField.setActionCommand(command); - scaleField.addActionListener(this); - scaleField.setHorizontalAlignment(JTextField.RIGHT); - - gridbag.setConstraints(scaleField, c); - - add(scaleField); - } - - /** - * Called to set the scale setting on the scale text object. - */ - public synchronized void setProjection(Projection aProjection) { - projection = aProjection; - if (Debug.debugging("scaletextpanel")) { - System.out.println("ScaleTextPanel.setProjection(): scale is " - + projection.getScale() + " \"" - + String.valueOf(projection.getScale()) + "\""); - } - - String oldScale = scaleField.getText(); - String newScale = df.format(projection.getScale()); - - if (!oldScale.equals(newScale)) { - scaleField.setText("1:" + newScale); - } - } - - /** - * Add a ZoomListener to the listener list. - * - * @param listener The ZoomListener to be added - */ - public synchronized void addZoomListener(ZoomListener listener) { - zoomDelegate.add(listener); - } - - /** - * Remove a ZoomListener from the listener list. - * - * @param listener The ZoomListener to be removed - */ - public synchronized void removeZoomListener(ZoomListener listener) { - zoomDelegate.remove(listener); - } - - /** - * Convenience function to set up listeners of the components. If - * you are hooking the MapBean up to the ScaleTextPanel, this is - * one of two methods you need to call. The other is - * addMouseModes(), if the MapBean has more than one Mouse Mode. - * - * @param aMap a map object. - */ - public void setupListeners(MapBean aMap) { - if (aMap != null) { - // Wire up the beans for event passing - addZoomListener((ZoomListener) aMap); - aMap.addProjectionListener(this); - // set the scaleEntry - scaleField.setText("1:" + String.valueOf(aMap.getScale())); - } - } - - /** - * This function removes the mapBean object from its set of - * Listeners. An inverse of setupListeners() method. - * - * @param mapBean a map object. - */ - public void removeFromAllListeners(MapBean mapBean) { - if (mapBean != null) { - // Unwire the mapBean from these listeners - removeZoomListener((ZoomListener) mapBean); - mapBean.removeProjectionListener(this); - // set the scaleEntry to 0 - scaleField.setText("----"/* String.valueOf(0) */); - } - } - - /** - * Get the scale field widget. - * - * @return JTextField that is rigged to set the scale for the map. - */ - public JTextField getScaleField() { - return scaleField; - } - - /** - * ActionListener interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - - if (Debug.debugging("scaletextpanel")) { - Debug.output("ScaleTextPanel.actionPerformed(): " + command); - } - - if (command.equals(setScaleCmd)) { - setScale(scaleField.getText()); - } - } - - protected void fireScaleChange(float scale) { - if (Debug.debugging("scaletextpanel")) { - Debug.output("ScaleTextPanel setting scale to " + scale); - } - zoomDelegate.fireZoom(ZoomEvent.ABSOLUTE, scale); - } - - //set the scale of the map. - private void setScale(String strscale) { - float scale; - - int colon = strscale.indexOf(':'); - - if (colon > -1) { - strscale = strscale.substring(colon + 1); - } - - try { - if (strscale.toLowerCase().endsWith("m")) { - strscale = strscale.substring(0, strscale.length() - 1); - scale = df.parse(strscale).floatValue() * 1000000f; - if (scale < 1f) - System.err.println("ScaleTextPanel.applyScale(): problem"); - else - fireScaleChange(scale); - } else if (strscale.toLowerCase().endsWith("k")) { - strscale = strscale.substring(0, strscale.length() - 1); - scale = df.parse(strscale).floatValue() * 1000f; - if (scale < 1f) - System.err.println("ScaleTextPanel.applyScale(): problem"); - else - fireScaleChange(scale); - } else if (strscale.trim().length() == 0) { - return; // ignore empty string - } else { - scale = df.parse(strscale).floatValue(); - if (scale < 1f) - System.err.println("ScaleTextPanel.applyScale(): problem"); - else - fireScaleChange(scale); - } - } catch (java.text.ParseException e) { - System.err.println("ScaleTextPanel.setScale(): invalid scale: " - + strscale); - } catch (NumberFormatException e) { - System.err.println("ScaleTextPanel.setScale(): invalid scale: " - + strscale); - } - } - - //------------------------------------------------------------ - // ProjectionListener interface - //------------------------------------------------------------ - - /** - * ProjectionListener interface method. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - if (Debug.debugging("scaletextpanel")) { - System.out.println("ScaleTextPanel.projectionChanged()"); - } - Projection newProj = e.getProjection(); - if (projection == null || (!projection.equals(newProj))) { - setProjection((Projection) newProj.makeClone()); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setupListeners((MapBean) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - removeFromAllListeners((MapBean) someObj); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ScrollPaneWindowSupport.java b/src/core/src/main/java/com/bbn/openmap/gui/ScrollPaneWindowSupport.java deleted file mode 100644 index 91952fd7c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ScrollPaneWindowSupport.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; - -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneLayout; - -/** - * Alternative ScrollPaneLayout that returns a preferred layout size that - * properly takes the scroll bars sizes into account. This is a workaround for a - * display problem with the Nimbus Look & Feel. - */ -class OMScrollPaneLayout extends ScrollPaneLayout { - - @Override - public Dimension preferredLayoutSize(Container parent) { - Dimension dim = super.preferredLayoutSize(parent); - JScrollPane pane = (JScrollPane) parent; - Component comp = pane.getViewport().getView(); - Dimension viewPref = comp.getPreferredSize(); - Dimension port = pane.getViewport().getExtentSize(); - - if (port.height < viewPref.height) { - dim.width += pane.getVerticalScrollBar().getPreferredSize().width; - } - - if (port.width < viewPref.width) { - dim.height += pane.getHorizontalScrollBar().getPreferredSize().height; - } - return dim; - } - -} - -/** - * The ScrollPaneWindowSupport class does the same thing as WindowSupport, it - * just wraps content in a JScrollPane. - */ -public class ScrollPaneWindowSupport extends WindowSupport { - - /** - * Create the window support. - * - * @param content the content to display in the window. - * @param windowTitle the title of the window. - */ - public ScrollPaneWindowSupport(Component content, String windowTitle) { - super(content, windowTitle); - } - - /** - * Wrap content in a JScrollPane. - */ - public Component modifyContent(Component comp) { - - JScrollPane pane = new JScrollPane(comp); - - // Use an alternative layout in order to properly handle scroll bars - // with the Nimbus L&F - pane.setLayout(new OMScrollPaneLayout()); - - return pane; - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/StatusLightPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/StatusLightPanel.java deleted file mode 100644 index 8944d042f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/StatusLightPanel.java +++ /dev/null @@ -1,395 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/StatusLightPanel.java,v $ -// $RCSfile: StatusLightPanel.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.net.URL; -import java.util.Hashtable; -import java.util.Properties; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - */ -public class StatusLightPanel extends OMComponentPanel implements - LayerStatusListener, PropertyChangeListener, PropertyConsumer { - - protected int numlayers = 0; - protected MapBean map; - protected Layer[] layers; - protected Hashtable statusLights = new Hashtable(); - protected JComponent container = null; - - protected final static transient URL greyURL = StatusLightPanel.class.getResource("grey.gif"); - public final static transient ImageIcon greyIcon = new ImageIcon(greyURL, "unknown"); - - protected final static transient URL redURL = StatusLightPanel.class.getResource("red.gif"); - public final static transient ImageIcon redIcon = new ImageIcon(redURL, "working"); - - protected final static transient URL greenURL = StatusLightPanel.class.getResource("green.gif"); - public final static transient ImageIcon greenIcon = new ImageIcon(greenURL, "stable"); - - protected boolean waitingForLayers = false; - protected boolean showWaitCursor = false; - - /** - * Flag to make the status light buttons act as triggers to bring - * up the layer palettes. - */ - protected boolean lightTriggers = true; - public final static String LightTriggersProperty = "triggers"; - - public final static String defaultKey = "StatusLightPanel"; - protected String key = defaultKey; - - public StatusLightPanel() { - super(); - setLayout(new GridLayout(1, 0)); - reset(); - } - - public void setMap(MapBean map) { - if (this.map != null) { - this.map.removePropertyChangeListener(this); - } - - this.map = map; - - if (map != null) { - map.addPropertyChangeListener(this); - } - } - - public MapBean getMap() { - return map; - } - - /** - * Listen for the layer changes within the MapBean, to display the - * status lights for each layer. - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MapBean.LayersProperty) { - listenToLayers((Layer[]) evt.getNewValue()); - } - } - - /** - * Method to add the StatusLightPanel as an Information Display - * Event listener to a list of layers. Should not be called - * directly, because it is called as a result of the property - * change (layers) of the MapBean. - */ - protected void listenToLayers(Layer[] newLayers) { - if (SwingUtilities.isEventDispatchThread()) { - listenToLayersFromEDT(newLayers); - } else { - SwingUtilities.invokeLater(new MyWorker(newLayers)); - } - } - - protected void listenToLayersFromEDT(Layer[] newLayers) { - int i; - - if (layers != null) { - for (i = 0; i < layers.length; i++) { - if (layers[i] != null) { - layers[i].removeLayerStatusListener(this); - - boolean stillOnMap = false; - for (int j = 0; j < newLayers.length; j++) { - if (layers[i] == newLayers[j]) { - stillOnMap = true; - } - } - if (!stillOnMap) { - JButton light = (JButton) statusLights.get(layers[i]); - light.removeActionListener(layers[i]); - statusLights.remove(layers[i]); - } - - layers[i] = null; - } - } - } - - if (newLayers != null) { - for (i = 0; i < newLayers.length; i++) { - // Could call addLayer(newLayers[i] instead, but I - // don't want to call setStatusBar unnecessarily. - if (newLayers[i] != null) { - newLayers[i].addLayerStatusListener(this); - getStatusLightForLayer(newLayers[i]); - } else { - Debug.message("statuslights", - "StatusLightPanel: null layer in new layer array"); - } - } - layers = newLayers; - reset(); - } - } - - /** - * This method is really a get and set. The JLabel status gif is - * returned out of the HashTable for the layer. If the layer isn't - * in the HashTable, the new light is created, and a tooltip for - * it is set. - * - * @param layer the layer for the needed light. - * @return JLabel representing the status of the layer. - */ - protected JButton getStatusLightForLayer(Layer layer) { - if (layer == null) { - return null; - } - - JButton newLight = statusLights.get(layer); - - if (newLight == null) { - // newLight = new JButton(greyIcon); - newLight = new JButton(greenIcon); - newLight.setToolTipText(layer.getName()); - newLight.setMargin(new Insets(2, 1, 2, 1)); - statusLights.put(layer, newLight); - - if (lightTriggers) { - newLight.setActionCommand(Layer.DisplayPaletteCmd); - newLight.addActionListener(layer); - newLight.setBorderPainted(true); - } else { - newLight.setBorderPainted(false); - } - } - return newLight; - } - - /** - * The method that updates the StatusLight display with the - * correct layer status representation. - */ - public void reset() { - removeAll(); - if (container != null) { - container.removeAll(); - } - - if (lightTriggers) { -// if (container == null) { -// container = new JToolBar(); -// container.setFloatable(false); -// } - - if (container == null) { - container = new JPanel(); - container.setLayout(new FlowLayout(FlowLayout.LEFT,0,0)); - } - - add(container); - } else { - container = null; - } - - if (layers != null) { - for (int i = 0; i < layers.length; i++) { - JButton statusgif = getStatusLightForLayer(layers[i]); - if (statusgif != null) { - if (lightTriggers) { - container.add(statusgif); - } else { - add(statusgif); - } - } - } - } - revalidate(); - } - - /** - * Set the light in the window to be a certain color, depending on - * the working status. If the layer light isn't stored, the whole - * thing is blown off. If the icon is red, then the watch cursor - * is requested, if allowed by showWaitCursor. - * - * @param layer the layer to update. - * @param icon the icon light representing the status. - */ - protected void setLayerStatus(Layer layer, Icon icon) { - JButton statusgif = statusLights.get(layer); - if (statusgif != null) { - statusgif.setIcon(icon); - - if (this.map != null) { - if (icon == redIcon && showWaitCursor) { - // this.map.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - waitingForLayers = true; - } else if (icon == greenIcon) { - waitingForLayers = false; - for (JButton light : statusLights.values()) { - if (light.getIcon() == redIcon) { - waitingForLayers = true; - } - } - - // if (!waitingForLayers) { - // if (currentMapBeanCursor != null) { - // this.map.setCursor(currentMapBeanCursor); - // } else { - // resetCursor(); - // } - // } - } - } - } - } - - /////////////////////////////////////////// - // LayerStatusListener interface - - /** - * Update the Layer status. - * - * @param evt LayerStatusEvent - */ - public void updateLayerStatus(LayerStatusEvent evt) { - switch (evt.getStatus()) { - // these need to be coordinated correctly by the Layer, - // otherwise - // we'll get phantom status ticks or maybe an ArrayOutOfBounds - // negative... - case LayerStatusEvent.START_WORKING: - setLayerStatus((Layer) evt.getSource(), redIcon); - break; - case LayerStatusEvent.STATUS_UPDATE: - break; - case LayerStatusEvent.FINISH_WORKING: - setLayerStatus((Layer) evt.getSource(), greenIcon); - break; - default: - System.err.println("InformationDelegator.updateLayerStatus(): " - + "unknown status: " + evt.getStatus()); - break; - } - } - - /** - * Called when an object has been added to the BeanContext. The - * InformationDelegator will look for certain objects it needs. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setMap((MapBean) someObj); - } - } - - /** - * Called when an object is being removed from the BeanContext. - * Will cause the object to be disconnected from the - * InformationDelegator if it is being used. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - setMap(null); - } - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - setLightTriggers(PropUtils.booleanFromProperties(props, prefix - + LightTriggersProperty, lightTriggers)); - } - - public void setLightTriggers(boolean set) { - lightTriggers = set; - statusLights.clear(); - reset(); - } - - public boolean getLightTriggers() { - return lightTriggers; - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + LightTriggersProperty, - new Boolean(lightTriggers).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - PropUtils.setI18NPropertyInfo(i18n, - props, - StatusLightPanel.class, - LightTriggersProperty, - "Enable Triggers", - "Layer status indicators should launch layer palettes.", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } - - class MyWorker implements Runnable { - - private Layer[] layers; - - public MyWorker(Layer[] inLayers) { - layers = inLayers.clone(); - } - - public void run() { - try { - listenToLayersFromEDT(layers); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/Tool.java b/src/core/src/main/java/com/bbn/openmap/gui/Tool.java deleted file mode 100644 index e07e15dfd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/Tool.java +++ /dev/null @@ -1,73 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/Tool.java,v $ -// $RCSfile: Tool.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/03/06 15:41:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Container; - -/** - * Represents an item on the ToolPanel. If the Tool is a PropertyConsumer and a - * property prefix is used, the prefix should be used as the key as it is - * supposed to be unique and can be used as a known discriminator. - * - * @author john gash contributed to this notion of a Tool. - */ - -public interface Tool { - - /** - * The retrieval tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace(); - - /** - * The retrieval key for this tool. - * - * @return String The key for this tool. - */ - public String getKey(); - - /** - * Set the retrieval key for this tool. - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey); - - /** - * Set the orientation for the GUI of the Tool, SwingConstants.HORIZONTAL or - * SwingConstants.VERTICAL. - * - * @param orientation that should be set on tool. - */ - public void setOrientation(int orientation); - - /** - * Set the orientation for the GUI of the Tool, SwingConstants.HORIZONTAL or - * SwingConstants.VERTICAL. - * - * @return orientation that is set on tool - */ - public int getOrientation(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ToolPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/ToolPanel.java deleted file mode 100644 index 4249cc239..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ToolPanel.java +++ /dev/null @@ -1,686 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ToolPanel.java,v $ -// $RCSfile: ToolPanel.java,v $ -// $Revision: 1.13 $ -// $Date: 2006/03/06 15:41:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JLabel; -import javax.swing.JToolBar; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.gui.menu.ToolPanelToggleMenuItem; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * Represents the toolbar containing tools to apply to the map. Tools can be - * added in sequential order, and retrieved using the tool's keyword. NOTE: - * Every time a string is passed into a method of this class, the interned - * version of it is used as a key. - *

- * - * When the ToolPanel is part of the BeanContext, it looks for Tools that have - * also been added to the BeanContext. If there is more than one ToolPanel in a - * BeanContext at a time, both will show the same Tool faces. The 'components' - * property can be used to control which tools can be added to a specific - * instance of a ToolPanel. That property should contain a space separated list - * of prefixes used for Tools, which in turn should be set in the Tools as their - * keys. - * - * @see Tool - * @author john gash - */ -public class ToolPanel extends JToolBar - implements BeanContextChild, BeanContextMembershipListener, MapPanelChild, PropertyConsumer, ComponentListener { - - private static Logger logger = Logger.getLogger(ToolPanel.class.getName()); - private static final long serialVersionUID = 1L; - /** The set of tools contained on the toolbar. */ - protected Hashtable items = new Hashtable(); - /** - * A flag to note whether the ToolPanel inserts spaces between tools. - */ - protected boolean autoSpace = false; - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - private BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(this); - - /** - * The property prefix used for this ToolPanel. - */ - protected String propertyPrefix = null; - - /** - * A list of components to use for filtering tools found in the MapHandler - * to add to this ToolPanel. - */ - public final static String ComponentsProperty = "components"; - - /** - * A list of components to use for filtering out tools found in the - * MapHandler. Components added to this list will NOT be added to this - * ToolPanel. - */ - public final static String AvoidComponentsProperty = "avoid"; - - public final static String MembershipProperty = "membership"; - - public final static String NameProperty = "name"; - - /** - * A filter list of components to look for and add. - */ - protected List componentList = null; - - /** - * A filter list of components to avoid. - */ - protected List avoidList = null; - - protected GridBagLayout gridbag = new GridBagLayout(); - protected GridBagConstraints c = new GridBagConstraints(); - protected String parentName = null; - - /** - * Holder that expands in the GridBagLayout, keeping things pushed to the - * left side of the toolpanel. - */ - protected JLabel filler = null; - - /** - * Constructor - */ - public ToolPanel() { - setLayout(gridbag); - setFloatable(false); - setVisible(false); - setName("Tool Panel"); - } - - /** - * Add an item to the tool bar. - * - * @param key The key associated with the item. - * @param item The Tool to add. - */ - public void add(String key, Tool item) { - add(key, item, -1); - } - - /** - * A little array used to track what indexes are already used, to prevent - * the GridBagLayout from placing things on top of each other. - */ - protected boolean[] usedIndexes; - public int MAX_INDEXES = 101; - - /** - * Provides the next available component index for placement, starting at 0. - */ - protected int getNextAvailableIndex() { - return getNextAvailableIndex(0); - } - - /** - * Provides the next available component index for placement, given a - * starting index. - */ - protected int getNextAvailableIndex(int startAt) { - - if (usedIndexes == null) { - usedIndexes = new boolean[MAX_INDEXES]; - } - - if (startAt < 0) - startAt = 0; - if (startAt >= MAX_INDEXES) - startAt = MAX_INDEXES - 1; - - int i = startAt; - // Find the first unused - for (; i < MAX_INDEXES && usedIndexes[i] == true; i++) { - } - usedIndexes[i] = true; - - return i; - } - - /** - * Add an item to the tool bar. - * - * @param key The key associated with the item. - * @param item The Tool to add. - * @param index The position index for placement of the tool. -1 puts it at - * the end, and if the position is greater than the size, it is - * placed at the end. This class does not remember where items - * were asked to be placed, so later additions may mess up - * intended order. - */ - public void add(String key, Tool item, int index) { - - int orientation = getOrientation(); - boolean hOrient = orientation == SwingConstants.HORIZONTAL; - item.setOrientation(orientation); - - Container face = item.getFace(); - - if (face != null) { - face.addComponentListener(this); - items.put(key.intern(), item); - - if (autoSpace) { - index *= 2; - } - - if (hOrient) { - c.weightx = 0; - c.gridx = getNextAvailableIndex(index); - c.gridy = 0; - c.anchor = GridBagConstraints.WEST; - } else { - c.weighty = 0; - c.gridx = 0; - c.gridy = getNextAvailableIndex(index); - c.anchor = GridBagConstraints.NORTH; - } - - gridbag.setConstraints(face, c); - add(face); - - if (filler == null) { - if (hOrient) { - c.gridx = getNextAvailableIndex(MAX_INDEXES); - c.anchor = GridBagConstraints.EAST; - c.weightx = 1; - } else { - c.gridy = getNextAvailableIndex(MAX_INDEXES); - c.anchor = GridBagConstraints.SOUTH; - c.weighty = 1; - } - - filler = new JLabel(""); - gridbag.setConstraints(filler, c); - add(filler); - } - - if (autoSpace) { - JLabel l = new JLabel(" "); - gridbag.setConstraints(l, c); - add(l); - } - } - - setVisibility(); - firePropertyChange(MembershipProperty, null, items); - } - - /** - * Add an item to the tool bar. Assumes that the key will be picked out of - * the Tool. - * - * @param item The Tool to add. - */ - public void add(Tool item) { - add(item, -1); - } - - /** - * Add an item to the tool bar. Assumes that the key will be picked out of - * the Tool. - * - * @param item The Tool to add. - * @param index The position to add the Tool. -1 will add it to the end. - */ - public void add(Tool item, int index) { - try { - add(item.getKey(), item, index); - } catch (NullPointerException npe) { - if (item != null) { - logger.warning("ToolPanel.add(): no name for " + item.getClass().getName()); - npe.printStackTrace(); - } else { - logger.warning("ToolPanel.add(): no name for null tool."); - } - } - } - - /** - * Get an item from the tool bar. - * - * @param key The key associated with the item. - * @return The tool associated with the key, null if not found. - */ - public Tool get(String key) { - return (Tool) items.get(key.intern()); - } - - /** Remove a tool with the right key */ - public void remove(String key) { - Tool tool = (Tool) items.remove(key.intern()); - if (tool != null) { - Container face = tool.getFace(); - if (face != null) { - remove(face); - face.removeComponentListener(this); - firePropertyChange(MembershipProperty, null, items); - } - } - } - - /** Add a space between tools. */ - protected void addSpace() { - add(new JLabel(" ")); - } - - /** Set whether spaces are placed between tools. */ - public void setAutoSpace(boolean set) { - autoSpace = set; - } - - /** - * BorderLayout.NORTH by default for this class. - */ - protected String preferredLocation = java.awt.BorderLayout.NORTH; - - /** - * MapPanelChild method. - */ - public void setPreferredLocation(String value) { - preferredLocation = value; - } - - /** MapPanelChild method. */ - public String getPreferredLocation() { - return preferredLocation; - } - - /** Find out whether spaces are being placed between tools. */ - public boolean isAutoSpace() { - return autoSpace; - } - - /** - * Set the list of strings used by the ToolPanel to figure out which Tools - * should be added (in the findAndInit()) method and where they should go. - */ - public void setComponentList(List list) { - componentList = list; - } - - /** - * Get the list of strings used by the ToolPanel to figure out which Tools - * should be added (in the findAndInit()) method and where they should go. - */ - public List getComponentList() { - return componentList; - } - - /** - * Set the list of strings used by the ToolPanel to figure out which Tools - * should not be added (in the findAndInit()) method. - */ - public void setAvoidList(List list) { - avoidList = list; - } - - /** - * Get the list of strings used by the ToolPanel to figure out which Tools - * should not be added (in the findAndInit()) method. - */ - public List getAvoidList() { - return avoidList; - } - - /** - * Called when the ToolPanel is added to the BeanContext, and when new - * objects are added to the BeanContext after that. The ToolPanel looks for - * Tools that are part of the BeanContext. - * - * @param it iterator to use to go through the new objects. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Figure out if the string key is in the provided list, and provide the - * location index of it is. - * - * @param key the key of the component to check for. - * @param list the list of keys to check. - * @return -1 if not on the list, the index starting at 0 if it is. - */ - protected int keyOnList(String key, List list) { - int ret = -1; - int index = 0; - if (list != null) { - for (String listKey : list) { - if (listKey.equalsIgnoreCase(key)) { - ret = index; - break; - } - index++; - } - } - return ret; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof Tool) { - String key = ((Tool) someObj).getKey(); - List list = getComponentList(); - int index; - if (list != null) { - index = keyOnList(key, list); - - if (index >= 0) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "ToolPanel: found a tool Object {0} for placement at {1}", - new Object[] { key, index }); - } - - add((Tool) someObj, index); - } - - } else { - index = keyOnList(key, getAvoidList()); - if (index < 0) { - logger.fine("ToolPanel: found a tool Object"); - add((Tool) someObj); - } - } - } - } - - /** - * Get a menu item that controls the visibility of this ToolPanel. - * - * @return ToolPanelToggleMenuItem - */ - public ToolPanelToggleMenuItem getToggleMenu() { - return new ToolPanelToggleMenuItem(this); - } - - /** - * Checks to see if the menu item controls this ToolPanel. - * - * @param mi - * @return true if menu item refers to this tool panel. - */ - public boolean checkToolPanelToggleMenuItem(ToolPanelToggleMenuItem mi) { - return (mi != null && mi.getToolPanel().equals(this)); - } - - /** - * BeanContextMembershipListener method. Called when objects have been added - * to the parent BeanContext. - * - * @param bcme the event containing the iterator with new objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when objects have been - * removed from the parent BeanContext. If the ToolPanel finds a Tool in the - * list, it removes it from the ToolPanel. - * - * @param bcme the event containing the iterator with removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - Object someObj; - while (it.hasNext()) { - someObj = it.next(); - if (someObj instanceof Tool) { - // do the initializing that need to be done here - logger.fine("ToolPanel removing tool Object"); - remove(((Tool) someObj).getKey()); - } - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Called when the ToolPanel is added - * to the BeanContext. - * - * @param in_bc the BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - public String getPropertyPrefix() { - return propertyPrefix; - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String componentsString = props.getProperty(prefix + ComponentsProperty); - - if (componentsString != null) { - setComponentList(PropUtils.parseSpacedMarkers(componentsString)); - } - - String avoidComponentsString = props.getProperty(prefix + AvoidComponentsProperty); - - if (avoidComponentsString != null) { - setAvoidList(PropUtils.parseSpacedMarkers(avoidComponentsString)); - } - - String preferredLocationString = props.getProperty(prefix + PreferredLocationProperty); - - if (preferredLocationString != null) { - try { - preferredLocationString = (String) java.awt.BorderLayout.class.getField(preferredLocationString) - .get(null); - } catch (NoSuchFieldException nsfe) { - preferredLocationString = null; - } catch (IllegalAccessException iae) { - preferredLocationString = null; - } - - if (preferredLocationString != null) { - setPreferredLocation(preferredLocationString); - if (preferredLocationString.equalsIgnoreCase("WEST") - || preferredLocationString.equalsIgnoreCase("EAST")) { - setOrientation(SwingConstants.VERTICAL); - } - } - } - - setName(props.getProperty(prefix + NameProperty, getName())); - setParentName(props.getProperty(prefix + ParentNameProperty, getParentName())); - } - - /** - * Take a List of strings, and return a space-separated version. Return null - * if the List is null. - */ - protected StringBuffer rebuildListProperty(List aList) { - StringBuffer list = null; - if (aList != null) { - list = new StringBuffer(); - for (String toolKey : aList) { - list.append(toolKey).append(" "); - } - } - return list; - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer listProp = rebuildListProperty(getComponentList()); - if (listProp != null) { - props.put(prefix + ComponentsProperty, listProp.toString()); - } - - listProp = rebuildListProperty(getAvoidList()); - if (listProp != null) { - props.put(prefix + AvoidComponentsProperty, listProp.toString()); - } - - PropUtils.putIfNotDefault(props, prefix + PreferredLocationProperty, getPreferredLocation()); - PropUtils.putIfNotDefault(props, prefix + NameProperty, getName()); - PropUtils.putIfNotDefault(props, prefix + ParentNameProperty, getParentName()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - I18n i18n = Environment.getI18n(); - - PropUtils.setI18NPropertyInfo(i18n, props, ToolPanel.class, ComponentsProperty, "Tool Names", - "List of Names of Tools to Add", null); - PropUtils.setI18NPropertyInfo(i18n, props, ToolPanel.class, AvoidComponentsProperty, "Avoid Tool Names", - "List of Names of Tools to Not Add", null); - PropUtils.setI18NPropertyInfo(i18n, props, ToolPanel.class, PreferredLocationProperty, "Location", - "Preferred Location of Tool Panel", null); - PropUtils.setI18NPropertyInfo(i18n, props, ToolPanel.class, NameProperty, "Tool Name", - "Name of This Tool Panel", null); - - return props; - } - - /** - * If any of the components are visible, set the ToolPanel to be visible. If - * all of them are invisible, make the ToolPanel invisible. - */ - protected void setVisibility() { - setVisible(areComponentsVisible()); - } - - public boolean areComponentsVisible() { - Enumeration enumeration = items.elements(); - while (enumeration.hasMoreElements()) { - Tool tool = enumeration.nextElement(); - Container face = tool.getFace(); - // make sure tool != filler - filler(JPanel) test is for object - // equivalence - if (!tool.equals(filler) && face != null && face.isVisible()) { - return true; - } - } - return false; - } - - public void componentHidden(ComponentEvent ce) { - setVisibility(); - } - - public void componentMoved(ComponentEvent ce) { - - } - - public void componentResized(ComponentEvent ce) { - - } - - public void componentShown(ComponentEvent ce) { - setVisibility(); - } - - public String getParentName() { - return parentName; - } - - public void setParentName(String parentName) { - this.parentName = parentName; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/UTMCoordPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/UTMCoordPanel.java deleted file mode 100644 index 8b526d830..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/UTMCoordPanel.java +++ /dev/null @@ -1,180 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/UTMCoordPanel.java,v $ -// $RCSfile: UTMCoordPanel.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.Serializable; - -import javax.swing.JLabel; -import javax.swing.JTextField; -import javax.swing.border.EtchedBorder; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.UTMPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * UTMCoordPanel is a simple gui with entry boxes and labels for Zone - * number and letters, and easting and northing representation of - * latitude and longitude. It sets the center of a map with the - * entered coordinates by firing CenterEvents. - */ -public class UTMCoordPanel extends CoordPanel implements Serializable { - - protected transient JTextField zoneLetter, zoneNumber, easting, northing; - - /** - * Creates the panel. - */ - public UTMCoordPanel() { - super(); - } - - /** - * Creates the panel. - */ - public UTMCoordPanel(CenterSupport support) { - super(support); - } - - /** - * Creates and adds the labels and entry fields for latitude and - * longitude - */ - protected void makeWidgets() { - String locText; - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - Insets leftInsets = new Insets(0, 10, 0, 10); - Insets centerInsets = new Insets(0, 0, 0, 0); - Insets rightInsets = new Insets(0, 0, 0, 10); - - setLayout(gridbag); - locText = i18n.get(UTMCoordPanel.class, - "border", - "Zone Number|Hemisphere|Easting|Northing"); - setBorder(new TitledBorder(new EtchedBorder(), locText)); - - locText = i18n.get(UTMCoordPanel.class, "utmLabel", "UTM: "); - JLabel utmLabel = new JLabel(locText); - c.gridx = 0; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.insets = leftInsets; - c.anchor = GridBagConstraints.EAST; - gridbag.setConstraints(utmLabel, c); - add(utmLabel); - - c.gridx = GridBagConstraints.RELATIVE; - zoneNumber = new JTextField(3); - zoneNumber.setToolTipText(i18n.get(UTMCoordPanel.class, - "zone", - I18n.TOOLTIP, - "Zone Number: 1-60")); - c.insets = centerInsets; - gridbag.setConstraints(zoneNumber, c); - add(zoneNumber); - - zoneLetter = new JTextField(2); - zoneLetter.setToolTipText(i18n.get(UTMCoordPanel.class, - "hemi", - I18n.TOOLTIP, - "Hemisphere: N or S")); - gridbag.setConstraints(zoneLetter, c); - add(zoneLetter); - - easting = new JTextField(8); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = .5f; - gridbag.setConstraints(easting, c); - add(easting); - - northing = new JTextField(8); - c.insets = rightInsets; - gridbag.setConstraints(northing, c); - add(northing); - } - - /** - * @return the LatLonPoint represented by contents of the entry - * boxes - */ - public LatLonPoint getLatLon() { - int iZoneNumber; - char cZoneLetter; - - try { - // Allow blank minutes and seconds fields to represent - // zero - iZoneNumber = Float.valueOf(zoneNumber.getText()).intValue(); - cZoneLetter = zoneLetter.getText().charAt(0); - - float minEasting = easting.getText().length() == 0 ? 0f - : Float.valueOf(easting.getText()).floatValue(); - easting.setText(Float.toString(Math.abs(minEasting))); - - float minNorthing = northing.getText().length() == 0 ? 0 - : Float.valueOf(northing.getText()).floatValue(); - northing.setText(Float.toString(Math.abs(minNorthing))); - - UTMPoint utm = new UTMPoint(minNorthing, minEasting, iZoneNumber, cZoneLetter); - return utm.toLatLonPoint(); - - } catch (NumberFormatException except) { - Debug.output(except.toString()); - clearTextBoxes(); - } - return null; - } - - /** - * Sets the contents of the latitude and longitude entry boxes - * - * @param llpoint the object containing the coordinates that - * should go in the boxes. - */ - public void setLatLon(LatLonPoint llpoint) { - if (llpoint == null) { - clearTextBoxes(); - return; - } - - UTMPoint utm = new UTMPoint(llpoint); - northing.setText(Double.toString(utm.northing)); - easting.setText(Double.toString(utm.easting)); - zoneNumber.setText(Integer.toString(utm.zone_number)); - zoneLetter.setText((char) utm.zone_letter + ""); - } - - protected void clearTextBoxes() { - northing.setText(""); - easting.setText(""); - zoneLetter.setText(""); - zoneNumber.setText(""); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/UserGuideMenuItems.java b/src/core/src/main/java/com/bbn/openmap/gui/UserGuideMenuItems.java deleted file mode 100644 index a05138c9d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/UserGuideMenuItems.java +++ /dev/null @@ -1,253 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/UserGuideMenuItems.java,v $ -// $RCSfile: UserGuideMenuItems.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.Vector; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.InformationDelegator; - -/** - * This class provides MenuItems that get added under HelpMenu. This - * object needs an instance of InformationDelegator, which can be set - * programmatically. If this objects environment is capable of - * providing BeanContextServices, it will look for - * InformationDelegator as a service. - */ -public class UserGuideMenuItems implements HelpMenuItems, ActionListener, - BeanContextMembershipListener, BeanContextChild { - private InformationDelegator informationDelegator; - private Vector menuItems = new Vector(); - - public UserGuideMenuItems() { - JMenuItem mi = new JMenuItem("OpenMap"); - mi.addActionListener(this); - getMenuItems().add(mi); - } - - /** - * Initializes the object with given InformationDelegator. - * - * @param in_informationDelegator - */ - public UserGuideMenuItems(InformationDelegator in_informationDelegator) { - setInformationDelegator(in_informationDelegator); - } - - /** - * @param in_informationDelegator - */ - public void setInformationDelegator( - InformationDelegator in_informationDelegator) { - informationDelegator = in_informationDelegator; - } - - /** - * Return current value of InformationDelegator. - */ - protected InformationDelegator getInformationDelegator() { - return informationDelegator; - } - - /** - * Returns a vector of MenuItems that are part of this object. - */ - protected Vector getMenuItems() { - return menuItems; - } - - /** - * Returns an Iterator to the MenuItems it holds. - */ - public Iterator iterator() { - return getMenuItems().iterator(); - } - - /** - * Called when our menu item is clicked by user. - */ - public void actionPerformed(ActionEvent ae) { - // check if we have the object that generated this event. if - // yes do it else complain - if (getMenuItems().contains(ae.getSource())) { - if (informationDelegator != null) { - informationDelegator.displayURL(Environment.get(Environment.HelpURL, - "http://javamap.bbn.com/projects/openmap/openmap_maindes.html")); - } - } - } - - /////////////////////////////////////////////////////////////////////////// - //// MapHandlerChild methods to make the tool work with - //// the MapHandler to find any SelectionProviders. - /////////////////////////////////////////////////////////////////////////// - - public void findAndInit(Object obj) { - if (obj instanceof InformationDelegator) { - setInformationDelegator((InformationDelegator) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof InformationDelegator) { - setInformationDelegator(null); - } - } - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * This is the method that your object can use to find other - * objects within the MapHandler (BeanContext). This method gets - * called when the object gets added to the MapHandler, or when - * another object gets added to the MapHandler after the object is - * a member. - * - * @param it Iterator to use to go through a list of objects. Find - * the ones you need, and hook yourself up. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object - * is added to the BeanContext of this object. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when a new object - * is removed from the BeanContext of this object. For the Layer, - * this method doesn't do anything. If your layer does something - * with the childrenAdded method, or findAndInit, you should take - * steps in this method to unhook the layer from the object used - * in those methods. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Adds this object as a - * BeanContextMembership listener, set the BeanContext in this - * objects BeanContextSupport, and receives the initial list of - * objects currently contained in the BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** - * Method for BeanContextChild interface. Uses the - * BeanContextChildSupport to add a listener to this object's - * property. This listener wants to have the right to veto a - * property change. - */ - public void addVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the - * BeanContextChildSupport to remove a listener to this object's - * property. The listener has the power to veto property changes. - */ - public void removeVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, - in_vcl); - } - - /** - * Report a vetoable property update to any registered listeners. - * If anyone vetos the change, then fire a new event reverting - * everyone to the old value and then rethrow the - * PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about - * to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the - * property change to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, - in_pcl); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/WindowSupport.java b/src/core/src/main/java/com/bbn/openmap/gui/WindowSupport.java deleted file mode 100644 index de42640e2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/WindowSupport.java +++ /dev/null @@ -1,814 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/WindowSupport.java,v $ -// $RCSfile: WindowSupport.java,v $ -// $Revision: 1.14.2.9 $ -// $Date: 2007/03/08 19:22:19 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GraphicsDevice; -import java.awt.GraphicsEnvironment; -import java.awt.Point; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Iterator; - -import javax.imageio.ImageIO; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JLayeredPane; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.util.Debug; - -/** - * The WindowSupport class provides support for managing JFrames or - * JInternalFrames for other components. The frame is disposed of when the - * window is closed, and recreated when displayInWindow is called. The - * WindowSupport remembers size and location changes for the window when it is - * recreated. - *

- * - * The WindowSupport class now has inner classes that are used to create - * different types of windows for components. Dlg is used for JDialogs, which - * remain on top of the main application frame even when they don't have focus. - * IntrnlFrm is used for JInternalFrames, for windows that get clipped if the - * move off the area of the main application. Frm is used for a standard JFrame - * which can be obscured by the main application window. Components are free to - * specify which WSDisplay type they always want to be display in, or they can - * ask for a standard WindowSupport object which will use the static - * defaultWindowSupportDisplayType variable to determine the WSDisplay type (for - * a consistent feel across the application). The default setting for this - * variable is to use the Frm type. - */ -public class WindowSupport extends ListenerSupport implements ComponentListener, - ActionListener { - - protected Component content; - protected String title; - protected Point componentLocation; - protected Dimension componentSize; - - public final static String DisplayWindowCmd = "displayWindowCmd"; - public final static String KillWindowCmd = "killWindowCmd"; - - protected transient WSDisplay display; - - protected static Class defaultWindowSupportDisplayType = Frm.class; - - /** - * Create the window support. - * - * @param content the content to display in the window. - * @param windowTitle the title of the window. - */ - public WindowSupport(Component content, String windowTitle) { - super(content); - setContent(content); - this.title = windowTitle; - } - - public WindowSupport(Component content, WSDisplay display) { - super(content); - setContent(content); - setDisplay(display); - if (display != null) { - this.title = display.getTitle(); - } - } - - /** - * Set the location of the window. - */ - public void setComponentLocation(Point p) { - componentLocation = p; - } - - /** - * Get the location of the window. - */ - public Point getComponentLocation() { - return componentLocation; - } - - /** - * Set the size of the window. - */ - public void setComponentSize(Dimension dim) { - componentSize = dim; - } - - /** - * Get the size of the window. - */ - public Dimension getComponentSize() { - return componentSize; - } - - /** - * ComponentListener method, new size is noted. - */ - public void componentResized(ComponentEvent e) { - Component source = (Component) e.getSource(); - setComponentSize(source.getSize()); - - Iterator it = iterator(); - while (it.hasNext()) { - ((ComponentListener) it.next()).componentResized(e); - } - } - - /** - * ComponentListener method, new location is noted. - */ - public void componentMoved(ComponentEvent e) { - setComponentLocation(((Component) e.getSource()).getLocation()); - Iterator it = iterator(); - while (it.hasNext()) { - ((ComponentListener) it.next()).componentMoved(e); - } - } - - /** - * ComponentListener method. - */ - public void componentShown(ComponentEvent e) { - Iterator it = iterator(); - while (it.hasNext()) { - ((ComponentListener) it.next()).componentShown(e); - } - } - - /** - * ComponentListener method. WindowSupport kills the window when it is - * hidden. - */ - public void componentHidden(ComponentEvent e) { - Iterator it = iterator(); - while (it.hasNext()) { - ((ComponentListener) it.next()).componentHidden(e); - } - - // We need to do this after componentHidden notifications, - // otherwise the component never finds out it's been hidden, - // it gets removed as a ComponentListener at cleanup. - Component source = (Component) e.getSource(); - if (display == source) { - cleanUp(); - } - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - if (command == KillWindowCmd) { - killWindow(); - } else if (command == DisplayWindowCmd) { - displayInWindow(); - } - } - - protected void finalize() { - if (Debug.debugging("gc")) { - Debug.output("WindowSupport being gc'd"); - } - } - - /** - * Sets the title of the JInternalFrame/JDialog. - */ - public void setTitle(String tle) { - title = tle; - if (display != null) { - display.setTitle(tle); - } - } - - public String getTitle() { - return title; - } - - /** - * Sets the content in the JInternalFrame/JDialog. - */ - public void setContent(Component comp) { - - if (content instanceof ComponentListener) { - removeComponentListener((ComponentListener) content); - } - - content = comp; - if (display != null) { - display.setContent(comp); - } - - if (content instanceof ComponentListener) { - addComponentListener((ComponentListener) content); - } - } - - public Component getContent() { - return content; - } - - protected int maxHeight = -1; - protected int maxWidth = -1; - - /** - * Sets the maximum pixel size of the window. If you don't care about a - * particular dimension, set it to be less than zero and the natural size of - * the content will be displayed. - */ - public void setMaxSize(int width, int height) { - maxHeight = height; - maxWidth = width; - } - - /** - * Called when a component hasn't specified what kind of window they want. - * If the Environment.useInternalFrames flag isn't set, then the - * getDefaultWindowSupportDisplayType() method is called to find out which - * WSDisplay type class should be created for the component. IF that returns - * null, a Frm is created. - * - * @param owner - * @return WSDisplay - */ - protected WSDisplay createDisplay(Frame owner) { - WSDisplay wsd; - if (persistentDisplayType == null && Environment.getBoolean(Environment.UseInternalFrames)) { - wsd = new IntrnlFrm(title); - } else { - Class wTypeClass = persistentDisplayType == null ? getDefaultWindowSupportDisplayType() - : persistentDisplayType; - if (wTypeClass == Dlg.class) { - wsd = new Dlg(owner, title); - } else if (wTypeClass == IntrnlFrm.class) { - wsd = new IntrnlFrm(title); - } else { - wsd = new Frm(title); - } - } - setFavIcon(wsd); - setDisplay(wsd); - return wsd; - } - - /** - * Called when a display type is known, and may override the default - * settings. A Frm is created if the displayType is not null but not a valid - * WSDisplay type. - * - * @param owner - * @param displayType a WSDisplay class to create. If null, the - * persistentDisplayType will be used. - * @return WSDisplay - */ - protected WSDisplay createDisplay(Frame owner, Class displayType) { - WSDisplay wsd; - - if (displayType == null) { - return createDisplay(owner); - } - - if (displayType == Dlg.class) { - wsd = new Dlg(owner, title); - } else if (displayType == IntrnlFrm.class) { - wsd = new IntrnlFrm(title); - } else { - wsd = new Frm(title); - } - - setDisplay(wsd); - return wsd; - } - - public static Class getDefaultWindowSupportDisplayType() { - return defaultWindowSupportDisplayType; - } - - public static void setDefaultWindowSupportDisplayType(Class defaultWindowSupportDisplayType) { - WindowSupport.defaultWindowSupportDisplayType = defaultWindowSupportDisplayType; - } - - public void setDisplay(WSDisplay dis) { - if (display != null) { - display.removeComponentListener(this); - } - - display = dis; - if (display != null) { - display.addComponentListener(this); - display.setContent(modifyContent(content)); - } - - } - - /** - * Subclass method to allow modifications to content, wrappers, etc. This - * version just returns comp. - */ - public Component modifyContent(Component comp) { - return comp; - } - - public WSDisplay getDisplay() { - return display; - } - - /** - * Display the window, and find out what the natural or revised size and - * location are for the window. - */ - public void displayInWindow() { - displayInWindow(null); - } - - /** - * Display the window, and find out what the natural or revised size and - * location are for the window. - * - * @param owner Frame for JDialog - */ - public void displayInWindow(Frame owner) { - - Dimension dim = getComponentSize(); - if (dim != null) { - content.setSize(dim); - } - - // -1 is a flag for the positioning code to recenter the - // -window on the owner if it's not null, for JDialogs. - - displayInWindow(owner, -1, -1, -1, -1); - } - - /** - * Display the window. - * - * @param x the horizontal pixel location for the window. - * @param y the vertical pixel location for the window. - * @param width the horizontal size of the window, if less than or equal to - * zero the content size will be used. - * @param height the vertical size of the window, if less than or equal to - * zero the content size will be used. - */ - public void displayInWindow(int x, int y, int width, int height) { - displayInWindow(null, x, y, width, height); - } - - /** - * Display the window. - * - * @param owner Frame for JDialog - * @param x the horizontal pixel location for the window. - * @param y the vertical pixel location for the window. - * @param width the horizontal size of the window, if less than or equal to - * zero the content size will be used. - * @param height the vertical size of the window, if less than or equal to - * zero the content size will be used. - */ - public void displayInWindow(Frame owner, int x, int y, int width, int height) { - displayInWindow(owner, null, x, y, width, height); - } - - /** - * Display the window. - * - * @param owner Frame for JDialog - * @param displayType the WSDisplay class to use for the window. - * @param x the horizontal pixel location for the window. - * @param y the vertical pixel location for the window. - * @param width the horizontal size of the window, if less than or equal to - * zero the content size will be used. - * @param height the vertical size of the window, if less than or equal to - * zero the content size will be used. - */ - public void displayInWindow(Frame owner, Class displayType, int x, int y, int width, int height) { - - if (content == null) { - Debug.message("windowsupport", "WindowSupport asked to display window with null content"); - return; - } - - if (x < 0 && y < 0) { - // See if we can remember where we were... - Point loc = getComponentLocation(); - if (loc != null) { - x = (int) loc.getX(); - y = (int) loc.getY(); - } - } - - if (display != null && displayType != null - && !display.getClass().getName().equals(displayType.getName())) { - display.dispose(); - display = null; - } - - if (display == null) { - display = createDisplay(owner, displayType); - } - - Container displayWindow = display.getWindow(); - checkBounds(displayWindow, x, y, width, height); - - display.show(x, y); - - setComponentLocation(displayWindow.getLocation()); - setComponentSize(displayWindow.getSize()); - } - - /** - * Checks the component's dimensions against the requested values and - * against any maximum limits that may have been set in the WindowSupport. - * Calls setBounds() on the Component. - */ - protected void checkBounds(Component comp, int x, int y, int width, int height) { - if (comp != null) { - - if (width <= 0) { - width = comp.getWidth(); - } - - if (maxWidth > 0 && width > maxWidth) { - width = maxWidth; - } - - if (height <= 0) { - height = comp.getHeight(); - } - - if (maxHeight > 0 && height > maxHeight) { - height = maxHeight; - } - - comp.setBounds(x, y, width, height); - } - } - - /** - * For applications, checks where the Environment says the window should be - * placed, and then uses the packed height and width to make adjustments. - */ - protected static void setDefaultPosition(Component comp) { - // get starting width and height - int w = comp.getWidth(); - int h = comp.getHeight(); - - // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5100801 - GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); - int width = gd.getDisplayMode().getWidth(); - int height = gd.getDisplayMode().getHeight(); - - int x = width / 2 - w / 2; - int y = height / 2 - h / 2; - Debug.message("basic", "Screen dimensions are " + gd.getDisplayMode()); - // Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); - // Debug.message("basic", "Screen dimensions are " + d); - // int x = d.width / 2 - w / 2; - // int y = d.height / 2 - h / 2; - - if (Debug.debugging("basic")) { - Debug.output("Setting PLG frame X and Y from properties to " + x + " " + y); - } - - // compose the frame, but don't show it here - comp.setBounds(x, y, w, h); - } - - /** - * Set the window to be hidden and fire a ComponentEvent for - * COMPONENT_HIDDEN. Normally, just setting the visibility of the window - * would be enough, but we're running into that problem we had with the - * layers not firing ComponentEvents when hidden. This method calls - * componentHidden, which in turn calls cleanUp. - */ - public void killWindow() { - - ComponentEvent ce = null; - if (display != null) { - ce = display.kill(); - } - - if (ce != null) { - componentHidden(ce); - } - } - - protected Class persistentDisplayType; - - /** - * Get rid of the window used to display the content. - */ - protected void cleanUp() { - if (display != null) { - persistentDisplayType = display.getClass(); - WSDisplay wsd = display; - setDisplay(null); - wsd.dispose(); - } - - // This seems to half-disconnect the window support from the content, - // and I am not sure it's necessary to remove the listeners. This was - // originally done to make it easier to release memory, but having the - // WindowSupport hold on to listeners won't prevent that from happening. - - // if (content instanceof ComponentListener) { - // removeComponentListener((ComponentListener) content); - // } - } - - /** - * Add a component listener that is interested in hearing about what happens - * to the window. - */ - public void addComponentListener(ComponentListener l) { - add(l); - } - - /** - * Remove a component listener that was interested in hearing about what - * happens to the window. - */ - public void removeComponentListener(ComponentListener l) { - remove(l); - } - - /** - * Return the window displaying the content. May be null. - */ - public Container getWindow() { - if (display != null) { - return display.getWindow(); - } else { - return null; - } - } - - /** - * Resize based on content changes. - */ - public void repack() { - if (display != null) { - display.repack(); - } - } - - public static interface WSDisplay { - - public void setTitle(String title); - - public String getTitle(); - - public Container getWindow(); - - public void setContent(Component content); - - public void show(int x, int y); - - public ComponentEvent kill(); - - public void dispose(); - - public Dimension getContentSize(); - - public void addComponentListener(ComponentListener cl); - - public void removeComponentListener(ComponentListener cl); - - public void repack(); - - } - - public static class IntrnlFrm extends JInternalFrame implements WSDisplay { - - public IntrnlFrm(String title) { - super(title, - /* resizable */true, - /* closable */true, - /* maximizable */true, - /* iconifiable */true); - setOpaque(true); - - JLayeredPane desktop = Environment.getInternalFrameDesktop(); - - Debug.message("windows", "WindowSupport creating internal frame"); - - if (desktop != null) { - desktop.remove(this); - desktop.add(this, JLayeredPane.PALETTE_LAYER); - } else { - Debug.output("WindowSupport: No desktop set for internal frame"); - } - } - - public Container getWindow() { - return this; - } - - public ComponentEvent kill() { - setVisible(false); - return new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); - } - - public void setContent(Component content) { - Container cp = getContentPane(); - // cp.removeAll(); - cp.add(content); - pack(); - } - - public Dimension getContentSize() { - return getContentPane().getSize(); - } - - public void show(int x, int y) { - if (!isVisible()) { - super.show(); - } - toFront(); - } - - public void repack() { - revalidate(); - pack(); - repaint(); - } - - } - - public static class Dlg extends JDialog implements WSDisplay { - - public Dlg(Frame owner, String title) { - super(owner, title); - Debug.message("windows", "WindowSupport creating frame"); - } - - public Container getWindow() { - return this; - } - - public ComponentEvent kill() { - setVisible(false); - return new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); - } - - public void setContent(Component content) { - Container cp = getContentPane(); - cp.removeAll(); - cp.add(content); - pack(); - } - - public Dimension getContentSize() { - return getContentPane().getSize(); - } - - public void show(int x, int y) { - if (!isVisible()) { - Window owner = getOwner(); - if (x <= 0 && y <= 0) { - if (owner != null) { - setLocationRelativeTo(owner); - } else if (owner == null) { - setDefaultPosition(this); - } - } - } - super.setVisible(true); - } - - public void repack() { - revalidate(); - pack(); - repaint(); - } - } - - public static class Frm extends JFrame implements WSDisplay { - - public Frm(String title) { - super(title); - // Need to call this to get the frame to pay attention to requests - // on where to locate it if it should be centered on the screen. - setLocation(-1, -1); - } - - public Frm(String title, boolean undecorated) { - super(title); - setUndecorated(undecorated); - // Need to call this to get the frame to pay attention to requests - // on where to locate it if it should be centered on the screen. - setLocation(-1, -1); - } - - public Container getWindow() { - return this; - } - - public ComponentEvent kill() { - setVisible(false); - return new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); - } - - public void setContent(Component content) { - Container cp = getContentPane(); - cp.removeAll(); - cp.add(content); - pack(); - } - - public Dimension getContentSize() { - return getContentPane().getSize(); - } - - public void show(int x, int y) { - if (!isVisible()) { - Window owner = getOwner(); - if (x <= 0 && y <= 0) { - if (owner != null) { - setLocationRelativeTo(owner); - } else if (owner == null) { - setDefaultPosition(this); - } - } - super.setVisible(true); - } - toFront(); - } - - public void repack() { - revalidate(); - pack(); - repaint(); - } - } - - /** - * Set the FavIcon for the WSDisplay. - * - * @param wsd - */ - protected void setFavIcon(WSDisplay wsd) { - String iconPath = Environment.get("openmap.favicon"); - if (iconPath != null && wsd instanceof Window) { - try { - BufferedImage favIcon = ImageIO.read(WindowSupport.class.getResourceAsStream(iconPath)); - - // Java 5 incompatible - // ((Window) wsd).setIconImage(favIcon); - - // Use reflection that'll work if using java 6 and higher. We - // can remove all this when OM makes the jump to java 6 or - // higher. - try { - Method siiMethod = wsd.getClass().getMethod("setIconImage", BufferedImage.class); - siiMethod.invoke((Window) wsd, favIcon); - } catch (NoSuchMethodException e) { - Debug.message("windows", e.getMessage()); - } catch (SecurityException e) { - Debug.message("windows", e.getMessage()); - } catch (IllegalAccessException e) { - Debug.message("windows", e.getMessage()); - } catch (IllegalArgumentException e) { - Debug.message("windows", e.getMessage()); - } catch (InvocationTargetException e) { - Debug.message("windows", e.getMessage()); - } - - } catch (IOException e) { - Debug.message("windows", e.getMessage()); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/ZoomPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/ZoomPanel.java deleted file mode 100644 index 93dc1aff7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/ZoomPanel.java +++ /dev/null @@ -1,248 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/ZoomPanel.java,v $ -// $RCSfile: ZoomPanel.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/02/02 13:14:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.net.URL; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.event.ZoomSupport; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * Bean to zoom the Map. - *

- * This bean is a source for ZoomEvents. It is a simple widget with a - * ZoomIn button and a ZoomOut button. When a button is pressed, the - * appropriate zoom event is fired to all registered listeners. - * - * @see #addZoomListener - */ -public class ZoomPanel extends OMToolComponent implements ActionListener, - Serializable { - - public final static transient String zoomInCmd = "zoomin"; - public final static transient String zoomOutCmd = "zoomout"; - - protected transient JButton zoomInButton, zoomOutButton; - protected transient ZoomSupport zoomDelegate; - - public final static String defaultKey = "zoompanel"; - - /** - * Default Zoom In Factor is 0.5. - */ - protected transient float zoomInFactor = 0.5f; - - /** - * Default Zoom Out Factor is 2.0. - */ - protected transient float zoomOutFactor = 2.0f; - - /** - * Construct the ZoomPanel. - */ - public ZoomPanel() { - super(); - setKey(defaultKey); - // setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - this.setOpaque(false); - - JPanel panel = new JPanel(); - GridBagLayout internalGridbag = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - panel.setLayout(internalGridbag); - - zoomDelegate = new ZoomSupport(this); - zoomInButton = getButton("zoomIn", "Zoom In", zoomInCmd); - c2.gridx = 0; - c2.gridy = 0; - internalGridbag.setConstraints(zoomInButton, c2); - panel.add(zoomInButton); - - zoomOutButton = getButton("zoomOut", "Zoom Out", zoomOutCmd); - c2.gridy = 1; - internalGridbag.setConstraints(zoomOutButton, c2); - panel.add(zoomOutButton); - - add(panel); - } - - /** - * Get the Zoom In Factor. - * - * @return float the degree by which map scale will be multiplied - * when zoom in button is pressed - */ - public float getZoomInFactor() { - return zoomInFactor; - } - - /** - * Sets the Zoom In factor. The factor must be < 1.0. - * (otherwise it would make ZoomIn into a ZoomOut). - * - * @param factor the degree by which map scale should be - * multiplied - */ - public void setZoomInFactor(float factor) { - if (factor < 1.0f) { - zoomInFactor = factor; - zoomInButton.setToolTipText(i18n.get(ZoomPanel.class, - zoomInCmd + "factor", - I18n.TOOLTIP, - "zoom in X" + zoomInFactor, - new Float(zoomInFactor))); - } else { - throw new IllegalArgumentException("Zoom In factor too large (must be < 1.0)"); - } - } - - /** - * Get the Zoom Out Factor. - * - * @return float the degree by which map scale will be multiplied - * when zoom out button is pressed - */ - public float getZoomOutFactor() { - return zoomOutFactor; - } - - /** - * Sets the Zoom Out Factor. The factor must be > 1.0 - * (otherwise it would turn ZoomOut into ZoomIn). - * - * @param factor the degree by which map scale should be - * multiplied. - */ - public void setZoomOutFactor(float factor) { - if (factor > 1.0f) { - zoomOutFactor = factor; - // zoomOutButton.setToolTipText("zoom out X" + - // zoomOutFactor); - zoomOutButton.setToolTipText(i18n.get(ZoomPanel.class, - zoomOutCmd + "factor", - I18n.TOOLTIP, - "zoom out X" + zoomOutFactor, - new Float(zoomOutFactor))); - - } else { - throw new IllegalArgumentException("Zoom In factor too small (must be > 1.0)"); - } - } - - /** - * Add the named button to the panel. - * - * @param name GIF image name - * @param info ToolTip text - * @param command String command name - * - */ - protected JButton getButton(String name, String info, String command) { - URL url = ZoomPanel.class.getResource(name + ".gif"); - ImageIcon icon = new ImageIcon(url, info); - JButton b = new JButton(icon); - b.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight())); - //b.setToolTipText(info); - b.setToolTipText(i18n.get(ZoomPanel.class, command, I18n.TOOLTIP, info)); - b.setMargin(new Insets(0, 0, 0, 0)); - b.setActionCommand(command); - b.addActionListener(this); - b.setBorderPainted(Debug.debugging("layout")); - b.setOpaque(false); - return b; - } - - /** - * Add a ZoomListener from the listener list. - * - * @param listener The ZoomListener to be added - */ - public synchronized void addZoomListener(ZoomListener listener) { - zoomDelegate.add(listener); - } - - /** - * Remove a ZoomListener from the listener list. - * - * @param listener The ZoomListener to be removed - */ - public synchronized void removeZoomListener(ZoomListener listener) { - zoomDelegate.remove(listener); - } - - /** - * ActionListener interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - - if (command.equals(zoomInCmd)) { - zoomDelegate.fireZoom(ZoomEvent.RELATIVE, zoomInFactor); - } else if (command.equals(zoomOutCmd)) { - zoomDelegate.fireZoom(ZoomEvent.RELATIVE, zoomOutFactor); - } - } - - public void setOpaque(boolean set) { - super.setOpaque(set); - if (zoomInButton != null) { - zoomInButton.setOpaque(set); - } - if (zoomOutButton != null) { - zoomOutButton.setOpaque(set); - } - } - - /////////////////////////////////////////////////////////////////////////// - //// OMComponentPanel methods to make the tool work with - //// the MapHandler to find objects it needs. - /////////////////////////////////////////////////////////////////////////// - - public void findAndInit(Object obj) { - if (obj instanceof ZoomListener) { - addZoomListener((ZoomListener) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof ZoomListener) { - removeZoomListener((ZoomListener) obj); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/BasicDockPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/BasicDockPanel.java deleted file mode 100644 index 8d941cfa6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/BasicDockPanel.java +++ /dev/null @@ -1,591 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/BasicDockPanel.java,v $ -// $RCSfile: BasicDockPanel.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 17:50:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.awt.Component; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import javax.swing.JComponent; -import javax.swing.JLayeredPane; -import javax.swing.JToolBar; -import javax.swing.UIManager; - -import com.bbn.openmap.util.Debug; - -/** - * A component that has a background component and docking children. - * - * @author Ben Lubin - * @version $Revision: 1.4 $ on $Date: 2005/08/09 17:50:51 $ - * @since 12/5/02 - */ -public class BasicDockPanel extends JLayeredPane implements DockPanel { - - /** Layer where we add the background component */ - private static final Integer BACKGROUND_LAYER = new Integer(-100); - - /** The one and only background component */ - private JComponent background; - - /** Maps children to their constraint objects */ - private HashMap childToConstraint = new HashMap(11); - - /** - * Maps children to their wrappers (not 1-to-1 when tabbing - * involved) - */ - private HashMap childToWrapper = new HashMap(11); - - /** A list of wrappers that are currently wrapped in JFrames */ - private List externalFrameWrappers = new ArrayList(0); - - /** A list of wrappers that are currently loose InternalFrames */ - private List internalFrameWrappers = new ArrayList(0); - - /** - * Invisible root dock wrapper, that will be pegged to the edge of - * the panel. - */ - private DockWrapper north = new DockWrapper(this, DockWrapper.DOCK_NORTH); - /** - * Invisible root dock wrapper, that will be pegged to the edge of - * the panel. - */ - private DockWrapper south = new DockWrapper(this, DockWrapper.DOCK_SOUTH); - /** - * Invisible root dock wrapper, that will be pegged to the edge of - * the panel. - */ - private DockWrapper east = new DockWrapper(this, DockWrapper.DOCK_EAST); - /** - * Invisible root dock wrapper, that will be pegged to the edge of - * the panel. - */ - private DockWrapper west = new DockWrapper(this, DockWrapper.DOCK_WEST); - - public BasicDockPanel() { - super(); - setLayout(new DockLayout(this)); - setBackground(UIManager.getColor("control")); - } - - //Background Methods: - ///////////////////// - - public JComponent getBackgroundComponent() { - return background; - } - - public void setBackgroundComponent(JComponent back) { - if (getBackgroundComponent() != null) { - remove(getBackgroundComponent()); - } - add(back, BACKGROUND); - } - - //Constraint Methods: - ///////////////////// - - public void setConstraint(JComponent child, DockConstraint c) { - childToConstraint.put(child, c); - } - - public DockConstraint getConstraint(JComponent child) { - return (DockConstraint) childToConstraint.get(child); - } - - public void removeConstraint(JComponent child) { - childToConstraint.remove(child); - } - - //Constraint Setup Functions: - ///////////////////////////// - - public void setPreferredHeight(JComponent child, int i) { - DockWrapper dw = getWrapper(child); - if (dw != null) { - dw.setPreferredHeight(i); - } - } - - public void setPreferredWidth(JComponent child, int i) { - DockWrapper dw = getWrapper(child); - if (dw != null) { - dw.setPreferredWidth(i); - } - } - - public void setCanOcclude(JComponent child, boolean b) { - getConstraint(child).setCanOcclude(b); - } - - public void setCanTransparent(JComponent child, boolean b) { - getConstraint(child).setCanTransparent(b); - DockWrapper dw = getWrapper(child); - if (dw != null) { - dw.updateTransparency(); - } - } - - public void setCanResize(JComponent child, boolean b) { - getConstraint(child).setCanResize(b); - DockWrapper dw = getWrapper(child); - if (dw != null) { - dw.updateResizable(); - } - } - - public void setCanTab(JComponent child, boolean b) { - getConstraint(child).setCanTab(b); - dockSomewhere(child); - } - - /** - * Set the name of the tab to use when the component is tabbed (if - * it can tab). If unspecified, defaults to Component.getName() - */ - public void setTabName(JComponent child, String tabName) { - getConstraint(child).setTabName(tabName); - getWrapper(child).setTabName(child, tabName); - } - - public void setCanExternalFrame(JComponent child, boolean b) { - getConstraint(child).setCanExternalFrame(b); - dockSomewhere(child); - } - - public void setCanInternalFrame(JComponent child, boolean b) { - getConstraint(child).setCanInternalFrame(b); - dockSomewhere(child); - } - - public void setCanClose(JComponent child, boolean b) { - getConstraint(child).setCanClose(b); - } - - public void setCanDockNorth(JComponent child, boolean b) { - getConstraint(child).setCanDockNorth(b); - dockSomewhere(child); - } - - public void setCanDockSouth(JComponent child, boolean b) { - getConstraint(child).setCanDockSouth(b); - dockSomewhere(child); - } - - public void setCanDockEast(JComponent child, boolean b) { - getConstraint(child).setCanDockEast(b); - dockSomewhere(child); - } - - public void setCanDockWest(JComponent child, boolean b) { - getConstraint(child).setCanDockWest(b); - dockSomewhere(child); - } - - //Docking Functions: - //////////////////// - - public void dockNorth(JComponent child) { - dockNorth(child, -1); - } - - public void dockNorth(JComponent child, int idx) { - dockNorth(getWrapper(child), idx); - } - - protected void dockNorth(DockWrapper wrapper) { - dockNorth(wrapper, -1); - } - - /** - * Dock the given child into the given position on the MapPanel - */ - protected void dockNorth(DockWrapper wrapper, int idx) { - dock(north, wrapper, idx); - } - - public void dockSouth(JComponent child) { - dockSouth(child, -1); - } - - public void dockSouth(JComponent child, int idx) { - dockSouth(getWrapper(child), idx); - } - - protected void dockSouth(DockWrapper wrapper) { - dockSouth(wrapper, -1); - } - - /** - * Dock the given child into the given position on the MapPanel - */ - protected void dockSouth(DockWrapper wrapper, int idx) { - dock(south, wrapper, idx); - } - - public void dockEast(JComponent child) { - dockEast(child, -1); - } - - public void dockEast(JComponent child, int idx) { - dockEast(getWrapper(child), idx); - } - - protected void dockEast(DockWrapper wrapper) { - dockEast(wrapper, -1); - } - - /** - * Dock the given child into the given position on the MapPanel - */ - protected void dockEast(DockWrapper wrapper, int idx) { - dock(east, wrapper, idx); - } - - public void dockWest(JComponent child) { - dockWest(child, -1); - } - - public void dockWest(JComponent child, int idx) { - dockWest(getWrapper(child), idx); - } - - protected void dockWest(DockWrapper wrapper) { - dockWest(wrapper, -1); - } - - /** - * Dock the given child into the given position on the MapPanel - */ - protected void dockWest(DockWrapper wrapper, int idx) { - dock(west, wrapper, idx); - } - - /** - * Dock the given child onto the given parent, which is itself a - * child of this class. - */ - public void dock(JComponent outter, JComponent inner) { - dock(outter, inner, -1); - } - - /** - * Dock the given child onto the given parent, which is itself a - * child of this class. - */ - public void dock(JComponent outter, JComponent inner, int idx) { - dock(getWrapper(outter), getWrapper(inner), idx); - } - - /** - * Dock the given child onto the given parent, which is itself a - * child of this class. - */ - protected void dock(DockWrapper outter, DockWrapper inner) { - dock(outter, inner, -1); - } - - /** - * Dock the given child onto the given parent, which is itself a - * child of this class. - */ - protected void dock(DockWrapper outter, DockWrapper inner, int idx) { - freeWrapper(inner); - outter.dock(inner, idx); - } - - /** - * Set the component to an internal frame - */ - public void internalFrame(JComponent child) { - internalFrame(getWrapper(child)); - } - - /** - * Set the component to an internal frame - */ - protected void internalFrame(DockWrapper wrapper) { - freeWrapper(wrapper); - internalFrameWrappers.add(wrapper); - wrapper.makeInternalFrame(); - } - - /** - * Set the component to an external frame - */ - public void externalFrame(JComponent child) { - externalFrame(getWrapper(child)); - } - - /** - * Set the component to an internal frame - */ - protected void externalFrame(DockWrapper wrapper) { - freeWrapper(wrapper); - externalFrameWrappers.add(wrapper); - wrapper.makeExternalFrame(); - } - - /** - * Dock the given child somewhere... - */ - public void dockSomewhere(JComponent child) { - dockSomewhere(getWrapper(child)); - } - - /** - * Dock the given child somewhere... - */ - protected void dockSomewhere(DockWrapper wrapper) { - if (wrapper == null) { - throw new RuntimeException("Can't dock null!"); - } - if (wrapper.canDockNorth()) { - dockNorth(wrapper); - return; - } - if (wrapper.canDockWest()) { - dockWest(wrapper); - return; - } - if (wrapper.canDockSouth()) { - dockSouth(wrapper); - return; - } - if (wrapper.canDockEast()) { - dockEast(wrapper); - return; - } - - if (wrapper.canInternalFrame()) { - internalFrame(wrapper); - return; - } - if (wrapper.canExternalFrame()) { - externalFrame(wrapper); - return; - } - - Debug.error("DockPanel: Can't dock anywhere..."); - externalFrame(wrapper); - } - - //Overwrite from Component: - /////////////////////////// - - /** - * We need to handle adding the component specially. If it is the - * background, do one thing. Otherwise wrap it up... - */ - public Component add(Component comp) { - add(comp, new DockConstraint()); - return comp; - } - - /** - * We need to handle adding the component specially. If it is the - * background, do one thing. Otherwise wrap it up... - */ - public void add(Component comp, Object constraints) { - if (comp == null) { - throw new RuntimeException("Can't add null component to DockPanel"); - } - if (comp instanceof DockWrapper) { - Debug.error("DockPanel: Unexpected call to add with a DockWrapper"); - super.add(comp, constraints); - } else { - if (constraints.equals(BACKGROUND)) { - background = (JComponent) comp; - super.add(comp, constraints); - setLayer(comp, BACKGROUND_LAYER.intValue()); - } else if (constraints instanceof DockConstraint) { - if (comp instanceof JToolBar) { - JToolBar t = (JToolBar) comp; - t.setFloatable(false); - } - setConstraint((JComponent) comp, (DockConstraint) constraints); - if (!alreadyAdded(comp)) { - createDockWrapper((JComponent) comp); - } - } else { - Debug.error("DockPanel: Unexpected constraint: " + constraints); - } - } - } - - public void remove(Component comp) { - if (comp == null) { - Debug.error("Trying to remove null component"); - } - if (comp instanceof DockWrapper) { - freeWrapper((DockWrapper) comp); - removeWrapper((DockWrapper) comp); - } else { - DockWrapper w = getWrapper((JComponent) comp); - if (w != null) { - super.remove(w); - } - super.remove(comp); - } - } - - public void removeAll() { - for (int i = 0; i < getComponentCount(); i++) { - JComponent comp = (JComponent) getComponent(i); - if (comp instanceof DockWrapper) { - freeWrapper((DockWrapper) comp); - removeWrapper((DockWrapper) comp); - } - } - super.removeAll(); - } - - //// - ////Package/Protected/Private Implementation Functions: - /////////////////////////////////////////////////////// - /////////////////////////////////////////////////////// - - protected DockWrapper getNorth() { - return north; - } - - protected DockWrapper getSouth() { - return south; - } - - protected DockWrapper getEast() { - return east; - } - - protected DockWrapper getWest() { - return west; - } - - protected int getOverlapTolerance() { - return 5; - } - - //Wrapper Functions: - ///////////////////// - - protected void setWrapper(JComponent child, DockWrapper w) { - childToWrapper.put(child, w); - } - - protected DockWrapper getWrapper(JComponent child) { - return (DockWrapper) childToWrapper.get(child); - } - - protected void removeWrapper(DockWrapper wrapper) { - for (Iterator iter = wrapper.getChildren().iterator(); iter.hasNext();) { - JComponent j = (JComponent) iter.next(); - childToWrapper.remove(j); - } - } - - /** - * Remove the wrapper from wherever it is currently - */ - protected void freeWrapper(DockWrapper w) { - if (externalFrameWrappers.remove(w)) { - w.freeWrapper(); - return; - } - if (internalFrameWrappers.remove(w)) { - w.freeWrapper(); - return; - } - if (north.freeWrapper(w)) { - return; - } - if (south.freeWrapper(w)) { - return; - } - if (east.freeWrapper(w)) { - return; - } - if (west.freeWrapper(w)) { - return; - } - } - - //Package Accessors for access from DockWrapper: - //////////////////////////////////////////////// - - /** - * Get a list of DockConstraint objects for a list of children. - * - * @param children a List of JComponent children - * @return a List of DockConstraints - */ - List getConstraints(List children) { - List ret = new ArrayList(children.size()); - for (Iterator iter = children.iterator(); iter.hasNext();) { - JComponent child = (JComponent) iter.next(); - ret.add(getConstraint(child)); - } - return ret; - } - - /** Create a DockWrapper for the given JComponent. */ - DockWrapper createDockWrapper(JComponent comp) { - DockWrapper dw = new DockWrapper(this); - setWrapper(comp, dw); - dw.addChild(comp); - dockSomewhere(comp); - return dw; - } - - /** Pass back to add the dockwrapper to the layer. */ - void addDockWrapper(DockWrapper dw) { - super.add(dw, null); - } - - /** Pass back to remove the dockwrapper from the layer. */ - void removeDockWrapper(DockWrapper dw) { - super.remove(dw); - } - - /** - * Returns true if the component has already been added to a - * DockWrapper that has been added to the DockPanel. - */ - boolean alreadyAdded(Component comp) { - Component components[] = getComponents(); - for (int i = 0; i < components.length; i++) { - Component c = components[i]; - if (c instanceof DockWrapper) { - DockWrapper dw = (DockWrapper) c; - if (dw.getChildren().contains(comp)) { - return true; - } - } - } - return false; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockConstraint.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/DockConstraint.java deleted file mode 100644 index 943218830..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockConstraint.java +++ /dev/null @@ -1,342 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/DockConstraint.java,v $ -// $RCSfile: DockConstraint.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.util.Iterator; -import java.util.List; - -/** - * Constraints used for DockPanel behavior. - * - * @author Ben Lubin - * @version $Revision: 1.3 $ on $Date: 2004/10/14 18:05:49 $ - * @since 12/5/02 - */ -public class DockConstraint { - - public DockConstraint() {} - - //Constraints used for layout: - ////////////////////////////// - - private String tabName = null; - - private boolean canTransparent = false; - private boolean canResize = false; - private boolean canOcclude = false; - private boolean canTab = false; - private boolean canClose = false; - private boolean canExternalFrame = true; - private boolean canInternalFrame = true; - private boolean canDockNorth = true; - private boolean canDockSouth = true; - private boolean canDockEast = true; - private boolean canDockWest = true; - - public String getTabName() { - return tabName; - } - - /** - * Set the name of the tab to use when the component is tabbed (if - * it can tab). If unspecified, defaults to Component.getName() - */ - public void setTabName(String name) { - tabName = name; - } - - /** - * True iff this class can be transparent - */ - public boolean canTransparent() { - return canTransparent; - } - - public void setCanTransparent(boolean b) { - canTransparent = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canTransparent(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canTransparent()) - return false; - } - return true; - } - - /** - * True iff this class can be resize - */ - public boolean canResize() { - return canResize; - } - - public void setCanResize(boolean b) { - canResize = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canResize(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canResize()) - return false; - } - return true; - } - - /** - * True iff this class can overlap the background - */ - public boolean canOcclude() { - return canOcclude; - } - - public void setCanOcclude(boolean b) { - canOcclude = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canOcclude(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canOcclude()) - return false; - } - return true; - } - - /** - * True iff this class can be tabbed together. - */ - public boolean canTab() { - return canTab; - } - - public void setCanTab(boolean b) { - canTab = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canTab(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canTab()) - return false; - } - return true; - } - - /** - * True iff this class can be closed - */ - public boolean canClose() { - return canClose; - } - - public void setCanClose(boolean b) { - canClose = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canClose(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canClose()) - return false; - } - return true; - } - - /** - * True iff this class can be changed to frame - */ - public boolean canExternalFrame() { - return canExternalFrame; - } - - public void setCanExternalFrame(boolean b) { - canExternalFrame = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canExternalFrame(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canExternalFrame()) - return false; - } - return true; - } - - /** - * True iff this class can be changed to frame - */ - public boolean canInternalFrame() { - return canInternalFrame; - } - - public void setCanInternalFrame(boolean b) { - canInternalFrame = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canInternalFrame(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canInternalFrame()) - return false; - } - return true; - } - - /** - * True iff this class can be docked in the given direction - */ - public boolean canDockNorth() { - return canDockNorth; - } - - public void setCanDockNorth(boolean b) { - canDockNorth = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canDockNorth(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canDockNorth()) - return false; - } - return true; - } - - /** - * True iff this class can be docked in the given direction - */ - public boolean canDockSouth() { - return canDockSouth; - } - - public void setCanDockSouth(boolean b) { - canDockSouth = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canDockSouth(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canDockSouth()) - return false; - } - return true; - } - - /** - * True iff this class can be docked in the given direction - */ - public boolean canDockEast() { - return canDockEast; - } - - public void setCanDockEast(boolean b) { - canDockEast = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canDockEast(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canDockEast()) - return false; - } - return true; - } - - /** - * True iff this class can be docked in the given direction - */ - public boolean canDockWest() { - return canDockWest; - } - - public void setCanDockWest(boolean b) { - canDockWest = b; - } - - /** - * Determine property over a list of DockConstraint objects - * - * @param constraints a List of DockConstraints - */ - public static boolean canDockWest(List constraints) { - for (Iterator iter = constraints.iterator(); iter.hasNext();) { - DockConstraint dc = (DockConstraint) iter.next(); - if (!dc.canDockWest()) - return false; - } - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockLayout.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/DockLayout.java deleted file mode 100644 index 385b68ece..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockLayout.java +++ /dev/null @@ -1,385 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/DockLayout.java,v $ -// $RCSfile: DockLayout.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:50:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.LayoutManager2; -import java.awt.Rectangle; -import java.util.Iterator; - -import javax.swing.JComponent; - -import com.bbn.openmap.util.Debug; - -/** - * A Layout manager used for the docking component... - * - * @author Ben Lubin - * @version $Revision: 1.5 $ on $Date: 2005/08/09 17:50:51 $ - * @since 12/5/02 - */ -public class DockLayout implements LayoutManager2 { - - private BasicDockPanel p; - - /** Size of the background control */ - protected Rectangle occludingBounds; - - /** Size of the background control */ - protected Rectangle backgroundBounds; - - public DockLayout(BasicDockPanel p) { - this.p = p; - } - - //Layout Query Functions: - ///////////////////////// - - /** Account for the extra size of the cardinal DockWrapper. */ - protected int getHeightAtLeftCardinal(DockWrapper dw) { - return getHeightAtLeft(dw) - p.getOverlapTolerance(); - } - - /** Account for the extra size of the cardinal DockWrapper. */ - protected int getHeightAtRightCardinal(DockWrapper dw) { - return getHeightAtRight(dw) - p.getOverlapTolerance(); - } - - /** Account for the extra size of the cardinal DockWrapper. */ - protected int getWidthAtYCardinal(DockWrapper dw, int y) { - return getWidthAtY(dw, y) - p.getOverlapTolerance(); - } - - /** - * Get the height at the left point for a north or south - * DockWrapper. - */ - protected int getHeightAtLeft(DockWrapper dw) { - int ret = dw.getPreferredSize().height; - java.util.List l = dw.getDockedWrappers(); - if (!l.isEmpty()) { - ret += getHeightAtLeft((DockWrapper) l.get(0)); - } - return ret; - } - - /** - * Get the height at the right point for a north or south - * DockWrapper. - */ - protected int getHeightAtRight(DockWrapper dw) { - int ret = dw.getPreferredSize().height; - java.util.List l = dw.getDockedWrappers(); - if (!l.isEmpty()) { - ret += getHeightAtRight((DockWrapper) l.get(l.size() - 1)); - } - return ret; - } - - /** - * Get the width at the given point for a east or west - * DockWrapper. - */ - protected int getWidthAtY(DockWrapper dw, int y) { - Rectangle bounds = dw.getBounds(); - int ret = 0; - if ((bounds.y <= y) && (bounds.y + bounds.height >= y)) { - ret = bounds.width; - } - for (Iterator iter = dw.getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper c = (DockWrapper) iter.next(); - ret += getWidthAtY(c, y); - } - return ret; - } - - //Layout Functions: - /////////////////// - - /** - * Layout the entire container. - */ - protected void layoutContainer() { - Rectangle inBounds = p.getBounds(); - Insets insets = p.getInsets(); - inBounds.x += insets.left; - inBounds.width -= insets.left; - inBounds.width -= insets.right; - inBounds.y += insets.top; - inBounds.height -= insets.top; - inBounds.height -= insets.bottom; - - backgroundBounds = (Rectangle) inBounds.clone(); - occludingBounds = (Rectangle) inBounds.clone(); - - layoutCardinals(); - layoutEast(p.getEast(), - occludingBounds.x + occludingBounds.width, - occludingBounds.y, - occludingBounds.width, - occludingBounds.height); - - layoutWest(p.getWest(), - occludingBounds.x, - occludingBounds.y, - occludingBounds.width, - occludingBounds.height); - - int southLeft = inBounds.x - + getWidthAtYCardinal(p.getWest(), inBounds.y + inBounds.height - - getHeightAtLeftCardinal(p.getSouth())); - int southRight = inBounds.x - + inBounds.width - - getWidthAtYCardinal(p.getEast(), inBounds.y + inBounds.height - - getHeightAtRightCardinal(p.getSouth())); - layoutSouth(p.getSouth(), - southLeft, - occludingBounds.y + occludingBounds.height, - southRight - southLeft, - occludingBounds.height); - - int northLeft = inBounds.x - + getWidthAtYCardinal(p.getWest(), inBounds.y - + getHeightAtLeftCardinal(p.getNorth())); - int northRight = inBounds.x - + inBounds.width - - getWidthAtYCardinal(p.getEast(), inBounds.y - + getHeightAtRightCardinal(p.getNorth())); - layoutNorth(p.getNorth(), northLeft, occludingBounds.y, northRight - - northLeft, occludingBounds.height); - - layoutBackground(); - } - - protected void layoutCardinals() { - p.getNorth().setBounds(0, 0, p.getWidth(), p.getOverlapTolerance()); - p.getSouth().setBounds(0, - p.getHeight() - p.getOverlapTolerance(), - p.getWidth(), - p.getOverlapTolerance()); - p.getEast().setBounds(p.getWidth() - p.getOverlapTolerance(), - 0, - p.getOverlapTolerance(), - p.getWidth()); - p.getWest().setBounds(0, 0, p.getOverlapTolerance(), p.getWidth()); - } - - /** - * Layout west side. - * - * @param x right most edge. - * @param y top most edge. - */ - protected void layoutEast(DockWrapper base, int x, int y, int maxwidth, - int maxheight) { - for (Iterator iter = base.getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - Dimension d = dw.getPreferredSize(); - int w = min(d.width, maxwidth); - int h = min(d.height, maxheight); - dw.setBounds(x - w, y, w, h); - if (!dw.canOcclude()) { - updateRight(backgroundBounds, x - w); - } - updateRight(occludingBounds, x - w); - layoutEast(dw, x - w, y, maxwidth - w, maxheight); - y += h; - maxheight -= h; - } - } - - /** - * Layout west side. - * - * @param x left most edge. - * @param y top most edge. - */ - protected void layoutWest(DockWrapper base, int x, int y, int maxwidth, - int maxheight) { - for (Iterator iter = base.getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - Dimension d = dw.getPreferredSize(); - int w = min(d.width, maxwidth); - int h = min(d.height, maxheight); - dw.setBounds(x, y, w, h); - if (!dw.canOcclude()) { - updateLeft(backgroundBounds, x + w); - } - updateLeft(occludingBounds, x + w); - layoutWest(dw, x + w, y, maxwidth - w, maxheight); - y += h; - maxheight -= h; - } - } - - /** - * Layout north side. - * - * @param x left most edge. - * @param y top most edge. - */ - protected void layoutNorth(DockWrapper base, int x, int y, int maxwidth, - int maxheight) { - for (Iterator iter = base.getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - Dimension d = dw.getPreferredSize(); - int w = min(d.width, maxwidth); - int h = min(d.height, maxheight); - dw.setBounds(x, y, w, h); - if (!dw.canOcclude()) { - updateTop(backgroundBounds, y + h); - } - updateTop(occludingBounds, y + h); - layoutNorth(dw, x, y + h, maxwidth, maxheight - h); - x += w; - maxwidth -= w; - } - } - - /** - * Layout north side. - * - * @param x left most edge. - * @param y bottom most edge. - */ - protected void layoutSouth(DockWrapper base, int x, int y, int maxwidth, - int maxheight) { - for (Iterator iter = base.getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - Dimension d = dw.getPreferredSize(); - int w = min(d.width, maxwidth); - int h = min(d.height, maxheight); - dw.setBounds(x, y - h, w, h); - // System.out.println("RES: "+ dw.getBounds()); - if (!dw.canOcclude()) { - updateBottom(backgroundBounds, y - h); - } - updateBottom(occludingBounds, y - h); - layoutSouth(dw, x, y - h, maxwidth, maxheight - h); - x += w; - maxwidth -= w; - } - } - - protected void layoutBackground() { - JComponent background = p.getBackgroundComponent(); - if (background != null) { - /* - * backgroundBounds.x += 10; backgroundBounds.y += 10; - * backgroundBounds.width -= 20; backgroundBounds.height -= - * 20; - */ - background.setBounds(backgroundBounds); - } - } - - // Utilities: - ///////////// - - protected int min(int a, int b) { - return Math.min(a, b); - } - - protected int max(int a, int b) { - return Math.max(a, b); - } - - protected void updateLeft(Rectangle r, int left) { - int tmp = left - r.x; - if (tmp > 0) { - r.x += tmp; - r.width -= tmp; - } - } - - protected void updateRight(Rectangle r, int right) { - r.width = min(r.x + r.width, right); - } - - protected void updateTop(Rectangle r, int top) { - int tmp = top - r.y; - if (tmp > 0) { - r.y += tmp; - r.height -= tmp; - } - } - - protected void updateBottom(Rectangle r, int bottom) { - r.height = min(r.y + r.height, bottom); - } - - // From LayoutManager2: - /////////////////////// - - public void layoutContainer(Container parent) { - if (parent != p) { - Debug.error("DockLayout: Asked to layout unexpected container"); - return; - } - layoutContainer(); - } - - public void addLayoutComponent(String name, Component comp) {} - - public void addLayoutComponent(Component comp, Object constraints) {} - - public void removeLayoutComponent(Component comp) {} - - public Dimension preferredLayoutSize(Container parent) { - JComponent background = p.getBackgroundComponent(); - if (background != null) { - return background.getPreferredSize(); - } - return new Dimension(0, 0); - } - - public Dimension minimumLayoutSize(Container parent) { - JComponent background = p.getBackgroundComponent(); - if (background != null) { - return background.getMinimumSize(); - } - return new Dimension(0, 0); - } - - public Dimension maximumLayoutSize(Container parent) { - JComponent background = p.getBackgroundComponent(); - if (background != null) { - return background.getMaximumSize(); - } - return new Dimension(0, 0); - } - - public float getLayoutAlignmentX(Container target) { - return .5f; - } - - public float getLayoutAlignmentY(Container target) { - return .5f; - } - - public void invalidateLayout(Container target) {} -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/DockPanel.java deleted file mode 100644 index 188d24106..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockPanel.java +++ /dev/null @@ -1,234 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/DockPanel.java,v $ -// $RCSfile: DockPanel.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.awt.BorderLayout; - -import javax.swing.JComponent; - -/** - * An interface onto a component that has a background component and - * docking children. - * - * @author Ben Lubin - * @version $Revision: 1.5 $ on $Date: 2004/10/14 18:05:49 $ - * @since 12/5/02 - */ -public interface DockPanel { - - /** Constraint for the background component */ - public static final String BACKGROUND = BorderLayout.CENTER; - - //Background Methods: - ///////////////////// - - /** - * Get the background component. - */ - public JComponent getBackgroundComponent(); - - /** - * Set the background component. - */ - public void setBackgroundComponent(JComponent back); - - //Constraint Methods: - ///////////////////// - - /** - * Set the constraint on the given child. - */ - public void setConstraint(JComponent child, DockConstraint c); - - /** - * Get the constraint on the given child. - */ - public DockConstraint getConstraint(JComponent child); - - /** - * Remove a constraint on a child. - */ - public void removeConstraint(JComponent child); - - //Constraint Setup Functions: - ///////////////////////////// - - /** - * Set the childs preferred height. - */ - public void setPreferredHeight(JComponent child, int i); - - /** - * Set the childs preferred width. - */ - public void setPreferredWidth(JComponent child, int i); - - /** - * Set that the given child can sit in front of the background - * component, without forcing the background component to be - * resized to make room. - */ - public void setCanOcclude(JComponent child, boolean b); - - /** - * Set the child component to have a transparent background. - */ - public void setCanTransparent(JComponent child, boolean b); - - /** - * Set that the child component can be user-resized. - */ - public void setCanResize(JComponent child, boolean b); - - /** - * Set that the child component can be tabbed up, if docked in the - * same location as other tab-able components. - */ - public void setCanTab(JComponent child, boolean b); - - /** - * Set the name of the tab to use when the component is tabbed (if - * it can tab). If unspecified, defaults to Component.getName() - */ - public void setTabName(JComponent child, String tabName); - - /** - * Set that the child can be become an external frame. - */ - public void setCanExternalFrame(JComponent child, boolean b); - - /** - * Set that the child can be become an internal frame. - */ - public void setCanInternalFrame(JComponent child, boolean b); - - /** - * Set that the child can be closed. - */ - public void setCanClose(JComponent child, boolean b); - - /** - * Set that the child can dock on the top-level north. - */ - public void setCanDockNorth(JComponent child, boolean b); - - /** - * Set that the child can dock on the top-level south. - */ - public void setCanDockSouth(JComponent child, boolean b); - - /** - * Set that the child can dock on the top-level east. - */ - public void setCanDockEast(JComponent child, boolean b); - - /** - * Set that the child can dock on the top-level west. - */ - public void setCanDockWest(JComponent child, boolean b); - - //Docking Functions: - //////////////////// - - //NORTH: - - /** - * Dock child on the DockPanel. - */ - public void dockNorth(JComponent child); - - /** - * Dock the given child into the given position on the DockPanel - */ - public void dockNorth(JComponent child, int idx); - - //SOUTH: - - /** - * Dock child on the DockPanel. - */ - public void dockSouth(JComponent child); - - /** - * Dock the given child into the given position on the DockPanel - */ - public void dockSouth(JComponent child, int idx); - - //EAST: - - /** - * Dock child on the DockPanel. - */ - public void dockEast(JComponent child); - - /** - * Dock the given child into the given position on the DockPanel - */ - public void dockEast(JComponent child, int idx); - - //WEST: - - /** - * Dock child on the DockPanel. - */ - public void dockWest(JComponent child); - - /** - * Dock the given child into the given position on the DockPanel - */ - public void dockWest(JComponent child, int idx); - - //ANYWHERE: - - /** - * Dock the given child somewhere on the DockPanel. - */ - public void dockSomewhere(JComponent child); - - //DOCK onto existing child: - - /** - * Dock the given child onto the given parent, which is itself a - * child. - */ - public void dock(JComponent outter, JComponent inner); - - /** - * Dock the given child onto the given parent, which is itself a - * child. - */ - public void dock(JComponent outter, JComponent inner, int idx); - - //FRAME Methods: - - /** - * Set the component to an internal frame - */ - public void internalFrame(JComponent child); - - /** - * Set the component to an external frame - */ - public void externalFrame(JComponent child); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockWrapper.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/DockWrapper.java deleted file mode 100644 index ae74978f4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/DockWrapper.java +++ /dev/null @@ -1,692 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/DockWrapper.java,v $ -// $RCSfile: DockWrapper.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 17:50:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JToolBar; -import javax.swing.UIManager; -import javax.swing.border.BevelBorder; -import javax.swing.border.Border; -import javax.swing.event.MouseInputAdapter; -import javax.swing.plaf.ButtonUI; - -import com.bbn.openmap.util.Debug; - -/** - * A panel that contains controls that will either be docked, - * internal-framed or external framed... - * - * @author Ben Lubin - * @version $Revision: 1.7 $ on $Date: 2005/08/09 17:50:51 $ - * @since 12/5/02 - */ -public class DockWrapper extends JPanel { - - /* package */static final int UNDEF = -1; - /* package */static final int EXTERNAL = 1; - /* package */static final int INTERNAL = 2; - /* package */static final int DOCK_NORTH = 3; - /* package */static final int DOCK_SOUTH = 4; - /* package */static final int DOCK_WEST = 5; - /* package */static final int DOCK_EAST = 6; - - /** Is this wrapper currently resizable? */ - private boolean resizable = false; - - /** Which docking state we are in */ - private int state = UNDEF; - - /** are we transparent? */ - private boolean transparent = false; - - /** Holds the tabbed pane if we are currently holding tabs. */ - private JTabbedPane tabPane = null; - - BasicDockPanel dockPanel; - - /** Contents of this wrapper, size >1 if tabbed, 1 if not tabbed. */ - private List children = new ArrayList(1); - - /** Other Wrappers that have been docked onto this one. */ - private List dockedWrappers = new ArrayList(0); - - private MouseHandler mouseHandler = new MouseHandler(); - - public DockWrapper(BasicDockPanel dp) { - dockPanel = dp; - setLayout(new BorderLayout()); - setOpaque(false); - } - - /** Special constructor for use in the cardinal DockWrappers */ - /* package */DockWrapper(BasicDockPanel dp, int state) { - this(dp); - this.state = state; - } - - //Accessor Methods: - /////////////////// - - public void addChild(JComponent child) { - children.add(child); - if (isTabbed()) { - String tabName = dockPanel.getConstraint(child).getTabName(); - if (tabName == null) { - tabName = child.getName(); - } - tabPane.insertTab(tabName, null, child, null, 0); - } else { - add(child, BorderLayout.CENTER); - } - } - - public void removeChild(JComponent child) { - if (children.size() < 1) { - Debug.error("DockWrapper: Unexpected children list"); - } - if (isTabbed()) { - tabPane.remove(child); - } else { - remove(child); - } - children.remove(child); - } - - /** - * Get all of the children that we are holding. The returned list - * will have one element iff the DockWrapper is not tabbed. - * - * @return a list of JComponents that are the children. - */ - public List getChildren() { - return children; - } - - /** - * Get the one and only child if we are not tabbed. If we are - * tabbed, there may be more than one child... - */ - public JComponent getChild() { - return (children.isEmpty() ? null : (JComponent) children.get(0)); - } - - //Tabbing Methods: - ////////////////// - - /* package */void setTabName(JComponent child, String name) { - if (isTabbed()) { - tabPane.setTitleAt(tabPane.indexOfComponent(child), name); - } - } - - /** Returns true iff this dockable contains more than one component */ - public boolean isTabbed() { - return tabPane != null; - } - - /** - * Get the index of the dockwrapper that we should use for - * tabbing-up, or -1 if there is none. - */ - public int getDockedWrapperIndexForTabbing() { - int idx = 0; - for (Iterator iter = getDockedWrappers().iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - if (dw.canTab()) { - return idx; - } - idx++; - } - return -1; - } - - private void tab(DockWrapper w) { - //Get rid of the existing wrapper: - dockPanel.removeWrapper(w); - if (children.size() == 1) { - //Create the tab pane: - JComponent child = getChild(); - removeChild(child); - tabPane = new JTabbedPane(JTabbedPane.BOTTOM); - add(tabPane, BorderLayout.CENTER); - setOpaque(true); - addChild(child); - } - for (Iterator iter = w.getChildren().iterator(); iter.hasNext();) { - JComponent child = (JComponent) iter.next(); - dockPanel.setWrapper(child, this); - addChild(child); - } - } - -// private void untab(JComponent child) { -// if (child == null) { -// throw new RuntimeException("Can't untab null"); -// } -// removeChild(child); -// if (children.size() == 1) { -// JComponent curChild = getChild(); -// removeChild(curChild); -// remove(tabPane); -// tabPane = null; -// addChild(curChild); -// setOpaque(false); -// } -// DockWrapper dw = dockPanel.createDockWrapper(child); -// } - - //Transparency Methods: - /////////////////////// - - public void doLayout() { - updateTransparency(); - super.doLayout(); - } - - /** - * Set the indicated JComponent to transparent or not transparent. - * - * @return true iff this call has changed the state - */ - protected static boolean setTransparent(JComponent child, boolean t) { - boolean ret = false; - if (child instanceof JPanel) { - child.setOpaque(!t); - ret |= child.isOpaque() == t; - } - if (child instanceof JToolBar) { - child.setOpaque(!t); - ret |= child.isOpaque() == t; - } - if (child instanceof AbstractButton) { - AbstractButton b = (AbstractButton) child; - if (t) { - if (!(b.getUI() instanceof TransparentButtonUI)) { - b.setContentAreaFilled(false); - b.setUI((ButtonUI) TransparentButtonUI.createUI(b)); - ret = true; - } - } else { - if (b.getUI() instanceof TransparentButtonUI) { - b.setContentAreaFilled(true); - b.setUI((ButtonUI) UIManager.getUI(b)); - ret = true; - } - } - } - - for (int i = 0; i < child.getComponentCount(); i++) { - Object o = child.getComponent(i); - if (o instanceof JComponent) { - JComponent c = (JComponent) o; - ret |= setTransparent(c, t); - } - } - return ret; - } - - //Resizing Methods: - /////////////////// - - protected void makeNotResizable() { - setBorder(null); - removeMouseListener(mouseHandler); - removeMouseMotionListener(mouseHandler); - } - - protected void makeResizable() { - setBorder(makeResizeBorder()); - addMouseListener(mouseHandler); - addMouseMotionListener(mouseHandler); - } - - /** get the border that mouse is in */ - protected int inBorder(int x, int y) { - Border b = getBorder(); - if (b == null) { - return UNDEF; - } - Insets i = b.getBorderInsets(this); - if (x <= i.left) { - return DOCK_WEST; - } - if (x >= getWidth() - i.right) { - return DOCK_EAST; - } - if (y <= i.top) { - return DOCK_NORTH; - } - if (y >= getHeight() - i.bottom) { - return DOCK_SOUTH; - } - return UNDEF; - } - - protected Border makeResizeBorder() { - Color highlightOuter = UIManager.getColor("controlLtHighlight"); - Color highlightInner = UIManager.getColor("controlHighlight"); - Color shadowOuter = UIManager.getColor("controlDkShadow"); - Color shadowInner = UIManager.getColor("controlShadow"); - if (transparent) { - highlightOuter = new Color(0, 0, 0, 50); - highlightInner = new Color(0, 0, 0, 75); - shadowOuter = new Color(0, 0, 0, 175); - shadowInner = new Color(0, 0, 0, 150); - } - Border border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, - highlightOuter, - highlightInner, - shadowOuter, - shadowInner), - BorderFactory.createBevelBorder(BevelBorder.LOWERED, - highlightOuter, - highlightInner, - shadowOuter, - shadowInner)); - return border; - } - - //Constraint methods: - ///////////////////// - - /** - * Set the transparency of this DockWrapper to whatever the - * Constraint says it should be. - * - * @return true iff the state has changed. - */ - public boolean updateTransparency() { - boolean ret = false; - if (children.size() == 1) { - boolean t = dockPanel.getConstraint(getChild()).canTransparent(); - transparent = t; - ret |= setTransparent(getChild(), t); - } else { - transparent = false; - for (Iterator iter = children.iterator(); iter.hasNext();) { - JComponent c = (JComponent) iter.next(); - ret |= setTransparent(c, transparent); - } - } - return ret; - } - - /** Make the dock wrapper's border reflect its resizability */ - public void updateResizable() { - List constraints = dockPanel.getConstraints(getChildren()); - boolean canResize = DockConstraint.canResize(constraints); - if (resizable && !canResize) { - makeNotResizable(); - } - if (!resizable && canResize) { - makeResizable(); - } - } - - /** Determine if this can occlude */ - public boolean canOcclude() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canOcclude(constraints); - } - - /** Determine if this can tab */ - public boolean canTab() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canTab(constraints); - } - - /** Determine if this can close */ - public boolean canClose() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canClose(constraints); - } - - /** Determine if this can internalFrame */ - public boolean canInternalFrame() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canInternalFrame(constraints); - } - - /** Determine if this can externalFrame */ - public boolean canExternalFrame() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canExternalFrame(constraints); - } - - /** Determine if this can dockNorth */ - public boolean canDockNorth() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canDockNorth(constraints); - } - - /** Determine if this can dockSouth */ - public boolean canDockSouth() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canDockSouth(constraints); - } - - /** Determine if this can dockEast */ - public boolean canDockEast() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canDockEast(constraints); - } - - /** Determine if this can dockWest */ - public boolean canDockWest() { - List constraints = dockPanel.getConstraints(getChildren()); - return DockConstraint.canDockWest(constraints); - } - - //State Methods: - //////////////// - - public void makeExternalFrame() { - freeWrapper(); - state = EXTERNAL; - } - - protected void removeExternalFrame() { - state = UNDEF; - } - - public void makeInternalFrame() { - freeWrapper(); - state = INTERNAL; - } - - protected void removeInternalFrame() { - state = UNDEF; - } - - public void makeDockNorth() { - makeDock(DOCK_NORTH); - } - - protected void removeDockNorth() { - removeDock(); - } - - public void makeDockSouth() { - makeDock(DOCK_SOUTH); - } - - protected void removeDockSouth() { - removeDock(); - } - - public void makeDockEast() { - makeDock(DOCK_EAST); - } - - protected void removeDockEast() { - removeDock(); - } - - public void makeDockWest() { - makeDock(DOCK_WEST); - } - - protected void removeDockWest() { - removeDock(); - } - - protected void makeDock(int state) { - freeWrapper(); - this.state = state; - dockPanel.addDockWrapper(this); - orientToolbars(); - } - - protected void orientToolbars() { - for (Iterator iter = getChildren().iterator(); iter.hasNext();) { - JComponent child = (JComponent) iter.next(); - if (!(child instanceof JToolBar)) { - continue; - } - JToolBar t = (JToolBar) child; - switch (state) { - case DOCK_NORTH: - case DOCK_SOUTH: - t.setOrientation(JToolBar.HORIZONTAL); - break; - case DOCK_EAST: - case DOCK_WEST: - t.setOrientation(JToolBar.VERTICAL); - break; - } - } - } - - protected void removeDock() { - dockPanel.removeDockWrapper(this); - this.state = UNDEF; - } - - protected void setState(int state) { - switch (state) { - case INTERNAL: - makeInternalFrame(); - break; - case EXTERNAL: - makeExternalFrame(); - break; - case DOCK_NORTH: - makeDockNorth(); - break; - case DOCK_SOUTH: - makeDockSouth(); - break; - case DOCK_WEST: - makeDockWest(); - break; - case DOCK_EAST: - makeDockEast(); - break; - } - } - - //Docking up Methods: - ///////////////////// - - public void freeWrapper() { - switch (state) { - case INTERNAL: - removeInternalFrame(); - break; - case EXTERNAL: - removeExternalFrame(); - break; - case DOCK_NORTH: - removeDockNorth(); - break; - case DOCK_SOUTH: - removeDockSouth(); - break; - case DOCK_WEST: - removeDockWest(); - break; - case DOCK_EAST: - removeDockEast(); - break; - } - } - - /** Attempt to remove the given wrapper from us */ - public boolean freeWrapper(DockWrapper w) { - if (dockedWrappers.remove(w)) { - w.freeWrapper(); - return true; - } - for (Iterator iter = dockedWrappers.iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - if (dw.freeWrapper(w)) { - return true; - } - } - return false; - } - - public boolean hasDockedWrappers() { - return !getDockedWrappers().isEmpty(); - } - - public List getDockedWrappers() { - return dockedWrappers; - } - - public DockWrapper getDockedWrapper(int idx) { - return (DockWrapper) dockedWrappers.get(idx); - } - - public void dock(DockWrapper w) { - dock(w, -1); - } - - public void dock(DockWrapper w, int i) { - w.setState(state); - int idx = getDockedWrapperIndexForTabbing(); - if (idx != -1 && w.canTab()) { - getDockedWrapper(idx).tab(w); - } else { - if (i == -1) { - dockedWrappers.add(w); - } else { - dockedWrappers.set(i, w); - } - } - } - - /** - * Recursively determine if another wrapper is docked on this one. - */ - public boolean isDockedOnRecurse(DockWrapper w) { - if (this.equals(w)) { - return true; - } - for (Iterator iter = dockedWrappers.iterator(); iter.hasNext();) { - DockWrapper dw = (DockWrapper) iter.next(); - if (dw.isDockedOnRecurse(w)) { - return true; - } - } - return false; - } - - public void setPreferredHeight(int i) { - Dimension d = getPreferredSize(); - d.height = i; - setPreferredSize(d); - } - - public void setPreferredWidth(int i) { - Dimension d = getPreferredSize(); - d.width = i; - setPreferredSize(d); - } - - //Nested Classes: - ///////////////// - - protected class MouseHandler extends MouseInputAdapter { - int resizeLoc = UNDEF; - int pressedVal = 0; - - public void mousePressed(MouseEvent e) { - resizeLoc = inBorder(e.getX(), e.getY()); - switch (resizeLoc) { - case DOCK_NORTH: - case DOCK_SOUTH: - pressedVal = e.getY(); - break; - case DOCK_EAST: - case DOCK_WEST: - pressedVal = e.getX(); - break; - } - } - - public void mouseReleased(MouseEvent e) { - Dimension d = getSize(); - switch (resizeLoc) { - case DOCK_NORTH: - d.height += pressedVal - e.getY(); - setPreferredSize(d); - revalidate(); - break; - case DOCK_SOUTH: - d.height -= pressedVal - e.getY(); - setPreferredSize(d); - revalidate(); - break; - case DOCK_EAST: - d.width -= pressedVal - e.getX(); - setPreferredSize(d); - revalidate(); - break; - case DOCK_WEST: - d.width += pressedVal - e.getX(); - setPreferredSize(d); - revalidate(); - break; - } - } - - public void mouseMoved(MouseEvent e) { - int loc = inBorder(e.getX(), e.getY()); - switch (loc) { - case DOCK_NORTH: - setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); - break; - case DOCK_SOUTH: - setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); - break; - case DOCK_EAST: - setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); - break; - case DOCK_WEST: - setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); - break; - default: - setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - } - - public void mouseExited(MouseEvent e) { - setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/dock/TransparentButtonUI.java b/src/core/src/main/java/com/bbn/openmap/gui/dock/TransparentButtonUI.java deleted file mode 100644 index ae17c34a5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/dock/TransparentButtonUI.java +++ /dev/null @@ -1,225 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/TransparentButtonUI.java,v $ -// $RCSfile: TransparentButtonUI.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 17:50:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.dock; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.ButtonModel; -import javax.swing.JComponent; -import javax.swing.plaf.ComponentUI; -import javax.swing.plaf.metal.MetalButtonUI; - -/** - * A subclass of the metal UI that draws a semi-transparent button on - * top of other components. - * - * @author Ben Lubin - * @version $Revision: 1.4 $ on $Date: 2005/08/09 17:50:51 $ - * @since 12/5/02 - */ -public class TransparentButtonUI extends MetalButtonUI { - private final static TransparentButtonUI transButtonUI = new TransparentButtonUI(); - - private static final int VshadowSize = 4; - private static final int HshadowSize = 2; - - private static final int VpressOffset = 3; - private static final int HpressOffset = 1; - - // ******************************** - // Create PLAF - // ******************************** - public static ComponentUI createUI(JComponent c) { - return transButtonUI; - } - - public void installDefaults(AbstractButton b) { - super.installDefaults(b); - b.setBorder(BorderFactory.createEmptyBorder(0, - 0, - VshadowSize, - HshadowSize)); - b.setFocusPainted(false); - } - - public Color getBGColor(AbstractButton c) { - Color bg = c.getBackground(); - return new Color(bg.getRed(), bg.getGreen(), bg.getBlue(), 200); - } - - public Color getSelectedBGColor(AbstractButton c) { -// Color bg = c.getBackground(); - return new Color(225, 225, 125, 200); - } - - Color darkShadow = new Color(0, 0, 0, 200); - - public Color getDarkShadow() { - return darkShadow; - } - - Color mediumShadow = new Color(0, 0, 0, 125); - - public Color getMediumShadow() { - return mediumShadow; - } - - Color lightShadow = new Color(0, 0, 0, 50); - - public Color getLightShadow() { - return lightShadow; - } - - // ******************************** - // Paint Methods - // ******************************** - - public void paint(Graphics g, JComponent c) { - AbstractButton b = (AbstractButton) c; - ButtonModel model = b.getModel(); - Dimension size = b.getSize(); - - // perform UI specific press action, e.g. Windows L&F shifts - // text - if (model.isArmed() && model.isPressed() || model.isSelected()) { - //We're pressed: - g = g.create(HpressOffset, VpressOffset, size.width, size.height); - Dimension sSize = new Dimension(size.width - HpressOffset, size.height - - VpressOffset); - drawShadow(g, sSize, VshadowSize - VpressOffset, HshadowSize - - HpressOffset); - } else { - //We're not pressed: - drawShadow(g, size, VshadowSize, HshadowSize); - } - - //Paint a background: - if (model.isArmed() && model.isPressed() || model.isSelected()) { - //Selected color: - g.setColor(getSelectedBGColor(b)); - } else { - //Button's color - g.setColor(getBGColor(b)); - } - g.fillRect(0, 0, size.width - HshadowSize, size.height - VshadowSize); - super.paint(g, c); - } - - private void drawShadow(Graphics g, Dimension size, int vShadowSize, - int hShadowSize) { - drawHArea(g, - size, - getDarkShadow(), - vShadowSize, - hShadowSize, - 0, - vShadowSize / 3); - drawHArea(g, - size, - getMediumShadow(), - vShadowSize, - hShadowSize, - vShadowSize / 3, - vShadowSize * 2 / 3); - drawHArea(g, - size, - getLightShadow(), - vShadowSize, - hShadowSize, - vShadowSize * 2 / 3, - vShadowSize); - int last = 0; - int next = hShadowSize / 3; - if (hShadowSize % 3 == 2) { - next += 1; - } - drawVArea(g, - size, - getDarkShadow(), - vShadowSize, - hShadowSize, - last, - next); - last = next; - if (hShadowSize * 2 / 3 > last) { - next = hShadowSize * 2 / 3; - drawVArea(g, - size, - getMediumShadow(), - vShadowSize, - hShadowSize, - last, - next); - } - last = next; - if (hShadowSize > last) { - next = hShadowSize; - drawVArea(g, - size, - getLightShadow(), - vShadowSize, - hShadowSize, - last, - next); - } - } - - private void drawHArea(Graphics g, Dimension size, Color c, - int vShadowSize, int hShadowSize, int low, int high) { - g.setColor(c); - for (int i = low; i < high; i++) { - drawHLine(g, size, vShadowSize, hShadowSize, i); - } - } - - private void drawHLine(Graphics g, Dimension size, int vShadowSize, - int hShadowSize, int i) { - g.drawLine(i * hShadowSize / vShadowSize, - size.height - vShadowSize + i, - size.width - hShadowSize + (i * hShadowSize / vShadowSize), - size.height - vShadowSize + i); - } - - private void drawVArea(Graphics g, Dimension size, Color c, - int vShadowSize, int hShadowSize, int low, int high) { - g.setColor(c); - for (int i = low; i < high; i++) { - drawVLine(g, size, vShadowSize, hShadowSize, i); - } - } - - private void drawVLine(Graphics g, Dimension size, int vShadowSize, - int hShadowSize, int i) { - g.drawLine(size.width - hShadowSize + i, - (i * vShadowSize / hShadowSize), - size.width - hShadowSize + i, - size.height - vShadowSize + (i * vShadowSize / hShadowSize) - 1); - } - - /** From super class. Don't want to do metal's behavior... */ - protected void paintButtonPressed(Graphics g, AbstractButton b) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/AbstractEventPresenter.java b/src/core/src/main/java/com/bbn/openmap/gui/event/AbstractEventPresenter.java deleted file mode 100644 index d20045921..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/AbstractEventPresenter.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/aar/src/com/bbn/ambush/gui/AbstractEventPresenter.java,v -// $ -// $RCSfile: AbstractEventPresenter.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:20 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.Component; -import java.util.Iterator; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.util.PropUtils; - -public abstract class AbstractEventPresenter extends OMComponentPanel implements - EventPresenter { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected String name; - - public AbstractEventPresenter() { - name = ""; - } - - public void setProperties(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - name = props.getProperty(prefix + Layer.PrettyNameProperty, name); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + Layer.PrettyNameProperty, name); - return props; - } - - public String getName() { - return name; - } - - public void setName(String n) { - name = n; - } - - public Component getComponent() { - return this; - } - - /** - * Optional optimized form. Passes through to the simpler form by default. - * @param start Start time (leftmost edge of timeline). - * @param end End time (rightmost edge of timeline). - * @param step Time span represented by a single pixel width. - * @return iterator of events appropriate for display given parameters provided. - */ - public Iterator getActiveEvents(long start, long end, long step) { - return getActiveEvents(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListCellRenderer.java b/src/core/src/main/java/com/bbn/openmap/gui/event/EventListCellRenderer.java deleted file mode 100644 index cb106b124..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListCellRenderer.java +++ /dev/null @@ -1,185 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.util.Properties; - -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.ListCellRenderer; - -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -public class EventListCellRenderer extends OMComponentPanel implements ListCellRenderer { - - private static final long serialVersionUID = 1L; - protected JLabel label = new JLabel(); - protected JLabel timeMark = new JLabel(); - protected JLabel ratingMark = new JLabel(); - - public Color fontColor = Color.BLACK; - public Color altFontColor = Color.BLACK; - public Color selectColor = Color.GRAY; - public Color timeWindowColor = Color.LIGHT_GRAY; - public Color regularBackgroundColor = Color.WHITE; - - public static final String FontColorProperty = "fontColor"; - public static final String AltFontColorProperty = "altFontColor"; - public static final String SelectColorProperty = "selectColor"; - public static final String TimeWindowColorProperty = "timeWindowColor"; - public static final String BackgroundColorProperty = "color"; - public static final String IconPackageClassProperty = "iconPackageClass"; - - /** - * This cell renderer is pretty closely tied to the icon package. If you - * want to change one, you'll probably want to change the other, too. - */ - protected EventListIconPackage iconPackage; - - public EventListCellRenderer() { - init(); - } - - protected void init() { - removeAll(); - setOpaque(true); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - gridbag.setConstraints(label, c); - this.add(label); - - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - gridbag.setConstraints(ratingMark, c); - this.add(ratingMark); - gridbag.setConstraints(timeMark, c); - this.add(timeMark); - - Font f = label.getFont(); - f = new Font(f.getName(), f.getStyle(), f.getSize() - 1); - label.setFont(f); - - // This gets icon package set up - setPreferredSize(new Dimension(20, getIconPackage().getButtonSize())); - } - - public EventListIconPackage getIconPackage() { - if (iconPackage == null) { - iconPackage = new EventListIconPackage(); - } - return iconPackage; - } - - public void setIconPackage(EventListIconPackage iconPackage) { - this.iconPackage = iconPackage; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - fontColor = PropUtils.parseColorFromProperties(props, prefix + FontColorProperty, fontColor); - altFontColor = PropUtils.parseColorFromProperties(props, prefix + AltFontColorProperty, altFontColor); - selectColor = PropUtils.parseColorFromProperties(props, prefix + SelectColorProperty, selectColor); - timeWindowColor = PropUtils.parseColorFromProperties(props, prefix + TimeWindowColorProperty, timeWindowColor); - regularBackgroundColor = PropUtils.parseColorFromProperties(props, prefix + BackgroundColorProperty, - regularBackgroundColor); - - String crc = props.getProperty(prefix + IconPackageClassProperty); - if (crc != null) { - iconPackage = (EventListIconPackage) ComponentFactory.create(crc, prefix, props); - init(); - } - - } - - public DrawingAttributes setRenderingAttributes(DrawingAttributes drawingAttributes) { - - if (drawingAttributes == null) { - drawingAttributes = DrawingAttributes.getDefaultClone(); - } - - drawingAttributes.setFillPaint(regularBackgroundColor); - drawingAttributes.setSelectPaint(selectColor); - drawingAttributes.setLinePaint(fontColor); - drawingAttributes.setMattingPaint(timeWindowColor); - return drawingAttributes; - } - - public Component getListCellRendererComponent(JList list, OMEvent value, int index, boolean isSelected, - boolean cellHasFocus) { - label.setText(value.toString()); - - if (value instanceof OMEvent) { - OMEvent OMe = (OMEvent) value; - isSelected = OMe.getAttribute(OMEvent.ATT_KEY_SELECTED) != null; - - timeMark.setIcon(OMe.getAttribute(OMEvent.ATT_KEY_PLAY_FILTER) == Boolean.TRUE ? iconPackage.clockImage - : iconPackage.invisibleImage); - - Object rating = OMe.getAttribute(OMEvent.ATT_KEY_RATING); - if (rating == OMEvent.ATT_VAL_BAD_RATING) { - ratingMark.setIcon(iconPackage.thumbsDownImage); - } else if (rating == OMEvent.ATT_VAL_GOOD_RATING) { - ratingMark.setIcon(iconPackage.thumbsUpImage); - } else { - ratingMark.setIcon(iconPackage.invisibleImage); - } - - if (OMe.isAtCurrentTime()) { - if (isSelected) { - setBackground(selectColor); - } else { - setBackground(timeWindowColor); - } - setForeground(altFontColor); - return this; - } - - } else { - timeMark.setIcon(iconPackage.invisibleImage); - ratingMark.setIcon(iconPackage.invisibleImage); - } - - setBackground(isSelected ? selectColor : regularBackgroundColor); - setForeground(isSelected ? altFontColor : fontColor); - return this; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListIconPackage.java b/src/core/src/main/java/com/bbn/openmap/gui/event/EventListIconPackage.java deleted file mode 100644 index 7a219d459..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListIconPackage.java +++ /dev/null @@ -1,322 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Polygon; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Line2D; -import java.awt.geom.Rectangle2D; -import java.util.Properties; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.tools.icon.BasicIconPart; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.IconPartList; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.util.PropUtils; - -public class EventListIconPackage extends OMComponent { - protected int buttonSize = 16; - - protected ImageIcon xImage; - protected ImageIcon clockImage; - protected ImageIcon thumbsUpImage; - protected ImageIcon thumbsDownImage; - protected ImageIcon invisibleImage; - - public final static String ShowRatingsProperty = "showRatings"; - public final static String ShowPlayFilterProperty = "showPlayFilter"; - public final static String ButtonSizeProperty = "buttonSize"; - - protected boolean showRatings = true; - protected boolean showPlayFilter = true; - - public EventListIconPackage() { - initIcons(); - } - - public EventListIconPackage(int buttonSize) { - setButtonSize(buttonSize); - initIcons(); - } - - public int getButtonSize() { - return buttonSize; - } - - public void setButtonSize(int buttonSize) { - this.buttonSize = buttonSize; - } - - public boolean isShowRatings() { - return showRatings; - } - - public void setShowRatings(boolean showRatings) { - this.showRatings = showRatings; - } - - public boolean isShowPlayFilter() { - return showPlayFilter; - } - - public void setShowPlayFilter(boolean showPlayFilter) { - this.showPlayFilter = showPlayFilter; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - showRatings = PropUtils.booleanFromProperties(props, prefix - + ShowRatingsProperty, showRatings); - showPlayFilter = PropUtils.booleanFromProperties(props, prefix - + ShowPlayFilterProperty, showPlayFilter); - buttonSize = PropUtils.intFromProperties(props, prefix - + ButtonSizeProperty, buttonSize); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.setProperty(prefix + ShowRatingsProperty, - Boolean.toString(showRatings)); - props.setProperty(prefix + ShowPlayFilterProperty, - Boolean.toString(showPlayFilter)); - props.setProperty(prefix + ButtonSizeProperty, - Integer.toString(buttonSize)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, - props, - this.getClass(), - ShowRatingsProperty, - "Show Ratings", - "Show controls for adding ratings to events", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, - props, - this.getClass(), - ShowPlayFilterProperty, - "Show Play Filter", - "Show controls for restricting playback to certain events", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, - props, - this.getClass(), - ButtonSizeProperty, - "Button Size", - "Pixel size for buttons", - null); - - return props; - } - - protected void initIcons() { - - DrawingAttributes greyDa = new DrawingAttributes(); - Color gry = new Color(0x99999999, true); - greyDa.setFillPaint(gry); - greyDa.setLinePaint(gry); - - DrawingAttributes whtDa = new DrawingAttributes(); - whtDa.setLinePaint(Color.white); - whtDa.setStroke(new BasicStroke(2)); - - DrawingAttributes handsDa = new DrawingAttributes(); - handsDa.setStroke(new BasicStroke(2)); - - DrawingAttributes invisDa = new DrawingAttributes(); - invisDa.setLinePaint(OMColor.clear); - invisDa.setFillPaint(OMColor.clear); - - DrawingAttributes timeDa = new DrawingAttributes(); - timeDa.setLinePaint(OMColor.blue); - timeDa.setFillPaint(OMColor.blue); - - IconPart ip = new BasicIconPart(new Rectangle2D.Double(0, 0, 100, 100), invisDa); - invisibleImage = OMIconFactory.getIcon(buttonSize, buttonSize, ip); - - IconPartList ipl = new IconPartList(); - ipl.add(new BasicIconPart(new Ellipse2D.Double(5, 5, 90, 90), greyDa)); - ipl.add(new BasicIconPart(new Line2D.Double(30, 30, 70, 70), whtDa)); - ipl.add(new BasicIconPart(new Line2D.Double(30, 70, 70, 30), whtDa)); - xImage = OMIconFactory.getIcon(buttonSize, buttonSize, ipl); - - ipl = new IconPartList(); - ipl.add(new BasicIconPart(new Ellipse2D.Double(10, 10, 80, 80), handsDa)); - ipl.add(new BasicIconPart(new Line2D.Double(50, 50, 50, 15), handsDa)); - ipl.add(new BasicIconPart(new Line2D.Double(50, 50, 70, 50), handsDa)); - clockImage = OMIconFactory.getIcon(buttonSize, buttonSize, ipl); - - DrawingAttributes goodDa = new DrawingAttributes(); - goodDa.setFillPaint(Color.green); - goodDa.setLinePaint(Color.green.darker().darker()); - ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { - 10, 90, 90, 10 }, 4), goodDa); - thumbsUpImage = OMIconFactory.getIcon(buttonSize, buttonSize, ip); - - DrawingAttributes badDa = new DrawingAttributes(); - badDa.setFillPaint(Color.red); - badDa.setLinePaint(Color.red.darker().darker()); - ip = new BasicIconPart(new Polygon(new int[] { 10, 90, 50, 10 }, new int[] { - 10, 10, 90, 10 }, 4), badDa); - thumbsDownImage = OMIconFactory.getIcon(buttonSize, buttonSize, ip); - - } - - /** - * Should only be called with a reference to a dedicated EventListPresenter - * for this IconPackage. - * - * @param elp EventListPresenter supplying events - * @return JPanel that contains components for controlling events. - */ - protected JPanel createEventControlPanel(EventListPresenter elp) { - - Dimension buttonDim = new Dimension(buttonSize, buttonSize); - final EventListPresenter eventListPresenter = elp; - - JPanel eventControlPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - eventControlPanel.setLayout(gridbag); - - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(2, 2, 2, 2); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 0.5f; - - if (showPlayFilter) { - JPanel timeFilterPanel = new JPanel(); - gridbag.setConstraints(timeFilterPanel, c); - - eventControlPanel.add(timeFilterPanel); - - // JLabel timerLabel = new JLabel("Play Selection:"); - // timeFilterPanel.add(timerLabel); - - JButton clockButton = new JButton(clockImage); - clockButton.setPreferredSize(buttonDim); - clockButton.setToolTipText("Mark event(s) for play filtering."); - clockButton.setBorderPainted(false); - clockButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - eventListPresenter.setSelectedEventsAttribute(OMEvent.ATT_KEY_PLAY_FILTER, - Boolean.TRUE); - } - }); - timeFilterPanel.add(clockButton); - - JButton timeClearAllButton = new JButton(xImage); - timeClearAllButton.setPreferredSize(buttonDim); - timeClearAllButton.setToolTipText("Clear selected events from play filtering."); - timeClearAllButton.setBorderPainted(false); - timeClearAllButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - eventListPresenter.setSelectedEventsAttribute(OMEvent.ATT_KEY_PLAY_FILTER, - null); - } - }); - timeFilterPanel.add(timeClearAllButton); - } - - c.weightx = 1.0f; - c.insets = new Insets(2, 0, 2, 2); - // JLabel ratingsLabel = new JLabel("Rating:", - // SwingConstants.RIGHT); - // gridbag.setConstraints(ratingsLabel, c); - // eventControlPanel.add(ratingsLabel); - - if (showRatings) { - c.weightx = 0.5f; - JPanel ratingsPanel = new JPanel(); - gridbag.setConstraints(ratingsPanel, c); - eventControlPanel.add(ratingsPanel); - - JButton thumbsUpButton = new JButton(thumbsUpImage); - thumbsUpButton.setPreferredSize(buttonDim); - thumbsUpButton.setToolTipText("Flag selected event(s) as positive."); - thumbsUpButton.setBorderPainted(false); - thumbsUpButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - eventListPresenter.setSelectedEventsAttribute(OMEvent.ATT_KEY_RATING, - OMEvent.ATT_VAL_GOOD_RATING); - } - }); - ratingsPanel.add(thumbsUpButton); - - JButton thumbsDownButton = new JButton(thumbsDownImage); - thumbsDownButton.setPreferredSize(buttonDim); - thumbsDownButton.setToolTipText("Flag selected event(s) as negative."); - thumbsDownButton.setBorderPainted(false); - thumbsDownButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - eventListPresenter.setSelectedEventsAttribute(OMEvent.ATT_KEY_RATING, - OMEvent.ATT_VAL_BAD_RATING); - } - }); - ratingsPanel.add(thumbsDownButton); - - JButton clearAllRatingsButton = new JButton(xImage); - clearAllRatingsButton.setPreferredSize(buttonDim); - clearAllRatingsButton.setToolTipText("Clear ratings of selected events."); - clearAllRatingsButton.setBorderPainted(false); - clearAllRatingsButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - eventListPresenter.setSelectedEventsAttribute(OMEvent.ATT_KEY_RATING, - null); - } - }); - ratingsPanel.add(clearAllRatingsButton); - } - - return eventControlPanel; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListPresenter.java b/src/core/src/main/java/com/bbn/openmap/gui/event/EventListPresenter.java deleted file mode 100644 index 63cf68711..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/EventListPresenter.java +++ /dev/null @@ -1,1220 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/OM/src/com/bbn/ambush/gui/EventListPanel.java,v -// $ -// $RCSfile: EventListPresenter.java,v $ -// $Revision: 1.2 $ -// $Date: 2007/09/27 23:12:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ConcurrentModificationException; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.TreeSet; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JToolBar; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.ToolTipManager; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.event.OMEventComparator; -import com.bbn.openmap.event.OMEventHandler; -import com.bbn.openmap.event.OMEventSelectionCoordinator; -import com.bbn.openmap.event.OMEventSelectionListener; -import com.bbn.openmap.gui.time.TimePanel; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.time.Clock; -import com.bbn.openmap.time.TimeBoundsEvent; -import com.bbn.openmap.time.TimeBoundsListener; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The EventListPresenter presents OMEvents as a list. It will find - * OMEventHandlers in the MapHandler and display the events of the active ones. - * Clicking on the list will set the current time to the event time, and also - * move the map to the event location. You can also use the filter and rating - * controls to group events. The TimePanel will limit playback over events that - * have been marked with the play filter, and the TimelineLayer will display the - * rating colors over the range of events designated with those ratings. - * - *

- * eventListPresenter.class=com.bbn.openmap.gui.event.EventListPresenter
- * eventListPresenter.prettyName=List
- * eventListPresenter.cellRendererClass=com.bbn.openmap.gui.event.EventListCellRenderer
- * eventListPresenter.selectColor=0xAA006699
- * eventListPresenter.timeWindowColor=0x55666666
- * # can override if you want to change what the icons look like
- * eventListPresenter.iconPackageClass=com.bbn.openmap.gui.event.EventListIconPackage
- * # optional, if you want to turn these off at the bottom of the presenter.
- * eventListPresenter.showRatings=false
- * eventListPresenter.showPlayFilter=false
- * 
- */ -public class EventListPresenter extends AbstractEventPresenter implements EventPresenter, ListSelectionListener, - PropertyChangeListener, MouseListener, MouseMotionListener, TimeBoundsListener, TimeEventListener { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.event.EventListPresenter"); - - protected LinkedList eventHandlers; - protected LinkedList macroFilters; - protected EventPanel parentPanel; - protected JList displayList; - protected Clock clock = null; - protected MapBean map = null; - protected List activeFilters; - protected Map filters = new Hashtable(); - protected JPanel filterPanel; - protected long displayTimeWindow = 1000; - protected int prefWidth = 200; - protected int prefHeight = 0; - - protected JLabel detailSpace; - protected JPanel detailSpacePanel; - - protected TreeSet activeEvents; - protected TreeSet allEvents; - - protected OMEventSelectionCoordinator aesc; - protected EventListCellRenderer cellRenderer; - - public static final String DisplayIntervalProperty = "displayInterval"; - public static final String CellRendererClassProperty = "cellRendererClass"; - public static final String PreferredWidthProperty = "width"; - public static final String PreferredHeightProperty = "height"; - - /** - * A drawing attributes object that holds the basic colors used for display. - * The font color is held as line paint, the select color is held as the - * select paint, the time window color is held as the matting paint, and the - * background color is held as the fill paint. - */ - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - - private OMEvent lastSelectedEvent; - - /** - * Create a new EventListPresenter with a BorderLayout. The scrolled pane - * containing the list is in the main body, and controls for bringing up the - * filter controls are display in the NORTH. - */ - public EventListPresenter() { - setIsolated(true); - eventHandlers = new LinkedList(); - macroFilters = new LinkedList(); - setLayout(new BorderLayout()); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String crc = props.getProperty(prefix + CellRendererClassProperty); - if (crc != null) { - setEventCellRenderer((EventListCellRenderer) ComponentFactory.create(crc, prefix, props)); - } - - displayTimeWindow = PropUtils.longFromProperties(props, prefix + DisplayIntervalProperty, displayTimeWindow); - - prefWidth = PropUtils.intFromProperties(props, prefix + PreferredWidthProperty, prefWidth); - prefHeight = PropUtils.intFromProperties(props, prefix + PreferredHeightProperty, prefHeight); - - } - - public DrawingAttributes getSelectionDrawingAttributes() { - return drawingAttributes; - } - - public void addEventHandler(OMEventHandler aeh) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("adding " + aeh.getClass().getName()); - } - eventHandlers.add(aeh); - retrieveFiltersFromEventHandlers(); - updateInterface(false); - } - - public void removeEventHandler(OMEventHandler aeh) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("removing " + aeh.getClass().getName()); - } - eventHandlers.remove(aeh); - retrieveFiltersFromEventHandlers(); - updateInterface(); - } - - public void clearEventHandlers() { - if (logger.isLoggable(Level.FINE)) { - logger.fine("clearing event handlers"); - } - eventHandlers.clear(); - retrieveFiltersFromEventHandlers(); - updateInterface(false); - } - - public void rebuildEventList() { - rebuildEventList(true); - } - - /** - * This is the method that rebuilds the list of visible events. - */ - public void rebuildEventList(boolean resetSelected) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("rebuilding list"); - } - // If allEvents isn't recreated here, weird things start happening with - // selection. I seems that this gets the entire event list reset for the - // interface. - allEvents = null; - activeEvents = null; - hideDetails(); - initInterface(getActiveEvents(), resetSelected); - highlightCurrentEvent(currentTime); - firePropertyChange(ActiveEventsProperty, null, getActiveEvents()); - } - - /** - * This is the method that creates a sorted list of all events. - * - * @return Iterator of OMEvents. - */ - public synchronized Iterator getAllEvents() { - TreeSet localRef = allEvents; - if (localRef == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("fetching all events from event handlers"); - } - - localRef = new TreeSet(new OMEventComparator()); - for (Iterator it = eventHandlers.iterator(); it.hasNext();) { - List eventList = it.next().getEventList(); - if (eventList != null) { - try { - localRef.addAll(eventList); - } catch (NullPointerException npe) { - return getAllEvents(); - } - } - } - allEvents = localRef; - } - return localRef.iterator(); - } - - public boolean isEventActive(OMEvent OMe) { - if (activeEvents != null) { - for (Iterator it = getActiveEvents(); it.hasNext();) { - if (it.next() == OMe) { - return true; - } - } - } - return false; - } - - /** - * This is the method that creates a sorted list of visible events. - * - * @return Iterator of OMEvents. - */ - public synchronized Iterator getActiveEvents() { - if (activeEvents == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("building list of active events"); - } - - activeEvents = new TreeSet(new OMEventComparator()); - List activeFilters = getActiveFilters(); - for (OMEventHandler aeh : eventHandlers) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("getting filtered list from (" + aeh.getClass().getName() + ")"); - } - - // Pass a filter to the OMEventHandler to get a - // filtered list back if desired. Need to ask - // MissionEventHandler for what filters it can handle - // (with pretty name) so that the filters can be created - // by the presenter and passed back - - List eventList = aeh.getEventList(activeFilters); - if (eventList != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("list from " + aeh.getClass().getName() + "has (" + eventList.size() + ") events"); - } - for (Iterator it2 = eventList.iterator(); it2.hasNext();) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("adding OM event"); - } - - OMEvent me = it2.next(); - if (me != null) { - activeEvents.add(me); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("The " + aeh.getClass().getName() + " is providing null events."); - } - } - } - } - } - - if (logger.isLoggable(Level.FINER)) { - logger.finer("--------"); - for (Iterator it = activeEvents.iterator(); it.hasNext();) { - OMEvent eve = (OMEvent) it.next(); - logger.finer(eve.getTimeStamp() + " " + eve); - } - - logger.finer("--------"); - } - } - - return activeEvents.iterator(); - } - - protected ToolTipManager ttmanager; - - /** - * Resets the event list. - * - * @param it Iterator over all visible events (active) - * @param setSelected select the last currently selected on the list, has - * the side effect of resetting the clock. You want this to be - * false when event handlers are being added. - */ - protected synchronized void initInterface(Iterator it, boolean setSelected) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("initing interface"); - } - - DefaultListModel listModel = new DefaultListModel(); - - int selectedIndex = -1; - int curIndex = 0; - while (it.hasNext()) { - // if (logger.isLoggable(Level.FINER)) { - // logger.finer("adding event to list model"); - // } - OMEvent curEvent = it.next(); - listModel.addElement(curEvent); - if (lastSelectedEvent == curEvent && lastSelectedEvent != null) { - selectedIndex = curIndex; - } - curIndex++; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("added " + curIndex + " events to list"); - } - - // This code below will cause the first visible event to be marked as - // selected - // if the list contents change and the previous selected version is no - // longer visible. - - // if (selectedIndex < 0) { - // selectedIndex = 0; - // } - - if (displayList == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating gui components"); - } - JPanel wrapper = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - wrapper.setLayout(gridbag); - - c.fill = GridBagConstraints.BOTH; - c.weighty = 1f; - c.weightx = 1f; - c.gridwidth = GridBagConstraints.REMAINDER; - c.insets = new Insets(0, 2, 0, 2); - // Don't show the panel if there are no events to show. - // if (listModel.getSize() > 0) { - if (ttmanager == null) { - ttmanager = ToolTipManager.sharedInstance(); - ttmanager.setEnabled(true); - ttmanager.setInitialDelay(1); - } else if (displayList != null) { - ttmanager.unregisterComponent(displayList); - } - - displayList = new JList(listModel); - displayList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION/* - * SINGLE_SELECTION - */); - displayList.addListSelectionListener(this); - displayList.addMouseListener(this); - displayList.addMouseMotionListener(this); - displayList.setCellRenderer(getEventCellRenderer()); - - ttmanager.registerComponent(displayList); - - JScrollPane listScrollPane = new JScrollPane(displayList); - listScrollPane.setPreferredSize(new Dimension(prefWidth, prefHeight)); - listScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - listScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - gridbag.setConstraints(listScrollPane, c); - wrapper.add(listScrollPane); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weighty = 0f; - // Initialize the detail space. We need to embed it in a JPanel - // so the background color fills the area. - detailSpace = new JLabel(""); - detailSpacePanel = new JPanel(new BorderLayout()); - detailSpacePanel.setBackground(new Color(0xffffcc)); - detailSpacePanel.setVisible(false); - detailSpacePanel.add(detailSpace, BorderLayout.CENTER); - gridbag.setConstraints(detailSpacePanel, c); - wrapper.add(detailSpacePanel); - - JComponent ecp = getEventControlPanel(); - gridbag.setConstraints(ecp, c); - wrapper.add(ecp); - - add(wrapper, BorderLayout.CENTER); - validate(); - repaint(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Done creating gui components"); - } - } else { - setListModel(listModel); - displayList.revalidate(); - displayList.repaint(); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("done initing"); - } - - if (selectedIndex >= 0 && setSelected) { - // only select the event if it's there. Otherwise, the list and - // timeline jump inexplicably to the top. - - displayList.setSelectedIndex(selectedIndex); - } else { - lastSelectedEvent = null; - } - - } - - public EventListCellRenderer getEventCellRenderer() { - if (cellRenderer == null) { - setEventCellRenderer(new EventListCellRenderer()); - } - return cellRenderer; - } - - public void setEventCellRenderer(EventListCellRenderer lcr) { - cellRenderer = lcr; - if (cellRenderer != null) { - drawingAttributes = cellRenderer.setRenderingAttributes(drawingAttributes); - } - } - - /** - * @param string adding a filter string to the list of presentable filters - * available from one of the MissionEventHandler. - */ - protected void addFilter(String string, Boolean value) { - filters.put(string, value); - } - - /** - * Clear out the list of filters. - */ - protected void clearFilters() { - filters.clear(); - } - - public JPanel getFilterPanel() { - if (filterPanel == null) { - filterPanel = new JPanel(); - } - return filterPanel; - } - - /** - * Rebuilds the contents of the panel in the popup window for the filters - * supplied by the event handlers. - */ - protected void rebuildFilterInterface() { - JPanel filterPanel = getFilterPanel(); - filterPanel.removeAll(); - - // Set up the overall panel layout - GridBagLayout gb1 = new GridBagLayout(); - GridBagConstraints c1 = new GridBagConstraints(); - filterPanel.setLayout(gb1); - c1.insets = new Insets(10, 10, 10, 10); - c1.gridwidth = GridBagConstraints.REMAINDER; - c1.fill = GridBagConstraints.VERTICAL; - c1.weighty = .33; - - // Set up the layout of the filter options - JPanel filterSubPanel = new JPanel(); - GridBagLayout gb2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - filterSubPanel.setLayout(gb2); - c2.anchor = GridBagConstraints.WEST; - c2.gridwidth = GridBagConstraints.REMAINDER; - - // Set up the filter options, add them to panel that centers - // itself in the window while aligning all on the left. - try { - for (String title : filters.keySet()) { - JCheckBox jcb = new JCheckBox(title, ((Boolean) filters.get(title)).booleanValue()); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - String title = jcb.getText(); - setFilterValue(title, jcb.isSelected()); - rebuildEventList(); - } - }); - - gb2.setConstraints(jcb, c2); - filterSubPanel.add(jcb); - } - } catch (ConcurrentModificationException cme) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("ConcurrentModificationException caught while rebuilding the event list"); - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("ArrayIndexOutOfBoundsException caught while rebuilding the event list: " - + aioobe.getMessage()); - } - } - - // Add filter choices to the overall panel - gb1.setConstraints(filterSubPanel, c1); - filterPanel.add(filterSubPanel); - - // Create the buttons to turn them all on or off - JButton allFiltersOnButton = new JButton(EventPanel.SHOW_ALL_EVENTS_STRING); - allFiltersOnButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - resetFilters(Boolean.TRUE); - } - }); - - JButton allFiltersOffButton = new JButton(EventPanel.HIDE_ALL_EVENTS_STRING); - allFiltersOffButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - resetFilters(Boolean.FALSE); - } - }); - - // Need to put these on/off buttons in their own panel so they - // float in the middle of all the extra space in the window - // without resizing themselves to fill in the space. - JPanel resetButtonPanel = new JPanel(); - GridBagLayout gb3 = new GridBagLayout(); - GridBagConstraints c3 = new GridBagConstraints(); - resetButtonPanel.setLayout(gb3); - gb3.setConstraints(allFiltersOnButton, c3); - gb3.setConstraints(allFiltersOffButton, c3); - resetButtonPanel.add(allFiltersOnButton); - resetButtonPanel.add(allFiltersOffButton); - - c1.fill = GridBagConstraints.BOTH; - c1.weighty = .66; - c1.weightx = 1; - c1.anchor = GridBagConstraints.CENTER; - gb1.setConstraints(resetButtonPanel, c1); - - filterPanel.add(resetButtonPanel); - filterPanel.revalidate(); - } - - /** - * @param title - * @param b - */ - protected void setFilterValue(String title, boolean b) { - setFilterValue(title, b ? Boolean.TRUE : Boolean.FALSE); - } - - protected void setFilterValue(String title, Boolean val) { - filters.put(title, val); - - // Tell all the OMEventHandlers that the setting has been - // updated, let the one that cares update itself. - for (Iterator it = eventHandlers.iterator(); it.hasNext();) { - OMEventHandler eh = it.next(); - // EventHandlers should only let this be set if they - // control the events described by the filter. - eh.setFilterState(title, val); - } - - activeFilters = null; - } - - /** - * Set the filters so that all event handlers will return anything they - * have, and rebuild interface. - */ - public void resetFilters() { - resetFilters(Boolean.TRUE); - } - - /** - * Set the filters on/off so that all event handlers will return anything - * they have, and rebuild interface. - */ - public void resetFilters(Boolean enabled) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("enabled = " + enabled); - } - for (String title : filters.keySet()) { - setFilterValue(title, enabled); - } - updateInterface(); - } - - public void updateInterface() { - updateInterface(true); - } - - public void updateInterface(boolean resetSelected) { - activeFilters = null; - rebuildFilterInterface(); - rebuildEventList(resetSelected); - if (parentPanel != null) { - parentPanel.initInterface(); - } - - // Tell everyone interested in the event list to check the events. - } - - /** - * @return a Hashtable containing filter strings as keys, with Boolean - * TRUE/FALSE for whether they are enabled. - */ - public Map getFilters() { - return filters; - } - - /** - * @return a List of Strings for the filters that have been turned on. - */ - public List getActiveFilters() { - if (activeFilters == null) { - activeFilters = new LinkedList(); - Set filterNames = filters.keySet(); - for (String filterName : filterNames) { - if (filters.get(filterName) == Boolean.TRUE) { - activeFilters.add(filterName); - } - } - } - return activeFilters; - } - - /** - * Contacts the OMEventHandlers and gets their filters from them. - * Re-initializes the filter GUI. - */ - public void retrieveFiltersFromEventHandlers() { - clearFilters(); - for (Iterator it = eventHandlers.iterator(); it.hasNext();) { - - OMEventHandler meh = it.next(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Checking out OM event handler " + meh.getClass().getName()); - } - // While we're checking out the OMEventHandler, might - // as well ask it for it's filter strings, and reset the - // filter interface. - List filters = meh.getFilters(); - - if (filters != null) { - for (String filter : filters) { - Boolean val = meh.getFilterState(filter); - addFilter(filter, val != null ? val : Boolean.FALSE); - } - } - } - rebuildFilterInterface(); - } - - public void clearSelection() { - if (displayList != null) { - displayList.clearSelection(); - } - } - - protected synchronized void setListModel(ListModel lm) { - displayList.setModel(lm); - } - - protected synchronized ListModel getListModel() { - return displayList.getModel(); - } - - /** - * This method is required by ListSelectionListener. It causes events to - * happen when something in the list is clicked on. - */ - public void valueChanged(ListSelectionEvent e) { - if (e.getValueIsAdjusting() == false && displayList != null) { - int[] indicies = displayList.getSelectedIndices(); - if (indicies.length > 0) { - ListModel listModel = getListModel(); - OMEvent selectedEvent = listModel.getElementAt(indicies[0]); - - lastSelectedEvent = selectedEvent; - - if (selectedEvent != null) { - if (clock != null) { - clock.setTime((long) selectedEvent.getTimeStamp()); - Point2D location = selectedEvent.getLocation(); - if (location != null && map != null) { - map.setCenter(location); - } - } - - String details = selectedEvent.getDetailedInformation(); - if (details != null) { - showDetails(details); - } else { - hideDetails(); - } - } - - for (Iterator it = getAllEvents(); it.hasNext();) { - ((OMEvent) it.next()).putAttribute(OMEvent.ATT_KEY_SELECTED, null); - } - - Vector v = new Vector(); - OMEvent firstInRangeEvent = null; - OMEvent lastSelectedEvent = null; - int lastIndex = -2; - boolean inRange = false; - - for (int i = 0; i < indicies.length; i++) { - int curIndex = indicies[i]; - selectedEvent = (OMEvent) listModel.getElementAt(curIndex); - - selectedEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED); - - if (curIndex == lastIndex + 1) { - inRange = true; - if (firstInRangeEvent == null) { - firstInRangeEvent = lastSelectedEvent; - firstInRangeEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, - OMEvent.ATT_VAL_SELECTED_START_RANGE); - } - } else if (inRange && lastSelectedEvent != null) { - lastSelectedEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED_END_RANGE); - inRange = false; - } - - v.add(selectedEvent); - // forward the call back to the thing that provided - // the event, so it knows that the event was selected - // if it cares. - Object src = selectedEvent.getSource(); - if (src instanceof OMEventSelectionListener) { - ((OMEventSelectionListener) src).selected(selectedEvent); - } - - lastSelectedEvent = selectedEvent; - lastIndex = curIndex; - } - - if (inRange && lastSelectedEvent != null) { - lastSelectedEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED_END_RANGE); - } - - if (aesc != null) { - aesc.eventsSelected(v); - } - } - } - } - - public boolean selectEvent(OMEvent event) { - boolean ret = false; - if (displayList != null) { - displayList.setSelectedValue(event, true); - - String details = event.getDetailedInformation(); - if (details != null) { - showDetails(details); - } else { - hideDetails(); - } - - ret = true; - } - - return ret; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof OMEventHandler) { - addEventHandler((OMEventHandler) someObj); - } - - if (someObj instanceof Clock) { - setClock((Clock) someObj); - } - - if (someObj instanceof MapBean) { - setMap((MapBean) someObj); - } - - if (someObj instanceof FilterPresenter && someObj != this) { - FilterPresenter filterPresenter = (FilterPresenter) someObj; - macroFilters.add(filterPresenter); - filterPresenter.addPropertyChangeListener(this); - } - - if (someObj instanceof EventPanel) { - parentPanel = (EventPanel) someObj; - } - - if (someObj instanceof OMEventSelectionCoordinator && aesc == null) { - aesc = (OMEventSelectionCoordinator) someObj; - aesc.addPropertyChangeListener(this); - } - - if (someObj instanceof TimePanel) { - ((TimePanel) someObj).setPlayFilterVisible(getEventCellRenderer().getIconPackage().isShowPlayFilter()); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof OMEventHandler) { - removeEventHandler((OMEventHandler) someObj); - } - - if (someObj == getClock()) { - setClock(null); - } - - if (someObj instanceof MapBean) { - setMap((MapBean) null); - } - - if (someObj instanceof FilterPresenter && someObj != this) { - FilterPresenter filterPresenter = (FilterPresenter) someObj; - macroFilters.remove(filterPresenter); - filterPresenter.removePropertyChangeListener(this); - } - - if (someObj == parentPanel) { - parentPanel = null; - } - - if (someObj == aesc) { - aesc.removePropertyChangeListener(this); - aesc = null; - } - } - - public void setClock(Clock cl) { - if (clock != null) { - clock.removeTimeEventListener(this); - clock.removeTimeBoundsListener(this); - } - clock = cl; - - if (clock != null) { - clock.addTimeEventListener(this); - clock.addTimeBoundsListener(this); - } - } - - public Clock getClock() { - return clock; - } - - public void setMap(MapBean map) { - this.map = map; - } - - public MapBean getMap() { - return map; - } - - /** - * @return Returns the displayTimeWindow. - */ - public long getDisplayTimeWindow() { - return displayTimeWindow; - } - - /** - * @param displayTimeWindow The displayTimeWindow to set. - */ - public void setDisplayTimeWindow(long displayTimeWindow) { - this.displayTimeWindow = displayTimeWindow; - } - - public void updateTimeBounds(TimeBoundsEvent tbe) { - // This section used to be called when the Clock.TIME_BOUNDS_PROPERTY - // was sent. - allEvents = null; - - if (displayList != null) { - displayList.repaint(); - } - // ///// - - // This part got called when a TimeBoundsProvider was activated or - // deactivated. - - // This gets called when the events change! Need to tell the - // timelines to recharge... - lastSelectedEvent = null; - // Resets active and all event lists. - rebuildEventList(); - firePropertyChange(EventAttributesUpdatedProperty, null, Boolean.TRUE); - // /////////// - } - - public void updateTime(TimeEvent te) { - highlightCurrentEvent(te.getSystemTime()); - - if (displayList != null) { - displayList.repaint(); - } - } - - /* - * (non-Javadoc) - * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - @SuppressWarnings("unchecked") - public void propertyChange(PropertyChangeEvent evt) { - String eventPropertyName = evt.getPropertyName(); - - if (eventPropertyName == FilterPresenter.FILTER_STATE) { - boolean rebuildFilters = ((Boolean) evt.getNewValue()).booleanValue(); - - if (rebuildFilters) { - logger.fine(eventPropertyName + " rebuilding filters and updating interface (list rebuild to follow)"); - retrieveFiltersFromEventHandlers(); - updateInterface(); - } else { - logger.fine(eventPropertyName + " clearing active filters and rebuilding list"); - activeFilters = null; - rebuildEventList(); - } - } - - if (eventPropertyName == OMEventSelectionCoordinator.EventsSelectedProperty) { - Object someObj = evt.getNewValue(); - if (someObj instanceof List) { - scrollToSelected((List) evt.getNewValue()); - displayList.repaint(); - } - } - - } - - protected void scrollToSelected(List selectedEvents) { - if (selectedEvents != null && !selectedEvents.isEmpty()) { - OMEvent event = selectedEvents.get(0); - lastSelectedEvent = event; - // need to check timestamps because the first selected event might - // not be visible, so if we come across a dlm timestamp that's - // greater than this one, that should be the first selected event. - long timeStamp = event.getTimeStamp(); - - OMEvent dlmEvent = null; - ListModel dlm = getListModel(); - int fvi = displayList.getFirstVisibleIndex(); - int lvi = displayList.getLastVisibleIndex(); - int numRowsVisible = lvi - fvi; - int size = dlm.getSize(); - for (int i = 0; i < size; i++) { - dlmEvent = dlm.getElementAt(i); - if (dlmEvent == event || dlmEvent.getTimeStamp() > timeStamp) { - - if (i < fvi || i > lvi - 1) { - fvi = i; - - if (size - i > numRowsVisible) { - lvi = i + numRowsVisible - 1; - } else { - lvi = size; - } - Rectangle rect = displayList.getCellBounds(fvi, lvi); - if (rect != null) { - displayList.scrollRectToVisible(rect); - } - } - break; - } - } - } - - } - - protected long currentTime; - - /** - * @param newCurrentTime the time to use for selecting current event. - */ - protected synchronized void highlightCurrentEvent(long newCurrentTime) { - currentTime = newCurrentTime; - - if (displayList == null) - return; - - ListModel dlm = displayList.getModel(); - boolean timeMarked = false; - OMEvent lastClosest = null; - int size = dlm.getSize(); - for (int i = 0; i < size; i++) { - OMEvent event = dlm.getElementAt(i); - long timeStamp = event.getTimeStamp(); - - boolean atCurrentTime = (Math.abs(timeStamp - currentTime) <= displayTimeWindow); - event.setAtCurrentTime(atCurrentTime); - // This work is done to mark the closest, but not over, - // event marking where the time is. - timeMarked = atCurrentTime || timeMarked; - if (!timeMarked) { - if (timeStamp < currentTime) { - lastClosest = event; - } else if (lastClosest != null) { - lastClosest.setAtCurrentTime(true); - timeMarked = true; - } - } - } - } - - public void mouseClicked(MouseEvent e) { - // hideDetails(); - // - // if (e.getButton() == MouseEvent.BUTTON3 && displayList != null) { - // // Right click - // int index = getDisplayListIndex(e); - // lastIndexOfCellDetail = index; - // ListModel model = displayList.getModel(); - // Object obj = model.getElementAt(index); - // - // String labelContents = null; - // - // if (obj instanceof OMEvent) { - // OMEvent ae = (OMEvent) obj; - // labelContents = ae.getDetailedInformation(); - // } - // - // if (labelContents == null) { - // labelContents = " No further information available. "; - // } - // - // showDetails(labelContents); - // } - - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseDragged(MouseEvent e) { - } - - public void mouseMoved(MouseEvent e) { - // if (lastIndexOfCellDetail != -1 - // && lastIndexOfCellDetail != getDisplayListIndex(e)) { - // hideDetails(); - // } - } - - protected int lastIndexOfCellDetail = -1; - - public void showDetails(String contents) { - - if (contents != null) { - detailSpace.setText(" " + contents + ""); - } - - detailSpacePanel.setVisible(contents != null); - } - - public void hideDetails() { - if (detailSpacePanel != null) { - detailSpacePanel.setVisible(false); - } - - lastIndexOfCellDetail = -1; - } - - protected int getDisplayListIndex(MouseEvent e) { - int index = 0; - - if (displayList != null) { - double height = getDisplayListCellHeight(); - - index = e.getY() / (int) height; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("For " + e.getY() + ", the first vis: " + displayList.getFirstVisibleIndex() - + ", heights are " + height + ", so index of click is " + index); - } - } - - return index; - } - - protected double getDisplayListCellHeight() { - double height = 0; - if (displayList != null) { - int rlFVI = displayList.getFirstVisibleIndex(); - Rectangle bounds = displayList.getCellBounds(rlFVI, rlFVI); - - height = bounds.getHeight(); - } - return height; - } - - JPanel eventControlPanel = null; - - protected JComponent getEventControlPanel() { - if (eventControlPanel == null) { - eventControlPanel = cellRenderer.getIconPackage().createEventControlPanel(this); - } - - JToolBar jsp = new JToolBar(); - jsp.add(eventControlPanel); - jsp.setFloatable(false); - jsp.setBorder(BorderFactory.createEmptyBorder()); - - // return eventControlPanel; - return jsp; - } - - public void setSelectedEventsAttribute(Object key, Object value) { - for (Iterator it = getActiveEvents(); it.hasNext();) { - OMEvent OMe = it.next(); - - if (OMe.getAttribute(OMEvent.ATT_KEY_SELECTED) != null) { - OMe.putAttribute(key, value); - } - } - - resolveSelectionForHiddenEvents(key, value); - - firePropertyChange(EventAttributesUpdatedProperty, null, Boolean.TRUE); - - displayList.repaint(); - } - - public void resolveSelectionForHiddenEvents(Object key, Object value) { - - boolean inRange = false; - for (Iterator iIt = getAllEvents(); iIt.hasNext();) { - OMEvent iEvent = (OMEvent) iIt.next(); - - if (iEvent.getAttribute(OMEvent.ATT_KEY_SELECTED) == OMEvent.ATT_VAL_SELECTED_START_RANGE) { - inRange = true; - } else if (iEvent.getAttribute(OMEvent.ATT_KEY_SELECTED) == OMEvent.ATT_VAL_SELECTED_END_RANGE) { - inRange = false; - } else if (inRange) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("setting " + iEvent.getClass().getName() + " " + key + ", " + value); - } - - iEvent.putAttribute(key, value); - } - } - } - - public void setAllEventsAttribute(Object key, Object value) { - for (Iterator it = getActiveEvents(); it.hasNext();) { - ((OMEvent) it.next()).putAttribute(key, value); - } - displayList.repaint(); - } - - public static void main(String[] argv) { - javax.swing.JFrame frame = new javax.swing.JFrame("EventListPresenter"); - EventListPresenter elp = new EventListPresenter(); - frame.add(elp); - frame.pack(); - frame.setVisible(true); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/EventPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/event/EventPanel.java deleted file mode 100644 index eab2d3186..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/EventPanel.java +++ /dev/null @@ -1,367 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/aar/src/com/bbn/ambush/gui/EventPanel.java,v $ -// $RCSfile: EventPanel.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:20 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.MapPanelChild; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.gui.OpenMapFrame; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.util.PropUtils; - -/** - * The EventPanel holds EventPresenters, which are components that will display - * events. Also contains a GUI framework for holding filtering controls, but - * that part hasn't been worked out yet. Finds EventPresenters in the - * MapHandler. If you add EventPresenters programmatically, make sure the - * EventPresenter has access to all of the other components it needs, too. - * - *
- * eventPanel.class=com.bbn.openmap.gui.event.EventPanel
- * eventPanel.parent=hotwashPanel
- * 
- * - * @author dietrick - */ -public class EventPanel extends OMComponentPanel implements MapPanelChild { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.event.EventPanel"); - - public final static String SHOW_ALL_EVENTS_STRING = " Show All Events "; - public final static String HIDE_ALL_EVENTS_STRING = " Hide All Events "; - public final static String SET_FILTERS_STRING = " Filter Events... "; - public final static String NO_EVENTS_STRING = "No Events"; - - protected List eventPresenters; - protected List macroFilters; - protected String preferredLocation = BorderLayout.WEST; - protected JPanel filterPanel; - protected Hashtable eventPresenterComponentLookup; - // Used to intellegently determine if filter callup buttons should - // be displayed. - protected boolean hasFilters = false; - protected String parentName; - - public EventPanel() { - setLayout(new BorderLayout()); - setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - " Events ")); - eventPresenters = new LinkedList(); - macroFilters = new LinkedList(); - eventPresenterComponentLookup = new Hashtable(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - parentName = props.getProperty(prefix - + MapPanelChild.ParentNameProperty); - } - - public void addEventPresenter(EventPresenter ep) { - logger.fine("adding " + ep.getClass().getName()); - eventPresenters.add(ep); - initInterface(); - } - - public void removeEventPresenter(EventPresenter ep) { - eventPresenters.remove(ep); - initInterface(); - } - - public void clearEventPresenters() { - eventPresenters.clear(); - eventPresenterComponentLookup.clear(); - initInterface(); - } - - public void addMacroFilter(MacroFilter mf) { - macroFilters.add(mf); - initInterface(); - } - - public void removeMacroFilter(MacroFilter mf) { - macroFilters.remove(mf); - initInterface(); - } - - public void clearMacroFilters() { - macroFilters.clear(); - initInterface(); - } - - /** - * Initialize the panel interface, showing the buttons for calling up the - * filter panel and the event presenter lists in a tabbed pane (if there is - * more than one, otherwise, just shows the component from that - * EventPresenter). - */ - public void initInterface() { - logger.fine("rebuilding interface"); - removeAll(); - - int numPresenters = eventPresenters.size(); - hasFilters = false; - EventPresenter eventPresenter = null; - Component presenterComponent = null; - - if (numPresenters == 1) { - eventPresenter = (EventPresenter) eventPresenters.get(0); - presenterComponent = eventPresenter.getComponent(); - add(presenterComponent, BorderLayout.CENTER); - eventPresenterComponentLookup.put(presenterComponent, - eventPresenter); - hasFilters = hasFilters - || (eventPresenter.getFilters() != null && - !eventPresenter.getFilters().isEmpty()); - setActiveEventPresenter(eventPresenter); - } else if (numPresenters > 1) { - - JTabbedPane jtb = new JTabbedPane(); - jtb.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JTabbedPane jtb = (JTabbedPane) ce.getSource(); - // Find out which EventPresenter panel is active, - // and set that interface in the filter window. - setActiveEventPresenter(eventPresenterComponentLookup.get(jtb.getSelectedComponent())); - } - }); - for (Iterator it = eventPresenters.iterator(); it.hasNext();) { - eventPresenter = it.next(); - String name = eventPresenter.getName(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("\tEventPanel: adding presenter (" + name - + ") to tabbed pane"); - } - presenterComponent = eventPresenter.getComponent(); - jtb.addTab(name, presenterComponent); - eventPresenterComponentLookup.put(presenterComponent, - eventPresenter); - hasFilters = hasFilters - || (eventPresenter.getFilters() != null && - !eventPresenter.getFilters().isEmpty()); - } - add(jtb, BorderLayout.CENTER); - } - - // Uses hasFilters - updateFilterCalloutInterface(); - updateMacroFilterInterface(); - - revalidate(); - - logger.fine("--- EventPanel: Done"); - - } - - protected JPanel launchFilterPanel = null; - protected JPanel macroPanel = null; - - /** - * - */ - protected void updateFilterCalloutInterface() { - if (launchFilterPanel == null) { - launchFilterPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.insets = new Insets(0, 2, 4, 2); - launchFilterPanel.setLayout(gridbag); - JButton launchFilterButton = new JButton(EventPanel.SET_FILTERS_STRING); - launchFilterButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - showFilterInterface(); - } - }); - - JButton clearFilterButton = new JButton(EventPanel.SHOW_ALL_EVENTS_STRING); - clearFilterButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - resetFilters(Boolean.TRUE); - } - }); - gridbag.setConstraints(clearFilterButton, c); - gridbag.setConstraints(launchFilterButton, c); - - launchFilterPanel.add(clearFilterButton); - launchFilterPanel.add(launchFilterButton); - } - - add(launchFilterPanel, BorderLayout.NORTH); - launchFilterPanel.setVisible(hasFilters); - } - - public void updateMacroFilterInterface() { - - if (macroPanel == null) { - macroPanel = new JPanel(); - } - - macroPanel.removeAll(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - macroPanel.setLayout(gridbag); - - c.insets = new Insets(10, 10, 0, 10); - c.gridwidth = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1; - for (Iterator it = macroFilters.iterator(); it.hasNext();) { - MacroFilter fp = it.next(); - JPanel fpp = fp.getFilterPanel(); - fpp.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY), - fp.getName())); - gridbag.setConstraints(fpp, c); - macroPanel.add(fpp); - } - - getFilterPanel().add(macroPanel, BorderLayout.NORTH); - macroPanel.setVisible(!macroFilters.isEmpty()); - getFilterPanel().revalidate(); - - } - - /** - * Sets all the filters to be off (true, enabling events of those types - * contained in each EventPresenter) or on. - * - * @param true1 Boolean.TRUE for all events shown, Boolean.FALSE for all - * events hidden. - */ - protected void resetFilters(Boolean true1) { - for (Iterator it = eventPresenters.iterator(); it.hasNext();) { - it.next().resetFilters(true1); - } - } - - /** - * Sets the EventPresenter as the active on, which also sets its filter - * panel in the overall filter panel. - * - * @param eventPresenter - */ - protected void setActiveEventPresenter(EventPresenter eventPresenter) { - JPanel filterPanel = getFilterPanel(); - filterPanel.add(eventPresenter.getFilterPanel(), BorderLayout.CENTER); - filterPanel.revalidate(); - } - - /** - * Displays the filter panel in the frame window. - */ - protected void showFilterInterface() { - if (windowSupport != null) { - windowSupport.killWindow(); - } - - MapHandler beanContext = (MapHandler) getBeanContext(); - OpenMapFrame frame = (OpenMapFrame) beanContext.get(com.bbn.openmap.gui.OpenMapFrame.class); - - windowSupport = new WindowSupport(getFilterPanel(), new WindowSupport.Dlg(frame, i18n.get(EventPanel.class, - "title", - "Event Filters"))); - windowSupport.displayInWindow(); - } - - /** - * This filter panel is the overall filter panel that is in the frame. It - * houses the macro filter interface common to all EventPresenters, and the - * filter panel of the active EventPresenter. - * - * @return JPanel containing filter controls - */ - protected JPanel getFilterPanel() { - if (filterPanel == null) { - filterPanel = new JPanel(); - filterPanel.setLayout(new BorderLayout()); - } - return filterPanel; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof EventPresenter) { - addEventPresenter((EventPresenter) someObj); - } - - if (someObj instanceof MacroFilter) { - addMacroFilter((MacroFilter) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof EventPresenter) { - removeEventPresenter((EventPresenter) someObj); - } - - if (someObj instanceof MacroFilter) { - removeMacroFilter((MacroFilter) someObj); - } - } - - public void setPreferredLocation(String loc) { - preferredLocation = loc; - } - - public String getPreferredLocation() { - return preferredLocation; - } - - public String getParentName() { - return parentName; - } - - public void setParentName(String pName) { - parentName = pName; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/EventPresenter.java b/src/core/src/main/java/com/bbn/openmap/gui/event/EventPresenter.java deleted file mode 100644 index 32a6041b3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/EventPresenter.java +++ /dev/null @@ -1,77 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/darwars/ambush/aar/src/com/bbn/hotwash/gui/EventPresenter.java,v $ -// $RCSfile: EventPresenter.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/08/16 22:15:20 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.awt.Component; -import java.util.Iterator; - -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * An EventPresenter is a empty interface that marks a component to be picked up - * by the EventPanel. - */ -public interface EventPresenter extends FilterPresenter { - - /** - * A property string to use for PropertyChangeListeners listening for when - * the presenter's contents have changed, either due to filtering or the - * availability of new EventHandlers. - */ - public final static String ActiveEventsProperty = "activeEvents"; - /** - * A property string to use for PropertyChangeListeners interested in - * knowing what events are currently selected by the user. - */ - public final static String SelectedEventsProperty = "selectedEvents"; - /** - * A property string used when event attributes (ratings, play filter - * settings) have been changed. - */ - public final static String EventAttributesUpdatedProperty = "eventAttributesUpdated"; - - /** - * @return the main event display. - */ - Component getComponent(); - - /** - * Return a list of active events. - */ - Iterator getActiveEvents(); - - /** - * Return a list of all events. - */ - Iterator getAllEvents(); - - /** - * Return a set of drawing attributes that match what the presenter is using - * for selection; - * - * @return DrawingAttributes containing rendering info for selected items. - */ - DrawingAttributes getSelectionDrawingAttributes(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/FilterPresenter.java b/src/core/src/main/java/com/bbn/openmap/gui/event/FilterPresenter.java deleted file mode 100644 index fccddbaaa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/FilterPresenter.java +++ /dev/null @@ -1,71 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: FilterPresenter.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:20 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.beans.PropertyChangeListener; -import java.util.List; -import java.util.Map; - -import javax.swing.JPanel; - -/** - * @author dietrick - */ -public interface FilterPresenter { - - public final static String FILTER_STATE = "FILTER_STATE"; - - /** - * @return the pretty name for the presenter, for the GUI. - */ - public String getName(); - - /** - * @return the JPanel containing filter controls for this display. - */ - public JPanel getFilterPanel(); - - /** - * @return a Map of filters that can be used for this - * display. The keys are the Strings for the filters, the - * values are Booleans indicating whether events of the - * key type are on or off. - */ - public Map getFilters(); - - /** - * @return the list of strings for things that should be shown. - */ - public List getActiveFilters(); - - /** - * Master control for turning all filters on or off. - */ - public void resetFilters(Boolean on_off); - - public void addPropertyChangeListener(PropertyChangeListener pcl); - - public void removePropertyChangeListener(PropertyChangeListener pcl); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/event/MacroFilter.java b/src/core/src/main/java/com/bbn/openmap/gui/event/MacroFilter.java deleted file mode 100644 index 627481f52..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/event/MacroFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MacroFilter.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:20 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.event; - -import java.util.List; - -import com.bbn.openmap.event.OMEvent; - -/** - * A Macro filter knows how to take a Collection of objects and return a list of - * them that pass its filters. - * - * @author dietrick - */ -public interface MacroFilter extends FilterPresenter { - public List getMacroFilteredList(List listOfEvents); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/AboutMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/AboutMenuItem.java deleted file mode 100644 index 447f8f2a8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/AboutMenuItem.java +++ /dev/null @@ -1,106 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/AboutMenuItem.java,v $ -// $RCSfile: AboutMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JMenuItem; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; - -/** - * This object brings up OpenMap about information. - */ -public class AboutMenuItem extends JMenuItem implements ActionListener { - - protected JDialog aboutBox = null; - - public AboutMenuItem() { - super("About"); - setMnemonic('t'); - addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - if (aboutBox == null) { - aboutBox = createAboutBox(); - aboutBox.getContentPane().setLayout(new BorderLayout()); - aboutBox.getContentPane().add(createCopyrightViewer(), - BorderLayout.CENTER); - aboutBox.getContentPane().add(createAboutControls(aboutBox), - BorderLayout.SOUTH); - aboutBox.pack(); - } - - aboutBox.setVisible(true); - } - - protected JComponent createCopyrightViewer() { - StringBuffer sb = new StringBuffer(MapBean.getCopyrightMessage()); - - String buildDate = Environment.get(Environment.BuildDate); - if (buildDate != null) { - sb.append(Environment.get("line.separator")).append("Build ").append(buildDate); - } - - JTextArea viewer = new JTextArea(sb.toString()); - viewer.setEditable(false); - JScrollPane scroller = new JScrollPane(viewer); - return scroller; - } - - protected Component createAboutControls(final JDialog window) { - JButton button = new JButton("OK"); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - window.setVisible(false); - } - }); - Box box = Box.createHorizontalBox(); - box.add(button); - return box; - } - - protected JDialog createAboutBox() { - java.awt.Container topContainer = getTopLevelAncestor(); - String title = "About " + Environment.get(Environment.Title); - if (topContainer instanceof Frame) { - return new JDialog((Frame) topContainer, title, true); - } else { - JDialog d = new JDialog(); - d.setTitle(title); - return d; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/BackgroundColorMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/BackgroundColorMenuItem.java deleted file mode 100644 index 5d4f4ee7b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/BackgroundColorMenuItem.java +++ /dev/null @@ -1,88 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/BackgroundColorMenuItem.java,v -// $ -// $RCSfile: BackgroundColorMenuItem.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.omGraphics.OMColorChooser; - -public class BackgroundColorMenuItem extends JMenuItem implements - ActionListener, LightMapHandlerChild { - - private static final long serialVersionUID = 1L; - protected MapBean map = null; - - public BackgroundColorMenuItem() { - this("Set Map Background Color"); - } - - public BackgroundColorMenuItem(String title) { - super(title); - addActionListener(this); - } - - public void setMap(MapBean mapbean) { - map = mapbean; - } - - public MapBean getMap() { - return map; - } - - public void actionPerformed(ActionEvent ae) { - if (map != null) { - Paint newPaint = OMColorChooser.showDialog(this, - getText(), - map.getBackground()); - if (newPaint != null) { - - String colorString = Integer.toString(((java.awt.Color) newPaint).getRGB()); - Environment.set(Environment.BackgroundColor, colorString); - map.setBackground((java.awt.Color) newPaint); - map.setBckgrnd(newPaint); - } - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setMap((MapBean) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - setMap(null); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/ControlPanelToggleMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/ControlPanelToggleMenuItem.java deleted file mode 100644 index a81b3ac2e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/ControlPanelToggleMenuItem.java +++ /dev/null @@ -1,94 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/ControlPanelToggleMenuItem.java,v $ -// $RCSfile: ControlPanelToggleMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.gui.OMControlPanel; - -/** - * Menu item that holds onto the OMControlPanel, and hides/displays it - * when selected. - */ -public class ControlPanelToggleMenuItem extends JMenuItem implements - ActionListener, LightMapHandlerChild { - - protected OMControlPanel controlPanel = null; - protected final static String hideLabel = "Hide Control Panel"; - protected final static String displayLabel = "Display Control Panel"; - - public ControlPanelToggleMenuItem() { - // assume that the control panel isn't there. - // Won't be visible if it isn't. - super(hideLabel); - init(null); - } - - public ControlPanelToggleMenuItem(OMControlPanel cp) { - super(cp.isVisible() ? hideLabel : displayLabel); - init(cp); - } - - public void init(OMControlPanel cp) { - setControlPanel(cp); - addActionListener(this); - } - - public void setControlPanel(OMControlPanel cp) { - controlPanel = cp; - this.setVisible(controlPanel != null); - } - - public OMControlPanel getControlPanel() { - return controlPanel; - } - - public boolean forControlPanel(OMControlPanel cp) { - return (cp == controlPanel); - } - - public void actionPerformed(ActionEvent ae) { - if (controlPanel != null) { - boolean selected = controlPanel.isVisible(); - controlPanel.setVisible(!selected); - setText(selected ? displayLabel : hideLabel); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof OMControlPanel) { - setControlPanel((OMControlPanel) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof OMControlPanel - && getControlPanel() == (OMControlPanel) someObj) { - setControlPanel(null); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/CoordsMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/CoordsMenuItem.java deleted file mode 100644 index 2969167f6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/CoordsMenuItem.java +++ /dev/null @@ -1,91 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/CoordsMenuItem.java,v $ -// $RCSfile: CoordsMenuItem.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/02/02 13:13:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.CombinedCoordPanel; -import com.bbn.openmap.gui.ScrollPaneWindowSupport; -import com.bbn.openmap.gui.WindowSupport; - -/** - * A menu item that will bring up a frame with a CombinedCoordPanel, - * showing different coordinate panels in a tabbed pane. This menu - * item forwards all objects received from the MapHandler to the - * CombinedCoordPanel. - */ -public class CoordsMenuItem extends MapHandlerMenuItem implements - ActionListener { - /** - * The WindowSupport for the CombinedCoordPanel. - */ - protected WindowSupport ws; - /** - * The coordinate content. - */ - protected CombinedCoordPanel ccp; - - public CoordsMenuItem() { - super("Coordinates..."); - this.setText(i18n.get(CoordsMenuItem.class, "name", "Coordinates...")); - addActionListener(this); - ccp = new CombinedCoordPanel(this); - } - - public void actionPerformed(ActionEvent ae) { - if (ae.getActionCommand() == CombinedCoordPanel.CloseCmd && ws != null) { - ws.killWindow(); - } else { - if (ws == null) { - ws = new ScrollPaneWindowSupport(ccp, i18n.get(CoordsMenuItem.class, - "combinedCoordDialog.title", - "Go To Coordinates...")); - } - - MapHandler mh = getMapHandler(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - ws.displayInWindow(frame); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapHandler) { - setMapHandler((MapHandler) someObj); - } - ccp.findAndInit(someObj); - } - - public void findAndUndo(Object someObj) { - if (someObj == getMapHandler()) { - setMapHandler(null); - } - ccp.findAndUndo(someObj); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/DataBoundsViewMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/DataBoundsViewMenuItem.java deleted file mode 100644 index 84553a557..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/DataBoundsViewMenuItem.java +++ /dev/null @@ -1,125 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/DataBoundsViewMenuItem.java,v -// $ -// $RCSfile: DataBoundsViewMenuItem.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.Debug; - -public class DataBoundsViewMenuItem extends MapHandlerMenuItem implements - ActionListener { - - protected MapBean map; - protected InformationDelegator infoDelegator; - protected DataBoundsProvider provider; - - public DataBoundsViewMenuItem(DataBoundsProvider dbp) { - super(dbp.getName()); - provider = dbp; - addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - if (map != null) { - Proj proj = (Proj) map.getProjection(); - DataBounds bounds = provider.getDataBounds(); - - if (bounds != null) { - java.awt.geom.Point2D center = bounds.getCenter(); - if (center != null) { - proj.setCenter(center.getY(), center.getX()); - LatLonPoint llp1 = new LatLonPoint.Double(bounds.getMax().getY(), bounds.getMin() - .getX()); - - LatLonPoint llp2 = new LatLonPoint.Double(bounds.getMin().getY(), bounds.getMax() - .getX()); - - float scale = ProjMath.getScale(llp1, llp2, proj); - proj.setScale(scale); - java.awt.geom.Point2D ul = proj.getUpperLeft(); - java.awt.geom.Point2D lr = proj.getLowerRight(); - double factor1 = (bounds.getMax().getY() - bounds.getMin().getY()) - / (ul.getY() - lr.getY()); - double factor2 = (bounds.getMax().getX() - bounds.getMin().getX()) - / (lr.getX() - ul.getX()); - - // 1.1 buffers the edges for viewing a little, a - // little zoomed out. - scale *= Math.max(factor1, factor2); - proj.setScale(scale * 1.1f); - map.setProjection(proj); - } - } else { - String complaint = "Can't move map over data: " - + provider.getName() + " isn't ready. Add to map?"; - if (infoDelegator != null) { - infoDelegator.displayMessage("Go Over Data", complaint); - } else { - Debug.error(complaint); - } - } - } - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof MapHandler) { - // Check to see if the MapBean is already available. - map = (MapBean) mapHandler.get("com.bbn.openmap.MapBean"); - infoDelegator = (InformationDelegator) mapHandler.get("com.bbn.openmap.InformationDelegator"); - } - - if (someObj instanceof MapBean) { - map = (MapBean) someObj; - } - - if (someObj instanceof InformationDelegator) { - infoDelegator = (InformationDelegator) someObj; - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - - if (someObj instanceof MapBean && map == someObj) { - map = null; - } - - if (someObj instanceof InformationDelegator && infoDelegator == someObj) { - - infoDelegator = null; - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/I18nFileCreateMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/I18nFileCreateMenuItem.java deleted file mode 100644 index 7e898939c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/I18nFileCreateMenuItem.java +++ /dev/null @@ -1,95 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: I18nFileCreateMenuItem.java,v $ -//$Revision: 1.1 $ -//$Date: 2005/02/11 22:30:29 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.BasicI18n; -import com.bbn.openmap.util.I18n; - -public class I18nFileCreateMenuItem extends JMenuItem implements ActionListener { - - /** - * - */ - public I18nFileCreateMenuItem() { - super("Create I18N Resource Files..."); - addActionListener(this); - } - - /** - * @param icon - */ - public I18nFileCreateMenuItem(Icon icon) { - super(icon); - } - - /** - * @param text - */ - public I18nFileCreateMenuItem(String text) { - super(text); - } - - /** - * @param a - */ - public I18nFileCreateMenuItem(Action a) { - super(a); - } - - /** - * @param text - * @param icon - */ - public I18nFileCreateMenuItem(String text, Icon icon) { - super(text, icon); - } - - /** - * @param text - * @param mnemonic - */ - public I18nFileCreateMenuItem(String text, int mnemonic) { - super(text, mnemonic); - } - - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - I18n i18n = Environment.getI18n(); - if (i18n instanceof BasicI18n) { - ((BasicI18n)i18n).dumpCreatedResourceBundles(); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/LoadPropertiesMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/LoadPropertiesMenuItem.java deleted file mode 100644 index a54f601b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/LoadPropertiesMenuItem.java +++ /dev/null @@ -1,126 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/LoadPropertiesMenuItem.java,v $ -// $RCSfile: LoadPropertiesMenuItem.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/02/27 15:11:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Iterator; -import java.util.Properties; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.util.Debug; - -/** - * This is a menu item that loads a file. This file should be a valid - * openmap properties file, with openmap.layers set and projection - * properties set. The components list is ignored, since it is pretty - * dependent on order, and it's hard to write a good properties file - * automatically with a valid components list. - *

- * If you want to change the components in an application, launch - * OpenMap with the properties file you want. - */ -public class LoadPropertiesMenuItem extends MapHandlerMenuItem implements - ActionListener { - - public LoadPropertiesMenuItem() { - super("Load Map Properties"); - addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - //Collect properties - if (mapHandler == null) { - return; - } - - PropertyHandler ph = null; - Iterator it = mapHandler.iterator(); - while (it.hasNext()) { - Object someObj = it.next(); - if (someObj instanceof PropertyHandler) { - ph = (PropertyHandler) someObj; - break; - } - } - - if (ph == null) { - Debug.error("Couldn't find PropertyHandler"); - return; - } - - FileDialog fd = new FileDialog(new Frame(), "Loading the map from a Properties file...", FileDialog.LOAD); - fd.setVisible(true); - - String fileName = fd.getFile(); - String dirName = fd.getDirectory(); - - if (fileName == null) { - Debug.message("loadpropertiesmenuitem", - "User did not select any file"); - return; - } - - Debug.message("loadpropertiesmenuitem", "User selected file " + dirName - + File.separator + fileName); - - File file = new File(new File(dirName), fileName); - - try { - Properties newProps = new Properties(); - FileInputStream fis = new FileInputStream(file); - - newProps.load(fis); - - String test = newProps.getProperty("openmap." - + LayerHandler.layersProperty); - if (test == null) { - throw new IOException("Doesn't seem like a valid properties file"); - } - - // Just reset the projection and layers, not the - // components. - ph.loadProjectionAndLayers(mapHandler, newProps); - - } catch (FileNotFoundException fnfe) { - Debug.error(fnfe.getMessage()); - } catch (IOException ioe) { - InformationDelegator id = (InformationDelegator) mapHandler.get("com.bbn.openmap.InformationDelegator"); - - if (id != null) { - id.displayMessage("Error loading file...", - "Error occurred loading " + file.getAbsolutePath() - + "\n" + ioe.getMessage()); - } - Debug.error("Error occurred loading " + file.getAbsolutePath()); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/MapBeanPrinterMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/MapBeanPrinterMenuItem.java deleted file mode 100644 index 64ba5ad4c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/MapBeanPrinterMenuItem.java +++ /dev/null @@ -1,81 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/MapBeanPrinterMenuItem.java,v $ -// $RCSfile: MapBeanPrinterMenuItem.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.image.MapBeanPrinter; - -/** - * A MapBeanPrinterMenuItem is a MapHandlerMenuItem that looks for the - * MapBean in the MapHandler and prints it when it is called. - */ -public class MapBeanPrinterMenuItem extends MapHandlerMenuItem implements - ActionListener { - - protected MapBean mapBean = null; - - public MapBeanPrinterMenuItem(String title) { - super(title); - addActionListener(this); - setEnabled(false); - } - - public MapBeanPrinterMenuItem() { - super("Print"); - addActionListener(this); - setEnabled(false); - } - - public void setMapBean(MapBean mb) { - setEnabled(mb != null); - mapBean = mb; - } - - public MapBean getMapBean() { - return mapBean; - } - - public void actionPerformed(ActionEvent ae) { - MapBean mb = getMapBean(); - if (mb != null) { - MapBeanPrinter.printMap(mb); - } - } - - public void findAndInit(Object obj) { - super.findAndInit(obj); - if (obj instanceof MapBean) { - setMapBean((MapBean) obj); - } - } - - public void findAndUndo(Object obj) { - super.findAndUndo(obj); - if (obj instanceof MapBean && obj == getMapBean()) { - setMapBean(null); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/MapHandlerMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/MapHandlerMenuItem.java deleted file mode 100644 index 2091336e6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/MapHandlerMenuItem.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/MapHandlerMenuItem.java,v $ -// $RCSfile: MapHandlerMenuItem.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/02/02 13:13:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.beans.beancontext.BeanContext; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.util.I18n; - -/** - * A MapHandlerMenuItem is a JMenuItem that uses the MapHandler to - * find objects it needs to operate. It's a LightMapHandlerChild so - * that it's parent AbstractOpenMapMenu will provide the MapHandler - * and other MapHandler objects to it. The MapHandlerMenuItem doesn't - * really need to be added to the MapHandler unless something else - * needs to find it from the MapHandler. Instead, it will see - * everything else in the MapHandler. - */ -public abstract class MapHandlerMenuItem extends JMenuItem implements - LightMapHandlerChild { - - protected MapHandler mapHandler = null; - - protected I18n i18n = Environment.getI18n(); - - public MapHandlerMenuItem(String title) { - super(title); - } - - public void setMapHandler(BeanContext in_mapHandler) { - if (in_mapHandler instanceof MapHandler) { - mapHandler = (MapHandler) in_mapHandler; - } - setEnabled(mapHandler != null); - } - - public MapHandler getMapHandler() { - return mapHandler; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapHandler) { - setMapHandler((MapHandler) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof MapHandler) { - setMapHandler(null); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/MenuList.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/MenuList.java deleted file mode 100644 index 776ade178..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/MenuList.java +++ /dev/null @@ -1,258 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/MenuList.java,v $ -// $RCSfile: MenuList.java,v $ -// $Revision: 1.6 $ -// $Date: 2007/03/08 17:35:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.swing.JMenu; -import javax.swing.JMenuBar; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.gui.MenuBar; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The MenuList is a component that creates a set of JMenus from Properties, and - * can provide a JMenuBar or JMenu with those JMenus. Used by the MapPanel. - *

- * - * The MenuList can be used in lieu of defining the OpenMap MenuBar and each - * Menu in the openmap.components property. The MenuList can be defined instead, - * with the menus it should create. It has one property: - * - *

- *   
- *   
- *    menulist.menus=menu1 menu2 menu3
- *    menu1.class=classname of menu1
- *    menu2.class=classname of menu2
- *    menu3.class=classname of menu3
- * 
- * 
- * 
- * - * When the MenuList.setBeanContext() method gets called, the MenuList will add - * its menus to that MapHandler/BeanContext. - * - * By default, the MenuList will provide an OpenMap MenuBar when asked for a - * JMenuBar, which will figure out if one of the child menus is a HelpMenu and - * place it at the end of the MenuBar menus. - */ -public class MenuList extends OMComponent { - - public final static String MenusProperty = "menus"; - public final static String MenuNameProperty = "name"; - - protected List menuList; - - protected String name = "Map"; - - /** - * Create an empty MenuList. - */ - public MenuList() { - menuList = new ArrayList(); - } - - /** - * Get a MenuBar with JMenus on it. If the MenuList has been given a - * MapHandler, the Menus will have been added to it, and therefore will be - * connected to OpenMap components. The MenuBar is not added to the - * MapHandler and probably shouldn't be, since it will find and re-add the - * Menus it finds there in some random order. - */ - public JMenuBar getMenuBar() { - MenuBar menuBar = new MenuBar(); - - for (JMenu menuu : menuList) { - menuBar.add(menuu); - } - - return menuBar; - } - - /** - * Get a JMenu with JMenus on it as sub-menus. If the MenuList has been - * given a MapHandler, the Menus will have been added to it, and therefore - * will be connected to OpenMap components. This menu will be named "Map", - * but you can rename it if you want. - */ - public JMenu getMenu() { - JMenu menu = new JMenu(name); - - for (JMenu menuu : menuList) { - menu.add(menuu); - } - - return menu; - } - - /** - * The MenuList will look for the "menus" property and build its menus. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - name = props.getProperty(prefix + MenuNameProperty, name); - - List menuItems = PropUtils.parseSpacedMarkers(props.getProperty(realPrefix + MenusProperty)); - if (!menuItems.isEmpty()) { - - for (String itemPrefix : menuItems) { - String classProperty = itemPrefix + ".class"; - String className = props.getProperty(classProperty); - if (className == null) { - Debug.error("MenuList.setProperties(): Failed to locate property \"" + classProperty - + "\"\n Skipping menu \"" + itemPrefix + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, itemPrefix, props); - if (obj instanceof JMenu) { - menuList.add((JMenu) obj); - } - } - } else { - if (Debug.debugging("menu")) { - Debug.output("MenuList created without menus in properties"); - } - } - } - - /** - * PropertyConsumer interface method. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - StringBuffer itemList = new StringBuffer(); - - for (JMenu menu : menuList) { - if (menu instanceof PropertyConsumer) { - PropertyConsumer ps = (PropertyConsumer) menu; - String prefix = ps.getPropertyPrefix(); - if (prefix == null) { - prefix = menu.getText().toLowerCase(); - ps.setPropertyPrefix(prefix); - } - - itemList.append(prefix).append(" "); - ps.getProperties(props); - } - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + MenusProperty, itemList.toString().trim()); - props.put(prefix + MenuNameProperty, PropUtils.unnull(name)); - - return props; - } - - /** - * PropertyConsumer interface method. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, props, MenuList.class, MenusProperty, "List of Menus", - "List of marker names for menu component properties.", null); - PropUtils.setI18NPropertyInfo(i18n, props, MenuList.class, MenuNameProperty, "Name", - "Name of the Menu provided by the MenuList.", null); - return props; - } - - /** - * Called when the MenuList is added to the MapHandler/BeanContext. The - * MenuList will add its menus to the BeanContext. - */ - public void setBeanContext(BeanContext bc) throws PropertyVetoException { - - super.setBeanContext(bc); - if (bc != null) { - for (JMenu menu : menuList) { - bc.add(menu); - } - } - } - - public void findAndInit(Object obj) { - if (obj instanceof JMenu) { - menuList.add((JMenu) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof JMenu) { - menuList.remove((JMenu) obj); - } - } - - public void add(JMenu menu) { - menuList.add(menu); - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * Builder method. - * - * @param name used on Map menu. - * @return this. - */ - public MenuList withName(String name) { - setName(name); - return this; - } - - /** - * Return a MenuList with a standard load of menus. - * - * @return MenuList - */ - public static MenuList standardConfig() { - MenuList menuList = new MenuList(); - menuList.add(new com.bbn.openmap.gui.FileMenu()); - menuList.add(new com.bbn.openmap.gui.NavigateMenu()); - menuList.add(new com.bbn.openmap.gui.ControlMenu()); - menuList.add(new com.bbn.openmap.gui.LayersMenu()); - menuList.add(new com.bbn.openmap.gui.GoToMenu()); - return menuList; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/MouseModeMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/MouseModeMenu.java deleted file mode 100644 index 7bf17ea17..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/MouseModeMenu.java +++ /dev/null @@ -1,193 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/MouseModeMenu.java,v $ -// $RCSfile: MouseModeMenu.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.ButtonGroup; -import javax.swing.JRadioButtonMenuItem; - -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.gui.AbstractOpenMapMenu; -import com.bbn.openmap.util.Debug; - -/** - * It provides GUI based on Mouse modes available from MouseDelegator - * object - */ -public class MouseModeMenu extends AbstractOpenMapMenu implements - PropertyChangeListener, ActionListener { - - public static final String defaultText = "Mouse Mode"; - public final static transient String mouseModeCmd = "setMouseMode"; - - protected transient MouseDelegator mouseDelegator = null; - // mouse mode widgets - protected transient JRadioButtonMenuItem[] mouseModeButtons = new JRadioButtonMenuItem[0]; - protected transient ButtonGroup group2 = null; - - public MouseModeMenu() { - super(); - setText(i18n.get(this, "mouseModeMenu", defaultText)); - addActionListener(this); - } - - /** - * Sets up the MouseModes submenu. - * - * @param md MouseDelegator - */ - public void setMouseDelegator(MouseDelegator md) { - mouseDelegator = md; - if (mouseDelegator != null) { - mouseDelegator.addPropertyChangeListener(this); - MapMouseMode[] modes = mouseDelegator.getMouseModes(); - String activeMode = mouseDelegator.getActiveMouseModeID(); - Debug.message("mousemodemenuitem", - "MouseModeMenuItem.setMouseDelegator MouseDelegator has " - + modes.length + " modes"); - setUpItems(modes, activeMode); - } - } - - public void unsetMouseDelegator(MouseDelegator md) { - if (md != null) { - mouseDelegator.removePropertyChangeListener(this); - - if (mouseModeButtons != null) { - for (int mms = 0; mms < mouseModeButtons.length; mms++) { - mouseModeButtons[mms].removeActionListener(this); - group2.remove(mouseModeButtons[mms]); - } - } - } - group2 = null; - mouseModeButtons = null; - mouseDelegator = null; - } - - protected void setUpItems(MapMouseMode[] modes, String activeMode) { - if (group2 == null) { - group2 = new ButtonGroup(); - } - mouseModeButtons = new JRadioButtonMenuItem[modes.length]; - - for (int mms = 0; mms < modes.length; mms++) { - Debug.message("mousemodemenuitem", - "MouseModeMenuItem.setUpItems adding " + modes[mms].getID()); - mouseModeButtons[mms] = (JRadioButtonMenuItem) this.add(new JRadioButtonMenuItem(modes[mms].getPrettyName())); - - mouseModeButtons[mms].setActionCommand(mouseModeCmd); - mouseModeButtons[mms].setName(modes[mms].getID()); - mouseModeButtons[mms].addActionListener(this); - mouseModeButtons[mms].setVisible(modes[mms].isVisible()); - group2.add(mouseModeButtons[mms]); - - if ((activeMode != null) && activeMode.equals(modes[mms].getID())) { - mouseModeButtons[mms].setSelected(true); - } - } - } - - /** - * ActionListener interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - - if (command.equals(mouseModeCmd)) { - JRadioButtonMenuItem rb = (JRadioButtonMenuItem) (e.getSource()); - mouseDelegator.setActiveMouseModeWithID(rb.getName()); - } - } - - /** - * This method gets called when a bound property is changed. - *

- * - * @param evt A PropertyChangeEvent object describing the event - * source and the property that has changed. - */ - public void propertyChange(PropertyChangeEvent evt) { - Debug.message("mousemodemenuitem", "MouseModeMenuItem.propertyChange()"); - - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - // Mark the radio button representing the new mode as - // active - String mmID = ((MapMouseMode) evt.getNewValue()).getID(); - for (int i = 0; i < mouseModeButtons.length; i++) { - //System.out.println(mmID + " " - // +mouseModeButtons[i].getName()); - if (mouseModeButtons[i].getName().equals(mmID)) { - mouseModeButtons[i].setSelected(true); - //System.out.println("MouseModeMenu: New Active - // Mode " + mmID); - break; - } - } - } - - else if (evt.getPropertyName() == MouseDelegator.MouseModesProperty) { - // Redo the whole submenu - for (int i = 0; i < mouseModeButtons.length; i++) { - remove(mouseModeButtons[i]); - } - MapMouseMode[] modes = mouseDelegator.getMouseModes(); - String activeMode = mouseDelegator.getActiveMouseModeID(); - setUpItems(modes, activeMode); - } - } - - /** - * Called when a component that is needed, and not available with - * an appropriate iterator from the BeanContext. This lets this - * object hook up with what it needs. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MouseDelegator) { - // do the initializing that need to be done here - Debug.message("mousemodemenuitem", - "MouseModeMenuItem found a MouseDelegator."); - setMouseDelegator((MouseDelegator) someObj); - } - } - - /** - * AbstractOpenMapMenu method. Called when an objects have been - * removed from the parent BeanContext. - */ - public void findAndUnInit(Object someObj) { - if (someObj instanceof MouseDelegator) { - // do the initializing that need to be done here - Debug.message("mousemodemenuitem", - "MouseModeMenuItem removing MouseDelegator."); - setMouseDelegator(null); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/OMBasicMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/OMBasicMenu.java deleted file mode 100644 index c83e97d92..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/OMBasicMenu.java +++ /dev/null @@ -1,40 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/OMBasicMenu.java,v $ -// $RCSfile: OMBasicMenu.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import com.bbn.openmap.gui.AbstractOpenMapMenu; - -/** - * This is version of AbstractOpenMapMenu that can be created and - * configured with properties. No items are added by default. - */ -public class OMBasicMenu extends AbstractOpenMapMenu { - - public OMBasicMenu() { - super(); - } - - public OMBasicMenu(String title) { - super(title); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/ProjectionMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/ProjectionMenu.java deleted file mode 100644 index 4366abcb5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/ProjectionMenu.java +++ /dev/null @@ -1,255 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/ProjectionMenu.java,v $ -// $RCSfile: ProjectionMenu.java,v $ -// $Revision: 1.7 $ -// $Date: 2007/01/26 14:13:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.JMenuItem; -import javax.swing.JRadioButtonMenuItem; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.ProjectionSupport; -import com.bbn.openmap.gui.AbstractOpenMapMenu; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionException; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.ProjectionLoader; - -/** - * Provides ProjectionMenu items for selecting Projection type. - */ -public class ProjectionMenu extends AbstractOpenMapMenu implements - ActionListener, ProjectionListener, PropertyChangeListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.menu.ProjectionMenu"); - - public static final String defaultText = "Projection"; - - protected transient ProjectionSupport projectionSupport = new ProjectionSupport(this, false); - protected transient Projection projection; - protected transient Component projComponent; - public final static transient String projCmd = "setProj"; - protected ProjectionFactory projectionFactory; - - /** - * Create the projection sub-menu. - */ - public ProjectionMenu() { - super(); - setText(i18n.get(this, "projectionMenu", defaultText)); - } - - public void configure(List loaders) { - removeAll(); - JRadioButtonMenuItem rb; - ButtonGroup group = new ButtonGroup(); - - for (ProjectionLoader pl : loaders) { - rb = new JRadioButtonMenuItem(pl.getPrettyName()); - rb.setActionCommand(projCmd); - String plclassname = pl.getProjectionClass().getName(); - rb.setName(plclassname); - rb.setToolTipText(pl.getDescription()); - rb.addActionListener(this); - group.add(rb); - add(rb); - } - - setProjection(projection); - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - - logger.fine("received command: " + command); - - if (command == projCmd) { - JRadioButtonMenuItem rb = (JRadioButtonMenuItem) (ae.getSource()); - String projclassname = rb.getName(); - logger.fine("ProjectionMenu new proj name: " + projclassname); - try { - Projection newProj = getProjectionFactory().makeProjection(projclassname, - projection); - fireProjectionChanged(newProj); - } catch (ProjectionException pe) { - logger.warning(pe.getMessage()); - rb.setEnabled(false); - } - } - } - - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName() == ProjectionFactory.AvailableProjectionProperty) { - configure((List) pce.getNewValue()); - } - } - - // ------------------------------------------------------------ - // ProjectionListener interface - // ------------------------------------------------------------ - - /** - * The Map projection has changed, in order to baseline new changes as a - * result of menu options being selected. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - - Projection newProj = e.getProjection(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(newProj != null ? newProj.toString() : "null"); - } - - if (newProj != null - && (projection == null || (!projection.equals(newProj)))) { - setProjection((Projection) newProj.makeClone()); - Object source = e.getSource(); - if (source instanceof Component) { - projComponent = (Component) source; - } - } - } - - /** - * Set the projection. This changes the setting of the projection radio - * button menu. - * - * @param aProjection Projection - */ - protected synchronized void setProjection(Projection aProjection) { - projection = aProjection; - - if (projection == null) { - return; - } - - String newProjClassName = projection.getClass().getName(); - - // Change the selected projection type menu item - for (int i = 0; i < getItemCount(); i++) { - JMenuItem item = getItem(i); - if (newProjClassName.equals(item.getName())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("ProjectionMenu | setting " + item.getName() - + " as active"); - } - item.setSelected(true); - return; - } - } - } - - /** - * Convenience function for setting up listeners - */ - public void setupListeners(MapBean map) { - logger.fine("seting up listeners"); - addProjectionListener(map); - map.addProjectionListener(this); - } - - /** - * Convenience function for undoing set up listeners - */ - public void undoListeners(MapBean map) { - removeProjectionListener(map); - map.removeProjectionListener(this); - } - - /*---------------------------------------------------------------------- - * Projection Support - for broadcasting projection changed events - *----------------------------------------------------------------------*/ - /** - * Add a ProjectionListener to this menu and its components. - */ - protected synchronized void addProjectionListener(ProjectionListener l) { - projectionSupport.add(l); - } - - /** - * Remove a ProjectionListener from this menu and its components. - */ - protected synchronized void removeProjectionListener(ProjectionListener l) { - projectionSupport.remove(l); - } - - /** - * Fire the changed projection from the support. - */ - public void fireProjectionChanged(Projection p) { - projectionSupport.fireProjectionChanged(p); - } - - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - setupListeners((MapBean) someObj); - } - if (someObj instanceof ProjectionFactory) { - projectionFactory = (ProjectionFactory) someObj; - projectionFactory.addPropertyChangeListener(this); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - undoListeners((MapBean) someObj); - } - - if (someObj.equals(projectionFactory)) { - projectionFactory.removePropertyChangeListener(this); - projectionFactory = null; - } - - if (someObj.equals(this)) { - dispose(); - } - } - - public ProjectionFactory getProjectionFactory() { - if (projectionFactory == null) { - projectionFactory = ProjectionFactory.loadDefaultProjections(); - } - return projectionFactory; - } - - public void setProjectionFactory(ProjectionFactory projectionFactory) { - this.projectionFactory = projectionFactory; - } - - public void dispose() { - projectionSupport.dispose(); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/QuitMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/QuitMenuItem.java deleted file mode 100644 index 08eaa8e7b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/QuitMenuItem.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/QuitMenuItem.java,v -// $ -// $RCSfile: QuitMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JMenuItem; - -public class QuitMenuItem extends JMenuItem { - - public QuitMenuItem() { - super("Quit"); - addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - // HACK - need to call shutdown() on mapbean - // actually we should broadcast a shutdown - // event so that the gui components can - // clean up, and maybe only one can call exit. - System.exit(0); - } - }); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsGifMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsGifMenuItem.java deleted file mode 100644 index 098b53f33..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsGifMenuItem.java +++ /dev/null @@ -1,35 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsGifMenuItem.java,v $ -// $RCSfile: SaveAsGifMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import com.bbn.openmap.image.AcmeGifFormatter; - -/** - * A JMenuItem that uses the MapHandler to find the MapBean and save - * an image of it in the GIF format. - */ -public class SaveAsGifMenuItem extends SaveAsImageMenuItem { - public SaveAsGifMenuItem() { - super("GIF", new AcmeGifFormatter()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageFileChooser.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageFileChooser.java deleted file mode 100644 index 807b50cd6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageFileChooser.java +++ /dev/null @@ -1,82 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsImageFileChooser.java,v $ -// $RCSfile: SaveAsImageFileChooser.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/11/14 22:41:05 $ -// $Author: kratkiew $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.BorderLayout; - -import javax.swing.JFileChooser; -import javax.swing.JPanel; - -import com.bbn.openmap.gui.DimensionQueryPanel; -import com.bbn.openmap.util.PaletteHelper; - -/** - * A class extended from a JFileChooser that adds fields for - * specifying the image size. - */ -public class SaveAsImageFileChooser extends JFileChooser { - - DimensionQueryPanel dqp = new DimensionQueryPanel(); - - /** - * Create file chooser with the image size fields filled in. - */ - public SaveAsImageFileChooser(int width, int height) { - super(); - dqp.setFieldHeight(height); - dqp.setFieldWidth(width); - JPanel imageSizePanel = PaletteHelper.createPaletteJPanel(" Set Image Size "); - imageSizePanel.setLayout(new BorderLayout()); - imageSizePanel.add(dqp, BorderLayout.CENTER); - setAccessory(imageSizePanel); - } - - /** - * Set the value of the image width setting from the GUI. - */ - public void setImageWidth(int w) { - dqp.setFieldWidth(w); - } - - /** - * Get the value of the image width setting from the GUI. - */ - public int getImageWidth() { - return dqp.getFieldWidth(); - } - - /** - * Set the value of the image height setting from the GUI. - */ - public void setImageHeight(int h) { - dqp.setFieldHeight(h); - } - - /** - * Get the value of the image height setting from the GUI. - */ - public int getImageHeight() { - return dqp.getFieldHeight(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageMenuItem.java deleted file mode 100644 index fdcdc4353..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsImageMenuItem.java +++ /dev/null @@ -1,156 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsImageMenuItem.java,v $ -// $RCSfile: SaveAsImageMenuItem.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.image.AbstractImageFormatter; -import com.bbn.openmap.util.Debug; - -/** - * A MenuItem that is capable of looking at MapBean and saving it as an Image - */ -public class SaveAsImageMenuItem extends MapHandlerMenuItem implements ActionListener { - - private static final long serialVersionUID = 1L; - AbstractImageFormatter formatter = null; - - public AbstractImageFormatter getFormatter() { - return formatter; - } - - public void setFormatter(AbstractImageFormatter formatter) { - this.formatter = formatter; - } - - /** - * @param display A String that will be displayed when this menuitem is - * shown in GUI - * @param in_formatter A formatter that knows how to generate an image from - * MapBean. - */ - public SaveAsImageMenuItem(String display, AbstractImageFormatter in_formatter) { - super(display); - formatter = in_formatter; - addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - Debug.message("saveimage", "SaveAsImageMenuItem: actionPerformed"); - - if (mapHandler == null) { - Debug.output("SaveAsImageMenuItem: mapHandler = null, returning"); - return; - } - - MapBean mb = (MapBean) mapHandler.get("com.bbn.openmap.MapBean"); - - if (mb != null) { - Debug.message("saveimage", "MapBean found, creating image"); - try { - - while (true) { - SaveAsImageFileChooser chooser = new SaveAsImageFileChooser(mb.getWidth(), mb.getHeight()); - - int returnVal = chooser.showSaveDialog(getParent()); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String filename = chooser.getSelectedFile().getAbsolutePath(); - if (formatter == null) { - break; - } - - filename = checkFileName(filename, formatter.getFormatLabel().toLowerCase()); - if (filename == null) { - // This is the reason for the while - // loop, the name didn't really pass - // muster, so we'll try again. - continue; - } - - int imageHeight = chooser.getImageHeight(); - int imageWidth = chooser.getImageWidth(); - - byte[] imageBytes = formatter.getImageFromMapBean(mb, imageWidth, imageHeight); - FileOutputStream binFile = new FileOutputStream(filename); - binFile.write(imageBytes); - binFile.close(); - if (Debug.debugging("saveimage")) { - com.bbn.openmap.proj.Projection proj = mb.getProjection(); - Debug.output("Created image at " + filename + "where projection covers " - + proj.getUpperLeft() + " to " + proj.getLowerRight()); - } - break; - } else if (returnVal == JFileChooser.CANCEL_OPTION) { - break; - } - } - } catch (Exception e) { - Debug.error("SaveAsImageMenuItem: " + e); - e.printStackTrace(); - } - } - } - - /** - * A little method that checks the file path to see if it exists, and - * modifies it with the imageSuffix if it doesn't have one specified by the - * user. Asks the user if it's OK to overwrite if the file exists. - * - * @param filePath absolute file path to check. - * @param imageSuffix suffix to append to filePath if it doesn't already - * have one. This word should not contain a starting '.'. - * @return null if name is no good, a String to use if good. - */ - protected String checkFileName(String filePath, String imageSuffix) { - - String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); - String newFilePath; - - if (fileName.indexOf('.') == -1) { - newFilePath = filePath + "." + imageSuffix; - } else { - // else leave it alone, user specified suffix - newFilePath = filePath; - } - - File file = new File(newFilePath); - if (file.exists()) { - // Check to see if it is alright to overwrite. - int choice = JOptionPane.showConfirmDialog(null, "The file " + newFilePath + " exists, replace?", - "Confirm File Replacement", JOptionPane.YES_NO_OPTION); - if (choice != JOptionPane.YES_OPTION) { - newFilePath = null; - } - } - - return newFilePath; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsJpegMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsJpegMenuItem.java deleted file mode 100644 index 580e89ae6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsJpegMenuItem.java +++ /dev/null @@ -1,35 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsJpegMenuItem.java,v $ -// $RCSfile: SaveAsJpegMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import com.bbn.openmap.image.SunJPEGFormatter; - -/** - * A JMenuItem that uses the MapHandler to find the MapBean and save - * an image of it in the JPEG format. - */ -public class SaveAsJpegMenuItem extends SaveAsImageMenuItem { - public SaveAsJpegMenuItem() { - super("JPEG", new SunJPEGFormatter()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsMenu.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsMenu.java deleted file mode 100644 index 46d53b75b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsMenu.java +++ /dev/null @@ -1,90 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsMenu.java,v -// $ -// $RCSfile: SaveAsMenu.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 17:51:43 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import javax.swing.JMenu; - -import com.bbn.openmap.gui.AbstractOpenMapMenu; -import com.bbn.openmap.image.AbstractImageFormatter; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; - -public class SaveAsMenu extends AbstractOpenMapMenu { - - /** - * - */ - private static final long serialVersionUID = 977535233425016853L; - - public SaveAsMenu() { - this("Save Map As"); - } - - public SaveAsMenu(String title) { - super(title); - add(new SaveAsJpegMenuItem()); - add(new SaveAsGifMenuItem()); - add(new SaveAsPngMenuItem()); - - addSVGMenuItem(this); - } - - /** - * Add the SVG menu item to the given menu if Batik can be found in the - * classpath. - * - * @param menu JMenu to add SVG option to - */ - protected void addSVGMenuItem(JMenu menu) { - try { - - // This is a test to see if the batik package is - // available. If it isn't, this statement should - // throw an exception, and the SVG option will not be - // added to the SaveAs Menu item. - - if (Class.forName("org.apache.batik.swing.JSVGCanvas") != null - && Class.forName("org.w3c.dom.ElementTraversal") != null - && Class.forName("com.bbn.openmap.image.SVGFormatter") != null) { - - // Need to do this in a way that allows it to be created if it's - // there, but gracefully skipped from compilation if the batik - // library is unavailable - Object obj = ComponentFactory.create("com.bbn.openmap.image.SVGFormatter"); - if (obj instanceof AbstractImageFormatter) { - menu.add(new SaveAsImageMenuItem("SVG", (AbstractImageFormatter) obj)); - } - } - return; - - } catch (ClassNotFoundException cnfe) { - } catch (NoClassDefFoundError ncdfe) { - } - - if (Debug.debugging("basic")) { - Debug.output("SVG not added to the Save As options, because Batik was not found in classpath."); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsPngMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsPngMenuItem.java deleted file mode 100644 index 63f577d5e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SaveAsPngMenuItem.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SaveAsGifMenuItem.java,v $ -// $RCSfile: SaveAsGifMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import com.bbn.openmap.image.PNG32ImageFormatter; - - -/** - * A JMenuItem that uses the MapHandler to find the MapBean and save - * an image of it in the PNG format. - */ -public class SaveAsPngMenuItem extends SaveAsImageMenuItem { - public SaveAsPngMenuItem() { - super("PNG", new PNG32ImageFormatter()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/SavePropertiesMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/SavePropertiesMenuItem.java deleted file mode 100644 index ba69de94b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/SavePropertiesMenuItem.java +++ /dev/null @@ -1,101 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/SavePropertiesMenuItem.java,v $ -// $RCSfile: SavePropertiesMenuItem.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/02/27 15:11:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; - -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.util.Debug; - -/** - * A Menu item that generates a Properties object when it is clicked - * upon. It needs BeanContext object. It iterates through objects in - * BeanContext and looks for objects that implement PropertyConsumer - * interface and generates Properties object from them.Wwhen it has - * found all the Properties, it writes them to a file by providing the - * user with a file dialog box. - */ -public class SavePropertiesMenuItem extends MapHandlerMenuItem implements - ActionListener { - - public SavePropertiesMenuItem() { - super("Save Map Properties"); - addActionListener(this); - } - - public void actionPerformed(ActionEvent ae) { - //Collect properties - if (mapHandler == null) { - if (Debug.debugging("menu")) { - Debug.error("SavePropertiesMenuItem: no Map Handler to use"); - } - return; - } - - FileDialog fd = new FileDialog(new Frame(), "Saving the map as Properties file...", FileDialog.SAVE); - fd.setVisible(true); - - String fileName = fd.getFile(); - String dirName = fd.getDirectory(); - - if (fileName == null) { - Debug.message("savepropertiesmenuitem", - "User did not select any file"); - return; - } - - Debug.message("savepropertiesmenuitem", "User selected file " + dirName - + File.separator + fileName); - - File file = new File(new File(dirName), fileName); - - FileOutputStream fos; - PrintStream ps = null; - try { - fos = new FileOutputStream(file); - } //catch (FileNotFoundException fnfe) { - /* - * In JDK 1.2, the FileOutputStream(File) constructor throws a - * IOException, but in JDK1.3 it throws FileNotFoundException. - * So in 1.2 it is insufficient to catch - * FileNotFoundException, you need to catch IOException. But - * in 1.3, catching FileNotFoundException is enough. - */ - catch (IOException fnfe) { - System.err.println(fnfe.getMessage()); - return; - } - - ps = new PrintStream(fos); - - PropertyHandler.createOpenMapProperties(mapHandler, ps); - ps.close(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/ToolPanelToggleMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/ToolPanelToggleMenuItem.java deleted file mode 100644 index d3eac487a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/ToolPanelToggleMenuItem.java +++ /dev/null @@ -1,166 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/ToolPanelToggleMenuItem.java,v $ -// $RCSfile: ToolPanelToggleMenuItem.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.gui.ToolPanel; -import com.bbn.openmap.util.I18n; - -/** - * Menu item that holds onto the tool panel, and hides/displays it when - * selected. Since the ToolPanel will make itself invisible if all of its - * components are invisible, this menu item will disable itself when the - * ToolPanel has set itself to be invisible, and vice-versa. - */ -public class ToolPanelToggleMenuItem extends JMenuItem implements - ActionListener, ComponentListener, PropertyChangeListener { - - protected ToolPanel toolPanel = null; - - public final static String HideLabelProperty = "hide"; - public final static String DisplayLabelProperty = "display"; - - protected final static String DefaultHideLabel = "Hide"; - protected final static String DefaultDisplayLabel = "Display"; - protected final static String DefaultToolPanelName = "Tool Panel"; - - protected String hideLabel = DefaultHideLabel; - protected String displayLabel = DefaultDisplayLabel; - - public ToolPanelToggleMenuItem() { - // assume that the tool panel isn't there. - // Won't be visible if it isn't. - super(DefaultHideLabel); - init(null); - } - - public ToolPanelToggleMenuItem(ToolPanel tp) { - super(tp.isVisible() ? DefaultHideLabel : DefaultDisplayLabel); - init(tp); - } - - public void init(ToolPanel tp) { - setI18NLabels(tp); - setToolPanel(tp); - addActionListener(this); - } - - public void setToolPanel(ToolPanel tp) { - if (toolPanel != null) { - toolPanel.removeComponentListener(this); - toolPanel.removePropertyChangeListener(this); - } - - toolPanel = tp; - this.setVisible(toolPanel != null); - - if (toolPanel != null) { - toolPanel.addComponentListener(this); - toolPanel.addPropertyChangeListener(this); - stateCheck(); - } - } - - public ToolPanel getToolPanel() { - return toolPanel; - } - - public boolean forToolPanel(ToolPanel tp) { - return (tp == toolPanel); - } - - public void actionPerformed(ActionEvent ae) { - if (toolPanel != null) { - boolean selected = toolPanel.isVisible(); - toolPanel.setVisible(!selected); - setText(selected ? displayLabel : hideLabel); - } - } - - public void dispose() { - setToolPanel(null); - } - - /** - * Check the state of the ToolPanel and set enabled state and text - * accordingly. - */ - public void stateCheck() { - if (toolPanel != null) { - setEnabled(toolPanel.areComponentsVisible()); - setText(toolPanel.isVisible() ? hideLabel : displayLabel); - } - } - - public void componentHidden(ComponentEvent ce) { - stateCheck(); - } - - public void componentMoved(ComponentEvent ce) {} - - public void componentResized(ComponentEvent ce) {} - - public void componentShown(ComponentEvent ce) { - stateCheck(); - } - - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - if (propertyName.equals(ToolPanel.MembershipProperty)) { - stateCheck(); - } - - } - - protected void setI18NLabels(ToolPanel tp) { - - I18n i18n = Environment.getI18n(); - String name = DefaultToolPanelName; - if (tp != null) { - name = tp.getName(); - } - - String interString = i18n.get(ToolPanelToggleMenuItem.class, - HideLabelProperty, - I18n.TOOLTIP, - hideLabel); - - hideLabel = interString + " " + name; - - interString = i18n.get(ToolPanelToggleMenuItem.class, - DisplayLabelProperty, - I18n.TOOLTIP, - displayLabel); - - displayLabel = interString + " " + name; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/UndoMenuItemStackTrigger.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/UndoMenuItemStackTrigger.java deleted file mode 100644 index 39637ad3b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/UndoMenuItemStackTrigger.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - */ -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.UndoEvent; -import com.bbn.openmap.event.UndoStack; -import com.bbn.openmap.event.UndoStackTrigger; -import com.bbn.openmap.util.I18n; - -/** - * UndoMenuItemStackTrigger holds a couple of menu items that can trigger an UndoStack. - * - * @author dietrick - */ -public class UndoMenuItemStackTrigger - implements UndoStackTrigger, ActionListener { - JMenuItem undoMI; - JMenuItem redoMI; - - protected final List listeners; - - protected String nothingToUndoString; - protected String nothingToRedoString; - protected String undoString; - protected String redoString; - - public UndoMenuItemStackTrigger() { - listeners = Collections.synchronizedList(new ArrayList()); - - I18n i18n = Environment.getI18n(); - - nothingToUndoString = i18n.get(this.getClass(), "nothingToUndoString", "Nothing to Undo"); - nothingToRedoString = i18n.get(this.getClass(), "nothingToRedoString", "Nothing to Redo"); - - undoString = i18n.get(this.getClass(), "undoString", "Undo "); - redoString = i18n.get(this.getClass(), "redoString", "Redo "); - - undoMI = new JMenuItem(nothingToUndoString); - undoMI.setActionCommand(UndoStack.UndoCmd); - redoMI = new JMenuItem(nothingToRedoString); - redoMI.setActionCommand(UndoStack.RedoCmd); - - undoMI.addActionListener(this); - redoMI.addActionListener(this); - - // Should be disabled until an event is received from the undo stack. - undoMI.setEnabled(false); - redoMI.setEnabled(false); - } - - /* - * Adding an action listener (UndoStack) to listen for undo and redo - * requests. - * - * @see com.bbn.openmap.event.UndoStackTrigger#addActionListener(java.awt - * .event.ActionListener) - */ - public void addActionListener(ActionListener al) { - if (!listeners.contains(al)) { - listeners.add(al); - } - } - - /* - * Removing action listener that was listening for undo and redo requests. - * - * @see com.bbn.openmap.event.UndoStackTrigger#removeActionListener(java. - * awt.event.ActionListener) - */ - public void removeActionListener(ActionListener al) { - listeners.remove(al); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.UndoStackTrigger#updateUndoStackStatus(boolean, - * boolean) - */ - public void updateUndoStackStatus(UndoEvent undoEvent, UndoEvent redoEvent) { - undoMI.setEnabled(undoEvent != null); - redoMI.setEnabled(redoEvent != null); - - if (undoEvent != null) { - undoMI.setText(undoString + undoEvent.getDescription()); - } else { - undoMI.setText(nothingToUndoString); - } - - if (redoEvent != null) { - redoMI.setText(redoString + redoEvent.getDescription()); - } else { - redoMI.setText(nothingToRedoString); - } - } - - /* - * (non-Javadoc) - * - * @see - * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - List listClone = new ArrayList(); - listClone.addAll(listeners); - - for (ActionListener al : listClone) { - al.actionPerformed(e); - } - } - - /** - * @return the undoMI - */ - public JMenuItem getUndoMenuItem() { - return undoMI; - } - - /** - * @return the redoMI - */ - public JMenuItem getRedoMenuItem() { - return redoMI; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/WebSiteHelpMenuItem.java b/src/core/src/main/java/com/bbn/openmap/gui/menu/WebSiteHelpMenuItem.java deleted file mode 100644 index 96df49049..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/WebSiteHelpMenuItem.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/WebSiteHelpMenuItem.java,v $ -// $RCSfile: WebSiteHelpMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.LightMapHandlerChild; - -/** - * This object tells a browser to bring up the OpenMap Website help. - */ -public class WebSiteHelpMenuItem extends JMenuItem implements ActionListener, - LightMapHandlerChild { - - protected InformationDelegator informationDelegator = null; - - public WebSiteHelpMenuItem() { - super("OpenMap WebSite Help"); - setMnemonic('h'); - addActionListener(this); - setEnabled(false); // enabled when InformationDelegator found. - } - - /** - * @param in_informationDelegator - */ - public void setInformationDelegator( - InformationDelegator in_informationDelegator) { - informationDelegator = in_informationDelegator; - setEnabled(informationDelegator != null); - } - - /** - * Return current value of InformationDelegator. - */ - protected InformationDelegator getInformationDelegator() { - return informationDelegator; - } - - public void actionPerformed(ActionEvent ae) { - if (informationDelegator != null) { - informationDelegator.displayURL(Environment.get(Environment.HelpURL, - "http://openmap.bbn.com/doc/user-guide.html")); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof InformationDelegator) { - setInformationDelegator((InformationDelegator) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof InformationDelegator - && getInformationDelegator() == (InformationDelegator) someObj) { - setInformationDelegator(null); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/menu/package.html b/src/core/src/main/java/com/bbn/openmap/gui/menu/package.html deleted file mode 100644 index f27bb5cce..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/menu/package.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -This package contains OpenMap Swing GUI components that can be used in -menus. Most of these components are LightMapHandlerChild components -that receive access to MapHandler components by their menu, via their -findAndInit() and findAndUndo() methods. - - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/package.html b/src/core/src/main/java/com/bbn/openmap/gui/package.html deleted file mode 100644 index 51ceb91e4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -This package contains the main OpenMap Swing GUI components. These -components have been written to connect to other objects -automatically when all objects are added to the MapHandler. - - diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/HotwashTimerControlButtonPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/time/HotwashTimerControlButtonPanel.java deleted file mode 100644 index 0ea861389..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/HotwashTimerControlButtonPanel.java +++ /dev/null @@ -1,132 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/HotwashTimerControlButtonPanel.java,v $ -// $RCSfile: HotwashTimerControlButtonPanel.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:31:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.net.MalformedURLException; -import java.net.URL; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.time.RealTimeHandler; -import com.bbn.openmap.time.TimerStatus; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The TimerControlButtonPanel provides control for starting and stopping a - * clock contained in a RealTimeHandler. This class also has provisions for - * having the clock run the reverse direction, and for stepping the clock - * forward and backward one interval. - */ -public class HotwashTimerControlButtonPanel extends TimerControlButtonPanel { - - JButton forwardStepButton; - JButton backwardStepButton; - - public HotwashTimerControlButtonPanel() { - } - - public HotwashTimerControlButtonPanel(RealTimeHandler rth) { - super(rth); - } - - /** - * Set the ImageIcons to whatever is set on the URL variables. Sets the - * running icon to be the pressed icon, and makes the stopped and inactive - * icons. - */ - public void initGUI() { - removeAll(); - try { - URL url = PropUtils.getResourceOrFileOrURL(TimerControlButtonPanel.class, - forwardIconURL); - forwardIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(TimerControlButtonPanel.class, - forwardStepIconURL); - forwardStepIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(TimerControlButtonPanel.class, - backwardIconURL); - backwardIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(TimerControlButtonPanel.class, - backwardStepIconURL); - backwardStepIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(TimerControlButtonPanel.class, - pauseIconURL); - pauseIcon = new ImageIcon(url); - } catch (MalformedURLException murle) { - Debug.error("TimerToggleButton: initGUI() bad icon."); - } catch (NullPointerException npe) { - Debug.error("TimerToggleButton: initGUI() bad icon."); - npe.printStackTrace(); - } - - JToolBar jtb = new JToolBar(); - jtb.setFloatable(false); - - backwardButton = new JButton(backwardIcon); - backwardButton.setToolTipText("Run Timer Backwards"); - backwardButton.setActionCommand(TimerStatus.TIMER_BACKWARD); - backwardButton.addActionListener(this); - // jtb.add(backwardButton); - - forwardStepButton = new JButton(backwardStepIcon); - forwardStepButton.setToolTipText("Step Timer Backward"); - forwardStepButton.setActionCommand(TimerStatus.TIMER_STEP_BACKWARD); - forwardStepButton.addActionListener(this); - jtb.add(forwardStepButton); - - forwardButton = new JButton(forwardIcon); - forwardButton.setToolTipText("Run Timer Forward"); - forwardButton.setActionCommand(TimerStatus.TIMER_FORWARD); - forwardButton.addActionListener(this); - jtb.add(forwardButton); - - backwardStepButton = new JButton(forwardStepIcon); - backwardStepButton.setToolTipText("Step Timer Forward"); - backwardStepButton.setActionCommand(TimerStatus.TIMER_STEP_FORWARD); - backwardStepButton.addActionListener(this); - jtb.add(backwardStepButton); - - add(jtb); - } - - public void enableForwardButton(boolean set) { - forwardButton.setEnabled(set && clockEnabled); - } - - public void enableBackwardButton(boolean set) { - backwardButton.setEnabled(set && clockEnabled); - } - - public void setEnableState(boolean set) { - super.setEnableState(set); - forwardStepButton.setEnabled(set); - backwardStepButton.setEnabled(set); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/ITimeBoundsUserActionsListener.java b/src/core/src/main/java/com/bbn/openmap/gui/time/ITimeBoundsUserActionsListener.java deleted file mode 100644 index 21f5937d0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/ITimeBoundsUserActionsListener.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.bbn.openmap.gui.time; - - -/** - * Interface that allows TimePanel to reach back into application when user clicks certain buttons. - */ -public interface ITimeBoundsUserActionsListener { - - /** - * Used with 'set bounds based on selection' button. - * @param start New start time. - * @param end New end time. - */ - void setTimeBounds(long start, long end); - - /** - * Immediately switch from historical mode to real-time mode (if necessary) and jump to current real time. - */ - void jumpToRealTime(); - - /** - * Bring up the GUI that allows time bounds to be set manually. - */ - void invokeDateSelectionGUI(boolean endFocus); - - /** - * Set a fixed window over which all events should be rendered. - * @param start The window's start time. - * @param end The window's end tim. - */ - void setFixedRenderRange(long start, long end); - - /** - * Clear any previously-set fixed render window. - */ - void clearFixedRenderRange(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimePanel.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimePanel.java deleted file mode 100755 index 4cc23b0a1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimePanel.java +++ /dev/null @@ -1,595 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/TimePanel.java,v $ -// $RCSfile: TimePanel.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:31:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.awt.BorderLayout; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; -import javax.swing.border.AbstractBorder; - -import com.bbn.openmap.event.OMEventSelectionCoordinator; -import com.bbn.openmap.gui.MapPanelChild; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.gui.event.EventPresenter; -import com.bbn.openmap.time.Clock; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.time.TimerRateHolder; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The TimePanel is a GUI widget that provides assortment of Clock controls, - * including play, step and reverse buttons, a rate controller, a current time - * label and a time slider. - *

- * A Clock is needed to create an interface. If there is no clock, an empty - * panel with a title will be displayed. - *

- * If you are using the openmap.properties file to configure your application - * and want to control the parent component of the TimePanel, use the "parent" - * property to specify the marker name of the parent component. The - * BasicMapPanel asks MapPanelChildren for their parent's names when deciding - * whether to add them or not, when it finds potential children in the - * findAndInit method. - */ -public class TimePanel extends OMComponentPanel implements MapPanelChild, - PropertyChangeListener, TimeEventListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimePanel"); - - /** - * This property is used to signify whether the play filter should be used. - */ - public final static String PlayFilterProperty = "playfilter"; - public final static String NO_TIME_STRING = "--:--:-- (--:--:--)"; - public final static String PanelTitleProperty = "panelTitle"; - private String defaultPanelTitle = " Timeline Controls "; - - public final static String RealTimeModeProperty = "realTimeMode"; - private boolean realTimeMode = false; - - public final static String ShowPlayFilterProperty = "showPlayFilter"; - private boolean showPlayFilter = true; - - /** - * The Clock object used by the TimePanel. - */ - protected Clock clock; - - // / GUI ToolPanel widgets. Kept here to make their visibility - // adjustable. - protected JToggleButton timeWrapToggle; - - // protected JSlider timeSlider; - - protected JLabel timeLabel; - protected JLabel mouseTimeLabel; - protected JLabel eventDetailLabel; - - protected JCheckBox playFilter; - - protected HotwashTimerControlButtonPanel timerControl; - - protected TimerRateComboBox timerRateControl; - - protected String preferredLocation = BorderLayout.SOUTH; - - protected boolean useTimeWrapToggle = false; - - public transient DecimalFormat df = new DecimalFormat("00"); - - // KMMOD - TimelinePanel timelinePanel; - - TimeSliderPanel timeSliderPanel; - - protected String parentName; - - // Isolating formats that have anything to do with months+days, for International audiences - final public static DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy (HH:mm:ss)"); - final public static DateFormat dateFormat_realTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); - final public static DateFormat dayFormat = new SimpleDateFormat("MM/dd/yyyy"); - - public TimePanel() { - // Needs Clock to create interface. - } - - public class NoBorder extends AbstractBorder { - NoBorder() {} - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - parentName = props.getProperty(prefix - + MapPanelChild.ParentNameProperty); - - defaultPanelTitle = props.getProperty(prefix - + PanelTitleProperty, - defaultPanelTitle); - - realTimeMode = PropUtils.booleanFromProperties(props, prefix - + RealTimeModeProperty, realTimeMode); - - showPlayFilter = PropUtils.booleanFromProperties(props, prefix - + ShowPlayFilterProperty, showPlayFilter); - - if(realTimeMode) { - // At this point, we know we're going to need a TimeSliderPanel - getTimeSliderPanel(); - } - } - - /** - * A Clock is needed to create an interface. If there is no clock, an empty - * panel with a title will be displayed. - */ - public void createInterface() { - removeAll(); - - String internString = i18n.get(this.getClass(), - "timeline_controls", - defaultPanelTitle); - - setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - internString)); - - if (clock == null) { - logger.info("No clock, not putting anything in interface."); - return; - } - // javax.swing.Border debugBorder = - // BorderFactory.createLineBorder(Color.red); - JPanel leftPanel = new JPanel(); - GridBagLayout lgridbag = new GridBagLayout(); - leftPanel.setLayout(lgridbag); - GridBagConstraints c = new GridBagConstraints(); - Insets insets = new Insets(2, 4, 2, 4); - c.weightx = 0f; - c.fill = GridBagConstraints.VERTICAL; - c.weighty = 1f; - c.gridx = GridBagConstraints.REMAINDER; - c.insets = insets; - - internString = i18n.get(this.getClass(), "play_selected", "Play Filter"); - if(showPlayFilter) { - playFilter = new JCheckBox(internString); - internString = i18n.get(this.getClass(), - "play_selected", - I18n.TOOLTIP, - "Jump clock to events with play filter markings."); - playFilter.setToolTipText(internString); - playFilter.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - firePropertyChange(PlayFilterProperty, - new Boolean(!jcb.isSelected()), - new Boolean(jcb.isSelected())); - } - }); - lgridbag.setConstraints(playFilter, c); - playFilter.setVisible(false); - leftPanel.add(playFilter); - } - - c.fill = GridBagConstraints.NONE; - c.weighty = 0f; - - JLabel dateTimeLabel = new JLabel("Date (Local Time)", SwingConstants.CENTER); - lgridbag.setConstraints(dateTimeLabel, c); - leftPanel.add(dateTimeLabel); - - timeLabel = new JLabel(NO_TIME_STRING, SwingConstants.CENTER); - Font defaultFont = timeLabel.getFont(); - timeLabel.setFont(new java.awt.Font(defaultFont.getName(), defaultFont.getStyle(), 12)); - internString = i18n.get(this.getClass(), "time", I18n.TOOLTIP, "Time"); - timeLabel.setToolTipText(internString); - lgridbag.setConstraints(timeLabel, c); - leftPanel.add(timeLabel); - - timerControl = new HotwashTimerControlButtonPanel(clock); - lgridbag.setConstraints(timerControl, c); - leftPanel.add(timerControl); - - clock.addTimeEventListener(timerControl); - - /* - * Not Used, but strangely enough needs to be created in order to tell - * the clock how fast to run, one second per clock tick. - */ - timerRateControl = new TimerRateComboBox(clock); - internString = i18n.get(this.getClass(), - "timer_rate_control", - I18n.TOOLTIP, - "Change Clock Rate For Timeline"); - timerRateControl.setToolTipText(internString); - - List timerRates = clock.getTimerRates(); - - Iterator it = timerRates.iterator(); - while (it.hasNext()) { - TimerRateHolder trh = it.next(); - timerRateControl.add(trh.getLabel(), - (int) trh.getClockInterval(), - (int) trh.getPace()); - } - - int si = timerRates.size() / 2; - if (si > 0) { - timerRateControl.setSelectedIndex(si); - } - - // lgridbag.setConstraints(timerRateControl, c); - // add(timerRateControl); - - // Right side - insets = new Insets(0, 4, 0, 4); - JPanel rightPanel = new JPanel(); - GridBagLayout rgridbag = new GridBagLayout(); - rightPanel.setLayout(rgridbag); - c = new GridBagConstraints(); - c.insets = insets; - c.fill = GridBagConstraints.NONE; - c.weighty = 0.0; - c.weightx = 0.0; - c.gridy = 0; - c.anchor = GridBagConstraints.WEST; - internString = i18n.get(this.getClass(), "mouse_time", "Mouse Time:"); - JLabel mouseTime = new JLabel(internString); - rgridbag.setConstraints(mouseTime, c); - rightPanel.add(mouseTime); - - mouseTimeLabel = new JLabel(""); - rgridbag.setConstraints(mouseTimeLabel, c); - rightPanel.add(mouseTimeLabel); - - c.anchor = GridBagConstraints.EAST; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0; - - eventDetailLabel = new JLabel("", SwingConstants.RIGHT); - rgridbag.setConstraints(eventDetailLabel, c); - rightPanel.add(eventDetailLabel); - - TimelinePanel timelinePanel = getTimelinePanel(); - timelinePanel.addMapComponent(new TimePanel.Wrapper(this)); - - c.fill = GridBagConstraints.BOTH; - c.weighty = 1f; - c.weightx = 1f; - c.gridwidth = GridBagConstraints.REMAINDER; - c.gridy = 1; - rgridbag.setConstraints(timelinePanel, c); - rightPanel.add(timelinePanel); - - TimeSliderPanel timeSliderPanel = getTimeSliderPanel(); - // Slider needs to know about the timeline to set projection - timeSliderPanel.addMapComponent(timelinePanel.getWrapper()); - c.fill = GridBagConstraints.HORIZONTAL; - c.weighty = 0f; - c.gridy = 2; - rgridbag.setConstraints(timeSliderPanel, c); - rightPanel.add(timeSliderPanel); - - GridBagLayout gridbag = new GridBagLayout(); - setLayout(gridbag); - c = new GridBagConstraints(); - c.fill = GridBagConstraints.VERTICAL; - c.weighty = 1f; - c.insets = new Insets(0, 0, 0, 0); - gridbag.setConstraints(leftPanel, c); - add(leftPanel); - - c.fill = GridBagConstraints.BOTH; - c.weightx = 1f; - c.insets = new Insets(0, 0, 4, 0); - gridbag.setConstraints(rightPanel, c); - add(rightPanel); - - revalidate(); - } - - public void updateEventDetailsDisplay(String details) { - if (eventDetailLabel != null) { - eventDetailLabel.setText(details); - } - } - - /** - * Displays the provided offset time in the Mouse Time display label. Time - * is expected to be milliseconds offset from the beginning of displayed - * time. - * - * @param mouseOffsetTime - */ - public void updateMouseTimeDisplay(long mouseOffsetTime) { - - String mtds = "--"; - - if (realTimeMode) { - if (mouseOffsetTime > timelinePanel.getTimelineLayer().getEndTime()) { - mouseOffsetTime = timelinePanel.getTimelineLayer().getEndTime(); - } - } else { - if (mouseOffsetTime < 0) { - mouseOffsetTime = 0; - } - } - - if (mouseOffsetTime >= 0) { - mtds = convertOffsetTimeToText(mouseOffsetTime); - } - - if (mouseTimeLabel != null) { - mouseTimeLabel.setText(mtds); - } - } - - public String convertOffsetTimeToText(long offsetTimeFromLeft) { - - long offsetTime = offsetTimeFromLeft; - - if(realTimeMode) { - offsetTime -= timelinePanel.getTimelineLayer().getDuration(); - } - - String sign = ""; - if(offsetTime < 0) { - sign = "-"; - offsetTime = -offsetTime; - } - int hours = (int) (offsetTime / (60 * 60 * 1000)); - int minutes = (int) Math.abs((offsetTime % (60 * 60 * 1000)) - / (60 * 1000)); - int seconds = (int) Math.abs((offsetTime % (60 * 1000)) / 1000); - - String relativeTime = sign + df.format(hours) + ":" + df.format(minutes) + ":" + df.format(seconds); - - if(realTimeMode) { - Date date = new Date(offsetTimeFromLeft + timeSliderPanel.getTimeSliderLayer().gameStartTime); - return TimePanel.dateFormat_realTime.format(date) + " (" + relativeTime + ")"; - } else { - return relativeTime; - } - } - - public void setPreferredLocation(String loc) { - preferredLocation = loc; - } - - public String getPreferredLocation() { - return preferredLocation; - } - - public void updateTime(TimeEvent te) { - - if (checkAndSetForNoTime(te)) { - return; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("TimePanel received TIMER_STATUS property update: " - + te); - } - - updateTimeLabel(te.getSystemTime(), te.getOffsetTime()); - - } - - /** - * PropertyChangeListener method called when a Clock fires, or the Clock - * time bounds change. - */ - public void propertyChange(PropertyChangeEvent pce) { - String propertyName = pce.getPropertyName(); - Object newVal = pce.getNewValue(); - - if (propertyName.equals(TimelineLayer.PlayFilterProperty)) { - timerControl.enableForwardButton(((Boolean) newVal).booleanValue()); - } else if (propertyName.equals(TimelineLayer.MouseTimeProperty)) { - updateMouseTimeDisplay(((Long) newVal).longValue()); - } else if (propertyName.equals(TimelineLayer.EventDetailsProperty)) { - updateEventDetailsDisplay((String) newVal); - } - - revalidate(); - } - - protected boolean checkAndSetForNoTime(TimeEvent te) { - - boolean isNoTime = te == TimeEvent.NO_TIME; - - if (isNoTime) { - updateEventDetailsDisplay(""); - updateMouseTimeDisplay(0l); - timeLabel.setText(NO_TIME_STRING); - } - // timerControl.setEnableState(!isNoTime); - - return isNoTime; - } - - /** - * Updates the timeLabel with the proper formats, dashes if needed. - * - * @param sysTime - * @param offsetTime - */ - public void updateTimeLabel(long sysTime, long offsetTime) { - // Do this so the label is reset if the time changes. - if (timeLabel != null) { - - if (sysTime != Long.MAX_VALUE) { - - if(realTimeMode) { - Date date = new Date(sysTime); - String timeText = TimePanel.dateFormat_realTime.format(date); - timeLabel.setText(timeText); - } else { - Date date = new Date(sysTime); - DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); - String sts = dateFormat.format(date); - - timeLabel.setText(sts + " (" - + convertOffsetTimeToText(offsetTime) + ")"); - } - } else { - timeLabel.setText(NO_TIME_STRING); - } - } - } - - public void setClock(Clock cl) { - logger.fine("found and setting clock: " + cl); - if (clock != null) { - clock.removeTimeEventListener(this); - } - clock = cl; - createInterface(); // Moved here for distributed - // configuration - if (clock != null) { - clock.addTimeEventListener(this); - } - - } - - public void setPlayFilterVisible(boolean visible) { - if (playFilter != null) { - playFilter.setVisible(visible); - } - } - - public boolean isPlayFilterVisible() { - return playFilter != null && playFilter.isVisible(); - } - - public Clock getClock() { - return clock; - } - - /** - * OMComponentPanel method, called when new components are added to the - * MapHandler. Lets the TimePanel register itself as PropertyChangeListener - * to the Clock. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof Clock) { - setClock((Clock) someObj); - getTimelinePanel().getMapHandler().add(someObj); - getTimeSliderPanel().getMapHandler().add(someObj); - } - - if (someObj instanceof OMEventSelectionCoordinator) { - getTimelinePanel().getMapHandler().add(someObj); - } - - if (someObj instanceof EventPresenter) { - getTimelinePanel().getMapHandler().add(someObj); - } - } - - /** - * OMComponentPanel method, called when new components are removed from the - * MapHandler. Lets the TimePanel unregister itself as - * PropertyChangeListener to the Clock. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof Clock && getClock() == someObj) { - setClock(null); - } - } - - public static class Wrapper { - TimePanel timePanel; - - public Wrapper(TimePanel panel) { - this.timePanel = panel; - } - - public TimePanel getTimePanel() { - return timePanel; - } - } - - public String getParentName() { - return parentName; - } - - public void setParentName(String pName) { - parentName = pName; - } - - public TimelinePanel getTimelinePanel() { - if (timelinePanel == null) { - timelinePanel = new TimelinePanel(); - timelinePanel.setRealTimeMode(realTimeMode); - } - return timelinePanel; - } - - public TimeSliderPanel getTimeSliderPanel() { - if (timeSliderPanel == null) { - timeSliderPanel = new TimeSliderPanel(realTimeMode); - } - return timeSliderPanel; - } - - public void setUserHasChangedScale(boolean userHasChangedScale) { - timeSliderPanel.setUserHasChangedScale(userHasChangedScale); - } - - public void addTimeBoundsUserActionsListener( - ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeSliderPanel.addTimeBoundsUserActionsListener(timeBoundsUserActionsListener); - } - - public void removeTimeBoundsUserActionsListener( - ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeSliderPanel.removeTimeBoundsUserActionsListener(timeBoundsUserActionsListener); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderLayer.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderLayer.java deleted file mode 100644 index 8cfe2783b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderLayer.java +++ /dev/null @@ -1,1060 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// - -package com.bbn.openmap.gui.time; - -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Polygon; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.event.ZoomSupport; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.proj.Cartesian; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.time.Clock; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.time.TimeBoundsEvent; -import com.bbn.openmap.time.TimeBoundsListener; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.time.TimerStatus; -import com.bbn.openmap.tools.icon.BasicIconPart; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.util.MoreMath; - -/** - * Timeline layer - * - * Render events and allow for their selection on a variable-scale timeline - */ -public class TimeSliderLayer - extends OMGraphicHandlerLayer - implements PropertyChangeListener, MapMouseListener, ComponentListener, TimeBoundsListener, TimeEventListener { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimeSliderLayer"); - - protected CenterSupport centerDelegate; - - protected ZoomSupport zoomDelegate; - - long currentTime = 0; - - long gameStartTime = 0; - - long gameEndTime = 0; - - // KMTODO package this up into a standalone widget? - // Times are generally in minutes - double selectionWidthMinutes = 1.0; - double maxSelectionWidthMinutes = 1.0; - - double selectionCenter = 0; - - OMRect boundsRectLeftHandle; // handles for scaling selection - - OMRect boundsRectRightHandle; - - Color selectionPointLineColor = TimelineLayer.tint; - Color selectionPointFillColor = TimelineLayer.tint; - Color leftHandleFillColor = Color.black; - Color rightHandleFillColor = Color.black; - - OMLine baseLine; // thick line along middle - - OMPoly contextPoly; // lines that relate time slider to timeline above. - - int sliderPointHalfWidth = 5; - - TimelinePanel timelinePanel; - TimelineLayer timelineLayer; - - public static double magicScaleFactor = 100000000; // KMTODO (Don? I guess - // this is to - // address a precision issue?) - - Clock clock; - - LabelPanel labelPanel; - - private boolean isNoTime = true; - - // In realTimeMode, gameEndTime is the origin, rather than gameStartTime - private final boolean realTimeMode; - - // Used to refrain from re-scaling every TimeBoundsUpdate (in realTimeMode - // only) - private boolean userHasChangedScale = false; - - private final List timeBoundsUserActionsListeners = - new ArrayList(); - - private final JButton zoomToSelection = new JButton("Zoom to Selection"); - private final JButton renderFixedSelection = new JButton("Show Entire Selection"); - - /** - * Construct the TimelineLayer. - * - * @param realTimeMode TODO - */ - public TimeSliderLayer(boolean realTimeMode) { - this.realTimeMode = realTimeMode; - setName("TimeSlider"); - - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, false)); - // Making the setting so this layer receives events from the - // SelectMouseMode, which has a modeID of "Gestures". Other - // IDs can be added as needed. - setMouseModeIDsForEvents(new String[] { - "Gestures" - }); - - centerDelegate = new CenterSupport(this); - zoomDelegate = new ZoomSupport(this); - addComponentListener(this); - } - - public void findAndInit(Object someObj) { - if (someObj instanceof Clock) { - clock = ((Clock) someObj); - clock.addTimeEventListener(this); - clock.addTimeBoundsListener(this); - - gameStartTime = ((Clock) someObj).getStartTime(); - gameEndTime = ((Clock) someObj).getEndTime(); - - // Just in case we missed an early TimeBoundEvent - updateTimeBounds(gameStartTime, gameEndTime); - } - if (someObj instanceof CenterListener) { - centerDelegate.add((CenterListener) someObj); - } - if (someObj instanceof ZoomListener) { - zoomDelegate.add((ZoomListener) someObj); - } - if (someObj instanceof TimelinePanel.Wrapper) { - timelinePanel = ((TimelinePanel.Wrapper) someObj).getTimelinePanel(); - timelinePanel.getMapBean().addPropertyChangeListener(this); - timelineLayer = timelinePanel.getTimelineLayer(); - } - } - - /** - * Called with the projection changes, should just generate the current - * markings for the new projection. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList list = getList(); - - if (list == null) { - list = new OMGraphicList(); - } else { - list.clear(); - } - - TimeDrape drape = new TimeDrape(0, 0, -1, -1); - drape.setVisible(isNoTime); - drape.setFillPaint(Color.gray); - drape.generate(getProjection()); - list.add(drape); - - list.add(getControlWidgetList(getProjection())); - - return list; - } - - /** - * All we want to do here is reset the current position of all of the - * widgets, and generate them with the projection for the new position. After - * this call, the widgets are ready to paint. - */ - public synchronized OMGraphicList getControlWidgetList(Projection proj) { - - Projection projection = getProjection(); - - OMGraphicList controlWidgetList = new OMGraphicList(); - - // triangle indicating center of selection - ImageIcon selectionPointImage; - - DrawingAttributes da = new DrawingAttributes(); - - da.setFillPaint(selectionPointFillColor); - da.setLinePaint(selectionPointLineColor); - IconPart ip = new BasicIconPart(new Polygon(new int[] { - 50, - 90, - 10, - 50 - }, new int[] { - 10, - 90, - 90, - 10 - }, 4), da); - - selectionPointImage = OMIconFactory.getIcon(32, 32, ip); - OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, 0, 6, selectionPointImage, 1.0f); - final float selectionPointScale = 1.8f; - selectionPoint.setMaxScale(selectionPointScale); - selectionPoint.setMinScale(selectionPointScale); - controlWidgetList.add(selectionPoint); - - boundsRectLeftHandle = new OMRect(0, 0, 0, 0); - boundsRectLeftHandle.setFillPaint(leftHandleFillColor); - controlWidgetList.add(boundsRectLeftHandle); - - boundsRectRightHandle = new OMRect(0, 0, 0, 0); - boundsRectRightHandle.setFillPaint(rightHandleFillColor); - controlWidgetList.add(boundsRectRightHandle); - - int[] xs = new int[8]; - int[] ys = new int[8]; - contextPoly = new OMPoly(xs, ys); - contextPoly.setFillPaint(Color.white); - controlWidgetList.add(contextPoly); - - baseLine = new OMLine(0, 0, 0, 0); - baseLine.setLinePaint(Color.black); - baseLine.setStroke(new BasicStroke(2)); - controlWidgetList.add(baseLine); - - if (projection == null) { - return controlWidgetList; // Huhn? - } - - double screenWidth = projection.getWidth(); - float scale = - (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); - Point2D projCenter = projection.getCenter(); - - // TODO reconsider proper test here - for the moment, just brute-force - // reproject always - if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { - double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; - projCenter.setLocation(nCenterLon, 0); - projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); - setProjection(projection); - } - - // Reset primary handle - int contextBuffer = (int) (projection.getHeight() * .4); - - // If 'selectionCenter' is outside current time bounds, first attempt to - // recompute from currentTime - if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { - selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); - } - - // And if _that_ fails, just clamp - // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because - // Java 5 doesn't have MINUTE - if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { - selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); - } - - if (selectionCenter < 0) { - selectionCenter = 0; - } - - int x = (int) projection.forward(0, selectionCenter).getX(); - - // Reset bounds and handles - - Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); - Point2D origin = projection.forward(0, 0); - int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); - - int north = contextBuffer; - int west = x - selectionHalfWidth; - int south = projection.getHeight() - 1; - int east = x + selectionHalfWidth; - int mid = contextBuffer + 1 + (south - contextBuffer) / 2; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x - + ", origin:" + origin); - logger.fine(" projection:" + projection); - } - - selectionPoint.setLon((float) selectionCenter); - selectionPoint.generate(projection); - - // and the two handles for the bounds - - int handleWest = west - sliderPointHalfWidth; - int handleEast = west + sliderPointHalfWidth; - - final int sliderPointHalfHeight = 2; - - boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); - boundsRectLeftHandle.generate(projection); - - handleWest = east - sliderPointHalfWidth; - handleEast = east + sliderPointHalfWidth; - - boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); - boundsRectRightHandle.generate(projection); - - // and the context lines, that show how the current selection maps to - // the timeline above - - xs = contextPoly.getXs(); - ys = contextPoly.getYs(); - - xs[0] = 0; - ys[0] = -1; - xs[1] = 0; - ys[1] = north; - xs[2] = west; - ys[2] = north; - xs[3] = west; - ys[3] = south; - xs[4] = east; - ys[4] = south; - xs[5] = east; - ys[5] = north; - xs[6] = projection.getWidth() - 1; - ys[6] = north; - xs[7] = projection.getWidth() - 1; - ys[7] = -1; - contextPoly.generate(projection); - - baseLine.setPts(new int[] { - 0, - mid, - projection.getWidth(), - mid - }); - baseLine.generate(projection); - - return controlWidgetList; - } - - protected void updateTimeline() { - if (timelinePanel != null) { - float scale = (float) (magicScaleFactor * selectionWidthMinutes / getProjection().getWidth()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Updating timeline with scale: " + scale); - } - timelinePanel.getMapBean().setScale(scale); - } - } - - public String getName() { - return "TimelineLayer"; - } - - public void setSelectionPointFillColor(Color color) { - selectionPointFillColor = color; - } - - public void setSelectionPointLineColor(Color color) { - selectionPointLineColor = color; - } - - public void setLeftHandleFillColor(Color color) { - leftHandleFillColor = color; - } - - public void setRightHandleFillColor(Color color) { - rightHandleFillColor = color; - } - - /** - * Updates zoom and center listeners with new projection information. - * - */ - protected void finalizeProjection() { - Projection projection = getProjection(); - Cartesian cartesian = (projection instanceof Cartesian) ? (Cartesian) projection : null; - - if (cartesian != null) { - - double screenWidth = cartesian.getWidth(); - cartesian.setLeftLimit(TimelineLayer.forwardProjectMillis(gameStartTime)); - cartesian.setRightLimit(TimelineLayer.forwardProjectMillis(gameEndTime)); - cartesian.setLimitAnchorPoint(new Point2D.Double(TimelineLayer.forwardProjectMillis(-gameStartTime), 0)); - - float scale = - (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); - - zoomDelegate.fireZoom(ZoomEvent.ABSOLUTE, scale); - - double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; - - logger.fine("Telling the center delegate that the new center is 0, " + nCenterLon); - - centerDelegate.fireCenter(0, nCenterLon); - - // We are getting really large values for the center point of the - // projection that the layer knows about. The MapBean projection - // gets set OK, but then the projection held by the layer wrong, and - // it throws the whole widget out of wack. If we set - // the center of the projection to what it should be (the center - // point between the start and end times), then everything settles - // out. - double x = cartesian.getCenter().getX(); - if (!MoreMath.approximately_equal(x, nCenterLon)) { - ((MapBean) ((MapHandler) getBeanContext()).get(MapBean.class)).setCenter(0, nCenterLon); - } - - repaint(); - } - } - - public void updateTime(TimeEvent te) { - - if (checkAndSetForNoTime(te)) { - return; - } - - TimerStatus timerStatus = te.getTimerStatus(); - - if (timerStatus.equals(TimerStatus.STEP_FORWARD) || timerStatus.equals(TimerStatus.STEP_BACKWARD) - || timerStatus.equals(TimerStatus.UPDATE)) { - - currentTime = te.getSystemTime(); - currentTime -= gameStartTime; - - selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); - doPrepare(); - } - - if (timerStatus.equals(TimerStatus.FORWARD) || timerStatus.equals(TimerStatus.BACKWARD) - || timerStatus.equals(TimerStatus.STOPPED)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("updated time: " + te); - } - // Checking for a running clock prevents a time status - // update after the clock is stopped. The - // AudioFileHandlers don't care about the current time - // if it isn't running. - if (realTimeMode || ((Clock) te.getSource()).isRunning()) { - // update(te.getSystemTime()); - currentTime = te.getSystemTime(); - currentTime -= gameStartTime; - - selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); - doPrepare(); - } - } - - } - - /* - * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - if (propertyName == MapBean.ProjectionProperty) { - // This property should be from the TimelineLayer's MapBean, solely - // for the scale measurement. - logger.fine(propertyName + " from " + evt.getSource()); - Projection timeLineProj = (Projection) evt.getNewValue(); - // Need to solve for selectionWidthMinutes - if (!realTimeMode || !userHasChangedScale) { - selectionWidthMinutes = timeLineProj.getScale() * getProjection().getWidth() / magicScaleFactor; - } - - if (selectionWidthMinutes > maxSelectionWidthMinutes + .0001 - /* || selectionWidthMinutes < .0001 */) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("resetting selectionWidthMinutes to max (projection change property change), was " - + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); - } - selectionWidthMinutes = maxSelectionWidthMinutes; - } - - doPrepare(); - } - } - - public boolean getUserHasChangedScale() { - return userHasChangedScale; - } - - public void setUserHasChangedScale(boolean userHasChangedScale) { - this.userHasChangedScale = userHasChangedScale; - } - - protected boolean checkAndSetForNoTime(TimeEvent te) { - isNoTime = te == TimeEvent.NO_TIME; - return isNoTime; - } - - public MapMouseListener getMapMouseListener() { - return this; - } - - public String[] getMouseModeServiceList() { - return getMouseModeIDsForEvents(); - } - - enum DragState { - NONE, PRIMARY_HANDLE, LEFT_HANDLE, RIGHT_HANDLE - } - - DragState dragState = DragState.NONE; - - public boolean mousePressed(MouseEvent e) { - updateMouseTimeDisplay(e); - clearFixedRenderRange(); - int x = e.getPoint().x; - int y = e.getPoint().y; - - if (boundsRectLeftHandle.contains(x, y)) { - dragState = DragState.LEFT_HANDLE; - userHasChangedScale = true; - } else if (boundsRectRightHandle.contains(x, y)) { - dragState = DragState.RIGHT_HANDLE; - userHasChangedScale = true; - } else { - dragState = DragState.PRIMARY_HANDLE; - Projection projection = getProjection(); - - if (projection != null) { - Point2D invPnt = projection.inverse(x, y); - setSelectionCenter(invPnt.getX()); - updateTimeline(); - } - } - return true; - } - - public boolean mouseReleased(MouseEvent e) { - updateMouseTimeDisplay(e); - dragState = DragState.NONE; - return false; - } - - public boolean mouseClicked(MouseEvent e) { - updateMouseTimeDisplay(e); - return false; - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - timelineLayer.updateMouseTimeDisplay(new Long(-1)); - } - - void setSelectionCenter(double newCenter) { - - selectionCenter = newCenter; - - if (selectionCenter < 0) { - selectionCenter = 0; - } - - double offsetEnd = (double) (gameEndTime - gameStartTime) / 1000.0 / 60.0; - - if (selectionCenter > offsetEnd) { - selectionCenter = offsetEnd; - } - - clock.setTime(gameStartTime + (long) (selectionCenter * 60 * 1000)); - } - - public boolean mouseDragged(MouseEvent e) { - updateMouseTimeDisplay(e); - Projection projection = getProjection(); - - if (projection == null) { - return false; // Huhn? - } - - double worldMouse; - Point2D invPnt; - int x = e.getPoint().x; - int y = e.getPoint().y; - int selectionCenterX = (int) projection.forward(0, selectionCenter).getX(); - boolean scaleChange = false; - - switch (dragState) { - - case PRIMARY_HANDLE: - invPnt = projection.inverse(x, y); - setSelectionCenter(invPnt.getX()); - break; - - case LEFT_HANDLE: - - if (x >= selectionCenterX - sliderPointHalfWidth) { - x = selectionCenterX - sliderPointHalfWidth; - } - - invPnt = projection.inverse(x, y); - worldMouse = invPnt.getX(); - selectionWidthMinutes = 2 * (selectionCenter - worldMouse); - scaleChange = true; - break; - - case RIGHT_HANDLE: - - if (x <= selectionCenterX + sliderPointHalfWidth) { - x = selectionCenterX + sliderPointHalfWidth; - } - invPnt = projection.inverse(x, y); - worldMouse = invPnt.getX(); - selectionWidthMinutes = 2 * (worldMouse - selectionCenter); - scaleChange = true; - break; - } - - if(scaleChange) { - if (selectionWidthMinutes > maxSelectionWidthMinutes) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("resetting selectionWidthMinutes to max, was " + selectionWidthMinutes + ", now " - + maxSelectionWidthMinutes); - } - selectionWidthMinutes = maxSelectionWidthMinutes; - } - updateTimeline(); - timelineLayer.doPrepare(); - } - - doPrepare(); - - return true; - } - - public boolean mouseMoved(MouseEvent e) { - updateMouseTimeDisplay(e); - return true; - } - - public void mouseMoved() { - } - - protected double updateMouseTimeDisplay(MouseEvent e) { - Projection proj = getProjection(); - Point2D latLong = proj.inverse(e.getPoint()); - double lon = latLong.getX(); - double endTime = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); - if (lon < 0) { - lon = 0; - } else if (lon > endTime) { - lon = endTime; - } - - long offsetMillis = TimelineLayer.inverseProjectMillis(lon); - - timelineLayer.updateMouseTimeDisplay(new Long(offsetMillis)); - - return lon; - } - - public void componentHidden(ComponentEvent e) { - } - - public void componentMoved(ComponentEvent e) { - } - - public void componentResized(ComponentEvent e) { - finalizeProjection(); - } - - public void componentShown(ComponentEvent e) { - } - - public LabelPanel getTimeLabels() { - if (labelPanel == null) { - labelPanel = new LabelPanel(); - } - return labelPanel; - } - - public void updateTimeLabels(long startTime, long endTime) { - LabelPanel lp = getTimeLabels(); - lp.updateTimeLabels(startTime, endTime); - } - - class LabelPanel - extends JPanel - implements com.bbn.openmap.gui.MapPanelChild { - protected JComponent timeStartLabel; - protected JComponent timeEndLabel; - public final static String NO_TIME_STRING = "--/--/-- (--:--:--)"; - - public LabelPanel() { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - if (realTimeMode) { - JButton timeStartLabelButton = new JButton(NO_TIME_STRING); - timeStartLabelButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.invokeDateSelectionGUI(false); - } - } - - }); - timeStartLabel = timeStartLabelButton; - Font f = timeStartLabel.getFont(); - f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); - timeStartLabel.setFont(f); - gridbag.setConstraints(timeStartLabel, c); - add(timeStartLabel); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - JLabel buffer = new JLabel(); - gridbag.setConstraints(buffer, c); - add(buffer); - - renderFixedSelection.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - long selectionStart = timelineLayer.getSelectionStart(); - long selectionEnd = timelineLayer.getSelectionEnd(); - if (selectionStart > 0 && selectionEnd > 0) { - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.setFixedRenderRange(selectionStart, selectionEnd); - } - } - } - - }); - - renderFixedSelection.setEnabled(false); - renderFixedSelection.setFont(f); - c.weightx = 0f; - gridbag.setConstraints(renderFixedSelection, c); - add(renderFixedSelection); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - buffer = new JLabel(); - gridbag.setConstraints(buffer, c); - add(buffer); - - zoomToSelection.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - long selectionStart = timelineLayer.getSelectionStart(); - long selectionEnd = timelineLayer.getSelectionEnd(); - if (selectionStart > 0 && selectionEnd > 0) { - timelineLayer.clearSelection(); - userHasChangedScale = false; - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.setTimeBounds(selectionStart, selectionEnd); - } - updateTimeBounds(selectionStart, selectionEnd); - updateTimeline(); - } - } - - }); - zoomToSelection.setEnabled(false); - zoomToSelection.setFont(f); - c.weightx = 0f; - gridbag.setConstraints(zoomToSelection, c); - add(zoomToSelection); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - buffer = new JLabel(); - gridbag.setConstraints(buffer, c); - add(buffer); - - JButton jumpToRealTime = new JButton("Jump to Real Time"); - jumpToRealTime.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - userHasChangedScale = false; - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.jumpToRealTime(); - } - updateTimeline(); - } - - }); - jumpToRealTime.setFont(f); - c.weightx = 0f; - gridbag.setConstraints(jumpToRealTime, c); - add(jumpToRealTime); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - buffer = new JLabel(); - gridbag.setConstraints(buffer, c); - add(buffer); - - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - JButton timeEndLabelButton = new JButton(NO_TIME_STRING); - timeEndLabelButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.invokeDateSelectionGUI(true); - } - } - - }); - timeEndLabel = timeEndLabelButton; - timeEndLabel.setFont(f); - gridbag.setConstraints(timeEndLabel, c); - add(timeEndLabel); - } else { - timeStartLabel = new JLabel(NO_TIME_STRING); - Font f = timeStartLabel.getFont(); - f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); - timeStartLabel.setFont(f); - gridbag.setConstraints(timeStartLabel, c); - add(timeStartLabel); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - JLabel buffer = new JLabel(); - gridbag.setConstraints(buffer, c); - add(buffer); - - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - timeEndLabel = new JLabel(NO_TIME_STRING, JLabel.RIGHT); - timeEndLabel.setFont(f); - gridbag.setConstraints(timeEndLabel, c); - add(timeEndLabel); - } - } - - public String getPreferredLocation() { - return BorderLayout.SOUTH; - } - - public void setPreferredLocation(String string) { - } - - public void updateTimeLabels(long startTime, long endTime) { - if (realTimeMode) { - ((JButton) timeStartLabel).setText(getLabelStringForTime(startTime)); - ((JButton) timeEndLabel).setText(getLabelStringForTime(endTime)); - } else { - ((JLabel) timeStartLabel).setText(getLabelStringForTime(startTime)); - ((JLabel) timeEndLabel).setText(getLabelStringForTime(endTime)); - } - } - - public String getLabelStringForTime(long time) { - String ret = NO_TIME_STRING; - if (time != Long.MAX_VALUE && time != Long.MIN_VALUE) { - Date date = new Date(time); - ret = TimePanel.dateFormat.format(date); - } - return ret; - - } - - public String getParentName() { - // TODO Auto-generated method stub - return null; - } - } - - public void paint(Graphics g) { - try { - super.paint(g); - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - logger.warning(e.getMessage()); - e.printStackTrace(); - } - } - } - - public static class TimeDrape - extends OMRect { - int lo; - int to; - int ro; - int bo; - - public TimeDrape(int leftOffset, int topOffset, int rightOffset, int bottomOffset) { - super(0, 0, 0, 0); - lo = leftOffset; - to = topOffset; - ro = rightOffset; - bo = bottomOffset; - } - - public boolean generate(Projection proj) { - setLocation(0 + lo, 0 + to, proj.getWidth() + ro, proj.getHeight() + bo); - return super.generate(proj); - } - - } - - public void updateTimeBounds(TimeBoundsEvent tbe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("updating time bounds: " + tbe); - } - TimeBounds timeBounds = (TimeBounds) tbe.getNewTimeBounds(); - - if (timeBounds != null) { - updateTimeBounds(timeBounds.getStartTime(), timeBounds.getEndTime()); - } else { - // TODO handle when time bounds are null, meaning when no time - // bounds providers are active. - } - } - - public void updateTimeBounds(long start, long end) { - - // Recall that currentTime is in relative space (assumes start == 0) - long boundsStartOffset = start - gameStartTime; - currentTime -= boundsStartOffset; - selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); - - gameStartTime = start; - gameEndTime = end; - - updateTimeLabels(gameStartTime, gameEndTime); - - // DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy - // HH:mm:ss"); - // Date date = new Date(gameStartTime); - // String sts = dateFormat.format(date); - // date.setTime(gameEndTime); - // String ets = dateFormat.format(date); - - maxSelectionWidthMinutes = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); - if (realTimeMode && !userHasChangedScale) { - selectionWidthMinutes = maxSelectionWidthMinutes; - } else { - if (selectionWidthMinutes > maxSelectionWidthMinutes || selectionWidthMinutes < .0001) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("resetting selectionWidthMinutes to max (time bounds property change), was " + selectionWidthMinutes - + ", now " + maxSelectionWidthMinutes); - } - selectionWidthMinutes = maxSelectionWidthMinutes; - } - } - - finalizeProjection(); - updateTimeline(); - doPrepare(); - repaint(); - } - - /** - * Treat mouse wheel rotations like slider-handle drags. - * - * @param rot The number of rotation clicks (positive for zoom in, negative - * for zoom out). - */ - public void adjustZoomFromMouseWheel(int rot) { - Projection projection = getProjection(); - - if (projection == null) { - return; // Huhn? - } - - setUserHasChangedScale(true); - - // Determine the effect of growing / shrinking the slider scale by 'rot' - // pixels - // So given current selection width (in minutes) and minutes-per-pixel, - // just - // apply rot as a delta - - Point2D minutesPnt0 = projection.inverse(0, 0); - Point2D minutesPnt1 = projection.inverse(1, 0); - - double minutesPerPixel = minutesPnt1.getX() - minutesPnt0.getX(); - double minSelectionWidthMinutes = minutesPerPixel * sliderPointHalfWidth * 2; - double selectionWidthPixels = selectionWidthMinutes / minutesPerPixel; - double multiplier = selectionWidthPixels / 40; - - // Use a multiplier - selectionWidthMinutes += rot * minutesPerPixel * multiplier; - - if (selectionWidthMinutes < minSelectionWidthMinutes) { - selectionWidthMinutes = minSelectionWidthMinutes; - } - - if (selectionWidthMinutes > maxSelectionWidthMinutes) { - selectionWidthMinutes = maxSelectionWidthMinutes; - } - - updateTimeline(); - - doPrepare(); - } - - public void addTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeBoundsUserActionsListeners.add(timeBoundsUserActionsListener); - } - - public void removeTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeBoundsUserActionsListeners.remove(timeBoundsUserActionsListener); - } - - public void clearFixedRenderRange() { - for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { - listener.clearFixedRenderRange(); - } - } - - void setSelectionValid(boolean valid) { - zoomToSelection.setEnabled(valid); - renderFixedSelection.setEnabled(valid); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderPanel.java deleted file mode 100644 index 9dc7dd8d7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimeSliderPanel.java +++ /dev/null @@ -1,93 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: TimeSliderPanel.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/09/25 17:31:26 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.event.MouseWheelEvent; -import java.awt.geom.Point2D; - -import javax.swing.BorderFactory; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.proj.Cartesian; - -public class TimeSliderPanel extends BasicMapPanel { - protected TimeSliderLayer timeSliderLayer; - - public TimeSliderPanel(boolean realTimeMode) { - super(true); - setLayout(new BorderLayout()); - Cartesian cartesian = new Cartesian(new Point2D.Double(), 300000f, 600, 20); - MapBean mapBean = getMapBean(); - mapBean.setProjection(cartesian); - mapBean.setMinimumSize(new Dimension(10, 20)); - mapBean.setBorder(BorderFactory.createEmptyBorder()); - mapBean.setBckgrnd(getBackground()); - - MapHandler mh = getMapHandler(); - mh.add(new com.bbn.openmap.LayerHandler()); - mh.add(new com.bbn.openmap.MouseDelegator()); - mh.add(new TimeSliderMouseMode()); - - timeSliderLayer = new TimeSliderLayer(realTimeMode); - mh.add(timeSliderLayer); - mh.add(timeSliderLayer.getTimeLabels()); - } - - public TimeSliderLayer getTimeSliderLayer() { - return timeSliderLayer; - } - - public void setTimeSliderLayer(TimeSliderLayer timeSliderLayer) { - this.timeSliderLayer = timeSliderLayer; - } - - public static class TimeSliderMouseMode extends - com.bbn.openmap.event.SelectMouseMode { - public TimeSliderMouseMode() { - super(); - } - - public void mouseWheelMoved(MouseWheelEvent e) {} - - } - - public void addTimeBoundsUserActionsListener( - ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeSliderLayer.addTimeBoundsUserActionsListener(timeBoundsUserActionsListener); - } - - public void removeTimeBoundsUserActionsListener( - ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { - timeSliderLayer.removeTimeBoundsUserActionsListener(timeBoundsUserActionsListener); - } - - public void setUserHasChangedScale(boolean userHasChangedScale) { - timeSliderLayer.setUserHasChangedScale(userHasChangedScale); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimelineLayer.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimelineLayer.java deleted file mode 100644 index 606191639..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimelineLayer.java +++ /dev/null @@ -1,1771 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -package com.bbn.openmap.gui.time; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.CenterSupport; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.event.OMEventSelectionCoordinator; -import com.bbn.openmap.gui.event.AbstractEventPresenter; -import com.bbn.openmap.gui.event.EventPresenter; -import com.bbn.openmap.gui.time.TimeSliderLayer.TimeDrape; -import com.bbn.openmap.gui.time.TimelineLayer.SelectionArea.PlayFilterSection; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.StandardPCPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Cartesian; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.time.Clock; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.time.TimeBoundsEvent; -import com.bbn.openmap.time.TimeBoundsListener; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.time.TimerStatus; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.icon.BasicIconPart; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.OMIconFactory; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.GridLayout; -import java.awt.Polygon; -import java.awt.Rectangle; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; - -/** - * Timeline layer - * - * Render events and allow for their selection on a variable-scale time line. - */ -public class TimelineLayer - extends OMGraphicHandlerLayer - implements - ActionListener, DrawingToolRequestor, PropertyChangeListener, - MapMouseListener, ComponentListener, TimeBoundsListener, - TimeEventListener { - - /** - * This property is used to signify whether any OMEvents have been designated as play filterable, so GUI controls - * for the play filter can be enabled/disabled. - */ - public final static String PlayFilterProperty = "playfilter"; - /** - * This property is used to send the current offset time where the mouse is over the timeline. - */ - public final static String MouseTimeProperty = "mouseTime"; - /** - * This property is used to send event details that can be displayed when the mouse is over an event in the - * timeline. - */ - public final static String EventDetailsProperty = "eventDetails"; - /** - * This property is used to notify listeners that the time projection parameters have changed, and they need to - * contact this object to figure out how to display those changes. - */ - public final static String TimeParametersProperty = "timeParameters"; - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimelineLayer"); - - protected OMGraphicList eventGraphicList = null; - protected OMGraphicList timeLinesList = null; - protected PlayFilter playFilter = new PlayFilter(); - protected OMGraphicList ratingAreas = new OMGraphicList(); - protected SelectionArea selectionRect; - protected TimeSliderLayer.TimeDrape drape; - protected CenterSupport centerDelegate; - - private TimeSliderLayer timeSliderLayer; - - long currentTime = 0; - long gameStartTime = 0; - long gameEndTime = 0; - - protected EventPresenter eventPresenter; - protected OMEventSelectionCoordinator aesc; - protected static Color tint = new Color(0x99000000, true); - - protected Clock clock; - private boolean realTimeMode; - private boolean isNoTime = true; - - private Timer scrollTimer = new Timer(); - private ScrollTask scrollTask = null; - - /** - * Construct the TimelineLayer. - */ - public TimelineLayer() { - setName("Timeline"); - - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. -// setProjectionChangePolicy(new NullProjectionChangePolicy(this)); - setProjectionChangePolicy(new StandardPCPolicy(this, false)); - // Making the setting so this layer receives events from the - // SelectMouseMode, which has a modeID of "Gestures". Other - // IDs can be added as needed. - setMouseModeIDsForEvents(new String[]{"Gestures"}); - - centerDelegate = new CenterSupport(this); - addComponentListener(this); - - drape = new TimeDrape(0, 0, -1, -1); - drape.setFillPaint(Color.gray); - drape.setVisible(true); - - } - - public void findAndInit(Object someObj) { - if (someObj instanceof Clock) { - clock = (Clock) someObj; - // clock.addPropertyChangeListener(Clock.TIMER_STATUS_PROPERTY, - // this); - clock.addTimeEventListener(this); - clock.addTimeBoundsListener(this); - setTimeBounds(clock.getStartTime(), clock.getEndTime()); - } - if (someObj instanceof CenterListener) { - centerDelegate.add((CenterListener) someObj); - } - if (someObj instanceof EventPresenter) { - eventPresenter = (EventPresenter) someObj; - selectionRect = null; - eventPresenter.addPropertyChangeListener(this); - } - if (someObj instanceof OMEventSelectionCoordinator) { - aesc = (OMEventSelectionCoordinator) someObj; - aesc.addPropertyChangeListener(this); - } - if (someObj instanceof TimePanel.Wrapper) { - TimePanel tp = ((TimePanel.Wrapper) someObj).getTimePanel(); - tp.addPropertyChangeListener(this); - addPropertyChangeListener(tp); - timeSliderLayer = tp.getTimeSliderPanel().getTimeSliderLayer(); - } - } - - public void findAndUndo(Object someObj) { - if (someObj == clock) { - // clock.removePropertyChangeListener(Clock.TIMER_STATUS_PROPERTY, - // this); - clock.removeTimeEventListener(this); - clock.removeTimeBoundsListener(this); - } - if (someObj instanceof CenterListener) { - centerDelegate.remove((CenterListener) someObj); - } - if (someObj == eventPresenter) { - eventPresenter.removePropertyChangeListener(this); - eventPresenter = null; - } - if (someObj == aesc) { - aesc.removePropertyChangeListener(this); - aesc = null; - } - if (someObj instanceof TimePanel.Wrapper) { - TimePanel tp = ((TimePanel.Wrapper) someObj).getTimePanel(); - removePropertyChangeListener(tp); - tp.removePropertyChangeListener(this); - } - } - - public static double forwardProjectMillis(long time) { - return (double) time / 60000f; // 60000 millis per minute - } - - public static long inverseProjectMillis(double timef) { - return (long) (timef * 60000f); // 60000 millis per minute - } - - /** - * Creates the OMGraphic list with the time and event markings. - */ - public synchronized OMGraphicList prepare() { - - Projection proj = getProjection(); - if (logger.isLoggable(Level.FINER)) { - logger.finer("Updating projection with " + proj); - } - - OMGraphicList graphicList = getList(); - if (getHeight() > 0) { - if (graphicList == null) { - graphicList = new OMGraphicList(); - } else { - graphicList.clear(); - } - - drape = new TimeDrape(0, 0, -1, -1); - drape.setFillPaint(Color.gray); - drape.setVisible(isNoTime); - drape.generate(proj); - graphicList.add(drape); - - graphicList.add(constructTimeLines(proj)); - graphicList.add(getCurrentTimeMarker(proj)); - - OMGraphicList eventGraphicList = realTimeMode ? null : getEventGraphicList(); - - // if new events are fetched, new rating areas and play filters are - // created here. - if (eventGraphicList == null || eventGraphicList.isEmpty()) { - eventGraphicList = getEventList(proj); - setEventGraphicList(eventGraphicList); - } else { - if (logger.isLoggable(Level.FINER)) { - logger.finer("don't need to re-create event lines, haven't changed with (" - + eventGraphicList.size() + ") events"); - } - // TODO Don, why does this not seem to place event markers properly if time is advancing? - eventGraphicList.generate(proj); - } - - ratingAreas.generate(proj); - playFilter.generate(proj); - - graphicList.add(playFilter); - graphicList.add(eventGraphicList); - SelectionArea selectionRenderRect = getSelectionRectangle(proj); - if (selectionRenderRect != null) { - graphicList.add(selectionRenderRect); - } - graphicList.add(ratingAreas); - } - - return graphicList; - } - - public synchronized OMGraphicList getEventGraphicList() { - return eventGraphicList; - } - - public synchronized void setEventGraphicList(OMGraphicList eventGraphicList) { - this.eventGraphicList = eventGraphicList; - } - - protected TimeHashFactory timeHashFactory; - - /** - * - * @return OMGraphicList new graphic list - */ - protected OMGraphicList constructTimeLines(Projection projection) { - - // if (timeLinesList == null) { - OMGraphicList tll = new OMGraphicList(); - - timeHashFactory = new TimeHashFactory(); - - tll.add(timeHashFactory.getHashMarks(projection, realTimeMode, gameStartTime)); - - if (!isNoTime) { - preTime = new SelectionArea.PreTime(0); - preTime.generate(projection); - tll.add(preTime); - - postTime = new SelectionArea.PostTime(gameEndTime - gameStartTime); - postTime.generate(projection); - tll.add(postTime); - } - - timeLinesList = tll; - - return tll; - } - - public SelectionArea getSelectionRectangle() { - return selectionRect; - } - - public SelectionArea getSelectionRectangle(Projection proj) { - SelectionArea selectRect = getSelectionRectangle(); - - if (selectRect == null) { - selectionRect = new SelectionArea(); - selectRect = selectionRect; - if (eventPresenter != null) { - selectRect.setFillPaint(eventPresenter.getSelectionDrawingAttributes().getSelectPaint()); - } - } - - if (selectRect.isVisible()) { - // Make a temp copy, just for painting during this render frame - SelectionArea selectionRectToRender = new SelectionArea(); - if (eventPresenter != null) { - selectionRectToRender.setFillPaint(eventPresenter.getSelectionDrawingAttributes().getSelectPaint()); - } - selectionRectToRender.setLocation(selectRect.getWestLon(), selectRect.getEastLon()); - selectionRectToRender.generate(proj); - return selectionRectToRender; - } else { - // Not visible, so don't bother sticking it on the list - return null; - } - } - - protected OMGraphicList currentTimeMarker; - protected SelectionArea.PreTime preTime; - protected SelectionArea.PostTime postTime; - - protected OMGraphic getCurrentTimeMarker(Projection proj) { - currentTimeMarker = new CurrentTimeMarker(); - currentTimeMarker.generate(proj); - return currentTimeMarker; - } - - protected final static String ATT_KEY_EVENT = "att_key_event"; - - protected OMGraphicList getEventList(Projection projection) { - OMGraphicList eventGraphicList; - if (eventPresenter != null) { - - // Hack to use optimized method if available - if (eventPresenter instanceof AbstractEventPresenter) { - Rectangle bounds = getBounds(null); - - Point2D minutesPnt0 = projection.inverse(0, 0); - Point2D minutesPnt1 = projection.inverse(1, 0); - double leftX = bounds.getMinX(); - double rightX = bounds.getMaxX(); - Point2D minutesPntLeft = projection.inverse(leftX, 0); - Point2D minutesPntRight = projection.inverse(rightX, 0); - - double minutesPerPixel = minutesPnt1.getX() - minutesPnt0.getX(); - long step = (long) (minutesPerPixel * 60 * 1000); - long start = gameStartTime + (long) (minutesPntLeft.getX() * 60 * 1000); - long end = gameStartTime + (long) (minutesPntRight.getX() * 60 * 1000); - eventGraphicList = getEventList(((AbstractEventPresenter) eventPresenter).getActiveEvents(start, end, - step), - projection); - } else { - eventGraphicList = getEventList(eventPresenter.getActiveEvents(), - projection); - } - - // As long as we feel the need to recreate the event markers, - // let's re-evaluate the annotations. - evaluateEventAttributes(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating event lines with (" - + eventGraphicList.size() + ") events"); - } - } else { - logger.fine("Can't create event list for timeline display, no event presenter"); - eventGraphicList = new OMGraphicList(); - } - - return eventGraphicList; - } - - protected OMGraphicList getEventList(Iterator it, - Projection projection) { - OMGraphicList eventGraphicList = new OMGraphicList(); - if (projection != null) { - - BasicStroke symbolStroke = new BasicStroke(2); - - while (it.hasNext()) { - OMEvent event = it.next(); - - long time = event.getTimeStamp() - gameStartTime; - float lon = (float) forwardProjectMillis(time); - EventMarkerLine currentLine = new EventMarkerLine(0f, lon, 6); - currentLine.setLinePaint(Color.black); - currentLine.setStroke(symbolStroke); - currentLine.generate(projection); - currentLine.putAttribute(ATT_KEY_EVENT, event); - eventGraphicList.add(currentLine); - } - } - return eventGraphicList; - } - - public class EventMarkerLine - extends OMLine { - - protected int heightRatioSetting; - protected byte symbolHeight; - - public EventMarkerLine(double lat, double lon, int heightRatioSetting) { - super(lat, lon, 0, 1, 0, -1); - this.heightRatioSetting = heightRatioSetting; - } - - public boolean generate(Projection proj) { - byte testSH = (byte) (proj.getHeight() * 2 / heightRatioSetting); - if (testSH != symbolHeight) { - int[] pts = getPts(); - int symbolHeight = proj.getHeight() / heightRatioSetting; - pts[1] = symbolHeight; - pts[3] = -symbolHeight; - this.symbolHeight = (byte) symbolHeight; - } - - return super.generate(proj); - } - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - protected Box paletteBox = null; - - public java.awt.Component getGUI() { - - if (paletteBox == null) { - logger.fine("creating Palette."); - - paletteBox = Box.createVerticalBox(); - - JPanel subbox3 = new JPanel(new GridLayout(0, 1)); - - JButton setProperties = new JButton(i18n.get(TimelineLayer.class, - "setProperties", - "Preferences")); - setProperties.setActionCommand(DisplayPropertiesCmd); - setProperties.addActionListener(this); - subbox3.add(setProperties); - - paletteBox.add(subbox3); - } - return paletteBox; - } - - public void drawingComplete(OMGraphic omg, OMAction action) { - - if (!doAction(omg, action)) { - // null OMGraphicList on failure, should only occur if - // OMGraphic is added to layer before it's ever been - // on the map. - setList(new OMGraphicList()); - doAction(omg, action); - } - - repaint(); - } - - public boolean isSelectable(OMGraphic omg) { - return false; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - public String getName() { - return "TimelineLayer"; - } - - protected void setTimeBounds(long start, long end) { - if (gameStartTime != start || gameEndTime != end) { - gameStartTime = start; - gameEndTime = end; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("gst: " + gameStartTime + ", get: " + gameEndTime - + ", bounds of " + postTime); - } - - if (realTimeMode) { - // TODO Don (see above) why is this necessary? Seems like the - // regenerate ought to reproject the event markers properly? - setEventGraphicList(null); - } - - if (!realTimeMode || !timeSliderLayer.getUserHasChangedScale()) { - setMapBeanMaxScale(true); - } - } - } - - public void updateTimeBounds(TimeBoundsEvent tbe) { - TimeBounds tb = tbe.getNewTimeBounds(); - if (tb != null) { - long oldStartTime = gameStartTime; - setTimeBounds(tb.getStartTime(), tb.getEndTime()); - if (realTimeMode) { - long boundsStartOffset = tb.getStartTime() - oldStartTime; - currentTime -= boundsStartOffset; - ((Proj) getProjection()).setCenter(0, forwardProjectMillis(currentTime)); - centerDelegate.fireCenter(0, forwardProjectMillis(currentTime)); - timeLinesList = null; - } - - SelectionArea selectRect = getSelectionRectangle(); - - // Update selection (this only deals with time translation for now; no scaling) - if (realTimeMode && selectRect != null && selectRect.isVisible()) { - long boundsWestDelta = tbe.getNewTimeBounds().getStartTime() - tbe.getOldTimeBounds().getStartTime(); - double selectionDelta = (double) boundsWestDelta / 60000.0; - double newWest = selectRect.getWestLon() - selectionDelta; - double newEast = selectRect.getEastLon() - selectionDelta; - selectRect.setLocation(newWest, newEast); - getSelectionRectangle(getProjection()); - } - } else { - checkAndSetForNoTime(TimeEvent.NO_TIME); - timeSliderLayer.setSelectionValid(false); - } - - if (tbe.isInduceGraphicalUpdate()) { - doPrepare(); - } - } - - public void updateTime(TimeEvent te) { - - if (checkAndSetForNoTime(te)) { - return; - } - - Clock clock = (Clock) te.getSource(); - setTimeBounds(clock.getStartTime(), clock.getEndTime()); - - TimerStatus timerStatus = te.getTimerStatus(); - - if (timerStatus.equals(TimerStatus.STEP_FORWARD) - || timerStatus.equals(TimerStatus.STEP_BACKWARD) - || timerStatus.equals(TimerStatus.UPDATE)) { - // These TimerStatus updates reflect the current time being - // specifically set to a value, as opposed to the clock running - // normally. - currentTime = te.getSystemTime() - gameStartTime; - ((Proj) getProjection()).setCenter(0, forwardProjectMillis(currentTime)); - centerDelegate.fireCenter(0, forwardProjectMillis(currentTime)); - timeLinesList = null; - doPrepare(); - } else if (timerStatus.equals(TimerStatus.FORWARD) - || timerStatus.equals(TimerStatus.BACKWARD) - || timerStatus.equals(TimerStatus.STOPPED)) { - // Checking for a running clock prevents a time status - // update after the clock is stopped. The - // AudioFileHandlers don't care about the current time - // if it isn't running. - - // This check might be avoided if just FORWARD and BACKWARD are sent - // if the clock is running. Need to check the behavior of the clock - // to make sure, and figure out what the state of the clock is when - // it stops. - if (clock.isRunning()) { - long currentTime = te.getSystemTime() - gameStartTime; - - if (playFilter.reactToCurrentTime(currentTime, - clock, - gameStartTime)) { - this.currentTime = currentTime; - timeLinesList = null; - centerDelegate.fireCenter(0, - forwardProjectMillis(currentTime)); - doPrepare(); - } - } - } else { - logger.info("none of the above: " + timerStatus.toString()); - } - - } - - /* - * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - - if (propertyName == EventPresenter.ActiveEventsProperty) { - setEventGraphicList(null); - logger.fine("EventPresenter updated event list, calling doPrepare() " - + evt.getNewValue()); - doPrepare(); - } else if (propertyName == OMEventSelectionCoordinator.EventsSelectedProperty) { - setSelectionRectangleToEvents(); - } else if (propertyName == EventPresenter.EventAttributesUpdatedProperty) { - evaluateEventAttributes(); - doPrepare(); - } else if (propertyName == TimePanel.PlayFilterProperty) { - boolean inUse = ((Boolean) evt.getNewValue()).booleanValue(); - playFilter.setInUse(inUse); - firePropertyChange(PlayFilterProperty, - null, - new Boolean(!inUse || !playFilter.isEmpty())); - } else { - logger.finer("AAGGH: " + propertyName); - } - } - - protected boolean checkAndSetForNoTime(TimeEvent te) { - isNoTime = te == TimeEvent.NO_TIME; - return isNoTime; - } - - double snapToEvent(double lon) { - - if (realTimeMode) { - return lon; - } - - double retVal = lon; - double minDiff = Double.MAX_VALUE; - - if (eventPresenter != null) { - - for (Iterator it = eventPresenter.getAllEvents(); it.hasNext();) { - - OMEvent event = it.next(); - - long time = event.getTimeStamp() - gameStartTime; - float timeMinutes = (float) forwardProjectMillis(time); - - if (Math.abs(timeMinutes - lon) < minDiff) { - minDiff = Math.abs(timeMinutes - lon); - retVal = timeMinutes; - } - - } - } - - return retVal; - } - - public MapMouseListener getMapMouseListener() { - return this; - } - - public String[] getMouseModeServiceList() { - return getMouseModeIDsForEvents(); - } - - public boolean mousePressed(MouseEvent e) { - doubleClick = false; - updateMouseTimeDisplay(e); - // Use current projection to determine rect top and bottom - Projection projection = getProjection(); - // Get latLong from mouse, and then snap to nearest event... - Point2D latLong = projection.inverse(e.getPoint()); - - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - double lon = latLong.getX(); - - float up = (float) ul.getY(); - float down = (float) lr.getY(); - - lon = snapToEvent(lon); - - SelectionArea selectRect = getSelectionRectangle(); - if (selectRect != null) { - selectRect.setVisible(false); - selectRect.setLocation(up, - (float) lon, - down, - (float) lon, - OMGraphic.LINETYPE_STRAIGHT); - selectRect.generate(projection); - } - timeSliderLayer.setSelectionValid(false); - - downLon = lon; - - return true; - } - - protected void selectEventForMouseEvent(MouseEvent e) { - // Handle a single click, select event if close - OMGraphicList eventGraphicList = getEventGraphicList(); - if (e != null && eventGraphicList != null) { - OMGraphic omg = eventGraphicList.findClosest((int) e.getX(), - (int) e.getY(), - 4); - - if (omg != null) { - OMEvent sourceEvent = (OMEvent) omg.getAttribute(ATT_KEY_EVENT); - if (sourceEvent != null) { - sourceEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, - OMEvent.ATT_VAL_SELECTED); - if (aesc != null) { - Vector eventList = new Vector(); - eventList.add(sourceEvent); - aesc.eventsSelected(eventList); - } - } - } - } - doubleClick = false; - } - - public boolean mouseReleased(MouseEvent e) { - updateMouseTimeDisplay(e); - handleEventSelection(); - if (scrollTask != null) { - scrollTask.cancel(); - scrollTask = null; - } - return true; - } - - double downLon; - boolean doubleClick = false; - - public boolean mouseClicked(MouseEvent e) { - if (e.getClickCount() >= 2) { - selectEventForMouseEvent(e); - doubleClick = true; - return true; - } - - double lon = updateMouseTimeDisplay(e); - - if (clock != null) { - clock.setTime(gameStartTime + inverseProjectMillis(lon)); - } - - timeSliderLayer.clearFixedRenderRange(); - SelectionArea selectionRect = getSelectionRectangle(); - selectionRect.setLocation(lon, lon); - selectionRect.setVisible(false); - timeSliderLayer.setSelectionValid(false); - - return true; - } - - protected double updateMouseTimeDisplay(MouseEvent e) { - Projection proj = getProjection(); - Point2D latLong = proj.inverse(e.getPoint()); - double lon = latLong.getX(); - double endTime = forwardProjectMillis(gameEndTime - gameStartTime); - if (lon < 0) { - lon = -1; - } else if (lon > endTime) { - lon = endTime; - } - - long offsetMillis = inverseProjectMillis(lon); - - updateMouseTimeDisplay(new Long(offsetMillis)); - - return lon < 0 ? 0 : lon; - } - - public void updateMouseTimeDisplay(Long offsetMillis) { - firePropertyChange(MouseTimeProperty, null, offsetMillis); - } - - protected void updateEventDetails(MouseEvent e) { - String details = ""; - OMGraphicList eventGraphicList = getEventGraphicList(); - if (e != null && eventGraphicList != null) { - OMGraphic omg = eventGraphicList.findClosest((int) e.getX(), - (int) e.getY(), - 4); - - if (omg != null) { - OMEvent sourceEvent = (OMEvent) omg.getAttribute(ATT_KEY_EVENT); - if (sourceEvent != null) { - details = sourceEvent.getDescription(); - } - } - } - - firePropertyChange(EventDetailsProperty, null, details); - - } - - protected void updateEventDetails() { - updateEventDetails(null); - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - firePropertyChange(MouseTimeProperty, null, new Long(-1)); - updateEventDetails(); - } - - class ScrollTask - extends TimerTask { - - private long delta; - private MouseEvent mouseEvent; - - ScrollTask(long delta, MouseEvent mouseEvent) { - this.delta = delta; - this.mouseEvent = mouseEvent; - } - - @Override - public void run() { - if (clock != null) { - long newTime = clock.getTime() + delta; - newTime = Math.max(gameStartTime, newTime); - newTime = Math.min(gameEndTime, newTime); - clock.setTime(newTime); - adjustSelection(mouseEvent); - doPrepare(); - } - } - - } - - private void adjustSelection(MouseEvent e) { - updateMouseTimeDisplay(e); - updateEventDetails(e); - timeSliderLayer.clearFixedRenderRange(); - - // Get latLong from mouse, and set E side of current select rect... - Projection proj = getProjection(); - Point2D latLong = proj.inverse(e.getPoint()); - double lon = snapToEvent(latLong.getX()); - - float west = (float) Math.min(downLon, lon); - float east = (float) Math.max(downLon, lon); - SelectionArea selectRect = getSelectionRectangle(); - if (selectRect != null) { - selectRect.setVisible(true); - selectRect.setLocation(west, east); - selectRect.generate(proj); - } - timeSliderLayer.setSelectionValid(east != west); - } - - public boolean mouseDragged(MouseEvent e) { - - // First the actual selection adjustment - adjustSelection(e); - - // Now reset the scroll timer as necessary - Projection proj = getProjection(); - final long scrollPeriod = 50; - float baseScrollMultiplier = 0.001f; - int x = e.getPoint().x; - if (scrollTask != null) { - scrollTask.cancel(); - scrollTask = null; - } - float scale = proj.getScale(); - if (x < 0) { - if (clock != null) { - final float multiplier = baseScrollMultiplier * x; - long delta = (long) (multiplier * scale); - scrollTask = new ScrollTask(delta, e); - scrollTimer.schedule(scrollTask, 0, scrollPeriod); - } - } else if (x > getWidth()) { - if (clock != null) { - final float multiplier = baseScrollMultiplier * (x - getWidth()); - long delta = (long) (multiplier * scale); - scrollTask = new ScrollTask(delta, e); - scrollTimer.schedule(scrollTask, 0, scrollPeriod); - } - } - - doPrepare(); - return true; - } - - public boolean mouseMoved(MouseEvent e) { - updateMouseTimeDisplay(e); - updateEventDetails(e); - return true; - } - - public void mouseMoved() { - updateEventDetails(); - } - - protected List handleEventSelection() { - List eventList = null; - SelectionArea selectRect = getSelectionRectangle(); - if (aesc != null && selectRect != null) { - - // The thing to be careful about here is that the selection - // Rectangle isn't where the user clicked and released. It's snapped - // to the visible events. It makes some weird behavior below when - // you try to highlight a single event, because the time for that - // event is the closest snapped time event, not the invisible event - // that may be clicked on. - boolean goodDrag = selectRect.isVisible(); - double lowerTime = selectRect.getWestLon(); - double upperTime = selectRect.getEastLon(); - // Convert to millis - long lowerTimeStamp = inverseProjectMillis((float) lowerTime); - long upperTimeStamp = inverseProjectMillis((float) upperTime); - - boolean sameTime = lowerTimeStamp == upperTimeStamp; - goodDrag = goodDrag && !sameTime; - - boolean labeledRangeStart = false; - OMEvent lastEventLabeled = null; - - for (Iterator it = eventPresenter.getAllEvents(); it.hasNext();) { - if (eventList == null) { - eventList = new Vector(); - } - - OMEvent event = (OMEvent) it.next(); - double timeStamp = event.getTimeStamp() - gameStartTime; - - // Don't forget, need to go through all of the events, not just - // the ones lower than the upper time stamp, because we need to - // set the selected flag to null for all of them and then only - // reset the ones that actually are selected. - event.putAttribute(OMEvent.ATT_KEY_SELECTED, null); - - if (goodDrag && timeStamp >= lowerTimeStamp - && timeStamp <= upperTimeStamp) { - eventList.add(event); - - // Needs to be updated to put ATT_VAL_SELECTED_START_RANGE, - // ATT_VAL_SELECTED_END_RANGE, or just ATT_VAL_SELECTED - if (!labeledRangeStart && lowerTimeStamp != upperTimeStamp) { - event.putAttribute(OMEvent.ATT_KEY_SELECTED, - OMEvent.ATT_VAL_SELECTED_START_RANGE); - labeledRangeStart = true; - } else { - event.putAttribute(OMEvent.ATT_KEY_SELECTED, - OMEvent.ATT_VAL_SELECTED); - } - lastEventLabeled = event; - } else if (sameTime && timeStamp == lowerTimeStamp) { - - // This code just returns the closest visible snapped time - // event. - // event.putAttribute(OMEvent.ATT_KEY_SELECTED, - // OMEvent.ATT_VAL_SELECTED); - // eventList.add(event); - // I guess this is OK when a visible event is clicked on, - // but it's not when a non-visible event is clicked on. - } - } - - if (labeledRangeStart && lastEventLabeled != null) { - lastEventLabeled.putAttribute(OMEvent.ATT_KEY_SELECTED, - OMEvent.ATT_VAL_SELECTED_END_RANGE); - } - - aesc.eventsSelected(eventList); - } - - return eventList; - } - - protected void evaluateEventAttributes() { - if (realTimeMode) { - return; // Never mind; we're not doing anything with attributes - } - ratingAreas.clear(); - playFilter.clear(); - SelectionArea.RatingArea currentRatingArea = null; - SelectionArea.PlayFilterSection currentPlayFilter = null; - - if (eventPresenter != null) { - for (Iterator it = eventPresenter.getAllEvents(); it.hasNext();) { - OMEvent aare = it.next(); - String rating = (String) aare.getAttribute(OMEvent.ATT_KEY_RATING); - Object playFilterObj = aare.getAttribute(OMEvent.ATT_KEY_PLAY_FILTER); - long timeStamp = aare.getTimeStamp() - gameStartTime; - - if (rating != null) { - if (currentRatingArea != null - && !currentRatingArea.isRating(rating)) { - currentRatingArea = null; - } - - if (currentRatingArea == null) { - currentRatingArea = new SelectionArea.RatingArea(timeStamp, rating); - ratingAreas.add(currentRatingArea); - } - - currentRatingArea.addTime(timeStamp); - - } else if (currentRatingArea != null) { - currentRatingArea = null; - } - - if (playFilterObj != null) { - if (currentPlayFilter != null) { - currentPlayFilter.addTime(timeStamp); - } else { - currentPlayFilter = new SelectionArea.PlayFilterSection(timeStamp); - // logger.info("adding play filter section to play - // filter"); - playFilter.add(currentPlayFilter); - } - } else { - currentPlayFilter = null; - } - - } - - OMGraphicList list = getList(); - if (list != null && list.isVisible()) { - firePropertyChange(PlayFilterProperty, - null, - new Boolean(!playFilter.isInUse() - || !playFilter.isEmpty())); - } - - } - } - - protected void setSelectionRectangleToEvents() { - if (aesc != null) { - SelectionArea selectRect = getSelectionRectangle(getProjection()); - - double lowerTime = Double.POSITIVE_INFINITY; - double upperTime = Double.NEGATIVE_INFINITY; - - for (Iterator it = eventPresenter.getAllEvents(); it.hasNext();) { - OMEvent event = it.next(); - - if (event.getAttribute(OMEvent.ATT_KEY_SELECTED) != null) { - // Convert to minutes for selectRect bounds - double timeStamp = (double) forwardProjectMillis(event.getTimeStamp() - - gameStartTime); - if (timeStamp < lowerTime) { - lowerTime = timeStamp; - } - if (timeStamp > upperTime) { - upperTime = timeStamp; - } - } - } - - if (selectRect != null) { - if (upperTime != Double.NEGATIVE_INFINITY - && lowerTime != Double.POSITIVE_INFINITY) { - selectRect.setLocation((float) lowerTime, (float) upperTime); - selectRect.setVisible(true); - selectRect.generate(getProjection()); - } else { - selectRect.setVisible(false); - } - } - } - doPrepare(); - } - - public static class SelectionArea - extends com.bbn.openmap.omGraphics.OMRect { - - public SelectionArea() { - setRenderType(OMRect.RENDERTYPE_LATLON); - } - - public void setLocation(double left, double right) { - super.setLocation(0f, left, 0f, right, OMRect.LINETYPE_STRAIGHT); - } - - public boolean generate(Projection proj) { - updateY(proj); - return super.generate(proj); - } - - protected void updateY(Projection proj) { - // The difference here is that the upper and lower bounds are - // determined by the projection. - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - lat1 = ul.getY(); - lat2 = lr.getY(); - } - - public static class PreTime - extends SelectionArea { - - public PreTime(long time) { - super(); - lon2 = forwardProjectMillis(time); - setFillPaint(tint); - setLinePaint(tint); - } - - public void setLocation() { - } - - public boolean generate(Projection proj) { - // The difference here is that the vertical bounds are - // determined the starting time and all times before that. - Point2D ul = proj.getUpperLeft(); - double ulx = ul.getX(); - if (ulx >= lon2) { - lon1 = lon2; - } else { - lon1 = ulx; - } - - return super.generate(proj); - } - } - - public static class PostTime - extends SelectionArea { - - public PostTime(long time) { - super(); - lon1 = forwardProjectMillis(time); - setFillPaint(tint); - setLinePaint(tint); - } - - public void setLocation() { - } - - public boolean generate(Projection proj) { - // The difference here is that the vertical bounds are - // determined the end time and all times after that. - Point2D lr = proj.getLowerRight(); - double lrx = lr.getX(); - if (lrx <= lon1) { - lon2 = lon1; - } else { - lon2 = lrx; - } - - return super.generate(proj); - } - } - - public static class RatingArea - extends SelectionArea { - - protected String rating; - protected static Color goodColor = new Color(0x9900ff00, true); - protected static Color badColor = new Color(0x99ff0000, true); - - public RatingArea(long time, String rating) { - super(); - this.rating = rating; - double timef = forwardProjectMillis(time); - setLocation(timef, timef); - Color ratingColor = badColor; - if (rating.equals(OMEvent.ATT_VAL_GOOD_RATING)) { - ratingColor = goodColor; - } - - setLinePaint(ratingColor); - setFillPaint(ratingColor); - } - - public boolean isRating(String rating) { - return this.rating.equalsIgnoreCase(rating); - } - - public void addTime(long timeToAdd) { - double time = forwardProjectMillis(timeToAdd); - double east = getEastLon(); - double west = getWestLon(); - boolean updated = false; - if (time < west) { - west = time; - updated = true; - } - - if (time > east) { - east = time; - updated = true; - } - - if (updated) { - setLocation(west, east); - } - } - } - - public static class PlayFilterSection - extends SelectionArea { - - protected static Color color = new Color(0x99000000, true); - protected String idString; - - public PlayFilterSection(long time) { - super(); - double timef = forwardProjectMillis(time); - setLocation(timef, timef); - setLinePaint(color); - setFillPaint(color); - } - - /** - * Checks time in relation to held times. - * - * @param timel time in unprojected milliseconds, offset from game start time. - * @return 0 if time is within bounds, -1 if time is before bounds, 1 if time is after bounds. - */ - public int isWithin(long timel) { - double time = forwardProjectMillis(timel); - int ret = -1; - if (time >= getWestLon()) { - ret++; - } - if (time > getEastLon()) { - ret++; - } - return ret; - } - - protected void updateY(Projection proj) { - Point2D ul = proj.getUpperLeft(); - lat1 = ul.getY(); - Point2D lrpt = proj.inverse(0, proj.getHeight() / 8); - lat2 = lrpt.getY(); - idString = null; - } - - public void addTime(long timeToAdd) { - double time = forwardProjectMillis(timeToAdd); - double east = getEastLon(); - double west = getWestLon(); - boolean updated = false; - if (time < west) { - west = time; - updated = true; - } - - if (time > east) { - east = time; - updated = true; - } - - if (updated) { - setLocation(west, east); - idString = null; - } - } - - public String toString() { - if (idString == null) { - idString = "PlayFilterSection[" + getWestLon() + "," - + getEastLon() + "]"; - } - - return idString; - } - } - - } - - public static class CurrentTimeMarker - extends OMGraphicList { - - protected OMRaster upperMark; - protected OMRaster lowerMark; - protected OMLine startingLine; - int iconSize = 16; - int lastHeight = 0; - int lastWidth = 0; - - public CurrentTimeMarker() { - - DrawingAttributes da = new DrawingAttributes(); - - da.setFillPaint(tint); - da.setLinePaint(tint); - IconPart ip = new BasicIconPart(new Polygon(new int[]{50, 90, 10, - 50}, new int[]{10, 90, 90, 10}, 4), da); - ImageIcon thumbsUpImage = OMIconFactory.getIcon(iconSize, - iconSize, - ip); - - lowerMark = new OMRaster(0, 0, thumbsUpImage); - - ip = new BasicIconPart(new Polygon(new int[]{10, 90, 50, 10}, new int[]{ - 10, 10, 90, 10}, 4), da); - ImageIcon thumbsDownImage = OMIconFactory.getIcon(iconSize, - iconSize, - ip); - - upperMark = new OMRaster(0, 0, thumbsDownImage); - - startingLine = new OMLine(0, 0, 0, 0); - da.setTo(startingLine); - add(startingLine); - add(lowerMark); - add(upperMark); - } - - public boolean generate(Projection proj) { - int height = proj.getHeight(); - int width = proj.getWidth(); - - if (height != lastHeight || width != lastWidth) { - lastHeight = height; - lastWidth = width; - - int halfX = (int) (width / 2); - - upperMark.setX(halfX - iconSize / 2); - upperMark.setY(0); - lowerMark.setX(halfX - iconSize / 2); - lowerMark.setY(height - iconSize); - int[] pts = startingLine.getPts(); - pts[0] = halfX; - pts[1] = 0 + iconSize; - pts[2] = halfX; - pts[3] = height - iconSize; - } - return super.generate(proj); - } - } - - public static class TimeHashFactory { - - List hashMarks = new ArrayList(5); - TimeHashMarks current; - - public TimeHashFactory() { - hashMarks.add(new TimeHashMarks.Seconds()); - hashMarks.add(new TimeHashMarks.Minutes()); - hashMarks.add(new TimeHashMarks.Hours()); - hashMarks.add(new TimeHashMarks.Days()); - hashMarks.add(new TimeHashMarks.Years()); - } - - public OMGraphicList getHashMarks(Projection proj, boolean realTimeMode, long gameStartTimeMillis) { - - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - - // timeSpan in minutes - double timeSpan = lr.getX() - ul.getX(); - - TimeHashMarks thm = null; - for (Iterator it = hashMarks.iterator(); it.hasNext();) { - TimeHashMarks cthm = it.next(); - if (cthm.passesThreshold(timeSpan)) { - thm = cthm; - } else { - break; - } - } - - if (current != null) { - current.clear(); - } - if (thm != current) { - current = thm; - } - - current.generate(proj, realTimeMode, timeSpan, gameStartTimeMillis); - - return current; - } - } - - public static class PlayFilter - extends OMGraphicList { - - protected boolean inUse = false; - String currentlyPlaying = null; - - public PlayFilter() { - } - - public boolean reactToCurrentTime(long currentTime, Clock clock, - long gameStartTime) { - boolean ret = !inUse; - if (inUse) { - // logger.info("checking " + size() + " sections"); - - for (Iterator it = iterator(); it.hasNext();) { - PlayFilterSection pfs = (PlayFilterSection) it.next(); - int where = pfs.isWithin(currentTime); - if (where == 0) { - ret = true; - currentlyPlaying = pfs.toString(); - // logger.info("where == 0, setting pfs " + - // currentlyPlaying); - break; - } else if (where > 0) { - - if ((currentlyPlaying != null && (currentlyPlaying.equals(pfs.toString()))) - || !it.hasNext()) { - // logger.info("where > 0, same pfs, stopping clock - // " + pfs); - clock.setTime(gameStartTime - + inverseProjectMillis(pfs.getEastLon())); - clock.stopClock(); - currentlyPlaying = null; - break; - } else { - // logger.info("where > 0, not the same pfs " + pfs - // + ", " + currentlyPlaying); - } - - continue; - } else { - // logger.info("where < 0, jumping clock " + pfs); - clock.setTime(gameStartTime - + inverseProjectMillis(pfs.getWestLon())); - break; - } - } - } - - return ret; - } - - public boolean isInUse() { - return inUse; - } - - public void setInUse(boolean inUse) { - this.inUse = inUse; - } - } - - public abstract static class TimeHashMarks - extends OMGraphicList { - - protected String annotation; - protected double unitPerMinute; - protected DateFormat dateFormat; - - protected TimeHashMarks(String annotation, double unitPerMinute, DateFormat dateFormat) { - this.annotation = annotation; - this.unitPerMinute = unitPerMinute; - this.dateFormat = dateFormat; - } - - public abstract boolean passesThreshold(double minVisibleOnTimeLine); - - public boolean generate(Projection proj, boolean realTimeMode, double timeSpanMinutes, long gameStartTimeMillis) { - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - double left = ul.getX() * unitPerMinute; - double right = lr.getX() * unitPerMinute; - double timeSpan = timeSpanMinutes * unitPerMinute; - - double num = Math.floor(timeSpan); - double heightStepSize = 1; - double stepSize = 1; - if (num < 2) { - stepSize = .25; - } else if (num < 5) { - stepSize = .5; - } else if (num > 30) { - stepSize = 10; - heightStepSize = 10; - } else if (num > 15) { - heightStepSize = 10; - } - - if (logger.isLoggable(Level.FINER)) { - logger.finer("figure on needing " + num + annotation + ", " - + stepSize + " stepsize for " + (timeSpan / stepSize) - + " lines"); - } - - int height = (int) (proj.getHeight() * .2); - double anchory = lr.getY(); - - if (realTimeMode) { - // Different approach here, since we're concerned with absolute time - // -So all of the above setup still applies, but we're going to convert - // once we have the start time set - double millisPerUnit = (long) (60.0 * 1000.0 / unitPerMinute); - double gameStartTimeUnits = (double) gameStartTimeMillis / millisPerUnit; - double firstMarkerOffsetMillis = (gameStartTimeMillis % millisPerUnit); - double firstMarkerOffsetUnits = (double) firstMarkerOffsetMillis / millisPerUnit; - - // need to do negative times. - if (left < 0) { - while (firstMarkerOffsetUnits > left) { - firstMarkerOffsetUnits -= stepSize; - } - } - - while (firstMarkerOffsetUnits < left) { - firstMarkerOffsetUnits += stepSize; - } - - double stepStart = Math.floor(firstMarkerOffsetUnits + gameStartTimeUnits); - double stepEnd = Math.ceil(right + gameStartTimeUnits); - - int count = 0; - - // i is in 'units' - for (double i = stepStart; i < stepEnd; i += stepSize, count++) { - double anchorx = (i - gameStartTimeUnits) / unitPerMinute; - - int thisHeight = height; - boolean doLabel = true; - if (count % heightStepSize != 0) { - thisHeight /= 2; - doLabel = false; - } - - OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); - currentLine.setLinePaint(tint); - currentLine.setStroke(new BasicStroke(2)); - add(currentLine); - - if (doLabel) { - Date date = new Date((long) (i * millisPerUnit)); - String labelString = dateFormat.format(date); - OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, labelString, - OMText.JUSTIFY_LEFT); - label.setLinePaint(tint); - add(label); - } - } - } else { - // Now, we need to baseline marks on 0, not on the left most value. - double start = 0; - // need to do negative times. - if (left < 0) { - while (start > left) { - start -= stepSize; - } - } - - while (start < left) { - start += stepSize; - } - - double stepStart = Math.floor(start); - double stepEnd = Math.ceil(right); - - for (double i = stepStart; i < stepEnd; i += stepSize) { - double anchorx = i / unitPerMinute; - - int thisHeight = height; - boolean doLabel = true; - if (i % heightStepSize != 0) { - thisHeight /= 2; - doLabel = false; - } - - OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); - currentLine.setLinePaint(tint); - currentLine.setStroke(new BasicStroke(2)); - add(currentLine); - - if (doLabel) { - OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) i - + annotation, OMText.JUSTIFY_LEFT); - label.setLinePaint(tint); - add(label); - } - } - } - - return super.generate(proj); - } - - public static class Seconds - extends TimeHashMarks { - - public Seconds() { - super("s", 60, new SimpleDateFormat("HH:mm:ss.SS")); - } - - public boolean passesThreshold(double minVisibleOnTimeLine) { - return true; - } - - } - - public static class Minutes - extends TimeHashMarks { - - public Minutes() { - super("m", 1, new SimpleDateFormat("HH:mm:ss")); - } - - public boolean passesThreshold(double minVisibleOnTimeLine) { - return minVisibleOnTimeLine > 2; - } - - } - - public static class Hours - extends TimeHashMarks { - - public Hours() { - super("h", (1d / 60d), new SimpleDateFormat("HH:mm:ss")); - } - - public boolean passesThreshold(double minVisibleOnTimeLine) { - return minVisibleOnTimeLine / 60 > 3; - } - } - - public static class Days - extends TimeHashMarks { - - public Days() { - super("d", (1d / 60d / 24d), TimePanel.dayFormat); - } - - public boolean passesThreshold(double minVisibleOnTimeLine) { - return minVisibleOnTimeLine / 60 / 24 > 2; - } - - } - - public static class Years - extends TimeHashMarks { - - public Years() { - super("y", (1d / 60d / 24d / 365d), TimePanel.dayFormat); - } - - public boolean passesThreshold(double minVisibleOnTimeLine) { - return minVisibleOnTimeLine / 60 / 24 / 365 > 1; - } - - } - - } - - protected void setMapBeanMaxScale(boolean setScaleToMax) { - Projection proj = getProjection(); - if (proj != null) { - float scale = (float) (TimeSliderLayer.magicScaleFactor - * (double) forwardProjectMillis(gameEndTime - gameStartTime) / proj.getWidth()); - - MapBean mb = (MapBean) ((MapHandler) getBeanContext()).get(com.bbn.openmap.MapBean.class); - ((Cartesian) mb.getProjection()).setMaxScale(scale); - - if (setScaleToMax) { - mb.setScale(scale); - } - } - } - - public void componentHidden(ComponentEvent e) { - } - - public void componentMoved(ComponentEvent e) { - } - - public void componentResized(ComponentEvent e) { - setMapBeanMaxScale(false); - } - - public void componentShown(ComponentEvent e) { - } - - public void paint(Graphics g) { - try { - super.paint(g); - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - logger.warning(e.getMessage()); - e.printStackTrace(); - } - } - } - - public void setRealTimeMode(boolean realTimeMode) { - this.realTimeMode = realTimeMode; - } - - public long getDuration() { - return gameEndTime - gameStartTime; - } - - public long getEndTime() { - return gameEndTime; - } - - public void setUserHasChangedScale(boolean userHasChangedScale) { - timeSliderLayer.setUserHasChangedScale(userHasChangedScale); - } - - public void adjustZoomFromMouseWheel(int rot) { - timeSliderLayer.adjustZoomFromMouseWheel(rot); - doPrepare(); - } - - long getSelectionStart() { - SelectionArea selectRect = getSelectionRectangle(); - if (selectRect != null) { - boolean goodDrag = selectRect.isVisible(); - double lowerTime = selectRect.getWestLon(); - double upperTime = selectRect.getEastLon(); - // Convert to millis - long lowerTimeStamp = inverseProjectMillis((float) lowerTime); - long upperTimeStamp = inverseProjectMillis((float) upperTime); - - boolean sameTime = lowerTimeStamp == upperTimeStamp; - goodDrag = goodDrag && !sameTime; - - return goodDrag ? lowerTimeStamp + gameStartTime : -1; - } - return -1; - } - - long getSelectionEnd() { - SelectionArea selectRect = getSelectionRectangle(); - if (selectRect != null) { - boolean goodDrag = selectRect.isVisible(); - double lowerTime = selectRect.getWestLon(); - double upperTime = selectRect.getEastLon(); - // Convert to millis - long lowerTimeStamp = inverseProjectMillis((float) lowerTime); - long upperTimeStamp = inverseProjectMillis((float) upperTime); - - boolean sameTime = lowerTimeStamp == upperTimeStamp; - goodDrag = goodDrag && !sameTime; - - return goodDrag ? upperTimeStamp + gameStartTime : -1; - } - return -1; - } - - public void clearSelection() { - SelectionArea selectRect = getSelectionRectangle(); - if (selectRect != null) { - selectRect.setLocation(0, 0); - selectRect.setVisible(false); - } - timeSliderLayer.setSelectionValid(false); - timeSliderLayer.clearFixedRenderRange(); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimelinePanel.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimelinePanel.java deleted file mode 100644 index fb2cf8281..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimelinePanel.java +++ /dev/null @@ -1,104 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: TimelinePanel.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/09/25 17:31:26 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.event.MouseWheelEvent; -import java.awt.geom.Point2D; - -import javax.swing.BorderFactory; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.proj.Cartesian; - -public class TimelinePanel extends BasicMapPanel { - - private static final long serialVersionUID = 1L; - protected TimelineLayer timelineLayer; - - public TimelinePanel() { - super(true); - Cartesian cartesian = new Cartesian(new Point2D.Double(), 300000f, 600, 20); - setLayout(new BorderLayout()); - MapBean mapBean = getMapBean(); - mapBean.setProjection(cartesian); - // mapBean.setPreferredSize(new Dimension(10, 70)); - mapBean.setBorder(BorderFactory.createLineBorder(TimelineLayer.tint)); - mapBean.setBckgrnd(Color.white); - - MapHandler mh = getMapHandler(); - mh.add(new com.bbn.openmap.LayerHandler()); - mh.add(new com.bbn.openmap.MouseDelegator()); - mh.add(new com.bbn.openmap.event.SelectMouseMode() { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Invoked from the MouseWheelListener interface. - */ - public void mouseWheelMoved(MouseWheelEvent e) { - int rot = e.getWheelRotation(); - timelineLayer.adjustZoomFromMouseWheel(rot); - } - - }); - - timelineLayer = new TimelineLayer(); - mh.add(timelineLayer); - } - - public TimelineLayer getTimelineLayer() { - return timelineLayer; - } - - public void TimelineLayer(TimelineLayer timelineLayer) { - this.timelineLayer = timelineLayer; - } - - public Wrapper getWrapper() { - return new Wrapper(this); - } - - public static class Wrapper { - TimelinePanel panel; - - public Wrapper(TimelinePanel tlp) { - panel = tlp; - } - - public TimelinePanel getTimelinePanel() { - return panel; - } - } - - public void setRealTimeMode(boolean realTimeMode) { - timelineLayer.setRealTimeMode(realTimeMode); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimerControlButtonPanel.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimerControlButtonPanel.java deleted file mode 100644 index b8224a774..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimerControlButtonPanel.java +++ /dev/null @@ -1,250 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/TimerControlButtonPanel.java,v $ -// $RCSfile: TimerControlButtonPanel.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.time.RealTimeHandler; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.time.TimerStatus; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The TimerControlButtonPanel provides control for starting and stopping a - * clock contained in a RealTimeHandler. This class also has provisions for - * having the clock run the reverse direction, and for stepping the clock - * forward and backward one interval. - */ -public class TimerControlButtonPanel extends OMComponentPanel implements - TimeEventListener, ActionListener { - - protected ImageIcon backwardStepIcon; - protected ImageIcon backwardIcon; - protected ImageIcon forwardIcon; - protected ImageIcon forwardStepIcon; - protected ImageIcon pauseIcon; - - protected String DefaultBackwardStepIconURL = "stepbackward.png"; - protected String DefaultBackwardIconURL = "playbackward.png"; - protected String DefaultForwardIconURL = "playforward.png"; - protected String DefaultForwardStepIconURL = "stepforward.png"; - protected String DefaultPauseIconURL = "pause.png"; - - protected String backwardStepIconURL = DefaultBackwardStepIconURL; - protected String backwardIconURL = DefaultBackwardIconURL; - protected String forwardIconURL = DefaultForwardIconURL; - protected String forwardStepIconURL = DefaultForwardStepIconURL; - protected String pauseIconURL = DefaultPauseIconURL; - - protected RealTimeHandler timeHandler; - protected JButton forwardButton; - protected JButton backwardButton; - - protected boolean clockEnabled = false; - - public final static String BackwardStepIconProperty = "backwardStepIcon"; - public final static String BackwardIconProperty = "backwardIcon"; - public final static String ForwardStepIconProperty = "forwardStepIcon"; - public final static String ForwardIconProperty = "forwardIcon"; - public final static String PauseIconProperty = "pauseIcon"; - - /** - * Make sure the RealTimeHandler gets set at some point. - */ - public TimerControlButtonPanel() {} - - public TimerControlButtonPanel(RealTimeHandler rth) { - super(); - setTimeHandler(rth); - } - - public void setTimeHandler(RealTimeHandler rth) { - if (timeHandler != null) { - timeHandler.removeTimeEventListener(this); - } - - timeHandler = rth; - - initGUI(); - - if (timeHandler != null) { - timeHandler.addTimeEventListener(this); - } - } - - public RealTimeHandler getTimeHandler() { - return timeHandler; - } - - /** - * Set the ImageIcons to whatever is set on the URL variables. Sets the - * running icon to be the pressed icon, and makes the stopped and inactive - * icons. - */ - public void initGUI() { - removeAll(); - try { - URL url = PropUtils.getResourceOrFileOrURL(this, forwardIconURL); - forwardIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(this, forwardStepIconURL); - forwardStepIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(this, backwardIconURL); - backwardIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(this, backwardStepIconURL); - backwardStepIcon = new ImageIcon(url); - - url = PropUtils.getResourceOrFileOrURL(this, pauseIconURL); - pauseIcon = new ImageIcon(url); - } catch (MalformedURLException murle) { - Debug.error("TimerToggleButton: initGUI() bad icon."); - } catch (NullPointerException npe) { - Debug.error("TimerToggleButton: initGUI() bad icon."); - npe.printStackTrace(); - } - - JToolBar jtb = new JToolBar(); - jtb.setFloatable(false); - - backwardButton = new JButton(backwardIcon); - backwardButton.setToolTipText("Run Timer Backwards"); - backwardButton.setActionCommand(TimerStatus.TIMER_BACKWARD); - backwardButton.addActionListener(this); - jtb.add(backwardButton); - - JButton button = new JButton(backwardStepIcon); - button.setToolTipText("Step Timer Backward"); - button.setActionCommand(TimerStatus.TIMER_STEP_BACKWARD); - button.addActionListener(this); - jtb.add(button); - - button = new JButton(forwardStepIcon); - button.setToolTipText("Step Timer Forward"); - button.setActionCommand(TimerStatus.TIMER_STEP_FORWARD); - button.addActionListener(this); - jtb.add(button); - - forwardButton = new JButton(forwardIcon); - forwardButton.setToolTipText("Run Timer Forward"); - forwardButton.setActionCommand(TimerStatus.TIMER_FORWARD); - forwardButton.addActionListener(this); - jtb.add(forwardButton); - - add(jtb); - } - - /** - * PropertyChangeListener Interface Method used to find out when the timer - * has been stopped and started. Is expecting that the property name and - * value are the actual string objects defined in the TimeConstants - * interface. It does ==, not equals(). - */ - // public void propertyChange(PropertyChangeEvent pce) { - // String propName = pce.getPropertyName(); - // Object obj = pce.getNewValue(); - // if (propName == RealTimeHandler.TIMER_STATUS && obj instanceof String) { - // update((String) obj); - // } - // } - - protected void update(TimerStatus newStatus) { - if (newStatus == TimerStatus.FORWARD) { - if (Debug.debugging("timedetail")) { - Debug.output("TimerControlButtonPanel: TIMER_FORWARD"); - } - backwardButton.setIcon(backwardIcon); - backwardButton.setActionCommand(TimerStatus.TIMER_BACKWARD); - forwardButton.setIcon(pauseIcon); - forwardButton.setActionCommand(TimerStatus.TIMER_STOPPED); - } else if (newStatus == TimerStatus.BACKWARD) { - if (Debug.debugging("timedetail")) { - Debug.output("TimerControlButtonPanel: TIMER_BACKWARD"); - } - forwardButton.setIcon(forwardIcon); - forwardButton.setActionCommand(TimerStatus.TIMER_FORWARD); - backwardButton.setIcon(pauseIcon); - backwardButton.setActionCommand(TimerStatus.TIMER_STOPPED); - } else if (newStatus == TimerStatus.STOPPED) { - if (Debug.debugging("timedetail")) { - Debug.output("TimerControlButtonPanel: TIMER_STOPPED"); - } - forwardButton.setIcon(forwardIcon); - forwardButton.setActionCommand(TimerStatus.TIMER_FORWARD); - backwardButton.setIcon(backwardIcon); - backwardButton.setActionCommand(TimerStatus.TIMER_BACKWARD); - } - - checkClock(newStatus); - } - - protected void checkClock(TimerStatus newStatus) { - boolean clockState = newStatus != TimerStatus.INACTIVE; - if (clockState != clockEnabled) { - clockEnabled = clockState; - setEnableState(clockEnabled); - } - } - - /** - * ActionListener Interface Method listens to the timer, in case something - * else starts it, we can update the gui. Also listens to this button, to - * start and stop the given timer. - */ - public void actionPerformed(ActionEvent ae) { - String cmd = ae.getActionCommand(); - if (cmd == TimerStatus.TIMER_FORWARD) { - timeHandler.setClockDirection(1); - timeHandler.startClock(); - } else if (cmd == TimerStatus.TIMER_BACKWARD) { - timeHandler.setClockDirection(-1); - timeHandler.startClock(); - } else if (cmd == TimerStatus.TIMER_STEP_BACKWARD) { - timeHandler.stepBackward(); - } else if (cmd == TimerStatus.TIMER_STEP_FORWARD) { - timeHandler.stepForward(); - } else if (cmd == TimerStatus.TIMER_STOPPED) { - timeHandler.stopClock(); - } - } - - public void updateTime(TimeEvent te) { - update(te.getTimerStatus()); - } - - public void setEnableState(boolean set) { - forwardButton.setEnabled(set); - backwardButton.setEnabled(set); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/gui/time/TimerRateComboBox.java b/src/core/src/main/java/com/bbn/openmap/gui/time/TimerRateComboBox.java deleted file mode 100644 index 06050e3bb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/gui/time/TimerRateComboBox.java +++ /dev/null @@ -1,146 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/TimerRateComboBox.java,v $ -// $RCSfile: TimerRateComboBox.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.time; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.JComboBox; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.time.RealTimeHandler; -import com.bbn.openmap.util.Debug; - -/** - * The TimerRateComboBox is a general pace selector for a - * RealTimeHandler. It provides a JComboBox interface (pop-up menu) - * that shows discrete choices of rates for timer/scenario settings. - * The RealTimeHandler can set these choices, with the GUI display - * name of the choice, the timer interval and the scenario pace that - * the interval represents. - */ -public class TimerRateComboBox extends JComboBox implements ActionListener, - PropertyConsumer { - - /** - * The RealTimeHandler to be updated. - */ - protected RealTimeHandler timeHandler; - - public TimerRateComboBox(RealTimeHandler rth) { - super(); - addActionListener(this); - setTimeHandler(rth); - } - - /** - * Only TimerRateHolders can be added. - */ - public void addItem(Object obj) { - if (obj instanceof TimerRateHolder) { - super.addItem(obj); - } else { - Debug.error("TimerRateComboBox: Only TimerRateHolders can be added"); - } - } - - /** - * The preferred way to add choices, since it creates the - * TimerRateHolder for you. - */ - public void add(String string, int interval, int pace) { - super.addItem(new TimerRateHolder(string, interval, pace)); - } - - public void setTimeHandler(RealTimeHandler rth) { - timeHandler = rth; - } - - public RealTimeHandler getTimeHandler() { - return timeHandler; - } - - /** - * When a choice is made, the TimerRateComboBox updates the - * RealTimeHandler. - */ - public void actionPerformed(ActionEvent ae) { - Object obj = ae.getSource(); - - if (obj == this) { - TimerRateHolder trh = (TimerRateHolder) getSelectedItem(); - trh.modifyTimer(getTimeHandler()); - } - } - - ///// Property Consumer Interface Methods - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - } - - public Properties getProperties(Properties props) { - return props; - } - - public Properties getPropertyInfo(Properties props) { - return props; - } - - protected String propPrefix = null; - - public String getPropertyPrefix() { - return propPrefix; - } - - public void setPropertyPrefix(String prefix) { - propPrefix = prefix; - } - - public class TimerRateHolder { - - protected String title; - protected int timerInterval; - protected int pace; - - public TimerRateHolder(String t, int ti, int p) { - title = t; - timerInterval = ti; - pace = p; - } - - public void modifyTimer(RealTimeHandler rth) { - rth.setPace(pace); - rth.setUpdateInterval(timerInterval); - } - - public String toString() { - return title; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/AbstractImageFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/AbstractImageFormatter.java deleted file mode 100644 index a777b04e6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/AbstractImageFormatter.java +++ /dev/null @@ -1,443 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/AbstractImageFormatter.java,v $ -// $RCSfile: AbstractImageFormatter.java,v $ -// $Revision: 1.11 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsEnvironment; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The abstract implementation of the ImageFormatter. The ImageFormatter deals - * with most of the image meanderings of Java, while letting you create an image - * in a specific format. The ImageFormatter's responsibility has grown slightly, - * since it now contains the BufferedImage that it will be formatting. Thisis to - * make things go smoother for different uses of the formatter - some image - * formats, for instance, really need to utilize a special implementation of a - * Graphics in order to create the data file they want. The new definition - * allows for that. Generally, however, you'll want to either hand the MapBean - * to the formatter to get the image bytes, or, as in the case of the - * ImageServer, get a Graphics from the formatter, paint the map into it, then - * retrieve the image bytes after that. - */ -public abstract class AbstractImageFormatter - implements ImageFormatter, PropertyConsumer, PropertyChangeListener { - - protected BufferedImage bufferedImage; - protected String propertiesPrefix; - - public AbstractImageFormatter() { - } - - /** Set the properties of the image formatter. */ - public void setProperties(String prefix, Properties props) { - } - - /** - * Convert a BufferedImage to a image file format... - * - * @param bi a BufferedImage.. - */ - public abstract byte[] formatImage(BufferedImage bi); - - /** - * Create a new instance of the same type of formatter. If you are running - * in a multi-threaded environment, you'll need to provide a new instance of - * the formatter to each thread, since the image and graphics that are being - * drawn into for each thread are contained within. - * - * @return a new instance of this type of formatter, with the same - * properties set. - */ - public abstract ImageFormatter makeClone(); - - /** - * Return true if the image format support fully transparent pixels. The - * returned value represent the capability of the image format, not the - * current color model. - * - * @return true of transparent pixels supported - */ - protected abstract boolean imageFormatSupportTransparentPixel(); - - /** - * Return true if the image format support alpha channel. The returned value - * represent the capability of the image format, not the current color - * model. - * - * @return true if alpha supported - */ - protected abstract boolean imageFormatSupportAlphaChannel(); - - /** - * Take a MapBean, and get the image bytes that represent the current state. - * - * @param map the MapBean. - * @return byte[] representing an image of the map in it's current state. - */ - public byte[] getImageFromMapBean(MapBean map) { - return getImageFromMapBean(map, -1, -1, false); - } - - /** - * Take a MapBean, and get the image bytes that represent the current state. - * - * @param map the MapBean. - * @param width the pixel width of the desired image. - * @param height the pixel height of the desired image. - * @return byte[] representing an image of the map in it's current state. - */ - public byte[] getImageFromMapBean(MapBean map, int width, int height) { - return getImageFromMapBean(map, width, height, true); - } - - /** - * Take a MapBean, and get the image bytes that represent the current state. - * - * @param map the MapBean. - * @param width the pixel width of the desired image. - * @param height the pixel height of the desired image. - * @param scaleImage true to resize image based on scale - * @return byte[] representing an image of the map in it's current state. - */ - public byte[] getImageFromMapBean(MapBean map, int width, int height, boolean scaleImage) { - if (map == null) { - return new byte[0]; - } - - Proj proj = (Proj) map.getProjection(); - - boolean needToScale = (width != proj.getWidth() || height != proj.getHeight()); - - if (Debug.debugging("formatter")) { - Debug.output("AIF: called with w:" + width + ", h:" + height + ", need to scale (" + needToScale + ")" - + " and scaleImage (" + scaleImage + ")"); - } - - if (width == -1) - width = proj.getWidth(); - if (height == -1) - height = proj.getHeight(); - - Graphics graphics = getGraphics(width, height); - - if (!needToScale) { - if (Debug.debugging("formatter")) { - Debug.output("AIF: don't need to scale, painting normally."); - } - // This way just paints what the MapBean is displaying. - map.paintAll(graphics); - } else { - // One problem with this approach is that it will - // use the ProjectionPainter interface on the layers. So, - // you may not get the same image that is on the map. All - // layers on the map will get painted in the image - so if - // a layer hasn't painted itself on the map window, you - // will see it in the image. - - // This lets us know what the layers are - map.addPropertyChangeListener(this); - - // Layers should be set... - Point2D cp = map.getCenter(); - - double scaleMod = 1f;// scale factor for image scale - // If we need to scale the image, - // figure out the scale factor. - if (scaleImage) { - if (Debug.debugging("formatter")) { - Debug.output("AIF: scaling image to w:" + width + ", h:" + height); - } - double area1 = (double) proj.getHeight() * (double) proj.getWidth(); - double area2 = (double) height * (double) width; - scaleMod = Math.sqrt(area1 / area2); - } - - Proj tp = - (Proj) map.getProjectionFactory().makeProjection(map.getProjection().getClass(), cp, - map.getScale() * (float) scaleMod, width, height); - - tp.drawBackground((Graphics2D) graphics, map.getBckgrnd()); - - if (layers != null) { - for (int i = layers.length - 1; i >= 0; i--) { - Projection oldProj = layers[i].getProjection(); - layers[i].renderDataForProjection(tp, graphics); - if (Debug.debugging("formatter")) { - Debug.output("AbstractImageFormatter: rendering " + layers[i].getName()); - } - // Need to set the old Projection object on the - // Layer, not the current MapBean Proj object. If - // you set the MapBean Proj object, make sure you - // clone it first. The Layer will do a check on - // the Projection object it has against any new - // ones it receives. If it has the original from - // the MapBean, the check it does will return a - // false negative, and the layer will think it - // doesn't have to do anything. - - if (oldProj != null && oldProj == map.getProjection()) { - // Seems like a lot of users are getting - // burned by manually setting the same - // projection on the MapBean as they are on - // the layers, and the layers are freezing up - // after they are used to create an image. - - // I don't see how this problem is manifesting - // itself, but this code section is an attempt - // to help. - oldProj = oldProj.makeClone(); - } - - layers[i].setProjection(oldProj); - } - - } else { - Debug.output("AbstractImageFormatter can't get layers from map!"); - } - - map.removePropertyChangeListener(this); - layers = null; - } - - return getImageBytes(); - } - - /** - * Return the applicable Graphics to use to paint the layers into. If the - * internal BufferedImage hasn't been created yet, or has been set to null, - * then a new buffered Image is created, set to the size specified by the - * height and width. The ImageGenerator extends MapBean. Remember to dispose - * of the graphics object when you are done with it. Uses the default - * BufferedImage.TYPE_INT_RGB colormodel. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @return Graphics object to use. - * @see java.awt.image.BufferedImage - */ - public Graphics getGraphics(int width, int height) { - return getGraphics(width, height, BufferedImage.TYPE_INT_RGB); - } - - public java.awt.Graphics getGraphics(int width, int height, boolean alpha) { - int imageFormat = BufferedImage.TYPE_INT_RGB; - if (alpha && (imageFormatSupportAlphaChannel() || imageFormatSupportTransparentPixel())) { - imageFormat = BufferedImage.TYPE_INT_ARGB; - } - return getGraphics(width, height, imageFormat); - } - - /** - * Return the applicable Graphics to use to paint the layers into. If the - * internal BufferedImage hasn't been created yet, or has been set to null, - * then a new buffered Image is created, set to the size specified by the - * height and width. The ImageGenerator extends MapBean. Remember to dispose - * of the graphics object when you are done with it. Lets you select the - * image type. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @param imageType image type - see BufferedImage - * @return java.awt.Graphics object to use. - * @see java.awt.image.BufferedImage - */ - public Graphics getGraphics(int width, int height, int imageType) { - bufferedImage = new BufferedImage(width, height, imageType); - - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - Graphics g = ge.createGraphics(bufferedImage); - g.setClip(0, 0, width, height); - return g; - } - - /** - * Return the BufferedImage contained within the formatter. - * - * @return the BufferedImage. - */ - public BufferedImage getBufferedImage() { - return bufferedImage; - } - - /** - * Return the BufferedImage contained within the formatter. - * - * @param bi the BufferedImage to use in this formatter. - */ - public void setBufferedImage(BufferedImage bi) { - bufferedImage = bi; - } - - /** - * Scale the internal BufferedImage to the pixel dimensions, and then return - * it. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return the scaled BufferedImage. - */ - public BufferedImage getScaledBufferedImage(int scaledWidth, int scaledHeight) { - - if (bufferedImage == null) { - return null; - } - - if (Debug.debugging("formatter")) { - Debug.output("Formatter: scaling image to : " + scaledWidth + ", " + scaledHeight); - } - - int imageType = (imageFormatSupportTransparentPixel() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB); - // Algorithm takes overall size? - java.awt.Image image = ImageScaler.getOptimalScalingImage(bufferedImage, bufferedImage.getWidth(), scaledWidth, imageType); - - if (Debug.debugging("formatter")) { - Debug.output("Formatter: creating scaled image..."); - } - - try { - - BufferedImage buffi = BufferedImageHelper.getBufferedImage(image, 0, 0, -1, -1, imageType); - - // Do this here, in case something bad happens in the - // buffered image creation, so at least the original image - // is retained. - bufferedImage = buffi; - } catch (InterruptedException ie) { - Debug.error("Formatter: Something bad happened during scaling! \n" + ie); - } - - if (Debug.debugging("formatter")) { - Debug.output("Formatter: image successfully scaled"); - } - - return bufferedImage; - } - - /** - * Return the image bytes of the formatted image. - * - * @return byte[] representing the image. - */ - public byte[] getImageBytes() { - BufferedImage bi = getBufferedImage(); - if (bi == null) { - return new byte[0]; - } else { - Debug.message("formatter", "Formatter: creating formatted image bytes..."); - return formatImage(bi); - } - } - - /** - * Scale the internal BufferedImage, then return the image bytes of the - * formatted image. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return byte[] representing the image. - */ - public byte[] getScaledImageBytes(int scaledWidth, int scaledHeight) { - BufferedImage bi = getScaledBufferedImage(scaledWidth, scaledHeight); - if (bi == null) { - return new byte[0]; - } else { - Debug.message("formatter", "Formatter: creating formatted image bytes..."); - return formatImage(bi); - } - } - - /** - * Set the layers and image type in the properties. - */ - public void setProperties(Properties props) { - setProperties((String) null, props); - } - - /** - * Part of the PropertyConsumer interface. Doesn't do anything yet. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - return props; - } - - /** - * Part of the PropertyConsumer interface. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - return list; - - } - - /** - * Part of the PropertyConsumer interface. Set the Properties prefix to use - * to scope the relevant properties passed into the setProperties method. - */ - public void setPropertyPrefix(String prefix) { - propertiesPrefix = prefix; - } - - /** - * Part of the PropertyConsumer interface. Get the Properties prefix used to - * scope the relevant properties passed into the setProperties method. - */ - public String getPropertyPrefix() { - return propertiesPrefix; - } - - /** - * Used when the layers from the MapBean are needed, in order to use the - * renderDataForProjection method. - */ - protected Layer[] layers = null; - - /** - * Used when the layers from the MapBean are needed, in order to use the - * renderDataForProjection method. Sets the Layer[] by adding the formatter - * as a PropertyChangeListener to the MapBean. Remember to remove the - * formatter from the MapBean as a PropertyChangeListener. - */ - public void propertyChange(PropertyChangeEvent pce) { - String propName = pce.getPropertyName(); - if (propName == MapBean.LayersProperty) { - layers = (Layer[]) pce.getNewValue(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/AcmeGifFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/AcmeGifFormatter.java deleted file mode 100644 index 23ae84371..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/AcmeGifFormatter.java +++ /dev/null @@ -1,97 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/AcmeGifFormatter.java,v $ -// $RCSfile: AcmeGifFormatter.java,v $ -// $Revision: 1.4 $ -// $Date: 2008/02/20 01:41:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.http.HttpConnection; - -/** - * This formatter requires the Acme.JPM.Encoders package. That code - * can be found at http://www.acme.com/java . - */ -public class AcmeGifFormatter extends AbstractImageFormatter { - - public AcmeGifFormatter() {} - - public void setProperties(String prefix, Properties props) {} - - public ImageFormatter makeClone() { - return new AcmeGifFormatter(); - } - - public byte[] formatImage(BufferedImage bi) { - try { - return AcmeGifHelper.encodeGif(bi); - } catch (java.io.IOException ioe) { - Debug.error("AcmeGifFormatter caught IOException formatting image!\n " - + ioe); - return new byte[0]; - } - } - - /** - * Get the Image Type created by the ImageFormatter. These - * responses should adhere to the OGC WMT standard format labels. - * Some are listed in the WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_GIF; - } - - /** - * Return the applicable Graphics to use to paint the layers into. - * If the internal BufferedImage hasn't been created yet, or has - * been set to null, then a new buffered Image is created, set to - * the size specified by the height and width. The ImageGenerator - * extends MapBean. Remember to dispose of the graphics object - * when you are done with it. Uses the BufferedImage.TYPE_INT_ARGB - * colormodel. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @return java.awt.Graphics object to use. - * @see java.awt.image.BufferedImage - */ - public java.awt.Graphics getGraphics(int width, int height) { - return getGraphics(width, height, BufferedImage.TYPE_INT_ARGB); - } - - public String getContentType() { - return HttpConnection.CONTENT_GIF; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return false; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return true; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/AcmeGifHelper.java b/src/core/src/main/java/com/bbn/openmap/image/AcmeGifHelper.java deleted file mode 100644 index 54bc68fc4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/AcmeGifHelper.java +++ /dev/null @@ -1,85 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/AcmeGifHelper.java,v $ -// $RCSfile: AcmeGifHelper.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/01/10 16:14:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import com.bbn.openmap.util.Debug; - -/** - * This class provides some utility methods for creating gif encoded - * images, using the Acme code available at http://www.acme.com/java/ - * A copy has been included in the contrib directory. - */ -public class AcmeGifHelper { - - /** - * This class has only static methods, so there is no need to - * construct anything. - */ - private AcmeGifHelper() {} - - /** - * Return a byte array that contains the GIF encoded image. - * - * @param image the image to encode - * @exception IOException an error occurred in encoding the image - */ - public static byte[] encodeGif(BufferedImage image) throws IOException { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - if (Debug.debugging("acmegifhelper")) { - Debug.output("Got output stream..." + out); - } - - Acme.JPM.Encoders.GifEncoder enc = new Acme.JPM.Encoders.GifEncoder(image, out); - if (Debug.debugging("acmegifhelper")) { - Debug.output("Got gif encoder..."); - } - - enc.encode(); - if (Debug.debugging("acmegifhelper")) { - Debug.output("encoded?"); - } - - return out.toByteArray(); - } - - /** - * Return a byte array that contains the GIF encoded image. - * - * @param w the width of the image - * @param h the height of the image - * @param pixels the array of pixels in RGB directcolor - * @exception IOException an error occurred in encoding the image - */ - public static byte[] encodeGif(int w, int h, int[] pixels) - throws IOException { - BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - bi.setRGB(0, 0, w, h, pixels, 0, w); - pixels = null; - return encodeGif(bi); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/BufferedImageHelper.java b/src/core/src/main/java/com/bbn/openmap/image/BufferedImageHelper.java deleted file mode 100644 index a48c9f656..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/BufferedImageHelper.java +++ /dev/null @@ -1,400 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/BufferedImageHelper.java,v $ -// $RCSfile: BufferedImageHelper.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/08/09 21:08:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.PixelGrabber; -import java.awt.image.WritableRaster; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.util.ComponentFactory; - -/** - * This class provides some utility methods for creating a BufferedImage. It - * will check to see if the Java Advanced Image package is available and use it - * if it can. - * - * @author dietrick - original implementation and reflection mods. - * @author Fredrik Lyden - JAI inspiration and initial code. - */ -public class BufferedImageHelper { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.io.BufferedImageHelper"); - - /** - * This class has only static methods, so there is no need to construct - * anything. - */ - private BufferedImageHelper() { - } - - /** - * A test/instantiation copy of the JAI object to use if JAI is installed. - */ - private static Object jaiObj = null; - /** - * Flag to use if the JAI has be checked for. - */ - private static boolean checkedForJAI = false; - - /** - * Get the JAI class if it's available. - */ - protected static Object getJAI() { - if (!checkedForJAI) { - jaiObj = ComponentFactory.create("javax.media.jai.JAI"); - checkedForJAI = true; - } - return jaiObj; - } - - /** - * Run the operation on JAI to create BufferedImage. Uses reflection to - * determine if JAI is available. - * - * @param opName JAI opName, like "file" or "url" - * @param param JAI object to use for operation, like the file path (String) - * or URL. - * @return BufferedImage if JAI can be used to create it, null if anything - * goes wrong. - */ - public static BufferedImage getJAIBufferedImage(String opName, Object param) { - boolean DEBUG = logger.isLoggable(Level.FINE); - - Object jai = getJAI(); - - if (jai == null) { - return null; - } - - if (DEBUG) { - logger.fine("Using JAI to create image from " + opName); - } - - try { - // Do a little reflection to run methods on classes we - // might not know about. - Class[] createArgs = new Class[] { - Class.forName("java.lang.String"), - Class.forName("java.lang.Object") - }; - - Method createMethod = jai.getClass().getDeclaredMethod("create", createArgs); - - Object[] createParams = new Object[] { - opName, - param - }; - Object planarImageObject = createMethod.invoke(jai, createParams); - - if (planarImageObject != null) { - Method getBufferedImageMethod = planarImageObject.getClass().getMethod("getAsBufferedImage", (Class[]) null); - - return (BufferedImage) getBufferedImageMethod.invoke(planarImageObject, (Object[]) null); - } - - } catch (ClassNotFoundException cnfe) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() ClassNotFoundException error: \n" + cnfe.getMessage()); - } - } catch (IllegalAccessException iae) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() IllegalAccessException error: \n" + iae.getMessage()); - } - } catch (InvocationTargetException ite) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() InvocationTargetException error: \n" + ite.getMessage()); - } - } catch (NoSuchMethodException nsme) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() NoSuchMethodException error: " + nsme.toString()); - nsme.printStackTrace(); - } - } catch (SecurityException se) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() SecurityException error: \n" + se.getMessage()); - } - } catch (Exception e) { - if (DEBUG) { - logger.warning("BufferedImageHelper.getJAIBufferedImage() Exception: \n" + e.getMessage()); - } - } - - return null; - // All this above to replace this: - // PlanarImage planarImage = JAI.create(opName, param); - // return getBufferedImage(planarImage.getAsBufferedImage(), - // x, y, w, h); - } - - /** - * Run the operation on JAI to create BufferedImage. Uses reflection to - * determine if JAI is available. If x or y is not zero, or w and h are not - * the image dimensions, the image returned will be cropped/translated to - * match the values. - * - * @param opName JAI opName, like "file" or "url" - * @param param JAI object to use for operation, like the file path (String) - * or URL. - * @param x x start pixel - * @param y y start pixel - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @return BufferedImage if JAI can be used to create it, null if anything - * goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getJAIBufferedImage(String opName, Object param, int x, int y, int w, int h) - throws InterruptedException { - - BufferedImage bi = getJAIBufferedImage(opName, param); - - // If the whole image isn't wanted, do another operation... - if (bi != null && (x != 0 || y != 0 || w > 0 || h > 0)) { - - int imageType = BufferedImage.TYPE_INT_RGB; - if (bi.getColorModel().hasAlpha()) { - imageType = BufferedImage.TYPE_INT_ARGB; - } - - return getBufferedImage(bi, x, y, w, h, imageType); - } - // else return null or the original image. - return bi; - } - - /** - * Return a BufferedImage loaded from a URL. - * - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(URL url) - throws InterruptedException { - return getBufferedImage(url, 0, 0, -1, -1); - } - - /** - * Return a BufferedImage loaded from a URL. If JAI isn't available, checks - * the file path to see if it ends in jpg or jpeg, and won't try to use an - * alpha channel if it does. - * - * @param url the source URL - * @param x x start pixel - * @param y y start pixel - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(URL url, int x, int y, int w, int h) - throws InterruptedException { - - if (url == null) { - return null; - } - - BufferedImage bi = getJAIBufferedImage("url", url, x, y, w, h); - - if (bi != null) { - return bi; - } - - logger.fine("BufferedImageHelper.getBufferedImage(URL) can't use JAI, using ImageIcon"); - - // if JAI is not installed.... - ImageIcon ii = new ImageIcon(url); - String path = url.getPath(); - boolean noAlpha = path.endsWith("jpg") || path.endsWith("jpeg"); - - BufferedImage bufferedImage = getBufferedImage(ii, x, y, w, h, !noAlpha); - ii.getImage().flush(); - return bufferedImage; - } - - /** - * Return a BufferedImage loaded from a URL. Doesn't use JAI if available. - * - * @param ii an ImageIcon created from the source. - * @param x x start pixel - * @param y y start pixel - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @param hasAlpha whether the image should be transparent. - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(ImageIcon ii, int x, int y, int w, int h, boolean hasAlpha) - throws InterruptedException { - if (w <= 0) - w = ii.getIconWidth(); - if (h <= 0) - h = ii.getIconHeight(); - - return getBufferedImage(ii.getImage(), x, y, w, h, (hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB)); - } - - /** - * Return a BufferedImage loaded from a file path. - * - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(String path) - throws InterruptedException { - return getBufferedImage(path, 0, 0, -1, -1); - } - - /** - * Return a BufferedImage loaded from an image file path. If JAI isn't - * available, checks the file path to see if it ends in jpg or jpeg, and - * won't try to use an alpha channel if it does. - * - * @param path file path to the image - * @param x x start pixel - * @param y y start pixel - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(String path, int x, int y, int w, int h) - throws InterruptedException { - - BufferedImage bi = getJAIBufferedImage("file", path, x, y, w, h); - - if (bi != null) { - return bi; - } - - logger.fine("BufferedImageHelper.getBufferedImage(path) can't use JAI, using ImageIcon"); - - // if JAI is not installed.... - ImageIcon ii = new ImageIcon(path); - boolean noAlpha = path.endsWith("jpg") || path.endsWith("jpeg"); - - return getBufferedImage(ii, x, y, w, h, !noAlpha); - } - - /** - * Return a BufferedImage loaded from a Image. The type of image is - * BufferedImage.Type_INT_RGB. If you know the height and width, use them - * because it's slower to have the class figure it out. - * - * @param image the source Image - * @param x x start pixel - * @param y y start pixel - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(Image image, int x, int y, int w, int h) - throws InterruptedException { - return getBufferedImage(image, x, y, w, h, BufferedImage.TYPE_INT_RGB); - } - - /** - * Return a BufferedImage loaded from a Image. If you know the height and - * width, use them because it's slower to have the class figure it out. - * - * @param image the source Image - * @param x x start pixel - the horizontal pixel location in the returned - * image that the provided image will be set. - * @param y y start pixel - the vertical pixel location in the returned - * image that the provided image will be set. - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @param imageType the image color model. See BufferedImage. - * @return BufferedImage if it can be created, null if anything goes wrong. - * @throws InterruptedException - */ - public static BufferedImage getBufferedImage(Image image, int x, int y, int w, int h, int imageType) - throws InterruptedException { - - if (w <= 0 || h <= 0) { - logger.fine("BufferedImageHelper.getBufferedImage() don't know h/w, using pixel grabber"); - return getBufferedImageFromPixelGrabber(image, x, y, w, h, imageType); - } else { - BufferedImage bufferedImage = new BufferedImage(w, h, imageType); - Graphics2D g2d = bufferedImage.createGraphics(); - g2d.drawImage(image, x, y, null); - g2d.dispose(); - return bufferedImage; - } - } - - /** - * Return a BufferedImage loaded from a Image, using a PixelGrabber. Good - * for when you have an Image, not a BufferedImage, and don't know the width - * and height. There is a performance penalty with this method, though. - * - * @param image the source Image - * @param x x start pixel - the horizontal pixel location in the returned - * image that the provided image will be set. - * @param y y start pixel - the vertical pixel location in the returned - * image that the provided image will be set. - * @param w crop width (-1 uses image width) - * @param h crop height (-1 uses image height) - * @param imageType the image color model. See BufferedImage. - * @return BufferedImage if it can be created, null if anything goes wrong. - */ - public static BufferedImage getBufferedImageFromPixelGrabber(Image image, int x, int y, int w, int h, int imageType) { - - PixelGrabber pg = new PixelGrabber(image, x, y, w, h, true); - int[] pixels = ImageHelper.grabPixels(pg); - - if (pixels == null) { - return null; - } - - w = pg.getWidth(); - h = pg.getHeight(); - pg = null; - - BufferedImage bi = new BufferedImage(w, h, imageType); - logger.fine("BufferedImageHelper.getBufferedImage(): Got buffered image..."); - - // bi.setRGB(0, 0, w, h, pixels, 0, w); - /** - * Looking at the standard BufferedImage code, an int[0] is allocated - * for every pixel. Maybe the memory usage is optimized for that, but it - * goes through a call stack for every pixel to do it. Let's just cycle - * through the data and write the pixels directly into the raster. - */ - WritableRaster raster = (WritableRaster) bi.getRaster(); - raster.setDataElements(0, 0, w, h, pixels); - - logger.fine("BufferedImageHelper.getBufferedImage(): set pixels in image..."); - - return bi; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ColorReducer.java b/src/core/src/main/java/com/bbn/openmap/image/ColorReducer.java deleted file mode 100644 index 3d75fda68..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ColorReducer.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.bbn.openmap.image; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.awt.image.IndexColorModel; -import java.awt.image.WritableRaster; -import java.util.Arrays; - -import com.bbn.openmap.omGraphics.OMColor; - -import doppelt.Quantize; -import doppelt.Quantize32; - -/** - * A with some static methods to reduce the number of colors in a - * {@link BufferedImage}. - * - * @author halset - */ -public class ColorReducer { - - private ColorReducer() { - } - - /** - * Reduce a 24 bit image to the given number of colors. Support fully - * transparent pixels, but not partially transparent pixels. - * - * @param bi - * @param colors - * @return BufferedImage with reduced colors. - */ - public static BufferedImage reduce24(BufferedImage bi, int colors) { - int width = bi.getWidth(); - int height = bi.getHeight(); - int[][] pixels = new int[width][height]; - boolean[][] transparent = new boolean[width][height]; - - WritableRaster r1 = bi.getRaster(); - boolean inputHasAlpha = bi.getColorModel().hasAlpha(); - int[] argb = new int[4]; - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - // this is easier than bi.getRGB, but still heavy - argb = r1.getPixel(x, y, argb); - int r = argb[0]; - int g = argb[1]; - int b = argb[2]; - pixels[x][y] = /* (a << 24) | */(r << 16) | (g << 8) | (b); - - if (inputHasAlpha) { - int a = argb[3]; - pixels[x][y] |= (a << 24); - // decide if pixel is transparent or not - transparent[x][y] = (a < 128) ? true : false; - } - } - } - - int[] palette = Quantize.quantizeImage(pixels, colors - 1); - - byte[] r = new byte[colors]; - byte[] g = new byte[colors]; - byte[] b = new byte[colors]; - byte[] a = new byte[colors]; - - // need to have full(256) size array to get rid of ugly rare errors msg - // from GIFImageWriter. We also need the *first* entry to be - // transparent. - Arrays.fill(r, (byte) OMColor.clear.getRed()); - Arrays.fill(g, (byte) OMColor.clear.getGreen()); - Arrays.fill(b, (byte) OMColor.clear.getBlue()); - Arrays.fill(a, (byte) OMColor.clear.getAlpha()); - - for (int i = 0; i < palette.length; i++) { - Color c = new Color(palette[i], true); - r[i + 1] = (byte) c.getRed(); - g[i + 1] = (byte) c.getGreen(); - b[i + 1] = (byte) c.getBlue(); - a[i + 1] = (byte) c.getAlpha(); - } - - IndexColorModel colorModel = new IndexColorModel(8, r.length, r, g, b, a); - - // create a image with the reduced colors - BufferedImage reducedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, colorModel); - - // manipulate raster directly for best performance & color match - WritableRaster raster = reducedImage.getRaster(); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - // add 1 as transparent is first - int value = transparent[x][y] ? 0 : (pixels[x][y] + 1); - raster.setSample(x, y, 0, value); - } - } - - return reducedImage; - } - - /** - * Reduce a 32 bit image to the given number of colors. Support partially - * transparent pixels. - * - * @param bi - * @param colors - * @return BufferedImage with reduced colors. - */ - public static BufferedImage reduce32(BufferedImage bi, int colors) { - int width = bi.getWidth(); - int height = bi.getHeight(); - int[][] pixels = new int[width][height]; - - WritableRaster r1 = bi.getRaster(); - int[] argb = new int[4]; - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - // this is easier than bi.getRGB, but still heavy - argb = r1.getPixel(x, y, argb); - int a = argb[3]; - int r = argb[0]; - int g = argb[1]; - int b = argb[2]; - pixels[x][y] = (a << 24) | (r << 16) | (g << 8) | (b); - } - } - - int[] palette = Quantize32.quantizeImage(pixels, colors); - colors = palette.length; - - // ImageIO (at least on Mac) does not like to *read* png images with - // only a single color in the color index - boolean useExtraColors = false; - int minimumColors = 2; - if (colors < minimumColors) { - colors = minimumColors; - useExtraColors = true; - } - - byte[] r = new byte[colors]; - byte[] g = new byte[colors]; - byte[] b = new byte[colors]; - byte[] a = new byte[colors]; - - if (useExtraColors) { - // can not be clear as ArcGIS does not handle PNG with multiple - // clear entries in the color index - Arrays.fill(r, (byte) OMColor.green.getRed()); - Arrays.fill(g, (byte) OMColor.green.getGreen()); - Arrays.fill(b, (byte) OMColor.green.getBlue()); - Arrays.fill(a, (byte) OMColor.green.getAlpha()); - } - - for (int i = 0; i < palette.length; i++) { - Color c = new Color(palette[i], true); - r[i] = (byte) c.getRed(); - g[i] = (byte) c.getGreen(); - b[i] = (byte) c.getBlue(); - a[i] = (byte) c.getAlpha(); - } - - IndexColorModel colorModel = new IndexColorModel(8, r.length, r, g, b, a); - - // create a image with the reduced colors - BufferedImage reducedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, colorModel); - - // manipulate raster directly for best performance & color match - WritableRaster raster = reducedImage.getRaster(); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - int value = pixels[x][y]; - raster.setSample(x, y, 0, value); - } - } - - return reducedImage; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/GIFImageIOFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/GIFImageIOFormatter.java deleted file mode 100644 index 6b3e9b826..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/GIFImageIOFormatter.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// (C) Copyright 2004 NAVICON A/S. All Rights Reserved. -// http://www.navicon.dk -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GIFImageIOFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/02/20 01:41:08 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; - -import javax.imageio.ImageIO; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.http.HttpConnection; - -public class GIFImageIOFormatter extends ImageIOFormatter { - - public GIFImageIOFormatter() { - setFormatName("gif"); - } - - public ImageFormatter makeClone() { - return new GIFImageIOFormatter(); - } - - public byte[] formatImage(BufferedImage bi) { - BufferedImage reducedImage = ColorReducer.reduce24(bi, 256); - try { - ByteArrayOutputStream byo = new ByteArrayOutputStream(); - ImageIO.write(reducedImage, getFormatName(), byo); - return byo.toByteArray(); - } catch (java.io.IOException e) { - Debug.error("ImageIOFormatter caught IOException formatting image!"); - return new byte[0]; - } - } - - /** - * Get the Image Type created by the ImageFormatter. These responses should - * adhere to the OGC WMT standard format labels. Some are listed in the - * WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_GIF; - } - - public String getContentType() { - return HttpConnection.CONTENT_GIF; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return false; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return true; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/GeneratorTester.java b/src/core/src/main/java/com/bbn/openmap/image/GeneratorTester.java deleted file mode 100644 index 8d3a18659..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/GeneratorTester.java +++ /dev/null @@ -1,140 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/GeneratorTester.java,v $ -// $RCSfile: GeneratorTester.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 17:56:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.Debug; - -/** - * A test class to play around with the image server. - * - * @deprecated uses ImageServer methods no longer supported. - */ -public class GeneratorTester implements ImageReceiver { - - ImageServer server; - String propertiesURLString = null; - String fileName = null; - Properties props = null; - - public GeneratorTester(String[] args) { - - props = System.getProperties(); - Debug.init(props); - parseArgs(args); - try { - URL propsURL = new URL(propertiesURLString); - Environment.init(props); - loadProperties(propsURL, props); - } catch (MalformedURLException mul) { - System.out.println("GeneratorTester: Malformed URL"); - return; - } - -// Projection proj = ProjectionFactory.makeProjection(CADRG.class, -// 42.0f, -// -72.0f, -// 5000000f, -// 500, -// 500); - - server = new ImageServer(props); - -// server.createImage(proj, this); - } - - public void receiveImageData(byte[] bytes) { - try { - File f = new File(fileName); - OutputStream writef = new FileOutputStream(f); - writef.write(bytes); - writef.close(); - System.out.println(fileName + " JPEG written."); - } catch (IOException ioe) { - System.out.println("No JPEG written due to IOExeception."); - } - System.exit(0); - } - - /** - * Test the image generator. - * - */ - public static void main(String[] args) { - new GeneratorTester(args); - } - - /** - * Loads properties from a java resource. This will load the named - * resource identifier into the given properties instance. - * - * @param props the Properties instance to receive the properties - * @param url the resource to load - */ - public boolean loadProperties(URL url, Properties props) { - try { - InputStream propsIn = url.openStream(); - props.load(propsIn); - return true; - } catch (java.io.IOException e) { - return false; - } - } - - /** - */ - public void parseArgs(String[] args) { - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-url")) { - propertiesURLString = args[++i]; - } else if (args[i].equalsIgnoreCase("-outputFile")) { - fileName = args[++i]; - } else if (args[i].equalsIgnoreCase("-h")) { - printHelp(); - } - } - - if (propertiesURLString == null || fileName == null) { - printHelp(); - } - } - - /** - * printHelp should print a usage statement which reflects - * the command line needs of the tester. - */ - public void printHelp() { - System.err.println("usage: java GeneratorTester -url -outputFile "); - System.exit(1); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/ImageFormatter.java deleted file mode 100644 index 95283ad47..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageFormatter.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageFormatter.java,v $ -// $RCSfile: ImageFormatter.java,v $ -// $Revision: 1.3 $ -// $Date: 2008/02/20 01:41:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.util.Properties; - -/** - * The ImageFormatter deals with most of the image meanderings of - * Java, while letting you create an image in a specific format. - */ -public interface ImageFormatter { - - /** Set the properties of the image formatter. */ - public void setProperties(String prefix, Properties props); - - /** - * Create a new instance of the same type of formatter. If you are - * running in a multi-threaded environment, you'll need to provide - * a new instance of the formatter to each thread, since the image - * and graphics that are being drawn into for each thread are - * contained within. - * - * @return a new instance of this type of formatter, with the same - * properties set. - */ - public abstract ImageFormatter makeClone(); - - /** - * Convert a BufferedImage to a image file format... - * - * @param bi a BufferedImage.. - */ - public byte[] formatImage(BufferedImage bi); - - /** - * Take a MapBean, and get the image bytes that represent the - * current state. - * - * @param map the MapBean. - * @return byte[] representing an image of the map in it's current - * state. - */ - public byte[] getImageFromMapBean(com.bbn.openmap.MapBean map); - - /** - * Return the applicable Graphics to use to paint the layers into. - * If the internal BufferedImage hasn't been created yet, or has - * been set to null, then a new buffered Image is created, set to - * the size specified by the height and width given. The - * ImageGenerator extends MapBean. Remember to dispose of the - * graphics object when you are done with it. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @return java.awt.Graphics object to use. - */ - public java.awt.Graphics getGraphics(int width, int height); - - public java.awt.Graphics getGraphics(int width, int height, boolean alpha); - - /** - * Return the BufferedImage contained within the formatter. - * - * @return the BufferedImage. - */ - public BufferedImage getBufferedImage(); - - /** - * Return the BufferedImage contained within the formatter. - * - * @param bi the BufferedImage to use in this formatter. - */ - public void setBufferedImage(BufferedImage bi); - - /** - * Scale the internal BufferedImage to the pixel dimensions, and - * then return it. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return the scaled BufferedImage. - */ - public BufferedImage getScaledBufferedImage(int scaledWidth, - int scaledHeight); - - /** - * Return the image bytes of the formatted image. - * - * @return byte[] representing the image. - */ - public byte[] getImageBytes(); - - /** - * Scale the internal BufferedImage, then return the image bytes - * of the formatted image. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return byte[] representing the image. - */ - public abstract byte[] getScaledImageBytes(int scaledWidth, int scaledHeight); - - /** - * Get the Image Type created by the ImageFormatter. These - * responses should adhere to the OGC WMT standard format labels. - * Some are listed in the WMTConstants interface file. - */ - public String getFormatLabel(); - - /** - * Get the Mime Content Type created by the ImageFormatter. - */ - public String getContentType(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageHelper.java b/src/core/src/main/java/com/bbn/openmap/image/ImageHelper.java deleted file mode 100644 index 2876defe3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageHelper.java +++ /dev/null @@ -1,92 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageHelper.java,v $ -// $RCSfile: ImageHelper.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.ImageObserver; -import java.awt.image.PixelGrabber; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A class that holds static functions that do things we tend to do to - * images a lot. - */ -public class ImageHelper { - - public final static Logger logger = Logger.getLogger("com.bbn.openmap.image.ImageHelper"); - - /** - * Take a PixelGrabber and get the pixels out of it. - * - * @param pg PixelGrabber - * @return int[] of pixels, null if anything bad happens. - */ - public static int[] grabPixels(PixelGrabber pg) { - - // Get only the pixels you need. - // Use a pixel grabber to get the right pixels. - try { - pg.startGrabbing(); - - boolean grabbed = pg.grabPixels(); - - if (!grabbed) { - logger.fine("Error in loading image, no pixels grabbed"); - return null; - } - - int framebitCount = 0; - while (true) { - int status = pg.getStatus(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("pixelgrabber status = " + status); - } - - if ((status & ImageObserver.ALLBITS) != 0) { - break; - } - if ((status & ImageObserver.FRAMEBITS) != 0) { - // Give some cycles to be sure - some times it - // seems - // to not really be ready, - if (framebitCount < 20) { - framebitCount++; - } - break; - } - if ((status & ImageObserver.ERROR) != 0) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Error in loading image, ImageObserver error"); - } - return null; - } - Thread.sleep(100); - } - return (int[]) pg.getPixels(); - - } catch (InterruptedException ie) { - return null; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageIOFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/ImageIOFormatter.java deleted file mode 100644 index c784e56ee..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageIOFormatter.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// (C) Copyright 2004 NAVICON A/S. All Rights Reserved. -// http://www.navicon.dk -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ImageIOFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2007/01/25 22:11:40 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; - -import javax.imageio.ImageIO; - -import com.bbn.openmap.util.Debug; - -public abstract class ImageIOFormatter extends AbstractImageFormatter { - - protected String formatName; - - public ImageIOFormatter() {} - - public String getFormatName() { - return formatName; - } - - /** - * @param formatName The formatName to set. - */ - public void setFormatName(String formatName) { - this.formatName = formatName; - } - - public byte[] formatImage(BufferedImage bi) { - try { - ByteArrayOutputStream byo = new ByteArrayOutputStream(); - ImageIO.write(bi, getFormatName(), byo); - return byo.toByteArray(); - } catch (java.io.IOException ioe) { - Debug.error("ImageIOFormatter caught IOException formatting image!"); - return new byte[0]; - } - } - - /** - * Return the applicable Graphics to use to paint the layers into. - * If the internal BufferedImage hasn't been created yet, or has - * been set to null, then a new buffered Image is created, set to - * the size specified by the height and width. The ImageGenerator - * extends MapBean. Remember to dispose of the graphics object - * when you are done with it. Uses the BufferedImage.TYPE_INT_ARGB - * colormodel. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @return java.awt.Graphics object to use. - * @see java.awt.image.BufferedImage - */ - public java.awt.Graphics getGraphics(int width, int height) { - return getGraphics(width, height, BufferedImage.TYPE_INT_ARGB); - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageMaster.java b/src/core/src/main/java/com/bbn/openmap/image/ImageMaster.java deleted file mode 100644 index 1d8be887c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageMaster.java +++ /dev/null @@ -1,508 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageMaster.java,v $ -// $RCSfile: ImageMaster.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Color; -import java.awt.geom.Point2D; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Hashtable; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The ImageMaster is an organizer for running the ImageServer to create one or - * more images. It relies on a properties file, which sets up a series of - * entries for an ImageServer. Each entry has parameters for setting up a - * projection for an image, a parameters for a URL for the ImageServer to use to - * set up the layers for an image, and a parameter to set the name and path of - * the output image file. - *

- * Each map entry in the ImageServer has parameters for the projection and layer - * properties to use for the map image, and the size, location and format of the - * output image. - */ -public class ImageMaster { - - /** Property for space separated image servers to be created. */ - public static final String ImageServersProperty = "servers"; - /** - * Property for the properties file holding property for a particular image. - */ - public static final String ServerPropertiesProperty = "properties"; - /** Property for an image's projection type. */ - public static final String ImageProjectionProperty = "imageProjection"; - /** Property for an image's projection center latitude. */ - public static final String ImageLatitudeProperty = "imageLatitude"; - /** Property for an image's projection center longitude. */ - public static final String ImageLongitudeProperty = "imageLongitude"; - /** Property for an image's projection scale. */ - public static final String ImageScaleProperty = "imageScale"; - /** Property for an image's height. */ - public static final String ImageHeightProperty = "imageHeight"; - /** Property for an image's width. */ - public static final String ImageWidthProperty = "imageWidth"; - /** Property for the image's background color. */ - public static final String ImageBackgroundColorProperty = "imageBackgroundColor"; - /** Property for an image's output name. */ - public static final String ImageNameProperty = "outputName"; - /** Property for scaling the width of image after creation. */ - public static final String ScaleToWidthProperty = "scaleToWidth"; - /** Property for scaling the height of image after creation. */ - public static final String ScaleToHeightProperty = "scaleToHeight"; - /** Property for an output log file. */ - public static final String OutputLogFileProperty = "outputLogFile"; - /** Property for an error log file. */ - public static final String ErrorLogFileProperty = "errorLogFile"; - /** - * Hashtable of instantiated layers across servers, to reduce duplication of - * same layers. - */ - protected Hashtable instantiatedLayers = new Hashtable(); - - ImageMasterHelper[] helpers; - - /** Create with properties. */ - public ImageMaster(Properties props) { - setProperties(props); - } - - /** Create with properties file. */ - public ImageMaster(String propertiesFile) { - Properties props = new Properties(); - loadProperties(props, propertiesFile); - setProperties(props); - } - - /** Create with properties file URL. */ - public ImageMaster(URL propertiesURL) { - Properties props = new Properties(); - loadProperties(props, propertiesURL); - setProperties(props); - } - - /** - * Loads properties from a java resource. This will load the named resource - * identifier into the given properties instance. - * - * @param props the Properties instance to receive the properties - * @param resourceName the name of the resource to load - * @return true if all's well. - */ - protected boolean loadPropertiesFromResource(Properties props, String resourceName) { - - InputStream propsIn = getClass().getResourceAsStream(resourceName); - - if (propsIn == null) { - if (Debug.debugging("imagemaster")) { - Debug.error("Unable to locate resources: " + resourceName); - } - return false; - } else { - try { - props.load(propsIn); - return true; - } catch (java.io.IOException e) { - Debug.error("ImageMaster: Caught IOException loading resources: " + resourceName); - return false; - } - } - } - - /** - * Loads properties from a java resource. This will load the named resource - * identifier into the given properties instance. - * - * @param props the Properties instance to receive the properties - * @param url the url to load - * @return true if all's well. - */ - public boolean loadProperties(Properties props, URL url) { - try { - InputStream propsIn = url.openStream(); - props.load(propsIn); - return true; - } catch (java.io.IOException e) { - Debug.error("ImageMaster: Caught IOException loading resources: " + url); - return false; - } - } - - /** - * Load the named file from the named directory into the given - * Properties instance. If the file is not found a warning is - * issued. If an IOException occurs, a fatal error is printed and the - * application will exit. - * - * @param file the name of the file - * @return true if all's well. - */ - public boolean loadProperties(Properties props, String file) { - File propsFile = new File(file); - try { - InputStream propsStream = new FileInputStream(propsFile); - props.load(propsStream); - return true; - } catch (java.io.FileNotFoundException e) { - Debug.error("ImageMaster.loadProperties(): Unable to read configuration file \"" + propsFile + "\""); - } catch (java.io.IOException e) { - Debug.error("ImageMaster.loadProperties(): Caught IO Exception reading configuration file \"" + propsFile - + "\" \n" + e); - } - return false; - } - - /** - * Set the properties for the ImageMaster, which also gets all the - * ImageMasterHelpers created. - */ - public void setProperties(Properties properties) { - helpers = setImageServers(properties); - } - - /** Start the ImageMaster to go through the ImageMasterHelpers. */ - public void run() { - doNext(); - } - - /** - * This causes the ImageMaster to look through the list of - * ImageMasterHelpers and launch the next one that hasn't been completed. It - * will cause the program to exit if there is nothing more to do. - */ - protected void doNext() { - for (int i = 0; i < helpers.length; i++) { - if (!helpers[i].complete) { - helpers[i].create(); - return; - } - } - System.exit(0); - } - - /** - * Creates the ImageMasterHelper array from an ImageMaster properties - * object. After this method is called, call run() to start the servers on - * their creative ways. - * - * @param properties the ImageMaster properties. - * @return ImageMasterHelper array. - */ - public ImageMasterHelper[] setImageServers(Properties properties) { - - String serversValue = properties.getProperty(ImageServersProperty); - - if (Debug.debugging("imagemaster")) { - Debug.output("ImageMaster.setImageServers(): servers = \"" + serversValue + "\""); - } - - if (serversValue == null) { - Debug.error("ImageMaster.setImageServers(): No property \"" + ImageServersProperty - + "\" found in application properties."); - return new ImageMasterHelper[0]; - } - - // Divide up the names ... - StringTokenizer tokens = new StringTokenizer(serversValue, " "); - Vector serverNames = new Vector(); - while (tokens.hasMoreTokens()) { - serverNames.addElement(tokens.nextToken()); - } - - if (Debug.debugging("imagemaster")) { - Debug.output("ImageMaster.setImageServers(): " + serverNames); - } - - int nServerNames = serverNames.size(); - ImageMasterHelper[] masterHelpers = new ImageMasterHelper[nServerNames]; - - for (int i = 0; i < nServerNames; i++) { - String serverName = (String) serverNames.elementAt(i); - masterHelpers[i] = new ImageMasterHelper(serverName, properties, this); - - } - return masterHelpers; - } - - /** - * Start up and go. - */ - public static void main(String[] args) { - Debug.init(); - ImageMaster master = null; - for (int i = 0; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-file")) { - master = new ImageMaster(args[++i]); - } else if (args[i].equalsIgnoreCase("-url")) { - String url = null; - try { - url = args[++i]; - master = new ImageMaster(new URL(url)); - } catch (MalformedURLException mue) { - Debug.output("ImageMaster: Malformed URL: " + url); - master = null; - } - } else if (args[i].equalsIgnoreCase("-masterprops")) { - printMasterProps(); - } else if (args[i].equalsIgnoreCase("-serverprops")) { - printServerProps(); - } else if (args[i].equalsIgnoreCase("-h")) { - printHelp(); - } - } - - if (master != null) { - master.run(); - } else { - printHelp(); - } - } - - /** - * printHelp should print a usage statement which reflects the - * command line needs of the ImageServer. - */ - public static void printHelp() { - Debug.output(""); - Debug.output( - "usage: java com.bbn.openmap.image.ImageMaster [-file || -url ] [-masterprops || -serverprops"); - Debug.output(" -file requires a complete path to a ImageMaster properties file."); - Debug.output(" -url requires an URL to a ImageMaster properties file."); - Debug.output(" -masterprops prints out an example of a ImageMaster properties file."); - Debug.output(" -serverprops prints out an example of a ImageServer properties file."); - Debug.output(""); - - System.exit(1); - } - - /** - * Prints an example of the ImageMaster properties file. - */ - public static void printMasterProps() { - Debug.output(""); - Debug.output("#################################################"); - Debug.output("# Properties file for the ImageMaster"); - Debug.output("# List of unique server nicknames (your choice)."); - Debug.output("servers= "); - Debug.output(""); - Debug.output("# URL of server1 properties"); - Debug.output("# If this is not included, it is assumed that "); - Debug.output("# the ImageServer properties reside in the "); - Debug.output("# ImageMaster properties file."); - Debug.output("server1.properties=http://"); - Debug.output("# Projection type of server1 image."); - Debug.output("server1.imageProjection=mercator"); - Debug.output("# Center latitude of server1 image."); - Debug.output("server1.imageLatitude=40f"); - Debug.output("# Center longitude of server1 image."); - Debug.output("server1.imageLongitude=-72f"); - Debug.output("# Projection scale of server1 image."); - Debug.output("server1.imageScale=20000000"); - Debug.output("# Pixel height of server1 image."); - Debug.output("server1.imageHeight=640"); - Debug.output("# Pixel width of server1 image."); - Debug.output("server1.imageWidth=480"); - Debug.output("# ARGB representation of the map background color (default is a saucy blue)"); - Debug.output("server1.imageBackgroundColor=ffffffff"); - Debug.output("# Complete path to server1 image output."); - Debug.output("server1.outputName="); - Debug.output(""); - Debug.output("# Repeat for each server listed in the servers property"); - Debug.output("#################################################"); - Debug.output(""); - } - - /** - * Print the ImageServer properties file, referenced by the ImageMaster - * properties file. - */ - public static void printServerProps() { - Debug.output(""); - Debug.output("#################################################"); - Debug.output("# Properties for ImageServer"); - Debug.output("# List of unique layer nicknames to use for the image (your choice)."); - Debug.output("# server1 is the name specified in the ImageMaster properties."); - Debug.output("server1.imageServer.layers= "); - Debug.output("# Classname of object to determine image format."); - Debug.output("server1.imageServer.formatter="); - Debug.output(""); - Debug.output("layer1.class= projClass = projectionFactory.getProjClassForName(projType); - if (projClass == null) { - projClass = Mercator.class; - } - - proj = (Proj) projectionFactory.makeProjection(projClass, new Point2D.Float(latitude, longitude), scale, - width, height); - - // Set the background color of the map - Color background = PropUtils.parseColorFromProperties(props, propPrefix + ImageBackgroundColorProperty, - MapBean.DEFAULT_BACKGROUND_COLOR); - - iMaster = master; - - Properties uniqueProps; - // if there isn't a unique properties file designated for - // the imageserver layers, assume that the layer properties - // reside in the ImageMaster properties file. - - if (uniquePropsURL != null) { - uniqueProps = new Properties(); - try { - loadProperties(uniqueProps, new URL(uniquePropsURL)); - } catch (MalformedURLException mue) { - Debug.error("ImageMaster: Malformed URL for server properties: " + uniquePropsURL); - uniqueProps = null; - } - } else { - uniqueProps = props; - } - - if (uniqueProps != null && outputFileName != null) { - iServer = new ImageServer(propPrefix, uniqueProps, instantiatedLayers); - iServer.setBackground(background); - } - } - - /** - * Override this method if you want to change the available projections - * from the defaults. - * - * @return the ProjectionFactory with projections - */ - public ProjectionFactory getProjectionFactory() { - return ProjectionFactory.loadDefaultProjections(); - } - - /** - * Start the ImageServer on it's creative journey. - */ - public void create() { - receiveImageData(iServer.createImage(proj, scaleToWidth, scaleToHeight)); - } - - /** - * Receive the bytes from a image. ImageReceiver interface function. - * - * @param imageBytes the formatted image.. - */ - public void receiveImageData(byte[] imageBytes) { - writeDataFile(outputFileName, imageBytes); - complete = true; - iMaster.doNext(); - } - - /** - * Write the image to a file. - * - * @param fileName the file name to write the image into. - * @param imageData the image data to put in the file. - */ - public void writeDataFile(String fileName, byte[] imageData) { - try { - Debug.message("imagemaster", "ImageMasterHelper: Writing image file " + fileName); - - FileOutputStream binFile = new FileOutputStream(fileName); - binFile.write(imageData); - binFile.close(); - - } catch (IOException ioe) { - Debug.error("ImageMasterHelper: Error writing image file " + fileName); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageReceiver.java b/src/core/src/main/java/com/bbn/openmap/image/ImageReceiver.java deleted file mode 100644 index 92d080da0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageReceiver.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageReceiver.java,v $ -// $RCSfile: ImageReceiver.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -/** - * The interface describing the object that receives the formatted - * image from the ImageServer. - */ -public interface ImageReceiver { - - /** - * Receive the bytes from a image. - * - * @param imageBytes the formatted image. - */ - public void receiveImageData(byte[] imageBytes); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageScaler.java b/src/core/src/main/java/com/bbn/openmap/image/ImageScaler.java deleted file mode 100644 index 22cc100ec..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageScaler.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.bbn.openmap.image; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; - -/** - * This code comes from the book "Filthy Rich Clients" Chapter 4. - * It is optimized for fast scaling. - * - * @author Chet Hasse - */ -public class ImageScaler { - - /** - * Progressive bilinear scaling: for any downscale size, scale - * iteratively by halves using BILINEAR filtering until the proper - * size is reached. - * - * @param inputImage the starting image - * @param startSize a starting dimension of the image, either h or w - * @param endSize a finishing dimension of the image, same as startSize h or w - * @param imageType the image type for rendering, from BufferedImage. - */ - public static Image getOptimalScalingImage(Image inputImage, - int startSize, int endSize, int imageType) { - int currentSize = startSize; - Image currentImage = inputImage; - int delta = currentSize - endSize; - int nextPow2 = currentSize >> 1; - while (currentSize > 1) { - if (delta <= nextPow2) { - if (currentSize != endSize) { - BufferedImage tmpImage = new BufferedImage(endSize, - endSize, imageType); - Graphics g = tmpImage.getGraphics(); - ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), - tmpImage.getHeight(), null); - currentImage = tmpImage; - } - return currentImage; - } else { - BufferedImage tmpImage = new BufferedImage(currentSize >> 1, - currentSize >> 1, imageType); - Graphics g = tmpImage.getGraphics(); - ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.drawImage(currentImage, 0, 0, tmpImage.getWidth(), - tmpImage.getHeight(), null); - currentImage = tmpImage; - currentSize = currentImage.getWidth(null); - delta = currentSize - endSize; - nextPow2 = currentSize >> 1; - } - } - return currentImage; - } - - /** - * Progressive bilinear scaling: for any downscale size, scale - * iteratively by halves using BILINEAR filtering until the proper - * size is reached. Assumes the image type is BufferedImage.TYPE_INT_ARGB. - * - * @param inputImage the starting image - * @param startSize a starting dimension of the image, either h or w - * @param endSize a finishing dimension of the image, same as startSize h or w - */ - public static Image getOptimalScalingImage(Image inputImage, - int startSize, int endSize) { - return getOptimalScalingImage(inputImage, startSize, endSize, BufferedImage.TYPE_INT_ARGB); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageServer.java b/src/core/src/main/java/com/bbn/openmap/image/ImageServer.java deleted file mode 100644 index a087c32f4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageServer.java +++ /dev/null @@ -1,1248 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServer.java,v $ -// $RCSfile: ImageServer.java,v $ -// $Revision: 1.14 $ -// $Date: 2007/04/17 20:23:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.RenderingHints; -import java.awt.geom.Point2D; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The image server is the class you want to deal with when creating images. It - * takes a properties file and creates images based on those properties. It also - * has this queuing thing going so that requests can stack up while the image - * generator is working on requests, and it will notify the requestor when the - * image is ready. - *

- * - * The ImageServer generally has the layers on the map predefined at - * construction, although you can change the layers that it has. When setting - * the layer array, do not use the same layer in two different slots of the - * array - it may not give you the expected map, and may mess around with the - * timing issues that the ImageGenerator takes care of. If you want to reorder - * the layers, do so before adding your request to the ImageServer. - * Additionally, each request has the option of not using certain layers in the - * ImageServer layer array, by turning off the appropriate bits in the layer - * mask. Understand that the image for a request will be created based on the - * layer array contents and the request layer mask at the time the request - * processing is started, not when it is submitted. - *

- * Right now, the ImageServer is single threaded - processing requests one after - * another. The request setup was written to support multi-threaded processing, - * though, where each image could be generated in it's own thread. That code is - * not written - maybe someday. - *

- * - *

- *                   
- * # If the ImageServer is created and given a prefix (in this example,
- * # 'imageServer') the properties file should contain the properties:
- * imageServer.layers=<layer1 layer2 ...>
- * layer1.className=<classname>
- * layer1.prettyName=<pretty name of layer>
- * # Add other attributes as required by layer1...
- * layer2.className=<classname>
- * layer2.prettyName=<pretty name of layer>
- * # Add other attributes as required by layer2...
- * # First formatter listed is default.
- * imageServer.formatters=<formatter1 formatter2 ...>
- * formatter1.class=<classname of formatter 1>
- * # Add other formatter1 properties
- * formatter2.class=<classname of formatter 2>
- *
- * 
- *

- * NOTE: If you simply hand the ImageServer a standard openmap.properties file, - * it works with the addition of the first two attributes except WITHOUT the - * 'imageServer.' prefix. - * - * New for 4.5: If the layers property is not defined, then the openmap.layers - * property is used to define which layers are available for the ImageServer. - */ -public class ImageServer implements/* ImageReadyListener, ImageReceiver, */PropertyConsumer { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.image.ImageServer"); - - /** The Image formatter for the output image. */ - protected ImageFormatter formatter; - - /** - * Hashtable of ImageFormatters available to be used. - */ - protected Map imageFormatters; - - /** The array of layers on the map. First is on top. */ - protected Layer[] layers; - - /** Property for space separated layers. */ - public static final String ImageServerLayersProperty = "layers"; - - /** OpenMap prefix */ - public static final String OpenMapPrefix = "openmap."; - - /** - * Property for the image formatter list of available formats. This property - * should contain a space separated list of marker names. - */ - public static final String ImageFormattersProperty = "formatters"; - - /** Property to turn on anti-aliasing. */ - public static final String AntiAliasingProperty = "antialiasing"; - - /** - * Property to set the background color. - */ - public static final String BackgroundProperty = "background"; - - /** Flag to do graphics and text anti-aliasing on the map image. */ - protected boolean doAntiAliasing = false; - - /** - * A place to hold on to a property prefix in case one is used. Useful for - * ImageServer properties files where more than one image server is defined. - */ - protected String propertiesPrefix = null; - - /** - * The ProjectionFactory to be used for image projections. If null, the - * default projection set will be used. - */ - protected ProjectionFactory projectionFactory; - - private boolean transparent = true; - - /** - * Empty constructor that expects to be configured later. - */ - protected ImageServer() { - } - - /** - * To create the image server, you hand it a set of properties that let it - * create an array of layers, and also to set the properties for those - * layers. The properties file for the ImageServer looks strikingly similar - * to the openmap.properties file. So, all the layers get set up here... - */ - public ImageServer(Properties props) { - setProperties(props); - } - - /** - * Same as the other constructor, except that the properties can have a - * prefix in front of them. The format of the prefix has to match how the - * property is specified the the properties file, which may include the - * period - i.e server1.imageServer.layers, the server1. is the prefix that - * should get passed in. The ImageMaster does this. - */ - public ImageServer(String prefix, Properties props) { - this(prefix, props, null); - } - - /** - * Create an ImageServer that should be configured with a Properties file. - * The prefix given is to scope the ImageServer properties to this instance. - * The Hashtable is for reusing any layers that may already be instantiated. - */ - public ImageServer(String prefix, Properties props, Map instantiatedLayers) { - setProperties(prefix, props, instantiatedLayers); - } - - /** - * Create an ImageServer from an array of Layers and an ImageFormatter. It's - * assumed that the layers are already configured. - * - * @param layers the array of layers. - * @param formatter the ImageFormatter to use for the output image format. - */ - public ImageServer(Layer[] layers, ImageFormatter formatter) { - this.layers = layers; - this.formatter = formatter; - } - - /** - * Set whether anti-aliasing is used when creating the image. - */ - public void setDoAntiAliasing(boolean set) { - doAntiAliasing = set; - } - - /** - * Find out whether anti-aliasing is used when creating the image. - */ - public boolean getDoAntiAliasing() { - return doAntiAliasing; - } - - /** - * Set the layers used on the NEXT request that is processed. Will not - * affect any image currently being created. - * - * @param newLayers an array of com.bbn.openmap.Layer objects, already - * configured and ready to respond to a projectionChanged method - * call. - */ - public synchronized void setLayers(Layer[] newLayers) { - if (newLayers == null) { - layers = new Layer[0]; - } else { - layers = newLayers; - } - } - - /** - * Retrieve the current set of layers used for requests. - * - * @return Layer[] - */ - public synchronized Layer[] getLayers() { - return layers; - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj) { - return createImage(proj, -1, -1, 0xFFFFFFFF); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight) { - return createImage(proj, scaledWidth, scaledHeight, 0xFFFFFFFF); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layer marker names reflecting the layers that should be - * part of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, List showLayers) { - return createImage(proj, scaledWidth, scaledHeight, showLayers, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layersthat should be part of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImageFromLayers(Projection proj, int scaledWidth, int scaledHeight, List showLayers) { - return createImageFromLayers(proj, scaledWidth, scaledHeight, showLayers, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layer marker names reflecting the layers that should be - * part of this image. - * @param background the Paint to be used for the background of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, List showLayers, - Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer string array."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - java.awt.Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (showLayers != null) { - int size = showLayers.size(); - for (int j = size - 1; j >= 0; j--) { - for (int i = layers.length - 1; i >= 0; i--) { - String layerName = (String) showLayers.get(j); - Layer layer = layers[i]; - String prefix = layer.getPropertyPrefix(); - - if (layerName.equals(prefix)) { - layer.renderDataForProjection(proj, graphics); - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layer.getName()); - } - } - } - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available for image"); - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * Create an image from a set of layers. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param layers A set of layers to paint into the image. - * @param background the Paint to be used for the background of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImageFromLayers(Projection proj, int scaledWidth, int scaledHeight, List layers, - Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer list."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - java.awt.Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (layers != null && !layers.isEmpty()) { - for (int i = layers.size() - 1; i >= 0; i--) { - Layer layer = layers.get(i); - - if (layer != null) { - layer.renderDataForProjection(proj, graphics); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layer.getName()); - } - } - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available for image"); - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * This method returns a integer representing a mask created from the - * visibility settings of the layers. - */ - public int calculateVisibleLayerMask() { - int ret = 0; // Initialize all the layer bits to zero. - for (int i = layers.length - 1; i >= 0; i--) { - if (layers[i].isVisible()) { - ret |= (0x00000001 << i); - } - } - return ret; - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. Uses the default background - * set in the ImageServer. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param includedLayerMask a mask signifying which of the ImageServer - * layers to use in the image. It's assumed that the called knows - * which layers are desired. Bit 1 of the mask refers to - * layer[0], etc. A bit turned on means the layer will be - * included. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, int includedLayerMask) { - return createImage(proj, scaledWidth, scaledHeight, includedLayerMask, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param includedLayerMask a mask signifying which of the ImageServer - * layers to use in the image. It's assumed that the called knows - * which layers are desired. Bit 1 of the mask refers to - * layer[0], etc. A bit turned on means the layer will be - * included. - * @param background the background Paint to use for the image, behind the - * layers. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, int includedLayerMask, - Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer mask."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - - Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("considering " + layers.length + " for image..."); - } - - if (layers != null) { - for (int i = layers.length - 1; i >= 0; i--) { - if ((includedLayerMask & (0x00000001 << i)) != 0) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layers[i].getName()); - } - - layers[i].renderDataForProjection(proj, graphics); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("skipping layer graphics from : " + layers[i].getName()); - } - } - } - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available"); - } - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * Create a java.awt.Graphics to use for an image. The Graphics will affect - * the image contained within the ImageFormatter. - * - * @param formatter the ImageFormatter containing the image. - * @param width the pixel width of the image. - * @param height the pixel height of the image. - */ - protected Graphics createGraphics(ImageFormatter formatter, int width, int height) { - - java.awt.Graphics graphics = null; - - if (formatter == null) { - logger.warning("ImageServer.createGraphics: Formatter is null, returning null graphics."); - return null; - } - - graphics = formatter.getGraphics(width, height, getTransparent()); - - if (graphics == null) { - logger.warning("ImageServer.createGraphics: NOT able to create Graphics!"); - return null; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("graphics is cool"); - } - - if (doAntiAliasing && graphics instanceof java.awt.Graphics2D) { - java.awt.Graphics2D g2d = (java.awt.Graphics2D) graphics; - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - } - - return graphics; - } - - /** - * Format the image that is contained in the ImageFormatter, scaling to a - * particular size if the scaledWidth and scaledHeight are greater than 0. - */ - protected byte[] getFormattedImage(ImageFormatter formatter, int scaledWidth, int scaledHeight) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("ready to create formatted image."); - } - byte[] formattedImage = null; - - // Now, scale the image, if needed... - if (scaledWidth > 0 && scaledHeight > 0) { - - formattedImage = formatter.getScaledImageBytes(scaledWidth, scaledHeight); - - } else { - logger.fine("ImageServer: using full scale image (unscaled)."); - formattedImage = formatter.getImageBytes(); - } - return formattedImage; - } - - /** - * Set the layers and image type in the properties. - */ - public void setProperties(Properties props) { - setProperties((String) null, props); - } - - /** - * Set the layers and image type in the properties. The properties might - * have a prefix in the file. - */ - public void setProperties(String prefix, Properties props) { - setProperties(prefix, props, (Map) null); - } - - /** - * Set the layers and image type in the properties. The properties might - * have a prefix in the file. - */ - public void setProperties(String prefix, Properties props, Map instantiatedLayers) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - layers = getLayers(props, instantiatedLayers); - formatter = getFormatters(props); - doAntiAliasing = PropUtils.booleanFromProperties(props, prefix + AntiAliasingProperty, false); - - background = getBackground(props, prefix + BackgroundProperty); - } - - /** - * Determine the background color based on property settings. If the - * property key isn't found, the openmap.BackgroundColor property will be - * used. If that isn't found, then Color.white will be returned as default. - * - * @param props properties to check - * @param propertyKey first key to check for. - * @return Paint used for background, as stated in properties - */ - public Paint getBackground(Properties props, String propertyKey) { - String paintString = props.getProperty(propertyKey); - if (paintString == null) { - paintString = props.getProperty(Environment.BackgroundColor); - } - - Paint ret = null; - if (paintString != null) { - try { - ret = PropUtils.parseColor(paintString, transparent); - } catch (NumberFormatException nfe) { - // Color set to white below... - } - } - - if (ret == null) { - ret = Color.white; - } - - return ret; - } - - /** - * Part of the PropertyConsumer interface. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer buf = new StringBuffer(); - for (Layer layer : getLayers()) { - buf.append(layer.getPropertyPrefix()).append(" "); - layer.getProperties(props); - } - - props.put(prefix + ImageServerLayersProperty, buf.toString().trim()); - - buf = new StringBuffer(); - if (imageFormatters != null) { - int index = 1; - for (ImageFormatter formatter : imageFormatters.values()) { - - String className = formatter.getClass().getName(); - String prfx = className.substring(className.lastIndexOf('.') + 1) + index; - - if (formatter instanceof PropertyConsumer) { - PropertyConsumer pc = (PropertyConsumer) formatter; - String opp = pc.getPropertyPrefix(); - - if (opp != null) { - prfx = opp; - pc.getProperties(props); - } else { - pc.setPropertyPrefix(prfx); - pc.getProperties(props); - // Reset it to whatever it was before we grabbed - // properties. - pc.setPropertyPrefix(null); - } - } - - buf.append(prfx).append(" "); - props.put(prfx + ComponentFactory.DotClassNameProperty, formatter.getClass().getName()); - - index++; - } - } - - props.put(prefix + ImageFormattersProperty, buf.toString().trim()); - - props.put(prefix + AntiAliasingProperty, Boolean.toString(doAntiAliasing)); - - if (background instanceof Color) { - String colorString = Integer.toHexString(((Color) background).getRGB()); - props.put(Environment.BackgroundColor, colorString); - } - - return props; - } - - /** - * Part of the PropertyConsumer interface. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(ImageServerLayersProperty, "A list of marker names (space-separated) for layer definitions"); - list.put(ImageFormattersProperty, "A list of marker names (space-separated) for ImageFormatter definitions"); - list.put(AntiAliasingProperty, "Whether to use anti-aliasing for the image"); - return list; - } - - /** - * Part of the PropertyConsumer interface. Set the Properties prefix to use - * to scope the relevant properties passed into the setProperties method. - */ - public void setPropertyPrefix(String prefix) { - propertiesPrefix = prefix; - } - - /** - * Part of the PropertyConsumer interface. Get the Properties prefix used to - * scope the relevant properties passed into the setProperties method. - */ - public String getPropertyPrefix() { - return propertiesPrefix; - } - - /** - * Given a integer that represents, bitwise, the layers that you want out of - * the current list held by the ImageServer layer array, return an array of - * those layers. - * - * @param layerMask bit mask for desired layers, bit 0 is layer 0. - * @return layer[] - */ - protected synchronized Layer[] getMaskedLayers(int layerMask) { - if (layerMask == 0xFFFFFFFF || layers == null) { - // They all want to be there - if (logger.isLoggable(Level.FINE)) { - logger.fine((layers != null ? "ImageServer: image request adding all layers." - : "ImageServer.getMaskedLayers() null layers")); - } - return layers; - } else { - // Use the vector as a growable array, and add the layers - // to it that the mask says should be there. - Vector layerVector = new Vector(layers.length); - for (int i = 0; i < layers.length; i++) { - if ((layerMask & (0x00000001 << i)) != 0) { - layerVector.add(layers[i]); - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer: " + layers[i].getName()); - } - } - } - Layer[] imageLayers = new Layer[layerVector.size()]; - return (Layer[]) layerVector.toArray(imageLayers); - } - } - - /** - * Get the ImageFormatter currently used for the image creation. - * - * @return ImageFormatter. - */ - public synchronized ImageFormatter getFormatter() { - return formatter; - } - - /** - * Set the ImageFormatter to be used for ImageCreation. - */ - public synchronized void setFormatter(ImageFormatter f) { - formatter = f; - - if (imageFormatters == null) { - imageFormatters = new Hashtable(); - } - - if (!imageFormatters.containsKey(formatter.getFormatLabel())) { - imageFormatters.put(formatter.getFormatLabel(), formatter); - } - } - - /** - * Set the default formatter to the one with the given label. The label can - * be retrieved from the ImageFormatter. - * - * @param formatterLabel String for a particular formatter. - * @return true if label matches up with a known formatter, false if no - * formatter found. - */ - public synchronized boolean setFormatter(String formatterLabel) { - ImageFormatter tmpFormatter = (ImageFormatter) imageFormatters.get(formatterLabel.intern()); - - if (tmpFormatter != null) { - setFormatter(tmpFormatter); - return true; - } else { - return false; - } - } - - /** - * Get the Hashtable used to hold the ImageFormatters. The label for each - * one is the lookup for it in the Hashtable. - * - * @return Hashtable of ImageFormatters. - */ - public synchronized Map getFormatters() { - return imageFormatters; - } - - /** - * Set the ImageFormatter Hashtable to set up the possible choices for image - * formats. - * - * @param iFormatters Hashtable of ImageFormatters - * @param defaultFormatterKey the key label of the formatter to use for a - * default. - */ - public synchronized void setFormatters(Map iFormatters, String defaultFormatterKey) { - imageFormatters = iFormatters; - formatter = (ImageFormatter) imageFormatters.get(defaultFormatterKey.intern()); - } - - /** - * Create an ImageFormatter from the contents of a properties object. - * - * @param p Properties used to initialize the Properties. - * @return default formatter. - */ - protected synchronized ImageFormatter getFormatters(Properties p) { - String formattersString; - ImageFormatter iFormatter = null; - - String prefix = PropUtils.getScopedPropertyPrefix(this); - formattersString = p.getProperty(prefix + ImageFormattersProperty); - - // First, look at the formatters string to get a marker list - // of available formatters. - if (formattersString != null) { - List markerNames = PropUtils.parseSpacedMarkers(formattersString); - List formatters = ComponentFactory.create(markerNames, p); - - int size = formatters.size(); - - if (imageFormatters == null) { - imageFormatters = new Hashtable(size); - } - - for (int i = 0; i < size; i++) { - ImageFormatter formatter = (ImageFormatter) formatters.get(i); - imageFormatters.put(formatter.getFormatLabel(), formatter); - - if (i == 0) { - iFormatter = formatter; - } - } - - } else { - logger.fine("no formatters specified"); - } - - return iFormatter; - } - - /** - * Create an array of Layers from a properties object. - */ - protected Layer[] getLayers(Properties p) { - return getLayers(p, (Map) null); - } - - /** - * Create an array of Layers from a properties object. Reuse the layer from - * the hashtable if it's there under the same property name. The Hashtable - * is kept for an ImageServer that is used buy an ImageMaster or another - * object that is using different layers for it's image. It will reuse the - * layers it's already created if the marker names are the same. - * - * @param p properties - * @param instantiatedLayers a hashtable containing layers, with the prefix - * layer name used as the key. - */ - protected Layer[] getLayers(Properties p, Map instantiatedLayers) { - - String layersValue; - String prefix = PropUtils.getScopedPropertyPrefix(this); - layersValue = p.getProperty(prefix + ImageServerLayersProperty); - - if (layersValue == null) { - // get openmap.layers value - layersValue = p.getProperty(OpenMapPrefix + ImageServerLayersProperty); - - if (layersValue == null) { - logger.warning("No property \"" + ImageServerLayersProperty + "\" found in ImageServer properties."); - return new Layer[0]; - } - } - - List layerNames = PropUtils.parseSpacedMarkers(layersValue); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("OpenMap.getLayers(): " + layerNames); - } - - int nLayerNames = layerNames.size(); - List layers = new ArrayList(nLayerNames); - - for (String layerName : layerNames) { - - // Check to see if some other ImageServer has used this - // layer, and reuse it. - if (instantiatedLayers != null) { - Layer iLayer = instantiatedLayers.get(layerName); - if (iLayer != null) { - - // We might want to consider adding this: - // iLayer.setProperties(layerName, p); - - layers.add(iLayer); - if (logger.isLoggable(Level.FINE)) { - logger.fine("adding instantiated layer /" + layerName + "/"); - } - continue; - } - } - - // Brand new layer, so instantiate it. - String classProperty = layerName + ".class"; - String className = p.getProperty(classProperty); - if (className == null) { - logger.warning("Failed to locate property \"" + classProperty + "\""); - logger.warning("Skipping layer \"" + layerName + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, layerName, p); - if (obj instanceof Layer) { - Layer l = (Layer) obj; - - layers.add(l); - - if (instantiatedLayers != null) { - instantiatedLayers.put(layerName, l); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Saving /" + layerName + "/ to instantiated layers hashtable."); - } - } - } - } - - int nLayers = layers.size(); - if (nLayers == 0) { - return new Layer[0]; - } else { - Layer[] layerArray = new Layer[nLayers]; - layers.toArray(layerArray); - return layerArray; - } - } - - public ProjectionFactory getProjectionFactory() { - if (projectionFactory == null) { - projectionFactory = ProjectionFactory.loadDefaultProjections(); - } - return projectionFactory; - } - - public void setProjectionFactory(ProjectionFactory projFactory) { - projectionFactory = projFactory; - } - - /** - * Takes a byte array and writes it out to a file path. - * - * @param imageBytes the formatted bytes of the image. - * @param outputPath the path of the image file. - * @param checkFormatterForExtension if true, will check the current active - * formatter for extension that will be added to the path if it - * doesn't end with the image type. - * @return the final file path used, with any extensions added. - * @throws IOException - */ - public String writeImageFile(byte[] imageBytes, String outputPath, boolean checkFormatterForExtension) - throws IOException { - String appendix = ""; - - if (checkFormatterForExtension) { - ImageFormatter formatter = getFormatter(); - if (formatter == null) { - appendix = ".jpg"; - } else { - String fileType = formatter.getFormatLabel(); - if (fileType.equals(WMTConstants.IMAGEFORMAT_JPEG)) { - appendix = ".jpg"; - } else { - appendix = "." + fileType.toLowerCase(); - } - } - - // If the file output path already ends properly, don't bother - // changing - // it. - if (outputPath.endsWith(appendix)) { - appendix = ""; - } - } - - String finalOutputPath = outputPath + appendix; - - FileOutputStream fos = new FileOutputStream(finalOutputPath); - - fos.write(imageBytes); - fos.flush(); - fos.close(); - - return finalOutputPath; - } - - /** - * For convenience, to create an image file based on the contents of a - * properties file (like an openmap.properties file). - * - * @param prefix The prefix for the ImageServer properties (layers and - * formatters) to use in the properties file. If defined, then - * this method will look for 'prefix.layers' and - * prefix.formatters' properties. If null, then this method will - * look 'layers' and 'formatters' properties. - * - * @param props The properties to use for defining the layers and plugins to - * use on the map image. Standard openmap.properties formats for - * layer definitions. See the standard openmap.properties file - * for more details on how to define layers and plugins. - * - * @param proj The projection to use for the map. If null, then the - * Environment projection properties will be looked for in the - * Properties. - * - * @param outputPath The output path for the image file. The image file - * should not have an appendix defined. This method will check - * which formatter is being used, and will assign one based on - * the image format (leave off the ., too). - * - * @return the final path of the written image file, with the chosen - * appendix attached. - */ - public static String createImageFile(String prefix, Properties props, Projection proj, String outputPath) - - throws MalformedURLException, IOException { - - String appendix = ""; - - ImageServer is = new ImageServer(props); - - ImageFormatter formatter = is.getFormatter(); - if (formatter == null) { - is.setFormatter(new SunJPEGFormatter()); - appendix = ".jpg"; - } else { - String fileType = formatter.getFormatLabel(); - if (fileType.equals(WMTConstants.IMAGEFORMAT_JPEG)) { - appendix = ".jpg"; - } else { - appendix = "." + fileType.toLowerCase(); - } - } - - Color background = MapBean.DEFAULT_BACKGROUND_COLOR; - background = PropUtils.parseColorFromProperties(props, Environment.BackgroundColor, background); - - is.setBackground(background); - - // Initialize the map projection, scale, center with - // user prefs or defaults - if (proj == null) { - ProjectionFactory projFactory = is.getProjectionFactory(); - String projName = props.getProperty(Environment.Projection); - Class projClass = projFactory.getProjClassForName(projName); - - if (projClass == null) { - projClass = Mercator.class; - } - - Point2D center = null; - - if (GeoProj.class.isAssignableFrom(projClass)) { - center = new LatLonPoint.Float(PropUtils.floatFromProperties(props, Environment.Latitude, 0f), - PropUtils.floatFromProperties(props, Environment.Longitude, 0f)); - } else { - center = new Point2D.Float(PropUtils.floatFromProperties(props, Environment.Latitude, 0f), - PropUtils.floatFromProperties(props, Environment.Longitude, 0f)); - } - - proj = projFactory.makeProjection(projClass, center, - PropUtils.floatFromProperties(props, Environment.Scale, MapBean.DEFAULT_SCALE), - PropUtils.intFromProperties(props, Environment.Width, MapBean.DEFAULT_WIDTH), - PropUtils.intFromProperties(props, Environment.Height, MapBean.DEFAULT_HEIGHT)); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("creating image with projection " + proj); - } - - byte[] imageBytes = is.createImage(proj); - String finalOutputPath = outputPath + appendix; - FileOutputStream fos = new FileOutputStream(finalOutputPath); - - fos.write(imageBytes); - fos.flush(); - fos.close(); - - return finalOutputPath; - } - - /** - * Paint object used for map backgrounds. - */ - protected Paint background; - - /** - * Set the Paint to use for image backgrounds. - */ - public void setBackground(Paint bg) { - background = bg; - } - - /** - * Get the Paint to use for image backgrounds. - */ - public Paint getBackground() { - return background; - } - - /** - * Set the transparent flag. Even if this flag is true, the image still may - * not end up transparent if the {@link ImageFormatter} does not support - * transparency or the image is completely filled. - * - * @param transparent - */ - public void setTransparent(boolean transparent) { - this.transparent = transparent; - } - - /** - * Get the transparent flag. Even if this flag is true, the image still may - * not end up transparent if the {@link ImageFormatter} does not support - * transparency or the image is completely filled. - * - * @return true if set for transparency - */ - public boolean getTransparent() { - return transparent; - } - - /** - * The ImageServer class main function will create a map image from a - * modified openmap.properties file. - * - *

-	 * java com.bbn.openmap.image.ImageServer -properties (path to properties file) -file (path to output image)
-	 * 
- * - *

- * The path to the output image should not have an appendix on it, that will - * get assigned depending on what image format is used. - */ - public static void main(String[] argv) { - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("ImageServer"); - - ap.add("properties", "The properties file to use for the image.", 1); - ap.add("file", "The output image file, without appendix (default is 'image').", 1); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String imagefile = "image"; - String arg[]; - - arg = ap.getArgValues("file"); - if (arg != null) { - imagefile = arg[0]; - } - - Properties props = null; - arg = ap.getArgValues("properties"); - if (arg != null) { - String ps = arg[0]; - try { - - URL url = PropUtils.getResourceOrFileOrURL(null, ps); - InputStream inputStream = url.openStream(); - - props = new Properties(); - props.load(inputStream); - - Projection proj = null; - - String finalOutputPath = ImageServer.createImageFile(null, props, proj, imagefile); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Writing image file to: " + finalOutputPath); - } - - } catch (MalformedURLException murle) { - logger.warning("ImageServer can't find properties file: " + arg[0]); - } catch (IOException ioe) { - logger.warning("ImageServer can't write output image: IOException"); - } - } - - System.exit(0); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageServerConstants.java b/src/core/src/main/java/com/bbn/openmap/image/ImageServerConstants.java deleted file mode 100644 index 6c2e57a5a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageServerConstants.java +++ /dev/null @@ -1,90 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerConstants.java,v $ -// $RCSfile: ImageServerConstants.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -/** - * This file defines the OpenMap extensions to the WMTConstants for - * making a web request for a map. They include String attribute - * keywords that let you request a certain OpenMap projection. - */ -public interface ImageServerConstants extends WMTConstants { - - /** - * Specific OpenMap projection parameter (PROJTYPE). Should match - * string identifier for OpenMap projection type. - */ - public final static String PROJTYPE = "PROJTYPE"; - /** - * Specific OpenMap projection parameter (SCALE). Should reflect - * right side of the scale ratio (1:XXXXX). - */ - public final static String SCALE = "SCALE"; - /** - * Specific OpenMap projection parameter (LAT). Float value. - */ - public final static String LAT = "LAT"; - /** - * Specific OpenMap projection parameter (LON). Float value. - */ - public final static String LON = "LON"; - /** - * Which layer number should be included in Image (LayerMask). - * Integer value. Bit 0 is for layer 0 and so on. - */ - public final static String LAYERMASK = "LAYERMASK"; - /** - * Specify OpenMap layers that should be part of Image (LAYERS) an - * String[] value - */ - public static final String LAYERS = "LAYERS"; - /** - * Keyword (pan) for the map server pan request. - */ - public final static String PAN = "PAN"; - - /** - * Keyword (recenter) for the map server recenter request. - */ - public final static String RECENTER = "RECENTER"; - - /** - * Specific OpenMap projection parameter (AZIMUTH). Float value. - */ - public final static String AZIMUTH = "AZIMUTH"; - - /** - * Keyword (query) for the map server query request; - */ - public final static String QUERY = "QUERY"; - - /** - * Specific OpenMap projection parameter (X). Int value. - */ - public final static String X = "X"; - - /** - * Specific OpenMap projection parameter (Y). Int value. - */ - public final static String Y = "Y"; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/ImageServerUtils.java b/src/core/src/main/java/com/bbn/openmap/image/ImageServerUtils.java deleted file mode 100644 index 99f38f49b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/ImageServerUtils.java +++ /dev/null @@ -1,149 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerUtils.java,v $ -// $RCSfile: ImageServerUtils.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/02/16 16:22:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A class to contain convenience functions for parsing web image requests. - */ -public class ImageServerUtils implements ImageServerConstants { - - /** - * Create an OpenMap projection from the values stored in a Properties - * object. The properties inside should be parsed out from a map request, - * with the keywords being those defined in the ImageServerConstants - * interface. Assumes that the shared instance of the ProjectionFactory has - * been initialized with the expected Projections. - */ - public static Proj createOMProjection(Properties props, - Projection defaultProj) { - - float scale = PropUtils.floatFromProperties(props, - SCALE, - defaultProj.getScale()); - int height = PropUtils.intFromProperties(props, - HEIGHT, - defaultProj.getHeight()); - int width = PropUtils.intFromProperties(props, - WIDTH, - defaultProj.getWidth()); - Point2D llp = defaultProj.getCenter(); - float longitude = PropUtils.floatFromProperties(props, - LON, - (float) llp.getX()); - float latitude = PropUtils.floatFromProperties(props, - LAT, - (float) llp.getY()); - - Class projClass = null; - String projType = props.getProperty(PROJTYPE); - - ProjectionFactory projFactory = ProjectionFactory.loadDefaultProjections(); - if (projType != null) { - projClass = projFactory.getProjClassForName(projType); - } - - if (projClass == null) { - projClass = defaultProj.getClass(); - } - - if (Debug.debugging("imageserver")) { - Debug.output("ImageServerUtils.createOMProjection: projection " - + projClass.getName() + ", with HEIGHT = " + height - + ", WIDTH = " + width + ", lat = " + latitude + ", lon = " - + longitude + ", scale = " + scale); - } - - Proj proj = (Proj) projFactory.makeProjection(projClass, - new Point2D.Float(longitude, latitude), - scale, - width, - height); - - return (Proj) proj; - } - - /** - * Create a Color object from the properties TRANSPARENT and BGCOLOR - * properties. Default color returned is white. - * - * @param props the Properties containing background color information. - * @return Color object for background. - */ - public static Color getBackground(Properties props) { - return (Color) getBackground(props, Color.white); - } - - /** - * Create a Color object from the properties TRANSPARENT and BGCOLOR - * properties. Default color returned is white. - * - * @param props the Properties containing background color information. - * @param defPaint the default Paint to use in case the color isn't defined - * in the properties. - * @return Color object for background. - */ - public static Paint getBackground(Properties props, Paint defPaint) { - boolean transparent = PropUtils.booleanFromProperties(props, - TRANSPARENT, - false); - - Paint backgroundColor = PropUtils.parseColorFromProperties(props, - BGCOLOR, - defPaint); - - if (backgroundColor == null) { - backgroundColor = Color.white; - } - - if (transparent) { - if (backgroundColor instanceof Color) { - Color bgc = (Color) backgroundColor; - backgroundColor = new Color(bgc.getRed(), bgc.getGreen(), bgc.getBlue(), 0x00); - } else { - backgroundColor = OMColor.clear; - } - } - - if (Debug.debugging("imageserver")) { - Debug.output("ImageServerUtils.createOMProjection: projection color: " - + (backgroundColor instanceof Color ? Integer.toHexString(((Color) backgroundColor).getRGB()) - : backgroundColor.toString()) - + ", transparent(" - + transparent + ")"); - } - - return backgroundColor; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/JPEGHelper.java b/src/core/src/main/java/com/bbn/openmap/image/JPEGHelper.java deleted file mode 100644 index 962580c56..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/JPEGHelper.java +++ /dev/null @@ -1,188 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/JPEGHelper.java,v $ -// $RCSfile: JPEGHelper.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URL; -import java.util.Iterator; - -import javax.imageio.IIOImage; -import javax.imageio.ImageIO; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.stream.FileImageOutputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.imageio.stream.MemoryCacheImageOutputStream; - -import com.bbn.openmap.util.Debug; - -/** - * This class provides some utility methods for creating jpeg encoded images. It - * relies on the Sun JDK/SDK JPEG codec classes. - */ -public class JPEGHelper { - - /** - * This class has only static methods, so there is no need to construct - * anything. - */ - private JPEGHelper() { - } - - /** - * Return a byte array that contains the JPEG encoded image. - * - * @param image the image to encode - * @param quality the JPEG quality factor to use in encoding - * @exception IOException an error occurred in encoding the image - */ - public static byte[] encodeJPEG(BufferedImage image, float quality) - throws IOException { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ImageOutputStream iosout = new MemoryCacheImageOutputStream(out); - - if (Debug.debugging("jpeghelper")) { - Debug.output("Got output stream..." + out); - } - - Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); - ImageWriter writer = iter.next(); - ImageWriteParam iwp = writer.getDefaultWriteParam(); - iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - iwp.setCompressionQuality(quality); - - if (Debug.debugging("jpeghelper")) { - Debug.output("Got encode params..."); - } - - writer.setOutput(iosout); - if (Debug.debugging("jpeghelper")) { - Debug.output("Got jpeg encoder..."); - } - - IIOImage iioi = new IIOImage(image, null, null); - writer.write(null, iioi, iwp); - - writer.dispose(); - if (Debug.debugging("jpeghelper")) { - Debug.output("encoded?"); - } - - return out.toByteArray(); - } - - /** - * Return a byte array that contains the JPEG encoded image. - * - * @param w the width of the image - * @param h the height of the image - * @param pixels the array of pixels in RGB directcolor - * @param quality the JPEG quality factor to use in encoding - * @exception IOException an error occurred in encoding the image - */ - public static byte[] encodeJPEG(int w, int h, int[] pixels, float quality) - throws IOException { - BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); - bi.setRGB(0, 0, w, h, pixels, 0, w); - pixels = null; - return encodeJPEG(bi, quality); - } - - private static void encodeAndWriteJPEGFile(File file, BufferedImage image, float quality) - throws IOException { - Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); - ImageWriter writer = iter.next(); - ImageWriteParam iwp = writer.getDefaultWriteParam(); - iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - iwp.setCompressionQuality(quality); - FileImageOutputStream output = new FileImageOutputStream(file); - writer.setOutput(output); - IIOImage iioi = new IIOImage(image, null, null); - writer.write(null, iioi, iwp); - writer.dispose(); - } - - /** - * A test main that encodes an image url at various jpeg quality factors. - * - * @param args url [width height] - */ - public static void main(String args[]) - throws Exception { - if (args.length == 0) { - System.out.println("java jpeg url [width height]"); - System.exit(-1); - } - - Debug.init(); - - int uw = -1; - int uh = -1; - if (args.length > 1) { - uw = Integer.parseInt(args[1]); - uh = Integer.parseInt(args[2]); - } - - String urlsource = args[0]; - int lastslash = urlsource.lastIndexOf('/'); - if (lastslash == -1) { - lastslash = 0; - } else { - lastslash++; - } - int lastdot = urlsource.lastIndexOf('.'); - if (lastdot == -1) { - lastdot = 0; - } - String filebase = urlsource.substring(lastslash, lastdot); - - Debug.output("url=" + urlsource + " filebase=" + filebase); - - BufferedImage bi = BufferedImageHelper.getBufferedImage(new URL(urlsource), 0, 0, uw, uh); - if (bi == null) { - Debug.error("JPEGHelper: Image load failed"); - } else { - PrintStream html = new PrintStream(new FileOutputStream(new File(filebase + ".html"))); - - html.println("Source url = " + urlsource + "
"); - html.println(" width = " + uw + " height=" + uh + " pixels=" + uw * uh + "


"); - for (int i = 0; i < 20; i++) { - File f = new File(filebase + ((i < 10) ? "0" : "") + i + ".jpg"); - float quality = 0.0499f * i; - encodeAndWriteJPEGFile(f, bi, quality); - html.println("Image Quality Factor: " + quality + "
"); - html.println("Image Size (bytes) : " + f.length() + "
"); - html.println("
"); - } - - html.close(); - } - System.exit(-1); // awt stinks - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/MagicPlanetImageComponent.java b/src/core/src/main/java/com/bbn/openmap/image/MagicPlanetImageComponent.java deleted file mode 100644 index 4c7e1d139..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/MagicPlanetImageComponent.java +++ /dev/null @@ -1,1091 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MagicPlanetImageComponent.java,v $ -//$Revision: 1.7 $ -//$Date: 2006/09/15 14:10:43 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.Properties; - -import javax.swing.JOptionPane; -import javax.swing.Timer; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.proj.LLXY; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The MagicPlanetImageComponent is an OpenMap Component designed to create - * images for Global Imagination's MagicPlanet Globe. This component, when added - * to an OpenMap MapHandler, will find the LayerHandler so it can find out when - * the Layer given to the MapBean change, so it knows which ones to use when - * creating an image file. This component also connects to the MapBean as a - * PropertyChangeListener to find out when the ocean color has changed. The - * MagicPlanet software (Storyteller) has the option of displaying images stored - * in a particular directory, either displaying the latest (lexically) image or - * cycling through a set of images in the directory to create a movie on the - * globe. - *

- * - * The class has options that change the format of the images created, where the - * images are stored, how often they are created, and the scale of the images. - * The scale of the image dictates its pixel size, since the proportion of the - * projection has to be constant for it to work on the globe. The projection - * used for the images is always the OpenMap LLXY projection, that's what the - * MagicPlanet expects. - *

- * - * The properties for this component are: - * - *

- *               outputDirectory=path_to_directory_for_writing_images
- *               
- *               # Milliseconds between image creation, 60000 is the default, representing 1 minute
- *               updateInterval=60000
- *               
- *               # Milliseconds after the timer is created before the MagicPlanetImageComponent takes
- *               # its first image and starts updating according to the updateInterval.  Default is 0,
- *               # so the first image is taken as soon as the component finds the layers.
- *               initialDelay=180000
- *               
- *               # The scale of the image, it determines the size of the image.  This 
- *               # may be important for certain layers to show particular details.  
- *               # The default is 60000000F, which represents an image approximately 2kx1k
- *               scale=60000000F
- *               
- *               # Property to tell the component to create a new image and reset the timer if the 
- *               # layers on the MapBean change.  True by default.
- *               autoUpdate=true
- *               
- *               # Property to tell the component to remove old images, default is true
- *               cleanup=true
- *               
- *               # Property to set the wait time before deleting old images, represented 
- *               # in milliseconds. The default is 86400000, representing one day. 
- *               cleanupInterval=86400000
- *               
- *               # Properties for setting the pixel width and height of the images. These properties 
- *               # provide a more precise way to control the image size, and tell the component to 
- *               # scale the image created with the scale setting set above.  The closer you get 
- *               # the scale to provide you the image size you want, the higher quality image 
- *               # you will have.  The default values for these properties are -1, which tells
- *               # the component to not change the size of the image resulting from the scale setting.
- *               width=-1 
- *               height=-1
- *               
- *               # Property to set the name of the last image written in a file, so other programs 
- *               # can more easily figure out what it was.  The property should reflect the path 
- *               # to the file to be written, which will contain 'MagicPlanet.lastFile=YYYYMMDDhhmmss.ext',
- *               # where YYYYMMDDhhmmss are year, month, day, hour, minute and second the file was created, 
- *               # and ext is the extension for the image type.  This information, combined with the directory 
- *               # information stored above, will let you know where the file is.  If this property is not set, 
- *               # no text file will be written.
- *               lastImageFile=path_to_text_file 
- *               
- *               # Property that describes a system command that should be run each time an image is created.
- *               # The property should contain exactly what would be typed into a command line for a script 
- *               # to be run, in the same environment this component is being run in.  There are special arguments
- *               # that can be inserted into this property string that the component will use to replace the current
- *               # image file name:
- *               #
- *               # %FILEPATH% gets replaced with the complete path of the new image file.
- *               # %FILENAME% gets replaced with the file name if the image file.
- *               # %FILENAME_WITHOUT_EXTENSION% gets replaced with the file name without a '.' or anything after that.
- *               #
- *               # The default is no value being set for the script, which means nothing will happen.  Here is an example for
- *               # creating a .dds file from the current image, using nvidia's nvdxt script.
- *               postProcessingScript="c:/Program Files/NVIDIA Corporation/NVIDIA DDS Utilities/nvdxt.exe" -swap -dxt1c -file %FILEPATH% -output c:/%FILENAME_WITHOUT_EXTENSION%.dds
- * 
- * - * @author dietrick - */ -public class MagicPlanetImageComponent extends OMComponent implements - LayerListener, PropertyChangeListener, ActionListener { - - public final static String OutputDirectoryProperty = "outputDirectory"; - - public final static String UpdateIntervalProperty = "updateInterval"; - - public final static String InitialDelayProperty = "initialDelay"; - - public final static String ScaleProperty = "scale"; - - public final static String AutoUpdateProperty = "autoUpdate"; - - public final static String CleanupProperty = "cleanup"; - - public final static String CleanupIntervalProperty = "cleanupInterval"; - - public final static String HeightProperty = "height"; - - public final static String WidthProperty = "width"; - - public final static String LastImageFileProperty = "lastImageFile"; - - public final static String PostProcessingScriptProperty = "postProcessingScript"; - - public final static String LAST_IMAGE_FILE_KEY = "MagicPlanet.lastFile"; - - public final static String REPLACE_FILEPATH_MARKER = "%FILEPATH%"; - - public final static String REPLACE_FILENAME_MARKER = "%FILENAME%"; - - public final static String REPLACE_FILENAME_WOEXT_MARKER = "%FILENAME_WITHOUT_EXTENSION%"; - - protected boolean DEBUG = false; - protected boolean DEBUG_DETAIL = false; - - // Kept in case replacements are added to the application, so we - // remember who to disconnect from. - protected LayerHandler layerHandler; - - protected MapBean mapBean; - - /** - * Parent directory for images. - */ - protected String outputDirectoryString; - - protected int updateInterval = 60000; - - protected int initialDelay = 0; - - protected float scale = 60000000F; // Produces 2k x 1k image - - protected Projection proj; - - protected Paint background; - - protected Layer[] layers; - - protected boolean autoUpdate = true; - - protected ImageFormatter imageFormatter = new SunJPEGFormatter(); - - protected boolean cleanup = true; - - protected int cleanupInterval = 86400000; // one day - - protected int height = -1;// unscaled, go with scale - - protected int width = -1; // unscaled, go with scale - - protected String lastImageFile = null; - - protected String postProcessingScript = null; - - protected Timer timer; - - public MagicPlanetImageComponent() { - DEBUG = Debug.debugging("magicplanet"); - } - - /** - * MapHandlerChild method extended through the OMComponent hierarchy. This - * is the method called by the MapHandler with objects added to the - * MapHandler. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof LayerHandler) { - setLayerHandler((LayerHandler) someObj); - } - - if (someObj instanceof MapBean) { - setMapBean((MapBean) someObj); - } - } - - /** - * MapHandlerChild method extended through the OMComponent hierarchy. This - * is the method called by the MapHandler with objects removed from the - * MapHandler. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerHandler && someObj == getLayerHandler()) { - setLayerHandler(null); - } - - if (someObj instanceof MapBean && someObj == getMapBean()) { - setMapBean(null); - } - } - - /** - * Get the timer being used for automatic updates. May be null if a timer is - * not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, you can set - * the timer to do that. Set it to null to disable it. If the current timer - * is not null, the graphic loader is removed as an ActionListener. If the - * new one is not null, the graphic loader is added as an ActionListener. - */ - public void setTimer(Timer t) { - if (timer != null) { - timer.removeActionListener(this); - timer.stop(); - } - - timer = t; - if (timer != null) { - timer.addActionListener(this); - } - } - - /** - * Creates a timer with the current updateInterval and calls setTimer(). - */ - public void createTimer() { - Timer t = new Timer(updateInterval, null); - t.setInitialDelay(initialDelay); - setTimer(t); - } - - /** - * The delay between timer pulses, in milliseconds. - */ - public void setUpdateInterval(int delay) { - updateInterval = delay; - if (timer != null) { - timer.setDelay(updateInterval); - if (timer.isRunning()) { - timer.restart(); - } - } - } - - public int getUpdateInterval() { - return updateInterval; - } - - public int getInitialDelay() { - return initialDelay; - } - - public void setInitialDelay(int initialDelay) { - this.initialDelay = initialDelay; - } - - /* - * Called when the timer kicks off. - * - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - if (DEBUG) { - Debug.output("MPIC.actionPerformed(" - + e.getSource().getClass().getName() + ")"); - } - createImage(); - } - - /** - * @return the object currently known as the LayerHandler by this object. - */ - protected LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Set the LayerHandler, become a LayerListener object to it to know when - * the layers on the MapBean change. If there is already a LayerHandler - * known to this component, this component will remove itself as a listener - * to the previous LayerHandler. - * - * @param lh LayerHandler. - */ - protected void setLayerHandler(LayerHandler lh) { - if (layerHandler != null) { - layerHandler.removeLayerListener(this); - } - - layerHandler = lh; - - if (layerHandler != null) { - layerHandler.addLayerListener(this); - // calling setLayers() will kick off an image creation. - // Don't want that right now, just setting the layers for - // initialization purposes, we'll let events or timer - // create the image. - layers = layerHandler.getMapLayers(); - - Timer timer = getTimer(); - if (timer == null) { - createTimer(); - } - - } - } - - /** - * @return the object currently known as the MapBean by this object. - */ - protected MapBean getMapBean() { - return mapBean; - } - - /** - * Set the MapBean, become a PropertyChangeListener object to it to know - * when the background color on the MapBean changes. If there is already a - * MapBean known to this component, this component will remove itself as a - * listener to the previous MapBean. - * - * @param mb MapBean. - */ - protected void setMapBean(MapBean mb) { - if (mapBean != null) { - mapBean.removePropertyChangeListener(this); - } - - mapBean = mb; - - if (mapBean != null) { - mapBean.addPropertyChangeListener(this); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - setOutputDirectoryString(props.getProperty(prefix - + OutputDirectoryProperty)); - setAutoUpdate(PropUtils.booleanFromProperties(props, prefix - + AutoUpdateProperty, isAutoUpdate())); - - setHeight(PropUtils.intFromProperties(props, - prefix + HeightProperty, - getHeight())); - setWidth(PropUtils.intFromProperties(props, - prefix + WidthProperty, - getWidth())); - - setScale(PropUtils.floatFromProperties(props, - prefix + ScaleProperty, - scale)); - - setUpdateInterval(PropUtils.intFromProperties(props, prefix - + UpdateIntervalProperty, getUpdateInterval())); - - setInitialDelay(PropUtils.intFromProperties(props, prefix - + InitialDelayProperty, getInitialDelay())); - - setCleanup(PropUtils.booleanFromProperties(props, prefix - + CleanupProperty, isCleanup())); - setCleanupInterval(PropUtils.intFromProperties(props, prefix - + CleanupIntervalProperty, getCleanupInterval())); - - setLastImageFile(props.getProperty(prefix + LastImageFileProperty, - getLastImageFile())); - - setPostProcessingScript(props.getProperty(prefix - + PostProcessingScriptProperty, getPostProcessingScript())); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + OutputDirectoryProperty, - PropUtils.unnull(getOutputDirectoryString())); - props.put(prefix + AutoUpdateProperty, Boolean.toString(isAutoUpdate())); - props.put(prefix + HeightProperty, Integer.toString(getHeight())); - props.put(prefix + WidthProperty, Integer.toString(getWidth())); - props.put(prefix + ScaleProperty, Float.toString(getScale())); - props.put(prefix + UpdateIntervalProperty, - Integer.toString(getUpdateInterval())); - props.put(prefix + InitialDelayProperty, - Integer.toString(getInitialDelay())); - props.put(prefix + CleanupProperty, Boolean.toString(isCleanup())); - props.put(prefix + CleanupIntervalProperty, - Integer.toString(getCleanupInterval())); - props.put(prefix + LastImageFileProperty, - PropUtils.unnull(getLastImageFile())); - props.put(prefix + PostProcessingScriptProperty, - PropUtils.unnull(getPostProcessingScript())); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String interString; - - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - OutputDirectoryProperty, - I18n.TOOLTIP, - "Path to directory that holds created images."); - props.put(OutputDirectoryProperty, interString); - props.put(OutputDirectoryProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - interString = i18n.get(MagicPlanetImageComponent.class, - OutputDirectoryProperty, - "Directory Path"); - props.put(OutputDirectoryProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - AutoUpdateProperty, - I18n.TOOLTIP, - "Immediately create new images when the layers/background color changes."); - props.put(AutoUpdateProperty, interString); - props.put(AutoUpdateProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(MagicPlanetImageComponent.class, - AutoUpdateProperty, - "Auto-Update"); - props.put(AutoUpdateProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - HeightProperty, - I18n.TOOLTIP, - "Image pixel height (-1 defers to scale setting)."); - props.put(HeightProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - HeightProperty, - "Image Height"); - props.put(HeightProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - WidthProperty, - I18n.TOOLTIP, - "Image pixel width (-1 defers to scale setting)."); - props.put(WidthProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - WidthProperty, - "Image Width"); - props.put(WidthProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - ScaleProperty, - I18n.TOOLTIP, - "Scale to use for image projection (larger numbers make smaller maps)."); - props.put(ScaleProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - ScaleProperty, - "Projection Scale"); - props.put(ScaleProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - UpdateIntervalProperty, - I18n.TOOLTIP, - "Number of milliseconds until next image."); - props.put(UpdateIntervalProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - UpdateIntervalProperty, - "Update Interval"); - props.put(UpdateIntervalProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - InitialDelayProperty, - I18n.TOOLTIP, - "Number of milliseconds until the first image is created."); - props.put(InitialDelayProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - InitialDelayProperty, - "Initial Delay"); - props.put(InitialDelayProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - CleanupProperty, - I18n.TOOLTIP, - "Delete old images automatically."); - props.put(CleanupProperty, interString); - props.put(CleanupProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(MagicPlanetImageComponent.class, - CleanupProperty, - "Delete Old Images"); - props.put(CleanupProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - CleanupIntervalProperty, - I18n.TOOLTIP, - "Number of milliseconds to keep old images (86400000 is one day)."); - props.put(CleanupIntervalProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - CleanupIntervalProperty, - "Cleanup Interval"); - props.put(CleanupIntervalProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - LastImageFileProperty, - I18n.TOOLTIP, - "Path to file containing name of last image file created."); - props.put(LastImageFileProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - LastImageFileProperty, - "Last Image Name"); - props.put(LastImageFileProperty + LabelEditorProperty, interString); - // ------- - interString = i18n.get(MagicPlanetImageComponent.class, - PostProcessingScriptProperty, - I18n.TOOLTIP, - "Script to run on the image file after it's been created."); - props.put(PostProcessingScriptProperty, interString); - interString = i18n.get(MagicPlanetImageComponent.class, - PostProcessingScriptProperty, - "Post Processing Script"); - props.put(PostProcessingScriptProperty + LabelEditorProperty, - interString); - - props.put(initPropertiesProperty, OutputDirectoryProperty + " " - + ScaleProperty + " " + InitialDelayProperty + " " - + UpdateIntervalProperty + " " + AutoUpdateProperty + " " - + CleanupProperty + " " + CleanupIntervalProperty + " " - + HeightProperty + " " + WidthProperty + " " - + LastImageFileProperty + " " + PostProcessingScriptProperty); - - return props; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.LayerListener#setLayers(com.bbn.openmap.event.LayerEvent) - */ - public void setLayers(LayerEvent evt) { - if (evt.getType() == LayerEvent.REPLACE) { - setLayers(evt.getLayers()); - } - } - - /** - * Checks to see if there is a timer, and if the component wants to - * automatically update the current image. If the timer isn't running, it's - * started. - */ - public void handleUpdate() { - Timer timer = getTimer(); - - if (timer != null && (isAutoUpdate() || !timer.isRunning())) { - timer.restart(); - } - // Else do nothing, the timer is running and will pick up the - // changes. - } - - /** - * Create a new image. - */ - public void createImage() { - - if (isCleanup()) { - cleanup(false); - } - - String fileName = getFileNameForTime(System.currentTimeMillis()); - String filePath = getOutputDirectoryString() + "/" + fileName; - - if (DEBUG) { - Debug.output("MagicPlanetImageComponent: creating image: " - + filePath); - } - - Layer[] layers = getLayers(); - if (layers == null) { - return; - } - - ImageServer is = new ImageServer(layers, new SunJPEGFormatter()); - try { - is.setBackground(getBackground()); - } catch (NoSuchMethodError nsme) { - // Older version of OpenMap, going to just use what the - // MapBean has - } - byte[] imageBytes = is.createImage(getProj(), getWidth(), getHeight()); - - FileOutputStream fos; - try { - fos = new FileOutputStream(filePath); - fos.write(imageBytes); - fos.flush(); - fos.close(); - - if (DEBUG) { - Debug.output(" MP: done writing image"); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - mapBean.setProjection(mapBean.getProjection()); - - String launchCmd = generatePostProcessingCmd(postProcessingScript, - filePath); - - if (launchCmd != null) { - try { - - if (DEBUG) - Debug.output("MP post processing: " + launchCmd); - Runtime.getRuntime().exec(launchCmd); - } catch (IOException e) { - System.err.println("MP post processing: " + e); - } - } - - if (lastImageFile != null) { - try { - File lastImageFileFile = new File(lastImageFile); - fos = new FileOutputStream(lastImageFileFile); - fos.write(new String(LAST_IMAGE_FILE_KEY + "=" + fileName).getBytes()); - fos.flush(); - fos.close(); - - if (DEBUG) { - Debug.output(" MP: done writing file noting last image file name: " - + lastImageFile); - } - } catch (IOException ioe) { - Debug.error("MP: error writing file to note last image file name:\n" - + ioe.getMessage()); - ioe.printStackTrace(); - lastImageFile = null; - } - } - } - - protected String generatePostProcessingCmd(String script, String filePath) { - String ret = null; - - if (script != null && filePath != null) { - // nvdxt.exe -file Image.jpg -all -swap -dxt1c -output - // Image.dds - // nvdxt.exe -file %FILENAME% -all -swap -dxt1c -output - // %FILENAME_WITHOUT_EXTENSION%.dds - if (DEBUG) { - Debug.output(" Replacing script: |" + script + "|" + filePath); - } - ret = script.replaceAll(REPLACE_FILEPATH_MARKER, filePath); - ret = ret.replaceAll(REPLACE_FILENAME_MARKER, - filePath.substring(filePath.lastIndexOf('/') + 1)); - ret = ret.replaceAll(REPLACE_FILENAME_WOEXT_MARKER, - filePath.substring(filePath.lastIndexOf('/') + 1, - filePath.lastIndexOf('.'))); - - try { - if (Environment.get("os.name").startsWith("Windows")) { - ret = ret.replace('/', '\\'); - } - } catch (NullPointerException npe) { - // Applet, or Environment not set up. - } - - if (DEBUG) { - Debug.output(" returning script: " + ret); - } - } - - return ret; - } - - /** - * @param l unix time in milliseconds - * @return String representing file name for the given time. - */ - protected String getFileNameForTime(long l) { - Calendar cal = new GregorianCalendar(); - cal.setTimeInMillis(l); - - DecimalFormat twoDigits = new DecimalFormat("00"); - - String tMarker = Integer.toString(cal.get(Calendar.YEAR)) - + twoDigits.format(cal.get(Calendar.MONTH) + 1) - + twoDigits.format(cal.get(Calendar.DAY_OF_MONTH)) - + twoDigits.format(cal.get(Calendar.HOUR_OF_DAY)) - + twoDigits.format(cal.get(Calendar.MINUTE)) - + twoDigits.format(cal.get(Calendar.SECOND)); - - return tMarker + "." - + getImageFormatter().getFormatLabel().toLowerCase(); - } - - /** - * Decode the file name to see what time the file was created. - * - * @param fileName - * @return milliseconds from unix epoch. - * @throws NumberFormatException if the filename can't be decoded. - */ - protected long getTimeForFileName(String fileName) - throws NumberFormatException { - - int dotIndex = fileName.indexOf("."); - if (dotIndex == -1) { - // Not something we care about - throw new NumberFormatException(); - } - fileName = fileName.substring(0, dotIndex); - if (fileName.length() == 14) { - // Fits our naming convention. - int year = Integer.parseInt(fileName.substring(0, 4)); - int month = Integer.parseInt(fileName.substring(4, 6)); - int day = Integer.parseInt(fileName.substring(6, 8)); - int hour = Integer.parseInt(fileName.substring(8, 10)); - int minute = Integer.parseInt(fileName.substring(10, 12)); - int sec = Integer.parseInt(fileName.substring(12)); - - if (DEBUG) { - Debug.output(year + " " + month + " " + day + " " + hour + " " - + minute + " " + sec); - } - - return new GregorianCalendar(year, month - 1, day, hour, minute, sec).getTimeInMillis(); - } - - throw new NumberFormatException(); - - } - - /** - * Remove old files. Checks the current time against the timestamps decoded - * by the names of files found in the output directory, and deletes them if - * the difference between those times is greater than the cleanupInterval. - * - * @param deleteAll if true, all images will be deleted, regardless of when - * they were created. - */ - public void cleanup(boolean deleteAll) { - long currentTime = System.currentTimeMillis(); - File file = new File(getOutputDirectoryString()); - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - File f = files[i]; - if (!deleteAll) { - try { - long ft = getTimeForFileName(f.getName()); - long tdiff = currentTime - ft; - - if (DEBUG) { - Debug.output("MagicPlanetImageComponent considering deleting " - + f.getName() - + ", file time:" - + ft - + ", current time:" - + currentTime - + ", interval:" - + getCleanupInterval() - + ", diff:" + tdiff); - } - - if (tdiff > getCleanupInterval()) { - if (DEBUG) - Debug.output(" deleting..."); - f.delete(); - } - - } catch (NumberFormatException nfe) { - // skip it. - } - } else { - f.delete(); - } - } - } - } - - /* - * (non-Javadoc) - * - * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MapBean.BackgroundProperty) { - setBackground((Paint) evt.getNewValue()); - } - } - - /** - * Set the 'ocean' color of the planet. The MagicPlanetImageComponent - * listens for events from the MapBean and will call this method if the - * ocean color on the MapBean is changed. - * - * @param paint - */ - protected void setBackground(Paint paint) { - background = paint; - handleUpdate(); - } - - /** - * Return the 'ocean' color of the planet. - * - * @return Returns the background. - */ - public Paint getBackground() { - return background; - } - - public Layer[] getLayers() { - return layers; - } - - public void setLayers(Layer[] layers) { - this.layers = layers; - - handleUpdate(); - } - - public String getOutputDirectoryString() { - return outputDirectoryString; - } - - /** - * Set the directory where the images should be written to. - * - * @param outputDirectoryString - */ - public void setOutputDirectoryString(String outputDirectoryString) { - this.outputDirectoryString = outputDirectoryString; - - try { - File dir = new File(outputDirectoryString); - if (dir.exists() || dir.mkdirs()) { - return; - } - } catch (SecurityException se) { - } - - // Ran into a problem - JOptionPane.showMessageDialog(getMapBean(), - "I can't access this directory to store the Magic Planet images in:\n" - + outputDirectoryString - + "\n\nPlease check the permissions for that directory.", - "Problem Creating Directory", - JOptionPane.ERROR_MESSAGE); - } - - /** - * Get the image projection. - * - * @return current Projection of image. - */ - public Projection getProj() { - return proj; - } - - /** - * Set the image projection. - * - * @param proj - */ - public void setProj(Projection proj) { - this.proj = proj; - handleUpdate(); - } - - /** - * @return the scale value of the projection. - */ - public float getScale() { - return scale; - } - - /** - * Sets the scale for the projection, which directly affects the size of the - * image. Larger numbers make smaller images. Calling this method causes the - * setProj() method to be called with the new projection to use for images. - * - * @param scale - */ - public void setScale(float scale) { - this.scale = scale; - - LatLonPoint center = new LatLonPoint.Double(); - LLXY llxy = new LLXY(center, scale, 2000, 1000); - Point2D p1 = llxy.forward(90f, -180f); - Point2D p2 = llxy.forward(-90f, 180f); - - int w = (int) (p2.getX() - p1.getX()); - int h = (int) (p2.getY() - p1.getY()); - Projection proj = new LLXY(center, scale, w, h); - setProj(proj); - - if (DEBUG) { - Debug.output("Created projection " + proj + " from " + p1 + ", " - + p2); - } - } - - /** - * @return check if a new image should be created if the layers or - * background color changes. - */ - public boolean isAutoUpdate() { - return autoUpdate; - } - - /** - * Set whether a new image should be created immediately if the MapBean's - * layers change, or if the MapBean's background color changes. If false, a - * new image will be created on the next normal timer cycle. - * - * @param autoUpdate - */ - public void setAutoUpdate(boolean autoUpdate) { - this.autoUpdate = autoUpdate; - } - - public ImageFormatter getImageFormatter() { - return imageFormatter; - } - - /** - * Set the ImageFormatter to use for creating the image files. - * - * @param iFormatter - */ - public void setImageFormatter(ImageFormatter iFormatter) { - imageFormatter = iFormatter; - if (imageFormatter == null) { - imageFormatter = new SunJPEGFormatter(); - } - } - - public boolean isCleanup() { - return cleanup; - } - - /** - * Set whether the component should delete old images. - * - * @param cleanup - */ - public void setCleanup(boolean cleanup) { - this.cleanup = cleanup; - } - - public int getCleanupInterval() { - return cleanupInterval; - } - - /** - * Set the interval, in milliseconds, between the current time and the time - * old images were created before they are deleted. This setting only - * matters if isCleanup() returns true. - * - * @param cleanupInterval - */ - public void setCleanupInterval(int cleanupInterval) { - this.cleanupInterval = cleanupInterval; - } - - public int getHeight() { - return height; - } - - /** - * Set the scaled pixel height of the images.-1 maintains what the scale - * setting decides. - * - * @param height pixels. - */ - public void setHeight(int height) { - this.height = height; - } - - public int getWidth() { - return width; - } - - /** - * Set the scaled pixel width of the images. -1 maintains what the scale - * setting decides. - * - * @param width pixels. - */ - public void setWidth(int width) { - this.width = width; - } - - /** - * Get the location of a file that can be read to find out the name of the - * last image to be created. If null, that means no such file is being - * created. - * - * @return the file name. - */ - public String getLastImageFile() { - return lastImageFile; - } - - /** - * Set the location of a file that can be read to find out the name of the - * last image to be created. If null, that means no such file is being - * created. - * - * @param lastImageFile - */ - public void setLastImageFile(String lastImageFile) { - this.lastImageFile = checkTrimAndNull(lastImageFile); - } - - public String getPostProcessingScript() { - return postProcessingScript; - } - - public void setPostProcessingScript(String postProcessingScript) { - this.postProcessingScript = checkTrimAndNull(postProcessingScript); - } - - protected String checkTrimAndNull(String s) { - if (s != null) { - s = s.trim(); - if (s.length() == 0) { - s = null; - } - } - return s; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/MapBeanPrinter.java b/src/core/src/main/java/com/bbn/openmap/image/MapBeanPrinter.java deleted file mode 100644 index 3836a83ff..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/MapBeanPrinter.java +++ /dev/null @@ -1,125 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/MapBeanPrinter.java,v $ -// $RCSfile: MapBeanPrinter.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.print.PageFormat; -import java.awt.print.Printable; -import java.awt.print.PrinterException; -import java.awt.print.PrinterJob; - -import javax.swing.RepaintManager; - -import com.bbn.openmap.MapBean; - -/** - * - * A simple utility class to print a MapBean and rescale it to fit the - * printed page. - * - */ -public class MapBeanPrinter implements Printable { - private MapBean MapBeanToBePrinted; - private Dimension MapSize; - - public static void printMap(MapBean mapBean) { - new MapBeanPrinter(mapBean).print(); - } - - public MapBeanPrinter(MapBean mapBean) { - MapSize = mapBean.getSize(); - MapBeanToBePrinted = mapBean; - } - - public void print() { - PrinterJob printJob = PrinterJob.getPrinterJob(); - printJob.setPrintable(this); - if (printJob.printDialog()) - try { - printJob.print(); - } catch (PrinterException pe) { - System.out.println("Error printing: " + pe); - } - } - - public int print(Graphics g, PageFormat pageFormat, int pageIndex) { - if (pageIndex > 0) { - return (NO_SUCH_PAGE); - } else { - - // Compute size of component to print - double frameHeight = MapSize.height; - double frameWidth = MapSize.width; - - // Compute size of paper - double pageHeight = pageFormat.getImageableHeight(); - double pageWidth = pageFormat.getImageableWidth(); - - // Compute x and y scales - double xScale = pageWidth / frameWidth; - double yScale = pageHeight / frameHeight; - - // Retain smallest scale - double scale = xScale; - if (yScale < xScale) - scale = yScale; - - /* - * Scale and position the graphic Remark : I had to remove - * 1 from getImageable() values in order to remove an ugly - * border that appears on the left and top of the printed - * map. bug in the JDK? - */ - Graphics2D g2d = (Graphics2D) g; - g2d.translate(pageFormat.getImageableX() - 1.0, - pageFormat.getImageableY() - 1.0); - g2d.scale(scale, scale); - - // Do the work now ... - disableDoubleBuffering(MapBeanToBePrinted); - MapBeanToBePrinted.paint(g2d); - enableDoubleBuffering(MapBeanToBePrinted); - - return (PAGE_EXISTS); - } - } - - /** - * The speed and quality of printing suffers dramatically if any - * of the containers have double buffering turned on. So this - * turns if off globally. - */ - public static void disableDoubleBuffering(Component c) { - RepaintManager currentManager = RepaintManager.currentManager(c); - currentManager.setDoubleBufferingEnabled(false); - } - - /** Re-enables double buffering globally. */ - public static void enableDoubleBuffering(Component c) { - RepaintManager currentManager = RepaintManager.currentManager(c); - currentManager.setDoubleBufferingEnabled(true); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/MapRequestFormatException.java b/src/core/src/main/java/com/bbn/openmap/image/MapRequestFormatException.java deleted file mode 100644 index 993da5dab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/MapRequestFormatException.java +++ /dev/null @@ -1,50 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/MapRequestFormatException.java,v $ -// $RCSfile: MapRequestFormatException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -/** - */ -public class MapRequestFormatException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Constructs a MapRequestFormatException with - * null as its error message string. - */ - public MapRequestFormatException() { - super(); - } - - /** - * Constructs a MapRequestFormatException, saving - * a reference to the error message string s for later - * retrieval by the getMessage method. - * - * @param s the detail message. - */ - public MapRequestFormatException(String s) { - super(s); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/image/MapRequestHandler.java b/src/core/src/main/java/com/bbn/openmap/image/MapRequestHandler.java deleted file mode 100644 index cdca357f2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/MapRequestHandler.java +++ /dev/null @@ -1,534 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/MapRequestHandler.java,v $ -// $RCSfile: MapRequestHandler.java,v $ -// $Revision: 1.14 $ -// $Date: 2006/02/15 22:28:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Paint; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URLDecoder; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.PropertyStringFormatException; -import com.bbn.openmap.util.http.HttpConnection; -/** - * The MapRequestHandler is the front end for String requests to the - * ImageServer. It's goal is to be able to handle OpenGIS WMT mapserver - * requests, so the String request format is in the same format. We've included - * some OpenMap extensions to that format, so an OpenMap projection can be - * defined. - *

- * - * The MapRequestHandler should be able to handle map requests, resulting in a - * map image, and capabilities requests, so a client can find out what layers, - * projection types and image formats are available. - *

- * - * If the 'layers' property is not defined the openmap.properties file, then the - * 'openmap.layers' property will be used, and the 'openmap.startUpLayers' - * property will be used to define the default set of layers. This lets there be - * more layers available to the client than would be sent by default (if the - * client doesn't specify layers). - *

- * - * The MapRequestHandler assumes that the ProjectionFactory shared instance has - * ProjectionLoaders added to it to let it know how to handle different - * projection names. A call to ProjectionFactory.loadDefaultProjections() will - * take care of this requirement if you just want the standard projections - * loaded. - */ -public class MapRequestHandler extends ImageServer implements - ImageServerConstants { - - public final static String valueSeparator = ","; - public final static String hexSeparator = "%"; - - public final static String defaultLayersProperty = OpenMapPrefix - + "startUpLayers"; - - /** - * The real new property for doing this. The old property, - * defaultLayersProperty set to openmap.startUpLayers, will work if this is - * not set. At some point, we should all start using this one, it's just - * right. (defaultLayers) - */ - public final static String DefaultLayersProperty = "defaultLayers"; - /** - * The property for using visibility of the layers to mark the default - * layers. The order that they are used depends on how they are specified in - * the layers property. - */ - public final static String UseVisibilityProperty = "useLayerVisibility"; - - /** - * Comma-separated list of layer scoping prefixes that specify what layers, - * and their order, should be used for default images where layers are not - * specified in the request. - */ - protected String defaultLayers; - - /** - * The default projection that provides projection parameters that are - * missing from the request. - */ - protected Projection defaultProjection; - - /** - * The layers' visibility will be set to true at initialization if this - * property is set, and the layers' visibility will determine if a layer - * will be part of the image. If you set this flag, then you have to set the - * layers' visibility yourself. This property takes precedence over the - * default layers property if both are defined. - */ - protected boolean useVisibility = false; - - public MapRequestHandler(Properties props) throws IOException { - this(null, props); - } - - public MapRequestHandler(String prefix, Properties props) - throws IOException { - setProperties(prefix, props); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - defaultProjection = initProjection(props); - defaultLayers = props.getProperty(prefix + DefaultLayersProperty); - - if (defaultLayers == null) { - defaultLayers = props.getProperty(defaultLayersProperty); - } - - setUseVisibility(PropUtils.booleanFromProperties(props, prefix - + UseVisibilityProperty, getUseVisibility())); - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - // Still have to do projection, and default layers. - - props.put(UseVisibilityProperty, - "Flag to use layer visibility settings to determine default layers"); - - return props; - } - - /** - * Set whether the layer visibility is used in order to determine default - * layers for the image. - */ - public void setUseVisibility(boolean value) { - useVisibility = value; - } - - public boolean getUseVisibility() { - return useVisibility; - } - - /** - * Set up the default projection, which parts are used if any parts of a - * projection are missing on an image request. - * - * @param props the properties to look for openmap projection parameters. - * @return a projection created from the properties. A mercator projection - * is created if no properties pertaining to a projection are found. - */ - protected Projection initProjection(Properties props) { - loadProjections(props); - Projection proj = new ProjectionFactory().getDefaultProjectionFromEnvironment(); - - if (Debug.debugging("imageserver")) { - Debug.output("MRH starting with default projection = " + proj); - } - return proj; - } - - /** - * Method called from initProjection to initialize the ProjectionFactory. By - * default, the standard OpenMap projections are loaded into the - * ProjectionFactory. If you want those projections replaced or add more - * projections to the default set, override this method and do what you - * need. * - * - * @param props Properties that can be used to figure out what to do. This - * implementation of the method doesn't use the Properties. - */ - protected void loadProjections(Properties props) { - ProjectionFactory.loadDefaultProjections(); - } - - /** - * Set the default projection to grab parameters from in case some - * projection terms are missing from the request string. - */ - public void setDefaultProjection(Projection proj) { - defaultProjection = proj; - } - - /** - * Get the Projection being used for parameters in case some parameters are - * missing from request strings. - */ - public Projection getDefaultProjection() { - return defaultProjection; - } - - /** - * Set the default layers that will be used for requests that don't specify - * layers. The String should be a comma separated list of prefix scoping - * strings for the layer (layer.getPropertyPrefix()). - */ - public void setDefaultLayers(String dLayers) { - defaultLayers = dLayers; - } - - public String getDefaultLayers() { - return defaultLayers; - } - - /** - * Get a list of all the layer identifiers that can be used in a request, - * for the current configuration of the MapRequestHandler. - */ - public String getAllLayerNames() { - Layer[] layers = getLayers(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < layers.length; i++) { - sb.append((i > 0 ? " " : "")).append(layers[i].getPropertyPrefix()); - } - return sb.toString(); - } - - protected Properties convertRequestToProps(String request) - throws MapRequestFormatException { - try { - // Convert any %XX to the real ASCII value. - request = URLDecoder.decode(request, "UTF-8"); - - Properties requestProperties = PropUtils.parsePropertyList(request); - - if (Debug.debugging("imageserver")) { - Debug.output("MRH: parsed request " + requestProperties); - } - - return requestProperties; - } catch (PropertyStringFormatException psfe) { - throw new MapRequestFormatException(psfe.getMessage()); - } catch (Exception e) { - throw new MapRequestFormatException(e.getMessage()); - } - } - - /** - * Given a general request, parse it and handle it. This is the method that - * servlets should call. Currently only handles image requests. - * - * @param request the request string of key value pairs. - * @return a byte[] for the image. - */ - public byte[] handleRequest(String request) throws IOException, - MapRequestFormatException { - - Properties requestProperties = convertRequestToProps(request); - String requestType = requestProperties.getProperty(REQUEST); - - if (requestType != null) { - if (requestType.equalsIgnoreCase(MAP)) { - Debug.message("imageserver", "MRH: Map request..."); - return handleMapRequest(requestProperties); - // } else if - // (requestType.equalsIgnoreCase(CAPABILITIES)) { - // Debug.message("imageserver", "MRH: Capabilities - // request..."); - // handleCapabilitiesRequest(requestProperties, out); - } else { - throw new MapRequestFormatException("Request type not handled: " - + requestType); - } - } else { - throw new MapRequestFormatException("Request not understood: " - + request); - } - } - - /** - * Given a general request, parse it and handle it. Appends a content type - * to the output stream which may mess things up for servlets asking for - * images. - * - * @param request the request string of key value pairs. - * @param out OutputStream to reply on. - */ - public void handleRequest(String request, OutputStream out) - throws IOException, MapRequestFormatException { - - Properties requestProperties = convertRequestToProps(request); - - String requestType = requestProperties.getProperty(REQUEST); - if (requestType != null) { - if (requestType.equalsIgnoreCase(MAP)) { - Debug.message("imageserver", "MRH: Map request..."); - handleMapRequest(requestProperties, out); - } else if (requestType.equalsIgnoreCase(CAPABILITIES)) { - Debug.message("imageserver", "MRH: Capabilities request..."); - handleCapabilitiesRequest(requestProperties, out); - } else if (requestType.equalsIgnoreCase(PAN)) { - Debug.message("imageserver", "MRH: Pan request..."); - handlePanRequest(requestProperties, out); - } else if (requestType.equalsIgnoreCase(RECENTER)) { - Debug.message("imageserver", "MRH: Recenter request..."); - handleRecenterRequest(requestProperties, out); - - } else { - throw new MapRequestFormatException("Request type not handled: " - + requestType); - } - } else { - throw new MapRequestFormatException("Request not understood: " - + request); - } - - } - - /** - * Handle a map request, and create and image for it. - * - * @param requestProperties the request in properties format. - * @return byte[] of formatted image. - */ - public byte[] handleMapRequest(Properties requestProperties) - throws IOException, MapRequestFormatException { - - Proj projection = ImageServerUtils.createOMProjection(requestProperties, - defaultProjection); - - // Old way, bad, bad. Can't set the background for the whole image - // server for one request, it wacks the default. - - // setBackground(ImageServerUtils.getBackground(requestProperties, - // getBackground())); - - // New way, passed along to ImageServer methods. - Paint bgPaint = ImageServerUtils.getBackground(requestProperties, - getBackground()); - - boolean formatFound = false; - - String format = requestProperties.getProperty(FORMAT); - if (format != null) { - formatFound = setFormatter(format.toUpperCase()); - formatFound = true; - Debug.message("imageserver", "Format requested " + format); - } - - if (Debug.debugging("imageserver")) { - if (format == null || formatFound == false) { - Debug.output("MRH: no formatter defined, using default"); - } - - Debug.output("Creating image with projection: " + projection); - } - - byte[] image; - - // We need to think about using the layer mask, parsing it - // intelligently, and not using it if it's a little freaky. - - // String strLayerMask = - // requestProperties.getProperty(LAYERMASK); - // // default is to show all the layers server knows about. - // int layerMask = 0xFFFFFFFF; - // if (strLayerMask != null) { - // if (Debug.debugging("imageserver") { - // Debug.output("MRH.handleMapRequest: LayerMask unsigned int - // is " + - // strLayerMask); - // } - // layerMask = Integer.parseInt(strLayerMask); - // } - - String strLayers = requestProperties.getProperty(LAYERS); - - // Pass any properties to the layers??? Maybe if another - // property is set, to bother with taking up the time to run - // through all of this... - - if (strLayers != null) { - - List layers = PropUtils.parseMarkers(strLayers, ","); - if (Debug.debugging("imageserver")) { - Debug.output("MRH.handleMapRequest: requested layers >> " - + layers); - } - image = createImage(projection, -1, -1, layers, bgPaint); - } else { - // if LAYERS property is not specified - // Check default layers or if visibility should be used to - // determine default - - if (getUseVisibility()) { - if (Debug.debugging("imageserver")) { - Debug.output("MRH.handleMapRequest: Using visibility to determine layers"); - } - image = createImage(projection, - -1, - -1, - calculateVisibleLayerMask(), - bgPaint); - } else { - List layers = PropUtils.parseMarkers(defaultLayers, " "); - if (Debug.debugging("imageserver")) { - Debug.output("MRH.handleMapRequest: requested layers >> " - + layers + " out of " + getAllLayerNames()); - } - image = createImage(projection, -1, -1, layers, bgPaint); - } - } - return image; - } - - /** - * Handle a Map Request. Appends a content type to the output stream which - * may mess things up for servlets. - */ - public void handleMapRequest(Properties requestProperties, OutputStream out) - throws IOException, MapRequestFormatException { - - byte[] image = handleMapRequest(requestProperties); - - if (Debug.debugging("imageserver")) { - Debug.output("MRH: have completed image, size " + image.length); - } - - String contentType = getFormatterContentType(getFormatter()); - - if (contentType == null) { - contentType = HttpConnection.CONTENT_PLAIN; - } - - Debug.message("imageserver", "MRH: have type = " + contentType); - - HttpConnection.writeHttpResponse(out, contentType, image); - } - - /** - * Handle a Pan Request. - */ - public void handlePanRequest(Properties requestProperties, OutputStream out) - throws IOException, MapRequestFormatException { - - Proj projection = ImageServerUtils.createOMProjection(requestProperties, - defaultProjection); - - String contentType = HttpConnection.CONTENT_PLAIN; - String response; - float panAzmth; - - try { - panAzmth = Float.parseFloat(requestProperties.getProperty(AZIMUTH)); - projection.pan(panAzmth); - } catch (Exception exc) { - Debug.output("MSH: Invalid Azimuth"); - } - - response = Math.round(projection.getCenter().getY() * 100.0) / 100.0 - + ":" + Math.round(projection.getCenter().getX() * 100.0) - / 100.0; - - HttpConnection.writeHttpResponse(out, contentType, response); - } - - /** - * Handle a Recenter Request. Appends a content type to the output stream - * which may mess things up for servlets. - */ - public void handleRecenterRequest(Properties requestProperties, - OutputStream out) throws IOException, - MapRequestFormatException { - - Proj projection = ImageServerUtils.createOMProjection(requestProperties, - defaultProjection); - - String contentType = HttpConnection.CONTENT_PLAIN; - - String response; - - try { - int x = Integer.parseInt(requestProperties.getProperty(X)); - int y = Integer.parseInt(requestProperties.getProperty(Y)); - projection.setCenter(projection.inverse(x, y)); - } catch (Exception exc) { - Debug.output("MSH: Invalid Azimuth"); - } - - response = Math.round(projection.getCenter().getY() * 100.0) / 100.0 - + ":" + Math.round(projection.getCenter().getX() * 100.0) - / 100.0; - - HttpConnection.writeHttpResponse(out, contentType, response); - } - - /** - * Given an ImageFormatter, get the HttpConnection content type that matches - * it. - */ - public String getFormatterContentType(ImageFormatter formatter) { - String ret = null; - String label = formatter.getFormatLabel(); - - String[] knownContentTypes = HttpConnection.getAllContentTypes(); - - for (int i = 0; i < knownContentTypes.length; i++) { - if (knownContentTypes[i].indexOf(label.toLowerCase()) != -1) { - ret = knownContentTypes[i]; - break; - } - } - return ret; - } - - /** - * Handle a capabilities request. - */ - public void handleCapabilitiesRequest(Properties requestProperties, - OutputStream out) throws IOException, - MapRequestFormatException { - - if (Debug.debugging("imageserver")) { - Debug.output("MRH.handleCapabilitiesRequest: unimplemented"); - } - - throw new MapRequestFormatException("Capabilities request currently not handled"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/PNG32ImageFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/PNG32ImageFormatter.java deleted file mode 100644 index 17aed4e4e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/PNG32ImageFormatter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.bbn.openmap.image; - -import com.bbn.openmap.util.http.HttpConnection; - -public class PNG32ImageFormatter extends ImageIOFormatter { - - public PNG32ImageFormatter() { - setFormatName("png"); - } - - public ImageFormatter makeClone() { - return new PNG32ImageFormatter(); - } - - public String getContentType() { - return HttpConnection.CONTENT_PNG + "; mode=32bit"; - } - - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_PNG + "32"; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return true; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return true; - } - - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/PNG8ImageFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/PNG8ImageFormatter.java deleted file mode 100644 index 991274ec6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/PNG8ImageFormatter.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; - -import javax.imageio.ImageIO; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.http.HttpConnection; - -public class PNG8ImageFormatter extends ImageIOFormatter { - - public PNG8ImageFormatter() { - setFormatName("png"); - } - - public byte[] formatImage(BufferedImage bi) { - BufferedImage reducedImage = null; - if (bi.getColorModel().hasAlpha()) { - reducedImage = ColorReducer.reduce32(bi, 256); - } else { - reducedImage = ColorReducer.reduce24(bi, 256); - } - try { - ByteArrayOutputStream byo = new ByteArrayOutputStream(); - ImageIO.write(reducedImage, getFormatName(), byo); - return byo.toByteArray(); - } catch (java.io.IOException e) { - Debug.error("ImageIOFormatter caught IOException formatting image!"); - return new byte[0]; - } - } - - public java.awt.Graphics getGraphics(int width, int height) { - return getGraphics(width, height, BufferedImage.TYPE_INT_ARGB); - } - - public ImageFormatter makeClone() { - return new PNG8ImageFormatter(); - } - - public String getContentType() { - return HttpConnection.CONTENT_PNG + "; mode=8bit"; - } - - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_PNG + "8"; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return true; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return true; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/PNGImageIOFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/PNGImageIOFormatter.java deleted file mode 100644 index 4851770db..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/PNGImageIOFormatter.java +++ /dev/null @@ -1,54 +0,0 @@ -// ********************************************************************** -// (C) Copyright 2004 NAVICON A/S. All Rights Reserved. -// http://www.navicon.dk -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: PNGImageIOFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/02/20 01:41:08 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.image; - -import com.bbn.openmap.util.http.HttpConnection; - -public class PNGImageIOFormatter extends ImageIOFormatter { - - public PNGImageIOFormatter() { - setFormatName("png"); - } - - public ImageFormatter makeClone() { - return new PNGImageIOFormatter(); - } - - /** - * Get the Image Type created by the ImageFormatter. These - * responses should adhere to the OGC WMT standard format labels. - * Some are listed in the WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_PNG; - } - - public String getContentType() { - return HttpConnection.CONTENT_PNG; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return true; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return true; - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/image/PPMFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/PPMFormatter.java deleted file mode 100644 index ece81157e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/PPMFormatter.java +++ /dev/null @@ -1,169 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/PPMFormatter.java,v $ -// $RCSfile: PPMFormatter.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/02/20 01:41:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.http.HttpConnection; -/** - * A simple formatter to create PPM images. - *

- * I got a simple definition of a PPM image an wrote something to make - * that. XV complains about the P3 image, but still draws it. No - * complaints for the P6. - */ -public class PPMFormatter extends AbstractImageFormatter { - - public static final String RawBitsProperty = "rawbits"; - public static final String regularMagicNumber = "P3"; - public static final String rawbitsMagicNumber = "P6"; - public static final int HEADER_BUFFER_SIZE = 50; // approximate, - // no big deal - public static final int MAX_COLOR_VALUE = 255; // I guess - - protected boolean rawbits; - - public PPMFormatter() {} - - public void setProperties(String prefix, Properties props) { - rawbits = PropUtils.booleanFromProperties(props, (prefix == null ? "" - : prefix) - + RawBitsProperty, true); - } - - public ImageFormatter makeClone() { - PPMFormatter formatter = new PPMFormatter(); - formatter.rawbits = rawbits; - return formatter; - } - - public boolean getRawbits() { - return rawbits; - } - - public void setRawbits(boolean rb) { - rawbits = rb; - } - - public byte[] formatImage(BufferedImage bi) { - - int height = bi.getHeight(); - int width = bi.getWidth(); - - int[] data = new int[width * height]; - bi.getRGB(0, 0, width, height, data, 0, width); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - - try { - int pixel, count, i, lastCount; - if (!rawbits) { - dos.writeBytes(regularMagicNumber); - dos.writeBytes(" " + width); - dos.writeBytes(" " + height); - dos.writeBytes(" " + MAX_COLOR_VALUE + "\n"); - count = 0; // Keep lines less that 70 characters long - - // Keep track of the number of characters added per - // pass - lastCount = 0; - - Debug.output("PPMFormatter: Header is " + dos.size() + " bytes"); - Debug.output("PPMFormatter: Height = " + height); - Debug.output("PPMFormatter: Width = " + width); - Debug.output("PPMFormatter: data length = " + data.length); - - for (i = 0; i < data.length; i++) { - - pixel = data[i]; - int r = (pixel >>> 16) & 0x000000FF; - int g = (pixel >>> 8) & 0x000000FF; - int b = (pixel) & 0x000000FF; - - dos.writeBytes(" " + r); - dos.writeBytes(" " + g); - dos.writeBytes(" " + b); - if (count > 57) { - dos.writeBytes("\n"); - count = 0; - } else { - count += dos.size() - lastCount; - } - lastCount = dos.size(); - } - Debug.output("PPMFormatter: after data, size is " + dos.size()); - - } else { - dos.writeBytes(rawbitsMagicNumber); - dos.writeBytes(" " + width); - dos.writeBytes(" " + height); - dos.writeBytes(" " + MAX_COLOR_VALUE + "\n"); - for (i = 0; i < data.length; i++) { - pixel = data[i]; - dos.writeByte(pixel >>> 16); - dos.writeByte(pixel >>> 8); - dos.writeByte(pixel); - } - } - - return baos.toByteArray(); - - } catch (java.io.IOException ioe) { - System.err.println("PPMFormatter caught IOException formatting image!"); - return new byte[0]; - } - } - - /** - * Get the Image Type created by the ImageFormatter. These - * responses should adhere to the OGC WMT standard format labels. - * Some are listed in the WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_PPM; - } - - public String getContentType() { - return HttpConnection.CONTENT_PPM; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - // TODO: Is this correct? - return false; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - // TODO: Is this correct? - return false; - } - - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/SVGFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/SVGFormatter.java deleted file mode 100644 index b15bc845f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/SVGFormatter.java +++ /dev/null @@ -1,234 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * GTE - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright 1999-2000 by BBNT Solutions LLC, - * A part of GTE, all rights reserved. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/svg/com/bbn/openmap/image/SVGFormatter.java,v $ - * $Revision: 1.8 $ - * $Date: 2009/02/23 22:37:33 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.image; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.OutputStreamWriter; -import java.util.Properties; - -import org.apache.batik.dom.GenericDOMImplementation; -import org.apache.batik.svggen.SVGGraphics2D; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; - -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.util.Debug; - -/** - * The SVGFormatter lets you create SVG documents from the MapBean and - * it's layers. Tested with the Batik-1.1.1 package available at: - * http://xml.apache.org/batik/dist/batik-1.1.1.zip - *

- * Code initially provided by Sebastien Prud'homme, modified by - * dietrick. - *

- */ -public class SVGFormatter extends AbstractImageFormatter { - - SVGGraphics2D svgGenerator = null; - - public SVGFormatter() {} - - /** Set the properties of the image formatter. */ - public void setProperties(String prefix, Properties props) {} - - /** - * Create a new instance of the same type of formatter. If you are - * running in a multi-threaded environment, you'll need to provide - * a new instance of the formatter to each thread, since the image - * and graphics that are being drawn into for each thread are - * contained within. - * - * @return a new instance of this type of formatter, with the same - * properties set. - */ - public ImageFormatter makeClone() { - return new SVGFormatter(); - } - - /** - * Convert a BufferedImage to a image file format. Not the same as - * other ImageFormatters. Returns a SVG document which refers to - * the image. - * - * @param bi BufferedImage - * @return null. The SVGFormatter returns the SVG file containing - * information about the image. Probably not what you - * expected. - */ - public byte[] formatImage(BufferedImage bi) { - return null; - } - - /** - * Take a MapBean, and get the SVG document that represents what's - * on it. - * - * @param map the MapBean. - * @return byte[] representing an SVG of the map in it's current - * state. - */ - public byte[] getImageFromMapBean(com.bbn.openmap.MapBean map) { - - Proj proj = (Proj) map.getProjection(); - java.awt.Graphics graphics = getGraphics(proj.getWidth(), - proj.getHeight()); - - // This should actually be getting the layers, and rendering - // each one. It turns out that calling paintChildren() will - // render a buffered image if the MapBean is buffered, and - // that's not what we really want here. - // map.paintChildren(graphics); - - map.addPropertyChangeListener(this); - - // Layers should be set... - proj.drawBackground((Graphics2D) graphics, map.getBckgrnd()); - - if (layers != null) { - for (int i = layers.length - 1; i >= 0; i--) { - layers[i].renderDataForProjection(proj, graphics); - } - } else { - Debug.error("SVGFormatter can't get layers from map!"); - } - - map.removePropertyChangeListener(this); - layers = null; - - return getImageBytes(); - } - - /** - * Return the applicable Graphics to use to paint the layers into. - * If the internal BufferedImage hasn't been created yet, or has - * been set to null, then a new buffered Image is created, set to - * the size specified by the height and width given. The - * ImageGenerator extends MapBean. Remember to dispose of the - * graphics object when you are done with it. - * - * @param width pixel width of Graphics. - * @param height pixel height of Graphics. - * @return java.awt.Graphics object to use. - */ - public Graphics getGraphics(int width, int height) { - if (svgGenerator == null) { - DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); - Document document = domImpl.createDocument(null, "svg", null); - svgGenerator = new SVGGraphics2D(document); - svgGenerator.setClip(0, 0, width, height); - } - return svgGenerator; - } - - /** - * Return the BufferedImage contained within the formatter. - * - * @return null - there isn't a BufferedImage in this formatter. - */ - public BufferedImage getBufferedImage() { - return null; - } - - /** - * For ImageFormatters, returns the BufferedImage contained within - * the formatter. Doesn't do anything for the SVGFormatter. - * - * @param bi the BufferedImage to use in this formatter. - */ - public void setBufferedImage(BufferedImage bi) {} - - /** - * Scale the internal BufferedImage to the pixel dimensions, and - * then return it. Not implemented. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return null. - */ - public BufferedImage getScaledBufferedImage(int scaledWidth, - int scaledHeight) { - return null; - } - - /** - * Return the string bytes for the SVG document. - * - * @return byte[] representing the image. - */ - public byte[] getImageBytes() { - if (svgGenerator != null) { - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - OutputStreamWriter writer = new OutputStreamWriter(stream, SVGGraphics2D.DEFAULT_XML_ENCODING); - svgGenerator.stream(writer, false); - return stream.toByteArray(); - } catch (java.io.IOException ioe) { - Debug.error("SVGFormatter caught IOException formatting svg!"); - } - } - return new byte[0]; - } - - /** - * Scale the internal BufferedImage, then return the image bytes - * of the formatted image. Not implemented. Unscaled image - * returned. - * - * @param scaledWidth the desired pixel width of the image. - * @param scaledHeight the desired pixel height of the image. - * @return byte[] representing the image. - */ - public byte[] getScaledImageBytes(int scaledWidth, int scaledHeight) { - return getImageBytes(); - } - - /** - * Get the Image Type created by the SVGFormatter. These responses - * should adhere to the OGC WMT standard format labels. Some are - * listed in the WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_SVG; - } - - public String getContentType() { - return "image/svg+xml"; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return false; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/SVGRasterizer.java b/src/core/src/main/java/com/bbn/openmap/image/SVGRasterizer.java deleted file mode 100644 index fcf50df7c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/SVGRasterizer.java +++ /dev/null @@ -1,316 +0,0 @@ -package com.bbn.openmap.image; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.RenderingHints; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; - -import org.apache.batik.transcoder.TranscoderException; -import org.apache.batik.transcoder.TranscoderInput; -import org.apache.batik.transcoder.TranscoderOutput; -import org.apache.batik.transcoder.TranscodingHints; -import org.apache.batik.transcoder.image.ImageTranscoder; -import org.apache.batik.transcoder.image.JPEGTranscoder; -import org.w3c.dom.svg.SVGDocument; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; - -public class SVGRasterizer { - - /** - * The transcoder input. - */ - protected TranscoderInput input; - - /** - * The transcoder hints. - */ - protected TranscodingHints hints = new TranscodingHints(); - - /** - * The image that represents the SVG document. - */ - protected BufferedImage img; - - /** - * Constructs a new SVGRasterizer. - * - * @param uri the uri of the document to rasterize - */ - /* - * public SVGRasterizer(String uri) { this.input = new TranscoderInput(uri); - * } - */ - - /** - * Constructs a new SVGRasterizer. - * - * @param url the URL of the document to rasterize - */ - public SVGRasterizer(URL url) { - this.input = new TranscoderInput(url.toString()); - } - - public SVGRasterizer(String filename) { - File f = new File(filename); - try { - this.input = new TranscoderInput(f.toURI().toURL().toString()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Constructs a new SVGRasterizer converter. - * - * @param istream the input stream that represents the SVG document to - * rasterize - */ - public SVGRasterizer(InputStream istream) { - this.input = new TranscoderInput(istream); - } - - /** - * Constructs a new SVGRasterizer converter. - * - * @param reader the reader that represents the SVG document. - */ - public SVGRasterizer(Reader reader) { - this.input = new TranscoderInput(reader); - } - - public SVGRasterizer() { - // this.input = new TranscoderInput(reader); - } - - /** - * Constructs a new SVGRasterizer converter. - * - * @param document the SVG document - */ - public SVGRasterizer(SVGDocument document) { - this.input = new TranscoderInput(document); - } - - /** - * Returns the image that represents the SVG document. - */ - public BufferedImage createBufferedImage() - throws TranscoderException, IOException { - Rasterizer r = new Rasterizer(); - r.setTranscodingHints(hints); - r.transcode(input, null); - return img; - } - - public BufferedImage resizeBufferedImage(Dimension d) - throws TranscoderException, IOException { - if (input != null) { - this.setImageDimension(d); - Rasterizer r = new Rasterizer(); - r.setTranscodingHints(hints); - r.transcode(input, null); - r = null; // for garbage collection - } - return img; - - } - - public BufferedImage createBufferedImage(Dimension d) - throws TranscoderException, IOException { - if (d != null) { - this.setImageDimension(d); - } - Rasterizer r = new Rasterizer(); - r.setTranscodingHints(hints); - r.transcode(input, null); - r = null; - return img; - } - - public BufferedImage createJPG(File f) - throws TranscoderException, IOException { - Rasterizer r = new Rasterizer(); - JPEGTranscoder jpeg = new JPEGTranscoder(); - r.setTranscodingHints(hints); - - String parentName = f.getParent(); - File parent = new File(parentName); - parent.mkdirs(); - - FileWriter fw = new FileWriter(f); - TranscoderOutput output = new TranscoderOutput(fw); - r.transcode(input, output); - r.setTranscodingHints(hints); - jpeg.transcode(input, output); - return img; - } - - /** - * Sets the width of the image to rasterize. - * - * @param width the image width - */ - public void setImageWidth(float width) { - hints.put(ImageTranscoder.KEY_WIDTH, new Float(width)); - } - - /** - * Sets the height of the image to rasterize. - * - * @param height the image height - */ - public void setImageHeight(float height) { - hints.put(ImageTranscoder.KEY_HEIGHT, new Float(height)); - } - - public void setImageDimension(Dimension d) { - hints.put(ImageTranscoder.KEY_WIDTH, new Float(d.width)); - hints.put(ImageTranscoder.KEY_HEIGHT, new Float(d.height)); - } - - public void setArea(Rectangle2D area) { - hints.put(ImageTranscoder.KEY_AOI, area); - } - - /** - * Sets the preferred language to use. SVG documents can provide text in - * multiple languages, this method lets you control which language to use if - * possible. e.g. "en" for english or "fr" for french. - * - * @param language the preferred language to use - */ - public void setLanguages(String language) { - hints.put(ImageTranscoder.KEY_LANGUAGE, language); - } - - /** - * Sets the unit conversion factor to the specified value. This method lets - * you choose how units such as 'em' are converted. e.g. 0.26458 is 96dpi - * (the default) or 0.3528 is 72dpi. - * - * @param px2mm the pixel to millimeter convertion factor. - */ - public void setPixelToMMFactor(float px2mm) { - hints.put(ImageTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(px2mm)); - } - - /** - * Sets the uri of the user stylesheet. The user stylesheet can be used to - * override styles. - * - * @param uri the uri of the user stylesheet - */ - public void setUserStyleSheetURI(String uri) { - hints.put(ImageTranscoder.KEY_USER_STYLESHEET_URI, uri); - } - - /** - * Sets whether or not the XML parser used to parse SVG document should be - * validating or not, depending on the specified parameter. For futher - * details about how media work, see the Media types in the CSS2 - * specification . - * - * @param b true means the XML parser will validate its input - */ - public void setXMLParserValidating(boolean b) { - hints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, (b ? Boolean.TRUE : Boolean.FALSE)); - } - - /** - * Sets the media to rasterize. The medium should be separated by comma. - * e.g. "screen", "print" or "screen, print" - * - * @param media the media to use - */ - public void setMedia(String media) { - hints.put(ImageTranscoder.KEY_MEDIA, media); - } - - /** - * Sets the alternate stylesheet to use. For futher details, you can have a - * look at the Associating - * Style Sheets with XML documents . - * - * @param alternateStylesheet the alternate stylesheet to use if possible - */ - public void setAlternateStylesheet(String alternateStylesheet) { - hints.put(ImageTranscoder.KEY_ALTERNATE_STYLESHEET, alternateStylesheet); - } - - /** - * Sets the Paint to use for the background of the image. - * - * @param p the paint to use for the background - */ - public void setBackgroundColor(Paint p) { - hints.put(ImageTranscoder.KEY_BACKGROUND_COLOR, p); - } - - public static void main(String[] args) { - try { - String fileName = FileUtils.getFilePathToOpenFromUser("Locate SVG File"); - URL fileURL = PropUtils.getResourceOrFileOrURL(fileName); - - SVGRasterizer svgr = new SVGRasterizer(fileURL); - svgr.setBackgroundColor(OMColor.clear); - BufferedImage bi = svgr.createBufferedImage(); - - JFrame frame = new JFrame(); - frame.addWindowListener(new WindowAdapter() { - public void windowClosed(WindowEvent e) { - System.exit(0); - } - }); - frame.getContentPane().add(new JLabel(new ImageIcon(bi))); - frame.pack(); - frame.setVisible(true); - - } catch (TranscoderException e2) { - e2.printStackTrace(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - /** - * An image transcoder that stores the resulting image. - */ - protected class Rasterizer - extends ImageTranscoder { - - public BufferedImage createImage(int w, int h) { - - BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - ((Graphics2D) bi.getGraphics()).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - return bi; - } - - public void writeImage(BufferedImage img, TranscoderOutput output) - throws TranscoderException { - - SVGRasterizer.this.img = img; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/SimpleHttpImageServer.java b/src/core/src/main/java/com/bbn/openmap/image/SimpleHttpImageServer.java deleted file mode 100644 index f05f1814a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/SimpleHttpImageServer.java +++ /dev/null @@ -1,247 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/SimpleHttpImageServer.java,v $ -// $RCSfile: SimpleHttpImageServer.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.util.Properties; - -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.http.HttpConnection; -import com.bbn.openmap.util.http.HttpRequestEvent; -import com.bbn.openmap.util.http.HttpRequestListener; -import com.bbn.openmap.util.http.HttpServer; - -/** - * The SimpleHttpImageServer is an ImageServer extended into a simple - * Http server that creates images based on arguments within the - * request. The Request has been modeled after the OpenGIS WMT map - * request, although it has to be noted that this server is not yet a - * OGC WMT-compliant server. - *

- * - * To see the parameters available to run this class, launch the - * server with: - *

- * - *

- * 
- *  java com.bbn.openmap.image.SimpleHttpImageServer -help
- * 
- *  
- * 
- * - * The server takes two main arguments, a properties file, and a port - * number to run on. The properties file is a standard ImageServer - * openmap.properties file, and its format is described in the - * ImageServer documentation. - *

- * - * The request format can be seen by pointing a browser at the port - * and host that the server is running on. It basically follows the - * format: - *

- * - *

- * 
- *  http://host:port/openmap?REQUEST=map&PROJTYPE=projtype&SCALE=XXXXXXXX&(etc)
- *  
- * 
- * - *

- * This SimpleHttpImageServer is expecting a properties file - * containing the "layers" and "formatters" properties, both without a - * prefix. i.e: - * - *

- * 
- * 
- *  layers=markername1 markername2 markername3
- *  formatters=formatter1 formatter2
- *  markername1.class
- *  # other markername1 properties follow...
- * 
- *  formatter1.class
- *  # other formatter1 properties follow...
- * 
- *  
- * 
- * - *

- * - * If the 'layers' property is not defined the openmap.properties - * file, then the 'openmap.layers' property will be used, and the - * 'openmap.startUpLayers' property will be used to define the default - * set of layers. This lets there be more layers available to the - * client than would be sent by default (if the client doesn't specify - * layers). - * - * @see ImageServer - */ -public class SimpleHttpImageServer implements HttpRequestListener { - - protected HttpServer httpd; - protected MapRequestHandler iServer; - public final static String ErrorMessage = "OpenMap SimpleHttpImageServer: Image request not understood. Please send request in this format:\n\nhttp://server_address/openmap?REQUEST=MAP&SCALE=XXXXXXX&LAT=y&LON=x&...\n\nArguments:\nLAT=latitude\nLON=longitude\nSCALE=1:scale\nPROJTYPE=projection ID\nHEIGHT=pixel height\nWIDTH=pixel width\n\nArguments may be in any order after the '?'"; - - public final static char queryChar = '?'; - - public SimpleHttpImageServer(Properties props) throws IOException { - this(HttpServer.DEFAULT_PORT, false, props); - } - - public SimpleHttpImageServer(int port, boolean asDeamon, Properties props) - throws IOException { - httpd = new HttpServer(port, asDeamon); - httpd.addHttpRequestListener(this); - - iServer = new MapRequestHandler(props); - } - - public void start() { - httpd.start(); - } - - /** - * Get the MapRequestHandler that is handling map image requests. - */ - public MapRequestHandler getMapRequestHandler() { - return iServer; - } - - /** - * If you want to configure the MapRequestHandler and set it in - * the SHIS, you can use this method. This will cause the SHIS to - * assume that the MapRequestHandler is ready to go. - */ - public void setMapRequestHandler(MapRequestHandler mrh) { - iServer = mrh; - } - - /** - * Invoked when an http request is received. - */ - public void httpRequest(HttpRequestEvent e) throws java.io.IOException { - - String request = e.getRequest(); - - if (Debug.debugging("shis")) { - Debug.output("SHIS: Handling request - \"" + request + "\""); - } - - if (request.charAt(0) == '/') { - request = request.substring(0, request.length()); - } - - int index = 0; - index = request.indexOf('?'); - if (index != -1) { // GET Request - request = request.substring(index + 1, request.length()); - Debug.message("shis", "SHIS: GET Request received"); - } else { - Debug.message("shis", "SHIS: Probably a POST Request received"); - } - - try { - iServer.handleRequest(request, e.getOutputStream()); - } catch (IOException ioe) { - Debug.error("SHIS: caught IOException - \n" + ioe.getMessage()); - } catch (MapRequestFormatException exception) { - String message = "OpenMap SimpleHttpImageServer encountered an problem with your request:\n\n" - + exception.getMessage() + "\n\n" + ErrorMessage; - HttpConnection.writeHttpResponse(e.getOutputStream(), - HttpConnection.CONTENT_PLAIN, - message); - } - } - - public static void main(String[] args) { - Debug.init(); - - try { - - ArgParser ap = new ArgParser("SimpleHttpImageServer"); - ap.add("properties", - "A URL to use to set the properties for the ImageServer.", - 1); - ap.add("port", - "The port to listen for new map image requests on. (Default 0)", - 1); - ap.add("verbose", "Print action messages."); - ap.add("test", "Create a test default image."); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String proparg[]; - PropertyHandler propHandler; - proparg = ap.getArgValues("properties"); - if (proparg != null) { - propHandler = new PropertyHandler(proparg[0]); - } else { - propHandler = new PropertyHandler(); - } - - String[] varg = ap.getArgValues("verbose"); - if (varg != null) { - Debug.put("shis"); - Debug.put("imageserver"); - } - - SimpleHttpImageServer shis; - String[] portarg = ap.getArgValues("port"); - if (portarg != null) { - int port = Integer.parseInt(portarg[0]); - shis = new SimpleHttpImageServer(port, false, propHandler.getProperties()); - } else { - shis = new SimpleHttpImageServer(propHandler.getProperties()); - } - - shis.start(); - - Debug.output("OpenMap SimpleHttpImageServer: listening on port: " - + shis.httpd.getPort() - + (proparg == null ? "" : " with properties in " - + proparg[0])); - - String[] testarg = ap.getArgValues("test"); - if (testarg != null) { - OutputStream out = new FileOutputStream("test.jpg"); - shis.httpRequest(new HttpRequestEvent(shis, "/openmap?REQUEST=map", out)); - } - - } catch (MalformedURLException murle) { - System.err.println("Bad URL path to properties file."); - murle.printStackTrace(); - } catch (IOException ioe) { - System.err.println("Unable to start http server:"); - ioe.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/SunJPEGFormatter.java b/src/core/src/main/java/com/bbn/openmap/image/SunJPEGFormatter.java deleted file mode 100644 index 7b9d8d963..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/SunJPEGFormatter.java +++ /dev/null @@ -1,98 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/SunJPEGFormatter.java,v -// $ -// $RCSfile: SunJPEGFormatter.java,v $ -// $Revision: 1.6 $ -// $Date: 2008/02/20 01:41:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.image.BufferedImage; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.http.HttpConnection; -public class SunJPEGFormatter extends AbstractImageFormatter { - - public static final String QualityProperty = "imagequality"; - - protected float imageQuality = .8f; - - public SunJPEGFormatter() {} - - public void setProperties(String prefix, Properties props) { - imageQuality = PropUtils.floatFromProperties(props, - (prefix == null ? "" : prefix) + QualityProperty, - imageQuality); - if (Debug.debugging("image")) { - Debug.output("SunJPEGFormatter setting image quality to: " - + imageQuality); - } - } - - public ImageFormatter makeClone() { - SunJPEGFormatter formatter = new SunJPEGFormatter(); - formatter.setImageQuality(getImageQuality()); - return formatter; - } - - public float getImageQuality() { - return imageQuality; - } - - /** For this formatter, image quality is a number in the 0-1 range. */ - public void setImageQuality(float quality) { - imageQuality = quality; - } - - public byte[] formatImage(BufferedImage bi) { - try { - return JPEGHelper.encodeJPEG(bi, imageQuality); - } catch (java.io.IOException ioe) { - Debug.error("SunJPEGFormatter caught IOException formatting image!"); - return new byte[0]; - } - } - - /** - * Get the Image Type created by the ImageFormatter. These - * responses should adhere to the OGC WMT standard format labels. - * Some are listed in the WMTConstants interface file. - */ - public String getFormatLabel() { - return WMTConstants.IMAGEFORMAT_JPEG; - } - - public String getContentType() { - return HttpConnection.CONTENT_JPEG; - } - - @Override - protected boolean imageFormatSupportAlphaChannel() { - return false; - } - - @Override - protected boolean imageFormatSupportTransparentPixel() { - return false; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/WMTConstants.java b/src/core/src/main/java/com/bbn/openmap/image/WMTConstants.java deleted file mode 100644 index 40db71b0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/WMTConstants.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/WMTConstants.java,v $ -// $RCSfile: WMTConstants.java,v $ -// $Revision: 1.4 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -/** - * This file contains all the String constants that are defined in the - * OpenGIS WMT specification. We are trying to get to a point where we - * use all of them. - */ -public interface WMTConstants { - /** - * After WMS version 1.0, use this parameter to identify the - * version - */ - public final static String VERSION = "VERSION"; - /** - * After WMS version 1.0, use this parameter to identify the service - */ - public final static String SERVICE = "SERVICE"; - /** - * After WMS version 1.0, use this parameter to identify the feature info - * request - */ - public final static String GETMAP = "GetMap"; - /** - * After WMS version 1.0, use this parameter to identify the capabilities - * request - */ - public final static String GETCAPABILITIES = "GetCapabilities"; - /** - * After WMS version 1.0, use this parameter to identify the feature info - * request - */ - public final static String GETFEATUREINFO = "GetFeatureInfo"; - - /** - * Use this request parameter to to get a image with legend - */ - public final static String GETLEGENDGRAPHIC = "GetLegendGraphic"; - - /** - * WMT Version (WMTVER), floating point industry. Required for WMT - * requests. - */ - public final static String WMTVER = "WMTVER"; - /** Request (REQUEST) type. Required for WMT requests. */ - public final static String REQUEST = "REQUEST"; - - /** - * Layer list (LAYERS), comma separated layer names. Required for - * WMS GetMap and GetFeatureInfo request. - */ - public final static String LAYERS = "LAYERS"; - - /** - * Layer name (LAYER)Required for WMS GetLegendGraphic request. - */ - public final static String LAYER = "LAYER"; - - /** - * Query Layer list (QUERY_LAYERS), comma separated layer names. Required for - * WMS GetFeatureInfo requests. - */ - public final static String QUERY_LAYERS = "QUERY_LAYERS"; - - /** - * (STYLES) Comma separated list for one rendering style per - * requested layer. Required for WMT requests. - */ - public final static String STYLES = "STYLES"; - - /** - * Style name (STYLE) parameter name. Used by WMS GetLegendGraphic - */ - public final static String STYLE = "STYLE"; - - /** - * Spatial Reference System identifier (SRS). Required for WMT - * requests. - */ - public final static String SRS = "SRS"; - /** - * Coordinate Reference System identifier (CRS). Required for WMS - * GetMap requests. - */ - public final static String CRS = "CRS"; - /** - * Bounding Box (BBOX) consisting of xmin, ymin, xmax, ymax list, - * in SRS units. Required for WMT requests. - */ - public final static String BBOX = "BBOX"; - /** - * Pixel height of requested image (HEIGHT). Required for WMT - * requests. - */ - public final static String HEIGHT = "HEIGHT"; - /** - * Pixel width of requested image (WIDTH). Required for WMT - * requests. - */ - public final static String WIDTH = "WIDTH"; - /** - * Output format for image (FORMAT). Required for WMT requests. - */ - public final static String FORMAT = "FORMAT"; - - /** - * Output format for GetFeatureInfo request (INFO_FORMAT). Required for WMS - * GetFeatureInfo requests. - */ - public final static String INFO_FORMAT = "INFO_FORMAT"; - - /** - * (TRANSPARENT) true if the background color should be rendered - * as transparent, if the image format supports transparency, or - * false otherwise. Optional for WMT requests. - */ - public final static String TRANSPARENT = "TRANSPARENT"; - /** - * (BGCOLOR) The hexidecimal RGB value to use for the background - * color, if transparency is not desired or not supported by the - * format type. Default is BGCOLOR=0xFFFFFF. Optional for WMT - * requests. - */ - public final static String BGCOLOR = "BGCOLOR"; - /** - * (EXCEPTIONS) The format where exceptions are to be reported - * from the map server. Default is EXCEPTIONS=INIMAGE. Optional - * for WMT requests. - */ - public final static String EXCEPTIONS = "EXCEPTIONS"; - - /** - * Keyword (map) for a Map request. - */ - public final static String MAP = "map"; - - /** - * Keyword (capabilities) for a map server capabilities request. - */ - public final static String CAPABILITIES = "capabilities"; - - public final static String IMAGEFORMAT_JPEG = "JPEG"; - public final static String IMAGEFORMAT_GIF = "GIF"; - public final static String IMAGEFORMAT_PNG = "PNG"; - public final static String IMAGEFORMAT_TIFF = "TIFF"; - public final static String IMAGEFORMAT_GEOTIFF = "GeoTIFF"; - public final static String IMAGEFORMAT_PPM = "PPM"; - public final static String IMAGEFORMAT_WBMP = "WBMP"; - public final static String IMAGEFORMAT_SVG = "SVG"; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/XBMFile.java b/src/core/src/main/java/com/bbn/openmap/image/XBMFile.java deleted file mode 100644 index f48eda054..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/XBMFile.java +++ /dev/null @@ -1,243 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/XBMFile.java,v $ -// $RCSfile: XBMFile.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/05/25 04:56:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -/** - * XBMFile is a class which reads in a bitmap file, and provides the - * parameters of the file. If called from the command line, it draws - * the bitmap to the command line using spaces and asterisks. It just - * needs a valid path to a bitmap file, either a .xbm or .bm format, - * or a File object for a bitmap file. - */ -public class XBMFile { - public File f; - public short width; - public short height; - public byte[] bits; - public int paddedWidth; - - // Internal - String fileStuffString; // string version of the file - int pict_size; - - public XBMFile(String filename) { - f = new File(filename); - if (f.exists()) { - readin(); - } else - System.out.println("XBMFile: framename not valid."); - } - - public XBMFile(File fileObj) { - f = fileObj; - if (f.exists()) { - readin(); - } else - System.out.println("XBMFile: file not valid."); - } - - /** - * This method leaves all to the caller, by creating a bitmap from - * scratch. Any modification to the bits must take into account - * the paddedWidth of the bitmap. The paddedWidth is only a factor - * of the width is is not an even multiple of eight. So, if you - * want to change the bits settings, you'll have to do the - * counting yourself, and remember it's little endian, and done by - * the byte. - * - * @param h Height of bitmap. - * @param w Width of bitmap. - * @param b byte string representing the pixels. - * - */ - public XBMFile(short w, short h, byte[] b) { - width = w; - height = h; - paddedWidth = (int) Math.ceil((float) width / 8.0) * 8; - int dim = paddedWidth * height; - if (b.length != dim) { - System.out.println("XBMFile: byte[] doesn't fit into dimensions"); - if (b.length > dim) - bits = b; - else { - bits = new byte[paddedWidth * height]; - for (int i = 0; i < b.length; i++) - bits[i] = b[i]; - } - } else - bits = b; - } - - /** - * readin() parses the file and sets the object variables. It - * assumes that the file f is valid/exists. - */ - private void readin() { - try { - byte[] fileStuff = new byte[(int) f.length()]; - FileInputStream in = new FileInputStream(f); - in.read(fileStuff); - fileStuffString = new String(fileStuff); - int startWidth = fileStuffString.indexOf("width") + 6; - int endWidth = fileStuffString.indexOf(System.getProperty("line.separator"), startWidth); - int startHeight = fileStuffString.indexOf("height") + 7; - int endHeight = fileStuffString.indexOf(System.getProperty("line.separator"), startHeight); - int startBits = fileStuffString.indexOf("0x"); - int endBits = fileStuffString.indexOf("};"); - - width = Short.parseShort(fileStuffString.substring(startWidth, - endWidth)); - height = Short.parseShort(fileStuffString.substring(startHeight, - endHeight)); - - paddedWidth = (int) Math.ceil((float) width / 8.0) * 8; - int num_bytes = paddedWidth * height; - pict_size = (int) height * (int) Math.ceil((float) width / 8.0); - bits = new byte[num_bytes]; - setBits(fileStuffString.substring(startBits, endBits)); - in.close(); - } catch (IOException e3) { - System.out.println("XBMFile: Error reading file."); - } - } - - /** - * Setting the bits based on a string of 0x00 numbers. Assumes - * that the length of the tmpString is sufficient as dictated by - * the height and width settings. - */ - public void setBits(String tmpString) { - // ASCII version of things - // System.out.println(tmpString); - int num_bytes = paddedWidth * height; - int i = 0; - int j = 0; - while (j < num_bytes) { - i = (tmpString.indexOf("0x", i)); - int first = Character.digit(tmpString.charAt(i + 2), 16) * 0x10; - int second = Character.digit(tmpString.charAt(i + 3), 16); - - bits[j] = new Integer(first + second).byteValue(); - j++; - i += 4; - } - } - - /** - * Methods that handle the printout for stand alone use. - */ - private int widthCheck(int widthTrak) { - if (widthTrak > paddedWidth - 2) { - System.out.println(); - widthTrak = 0; - } else - widthTrak++; - return widthTrak; - } - - /** - * Prints the bitmap to stdout, using * and spaces - * - */ - public void printout() { - - // System.out.println("Width = " + width + " | Height = " + - // height - // + " | Bit length = " + bits.length); - int widthTrak = -1; - for (int i = 0; i < pict_size; i++) { - int val = new Byte(bits[i]).intValue(); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x01) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x02) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x04) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x08) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x10) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x20) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x40) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - - widthTrak = widthCheck(widthTrak); - if ((val & 0x80) != 0) - System.out.print((char) '*'); - else - System.out.print((char) ' '); - } - System.out.println(); - } - - /** - * The main function just prints the bitmap to stdout. - * - * parameters: args is the path to the file - */ - public static void main(String args[]) { - - if (args.length < 1) { - System.out.println("XBMFile: Need a path/filename"); - System.exit(0); - } - - System.out.println("XBMFile: " + args[0]); - XBMFile xbm = new XBMFile(args[0]); - xbm.printout(); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/image/package.html b/src/core/src/main/java/com/bbn/openmap/image/package.html deleted file mode 100644 index f2f79a1d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/package.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -This package has classes that provide image creation and manipulation -capabilities. The Helper classes are for managing java images and -their pixels. The other classes can be used to work with the MapBean -to create image files. -

-To create image files, you'll want to focus on the ImageServer, -ImageReceiver and ImageGenerator classes. -

-The ImageGenerator has the smarts to control the layers in a -MapBean, managing the multithreaded nature of them, to get them to -draw their graphics into an image for a given projection. It accepts -an array of layers, a projection, and a ImageReadyListener to notify -when the java.awt.Image is ready. The ImageReadyListener handles the -formatting of the java.awt.Image into a standard image format - JPEG, -GIF, etc. Caution: The ImageGenerator has been found to have timing -issues under loading, and some layers, for some reason, don't always -make it to the final image. The ImageServer utilizes the Layers' -ProjectionPainter interface methods to provide a reliable path for map -image creation. -

-The ImageServer is a manager class that prepares layers for the -ImageGenerator to use. The ImageServer has several forms of -createImage() methods, which accept projection requests, and then, -either cycle through the ImageGenerator to create map images, or cycle -through the Layers using their ProjectionPainter interface method. -With the former, the ImageServer also calls the appropriate -ImageReceiver for each projection request to hand over the formatted -image bytes when the image is created. -

-The MapRequestHandler is an extended ImageServer with methods that -parse OpenGIS Web Mapping Server format requests, and create images in -response to those requests. - diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/CapabilitiesSupport.java b/src/core/src/main/java/com/bbn/openmap/image/wms/CapabilitiesSupport.java deleted file mode 100644 index a6b6969ab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/CapabilitiesSupport.java +++ /dev/null @@ -1,450 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/CapabilitiesSupport.java,v 1.5 2009/01/15 19:38:33 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.awt.geom.Dimension2D; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import com.bbn.openmap.image.ImageServer; -import com.bbn.openmap.image.WMTConstants; -import com.bbn.openmap.proj.coords.AxisOrder; -import com.bbn.openmap.proj.coords.BoundingBox; -import com.bbn.openmap.proj.coords.CoordinateReferenceSystem; - -/** - * @version $Header: - * /cvs/CVS_LEBA/external/openmap/openmap/src/openmap/com/bbn/openmap - * /wms/CapabilitiesSupport.java,v 1.1 2006/03/21 10:27:54 tomrak Exp $ - * @author pitek - */ -public class CapabilitiesSupport { - - public static final String WMSPrefix = ImageServer.OpenMapPrefix + "wms."; - - public static final int FMT_GETMAP = 0; - - public static final int FMT_GETFEATUREINFO = 1; - - private Map> formatsList = new HashMap>(); - - private String onlineResource; - - private List keywordsList = null; - - private String wmsTitle = null; - - private String wmsAbstract = null; - - private int updateSequence = 1; - - private List wmslayers = new ArrayList(); - - private String layersTitle; - - private Collection crsCodes = CoordinateReferenceSystem.getCodes(); - - /** - * Creates a new instance of CapabilitiesSupport - * - * @param props - * @param scheme - * @param hostName - * @param port - * @param path - * @throws WMSException - */ - CapabilitiesSupport(Properties props, String scheme, String hostName, int port, String path) - throws WMSException { - - wmsTitle = props.getProperty(WMSPrefix + "Title", "Sample Title"); - wmsAbstract = props.getProperty(WMSPrefix + "Abstract", "Sample Abstract"); - layersTitle = props.getProperty(WMSPrefix + "LayersTitle", "Sample Layer List"); - String[] strKeywords = props.getProperty(WMSPrefix + "Keyword", "").split(" "); - List keywords = Arrays.asList(strKeywords); - setKeywords(keywords); - - setUrl(scheme, hostName, port, path); - - List al = new ArrayList(); - setFormats(FMT_GETMAP, al); - setFormats(FMT_GETFEATUREINFO, al); - } - - /** - * Set url to wms servlet. - * - * @param scheme - * @param hostName - * @param port - * @param path a String like "/myproject/wms" - */ - public void setUrl(String scheme, String hostName, int port, String path) { - StringBuilder url = new StringBuilder(); - url.append(scheme); - url.append("://"); - url.append(hostName); - if (!((scheme.equals("http") && (port == 80)) || (scheme.equals("https") && (port == 443)))) { - url.append(":"); - url.append(port); - } - url.append(path); - setUrl(url.toString()); - } - - /** - * Set url to wms servlet like "http://myserver/myproject/wms" - * - * @param url - */ - public void setUrl(String url) { - this.onlineResource = url; - } - - /** - * @return Document specifying capabilities. - */ - private Document generateCapabilitiesDocument(Version version) { - - Document doc = version.createCapabilitiesDocumentStart(); - - Element root = doc.getDocumentElement(); - root.setAttribute("version", version.getVersionString()); - root.setAttribute("updateSequence", Integer.toString(updateSequence)); - - Element service = doc.createElement("Service"); - service.appendChild(textnode(doc, "Name", version.getServiceName())); - service.appendChild(textnode(doc, "Title", wmsTitle)); - service.appendChild(textnode(doc, "Abstract", wmsAbstract)); - - if (!keywordsList.isEmpty()) { - Element keywordListElement = doc.createElement("KeywordList"); - for (int i = 0; i < keywordsList.size(); i++) { - keywordListElement.appendChild(textnode(doc, "Keyword", (String) keywordsList.get(i))); - } - service.appendChild(keywordListElement); - } - - service.appendChild(onlineResource(doc, onlineResource)); - - service.appendChild(textnode(doc, "Fees", "none")); - service.appendChild(textnode(doc, "AccessConstraints", "none")); - root.appendChild(service); - - Node capability = doc.createElement("Capability"); - Element request = doc.createElement("Request"); - - request.appendChild(requestcap(doc, WMTConstants.GETCAPABILITIES, version.getCapabiltiesFormats(), "Get", - onlineResource)); - request.appendChild(requestcap(doc, WMTConstants.GETMAP, formatsList.get(FMT_GETMAP), "Get", - onlineResource)); - request.appendChild(requestcap(doc, WMTConstants.GETFEATUREINFO, formatsList.get(FMT_GETFEATUREINFO), "Get", - onlineResource)); - capability.appendChild(request); - - Element exceptionElement = doc.createElement("Exception"); - for (String format : version.getExceptionFormats()) { - exceptionElement.appendChild(textnode(doc, "Format", format)); - } - capability.appendChild(exceptionElement); - - capability.appendChild(createLayersElement(doc, version)); - root.appendChild(capability); - - return doc; - } - - private Element createLayersElement(Document doc, Version version) { - Element layers = doc.createElement("Layer"); - layers.appendChild(textnode(doc, "Title", layersTitle)); - for (Iterator it = crsCodes.iterator(); it.hasNext();) { - layers.appendChild(textnode(doc, version.getCoordinateReferenceSystemAcronym(), it.next())); - } - - // append bounding boxes - layers.appendChild(version.createLatLonBoundingBox(doc)); - for (Iterator it = crsCodes.iterator(); it.hasNext();) { - appendSRSBoundingBox(doc, layers, it.next(), version); - } - - // append layers - // in OpenMap, the layer on top is listed first, but in WMS - // Capabilities, the layer on top is listed at the bottom - List reverseLayers = new ArrayList(wmslayers); - Collections.reverse(reverseLayers); - for (IWmsLayer wmsLayer : reverseLayers) { - createLayerElement(doc, layers, wmsLayer, version); - } - return layers; - } - - private void createLayerElement(Document doc, Element layers, IWmsLayer wmsLayer, Version version) { - org.w3c.dom.Element layerElement = (org.w3c.dom.Element) node(doc, "Layer"); - layerElement.setAttribute("queryable", wmsLayer.isQueryable() ? "1" : "0"); - // implied layerElement.setAttribute("cascaded", "0"); - layerElement.setAttribute("opaque", "0"); - layerElement.setAttribute("noSubsets", "0"); - // implied layerElement.setAttribute("fixedWidth", "0"); - // implied layerElement.setAttribute("fixedHeight", "0"); - - layerElement.appendChild(textnode(doc, "Name", wmsLayer.getWmsName())); - layerElement.appendChild(textnode(doc, "Title", wmsLayer.getTitle())); - if (wmsLayer.getAbstract() != null) { - layerElement.appendChild(textnode(doc, "Abstract", wmsLayer.getAbstract())); - } - - // add styles - IWmsLayerStyle[] styles = wmsLayer.getStyles(); - if (styles != null) { - for (int i = 0; i < styles.length; i++) { - IWmsLayerStyle style = styles[i]; - org.w3c.dom.Element styleElement = (org.w3c.dom.Element) node(doc, "Style"); - styleElement.appendChild(textnode(doc, "Name", style.getName())); // "default" - styleElement.appendChild(textnode(doc, "Title", style.getTitle())); // "Default - // style" - if (style.getAbstract() != null) { - styleElement.appendChild(textnode(doc, "Abstract", style.getAbstract())); - } - - // tell the layer about the style so the style can used legend - // graphics - wmsLayer.setStyle(style.getName()); - Legend legend = wmsLayer.getLegend(); - if (legend != null) { - for (Dimension2D dimension : legend.getSizeHints()) { - int width = (int) dimension.getWidth(); - int height = (int) dimension.getHeight(); - String format = "image/png"; - - Element legendURLElement = (Element) node(doc, "LegendURL"); - legendURLElement.setAttribute("width", Integer.toString(width)); - legendURLElement.setAttribute("height", Integer.toString(height)); - legendURLElement.appendChild(textnode(doc, "Format", format)); - - StringBuilder url = new StringBuilder(); - // would be nicer to use FMT_GETLEGENDGRAPHIC, but it - // may not be listed - url.append(onlineResource); - url.append("?").append(WMTConstants.SERVICE).append("=WMS"); - url.append("&").append(WMTConstants.VERSION).append("="); - url.append(version.getVersionString()); - url.append("&").append(WMTConstants.REQUEST).append("="); - url.append(WMTConstants.GETLEGENDGRAPHIC); - url.append("&").append(WMTConstants.LAYER).append("="); - url.append(wmsLayer.getWmsName()); - url.append("&").append(WMTConstants.STYLE).append("=").append(style.getName()); - url.append("&").append(WMTConstants.FORMAT).append("=").append(format); - url.append("&").append(WMTConstants.WIDTH).append("=").append(width); - url.append("&").append(WMTConstants.HEIGHT).append("=").append(height); - - legendURLElement.appendChild(onlineResource(doc, url.toString())); - - styleElement.appendChild(legendURLElement); - } - } - - layerElement.appendChild(styleElement); - } - } - - // add nested layers - if (wmsLayer instanceof IWmsNestedLayer) { - IWmsLayer[] nestedLayers = ((IWmsNestedLayer) wmsLayer).getNestedLayers(); - if (nestedLayers != null) { - for (int i = 0; i < nestedLayers.length; i++) { - createLayerElement(doc, layerElement, nestedLayers[i], version); - } - } - } - - layers.appendChild(layerElement); - } - - /** - */ - public void incUpdateSequence() { - updateSequence++; - } - - /** - * @param request - * @param formats - * @return true if request type handled - */ - public boolean setFormats(int request, Collection formats) { - switch (request) { - case FMT_GETMAP: - case FMT_GETFEATUREINFO: - formatsList.put(request, new ArrayList(formats)); - return true; - default: - return false; - } - } - - /** - * @param url - */ - public void setOnlineResource(String url) { - this.onlineResource = url; - } - - /** - * @param keywordsList - */ - public void setKeywords(List keywordsList) { - this.keywordsList = keywordsList; - } - - public void addLayer(IWmsLayer wmsLayer) { - wmslayers.add(wmsLayer); - } - - public void setLayersTitle(String title) { - this.layersTitle = title; - } - - private void appendSRSBoundingBox(Document doc, Element layers, String crsCode, Version version) { - CoordinateReferenceSystem crs = CoordinateReferenceSystem.getForCode(crsCode); - BoundingBox bbox = crs.getBoundingBox(); - if (bbox == null) { - return; - } - org.w3c.dom.Element e1 = (org.w3c.dom.Element) node(doc, "BoundingBox"); - e1.setAttribute(version.getCoordinateReferenceSystemAcronym(), crs.getCode()); - - if (version.usesAxisOrder() && (crs.getAxisOrder() == AxisOrder.northBeforeEast)) { - // wms 1.3.0. 6.7.4 EXAMPLE 2 - // "A representing the entire Earth in the EPSG:4326 - // Layer CRS would be written as . A BBOX parameter - // requesting a map of the entire Earth would be written in this CRS - // as - // BBOX=-90,-180,90,180." - e1.setAttribute("minx", Double.toString(bbox.getMinY())); - e1.setAttribute("miny", Double.toString(bbox.getMinX())); - e1.setAttribute("maxx", Double.toString(bbox.getMaxY())); - e1.setAttribute("maxy", Double.toString(bbox.getMaxX())); - } else { - e1.setAttribute("minx", Double.toString(bbox.getMinX())); - e1.setAttribute("miny", Double.toString(bbox.getMinY())); - e1.setAttribute("maxx", Double.toString(bbox.getMaxX())); - e1.setAttribute("maxy", Double.toString(bbox.getMaxY())); - } - layers.appendChild(e1); - } - - /** - * Generate String out of the XML document object - * - * @throws IOException, TransformerException, - * TransformerConfigurationException - */ - String generateXMLString(Version version) - throws IOException, TransformerConfigurationException, TransformerException { - - StringWriter strWriter = new StringWriter(); - Transformer tr = TransformerFactory.newInstance().newTransformer(); - tr.setOutputProperty(OutputKeys.INDENT, "yes"); - tr.setOutputProperty(OutputKeys.METHOD, "xml"); - tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - tr.setOutputProperty(OutputKeys.VERSION, "1.0"); - tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - - Document document = generateCapabilitiesDocument(version); - - // system id not transformed by default transformer - if (document.getDoctype() != null) { - tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, document.getDoctype().getSystemId()); - } - - // Serialize XML Document - tr.transform(new DOMSource(document), new StreamResult(strWriter)); - return strWriter.toString(); - } - - /** - * @param Name - * @param Text - * @return Node created for doc with name - */ - private Node textnode(Document doc, String Name, String text) { - Element e1 = doc.createElement(Name); - if (text == null) { - text = ""; - } - Node n = doc.createTextNode(text); - e1.appendChild(n); - return e1; - } - - /** - * @param doc Document - * @param Name name - * @return Node created for doc with name - */ - private Node node(Document doc, String Name) { - return doc.createElement(Name); - } - - private Node onlineResource(Document doc, String url) { - Element onlineResource = doc.createElement("OnlineResource"); - onlineResource.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink"); - onlineResource.setAttribute("xlink:type", "simple"); - onlineResource.setAttribute("xlink:href", url); - return onlineResource; - } - - /** - * @param doc - * @param requestName like "GetMap" - * @param formatList - * @param methodName like "Get" or "Post" - * @param url - * @return Node - */ - private Node requestcap(Document doc, String requestName, Collection formatList, String methodName, String url) { - Element methodNode = doc.createElement(methodName); - methodNode.appendChild(onlineResource(doc, url)); - - Element httpNode = doc.createElement("HTTP"); - httpNode.appendChild(methodNode); - - Element dcpTypeNode = doc.createElement("DCPType"); - dcpTypeNode.appendChild(httpNode); - - Element requestNameNode = doc.createElement(requestName); - for (String format : formatList) { - requestNameNode.appendChild(textnode(doc, "Format", format)); - } - requestNameNode.appendChild(dcpTypeNode); - - return requestNameNode; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultFeatureInfoResponse.java b/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultFeatureInfoResponse.java deleted file mode 100644 index 815c4e3b1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultFeatureInfoResponse.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.util.Arrays; -import java.util.Collection; - -import com.bbn.openmap.util.http.HttpConnection; - -public class DefaultFeatureInfoResponse implements FeatureInfoResponse { - - private StringBuffer out; - private String contentType; - - public void setOutput(String contentType, StringBuffer out) { - this.out = out; - this.contentType = contentType; - - appendHeader(); - } - - public void flush() { - appendFooter(); - } - - public Collection getInfoFormats() { - return Arrays.asList(HttpConnection.CONTENT_HTML, - HttpConnection.CONTENT_PLAIN); - } - - public void output(LayerFeatureInfoResponse layerFeatureInfoResponse) { - layerFeatureInfoResponse.output(contentType, out); - } - - protected void write(String s){ - out.append(s); - } - - protected String getContentType(){ - return contentType; - } - - protected void appendHeader() { - if (getContentType().equals(HttpConnection.CONTENT_HTML)) { - write("\n"); - write("\n"); - write("\n"); - } else if (getContentType().equals(HttpConnection.CONTENT_JSON)) { - write("{\n"); - write(" \"type\": \"FeatureCollection\",\n"); - write(" \"features\": [\n"); - } - } - - protected void appendFooter() { - if (getContentType().equals(HttpConnection.CONTENT_HTML)) { - write(""); - } else if (getContentType().equals(HttpConnection.CONTENT_JSON)) { - write(" ]\n"); - write("}\n"); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultLayerAdapter.java b/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultLayerAdapter.java deleted file mode 100644 index 23094c6ae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultLayerAdapter.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/DefaultLayerAdapter.java,v 1.3 2008/09/19 14:20:14 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.util.Properties; - -import com.bbn.openmap.Layer; - -/** - * Used to wrap a {@link Layer}s that does not implement {@link IWmsLayer} - * - * @version $Header: - * /cvs/openmap/openmap/src/openmap/com/bbn/openmap/image/wms/DefaultLayerAdapter.java,v - * 1.2.2.1 2008/08/20 11:28:43 halset Exp $ - * @author pitek - */ -class DefaultLayerAdapter implements IWmsLayer { - - private static final IWmsLayerStyle[] defaultStyle = new IWmsLayerStyle[1]; - - static { - defaultStyle[0] = new DefaultWmsLayerStyle("default", "Default style", null); - } - - protected final Layer layer; - - /** - * Creates a new instance of OpenMapLayerAdapter - * - * @param layer - */ - public DefaultLayerAdapter(Layer layer) { - this.layer = layer; - } - - /** - * @return - */ - public boolean isQueryable() { - return false; - } - - public LayerFeatureInfoResponse query(int x, int y) { - return new LayerFeatureInfoResponse() { - - public void output(String contentType, StringBuffer out) { - } - - }; - } - - /** - * @return - */ - public String getTitle() { - return layer.getName(); - } - - /** - * @return - */ - public IWmsLayerStyle[] getStyles() { - return defaultStyle; - } - - /** - * @return - */ - public String getWmsName() { - return layer.getPropertyPrefix(); - } - - /** - * @return - */ - public String getAbstract() { - return layer.getName(); - } - - /** - * @param name - * @throws IllegalArgumentException - */ - public void setStyle(String name) { - if (!isStyleSupported(name)) { - throw new IllegalArgumentException("Unsupported style " + name); - } - } - - /** - * @param name - * @return - */ - public boolean isStyleSupported(String name) { - IWmsLayerStyle[] styles = getStyles(); - for (int i = 0; i < styles.length; i++) { - IWmsLayerStyle style = styles[i]; - if (style.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - */ - public void setDefaultStyle() { - // DO NOTHING - } - - public void setRequestParameters(Properties requestParameters) { - // DO NOTHING - } - - public Legend getLegend() { - return null; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultWmsLayerStyle.java b/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultWmsLayerStyle.java deleted file mode 100644 index c635b19ae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/DefaultWmsLayerStyle.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/DefaultWmsLayerStyle.java,v 1.2 2008/01/29 22:04:13 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - - -/** - * @version $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/DefaultWmsLayerStyle.java,v 1.2 2008/01/29 22:04:13 dietrick Exp $ - * @author pitek - */ -public class DefaultWmsLayerStyle implements IWmsLayerStyle { - - private final String name; - private final String title; - private final String styleAbstract; - - /** - * Creates a new instance of DefaultWmsLayerStyle - * - * @param name - * @param title - * @param styleAbstract - */ - public DefaultWmsLayerStyle(String name, String title, String styleAbstract) { - this.name = name; - this.title = title; - this.styleAbstract = styleAbstract; - } - - /** - * @return title - */ - public String getTitle() { - return title; - } - - /** - * @return name - */ - public String getName() { - return name; - } - - /** - * @return string for style abstract - */ - public String getAbstract() { - return styleAbstract; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/DynamicWmsRequestHandler.java b/src/core/src/main/java/com/bbn/openmap/image/wms/DynamicWmsRequestHandler.java deleted file mode 100644 index 0d9f8a9c7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/DynamicWmsRequestHandler.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/DynamicWmsRequestHandler.java,v 1.2 2008/01/29 22:04:13 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.util.Debug; - -/** - * @version $Header: - * /cvs/CVS_LEBA/external/openmap/openmap/src/openmap/com/bbn/openmap - * /wms/DynamicWmsRequestHandler.java,v 1.1 2006/03/21 10:27:54 tomrak - * Exp $ - * @author Adam Dawidowski - * @author wachu - * @author pitek - */ -public class DynamicWmsRequestHandler - extends WmsRequestHandler { - - // Handle the dynamic and static layers - final LayerHandler mapLayerHandler; - - // layer names loaded from the file properties - private final String staticLayersNames; - - public DynamicWmsRequestHandler(String scheme, String hostName, int port, String path, Properties props, - LayerHandler mapLayerHandler) - throws IOException, WMSException { - super(scheme, hostName, port, path, props); - this.mapLayerHandler = mapLayerHandler; - // remember the name of the static layer that, when not to UpdateLayer y - // retrieved from LayerHandlera - staticLayersNames = props.getProperty("openmap.layers"); - } - - /** - * export method used to read the new target data, in order to upload newly - * created layers of graphics (using layerHandlera) on under the assumed - * adowach earlier data for the layers with static data, ie maps of the - * ports, are out to date, and only s remaining layer (read from - * LayerHandler) and updated added to the array layers. Table stores layers - * layers used by the image server to image generation. - */ - public void updateLayers() { - Debug.message("imageserver", "OGCMRH: updateLayers updating..."); - if (layers == null) { - layers = new Layer[0]; - Debug.message("imageserver", "OGCMRH: updateLayers layers==null, so create new layer."); - } - if (getLayerHandler() == null) { - Debug.message("imageserver", "OGCMRH: updateLayers: LayerHandler is null."); - return; - } - Layer[] newLayers = getLayerHandler().getLayers(); - if (layers.length < newLayers.length) { - // here come only once, when - // first add layers of - // targets Gdynia, Hel ... - // vector at the encoder is used only when it will switch the new - // layer (layers is a normal array and you can not enlarge it, so - // use vector which later changed to an array) - Debug.message("ms", "OGCserver: updateLayers: NEW LAYERS COMES."); - - List tmpLayers = new ArrayList(); - for (int j = 0; j < layers.length; j++) { - /* add the old layers (static, washers ad maps) */ - tmpLayers.add(layers[j]); - } - - for (int i = 0; i < newLayers.length; i++) { - /* - * add new layer (dynamic maps) but no static that's already - * added - */ - boolean layerAlreadyAdded = false; - for (int j = 0; j < layers.length; j++) { - /* - * Check that among the new layer has no chance static layer - * (ie the old layers) - */ - String layerName = layers[j].getName(); - String newLayerName = newLayers[i].getName(); - if (layerName.trim().equalsIgnoreCase(newLayerName.trim())) { - layerAlreadyAdded = true; - } - } - if (!layerAlreadyAdded) { - /* - * if the layer is not checked for static (ie, port map) to - * j add to vector - */ - tmpLayers.add(newLayers[i]); - } - } - Layer[] newArrLayers = (Layer[]) tmpLayers.toArray(new Layer[tmpLayers.size()]); - layers = newArrLayers; - for (int j = 0; j < layers.length; j++) { // dodaj stare warstwy - // (statyczne, podkad - // mapy) - layers[j].setPropertyPrefix(layers[j].getName()); - // Debug.message("imageserver", "OGCMRH: updateLayers NEW LAYERS - // layer:" + layers[j].getName()); - } - } else { // update the existing layers - Debug.message("ms", "OGCserver: updateLayers: UPDATE LAYERS COMES."); - for (int i = 0; i < newLayers.length; i++) { - for (int j = 0; j < layers.length; j++) { - // Debug.message("imageserver", "OGCMRH: updateLayers layer: - // sprawdzam par warstw :>" + newLayers[i].getName()+"< i - // >"+layers[j].getName()+"<"); - if (layers[j].getName().trim().equalsIgnoreCase(newLayers[i].getName().trim())) { - // if - // (newLayers[i].getName().trim().equalsIgnoreCase("Ports") - // || - // newLayers[i].getName().trim().equalsIgnoreCase("PortsGd")) - // { - String[] oldLayers = staticLayersNames.split(" "); - boolean found = false; - for (int k = 0; k < oldLayers.length; k++) { - if (oldLayers[k].equals(newLayers[i].getName().trim())) { - found = true; - break; - } - } - // if - // (staticLayersNames.contains(newLayers[i].getName().trim())) - // { - // // Debug.message("imageserver", "OGCMRH: - // // updateLayers layer:" + newLayers[i].getName()+" - // // nie jest zmieniana "); - // } else { // update istniejacej warstwy - if (found == false) { - layers[j] = newLayers[i]; - layers[j].setPropertyPrefix(layers[j].getName()); - // Debug.message("imageserver", "OGCMRH: - // updateLayers layer:" + layers[j].getName()); - } - } - } - } - } - - // update map names - createWmsLayers(); - } - - /** - * return - calls layer handler - * - * @return LayerHandler - */ - public LayerHandler getLayerHandler() { - return this.mapLayerHandler; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/FeatureInfoResponse.java b/src/core/src/main/java/com/bbn/openmap/image/wms/FeatureInfoResponse.java deleted file mode 100644 index c1804cf6e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/FeatureInfoResponse.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.util.Collection; - -public interface FeatureInfoResponse { - - /** - * Return a {@link Collection} of the supported INFO_FORMAT supported by - * this {@link FeatureInfoResponse} - * - * @return collection of strings for info formats - */ - public Collection getInfoFormats(); - - /** - * Initiate a new feature info response output with the given content type - * and output buffer - * - * @param contentType - * @param out - */ - public void setOutput(String contentType, StringBuffer out); - - public void flush(); - - public void output(LayerFeatureInfoResponse layerFeatureInfoResponse); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/FormatRequestParameter.java b/src/core/src/main/java/com/bbn/openmap/image/wms/FormatRequestParameter.java deleted file mode 100644 index 9aa3e602e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/FormatRequestParameter.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.bbn.openmap.image.wms; - -import com.bbn.openmap.image.ImageFormatter; - -/** - * A wms request parameter object that contain FORMAT element - */ -interface FormatRequestParameter { - - public void setFormatter(ImageFormatter formatter); - - public ImageFormatter getFormatter(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/GetCapabilitiesRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/GetCapabilitiesRequestParameters.java deleted file mode 100644 index de814f8d2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/GetCapabilitiesRequestParameters.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.bbn.openmap.image.wms; - -class GetCapabilitiesRequestParameters extends WmsRequestParameters { - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/GetFeatureInfoRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/GetFeatureInfoRequestParameters.java deleted file mode 100644 index ab8da94d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/GetFeatureInfoRequestParameters.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.util.ArrayList; -import java.util.List; - -class GetFeatureInfoRequestParameters extends GetMapRequestParameters { - - public int x; - - public int y; - - public final List queryLayerNames = new ArrayList(); - - public String infoFormat; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/GetLegendGraphicRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/GetLegendGraphicRequestParameters.java deleted file mode 100644 index 154a6efd7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/GetLegendGraphicRequestParameters.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.bbn.openmap.image.wms; - -import com.bbn.openmap.image.ImageFormatter; - -class GetLegendGraphicRequestParameters extends WmsRequestParameters implements FormatRequestParameter, - WidthAndHeightRequestParameters { - - private int width; - - private int height; - - private ImageFormatter formatter; - - public String layerName; - - public ImageFormatter getFormatter() { - return formatter; - } - - public void setFormatter(ImageFormatter formatter) { - this.formatter = formatter; - } - - public int getHeight() { - return height; - } - - public int getWidth() { - return width; - } - - public void setHeight(int height) { - this.height = height; - } - - public void setWidth(int width) { - this.width = width; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/GetMapRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/GetMapRequestParameters.java deleted file mode 100644 index 0e7a5f3cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/GetMapRequestParameters.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.awt.Paint; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.image.ImageFormatter; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.coords.CoordinateReferenceSystem; -import com.bbn.openmap.proj.coords.LatLonPoint; - -class GetMapRequestParameters extends WmsRequestParameters implements FormatRequestParameter, - WidthAndHeightRequestParameters { - - public int width; - - public int height; - - public CoordinateReferenceSystem crs; - - public LatLonPoint bboxLatLonLowerLeft; - - public LatLonPoint bboxLatLonUpperRight; - - public LatLonPoint bboxLatLonCenter; - - public ImageFormatter formatter; - - private boolean transparent = true; - - public Paint background = OMColor.clear; - - /** - * All wms layer names as they appear in the LAYERS-element of the request. - * Some of the layer names may be to a nested layer. - */ - public final List layerNames = new ArrayList(); - - /** - * All top level layer names for each of the layer names. So, if the request - * has two sub level layer names with the same top level layer name, this - * list will only have that single top level layer name. - */ - public final List topLayerNames = new ArrayList(); - - public ImageFormatter getFormatter() { - return formatter; - } - - public void setFormatter(ImageFormatter formatter) { - this.formatter = formatter; - } - - public int getHeight() { - return height; - } - - public int getWidth() { - return width; - } - - public void setHeight(int height) { - this.height = height; - } - - public void setWidth(int width) { - this.width = width; - } - - public void setTransparent(boolean transparent) { - this.transparent = transparent; - } - - public boolean getTransparent() { - return transparent; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayer.java b/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayer.java deleted file mode 100644 index 69aafbc85..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayer.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/IWmsLayer.java,v 1.3 2008/09/19 14:20:14 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.util.Properties; - -/** - * @version $Header: - * /cvs/openmap/openmap/src/openmap/com/bbn/openmap/image/wms/IWmsLayer.java,v - * 1.2.2.1 2008/08/20 11:28:43 halset Exp $ - * @author pitek - */ -public interface IWmsLayer { - - /** - * @return a string for the layer title - */ - public String getTitle(); - - /** - * @return a String representing the short layer name. It is like - * {@link com.bbn.openmap.Layer#getPropertyPrefix()} and are used in WMS Urls. - */ - public String getWmsName(); - - /** - * @return a string description of the layer - */ - public String getAbstract(); - - /** - * @return true if layer is queryable - */ - public boolean isQueryable(); - - /** - * Do a GetFeatureInfo query. - * - * @param x - * @param y - * @return LayerFeatureInfoResponse from query - */ - public LayerFeatureInfoResponse query(int x, int y); - - /** - * @return IWmsLayerStyle array of available styles. - */ - public IWmsLayerStyle[] getStyles(); - - /** - * Set the style in the layer - * - * @param name style name - */ - public void setStyle(String name); - - /** - * @param name style name for query - * @return true if style supported - */ - public boolean isStyleSupported(String name); - - /** - */ - public void setDefaultStyle(); - - /** - * OpenMap will use this method to set request parameters to the layer. The - * layer can then pick up extra non-standard parameters if needed. - *

- * For nested layers, this method may be called several times. - *

- * See wms-1.1.1 chapter 6.5.11 Vendor-Specific Parameters - * - * @param requestParameters - */ - public void setRequestParameters(Properties requestParameters); - - /** - * Return a {@link Legend} with legend information or null if legend can not - * be created. - * - * @return Legend for layer. - */ - public Legend getLegend(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayerStyle.java b/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayerStyle.java deleted file mode 100644 index afa15d906..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsLayerStyle.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/IWmsLayerStyle.java,v 1.2 2008/01/29 22:04:13 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -/** - * @version $Header: - * /cvs/CVS_LEBA/external/openmap/openmap/src/openmap/com/bbn/openmap - * /wms/IWmsLayerStyle.java,v 1.1 2006/03/21 10:27:54 tomrak Exp $ - * @author pitek - */ -public interface IWmsLayerStyle { - - /** - * @return title - */ - public String getTitle(); - - /** - * @return name - */ - public String getName(); - - /** - * @return abstract - */ - public String getAbstract(); - // public IWmsLegend getLegend(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsNestedLayer.java b/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsNestedLayer.java deleted file mode 100644 index 2a5269624..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/IWmsNestedLayer.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.bbn.openmap.image.wms; - -/** - * A variant of {@link IWmsLayer} that allow for nesting of wms layers. - *

- * Nested wms layers below a OpenMap {@link com.bbn.openmap.Layer} may be used - * to split up information in a single OpenMap Layer for wms users. - *

- * Example: A OpenMap city layer may have nested wms layers for the different - * type of cities. That way a wms user can select only the large cities. - *

- * There is always one top level {@link IWmsLayer} that also is a OpenMap - * {@link com.bbn.openmap.Layer} - see {@link #getTopLayer()}. There may be some - * nested layers "below" this layer - see {@link #getNestedLayers()} - */ -public interface IWmsNestedLayer extends IWmsLayer { - - /** - * Return an array of {@link IWmsLayer} for each of the nested layers. - * Nested layers may also be {@link IWmsNestedLayer} to support multiple - * nesting levels. - *

- * Null or an empty array is returned if no nested layers exist. - * - * @return an array of {@link IWmsLayer} with info about nested layers - */ - public IWmsNestedLayer[] getNestedLayers(); - - /** - * Return the top layer, that is the IWmsLayer that also is an OpenMap - * {@link com.bbn.openmap.Layer}. For such a top level layer, this method - * should return it self. - */ - public IWmsNestedLayer getTopLayer(); - - /** - * Called by the outside to turn this nested layer on or off. - *

- * If this method is not called, then this nested layer is off. - */ - public void setIsActive(boolean active); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/LayerFeatureInfoResponse.java b/src/core/src/main/java/com/bbn/openmap/image/wms/LayerFeatureInfoResponse.java deleted file mode 100644 index a6ddaebb9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/LayerFeatureInfoResponse.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.bbn.openmap.image.wms; - -public interface LayerFeatureInfoResponse { - - public void output(String contentType, StringBuffer out); -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/Legend.java b/src/core/src/main/java/com/bbn/openmap/image/wms/Legend.java deleted file mode 100644 index 6f6940a16..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/Legend.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.awt.Graphics; -import java.awt.geom.Dimension2D; -import java.util.Collection; - -/** - * An interface for providing legend graphics to wms clients - */ -public interface Legend { - - public Collection getSizeHints(); - - public void setSize(int width, int height); - - public void paint(Graphics g); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/Version.java b/src/core/src/main/java/com/bbn/openmap/image/wms/Version.java deleted file mode 100644 index 83b2de163..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/Version.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.bbn.openmap.image.wms; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.w3c.dom.Element; - -/** - * WMS version as found in the request parameter named VERSION. - */ -abstract class Version { - - private static final Version V111 = new V111("1.1.1"); - - private static final Version V130 = new V130("1.3.0"); - - private static final Map byVersionString; - - static { - Map m = new HashMap(); - m.put(V111.getVersionString(), V111); - m.put(V130.getVersionString(), V130); - byVersionString = Collections.unmodifiableMap(m); - } - - private String version; - - private Version(String version) { - this.version = version; - } - - public static Version getVersion(String versionString) { - return byVersionString.get(versionString); - } - - public static Version getVersionBestMatch(String versionString) { - Version version = getVersion(versionString); - if (version != null) { - return version; - } - if (versionString == null) { - return getDefault(); - } - if (versionString.startsWith("1.1")) { - return V111; - } - if (versionString.startsWith("1.3")) { - return V130; - } - return getDefault(); - } - - public static Version getDefault() { - return V111; - } - - public String getVersionString() { - return version; - } - - public String toString() { - return getVersionString(); - } - - public abstract Document createCapabilitiesDocumentStart(); - - public abstract Element createLatLonBoundingBox(Document doc); - - public abstract String getCoordinateReferenceSystemAcronym(); - - public abstract boolean usesAxisOrder(); - - public abstract String getServiceName(); - - public abstract Collection getCapabiltiesFormats(); - - public abstract Collection getExceptionFormats(); - - private static class V111 extends Version { - - public V111(String version) { - super(version); - } - - public Document createCapabilitiesDocumentStart() { - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); - - DOMImplementation impl = builder.getDOMImplementation(); - DocumentType doctype = impl - .createDocumentType("wms", "WMT_MS_Capabilities", - "http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd"); - Document doc = impl.createDocument(null, "WMT_MS_Capabilities", - doctype); - - return doc; - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new RuntimeException("Cannot create new Xml Document:" - + ex.getMessage()); - } - } - - public Element createLatLonBoundingBox(Document doc) { - Element e1 = doc.createElement("LatLonBoundingBox"); - e1.setAttribute("minx", "-180"); - e1.setAttribute("miny", "-90"); - e1.setAttribute("maxx", "180"); - e1.setAttribute("maxy", "90"); - return e1; - } - - @Override - public String getCoordinateReferenceSystemAcronym() { - return "SRS"; - } - - @Override - public boolean usesAxisOrder() { - return false; - } - - @Override - public String getServiceName() { - return "OGC:WMS"; - } - - @Override - public Collection getExceptionFormats() { - return Arrays.asList("application/vnd.ogc.se_xml"); - } - - @Override - public Collection getCapabiltiesFormats() { - return Arrays.asList("application/vnd.ogc.wms_xml"); - } - - } - - private static class V130 extends Version { - - public V130(String version) { - super(version); - } - - public Document createCapabilitiesDocumentStart() { - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); - - DOMImplementation impl = builder.getDOMImplementation(); - // TODO: add xsd stuff for WMS_Capabilities. how? - // - Document doc = impl.createDocument( - "http://www.opengis.net/wms", "WMS_Capabilities", null); - - return doc; - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new RuntimeException("Cannot create new Xml Document:" - + ex.getMessage()); - } - } - - public Element createLatLonBoundingBox(Document doc) { - Element bb = doc.createElement("EX_GeographicBoundingBox"); - - Element w = doc.createElement("westBoundLongitude"); - w.setTextContent("-180"); - bb.appendChild(w); - - Element e = doc.createElement("eastBoundLongitude"); - e.setTextContent("180"); - bb.appendChild(e); - - Element s = doc.createElement("southBoundLatitude"); - s.setTextContent("-90"); - bb.appendChild(s); - - Element n = doc.createElement("northBoundLatitude"); - n.setTextContent("90"); - bb.appendChild(n); - - return bb; - } - - @Override - public String getCoordinateReferenceSystemAcronym() { - return "CRS"; - } - - @Override - public boolean usesAxisOrder() { - return true; - } - - @Override - public String getServiceName() { - return "WMS"; - } - - @Override - public Collection getExceptionFormats() { - return Arrays.asList("XML"); - } - - @Override - public Collection getCapabiltiesFormats() { - return Arrays.asList("text/xml"); - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/WMSException.java b/src/core/src/main/java/com/bbn/openmap/image/wms/WMSException.java deleted file mode 100644 index 64b51fe9d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/WMSException.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/WMSException.java,v 1.3 2009/01/15 19:38:33 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.io.StringWriter; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.bbn.openmap.util.Debug; - -/** - * Generates a WMS Exception in the form of XML with the specified code and - * explanation message. - * - * @version $Header: - * /cvs/CVS_LEBA/common/porttrack/src/java/com/obrctm/porttrack/modules/OGCMapRequestHandler.java,v - * 1.10 2005/10/14 10:08:32 wachu Exp - * @author pitek - */ -public class WMSException extends Exception { - - // these codes are defined in WMS specification version 1.3.0 - /** - */ - public static final String INVALIDFORMAT = "InvalidFormat"; - - // WMS 1.3.0 - // public static final String INVALIDCRS = "InvalidCRS"; - // WMS 1.1.1 - /** - */ - public static final String INVALIDSRS = "InvalidSRS"; - - /** - */ - public static final String LAYERNOTDEFINED = "LayerNotDefined"; - - /** - */ - public static final String STYLENOTDEFINED = "StyleNotDefined"; - - /** - */ - public static final String LAYERNOTQUERYABLE = "LayerNotQueryable"; - - /** - */ - public static final String INVALIDPOINT = "InvalidPoint"; - - /** - */ - public static final String CURRENTUPDATESEQUENCE = "CurrentUpdateSequence"; - - /** - */ - public static final String INVALIDUPDATESEQUENCE = "InvalidUpdateSequence"; - - /** - */ - public static final String MISSINGDIMENSIONVALUE = "MissingDimensionValue"; - - /** - */ - public static final String INVALIDDIMENSIONVALUE = "InvalidDimensionValue"; - - // only in WMS 1.3.0, but who cares... - /** - */ - public static final String OPERATIONNOTSUPPORTED = "OperationNotSupported"; - - // this is an unsupported code, but it seems useful enough to include. - /** - */ - public static final String INTERNALERROR = "InternalError"; - - protected static String exceptionTemplate = "" - + "" - + ""; - - private String XML; - - private String Message; - - private String Code; - - /** - * Creates a new WMSException object. - */ - public WMSException() { - this("All your base are belong to us.", null); - } - - /** - * Creates a new WMSException object. - * - * @param message - */ - public WMSException(String message) { - this(message, null); - } - -// /** -// * Creates a new WMSException object. -// * -// * @param message -// * @param code -// */ -// public WMSException(String message, String code) { -// super(); -// Message = message; -// Code = code; -// -// Document doc = new DocumentImpl(); -// Element root = doc.createElement("ServiceExceptionReport"); -// root.setAttribute("version", "1.1.0"); -// Element ex = doc.createElement("ServiceException"); -// ex.appendChild(doc.createTextNode(Message)); -// if (Code != null) -// ex.setAttribute("code", Code); -// -// root.appendChild(ex); -// doc.appendChild(root); -// -// StringWriter strWriter = null; -// XMLSerializer serializer = null; -// OutputFormat outFormat = null; -// -// try { -// serializer = new XMLSerializer(); -// strWriter = new StringWriter(); -// outFormat = new OutputFormat(); -// -// // Setup format settings -// outFormat.setEncoding("UTF-8"); -// outFormat.setVersion("1.0"); -// outFormat.setIndenting(true); -// outFormat.setIndent(2); -// -// // Define a Writer -// serializer.setOutputCharStream(strWriter); -// -// // Apply the format settings -// serializer.setOutputFormat(outFormat); -// -// // Serialize XML Document -// serializer.serialize(doc); -// this.XML = strWriter.toString(); -// strWriter.close(); -// } catch (IOException ioEx) { -// Debug.output("WMSException Internal Error !\n["); -// ioEx.printStackTrace(); -// Debug.output("]"); -// this.XML = INTERNALERROR; -// } -// -// } - - /** - * Creates a new WMSException object. - * - * @param message - * @param code - */ - public WMSException(String message, String code) { - super(); - Message = message; - Code = code; - - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - -// Document doc = new DocumentImpl(); - Element root = doc.createElement("ServiceExceptionReport"); - root.setAttribute("version", "1.1.0"); - Element ex = doc.createElement("ServiceException"); - ex.appendChild(doc.createTextNode(Message)); - if (Code != null) - ex.setAttribute("code", Code); - - root.appendChild(ex); - doc.appendChild(root); - - StringWriter strWriter = new StringWriter(); -// XMLSerializer serializer = null; -// OutputFormat outFormat = null; - Transformer tr = TransformerFactory.newInstance().newTransformer(); - tr.setOutputProperty(OutputKeys.INDENT, "yes"); - tr.setOutputProperty(OutputKeys.METHOD,"xml"); - tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - tr.setOutputProperty(OutputKeys.VERSION,"1.0"); - tr.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); - -// Serialize XML Document - tr.transform( new DOMSource(doc),new StreamResult(strWriter)); - -// try { -// serializer = new XMLSerializer(); -// strWriter = new StringWriter(); -// outFormat = new OutputFormat(); -// -// // Setup format settings -// outFormat.setEncoding("UTF-8"); -// outFormat.setVersion("1.0"); -// outFormat.setIndenting(true); -// outFormat.setIndent(2); -// -// // Define a Writer -// serializer.setOutputCharStream(strWriter); -// -// // Apply the format settings -// serializer.setOutputFormat(outFormat); -// -// // Serialize XML Document -// serializer.serialize(doc); - this.XML = strWriter.toString(); - strWriter.close(); - } catch (Exception ex) { - Debug.output("WMSException Internal Error !\n["); - ex.printStackTrace(); - Debug.output("]"); - this.XML = INTERNALERROR; - } - - } - - /** - * @return xml for exception - */ - public String getXML() { - return XML; - } - - /** - * @return string error message - */ - public String getMessage() { - return Message; - } - - /** - * @return string for error code - */ - public String getCode() { - return Code; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/WidthAndHeightRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/WidthAndHeightRequestParameters.java deleted file mode 100644 index be01bbcb8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/WidthAndHeightRequestParameters.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.bbn.openmap.image.wms; - -interface WidthAndHeightRequestParameters { - - public void setWidth(int width); - - public int getWidth(); - - public void setHeight(int height); - - public int getHeight(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsLayerFactory.java b/src/core/src/main/java/com/bbn/openmap/image/wms/WmsLayerFactory.java deleted file mode 100644 index 341648cb7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsLayerFactory.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/WmsLayerFactory.java,v 1.2 2008/01/29 22:04:13 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.lang.reflect.Constructor; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Class responsible for creation IWmsLayer for Layers. - * - * @author tomrak - */ -public class WmsLayerFactory { - - private final Map wmsLayersMap = new HashMap(); - - public WmsLayerFactory(Properties props) throws WMSException { - String wmsLayers = props.getProperty("wms.layers"); - try { - for (Iterator it = PropUtils.parseSpacedMarkers(wmsLayers) - .iterator(); it.hasNext();) { - Object key = it.next(); - // TODO: looks like layerClass is supposed to be the IWmsLayer. really messy - Class layerClass = Class.forName(props.getProperty((String) key - + ".layerClass")); - Class clazz = Class.forName(props.getProperty((String) key - + ".class")); - wmsLayersMap.put(layerClass, clazz); - } - } catch (ClassNotFoundException ex) { - throw new WMSException("Problem with wmsLayers configuration"); - } - } - - /** - * "Convert" the Layer to a IWmsLayer. - * - * 1. pri: Will return the given Layer if it is a IWmsLayer. - * - * 2. pri: Use the .layerClass property for a IWmsLayer that takes Layer in - * the constructor to wrap the Layer in a IWmsLayer. TODO: This is a bit messy and - * should be refactored. - * - * 3. pri: Wrap it in DefaultLayerAdapter. - * - * @param layer source layer - * @return IWmsLayer created from layer - */ - IWmsLayer createWmsLayer(Layer layer) { - if (layer instanceof IWmsLayer) { - return (IWmsLayer) layer; - } - Class layerClass = layer.getClass(); - Class wmsLayerClass = (Class) wmsLayersMap.get(layerClass); - if (wmsLayerClass == null) { - return new DefaultLayerAdapter(layer); - } - IWmsLayer wmsLayer = null; - try { - Constructor constructor = wmsLayerClass.getConstructor(new Class[] { Layer.class }); - wmsLayer = (IWmsLayer) constructor.newInstance(new Object[] { layer }); - } catch (Exception ex) { - Debug.message("ms", "Problem calling constructor for class " - + wmsLayerClass.getName() + ":" + ex.getMessage()); - } - if (wmsLayer == null) { - wmsLayer = new DefaultLayerAdapter(layer); - } - return wmsLayer; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestHandler.java b/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestHandler.java deleted file mode 100644 index 3294219cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestHandler.java +++ /dev/null @@ -1,933 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/wms/WmsRequestHandler.java,v 1.5 2008/10/16 03:30:35 dietrick Exp $ - * - * Copyright 2001-2005 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.image.wms; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Pattern; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.image.ImageFormatter; -import com.bbn.openmap.image.ImageServer; -import com.bbn.openmap.image.ImageServerConstants; -import com.bbn.openmap.image.MapRequestFormatException; -import com.bbn.openmap.proj.AspectRatioProjection; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.coords.CoordinateReferenceSystem; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.http.HttpConnection; -import com.bbn.openmap.util.http.IHttpResponse; - -/** - * @version $Header: - * /cvs/CVS_LEBA/external/openmap/openmap/src/openmap/com/bbn/openmap - * /wms/WmsRequestHandler.java,v 1.2 2006/03/27 10:51:13 tomrak Exp $ - * @author Adam Dawidowski - * @author wachu - * @author pitek - */ -public class WmsRequestHandler extends ImageServer implements ImageServerConstants { - - /** - */ - private CapabilitiesSupport capabilities; - private Map wmsLayerByName = new HashMap(); - private List wmsLayers = new ArrayList(); - private WmsLayerFactory wmsLayerFactory; - private Map imageFormatterByContentType = new HashMap(); - private FeatureInfoResponse featureInfoResponse; - public static final String WMSPrefix = CapabilitiesSupport.WMSPrefix; - private static final String FeatureInfoResponseClassNameProperty = "featureInfoResponse.class"; - - /** - * Creates a new WmsRequestHandler object. - * - * @param wmsScheme for capabilities description - * @param wmsHostName for capabilities description - * @param wmsPort for capabilities description - * @param wmsUrlPath for capabilities description - * @param props openmap properties to configure layers - * @throws IOException - * @throws WMSException - */ - public WmsRequestHandler(String wmsScheme, String wmsHostName, int wmsPort, String wmsUrlPath, - Properties props) throws IOException, WMSException { - - super(props); - setProperties(props); - - // separate antialias property for wms. - boolean antialias = PropUtils.booleanFromProperties(props, WMSPrefix + AntiAliasingProperty, false); - setDoAntiAliasing(antialias); - - // for each Openmap Layer created by ImageServer (defined in properties) - // create corresponding IWmsLayer which contains all necessary - // information required by - // WMS (e.g getCapabilities method) - wmsLayerFactory = new WmsLayerFactory(props); - createWmsLayers(); - - // create a Map of all formatters by their contentType - for (ImageFormatter formatter : getFormatters().values()) { - imageFormatterByContentType.put(formatter.getContentType(), formatter); - } - - // create FeatureInfoResponse from properties. - featureInfoResponse = (FeatureInfoResponse) PropUtils.objectFromProperties(props, WMSPrefix - + FeatureInfoResponseClassNameProperty); - if (featureInfoResponse == null) { - featureInfoResponse = new DefaultFeatureInfoResponse(); - } - - // read from configuration fixed part of Capabilities Document returned - // in getCapabilities method - capabilities = new CapabilitiesSupport(props, wmsScheme, wmsHostName, wmsPort, wmsUrlPath); - List formatsList = new ArrayList(imageFormatterByContentType.keySet()); - capabilities.setFormats(CapabilitiesSupport.FMT_GETMAP, formatsList); - capabilities.setFormats(CapabilitiesSupport.FMT_GETFEATUREINFO, getFeatureInfoResponse().getInfoFormats()); - } - - /** - * For each layer managed by ImageServer create corresponding IWmsLayer - * which contains additional information for WMS service about given openmap - * layer. - * - * For Layers that already implement IWmsLayer, the instances will be the - * same. - */ - protected void createWmsLayers() { - wmsLayerByName.clear(); - wmsLayers.clear(); - for (int i = 0; i < layers.length; i++) { - Layer layer = layers[i]; - createWmsLayers(wmsLayerFactory.createWmsLayer(layer)); - } - } - - private void createWmsLayers(IWmsLayer layer) { - wmsLayerByName.put(layer.getWmsName(), layer); - wmsLayers.add(layer); - if (layer instanceof IWmsNestedLayer) { - IWmsNestedLayer n = (IWmsNestedLayer) layer; - if (n.getNestedLayers() != null) { - for (int i = 0; i < n.getNestedLayers().length; i++) { - createWmsLayers(n.getNestedLayers()[i]); - } - } - } - } - - /** - * Set the request parameters on all the layers - * - * @see IWmsLayer#setRequestParameters(Properties requestParameters) - * @param requestProperties - */ - protected void setRequestParametersOnLayers(Properties requestProperties) { - // use a Set to make sure we only set it once for each layer - Set handledNames = new HashSet(); - for (IWmsLayer wmsLayer : wmsLayers) { - if (!handledNames.contains(wmsLayer.getWmsName())) { - wmsLayer.setRequestParameters(requestProperties); - handledNames.add(wmsLayer.getWmsName()); - } - if (wmsLayer instanceof IWmsNestedLayer) { - IWmsNestedLayer nestedLayer = (IWmsNestedLayer) wmsLayer; - // make sure the top layer also get info about the request - // parameters - if (!handledNames.contains(nestedLayer.getTopLayer().getWmsName())) { - nestedLayer.getTopLayer().setRequestParameters(requestProperties); - handledNames.add(nestedLayer.getTopLayer().getWmsName()); - } - } - } - } - - protected IWmsLayer getLayerByName(String wmsName) { - return (IWmsLayer) wmsLayerByName.get(wmsName); - } - - /** - * Return the top OpenMap {@link Layer} for the given wms layer name. - * - * @param wmsName - * @return top layer - */ - protected Layer getTopLayerByName(String wmsName) { - IWmsLayer layer = getLayerByName(wmsName); - if (layer == null) { - return null; - } - if (layer instanceof IWmsNestedLayer) { - layer = ((IWmsNestedLayer) layer).getTopLayer(); - } - if (layer instanceof DefaultLayerAdapter) { - return ((DefaultLayerAdapter) layer).layer; - } - if (layer instanceof Layer) { - return (Layer) layer; - } - throw new IllegalStateException("Top layer must be a OpenMap Layer, not " - + layer.getClass()); - } - - /** - * @param requestProperties - * @param httpResponse output - * @throws IOException - * @throws MapRequestFormatException - */ - public void handleRequest(Properties requestProperties, IHttpResponse httpResponse) - throws IOException, MapRequestFormatException { - try { - String requestType = requestProperties.getProperty(REQUEST); - checkRequest(requestProperties); - if (requestType == null) { - throw new WMSException("Missing REQUEST type parameter"); - } - setRequestParametersOnLayers(requestProperties); - if (requestType.equalsIgnoreCase(GETMAP)) { - Debug.message("ms", "OGCMRH: GetMap request..."); - handleGetMapRequest(requestProperties, httpResponse); - } else if (requestType.equals(GETCAPABILITIES)) { - Debug.message("ms", "OGCMRH: GetCapabilities request..."); - handleGetCapabilitiesRequest(requestProperties, httpResponse); - } else if (requestType.equalsIgnoreCase(GETFEATUREINFO)) { - Debug.message("ms", "OGCMRH: GetFeatureInfo request..."); - handleGetFeatureInfoRequest(requestProperties, httpResponse); - } else if (requestType.equalsIgnoreCase(GETLEGENDGRAPHIC)) { - Debug.message("ms", "OGCMRH: GetFeatureInfo request..."); - handleGetLegendGraphicRequest(requestProperties, httpResponse); - } else { - throw new WMSException("Invalid REQUEST parameter: " + requestType, WMSException.OPERATIONNOTSUPPORTED); - } - } catch (WMSException e) { - Debug.output("WMSException(" + e.getCode() + "): " + e.getMessage()); - httpResponse.writeHttpResponse("application/vnd.ogc.se_xml", e.getXML()); - } - } - - /** - * @param requestProperties - * @param httpResponse output - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public void handleGetMapRequest(Properties requestProperties, IHttpResponse httpResponse) - throws IOException, MapRequestFormatException, WMSException { - byte[] image = handleGetMapRequest(requestProperties); - if (Debug.debugging("imageserver")) { - Debug.output("OGCMRH: have completed image, size " + image.length); - } - String contentType = getFormatter().getContentType(); - if (contentType == null) { - contentType = HttpConnection.CONTENT_PLAIN; - } - httpResponse.writeHttpResponse(contentType, image); - } - - /** - * @param requestProperties - * @return byte array for image, formatted - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public byte[] handleGetMapRequest(Properties requestProperties) - throws IOException, MapRequestFormatException, WMSException { - GetMapRequestParameters parameters = new GetMapRequestParameters(); - - checkVersion(requestProperties, parameters); - checkExceptions(requestProperties, parameters); - checkFormat(requestProperties, parameters); - setFormatter(parameters.formatter); - - checkBackground(requestProperties, parameters); - Paint bgPaint = parameters.background; - - checkProjectionType(requestProperties, parameters); - checkWidthAndHeight(requestProperties, parameters); - checkBoundingBox(requestProperties, parameters); - Proj projection = createProjection(requestProperties, parameters); - - checkLayersAndStyles(requestProperties, parameters); - - Debug.message("ms", "handleGetMapRequest: createImage layers:" - + parameters.topLayerNames.toString()); - return createImage(projection, parameters.width, parameters.height, parameters.topLayerNames, bgPaint); - } - - public byte[] handleGetLegendGraphicRequest(Properties requestProperties) - throws IOException, MapRequestFormatException, WMSException { - GetLegendGraphicRequestParameters parameters = new GetLegendGraphicRequestParameters(); - - checkVersion(requestProperties, parameters); - checkExceptions(requestProperties, parameters); - checkWidthAndHeight(requestProperties, parameters); - checkFormat(requestProperties, parameters); - setFormatter(parameters.getFormatter()); - checkLayerAndStyle(requestProperties, parameters); - - Debug.message("ms", "handleGetLegendGraphic: createImage layer:" + parameters.layerName); - - IWmsLayer layer = wmsLayerByName.get(parameters.layerName); - - ImageFormatter imageFormatter = formatter.makeClone(); - java.awt.Graphics graphics = createGraphics(imageFormatter, parameters.getWidth(), parameters.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - Legend legend = layer.getLegend(); - if (legend != null) { - legend.setSize(parameters.getWidth(), parameters.getHeight()); - legend.paint(graphics); - } - - byte[] formattedImage = getFormattedImage(imageFormatter, parameters.getWidth(), parameters.getHeight()); - graphics.dispose(); - - return formattedImage; - } - - /** - * @param requestProperties - * @param httpResponse out - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public void handleGetCapabilitiesRequest(Properties requestProperties, - IHttpResponse httpResponse) - throws IOException, MapRequestFormatException, WMSException { - String response = handleGetCapabilitiesRequest(requestProperties); - httpResponse.writeHttpResponse(HttpConnection.CONTENT_XML, response.getBytes("UTF-8")); - } - - /** - * Get the {@link CapabilitiesSupport} object. The - * {@link CapabilitiesSupport} object can be modified and will be kept as - * long as the {@link WmsRequestHandler}. - * - * @return CapabilitiesSupport for capabilities - */ - public CapabilitiesSupport getCapabilities() { - return capabilities; - } - - /** - * @param requestProperties - * @return String describing capabilities - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public String handleGetCapabilitiesRequest(Properties requestProperties) - throws IOException, MapRequestFormatException, WMSException { - - GetCapabilitiesRequestParameters parameters = new GetCapabilitiesRequestParameters(); - checkVersion(requestProperties, parameters); - String format = requestProperties.getProperty(FORMAT); - if (format != null && !format.equals("application/vnd.ogc.wms_xml")) { - throw new WMSException("Invalid FORMAT parameter.", WMSException.INVALIDFORMAT); - } - - Layer[] layers = getLayers(); - for (int i = 0; i < layers.length; i++) { - if (layers[i].getPropertyPrefix() != null) { - getCapabilities().addLayer(wmsLayerFactory.createWmsLayer(layers[i])); - } - } - - try { - return getCapabilities().generateXMLString(parameters.getVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw new WMSException("Unable to compile a response due to server misconfiguration.", WMSException.INTERNALERROR); - } - } - - /** - * @param requestProperties - * @param httpResponse out - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public void handleGetLegendGraphicRequest(Properties requestProperties, - IHttpResponse httpResponse) - throws IOException, MapRequestFormatException, WMSException { - byte[] image = handleGetLegendGraphicRequest(requestProperties); - String contentType = getFormatter().getContentType(); - httpResponse.writeHttpResponse(contentType, image); - } - - /** - *

    - *
  • VERSION - checked - *
  • REQUEST - checked - *
  • EXCEPTIONS - checked - *
  • all from GetMap except VERSION and REQUEST - *
  • QUERY_LAYERS - specific - *
  • INFO_FORMAT - specific - *
  • FEATURE_COUNT - specific - *
  • I,J - specific - *
- * - * @param requestProperties - * @param httpResponse - * @throws IOException - * @throws MapRequestFormatException - * @throws WMSException - */ - public void handleGetFeatureInfoRequest(Properties requestProperties, IHttpResponse httpResponse) - throws IOException, MapRequestFormatException, WMSException { - - GetFeatureInfoRequestParameters parameters = new GetFeatureInfoRequestParameters(); - - checkVersion(requestProperties, parameters); - checkExceptions(requestProperties, parameters); - checkFormat(requestProperties, parameters); - setFormatter(parameters.formatter); - checkBackground(requestProperties, parameters); - checkProjectionType(requestProperties, parameters); - checkWidthAndHeight(requestProperties, parameters); - checkBoundingBox(requestProperties, parameters); - checkFeatureInfoPoint(requestProperties, parameters); - - checkLayersAndStyles(requestProperties, parameters); - checkQueryLayers(requestProperties, parameters); - checkInfoFormat(requestProperties, parameters); - - Proj projection = createProjection(requestProperties, parameters); - - FeatureInfoResponse featureInfoResponse = getFeatureInfoResponse(); - StringBuffer out = new StringBuffer(); - featureInfoResponse.setOutput(parameters.infoFormat, out); - - for (String queryLayerName : parameters.queryLayerNames) { - IWmsLayer wmslayer = wmsLayerByName.get(queryLayerName); - Layer layer = getTopLayerByName(queryLayerName); - - layer.setProjection(new ProjectionEvent(this, projection)); - - LayerFeatureInfoResponse layerResponse = wmslayer.query(parameters.x, parameters.y); - featureInfoResponse.output(layerResponse); - } - - featureInfoResponse.flush(); - - byte[] response = out.toString().getBytes("UTF-8"); - httpResponse.writeHttpResponse(parameters.infoFormat, response); - } - - private FeatureInfoResponse getFeatureInfoResponse() { - return featureInfoResponse; - } - - /** - * TODO: This method covers the equivalent of a base class and returns the - * drawing, which is not rescaled. To them may be a problem. Scaling has - * been locked, because the forms are drawing without the alpha channel, and - * at least it will look odd. - * - * @param formatter - * @param scaledWidth - * @param scaledHeight - * @return byte array of formatted image bytes - */ - @Override - protected byte[] getFormattedImage(ImageFormatter formatter, int scaledWidth, int scaledHeight) { - Debug.message("imageserver", "ImageServer: using full scale image (unscaled)."); - byte[] formattedImage = formatter.getImageBytes(); - return formattedImage; - } - - /** - * @param requestProperties - * @throws WMSException - */ - private void checkRequest(Properties requestProperties) throws WMSException { - String service = requestProperties.getProperty(SERVICE); - String requestType = requestProperties.getProperty(REQUEST); - - boolean getcaps = ((requestType != null) && requestType.equals(GETCAPABILITIES)); - if (getcaps) { - if ((service == null) || !service.equals("WMS")) { - throw new WMSException("Unsupported service name: " + service); - } - } - } - - /** - * @param requestProperties - * @param parameters - * @throws WMSException - */ - private void checkProjectionType(Properties requestProperties, - GetMapRequestParameters parameters) throws WMSException { - String strSRS = requestProperties.getProperty(SRS); - if (strSRS == null) { - // wms 1.3.0 uses CRS parameter instead of SRS - strSRS = requestProperties.getProperty(CRS); - } - if (strSRS == null) { - throw new WMSException("Missing SRS parameter."); - } - - CoordinateReferenceSystem crs = CoordinateReferenceSystem.getForCode(strSRS); - if (crs == null) { - throw new WMSException("Invalid SRS/CRS parameter: " + strSRS, WMSException.INVALIDSRS); - } - parameters.crs = crs; - } - - private void checkWidthAndHeight(Properties requestProperties, - WidthAndHeightRequestParameters parameters) - throws WMSException { - String strWidth = requestProperties.getProperty(WIDTH); - if (strWidth == null) { - throw new WMSException("Missing WIDTH parameter.", WMSException.MISSINGDIMENSIONVALUE); - } - String strHeight = requestProperties.getProperty(HEIGHT); - if (strHeight == null) { - throw new WMSException("Missing HEIGHT parameter.", WMSException.MISSINGDIMENSIONVALUE); - } - - parameters.setWidth(0); - try { - parameters.setWidth(Integer.parseInt(strWidth)); - if (parameters.getWidth() <= 0) { - throw new WMSException("Invalid value encountered while parsing WIDTH parameter."); - } - } catch (NumberFormatException e) { - throw new WMSException("Invalid value encountered while parsing WIDTH parameter."); - } - parameters.setHeight(0); - try { - parameters.setHeight(Integer.parseInt(strHeight)); - if (parameters.getHeight() <= 0) { - throw new WMSException("Invalid value encountered while parsing HEIGHT parameter."); - } - } catch (NumberFormatException e) { - throw new WMSException("Invalid value encountered while parsing HEIGHT parameter."); - } - - } - - /** - * @param requestProperties - * @param parameters - * @throws WMSException - */ - private void checkBoundingBox(Properties requestProperties, GetMapRequestParameters parameters) - throws WMSException { - String strBBox = requestProperties.getProperty(BBOX); - if (strBBox == null) { - throw new WMSException("Missing BBOX parameter.", WMSException.MISSINGDIMENSIONVALUE); - } - String[] arrayBBox = strBBox.split(","); - if (arrayBBox.length != 4) { - throw new WMSException("Invalid BBOX parameter. BBOX must contain exactly 4 values separated with comas.", WMSException.INVALIDDIMENSIONVALUE); - } - - try { - // BBOX is minx, miny, maxx, maxy - double minX = Double.parseDouble(arrayBBox[0]); - double minY = Double.parseDouble(arrayBBox[1]); - double maxX = Double.parseDouble(arrayBBox[2]); - double maxY = Double.parseDouble(arrayBBox[3]); - double medY = ((maxY - minY) / 2d) + minY; - - // This doesn't work over the dateline - double medX = ((maxX - minX) / 2d) + minX; - - // Maybe we need to add a crs capability for figuring out medX if - // the dateline is being crossed. If we had a proper medX it - // wouldn't be a problem, OpenMap can handle creating images that - // cross the dateline. - - // use CRS to convert BBOX to latlon values - CoordinateReferenceSystem crs = parameters.crs; - parameters.bboxLatLonLowerLeft = crs.inverse(minX, minY, parameters.getVersion().usesAxisOrder()); - parameters.bboxLatLonUpperRight = crs.inverse(maxX, maxY, parameters.getVersion().usesAxisOrder()); - parameters.bboxLatLonCenter = crs.inverse(medX, medY, parameters.getVersion().usesAxisOrder()); - - // TODO: use CRS to check value validity? - } catch (NumberFormatException e) { - throw new WMSException("Invalid BBOX parameter. BBOX parameter must be in the form of minx, miny, maxx, maxy" - + " confirming to the selected SRS/CRS.", WMSException.INVALIDDIMENSIONVALUE); - } - } - - private void checkLayersAndStyles(Properties requestProperties, - GetMapRequestParameters parameters) throws WMSException { - String strLayers = requestProperties.getProperty(LAYERS); - if (strLayers == null) { - throw new WMSException("LAYERS not specified.", WMSException.LAYERNOTDEFINED); - } - if (Debug.debugging("imageserver")) { - Debug.output("OGCMRH.checkLayersAndStyles: requested layers >> " + strLayers); - } - String[] layers_in = strLayers.replace('\"', '\0').split(",", -1); - // ... i style - String strStyles = requestProperties.getProperty(STYLES); - String[] styles_in = null; - if (strStyles != null) { - styles_in = strStyles.replace('\"', '\0').split(",", -1); - - // wms-1.1.1 7.2.3.4. "If all layers are - // to be shown using the default style, either the form "STYLES=" or - // "STYLES=,,," is valid." - if (strStyles.length() == 0) { - styles_in = new String[layers_in.length]; - Arrays.fill(styles_in, ""); - } - - if (styles_in.length != layers_in.length) { - throw new WMSException("Number of specified styles does not match the number of specified layers."); - } - } - - parameters.topLayerNames.clear(); - parameters.layerNames.clear(); - - /* - * The order of layers, because the WMS should first render layer at the - * bottom, the second tablet you any longer, etc. imageserver rendering - * in reverse order by the way, make sure the layers are there - */ - for (int i = layers_in.length - 1; i >= 0; i--) { - String layerName = layers_in[i]; - - IWmsLayer wmsLayer = (IWmsLayer) wmsLayerByName.get(layerName); - if (wmsLayer == null) { - throw new WMSException("Unknown layer specified (" + layerName + ").", WMSException.LAYERNOTDEFINED); - } - - if (wmsLayer instanceof IWmsNestedLayer) { - IWmsNestedLayer nestedLayer = (IWmsNestedLayer) wmsLayer; - String topLayerName = nestedLayer.getTopLayer().getWmsName(); - if (!parameters.topLayerNames.contains(topLayerName)) { - parameters.topLayerNames.add(topLayerName); - } - nestedLayer.setIsActive(true); - } else { - if (!parameters.topLayerNames.contains(layerName)) { - parameters.topLayerNames.add(layerName); - } - } - - // apply style to layer - if (styles_in == null) { - wmsLayer.setDefaultStyle(); - } else { - String styleName = styles_in[i]; - if (styleName.length() == 0) { - wmsLayer.setDefaultStyle(); - } else if (wmsLayer.isStyleSupported(styleName)) { - wmsLayer.setStyle(styleName); - } else { - throw new WMSException("Unknown style specified (" + styleName + ").", WMSException.STYLENOTDEFINED); - } - } - - parameters.layerNames.add(layerName); - } - if (parameters.layerNames.isEmpty()) { - throw new WMSException("LAYERS not specified.", WMSException.LAYERNOTDEFINED); - } - } - - private void checkLayerAndStyle(Properties requestProperties, - GetLegendGraphicRequestParameters parameters) - throws WMSException { - - String layerName = requestProperties.getProperty(LAYER); - if (layerName == null) { - throw new WMSException(LAYER + " not specified.", WMSException.LAYERNOTDEFINED); - } - - IWmsLayer wmsLayer = wmsLayerByName.get(layerName); - if (wmsLayer == null) { - throw new WMSException("Unknown layer specified (" + layerName + ").", WMSException.LAYERNOTDEFINED); - } - parameters.layerName = layerName; - - // apply style to layer - String styleName = requestProperties.getProperty(STYLE); - if (styleName == null) { - wmsLayer.setDefaultStyle(); - } else if (styleName.length() == 0) { - wmsLayer.setDefaultStyle(); - } else if (wmsLayer.isStyleSupported(styleName)) { - wmsLayer.setStyle(styleName); - } else { - throw new WMSException("Unknown style specified (" + styleName + ").", WMSException.STYLENOTDEFINED); - } - } - - private void checkQueryLayers(Properties requestProperties, - GetFeatureInfoRequestParameters parameters) throws WMSException { - - String strLayers = requestProperties.getProperty(QUERY_LAYERS); - if (strLayers == null) { - throw new WMSException("QUERY_LAYERS not specified.", WMSException.LAYERNOTDEFINED); - } - if (Debug.debugging("imageserver")) { - Debug.output("OGCMRH.checkQueryLayers: requested layers >> " + strLayers); - } - String[] layers_in = strLayers.replace('\"', '\0').split(",", -1); - - parameters.queryLayerNames.clear(); - - for (int i = 0; i < layers_in.length; i++) { - String layerName = layers_in[i]; - - if (!parameters.layerNames.contains(layerName)) { - throw new WMSException("Layers missing Query Layer " + layerName + ".", WMSException.LAYERNOTDEFINED); - } - - IWmsLayer layer = (IWmsLayer) wmsLayerByName.get(layerName); - if (layer == null) { - throw new WMSException("Could not find layer " + layerName); - } - - if (!layer.isQueryable()) { - throw new WMSException("Layer " + layerName + " is not queryable"); - } - - parameters.queryLayerNames.add(layerName); - } - - } - - /** - * Create and return a Projection object based on the wms request - * parameters. - * - * @param requestProperties - * @param parameters - * @return Proj object for projection - * @throws WMSException - */ - private Proj createProjection(Properties requestProperties, GetMapRequestParameters parameters) - throws WMSException { - - Properties projProps = new Properties(); - projProps.put(ProjectionFactory.CENTER, new LatLonPoint.Double(0f, 0f)); - projProps.setProperty(ProjectionFactory.WIDTH, Integer.toString(parameters.width)); - projProps.setProperty(ProjectionFactory.HEIGHT, Integer.toString(parameters.height)); - - GeoProj projection = parameters.crs.createProjection(projProps); - parameters.crs.prepareProjection(projection); - projection.setScale(projection.getMinScale()); - - LatLonPoint llp1 = parameters.bboxLatLonLowerLeft; - LatLonPoint llp2 = parameters.bboxLatLonUpperRight; - Debug.message("wms", "bbox toLatLon: 1: " + llp1 + ", 2: " + llp2 + ", center: " - + parameters.bboxLatLonCenter); - projection.setCenter(parameters.bboxLatLonCenter); - - int intnewwidth = parameters.width; - int intnewheight = parameters.height; - - float newscale = projection.getScale(llp1, llp2, new Point(0, 0), new Point(intnewwidth, intnewheight)); - projection.setScale(newscale); - - // OGC 01-068r3 (wms 1.1.1) 7.2.3.8. "In the case where the aspect ratio - // of the BBOX and the ratio width/height are different, the WMS shall - // stretch the returned map so that the resulting - // pixels could themselves be rendered in the aspect ratio of the BBOX" - Point2D xyp1 = projection.forward(llp1); - Point2D xyp2 = projection.forward(llp2); - int w = (int) (xyp2.getX() - xyp1.getX()); - int h = (int) (xyp1.getY() - xyp2.getY()); - if (Math.abs(w - parameters.width) > 2 || Math.abs(h - parameters.height) > 2) { - Debug.message("wms", "use aspect ratio fix"); - projection.setWidth(w); - projection.setHeight(h); - projection.setCenter(parameters.bboxLatLonCenter); - float underlyingScale = projection.getScale(llp1, llp2, new Point(0, 0), new Point(w, h)); - projection.setScale(underlyingScale); - AspectRatioProjection p = new AspectRatioProjection(projection, parameters.width, parameters.height); - projection = p; - } - - return projection; - } - - /** - * @param requestProperties - * @param parameters - * @throws WMSException - */ - private void checkFormat(Properties requestProperties, FormatRequestParameter parameters) - throws WMSException { - String format = requestProperties.getProperty(FORMAT); - - // hack to handle WMS clients like ArcGIS 9.2 that are issuing - // GetFeatureInfo without FORMAT parameter - if ((format == null) && (parameters instanceof GetFeatureInfoRequestParameters)) { - parameters.setFormatter(getFormatters().values().iterator().next()); - format = parameters.getFormatter().getContentType(); - } - - if (format == null) { - throw new WMSException("Missing FORMAT parameter.", WMSException.INVALIDFORMAT); - } - - parameters.setFormatter(imageFormatterByContentType.get(format)); - if (parameters.getFormatter() == null) { - throw new WMSException("Invalid FORMAT parameter: " + format, WMSException.INVALIDFORMAT); - } - } - - private void checkVersion(Properties requestProperties, WmsRequestParameters parameters) - throws WMSException { - String versionString = requestProperties.getProperty(VERSION); - if (versionString == null) { - parameters.setVersion(Version.getDefault()); - Debug.message("wms", "missing version string. default to " + parameters.getVersion()); - } else { - if (parameters instanceof GetCapabilitiesRequestParameters) { - parameters.setVersion(Version.getVersionBestMatch(versionString)); - } else { - parameters.setVersion(Version.getVersion(versionString)); - } - if (parameters.getVersion() == null) { - throw new WMSException("Unsupported protocol version: " + versionString); - } - } - } - - private void checkExceptions(Properties requestProperties, WmsRequestParameters parameters) - throws WMSException { - Version version = parameters.getVersion(); - if (version == null) { - return; - } - - String ex = requestProperties.getProperty(EXCEPTIONS); - - // exceptions parameter is optional. ignore if missing. - if (ex == null) { - return; - } - - // ArcGIS uses both 1.1.1 and 1.3.0 type exceptions value with 1.3.0, so - // we should not throw here. - - // TODO: handle optional exceptions value after OpenMap wms get support - // for image base exceptions - } - - private void checkFeatureInfoPoint(Properties requestProperties, - GetFeatureInfoRequestParameters parameters) - throws WMSException { - - parameters.x = -1; - parameters.y = -1; - - try { - parameters.x = Integer.parseInt(requestProperties.getProperty(X)); - } catch (NumberFormatException e) { - throw new WMSException("Invalid X parameter: " + requestProperties.getProperty(X), WMSException.INVALIDPOINT); - } - - try { - parameters.y = Integer.parseInt(requestProperties.getProperty(Y)); - } catch (NumberFormatException e) { - throw new WMSException("Invalid Y parameter: " + requestProperties.getProperty(Y), WMSException.INVALIDPOINT); - } - } - - private void checkInfoFormat(Properties requestProperties, - GetFeatureInfoRequestParameters parameters) throws WMSException { - - String format = requestProperties.getProperty(INFO_FORMAT); - - if (format == null) { - // INFO_FORMAT is optional. default to html, then text - if (getFeatureInfoResponse().getInfoFormats().contains(HttpConnection.CONTENT_HTML)) { - format = HttpConnection.CONTENT_HTML; - } else { - format = HttpConnection.CONTENT_PLAIN; - } - } else if (!getFeatureInfoResponse().getInfoFormats().contains(format)) { - throw new WMSException("Invalid value for " + INFO_FORMAT + ": " + format, WMSException.INVALIDFORMAT); - } - - parameters.infoFormat = format; - } - - /** - * @param requestProperties - * @param parameters - * @throws WMSException - */ - private void checkBackground(Properties requestProperties, GetMapRequestParameters parameters) - throws WMSException { - - String transparent = requestProperties.getProperty(TRANSPARENT); - String bgcolor = requestProperties.getProperty(BGCOLOR); - - if (transparent != null) { - if (transparent.equals("1") || transparent.equalsIgnoreCase("TRUE")) { - parameters.setTransparent(true); - - // if user explicit set TRANSPARENT=TRUE, then skip any BGCOLOR. - // This is not strictly according to wms standard, but as some - // clients (gaia) send BGCOLOR=...&TRANSPARENT=TRUE - bgcolor = null; - - } else if (transparent.equals("0") || transparent.equalsIgnoreCase("FALSE")) { - parameters.setTransparent(false); - } else { - throw new WMSException("Invalid TRANSPARENT format '" + transparent - + "'. Please specify a boolean value (0,1,FALSE,TRUE)"); - } - } - - if (bgcolor != null) { - if (Pattern.matches("0x[0-9a-fA-F]{6}", bgcolor)) { - // for some reason, ColorFactory.parseColor(test) always return - // black.. - parameters.background = Color.decode(bgcolor); - - // wms only allow for 24 bit BGCOLOR without transparency, so if - // there is a BGCOLOR, the image will not be transparent - parameters.setTransparent(false); - } else { - throw new WMSException("Invalid BGCOLOR format. Please specify an hexadecimal" - + " number in the form 0xXXXXXX, where X is a hexadecimal digit (0..9,A-F)"); - } - } - - // hint to the ImageServer - setTransparent(parameters.getTransparent()); - setBackground(parameters.background); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestParameters.java b/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestParameters.java deleted file mode 100644 index ef4517566..000000000 --- a/src/core/src/main/java/com/bbn/openmap/image/wms/WmsRequestParameters.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.bbn.openmap.image.wms; - -abstract class WmsRequestParameters { - - private Version version; - - public void setVersion(Version version) { - this.version = version; - } - - public Version getVersion() { - return version; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/io/BinaryBufferedFile.java b/src/core/src/main/java/com/bbn/openmap/io/BinaryBufferedFile.java deleted file mode 100644 index ffc8b8879..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/BinaryBufferedFile.java +++ /dev/null @@ -1,595 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/BinaryBufferedFile.java,v $ -// $RCSfile: BinaryBufferedFile.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/02/25 23:19:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.EOFException; -import java.io.File; -import java.io.IOException; - -import com.bbn.openmap.util.MoreMath; - -/** - * This class extends the BinaryFile class, doing buffered reads on the - * underlying input file. The buffer size is not modifiable after construction, - * and the buffer management isn't the greatest. - */ -public class BinaryBufferedFile extends BinaryFile { - /** Where reads get buffered */ - private byte buffer[]; - /** Where current reads will come from */ - private int curptr = 0; - /** how many valid bytes are in the buffer */ - private int bytesinbuffer = 0; - /** the byte offset of the first byte in the buffer */ - private long firstbyteoffset = 0; - - /** - * Constructs a BinaryBufferedFile with a File and a buffer size - * - * @param f the input file - * @param buffersize the size to use for buffering reads - * @exception IOException pass-through errors from opening a BinaryFile with - * f - * @see com.bbn.openmap.io.BinaryFile - */ - public BinaryBufferedFile(File f, int buffersize) throws IOException { - super(f); - buffer = new byte[buffersize]; - } - - /** - * Constructs a BinaryBufferedFile with a File - * - * @param f the input file - * @exception IOException pass-through errors from opening a BinaryFile with - * f - * @see com.bbn.openmap.io.BinaryFile - */ - public BinaryBufferedFile(File f) throws IOException { - this(f, 4096); - } - - /** - * Constructs a BinaryBufferedFile with a filename and a buffersize - * - * @param name the name/path of the input file - * @param buffersize the size to use for buffering reads - * @exception IOException pass-through errors from opening a BinaryFile with - * f - * @see com.bbn.openmap.io.BinaryFile - */ - public BinaryBufferedFile(String name, int buffersize) throws IOException { - super(name); - buffer = new byte[buffersize]; - } - - /** - * Constructs a BinaryBufferedFile with a filename - * - * @param name the name/path of the input file - * @exception IOException pass-through errors from opening a BinaryFile with - * f - * @see com.bbn.openmap.io.BinaryFile - */ - public BinaryBufferedFile(String name) throws IOException { - this(name, 4096); - } - - /** - * A simple factory method that lets you try to create something without - * having to really deal with failure. Returns a BinaryFile if successful, - * null if not. - */ - public static BinaryBufferedFile create(String name) { - return create(name, 4096); - } - - /** - * A simple factory method that lets you try to create something without - * having to really deal with failure. Returns a BinaryFile if successful, - * null if not. - */ - public static BinaryBufferedFile create(String name, int buffersize) { - BinaryBufferedFile bf = null; - try { - bf = new BinaryBufferedFile(name, buffersize); - } catch (IOException ioe) { - } - return bf; - } - - /** - * Set the input reader used by the BinaryFile. Make sure it's initialized - * properly. Assumes that the pointer is at the beginning of the file. - */ - public void setInputReader(InputReader reader) { - super.setInputReader(reader); - firstbyteoffset = 0; - bytesinbuffer = 0; - curptr = 0; - } - - /** - * Throws away whatever data is in the buffer, and refills it. - * - * @exception IOException IO errors encountered while refilling the buffer - * @exception EOFException no data was left in the file - */ - private void refillBuffer() throws IOException, EOFException { - firstbyteoffset += (curptr + bytesinbuffer); - int err = super.read(buffer, 0, buffer.length); - curptr = 0; - if (err == -1) - throw new EOFException(); - bytesinbuffer = err; - } - - /** - * Forces the buffer to have at least some minimum number of bytes in it. - * - * @param minlength the minimum number of bytes to have in the buffer - * @exception FormatException couldn't get enough bytes (or IO Exception) - * @exception EOFException couldn't get any bytes - */ - private void assertSize(int minlength) throws FormatException, EOFException { - try { - if (bytesinbuffer < minlength) { - if (curptr != 0) { - firstbyteoffset += curptr; - System.arraycopy(buffer, curptr, buffer, 0, bytesinbuffer); - curptr = 0; - } - int err = super.read(buffer, bytesinbuffer, buffer.length - - bytesinbuffer); - if (err == -1) { - - if (available() <= 0) { - throw new EOFException("BinaryBufferedFile, no bytes at all, trying to read " - + minlength); - } else { - throw new FormatException("BinaryBufferedFile: failed to read " - + minlength - + " bytes, with " - + bytesinbuffer - + " bytes in the buffer and " - + available() - + " bytes available, have read " - + curptr - + " bytes."); - } - } - bytesinbuffer += err; - assertSize(minlength); - } - } catch (EOFException e) { - throw e; - } catch (IOException i) { - throw new FormatException("assertSize IOException: " - + i.getMessage()); - } - } - - public long skipBytes(long n) throws IOException { - if (n < bytesinbuffer) { - bytesinbuffer -= n; - curptr += n; - return n; - } - final long oldbinb = bytesinbuffer; - bytesinbuffer = 0; - curptr = 0; - final int skipcnt = (int) super.skipBytes(n - oldbinb); - firstbyteoffset += skipcnt; - return (oldbinb + skipcnt); - } - - public long getFilePointer() throws IOException { - return (firstbyteoffset + curptr); - } - - public void seek(long pos) throws IOException { - final long relpos = pos - firstbyteoffset; - if ((relpos >= 0) && (relpos < (curptr + bytesinbuffer))) { - final int relcur = (int) relpos - curptr; - if (relcur != 0) { - bytesinbuffer -= relcur; - curptr = (int) relpos; - } // else we're already at the right place - } else { - super.seek(pos); - firstbyteoffset = pos; - bytesinbuffer = 0; - curptr = 0; - } - } - -// public long length() throws IOException { -// return super.length(); -// } - - public long available() throws IOException { - return (length() - firstbyteoffset - curptr); - } - - /** - * Disposes the underlying file input, and releases some resources of the - * class. Calling any other members after this one will return bogus - * results. - * - * @exception IOException IO errors encountered in closing the file - */ - public void dispose() throws IOException { - buffer = null; - super.dispose(); - } - - /** - * Overriding because of bug report of memory leak. - */ - public void close() throws IOException { - super.close(); - firstbyteoffset = 0; - curptr = 0; - bytesinbuffer = 0; - } - - public int read() throws IOException { - try { - if (bytesinbuffer == 0) - refillBuffer(); - } catch (EOFException e) { - return -1; - } - bytesinbuffer--; - return MoreMath.signedToInt(buffer[curptr++]); - } - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read(byte b[], int off, int len) throws IOException { - int numread = 0; - int copy; - if (len < bytesinbuffer) - copy = len; - else - copy = bytesinbuffer; - numread += copy; - bytesinbuffer -= copy; - System.arraycopy(buffer, curptr, b, off, copy); - curptr += copy; - off += copy; - - if (len == copy) - return numread; - - len -= copy; - // was not enough stuff in buffer, do some reads... - - if (len > 512) {// threshold exceeded, read straight into user - // buffer - - final int bcnt = super.read(b, off, len); - firstbyteoffset += (curptr + bcnt); - curptr = 0; - return (numread + bcnt); - - } else { // refill buffer and recurse - - try { - refillBuffer(); - } catch (EOFException e) { - if (numread >= 0) { - // If it's really EOF and nothing was ever read (as opposed - // to getting a little out of the buffer before the EOF), - // return EOF value - numread = -1; - } - return numread; - } - return (numread + read(b, off, len)); - - } - } - - public int read(byte b[]) throws IOException { - return read(b, 0, b.length); - } - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an end-of-file - * encountered after reading some, but now enough, bytes when - * allowless was false - * @exception EOFException Encountered an end-of-file while allowless was - * false, but NO bytes had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) - throws EOFException, FormatException { - - byte foo[] = new byte[howmany]; - int gotsofar = 0; - try { - while (gotsofar < howmany) { - int err = read(foo, gotsofar, howmany - gotsofar); - if (err == -1) { - if (allowless) { - /* - * return a smaller array, so the caller can tell how - * much they really got - */ - byte retval[] = new byte[gotsofar]; - System.arraycopy(foo, 0, retval, 0, gotsofar); - return retval; - } else { // some kind of failure... - if (gotsofar > 0) { - throw new FormatException("EOF while reading"); - } else { - throw new EOFException(); - } - } - } - - gotsofar += err; - } - } catch (IOException i) { - throw new FormatException("IOException reading file: " - + i.getMessage()); - } - return foo; - } - - /** - * Reads and returns a single byte, cast to a char. - * - * @return the byte read from the file, cast to a char - * @exception EOFException the end-of-file has been reached, so no chars - * where available - * @exception FormatException a rethrown IOException - */ - public char readChar() throws EOFException, FormatException { - try { - int retv = read(); - if (retv == -1) { - throw new EOFException("Error in ReadChar, EOF reached"); - } - return (char) retv; - } catch (IOException i) { - throw new FormatException("IOException in ReadChar: " - + i.getMessage()); - } - } - - /** - * Reads and returns a short. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public short readShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - assertSize(2); - curptr += 2; - bytesinbuffer -= 2; - return MoreMath.BuildShort(buffer, curptr - 2, MSBFirst); - } - - /** - * Reads and returns a integer from 2 bytes. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering, and then unsigned to int. - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public int readUnsignedShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.signedToInt(readShort()); - } - - /** - * Reads an array of shorts. - * - * @param vec the array to write the shorts into - * @param offset the first array index to write to - * @param len the number of shorts to read - * @exception EOFException there were fewer bytes than needed in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the array - */ - public void readShortArray(short vec[], int offset, int len) - throws EOFException, FormatException { - - while (len > 0) { - int shortsleft = bytesinbuffer / 2; - if (shortsleft == 0) { - assertSize(2); // force a buffer refill - throws - // exception if it can't - continue; - } - int reallyread = (len < shortsleft) ? len : shortsleft; - if (MSBFirst) { - for (int i = 0; i < reallyread; i++) { - vec[offset++] = MoreMath.BuildShortBE(buffer, curptr); - curptr += 2; - } - } else { - for (int i = 0; i < reallyread; i++) { - vec[offset++] = MoreMath.BuildShortLE(buffer, curptr); - curptr += 2; - } - } - len -= reallyread; - bytesinbuffer -= (2 * reallyread); - } - } - - /** - * Reads and returns a long. - * - * @return the 4 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 4 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the integer - */ - public int readInteger() throws EOFException, FormatException { - // MSBFirst must be set when we are called - assertSize(4); - curptr += 4; - bytesinbuffer -= 4; - return MoreMath.BuildInteger(buffer, curptr - 4, MSBFirst); - } - - /** - * Reads an array of integers. - * - * @exception EOFException there were fewer bytes than needed in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the array - */ - public void readIntegerArray(int vec[], int offset, int len) - throws EOFException, FormatException { - while (len > 0) { - int intsleft = bytesinbuffer / 4; - if (intsleft == 0) { - assertSize(4); // force a buffer refill - continue; - } - int reallyread = (len < intsleft) ? len : intsleft; - int cursor = curptr; - if (MSBFirst) { - for (int i = 0; i < reallyread; i++) { - vec[offset++] = MoreMath.BuildIntegerBE(buffer, cursor); - cursor += 4; - } - } else { - for (int i = 0; i < reallyread; i++) { - vec[offset++] = MoreMath.BuildIntegerLE(buffer, cursor); - cursor += 4; - } - } - len -= reallyread; - bytesinbuffer -= (4 * reallyread); - curptr = cursor; - } - } - - /** - * Reads an array of floats from the input. - * - * @param vec the vector to read into - * @param offset the first float read goes into vec[offset] - * @param len the number of floats to read from the stream - * @exception EOFException not enough bytes were left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the integer - */ - public void readFloatArray(float vec[], int offset, int len) - throws EOFException, FormatException { - while (len > 0) { - int floatsleft = bytesinbuffer / 4; - if (floatsleft == 0) { - assertSize(4); // force a buffer refill - continue; - } - int reallyread = (len < floatsleft) ? len : floatsleft; - int cursor = curptr; - if (MSBFirst) { - for (int i = 0; i < reallyread; i++) { - int floatasint = MoreMath.BuildIntegerBE(buffer, cursor); - vec[offset++] = Float.intBitsToFloat(floatasint); - cursor += 4; - } - } else { - for (int i = 0; i < reallyread; i++) { - int floatasint = MoreMath.BuildIntegerLE(buffer, cursor); - vec[offset++] = Float.intBitsToFloat(floatasint); - cursor += 4; - } - } - len -= reallyread; - bytesinbuffer -= (4 * reallyread); - curptr = cursor; - } - } - - /** - * Reads and returns a long. - * - * @return the 8 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 8 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the long - * @see #read(byte[]) - */ - public long readLong() throws EOFException, FormatException { - assertSize(8); - curptr += 8; - bytesinbuffer -= 8; - return MoreMath.BuildLong(buffer, curptr - 8, MSBFirst); - } - - /** - * Reads length bytes and returns a string composed of the - * bytes cast to chars. - * - * @param length the number of bytes to read into the string - * @return the composed string - * @exception EOFException there were less than length bytes - * left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - */ - public String readFixedLengthString(int length) throws EOFException, - FormatException { - String retstring; - if (length < buffer.length) { - assertSize(length); - retstring = new String(buffer, curptr, length); - curptr += length; - bytesinbuffer -= length; - } else { - byte foo[] = readBytes(length, false); - retstring = new String(foo, 0, length); - } - return retstring; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/BinaryFile.java b/src/core/src/main/java/com/bbn/openmap/io/BinaryFile.java deleted file mode 100644 index 9ea739302..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/BinaryFile.java +++ /dev/null @@ -1,844 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/BinaryFile.java,v $ -// $RCSfile: BinaryFile.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * The BinaryFile is the standard object used to access data files. It acts like - * a RandomAccessFile, but will work on jar file contents and URLs, too. The - * source of the data is isolated through the InputReader interface. - */ -public class BinaryFile { - - private InputReader inputReader = null; - - /** - * The byte order of the underlying file. (true== MSB-First == - * big-endian) - */ - protected boolean MSBFirst = false; - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * default byte-order is LSB first. Reads start at the first byte of the - * file. - * - * @param f the file to be opened for reading - * @exception IOException pass-through errors from opening a - * RandomAccessFile with f - * @see java.io.RandomAccessFile - */ - public BinaryFile(File f) throws IOException { - inputReader = new FileInputReader(f); - } - - /** - * Constructs a new BinaryFile with the specified inputReader as the input. - * - * @param inputReader the input reader to be opened for reading - */ - private BinaryFile(InputReader inputReader) { - this.inputReader = inputReader; - } - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * byte-order is undefined. Reads start at the first byte of the file. This - * constructor looks for the file with the string given, and will call the - * correct constructor as appropriate. If the string represents a file - * available locally, then the BinaryFile will be accessed with a - * FileInputReader using a RandomAccessFile. If it's only available as a - * resource, then a StreamInputReader will be used. The name should be a - * path to a file, or the name of a resource that can be found in the - * classpath, or a URL. - * - * @param name the name of the file to be opened for reading - * @exception IOException pass-through errors from opening the file. - */ - public BinaryFile(String name) throws IOException { - boolean showDebug = false; - if (Debug.debugging("binaryfile")) { - showDebug = true; - } - - if (showDebug) { - Debug.output("BinaryFile: trying to figure out how to handle " + name); - } - - try { - File file = null; - URL url = null; - - if (!Environment.isApplet()) { - file = new File(name); - } - - if (file != null && file.exists()) { - // If the string represents a file, then we want to - // use the RandomAccessFile aspect of the BinaryFile. - setInputReader(new FileInputReader(file)); - } else { - // see JNLP deploy tip here - // http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#ClassLoader_and_Resources - final InputStream resourceStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(name); - if (resourceStream != null) { - if (showDebug) { - Debug.output("BinaryFile: loading " + name + " via getResourceAsStream"); - } - final String urlName = name; - setInputReader(new StreamInputReader() { - { - this.name = urlName; - this.inputStream = resourceStream; - } - - @Override - protected void reopen() throws IOException { - super.reopen(); - inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - } - }); - } else { - // If the getResourceAsStream didn't work, go back to the - // old way of doing things... - // url = ClassLoader.getSystemResource(name); - url = Thread.currentThread().getContextClassLoader().getResource(name); - - // OK, now we want to look around for the file, in the - // classpaths, and as a resource. It may be a file in - // a classpath, available for direct access. - if (url != null) { - - String newname = url.getFile(); - if (showDebug) { - Debug.output("BinaryFile: looking for " + newname); - } - - if (!Environment.isApplet()) { - file = new File(newname); - } - - if (file != null && file.exists()) { - // It's still a file, available directly. - // Access it with the RandomAccessFile - setInputReader(new FileInputReader(file)); - } else { - // Need to get it as a resource. Needs - // special handling if it's coming in a jar - // file. Jar file references have a "!" in - // them - if (!setJarInputReader(newname)) { - if (showDebug) { - Debug.output(" trying as url: " + url); - } - setInputReader(new URLInputReader(url)); - } - - } - - } else if (Environment.isApplet()) { - if (showDebug) { - Debug.output(" As applet, checking codebase..."); - } - // Look in the codebase for applets... - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - - URLClassLoader ucl = URLClassLoader.newInstance(cba); - url = ucl.getResource(name); - - if (url != null) { - setInputReader(new URLInputReader(url)); - } - } - } - - // It's not in the classpath, so try it as a URL. - if (inputReader == null) { - - if (showDebug) { - Debug.output(" lastly, trying as URL: " + name); - } - try { - setInputReader(new URLInputReader(new URL(name))); - } catch (java.security.AccessControlException ace) { - Debug.output("BinaryFile: " + name + " couldn't be accessed."); - throw new IOException("AccessControlException trying to fetch " + name + " as a URL"); - } - } - - } - - if (inputReader == null) { - throw new FileNotFoundException("BinaryFile can't find: " + name); - } - - } catch (IOException ioe) { - throw ioe; - } - } - - /** - * Takes a name of a file, and checks to see if it reflects an entry in a - * jar file. (Check the filename and see if it looks like - * "jarfile!jarfileentry".) If it is, it separates the path, and set the - * inputReader to a JarInputReader and returns true. If not, it returns - * false. - */ - protected boolean setJarInputReader(String name) throws IOException { - - try { - int index = name.indexOf("!"); - if (index != -1) { - - // Used to be this, modified by Erik Sanders to work - // with jdk 1.4 plugin - // String jarFileName = - // name.substring(name.indexOf(":") + 1, index); - - // changed to this... - String jarFileName; - - if (name.startsWith("file:")) { - // java-plugin 1.3 returns local file: strip file: - // from string - jarFileName = name.substring(name.indexOf(":") + 1, index); - } else { - // java-plugin 1.4 returns reference to server, so - // leave http:// part - - // Used to start the substring from 1, but changed - // to 0 thanks to DGK - jarFileName = name.substring(0, index); - } - - // skip !/ " - String jarEntryName = name.substring(index + 2); - if (Debug.debugging("binaryfile")) { - Debug.output(" got: \n" + jarFileName + "\n" + jarEntryName); - } - - // If the jar doesn't exist, should return something - // that indicates this. Should check the performance - // implications of this call, though, at some point. - - // DGK added - File f = new File(jarFileName); - if (f.exists() == false) { - return false; - } - - setInputReader(new JarInputReader(jarFileName, jarEntryName)); - return true; - } - } catch (java.security.AccessControlException ace) { - if (Debug.debugging("binaryfile")) { - Debug.output("BinaryFile.setJarInputFile: AccessControlException for " + name); - } - } - - return false; - } - - /** - * A simple test method to determine if a file or directory, represented by - * a string, can be found by the current Java environment. Uses the same - * tests as BinaryFile constructor for tracking down a file. - * - * @param name A path to a file, a URL, or a path to a jar file entry. - * @return true if the file can be found - */ - public static boolean exists(String name) { - boolean exists = false; - - try { - File file = null; - URL url = null; - - if (!Environment.isApplet()) { - file = new File(name); - } - - if (file != null && file.exists()) { - exists = true; - } else { - - // Could be a binary file stored in a jar file - try { - url = new URL(name); - return true; - } catch (MalformedURLException e) { - // Do nothing, try other url types - url = null; - } - - // url = ClassLoader.getSystemResource(name); - url = Thread.currentThread().getContextClassLoader().getResource(name); - - // OK, now we want to look around for the file, in the - // classpaths, and as a resource. It may be a file in - // a classpath, available for direct access. - if (url != null) { - exists = true; - } else if (Environment.isApplet()) { - if (Debug.debugging("binaryfile")) { - Debug.output(" As applet, checking codebase..."); - } - // Look in the codebase for applets... - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - - URLClassLoader ucl = URLClassLoader.newInstance(cba); - if (ucl.getResource(name) != null) { - exists = true; - - // This has been commented out because the - // AppletDataNugget has been deprecated, and - // is not needed. - - // } else { - // url = AppletDataNugget.findResource(name); - - // if (url != null) { - // exists = true; - // } - } - } - - // It's not in the classpath, so try it as a URL to a - // webserver. - if (!exists && name.indexOf("http:") != -1) { - - try { - InputStream stream = new URL(name).openStream(); - stream.close(); - exists = true; - } catch (java.security.AccessControlException ace) { - exists = false; - } - } - } - - } catch (IOException ioe) { - Debug.message("binaryfile", "BinaryFile.exists() caught IOException"); - exists = false; - } - - if (Debug.debugging("binaryfile")) { - Debug.output("BinaryFile.exists(" + name + ") = " + exists); - } - - return exists; - } - - /** - * Get the source name from the input reader. - */ - public String getName() { - if (inputReader != null) { - return inputReader.getName(); - } - return null; - } - - /** - * Get the inputReader used for accessing the file, for querying purposes. - * Don't use it to get data, or the file pointers may get messed up. - */ - public InputReader getInputReader() { - return inputReader; - } - - /** - * Set the input reader used by the BinaryFile. Make sure it's initialized - * properly. - */ - public void setInputReader(InputReader reader) { - if (Debug.debugging("binaryfile")) { - Debug.output("Setting inputReader"); - } - inputReader = reader; - } - - /** - * Set the byte-ordering used to read shorts, int, etc. - * - * @param msbfirst true= MSB first, false= LSB - * first - */ - public void byteOrder(boolean msbfirst) { - MSBFirst = msbfirst; - } - - /** - * Accessor for the byte ordering used to read multibyte types. - * - * @return byte ordering, true means MSB first. - */ - public boolean byteOrder() { - return MSBFirst; - } - - /** - * Skip over n bytes in the input file - * - * @param n the number of bytes to skip - * @return the actual number of bytes skipped. annoying, isn't it? - * @exception IOException Any IO errors that occur in skipping bytes in the - * underlying file - */ - public long skipBytes(long n) throws IOException { - return inputReader.skipBytes(n); - } - - /** - * Get the index of the next character to be read - * - * @return the index - * @exception IOException Any IO errors that occur in accessing the - * underlying file - */ - public long getFilePointer() throws IOException { - return inputReader.getFilePointer(); - } - - /** - * Set the index of the next character to be read. - * - * @param pos the position to seek to. - * @exception IOException Any IO Errors that occur in seeking the underlying - * file. - */ - public void seek(long pos) throws IOException { - inputReader.seek(pos); - } - - /** - * The length of the InputReader source. - */ - public long length() throws IOException { - return inputReader.length(); - } - - /** - * Return how many bytes left to be read in the file. - * - * @return the number of bytes remaining to be read (counted in bytes) - * @exception IOException Any IO errors encountered in accessing the file - */ - public long available() throws IOException { - return inputReader.available(); - } - - /** - * Closes the underlying file, but with a chance for re-opening if accessed - * again. - * - * @exception IOException Any IO errors encountered in accessing the file - */ - public void close() throws IOException { - if (inputReader != null) { - inputReader.close(); - } - } - - /** - * Closes underlying file, get rid of resources and knowledge of file. To be - * called when you don't need the file any more. - * - * @throws IOException - */ - public void dispose() throws IOException { - close(); - inputReader = null; - } - - /** - * Read from the file. - * - * @return one byte from the file. -1 for EOF - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read() throws IOException { - return inputReader.read(); - } - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read(byte b[], int off, int len) throws IOException { - return inputReader.read(b, off, len); - } - - /** - * Read from the file. - * - * @param b the byte array to read into. Equivalent to - * read(b, 0, b.length) - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - * @see java.io.RandomAccessFile#read(byte[]) - */ - public int read(byte b[]) throws IOException { - return inputReader.read(b); - } - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an end-of-file - * encountered after reading some, but now enough, bytes when - * allowless was false - * @exception EOFException Encountered an end-of-file while allowless was - * false, but NO bytes had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) throws EOFException, FormatException { - - return inputReader.readBytes(howmany, allowless); - } - - /** - * Reads and returns a single byte, cast to a char - * - * @return the byte read from the file, cast to a char - * @exception EOFException the end-of-file has been reached, so no chars - * where available - * @exception FormatException a rethrown IOException - */ - public char readChar() throws EOFException, FormatException { - try { - int retv = inputReader.read(); - - if (retv == -1) { - throw new EOFException("Error in ReadChar, EOF reached"); - } - return (char) retv; - } catch (IOException i) { - throw new FormatException("readChar IOException: " + i.getMessage()); - } - } - - /** - * Read a byte from the file, return an unsigned integer. - * - * @return one byte from the file. -1 for EOF causes EOFException - * @exception IOException Any IO errors encountered in reading from the file - */ - public int readUnsigned() throws IOException, EOFException { - byte b = (byte) read(); - if (b == -1) { - throw new EOFException(); - } - return MoreMath.signedToInt(b); - } - - /** - * Reads and returns a short. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public short readShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.BuildShort(readBytes(2, false), MSBFirst); - } - - /** - * Code for reading shorts that are two-byte integers, high order first, and - * negatives are signed magnitude. Users may have to switch the bytes and - * convert negatives to the complement they use. This can be done by putting - * the low order byte first, then turning off bit 15 (the high order bit), - * and then multiplying by -1." Basically they are encoded as positive - * numbers, but bit 15 is set to 1. - * - * @return 2 bytes merged into a short - * @throws EOFException - * @throws FormatException - */ - public short readShortData() throws EOFException, FormatException { - // read in the two bytes - byte[] bytevec = readBytes(2, false); - - // check for negative values - bit 7 of byte 0 - if (bytevec[0] < 0) { - // mask bit 7 - bytevec[0] &= 0x7f; - // create the short and multiply the result by -1 - return ((short) (MoreMath.BuildShort(bytevec, true) * -1)); - } - return MoreMath.BuildShort(bytevec, true); - } - - /** - * Reads and returns a integer from 2 bytes. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering, and then unsigned to int. - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public int readUnsignedShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.signedToInt(readShort()); - } - - /** - * Reads and returns a long - * - * @return the 4 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 4 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the integer - * @see #read(byte[]) - */ - public int readInteger() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.BuildInteger(readBytes(4, false), MSBFirst); - } - - public void readIntegerArray(int vec[], int offset, int len) throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readInteger(); - } - } - - /** - * Reads and returns a long - * - * @return the 8 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 8 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the long - * @see #read(byte[]) - */ - public long readLong() throws EOFException, FormatException { - return MoreMath.BuildLong(readBytes(8, false), MSBFirst); - } - - /** - * Reads and returns a float - * - * @return the 4 bytes merged into a float, according to the current byte - * ordering - * @exception EOFException there were less than 4 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the float - * @see #read(byte[]) - */ - public float readFloat() throws EOFException, FormatException { - return Float.intBitsToFloat(readInteger()); - } - - public void readFloatArray(float vec[], int offset, int len) throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readFloat(); - } - } - - public void readFloatArray(double vec[], int offset, int len) throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readFloat(); - } - } - - /** - * Reads and returns a double - * - * @return the 8 bytes merged into a double, according to the current byte - * ordering - * @exception EOFException there were less than 8 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public double readDouble() throws EOFException, FormatException { - return Double.longBitsToDouble(readLong()); - } - - /** - * Reads length bytes and returns a string composed of the - * bytes cast to chars - * - * @param length the number of bytes to read into the string - * @return the composed string - * @exception EOFException there were less than length bytes - * left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - */ - public String readFixedLengthString(int length) throws EOFException, FormatException { - - byte foo[] = readBytes(length, false); - return new String(foo, 0, length); - } - - /** - * Read a bytes and throw an InvalidCharException if it doesn't match - * expected - * - * @param expected what the next char is claimed to be - * @exception EOFException there wasn't a byte, so we can't check for a - * match - * @exception InvalidCharException throws when the character read doesn't - * match expected The .c member of the thrown - * exception is the actual char read - * @exception FormatException some other error from reading the file - */ - public void assertChar(char expected) throws EOFException, FormatException { - char c = readChar(); - if (c != expected) { - throw new InvalidCharException("AssertChar: expected " + expected + " got " + c, c); - } - } - - /** - * Reads a string until the specified delimiter or EOF is encountered - * - * @param delim the end-of-string delimiter - * @return the string that was read - * @exception FormatException rethrow of IOExceptions from the read methods - */ - public String readToDelimiter(char delim) throws FormatException { - StringBuffer buildretval = new StringBuffer(); - char tmp; - try { - while ((tmp = readChar()) != delim) - buildretval.append(tmp); - } catch (EOFException e) { - // allowable - } catch (FormatException fe) { - if (buildretval.length() == 0) { - throw fe; - } - } - return buildretval.toString(); - } - - /** - * Makes sure that the file has been closed. - * - * @exception Throwable what it throws. - */ - protected void finalize() throws Throwable { - close(); - } - - /** - * Maintains a list of objects that can be closed so that other files can be - * opened. - */ - private static Vector> closableList = new Vector>(); - - /** - * Add an object that can be closed if needed. Duplicates are allowed. Only - * holds a WeakReference, so that the object can still be garbage-collected. - * - * @param it the object that can be closed - */ - public static synchronized void addClosable(Closable it) { - closableList.addElement(new WeakReference(it)); - } - - /** - * Remove an object from the closable list. - * - * @param it the object to remove - */ - public static synchronized void removeClosable(Closable it) { - for (int i = 0; i < closableList.size(); i++) { - Object o = closableList.elementAt(i).get(); - if ((o == it) || (o == null)) { - closableList.removeElementAt(i); - i--; // in case its in the list more than once - } - } - } - - public static synchronized void closeClosable() { - System.out.println("closeClosable " + closableList.size()); - for (int i = 0; i < closableList.size(); i++) { - Closable c = (Closable) ((WeakReference) closableList.elementAt(i)).get(); - if ((c == null) || !c.close(false)) { - closableList.removeElementAt(i); - i--; - } - } - } - - /** - * Read the {@link BinaryFile} into memory and return a new - * {@link BinaryFile} instance working on that in-memory version of the - * file. - * - * @return BinaryFile object pointing to memory version. - * @throws IOException - */ - public BinaryFile readFully() throws IOException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - - seek(0); - int len; - while (available() > 0) { - len = read(buf); - baos.write(buf, 0, len); - } - - return new BinaryFile(new ByteArrayInputReader(baos.toByteArray())); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/ByteArrayInputReader.java b/src/core/src/main/java/com/bbn/openmap/io/ByteArrayInputReader.java deleted file mode 100644 index a54696337..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/ByteArrayInputReader.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.bbn.openmap.io; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -/** - * An {@link InputReader} working on a byte array - * - * @author halset - */ -public class ByteArrayInputReader extends StreamInputReader { - - private byte[] bytes; - - public ByteArrayInputReader(byte[] bytes) { - this.bytes = bytes; - try { - reopen(); - } catch (IOException e) { - // should not happen - throw new RuntimeException(e); - } - } - - protected void reopen() throws IOException { - super.reopen(); - - inputStream = new ByteArrayInputStream(bytes); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/io/CSVFile.java b/src/core/src/main/java/com/bbn/openmap/io/CSVFile.java deleted file mode 100644 index 067251adc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/CSVFile.java +++ /dev/null @@ -1,207 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/CSVFile.java,v $ -// $RCSfile: CSVFile.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/08/09 18:00:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.util.CSVTokenizer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The CSVFile holds on to the contents of a CSV file. - *

- * NOTE: By default, the numbers that are found in the CSV file are converted to - * Doubles. Use the load(boolean) method to control this, especially if you are - * using the fields later as the key in a Hashtable. - */ -public class CSVFile - implements Iterable> { - - /** The location of the CSV file */ - public URL infoUrl; - - /** The records of the CSV file */ - protected List> infoRecords = null; - - /** The header record, if there is one */ - protected List headerRecord = null; - - /** Whether file has a line of column headers. */ - protected boolean headersExist = true; - - /** - * Don't do anything special, since all defaults are set already - */ - public CSVFile(String name) - throws MalformedURLException { - infoUrl = PropUtils.getResourceOrFileOrURL(name); - } - - /** - * Don't do anything special, since all defaults are set already - */ - public CSVFile(URL url) - throws MalformedURLException { - infoUrl = url; - } - - /** - * Set whether the first line should be considered as headers to each column. - */ - public void setHeadersExist(boolean set) { - headersExist = set; - } - - /** - * Get whether the first line should be considered as headers to each column. - */ - public boolean isHeadersExist() { - return headersExist; - } - - /** - * Reads the numbers and stores them as Doubles. - */ - public void loadData() { - loadData(false); - } - - /** - * Read the data in from the file, with the option of reading the numbers in - * the files as strings. - */ - public void loadData(boolean readNumbersAsStrings) { - BufferedReader streamReader = null; - List> records = new ArrayList>(); - - try { - Object token = null; - boolean header_read = false; - - if (!headersExist) { - header_read = true; - headerRecord = new ArrayList<>(); - } - - // This lets the property be specified as a file name - // even if it's not specified as file:/ in - // the properties file. - URL csvURL = infoUrl; - streamReader = new BufferedReader(new InputStreamReader(csvURL.openStream())); - CSVTokenizer csvt = new CSVTokenizer(streamReader, readNumbersAsStrings); - token = csvt.token(); - while (!csvt.isEOF(token)) { - List rec_line = new ArrayList<>(); - while (!csvt.isNewline(token)) { - rec_line.add(token); - token = csvt.token(); - if (csvt.isEOF(token)) - break; - } - - // Don't add the header record, because we don't care - // about it. - if (header_read) { - records.add(rec_line); - } else if (headersExist) { - headerRecord = rec_line; - header_read = true; - } - - if (Debug.debugging("csv")) { - Debug.output("CSVFile.read: " + rec_line); - } - - token = csvt.token(); - } - - csvt.close(); - } catch (java.io.IOException ioe) { - throw new com.bbn.openmap.util.HandleError(ioe); - } catch (ArrayIndexOutOfBoundsException aioobe) { - throw new com.bbn.openmap.util.HandleError(aioobe); - } catch (ClassCastException cce) { - throw new com.bbn.openmap.util.HandleError(cce); - } catch (NullPointerException npe) { - // Usually gets fired when the URL isn't properly formatted in windows - Debug.error("CSVFile can't open: " + infoUrl + ", check URL notation."); - } - - infoRecords = records; - - if (Debug.debugging("csv")) { - Debug.output("CSVFile: read in " + infoRecords.size() + " records"); - } - } - - /** - * @return the number of records read. - */ - public int getNumberOfRecords() { - int numberOfRecords = 0; - if (infoRecords != null) { - numberOfRecords = infoRecords.size(); - } - return numberOfRecords; - } - - /** - * Return a particular Vector representing the contents of a record line in - * the CSV file. The record choice is picked via the record number given - * -zero is the first one, and the header record, if it exists, does not - * count. - * - * @param recordnumber the number of the record in the csv file. - * @return Vector Vector of contents of record line. - */ - public List getRecord(int recordnumber) { - List list; - try { - list = infoRecords.get(recordnumber); - } catch (ArrayIndexOutOfBoundsException e) { - Debug.error(infoUrl.toString() + ": Don't have information for shape record " + recordnumber); - return null; - } - return list; - } - - /** - * Return an iterator, that can be used to traverse the records of the file. - * - * @return Iterator - */ - public Iterator> iterator() { - if (infoRecords != null) { - return infoRecords.iterator(); - } else { - return new ArrayList>().iterator(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/Closable.java b/src/core/src/main/java/com/bbn/openmap/io/Closable.java deleted file mode 100644 index c0a5aaf4f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/Closable.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/Closable.java,v $ -// $RCSfile: Closable.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -/** - * Objects that implement this interface can be registered with - * BinaryFile to have associated file resources closed when file - * limits are hit. - */ -public interface Closable { - - /** - * close/reclaim associated resources. - * - * @param done true indicates that this is a - * permanent closure. false indicates that - * the object may be used again later, as this is only an - * attempt to temporarily reclaim resources - * @return true indicates the object is still - * usable. false indicates that the object - * is now unusable, and any references to it should be - * released so the garbage collector can do its job. - */ - public boolean close(boolean done); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/FileInputReader.java b/src/core/src/main/java/com/bbn/openmap/io/FileInputReader.java deleted file mode 100644 index e608ac033..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/FileInputReader.java +++ /dev/null @@ -1,307 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/FileInputReader.java,v $ -// $RCSfile: FileInputReader.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/10/24 21:28:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.EOFException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; - -import com.bbn.openmap.util.Debug; - -/** - * This class wraps a java.io.RandomAccessFile to allow us to choose the - * byte-order of the underlying file. It has a user-settable byte-ordering, - * which is then used to properly implement the various multibyte reading - * members. Used for reading local files. - * - * @see java.io.RandomAccessFile - * @see com.bbn.openmap.io.InputReader - * @see com.bbn.openmap.io.BinaryFile - */ -public class FileInputReader implements InputReader { - /** The underlying file input */ - protected RandomAccessFile inputFile = null; - /** - * Needed for input reader interface. - */ - protected String name = null; - /** - * Needed for reopening files that have been closed. - */ - protected String absolutePath = null; - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * default byte-order is LSB first. Reads start at the first byte of the - * file. - * - * @param f the file to be opened for reading - * @exception IOException pass-through errors from opening a - * RandomAccessFile with f - * @see java.io.RandomAccessFile - */ - public FileInputReader(File f) throws IOException { - if (Debug.debugging("binaryfile")) { - Debug.output("FileInputReader created from " + f.getAbsolutePath()); - } - name = f.getName(); - absolutePath = f.getAbsolutePath(); - inputFile = init(f); - } - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * default byte-order is LSB first. Reads start at the first byte of the - * file. - * - * @param f the path to the file to be opened for reading. - * @exception IOException pass-through errors from opening a - * RandomAccessFile with f - * @see java.io.RandomAccessFile - */ - public FileInputReader(String f) throws IOException { - if (Debug.debugging("binaryfile")) { - Debug.output("FileInputReader created from " + f); - } - - File file = new File(f); - name = file.getName(); - absolutePath = file.getAbsolutePath(); - inputFile = init(file); - } - - /** - * Get the file name. - */ - public String getName() { - return name; - } - - /** - * @return the absolute path of the file. - */ - public String getAbsolutePath() { - return absolutePath; - } - - /** - * Initialize the underlying RandomAccessFile. If it's found, but there are - * too many files open, it calls BinaryFile.closeClosable to try to get an - * open file pointer from the system, and then tries again. - * - * @param f a java.io.File - * @throws IOException - */ - protected RandomAccessFile init(File f) throws IOException { - RandomAccessFile inputFile = null; - try { - inputFile = new RandomAccessFile(f, "r"); - } catch (IOException i) { - if (i instanceof FileNotFoundException) { - throw i; - } - - if (f.canRead()) { - BinaryFile.closeClosable(); - inputFile = new RandomAccessFile(f, "r"); - } else { - throw i; - } - } - return inputFile; - } - - /** - * Get the RandomAccessFile, for querying purposes only. Don't use it to get - * data! - */ - public RandomAccessFile getInputFile() { - return inputFile; - } - - public RandomAccessFile checkInputFile() throws IOException { - if (inputFile == null && absolutePath != null) { - inputFile = init(new File(absolutePath)); - } - return inputFile; - } - - /** - * Skip over n bytes in the input file - * - * @param n the number of bytes to skip - * @return the actual number of bytes skipped. annoying, isn't it? - * @exception IOException Any IO errors that occur in skipping bytes in the - * underlying file - */ - public long skipBytes(long n) throws IOException { - return checkInputFile().skipBytes((int) n); - } - - /** - * Get the index of the next character to be read - * - * @return the index - * @exception IOException Any IO errors that occur in accessing the - * underlying file - */ - public long getFilePointer() throws IOException { - return checkInputFile().getFilePointer(); - } - - /** - * Set the index of the next character to be read. - * - * @param pos the position to seek to. - * @exception IOException Any IO Errors that occur in seeking the underlying - * file. - */ - public void seek(long pos) throws IOException { - checkInputFile().seek(pos); - } - - /** - * Local files only. Retrieve the length of the file being accessed. - * - * @return the length of the file (counted in bytes) - * @exception IOException Any IO errors that occur in accessing the - * underlying file. - */ - public long length() throws IOException { - return checkInputFile().length(); - } - - /** - * Return how many bytes left to be read in the file. - * - * @return the number of bytes remaining to be read (counted in bytes) - * @exception IOException Any IO errors encountered in accessing the file - */ - public long available() throws IOException { - return (length() - getFilePointer()); - } - - /** - * Closes the underlying file - * - * @exception IOException Any IO errors encountered in accessing the file - */ - public void close() throws IOException { - if (Debug.debugging("binaryfile")) { - Debug.output("FileInputReader.close()"); - } - try { - if (inputFile != null) - inputFile.close(); - } catch (Exception e) { - e.printStackTrace(); - } - inputFile = null; - } - - /** - * Read from the file. - * - * @return one byte from the file. -1 for EOF - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read() throws IOException { - return checkInputFile().read(); - } - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read(byte b[], int off, int len) throws IOException { - return checkInputFile().read(b, off, len); - } - - /** - * Read from the file. - * - * @param b the byte array to read into. Equivalent to - * read(b, 0, b.length) - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - * @see java.io.RandomAccessFile#read(byte[]) - */ - public int read(byte b[]) throws IOException { - return checkInputFile().read(b); - } - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an end-of-file - * encountered after reading some, but now enough, bytes when - * allowless was false - * @exception EOFException Encountered an end-of-file while allowless was - * false, but NO bytes had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) - throws EOFException, FormatException { - byte foo[] = new byte[howmany]; - int gotsofar = 0; - int err = 0; - try { - RandomAccessFile inputFile = checkInputFile(); - while (gotsofar < howmany) { - err = inputFile.read(foo, gotsofar, howmany - gotsofar); - - if (err == -1) { - if (allowless) { - // return a smaller array, so the caller can tell how - // much - // they really got - byte retval[] = new byte[gotsofar]; - System.arraycopy(foo, 0, retval, 0, gotsofar); - return retval; - } else { // some kind of failure... - if (gotsofar > 0) { - throw new FormatException("EOF while reading data"); - } else { - throw new EOFException(); - } - } - } - gotsofar += err; - } - } catch (IOException i) { - throw new FormatException("FileInputReader: readBytes IOException: " - + i.getMessage()); - } - return foo; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/io/FormatException.java b/src/core/src/main/java/com/bbn/openmap/io/FormatException.java deleted file mode 100644 index 570e6ef79..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/FormatException.java +++ /dev/null @@ -1,114 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/FormatException.java,v $ -// $RCSfile: FormatException.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.PrintStream; -import java.io.PrintWriter; - -/** - * This class is used for exceptions that result from some format - * errors of the data when using the BinaryFile. - */ -public class FormatException extends Exception { - /** nested exception that caused this one */ - final private Throwable rootCause; - - /** - * Construct a FormatException without a detail message. - */ - public FormatException() { - super(); - rootCause = null; - } - - /** - * Construct a FormatException with a detail message. - * - * @param s the detail message - */ - public FormatException(String s) { - super(s); - rootCause = null; - } - - /** - * Construct a FormatException with a detail message and root - * cause. - * - * @param s the detail message - * @param rootCause the root cause (not null) - */ - public FormatException(String s, Throwable rootCause) { - super(s + ": " + rootCause.getLocalizedMessage()); - this.rootCause = rootCause; - } - - /** - * Returns the exception that caused this one. - * - * @return the root exception, or null if there isn't one - */ - public Throwable getRootCause() { - return rootCause; - } - - /** - * Prints a backtrace of this exception and the rootCause (if any) - * to System.err. - */ - public void printStackTrace() { - super.printStackTrace(); - if (rootCause != null) { - System.err.println("With Root Cause:"); - rootCause.printStackTrace(); - } - } - - /** - * Prints a backtrace of this exception and the rootCause (if any) - * to a stream. - * - * @param ps the stream to print to - */ - public void printStackTrace(PrintStream ps) { - super.printStackTrace(ps); - if (rootCause != null) { - ps.println("With Root Cause:"); - rootCause.printStackTrace(ps); - } - } - - /** - * Prints a backtrace of this exception and the rootCause (if any) - * to a writer. - * - * @param pw the writer to print to - */ - public void printStackTrace(PrintWriter pw) { - super.printStackTrace(pw); - if (rootCause != null) { - pw.println("With Root Cause:"); - rootCause.printStackTrace(pw); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/InputReader.java b/src/core/src/main/java/com/bbn/openmap/io/InputReader.java deleted file mode 100644 index 01787d50f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/InputReader.java +++ /dev/null @@ -1,146 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/InputReader.java,v $ -// $RCSfile: InputReader.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/06/21 21:39:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.EOFException; -import java.io.IOException; - -/** - * The InputReader is an interface that isolates the data file source - * type from the BinaryFile. Represents an InputStream setup, and - * basic read functions. - */ -public interface InputReader { - - /** - * Get the name of the source. - */ - public String getName(); - - /** - * Skip over n bytes in the input file - * - * @param n the number of bytes to skip - * @return the actual number of bytes skipped. annoying, isn't it? - * @exception IOException Any IO errors that occur in skipping - * bytes in the underlying file - */ - public long skipBytes(long n) throws IOException; - - /** - * Get the index of the next character to be read - * - * @return the index - * @exception IOException Any IO errors that occur in accessing - * the underlying file - */ - public long getFilePointer() throws IOException; - - /** - * Set the index of the next character to be read. - * - * @param pos the position to seek to. - * @exception IOException Any IO Errors that occur in seeking the - * underlying file. - */ - public void seek(long pos) throws IOException; - - /** - * Return the total byte length of the source. May not be accurate - * for StreamInputReaders. - * - * @return the number of bytes remaining to be read (counted in - * bytes) - * @exception IOException Any IO errors encountered in accessing - * the file - */ - public long length() throws IOException; - - /** - * Return how many bytes left to be read in the file. - * - * @return the number of bytes remaining to be read (counted in - * bytes) - * @exception IOException Any IO errors encountered in accessing - * the file - */ - public long available() throws IOException; - - /** - * Closes the underlying file. - * - * @exception IOException Any IO errors encountered in accessing - * the file - */ - public void close() throws IOException; - - /** - * Read from the file. - * - * @return one byte from the file. -1 for EOF - * @exception IOException Any IO errors encountered in reading - * from the file - */ - public int read() throws IOException; - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading - * from the file - */ - public int read(byte b[], int off, int len) throws IOException; - - /** - * Read from the file. - * - * @param b the byte array to read into. Equivalent to - * read(b, 0, b.length) - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading - * from the file - * @see java.io.RandomAccessFile#read(byte[]) - */ - public int read(byte b[]) throws IOException; - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an - * end-of-file encountered after reading some, but now - * enough, bytes when allowless was false - * @exception EOFException Encountered an end-of-file while - * allowless was false, but NO bytes - * had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) - throws EOFException, FormatException; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/InputStreamSplitter.java b/src/core/src/main/java/com/bbn/openmap/io/InputStreamSplitter.java deleted file mode 100644 index f6c3fcec8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/InputStreamSplitter.java +++ /dev/null @@ -1,137 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/InputStreamSplitter.java,v $ -// $RCSfile: InputStreamSplitter.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/06/21 21:39:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * The InputStreamSplitter is a - * FilterInputStream that reads and returns data from - * an input stream, while also sending the data to an output stream. - * Thus, the InputStreamSplitter can provide a handy - * sniffing/logging mechanism. In addition, the output stream could be - * coupled with a PipedInputStream to create two input - * sources out of a single source. - */ -public class InputStreamSplitter extends FilterInputStream { - - /** - * The OutputStream to route the data to. - */ - protected OutputStream out; - - /** - * Creates an InputStreamSplitter. - * - * @param in the underlying input stream - * @param out the output stream - */ - public InputStreamSplitter(InputStream in, OutputStream out) { - super(in); - this.out = out; - } - - /** - * Reads the next byte of data from the input stream and writes it - * to the output stream. The value byte is returned as an - * int in the range 0 to - * 255. If no byte is available because the end of - * the stream has been reached, the value -1 is - * returned. This method blocks until input data is available, the - * end of the stream is detected, or an exception is thrown. - * - * @return the next byte of data, or -1 if the end - * of the stream is reached. - * @exception IOException if an I/O error occurs. - */ - public int read() throws IOException { - final int i = super.read(); - if (i >= 0) - out.write(i); - return i; - } - - /** - * Reads up to b.length bytes of data from this - * input stream into an array of bytes, and writes those bytes to - * the output stream. This method blocks until some input is - * available. - * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the - * end of the stream has been reached. - * @exception IOException if an I/O error occurs. - * @see #read(byte[], int, int) - */ - public int read(byte b[]) throws IOException { - final int i = super.read(b); - if (i >= 0) - out.write(b, 0, i); - return i; - } - - /** - * Reads up to len bytes of data from this input - * stream into an array of bytes, and writes those bytes to the - * output stream. This method blocks until some input is - * available. - * - * @param b the buffer into which the data is read. - * @param off the start offset of the data. - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the - * end of the stream has been reached. - * @exception IOException if an I/O error occurs. - */ - public int read(byte b[], int off, int len) throws IOException { - final int i = super.read(b, off, len); - if (i >= 0) - out.write(b, off, i); - return i; - } - - /** - * Closes the input and output streams and releases any system - * resources associated with those streams. - * - * @exception IOException if an I/O error occurs. - */ - public void close() throws IOException { - super.close(); - out.close(); - } - - /** - * Flushes the output stream. - * - * @exception IOException if an I/O error occurs. - */ - public void flush() throws IOException { - out.flush(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/InvalidCharException.java b/src/core/src/main/java/com/bbn/openmap/io/InvalidCharException.java deleted file mode 100644 index 33668c9a8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/InvalidCharException.java +++ /dev/null @@ -1,53 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/InvalidCharException.java,v $ -// $RCSfile: InvalidCharException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -/** - * An invalid character occurred on in input stream. - */ -public class InvalidCharException extends FormatException { - - /** the invalid character that we found */ - final public char c; - - /** - * Construct an object with no detail message - * - * @param val the character encountered - */ - public InvalidCharException(char val) { - super(); - c = val; - } - - /** - * Construct an object with a detail message - * - * @param s the detail message - * @param val the character encountered - */ - public InvalidCharException(String s, char val) { - super(s); - c = val; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/JarInputReader.java b/src/core/src/main/java/com/bbn/openmap/io/JarInputReader.java deleted file mode 100644 index 9010c9e5e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/JarInputReader.java +++ /dev/null @@ -1,96 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/JarInputReader.java,v $ -// $RCSfile: JarInputReader.java,v $ -// $Revision: 1.5 $ -// $Date: 2007/06/21 21:39:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.IOException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import com.bbn.openmap.util.Debug; - -/** - * An InputReader to handle entries in a Jar file. - */ -public class JarInputReader extends StreamInputReader { - - /** Where to go to hook up with a resource. */ - protected URL inputURL = null; - - protected JarFile jarFile = null; - protected String jarFileName = null; - protected String jarEntryName = null; - - /** - * Create a JarInputReader win the path to a jar file, and the - * entry name. The entry name should be a path to the entry from - * the internal root of the jar file. - */ - public JarInputReader(String jarFilePath, String jarEntryName) - throws IOException { - - if (Debug.debugging("binaryfile")) { - Debug.output("JarInputReader created for " + jarEntryName + " in " - + jarFilePath); - } - this.jarFileName = jarFilePath; - this.jarEntryName = jarEntryName; - reopen(); - name = jarFilePath + "!" + jarEntryName; - } - - /** - * Reset the InputStream to the beginning, by closing the current - * connection and reopening it. - */ - public void reopen() throws IOException { - super.reopen(); - - Debug.message("binaryfile", "JarInputReader: reopening jarFile " - + jarFileName); - if (jarFile != null) - jarFile.close(); - jarFile = null; - - jarFile = new JarFile(URLDecoder.decode(jarFileName, "UTF-8")); - JarEntry entry = jarFile.getJarEntry(jarEntryName); - inputStream = jarFile.getInputStream(entry); - if (inputStream == null) { - Debug.error("JarInputReader: Problem getting input stream for " - + jarEntryName + " in " + jarFileName); - } - } - - /** - * Closes the underlying file - * - * @exception IOException Any IO errors encountered in accessing - * the file - */ - public void close() throws IOException { - jarFile.close(); - super.close(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/StreamInputReader.java b/src/core/src/main/java/com/bbn/openmap/io/StreamInputReader.java deleted file mode 100644 index 32334e858..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/StreamInputReader.java +++ /dev/null @@ -1,360 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/StreamInputReader.java,v $ -// $RCSfile: StreamInputReader.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/06/21 21:39:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -import com.bbn.openmap.util.Debug; - -/** - * An Abstract InputReader to handle reading data from streams, where seeking to - * a place in the file in front of the current pointer involves closing the - * stream, and re-seeking from the beginning. - * - * @see com.bbn.openmap.io.InputReader - * @see com.bbn.openmap.io.BinaryFile - */ -public abstract class StreamInputReader - implements InputReader { - - /** - * The underlying data input stream, for resource files. Is used if the - * inputFile is null. - */ - protected InputStream inputStream = null; - - /** - * Keep track of how many bytes have been read when using the DataInputStream - * to read the file. - */ - protected long inputStreamCount = 0; - - /** - * The source name. - */ - protected String name = null; - - public String getName() { - return name; - } - - /** - * Add the number of bytes to the inputStreamCount. - * - * @return number of bytes added in this call, to pass along to anything else - * that will be interested. - */ - protected int count(int add) { - inputStreamCount += add; - return (int) add; - } - - /** - * Reset the DataInputStream to the beginning, by closing the current - * connection and reopening it. The StreamInputReader method simply closes - * the input stream and resets the input stream count, so the implementation - * of this class needs to reopen the stream at the beginning of the source - * file. - */ - protected void reopen() - throws IOException { - if (inputStream != null) { - Debug.message("binaryfile", "StreamInputReader: Closing inputStream"); - inputStream.close(); - } - - inputStreamCount = 0; - } - - /** - * Skip over n bytes in the input file - * - * @param n the number of bytes to skip - * @return the actual number of bytes skipped. annoying, isn't it? - * @exception IOException Any IO errors that occur in skipping bytes in the - * underlying file - */ - public long skipBytes(long n) - throws IOException { - - long count = 0; - long gotsofar = 0; - - if (inputStream == null) { - reopen(); - - if (inputStream == null) { - reopen(); - throw new IOException("Stream closed, can't be reopened"); - } - } - - while (count < n) { - gotsofar = inputStream.skip(n - count); - if (gotsofar == 0) { // added from david marklund - Debug.error("StreamInputReader can't skip " + n + " bytes as instructed"); - break; - } - count += gotsofar; - } - - count((int) count); - return count; - } - - /** - * Get the index of the next character to be read - * - * @return the index - * @exception IOException Any IO errors that occur in accessing the - * underlying file - */ - public long getFilePointer() - throws IOException { - return inputStreamCount; - } - - /** - * Set the index of the next character to be read. - * - * @param pos the position to seek to. - * @exception IOException Any IO Errors that occur in seeking the underlying - * file. - */ - public void seek(long pos) - throws IOException { - boolean seekComments = false; - long skipped; - if (Debug.debugging("binaryfileseek")) { - seekComments = true; - } - - long curPosition = inputStreamCount; - if (pos >= curPosition) { - if (seekComments) { - Debug.output("StreamInputReader - seeking to " + pos + " from " + curPosition); - } - - skipped = skipBytes(pos - curPosition); - - if (seekComments) { - Debug.output(" now at: " + inputStreamCount + ", having skipped " + skipped); - } - } else { - if (seekComments) { - Debug.output("StreamInputReader - having to start over for seek - " + pos + " from " + curPosition); - } - reopen(); - if (seekComments) - Debug.output(" skipping to: " + pos); - skipped = skipBytes(pos); - if (seekComments) { - Debug.output(" now at: " + inputStreamCount + ", having skipped " + skipped); - } - } - } - - /** - * Return how many bytes the input stream thinks make up the file. This is - * calculated by adding the number of bytes read to the number of bytes - * available. May not be reliable. - * - * @return the number of bytes remaining to be read (counted in bytes) - * @exception IOException Any IO errors encountered in accessing the file - */ - public long length() - throws IOException { - - if (inputStream == null) { - throw new IOException("Stream closed"); - } - - return inputStreamCount + inputStream.available(); - } - - /** - * Return how many bytes the input stream thinks are available. - * - * @return the number of bytes remaining to be read (counted in bytes) - * @exception IOException Any IO errors encountered in accessing the file - */ - public long available() - throws IOException { - - if (inputStream == null) { - throw new IOException("Stream closed"); - } - - return inputStream.available(); - } - - /** - * Closes the underlying file - * - * @exception IOException Any IO errors encountered in accessing the file - */ - public void close() - throws IOException { - try { - Debug.message("binaryfile", "StreamInputReader.close()"); - - // From the Sun Network Programming Guide for 1.4, if - // there are - // problems with Connection reset by peer, then you should - // do this before closing the stream, giving all the data - // a chance to be read. Haven't decided to do this by - // default, but put it in here for easy access if people - // decided they need it. - if (Debug.debugging("connection_problems")) { - Thread.sleep(1000); - } - - if (inputStream != null) - inputStream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - inputStream = null; - } - - /** - * Read from the file. - * - * @return one byte from the file. -1 for EOF - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read() - throws IOException { - - if (inputStream == null) { - reopen(); - } - - count(1); - return inputStream.read(); - } - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read(byte b[], int off, int len) - throws IOException { - - if (inputStream == null) { - throw new IOException("Stream closed"); - } - - int gotsofar = 0; - while (gotsofar < len) { - int read = inputStream.read(b, off + gotsofar, len - gotsofar); - if (read == -1) { - if (gotsofar > 0) { - // Hit the EOF in the middle of the loop. - count(gotsofar); // bug fix from Carsten - return gotsofar; - } else { - return read; - } - } else { - gotsofar += read; - } - } - - count(gotsofar); - return gotsofar; - } - - /** - * Read from the file. - * - * @param b the byte array to read into. Equivalent to - * read(b, 0, b.length) - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - * @see java.io.RandomAccessFile#read(byte[]) - */ - public int read(byte b[]) - throws IOException { - if (inputStream == null) { - throw new IOException("Stream closed"); - } - return inputStream.read(b, 0, b.length); - } - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an end-of-file - * encountered after reading some, but now enough, bytes when - * allowless was false - * @exception EOFException Encountered an end-of-file while allowless was - * false, but NO bytes had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) - throws EOFException, FormatException { - - byte foo[] = new byte[howmany]; - int gotsofar = 0; - int err = 0; - try { - while (gotsofar < howmany) { - err = inputStream.read(foo, gotsofar, howmany - gotsofar); - - if (err == -1) { - if (allowless) { - // return a smaller array, so the caller can - // tell how much - // they really got - byte retval[] = new byte[gotsofar]; - System.arraycopy(foo, 0, retval, 0, gotsofar); - count(gotsofar); - return retval; - } else { // some kind of failure... - if (gotsofar > 0) { - throw new FormatException("StreamInputReader: EOF while reading data"); - } else { - throw new EOFException(); - } - } - } - gotsofar += err; - } - } catch (IOException i) { - throw new FormatException("StreamInputReader: readBytes IOException: " + i.getMessage()); - } - count(howmany); - return foo; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/URLInputReader.java b/src/core/src/main/java/com/bbn/openmap/io/URLInputReader.java deleted file mode 100644 index d2a636cfc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/URLInputReader.java +++ /dev/null @@ -1,58 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/URLInputReader.java,v $ -// $RCSfile: URLInputReader.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/06/21 21:39:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.IOException; -import java.net.URL; - -import com.bbn.openmap.util.Debug; - -/** - * An InputReader to handle files at a URL. - */ -public class URLInputReader extends StreamInputReader { - - /** Where to go to hook up with a resource. */ - protected URL inputURL = null; - - /** - * Construct a URLInputReader from a URL. - */ - public URLInputReader(java.net.URL url) throws IOException { - if (Debug.debugging("binaryfile")) { - Debug.output("URLInputReader created from URL "); - } - inputURL = url; - reopen(); - name = url.getProtocol() + "://" + url.getHost() + url.getFile(); - } - - /** - * Reset the InputStream to the beginning, by closing the current - * connection and reopening it. - */ - public void reopen() throws IOException { - super.reopen(); - inputStream = inputURL.openStream(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/io/package.html b/src/core/src/main/java/com/bbn/openmap/io/package.html deleted file mode 100644 index 2a9323d1f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/io/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package provides classes that let you read data from local -files, URLs and resources, using the BinaryFile and BinaryBufferedFile. - diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/Camera.java b/src/core/src/main/java/com/bbn/openmap/j3d/Camera.java deleted file mode 100644 index babd95f39..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/Camera.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 1999 Justin Couch Java Source Raw J3D - * Tutorial Version History Date Version Programmer - * ---------- ------- ------------------------------------------ - * 01/08/1998 1.0.0 Justin Couch - */ - -package com.bbn.openmap.j3d; - -// Standard imports -import javax.media.j3d.Canvas3D; -import javax.media.j3d.DirectionalLight; -import javax.media.j3d.Group; -import javax.media.j3d.Light; -import javax.media.j3d.Node; -import javax.media.j3d.PhysicalBody; -import javax.media.j3d.PhysicalEnvironment; -import javax.media.j3d.Transform3D; -import javax.media.j3d.TransformGroup; -import javax.media.j3d.View; -import javax.media.j3d.ViewPlatform; -import javax.vecmath.AxisAngle4f; -import javax.vecmath.Vector3f; - -/** - * This Camera class was modified from Justin Couch's - * http://www.j3d.org tutorial examples. Test class for showing the - * use of a View and ViewPlatform - *

- * - * Basic view consists of the standard placement. - * - * @author Justin Couch - * @author dietrick - */ -public class Camera implements OM3DConstants { - - private Group hud_group; - private TransformGroup root_tx_grp; - private Transform3D location; - private ViewPlatform platform; - private View view; - private DirectionalLight headlight; - - private PhysicalBody body; - private PhysicalEnvironment env; - - public Camera() { - hud_group = new Group(); - hud_group.setCapability(Group.ALLOW_CHILDREN_EXTEND); - - platform = new ViewPlatform(); - location = new Transform3D(); - - root_tx_grp = new TransformGroup(); - root_tx_grp.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); - root_tx_grp.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); - root_tx_grp.setTransform(location); - root_tx_grp.addChild(platform); - root_tx_grp.addChild(hud_group); - - // now create the headlight - headlight = new DirectionalLight(); - headlight.setCapability(Light.ALLOW_STATE_WRITE); - headlight.setColor(White); - headlight.setInfluencingBounds(LIGHT_BOUNDS); - root_tx_grp.addChild(headlight); - - body = new PhysicalBody(); - env = new PhysicalEnvironment(); - - view = new View(); - view.setBackClipDistance(BACK_CLIP_DISTANCE); - view.setPhysicalBody(body); - view.setPhysicalEnvironment(env); - view.attachViewPlatform(platform); - } - - /** - * Set the canvas that this camera is using - * - * @param canvas The canvas that is to be used for this camera - */ - public void setCanvas(Canvas3D canvas) { - view.addCanvas3D(canvas); - } - - /** - * Set the location of the camera. This is the location of the - * center of the camera relative to whatever is used as its root - * group node. - * - * @param loc The location of the camera - */ - public void setLocation(Vector3f loc) { - location.setTranslation(loc); - root_tx_grp.setTransform(location); - } - - /** - * Set the orientation of the camera. - * - * @param angle The orientation of the camera - */ - public void setOrientation(AxisAngle4f angle) { - location.setRotation(angle); - root_tx_grp.setTransform(location); - } - - /** - * Add some goemetry to the HUD area. This geometry must come - * complete with its own parent transform to offset the object by - * the appropriate amount. The camera does not do any auto-offsets - * of geometry. - * - * @param geom The geometry to add - */ - public void addHUDObject(Node geom) { - hud_group.addChild(geom); - } - - /** - * Enable the headlight that is attached to the camera. - * - * @param enable True if the light is to be turned on - */ - public void setHeadLight(boolean enable) { - headlight.setEnable(enable); - } - - /** - * Get the J3D node that is used to represent the camera - * - * @return The root TransformGroup of the camera - */ - public Node getNode() { - return root_tx_grp; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/ControlledManager.java b/src/core/src/main/java/com/bbn/openmap/j3d/ControlledManager.java deleted file mode 100644 index 6d532b988..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/ControlledManager.java +++ /dev/null @@ -1,106 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/ControlledManager.java,v $ -// $RCSfile: ControlledManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/11 21:34:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.BorderLayout; - -import javax.media.j3d.Background; -import javax.media.j3d.Behavior; -import javax.media.j3d.TransformGroup; -import javax.swing.JFrame; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.proj.Projection; - -/** - * A 3D manager where the eye position is controlled by an outside - * object. The keys should still work to control the view orientation, - * just not position. (I don't think they do, yet). - * - * @author dietrick - */ -public class ControlledManager extends MapContentManager { - - /** - * The object controlling the viewer's position. - */ - protected NavBehaviorProvider controller; - - public ControlledManager(MapHandler mapHandler, NavBehaviorProvider cont, - int contentMask) { - this(mapHandler, cont, new Background(0f, 0f, 0f), contentMask); - } - - public ControlledManager(MapHandler mapHandler, NavBehaviorProvider cont, - Background background, int contentMask) { - super(); - - // background.setCapability(Background.ALLOW_APPLICATION_BOUNDS_WRITE); - // background.setCapability(Background.ALLOW_APPLICATION_BOUNDS_READ); - // background.setCapability(Background.ALLOW_COLOR_READ); - // background.setCapability(Background.ALLOW_COLOR_WRITE); - - setController(cont); - this.setSceneBackground(background); - addMapContent(mapHandler, objRootBG, contentMask); - - // Important!! Compiles the universe - ((UniverseManager) universe).makeLive(); - } - - protected void setController(NavBehaviorProvider cont) { - controller = cont; - } - - public NavBehaviorProvider getController() { - return controller; - } - - public Behavior getMotionBehavior(TransformGroup cameraTransform, - Projection projection) { - - Behavior behavior = null; - if (controller != null) { - behavior = controller.setViewingPlatformBehavior(cameraTransform, - projection, - scaleFactor); - } - return behavior; - } - - public static JFrame getFrame(String title, int width, int height, - MapHandler mapHandler, - NavBehaviorProvider controller, - Background background, int contentMask) { - - JFrame frame = new JFrame(title); - frame.setSize(width, height); - frame.getContentPane().setLayout(new BorderLayout()); - ControlledManager c3d = new ControlledManager(mapHandler, controller, background, contentMask); - c3d.compileUniverse(); - frame.getContentPane().add("Center", c3d.getCanvas()); - return frame; - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/J3DGeo.java b/src/core/src/main/java/com/bbn/openmap/j3d/J3DGeo.java deleted file mode 100644 index cbc4c9092..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/J3DGeo.java +++ /dev/null @@ -1,147 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: J3DGeo.java,v $ -//$Revision: 1.2 $ -//$Date: 2007/01/30 21:25:32 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.j3d; - -import javax.vecmath.Point3d; - -import com.bbn.openmap.geo.Geo; - -/** - * This class is basically a Geo class, with constructors and accessors that - * know that J3D space is aligned differently. In J3D, the x axis increases to - * the right, y axis increases up, and z increases out of the screen to the - * viewer. In Geo, x is the same, y is positive into the screen, and z increases - * up. J3DGeo deals with external components thinking of x, y, z in J3D space, - * while internally representing things in normal Geo orientation. - * - * @author dietrick - */ -public class J3DGeo extends Geo { - - public J3DGeo(double lat, double lon) { - super(lat, lon); - } - - public J3DGeo(double lat, double lon, boolean isDegrees) { - super(lat, lon, isDegrees); - } - - public J3DGeo(double lat, double lon, boolean isDegrees, double length) { - super(lat, lon, isDegrees); - setLength(length); - } - - public J3DGeo(double x, double y, double z) { - super(x, -z, y); - } - - public J3DGeo(Geo geo) { - super(geo); - } - - public J3DGeo(Point3d pt) { - this(pt.x, pt.y, pt.z); - } - - public void initialize(double x, double y, double z) { - super.initialize(x, -z, y); - } - - /** - * Reader for x in J3D axis representation (positive going to right of screen). - * @return - */ - public double getX() { - return super.x(); - } - - /** - * Reader for y in J3D axis representation (positive going to top of screen). - * @return - */ - public double getY() { - return super.z(); - } - - /** - * Reader for z in J3D axis representation (positive coming out of screen). - * @return - */ - public double getZ() { - return -super.y(); - } - - /** - * Create a J3DGeo with x, y, and z relative to Geo axis. - * @param superX - * @param superY - * @param superZ - * @return - */ - protected J3DGeo create(double superX, double superY, double superZ) { -// return new J3DGeo(new Geo(superX, superY, superZ)); - return new J3DGeo(superX, superZ, -superY); - } - - /** Returns this + b. */ - public Geo add(Geo b) { - return create(this.x() + b.x(), this.y() + b.y(), this.z() + b.z()); - } - - /** Returns this - b. */ - public Geo subtract(Geo b) { - return create(this.x() - b.x(), this.y() - b.y(), this.z() - b.z()); - } - - /** Multiply this by s. * */ - public Geo scale(double s) { - return create(this.x() * s, this.y() * s, this.z() * s); - } - - /** Vector cross product. */ - public Geo cross(Geo b) { - return create(this.y() * b.z() - this.z() * b.y(), this.z() * b.x() - - this.x() * b.z(), this.x() * b.y() - this.y() * b.x()); - } - - /** Eqvivalent to this.cross(b).normalize(). */ - public Geo crossNormalize(Geo b) { - double x = this.y() * b.z() - this.z() * b.y(); - double y = this.z() * b.x() - this.x() * b.z(); - double z = this.x() * b.y() - this.y() * b.x(); - double L = Math.sqrt(x * x + y * y + z * z); - return create(x / L, y / L, z / L); - } - - public Point3d getPoint3d() { - return getPoint3d(new Point3d()); - } - - public Point3d getPoint3d(Point3d pt) { - pt.set(getX(), getY(), getZ()); - return pt; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/LayerMapContent.java b/src/core/src/main/java/com/bbn/openmap/j3d/LayerMapContent.java deleted file mode 100644 index d0a31ac98..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/LayerMapContent.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * ********************************************************************** - * - * BBN Corporation - * 10 Moulton St. - * Cambridge, MA 02138 - * (617) 873-2000 - * - * Copyright (C) 2002 - * This software is subject to copyright protection under the laws of - * the United States and other countries. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/LayerMapContent.java,v $ - * $RCSfile: LayerMapContent.java,v $ - * $Revision: 1.7 $ - * $Date: 2005/08/11 21:34:55 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ -package com.bbn.openmap.j3d; - -import java.awt.Color; -import java.util.Iterator; - -import javax.media.j3d.Group; -import javax.media.j3d.OrderedGroup; -import javax.media.j3d.Shape3D; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.ScaleFilterLayer; -import com.bbn.openmap.omGraphics.OMGraphicAdapter; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * Simple 3D world creation from OpenMap Layers that are OMGraphicHandlerLayers. - * The Layer objects are not given height. Although you can control that with - * the LayerSeparation variable. This LayerMapContent will also create a simple - * plane colored the background color of the map. - * - * @author dietrick - */ -public class LayerMapContent extends OrderedGroup { - - /** - * The default amount of separation to place between layer objects (.1), - * just to keep them from merging together. - */ - public final static double DEFAULT_LAYER_SEPARATION = .1; - - /** - * The height spacer that is being placed between layers, in straight 3D - * coordinate space. - */ - protected double layerSeparation = DEFAULT_LAYER_SEPARATION; - - /** - * Constructor that creates a Group from the OMGraphicHandler layers that - * are part of the map. - * - * @param mapHandler MapHandler to use to get OMGraphicHandlerLayers. - */ - public LayerMapContent(MapHandler mapHandler) { - super(); - createMap(mapHandler); - } - - /** - * Constructor that creates a Group from a single OMGraphicHandler layer. - * - * @param layer Description of the Parameter - */ - public LayerMapContent(OMGraphicHandlerLayer layer) { - addContent(this, layer); - } - - /** - * Add content to this Group. The OMGraphicHandler layers that are part of - * the map with have their graphics may be added with a small separation - * between the layers, depending on the value of layerSeparation. - * - * @param mapHandler Description of the Parameter - */ - protected void createMap(MapHandler mapHandler) { - - double baselineHeight = layerSeparation; - - LayerHandler lh = (LayerHandler) mapHandler.get("com.bbn.openmap.LayerHandler"); - if (lh != null) { - Debug.message("3d", - "LayerMapContent: putting layer graphics on the map."); - Layer[] layers = lh.getLayers(); - - // Back to front makes the sea in the back, and keeps - // first layers on top, to go with the OpenMap paradigm. - for (int i = layers.length - 1; i >= 0; i--) { - Layer layer = layers[i]; - if (layer.isVisible()) { - if (layer instanceof ScaleFilterLayer) { - ScaleFilterLayer sfl = (ScaleFilterLayer) layer; - layer = sfl.getAppropriateLayer(); - } - if (layer instanceof OMGraphicHandlerLayer) { - addContent(this, - (OMGraphicHandlerLayer) layer, - baselineHeight += layerSeparation); - } else { - Debug.message("3d", "LayerMapContent: skipping layer " - + layer.getName()); - } - } - } - } - - addSea(this, mapHandler); - } - - /** - * Add the projection background color to the base level of the Java 3D map. - * The MapHandler provides the MapBean and therefore the projection. - * - * @param bg The feature to be added to the Sea attribute - * @param mh The feature to be added to the Sea attribute - */ - protected void addSea(Group bg, MapHandler mh) { - MapBean map = (MapBean) mh.get("com.bbn.openmap.MapBean"); - if (map != null) { - Debug.message("3d", "LayerMapContent: putting down sea."); - Color seaColor = map.getBackground(); - - Projection proj = map.getProjection(); - - // Make the background strech a screen around the current - // map, all directions. - int width = proj.getWidth(); - int height = proj.getHeight(); - - java.awt.geom.GeneralPath background = - // OMGraphic.createBoxShape(0, 0, width, height); - OMGraphicAdapter.createBoxShape(-width, - -height, - width * 3, - height * 3); - - addTo(bg, - OMGraphicUtil.createShape3D(background, 0, seaColor, true)); - } - } - - /** - * Add a layer to the Group. - * - * @param bg The feature to be added to the Content attribute - * @param layer The feature to be added to the Content attribute - */ - protected void addContent(Group bg, OMGraphicHandlerLayer layer) { - addContent(bg, layer, 0); - } - - /** - * Add a layer to the Group, at a specific height. - * - * @param bg The feature to be added to the Content attribute - * @param layer The feature to be added to the Content attribute - * @param baselineHeight The feature to be added to the Content attribute - */ - protected void addContent(Group bg, OMGraphicHandlerLayer layer, - double baselineHeight) { - Debug.message("3d", "LayerMapContent: putting layer " + layer.getName() - + " graphics on the map."); - addTo(bg, OMGraphicUtil.createShape3D(layer.getList(), baselineHeight)); - } - - /** - * Set the height spacer that is bing placed between layers. - * - * @param separation The new layerSeparation value - */ - public void setLayerSeparation(double separation) { - layerSeparation = separation; - } - - /** - * Return the height spacer that is being placed between layers. - * - * @return The layerSeparation value - */ - public double getLayerSeparation() { - return layerSeparation; - } - - /** - * Add the Shape3D objects from an iterator to a Group object. - * - * @param bg The feature to be added to the To attribute - * @param shapeIterator The feature to be added to the To attribute - */ - protected void addTo(Group bg, Iterator shapeIterator) { - - while (shapeIterator.hasNext()) { - try { - Shape3D shape = (Shape3D) shapeIterator.next(); - if (shape != null) { - bg.addChild(shape); - } - } catch (ClassCastException cce) { - continue; - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/MapContent.java b/src/core/src/main/java/com/bbn/openmap/j3d/MapContent.java deleted file mode 100644 index 0742eb8ed..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/MapContent.java +++ /dev/null @@ -1,337 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/MapContent.java,v $ -// $RCSfile: MapContent.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/11 19:27:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.image.BufferedImage; -import java.util.HashSet; -import java.util.Iterator; - -import javax.media.j3d.Appearance; -import javax.media.j3d.BranchGroup; -import javax.media.j3d.GeometryArray; -import javax.media.j3d.ImageComponent2D; -import javax.media.j3d.QuadArray; -import javax.media.j3d.Shape3D; -import javax.media.j3d.Texture; -import javax.media.j3d.Texture2D; -import javax.media.j3d.TransformGroup; -import javax.media.j3d.TransparencyAttributes; -import javax.vecmath.Point2f; -import javax.vecmath.Point3f; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.image.AcmeGifFormatter; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.sun.j3d.utils.image.TextureLoader; - -/** - * A more complex MapContent. The regular layers get drawn into a base - * image that is overlaid upon the earth geometry which can have - * shape, if elevation data is available. The other layers, that - * provide objects that should be rendered in 3D space, get entered - * into the scene as specific objects. - * - * @author dietrick - */ -public class MapContent extends BranchGroup implements OM3DConstants { - - protected MapBean map; - protected Proj proj; - protected LayerHandler layerHandler; - protected HashSet graphicHandlers; - protected MapHandler mapHandler; - - public MapContent(MapHandler mapHandler, int contentMask) { - super(); - init(mapHandler); - - if ((contentMask & CONTENT_MASK_OM3DGRAPHICHANDLERS) != 0) { - createMapObjects(); - } - if ((contentMask & CONTENT_MASK_IMAGEMAP) != 0) { - createMapImage(); - } - if ((contentMask & CONTENT_MASK_ELEVATIONMAP) != 0) { - createMapElevations(); - } - } - - protected void init(MapHandler mapHandler) { - - if (mapHandler == null) { - return; - } - - map = (MapBean) mapHandler.get("com.bbn.openmap.MapBean"); - proj = null; - - if (map != null) { - proj = (Proj) map.getProjection(); - } - - this.mapHandler = mapHandler; - } - - protected HashSet getGraphicHandlers(MapHandler mapHandler) { - - Debug.message("3d", "LayerMapContent: looking for OM3DGraphicHandlers."); - - HashSet ret = new HashSet(); - Iterator iterator = mapHandler.iterator(); - - while (iterator.hasNext()) { - Object obj = iterator.next(); - if (obj instanceof OM3DGraphicHandler) { - Debug.message("3d", "LayerMapContent: found one, adding " + obj); - ret.add(obj); - } - } - - // Have to do layers separately because they may not be - // exposed to the MapHandler. - layerHandler = (LayerHandler) mapHandler.get("com.bbn.openmap.LayerHandler"); - - if (layerHandler != null) { - Layer[] layers = layerHandler.getLayers(); - int size = layers.length; - - for (int i = size - 1; i >= 0; i--) { - Layer layer = layers[i]; - - if (layer.isVisible() && (layer instanceof OM3DGraphicHandler)) { - Debug.message("3d", - "LayerMapContent: found layer version, adding " - + layer.getName()); - ret.add(layer); - } - } - } - return ret; - } - - /** - * May be used for OM3DGraphicHandlers to get an idea of what the - * map looks like. - * - * @return The projection value - */ - public Projection getProjection() { - return proj; - } - - /** - * Goes through the MapHandler, and sets this object in any - * OM3DGraphicHandler, so they can call back to load in Shape3D or - * OMGraphic objects. - */ - protected void createMapObjects() { - - if (mapHandler == null) { - Debug.error("MapContent: MapHandler not set!"); - return; - } - - graphicHandlers = getGraphicHandlers(mapHandler); - - Iterator iterator = graphicHandlers.iterator(); - while (iterator.hasNext()) { - ((OM3DGraphicHandler) iterator.next()).addGraphicsToScene(this); - } - } - - /** - * Callback method for OM3DGraphicHandlers, to add an OMGrid - * object to the scene. For now, the values of the OMGrid - * correspond to the height of the values in the grid. The heights - * should be relative to the 3D scene, in relation to the OpenMap - * projection (screen X/Y coordinates of the OpenMap projection - * have a direct relationship with the X/Z axis of the 3D scene). - * - * @param grid Description of the Parameter - */ - public void add(OMGrid grid) { - add(OMGraphicUtil.createShape3D(grid, 0, proj)); - } - - /** - * Callback method for OM3DGraphicHandlers, to add an OMGraphics - * to the scene. - * - * @param omgraphic an OMGraphic. - * @param height the height of the object. All points of the - * object are at this height. The height should be relative - * to the 3D scene, in relation to the OpenMap projection - * (screen X/Y coordinates of the OpenMap projection have a - * direct relationship with the X/Z axis of the 3D scene). - * If you have an object with varying height, create an - * Shape3D object instead and use the other add() method. - */ - public void add(OMGraphic omgraphic, double height) { - add(OMGraphicUtil.createShape3D(omgraphic, height)); - } - - /** - * Callback method for OM3DGraphicHandlers, to add a Shape3D - * object to the scene. - * - * @param shape Description of the Parameter - */ - public void add(Shape3D shape) { - addChild(shape); - } - - /** - * Add the Shape3D objects from an iterator. - * - * @param shapeIterator Iterator containing Shape3D objects. - */ - protected void add(Iterator shapeIterator) { - - while (shapeIterator.hasNext()) { - try { - Shape3D shape = (Shape3D) shapeIterator.next(); - if (shape != null) { - add(shape); - } - } catch (ClassCastException cce) { - continue; - } - } - } - - /** - * Add a TransformGroup from a OM3DGraphicHandler. This will - * provide an object to the scene that can be controlled by an - * outside source. - * - * @param transformGroup any transform group containing Shape3D - * objects. - */ - protected void add(TransformGroup transformGroup) { - addChild(transformGroup); - } - - protected void createMapElevations() { - Debug.error("MapContent.createMapElevations not implemented."); - } - - protected void createMapImage() { - - if (proj == null || mapHandler == null) { - Debug.error("MapContent: MapHandler not set!"); - return; - } - - int pwidth = 512; - int pheight = 512; - - AcmeGifFormatter formatter = new AcmeGifFormatter(); - Graphics graphics = formatter.getGraphics(pwidth, pheight); - - Paint background; - if (map == null) { - background = MapBean.DEFAULT_BACKGROUND_COLOR; - } else { - background = map.getBckgrnd(); - } - proj.drawBackground((Graphics2D) graphics, background); - - layerHandler = (LayerHandler) mapHandler.get("com.bbn.openmap.LayerHandler"); - if (layerHandler != null) { - Debug.message("3d", - "LayerMapContent: putting layer graphics on the map."); - Layer[] layers = layerHandler.getLayers(); - int size = layers.length; - - for (int i = size - 1; i >= 0; i--) { - Layer layer = layers[i]; - - if (layer.isVisible() && !(layer instanceof OM3DGraphicHandler)) { - - layer.renderDataForProjection(proj, graphics); - } - } - } - - BufferedImage bimage = formatter.getBufferedImage(); - - // Now we have our textured image. - - QuadArray plane = new QuadArray(4, GeometryArray.COORDINATES - | GeometryArray.TEXTURE_COORDINATE_2); - float height = (float) pheight; - float width = (float) pwidth; - - Point3f p = new Point3f(0f, 0f, 0f);//-1.0f, 1.0f, 0.0f); - plane.setCoordinate(0, p); - p.set(0f, 0f, height);//-1.0f, -1.0f, 0.0f); - plane.setCoordinate(1, p); - p.set(width, 0f, height);//1.0f, -1.0f, 0.0f); - plane.setCoordinate(2, p); - p.set(0f, 0f, height);//1.0f, 1.0f, 0.0f); - plane.setCoordinate(3, p); - - Point2f q = new Point2f(0.0f, 1.0f); - plane.setTextureCoordinate(0, q); - q.set(0.0f, 0.0f); - plane.setTextureCoordinate(1, q); - q.set(1.0f, 0.0f); - plane.setTextureCoordinate(2, q); - q.set(1.0f, 1.0f); - plane.setTextureCoordinate(3, q); - - Appearance appear = new Appearance(); - - TextureLoader loader = new TextureLoader(bimage); - ImageComponent2D image = loader.getImage(); - - if (Debug.debugging("3d")) { - Debug.output("MapContent: image height: " + image.getHeight() - + ", width: " + image.getWidth()); - } - - // can't use parameterless constuctor - Texture2D texture = new Texture2D(Texture.BASE_LEVEL, Texture.RGBA, image.getWidth(), image.getHeight()); - texture.setImage(0, image); - //texture.setEnable(false); - - appear.setTexture(texture); - - appear.setTransparencyAttributes(new TransparencyAttributes(TransparencyAttributes.FASTEST, 0.1f)); - - Shape3D planeObj = new Shape3D(plane, appear); - addChild(planeObj); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/MapContentManager.java b/src/core/src/main/java/com/bbn/openmap/j3d/MapContentManager.java deleted file mode 100644 index 1911d565d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/MapContentManager.java +++ /dev/null @@ -1,210 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/MapContentManager.java,v $ -// $RCSfile: MapContentManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/11 21:34:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.BorderLayout; - -import javax.media.j3d.AmbientLight; -import javax.media.j3d.Background; -import javax.media.j3d.Behavior; -import javax.media.j3d.BoundingSphere; -import javax.media.j3d.BranchGroup; -import javax.media.j3d.Group; -import javax.media.j3d.TransformGroup; -import javax.swing.JFrame; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The 3D manager that takes an OpenMap MapHandler, and creates a 3D - * world from the layers in it. The layer's OMGraphics are converted - * to 3D objects. - * - * @author dietrick - */ -public class MapContentManager extends OM3DManager { - - protected MapContentManager() { - super.init(); - } - - /** - * @param mapHandler the OpenMap MapHandler. - */ - public MapContentManager(MapHandler mapHandler, int contentMask) { - this(mapHandler, new Background(0f, 0f, 0f), contentMask); - } - - /** - * @param mapHandler the OpenMap MapHandler. - * @param background the background object to use for the 3D - * scene. Use this to change the sky color, for instance. - */ - public MapContentManager(MapHandler mapHandler, Background background, - int contentMask) { - super.init(); - createWorld(mapHandler, background, contentMask); - } - - protected void createWorld(MapHandler mapHandler, Background background, - int contentMask) { - setSceneBackground(background); - // objRootBG gets created in super class - addMapContent(mapHandler, objRootBG, contentMask); - } - - /** - * IMPORTANT! You need to call this to compile the universe after - * everything is set. - */ - public void compileUniverse() { - // Important!! Compiles the universe - ((UniverseManager) universe).makeLive(); - } - - public void addBehavior(Behavior behavior) { - objRootBG.addChild(behavior); - } - - /** - * This is the main function that gets called when the - * MapContentViewer is created, to create the world objects in the - * universe. It builds the objects to put in the J3D world from - * the objects contained within the MapHandler. This method calls - * setCameraLocation(), so you can modify where the camera is - * placed there, and then calls createMapContent() to have a - * BranchGroup created with 3D objects. You can modify those - * methods to adjust how things get created. - * - * @param mapHandler The feature to be added to the MapContent - * attribute - * @param worldGroup The feature to be added to the MapContent - * attribute - */ - protected void addMapContent(MapHandler mapHandler, BranchGroup worldGroup, - int contentMask) { - - Projection projection = null; - - if (mapHandler != null) { - - MapBean mapBean = (MapBean) mapHandler.get("com.bbn.openmap.MapBean"); - - if (mapBean != null) { - projection = mapBean.getProjection(); - } - - TransformGroup mapTransformGroup = new TransformGroup(); - mapTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ); - mapTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); - - Debug.message("3d", "OM3DViewer: adding map content"); - - BoundingSphere bs = new BoundingSphere(ORIGIN, boundsDimension); - - //BoundingLeaf boundingLeaf = new BoundingLeaf(bs); - - background.setApplicationBounds(bs); - - mapTransformGroup.addChild(background); - - createMapContent(mapTransformGroup, mapHandler, contentMask); - - // Lights up the whole world. If this isn't added, the - // land is black - AmbientLight ambientLight = new AmbientLight(); - ambientLight.setInfluencingBounds(bs); - worldGroup.addChild(ambientLight); - - // /////// - Behavior beh = getMotionBehavior((TransformGroup) getCamera().getNode(), - projection); - beh.setSchedulingBounds(bs); - - worldGroup.addChild(beh); - // /////// - worldGroup.addChild(mapTransformGroup); - } - } - - protected void createMapContent(TransformGroup mapTransformGroup, - MapHandler mapHandler, int contentMask) { - if ((contentMask & CONTENT_MASK_OMGRAPHICHANDLERLAYERS) != 0) { - mapTransformGroup.addChild(createLayerMapContent(mapHandler)); - } - - mapTransformGroup.addChild(createMapContent(mapHandler, contentMask)); - } - - /** - * Called from addMapContent. Create a BranchGroup, and put your - * 3D objects in it. The MapBean in the MapHandler has a - * projection that can be used to lay things out, and the layers - * have objects to render. - * - * @param mapHandler Description of the Parameter - * @return Description of the Return Value - */ - protected Group createLayerMapContent(MapHandler mapHandler) { - return new LayerMapContent(mapHandler); - } - - /** - * @param mapHandler Description of the Parameter - * @return Description of the Return Value - */ - protected Group createMapContent(MapHandler mapHandler, int contentMask) { - return new MapContent(mapHandler, contentMask); - } - - /** - * Called from addMapContent(), to set up the Transforms for - * motion. The projection is provided in case you want to locate - * the camera or map in a certain geographical location. - * - * @param cameraTransform Description of the Parameter - * @param projection Description of the Parameter - * @return The motionBehavior value - */ - public Behavior getMotionBehavior(TransformGroup cameraTransform, - Projection projection) { - - return new OMKeyBehavior(cameraTransform, projection); - } - - public static JFrame getFrame(String title, int width, int height, - MapHandler mapHandler, Background background, - int contentMask) { - - JFrame frame = new JFrame(title); - frame.setSize(width, height); - frame.getContentPane().setLayout(new BorderLayout()); - MapContentManager mc3d = new MapContentManager(mapHandler, background, contentMask); - mc3d.compileUniverse(); - frame.getContentPane().add("Center", mc3d.getCanvas()); - return frame; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/NavBehaviorProvider.java b/src/core/src/main/java/com/bbn/openmap/j3d/NavBehaviorProvider.java deleted file mode 100644 index 9d7a0ff9b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/NavBehaviorProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ********************************************************************** - * - * BBN Corporation 10 Moulton St. Cambridge, MA 02138 (617) 873-2000 - * - * Copyright (C) 2002 This software is subject to copyright protection - * under the laws of the United States and other countries. - * - * ********************************************************************** - * - * $Source: - * /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/NavBehaviorProvider.java,v $ - * $RCSfile: NavBehaviorProvider.java,v $ $Revision: 1.3 $ $Date: - * 2004/02/09 13:33:36 $ $Author: dietrick $ - * - * ********************************************************************** - */ -package com.bbn.openmap.j3d; - -import javax.media.j3d.Behavior; -import javax.media.j3d.TransformGroup; - -import com.bbn.openmap.proj.Projection; - -public interface NavBehaviorProvider { - - /** - * Set the behavior for the viewing platform. - * - * @param cameraTransformGroup The new viewingPlatformBehavior - * value - * @return Description of the Return Value - */ - public Behavior setViewingPlatformBehavior( - TransformGroup cameraTransformGroup, - Projection projection, - float scaleFactor); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DConstants.java b/src/core/src/main/java/com/bbn/openmap/j3d/OM3DConstants.java deleted file mode 100644 index c4d936490..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DConstants.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OM3DConstants.java,v $ -// $RCSfile: OM3DConstants.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 19:27:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import javax.media.j3d.BoundingSphere; -import javax.vecmath.Color3f; -import javax.vecmath.Point3d; - -/** - * An interface that any class can implement to get access to common - * constant values. - * - * @author dietrick - */ -public interface OM3DConstants { - - public final static Point3d ORIGIN = new Point3d(0, 0, 0); - public final static double BACK_CLIP_DISTANCE = 10000.0; - public final static BoundingSphere LIGHT_BOUNDS = new BoundingSphere(ORIGIN, BACK_CLIP_DISTANCE); - - /** - * Standard light color. - */ - public final static Color3f White = new Color3f(1, 1, 1); - - /** - * Default bounds dimension. - */ - public final static double DEFAULT_BOUNDS_DIMENSION = 1000.0; - - /** - * Default size of the window edge. - */ - public final static int DEFAULT_DIMENSION = 400; - - /** - * Mask for Content. To tell them to look for any layers that are - * OMGraphicHandlers, and add those layers' objects to the scene. - */ - public final static int CONTENT_MASK_OMGRAPHICHANDLERLAYERS = 1 << 0; - /** - * Mask for Content. Tells the Content to look for - * OM3DGraphicHandlers in the MapHandler. Any OM3dGraphicHandler - * is given a reference to the Content, and the OM3DGraphicHandler - * can call methods on the content to add graphics and shapes to - * the scene. - */ - public final static int CONTENT_MASK_OM3DGRAPHICHANDLERS = 1 << 1; - /** - * Mask for Content. To tell them to take all the standard OpenMap - * layers and incorporate them into an image. - */ - public final static int CONTENT_MASK_IMAGEMAP = 1 << 2; - public final static int CONTENT_MASK_ELEVATIONMAP = 1 << 3; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DGraphicHandler.java b/src/core/src/main/java/com/bbn/openmap/j3d/OM3DGraphicHandler.java deleted file mode 100644 index 486c4da99..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DGraphicHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ********************************************************************** - * - * BBN Corporation - * 10 Moulton St. - * Cambridge, MA 02138 - * (617) 873-2000 - * - * Copyright (C) 2002 - * This software is subject to copyright protection under the laws of - * the United States and other countries. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OM3DGraphicHandler.java,v $ - * $RCSfile: OM3DGraphicHandler.java,v $ - * $Revision: 1.4 $ - * $Date: 2005/08/11 19:27:04 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ -package com.bbn.openmap.j3d; - -/** - * This is an interface that denotes an object that will contribute - * objects into a Java 3D scene graph. If you write an object that - * implements this interface, it will be called with a MapContent - * object that you can use to add different objects to the scene. - * - * @author dietrick - */ -public interface OM3DGraphicHandler { - - /** - * Provide a MapContent object for the OM3DGraphicHandler to add - * objects to. The MapContent object as three add() methods, one - * for OMGraphics, one for OMGrid specifically, and one for - * Shape3D objects. The OM3DGraphicHandler should go through its - * graphics and add them to this MapContext object. This should be - * done *before* the OM3DGraphicHandler returns from this method! - * - * @param mapContent The feature to be added to the - * GraphicsToScene attribute - * @see MapContent - */ - public void addGraphicsToScene(MapContent mapContent); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DManager.java b/src/core/src/main/java/com/bbn/openmap/j3d/OM3DManager.java deleted file mode 100644 index d6643ace9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DManager.java +++ /dev/null @@ -1,171 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OM3DManager.java,v $ -// $RCSfile: OM3DManager.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 19:27:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.Dimension; -import java.awt.GraphicsConfiguration; -import java.awt.GraphicsDevice; -import java.awt.GraphicsEnvironment; - -import javax.media.j3d.Background; -import javax.media.j3d.BranchGroup; -import javax.media.j3d.Canvas3D; -import javax.media.j3d.GraphicsConfigTemplate3D; -import javax.media.j3d.Group; -import javax.media.j3d.VirtualUniverse; -import javax.vecmath.Vector3f; - -/** - * An abstract 3D manager object, containing content, canvas, camera - * and the universe. The canvase is the thing you add to the GUI to - * see the 3D world. - * - * @author dietrick - */ -public abstract class OM3DManager implements OM3DConstants { - - protected float scaleFactor = 1f; - - /** - * The Universe for the scene. - */ - protected UniverseManager universe = null; - - /** - * The root branch group of worldly objects. - */ - protected BranchGroup objRootBG = null; - - /** - * The camera, the viewer's eye. - */ - protected Camera cam = null; - - /** - * The bounding sphere radius for the root branch group. - */ - protected double boundsDimension = DEFAULT_BOUNDS_DIMENSION; - - /** - * The Background to the universe. - */ - protected Background background = new Background(); - - /** - */ - protected Canvas3D canvas = null; - - protected OM3DManager() { - init(); - } - - /** - * Set up the canvas and the universe. - */ - protected void init() { - - // Try to set a GraphicsConfiguration... - GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D(); - GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); - GraphicsDevice device = env.getDefaultScreenDevice(); - GraphicsConfiguration config = device.getBestConfiguration(template); - - canvas = new Canvas3D(config); - canvas.setSize(new Dimension(DEFAULT_DIMENSION, DEFAULT_DIMENSION)); - - objRootBG = new BranchGroup(); - objRootBG.setCapability(Group.ALLOW_CHILDREN_EXTEND); - - constructWorld(objRootBG); - } - - /** - * Construct everything that we want in the basic test world - * - * @param worldBranchGroup Description of the Parameter - */ - protected void constructWorld(BranchGroup worldBranchGroup) { - // create the basic universe - UniverseManager univ = new UniverseManager(worldBranchGroup); - - cam = new Camera(); - Vector3f loc = new Vector3f(0, 0, 0); - cam.setLocation(loc); - cam.setHeadLight(true); - cam.setCanvas(canvas); - univ.addCamera(cam); - - universe = univ; - } - - /** - * Get the Camera, which is controlling the viewer's perspective. - * - * @return The camera value - */ - public Camera getCamera() { - return cam; - } - - public Canvas3D getCanvas() { - return canvas; - } - - /** - * Get the BranchGroup that represents the head of the world - * object tree. - * - * @return The world value - */ - public BranchGroup getWorld() { - return objRootBG; - } - - public void setScaleFactor(float sf) { - scaleFactor = sf; - } - - public float getScaleFactor() { - return scaleFactor; - } - - public void setBoundsDimension(double bd) { - boundsDimension = bd; - } - - public double getBoundsDimension() { - return boundsDimension; - } - - public VirtualUniverse getUniverse() { - return universe; - } - - public void setSceneBackground(Background background) { - this.background = background; - } - - public Background getSceneBackground() { - return background; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DViewerLauncher.java b/src/core/src/main/java/com/bbn/openmap/j3d/OM3DViewerLauncher.java deleted file mode 100644 index c28716017..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OM3DViewerLauncher.java +++ /dev/null @@ -1,161 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OM3DViewerLauncher.java,v $ -// $RCSfile: OM3DViewerLauncher.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/03/06 16:40:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.Container; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.util.Iterator; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.SwingConstants; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MapHandlerChild; -import com.bbn.openmap.gui.Tool; -import com.bbn.openmap.j3d.geometry.Curtain; -import com.bbn.openmap.util.Debug; - -/** - * @author dietrick - */ -public class OM3DViewerLauncher extends MapHandlerChild implements - ActionListener, Tool, OM3DGraphicHandler { - - /** - * Default key for the DrawingToolLauncher Tool. - */ - public final static String defaultKey = "OM3DViewerLauncher"; - /** - * The key used when this DrawingToolLauncher is used as a Tool. - */ - protected String key = defaultKey; - /** - * The frame used when the DrawingToolLauncher is used in an application. - */ - protected transient JFrame viewer; - - public final static String CreateCmd = "CREATE"; - - public OM3DViewerLauncher() {} - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand().intern(); - - Debug.message("3d", "OM3DViewerLauncher.actionPerformed(): " + command); - - if (command == CreateCmd) { - - viewer = MapContentManager.getFrame("OpenMap 3D", - 500, - 500, - (MapHandler) getBeanContext(), - new javax.media.j3d.Background(.3f, .3f, .3f), - OM3DConstants.CONTENT_MASK_OMGRAPHICHANDLERLAYERS - | OM3DConstants.CONTENT_MASK_OM3DGRAPHICHANDLERS); - viewer.setVisible(true); - } - } - - /** - * This is the method that your object can use to find other objects within - * the MapHandler (BeanContext). This method gets called when the object - * gets added to the MapHandler, or when another object gets added to the - * MapHandler after the object is a member. - * - * @param it Iterator to use to go through a list of objects. Find the ones - * you need, and hook yourself up. - */ - public void findAndInit(Iterator it) {} - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - * - * @param bcme Description of the Parameter - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) {} - - /** - * Tool interface method. The retrieval tool's interface. This method - * creates a button that will bring up the LauncherPanel. - * - * @return String The key for this tool. - */ - public Container getFace() { - JButton launcherButton = new JButton(new ImageIcon(OM3DViewerLauncher.class.getResource("launcher.gif"), "3D Viewer Launcher")); - launcherButton.setBorderPainted(false); - launcherButton.setToolTipText("3D Viewer Launcher"); - launcherButton.setMargin(new Insets(0, 0, 0, 0)); - launcherButton.addActionListener(this); - launcherButton.setActionCommand(CreateCmd); - return launcherButton; - } - - /** - */ - public void resetGUI() {} - - /** - * Tool interface method. The retrieval key for this tool. - * - * @return String The key for this tool. - */ - public String getKey() { - return key; - } - - /** - * Tool interface method. Set the retrieval key for this tool. - * - * @param aKey The new key value - */ - public void setKey(String aKey) { - key = aKey; - } - - protected Curtain curtain = new Curtain(); - - /** - * OM3DGraphicHandler method, gets called from MapContent. - * - * @see OM3DGraphicHandler - */ - public void addGraphicsToScene(MapContent mapContent) { - curtain.addGraphicsToScene(mapContent); - } - - public void setOrientation(int orientation) {} - - public int getOrientation() { - return SwingConstants.HORIZONTAL; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OMGraphicUtil.java b/src/core/src/main/java/com/bbn/openmap/j3d/OMGraphicUtil.java deleted file mode 100644 index 21d7fc9e6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OMGraphicUtil.java +++ /dev/null @@ -1,652 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OMGraphicUtil.java,v $ -// $RCSfile: OMGraphicUtil.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.Color; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.FlatteningPathIterator; -import java.awt.geom.PathIterator; -import java.util.HashSet; -import java.util.Iterator; - -import javax.media.j3d.Appearance; -import javax.media.j3d.ColoringAttributes; -import javax.media.j3d.LineArray; -import javax.media.j3d.LineStripArray; -import javax.media.j3d.Material; -import javax.media.j3d.PolygonAttributes; -import javax.media.j3d.Shape3D; -import javax.media.j3d.TriangleStripArray; -import javax.vecmath.Color3f; -import javax.vecmath.Color4b; -import javax.vecmath.Point3d; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.GridData; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.omGraphics.grid.SimpleColorGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.sun.j3d.utils.geometry.GeometryInfo; -import com.sun.j3d.utils.geometry.NormalGenerator; -import com.sun.j3d.utils.geometry.Stripifier; -import com.sun.j3d.utils.geometry.Triangulator; - -/** - * This class handles translating OMGraphics into a Java 3D Scene. - * - * @author dietrick - */ -public class OMGraphicUtil { - - public final static int DEFAULT_NPOINTS_BUFFER_SIZE = 100; - public final static Iterator NULL_ITERATOR = new HashSet().iterator(); - - /** - * Method takes an OMGraphic, creates one or more Shape3D objects - * out of it, and returns an Iterator containing them. - * - * @param graphic the OMGraphic. - * @return Iterator containing Shape3D objects. - */ - public static Iterator createShape3D(OMGraphic graphic) { - return createShape3D(graphic, 0); - } - - /** - * Method takes an OMGraphic, creates one or more Shape3D objects - * out of it, and returns an Iterator containing them. - * - * @param graphic the OMGraphic. - * @param baselineHeight the baselined height for all the graphics - * on the list. - * @return Iterator containing Shape3D objects. - */ - public static Iterator createShape3D(OMGraphic graphic, - double baselineHeight) { - - Debug.message("3detail", "OMGraphicUtil.createShape3D()"); - - boolean DEBUG_SHAPE = Debug.debugging("3dshape"); - - if (graphic == null) { - return NULL_ITERATOR; - } - - if (graphic instanceof OMGraphicList) { - - HashSet set = new HashSet(); - - for (OMGraphic subgraphic : (OMGraphicList) graphic) { - Debug.message("3detail", - "OMGraphicUtil.createShape3D(): recursivly adding list..."); - Iterator iterator = createShape3D(subgraphic, baselineHeight); - while (iterator.hasNext()) { - set.add(iterator.next()); - } - } - return set.iterator(); - } else { - - if (DEBUG_SHAPE) { - Debug.output("OMGraphicUtil.createShape3D(): adding shape..."); - } - - Shape shape = graphic.getShape(); - - if (shape != null) { - // Handle the shapes, depending on if they should - // be filled or not... - - // First, determine wether this is a line or - // polygon thingy, and set the color accordingly. - - // Text should be handled differently - might need - // to render text, and the background block. - - if (graphic.shouldRenderFill()) { - // Do polygons. - return createShape3D(shape, - baselineHeight, - graphic.getFillColor(), - true); - } else if (graphic.shouldRenderEdge()) { - // Might as well make sure it's not totally - // clear before creating lines. - return createShape3D(shape, - baselineHeight, - graphic.getDisplayColor(), - false); - } else if (DEBUG_SHAPE) { - Debug.output("OMGraphicUtil.createShape3D(): can't render graphic"); - } - } else if (DEBUG_SHAPE) { - Debug.output("OMGraphicUtil.createShape3D(): shape from graphic is null"); - } - } - return NULL_ITERATOR; - } - - /** - * Create an Iterator containing a set of Shape3D objects, created - * from OMGrid. Currently only works for OMGrids containing - * GridData.Int data. - * - * @param grid the OMGrid to create a 3D terrain object from. - * @param baselineHeight the baselined height for all the values - * in the grid, if the OMGridGenerator wants to use it. - * @param projection the map projection - * @return an iterator containing all Shape3D objects - */ - public static Iterator createShape3D(OMGrid grid, double baselineHeight, - Projection projection) { - - TriangleStripArray gridStrip; - - if (grid.getRenderType() != OMGraphic.RENDERTYPE_LATLON) { - Debug.error("OMGraphicUtil.createShape3D: can't handle non-LATLON grids yet"); - return NULL_ITERATOR; - } - - boolean DEBUG = false; - if (Debug.debugging("3dgrid")) { - DEBUG = true; - } - - // if (grid.getGenerator() == null && grid.getFillColor() == - // OMColor.clear) { - // return createWireFrame(grid, baselineHeight, projection); - // } - - Color fColor = grid.getFillColor(); - Color lColor = grid.getLineColor(); - - boolean polyline = (fColor == OMColor.clear); - if (DEBUG) { - Debug.output("Polyline = " + polyline); - } - Color3f fillcolor = new Color3f(fColor); - Color3f linecolor = new Color3f(lColor); - - int numRows = grid.getRows(); - int numCols = grid.getColumns(); - - // create triangle strip for twist - int stripCount = numRows - 1; - int numberVerticesPerStrip = numCols * 2; - int[] stripCounts = new int[stripCount]; - - for (int i = 0; i < stripCount; i++) { - stripCounts[i] = numberVerticesPerStrip; - } - - LatLonPoint anchorLL = new LatLonPoint.Double(grid.getLatitude(), grid.getLongitude()); -// Point anchorP = projection.forward(anchorLL); - double vRes = grid.getVerticalResolution(); - double hRes = grid.getHorizontalResolution(); - - gridStrip = new TriangleStripArray(stripCount * numberVerticesPerStrip, TriangleStripArray.COORDINATES - | TriangleStripArray.COLOR_3 | TriangleStripArray.NORMALS, stripCounts); - - // OK, what you want to do is calculate the index of the - // vertices, add the correct multiplication of offsets in - // degree space, and then inverse project that point to get - // the actual coordinates. - - Point p = new Point(); - int pointer = 0; - - GridData gridData = grid.getData(); - - if (!(gridData instanceof GridData.Int)) { - // Need to fix this to work with all GridData types! - Debug.error("OMGrid.interpValueAt only works for integer data."); - } - - int[][] data = ((GridData.Int) gridData).getData(); - boolean major = gridData.getMajor(); - - // int[][] data = grid.getData(); - // boolean major = grid.getMajor(); - - int dataPoint; - Color3f color; - - SimpleColorGenerator generator = null; - OMGridGenerator tempGen = grid.getGenerator(); - - if (tempGen instanceof SimpleColorGenerator) { - generator = (SimpleColorGenerator) tempGen; - } - - for (int j = 0; j < numRows - 1; j++) { - - if (DEBUG) { - Debug.output("Creating strip " + j); - } - // I think the '-' should be '+'... (changed, DFD) - double lat1 = anchorLL.getY() + (j * vRes); - double lat2 = anchorLL.getY() + (( j + 1.0) * vRes); - - for (int k = 0; k < numCols; k++) { - - if (DEBUG) { - Debug.output(" working row " + k); - } - - double lon = anchorLL.getX() + (k * hRes); - - projection.forward(lat1, lon, p); - if (major) { - dataPoint = data[k][j]; - } else { - dataPoint = data[j][k]; - } - - gridStrip.setCoordinate(pointer, - new Point3d((float) p.getX(), (float) dataPoint, (float) p.getY())); - - if (DEBUG) { - Debug.output(" 1st coord " + p.getX() + ", " - + dataPoint + ", " + p.getY()); - } - - projection.forward(lat2, lon, p); - - if (major) { - dataPoint = data[k][j + 1]; - } else { - dataPoint = data[j + 1][k]; - } - gridStrip.setCoordinate(pointer + 1, - new Point3d((float) p.getX(), (float) dataPoint, (float) p.getY())); - - if (DEBUG) { - Debug.output(" 2nd coord " + p.getX() + ", " - + dataPoint + ", " + p.getY()); - } - - // Need the TriangleStripArray.COLOR_3 Attribute set - // above - if (generator == null) { - if (polyline) { - color = linecolor; - } else { - color = fillcolor; - } - } else { - color = new Color3f(new Color(generator.calibratePointValue(dataPoint))); - } - - gridStrip.setColor(pointer++, color); - gridStrip.setColor(pointer++, color); - // else - // pointer += 2; - } - } - - Shape3D shape = new Shape3D(gridStrip); - - Appearance appear = new Appearance(); - PolygonAttributes polyAttrib = new PolygonAttributes(); - if (polyline) { - polyAttrib.setPolygonMode(PolygonAttributes.POLYGON_LINE); - } - polyAttrib.setCullFace(PolygonAttributes.CULL_NONE); - - appear.setPolygonAttributes(polyAttrib); - - shape.setAppearance(appear); - - HashSet set = new HashSet(); - set.add(shape); - - return set.iterator(); - } - - /** - * Create an Iterator containing a set of Shape3D objects, created - * from a java.awt.Shape. - * - * @param shape java.awt.Shape object. - * @param baselineHeight the baselined height for all the values - * in the grid, if the OMGridGenerator wants to use it. - * @param color the color to make the object. - * @param filled whether or not to fill the object with color. - * @return Iterator containing Shape3D objects created from shape - * object. - */ - public static Iterator createShape3D(Shape shape, double baselineHeight, - Color color, boolean filled) { - - int bufferSize = DEFAULT_NPOINTS_BUFFER_SIZE; - - double[] data = expandArrayD(bufferSize, null); - int dataIndex = 0; - - // How many spaces are left in the buffer. - int refreshCounter = bufferSize; - int[] stripCount = new int[1]; - stripCount[0] = 0; - - // null is AffineTransform... - PathIterator pi2 = shape.getPathIterator(null); - - // flatness might need to be calculated, based - // on scale or something. Depends on how many - // points there should be for an accurate - // shape rendition. - float flatness = .25f; - FlatteningPathIterator pi = new FlatteningPathIterator(pi2, flatness); - - double[] coords = new double[6]; - double pntx = 0; - double pnty = 0; - double pntz = baselineHeight; - - HashSet set = new HashSet(); - Shape3D shape3D = null; - - Debug.message("3detail", - "OMGraphicUtil.createShape3D(): figuring out coordinates"); - - // Creating the data[] - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - switch (type) { - case PathIterator.SEG_MOVETO: - if (dataIndex != 0) { - shape3D = createShape3D(data, - dataIndex, - stripCount, - color, - filled); - if (shape3D != null) { - set.add(shape3D); - } - data = expandArrayD(bufferSize, null); - dataIndex = 0; - } - case PathIterator.SEG_LINETO: - - // SEG_MOVETO is the first point of - // the shape, SEG_LINETO are the - // middle and end points. SEG_CLOSE - // confirms the close, but we don't - // need it. - pntx = coords[0]; - pnty = coords[1]; - - if (Debug.debugging("3detail")) { - Debug.output("Shape coordinates: " + pntx + ", " + pnty); - } - - // Get Z here, if you want to set the height of the - // coordinate... - // pntz = - - // See if there is space in the buffer. - if (dataIndex >= data.length) { - data = expandArrayD(bufferSize, data); - refreshCounter = bufferSize; - } - - data[dataIndex++] = pntx; - data[dataIndex++] = pntz; - data[dataIndex++] = pnty; - - // data[dataIndex++] = pntx; - // data[dataIndex++] = pnty; - // data[dataIndex++] = pntz; - - stripCount[0]++; - - refreshCounter -= 3; - break; - default: - // Do nothing, because it's a repeat - // of the last SEG_LINETO point. - - Debug.message("3detail", "Shape coordinates: " + coords[0] - + ", " + coords[1] + " rounding out SEG_CLOSE"); - } - - pi.next(); - } - - if (dataIndex != 0) { - shape3D = createShape3D(data, dataIndex, stripCount, color, filled); - if (shape3D != null) { - set.add(shape3D); - } - } - - return set.iterator(); - } - - /** - * Create a Shape3D from raw components. May return null. Assumes - * a stripCount array of size one. - * - * @param data Description of the Parameter - * @param realDataIndex Description of the Parameter - * @param stripCount Description of the Parameter - * @param color Description of the Parameter - * @param filled Description of the Parameter - * @return Description of the Return Value - */ - public static Shape3D createShape3D(double[] data, int realDataIndex, - int[] stripCount, Color color, - boolean filled) { - try { - double[] newData = new double[realDataIndex]; - System.arraycopy(data, 0, newData, 0, realDataIndex); - if (filled) { - return createFilled(newData, stripCount, color); - } else { - return createEdges(newData, color); - } - } catch (java.lang.IllegalArgumentException iae) { - Debug.error("OMGraphicUtil.createShape3D(): IllegalArgumentException caught: \n" - + iae.toString()); - - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < stripCount.length; i++) { - sb.append("{" + stripCount[i] + "}"); - } - - Debug.output("Something funny happened on " - + (filled ? "filled" : "edge") + " data[" + data.length - + "], reflecting " + data.length / 3 - + " nodes, with stripCount[" + stripCount.length + "] " - + sb.toString()); - } - return null; - } - - public static Shape3D createFilled(double[] data, int[] stripCount, - Color color) - throws IllegalArgumentException { - - // j + 1 is the number of shapes. - // Might have to track the number of coordinates per shape. - - // Use a Triangulator to take geometry data and create - // polygons out of it. - Debug.message("3detail", "OMGraphicUtil: adding polygon, data length " - + data.length + ", reflecting " + data.length / 3 - + " nodes, with a strip count of " + stripCount.length); - GeometryInfo gi = new GeometryInfo(GeometryInfo.POLYGON_ARRAY); - gi.setCoordinates(data); - gi.setStripCounts(stripCount); - - Triangulator tr = new Triangulator(); - // Triangulator tr = new Triangulator(1); - Debug.message("3detail", "OMGraphicUtil: begin triangulation"); - tr.triangulate(gi); - Debug.message("3detail", "OMGraphicUtil: end triangulation"); - gi.recomputeIndices(); - - NormalGenerator ng = new NormalGenerator(); - ng.generateNormals(gi); - gi.recomputeIndices(); - - Stripifier st = new Stripifier(); - st.stripify(gi); - gi.recomputeIndices(); - - Shape3D shape3D = new Shape3D(); - shape3D.setAppearance(createMaterialAppearance(color)); - shape3D.setGeometry(gi.getGeometryArray()); - - return shape3D; - } - - public static Shape3D createEdges(double[] data, Color color) - throws IllegalArgumentException { - - int numPoints = data.length / 3; - - // Create a line for the polyline. - Debug.message("3detail", "OMGraphicUtil: adding polyline of " - + numPoints + " points."); - - LineStripArray la = new LineStripArray(numPoints, LineArray.COORDINATES - | LineArray.COLOR_4, new int[] { numPoints }); - - la.setCoordinates(0, data); - Color4b[] colors = createColorArray(numPoints, color); - la.setColors(0, colors); - return new Shape3D(la); - } - - public static Appearance createMaterialAppearance(Color color) { - - Appearance materialAppear = new Appearance(); - - PolygonAttributes polyAttrib = new PolygonAttributes(); - polyAttrib.setCullFace(PolygonAttributes.CULL_NONE); - materialAppear.setPolygonAttributes(polyAttrib); - - Material material = new Material(); - // Might want to look into using a Color4b at some point - material.setAmbientColor(new Color3f(color)); - materialAppear.setMaterial(material); - - return materialAppear; - } - - public static Appearance createWireFrameAppearance(Color color) { - - Appearance materialAppear = new Appearance(); - PolygonAttributes polyAttrib = new PolygonAttributes(); - polyAttrib.setPolygonMode(PolygonAttributes.POLYGON_LINE); - materialAppear.setPolygonAttributes(polyAttrib); - ColoringAttributes redColoring = new ColoringAttributes(); - redColoring.setColor(1.0f, 0.0f, 0.0f); - materialAppear.setColoringAttributes(redColoring); - - return materialAppear; - } - - /** - * Create an array of Color4b objects for an OMGraphic - * representation. The colors in an OMGraphic are ARGB, which is - * why this creates a Color4b object. Since all the parts of an - * OMGraphic are colored the same, create the array of colors to - * be all the same color retrieved from the OMGraphic. - * - * @param size Description of the Parameter - * @param color Description of the Parameter - * @return Description of the Return Value - */ - public static Color4b[] createColorArray(int size, Color color) { - Color4b[] colors = new Color4b[size]; - for (int i = 0; i < size; i++) { - colors[i] = new Color4b(color); - } - return colors; - } - - /** - * Create an array to hold double data for 3d polygons and lines. - * - * @param bufferSize the number of - * - *

-     * points
-     * 
- * - * to buffer. Equals three doubles per point. - * @param currentArray if not null, will create an array the size - * of the current array plus the size needed to hold the - * desired number of points. - * @return a double[]. - */ - public static double[] expandArrayD(int bufferSize, double[] currentArray) { - - if (currentArray == null) { - return new double[bufferSize * 3]; - } - int length = currentArray.length; - double[] ret = new double[length + bufferSize * 3]; - System.arraycopy(currentArray, 0, ret, 0, length); - - return ret; - } - - /** - * Create an array to hold float data for 3d polygons and lines. - * - * @param bufferSize the number of - * - *
-     * points
-     * 
- * - * to buffer. Equals three floats per point. - * @param currentArray if not null, will create an array the size - * of the current array plus the size needed to hold the - * desired number of points. - * @return a float[]. - */ - public static float[] expandArrayF(int bufferSize, float[] currentArray) { - - if (currentArray == null) { - return new float[bufferSize * 3]; - } - int length = currentArray.length; - float[] ret = new float[length + bufferSize * 3]; - System.arraycopy(currentArray, 0, ret, 0, length); - - return ret; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/OMKeyBehavior.java b/src/core/src/main/java/com/bbn/openmap/j3d/OMKeyBehavior.java deleted file mode 100644 index 6316e7031..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/OMKeyBehavior.java +++ /dev/null @@ -1,592 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/tools/j3d/OMKeyBehavior.java,v $ -// $RCSfile: OMKeyBehavior.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/11 19:27:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d; - -import java.awt.AWTEvent; -import java.awt.event.KeyEvent; -import java.util.Enumeration; - -import javax.media.j3d.Behavior; -import javax.media.j3d.Transform3D; -import javax.media.j3d.TransformGroup; -import javax.media.j3d.WakeupCondition; -import javax.media.j3d.WakeupCriterion; -import javax.media.j3d.WakeupOnAWTEvent; -import javax.media.j3d.WakeupOr; -import javax.vecmath.Vector3d; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * OMKeyBehavior is a modified version of KeyBehavior, available from - * http://www.J3D.org. The modifications include having a notion of - * body position, and view position. You can modify a view, which can - * be thought of as where your eyes are pointing. You can also modify - * the position, which can be thought of where your body is pointing. - * So, you can look in a different directin than your motion.This - * allows the user to adjust the view angle to the map, but not have - * it interfere with navigation - for instance, you can look down at - * the ground, but not fly into it, instead keeping a constant - * distance above it. - * - *

- * The controls are: - * - *

- * 
- *  left - turn left
- *  right - turn right
- *  up - move forward
- *  down - move backward
- * 
- *  Cntl left - look down
- *  Cntl right - look up
- *  Cntl up - move up (elevation)
- *  Cntl down - move down (elevation)
- * 
- *  Alt right - move right
- *  Alt left - move left
- *  Alt up - rotate up (movement forward will increase elevation).
- *  Alt down - rotate down (movement forward will decrease elevation).
- * 
- *  
- * 
- * - * From the original KeyBehavier header: - * - *
- * 
- *   KeyBehavior is a generic behavior class to take key presses and move a
- *   TransformGroup through a Java3D scene. The actions resulting from the key strokes
- *   are modified by using the Ctrl, Alt and Shift keys.
- * 
- *   (version 1.0) reconstructed class to make more generic.
- * 
- *  MODIFIED:
- * 
- * 
- *  @author    Andrew AJ Cain, Swinburne University,
- *       Australia <acain@it.swin.edu.au> edited from code
- *       by: Gary S. Moss <moss@arl.mil> U. S. Army Research
- *       Laboratory * CLASS NAME: KeyBehavior PUBLIC
- *       FEATURES: // Data // Constructors // Methods:
- *       COLLABORATORS: 
- * 
- * - * @version 1.0, 25 September 1998 aajc - */ -public class OMKeyBehavior extends Behavior { - - protected final static double FAST_SPEED = 2.0; - protected final static double NORMAL_SPEED = 1.0; - protected final static double SLOW_SPEED = 0.5; - - private TransformGroup cameraTransformGroup; - private Transform3D transform3D; - private Transform3D locationTransform3D; - private Transform3D xRotLookTransform; - private Transform3D yRotLookTransform; - private Transform3D zRotLookTransform; - - private WakeupCondition keyCriterion; - - protected final static double TWO_PI = (2.0 * Math.PI); - protected double rotateXAmount = Math.PI / 16.0; - protected double rotateYAmount = Math.PI / 16.0; - protected double rotateZAmount = Math.PI / 16.0; - - protected double moveRate = 0.3; - protected double speed = NORMAL_SPEED; - - protected int forwardKey = KeyEvent.VK_UP; - protected int backKey = KeyEvent.VK_DOWN; - protected int leftKey = KeyEvent.VK_LEFT; - protected int rightKey = KeyEvent.VK_RIGHT; - - protected boolean DEBUG = false; - - protected Projection projection; - - public OMKeyBehavior(TransformGroup cameraTG, Projection proj) { - this(cameraTG, proj, null); - } - - public OMKeyBehavior(TransformGroup cameraTG, Projection proj, - Vector3d initialLocation) { - - projection = proj; - - DEBUG = Debug.debugging("3dkey"); - - cameraTransformGroup = cameraTG; - transform3D = new Transform3D(); - locationTransform3D = new Transform3D(); - - // These are the looking transforms, for the view. - xRotLookTransform = new Transform3D(); - yRotLookTransform = new Transform3D(); - zRotLookTransform = new Transform3D(); - - setViewerLocation(initialLocation); - setEnable(true); - } - - public void initialize() { - WakeupCriterion[] keyEvents = new WakeupCriterion[2]; - - keyEvents[0] = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED); - keyEvents[1] = new WakeupOnAWTEvent(KeyEvent.KEY_RELEASED); - - keyCriterion = new WakeupOr(keyEvents); - wakeupOn(keyCriterion); - } - - public void setViewerLocation(Vector3d initialLocation) { - cameraTransformGroup.getTransform(locationTransform3D); - - // scale of < 1 shrinks the object. (.5) is the scale. - float scale = 1f; - - if (initialLocation == null) { - - initialLocation = new Vector3d(); - - // So, this lays out where the land is, in relation to the - // viewer. We should get the projection from the MapBean, - // and - // offset the transform to the middle of the map. - if (projection != null) { - float centerXOffset = projection.getWidth() / 2f * scale; - float centerYOffset = projection.getHeight() * 2 / 3f * scale; - - Debug.message("3d", "OM3DViewer with projection " + projection - + ", setting center of scene to " + centerXOffset - + ", " + centerYOffset); - - initialLocation.set((double) centerXOffset, - (double) 50, - (double) centerYOffset); - } else { - initialLocation.set(0.0, 50, 0.0); - } - } - - Transform3D toMove = new Transform3D(); - toMove.set(scale, initialLocation); - locationTransform3D.mul(toMove); - cameraTransformGroup.setTransform(locationTransform3D); - } - - public void processStimulus(Enumeration criteria) { - - if (DEBUG) { - Debug.output("OMKeyBehavior: processStimulus"); - } - - WakeupCriterion wakeup; - AWTEvent[] event; - - while (criteria.hasMoreElements()) { - wakeup = (WakeupCriterion) criteria.nextElement(); - - if (!(wakeup instanceof WakeupOnAWTEvent)) { - continue; - } - - event = ((WakeupOnAWTEvent) wakeup).getAWTEvent(); - - for (int i = 0; i < event.length; i++) { - if (event[i].getID() == KeyEvent.KEY_PRESSED) { - processKeyEvent((KeyEvent) event[i]); - } - } - } - wakeupOn(keyCriterion); - } - - protected void processKeyEvent(KeyEvent event) { - int keycode = event.getKeyCode(); - - if (event.isShiftDown()) { - speed = FAST_SPEED; - } else { - speed = NORMAL_SPEED; - } - - if (event.isAltDown()) { - altMove(keycode); - } else if (event.isControlDown()) { - controlMove(keycode); - } else { - standardMove(keycode); - } - } - - //moves forward backward or rotates left right - protected void standardMove(int keycode) { - if (keycode == forwardKey) { - moveForward(); - } else if (keycode == backKey) { - moveBackward(); - } else if (keycode == leftKey) { - rotLeft(); - } else if (keycode == rightKey) { - rotRight(); - } - } - - //moves left right, rotate up down - protected void altMove(int keycode) { - if (DEBUG) { - Debug.output("altMove"); - } - if (keycode == forwardKey) { - rotUp(); - } else if (keycode == backKey) { - rotDown(); - } else if (keycode == leftKey) { - moveLeft(); - } else if (keycode == rightKey) { - moveRight(); - } - } - - //move up down, rot left right - protected void controlMove(int keycode) { - - if (keycode == forwardKey) { - moveUp(); - } else if (keycode == backKey) { - moveDown(); - } else if (keycode == leftKey) { - // rollLeft(); - lookUp(); - } else if (keycode == rightKey) { - // rollRight(); - lookDown(); - } - } - - public void moveForward() { - if (DEBUG) { - Debug.output("Moving forward +"); - } - doMove(new Vector3d(0.0, 0.0, -getMovementRate())); - } - - public void moveBackward() { - if (DEBUG) { - Debug.output("Moving Backward _"); - } - doMove(new Vector3d(0.0, 0.0, getMovementRate())); - } - - public void moveLeft() { - if (DEBUG) { - Debug.output("Moving left <"); - } - doMove(new Vector3d(-getMovementRate(), 0.0, 0.0)); - } - - public void moveRight() { - if (DEBUG) { - Debug.output("Moving right >"); - } - doMove(new Vector3d(getMovementRate(), 0.0, 0.0)); - } - - public void moveUp() { - if (DEBUG) { - Debug.output("Moving up ^"); - } - doMove(new Vector3d(0.0, getMovementRate(), 0.0)); - } - - public void moveDown() { - if (DEBUG) { - Debug.output("Moving down v "); - } - doMove(new Vector3d(0.0, -getMovementRate(), 0.0)); - } - - public void rotRight() { - if (DEBUG) { - Debug.output("Rotating right"); - } - doRotateY(getRotateRightAmount()); - } - - public void lookRight() { - if (DEBUG) { - Debug.output("Looking right"); - } - doLookY(getRotateRightAmount()); - } - - public void rotUp() { - if (DEBUG) { - Debug.output("Rotating up"); - } - doRotateX(getRotateUpAmount()); - } - - public void lookUp() { - if (DEBUG) { - Debug.output("Looking up"); - } - doLookX(getRotateUpAmount()); - } - - public void rotLeft() { - if (DEBUG) { - Debug.output("Rotating left"); - } - doRotateY(getRotateLeftAmount()); - } - - public void lookLeft() { - if (DEBUG) { - Debug.output("Looking left"); - } - doLookY(getRotateLeftAmount()); - } - - public void rotDown() { - if (DEBUG) { - Debug.output("Rotating down"); - } - doRotateX(getRotateDownAmount()); - } - - public void lookDown() { - if (DEBUG) { - Debug.output("Looking down"); - } - doLookX(getRotateDownAmount()); - } - - /** - * Rotating position on the z axis, negative. - */ - public void rollLeft() { - if (DEBUG) { - Debug.output("Rolling left"); - } - doRotateZ(getRollLeftAmount()); - } - - /** - * Tilting the view to the left. - */ - public void rollLookLeft() { - if (DEBUG) { - Debug.output("Tilting left"); - } - doLookZ(getRollLeftAmount()); - } - - /** - * Rotating position on the z axis, positive. - */ - public void rollRight() { - if (DEBUG) { - Debug.output("Rolling right"); - } - doRotateZ(getRollRightAmount()); - } - - /** - * Tilting the view to the right. - */ - public void rollLookRight() { - if (DEBUG) { - Debug.output("Tilting right"); - } - doLookZ(getRollRightAmount()); - } - - protected void changePosition(Transform3D toMove) { - cameraTransformGroup.getTransform(transform3D); - - // Gather the total look transform on all three axis - Transform3D viewTransform = new Transform3D(); - viewTransform.invert(xRotLookTransform); - viewTransform.mulInverse(yRotLookTransform); - viewTransform.mulInverse(zRotLookTransform); - - transform3D.mul(viewTransform); - transform3D.mul(toMove); - - // May have to create and multiply the non-inverse look - // transforms. - transform3D.mulInverse(viewTransform); - - cameraTransformGroup.setTransform(transform3D); - } - - public void doRotateY(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating Y " + radians + " radians"); - } - Transform3D toMove = new Transform3D(); - toMove.rotY(radians); - changePosition(toMove); - } - - public void doLookY(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating view Y " + radians - + " radians"); - } - cameraTransformGroup.getTransform(transform3D); - Transform3D toMove = new Transform3D(); - toMove.rotY(radians); - transform3D.mul(toMove); - cameraTransformGroup.setTransform(transform3D); - - //Keep track of the view y rotation. - yRotLookTransform.mul(toMove); - } - - public void doRotateX(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating X " + radians + " radians"); - } - Transform3D toMove = new Transform3D(); - toMove.rotX(radians); - changePosition(toMove); - } - - public void doLookX(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating view X " + radians - + " radians"); - } - cameraTransformGroup.getTransform(transform3D); - Transform3D toMove = new Transform3D(); - toMove.rotX(radians); - transform3D.mul(toMove); - cameraTransformGroup.setTransform(transform3D); - - //Keep track of the view x rotation. - xRotLookTransform.mul(toMove); - } - - public void doRotateZ(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating Z " + radians + " radians"); - } - Transform3D toMove = new Transform3D(); - toMove.rotZ(radians); - changePosition(toMove); - } - - public void doLookZ(double radians) { - if (DEBUG) { - Debug.output("OMKeyBehavior: rotating view Z " + radians - + " radians"); - } - cameraTransformGroup.getTransform(transform3D); - Transform3D toMove = new Transform3D(); - toMove.rotZ(radians); - transform3D.mul(toMove); - cameraTransformGroup.setTransform(transform3D); - - //Keep track of the view z rotation. - zRotLookTransform.mul(toMove); - } - - public void doMove(Vector3d theMove) { - if (DEBUG) { - Debug.output("OMKeyBehavior: moving " + theMove); - Debug.output(" transform before:\n " + transform3D); - } - - Transform3D toMove = new Transform3D(); - toMove.setTranslation(theMove); - changePosition(toMove); - } - - public double getMovementRate() { - return moveRate * speed; - } - - public double getRollLeftAmount() { - return rotateZAmount * speed; - } - - public double getRollRightAmount() { - return -rotateZAmount * speed; - } - - public double getRotateUpAmount() { - return rotateYAmount * speed; - } - - public double getRotateDownAmount() { - return -rotateYAmount * speed; - } - - public double getRotateLeftAmount() { - return rotateYAmount * speed; - } - - public double getRotateRightAmount() { - return -rotateYAmount * speed; - } - - public void setRotateXAmount(double radians) { - rotateXAmount = radians; - } - - public void setRotateYAmount(double radians) { - rotateYAmount = radians; - } - - public void setRotateZAmount(double radians) { - rotateZAmount = radians; - } - - public void setMovementRate(double meters) { - moveRate = meters; - // Travel rate in meters/frame - } - - public void setForwardKey(int key) { - forwardKey = key; - } - - public void setBackKey(int key) { - backKey = key; - } - - public void setLeftKey(int key) { - leftKey = key; - } - - public void setRightKey(int key) { - rightKey = key; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/UniverseManager.java b/src/core/src/main/java/com/bbn/openmap/j3d/UniverseManager.java deleted file mode 100644 index 526eec460..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/UniverseManager.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 1999 Justin Couch Java Source Raw J3D - * Tutorial Version History Date Version Programmer - * ---------- ------- ------------------------------------------ - * 01/08/1998 1.0.0 Justin Couch - */ - -package com.bbn.openmap.j3d; - -import javax.media.j3d.BranchGroup; -import javax.media.j3d.Group; -import javax.media.j3d.Locale; -import javax.media.j3d.Node; -import javax.media.j3d.VirtualUniverse; - -/** - * Test class for representing a universe - *

- * - * Basic universe consisting of a default Locale and three branch - * graphs for objects that exist in the display and world spaces, as - * well as a separate branch for cameras. - * - * @author Justin Couch - * @version Who Cares! - */ -public class UniverseManager extends VirtualUniverse { - - private Locale locale; - private BranchGroup view_group; - private BranchGroup world_object_group; - - /** - * Create the basic universe and all of the supporting - * infrastructure that is needed by a J3D application. The default - * setup just uses a single local located at the origin. - */ - public UniverseManager() { - this(null); - } - - /** - * Create the basic universe and all of the supporting - * infrastructure that is needed by a J3D application. The default - * setup just uses a single local located at the origin. - * - * @param worldGroup Description of the Parameter - */ - public UniverseManager(BranchGroup worldGroup) { - locale = new Locale(this); - - view_group = new BranchGroup(); - view_group.setCapability(Group.ALLOW_CHILDREN_EXTEND); - - if (worldGroup == null) { - world_object_group = new BranchGroup(); - world_object_group.setCapability(Group.ALLOW_CHILDREN_EXTEND); - } else { - world_object_group = worldGroup; - } - } - - /** - * Add a camera to the world. - * - * @param cam The camera that may be added - */ - public void addCamera(Camera cam) { - view_group.addChild(cam.getNode()); - } - - /** - * Add an object to the world object group. - * - * @param node The node that may be added - */ - public void addWorldObject(Node node) { - world_object_group.addChild(node); - } - - public BranchGroup getWorldBranchGroup() { - return world_object_group; - } - - /** - * Make the universe live by adding the objects to the locale - */ - public void makeLive() { - view_group.compile(); - world_object_group.compile(); - - locale.addBranchGraph(view_group); - locale.addBranchGraph(world_object_group); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/Curtain.java b/src/core/src/main/java/com/bbn/openmap/j3d/geometry/Curtain.java deleted file mode 100644 index 5abc560a9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/Curtain.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.bbn.openmap.j3d.geometry; - -import java.awt.Color; -import java.util.HashSet; -import java.util.Iterator; - -import javax.media.j3d.Shape3D; - -import com.bbn.openmap.MapHandlerChild; -import com.bbn.openmap.j3d.MapContent; -import com.bbn.openmap.j3d.OM3DGraphicHandler; -import com.bbn.openmap.j3d.OMGraphicUtil; -import com.bbn.openmap.proj.Projection; - -/** - * The curtain class is just a set of planes around the projection - * boundaries in the map. OpenMap depends on the MapBean clipping for - * not drawing things on the map. Unfortunately, this means that some - * leftovers can appear in the 3D scene. Use this class to create a 3D - * barrier that will hide those leftovers. - * - * @author dietrick - */ -public class Curtain extends MapHandlerChild implements OM3DGraphicHandler { - - /** - * The color of the curtains. - */ - protected Color color = Color.lightGray; - - Iterator curtains = null; - - /** - * An amount to add (or subtract) from the projection boundaries. - */ - protected double extra = 0; - - /** - * The height of the box. Default is 500. - */ - protected double curtainHeight = 500; - - public Curtain() {} - - public void addGraphicsToScene(MapContent mapContent) { - - if (curtains == null) { - curtains = init(mapContent.getProjection()); - } - - while (curtains.hasNext()) { - mapContent.add((Shape3D) curtains.next()); - } - - curtains = null; - } - - protected Iterator init(Projection proj) { - - HashSet set = new HashSet(); - - double width = (double) proj.getWidth() + extra; - double depth = (double) proj.getHeight() + extra; - double height = curtainHeight + extra; - - // The lower left corner value, or the value of zero. - double origin = 0 - extra; - - double[] data = new double[60]; - - data[0] = origin; - //width - data[1] = origin; - //depth - data[2] = origin; - //height - data[3] = width; - data[4] = origin; - data[5] = origin; - data[6] = width; - data[7] = depth; - data[8] = origin; - data[9] = origin; - data[10] = depth; - data[11] = origin; - - data[12] = width; - data[13] = origin; - data[14] = origin; - data[15] = width; - data[16] = depth; - data[17] = origin; - data[18] = width; - data[19] = depth; - data[20] = height; - data[21] = width; - data[22] = origin; - data[23] = height; - - data[24] = width; - data[25] = depth; - data[26] = origin; - data[27] = width; - data[28] = depth; - data[29] = height; - data[30] = origin; - data[31] = depth; - data[32] = height; - data[33] = origin; - data[34] = depth; - data[35] = origin; - - data[36] = origin; - data[37] = origin; - data[38] = origin; - data[39] = origin; - data[40] = origin; - data[41] = height; - data[42] = origin; - data[43] = depth; - data[44] = height; - data[45] = origin; - data[46] = depth; - data[47] = origin; - - data[48] = origin; - data[49] = origin; - data[50] = height; - data[51] = width; - data[52] = origin; - data[53] = height; - data[54] = width; - data[55] = depth; - data[56] = height; - data[57] = origin; - data[58] = depth; - data[59] = height; - - int[] stripCount = new int[5]; - stripCount[0] = 4; - stripCount[1] = 4; - stripCount[2] = 4; - stripCount[3] = 4; - stripCount[4] = 4; - - int dataIndex = 0; - int[] sc = new int[1]; - - for (int i = 0; i < stripCount.length; i++) { - - double[] temp = new double[12]; - sc[0] = stripCount[i]; - - System.arraycopy(data, dataIndex, temp, 0, 12); - - set.add(OMGraphicUtil.createFilled(temp, sc, color)); - - dataIndex += 12; - } - - return set.iterator(); - } - - public void setColor(Color curtainColor) { - color = curtainColor; - } - - public Color getColor() { - return color; - } - - public void setCurtainHeight(double height) { - curtainHeight = height; - } - - public double getCurtainHeight() { - return curtainHeight; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/GridTester.java b/src/core/src/main/java/com/bbn/openmap/j3d/geometry/GridTester.java deleted file mode 100644 index a69016725..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/GridTester.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.bbn.openmap.j3d.geometry; - -import java.awt.Color; - -import com.bbn.openmap.j3d.MapContent; -import com.bbn.openmap.j3d.OM3DGraphicHandler; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.SimpleColorGenerator; - -public class GridTester implements OM3DGraphicHandler { - - OMGrid grid; - - public GridTester() { - - int[][] data = new int[][] { new int[] { 10, 10, 10, 10, 10 }, - new int[] { 10, 51, 51, 51, 10 }, - new int[] { 10, 51, 102, 51, 10 }, - new int[] { 10, 51, 51, 51, 10 }, - new int[] { 10, 10, 10, 10, 10 } }; - - // int[][] data = new int[][] { - // new int[] {10, 10, 10, 10, 10}, - // new int[] {10, 20, 20, 20, 10}, - // new int[] {10, 20, 30, 20, 10}, - // new int[] {10, 20, 20, 20, 10}, - // new int[] {10, 10, 10, 10, 10}}; - - grid = new OMGrid(43f, -72f, .5f, .5f, data); - grid.setLinePaint(java.awt.Color.red); - grid.setFillPaint(OMColor.clear); - - // grid.setGenerator(new GridTesterGenerator()); - } - - /** - * Provide a MapContent object for the OM3DGraphicHandler to add - * objects to. The MapContent object as three add() methods, one - * for OMGraphics, one for OMGrid specifically, and one for - * Shape3D objects. The OM3DGraphicHandler should go through its - * graphics and add them to this MapContext object. - * - * @param mapContent The feature to be added to the - * GraphicsToScene attribute - */ - public void addGraphicsToScene(MapContent mapContent) { - mapContent.add(grid); - } - - protected class GridTesterGenerator extends SimpleColorGenerator { - - public GridTesterGenerator() {} - - public int calibratePointValue(int source) { - - if (source > 200) { - return Color.red.getRGB(); - } - if (source > 150) { - return Color.orange.getRGB(); - } - if (source > 125) { - return Color.yellow.getRGB(); - } - if (source > 100) { - return Color.green.getRGB(); - } - if (source > 75) { - return Color.blue.getRGB(); - } - if (source > 50) { - return Color.magenta.getRGB(); - } - return Color.lightGray.getRGB(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/SphereBox.java b/src/core/src/main/java/com/bbn/openmap/j3d/geometry/SphereBox.java deleted file mode 100644 index e9c6aa11f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/SphereBox.java +++ /dev/null @@ -1,141 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: SphereBox.java,v $ -//$Revision: 1.1 $ -//$Date: 2006/04/07 17:44:36 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.j3d.geometry; - -import javax.vecmath.Point3d; - -import com.bbn.openmap.j3d.J3DGeo; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class SphereBox { - - LatLonPoint upper; - LatLonPoint lower; - double lowerElevation; - double upperElevation; - - public SphereBox() { - lowerElevation = Double.POSITIVE_INFINITY; - upperElevation = Double.NEGATIVE_INFINITY; - } - - public SphereBox(Point3d lower, Point3d upper) { - init(new J3DGeo(lower.x, lower.y, lower.z)); - add(upper); - } - - public SphereBox(J3DGeo lower, J3DGeo upper) { - init(lower); - add(upper); - } - - public SphereBox(SphereBox sBox) { - this.upper = sBox.upper; - this.lower = sBox.lower; - lowerElevation = sBox.lowerElevation; - upperElevation = sBox.upperElevation; - } - - public void init(J3DGeo lower) { - this.lower = new LatLonPoint.Double(lower.getLatitudeRadians(), lower.getLongitudeRadians(), true); - this.upper = new LatLonPoint.Double(lower.getLatitudeRadians(), lower.getLongitudeRadians(), true); - lowerElevation = lower.length(); - upperElevation = lowerElevation; - } - - public J3DGeo getLower() { - if (lower != null) { - return new J3DGeo(lower.getRadLat(), lower.getRadLon(), false, lowerElevation); - } - - return null; - } - - public J3DGeo getUpper() { - if (upper != null) { - return new J3DGeo(upper.getRadLat(), upper.getRadLon(), false, upperElevation); - } - - return null; - } - - public void add(Point3d pt) { - add(new J3DGeo(pt.x, pt.y, pt.z)); - } - - public void add(J3DGeo pt) { - - if (lower == null) { - init(pt); - return; - } - - double llat = lower.getRadLat(); - double llon = lower.getRadLon(); - double ulat = upper.getRadLat(); - double ulon = upper.getRadLon(); - - double lat = pt.getLatitudeRadians(); - double lon = pt.getLongitudeRadians(); - double elev = pt.length(); - - if (lat < llat) { - llat = lat; - } - - if (lat > ulat) { - ulat = lat; - } - - if (lon < llon) { - llon = lon; - } - - if (lon > ulon) { - ulon = lon; - } - - if (elev < lowerElevation) { - lowerElevation = elev; - } - - if (elev > upperElevation) { - upperElevation = elev; - } - - upper.setLatLon(ulat, ulon, true); - lower.setLatLon(llat, llon, true); - } - - public void add(SphereBox sBox) { - J3DGeo lg = sBox.getLower(); - J3DGeo ug = sBox.getUpper(); - if (lg != null) - add(lg); - if (ug != null) - add(ug); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/package.html b/src/core/src/main/java/com/bbn/openmap/j3d/geometry/package.html deleted file mode 100644 index 8bf3afd04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/geometry/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The com.bbn.openmap.tools.j3d.geometry package holds components that -can create their unique Shape3D objects to add to Java 3D scenes. - - diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/launcher.gif b/src/core/src/main/java/com/bbn/openmap/j3d/launcher.gif deleted file mode 100644 index 372aca38d..000000000 Binary files a/src/core/src/main/java/com/bbn/openmap/j3d/launcher.gif and /dev/null differ diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/package.html b/src/core/src/main/java/com/bbn/openmap/j3d/package.html deleted file mode 100644 index 83946283f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/package.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The com.bbn.openmap.tools.j3d package holds components that can create -a 3D scene, with a viewer, from OpenMap maps. The Java3D package, -distributed separately and requiring it's own installation, is -required for all classes in this package.

- -The Manager classes create the 3D scene, setting up the camera -(Viewing Platform), universe, and all the BranchGroups containing map -information. The MapContentManager is the basic manager, providing a -view that can be controlled with keyboard strokes. The -ControlledManager is an extended manager class, which provides a -viewer controlled by external code.

- -All Managers need a content mask - and each decided what content to -add based on the settings in the mask. For this initial release, the -3D scene can be created from OpenMap components in a couple of -different ways:

- -

    -
  • OM3DConstants.CONTENT_MASK_OMGRAPHICHANDLERLAYERS - The manager -will use a MapContent object that uses -com.bbn.openmap.layers.OMGraphicHandlerLayers to get OMGraphics to -convert to Shape3D objects. -
  • OM3DConstants.CONTENT_MASK_OM3DGRAPHICHANDLERS - The manager will -will use a MapContent object that contacts OM3DGraphicHandler objects, -to let them know what MapContent object they should add scene objects -to. They have different options for doing this. -
  • OM3DConstants.CONTENT_MASK_IMAGEMAP - The manager will take all -the layers and paint themselves into an image to be used as a texture -for a flat plane. This is not entirely implemented yet. -
  • OM3DConstants.CONTENT_MASK_ELEVATIONMAP - The manager will use a -DTEDFrameCache to create an OMGrid object to use to build a terrain, -and then fill the terrain with whatever is painted on the map. This -is also not implemented, yet. -
- -

Thanks to the guys at j3d.org (Justin Couch) for all their work in creating a -great informational site, and for putting code examples up. There is -a lot if their code sprinkled around in this package. - - diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/Pilot.java b/src/core/src/main/java/com/bbn/openmap/j3d/pilot/Pilot.java deleted file mode 100644 index e07ee2353..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/Pilot.java +++ /dev/null @@ -1,281 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/plugin/pilot/Pilot.java,v $ -// $RCSfile: Pilot.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/02/23 22:37:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d.pilot; - -import java.awt.Color; -import java.awt.GridLayout; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.geom.Point2D; - -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.InternalFrameAdapter; -import javax.swing.event.InternalFrameEvent; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * The Pilot is the base class representing a location over the map. - */ -public class Pilot extends OMPoint implements ActionListener, FocusListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - public static Color CONNECTED_COLOR = Color.green; - public static Color DISCONNECTED_COLOR = Color.red; - /** Flag to mark whether the pilot is moving or not. */ - protected boolean stationary = true; - protected String name; - protected double height = 0;// meters. - - public Pilot(double lat, double lon, int radius, boolean isOval) { - super(lat, lon, radius); - setOval(isOval); - } - - /** Really has no meaning, other than to set the color. */ - public void resetConnected() { - setFillPaint(DISCONNECTED_COLOR); - } - - /** Really has no meaning, other than to set the color. */ - public void connected(boolean connected) { - if (connected) { - setFillPaint(CONNECTED_COLOR); - } - } - - /** - * A little method that will cause the location to move around a - * little. - */ - protected void moveRandomly(float factor) { - double hor = Math.random() - .5; - double vert = Math.random() - .5; - - setLat(getLat() + (float) vert / factor); - setLon(getLon() + (float) hor / factor); - } - - /** - * If not stationary, then the location will move around randomly - * to a different location. - */ - public void move(float factor) { - if (!stationary) { - moveRandomly(factor); - } - } - - public void move(int distance, Length units, float Az) { - Point2D newLocation = GreatCircle.sphericalBetween(ProjMath.degToRad(getLat()), - ProjMath.degToRad(getLon()), - units.toRadians(distance), - Az); - - setLat((float) newLocation.getY()); - setLon((float) newLocation.getX()); - } - - public void setStationary(boolean set) { - stationary = set; - if (movementButton != null) { - movementButton.setSelected(set); - } - } - - public boolean getStationary() { - return stationary; - } - - public void setName(String set) { - name = set; - } - - public String getName() { - return name; - } - - public void setHeight(double h) { - height = h; - if (heightField != null) { - heightField.setText(Double.toString(h)); - } - if (Debug.debugging("pilotloader")) { - Debug.output("Pilot: " + getName() + " setting height to : " + h); - } - } - - public double getHeight() { - return height; - } - - protected transient java.awt.Container palette = null; - - /** - * Make the palette visible. Will automatically determine if we're - * running in an applet environment and will use a JInternalFrame - * over a JFrame if necessary. - */ - public void showPalette() { - if (Environment.getBoolean(Environment.UseInternalFrames)) { - - final JLayeredPane desktop = Environment.getInternalFrameDesktop(); - - // get the window - palette = PaletteHelper.getPaletteInternalWindow(getGUI(), - getName(), - new InternalFrameAdapter() { - public void internalFrameClosed(InternalFrameEvent e) { - if (desktop != null) { - desktop.remove((JInternalFrame) palette); - desktop.repaint(); - } - palette = null; - // firePaletteEvent(false); - } - }); - // add the window to the desktop - if (desktop != null) { - desktop.add(palette); - palette.setVisible(true); - } - } else { - if (palette == null) { - palette = PaletteHelper.getPaletteWindow(getGUI(), - getName(), - new ComponentAdapter() { - public void componentHidden(ComponentEvent e) { - // firePaletteEvent(false); - } - }); - } - palette.setVisible(true); - ((JFrame) palette).setState(java.awt.Frame.NORMAL); - } - } - - /** - * Hide the Pilot's palette. - */ - public void hidePalette() { - if (palette == null) { - return; - } - - if (Environment.getBoolean(Environment.UseInternalFrames)) { - // close the palette - try { - ((JInternalFrame) palette).setClosed(true); - } catch (java.beans.PropertyVetoException evt) { - com.bbn.openmap.util.Assert.assertExp(false, - "Pilot.hidePalette(): internal error!"); - } - } else { - palette.setVisible(false); - } - } - - JCheckBox movementButton = null; - JTextField heightField = null; - - /** - * Gets the gui controls associated with the Pilot. This default - * implementation returns null indicating that the Pilot has no - * gui controls. - * - * @return java.awt.Component or null - */ - public java.awt.Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - - // Only want to do this once... - if (movementButton == null) { - movementButton = new JCheckBox("Stationary", getStationary()); - movementButton.addActionListener(this); - movementButton.setActionCommand(MoveCmd); - } - - panel.add(movementButton); - - JPanel heightPanel = new JPanel(new GridLayout(0, 3)); - - heightPanel.add(new JLabel("Object height: ")); - if (heightField == null) { - heightField = new JTextField(Double.toString(height), 10); - heightField.setHorizontalAlignment(JTextField.RIGHT); - heightField.addActionListener(this); - heightField.addFocusListener(this); - } - heightPanel.add(heightField); - heightPanel.add(new JLabel(" meters")); - - panel.add(heightPanel); - - return panel; - } - - public final static String MoveCmd = "MoveCommand"; - - public void actionPerformed(java.awt.event.ActionEvent ae) { - String cmd = ae.getActionCommand(); - if (cmd == MoveCmd) { - JCheckBox check = (JCheckBox) ae.getSource(); - setStationary(check.isSelected()); - } else { - try { - setHeight(Float.parseFloat(cmd)); - } catch (NumberFormatException nfe) { - setHeight(getHeight()); - } - } - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) { - try { - setHeight(Float.parseFloat(((JTextField) (e.getSource())).getText())); - } catch (NumberFormatException nfe) { - setHeight(0); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoader.java b/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoader.java deleted file mode 100644 index 421805094..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoader.java +++ /dev/null @@ -1,276 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/plugin/pilot/PilotLoader.java,v $ -// $RCSfile: PilotLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/02/23 22:37:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d.pilot; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionListener; -import java.util.HashMap; -import java.util.Iterator; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.graphicLoader.MMLGraphicLoader; -import com.bbn.openmap.omGraphics.BasicStrokeEditor; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; - -/** - * The PilotLoader is a managing object that pushes Pilots and - * PilotPaths to the PilotLoaderPlugIn for display on the map. - */ -public class PilotLoader extends MMLGraphicLoader implements ActionListener, - DrawingToolRequestor { - - protected OMDrawingTool dt = null; - - public final static String AddNodeCmd = "AddNodeCommand"; - public final static String AddPathCmd = "AddPathCommand"; - - HashMap points = new HashMap(); - - public PilotLoader() { - super(); - } - - public PilotLoader(OMGraphicHandler receiver) { - this(); - - this.receiver = receiver; - // getTimer().start(); - // Debug.message("pilotLoader", "PilotLoader starting timer"); - } - - public void manageGraphics() { - OMGraphicList list = new OMGraphicList(); - - Iterator it = points.values().iterator(); - Pilot mp; - - while (it.hasNext()) { - mp = (Pilot) it.next(); - mp.move(40f); - mp.resetConnected(); - list.add(mp); - } - - if (receiver != null) { - Debug.message("pilotloader", - "PilotLoader.manageGraphics: Updating graphics."); - receiver.setList(list); - } else { - Debug.message("pilotloader", - "PilotLoader.manageGraphics: no receiver to notify."); - } - } - - public void actionPerformed(java.awt.event.ActionEvent ae) { - String cmd = ae.getActionCommand(); - if (cmd == TimerCmd) { - JCheckBox check = (JCheckBox) ae.getSource(); - if (check.isSelected()) { - timer.restart(); - } else { - timer.stop(); - } - } else if (cmd == AddNodeCmd) { - if (dt != null) { - GraphicAttributes ga = new GraphicAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - OMPoint pt = (OMPoint) dt.create("com.bbn.openmap.omGraphics.OMPoint", - ga, - this, - false); - if (pt != null) { - getTimer().stop(); - pt.setRadius(5); - pt.setOval(true); - pt.setFillPaint(Color.red); -// addNodeButton.setEnabled(false); - addPathButton.setEnabled(false); - } - } - } else if (cmd == AddPathCmd) { - if (dt != null) { - GraphicAttributes ga = new GraphicAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - OMPoly poly = (OMPoly) dt.create("com.bbn.openmap.omGraphics.OMPoly", - ga, - this, - true); - if (poly != null) { - getTimer().stop(); - BasicStrokeEditor bse = new BasicStrokeEditor(); - bse.setDash(new float[] { 5, 5 }); - ga.setStroke(bse.getBasicStroke()); - ga.setLinePaint(Color.yellow); - - // addNodeButton.setEnabled(false); - addPathButton.setEnabled(false); - } - } - } - - manageGraphics(); - } - - /** - * MapHandlerChild methods modified to look for the OMDrawingTool. - */ - public void findAndInit(Object obj) { - if (obj instanceof OMDrawingTool) { - Debug.message("graphicloader", - "LOSGraphicLoader: found OMDrawingTool"); - setDrawingTool((OMDrawingTool) obj); - } - } - - /** - * MapHandlerChild methods modified to look for the OMDrawingTool. - */ - public void findAndUndo(Object obj) { - if (obj instanceof OMDrawingTool) { - Debug.message("graphicloader", - "LOSGraphicLoader: removing OMDrawingTool"); - OMDrawingTool odt = getDrawingTool(); - if (odt == obj) { - setDrawingTool(null); - } - } - } - - public void setDrawingTool(OMDrawingTool drawingTool) { - dt = drawingTool; -// if (addNodeButton != null) { -// addNodeButton.setEnabled(drawingTool != null); -// } - if (addPathButton != null) { - addPathButton.setEnabled(drawingTool != null); - } - } - - public OMDrawingTool getDrawingTool() { - return dt; - } - - JCheckBox timerButton = null; - //JButton addNodeButton = null; - JButton addPathButton = null; - - public Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - - // if (addNodeButton == null) { - // addNodeButton = new JButton("Add Node..."); - // addNodeButton.addActionListener(this); - // addNodeButton.setActionCommand(AddNodeCmd); - // } - - // addNodeButton.setEnabled(getDrawingTool() != null); - - if (addPathButton == null) { - addPathButton = new JButton("Add Path for Pilot"); - addPathButton.addActionListener(this); - addPathButton.setActionCommand(AddPathCmd); - } - - if (getDrawingTool() == null) { - addPathButton.setEnabled(false); - addPathButton.setToolTipText("Drawing Tool not connected, can't create Pilot path."); - } else { - addPathButton.setToolTipText("Click to use Drawing Tool to create Pilot path."); - } - - // panel.add(addNodeButton); - panel.add(addPathButton); - - // Only want to do this once... - if (timerButton == null) { - timerButton = new JCheckBox("Run Timer", getTimer().isRunning()); - timerButton.addActionListener(this); - timerButton.setActionCommand(TimerCmd); - } - - panel.add(timerButton); - - return panel; - } - - public static int pointCount = 1; - - /** - * The method where a graphic, and an action to take on the - * graphic, arrives. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - if (timerButton.isSelected()) { - timer.restart(); - } - - if (omg instanceof OMPoint) { - - OMPoint p = (OMPoint) omg; - - Pilot mp = new Pilot(p.getLat(), p.getLon(), p.getRadius(), true); - mp.setName("Added Node " + (pointCount++)); - mp.setStationary(true); - mp.showPalette(); - points.put(mp.getName(), mp); - manageGraphics(); - } else if (omg instanceof OMPoly) { - OMPoly poly = (OMPoly) omg; - PilotPath pmp = new PilotPath(poly, 5, true); - pmp.setName("Added Node " + (pointCount++)); - pmp.setStationary(true); - pmp.showPalette(); - points.put(pmp.getName(), pmp); - pmp.setMapHandler((MapHandler) getBeanContext()); - manageGraphics(); - } - - // addNodeButton.setEnabled(true); - addPathButton.setEnabled(true); - } - - /** - * Needed to fill in a GUI with a receiver's name, to enable the - * user to send a graphic to a specific object. Should be a pretty - * name, suitable to let a user know what it is. - */ - public String getName() { - return ""; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoaderLayer.java b/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoaderLayer.java deleted file mode 100644 index 0dfd7b1cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotLoaderLayer.java +++ /dev/null @@ -1,159 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/plugin/pilot/PilotLoaderPlugIn.java,v $ -// $RCSfile: PilotLoaderPlugIn.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:38 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d.pilot; - -import java.awt.Component; -import java.awt.event.MouseEvent; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; - -import com.bbn.openmap.layer.graphicLoader.GraphicLoaderLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; - -/** - * The PilotLoaderLayer receives OMGraphics from the PilotLoader and displays - * them. It just waits and listens, and redraws when necessary. - */ -public class PilotLoaderLayer extends GraphicLoaderLayer { - - private static final long serialVersionUID = 1L; - - protected OMDrawingTool dt = null; - - public PilotLoaderLayer() { - super(); - setGraphicLoader(new PilotLoader(this)); - } - - /** - * The getRectangle call is the main call into the PlugIn module. The module - * is expected to fill the graphics list with objects that are within the - * screen parameters passed. - * - * @return OMGraphic that should be displayed for the current projection. - */ - public OMGraphicList prepare() { - Projection p = getProjection(); - - if (loader != null) { - loader.setProjection(p); - } - - OMGraphicList list = new OMGraphicList(getList()); - list.generate(p); - - if (Debug.debugging("pilotloader")) { - Debug.output("GraphicLoaderPlugIn returning list of " + list.size() + " objects."); - } - - return list; - } - - public synchronized void setList(OMGraphicList graphics) { - super.setList(graphics); - doPrepare(); - } - - public synchronized boolean doAction(OMGraphic graphic, OMAction action) { - boolean ret = super.doAction(graphic, action); - doPrepare(); - return ret; - } - - /** - * Get the path/point loader. - */ - public void setGraphicLoader(PilotLoader pl) { - loader = pl; - setMapMouseListener(pl); - - try { - pl.setBeanContext(getBeanContext()); - } catch (PropertyVetoException pve) { - } - } - - public Component getGUI() { - if (loader != null) { - return loader.getGUI(); - } else { - return null; - } - } - - /** - * Invoked when the mouse has been clicked on a component. The listener will - * receive this event if it successfully processed - * mousePressed(), or if no other listener processes the event. - * If the listener successfully processes mouseClicked(), then - * it will receive the next mouseClicked() notifications that - * have a click count greater than one. - *

- * NOTE: We have noticed that this method can sometimes be erroneously - * invoked. It seems to occur when a light-weight AWT component (like an - * internal window or menu) closes (removes itself from the window - * hierarchy). A specific OpenMap example is when you make a menu selection - * when the MenuItem you select is above the MapBean canvas. After making - * the selection, the mouseClicked() gets invoked on the MouseDelegator, - * which passes it to the appropriate listeners depending on the MouseMode. - * The best way to avoid this problem is to not implement anything crucial - * in this method. Use a combination of mousePressed() and - * mouseReleased() instead. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - - OMGraphicList list = getList(); - - if (list != null) { - OMGraphic graphic = list.getContains(e.getX(), e.getY()); - if (graphic instanceof Pilot) { - Pilot mp = (Pilot) graphic; - mp.showPalette(); - return true; - } - } - return false; - } - - /** - * Method for BeanContextChild interface. Adds this object as a - * BeanContextMembership listener, set the BeanContext in this objects - * BeanContextSupport, and receives the initial list of objects currently - * contained in the BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - super.setBeanContext(in_bc); - if (loader instanceof PilotLoader) { - ((PilotLoader) loader).setBeanContext(in_bc); - } - } - -} // end PilotLoaderLayer. diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotPath.java b/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotPath.java deleted file mode 100644 index 3318ee47f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/PilotPath.java +++ /dev/null @@ -1,422 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/j3d/com/bbn/openmap/plugin/pilot/PilotPath.java,v $ -// $RCSfile: PilotPath.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/02/23 22:37:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.j3d.pilot; - -import java.awt.Graphics; -import java.awt.GridLayout; -import java.awt.geom.Point2D; - -import javax.media.j3d.Behavior; -import javax.media.j3d.Transform3D; -import javax.media.j3d.TransformGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.vecmath.Vector3d; - -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.j3d.ControlledManager; -import com.bbn.openmap.j3d.NavBehaviorProvider; -import com.bbn.openmap.j3d.OM3DConstants; -import com.bbn.openmap.j3d.OMKeyBehavior; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The PilotPath is a definition of a path that a Java 3D window will take. This - * is a demonstration class that will have improvements as time goes on. Right - * now, height does not have an effect on the view. - *

- * - * The PlugIn palette lets the user use the OMDrawingTool to define the path. - * The path also provides a button on the palette to launch the J3D viewer. - */ -public class PilotPath extends Pilot implements NavBehaviorProvider { - - double[] pathPoints = null; - OMPoly poly = null; - int pathIndex = 0; - double currentSegDist = 0.0; - double nextSegOffset = 0.0; - double rate = Length.METER.toRadians(10000.0); - - protected boolean DEBUG = false; - - /** - * Define a path, with the radius and isOval referring to the marker for - * marking the pilot's position on the path. - */ - public PilotPath(OMPoly path, int radius, boolean isOval) { - super(0f, 0f, radius, isOval); - setPoly(path); - DEBUG = Debug.debugging("pilot"); - - setHeight(10.3f); - } - - /** - * Tell the pilot to move along the path. The factor is not currently used. - */ - public void move(float factor) { - if (!stationary) { - moveAlong(); - } - } - - /** - * Returns the coordinates for the current poly segment. - */ - public double[] getSegmentCoordinates(int currentPathIndex) { - double[] latlons = new double[4]; - - if (pathIndex > pathPoints.length - 2 || pathIndex < 0) { - pathIndex = 0; - } - - if (pathPoints.length >= 4) { - - int la1 = pathIndex; - int lo1 = pathIndex + 1; - - int la2 = pathIndex + 2; - int lo2 = pathIndex + 3; - - if (lo2 >= pathPoints.length) { - if (poly.isPolygon()) { - if (DEBUG) - Debug.output("PilotPath.moveAlong(): index too big, wrapping... "); - la2 = 0; - lo2 = 1; - } else { - pathIndex = 0; - if (DEBUG) - Debug.output("PilotPath.moveAlong(): index too big, no wrapping, starting over... "); - return getSegmentCoordinates(pathIndex); - } - } - - latlons[0] = pathPoints[la1]; - latlons[1] = pathPoints[lo1]; - latlons[2] = pathPoints[la2]; - latlons[3] = pathPoints[lo2]; - } - - return latlons; - } - - /** - * Figures out the next position of the pilot, given the distance the pilot - * should move for this turn. - */ - public void moveAlong() { - if (DEBUG) { - Debug.output("PilotPath.moveAlong(): segment " + (pathIndex / 2) + " of " - + (pathPoints.length / 2)); - } - - double[] latlons = getSegmentCoordinates(pathIndex); - - double segLength = GreatCircle.sphericalDistance(latlons[0], latlons[1], latlons[2], latlons[3]); - if (DEBUG) { - Debug.output("PilotPath.moveAlong(): segment Length " + segLength - + ", and already have " + currentSegDist + " of it."); - } - double needToTravel = rate; - int originalPathIndex = pathIndex; - int loopingTimes = 0; - while (needToTravel >= segLength - currentSegDist) { - - needToTravel -= (segLength - currentSegDist); - currentSegDist = 0f; - - pathIndex += 2; - // Move to the next segment of the poly - - if (DEBUG) { - Debug.output("PilotPath to next segment(" + (pathIndex / 2) + "), need to travel " - + needToTravel); - } - latlons = getSegmentCoordinates(pathIndex); - - if (pathIndex == originalPathIndex) { - loopingTimes++; - if (loopingTimes > 1) { - if (DEBUG) - Debug.output("PilotPath looping on itself, setting to stationary"); - setStationary(true); - return; - } - } - - segLength = GreatCircle.sphericalDistance(latlons[0], latlons[1], latlons[2], latlons[3]); - } - - if (DEBUG) { - Debug.output("Moving PilotPath within current(" + (pathIndex / 2) - + ") segment, segLength: " + segLength + ", ntt: " + needToTravel); - } - - // Staying on this segment, just calculate where the - // next point on the segment is. - double azimuth = GreatCircle.sphericalAzimuth(latlons[0], latlons[1], latlons[2], latlons[3]); - - Point2D newPoint = GreatCircle.sphericalBetween(latlons[0], latlons[1], currentSegDist - + needToTravel, azimuth); - - setLat(newPoint.getY()); - setLon(newPoint.getX()); - - currentSegDist = GreatCircle.sphericalDistance(latlons[0], latlons[1], Math.toRadians(newPoint.getY()), Math.toRadians(newPoint.getX())); - - // OK, now move the camera accordingly... - - if (DEBUG) - Debug.output("moveAlong: azimuth = " + azimuth); - - if (viewProjection == null) { - return; - } - - Point2D newLoc = viewProjection.forward(newPoint); - - if (DEBUG) - Debug.output(newLoc.toString() + ", compared with lastX, lastY: " + lastX + ", " - + lastY + ", scaleFactor= " + scaleFactor); - - double centerXOffset = newLoc.getX() * scaleFactor; - double centerYOffset = newLoc.getY() * scaleFactor; - - Vector3d translate = new Vector3d(); - - // 0f can be changed to account for any height change. - translate.set(centerXOffset - lastX, 0, centerYOffset - lastY); - lastX = centerXOffset; - lastY = centerYOffset; - - if (DEBUG) - Debug.output("PP moving: " + translate); - - // translateTransform.set(scaleFactor, translate); - - // cameraTransformGroup.getTransform(translateTransform); - // Transform3D toMove = new Transform3D(); - - // toMove.setTranslation(translate); - // translateTransform.mul(toMove); - - // cameraTransformGroup.setTransform(translateTransform); - - if (platformBehavior != null) { - - platformBehavior.doMove(translate); - if (lastAzimuth != azimuth) { - platformBehavior.doLookY(lastAzimuth - azimuth); - lastAzimuth = azimuth; - } - } - } - - protected Transform3D translateTransform = new Transform3D(); - protected Projection viewProjection; - protected TransformGroup cameraTransformGroup; - protected float scaleFactor = 1f; - protected double lastX; - protected double lastY; - protected double lastAzimuth = 0; - - /** - * Standard generate method, generating all the OMGraphics with the current - * position. - */ - public boolean generate(Projection p) { - // At least try to keep the current version, in case things - // get set up with the 3D viewer out of order. - viewProjection = p; - - boolean ret = super.generate(p); - if (poly != null) { - poly.generate(p); - } - return ret; - } - - public void render(Graphics g) { - if (poly != null) { - poly.render(g); - } - super.render(g); - } - - /** - * Set the polygon for the path. - */ - public void setPoly(OMPoly p) { - poly = p; - - if (poly.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - pathPoints = poly.getLatLonArray(); - setLat(ProjMath.radToDeg(pathPoints[0])); - setLon(ProjMath.radToDeg(pathPoints[1])); - setStationary(false); - } else { - setStationary(true); - } - } - - public OMPoly getPoly() { - return poly; - } - - OMKeyBehavior platformBehavior; - - public Behavior setViewingPlatformBehavior(TransformGroup ctg, Projection projection, - float scaleFactor) { - - if (DEBUG) - Debug.output("PilotPath setting viewing platform behavior"); - cameraTransformGroup = ctg; - - platformBehavior = new OMKeyBehavior(cameraTransformGroup, viewProjection, locateWorld(projection, scaleFactor)); - // Trying to look down a little, didn't work. Should have, - // though. - // platformBehavior.doLookX(com.bbn.openmap.MoreMath.HALF_PI/2f); - return platformBehavior; - } - - /** - */ - public Vector3d locateWorld(Projection projection, float scaleFactor) { - - // Set the view parameters. - this.viewProjection = projection; - translateTransform = new Transform3D(); - this.scaleFactor = scaleFactor; - - cameraTransformGroup.getTransform(translateTransform); - - if (DEBUG) - Debug.output("PilotPath setting camera location, scaleFactor = " + this.scaleFactor); - Vector3d translate = new Vector3d(); - - if (projection != null) { - - Point2D pilotPoint = projection.forward(getLat(), getLon()); - - // scaleFactor of < 1 shrinks the object.(.5) is the scale. - - // So, this lays out where the land is, in relation to the - // viewer. We should get the projection from the MapBean, and - // offset the transform to the middle of the map. - - double centerXOffset = pilotPoint.getX() * scaleFactor; - double centerYOffset = pilotPoint.getY() * scaleFactor; - - if (DEBUG) - Debug.output("OM3DViewer with projection " + projection - + ", setting center of scene to " + centerXOffset + ", " + centerYOffset); - - translate.set(centerXOffset, (double) height, centerYOffset); - lastX = centerXOffset; - lastY = centerYOffset; - } else { - translate.set(0, height, 0); - } - - return translate; - } - - /** Needed for J3D world. */ - protected MapHandler mapHandler; - - public void setMapHandler(MapHandler mh) { - mapHandler = mh; - } - - public void launch3D() { - JFrame viewer = ControlledManager.getFrame("OpenMap 3D", 500, 500, mapHandler, (NavBehaviorProvider) this, new javax.media.j3d.Background(.3f, .3f, .3f), OM3DConstants.CONTENT_MASK_OMGRAPHICHANDLERLAYERS - | OM3DConstants.CONTENT_MASK_OM3DGRAPHICHANDLERS); - viewer.setVisible(true); - } - - public final static String Launch3DCmd = "Launch3D"; - - /** - * Gets the gui controls associated with the Pilot. This default - * implementation returns null indicating that the Pilot has no gui - * controls. - * - * @return java.awt.Component or null - */ - public java.awt.Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - - // Only want to do this once... - if (movementButton == null) { - movementButton = new JCheckBox("Stationary", getStationary()); - movementButton.addActionListener(this); - movementButton.setActionCommand(MoveCmd); - } - - panel.add(movementButton); - - JPanel heightPanel = new JPanel(new GridLayout(0, 3)); - - heightPanel.add(new JLabel("Object height: ")); - if (heightField == null) { - heightField = new JTextField(Double.toString(height), 10); - heightField.setHorizontalAlignment(JTextField.RIGHT); - heightField.addActionListener(this); - heightField.addFocusListener(this); - } - heightPanel.add(heightField); - // There aren't any units to this yet - we need a good - // translation between meters and the j3d world elevations. - heightPanel.add(new JLabel(" ")); - panel.add(heightPanel); - - JButton launch3DButton = new JButton("Launch 3D"); - launch3DButton.setActionCommand(Launch3DCmd); - launch3DButton.addActionListener(this); - - panel.add(launch3DButton); - - return panel; - } - - public void actionPerformed(java.awt.event.ActionEvent ae) { - super.actionPerformed(ae); - String cmd = ae.getActionCommand(); - if (cmd == Launch3DCmd) { - launch3D(); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/package.html b/src/core/src/main/java/com/bbn/openmap/j3d/pilot/package.html deleted file mode 100755 index 414625207..000000000 --- a/src/core/src/main/java/com/bbn/openmap/j3d/pilot/package.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The Pilot PlugIn package is a demonstration of how to use the Java 3D -package within OpenMap - specifically, the ControlledManager viewer -class.

- -The package consists of a PilotPlugIn, which is a PlugIn that accepts -graphics from another object, called the PilotLoader. The PilotLoader -is an object with a timer that manages these location objects called -Pilots (and by extension, PilotPaths). As the timer runs, the -PilotPaths adjust the Pilot's location on the map.

- -For the Java 3D demonstration, the PilotPaths can also launch a Java 3D -viewer window which shows the view from the Pilot point in 3D space. -As the timer runs, the 3D view changes in the viewer.

- -There are still some issues to be worked out in all of this. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/AOILayer.java b/src/core/src/main/java/com/bbn/openmap/layer/AOILayer.java deleted file mode 100644 index 0493c77ae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/AOILayer.java +++ /dev/null @@ -1,129 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: AOILayer.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:27 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer; - -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.util.PropUtils; - -/** - * A simple layer that lets you define areas to be drawn on the map by defining - * coordinates for areas in the properties file. A sample of properties that - * could be used for this layer: - *

 
- * 
- * aoi.class=com.bbn.openmap.layer.AOILayer
- * aoi.prettyName=Areas of Interest
- * aoi.aoi=area1 area2
- * aoi.area1.name=First Area
- * aoi.area1.coords=33.469604f 69.852425f 33.591957f 69.85425f 33.598362f 69.965256f 33.474995f 69.96891f 33.469604f 69.852425f
- * aoi.area1.lineColor=FF9900
- * aoi.area1.selectColor=FF9900
- * aoi.area1.fillColor=33FF9900
- * aoi.area1.lineWidth=2
- * aoi.area2.name=Second Area
- * aoi.area2.coords=34.59030485181645f 70.10225955962484f 34.70749132408063f 70.10062341994104f 34.705166929775665f 70.24468896438881f 34.58780191583231f 70.24351387509675f 34.59030485181645f 70.10225955962484f
- * aoi.area2.lineColor=CCFF00
- * aoi.area2.selectColor=CCFF00
- * aoi.area2.fillColor=33CCFF00
- * aoi.area2.lineWidth=2
- * 
- * 
- * @author dietrick - */ -public class AOILayer extends OMGraphicHandlerLayer { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.AOILayer"); - - public final static String AOIProperty = "aoi"; - public final static String AOICoordsProperty = "coords"; - public final static String AOINameProperty = "name"; - - public AOILayer() { - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - DrawingAttributes attributes = new DrawingAttributes(); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - List aois = PropUtils.parseSpacedMarkers(props.getProperty(prefix - + AOIProperty)); - - OMGraphicList list = new OMGraphicList(); - - for (Iterator it = aois.iterator(); it.hasNext();) { - String aoi = it.next(); - - String aoiPrefix = PropUtils.getScopedPropertyPrefix(prefix + aoi); - List coordV = PropUtils.parseSpacedMarkers(props.getProperty(aoiPrefix - + AOICoordsProperty)); - double[] coords = new double[coordV.size()]; - int coordCount = 0; - for (Iterator cit = coordV.iterator(); cit.hasNext();) { - try { - coords[coordCount++] = Double.parseDouble(cit.next()); - } catch (NumberFormatException nfe) { - logger.warning("can't parse coords for " + aoi + ": " - + coordV); - break; - } - } - - if (coordCount < coordV.size()) { - continue; - } - - attributes.setProperties(aoiPrefix, props); - String name = props.getProperty(aoiPrefix + AOINameProperty); - - OMPoly aoiGraphic = new OMPoly(coords, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE); - attributes.setTo(aoiGraphic); - aoiGraphic.putAttribute(OMGraphic.TOOLTIP, name); - - list.add(aoiGraphic); - } - - setList(list); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/BufferedLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/BufferedLayer.java deleted file mode 100644 index 9e6489dfe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/BufferedLayer.java +++ /dev/null @@ -1,634 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/BufferedLayer.java,v $ -// $RCSfile: BufferedLayer.java,v $ -// $Revision: 1.13 $ -// $Date: 2008/10/01 15:26:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ContainerEvent; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * A BufferedLayer is a layer that buffers a group of layers into an image. When - * this layer repaints, the image gets rendered. This layer can be used to group - * a set of layers into one, and was designed with the idea that it is a - * background layer where a more animated layer would be on top of it. - *

- * - * This layer contains a MapBean, and any layer that gets added to it simply - * gets added to the MapBean. When a layer needs to redraw itself, it can act - * normally, and the BufferedLayer will get updated as needed. If the MapBean is - * a BufferedMapBean (which it is by default), then the layers will get buffered - * into an image. - *

- * - * The BufferedLayer can be configured in the openmap.properties file: - * - *

- *
- *
- *  bufLayer.class=com.bbn.openmap.layer.BufferedLayer
- *  bufLayer.prettyName=My Layer Group
- *  bufLayer.layers=layer1 layer2 layer3
- *  bufLayer.visibleLayers=layer1 layer3
- * 
- * - * layer1, layer2, etc should be defined as any other openmap layer. - */ -public class BufferedLayer extends OMGraphicHandlerLayer implements PropertyChangeListener { - - private static final long serialVersionUID = 1L; - public final static String LayersProperty = "layers"; - public final static String VisibleLayersProperty = "visibleLayers"; - - /** - * Used to tell the BufferedLayer that the background is transparent. Will - * cause a new image buffer to be created when the projection changes, in - * order to cover up what was already there. This is set to true but - * default, since the internal MapBean color is set to OMColor.clear. - */ - protected boolean hasTransparentBackground = true; - - /** - * The MapBean used as the group organized. If this is a BufferedMapBean, - * the layer will provide a buffered image. - */ - MapBean mapBean; - - public BufferedLayer() { - this.setLayout(new BorderLayout()); - - // Adds the mapbean to the layer - MapBean mb = new BLMapBean(); - - // Add it the layer properly... - setMapBean(mb); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - PropUtils.putDataPrefixToLayerList(this, props, prefix + LayersProperty); - - List layersValue = PropUtils.parseSpacedMarkers(props.getProperty(prefix + LayersProperty)); - List startuplayers = PropUtils.parseSpacedMarkers(props.getProperty(prefix + VisibleLayersProperty)); - - Layer[] layers = LayerHandler.getLayers(layersValue, startuplayers, props); - - for (Layer layer : layers) { - mapBean.add(layer); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer layersListProperty = new StringBuffer(); - StringBuffer startupLayersListProperty = new StringBuffer(); - - Component[] comps = mapBean.getComponents(); - for (int i = 0; i < comps.length; i++) { - // they have to be layers - Layer layer = (Layer) comps[i]; - String lPrefix = layer.getPropertyPrefix(); - boolean unsetPrefix = false; - if (lPrefix == null) { - lPrefix = "layer" + i; - // I think we need to do this, in order to get proper - // scoping in the properties. We'll unset it later... - layer.setPropertyPrefix(lPrefix); - unsetPrefix = true; - } - layersListProperty.append(" ").append(lPrefix); - - if (layer.isVisible()) { - startupLayersListProperty.append(" ").append(lPrefix); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("BufferedLayer: getting properties for " + layer.getName() + " " - + layer.getProperties(new Properties())); - } - - layer.getProperties(props); - - if (unsetPrefix) { - layer.setPropertyPrefix(null); - } - } - - props.put(prefix + LayersProperty, layersListProperty.toString()); - props.put(prefix + VisibleLayersProperty, startupLayersListProperty.toString()); - - return props; - } - - /** - * Not really implemented, because the mechanism for providing a set of - * properties that let you add a variable number of new objects as children - * to this one. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - return props; - } - - /** - * If true, will create a new image buffer when the projection changes. - * Should be set to true if the background has any transparency. - */ - public void setHasTransparentBackground(boolean value) { - hasTransparentBackground = value; - } - - public boolean getHasTransparentBackground() { - return hasTransparentBackground; - } - - /** - * Remove all layers from the group. - */ - public void clearLayers() { - Component[] layers = getLayers(); - if (layers != null && layers.length > 0) { - for (int i = 0; i < layers.length; i++) { - removeLayer((Layer) layers[i]); - } - } - - resetPalette(); - } - - /** - * Method for BeanContextChild interface. Gets an iterator from the - * BeanContext to call findAndInit() over. Sets BeanContext on sub-layers. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - super.setBeanContext(in_bc); - - Component[] layers = getLayers(); - if (layers != null && layers.length > 0) { - for (int i = 0; i < layers.length; i++) { - ((Layer) layers[i]).setBeanContext(in_bc); - } - } - } - - /** - * Add a layer to the group. Sets the BeanContext on the added layer. - */ - public void addLayer(Layer layer) { - mapBean.add(layer); - try { - layer.setBeanContext(getBeanContext()); - } catch (PropertyVetoException nve) { - } - resetPalette(); - } - - /** - * Remove the layer from group. - */ - public void removeLayer(Layer layer) { - mapBean.remove(layer); - resetPalette(); - } - - /** - * Return if there is at least one layer assigned to the group. - */ - public boolean hasLayers() { - return (mapBean.getComponentCount() > 0); - } - - /** - * Get the layers assigned to the internal MapBean. - * - * @return a Component[]. - */ - public Component[] getLayers() { - return mapBean.getComponents(); - } - - /** - * Returns true if all children are are ready to be painted - that is, they - * have called for a repaint. - * - * @return the readyToPaint - */ - public boolean isReadyToPaint() { - for (Component c : getLayers()) { - if (!((Layer) c).isReadyToPaint()) { - return false; - } - } - return true; - } - - /** - * Set whether this layer should be ready to paint. Called when the - * projection changes, to make child layers 'dirty'. We don't change the - * super classes' version of the variable, because it's never consulted and - * it's probably better that it's always true by default. - * - * @param readyToPaint the readyToPaint to set - */ - public void setReadyToPaint(boolean readyToPaint) { - for (Component c : getLayers()) { - ((Layer) c).setReadyToPaint(readyToPaint); - } - } - - /** - * You can change what kind of MapBean is used to hold onto the layers. This - * method just sets the new MapBean into the layer, as is. If there was a - * previous MapBean with layers, they're gone and replaces with whatever is - * attached to the new MapBean. - * - * @param mb new MapBean - */ - public void setMapBean(MapBean mb) { - if (mapBean != null) { - remove(mapBean); - } - - mapBean = mb; - add(mapBean, BorderLayout.CENTER); - } - - /** - * Get the current MapBean used in the BufferedLayer. - * - * @return MapBean - */ - public MapBean getMapBean() { - return mapBean; - } - - /** - * Set the background color of the group. Actually sets the background color - * of the projection used by the internal MapBean, and which then forces a - * repaint() on it. - * - * @param color java.awt.Color. - */ - public void setBackground(Color color) { - setBckgrnd(color); - } - - /** - * Set the background paint of the group. Actually sets the background paint - * of the projection used by the internal MapBean. - * - * @param paint java.awt.Paint - */ - public void setBckgrnd(Paint paint) { - mapBean.setBckgrnd(paint); - - if (paint instanceof Color) { - setHasTransparentBackground(((Color) paint).getAlpha() < 255); - } else { - // then we don't know, assume it is. - setHasTransparentBackground(true); - } - } - - /** - * Get the background color of the image. Actually returns the background - * color of the projection of the internal MapBean. - * - * @return color java.awt.Color - */ - public Color getBackground() { - return mapBean.getBackground(); - } - - /** - * Get the background Paint object used for the internal MapBean. - * - * @return java.awt.Paint - */ - public Paint getBckgrnd(Paint paint) { - return mapBean.getBckgrnd(); - } - - /** - * We don't want a projection change policy called here, because that will - * call for a repaint. We want the buffered layers to call for a repaint if - * necessary. - */ - @Override - public void projectionChanged(ProjectionEvent pevent) { - // Just pass it on, let the layers decide if they have to update. - mapBean.setProjection(pevent.getProjection()); - } - - /** - * Called when the layer is removed from the MapBean, and after the - * projection changes. Lets the layer know to release memory that might not - * be needed. - */ - @Override - public void removed(Container cont) { - Component[] layers = getLayers(); - if (layers != null && layers.length > 0) { - for (int i = 0; i < layers.length; i++) { - ((Layer) layers[i]).remove(cont); - } - } - } - - /** - * The GUI panel. - */ - JPanel panel = null; - - /** - * Should be called if layers are added or removed from the buffer. - */ - public void resetPalette() { - panel = null; - super.resetPalette(); - } - - /** - * Get the GUI (palettes) for the layers. The BufferedLayer actually creates - * a JTabbedPane holding the palettes for all of its layers, and also has a - * pane for itself that provides visibility control for the group layers. - */ - public Component getGUI() { - if (panel == null) { - Component[] layerComps = getLayers(); - - panel = new JPanel(); - GridBagLayout pGridbag = new GridBagLayout(); - GridBagConstraints pC = new GridBagConstraints(); - pC.fill = GridBagConstraints.BOTH; - pC.weightx = 1.0f; - pC.weighty = 1.0f; - panel.setLayout(pGridbag); - - JTabbedPane tabs = new JTabbedPane(); - pGridbag.setConstraints(tabs, pC); - panel.add(tabs); - - JPanel bfPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.BOTH; - c.weightx = 0.0f; - c.weighty = 0.0f; - c.anchor = GridBagConstraints.CENTER; - c.gridwidth = GridBagConstraints.REMAINDER; - bfPanel.setLayout(gridbag); - - tabs.addTab("Layer Visibility", bfPanel); - - for (int i = 0; i < layerComps.length; i++) { - Layer layer = (Layer) layerComps[i]; - Component layerGUI = layer.getGUI(); - if (layerGUI != null) { - tabs.addTab(layer.getName(), layerGUI); - } - - VisHelper layerVisibility = new VisHelper(layer); - gridbag.setConstraints(layerVisibility, c); - bfPanel.add(layerVisibility); - } - } - return panel; - } - - public void paint(Graphics g) { - if (hasLayers()) { - mapBean.paintChildren(g); - } - mapBean.paintPainters(g); - } - - /** - * Class that helps track turning on/off layers in the buffered layer. - */ - protected class VisHelper extends JCheckBox implements ActionListener { - - private static final long serialVersionUID = 1L; - Layer layer; - - public VisHelper(Layer l) { - super(l.getName(), l.isVisible()); - super.addActionListener(this); - layer = l; - } - - public void actionPerformed(ActionEvent ae) { - layer.setVisible(((JCheckBox) ae.getSource()).isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Turning " + layer.getName() - + (((JCheckBox) ae.getSource()).isSelected() ? " on" : " off")); - } - - layer.repaint(); - } - } - - /** - * Part of the ProjectionPainter interface. The group layers are given the - * projection and the graphics to paint into. - */ - public void renderDataForProjection(Projection proj, Graphics g) { - Component[] layersComps = mapBean.getComponents(); - - for (int i = layersComps.length - 1; i >= 0; i--) { - Layer layer = (Layer) layersComps[i]; - if (layer.isVisible()) { - layer.renderDataForProjection(proj, g); - } - } - } - - /** - * PropertyChangeListener method, to listen for the source map's background - * changes. Act on if necessary. - */ - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName() == MapBean.BackgroundProperty) { - mapBean.setBckgrnd((Paint) pce.getNewValue()); - } - } - - public void dispose() { - if (mapBean != null) { - mapBean.dispose(); - } - - if (panel != null) { - panel.removeAll(); - panel = null; - } - } - - public void setBufferDirty(boolean value) { - mapBean.setBufferDirty(value); - } - - /** - * An simple extension of the BufferedMapBean that calls a layer, presumably - * its parent, to call repaint(). This is necessary in order to make sure - * Swing calls paint properly. Only repaint() is overridden in this class - * over a standard BufferedMapBean. - */ - public class BLMapBean extends BufferedMapBean { - - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public BLMapBean() { - super(false); - background = OMColor.ALMOST_CLEAR; - } - - /** - * For the Buffered Layer MapBean, the background color is always clear. - * Let the layers add the color... - * - * @return color java.awt.Color. - */ - public Color getBackground() { - return OMColor.ALMOST_CLEAR; - } - - /** - * Set the buffer dirty, and call repaint on the layer. - */ - public void repaint(Layer layer) { - super.setBufferDirty(true); - BufferedLayer.this.repaint(); - } - - /** - * Fine-tuned for the purposes of a BufferedLayer - just create a new - * image if the buffer is dirty. - */ - public void paintChildren(Graphics g, Rectangle clip) { - BufferedImage localDrawingBuffer = drawingBuffer; - if (bufferDirty) { - - // Reset will clear out the pixels if the size of the buffer is - // appropriate for the projection - localDrawingBuffer = resetDrawingBuffer(localDrawingBuffer, getProjection()); - - // We need to draw the projection background with oh-so-slight - // transparent rect to allow semi-transparent layers to render - // properly. - - drawProjectionBackground(localDrawingBuffer.getGraphics()); - /** - * We used to call paintLayers here. - */ - // paintLayers(localDrawingBuffer.getGraphics()); - /** - * But, there are problems with rendering if the projection - * changes quickly (rotation, following a track, etc) and - * there's an animated layer active. Calling - * renderDataForProjection on the background layer eliminates - * flickering with background layers and the background color. - * Sometimes having a BufferedImageRenderPolicy on some of these - * background layers also causes flashing. Since the - * BufferedLayer provides buffering, those layers can have a - * StandardRenderPolicy. - */ - renderDataForProjection(getProjection(), localDrawingBuffer.getGraphics()); - - // Reassign the drawingBuffer if a new buffer was allocated. - drawingBuffer = localDrawingBuffer; - } - - if (localDrawingBuffer != null) { - g.drawImage(localDrawingBuffer, 0, 0, null); - } - - } - - /** - * @return the expanded rotated projection if map rotated, normal - * projection if not rotated. The rotated projection is larger - * than the MapBean and has extra offsets. - */ - public Projection getRotatedProjection() { - RotationHelper rotation = getUpdatedRotHelper(); - Projection proj = rotation != null ? rotation.getProjection() : projection; - /** - * The original method in the superclass sets the rotation angle on - * the projection, but the rotation in this map bean is 0, so - * calling this just messes up rotation settings in the projection, - * stomping it to zero. This has the effect of breaking - * anti-rotation in OMText and OMScalingIcons. - */ - // ((Proj) proj).setRotationAngle(getRotationAngle()); - return proj; - } - - /** - * We don't want the BLMapBean to be hanging on to removed layers, - * that'll be done at a higher level. - */ - public void componentRemoved(ContainerEvent e) { - super.componentRemoved(e); - removedLayers.clear(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/CacheLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/CacheLayer.java deleted file mode 100644 index 6b888920b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/CacheLayer.java +++ /dev/null @@ -1,389 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/CacheLayer.java,v $ -// $RCSfile: CacheLayer.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 19:20:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.IOException; -import java.net.URL; -import java.util.Properties; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JTextField; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A Layer that gets it's graphics from a URL containing a serialized - * OMGraphicList. This layer does respond to gesturing on the - * graphics, but doesn't do anything. You can extend this class to be - * more useful to you. It has one property that needs to be set in the - * properties file: - *

- *

- * # CacheLayer property, the layer should figure out whether it's a file or URL.
- * cachelayer.cacheFile=<url of cachefile>
- * 
- */ -public class CacheLayer extends Layer implements ActionListener, - MapMouseListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final String CacheFileProperty = "cacheFile"; - - /** Used by the gui */ - private static final String READ_DATA_COMMAND = "ReadData"; - - /** - * URL to read data from. This data will be in the form of a - * serialized stream of OMGraphics. - */ - protected URL cacheURL; - - /** - * A list of graphics to be painted on the map. - */ - protected OMGraphicList omgraphics = new OMGraphicList(); - - /** - * Construct a default CacheLayer. - */ - public CacheLayer() {} - - /** - * Read a cache of OMGraphics - */ - public void readGraphics() throws java.io.IOException { - - if (Debug.debugging("cachelayer")) { - Debug.output("Reading cached graphics"); - } - - if (omgraphics == null) { - omgraphics = new OMGraphicList(); - } - - if (cacheURL != null) { - omgraphics.readGraphics(cacheURL); - } - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for - * this layer - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String cacheFile = props.getProperty(prefix + CacheFileProperty); - - try { - if (cacheFile != null) { - if (Debug.debugging("cachelayer")) { - Debug.output("Getting cachefile: " + cacheFile); - } - - // First find the resource, if not, then try as a - // file-URL... b - cacheURL = PropUtils.getResourceOrFileOrURL(this, cacheFile); - - if (cacheURL != null) { - readGraphics(); - } - } - } catch (java.net.MalformedURLException mue) { - mue.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } catch (NullPointerException e) { - e.printStackTrace(); - } - } - - //---------------------------------------------------------------------- - // Layer overrides - //---------------------------------------------------------------------- - - /** - * Renders the graphics list. It is important to make this routine - * as fast as possible since it is called frequently by Swing, and - * the User Interface blocks while painting is done. - */ - public void paint(java.awt.Graphics g) { - omgraphics.render(g); - } - - //---------------------------------------------------------------------- - // ProjectionListener interface implementation - //---------------------------------------------------------------------- - - /** - * Handler for ProjectionEvents. This function is - * invoked when the MapBean projection changes. The - * graphics are reprojected and then the Layer is repainted. - *

- * - * @param e the projection event - */ - public void projectionChanged(ProjectionEvent e) { - omgraphics.project(e.getProjection(), true); - repaint(); - } - - //---------------------------------------------------------------------- - /** - * Provides the palette widgets to control the options of showing - * maps, or attribute text. - * - * @return Component object representing the palette widgets. - */ - public Component getGUI() { - - JButton rereadFilesButton = new JButton("Reload OMGraphics"); - rereadFilesButton.setActionCommand(READ_DATA_COMMAND); - rereadFilesButton.addActionListener(this); - - JLabel fileLabel = new JLabel("Read from: "); - JTextField pathText = new JTextField(cacheURL.toString()); - - Box filebox = Box.createHorizontalBox(); - filebox.add(fileLabel); - filebox.add(pathText); - - Box box = Box.createVerticalBox(); - box.add(rereadFilesButton); - box.add(filebox); - return box; - } - - //---------------------------------------------------------------------- - // ActionListener interface implementation - //---------------------------------------------------------------------- - - /** - * The Action Listener method, that reacts to the palette widgets - * actions. - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String cmd = e.getActionCommand(); - if (cmd == READ_DATA_COMMAND) { - Debug.message("cachelayer", - "CacheLayer: Reading serialized graphics"); - try { - readGraphics(); - } catch (java.io.IOException exc) { - exc.printStackTrace(); - } - } else { - Debug.error("Unknown action command \"" + cmd - + "\" in SaveShapeLayer.actionPerformed()."); - } - } - - //---------------------------------------------------------------------- - // MapMouseListener interface implementation - //---------------------------------------------------------------------- - - private OMGraphic selectedGraphic; - - /** - * Indicates which mouse modes should send events to this - * Layer. - * - * @return An array mouse mode names - * - * @see com.bbn.openmap.event.MapMouseListener - * @see com.bbn.openmap.MouseDelegator - */ - public String[] getMouseModeServiceList() { - String[] ret = { SelectMouseMode.modeID }; - return ret; - } - - /** - * Called whenever the mouse is pressed by the user and one of the - * requested mouse modes is active. - * - * @param e the press event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mousePressed(MouseEvent e) { - return false; - } - - /** - * Called whenever the mouse is released by the user and one of - * the requested mouse modes is active. - * - * @param e the release event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseReleased(MouseEvent e) { - return false; - } - - /** - * Called whenever the mouse is clicked by the user and one of the - * requested mouse modes is active. - * - * @param e the click event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseClicked(MouseEvent e) { - if (selectedGraphic != null) { - switch (e.getClickCount()) { - case 1: - if (Debug.debugging("cachelayer")) { - Debug.output("CacheLayer: Show Info: " - + selectedGraphic.getAttribute(OMGraphic.INFOLINE)); - } - break; - case 2: - if (Debug.debugging("cachelayer")) { - Debug.output("CacheLayer: Request URL: " + selectedGraphic); - } - break; - default: - break; - } - return true; - } else { - return false; - } - } - - /** - * Called whenever the mouse enters this layer and one of the - * requested mouse modes is active. - * - * @param e the enter event - * @see #getMouseModeServiceList - */ - public void mouseEntered(MouseEvent e) {} - - /** - * Called whenever the mouse exits this layer and one of the - * requested mouse modes is active. - * - * @param e the exit event - * @see #getMouseModeServiceList - */ - public void mouseExited(MouseEvent e) {} - - /** - * Called whenever the mouse is dragged on this layer and one of - * the requested mouse modes is active. - * - * @param e the drag event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseDragged(MouseEvent e) { - return false; - } - - private Color oldFillColor = java.awt.Color.yellow; - - /** - * Called whenever the mouse is moved on this layer and one of the - * requested mouse modes is active. - *

- * Tries to locate a graphic near the mouse, and if it is found, - * it is highlighted and the Layer is repainted to show the - * highlighting. - * - * @param e the move event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseMoved(MouseEvent e) { - OMGraphic newSelectedGraphic = omgraphics.selectClosest(e.getX(), - e.getY(), - 2.0f); - - if (newSelectedGraphic != selectedGraphic) { - if (selectedGraphic != null) - selectedGraphic.setFillPaint(oldFillColor); - - selectedGraphic = newSelectedGraphic; - if (newSelectedGraphic != null) { - oldFillColor = newSelectedGraphic.getFillColor(); - newSelectedGraphic.setFillPaint(Color.white); - fireRequestInfoLine(newSelectedGraphic.getAttribute(OMGraphic.INFOLINE) - .toString()); - } - repaint(); - } - - return true; - } - - /** - * Called whenever the mouse is moved on this layer and one of the - * requested mouse modes is active, and the gesture is consumed by - * another active layer. We need to deselect anything that may be - * selected. - * - * @see #getMouseModeServiceList - */ - public void mouseMoved() { - omgraphics.deselect(); - repaint(); - } - - /** - * Returns self as the MapMouseListener in order to - * receive MapMouseEvents. If the implementation - * would prefer to delegate MapMouseEvents, it - * could return the delegate from this method instead. - * - * @return The object to receive MapMouseEvent s or - * null if this layer isn't interested in - * MapMouseEvent s - */ - public MapMouseListener getMapMouseListener() { - return this; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/DateLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/DateLayer.java deleted file mode 100644 index 99f343138..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/DateLayer.java +++ /dev/null @@ -1,167 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/DateLayer.java,v $ -// $RCSfile: DateLayer.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Graphics; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Properties; -import java.util.TimeZone; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.Taskable; - -/** - * Layer that displays date and time. This Layer is a Taskable - * (ActionListener) object so that it can be prompted by a - * javax.swing.Timer object. This layer understands the following - * properties: - *

- *

- * 
- *  # display font as a Java font string
- *  date.font=SansSerif-Bold
- *  # like XWindows geometry: [+-]X[+-]Y, `+' indicates relative to
- *  # left edge or top edges, `-' indicates relative to right or bottom
- *  # edges, XX is x coordinate, YY is y coordinate
- *  date.geometry=+20-30
- *  # background rectangle color (ARGB)
- *  date.color.bg=ffb3b3b3
- *  # foreground text color (ARGB)
- *  date.color.fg=ff000000
- *  # date format (using java.text.SimpleDateFormat patterns)
- *  date.format=EEE, d MMM yyyy HH:mm:ss z
- *  
- * 
- *

- * In addition to the previous properties, you can get this layer to - * work with the OpenMap viewer by adding/editing the additional - * properties in your openmap.properties file: - *

- *

- * 
- *  # layers
- *  openmap.layers=date ...
- *  # class
- *  date.class=com.bbn.openmap.layer.DateLayer
- *  # name
- *  date.prettyName=Date & Time
- *  
- * 

NOTE: the color properties do not support alpha value if - * running on JDK 1.1... - */ -public class DateLayer extends LabelLayer implements Taskable, MapMouseListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - - // property keys - public final static transient String dateFormatProperty = "date.format"; - - // properties - // Dateformat default is similar to IETF standard date syntax: - // "Sat, 12 Aug 1995 13:30:00 GMT", except for the local timezone. - protected DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); - - /** - * Sets the properties for the Layer. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String dateFormatString = props.getProperty(prefix + dateFormatProperty, - ((SimpleDateFormat) dateFormat).toPattern()); - - dateFormat = new SimpleDateFormat(dateFormatString); - - } - - /** - * Get a string representation of the current time. Format the - * string using the current DateFormat. - * - * @return String - */ - public String getCurrentTimeString() { - Calendar cal = Calendar.getInstance(TimeZone.getDefault()); - return " " + dateFormat.format(cal.getTime()) + " "; - } - - /** - * Set the DateFormat used to display the date. - * - * @param df DateFormat - */ - protected void setDateFormat(DateFormat df) { - dateFormat = df; - } - - /** - * Get the DateFormat used to display the date. - * - * @return DateFormat - */ - protected DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(Graphics g) { - String data = getCurrentTimeString(); - if (Debug.debugging("datelayer")) { - System.out.println("DateLayer.paint(): " + data); - } - labelText = data; - super.paint(g); - } - - /** - * Get the sleep hint in milliseconds. The Taskable implementation - * should determine the sleep (delay) interval between invocations - * of its actionPerformed(). - *

- * NOTE: this is only a hint for the timer. It's the Taskable's - * responsibility to determine if too little or too much time has - * elapsed between invocations of actionPerformed() - * (if it really matters). - * - * @return int milliseconds of sleep interval - */ - public int getSleepHint() { - return 1000;//update every second - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/DeclutterMatrix.java b/src/core/src/main/java/com/bbn/openmap/layer/DeclutterMatrix.java deleted file mode 100644 index 520e8399c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/DeclutterMatrix.java +++ /dev/null @@ -1,973 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/DeclutterMatrix.java,v $ -// $RCSfile: DeclutterMatrix.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * ********************************************************************** - * - * A port to Java/Openmap of the MATT decluttering code. - * - * Created on: Thu Aug 19 14:55:41 1999 - * ********************************************************************** - * - * Modification history: - * $Log: DeclutterMatrix.java,v $ - * Revision 1.6 2005/12/09 21:09:08 dietrick - * Projection and LatLonPoint Paradigm shift! Handling preprojected data. Proj based on Point2D objects, new com.bbn.openmap.proj.coords.LatLonPoint to support that for Projection subclasses. New Cartesian projection. All other components seem to be updated and working with the changes. - * There will be incompatibilities with OpenMap 4.6 and previous versions of OpenMap, this is a new minor revision. - * - * Revision 1.5 2004/10/14 18:05:52 dietrick - * Copyright updates, removed extemporaneous import statements, cleaned up deprecations - * - * Revision 1.4 2004/02/06 19:06:20 dietrick - * Fixed harmless lines in DeclutterMatrix, modified DemoLayer to create OMEllipse objects instead of hacking them up, added FullProjectionRenderPolicy which forces clipping area for layers to match the projection, and made RpfLayer call the RenderPolicy - * - * Revision 1.3 2004/01/26 18:18:08 dietrick - * Untabified - * - * Revision 1.2 2003/12/23 20:43:25 wjeuerle - * no code changes, updated javadoc comments to fix javadoc warnings - * - * Revision 1.1 2003/02/14 21:35:48 dietrick - * Initial revision - * - * Revision 1.14 2002/04/02 20:59:41 bmackiew - * Updated with revised copyright information. - * - * Revision 1.13 2000/06/21 22:40:29 dietrick - * Fixed the runoff of some partial words on the right side when partials weren't allowed. - * - * Added a main to RpfFrame to print out information about the frame file. - * - * Added a string converter to Location.java to translate N340000 to 34.000, etc. - * - * Revision 1.12 2000/05/08 14:22:19 wjeuerle - * BBNT Solutions LLC in copyright headers - * include Y2K in copyright years - * - * Revision 1.11 2000/01/21 03:44:08 dietrick - * Added the capability to set whether you want to allow objects to be - * straddling the edge of the map. - * - * Revision 1.10 1999/12/03 18:35:52 dietrick - * Changing System.out and System.error to Debug.output and Debug.error. - * - * Revision 1.9 1999/12/02 21:07:35 dietrick - * Comments and tweaks. - * - * Revision 1.8 1999/11/30 22:43:17 dietrick - * Updates and revamping. - * - * Revision 1.7 1999/10/07 22:15:45 dietrick - * Took out the reset function I added, because it's unnecessary. - * - * Revision 1.6 1999/10/07 16:08:51 dietrick - * Added a static getGraphics() call, which returns a fake graphics to - * use to figure out the dimensions of font metrics at projection time, - * as opposed to render time. - * - * Revision 1.5 1999/10/05 17:33:50 gkeith - * Cleaned up a bit, but not fully documented yet. - * Stay tuned... - * - * Revision 1.4 1999/09/10 17:54:17 pmanghwa - * Removed unnecessary checks - * - * Revision 1.3 1999/09/08 20:08:40 pmanghwa - * added methods to handle height. - * Slow but good looking - * - * Revision 1.2 1999/09/07 21:26:43 pmanghwa - * Now its Readable - * - * Revision 1.1 1999/08/24 19:02:35 gkeith - * JAVA-port of the old MATT decluttering code. - * - * - **********************************************************************/ - -package com.bbn.openmap.layer; - -import java.awt.GraphicsEnvironment; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; - -import com.bbn.openmap.util.Debug; - -/** - * This class represents the screen divided up into sections, and tracks the - * sections that are marked, for any reason. The pix_intervals are the height - * and width of the sections. isClear() returns 1 if the space is clear, and - * setTaken returns true if the space was clear and the space is now marked - * taken. - */ -public class DeclutterMatrix { - - /** - * The height of the screen to be covered by the matrix, in pixels. The - * number of vertical matrix cell is the height/y_pix_interval. - */ - protected int height = 0; - /** - * The width of the screen to be covered by the matrix, in pixels. The - * number of horizontal matrix cell is the width/x_pix_interval. - */ - protected int width = 0; - /** The number of horizontal pixels per matrix cell */ - protected int x_pix_interval = 1; - /** The number of vertical pixels per matrix cell */ - protected int y_pix_interval = 1; - /** The matrix itself, width x height. */ - protected boolean[][] matrix = new boolean[0][0]; - /** - * The maximum index for the horizontal locations within the matrix. - */ - protected int maxx; - /** - * The maximum index for the vertical locations within the matrix. - */ - protected int maxy; - /** - * Whether or not objects are allowed to appear partially off the matrix. If - * true, cells off the matrix will be automatically counted as clear. The - * default is true. - */ - protected boolean allowPartials = true; - /** - * A set of matrix indexes that get set for a particular object for a - * search. This is to limit the number of off matrix indexes used. - */ - protected MatrixIndexes indexes = new MatrixIndexes(); - /** - * A flag to force a recreation of the matrix if the dimensions change. - */ - protected boolean needToRecreate = false; - - /* - * These are all magic numbers that don't need to be anything in particular, - * apart from sequential. They are used to calculate where to next search - * for an opening in the matrix. The order reflects the pattern in which - * openings are searched for from the original position. In general, the - * original position is checked, and then alternatives are sought, checking - * the areas around the original in a search pattern. The search pattern is - * continued, but the distance from the original location is increased until - * a clear position is/is not found. As stated in the setNextOpen comments, - * the search pattern is a square, but the order of these notations let you - * control which sides/corners of the square are looked at first, in terms - * of finding an open space. The square expands outward until a place is - * found, or until no place is found, given some desired limit. - */ - public final static int DCP_MIDDLE = 20875; - public final static int DCP_EAST = 20876; - public final static int DCP_NORTH = 20877; - public final static int DCP_SOUTH = 20878; - public final static int DCP_WEST = 20879; - public final static int DCP_NEAST = 20880; - public final static int DCP_SEAST = 20881; - public final static int DCP_SWEST = 20882; - public final static int DCP_NWEST = 20883; - - /* - * The Declutter direction variables are general notations for the declutter - * positions. Within the search square, some positions, like along the side, - * present an opportunity to check in different places - for instance, if we - * are on the top part of the square, the search must travers East to West, - * hence, the direction is noted as DCD_EW. Corners have no search - * direction, and the left and right sides have North-South search traversal - * directions. - */ - public final static int DCD_NS = 20884; - public final static int DCD_EW = 20885; - public final static int DCD_NONE = 20886; - - /** - * This Denotes the parameters of one of the 8 possible positions around a - * decluttermatrix tile. - */ - public static class PositionParameters { - public int position; // should be one of the DCP variables - public int ewindex; - public int nsindex; - public int direction; // should be one of the DCD_ variables - - public PositionParameters(int pos, int ewindx, int nsindx, int direc) { - position = pos; - ewindex = ewindx; - nsindex = nsindx; - direction = direc; - } - } - - /** - * This is an ordering of the possible positions around a matrix tile. - */ - public final static PositionParameters dcPos[] = new PositionParameters[9]; - - static { // Now initialize it. - dcPos[0] = new PositionParameters(DCP_EAST, 1, 0, DCD_NS); - dcPos[1] = new PositionParameters(DCP_NORTH, 0, -1, DCD_EW); - dcPos[2] = new PositionParameters(DCP_SOUTH, 0, 1, DCD_EW); - dcPos[3] = new PositionParameters(DCP_WEST, -1, 0, DCD_NS); - dcPos[4] = new PositionParameters(DCP_NEAST, 1, -1, DCD_NONE); - dcPos[5] = new PositionParameters(DCP_SEAST, 1, 1, DCD_NONE); - dcPos[6] = new PositionParameters(DCP_SWEST, -1, 1, DCD_NONE); - dcPos[7] = new PositionParameters(DCP_NWEST, -1, -1, DCD_NONE); - dcPos[8] = new PositionParameters(DCP_MIDDLE, 0, 0, DCD_NONE); - } - - public class MatrixIndexes { - - public boolean withinMatrix = false; - public boolean partial = false; - public int xStart = 0; - public int yStart = 0; - public int xEnd = 0; - public int yEnd = 0; - - public int origXIndex = -1; - public int origYIndex = -1; - public int origIndexLength = 1; - public int origIndexHeight = 1; - - public MatrixIndexes() { - } - - public boolean setFromPixels(int pixelXLocation, int pixelYLocation, int pixelLength, int pixelHeight) { - int objXIndex = pixelXLocation / x_pix_interval; - int objYIndex = pixelYLocation / y_pix_interval; - int objLength = (int) Math.ceil((double) pixelLength / (double) x_pix_interval); - int objHeight = (int) Math.ceil((double) pixelHeight / (double) y_pix_interval); - return set(objXIndex, objYIndex, objLength, objHeight); - } - - public boolean setFromPixels(int pixelXLocation, int pixelYLocation) { - int objXIndex = pixelXLocation / x_pix_interval; - int objYIndex = pixelYLocation / y_pix_interval; - return set(objXIndex, objYIndex, origIndexLength, origIndexHeight); - } - - public boolean set(int objXIndex, int objYIndex) { - return set(objXIndex, objYIndex, origIndexLength, origIndexHeight); - } - - public boolean set(int objXIndex, int objYIndex, int objIndexLength, int objIndexHeight) { - - // Save as reference - origXIndex = objXIndex; - origYIndex = objYIndex; - - // This may be redundant, but so what. It's too hard to - // tell... - origIndexLength = objIndexLength; - origIndexHeight = objIndexHeight; - - withinMatrix = objOnMatrix(objXIndex, objYIndex, objIndexLength, objIndexHeight); - if (!withinMatrix) { - return false; - } - - // End variables refer to an end index - partial = false; - // Set the end of the check - if the end sticks out past - // the - // matrix, just check the part that's on the matrix. If - // it's - // left of the matrix, don't bother going into the loop by - // setting the end point to 0. - if ((objXIndex + objIndexLength) <= maxx) { - xEnd = objXIndex + objIndexLength; - } else { - xEnd = maxx; - partial = true; - } - if (xEnd < 0) - xEnd = 0; - - // Now do the vertical version of the same thing... - if ((objYIndex + objIndexHeight) <= maxy) { - yEnd = objYIndex + objIndexHeight; - } else { - yEnd = maxy; - partial = true; - } - if (yEnd < 0) - yEnd = 0; - - // And, figure out what the good starting index point is - // to - // check for vertical conflicts - This is all to make the - // checkMatrixLocation methods run as efficiently as - // possible. - if (objYIndex >= 0) { - yStart = objYIndex; - } else { - objYIndex = 0; - partial = true; - } - // And horizontal starting index - if (objXIndex >= 0) { - xStart = objXIndex; - } else { - xStart = 0; - partial = true; - } - - return true; - } - - /** - * Test to see if the object is on the matrix. Assumes that the matrix - * is not null. - * - * @return true if object is on matrix. - */ - public boolean objOnMatrix(int objXIndex, int objYIndex, int objIndexLength, int objIndexHeight) { - if (objXIndex + objIndexLength < 0 || // left off-matrix - objYIndex + objIndexHeight < 0 || // below matrix - // right off-matrix and above matrix - objXIndex > maxx || objYIndex > maxy) { - return false; - } - return true; - } - } - - /** - * Set whether names can appear partially on/off the map. True means they - * can, i.e., the spaces off the map are by default, clear. - */ - public void setAllowPartials(boolean value) { - allowPartials = value; - } - - /** - * Find out whether the spaces off the map are counted as clear and - * available. If they are, then objects can appear partially on the map. - */ - public boolean isAllowPartials() { - return allowPartials; - } - - /** ******************************************************************* */ - - /** - * Construct a new DeclutterMatrix, given the screen dimensions and the size - * of the matrix cells - */ - public DeclutterMatrix(int width, int height, int x_pix_interval, int y_pix_interval) { - this.width = width; - this.height = height; - if (x_pix_interval != 0) { - this.x_pix_interval = x_pix_interval; - } else { - x_pix_interval = 1; - } - - if (y_pix_interval != 0) { - this.y_pix_interval = y_pix_interval; - } else { - y_pix_interval = 1; - } - - this.matrix = null; - - this.maxx = (this.width / this.x_pix_interval) - 1; - this.maxy = (this.height / this.y_pix_interval) - 1; - create(); - Debug.message("declutter", "Decluttering matrix created." + " Width = " + width + " Height = " + height); - } - - /** - * Construct a new matrix, given the screen dimensions, and using the - * default matrix cell size - */ - public DeclutterMatrix(int width, int height) { - this(width, height, 1, 1); - } - - /** Create a new matrix, with null dimensions */ - public DeclutterMatrix() { - this(0, 0); - } - - /* - * Any of these delete the current matrix if it exists and resets the - * variable. create() needs to be called to recreate a new matrix after all - * the changes. - */ - - public void setXInterval(int x_pix_interval) { - if (x_pix_interval != 0) { - this.x_pix_interval = x_pix_interval; - } else { - this.x_pix_interval = 1; // To avoid DBZ error? - } - this.maxx = (this.width / this.x_pix_interval) - 1; - needToRecreate = true; - Debug.message("declutter", "Decluttering matrix: x_pix_interval changed to " + x_pix_interval); - } - - public void setYInterval(int y_pix_interval) { - if (y_pix_interval != 0) { - this.y_pix_interval = y_pix_interval; - } else { - this.y_pix_interval = 1; - } - this.maxy = (this.height / this.y_pix_interval) - 1; - needToRecreate = true; - Debug.message("declutter", "Decluttering matrix: y_pix_interval changed to " + y_pix_interval); - } - - public void setWidth(int width) { - this.width = width; - this.maxx = (this.width / this.x_pix_interval) - 1; - needToRecreate = true; - - Debug.message("declutter", "Decluttering matrix: Width reset to " + width); - } - - public void setHeight(int height) { - this.height = height; - this.maxy = (this.height / this.y_pix_interval) - 1; - needToRecreate = true; - - Debug.message("declutter", "Decluttering matrix: height reset to " + height); - } - - /** - * Allocate the matrix. - * - * @return true if successful, and if the height and width settings were - * valid (>0). - */ - public boolean create() { - if ((height > 0) && (width > 0)) { - matrix = new boolean[maxx + 1][maxy + 1]; - needToRecreate = false; - return true; - } - needToRecreate = true; - return false; - } - - /** - * Query whether the matrix is clear, given a set of indexes. - * - * @param indexes the set of indexes - * @param markAsTaken mark the spaces as used if they are previously clear. - * @return true if they were clear previously. - */ - protected boolean isClear(MatrixIndexes indexes, boolean markAsTaken) { - - Debug.message("declutterdetail", "DeclutterMatrix: Checking space for clear."); - - if (this.matrix == null) { - return false; - } - - if (!indexes.withinMatrix) { - // But, withinMatrix doesn't tell you if there is a - // partial. It only tells you if any part of the object - // is over the matrix. So, if it's not within the Matrix, - // the answer should be yes, all the time, because you - // don't have to declutter what you can't see... - - // return allowPartials; - return true; - } - - if (!allowPartials && indexes.partial) { - return false; - } - - // OK - the above check should verify that some part of the - // object is on the matrix - so there is a reason to set the - // limits for the matrix search below, and not worry about - // dealing with funky index values. - - boolean notClear = false; - - // Since we have the matrix index limits, have two loops, the - // first to check for the open cells, the other to mark the - // cells as occupied. The second loop only gets run if the - // markAsTaken flag is set by the caller. - for (int taken = 0; taken < 2; taken++) { - - // Check to see if the horizontal indexes are on the - // matrix - i should be at least greater than zero here, - // as should j. - for (int i = indexes.xStart; i <= indexes.xEnd; i++) { - - // Check for loop - the first loop is to see if - // the spaces are open. - if (taken == 0) { - notClear = isMatrixLocationTaken(i, indexes.yStart, indexes.yEnd - indexes.yStart + 1); - if (notClear) { - return false; - } - } else { - // The second loop is to mark the cells as - // taken - setTaken(i, indexes.yStart, indexes.yEnd - indexes.yStart + 1); - } - } - - // This will prevent the second loop from occurring if it's - // not supposed to - the caller just wanted to check the - // spaces, rather than check and mark. - if (!markAsTaken) { - return true; - } - } - return true; - } - - /** - * Check a vertical portion of the matrix, to see if it has already been - * taken. If a query occurs that is outside the matrix, this returns false. - * - * @param horizontalIndex the horizontal index of the matrix to check. - * @param verticalIndex the vertical starting index of the matrix to check. - * @param numCellsToCheck the number of matrix cells to check for taken. - * @return true if taken, false if available. - */ - protected boolean isMatrixLocationTaken(int horizontalIndex, int verticalIndex, int numCellsToCheck) { - try { - for (int i = numCellsToCheck - 1; i >= 0; i--) { - if (matrix[horizontalIndex][verticalIndex + i]) { - return true; - } - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - return allowPartials; - } - return false; - } - - /** - * Mark a vertical portion of the matrix as taken. - * - * @param horizontalIndex the horizontal index of the matrix to mark. - * @param verticalIndex the vertical starting index of the matrix to mark. - * @param numCellsToMark the number of matrix cells to mark as taken. - */ - protected void setTaken(int horizontalIndex, int verticalIndex, int numCellsToMark) { - try { - for (int i = numCellsToMark - 1; i >= 0; i--) { - matrix[horizontalIndex][verticalIndex + i] = true; - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - } - - /** - * SetTaken returns true if the space was clear before the it was taken, - * false if it was not. Either way, the spaces are marked. Except if the - * matrix is not built, in which case false is returned anyway. - * - * @param indexes the start and end matrix indexes for an object. - * @return true if successful. - */ - protected boolean setTaken(MatrixIndexes indexes) { - if (this.matrix == null) { - return false; - } - - if (!indexes.withinMatrix) { - return allowPartials; - } - - for (int i = indexes.xStart; i < indexes.xEnd; i++) { - setTaken(i, indexes.yStart, indexes.yEnd - indexes.yStart + 1); - } - return true; - } - - /** - * Set an area as taken, given a point and a length of pixels. The length is - * checked from left to right. - */ - public boolean setTaken(Point point, int pixelLength) { - return setTaken(point, pixelLength, y_pix_interval); - } - - /** - * Set an area as taken, given a point, a length of pixels and a height of - * pixels. The length is from left to right, the height from the bottom to - * top (NOT like screen coordinates) - */ - public boolean setTaken(Point point, int pixelLength, int pixelHeight) { - if (needToRecreate) - create(); - - indexes.setFromPixels(point.x, point.y, pixelLength, pixelHeight); - return setTaken(indexes); - } - - /** - * The method to call if you are trying to set something in an open place, - * anywhere on the map. - * - * @param point the window point - * @param pixelLength the pixel length of space from left to right. - * @param pixelHeight the pixel height from bottom to top. - * @return Point of closest open space. - */ - public Point2D setNextOpen(Point2D point, int pixelLength, int pixelHeight) { - return setNextOpen(point, pixelLength, pixelHeight, -1); - } - - /** - * The method to call if you are trying to set something in an open place, - * but want to limit how far away the object could be placed. - * - * @param point the window point - * @param pixelLength the pixel length of space from left to right. - * @param pixelHeight the pixel height from bottom to top. - * @param pixelAwayLimit the pixel distance away from the original location - * that where an object will be discarded if it's not at least - * that close. -1 means find anywhere on the map where the object - * will fit. - * @return Point of closest open space. - */ - public Point2D setNextOpen(Point2D point, int pixelLength, int pixelHeight, int pixelAwayLimit) { - - Debug.message("declutterdetail", "DeclutterMatrix: Trying to find an open space."); - - if (needToRecreate) - create(); - - int pointx = (int) point.getX(); - int pointy = (int) point.getY(); - boolean set = false; - - // mark the original spot. These are indexes, not pixels. - int windex = pointx / x_pix_interval; - int hindex = pointy / y_pix_interval; - - // intermediate values used for ew/ns spanning. This are not - // pixels, they are indexes into the matrix - int xpoint; - int ypoint; - - // The point to be returned with the new, declutter postition - // for the object. - Point ret = null; - // Test point, for memory allocation savings. - Point testPoint = new Point(); - - // A round is a cycle through the positions in the search - // algorithm. With every round the distance from the original - // position increases. The search pattern looks like an - // expanding square, and it's broken into different pieces: - // Each side, not including the corners, and each corner. - - int round = 0; // Round 1, round 2 - get it!?!? - int pos, i; - - // Set up the indexes for the original spot. - indexes.setFromPixels(pointx, pointy, pixelLength, pixelHeight); - - // Make sure the graphic is on the visible screen - if (matrix == null || !indexes.withinMatrix) { - return point; - } - - // Do check for the center here, before looping. Who knows, - // the space might be open. - ret = isAreaClearR(windex, hindex, testPoint); - int round_limit; - if (pixelAwayLimit < 0) { - round_limit = Math.abs(maxy / 2 - indexes.yStart) + (maxy / 2); - } else { - round_limit = pixelAwayLimit; - } - - // Now that we know it is not open, move on and start - // searching for - // the right place. - while (ret == null) { - - Debug.message("declutterdetail", "DeclutterMatrix: round " + round + "\n"); - round++; - for (pos = 0; (dcPos[pos].position != DCP_MIDDLE) && (ret == null); pos++) { - - // Need to do this based on the length, so as to skip - // unnecessary checks. The xpoint and ypoint are the - // starting point for each little incremental search. - // This point, in every round, spirals outward from - // the original desired location. - xpoint = windex + (round * dcPos[pos].ewindex); - ypoint = hindex + (round * dcPos[pos].nsindex); - - // checks to keep starting point away from being - // offscreen - if (xpoint <= maxx && ypoint <= maxy && xpoint >= 0 && ypoint >= 0) { - - // Start at handling the parts of the search - // square that make up the sides of the square - - // DCD_NS refers to the fact that the search - // pattern is traversing up the side of the - // square, for either side. - - // for the east and west checks, look - // a north and south variations - if (dcPos[pos].direction == DCD_NS) { - for (i = -1 * (round - 1); (i < round - 1) && !set; i++) { - - // isAreaClearR used to be used here in - // order to prevent a name from being - // written over an icon. You know, if the - // icon shouldn't be written over, let it - // be added to the matrix before the name. - // Then it won't be covered. - - // // Don't look both ways if directly to - // the - // // east, you'll write over the icon - // if(dcPos[pos].position == DCP_EAST && - // i <= pixelHeight) { - // ret = isAreaClearR(xpoint, - // ypoint+i, - // testPoint); - // } else { - ret = isAreaClearBW(xpoint, ypoint + i, testPoint); - // } - - // If we've found a clear spot, jump out. - if (ret != null) - break; - } - } else { - - // Now we're checking the top and bottom of - // the search square, which moves East-West - - // for the north and south check, look - // at EW variations - if (dcPos[pos].direction == DCD_EW) { - for (i = round - 1; (i >= -1 * (round - 1)) && !set; i--) { - ret = isAreaClearBW(xpoint + i, ypoint, testPoint); - - // If we've found a clear spot, jump - // out. - if (ret != null) - break; - } - - } else { - - // This part of the code handles the - // corners of the square. - - // looking at the corners for the - // search pattern - ret = isAreaClearBW(xpoint, ypoint, testPoint); - } - } - } - } - - if (round > round_limit) { - break; - } - } // while (ret == null) - - if (ret != null) { - if (Debug.debugging("declutter")) { - Debug.output("Placing object at " + ret.x + " | " + ret.y); - } - } else { - Debug.message("declutter", "Decluttering: No space for entry."); - // If you got here, space not found, toss - // oject offscreen - ret = testPoint; - ret.x = -1 * windex; - ret.y = -1 * hindex; - } - - return ret; - } - - /***************************************************************** - * Protected Methods - ****************************************************************/ - - /** - * Check to see if there is space to the right of the desired place. - * - * @return point for a good clear space, null if not. - */ - protected Point isAreaClearR(int xPoint, int yPoint, Point point) { - Debug.message("declutterdetail", "Decluttering: Checking to the right..."); - if (!indexes.setFromPixels(xPoint, yPoint)) { - return null; - } - - if (isClear(indexes, true)) { - point.x = xPoint; - point.y = yPoint; - Debug.message("declutterdetail", "*******Decluttering: found a spot"); - - return point; - } - return null; - } - - /** - * Check to see if there is space to the left and right. This just checks - * for all the way to the right, and all the way to the left. - * - * @return Point for a good space, null if not. - */ - protected Point isAreaClearBWT(int xPoint, int yPoint, Point point) { - Debug.message("declutterdetail", "Decluttering: Checking both ways..."); - if (!indexes.setFromPixels(xPoint, yPoint)) { - return null; - } - - if (isClear(indexes, true)) { - point.x = xPoint; - point.y = yPoint; - Debug.message("declutterdetail", "*******Decluttering: found a spot"); - - return point; - } - - int leftMostIndex = indexes.origXIndex - indexes.origIndexLength; - - if (!indexes.set(leftMostIndex, indexes.origYIndex)) { - return null; - } - - if (isClear(indexes, true)) { - point.x = leftMostIndex * x_pix_interval; - point.y = yPoint; - Debug.message("declutterdetail", "*******Decluttering: found a spot"); - - return point; - } - return null; - } - - /** - * Looks both ways for a clear space BW = Both ways = look both ways = check - * left and right. This method will look all the way to the rigth, and then - * check incrementally to the left until it's looking all the way there. - * - * @return point of some good place is found, null if not. - */ - protected Point isAreaClearBW(int xPoint, int yPoint, Point point) { - - Debug.message("declutterdetail", "Decluttering: Checking both ways..."); - - // Check to see if it's totally offscreen. If it is, keep it - // there.. Also check to see if the first location is good - // (isClear) - if (!indexes.setFromPixels(xPoint, yPoint) || isClear(indexes, true)) { - point.x = xPoint; - point.y = yPoint; - return point; - } - - // Guess not. Step our way to the left to see if anything is - // available... - - // We're going to test the right, and then work our way left - // until the original spot is the rightmost spot. - int leftMostIndex = indexes.origXIndex - indexes.origIndexLength; - - // Start by keeping track of clear vertical cells. If we get - // a run of them that equals the origIndexLength, then we have - // space right there. - int count = 0; - int currentXIndex = indexes.origXIndex + indexes.origIndexLength; - - while (count < indexes.origIndexLength && currentXIndex > leftMostIndex) { - - if (!indexes.set(currentXIndex, indexes.origYIndex)) { - // Still off the matrix - count = 0; - currentXIndex--; - continue; - } - - if (currentXIndex >= 0 && currentXIndex <= maxx) { - if (!isMatrixLocationTaken(currentXIndex, indexes.yStart, indexes.yEnd - indexes.yStart + 1)) { - count++; // clear column - } else { - count = 0; // Start counting again - } - } else { - // If we are off the matrix, check and see if we want - // to consider those space as open autmatically. - if (allowPartials) { - count++; - } else { - // This will not, Because it makes it look like - // we ran out of space. - count = 0; - } - } - - if (count < indexes.origIndexLength) { - currentXIndex--; - } - - } - - // So, either we ran out of space, or we found a space big - // enough for the text. - if (count >= indexes.origIndexLength) { - point.x = currentXIndex * x_pix_interval; - point.y = yPoint; - - indexes.xStart = currentXIndex; - setTaken(indexes); - Debug.message("declutterdetail", "Decluttering: found a spot"); - return point; - } - // Ran out of space. - return null; - } - - private static java.awt.Graphics2D workingGraphics = null; - - /** - * This is a graphics that is only available to fiddle around with text and - * fonts, in order to get pre-measurements. DO NOT write anything into this - * thing. - * - * @return java.awt.Graphics2D - */ - public static java.awt.Graphics2D getGraphics() { - if (workingGraphics == null) { - BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - - workingGraphics = ge.createGraphics(bi); - } - - return workingGraphics; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/DrawingToolLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/DrawingToolLayer.java deleted file mode 100644 index 695d99203..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/DrawingToolLayer.java +++ /dev/null @@ -1,843 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/DrawingToolLayer.java,v $ -// $RCSfile: DrawingToolLayer.java,v $ -// $Revision: 1.35 $ -// $Date: 2008/02/28 23:36:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.StreamCorruptedException; -import java.net.URL; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.DbfTableModelFactory; -import com.bbn.openmap.dataAccess.shape.EsriShapeExport; -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.MapMouseSupport; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.DrawingTool; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * This layer can receive graphics from the OMDrawingToolLauncher, and also sent - * it's graphics to the OMDrawingTool for editing. - *

- * - * The projectionChanged() method is taken care of in the OMGraphicHandlerLayer - * superclass. - *

- * - * This class responds to all the properties that the OMGraphicHandlerLayer - * responds to, including the mouseModes property. If the mouseModes property - * isn't set, the SelectMouseMode.modeID mode ID is set. When the - * MapMouseInterpreter calls select(OMGraphic), the OMGraphic is passed to the - * DrawingTool. This class also responds to the showHints property (true by - * default), which dictates if tooltips and information delegator text is - * displayed when the layer's contents are moused over. - * - *

- * 
- *   # Properties for DrawingToolLayer:
- *   drawingToolLayer.class=com.bbn.openmap.layer.DrawingToolLayer
- *                              
- *   drawingToolLayer.prettyName=General Layer
- *                              
- *   # optional flag to tell layer to display tooltip queues over it's OMGraphics
- *   drawingToolLayer.showHints=true
- *                               
- *   # optional flag to specify file to store and read OMGraphics.  A Save button 
- *   # is available on the palette.  If it's not specified and the Save button is 
- *   # chosen, the user will queried for this location.
- *   drawingToolLayer.file=file to read OMGraphics from
- * 
- * 
- */ -public class DrawingToolLayer extends OMGraphicHandlerLayer implements DrawingToolRequestor { - - private static final long serialVersionUID = 1L; - - /** Get a handle on the DrawingTool. */ - protected OMDrawingTool drawingTool; - - /** - * A flag to provide a tooltip over OMGraphics to click to edit. - */ - protected boolean showHints = true; - - /** - * A property that can control whether mouse events generate hints over map - * objects (showHints). - */ - public final static String ShowHintsProperty = "showHints"; - - /** - * A property to specify the file to use to read and save map objects in - * (file). - */ - public final static String SerializedURLNameProperty = "file"; - - /** - * The name of the file to read/save OMGraphics in. - */ - protected String fileName; - - protected boolean DTL_DEBUG = false; - - protected DbfTableModelFactory dbfFactory = null; - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - protected OMGraphicList omGraphics; - - public DrawingToolLayer() { - setAddToBeanContext(true); - - DTL_DEBUG = Debug.debugging("dtl"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - drawingAttributes.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - showHints = PropUtils.booleanFromProperties(props, realPrefix + ShowHintsProperty, showHints); - - if (getMouseModeIDsForEvents() == null) { - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - } - - String fileName = props.getProperty(realPrefix + SerializedURLNameProperty); - - String dataPathPrefix = (String) getAttribute(DataPathPrefixProperty); - if (dataPathPrefix != null) { - fileName = dataPathPrefix + "/" + fileName; - } - - if (fileName != null && fileName.trim().length() > 0) { - this.fileName = fileName; - setOMGraphics(load()); - } - - if (dbfFactory != null) { - dbfFactory.setProperties(prefix, props); - - OMGraphicList list = getOMGraphics(); - if (list != null && list.getAttribute(ShapeConstants.DBF_ATTRIBUTE) == null) { - dbfFactory.createDbf(list); - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - drawingAttributes.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ShowHintsProperty, new Boolean(showHints).toString()); - props.put(prefix + SerializedURLNameProperty, PropUtils.unnull(fileName)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - drawingAttributes.getPropertyInfo(props); - - String interString; - - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, I18n.TOOLTIP, - "Display tooltips over layer's map objects."); - props.put(ShowHintsProperty, interString); - props.put(ShowHintsProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, "Show Hints"); - props.put(ShowHintsProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingToolLayer.class, SerializedURLNameProperty, I18n.TOOLTIP, - "File to use for reading and saving map objects."); - props.put(SerializedURLNameProperty, interString); - props.put(SerializedURLNameProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, "File Name for Saving"); - props.put(SerializedURLNameProperty + LabelEditorProperty, interString); - - props.put(initPropertiesProperty, SerializedURLNameProperty + " " + ShowHintsProperty); - return props; - } - - public synchronized OMGraphicList prepare() { - - Projection proj = getProjection(); - - OMGraphicList currentGraphics = getOMGraphics(); - if (currentGraphics == null) { - currentGraphics = load(); - setOMGraphics(currentGraphics); - } - - if (currentGraphics != null && proj != null) { - currentGraphics.generate(proj); - currentGraphics.setVisible(true); - return new OMGraphicList(currentGraphics); - } - - return null; - } - - public OMDrawingTool getDrawingTool() { - return drawingTool; - } - - public void setDrawingTool(OMDrawingTool dt) { - drawingTool = dt; - } - - /** - * This is the managed list of OMGraphics, the internal list used for - * rendering. - * - * @param omgList - */ - public void setOMGraphics(OMGraphicList omgList) { - omGraphics = omgList; - } - - public OMGraphicList getOMGraphics() { - return omGraphics; - } - - /** - * DrawingToolRequestor method. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - - if (DTL_DEBUG) { - String cname = omg.getClass().getName(); - int lastPeriod = cname.lastIndexOf('.'); - if (lastPeriod != -1) { - cname = cname.substring(lastPeriod + 1); - } - Debug.output("DrawingToolLayer: DrawingTool complete for " + cname + " > " + action); - } - // First thing, release the proxy MapMouseMode, if there is - // one. - releaseProxyMouseMode(); - - // GRP, assuming that selection is off. - OMGraphicList omgl = new OMGraphicList(); - omg.putAttribute(OMGraphicConstants.UPDATED, Boolean.TRUE); - omgl.add(omg); - deselect(omgl); - - OMGraphicList list = getOMGraphics(); - - if (list == null) { - list = new OMGraphicList(); - setOMGraphics(list); - } - - DbfTableModel dbf = (DbfTableModel) list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - // Adding an OMGraphic without dbf being set, if we can create one - // from a factory, do it. - if (dbf == null && dbfFactory != null) { - dbf = dbfFactory.createDbf(list); - } - - if (dbf != null) { - dbf.doAction(list, omg, action, dbfFactory); - } else { - list.doAction(omg, action); - } - doPrepare(); - } - - /** - * If the DrawingToolLayer is using a hidden OMDrawingTool, release the - * proxy lock on the active MapMouseMode. - */ - public void releaseProxyMouseMode() { - MapMouseMode pmmm = getProxyMouseMode(); - OMDrawingTool dt = getDrawingTool(); - if (pmmm != null && dt != null) { - if (pmmm.isProxyFor(dt.getMouseMode())) { - if (DTL_DEBUG) { - Debug.output("DTL: releasing proxy on " + pmmm.getID()); - } - - pmmm.releaseProxy(); - setProxyMouseMode(null); - fireRequestInfoLine(""); // hidden drawing tool put up - // coordinates, clean up. - } - - if (dt.isActivated()) { - dt.deactivate(); - } - } - } - - /** - * Called by findAndInit(Iterator) so subclasses can find objects, too. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof OMDrawingTool) { - Debug.message("dtl", "DrawingToolLayer: found a drawing tool"); - setDrawingTool((OMDrawingTool) someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. - */ - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof DrawingTool && getDrawingTool() == someObj) { - setDrawingTool(null); - } - } - - protected MapMouseMode proxyMMM = null; - - /** - * Set the ProxyMouseMode for the internal drawing tool, if there is one. - * Can be null. Used to reset the mouse mode when drawing's complete. - */ - protected synchronized void setProxyMouseMode(MapMouseMode mmm) { - proxyMMM = mmm; - } - - /** - * Get the ProxyMouseMode for the internal drawing tool, if there is one. - * May be null. Used to reset the mouse mode when drawing's complete. - */ - protected synchronized MapMouseMode getProxyMouseMode() { - return proxyMMM; - } - - /** - * A method called from within different MapMouseListener methods to check - * whether an OMGraphic *should* be edited if the OMDrawingTool is able to - * edit it. Can be used by subclasses to delineate between OMGraphics that - * are non-relocatable versus those that can be moved. This method should - * work together with the getToolTipForOMGraphic() method so that OMGraphics - * that shouldn't be edited don't provide tooltips that suggest that they - * can be. - *

- * - * By default, this method always returns true because the DrawingToolLayer - * always thinks the OMGraphic should be edited. - */ - public boolean shouldEdit(OMGraphic omgr) { - return true; - } - - protected JPanel box; - protected JComboBox jcb; - - public Component getGUI() { - if (box == null) { - - String interString = i18n.get(DrawingToolLayer.class, "QUERY_HEADER", "What would you like to do?"); - - box = PaletteHelper.createVerticalPanel(interString); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - box.setLayout(gridbag); - - jcb = new JComboBox(getActions()); - c.gridx = GridBagConstraints.REMAINDER; - gridbag.setConstraints(jcb, c); - box.add(jcb); - - JPanel goPanel = new JPanel(); - gridbag.setConstraints(goPanel, c); - box.add(goPanel); - - interString = i18n.get(DrawingToolLayer.class, "OK", "OK"); - JButton button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "OK", I18n.TOOLTIP, "Do action and dismiss window."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - doIt(); - hidePalette(); - } - }); - goPanel.add(button); - - interString = i18n.get(DrawingToolLayer.class, "Apply", "Apply"); - button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "Apply", I18n.TOOLTIP, "Do action and leave window up."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - doIt(); - } - }); - goPanel.add(button); - - interString = i18n.get(DrawingToolLayer.class, "Cancel", "Cancel"); - button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "Cancel", I18n.TOOLTIP, "Do nothing and dismiss window."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - hidePalette(); - } - }); - goPanel.add(button); - - } - - return box; - } - - protected void doIt() { - if (jcb != null) { - ((javax.swing.Action) jcb.getSelectedItem()).actionPerformed(null); - } - } - - protected Vector actions; - - /** - * You can override this class if you want to provide more, fewer or - * different actions to the user. - * - * @return Vector of Actions - */ - @SuppressWarnings("serial") - protected Vector getActions() { - if (actions == null) { - actions = new Vector(); - - actions.add(new AbstractAction() { - public void actionPerformed(ActionEvent e) { - OMGraphicList list = getOMGraphics(); - Object obj = list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - DbfTableModel dbf = null; - - if (obj instanceof DbfTableModel) { - dbf = (DbfTableModel) obj; - } else if (dbfFactory != null) { - dbf = dbfFactory.createDbf(list); - } - - if (dbf == null) { - dbf = new DbfTableModel(0); - int numGraphics = list.size(); - for (int i = 0; i < numGraphics; i++) { - dbf.addBlankRecord(); - } - list.putAttribute(ShapeConstants.DBF_ATTRIBUTE, dbf); - } - dbf.setExitOnClose(false); - dbf.setWritable(true); - dbf.showGUI(getName() + " Attributes", DbfTableModel.MODIFY_COLUMN_MASK - | DbfTableModel.MODIFY_ROW_MASK | DbfTableModel.SAVE_MASK | DbfTableModel.DONE_MASK); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "UPDATE_ATTRIBUTES", "Update feature attributes"); - } - }); - - actions.add(new AbstractAction() { - public void actionPerformed(ActionEvent e) { - saveOMGraphics(getProjection()); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "SAVE_MAP", "Save map"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - OMGraphicList list = new OMGraphicList(getOMGraphics()); - if (list != null && !list.isEmpty()) { - Object obj = list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - - if (!(obj instanceof DbfTableModel) && dbfFactory != null) { - // If there isn't a dbf table model, create one if - // the DbfTableModelFactory has been configured. - dbfFactory.createDbf(list); - } - - String title = i18n.get(DrawingToolLayer.class, "SHAPE_SAVE_MAP_TITLE", "Save Shape File"); - String saveFilePath = FileUtils.getFilePathToSaveFromUser(title); - - if (saveFilePath != null) { - setFileName(saveFilePath); - } - - EsriShapeExport ese = new EsriShapeExport(list, getProjection(), saveFilePath); - ese.setTransform(coordTransform); - ese.export(); - - } else { - String message = i18n.get(DrawingToolLayer.class, "SHAPE_ERROR_MESSAGE", - "There's nothing on the map for this layer to save."); - fireRequestMessage(message); - } - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "SHAPE_SAVE_MAP", "Save map as Shape file(s)"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - setOMGraphics(load()); - doPrepare(); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "RELOAD", "Re-load map from file"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - Inspector inspector = new Inspector(); - inspector.inspectPropertyConsumer(DrawingToolLayer.this); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "PREFERENCES", "Change preferences"); - } - }); - } - return actions; - } - - /** - * Get the current OMGraphicList and save it out to the file named in this - * class. If that's null, the user will be asked for one. - * - */ - public void saveOMGraphics(Projection proj) { - if (fileName == null) { - fileName = FileUtils.getFilePathToSaveFromUser( - i18n.get(DrawingToolLayer.class, "CHOOSE_SAVE", "Choose file to use to save layer:")); - } - - if (fileName != null) { - OMGraphicList list = getOMGraphics(); - - if (fileName.toLowerCase().endsWith(".shp")) { - EsriShapeExport ese = new EsriShapeExport(list, proj, fileName); - ese.setTransform(getCoordTransform()); - ese.export(); - } else { - - if (list != null) { - try { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(list); - oos.close(); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } - - /** - * Load the data from the file set in this layer. - * - * @return OMGraphicList loaded from fileName. - */ - public OMGraphicList load() { - OMGraphicList graphicList = new OMGraphicList(); - boolean err = false; - - if (fileName != null) { - try { - OMGraphicList list = null; - URL url = PropUtils.getResourceOrFileOrURL(fileName); - if (url != null) { - if (fileName.endsWith(".shp")) { - list = EsriShapeExport.read(url, drawingAttributes, getCoordTransform()); - // Now that we've established that we are working (or - // want to work with) with a - // shape file, create a dbfFactory for the layer to help - // out with editing. - dbfFactory = new DbfTableModelFactory(); - } else { - ObjectInputStream ois = new ObjectInputStream(url.openStream()); - list = (OMGraphicList) ois.readObject(); - ois.close(); - } - } - - if (list != null) { - graphicList.addAll(list); - graphicList.setAttributes(list.getAttributes()); - } - } catch (FileNotFoundException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (StreamCorruptedException sce) { - sce.printStackTrace(); - fireRequestMessage(i18n.get(DrawingToolLayer.class, "LOAD_ERROR", - "The file doesn't appear to be a valid map file")); - err = true; - } catch (IOException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (ClassNotFoundException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (ClassCastException cce) { - if (DTL_DEBUG) { - cce.printStackTrace(); - } - err = true; - } - } - // Something went wrong, we don't want to overwrite something - // that might potentially be something else if a save is - // called for later. - if (err) { - fileName = null; - } - return graphicList; - } - - /** - * A flag to provide a tooltip over OMGraphics to click to edit. - */ - public void setShowHints(boolean show) { - showHints = show; - } - - public boolean getShowHints() { - return showHints; - } - - /** - * Query that an OMGraphic can be highlighted when the mouse moves over it. - * If the answer is true, then highlight with this OMGraphics will be - * called, in addition to getInfoText() and getToolTipTextFor() - */ - public boolean isHighlightable(OMGraphic omg) { - return showHints; - } - - /** - * Query that an OMGraphic is selectable. - */ - public boolean isSelectable(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - return (shouldEdit(omg) && dt != null && dt.canEdit(omg.getClass())); - } - - String editInstruction = i18n.get(DrawingToolLayer.class, "CLICK_TO_EDIT", "Click to edit."); - - /** - * Query for what text should be placed over the information bar when the - * mouse is over a particular OMGraphic. - */ - public String getInfoText(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - if (dt != null && dt.canEdit(omg.getClass())) { - return editInstruction; - } else { - return null; - } - } - - /** - * Query for what tooltip to display for an OMGraphic when the mouse is over - * it. - */ - public String getToolTipTextFor(OMGraphic omgr) { - OMDrawingTool dt = getDrawingTool(); - if (shouldEdit(omgr) && dt.canEdit(omgr.getClass()) && !dt.isActivated()) { - return editInstruction; - } else { - return null; - } - } - - /** - * GestureResponsePolicy method. - */ - public void select(OMGraphicList omgl) { - super.select(omgl); - if (omgl != null && !omgl.isEmpty()) { - if (omgl.size() == 1) { - edit(omgl.getOMGraphicAt(0)); - } else { - edit(omgl); - } - } - } - - public void edit(OMGraphic omg) { - - OMDrawingTool dt = getDrawingTool(); - - if (dt != null && dt.canEdit(omg.getClass())) { - - // if (dt.isEditing(omg)) { - // dt.deselect(omg); - // return; - // } - - dt.resetBehaviorMask(); - - MapMouseMode omdtmm = dt.getMouseMode(); - if (!omdtmm.isVisible()) { - dt.setMask(OMDrawingTool.PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK); - } - - MapMouseInterpreter mmi = (MapMouseInterpreter) getMapMouseListener(); - - MouseEvent mevent = null; - if (mmi != null) { - mevent = mmi.getCurrentMouseEvent(); - } - - if (omg.isSelected()) { - omg.deselect(); - } - - if (dt.select(omg, this, mevent)) { - // OK, means we're editing - let's lock up the - // MouseMode - if (DTL_DEBUG) { - Debug.output("DTL: starting edit of OMGraphic..."); - } - - // Check to see if the DrawingToolMouseMode wants to - // be invisible. If it does, ask the current - // active MouseMode to be the proxy for it... - if (!omdtmm.isVisible() && mevent instanceof MapMouseEvent) { - MapMouseMode mmm = ((MapMouseEvent) mevent).getMapMouseMode(); - if (mmm.actAsProxyFor(omdtmm, - MapMouseSupport.PROXY_DISTRIB_MOUSE_MOVED & MapMouseSupport.PROXY_DISTRIB_MOUSE_DRAGGED)) { - if (DTL_DEBUG) { - Debug.output("DTL: Setting " + mmm.getID() + " as proxy for drawing tool"); - } - setProxyMouseMode(mmm); - } else { - // WHOA, couldn't get proxy lock - bail - if (DTL_DEBUG) { - Debug.output("DTL: couldn't get proxy lock on " + mmm.getID() - + " deactivating internal drawing tool"); - } - dt.deactivate(); - } - } else { - if (DTL_DEBUG) { - Debug.output("DTL: MouseMode wants to be visible(" + (omdtmm.isVisible()) - + "), or MouseEvent is not a MapMouseEvent(" + !(mevent instanceof MapMouseEvent) - + ")"); - } - } - } else { - if (DTL_DEBUG) { - Debug.output("DTL.edit: dt.select returns false, avoiding modification over " - + omg.getClass().getName()); - } - } - } - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String serializedFile) { - this.fileName = serializedFile; - } - - public DbfTableModelFactory getDbfFactory() { - return dbfFactory; - } - - public void setDbfFactory(DbfTableModelFactory dbfFactory) { - this.dbfFactory = dbfFactory; - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - public void setDrawingAttributes(DrawingAttributes drawingAttributes) { - this.drawingAttributes = drawingAttributes; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/GraticuleLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/GraticuleLayer.java deleted file mode 100644 index 9443bba64..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/GraticuleLayer.java +++ /dev/null @@ -1,1204 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/GraticuleLayer.java,v $ -// $RCSfile: GraticuleLayer.java,v $ -// $Revision: 1.17 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -// Modified 28 September 2002 by David N. Allsopp to allow font size -// to be changed. See sections commented with 'DNA'. - -// Modified 20 February 2010 by Steve C. Tang to allow graticule lines equally -// bisect from projection center to avoid swapping. Also fixed possible dead-loop when -// calculating label locations. -// - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.GridLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.Properties; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * Layer that draws graticule lines. If the showRuler property is set to true, - * then longitude values are displayed on the bottom of the map, and latitude - * values are displayed on the left side. If the show1And5Lines property is - * true, then 5 degree lines are drawn when there are <= threshold ten degree - * latitude or longitude lines, and 1 degree lines are drawn when there are - * <= threshold five degree latitude or longitude degree lines. - * - *

- * The openmap.properties file can control the layer with the following - * settings: - *

- *   
- *    # Show lat / lon spacing labels
- *    graticule.showRuler=true
- *    graticule.show1And5Lines=true
- *    # Controls when the five degree lines and one degree lines kick in
- *    #- when there is less than the threshold of ten degree lat or lon
- *    #lines, five degree lines are drawn. The same relationship is there
- *    #for one to five degree lines.
- *    graticule.threshold=2
- *    # the color of 10 degree spacing lines (Hex ARGB)
- *    graticule.10DegreeColor=FF000000
- *    # the color of 5 degree spacing lines (Hex ARGB)
- *    graticule.5DegreeColor=C7009900
- *    # the color of 1 degree spacing lines (Hex ARGB)
- *    graticule.1DegreeColor=C7003300
- *    # the color of the equator (Hex ARGB)
- *    graticule.equatorColor=FFFF0000
- *    # the color of the international dateline (Hex ARGB)
- *    graticule.datelineColor=7F000099
- *    # the color of the special lines (Hex ARGB)
- *    graticule.specialLineColor=FF000000
- *    # the color of the labels (Hex ARGB)
- *    graticule.textColor=FF000000
- *   
- * 
- *

In addition, you can get this layer to work with the OpenMap - * viewer by editing your openmap.properties file: - *

- *   
- *    # layers
- *    openmap.layers=graticule ...
- *    # class
- *    graticule.class=com.bbn.openmap.layer.GraticuleLayer
- *    # name
- *    graticule.prettyName=Graticule
- *   
- * 
- */ -public class GraticuleLayer - extends OMGraphicHandlerLayer - implements ActionListener { - - // default to not showing the ruler (mimicking older - // GraticuleLayer) - protected boolean defaultShowRuler = true; - protected boolean defaultShowOneAndFiveLines = true; - protected boolean defaultShowBelowOneLines = false; - protected int defaultThreshold = 2; - - /** - * Flag for lineType - true is LINETYPE_STRAIGHT, false is - * LINETYPE_GREATCIRCLE. - */ - protected boolean boxy = true; - /** - * Threshold is the total number of ten lines on the screen before the five - * lines appear, and the total number of five lines on the screen before the - * one lines appear. - */ - protected int threshold = defaultThreshold; - /** The ten degree latitude and longitude lines, premade. */ - protected OMGraphicList tenDegreeLines = null; - /** The equator, dateline and meridian lines, premade. */ - protected OMGraphicList markerLines = null; - - private final static int SHOW_TENS = 0; - private final static int SHOW_FIVES = 1; - private final static int SHOW_ONES = 2; - - protected boolean showOneAndFiveLines = defaultShowOneAndFiveLines; - protected boolean showBelowOneLines = defaultShowBelowOneLines; - protected boolean showRuler = defaultShowRuler; - - // protected Font font = new Font("Helvetica", - // java.awt.Font.PLAIN, 10); - protected Font font = null; - protected int fontSize = 10; - - // Color variables for different line types - protected Color tenDegreeColor = null; - protected Color fiveDegreeColor = null; - protected Color oneDegreeColor = null; - protected Color belowOneDegreeColor = null; - protected Color equatorColor = null; - protected Color dateLineColor = null; - protected Color specialLineColor = null; // Tropic of Cancer, - // Capricorn - protected Color textColor = null; - - // Default colors to use, if not specified in the properties. - protected String defaultTenDegreeColorString = "000000"; - protected String defaultFiveDegreeColorString = "33009900"; - protected String defaultOneDegreeColorString = "33003300"; - protected String defaultBelowOneDegreeColorString = "9900ff00"; - protected String defaultEquatorColorString = "990000"; - protected String defaultDateLineColorString = "000099"; - protected String defaultSpecialLineColorString = "000000"; - protected String defaultTextColorString = "000000"; - - // property text values - public static final String TenDegreeColorProperty = "10DegreeColor"; - public static final String FiveDegreeColorProperty = "5DegreeColor"; - public static final String OneDegreeColorProperty = "1DegreeColor"; - public static final String BelowOneDegreeColorProperty = "Below1DegreeColor"; - public static final String EquatorColorProperty = "equatorColor"; - public static final String DateLineColorProperty = "datelineColor"; - public static final String SpecialLineColorProperty = "specialLineColor"; - public static final String TextColorProperty = "textColor"; - public static final String ThresholdProperty = "threshold"; - public static final String ShowRulerProperty = "showRuler"; - public static final String ShowOneAndFiveProperty = "show1And5Lines"; - public static final String ShowBelowOneProperty = "showBelow1Lines"; - public static final String FontSizeProperty = "fontSize"; // DNA - - /** - * Construct the GraticuleLayer. - */ - public GraticuleLayer() { - // precalculate for boxy - boxy = true; - setName("Graticule"); - setRenderPolicy(new BufferedImageRenderPolicy(this)); - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the GraticuleLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - tenDegreeColor = - PropUtils.parseColorFromProperties(properties, prefix + TenDegreeColorProperty, defaultTenDegreeColorString, true); - - fiveDegreeColor = - PropUtils.parseColorFromProperties(properties, prefix + FiveDegreeColorProperty, defaultFiveDegreeColorString, true); - - oneDegreeColor = - PropUtils.parseColorFromProperties(properties, prefix + OneDegreeColorProperty, defaultOneDegreeColorString, true); - - belowOneDegreeColor = - PropUtils.parseColorFromProperties(properties, prefix + BelowOneDegreeColorProperty, defaultBelowOneDegreeColorString, - true); - - equatorColor = PropUtils.parseColorFromProperties(properties, prefix + EquatorColorProperty, defaultEquatorColorString, true); - - dateLineColor = - PropUtils.parseColorFromProperties(properties, prefix + DateLineColorProperty, defaultDateLineColorString, true); - - specialLineColor = - PropUtils.parseColorFromProperties(properties, prefix + SpecialLineColorProperty, defaultSpecialLineColorString, true); - - textColor = PropUtils.parseColorFromProperties(properties, prefix + TextColorProperty, defaultTextColorString, true); - - threshold = PropUtils.intFromProperties(properties, prefix + ThresholdProperty, defaultThreshold); - - fontSize = PropUtils.intFromProperties(properties, prefix + FontSizeProperty, fontSize); - - font = new Font("Helvetica", java.awt.Font.PLAIN, fontSize); - - setShowOneAndFiveLines(PropUtils.booleanFromProperties(properties, prefix + ShowOneAndFiveProperty, - defaultShowOneAndFiveLines)); - - setShowBelowOneLines(PropUtils.booleanFromProperties(properties, prefix + ShowBelowOneProperty, defaultShowBelowOneLines)); - - setShowRuler(PropUtils.booleanFromProperties(properties, prefix + ShowRulerProperty, defaultShowRuler)); - - // So they will get re-created. - tenDegreeLines = null; - markerLines = null; - } - - protected JCheckBox showRulerButton = null; - protected JCheckBox show15Button = null; - protected JCheckBox showBelow1Button = null; - - public void setShowOneAndFiveLines(boolean set) { - showOneAndFiveLines = set; - if (show15Button != null) { - show15Button.setSelected(set); - } - } - - public void setShowBelowOneLines(boolean set) { - showBelowOneLines = set; - if (showBelow1Button != null) { - showBelow1Button.setSelected(set); - } - } - - public boolean getShowOneAndFiveLines() { - return showOneAndFiveLines; - } - - public boolean getShowBelowOneLines() { - return showBelowOneLines; - } - - public void setShowRuler(boolean set) { - showRuler = set; - if (showRulerButton != null) { - showRulerButton.setSelected(set); - } - } - - public boolean getShowRuler() { - return showRuler; - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the GraticuleLayer. - * - * @param properties the properties set in the properties file. - */ - public Properties getProperties(Properties properties) { - properties = super.getProperties(properties); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - String colorString; - - if (tenDegreeColor == null) { - colorString = defaultTenDegreeColorString; - } else { - colorString = Integer.toHexString(tenDegreeColor.getRGB()); - } - properties.put(prefix + TenDegreeColorProperty, colorString); - - if (fiveDegreeColor == null) { - colorString = defaultFiveDegreeColorString; - } else { - colorString = Integer.toHexString(fiveDegreeColor.getRGB()); - } - properties.put(prefix + FiveDegreeColorProperty, colorString); - - if (oneDegreeColor == null) { - colorString = defaultOneDegreeColorString; - } else { - colorString = Integer.toHexString(oneDegreeColor.getRGB()); - } - properties.put(prefix + OneDegreeColorProperty, colorString); - - if (belowOneDegreeColor == null) { - colorString = defaultBelowOneDegreeColorString; - } else { - colorString = Integer.toHexString(belowOneDegreeColor.getRGB()); - } - properties.put(prefix + BelowOneDegreeColorProperty, colorString); - - if (equatorColor == null) { - colorString = defaultEquatorColorString; - } else { - colorString = Integer.toHexString(equatorColor.getRGB()); - } - properties.put(prefix + EquatorColorProperty, colorString); - - if (dateLineColor == null) { - colorString = defaultDateLineColorString; - } else { - colorString = Integer.toHexString(dateLineColor.getRGB()); - } - properties.put(prefix + DateLineColorProperty, colorString); - - if (specialLineColor == null) { - colorString = defaultSpecialLineColorString; - } else { - colorString = Integer.toHexString(specialLineColor.getRGB()); - } - properties.put(prefix + SpecialLineColorProperty, colorString); - - if (textColor == null) { - colorString = defaultTextColorString; - } else { - colorString = Integer.toHexString(textColor.getRGB()); - } - properties.put(prefix + TextColorProperty, colorString); - - properties.put(prefix + ThresholdProperty, Integer.toString(threshold)); - properties.put(prefix + FontSizeProperty, Integer.toString(fontSize)); // DNA - - properties.put(prefix + ShowOneAndFiveProperty, new Boolean(showOneAndFiveLines).toString()); - - properties.put(prefix + ShowBelowOneProperty, new Boolean(showBelowOneLines).toString()); - - properties.put(prefix + ShowRulerProperty, new Boolean(showRuler).toString()); - - return properties; - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the GraticuleLayer. - * - * @param properties the properties set in the properties file. - */ - public Properties getPropertyInfo(Properties properties) { - properties = super.getPropertyInfo(properties); - String interString; - properties.put(initPropertiesProperty, TenDegreeColorProperty + " " + FiveDegreeColorProperty + " " + OneDegreeColorProperty - + " " + /* BelowOneDegreeColorProperty + " " + */EquatorColorProperty + " " + DateLineColorProperty + " " - + SpecialLineColorProperty + " " + ShowOneAndFiveProperty /* - * + " " + - * ShowBelowOneProperty - */ - + " " + ShowRulerProperty + " " + ThresholdProperty + " " + FontSizeProperty); - - interString = - i18n.get(GraticuleLayer.class, TenDegreeColorProperty, I18n.TOOLTIP, "Color of the ten degree graticule lines."); - properties.put(TenDegreeColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, TenDegreeColorProperty, "Ten Degree Color"); - properties.put(TenDegreeColorProperty + LabelEditorProperty, interString); - properties.put(TenDegreeColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = - i18n.get(GraticuleLayer.class, FiveDegreeColorProperty, I18n.TOOLTIP, "Color of the five degree graticule lines."); - properties.put(FiveDegreeColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, FiveDegreeColorProperty, "Color of the five degree graticule lines."); - interString = i18n.get(GraticuleLayer.class, FiveDegreeColorProperty, "File Degree Color"); - properties.put(FiveDegreeColorProperty + LabelEditorProperty, interString); - properties.put(FiveDegreeColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = - i18n.get(GraticuleLayer.class, OneDegreeColorProperty, I18n.TOOLTIP, "Color of the one degree graticule lines."); - properties.put(OneDegreeColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, OneDegreeColorProperty, "1 Degree Color"); - properties.put(OneDegreeColorProperty + LabelEditorProperty, interString); - properties.put(OneDegreeColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = - i18n.get(GraticuleLayer.class, BelowOneDegreeColorProperty, I18n.TOOLTIP, - "Color of the sub-one degree graticule lines."); - properties.put(BelowOneDegreeColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, BelowOneDegreeColorProperty, "Sub-One Degree Color"); - properties.put(BelowOneDegreeColorProperty + LabelEditorProperty, interString); - properties.put(BelowOneDegreeColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(GraticuleLayer.class, EquatorColorProperty, I18n.TOOLTIP, "Color of the Equator."); - properties.put(EquatorColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, EquatorColorProperty, "Equator Line Color"); - properties.put(EquatorColorProperty + LabelEditorProperty, interString); - properties.put(EquatorColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(GraticuleLayer.class, DateLineColorProperty, I18n.TOOLTIP, "Color of the Date line."); - properties.put(DateLineColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, DateLineColorProperty, "Date Line Color"); - properties.put(DateLineColorProperty + LabelEditorProperty, interString); - properties.put(DateLineColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = - i18n.get(GraticuleLayer.class, SpecialLineColorProperty, I18n.TOOLTIP, "Color of Tropic of Cancer, Capricorn lines."); - properties.put(SpecialLineColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, SpecialLineColorProperty, "Special Line Color"); - properties.put(SpecialLineColorProperty + LabelEditorProperty, interString); - properties.put(SpecialLineColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(GraticuleLayer.class, TextColorProperty, I18n.TOOLTIP, "Color of the line label text."); - properties.put(TextColorProperty, interString); - interString = i18n.get(GraticuleLayer.class, TextColorProperty, "Text Color"); - properties.put(TextColorProperty + LabelEditorProperty, interString); - properties.put(TextColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = - i18n.get(GraticuleLayer.class, ThresholdProperty, I18n.TOOLTIP, - "The number of lines showing before finer grain lines appear."); - properties.put(ThresholdProperty, interString); - interString = i18n.get(GraticuleLayer.class, ThresholdProperty, "Line Threshold"); - properties.put(ThresholdProperty + LabelEditorProperty, interString); - - interString = i18n.get(GraticuleLayer.class, ShowOneAndFiveProperty, I18n.TOOLTIP, "Show the one and five degree lines."); - properties.put(ShowOneAndFiveProperty, interString); - interString = i18n.get(GraticuleLayer.class, ShowOneAndFiveProperty, "Show 1 and 5 Lines"); - properties.put(ShowOneAndFiveProperty + LabelEditorProperty, interString); - properties.put(ShowOneAndFiveProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - - interString = i18n.get(GraticuleLayer.class, ShowBelowOneProperty, I18n.TOOLTIP, "Show the one and five degree lines."); - properties.put(ShowBelowOneProperty, interString); - interString = i18n.get(GraticuleLayer.class, ShowBelowOneProperty, "Show Sub-1 Lines"); - properties.put(ShowBelowOneProperty + LabelEditorProperty, interString); - properties.put(ShowBelowOneProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - - interString = i18n.get(GraticuleLayer.class, ShowRulerProperty, I18n.TOOLTIP, "Show the line label text."); - properties.put(ShowRulerProperty, interString); - interString = i18n.get(GraticuleLayer.class, ShowRulerProperty, "Show Labels"); - properties.put(ShowRulerProperty + LabelEditorProperty, interString); - properties.put(ShowRulerProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - - // DNA - interString = - i18n.get(GraticuleLayer.class, FontSizeProperty, I18n.TOOLTIP, "The size of the font, in points, of the line labels."); - properties.put(FontSizeProperty, interString); - interString = i18n.get(GraticuleLayer.class, FontSizeProperty, "Label Font Size"); - properties.put(FontSizeProperty + LabelEditorProperty, interString); - // DNA - return properties; - } - - /** - * Implementing the ProjectionPainter interface. - */ - public synchronized void renderDataForProjection(Projection proj, java.awt.Graphics g) { - if (proj == null) { - Debug.error("GraticuleLayer.renderDataForProjection: null projection!"); - return; - } else if (!proj.equals(getProjection())) { - setProjection(proj.makeClone()); - // Figure out which line type to use - if (proj instanceof Cylindrical) - boxy = true; - else - boxy = false; - - setList(constructGraticuleLines()); - } - paint(g); - } - - /** - * Invoked when the projection has changed or this Layer has been added to - * the MapBean. - *

- * Perform some extra checks to see if reprojection of the graphics is really - * necessary. - * - * @param e ProjectionEvent - * - */ - public void projectionChanged(ProjectionEvent e) { - - // extract the projection and check to see if it's really - // different. - // if it isn't then we don't need to do all the work again, - // just - // repaint. - Projection proj = setProjection(e); - if (proj == null) { - repaint(); - return; - } - - // Figure out which line type to use - if (proj instanceof Cylindrical) - boxy = true; - else - boxy = false; - - setList(null); - doPrepare(); - } - - /** - * Creates the OMGraphic list with graticule lines. - */ - public synchronized OMGraphicList prepare() { - return constructGraticuleLines(); - } - - /** - * Create the graticule lines. - *

- * NOTES: - *

    - *
  • Currently graticule lines are hardcoded to 10 degree intervals. - *
  • No thought has been given to clipping based on the view rectangle. For - * non-boxy projections performance may be degraded at very large scales. - * (But we make up for this by running the task in its own thread to support - * liveness). - *
- * - * @return OMGraphicList new graphic list - */ - protected OMGraphicList constructGraticuleLines() { - - OMGraphicList newgraphics = new OMGraphicList(20); - // Lets figure out which lines should be painted... - Projection projection = getProjection(); - - if (projection == null) { - return newgraphics; - } - tenDegreeLines = null; - // Need the cast to make Windows happy during the ant build for jdk1.5.0_22 - double ctrLon = ((Point2D)projection.getCenter()).getX(); - if (projection instanceof GeoProj) { - ctrLon = ((GeoProj) projection).getReferenceLon(); - } - - if (showOneAndFiveLines || showRuler || showBelowOneLines) { - - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - - float left = (float) ul.getX(); - float right = (float) lr.getX(); - float up = (float) ul.getY(); - float down = (float) lr.getY(); - - if (up > 80.0f) - up = 80.0f; - if (down > 80.0f) - down = 80f; // unlikely - if (up < -80.0f) - up = -80.0f; // unlikely - if (down < -80) - down = -80.0f; - - int showWhichLines = evaluateSpacing(up, down, left, right); - - // Find out whether we need to do one or two queries, - // depending on if we're straddling the dateline. - if ((left > 0 && right < 0) || (left > right) || (Math.abs(left - right) < 1)) { - // Test to draw the ones and fives, which will also do - // the labels. - - if (showWhichLines != SHOW_TENS) { - newgraphics.add(constructGraticuleLines(up, down, left, 180.0f, showWhichLines)); - newgraphics.add(constructGraticuleLines(up, down, -180.0f, right, showWhichLines)); - } else if (showRuler) { // Just do the labels for the - // tens lines - newgraphics.add(constructTensLabels(up, down, left, 180.0f, true)); - newgraphics.add(constructTensLabels(up, down, -180.0f, right, false)); - } - } else { - // Test to draw the ones and fives, which will also do - // the labels. - if (showWhichLines != SHOW_TENS) { - newgraphics = constructGraticuleLines(up, down, left, right, showWhichLines); - } else if (showRuler) { // Just do the labels for the - // tens lines - newgraphics.add(constructTensLabels(up, down, left, right, true)); - } - } - } - - OMGraphicList list; - if (tenDegreeLines == null) { - list = constructTenDegreeLines(ctrLon); - tenDegreeLines = list; - } else { - synchronized (tenDegreeLines) { - setLineTypeAndProject(tenDegreeLines, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_RHUMB); - } - } - if (markerLines == null) { - list = constructMarkerLines(ctrLon); - markerLines = list; - } else { - synchronized (markerLines) { - setLineTypeAndProject(markerLines, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_RHUMB); - } - } - - newgraphics.add(markerLines); - newgraphics.add(tenDegreeLines); - - if (Debug.debugging("graticule")) { - Debug.output("GraticuleLayer.constructGraticuleLines(): " + "constructed " + newgraphics.size() + " graticule lines"); - } - - return newgraphics; - } - - /** - * Figure out which graticule lines should be drawn based on the treshold set - * in the layer, and the coordinates of the screen. Method checks for - * crossing of the dateline, but still assumes that the up and down latitude - * coordinates are less than abs(+/-80). This is because the projection - * shouldn't give anything above 90 degrees, and we limit the lines to less - * than 80.. - * - * @param up northern latitude coordinate, in decimal degrees, - * @param down southern latitude coordinate, in decimal degrees. - * @param left western longitude coordinate, in decimal degrees, - * @param right eastern longitude coordinate, in decimal degrees. - * @return which lines should be shown, either SHOW_TENS, SHOW_FIVES and - * SHOW_ONES. - */ - protected int evaluateSpacing(float up, float down, float left, float right) { - int ret = SHOW_TENS; - - // Set the flag for when labels are wanted, but not the 1 and - // 5 lines; - if (!showOneAndFiveLines && !showBelowOneLines) { - return ret; - } - - // Find the north - south difference - float nsdiff = up - down; - // And the east - west difference - float ewdiff; - // Check for straddling the dateline -west is positive while - // right is negative, or, in a big picture view, the west is - // positive, east is positive, and western hemisphere is - // between them. - if ((left > 0 && right < 0) || (left > right) || (Math.abs(left - right) < 1)) { - ewdiff = (180.0f - left) + (right + 180.0f); - } else { - ewdiff = right - left; - } - - // And use the lesser of the two. - float diff = (nsdiff < ewdiff) ? nsdiff : ewdiff; - // number of 10 degree lines - if ((diff / 10) <= (float) threshold) - ret = SHOW_FIVES; - // number of five degree lines - if ((diff / 5) <= (float) threshold) - ret = SHOW_ONES; - - return ret; - } - - /** - * Construct the five degree and one degree graticule lines, depending on the - * showWhichLines setting. Assumes that the coordinates passed in do not - * cross the dateline, and that the up is not greater than 80 and that the - * south is not less than -80. - * - * @param up northern latitude coordinate, in decimal degrees, - * @param down southern latitude coordinate, in decimal degrees. - * @param left western longitude coordinate, in decimal degrees, - * @param right eastern longitude coordinate, in decimal degrees. - * @param showWhichLines indicator for which level of lines should be - * included, either SHOW_FIVES or SHOW_ONES. SHOW_TENS could be there, - * too, but then we wouldn't do anything. - */ - protected OMGraphicList constructGraticuleLines(float up, float down, float left, float right, int showWhichLines) { - OMGraphicList lines = new OMGraphicList(); - - // Set the line limits for the lat/lon lines... - int north = (int) Math.ceil(up); - if (north > 80) - north = 80; - - int south = (int) Math.floor(down); - south -= (south % 10); // Push down to the lowest 10 degree - // line. - // for neg numbers, Mod raised it, lower it again. Also - // handle straddling the equator. - if ((south < 0 && south > -80) || south == 0) - south -= 10; - - int west = (int) Math.floor(left); - west -= (west % 10); - // for neg numbers, Mod raised it, lower it again. Also - // handle straddling the prime meridian. - if ((west < 0 && west > -180) || west == 0) - west -= 10; - - int east = (int) Math.ceil(right); - if (east > 180) - east = 180; - - int stepSize; - int stepSum; - double point_x, point_y; - // Choose how far apart the lines will be. - stepSize = ((showWhichLines == SHOW_ONES) ? 1 : 5); - double[] llp; - OMPoly currentLine; - OMText currentText; - - // For calculating text locations - Point point = new Point(); - LatLonPoint llpoint; - - Projection projection = getProjection(); - - // generate other parallels of latitude be creating series - // of polylines - for (int i = south; i < north; i += stepSize) { - float lat = (float) i; - // generate parallel of latitude North/South of the - // equator - if (west < 0 && east > 0) { - llp = new double[6]; - llp[2] = lat; - llp[3] = 0f; - llp[4] = lat; - llp[5] = east; - } else { - llp = new double[4]; - llp[2] = lat; - llp[3] = east; - } - llp[0] = lat; - llp[1] = west; - - // Do not duplicate the 10 degree line. - if ((lat % 10) != 0) { - currentLine = new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_RHUMB); - if ((lat % 5) == 0) { - currentLine.setLinePaint(fiveDegreeColor); - } else { - currentLine.setLinePaint(oneDegreeColor); - } - lines.add(currentLine); - } - - if (showRuler && (lat % 2) == 0) { - if (boxy) { - projection.forward(lat, west, point); - point.x = 0; - llpoint = projection.inverse(point.x, point.y, new LatLonPoint.Double()); - } else { - llpoint = new LatLonPoint.Double(lat, west); - stepSum = 0; - while (stepSum < 360) { - point_x = projection.forward(llpoint).getX(); - if (point_x > 0 && point_x < projection.getWidth()) - break; - stepSum += stepSize; - llpoint.setLongitude(llpoint.getX() + stepSize); - } - } - - currentText = new OMText(llpoint.getY(), llpoint.getX(), - // Move them up a little - (int) 2, (int) -2, Integer.toString((int) lat), font, OMText.JUSTIFY_LEFT); - currentText.setLinePaint(textColor); - lines.add(currentText); - } - } - - // generate lines of longitude - for (int i = west; i < east; i += stepSize) { - float lon = (float) i; - - if (north < 0 && south > 0) { - llp = new double[6]; - llp[2] = 0f; - llp[3] = lon; - llp[4] = south; - llp[5] = lon; - } else { - llp = new double[4]; - llp[2] = south; - llp[3] = lon; - } - llp[0] = north; - llp[1] = lon; - - if ((lon % 10) != 0) { - currentLine = - new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_GREATCIRCLE); - if ((lon % 5) == 0) { - currentLine.setLinePaint(fiveDegreeColor); - } else { - currentLine.setLinePaint(oneDegreeColor); - } - lines.add(currentLine); - } - - if (showRuler && (lon % 2) == 0) { - if (boxy) { - projection.forward(south, lon, point); - point.y = projection.getHeight(); - llpoint = projection.inverse(point.x, point.y, new LatLonPoint.Double()); - } else { - llpoint = new LatLonPoint.Double(south, lon); - stepSum = 0; - while (stepSum < 360) { - point_y = projection.forward(llpoint).getY(); - if (point_y > 0 && point_y < projection.getHeight()) - break; - stepSum += stepSize; - llpoint.setLatitude(llpoint.getY() + stepSize); - } - } - - currentText = new OMText(llpoint.getY(), llpoint.getX(), - // Move them up a little - (int) 2, (int) -5, Integer.toString((int) lon), font, OMText.JUSTIFY_CENTER); - currentText.setLinePaint(textColor); - lines.add(currentText); - - } - } - - if (Debug.debugging("graticule")) { - Debug.output("GraticuleLayer.constructTenDegreeLines(): " + "constructed " + lines.size() + " graticule lines"); - } - lines.generate(projection); - return lines; - } - - /** Create the ten degree lines. */ - protected OMGraphicList constructTenDegreeLines(double ctrLon) { - - OMGraphicList lines = new OMGraphicList(3); - OMPoly currentLine; - - // generate other parallels of latitude by creating series - // of polylines - for (int i = 1; i <= 8; i++) { - for (int j = -1; j < 2; j += 2) { - float lat = (float) (10 * i * j); - // generate parallel of latitude North/South of the - // equator - double[] llp = { - lat, - ctrLon - 180f, - lat, - ctrLon - 90f, - lat, - ctrLon, - lat, - ctrLon + 90f, - lat, - ctrLon + 180f - }; - currentLine = new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_RHUMB); - currentLine.setLinePaint(tenDegreeColor); - lines.add(currentLine); - } - } - - // generate lines of longitude - for (int i = 1; i < 18; i++) { - for (int j = -1; j < 2; j += 2) { - float lon = (float) (10 * i * j); - // not quite 90.0 for beautification reasons. - double[] llp = { - 80f, - lon, - 0f, - lon, - -80f, - lon - }; - if (MoreMath.approximately_equal(Math.abs(lon), 90f, 0.001f)) { - llp[0] = 89.999f; - llp[4] = -89.999f; - } - currentLine = - new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_GREATCIRCLE); - currentLine.setLinePaint(tenDegreeColor); - lines.add(currentLine); - } - } - - if (Debug.debugging("graticule")) { - Debug.output("GraticuleLayer.constructTenDegreeLines(): " + "constructed " + lines.size() + " graticule lines"); - } - lines.generate(getProjection()); - return lines; - } - - /** - * Constructs the labels for the tens lines. Called from within the - * constructGraticuleLines if the showRuler variable is true. Usually called - * only if the ones and fives lines are not being drawn. - * - * @param up northern latitude coordinate, in decimal degrees, - * @param down southern latitude coordinate, in decimal degrees. - * @param left western longitude coordinate, in decimal degrees, - * @param right eastern longitude coordinate, in decimal degrees. - * @param doLats do the latitude labels if true. - * @return OMGraphicList of labels. - */ - protected OMGraphicList constructTensLabels(float up, float down, float left, float right, boolean doLats) { - - OMGraphicList labels = new OMGraphicList(); - - // Set the line limits for the lat/lon lines... - int north = (int) Math.ceil(up); - if (north > 80) - north = 80; - - int south = (int) Math.floor(down); - south -= (south % 10); // Push down to the lowest 10 degree - // line. - // for neg numbers, Mod raised it, lower it again - if ((south < 0 && south > -70) || south == 0) { - south -= 10; - } - - int west = (int) Math.floor(left); - west -= (west % 10); - // for neg numbers, Mod raised it, lower it again - if ((west < 0 && west > -170) || west == 0) { - west -= 10; - } - - int east = (int) Math.ceil(right); - if (east > 180) - east = 180; - - int stepSize = 10; - int stepSum; - double point_x, point_y; - OMText currentText; - - // For calculating text locations - Point point = new Point(); - LatLonPoint llpoint; - Projection projection = getProjection(); - - if (doLats) { - - // generate other parallels of latitude be creating series - // of labels - for (int i = south; i < north; i += stepSize) { - float lat = (float) i; - - if ((lat % 2) == 0) { - if (boxy) { - projection.forward(lat, west, point); - point.x = 0; - llpoint = projection.inverse(point.x, point.y, new LatLonPoint.Double()); - } else { - llpoint = new LatLonPoint.Double(lat, west); - stepSum = 0; - while (stepSum < 360) { - point_x = projection.forward(llpoint).getX(); - if (point_x > 0 && point_x < projection.getWidth()) - break; - stepSum += stepSize; - llpoint.setLongitude(llpoint.getX() + stepSize); - } - } - - currentText = new OMText(llpoint.getY(), llpoint.getX(), (int) 2, (int) -2, // Move - // them - // up a - // little - Integer.toString((int) lat), font, OMText.JUSTIFY_LEFT); - currentText.setLinePaint(textColor); - labels.add(currentText); - } - } - } - - // generate labels of longitude - for (int i = west; i < east; i += stepSize) { - float lon = (float) i; - - if ((lon % 2) == 0) { - if (boxy) { - projection.forward(south, lon, point); - point.y = projection.getHeight(); - llpoint = projection.inverse(point.x, point.y, new LatLonPoint.Double()); - } else { - llpoint = new LatLonPoint.Double(south, lon); - stepSum = 0; - while (stepSum < 360) { - point_y = projection.forward(llpoint).getY(); - if (point_y > 0 && point_y < projection.getHeight()) - break; - stepSum += stepSize; - llpoint.setLatitude(llpoint.getY() + stepSize); - } - } - - currentText = new OMText(llpoint.getY(), llpoint.getX(), - // Move them up a little - (int) 2, (int) -5, Integer.toString((int) lon), font, OMText.JUSTIFY_CENTER); - currentText.setLinePaint(textColor); - labels.add(currentText); - - } - } - - if (Debug.debugging("graticule")) { - Debug.output("GraticuleLayer.constructTensLabels(): " + "constructed " + labels.size() + " graticule labels"); - } - labels.generate(projection); - return labels; - } - - /** Constructs the Dateline and Prime Meridian lines. */ - protected OMGraphicList constructMarkerLines(double ctrLon) { - - OMGraphicList lines = new OMGraphicList(3); - OMPoly currentLine; - - // generate Prime Meridian and Dateline - for (int j = 0; j < 360; j += 180) { - float lon = (float) j; - double[] llp = { - 90f, - lon, - 0f, - lon, - -90f, - lon - }; - currentLine = - new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_GREATCIRCLE); - currentLine.setLinePaint(dateLineColor); - lines.add(currentLine); - } - - // equator - double[] llp = { - 0f, - ctrLon - 180f, - 0f, - ctrLon - 90f, - 0f, - ctrLon, - 0f, - ctrLon + 90f, - 0f, - ctrLon + 180f - }; - // polyline - currentLine = new OMPoly(llp, OMGraphic.DECIMAL_DEGREES, boxy ? OMGraphic.LINETYPE_STRAIGHT : OMGraphic.LINETYPE_GREATCIRCLE); - currentLine.setLinePaint(equatorColor); - lines.add(currentLine); - - if (Debug.debugging("graticule")) { - Debug.output("GraticuleLayer.constructMarkerLines(): " + "constructed " + lines.size() + " graticule lines"); - } - lines.generate(getProjection()); - return lines; - } - - /** - * Take a graphic list, and set all the items on the list to the line type - * specified, and project them into the current projection. - * - * @param list the list containing the lines to change. - * @param lineType the line type to change the lines to. - */ - protected void setLineTypeAndProject(OMGraphicList list, int lineType) { - int size = list.size(); - OMGraphic graphic; - for (int i = 0; i < size; i++) { - graphic = list.getOMGraphicAt(i); - graphic.setLineType(lineType); - graphic.generate(getProjection()); - } - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - /** The user interface palette for the Graticule layer. */ - protected Box paletteBox = null; - - /** Creates the interface palette. */ - public java.awt.Component getGUI() { - - if (paletteBox == null) { - if (Debug.debugging("graticule")) - Debug.output("GraticuleLayer: creating Graticule Palette."); - - paletteBox = Box.createVerticalBox(); - - JPanel layerPanel = - PaletteHelper.createPaletteJPanel(i18n.get(GraticuleLayer.class, "layerPanel", "Graticule Layer Options")); - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - - if (ac.equalsIgnoreCase(ShowRulerProperty)) { - JCheckBox jcb = (JCheckBox) e.getSource(); - showRuler = jcb.isSelected(); - } else if (ac.equalsIgnoreCase(ShowOneAndFiveProperty)) { - JCheckBox jcb = (JCheckBox) e.getSource(); - showOneAndFiveLines = jcb.isSelected(); - } else { - Debug.error("Unknown action command \"" + ac + "\" in GraticuleLayer.actionPerformed()."); - } - } - }; - - showRulerButton = new JCheckBox(i18n.get(GraticuleLayer.class, "showRulerButton", "Show Lat/Lon Labels"), showRuler); - showRulerButton.addActionListener(al); - showRulerButton.setActionCommand(ShowRulerProperty); - - show15Button = - new JCheckBox(i18n.get(GraticuleLayer.class, "show15Button", "Show 1, 5 Degree Lines"), showOneAndFiveLines); - show15Button.addActionListener(al); - show15Button.setActionCommand(ShowOneAndFiveProperty); - - // showBelow1Button = new JCheckBox(i18n.get(GraticuleLayer.class, - // "showSub1Button", - // "Show Sub-1 Degree Lines"), showBelowOneLines); - // showBelow1Button.addActionListener(al); - // showBelow1Button.setActionCommand(ShowBelowOneProperty); - - layerPanel.add(showRulerButton); - layerPanel.add(show15Button); - // layerPanel.add(showBelow1Button); - paletteBox.add(layerPanel); - - JPanel subbox3 = new JPanel(new GridLayout(0, 1)); - - JButton setProperties = new JButton(i18n.get(GraticuleLayer.class, "setProperties", "Preferences")); - setProperties.setActionCommand(DisplayPropertiesCmd); - setProperties.addActionListener(this); - subbox3.add(setProperties); - - JButton redraw = new JButton(i18n.get(GraticuleLayer.class, "redraw", "Redraw Graticule Layer")); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - subbox3.add(redraw); - paletteBox.add(subbox3); - } - return paletteBox; - } - - // ---------------------------------------------------------------------- - - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * Used just for the redraw button. - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String command = e.getActionCommand(); - - if (command == RedrawCmd) { - // redrawbutton - if (isVisible()) { - doPrepare(); - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/LabelLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/LabelLayer.java deleted file mode 100644 index 1c42c7bb3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/LabelLayer.java +++ /dev/null @@ -1,405 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/LabelLayer.java,v $ -// $RCSfile: LabelLayer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.util.Properties; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.Taskable; - -/** - * Layer that displays a label. This Layer is a Taskable (ActionListener) object - * so that it can be prompted by a javax.swing.Timer object. This layer - * understands the following properties: - *

- * - *

- * 
- *   # display font as a Java font string
- *   label.font=SansSerif-Bold
- *   # like XWindows geometry: [+-]X[+-]Y, `+' indicates relative to
- *   # left edge or top edges, `-' indicates relative to right or bottom
- *   # edges, XX is x coordinate, YY is y coordinate
- *   label.geometry=+20-30
- *   # background rectangle color (ARGB)
- *   label.color.bg=ffb3b3b3
- *   # foreground text color (ARGB)
- *   label.color.fg=ff000000
- *   # date format (using java.text.SimpleDateFormat patterns)
- *   label.text=The Graph
- * 
- * 
- *

- * In addition to the previous properties, you can get this layer to work with - * the OpenMap viewer by adding/editing the additional properties in your - * openmap.properties file: - *

- * - *

- * 
- *   # layers
- *   openmap.layers=label ...
- *   # class
- *   label.class=com.bbn.openmap.layer.LabelLayer
- *   # name
- *   label.prettyName=Label Layer
- * 
- * 
- *

- * NOTE: the color properties do not support alpha value if running on JDK - * 1.1... - */ -public class LabelLayer extends OMGraphicHandlerLayer implements Taskable, MapMouseListener { - - // property keys - public final static transient String fontProperty = "font"; - public final static transient String fgColorProperty = "color.fg"; - public final static transient String bgColorProperty = "color.bg"; - public final static transient String geometryProperty = "geometry"; - public final static transient String labelProperty = "text"; - - // properties - protected String fontString = "SansSerif"; - protected Font font = Font.decode(fontString); - protected int fgColorValue = 0x000000;// black - protected Color fgColor = new Color(fgColorValue); - protected int bgColorValue = 0xffffff;// white - protected Color bgColor = new Color(bgColorValue); - protected String geometryString = "+20+20"; - protected String labelText = ""; - - protected OMText text; - - protected int xpos = 10; - protected int ypos = 10; - protected String xgrav = geometryString.substring(0, 1); - protected String ygrav = geometryString.substring(3, 4); - - private int dragX; - private int dragY; - private boolean dragging = false; - - /** - * Construct the LabelLayer. - */ - public LabelLayer() { - text = new OMText(0, 0, "uninitialized", font, OMText.JUSTIFY_RIGHT); - text.setLinePaint(fgColor); - text.setFillPaint(bgColor); - } - - /** - * Sets the properties for the Layer. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = com.bbn.openmap.util.PropUtils.getScopedPropertyPrefix(prefix); - - fontString = props.getProperty(prefix + fontProperty, fontString); - - fgColor = ColorFactory.parseColorFromProperties(props, prefix + fgColorProperty, - Integer.toString(fgColorValue)); - - bgColor = ColorFactory.parseColorFromProperties(props, prefix + bgColorProperty, - Integer.toString(bgColorValue)); - - geometryString = props.getProperty(prefix + geometryProperty, geometryString); - parseGeometryString(); - - labelText = props.getProperty(prefix + labelProperty, labelText); - - // reset the property values - font = Font.decode(fontString); - text.setFont(font); - text.setLinePaint(fgColor); - text.setFillPaint(bgColor); - } - - /** Parse X-like geometry string. */ - protected void parseGeometryString() { - int i = 0; - byte[] bytes = geometryString.getBytes(); - xgrav = new String(bytes, 0, 1); - for (i = 2; i < bytes.length; i++) { - if ((bytes[i] == '-') || (bytes[i] == '+')) - break; - } - if (i == bytes.length) - return; - ygrav = (bytes[i] == '-') ? "-" : "+"; - xpos = Integer.parseInt(new String(bytes, 1, i - 1)); - ++i; - ypos = Integer.parseInt(new String(bytes, i, bytes.length - i)); - } - - /** Position the text graphic */ - protected void positionText(int w, int h) { - int xoff, yoff, justify; - if (xgrav.equals("+")) { - xoff = xpos; - justify = OMText.JUSTIFY_LEFT; - } else { - xoff = w - xpos; - justify = OMText.JUSTIFY_RIGHT; - } - if (ygrav.equals("+")) { - yoff = ypos; - } else { - yoff = h - ypos; - } - text.setX(xoff); - text.setY(yoff); - text.setJustify(justify); - } - - /** - * Set the text to display - * - * @param s String - */ - public void setLabelText(String s) { - labelText = s; - } - - /** - * Get the String to display - * - * @return String - */ - public String getLabelText() { - return labelText; - } - - // Part of a small hack to get LabelLayer working in background mode. Will - // be removed when layer is updated. - private OMGraphicList hackList = new OMGraphicList(); - - // Part of a small hack to get LabelLayer working in background mode. Will - // be removed when layer is updated. - public OMGraphicList prepare() { - return hackList; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(Graphics g) { - Projection p = getProjection(); - - if (p == null) - return; - - if (Debug.debugging("labellayer")) { - System.out.println("labelLayer.paint(): " + labelText); - } - - positionText(p.getWidth(), p.getHeight()); - text.setData(labelText); - text.generate(p);// to get bounds - - // render graphics - text.render(g); - } - - // ---------------------------------------------------------------------- - // Taskable Interface - // ---------------------------------------------------------------------- - - /** - * Invoked by a javax.swing.Timer. - * - * @param e ActionEvent - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - if (Debug.debugging("labellayer")) { - System.out.println("LabelLayer.actionPerformed()"); - } - - repaint(); - } - - // ---------------------------------------------------------------------- - // MapMouseListener Interface - // ---------------------------------------------------------------------- - - /** - * Returns the MapMouseListener object that handles the mouse events. - * - * @return MapMouseListener this - */ - public MapMouseListener getMapMouseListener() { - return this; - } - - /** - * Return a list of the modes that are interesting to the MapMouseListener. - * - * @return String[] { SelectMouseMode.modeID } - */ - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - // Mouse Listener events - //////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mousePressed(MouseEvent e) { - int x = e.getX(); - int y = e.getY(); - if (text.distance(x, y) <= 0f) { - dragging = true; - dragX = x; - dragY = y; - return true; - } - return false; // did not handle the event - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - dragging = false; - return false; - } - - /** - * Invoked when the mouse has been clicked on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseClicked(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - } - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * The listener will receive these events if it - * - * @param e MouseEvent - * @return false - */ - public boolean mouseDragged(MouseEvent e) { - Projection proj = getProjection(); - int w = proj.getWidth(); - int h = proj.getHeight(); - int x = e.getX(); - int y = e.getY(); - - // limit coordinates - if (x < 0) - x = 0; - if (y < 0) - y = 0; - if (x > w) - x = w; - if (y > h) - y = h; - - // calculate deltas - int dx = x - dragX; - int dy = y - dragY; - - if (dragging) { - // reset dragging parms - dragX = x; - dragY = y; - // reset graphics positions - text.setX(text.getX() + dx); - text.setY(text.getY() + dy); - repaint(); - return true; - } - return false; - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return false - */ - public boolean mouseMoved(MouseEvent e) { - return false; - } - - /** - * Handle a mouse cursor moving without the button being pressed. Another - * layer has consumed the event. - */ - public void mouseMoved() { - } - - public int getSleepHint() { - return 1000000;// update every 1000 seconds - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/OMGraphicHandlerLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/OMGraphicHandlerLayer.java deleted file mode 100644 index 887004a37..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/OMGraphicHandlerLayer.java +++ /dev/null @@ -1,1542 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/OMGraphicHandlerLayer.java,v $ -// $RCSfile: OMGraphicHandlerLayer.java,v $ -// $Revision: 1.33 $ -// $Date: 2007/04/24 19:53:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Component; -import java.awt.Composite; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Shape; -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.policy.ProjectionChangePolicy; -import com.bbn.openmap.layer.policy.RenderPolicy; -import com.bbn.openmap.layer.policy.StandardPCPolicy; -import com.bbn.openmap.layer.policy.StandardRenderPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.FilterSupport; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.event.GestureResponsePolicy; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.tools.icon.OMIconPart; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.ISwingWorker; -import com.bbn.openmap.util.PooledSwingWorker; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMGraphicHandlerLayer is a layer that provides OMGraphicHandler support. - * With this support, the OMGraphicHandlerLayer can accept OMAction instructions - * for managing OMGraphics, and can perform display filtering as supported by - * the FilterSupport object. - *

- * - * When extending this class for a simple layer, they only method you need to - * override is the prepare() method. This is a good class to use to start - * writing your own layers. Start with overriding the prepare() method, having - * it return an OMGraphicList containing OMGraphics on the map that are - * appropriate for the current projection. - *

- * - * The OMGraphicHandlerLayer already has an OMGraphicList variable, so if you - * extend this class you don't have to manage another one. You can add your - * OMGraphics to the list provided with getList(). If you create a list of - * OMGraphics that is reused and simply re-projected when the projection - * changes, do nothing - that's what happens anyway based on the default - * ProjectionChangePolicy set for the layer (StandardPCPolicy). You can either - * create an OMGraphicList in the constructor and set it by calling - * setList(OMGraphicList), or you can test for a null OMGraphicList returned - * from getList() in prepare() and create one if it needs to be. If the list - * isn't null, make sure you still call generate on it. The advantage of waiting - * to create the list in prepare is that the processing time to create the - * OMGraphics is delayed until the layer is added to the map. If you create - * OMGraphics in the constructor, you delay the entire program (maybe startup of - * the map!) while the OMGraphics are created. - *

- * - * If you let prepare() create a new OMGraphicList based on the new projection, - * then make sure the ProjectionChangePolicy for the layer is set to a - * com.bbn.openmap.layer.policy.ResetListPCPolicy, or at least clear out the old - * graphics at some point before adding new OMGraphics to the list in that - * method. You just have to do one, not both, of those things. If you are - * managing a lot of OMGraphics and do not null out the list, you may see your - * layer appear to lag behind the projection changes. That's because another - * layer with less work to do finishes and calls repaint, and since your list is - * still set with OMGraphics ready for the old projection, it will just draw - * what it had, and then draw again when it has finished working. Nulling out - * the list will prevent your layer from drawing anything on the new projection - * until it is ready. - *

- * - * The OMGraphicHandlerLayer has support built in for launching a SwingWorker to - * do work for you in a separate thread. This behavior is controlled by the - * ProjectionChangePolicy that is set for the layer. Both the StandardPCPolicy - * and ListResetPCPolicy launch threads by calling doPrepare() on this layer. - * The StandardPCPolicy only calls this if the number of OMGraphics on its list - * is greater than some cutoff value. - *

- * - * useLayerWorker variable is true (default), then doPrepare() will be called - * when a new ProjectionEvent is received in the projectionChanged method. This - * will cause prepare() to be called in a separate thread. You can use prepare() - * to create OMGraphics, the projection will have been set in the layer and is - * available via getProjection(). You should generate() the OMGraphics in - * prepare. NOTE: You can override the projectionChanged() method to - * create/manage OMGraphics any way you want. The SwingWorker only gets launched - * if doPrepare() gets called. - *

- * - * MouseEvents are not handled by a MapMouseInterpreter, with the layer being - * the GestureResponsePolicy object dictating how events are responded to. The - * interpreter does the work of fielding MapMouseEvents, figuring out if they - * concern an OMGraphic, and asking the policy what it should do in certain - * situations, including providing tooltips, information, or opportunities to - * edit OMGraphics. The mouseModes property can be set to the MapMouseMode IDs - * that the interpreter should respond to. - *

- * - * For OMGraphicHandlerLayers, there are several properties that can be set that - * dictate important behavior: - * - *

- *
- *     layer.projectionChangePolicy=pcp
- *     layer.pcp.class=com.bbn.openmap.layer.policy.StandardPCPolicy
- * 
- *     layer.renderPolicy=srp
- *     layer.srp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy
- *     # or
- *     layer.renderPolicy=ta
- *     layer.ta.class=com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy
- *     layer.ta.renderingHints=KEY_TEXT_ANTIALIASING
- *     layer.ta.KEY_TEXT_ANTIALIASING=VALUE_TEXT_ANTIALIAS_ON
- * 
- *     layer.mouseModes=Gestures
- *     layer.consumeEvents=true
- *
- *
- * 
- */ -public class OMGraphicHandlerLayer extends Layer implements GestureResponsePolicy, OMGraphicHandler { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.OMGraphicHandlerLayer"); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * The property that can be set for the ProjectionChangePolicy. This - * property should be set with a scoping marker name used to define a policy - * class and any other properties that the policy should use. - * "projectionChangePolicy" - * - * @see com.bbn.openmap.layer.policy.ProjectionChangePolicy - * @see com.bbn.openmap.layer.policy.StandardPCPolicy - * @see com.bbn.openmap.layer.policy.ListResetPCPolicy - */ - public final static String ProjectionChangePolicyProperty = "projectionChangePolicy"; - /** - * The property that can be set for the RenderPolicy. This property should - * be set with a marker name used to define a policy class and any other - * properties that the policy should use. "renderPolicy" - * - * @see com.bbn.openmap.layer.policy.StandardRenderPolicy - * @see com.bbn.openmap.layer.policy.BufferedImageRenderPolicy - * @see com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy - */ - public final static String RenderPolicyProperty = "renderPolicy"; - - /** - * The property that can be set to tell the layer which mouse modes to - * listen to. The property should be a space-separated list of mouse mode - * IDs, which can be specified for a MapMouseMode in the properties file or, - * if none is specified, the default ID hard-coded into the MapMouseMode. - * "mouseModes" - */ - public final static String MouseModesProperty = "mouseModes"; - - /** - * The property that can be set to tell the layer to consume mouse events. - * The maim reason not to do this is in case you have OMGraphics that you - * are moving, and you need other layers to respond to let you know when you - * are over the place you think you need to be. - */ - public final static String ConsumeEventsProperty = "consumeEvents"; - - /** - * The property to tell the layer how transparent it is. 0 is totally clear, - * 1f is opaque. - */ - public final static String TransparencyProperty = "transparency"; - /** - * The property to tell the layer if the thread launched for prepare() - * method calls can be interrupted. If false, the thread will be allowed to - * complete it's work. This (false) is generally a good setting for layers - * contacting servers. The default setting is, however, true. - */ - public final static String InterruptableProperty = "interruptable"; - - /** - * Filter support that can be used to manage OMGraphics. - */ - protected FilterSupport filter = new FilterSupport(); - - /** - * The ProjectionChangePolicy object that determines how a layer reacts and - * sets up the OMGraphicList to be rendered for the layer when the - * projection changes. - */ - protected ProjectionChangePolicy projectionChangePolicy = null; - - /** - * The RenderPolicy object that determines how a layer's OMGraphicList is - * rendered in the layer.paint() method. - */ - protected RenderPolicy renderPolicy = null; - - /** - * A SwingWorker that can be used for gathering OMGraphics or doing other - * work in a different thread. - */ - protected ISwingWorker layerWorker; - /** - * A SwingWorker created if the projection changes when the primary - * layerworker is off doing work. If a bunch of project changes occur before - * the primary layerworker returns from being interrupted, setting the one - * in the queue will take care of all of them. - */ - protected boolean layerWorkerQueue = false; - - protected String[] mouseModeIDs = null; - - /** - * A flag to tell the layer to be selfish about consuming MouseEvents it - * receives. If set to true, it will consume events so that other layers - * will not receive the events. If false, lower layers will also receive - * events, which will let them react too. Intended to let other layers - * provide information about what the mouse is over when editing. - */ - protected boolean consumeEvents = false; - - /** - * Flag used to avoid the SwingWorker to be interrupted. Useful for layers - * that load an image from a server such as the WMSPlugin to avoid an ugly - * java output "Interrupted while loading image". - */ - protected boolean interruptable = true; - - /** - * Sets the interruptible flag, allowing the current swing worker thread to - * have interrupt called on it. - */ - public void setInterruptable(boolean b) { - interruptable = b; - } - - /** - * Queries for the interruptible flag. - * - * @return true if interruptible flag is set, allowing interrupt to be - * called on swing worker threads. - */ - public boolean isInterruptable() { - return interruptable; - } - - // OMGraphicHandler methods, deferred to FilterSupport... - - /** - * Sets all the OMGraphics outside of this shape to be invisible. Also - * returns another OMGraphicList containing OMGraphics that are contained - * within the Shape provided. - */ - public OMGraphicList filter(Shape withinThisShape) { - return filter.filter(withinThisShape); - } - - /** - * @see com.bbn.openmap.omGraphics.OMGraphicHandler#filter(Shape, boolean) - */ - public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary) { - return filter.filter(shapeBoundary, getInsideBoundary); - } - - /** - * To find out whether SQL queries are handled. - * - * @see com.bbn.openmap.omGraphics.OMGraphicHandler#supportsSQL() - */ - public boolean supportsSQL() { - return filter.supportsSQL(); - } - - /** - * Depending on the filter's SQL support, returns an OMGraphicList that fit - * the query. - */ - public OMGraphicList filter(String SQLQuery) { - return filter.filter(SQLQuery); - } - - /** - * Perform the OMAction on the OMGraphic, within the OMGraphicList contained - * in the layer. - */ - public boolean doAction(OMGraphic graphic, OMAction action) { - return filter.doAction(graphic, action); - } - - /** - * Get the OMGraphicList held by the layer. May be null. - */ - public OMGraphicList getList() { - return filter.getList(); - } - - /** - * Indicates if the OMGraphicHandler can have its OMGraphicList set. - */ - public boolean canSetList() { - return filter.canSetList(); - } - - /** - * Set the OMGraphicList within this OMGraphicHandler. Works if - * canSetGraphicList == true. - */ - public void setList(OMGraphicList omgl) { - filter.setList(omgl); - } - - /** - * Remove all filters, and reset all graphics to be visible. - */ - public void resetFiltering() { - filter.resetFiltering(); - } - - /** - * Don't set to null. This is here to let subclasses put a more/less capable - * FilterSupport in place. - */ - public void setFilter(FilterSupport fs) { - filter = fs; - } - - /** - * Get the FilterSupport object that is handling the OMGraphicHandler - * methods. - */ - public FilterSupport getFilter() { - return filter; - } - - /** - * From the ProjectionListener interface. The method gets called when the - * layer is part of the map, and whenever the map projection changes. Will - * trigger a repaint(). - *

- * - * The ProjectionEvent is passed to the current ProjectionChangePolicy - * object, which determines what will happen on the layer and how. By - * default, a StandardPCPolicy is notified with the projection change, and - * it will test the projection for changes and make sure prepare() is - * called. It will make the decision whether doPrepare() is called, based on - * the number of OMGraphics on the list, which may launch a swing worker - * thread to call prepare(). The StandardPCPolicy does not do anything to - * the OMGraphicList when the projection changes. - *

- * - * If you need the OMGraphicList cleared out with a new projection, you can - * substitute a ListRestPCPolicy for the StandardPCPolicy. You would want to - * do this if your OMGraphicList changes for different projections - The - * reason the OMGraphicList is nulled out is so if another layer finishes - * before yours does and gets repainted, your old OMGraphics don't get - * painted along side their new ones - it's a mismatched situation. You can - * set the ProjectionChangePolicy directly with the - * setProjectionChangePolicy, or by overriding the getProjectionChangePolicy - * method and returning the type you want by default if it is null. - * - * @see com.bbn.openmap.layer.policy.ProjectionChangePolicy - * @see com.bbn.openmap.layer.policy.StandardPCPolicy - * @see com.bbn.openmap.layer.policy.ListResetPCPolicy - */ - public void projectionChanged(ProjectionEvent pe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("OMGraphicHandlerLayer " + getName() + " projection changed, calling " - + getProjectionChangePolicy().getClass().getName()); - } - - getRenderPolicy().prePrepare(pe.getProjection()); - getProjectionChangePolicy().projectionChanged(pe); - } - - /** - * Get the ProjectionChangePolicy that determines how a layer reacts and - * gathers OMGraphics for a projection change. - */ - public ProjectionChangePolicy getProjectionChangePolicy() { - if (projectionChangePolicy == null) { - projectionChangePolicy = new StandardPCPolicy(this); - } - return projectionChangePolicy; - } - - /** - * Set the ProjectionChangePolicy that determines how a layer reacts and - * gathers OMGraphics for a projection change. - */ - public void setProjectionChangePolicy(ProjectionChangePolicy pcp) { - projectionChangePolicy = pcp; - // Just to make sure, - pcp.setLayer(this); - } - - /** - * Get the RenderPolicy that determines how an OMGraphicList is rendered. - */ - public RenderPolicy getRenderPolicy() { - if (renderPolicy == null) { - renderPolicy = new StandardRenderPolicy(this); - } - return renderPolicy; - } - - /** - * Set the RenderPolicy that determines how the OMGraphicList is rendered. - */ - public void setRenderPolicy(RenderPolicy rp) { - renderPolicy = rp; - // Just to make sure, - rp.setLayer(this); - } - - /** - * Sets the SwingWorker off to call prepare(). If the SwingWorker passed in - * is not null, start() is called on it. - * - * @param worker - * null to reset the layerWorker variable, or a SwingWorker to - * start up. - */ - protected void setLayerWorker(ISwingWorker worker) { - synchronized (LAYERWORKER_LOCK) { - layerWorker = worker; - layerWorkerQueue = false; - } - - if (worker != null) { - worker.start(); - } - } - - protected ISwingWorker getLayerWorker() { - return layerWorker; - } - - /** - * Called from within the layer to create a LayerWorker to use for the - * prepare() method. By default, a new LayerWorker is returned. This method - * may be overridden to make the layer use an extended - * LayerWorker/SwingWorker class. - * - * @return SwingWorker/LayerWorker - */ - protected ISwingWorker createLayerWorker() { - return new LayerWorker(); - } - - /** - * Overrides Layer.dispose(), makes sure the OMGraphicList is cleared. - */ - public void dispose() { - super.dispose(); - setList(null); - } - - /** - * This method is here to provide a default action for Layers as they act as - * a ProjectionPainter. Normally, ProjectionPainters are expected to receive - * the projection, gather/create OMGraphics that apply to the projection, - * and render them into the Graphics provided. This is supposed to be done - * in the same thread that calls this function, so the caller knows that - * when this method returns, everything that the ProjectionPainter needed to - * do is complete. - *

- * If the layer doesn't override this method, then the paint(Graphics) - * method will be called. - * - * @param proj - * Projection of the map. - * @param g - * java.awt.Graphics to draw into. - */ - public synchronized void renderDataForProjection(Projection proj, Graphics g) { - if (proj == null) { - logger.warning("Layer(" + getName() + ").renderDataForProjection: null projection!"); - return; - } else if (!proj.equals(getProjection())) { - setProjection(proj.makeClone()); - setList(getRenderPolicy().prepare()); - } - paint(g); - } - - /** - * The default action is to get the OMGraphicList and render it. - * - * @param g - * java.awt.Graphics object to render OMGraphics into. - */ - public void paint(Graphics g) { - getRenderPolicy().paint(g); - } - - /** - * A method that will launch a LayerWorker thread to call the prepare - * method. This method will set in motion all the steps needed to create and - * render the current OMGraphicList with the current projection. Nothing - * more needs to be called, because the LayerWorker will be started, it will - * call prepare(). Inside the prepare() method, the OMGraphicList should be - * created and the OMGraphics generated for the current projection that can - * be picked up in the getProjection() method, and the LayerWorker will call - * workerComplete() which will call repaint() on this layer. - */ - public void doPrepare() { - synchronized (LAYERWORKER_LOCK) { - - if (layerWorkerQueue) { - return; - } - - ISwingWorker currentLayerWorker = layerWorker; - - if (currentLayerWorker != null) { - layerWorkerQueue = true; - if (interruptable) { - currentLayerWorker.interrupt(); - } - return; - } - - setLayerWorker(createLayerWorker()); - } - } - - /** - * A check to see if the LayerWorker (SwingWorker) exists (is doing - * something). - */ - public boolean isWorking() { - // We don't care if it hasn't been interrupted - since the - // LayerWorker will launch a new thread when things settle out, we - // just want to know if there is a LayerWorker in place. If multiple - // doPrepare() calls come in, we need to ignore all of the requests - // that have come it after the first one that canceled the - // LayerWorker in the first place. - synchronized (LAYERWORKER_LOCK) { - return (layerWorker != null); - } - } - - /** - * This is the main method you should be concerned with when overriding this - * class. You have to make sure that this method returns an OMGraphicList - * that is ready to be rendered. That means they need to be generated with - * the current projection, which can be retrieved by calling - * getProjection(). - *

- * - * This method will be called in a separate thread if doPrepare() is called - * on the layer. This will automatically cause repaint() to be called, which - * lets java know to call paint() on this class. - *

- * - * Note that the default action of this method is to get the OMGraphicList - * as it is currently set in the layer, re-projects the list with the - * current projection (calls generate() on them), and then returns the - * current list. - *

- * - * If your layer needs to change what is on the list based on what the - * current projection is, you can either clear() the list yourself and add - * new OMGraphics to it (remember to call generate(Projection) on them), and - * return the list. You also have the option of setting a ListResetPCPolicy, - * which will automatically set the list to null when the projection changes - * before calling this method. The OMGraphicHandlerList will ignore a null - * OMGraphicList. - *

- * - * NOTE: If you call prepare directly, you may need to call repaint(), too. - * With all invocations of this method that are cause by a projection - * change, repaint() will be called for you. - * - * The method is synchronized in case renderDataForProjection() gets called - * while in the middle of this method. For a different projection, that - * would be bad. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList currentList = getList(); - Projection proj = getProjection(); - - // if the layer hasn't been added to the MapBean - // the projection could be null. - if (currentList != null && proj != null) { - currentList.generate(proj); - } - - return currentList; - } - - /** - * Lock object used for managing LayerWorker and queue synchronization. - */ - protected final Object LAYERWORKER_LOCK = new Object(); - - /** - * Check to see if it's likely the current thread will be replaced with - * another one. - * - * @return true if another layer worker is queued up. - */ - public boolean isCancelled() { - synchronized (LAYERWORKER_LOCK) { - return layerWorkerQueue; - } - } - - /** - * The LayerWorker calls this method on the layer when it is done working. - * If the calling worker is not the same as the "current" worker, then a new - * worker is created. - * - * @param worker - * the worker that has the graphics, must not be null. - */ - protected void workerComplete(ISwingWorker worker) { - - boolean finishUpWithWorker = false; - - synchronized (LAYERWORKER_LOCK) { - finishUpWithWorker = !layerWorkerQueue; - setLayerWorker(layerWorkerQueue ? createLayerWorker() : null); - layerWorkerQueue = false; - } - - if (finishUpWithWorker) { - // CAUTION! layer.repaint() is called in workerComplete!! - getProjectionChangePolicy().workerComplete(worker.get()); - } - } - - /** - * Since we can't have the main thread taking up the time to do the work to - * create OMGraphics, we use this worker thread to do it. - */ - class LayerWorker extends PooledSwingWorker { - /** Constructor used to create a worker thread. */ - public LayerWorker() { - super(); - } - - /** - * Compute the value to be returned by the get method. - */ - public OMGraphicList construct() { - logger.fine(getName() + "|LayerWorker.construct()"); - fireStatusUpdate(LayerStatusEvent.START_WORKING); - String errorMsg = null; - - try { - long start = System.currentTimeMillis(); - OMGraphicList list = getRenderPolicy().prepare(); - long stop = System.currentTimeMillis(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + "|LayerWorker.construct(): fetched " - + (list == null ? "null list in " : (list.size() + " graphics in ")) - + (double) ((stop - start) / 1000d) + " seconds"); - } - return list; - - } catch (OutOfMemoryError e) { - errorMsg = getName() + "| Ran out of memory: " + e.getMessage(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(errorMsg); - e.printStackTrace(); - } else { - logger.warning(getName() + " layer ran out of memory, attempting to recover..."); - } - } catch (Throwable e) { - errorMsg = getName() + "Caught thrown error: " + e.getClass().getName() + ", details: " + e.getMessage(); - logger.warning(errorMsg); - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - } - - // This is only called if there is an error. - if (errorMsg != null && logger.isLoggable(Level.FINE)) { - fireRequestMessage(new InfoDisplayEvent(this, errorMsg)); - } - - return null; - } - - /** - * Called on the event dispatching thread (not on the worker thread) - * after the construct method has returned. - */ - public void finished() { - workerComplete(this); - if (!isInterrupted()) { - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - } - - public String toString() { - return getName() + " LayerWorker"; - } - - } - - /** - * Overrides the Layer setProperties method. Also calls Layer's version. If - * the ProjectionChangePolicy and RenderPolicy objects are set - * programmatically, are PropertyConsumers and the .class property is not - * set, they will still have access to properties if this method is called. - * Their property prefix will be scoped as if the OMGraphicHandlerLayer had - * them created, with their prefix being prefix + . + - * PropertyChangePolicyProperty and prefix + . + RenderPolicyProperty. If - * the .class property is set, then a new policy object will be created and - * replace the one set before this method is called. - * - * @param prefix - * the token to prefix the property names - * @param props - * the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - // Check to see if the layer wants to set its own projection - // change policy. - String pcpString = props.getProperty(realPrefix + ProjectionChangePolicyProperty); - String policyPrefix; - if (pcpString != null) { - policyPrefix = realPrefix + pcpString; - - // If the projection change policy is null, try to create - // it. - String pcpClass = props.getProperty(policyPrefix + ".class"); - if (pcpClass != null) { - - Object obj = ComponentFactory.create(pcpClass, policyPrefix, props); - if (obj != null) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " setting ProjectionChangePolicy [" - + obj.getClass().getName() + "]"); - } - - try { - setProjectionChangePolicy((ProjectionChangePolicy) obj); - } catch (ClassCastException cce) { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for ProjectionChangePolicy, but " + policyPrefix - + ".class property (" + pcpClass - + ") does not define a valid ProjectionChangePolicy. A " + obj.getClass().getName() - + " was created instead."); - } - - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for PropertyChangePolicy, but " + policyPrefix - + ".class property does not define a valid PropertyChangePolicy."); - } - - } else if (projectionChangePolicy != null) { // ProjectionChangePolicy - // is not null... - // If the projection change policy is not null and the - // policy is a PropertyConsumer, pass the properties - // to the policy. Note that the property prefix for - // the policy is prefix + - // ProjectionChangePolicyProperty - - if (projectionChangePolicy instanceof PropertyConsumer) { - ((PropertyConsumer) projectionChangePolicy).setProperties(policyPrefix, props); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for PropertyChangePolicy, but " + policyPrefix - + ".class property is undefined."); - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " using default ProjectionChangePolicy [" - + getProjectionChangePolicy().getClass().getName() + "]"); - } - - // Check to see if the layer want to set its own rendering - // policy. - String rpString = props.getProperty(realPrefix + RenderPolicyProperty); - if (rpString != null) { - policyPrefix = realPrefix + rpString; - String rpClass = props.getProperty(policyPrefix + ".class"); - - if (rpClass != null) { - - Object rpObj = ComponentFactory.create(rpClass, policyPrefix, props); - - if (rpObj != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine( - "Layer " + getName() + " setting RenderPolicy [" + rpObj.getClass().getName() + "]"); - } - - try { - setRenderPolicy((RenderPolicy) rpObj); - } catch (ClassCastException cce) { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " + policyPrefix - + ".class property (" + rpClass + ") does not define a valid RenderPolicy. A " - + rpObj.getClass().getName() + " was created instead."); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " + policyPrefix - + ".class property (" + rpClass + ") isn't being created."); - } - - } else if (renderPolicy != null) { // RenderPolicy is not null... - // Same thing with renderPolicy as with projection - // change policy. - if (renderPolicy instanceof PropertyConsumer) { - ((PropertyConsumer) renderPolicy).setProperties(policyPrefix, props); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " + policyPrefix - + ".class property is undefined."); - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " using default RenderPolicy [" + getRenderPolicy().getClass().getName() - + "]"); - } - - String mmString = props.getProperty(realPrefix + MouseModesProperty); - if (mmString != null) { - List mmv = PropUtils.parseSpacedMarkers(mmString); - if (!mmv.isEmpty()) { - String[] mm = new String[mmv.size()]; - int i = 0; - for (String it : mmv) { - mm[i++] = it; - } - setMouseModeIDsForEvents(mm); - } - } - - consumeEvents = PropUtils.booleanFromProperties(props, realPrefix + ConsumeEventsProperty, consumeEvents); - - setTransparency(PropUtils.floatFromProperties(props, realPrefix + TransparencyProperty, getTransparency())); - - setInterruptable(PropUtils.booleanFromProperties(props, realPrefix + InterruptableProperty, isInterruptable())); - } - - /** - * Overrides Layer getProperties method., also calls that method on Layer. - * Sets the properties from the policy objects used by this OMGraphicHandler - * layer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - String policyPrefix = null; - - // //// ProjectionChangePolicy - - ProjectionChangePolicy pcp = getProjectionChangePolicy(); - if (pcp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) pcp).getPropertyPrefix(); - ((PropertyConsumer) pcp).getProperties(props); - } - - if (policyPrefix == null) { - policyPrefix = prefix + "pcp"; - } - - // Whoops, need to make sure pcp is valid but removing the - // OMGHL prefix from the front of the policy prefix (if - // applicable). Same for RenderPolicy - - props.put(prefix + ProjectionChangePolicyProperty, policyPrefix.substring(prefix.length())); - // This has to come after the above line, or the above - // property will have a trailing period. - policyPrefix = PropUtils.getScopedPropertyPrefix(policyPrefix); - props.put(policyPrefix + "class", pcp.getClass().getName()); - - RenderPolicy rp = getRenderPolicy(); - if (rp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) rp).getPropertyPrefix(); - ((PropertyConsumer) rp).getProperties(props); - } - - // /// RenderPolicy - - if (policyPrefix == null) { - policyPrefix = prefix + "rp"; - } - - props.put(prefix + RenderPolicyProperty, policyPrefix.substring(prefix.length())); - // This has to come after the above line, or the above - // property will have a trailing period. - policyPrefix = PropUtils.getScopedPropertyPrefix(policyPrefix); - props.put(policyPrefix + "class", rp.getClass().getName()); - - props.put(prefix + ConsumeEventsProperty, new Boolean(consumeEvents).toString()); - - String[] mm = getMouseModeIDsForEvents(); - if (mm != null && mm.length > 0) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mm.length; i++) { - // Don't need any MouseModes that have been scoped to - // the pretty name, those are automatically generated. - if (mm[i].equals(getName())) { - continue; - } - sb.append(mm[i]).append(" "); - } - props.put(prefix + MouseModesProperty, sb.toString()); - } - - props.put(prefix + TransparencyProperty, Float.toString(getTransparency())); - - props.put(prefix + InterruptableProperty, Boolean.toString(isInterruptable())); - - return props; - } - - /** - * Overrides Layer getProperties method., also calls that method on Layer. - * Sets the properties from the policy objects used by this OMGraphicHandler - * layer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - String policyPrefix = null; - - ProjectionChangePolicy pcp = getProjectionChangePolicy(); - if (pcp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) pcp).getPropertyPrefix(); - if (policyPrefix != null) { - int index = policyPrefix.indexOf("."); - if (index != -1) { - policyPrefix = policyPrefix.substring(index + 1); - } - - ((PropertyConsumer) pcp).getPropertyInfo(list); - } - } - - if (policyPrefix == null) { - policyPrefix = "pcp"; - } - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, policyPrefix + ".class", - "Projection Change Policy", "Class name of ProjectionChangePolicy (optional)", null); - - RenderPolicy rp = getRenderPolicy(); - if (rp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) rp).getPropertyPrefix(); - - if (policyPrefix != null) { - int index = policyPrefix.indexOf("."); - if (index != -1) { - policyPrefix = policyPrefix.substring(index + 1); - } - } - - ((PropertyConsumer) rp).getPropertyInfo(list); - } else { - } - - if (policyPrefix == null) { - policyPrefix = "rp"; - } - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, policyPrefix + ".class", - "Rendering Policy", "Class name of RenderPolicy (optional)", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, ConsumeEventsProperty, - "Consume mouse events", - "Flag that tells the layer to consume mouse events, or let other layers use them as well.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, MouseModesProperty, "Mouse modes", - "Space-separated list of MouseMode IDs to receive events from.", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, TransparencyProperty, "Transparency", - "Transparency setting for layer, between 0 (clear) and 1", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, InterruptableProperty, "Interruptable", - "Flat to set whether the layer should immediately stop performing current work when the projection changes.", - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return list; - } - - /** - * The MapMouseInterpreter used to catch the MapMouseEvents and direct them - * to layer as referencing certain OMGraphics. Manages how the layer - * responds to mouse events. - */ - protected MapMouseInterpreter mouseEventInterpreter = null; - - /** - * Set the interpreter used to field and interpret MouseEvents, thereby - * calling GestureResponsePolicy methods on this layer. - */ - public synchronized void setMouseEventInterpreter(MapMouseInterpreter mmi) { - - if (mmi instanceof StandardMapMouseInterpreter) { - String[] modeList = getMouseModeIDsForEvents(); - ((StandardMapMouseInterpreter) mmi).setMouseModeServiceList(modeList); - ((StandardMapMouseInterpreter) mmi).setConsumeEvents(getConsumeEvents()); - } - - if (mouseEventInterpreter != null) { - // Remove handle - mouseEventInterpreter.setGRP(null); - } - - mmi.setGRP(this); - mouseEventInterpreter = mmi; - } - - /** - * Get the interpreter used to field and interpret MouseEvents, thereby - * calling GestureResponsePolicy methods on this layer. This method checks - * to see if any mouse modes ids have been set via the - * getMouseModeIDsForEvents() method, and if there were and the interpreter - * hasn't been set, it will create a StandardMapMouseInterpreter. Otherwise, - * it returns whatever has been set as the interpreter, which could be null. - */ - public synchronized MapMouseInterpreter getMouseEventInterpreter() { - if (getMouseModeIDsForEvents() != null && mouseEventInterpreter == null) { - setMouseEventInterpreter(new StandardMapMouseInterpreter(this)); - } - - return mouseEventInterpreter; - } - - /** - * Query asked from the MouseDelegator for interest in receiving - * MapMouseEvents. This returns a MapMouseInterpreter that has been told to - * listen for events from the MapMouseModes in setMouseModeIDsForEvents(). - */ - public MapMouseListener getMapMouseListener() { - MapMouseListener mml = getMouseEventInterpreter(); - - if (mml != null) { - if (logger.isLoggable(Level.FINE)) { - - String[] modes = mml.getMouseModeServiceList(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < modes.length; i++) { - sb.append(modes[i]).append(", "); - } - - logger.fine("Layer " + getName() + " returning " + mml.getClass().getName() - + " as map mouse listener that listens to: " + sb.toString()); - } - } - - return mml; - } - - /** - * A flag to tell the layer to be selfish about consuming MouseEvents it - * receives. If set to true, it will consume events so that other layers - * will not receive the events. If false, lower layers will also receive - * events, which will let them react too. Intended to let other layers - * provide information about what the mouse is over when editing. - */ - public void setConsumeEvents(boolean consume) { - consumeEvents = consume; - - if (mouseEventInterpreter instanceof StandardMapMouseInterpreter) { - ((StandardMapMouseInterpreter) mouseEventInterpreter).setConsumeEvents(getConsumeEvents()); - } - } - - public boolean getConsumeEvents() { - return consumeEvents; - } - - /** - * This is the important method call that determines what MapMouseModes the - * interpreter for this layer responds to. The MapMouseInterpreter calls - * this so it can respond to MouseDelegator queries. You can - * programmatically call setMouseModeIDsForEvents with the mode IDs to set - * these values, or set the mouseModes property for this layer set to a - * space-separated list of mode IDs. - */ - public String[] getMouseModeIDsForEvents() { - return mouseModeIDs; - } - - /** - * Use this method to set which mouse modes this layer responds to. The - * array should contain the mouse mode IDs. - */ - public void setMouseModeIDsForEvents(String[] mm) { - - if (logger.isLoggable(Level.FINE)) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mm.length; i++) { - sb.append(mm[i]).append(" "); - } - - logger.fine("For layer " + getName() + ", setting mouse modes to " + sb.toString()); - } - - mouseModeIDs = mm; - - if (mouseEventInterpreter instanceof StandardMapMouseInterpreter) { - ((StandardMapMouseInterpreter) mouseEventInterpreter).setMouseModeServiceList(mm); - } - } - - /** - * Query asking if OMGraphic is highlight-able, which means that something - * in the GUI should change when the mouse is moved or dragged over the - * given OMGraphic. Highlighting shows that something could happen, or - * provides cursory information about the OMGraphic. Responding true to this - * method may cause getInfoText() and getToolTipTextFor() methods to be - * called (depends on the MapMouseInterpetor). - */ - public boolean isHighlightable(OMGraphic omg) { - return true; - } - - /** - * Query asking if an OMGraphic is select-able, or able to be moved, deleted - * or otherwise modified. Responding true to this method may cause select() - * to be called (depends on the MapMouseInterpertor) so the meaning depends - * on what the layer does in select. - */ - public boolean isSelectable(OMGraphic omg) { - return false; - } - - /** - * A current list of select OMGraphics. - */ - protected OMGraphicList selectedList; - - /** - * Retrieve the list of currently selected OMGraphics. - */ - public OMGraphicList getSelected() { - return selectedList; - } - - // //// Reactions - - /** - * Fleeting change of appearance for mouse movements over an OMGraphic. - */ - public void highlight(OMGraphic omg) { - omg.select(); - omg.generate(getProjection()); - repaint(); - } - - /** - * Notification to set OMGraphic to normal appearance. - */ - public void unhighlight(OMGraphic omg) { - omg.deselect(); - omg.generate(getProjection()); - repaint(); - } - - /** - * Designate a list of OMGraphics as selected. - */ - public void select(OMGraphicList list) { - if (list != null) { - for (OMGraphic omg : list) { - - if (selectedList == null) { - selectedList = new OMGraphicList(); - } - - if (omg instanceof OMGraphicList && !((OMGraphicList) omg).isVague()) { - select((OMGraphicList) omg); - } else { - selectedList.add(omg); - } - - } - } - } - - /** - * Designate a list of OMGraphics as de-selected. - */ - public void deselect(OMGraphicList list) { - if (list != null) { - for (OMGraphic omg : list) { - if (omg instanceof OMGraphicList && !((OMGraphicList) omg).isVague()) { - deselect((OMGraphicList) omg); - } else if (selectedList != null) { - selectedList.remove(omg); - } - } - } - } - - /** - * Remove OMGraphics from the layer. - */ - public OMGraphicList cut(OMGraphicList omgl) { - OMGraphicList list = getList(); - if (list != null && omgl != null) { - list.removeAll(omgl); - } - return omgl; - } - - /** - * Return a copy of OMGraphics. - */ - public OMGraphicList copy(OMGraphicList omgl) { - return (OMGraphicList) omgl.clone(); - } - - /** - * Add OMGraphics to the Layer. - */ - public void paste(OMGraphicList omgl) { - OMGraphicList list = getList(); - list.addAll(omgl); - } - - /** - * If applicable, should return a short, informational string about the - * OMGraphic to be displayed in the InformationDelegator. Return null if - * nothing should be displayed. - */ - public String getInfoText(OMGraphic omg) { - return null; - } - - /** - * If applicable, should return a tool tip for the OMGraphic. Return null if - * nothing should be shown. - */ - public String getToolTipTextFor(OMGraphic omg) { - return null; - } - - /** - * Return a JMenu with contents applicable to a pop-up menu for a location - * over the map. The pop-up doesn't concern any OMGraphics, and should be - * presented for a click on the map background. - * - * @param mme - * a MapMouseEvent describing the location over where the menu - * items should apply, in case different options are appropriate - * for different places. - * @return a JMenu for the map. Return null or empty List if no input - * required. - */ - public List getItemsForMapMenu(MapMouseEvent mme) { - return null; - } - - /** - * Return a java.util.List containing input for a JMenu with contents - * applicable to a pop-up menu for a location over an OMGraphic. - * - * @return a List containing options for the given OMGraphic. Return null or - * empty list if there are no options. - */ - public List getItemsForOMGraphicMenu(OMGraphic omg) { - return null; - } - - /** - * A query from the MapMouseInterpreter wondering if the - * GestureResponsePolicy wants events pertaining to mouse movements over the - * map that are not over an OMGraphic. If the GestureResponsePolicy responds - * true, then the mouseOver and leftClick methods will be called on the - * GestureResponsePolicy by the interpreter. There is no rightClick method - * that is called, because a right click will always cause a - * getItemsForMapMenu() method to be called. - */ - public boolean receivesMapEvents() { - return false; - } - - /** - * A notification that the mouse cursor has been moved over the map, not - * over any of the OMGraphics on the GestureResponsePolicy. This only gets - * called if the response to receiveMapEvents is true. - * - * @param mme - * MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed and should - * not be passed to anybody else. - */ - public boolean mouseOver(MapMouseEvent mme) { - return false; - } - - /** - * A notification that the mouse has been clicked with the left mouse button - * on the map, and not on any of the OMGraphics. This only gets called if - * the response to receiveMapEvents is true. Right clicks on the map are - * always reported to the getItemsForMapMenu method. - * - * @param mme - * MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed and should - * not be passed to anybody else. - */ - public boolean leftClick(MapMouseEvent mme) { - return false; - } - - /** - * Create a JPanel that has a slider to control the layer transparency. An - * action listener that calls layer repaint() when the value changes will be - * added to the slider. - * - * @param label - * the label for the panel around the slider. - * @param orientation - * JSlider.HORIZONTAL/JSlider.VERTICAL - * @param initialValue - * an initial transparency value between 0-1, 0 being clear. - * @return JPanel with controls for transparency setting. - */ - public JPanel getTransparencyAdjustmentPanel(String label, int orientation, float initialValue) { - JPanel opaquePanel = new JPanel(); - // opaquePanel.setBorder(BorderFactory.createEtchedBorder()); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - opaquePanel.setLayout(gridbag); - - c.anchor = GridBagConstraints.NORTHWEST; - JLabel jb = new JLabel(i18n.get(OMGraphicHandlerLayer.class, "layerTransparency", "Layer Transparency")); - gridbag.setConstraints(jb, c); - opaquePanel.add(jb); - - JSlider opaqueSlide = new JSlider(orientation, 0/* min */, 255/* max */, - (int) (255f * initialValue)/* inital */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(0), new JLabel(i18n.get(OMGraphicHandlerLayer.class, "clearSliderLabel", "clear"))); - dict.put(new Integer(255), new JLabel(i18n.get(OMGraphicHandlerLayer.class, "opqueSliderLabel", "opaque"))); - opaqueSlide.setLabelTable(dict); - opaqueSlide.setPaintLabels(true); - opaqueSlide.setMajorTickSpacing(50); - opaqueSlide.setPaintTicks(true); - opaqueSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - OMGraphicHandlerLayer.this.setTransparency((float) slider.getValue() / 255f); - repaint(); - } - } - }); - - c.gridy = 1; - gridbag.setConstraints(opaqueSlide, c); - opaquePanel.add(opaqueSlide); - - return opaquePanel; - } - - public JButton getRedrawButton(String tooltip) { - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setStroke(new BasicStroke(3)); - - IconPart reloadSymbol = OMIconPart.getReloadSymbol(); - reloadSymbol.setRenderingAttributes(da); - - ImageIcon ii = OMIconFactory.getIcon(20, 20, reloadSymbol); - JButton redraw = new JButton(ii); - redraw.setActionCommand(RedrawCmd); - redraw.setToolTipText("Redraw Layer"); - redraw.addActionListener(this); - return redraw; - } - - public JButton getSettingsButton(String tooltip) { - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setStroke(new BasicStroke(3)); - - IconPart settingsSymbol = OMIconPart.getSettingsSymbol(); - settingsSymbol.setRenderingAttributes(da); - - ImageIcon ii = OMIconFactory.getIcon(20, 20, settingsSymbol); - JButton redraw = new JButton(ii); - redraw.setActionCommand(DisplayPropertiesCmd); - redraw.setToolTipText(tooltip); - redraw.addActionListener(this); - return redraw; - } - - /** - * Get a default settings panel that contains the layer transparency - * setting, the settings button and a layer refresh button. - * - * @param clss - * The class for i18n translations - * @param opaquenessSetting - * The current opaqueness setting, as some fraction of 255. 1 is - * opaque. - * @return JPanel with the components all laid out. - */ - public JPanel getDefaultSettingsPanel(Class clss, float opaquenessSetting) { - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - panel.setLayout(gridbag); - - c.gridx = 0; - c.gridy = 0; - c.gridheight = 2; - c.insets = new Insets(5, 5, 5, 0); - - JPanel transPanel = getTransparencyAdjustmentPanel( - i18n.get(clss, "layerTransparencyGUILabel", "Layer Transparency"), JSlider.HORIZONTAL, - opaquenessSetting); - gridbag.setConstraints(transPanel, c); - panel.add(transPanel); - - c.gridx = 1; - c.gridheight = 1; - c.insets = new Insets(5, 0, 0, 5); - JButton jb = getSettingsButton(i18n.get(clss, "layerSettingsButtonTooltip", "Change Layer Settings")); - gridbag.setConstraints(jb, c); - panel.add(jb); - - c.gridy = 1; - c.insets = new Insets(0, 0, 5, 5); - jb = getRedrawButton(i18n.get(clss, "layerRedrawButtonTooltip", "Refresh Layer")); - gridbag.setConstraints(jb, c); - panel.add(jb); - - return panel; - } - - /** - * Set the transparency of the layer. This transparency is applied during - * rendering. - * - * @param value - * 0f for clear, 1f for opaque. - */ - public void setTransparency(float value) { - AlphaComposite ac = null; - if (value != 1f) { - ac = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, value); - } - getRenderPolicy().setComposite(ac); - } - - /** - * Get the transparency value for this layer. - * - * @return 1 if opaque, 0 for clear. - */ - public float getTransparency() { - float ret = 1f; - RenderPolicy rp = getRenderPolicy(); - - if (rp != null) { - Composite comp = rp.getComposite(); - if (comp instanceof AlphaComposite) { - ret = ((AlphaComposite) comp).getAlpha(); - } - } - - return ret; - } - - /** - * Override of Layer's actionPerformed method, adds the capability that - * calls doPrepare() if the layer is visible and it receives a RedrawCmd - * command. Also calls Layer.actionPerformed(ActionEvent). - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String cmd = e.getActionCommand(); - if (cmd == RedrawCmd) { - if (isVisible()) { - doPrepare(); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/OverviewMapAreaLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/OverviewMapAreaLayer.java deleted file mode 100644 index e323899a8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/OverviewMapAreaLayer.java +++ /dev/null @@ -1,137 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/OverviewMapAreaLayer.java,v $ -// $RCSfile: OverviewMapAreaLayer.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Graphics; -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.OverviewMapStatusListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * A class used to draw a polygon representing the area covered by the source - * MapBean projection. Used by the OverviewMapHandler. The layer responds to - * DrawingAttributes properties being set, which are forwarded on to the - * coverage box rectangle. - *

- * This layer uses the source map's projection to construct a polygon to depict - * the coverage area. A coverage area in one projection does not necessarily - * translate into a rectangle on another projection. This layer uses the source - * map projection to create a polygon that approximates the extents of the - * projection by walking the perimeter of the projection's screen coordinates - * and translating those screen coordinates into a lat/lon array for the - * polygon. - */ -public class OverviewMapAreaLayer extends Layer implements OverviewMapStatusListener { - - protected float overviewScale; - protected OMGraphic poly; - protected Projection sourceMapProjection; - protected DrawingAttributes areaAttributes = DrawingAttributes.getDefaultClone(); - - public void projectionChanged(ProjectionEvent pEvent) { - - if (sourceMapProjection == null) - return; - - Projection proj = pEvent.getProjection(); - - // Save the scale for use in the - overviewScale = proj.getScale(); - - boolean cylindrical = sourceMapProjection instanceof Cylindrical; - - double[] llarr = ProjMath.getProjectionScreenOutlineCoords(sourceMapProjection); - - if (llarr != null) { - - boolean northPoleVisible = ProjMath.isVisible(sourceMapProjection, new LatLonPoint.Double(90, 0)); - boolean southPoleVisible = ProjMath.isVisible(sourceMapProjection, new LatLonPoint.Double(-90, 0)); - - if (northPoleVisible || southPoleVisible) { - Point2D center = sourceMapProjection.getCenter(); - Point2D ul = sourceMapProjection.getUpperLeft(); - double dist = Geo.distance(center.getY(), center.getX(), ul.getY(), ul.getX()); - poly = new OMCircle(center.getY(), center.getX(), dist, Length.RADIAN); - } else { - poly = new OMPoly(llarr, OMPoly.DECIMAL_DEGREES, cylindrical ? OMGraphic.LINETYPE_STRAIGHT - : OMGraphic.LINETYPE_GREATCIRCLE); - } - areaAttributes.setTo(poly); - - // And finally generate the poly - poly.generate(proj); - } - } - - /** - * Set with the projection of the source MapBean, before changing the - * projection of the overview MapBean. That way, the rectangle coordinates - * are set before they get generated(). - */ - public void setSourceMapProjection(Projection proj) { - sourceMapProjection = proj; - } - - public void paint(Graphics g) { - if (poly != null && overviewScale > sourceMapProjection.getScale()) - poly.render(g); - } - - public DrawingAttributes getAreaAttributes() { - return areaAttributes; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - areaAttributes.setProperties(prefix, props); - // Cause a rebuild if this is called after - // the first projection change. - poly = null; - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - areaAttributes.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - areaAttributes.getPropertyInfo(props); - return props; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/PointGroupLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/PointGroupLayer.java deleted file mode 100644 index 8762778f0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/PointGroupLayer.java +++ /dev/null @@ -1,131 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: AOILayer.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:27 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer; - -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * A simple layer that lets you define point group sets to be drawn on the map - * by defining coordinates for points in the properties file. It's similar to - * the AOILayer except the coordinates are drawn as a set of points, and are not - * connected. Each group of points share rendering properties. A sample of - * properties that could be used for this layer: - * - *

- * 
- * pgl.class=com.bbn.openmap.layer.PointGroupLayer
- * pgl.prettyName=Points of Interest
- * pgl.goi=goi1 goi2
- * pgl.goi1.name=First Grouping
- * pgl.goi1.coords=33.469604f 69.852425f 33.591957f 69.85425f 33.598362f 69.965256f 33.474995f 69.96891f 33.469604f 69.852425f
- * pgl.goi1.lineColor=FF9900
- * pgl.goi1.selectColor=FF9900
- * pgl.goi1.fillColor=33FF9900
- * pgl.goi1.lineWidth=2
- * pgl.goi1.pointOval=false
- * pgl.goi1.pointRadius=3
- * pgl.goi2.name=Second Grouping
- * pgl.goi2.coords=34.59030485181645f 70.10225955962484f 34.70749132408063f 70.10062341994104f 34.705166929775665f 70.24468896438881f 34.58780191583231f 70.24351387509675f 34.59030485181645f 70.10225955962484f
- * pgl.goi2.lineColor=CCFF00
- * pgl.goi2.selectColor=CCFF00
- * pgl.goi2.fillColor=33CCFF00
- * pgl.goi2.lineWidth=2
- * pgl.goi2.pointOval=true
- * pgl.goi2.pointRadius=5
- * 
- * 
- * - * @author dietrick - */ -public class PointGroupLayer extends OMGraphicHandlerLayer { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.PointGroupLayer"); - - public final static String GOIProperty = "goi"; - public final static String GOICoordsProperty = "coords"; - public final static String GOINameProperty = "name"; - - public PointGroupLayer() { - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - DrawingAttributes attributes = new DrawingAttributes(); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - List aois = PropUtils.parseSpacedMarkers(props.getProperty(prefix + GOIProperty)); - - OMGraphicList list = new OMGraphicList(); - - for (Iterator it = aois.iterator(); it.hasNext();) { - String aoi = it.next(); - - String aoiPrefix = PropUtils.getScopedPropertyPrefix(prefix + aoi); - List coordV = PropUtils.parseSpacedMarkers(props.getProperty(aoiPrefix + GOICoordsProperty)); - - attributes.setProperties(aoiPrefix, props); - String name = props.getProperty(aoiPrefix + GOINameProperty); - - OMGraphicList groupList = new OMGraphicList(); - - for (Iterator cit = coordV.iterator(); cit.hasNext();) { - try { - double lat = Double.parseDouble(cit.next()); - double lon = Double.parseDouble(cit.next()); - - OMPoint omp = new OMPoint(lat, lon); - attributes.setTo(omp); - omp.putAttribute(OMGraphic.TOOLTIP, "Location: " + lat + ", " + lon); - groupList.add(omp); - - } catch (NumberFormatException nfe) { - logger.warning("can't parse coords for " + aoi + ": " + coordV); - break; - } - } - - groupList.putAttribute(OMGraphic.TOOLTIP, name); - - list.add(groupList); - } - - setList(list); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/ScaleDisplayLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/ScaleDisplayLayer.java deleted file mode 100644 index 82226649b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/ScaleDisplayLayer.java +++ /dev/null @@ -1,345 +0,0 @@ -/* ********************************************************************** - * - * ROLANDS & ASSOCIATES Corporation - * 500 Sloat Avenue - * Monterey, CA 93940 - * (831) 373-2025 - * - * Copyright (C) 2002, 2003 ROLANDS & ASSOCIATES Corporation. All rights reserved. - * Openmap is a trademark of BBN Technologies, A Verizon Company - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/ScaleDisplayLayer.java,v $ - * $Revision: 1.9 $ - * $Date: 2005/12/09 21:09:08 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.layer; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * The ScaleDisplayLayer draws a scale indicator in the corner of the map, - * showing a line and displaying its length. You can set the location of the - * indicator, the colors, and the units being shown. - *

- * - *

- * 
- * ### Layer used by the overview handler
- * scaleLayer.class=com.bbn.openmap.layer.ScaleDisplayLayer
- * scaleLayer.prettyName=Scale
- * scaleLayer.lineColor=ff777777
- * scaleLayer.textColor=ff000000
- * scaleLayer.unitOfMeasure=nm
- * scaleLayer.locationXoffset=-10
- * scaleLayer.locationYoffset=-20
- * scaleLayer.width=150
- * scaleLayer.height=10
- * 
- * # unitOfMeasure - any com.bbn.openmap.proj.Length instance returned by Length.get(string).
- * # locationXoffset - offset in pixels from left/right, positive from left edge, negative from right edge
- * # locationYoffset - offset in pixels from top/bottom, positive from top edge, negative from bottom edge
- * # width - width of scale indicator bar in pixels
- * # height - height of scale indicator bar in pixels
- *
- * 
- */ -public class ScaleDisplayLayer extends OMGraphicHandlerLayer { - - public ScaleDisplayLayer() { - super(); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setUnitOfMeasure(Length.KM.toString()); - } - - protected Logger logger = Logger.getLogger("com.bbn.openmap.layer.ScaleDisplayLayer"); - - // Color variables for different line types - protected java.awt.Color lineColor = null; - protected java.awt.Color textColor = null; - - // Default colors to use, if not specified in the properties. - protected String defaultLineColorString = "FFFFFF"; - protected String defaultTextColorString = "FFFFFF"; - protected String defaultUnitOfMeasureString = "km"; - protected int defaultLocationXoffset = -10; - protected int defaultLocationYoffset = -10; - protected int defaultWidth = 150; - protected int defaultHeight = 10; - - // property text values - public static final String UnitOfMeasureProperty = "unitOfMeasure"; - public static final String LocationXOffsetProperty = "locationXoffset"; - public static final String LocationYOffsetProperty = "locationYoffset"; - public static final String WidthProperty = "width"; - public static final String HeightProperty = "height"; - - protected String unitOfMeasure = null; - protected Length uom = Length.get(defaultUnitOfMeasureString); - protected String uomAbbr = uom.getAbbr(); - protected int locationXoffset = defaultLocationXoffset; - protected int locationYoffset = defaultLocationYoffset; - protected int width = defaultWidth; - protected int height = defaultHeight; - - protected DrawingAttributes dAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than the - * setArgs method. - * - * @param prefix the token to prefix the property names - * @param properties the Properties object - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - dAttributes.setProperties(prefix, properties); - - String unitOfMeasureString = properties.getProperty(prefix + UnitOfMeasureProperty); - if (unitOfMeasureString != null) { - setUnitOfMeasure(unitOfMeasureString); - } - - locationXoffset = PropUtils.intFromProperties(properties, prefix + LocationXOffsetProperty, - defaultLocationXoffset); - - locationYoffset = PropUtils.intFromProperties(properties, prefix + LocationYOffsetProperty, - defaultLocationYoffset); - - width = PropUtils.intFromProperties(properties, prefix + WidthProperty, defaultWidth); - - height = PropUtils.intFromProperties(properties, prefix + HeightProperty, defaultHeight); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - dAttributes.setProperties(props); - - props.put(prefix + LocationXOffsetProperty, Integer.toString(locationXoffset)); - props.put(prefix + LocationYOffsetProperty, Integer.toString(locationYoffset)); - props.put(prefix + WidthProperty, Integer.toString(width)); - props.put(prefix + HeightProperty, Integer.toString(height)); - - props.put(prefix + UnitOfMeasureProperty, unitOfMeasure); - - return props; - } - - public synchronized OMGraphicList prepare() { - int w, h, left_x = 0, right_x = 0, lower_y = 0, upper_y = 0; - Projection projection = getProjection(); - OMGraphicList graphics = new OMGraphicList(); - - w = projection.getWidth(); - h = projection.getHeight(); - if (locationXoffset < 0) { - left_x = w + locationXoffset - width; - right_x = w + locationXoffset; - } else if (locationXoffset >= 0) { - left_x = locationXoffset; - right_x = locationXoffset + width; - } - if (locationYoffset < 0) { - upper_y = h + locationYoffset - height; - lower_y = h + locationYoffset; - } else if (locationYoffset >= 0) { - upper_y = locationYoffset; - lower_y = locationYoffset + height; - } - - graphics.clear(); - - OMLine line = new OMLine(left_x, lower_y, right_x, lower_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(left_x, lower_y, left_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(right_x, lower_y, right_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - /* - * We need to use better coordinates to measure distance, like the same - * pixel distance at the center of the map. There's a problem using the - * lower right location, in that those distances decrease as you zoom - * out. - */ - - int y = h / 2; - int x = w / 2; - int xSide = (right_x - left_x) / 2; - - LatLonPoint loc1 = projection.inverse(x - xSide, y, new LatLonPoint.Double()); - LatLonPoint loc2 = projection.inverse(x + xSide, y, new LatLonPoint.Double()); - - double dist = uom.fromRadians(loc1.distance(loc2)); - - String outtext; - if (dist < 1.0f) { - outtext = String.format("%.3f %s", dist, uomAbbr); - } else if (dist < 10.0f) { - outtext = String.format("%.2f %s", dist, uomAbbr); - } else if (dist < 100.0f) { - outtext = String.format("%.1f %s", dist, uomAbbr); - } else { - outtext = String.format("%.0f %s", dist, uomAbbr); - } - - /* - * OMText text = new OMText((left_x + right_x) / 2, lower_y - 3, "" + - * outtext, OMText.JUSTIFY_CENTER); Font font = text.getFont(); - * text.setFont(font.deriveFont(font.BOLD, font.getSize() + 4)); - * dAttributes.setTo(text); text.setTextMatteColor((Color) - * dAttributes.getMattingPaint()); text.setTextMatteStroke(new - * BasicStroke(5)); text.setMattingPaint(OMColor.clear); - * graphics.add(text); graphics.generate(projection); - */ - - OMText text = new OMText(right_x, lower_y - 20, "" + outtext, OMText.JUSTIFY_RIGHT); - - Font font = text.getFont(); - text.setFont(font.deriveFont(Font.BOLD, font.getSize() + 4)); - - dAttributes.setTo(text); - text.setTextMatteColor((Color) dAttributes.getMattingPaint()); - text.setTextMatteStroke(new BasicStroke(5)); - text.setMattingPaint(OMColor.clear); - graphics.add(text); - graphics.generate(projection); - - return graphics; - } - - /** - * Getter for property unitOfMeasure. - * - * @return Value of property unitOfMeasure. - */ - public String getUnitOfMeasure() { - return this.unitOfMeasure; - } - - /** - * Setter for property unitOfMeasure. - * - * @param unitOfMeasure New value of property unitOfMeasure. - */ - public void setUnitOfMeasure(String unitOfMeasure) { - if (unitOfMeasure == null) - unitOfMeasure = Length.KM.toString(); - this.unitOfMeasure = unitOfMeasure; - - // There is a bug in the Length.get() method that will not - // return - // the correct (or any value) for a requested uom. - // This does not work: - // uom = com.bbn.openmap.proj.Length.get(unitOfMeasure); - - // Therefore, The following code correctly obtains the proper - // Length object. - - Length[] choices = Length.values(); - uom = null; - for (int i = 0; i < choices.length; i++) { - if (unitOfMeasure.equalsIgnoreCase(choices[i].toString()) - || unitOfMeasure.equalsIgnoreCase(choices[i].getAbbr())) { - uom = choices[i]; - break; - } - } - - // of no uom is found assign Kilometers as the default. - if (uom == null) - uom = Length.KM; - - uomAbbr = uom.getAbbr(); - - } - - JPanel palettePanel; - ButtonGroup uomButtonGroup; - Vector buttons = new Vector(); - - /** - * Creates the interface palette. - */ - public java.awt.Component getGUI() { - - if (palettePanel == null) { - - logger.fine("creating palette."); - - palettePanel = new JPanel(); - uomButtonGroup = new ButtonGroup(); - - palettePanel.setLayout(new javax.swing.BoxLayout(palettePanel, javax.swing.BoxLayout.Y_AXIS)); - palettePanel.setBorder(new javax.swing.border.TitledBorder("Unit Of Measure")); - - java.awt.event.ActionListener al = new ActionListener() { - // We don't have to check for action commands or anything like - // that. - // We know this listener is going to be added to JRadioButtons - // that are labeled with abbreviations for length. - public void actionPerformed(ActionEvent e) { - JRadioButton jrb = (JRadioButton) e.getSource(); - setUnitOfMeasure(jrb.getText()); - } - }; - - for (Length lengthType : Length.values()) { - JRadioButton jrb = new JRadioButton(); - jrb.setText(lengthType.getAbbr()); - jrb.setToolTipText(lengthType.toString()); - uomButtonGroup.add(jrb); - palettePanel.add(jrb); - - jrb.addActionListener(al); - - jrb.setSelected(unitOfMeasure.equalsIgnoreCase(lengthType.getAbbr())); - buttons.add(jrb); - } - - } else { - for (JRadioButton button : buttons) { - button.setSelected(uom.getAbbr().equalsIgnoreCase(button.getText())); - } - } - - return palettePanel; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/ScaleFilterLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/ScaleFilterLayer.java deleted file mode 100644 index 2ae032d81..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/ScaleFilterLayer.java +++ /dev/null @@ -1,935 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/ScaleFilterLayer.java,v $ -// $RCSfile: ScaleFilterLayer.java,v $ -// $Revision: 1.14 $ -// $Date: 2008/09/26 12:07:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that encapsulates other layers and acts as a scale filter. - * It will delegate responsibility to one of several layers depending on the - * scale. - *

- * To use this layer, list it as a layer in the openmap.properties file in the - * openmap.layers properties, as you would add any other layer. Then, add these - * properties to the openmap.properties file. The layers added to the - * ScaleFilterLayer do not get added to the openmap.layers property, but instead - * get added to the scaledFilterLayer.layers property listed here. Then, the - * properties for these layers are added to the openmap.properties file like any - * other layer. - *

- * - *

- * The properties for this layer look like this:
- * 
- * scaledFilterLayer.class=com.bbn.openmap.layer.ScaleFilterLayer
- * scaledFilterLayer.prettyName=<Pretty name used on menu>
- * # List 2 or more layer prefixes, larger scale layers first
- * scaledFilterLayer.layers=layer_1 layer_2 layer_3 ...
- * # List the transition scales to switch between layers
- * scaledFilterLayer.transitionScales= (transition scale from layer 1 to 2) (transition scale from layer 2 to 3) (...)
- * # have layers dump resources when not on map.  May not want to do this for layers with long initializations.
- * cleanupLayers=true
- * 
- */ -public class ScaleFilterLayer extends Layer - implements InfoDisplayListener, LayerStatusListener, PropertyChangeListener, MapMouseListener { - - /** - * The layers property. - */ - public final static transient String layersProperty = "layers"; - - /** - * The transition scales property. - */ - public final static transient String transitionScalesProperty = "transitionScales"; - /** - * Property for setting aggressive layer cleanup, when layer isn't being - * displayed on map. - */ - public final static transient String AGGRESSIVE_LAYER_CLEAUP_PROPERTY = "cleanupLayers"; - /** - * The layers. - */ - protected Vector layers; - - /** - * The transition scales. - */ - protected float[] transitionScales; - - /** - * The default transition scale. - */ - protected float defaultTransitionScale = 40000000f; - - /** - * The index of the currently selected layer. - */ - protected int targetIndex = -1; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.ScaleFilterLayer"); - /** - * Flag to notify layers when they aren't active, so they can dump resources - * when they aren't on the map. Set to false to improve reaction times when - * zooming, since any layer would be initialized once. Setting this to true - * will force layers to reinitialize when they are put back on the map. - * - * This will only affect layers that override removed(Container) properly. - */ - public boolean aggressiveLayerCleanup = false; - - /** - * Initializes an empty layer. - */ - public ScaleFilterLayer() { - // Setting the overlay layout seemed like a good idea at the time, but - // it introduces a strange bug where the bounds of the layer get set - // between the center of the map and the lower left corner. This only - // happens for the BufferedLayerMapBean, when there are buffered layers - // active. Very strange, but not setting an overlay seems to work OK, - // too. - // setLayout(new OverlayLayout(this)); - - // To get MouseDelegator, to make decisions on receiving mouse - // modes for child layers. - setAddToBeanContext(true); - } - - /** - * Get the Vector holding the Layers. If it hasn't been asked for yet, a - * new, empty Vector will be returned, one that will be used internally. - */ - public Vector getLayers() { - if (layers == null) { - layers = new Vector(); - } - return layers; - } - - /** - * Get the transition scales used to set the active layer. - */ - public float[] getTransitionScales() { - return transitionScales; - } - - /** - * Programmatic way to set layers and scales. There should be one more layer - * on the list than there is scale in the float array. Layers that should be - * displayed for larger scale numbers (smaller scale) should be at the front - * of the Vector list, and larger numbers should be at the front of the - * scale array. For scale numbers larger than the first number in the array, - * the first layer will be displayed. As the scale number decreases, other - * layers will be displayed. - * - * @param list Vector of layers - * @param scales Array of transition scales. - */ - public void setLayersAndScales(Vector list, float[] scales) { - layers = list; - transitionScales = scales; - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for this layer - */ - public void setProperties(String prefix, Properties props) { - // Clear out layer and scale state - setLayersAndScales(null, null); - - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - parseLayers(prefix, props); - parseScales(prefix, props); - - // Update our target layer. If there is a current projection and this - // layer is active, we need to pass it along. - if (getProjection() != null) { - Layer currentLayer = configureAppropriateLayer(getProjection().getScale()); - fireStatusUpdate(LayerStatusEvent.START_WORKING); - currentLayer.projectionChanged(new ProjectionEvent((Object) null, getProjection())); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - float[] ts = getTransitionScales(); - StringBuffer tsBuffer = new StringBuffer(); - if (ts != null) { - for (int i = 0; i < ts.length; i++) { - tsBuffer.append(Float.toString(ts[i])).append(" "); - } - } - props.put(prefix + transitionScalesProperty, tsBuffer.toString()); - - StringBuffer layerBuffer = new StringBuffer(); - for (Layer layer : getLayers()) { - layerBuffer.append(layer.getPropertyPrefix()).append(" "); - layer.getProperties(props); - } - props.put(prefix + layersProperty, layerBuffer.toString()); - - return props; - } - - /** - * Get the layer that's appropriate at the current scale. The targetedIndex - * needs to be set before this is called. The targetedIndex is the index to - * the layers array representing the current layer. - * - * @return Layer - */ - public Layer getAppropriateLayer() { - try { - return getLayers().elementAt(targetIndex); - } catch (NullPointerException npe) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - - return SinkLayer.getSharedInstance(); - } - - /** - * Create the Layers from a property value string. - * - * @param prefix String - * @param props Properties - */ - protected void parseLayers(String prefix, Properties props) { - PropUtils.putDataPrefixToLayerList(this, props, prefix + layersProperty); - - String layersString = props.getProperty(prefix + layersProperty); - Vector layers = getLayers(); - if (layersString == null || layersString.length() == 0) { - logger.info("ScaleFilterLayer(): null layersString!"); - return; - } - StringTokenizer tok = new StringTokenizer(layersString); - while (tok.hasMoreTokens()) { - Object obj; - String layerName = tok.nextToken(); - String classProperty = layerName + ".class"; - String className = props.getProperty(classProperty); - if (className == null) { - logger.info("ScaleFilterLayer.parseLayers(): Failed to locate property \"" + classProperty + "\""); - logger.info("ScaleFilterLayer.parseLayers(): Skipping layer \"" + layerName + "\""); - className = SinkLayer.class.getName(); - } - - try { - if (className.equals(SinkLayer.class.getName())) { - obj = SinkLayer.getSharedInstance(); - } else { - obj = Class.forName(className).newInstance(); - } - if (logger.isLoggable(Level.FINE)) { - logger.fine("Instantiated " + className); - } - } catch (Exception e) { - logger.info("Failed to instantiate \"" + className + "\": " + e); - obj = SinkLayer.getSharedInstance(); - } - - // create the layer and set its properties - if (obj instanceof Layer) { - Layer l = (Layer) obj; - l.setProperties(layerName, props); - l.addLayerStatusListener(this); - l.addInfoDisplayListener(this); - layers.addElement(l); - } - } - } - - /** - * Create the transition scales from a property value string. If there are N - * layers, there should be N-1 transition scales. - * - * @param prefix String - * @param props Properties - */ - protected void parseScales(String prefix, Properties props) { - StringTokenizer tok = null; - Vector layers = getLayers(); - int size = layers.size(); - if (size > 0) { - --size; - } - transitionScales = new float[size]; - - String scales = props.getProperty(prefix + transitionScalesProperty); - if (scales == null) { - logger.info("Failed to locate property \"" + transitionScalesProperty + "\""); - if (transitionScales.length > 0) { - transitionScales[0] = defaultTransitionScale; - } - for (int i = 1; i < transitionScales.length; i++) { - transitionScales[i] = transitionScales[i - 1] / 3; - } - return; - } - - try { - tok = new StringTokenizer(scales); - transitionScales[0] = (tok.hasMoreTokens()) ? new Float(tok.nextToken()).floatValue() - : defaultTransitionScale; - } catch (NumberFormatException e) { - logger.info("ScaleFilterLayer.parseScales()1: " + e); - transitionScales[0] = defaultTransitionScale; - } - - if (tok != null) { - for (int i = 1; i < transitionScales.length; i++) { - try { - transitionScales[i] = (tok.hasMoreTokens()) ? new Float(tok.nextToken()).floatValue() - : transitionScales[i - 1] / 3; - } catch (NumberFormatException e) { - logger.info("ScaleFilterLayer.parseScales()2: " + e); - transitionScales[i] = transitionScales[i - 1] / 3; - } - } - } - } - - /** - * Implementing the ProjectionPainter interface. - */ - public synchronized void renderDataForProjection(Projection proj, java.awt.Graphics g) { - // This is a special case for a layer - It doesn't get told when - // sub-layers are done working. - // This may be the only time it finds out they are done (if part of SFL - // in background). - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - if (proj == null) { - logger.info("null projection!"); - return; - } else { - setTargetIndex(proj.getScale()); - Layer layer = getAppropriateLayer(); - layer.renderDataForProjection(proj, g); - } - } - - /** - * Calculate the index of the target layer. If there are N layers, there are - * N-1 transitionScales. The ith layer is chosen if the scale is greater - * than the ith transitionScale. - * - * @param scale the current map scale - * @return true if the targetIndex has changed as a result of the new scale. - */ - public boolean setTargetIndex(float scale) { - boolean changed = false; - float[] target = transitionScales; - - int i = 0; - if (target != null) { - for (i = 0; i < target.length; i++) { - if (scale > target[i]) { - break; - } - } - } - - if (targetIndex != i) { - changed = true; - } - targetIndex = i; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("ScaleFilterLayer(" + getName() + ") targetIndex: " + targetIndex + ", changed: " + changed); - } - - return changed; - } - - /** - * Handles projection change notification events. Throws out old graphics, - * and requests new graphics from the spatial index based on the bounding - * rectangle of the new Projection. - * - * @param ev the new projection event - */ - public void projectionChanged(ProjectionEvent ev) { - // Lets the ScaleFilterLayer remember the projection, just in case. - setProjection(ev); - - Projection proj = ev.getProjection(); - // get the appropriate layer and invoke projectionChanged - Layer layer = configureAppropriateLayer(proj.getScale()); - - fireStatusUpdate(LayerStatusEvent.START_WORKING); - layer.projectionChanged(ev); - } - - protected Layer configureAppropriateLayer(float scale) { - Layer currentLayer = getAppropriateLayer(); - boolean changed = setTargetIndex(scale); - - // get the appropriate layer and invoke projectionChanged - Layer layer = getAppropriateLayer(); - if (changed) { - currentLayer.removeNotify(); - setPaletteTab(targetIndex); - remove(currentLayer); - // Allow current layer to clean up - if (aggressiveLayerCleanup) { - currentLayer.removed(this); - } - - // This will handle the repaint() requests from the - // layer... - add(layer); - layer.addNotify(); - checkMouseMode(); - } - - return layer; - } - - /** - * This method is called after the layer is removed from the MapBean and - * when the projection changes. We recommend that Layers override this - * method and nullify memory-intensive variables. - * - * @param cont Container - */ - public void removed(Container cont) { - getAppropriateLayer().removed(this); - } - - /** - * Renders the scale-appropriate layer on the map. - * - * @param g a graphics context - */ - public void paint(Graphics g) { - getAppropriateLayer().paint(g); - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - - /** - * Try to handle receiving LayerStatusEvents from child layers. May not - * always work, depending on what thread sends/receives this event - usually - * in the Swing thread, and the GUI can't always be updated as expected. - * - * @param evt LayerStatusEvent - */ - public void updateLayerStatus(LayerStatusEvent evt) { - fireStatusUpdate(evt); - } - - protected JPanel panel = null; - protected JTabbedPane tabs = null; - - /** - * Get the GUI (palettes) for the layers. The BufferedLayer actually creates - * a JTabbedPane holding the palettes for all of its layers, and also has a - * pane for itself that provides visibility control for the group layers. - */ - public Component getGUI() { - if (panel == null) { - - Iterator it = getLayers().iterator(); - panel = new JPanel(); - tabs = new JTabbedPane(); - - // bfPanel still needs controls for controlling scales, - // etc, showing which one is showing, etc., as well as - // some indication as which layer is currently active. - - JPanel bfPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - bfPanel.setLayout(gridbag); - - tabs.addTab("Scale Filter Controls", bfPanel); - - JButton gotoButton = new JButton("Go to Active Layer Tab"); - gotoButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setPaletteTab(targetIndex); - } - }); - - c.gridy = 0; - gridbag.setConstraints(gotoButton, c); - bfPanel.add(gotoButton); - - while (it.hasNext()) { - Layer layer = it.next(); - Component layerGUI = layer.getGUI(); - if (layerGUI != null) { - tabs.addTab(layer.getName(), layerGUI); - } else { - tabs.addTab(layer.getName(), getEmptyGUIFiller(layer)); - } - } - panel.add(tabs); - } - setPaletteTab(targetIndex); - return panel; - } - - public Component getEmptyGUIFiller(Layer layer) { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - JPanel panel = new JPanel(); - panel.setLayout(gridbag); - - JLabel label = new JLabel("No properties available for"); - JLabel label2 = new JLabel("the " + layer.getName() + "."); - - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(label, c); - gridbag.setConstraints(label2, c); - panel.add(label); - panel.add(label2); - return panel; - } - - protected void setPaletteTab(int layerIndex) { - Vector layers = getLayers(); - if (layers.size() > layerIndex && tabs != null && layerIndex < tabs.getTabCount()) { - // +1 because the first tab is the ScaleFilterLayer tab - tabs.setSelectedIndex(layerIndex + 1); - } - } - - // ////////////////////////////// - // InfoDisplayListener Methods - // ////////////////////////////// - - /** - * Request to have a URL displayed in a Browser. - * - * @param event InfoDisplayEvent - */ - public void requestURL(InfoDisplayEvent event) { - fireRequestURL(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request to have a message displayed in a dialog window. - * - * @param event InfoDisplayEvent - */ - public void requestMessage(InfoDisplayEvent event) { - fireRequestMessage(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request to have an information line displayed in an application status - * window. - * - * @param event InfoDisplayEvent - */ - public void requestInfoLine(InfoDisplayEvent event) { - fireRequestInfoLine(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request that plain text or html text be displayed in a browser. - * - * @param event InfoDisplayEvent - */ - public void requestBrowserContent(InfoDisplayEvent event) { - fireRequestBrowserContent(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request that the MapBean cursor be set to a certain type. - * - * @param cursor java.awt.Cursor to set over the MapBean. - */ - public void requestCursor(java.awt.Cursor cursor) { - fireRequestCursor(cursor); - } - - /** - * Request a tool tip be shown. - * - * @param event The InfoDisplayEvent containing the text and requestor. - */ - public void requestShowToolTip(InfoDisplayEvent event) { - fireRequestToolTip(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request a tool tip be hidden. - */ - public void requestHideToolTip() { - fireHideToolTip(); - } - - /** - * Try to handle mouse events for the current layer. - */ - public synchronized MapMouseListener getMapMouseListener() { - return this; - } - - /** The current active mouse mode ID. */ - protected String mmID = null; - /** - * Flag to specify that the current layer wants events from the current - * active mouse mode. - */ - protected boolean coolMM = false; - /** - * The current MapMouseListener from the currently appropriate layer. - */ - protected MapMouseListener clmml = null; // current layer map mouse listener - - /** - * Set the coolMM flag, whenever the scale-appropriate layer changes, or if - * the active mouse mode changes. - */ - public synchronized boolean checkMouseMode() { - // check the current MouseMode with the current layer - coolMM = false; - Layer layer = getAppropriateLayer(); - MapMouseListener mml = layer.getMapMouseListener(); - setCurrentLayerMapMouseListener(mml); - if (mml != null) { - String[] mmsl = mml.getMouseModeServiceList(); - for (int i = 0; i < mmsl.length; i++) { - if (mmsl[i].intern() == mmID) { - coolMM = true; - break; - } - } - } - return coolMM; - } - - /** - * Pre-set the MapMouseListener to received events if the current layer - * wants them. - */ - public void setCurrentLayerMapMouseListener(MapMouseListener mml) { - clmml = mml; - } - - /** - * Get the MapMouseListener to received events if the current layer wants - * them. May be null, but coolMM should be false in that case. - */ - public MapMouseListener getCurrentLayerMapMouseListener() { - return clmml; - } - - /** - * Listen for changes to the active mouse mode and for any changes to the - * list of available mouse modes - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - mmID = ((MapMouseMode) evt.getNewValue()).getID().intern(); - checkMouseMode(); - } - } - - /** - * Return a list of the modes that are interesting to the MapMouseListener. - * The source MouseEvents will only get sent to the MapMouseListener if the - * mode is set to one that the listener is interested in. Layers interested - * in receiving events should register for receiving events in "select" - * mode: - * - *
-	 * 
-	 * return new String[] { SelectMouseMode.modeID };
-	 * 
-	 * 
- * - * - * @return String[] of modeID's - * @see com.bbn.openmap.event.NavMouseMode#modeID - * @see com.bbn.openmap.event.SelectMouseMode#modeID - * @see com.bbn.openmap.event.NullMouseMode#modeID - */ - public String[] getMouseModeServiceList() { - HashSet mmsl = new HashSet(); - Iterator it = getLayers().iterator(); - while (it.hasNext()) { - Layer l = (Layer) it.next(); - MapMouseListener mml = l.getMapMouseListener(); - if (mml != null) { - String[] llist = mml.getMouseModeServiceList(); - for (int i = 0; i < llist.length; i++) { - mmsl.add(llist[i].intern()); - } - } - } - String[] rets = new String[mmsl.size()]; - return mmsl.toArray(rets); - } - - // Mouse Listener events - // ////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mousePressed(e); - } else { - return false; - } - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseReleased(e); - } else { - return false; - } - } - - /** - * Invoked when the mouse has been clicked on a component. The listener will - * receive this event if it successfully processed - * mousePressed(), or if no other listener processes the event. - * If the listener successfully processes mouseClicked(), then - * it will receive the next mouseClicked() notifications that - * have a click count greater than one. - *

- * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseClicked(e); - } else { - return false; - } - - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseEntered(e); - } - - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseExited(e); - } - } - - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * The listener will receive these events if it successfully processes - * mousePressed(), or if no other listener processes the event. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseDragged(e); - } else { - return false; - } - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseMoved(e); - } else { - return false; - } - - } - - /** - * Handle a mouse cursor moving without the button being pressed. This event - * is intended to tell the listener that there was a mouse movement, but - * that the event was consumed by another layer. This will allow a mouse - * listener to clean up actions that might have happened because of another - * motion event response. - */ - public void mouseMoved() { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseMoved(); - } - } - - /** - * Method for BeanContextChild interface. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - - for (Layer layer : getLayers()) { - // You don't actually want to add the layer to the - // BeanContext, because then the LayerHandler will pick it - // up and add it to the main list of layers. - - layer.connectToBeanContext(in_bc); - } - - super.setBeanContext(in_bc); - } - - public void dispose() { - try { - for (Layer layer : getLayers()) { - layer.disconnectFromBeanContext(); - } - } catch (PropertyVetoException pve) { - - } - - BeanContext bc = getBeanContext(); - if (bc instanceof MapHandler) { - MapHandler mh = (MapHandler) bc; - findAndUndo(mh.get(MouseDelegator.class)); - } - super.dispose(); - } - - /** - * MapHandler child methods, passing found objects to child layers. - */ - public void findAndInit(Object obj) { - super.findAndInit(obj); - - if (obj instanceof MouseDelegator) { - ((MouseDelegator) obj).addPropertyChangeListener(this); - } - - for (Layer layer : getLayers()) { - layer.findAndInit(obj); - } - } - - /** - * MapHandler child methods, passing removed objects to child layers. - */ - public void findAndUndo(Object obj) { - super.findAndUndo(obj); - - if (obj == null) { - return; - } - - if (obj instanceof MouseDelegator) { - ((MouseDelegator) obj).removePropertyChangeListener(this); - } - - for (Layer layer : getLayers()) { - layer.findAndUndo(obj); - } - } - - /** - * @return the aggressiveLayerCleanup - */ - public boolean isAggressiveLayerCleanup() { - return aggressiveLayerCleanup; - } - - /** - * @param aggressiveLayerCleanup the aggressiveLayerCleanup to set - */ - public void setAggressiveLayerCleanup(boolean aggressiveLayerCleanup) { - this.aggressiveLayerCleanup = aggressiveLayerCleanup; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/SinkLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/SinkLayer.java deleted file mode 100644 index 09044ebf9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/SinkLayer.java +++ /dev/null @@ -1,57 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/SinkLayer.java,v $ -// $RCSfile: SinkLayer.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:53 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.ProjectionEvent; - -/** - * SinkLayer is a Layer which does nothing. This can be used primarily - * as a placeholder. - */ -public class SinkLayer extends Layer { - - // the shared instance - private static SinkLayer sharedInstance; - - /** - * Get a shared instance of the SinkLayer. - * - * @return SinkLayer shared instance - */ - public final static SinkLayer getSharedInstance() { - if (sharedInstance == null) - sharedInstance = new SinkLayer(); - return sharedInstance; - } - - // cannot construct - private SinkLayer() {} - - /** - * ProjectionListener interface method. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/UTMGridLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/UTMGridLayer.java deleted file mode 100644 index e54010490..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/UTMGridLayer.java +++ /dev/null @@ -1,957 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/UTMGridLayer.java,v $ -// $RCSfile: UTMGridLayer.java,v $ -// $Revision: 1.21 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Paint; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.Iterator; -import java.util.Properties; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColorChooser; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.geom.BasicGeometry; -import com.bbn.openmap.omGraphics.geom.PolygonGeometry; -import com.bbn.openmap.omGraphics.geom.PolylineGeometry; -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.MGRSPoint; -import com.bbn.openmap.proj.coords.UTMPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * The UTMGridLayer renders UTM Zone areas, and renders a grid marking - * equal-distance areas around the center of the current projection. This - * distance grid only extends east-west for 500km in both directions from the - * center of the current zone because that is the extent of accuracy for those - * measurements - after that, you get too far away from the central meridian for - * the current UTM zone. - *

- * - * Currently, this layer only draws 100km distance squares. Updates on the way. - * The layer has the following properties that may be set: - *

- * - *

- * 
- * 
- *    # Turn zone area labels on when zoomed in closer than 1:33M (true
- *    # is default)
- *    showZones=true
- *    showLabels=true
- *    # Color for UTM Zone area boundaries
- *    utmGridColor=hex AARRGGBB value
- *    # Color for the distance area grid lines
- *    distanceGridColor= hex AARRGGBB value
- *    labelCutoffScale=scale to start showing labels, default is 33000000
- *    show100KmGrid=false
- *    utmGridColor
- *    distanceGridColor
- *    distanceGridResolution=0 (not shown by default, 1 = 10000 meter grid, 5 is 1 meter grid)
- *    mgrsLabels=false
- * 
- * 
- */ -public class UTMGridLayer extends OMGraphicHandlerLayer { - - protected boolean UTM_DEBUG = false; - protected boolean UTM_DEBUG_VERBOSE = false; - - public final static int INTERVAL_100K = 100000; - public final static float DEFAULT_UTM_LABEL_CUTOFF_SCALE = 33000000; - - protected boolean showZones = true; - protected boolean showLabels = true; - protected float labelCutoffScale = DEFAULT_UTM_LABEL_CUTOFF_SCALE; - protected boolean show100kGrid = false; - protected boolean labelsAsMGRS = false; - /** - * Resolution should be MGRS accuracy, 0 for none, 1-5 otherwise, where 1 = - * 10000 meter grid, 5 is 1 meter grid. - */ - protected int distanceGridResolution = 0; - protected Paint utmGridPaint = Color.black; - protected Paint distanceGridPaint = Color.black; - - /** - * Used to hold OMText UTM zone labels. - */ - protected QuadTree labelTree; - /** - * Used for UTM zone labels. - */ - protected OMGraphicList labelList; - /** - * The vertical list of OMLines used for UTM zones. - */ - protected OMGeometryList verticalList; - /** - * The horizontal list of OMLines used for UTM zones. - */ - protected OMGeometryList horizontalList; - - public final static String ShowLabelsProperty = "showLabels"; - public final static String ShowZonesProperty = "showZones"; - public final static String LabelCutoffScaleProperty = "labelCutoffScale"; - public final static String Show100kGridProperty = "show100KmGrid"; - public final static String UTMGridColorProperty = "utmGridColor"; - public final static String DistanceGridColorProperty = "distanceGridColor"; - public final static String DistanceGridResolutionProperty = "distanceGridResolution"; - public final static String LabelsAsMGRSProperty = "mgrsLabels"; - - public final static String LABEL_ATTRIBUTE = "label"; - - public UTMGridLayer() { - UTM_DEBUG = Debug.debugging("utmgrid"); - UTM_DEBUG_VERBOSE = Debug.debugging("utmgrid_verbose"); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - } - - protected OMGeometryList createUTMZoneVerticalLines() { - - OMGeometryList verticalList = new OMGeometryList(); - double[] points = null; - - for (double lon = -180; lon < 180; lon += 6) { - if (lon == 6) { - points = new double[] { 56f, lon, -80f, lon }; - } else if (lon > 6 && lon < 42) { - points = new double[] { 72f, lon, -80f, lon }; - } else { - points = new double[] { 84f, lon, -80f, lon }; - } - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - } - - points = new double[] { 72f, 6f, 64f, 6f }; - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - - points = new double[] { 64f, 3f, 56f, 3f }; - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - - points = new double[] { 84f, 9f, 72f, 9f }; - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - - points = new double[] { 84f, 21f, 72f, 21f }; - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - - points = new double[] { 84f, 33f, 72f, 33f }; - verticalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE)); - - verticalList.setLinePaint(utmGridPaint); - - return verticalList; - } - - protected OMGeometryList createUTMZoneHorizontalLines() { - OMGeometryList horizontalList = new OMGeometryList(); - double[] points = null; - - for (double lat = -80f; lat <= 72f; lat += 8f) { - points = new double[] { lat, -180f, lat, -90f, lat, 0f, lat, 90f, lat, 180f }; - horizontalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB)); - } - - points = new double[] { 84f, -180f, 84f, -90f, 84f, 0f, 84f, 90f, 84f, 180f }; - horizontalList.add(new PolylineGeometry.LL(points, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB)); - - horizontalList.setLinePaint(utmGridPaint); - - return horizontalList; - } - - protected QuadTree createUTMZoneLabels() { - - QuadTree labelTree = new QuadTree(); - - // Need to use MGRSPoint to get MGRS zone letters, the UTM - // zone letters are N and S for the hemisphere, which isn't - // very interesting. - UTMPoint utm = new MGRSPoint(); - LatLonPoint llp = new LatLonPoint.Double(); - float latitude; - float longitude; - - for (int lat = -80; lat <= 72; lat += 8) { - for (int lon = -180; lon < 180; lon += 6) { - - latitude = (float) lat; - longitude = (float) lon; - - if (lat == 56 && lon == 6) { - longitude = 3f; - } else if (lat == 72 && (lon > 0 && lon < 42)) { - continue; - } - llp.setLatLon(latitude, longitude); - addLabel(llp, UTMPoint.LLtoUTM(llp, utm), labelTree); - } - } - - latitude = 72f; - llp.setLatLon(latitude, 9f); - addLabel(llp, UTMPoint.LLtoUTM(llp, utm), labelTree); - llp.setLongitude(21f); - addLabel(llp, UTMPoint.LLtoUTM(llp, utm), labelTree); - llp.setLongitude(33f); - addLabel(llp, UTMPoint.LLtoUTM(llp, utm), labelTree); - - return labelTree; - } - - protected QuadTree createMGRSZoneLabels() { - - QuadTree labelTree = new QuadTree(); - - // Need to use MGRSPoint to get MGRS zone letters, the UTM - // zone letters are N and S for the hemisphere, which isn't - // very interesting. - MGRSPoint mgrs = new MGRSPoint(); - LatLonPoint llp = new LatLonPoint.Double(); - float latitude; - float longitude; - - for (int lat = -80; lat <= 72; lat += 8) { - for (int lon = -180; lon < 180; lon += 6) { - - latitude = (float) lat; - longitude = (float) lon; - - if (lat == 56 && lon == 6) { - longitude = 3f; - } else if (lat == 72 && (lon > 0 && lon < 42)) { - continue; - } - llp.setLatLon(latitude, longitude); - addLabel(llp, MGRSPoint.LLtoMGRS(llp, mgrs), labelTree); - } - } - - latitude = 72f; - llp.setLatLon(latitude, 9f); - addLabel(llp, MGRSPoint.LLtoMGRS(llp, mgrs), labelTree); - llp.setLongitude(21f); - addLabel(llp, MGRSPoint.LLtoMGRS(llp, mgrs), labelTree); - llp.setLongitude(33f); - addLabel(llp, MGRSPoint.LLtoMGRS(llp, mgrs), labelTree); - - return labelTree; - } - - protected void addLabel(LatLonPoint llp, UTMPoint utm, QuadTree labelTree) { - double latitude = llp.getY(); - double longitude = llp.getX(); - labelTree.put(latitude, longitude, new OMText(latitude, longitude, 2, -2, utm.zone_number - + "" + utm.zone_letter, OMText.JUSTIFY_LEFT)); - } - - /** - * Called to create 100km distance grid lines. Was originally designed to - * accept different gridLineInterval distances, but has only been debugged - * and tested for 100000. - * - * @param utm the UTMPoint of the center of the area to create lines for. - */ - protected OMGraphicList createEquiDistanceLines(UTMPoint utm, int gridLineInterval) { - - OMGraphicList list = new OMGraphicList(); - - // Used to calculate the endpoints of the horizontal lines. - UTMPoint utm1 = new UTMPoint(utm); - UTMPoint utm2 = new UTMPoint(utm); - LatLonPoint point1 = new LatLonPoint.Double(); - LatLonPoint point2 = new LatLonPoint.Double(); - - // Used to calculate the pieces of the vertical lines. - UTMPoint utmp = new UTMPoint(utm); - LatLonPoint llp = new LatLonPoint.Double(); - - int i; - OMLine line; - BasicGeometry poly; - - double lat2; - int endNorthing = (int) Math.floor(utm.northing / INTERVAL_100K) + 10; - int startNorthing = (int) Math.floor(utm.northing / INTERVAL_100K) - 10; - - int numVertLines = 9; - int numHorLines = endNorthing - startNorthing; - - double[][] vertPoints = new double[numVertLines][numHorLines * 2]; - - if (UTM_DEBUG_VERBOSE) { - Debug.output("Array is [" + vertPoints.length + "][" + vertPoints[0].length + "]"); - } - - int coordCount = 0; - boolean doPolys = true; - - utm1.easting = INTERVAL_100K; - utm2.easting = 9 * INTERVAL_100K; - - // Horizontal lines - for (i = startNorthing; i < endNorthing; i++) { - utm1.northing = (float) i * gridLineInterval; - utm2.northing = utm1.northing; - utmp.northing = utm1.northing; - - if (doPolys) { - for (int j = 0; j < numVertLines; j++) { - utmp.easting = (float) (j + 1) * gridLineInterval; - llp = utmp.toLatLonPoint(Ellipsoid.WGS_84, llp); - - vertPoints[j][coordCount] = llp.getY(); - vertPoints[j][coordCount + 1] = llp.getX(); - - if (UTM_DEBUG_VERBOSE) { - Debug.output("for vline " + j + ", point " + i + ", easting: " - + utmp.easting + ", northing: " + utmp.northing + ", lat:" - + vertPoints[j][coordCount] + ", lon:" - + vertPoints[j][coordCount + 1]); - } - } - coordCount += 2; - } - - point1 = utm1.toLatLonPoint(Ellipsoid.WGS_84, point1); - point2 = utm2.toLatLonPoint(Ellipsoid.WGS_84, point2); - - lat2 = point1.getLatitude(); - - if (lat2 < 84f) { - line = new OMLine(point1.getY(), point1.getX(), point2.getY(), point2.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - line.setLinePaint(distanceGridPaint); - list.add(line); - } - } - - if (doPolys) { - OMGeometryList polys = new OMGeometryList(); - for (i = 0; i < vertPoints.length; i++) { - if (UTM_DEBUG_VERBOSE) { - for (int k = 0; k < vertPoints[i].length; k += 2) { - System.out.println(" for poly " + i + ": lat = " + vertPoints[i][k] - + ", lon = " + vertPoints[i][k + 1]); - } - } - poly = new PolylineGeometry.LL(vertPoints[i], OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE); - polys.add(poly); - } - polys.setLinePaint(distanceGridPaint); - list.add(polys); - } else { - - // This doesn't seem to calculate the right - // lines, although it looks like it should. - - if (UTM_DEBUG) { - Debug.output("Doing vertical lines"); - } - - utm1.northing = startNorthing; - utm2.northing = endNorthing; - - // Vertical lines - for (i = 1; i <= 9; i++) { - utm1.easting = i * 100000f; - utm2.easting = i * 100000f; - - point1 = utm1.toLatLonPoint(Ellipsoid.WGS_84, point1); - point2 = utm2.toLatLonPoint(Ellipsoid.WGS_84, point2); - - line = new OMLine(point1.getY(), point1.getX(), point2.getY(), point2.getX(), OMGraphic.LINETYPE_GREATCIRCLE); - line.setLinePaint(distanceGridPaint); - list.add(line); - } - } - - return list; - } - - /** - * Create a list of rectangles representing equal areas of MGRS coordinates - * around a lat/lon location. The rectangles are laid out on the MGRS grid, - * their size determined by the accuracy limitation given, which reflects - * how many digits are provided in a MGRS coordinate. Uses WGS 84 ellipsoid. - * - * @param llp the lat/lon point of concern. - * @param accuracy the number of digits for northing and easting values of a - * MGRS coordinate, which implicitly translates to meters - 5 (1 - * meter) to 1 (10,000 meter). - * @param numRects the number of rectangles in each direction from the llp - * to create. - */ - protected OMGeometryList createMGRSRectangles(LatLonPoint llp, int accuracy, int numRects) { - return createMGRSRectangles(llp, accuracy, numRects, Ellipsoid.WGS_84); - } - - /** - * Create a list of rectangles representing equal areas of MGRS coordinates - * around a lat/lon location. The rectangles are laid out on the MGRS grid, - * their size determined by the accuracy limitation given, which reflects - * how many digits are provided in a MGRS coordinate. - * - * @param llp the lat/lon point of concern. - * @param accuracy the number of digits for northing and easting values of a - * MGRS coordinate, which implicitly translates to meters - 5 (1 - * meter) to 1 (10,000 meter). - * @param numRects the number of rectangles in each direction from the llp - * to create. - * @param ellipsoid the ellipsoid to use. - */ - protected OMGeometryList createMGRSRectangles(LatLonPoint llp, int accuracy, int numRects, - Ellipsoid ellipsoid) { - MGRSPoint mgrs = new MGRSPoint(); - mgrs.setAccuracy(accuracy); - MGRSPoint.LLtoMGRS(llp, ellipsoid, mgrs); - - double accuracyBonus = 100000 / Math.pow(10, accuracy); - - OMGeometryList list = new OMGeometryList(); - - for (double i = -numRects * accuracyBonus; i < numRects * accuracyBonus; i += accuracyBonus) { - for (double j = -numRects * accuracyBonus; j < numRects * accuracyBonus; j += accuracyBonus) { - if (Debug.debugging("utmdistancegrid")) { - System.out.print("."); - } - list.add(createMGRSRectangle(mgrs, i, j, accuracyBonus, ellipsoid)); - } - if (Debug.debugging("utmdistancegrid")) { - System.out.println(); - } - } - - return list; - } - - /** - * Create a polygon representing an equi-distant area, at a meters offset - * with a meters interval. - * - * @param mgrsBasePoint the center point of interest that has been - * normalized for the units of the rectangle (meters, km, etc). - * @param voffset vertical offset in meters, normalized for units, for - * entire polygon. - * @param hoffset horizontal offset in meters, normalized for units, for - * entire polygon. - * @param interval edge length of rectangle polygon in meters, normalized - * for units. - * @param ellipsoid Ellipsoid for coordinate translation. - */ - protected OMGeometry createMGRSRectangle(MGRSPoint mgrsBasePoint, double voffset, - double hoffset, double interval, Ellipsoid ellipsoid) { - - double[] llpoints = new double[10]; - - double easting = mgrsBasePoint.easting + hoffset; - double northing = mgrsBasePoint.northing + voffset; - int zone_number = mgrsBasePoint.zone_number; - char zone_letter = mgrsBasePoint.zone_letter; - - LatLonPoint llp1 = new LatLonPoint.Double(); - llp1 = MGRSPoint.MGRStoLL(ellipsoid, northing, easting, zone_number, zone_letter, llp1); - llpoints[0] = llp1.getY(); - llpoints[1] = llp1.getX(); - llpoints[8] = llp1.getY(); - llpoints[9] = llp1.getX(); - - MGRSPoint.MGRStoLL(ellipsoid, northing, easting + interval, zone_number, zone_letter, llp1); - llpoints[2] = llp1.getY(); - llpoints[3] = llp1.getX(); - - MGRSPoint.MGRStoLL(ellipsoid, northing + interval, easting + interval, zone_number, zone_letter, llp1); - llpoints[4] = llp1.getY(); - llpoints[5] = llp1.getX(); - - MGRSPoint.MGRStoLL(ellipsoid, northing + interval, easting, zone_number, zone_letter, llp1); - llpoints[6] = llp1.getY(); - llpoints[7] = llp1.getX(); - - MGRSPoint mgrs = new MGRSPoint(northing, easting, zone_number, zone_letter); - mgrs.resolve(mgrsBasePoint.getAccuracy()); - // MGRSPoint.MGRStoLL(mgrs, ellipsoid, llp1); - String mgrsString = mgrs.getMGRS(); - - if (Debug.debugging("utmgriddetail")) - Debug.output(" - assigning " + mgrsString + " to poly with " + mgrs.getAccuracy()); - - PolygonGeometry poly = new PolygonGeometry.LL(llpoints, OMGraphic.DECIMAL_DEGREES, (interval <= 1000 ? OMGraphic.LINETYPE_STRAIGHT - : OMGraphic.LINETYPE_GREATCIRCLE)); - poly.putAttribute(LABEL_ATTRIBUTE, mgrsString); - return poly; - } - - /** - * The prepare is the main call when the projection changes. - * - * @return OMGraphicList for rendering for the current projection. - */ - public OMGraphicList prepare() { - - OMGraphicList list = new OMGraphicList(); - Projection p = getProjection(); - - if (verticalList == null) { - verticalList = createUTMZoneVerticalLines(); - horizontalList = createUTMZoneHorizontalLines(); - if (labelsAsMGRS) { - labelTree = createMGRSZoneLabels(); - } else { - labelTree = createUTMZoneLabels(); - } - } - - if (showZones) { - list.add(verticalList); - list.add(horizontalList); - } - - LatLonPoint center = p.getCenter(new LatLonPoint.Double()); - UTMPoint utm = new UTMPoint(center); - - if (show100kGrid) { - Debug.message("utmgrid", "Creating 100k distance lines..."); - - OMGraphicList hunKLines = createEquiDistanceLines(utm, 100000); - list.add(hunKLines); - } - - if (distanceGridResolution > 0) { - Debug.message("utmgrid", "Creating distance lines..."); - - double decisionAid = 100000f / Math.pow(10, distanceGridResolution); - double dglc = 30f * decisionAid; // distance grid label - // cutoff - // Debug.output("Basing decision to display labels on " + - // dglc); - - int numberBasedForScale = (int) (p.getScale() / (2 * decisionAid)); - if (numberBasedForScale > 10) { - numberBasedForScale = 10; - } - // Debug.output(numberBasedForScale + ""); - - OMGeometryList geoList = createMGRSRectangles(center, distanceGridResolution, numberBasedForScale); - - if (showLabels && p.getScale() <= dglc) { - Debug.message("utmgrid", "Creating labels for distance lines ..."); - - OMGraphicList textList = new OMGraphicList(); - LatLonPoint llp = new LatLonPoint.Double(); - Point point = new Point(); - Iterator it = geoList.iterator(); - while (it.hasNext()) { - PolygonGeometry.LL pll = (PolygonGeometry.LL) it.next(); - String labelString = (String) pll.getAttribute(LABEL_ATTRIBUTE); - if (labelString == null) { - continue; - } - double[] ll = pll.getLatLonArray(); - llp.setLatLon(ll[0], ll[1], true); - - p.forward(llp, point); - - double x = point.getX(); - double y = point.getY(); - int buffer = 20; - - // Lame attempt of testing whether the label is - // on-screen - if ((x > -buffer || x < p.getWidth() + buffer) - && (y > -buffer || y < p.getHeight() + buffer)) { - - OMText label = new OMText(llp.getY(), llp.getX(), 4, -4, labelString, OMText.JUSTIFY_LEFT); - label.setLinePaint(distanceGridPaint); - textList.add(label); - } - } - list.add(textList); - } - - geoList.setLinePaint(distanceGridPaint); - list.add(geoList); - } - - if (labelList != null) { - labelList.clear(); - } else { - labelList = new OMGraphicList(); - } - - if (showLabels && p.getScale() <= labelCutoffScale) { - Debug.message("utmgrid", "Creating labels for map..."); - Point2D ul = p.getUpperLeft(); - Point2D lr = p.getLowerRight(); - - Collection labels = labelTree.get(ul.getY(), ul.getX(), lr.getY(), lr.getX()); - - labelList.addAll(labels); - labelList.setLinePaint(getUTMGridPaint()); - list.add(labelList); - } - - Debug.message("utmgrid", "Generating OMGraphics..."); - list.generate(p); - Debug.message("utmgrid", "Done."); - return list; - } // end getRectangle - - public Component getGUI() { - JPanel panel = new JPanel(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - panel.setLayout(gridbag); - - JCheckBox setZonesButton = new JCheckBox(i18n.get(UTMGridLayer.class, "setZonesButton", "Show UTM Zone Grid"), showZones); - setZonesButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox button = (JCheckBox) ae.getSource(); - showZones = button.isSelected(); - doPrepare(); - } - }); - c.gridy = 0; - c.anchor = GridBagConstraints.WEST; - gridbag.setConstraints(setZonesButton, c); - panel.add(setZonesButton); - - JCheckBox set100kGridButton = new JCheckBox(i18n.get(UTMGridLayer.class, "set100kGridButton", "Show 100Km Distance Grid"), show100kGrid); - set100kGridButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox button = (JCheckBox) ae.getSource(); - show100kGrid = button.isSelected(); - doPrepare(); - } - }); - - c.gridy = 1; - gridbag.setConstraints(set100kGridButton, c); - panel.add(set100kGridButton); - - JCheckBox setLabelsButton = new JCheckBox(i18n.get(UTMGridLayer.class, "setLabelsButton", "Show Zone Labels"), showLabels); - setLabelsButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox button = (JCheckBox) ae.getSource(); - showLabels = button.isSelected(); - doPrepare(); - } - }); - c.gridy = 2; - gridbag.setConstraints(setLabelsButton, c); - panel.add(setLabelsButton); - - JPanel resPanel = PaletteHelper.createPaletteJPanel(i18n.get(UTMGridLayer.class, "resPanel", "Distance Grid Units")); - - String[] resStrings = { i18n.get(UTMGridLayer.class, "resStrings.noGrid", " No Grid "), - i18n.get(UTMGridLayer.class, "resStrings.10000m", " 10,000 meter "), - i18n.get(UTMGridLayer.class, "resStrings.1000m", " 1000 meter "), - i18n.get(UTMGridLayer.class, "resStrings.100m", " 100 meter "), - i18n.get(UTMGridLayer.class, "resStrings.10m", " 10 meter "), - i18n.get(UTMGridLayer.class, "resStrings.1m", " 1 meter ") }; - - JComboBox resList = new JComboBox(resStrings); - resList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - setDistanceGridResolution(jcb.getSelectedIndex()); - doPrepare(); - } - }); - resList.setSelectedIndex(getDistanceGridResolution()); - - resPanel.add(resList); - - c.gridy = 3; - c.anchor = GridBagConstraints.CENTER; - gridbag.setConstraints(resPanel, c); - panel.add(resPanel); - - JButton utmGridColorButton = new JButton(DrawingAttributes.getIconForPaint(getUTMGridPaint(), true)); - utmGridColorButton.setContentAreaFilled(false); - utmGridColorButton.setBorder(null); - utmGridColorButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - Color tmpPaint = getNewPaint((Component) ae.getSource(), i18n.get(UTMGridLayer.class, "utmGridColorChooser", "Choose UTM Grid Color"), (Color) getUTMGridPaint()); - if (tmpPaint != null) { - setUTMGridPaint(tmpPaint); - ((JButton) ae.getSource()).setIcon(DrawingAttributes.getIconForPaint(tmpPaint, true)); - doPrepare(); - } - } - }); - - JLabel utmGridLabel = new JLabel(i18n.get(UTMGridLayer.class, "utmGridColorButton", "Set UTM Grid Color")); - - JPanel utmGridPanel = new JPanel(); - utmGridPanel.add(utmGridColorButton); - utmGridPanel.add(utmGridLabel); - - c.gridy = 4; - c.anchor = GridBagConstraints.WEST; - gridbag.setConstraints(utmGridPanel, c); - panel.add(utmGridPanel); - - JButton distGridColorButton = new JButton(DrawingAttributes.getIconForPaint(getDistanceGridPaint(), true)); - distGridColorButton.setContentAreaFilled(false); - distGridColorButton.setBorder(null); - distGridColorButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - Color tmpPaint = getNewPaint((Component) ae.getSource(), i18n.get(UTMGridLayer.class, "distanceGridColorChooser", "Choose Distance Grid Color"), (Color) getDistanceGridPaint()); - if (tmpPaint != null) { - setDistanceGridPaint(tmpPaint); - ((JButton) ae.getSource()).setIcon(DrawingAttributes.getIconForPaint(tmpPaint, true)); - doPrepare(); - } - } - }); - JLabel distanceGridLabel = new JLabel(i18n.get(UTMGridLayer.class, "distGridColorButton", "Set Distance Grid Color")); - JPanel distGridPanel = new JPanel(); - distGridPanel.add(distGridColorButton); - distGridPanel.add(distanceGridLabel); - c.gridy = 5; - gridbag.setConstraints(distGridPanel, c); - panel.add(distGridPanel); - - return panel; - } - - /** - * A convenience method to get a color from a JColorChooser. Null will be - * returned if the JColorChooser lock is in place, or if something else is - * done where the JColorChooser would normally return null. - * - * @param source the source component for the JColorChooser. - * @param title the String to label the JColorChooser window. - * @param startingColor the color to give to the JColorChooser to start - * with. Returned if the cancel button is pressed. - * @return Color chosen from the JColorChooser, null if lock for chooser - * can't be acquired. - */ - protected Color getNewPaint(Component source, String title, Color startingColor) { - Color newPaint = null; - if (getLock()) { - newPaint = OMColorChooser.showDialog(source, title, startingColor); - releaseLock(); - } - return newPaint; - } - - /** - * A lock to use to limit the number of JColorChoosers that can pop up for a - * given DrawingAttributes GUI. - */ - private boolean colorChooserLock = false; - - /** - * Get the lock to use a JColorChooser. Returns true if you got the lock, - * false if you didn't. - */ - protected synchronized boolean getLock() { - if (colorChooserLock == false) { - colorChooserLock = true; - return colorChooserLock; - } else { - return false; - } - } - - /** - * Release the lock on the JColorChooser. - */ - protected synchronized void releaseLock() { - colorChooserLock = false; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - showLabels = PropUtils.booleanFromProperties(props, prefix + ShowLabelsProperty, showLabels); - showZones = PropUtils.booleanFromProperties(props, prefix + ShowZonesProperty, showZones); - show100kGrid = PropUtils.booleanFromProperties(props, prefix + Show100kGridProperty, show100kGrid); - labelCutoffScale = PropUtils.floatFromProperties(props, prefix + LabelCutoffScaleProperty, labelCutoffScale); - utmGridPaint = PropUtils.parseColorFromProperties(props, prefix + UTMGridColorProperty, utmGridPaint); - distanceGridPaint = PropUtils.parseColorFromProperties(props, prefix - + DistanceGridColorProperty, distanceGridPaint); - setDistanceGridResolution(PropUtils.intFromProperties(props, prefix - + DistanceGridResolutionProperty, distanceGridResolution)); - labelsAsMGRS = PropUtils.booleanFromProperties(props, prefix + LabelsAsMGRSProperty, labelsAsMGRS); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + ShowLabelsProperty, Boolean.toString(showLabels)); - props.put(prefix + ShowZonesProperty, new Boolean(showZones).toString()); - props.put(prefix + LabelCutoffScaleProperty, Float.toString(labelCutoffScale)); - props.put(prefix + Show100kGridProperty, Boolean.toString(show100kGrid)); - props.put(prefix + UTMGridColorProperty, Integer.toHexString(((Color) utmGridPaint).getRGB())); - props.put(prefix + DistanceGridColorProperty, Integer.toHexString(((Color) distanceGridPaint).getRGB())); - props.put(prefix + DistanceGridResolutionProperty, Integer.toString(distanceGridResolution)); - props.put(prefix + LabelsAsMGRSProperty, Boolean.toString(labelsAsMGRS)); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String interString; - - interString = i18n.get(UTMGridLayer.class, ShowZonesProperty, I18n.TOOLTIP, "Show UTM Zone Grid Lines."); - props.put(ShowZonesProperty, interString); - interString = i18n.get(UTMGridLayer.class, ShowZonesProperty, ShowZonesProperty); - props.put(ShowZonesProperty + LabelEditorProperty, interString); - props.put(ShowZonesProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(UTMGridLayer.class, UTMGridColorProperty, I18n.TOOLTIP, "Color for UTM Zone Grid lines."); - props.put(UTMGridColorProperty, interString); - interString = i18n.get(UTMGridLayer.class, UTMGridColorProperty, UTMGridColorProperty); - props.put(UTMGridColorProperty + LabelEditorProperty, interString); - props.put(UTMGridColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(UTMGridLayer.class, ShowLabelsProperty, I18n.TOOLTIP, "Show Labels for Grid Lines"); - props.put(ShowLabelsProperty, interString); - interString = i18n.get(UTMGridLayer.class, ShowLabelsProperty, ShowLabelsProperty); - props.put(ShowLabelsProperty + LabelEditorProperty, interString); - props.put(ShowLabelsProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(UTMGridLayer.class, Show100kGridProperty, I18n.TOOLTIP, "Show 100Km Distance Grid Lines"); - props.put(Show100kGridProperty, interString); - interString = i18n.get(UTMGridLayer.class, Show100kGridProperty, Show100kGridProperty); - props.put(Show100kGridProperty + LabelEditorProperty, interString); - props.put(Show100kGridProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(UTMGridLayer.class, DistanceGridColorProperty, I18n.TOOLTIP, "Color for Equal-Distance Grid Lines."); - props.put(DistanceGridColorProperty, interString); - interString = i18n.get(UTMGridLayer.class, DistanceGridColorProperty, DistanceGridColorProperty); - props.put(DistanceGridColorProperty + LabelEditorProperty, interString); - props.put(DistanceGridColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(UTMGridLayer.class, DistanceGridResolutionProperty, I18n.TOOLTIP, "Meter Resolution for Distance Grid Lines (0-5)"); - props.put(DistanceGridResolutionProperty, interString); - interString = i18n.get(UTMGridLayer.class, DistanceGridResolutionProperty, DistanceGridResolutionProperty); - props.put(DistanceGridResolutionProperty + LabelEditorProperty, interString); - - PropUtils.setI18NPropertyInfo(i18n, props, UTMGridLayer.class, LabelsAsMGRSProperty, "Labels as MGRS", "Flag to display labels in MGRS notation, or UTM.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - props.put(initPropertiesProperty, ShowZonesProperty + " " + UTMGridColorProperty + " " - + Show100kGridProperty + " " + ShowLabelsProperty + " " - + DistanceGridResolutionProperty + " " + DistanceGridColorProperty + " " - + LabelsAsMGRSProperty); - return props; - } - - public void setShowZones(boolean value) { - showZones = value; - } - - public boolean isShowZones() { - return showZones; - } - - public void setShowLabels(boolean value) { - showLabels = value; - } - - public boolean isShowLabels() { - return showLabels; - } - - public void setLabelCutoffScale(float value) { - labelCutoffScale = value; - } - - public float getLabelCutoffScale() { - return labelCutoffScale; - } - - public void setShow100kGrid(boolean value) { - show100kGrid = value; - } - - public boolean isShow100kGrid() { - return show100kGrid; - } - - /** - * Resolution should be MGRS accuracy, 0 for none, 1-5 otherwise, where 1 = - * 10000 meter grid, 5 is 1 meter grid. - */ - public void setDistanceGridResolution(int value) { - distanceGridResolution = value; - if (distanceGridResolution < 0 || distanceGridResolution > MGRSPoint.ACCURACY_1_METER) { - distanceGridResolution = 0; - } - } - - public int getDistanceGridResolution() { - return distanceGridResolution; - } - - public void setUTMGridPaint(Paint value) { - utmGridPaint = value; - - if (verticalList != null) { - verticalList.setLinePaint(getUTMGridPaint()); - horizontalList.setLinePaint(getUTMGridPaint()); - } - } - - public Paint getUTMGridPaint() { - return utmGridPaint; - } - - public void setDistanceGridPaint(Paint value) { - distanceGridPaint = value; - } - - public Paint getDistanceGridPaint() { - return distanceGridPaint; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/asrp/ASRPLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/asrp/ASRPLayer.java deleted file mode 100644 index b62ee5770..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/asrp/ASRPLayer.java +++ /dev/null @@ -1,419 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/asrp/ASRPLayer.java,v $ -// $RCSfile: ASRPLayer.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/08/25 16:04:40 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.asrp; - -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.util.Properties; - -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.dataAccess.asrp.ASRPConstants; -import com.bbn.openmap.dataAccess.asrp.ASRPDirectory; -import com.bbn.openmap.dataAccess.asrp.ASRPDirectoryHandler; -import com.bbn.openmap.dataAccess.asrp.TransmittalHeaderFile; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The ASRPLayer displays ASRP data, which is an international, - * seamless imagery format, kind of like CADRG. This data must be - * displayed on either LLYX or CADRG projections, although the layer - * will display coverage rectangles over areas with imagery for - * projections that are not the right type, or if the user should zoom - * in or out to view the images. The properties for this layer are: - *

- * - *

- *  
- *   
- *   
- *    # Paths to TRANSH01.THF files that organize sets of ASRP image directories.
- *    asrpLayer.thf=thf1;thf2
- *    # Alternatively, paths to ASRP directories can be used if the thf property is undefined.
- *    asrpLayer.asrpDirs=dir1;dir2
- *    # Flag to show coverages when images can't be displayed.
- *    asrpLayer.showCoverage
- *    # Lastly, the suite of DrawingAttributes properties can be provided to set 
- *    # the parameters for the coverage rectangles. See DrawingAttributes for more options.
- *    asrpLayer.lineColor=FFFF0000
- *    asrpLayer.fillColor=FFFF0000
- *   
- *    
- *   
- * 
- */ -public class ASRPLayer extends OMGraphicHandlerLayer implements - DataBoundsProvider, ASRPConstants { - - protected ASRPDirectoryHandler asrpHandler; - protected String[] thfPaths = null; - protected String[] asrpDirs = null; - - protected boolean showCoverage = true; - - protected DrawingAttributes coverageDrawingAttributes; - - /** - * Property describing a flag that can be set to show where image - * files are when they cannot be displayed or aren't showing up. - */ - public final static String ShowCoverageProperty = "showCoverage"; - /** - * The ASRPDirectory can be used to view the images from ASRP - * directories containing GEN, GER, SOU, QAL and IMG files. This - * property is only checked if the THFProperty is not set - * (asrpDir). Should contain a list of semi-colon separated paths - * to ASRP directories containing the files specified above. - */ - public final static String ASRPDirectoryProperty = "asrpDirs"; - /** - * A semi-colon separated set of paths to TRANSH01.THF files - * containing information about ASRP images stored in directories - * next to the TRANSH01.THF file. - */ - public final static String THFProperty = "thf"; - - public ASRPLayer() { - setName("ASRP"); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - coverageDrawingAttributes = DrawingAttributes.getDefaultClone(); - } - - public synchronized OMGraphicList prepare() { - - OMGraphicList ret = null; - Projection proj = getProjection(); - - if (proj == null) { - return ret; - } - - try { - - if (asrpHandler == null) { - asrpHandler = initialize(); - } - - if (!(proj instanceof EqualArc)) { - fireRequestInfoLine("ASRP data requires an Equal Arc projection (CADRG/LLXY)"); - } else { - ret = asrpHandler.getImagesForProjection((EqualArc) proj); - } - - if (ret == null && showCoverage) { - ret = asrpHandler.getCoverageBounds(proj, - coverageDrawingAttributes); - } - - } catch (IOException ioe) { - Debug.error("ASRPLayer(" + getName() - + ") caught exception fetching images:\n" - + ioe.getMessage()); - } - - return ret; - } - - protected ASRPDirectoryHandler initialize() { - ASRPDirectoryHandler asrpDirHandler = new ASRPDirectoryHandler(); - int i; - if (thfPaths != null) { - for (i = 0; i < thfPaths.length; i++) { - try { - asrpDirHandler.add(new TransmittalHeaderFile(thfPaths[i])); - } catch (IOException ioe) { - Debug.error("ASRPLayer (" + getName() - + ") caught exception trying to read " - + ASRPConstants.TRANS + ": " + ioe.getMessage()); - } - } - } else if (asrpDirs != null) { - for (i = 0; i < asrpDirs.length; i++) { - asrpDirHandler.add(new ASRPDirectory(asrpDirs[i])); - } - } - - return asrpDirHandler; - } - - public ASRPDirectoryHandler getASRPHandler() { - return asrpHandler; - } - - public void setASRPHandler(ASRPDirectoryHandler asrpHandlerIn) { - asrpHandler = asrpHandlerIn; - } - - /** - * Set the paths used by the layer. Clears out the ASRP List - * currently set. The contents of the provided paths will be - * checked to see if they are paths to TRANSH01.THF files, and - * will be set to the ASRP directory files if they aren't. Call - * doPrepare() on this layer if you want the changes to take - * effect immediately. - */ - public void setPaths(String[] pathsIn) { - if (pathsIn != null) { - if (pathsIn[0].indexOf(ASRPConstants.TRANS) != -1) { - thfPaths = pathsIn; - } else { - asrpDirs = pathsIn; - } - - asrpHandler = null;// next projection change, we reload. - } - } - - /** - * Returns THF paths if they are set, otherwise returns ASRP - * directory paths. - */ - public String[] getPaths() { - if (thfPaths != null) { - return thfPaths; - } else { - return asrpDirs; - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - coverageDrawingAttributes.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - thfPaths = PropUtils.initPathsFromProperties(props, prefix - + THFProperty, thfPaths); - if (thfPaths == null) { - asrpDirs = PropUtils.initPathsFromProperties(props, prefix - + ASRPDirectoryProperty, asrpDirs); - } - - showCoverage = PropUtils.booleanFromProperties(props, prefix - + ShowCoverageProperty, showCoverage); - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - // find out paths... - if (thfPaths != null) { - String[] p = thfPaths; - StringBuffer pathString = new StringBuffer(); - if (p != null) { - for (int i = 0; i < p.length; i++) { - if (p[i] != null) { - pathString.append(p[i]); - if (i < p.length - 1) { - pathString.append(";"); // separate paths - // with ; - } - } - } - } - props.put(prefix + THFProperty, pathString.toString()); - } else { - props.put(prefix + THFProperty, ""); - } - - if (asrpDirs != null) { - String[] p = asrpDirs; - StringBuffer pathString = new StringBuffer(); - if (p != null) { - for (int i = 0; i < p.length; i++) { - if (p[i] != null) { - pathString.append(p[i]); - if (i < p.length - 1) { - pathString.append(";"); // separate paths - // with ; - } - } - } - } - props.put(prefix + ASRPDirectoryProperty, pathString.toString()); - } else { - props.put(prefix + ASRPDirectoryProperty, ""); - } - - props.put(prefix + ShowCoverageProperty, - new Boolean(showCoverage).toString()); - - coverageDrawingAttributes.setPropertyPrefix(prefix); - coverageDrawingAttributes.getProperties(props); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String interString; - - interString = i18n.get(ASRPLayer.class, - THFProperty, - I18n.TOOLTIP, - "Paths to TRANSH01.THF files, takes precedence over ASRP property. Separated by ;"); - props.put(THFProperty, interString); - interString = i18n.get(ASRPLayer.class, - THFProperty, - "TRANSH01.THF files"); - props.put(THFProperty + LabelEditorProperty, interString); - props.put(THFProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.MultiDirFilePropertyEditor"); - - interString = i18n.get(ASRPLayer.class, - ASRPDirectoryProperty, - I18n.TOOLTIP, - "Paths to ASRP Directories (if no TRANSH01.THF files)"); - props.put(ASRPDirectoryProperty, interString); - interString = i18n.get(ASRPLayer.class, - ASRPDirectoryProperty, - "ASRP directories"); - props.put(ASRPDirectoryProperty + LabelEditorProperty, interString); - props.put(ASRPDirectoryProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.MultiDirectoryPropertyEditor"); - - interString = i18n.get(ASRPLayer.class, - ShowCoverageProperty, - I18n.TOOLTIP, - "Show coverage areas when images can't be displayed."); - props.put(ShowCoverageProperty, interString); - interString = i18n.get(ASRPLayer.class, - ShowCoverageProperty, - "Show Coverage Areas"); - props.put(ShowCoverageProperty + LabelEditorProperty, interString); - props.put(ShowCoverageProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - coverageDrawingAttributes.getPropertyInfo(props); - - interString = i18n.get(ASRPLayer.class, - DrawingAttributes.linePaintProperty, - I18n.TOOLTIP, - "Edge color for coverage area markings."); - props.put(DrawingAttributes.linePaintProperty, interString); - - interString = i18n.get(ASRPLayer.class, - DrawingAttributes.lineWidthProperty, - I18n.TOOLTIP, - "Line Width for coverage area markings."); - props.put(DrawingAttributes.lineWidthProperty, interString); - - interString = i18n.get(ASRPLayer.class, - DrawingAttributes.fillPaintProperty, - I18n.TOOLTIP, - "Fill color for coverage area markings."); - props.put(DrawingAttributes.fillPaintProperty, interString); - - props.put(initPropertiesProperty, THFProperty + " " - + ASRPDirectoryProperty + " " + ShowCoverageProperty + " " - + DrawingAttributes.linePaintProperty + " " - + DrawingAttributes.lineWidthProperty + " " - + DrawingAttributes.fillPaintProperty); - - return props; - } - - /** - * DataBoundsInformer interface. - */ - public DataBounds getDataBounds() { - DataBounds box = null; - - if (asrpHandler != null) { - box = asrpHandler.getDataBounds(); - } - - return box; - } - - public void setShowCoverage(boolean showCoverageIn) { - showCoverage = showCoverageIn; - } - - public boolean getShowCoverage() { - return showCoverage; - } - - protected JPanel guiPanel = null; - - public Component getGUI() { - if (guiPanel == null) { - JPanel gp = new JPanel(); - gp.setLayout(new GridLayout(0, 1)); - String interString = i18n.get(ASRPLayer.class, - "showCoverageCheck", - "Show Coverage"); - JCheckBox coverageCheck = new JCheckBox(interString, getShowCoverage()); - interString = i18n.get(ASRPLayer.class, - "showCoverageCheck", - I18n.TOOLTIP, - "Show coverage areas when images can't be displayed."); - coverageCheck.setToolTipText(interString); - coverageCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - setShowCoverage(jcb.isSelected()); - doPrepare(); - } - }); - - coverageDrawingAttributes.getPropertyChangeSupport() - .addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent pce) { - doPrepare(); - } - }); - - interString = i18n.get(ASRPLayer.class, - "coveragePanelTitle", - "Coverage Controls"); - JPanel covPanel = com.bbn.openmap.util.PaletteHelper.createVerticalPanel(interString); - - covPanel.add(coverageCheck); - covPanel.add(coverageDrawingAttributes.getGUI()); - gp.add(covPanel); - guiPanel = gp; - } - - return guiPanel; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/ContainerGraphic.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/ContainerGraphic.java deleted file mode 100644 index e54de09b0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/ContainerGraphic.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMRect; - -/** - * A custom graphic class for representing objects of type - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanContainer}as a - * rectangular box. - */ -public class ContainerGraphic extends CustomGraphic { - - public ContainerGraphic(SimpleBeanObject object) { - super(object); - this.setRenderType(OMGraphicConstants.RENDERTYPE_LATLON); - } - - /** - * Returns an OMRect object with dimensions equal to the width and - * height of the SimpleBeanContainer and position equal to the - * center lat/lon position of the SimpleBeanContainer object. - */ - public OMGraphic createGraphic(SimpleBeanObject object) { - - if (!(object instanceof SimpleBeanContainer)) { - throw new IllegalArgumentException(object - + " not instance of SimpleBeanContainer"); - } - - SimpleBeanContainer bc = (SimpleBeanContainer) object; - - return new OMRect(bc.getTopLatitude(), bc.getLeftLongitude(), bc.getBottomLatitude(), bc.getRightLongitude(), OMGraphicConstants.LINETYPE_RHUMB); - } - - /** - * Updates the width, height and position of OMRect object used to - * represent the SimpleBeanContainer object with the corresponding - * values in the SimpleBeanContainer object. - */ - public void updateGraphic(SimpleBeanObject object) { - - if (!(object instanceof SimpleBeanContainer)) { - throw new IllegalArgumentException(object - + " not instance of SimpleBeanContainer"); - } - - SimpleBeanContainer bc = (SimpleBeanContainer) object; - - OMGraphic graphic = super.getOMGraphicAt(0); - - if (graphic instanceof OMRect) { - - OMRect rect = (OMRect) graphic; - - rect.setLocation(bc.getTopLatitude(), - bc.getLeftLongitude(), - bc.getBottomLatitude(), - bc.getRightLongitude(), - OMGraphicConstants.LINETYPE_RHUMB); - - } - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/CustomGraphic.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/CustomGraphic.java deleted file mode 100644 index ab7ad1ce9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/CustomGraphic.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * A custom graphic class for representing SimpleBeanObject beans on - * the map. See - * {@link com.bbn.openmap.layer.beanbox.ContainerGraphic}for an - * example implementation. - */ -public abstract class CustomGraphic extends OMGraphicList { - - protected OMGraphic graphic; - - /** - * Create a graphical representation of the object. The - * constructor calls the abstract createGraphic method of this - * class to create the custom graphic which is then added to the - * OMGraphicList. This method also sets the SimpleBeanObject's id - * as the appObject associated with the created graphic. - */ - public CustomGraphic(SimpleBeanObject object) { - - super(1); - - setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - graphic = createGraphic(object); - - super.add(graphic); - - putAttribute(OMGraphic.INDEX, new Long(object.getId())); - } - - /** - * Override this method to create and return the object's graphic - * representation. - */ - public abstract OMGraphic createGraphic(SimpleBeanObject object); - - /** - * Change the graphic to reflect the current state of the object. - * Default implementation does nothing. This method is called by - * the SimpleBeanLayer to update a graphic in response to a user - * action such as moving the object on the map. - */ - public void updateGraphic(SimpleBeanObject object) {} - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/Fighter.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/Fighter.java deleted file mode 100644 index a3d285aa7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/Fighter.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -/** - * A SimpleBeanObject that represents a Fighter. Contains two fighter - * specific fields: type (eg. F16, M21 etc) and speedInNMPerHr. - */ -public class Fighter extends SimpleBeanObject { - - protected String type; - - protected float speedInNMPerHr; - - public Fighter() { - super(); - this.setType("F16"); - this.setSpeedInNMPerHr(1200); - } - - public Fighter(long id, String type, float lat, float lon, - float bearingInDeg, float speedInNMPerHr) { - super(id, lat, lon, bearingInDeg); - this.setType(type); - this.setSpeedInNMPerHr(speedInNMPerHr); - } - - public void setType(String type) { - this.type = type; - } - - public String getType() { - return this.type; - } - - public float getSpeedInNMPerHr() { - return speedInNMPerHr; - } - - public void setSpeedInNMPerHr(float speedInNMPerHr) { - this.speedInNMPerHr = speedInNMPerHr; - } - - public String toString() { - return "[FIGHTER " + id + " " + latitude + " " + longitude + " " - + bearingInDeg + " " + customGraphicClassName + " " - + graphicImage + " " + type + " " + speedInNMPerHr + "]"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/FighterBeanInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/FighterBeanInfo.java deleted file mode 100644 index 4354cd38c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/FighterBeanInfo.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Image; -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * A BeanInfo for the {@link com.bbn.openmap.layer.beanbox.Fighter} - * bean. - */ -public class FighterBeanInfo extends SimpleBeanObjectBeanInfo { - - public PropertyDescriptor[] getPropertyDescriptors() { - - ArrayList list = new ArrayList(7); - - PropertyDescriptor[] pds = super.getPropertyDescriptors(); - list.addAll(Arrays.asList(pds)); - - try { - list.add(new PropertyDescriptor("type", Fighter.class)); - list.add(new PropertyDescriptor("speedInNMPerHr", Fighter.class)); - } catch (IntrospectionException e) { - e.printStackTrace(); - } - - return list.toArray(new PropertyDescriptor[list.size()]); - } - - public Image getIcon(int iconKind) { - - Image image = loadImage("/com/bbn/openmap/layer/beanbox/fighter.gif"); - - return image; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/LayoutClassEditor.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/LayoutClassEditor.java deleted file mode 100644 index b5e06d506..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/LayoutClassEditor.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.beans.PropertyEditorSupport; - -/** - * Custom property editor for the layout class property of a - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanContainer}. - */ -public class LayoutClassEditor extends PropertyEditorSupport { - - /** - * returns a String array containing the class names of two layout - * managers: viz the NullLayout and the WallFormationLayout - */ - public String[] getTags() { - String result[] = { "com.bbn.openmap.layer.beanbox.NullLayout", - "com.bbn.openmap.layer.beanbox.WallFormationLayout" }; - return result; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/NullLayout.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/NullLayout.java deleted file mode 100644 index 66adcf182..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/NullLayout.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import com.bbn.openmap.tools.beanbox.BeanLayoutManager; - -/** - * A layout manager that represents a null layout. This is as good as - * not specifying a layout for the - * {@link SimpleBeanContainer}. - */ -public class NullLayout extends BeanLayoutManager { - - /** does nothing. */ - public void layoutContainer() { - // NOOP - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/README b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/README deleted file mode 100644 index 0b6f86303..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/README +++ /dev/null @@ -1,74 +0,0 @@ - -This directory contains a sample implementation of the -com.bbn.openmap.tools.beanbox.BeanBox class as well as an example OpenMap layer -that uses this sample implementation. - -To run the application, use the beanbox.bat file (or beanbox on cygwin). -This will bring up the standard OpenMap frame that contains one additional -component in the form of a blue bean button on the far right side of the -components toolbar. - -Clicking on this button should bring up the Bean Box frame -that contains three tabs: Generic, Container and Military, -each containing a single example bean. The configuration of the Bean Box -is specified in the openmap.properties file contained in this package. The -openmap.properties file also contains the following three components necessary -for the drag-n-drop bean package to work correctly: - -dropSupport.class=com.bbn.openmap.tools.dnd.DropListenerSupport -dndCatcher.class=com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher -beanpanel.class=com.bbn.openmap.tools.beanbox.BeanPanel - - -The manifest.txt file contained in this package contains the statements -that declares the beans in this package. -This file is compiled into the openmap.jar. - -Example Usage: - -1. Run beanbox.bat or beanbox to bring up the OpenMap frame and click on - the blue bean icon on the component bar to bring up the Bean Box frame. - Switch to the OpenMap Gestures mode. - -2. In the Bean Box frame, switch to the Military tab and drag two fighter - beans from the Bean Box to the map. - NOTE: When you drag and drop a bean on the map, a menu will open - listing the layers willing to accept the drop event. In this example - only the SimpleBeanLayer accepts bean drop events. So select this layer - in the menu. - A property sheet for the bean will now open giving you a chance to change - the bean's properties *before* it is added to the layer. Once this sheet - is closed the bean appears on the layer. You can always change a bean's - properties at any time by right-clicking on the bean icon on the layer. - -3. In the Bean Box frame, switch to the container tab and drag a container bean - from the Bean Box to the map. - -4. Drag the two fighter beans on the map into the container bean. - -4. Right click on the container bean to bring up its property sheet. (If - the propertysheet does not open, try dragging the bean a little bit on the - map and then right-click on it again.) - -5. The default layoutClass for the container is the NullLayout, which - is as good as not having a layout manager. Change the layoutClass property's - value to WallFormationLayout. The two fighter beans will get rearranged into - a wall formation. Dismiss the container's property sheet. - -6. Drag another fighter bean from the Bean Box into the container bean - on the map. The three fighters in the container now get re-layed out in - a 3-ship wall formation. - -7. Once again right-click on the container to bring up its property sheet. - -8. Click on the property editor for the layoutmanager property and adjust the - parameters of the WallFormationLayout, namely bearingInDeg and separationInNM - and watch the effect of these changes on the aircraft formation inside - the container. Close all property sheets. - -9. Drag the container to a different location and notice how the 3-ship - formation moves with it. - -10.Drag one of the fighters out of the container. This fighter is now no longer - a part of the container. The container now rearranges into a 2-ship formation. - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanBox.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanBox.java deleted file mode 100644 index e35b3eccf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanBox.java +++ /dev/null @@ -1,434 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Image; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.beans.BeanInfo; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.beanbox.BeanBox; -import com.bbn.openmap.tools.beanbox.BeanContainer; - -/** - * SimpleBeanBox is a sample implementation of the - * {@link com.bbn.openmap.tools.beanbox.BeanBox} class. SimpleBeanBox manages - * beans of type SimpleBeanObject. - */ -public class SimpleBeanBox extends BeanBox implements MapMouseListener { - - private SimpleBeanLayer layer; - - public SimpleBeanBox(SimpleBeanLayer l) { - super(); - layer = l; - } - - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - public boolean mousePressed(MouseEvent evt) { - return true; - } - - public boolean mouseReleased(MouseEvent evt) { - return true; - } - - public boolean mouseClicked(MouseEvent evt) { - return true; - } - - public void mouseEntered(MouseEvent evt) { - } - - public void mouseExited(MouseEvent evt) { - } - - public boolean mouseDragged(MouseEvent evt) { - return true; - } - - public boolean mouseMoved(MouseEvent evt) { - return true; - } - - public void mouseMoved() { - } - - /** - * adds the specified bean to SimpleBeanLayer. This method is called by the - * com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher class to add - * the specified bean to a OpenMap layer. - */ - public void addBean(Object bean) { - - // System.out.println("Enter> SimpleBeanBox.addBean"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject"); - - layer.addObject((SimpleBeanObject) bean); - - // System.out.println("Exit> SimpleBeanBox.addBean"); - - } - - /** - * removes the specified bean from SimpleBeanLayer. This method is called by - * the com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher class to - * remove the specified bean from a OpenMap layer. - */ - public void removeBean(Object bean) { - - // System.out.println("Enter> SimpleBeanBox.removeBean"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject"); - - layer.removeObject(((SimpleBeanObject) bean).getId()); - - // System.out.println("Exit> SimpleBeanBox.removeBean"); - - } - - /** - * checks if the specified bean is present in SimpleBeanLayer. returns true - * if present, false otherwise. - */ - public boolean containsBean(Object bean) { - - // System.out.println("Called> SimpleBeanBox.containsBean"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject " + bean); - - return (layer.getObject(((SimpleBeanObject) bean).getId()) != null); - } - - /** - * Sets the image associated with the bean using the image present in the - * BeanInfo. Also sets the bean's location. This method is called by the - * com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher class to set - * the bean's properties before it is displayed in a property sheet prior to - * adding to an OpenMap layer. - */ - public void setBeanProperties(Object bean, BeanInfo beanInfo, Point location) { - - // System.out.println("Enter> - // SimpleBeanBox.setBeanProperties"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject " + bean); - - SimpleBeanObject obj = (SimpleBeanObject) bean; - - Image img = beanInfo.getIcon(BeanInfo.ICON_COLOR_32x32); - obj.setGraphicImage(img); - - Point2D llp = layer.getProjection().inverse(location.x, location.y); - - obj.setLatitude((float) llp.getY()); - obj.setLongitude((float) llp.getX()); - - // System.out.println("Exit> - // SimpleBeanBox.setBeanProperties"); - } - - /** - * gets a Vector of beans that implement the - * com.bbn.openmap.tools.beanbox.BeanContainer interface. - * - * @return a possibly empty List of container beans. - */ - protected List getAllContainers() { - - List containers = new ArrayList(); - List list = layer.getObjects(); - - if (list != null) { - for (SimpleBeanObject sbo : list) { - if (sbo instanceof BeanContainer) { - containers.add((SimpleBeanContainer) sbo); - } - } - } - return containers; - } - - /** - * @param bean an object to test against, should be a SimpleBeanObject - * @return a BeanContainer bean that contains the specified - * bean object. - */ - public BeanContainer findEnclosingContainer(Object bean) { - - // System.out.println("Called> - // SimpleBeanBox.findEnclosingContainer"); - - if (!(bean instanceof SimpleBeanObject)) { - return null; - } - - SimpleBeanObject obj = (SimpleBeanObject) bean; - - float objLat = obj.getLatitude(); - float objLon = obj.getLongitude(); - LatLonPoint llp = new LatLonPoint.Float(objLat, objLon); - - return findEnclosingContainer(llp); - } - - /** - * returns a SimpleBeanContainer bean that contains the specified - * LatLonPoint on the map. - */ - public SimpleBeanContainer findEnclosingContainer(LatLonPoint llp) { - - for (SimpleBeanContainer sbc : getAllContainers()) { - if (encloses(sbc, llp)) { - return sbc; - } - } - - return null; - } - - /** - * helper method returns true if the specified LatLonPoint is - * contained within the specified SimpleBeanContainer. - */ - boolean encloses(SimpleBeanContainer container, Point2D llp) { - - float topLat = container.getTopLatitude(); - float leftLon = container.getLeftLongitude(); - float botLat = container.getBottomLatitude(); - float rightLon = container.getRightLongitude(); - float lat = (float) llp.getY(); - float lon = (float) llp.getX(); - - if ((lon > rightLon) || (lon < leftLon)) { - return false; - } - - if ((lat > topLat) || (lat < botLat)) { - return false; - } - - return true; - } - - /** - * finds a bean of type - * com.bbn.openmap.tools.beanbox.BeanContainer that encloses - * the specified (x,y) point. In case more than one container encloses the - * specified point the first one found is returned. Returns null if none is - * found. - */ - BeanContainer findContainerBean(Point pointOnMap) { - if (layer != null && layer.getProjection() != null) { - Point2D llp = layer.getProjection().inverse(pointOnMap.x, pointOnMap.y); - return findEnclosingContainer(llp); - } else { - return null; - } - } - - /** - * returns a bean that does NOT implement - * com.bbn.openmap.tools.beanbox.BeanContainer and which lies - * closest to and within 10 pixels of the specified (x,y) point. Returns - * null if no such object is found. - */ - SimpleBeanObject findNonContainerBean(Point pointOnMap) { - - List list = layer.getObjects(); - - double minSep = Double.MAX_VALUE; - SimpleBeanObject closest = null; - - for (SimpleBeanObject sbo : list) { - - if (sbo instanceof SimpleBeanContainer) { - continue; - } - - Point2D p2 = layer.getProjection().forward(new LatLonPoint.Float(sbo.getLatitude(), sbo.getLongitude())); - - double sep = almostEquals(pointOnMap, p2, 20); - - if (sep < minSep) { - minSep = sep; - closest = sbo; - } - } - - return closest; - } - - /** - * return bean at specified location giving preference to non-container - * beans over container beans. If neither type of bean is found to be close - * enough to the specified location, a null is returned. - */ - public Object getBeanAtLocation(Point pointOnMap) { - - // System.out.println("Called> - // SimpleBeanBox.getBeanAtLocation"); - - SimpleBeanObject obj = findNonContainerBean(pointOnMap); - - if (obj != null) - return obj; - - BeanContainer container = findContainerBean(pointOnMap); - - if (container != null) - return container; - - return null; - } - - /** - * returns the straight line separation in pixels between the specified - * points if separation is equal to or less than the specified tolerance - * amount, else returns Double.MAX_VALUE - */ - - double almostEquals(Point2D p1, Point2D p2, double tol) { - - double sepX = p1.getX() - p2.getX(); - double sepY = p1.getY() - p2.getY(); - double sep = Math.sqrt(sepX * sepX + sepY * sepY); - - if (sep <= tol) - return sep; - else - return Double.MAX_VALUE; - } - - /** - * relocates the specified bean to the new location. This method is called - * by the com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher - * whenever the user moves a bean on the map within the same openmap layer. - * - * @throws IllegalArgumentException is specified bean is not of type - * SimpleBeanObject. - */ - public void relocateBean(Object bean, BeanInfo beanInfo, Point newLocation) { - - // System.out.println("Enter> SimpleBeanBox.relocateBean"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject " + bean); - - SimpleBeanObject obj = (SimpleBeanObject) bean; - - Point2D llp = layer.getProjection().inverse(newLocation.x, newLocation.y); - - relocateSimpleBeanObject(obj, llp); - - layer.updateGraphics(); - - // System.out.println("Exit> SimpleBeanBox.relocateBean"); - } - - /** relocates the specified SimpleBeanObject to the new location. */ - void relocateSimpleBeanObject(SimpleBeanObject obj, Point2D newllp) { - - SimpleBeanContainer oldContainer = null; - - // no support yet for containers within containers because - // of unresolved issues regarding partially over-lapping - // containers. - if (!(obj instanceof SimpleBeanContainer)) { - oldContainer = (SimpleBeanContainer) findEnclosingContainer(obj); - } - - if (oldContainer != null) { - oldContainer.remove(obj); - } - - obj.setLatitude((float) newllp.getY()); - obj.setLongitude((float) newllp.getX()); - - if (obj instanceof SimpleBeanContainer) - ((SimpleBeanContainer) obj).validate(); - - SimpleBeanContainer newContainer = null; - - if (!(obj instanceof SimpleBeanContainer)) { - newContainer = (SimpleBeanContainer) findEnclosingContainer(obj); - } - - if (newContainer != null) { - newContainer.add(obj); - } - } - - /** - * this method is a callback method that is called by a - * com.bbn.openmap.tools.beanbox.GenericPropertySheet when the - * user closes the property sheet. - */ - public void beanChanged(Object bean, String changedPropertyName) { - - // System.out.println("Enter> SimpleBeanBox.beanChanged"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject " + bean); - - SimpleBeanObject obj = (SimpleBeanObject) bean; - - layer.updateObject(obj); - - // System.out.println("Exit> SimpleBeanBox.beanChanged"); - - } - - /** - * returns the image that the cursor is set to when the specified bean is - * dragged on the map. - */ - protected Image getDragImage(Object bean) { - - // System.out.println("Called> SimpleBeanBox.getDragImage"); - - if (!(bean instanceof SimpleBeanObject)) - throw new IllegalArgumentException("not instanceof SimpleBeanObject " + bean); - - SimpleBeanObject obj = (SimpleBeanObject) bean; - - OMGraphic graphic = layer.getGraphic(obj.getId()); - - if (graphic instanceof OMRasterObject) { - return ((OMRasterObject) graphic).getImage(); - } else - return super.getDragImage(bean); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainer.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainer.java deleted file mode 100644 index 7a8bdc8a3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainer.java +++ /dev/null @@ -1,225 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.util.Vector; - -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.tools.beanbox.BeanContainer; -import com.bbn.openmap.tools.beanbox.BeanLayoutManager; - -/** - * A SimpleBeanContainer is itself a bean. Hence this class extends - * the {@link com.bbn.openmap.layer.beanbox.SimpleBeanObject}. - * SimpleBeanContainer is a sample implementation of the - * {@link com.bbn.openmap.tools.beanbox.BeanContainer}interface. - */ -public class SimpleBeanContainer extends SimpleBeanObject implements - BeanContainer { - - private float widthInNM; - private float heightInNM; - - private Vector contents; - private BeanLayoutManager layoutManager; - private String layoutClass; - - public SimpleBeanContainer() { - this(System.currentTimeMillis(), 0, 0, 0, 200, 200, null); - } - - public SimpleBeanContainer(long id, float centerLatitude, - float centerLongitude, float bearingInDeg, float widthInNM, - float heightInNM, BeanLayoutManager layoutManager) { - - super(id, centerLatitude, centerLongitude, bearingInDeg); - setWidthInNM(widthInNM); - setHeightInNM(heightInNM); - setLayout(layoutManager); - - contents = new Vector(); - - super.setCustomGraphicClassName("com.bbn.openmap.layer.beanbox.ContainerGraphic"); - - } - - public Vector getContents() { - return this.contents; - } - - public void setContents(Vector contents) { - this.contents = contents; - } - - public void add(Object bean) { - - if (bean instanceof SimpleBeanObject) { - SimpleBeanObject obj = (SimpleBeanObject) bean; - - if (!contents.contains(new Long(obj.getId()))) { - contents.add(new Long(obj.getId())); - } - - if (layoutManager != null) { - layoutManager.layoutContainer(); - } - } - - } - - public void remove(Object bean) { - - if (bean instanceof SimpleBeanObject) { - SimpleBeanObject obj = (SimpleBeanObject) bean; - - if (contents.contains(new Long(obj.getId()))) { - contents.remove(new Long(obj.getId())); - } - - if (layoutManager != null) - layoutManager.layoutContainer(); - } - } - - public void removeAll() { - - if (!contents.isEmpty()) { - - contents.clear(); - - if (layoutManager != null) - layoutManager.layoutContainer(); - } - - } - - public boolean contains(Object obj) { - - if (obj instanceof SimpleBeanObject) { - return this.contains(new Long(((SimpleBeanObject) obj).getId())); - } - - return false; - } - - public BeanLayoutManager getLayout() { - return layoutManager; - } - - public void setLayout(BeanLayoutManager layout) { - - layoutManager = layout; - - if (layoutManager == null) - layoutManager = new NullLayout(); - - layoutClass = layoutManager.getClass().getName(); - - layoutManager.setContainer((BeanContainer) this); - - layoutManager.layoutContainer(); - - } - - public String getLayoutClass() { - return layoutClass; - } - - public void setLayoutClass(String lc) { - - layoutClass = lc; - - if ((layoutClass == null) - || ((layoutClass = layoutClass.trim()).length() == 0)) { - System.out.println("loading null layout!"); - this.setLayout(new NullLayout()); - } else { - try { - Class lClass = Class.forName(layoutClass); - BeanLayoutManager blm = (BeanLayoutManager) lClass.newInstance(); - this.setLayout(blm); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void validate() { - if (layoutManager != null) - layoutManager.layoutContainer(); - } - - public void setLatitude(float lat) { - super.setLatitude(lat); - validate(); - } - - public void setLongitude(float lon) { - super.setLongitude(lon); - validate(); - } - - public void setBearingInDeg(float bearingInDeg) { - super.setBearingInDeg(bearingInDeg); - validate(); - } - - public float getWidthInNM() { - return widthInNM; - } - - public void setWidthInNM(float w) { - widthInNM = w; - this.validate(); - } - - public float getHeightInNM() { - return heightInNM; - } - - public void setHeightInNM(float h) { - heightInNM = h; - this.validate(); - } - - // utility methods - - public float getBottomLatitude() { - return (float) (getLatitude() - ProjMath.radToDeg(Length.NM.toRadians(heightInNM / 2))); - } - - public float getRightLongitude() { - return (float) (getLongitude() + ProjMath.radToDeg(Length.NM.toRadians(widthInNM / 2))); - } - - public float getTopLatitude() { - return (float) (getLatitude() + ProjMath.radToDeg(Length.NM.toRadians(heightInNM / 2))); - } - - public float getLeftLongitude() { - return (float) (getLongitude() - ProjMath.radToDeg(Length.NM.toRadians(widthInNM / 2))); - } - - public String toString() { - return "[SBC " + id + " " + latitude + " " + longitude + " " - + bearingInDeg + " " + customGraphicClassName + " " - + graphicImage + " " + widthInNM + " " + heightInNM + " " - + contents + " " + layoutClass + "]"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainerBeanInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainerBeanInfo.java deleted file mode 100644 index b00117daa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanContainerBeanInfo.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Image; -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.util.ArrayList; -import java.util.Arrays; - -import com.bbn.openmap.tools.beanbox.BeanLayoutEditor; - -/** - * A BeanInfo for the - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanContainer} bean - */ -public class SimpleBeanContainerBeanInfo extends SimpleBeanObjectBeanInfo { - - public PropertyDescriptor[] getPropertyDescriptors() { - - ArrayList list = new ArrayList(8); - - PropertyDescriptor[] pds = super.getPropertyDescriptors(); - list.addAll(Arrays.asList(pds)); - - try { - list.add(new PropertyDescriptor("widthInNM", SimpleBeanContainer.class)); - list.add(new PropertyDescriptor("heightInNM", SimpleBeanContainer.class)); - PropertyDescriptor pd = new PropertyDescriptor("layoutClass", SimpleBeanContainer.class); - pd.setPropertyEditorClass(LayoutClassEditor.class); - list.add(pd); - - pd = new PropertyDescriptor("layoutManager", SimpleBeanContainer.class, "getLayout", "setLayout"); - - // since layoutManager property is itself a bean - // (of type BeanLayoutManager), use the - // general purpose BeanLayoutEditor class provided in the - // tools.beanbox - // package as the editor class of this bean property. - pd.setPropertyEditorClass(BeanLayoutEditor.class); - - list.add(pd); - } catch (IntrospectionException e) { - e.printStackTrace(); - } - - return list.toArray(new PropertyDescriptor[list.size()]); - } - - public Image getIcon(int iconKind) { - - Image image = loadImage("/com/bbn/openmap/layer/beanbox/simplebeancontainer.gif"); - - return image; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanLayer.java deleted file mode 100644 index 73fe022c4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanLayer.java +++ /dev/null @@ -1,259 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Graphics; -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.beanbox.BeanBox; -import com.bbn.openmap.tools.beanbox.BeanBoxHandler; - -/** - * An OpenMap Layer for displaying - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanObject}beans. - * This class an example of an openmap layer that contains an instance - * of the {@link com.bbn.openmap.tools.beanbox.BeanBox}class. This - * layer maintains a reference to an instance of - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanBox}class which - * is a sample implementation of the - * {@link com.bbn.openmap.tools.beanbox.BeanBox}class. The - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanBox}class - * manages the set of - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanObject}beans - * that are displayed by this layer. - */ -public class SimpleBeanLayer extends Layer implements BeanBoxHandler { - - protected HashMap beans = new HashMap(); - protected HashMap graphics = new HashMap(); - - protected Projection projection; - - protected SimpleBeanBox beanBox; - - public SimpleBeanLayer() { - super(); - - setName("Simple Bean Layer"); - - addToBeanContext = true; - - beanBox = new SimpleBeanBox(this); - } - - /** - * @return the instance of - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanBox} - * that is maintained by this layer. - */ - public BeanBox getBeanBox() { - return beanBox; - } - - /** Gets the current projection */ - public Projection getProjection() { - return projection; - } - - /** - * @return an instance of - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanBox}, - * which implements the MapMouseListener interface. - */ - public MapMouseListener getMapMouseListener() { - return (MapMouseListener) beanBox; - } - - /** Implement ProjectionListener method inherited from Layer. */ - public void projectionChanged(ProjectionEvent event) { - projection = event.getProjection(); - - for (OMGraphic omg : graphics.values()) { - omg.generate(projection); - } - } - - /** override Component method */ - public void paint(Graphics g) { - - for (OMGraphic omg : graphics.values()) { - omg.render(g); - } - } - - /** - * Update all OMGraphic objects maintained by this layer using the - * information stored in corresponding SimpleBeanObject beans. - */ - public void updateGraphics() { - - Projection proj = projection; - - for (Long id : beans.keySet()) { - SimpleBeanObject bean = (SimpleBeanObject) beans.get(id); - - OMGraphic graphic = graphics.get(id); - - if ((graphic instanceof CustomGraphic)) { - ((CustomGraphic) graphic).updateGraphic(bean); - } else if (graphic instanceof OMRasterObject) { - ((OMRasterObject) graphic).setLat(bean.getLatitude()); - ((OMRasterObject) graphic).setLon(bean.getLongitude()); - ((OMRasterObject) graphic).setRotationAngle(Math.toRadians(bean.getBearingInDeg())); - } - - graphic.setNeedToRegenerate(true); - - if (proj != null) { - graphic.generate(proj); - } - - } - - repaint(); - } - - /** - * Adds a bean to this layer. - */ - public void addObject(SimpleBeanObject object) { - - beans.put(new Long(object.getId()), object); - String customGraphicClassName = object.getCustomGraphicClassName(); - - OMGraphic graphic = null; - - if (customGraphicClassName == null) { - - ImageIcon icon = new ImageIcon(object.getGraphicImage()); - int width = icon.getIconWidth(); - int height = icon.getIconHeight(); - graphic = new OMRaster(object.getLatitude(), object.getLongitude(), -width / 2, -height / 2, icon); - - ((OMRaster) graphic).setRotationAngle(Math.toRadians(object.getBearingInDeg())); - - graphic.setRenderType(OMGraphicConstants.RENDERTYPE_OFFSET); - - graphic.putAttribute(OMGraphic.INDEX, new Long(object.getId())); - - } else { - - try { - - Class graphicClass = Class.forName(customGraphicClassName); - - Class parentClass = graphicClass; - while (parentClass != null) { - if (parentClass == CustomGraphic.class) { - break; - } else - parentClass = parentClass.getSuperclass(); - } - - if (parentClass != null) { - Constructor constructor = graphicClass.getConstructor(new Class[] { SimpleBeanObject.class }); - graphic = (CustomGraphic) constructor.newInstance(new Object[] { object }); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - if (graphic != null) { - - graphic.setNeedToRegenerate(true); - - graphics.put(new Long(object.getId()), graphic); - - if (projection != null) - graphic.generate(projection); - - repaint(); - } - - } - - /** - * Removes a bean from this layer. - */ - public void removeObject(Long id) { - beans.remove(id); - graphics.remove(id); - } - - public void removeObject(long id) { - removeObject(new Long(id)); - } - - /** - * returns a bean with the specified id. - */ - public SimpleBeanObject getObject(Long id) { - return (SimpleBeanObject) beans.get(id); - } - - public SimpleBeanObject getObject(long id) { - return (SimpleBeanObject) beans.get(new Long(id)); - } - - /** - * return all SimpleBeanObject beans maintained by this layer. - */ - public List getObjects() { - return new ArrayList(beans.values()); - } - - /** - * return the OMGraphic object associated with the - * SimpleBeanObject with the specified id. - */ - public OMGraphic getGraphic(Long id) { - return (OMGraphic) graphics.get(id); - } - - public OMGraphic getGraphic(long id) { - return (OMGraphic) graphics.get(new Long(id)); - } - - /** - * Update the specified SimpleBeanObject object that may be - * maintained by this layer. - */ - public void updateObject(SimpleBeanObject object) { - - // not yet added to layer. ignore - if (getObject(object.getId()) == null) - return; - - removeObject(object.getId()); - addObject(object); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObject.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObject.java deleted file mode 100644 index cee526e11..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObject.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Image; - -/** - * A simple bean object. Contains a unique long id, a lat, lon - * position an orientation measured in degrees clockwise from the +ve - * Y axis and an optional graphic image or custom graphics class name. - */ -public class SimpleBeanObject { - - protected long id; - protected float latitude; - protected float longitude; - protected float bearingInDeg; - - protected Image graphicImage; - - protected String customGraphicClassName; - - public SimpleBeanObject() { - this(System.currentTimeMillis(), 0, 0, 0); - } - - public SimpleBeanObject(long id, float latitude, float longitude, - float bearingInDeg) { - this.id = id; - this.latitude = latitude; - this.longitude = longitude; - this.bearingInDeg = bearingInDeg; - } - - public void setId(long id) { - this.id = id; - } - - public long getId() { - return this.id; - } - - public void setLatitude(float lat) { - this.latitude = lat; - } - - public float getLatitude() { - return this.latitude; - } - - public void setLongitude(float lon) { - this.longitude = lon; - } - - public float getLongitude() { - return this.longitude; - } - - public float getBearingInDeg() { - return bearingInDeg; - } - - public void setBearingInDeg(float bearingInDeg) { - this.bearingInDeg = bearingInDeg; - } - - public Image getGraphicImage() { - return graphicImage; - } - - public void setGraphicImage(Image graphicImage) { - this.graphicImage = graphicImage; - } - - public String getCustomGraphicClassName() { - return customGraphicClassName; - } - - public void setCustomGraphicClassName(String className) { - this.customGraphicClassName = className; - } - - public String toString() { - return "[SBO " + id + " " + latitude + " " + longitude + " " - + bearingInDeg + " " + customGraphicClassName + " " - + graphicImage + "]"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObjectBeanInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObjectBeanInfo.java deleted file mode 100644 index d16491709..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/SimpleBeanObjectBeanInfo.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.awt.Image; -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.beans.SimpleBeanInfo; -import java.util.ArrayList; - -/** - * A BeanInfo for the - * {@link com.bbn.openmap.layer.beanbox.SimpleBeanObject}bean. - */ -public class SimpleBeanObjectBeanInfo extends SimpleBeanInfo { - - public PropertyDescriptor[] getPropertyDescriptors() { - - ArrayList list = new ArrayList(4); - - try { - list.add(new PropertyDescriptor("id", SimpleBeanObject.class)); - list.add(new PropertyDescriptor("latitude", SimpleBeanObject.class)); - list.add(new PropertyDescriptor("longitude", SimpleBeanObject.class)); - list.add(new PropertyDescriptor("bearingInDeg", SimpleBeanObject.class)); - } catch (IntrospectionException e) { - e.printStackTrace(); - } - - return list.toArray(new PropertyDescriptor[list.size()]); - } - - public Image getIcon(int iconKind) { - - Image image = loadImage("/com/bbn/openmap/layer/beanbox/simplebean.gif"); - - return image; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayout.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayout.java deleted file mode 100644 index aa349d277..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayout.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.util.Vector; - -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.beanbox.BeanLayoutManager; -import com.bbn.openmap.util.Debug; - -/** - * A layout manager for laying out SimpleBeanbObject beans in a wall - * formation. The WallFormationLayout object is itself a bean. - */ -public class WallFormationLayout extends BeanLayoutManager { - - private float separationInNM; - private float bearingInDeg; - - public WallFormationLayout() { - this(35, 90, null); - } - - public WallFormationLayout(float sep, float bearing, SimpleBeanContainer c) { - this.separationInNM = sep; - this.bearingInDeg = bearing; - super._container = c; - } - - public float getSeparationInNM() { - return separationInNM; - } - - public void setSeparationInNM(float sep) { - separationInNM = sep; - layoutContainer(); - } - - public float getBearingInDeg() { - return bearingInDeg; - } - - public void setBearingInDeg(float bearing) { - - if (bearing < 0) - bearing = 360 - bearing; - - bearingInDeg = bearing % 360; - - layoutContainer(); - } - - /** - * Called by the SimpleBeanContainer to layout its contents. - */ - public void layoutContainer() { - - //System.out.println("Called> layoutContainer"); - - if (super._container == null) - return; - - SimpleBeanContainer container = (SimpleBeanContainer) _container; - - Vector contents = super._container.getContents(); - - if (contents == null || contents.isEmpty()) - return; - - LatLonPoint midllp = new LatLonPoint.Float(container.getLatitude(), container.getLongitude()); - - LatLonPoint[] llps = new LatLonPoint[contents.size()]; - - if (contents.size() == 1) - llps[0] = midllp; - else { - float angle1Deg = bearingInDeg - 90; - float angle1Rad = (float) Math.toRadians(angle1Deg); - float angle2Deg = bearingInDeg + 90; - float angle2Rad = (float) Math.toRadians(angle2Deg); - int numBeans = contents.size(); - float spanNM = (numBeans - 1) * separationInNM; - LatLonPoint cornerllp1 = midllp.getPoint( - Length.NM.toRadians(spanNM / 2), - angle1Rad); - llps[0] = cornerllp1; - - for (int i = 1; i < contents.size(); i++) - llps[i] = GreatCircle.sphericalBetween((float)cornerllp1.getRadLat(), - (float)cornerllp1.getRadLon(), - Length.NM.toRadians(separationInNM) * i, - angle2Rad); - } - - for (int i = 0; i < contents.size(); i++) { - - Long id = (Long) contents.get(i); - Debug.error("Here in WallFormationLayout, trying to get layer SimpleBeanObjects"); - /*SimpleBeanObject obj = SimpleBeanLayer.getLayer().getObject(id); - - if (obj == null) - continue; - - obj.setLatitude(llps[i].getLatitude()); - obj.setLongitude(llps[i].getLongitude()); - - obj.setBearingInDeg(bearingInDeg); - */ - - } - - // SimpleBeanLayer.getLayer().updateGraphics(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayoutBeanInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayoutBeanInfo.java deleted file mode 100644 index fc2fe6733..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/WallFormationLayoutBeanInfo.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.layer.beanbox; - -import java.util.List; - -import com.bbn.openmap.tools.beanbox.BeanLayoutManagerBeanInfo; - -/** - * A BeanInfo for the - * {@link com.bbn.openmap.layer.beanbox.WallFormationLayout}bean. - */ -public class WallFormationLayoutBeanInfo extends BeanLayoutManagerBeanInfo { - - protected void localProperties(List propsList) { - super.localProperties(propsList); - property(propsList, "separationInNM", WallFormationLayout.class); - property(propsList, "bearingInDeg", WallFormationLayout.class); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox deleted file mode 100644 index 613c2d90e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox +++ /dev/null @@ -1,91 +0,0 @@ -#! /bin/sh - -# Modified from the ant startup script to start the BeanBox example instead. - -# Cygwin support. $cygwin _must_ be set to either true or false. -case "`uname`" in - CYGWIN*) cygwin=true ;; - *) cygwin=false ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$OPENMAP_HOME" ] && - OPENMAP_HOME=`cygpath --unix "$OPENMAP_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -if [ "$OPENMAP_HOME" = "" ] ; then - # try to find OPENMAP - if [ -d /usr/local/openmap ] ; then - OPENMAP_HOME=/usr/local/openmap - fi - - if [ -d ${HOME}/openmap ] ; then - OPENMAP_HOME=${HOME}/openmap - fi - - ## resolve links - $0 may be a link to ant's home - PRG=$0 - progname=`basename $0` - - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '.*/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname $PRG`/$link" - fi - - done - - OPENMAP_HOME=`dirname "$PRG"`/.. - -fi - -if [ "$JAVA_HOME" != "" ] ; then - if [ "$JAVACMD" = "" ] ; then - JAVACMD=$JAVA_HOME/bin/java - fi -else - if [ "$JAVACMD" = "" ] ; then - JAVACMD=java - fi -fi - -# add in the dependency .jar files -DIRLIBS=${OPENMAP_HOME}/lib/*.jar -# Change to match your installation -for i in ${DIRLIBS} -do - # if the directory is empty, then it will return the input string - # this is stupid, so case for it - if [ "$i" != "${DIRLIBS}" ] ; then - if [ "$LOCALCLASSPATH" != "" ] ; then - LOCALCLASSPATH=$LOCALCLASSPATH:"$i" - else - LOCALCLASSPATH="$i" - fi - fi -done - -LOCALCLASSPATH=$LOCALCLASSPATH:${OPENMAP_HOME}/share - -if [ "$CLASSPATH" != "" ] ; then - LOCALCLASSPATH=$CLASSPATH:${OPENMAP_HOME}/classes/openmap:${OPENMAP_HOME}/classes/corba_vb$LOCALCLASSPATH -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - OPENMAP_HOME=`cygpath --path --windows "$OPENMAP_HOME"` - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"` -fi - -$JAVACMD -Xmx64m -classpath "$LOCALCLASSPATH" -Dopenmap.configDir=$OPENMAP_HOME/share com.bbn.openmap.app.OpenMap -properties ./openmap.properties - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox.bat b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox.bat deleted file mode 100644 index 32d202415..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/beanbox.bat +++ /dev/null @@ -1,19 +0,0 @@ -'@echo off - -rem This will launch the OpenMap application with the BeanBox component -rem YOU MUST EDIT THE SETTINGS IN THIS FILE TO MATCH YOUR CONFIGURATION - -rem Java Virtual Machine -rem CHANGE THIS TO POINT TO YOUR JAVA INSTALLATION IF JAVA ISN"T IN YOUR PATH -set JAVABIN=java.exe - -rem OpenMap top-level directory -rem THIS POINTS TO THE DIRECTORY ABOVE "BIN". CHANGE THIS IF YOU MOVE THE -rem BATCH FILE. -set OPENMAP_HOME=..\..\..\..\.. - -rem CLASSPATH points to toplevel OpenMap directory and share subdirectory -set CLASSPATH=.;%OPENMAP_HOME%\classes\openmap;%OPENMAP_HOME%\share;%OPENMAP_HOME%\lib\openmap.jar; - -rem OK, now run OpenMap -%JAVABIN% -mx64m -Dopenmap.configDir=%OPENMAP_HOME%\share com.bbn.openmap.app.OpenMap -properties %OPENMAP_HOME%\src\openmap\com\bbn\openmap\examples\beanbox\openmap.properties diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/manifest.txt b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/manifest.txt deleted file mode 100644 index f4ae6fc14..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/manifest.txt +++ /dev/null @@ -1,10 +0,0 @@ -Manifest-Version: 1.0 - -Name: com/bbn/openmap/examples/beanbox/SimpleBeanObject.class -Java-Bean: True - -Name: com/bbn/openmap/examples/beanbox/SimpleBeanContainer.class -Java-Bean: True - -Name: com/bbn/openmap/examples/beanbox/Fighter.class -Java-Bean: True diff --git a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/package.html b/src/core/src/main/java/com/bbn/openmap/layer/beanbox/package.html deleted file mode 100644 index 3983ace2a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/beanbox/package.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - -Provides a sample openmap application that uses the openmap beanbox. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/daynight/DayNightLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/daynight/DayNightLayer.java deleted file mode 100644 index a010c05ce..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/daynight/DayNightLayer.java +++ /dev/null @@ -1,478 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/daynight/DayNightLayer.java,v $ -// $RCSfile: DayNightLayer.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/04/07 17:36:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.daynight; - -/* Java Core */ -import java.awt.Color; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.Timer; - -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; - -/** - * The DayNightLayer is a layer that draws the day/Night terminator on the map. - * When the layer is re-projected, it figures out the brightest point on the - * earth (closest to the sun), and creates an image that has daytime pixels - * clear and the nighttime pixels shaded. There are a couple of options - * available for the layer. The terminator can be faded from light to dark, and - * the width of the fading can be adjusted. The color of the shading can be - * changed. The shading can reflect the current time, or be set to display the - * shading of a specified time. A time interval can be set to have the layer - * automatically update at regular intervals. - * - *

- * The openmap.properties file can control the layer with the following - * settings: - * - *

- * 
- *  # These are all optional, and can be omitted if you want to use the defaults.
- *  # draw terminator as poly (faster calculation than image,
- *  # defaults to true).
- *  daynight.doPolyTerminator=true
- *  # number of vertices for polygon terminator line.  this is only valid
- *  # if doPolyTerminator is true...
- *  daynight.terminatorVerts=360
- *  # termFade - the distance of the transition of fade, as a percentage of PI.
- *  daynight.termFade=.1
- *  # currentTime - true to display the shading at the computer's current time.
- *  daynight.currentTime=true
- *  # overlayTime - time, in milliseconds from java/unix epoch, to set the layer
- *  # time being displayed.  currentTime has to be false for this to be used.
- *  daynight.overlayTime=919453689000
- *  # updateInterval - time in milliseconds between updates.  currentTime has to be
- *  # true for this to be used.
- *  daynight.updateInterval=300000
- *  # Color of the shading (32bit Hex ARGB)
- *  daynight.nighttimeColor=64000000
- * 
- * 
- *

- * In addition, you can get this layer to work with the OpenMap viewer by - * editing your openmap.properties file: - * - *

- * 
- *  # layers
- *  openmap.layers=daynight ...
- *  # class
- *  daynight.class=com.bbn.openmap.layer.daynight.DayNightLayer
- *  # name
- *  daynight.prettyName=Day/Night Shading
- * 
- * 
- * - */ -public class DayNightLayer extends OMGraphicHandlerLayer implements ProjectionListener, ActionListener { - /** - * Default value of fade to the terminator line, set to .10f. This means - * that the last 10% of the horizon will be faded out. - */ - public static final float DEFAULT_TERM_FADE = .10f; - /** - * Default update interval, which is never - updates occur on - * re-projections. - */ - public static final int DO_NOT_UPDATE = -1; - - /** The color of daytime - default is white and clear. */ - protected Color daytimeColor = new Color(0x00FFFFFF, true); - /** the color of darkness - default is black. */ - protected Color nighttimeColor = new Color(0x7F000000, true); - - /** - * Percentage of the distance from the horizon to the brightest point to - * start fading to darkness. Expected to be between 0.0 and 0.5. - */ - protected float termFade = DEFAULT_TERM_FADE; - /** - * If true, the layer will set the darkness according to the current time. - */ - protected boolean currentTime = true; - /** - * The time used to create the layer, in milliseconds from java/unix epoch. - */ - protected long overlayTime = 0; - /** - * Update interval to automatically update the layer, in milli-seconds - */ - protected int updateInterval = 300000; - /** Update timer. */ - protected Timer timer; - - /** - * Create the terminator line as a polygon. - */ - protected boolean doPolyTerminator = true; - - /** - * The number of vertices of the polygon terminator line. - */ - protected int terminatorVerts = 360; - - /////// Properties - public static final String DaytimeColorProperty = "daytimeColor"; - public static final String NighttimeColorProperty = "nighttimeColor"; - public static final String TermFadeProperty = "termFade"; - public static final String CurrentTimeProperty = "useCurrentTime"; - public static final String OverlayTimeProperty = "overlayTime"; - public static final String UpdateIntervalProperty = "updateInterval"; - public static final String DoPolyTerminatorProperty = "doPolyTerminator"; - public static final String TerminatorVertsProperty = "terminatorVerts"; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DayNightLayer() { - setName("Day-Night"); - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the DayNightLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - overlayTime = PropUtils.longFromProperties(properties, prefix + OverlayTimeProperty, overlayTime); - if (overlayTime <= 0) { - currentTime = true; - } - - currentTime = PropUtils.booleanFromProperties(properties, prefix + CurrentTimeProperty, currentTime); - - updateInterval = PropUtils.intFromProperties(properties, prefix + UpdateIntervalProperty, updateInterval); - - if (updateInterval > 0) { - timer = new Timer(updateInterval, this); - } - - termFade = PropUtils.floatFromProperties(properties, prefix + TermFadeProperty, termFade); - - if (termFade < 0 || termFade >= .5) { - Debug.output("DayNightLayer: termFade funky value ignored."); - termFade = DEFAULT_TERM_FADE; - } - - daytimeColor = PropUtils.parseColorFromProperties(properties, prefix + DaytimeColorProperty, daytimeColor); - nighttimeColor = PropUtils.parseColorFromProperties(properties, prefix + NighttimeColorProperty, - nighttimeColor); - - doPolyTerminator = PropUtils.booleanFromProperties(properties, prefix + DoPolyTerminatorProperty, - doPolyTerminator); - terminatorVerts = PropUtils.intFromProperties(properties, prefix + TerminatorVertsProperty, terminatorVerts); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + OverlayTimeProperty, Long.toString(overlayTime)); - props.put(prefix + CurrentTimeProperty, new Boolean(currentTime).toString()); - props.put(prefix + UpdateIntervalProperty, Integer.toString(updateInterval)); - props.put(prefix + TermFadeProperty, Float.toString(termFade)); - props.put(prefix + DaytimeColorProperty, Integer.toHexString(daytimeColor.getRGB())); - props.put(prefix + NighttimeColorProperty, Integer.toHexString(nighttimeColor.getRGB())); - props.put(prefix + DoPolyTerminatorProperty, new Boolean(doPolyTerminator).toString()); - props.put(prefix + TerminatorVertsProperty, Integer.toString(terminatorVerts)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String interString; - - interString = i18n.get(DayNightLayer.class, OverlayTimeProperty, I18n.TOOLTIP, - "The time used to create the layer, in milliseconds from java/unix epoch (leave empty for current time)."); - props.put(OverlayTimeProperty, interString); - interString = i18n.get(DayNightLayer.class, OverlayTimeProperty, OverlayTimeProperty); - props.put(OverlayTimeProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, CurrentTimeProperty, I18n.TOOLTIP, - "If true, the layer will set the darkness according to the current time."); - props.put(CurrentTimeProperty, interString); - interString = i18n.get(DayNightLayer.class, CurrentTimeProperty, CurrentTimeProperty); - props.put(CurrentTimeProperty + LabelEditorProperty, interString); - props.put(CurrentTimeProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, UpdateIntervalProperty, I18n.TOOLTIP, - "Update interval to automatically update the layer, in milli-seconds."); - props.put(UpdateIntervalProperty, interString); - interString = i18n.get(DayNightLayer.class, UpdateIntervalProperty, UpdateIntervalProperty); - props.put(UpdateIntervalProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, TermFadeProperty, I18n.TOOLTIP, - "Percentage of the distance from the horizon to the brightest point to start fading to darkness, 0.0 to 0.5."); - props.put(TermFadeProperty, interString); - interString = i18n.get(DayNightLayer.class, TermFadeProperty, TermFadeProperty); - props.put(TermFadeProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, DaytimeColorProperty, I18n.TOOLTIP, - "Color for the daytime area, if polygon terminator isn't used."); - props.put(DaytimeColorProperty, interString); - interString = i18n.get(DayNightLayer.class, DaytimeColorProperty, DaytimeColorProperty); - props.put(DaytimeColorProperty + LabelEditorProperty, interString); - props.put(DaytimeColorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, NighttimeColorProperty, I18n.TOOLTIP, - "Color for the nighttime area."); - props.put(NighttimeColorProperty, interString); - interString = i18n.get(DayNightLayer.class, NighttimeColorProperty, NighttimeColorProperty); - props.put(NighttimeColorProperty + LabelEditorProperty, interString); - props.put(NighttimeColorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, DoPolyTerminatorProperty, I18n.TOOLTIP, - "Render with polygon instead of image (it's faster)."); - props.put(DoPolyTerminatorProperty, interString); - interString = i18n.get(DayNightLayer.class, DoPolyTerminatorProperty, DoPolyTerminatorProperty); - props.put(DoPolyTerminatorProperty + LabelEditorProperty, interString); - props.put(DoPolyTerminatorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, TerminatorVertsProperty, I18n.TOOLTIP, - "Number of vertices of the polygon terminator (more is smoother)."); - props.put(TerminatorVertsProperty, interString); - interString = i18n.get(DayNightLayer.class, TerminatorVertsProperty, TerminatorVertsProperty); - props.put(TerminatorVertsProperty + LabelEditorProperty, interString); - - props.put(initPropertiesProperty, - CurrentTimeProperty + " " + OverlayTimeProperty + " " + UpdateIntervalProperty + " " - + NighttimeColorProperty + " " + DoPolyTerminatorProperty + " " + TerminatorVertsProperty + " " - + DaytimeColorProperty + " " + TermFadeProperty + " " + RemovableProperty + " " - + AddAsBackgroundProperty); - - return props; - } - - /** - * Handle an ActionEvent from the Timer. - * - * @param ae action event from the timer. - */ - public void actionPerformed(java.awt.event.ActionEvent ae) { - super.actionPerformed(ae); - if (Debug.debugging("daynight")) { - Debug.output(getName() + "| updating image via timer..."); - } - doPrepare(); - } - - /** - * Create the OMGraphic that acts as an overlay showing the day/night - * terminator. The brightest spot on the earth is calculated, and then each - * pixel is inverse projected to find out its coordinates. Then the great - * circle distance is calculated. The terminator is assumed to be the great - * circle where all the points are PI/2 away from the bright point. If the - * termFade variable is set, then the difference in color over the - * terminator is feathered, on equal amount of the terminator. - * - * @param projection the projection of the screen, - * @return OMGraphic containing image to use for the layer. The image has - * been projected. - */ - protected OMGraphic createImage(Projection projection) { - - if (currentTime) - overlayTime = System.currentTimeMillis(); - - if (Debug.debugging("daynight")) { - Debug.output("DayNightLayer: Calculating sun position at time " + Long.toString(overlayTime)); - } - - LatLonPoint brightPoint = SunPosition.sunPosition(overlayTime); - - Debug.message("daynight", "DayNightLayer: Calculated sun position"); - - // Do a fast and relatively inexpensive calculation of the - // terminator. NOTE: for non-cylindrical projections we don't - // create a full-hemisphere circle so that we don't get - // flip-rendering problem... - if (doPolyTerminator) { - Debug.message("daynight", "DayNightLayer: Creating polygon terminator"); - LatLonPoint darkPoint = brightPoint.getPoint(Math.PI, Math.PI / 4); - OMCircle circle = new OMCircle((float) darkPoint.getY(), (float) darkPoint.getX(), - (projection instanceof Cylindrical) ? 90f : 89.0f, // HACK - Length.DECIMAL_DEGREE, terminatorVerts); - circle.setPolarCorrection(true); - circle.setFillPaint(nighttimeColor); - circle.setLinePaint(nighttimeColor); - circle.generate(projection); - Debug.message("daynight", "DayNightLayer: Done creating polygon terminator"); - return circle; - } - - int width = projection.getWidth(); - int height = projection.getHeight(); - int[] pixels = new int[width * height]; - - OMRaster ret = new OMRaster((int) 0, (int) 0, width, height, pixels); - - Debug.message("daynight", getName() + "|createImage: Center of bright spot lat= " + brightPoint.getLatitude() - + ", lon= " + brightPoint.getLongitude()); - - // Light is clear and/or white - int light = daytimeColor.getRGB(); - - // Allocate the memory here for the testPoint - LatLonPoint testPoint = new LatLonPoint.Float(0f, 0f); - // great circle distance between the bright point and each - // pixel. - double distance; - - // Set the darkeness value - int dark = nighttimeColor.getRGB();// ARGB - int darkness = dark >>> 24;// darkness alpha - int value; - - // Calculate the fae limits around the terminator - float upperFadeLimit = (float) (MoreMath.HALF_PI * (1.0 + termFade)); - float lowerFadeLimit = (float) (MoreMath.HALF_PI * (1.0 - termFade)); - int fadeColorValue = 0x00FFFFFF & (dark); // RGB - - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - - projection.inverse(i, j, testPoint); - distance = brightPoint.distance(testPoint); - - if (distance > upperFadeLimit) { - pixels[j * width + i] = dark; - } else if (distance > lowerFadeLimit) { - value = (int) (darkness * (1 - ((upperFadeLimit - distance) / (upperFadeLimit - lowerFadeLimit)))); - value <<= 24; - pixels[j * width + i] = fadeColorValue | value; - } else { - pixels[j * width + i] = light; - } - } - } - - ret.generate(projection); - return ret; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the location. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - */ - public synchronized OMGraphicList prepare() { - - OMGraphicList list = getList(); - if (list == null) { - list = new OMGraphicList(); - } else { - list.clear(); - } - - Debug.message("basic", getName() + "|DayNightLayer.prepare(): doing it"); - - OMGraphic ras = createImage(getProjection()); - if (timer != null) - timer.restart(); - list.add(ras); - - return list; - } - - /** - * Get the time of the overlay. - */ - public long getOverlayTime() { - return overlayTime; - } - - /** - * Set the time for the overlay. - */ - public void setOverlayTime(long ot) { - overlayTime = ot; - currentTime = false; - doPrepare(); - } - - /** - * Returns whether the layer will set the overlayTime to the time the image - * is created. - */ - public boolean getCurrentTime() { - return currentTime; - } - - /** - * Set whether the layer should set the overlayTime to the time the image is - * created. If the time is being set to reflect a time other than the - * current time, this needs to be set to false. It actually is, if you - * manually set the overlay time. - */ - public void setCurrentTime(boolean ct) { - currentTime = ct; - } - - /** - * Get the timer being used for automatic updates. May be null if a timer is - * not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, you can set - * the timer to do that. Set it to null to disable it. - */ - public void setTimer(Timer t) { - timer = t; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/daynight/SunPosition.java b/src/core/src/main/java/com/bbn/openmap/layer/daynight/SunPosition.java deleted file mode 100644 index a2e6a29da..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/daynight/SunPosition.java +++ /dev/null @@ -1,427 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/daynight/SunPosition.java,v $ -// $RCSfile: SunPosition.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:53 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.daynight; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; - -/** - * SunPosition calculates the latitude/longitude on the Earth that is closest to - * the Sun, the point on the Earth where the sun is directly overhead. - *

- * - * All of these calculations are based on an epoch, or a starting point where - * the Sun's position is known. From the reference book, the epoch is 1990 - * January 0.0. - *

- * - * Also, all of the equations, and understanding of this whole algorithm, was - * gained from a great book - Practical Astronomy with Your Calculator, by Peter - * Duffett-Smith, Third Edition, Cambridge University Press 1988. - */ -public class SunPosition { - - /** Epoch Julian Date. */ - public final static double EPOCH_JULIAN_DATE = 2447891.5; - /** Epoch start time in seconds. */ - public final static double EPOCH_TIME_SECS = 631065600; - - /** - * Constant denoting the number of radians an object would travel if it - * orbited around the earth in a day. - */ - public static double ORBIT_RADS_PER_DAY = MoreMath.TWO_PI / 365.242191; - - /** - * Ecliptic Longitude of earth at 1990 January epoch. From Duffett-Smith, - * chapter 46, table 6. (279.403303 degrees converted to radians). - */ - public static final double ECLIPTIC_LONGITUDE_EPOCH = 4.87650757893409; - /** - * Variable notation of ECLIPTIC_LONGITUDE_EPOCH from Duffett-Smith. - */ - public static final double epsilon_g = ECLIPTIC_LONGITUDE_EPOCH; - - /** - * Ecliptic Longitude of of perigee. From Duffett-Smith, chapter 46, table - * 6. (282.768422 degrees converted to radians). - */ - public static final double ECLIPTIC_LONGITUDE_PERIGEE = 4.935239985213178; - /** - * Variable notation of ECLIPTIC_LONGITUDE_PERIGEE from Duffett-Smith. - */ - public static final double omega_bar_g = ECLIPTIC_LONGITUDE_PERIGEE; - - /** - * Eccentricity of orbit, from Duffett-Smith, chapter 46, table 6. - */ - public static final double ECCENTRICITY = 0.016713; - - /** - * MEAN_OBLIQUITY_OF_EPOCH gives the mean obliquity of the ecliptic, which - * is the angle between the planes of the equator and the ecliptic. Using - * the algorithm described in Duffett-Smith, chapter 27, this is calculated - * for the 1990 January epoch to be .4091155 radians (23.440592 degrees). - */ - public static final double MEAN_OBLIQUITY_OF_EPOCH = .4091155; - - // These parameters are used in the Moon position calculations. - - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double MOON_EPOCH_MEAN_LONGITUDE = 318.351648 * Math.PI / 180.0; - /** - * The algorithm representation for the moon MOON_EPOCH_MEAN_LONGITUDE, "l". - */ - public static final double el0 = MOON_EPOCH_MEAN_LONGITUDE; - - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double PERIGEE_EPOCH_MEAN_LONGITUDE = 36.340410 * Math.PI / 180.0; - /** - * The algorithm representation for the moon PERIGEE_EPOCH_MEAN_LONGITUDE. - */ - public static final double P0 = PERIGEE_EPOCH_MEAN_LONGITUDE; - - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double NODE_EPOCH_MEAN_LONGITUDE = 318.510107 * Math.PI / 180.0; - /** - * The algorithm representation for the moon NODE_EPOCH_MEAN_LONGITUDE. - */ - public static final double N0 = NODE_EPOCH_MEAN_LONGITUDE; - - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double MOON_ORBIT_INCLINATION = 5.145396 * Math.PI / 180.0; - /** - * The algorithm representation for the moon MOON_ORBIT_INCLINATION, "i". - */ - public static final double eye = MOON_ORBIT_INCLINATION; - - /** Moon parameter, from Duffett-Smith, chapter 65, table 10. */ - public static final double MOON_ECCENTRICITY = .054900; - /** Moon parameter, from Duffett-Smith, chapter 65, table 10. */ - public static final double MAJOR_AXIS_MOON_ORBIT = 384401; // km - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double MOON_ANGULAR_SIZE = .5181 * Math.PI / 180.0; - /** - * Moon parameter, from Duffett-Smith, chapter 65, table 10. In radians. - */ - public static final double MOON_PARALLAX = .9507 * Math.PI / 180.0; - - /** - * Use Kepllers's equation to find the eccentric anomaly. From - * Duffett-Smith, chapter 47. - * - * @param M the angle that the Sun has moved since it passed through - * perigee. - */ - public static double eccentricAnomaly(double M) { - double delta; - double E = M; - while (true) { - delta = E - (ECCENTRICITY * Math.sin(E)) - M; - - if (Math.abs(delta) <= 1E-10) - break; - E -= (delta / (1.0 - (ECCENTRICITY * Math.cos(E)))); - } - return E; - } - - /** - * Calculate the mean anomaly of sun, in radians. From Duffett-Smith, - * chapter 47. - * - * @param daysSinceEpoch number of days since 1990 January epoch. - */ - protected static double sunMeanAnomaly(double daysSinceEpoch) { - - double N = ORBIT_RADS_PER_DAY * daysSinceEpoch; - N %= MoreMath.TWO_PI; - if (N < 0) - N += MoreMath.TWO_PI; - - double M0 = N + epsilon_g - omega_bar_g; - if (M0 < 0) - M0 += MoreMath.TWO_PI; - return M0; - } - - /** - * Calculate the ecliptic longitude of sun, in radians. From Duffett-Smith, - * chapter 47. - * - * @param M0 sun's mean anomaly, calculated for the requested time relative - * to the 1990 epoch. - */ - protected static double sunEclipticLongitude(double M0) { - double E = eccentricAnomaly(M0); - double v = 2 * Math.atan(Math.sqrt((1 + ECCENTRICITY) / (1 - ECCENTRICITY)) * Math.tan(E / 2.0)); - double ret = v + omega_bar_g; - ret = adjustWithin2PI(ret); - return ret; - } - - /** - * Conversion from ecliptic to equatorial coordinates for ascension. From - * Duffett-Smith, chapter 27. - * - * @param lambda ecliptic longitude - * @param beta ecliptic latitude - */ - protected static double eclipticToEquatorialAscension(double lambda, double beta) { - double sin_e = Math.sin(MEAN_OBLIQUITY_OF_EPOCH); - double cos_e = Math.cos(MEAN_OBLIQUITY_OF_EPOCH); - - return Math.atan2(Math.sin(lambda) * cos_e - Math.tan(beta) * sin_e, Math.cos(lambda)); - } - - /** - * Conversion from ecliptic to equatorial coordinates for declination. From - * Duffett-Smith, chapter 27. - * - * @param lambda ecliptic longitude - * @param beta ecliptic latitude - */ - protected static double eclipticToEquatorialDeclination(double lambda, double beta) { - double sin_e = Math.sin(MEAN_OBLIQUITY_OF_EPOCH); - double cos_e = Math.cos(MEAN_OBLIQUITY_OF_EPOCH); - - return Math.asin(Math.sin(beta) * cos_e + Math.cos(beta) * sin_e * Math.sin(lambda)); - } - - /** - * Given a date from a gregorian calendar, give back a julian date. From - * Duffett-Smith, chapter 4. - * - * @param cal Gregorian calendar for requested date. - * @return julian date of request. - */ - public static double calculateJulianDate(GregorianCalendar cal) { - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH); - int day = cal.get(Calendar.DAY_OF_MONTH); - - // Algorithm expects that the January is = 1, which is - // different from the Java representation - month++; - - if ((month == 1) || (month == 2)) { - year -= 1; - month += 12; - } - - int A = year / 100; - int B = (int) (2 - A + (A / 4)); - int C = (int) (365.25 * (float) year); - int D = (int) (30.6001 * (float) (month + 1)); - - double julianDate = (double) (B + C + D + day) + 1720994.5; - - return julianDate; - } - - /** - * Calculate the greenwich sidereal time (GST). From Duffett-Smith, chapter - * 12. - * - * @param julianDate julian date of request - * @param time calendar reflecting local time zone change to greenwich - * @return GST relative to unix epoch. - */ - public static double greenwichSiderealTime(double julianDate, GregorianCalendar time) { - - double T = (julianDate - 2451545.0) / 36525.0; - double T0 = 6.697374558 + (T * (2400.051336 + (T + 2.5862E-5))); - - T0 %= 24.0; - if (T0 < 0) { - T0 += 24.0; - } - - double UT = time.get(Calendar.HOUR_OF_DAY) + (time.get(Calendar.MINUTE) + time.get(Calendar.SECOND) / 60.0) / 60.0; - - T0 += UT * 1.002737909; - - T0 %= 24.0; - if (T0 < 0) { - T0 += 24.0; - } - - return T0; - } - - /** - * Given the number of milliseconds since the unix epoch, compute position - * on the earth (lat, lon) such that sun is directly overhead. From - * Duffett-Smith, chapter 46-47. - * - * @param mssue milliseconds since unix epoch - * @return LatLonPoint of the point on the earth that is closest. - */ - public static LatLonPoint sunPosition(long mssue) { - - // Set the date and clock, based on the millisecond count: - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(new Date(mssue)); - - double julianDate = calculateJulianDate(cal); - - // Need to correct time to GMT - long gmtOffset = cal.get(Calendar.ZONE_OFFSET); - // thanks to Erhard... - long dstOffset = cal.get(Calendar.DST_OFFSET); // ins. - // 12.04.99 - cal.setTime(new Date(mssue - (gmtOffset + dstOffset))); // rep. - // 12.04.99 - - double numDaysSinceEpoch = ((mssue / 1000) - EPOCH_TIME_SECS) / (24.0f * 3600.0f); - - // M0 - mean anomaly of the sun - double M0 = sunMeanAnomaly(numDaysSinceEpoch); - // lambda - double sunLongitude = sunEclipticLongitude(M0); - // alpha - double sunAscension = eclipticToEquatorialAscension(sunLongitude, 0.0); - // delta - double sunDeclination = eclipticToEquatorialDeclination(sunLongitude, 0.0); - - double tmpAscension = sunAscension - (MoreMath.TWO_PI / 24) * greenwichSiderealTime(julianDate, cal); - - return new LatLonPoint.Double(sunDeclination, tmpAscension, true); - } - - /** - * Given the number of milliseconds since the unix epoch, compute position - * on the earth (lat, lon) such that moon is directly overhead. From - * Duffett-Smith, chapter 65. Note: This is acting like it works, but I - * don't have anything to test it against. No promises. - * - * @param mssue milliseconds since unix epoch - * @return LatLonPoint of the point on the earth that is closest. - */ - public static LatLonPoint moonPosition(long mssue) { - - // Set the date and clock, based on the millisecond count: - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(new Date(mssue)); - - double julianDate = calculateJulianDate(cal); - - // Need to correct time to GMT - long gmtOffset = cal.get(Calendar.ZONE_OFFSET); - cal.setTime(new Date(mssue - gmtOffset)); - - // Step 1,2 - double numDaysSinceEpoch = ((mssue / 1000) - EPOCH_TIME_SECS) / (24.0f * 3600.0f); - // Step 3 - // M0 - mean anomaly of the sun - double M0 = sunMeanAnomaly(numDaysSinceEpoch); - // lambda - double sunLongitude = sunEclipticLongitude(M0); - // Step 4 - double el = (13.1763966 * numDaysSinceEpoch * Math.PI / 180) + el0; - el = adjustWithin2PI(el); - // Step 5 - double Mm = el - (.1114041 * numDaysSinceEpoch * Math.PI / 180) - P0; - Mm = adjustWithin2PI(Mm); - // Step 6 - double N = N0 - (.0529539 * numDaysSinceEpoch * Math.PI / 180); - N = adjustWithin2PI(N); - // Step 7 - double C = el - sunLongitude; - double Ev = 1.2739 * Math.sin(2 * C - Mm); - // Step 8 - double Ae = .1858 * Math.sin(M0); - double A3 = .37 * Math.sin(M0); - // Step 9 - double Mmp = Mm + Ev - Ae - A3; - // Step 10 - double Ec = 6.2886 * Math.sin(Mmp); - // Step 11 - double A4 = 0.214 * Math.sin(2 * Mmp); - // Step 12 - double elp = el + Ev + Ec - Ae + A4; - // Step 13 - double V = .6583 * Math.sin(2 * (elp - sunLongitude)); - // Step 14 - double elpp = elp + V; - // Step 15 - double Np = N - (.16 * Math.sin(M0)); - // Step 16 - double y = Math.sin(elpp - Np) * Math.cos(eye); - // Step 17 - double x = Math.cos(elpp - Np); - // Step 18 - double amb = Math.atan2(y, x); - // Step 19 - double lambda_m = amb + Np; - // Step 20 - double beta_m = Math.asin(Math.sin(elpp - Np) * Math.sin(eye)); - // Step 21 - // alpha - double moonAscension = eclipticToEquatorialAscension(lambda_m, beta_m); - // delta - double moonDeclination = eclipticToEquatorialDeclination(lambda_m, beta_m); - - double tmpAscension = moonAscension - (MoreMath.TWO_PI / 24) * greenwichSiderealTime(julianDate, cal); - - return new LatLonPoint.Double(moonDeclination, tmpAscension, true); - } - - /** - * Little function that resets the input to be within 0 - 2*PI, by adding or - * subtracting 2PI as needed. - * - * @param num The number to be modified, if needed. - */ - protected static double adjustWithin2PI(double num) { - if (num < 0) { - do - num += MoreMath.TWO_PI; - while (num < 0); - } else if (num > MoreMath.TWO_PI) { - do - num -= MoreMath.TWO_PI; - while (num > MoreMath.TWO_PI); - } - return num; - } - - public static void main(String[] arg) { - System.out.println("Sun is over " + SunPosition.sunPosition(System.currentTimeMillis())); - System.out.println("Moon is over " + SunPosition.moonPosition(System.currentTimeMillis())); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/daynight/package.html b/src/core/src/main/java/com/bbn/openmap/layer/daynight/package.html deleted file mode 100644 index df208a035..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/daynight/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides an OpenMap layer that displays day/night shading. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheHandler.java deleted file mode 100644 index 02e88acca..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheHandler.java +++ /dev/null @@ -1,436 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDCacheHandler.java,v $ -// $RCSfile: DTEDCacheHandler.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.LLXY; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * The DTEDCacheHandler controls the real cache of DTED frames. It is managed by - * the DTEDCacheManager, and the manager asks it for frames. The - * DTEDCacheHandler goes to its cache for the images, but it also manages the - * configuration of the frames, and figures out what frames are needed, given a - * projection. - */ -public class DTEDCacheHandler { - /** Default frame cache size. */ - public final static int FRAME_CACHE_SIZE = 20; - /** Subframe pixel height and width. */ - public final static int SF_PIXEL_HW = 200; - /** The DTED level 0, 1 directory paths. */ - protected String[] paths; - /** The real frame cache. */ - protected DTEDFrameCache frameCache; - protected int frameCacheSize = -1; // No limit. - /** The colors used by the frames to create the images. */ - protected DTEDFrameColorTable colortable; // numColors, reduced - // colortable - - // Setting up the screen... - LatLonPoint ulCoords, lrCoords; - double frameUp, frameDown, frameLeft, frameRight; - double xPixInterval, yPixInterval; // degrees/pixel - int numXSubframes, numYSubframes; - int lastSubframeWidth, lastSubframeHeight; - int currentFrameCacheSize = -10; // guarantees that it - // will changed first - // time. - - // Returning the images... - boolean firstImageReturned = true; - double frameLon = 0.0; - double frameLat = 0.0; - int subx = 0; - int suby = 0; - boolean newframe = false; - DTEDSubframedFrame frame = null; - - /** A description of the drawing attributes of the images. */ - protected DTEDFrameSubframeInfo dfsi = new DTEDFrameSubframeInfo(DTEDFrameSubframe.NOSHADING, DTEDFrameSubframe.DEFAULT_BANDHEIGHT, DTEDFrameSubframe.LEVEL_0, DTEDFrameSubframe.DEFAULT_SLOPE_ADJUST); - - public DTEDCacheHandler() { - this(null, DTEDFrameColorTable.DTED_COLORS, DTEDFrameColorTable.DEFAULT_OPAQUENESS, FRAME_CACHE_SIZE); - } - - public DTEDCacheHandler(String[] dataPaths, int numColors, int opaque) { - this(dataPaths, numColors, opaque, -1); - } - - public DTEDCacheHandler(String[] dataPaths, int numColors, int opaqueness, - int subframe_cache_size) { - - colortable = new DTEDFrameColorTable(numColors, opaqueness, true); - - setFrameCacheSize(subframe_cache_size); - - paths = dataPaths; - frameCache = new DTEDFrameCache(dataPaths, frameCacheSize); - - if (Debug.debugging("dted")) { - Debug.output("DTEDCacheHandler: Created with cache size of " + frameCacheSize); - } - } - - /** - * Normally, the cache grows and shrinks as appropriate according to the - * number of frames needed to cover the screen. If you want to limit the - * size it can grow, set the size. If it's negative, then there will be no - * limit. - */ - public void setFrameCacheSize(int size) { - if (size <= 0) { - frameCacheSize = FRAME_CACHE_SIZE; - } else { - frameCacheSize = size; - } - } - - /** - * Get the limit imposed on the number of frames used in the cache. - */ - public int getFrameCacheSize() { - return frameCacheSize; - } - - /** - * Get an elevation at a point. Always uses the cache to load the frame and - * get the data. - */ - public int getElevation(float lat, float lon) { - return frameCache.getElevation(lat, lon); - } - - /** Setting the subframe attributes. */ - public void setSubframeInfo(DTEDFrameSubframeInfo new_dfsi) { - dfsi = new_dfsi; - if (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING) - colortable.setGreyScale(false); - else - colortable.setGreyScale(true); - } - - /** - * The method to call to let the cache handler know what the projection - * looks like so it can figure out which frames (and subframes) will be - * needed. - * - * @param proj the EqualArc projection of the screen. - */ - public void setProjection(EqualArc proj) { - setProjection(proj, ((Point2D) proj.getUpperLeft()).getY(), ((Point2D) proj.getUpperLeft()).getX(), ((Point2D) proj.getLowerRight()).getY(), ((Point2D) proj.getLowerRight()).getX()); - } - - /** - * The method to call to let the cache handler know what the projection - * looks like so it can figure out which frames (and subframes) will be - * needed. Should be called when the CacheHandler is dealing with just a - * part of the map, such as when the map covers the dateline or equator. - * - * @param proj the EqualArc projection of the screen. - * @param lat1 latitude of the upper left corner of the window, in decimal - * degrees. - * @param lon1 longitude of the upper left corner of the window, in decimal - * degrees. - * @param lat2 latitude of the lower right corner of the window, in decimal - * degrees. - * @param lon2 longitude of the lower right corner of the window, in decimal - * degrees. - */ - public void setProjection(Projection proj, double lat1, double lon1, double lat2, double lon2) { - - ulCoords = new LatLonPoint.Double(lat1, lon1); - lrCoords = new LatLonPoint.Double(lat2, lon2); - - firstImageReturned = true; - - // upper lat of top frame of the screen - // lower lat of bottom frame of the screen - // left lon of left frame of the screen - // upper lon of right frame of the screen - frameUp = Math.floor((double) lat1); - frameDown = Math.floor((double) lat2); - frameLeft = Math.floor((double) lon1); - frameRight = Math.ceil((double) lon2); - - if (Debug.debugging("dted")) - Debug.output("frameUp = " + frameUp + ", frameDown = " + frameDown + ", frameLeft = " - + frameLeft + ", frameRight = " + frameRight); - - int numFramesNeeded; - // Limit the size of the cache, if desired. - if (frameCacheSize > 0) { - numFramesNeeded = frameCacheSize; - if (Debug.debugging("dteddetail")) { - Debug.output("DTEDCacheHandler: frameCacheSize remains at: " + numFramesNeeded); - } - } else { - // calculate how many frames should be in the cache... - numFramesNeeded = (int) (Math.abs(frameUp - frameDown) - * Math.abs(frameRight - frameLeft) * 2); - } - - EqualArc eaProj = null; - boolean isEqualArcProj = proj instanceof EqualArc; - - if (isEqualArcProj) { - eaProj = (EqualArc) proj; - } else { - eaProj = LLXY.convertProjection(proj); - } - - double xpi = 360 / eaProj.getXPixConstant(); - double ypi = 90 / eaProj.getYPixConstant(); - - if (!MoreMath.approximately_equal(xPixInterval, xpi) - || !MoreMath.approximately_equal(yPixInterval, ypi)) { - - // Screen attributes changed!!!! - xPixInterval = xpi; - yPixInterval = ypi; - - // While it changed... - dfsi.xPixInterval = xPixInterval; - dfsi.yPixInterval = yPixInterval; - - // Trap for funky values... - if (xpi == 0 || ypi == 0) { - numXSubframes = 0; - numYSubframes = 0; - return; - } - - int frame_width = (int) Math.ceil(1.0 / xpi); - int frame_height = (int) Math.ceil(1.0 / ypi); - - /* - * There is some weird projection parameter stuff going on when the - * projection is not equal arc, the subframe placement isn't quite - * being set up right. Some subframes are getting misplaced. To work - * around this, since I don't have time/money to really look at it, - * we're going to make one subframe for non-equal-arc projections - * and let the OMWarpingImage handle it. The DTEDFrameSubframe has - * also been modified to make the bounds of the subframe the entire - * image for non-EA projections. - */ - if (!isEqualArcProj) { - numXSubframes = 1; - numYSubframes = 1; - lastSubframeHeight = frame_height; - lastSubframeWidth = frame_width; - } else { - - // Even number of subframes in frame - numXSubframes = frame_width / SF_PIXEL_HW; - lastSubframeWidth = SF_PIXEL_HW; - numYSubframes = frame_height / SF_PIXEL_HW; - lastSubframeHeight = SF_PIXEL_HW; - - if (frame_width % SF_PIXEL_HW != 0) { - lastSubframeWidth = frame_width - (numXSubframes * SF_PIXEL_HW); - numXSubframes++; - } - if (frame_height % SF_PIXEL_HW != 0) { - lastSubframeHeight = frame_height - (numYSubframes * SF_PIXEL_HW); - numYSubframes++; - } - } - currentFrameCacheSize = numFramesNeeded; - - frameCache.resizeCache(numFramesNeeded, numXSubframes, numYSubframes); - if (Debug.debugging("dteddetail")) { - Debug.output("DTEDCacheHandler: frameCacheSize set to: " + numFramesNeeded); - } - - if (Debug.debugging("dted")) - Debug.output("***** Screen Parameters Changed! \n" + " Frame width (pix) = " - + frame_width + "\n" + " Frame height (pix) = " + frame_height + "\n" - + " Num x subframes = " + numXSubframes + "\n" + " Num y subframes = " - + numYSubframes + "\n" + " last sf width = " + lastSubframeWidth + "\n" - + " last sf height = " + lastSubframeHeight + "\n" + " X pix interval = " - + xpi + "\n" + " Y pix interval = " + ypi + "\n"); - - } else if (Math.abs(numFramesNeeded - currentFrameCacheSize) > numFramesNeeded / 2) { - currentFrameCacheSize = numFramesNeeded; - frameCache.resizeCache(numFramesNeeded); - if (Debug.debugging("dteddetail")) { - Debug.output("DTEDCacheHandler: frameCacheSize set to: " + numFramesNeeded); - } - } - } - - /** - * Returns the next OMRaster image. When setProjection() is called, the - * cache sets the projection parameters it needs, and also resets this - * popping mechanism. When this mechanism is reset, you can keep calling - * this method to get another subframe image. When it returns a null value, - * it is done. It will automatically skip over window frames it doesn't - * have, and return the next one it does have. It traverses from the top - * left to right frames, and top to bottom for each column of frames. It - * handles all the subframes for a frame at one time. - * - * @param proj current projection. - * @return OMGraphic image, projected if not null. - */ - public OMGraphic getNextImage(Projection proj) { - - OMGraphic subframe = null; - - // Subframe coordinates and height and width - // upper left, lower right - double sf_ullat, sf_ullon, sf_lrlat, sf_lrlon; - long sf_width = SF_PIXEL_HW; - long sf_height = SF_PIXEL_HW; - - if (Debug.debugging("dted")) - Debug.output("--- DTEDCacheHandler: getNextImage:"); - - while (true) { - - if (firstImageReturned == true) { - frameLon = frameLeft; - frameLat = frameDown; - subx = 0; - suby = 0; - newframe = true; - firstImageReturned = false; - } else { - if (frame != null && subx < numXSubframes) { - // update statics to look for next subframe - if (suby < numYSubframes - 1) - suby++; - else { - suby = 0; - subx++; - } - } else if (frameLon < frameRight) { - // update statics to look for next frame - subx = 0; - suby = 0; - if (frameLat < frameUp) - frameLat++; - else { - frameLat = frameDown; - frameLon++; - } - newframe = true; - } else { // bounds exceeded, all done - return (OMRaster) null; - } - } - - if (newframe && frameLon < frameRight) { - if (Debug.debugging("dted")) - Debug.output(" gni: Getting new frame Lat = " + frameLat + " Lon = " + frameLon); - - frame = frameCache.get(frameLat, frameLon, dfsi.dtedLevel); - } - - // Figure out subframe lat/lon and height/width - if (frame != null) { - - newframe = false; - if (subx == (numXSubframes - 1)) - sf_width = lastSubframeWidth; - if (suby == (numYSubframes - 1)) - sf_height = lastSubframeHeight; - // width/height degrees are spacers - degrees to - // subframe within the frame. sf_height/width_degrees - // are the lat/lon of the frame corner. - double sf_width_degrees = (double) sf_width * xPixInterval; - double sf_height_degrees = (double) sf_height * yPixInterval; - double width_degrees = (double) SF_PIXEL_HW * xPixInterval; - double height_degrees = (double) SF_PIXEL_HW * yPixInterval; - - sf_ullat = (double) (frameLat + 1.0) - ((double) suby * height_degrees); - sf_ullon = (double) frameLon + ((double) subx * width_degrees); - sf_lrlat = (double) (frameLat + 1.0) - ((double) suby * height_degrees) - - sf_height_degrees; - sf_lrlon = (double) frameLon + ((double) subx * width_degrees) + sf_width_degrees; - - if ((ulCoords.getY() > sf_lrlat && lrCoords.getY() < sf_ullat) && - - (ulCoords.getX() < sf_lrlon && lrCoords.getX() > sf_ullon) && - - subx < numXSubframes) { - - dfsi.height = (int) sf_height; - dfsi.width = (int) sf_width; - dfsi.lon = (float) sf_ullon; - dfsi.lat = (float) sf_ullat; - dfsi.subx = subx; - dfsi.suby = suby; - - if (Debug.debugging("dteddetail")) { - Debug.output(" gni: Looking for Subframe " + subx + ", " + suby); - } - - subframe = frame.getSubframeImage(dfsi, colortable, proj); - - if (subframe != null) { - if (Debug.debugging("dted")) { - Debug.output(" gni: Subframe " + subx + ", " + suby + " found :)"); - } - return subframe; - } - } else if (Debug.debugging("dteddetail")) { - Debug.output(" gni: Subframe " + subx + ", " + suby - + " didn't meet screen criteria"); - } - } - sf_width = SF_PIXEL_HW; - sf_height = SF_PIXEL_HW; - } - } - - /** - * Get the colortable being used to color the frames. - * - * @return DTEDFrameColorTable - */ - public DTEDFrameColorTable getColortable() { - return colortable; - } - - /** - * Set the DTEDFrameColorTable used by the handler. If you pass in a null - * value, a default colortable will be inserted. - * - * @param colorT - */ - public void setColortable(DTEDFrameColorTable colorT) { - if (colorT == null) { - colortable = new DTEDFrameColorTable(DTEDFrameColorTable.DTED_COLORS, DTEDFrameColorTable.DEFAULT_OPAQUENESS, true); - } else { - colortable = colorT; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheManager.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheManager.java deleted file mode 100644 index 97ef71a1a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCacheManager.java +++ /dev/null @@ -1,329 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDCacheManager.java,v $ -// $RCSfile: DTEDCacheManager.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/12/09 21:09:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The DTEDCacheManager is the object you need if you want to retrieve DTED - * files en masse for display. You set it up with the paths to the files, and - * then ask it for an OMGraphicList that contains the frames for a geographical - * area. - *

- * The DTEDCacheManager also manages objects called DTEDCacheHandlers. Cache - * handlers have their own set of frames, figure out which frames are needed to - * fill the screen, and ask each frame for the rasters (subframes). The - * situation gets pretty tricky when the screen has the equator and/or the - * dateline on it, and a different cache handler is needed for each quadrant of - * the earth. This situation is relatively rare, though, and the - * DTEDCacheManager automatically checks for these situations and creates the - * cache handlers needed. - *

- * There are two calls to the Cache that you need to use. The constructor sets - * up the cache with the location of the data on your system. The getRectangle() - * call returns an OMGraphicList of objects to draw, that cover the area asked - * for. - */ -public class DTEDCacheManager { - /** - * The size of the smaller caches, when more cachehandlers are needed to - * cover the equator and the dateline. - */ - public final static int SMALL_CACHE_SIZE = 20; - /** A box is a earth quadrant. */ - public final static int MAX_NUM_BOXES = 4; - - /** - * The cache handlers needed to cover the screen. Need one for each earth - * quadrant, and for each DTED directory, in case coverage is spread out - * over different sources. - */ - protected DTEDCacheHandler[] caches = new DTEDCacheHandler[MAX_NUM_BOXES]; - - protected DTEDFrameSubframeInfo subframeInfo; - protected String[] dtedDirPaths; - - // for cache constructors - protected int numColors; - protected int opaqueness = DTEDFrameColorTable.DEFAULT_OPAQUENESS; - protected int cacheSize = DTEDCacheHandler.FRAME_CACHE_SIZE; - - /** - * Constructor that uses the default paths and the default number of colors. - */ - public DTEDCacheManager() { - this(null, DTEDFrameColorTable.DTED_COLORS, DTEDFrameColorTable.DEFAULT_OPAQUENESS); - } - - /** - * Constructor that lets you set the paths of the DTED directories, where - * the data is located. - * - * @param DTEDPaths pathnames to the DTED directories. - */ - public DTEDCacheManager(String[] DTEDPaths) { - this(DTEDPaths, DTEDFrameColorTable.DTED_COLORS, DTEDFrameColorTable.DEFAULT_OPAQUENESS); - } - - /** - * Constructor that lets you set the paths of the DTED directories, where - * the data is located, as well as the number of colors you want used in the - * graphics. - * - * @param DTEDPaths pathnames to the DTED level 0 and 1 directories. - * @param num_colors number of colors to be used in the graphics. - * @param opaque the opaqueness of the dted images, 0 - 255 (0 is clear) - */ - public DTEDCacheManager(String[] DTEDPaths, int num_colors, int opaque) { - dtedDirPaths = DTEDPaths; - numColors = num_colors; - opaqueness = opaque; - } - - /** - * Used to set the DTED directory paths. - * - * @param paths DTED Level 0 and 1 directory paths. - */ - public void setDtedDirPaths(String[] paths) { - dtedDirPaths = paths; - resetCaches(); - } - - /** - * Reset the DTEDCacheHandler array so the handlers will get created on the - * next frame request. - */ - public void resetCaches() { - caches = new DTEDCacheHandler[MAX_NUM_BOXES]; - } - - /** - * Set the number of frames that the caches should contain. If negative or - * zero, the cache calculates the cache size based on the projection. - */ - public void setCacheSize(int size) { - cacheSize = size; - } - - /** - * Get the number of frames that the caches should contain. If negative or - * zero, the cache is calculating the cache size based on the projection. - */ - public int getCacheSize() { - return cacheSize; - } - - /** - * Get an elevation at a point. Always uses the main cache to load the frame - * and get the data. - * - * @param lat latitude of point in decimal degrees. - * @param lon longitude of point in decimal degrees. - */ - public int getElevation(float lat, float lon) { - if (caches[0] == null) { - caches[0] = new DTEDCacheHandler(dtedDirPaths, numColors, opaqueness); - caches[0].setSubframeInfo(subframeInfo); - } - return caches[0].getElevation(lat, lon); - } - - public void setSubframeInfo(DTEDFrameSubframeInfo dfsi) { - subframeInfo = dfsi; - for (int i = 0; i < MAX_NUM_BOXES; i++) { - if (caches[i] != null) - caches[i].setSubframeInfo(dfsi); - } - } - - public DTEDFrameSubframeInfo getSubframeInfo() { - return subframeInfo; - } - - /** - * The call to the cache that lets you choose what kind of information is - * returned. This function also figures out what part of the earth is - * covered on the screen, and creates auxillary cache handlers as needed. - * - * @param proj The projection of the screen (CADRG). - * @return List of rasters to display. - */ - public OMGraphicList getRectangle(Projection proj) { - - float[] lat = new float[3]; - float[] lon = new float[3]; - - // This next bit of mumbo jumbo is to handle the equator and - // dateline: Worst case, crossing both, treat each area - // separately, so it is the same as handling four requests for - // data - above and below the equator, and left and right of - // the dateline. Normal case, there is only one box. Two - // boxes if crossing only one of the boundaries. - - int xa = 2; - int ya = 2; - int lat_minus = 2; - int lon_minus = 2; - // Set up checks for equator and dateline - Point2D ll1 = proj.getUpperLeft(); - Point2D ll2 = proj.getLowerRight(); - - lat[0] = (float) ll1.getY(); - lon[0] = (float) ll1.getX(); - lat[1] = (float) ll2.getY(); - lon[1] = (float) ll2.getX(); - lat[2] = (float) ll2.getY(); - lon[2] = (float) ll2.getX(); - - if (lon[0] > 0 && lon[2] < 0) { - lon[1] = -179.999f; // put a little breather on the - // dateline - lon_minus = 1; - } - if (lat[0] > 0 && lat[2] < 0) { - lat[1] = -0.0001f; // put a little breather on the equator - lat_minus = 1; - } - - if (Debug.debugging("dteddetail")) { - Debug.output("For :"); - Debug.output("lat[0] " + lat[0]); - Debug.output("lon[0] " + lon[0]); - Debug.output("lat[1] " + lat[1]); - Debug.output("lon[1] " + lon[1]); - Debug.output("lat[2] " + lat[2]); - Debug.output("lon[2] " + lon[2]); - Debug.output("lat_minus = " + lat_minus); - Debug.output("lon_minus = " + lon_minus); - } - - /* - * Look at all the paths if needed. Worst case, there are four boxes on - * the screen. Best case, there is one. The things that create boxes and - * dictates how large they are are the equator and the dateline. When - * the screen straddles one or both of these lat/lon lines, lon_minus - * and lat_minus get adjusted, causing two or four different calls to - * the tochandler to get the data above/below the equator, and - * left/right of the dateline. Plus, each path gets checked until the - * required boxes are filled. - */ - - if (caches[0] == null) { - caches[0] = new DTEDCacheHandler(dtedDirPaths, numColors, opaqueness, cacheSize); - caches[0].setSubframeInfo(subframeInfo); - } - - caches[0].setProjection(proj, lat[ya - lat_minus], lon[xa - lon_minus], lat[ya], lon[xa]); - - // Dateline split - if (lon_minus == 1) { - if (caches[1] == null) { - caches[1] = new DTEDCacheHandler(dtedDirPaths, numColors, opaqueness, cacheSize); - caches[1].setSubframeInfo(subframeInfo); - } - - caches[1].setProjection(proj, lat[ya - lat_minus], lon[0], lat[ya], -1f * lon[1]); // -1 - // to - // make - // it - // 180 - } else - caches[1] = null; - - // Equator Split - if (lat_minus == 1) { - if (caches[2] == null) { - caches[2] = new DTEDCacheHandler(dtedDirPaths, numColors, opaqueness, cacheSize); - caches[2].setSubframeInfo(subframeInfo); - } - - caches[2].setProjection(proj, lat[0], lon[xa - lon_minus], -1f * lat[1], // flip - // breather - lon[xa]); - } else - caches[2] = null; - - // Both!! - if (lon_minus == 1 && lat_minus == 1) { - if (caches[3] == null) { - caches[3] = new DTEDCacheHandler(dtedDirPaths, numColors, opaqueness, cacheSize); - caches[3].setSubframeInfo(subframeInfo); - } - - caches[3].setProjection(proj, lat[0], lon[0], -1f * lat[1],// flip - // breather - -1f * lon[1]);// -1 to make it 180, not -180 - } else - caches[3] = null; - - OMGraphicList graphics = new OMGraphicList(); - - if (Debug.debugging("dted")) - Debug.output("--- DTEDCacheManager: getting images: ---"); - - for (int nbox = 0; nbox < MAX_NUM_BOXES; nbox++) { - if (caches[nbox] != null) { - OMGraphic image = caches[nbox].getNextImage(proj); - while (image != null) { - graphics.add(image); - image = caches[nbox].getNextImage(proj); - } - } - } - return graphics; - } - - public void setNumColors(int numberOfColors) { - numColors = numberOfColors; - } - - public int getNumColors() { - return numColors; - } - - public void setOpaqueness(int setting) { - opaqueness = setting; - } - - public int getOpaqueness() { - return opaqueness; - } - - /** - * The DTEDCacheManager uses four DTEDCacheHandlers to create frame from - * DTED files. The one at postion 0 is the main one. The one at index 1 is - * used when the map cross the equator. The other two are used when the map - * crosses the dateline. - * - * @return gets the array of DTEDCacheHandlers. - */ - public DTEDCacheHandler[] getCaches() { - return caches; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageLayer.java deleted file mode 100644 index 795504133..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageLayer.java +++ /dev/null @@ -1,236 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageLayer.java,v $ -// $RCSfile: DTEDCoverageLayer.java,v $ -// $Revision: 1.3.2.2 $ -// $Date: 2004/10/14 18:27:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -/* Java Core */ -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * This is a Layer that provides coverage information on the DTED data. There is - * a palette for this layer, that lets you turn off the coverage for different - * levels of DTED. Right now, only level 0, 1 and 2 are handled. - * - *

- * 
- *  The properties for this file are:
- *  
- *  # Java DTED properties
- *  dtedcov.class=com.bbn.openmap.layer.dted.DTEDCoverageLayer
- *  dtedcov.prettyName=DTED Coverage
- *  # This property should reflect the paths to the DTED directories
- *  dtedcov.paths=/tmp/data/dted
- *  
- *  # coverage cache file, will be created if it doesn't exist
- *  dtedcov.coverageFile=local_path_to_file
- *  # Using property prefix, append 0, 1, 2 to prefix for drawing attributes.  In this example, dtedcov is prefix
- *  #dtedcov0.(drawing attribute properties affect level 0 coverage rendering)
- *  #dtedcov1.(drawing attribute properties affect level 1 coverage rendering)
- *  #dtedcov2.(drawing attribute properties affect level 2 coverage rendering)
- * 
- * 
- */ -public class DTEDCoverageLayer extends OMGraphicHandlerLayer { - - /** The paths to the DTED directories, telling where the data is. */ - protected String[] paths; - - protected DTEDCoverageManager coverageManager = null; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DTEDCoverageLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - } - - /** Method that sets all the variables to the default values. */ - protected void setDefaultValues() { - paths = null; - } - - /** - * Set all the DTED properties from a properties object. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - setDefaultValues(); - - String propPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String[] pathStrings = PropUtils.initPathsFromProperties(properties, propPrefix - + DTEDLayer.DTEDPathsProperty); - - if (pathStrings != null) { - paths = pathStrings; - - coverageManager = new DTEDCoverageManager(paths); - coverageManager.setProperties(prefix, properties); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - - if (coverageManager != null) { - coverageManager.getProperties(props); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - if (paths != null) { - StringBuilder sBuilder = new StringBuilder(); - for (String path : paths) { - if (sBuilder.length() != 0) { - sBuilder.append(";"); - } - sBuilder.append(path); - } - props.put(prefix + DTEDLayer.DTEDPathsProperty, sBuilder.toString()); - } - - return props; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the dtedcov. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public synchronized OMGraphicList prepare() { - - Debug.message("basic", getName() - + "|DTEDCoverageLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - Projection projection = getProjection(); - // call getRectangle(); - if (Debug.debugging("dtedcov")) { - Debug.output(getName() + "|DTEDCoverageLayer.prepare(): " - + "calling prepare with projection: " + projection - + " ul = " + projection.getUpperLeft() + " lr = " - + projection.getLowerRight()); - } - - // IF the coverage manager has not been set up yet, do it! - if (coverageManager == null) { - coverageManager = new DTEDCoverageManager(paths); - - if (Debug.debugging("dtedcov")) { - Debug.output(getName() - + "|DTEDCoverageLayer.prepare(): created DTEDCoverageManager"); - } - } - - return coverageManager.getCoverageRects(projection); - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - JPanel panel = null; - if (coverageManager != null) { - panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - panel.setLayout(gridbag); - - Component gui = coverageManager.getGUI(this); - c.gridx = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.BOTH; - c.weightx = 1.0f; - c.weighty = 1.0f; - gridbag.setConstraints(gui, c); - panel.add(gui); - c.fill = GridBagConstraints.HORIZONTAL; - c.weighty = 0f; - String interString = i18n.get(DTEDCoverageManager.class, - "reset", - "Reset"); - JButton reset = new JButton(interString); - reset.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - coverageManager.reset(); - doPrepare(); - } - }); - gridbag.setConstraints(reset, c); - panel.add(reset); - } - return panel; - } - - public String[] getPaths() { - return paths; - } - - public void setPaths(String[] paths) { - this.paths = paths; - if (coverageManager != null) { - coverageManager.reset(); - coverageManager = null; - } - } - - public DTEDCoverageManager getCoverageManager() { - return coverageManager; - } - - public void setCoverageManager(DTEDCoverageManager coverageManager) { - this.coverageManager = coverageManager; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageManager.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageManager.java deleted file mode 100644 index 17f5ced7b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDCoverageManager.java +++ /dev/null @@ -1,545 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageManager.java,v $ -// $RCSfile: DTEDCoverageManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -/* Java Core */ -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.wanderer.Wanderer; -import com.bbn.openmap.util.wanderer.WandererCallback; - -/** - * A DTEDCoverageManager knows how to look at DTED data and figure out what - * coverage is available. - */ -public class DTEDCoverageManager extends OMGraphicList implements PropertyConsumer { - - protected I18n i18n = Environment.getI18n(); - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.dted.DTEDCoverageManager"); - - protected String[] paths; - - /** The default line color for level 0. */ - public final static String DEFAULT_LEVEL0_COLOR_STRING = "CE4F3F"; // redish - /** The default line color for level 1. */ - public final static String DEFAULT_LEVEL1_COLOR_STRING = "339159"; // greenish - /** The default line color for level 2. */ - public final static String DEFAULT_LEVEL2_COLOR_STRING = "0C75D3"; // bluish - - public final static String COVERAGE_FILE_PROPERTY = "coverageFile"; - - /** Coverage for level 0, 1, 2 frames */ - protected boolean[][][] coverage = null; - /** - * CoverageDataFile object handling pre-cached coverage - */ - protected CoverageDataFile coverageFile = null; - - protected DrawingAttributes[] drawingAttributes = null; - protected OMGraphicList[] levelRects = null; - - public DTEDCoverageManager(String[] paths) { - this.paths = paths; - - drawingAttributes = new DrawingAttributes[3]; - drawingAttributes[0] = DrawingAttributes.getDefaultClone(); - drawingAttributes[0].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL0_COLOR_STRING)); - drawingAttributes[1] = DrawingAttributes.getDefaultClone(); - drawingAttributes[1].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL1_COLOR_STRING)); - drawingAttributes[2] = DrawingAttributes.getDefaultClone(); - drawingAttributes[2].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL2_COLOR_STRING)); - - levelRects = new OMGraphicList[3]; - levelRects[0] = new OMGraphicList(); - levelRects[1] = new OMGraphicList(); - levelRects[2] = new OMGraphicList(); - } - - public void reset() { - coverage = null; - clear(); - } - - /** - * The method that cycles through all the paths, looking for the frames. - * This takes time, so it's only done when a coverage file can't be found. - * - * @param paths paths to the level 0, 1 and 2 dted root directory. - */ - public boolean[][][] checkOutCoverage(String[] paths) { - - if (paths == null || paths.length == 0) { - logger.warning("No paths for DTED data given."); - return null; - } - - logger.fine("checking out DTED at paths:"); - for (int d1 = 0; d1 < paths.length; d1++) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(" " + paths[d1]); - } - if (!BinaryFile.exists(paths[d1])) { - paths[d1] = null; - logger.fine(" - path invalid, ignoring."); - } - } - - CoverageWandererCallback callback = new CoverageWandererCallback(); - Wanderer wanderer = new Wanderer(callback); - - for (int pathNum = 0; pathNum < paths.length; pathNum++) { - wanderer.handleEntry(new File(paths[pathNum])); - } - - return callback.getCoverage(); - } - - /** - * Method organizes the query based on the projection, and returns the - * applicable rectangles representing the frame coverage. If the coverage - * spans over the date line, then two queries are performed, one for each - * side of the date line. - * - * @param proj the projection of the screen - * @return an array of lists, one for each level of dted data. - */ - public OMGraphicList getCoverageRects(Projection proj) { - - if (coverage == null) { - - if (coverageFile != null) { - coverage = coverageFile.readCoverage(); - } - - if (coverage == null) { - logger.fine("Scanning for frames - This could take several minutes!"); - coverage = checkOutCoverage(paths); - - if (coverageFile != null) { - coverageFile.writeFile(coverage); - } - } - } - - if (isEmpty()) { - getCoverageRects(-180, -90, 179, 89, OMGraphic.LINETYPE_RHUMB, proj); - } else { - generate(proj); - } - return this; - } - - /** - * Get a percentage value of how much of the map is covered for a - * projection. - * - * @param proj - * @return float[] with percentages, float[0] is level 0 coverage, 1 is - * level 1, 2 is level 2. - */ - public float[] getCoverage(Projection proj) { - float[] ret = new float[3]; - if (coverage != null) { - Point pnt1 = new Point(); - Point pnt2 = new Point(); - int height = proj.getHeight(); - int width = proj.getWidth(); - // Number frames possible on map - int total = 0; - for (int x = -180; x < 180; x++) { - for (int y = -90; y < 89; y++) { - proj.forward((float) y, (float) x, pnt1); - proj.forward((float) (y + 1), (float) (x + 1), pnt2); - - double x1 = pnt1.getX(); - double y1 = pnt1.getY(); - double x2 = pnt2.getX(); - double y2 = pnt2.getY(); - - boolean someX = (x1 >= 0 && x1 <= width) || (x2 >= 0 && x2 <= width); - boolean someY = (y1 >= 0 && y1 <= height) || (y2 >= 0 && y2 <= height); - - boolean onMap = someX && someY; - - if (onMap) { - int xIndex = x + 180; - int yIndex = y + 90; - total++; - if (coverage[0][yIndex][xIndex]) - ret[0] += 1f; - if (coverage[1][yIndex][xIndex]) - ret[1] += 1f; - if (coverage[2][yIndex][xIndex]) - ret[2] += 1f; - } - } - } - - logger.info("Total frames: " + total + " " + ret[0] + ", " + ret[1] + ", " + ret[2]); - - ret[0] = ret[0] / total * 100f; - ret[1] = ret[1] / total * 100f; - ret[2] = ret[2] / total * 100f; - } - return ret; - } - - /** - * Method looks at the coverage arrays, and returns the applicable - * rectangles representing the frame coverages. - * - * @param startx the western-most longitude. - * @param starty the southern-most latitude. - * @param endx the eastern-most longitude. - * @param endy the northern-most latitude. - * @param lineType the type of line to use on the rectangles - Cylindrical - * projections can use straight lines, but other projections should - * use Rhumb lines. - * @return an array of lists, one for each level of dted data. - */ - public OMGraphicList getCoverageRects(int startx, int starty, int endx, int endy, int lineType, - Projection proj) { - clear(); - OMRect rect; - - for (int level = 0; level < 3; level++) { - - OMGraphicList rectangles = levelRects[level]; - rectangles.clear(); - rectangles.setVague(true); - - for (int lat = starty; lat <= endy && lat < 90; lat++) { - for (int lon = startx; lon <= endx && lon < 180; lon++) { - if (coverage[level][lat + 90][lon + 180]) { - - double offset = level * .1; - double up = lat + offset; - double left = lon + offset; - double down = lat + 1.0 - offset; - double right = lon + 1.0 - offset; - - rect = new OMRect(up, left, down, right, lineType); - drawingAttributes[level].setTo(rect); - rect.generate(proj); - rectangles.add(rect); - } - } - } - add(rectangles); - } - - return this; - } - - ////// PropertyConsumer methods - - protected String prefix; - - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - for (DrawingAttributes atts : drawingAttributes) { - atts.getProperties(getList); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - if (coverageFile != null) { - getList.put(prefix + COVERAGE_FILE_PROPERTY, coverageFile.getAbsolutePath()); - } - - if (paths != null) { - StringBuilder sBuilder = new StringBuilder(); - for (String path : paths) { - if (sBuilder.length() != 0) { - sBuilder.append(";"); - } - sBuilder.append(path); - } - getList.put(prefix + DTEDLayer.DTEDPathsProperty, sBuilder.toString()); - } - - return getList; - } - - public Properties getPropertyInfo(Properties list) { - return list; - } - - public String getPropertyPrefix() { - return prefix; - } - - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - drawingAttributes[0].setProperties(prefix + "0", setList); - drawingAttributes[1].setProperties(prefix + "1", setList); - drawingAttributes[2].setProperties(prefix + "2", setList); - - String coverageFileString = setList.getProperty(prefix + COVERAGE_FILE_PROPERTY); - if (coverageFileString != null) { - coverageFile = new CoverageDataFile(coverageFileString); - } - } - - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - ////// end of PropertyConsumer methods - - /** - * @return the coverageFile - */ - public CoverageDataFile getCoverageFile() { - return coverageFile; - } - - /** - * @param coverageFile the coverageFile to set - */ - public void setCoverageFile(CoverageDataFile coverageFile) { - this.coverageFile = coverageFile; - } - - protected JPanel panel; - - public Component getGUI(final OMGraphicHandlerLayer layer) { - if (panel == null) { - panel = new JPanel(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.gridx = 0; - panel.setLayout(gridbag); - - ActionListener aListener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - int level = Integer.parseInt(ae.getActionCommand()); - levelRects[level].setVisible(((JCheckBox) ae.getSource()).isSelected()); - layer.doPrepare(); - } - }; - - for (int level = 0; level < 3; level++) { - - JPanel pane = new JPanel(); - String interString = i18n.get(DTEDCoverageManager.class, "level" + level - + "title", "Level " + level + ": "); - pane.add(new JLabel(interString)); - String showString = i18n.get(DTEDCoverageManager.class, "show", "Show"); - JCheckBox jcb = new JCheckBox(showString, levelRects[level].isVisible()); - jcb.addActionListener(aListener); - jcb.setActionCommand(Integer.toString(level)); - pane.add(jcb); - pane.add(drawingAttributes[level].getGUI()); - c.gridy = level; - gridbag.setConstraints(pane, c); - panel.add(pane); - } - } - - return panel; - } - - /** - * WandererCallback class that provides coverage array based on existance of - * DTED frames. - * - * @author dietrick - */ - static class CoverageWandererCallback implements WandererCallback { - - boolean[][][] cov; - protected int curLon = Integer.MAX_VALUE; - - CoverageWandererCallback() { - cov = new boolean[3][180][360]; - } - - public boolean handleDirectory(File directory) { - String name = directory.getName().toLowerCase(); - char hemi = name.charAt(0); - if (name.length() == 4 && (hemi == 'e' || hemi == 'w')) { - try { - // Get the longitude index right, use hemi to set the +/-, - // and - // then add 180 to get indexy. - curLon = (hemi == 'w' ? -1 : 1) * Integer.parseInt(name.substring(1)) + 180; - - } catch (NumberFormatException nfe) { - curLon = Integer.MAX_VALUE; - logger.warning("Can't process " + name); - } - } - return true; - } - - public boolean handleFile(File file) { - if (curLon != Integer.MAX_VALUE) { - String name = file.getName().toLowerCase(); - char hemi = name.charAt(0); - char level = name.charAt(name.length() - 1); - if (name.length() == 7 && name.charAt(name.length() - 4) == '.' - && (hemi == 'n' || hemi == 's')) { - - try { - int curLat = (hemi == 's' ? -1 : 1) - * Integer.parseInt(name.substring(1, name.length() - 4)) + 90; - - if (level == '0') { - cov[0][curLat][curLon] = true; - } else if (level == '1') { - cov[1][curLat][curLon] = true; - } else if (level == '2') { - cov[2][curLat][curLon] = true; - } - - } catch (NumberFormatException nfe) { - logger.warning("Can't process " + name); - } - - } - - } - - return true; - } - - boolean[][][] getCoverage() { - return cov; - } - - } - - /** - * Inner class that handles reading and writing coverage cache file. - * - * @author dietrick - */ - public static class CoverageDataFile { - - File coverageFile = null; - - public CoverageDataFile(String path) { - coverageFile = new File(path); - } - - public boolean exists() { - return coverageFile != null && coverageFile.exists(); - } - - public String getAbsolutePath() { - if (coverageFile != null) { - return coverageFile.getAbsolutePath(); - } - - return ""; - } - - public boolean[][][] readCoverage() { - if (exists()) { - - try { - RandomAccessFile raf = new RandomAccessFile(coverageFile, "rw"); - - boolean[][][] coverage = new boolean[3][180][360]; - for (int level = 0; level < 3; level++) { - for (int y = 0; y < 180; y++) { - for (int x = 0; x < 360; x++) { - coverage[level][y][x] = raf.readBoolean(); - } - } - } - raf.close(); - return coverage; - } catch (FileNotFoundException e) { - - } catch (IOException ioe) { - - } - } - return null; - } - - public void writeFile(boolean[][][] coverage) { - try { - RandomAccessFile raf = new RandomAccessFile(coverageFile, "rw"); - - for (int level = 0; level < 3; level++) { - for (int y = 0; y < 180; y++) { - for (int x = 0; x < 360; x++) { - raf.writeBoolean(coverage[level][y][x]); - } - } - } - raf.close(); - } catch (FileNotFoundException e) { - - } catch (IOException ioe) { - - } catch (ArrayIndexOutOfBoundsException aioobe) { - - } - } - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCache.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCache.java deleted file mode 100644 index 4defbf24d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCache.java +++ /dev/null @@ -1,646 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrameCache.java,v $ -// $RCSfile: DTEDFrameCache.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/12/09 21:09:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.dted.DTEDFrameUtil; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The DTEDFrameCache is an object that retrieves DTED paths, frames or - * elevation values, given a latitude, longitude and dted level. It maintains a - * collection of the frames it has already used for quicker access later. The - * size of the cache is user-determined, and the cache also relies on user - * provided paths to the dted directory, which is the top level directory in a - * dted file structure. The paths are provided in a String array, so you can - * have data in different places on a system, including a CDROM drive. - */ -public class DTEDFrameCache - extends CacheHandler - implements PropertyConsumer { - /** The elevation value returned if there is no data at a lat/lon. */ - public final static int NO_DATA = -500; - /** - * The maximum DTED level to check for data, given a lat/lon and a path to a - * dted data directory. - */ - public final static int MAX_DTED_LEVEL = 1; - /** An array of strings representing data directory paths. */ - protected String[] dtedDirPaths; - /** - * Number of subframes used by each frame. Calculated by the - * DTEDCacheHandler when it is given a projection. - */ - protected int numXSubframes; // per frame, at the current scale - /** - * Number of subframes used by each frame. Calculated by the - * DTEDCacheHandler when it is given a projection. - */ - protected int numYSubframes; - - public static final String DTEDPathsProperty = "paths"; - public static final String DTEDFrameCacheSizeProperty = "cacheSize"; - - protected String propertyPrefix = null; - - public DTEDFrameCache() { - super(); - } - - /** - * Create the cache with paths to search for frames, and the maximum number - * of frames to keep on hand. Assumes the paths given are for level 0 and 1 - * data. - * - * @param dtedPaths path to the level 0 and level 1 dted directories - * @param max_size max number of frames to keep in the cache.. - */ - public DTEDFrameCache(String[] dtedPaths, int max_size) { - super(max_size); - dtedDirPaths = dtedPaths; - } - - /** - * Set the data paths. - * - * @param paths paths to the dted level 0 and 1 directories. - */ - public void setDtedDirPaths(String[] paths) { - dtedDirPaths = paths; - } - - /** - * A utility to find the path to a dted file, given a lat, lon and a dted - * level. Assumes that paths have been given to the cache. Lat/lons in - * decimal degrees. - * - * @return complete path to file with lat/lon. - * @param lat latitude of point - * @param lon longitude of point - * @param level the dted level wanted (0, 1, 2, 3) - */ - public String findFileName(double lat, double lon, int level) { - - String lonString = DTEDFrameUtil.lonToFileString((float) lon); - String latString = DTEDFrameUtil.latToFileString((float) lat, level); - - String partialFile = "/" + lonString + "/" + latString; - String ret = findFileName(dtedDirPaths, partialFile); - - return ret; - } - - /** - * Method to check the searchPaths for a file. - * - * @param searchPaths an array of dted root directories - * @param partialFile the relative pathname of a dted frame file from the - * dted root. - * @return the name of the file, or null if not found. - */ - protected String findFileName(String[] searchPaths, String partialFile) { - if (searchPaths == null || searchPaths.length == 0) { - return null; - } - - for (int i = 0; i < searchPaths.length; i++) { - String dtedFileName = searchPaths[i] + partialFile; - if (BinaryFile.exists(dtedFileName)) { - return dtedFileName; - } - } - return null; - } - - /** - * Return The Dted Frame, Given A Lat, Lon And Dted Level. - * - * @return Dted frame. - * @param lat latitude of point - * @param lon longitude of point - * @param level the dted level wanted (0, 1, 2) - */ - public DTEDSubframedFrame get(double lat, double lon, int level) { - String name = findFileName(lat, lon, level); - if (name != null) { - return (DTEDSubframedFrame) get(name); - } - return null; - } - - /** - * A private class that makes sure that cached frames get disposed properly. - */ - private static class DTEDCacheObject - extends CacheObject { - /** - * Construct a DTEDCacheObject, just calls superclass constructor - * - * @param id passed to superclass - * @param obj passed to superclass - */ - public DTEDCacheObject(String id, DTEDSubframedFrame obj) { - super(id, obj); - } - - /** - * Calls dispose() on the contained frame, to make it eligible for - * garbage collection. - */ - protected void finalize() { - ((DTEDSubframedFrame) obj).dispose(); - } - } - - /** - * Load a dted frame into the cache, based on the path of the frame as a - * key. - * - * @param key complete path to the frame, as a string. - * @return DTED frame, hidden in a CacheObject. - */ - public CacheObject load(Object key) { - if (key != null) { - String dtedFramePath = key.toString(); - // If it's a DTED level 0 frame, read it all in, - // otherwise, read just what you need. - DTEDSubframedFrame frame = new DTEDSubframedFrame(dtedFramePath, dtedFramePath.endsWith("dt0")); - frame.initSubframes(numXSubframes, numYSubframes); - - if (frame.frame_is_valid) { - return new DTEDCacheObject(dtedFramePath, frame); - } - } - return null; - } - - /** - * This version of resizeCache is for projection changes, where the - * post/pixel spacing of the images has changed, and the images need to be - * rebuilt. The cache size will change based on scale, because more frames - * are needed for smaller scales. If the number of subframes in either - * direction is zero, then the resize becomes non-destructive, which means - * that the frames will not delete their subframes. If the scale of the map - * changes, then the frame subframe sizes need to be recalculated, and a - * destructive resizing is necessary. - * - * @param max_size the maximum number of frames in the cache. - * @param num_x_subframes the number of horizontal subframes in each frame. - * @param num_y_subframes the number of vertical subframes in each frame. - */ - public void resizeCache(int max_size, int num_x_subframes, int num_y_subframes) { - - boolean destructive = false; - - if (num_x_subframes > 0 && num_y_subframes > 0) { - numXSubframes = num_x_subframes; - numYSubframes = num_y_subframes; - destructive = true; - Debug.message("dted", "DTEDFrameCache: destructive resizing"); - } else { - Debug.message("dted", "DTEDFrameCache: passive resizing"); - } - - CacheObject[] oldObjs = objs; - - if (max_size != objs.length && max_size > 0) { - objs = new CacheObject[max_size]; - } - - for (int i = 0; i < objs.length; i++) { - - if (i >= oldObjs.length) { - break; - } - - DTEDCacheObject dco = (DTEDCacheObject) oldObjs[i]; - - if (dco == null) { - // We load from the front to the back 0 -> length - 1; - // Once you hit a null, the rest should be null, too. - objs[i] = null; - continue; - } - - DTEDSubframedFrame frame = (DTEDSubframedFrame) (dco.obj); - dco.cachedTime = 0; - - if (frame == null) { - Debug.output("DTEDFrameCache: No Frame for key!"); - continue; - } - - if (destructive) { - frame.initSubframes(num_x_subframes, num_y_subframes); - } else { - // If it's not destructive, and the size didn't - // change, then just continue through the loop - // resetting the cachedTime for the CacheObjects. - if (oldObjs == objs) { - continue; - } - } - - if (i < oldObjs.length) { - objs[i] = oldObjs[i]; - } else { - objs[i] = null; - } - } - - oldObjs = null; - } - - /** - * This version of resizeCache is for screen size changes, where the number - * of frames kept on hand in the cache must change, but the images - * themselves don't have to because the pixel/posting spacing hasn't changed - * in the projection. The frames already in the cache are re-added to the - * new cache, if the cache size is increasing. If the cache size is - * shrinking, then as many as will fit are added to the new cache. - * - * @param max_size the new size of the cache. - */ - public void resizeCache(int max_size) { - resizeCache(max_size, 0, 0); - } - - /** - * Return the elevation of a lat/lon point, in meters. - * - * @return elevation in meters. - * @param lat in decimal degrees. - * @param lon in decimal degrees. - */ - public int getElevation(float lat, float lon) { - for (int i = /* dted level */2; i >= /* dted level */0; i--) { - DTEDSubframedFrame frame = null; - String dtedFileName = findFileName((double) lat, (double) lon, i); - - if (dtedFileName != null) - frame = (DTEDSubframedFrame) get(dtedFileName); - - if (frame != null) - return (int) frame.elevationAt(lat, lon); - } - return NO_DATA; - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection, and that's why the - * rectangle is defined by the projection parameters. - * - * @param proj the projection describing the wanted area - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - * @return array of elevations, in meters. Spacing depends on the DTED - * level. - */ - public short[][] getElevations(EqualArc proj, int dtedLevel) { - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - - return getElevations((float) ul.getY(), (float) ul.getX(), (float) lr.getY(), (float) lr.getX(), dtedLevel); - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection. Doesn't handle - * projections which cross the dateline - You must handle that yourself by - * making two inquiries. - * - * @param ullat upper latitude, in decimal degrees - * @param ullon left longitude, in decimal degrees - * @param lrlat lower latitude, in decimal degrees - * @param lrlon right longitude, in decimal degrees - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - */ - public short[][] getElevations(float ullat, float ullon, float lrlat, float lrlon, int dtedLevel) { - return getElevations(ullat, ullon, lrlat, lrlon, dtedLevel, null); - } - - /** - * Return the two-dimensional matrix of elevation posts (heights) - * representing coverage of a given geographical rectangle. The matrix - * represents coverage in an Equal Arc projection. Doesn't handle - * projections which cross the dateline - You must handle that yourself by - * making two inquiries. - *

- * This method is slightly different that the one above, because it includes - * a input variable DTEDFrame. There is an inherent problem in the algorithm - * if some of the DTED frames are missing. It's too difficult to calculate - * the size of the return array if you don't know that any frames are - * available. So, you should always use the method above, which calls this - * method with a null refFrame. If some of the DTED frames are missing, then - * this method is called recursively, with a frame to use for calculating - * post spacings at the right time. - * - * @param ullat upper latitude, in decimal degrees - * @param ullon left longitude, in decimal degrees - * @param lrlat lower latitude, in decimal degrees - * @param lrlon right longitude, in decimal degrees - * @param dtedLevel the DTED level (0, 1, 2) to be used, which describes the - * geographicsal spacing between the posts. - * @param refFrame DTEDFrame used to calculate measurements. - * @return array of elevations, in meters. Spacing depends on the DTED - * level. - */ - protected short[][] getElevations(float ullat, float ullon, float lrlat, float lrlon, int dtedLevel, DTEDSubframedFrame refFrame) { - - float upper = ullat; - float lower = lrlat; - float right = lrlon; - float left = ullon; - - // Since matrix indexes depend on these being in the right - // order, we'll double check and flip values, just to make - // sure lower is lower, and higher is higher. - if (ullon > lrlon) { - if (ullon > 0 && lrlon < 0) { - Debug.error("DTEDFrameCache: getElevations: Stradling dateline not handled!"); - return null; - } - right = ullon; - left = lrlon; - } - - if (lrlat > ullat) { - upper = lrlat; - lower = ullat; - } - - // These are the limits of the lat/lons per frame searched - float upperlat = 0; - float upperlon = 0; - float lowerlat = 0; - float lowerlon = 0; - - int xSize = (int) (Math.ceil(right) - Math.floor(left)); - int ySize = (int) (Math.ceil(upper) - Math.floor(lower)); - - // System.out.println("Going with size = " + xSize + "x" + - // ySize); - - int[] xLengths = new int[xSize]; - int[] yLengths = new int[ySize]; - - short[][][][] es = new short[xSize][ySize][][]; - int x, y; - DTEDSubframedFrame frame = null; - boolean needCalc = false; - // Let's march through the frames, bottom to top, left to - // right. - for (x = 0; x < xSize; x++) { - - if (x == 0) - lowerlon = left; - else - lowerlon = (float) Math.floor(left) + (float) x; - - if (x == xSize - 1) - upperlon = right; - else - upperlon = (float) Math.floor(left) + (float) (x + 1); - - for (y = 0; y < ySize; y++) { - - if (y == 0) - lowerlat = lower; - else - lowerlat = (float) Math.floor(lower) + (float) y; - - if (y == ySize - 1) - upperlat = upper; - else - upperlat = (float) Math.floor(lower) + (float) (y + 1); - - DTEDSubframedFrame thisFrame = get(lowerlat, lowerlon, dtedLevel); - - if (thisFrame != null) { - // System.out.println("Getting elev for " + - // upperlat + ", " + - // lowerlon + ", " + - // lowerlat+ ", " + upperlon); - es[x][y] = thisFrame.getElevations(upperlat, lowerlon, lowerlat, upperlon); - xLengths[x] = es[x][y].length; - yLengths[y] = es[x][y][0].length; - frame = thisFrame; - } else { - if (refFrame != null) { - Debug.output("DTEDFrameCache: Missing frames, going to use reference frame"); - // calculate these lengths, since the refFrame - // was set... - int[] indexes = refFrame.getIndexesFromLatLons(upperlat, lowerlon, lowerlat, upperlon); - xLengths[x] = indexes[2] - indexes[0] + 1; - yLengths[y] = indexes[3] - indexes[1] + 1; - - } else { - if (frame != null) { - // Well, we have a frame to do - // calculations on, and we know we need - // to do at least one calculation, so - // might as well go and do this right... - return getElevations(ullat, ullon, lrlat, lrlon, dtedLevel, frame); - } else { - needCalc = true; - } - } - } - } - } - - // refFrame == null, and all the empty frames were found - // before the good ones... - if (needCalc == true && frame != null) - return getElevations(ullat, ullon, lrlat, lrlon, dtedLevel, frame); - - int xLength = 0; - int yLength = 0; - - // Need to figure out how big the returned matrix is! This - // only works if all the frames come back.... - for (x = 0; x < xLengths.length; x++) - xLength += xLengths[x]; - for (y = 0; y < yLengths.length; y++) - yLength += yLengths[y]; - - // System.out.println("Creating a matrix: " + xLength + "x" + - // yLength); - short[][] matrix = new short[xLength][yLength]; - - // Now copy all the little matrixes into the big matrix - int xspacer = 0; - // Through each little matrix in the x direction - for (x = 0; x < es.length; x++) { - int yspacer = 0; - // Through each little matrix in the y direction - for (y = 0; y < es[x].length; y++) { - - // Make sure the frame exists and is found... - if (es[x][y] != null) { - // Through each lon row in each little matrix - for (int i = 0; i < es[x][y].length; i++) { - System.arraycopy(es[x][y][i], 0, matrix[i + xspacer], yspacer, es[x][y][i].length); - } - // On the last one lon column, increase the spacer - // for the - // next little matrix above this one. - yspacer += yLengths[y]; - } else - yspacer += xLengths[y]; - } - // On the last little matrix in the column, increase the - // xspacer for the little matrixes in the next column. - xspacer += xLengths[x]; - } - - return matrix; - } - - /** - * PropertyConsumer method. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * PropertyConsumer method. - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * PropertyConsumer method. - */ - public void setProperties(Properties props) { - setProperties(null, props); - } - - /** - * PropertyConsumer method. - */ - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(this); - - String[] paths = PropUtils.initPathsFromProperties(props, prefix + DTEDPathsProperty); - - setDtedDirPaths(paths); - - resetCache((int) PropUtils.intFromProperties(props, prefix + DTEDFrameCacheSizeProperty, DTEDCacheHandler.FRAME_CACHE_SIZE)); - - } - - /** - * PropertyConsumer method. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + DTEDFrameCacheSizeProperty, Integer.toString(getCacheSize())); - - // find out paths... - String[] p; - String prop = null; - - StringBuffer pathString = new StringBuffer(); - if (dtedDirPaths != null && dtedDirPaths.length > 0) { - for (String path : dtedDirPaths) { - if (pathString.length() > 0) { - pathString.append(';'); - } - - pathString.append(path); - } - } - props.put(prefix + prop, pathString.toString()); - - return props; - } - - /** - * PropertyConsumer method. - */ - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - props.put(DTEDPathsProperty, "Paths to the DTED directories"); - props.put(DTEDFrameCacheSizeProperty, "Size of the frame cache"); - return props; - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - Debug.output("DTEDFrameCache: Need a path/filename"); - System.exit(0); - } - - Debug.output("DTEDFrameCache: " + args[0]); - DTEDFrameCache dfc = new DTEDFrameCache(args, 10); - - // 35.965065 -121.198715 - // 35.998 36.002 lon -121.002 -120.998 - float ullat = 37.002f; - float ullon = -121.002f; - float lrlat = 35.998f; - float lrlon = -119.998f; - - // System.out.println("Getting elevations for " + - // ullat + ", " + ullon + ", " + - // lrlat + ", " + lrlon); - short[][] e = dfc.getElevations(ullat, ullon, lrlat, lrlon, 0); - if (e != null) { - for (int i = e[0].length - 1; i >= 0; i--) { - int col = 0; - System.out.print("r" + i + "-"); - for (int j = 0; j < e.length; j++) { - System.out.print(e[j][i] + " "); - col++; - } - System.out.println(" - " + col); - } - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCacheLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCacheLayer.java deleted file mode 100644 index 5fdac3068..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameCacheLayer.java +++ /dev/null @@ -1,624 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrameCacheLayer.java,v $ -// $RCSfile: DTEDFrameCacheLayer.java,v $ -// $Revision: 1.10 $ -// $Date: 2005/12/09 21:09:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -/* Java Core */ -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - -import com.bbn.openmap.dataAccess.dted.DTEDConstants; -import com.bbn.openmap.dataAccess.dted.DTEDDirectoryHandler; -import com.bbn.openmap.dataAccess.dted.DTEDFrameCacheHandler; -import com.bbn.openmap.dataAccess.dted.DTEDNameTranslator; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter; -import com.bbn.openmap.omGraphics.grid.GeneratorLoader; -import com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The DTEDFrameCacheLayer fills the screen with DTED data. To view the DTED - * iamges, the projection has to be set in an ARC projection, which OpenMap - * calls the CADRG or LLXY projection. In Gesture mode, clicking on the map will - * cause the DTEDFrameCacheLayer to place a point on the window and show the - * elevation of that point. The Gesture response is not dependent on the scale - * or projection of the screen. - *

- * - * The DTEDFrameCacheLayer uses the DTEDCacheHandler to get the images it needs. - * The DTEDFrameCacheLayer receives projection change events, and then asks the - * cache handler for the images it needs based on the new projection. - * - * The DTEDFrameCacheLayer also relies on properties to set its variables, such - * as the dted frame paths (there can be several at a time), the opaqueness of - * the frame images, number of colors to use, and some other display variables. - * The DTEDFrameCacheLayer properties look something like this: - *

- * - * NOTE: Make sure your DTED file and directory names are in lower case. You can - * use the com.bbn.openmap.layer.rpf.ChangeCase class to make modifications if - * necessary. - *

- * - *

- * 
- * 
- *    #------------------------------
- *    # Properties for DTEDFrameCacheLayer
- *    #------------------------------
- *    
- *    # Level of DTED data to use 0, 1, 2
- *    dted.level=0
- *    
- *    # height (meters or feet) between color changes in band shading
- *    dted.band.height=25
- *    
- *    # Minumum scale to display images. Larger numbers mean smaller scale, 
- *    # and are more zoomed out.
- *    dted.min.scale=20000000
- *    
- *    # Delete the cache if the layer is removed from the map.
- *    dted.kill.cache=true
- *   
- *    # Need to set GeneratorLoaders for DTED rendering.  These properties get
- *    # forwarded on to the DTEDFrameCacheHandler.
- *    dted.generators=greys colors
- *    dted.greys.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader
- *    dted.greys.prettyName=Slope Shading
- *    dted.greys.colorsClass=com.bbn.openmap.omGraphics.grid.GreyscaleSlopeColors
- *    dted.colors.class=com.bbn.openmap.omGraphics.grid.SlopeGeneratorLoader
- *    dted.colors.prettyName=Elevation Shading
- *    dted.colors.colorsClass=com.bbn.openmap.omGraphics.grid.ColoredShadingColors
- *   
- *    #-------------------------------------
- *    # End of properties for DTEDFrameCacheLayer
- *    #-------------------------------------
- * 
- * 
- * 
- * - * @see com.bbn.openmap.util.wanderer.ChangeCase - */ -public class DTEDFrameCacheLayer extends OMGraphicHandlerLayer implements ActionListener, - Serializable, DTEDConstants { - - /** The cache handler. */ - protected transient DTEDFrameCacheHandler cache = new DTEDFrameCacheHandler(null); - protected long minScale = 20000000; - /** Flag to delete the cache if the layer is removed from the map. */ - protected boolean killCache = true; - - public static final String DTEDLevelProperty = "level"; - public static final String DTEDMinScaleProperty = "min.scale"; - public static final String DTEDKillCacheProperty = "kill.cache"; - - private String level0Command = "setLevelTo0"; - private String level1Command = "setLevelTo1"; - private String level2Command = "setLevelTo2"; - - /** The elevation spot used in the gesture mode. */ - DTEDLocation location = null; - - /** - * Instances of this class are used to display elevation labels on the map. - */ - static class DTEDLocation { - OMText text; - OMRect dot; - - public DTEDLocation(int x, int y) { - text = new OMText(x + 10, y, (String) null, (java.awt.Font) null, OMText.JUSTIFY_LEFT); - - dot = new OMRect(x - 1, y - 1, x + 1, y + 1); - text.setLinePaint(java.awt.Color.red); - dot.setLinePaint(java.awt.Color.red); - } - - /** - * Set the text to the elevation text. - * - * @param elevation elevation of the point in meters. - */ - public void setElevation(int elevation) { - // m - ft conversion - if (elevation < -100) - text.setData("No Data Here"); - else { - int elevation_ft = (int) ((float) elevation * 3.280840f); - text.setData(elevation + " m / " + elevation_ft + " ft"); - } - } - - /** Set the x-y location of the combo in the screen */ - public void setLocation(int x, int y) { - text.setX(x + 10); - text.setY(y); - dot.setLocation(x - 1, y - 1, x + 1, y + 1); - } - - public void render(java.awt.Graphics g) { - text.render(g); - dot.render(g); - } - - public void generate(Projection proj) { - text.generate(proj); - dot.generate(proj); - } - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DTEDFrameCacheLayer() { - setMouseModeIDsForEvents(new String[] { "Gestures" }); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - * - * @param dfc paths to the DTED directories that hold level 0 and 1 data. - */ - public DTEDFrameCacheLayer(com.bbn.openmap.dataAccess.dted.DTEDFrameCache dfc) { - this(); - setFrameCache(dfc); - } - - public void setFrameCache(com.bbn.openmap.dataAccess.dted.DTEDFrameCache dfc) { - cache.setFrameCache(dfc); - cache.resetCache(); - } - - public com.bbn.openmap.dataAccess.dted.DTEDFrameCache getFrameCache() { - if (cache != null) { - return cache.getFrameCache(); - } else - return null; - } - - public DTEDFrameCacheHandler getCache() { - return cache; - } - - public void setCache(DTEDFrameCacheHandler cache) { - this.cache = cache; - } - - protected void setDefaultValues() { - // defaults - setMaxScale(20000000); - } - - /** - * Set all the DTED properties from a properties object. - */ - public void setProperties(java.util.Properties properties) { - setProperties(null, properties); - } - - /** - * Set all the DTED properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(this); - - setDtedLevel(PropUtils.intFromProperties(properties, prefix + DTEDLevelProperty, getDtedLevel())); - cache.setProperties(prefix, properties); - - } - - /** - * Called when the layer is no longer part of the map. - */ - public void removed(java.awt.Container cont) { - OMGraphicList rasters = getList(); - if (rasters != null) { - rasters.clear(); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof com.bbn.openmap.dataAccess.dted.DTEDFrameCache) { - setFrameCache((com.bbn.openmap.dataAccess.dted.DTEDFrameCache) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj == getFrameCache()) { - setFrameCache(null); - } - } - - /** - * A flag to keep track of when the first time a warning was put up if the - * projection isn't EquiArc. - */ - protected boolean firstProjectionWarningSent = false; - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the dted. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - */ - public synchronized OMGraphicList prepare() { - - if (cache == null) { - Debug.message("dted", getName() - + "|DTEDFrameCacheLayer can't add anything to map because the DTEDFrameCache has not been set."); - } - - Projection projection = getProjection(); - - if (projection == null) { - Debug.output("DTED Layer needs to be added to the MapBean before it can draw images!"); - return new OMGraphicList(); - } - - // Check to make sure the projection is EqualArc - if (!(projection instanceof EqualArc)) { - if (!firstProjectionWarningSent) { - fireRequestInfoLine(" DTED requires an Equal Arc projection (CADRG/LLXY) to view images."); - Debug.output("DTEDFrameCacheLayer: DTED requires an Equal Arc projection (CADRG/LLXY) to view images."); - firstProjectionWarningSent = true; - } - return new OMGraphicList(); - } - - Debug.message("basic", getName() + "|DTEDFrameCacheLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (Debug.debugging("dted")) { - Debug.output(getName() + "|DTEDFrameCacheLayer.prepare(): " + "calling getRectangle " - + " with projection: " + projection + " ul = " + projection.getUpperLeft() - + " lr = " + projection.getLowerRight()); - } - - OMGraphicList omGraphicList; - - if (projection.getScale() < maxScale) { - omGraphicList = cache.getRectangle((EqualArc) projection); - } else { - fireRequestInfoLine(" The scale is too small for DTED viewing."); - Debug.error("DTEDFrameCacheLayer: scale (1:" + projection.getScale() - + ") is smaller than minimum (1:" + maxScale + ") allowed."); - omGraphicList = new OMGraphicList(); - } - // /////////////////// - // safe quit - int size = 0; - if (omGraphicList != null) { - size = omGraphicList.size(); - Debug.message("basic", getName() + "|DTEDFrameCacheLayer.prepare(): finished with " - + size + " graphics"); - - // Don't forget to project them. Since they are only - // being recalled if the projection has changed, then we - // need to force a reprojection of all of them because the - // screen position has changed. - omGraphicList.project(projection, true); - - } else { - Debug.message("basic", getName() - + "|DTEDFrameCacheLayer.prepare(): finished with null graphics list"); - } - - return omGraphicList; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(java.awt.Graphics g) { - super.paint(g); - - if (location != null) - location.render(g); - location = null; - } - - /** - * Get the value set for which DTED level is being used, 0-2. - */ - public int getDtedLevel() { - if (cache != null) { - return cache.getDtedLevel(); - } else - return LEVEL_0; - } - - public void setDtedLevel(int level) { - if (cache != null) { - cache.setDtedLevel(level); - } - } - - /** - * Get whether the cache will be killed when the layer is removed from the - * map. - */ - public boolean getKillCache() { - return killCache; - } - - public void setKillCache(boolean kc) { - killCache = kc; - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - /** The user interface palette for the DTED layer. */ - protected Box paletteBox = null; - - /** Creates the interface palette. */ - public Component getGUI() { - - if (paletteBox == null) { - if (Debug.debugging("dted")) - Debug.output("DTEDFrameCacheLayer: creating DTED Palette."); - - paletteBox = Box.createVerticalBox(); - Box subbox1 = Box.createHorizontalBox(); - Box subbox3 = Box.createHorizontalBox(); - - // The DTED Level selector - JPanel levelPanel = PaletteHelper.createPaletteJPanel("DTED Level"); - ButtonGroup levels = new ButtonGroup(); - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (cache != null) { - String ac = e.getActionCommand(); - int newLevel; - if (ac.equalsIgnoreCase(level2Command)) - newLevel = LEVEL_2; - else if (ac.equalsIgnoreCase(level1Command)) - newLevel = LEVEL_1; - else - newLevel = LEVEL_0; - setDtedLevel(newLevel); - } - } - }; - - JRadioButton level0 = new JRadioButton("Level 0"); - level0.addActionListener(al); - level0.setActionCommand(level0Command); - JRadioButton level1 = new JRadioButton("Level 1"); - level1.addActionListener(al); - level1.setActionCommand(level1Command); - JRadioButton level2 = new JRadioButton("Level 2"); - level2.addActionListener(al); - level2.setActionCommand(level2Command); - - levels.add(level0); - levels.add(level1); - levels.add(level2); - - switch (getDtedLevel()) { - case 2: - level2.setSelected(true); - break; - case 1: - level1.setSelected(true); - break; - case 0: - default: - level0.setSelected(true); - } - - levelPanel.add(level0); - levelPanel.add(level1); - levelPanel.add(level2); - - // The DTED view selector from DTEDFrameCacheHandler - JPanel viewPanel = PaletteHelper.createPaletteJPanel("View Type"); - viewPanel.add(cache.getGUI()); - - JButton redraw = new JButton("Redraw DTED Layer"); - redraw.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - doPrepare(); - } - }); - - subbox1.add(levelPanel); - subbox1.add(viewPanel); - paletteBox.add(subbox1); - subbox3.add(redraw); - paletteBox.add(subbox3); - } - - return paletteBox; - } - - /** - * Overridden to modify the MapMouseInterpreter used by the layer. - */ - public synchronized MapMouseInterpreter getMouseEventInterpreter() { - if (getMouseModeIDsForEvents() != null && mouseEventInterpreter == null) { - setMouseEventInterpreter(new StandardMapMouseInterpreter(this) { - public boolean leftClick(MouseEvent me) { - super.leftClick(me); - determineLocation(me); - return true; - } - - public boolean leftClick(OMGraphic omg, MouseEvent me) { - super.leftClick(omg, me); - determineLocation(me); - return true; - } - - }); - } - - return mouseEventInterpreter; - } - - public boolean determineLocation(MouseEvent e) { - Projection projection = getProjection(); - if (cache != null && projection != null) { - LatLonPoint ll = projection.inverse(e.getX(), e.getY(), new LatLonPoint.Double()); - location = new DTEDLocation(e.getX(), e.getY()); - location.setElevation(cache.getElevation((float) ll.getY(), (float) ll.getX())); - location.generate(projection); - repaint(); - return true; - } - return false; - } - - /** - * Don't need DTEDFrames highlighting themselves. - */ - public boolean isHighlightable(OMGraphic omg) { - return false; - } - - /** - * This is the easiest way to construct a DTEDFrameCacheLayer programmatically. - * Create the Builder, configure it, and call create() to configure the layer. - */ - - public static class Builder { - List dirHandlers; - List loaders = new ArrayList(); - DTEDNameTranslator nTranslator; - - /** - * Create a builder for a DTEDFrameCacheLayer. - * @param dtedDirectory a path to the dted directory. - */ - public Builder(String dtedDirectory) { - this(new DTEDDirectoryHandler(dtedDirectory)); - } - - /** - * Create a builder for a DTEDFrameCacheLayer. - * - * @param dirHandler don't pass in a null value, things will get ugly. - */ - public Builder(DTEDDirectoryHandler dirHandler) { - dirHandlers = new ArrayList(); - dirHandlers.add(dirHandler); - } - - /** - * If set, this name translator will be added to all directory handlers - * set in this builder. If not called the StandardDTEDNameTranslator - * will be used. - * - * @param translator DTEDNameTranslator. - * @return this builder. - */ - public Builder setNameTranslator(DTEDNameTranslator translator) { - nTranslator = translator; - return this; - } - - /** - * Add a generator loader to the DTEDFrameCache to be used by the layer. - * If not called, the SloperGeneratorLoader will be used. - * - * @param gLoader - * @return this Builder. - */ - public Builder addGeneratorLoader(GeneratorLoader gLoader) { - if (loaders == null) { - loaders = new ArrayList(); - } - if (gLoader != null) { - loaders.add(gLoader); - } - return this; - } - - /** - * Create the DTEDFrameCacheLayer. - * @return the new layer, configured with Builder settings. - */ - public DTEDFrameCacheLayer create() { - com.bbn.openmap.dataAccess.dted.DTEDFrameCache dfc = new com.bbn.openmap.dataAccess.dted.DTEDFrameCache(); - for (DTEDDirectoryHandler dHandler : dirHandlers) { - if (nTranslator != null) { - dHandler.setTranslator(nTranslator); - } - dfc.addDTEDDirectoryHandler(dHandler); - } - - DTEDFrameCacheLayer layer = new DTEDFrameCacheLayer(dfc); - com.bbn.openmap.dataAccess.dted.DTEDFrameCacheHandler dfcHandler = layer.getCache(); - - if (!loaders.isEmpty()) { - dfcHandler.setGeneratorLoaders(loaders); - } else { - dfcHandler.addGeneratorLoader(new SlopeGeneratorLoader()); - } - - dfcHandler.setActiveGeneratorLoader(dfcHandler.getGeneratorLoaders().get(0).getPrettyName()); - - return layer; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameColorTable.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameColorTable.java deleted file mode 100644 index ba6b48697..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameColorTable.java +++ /dev/null @@ -1,300 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrameColorTable.java,v $ -// $RCSfile: DTEDFrameColorTable.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:54 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.Color; - -import com.bbn.openmap.util.Debug; - -/** - * Creates the colors used for displaying the DTED images. The default - * mode is to use greyscale colors. - */ -public class DTEDFrameColorTable { - - public final static int DTED_COLORS = 216; - public final static int NUM_ELEVATION_COLORS = 16; - public final static int DEFAULT_OPAQUENESS = 255; - /** the colors in use right now. */ - public Color[] colors; - /** The colored colortable. */ - protected Color[] ccolors = null; - /** The greyscale colortable. */ - protected Color[] gcolors = null; - /** opaqueness should be a value between 0 (clear) and 255 (opaque) */ - protected int opaqueness = 255; - /** Flag to indicate which colortable to use - color or greys. */ - protected boolean greyScale = true; - /** adjustment is set up for values between 1-5. */ - public int adjustment = 3; - - int[] elevation_color_cutoff = { 0, 50, 100, 200, 400, 800, 1200, 1600, - 2000, 3000, 4000, 6000, 8000, 10000, 12000, 33000 }; - - ////////////////////////////////////////// - ///// OLD settings, for a different feel. - // int[] elevation_color_cutoff = {0, 0, 50, 100, 200, 400, 800, - // 1200, 1600, - // 2000, 3000, 4000, 6000, 8000, 10000, 33000}; - // Bright colors - green - yellow- red - // int[] reds[] = { 191, 10, 56, 96, 112, 128, 160, 208, - // 224, 225, 255, 240, 240, 240, 225, 208}; - // int[] greens[] = {239, 154, 166, 192, 208, 224, 224, 208, - // 224, 236, 186, 176, 144, 112, 96, 80}; - // int[] blues[] = { 255, 0, 0, 0, 0, 0, 0, 0, - // 0, 116, 102, 0, 0, 0, 0, 0}; - ////////////////////////////////////////// - - // Natural kinda colors green-light green-green grey-tan-to white - int[] reds = { 191, 20, 40, 60, 110, 140, 190, 225, 179, 159, 163, 178, - 185, 215, 217, 243 }; - int[] greens = { 239, 95, 102, 128, 153, 175, 200, 200, 158, 142, 152, 165, - 165, 205, 217, 243 }; - int[] blues = { 250, 70, 80, 100, 130, 150, 150, 155, 77, 51, 51, 77, 112, - 140, 217, 230 }; - - /** Default setting is 216 colors, and greyscale. */ - public DTEDFrameColorTable() { - this(216, 255, true); - } - - public DTEDFrameColorTable(int num_colors) { - this(num_colors, 255, true); - } - - public DTEDFrameColorTable(int num_colors, int opaque, boolean greyscale) { - opaqueness = opaque; - ccolors = createColors(num_colors, adjustment); - gcolors = createGreyScaleColors(num_colors); - greyScale = greyscale; - - if (greyScale) - colors = gcolors; - else - colors = ccolors; - } - - public DTEDFrameColorTable(DTEDFrameColorTable cTable) { - opaqueness = cTable.getOpaqueness(); - ccolors = cTable.getCColors(); - gcolors = cTable.getGColors(); - setGreyScale(cTable.getGreyScale()); - - for (int i = 0; i < cTable.colors.length; i++) - colors[i] = cTable.colors[i]; - } - - public int getOpaqueness() { - return opaqueness; - } - - public void setOpaqueness(int opaque) { - int i; - opaqueness = opaque; - Color tc; // tmp color - if (ccolors != null) { - for (i = 0; i < ccolors.length; i++) { - tc = ccolors[i]; - ccolors[i] = new Color(tc.getRed(), tc.getGreen(), tc.getBlue(), opaqueness); - } - } - if (gcolors != null) { - for (i = 0; i < gcolors.length; i++) { - tc = gcolors[i]; - gcolors[i] = new Color(tc.getRed(), tc.getGreen(), tc.getBlue(), opaqueness); - } - } - } - - public Color[] getCColors() { - return ccolors; - } - - public Color[] getGColors() { - return gcolors; - } - - public void setGreyScale(boolean greyscale) { - greyScale = greyscale; - if (greyScale) { - colors = gcolors; - } else { - colors = ccolors; - } - } - - public boolean getGreyScale() { - return greyScale; - } - - public int numColors() { - return colors.length; - } - - public int colorValue(int color_index) { - if ((color_index > 0) && (color_index < colors.length)) - return colors[color_index].getRGB(); - else - return -1; - } - - protected Color[] createGreyScaleColors(int num_colors) { - if (num_colors == 0) { - num_colors = 216; - } - Color[] tempColors = new Color[num_colors]; - - int grey_interval = 256 / num_colors; - - for (int i = 0; i < num_colors; i++) { - - if (i == 0) - tempColors[i] = new Color(191, 239, 255, 0); - - else { - int color = (i * grey_interval) + (grey_interval / 2); - tempColors[i] = new Color(color, color, color, opaqueness); - } - } - return tempColors; - } - - protected Color[] createColors(int num_colors, int adjustment) { - if (num_colors == 0) { - num_colors = 216; - } - Color[] tempColors = new Color[num_colors]; - int ncolors = NUM_ELEVATION_COLORS; - // How many versions of each color to make up, for sloping - int num_loops = 1; - int modifier = (5 - adjustment) * 4; - int red, green, blue; - // Re-adjust the number of colors to match the number of - // colors - // available. - if (num_colors >= NUM_ELEVATION_COLORS * 3) { - ncolors = NUM_ELEVATION_COLORS * 3; - num_loops = 3; - } else if (num_colors >= NUM_ELEVATION_COLORS * 2) { - ncolors = NUM_ELEVATION_COLORS * 2; - num_loops = 2; - } - - tempColors = new Color[ncolors]; - - if (Debug.debugging("dteddetail")) - Debug.output("DTEDFrameColortable: Setting number of colors to " - + ncolors); - - for (int j = 0; j < num_loops; j++) { - if (Debug.debugging("dteddetail")) - Debug.output("dted_raster: Setting round " + j + " of colors."); - // Color the 0 index (and the multiples) to be clear water - tempColors[(NUM_ELEVATION_COLORS * j)] = new Color(191, 239, 255, 0); - - for (int i = 1; i < NUM_ELEVATION_COLORS; i++) { - switch (j) { - case 0: - red = reds[i] - (20 - modifier) / 2; - green = greens[i] - (20 - modifier) / 2; - blue = blues[i] - (20 - modifier) / 2; - tempColors[i] = new Color(red, green, blue, opaqueness); - break; - case 1: - red = reds[i] - (20 - modifier); - green = greens[i] - (20 - modifier); - blue = blues[i] - (20 - modifier); - tempColors[i + NUM_ELEVATION_COLORS] = new Color(red, green, blue, opaqueness); - break; - case 2: - red = reds[i]; - green = greens[i]; - blue = blues[i]; - tempColors[i + (NUM_ELEVATION_COLORS * 2)] = new Color(red, green, blue, opaqueness); - break; - - // These settings are the original ones, where flat - // lands get - // the original color, and slopes are changed color. - // In the - // above settings, the positive slope gets the - // original - // color, the level gets a darker color, and the - // negative - // slope gets a twice darker color. - // case 0: - // colors_[i].red = reds[i]; - // colors_[i].green = greens[i]; - // colors_[i].blue = blues[i]; - // break; - // case 1: - // colors_[i + NUM_ELEVATION_COLORS].red = - // reds[i]-(20-modifier); - // colors_[i + NUM_ELEVATION_COLORS].green = - // greens[i]-(20-modifier); - // colors_[i + NUM_ELEVATION_COLORS].blue = - // blues[i]-(20-modifier); - // break; - // case 2: - // colors_[i + (NUM_ELEVATION_COLORS*2)].red = - // reds[i]+(5);//20-modifier); - // colors_[i + (NUM_ELEVATION_COLORS*2)].green = - // greens[i]+(5);//20-modifier); - // colors_[i + (NUM_ELEVATION_COLORS*2)].blue = - // blues[i]+(5);//20-modifier); - // break; - - default: - break; - } - } - } - return tempColors; - } - - public static void main(String args[]) { - Debug.init(); - if (args.length < 1) { - System.out.println("DTEDFrameColorTable: Need a number."); - System.exit(0); - } - - System.out.println("DTEDFrameColorTable: " + args[0]); - int nColors = new Integer(args[0]).intValue(); - DTEDFrameColorTable ct = new DTEDFrameColorTable(nColors); - System.out.println(ct); - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("DTEDFrameColortable: \n"); - for (int i = 0; i < colors.length; i++) { - s.append("OMColor ").append(i).append(": alpha = ").append(colors[i].getAlpha()); - s.append(", red = ").append(colors[i].getRed()); - s.append(", green = ").append(colors[i].getGreen()); - s.append(", blue = ").append(colors[i].getBlue()).append("\n"); - } - return s.toString(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframe.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframe.java deleted file mode 100644 index 959864b0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframe.java +++ /dev/null @@ -1,259 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrameSubframe.java,v -// $ -// $RCSfile: DTEDFrameSubframe.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:54 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.Color; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.DataBounds; - -public class DTEDFrameSubframe { - // Types of slope shading - /** Empty image. */ - public static final int NOSHADING = 0; - /** Gray scale slope shading, sun from the Northwest. */ - public static final int SLOPESHADING = 1; - /** Banded contour coloring, contour based on meters. */ - public static final int METERSHADING = 2; - /** Banded contour coloring, contour based on feet. */ - public static final int FEETSHADING = 3; - /** Test markings, for the boundary of the subframe. */ - public static final int BOUNDARYSHADING = 4; - /** - * Colorized slope shading. Color bands are based on elevation, and are - * accented by shaded indications. - */ - public static final int COLOREDSHADING = 5; - /** DTED LEVEL 0, 1km posts. */ - public static final int LEVEL_0 = 0; - /** DTED LEVEL 1, 100m posts. */ - public static final int LEVEL_1 = 1; - /** DTED LEVEL 2, 30m posts. */ - public static final int LEVEL_2 = 2; - /** Default height between bands in band views. */ - public static final int DEFAULT_BANDHEIGHT = 25; - /** Default contrast setting for slope shading. */ - public static final int DEFAULT_SLOPE_ADJUST = 3; - - public DTEDFrameSubframeInfo dfsi; - protected ImageCreator imageCreator = null; - - public DTEDFrameSubframe(DTEDFrameSubframeInfo info) { - dfsi = info.makeClone(); - } - - public OMGraphic getImageIfCurrent(Projection proj, DTEDFrameSubframeInfo dfsi) { - if (dfsi.equals(this.dfsi) && imageCreator != null) { - return imageCreator.getImage(proj); - } - - return null; - } - - // public void finalize(){ - // Debug.message("gc", " DTEDFrameSubframe: getting GC'd"); - // } - - public OMGraphic getImage(Projection proj) { - if (imageCreator != null) { - return imageCreator.getImage(proj); - } - return null; - } - - public void setPixels(int[] pixels) { - imageCreator = new Pixels(pixels); - } - - public void setBitsAndColors(byte[] bits, Color[] colors) { - imageCreator = new BitsAndColors(bits, colors); - } - - public abstract class ImageCreator { - /** - * The OMGraphic holding the image. - */ - OMGraphic image; - - /** - * Get the proper OMGraphic given the projection type. - * - * @param proj - * @return a projected OMGraphic for the image. - */ - protected abstract OMGraphic getImage(Projection proj); - - /** - * Set the transparent color index or opaqueness setting, depending on - * color model. - * - * @param opaqueness - */ - protected abstract void setTransparent(int opaqueness); - - } - - /** - * Direct colormodel implementation. - * - * @author ddietrick - */ - public class Pixels - extends ImageCreator { - - int[] pixels = null; - - protected Pixels(int[] pixels) { - this.pixels = pixels; - } - - protected void setTransparent(int opaqueness) { - if (pixels != null) { - for (int i = 0; i < pixels.length; i++) { - pixels[i] = (0x00FFFFFF & pixels[i]) | (opaqueness << 24); - } - // image = null; ?? - } - } - - protected OMGraphic getImage(Projection proj) { - - boolean scaling = proj instanceof EqualArc; - - if (pixels == null || dfsi == null) { - return null; - } - - Point2D projOrigin = proj.forward(dfsi.lat, dfsi.lon); - Point2D otherCorner = new Point2D.Double(); - if (proj instanceof EqualArc) { - projOrigin.setLocation(projOrigin.getX() + dfsi.width, projOrigin.getY() + dfsi.height); - proj.inverse(projOrigin, otherCorner); - } else { - /* - * Working with DTEDCacheHandler to work around non-EqualArc - * projection subframe bounds location problems. For those - * projection types, making one subframe per frame that covers - * the entire degree x degree area. - */ - otherCorner.setLocation(dfsi.lon + 1, dfsi.lat - 1); - } - - if (image == null) { - if (scaling) { - image = - new OMScalingRaster(dfsi.lat, dfsi.lon, otherCorner.getY(), otherCorner.getX(), dfsi.width, - dfsi.height, pixels); - } else { - DataBounds bounds = - new DataBounds(otherCorner.getX(), otherCorner.getY(), (double) dfsi.lon, (double) dfsi.lat); - image = new OMWarpingImage(pixels, dfsi.width, dfsi.height, new LatLonGCT(), bounds); - } - } else { - if (scaling) { - if (!(image instanceof OMScalingRaster)) { - image = - new OMScalingRaster(dfsi.lat, dfsi.lon, otherCorner.getY(), otherCorner.getX(), dfsi.width, - dfsi.height, pixels); - } - } else { - if (image instanceof OMScalingRaster) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } - } - - image.generate(proj); - - return image; - } - - } - - /** - * Indexed colormodel implementation. - * - * @author ddietrick - */ - public class BitsAndColors - extends ImageCreator { - - byte[] bits = null; - Color[] colors = null; - - protected BitsAndColors(byte[] bits, Color[] colors) { - this.bits = bits; - this.colors = colors; - } - - protected void setTransparent(int opaqueness) { - // setTransparent has to be set on the resulting OMScalingRaster and - // regenerated - } - - protected OMGraphic getImage(Projection proj) { - boolean scaling = proj instanceof EqualArc; - - if (bits == null || colors == null || dfsi == null) { - return null; - } - - Point2D projOrigin = proj.forward(dfsi.lat, dfsi.lon); - projOrigin.setLocation(projOrigin.getX() + dfsi.width, projOrigin.getY() + dfsi.height); - Point2D otherCorner = proj.inverse(projOrigin); - - if (image == null) { - image = - new OMScalingRaster(dfsi.lat, dfsi.lon, otherCorner.getY(), otherCorner.getX(), dfsi.width, dfsi.height, - bits, colors, 255); - image.generate(proj); - if (!scaling) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } else { - if (scaling) { - if (!(image instanceof OMScalingRaster)) { - image = - new OMScalingRaster(dfsi.lat, dfsi.lon, otherCorner.getY(), otherCorner.getX(), dfsi.width, - dfsi.height, bits, colors, 255); - } - } else { - if (image instanceof OMScalingRaster) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } - } - image.generate(proj); - - return image; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframeInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframeInfo.java deleted file mode 100644 index 90090a663..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDFrameSubframeInfo.java +++ /dev/null @@ -1,144 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrameSubframeInfo.java,v $ -// $RCSfile: DTEDFrameSubframeInfo.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:54 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.util.HashCodeUtil; - -/** - * The DTEDFrameSubframeInfo contains information about how a subframe image - * ought to be presented. It contains the view settings, and the location of the - * subframe image. - */ -public class DTEDFrameSubframeInfo { - /** - * The type of shading to use in the image. DTEDFrameSubframe has the - * different types of possibilities. - */ - public int viewType; - /** - * The distance (elevation) range that each color section of the band - * viewtype represents. - */ - public int bandHeight; - /** The DTED level of the data. */ - public int dtedLevel; - /** - * A user adjusted setting for contrast for the slope shading. Some areas of - * the earth require different settings, for more or less detail. - */ - public int slopeAdjust; - /** - * The degrees/pixel of the image in the x direction, derived from the scale - * of the projection. - */ - public double xPixInterval; - /** - * The degrees/pixel of the image in the y direction, derived from the scale - * of the projection. - */ - public double yPixInterval; - /** - * x number of the subframe within the DTEDFrame, from the left side of the - * frame (east). - */ - public int subx; - /** - * y number of the subframe within the DTEDFrame, from the bottom side of - * the frame (south). - */ - public int suby; - /** Longitude of the upper left corner of the subframe image. */ - public float lon; - /** Latitude of the upper left corner of the subframe image. */ - public float lat; - /** height of the subframe image. */ - public int height; - /** Width of the subframe image. */ - public int width; - /** - * The colormodel of the images. Use OMRasterObject.COLORMODEL_DIRECT - * (default) or OMRasterObject.COLORMODEL_INDEXED - */ - public int colorModel = OMRasterObject.COLORMODEL_DIRECT; - - public DTEDFrameSubframeInfo(int Vt, int Bh, int Dl, int Sa) { - this(DTEDCacheHandler.SF_PIXEL_HW, DTEDCacheHandler.SF_PIXEL_HW, 0.0f, 0.0f, 0, 0, (double) 0.0, (double) 0.0, Vt, Bh, Dl, - Sa); - } - - public DTEDFrameSubframeInfo(int Height, int Width, float Lon, float Lat, int Subx, int Suby, double xpi, double ypi, int Vt, - int Bh, int Dl, int Sa) { - viewType = Vt; - bandHeight = Bh; - dtedLevel = Dl; - slopeAdjust = Sa; - xPixInterval = xpi; - yPixInterval = ypi; - subx = Subx; - suby = Suby; - lon = Lon; - lat = Lat; - height = Height; - width = Width; - } - - public DTEDFrameSubframeInfo makeClone() { - return new DTEDFrameSubframeInfo(height, width, lon, lat, subx, suby, xPixInterval, yPixInterval, viewType, bandHeight, - dtedLevel, slopeAdjust); - } - - /** - * A comparison test to test the drawing parameters, to figure out if the - * presentation configuration has changed, and that the pixel color values - * need to be recalculated. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DTEDFrameSubframeInfo newInfo = (DTEDFrameSubframeInfo) obj; - boolean result = true; - - return viewType != newInfo.viewType && bandHeight != newInfo.bandHeight && dtedLevel != newInfo.dtedLevel - && slopeAdjust != newInfo.slopeAdjust && xPixInterval != newInfo.xPixInterval - && yPixInterval != newInfo.yPixInterval && newInfo.subx == subx && newInfo.suby == suby; - } - - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, viewType); - result = HashCodeUtil.hash(result, bandHeight); - result = HashCodeUtil.hash(result, dtedLevel); - result = HashCodeUtil.hash(result, slopeAdjust); - result = HashCodeUtil.hash(result, xPixInterval); - result = HashCodeUtil.hash(result, yPixInterval); - result = HashCodeUtil.hash(result, subx); - result = HashCodeUtil.hash(result, suby); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDLayer.java deleted file mode 100644 index 97098e70a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDLayer.java +++ /dev/null @@ -1,853 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDLayer.java,v $ -// $RCSfile: DTEDLayer.java,v $ -// $Revision: 1.13 $ -// $Date: 2005/12/09 21:09:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; - -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The DTEDLayer fills the screen with DTED data. To view the DTED images, the - * projection has to be set in a Equal ARC projection, which OpenMap calls the - * CADRG projection or the LLXY projection. In Gesture mode, clicking on the map - * will cause the DTEDLayer to place a point on the window and show the - * elevation of that point. The Gesture response is not dependent on the scale - * or projection of the screen. - *

- * - * The DTEDLayer uses the DTEDCacheManager to get the images it needs. The - * DTEDLayer receives projection change events, and then asks the cache manager - * for the images it needs based on the new projection. - * - * The DTEDLayer also relies on properties to set its variables, such as the - * dted frame paths (there can be several at a time), the opaqueness of the - * frame images, number of colors to use, and some other display variables. The - * DTEDLayer properties look something like this: - *

- * - * NOTE: Make sure your DTED file and directory names are in lower case. You can - * use the com.bbn.openmap.util.wanderer.ChangeCase class to make modifications - * if necessary. - *

- * - *

- * 
- *     #------------------------------
- *     # Properties for DTEDLayer
- *     #------------------------------
- *     # This property should reflect the paths to the dted level 0, 1 and newer 2 (file extension .dt2) data directories, separated by a semicolon.
- *     dted.paths=/usr/local/matt/data/dted;/cdrom/cdrom0/dted
- *     
- *     # Number between 0-255: 0 is transparent, 255 is opaque
- *     dted.opaque=255
- *     
- *     # Number of colors to use on the maps - 16, 32, 216
- *     dted.number.colors=216
- *     
- *     # Level of DTED data to use 0, 1, 2
- *     dted.level=0
- *     
- *     # Type of display for the data
- *     # 0 = no shading at all
- *     # 1 = greyscale slope shading
- *     # 2 = band shading, in meters
- *     # 3 = band shading, in feet
- *     # 4 = subframe testing
- *     # 5 = elevation, colored
- *     dted.view.type=5
- *     
- *     # Contrast setting, 1-5
- *     dted.contrast=3
- *     
- *     # height (meters or feet) between color changes in band shading
- *     dted.band.height=25
- *     
- *     # Minumum scale to display images. Larger numbers mean smaller scale, 
- *     # and are more zoomed out.
- *     dted.min.scale=20000000
- *     
- *     # Delete the cache if the layer is removed from the map.
- *     dted.kill.cache=true
- *     # Number of frames to hold in the cache. The default is 
- *     # DTEDFrameCache.FRAME_CACHE_SIZE, which is 15 to help smaller systems.  Better
- *     # caching happens, the larger the number.
- *     dted.cacheSize=40
- *     #-------------------------------------
- *     # End of properties for DTEDLayer
- *     #-------------------------------------
- * 
- * 
- * - * @see com.bbn.openmap.util.wanderer.ChangeCase - */ -public class DTEDLayer - extends OMGraphicHandlerLayer { - - /** The cache manager. */ - protected transient DTEDCacheManager cache = null; - /** - * Set when the projection has changed while a swing worker is gathering - * graphics, and we want him to stop early. - */ - protected boolean cancelled = false; - /** - * The paths to the DTED Level 0, 1 directories, telling where the data is. - * Newer level 2 data, with the .dt2 file extensions, should be set in this - * path property. - */ - protected String[] paths; - /** - * The level of DTED to use. Level 0 is 1km post spacing, Level 1 is 100m - * post spacing. Level 2 is 30m post spacing - */ - protected int dtedLevel = DTEDFrameSubframe.LEVEL_0; - /** - * The display type for the dted images. Slope shading is greyscale terrain - * modeling with highlights and shading, with the 'sun' being in the - * NorthWest. Colored Elevation shading is the same thing, except colors are - * added to indicate the elevation. Band shading colors the pixels according - * to a range of elevations. - */ - protected int viewType = DTEDFrameSubframe.NOSHADING; - /** The elevation range to use for each color in band shading. */ - protected int bandHeight = 25; - /** A contrast adjustment, for slope shading (1-5). */ - protected int slopeAdjust = DTEDFrameSubframe.DEFAULT_SLOPE_ADJUST; - protected int numColors = DTEDFrameColorTable.DTED_COLORS; - protected int opaqueness = DTEDFrameColorTable.DEFAULT_OPAQUENESS; - /** Flag to delete the cache if the layer is removed from the map. */ - protected boolean killCache = true; - /** The number of frames held by the cache objects. */ - protected int cacheSize = DTEDCacheHandler.FRAME_CACHE_SIZE; - - public static final String DTEDPathsProperty = "paths"; - public static final String DTED2PathsProperty = "level2.paths"; - public static final String OpaquenessProperty = "opaque"; - public static final String NumColorsProperty = "number.colors"; - public static final String DTEDLevelProperty = "level"; - public static final String DTEDViewTypeProperty = "view.type"; - public static final String DTEDSlopeAdjustProperty = "contrast"; - public static final String DTEDBandHeightProperty = "band.height"; - public static final String DTEDMinScaleProperty = "min.scale"; - public static final String DTEDKillCacheProperty = "kill.cache"; - public static final String DTEDFrameCacheSizeProperty = "cacheSize"; - - private String level0Command = "setLevelTo0"; - private String level1Command = "setLevelTo1"; - private String level2Command = "setLevelTo2"; - - /** The elevation spot used in the gesture mode. */ - DTEDLocation location = null; - - /** - * Instances of this class are used to display elevation labels on the map. - */ - static class DTEDLocation { - OMText text; - OMRect dot; - - public DTEDLocation(int x, int y) { - text = new OMText(x + 10, y, (String) null, (java.awt.Font) null, OMText.JUSTIFY_LEFT); - - dot = new OMRect(x - 1, y - 1, x + 1, y + 1); - text.setLinePaint(java.awt.Color.red); - dot.setLinePaint(java.awt.Color.red); - } - - /** - * Set the text to the elevation text. - * - * @param elevation elevation of the point in meters. - */ - public void setElevation(int elevation) { - // m - ft conversion - if (elevation < -100) - text.setData("No Data Here"); - else { - int elevation_ft = (int) ((float) elevation * 3.280840f); - text.setData(elevation + " m / " + elevation_ft + " ft"); - } - } - - /** Set the x-y location of the combo in the screen */ - public void setLocation(int x, int y) { - text.setX(x + 10); - text.setY(y); - dot.setLocation(x - 1, y - 1, x + 1, y + 1); - } - - public void render(java.awt.Graphics g) { - text.render(g); - dot.render(g); - } - - public void generate(Projection proj) { - text.generate(proj); - dot.generate(proj); - } - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DTEDLayer() { - this(null); - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - * - * @param pathsToDTEDDirs paths to the DTED directories that hold level 0, 1 - * and 2 data. - */ - public DTEDLayer(String[] pathsToDTEDDirs) { - setName("DTED"); - setDefaultValues(); - setPaths(pathsToDTEDDirs); - setMouseModeIDsForEvents(new String[] { - "Gestures" - }); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - } - - /** - * Set the paths to the DTED directories. - */ - public void setPaths(String[] pathsToDTEDDirs) { - paths = pathsToDTEDDirs; - if (cache != null) { - cache.setDtedDirPaths(pathsToDTEDDirs); - } - } - - /** - * Get the paths to the DTED directories. - */ - public String[] getPaths() { - return paths; - } - - public DTEDCacheManager getCache() { - if (cache == null) { - // Debug.output("DTEDLayer: Creating cache! (This is a one-time operation!)"); - cache = new DTEDCacheManager(paths, numColors, opaqueness); - cache.setCacheSize(cacheSize); - DTEDFrameSubframeInfo dfsi = new DTEDFrameSubframeInfo(viewType, bandHeight, dtedLevel, slopeAdjust); - cache.setSubframeInfo(dfsi); - } - return cache; - } - - public void setCache(DTEDCacheManager cache) { - this.cache = cache; - } - - protected void setDefaultValues() { - // defaults - paths = null; - setOpaqueness(DTEDFrameColorTable.DEFAULT_OPAQUENESS); - setDtedLevel(DTEDFrameSubframe.LEVEL_0); - setBandHeight(DTEDFrameSubframe.DEFAULT_BANDHEIGHT); - setSlopeAdjust(DTEDFrameSubframe.DEFAULT_SLOPE_ADJUST); - setViewType(DTEDFrameSubframe.COLOREDSHADING); - setMaxScale(20000000); - } - - /** - * Set all the DTED properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(this); - - paths = PropUtils.initPathsFromProperties(properties, prefix + DTEDPathsProperty, paths); - setOpaqueness(PropUtils.intFromProperties(properties, prefix + OpaquenessProperty, getOpaqueness())); - - setNumColors(PropUtils.intFromProperties(properties, prefix + NumColorsProperty, getNumColors())); - - setDtedLevel(PropUtils.intFromProperties(properties, prefix + DTEDLevelProperty, getDtedLevel())); - - setViewType(PropUtils.intFromProperties(properties, prefix + DTEDViewTypeProperty, getViewType())); - - setSlopeAdjust(PropUtils.intFromProperties(properties, prefix + DTEDSlopeAdjustProperty, getSlopeAdjust())); - - setBandHeight(PropUtils.intFromProperties(properties, prefix + DTEDBandHeightProperty, getBandHeight())); - - // The Layer maxScale is talking the place of the DTEDLayer minScale - // property. - setMaxScale(PropUtils.floatFromProperties(properties, prefix + DTEDMinScaleProperty, getMaxScale())); - - setCacheSize((int) PropUtils.intFromProperties(properties, prefix + DTEDFrameCacheSizeProperty, getCacheSize())); - - setKillCache(PropUtils.booleanFromProperties(properties, prefix + DTEDKillCacheProperty, getKillCache())); - - } - - /** - * Called when the layer is no longer part of the map. In this case, we - * should disconnect from the server if we have a link. - */ - public void removed(java.awt.Container cont) { - if (killCache) { - Debug.output("DTEDLayer: emptying cache!"); - cache = null; - } - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the dted. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - Debug.error("DTED Layer needs to be added to the MapBean before it can draw images!"); - return new OMGraphicList(); - } - - DTEDCacheManager cache = getCache(); - - if (!(projection instanceof EqualArc)) { - //fireRequestInfoLine("DTED works faster with an Equal Arc projection (CADRG/LLXY)."); - } - - Debug.message("basic", getName() + "|DTEDLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (Debug.debugging("dted")) { - Debug.output(getName() + "|DTEDLayer.prepare(): " + "calling getRectangle " + " with projection: " + projection - + " ul = " + projection.getUpperLeft() + " lr = " + projection.getLowerRight()); - } - - OMGraphicList omGraphicList; - - if (projection.getScale() < maxScale) { - omGraphicList = cache.getRectangle(projection); - } else { - fireRequestInfoLine(" The scale is too small for DTED viewing."); - Debug.error("DTEDLayer: scale (1:" + projection.getScale() + ") is smaller than minimum (1:" + maxScale + ") allowed."); - omGraphicList = new OMGraphicList(); - } - // /////////////////// - // safe quit - int size = 0; - if (omGraphicList != null) { - size = omGraphicList.size(); - Debug.message("basic", getName() + "|DTEDLayer.prepare(): finished with " + size + " graphics"); - - // // Don't forget to project them. Since they are only - // // being recalled if the projection has changed, then we - // // need to force a reprojection of all of them because the - // // screen position has changed. - // omGraphicList.project(projection, true); - - } else { - Debug.message("basic", getName() + "|DTEDLayer.prepare(): finished with null graphics list"); - } - - return omGraphicList; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(java.awt.Graphics g) { - Debug.message("dted", getName() + "|DTEDLayer.paint()"); - - super.paint(g); - - if (location != null) - location.render(g); - location = null; - } - - /** - * Get the view type set for creating images. - *

- * - *

-     * 
-     * 
-     * 
-     * 
-     *     0: DTEDFrameSubframe.NOSHADING
-     *     1: DTEDFrameSubframe.SLOPESHADING
-     *     2: DTEDFrameSubframe.COLOREDSHADING
-     *     3: DTEDFrameSubframe.METERSHADING
-     *     4: DTEDFrameSubframe.FEETSHADING
-     * 
-     * 
-     * 
-     * 
-     * 
- */ - public int getViewType() { - return viewType; - } - - public void setViewType(int vt) { - switch (vt) { - case DTEDFrameSubframe.NOSHADING: - case DTEDFrameSubframe.SLOPESHADING: - case DTEDFrameSubframe.COLOREDSHADING: - case DTEDFrameSubframe.METERSHADING: - case DTEDFrameSubframe.FEETSHADING: - viewType = vt; - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.viewType = viewType; - } - - break; - default: - // unchanged - } - } - - /** - * Get the value for the interval between band colors for meter and feet - * shading view types. - */ - public int getBandHeight() { - return bandHeight; - } - - public void setBandHeight(int bh) { - bandHeight = bh; - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.bandHeight = bandHeight; - } - } - - /** - * Get the value for contrast adjustments, 1-5. - */ - public int getSlopeAdjust() { - return slopeAdjust; - } - - public void setSlopeAdjust(int sa) { - if (sa > 0 && sa <= 5) { - slopeAdjust = sa; - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.slopeAdjust = slopeAdjust; - } - } else { - Debug.output("DTEDLayer (" + getName() + ") being told to set slope adjustment to invalid value (" + sa - + "), must be 1-5"); - } - } - - /** - * Get the value set for which DTED level is being used, 0-2. - */ - public int getDtedLevel() { - return dtedLevel; - } - - public void setDtedLevel(int level) { - dtedLevel = level; - } - - /** - * Get the opaqueness value used for the images, 0-255. - */ - public int getOpaqueness() { - return opaqueness; - } - - public void setOpaqueness(int o) { - if (o >= 0) { - opaqueness = o; - if (cache != null) { - cache.setOpaqueness(opaqueness); - } - } - } - - /** - * Get whether the cache will be killed when the layer is removed from the - * map. - */ - public boolean getKillCache() { - return killCache; - } - - public void setKillCache(boolean kc) { - killCache = kc; - } - - /** - * Get the cache size, or how many DTED frames are held in memory. - */ - public int getCacheSize() { - return cacheSize; - } - - public void setCacheSize(int cs) { - if (cs > 0) { - cacheSize = cs; - } else { - Debug.output("DTEDLayer (" + getName() + ") being told to set cache size to invalid value (" + cs + ")."); - } - } - - /** - * Get the number of colors used in the DTED images. - */ - public int getNumColors() { - return numColors; - } - - public void setNumColors(int nc) { - if (nc > 0) { - numColors = nc; - - if (cache != null) { - cache.setNumColors(numColors); - } - } - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - /** The user interface palette for the DTED layer. */ - protected Box paletteBox = null; - - /** Creates the interface palette. */ - public java.awt.Component getGUI() { - - if (paletteBox == null) { - if (Debug.debugging("dted")) - Debug.output("DTEDLayer: creating DTED Palette."); - - paletteBox = Box.createVerticalBox(); - Box subbox1 = Box.createHorizontalBox(); - Box subbox2 = Box.createVerticalBox(); - Box subbox3 = Box.createHorizontalBox(); - - // palette = new JPanel(); - // palette.setLayout(new GridLayout(0, 1)); - - // The DTED Level selector - JPanel levelPanel = PaletteHelper.createPaletteJPanel("DTED Level"); - ButtonGroup levels = new ButtonGroup(); - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (cache != null) { - String ac = e.getActionCommand(); - int newLevel; - if (ac.equalsIgnoreCase(level2Command)) - newLevel = DTEDFrameSubframe.LEVEL_2; - else if (ac.equalsIgnoreCase(level1Command)) - newLevel = DTEDFrameSubframe.LEVEL_1; - else - newLevel = DTEDFrameSubframe.LEVEL_0; - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.dtedLevel = newLevel; - // cache.setSubframeInfo(dfsi); - } - } - }; - - JRadioButton level0 = new JRadioButton("Level 0"); - level0.addActionListener(al); - level0.setActionCommand(level0Command); - JRadioButton level1 = new JRadioButton("Level 1"); - level1.addActionListener(al); - level1.setActionCommand(level1Command); - JRadioButton level2 = new JRadioButton("Level 2"); - level2.addActionListener(al); - level2.setActionCommand(level2Command); - - levels.add(level0); - levels.add(level1); - levels.add(level2); - - switch (dtedLevel) { - case 2: - level2.setSelected(true); - break; - case 1: - level1.setSelected(true); - break; - case 0: - default: - level0.setSelected(true); - } - - levelPanel.add(level0); - levelPanel.add(level1); - levelPanel.add(level2); - - // The DTED view selector - JPanel viewPanel = PaletteHelper.createPaletteJPanel("View Type"); - String[] viewStrings = { - "None", - "Shading", - "Elevation Shading", - "Elevation Bands (Meters)", - "Elevation Bands (Feet)" - }; - - JComboBox viewList = new JComboBox(viewStrings); - viewList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - int newView = jcb.getSelectedIndex(); - switch (newView) { - case 0: - viewType = DTEDFrameSubframe.NOSHADING; - break; - case 1: - viewType = DTEDFrameSubframe.SLOPESHADING; - break; - case 2: - viewType = DTEDFrameSubframe.COLOREDSHADING; - break; - case 3: - viewType = DTEDFrameSubframe.METERSHADING; - break; - case 4: - viewType = DTEDFrameSubframe.FEETSHADING; - break; - default: - viewType = DTEDFrameSubframe.NOSHADING; - } - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.viewType = viewType; - // cache.setSubframeInfo(dfsi); - } - - } - }); - int selectedView; - switch (viewType) { - case 0: - case 1: - selectedView = viewType; - break; - case 2: - case 3: - selectedView = viewType + 1; - break; - case 4: - // This puts the layer in testing mode, and the menu - // changes. - String[] viewStrings2 = { - "None", - "Shading", - "Elevation Bands (Meters)", - "Elevation Bands (Feet)", - "Subframe Testing", - "Elevation Shading" - }; - viewList = new JComboBox(viewStrings2); - viewList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - int newView = jcb.getSelectedIndex(); - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.viewType = newView; - // cache.setSubframeInfo(dfsi); - } - } - }); - selectedView = viewType; - break; - case 5: - selectedView = 2; // DTEDFrameSubframe.COLOREDSHADING - break; - default: - selectedView = DTEDFrameSubframe.NOSHADING; - } - - viewList.setSelectedIndex(selectedView); - viewPanel.add(viewList); - - // The DTED Contrast Adjuster - JPanel contrastPanel = PaletteHelper.createPaletteJPanel("Contrast Adjustment"); - JSlider contrastSlide = new JSlider(JSlider.HORIZONTAL, 1/* min */, 5/* max */, slopeAdjust/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(1), new JLabel("min")); - dict.put(new Integer(5), new JLabel("max")); - contrastSlide.setLabelTable(dict); - contrastSlide.setPaintLabels(true); - contrastSlide.setMajorTickSpacing(1); - contrastSlide.setPaintTicks(true); - contrastSlide.setSnapToTicks(true); - contrastSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - fireRequestInfoLine(getName() + " - Contrast Slider value = " + slider.getValue()); - slopeAdjust = slider.getValue(); - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.slopeAdjust = slopeAdjust; - // cache.setSubframeInfo(dfsi); - } - } - } - }); - contrastPanel.add(contrastSlide); - - // The DTED Band Height Adjuster - JPanel bandPanel = PaletteHelper.createPaletteJPanel("Band Elevation Spacing"); - JSlider bandSlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 1000/* max */, bandHeight/* initial */); - bandSlide.setLabelTable(bandSlide.createStandardLabels(250)); - bandSlide.setPaintLabels(true); - bandSlide.setMajorTickSpacing(250); - bandSlide.setMinorTickSpacing(50); - bandSlide.setPaintTicks(true); - bandSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - fireRequestInfoLine(getName() + " - Band Slider value = " + slider.getValue()); - bandHeight = slider.getValue(); - if (cache != null) { - DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo(); - dfsi.bandHeight = bandHeight; - // cache.setSubframeInfo(dfsi); - } - } - } - }); - - bandPanel.add(bandSlide); - - JButton redraw = new JButton("Redraw DTED Layer"); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - - subbox1.add(levelPanel); - subbox1.add(viewPanel); - paletteBox.add(subbox1); - subbox2.add(contrastPanel); - subbox2.add(bandPanel); - paletteBox.add(subbox2); - subbox3.add(redraw); - paletteBox.add(subbox3); - } - - return paletteBox; - } - - /** - * Overridden to modify the MapMouseInterpreter used by the layer. - */ - public synchronized MapMouseInterpreter getMouseEventInterpreter() { - if (getMouseModeIDsForEvents() != null && mouseEventInterpreter == null) { - setMouseEventInterpreter(new StandardMapMouseInterpreter(this) { - public boolean leftClick(MouseEvent me) { - super.leftClick(me); - determineLocation(me); - return true; - } - - public boolean leftClick(OMGraphic omg, MouseEvent me) { - super.leftClick(omg, me); - determineLocation(me); - return true; - } - - }); - } - - return mouseEventInterpreter; - } - - public boolean determineLocation(MouseEvent e) { - Projection projection = getProjection(); - if (cache != null && projection != null) { - LatLonPoint ll = projection.inverse(e.getX(), e.getY(), new LatLonPoint.Double()); - location = new DTEDLocation(e.getX(), e.getY()); - location.setElevation(cache.getElevation((float) ll.getY(), (float) ll.getX())); - location.generate(projection); - repaint(); - return true; - } - return false; - } - - /** - * Don't need DTEDFrames highlighting themselves. - */ - public boolean isHighlightable(OMGraphic omg) { - return false; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDSubframedFrame.java b/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDSubframedFrame.java deleted file mode 100644 index c1cb17d6c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/DTEDSubframedFrame.java +++ /dev/null @@ -1,691 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDFrame.java,v $ -// $RCSfile: DTEDFrame.java,v $ -// $Revision: 1.8 $ -// $Date: 2008/02/29 00:51:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -import java.awt.Color; - -import com.bbn.openmap.dataAccess.dted.DTEDFrame; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The DTEDSubframedFrame is the representation of the DTED (Digital Terrain - * Elevation Data) data from a single dted data file. It keeps track of all the - * attribute information of it's data, and also maintains an array of images - * (DTEDFrameSubframe) that represent views of the elevation posts. - */ -public class DTEDSubframedFrame - extends DTEDFrame { - - /** The colortable used to create the images. */ - public DTEDFrameColorTable colorTable; - /** The subframe presentation attributes. */ - public DTEDFrameSubframeInfo subframeInfo; // master - - /** - * The frame image is divided into 200x200 pixel subframes, with a leftover - * frame at the end. This is how many horizontal subframes there are. - */ - public int number_horiz_subframes; - /** - * The frame image is divided into 200x200 pixel subframes, with a leftover - * frame at the end. This is how many vertical subframes there are. - */ - public int number_vert_subframes; - - /** The image array for the subframes. */ - public DTEDFrameSubframe subframes[][]; - - // //////////////// - // Administrative methods - // //////////////// - - /** - * Simplest constructor. - * - * @param filePath complete path to the DTED frame. - */ - public DTEDSubframedFrame(String filePath) { - this(filePath, null, null, false); - } - - /** - * Constructor with colortable and presentation information. - * - * @param filePath complete path to the DTED frame. - * @param cTable the colortable to use for the images. - * @param info presentation parameters. - */ - public DTEDSubframedFrame(String filePath, DTEDFrameColorTable cTable, DTEDFrameSubframeInfo info) { - this(filePath, cTable, info, false); - } - - /** - * Constructor with colortable and presentation information. - * - * @param filePath complete path to the DTED frame. - * @param readWholeFile If true, all of the elevation data will be read at - * load time. If false, elevation post data will be read in per - * longitude column depending on the need. False is recommended for - * DTEd level 1 and 2. - */ - public DTEDSubframedFrame(String filePath, boolean readWholeFile) { - this(filePath, null, null, readWholeFile); - } - - /** - * Constructor with colortable and presentation information. - * - * @param filePath complete path to the DTED frame. - * @param cTable the colortable to use for the images. - * @param info presentation parameters. - * @param readWholeFile If true, all of the elevation data will be read at - * load time. If false, elevation post data will be read in per - * longitude column depending on the need. False is recommended for - * DTED level 1 and 2. - */ - public DTEDSubframedFrame(String filePath, DTEDFrameColorTable cTable, DTEDFrameSubframeInfo info, boolean readWholeFile) { - - super(filePath, readWholeFile); - - colorTable = cTable; - subframeInfo = info; - } - - public void setColorTable(DTEDFrameColorTable c_Table) { - colorTable = c_Table; - } - - public DTEDFrameColorTable getColorTable() { - return colorTable; - } - - /** - * Sets the subframe array. Blows away any images that may already be there. - */ - public void initSubframes(int numHorizSubframes, int numVertSubframes) { - number_horiz_subframes = numHorizSubframes; - number_vert_subframes = numVertSubframes; - subframes = new DTEDFrameSubframe[numHorizSubframes][numVertSubframes]; - if (Debug.debugging("dted")) { - Debug.output("///////// DTEDFrame: subframe array initialized, " + numHorizSubframes + "x" + numVertSubframes); - } - } - - /** - * If you just want to get an image for the DTEDFrame, then call this. One - * OMRaster for the entire DTEDFrame will be returned, with the default - * rendering parameters (Colored shading) and the default colortable. Use - * the other getOMRaster method if you want something different. This method - * actually calls that other method, so read the documentation for that as - * well. - * - * @param proj EqualArc projection to use to create image. - * @return raster image to display in OpenMap. - */ - public OMGraphic getImage(Projection proj) { - return getImage(null, null, proj); - } - - /** - * If you just want to get an image for the DTEDFrame, then call this. One - * OMRaster for the entire DTEDFrame will be returned. In the - * DTEDFrameSubframeInfo, you need to set the color type and all the - * parameters that are assiociated with the rendering parameters. The - * projection parameters of the DFSI (image height, width, pixel intervals) - * will be set in this method based on the projection. If you want a - * different sized image, scale the thing you get back from this method, or - * change the scale of the projection that is passed in. Calling this method - * will cause the DTEDFrame subframe cache to reset itself to hold one - * subframe covering the entire frame. Just so you know. - * - * @param dfsi the DTEDFrameSubframeInfo describing the subframe. - * @param colortable the colortable to use when building the image. - * @return raster image to display in OpenMap. - * @param proj EqualArc projection to use to create image. - */ - public OMGraphic getImage(DTEDFrameSubframeInfo dfsi, DTEDFrameColorTable colortable, Projection proj) { - if (proj == null) { - Debug.error("DTEDFrame.getOMRaster: need projection to create image."); - return null; - } - - if (colortable == null) { - colortable = new DTEDFrameColorTable(); - } - - if (dfsi == null) { - dfsi = - new DTEDFrameSubframeInfo(DTEDFrameSubframe.COLOREDSHADING, DTEDFrameSubframe.DEFAULT_BANDHEIGHT, - DTEDFrameSubframe.LEVEL_1, // Doesn't - // matter - DTEDFrameSubframe.DEFAULT_SLOPE_ADJUST); - } - - CADRG cadrg = CADRG.convertProjection(proj); - - dfsi.xPixInterval = 360 / cadrg.getXPixConstant(); // degrees/pixel - dfsi.yPixInterval = 90 / cadrg.getYPixConstant(); - dfsi.height = (int) (1 / dfsi.yPixInterval); - dfsi.width = (int) (1 / dfsi.xPixInterval); - - // Will trigger the right thing in getSubframeOMRaster; - subframes = null; - - return getSubframeImage(dfsi, colortable, proj); - } - - /** - * Return the subframe image as described in the DTEDFrameSubframeInfo. This - * is called by the DTEDCacheHandler, which has in turn set the - * DTEDFrameSubframeInfo parameters to match the projection parameters. This - * turns out to be kinda important. - * - * @param dfsi the DTEDFrameSubframeInfo describing the subframe. - * @param colortable the colortable to use when building the image. - * @return raster image to display in OpenMap. - */ - public OMGraphic getSubframeImage(DTEDFrameSubframeInfo dfsi, DTEDFrameColorTable colortable, Projection proj) { - if (!frame_is_valid) - return null; - - OMGraphic raster = null; - - if (dfsi.viewType == DTEDFrameSubframe.NOSHADING) - return null; - - if (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING) - colortable.setGreyScale(false); - else - colortable.setGreyScale(true); - - float lat_origin = dfsi.lat; - float lon_origin = dfsi.lon; - - if (subframes == null) { - // Need to set a couple of things up if the DTEDFrameCache - // isn't being used to set up the subframe information in - // the dfsi. - initSubframes(1, 1); - // NOTE!! The algorithm uses the coordinates of the top - // left corner as a reference!!!!!!!! - lat_origin = dsi.lat_origin + 1; - lon_origin = dsi.lon_origin; - } - - DTEDFrameSubframe subframe = subframes[dfsi.subx][dfsi.suby]; - - if (Debug.debugging("dteddetail")) { - Debug.output("Subframe lat/lon => lat= " + lat_origin + " vs. " + dfsi.lat + " lon= " + lon_origin + " vs. " + dfsi.lon - + " subx = " + dfsi.subx + " suby = " + dfsi.suby); - Debug.output("Height/width of subframe => height= " + dfsi.height + " width= " + dfsi.width); - } - - if (subframe != null) { - - raster = subframe.getImageIfCurrent(proj, dfsi); - if (raster != null) { - if (Debug.debugging("dted")) { - Debug.output("######## DTEDFrame: returning cached subframe"); - } - return raster; - } - - if (Debug.debugging("dted")) { - Debug.output(" *** DTEDFrame: changing image of cached subframe"); - } - - /* - * If there is an image, the types are different and it needs to be - * redrawn - */ - subframe.dfsi = dfsi.makeClone(); - - } else { - - if (Debug.debugging("dted")) { - Debug.output(" +++ DTEDFrame: creating subframe"); - } - - subframe = new DTEDFrameSubframe(dfsi); - subframes[dfsi.subx][dfsi.suby] = subframe; - } - - // lat/lon_post_intervals are *10 too big - // extra 0 in - // 36000 to counteract - // start in lower left of subframe - double start_lat_index = (lat_origin - (double) dsi.sw_lat) * 36000.0 / (double) uhl.lat_post_interval; - double start_lon_index = (lon_origin - (double) dsi.sw_lon) * 36000.0 / (double) uhl.lon_post_interval; - double end_lat_index = - ((lat_origin - ((double) dfsi.height * dfsi.yPixInterval)) - (double) dsi.sw_lat) * 36000.0 - / (double) uhl.lat_post_interval; - double end_lon_index = - ((lon_origin + ((double) dfsi.width * dfsi.xPixInterval)) - (double) dsi.sw_lon) * 36000.0 - / (double) uhl.lon_post_interval; - double lat_interval = (start_lat_index - end_lat_index) / (double) dfsi.height; - double lon_interval = (end_lon_index - start_lon_index) / (double) dfsi.width; - - if (Debug.debugging("dteddetail")) - Debug.output(" start_lat_index => " + start_lat_index + "\n" + " end_lat_index => " + end_lat_index + "\n" - + " start_lon_index => " + start_lon_index + "\n" + " end_lon_index => " + end_lon_index + "\n" - + " lat_interval => " + lat_interval + "\n" + " lon_interval => " + lon_interval); - - short e1, e2; - short xc = 0; - short yc = 0; - short xnw = 0; - short ynw = 0; - short xse = 0; - short yse = 0; - double slope; - double distance = 1.0; - float value = 0.0f; - int assignment = 0; - double modifier = (double) 0; - double xw_offset = 0; - double xe_offset = 0; - double yn_offset = 0; - double ys_offset = 0; - int elevation = (int) 0; - - // Calculations needed once for slope shading - if (dfsi.viewType == DTEDFrameSubframe.SLOPESHADING - || (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING && colortable.colors.length > DTEDFrameColorTable.NUM_ELEVATION_COLORS)) { - // to get to the right part of the frame, kind of like a - // subframe - // indexing thing - xw_offset = start_lon_index - Math.ceil(lon_interval); - xe_offset = start_lon_index + Math.ceil(lon_interval); - yn_offset = start_lat_index + Math.ceil(lat_interval); - ys_offset = start_lat_index - Math.ceil(lat_interval); - - switch (dfsi.dtedLevel) { - // larger numbers make less contrast - case 0: - modifier = (double) 4; - break;// 1000 ideal - case 1: - modifier = (double) .02; - break;// 2 ideal - case 2: - modifier = (double) .0001; - break; - case 3: - modifier = (double) .000001; - break; - default: - modifier = (double) 1; - } - // With more colors, contrast tends to be a little light - // for the - // default - brighten it up more - if (colortable.colors.length > 215) - modifier /= 10; - - for (int h = dfsi.slopeAdjust; h < 5; h++) - modifier *= 10; - distance = Math.sqrt((modifier * lon_interval * lon_interval) + (modifier * lat_interval * lat_interval)); - } - - ImageData imageData = ImageData.getImageData(dfsi.colorModel, dfsi.width, dfsi.height, colortable.colors); - - for (short x = 0; x < dfsi.width; x++) { - - // used for both elevation banding and slope - xc = (short) (start_lon_index + ((x) * lon_interval)); - if (xc < 0) - xc = 0; - if (xc > dsi.num_lon_points - 1) - xc = (short) (dsi.num_lon_points - 1); - - if ((elevations[xc] == null) && !readDataRecord(xc)) { - Debug.error("DTEDFrame: Problem reading lat point line in data record"); - return null; - } - if (dfsi.viewType == DTEDFrameSubframe.SLOPESHADING - || (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING && colortable.colors.length > DTEDFrameColorTable.NUM_ELEVATION_COLORS)) { - // This is actually finding the right x post for this - // pixel, - // within the subframe measurements. - xnw = (short) (xw_offset + Math.floor(x * lon_interval)); - xse = (short) (xe_offset + Math.floor(x * lon_interval)); - - // trying to smooth out the edge of the frame - if (xc == 0 || xnw < 0) { - xnw = xc; - xse = (short) (xnw + 2.0 * Math.ceil(lon_interval)); - } - if (xc == dsi.num_lon_points - 1 || xse > dsi.num_lon_points - 1) { - xse = (short) (dsi.num_lon_points - 1); - xnw = (short) (xse - 2.0 * Math.ceil(lon_interval)); - } - - if (((elevations[xnw] == null) && !readDataRecord(xnw)) || ((elevations[xse] == null) && !readDataRecord(xse))) { - Debug.error("DTEDFrame: Problem reading lat point line in data record"); - return null; - } - } - - // Now, calculate the data and assign the pixels based on - // y - for (short y = 0; y < dfsi.height; y++) { - - // used for elevation band and slope - yc = (short) (start_lat_index - ((y) * lat_interval)); - if (yc < 0) - yc = 0; - elevation = (int) elevations[xc][yc]; - - // elevation shading - if (dfsi.viewType == DTEDFrameSubframe.METERSHADING || dfsi.viewType == DTEDFrameSubframe.FEETSHADING) { - - // Just use the top two-thirds of the colors - if (elevation == 0) - assignment = 0; // color water Blue - else { - if (elevation < 0) - elevation *= -1; // Death Valley - if (dfsi.viewType == DTEDFrameSubframe.FEETSHADING) - elevation = (int) (elevation * 3.2); - // Start at the darkest color, and then go up - // through the - // colormap for each band height, the start - // back at the - // darkest when you get to the last color. To - // make this - // more useful, I limit the number of colors - // (10) used - if - // there isn;t enough contrast between the - // colors, you can't - // see the bands. The contrast adjustment in - // 24-bit color - // mode(216 colors) lets you add a few colors. - if (colortable.colors.length < 216) { - try { - assignment = (int) ((elevation / dfsi.bandHeight) % (colortable.colors.length - 6) + 6); - } catch (java.lang.ArithmeticException ae) { - assignment = 1; - } - } else { - try { - assignment = - (int) (((elevation / dfsi.bandHeight) % (10 - 2 * (3 - dfsi.slopeAdjust)) * (colortable.colors.length / (10 - 2 * (3 - dfsi.slopeAdjust)))) + 6); - } catch (java.lang.ArithmeticException ae) { - assignment = 1; - } - } - } - - imageData.set(x, y, assignment); - } - - // Slope shading - else if (dfsi.viewType == DTEDFrameSubframe.SLOPESHADING - || (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING && colortable.colors.length > DTEDFrameColorTable.NUM_ELEVATION_COLORS)) { - - // find the y post indexes within the subframe - ynw = (short) (yn_offset - Math.floor(y * lat_interval)); - yse = (short) (ys_offset - Math.floor(y * lat_interval)); - - // trying to smooth out the edge of the frame by - // handling the - // frame limits - if (yse < 0) - yse = 0; - if (yc == dsi.num_lat_lines - 1 || ynw > dsi.num_lat_lines - 1) - ynw = (short) (dsi.num_lat_lines - 1); - - e2 = elevations[xse][yse]; // down & right - // elevation - e1 = elevations[xnw][ynw]; // up and left - // elevation - - slope = (e2 - e1) / distance; // slope relative to - // nw sun - // colormap value darker for negative slopes, - // brighter for - // positive slopes - - if (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING) { - assignment = 1; - elevation = (int) (elevation * 3.2);// feet - for (int l = 1; l < DTEDFrameColorTable.NUM_ELEVATION_COLORS; l++) - if (elevation <= colortable.elevation_color_cutoff[l]) { - if (slope < 0) - assignment = (int) (l + DTEDFrameColorTable.NUM_ELEVATION_COLORS); - else if (slope > 0) - assignment = (int) (l + (DTEDFrameColorTable.NUM_ELEVATION_COLORS * 2)); - else - assignment = (int) l; - break; - } - if (elevation == 0) - assignment = 0; - - imageData.set(x, y, assignment); - } - - else { - value = (float) (((colortable.colors.length - 1) / 2) + slope); - - // not water, but close in the colormap - max - // dark - if (slope != 0 && value < 1) - value = 1; - if (elevation == 0) - value = 0; // water?!? - if (value > (colortable.colors.length - 1)) - value = colortable.colors.length - 1; // max - // bright - - assignment = (int) value; - - imageData.set(x, y, assignment); - } - } - // Subframe outlines - different colors for each side - // of the frame - // This is really for debugging purposes, really. - else if (dfsi.viewType == DTEDFrameSubframe.BOUNDARYSHADING) { - int c; - if (x < 1) - c = 1; - else if (x > dfsi.width - 2) - c = 12; - else if (y < 1) - c = 1; - else if (y > dfsi.height - 2) - c = 12; - else - c = 7; - - imageData.set(x, y, c); - - } else if (dfsi.viewType == DTEDFrameSubframe.COLOREDSHADING) { - assignment = 1; - elevation = (int) (elevation * 3.2);// feet - for (int l = 1; l < DTEDFrameColorTable.NUM_ELEVATION_COLORS; l++) - if (elevation <= colortable.elevation_color_cutoff[l]) { - assignment = (int) l; - break; - } - - if (elevation == 0) - assignment = 0; - if (elevation < 0) - assignment = 1; - if (elevation > 33000) - assignment = 1; - - imageData.set(x, y, assignment); - } - } - - } - - imageData.updateData(subframe); - - if (Debug.debugging("dteddetail")) - Debug.output("DTEDFrame: leaving raster"); - - - return subframe.getImage(proj); - } - - public static void main(String args[]) { - Debug.init(); - if (args.length < 1) { - System.out.println("DTEDFrame: Need a path/filename"); - System.exit(0); - } - - System.out.println("DTEDFrame: " + args[0]); - DTEDSubframedFrame df = new DTEDSubframedFrame(args[0]); - if (df.frame_is_valid) { - System.out.println(df.uhl); - System.out.println(df.dsi); - System.out.println(df.acc); - - // int startx = 5; - // int starty = 6; - // int endx = 10; - // int endy = 30; - - // short[][] e = df.getElevations(startx, starty, endx, - // endy); - // for (int i = e[0].length-1; i >= 0; i--) { - // for (int j = 0; j < e.length; j++) { - // System.out.print(e[j][i] + " "); - // } - // System.out.println(); - // } - } - float lat = df.dsi.lat_origin + .5f; - float lon = df.dsi.lon_origin + .5f; - - CADRG crg = new CADRG(new LatLonPoint.Double(lat, lon), 1500000, 600, 600); - final OMGraphic ras = df.getImage(crg); - - // Pushes the image to the left top of the frame. - if (ras instanceof OMRaster) { - crg.setHeight(((OMRaster) ras).getHeight()); - crg.setWidth(((OMRaster) ras).getWidth()); - } - - ras.generate(crg); - - java.awt.Frame window = new java.awt.Frame(args[0]) { - public void paint(java.awt.Graphics g) { - if (ras != null) { - ras.render(g); - } - } - }; - - window.addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent e) { - // need a shutdown event to notify other gui beans and - // then exit. - System.exit(0); - } - }); - - window.setSize(crg.getWidth(), crg.getHeight()); - window.setVisible(true); - window.repaint(); - } - - protected static abstract class ImageData { - protected abstract void set(short x, short y, int value); - protected abstract void updateData(DTEDFrameSubframe dfs); - - int width = 0; - int height = 0; - Color[] colors; - - protected ImageData(int w, int h, Color[] colors) { - this.width = w; - this.height = h; - this.colors = colors; - } - - protected static ImageData getImageData(int colorModel, int width, int height, Color[] colors) { - if (colorModel == OMRasterObject.COLORMODEL_DIRECT) { - return new Pixel(width, height, colors); - } else { - return new Byte(width, height, colors); - } - } - - protected static class Pixel - extends ImageData { - int[] pixels; - - int ranColor; - - protected Pixel(int w, int h, Color[] colors) { - super(w, h, colors); - pixels = new int[w * h]; - - int red = (int) (Math.random() * 255); - int green = (int) (Math.random() * 255); - int blue = (int) (Math.random() * 255); - - Color color = new Color(red, green, blue); - ranColor = color.getRGB(); - } - - protected void set(short x, short y, int value) { - pixels[(y * width) + x] = colors[value].getRGB(); -// pixels[(y * width) + x] = ranColor; - } - - protected void updateData(DTEDFrameSubframe dfs) { - dfs.setPixels(pixels); - } - } - - protected static class Byte - extends ImageData { - byte[] bytes; - - protected Byte(int w, int h, Color[] colors) { - super(w, h, colors); - bytes = new byte[w * h]; - } - - protected void set(short x, short y, int value) { - bytes[(y * width) + x] = (byte) value; - } - - protected void updateData(DTEDFrameSubframe dfs) { - dfs.setBitsAndColors(bytes, colors); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/dted/package.html b/src/core/src/main/java/com/bbn/openmap/layer/dted/package.html deleted file mode 100644 index 50c3c86fc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/dted/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a layer that displays DTED (Digital Terrain Elevation Data) data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/ArcData.java b/src/core/src/main/java/com/bbn/openmap/layer/e00/ArcData.java deleted file mode 100644 index b2b582e04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/ArcData.java +++ /dev/null @@ -1,204 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/e00/ArcData.java,v -// $ -// $RCSfile: ArcData.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.e00; - -public class ArcData - extends E00Data { - double[] coords; - int deja = 0; - - public ArcData() { - } - - public ArcData(E00Data d) { - valeur = d.valeur; - valeur2 = d.valeur2; - id = d.id; - type = d.type; - } - - ArcData c0, c1, f0, f1, c2, f2; - int numpoint; - - void setC(ArcData d) { - if (d.type == 0) { - if (c0 == null) - c0 = d; - else - c2 = d; - if (type == 1) - d.valeur2 = valeur; - } else if (d.type == 1) { - if (c1 == null) - c1 = d; - else - c2 = d; - if (type == 0) - valeur = d.valeur; - } - } - - void setF(ArcData d) { - if (d.type == 0) { - if (f0 == null) - f0 = d; - else - f2 = d; - if (type == 1) - d.valeur = valeur; - } else if (d.type == 1) { - if (f1 == null) - f1 = d; - else - f2 = d; - if (type == 0) - valeur2 = d.valeur; - } - } - - void print() { - System.out.print("arc " + id + " type " + type + " "); - System.out.print((c0 != null) ? c0.id : 0); - System.out.print(' '); - System.out.print((f0 != null) ? f0.id : 0); - System.out.print(' '); - System.out.print((c1 != null) ? c1.id : 0); - System.out.print(' '); - System.out.print((f1 != null) ? f1.id : 0); - System.out.print(' '); - System.out.print((c2 != null) ? c2.id : 0); - System.out.print(' '); - System.out.print((f2 != null) ? f2.id : 0); - System.out.println(); - } - - ArcData visit(ArcData d) { - ArcData g1, g2, h1, h2; - if (d.type > 1) - return null; - if ((d == c0) || (d == c1) || (d == c2)) { - deja = 1; - if (f0 != null) - return f0; - h1 = f1; - h2 = f2; - } else if ((d == f0) || (d == f1) || (d == f2)) { - deja = -1; - if (c0 != null) - return c0; - h1 = c1; - h2 = c2; - } else { - System.out.println("ERREUR " + id); - return null; - } - g1 = teste(h1); - g2 = teste(h2); - if (g1 == null) - return h2; - if (g2 != null) - System.out.print("(ALT " + h2.id + ")"); - return h1; - } - - ArcData teste(ArcData d) { - if (d == null) - return null; - if (d.deja != 0) - return null; - ArcData h = null; - if (d.c0 == this) - h = d.f0; - else if (d.f0 == this) - h = d.c0; - else - System.out.println("ERREUR " + id + " " + d.id); - if (h == null) - return null; - if (((h.f1 == d) || (h.f2 == d)) && (h.f0 == null) && (h.deja <= 0)) - return h; - if (((h.c1 == d) || (h.c2 == d)) && (h.c0 == null) && (h.deja >= 0)) - return h; - return null; - } - - ArcData visit() { - if (f0 != null) - return f0; - if (c0 != null) - return c0; - return null; - } - - ArcData[] getChaine0() { - deja = 1; - ArcData d1, d2, di, df; - d1 = this; - d2 = c0; - while (d2 != null) { - if (d2 == this) { - System.out.println("Arc " + id); - return new ArcData[] { - this, - null - }; - } - d2.deja = 1; - if (d2.c0 == d1) { - d1 = d2; - d2 = d2.f0; - } else if (d2.f0 == d1) { - d1 = d2; - d2 = d2.c0; - } else { - System.out.println("Erreur " + d1.id + "->" + d2.id); - break; - } - } - di = d1; - d1 = this; - d2 = f0; - while (d2 != null) { - d2.deja = 1; - if (d2.c0 == d1) { - d1 = d2; - d2 = d2.f0; - } else if (d2.f0 == d1) { - d1 = d2; - d2 = d2.c0; - } else { - System.out.println("Erreur " + d1.id + "->" + d2.id); - break; - } - } - df = d1; - System.out.println("arc " + di.id + "->" + df.id); - return new ArcData[] { - di, - df - }; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Data.java b/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Data.java deleted file mode 100644 index 23face498..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Data.java +++ /dev/null @@ -1,58 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/e00/E00Data.java,v -// $ -// $RCSfile: E00Data.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.e00; - -public class E00Data { - int type, valeur, id, valeur2, ID = -1; - - public E00Data(int id) { - this.id = id; - } - - public E00Data() {} - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(" id:"); - sb.append(id); - - if (ID != -1) { - sb.append(" ID:"); - sb.append(ID); - } - - sb.append(" type:"); - sb.append(type); - sb.append(" value:"); - sb.append(valeur); - - if (valeur != valeur2) { - sb.append('-'); - sb.append(valeur2); - } - sb.append(' '); - return sb.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Layer.java b/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Layer.java deleted file mode 100644 index 2d07a800b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Layer.java +++ /dev/null @@ -1,820 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/e00/E00Layer.java,v $ -// $RCSfile: E00Layer.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.e00; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Font; -import java.awt.Frame; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.AbstractButton; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JTextField; - -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.location.BasicLocation; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * Description of the Class an Layer showing data from an .e00 file - * data is extracted with E00Parser class possibilities to filter arcs - * according to their types or value. - *

- * - * Examples of properties for OpenMap: - *

- * - *

- * 
- *  
- *   
- *    
- *     
- *      
- *       
- *        
- *         ### E00 layer
- *         e00.class=com.bbn.openmap.layer.e00.E00Layer
- *         e00.prettyName=E00 file
- *         e00.FileName=data/france/hynet.e00
- *         ### E00 layer
- *         es00.class=E00.E00Layer
- *         es00.prettyName=ES00 file
- *         es00.FileName=data/france/rdline.e00
- *         es00.ArcColors= FF0000FF,FFEE5F3C,FFFFCC00,FF339700,FFFFFFFF,FFFFFFFF,FFFFFFFF,FFFFFFFF,FF666666,FFFFFFFF
- *         es00.ArcVisible=true
- *         es00.LabVisible=false
- *         es00.Tx7Visible=true
- *         es00.LabFont =Arial 10 ITALIC BOLD
- *         ###other properties Tx7Color LabColors SelectTx7Color SelectLabColor SelectArcColor LabTextColor Tx7Font
- *          
- *        
- *       
- *      
- *     
- *    
- *   
- *  
- * 
- * - * @since OpenMap 4.5.5 - * @author Thomas Paricaud - */ -public class E00Layer extends OMGraphicHandlerLayer implements ActionListener { - - protected OMGraphicList arcs; - protected OMGraphicList labs; - protected OMGraphicList tx7; - protected boolean ArcVisible = true; - protected boolean LabVisible = true; - protected boolean Tx7Visible = true; - protected JPanel gui; - protected JLabel label; - - protected Paint[] ArcColors, LabColors; - protected Paint Tx7Color; - protected Paint SelectTx7Color; - protected Paint SelectLabColor; - protected Paint SelectArcColor; - protected Paint LabTextColor; - protected OMGraphic LabMarker; - protected Font LabFont, Tx7Font; - protected int filtreValeur = Integer.MIN_VALUE; - protected int filtreType = Integer.MIN_VALUE; - protected JFileChooser fileChooser; - protected File E00File; - - public E00Layer() { - super(); - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - } - - /** - * OMGraphicHandlerLayer method, get the OMGraphics from the data - * in the file. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList g = getList(); - - if (g == null) { - try { - E00Parser parser = new E00Parser(E00File); - parser.setPaints(ArcColors, - LabColors, - Tx7Color, - SelectTx7Color, - SelectLabColor, - SelectArcColor, - LabTextColor); - parser.setLabMarker(LabMarker); - parser.setFonts(LabFont, Tx7Font); - - g = parser.getOMGraphics(); - arcs = parser.getArcList(); - labs = parser.getLabList(); - tx7 = parser.getTx7List(); - - setListVisibility(); - - } catch (Exception ex) { - ex.printStackTrace(System.out); - Debug.error("E00Layer|" + getName() + ".prepare(): " - + ex.getMessage()); - } - } - - Projection proj = getProjection(); - if (proj != null && g != null) { - g.generate(proj); - } - - return g; - } - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than - * the setArgs method. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - * @since - */ - public void setProperties(String prefix, java.util.Properties props) { - super.setProperties(prefix, props); - String E00FileName = props.getProperty(prefix + ".FileName"); - ArcVisible = PropUtils.booleanFromProperties(props, prefix - + ".ArcVisible", ArcVisible); - LabVisible = PropUtils.booleanFromProperties(props, prefix - + ".LabVisible", LabVisible); - Tx7Visible = PropUtils.booleanFromProperties(props, prefix - + ".Tx7Visible", Tx7Visible); - - Paint dfault = null; - - ArcColors = parseColors(props, prefix, "ArcColors", Color.black); - LabColors = parseColors(props, prefix, "LabColors", Color.black); - Tx7Color = parseColor(props, prefix, "Tx7Color", dfault); - SelectTx7Color = parseColor(props, prefix, "SelectTx7Color", null); - SelectLabColor = parseColor(props, prefix, "SelectLabColor", null); - SelectArcColor = parseColor(props, prefix, "SelectArcColor", null); - LabTextColor = parseColor(props, prefix, "LabTextColor", null); - LabFont = parseFont(props, prefix, "LabFont", null); - Tx7Font = parseFont(props, prefix, "tx7Font", null); - - try { - openFile(new File(E00FileName)); - } catch (Exception ex) { - Debug.error("E00Layer: error - " + ex.getMessage()); - if (Debug.debugging("e00")) { - ex.printStackTrace(); - } - } - } - - /** - * Gets the GUI attribute of the E00Layer object - * - * @return The GUI value - * @since - */ - public Component getGUI() { - if (gui == null) { - gui = PaletteHelper.createPaletteJPanel("E00"); - label = new JLabel((E00File != null) ? E00File.getName() - : " "); - gui.add(label); - addToGUI(gui, new JCheckBox("Arcs", ArcVisible), "ARCS"); - addToGUI(gui, new JCheckBox("Points", LabVisible), "LABS"); - addToGUI(gui, new JCheckBox("Tx7", Tx7Visible), "TX7"); - gui.add(new JLabel("Filter")); - gui.add(new JLabel(" By Value")); - addToGUI(gui, new JTextField(10), "VALEUR"); - gui.add(new JLabel(" By Type")); - addToGUI(gui, new JTextField(10), "TYPE"); - gui.add(new JSeparator()); - addToGUI(gui, new JButton("Open File"), "OPEN"); - addToGUI(gui, new JButton("Export Arcs"), "ExpArcs"); - addToGUI(gui, new JButton("Export Points"), "ExpPoints"); - } - return gui; - } - - /** - * Adds a feature to the GUI attribute of the E00Layer object - * - * @param b The feature to be added to the GUI attribute - * @param cmd The feature to be added to the GUI attribute - * @since - */ - protected void addToGUI(JPanel gui, AbstractButton b, String cmd) { - b.setActionCommand(cmd); - b.addActionListener(this); - gui.add(b); - } - - /** - * Adds a feature to the Gui attribute of the E00Layer object - * - * @param b The feature to be added to the Gui attribute - * @param cmd The feature to be added to the Gui attribute - * @since - */ - protected void addToGUI(JPanel gui, JTextField b, String cmd) { - b.setActionCommand(cmd); - b.addActionListener(this); - gui.add(b); - } - - /** - * Description of the Method - * - * @param e Description of Parameter - * @since - */ - public void actionPerformed(ActionEvent e) { - String Action = e.getActionCommand(); - if ("OPEN".equals(Action)) { - openFile(chooseFile(0)); - doPrepare(); - } else if ("ExpArcs".equals(Action)) { - exportArcs1(); - } else if ("ExpPoints".equals(Action)) { - exportPoints(); - } else if ("VALEUR".equals(Action)) { - filtreValeur = getVal(e); - filtre(); - } else if ("TYPE".equals(Action)) { - filtreType = getVal(e); - filtre(); - } else if ("ARCS".equals(Action)) { - JCheckBox cb = (JCheckBox) e.getSource(); - ArcVisible = cb.isSelected(); - if (arcs != null) - arcs.setVisible(ArcVisible); - repaint(); - } else if ("LABS".equals(Action)) { - JCheckBox cb = (JCheckBox) e.getSource(); - LabVisible = cb.isSelected(); - if (labs != null) - labs.setVisible(LabVisible); - repaint(); - } else if ("TX7".equals(Action)) { - JCheckBox cb = (JCheckBox) e.getSource(); - Tx7Visible = cb.isSelected(); - if (tx7 != null) - tx7.setVisible(Tx7Visible); - repaint(); - } - } - - public String getInfoText(OMGraphic omg) { - String t = ""; - if (arcs != null && arcs.contains(omg)) { - t = "arcs"; - } else if (labs != null && labs.contains(omg)) { - t = "point"; - } - - E00Data d = (E00Data) omg.getAttribute(OMGraphic.APP_OBJECT); - return t + d; - } - - /** - * Gets the Frame attribute of the E00Layer object - * - * @return The Frame value - * @since - */ - protected Frame getFrame() { - if (gui == null) { - return null; - } - - for (Container p = gui.getParent(); p != null; p = p.getParent()) { - if (p instanceof Frame) { - return (Frame) p; - } - } - - return null; - } - - /** - * Sets the LineColor attribute of the E00Layer object - * - * @param C The new LineColor value - * @since - */ - void setLineColor(Color C) { - OMGraphicList graphics = getList(); - if (graphics != null) { - graphics.setLinePaint(C); - } - repaint(); - } - - /** - * Gets the Val attribute of the E00Layer object - * - * @param e Description of Parameter - * @return The Val value - * @since - */ - int getVal(ActionEvent e) { - int val; - JTextField T = (JTextField) e.getSource(); - try { - val = Integer.parseInt(T.getText()); - } catch (NumberFormatException ex) { - val = Integer.MIN_VALUE; - } - return val; - } - - public void setListVisibility() { - - if (arcs != null) { - arcs.setVisible(ArcVisible); - } - - if (labs != null) { - labs.setVisible(LabVisible); - } - - if (tx7 != null) { - tx7.setVisible(Tx7Visible); - } - - } - - /** - * Description of the Method - * - * @param f Description of Parameter - * @since - */ - protected void openFile(File f) { - - if (f == null) { - return; - } - - if (!f.exists()) { - Debug.output("E00|" + getName() + ": missing file"); - return; - } - - E00File = f; - - if (gui != null) { - label.setText(E00File.getName()); - } - } - - /** - * Description of the Method - * - * @param type Description of Parameter - * @return Description of the Returned Value - * @since - */ - protected File chooseFile(int type) { - Frame frame = getFrame(); - File f = null; - if (fileChooser == null) - fileChooser = new JFileChooser(); - - fileChooser.setCurrentDirectory(E00File); - if (type == 0) - fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); - else - fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); - int retval = fileChooser.showDialog(frame, null); - if (retval == JFileChooser.APPROVE_OPTION) - f = fileChooser.getSelectedFile(); - - return f; - } - - /** - * Description of the Method - * - * @since - */ - protected void filtre() { - System.out.print("E00: filter type=" + filtreType + " value=" - + filtreValeur); - OMGraphic og; - Object O; - int count = 0; - OMGraphicList g = arcs; - int n = arcs.size(); - if ((filtreType == Integer.MIN_VALUE) - && (filtreValeur == Integer.MIN_VALUE)) { - for (int i = 0; i < n; i++) - g.getOMGraphicAt(i).setVisible(true); - count = n; - } else - for (int i = 0; i < n; i++) { - og = g.getOMGraphicAt(i); - O = og.getAttribute(OMGraphic.APP_OBJECT); - if (O == null) - setVisible(false); - else { - E00Data d = (E00Data) O; - boolean r = true; - if (filtreType != Integer.MIN_VALUE) - r &= (filtreType == d.type); - if (filtreValeur != Integer.MIN_VALUE) - r &= (filtreValeur == d.valeur); - og.setVisible(r); - if (r) - count++; - } - } - - Debug.output(" count:" + count); - repaint(); - } - - /** - * Description of the Method - * - * @since - */ - protected void exportArcs() { - if (arcs == null) - return; - - Vector V = new Vector(); - int n = arcs.size(); - double ll[]; - int llsize; - double lnmax = Double.MIN_VALUE; - double lnmin = Double.MAX_VALUE; - double ltmin = lnmin; - double ltmax = lnmax; - double lt; - double ln; - for (int i = 0; i < n; i++) { - OMPoly oj = (OMPoly) arcs.getOMGraphicAt(i); - if (oj == null) - continue; - E00Data data = (E00Data) oj.getAttribute(OMGraphic.APP_OBJECT); - if (data == null) - continue; - ll = oj.getLatLonArray(); - llsize = ll.length; - if ((ll[0] != ll[llsize - 2]) || (ll[1] != ll[llsize - 1])) { - // contour non clos; - double[] coords = new double[] { ll[0], ll[1], ll[llsize - 2], - ll[llsize - 1] }; - ArcData dn = new ArcData(data); - dn.coords = coords; - oj.putAttribute(OMGraphic.APP_OBJECT, dn); - V.add(dn); - } - int k = 0; - while (k < llsize) { - lt = ll[k++]; - ln = ll[k++]; - if (lt > ltmax) - ltmax = lt; - else if (lt < ltmin) - ltmin = lt; - if (ln > lnmax) - lnmax = ln; - else if (ln < lnmin) - lnmin = ln; - } - } - System.out.println("#minmax " + lnmin + " " + lnmax + " " + ltmin + " " - + ltmax); - int unClosedCount = V.size(); - ArcData[] unClosed = (ArcData[]) V.toArray(new ArcData[unClosedCount]); - - V.clear(); - V = null; - //chercher les connections; - ArcData d0; - //chercher les connections; - ArcData d1; - //chercher les connections; - ArcData d2; - //chercher les connections; - ArcData dx; - double lt1; - double lg1; - double lt2; - double lg2; - for (int i = 0; i < unClosedCount; i++) { - d0 = unClosed[i]; - d0.deja = 0; - if (d0.type > 1) - continue; - lt1 = d0.coords[0]; - lg1 = d0.coords[1]; - lt2 = d0.coords[2]; - lg2 = d0.coords[3]; - for (int j = i + 1; j < unClosedCount; j++) { - d1 = unClosed[j]; - if (d1.type > 1) - continue; - if ((lt1 == d1.coords[0]) && (lg1 == d1.coords[1])) { - d1.setC(d0); - d0.setC(d1); - } else if ((lt1 == d1.coords[2]) && (lg1 == d1.coords[3])) { - d1.setF(d0); - d0.setC(d1); - } - if ((lt2 == d1.coords[0]) && (lg2 == d1.coords[1])) { - d1.setC(d0); - d0.setF(d1); - } else if ((lt2 == d1.coords[2]) && (lg2 == d1.coords[3])) { - d1.setF(d0); - d0.setF(d1); - } - } - } - for (int k = 0; k < unClosedCount; k++) { - d0 = unClosed[k]; - if ((d0.type != 0) || (d0.deja != 0)) - continue; - if ((d0.c0 == null) && (d0.f0 == null)) - continue; - d1 = d0; - d2 = (d1.c0 == null) ? d1.f0 : d1.c0; - System.out.print("#contour "); - System.out.print(d0.id); - System.out.print(' '); - int decount = unClosedCount * 3 / 2; - do { - System.out.print(d2.id); - if (d2.deja != 0) - System.out.print('*'); - System.out.print(' '); - dx = d2.visit(d1); - d1 = d2; - d2 = dx; - if (decount-- < 0) { - System.out.print(" BOUCLE "); - break; - } - } while ((d2 != null) && (d2 != d0)); - if (d2 == null) - System.out.print(" unclosed"); - System.out.println(); - System.out.println(); - } - - for (int i = 0; i < n; i++) { - OMPoly oj = (OMPoly) arcs.getOMGraphicAt(i); - if (oj == null) - continue; - E00Data data = (E00Data) oj.getAttribute(OMGraphic.APP_OBJECT); - if (data == null) - continue; - ll = oj.getLatLonArray(); - llsize = ll.length; - double z = data.valeur * 0.304; -// double z2 = data.valeur2 * 0.304; - boolean closed = true; -// float[] coords = null; - if (data instanceof ArcData) { - ArcData dn = (ArcData) data; -// coords = dn.coords; - dn.coords = null; - closed = false; - } - int k = 0; - System.out.println("#type " + data.type); - while (k < llsize) { - lt = ll[k++]; - ln = ll[k++]; - System.out.println("c " + ln + " " + lt + " " + z); - } - System.out.println((closed) ? "#LC" : "#LX"); - System.out.println(); - } - - } - - /** - * Description of the Method - * - * @since - */ - protected void exportArcs1() { - PrintStream out = null; - double lt; - double ln; - double ll[]; - int llsize; - int n; - File f = chooseFile(1); - if (arcs == null) - return; - if (f == null) - return; - try { - out = new PrintStream(new FileOutputStream(f)); - } catch (IOException e) { - System.out.println(e); - return; - } - - n = arcs.size(); - for (int i = 0; i < n; i++) { - OMPoly oj = (OMPoly) arcs.getOMGraphicAt(i); - if (oj == null) - continue; - if (!oj.isSelected()) - continue; - ll = oj.getLatLonArray(); - llsize = ll.length; - out.println(oj.getLinePaint()); - if ((ll[0] != ll[llsize - 2]) || (ll[1] != ll[llsize - 1])) - out.print("MetaPolyline: "); - else { - llsize -= 2; - out.print("MetaPolyline: "); - } - out.print(llsize / 2); - Object o = oj.getAttribute(OMGraphic.APP_OBJECT); - if (o instanceof String) - System.out.println(o); - else - out.println(); - int k = 0; - while (k < llsize) { - lt = ll[k++]; - ln = ll[k++]; - out.println(ln + " " + lt); - } - } - out.close(); - - } - - /** - * Description of the Method - * - * @since - */ - protected void exportPoints() { - if (labs == null) - return; - //OMGraphic oj ; - BasicLocation oj; - double lt; - double ln; - double z; - int n = labs.size(); - System.out.println("#type 0"); - for (int i = 0; i < n; i++) { - oj = (BasicLocation) labs.getOMGraphicAt(i); - if (oj == null) - continue; - E00Data data = (E00Data) getAttribute(OMGraphic.APP_OBJECT); - if (data == null) - continue; - lt = Math.toRadians(oj.lat); - ln = Math.toRadians(oj.lon); - z = data.valeur * 0.304; - System.out.println("c " + ln + " " + lt + " " + z); - } - - } - - /** - * Description of the Method - * - * @param props Description of Parameter - * @param prefix Description of Parameter - * @param prop Description of Parameter - * @param dfault Description of Parameter - * @return Description of the Returned Value - * @since - */ - protected Paint parseColor(Properties props, String prefix, String prop, - Paint dfault) { - try { - return PropUtils.parseColorFromProperties(props, prefix + "." - + prop, dfault); - } catch (NumberFormatException exc) { - System.out.println("Color Error " + prefix + "." + prop); - } - return dfault; - } - - /** - * Description of the Method - * - * @param props Description of Parameter - * @param prefix Description of Parameter - * @param prop Description of Parameter - * @param err Description of Parameter - * @return Description of the Returned Value - * @since - */ - protected Paint[] parseColors(Properties props, String prefix, String prop, - Paint err) { - Paint[] colors = null; - String[] colorStrings = PropUtils.stringArrayFromProperties(props, - prefix + "." + prop, - " ,"); - if (colorStrings != null) { - colors = new Color[colorStrings.length]; - for (int i = 0; i < colorStrings.length; i++) - try { - colors[i] = PropUtils.parseColor(colorStrings[i]); - } catch (NumberFormatException exc) { - System.out.println("Colors Error " + prefix + "." + prop - + " " + i); - colors[i] = err; - } - - } - return colors; - } - - /** - * Description of the Method - * - * @param props Description of Parameter - * @param prefix Description of Parameter - * @param prop Description of Parameter - * @param dfault Description of Parameter - * @return Description of the Returned Value - * @since - */ - protected Font parseFont(Properties props, String prefix, String prop, - Font dfault) { - String[] fontItems = PropUtils.stringArrayFromProperties(props, prefix - + "." + prop, " ,"); - int style = 0; - int size = 10; - if (fontItems == null || fontItems.length == 0) - return dfault; - try { - size = Integer.parseInt(fontItems[1]); - } catch (Exception e) { - } - - for (int i = 2; i < fontItems.length; i++) { - String S = fontItems[i]; - if ("BOLD".equals(S)) - style |= Font.BOLD; - else if ("ITALIC".equals(S)) - style |= Font.ITALIC; - else if ("PLAIN".equals(S)) - style |= Font.PLAIN; - } - return new Font(fontItems[0], style, size); - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Parser.java b/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Parser.java deleted file mode 100644 index 4bf2ced8a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/E00Parser.java +++ /dev/null @@ -1,997 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/e00/E00Parser.java,v $ -// $RCSfile: E00Parser.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.e00; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Paint; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -import com.bbn.openmap.layer.location.BasicLocation; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.Debug; - -/** - * A parser for an E00 file. Description of the Class parses an E00 file and - * provides as result an OMGraphicList containing up to 3 OMGraphicLists: - * - *
- * 
- *   - arcs : OMPoly read in ARC records
- *   - labs : BasicLocations read in LAB records
- *   - tx7  : OMPolys and BasicLocation read in TX7 records
- * 
- * 
- * - * PAl,LOG,SIN,PRJ,TOL records are ignored.
- * From IFO records (if available) :
- * - each arc gets an AppObject including the type and a value (generally an - * altitude)
- * - each lab gets an AppObject including the type, 2 values and the String to - * display if available - the type is used to decide the color, from the Color - * array. Color and String may be also extracted from PAT or AAT records.
- * - * This software is provided as it is. No warranty of any kind, and in - * particular I don't know at all if it meets e00 file specification. It works - * quite good on files from GIS data depot . - * - * - * @author paricaud - */ -public class E00Parser { - protected OMGraphicList labs, arcs, tx7; - protected BufferedReader isr; - protected String prefix; - protected int narc = 1, npoint = 1, unClosedCount = 0; - protected Paint[] ArcColors = defaultColors; - protected Paint[] LabColors = defaultColors; - protected Paint tx7Color; - protected Paint SelectTX7Color, SelectLabColor, SelectArcColor, LabTextColor; - protected Font labFont, tx7Font; - protected OMGraphic LabMarker; - protected Color defaultcolor = Color.blue; - public final static Color[] defaultColors = { Color.black, Color.blue, Color.cyan, - Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, - Color.pink, Color.red, Color.white, Color.yellow }; - - protected static E00Record infoRecord = new E00Record(new int[] { 0, 30, 34, 38, 42, 46, 56 }, new int[] { - 20, 20, 50, 50, 50, 50 }, null); - protected static E00Record itemRecord = new E00Record(new int[] { 0, 14, 19, 21, 26, 28, 32, - 34, 37, 39, 43, 47, 49, 69 }, new int[] { 20, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, - 50, 50 }, null); - - /** - * Constructor for the E00Parser object - * - * @param mdname File Name to parse - * @exception IOException - * @since - */ - public E00Parser(String mdname) throws IOException { - isr = new BufferedReader(new FileReader(mdname)); - setPrefix(mdname); - } - - /** - * Constructor for the E00Parser object - * - * @param f File to parse - * @exception IOException - * @since - */ - public E00Parser(File f) throws IOException { - isr = new BufferedReader(new FileReader(f)); - setPrefix(f.getName()); - } - - /** - * Sets the Prefix attribute of the E00Parser object - * - * @param S The new Prefix value - * @since - */ - public void setPrefix(String S) { - int n = S.indexOf('.'); - if (n == -1) - prefix = S.toUpperCase(); - else - prefix = S.substring(0, n).toUpperCase(); - } - - /** - * Sets the Colors attribute of the E00Parser object - * - * @param ArcColors Paint array for arcs - * @param LabColors Paint array for labs marker - * @param tx7Color Paint for tx7 - * @param SelectTX7Color Paint for tx7 when selected - * @param SelectLabColor Paint for labs when selected (not working ?) - * @param SelectArcColor Paint for arcs when selected - * @param LabTextColor Paint for labs text . If null, text has same paint as - * marker - * @since - */ - public void setPaints(Paint[] ArcColors, Paint[] LabColors, Paint tx7Color, - Paint SelectTX7Color, Paint SelectLabColor, Paint SelectArcColor, - Paint LabTextColor) { - - this.ArcColors = (ArcColors == null) ? defaultColors : ArcColors; - this.LabColors = (LabColors == null) ? defaultColors : LabColors; - this.tx7Color = tx7Color; - this.SelectTX7Color = SelectTX7Color; - this.SelectLabColor = SelectLabColor; - this.SelectArcColor = SelectArcColor; - this.LabTextColor = LabTextColor; - } - - /** - * Sets the Fonts attribute of the E00Parser object - * - * @param labFont font for labs text - * @param tx7Font font for tx7 text - * @since - */ - public void setFonts(Font labFont, Font tx7Font) { - this.labFont = labFont; - this.tx7Font = tx7Font; - } - - /** - * Sets the LabMarker attribute of the E00Parser object - * - * @param marker The new LabMarker value - * @since - */ - public void setLabMarker(OMGraphic marker) { - LabMarker = marker; - } - - /** - * Gets the result of the parse process - * - * @return The OMGraphics value - * @exception IOException - * @since - */ - public OMGraphicList getOMGraphics() throws IOException { - OMGraphicList WV = new OMGraphicList(); - isr.readLine(); - while (true) { - String S = isr.readLine(); - if (S == null) - break; - // System.out.println("E00 "+S); - if (S.startsWith("ARC")) - readARC(); - else if (S.startsWith("LAB")) - readLAB(); - else if (S.startsWith("IFO")) - readIFO(); - else if (S.startsWith("LOG")) - readLOG(); - else if (S.startsWith("PRJ")) - readPRJ(); - else if (S.startsWith("CNT")) - readCNT(); - else if (S.startsWith("PAL")) - readPAL(); - else if (S.startsWith("SIN")) - readSIN(); - else if (S.startsWith("TOL")) - readTOL(); - else if (S.startsWith("TX7")) - readTX7(); - else if (S.startsWith("EOS")) - break; - // System.out.println("E00 "+S+" fin"); - } - - if (labs != null) { - labs.putAttribute(OMGraphic.APP_OBJECT, "LABS"); - WV.add(labs); - } - if (arcs != null) { - arcs.putAttribute(OMGraphic.APP_OBJECT, "ARCS"); - WV.add(arcs); - } - if (tx7 != null) { - tx7.putAttribute(OMGraphic.APP_OBJECT, "TX7"); - WV.add(tx7); - } - - return WV; - } - - /** - * Gets the LabMarker attribute of the E00Parser object - * - * @return The LabMarker value - * @since - */ - public OMGraphic getLabMarker() { - return LabMarker; - } - - /** - * read from a string an array of int each float being represented by l - * characters - * - * @param S the String to parse - * @param l the length of int representation - * @param I Description of Parameter - * @since - */ - void parseString(String S, int[] I, int l) { - int i = 0; - for (int j = 0; i < I.length && j < S.length(); j += l) - I[i++] = Integer.parseInt(S.substring(j, j + l).trim()); - } - - /** - * read from a string an array of float each float being represented by 14 - * characters - * - * @param S the String to parse - * @param F the float array receiving the result - * @since - */ - void parseString(String S, double[] F) { - int i = 0; - for (int j = 0; i < F.length && j < S.length(); j += 14) - F[i++] = Float.parseFloat(S.substring(j, j + 14).trim()); - - } - - /** - * read SIN records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readSIN() throws IOException { - while (true) { - String S = isr.readLine(); - if (S == null) - return; - if (S.startsWith("EOX")) - return; - } - } - - /** - * read CNT records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readCNT() throws IOException { - int[] header = new int[1]; - while (true) { - String S = isr.readLine(); - if (S == null) - break; - parseString(S, header, 10); - int n = header[0]; - if (n == -1) - break; - for (int i = 0; i < n; i++) - isr.readLine(); - } - } - - /** - * read TOL records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readTOL() throws IOException { - int[] header = new int[1]; - while (true) { - String S = isr.readLine(); - if (S == null) - break; - parseString(S, header, 10); - if (header[0] == -1) - break; - } - } - - /** - * read PAL records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readPAL() throws IOException { - int[] header = new int[1]; - while (true) { - String S = isr.readLine(); - if (S == null) - break; - parseString(S, header, 10); - int n = header[0]; - if (n == -1) - break; - for (int i = 0; i < n; i += 2) - isr.readLine(); - } - } - - /** - * read TX7 records - * - * @exception IOException - * @since - */ - void readTX7() throws IOException { - Debug.message("e00", "E00: read TX7"); - tx7 = new OMGraphicList(); - int[] header = new int[8]; - double[] coords = new double[2]; - isr.readLine(); - while (true) { - String S = isr.readLine(); - if (S == null) - break; - parseString(S, header, 10); - if (header[0] == -1) - break; - int n = header[2]; - for (int i = 0; i < 8; i++) - isr.readLine(); - double[] llpoints = new double[2 * n]; - int k = 0; - for (int j = 0; j < n; j++) { - S = isr.readLine(); - if (S == null) - return; - parseString(S, coords); - llpoints[k++] = coords[1]; - llpoints[k++] = coords[0]; - } - S = isr.readLine(); - /* - * OMPoly P = new OMPoly(llpoints, OMGraphic.DECIMAL_DEGREES, - * OMGraphic.LINETYPE_STRAIGHT); / llpoints is so transformed to - * radians P.setLinePaint(Color.red); tx7.add(P); BasicLocation bl = - * new BasicLocation(coords[1], coords[0], S, null); - * bl.setShowLocation(true); bl.setShowName(true); tx7.add(bl); - */ - TX7 t = new TX7(llpoints, S, false, tx7Font); - // decimal degrees - if (tx7Color != null) - t.setLinePaint(tx7Color); - if (SelectTX7Color != null) - t.setSelectPaint(SelectTX7Color); - - tx7.add(t); - } - } - - /** - * read LOG records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readLOG() throws IOException { - while (true) { - String S = isr.readLine(); - if (S == null) - return; - if (S.startsWith("EOL")) - return; - } - } - - /** - * read PRJ records (in fact does nothing) - * - * @exception IOException - * @since - */ - void readPRJ() throws IOException { - while (true) { - String S = isr.readLine(); - if (S == null) - return; - if (S.startsWith("EOP")) - return; - } - } - - /** - * read LAB records - * - * @exception IOException - * @since - */ - void readLAB() throws IOException { - Debug.message("e00", "E00: read LAB"); - labs = new OMGraphicList(); - double[] coords = new double[2]; - int[] header = new int[1]; - while (true) { - String S = isr.readLine(); - if (S == null) - break; - parseString(S, header, 10); - int id = header[0]; - if (id == -1) - break; - S = isr.readLine(); - if (S == null) - break; - parseString(S, coords); - BasicLocation bl = new BasicLocation(coords[1], coords[0], "", LabMarker); - setLocationColor(bl, 0); - bl.setShowLocation(true); - labs.add(bl); - bl.putAttribute(OMGraphic.APP_OBJECT, new E00Data(id)); - } - } - - /** - * read ARC records - * - * @exception IOException - * @since - */ - void readARC() throws IOException { - Debug.message("e00", "E00: read ARC"); - arcs = new OMGraphicList(); - int narc = 1; - int[] header = new int[7]; - double[] coords = new double[4]; - while (true) { - String S = isr.readLine(); - if (S == null) - return; - // System.out.println("E00: F "+S); - parseString(S, header, 10); - if (header[0] == -1) - break; - int n = header[6]; - double[] llpoints = new double[2 * n]; - int k = 0; - for (int j = 0; j < n; j++) { - S = isr.readLine(); - if (S == null) - return; - parseString(S, coords); - llpoints[k++] = coords[1]; - llpoints[k++] = coords[0]; - if (++j >= n) - break; - llpoints[k++] = coords[3]; - llpoints[k++] = coords[2]; - } - // System.out.print("f "); - // System.out.println(" # "+narc++ +" nb:"+npoint); - OMPoly P = new OMPoly(llpoints, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT); - P.setLinePaint(getArcPaint(0)); - if (SelectArcColor != null) - P.setSelectPaint(SelectArcColor); - - arcs.add(P); - P.putAttribute(OMGraphic.APP_OBJECT, new E00Data(narc++)); - } - } - - /** - * read AAT records - * - * @exception IOException - * @since - */ - void readAAT() throws IOException { - String S; - String C = prefix + ".AAT"; - do { - S = isr.readLine(); - if (S == null) - return; - } while (!S.startsWith(C)); - int n = Integer.parseInt(S.substring(46).trim()); - Debug.message("e00", "E00: read " + C + " " + n + " points"); - for (int i = 0; i < 9; i++) - isr.readLine(); - int[] I = new int[2]; - for (int i = 0; i < n; i++) { - isr.readLine(); - S = isr.readLine(); - parseString(S, I, 2); - arcs.getOMGraphicAt(i).setLinePaint(getArcPaint(I[0])); - } - } - - /** - * read PAT records - * - * @exception IOException - * @since - */ - void readPAT() throws IOException { - String S; - String C = prefix + ".PAT"; - do { - S = isr.readLine(); - if (S == null) - return; - } while (!S.startsWith(C)); - int n = Integer.parseInt(S.substring(46).trim()); - Debug.message("e00", "E00: read " + C + " " + n + " points"); - for (int i = 0; i < 7; i++) - isr.readLine(); - int[] I = new int[1]; - for (int i = 0; i < n; i++) { - S = isr.readLine(); - if (S == null) - break; - String name = S.substring(50); - // System.out.print(i+" "+S); - S = isr.readLine(); - if (S == null) - break; - // System.out.println(" "+S); - parseString(S, I, 14); - BasicLocation bl = (BasicLocation) labs.getOMGraphicAt(i); - if (S.length() > 0) - bl.setName(name); - else - bl.setLabel(null); - setLocationColor(bl, I[0]); - bl.setShowLocation(true); - } - } - - /** - * read IFO information - * - * @exception IOException - * @since - */ - void readIFO() throws IOException { - while (true) { - infoRecord.read(isr); - String info = infoRecord.getStringField(0).trim(); - if (info.startsWith("EOI")) - break; - int n = infoRecord.getIntField(5); - E00Record r = getRecord(); - if (!info.startsWith(prefix)) - readANY(r, n); - else { - String suffix = info.substring(prefix.length() + 1); - if (suffix.equals("PAT")) - readPAT(r, n); - else if (suffix.equals("AAT")) - readAAT(r, n); - else if (suffix.equals("BND")) - readANY(r, n); - else if (suffix.equals("TIC")) - readANY(r, n); - else - readANY(r, n); - } - Debug.message("e00", "E00: " + info + " " + n); - } - } - - /** - * read other records from IFO (does nothing else) - * - * @param r record structure - * @param n number of records - * @exception IOException - * @since - */ - void readANY(E00Record r, int n) throws IOException { - for (int i = 0; i < n; i++) - r.read(isr); - } - - /** - * read form IFO, PAT records extract data from them and put this data in an - * E00data structure associated with the graphic object - * - * @param r PTT/IFO structure - * @param n record number to read - * @exception IOException - * @since - */ - void readPAT(E00Record r, int n) throws IOException { - int itype = r.getItemIndex(prefix.substring(0, 2) + "PTTYPE"); - int ival = r.getItemIndex(prefix.substring(0, 2) + "PTVAL"); - int ival2 = r.getItemIndex(prefix.substring(0, 2) + "PYTYPE"); - int iname = r.getItemIndex(prefix.substring(0, 2) + "PTNAME"); - // Unused - // int iflag = r.getItemIndex(prefix.substring(0, 2) + "PTFLAG"); - - // System.out.println(itype+" "+iname+" "+iflag); - for (int i = 0; i < n; i++) { - r.read(isr); - BasicLocation bl = (BasicLocation) labs.getOMGraphicAt(i); - String S = r.getStringField(iname).trim(); - if (bl == null) - continue; - if (S.length() > 0) { - Debug.message("e00", S); - bl.setName(S); - bl.setShowName(true); - } else - bl.setLabel(null); - E00Data d = (E00Data) bl.getAttribute(OMGraphic.APP_OBJECT); - if (itype != -1) - d.type = r.getIntField(itype); - if (ival != -1) - d.valeur = r.getIntField(ival); - if (ival2 != -1) - d.valeur2 = r.getIntField(ival2); - else - d.valeur2 = d.valeur; - if (itype >= 0) - setLocationColor(bl, r.getIntField(itype)); - } - } - - /** - * read form IFO, AAT records extract data from them and put this data in an - * E00data structure associated with the graphic object - * - * @param r AAT/IFO structure - * @param n record number to read - * @exception IOException - * @since - */ - void readAAT(E00Record r, int n) throws IOException { - OMGraphic og; - int type = Integer.MIN_VALUE; - int val = Integer.MIN_VALUE; - int itype = r.getItemIndex(prefix.substring(0, 2) + "LNTYPE"); - int ival = r.getItemIndex(prefix.substring(0, 2) + "LNVAL"); - int iID = r.getItemIndex(prefix.substring(0, 2) + "NET-ID"); - int ID = -1; - for (int i = 0; i < n; i++) { - r.read(isr); - if ((itype == -1) && (ival == -1)) - continue; - og = arcs.getOMGraphicAt(i); - if (itype != -1) { - type = r.getIntField(itype); - og.setLinePaint(getArcPaint(type)); - } - if (ival != -1) - val = r.getIntField(ival); - - if (iID != -1) - ID = r.getIntField(iID); - - E00Data data = (E00Data) og.getAttribute(OMGraphic.APP_OBJECT); - data.type = type; - data.valeur = val; - data.valeur2 = val; - data.ID = ID; - } - } - - /** - * Sets the Location Color anf font attributes - * - * @param bl basic location - * @param t color index - * @since - */ - private void setLocationColor(BasicLocation bl, int t) { - if (bl == null) - return; - Paint c = getLabPaint(t); - OMText label = bl.getLabel(); - if (label != null) { - if (LabTextColor != null) - label.setLinePaint(LabTextColor); - else - label.setLinePaint(c); - if (labFont != null) - label.setFont(labFont); - } - bl.setLocationPaint(c); - if (SelectLabColor != null) - bl.setSelectPaint(SelectLabColor); - } - - /** - * get the arc color associated with a type value . - * - * @param i the type value - * @return The Color value - * @since - */ - private Paint getArcPaint(int i) { - if (i >= ArcColors.length) - i = ArcColors.length - 1; - if (i < 0) - i = 0; - return ArcColors[i]; - } - - /** - * get the lab color associated with a type value . - * - * @param i the type value - * @return The Color value - * @since - */ - private Paint getLabPaint(int i) { - if (i >= LabColors.length) - i = LabColors.length - 1; - if (i < 0) - i = 0; - return LabColors[i]; - } - - /** - * set the itemRecord structure from the data read with infoRecord - * - * @return The itemRecord set - * @exception IOException - * @since - */ - private E00Record getRecord() throws IOException { - int itemNumber = infoRecord.getIntField(2); - int positions[] = new int[itemNumber + 1]; - int types[] = new int[itemNumber]; - String[] names = new String[itemNumber]; - for (int i = 0; i < itemNumber; i++) { - itemRecord.read(isr); - types[i] = itemRecord.getIntField(7); - names[i] = itemRecord.getStringField(0).trim(); - int p = positions[i]; - switch (types[i]) { - case 20: - positions[i + 1] = p + itemRecord.getIntField(5); - break; - case 30: - positions[i + 1] = p + itemRecord.getIntField(5); - break; - case 50: - positions[i + 1] = p + 11; - break; - case 60: - positions[i + 1] = p + 14; - } - } - return new E00Record(positions, types, names); - } - - /** - * Description of the Class - * - * a class used to - describe the structure of records (fixed columns) - - * parse records according to the structure - deliver data on le last persed - * record - * - * @author tparicau - */ - static class E00Record { - String[] itemName; - int n; - int[] fieldType, fieldPosition; - private String[] stringField; - private float[] floatField; - private int[] intField; - - /** - * Constructor for the E00Record object - * - * @param positions Description of Parameter - * @param types Description of Parameter - * @param names Description of Parameter - * @since - */ - E00Record(int[] positions, int[] types, String[] names) { - fieldType = types; - fieldPosition = positions; - itemName = names; - n = positions.length - 1; - if (types.length < n) { - n = types.length; - System.err.println("E00Record err 1"); - } - stringField = new String[n]; - floatField = new float[n]; - intField = new int[n]; - // print(); - } - - /** - * delivers the int in fth position - * - * @param f the position - * @return The int value - * @since - */ - int getIntField(int f) { - if (f < 0) - return Integer.MIN_VALUE; - return intField[f]; - } - - /** - * delivers the float in fth position - * - * @param f the position - * @return The float value - * @since - */ - float getFloatField(int f) { - if (f < 0) - return Float.MIN_VALUE; - return floatField[f]; - } - - /** - * delivers the String in fth position - * - * @param f the position - * @return The String - * @since - */ - - String getStringField(int f) { - if (f < 0) - return ""; - return stringField[f]; - } - - /** - * Gets the ItemIndex attribute of the E00Record object - * - * @param S the name of item - * @return the index of item - * @since - */ - int getItemIndex(String S) { - if (itemName == null) - return -1; - for (int i = 0; i < itemName.length; i++) - if (itemName[i].equals(S)) - return i; - return -1; - } - - /** - * read a record according with the structure described in thi E00record - * - * @param isr reader where to read data - * @exception IOException - * @since - */ - void read(BufferedReader isr) throws IOException { - String Line = isr.readLine(); - if (Line == null) - return; - int delta = 0; - for (int i = 0; i < n; i++) { - int n1 = fieldPosition[i] - delta; - int n2 = fieldPosition[i + 1] - delta; - if (n1 > 80) { - delta += 80; - n1 -= 80; - n2 -= 80; - Line = isr.readLine(); - } - String S; - if (Line == null) { - break; - } - if (n1 >= Line.length()) - S = ""; - else if (n2 < Line.length()) - S = Line.substring(n1, n2); - else - S = Line.substring(n1); - if (n2 > 80) { - delta += 80; - n2 -= 80; - Line = isr.readLine(); - if (Line == null) { - break; - } - if (n2 < Line.length()) - S += Line.substring(0, n2); - else { - S = Line; - Debug.message("e00", "??" + S); - } - } - try { - switch (fieldType[i]) { - case 20: - stringField[i] = S; - break; - case 30: - case 50: - intField[i] = Integer.parseInt(S.trim()); - break; - case 60: - floatField[i] = Float.parseFloat(S.trim()); - } - } catch (NumberFormatException e) { - if (!Line.startsWith("EOI")) { - Debug.message("e00", "E00:parserr " + i + " " + fieldPosition[i] + " " - + fieldPosition[i + 1] + " " + S); - Debug.message("e00", ">" + Line); - } - } - } - - } - - /** - * Print the record structure - * - * @since - */ - void print() { - System.out.print("Record "); - for (int i = 0; i < n + 1; i++) - System.out.print(fieldPosition[i] + " "); - - System.out.println(); - System.out.print(" "); - for (int i = 0; i < n; i++) - System.out.print(fieldType[i] + " "); - - System.out.println(); - } - } - - /** - * @return OMGraphicsList of arcs. - */ - public OMGraphicList getArcList() { - return arcs; - } - - /** - * @return OMGraphicList of lab. - */ - public OMGraphicList getLabList() { - return labs; - } - - /** - * @return OMGraphicList of Tx7. - */ - public OMGraphicList getTx7List() { - return tx7; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/TX7.java b/src/core/src/main/java/com/bbn/openmap/layer/e00/TX7.java deleted file mode 100644 index bb9895a7b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/TX7.java +++ /dev/null @@ -1,421 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/e00/TX7.java,v $ -// $RCSfile: TX7.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.e00; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.font.LineMetrics; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import com.bbn.openmap.omGraphics.OMGraphicAdapter; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Description of the Class that displays a String along a polygon or a polyline - * defined by lat lon points. - * - * @author paricaud - */ -public class TX7 extends OMGraphicAdapter { - double w = 1, angle = 0; - LatLonPoint llp1 = new LatLonPoint.Double(), - llp2 = new LatLonPoint.Double(); - Point pt1 = new Point(), pt2 = new Point(); - AffineTransform at = new AffineTransform(); - double llpoints[]; - String str; - Font font = defaultFont; - GlyphVector gv; - // GeneralPath path; - double distance; - boolean badprojection; - final static Font defaultFont = new Font("Arial", Font.PLAIN, 10); - - /** - * Constructor for the TX7 object - * - * @param llpoints - * array on lat lon lat lon ... - * @param str - * Text - * @param isRadian - * true if lat lons given in radians - * @since - */ - public TX7(double llpoints[], String str, boolean isRadian) { - this(llpoints, str, isRadian, null); - } - - /** - * Constructor for the TX7 object - * - * @param llpoints - * array on lat lon lat lon ... - * @param str - * Text - * @param isRadian - * true if lat lons given in radians - * @param font - * font used to draw text - * @since - */ - public TX7(double llpoints[], String str, boolean isRadian, Font font) { - if (str == null) - this.str = " "; - else - this.str = str; - if (font == null) - this.font = defaultFont; - else - this.font = font; - setLocation(llpoints, isRadian); - } - - /** - * Constructor for the TX7 object - * - * @param llpoints - * array on lat lon lat lon ... - * @param str - * Text * - * @since - */ - public TX7(double llpoints[], String str) { - this(llpoints, str, true, null); - } - - /** - * Sets the text attribute of the TX7 object - * - * @param S - * The new text value - * @since - */ - public void setText(String S) { - str = S; - compute(); - } - - /** - * Sets the font attribute of the TX7 object - * - * @param f - * The new font value - * @since - */ - public void setFont(Font f) { - font = f; - compute(); - } - - /** - * Sets the location attribute of the TX7 object - * - * @param llpoints - * array on lat lon lat lon ... - * @param isRadian - * true if lat lons given in radians - * @since - */ - public void setLocation(double[] llpoints, boolean isRadian) { - this.llpoints = llpoints; - if (!isRadian) { - float cv = (float) (Math.PI / 180.0); - for (int i = 0; i < llpoints.length; i++) - llpoints[i] *= cv; - } - compute(); - } - - /** - * Gets the font attribute of the TX7 object - * - * @return The font value - * @since - */ - public Font getFont() { - return font; - } - - /** - * Gets the text attribute of the TX7 object - * - * @return The text value - * @since - */ - public String getText() { - return str; - } - - /** - * Gets the location attribute of the TX7 object - * - * @return array on lat lon lat lon ... in radians - * @since - */ - public double[] getLocation() { - return llpoints; - } - - /** - * generate with a new projection - * - * @param proj - * new Projection - * @return Description of the Returned Value - * @since - */ - public boolean generate(Projection proj) { - proj.forward(llp1, pt1); - proj.forward(llp2, pt2); - double dx = pt2.x - pt1.x; - double dy = pt2.y - pt1.y; - at.setToTranslation(pt1.x, pt1.y); - at.rotate(Math.atan2(dy, dx) - angle, 0, 0); - double sc = Math.sqrt(dx * dx + dy * dy); - badprojection = (Double.isNaN(sc) || sc / distance * proj.getScale() > 1000000); - if (badprojection) - Debug.message("e00", "badprojection " + str); - else { - sc /= w; - at.scale(sc, sc); - } - return true; - } - - /** - * render - * - * @param g - * Graphics - * @since - */ - public void render(Graphics g) { - if (!visible) - return; - if (badprojection) - return; - g.setColor(Color.red); - Graphics2D g2d = (Graphics2D) g; - if (selected) - g2d.setPaint(selectPaint); - else - g2d.setPaint(linePaint); - AffineTransform saveAT = g2d.getTransform(); - // Perform transformation - g2d.transform(at); - // Render - g2d.drawGlyphVector(gv, 0, 0); - g.setColor(Color.blue); - /* - * if (path != null) { Stroke st = g2d.getStroke(); g2d.setStroke(new - * BasicStroke(.3f)); g2d.draw(path); g2d.setStroke(st); } - */ - // Restore original transform - g2d.setTransform(saveAT); - } - - /** - * compute the glyphVector - * - * @since - */ - void compute() { - double lt1; - double ln1; - double lt2; - double ln2; - FontRenderContext frc = new FontRenderContext(new AffineTransform(), - true, true); - gv = font.createGlyphVector(frc, str); - Rectangle2D r = gv.getLogicalBounds(); - w = r.getWidth(); - angle = 0; - int nseg = llpoints.length / 2 - 1; - lt1 = llpoints[0]; - ln1 = llpoints[1]; - llp1.setLatLon(lt1, ln1, true); - lt2 = llpoints[2 * nseg]; - ln2 = llpoints[2 * nseg + 1]; - llp2.setLatLon(lt2, ln2, true); - distance = GreatCircle.sphericalDistance(lt1, ln1, lt2, ln2) - * Planet.wgs84_earthEquatorialRadiusMeters; - // System.out.println(nseg+" "+llp1+" "+llp2); - setNeedToRegenerate(true); - visible = false; - - double[] ds = new double[nseg]; - double[] az = new double[nseg]; - double[] cs = new double[nseg]; - int j = 2; - double s = 0; - double corr = 0; - double dz; - double az0 = 0; - for (int i = 0; i < nseg; i++) { - // if(j>llpoints.length-2){System.out.println(j+" "+i+" - // "+nseg);nseg=1;break;} - lt2 = (float) llpoints[j++]; - ln2 = (float) llpoints[j++]; - if (lt2 == lt1 && ln2 == ln1) { - // suppress null segments - i--; - nseg--; - } else { - s += GreatCircle.sphericalDistance(lt1, ln1, lt2, ln2); - ds[i] = s; - az[i] = GreatCircle.sphericalAzimuth(lt1, ln1, lt2, ln2); - if (i > 0) { - dz = (float) Math.tan((az[i] - az0) / 2); - if (dz < 0) { - cs[i - 1] = -dz; - corr -= 2 * dz; - } - } - az0 = az[i]; - lt1 = lt2; - ln1 = ln2; - } - } - if (nseg <= 1) - return; - // now try to play with little boxes - // rotate them either on upper left corner or lower lef corner - // probably can be simplified ... - visible = true; - LineMetrics lm = font.getLineMetrics("MM", frc); - if (lm == null) { - System.out.println("null metrics"); - return; - } - float h = (float) lm.getAscent(); - // System.out.println("ascent:" + h + " w:" + w + " s:" + s + - // " corr:" + corr + " wc:" + (w - corr * h) + " " + str); - corr = 0f; - w -= corr * h; - float sc = (float) (w / s); - for (int i = 0; i < nseg; i++) - ds[i] *= sc; - int m = gv.getNumGlyphs(); - float[] gp = gv.getGlyphPositions(0, m, null); - if (gp == null) - System.out.println("gp null"); - // path = new GeneralPath(); - AffineTransform at; - double dx; - double dy; - double x = 0; - double y = 0; - double xa; - double ya; - double s0 = 0; - double ps; - double s1; - double s2; - double theta; - double theta2; - double thetai; - double dtheta; - double ch0 = 0; - double cos1; - double sin1; - double cos2; - double sin2; - j = 0; - for (int i = 0; i < m; i++) { - if (i == m - 1 || gp == null) { - s = (float) w; - } else { - s = gp[2 * i + 2]; - } - - ps = s - s0; - theta = az[j]; - cos1 = Math.cos(theta); - sin1 = Math.sin(theta); - float ch = (float) (cs[j] * h); - if (s + ch0 < ds[j] - ch || j == nseg - 1) { - xa = x; - ya = y; - x += ps * cos1; - y += ps * sin1; - } else { - theta2 = az[j + 1]; - cos2 = Math.cos(theta2); - sin2 = Math.sin(theta2); - dtheta = theta2 - theta; - s1 = ds[j] - ch - ch0 - s0; - s2 = s1 * Math.sin(dtheta); - s2 = ps * ps - s2 * s2; - s2 = Math.sqrt(s2) - s1 * Math.cos(dtheta); - dx = s1 * cos1 + s2 * cos2; - dy = s1 * sin1 + s2 * sin2; - thetai = Math.atan2(dy, dx); - if (ch == 0) { - xa = x; - ya = y; - } else { - dx += ch * cos1 + ch * cos2; - dy += ch * sin1 + ch * sin2; - xa = x + h * sin1 - h * Math.sin(thetai); - ya = y - h * cos1 + h * Math.cos(thetai); - } - x += dx; - y += dy; - j++; - ch0 = ch; - theta = thetai; - } - - gv.setGlyphPosition(i, new Point2D.Double(xa, ya)); - if (theta != 0) { - at = new AffineTransform(); - at.rotate(theta); - gv.setGlyphTransform(i, at); - } - s0 = s; - /* - * path.moveTo((float) xa, (float) ya); xa += ps * Math.cos(theta); - * ya += ps * Math.sin(theta); path.lineTo((float) xa, (float) ya); - * xa += h * Math.sin(theta); ya -= h * Math.cos(theta); - * path.lineTo((float) xa, (float) ya); xa -= ps * Math.cos(theta); - * ya -= ps * Math.sin(theta); path.lineTo((float) xa, (float) ya); - * path.closePath(); - */ - } - angle = Math.atan2(y, x); - w = Math.sqrt(x * x + y * y); - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/e00/package.html b/src/core/src/main/java/com/bbn/openmap/layer/e00/package.html deleted file mode 100644 index e9851d34c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/e00/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains a Layer that displays e00 data. - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/AbstractEditorTool.java b/src/core/src/main/java/com/bbn/openmap/layer/editor/AbstractEditorTool.java deleted file mode 100644 index 83012d999..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/AbstractEditorTool.java +++ /dev/null @@ -1,146 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/editor/AbstractEditorTool.java,v -// $ -// $RCSfile: AbstractEditorTool.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.editor; - -import java.awt.Container; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter; - -public class AbstractEditorTool extends StandardMapMouseInterpreter implements - EditorTool { - - /** - * Flag to let it's layer know when it wants control over mouse events. - */ - protected boolean wantsEvents = false; - /** - * Used as a placeholder if face is null. - */ - protected boolean visible = false; // until we are told otherwise. - - /** - * Make sure you set the EditorLayer at some point. - */ - protected AbstractEditorTool() { - // Set the layer later. - } - - /** - * The preferred constructor. - */ - public AbstractEditorTool(EditorLayer eLayer) { - setLayer(eLayer); - } - - public void setLayer(OMGraphicHandlerLayer eLayer) { - super.setLayer(eLayer); - if (eLayer instanceof EditorLayer) { - ((EditorLayer) eLayer).setMouseEventInterpreter(this); - } - } - - /** - * Set whether the tool should want MouseEvents. - */ - public void setWantsEvents(boolean value) { - wantsEvents = value; - } - - /** - * Whether the Tool is expecting to be fed MouseEvents. - */ - public boolean wantsEvents() { - return wantsEvents; - } - - /** - * Part of the interface where the EditorLayer can provide components that - * are available via the MapHandler/BeanContext. The object is something - * that has been added to the MapHandler. - */ - public void findAndInit(Object obj) {} - - /** - * Part of the interface where the EditorLayer can provide components that - * are available via the MapHandler/BeanContext. The object is something - * that has been removed from the MapHandler. - */ - public void findAndUndo(Object obj) {} - - /** - * Method where the EditorLayer lets the tool know that the editing function - * has come full circle, so the user interface can be adjusted. - */ - public void drawingComplete(OMGraphic omg, OMAction action) {} - - /** - * A method that lets the EditorTool know whether its interface should be - * visible. - */ - public void setVisible(boolean value) { - if (face != null) { - face.setVisible(value); - } - visible = value; - } - - /** - * A method that lets the EditorTool respond to queries wondering whether - * its interface is visible. - */ - public boolean isVisible() { - if (face != null) { - return face.isVisible(); - } else { - return visible; // they should be the same... - } - } - - // ///////////////////////////// - // Tool interface methods - // ///////////////////////////// - - protected Container face = null; - - /** - * The tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - return face; - } - - /** - * Called when the parent layer detects that it has been removed from the - * application. - */ - public void dispose() { - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/DrawingEditorTool.java b/src/core/src/main/java/com/bbn/openmap/layer/editor/DrawingEditorTool.java deleted file mode 100644 index 175273c5d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/DrawingEditorTool.java +++ /dev/null @@ -1,898 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/editor/DrawingEditorTool.java,v $ -// $RCSfile: DrawingEditorTool.java,v $ -// $Revision: 1.14 $ -// $Date: 2008/09/16 18:37:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.editor; - -import java.awt.Container; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.beancontext.BeanContext; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.gui.GridBagToolBar; -import com.bbn.openmap.gui.OMGraphicDeleteTool; -import com.bbn.openmap.layer.DrawingToolLayer; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.EditToolLoader; -import com.bbn.openmap.tools.drawing.OMCircleLoader; -import com.bbn.openmap.tools.drawing.OMDistanceLoader; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.tools.drawing.OMDrawingToolMouseMode; -import com.bbn.openmap.tools.drawing.OMLineLoader; -import com.bbn.openmap.tools.drawing.OMPointLoader; -import com.bbn.openmap.tools.drawing.OMPolyLoader; -import com.bbn.openmap.tools.drawing.OMRectLoader; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The DrawingEditorTool is a EditorTool for the EditorLayer that will use a - * custom OMDrawingTool to create OMGraphics as needed by the EditorTool. This - * is a class that lets you define which EditToolLoaders the internal - * OMDrawingTool will use for its own, targeted use. These definitions are - * specified in the properties for the EditorLayer using this tool. This class - * provides the OMDrawingTool and all the button mechanisms organized for smooth - * behavior integrated with the regular OpenMap mouse modes. - * - * Properties for an EditorLayer using the DrawingEditorTool: - * - *
- *
- *   # Layer declaration, dtlayer has to go in openmap.layers property
- *   dtlayer.class=com.bbn.openmap.layer.editor.EditorLayer
- *   # GUI name for layer, will also be the ID of the 'hidden' mouse mode used for tool.
- *   dtlayer.prettyName=Drawing Layer
- *   # List of other MouseModes to respond to for the layer, when *not* in editing mode.
- *   dtlayer.mouseModes=Gestures
- *   # Editor Tool to use with layer
- *   dtlayer.editor=com.bbn.openmap.layer.editor.DrawingEditorTool
- *   # This tool lets you hide the drawing attribute controls (lines,
- *   # colors) for the different objects. Default is true.
- *   dtlayer.showAttributes=false
- *  
- *   # List of EditToolLoaders to use in DrawingEditorTool
- *   dtlayer.loaders=polys points lines
- *   # EditToolLoader class to use for the polys
- *   dtlayer.polys.class=com.bbn.openmap.tools.drawing.OMPolyLoader
- *   # Set the DrawingAttributes class to use for polys
- *   dtlayer.polys.attributesClass=com.bbn.openmap.omGraphics.DrawingAttributes
- *   # Polys have specific line color, defaults for other settings.
- *   dtlayer.polys.lineColor=FFFF0000
- *  
- *   # EditToolLoader classes for points and lines, they get rendered
- *   # with whatever color was set last for the DrawingEditorTool.
- *   dtlayer.points.class=com.bbn.openmap.tools.drawing.OMPointLoader
- * 	 dtlayer.lines.class=com.bbn.openmap.tools.drawing.OMLineLoader
- * 
- * 
- */ -public class DrawingEditorTool extends AbstractEditorTool implements ActionListener, - PropertyChangeListener, PropertyConsumer { - - /** - * OMDrawingTool handling OMGraphic modifications and creations. - */ - protected OMDrawingTool drawingTool = null; - /** - * A handler on the OMDrawingToolMouseMode that the OMDrawingTool is using, - * for convenience. If this handle is not null, then that's an internal - * signal for this EditorTool to know that it's active and interpreting - * MouseEvents. If this is null, and the EditorTool wants events, that's a - * signal to create a new OMGraphic (see mousePressed). - */ - protected OMDrawingToolMouseMode omdtmm = null; - /** - * The class name of the next thing to create. Used as a signal to this - * EditorTool that when the next appropriate MouseEvent comes in, this - * "thing" should be created. - */ - protected String thingToCreate = null; - /** - * The ButtonGroup to use for the face. - */ - protected ButtonGroup bg = null; - - /** - * The button that unpicks all the rest of the tool buttons. It is kept - * invisible, but a member of all the other button's ButtonGroup. When - * selected, all of the other buttons are deselected. - */ - protected JToggleButton unpickBtn = null; - - protected GraphicAttributes ga = null; - - /** - * The MouseDelegator that is controlling the MouseModes. We need to keep - * track of what's going on so we can adjust our tools accordingly. - */ - protected MouseDelegator mouseDelegator; - - /** - * The ArrayList containing the EditToolLoaders for the drawing tool. - */ - protected ArrayList loaderList = new ArrayList(); - - public final static String RESET_CMD = "RESET_CMD"; - - /** - * Property prefix for PropertyConsumer interface. - */ - protected String propertyPrefix; - - /** - * Hashtable that holds default DrawingAttributes for different loaders. - */ - protected Hashtable drawingAttributesTable; - - protected boolean showAttributes = true; - - public final static String ShowAttributesProperty = "showAttributes"; - public final static String LoaderProperty = "loaders"; - public final static String AttributesClassProperty = "attributesClass"; - public final static String DefaultDrawingAttributesClass = "com.bbn.openmap.omGraphics.DrawingAttributes"; - - /** - * The general constructor that can be called from subclasses to initialize - * the drawing tool and interface. All that is left to do for subclasses is - * to add EditToolLoaders to the DrawingEditorTool subclass. - */ - public DrawingEditorTool(EditorLayer layer) { - super(layer); - - drawingAttributesTable = new Hashtable(); - initDrawingTool(); - - // Ensures that the drawing tool used by super classes fits - // the OMGraphics created by the EditorTool - layer.setDrawingTool(drawingTool); - } - - /** - * Method called in the AbstractDrawingEditorTool constructor. - */ - public void initDrawingTool() { - drawingTool = createDrawingTool(); - drawingTool.setUseAsTool(true); // prevents popup menu use. - drawingTool.getMouseMode().setVisible(false); - ga = drawingTool.getAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - - protected OMDrawingTool createDrawingTool() { - return new OMDrawingTool(); - } - - public void addEditToolLoader(EditToolLoader loader) { - loaderList.add(loader); - drawingTool.addLoader(loader); - } - - public void removeEditToolLoader(EditToolLoader loader) { - loaderList.remove(loader); - drawingTool.removeLoader(loader); - } - - public void clearEditToolLoaders() { - loaderList.clear(); - drawingTool.setLoaders(null); - } - - /** - * Add the default (line, poly, rectangle, circle/range rings, point) - * capabilities to the tool. - */ - public void initDefaultDrawingToolLoaders() { - addEditToolLoader(new OMDistanceLoader()); - addEditToolLoader(new OMLineLoader()); - addEditToolLoader(new OMPolyLoader()); - addEditToolLoader(new OMRectLoader()); - addEditToolLoader(new OMCircleLoader()); - addEditToolLoader(new OMPointLoader()); - } - - /** - * The main method for getting the tool ready to create something. When - * called, it sets the thingToCreate from the command, calls - * setWantEvents(true), which calls resetForNewGraphic(). - */ - protected void setWantsEvents(String command) { - - if (Debug.debugging("editortool")) { - Debug.output("DET.setWantsEvents(" + command + ")"); - } - - // Has to be called first - thingToCreate = command; - setWantsEvents(true); - } - - /** - * The EditorTool method, with the added bonus of resetting the tool if it - * doesn't want events. - */ - public void setWantsEvents(boolean value) { - super.setWantsEvents(value); - if (!value) { - thingToCreate = null; - } - - if (drawingTool != null && drawingTool.isActivated()) { - drawingTool.resetGUIWhenDeactivated(true); - drawingTool.deactivate(); - } - - resetForNewGraphic(); - - if (drawingTool != null) { - drawingTool.setVisible(showAttributes);// Just to make - // sure... - } - } - - /** - * Called by findAndInit(Iterator) so subclasses can find objects, too. - */ - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof MapBean || someObj instanceof InformationDelegator) { - drawingTool.findAndInit(someObj); - } - - if (someObj instanceof MouseDelegator) { - setMouseDelegator((MouseDelegator) someObj); - // I think we want to handle this differently. The - // EditorToolLayer should get the Gestures MouseMode to - // act as a proxy for the drawing tool mouse mode when a - // tool is not being used. - drawingTool.findAndInit(someObj); - } - - if (someObj instanceof OMGraphicDeleteTool) { - ((OMGraphicDeleteTool) someObj).findAndInit(getDrawingTool()); - } - - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - unhook(someObj); - } - - public void dispose() { - Layer layer = getLayer(); - if (layer != null) { - BeanContext bc = layer.getBeanContext(); - if (bc instanceof MapHandler) { - MapHandler mh = (MapHandler) bc; - - unhook(mh.get(MouseDelegator.class)); - unhook(mh.get(MapBean.class)); - unhook(mh.get(InformationDelegator.class)); - unhook(mh.get(OMGraphicDeleteTool.class)); - } - } - } - - protected void unhook(Object someObj) { - if (someObj == null) { - return; - } - - if (someObj == mouseDelegator) { - setMouseDelegator(null); - } - - if (someObj instanceof MapBean || someObj instanceof InformationDelegator) { - drawingTool.findAndUndo(someObj); - } - - if (someObj instanceof OMGraphicDeleteTool) { - ((OMGraphicDeleteTool) someObj).findAndUndo(drawingTool); - } - } - - /** - * When a graphic is complete, the drawing tool gets ready to make another. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - // Watch out, gets called when drawingTool.deactivate() gets - // called, so you can get in a loop if you try to do too much - // here with regard to setting up the next OMGraphic to - // create. - if (thingToCreate != null) { - drawingTool.resetGUIWhenDeactivated(false); - } - omdtmm = null; - } - - /** - * Called when the Tool should be reset to draw a new graphic. Currently - * sets the OMDrawingToolMouseMode to null, which is a signal to the - * DrawingEditorTool that if an appropriate MouseEvent is provided, that the - * DrawingTool should be configured to create a new OMGraphic. If the - * OMDrawingToolMouseMode is not null, then the MouseEvent is just given to - * it. - */ - public void resetForNewGraphic() { - // if thingToCreate is null, then omdtmm will be set to null - // and the drawingTool deactivated. If thingToCreate is not - // null, omdtmm will be ready to receive mouse events for - // editing the new OMGraphic. - omdtmm = activateDrawingTool(thingToCreate); - } - - /** - * Does everything to make the DrawingEditorTool go to sleep, and disable - * all buttons. - */ - public void totalReset() { - // Need to check if the tool wants events before just - // deactivating the drawing tool - that can mess up a edit - // session that is unrelated to the tool but still related to - // the DrawingToolLayer. - if (wantsEvents()) { - setWantsEvents(false); - if (unpickBtn != null) { - unpickBtn.doClick(); - } - - if (mouseDelegator != null) { - MapMouseMode[] modes = mouseDelegator.getMouseModes(); - if (modes != null && modes.length > 0) - mouseDelegator.setActiveMouseMode(modes[0]); - } - } - } - - /** - * Set the OMDrawingTool to use. It's created internally, though. - */ - public void setDrawingTool(OMDrawingTool omdt) { - drawingTool = omdt; - } - - /** - * Get the OMDrawingTool to use with this DrawingEditorTool. - */ - public OMDrawingTool getDrawingTool() { - return drawingTool; - } - - public GraphicAttributes getGraphicAttributes() { - return ga; - } - - public void setGraphicAttributes(GraphicAttributes ga) { - this.ga = ga; - } - - public boolean isShowAttributes() { - return showAttributes; - } - - public void setShowAttributes(boolean showAttributes) { - this.showAttributes = showAttributes; - } - - /** - * actionPerformed - Handle the mouse clicks on the button(s) - */ - public void actionPerformed(ActionEvent e) { - String command = e.getActionCommand(); - - if (Debug.debugging("editortool")) { - Debug.output("DET.actionPerformed(" + command + ")"); - } - - if (RESET_CMD.equals(command)) { - setWantsEvents(false); - } else if (command != null) { - if (!command.equals(thingToCreate)) { - - EditorLayer elayer = (EditorLayer) getLayer(); - elayer.releaseProxyMouseMode(); - - if (thingToCreate == null && mouseDelegator != null) { - mouseDelegator.setActiveMouseModeWithID(elayer.getMouseMode().getID()); - } - - // Calling with command will set 'thingToCreate' and - // resetForNewGraphic - setWantsEvents(command); - } else { - // This is the key to making this work with the OMMouseMode and - // OverlayMapPanel (Main app). Clicking on the active toggle - // button just resets the layer and passes control back to the - // main mouse mode. Kinda like it for the regular OpenMap app, - // too. - totalReset(); - } - } - } - - /** - * Method to set up the drawing tool with default behavior in order to - * create a new OMGraphic. Will try to deactivate the OMDrawingTool if it - * thinks it's busy. - * - * @param ttc thingToCreate, classname of thing to create - * @return OMDrawingToolMouseMode of DrawingTool if all goes well, null if - * the drawing tool can't create the new thingy. - */ - protected OMDrawingToolMouseMode activateDrawingTool(String ttc) { - if (drawingTool != null && ttc != null) { - // If there is a pre-defined set of DrawingAttributes for - // a particular OMGraphic, set those attributes in the - // GraphicAttributes used in the OMDrawingTool. - DrawingAttributes da = (DrawingAttributes) drawingAttributesTable.get(ttc); - if (da != null) { - da.setOrientation(ga.getOrientation()); - da.setTo(ga); - } - - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool.activateDrawingTool(" + ttc + ")"); - } - - drawingTool.setMask(OMDrawingTool.PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK - | OMDrawingTool.QUICK_CHANGE_BEHAVIOR_MASK); - - OMGraphic newOMG = drawingTool.create(ttc, ga, (DrawingToolRequestor) getLayer(), true); - - if (newOMG == null) { - // Something bad happened, might as well try to clean - // up. - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool.activateDrawingTool() failed, cleaning up..."); - } - drawingTool.deactivate(); - return null; - } - - OMGraphicHandlerLayer el = getLayer(); - if (el instanceof EditorLayer) { - ((EditorLayer) el).creatingOMGraphic(newOMG); - } - - return drawingTool.getMouseMode(); - } else { - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool.activateDrawingTool(" + ttc - + ") with drawing tool = " + drawingTool); - } - } - - return null; - } - - // ////////////////////// - // Mouse Listener events - // ////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mousePressed(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - - // if you only want one OMGraphic at a time: - // OMGraphicList omgl = layer.getList(); - // if (omgl != null && !omgl.isEmpty()) { - // omgl.clear(); - // layer.repaint(); - // } - - omdtmm.mousePressed(e); - } - return consumeEvents; - } else { - return super.mousePressed(e); - } - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseReleased(e); - return true; - } else { - return false; - } - } else { - return super.mouseReleased(e); - } - } - - /** - * Invoked when the mouse has been clicked on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseClicked(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseClicked(e); - return consumeEvents; - } else { - return false; - } - } else { - return super.mouseClicked(e); - } - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseEntered(e); - } - } else { - super.mouseEntered(e); - } - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseExited(e); - } - } else { - super.mouseExited(e); - } - } - - // ///////////////////////////// - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * The listener will receive these events if it - * - * @param e MouseEvent - * @return false - */ - public boolean mouseDragged(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseDragged(e); - return consumeEvents; - } else { - return false; - } - } else { - return super.mouseDragged(e); - } - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return false - */ - public boolean mouseMoved(MouseEvent e) { - if (wantsEvents()) { - if (omdtmm != null) { - omdtmm.mouseMoved(e); - return consumeEvents; - } else if (thingToCreate != null) { - // This is needed to reinitialize the drawing tool to - // create another OMGraphic after the same one was - // just completed. drawingComplete just nulls out - // omdtmm so that the drawing tool can finish - // deactivating. The first mouseMoved event should - // get the next OMGraphic ready. - omdtmm = activateDrawingTool(thingToCreate); - return consumeEvents; - } else { - return false; - } - } else { - return super.mouseMoved(e); - } - } - - // ///////////////////////////// - // Tool interface methods - // ///////////////////////////// - - public void setVisible(boolean value) { - super.setVisible(value); - if (!value) { - totalReset(); - } - } - - /** - * The tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - if (face == null) { - JToolBar faceTB = new GridBagToolBar(); - int orientation = ((EditorLayer) getLayer()).getOrientation(); - faceTB.setOrientation(orientation); - - if (bg == null) { - bg = new ButtonGroup(); - } - - fillFaceToolBar(faceTB, bg); - - unpickBtn = new JToggleButton("", false); - unpickBtn.setActionCommand(RESET_CMD); - unpickBtn.addActionListener(this); - unpickBtn.setVisible(false); - bg.add(unpickBtn); - faceTB.add(unpickBtn); - - if (drawingTool != null && showAttributes) { - drawingTool.setOrientation(orientation); - faceTB.add(drawingTool); - drawingTool.showPalette(); - } - - face = faceTB; - face.setVisible(visible); - } - - return face; - } - - /** - * Fill the Face's toolbar with buttons - */ - protected void fillFaceToolBar(JToolBar faceTB, ButtonGroup bg) { - for (EditToolLoader loader : loaderList) { - String[] classnames = loader.getEditableClasses(); - - for (int i = 0; i < classnames.length; i++) { - ImageIcon icon = loader.getIcon(classnames[i]); - JToggleButton btn = new JToggleButton(icon, false); - btn.setToolTipText(loader.getPrettyName(classnames[i])); - btn.setFocusable(false); - btn.setActionCommand(classnames[i]); - btn.addActionListener(this); - bg.add(btn); - faceTB.add(btn); - } - } - } - - /** - * Set the MouseDelegator used to hold the different MouseModes available to - * the map. - */ - public void setMouseDelegator(MouseDelegator md) { - EditorLayer el = (EditorLayer) getLayer(); - - if (mouseDelegator != null) { - if (el != null) { - mouseDelegator.removeMouseMode(el.getMouseMode()); - } - mouseDelegator.removePropertyChangeListener(this); - } - - mouseDelegator = md; - - if (mouseDelegator == null) { - return; - } - - if (el != null) { - mouseDelegator.addMouseMode(el.getMouseMode()); - } - - mouseDelegator.addPropertyChangeListener(this); - } - - /** - * Get the MouseDelegator used to control mouse gestures over the map. - */ - public MouseDelegator getMouseDelegator() { - return mouseDelegator; - } - - /** - * Listen for changes to the active mouse mode and for any changes to the - * list of available mouse modes - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - /* - * If the mouse mode changes, we want to reset ourselves to be ready - * to just adjust what's on our layer. - */ - String mmID = ((MapMouseMode) evt.getNewValue()).getID(); - - if (Debug.debugging("editortool")) { - Debug.output("DET.propertyChange: mousemode changed to " + mmID); - } - - if (!mmID.equals(((EditorLayer) getLayer()).getMouseMode().getID())) { - totalReset(); - } - drawingTool.showPalette(); // Reset to basic parameters - } - } - - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - public String getPropertyPrefix() { - return propertyPrefix; - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - showAttributes = PropUtils.booleanFromProperties(props, prefix + ShowAttributesProperty, showAttributes); - - if (drawingTool != null) { - drawingTool.setProperties(prefix, props); - } - - String loaderListString = props.getProperty(prefix + LoaderProperty); - - if (loaderListString != null) { - List loaderVector = PropUtils.parseSpacedMarkers(loaderListString); - for (String loaderPrefix : loaderVector) { - String loaderPropertyPrefix = PropUtils.getScopedPropertyPrefix(prefix - + loaderPrefix); - String loaderClassString = props.getProperty(loaderPropertyPrefix + "class"); - String loaderAttributeClass = props.getProperty(loaderPropertyPrefix - + AttributesClassProperty); - if (loaderClassString != null) { - Object obj = ComponentFactory.create(loaderClassString, loaderPropertyPrefix, props); - - if (obj instanceof EditToolLoader) { - EditToolLoader loader = (EditToolLoader) obj; - - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool: adding " + loaderClassString); - } - - addEditToolLoader(loader); - - if (loaderAttributeClass != null) { - - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool: getting attributes for " - + loaderAttributeClass); - } - - Object daObject = ComponentFactory.create(loaderAttributeClass, loaderPropertyPrefix, props); - - if (daObject instanceof DrawingAttributes) { - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool: attributes from " - + loaderAttributeClass); - } - - String[] classnames = loader.getEditableClasses(); - for (int i = 0; i < classnames.length; i++) { - drawingAttributesTable.put(classnames[i], (DrawingAttributes) daObject); - } - - } else { - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool: attributes not an instance of DrawingAttributes"); - } - } - - } else { - if (Debug.debugging("editortool")) { - Debug.output("DrawingEditorTool: attributes not defined for " - + loaderClassString); - } - - } - } - - } else { - Debug.output("DrawingEditorTool.setProperties: no loader class provided for " - + loaderPropertyPrefix); - } - } - - // Pick up initial settings from properties from the layer, if it's - // an editor layer. - if (layer instanceof DrawingToolLayer && ga != null) { - ((DrawingToolLayer) layer).getDrawingAttributes().setTo(ga); - } - - } else { - Debug.output("DrawingEditorTool.setProperties: no loaders set in properties"); - } - } - - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - return props; - } - - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - return props; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayer.java deleted file mode 100644 index 9b7592af3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayer.java +++ /dev/null @@ -1,356 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/editor/EditorLayer.java,v $ -// $RCSfile: EditorLayer.java,v $ -// $Revision: 1.14 $ -// $Date: 2006/04/11 00:15:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.editor; - -import java.awt.Container; -import java.util.Properties; - -import javax.swing.JPanel; -import javax.swing.SwingConstants; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.gui.Tool; -import com.bbn.openmap.layer.DrawingToolLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.tools.drawing.DrawingTool; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The EditorLayer is a layer that provides a specific set of tools to modify a - * set of OMGraphics that represent specific types of objects. It has an - * EditorTool that controls what the interface looks like, and controls - * reception of the mouse events to direct their interpretation usefully. The - * EditorLayer can use the following property: - * - *
- * 
- * 
- *   # could be com.bbn.openmap.layer.editor.DrawingEditorTool, for instance
- *   editorLayer.editor=EditorTool class
- * 
- * 
- * 
- */ -public class EditorLayer extends DrawingToolLayer implements Tool { - - private static final long serialVersionUID = 1L; - - /** - * The EditorTool controls the interface, and how OMGraphics are managed. - */ - protected EditorTool editorTool = null; - - /** - * The mouse mode used to direct mouse events to the editor. - */ - protected EditorLayerMouseMode elmm = null; - - /** - * The property to use of the EditorLayer doesn't really know what - * EditorTool it will have. This property is used in setProperties if the - * EditorTool isn't already set. If you extend the EditorLayer and - * specifically set the EditorTool in the constructor, this property will be - * ignored. - */ - public final static String EditorToolProperty = "editor"; - - /** - * Set whether the face of the EditorTool should be on the palette for the - * layer (via getGUI). False by default. - */ - public final static String FACE_ON_PALETTE_PROPERTY = "faceOnPalette"; - - protected int orientation = SwingConstants.HORIZONTAL; - protected boolean faceOnPalette = false; - - public EditorLayer() { - super(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - setFaceOnPalette(PropUtils.booleanFromProperties(props, realPrefix + FACE_ON_PALETTE_PROPERTY, isFaceOnPalette())); - - if (editorTool == null) { - String editorClassName = props.getProperty(realPrefix + EditorToolProperty); - if (editorClassName != null) { - // Try to create with this layer as an argument. - Object[] objArgs = { this }; - - editorTool = (EditorTool) ComponentFactory.create(editorClassName, objArgs, prefix, props); - - if (editorTool == null) { - // OK, try to create with an empty constructor. - editorTool = (EditorTool) ComponentFactory.create(editorClassName, prefix, props); - } - - if (editorTool == null) { - String additionalInfo = "."; - if (editorClassName != null) { - additionalInfo = ", although an editor tool class (" + editorClassName + ") was defined."; - } - Debug.error(getName() + " doesn't have a EditorTool defined" + additionalInfo); - } - } - } - } - - /** - * Get and/or create the EditorLayerMouseMode that can be used specifically - * for this layer, used to capture the MapBean's MouseEvents when an - * EditorTool is invoked. The EditorLayerMouseMode is invisible, meaning it - * won't show up in standard OpenMap GUI widgets as a viable MouseMode. It - * is expected that the EditorTool will compensate for displaying what is - * going on. - *

- * - * If the EditorLayerMouseMode isn't set programmatically, this method will - * create one with this layer's name as the mouse mode ID. If the layer's - * name hasn't been set, a temporary mouse mode will be returned, but with a - * somewhat random name that may not really work as expected. Once the - * layer's name gets set, however, a good, usable mouse mode will get picked - * up and used. - */ - public EditorLayerMouseMode getMouseMode() { - if (elmm == null) { - String ln = getName(); - if (ln == null) { - // Try something unique, but don't make it permanent. - // This will keep the layer cookin' along, but force a - // new mouse mode until the name gets set. - ln = this.getClass().getName() + System.currentTimeMillis(); - return new EditorLayerMouseMode(ln.intern(), true); - } - elmm = new EditorLayerMouseMode(ln.intern(), true); - } - return elmm; - } - - /** - * Need to do this so the EditorLayerMouseMode will be recreated with the - * proper identification if the name of the layer changes. - */ - public void setName(String name) { - super.setName(name); - elmm = null; - /* - * Need to call this in case the layer name gets set after the mouse - * mode ids are set, so the new elmm id is included in this list. This - * list might get populated with unused strings, but that should be OK, - * as long as the one we need is on the list. - */ - setMouseModeIDsForEvents(getMouseModeIDsForEvents()); - } - - /** - * DrawingToolRequestor method. It's actually pretty important to call - * EditorTool.drawingComplete() from here, too, if you create a subclass to - * EditorLayer. The EditorTool needs to know this to reset the drawing tool - * mouse mode, to get ready for another new OMGraphic if necessary. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - super.drawingComplete(omg, action); - if (editorTool != null) { - editorTool.drawingComplete(omg, action); - } - } - - /** - * Called by findAndInit(Iterator) so subclasses can find objects, too. - */ - public void findAndInit(Object someObj) { - // We don't want the EditorLayer to find the DrawingTool - // in the MapHandler. The EditorTool should set its own. - if (!(someObj instanceof DrawingTool)) { - super.findAndInit(someObj); - } - - if (editorTool != null) { - editorTool.findAndInit(someObj); - } - - if (someObj instanceof InformationDelegator || someObj instanceof SelectMouseMode) { - getMouseMode().findAndInit(someObj); - } - } - - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (editorTool != null) { - editorTool.findAndUndo(someObj); - } - - if (someObj instanceof InformationDelegator || someObj instanceof SelectMouseMode) { - getMouseMode().findAndUndo(someObj); - } - } - - public void dispose() { - if (editorTool != null) { - editorTool.dispose(); - } - super.dispose(); - } - - public void setMouseModeIDsForEvents(String[] modes) { - // creates the MouseMode if needed - EditorLayerMouseMode elmm = getMouseMode(); - - String[] newModes = new String[modes.length + 1]; - System.arraycopy(modes, 0, newModes, 0, modes.length); - newModes[modes.length] = elmm.getID(); - super.setMouseModeIDsForEvents(newModes); - } - - public String[] getMouseModeIDsForEvents() { - String[] modes = super.getMouseModeIDsForEvents(); - if (modes == null) { - // Set the internal mouse mode as valid, since it hasn't - // been set yet. - setMouseModeIDsForEvents(new String[0]); - // Since it's set now, return it. - return super.getMouseModeIDsForEvents(); - } else { - return modes; - } - } - - /** - * Get the interpreter used to field and interpret MouseEvents, thereby - * calling GestureResponsePolicy methods on this layer. It returns whatever - * has been set as the interpreter, which could be null. - */ - public MapMouseInterpreter getMouseEventInterpreter() { - return mouseEventInterpreter; - } - - public EditorTool getEditorTool() { - return editorTool; - } - - public void setEditorTool(EditorTool editorTool) { - this.editorTool = editorTool; - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void setVisible(boolean show) { - if (editorTool != null) { - editorTool.setVisible(show); - } - super.setVisible(show); - } - - // ///////////////////////////// - // Tool interface methods - // ///////////////////////////// - - /** - * The tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - if (isFaceOnPalette()) { - return null; - } - - if (editorTool != null) { - return editorTool.getFace(); - } else { - return new JPanel(); - } - } - - /** - * The retrieval key for this tool. We use the property prefix for the key. - * If the property prefix is not set then the name is used, which may not be - * that unique. - * - * @return String The key for this tool. - */ - public String getKey() { - String tmpKey = getPropertyPrefix(); - if (tmpKey == null) { - tmpKey = getName(); - if (tmpKey == null) { - tmpKey = getClass().getName(); - } - } - return tmpKey; - } - - /** - * Set the retrieval key for this tool. This call sets the key used for the - * Tool interface method, which is generally the property prefix used for - * this layer. Do not use this lightly, since the ToolPanel may be expecting - * to find a key that is reflected in the openmap.properties file. - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - setPropertyPrefix(aKey); - } - - public int getOrientation() { - return orientation; - } - - public void setOrientation(int orientation) { - this.orientation = orientation; - } - - /** - * @return the faceOnPalette - */ - public boolean isFaceOnPalette() { - return faceOnPalette; - } - - /** - * @param faceOnPalette the faceOnPalette to set - */ - public void setFaceOnPalette(boolean faceOnPalette) { - this.faceOnPalette = faceOnPalette; - } - - /** - * A hook to get a handle on a new OMGraphic that is being created for - * editing. The DrawingEditorTool calls this. NOOP here, but if you need a - * handle to the new OMGraphic just as it's being created, here it is. - * - * @param newOMG - */ - protected void creatingOMGraphic(OMGraphic newOMG) { - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayerMouseMode.java b/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayerMouseMode.java deleted file mode 100644 index 4e2cebd3b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorLayerMouseMode.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/editor/EditorLayerMouseMode.java,v $ -// $RCSfile: EditorLayerMouseMode.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.editor; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.CoordMouseMode; -import com.bbn.openmap.event.SelectMouseMode; - -/** - * The EditorLayerMouseMode is a mouse mode that is made active when - * the EditorTool needs events. It serves to ensure that the - * EditorLayer is the only layer receiving events from the MapBean - * when the EditorTool needs them, with the addition bonus of being - * invisible. The EditorTool should take care of indicating what it is - * doing with the MouseEvents, by creating certain OMGraphics, - * selecting certain types of objects, etc. - */ -public class EditorLayerMouseMode extends CoordMouseMode { - - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Mouse Mode identifier, which is "EditorLayer". This is returned - * on getID(). This mouse mode is invisible, so id doesn't have to - * be pretty for the GUI. - */ - public transient String modeID = null; - - /** - * Construct a EditorLayerMouseMode. Default constructor. Sets the - * ID to the modeID, and the consume mode to true. - * - * @param idToUse a uniqueID to use just for a particular layer. - */ - public EditorLayerMouseMode(String idToUse) { - this(idToUse, true); - } - - /** - * Construct a EditorLayerMouseMode. The constructor that lets you - * set the consume mode. - * - * @param idToUse a uniqueID to use just for a particular layer. - * @param consumeEvents the consume mode setting. - */ - public EditorLayerMouseMode(String idToUse, boolean consumeEvents) { - super(idToUse, consumeEvents); - modeID = idToUse; - setVisible(false); - } - - SelectMouseMode gestures = null; - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof SelectMouseMode - && ((SelectMouseMode) someObj).getID() == SelectMouseMode.modeID) { - gestures = (SelectMouseMode) someObj; - } - } - - public void findAndUndo(Object someObj) { - super.findAndInit(someObj); - if (someObj == gestures) { - gestures = null; - } - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseClicked(MouseEvent e) { - mouseSupport.fireMapMouseClicked(e); - fireMouseLocation(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mousePressed(MouseEvent e) { - mouseSupport.fireMapMousePressed(e); - fireMouseLocation(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseReleased(MouseEvent e) { - mouseSupport.fireMapMouseReleased(e); - fireMouseLocation(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseEntered(MouseEvent e) { - mouseSupport.fireMapMouseEntered(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseExited(MouseEvent e) { - mouseSupport.fireMapMouseExited(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseDragged(MouseEvent e) { - if (gestures != null) { - gestures.mouseDragged(e); - } - mouseSupport.fireMapMouseDragged(e); - fireMouseLocation(e); - } - - /** - * Fires the MapMouseSupport method. - * - * @param e mouse event. - */ - public void mouseMoved(MouseEvent e) { - if (gestures != null) { - gestures.mouseMoved(e); - } - mouseSupport.fireMapMouseMoved(e); - fireMouseLocation(e); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorTool.java b/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorTool.java deleted file mode 100644 index 60653ff57..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/EditorTool.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/editor/EditorTool.java,v $ -// $RCSfile: EditorTool.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.editor; - -import java.awt.Container; - -import com.bbn.openmap.LightMapHandlerChild; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; - -/** - * An EditorTool is a component that provides specific functionality to the - * EditorLayer. The EditorTool is responsible for modifying or creating a set of - * OMGraphics in a certain way, where the OMGraphics actually represent a - * specific set of objects on the map, and the actions on the OMGraphics need to - * be controlled. - */ -public interface EditorTool extends MapMouseInterpreter, LightMapHandlerChild { - - /** - * Method where the EditorLayer lets the tool know that the editing function - * has come full circle, so the user interface can be adjusted. - */ - public void drawingComplete(OMGraphic omg, OMAction action); - - /** - * A method that is checked by the EditorLayer to see if the EditorTool - * wants to receive mouse events. - */ - public boolean wantsEvents(); - - /** - * A method that lets the EditorTool know whether its interface should be - * visible. Usually, called when the layer is turned on or off. - */ - public void setVisible(boolean value); - - /** - * A method that lets the EditorTool respond to queries wondering whether - * its interface is visible. - */ - public boolean isVisible(); - - /** - * The method that allows an EditorTool provide its GUI. - */ - public Container getFace(); - - /** - * Called when the EditorLayer is removed from application. - */ - public void dispose(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/editor/package.html b/src/core/src/main/java/com/bbn/openmap/layer/editor/package.html deleted file mode 100644 index 626ca71ba..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/editor/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package provides the infrastructure to create layers that -provide a Tool interface that controls their content. - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOJarLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOJarLayer.java deleted file mode 100644 index c34c2d628..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOJarLayer.java +++ /dev/null @@ -1,421 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/etopo/ETOPOJarLayer.java,v $ -// $RCSfile: ETOPOJarLayer.java,v $ -// $Revision: 1.8 $ -// $Date: 2008/02/27 01:57:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.etopo; - -/** - * Creation date: (1/12/2001 9:41:59 PM) - * @author John Watts from nextjet.com: - */ -import java.awt.Color; -import java.awt.geom.Point2D; -import java.io.BufferedInputStream; -import java.io.EOFException; -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * This subclass of ETOPOLayer reads data from jar files and * interpolates - * elevations to provide more smooth color transitions using * low resolution - * data. - */ -public class ETOPOJarLayer extends ETOPOLayer { - - /** - * ETOPOJarLayer constructor comment. - */ - public ETOPOJarLayer() { - super(); - } - - /** - * ETOPOJarLayer constructor comment. - * - * @param pathToETOPODir - * java.lang.String - */ - public ETOPOJarLayer(String pathToETOPODir) { - super(pathToETOPODir); - } - - /** - * Loads the database from the appropriate file based on the current - * resolution. The data files are in INTEL format (must call - * BinaryBufferedFile.byteOrder(true)). - */ - protected void loadBuffer() { - - // get the resolution index - int resIdx = minuteSpacing / 5 - 1; - if (resIdx < 0) - resIdx = 0; - else if (resIdx > 2) - resIdx = 2; - - // build file name - String fileName = path + etopoFileNames[resIdx]; - - try { - - // open etopo file as resource stream - BufferedInputStream bis = new BufferedInputStream(ClassLoader - .getSystemResourceAsStream(fileName)); - - // set width/height - bufferWidth = etopoWidths[resIdx]; - bufferHeight = etopoHeights[resIdx]; - - int spacer = 1; - // don't know why I have to do this, but there seems to be - // a wrapping thing going on with different data sets. - switch (minuteSpacing) { - case (2): - spacer = 1 + this.spacer; - break; - case (5): - spacer = 0 + this.spacer; - break; - default: - spacer = 1 + this.spacer; - } - - int numberOfWords = (bufferWidth + spacer) * bufferHeight; - - // allocate storage - dataBuffer = new short[numberOfWords]; - - // read data - iv_buffer = new byte[2 * numberOfWords]; - - iv_bytesinbuffer = bis.read(iv_buffer, 0, 2 * numberOfWords); - iv_curptr = 0; - - for (int i = 0; i < bufferWidth * bufferHeight; i++) - dataBuffer[i] = readShort(); - - // done - bis.close(); - - // don't know why I have to do this, but... - bufferWidth += spacer; - - } catch (FileNotFoundException e) { - Debug.error("ETOPOLayer loadBuffer(): file " + fileName - + " not found"); - } catch (IOException e) { - Debug.error("ETOPOLayer loadBuffer(): File IO Error!\n" - + e.toString()); - } - - } - - byte iv_buffer[]; - int iv_bytesinbuffer; - int iv_curptr; - - /** - * Reads and returns a short - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering - * @exception EOFException - * there were less than 2 bytes left in the file - */ - public short readShort() throws EOFException { - // MSBFirst must be set when we are called - if (iv_bytesinbuffer < 2) { - throw new EOFException(); - } - iv_curptr += 2; - iv_bytesinbuffer -= 2; - return MoreMath.BuildShort(iv_buffer, iv_curptr - 2, true); - } - - /* - * Builds the raster image that has the dimensions of the current - * projection. The algorithm is is follows: - * - * allocate storage the size of the projection (use ints for RGBA) - * - * for each screen point - * - * inverse project screen point to get lat/lon (world coords) get altitude - * and/or slope at the world coord compute (lookup) color at the world coord - * set color value into screen coord location - * - * end - * - * create OMRaster from the int array data. - * - * The code contains a HACK (primarily for the Orthographic projection) - * since * x/y values which would return an "Outer Space" value actually - * return lat/lon values for the center of the projection (see - * Orthographic.inverse(...)). This resulted in the "Outer Space" being - * painted the color of whatever the center lat/lon was. The HACK turns any - * center lat/lon value into black. Of course, this causes valid center - * lat/lon values to be painted black, but the trade off is worth it - * visually. The appropriate method may be to have Projection.inverse and - * its variants raise an exception for "Outer Space" values. - */ - protected OMRaster buildRaster() { - // initialize the return - OMRaster ret = null; - Projection projection = getProjection(); - // work with the slopeMap - if (slopeMap != null) { - - // compute our deltas - int pixelColumns = projection.getWidth(); - int pixelRows = projection.getHeight(); - - // create int array to hold colors - int[] colors = new int[pixelColumns * pixelRows]; - - // compute scalers for lat/lon indicies - float yPixPerDataPt = (float) bufferHeight / 180F; - float xPixPerDataPt = (float) bufferWidth / 360F; - - // starting and ending indices - int sx = 0, sy = 0, ex = pixelColumns, ey = pixelRows; - - // handle CADRG - if (projection instanceof CADRG) { - - // get corners - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - - // set start/end indicies - Point2D ulp = projection.forward(ul); - Point2D lrp = projection.forward(lr); - sx = (int) ulp.getX(); - ex = (int) lrp.getX(); - sy = (int) ulp.getY(); - ey = (int) lrp.getY(); - - } - - // get the center lat/lon (used by the HACK, see above in - // method description) - Point2D center = projection.getCenter(); - LatLonPoint llp = new LatLonPoint.Double(); - - // build array - float lat; - float lon; - int lat_idx; - int lon_idx; - float latWt; - float lonWt; - - // offset - int ofs; - int ofsRight; - int ofsDown; - int ofsDownRight; - - for (int y = sy; y < ey; y++) { - - // process each column - for (int x = sx; x < ex; x++) { - - // inverse project x,y to lon,lat - projection.inverse(x, y, llp); - - // get point values - lat = llp.getLatitude(); - lon = llp.getLongitude(); - - // check - if (lon < 0.) { - lon += 360.; - } - - // find indicies - lat_idx = (int) ((90. - lat) * yPixPerDataPt); - lon_idx = (int) (lon * xPixPerDataPt); - - // most pixels fall between data points. The data - // point originally used is the one immediately - // above and to the left of the pixel. The amount - // by which the pixel is offset from the data - // point can be used to weight the elevation - // contribution of the four data points - // surrounding the pixel ie. the weights. The - // truncated decimal part of the index computation - // is the weight. - latWt = ((90f - lat) * yPixPerDataPt) - (float) lat_idx; - lonWt = (lon * xPixPerDataPt) - (float) lon_idx; - - // offsets of the four surrounding data points. - ofs = lon_idx + lat_idx * bufferWidth; - ofsRight = ofs + 1; - if (lat_idx + 1 < bufferHeight) { - ofsDown = lon_idx + (1 + lat_idx) * bufferWidth; - } else { - ofsDown = ofs; - } - ofsDownRight = ofsDown + 1; - - // make a color - int idx = 0; - int gray = 0; - short el = 0; - byte sl = 0; - - try { - - try { - float ulwt = (1f - lonWt + 1f - latWt); - float urwt = (lonWt + 1f - latWt); - float llwt = (1f - lonWt + latWt); - float lrwt = (lonWt + latWt); - // get elevation - el = (short) ((float) dataBuffer[ofs] * ulwt - + (float) dataBuffer[ofsRight] * urwt - + (float) dataBuffer[ofsDown] * llwt + (float) dataBuffer[ofsDownRight] - * lrwt); - - // slope - sl = (byte) ((float) slopeMap[ofs] * ulwt - + (float) slopeMap[ofsRight] * urwt - + (float) slopeMap[ofsDown] * llwt + (float) slopeMap[ofsDownRight] - * lrwt); - float exagFactor = 1f / (el > 0 ? 1.5f : 3f); - el = (short) ((float) el * exagFactor); - sl = (byte) ((float) sl * exagFactor); - - // bad index - } catch (ArrayIndexOutOfBoundsException e) { - Debug.error(e.toString() + ":" + ofs + " limit=" - + dataBuffer.length); - } - // our index - idx = y * pixelColumns + x; - - // create a color - Color pix = null; - if (viewType == SLOPESHADING) { - // HACK (see method description above) - if ((llp.getLatitude() == center.getY()) - && (llp.getLongitude() == center.getX())) - gray = 0; - else - gray = 127 + sl; - pix = new Color(gray, gray, gray, opaqueness); - } else if (viewType == COLOREDSHADING) { - // HACK (see method description above) - if ((llp.getLatitude() == center.getY()) - && (llp.getLongitude() == center.getX())) - pix = new Color(0, 0, 0, opaqueness); - else - pix = getColor(el, sl); - } - - // set - if (pix != null) { - colors[idx] = pix.getRGB(); - } - - } - - // tried to set a bad color level - catch (IllegalArgumentException e) { - Debug.error(e.toString() + ":" + gray); - } - - // bad index - catch (ArrayIndexOutOfBoundsException e) { - Debug.error(e.toString() + ":" + idx); - } - } - } - - // create the raster - ret = new OMRaster(0, 0, pixelColumns, pixelRows, colors); - - } - - // return or raster - return ret; - - } - - protected Color getColor(short elevation, byte slopeVal) { - // build first time - if (slopeColors == null) {// || slopeColors[0][0].getAlpha() != - // opaqueness) { - System.out.println("loading colors"); - // allocate storage for elevation bands, 8 slope bands - slopeColors = new Color[elevLimitCnt][8]; - - // process each elevation band - for (int i = 0; i < elevLimitCnt; i++) { - - // get base color (0 slope color) - Color base = new Color(redElev[i], greenElev[i], blueElev[i], - opaqueness); - - // call the "brighter" method on the base color for - // positive slope - for (int j = 4; j < 8; j++) { - - // set - if (j == 4) - slopeColors[i][j] = base; - else - slopeColors[i][j] = slopeColors[i][j - 1].brighter(); - } - - // call the "darker" method on the base color for negative - // slopes - for (int k = 3; k >= 0; k--) { - // set - slopeColors[i][k] = slopeColors[i][k + 1].darker(); - } - } - } - - // get the elevation band index - int elIdx = getElevIndex(elevation); - - // compute slope idx - int slopeIdx = ((int) slopeVal + 127) >> 5; - // int slopeIdx = ((int)slopeVal+127)/32; - - // return color - return slopeColors[elIdx][slopeIdx]; - // Color norm = slopeColors[elIdx][slopeIdx]; - - // set alpha - // return new - // Color(norm.getRed(),norm.getGreen(),norm.getBlue(),opaqueness); - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOLayer.java deleted file mode 100644 index 90677157b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/etopo/ETOPOLayer.java +++ /dev/null @@ -1,880 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/etopo/ETOPOLayer.java,v $ -// $RCSfile: ETOPOLayer.java,v $ -// $Revision: 1.11 $ -// $Date: 2008/02/27 01:57:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.etopo; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.io.FileNotFoundException; -import java.io.IOException; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * ETOPOLayer extends Layer to provide rendering of the ETOPO5 world elevation - * data set. The ETOPO5 data consists of terrain altitude and ocean depth - * measurements at 5 minute intervals for the entire globe. Rendering is allowed - * in any projection that implements the inverse(int,int) method. Two types of - * rendering are provided: grayscale slope-shaded and colored slope-shaded. - *

- * The distribution consists of the following: - *

    - *
  • 1. ETOPOLayer.java
  • - *
  • 2. ETOPO5 (5 minute spacing data set, 4320x2160 shorts, ~18MB)
  • - *
  • 3. ETOPO10 (10 minute spacing data set, sampled from ETOPO5, ~4.6MB)
  • - *
  • 4. ETOPO15 (15 minute spacing data set, sampled from ETOPO5, ~2MB)
  • - *
  • 5. ETOPOLayer.properties (example properties for openmap.properties)
  • - *
- *

- * The sampled ETOPO data sets are provided to speed up the loading of data to - * compute the slope shading. The algorithm inverse projects the x/y screen - * coords (for the entire projection screen space) to get the corresponding - * lat/lon coords then samples the database to get altitude/depth and slope - * values. While this method is slower than the forward projection method, it - * does provide a more attractive screen presentation and will support all - * projections (not just the equidistant cylindrical). A palette provides the - * ability to choose between the 5,10, or 15 minute resolutions, as well as - * color or grayscale selection, transparency, and slope contrast. - *

- * The ETOPOLayer also relies on properties to set its variables, such as the - * etopo frame paths (there can be several at a time), the opaqueness of the - * frame images, number of colors to use, and some other display variables. The - * ETOPOLayer properties look something like this: - *

- * - * #------------------------------
- * # Properties for ETOPOLayer
- * #------------------------------
- * # This property should reflect the paths to the etopo directory
- * etopo.path=c:/openmap/share
- *
- * # Number between 0-255: 0 is transparent, 255 is opaque
- * etopo.opaque=255
- *
- * # Number of colors to use on the maps - 16, 32, 216
- * etopo.number.colors=216
- *
- * # Type of display for the data
- * # 0 = grayscale slope shading
- * # 1 = colored slope shading
- * etopo.view.type=1
- *
- * # Contrast setting, 1-5
- * etopo.contrast=3
- *
- * # lat/lon spacing in minutes
- * # must be 5, 10, or 15
- * etopo.minute.spacing=10
- *
- * #-------------------------------------
- * # End of properties for ETOPOLayer
- * #-------------------------------------
- * - */ -public class ETOPOLayer extends OMGraphicHandlerLayer implements ActionListener { - - /** Gray scale slope shading, sun from the Northwest. */ - public static final int SLOPESHADING = 0; - - /** - * Colorized slope shading. Color bands are based on elevation, and are - * accented by shaded indications. - */ - public static final int COLOREDSHADING = 1; - - /** Default contrast setting for slope shading. */ - public static final int DEFAULT_SLOPE_ADJUST = 3; - - /** Default minute spacing */ - public static final int DEFAULT_MINUTE_SPACING = 10; - - /** for colorizing */ - public final static int DEFAULT_OPAQUENESS = 255; - - /** - * The paths to the ETOPO directory, telling where the data is. - */ - protected String path; - - /** The etopo elevation data */ - protected short[] dataBuffer = null; - protected int bufferWidth; - protected int bufferHeight; - - /** The current resolution (in minutes) */ - protected int minuteSpacing; - - /** ETOPO elevation files */ - protected final static String[] etopoFileNames = { "/ETOPO2", "/ETOPO5", - "/ETOPO10", "/ETOPO15" }; // ep-g - - /** dimensions of the ETOPO files (don't mess with these!) */ - protected final static int[] etopoWidths = { 10800, 4320, 2160, 1440 };// ep-g - protected final static int[] etopoHeights = { 5400, 2160, 1080, 720 }; // ep-g - - /** - * Spacings (in meters) between adjacent lon points at the equator. The - * values here were aesthetically defined (they are not the actual spacings) - */ - protected double[] etopoSpacings = { 1800., 3500., 7000., - 10500. }; // ep-g - - /** - * The display type for the etopo images. Slope shading is grayscale terrain - * modeling with highlights and shading, with the 'sun' being in the - * NorthWest. Colored Elevation shading is the same thing, except colors are - * added to indicate the elevation. Band shading colors the pixels according - * to a range of elevations. - */ - protected int viewType; - - /** The elevation range to use for each color in band shading. */ - protected int bandHeight; - - /** A contrast adjustment, for slope shading (1-5). */ - protected int slopeAdjust; - - /** transparency control */ - protected int opaqueness; - - /** - * Number of pixel spacers that should be added to a data file, per line, to - * adjust for skewing. - */ - protected int spacer = 0; - - /** property suffixes */ - public static final String ETOPOPathProperty = "path"; - public static final String OpaquenessProperty = "opaque"; - public static final String ETOPOViewTypeProperty = "view.type"; - public static final String ETOPOSlopeAdjustProperty = "contrast"; - public static final String ETOPOMinuteSpacingProperty = "minute.spacing"; - public static final String ETOPOPixelSpacerProperty = "spacer"; - - /** - * Holds the slope values, updated when the resolution changes or the slope - * adjustment (contrast) is changed. Slope values are scaled between -127 to - * 127. - */ - protected byte[] slopeMap = null; - - /** elevation bands */ - protected int[] elevLimit = { -11000, -9000, -7000, -5000, - -3000, -1500, 0, 250, 500, 750, 1000, 2000, 3500, 5000 }; - /** number of elevation bands */ - protected int elevLimitCnt = 14; - - /** elevation band colors (one for each elevation band) */ - protected int[] redElev = { 0, 0, 4, 20, 124, 130, 135, 117, - 252, 253, 229, 244, 252, 132 }; - protected int[] greenElev = { 2, 12, 51, 159, 235, 255, 235, - 255, 236, 162, 115, 50, 20, 132 }; - protected int[] blueElev = { 76, 145, 242, 249, 252, 255, 110, - 58, 29, 35, 5, 14, 46, 132 }; - - /** for slope shading colors, indexed by elevation band then slope */ - protected Color[][] slopeColors = null; - - /* flag to recompute slope map */ - protected boolean slopeReset = true; - - /* flag to load new elevation file */ - protected boolean spacingReset = true; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public ETOPOLayer() { - this(null); - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - * - * @param pathToETOPODir - * path to the directory holding the ETOPO data - */ - public ETOPOLayer(String pathToETOPODir) { - setName("ETOPO"); - setDefaultValues(); - path = pathToETOPODir; - setProjectionChangePolicy(new ListResetPCPolicy(this)); - } - - public void setPath(String pathToETOPODir) { - path = pathToETOPODir; - } - - protected void setDefaultValues() { - // defaults - path = null; - dataBuffer = null; - opaqueness = DEFAULT_OPAQUENESS; - slopeAdjust = DEFAULT_SLOPE_ADJUST; - viewType = COLOREDSHADING; - minuteSpacing = DEFAULT_MINUTE_SPACING; - } - - /* returns the color lookup index based on elevation */ - protected int getElevIndex(short el) { - for (int i = 0; i < elevLimitCnt - 1; i++) - if (el < elevLimit[i + 1]) - return i; - return elevLimitCnt - 1; - } - - /* returns a color based on slope and elevation */ - protected Color getColor(short elevation, byte slopeVal) { - // build first time - if (slopeColors == null) { - - // allocate storage for elevation bands, 8 slope bands - slopeColors = new Color[elevLimitCnt][8]; - - // process each elevation band - for (int i = 0; i < elevLimitCnt; i++) { - - // get base color (0 slope color) - Color base = new Color(redElev[i], greenElev[i], blueElev[i]); - - // call the "brighter" method on the base color for - // positive slope - for (int j = 4; j < 8; j++) { - // set - if (j == 4) - slopeColors[i][j] = base; - else - slopeColors[i][j] = slopeColors[i][j - 1].brighter(); - } - - // call the "darker" method on the base color for - // negative slopes - for (int k = 3; k >= 0; k--) { - slopeColors[i][k] = slopeColors[i][k + 1].darker(); - } - } - } - - // get the elevation band index - int elIdx = getElevIndex(elevation); - - // compute slope idx - int slopeIdx = ((int) slopeVal + 127) / 32; - - // return color - Color norm = slopeColors[elIdx][slopeIdx]; - - // set alpha - return new Color(norm.getRed(), norm.getGreen(), norm.getBlue(), - opaqueness); - - } - - /** - * Set all the ETOPO properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(this); - - path = properties.getProperty(prefix + ETOPOPathProperty); - - opaqueness = PropUtils.intFromProperties(properties, prefix - + OpaquenessProperty, DEFAULT_OPAQUENESS); - - viewType = PropUtils.intFromProperties(properties, prefix - + ETOPOViewTypeProperty, COLOREDSHADING); - - slopeAdjust = PropUtils.intFromProperties(properties, prefix - + ETOPOSlopeAdjustProperty, DEFAULT_SLOPE_ADJUST); - - minuteSpacing = PropUtils.intFromProperties(properties, prefix - + ETOPOMinuteSpacingProperty, DEFAULT_MINUTE_SPACING); - - spacer = PropUtils.intFromProperties(properties, prefix - + ETOPOPixelSpacerProperty, spacer); - - } - - /** - * Builds the slope index map. This method is called when the ETOPO - * resolution changes and when the slope contrast changes. The slope of the - * terrain is clipped; slopes are between the range of +/- 45 deg. The - * calculated slope value is then linearly scaled to the range +/- 127. - */ - protected void buildSlopeMap() { - // this should never happen, but... - if (dataBuffer == null) - return; - - // get resolution index - int resIdx = minuteSpacing / 5; // ep-g - if (resIdx < 0) - resIdx = 0; - else if (resIdx > 3) // ep-g - resIdx = 3; // ep-g - - // Set deltaX constant. The deltaX is actually is smaller at - // latitude - // extremes, but - double deltaX = etopoSpacings[resIdx]; - - // allocate storage for slope map - slopeMap = new byte[bufferWidth * bufferHeight]; - - // process dataBuffer to create slope - for (int y = 0; y < bufferHeight; y++) { - - // compute the latitude of this - double lat = 90. - 180. * (double) y / (double) bufferHeight; - - // get cosine of the latitude. This is used because the - // spacing between minutes gets smaller in high latitude - // extremes. - double coslat = Math.cos(Math.toRadians(lat)); - - // for scaling the slope - double slopeScaler = (double) slopeAdjust * coslat / deltaX; - - // indeces - int idx0 = y * bufferWidth; - - // do each row - for (int x = 0; x < bufferWidth; x++) { - - // indeces - int idx1 = idx0 + x; - int idx2 = idx1 + bufferWidth; - - // special case at end - if (y == bufferHeight - 1) - idx2 = idx1; - - // get altitudes - double d1 = (double) dataBuffer[idx1]; - double d2 = (double) dataBuffer[idx2]; - - // compute (lookup) slope - double slope = slopeScaler * (d2 - d1); - - // clip - if (slope > 0.99) - slope = 0.99; - else if (slope < -0.99) - slope = -0.99; - - // scale - int islope = (int) (slope * 127.); - - // store - slopeMap[idx1] = (byte) islope; - - } - } - } - - /** - * Loads the database from the appropriate file based on the current - * resolution. The data files are in INTEL format (must call - * BinaryBufferedFile.byteOrder(true)). - */ - protected void loadBuffer() { - - // get the resolution index - int resIdx = minuteSpacing / 5; // ep-g - if (resIdx < 0) - resIdx = 0; - else if (resIdx > 3) // ep-g - resIdx = 3; // ep-g - - // build file name - String fileName = path + etopoFileNames[resIdx]; - - // Clean this out...dfd - dataBuffer = null; - - try { - - // treat as buffered binary - BinaryBufferedFile binFile = new BinaryBufferedFile(fileName); - binFile.byteOrder(true); - - // set width/height - bufferWidth = etopoWidths[resIdx]; - bufferHeight = etopoHeights[resIdx]; - - int spacer = 1; - - // don't know why I have to do this, but there seems to be - // a wrapping thing going on with different data sets. - switch (minuteSpacing) { - case (2): - spacer = 1 + this.spacer; - break; - case (5): - spacer = 0 + this.spacer; - break; - default: - spacer = 1 + this.spacer; - } - - // allocate storage - dataBuffer = new short[(bufferWidth + spacer) * bufferHeight]; - - // read data - for (int i = 0; i < bufferWidth * bufferHeight; i++) - dataBuffer[i] = binFile.readShort(); - - // done - binFile.close(); - - // This is important for image creation. - bufferWidth += spacer; - - } catch (FileNotFoundException e) { - Debug.error("ETOPOLayer loadBuffer(): file " + fileName - + " not found"); - } catch (IOException e) { - Debug.error("ETOPOLayer loadBuffer(): File IO Error!\n" - + e.toString()); - } catch (FormatException e) { - Debug.error("ETOPOLayer loadBuffer(): Format exception!\n" - + e.toString()); - } - - } - - /* - * Builds the raster image that has the dimensions of the current - * projection. The algorithm is is follows:

 allocate storage the
-	 * size of the projection (use ints for RGBA)
-	 * 
-	 * for each screen point
-	 * 
-	 * inverse project screen point to get lat/lon (world coords) get altitude
-	 * and/or slope at the world coord compute (lookup) color at the world coord
-	 * set color value into screen coord location
-	 * 
-	 * end
-	 * 
-	 * create OMRaster from the int array data. 
- * - * The code contains a HACK (primarily for the Orthographic projection) - * since * x/y values which would return an "Outer Space" value actually - * return lat/lon values for the center of the projection (see - * Orthographic.inverse(...)). This resulted in the "Outer Space" being - * painted the color of whatever the center lat/lon was. The HACK turns any - * center lat/lon value into black. Of course, this causes valid center - * lat/lon values to be painted black, but the trade off is worth it - * visually. The appropriate method may be to have Projection.inverse and - * its variants raise an exception for "Outer Space" values. - */ - protected OMRaster buildRaster() { - // initialize the return - OMRaster ret = null; - Projection projection = getProjection(); - // work with the slopeMap - if (slopeMap != null) { - - // compute our deltas - int width = projection.getWidth(); - int height = projection.getHeight(); - - // create int array to hold colors - int[] colors = new int[width * height]; - - // compute scalers for lat/lon indicies - float scy = (float) bufferHeight / 180F; - float scx = (float) bufferWidth / 360F; - - // starting and ending indices - int sx = 0, sy = 0, ex = width, ey = height; - - // handle CADRG - if (projection instanceof CADRG) { - - // get corners - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - - // set start/end indicies - Point2D ulp = projection.forward(ul); - Point2D lrp = projection.forward(lr); - sx = (int) ulp.getX(); - ex = (int) lrp.getX(); - sy = (int) ulp.getY(); - ey = (int) lrp.getY(); - - } - - // get the center lat/lon (used by the HACK, see above in - // method description) - Point2D center = projection.getCenter(); - LatLonPoint llp = new LatLonPoint.Double(); - // build array - for (int y = sy; y < ey; y++) { - - // process each column - for (int x = sx; x < ex; x++) { - - // inverse project x,y to lon,lat - projection.inverse(x, y, llp); - - // get point values - float lat = llp.getLatitude(); - float lon = llp.getLongitude(); - - // check... dfd - if (minuteSpacing == 2) { - lon += 180.; - } else { - if (lon < 0.) - lon += 360.; - } - - // find indicies - int lat_idx = (int) ((90. - lat) * scy); - int lon_idx = (int) (lon * scx); - - // offset - int ofs = lon_idx + lat_idx * bufferWidth; - - // make a color - int idx = 0; - int gray = 0; - try { - - // get elevation - short el = dataBuffer[ofs]; - - // slope - byte sl = slopeMap[ofs]; - - // our index - idx = y * width + x; - - // create a color - Color pix = null; - if (viewType == SLOPESHADING) { - // HACK (see method description above) - if ((llp.getLatitude() == center.getY()) - && (llp.getLongitude() == center.getX())) - gray = 0; - else - gray = 127 + sl; - pix = new Color(gray, gray, gray, opaqueness); - } else if (viewType == COLOREDSHADING) { - // HACK (see method description above) - if ((llp.getLatitude() == center.getY()) - && (llp.getLongitude() == center.getX())) - pix = new Color(0, 0, 0, opaqueness); - else - pix = getColor(el, sl); - } - - // set - if (pix != null) { - colors[idx] = pix.getRGB(); - } - - } - - // tried to set a bad color level - catch (IllegalArgumentException e) { - Debug.error(e.toString() + ":" + gray); - } - - // bad index - catch (ArrayIndexOutOfBoundsException e) { - Debug.error(e.toString() + ":" + idx); - } - } - } - - // create the raster - ret = new OMRaster(0, 0, width, height, colors); - - } - - // return or raster - return ret; - - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the etopo. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - if (projection == null) { - Debug - .error("ETOPO Layer needs to be added to the MapBean before it can draw images!"); - return new OMGraphicList(); - } - - // load the buffer - if (dataBuffer == null || spacingReset) { - loadBuffer(); - spacingReset = false; - slopeReset = true; - } - - // re-do the slope map - if (slopeReset) { - buildSlopeMap(); - slopeReset = false; - } - - Debug.message("basic", getName() + "|ETOPOLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (Debug.debugging("etopo")) { - Debug.output(getName() + "|ETOPOLayer.prepare(): " - + "calling getRectangle " + " with projection: " - + projection + " ul = " + projection.getUpperLeft() - + " lr = " + projection.getLowerRight()); - } - - // build graphics list - OMGraphicList omGraphicList = new OMGraphicList(); - omGraphicList.add(buildRaster()); - - // /////////////////// - // safe quit - int size = 0; - if (omGraphicList != null) { - size = omGraphicList.size(); - Debug.message("basic", getName() - + "|ETOPOLayer.prepare(): finished with " + size - + " graphics"); - } else { - Debug - .message( - "basic", - getName() - + "|ETOPOLayer.prepare(): finished with null graphics list"); - omGraphicList = new OMGraphicList(); - } - - // Don't forget to project them. Since they are only being - // recalled if the projection has changed, then we need to - // force a reprojection of all of them because the screen - // position has changed. - omGraphicList.project(projection, true); - return omGraphicList; - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - /** The user interface palette for the ETOPO layer. */ - protected Box paletteBox = null; - - /** Creates the interface palette. */ - public Component getGUI() { - - if (paletteBox == null) { - if (Debug.debugging("etopo")) - Debug.output("ETOPOLayer: creating ETOPO Palette."); - - paletteBox = Box.createVerticalBox(); - Box subbox0 = Box.createHorizontalBox(); - Box subbox1 = Box.createHorizontalBox(); - Box subbox2 = Box.createVerticalBox(); - Box subbox3 = Box.createHorizontalBox(); - - // The ETOPO resolution selector - JPanel resPanel = PaletteHelper - .createPaletteJPanel("Lat/Lon Spacing"); - String[] resStrings = { "2 Minute", "5 Minute", "10 Minute", - "15 Minute" }; // ep-g - - JComboBox resList = new JComboBox(resStrings); - resList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - int newRes = jcb.getSelectedIndex(); - int curRes = minuteSpacing / 5; // ep-g - if (curRes != newRes) - spacingReset = true; - switch (newRes) { - case 0: - minuteSpacing = 2; - break; // ep-g - case 1: - minuteSpacing = 5; - break; // ep-g - case 2: - minuteSpacing = 10; - break; // ep-g - case 3: - minuteSpacing = 15; - break; // ep-g - } - - } - }); - - resList.setSelectedIndex(minuteSpacing / 5); // ep-g - resPanel.add(resList); - - // The ETOPO view selector - JPanel viewPanel = PaletteHelper.createPaletteJPanel("View Type"); - String[] viewStrings = { "Grayscale Shading", "Color Shading" }; - - JComboBox viewList = new JComboBox(viewStrings); - viewList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - int newView = jcb.getSelectedIndex(); - if (newView != viewType) - slopeReset = true; - switch (newView) { - case 0: - viewType = SLOPESHADING; - break; - case 1: - viewType = COLOREDSHADING; - break; - } - - } - }); - - viewList.setSelectedIndex(viewType); - viewPanel.add(viewList); - - // The ETOPO Contrast Adjuster - JPanel contrastPanel = PaletteHelper - .createPaletteJPanel("Contrast Adjustment"); - JSlider contrastSlide = new JSlider(JSlider.HORIZONTAL, 1/* min */, - 5/* max */, 3/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(1), new JLabel("min")); - dict.put(new Integer(5), new JLabel("max")); - contrastSlide.setLabelTable(dict); - contrastSlide.setPaintLabels(true); - contrastSlide.setMajorTickSpacing(1); - contrastSlide.setPaintTicks(true); - contrastSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - Debug.output("ETOPOLayer - Contrast Slider value = " - + slider.getValue()); - slopeAdjust = slider.getValue(); - } - } - }); - contrastPanel.add(contrastSlide); - - // The ETOPO Opaqueness - JPanel opaquenessPanel = PaletteHelper - .createPaletteJPanel("Opaqueness"); - JSlider opaquenessSlide = new JSlider(JSlider.HORIZONTAL, - 0/* min */, 255/* max */, opaqueness/* initial */); - opaquenessSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - fireRequestInfoLine("ETOPOLayer - Opaqueness Slider value = " - + slider.getValue()); - opaqueness = slider.getValue(); - } - } - }); - - opaquenessPanel.add(opaquenessSlide); - - JButton redraw = new JButton("Redraw ETOPO Layer"); - redraw.addActionListener(this); - redraw.setActionCommand(RedrawCmd); - - subbox0.add(resPanel); - paletteBox.add(subbox0); - subbox1.add(viewPanel); - paletteBox.add(subbox1); - subbox2.add(contrastPanel); - subbox2.add(opaquenessPanel); - paletteBox.add(subbox2); - subbox3.add(redraw); - paletteBox.add(subbox3); - } - - return paletteBox; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * Used just for the redraw button. - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - if (e.getActionCommand() == RedrawCmd) { - doPrepare(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/etopo/package.html b/src/core/src/main/java/com/bbn/openmap/layer/etopo/package.html deleted file mode 100644 index 1ea603a54..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/etopo/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - -Provides a layer that displays ETOPO data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/event/CSVEventImporter.java b/src/core/src/main/java/com/bbn/openmap/layer/event/CSVEventImporter.java deleted file mode 100644 index c01b374b2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/event/CSVEventImporter.java +++ /dev/null @@ -1,493 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** -package com.bbn.openmap.layer.event; - -import java.net.MalformedURLException; -import java.net.URL; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.SwingConstants; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.layer.location.LocationHandler; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.time.TemporalOMGraphic; -import com.bbn.openmap.omGraphics.time.TemporalOMGraphicList; -import com.bbn.openmap.omGraphics.time.TemporalOMPoint; -import com.bbn.openmap.omGraphics.time.TemporalOMScalingIcon; -import com.bbn.openmap.omGraphics.time.TemporalPoint; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * A data importer for the EventLayer. The location file should contain - * information about objects that will be moving on the map. The activity file - * will contain information about where and when the objects moved. Sample - * properties: - * - *

- *    eventLayer.class=com.bbn.openmap.layer.time.EventLayer
- *    eventLayer.importer=com.bbn.openmap.layer.time.CSVEventImporter
- *    eventLayer.prettyName=Test Event
- *    eventLayer.locationFile=org-list.csv
- *    eventLayer.locationFileHasHeader=true
- *    eventLayer.nameIndex=0
- *    eventLayer.iconIndex=5
- *    eventLayer.activityFile=org-activities.csv
- *    eventLayer.activityFileHasHeader=true
- *    eventLayer.activityNameIndex=1
- *    eventLayer.latIndex=9
- *    eventLayer.lonIndex=10
- *    eventLayer.timeFormat=d-MMM-yyyy HH:mm
- *    eventLayer.timeIndex=7
- *    # If no icon defined, used for location markers edge.
- *    eventLayer.lineColor=aaaaaa33
- *    # If no icon defined, used for location markers fill.
- *    eventLayer.fillColor=aaaaaa33
- * 
- * - * @author dietrick - */ -public class CSVEventImporter extends OMComponent implements EventImporter { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.event.CSVEventImporter"); - - /** - * locationFile - */ - public final static String LocationFileProperty = "locationFile"; - /** - * locationFileHasHeader - */ - public final static String LocationHeaderProperty = "locationFileHasHeader"; - /** - * iconIndex - */ - public final static String IconIndexProperty = "iconIndex"; - /** - * nameIndex - */ - public final static String NameIndexProperty = "nameIndex"; - - /** - * activityFile - */ - public final static String ActivityFileProperty = "activityFile"; - /** - * activityNameIndex - */ - public final static String ActivityNameIndexProperty = "activityNameIndex"; - /** - * activityFileHasHeader - */ - public final static String ActivityHeaderProperty = "activityFileHasHeader"; - /** - * latIndex - */ - public final static String LatIndexProperty = "latIndex"; - /** - * lonIndex - */ - public final static String LonIndexProperty = "lonIndex"; - /** - * timeIndex - */ - public final static String TimeIndexProperty = "timeIndex"; - /** - * eastIsNeg - */ - public final static String EastIsNegProperty = "eastIsNeg"; - /** - * showNames - */ - public final static String ShowNamesProperty = LocationHandler.ShowNamesProperty; - /** - * defaultURL - */ - public final static String DefaultIconURLProperty = "defaultURL"; - /** - * timeFormat - */ - public final static String TimeFormatProperty = "timeFormat"; - /** - * TimeFormat default is similar to IETF standard date syntax: "Sat, 12 Aug 1995 - * 13:30:00 GMT" represented by (EEE, d MMM yyyy HH:mm:ss z), except for the - * local timezone. - */ - protected SimpleDateFormat timeFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); - - protected String locationFile; - protected boolean locationHeader = true; - protected int nameIndex; - protected int iconIndex; - protected String activityFile; - protected boolean activityHeader = true; - protected int activityNameIndex; - protected int latIndex; - protected int lonIndex; - protected int timeIndex; - protected boolean eastIsNeg = false; - protected int orientation = SwingConstants.HORIZONTAL; - - /** - * Icon URL for points to use as default. May be null. - */ - protected String defaultIconURL; - protected boolean showNames = false; - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - public CSVEventImporter() { - - } - - /** - * Read the data files and construct the TemporalOMGraphics. You also need to - * create TimeBounds, keep track of the time stamps from the data source, and - * set the new TimeBounds on the EventLayer before returning from this method. - * If you want to set the DataBounds on the layer, in order for the view menu to - * have a selection for the area of interest, fetch the DataBounds object and - * set it accordingly while you are in this method. - *

- * Read the data files and construct the TemporalOMGraphics. There are four - * things you need to do in this method. - *

    - *
  • Create an TemporalOMGraphicList, add TemporalOMGraphics, return it. - *
  • Set a new TimeBounds object on the callback EventLayer when all the - * timestamp range is known. - *
  • Add OMEvents to the callback.events list, one for each TemporalPoint - * created. - *
  • Add locations to callback's DataBounds (callback.getDataBounds()). - *
- */ - public synchronized TemporalOMGraphicList createData(EventLayer callback) { - TemporalOMGraphicList list = new TemporalOMGraphicList(); - Hashtable library = new Hashtable(); - Hashtable iconLibrary = new Hashtable(); - - // BOTH IMPORTANT - DataBounds dataBounds = callback.getDataBounds(); - TimeBounds timeBounds = new TimeBounds(); - - // Create TemporalOMGraphics, to associate events to - if (locationFile != null && nameIndex != -1) { - logger.fine("Reading location file..."); - try { - CSVFile locations = new CSVFile(locationFile); - locations.loadData(); - - for (List record : locations) { - - String name = null; - String iconName = null; - ImageIcon icon = null; - - if (record.isEmpty()) { - continue; - } - - name = (String) record.get(nameIndex); - - if (iconIndex != -1) { - iconName = (String) record.get(iconIndex); - - icon = iconLibrary.get(iconName); - - if (icon == null) { - URL icURL = PropUtils.getResourceOrFileOrURL(iconName); - if (icURL != null) { - icon = new ImageIcon(icURL); - if (icon != null) { - iconLibrary.put(iconName, icon); - } - } - } - } - - if (name != null) { - TemporalOMGraphic location; - if (icon == null) { - location = new TemporalOMPoint(name, OMGraphic.RENDERTYPE_LATLON, true); - } else { - location = new TemporalOMScalingIcon(name, OMGraphic.RENDERTYPE_LATLON, true, icon, - 4000000); - } - // location.setShowName(showNames); - drawingAttributes.setTo(location); - library.put(name.intern(), location); - list.add(location); - } else { - logger.warning("no name to use to create location: " + name); - } - } - } catch (MalformedURLException murle) { - logger.warning("problem finding the location file: " + locationFile); - return list; - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.warning("problem with parsing location file: " + locationFile); - if (logger.isLoggable(Level.FINE)) { - logger.fine("The problem is with one of the indexes into the file: \n" + aioobe.getMessage()); - aioobe.printStackTrace(); - } - } catch (NullPointerException npe) { - logger.warning("null pointer exception, most likely a problem finding the organization data file"); - } - } else { - logger.warning("Location file (" + locationFile + ") not configured."); - return list; - } - - // OK, got the TemporalOMGraphics built up, need to fill up the - // events - // - if (activityFile != null && activityNameIndex != -1 && latIndex != -1 && lonIndex != -1 && timeIndex != -1) { - logger.fine("Reading activity file..."); - - try { - CSVFile activities = new CSVFile(activityFile); - activities.loadData(); // numbers as strings == false - - for (List activity : activities) { - String name = null; - float lat; - float lon; - - if (activity.isEmpty()) { - continue; - } - - name = activity.get(activityNameIndex).toString().intern(); - - try { - lat = ((Double) activity.get(latIndex)).floatValue(); - lon = ((Double) activity.get(lonIndex)).floatValue(); - - // parse time from string, ending up with - // milliseconds from time epoch. - String timeString = (String) activity.get(timeIndex); - Date timeDate = timeFormat.parse(timeString); - long time = timeDate.getTime(); - - // BOTH IMPORTANT - timeBounds.addTimeToBounds(time); - dataBounds.add((double) lon, (double) lat); - - if (name != null) { - TemporalOMGraphic point = library.get(name); - if (point != null) { - LatLonPoint location = new LatLonPoint.Double(lat, lon); - TemporalPoint ts = new TemporalPoint(location, time); - point.addTimeStamp(ts); - - OMEvent event = new OMEvent(ts, name + " moving", time, location); - - // IMPORTANT - callback.events.add(event); - - } else { - logger.warning("ScenarioPoint not found for " + name + ", entry: " + activity); - } - } else { - logger.warning("no name to use to create activity point: " + name); - } - - } catch (ClassCastException cce) { - - Object obj0 = activity.get(activityNameIndex); - Object obj1 = activity.get(latIndex); - Object obj2 = activity.get(lonIndex); - Object obj3 = activity.get(timeIndex); - - logger.warning("Problem with indexes in activity file for " + obj0 + " (" - + obj0.getClass().getName() + ")" + ":\n\tlat index = " + latIndex + ", value = " + obj1 - + " (" + obj1.getClass().getName() + ")\n\t lon index = " + lonIndex + ", value = " - + obj2 + " (" + obj2.getClass().getName() + ")\n\t time index = " + timeIndex - + ", value = " + obj3 + " (" + obj3.getClass().getName() + ")"); - } catch (ParseException pe) { - logger.fine("Problem with time format. " + pe.getMessage()); - } - } - } catch (MalformedURLException murle) { - logger.warning("problem with activity file: " + activityFile); - return list; - } catch (NullPointerException npe) { - logger.warning("null pointer exception, most likely a problem finding the activites data file"); - } - } else { - logger.warning("Activity file (" + activityFile + ") not configured."); - return list; - } - - logger.fine("Reading files OK"); - - // IMPORTANT! - callback.setTimeBounds(timeBounds); - - // Time will get updated automatically when the TimeEvent gets sent from - // the clock. - return list; - } - - /** - * The properties and prefix are managed and decoded here, for the standard uses - * of the EventLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - drawingAttributes.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - locationFile = properties.getProperty(prefix + LocationFileProperty); - iconIndex = PropUtils.intFromProperties(properties, prefix + IconIndexProperty, -1); - nameIndex = PropUtils.intFromProperties(properties, prefix + NameIndexProperty, -1); - activityNameIndex = PropUtils.intFromProperties(properties, prefix + ActivityNameIndexProperty, -1); - activityFile = properties.getProperty(prefix + ActivityFileProperty); - latIndex = PropUtils.intFromProperties(properties, prefix + LatIndexProperty, -1); - lonIndex = PropUtils.intFromProperties(properties, prefix + LonIndexProperty, -1); - timeIndex = PropUtils.intFromProperties(properties, prefix + TimeIndexProperty, -1); - eastIsNeg = PropUtils.booleanFromProperties(properties, prefix + EastIsNegProperty, eastIsNeg); - showNames = PropUtils.booleanFromProperties(properties, prefix + ShowNamesProperty, showNames); - defaultIconURL = properties.getProperty(prefix + DefaultIconURLProperty); - locationHeader = PropUtils.booleanFromProperties(properties, prefix + LocationHeaderProperty, false); - activityHeader = PropUtils.booleanFromProperties(properties, prefix + ActivityHeaderProperty, false); - - String timeFormatString = properties.getProperty(prefix + TimeFormatProperty, - ((SimpleDateFormat) timeFormat).toPattern()); - - timeFormat = new SimpleDateFormat(timeFormatString); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("EventLayer indexes:" + "\n\tlocation file: " + locationFile + "\n\tlocation file has header: " - + locationHeader + "\n\tnameIndex = " + nameIndex + "\n\ticonIndex = " + iconIndex - + "\n\tactivity file: " + activityFile + "\n\tactivity file has header: " + activityHeader - + "\n\tlatIndex = " + latIndex + "\n\tlonIndex = " + lonIndex + "\n\ttimeIndex = " + timeIndex); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to each - * property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it should - * be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - drawingAttributes.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + LocationFileProperty, PropUtils.unnull(locationFile)); - props.put(prefix + LocationHeaderProperty, new Boolean(locationHeader).toString()); - props.put(prefix + NameIndexProperty, (nameIndex != -1 ? Integer.toString(nameIndex) : "")); - - props.put(prefix + ActivityFileProperty, PropUtils.unnull(activityFile)); - props.put(prefix + ActivityHeaderProperty, new Boolean(activityHeader).toString()); - props.put(prefix + ActivityNameIndexProperty, - (activityNameIndex != -1 ? Integer.toString(activityNameIndex) : "")); - props.put(prefix + EastIsNegProperty, new Boolean(eastIsNeg).toString()); - props.put(prefix + ShowNamesProperty, new Boolean(showNames).toString()); - props.put(prefix + LatIndexProperty, (latIndex != -1 ? Integer.toString(latIndex) : "")); - props.put(prefix + LonIndexProperty, (lonIndex != -1 ? Integer.toString(lonIndex) : "")); - props.put(prefix + TimeIndexProperty, (timeIndex != -1 ? Integer.toString(timeIndex) : "")); - props.put(prefix + IconIndexProperty, (iconIndex != -1 ? Integer.toString(iconIndex) : "")); - props.put(prefix + DefaultIconURLProperty, PropUtils.unnull(defaultIconURL)); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the properties - * able to be set on this PropertyConsumer. The key for each property should be - * the raw property name (without a prefix) with a value that is a String that - * describes what the property key represents, along with any other information - * about the property that would be helpful (range, default value, etc.). This - * method takes care of the basic LocationHandler parameters, so any - * LocationHandlers that extend the AbstractLocationHandler should call this - * method, too, before adding any specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties into. - * If getList equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it should - * be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put(LocationFileProperty, "URL of file containing location information."); - list.put(LocationFileProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - list.put(LocationHeaderProperty, "Location file has a header row to be ignored."); - list.put(LocationHeaderProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(ActivityFileProperty, "URL of file containing scenario activity information."); - list.put(ActivityFileProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - list.put(ActivityHeaderProperty, "Activity file has a header row to be ignored."); - list.put(ActivityHeaderProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(EastIsNegProperty, "Flag to note that negative latitude are over the eastern hemisphere."); - list.put(EastIsNegProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(ShowNamesProperty, "Flag to note that locations should display their names."); - list.put(ShowNamesProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(NameIndexProperty, "The column index, in the location file, of the location label text."); - - list.put(ActivityNameIndexProperty, "The column index, in the activity file, of the location label text."); - - list.put(LatIndexProperty, "The column index, in the activity file, of the latitudes."); - list.put(LonIndexProperty, "The column index, in the activity file, of the longitudes."); - list.put(TimeIndexProperty, "The column index, in the activity file, of the time of the activity."); - list.put(IconIndexProperty, "The column index, in the location file, of the icon for locations (optional)."); - list.put(DefaultIconURLProperty, - "The URL of an image file to use as a default for the location markers (optional)."); - - drawingAttributes.getPropertyInfo(list); - - return list; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/event/EventImporter.java b/src/core/src/main/java/com/bbn/openmap/layer/event/EventImporter.java deleted file mode 100644 index 99c5257f8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/event/EventImporter.java +++ /dev/null @@ -1,52 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.event; - -import com.bbn.openmap.omGraphics.time.TemporalOMGraphicList; - -/** - * EventImporter is an object that the EventLayer uses to query a data source - * for events/records. It creates a TemporalOMGraphicList for the EventLayer to - * use. - * - * @author dietrick - */ -public interface EventImporter { - - /** - * Read the data files and construct the TemporalOMGraphics. There are four things you need to do in this method. - *
    - *
  • Create an TemporalOMGraphicList, add TemporalOMGraphics, return it. - *
  • Set a new TimeBounds object on the callback EventLayer when all the timestamp range is known. - *
  • Add OMEvents to the callback.events list, one for each TemporalPoint created. - *
  • Add locations to callback's DataBounds (callback.getDataBounds()). - *
- * - * @param callback EventLayer to set all the information on. - * @return TemporalOMGraphicList with the events on the map. - */ - TemporalOMGraphicList createData(EventLayer callback); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/event/EventLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/event/EventLayer.java deleted file mode 100644 index 5cfe02d37..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/event/EventLayer.java +++ /dev/null @@ -1,361 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/scenario/EventLayer.java,v $ -// $RCSfile: EventLayer.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/03/06 16:13:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.event; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.event.OMEventHandler; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.time.TemporalOMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.time.RealTimeHandler; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.time.TimeBoundsHandler; -import com.bbn.openmap.time.TimeBoundsProvider; -import com.bbn.openmap.time.TimeEvent; -import com.bbn.openmap.time.TimeEventListener; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.PropUtils; - -/** - * The EventLayer contains all the TemporalOMGraphics and manages the time for - * the graphics and how they should be displayed. This layer works as a - * TimeBoundsProvider (an object that provides an active range of time, a - * OMEventHandler (an object that provides OMEvents to the - * EventPanel/EventPresenter), and a TimeEventListener (an object that changes - * when the cloc changes). - *

- * - * Sample properties: - * - *

- *    eventLayer.class=com.bbn.openmap.layer.time.EventLayer
- *    eventLayer.importer=com.bbn.openmap.layer.time.CSVEventImporter
- *    eventLayer.prettyName=Test Event
- *    
- *    ... see CSVEventImporter for its properties, other importers can be specified here.
- * 
- */ -public class EventLayer extends OMGraphicHandlerLayer - implements DataBoundsProvider, TimeBoundsProvider, TimeEventListener, OMEventHandler { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.event.EventLayer"); - - public final static String ImporterProperty = "importer"; - protected EventImporter importer = null; - protected DataBounds dataBounds = null; - - protected TimeBounds timeBounds; - protected long time; - protected String mode; - protected boolean active = false; - - public EventLayer() { - dataBounds = new DataBounds(); - } - - /** - * The main method call in the EventLayer that actually modifies the - * OMGraphics and updates the map. - */ - public synchronized OMGraphicList prepare() { - Projection p = getProjection(); - TemporalOMGraphicList scenarioGraphics = null; - OMGraphicList list = getList(); - - // Need this check in here because the time stuff might cause this to be - // called before the layer is actually added to the map. - if (p != null) { - boolean DEBUG = logger.isLoggable(Level.FINE); - if (list == null || !(list instanceof TemporalOMGraphicList)) { - scenarioGraphics = createData(); - if (scenarioGraphics == null) { - // Don't do anything - return null; - } - // The data importer should have set the time bounds, and that - // should be calling this then. - callForTimeBoundsReset(); - } else { - scenarioGraphics = new TemporalOMGraphicList(list); - } - - long currentTime = getTime(); - - if (DEBUG) { - logger.fine("EventLayer (" + getName() + ") snapshot at " + currentTime); - } - - scenarioGraphics.generate(p, currentTime); - - if (DEBUG) { - logger.fine("EventLayer (" + getName() + ") setting list of " + scenarioGraphics.size() - + " scenario graphics"); - } - } - - return scenarioGraphics; - } - - /** - * Read the data files and construct the TemporalOMGraphics. - */ - public synchronized TemporalOMGraphicList createData() { - if (importer != null) { - return importer.createData(this); - } else { - return null; - } - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the EventLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String importerClass = properties.getProperty(prefix + ImporterProperty); - if (importerClass != null) { - importer = (EventImporter) ComponentFactory.create(importerClass, prefix, properties); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - if (importer != null) { - props.put(prefix + ImporterProperty, importer.getClass().getName()); - } - - if (importer instanceof PropertyConsumer) { - ((PropertyConsumer) importer).getProperties(props); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - PropUtils.setI18NPropertyInfo(i18n, list, getClass(), ImporterProperty, "Data Importer", - "Class name of data importer", null); - - if (importer instanceof PropertyConsumer) { - ((PropertyConsumer) importer).getPropertyInfo(list); - } - - return list; - } - - public String getMode() { - return mode; - } - - public void setMode(String mode) { - this.mode = mode; - } - - /** - * DataBoundsProvider method. - */ - public DataBounds getDataBounds() { - return dataBounds; - } - - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - - if (someObj instanceof TimeBoundsHandler) { - addTimeBoundsHandler((TimeBoundsHandler) someObj); - } - - if (someObj instanceof RealTimeHandler) { - ((RealTimeHandler) someObj).addTimeEventListener(this); - } - } - - // TimeBoundsProvider methods. - protected List timeBoundsHandlers = new ArrayList(); - - public void addTimeBoundsHandler(TimeBoundsHandler tbh) { - logger.fine("found TimeBoundsHandler: " + tbh.getClass().getName()); - timeBoundsHandlers.add(tbh); - } - - public void setTimeBounds(TimeBounds tb) { - timeBounds = tb; - /*if (active) { - callForTimeBoundsReset(); - }*/ - } - - public TimeBounds getTimeBounds() { - if (active) { - return timeBounds; - } - return null; - } - - public void handleTimeBounds(TimeBounds tb) { - // NoOp, we don't really care what the current time bounds are - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - if (timeBounds != null) { - callForTimeBoundsReset(); - } - } - - public void removeTimeBoundsHandler(TimeBoundsHandler tbh) { - timeBoundsHandlers.remove(tbh); - } - - public void updateTime(TimeEvent te) { - time = te.getSystemTime(); - if (active) { - setList(prepare()); - repaint(); - } - } - - public long getTime() { - return time; - } - - protected LinkedList events = new LinkedList(); - protected LinkedList filters = new LinkedList(); - - public List getEventList() { - return getEventList(null); - } - - public List getEventList(List filters) { - if (active) { - return events; - } - return null; - } - - public Boolean getFilterState(String filterName) { - return (isVisible() ? Boolean.TRUE : Boolean.FALSE); - } - - public List getFilters() { - return filters; - } - - public List getMacroFilteredList(Collection eventCollection) { - return events; - } - - public void setFilterState(String filterName, Boolean state) { - } - - public void callForTimeBoundsReset() { - for (TimeBoundsHandler tbh : timeBoundsHandlers) { - tbh.resetTimeBounds(); - } - } - - public void setVisible(boolean setting) { - super.setVisible(setting); - setActive(setting); - } - - /** - * @return the importer that creates temporal events from data. - */ - public EventImporter getImporter() { - return importer; - } - - /** - * The importer creates temporal events from data. - * - * @param importer the importer to set - */ - public void setImporter(EventImporter importer) { - this.importer = importer; - - // Reset - events.clear(); - dataBounds = new DataBounds(); - setList(null); - doPrepare(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/event/TestEventHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/event/TestEventHandler.java deleted file mode 100644 index 624e72803..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/event/TestEventHandler.java +++ /dev/null @@ -1,118 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.event; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.event.OMEventHandlerAdapter; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.time.TimeBoundsHandler; -import com.bbn.openmap.time.TimeBoundsProvider; - -/** - * Sample OMEventHandler to demonstrate being a TimeBoundsProvider and TimeBoundsHandler. - * - * @author dietrick - */ -public class TestEventHandler extends OMEventHandlerAdapter implements - TimeBoundsProvider { - - protected TimeBounds timeBounds; - protected List timeBoundsHandlers = new ArrayList(); - protected boolean active = true; - - public TestEventHandler() { - super(); - timeBounds = new TimeBounds(); - createEvents(); - } - - protected void createEvents() { - - - addEvent(new OMEvent("Object Source", "Event 1", System.currentTimeMillis())); - addEvent(new OMEvent("Object Source", "Event 2", System.currentTimeMillis() + 1000l)); - addEvent(new OMEvent("Object Source", "Event 3", System.currentTimeMillis() + 2000l)); - addEvent(new OMEvent("Object Source", "Event 4", System.currentTimeMillis() + 3500l)); - addEvent(new OMEvent("Object Source", "Event 5", System.currentTimeMillis() + 5500l)); - addEvent(new OMEvent("Object Source", "Event 6", System.currentTimeMillis() + 10000l)); - addEvent(new OMEvent("Object Source", "Event 7", System.currentTimeMillis() + 20000l)); - addEvent(new OMEvent("Object Source", "Event 8", System.currentTimeMillis() + 25600l)); - addEvent(new OMEvent("Object Source", "Event 9", System.currentTimeMillis() + 45000l)); - addEvent(new OMEvent("Object Source", "Event 10", System.currentTimeMillis() + 60900l)); - - callForTimeBoundsReset(); - } - - public void addEvent(OMEvent event) { - super.addEvent(event); - timeBounds.addTimeToBounds(event.getTimeStamp()); - } - - public List getEventList(List filters) { - // At this level, we just want to return all events. Let - // subclasses worry about macro-filtered events... - // return getMacroFilteredList(events); - if (active) { - return events; - } else { - return new ArrayList(); - } - } - - public void addTimeBoundsHandler(TimeBoundsHandler tbh) { - timeBoundsHandlers.add(tbh); - } - - public TimeBounds getTimeBounds() { - return timeBounds; - } - - public void handleTimeBounds(TimeBounds tb) { - // NO-OP - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - callForTimeBoundsReset(); - } - - public void removeTimeBoundsHandler(TimeBoundsHandler tbh) { - timeBoundsHandlers.remove(tbh); - } - - public void callForTimeBoundsReset() { - for (TimeBoundsHandler tbh : timeBoundsHandlers) { - tbh.resetTimeBounds(); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/geojson/GeoJSONLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/geojson/GeoJSONLayer.java deleted file mode 100644 index 529cda620..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/geojson/GeoJSONLayer.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.layer.geojson; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Map; -import java.util.Properties; - -import com.bbn.openmap.dataAccess.geojson.FeatureCollection; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.rule.MapRule; -import com.bbn.openmap.omGraphics.rule.Rule; -import com.bbn.openmap.omGraphics.rule.RuleHandler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * GeoJSONLayer displays geometries loaded from a GeoJSON document. - * - * @author dietrick - */ -public class GeoJSONLayer extends OMGraphicHandlerLayer { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public final static String SOURCE_PROPERTY = "source"; - - /** - * RuleHandler to apply to OMGraphics for rendering and action controls. - */ - GeoJSONRuleHandler rules = new GeoJSONRuleHandler(); - /** - * OMGraphics converted from JSON. Read once, then checked every projection - * change. - */ - OMGraphic convertedJSON = null; - /** - * The JSON source to display (URL). - */ - String jsonFile = null; - - /** - * Default rendering attributes for converted JSON OMGraphics before the - * rules are applied. - */ - DrawingAttributes defaultDrawingAttributes = DrawingAttributes.getDefaultClone(); - - public GeoJSONLayer() { - setProjectionChangePolicy(new ListResetPCPolicy(this)); - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - rules.setProperties(prefix, props); - - defaultDrawingAttributes.setProperties(prefix, props); - - String jsonFileString = props.getProperty(PropUtils.getScopedPropertyPrefix(prefix) - + SOURCE_PROPERTY); - if (jsonFileString != null) { - setJsonFile(jsonFileString); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - rules.getProperties(props); - defaultDrawingAttributes.getProperties(props); - props.setProperty(PropUtils.getScopedPropertyPrefix(this) + SOURCE_PROPERTY, getJsonFile()); - return props; - } - - protected OMGraphicList checkRules(OMGraphic omgraphic, OMGraphicList labelList, Projection proj) { - OMGraphicList retList = null; - - if (omgraphic instanceof OMGraphicList) { - - OMGraphicList innerLoopList = new OMGraphicList(); - OMGraphic innerLoopTest = null; - - for (OMGraphic omg1 : (OMGraphicList) omgraphic) { - // Doing this here might alleviate more checkRules calls and a - // bunch of other instanceof checks. - if (omg1 instanceof OMGraphicList) { - innerLoopTest = checkRules(omg1, labelList, proj); - } else { - innerLoopTest = rules.evaluate(omg1, labelList, proj); - - if (innerLoopTest != null) { - innerLoopTest.generate(proj); - } - } - - if (innerLoopTest != null) { - innerLoopList.add(innerLoopTest); - } - } - - if (!innerLoopList.isEmpty()) { - retList = innerLoopList; - } - } else { - OMGraphic omg1 = rules.evaluate(omgraphic, labelList, proj); - - if (omg1 != null) { - retList = new OMGraphicList(); - omg1.generate(proj); - retList.add(omg1); - } - } - - return retList; - } - - public OMGraphic loadJSON(String urlString) { - if (urlString != null) { - URL input; - try { - input = PropUtils.getResourceOrFileOrURL(urlString); - - InputStream inputStream = input.openStream(); - FeatureCollection featureCollection = new ObjectMapper().readValue(inputStream, FeatureCollection.class); - - OMGraphic omg = featureCollection.convert(); - defaultDrawingAttributes.setTo(omg); - return omg; - - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - return null; - } - - public OMGraphicList prepare() { - OMGraphicList ret = new OMGraphicList(); - - if (convertedJSON == null) { - convertedJSON = loadJSON(jsonFile); - } - - OMGraphicList labelList = new OMGraphicList(); - if (convertedJSON != null) { - ret = checkRules(convertedJSON, labelList, getProjection()); - - if (ret != null) { - ret.add(labelList); - } - } - - return ret; - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - public String getInfoText(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.INFOLINE); - } - - /** - * @return the jsonFile - */ - public String getJsonFile() { - return jsonFile; - } - - /** - * @param jsonFile the jsonFile to set - */ - public void setJsonFile(String jsonFile) { - this.jsonFile = jsonFile; - convertedJSON = null; - } - - /** - * GeoJSONRuleHandler knows how to handle rules for the GeoJSON parameters. - * The Attributes are stored directly into the OMGraphic attributes. - * - * @author dietrick - */ - public class GeoJSONRuleHandler extends RuleHandler> { - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.omGraphics.rule.RuleHandler#createRule() - */ - @Override - public Rule createRule() { - return new MapRule(); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.omGraphics.rule.RuleHandler#getRecordDataForOMGraphic - * (com.bbn.openmap.omGraphics.OMGraphic) - */ - @Override - public Map getRecordDataForOMGraphic(OMGraphic omg) { - return omg.getAttributes(); - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderConnector.java b/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderConnector.java deleted file mode 100644 index 6eaeb6e54..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderConnector.java +++ /dev/null @@ -1,201 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/graphicLoader/GraphicLoaderConnector.java,v $ -// $RCSfile: GraphicLoaderConnector.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 20:35:11 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.graphicLoader; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.graphicLoader.GraphicLoader; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -/** - * The GraphicLoaderConnector is a MapHandler membership listener, looking for GraphicLoaders without receivers. This - * class uses the MapHandler to find GraphicLoaders, and requires the LayerHandler to be added to the MapHandler, also. - *

- * - * If the GraphicLoaderConnector finds a GraphicLoader that is not hooked up to a receiver, it creates a - * GraphicLoaderLayer, and adds the layer to the LayerHandler. This causes the LayerHandler to add the layer to the - * application. If the GraphicLoaderConnector doesn't have a handle to the LayerHandler when it finds a GraphicLoader, - * it adds the PlugInLayer it created to an internal list to add to the LayerHandler when the connector finds one. - */ -public class GraphicLoaderConnector - extends OMComponent { - - protected LayerHandler layerHandler = null; - protected int newLayerIndex = 0; // On Top by default - protected boolean newLayerVisible = true; // Make new PlugInLayers - // visible. - protected List orphanGraphicLoaderLayers = null; - public final static String NewLayerIndexProperty = "newLayerIndex"; - public final static String NewLayerVisibleProperty = "newLayerVisible"; - - public GraphicLoaderConnector() { - } - - /** - * Set the index of any new layers to be added to the LayerHandler. Negative numbers put the layer on top of the - * map. - */ - public void setNewLayerIndex(int i) { - newLayerIndex = i; - } - - public int getNewLayerIndex() { - return newLayerIndex; - } - - /** - * Set whether the new layers should initially be visible when they are added to the map. - */ - public void setNewLayerVisible(boolean set) { - newLayerVisible = set; - } - - public boolean setNewLayerVisible() { - return newLayerVisible; - } - - /** - * Set the LayerHandler to be notified with any new GraphicLoaderLayers. - */ - public void setLayerHandler(LayerHandler lh) { - layerHandler = lh; - if (orphanGraphicLoaderLayers != null) { - if (Debug.debugging("glc")) { - Debug.output( - "GraphicLoaderConnector: have LayerHandler, adding PlugInLayers from orphaned GraphicLoaders"); - } - - for (Layer layer : orphanGraphicLoaderLayers) { - layerHandler.addLayer(layer, newLayerIndex); - } - orphanGraphicLoaderLayers = null; - } - } - - public LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Check to see if the GraphicLoader already has a receiver set inside it. If it doesn't call - * hookUpGraphicLoaderWithLayer(); - */ - public void checkGraphicLoader(GraphicLoader gl) { - if (gl.getReceiver() == null) { - hookUpGraphicLoaderWithLayer(gl); - } - } - - /** - * Assumes that the GraphicLoader doesn't already have a receiver. Creates a GraphicLoaderPlugIn, and a PlugInLayer, - * and hooks everything up. Then hands the PlugInLayer to the LayerHandler to get set on the map. - */ - public void hookUpGraphicLoaderWithLayer(GraphicLoader gl) { - if (gl != null) { - GraphicLoaderLayer layer = new GraphicLoaderLayer(); - gl.setReceiver(layer); - layer.setGraphicLoader(gl); - LayerHandler lh = getLayerHandler(); - - if (lh != null) { - lh.addLayer(layer, newLayerIndex); - } else { - // If we haven't seen the LayerHandler yet, add the - // PlugInLayer to a list that we can use later when - // the LayerHandler is found. - if (orphanGraphicLoaderLayers == null) { - orphanGraphicLoaderLayers = new LinkedList(); - } - orphanGraphicLoaderLayers.add(layer); - } - } - } - - /** - * Find GraphicLoaders and LayerHandler in the MapHandler. - */ - public void findAndInit(Object obj) { - if (obj instanceof GraphicLoader) { - checkGraphicLoader((GraphicLoader) obj); - } - - if (obj instanceof LayerHandler) { - Debug.message("graphicLoader", - "GraphicLoaderConnector found a LayerHandler."); - setLayerHandler((LayerHandler) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof LayerHandler) { - Debug.message("graphicLoader", - "GraphicLoaderConnector removing a LayerHandler."); - LayerHandler lh = getLayerHandler(); - if (lh != null && lh == (LayerHandler) obj) { - setLayerHandler(null); - } - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - newLayerIndex = PropUtils.intFromProperties(props, prefix - + NewLayerIndexProperty, newLayerIndex); - - newLayerVisible = PropUtils.booleanFromProperties(props, prefix - + NewLayerVisibleProperty, newLayerVisible); - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + NewLayerIndexProperty, - Integer.toString(newLayerIndex)); - props.put(prefix + NewLayerVisibleProperty, - new Boolean(newLayerVisible).toString()); - return props; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put(NewLayerIndexProperty, - "The new layer index, where it should be added to the map. (0 on top)"); - list.put(NewLayerVisibleProperty, - "Whether a new layer should initially be visible"); - list.put(NewLayerVisibleProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return list; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderLayer.java deleted file mode 100644 index 30bab4fbe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/GraphicLoaderLayer.java +++ /dev/null @@ -1,290 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/graphicLoader/GraphicLoaderLayer.java,v $ -// $RCSfile: GraphicLoaderLayer.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/08/09 20:35:11 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.graphicLoader; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.graphicLoader.GraphicLoader; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import java.awt.Component; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.Properties; - -/** - * A GraphicLoaderLayer is a layer that receives its OMGraphics from some other source, at any time. It just listens to - * its GraphicLoader for updates to the OMGraphicList, and then updates the map as necessary. GraphicLoader is an - * interface, so you can think of them as a source of changing OMGraphics, from some data feed or some other - * application-specific component. - *

- * The GraphicLoaderLayer passes projection changes onto the GraphicLoader, and if the GraphicLoader is a - * MapMouseListener, the GraphicLoaderLayer will defer all MouseEvents to it. - *

- * - * To add a GraphicLoader to the OpenMap application, you can do it several ways: - *

    - *
  • You can create a specific GraphicLoaderLayer that creates its own GraphicLoader, and initializes it accordingly. - * You would add the GraphicLoaderLayer to the openmap.layers property in the openmap.properties file. - *
  • You can create a GraphicLoaderLayer by adding an entry to the openmap.layer property in the openmap.properties - * file, and define what kind of GraphicLoader to create in the properties for the GraphicLoaderLayer. - *

    - * - *

    - *
    - *  graphicLoaderPlugIn.class=com.bbn.openmap.layer.graphicLoader.GraphicLoaderLayer
    - *  graphicLoaderPlugIn.prettyName=Name of Layer
    - *  graphicLoaderPlugIn.graphicLoader=GraphicLoader Classname
    - *  graphicLoaderPlugIn.addGraphicLoaderToMapHandler=true/false (false by default)
    - *
    - * 
    - * - *
  • You can add a com.bbn.openmap.layer.graphicLoader.GraphicLoaderConnector to the openmap.components property, and - * then add the GraphicLoader to the openmap.components property as well. The GraphicLoaderConnector will find the - * GraphicLoader, and create a GraphicLoaderLayer for the GraphicLoader and add it to the LayerHandler on top of the - * map. - *
- * - */ -public class GraphicLoaderLayer - extends OMGraphicHandlerLayer { - - protected GraphicLoader loader = null; - public final static String GraphicLoaderProperty = "graphicLoader"; - public final static String AddGraphicLoaderToMapHandlerProperty = "addGraphicLoaderToMapHandler"; - - protected boolean addGraphicLoaderToMapHandler = false; - protected boolean needToAddGraphicLoaderToMapHandler = false; - - private boolean inGetRectangle = false; - protected Object lock = new Object(); - - protected MapMouseListener mapMouseListener = null; - - public GraphicLoaderLayer() { - super(); - } - - /** - * The prepare call is the main call into the Layer when the layer is added to the map or the projection changes.. - * The layer is expected to fill the graphics list with objects that are within the screen parameters passed. - * - * @return OMGraphicList that should be displayed for the current projection. - */ - public OMGraphicList prepare() { - // Used to control the doPrepare() call in setList(). - synchronized (lock) { - inGetRectangle = true; - } - - Projection p = getProjection(); - - if (loader != null) { - loader.setProjection(p); - } - - OMGraphicList list = (OMGraphicList) super.getList(); - list.generate(p); - - if (Debug.debugging("graphicloader")) { - Debug.output("GraphicLoaderLayer returning list of " + list.size() + " objects."); - } - - // Used to control the doPrepare() call in setList(). - synchronized (lock) { - inGetRectangle = false; - } - - return list; - } - - public synchronized void setList(OMGraphicList graphics) { - super.setList(graphics); - - synchronized (lock) { - if (!inGetRectangle) { - // Should be OK, launching a separate thread to - // come back into getRectangle. We only want to call - // doPrepare() if setList is being called in a thread - // from something else controlling the GraphicLoader, - // like a timer or something. - doPrepare(); - } - } - } - - /** - * OMGraphicHandler method. - */ - public synchronized boolean doAction(OMGraphic graphic, OMAction action) { - boolean ret = super.doAction(graphic, action); - doPrepare(); - return ret; - } - - /** - * Set the GraphicLoader for the layer. - */ - public void setGraphicLoader(GraphicLoader gl) { - loader = gl; - - gl.setReceiver(this); - - if (needToAddGraphicLoaderToMapHandler && getBeanContext() != null && loader != null) { - - getBeanContext().add(loader); - needToAddGraphicLoaderToMapHandler = false; - } - } - - /** - * Get the GraphicLoader loader. - */ - public GraphicLoader getGraphicLoader() { - return loader; - } - - /** - * Set whether to add the GraphicLoader, which is assumed to yet be added to the GraphicLoaderLayer, to the - * MapHandler. - */ - public void setAddGraphicLoaderToMapHandler(boolean val) { - addGraphicLoaderToMapHandler = val; - needToAddGraphicLoaderToMapHandler = val; - } - - public boolean getAddGraphicLoaderToMapHandler() { - return addGraphicLoaderToMapHandler; - } - - /** - * Method for BeanContextChild interface. Adds this object as a BeanContextMembership listener, set the BeanContext - * in this objects BeanContextSupport, and receives the initial list of objects currently contained in the - * BeanContext. - */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - super.setBeanContext(in_bc); - - if (in_bc != null && needToAddGraphicLoaderToMapHandler && getGraphicLoader() != null) { - in_bc.add(getGraphicLoader()); - needToAddGraphicLoaderToMapHandler = false; - } - } - - /** - * PropertyConsumer interface method. - * - * @see com.bbn.openmap.PropertyConsumer - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String glString = props.getProperty(realPrefix + GraphicLoaderProperty); - addGraphicLoaderToMapHandler = PropUtils.booleanFromProperties(props, realPrefix - + AddGraphicLoaderToMapHandlerProperty, addGraphicLoaderToMapHandler); - - if (glString != null) { - GraphicLoader gl = (GraphicLoader) ComponentFactory.create(glString, prefix, props); - if (gl != null) { - needToAddGraphicLoaderToMapHandler = addGraphicLoaderToMapHandler; - setGraphicLoader(gl); - } - } - } - - /** - * PropertyConsumer interface method. - * - * @see com.bbn.openmap.PropertyConsumer - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - GraphicLoader gl = getGraphicLoader(); - - if (gl != null) { - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.setProperty(prefix + GraphicLoaderProperty, gl.getClass().getName()); - if (gl instanceof PropertyConsumer) { - ((PropertyConsumer) gl).getProperties(props); - } - } - return props; - } - - /** - * PropertyConsumer interface method. - * - * @see com.bbn.openmap.PropertyConsumer - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - props.setProperty(GraphicLoaderProperty, "Classname of GraphicLoader"); - - GraphicLoader gl = getGraphicLoader(); - if (gl instanceof PropertyConsumer) { - ((PropertyConsumer) gl).getPropertyInfo(props); - } - - return props; - } - - /** - * Standard PlugIn method to provide palette. Differed to the GraphicLoader. - */ - public Component getGUI() { - if (loader != null) { - return loader.getGUI(); - } else { - return null; - } - } - - /** - * Some GraphicLoaders want mouse events, this allows them to set the MapMouseListener provided by the layer, - * redirecting MouseEvents to the GraphicLoader instead of the MapMouseInterpreter. - * - * @param mml the MapMouseListener to receive events. - */ - public void setMapMouseListener(MapMouseListener mml) { - mapMouseListener = mml; - } - - /** - * If the MapMouseListener has been set by a GraphicLoader, it is returned here to the MouseDelegator. Otherwise, - * this layer acts like any other OMGraphicHandlerLayer and returns the MapMouseInterpreter. - */ - public MapMouseListener getMapMouseListener() { - if (mapMouseListener != null) { - return mapMouseListener; - } else { - return super.getMapMouseListener(); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/package.html b/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/package.html deleted file mode 100644 index 170ab7e4c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/graphicLoader/package.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - The GraphicLoader package is designed to provide support for - GraphicLoaders, which in turn are objects that need to drive changes in - OMGraphics over a map. The GraphicLoader is an object that manages - OMGraphics and their positions, and sends an OMGraphicList to its - receiver when they need to be updated.

- - The package consists of a GraphicLoaderLayer, which is a layer that accepts - graphics from another object, called the GraphicLoader. The GraphicLoader - is an object with a timer that manages these location objects. The - GraphicLoaderConnector is an object that should be added to the - MapHander - when it finds a GraphicLoader in the MapHandler, it will - automatically create a GraphicLoaderLayer for it, and - will give it to the LayerHandler if it - knows about one, or give the GraphicLoaderLayer to the MapHandler so - it can be found by the LayerHandler later.

- - To add a GraphicLoader to the OpenMap application, you can do it - several ways: -

    -
  • You can create a specific GraphicLoaderLayer that creates its - own GraphicLoader, and initializes it accordingly. You would add - the GraphicLoaderLayer to the openmap.layers property in the - openmap.properties file. -
  • You can create a GraphicLoaderLayer by adding an entry to the - openmap.layer property in the openmap.properties file, and define - what kind of GraphicLoader to create in the properties for the - GraphicLoaderLayer. -
  • You can add a - com.bbn.openmap.layer.graphicLoader.GraphicLoaderConnector to the - openmap.components property, and then add the GraphicLoader to the - openmap.components property as well. The GraphicLoaderConnector - will find the GraphicLoader, and create a - GraphicLoaderLayer for the GraphicLoader and add it to - the LayerHandler on top of the map. -
- diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/CSVTiledImageLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/CSVTiledImageLayer.java deleted file mode 100644 index 952100db9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/CSVTiledImageLayer.java +++ /dev/null @@ -1,398 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/plugin/CSVTiledImagePlugIn.java,v $ -// $RCSfile: CSVTiledImagePlugIn.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/01/13 21:05:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.image; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.Vector; - -import javax.imageio.ImageIO; -import javax.imageio.stream.FileCacheImageInputStream; - -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The CSVTiledImageLayer can be used to load image files for background use. - * The images are automatically scaled to fit the projection. The actual - * accuracy of matching the scaled images to the map depends on the projection - * of the images, and the projection type being used for the map. At larger - * scales, the error may not be noticeable. - *

- * - * This Layer uses a csv file to find out about the images that should be - * loaded. The layer assumes that the csv file has these fields, in this order: - * - *

- * 
- *   Upper Latitude, Western Longitude, Lower Latitude, Eastern Longitude, URL of image
- *   42,-73.5,40,-72,file:///data/images/test1.jpg
- *   40,-73.5,38,-72,file:///data/images/test2.jpg
- * 
- * 
- * - * Make sure there are not spaces in the data portion of the file! - *

- * The properties for the layer look like this: - * - *

- * 
- *   layer.class=com.bbn.openmap.layer.image.CSVTiledImageLayer
- *   layer.prettyName=Name of Layer
- *   # URL of the data file
- *   layer.tileFile=URL of csv file
- *   # If the csv file has descriptive header line that should not be used for images. (default = true)
- *   layer.fileHasHeader=true
- * 
- * 
- * - * The layer doesn't do anything fancy with image caching. The layer loads all - * of the images when the layer is turned on. You might have to bump up the heap - * size of the JVM when loading large or many images. - *

- * - * This class was inspired by, and created from parts of the ImageLayer - * submission from Adrian Lumsden@sss, on 25-Jan-2002. Use the MediaTracker code - * from that class. Update: The MediaTracker has been replaced by ImageIO - * components in OpenMap 4.6.3. - */ -public class CSVTiledImageLayer extends OMGraphicHandlerLayer { - /** - * The set of tiles. - */ - protected HashSet tiles = new HashSet(); - protected boolean DEBUG = false; - /** The property for the data file - tileFile. */ - public final static String CSVFileNameProperty = "tileFile"; - /** - * The property for whether the data file has a descriptive header on the - * first line, to let the reader know to ignore that line - fileHasHeader. - * Default is true. - */ - public final static String FileHasHeaderProperty = "fileHasHeader"; - - protected String tileFileName = null; - protected boolean fileHasHeader = true; - protected CSVFile tilefile = null; - - /** - * Index of column for upper latitude of image in the csv file. Default 0. - */ - public int ullatIndex = 0; - /** - * Index of column for western longitude of image in the csv file. Default - * 1. - */ - public int ullonIndex = 1; - /** - * Index of column for lower latitude of image in the csv file. Default 2. - */ - public int lrlatIndex = 2; - /** - * Index of column for eastern longitude of image in the csv file. Default - * 3. - */ - public int lrlonIndex = 3; - /** - * Index of column for URL of image file in the csv file. Default 4. - */ - public int urlIndex = 4; - - /** - * Default constructor. - */ - public CSVTiledImageLayer() { - DEBUG = Debug.debugging("tiledimage"); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - } - - /** - * The prepare method is called when the projection change. - * - * @return OMGraphicList to be painted for the current projection. - */ - public OMGraphicList prepare() { - - OMGraphicList list = new OMGraphicList(); - Projection p = getProjection(); - if (DEBUG) { - Debug.output("CSVTIPI: getRectangle"); - } - - if (tilefile == null) { - loadTiles(tileFileName); - } - - // doesn't matter if loadDataFile fails or not, the iterator - // will be empty if it is. - - // Now, add the tiles that are on the screen. - Iterator it = tiles.iterator(); - while (it.hasNext()) { - - OMScalingRaster tile = (OMScalingRaster) it.next(); - - if (tile.isOnMap(p)) { - if (DEBUG) { - Debug.output("CSVTIPI: image on map"); - } - tile.generate(p); - list.add(tile); - } else if (DEBUG) { - Debug.output("CSVTIPI: image not on map, skipping"); - } - } - - return list; - } // end getRectangle - - /** - * PropertyConsumer method, setting the layer with properties that apply to - * it. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - tileFileName = props.getProperty(realPrefix + CSVFileNameProperty); - - if (DEBUG) { - Debug.output("CSVTIPI: file: " + tileFileName); - } - - fileHasHeader = PropUtils.booleanFromProperties(props, realPrefix + FileHasHeaderProperty, fileHasHeader); - - if (DEBUG) { - Debug.output("CSVTIPI: file has header: " + fileHasHeader); - } - } - - /** - * Takes the URL to a csv file and parses it into OMScaledRasters, adding - * them to the tiles HashSet. - */ - protected void loadTiles(String csvFileName) { - int imageCount = 0; - - if (csvFileName != null) { - try { - tilefile = new CSVFile(csvFileName); - tilefile.setHeadersExist(fileHasHeader); - tilefile.loadData(false); - // MediaTracker tracker = new MediaTracker(component); // Create - // a media tracker - - Iterator records = tilefile.iterator(); - while (records.hasNext()) { - Vector record = (Vector) records.next(); - - if (DEBUG) { - Debug.output("CSVTIPI: record: " + record); - } - - String imageURLString = null; - - try { - - float ullat = ((Double) record.get(ullatIndex)).floatValue(); - float ullon = ((Double) record.get(ullonIndex)).floatValue(); - float lrlat = ((Double) record.get(lrlatIndex)).floatValue(); - float lrlon = ((Double) record.get(lrlonIndex)).floatValue(); - imageURLString = (String) record.get(urlIndex); - - URL imageURL = PropUtils.getResourceOrFileOrURL(imageURLString); - - FileCacheImageInputStream fciis = new FileCacheImageInputStream(imageURL.openStream(), null); - BufferedImage fileImage = ImageIO.read(fciis); - - // ImageIcon ii = new ImageIcon(imageURL); - // Image fileImage = ii.getImage(); - - // try { - // tracker.addImage(fileImage, imageCount); - // tracker.waitForID(imageCount); - // } catch (Exception e) { - // if (Debug.debugging("csvtiledimage")) { - // e.printStackTrace(); - // } - // } // Catch errors - - OMScalingRaster omsr = new OMScalingRaster(ullat, ullon, lrlat, lrlon, fileImage); - tiles.add(omsr); - imageCount++; - - } catch (MalformedURLException innerMurle) { - Debug.error("CSVTiledImageLayer: image tile path not valid: " - + imageURLString + ", skipping..."); - } catch (ArrayIndexOutOfBoundsException aioobe) { - Debug.error("CSVTiledImageLayer: having trouble reading line (" - + imageCount + "), skipping...\n" + aioobe.getMessage()); - } catch (IOException ioe) { - Debug.error("CSVTiledImageLayer: having trouble reading line (" - + imageCount + "), skipping...\n" + ioe.getMessage()); - } - } - - } catch (MalformedURLException murle) { - Debug.error("CSVTiledImageLayer: CSV tile file not valid: " + csvFileName); - } - } - } - - /** - * Method to fill in a Properties object, reflecting the current values of - * the PropertyConsumer. If the PropertyConsumer has a prefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param getList a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new Properties - * object should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - getList.put(prefix + CSVFileNameProperty, PropUtils.unnull(tileFileName)); - getList.put(prefix + FileHasHeaderProperty, new Boolean(fileHasHeader).toString()); - - return getList; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(CSVFileNameProperty, "URL to CSV data file"); - list.put(FileHasHeaderProperty, "Flag to note if CSV file has descriptive header line"); - list.put(FileHasHeaderProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return list; - } - - public boolean isFileHasHeader() { - return fileHasHeader; - } - - public void setFileHasHeader(boolean fileHasHeader) { - this.fileHasHeader = fileHasHeader; - } - - public int getLrlatIndex() { - return lrlatIndex; - } - - public void setLrlatIndex(int lrlatIndex) { - this.lrlatIndex = lrlatIndex; - } - - public int getLrlonIndex() { - return lrlonIndex; - } - - public void setLrlonIndex(int lrlonIndex) { - this.lrlonIndex = lrlonIndex; - } - - public CSVFile getTilefile() { - return tilefile; - } - - public void setTilefile(CSVFile tilefile) { - this.tilefile = tilefile; - } - - public String getTileFileName() { - return tileFileName; - } - - public void setTileFileName(String tileFileName) { - this.tileFileName = tileFileName; - } - - public HashSet getTiles() { - return tiles; - } - - public void setTiles(HashSet tiles) { - this.tiles = tiles; - } - - public int getUllatIndex() { - return ullatIndex; - } - - public void setUllatIndex(int ullatIndex) { - this.ullatIndex = ullatIndex; - } - - public int getUllonIndex() { - return ullonIndex; - } - - public void setUllonIndex(int ullonIndex) { - this.ullonIndex = ullonIndex; - } - - public int getUrlIndex() { - return urlIndex; - } - - public void setUrlIndex(int urlIndex) { - this.urlIndex = urlIndex; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/EarthImageLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/EarthImageLayer.java deleted file mode 100644 index f038d0702..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/EarthImageLayer.java +++ /dev/null @@ -1,360 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/image/EarthImageLayer.java,v $ -// $RCSfile: EarthImageLayer.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.image; - -import java.awt.Image; -import java.awt.Point; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.awt.image.PixelGrabber; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.image.ImageServerConstants; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * This class takes an image of the earth, and creates a background image from - * it that matches an OpenMap projection. It currently assumes that the - * degrees/pixel ratios are constant in both directions, the coordinate system - * origins in both directions are at the center of the picture, and that the - * left an right edges of the images are at -180/180 degrees longitude, and that - * the top and bottom of the edges are at 90/-90 degrees latitude. I think the - * code will work for images that do not cover the entire earth in this manner, - * as long as the degree/pixel ratios are the same, but the ImageTranslator - * limits would have to be adjusted to fit the source image. - * - *

- * #For the layer 
- * layer.class=com.bbn.openmap.layer.image.EarthImageLayer
- * layer.prettyName=Whatever
- * layer.image=path to file, URL or resource.
- * 
- */ -public class EarthImageLayer extends OMGraphicHandlerLayer implements ImageServerConstants { - - protected BufferedImage bi = null; - protected ImageTranslator it = null; - public final static String ImageProperty = "image"; - protected String imageString = null; - - public EarthImageLayer() { - } - - /** - * @return an OMGraphicList containing an OMRaster with the image to be - * displayed. - */ - public OMGraphicList prepare() { - OMGraphicList list = new OMGraphicList(); - Projection p = getProjection(); - - // The first time through with a good bi, the it will be - // created later. This routine will only be executed if the - // image icon is no good. - if (bi == null && it == null) { - return list; - } - - OMRaster ras = null; - - if (it == null) { - it = new ImageTranslator(bi); - bi = null; // don't hold onto it. - } - - ras = it.getImage(p); - - if (ras != null) { - ras.generate(p); - list.add(ras); - } - - return list; - } - - /** - * Method to set the properties in the PropertyConsumer. The prefix is a - * string that should be prepended to each property key (in addition to a - * separating '.') in order for the PropertyConsumer to uniquely identify - * properties meant for it, in the midst of of Properties meant for several - * objects. - * - * @param prefix a String used by the PropertyConsumer to prepend to each - * property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix had already - * been set, then the prefix passed in should replace that previous - * value. - * @param setList a Properties object that the PropertyConsumer can use to - * retrieve expected properties it can use for configuration. - */ - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - imageString = setList.getProperty(realPrefix + ImageProperty); - - if (imageString == null || imageString.length() == 0) { - Debug.error("EarthImageLayer needs an image."); - Debug.output(setList.toString()); - return; - } else if (Debug.debugging("earthimage")) { - Debug.output("EarthImageLayer: fetching " + realPrefix + ImageProperty + " : " - + imageString); - } - try { - URL url = PropUtils.getResourceOrFileOrURL(this, imageString); - bi = BufferedImageHelper.getBufferedImage(url, 0, 0, -1, -1); - - if (Debug.debugging("earthimage") && bi != null) { - Debug.output("EarthImageLayer: buffered image OK"); - } - } catch (MalformedURLException murle) { - Debug.error("EarthImageLayer: image path is not good: " + imageString); - } catch (InterruptedException ie) { - Debug.error("EarthImageLayer: problem reading image from path: " + imageString); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ImageProperty, (imageString == null ? "" : imageString)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - props.put(ImageProperty, "Path to image file (URL, resource or file)"); - props.put(ImageProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - props.put(initPropertiesProperty, ImageProperty); - - return props; - } - - /** - * The ImageTranslator is the object that takes the BufferedImage and - * creates the OMRaster from it based on a Projection object. - */ - public class ImageTranslator { - - protected int[] pixels = null; - - /** Image Icon width, */ - public int iwidth; - /** Image Icon height, */ - public int iheight; - /** - * Horizontal degrees/pixel in the source BufferedImage. Assumed to be - * constant across the image. - */ - public float hor_dpp; - /** - * Vertical degrees/pixel in the source BufferedImage. Assumed to be - * constant across the image. - */ - public float ver_dpp; - /** - * The vertical origin pixel location in the source image for the - * coordinate system origin (0 degrees latitude). - */ - public int verOrigin; - /** - * The horizontal origin pixel location in the source image for the - * coordinate system origin (0 degrees longitude). - */ - public int horOrigin; - - /** - * Create an image translator for an image assumed to be world wide - * coverage, with the top at 90 degrees, the bottom at -90, the left - * side at -180 and the right side at 180. Assumes the origin point is - * in the middle of the image. - */ - public ImageTranslator(BufferedImage bi) { - if (bi != null) { - iwidth = bi.getWidth(); - iheight = bi.getHeight(); - - verOrigin = iheight / 2; - horOrigin = iwidth / 2; - - hor_dpp = 360f / (float) iwidth; - ver_dpp = 180f / (float) iheight; - - if (Debug.debugging("earthimage")) { - Debug.output("ImageTranslator: getting image pixels w:" + iwidth + ", h:" - + iheight + "\n hor dpp:" + hor_dpp + ", ver dpp:" + ver_dpp); - } - - pixels = getPixels(bi, 0, 0, iwidth, iheight); - - // See if this saves on memory. Seems to. - bi = null; - } - } - - /** - * The pixels used in the OMRaster. - */ - int[] tmpPixels = new int[0]; - - /** - * Given a projection, create an OMRaster that reflects the image warped - * to that projection. - */ - public OMRaster getImage(Projection p) { - if (pixels != null && p != null) { - int projHeight = p.getHeight(); - int projWidth = p.getWidth(); - - // See if we can reuse the pixel array we have. - if (tmpPixels.length != projWidth * projHeight) { - tmpPixels = new int[projWidth * projHeight]; - } - - // ///////////////////////////////// - // For Testing... - // LatLonPoint ul = p.getUpperLeft(); - // LatLonPoint lr = p.getLowerRight(); - - // int ulhorIndex = horOrigin + - // (int)(ul.getLongitude()/hor_dpp); - // int ulverIndex = verOrigin - - // (int)(ul.getLatitude()/ver_dpp); - - // int lrhorIndex = horOrigin + - // (int)(lr.getLongitude()/hor_dpp); - // int lrverIndex = verOrigin - - // (int)(lr.getLatitude()/ver_dpp); - - // Debug.output("The image file will be referenced - // from:\n " + - // ulhorIndex + ", " + ulverIndex + "\n " + - // lrhorIndex + ", " + lrverIndex); - // ///////////////////////////////// - - int clear = 0x00000000; - - Point ctp = new Point(); - LatLonPoint llp = new LatLonPoint.Double(); - LatLonPoint center = p.getCenter(new LatLonPoint.Double()); - - for (int i = 0; i < projWidth; i++) { - for (int j = 0; j < projHeight; j++) { - p.inverse(i, j, llp); - - // index into the OMRaster pixel array - int tmpIndex = i + (j * projWidth); - - // If the llp calculated isn't on the map, - // don't bother drawing it. Could be a space - // point in Orthographic projection, for - // instance. - if (llp.equals(center) - || !((GeoProj) p).isPlotable(llp.getLatitude(), llp.getLongitude())) { - p.forward(llp, ctp); - if (ctp.x != i || ctp.y != j) { - tmpPixels[tmpIndex] = clear; - continue; - } - } - - // Find the corresponding pixel location in - // the source image. - int horIndex = horOrigin + (int) (llp.getLongitude() / hor_dpp); - int verIndex = verOrigin - (int) (llp.getLatitude() / ver_dpp); - - if (horIndex < 0 || horIndex >= iwidth || verIndex <= 0 - || verIndex >= iheight) { - /** - * If the verIndex is 0, that means it's at 90N, - * which is kind of an abstract thing. So lets make - * it clear. Literally. - */ - - // pixel not on the source image. This - // happens if the image doesn't cover the - // entire earth. - continue; - } - - int imageIndex = horIndex + (verIndex * iwidth); - - if (imageIndex >= 0 && imageIndex < pixels.length) { - tmpPixels[tmpIndex] = pixels[imageIndex]; - // } else { - // Debug.message("earthimage", - // "ImageTranslator: outside pixel - // range"); - } - } - } - - Debug.message("earthimage", "ImageTranslator: finished creating image"); - return new OMRaster(0, 0, projWidth, projHeight, tmpPixels); - } else { - Debug.message("earthimage", "ImageTranslator: problem creating image"); - } - - // If you get here, something's not right. - return null; - } - - /** - * Get the pixels from the BufferedImage. If anything goes wrong, - * returns a int[0]. - */ - protected int[] getPixels(Image img, int x, int y, int w, int h) { - int[] pixels = new int[w * h]; - PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w); - try { - pg.grabPixels(); - } catch (InterruptedException e) { - Debug.error("ImageTranslator: interrupted waiting for pixels!"); - return new int[0]; - } - - if ((pg.getStatus() & ImageObserver.ABORT) != 0) { - System.err.println("ImageTranslator: image fetch aborted or errored"); - return new int[0]; - } - - return pixels; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/ImageTileLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/ImageTileLayer.java deleted file mode 100644 index 3c63130d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/ImageTileLayer.java +++ /dev/null @@ -1,1358 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ImageTileLayer.java,v $ -//$Revision: 1.4 $ -//$Date: 2009/01/21 01:24:42 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.image; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Polygon; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.DefaultListModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JToggleButton; -import javax.swing.ListCellRenderer; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.filechooser.FileFilter; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.dataAccess.image.ErrImageTile; -import com.bbn.openmap.dataAccess.image.ImageReader; -import com.bbn.openmap.dataAccess.image.ImageReaderLoader; -import com.bbn.openmap.dataAccess.image.ImageTile; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.gui.LayerControlButtonPanel; -import com.bbn.openmap.gui.LayersPanel; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.tools.icon.BasicIconPart; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.IconPartList; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The ImageTileLayer is a layer that manages geo-referenced images over a map. - * The layer uses ImageReaders to figure out how to load images from a file, - * create an ImageTile object from the image data, and deduce where the - * ImageTile should be located from the information provided with/in the image - * data. - *

- * - * ImageReaderLoader objects are held by the layer to assist in finding the - * appropriate ImageReader for an image file. - *

- * - * The properties for this layer are: - * - *

- * # semi-colon separated paths to image files or directories containing images
- * imageTileLayer.imageFilePath=path/to/file1;path/to/directory;path/to/file2
- *                        
- * # optional - image cache size specifies how many images will be held in memory for fast retrieval.
- * imageTileLayer.imageCacheSize=20
- *                         
- * # optional - image cutoff ratio specifies the scale that images will not load when the projection is zoomed out from it.
- * imageTileLayer.imageCutoffRatio=5
- *                     
- * # optional - image Reader loaders specify which image files are handled
- * imageTileLayer.imageReaderLoaders=geotiff
- * imageTileLayer.geotiff=com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFImageReaderLoader
- *                       
- * # optional - Drawing attributes properties for image highlighting
- * imageTileLayer.lineWidth=2
- * imageTileLayer.selectColor=FFFFFF00
- * 
- * - * @author dietrick - * - */ -public class ImageTileLayer extends OMGraphicHandlerLayer { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.imageTile.ImageTileLayer"); - - public final static String ImageFilePathProperty = "imageFilePath"; - public final static String ImageReaderLoadersProperty = "imageReaderLoaders"; - public final static String ImageCacheSizeProperty = "imageCacheSize"; - public final static String ImageCutoffRatioProperty = "imageCutoffRatio"; - - protected String SHOW_TILES_TITLE; - protected String HIDE_TILES_TITLE; - - protected List filePaths; - - protected List imageReaderLoaders; - - protected ImageTile.Cache imageCache; - - protected DrawingAttributes selectedDrawingAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Default constructor for layer, initializes tile cache. - * - */ - public ImageTileLayer() { - - configureImageReaderLoaders(); - imageCache = new ImageTile.Cache(); - - SHOW_TILES_TITLE = i18n.get(ImageTileLayer.class, "showTilesButton", "Show"); - HIDE_TILES_TITLE = i18n.get(ImageTileLayer.class, "hideTilesButton", "Hide"); - } - - /** - * PropertyConsumer interface method. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - selectedDrawingAttributes.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - filePaths = PropUtils.parseMarkers(props.getProperty(prefix + ImageFilePathProperty), ";"); - - imageCache.resetCache( - PropUtils.intFromProperties(props, prefix + ImageCacheSizeProperty, imageCache.getCacheSize())); - - imageCache.setCutoffScaleRatio(PropUtils.floatFromProperties(props, prefix + ImageCutoffRatioProperty, - imageCache.getCutoffScaleRatio())); - - String imageReaderLoaderString = props.getProperty(prefix + ImageReaderLoadersProperty); - - if (imageReaderLoaders == null) { - imageReaderLoaders = new Vector(); - } - - if (imageReaderLoaderString != null) { - imageReaderLoaders.clear(); - List idls = PropUtils.parseSpacedMarkers(imageReaderLoaderString); - for (String idlMarkerName : idls) { - String idlClassName = props.getProperty(prefix + idlMarkerName); - - Object obj = ComponentFactory.create(idlClassName); - if (obj instanceof ImageReaderLoader) { - imageReaderLoaders.add((ImageReaderLoader) obj); - } - } - } - } - - /** - * Internal callback method for subclasses to use to be able to configure - * imageReaderLoader Vector with specific ImageReaderLoaders. By default, loads - * GeoTIFFImageReader.Loader. - */ - protected void configureImageReaderLoaders() { - imageReaderLoaders = new Vector(); - - ImageReaderLoader idl = (ImageReaderLoader) ComponentFactory - .create("com.bbn.openmap.dataAccess.image.geotiff.GeoTIFFImageReaderLoader"); - - if (idl != null) { - imageReaderLoaders.add(idl); - } else { - logger.warning("ImageTileLayer needs JAI installed in order to use GeoTIFF Image Reader."); - } - - idl = (ImageReaderLoader) ComponentFactory - .create("com.bbn.openmap.dataAccess.image.WorldFileImageReaderLoader"); - if (idl != null) { - imageReaderLoaders.add(idl); - } else { - logger.warning("ImageTileLayer needs JAI installed in order to use World File Image Reader."); - } - } - - /** - * PropertyConsumer interface method. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - selectedDrawingAttributes.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - OMGraphicList list = getList(); - if (list != null) { - StringBuffer buf = new StringBuffer(); - for (OMGraphic omg : list) { - if (buf.length() > 0) { - buf.append(";"); - } - - ImageTile imageTile = (ImageTile) omg; - String filePath = (String) imageTile.getAttribute(FILE_PATH_ATTRIBUTE); - if (filePath != null) { - buf.append(filePath); - } - } - props.put(prefix + ImageFilePathProperty, buf.toString()); - } - - if (imageReaderLoaders != null) { - int count = 0; - StringBuffer sbuf = null; - for (ImageReaderLoader idl : imageReaderLoaders) { - props.put(prefix + "idl" + count, idl.getClass().getName()); - - if (sbuf == null) { - sbuf = new StringBuffer("idl").append(count); - } else { - // Space separated for parsing on input - sbuf.append(" idl").append(count); - } - } - - if (sbuf != null) { - props.put(prefix + ImageReaderLoadersProperty, sbuf.toString()); - } - } - - props.put(prefix + ImageCacheSizeProperty, Integer.toString(imageCache.getCacheSize())); - props.put(prefix + ImageCutoffRatioProperty, Float.toString(imageCache.getCutoffScaleRatio())); - - return props; - } - - /** - * PropertyConsumer interface method. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - selectedDrawingAttributes.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, props, ImageTileLayer.class, ImageFilePathProperty, "Images", - "A list of images or directories to display (separated by ;).", - "com.bbn.openmap.util.propertyEditor.MultiDirFilePropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, props, ImageTileLayer.class, ImageCacheSizeProperty, "Cache Size", - "Number of images to keep in cache.", null); - - PropUtils.setI18NPropertyInfo(i18n, props, ImageTileLayer.class, ImageCutoffRatioProperty, "Cutoff Scale", - "Projection scale where larger values won't cause images to be loaded and displayed.", null); - - String dummyMarker = PropUtils.getDummyMarkerForPropertyInfo(getPropertyPrefix(), null); - - PropUtils.setI18NPropertyInfo(i18n, props, ImageTileLayer.class, dummyMarker, "Highlight Settings", - "Settings for annotations on highlighted images.", - "com.bbn.openmap.omGraphics.DrawingAttributesPropertyEditor"); - - props.put(initPropertiesProperty, ImageFilePathProperty + " " + ImageCacheSizeProperty + " " - + ImageCutoffRatioProperty + " " + dummyMarker); - return props; - } - - /** - * OMGraphicHandlerLayer method called when projection changes or when - * doPrepare() is called. If the internal OMGraphicList is null the image file - * paths will be used to read image files. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList list = getList(); - - if (list == null) { - list = new OMGraphicList(); - setList(list); - Thread loadThread = new Thread() { - public void run() { - loadImages(); - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - }; - loadThread.start(); - } else { - list.generate(getProjection()); - } - - return list; - } - - /** - * Gets the filePaths and loads the images found in those places. Should be - * called in a non-AWT thread. - * - * @return OMGraphicList retrieved from getList(), or a new list of that list is - * null. - */ - protected OMGraphicList loadImages() { - clearImageTileList(); - - OMGraphicList ret = getList(); - - if (ret == null) { - ret = new OMGraphicList(); - setList(ret); - } else { - ret.clear(); - } - - if (filePaths != null) { - for (String path : filePaths) { - loadImage(path, ret); - } - } - return ret; - } - - /** - * If filePath is a file, the ImageReaderLoaders are used to try to load and - * place the image. If filePath is a directory, this method is called for each - * file contained within. ImageTile objects are created from the image files. - * - * @param filePath - * @param ret The OMGraphicList to add any ImageTiles to. - */ - protected void loadImage(String filePath, OMGraphicList ret) { - - File file = new File(filePath); - if (file.exists() && file.isDirectory()) { - String[] files = file.list(); - for (int i = 0; i < files.length; i++) { - loadImage(filePath + "/" + files[i], ret); - } - } else { - - fireStatusUpdate(LayerStatusEvent.START_WORKING); - - try { - URL fileURL = PropUtils.getResourceOrFileOrURL(filePath); - if (fileURL != null) { - if (imageReaderLoaders != null) { - ImageTile imageTile = null; - for (ImageReaderLoader idl : imageReaderLoaders) { - if (idl.isLoadable(filePath)) { - ImageReader id = idl.getImageReader(fileURL); - ImageTile tmpImageTile = id.getImageTile(imageCache); - - if (imageTile == null) { - imageTile = tmpImageTile; - } else if (tmpImageTile != null && imageTile instanceof ErrImageTile) { - imageTile = tmpImageTile; - } - - if (imageTile != null && !(imageTile instanceof ErrImageTile)) { - break; - } - } - } - - // Need to check for null in case none of the - // ImageReaders could handle the file. - if (imageTile != null) { - addImageToLists(imageTile, ret, fileURL); - } - - } else { - logger.warning("ImageReaders not configured in " + getName() + " ImageTileLayer."); - } - } else { - logger.warning("Can't get URL from " + filePath); - } - - } catch (MalformedURLException murle) { - } - } - } - - /** - * A method to handle a newly created ImageTile object from the loadImage - * method. - * - * @param imageTile The new ImageTile - * @param ret An OMGraphicList to add the ImageTile to. - * @param fileURL A URL describing the location of the source image file. - */ - protected void addImageToLists(ImageTile imageTile, OMGraphicList ret, URL fileURL) { - imageTile.generate(getProjection()); - ret.add(imageTile); - addImageTileToList(imageTile); - - imageTile.putAttribute(FILE_PATH_ATTRIBUTE, fileURL.getPath()); - // Probably need to check for the last slash - // and grab that part. - imageTile.putAttribute(NAME_ATTRIBUTE, fileURL.getFile()); - - selectedDrawingAttributes.setTo(imageTile); - - // Let's just assume that we're working with - // the main list here at the top level, and we - // can paint the images we have. - repaint(); - if (resultsList != null) { - resultsList.repaint(); - } - } - - public final static String NAME_ATTRIBUTE = "NAME"; - public final static String FILE_PATH_ATTRIBUTE = "FILE_PATH"; - - protected JPanel itPanel; - protected JList resultsList; - protected DefaultListModel listModel; - protected ListManager listManager; - - JButton showHideButton; - JButton gotoButton; - JToggleButton locateButton; - - ImageControlButtonPanel icbp; - - /** - * Gets the gui controls associated with the layer. - * - * @return IPanel for layer controls. - */ - public Component getGUI() { - if (itPanel == null) { - itPanel = new JPanel(); - GridBagConstraints c = new GridBagConstraints(); - GridBagLayout gridbag = new GridBagLayout(); - itPanel.setLayout(gridbag); - - icbp = new ImageControlButtonPanel(); - gridbag.setConstraints(icbp, c); - - itPanel.add(icbp); - - resultsList = new JList<>(getListModel()); - resultsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - listManager = new ListManager(); - resultsList.addListSelectionListener(listManager); - resultsList.addMouseListener(listManager); - resultsList.addMouseMotionListener(listManager); - resultsList.setCellRenderer(new ImageListCellRenderer()); - - JScrollPane listScrollPane = new JScrollPane(resultsList); - listScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - listScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - c.fill = GridBagConstraints.BOTH; - c.weightx = 1.0f; - c.weighty = 1.0f; - c.insets = new Insets(5, 5, 5, 5); - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(listScrollPane, c); - itPanel.add(listScrollPane); - - JPanel buttonPanel = new JPanel(); - GridBagLayout bGridbag = new GridBagLayout(); - GridBagConstraints bc = new GridBagConstraints(); - - showHideButton = new JButton(HIDE_TILES_TITLE); - showHideButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - showHideTiles(((JButton) ae.getSource()).getText(), getSelectedTiles()); - } - }); - bGridbag.setConstraints(showHideButton, bc); - buttonPanel.add(showHideButton); - - gotoButton = new JButton(i18n.get(ImageTileLayer.class, "gotoButton", "Go To")); - gotoButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - goTo(getSelectedTiles()); - } - }); - bGridbag.setConstraints(gotoButton, bc); - buttonPanel.add(gotoButton); - - locateButton = new JToggleButton(i18n.get(ImageTileLayer.class, "locateButton", "Highlight")); - locateButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JToggleButton jtb = (JToggleButton) ae.getSource(); - setSelection(getSelectedTiles(), jtb.isSelected()); - } - }); - bGridbag.setConstraints(locateButton, bc); - buttonPanel.add(locateButton); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.weighty = 0f; - c.insets = new Insets(0, 5, 5, 5); - gridbag.setConstraints(buttonPanel, c); - itPanel.add(buttonPanel); - - setGUIButtonEnableState(false); - } - - return itPanel; - } - - /** - * A modified LayerControlButtonPanel that is used to control which image files - * are available and their display order relative to each other on the image - * stack. - * - * @author dietrick - */ - class ImageControlButtonPanel extends LayerControlButtonPanel { - - private static final long serialVersionUID = 1L; - - public ImageControlButtonPanel() { - super(); - - add = new JButton(addgif); - add.setActionCommand(LayersPanel.LayerAddCmd); - add.setToolTipText(i18n.get(ImageTileLayer.class, "addImage", I18n.TOOLTIP, "Add images(s)")); - add.addActionListener(ImageControlButtonPanel.this); - add(add); - - // Fix the tooltips: - delete.setToolTipText(i18n.get(ImageTileLayer.class, "deleteImage", I18n.TOOLTIP, "Remove image(s)")); - delete.setEnabled(true); - top.setToolTipText( - i18n.get(ImageTileLayer.class, "moveImageToTop", I18n.TOOLTIP, "Move selected image(s) to top")); - up.setToolTipText(i18n.get(ImageTileLayer.class, "moveImageUp", I18n.TOOLTIP, "Move selected image(s) up")); - down.setToolTipText(i18n.get(ImageTileLayer.class, "moveImageDown", "Move selected image(s) down")); - bottom.setToolTipText(i18n.get(ImageTileLayer.class, "moveImageToBottom", I18n.TOOLTIP, - "Move selected image(s) to bottom")); - } - - public void actionPerformed(ActionEvent ae) { - String cmd = ae.getActionCommand(); - - if (cmd == LayersPanel.LayerAddCmd) { - addNewImagesWithFileChooser(); - } else if (cmd == LayersPanel.LayerRemoveCmd) { - removeImages(getSelectedTiles()); - } else if (cmd == LayersPanel.LayerDownCmd) { - moveOneSlotToBottom(getSelectedTiles()); - ImageTileLayer.this.repaint(); - } else if (cmd == LayersPanel.LayerBottomCmd) { - moveToBottom(getSelectedTiles()); - ImageTileLayer.this.repaint(); - } else if (cmd == LayersPanel.LayerTopCmd) { - moveToTop(getSelectedTiles()); - ImageTileLayer.this.repaint(); - } else if (cmd == LayersPanel.LayerUpCmd) { - moveOneSlotToTop(getSelectedTiles()); - ImageTileLayer.this.repaint(); - } - } - - public void setGUIButtonEnableState(boolean somethingSelected) { - delete.setEnabled(somethingSelected); - top.setEnabled(somethingSelected); - up.setEnabled(somethingSelected); - down.setEnabled(somethingSelected); - bottom.setEnabled(somethingSelected); - } - - public void setGUIDeleteButtonEnableState(boolean state) { - delete.setEnabled(state); - } - } - - /** - * Changes the visibility setting on all ImageTile objects. - * - * @param visible - */ - protected void setVisibilityOnAllTiles(boolean visible) { - OMGraphicList list = getList(); - if (list != null) { - list.setVisible(visible); - repaint(); - } - } - - /** - * Action method called when the show/hide button is pressed. - * - * @param text if SHOW_TILES_TITLE, tiles made visible. - * @param selectedTiles2 - */ - protected void showHideTiles(String text, ImageTile[] selectedTiles2) { - boolean isVisible = (SHOW_TILES_TITLE.equals(text)); - for (int i = 0; i < selectedTiles2.length; i++) { - selectedTiles2[i].setVisible(isVisible); - } - - checkShowHideStatus(); - repaint(); - if (resultsList != null) { - resultsList.repaint(); - } - } - - /** - * Move all the selected tiles down one space. - * - * @param selectedTiles2 - */ - protected void moveOneSlotToBottom(ImageTile[] selectedTiles2) { - OMGraphicList list = getList(); - if (list != null && selectedTiles != null && selectedTiles.length > 0) { - for (int i = selectedTiles2.length - 1; i >= 0; i--) { - ImageTile tile = selectedTiles2[i]; - list.moveIndexedOneToBottom(list.indexOf(tile)); - } - rebuildListModel(); - } - } - - /** - * Move all of the selected tiles to the bottom of the stack. - * - * @param selectedTiles2 - */ - protected void moveToBottom(ImageTile[] selectedTiles2) { - OMGraphicList list = getList(); - if (list != null && selectedTiles != null && selectedTiles.length > 0) { - for (int i = 0; i < selectedTiles2.length; i++) { - ImageTile tile = selectedTiles2[i]; - list.moveIndexedToBottom(list.indexOf(tile)); - } - rebuildListModel(); - } - } - - /** - * Move all of the selected tiles up one space. - * - * @param selectedTiles2 - */ - protected void moveOneSlotToTop(ImageTile[] selectedTiles2) { - OMGraphicList list = getList(); - if (list != null && selectedTiles != null && selectedTiles.length > 0) { - for (int i = 0; i < selectedTiles2.length; i++) { - ImageTile tile = selectedTiles2[i]; - list.moveIndexedOneToTop(list.indexOf(tile)); - } - rebuildListModel(); - } - } - - /** - * Move all of the selected tiles to the top of the stack. - * - * @param selectedTiles2 - */ - protected void moveToTop(ImageTile[] selectedTiles2) { - OMGraphicList list = getList(); - if (list != null && selectedTiles != null && selectedTiles.length > 0) { - for (int i = selectedTiles2.length - 1; i >= 0; i--) { - ImageTile tile = selectedTiles2[i]; - list.moveIndexedToTop(list.indexOf(tile)); - } - rebuildListModel(); - } - } - - /** - * MapBean is used to reset the projection of the map over the selected images. - */ - protected MapBean mapBean; - - /** - * Figure out where the images are and move the MapBean over them. - * - * @param selectedTiles2 - */ - protected void goTo(ImageTile[] selectedTiles2) { - if (mapBean == null) { - MapHandler bc = (MapHandler) getBeanContext(); - if (bc != null) { - mapBean = (MapBean) bc.get(com.bbn.openmap.MapBean.class); - } - } - - if (mapBean != null) { - if (selectedTiles != null && selectedTiles.length > 0) { - Rectangle2D rec = null; - for (int i = selectedTiles2.length - 1; i >= 0; i--) { - ImageTile tile = selectedTiles2[i]; - - if (rec == null) { - rec = new Rectangle2D.Double(tile.getLRLon(), tile.getLRLat(), 0f, 0f); - rec.add(tile.getULLon(), tile.getULLat()); - } else { - rec.add(tile.getULLon(), tile.getULLat()); - rec.add(tile.getLRLon(), tile.getLRLat()); - } - } - - if (rec != null) { - Point2D center = new Point2D.Double(rec.getCenterX(), rec.getCenterY()); - Point2D anchor1 = new Point2D.Double(rec.getMinX(), rec.getMaxY()); - Point2D anchor2 = new Point2D.Double(rec.getMaxX(), rec.getMinY()); - - Proj proj = (Proj) mapBean.getProjection(); - float scale = proj.getScale(anchor1, anchor2, proj.forward(anchor1), proj.forward(anchor2)); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Images cover " + anchor1 + " to " + anchor2 + ", scale adjusted to " + scale); - } - - proj.setCenter(center); - proj.setScale(scale); - mapBean.setProjection(proj); - } - } - } - } - - /** - * Note the provided tiles as being highlighted. Selection, in this case, means - * the OMGraphic selection. - * - * @param selectedTiles2 - */ - protected void select(ImageTile[] selectedTiles2) { - setSelection(selectedTiles2, true); - } - - /** - * Note the provided tiles as being highlighted or not. Selection, in this case, - * means the OMGraphic selection. - * - * @param selectedTiles2 - */ - protected void setSelection(ImageTile[] selectedTiles2, boolean isSelected) { - for (int i = 0; i < selectedTiles2.length; i++) { - selectedTiles2[i].setSelected(isSelected); - } - repaint(); - } - - /** - * Un-highlight all of the tiles. - */ - public void deselect() { - OMGraphicList list = getList(); - if (list != null) { - list.deselect(); - repaint(); - } - } - - /** - * Take the drawing attributes held by the layer and push the settings on all of - * the ImageTiles. - */ - public void resetSelectAttributes() { - OMGraphicList list = getList(); - if (list != null) { - for (OMGraphic omg : list) { - selectedDrawingAttributes.setTo(omg); - } - repaint(); - } - } - - /** - * Remove the selected tiles from the image stack. Asks the user for - * confirmation. - * - * @param selectedTiles2 - */ - protected void removeImages(ImageTile[] selectedTiles2) { - ImageTile[] selectedTiles = getSelectedTiles(); - if (selectedTiles != null && selectedTiles.length > 0) { - String confirmStringMulti = i18n.get(ImageTileLayer.class, "removeConfirmMultiple", - "Are you sure you want to remove these images from the layer?"); - String confirmStringSolo = i18n.get(ImageTileLayer.class, "removeConfirmSolo", - "Are you sure you want to remove this image from the layer?"); - String confirmTitleString = i18n.get(ImageTileLayer.class, "removeConfirmTitle", "Remove Images?"); - int answer = JOptionPane.showConfirmDialog(this, - (selectedTiles.length == 1 ? confirmStringSolo : confirmStringMulti), confirmTitleString, - JOptionPane.YES_NO_OPTION); - if (answer == JOptionPane.YES_OPTION) { - OMGraphicList list = getList(); - if (list != null) { - for (int i = 0; i < selectedTiles.length; i++) { - ImageTile selectedTile = selectedTiles[i]; - list.remove(selectedTile); - ((DefaultListModel) getListModel()).removeElement(selectedTile); - } - if (resultsList != null) { - resultsList.repaint(); - } - repaint(); - } - } - } - } - - /** - * Asks the user to choose a new file or directory to load. The - * ImageReaderLoaders are consulted to only allow files that can be handled to - * be selectable. - */ - protected void addNewImagesWithFileChooser() { - // Need to get File Chooser, and allow the user to add a directory or - // file. We could even set up filters to check the ImageReaderLoaders - // available to this Layer and limit file selection based on matches. We - // should also report to the user what files were loaded using a dialog - // window, - // or we could simply select the new images and scroll the list to make - // those images visible. - File startingPoint = new File(Environment.get("lastchosendirectory", System.getProperty("user.home"))); - JFileChooser chooser = new JFileChooser(startingPoint); - String title = i18n.get(ImageTileLayer.class, "addImagesWindowTitle", "Add Images"); - chooser.setDialogTitle(title); - chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); - - chooser.setFileFilter(new ImageLoaderFileFilter(imageReaderLoaders)); - String acceptButtonText = i18n.get(ImageTileLayer.class, "acceptButtonText", "Add"); - int state = chooser.showDialog(null, acceptButtonText); - - try { - // only bother trying to read the file if there is one - // for some reason, the APPROVE_OPTION said it was a - // boolean during compile and didn't work in this next - // statement - if ((state != JFileChooser.CANCEL_OPTION) && (state != JFileChooser.ERROR_OPTION)) { - - String newFile = chooser.getSelectedFile().getCanonicalPath(); - - int dirIndex = newFile.lastIndexOf(File.separator); - if (dirIndex >= 0) { - // store the selected file for later - Environment.set("lastchosendirectory", newFile.substring(0, dirIndex)); - } - OMGraphicList list = getList(); - if (list == null) { - list = new OMGraphicList(); - setList(list); - } - - LoadImageThread lit = new LoadImageThread(newFile, list); - lit.start(); - } - } catch (IOException ioe) { - JOptionPane.showMessageDialog(null, ioe.getMessage(), "Error picking file", JOptionPane.ERROR_MESSAGE); - ioe.printStackTrace(); - } - } - - /** - * A special Thread subclass to handle image loading, so it's not managed by the - * AWT thread. - * - * @author dietrick - */ - class LoadImageThread extends Thread { - String fileToOpen; - OMGraphicList listToAddTo; - - public LoadImageThread(String fto, OMGraphicList ltat) { - fileToOpen = fto; - listToAddTo = ltat; - } - - public void run() { - loadImage(fileToOpen, listToAddTo); - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - } - - /** - * Set the GUI button state to be enabled or not based on something on the list - * being selected. - * - * @param somethingSelected whether something is selected. - */ - protected void setGUIButtonEnableState(boolean somethingSelected) { - if (icbp != null) { - icbp.setGUIButtonEnableState(somethingSelected); - - showHideButton.setEnabled(somethingSelected); - gotoButton.setEnabled(somethingSelected); - locateButton.setEnabled(somethingSelected); - } - } - - /** - * The ListModel used by the JList, displaying the images. - * - * @return the ListModel - */ - protected synchronized ListModel getListModel() { - if (listModel == null) { - listModel = new DefaultListModel(); - } - - return listModel; - } - - /** - * Add an ImageTile to the list model. - * - * @param tile - */ - protected void addImageTileToList(ImageTile tile) { - ((DefaultListModel) getListModel()).addElement(tile); - } - - /** - * Clear the list model. - */ - protected void clearImageTileList() { - ((DefaultListModel) getListModel()).clear(); - } - - /** - * Remove an ImageTile from the ListModel. - * - * @param tile - * @return true if removal was successful. - */ - protected boolean removeImageTileFromList(ImageTile tile) { - return ((DefaultListModel) getListModel()).removeElement(tile); - } - - /** - * Rebuild the list model contents based on the ImageTiles contained on the - * OMGraphicList. - * - */ - protected void rebuildListModel() { - DefaultListModel dlm = (DefaultListModel) getListModel(); - - OMGraphicList list = getList(); - int[] selectedIndicies = null; - - if (list != null) { - - if (selectedTiles != null && selectedTiles.length > 0) { - selectedIndicies = new int[selectedTiles.length]; - } - - int tileCount = 0; - int selectedIndex = 0; - if (selectedIndicies != null) { - for (OMGraphic omg : list) { - ImageTile imageTile = (ImageTile) omg; - - if (imageTile.isSelected() && selectedIndex < selectedIndicies.length) { - selectedIndicies[selectedIndex++] = tileCount; - } - - tileCount++; - } - } - - // Causes value changed() to be called, which then unsets selected - // tiles. So we need to find out which tiles were selected above, - // and then set them again later. - dlm.clear(); - - for (OMGraphic omg : list) { - tileCount++; - dlm.addElement((ImageTile) omg); - } - } - - if (resultsList != null) { - - if (selectedIndicies != null) { - resultsList.setSelectedIndices(selectedIndicies); - } - - resultsList.repaint(); - } - } - - /** - * The ImageTiles currently selected on the list in the GUI. - */ - protected ImageTile[] selectedTiles; - - /** - * @return the ImageTile[] of tiles currently selected in the GUI. - */ - protected ImageTile[] getSelectedTiles() { - return selectedTiles; - } - - /** - * Set the ImageTile[] of tiles currently selected in the GUI. - * - * @param sTiles - */ - protected void setSelectedTiles(ImageTile[] sTiles) { - selectedTiles = sTiles; - if (sTiles != null) { - boolean allTilesDefective = areAllTilesDefective(sTiles); - setGUIButtonEnableState(sTiles.length > 0 && !allTilesDefective); - - if (allTilesDefective && icbp != null) { - icbp.setGUIDeleteButtonEnableState(allTilesDefective); - } - - for (ImageTile it : sTiles) { - it.select(); - } - } - - checkShowHideStatus(); - doPrepare(); - } - - protected boolean areAllTilesDefective(ImageTile[] sTiles) { - boolean allTilesDefective = false; - if (sTiles != null && sTiles.length > 0) { - allTilesDefective = true; - for (int i = 0; i < sTiles.length; i++) { - if (!(sTiles[i] instanceof ErrImageTile)) { - allTilesDefective = false; - break; - } - } - } - - return allTilesDefective; - } - - /** - * Checks the selected tiles from the visible list and tallies their visibility. - * If all of the tiles are invisible, the GUI button will allow them to be made - * visible. If any of them are visible, all of them can be made invisible before - * the button will change them to the visible. - * - */ - public void checkShowHideStatus() { - ImageTile[] sTiles = getSelectedTiles(); - - boolean anyTilesVisible = (sTiles == null || sTiles.length == 0); - if (sTiles != null) { - for (int i = 0; i < sTiles.length; i++) { - anyTilesVisible = sTiles[i].isVisible() || anyTilesVisible; - } - } - - showHideButton.setText(anyTilesVisible ? HIDE_TILES_TITLE : SHOW_TILES_TITLE); - } - - /** - * A list selection listener object for the JList. - * - * @author dietrick - */ - class ListManager implements ListSelectionListener, MouseListener, MouseMotionListener { - public ListManager() { - - } - - public void valueChanged(ListSelectionEvent e) { - if (e.getValueIsAdjusting() == false && resultsList != null) { - // Reset the location selection; - locateButton.setSelected(false); - deselect(); - - int[] indicies = resultsList.getSelectedIndices(); - ImageTile[] selectedTiles = new ImageTile[indicies.length]; - if (indicies.length > 0) { - ListModel listModel = getListModel(); - for (int i = 0; i < indicies.length; i++) { - selectedTiles[i] = (ImageTile) listModel.getElementAt(indicies[i]); - } - } - setSelectedTiles(selectedTiles); - } - } - - public void mouseClicked(MouseEvent e) { - - } - - public void mouseEntered(MouseEvent e) { - - } - - public void mouseExited(MouseEvent e) { - - } - - public void mousePressed(MouseEvent e) { - checkMouseSelection(e); - } - - public void mouseReleased(MouseEvent e) { - checkMouseSelection(e); - } - - protected void checkMouseSelection(MouseEvent e) { - int selectedIndex = getResultListIndex(e); - if (selectedIndex < 0) { - resultsList.clearSelection(); - } - } - - public void mouseDragged(MouseEvent e) { - - } - - public void mouseMoved(MouseEvent e) { - int selectedIndex = getResultListIndex(e); - if (selectedIndex >= 0) { - Object it = getListModel().getElementAt(selectedIndex); - if (it instanceof ErrImageTile) { - resultsList.setToolTipText(((ErrImageTile) it).getProblemMessage()); - return; - } - } - resultsList.setToolTipText(null); - } - } - - /** - * find out which list object was moused. - * - * @param e - * @return index of list member moused on. - */ - protected int getResultListIndex(MouseEvent e) { - int index = -1; - - if (resultsList != null) { - double height = getResultsListCellHeight(); - - if (height == 0) { - return index; - } - - int nIndex = e.getY() / (int) height; - - if (nIndex < getListModel().getSize()) { - index = nIndex; - } - } - - return index; - } - - /** - * Get the pixel height of each cell in the JList. - * - * @return pixel height of cell - */ - protected double getResultsListCellHeight() { - double height = 0; - if (resultsList != null) { - int rlFVI = resultsList.getFirstVisibleIndex(); - Rectangle bounds = resultsList.getCellBounds(rlFVI, rlFVI); - - if (bounds != null) { - height = bounds.getHeight(); - } - } - - return height; - } - - public static int buttonSize = 16; - public static ImageIcon warningImage; - public static ImageIcon invisibleImage; - - protected static void initIcons() { - DrawingAttributes blackDa = new DrawingAttributes(); - - DrawingAttributes invisDa = new DrawingAttributes(); - invisDa.setLinePaint(OMColor.clear); - invisDa.setFillPaint(OMColor.clear); - - DrawingAttributes yellowDa = new DrawingAttributes(); - yellowDa.setLinePaint(OMColor.yellow); - yellowDa.setFillPaint(OMColor.yellow); - - IconPart ip = new BasicIconPart(new Rectangle2D.Double(0, 0, 100, 100)); - ip.setRenderingAttributes(invisDa); - invisibleImage = OMIconFactory.getIcon(buttonSize, buttonSize, ip); - - IconPartList ipl = new IconPartList(); - - Polygon triangle = new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4); - - BasicIconPart bip = new BasicIconPart(triangle); - bip.setRenderingAttributes(yellowDa); - ipl.add(bip); - - bip = new BasicIconPart(triangle); - bip.setRenderingAttributes(yellowDa); - ipl.add(bip); - bip = new BasicIconPart(triangle); - bip.setRenderingAttributes(blackDa); - ipl.add(bip); - bip = new BasicIconPart(new Line2D.Double(49, 35, 49, 65)); - bip.setRenderingAttributes(blackDa); - ipl.add(bip); - bip = new BasicIconPart(new Line2D.Double(49, 75, 49, 77)); - bip.setRenderingAttributes(blackDa); - ipl.add(bip); - bip = new BasicIconPart(new Line2D.Double(51, 35, 51, 65)); - bip.setRenderingAttributes(blackDa); - ipl.add(bip); - bip = new BasicIconPart(new Line2D.Double(51, 75, 51, 77)); - bip.setRenderingAttributes(blackDa); - ipl.add(bip); - warningImage = OMIconFactory.getIcon(buttonSize, buttonSize, ipl); - - } - - /** - * Renders the JList cells. - */ - public static class ImageListCellRenderer extends JPanel implements ListCellRenderer { - - private static final long serialVersionUID = 1L; - protected int buttonSize = 16; - protected JLabel label = new JLabel(); - protected JLabel statusMark = new JLabel(); - - public static Color fontColor = Color.BLACK; - public static Color altFontColor = Color.BLACK; - public static Color selectColor = Color.GRAY; - public static Color notVisibleColor = new Color(100, 100, 100); - public static Color regularBackgroundColor = Color.WHITE; - - public ImageListCellRenderer() { - if (warningImage == null) { - initIcons(); - } - - setOpaque(true); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - gridbag.setConstraints(label, c); - this.add(label); - - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - gridbag.setConstraints(statusMark, c); - this.add(statusMark); - - Font f = label.getFont(); - f = new Font(f.getName(), f.getStyle(), f.getSize() - 1); - label.setFont(f); - - setPreferredSize(new Dimension(20, buttonSize)); - } - - public Component getListCellRendererComponent(JList list, ImageTile value, int index, - boolean isSelected, boolean cellHasFocus) { - - ImageTile imageTile = (ImageTile) value; - label.setText((String) imageTile.getAttribute(NAME_ATTRIBUTE)); - - if (!isSelected) { - label.setForeground(imageTile.isVisible() ? fontColor : notVisibleColor); - } - - if (value instanceof ErrImageTile) { - statusMark.setIcon(warningImage); - } else { - statusMark.setIcon(invisibleImage); - } - - setBackground(isSelected ? selectColor : regularBackgroundColor); - return this; - } - - } - - /** - * File filter created based on what the ImageReaders can handle. - * - * @author dietrick - */ - class ImageLoaderFileFilter extends FileFilter { - - List imageReaderLoaders; - - public ImageLoaderFileFilter(List imgDcdrLdrs) { - imageReaderLoaders = imgDcdrLdrs; - } - - public boolean accept(File f) { - if (f.isDirectory()) { - return true; - } - - if (imageReaderLoaders != null) { - for (ImageReaderLoader irl : imageReaderLoaders) { - if (irl.isLoadable(f.getName())) { - return true; - } - } - } - return false; - } - - public String getDescription() { - String description = i18n.get(ImageTileLayer.class, "fileFilterDescription", - "Image File Formats Supported by Layer"); - return description; - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileLayer.java deleted file mode 100644 index d6c9c2ee9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileLayer.java +++ /dev/null @@ -1,529 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.image; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.event.ActionEvent; -import java.net.MalformedURLException; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JOptionPane; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.mapTile.MapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.MapTileRequester; -import com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * A Layer that uses a MapTileFactory to display information (tiles) on the map. - * Properties for this layer look like this: - * - *
- * 
- * tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer
- * tiles.prettyName=TILES
- * tiles.tileFactory=com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory
- * tiles.rootDir=root_directory_of_tiles
- * #optional, .png is default
- * tiles.fileExt=.png
- * tiles.cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # transform for naming convention of tiles default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * tiles.mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * 
- * 
- * - * You can use a server that provides image tiles: - * - *
- * 
- * tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer
- * tiles.prettyName=TILES
- * tiles.tileFactory=com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory
- * tiles.rootDir=URL root directory of tiles
- * # a local location to cache tiles, to reduce load on server.
- * tiles.localCacheRootDir=/data/tiles/osmtiles
- * # save cache when layer is done (true by default)
- * tiles.saveCache=true
- * 
- * # other properties are the same.
- * tiles.fileExt=.png
- * tiles.cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # transform for naming convention of tiles default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * 
- * 
- * - * The rootDir property can be defined as a pattern, with the zoom level z, x - * tile coordinate and y tile coordinate set using {z}{x}{y} for however the - * tiles are stored or retrieved: - * - *
- * rootDir=/data/tiles/{z}/{x}/{y}.png
- * 
- * #or, for the ServerMapTileFactory:
- * rootDir=http://someserver.com/tileset/{z}/{x}/{y}.png
- * 
- * 
- * - * In this case, the fileExt won't be used as the code will assume you are - * setting that. - * - * To make things simpler, you can define a tiles.omp file that sits under the - * tile root directory or at the top level of the jar file, and let it specify - * the properties for the tile set. The properties in that file should be - * unscoped: - * - *
- * 
- * fileExt=.png
- * #for instance, for GDAL processed images you need this transform since tiles have difference reference coordinates
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * #in jar file, should specify rootDir inside jar to tiles (don't need this for layers accessing local file system rootDirs, unless you want to specify z,x,y order differently):
- * rootDir=mytiles
- * 
- * #optional
- * attribution=map data 2013 OpenStreetMap
- * 
- * 
- * - * If you do this last configuration, all you need to define is rootDir (and - * prettyName, class) property for layer, and then define all other props with - * data. - * - * @author dietrick - */ -public class MapTileLayer extends OMGraphicHandlerLayer implements MapTileRequester { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.image.MapTileLayer"); - - /** - * Property that sets the class name of the MapTileFactory to use for this - * layer. - */ - public final static String TILE_FACTORY_CLASS_PROPERTY = "tileFactory"; - /** - * Property to allow the MapTileFactory to call repaint on this layer as map - * tiles become available. Default is false, enabling it will not allow this - * layer to be used with an ImageServer (renderDataForProjection won't - * work). - */ - public final static String INCREMENTAL_UPDATES_PROPERTY = "incrementalUpdates"; - - /** - * A property to set if you want to force the layer to use tiles of a - * certain zoom level. - */ - public final static String ZOOM_LEVEL_PROPERTY = "zoomLevel"; - - /** - * A property to set for displaying attribution for the data used by the - * layer. - */ - public final static String DATA_ATTRIBUTION_PROPERTY = "attribution"; - - /** - * A property to save or destroy the tile factory cache when the layer is - * removed. - */ - public final static String SAVE_CACHE_PROPERTY = "saveCache"; - /** - * The MapTileFactory that knows how to fetch image files and create - * OMRasters for them. - */ - protected MapTileFactory tileFactory; - /** - * Flag to allow this layer to set itself as a repaint callback object on - * the tile factory. - */ - protected boolean incrementalUpdates = false; - /** - * The zoomLevel to use when requesting tiles from the MapTileFactory. Is -1 - * for default, which lets the factory choose the zoom level based on the - * current scale setting. You can choose 1-20 if you want to force the layer - * to use something else. - */ - protected int zoomLevel = -1; - - /** - * Attribution for the map data. If it exists, it will be displayed on the - * lower left corner of the map. - */ - protected String attribution = null; - - /** - * Flag to save tile factory cache when the layer is no longer used. - */ - protected boolean saveCache = true; - - /** - * Rendering parameters for attribution string. - */ - protected DrawingAttributes attributionAttributes = DrawingAttributes.getDefaultClone(); - - public MapTileLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setTileFactory(new StandardMapTileFactory()); - // We need to make this layer uninterruptable, because that messes with - // the image file loading. - setInterruptable(false); - } - - public MapTileLayer(MapTileFactory tileFactory) { - this(); - this.tileFactory = tileFactory; - } - - /** - * OMGraphicHandlerLayer method, called with projection changes or whenever - * else doPrepare() is called. Calls getTiles on the map tile factory. - * - * @return OMGraphicList that contains tiles to be displayed for the current - * projection. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - return null; - } - - if (tileFactory != null) { - return tileFactory.getTiles(projection, zoomLevel, new OMGraphicList()); - } - return null; - } - - public void paint(java.awt.Graphics g) { - super.paint(g); - - OMText attrib = getAttributionGraphic(); - if (attrib != null) { - attrib.render(g); - } - } - - /** - * @return OMText for attribution text - */ - protected OMText getAttributionGraphic() { - Projection proj = getProjection(); - if (attribution != null && proj != null) { - OMText attText = new OMText(10, proj.getHeight() - 10, attribution, OMText.JUSTIFY_LEFT); - if (attributionAttributes != null) { - attributionAttributes.setTo(attText); - } - attText.generate(proj); - return attText; - } - - return null; - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - attribution = props.getProperty(prefix + DATA_ATTRIBUTION_PROPERTY, attribution); - attributionAttributes.setProperties(prefix, props); - - String tileFactoryClassString = props.getProperty(prefix + TILE_FACTORY_CLASS_PROPERTY); - if (tileFactoryClassString != null) { - MapTileFactory itf = (MapTileFactory) ComponentFactory.create(tileFactoryClassString, prefix, props); - if (itf != null) { - setTileFactory(itf); - } - } else { - // Let's see if we can figure out what kind of MapTileFactory is - // needed based on rootDir - String rootDirString = props.getProperty(prefix + StandardMapTileFactory.ROOT_DIR_PROPERTY); - if (rootDirString != null) { - try { - // We build URL here to test if the rootDir location exists. - // Comment out url to avoid dead store findbugs problem. - /* URL url = */new java.net.URL(rootDirString); - // If we get here, we have a protocol, looks remote, so we - // should make sure the - // ServerMapTileFactory is used. - if (!(getTileFactory() instanceof ServerMapTileFactory)) { - setTileFactory(new ServerMapTileFactory(rootDirString)); - } - - } catch (MalformedURLException e) { - // no protocol or something, use default - // StandardMapTileFactory - if (!(getTileFactory() instanceof StandardMapTileFactory)) { - setTileFactory(new StandardMapTileFactory()); - } - } - } - } - - if (tileFactory instanceof PropertyConsumer) { - ((PropertyConsumer) tileFactory).setProperties(prefix, props); - } - - incrementalUpdates = PropUtils.booleanFromProperties(props, prefix + INCREMENTAL_UPDATES_PROPERTY, - incrementalUpdates); - - setZoomLevel(PropUtils.intFromProperties(props, prefix + ZOOM_LEVEL_PROPERTY, zoomLevel)); - - saveCache = PropUtils.booleanFromProperties(props, prefix + SAVE_CACHE_PROPERTY, saveCache); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - if (tileFactory != null) { - props.put(prefix + TILE_FACTORY_CLASS_PROPERTY, tileFactory.getClass().getName()); - if (tileFactory instanceof PropertyConsumer) { - ((PropertyConsumer) tileFactory).getProperties(props); - } - } - - props.put(prefix + INCREMENTAL_UPDATES_PROPERTY, Boolean.toString(incrementalUpdates)); - props.put(prefix + ZOOM_LEVEL_PROPERTY, Integer.toString(zoomLevel)); - props.put(prefix + DATA_ATTRIBUTION_PROPERTY, PropUtils.unnull(attribution)); - props.put(prefix + SAVE_CACHE_PROPERTY, Boolean.toString(saveCache)); - - attributionAttributes.getProperties(props); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - I18n i18n = Environment.getI18n(); - - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), ZOOM_LEVEL_PROPERTY, "Zoom Level", - "Force zoom level for queries (-1 is no forcing)", null); - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), DATA_ATTRIBUTION_PROPERTY, "Attribution", - "Attribution for data source", null); - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), SAVE_CACHE_PROPERTY, "Disable Tile Factory Reset", "Disable tile factory reset on layer remove", null); - if (tileFactory instanceof StandardMapTileFactory) { - ((StandardMapTileFactory) tileFactory).getPropertyInfo(props); - props.put(initPropertiesProperty, ((StandardMapTileFactory) tileFactory).getInitPropertiesOrder() - + " " + ZOOM_LEVEL_PROPERTY + " " + DATA_ATTRIBUTION_PROPERTY + " " - + SAVE_CACHE_PROPERTY); - } else { - props.put(initPropertiesProperty, StandardMapTileFactory.ROOT_DIR_PROPERTY + " " - + StandardMapTileFactory.FILE_EXT_PROPERTY + " " + ZOOM_LEVEL_PROPERTY + " " - + DATA_ATTRIBUTION_PROPERTY + " " + SAVE_CACHE_PROPERTY); - } - - return props; - } - - /** - * Called when the layer has been turned off and the projection changes, - * signifying that the layer can clean up. - */ - public void removed(Container cont) { - MapTileFactory tileFactory = getTileFactory(); - if (tileFactory != null && !saveCache) { - tileFactory.reset(); - } - } - - public MapTileFactory getTileFactory() { - return tileFactory; - } - - public void setTileFactory(MapTileFactory tileFactory) { - getLogger().fine("setting tile factory to: " + tileFactory.getClass().getName()); - // This allows for general faster response, but causes the map to jump - // around a little bit when used with the BufferedImageRenderPolicy and - // when the projection changes occur rapidly, like when zooming and - // panning several times in a second. The generation/positioning can't - // keep up. It'll settle out, but it might be better to be slower and - // less confusing to the user. - - tileFactory.setMapTileRequester(this); - - this.tileFactory = tileFactory; - - doPrepare(); - } - - public boolean isIncrementalUpdates() { - return incrementalUpdates; - } - - public void setIncrementalUpdates(boolean incrementalUpdates) { - this.incrementalUpdates = incrementalUpdates; - } - - public int getZoomLevel() { - return zoomLevel; - } - - public void setZoomLevel(int zoomLevel) { - this.zoomLevel = zoomLevel; - } - - public java.awt.Component getGUI() { - // Only allow delete cache button if the source of the tiles are from a - // server. - - JPanel panel = new JPanel(); - panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - - if (getTileFactory() instanceof ServerMapTileFactory) { - JPanel clearCachePanel = new JPanel(new BorderLayout()); - clearCachePanel.add(new JPanel(), BorderLayout.WEST); - clearCachePanel.add(new JPanel(), BorderLayout.EAST); - JButton clearButton = new JButton(i18n.get(MapTileLayer.class, "clearCacheLabel", "Clear Tile Cache")); - clearCachePanel.add(clearButton, BorderLayout.CENTER); - clearButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - String query = i18n.get(MapTileLayer.class, "mapTileLayerDeleteCacheQuery", "Delete tiles on disk? Click OK to delete..."); - - int dialogResult = JOptionPane.showConfirmDialog(null, query, "Warning", JOptionPane.OK_CANCEL_OPTION); - if (dialogResult == JOptionPane.OK_OPTION) { - clearCache(); - } - } - }); - - panel.add(clearCachePanel); - } - - panel.add(getDefaultSettingsPanel(this.getClass(), getTransparency())); - return panel; - } - - /** - * @return the attribution - */ - public String getAttribution() { - return attribution; - } - - /** - * @param attribution - * the attribution to set - */ - public void setAttribution(String attribution) { - this.attribution = attribution; - } - - /** - * @return the attributionAttributes - */ - public DrawingAttributes getAttributionAttributes() { - return attributionAttributes; - } - - /** - * @param attributionAttributes - * the attributionAttributes to set - */ - public void setAttributionAttributes(DrawingAttributes attributionAttributes) { - this.attributionAttributes = attributionAttributes; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.MapTileRequestor#shouldContinue() - */ - public boolean shouldContinue() { - return !isInterruptable() || !isCancelled(); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.MapTileRequestor#listUpdated() - */ - public void listUpdated() { - if (incrementalUpdates) { - repaint(); - } - } - - /** - * Clear the MapTileFactory cache. - */ - public void clearCache() { - MapTileFactory mtf = getTileFactory(); - if (mtf != null) { - mtf.reset(); - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(MapTileLayer.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileUtilLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileUtilLayer.java deleted file mode 100644 index a4871a30f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/MapTileUtilLayer.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ -package com.bbn.openmap.layer.image; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.HashMap; -import java.util.logging.Logger; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.proj.coords.MercatorUVGCT; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor; - -/** - * A layer to assist with creating map tiles, it creates an overlay that - * represents tile coverage for different zoom levels. You could just view the - * tiles, but then you are limited to looking at that coverage at the scale for - * that zoom level. This tool lets you figure out what tiles you have and what - * you may need to create. - * - * @author dietrick - */ -public class MapTileUtilLayer - extends OMGraphicHandlerLayer - implements ListSelectionListener { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.imageTile.MapTileUtilLayer"); - protected String tileRootDir; - protected HashMap images; - protected OMGraphicList omgraphics; - - public MapTileUtilLayer() { - images = new HashMap(); - omgraphics = new OMGraphicList(); - coordTransform = LatLonGCT.INSTANCE; - setProjectionChangePolicy(new ListResetPCPolicy(this)); - } - - public String getTileRootDir() { - return tileRootDir; - } - - public void setTileRootDir(String tileRootDir) { - this.tileRootDir = tileRootDir; - - if (generateButton != null) { - generateButton.setEnabled(tileRootDir != null && tileRootDir.length() != 0); - } - } - - protected OMGraphicList getOMGraphics() { - return omgraphics; - } - - protected void setOMGraphics(OMGraphicList omgl) { - omgraphics = omgl; - } - - public synchronized OMGraphicList prepare() { - OMGraphicList ret = new OMGraphicList(); - - OMGraphicList currentList = getOMGraphics(); - if (currentList != null) { - ret.addAll(currentList); - } - - Projection proj = getProjection(); - if (proj != null) { - ret.generate(proj); - } - - return ret; - } - - protected BufferedImage getImageForZoomLevel(int zoomLevel) { - int dimensionForZoom = (int) Math.pow(2, zoomLevel); - return new BufferedImage(dimensionForZoom, dimensionForZoom, BufferedImage.TYPE_INT_ARGB); - } - - protected OMWarpingImage getOMWarpingImage(BufferedImage bufImage, int zoomLevel) { - GeoCoordTransformation gct = new MercatorUVGCT.TMS(zoomLevel); - return new OMWarpingImage(bufImage, gct, new DataBounds(new Point2D.Double(0, 0), new Point2D.Double(bufImage.getWidth(), - bufImage.getHeight()))); - } - - protected void colorImage(File zoomLevelDir, BufferedImage bufImage, int rgb) { - int width = bufImage.getWidth(); - int height = bufImage.getHeight(); - - for (int x = 0; x < width; x++) { - File rowDir = new File(zoomLevelDir, Integer.toString(x)); - if (rowDir.exists()) { - for (int y = 0; y < height; y++) { - File colFile = new File(rowDir, Integer.toString(y) + ".png"); - if (colFile.exists()) { - bufImage.setRGB(x, y, rgb); - } - } - } - } - } - - protected void generateMapTileImages() { - - if (imageList == null) { - logger.info("imageList is null, something weird going on"); - return; - } - - if (images != null) { - images.clear(); - } - - if (tileRootDir != null) { - File rootFile = new File(tileRootDir); - if (rootFile.exists()) { - for (int zoomLevel = 0; zoomLevel < 21; zoomLevel++) { - BufferedImage buf = getImageForZoomLevel(zoomLevel); - - File levelDir = new File(rootFile, Integer.toString(zoomLevel)); - if (levelDir.exists()) { - colorImage(levelDir, buf, 0x77aaaa00); - images.put(levelDir.getName(), buf); - imageList.setListData(images.keySet().toArray()); - } - } - } - } - } - - protected void clearMapTileImages() { - if (images != null) { - images.clear(); - } - - if (imageList != null) { - imageList.removeAll(); - } - } - - - JPanel gui = null; - DirectoryPropertyEditor dirEditor = null; - JButton generateButton = null; - JButton clearButton = null; - JList imageList = null; - - public JComponent getGUI() { - if (gui == null) { - - gui = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - - c.gridx = 0; - c.gridy = 0; - c.gridwidth = 1; - c.gridheight = 1; - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(10, 10, 0, 10); - - JLabel label1 = new JLabel("Tile Root Directory:"); - gui.add(label1, c); - - dirEditor = new DirectoryPropertyEditor(); - dirEditor.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent pce) { - DirectoryPropertyEditor de = (DirectoryPropertyEditor) pce.getSource(); - setTileRootDir(de.getAsText()); - } - }); - c.gridx = 1; - c.gridwidth = 2; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - gui.add(dirEditor.getCustomEditor(), c); - - imageList = new JList(); - imageList.addListSelectionListener(this); - imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - JScrollPane scrollPane = - new JScrollPane(imageList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - c.gridx = 0; - c.gridy = 1; - c.gridwidth = 3; - c.fill = GridBagConstraints.BOTH; - c.weighty = 1.0f; - c.insets = new Insets(10, 10, 10, 10); - - gui.add(scrollPane, c); - - c.fill = GridBagConstraints.NONE; - c.weightx = 0.0f; - c.weighty = 0.0f; - c.gridwidth = 1; - c.gridy = 2; - c.insets = new Insets(0, 10, 10, 10); - - clearButton = new JButton("Clear"); - clearButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - clearMapTileImages(); - } - }); - generateButton = new JButton("Generate"); - generateButton.setEnabled(tileRootDir != null && tileRootDir.length() != 0); - generateButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - generateMapTileImages(); - } - }); - - c.gridx = 0; - gui.add(clearButton, c); - - c.gridx = 2; - c.anchor = GridBagConstraints.NORTHEAST; - gui.add(generateButton, c); - } - - return gui; - } - - public static void main(String[] args) { - logger.info("for zoom level 17: " + Math.pow(2, 17)); - - JFrame frame = new JFrame("GUI"); - MapTileUtilLayer layer = new MapTileUtilLayer(); - frame.setContentPane(layer.getGUI()); - - frame.pack(); - frame.setVisible(true); - } - - /* - * (non-Javadoc) - * - * @see - * javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event - * .ListSelectionEvent) - */ - public void valueChanged(ListSelectionEvent arg0) { - if (arg0.getValueIsAdjusting()) { - int firstIndex = arg0.getFirstIndex(); - - JList list = (JList) arg0.getSource(); - String zoomLevel = list.getSelectedValue().toString(); - - if (images != null) { - BufferedImage buf = images.get(zoomLevel); - OMGraphicList omgl = new OMGraphicList(); - OMWarpingImage omwiImage = getOMWarpingImage(buf, Integer.parseInt(zoomLevel)); - omgl.add(omwiImage); - setOMGraphics(omgl); - doPrepare(); - } - - clearButton.setEnabled(((JList)arg0.getSource()).getComponentCount() > 0); - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/SHISLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/SHISLayer.java deleted file mode 100644 index 66d5e032b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/SHISLayer.java +++ /dev/null @@ -1,209 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/plugin/shis/SHISPlugIn.java,v $ -// $RCSfile: SHISPlugIn.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.image; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.image.ImageServerConstants; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The SHISLayer asks for an image from a SimpleHttpImageServer. It has some - * properties that you can set in the openmap.properties file: - *

- * The query to the SimpleHttpImageServer looks like something you can plug into - * your browser to test the server: - *

- * http://hostname:port/path?REQUEST=MAP&PROJTYPE=projection_type_value&SCALE= - * scale_value - * &LAT=center_latitude&LON=center_longitude&HEIGHT=map_pixel_height&WIDTH - * =map_pixel_width - * &FORMAT=image_format&TRANSPARENT=true|false&BGCOLOR=background_color - * - *

- * The projection information will be entered automatically by the layer based - * on the projection it receives from the MapBean. The other parameters can be - * entered in the properties for the layer. - * - *

- * 
- * #For the SHISLayer
- * shislayer.class=com.bbn.openmap.layer.image.SHISLayer
- * shislayer.prettyName=Whatever you like
- * shislayer.host=hostname 
- * shislayer.port=port number 
- * shislayer.path=query path (default is openmap)
- * shislayer.format=image format (JPEG, GIF from WMTConstants.java) 
- * shislayer.transparent=true or false, depends on imageformat 
- * shislayer.backgroundColor=RGB hex string (RRGGBB)
- * 
- * 
- */ -public class SHISLayer extends WebImageLayer { - - protected String queryHeader = null; - protected String imageFormat = null; - protected String backgroundColor = null; - protected String transparent = null; - protected String host = null; - protected String port = null; - protected String path = null; - - public final static String HostNameProperty = "host"; - public final static String PortNumberProperty = "port"; - public final static String PathProperty = "path"; - public final static String ImageFormatProperty = "format"; - public final static String BackgroundColorProperty = "backgroundColor"; - public final static String TransparentProperty = "transparent"; - - public SHISLayer() { - } - - /** - * When a projection is received, translate it into a valid request for a - * SimpleHttpImageServer, and then return the image received back from it. - * - * @param p projection of the screen, holding scale, center coords, height, - * width. - * @return a string describing the request to sent to the SHIS. - */ - public String createQueryString(Projection p) { - - if (queryHeader == null) { - return null; - } - - StringBuffer buf = new StringBuffer(queryHeader); - buf.append(REQUEST).append("=").append(MAP).append("&"); - - if (p != null) { - Point2D center = p.getCenter(); - buf.append(PROJTYPE).append("=").append(p.getName()).append("&").append(SCALE).append("=").append(p.getScale()).append("&").append(LAT).append("=").append(center.getY()).append("&").append(LON).append("=").append(center.getX()).append("&").append(ImageServerConstants.HEIGHT).append("=").append(p.getHeight()).append("&").append(ImageServerConstants.WIDTH).append("=").append(p.getWidth()); - } else { - buf.append(PROJTYPE).append("=name_undefined&").append(SCALE).append("=scale_undefined&").append(LAT).append("=center_lat_undefined&").append(LON).append("=center_lon_undefined&").append(ImageServerConstants.HEIGHT).append("=height_undefined&").append(ImageServerConstants.WIDTH).append("=width_undefined"); - } - - if (imageFormat != null) { - buf.append("&").append(FORMAT).append("=").append(imageFormat); - } - - if (transparent != null) { - buf.append("&").append(TRANSPARENT).append("=true"); - } - - if (backgroundColor != null) { - buf.append("&").append(BGCOLOR).append("=").append(backgroundColor); - } - - String layers = getLayerMarkers(); - if (layers != null) { - buf.append("&").append(layers); - } - - return buf.toString(); - } - - public String getServerName() { - return queryHeader; - } - - public String getLayerMarkers() { - // Not implemented - should be a list that can be set by the - // user. - return null; - } - - /** - * PropertyConsumer method. - */ - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - host = setList.getProperty(prefix + HostNameProperty); - port = setList.getProperty(prefix + PortNumberProperty); - path = setList.getProperty(prefix + PathProperty); - imageFormat = setList.getProperty(prefix + ImageFormatProperty); - transparent = setList.getProperty(prefix + TransparentProperty); - backgroundColor = setList.getProperty(prefix + BackgroundColorProperty); - - if (path == null) { - path = com.bbn.openmap.Environment.OpenMapPrefix; // "openmap" - } - - if (host == null || port == null) { - Debug.error("SHISPlugIn needs a host name and port number for the image server."); - queryHeader = null; - return; - } - - queryHeader = "http://" + (host == null ? "localhost" : host) - + (port == null ? "" : (":" + port)) + "/" + path + "?"; - - if (Debug.debugging("plugin")) { - Debug.output("SHISPlugIn: set up with header \"" + queryHeader + "\""); - } - } - - /** - * PropertyConsumer method. - */ - public Properties getProperties(Properties getList) { - getList = super.getProperties(getList); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - getList.put(prefix + HostNameProperty, PropUtils.unnull(host)); - getList.put(prefix + PortNumberProperty, PropUtils.unnull(port)); - getList.put(prefix + PathProperty, PropUtils.unnull(path)); - getList.put(prefix + ImageFormatProperty, PropUtils.unnull(imageFormat)); - getList.put(prefix + TransparentProperty, PropUtils.unnull(transparent)); - getList.put(prefix + BackgroundColorProperty, PropUtils.unnull(backgroundColor)); - return getList; - } - - /** - * PropertyConsumer method. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put(initPropertiesProperty, HostNameProperty + " " + PortNumberProperty + " " - + PathProperty + " " + ImageFormatProperty + " " + TransparentProperty + " " - + BackgroundColorProperty); - - list.put(HostNameProperty, "This hostname of the server machine."); - list.put(PortNumberProperty, "The port number the server is running on."); - list.put(PathProperty, "The path to the server (openmap is default)"); - list.put(ImageFormatProperty, "Image format (JPEG|GIF|PPM|PNG)"); - list.put(TransparentProperty, "Whether background of image should be transparent."); - list.put(TransparentProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - list.put(BackgroundColorProperty, "Background color for image."); - list.put(BackgroundColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - return list; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/VectorMapTileLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/VectorMapTileLayer.java deleted file mode 100644 index 515cc7c21..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/VectorMapTileLayer.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.bbn.openmap.layer.image; - -import java.awt.BorderLayout; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.BoxLayout; -import javax.swing.JComponent; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.dataAccess.mapTile.MapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.mb.StyleRoot; -import com.bbn.openmap.dataAccess.mapTile.mb.VectorMapTileFactory; -import com.bbn.openmap.gui.ScrollPaneWindowSupport; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class VectorMapTileLayer extends MapTileLayer { - - private static final long serialVersionUID = 1L; - - public final static String STYLE_LOCATION_PROPERTY = "style"; - - String styleLocation; - StyleRoot renderStyle; - - public VectorMapTileLayer() { - super(); - setTileFactory(new VectorMapTileFactory()); - } - - /** - * OMGraphicHandlerLayer method, called with projection changes or whenever - * else doPrepare() is called. Calls getTiles on the map tile factory. - * - * @return OMGraphicList that contains tiles to be displayed for the current - * projection. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - return null; - } - - if (renderStyle == null && styleLocation != null) { - renderStyle = loadStyleJSON(styleLocation); - if (tileFactory instanceof VectorMapTileFactory) { - getLogger().fine("setting new render style on tile factory"); - ((VectorMapTileFactory) tileFactory).setRenderStyle(renderStyle); - } - } - - if (tileFactory != null) { - OMGraphicList newList = new OMGraphicList(); - - OMText attrib = getAttributionGraphic(); - if (attrib != null) { - newList.add(attrib); - } - - return tileFactory.getTiles(projection, zoomLevel, newList); - } - - return null; - } - - public StyleRoot loadStyleJSON(String urlString) { - if (urlString != null) { - try { - - URL input = PropUtils.getResourceOrFileOrURL(urlString); - InputStream inputStream = input.openStream(); - return new StyleRoot(new ObjectMapper().readTree(inputStream)); - - } catch (MalformedURLException e) { - getLogger().warning(urlString + " style couldn't be found, " + e.getMessage()); - } catch (IOException e) { - getLogger().warning(urlString + " style couldn't be loaded property, " + e.getMessage()); - } - } - - return null; - } - - /** - * @return the styleLocation - */ - public String getStyleLocation() { - return styleLocation; - } - - /** - * Will cause a reset of the tile factory. - * - * @param styleLocation - * the styleLocation to set - */ - public void setStyleLocation(String styleLocation) { - this.styleLocation = styleLocation; - renderStyle = null; - - doPrepare(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - setStyleLocation(props.getProperty(prefix + STYLE_LOCATION_PROPERTY, getStyleLocation())); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + STYLE_LOCATION_PROPERTY, PropUtils.unnull(getStyleLocation())); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), STYLE_LOCATION_PROPERTY, "Style", - "Location of JSON Style file", "com.bbn.openmap.util.propertyEditor.FilePropertyEditor"); - - props.put(initPropertiesProperty, - PropUtils.unnull(props.getProperty(initPropertiesProperty)) + " " + STYLE_LOCATION_PROPERTY); - return props; - } - - /** - * Callback method to override how window support is created. - * - * @return WindowSupport object for layer palette. - */ - protected WindowSupport createWindowSupport() { - return new WindowSupport(getGUI(), getName()); - } - - public java.awt.Component getGUI() { - // Only allow delete cache button if the source of the tiles are from a - // server. - - JPanel panel = new JPanel(); - panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - - MapTileFactory mtf = getTileFactory(); - if (mtf instanceof VectorMapTileFactory) { - JPanel layerFilterPanel = new JPanel(new BorderLayout()); - layerFilterPanel.add(new JPanel(), BorderLayout.WEST); - layerFilterPanel.add(new JPanel(), BorderLayout.EAST); - JComponent filters = ((VectorMapTileFactory) mtf).getFilterPanel(); - - if (filters != null) { - layerFilterPanel.add(filters, BorderLayout.CENTER); - panel.add(layerFilterPanel); - } - } - - panel.add(getDefaultSettingsPanel(this.getClass(), getTransparency())); - return panel; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(VectorMapTileLayer.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/WMSLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/WMSLayer.java deleted file mode 100644 index 81efe1d5b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/WMSLayer.java +++ /dev/null @@ -1,505 +0,0 @@ -/* ********************************************************************** - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/plugin/wms/WMSPlugIn.java,v $ - * $Revision: 1.9 $ - * $Date: 2008/09/19 18:13:34 $ - * $Author: dietrick $ - * - * Code provided by Raj Singh, raj@rajsingh.org - * Updates provided by Holger Kohler, Holger.Kohler@dsto.defence.gov.au - * Raj Singh updates in July 2002 to: - * - support WMS versions 1.0.8, 1.1.0 and 1.1.1 - * - make JPEG image quality setting adjustable - * ********************************************************************* - */ - -package com.bbn.openmap.layer.image; - -import java.awt.geom.Point2D; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; - -import com.bbn.openmap.image.WMTConstants; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * This layer asks for an image from an OpenGIS compliant Web Map Server (WMS). - * Make sure that OpenMap is using the LLXY projection, because this plugin is - * only asking for images that are in the Spatial Reference System EPS 4326 - * projection, and anything else won't match up. This class will be growing to - * be more interactive with the WMS. - * - * It has some properties that you can set in the openmap.properties file: - * - *
- * 
- *     #For the WMSLayer
- *     wmsLayer=com.bbn.openmap.layer.image.WMSLayer
- *     wmsLayer.wmsserver=A URL for the WMS server (eg. http://host.domain.name/servlet/com.esri.wms.Esrimap)
- *     wmsLayer.wmsversion=OpenGIS WMS version number (eg. 1.1.1)
- *     wmsLayer.format=image format (eg. image/jpeg, image/png)
- *     wmsLayer.transparent=true or false, depends on imageformat
- *     wmsLayer.backgroundcolor=RGB hex string (RRGGBB)
- *     wmsLayer.layers=comma separated list of map layer names (eg. SDE.SASAUS_BND_COASTL,SDE.SASAUS_BND_POLBNDL)
- *     wmsLayer.styles=comma separated list of layer rendering styles corresponding to the layers listed
- *     wmsLayer.vendorspecificnames=comma separated list of vendor specific parameter names in order (eg. SERVICENAME)
- *     wmsLayer.vendorspecificvalues=comma separated list of vendor specific parameter values in order (eg. default)
- * 
- * 
- * - *

- * One of the best demo WMS servers can be found at: - * http://demo.cubewerx.com/demo/cubeserv/cubeserv.cgi - */ -public class WMSLayer extends WebImageLayer { - - /** URL to the server script that responds to WMS map requests */ - protected String wmsServer = null; - /** GIF, PNG, JPEG, etc. (anything the server supports) */ - protected String imageFormat = "image/png"; - /** - * If using a lossy image format, such as jpeg, set this to high, medium or - * low - */ - protected String imageQuality = "MEDIUM"; - /** Specify the color for non-data areas of the image in r,g,b */ - protected String backgroundColor = "0x00FFFFFF"; - /** true=make the backgroundColor transparent */ - protected String transparent = "true"; - /** version of the Web map server spec the server supports */ - protected String wmsVersion = "1.1.1"; - /** Comma-separated list of layer names */ - protected String layers = null; - /** Comma-separated list of style names */ - protected String styles = null; - /** Comma-separated list of vendor specific parameter names */ - protected String vendorSpecificNames = null; - /** Comma-separated list of vendor specific parameter values */ - protected String vendorSpecificValues = null; - /** Same as wmsServer */ - protected String queryHeader = null; - /** Keyword for map request. Changes to MAP for WMS version 1.0.0 */ - protected String mapRequestName = WMTConstants.GETMAP; - /** - * Keyword for error handling. Changes to INIMAGE for WMS version under - * 1.1.0. Changes to application/vnd.ogc.se+inimage for versions greater - * than 1.1.1 - */ - protected String errorHandling = "application/vnd.ogc.se_inimage"; - - public final static String WMSNameProperty = "wmsname"; - public final static String WMSServerProperty = "wmsserver"; - public final static String ImageFormatProperty = "format"; - public final static String BackgroundColorProperty = "backgroundcolor"; - public final static String TransparentProperty = "transparent"; - public static final String WMSVersionProperty = "wmsversion"; - public static final String LayersProperty = "layers"; - public static final String StylesProperty = "styles"; - public static final String VendorSpecificNamesProperty = "vendorspecificnames"; - public static final String VendorSpecificValuesProperty = "vendorspecificvalues"; - /** integer identifier for high image quality */ - public static final int LOSSY_IMAGE_QUALITY_HIGH = 2; - /** integer identifier for medium image quality */ - public static final int LOSSY_IMAGE_QUALITY_MEDIUM = 1; - /** integer identifier for low image quality */ - public static final int LOSSY_IMAGE_QUALITY_LOW = 0; - - public WMSLayer() { - } - - /** - * Add new layers to the server request, using the default style. - */ - public void addLayers(String[] ls) { - addLayers(ls, null); - } - - /** - * Add new layers to the server request, using specified styles. - */ - public void addLayers(String[] ls, String[] st) { - - // DFD - do they have to be the same length? How about we just - // use the styles we have for that number of layers, and let - // the defaults take over for the rest. - - // if (ls.length != st.length) { - // return null; - // } - - for (int j = 0; j < ls.length; j++) { - layers += "," + ls[j]; - - // Put some other checks in here instead of the length - // check above. - if (st == null || j >= st.length || st[j] == null) { - styles += ","; - } else { - styles += "," + st[j]; - } - } - } - - /** - * Create the query to be sent to the server, based on current settings. - */ - public String createQueryString(Projection p) { - - if (queryHeader == null) { - return null; - } - - String bbox = "undefined"; - String height = "undefined"; - String width = "undefined"; - - String sCoordParamName = WMTConstants.SRS; - - if (p != null) { - Point2D ul = p.getUpperLeft(); - Point2D lr = p.getLowerRight(); - - if (wmsVersion.compareTo("1.3.0") == 0) { - bbox = Double.toString(lr.getY()) + "," + Double.toString(ul.getX()) + "," - + Double.toString(ul.getY()) + "," + Double.toString(lr.getX()); - sCoordParamName = WMTConstants.CRS; - errorHandling = "INIMAGE"; - } else { - bbox = Double.toString(ul.getX()) + "," + Double.toString(lr.getY()) + "," - + Double.toString(lr.getX()) + "," + Double.toString(ul.getY()); - } - - height = Integer.toString(p.getHeight()); - width = Integer.toString(p.getWidth()); - } - - StringBuffer buf = new StringBuffer(queryHeader); - buf.append("?").append(WMTConstants.VERSION).append("=").append(wmsVersion).append("&").append(WMTConstants.REQUEST).append("=").append(mapRequestName).append("&").append(sCoordParamName).append("=").append("EPSG:4326").append("&").append(WMTConstants.BBOX).append("=").append(bbox).append("&").append(WMTConstants.HEIGHT).append("=").append(height).append("&").append(WMTConstants.WIDTH).append("=").append(width).append("&").append(WMTConstants.EXCEPTIONS).append("=").append(errorHandling); - - if (imageFormat != null) { - buf.append("&").append(WMTConstants.FORMAT).append("=").append(imageFormat); - - String baseImageFormat = imageFormat; - if (baseImageFormat.indexOf('/') > 0) - baseImageFormat = baseImageFormat.substring(baseImageFormat.indexOf('/')); - if (baseImageFormat.equals(WMTConstants.IMAGEFORMAT_JPEG)) { - buf.append("&quality=").append(imageQuality); - } - } - - if (transparent != null) { - buf.append("&").append(WMTConstants.TRANSPARENT).append("=").append(transparent); - } - - if (backgroundColor != null) { - buf.append("&").append(WMTConstants.BGCOLOR).append("=").append(backgroundColor); - } - - if (layers != null) { - buf.append("&").append(WMTConstants.LAYERS).append("=").append(layers); - } - - String cStyles = styles; - if (cStyles == null) { - cStyles = ""; - } - - // if (styles != null) { - buf.append("&").append(WMTConstants.STYLES).append("=").append(cStyles); - // } - - if (Debug.debugging("wms")) { - Debug.output("query string: " + buf); - } - - /* - * Included to allow for one or more vendor specific parameters to be - * specified such as ESRI's ArcIMS's "ServiceName" parameter. - */ - if (vendorSpecificNames != null) { - if (vendorSpecificValues != null) { - StringTokenizer nameTokenizer = new StringTokenizer(vendorSpecificNames, ","); - StringTokenizer valueTokenizer = new StringTokenizer(vendorSpecificValues, ","); - String paramName = null; - String paramValue = null; - while (nameTokenizer.hasMoreTokens()) { - try { - paramName = nameTokenizer.nextToken(); - paramValue = valueTokenizer.nextToken(); - buf.append("&").append(paramName).append("=").append(paramValue); - } catch (NoSuchElementException e) { - if (Debug.debugging("wms")) { - Debug.output("WMSPlugIn.getRectangle(): " + "parameter \"" + paramName - + "\" has no value"); - } - } - } - } - } - return buf.toString(); - } - - /** - * Method to set the properties in the PropertyConsumer. The prefix is a - * string that should be prepended to each property key (in addition to a - * separating '.') in order for the PropertyConsumer to uniquely identify - * properties meant for it, in the midst of Properties meant for several - * objects. - * - * @param prefix a String used by the PropertyConsumer to prepend to each - * property value it wants to look up - - * setList.getProperty(prefix.propertyKey). If the prefix had already - * been set, then the prefix passed in should replace that previous - * value. - * - * @param setList a Properties object that the PropertyConsumer can use to - * retrieve expected properties it can use for configuration. - */ - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - wmsServer = setList.getProperty(prefix + WMSServerProperty); - if (wmsServer == null) { - Debug.error("WMSPlugIn needs a WMS server."); - } - - queryHeader = wmsServer; - - setImageFormat(setList.getProperty(prefix + ImageFormatProperty, getImageFormat())); - - setTransparent(setList.getProperty(prefix + TransparentProperty, getTransparent())); - - setBackgroundColor(setList.getProperty(prefix + BackgroundColorProperty, getBackgroundColor())); - - setWmsVersion(setList.getProperty(prefix + WMSVersionProperty, getWmsVersion())); - - layers = setList.getProperty(prefix + LayersProperty); - styles = setList.getProperty(prefix + StylesProperty); - - /** - * Include for vendor specific parameters - */ - setVendorSpecificNames(setList.getProperty(prefix + VendorSpecificNamesProperty, getVendorSpecificNames())); - setVendorSpecificValues(setList.getProperty(prefix + VendorSpecificValuesProperty, getVendorSpecificValues())); - - } // end setProperties - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + WMSServerProperty, PropUtils.unnull(wmsServer)); - props.put(prefix + ImageFormatProperty, PropUtils.unnull(imageFormat)); - props.put(prefix + TransparentProperty, PropUtils.unnull(transparent)); - props.put(prefix + BackgroundColorProperty, PropUtils.unnull(backgroundColor)); - props.put(prefix + WMSVersionProperty, PropUtils.unnull(wmsVersion)); - props.put(prefix + LayersProperty, PropUtils.unnull(layers)); - props.put(prefix + StylesProperty, PropUtils.unnull(styles)); - props.put(prefix + VendorSpecificNamesProperty, PropUtils.unnull(vendorSpecificNames)); - props.put(prefix + VendorSpecificValuesProperty, PropUtils.unnull(vendorSpecificValues)); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - props.put(initPropertiesProperty, WMSServerProperty + " " + WMSVersionProperty + " " - + LayersProperty + " " + StylesProperty + " " + VendorSpecificNamesProperty + " " - + VendorSpecificValuesProperty + " " + ImageFormatProperty + " " - + TransparentProperty + " " + BackgroundColorProperty); - - props.put(WMSServerProperty, "URL to the server script that responds to WMS map requests"); - props.put(ImageFormatProperty, "Image format (GIF, PNG, JPEG)"); - props.put(TransparentProperty, "Flag to indicate that background of image should be tranparent"); - props.put(TransparentProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - props.put(BackgroundColorProperty, "The Background color for the image"); - props.put(BackgroundColorProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - props.put(WMSVersionProperty, "The WMS specification version"); - props.put(LayersProperty, "A list of layers to use in the query"); - props.put(StylesProperty, "A list of layer styles to use in the query"); - props.put(VendorSpecificNamesProperty, "Vendor-specific capability names to use in the query"); - props.put(VendorSpecificValuesProperty, "Vendor-specific capability values for the names"); - return props; - } - - public String getImageFormat() { - return imageFormat; - } - - public void setImageFormat(String newImageFormat) { - if (newImageFormat.indexOf('/') > 0) { - imageFormat = newImageFormat; - } else { - // convert "PNG" to "image/png" to be compatible with old OpenMap - // practice - imageFormat = "image/" + newImageFormat.toLowerCase(); - } - } - - public void setImageQuality(int newImageQuality) { - if (newImageQuality == WMSLayer.LOSSY_IMAGE_QUALITY_HIGH) - imageQuality = "HIGH"; - else if (newImageQuality == WMSLayer.LOSSY_IMAGE_QUALITY_MEDIUM) - imageQuality = "MEDIUM"; - else if (newImageQuality == WMSLayer.LOSSY_IMAGE_QUALITY_LOW) - imageQuality = "LOW"; - } - - public String getImageQuality() { - return imageQuality; - } - - public void setImageQuality(String imageQuality) { - this.imageQuality = imageQuality; - } - - public String getTransparent() { - return transparent; - } - - public void setTransparent(String transparent) { - if (transparent != null) { - transparent = Boolean.valueOf(transparent).toString().toUpperCase(); - } - this.transparent = transparent; - } - - public String getBackgroundColor() { - return backgroundColor; - } - - public void setBackgroundColor(String backgroundColor) { - if (backgroundColor != null) { - if (backgroundColor.length() > 6) { - backgroundColor = backgroundColor.substring(backgroundColor.length() - 6); - } - - if (!backgroundColor.startsWith("0x")) { - backgroundColor = "0x" + backgroundColor; - } - } - this.backgroundColor = backgroundColor; - } - - public String getErrorHandling() { - return errorHandling; - } - - public void setErrorHandling(String errorHandling) { - this.errorHandling = errorHandling; - } - - public String getLayers() { - return layers; - } - - public void setLayers(String layers) { - this.layers = layers; - } - - public String getMapRequestName() { - return mapRequestName; - } - - public void setMapRequestName(String mapRequestName) { - this.mapRequestName = mapRequestName; - } - - public String getQueryHeader() { - return queryHeader; - } - - public void setQueryHeader(String queryHeader) { - this.queryHeader = queryHeader; - } - - public String getStyles() { - return styles; - } - - public void setStyles(String styles) { - this.styles = styles; - } - - public String getVendorSpecificNames() { - return vendorSpecificNames; - } - - public void setVendorSpecificNames(String vendorSpecificNames) { - this.vendorSpecificNames = vendorSpecificNames; - } - - public String getVendorSpecificValues() { - return vendorSpecificValues; - } - - public void setVendorSpecificValues(String vendorSpecificValues) { - this.vendorSpecificValues = vendorSpecificValues; - } - - public String getWmsServer() { - return wmsServer; - } - - public void setWmsServer(String wmsServer) { - this.wmsServer = wmsServer; - } - - // make this better! - public String getServerName() { - return wmsServer; - } - - public String getWmsVersion() { - return wmsVersion; - } - - /** - * Does more than just set the version, it also adjusts other parameters - * based on version. Be careful calling this without knowing what it does - * and how it affects other settings. - * - * @param wmsVer - */ - public void setWmsVersion(String wmsVer) { - if (wmsVer == null || wmsVer.length() == 0) { - wmsVer = "1.1.1"; - Debug.output("WMSPlugin: wmsVersion was null, now set to 1.1.1"); - } - - if (Debug.debugging("wms")) { - Debug.output("WMSPlugIn: set up with header \"" + queryHeader + "\""); - } - - java.util.StringTokenizer st = new java.util.StringTokenizer(wmsVer, "."); - int majorVersion = Integer.parseInt(st.nextToken()); - int midVersion = Integer.parseInt(st.nextToken()); - int minorVersion = Integer.parseInt(st.nextToken()); - - // set the REQUEST parameter - if (majorVersion == 1 && midVersion == 0 && minorVersion < 3) { - mapRequestName = WMTConstants.MAP; - } - - // set the image type parameter - if (majorVersion == 1 && minorVersion > 7 && !imageFormat.startsWith("image/")) { - imageFormat = "image/" + imageFormat; - } - - // set the error handling parameter - if (majorVersion == 1 && midVersion == 0) { - errorHandling = "INIMAGE"; - } else if (majorVersion == 1 && midVersion >= 1 && minorVersion > 1) { - errorHandling = "application/vnd.ogc.se+inimage"; - } else if (majorVersion > 1) { - errorHandling = "application/vnd.ogc.se+inimage"; - } - - this.wmsVersion = wmsVer; - } - -} // end WMSLayer diff --git a/src/core/src/main/java/com/bbn/openmap/layer/image/WebImageLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/image/WebImageLayer.java deleted file mode 100644 index 5205c536b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/image/WebImageLayer.java +++ /dev/null @@ -1,233 +0,0 @@ -// Bart 20060831 -> i18n - -/* ********************************************************************** - * $Source: /home/cvs/nodus/src/com/bbn/openmap/plugin/WebImagePlugIn.java,v $ - * $Revision: 1.2 $ - * $Date: 2006-10-25 12:21:54 $ - * $Author: jourquin $ - * - * Code provided by Raj Singh from Syncline, rs@syncline.com - * Updates provided by Holger Kohler, Holger.Kohler@dsto.defence.gov.au - * ********************************************************************* - */ - -package com.bbn.openmap.layer.image; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.gui.MiniBrowser; -import com.bbn.openmap.image.ImageServerConstants; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.LLXY; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.PropUtils; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JOptionPane; -import javax.swing.JPanel; - -/** - * This class asks for an image from a web server. How it asks for that image is - * what is abstract. - */ -public abstract class WebImageLayer extends OMGraphicHandlerLayer implements ImageServerConstants { - - /** - * - */ - private static final long serialVersionUID = 1L; - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.image.WebImageLayer"); - - /** - * Create the query to be sent to the server, based on current settings. - */ - public abstract String createQueryString(Projection p); - - public abstract String getServerName(); - - /** - * OMGraphicHandlerLayer method that gets called when the projection - * changes. For this class, it takes the query string, contacts the server - * and handles the image data returned from the server. - * - * @return OMGraphicList to display for the current projection. - */ - public OMGraphicList prepare() { - OMGraphicList list = new OMGraphicList(); - Projection p = getProjection(); - - String urlString = createQueryString(p); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("WebImagePlugIn.getRectangle() with \"" + urlString + "\""); - } - - if (urlString == null) { - return new OMGraphicList(); - } - - java.net.URL url; - - try { - url = new java.net.URL(urlString); - java.net.HttpURLConnection urlc = (java.net.HttpURLConnection) url.openConnection(); - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "url content type: {0}", urlc.getContentType()); - } - - if (urlc == null || urlc.getContentType() == null) { - fireRequestMessage(getName() + ": unable to connect to " + getServerName()); - return list; - } - - // text - if (urlc.getContentType().startsWith("text")) { - java.io.BufferedReader bin = new java.io.BufferedReader(new java.io.InputStreamReader(urlc.getInputStream())); - String st; - StringBuffer message = new StringBuffer(); - while ((st = bin.readLine()) != null) { - message.append(st); - } - - // Debug.error(message.toString()); - // How about we toss the message out to the user - // instead? - fireRequestMessage(message.toString()); - - // image - } else if (urlc.getContentType().startsWith("image")) { - - // the best way, no reconnect, but can be an - // additional 'in memory' image - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - ImageIcon ii = new ImageIcon(out.toByteArray()); - - // -------- To here, replaced by two lines below... - - // DFD - I've seen problems with these lines below handling PNG - // images, and with some servers with some coverages, like there - // was something in the image under certain conditions that made - // it tough to view. So while it might be more memory efficient - // to do the code below, we'll error on the side of correctness - // until we figure out what's going on. - - // FileCacheImageInputStream fciis = new - // FileCacheImageInputStream(in, null); - // BufferedImage ii = ImageIO.read(fciis); - - if (p instanceof LLXY) { - // EPSG:4326, just put it on the screen - OMRaster image = new OMRaster((int) 0, (int) 0, ii); - list.add(image); - } else { - Point2D ul = p.getUpperLeft(); - Point2D lr = p.getLowerRight(); - OMScalingRaster omsr = new OMScalingRaster(ul.getY(), ul.getX(), lr.getY(), lr.getX(), ii); - - OMWarpingImage omwi = new OMWarpingImage(omsr, LatLonGCT.INSTANCE); - list.add(omwi); - } - - } // end if image - } catch (java.net.MalformedURLException murle) { - logger.warning("WebImagePlugIn: URL \"" + urlString + "\" is malformed."); - } catch (java.io.IOException ioe) { - JOptionPane.showMessageDialog(null, getName() + ":\n\n Couldn't connect to " - + getServerName(), "Connection Problem", JOptionPane.INFORMATION_MESSAGE); - - } - - list.generate(p); - return list; - } // end prepare - - @Override - public java.awt.Component getGUI() { - JPanel panel = new JPanel(new GridLayout(0, 1)); - JButton parameterButton = new JButton(i18n.get(WebImageLayer.class, "Adjust_Parameters", "Adjust Parameters")); - - parameterButton.setActionCommand(Layer.DisplayPropertiesCmd); - parameterButton.addActionListener(this); - - JButton viewQueryButton = new JButton(i18n.get(WebImageLayer.class, "View_Current_Query", "View Current Query")); - JButton redrawButton = new JButton(i18n.get(WebImageLayer.class, "Query_Server", "Query Server")); - - viewQueryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - - String query = createQueryString(getProjection()); - List queryStrings = PropUtils.parseMarkers(query, "&"); - StringBuffer updatedQuery = new StringBuffer(); - Iterator it = queryStrings.iterator(); - if (it.hasNext()) { - updatedQuery.append(it.next()); - } - while (it.hasNext()) { - updatedQuery.append("&\n "); - updatedQuery.append(it.next()); - } - - if (logger.isLoggable(Level.FINE)) { - String stb = "Send Query to Browser"; - String ok = "OK"; - - Object[] options = new Object[] { stb, ok }; - int selectedVal = JOptionPane.showOptionDialog(null, updatedQuery, "Current Query for " - + getName(), JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, ok); - - if (selectedVal == 0) { - try { - new MiniBrowser(new URL(query)); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - - } else { - JOptionPane.showMessageDialog(null, updatedQuery.toString(), "Current Query for " - + getName(), JOptionPane.INFORMATION_MESSAGE); - } - - } - }); - - redrawButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - doPrepare(); - } - }); - - panel.add(parameterButton); - panel.add(viewQueryButton); - panel.add(redrawButton); - return panel; - } - -} // end WebImageLayer diff --git a/src/core/src/main/java/com/bbn/openmap/layer/learn/BasicLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/learn/BasicLayer.java deleted file mode 100644 index 0cb041d8d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/learn/BasicLayer.java +++ /dev/null @@ -1,175 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/learn/BasicLayer.java,v $ -// $RCSfile: BasicLayer.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/02/26 16:56:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.learn; - -import java.awt.BasicStroke; -import java.awt.Color; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMTextLabeler; - -/** - * This layer is a good place to start learning how to create OpenMap layers. It - * extends OMGraphicHandler, which contains a good bit of functionality, but - * exposes only the methods you need to start putting features (OMGraphics) on - * the map. - * - * Note that this is a layer where the objects never change, and the map objects - * used by this layer never change. They always get managed and drawn, even if - * they are off the visible map. When the projection changes, the OMGraphics are - * told what the new projection is so they can reposition themselves, and then - * they are redrawn. - * - * If you want the OMGraphics on the layer to change depending on where the map - * view is, look at ProjectionResponseLayer. You'll want to look at that layer - * if you have a lot of map stuff to display on your layer, so you only render - * what you need. - * - * If you want to learn more about interacting with your OMGraphics after you - * get the hang of displaying them efficiently, then move to the - * InteractionLayer. - */ -public class BasicLayer - extends OMGraphicHandlerLayer { - - /** - * The empty constructor is necessary for any layer being created using the - * openmap.properties file, via the openmap.layers property. This method - * needs to be public, too. Don't try to do too much in the constructor - - * remember, this code gets executed whether the user uses the layer or not. - * Performance-wise, it's better to do most initialization the first time the - * layer is made part of the map. You can test for that in the prepare() - * method, by testing whether the OMGraphicList for the layer is null or not. - * - * @see #prepare - */ - public BasicLayer() { - // Sets the name of the layer that is visible in the GUI. Can also be - // set with properties with the 'prettyName' property. - setName("Basic Layer"); - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. The StandardPCPolicy is the default policy and you don't - // need to set it, this method call is here to illustrate where and how - // you would make that call with a different policy. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, true)); - // Improves performance - setRenderPolicy(new BufferedImageRenderPolicy()); - } - - /** - * This is an important Layer method to override. The prepare method gets - * called when the layer is added to the map, or when the map projection - * changes. We need to make sure the OMGraphicList returned from this method - * is what we want painted on the map. The OMGraphics need to be generated - * with the current projection. We test for a null OMGraphicList in the layer - * to see if we need to create the OMGraphics. This layer doesn't change its - * OMGraphics for different projections, if your layer does, you need to - * clear out the OMGraphicList and add the OMGraphics you want for the - * current projection. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList list = getList(); - - // Here's a test to see if it's the first time that the layer has been - // added to the map. This list object will be whatever was returned from - // this method the last time prepare() was called. In this - // example, we always return an OMGraphicList object, so if it's null, - // prepare() must not have been called yet. - - if (list == null) { - list = init(); - } - - /* - * This call to the list is critical! OMGraphics need to be told where to - * paint themselves, and they figure that out when they are given the - * current Projection in the generate(Projection) call. If an OMGraphic's - * location is changed, it will need to be regenerated before it is - * rendered, otherwise it won't draw itself. You generally know you have a - * generate problem when OMGraphics show up with the projection changes - * (zooms and pans), but not at any other time after something about the - * OMGraphic changes. - * - * If you want to be more efficient, you can replace this call to the list - * as an else clause to the (list == null) check above, and call - * generate(Projection) on all the OMGraphics in the init() method below - * as you create them. This will prevent the - * OMGraphicList.generate(Projection) call from making an additional loop - * through all of the OMGraphics before they are returned. - */ - list.generate(getProjection()); - - return list; - } - - /** - * Called from the prepare() method if the layer discovers that its - * OMGraphicList is null. - * - * @return new OMGraphicList with OMGraphics that you always want to display - * and reproject as necessary. - */ - public OMGraphicList init() { - - // This layer keeps a pointer to an OMGraphicList that it uses - // for painting. It's initially set to null, which is used as - // a flag in prepare() to signal that the OMGraphcs need to be - // created. The list returned from prepare() gets set in the - // layer. - // This layer uses the StandardPCPolicy for new - // projections, which keeps the list intact and simply calls - // generate() on it with the new projection, and repaint() - // which calls paint(). - - OMGraphicList omList = new OMGraphicList(); - - // Add an OMLine - OMLine line = new OMLine(40f, -145f, 42f, -70f, OMGraphic.LINETYPE_GREATCIRCLE); - // line.addArrowHead(true); - line.setStroke(new BasicStroke(2)); - line.setLinePaint(Color.red); - line.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("Line Label")); - - omList.add(line); - - // Add a list of OMPoints. - OMGraphicList pointList = new OMGraphicList(); - for (int i = 0; i < 100; i++) { - OMPoint point = new OMPoint((float) (Math.random() * 89f), (float) (Math.random() * -179f), 3); - point.setFillPaint(Color.yellow); - point.setOval(true); - pointList.add(point); - } - omList.add(pointList); - - return omList; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/learn/InteractionLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/learn/InteractionLayer.java deleted file mode 100644 index 506be1220..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/learn/InteractionLayer.java +++ /dev/null @@ -1,289 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/learn/InteractionLayer.java,v $ -// $RCSfile: InteractionLayer.java,v $ -// $Revision: 1.2 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.learn; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMTextLabeler; - -/** - * This layer demonstrates how to interact with your OMGraphics on the map, - * getting them to change appearance with mouse events and provide additional - * information about themselves. This layer builds on the example demonstrated - * in the BasicDisplayLayer, which involved creating OMGraphics for the map. For - * any of the methods listed below that are designed to assist with responding - * to mouse events, simply return null from them if you want a no-op, which is - * the default implementation in the OMGraphicHandlerLayer (so don't even - * override them). - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#isHighlightable - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#highlight - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#unhighlight - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#getInfoText - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#getToolTipText - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#isSelectable - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#select - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#deselect - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#getItemsForMapMenu - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#getItemsForOMGraphicMenu - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#receivesMapEvents - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#mouseOver(MapMouseEvent) - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#leftClick - */ -public class InteractionLayer extends BasicLayer { - - public InteractionLayer() { - // Sets the name of the layer that is visible in the GUI. Can also be - // set with properties with the 'prettyName' property. - setName("Interaction Layer"); - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. The StandardPCPolicy is the default policy and you don't - // need to set it, this method call is here to illustrate where and how - // you would make that call with a different policy. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, true)); - // Making the setting so this layer receives events from the - // SelectMouseMode, which has a modeID of "Gestures". Other - // IDs can be added as needed. You need to tell the layer which - // MouseMode it should listen to, so it can tell the MouseModes to send - // events to it. - setMouseModeIDsForEvents(new String[] { "Gestures" }); - - // Instead of "Gestures", you can also use SelectMouseMode.modeID or OMMouseMode.modeID - } - - /** - * Called from the prepare() method if the layer discovers that its - * OMGraphicList is null. This method is being overridden so that TOOLTIPS - * can be set as attributes on the OMGraphics, and retrieved later in the - * gesturing queries. - * - * @return new OMGraphicList with OMGraphics that you always want to display - * and reproject as necessary. - * - * @see BasicLayer#prepare - */ - public OMGraphicList init() { - - // This layer keeps a pointer to an OMGraphicList that it uses - // for painting. It's initially set to null, which is used as - // a flag in prepare() to signal that the OMGraphcs need to be - // created. The list returned from prepare() gets set in the - // layer. - // This layer uses the StandardPCPolicy for new - // projections, which keeps the list intact and simply calls - // generate() on it with the new projection, and repaint() - // which calls paint(). - - /* - * Note that the OMGraphics have their select paint set in order to - * react to highlight calls, and an OMGraphicConstants.TOOLTIP - * attribute set to provide tooltip text when needed. - */ - - OMGraphicList omList = new OMGraphicList(); - - // Add an OMLine - OMLine line = new OMLine(40f, -75f, 42f, -70f, OMGraphic.LINETYPE_GREATCIRCLE); - line.setStroke(new BasicStroke(2)); - line.putAttribute(OMGraphicConstants.LABEL, - new OMTextLabeler("Line Label")); - line.setLinePaint(Color.red); - line.setSelectPaint(Color.blue); - line.putAttribute(OMGraphicConstants.TOOLTIP, "This is an OMLine."); - - omList.add(line); - - // Add a list of OMPoints. - OMGraphicList pointList = new OMGraphicList(); - for (int i = 0; i < 100; i++) { - OMPoint point = new OMPoint((float) (Math.random() * 89f), (float) (Math.random() * -179f), 3); - point.putAttribute(OMGraphicConstants.TOOLTIP, "This is OMPoint #" - + i); - point.setLinePaint(Color.green); - point.setSelectPaint(Color.yellow); - pointList.add(point); - } - omList.add(pointList); - - return omList; - } - - /** - * Query that an OMGraphic can be highlighted when the mouse moves over it. - * If the answer is true, then highlight with this OMGraphics will be - * called, and unhighlight will be called with the mouse is moved off of it. - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#highlight - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#unhighlight - */ - public boolean isHighlightable(OMGraphic omg) { - return true; - } - - /** - * Query that an OMGraphic is selectable. Examples of handing selection are - * in the EditingLayer. The default OMGraphicHandlerLayer behavior is to add - * the OMGraphic to an OMGraphicList called selectedList. If you aren't - * going to be doing anything in particular with the selection, then return - * false here to reduce the workload of the layer. - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#select - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#deselect - */ - public boolean isSelectable(OMGraphic omg) { - return true; - } - - /** - * Designate a list of OMGraphics as selected. - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#select - */ - public void select(OMGraphicList list) { - super.select(list); - - // selectedList is a member variable held by OMGraphicHandlerLayer. - if (selectedList != null) { - System.out.println("Current selection list: " + selectedList.getDescription()); - } - } - - /** - * Designate a list of OMGraphics as deselected. - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#deselect - */ - public void deselect(OMGraphicList list) { - super.deselect(list); - - // selectedList is a member variable held by OMGraphicHandlerLayer. - if (selectedList != null) { - System.out.println("Current selection list: " + selectedList.getDescription()); - } - } - - /** - * Query for what text should be placed over the information bar when the - * mouse is over a particular OMGraphic. - */ - public String getInfoText(OMGraphic omg) { - String classname = omg.getClass().getName(); - return "Interaction Layer OMGraphic - " - + classname.substring(classname.lastIndexOf('.') + 1); - } - - /** - * Query for what tooltip to display for an OMGraphic when the mouse is over - * it. - */ - public String getToolTipTextFor(OMGraphic omg) { - Object tt = omg.getAttribute(OMGraphic.TOOLTIP); - if (tt instanceof String) { - return (String) tt; - } else { - return null; - } - } - - /** - * This method is called when a right mouse click is detected over the map - * and not over an OMGraphic. You can provide a List of components to be - * displayed in a popup menu. You have to do the wiring for making the list - * components do something, though. - */ - public List getItemsForMapMenu(MapMouseEvent me) { - List l = new ArrayList(); - JMenuItem when = new JMenuItem("When"); - when.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - fireRequestMessage("When was chosen."); - } - }); - JMenuItem where = new JMenuItem("Where"); - where.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - fireRequestMessage("Where was chosen."); - } - }); - JMenuItem how = new JMenuItem("How"); - how.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - fireRequestMessage("How was chosen."); - } - }); - - l.add(when); - l.add(where); - l.add(how); - - return l; - } - - /** - * This method is called when a right mouse click is detected over an - * OMGraphic. You can provide a List of components to be displayed in a - * popup menu. You have to do the wiring for making the list components do - * something, though. - */ - public List getItemsForOMGraphicMenu(OMGraphic omg) { - final OMGraphic chosen = omg; - List l = new ArrayList(); - JMenuItem which = new JMenuItem("Which"); - which.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String classname = chosen.getClass().getName(); - fireRequestMessage("Which was chosen over " - + classname.substring(classname.lastIndexOf('.') + 1)); - } - }); - JMenuItem why = new JMenuItem("Why"); - why.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String classname = chosen.getClass().getName(); - fireRequestMessage("Why was chosen over " - + classname.substring(classname.lastIndexOf('.') + 1)); - } - }); - - l.add(which); - l.add(why); - return l; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/learn/ProjectionResponseLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/learn/ProjectionResponseLayer.java deleted file mode 100644 index af1f2e2d0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/learn/ProjectionResponseLayer.java +++ /dev/null @@ -1,185 +0,0 @@ - -package com.bbn.openmap.layer.learn; - -import java.awt.Color; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DataBounds; - -/** - * This layer demonstrates how to use the projection to update the OMGraphics a - * Layer is managing when the map view changes. - * - * If you aren't sure how Layers manage OMGraphics, check out the BasicLayer - * first. - */ -public class ProjectionResponseLayer - extends OMGraphicHandlerLayer { - - /** - * The empty constructor is necessary for any layer being created using the - * openmap.properties file, via the openmap.layers property. This method - * needs to be public, too. Don't try to do too much in the constructor - - * remember, this code gets executed whether the user uses the layer or not. - * Performance-wise, it's better to do most initialization the first time - * the layer is made part of the map. You can test for that in the prepare() - * method, by testing whether the OMGraphicList for the layer is null or - * not. - * - * @see #prepare - */ - public ProjectionResponseLayer() { - // Sets the name of the layer that is visible in the GUI. Can also be - // set with properties with the 'prettyName' property. - setName("Projection Response Layer"); - - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. The ListResetPCPolicy is a policy that clears out the old - // OMGraphicList when the projection changes so that old data doesn't - // get redrawn on the map before this layer has the chance to update the - // list it renders. - - // Remember, you don't have control over when paint() gets called on - // this layer. All layers work independently, so if other layers finish - // handling the projection change before this one, they will request to - // be painted. This will cause paint() to be called on all - // layers that are on/visible/part of the map. If the layer is still in - // the prepare() method when those paint() calls are made, you want to - // make sure your layer doesn't render anything if your layer's list is - // from the old projection. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - // Improves performance - setRenderPolicy(new BufferedImageRenderPolicy()); - - } - - /** - * This is an important Layer method to override. The prepare method gets - * called when the layer is added to the map, or when the map projection - * changes. We need to make sure the OMGraphicList returned from this method - * is what we want painted on the map. The OMGraphics need to be generated - * with the current projection. - */ - public synchronized OMGraphicList prepare() { - - // We're going to create a new OMGraphicList to return from this - // projection change. The ListRestPCPolicy has already taken care of - // removing the OMGraphics from the current list (if it exists) so we - // can just ignore that for now. - - OMGraphicList list = new OMGraphicList(); - - Projection proj = getProjection(); - - // Just a safety check in case someone calls prepare without ever adding - // it to the map. - if (proj == null) { - return list; - } - - Point2D upperLeft = proj.getUpperLeft(); - Point2D lowerRight = proj.getLowerRight(); - - /** - * Now, upperLeft and lowerRight are the coordinate bounds covered by - * the map. You can use those bounds to filter data. - * - * One other thing. OpenMap projections can only cover a maximum of 360 - * degrees. So to test for the date line, you can check the longitudes - * of the corners. If the x value of the left side is greater than the x - * value of the right side, the map is covering the date line. - */ - - if (upperLeft.getX() > lowerRight.getX()) { - // crossing the date line. Depending on your data source, you may - // need to make two queries for your data, one for the left side of - // date line, one for the right side. If you want to see what - // happens without this check, go ahead and comment these two lines - // out. - - // Make query for map on left side of date line - getPoints(new DataBounds(upperLeft, new Point2D.Double(180, lowerRight.getY())), list, proj); - // Make query for map on right side if date line - getPoints(new DataBounds(new Point2D.Double(-180, upperLeft.getY()), lowerRight), list, proj); - - } else { - getPoints(new DataBounds(upperLeft, lowerRight), list, proj); - } - - // Let's add a little statement in the lower left corner of the map - // describing the number of OMPoints created and drawn. - OMText statement = - new OMText(10, proj.getHeight() - 10, getName() + " displaying " + list.size() + "/" + dataSource.size() - + " points", OMText.JUSTIFY_LEFT); - // Just to add a little background behind the letters. - statement.setFillPaint(Color.gray); - // Have to generate the OMText, too. - statement.generate(proj); - // Add it to the front of the list, so it's on top. - list.add(0, statement); - - return list; - } - - /** Some make-believe source of data. */ - protected List dataSource; - - /** - * Using this method to look at data source and create OMGraphics based on - * DataBounds, and render them differently depending on where they are. - * - * @param dataBounds the bounds of the map projection. - * @param retList the list to add new OMGraphics to. - * @param proj the projection to use for generating OMGraphics. If we pass - * the projection to the point where the OMGraphics are created and - * generate them at creation time, we save ourselves another loop - * through the OMGraphicList to generate them later. - */ - protected void getPoints(DataBounds dataBounds, OMGraphicList retList, Projection proj) { - - if (dataSource == null) { - // For lack of having a data source, lets just create one on the - // fly. - dataSource = initSource(); - } - - for (Point2D point : dataSource) { - if (dataBounds.contains(point)) { - OMPoint newPoint = new OMPoint(point.getY(), point.getX()); - // Color western points green, eastern points yellow - newPoint.setFillPaint(point.getX() < 0 ? Color.green : Color.yellow); - newPoint.generate(proj); - retList.add(newPoint); - } - } - } - - /** - * Just creating a set of Points to use as data source. - * - * @return List of Point2D objects in a grid. - */ - protected List initSource() { - List source = new ArrayList(); - - for (double y = -85; y <= 85; y++) { - for (double x = -180; x < 180; x++) { - source.add(new Point2D.Double(x, y)); - } - } - - logger.fine("created source with " + source.size() + " points"); - - return source; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/learn/SimpleAnimationLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/learn/SimpleAnimationLayer.java deleted file mode 100644 index c3967760f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/learn/SimpleAnimationLayer.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * - * Copyright 2013 BBN Technologies - * - */ -package com.bbn.openmap.layer.learn; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.Timer; -import java.util.TimerTask; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * A simple demonstration of doing animation on a Layer. This layer has a GUI - * interface to add/remove points on the map, and they are moved randomly based - * on timer intervals. All the parameters can be modified in the GUI. - * - * This layer uses code fetched from the AnimationTester and - * AbstractGraphicLoader. - * - * @author dietrick - */ -public class SimpleAnimationLayer extends OMGraphicHandlerLayer { - - /** - * Managed list of moving points, separate from the OMGraphicList the layer - * will use to paint on the map. The objects on the lists are the same, but - * the lists holding them are different to allow one list to be modified - * without affecting the actions being performed on the other (concurrent - * modification). - */ - OMGraphicList movingPoints = new OMGraphicList(); - /** - * A movement factor for the points. - */ - double movementFactor = 4.0; - /** - * Timer used to drive the animation for the layer. - */ - Timer timer; - /** - * The timer interval used to make the sprites move. - */ - int timerDelay = 3000; - - public SimpleAnimationLayer() { - } - - /** - * The prepare method always returns the OMGraphicList to be drawn on the - * map. We're assuming that movingPoints holds the OMPoints as they are - * modified. We need to create a separate OMGraphicList to return for - * painting after we call generate() on the OMGraphics with the current map. - * If we forget to call generate(), the OMGraphics will not know where they - * are on the map, and they won't drawn themselves. - * - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer#prepare() - */ - public synchronized OMGraphicList prepare() { - OMGraphicList ret = new OMGraphicList(movingPoints); - ret.generate(getProjection()); - // The ret list is the one used for painting. - return ret; - } - - /** - * Called when the layer is removed from the map. Cleanup! - */ - public void removed(Container cont) { - movingPoints.clear(); - stopTimer(); - } - - /** - * Create a new point for the list. We're going to look at the current - * projection and find some random point within the height and width of the - * map. If the projection isn't set on the layer yet (it hasn't been added - * to the map), no point will be added. - */ - public void addMovingPoint() { - - Projection proj = getProjection(); - - if (proj == null) { - return; - } - - int numOfSpritesToAdd = 1; - - if (spinner != null) { - try { - numOfSpritesToAdd = Integer.parseInt(spinner.getValue().toString()); - } catch (NumberFormatException nfe) { - spinner.setValue(1); - } - } - - double mapHeight = proj.getHeight(); - double mapWidth = proj.getWidth(); - - for (int i = 0; i < numOfSpritesToAdd; i++) { - - double ranY = (Math.random() * mapHeight); - double ranX = (Math.random() * mapWidth); - - Point2D newLoc = proj.inverse(ranX, ranY); - - OMPoint point = new OMPoint(newLoc.getY(), newLoc.getX(), 5); - point.setFillPaint(Color.red); - movingPoints.add(point); - } - - spriteCountLabel.setText(Integer.toString(movingPoints.size())); - - // Update the map - doPrepare(); - } - - /** - * Clears the point list. - */ - public void clearMovingPoints() { - movingPoints.clear(); - spriteCountLabel.setText(Integer.toString(movingPoints.size())); - // Update the map - doPrepare(); - stopTimer(); - } - - /** - * Called when the timer should be stopped. - */ - public void stopTimer() { - if (timer != null) { - timer.cancel(); - timer.purge(); - timer = null; - } - - if (timerButton != null) { - timerButton.setSelected(false); - } - } - - /** - * Called when the timer should be started. - * - * @param interval the interval that the timer task gets executed on. - */ - public void resetTimer(int interval) { - timerDelay = interval; - - stopTimer(); - - timer = new Timer(); - timer.scheduleAtFixedRate(new ManageGraphicsTask(SimpleAnimationLayer.this), 0, timerDelay); - - if (timerButton != null) { - timerButton.setSelected(true); - } - } - - JPanel panel = null; - JButton addButton = null; - JCheckBox timerButton = null; - JSpinner spinner = null; - JLabel spriteCountLabel = null; - - /** - * This method is called by other OpenMap components to present a GUI - * interface to a user. We keep an handle to a panel that we reuse for later - * requests. - */ - public Component getGUI() { - if (panel == null) { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - panel = new JPanel(gridbag); - - addButton = new JButton("Add Sprites"); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - addMovingPoint(); - } - }); - - c.insets = new Insets(5, 5, 5, 2); - c.anchor = GridBagConstraints.NORTHWEST; - gridbag.setConstraints(addButton, c); - panel.add(addButton); - - JButton clearButton = new JButton("Clear Sprites"); - clearButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - clearMovingPoints(); - } - }); - - c.insets = new Insets(5, 2, 5, 5); - c.anchor = GridBagConstraints.NORTHEAST; - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(clearButton, c); - panel.add(clearButton); - - JLabel numSpritesLabel = new JLabel("Number of Sprites to Add:"); - SpinnerModel numSpritesSpinnerModel = new SpinnerNumberModel(1, 1, 50, 1); - spinner = new JSpinner(numSpritesSpinnerModel); - numSpritesLabel.setLabelFor(spinner); - - c.insets = new Insets(0, 5, 5, 5); - c.anchor = GridBagConstraints.WEST; - c.gridwidth = GridBagConstraints.RELATIVE; - - gridbag.setConstraints(numSpritesLabel, c); - panel.add(numSpritesLabel); - - c.anchor = GridBagConstraints.EAST; - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(spinner, c); - panel.add(spinner); - - JLabel numMapSpritesLabel = new JLabel("Number of Sprites on Map:"); - spriteCountLabel = new JLabel(Integer.toString(movingPoints.size())); - - c.insets = new Insets(0, 5, 5, 5); - c.anchor = GridBagConstraints.WEST; - c.gridwidth = GridBagConstraints.RELATIVE; - - gridbag.setConstraints(numMapSpritesLabel, c); - panel.add(numMapSpritesLabel); - - c.anchor = GridBagConstraints.EAST; - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(spriteCountLabel, c); - panel.add(spriteCountLabel); - - JSlider slider = new JSlider(JSlider.HORIZONTAL, 0/* min */, 20/* max */, 10/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(5), new JLabel(".5")); - dict.put(new Integer(10), new JLabel("1")); - dict.put(new Integer(15), new JLabel("1.5")); - dict.put(new Integer(20), new JLabel("2")); - slider.setLabelTable(dict); - slider.setPaintLabels(true); - slider.setMajorTickSpacing(2); - slider.setPaintTicks(true); - - slider.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider2 = (JSlider) ce.getSource(); - if (slider2.getValueIsAdjusting()) { - float interval = ((float) (slider2.getValue()) + .01f) * 100f; - Debug.output("SimpleAnimationLayer delay set to: " + interval / 1000f - + " seconds"); - resetTimer((int) interval); - } - } - }); - - JPanel sliderPanel = PaletteHelper.createHorizontalPanel("Timer interval in seconds:"); - sliderPanel.add(slider); - - c.insets = new Insets(0, 5, 5, 5); - c.anchor = GridBagConstraints.WEST; - c.gridwidth = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0; - gridbag.setConstraints(sliderPanel, c); - panel.add(sliderPanel); - - timerButton = new JCheckBox("Run Timer", timer != null); - timerButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox check = (JCheckBox) ae.getSource(); - if (check.isSelected()) { - resetTimer(timerDelay); - } else { - stopTimer(); - } - } - }); - - gridbag.setConstraints(timerButton, c); - panel.add(timerButton); - - } - return panel; - } - - /** - * This is a TimerTask the timer uses to tell the points to update their - * position. - * - * This is where you would do work to change the position of your OMGraphics - * - whether by reading a data file, or checking a web site, whatever. This - * method could also be the call another object could call with new - * OMGraphics to display, if you wanted a different object to control the - * updates. - */ - public class ManageGraphicsTask extends TimerTask { - - final SimpleAnimationLayer sal; - - public ManageGraphicsTask(SimpleAnimationLayer layer) { - sal = layer; - } - - /* - * (non-Javadoc) - * - * @see java.util.TimerTask#run() - */ - @Override - public void run() { - Projection proj = sal.getProjection(); - OMGraphicList safeList = new OMGraphicList(sal.movingPoints); - - for (OMGraphic point : safeList) { - if (point instanceof OMPoint) { - moveRandomly((OMPoint) point, sal.movementFactor, proj); - } else if (point instanceof OMScalingIcon) { - moveRandomly((OMScalingIcon) point, sal.movementFactor, proj); - } - - if (proj != null) { - point.generate(proj); - } - } - - /* - * We have a couple of options here. We could call doPrepare(), - * which will launch a separate thread to call prepare() and - * repaint(). prepare() will call generate() on all the OMGraphics, - * but we've already done that above. So we can ask for the event - * thread to paint the layer by calling repaint(). This saves us - * from launching a separate thread to do the same thing. If we - * didn't call generate() on the points above, we would have to call - * doPrepare() instead of repaint(), because the points need to be - * generated after they are moved, in order to know where they get - * drawn. - */ - sal.repaint(); - } - - /** - * Simple method to move an OMPoint around randomly. - * - * @param point the OMPoint to move. - * @param factor a movement factor, in pixels. - * @param proj the current map projection - */ - protected void moveRandomly(OMPoint point, double factor, Projection proj) { - double hor = Math.random() - .5; - double vert = Math.random() - .5; - - Point2D mapPoint = proj.forward(point.getLat(), point.getLon()); - mapPoint.setLocation(mapPoint.getX() + (hor * factor), mapPoint.getY() - + (vert * factor)); - Point2D llp = proj.inverse(mapPoint); - - point.setLat(llp.getY()); - point.setLon(llp.getX()); - } - - /** - * Simple method to move an OMPoint around randomly. - * - * @param point the OMPoint to move. - * @param factor a movement factor, in pixels. - * @param proj the current map projection - */ - protected void moveRandomly(OMScalingIcon point, double factor, Projection proj) { - double hor = Math.random() - .5; - double vert = Math.random() - .5; - - Point2D mapPoint = proj.forward(point.getLat(), point.getLon()); - mapPoint.setLocation(mapPoint.getX() + (hor * factor), mapPoint.getY() - + (vert * factor)); - Point2D llp = proj.inverse(mapPoint); - - point.setLat(llp.getY()); - point.setLon(llp.getX()); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/BufferedLinkLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/link/BufferedLinkLayer.java deleted file mode 100644 index 0f13683bf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/BufferedLinkLayer.java +++ /dev/null @@ -1,220 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/BufferedLinkLayer.java,v $ -// $RCSfile: BufferedLinkLayer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/* Java Core */ -import java.awt.geom.Point2D; -import java.io.IOException; -import java.net.UnknownHostException; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The BufferedLinkLayer is a Swing component, and an OpenMap layer, - * that communicates with a server via the Link protocol. It transmits - * graphics requests and gesture information, and handles the - * responses to those queries. The entry in the openmap.properties - * file looks like this: - *

- * - * # port number of server - * link.port=3031 - * # host name of server - * link.host=host.com - * # URL of properties file for server attributes - * link.propertiesURL=http://location.of.properties.file.com - * - */ -public class BufferedLinkLayer extends LinkLayer { - - /** - * The default constructor for the Layer. All of the attributes - * are set to their default values. - */ - public BufferedLinkLayer() { - super(); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this)); - } - - /** - * Constructor to use when LinkLayer is not being used with - * OpenMap application. - * - * @param host the hostname of the server's computer. - * @param port the port number of the server. - * @param propertiesURL the URL of a properties file that contains - * parameters for the server. - */ - public BufferedLinkLayer(String host, int port, String propertiesURL) { - super(host, port, propertiesURL); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this)); - } - - /** - * Prepares the graphics for the layer. This is where the - * getRectangle() method call is made on the link. - *

- * Occasionally it is necessary to abort a prepare call. When this - * happens, the map will set the cancel bit in the LayerThread, - * (the thread that is running the prepare). If this Layer needs - * to do any cleanups during the abort, it should do so, but - * return out of the prepare asap. - * - * @return a list of graphics. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - System.err.println("Link Layer needs to be added to the MapBean before it can get graphics!"); - return new LinkOMGraphicList(); - } - - Debug.message("basic", getName() - + "|BufferedLinkLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // LinkOMGraphicList is made up of OMGraphics, which are - // generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - OMGraphicList omGraphics = getList(); - - if (omGraphics == null || omGraphics.isEmpty()) { - - ////////////// Call getRectangle for server.... - try { - // We do want the link object here... If another - // thread is - // using the link, wait. - ClientLink l = linkManager.getLink(true); - - if (l == null) { - System.err.println("BufferedLinkLayer: unable to get link in prepare()."); - return new LinkOMGraphicList(); - } - - synchronized (l) { - omGraphics = getAllGraphics(l, projection); - } - - linkManager.finLink(); - - } catch (UnknownHostException uhe) { - System.err.println("BufferedLinkLayer: unknown host!"); - omGraphics = new LinkOMGraphicList(); - } catch (java.io.IOException ioe) { - System.err.println("BufferedLinkLayer: IOException contacting server for map request!"); - System.err.println(ioe); - - linkManager.resetLink(); - - if (!quiet) { - fireRequestMessage("Communication error between " - + getName() + " layer\nand Link Server: Host: " - + host + ", Port: " + port); - } - - System.err.println("BufferedLinkLayer: Communication error between " - + getName() - + " layer\nand Link Server: Host: " - + host - + ", Port: " + port); - - omGraphics = new LinkOMGraphicList(); - } - } else { - omGraphics.project(projection); - } - - ///////////////////// - // safe quit - int size = 0; - if (omGraphics != null) { - size = omGraphics.size(); - - if (Debug.debugging("basic")) { - System.out.println(getName() - + "|BufferedLinkLayer.prepare(): finished with " + size - + " graphics"); - } - } else { - Debug.message("basic", - getName() - + "|BufferedLinkLayer.prepare(): finished with null graphics list"); - } - - return omGraphics; - } - - /** - * Creates the LinkMapRequest, and gets the results. - * - * @param link the link to communicate over. - * @param proj the projection to give to the graphics. - * @return LinkOMGraphicList containing graphics from the server. - * @throws IOException - */ - protected LinkOMGraphicList getAllGraphics(ClientLink link, Projection proj) - throws IOException { - - LinkBoundingPoly[] boundingPolys = new LinkBoundingPoly[1]; - boundingPolys[0] = new LinkBoundingPoly(-180.0f, -90f, 180f, 90); - - - Point2D center = proj.getCenter(); - LinkMapRequest.write((float) center.getY(), - (float) center.getX(), - proj.getScale(), - proj.getHeight(), - proj.getWidth(), - boundingPolys, - args, - link); - - link.readAndParse(proj, currentGenerator); - - // While we are here, check for any change in gesture query - // requests. - LinkActionRequest lar = link.getActionRequest(); - if (lar != null) { - setGestureDescriptor(lar.getDescriptor()); - } - - LinkGraphicList lgl = link.getGraphicList(); - if (lgl != null) { - //Deal with all the messaging.... - handleMessages(lgl.getProperties()); - return lgl.getGraphics(); - } else { - Debug.message("link", - "BufferedLinkLayer: getAllGraphics(): no graphic response."); - return new LinkOMGraphicList(); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/ClientLink.java b/src/core/src/main/java/com/bbn/openmap/layer/link/ClientLink.java deleted file mode 100644 index e1feee43d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/ClientLink.java +++ /dev/null @@ -1,58 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/ClientLink.java,v $ -// $RCSfile: ClientLink.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; -import java.net.Socket; - -/** - * The ClientLink provides the method to close the link down, since it - * makes that decision. The server should remain connected until the - * client is finished. The server can request to be disconnected, - * however, and the ClientLink provides a method for the client to - * check if that request has been made. - */ -public class ClientLink extends Link { - - /** Constructor. */ - public ClientLink(Socket socket) throws IOException { - super(socket); - } - - /** Close the socket of the link. */ - public void close() throws IOException { - socket.close(); - } - - /** - * A method used by the client after a communication exchange. - * Since the client is the side of the link that can close the - * link, it can find out if the server wants to close down the - * link with this method. - * - * @return true if the link should be shut down. - */ - public boolean isCloseLink() { - return closeLink; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/GraphicUpdate.java b/src/core/src/main/java/com/bbn/openmap/layer/link/GraphicUpdate.java deleted file mode 100644 index a68d926d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/GraphicUpdate.java +++ /dev/null @@ -1,61 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/GraphicUpdate.java,v $ -// $RCSfile: GraphicUpdate.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * A simple object used by the GestureLinkResponse to associate an - * action with a particular graphic, either with the graphic's ID for - * MODIFY-type actions, or with the graphic for UPDATE-type actions. - */ -public class GraphicUpdate implements LinkPropertiesConstants { - /** - * A masked integer describing the action for the graphic. See - * GestureLinkResponse fo the masks. - */ - public int action = 0; - /** The graphic's ID. */ - public String id = null; - /** The graphic, for updates. */ - public OMGraphic graphic = null; - - /** Constructor for modify-type actions. */ - public GraphicUpdate(int graphicAction, String gid) { - action = graphicAction; - id = gid; - } - - /** Constructor for update-type actions. */ - public GraphicUpdate(int graphicAction, OMGraphic omg) { - action = graphicAction; - if (omg != null) { - Object obj = omg.getAttribute(OMGraphic.APP_OBJECT); - if (obj instanceof LinkProperties) { - id = ((LinkProperties) obj).getProperty(LPC_GRAPHICID); - } - } - graphic = omg; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/Link.java b/src/core/src/main/java/com/bbn/openmap/layer/link/Link.java deleted file mode 100644 index d49ca3108..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/Link.java +++ /dev/null @@ -1,505 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/Link.java,v $ -// $RCSfile: Link.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:55 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The Link object is the main mechanism for communications between a - * LinkClient (most likely a LinkLayer) and a LinkServer. This class - * should only be used directly by a server - clients should use the - * ClientLink object. This object defines the communications that - * either side can make. - *

- * - * The ClientLink adds some control methods that the client should - * use. The client needs to make sure that several queries are not - * sent to the server at the same time. The ClientLink contains a lock - * that can be checked, and set. It is up to the client to manage the - * lock. The ClientLink also provides the method to close the link - * down, since it makes that decision. The server should remain - * connected until the client is finished. The server can request to - * be disconnected, however, and the ClientLink provides a method for - * the client to check if that request has been made. - */ -public class Link implements LinkConstants { - /** The apparent maximum size of a header. */ - public final static int MAX_HEADER_LENGTH = 80; - /** For outgoing traffic. */ - protected LinkOutputStream dos = null; - /** For incoming traffic. */ - protected DataInputStream dis = null; - /** Used to read/create strings from off the input stream. */ - protected char[] charArray = new char[MAX_HEADER_LENGTH]; - /** - * Set for the client, by the server, to indicate whether the - * socket should be closed. By default, this will be false, Used - * when the server wants to run in a stateless mode, and doesn't - * care to maintain a connection with the client. It's included in - * the Link object because the server knows about it and sets it - * in the client. - */ - protected boolean closeLink = false; - /** - * Used to retrieve any potential graphics queries that came in - * over the link. - */ - protected LinkMapRequest mapRequest = null; - /** - * Used to retrieve any potential graphics responses that came in - * over the link. - */ - protected LinkGraphicList graphicList = null; - /** - * Used to retrieve any potential gesture queries that came in - * over the link. - */ - protected LinkActionRequest actionRequest = null; - /** - * Used to retrieve any potential gesture responses that came in - * over the link. - */ - protected LinkActionList actionList = null; - /** - * Used to retrieve any potential GUI queries that came in over - * the link. - */ - protected LinkGUIRequest guiRequest = null; - /** - * Used to retrieve any potential GUI responses that came in over - * the link. - */ - protected LinkGUIList guiList = null; - /** The socket used for the link. Kept for convenience. */ - protected Socket socket = null; - /** - * The lock. This should only be changed within a synchronized - * block of code, synchronized on the link object.!! Otherwise, - * race conditions can result. - */ - protected boolean locked = false; - /** - * Flag to control whether this side of the link will adhere to - * shutdown commands issued from other side of the link. False by - * default. - */ - protected boolean obeyCommandToExit = false; - - /** - * Open up a link over a socket. - * - * @param socket the socket to open the Link on. - * @throws IOException - */ - public Link(Socket socket) throws IOException { - this.socket = socket; - InputStream is = socket.getInputStream(); - BufferedInputStream bis = new BufferedInputStream(is); - this.dis = new DataInputStream(bis); - - OutputStream os = socket.getOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(os); - this.dos = new LinkOutputStream(bos); - } - - /** - * Should be called by the server and/or client to release - * resources when the link is through being used. - */ - public void cleanUp() { - try { - this.dis.close(); - this.dos.close(); - } catch (IOException ioe) { - } - - this.dis = null; - this.dos = null; - } - - /** - * The method to call at the beginning of a request or response. - * It writes the header given to the link. This header is expected - * on the other side of the link. - * - * @param messageHeader Header string, defined in the Link object, - * that describes the tranmission. - * @throws IOException - */ - public void start(String messageHeader) throws IOException { - dos.write(messageHeader.getBytes()); - } - - /** - * The method that needs to be called at the end of a - * request/response or section. This places the END_TOTAL symbol - * on the link to let the other side know that the transmission is - * done, and it also flushes the output stream buffer. - * - * @param endType use END_SECTION if you want to add more types of - * responses. Use END_TOTAL at the end of the total - * transmission. - * @throws IOException - */ - public void end(String endType) throws IOException { - dos.write(endType.getBytes()); - if (END_TOTAL.equals(endType)) { - dos.flush(); - } - } - - /** - * Called to begin reading the information coming off the link. - * Since the information can be coming in different sections, this - * method figures out how to read the different sections and get - * ready for requests on what was read. After the link is read, - * you can then request the link to find out what was sent back - - * for graphics, GUI components, or actions. When this method is - * called, the link resets the objects that are returned by - * getGraphics(), getGUI and getActions(). These methods are meant - * to be used after read() to find out what was returned. - * - * @throws IOException - */ - public void readAndParse() throws IOException { - readAndParse(null, null); - } - - /** - * Called to begin reading the information coming off the link. - * - * @param proj a projection for graphics - * @param generator an OMGridGenerator that knows how to render - * grid objects. - * @throws IOException - */ - public void readAndParse(Projection proj, OMGridGenerator generator) - throws IOException { - readAndParse(proj, generator, null); - } - - /** - * Called to begin reading the information coming off the link. - * - * @param proj pass in a projection if you are expecting graphics - * to arrive, and they will be projected as they come off - * the link. - * @param generator an OMGridGenerator that knows how to render - * grid objects. - * @param layer a layer that is interested in gesture reactions. - * @throws IOException - */ - public void readAndParse(Projection proj, OMGridGenerator generator, - Layer layer) throws IOException { - - // Reset everything // - - // Keep this here, so if there is more than one graphics - // section, then all the graphics get added to one list. - LinkOMGraphicList graphics = new LinkOMGraphicList(); - - graphicList = null; - mapRequest = null; - actionRequest = null; - actionList = null; - guiRequest = null; - guiList = null; - closeLink = false; - - String delimiter = null; - - if (Debug.debugging("link")) { - System.out.println("Link|readAndParse: listening to link:"); - System.out.println((proj == null ? " without " : " with ") - + "a projection and"); - System.out.println((layer == null ? " without " : " with ") - + "a layer"); - } - - while (true) { - delimiter = readDelimiter(true); - if (Debug.debugging("link")) { - System.out.println("Link:reading section: " + delimiter); - } - if (delimiter == GRAPHICS_HEADER) { - if (layer != null) { - graphicList = new LinkGraphicList(this, graphics, layer.getProjection(), generator); - } else { - graphicList = new LinkGraphicList(this, graphics, proj, generator); - } - delimiter = graphicList.getLinkStatus(); - } else if (delimiter == ACTIONS_HEADER) { - actionList = new LinkActionList(this, layer, proj, generator); - delimiter = actionList.getLinkStatus(); - } else if (delimiter == GUI_HEADER) { - guiList = new LinkGUIList(this); - delimiter = guiList.getLinkStatus(); - } else if (delimiter == CLOSE_LINK_HEADER) { - closeLink = true; - } else if (delimiter == SHUTDOWN_HEADER) { - Debug.message("link", "Link.received command to exit"); - if (obeyCommandToExit) { - System.exit(0); - } - } else if (delimiter == HUH_HEADER) { - delimiter = readDelimiter(true); - } else if (delimiter == MAP_REQUEST_HEADER) { - mapRequest = new LinkMapRequest(this); - delimiter = mapRequest.getLinkStatus(); - } else if (delimiter == ACTION_REQUEST_HEADER) { - actionRequest = new LinkActionRequest(this); - delimiter = actionRequest.getLinkStatus(); - } else if (delimiter == GUI_REQUEST_HEADER) { - guiRequest = new LinkGUIRequest(this); - delimiter = guiRequest.getLinkStatus(); - } else if (delimiter == PING_REQUEST_HEADER) { - start(PING_RESPONSE_HEADER); - end(END_TOTAL); - delimiter = readDelimiter(false); - } - - if (delimiter == END_TOTAL) { - return; - } - } - } - - public void setObeyCommandToExit(boolean value) { - obeyCommandToExit = value; - } - - public boolean getAcceptCommandToExit() { - return obeyCommandToExit; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve a graphics request, if one was sent. - * - * @return LinkMapRequest containing the request. - */ - public LinkMapRequest getMapRequest() { - return mapRequest; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve graphics in an LinkOMGraphicList, if any - * graphics were sent. - * - * @return GraphicLinkRsponse containing the information. If no - * graphics were sent the list will be empty. - */ - public LinkGraphicList getGraphicList() { - return graphicList; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve a gesture notification/request, if one was - * sent. - * - * @return LinkActionRequest containing the request. - */ - public LinkActionRequest getActionRequest() { - return actionRequest; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve the gesture response. - * - * @return LinkActionList containing the information. - */ - public LinkActionList getActionList() { - return actionList; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve a gesture notification/request, if one was - * sent. - * - * @return LinkGUIRequest containing the request. - */ - public LinkGUIRequest getGUIRequest() { - return guiRequest; - } - - /** - * After a readAndParse() has been called on a link, this can be - * called to retrieve the GUI response, if any GUI components were - * sent. - * - */ - public LinkGUIList getGUIList() { - return guiList; - } - - /** - * readDelimiter is a function designed to read a header string - * off the data input stream in the Link object. It expects that - * the next byte off the link will be a '<' in the stream, and - * then reads through the stream until it finds the '>' expected - * at the end of the string. It will also return a string version - * of END_TOTAL or END_SECTION if it is encountered instead. If - * desired, an intern version of the string is returned. - * - * @param returnString if true, an intern String version of the - * characters is returned. - * @throws IOException - * @throws ArrayIndexOutOfBoundsException - */ - protected String readDelimiter(boolean returnString) throws IOException, - ArrayIndexOutOfBoundsException { - String ret = END_TOTAL; - - char END_TOTAL_CHAR = END_TOTAL.charAt(0); - char END_SECTION_CHAR = END_SECTION.charAt(0); - - char c = (char) dis.readByte(); - - // NOTE: possibility of early exits here... - if (c == END_TOTAL_CHAR) { - Debug.message("link", "Link|readDelimiter: Found END_TOTAL"); - return END_TOTAL; - } else if (c == END_SECTION_CHAR) { - Debug.message("link", "Link|readDelimiter: Found END_SECTION"); - return END_SECTION; - } else if (c != '<') { - if (Debug.debugging("link")) { - System.out.println("Link|readDelimiter: unexpected protocol data read '" - + c + "'"); - } - throw new IOException("readDelimiter: unexpected protocol data read."); - } - - // The byte read does indeed equal '<' - int charCount = 0; - - // c should == '<' - charArray[charCount++] = c; - // Get the rest of the header information - c = (char) dis.readByte(); - while (c != '>' && charCount < MAX_HEADER_LENGTH - 1) { - charArray[charCount++] = c; - c = (char) dis.readByte(); - } - - // c should == '>' or uh-oh - too many characters between - // them. Exit with a faulty return if this is the case. - if (c != '>') { - throw new IOException("readDelimiter: header is too long."); - } - - charArray[charCount++] = c; - - // OK, got it - return string - if (returnString) { - ret = new String(charArray, 0, charCount).intern(); - } else { - ret = ""; - } - return ret; - } - - /** - * Other threads can check to see if the link is in use. - * - * @return true if link in use and unavailable. - */ - public boolean isLocked() { - return locked; - } - - /** - * Set the lock. Should only be called in a synchronized block of - * code, where you have control over the link. - * - * @param set true if the lock should be turned on, false if the - * link should be released. - */ - public synchronized boolean setLocked(boolean set) { - if (set == true) { - if (locked == true) { - // The lock was NOT set for the caller - unsuccessful. - return false; - } else { - locked = true; - // The lock was set for the caller, successfully. - return true; - } - } else { - locked = set; - // The state was set to false, successfully. - return true; - } - } - - /** - * This method is provided for those who want to optimize how they - * write the graphical objects to the output stream. Look in the - * LinkGraphics API to find out the order of the pieces for - * each graphic type. Not recommended for the faint of heart. - */ - public DataOutput getDOS() { - return dos; - } - - /** - * This method complements getDOS(). - */ - public DataInput getDIS() { - return dis; - } - - /** - * Returns the number of bytes written since the last - * clearBytesWritten() call. - */ - public int getBytesWritten() { - return dos.size(); - } - - /** - * Reset the bytes written count to 0. - * - * @return the old byte count - */ - public int clearBytesWritten() { - return dos.clearWritten(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionConstants.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionConstants.java deleted file mode 100644 index b751f8562..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionConstants.java +++ /dev/null @@ -1,116 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkActionConstants.java,v $ -// $RCSfile: LinkActionConstants.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/** - * The LinkActionConstants interface contains all the constants needed - * for the LinkActionList and LinkActionRequest that are defined by - * the Link Protocol. - */ -public interface LinkActionConstants { - - ///////// LinkActionList constants. /////////////// - - /** Action identifier - change/modify/add graphics. */ - public static final int ACTION_GRAPHICS = 0; - /** Action identifier - change/modify/add GUI components. */ - public static final int ACTION_GUI = 1; - /** Action identifier - center/zoom/change projection of map. */ - public static final int ACTION_MAP = 2; - - /** - * Graphic action descriptor mask - raise the graphic on top of - * others. - */ - public static final int MODIFY_RAISE_GRAPHIC_MASK = 1 << 0; - /** Graphic action descriptor mask - lower graphics below others. */ - public static final int MODIFY_LOWER_GRAPHIC_MASK = 1 << 1; - /** Graphic action descriptor mask - delete the graphic. */ - public static final int MODIFY_DELETE_GRAPHIC_MASK = 1 << 2; - /** Graphic action descriptor mask - select the graphic. */ - public static final int MODIFY_SELECT_GRAPHIC_MASK = 1 << 3; - /** Graphic action descriptor mask - deselect the graphic. */ - public static final int MODIFY_DESELECT_GRAPHIC_MASK = 1 << 4; - /** Graphic action descriptor mask - deselect all graphics. */ - public static final int MODIFY_DESELECTALL_GRAPHIC_MASK = 1 << 5; - /** Graphic action descriptor mask - add a graphic. */ - public static final int UPDATE_ADD_GRAPHIC_MASK = 1 << 6; - /** Graphic action descriptor mask - update the graphic. */ - public static final int UPDATE_GRAPHIC_MASK = 1 << 7; - - ///////// LinkActionResponse constants. /////////////// - - /** - * Gesture descriptor mask - Set if the mouse buttons were pressed - * and released. - */ - public static final int MOUSE_CLICKED_MASK = 1 << 0; - /** Gesture descriptor mask - Set if the mouse button was pressed. */ - public static final int MOUSE_PRESSED_MASK = 1 << 1; - /** Gesture descriptor mask - Set if the mouse button was released. */ - public static final int MOUSE_RELEASED_MASK = 1 << 2; - /** - * Gesture descriptor mask - Set if the mouse moved with no - * buttons pressed. - */ - public static final int MOUSE_MOVED_MASK = 1 << 3; - /** - * Gesture descriptor mask - Set if the mouse cursor has entered - * the map window. - */ - public static final int MOUSE_ENTERED_MASK = 1 << 4; - /** - * Gesture descriptor mask - Set if the mouse cursor has left the - * map window. - */ - public static final int MOUSE_EXITED_MASK = 1 << 5; - /** - * Gesture descriptor mask - Set if the mouse moved with a button - * down. - */ - public static final int MOUSE_DRAGGED_MASK = 1 << 6; - /** Gesture descriptor mask - Set if a keyboard button was pressed. */ - public static final int KEY_PRESSED_MASK = 1 << 7; - /** - * Gesture descriptor mask - Set if a keyboard button was - * released. - */ - public static final int KEY_RELEASED_MASK = 1 << 8; - /** - * Gesture descriptor mask - Set if a gesture is affiliated with a - * particular graphic. The graphic ID will be available via the - * getGraphicID() method. - */ - public static final int GRAPHIC_ID_MASK = 1 << 9; - /** - * Gesture descriptor mask - Set if the integer is being sent to - * the client to tell it what types of events the server is - * interested in receiving. - */ - public static final int CLIENT_NOTIFICATION_MASK = 1 << 10; - /** - * Gesture descriptor mask - Set if the server is interested in - * receiving events even if a graphic gesture is handled locally. - */ - public static final int SERVER_NOTIFICATION_MASK = 1 << 11; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionList.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionList.java deleted file mode 100644 index 5b4fd65f6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionList.java +++ /dev/null @@ -1,1926 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkActionList.java,v $ -// $RCSfile: LinkActionList.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.Color; -import java.awt.Image; -import java.io.EOFException; -import java.io.IOException; -import java.util.Vector; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The LinkActionList carries information about actions that the client should - * perform in response to a gesture query. The possible actions include URLs and - * HTML text to display in a browser, information to display in a pop-up window - * or status display, or changes to make to graphics. - */ -public class LinkActionList implements LinkActionConstants, - LinkPropertiesConstants { - - /** Link used for the transmission/reception of actions. */ - protected Link link = null; - /** The terminator of the gesture section when receiving actions. */ - protected String linkStatus = Link.END_TOTAL; - /** */ - protected boolean reacted = false; - /** - * This flag tells whether properties have been received that note how to - * update the map. - */ - protected boolean mapUpdate = false; - /** Use these properties to set the map */ - protected LinkProperties mapProperties; - /** - * Instead of allocating a new empty vector for each gesture response, even - * if there isn't a graphic update, use this to return an empty vector. - */ - protected static Vector emptyGraphicUpdates = new Vector(); - /** Graphics list received. */ - protected Vector updates = null; - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - /** The properties returned for this list. */ - protected LinkProperties properties; - - /** - * Write a gesture response section to the link, from the server side. - * - * @param link the Link to write to. - * @throws IOException - */ - public LinkActionList(Link link, LinkProperties properties) - throws IOException { - this.link = link; - link.start(Link.ACTIONS_HEADER); - link.dos.writeFloat(version); - properties.write(link); - } - - /** - * Read the gesture section off the link, from the client. - * - * @param link the link to read from. - * @param layer the client layer. - * @param proj the projection to use on graphic updates. - * @param generator an OMGridGenerator that knows how to render grid - * objects. - * @throws IOException - * @throws EOFException - */ - public LinkActionList(Link link, Layer layer, Projection proj, - OMGridGenerator generator) throws IOException, EOFException { - this.link = link; - linkStatus = readGestureResponses(layer, proj, generator); - } - - /** - * After reading the gesture response, this returns the section ending - * string terminating the gesture section, either Link.END_TOTAL or - * Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - /** - * Get the properties for the LinkActionList. Any information messages can - * be picked up from within the properties - html, URL, messages, text and - * information lines. - * - * @return properties - */ - public LinkProperties getProperties() { - return properties; - } - - /** - * Get the properties for the map update. - * - * @return mapProperties - */ - public LinkProperties getMapProperties() { - return mapProperties; - } - - /** - * Return all the graphic updates that came across the link, in the form of - * a Vector of LinkActionList.GraphicUpdate objects. - * - * @return Vector of GraphicUpdate objects. - */ - public Vector getGraphicUpdates() { - if (updates == null) { - return emptyGraphicUpdates; - } else { - return updates; - } - } - - /** - * The server method that needs to be called at the end of sending a gesture - * response. This will tell the link what type of teminator to put on the - * end of the gesture response section, and also tell the link to fluxh the - * output stream.. - * - * @param endType use Link.END_SECTION if you want to add more types of - * responses. Use Link.END_TOTAL at the end of the total - * transmission. - * @throws IOException - */ - public void end(String endType) throws IOException { - link.end(endType); - } - - /** - * If a ACTIONS_HEADER has been encountered coming off the link, then this - * method should be called to read the string of gesture that follows. The - * gestures are read and reacted to directly - the responses that involve - * the Information Delegator are handled here, and all graphic updates are - * stored in the graphicUpdates Vector. Assumes the ACTIONS_HEADER has been - * read. - * - * @param layer the layer that wants the gesture results.. - * @param proj If you want the gesture graphic to be projected as it comes - * off the wire, add a projection here. Otherwise, use null. - * @param generator an OMGridGenerator that knows how to render grid - * objects. - * @return Link.END_TOTAL or Link.END_SECTION, depending on how the section - * ends. - * @throws IOException - * @throws EOFException - */ - protected String readGestureResponses(Layer layer, Projection proj, - OMGridGenerator generator) - throws IOException, EOFException { - - long startTime = System.currentTimeMillis(); - String header = null; - int gestureType; - - float ver = link.dis.readFloat(); - - if (ver != version) { - if (ver == .1) {// Big difference.... - throw new IOException("LinkActionList: Versions do not match! DANGER!"); - } else { - Debug.message("link", "LinkActionList: Versions do not match"); - } - } - - if (properties != null) { - properties.clear(); - } - - properties = LinkProperties.read(link.dis, properties); - LinkProperties graphicProperties = new LinkProperties(); - - Debug.message("link", "LinkActionList: reading actions:"); - - while (true) { - // Just consume the header, don't create a useless - // string object. - header = link.readDelimiter(false); - - if (header == Link.END_TOTAL || header == Link.END_SECTION) { - - long endTime = System.currentTimeMillis(); - if (Debug.debugging("link")) { - Debug.output("LinkActionList: received in " - + (float) (endTime - startTime) / 1000.0f - + " seconds"); - } - - return header; - } - - gestureType = link.dis.readByte(); - - switch (gestureType) { - case ACTION_GRAPHICS: - int graphicAction = link.dis.readInt(); - - if (updates == null) { - updates = new Vector(); - } - - if (LinkUtil.isMask(graphicAction, UPDATE_ADD_GRAPHIC_MASK) - || LinkUtil.isMask(graphicAction, UPDATE_GRAPHIC_MASK)) { - updates.addElement(readGraphic(graphicAction, graphicProperties, - proj, - generator)); - } else { - graphicProperties = LinkProperties.read(link.dis, graphicProperties); - updates.addElement(new GraphicUpdate(graphicAction, graphicProperties.getProperty(LPC_GRAPHICID))); - } - reacted = true; - break; - case ACTION_GUI: - break; - case ACTION_MAP: - mapUpdate = true; - if (mapProperties != null) { - mapProperties.clear(); - } - mapProperties = LinkProperties.read(link.dis, mapProperties); - break; - default: - System.err.println("LinkActionList: received unknown gesture type."); - } - } - } - - /** - * Read a graphic's particulars, for upates and additions. Assumes that the - * gesture type and graphic action has been read. - * - * @param graphicAction the action to take on the graphic. - * @param proj the projection to apply to the graphic. - * @param generator an OMGridGenerator that knows how to render grid - * objects. - * @throws IOException - */ - protected GraphicUpdate readGraphic(int graphicAction, LinkProperties graphicProperties, Projection proj, - OMGridGenerator generator) - throws IOException { - - OMGraphic graphic = null; - String header = link.readDelimiter(false); - - // Sanity check - if (header == Link.END_TOTAL || header == Link.END_SECTION) { - return null; - } - - int graphicType = link.dis.readByte(); - - switch (graphicType) { - case LinkGraphicList.GRAPHICTYPE_LINE: - graphic = LinkLine.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_POLY: - graphic = LinkPoly.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_RECTANGLE: - graphic = LinkRectangle.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_POINT: - graphic = LinkPoint.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_CIRCLE: - graphic = LinkCircle.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_ELLIPSE: - graphic = LinkEllipse.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_RASTER: - graphic = LinkRaster.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_BITMAP: - graphic = LinkBitmap.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_TEXT: - graphic = LinkText.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_GRID: - graphic = LinkGrid.read(link.dis, graphicProperties); - break; - case LinkGraphicList.GRAPHICTYPE_ARC: - graphic = LinkArc.read(link.dis, graphicProperties); - break; - default: - System.err.println("LinkActionList: received unknown graphic type."); - } - - if (graphic != null && proj != null) { - if (graphic instanceof OMGrid) { - ((OMGrid) graphic).setGenerator(generator); - } - graphic.generate(proj); - } - - return (new GraphicUpdate(graphicAction, graphic)); - } - - /** Returns true if the gesture was consumed by the server. */ - public boolean consumedGesture() { - return reacted; - } - - /** Returns true if a map update command was given. */ - public boolean getNeedMapUpdate() { - return mapUpdate; - } - - /** - * Sets whether a set of MapUpdate parameters needs to be fetched. Should be - * reset to false after the map projection has been updated. - */ - public void setNeedMapUpdate(boolean value) { - mapUpdate = value; - } - - /** - * The server method for writing a request to the client to deselect all the - * graphics. - * - * @throws IOException - */ - public void deselectGraphics() throws IOException { - link.dos.write(Link.UPDATE_GRAPHICS.getBytes()); - link.dos.writeByte(ACTION_GRAPHICS); - link.dos.writeInt(MODIFY_DESELECTALL_GRAPHIC_MASK); - LinkProperties.EMPTY_PROPERTIES.write(link.dos); // Write - // empty - } - - /** - * Server can use this method to modify a graphic with an action described - * by the MODIFY mask values. Assumes that you don't want to update or add a - * graphic, because that requires the graphic being added. - * - * @param maskDescription an integer with the applicable MODIFY_MASKS set. - * @param props property list containing the identifier used by the client - * to know which graphic to modify. - * @throws IOException - */ - public void modifyGraphic(int maskDescription, LinkProperties props) - throws IOException { - link.dos.write(Link.UPDATE_GRAPHICS.getBytes()); - link.dos.writeByte(ACTION_GRAPHICS); - link.dos.writeInt(maskDescription); - props.write(link.dos); - } - - /** - * Used by the graphic methods to write the correct mask and graphic header - * when a graphic is updated. Should not be called directly unless you - * understand the protocol. - * - * @param graphicUpdateMask the masked integer to describe the action on the - * graphic. - * @throws IOException - */ - public void writeGraphicGestureHeader(int graphicUpdateMask) - throws IOException { - link.dos.write(Link.UPDATE_GRAPHICS.getBytes()); - link.dos.writeByte(ACTION_GRAPHICS); - link.dos.writeInt(graphicUpdateMask); - } - - /** - * Update an arc with lat/lon placement. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(float latPoint, float lonPoint, int w, int h, - float s, float e, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(latPoint, - lonPoint, - 0, - 0, - w, - h, - s, - e, - properties, - link.dos); - } - - /** - * Update an arc with x/y placement. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(int x1, int y1, int w, int h, float s, float e, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(x1, y1, w, h, s, e, properties, link.dos); - } - - /** - * Writing an arc at a x, y, offset to a Lat/Lon location. - * - * @param latPoint latitude of center of arc. - * @param lonPoint longitude of center of arc. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of arc, pixels. - * @param h vertical diameter of arc, pixels. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float s, float e, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - s, - e, - properties, - link.dos); - } - - /** - * Update an arc with a certain radius at a Lat/Lon location. Assumes the - * radius is in decimal degrees. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(float latPoint, float lonPoint, float radius, - float s, float e, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(latPoint, - lonPoint, - radius, - -1, - -1, - s, - e, - properties, - link.dos); - } - - /** - * Update an arc with a certain radius at a Lat/Lon location, and allows you - * to specify units of the radius. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - KM, MILES, NMILES. If - * < 0, assume decimal degrees. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(float latPoint, float lonPoint, float radius, - int units, float s, float e, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(latPoint, - lonPoint, - radius, - units, - -1, - s, - e, - properties, - link.dos); - } - - /** - * Update an arc with a certain radius at a Lat/Lon location, and allows you - * to specify units of the radius, as well as the number of vertices to use - * to approximate the arc. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - OMArc.KM, - * OMArc.MILES, OMArc.NMILES. If < 0, assume decimal degrees. - * @param nverts number of vertices for the poly-arc (if < 3, value is - * generated internally). - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void updateArc(float latPoint, float lonPoint, float radius, - int units, int nverts, float s, float e, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkArc.write(latPoint, - lonPoint, - radius, - units, - nverts, - s, - e, - properties, - link.dos); - } - - /** - * Update the bitmap. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void updateBitmap(float lt, float ln, int w, int h, byte[] bytes, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkBitmap.write(lt, ln, w, h, bytes, properties, link.dos); - } - - /** - * Update the bitmap. - * - * @param x1 horizontal placement of upper left corner of bitmap. - * @param y1 vertical placement of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void updateBitmap(int x1, int y1, int w, int h, byte[] bytes, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkBitmap.write(x1, y1, w, h, bytes, properties, link.dos); - } - - /** - * Write a bitmap in the response. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param offset_x1 horizontal offset of upper left corner of bitmap. - * @param offset_y1 vertical offset of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void updateBitmap(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkBitmap.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - bytes, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param w pixel width of circle. - * @param h pixel height of circle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(float latPoint, float lonPoint, int w, int h, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(latPoint, lonPoint, w, h, properties, link.dos); - } - - /** - * Write a circle in the response. - * - * @param x1 horizontal pixel placement of center of circle.. - * @param y1 vertical pixel placement of center of circle.. - * @param w pixel width of circle. - * @param h pixel height of circle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(int x1, int y1, int w, int h, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(x1, y1, w, h, properties, link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param offset_x1 horizontal pixel offset of center of circle.. - * @param offset_y1 vertical pixel offset of center of circle.. - * @param w width of circle. - * @param h height of circle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(float latPoint, float lonPoint, float radius, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(latPoint, - lonPoint, - radius, - -1, - -1, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param units units of the radius - km, miles, nmiles, degrees.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(float latPoint, float lonPoint, float radius, - int units, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(latPoint, - lonPoint, - radius, - units, - -1, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param units units of the radius - km, miles, nmiles, degrees.. - * @param nverts number of points to use to approximate the circle. If - * negative, the client algorithm will figure out what is best. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void updateCircle(float latPoint, float lonPoint, float radius, - int units, int nverts, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkCircle.write(latPoint, - lonPoint, - radius, - units, - nverts, - properties, - link.dos); - } - - /** - * Write an ellipse in the response. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param majorAxisSpan x axis value, units - * @param minorAxisSpan y axis value, units - * @param units integer value for units for distance - OMCircle.KM, - * OMCircle.MILES, OMCircle.NMILES. If < 0, assume decimal - * degrees. - * @param rotationAngle The angle by which the circle/ellipse is to be - * rotated, in radians - * - * @param properties attributes for the circle. - * @throws IOException - */ - public void updateEllipse(float latPoint, float lonPoint, - float majorAxisSpan, float minorAxisSpan, - int units, float rotationAngle, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkEllipse.write(latPoint, - lonPoint, - majorAxisSpan, - minorAxisSpan, - units, - rotationAngle, - properties, - link.dos); - } - - /** - * Write an ellipse in the response. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param majorAxisSpan horizontal diameter of circle/ellipse, pixels - * @param minorAxisSpan vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians * - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void updateEllipse(int x1, int y1, int majorAxisSpan, - int minorAxisSpan, float rotateAngle, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkEllipse.write(x1, - y1, - majorAxisSpan, - minorAxisSpan, - rotateAngle, - properties, - link.dos); - } - - /** - * Write an ellipse in the response. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void updateEllipse(float latPoint, float lonPoint, int w, int h, - float rotateAngle, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkEllipse.write(latPoint, - lonPoint, - w, - h, - rotateAngle, - properties, - link.dos); - } - - /** - * Write an ellipse in the response. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - * @param rotateAngle the rotation of the ellipse around the center point, - * in radians. - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void updateEllipse(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float rotateAngle, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkEllipse.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - rotateAngle, - properties, - link.dos); - } - - /** - * Lat/Lon placement grid. - * - * @param lt latitude of the top of the grid. - * @param ln longitude of the left side of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution degrees/point between rows of the grid. - * @param hResolution degrees/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @see com.bbn.openmap.layer.link.LinkGrid - * @throws IOException - */ - public void updateGrid(float lt, float ln, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkGrid.write(lt, - ln, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * XY placement grid. - * - * @param x1 window location of the left side of the grid. - * @param y1 window location of the top of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @see com.bbn.openmap.layer.link.LinkGrid - * @throws IOException - */ - public void updateGrid(int x1, int y1, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkGrid.write(x1, - y1, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * Lat/lon placement with XY offset. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @see com.bbn.openmap.layer.link.LinkGrid - * @throws IOException - */ - public void updateGrid(float lt, float ln, int offset_x1, int offset_y1, - int rows, int columns, float orientation, - float vResolution, float hResolution, int major, - int[] data, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkGrid.write(lt, - ln, - offset_x1, - offset_y1, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void updateLine(float lat_1, float lon_1, float lat_2, float lon_2, - int lineType, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkLine.write(lat_1, - lon_1, - lat_2, - lon_2, - lineType, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param nsegs number of points to use to approximate curved line.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void updateLine(float lat_1, float lon_1, float lat_2, float lon_2, - int lineType, int nsegs, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkLine.write(lat_1, - lon_1, - lat_2, - lon_2, - lineType, - nsegs, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param x1 Horizontal pixel placement of start of line. - * @param y1 Vertical pixel placement of start of line. - * @param x2 Horizontal pixel placement of end of line. - * @param y2 Vertical pixel placement of end of line. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void updateLine(int x1, int y1, int x2, int y2, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkLine.write(x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of line. - * @param lon_1 longitude of placement of line. - * @param x1 Horizontal pixel offset of start of line. - * @param y1 Vertical pixel offset of start of line. - * @param x2 Horizontal pixel offset of end of line. - * @param y2 Vertical pixel offset of end of line. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void updateLine(float lat_1, float lon_1, int x1, int y1, int x2, - int y2, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkLine.write(lat_1, lon_1, x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, ImageIcon ii, - LinkProperties properties, int graphicUpdateMask) - throws IOException, InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, ln, ii, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(int x1, int y1, ImageIcon ii, - LinkProperties properties, int graphicUpdateMask) - throws IOException, InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(x1, y1, ii, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int offset_x1, int offset_y1, - ImageIcon ii, LinkProperties properties, - int graphicUpdateMask) throws IOException, - InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, ln, offset_x1, offset_y1, ii, properties, link.dos); - } - - /** - * Write a bitmap in the response. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param image_width width of bitmap. - * @param image_height height of bitmap. - * @param image the java.awt.Image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, Image image, int image_width, - int image_height, LinkProperties properties, - int graphicUpdateMask) throws IOException, - InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param image Image to place on map. - * @param image_width width of image. - * @param image_height height of image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(int x1, int y1, Image image, int image_width, - int image_height, LinkProperties properties, - int graphicUpdateMask) throws IOException, - InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(x1, - y1, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param image Image to place on map. - * @param image_width width of image. - * @param image_height height of image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int offset_x1, int offset_y1, - Image image, int image_width, int image_height, - LinkProperties properties, int graphicUpdateMask) - throws IOException, InterruptedException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int w, int h, int[] pix, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, ln, w, h, pix, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(int x1, int y1, int w, int h, int[] pix, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(x1, y1, w, h, pix, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, int[] pix, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - pix, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param url the url to download image from. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, String url, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, ln, url, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param url the url to download the image from. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(int x1, int y1, String url, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(x1, y1, url, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param url the url to download the image from. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int offset_x1, int offset_y1, - String url, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - url, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(int x1, int y1, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(x1, - y1, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void updateRaster(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, Color[] colorTable, - int trans, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of rectangle. - * @param ln1 longitude of placement of upper left corner of rectangle. - * @param lt2 latitude of placement of lower right corner of rectangle. - * @param ln2 longitude of placement of lower right corner of rectangle. - * @param lType the line type to use for the rectangle - straight, rhumb, - * great circle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void updateRectangle(float lt1, float ln1, float lt2, float ln2, - int lType, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRectangle.write(lt1, ln1, lt2, ln2, lType, properties, link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of rectangle. - * @param ln1 longitude of placement of upper left corner of rectangle. - * @param lt2 latitude of placement of lower right corner of rectangle. - * @param ln2 longitude of placement of lower right corner of rectangle. - * @param lType the line type to use for the rectangle - straight, rhumb, - * great circle. - * @param nsegs number of segments to use to approximate curved rectangle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void updateRectangle(float lt1, float ln1, float lt2, float ln2, - int lType, int nsegs, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRectangle.write(lt1, - ln1, - lt2, - ln2, - lType, - nsegs, - properties, - link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param x1 Horizontal pixel offset of upper left corner of rectangle.. - * @param y1 Vertical pixel offset of upper left corner of rectangle. - * @param x2 Horizontal pixel offset of lower right corner of rectangle.. - * @param y2 Vertical pixel offset of lower right corner of rectangle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void updateRectangle(int x1, int y1, int x2, int y2, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRectangle.write(x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of bitmap. - * @param ln1 longitude of placement of upper left corner of bitmap. - * @param x1 Horizontal pixel offset of upper left corner of rectangle.. - * @param y1 Vertical pixel offset of upper left corner of rectangle. - * @param x2 Horizontal pixel offset of lower right corner of rectangle.. - * @param y2 Vertical pixel offset of lower right corner of rectangle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void updateRectangle(float lt1, float ln1, int x1, int y1, int x2, - int y2, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkRectangle.write(lt1, ln1, x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param lt1 latitude of point. - * @param ln1 longitude of point. - * @param radius the radius of the point graphic. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void updatePoint(float lt1, float ln1, int radius, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoint.write(lt1, ln1, radius, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param x1 the horizontal screen pixel location of the point. - * @param y1 the vertical screen pixel location of the point. - * @param radius the pixel radius size of the point. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void updatePoint(int x1, int y1, int radius, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoint.write(x1, y1, radius, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param lt1 latitude of placement of upper left corner of bitmap. - * @param ln1 longitude of placement of upper left corner of bitmap. - * @param x1 Horizontal pixel offset of upper left corner of point.. - * @param y1 Vertical pixel offset of upper left corner of point. - * @param radius the pixel size of the point. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void updatePoint(float lt1, float ln1, int x1, int y1, int radius, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoint.write(lt1, ln1, x1, y1, radius, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param llPoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(double[] llPoints, int units, int lType, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(llPoints, units, lType, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param llpoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param nsegs number of segments to use to approximate curved poly lines.. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(double[] llpoints, int units, int lType, int nsegs, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(llpoints, units, lType, nsegs, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param xypoints alternating x and y pixel locations of poly. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(int[] xypoints, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(xypoints, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param xpoints horizontal pixel locations of poly. - * @param ypoints vertical pixel locations of poly. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(int[] xpoints, int[] ypoints, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(xpoints, ypoints, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xypoints alternating x and y offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(float latPoint, float lonPoint, int[] xypoints, - int cMode, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(latPoint, - lonPoint, - xypoints, - cMode, - properties, - link.dos); - } - - /** - * Write a poly in the response. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xpoints horizontal pixel offset polygon points. - * @param ypoints vertical pixel offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void updatePoly(float latPoint, float lonPoint, int[] xpoints, - int[] ypoints, int cMode, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkPoly.write(latPoint, - lonPoint, - xpoints, - ypoints, - cMode, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of placement of text. - * @param lonPoint longitude of placement of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(float latPoint, float lonPoint, String stuff, - int justify, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(latPoint, - lonPoint, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param x Horizontal pixel location of text. - * @param y Vertical pixel location of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(int x, int y, String stuff, int justify, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(x, - y, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of text placement. - * @param lonPoint longitude of text placement. - * @param offset_x Horizontal pixel offset of text. - * @param offset_y Vertical pixel offset of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(float latPoint, float lonPoint, int offset_x, - int offset_y, String stuff, int justify, - LinkProperties properties, int graphicUpdateMask) - throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(latPoint, - lonPoint, - offset_x, - offset_y, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of placement of text. - * @param lonPoint longitude of placement of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(float latPoint, float lonPoint, String stuff, - String font, int justify, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(latPoint, - lonPoint, - stuff, - font, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param x Horizontal pixel location of text. - * @param y Vertical pixel location of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(int x, int y, String stuff, String font, - int justify, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(x, y, stuff, font, justify, properties, link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of text placement. - * @param lonPoint longitude of text placement. - * @param offset_x Horizontal pixel offset of text. - * @param offset_y Vertical pixel offset of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties description of drawing attributes. - * @param graphicUpdateMask the mask describing the graphic update. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateText(float latPoint, float lonPoint, int offset_x, - int offset_y, String stuff, String font, - int justify, LinkProperties properties, - int graphicUpdateMask) throws IOException { - writeGraphicGestureHeader(graphicUpdateMask); - LinkText.write(latPoint, - lonPoint, - offset_x, - offset_y, - stuff, - font, - justify, - properties, - link.dos); - } - - /** - * Write an OMGraphic to the response. - * - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void updateGraphic(OMGraphic omGraphic, int graphicUpdateMask) - throws IOException { - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionRequest.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionRequest.java deleted file mode 100644 index c2edd1e5a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkActionRequest.java +++ /dev/null @@ -1,310 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkActionRequest.java,v $ -// $RCSfile: LinkActionRequest.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.io.IOException; - -import com.bbn.openmap.util.Debug; - -/** - * Class used to send a gesture to a server. In this case, a gesture - * can be a mouse click event, a mouse event, or a key event. This - * class defines how such notification is formatted and sent. The - * client can use the static write methods to put the object on the - * link, and the server creates an instance of this object to read the - * object off the link, and find out what the fields were. - */ -public class LinkActionRequest implements LinkActionConstants, - LinkPropertiesConstants { - /** The horizontal screen location of the mouse event, in pixels. */ - protected int x = 0; - /** The vertical screen location of the mouse event, in pixels. */ - protected int y = 0; - /** The latitide location of the mouse event, in decimal degrees. */ - protected float lat = 0; - /** The longitude location of the mouse event, in decimal degrees. */ - protected float lon = 0; - /** The click count of the mouse event. */ - protected int clickCount = 0; - /** - * The modifier of the event, that describes any keys that may - * have been pressed while the event occurred. - */ - protected int modifiers = 0; - /** The character of the key that was pressed in a key event. */ - protected char key; - /** The mask describing the event. */ - protected int descriptor = 0; - /** Graphic ID of an object selected by a gesture. */ - protected String id = null; - /** The properties object that contains any pertinent arguments. */ - protected LinkProperties properties = null; - /** - * The terminator of the graphics section when receiving gesture - * queries. - */ - String linkStatus = Link.END_TOTAL; - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - - public LinkActionRequest(Link link) throws IOException { - linkStatus = read(link); - } - - /** - * Constructor used by a server to let the client know what types - * of gestures the server can receive. This constructor - * automatically writes out the header and descriptor to the link. - * It does not call the link.end() method to end the transmission, - * since this will probably be sent along with other sections in a - * communication to the client. - * - * @param link the link to write to. - * @param descriptor a masked integer (see constants) describing - * the event to receive. - * @param sectionEnder the endType string to use for this - * description, either Link.END_TOTAL if this is the last - * section to the client, or END_SECTION if there are more - * sections following. - */ - public LinkActionRequest(Link link, int descriptor, String sectionEnder) - throws IOException { - link.start(Link.ACTION_REQUEST_HEADER); - link.dos.writeFloat(version); - descriptor = LinkUtil.setMask(descriptor, CLIENT_NOTIFICATION_MASK); - link.dos.writeInt(descriptor); - link.end(sectionEnder); - } - - public String getType() { - return Link.ACTION_REQUEST_HEADER; - } - - /** - * After reading the gesture response, this returns the section - * ending string terminating the gesture section, either - * Link.END_TOTAL or Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - /** - * Write a MouseEvent on the link to the server. - * - * @param descriptor the MASK that describes the event. - * @param me the MouseEvent - * @param latPoint the latitude of the mouse event. - * @param lonPoint the longitude of the mouse event. - * @param props an array of strings representing key-value pairs. - * @param link the link to write the gesture to. - */ - public static void write(int descriptor, MouseEvent me, float latPoint, - float lonPoint, LinkProperties props, Link link) - throws IOException { - - if (props.getProperty(LPC_GRAPHICID) != null) { - descriptor = LinkUtil.setMask(descriptor, GRAPHIC_ID_MASK); - } - - link.start(Link.ACTION_REQUEST_HEADER); - link.dos.writeFloat(version); - link.dos.writeInt(descriptor); - link.dos.writeInt(me.getX()); - link.dos.writeInt(me.getY()); - link.dos.writeInt(me.getClickCount()); - link.dos.writeInt(me.getModifiers()); - link.dos.writeFloat(latPoint); - link.dos.writeFloat(lonPoint); - - props.write(link); - - link.end(Link.END_TOTAL); - } - - /** - * Write a KeyEvent on the link to the server. - * - * @param descriptor the MASK that describes the event. - * @param ke the KeyEvent - * @param props Properties representing attributes. - * @param link the Link to write the gesture to. - */ - public static void write(int descriptor, KeyEvent ke, LinkProperties props, - Link link) throws IOException { - - link.start(Link.ACTION_REQUEST_HEADER); - link.dos.writeFloat(version); - link.dos.writeInt(descriptor); - link.dos.writeChar(ke.getKeyChar()); - link.dos.writeInt(ke.getModifiers()); - - props.write(link); - - link.end(Link.END_TOTAL); - } - - /** - * Read the link and pull off the gesture, filling in the fields - * of this object. - * - * @param link the link to read from. - * @return Link.END_TOTAL or Link.END_SECTION - */ - public String read(Link link) throws IOException { - - float ver = link.dis.readFloat(); - - if (ver != version) { - if (ver == .1) {// Big difference.... - throw new IOException("LinkActionRequest: Versions do not match! DANGER!"); - } else { - Debug.message("link", - "LinkActionRequest: Versions do not match"); - } - } - - // the second thing we get is the descriptor - descriptor = link.dis.readInt(); - if (isClientNotification()) { - // In case it is passed back later to the server - we - // really don't need to know that it was a notification - // mask after this, right?? - descriptor = LinkUtil.unsetMask(descriptor, - CLIENT_NOTIFICATION_MASK); - return link.readDelimiter(false); - } else if (isKeyEvent()) { - // key event - key = link.dis.readChar(); - modifiers = link.dis.readInt(); - } else { - // Mouse event - x = link.dis.readInt(); - y = link.dis.readInt(); - clickCount = link.dis.readInt(); - modifiers = link.dis.readInt(); - lat = link.dis.readFloat(); - lon = link.dis.readFloat(); - } - - properties = new LinkProperties(link); - - if (LinkUtil.isMask(descriptor, GRAPHIC_ID_MASK)) { - id = properties.getProperty(LPC_GRAPHICID); - } - - return link.readDelimiter(false); - } - - /** Get latitude of mouse gesture, in decimal degrees. */ - public float getLat() { - return lat; - } - - /** Get longitude of mouse gesture, in decimal degrees. */ - public float getLon() { - return lon; - } - - /** - * Get horizontal pixel location of mouse gesture, from left side - * of map. - */ - public int getX() { - return x; - } - - /** Get vertical pixel location of mouse gesture, from top of map. */ - public int getY() { - return y; - } - - /** Get the keyboard key that was pressed from a key gesture. */ - public char getKey() { - return key; - } - - /** Get the masked int that describes the gesture. */ - public int getDescriptor() { - return descriptor; - } - - /** - * If this is null, it means that the gesture occurred on the map - * background and is not affiliated with a particular graphic. - * Otherwise, the graphic ID string is returned for the affiliated - * graphic. - */ - public String getGraphicID() { - return id; - } - - /** - * Get the masked int that describes any modifing keys pressed - * with the gesture. - */ - public int getModifiers() { - return modifiers; - } - - /** Get the key-value args sent with the gesture. */ - public LinkProperties getProperties() { - return properties; - } - - /** - * Returns true if the query is to let the client know what - * gestures the server is interested in receiving. - */ - protected boolean isClientNotification() { - return ((descriptor & CLIENT_NOTIFICATION_MASK) != 0); - } - - /** Returns true if the query is representing a key event. */ - protected boolean isKeyEvent() { - return ((descriptor & KEY_RELEASED_MASK) != 0) - || ((descriptor & KEY_PRESSED_MASK) != 0); - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("LinkActionRequest:\n"); - if (isKeyEvent()) { - s.append(" Key Event\n"); - s.append(" Key: ").append(key).append("\n"); - } else { - s.append(" Mouse Event\n"); - s.append(" X: ").append(x).append("\n"); - s.append(" Y: ").append(y).append("\n"); - s.append(" Lat: ").append(lat).append("\n"); - s.append(" Lon: ").append(lon).append("\n"); - } - s.append(" Modifiers: ").append(modifiers).append("\n"); - - return s.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkArc.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkArc.java deleted file mode 100644 index 4df7939a9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkArc.java +++ /dev/null @@ -1,346 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkArc.java,v $ -// $RCSfile: LinkArc.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMArc; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Reading and writing a Link protocol version of a circle. - */ -public class LinkArc implements LinkGraphicConstants, LinkPropertiesConstants { - - /** - * Write an arc with lat/lon placement. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int w, int h, - float s, float e, LinkProperties properties, - DataOutputStream dos) throws IOException { - LinkArc.write(latPoint, lonPoint, 0, 0, w, h, s, e, properties, dos); - } - - /** - * Write an arc with x/y placement. - * - * @param x1 window position of center point from left of window, - * in pixels - * @param y1 window position of center point from top of window, - * in pixels - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(int x1, int y1, int w, int h, float s, float e, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.ARC_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ARC); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeFloat(s); - dos.writeFloat(e); - properties.write(dos); - } - - /** - * Writing an arc at a x, y, offset to a Lat/Lon location. - * - * @param latPoint latitude of center of arc. - * @param lonPoint longitude of center of arc. - * @param offset_x1 # pixels to the right the center will be moved - * from lonPoint. - * @param offset_y1 # pixels down that the center will be moved - * from latPoint. - * @param w horizontal diameter of arc, pixels. - * @param h vertical diameter of arc, pixels. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float s, float e, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.ARC_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ARC); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeFloat(s); - dos.writeFloat(e); - properties.write(dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location. - * Assumes the radius is in decimal degrees. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - float s, float e, LinkProperties properties, - DataOutputStream dos) throws IOException { - LinkArc.write(latPoint, lonPoint, radius, -1, -1, s, e, properties, dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location, and - * allows you to specify units of the radius. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - KM, MILES, - * NMILES. If < 0, assume decimal degrees. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - int units, float s, float e, - LinkProperties properties, DataOutputStream dos) - throws IOException { - LinkArc.write(latPoint, - lonPoint, - radius, - units, - -1, - s, - e, - properties, - dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location, and - * allows you to specify units of the radius, as well as the - * number of vertices to use to approximate the arc. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - OMArc.KM, - * OMArc.MILES, OMArc.NMILES. If < 0, assume decimal - * degrees. - * @param nverts number of vertices for the poly-arc (if < 3, - * value is generated internally). - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - int units, int nverts, float s, float e, - LinkProperties properties, DataOutputStream dos) - throws IOException { - // Write this out... - dos.write(Link.ARC_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ARC); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeFloat(radius); - dos.writeByte(units); - dos.writeInt(nverts); - dos.writeFloat(s); - dos.writeFloat(e); - properties.write(dos); - } - - public static void write(OMArc arc, Link link, LinkProperties props) - throws IOException { - - LatLonPoint llp; - switch (arc.getRenderType()) { - case OMArc.RENDERTYPE_LATLON: - llp = arc.getLatLon(); - LinkArc.write((float) llp.getLatitude(), - (float) llp.getLongitude(), - (float) arc.getRadius(), - (float) arc.getStartAngle(), - (float) arc.getExtentAngle(), - props, - link.dos); - break; - case OMArc.RENDERTYPE_XY: - LinkArc.write(arc.getX(), - arc.getY(), - arc.getWidth(), - arc.getHeight(), - (float) arc.getStartAngle(), - (float) arc.getExtentAngle(), - props, - link.dos); - break; - case OMArc.RENDERTYPE_OFFSET: - llp = arc.getLatLon(); - LinkArc.write((float) llp.getLatitude(), - (float) llp.getLongitude(), - arc.getOffX(), - arc.getOffY(), - arc.getWidth(), - arc.getHeight(), - (float) arc.getStartAngle(), - (float) arc.getExtentAngle(), - props, - link.dos); - break; - default: - Debug.error("LinkArc.write: arc rendertype unknown."); - } - } - - /** - * Read the arc protocol off the data input, and return an OMArc. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @return OMArc - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMLine - */ - public static OMArc read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the arc protocol off the data input, and return an OMArc. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMArc being read. - * @return OMArc - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMArc - */ - public static OMArc read(DataInputStream dis, LinkProperties propertiesBuffer) throws IOException { - - OMArc arc = null; - float lat, lon, radius, start, extent; - int x, y, w, h; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - lat = dis.readFloat(); - lon = dis.readFloat(); - radius = dis.readFloat(); - start = dis.readFloat(); - extent = dis.readFloat(); - int units = dis.readByte(); - int nverts = dis.readInt(); - - Length unit = Length.DECIMAL_DEGREE; - - switch (units) { - case 0: - unit = Length.KM; - break; - case 1: - unit = Length.MILE; - break; - case 2: - unit = Length.NM; - break; - default: - } - - arc = new OMArc(new LatLonPoint.Double(lat, lon), radius, unit, nverts, start, extent); - break; - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - w = dis.readInt(); - h = dis.readInt(); - start = dis.readFloat(); - extent = dis.readFloat(); - - arc = new OMArc(x, y, w, h, start, extent); - break; - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - x = dis.readInt(); - y = dis.readInt(); - w = dis.readInt(); - h = dis.readInt(); - start = dis.readFloat(); - extent = dis.readFloat(); - arc = new OMArc(lat, lon, x, y, w, h, start, extent); - break; - default: - } - - if (arc != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, - arc, - propertiesBuffer); - } - - return arc; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBitmap.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBitmap.java deleted file mode 100644 index e7914825e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBitmap.java +++ /dev/null @@ -1,256 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkBitmap.java,v $ -// $RCSfile: LinkBitmap.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMBitmap; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Reading and writing the Link protocol version of a bitmap.. - */ -public class LinkBitmap implements LinkGraphicConstants, - LinkPropertiesConstants { - - /** - * Lat/Lon placement. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes bytes for the bitmap. - * @param properties attributes for the bitmap. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float lt, float ln, int w, int h, byte[] bytes, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.BITMAP_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_BITMAP); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(w); - dos.writeInt(h); - - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - - properties.write(dos); - } - - /** - * XY placement. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes bytes for the bitmap. - * @param properties attributes for the bitmap. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(int x1, int y1, int w, int h, byte[] bytes, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.BITMAP_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_BITMAP); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(w); - dos.writeInt(h); - - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - - properties.write(dos); - } - - /** - * Lat/lon placement with XY offset. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes bytes for the bitmap. - * @param properties attributes for the bitmap. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.BITMAP_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_BITMAP); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - - properties.write(dos); - } - - /** - * Write a bitmap to the link. - */ - public static void write(OMBitmap bitmap, Link link, LinkProperties props) - throws IOException { - - switch (bitmap.getRenderType()) { - case OMBitmap.RENDERTYPE_LATLON: - LinkBitmap.write((float) bitmap.getLat(), - (float) bitmap.getLon(), - bitmap.getWidth(), - bitmap.getHeight(), - bitmap.getBits(), - props, - link.dos); - break; - case OMBitmap.RENDERTYPE_XY: - LinkBitmap.write(bitmap.getX(), - bitmap.getY(), - bitmap.getWidth(), - bitmap.getHeight(), - bitmap.getBits(), - props, - link.dos); - break; - case OMBitmap.RENDERTYPE_OFFSET: - LinkBitmap.write((float) bitmap.getLat(), - (float) bitmap.getLon(), - bitmap.getX(), - bitmap.getY(), - bitmap.getBits(), - props, - link.dos); - break; - default: - Debug.error("LinkBitmap.write: bitmap rendertype not handled."); - } - } - - /** - * Read a Bitmap off a DataInputStream. Assumes the Bitmap header has - * already been read. - * - * @param dis DataInputStream to read from. - * @return OMBitmap - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMBitmap - */ - public static OMBitmap read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read a Bitmap off a DataInputStream. Assumes the Bitmap header has - * already been read. - * - * @param dis DataInputStream to read from. - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMBitmap - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMBitmap - */ - public static OMBitmap read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMBitmap bitmap = null; - float lat = 0; - float lon = 0; - int x = 0; - int y = 0; - int w = 0; - int h = 0; - int length; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - // Fall through... - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - break; - case RENDERTYPE_LATLON: - default: - lat = dis.readFloat(); - lon = dis.readFloat(); - } - - w = dis.readInt(); - h = dis.readInt(); - length = dis.readInt(); - - byte[] bytes = new byte[length]; - dis.readFully(bytes); - - switch (renderType) { - case RENDERTYPE_OFFSET: - bitmap = new OMBitmap(lat, lon, x, y, w, h, bytes); - break; - case RENDERTYPE_XY: - bitmap = new OMBitmap(x, y, w, h, bytes); - break; - case RENDERTYPE_LATLON: - default: - bitmap = new OMBitmap(lat, lon, w, h, bytes); - } - - if (bitmap != null) { - LinkProperties properties = LinkProperties.loadPropertiesIntoOMGraphic(dis, bitmap, propertiesBuffer); - bitmap.setRotationAngle((double) ProjMath.degToRad(PropUtils.floatFromProperties(properties, - LPC_LINKROTATION, - 0.0f))); - } - - return bitmap; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBoundingPoly.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBoundingPoly.java deleted file mode 100644 index 673bd4d91..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkBoundingPoly.java +++ /dev/null @@ -1,187 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkBoundingPoly.java,v $ -// $RCSfile: LinkBoundingPoly.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * LinkBoundingPoly objects are used to describe simple polygons that - * cover a certain area. If the area described is in coordinates, the - * polygon should not be sued for areas covering a pole or straddling - * the dateline. More than one LinkBoundingPolys should be used for - * areas like that. - */ -public class LinkBoundingPoly { - - public float maxX; - public float maxY; - public float minX; - public float minY; - protected float[] points; - - /** - * The constructor to use when reading the bounding polygon off an - * input stream. - * - * @param dis DataInputStream to read from. - */ - public LinkBoundingPoly(DataInput dis) throws IOException { - read(dis); - } - - /** - * The constructor to use to create a LinkBoundingPoly to write to - * an output stream. - * - * @param poly a series of alternating x, y points describing a - * polygon. - */ - public LinkBoundingPoly(float[] poly) { - points = poly; - } - - /** - * Create a LinkBoundingPoly out of minimum and max x, y, values. - * - * @param minX minimum X value. - * @param minY minimum Y value. - * @param maxX maximum X value. - * @param maxY maximum Y value. - */ - public LinkBoundingPoly(float minX, float minY, float maxX, float maxY) { - points = new float[10]; - - Debug.message("link", - "LinkBoundingPoly: Creating link bounding poly with " + minX - + ", " + minY + ", " + maxX + ", " + maxY); - - points[0] = minY; - points[1] = minX; - points[2] = maxY; - points[3] = minX; - points[4] = maxY; - points[5] = maxX; - points[6] = minY; - points[7] = maxX; - points[8] = minY; - points[9] = minX; - } - - /** - * Write the polygon on the output stream. If the number of points - * is an odd number, the last number will be left off. - * - * @param dos the DataOutput to write to. - */ - public void write(DataOutput dos) throws IOException { - // round down to a multiple of two. - int length = (points.length / 2) * 2; - - dos.writeInt(length); - for (int i = 0; i < length; i++) { - dos.writeFloat(points[i]); - } - } - - /** - * Read the bounding polygon off the input stream. - * - * @param dis DataInputStream to read from. - */ - public void read(DataInput dis) throws IOException { - - Debug.message("link", "LinkBoundingPoly: read()"); - - int polyLength = dis.readInt(); - points = new float[polyLength]; - float x, y; - - for (int i = 0; i < points.length; i += 2) { - y = dis.readFloat(); - x = dis.readFloat(); - - if (i == 0) { - minX = x; - minY = y; - maxX = x; - maxY = y; - } - - points[i] = y; - points[i + 1] = x; - - if (x < minX) - minX = x; - if (x > maxX) - maxX = x; - if (y < minY) - minY = y; - if (y > maxY) - maxY = y; - } - } - - /** - * Return the polygon points, as a series of alternating x and y - * values. - * - * @return float[] of alternating x, y, points. - */ - public float[] getPoints() { - return points; - } - - /** - * Convert the points to Lat/Lon points. There is no guarantee - * that the points really translate into latitude and longitude - * points. - * - * @return LatLonPoints - */ - public LatLonPoint[] getLatLonPoints() { - LatLonPoint[] boundingPoly = new LatLonPoint[points.length / 2]; - float lat, lon; - for (int i = 0; i < points.length; i += 2) { - lat = points[i]; - lon = points[i + 1]; - boundingPoly[i] = new LatLonPoint.Double(lat, lon); - } - return boundingPoly; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append(" LinkBoundingPoly has ") - .append(points.length / 2).append(" points."); - for (int i = 0; i < points.length; i += 2) { - s.append("\n |Lat = ").append(points[i]) - .append(", Lon = ").append(points[i + 1]).append("|"); - } - return s.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkCircle.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkCircle.java deleted file mode 100644 index 74d4a794e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkCircle.java +++ /dev/null @@ -1,306 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkCircle.java,v $ -// $RCSfile: LinkCircle.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Reading and writing a Link protocol version of a circle. - */ -public class LinkCircle implements LinkGraphicConstants, - LinkPropertiesConstants { - - /** - * Write a circle with lat/lon placement. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int w, int h, - LinkProperties properties, DataOutputStream dos) - throws IOException { - LinkCircle.write(latPoint, lonPoint, 0, 0, w, h, properties, dos); - } - - /** - * Write a circle with x/y placement. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(int x1, int y1, int w, int h, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.CIRCLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_CIRCLE); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(w); - dos.writeInt(h); - properties.write(dos); - } - - /** - * Writing a circle at a x, y, offset to a Lat/Lon location. - * - * @param latPoint latitude of center of circle/ellipse. - * @param lonPoint longitude of center of circle/ellipse. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.CIRCLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_CIRCLE); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - properties.write(dos); - } - - /** - * Write a circle with a certain radius at a Lat/Lon location. Assumes the - * radius is in decimal degrees. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - LinkProperties properties, DataOutputStream dos) - throws IOException { - LinkCircle.write(latPoint, lonPoint, radius, -1, -1, properties, dos); - } - - /** - * Write a circle with a certain radius at a Lat/Lon location, and allows - * you to specify units of the radius. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units integer value for units for distance - KM, MILES, NMILES. If - * < 0, assume decimal degrees. - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - int units, LinkProperties properties, - DataOutputStream dos) throws IOException { - LinkCircle.write(latPoint, lonPoint, radius, units, -1, properties, dos); - } - - /** - * Write a circle with a certain radius at a Lat/Lon location, and allows - * you to specify units of the radius, as well as the number of vertices to - * use to approximate the circle. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units integer value for units for distance - OMCircle.KM, - * OMCircle.MILES, OMCircle.NMILES. If < 0, assume decimal - * degrees. - * @param nverts number of vertices for the poly-circle (if < 3, value is - * generated internally). - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, float radius, - int units, int nverts, LinkProperties properties, - DataOutputStream dos) throws IOException { - // Write this out... - dos.write(Link.CIRCLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_CIRCLE); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeFloat(radius); - dos.writeByte(units); - dos.writeInt(nverts); - properties.write(dos); - } - - public static void write(OMCircle circle, Link link, LinkProperties props) - throws IOException { - - LatLonPoint llp; - switch (circle.getRenderType()) { - case OMCircle.RENDERTYPE_LATLON: - llp = circle.getLatLon(); - LinkCircle.write((float) llp.getLatitude(), - (float) llp.getLongitude(), - (float) circle.getRadius(), - props, - link.dos); - break; - case OMCircle.RENDERTYPE_XY: - LinkCircle.write(circle.getX(), - circle.getY(), - circle.getWidth(), - circle.getHeight(), - props, - link.dos); - break; - case OMCircle.RENDERTYPE_OFFSET: - llp = circle.getLatLon(); - LinkCircle.write(llp.getLatitude(), - llp.getLongitude(), - circle.getOffX(), - circle.getOffY(), - circle.getWidth(), - circle.getHeight(), - props, - link.dos); - break; - default: - Debug.error("LinkCircle.write: circle rendertype unknown."); - } - } - - /** - * Read the circle protocol off the data input, and return an OMCircle. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @return OMCircle - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMCircle - */ - public static OMCircle read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the circle protocol off the data input, and return an OMCircle. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMCircle - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMCircle - */ - public static OMCircle read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMCircle circle = null; - float lat, lon, radius; - int x, y, w, h; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - lat = dis.readFloat(); - lon = dis.readFloat(); - radius = dis.readFloat(); - int units = dis.readByte(); - int nverts = dis.readInt(); - - Length unit = Length.DECIMAL_DEGREE; - - switch (units) { - case 0: - unit = Length.KM; - break; - case 1: - unit = Length.MILE; - break; - case 2: - unit = Length.NM; - break; - default: - } - - circle = new OMCircle(new LatLonPoint.Double(lat, lon), radius, unit, nverts); - break; - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - w = dis.readInt(); - h = dis.readInt(); - - circle = new OMCircle(x, y, w, h); - break; - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - x = dis.readInt(); - y = dis.readInt(); - w = dis.readInt(); - h = dis.readInt(); - - circle = new OMCircle(lat, lon, x, y, w, h); - break; - default: - } - - if (circle != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, circle, propertiesBuffer); - } - - return circle; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkConstants.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkConstants.java deleted file mode 100644 index 76a982339..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkConstants.java +++ /dev/null @@ -1,96 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkConstants.java,v $ -// $RCSfile: LinkConstants.java,v $ -// $Revision: 1.5 $ -// $Date: 2007/02/26 17:12:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/** - * The LinkConstants object is an interface that describes all the - * constants that relate directly to the Link object, and that are - * defined by the Link Protocol. They are kept here in the - * LinkConstants interface to keep the Link object less cluttered. - */ -public interface LinkConstants { - /** The value used for an unknown or invalid setting. */ - public final static int UNKNOWN = -1; - /** The symbol used to end a request or response. */ - public final static String END_TOTAL = "\r"; - /** The symbol used to end a section/part of a request/response. */ - public final static String END_SECTION = "\n"; - /** The Link Protocol version. Latest version is 0.6. */ - public static final float LINK_VERSION = 0.6f; - - /** Graphics request header. */ - public static final String MAP_REQUEST_HEADER = ""; - /** Gesture request header. */ - public static final String ACTION_REQUEST_HEADER = ""; - /** GUI request header. */ - public static final String GUI_REQUEST_HEADER = ""; - /** Graphics response header. */ - public static final String GRAPHICS_HEADER = ""; - /** Gesture response header. */ - public static final String ACTIONS_HEADER = ""; - /** GUI response header. */ - public static final String GUI_HEADER = ""; - /** Close Link header. */ - public static final String CLOSE_LINK_HEADER = ""; - /** No Action header. */ - public static final String HUH_HEADER = ""; - /** Ping request header. */ - public static final String PING_REQUEST_HEADER = ""; - /** Ping response header */ - public static final String PING_RESPONSE_HEADER = ""; - /** Header to instruct the other other side to quit. */ - public static final String SHUTDOWN_HEADER = ""; - - /** Bitmap graphic object header. */ - public static final String BITMAP_HEADER = ""; - /** Text graphic object header. */ - public static final String TEXT_HEADER = ""; - /** Poly graphic object header. */ - public static final String POLY_HEADER = ""; - /** Line graphic object header. */ - public static final String LINE_HEADER = ""; - /** Rectangle graphic object header. */ - public static final String RECTANGLE_HEADER = ""; - /** Circle graphic object header. */ - public static final String CIRCLE_HEADER = ""; - /** Raster graphic object header. */ - public static final String RASTER_HEADER = ""; - /** Grid graphic object header. */ - public static final String GRID_HEADER = ""; - /** Generic graphic object header. */ - public static final String GRAPHIC_HEADER = ""; - /** Point graphic object header. */ - public static final String POINT_HEADER = ""; - /** Arc graphic object header. */ - public static final String ARC_HEADER = ""; - /** Ellipse graphic object header. */ - public static final String ELLIPSE_HEADER = ""; - - /** Graphics action object header. */ - public static final String UPDATE_GRAPHICS = ""; - /** GUI action object header. */ - public static final String UPDATE_GUI = ""; - /** Map action object header. */ - public static final String UPDATE_MAP = ""; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkEllipse.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkEllipse.java deleted file mode 100644 index 7b45051c1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkEllipse.java +++ /dev/null @@ -1,277 +0,0 @@ -// ********************************************************************** -// -// -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkEllipse.java,v $ -// $RCSfile: LinkEllipse.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMEllipse; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Reading and writing a Link protocol version of a circle. - */ -public class LinkEllipse implements LinkGraphicConstants, - LinkPropertiesConstants { - - /** - * Write an ellipse with Lat/Lon placement with axis defined in terms of - * distance. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param majorAxisSpan x axis value, units - * @param minorAxisSpan y axis value, units - * @param units integer value for units for distance - OMCircle.KM, - * OMCircle.MILES, OMCircle.NMILES. If < 0, assume decimal - * degrees. - * @param rotationAngle The angle by which the circle/ellipse is to be - * rotated, in radians - * - * @param properties attributes for the circle. - * @param dos DataOutputStream. - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, - float majorAxisSpan, float minorAxisSpan, - int units, float rotationAngle, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.ELLIPSE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ELLIPSE); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeFloat(majorAxisSpan); - dos.writeFloat(minorAxisSpan); - dos.writeByte(units); - dos.writeFloat(rotationAngle); - properties.write(dos); - } - - /** - * Create a OMEllipse, positioned with a x-y center with x-y axis. - * Rendertype is RENDERTYPE_XY. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param majorAxisSpan horizontal diameter of circle/ellipse, pixels - * @param minorAxisSpan vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - */ - public static void write(int x1, int y1, int majorAxisSpan, - int minorAxisSpan, float rotateAngle, - LinkProperties properties, DataOutputStream dos) - throws IOException { - dos.write(Link.ELLIPSE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ELLIPSE); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(majorAxisSpan); - dos.writeInt(minorAxisSpan); - dos.writeFloat(rotateAngle); - properties.write(dos); - } - - /** - * Create a OMEllipse, positioned with a lat-lon center and x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - */ - public static void write(float latPoint, float lonPoint, int w, int h, - float rotateAngle, LinkProperties properties, - DataOutputStream dos) throws IOException { - write(latPoint, lonPoint, 0, 0, w, h, rotateAngle, properties, dos); - } - - /** - * Create a OMEllipse, positioned at a Lat-lon location, x-y offset, x-y - * axis. Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - */ - public static void write(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float rotateAngle, - LinkProperties properties, DataOutputStream dos) - throws IOException { - dos.write(Link.ELLIPSE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_ELLIPSE); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeFloat(rotateAngle); - properties.write(dos); - } - - public static void write(OMEllipse ellipse, Link link, LinkProperties props) - throws IOException { - - LatLonPoint llp; - switch (ellipse.getRenderType()) { - case OMEllipse.RENDERTYPE_LATLON: - llp = ellipse.getLatLon(); - LinkEllipse.write(llp.getLatitude(), - llp.getLongitude(), - (float) Length.KM.fromRadians(ellipse.getMajorAxis()), - (float) Length.KM.fromRadians(ellipse.getMinorAxis()), - 0, /* Length.KM */ - (float) ellipse.getRotationAngle(), - props, - link.dos); - break; - case LinkEllipse.RENDERTYPE_XY: - LinkEllipse.write(ellipse.getX(), - ellipse.getY(), - (int) ellipse.getMajorAxis(), - (int) ellipse.getMinorAxis(), - (float) ellipse.getRotationAngle(), - props, - link.dos); - break; - case LinkEllipse.RENDERTYPE_OFFSET: - llp = ellipse.getLatLon(); - LinkEllipse.write(llp.getLatitude(), - llp.getLongitude(), - ellipse.getOffX(), - ellipse.getOffY(), - (int) ellipse.getMajorAxis(), - (int) ellipse.getMinorAxis(), - (float) ellipse.getRotationAngle(), - props, - link.dos); - break; - default: - Debug.error("LinkCircle.write: circle rendertype unknown."); - } - } - - /** - * Read the ellipse protocol off the data input, and return an OMEllipse. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @return OMEllipse - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMEllipse - */ - public static OMEllipse read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the ellipse protocol off the data input, and return an OMEllipse. - * Assumes the header for the graphic has already been read. - * - * @param dis the DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMEllipse - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMEllipse - */ - public static OMEllipse read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - OMEllipse ellipse = null; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: { - float lat = dis.readFloat(); - float lon = dis.readFloat(); - double majorAxisSpan = dis.readFloat(); - double minorAxisSpan = dis.readFloat(); - int units = dis.readByte(); - double rotationAngle = dis.readFloat(); - - Length unit = Length.DECIMAL_DEGREE; - switch (units) { - case 0: - unit = Length.KM; - break; - case 1: - unit = Length.MILE; - break; - case 2: - unit = Length.NM; - break; - default: - break; - } - - ellipse = new OMEllipse(new LatLonPoint.Double(lat, lon), majorAxisSpan, minorAxisSpan, unit, rotationAngle); - break; - } - case RENDERTYPE_XY: { - int x = dis.readInt(); - int y = dis.readInt(); - int majorAxisSpan = dis.readInt(); - int minorAxisSpan = dis.readInt(); - double rotationAngle = dis.readFloat(); - - ellipse = new OMEllipse(x, y, majorAxisSpan, minorAxisSpan, rotationAngle); - break; - } - case RENDERTYPE_OFFSET: { - float lat = dis.readFloat(); - float lon = dis.readFloat(); - int offsetX = dis.readInt(); - int offsetY = dis.readInt(); - int w = dis.readInt(); - int h = dis.readInt(); - double rotationAngle = dis.readFloat(); - - ellipse = new OMEllipse(new LatLonPoint.Double(lat, lon), offsetX, offsetY, w, h, rotationAngle); - break; - } - default: { - Debug.error("LinkEllipse.read: ellipse rendertype unknown."); - break; - } - } - - if (ellipse != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, - ellipse, - propertiesBuffer); - } - - return ellipse; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIList.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIList.java deleted file mode 100644 index 0aa0acc31..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIList.java +++ /dev/null @@ -1,122 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGUIList.java,v $ -// $RCSfile: LinkGUIList.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 18:08:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.EOFException; -import java.io.IOException; - -import javax.swing.JComponent; - -import com.bbn.openmap.util.Debug; - -/** - * Uhhh, unimplemented so far. Big plans, though. Widgets don't get set yet. - */ -public class LinkGUIList { - - /** Link used for the transmission/reception of widgets. */ - Link link = null; - /** GUI widget list received. */ - JComponent widgets = null; - /** The terminator of the graphics section when receiving graphics. */ - String linkStatus = Link.END_TOTAL; - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - - /** Write a gui section to the link. */ - public LinkGUIList(Link link) throws IOException { - this.link = link; - link.start(Link.GUI_HEADER); - link.dos.writeFloat(version); - } - - /** - */ - public JComponent getGUI() { - return widgets; - } - - /** - * After reading the graphics response, this returns the section - * ending string terminating the graphics section, either - * Link.END_TOTAL or Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - /** - * The server method that needs to be called at the end of sending - * a gui response. This will tell the link what type of teminator - * to put on the end of the graphics response section, and also - * tell the link to fluxh the output stream.. - * - * @param endType use Link.END_SECTION if you want to add more - * types of response sections. Use Link.END_TOTAL at the - * end of the total transmission. - * @throws IOException - */ - public void end(String endType) throws IOException { - link.end(endType); - } - - /** - * @throws IOException - * @throws EOFException - */ - protected String readWidgets() throws IOException, EOFException { - - long startTime = System.currentTimeMillis(); - String header = null; - int widgetType; - - float ver = link.dis.readFloat(); - Debug.message("link", "LinkGUIList: reading graphics: version(" + ver + ")"); - - while (true) { - - // Just consume the header, don't create a useless - // string object. - header = link.readDelimiter(false); - - if (header == Link.END_TOTAL || header == Link.END_SECTION) { - - long endTime = System.currentTimeMillis(); - Debug.message("link", "LinkGUIList: received bytes in " - + (float) (endTime - startTime) / 1000.0f + " seconds"); - - return header; - } - - widgetType = link.dis.readInt(); - - switch (widgetType) { - - default: - System.err.println("LinkGUIList: received unknown graphic type."); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIRequest.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIRequest.java deleted file mode 100644 index 92d18f74b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGUIRequest.java +++ /dev/null @@ -1,79 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGUIRequest.java,v $ -// $RCSfile: LinkGUIRequest.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; - -/** - */ -public class LinkGUIRequest { - - String linkStatus = Link.END_TOTAL; - - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - - public LinkGUIRequest(Link link) throws IOException {} - - public String getType() { - return Link.GUI_REQUEST_HEADER; - } - - /** - * After reading the gesture response, this returns the section - * ending string terminating the gesture section, either - * Link.END_TOTAL or Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - public static void write(String[] args, Link link) throws IOException { - - // Do a check to make sure the arguments are set in key - // value pairs. If there is a leftover arg, leave it off. - int normedNumArgs = (args.length / 2) * 2; - link.dos.writeFloat(version); - link.dos.writeInt(normedNumArgs); - for (int i = 0; i < normedNumArgs; i++) { - link.dos.writeInt(args[i].length()); - link.dos.writeChars(args[i]); - } - - link.end(Link.END_TOTAL); - } - - /** - * Read the link and pull off the gesture, filling in the fields - * of this object. - * - * @param link the link to read from. - * @return Link.END_TOTAL or Link.END_SECTION - */ - public String read(Link link) throws IOException { - return link.readDelimiter(false); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphic.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphic.java deleted file mode 100644 index df2e60f6e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphic.java +++ /dev/null @@ -1,123 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGraphic.java,v -// $ -// $RCSfile: LinkGraphic.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/10/10 22:05:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Paint; -import java.io.IOException; -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.OMBitmap; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMEllipse; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; - -public class LinkGraphic implements LinkConstants, LinkPropertiesConstants { - - public static void write(OMGraphic omGraphic, Link link) throws IOException { - write(omGraphic, link, null); - } - - public static void write(OMGraphic omGraphic, Link link, - LinkProperties props) throws IOException { - - // This is so not object-oriented. I know, I know. - - if (props == null) { - Object obj = omGraphic.getAttribute(OMGraphic.APP_OBJECT); - if (obj instanceof LinkProperties) { - props = (LinkProperties) obj; - } else { - props = new LinkProperties(); - } - } - - if (omGraphic instanceof OMGraphicList) { - Iterator iterator = ((OMGraphicList) omGraphic).getTargets() - .iterator(); - while (iterator.hasNext()) { - write((OMGraphic) iterator.next(), link); - } - return; - } - - props.setProperty(LPC_LINEWIDTH, - Integer.toString((int) ((BasicStroke) omGraphic.getStroke()).getLineWidth())); - - Paint paint = omGraphic.getLinePaint(); - if (paint instanceof Color) { - props.setProperty(LPC_LINECOLOR, - ColorFactory.getHexColorString((Color) paint)); - } - - paint = omGraphic.getFillPaint(); - if (paint instanceof Color) { - props.setProperty(LPC_FILLCOLOR, - ColorFactory.getHexColorString((Color) paint)); - } - - paint = omGraphic.getSelectPaint(); - if (paint instanceof Color) { - props.setProperty(LPC_HIGHLIGHTCOLOR, - ColorFactory.getHexColorString((Color) paint)); - } - - if (omGraphic instanceof OMBitmap) { - LinkBitmap.write((OMBitmap) omGraphic, link, props); - } else if (omGraphic instanceof OMCircle) { - LinkCircle.write((OMCircle) omGraphic, link, props); - } else if (omGraphic instanceof OMEllipse) { - LinkEllipse.write((OMEllipse) omGraphic, link, props); - } else if (omGraphic instanceof OMGrid) { - LinkGrid.write((OMGrid) omGraphic, link, props); - } else if (omGraphic instanceof OMLine) { - LinkLine.write((OMLine) omGraphic, link, props); - } else if (omGraphic instanceof OMPoint) { - LinkPoint.write((OMPoint) omGraphic, link, props); - } else if (omGraphic instanceof OMRect) { - LinkRectangle.write((OMRect) omGraphic, link, props); - } else if (omGraphic instanceof OMRaster) { - LinkRaster.write((OMRaster) omGraphic, link, props); - } else if (omGraphic instanceof OMText) { - LinkText.write((OMText) omGraphic, link, props); - } else if (omGraphic instanceof OMPoly) { - LinkPoly.write((OMPoly) omGraphic, link, props); - } else { - Debug.error("LinkGraphic.write: OMGraphic Type not handled by LinkProtocol"); - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicConstants.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicConstants.java deleted file mode 100644 index 85fed0330..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicConstants.java +++ /dev/null @@ -1,166 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGraphicConstants.java,v $ -// $RCSfile: LinkGraphicConstants.java,v $ -// $Revision: 1.4 $ -// $Date: 2006/10/10 22:05:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/** - * The LinkGraphicConstants is an interface that defines the constants - * associated with link graphic objects. These constants are defined in - * the Link Protocol. - */ -public interface LinkGraphicConstants { - - /** - * The direct colormodel, for OMRasters, means the integer values - * passed in as pixels, already reflect the RGB color values each - * pixel should display. - */ - public final static int COLORMODEL_DIRECT = 0; - /** - * The indexed colormodel, for OMRasters, means that the byte - * array passed in for the pixels has to be resolved with a - * colortable in order to create a integer array of RGB pixels. - */ - public final static int COLORMODEL_INDEXED = 1; - /** - * The ImageIcon colormode used that means that the image has to - * be downloaded from an URL. Right now, the IMAGEICON colormodel - * does this. At some point, it will be changed. - */ - public static final int COLORMODEL_URL = 2; - - /** Line type is unknown. */ - public final static int LINETYPE_UNKNOWN = 0; - /** Line will be drawn straight between window points. */ - public final static int LINETYPE_STRAIGHT = 1; - /** - * Line will be drawn on a constant bearing between two points. - */ - public final static int LINETYPE_RHUMB = 2; - /** - * Line will be drawn on the shortest geographical path between - * two locations. - */ - public final static int LINETYPE_GREATCIRCLE = 3; - - /** Render type is unknown. */ - public final static int RENDERTYPE_UNKNOWN = 0; - /** - * The graphic should be projected relative to its lat/lon - * position. - */ - public final static int RENDERTYPE_LATLON = 1; - /** - * The graphic should be projected relative to its window - * position. - */ - public final static int RENDERTYPE_XY = 2; - /** - * The graphic should be projected in window space relative to a - * lat/lon position. - */ - public final static int RENDERTYPE_OFFSET = 3; - - /** The generic graphic type. */ - public final static int GRAPHICTYPE_GRAPHIC = 0; - /** A bitmap type. */ - public final static int GRAPHICTYPE_BITMAP = 1; - /** A text type. */ - public final static int GRAPHICTYPE_TEXT = 2; - /** A polygon/polyline type. */ - public final static int GRAPHICTYPE_POLY = 3; - /** A line type. */ - public final static int GRAPHICTYPE_LINE = 4; - /** A rectangle type. */ - public final static int GRAPHICTYPE_RECTANGLE = 5; - /** A circle type. */ - public final static int GRAPHICTYPE_CIRCLE = 6; - /** A raster type. */ - public final static int GRAPHICTYPE_RASTER = 7; - /** A grid type. */ - public final static int GRAPHICTYPE_GRID = 8; - /** A point type. */ - public final static int GRAPHICTYPE_POINT = 9; - /** An arc type. */ - public final static int GRAPHICTYPE_ARC = 10; - /** An ellipse type. */ - public final static int GRAPHICTYPE_ELLIPSE = 11; - - /** The float coordinates are in decimal degrees. */ - public final static int DECIMAL_DEGREES = 0; - /** The float coordinates are in radians. */ - public final static int RADIANS = 1; - - /** Unit notation - kilometers. */ - final public static int KM = 0; - /** Unit notation - miles. */ - final public static int MILES = 1; - /** Unit notation - nautical miles. */ - final public static int NMILES = 2; - - /** - * Polygon Translation offsets. For RENDERTYPE_OFFSET in a Poly, - * the xy points are relative to the position of fixed latlon - * point. - */ - public final static int COORDMODE_ORIGIN = 0; - /** - * Polygon Delta offsets. For RENDERTYPE_OFFSET in a Poly, each xy - * point in the array is relative to the previous point, and the - * first point is relative to the fixed latlon point. - */ - public final static int COORDMODE_PREVIOUS = 1; - /** Align the text to the right of the location. */ - public final static int JUSTIFY_LEFT = 0; - /** Align the text centered on the location. */ - public final static int JUSTIFY_CENTER = 1; - /** Align the text to the left of the location. */ - public final static int JUSTIFY_RIGHT = 2; - /** Align the baseline of text to the location. */ - public final static int BASELINE_BOTTOM = 0; - /** Align the middle of text to the location. */ - public final static int BASELINE_MIDDLE = 1; - /** Align the top of text to the location. */ - public final static int BASELINE_TOP = 2; - - /** - * For Grids, note that the columns are the primary dimension of - * the data. - */ - public final static int COLUMN_MAJOR = 0; - /** - * For Grids, note that the rows are the primary dimension of the - * data. - */ - public final static int ROW_MAJOR = 1; - - /** - * The hex string representation of a black color, used as a - * default. - */ - public final static String BLACK_COLOR_STRING = "FF000000"; - /** - * The hex string representation of a clear black color, used as a - * default. - */ - public final static String CLEAR_COLOR_STRING = "00000000"; -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicList.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicList.java deleted file mode 100644 index 7b6fa5958..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGraphicList.java +++ /dev/null @@ -1,1645 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGraphicList.java,v $ -// $RCSfile: LinkGraphicList.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.Color; -import java.awt.Image; -import java.io.EOFException; -import java.io.IOException; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The LinkGraphicList is an object that describes a list of graphics. This - * object can be used to write the graphics to the link, and read the graphics - * response section from the link. - *

- * - * To use it to write to the link, create the LinkGraphicList with the - * constructor that takes a link as its only argument, and then use the write - * methods to add graphics. When all the graphics are written to the link, close - * the section by calling end() with the appropriate symbol. - *

- * - * To use it to read from a link, use the constructor that takes a link and a - * LinkOMGraphicsList (and a projection, if you want to generate the graphics as - * you read them). Call getGraphics() to get the updated list. - */ -public class LinkGraphicList implements LinkGraphicConstants { - - /** Link used for the transmission/reception of graphics. */ - protected Link link = null; - /** Graphics list received. */ - protected LinkOMGraphicList graphics = null; - /** The terminator of the graphics section when receiving graphics. */ - protected String linkStatus = Link.END_TOTAL; - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - /** The properties returned for this list. */ - protected LinkProperties properties; - - /** Write a graphics section to the link. */ - public LinkGraphicList(Link link, LinkProperties properties) - throws IOException { - this.link = link; - link.start(Link.GRAPHICS_HEADER); - link.dos.writeFloat(version); - properties.write(link); - } - - /** - * Read the graphics section off the link. - * - * @param link the link to read the response from. - * @param graphicList the list to add graphics to. - * @throws IOException - * @throws EOFException - */ - public LinkGraphicList(Link link, LinkOMGraphicList graphicList) - throws IOException, EOFException { - this(link, graphicList, (Projection) null, (OMGridGenerator) null); - } - - /** - * Read the graphics section off the link, if you want the graphics to be - * projected as they come off the link. - * - * @param link the link to read graphics from. - * @param graphicList the list to add graphics to. - * @param proj the projection to use for generating graphics. - * @param generator an OMGridGenerator that knows how to render grid - * objects. - * @throws IOException - * @throws EOFException - */ - public LinkGraphicList(Link link, LinkOMGraphicList graphicList, - Projection proj, OMGridGenerator generator) throws IOException, - EOFException { - this.link = link; - graphics = graphicList; - - if (graphics == null) { - graphics = new LinkOMGraphicList(); - } - - linkStatus = readGraphics(graphics, proj, generator); - } - - /** - * After a readAndParse() has been called on a link, this can be called to - * retrieve graphics in an LinkOMGraphicList, if any graphics were sent. - * - * @return LinkOMGraphicList containing the graphics read off the link. If - * no graphics were sent the list will be empty. - */ - public LinkOMGraphicList getGraphics() { - return graphics; - } - - /** - * After reading the graphics response, this returns the section ending - * string terminating the graphics section, either Link.END_TOTAL or - * Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - /** - * Get the properties for the LinkGraphicList. Any information messages can - * be picked up from within the properties - html, URL, messages, text and - * information lines. - * - * @return properties - */ - public LinkProperties getProperties() { - if (properties != null) { - return properties; - } else { - return LinkProperties.EMPTY_PROPERTIES; - } - } - - /** - * The server method that needs to be called at the end of sending a - * graphics response. This will tell the link what type of teminator to put - * on the end of the graphics response section, and also tell the link to - * fluxh the output stream.. - * - * @param endType use Link.END_SECTION if you want to add more types of - * response sections. Use Link.END_TOTAL at the end of the total - * transmission. - * @throws IOException - */ - public void end(String endType) throws IOException { - link.end(endType); - } - - /** - * If a GRAPHICS_RESPONSE_HEADER has been encountered coming off the link, - * then this method should be called to read the string of graphics that - * follows. The graphics are read and added to the LinkOMGraphicList - * provided. - * - * @param graphics the LinkOMGraphicList to add the link graphics too. This - * method assumes that this is never null. - * @param proj If you want the graphics to be projected as they come off the - * wire, add a projection here. Otherwise, use null. - * @param generator an OMGridGenerator that knows how to render grid - * objects. - * @throws IOException - * @throws EOFException - */ - protected String readGraphics(LinkOMGraphicList graphics, Projection proj, - OMGridGenerator generator) - throws IOException, EOFException { - - OMGraphic graphic; - long startTime = System.currentTimeMillis(); - String header = null; - int graphicType; - - // This is important, it's checked by the LinkLayer to see if - // it needs to generate the LinkOMGraphicList to see if the - // contents need to be generated. - graphics.setNeedToRegenerate(proj == null); - - // doing nothing with the version number. - float ver = link.dis.readFloat(); - - if (ver != version) { - if (ver == .1) {// Big difference.... - throw new IOException("LinkGraphicList: Versions do not match! DANGER!"); - } else { - Debug.message("link", "LinkGraphicList: Versions do not match."); - } - } - - if (properties != null) { - properties.clear(); - } - - properties = LinkProperties.read(link.dis, properties); - - Debug.message("link", "LinkGraphicList: reading graphics:"); - - LinkProperties propertiesBuffer = new LinkProperties(properties); - - while (true) { - graphic = null; - // Just consume the header, don't create a useless - // string object. - header = link.readDelimiter(false); - - if (header == Link.END_TOTAL || header == Link.END_SECTION) { - - long endTime = System.currentTimeMillis(); - Debug.message("link", "LinkGraphicList: received " - + graphics.size() + " graphics in " - + (float) (endTime - startTime) / 1000.0f + " seconds"); - - return header; - } - - graphicType = link.dis.readByte(); - - switch (graphicType) { - case GRAPHICTYPE_LINE: - graphic = LinkLine.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_POLY: - graphic = LinkPoly.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_RECTANGLE: - graphic = LinkRectangle.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_POINT: - graphic = LinkPoint.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_CIRCLE: - graphic = LinkCircle.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_ELLIPSE: - graphic = LinkEllipse.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_RASTER: - graphic = LinkRaster.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_BITMAP: - graphic = LinkBitmap.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_TEXT: - graphic = LinkText.read(link.dis, propertiesBuffer); - break; - case GRAPHICTYPE_GRID: - graphic = LinkGrid.read(link.dis, propertiesBuffer); - break; - default: - throw new IOException("LinkGraphicList: received unknown graphic type."); - } - - if (graphic != null) { - if (graphic instanceof OMGrid) { - ((OMGrid) graphic).setGenerator(generator); - } - if (proj != null) { - graphic.generate(proj); - } - graphics.add(graphic); - } - } - } - - /** - * Write an arc with lat/lon placement. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(float latPoint, float lonPoint, int w, int h, float s, - float e, LinkProperties properties) throws IOException { - LinkArc.write(latPoint, - lonPoint, - 0, - 0, - w, - h, - s, - e, - properties, - link.dos); - } - - /** - * Write an arc with x/y placement. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(int x1, int y1, int w, int h, float s, float e, - LinkProperties properties) throws IOException { - LinkArc.write(x1, y1, w, h, s, e, properties, link.dos); - } - - /** - * Writing an arc at a x, y, offset to a Lat/Lon location. - * - * @param latPoint latitude of center of arc. - * @param lonPoint longitude of center of arc. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of arc, pixels. - * @param h vertical diameter of arc, pixels. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float s, float e, - LinkProperties properties) throws IOException { - LinkArc.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - s, - e, - properties, - link.dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location. Assumes the - * radius is in decimal degrees. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(float latPoint, float lonPoint, float radius, float s, - float e, LinkProperties properties) throws IOException { - LinkArc.write(latPoint, - lonPoint, - radius, - -1, - -1, - s, - e, - properties, - link.dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location, and allows you - * to specify units of the radius. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - KM, MILES, NMILES. If - * < 0, assume decimal degrees. - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(float latPoint, float lonPoint, float radius, int units, - float s, float e, LinkProperties properties) - throws IOException { - LinkArc.write(latPoint, - lonPoint, - radius, - units, - -1, - s, - e, - properties, - link.dos); - } - - /** - * Write an arc with a certain radius at a Lat/Lon location, and allows you - * to specify units of the radius, as well as the number of vertices to use - * to approximate the arc. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units integer value for units for distance - OMArc.KM, - * OMArc.MILES, OMArc.NMILES. If < 0, assume decimal degrees. - * @param nverts number of vertices for the poly-arc (if < 3, value is - * generated internally). - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - * @param properties attributes for the arc. - * @throws IOException - */ - public void addArc(float latPoint, float lonPoint, float radius, int units, - int nverts, float s, float e, LinkProperties properties) - throws IOException { - LinkArc.write(latPoint, - lonPoint, - radius, - units, - nverts, - s, - e, - properties, - link.dos); - } - - /** - * Write a bitmap in the response. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void addBitmap(float lt, float ln, int w, int h, byte[] bytes, - LinkProperties properties) throws IOException { - LinkBitmap.write(lt, ln, w, h, bytes, properties, link.dos); - } - - /** - * Write a bitmap in the response. - * - * @param x1 horizontal placement of upper left corner of bitmap. - * @param y1 vertical placement of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void addBitmap(int x1, int y1, int w, int h, byte[] bytes, - LinkProperties properties) throws IOException { - LinkBitmap.write(x1, y1, w, h, bytes, properties, link.dos); - } - - /** - * Write a bitmap in the response. - * - * @param lt latitude of placement of upper left corner of bitmap. - * @param ln longitude of placement of upper left corner of bitmap. - * @param offset_x1 horizontal offset of upper left corner of bitmap. - * @param offset_y1 vertical offset of upper left corner of bitmap. - * @param w pixel width of bitmap. - * @param h pixel height of bitmap. - * @param bytes bitmap data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkBitmap - */ - public void addBitmap(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, LinkProperties properties) - throws IOException { - LinkBitmap.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - bytes, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param w pixel width of circle. - * @param h pixel height of circle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(float latPoint, float lonPoint, int w, int h, - LinkProperties properties) throws IOException { - LinkCircle.write(latPoint, lonPoint, w, h, properties, link.dos); - } - - /** - * Write a circle in the response. - * - * @param x1 horizontal pixel placement of center of circle.. - * @param y1 vertical pixel placement of center of circle.. - * @param w pixel width of circle. - * @param h pixel height of circle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(int x1, int y1, int w, int h, - LinkProperties properties) throws IOException { - LinkCircle.write(x1, y1, w, h, properties, link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param offset_x1 horizontal pixel offset of center of circle.. - * @param offset_y1 vertical pixel offset of center of circle.. - * @param w width of circle. - * @param h height of circle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, LinkProperties properties) - throws IOException { - LinkCircle.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(float latPoint, float lonPoint, float radius, - LinkProperties properties) throws IOException { - LinkCircle.write(latPoint, - lonPoint, - radius, - -1, - -1, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param units units of the radius - km, miles, nmiles, degrees.. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(float latPoint, float lonPoint, float radius, - int units, LinkProperties properties) - throws IOException { - LinkCircle.write(latPoint, - lonPoint, - radius, - units, - -1, - properties, - link.dos); - } - - /** - * Write a circle in the response. - * - * @param latPoint latitude of placement of center of circle. - * @param lonPoint longitude of placement of center of circle. - * @param radius radius of circle, in decimal degrees.. - * @param units units of the radius - km, miles, nmiles, degrees.. - * @param nverts number of points to use to approximate the circle. If - * negative, the client algorithm will figure out what is best. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkCircle - */ - public void addCircle(float latPoint, float lonPoint, float radius, - int units, int nverts, LinkProperties properties) - throws IOException { - LinkCircle.write(latPoint, - lonPoint, - radius, - units, - nverts, - properties, - link.dos); - } - - /** - * Write an ellipse with Lat/Lon placement with axis defined in terms of - * distance. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param majorAxisSpan x axis value, units - * @param minorAxisSpan y axis value, units - * @param units integer value for units for distance - OMCircle.KM, - * OMCircle.MILES, OMCircle.NMILES. If < 0, assume decimal - * degrees. - * @param rotationAngle The angle by which the circle/ellipse is to be - * rotated, in radians - * - * @param properties attributes for the circle. - * @throws IOException - */ - public void addEllipse(float latPoint, float lonPoint, float majorAxisSpan, - float minorAxisSpan, int units, float rotationAngle, - LinkProperties properties) throws IOException { - - LinkEllipse.write(latPoint, - lonPoint, - majorAxisSpan, - minorAxisSpan, - units, - rotationAngle, - properties, - link.dos); - } - - /** - * Create a OMEllipse, positioned with a x-y center with x-y axis. - * Rendertype is RENDERTYPE_XY. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param majorAxisSpan horizontal diameter of circle/ellipse, pixels - * @param minorAxisSpan vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians * - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void addEllipse(int x1, int y1, int majorAxisSpan, - int minorAxisSpan, float rotateAngle, - LinkProperties properties) throws IOException { - - LinkEllipse.write(x1, - y1, - majorAxisSpan, - minorAxisSpan, - rotateAngle, - properties, - link.dos); - } - - /** - * Create a OMEllipse, positioned with a lat-lon center and x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void addEllipse(float latPoint, float lonPoint, int w, int h, - float rotateAngle, LinkProperties properties) - throws IOException { - - LinkEllipse.write(latPoint, - lonPoint, - w, - h, - rotateAngle, - properties, - link.dos); - } - - /** - * Create a OMEllipse, positioned at a Lat-lon location, x-y offset, x-y - * axis. Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - * @param rotateAngle the rotation of the ellipse around the center point, - * in radians. - * @param properties the LinkProperties describing the attributes of the - * ellipse. - */ - public void addEllipse(float latPoint, float lonPoint, int offset_x1, - int offset_y1, int w, int h, float rotateAngle, - LinkProperties properties) throws IOException { - - LinkEllipse.write(latPoint, - lonPoint, - offset_x1, - offset_y1, - w, - h, - rotateAngle, - properties, - link.dos); - } - - /** - * Add a Grid with Lat/Lon placement. - * - * @param lt latitude of the top of the grid. - * @param ln longitude of the left side of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution degrees/point between rows of the grid. - * @param hResolution degrees/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties Properties containing attributes. - * @throws IOException - */ - public void addGrid(float lt, float ln, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties) throws IOException { - LinkGrid.write(lt, - ln, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * Add a Grid with XY placement. - * - * @param x1 window location of the left side of the grid. - * @param y1 window location of the top of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties Properties containing attributes. - * @throws IOException - */ - public void addGrid(int x1, int y1, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties) throws IOException { - LinkGrid.write(x1, - y1, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * Grid Lat/lon placement with XY offset. - * - * @param lt latitude of the top of the grid, before the offset. - * @param ln longitude of the left side of the grid, before the offset. - * @param offset_x1 number of pixels to move grid to the right. - * @param offset_y1 number of pixels to move grid down. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties Properties containing attributes. - * @throws IOException - */ - public void addGrid(float lt, float ln, int offset_x1, int offset_y1, - int rows, int columns, float orientation, - float vResolution, float hResolution, int major, - int[] data, LinkProperties properties) - throws IOException { - LinkGrid.write(lt, - ln, - offset_x1, - offset_y1, - rows, - columns, - orientation, - vResolution, - hResolution, - major, - data, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void addLine(float lat_1, float lon_1, float lat_2, float lon_2, - int lineType, LinkProperties properties) - throws IOException { - LinkLine.write(lat_1, - lon_1, - lat_2, - lon_2, - lineType, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param nsegs number of points to use to approximate curved line.. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void addLine(float lat_1, float lon_1, float lat_2, float lon_2, - int lineType, int nsegs, LinkProperties properties) - throws IOException { - LinkLine.write(lat_1, - lon_1, - lat_2, - lon_2, - lineType, - nsegs, - properties, - link.dos); - } - - /** - * Write a line in the response. - * - * @param x1 Horizontal pixel placement of start of line. - * @param y1 Vertical pixel placement of start of line. - * @param x2 Horizontal pixel placement of end of line. - * @param y2 Vertical pixel placement of end of line. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void addLine(int x1, int y1, int x2, int y2, - LinkProperties properties) throws IOException { - LinkLine.write(x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a line in the response. - * - * @param lat_1 latitude of placement of line. - * @param lon_1 longitude of placement of line. - * @param x1 Horizontal pixel offset of start of line. - * @param y1 Vertical pixel offset of start of line. - * @param x2 Horizontal pixel offset of end of line. - * @param y2 Vertical pixel offset of end of line. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkLine - */ - public void addLine(float lat_1, float lon_1, int x1, int y1, int x2, - int y2, LinkProperties properties) throws IOException { - LinkLine.write(lat_1, lon_1, x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, ImageIcon ii, - LinkProperties properties) throws IOException, - InterruptedException { - LinkRaster.write(lt, ln, ii, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(int x1, int y1, ImageIcon ii, - LinkProperties properties) throws IOException, - InterruptedException { - LinkRaster.write(x1, y1, ii, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param ii ImageIcon to place on the map.. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int offset_x1, int offset_y1, - ImageIcon ii, LinkProperties properties) - throws IOException, InterruptedException { - LinkRaster.write(lt, ln, offset_x1, offset_y1, ii, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param image_width width of raster. - * @param image_height height of raster. - * @param image the java.awt.Image. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, Image image, int image_width, - int image_height, LinkProperties properties) - throws IOException, InterruptedException { - LinkRaster.write(lt, - ln, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param image Image to place on map. - * @param image_width width of image. - * @param image_height height of image. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(int x1, int y1, Image image, int image_width, - int image_height, LinkProperties properties) - throws IOException, InterruptedException { - LinkRaster.write(x1, - y1, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param image Image to place on map. - * @param image_width width of image. - * @param image_height height of image. - * @param properties Properties containing attributes. - * @throws IOException - * @throws InterruptedException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int offset_x1, int offset_y1, - Image image, int image_width, int image_height, - LinkProperties properties) throws IOException, - InterruptedException { - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - image, - image_width, - image_height, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int w, int h, int[] pix, - LinkProperties properties) throws IOException { - LinkRaster.write(lt, ln, w, h, pix, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(int x1, int y1, int w, int h, int[] pix, - LinkProperties properties) throws IOException { - LinkRaster.write(x1, y1, w, h, pix, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param w width of raster. - * @param h height of raster. - * @param pix integer image pixel data. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, int[] pix, LinkProperties properties) - throws IOException { - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - pix, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param url the url to download image from. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, String url, - LinkProperties properties) throws IOException { - LinkRaster.write(lt, ln, url, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param url the url to download the image from. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(int x1, int y1, String url, LinkProperties properties) - throws IOException { - LinkRaster.write(x1, y1, url, properties, link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param url the url to download the image from. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int offset_x1, int offset_y1, - String url, LinkProperties properties) - throws IOException { - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - url, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties) throws IOException { - LinkRaster.write(lt, - ln, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param x1 horizontal pixel location of upper left corner of raster. - * @param y1 vertical pixel location of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(int x1, int y1, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties) throws IOException { - LinkRaster.write(x1, - y1, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a raster in the response. - * - * @param lt latitude of placement of upper left corner of raster. - * @param ln longitude of placement of upper left corner of raster. - * @param offset_x1 horizontal pixel offset of upper left corner of raster. - * @param offset_y1 vertical pixel offset of upper left corner of raster. - * @param w width of image. - * @param h height of image. - * @param bytes the image data, indexes into the colortable. - * @param colorTable RGB integers representing colortable of image. - * @param trans the transparency of image. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRaster - */ - public void addRaster(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, Color[] colorTable, - int trans, LinkProperties properties) - throws IOException { - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - w, - h, - bytes, - colorTable, - trans, - properties, - link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of rectangle. - * @param ln1 longitude of placement of upper left corner of rectangle. - * @param lt2 latitude of placement of lower right corner of rectangle. - * @param ln2 longitude of placement of lower right corner of rectangle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void addRectangle(float lt1, float ln1, float lt2, float ln2, - int lType, LinkProperties properties) - throws IOException { - LinkRectangle.write(lt1, ln1, lt2, ln2, lType, properties, link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of rectangle. - * @param ln1 longitude of placement of upper left corner of rectangle. - * @param lt2 latitude of placement of lower right corner of rectangle. - * @param ln2 longitude of placement of lower right corner of rectangle. - * @param lType the line type to use for the rectangle - straight, rhumb, - * great circle. - * @param nsegs number of segments to use to approximate curved rectangle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void addRectangle(float lt1, float ln1, float lt2, float ln2, - int lType, int nsegs, LinkProperties properties) - throws IOException { - LinkRectangle.write(lt1, - ln1, - lt2, - ln2, - lType, - nsegs, - properties, - link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param x1 Horizontal pixel location of upper left corner of rectangle.. - * @param y1 Vertical pixel location of upper left corner of rectangle. - * @param x2 Horizontal pixel location of lower right corner of rectangle.. - * @param y2 Vertical pixel location of lower right corner of rectangle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void addRectangle(int x1, int y1, int x2, int y2, - LinkProperties properties) throws IOException { - LinkRectangle.write(x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a rectangle in the response. - * - * @param lt1 latitude of placement of upper left corner of rectangle. - * @param ln1 longitude of placement of upper left corner of rectangle.. - * @param x1 Horizontal pixel offset of upper left corner of rectangle. - * @param y1 Vertical pixel offset of upper left corner of rectangle. - * @param x2 Horizontal pixel offset of lower right corner of rectangle. - * @param y2 Vertical pixel offset of lower right corner of rectangle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkRectangle - */ - public void addRectangle(float lt1, float ln1, int x1, int y1, int x2, - int y2, LinkProperties properties) - throws IOException { - LinkRectangle.write(lt1, ln1, x1, y1, x2, y2, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param lt1 latitude of placement of upper left corner of point. - * @param ln1 longitude of placement of upper left corner of point. - * @param radius the pixel radius size of the point. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void addPoint(float lt1, float ln1, int radius, - LinkProperties properties) throws IOException { - LinkPoint.write(lt1, ln1, radius, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param x1 Horizontal pixel location of upper left corner of point.. - * @param y1 Vertical pixel location of upper left corner of point. - * @param radius Pixel radius of the point. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void addPoint(int x1, int y1, int radius, LinkProperties properties) - throws IOException { - LinkPoint.write(x1, y1, radius, properties, link.dos); - } - - /** - * Write a point in the response. - * - * @param lt1 latitude of placement of upper left corner of point. - * @param ln1 longitude of placement of upper left corner of point.. - * @param x1 Horizontal pixel offset of upper left corner of point. - * @param y1 Vertical pixel offset of upper left corner of point. - * @param radius Pixel radius of the point. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoint - */ - public void addPoint(float lt1, float ln1, int x1, int y1, int radius, - LinkProperties properties) throws IOException { - LinkPoint.write(lt1, ln1, x1, y1, radius, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param llPoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(double[] llPoints, int units, int lType, - LinkProperties properties) throws IOException { - LinkPoly.write(llPoints, units, lType, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param llpoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param nsegs number of segments to use to approximate curved poly lines.. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(double[] llpoints, int units, int lType, int nsegs, - LinkProperties properties) throws IOException { - LinkPoly.write(llpoints, units, lType, nsegs, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param xypoints alternating x and y pixel locations of poly. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(int[] xypoints, LinkProperties properties) - throws IOException { - LinkPoly.write(xypoints, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param xpoints horizontal pixel locations of poly. - * @param ypoints vertical pixel locations of poly. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(int[] xpoints, int[] ypoints, LinkProperties properties) - throws IOException { - LinkPoly.write(xpoints, ypoints, properties, link.dos); - } - - /** - * Write a poly in the response. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xypoints alternating x and y offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(float latPoint, float lonPoint, int[] xypoints, - int cMode, LinkProperties properties) - throws IOException { - LinkPoly.write(latPoint, - lonPoint, - xypoints, - cMode, - properties, - link.dos); - } - - /** - * Write a poly in the response. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xpoints horizontal pixel offset polygon points. - * @param ypoints vertical pixel offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkPoly - */ - public void addPoly(float latPoint, float lonPoint, int[] xpoints, - int[] ypoints, int cMode, LinkProperties properties) - throws IOException { - LinkPoly.write(latPoint, - lonPoint, - xpoints, - ypoints, - cMode, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of placement of text. - * @param lonPoint longitude of placement of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(float latPoint, float lonPoint, String stuff, - int justify, LinkProperties properties) - throws IOException { - LinkText.write(latPoint, - lonPoint, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param x Horizontal pixel location of text. - * @param y Vertical pixel location of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(int x, int y, String stuff, int justify, - LinkProperties properties) throws IOException { - LinkText.write(x, - y, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of text placement. - * @param lonPoint longitude of text placement. - * @param offset_x Horizontal pixel offset of text. - * @param offset_y Vertical pixel offset of text. - * @param stuff the text. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(float latPoint, float lonPoint, int offset_x, - int offset_y, String stuff, int justify, - LinkProperties properties) throws IOException { - LinkText.write(latPoint, - lonPoint, - offset_x, - offset_y, - stuff, - LinkText.DEFAULT_FONT, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of placement of text. - * @param lonPoint longitude of placement of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(float latPoint, float lonPoint, String stuff, - String font, int justify, LinkProperties properties) - throws IOException { - LinkText.write(latPoint, - lonPoint, - stuff, - font, - justify, - properties, - link.dos); - } - - /** - * Write a text in the response. - * - * @param x Horizontal pixel location of text. - * @param y Vertical pixel location of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(int x, int y, String stuff, String font, int justify, - LinkProperties properties) throws IOException { - LinkText.write(x, y, stuff, font, justify, properties, link.dos); - } - - /** - * Write a text in the response. - * - * @param latPoint latitude of text placement. - * @param lonPoint longitude of text placement. - * @param offset_x Horizontal pixel offset of text. - * @param offset_y Vertical pixel offset of text. - * @param stuff the text. - * @param font a text representation of the font. - * @param justify place the text left, right or centered on location. - * @param properties Properties containing attributes. - * @throws IOException - * @see com.bbn.openmap.layer.link.LinkText - */ - public void addText(float latPoint, float lonPoint, int offset_x, - int offset_y, String stuff, String font, int justify, - LinkProperties properties) throws IOException { - LinkText.write(latPoint, - lonPoint, - offset_x, - offset_y, - stuff, - font, - justify, - properties, - link.dos); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGrid.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGrid.java deleted file mode 100644 index ff67857d2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkGrid.java +++ /dev/null @@ -1,381 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkGrid.java,v $ -// $RCSfile: LinkGrid.java,v $ -// $Revision: 1.7 $ -// $Date: 2007/02/26 17:12:43 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.grid.GridData; -import com.bbn.openmap.util.Debug; - -/** - * Reading and writing the Link protocol version of a grid object. It is assumed - * that the client will know how to render/handle this grid when it arrives, - * since it doesn't have any implicit drawing attributes, despite having a - * semantics object. - */ -public class LinkGrid implements LinkGraphicConstants { - - /** - * Lat/Lon placement. - * - * @param lt latitude of the top of the grid. - * @param ln longitude of the left side of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution degrees/point between rows of the grid. - * @param hResolution degrees/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param dos the data output stream to write the object to. - * @throws IOException - */ - public static void write(float lt, float ln, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.GRID_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_GRID); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(rows); - dos.writeInt(columns); - dos.writeFloat(orientation); - dos.writeFloat(vResolution); - dos.writeFloat(hResolution); - dos.writeByte(major); - - dos.writeInt(data.length); - for (int i = 0; i < data.length; i++) { - dos.writeInt(data[i]); - } - - properties.write(dos); - } - - /** - * XY placement. - * - * @param x1 window location of the left side of the grid. - * @param y1 window location of the top of the grid. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param dos the data output stream to write the object to. - * @throws IOException - */ - public static void write(int x1, int y1, int rows, int columns, - float orientation, float vResolution, - float hResolution, int major, int[] data, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.GRID_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_GRID); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - - dos.writeInt(rows); - dos.writeInt(columns); - dos.writeFloat(orientation); - dos.writeFloat(vResolution); - dos.writeFloat(hResolution); - dos.writeByte(major); - - dos.writeInt(data.length); - for (int i = 0; i < data.length; i++) { - dos.writeInt(data[i]); - } - - properties.write(dos); - } - - /** - * Lat/lon placement with XY offset. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param rows number of vertical points of the grid. - * @param columns number of horizontal points of the grid. - * @param orientation the direction of the vertical axits of the grid, in - * radians from up ( North). - * @param vResolution pixels/point between rows of the grid. - * @param hResolution pixels/point between columns of the grid. - * @param major designation of the presentation of the data, as columns - * (COLUMN_MAJOR) or rows (ROW_MAJOR). - * @param data data points of the grid. - * @param properties description of drawing attributes. - * @param dos the data output stream to write the object to. - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - int rows, int columns, float orientation, - float vResolution, float hResolution, int major, - int[] data, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.GRID_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_GRID); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - - dos.writeInt(rows); - dos.writeInt(columns); - dos.writeFloat(orientation); - dos.writeFloat(vResolution); - dos.writeFloat(hResolution); - dos.writeByte(major); - - dos.writeInt(data.length); - for (int i = 0; i < data.length; i++) { - dos.writeInt(data[i]); - } - - properties.write(dos); - } - - public static void write(OMGrid grid, Link link, LinkProperties props) - throws IOException { - - int major = grid.getMajor() ? LinkGraphicConstants.ROW_MAJOR - : LinkGraphicConstants.COLUMN_MAJOR; - - int rows = grid.getRows(); - int columns = grid.getColumns(); - - GridData gd = grid.getData(); - - if (!(gd instanceof GridData.Int)) { - Debug.output("LinkGrid requires OMGrid containing integer data."); - return; - } - - int[][] d = ((GridData.Int) gd).getData(); - int[] data = new int[rows * columns]; - for (int i = 0; i < d.length; i++) { - for (int j = 0; j < d[0].length; j++) { - data[(i * d[0].length) + j] = d[i][j]; - } - } - - switch (grid.getRenderType()) { - case OMGrid.RENDERTYPE_LATLON: - LinkGrid.write((float) grid.getLatitude(), - (float) grid.getLongitude(), - rows, - columns, - (float) grid.getOrientation(), - (float) grid.getVerticalResolution(), - (float) grid.getHorizontalResolution(), - major, - data, - props, - link.dos); - break; - case OMGrid.RENDERTYPE_XY: - LinkGrid.write((int) grid.getPoint().getX(), - (int) grid.getPoint().getY(), - rows, - columns, - (float) grid.getOrientation(), - (float) grid.getVerticalResolution(), - (float) grid.getHorizontalResolution(), - major, - data, - props, - link.dos); - break; - case OMGrid.RENDERTYPE_OFFSET: - LinkGrid.write((float) grid.getLatitude(), - (float) grid.getLongitude(), - (int) grid.getPoint().getX(), - (int) grid.getPoint().getY(), - rows, - columns, - (float) grid.getOrientation(), - (float) grid.getVerticalResolution(), - (float) grid.getHorizontalResolution(), - major, - data, - props, - link.dos); - break; - default: - Debug.error("LinkGrid.write: grid rendertype unknown."); - } - } - - /** - * Read a Grid off a DataInputStream. Assumes the Grid header has already - * been read. - * - * @param dis DataInputStream to read from. - * @return OMGrid - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMGrid - */ - public static OMGrid read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read a Grid off a DataInputStream. Assumes the Grid header has already - * been read. - * - * @param dis DataInputStream to read from. - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMGrid - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMGrid - */ - public static OMGrid read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - Debug.message("linkdetail", "LinkGrid: reading from link."); - - OMGrid grid = null; - float lat = 0; - float lon = 0; - int x = 0; - int y = 0; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - Debug.message("linkdetail", "LinkGrid: Offset Lat/Lon = " + lat - + "/" + lon + " with"); - // Fall through... - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - Debug.message("linkdetail", "LinkGrid: x/y = " + x + "/" + y); - break; - case RENDERTYPE_LATLON: - default: - lat = dis.readFloat(); - lon = dis.readFloat(); - Debug.message("linkdetail", "LinkGrid: Lat/Lon = " + lat + "/" - + lon); - } - - int rows = dis.readInt(); - int columns = dis.readInt(); - float orientation = dis.readFloat(); - float vResolution = dis.readFloat(); - float hResolution = dis.readFloat(); - int major = dis.readByte(); - - int length = dis.readInt(); - - Debug.message("linkdetail", "LinkGrid details: rows = " - + rows - + ", columns = " - + columns - + ", orientation = " - + orientation - + ", vertical resolution = " - + vResolution - + ", horizontal resolution = " - + hResolution - + ", major dimension = " - + (major == LinkGraphicConstants.COLUMN_MAJOR ? "COLUMN_MAJOR" - : "ROW_MAJOR") + ", with number of points = " + length); - - int[][] data; - if (major == LinkGraphicConstants.COLUMN_MAJOR) { - data = new int[columns][rows]; - } else { - data = new int[rows][columns]; - } - - for (int i = 0; i < data.length; i++) { - for (int j = 0; j < data[0].length; j++) { - data[i][j] = dis.readInt(); - // Debug.message("linkdetail", "LinkGrid reading " + - // (rows*i + j) + " " + - // (major != - // LinkGraphicConstants.COLUMN_MAJOR?"column":"row")+ - // " " + j + " = " + Integer.toHexString(data[i][j]) + - // " (" + data[i][j] + ")"); - } - // Debug.message("linkdetail", "LinkGrid reading " + - // (major == - // LinkGraphicConstants.COLUMN_MAJOR?"column":"row")+ - // " " + i); - } - - Debug.message("linkdetail", "LinkGrid read all the data."); - - switch (renderType) { - case RENDERTYPE_OFFSET: - grid = new OMGrid(lat, lon, x, y, vResolution, hResolution, data); - break; - case RENDERTYPE_XY: - grid = new OMGrid(x, y, vResolution, hResolution, data); - break; - case RENDERTYPE_LATLON: - default: - grid = new OMGrid(lat, lon, vResolution, hResolution, data); - } - - Debug.message("linkdetail", "LinkGrid created OMGrid."); - - if (grid != null) { - grid.setMajor(major == LinkGraphicConstants.COLUMN_MAJOR ? true - : false); - grid.setOrientation(orientation); - LinkProperties.loadPropertiesIntoOMGraphic(dis, grid, propertiesBuffer); - } - - Debug.message("linkdetail", "LinkGrid done."); - - return grid; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLayer.java deleted file mode 100644 index afe77c379..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLayer.java +++ /dev/null @@ -1,1336 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkLayer.java,v $ -// $RCSfile: LinkLayer.java,v $ -// $Revision: 1.17 $ -// $Date: 2007/06/21 21:39:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/* Java Core */ -import java.awt.Container; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.Enumeration; -import java.util.Properties; -import java.util.Vector; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The LinkLayer is a Swing component, and an OpenMap layer, that communicates - * with a server via the Link protocol. It transmits graphics requests and - * gesture information, and handles the responses to those queries. The entry in - * the openmap.properties file looks like this: - *

- * - *

- * 
- * 
- * 
- * 
- *       # port number of server
- *       link.port=3031
- *      
- *       # host name of server
- *       link.host=host.com
- *      
- *       # URL of properties file for server attributes.  Properties
- *       # contained in this file are passed directly to the server to provide
- *       # additional information to the server about how to provide the
- *       # graphics.  Some standard properties are listed in the
- *       # LinkPropertiesConstants file, but any property can be passed to the
- *       # server.  How the server handles the property depends on the server,
- *       # but non-applicable properties are ignored.
- *       link.propertiesURL=http://location.of.properties.file.com
- * 
- * 
- * 
- * 
- * 
- * - * You have to call setProperties() on this layer to set its parameters, and to - * start the thread that listens to updates from the server. - */ -public class LinkLayer extends OMGraphicHandlerLayer implements - MapMouseListener, LinkPropertiesConstants, LinkActionConstants, - DrawingToolRequestor { - - /** - * The thread listener used to communicate asynchronously. The LinkLayer - * sends out requests and notifications to the server, and the LinkListener - * reads any input from the server, making calls on the LinkLayer as - * appropriate. - */ - protected LinkListener listener; - /** - * A masked integer describing which gestures should be sent to the server. - */ - protected int gestureDescriptor = 0; - /** The port to connect to the server on. */ - protected int port; - /** The host where the server is running. */ - protected String host; - /** - * The special parameters (attributes) transmitted to the server with every - * query. - */ - protected LinkProperties args; - /** - * The object that provides a link to the layer (and its various threads) on - * a coordinateed basis. - */ - protected LinkManager linkManager = null; - /** The flag to suppress pop-up messages. */ - protected boolean quiet = false; - /** The generator to use with LinkGrid objects. */ - protected OMGridGenerator currentGenerator = null; - - /** - * The property name to specify what port the server is running on. "port" - */ - public final static String PortProperty = "port"; - /** - * The property name to specify the hostname the server is running on. - * "host" - */ - public final static String HostProperty = "host"; - /** - * The property name to specify a URL of a properties file containing - * properties that will be sent to the server within requests to it. The - * contents of this file depends on the server. "propertiesURL" - */ - public final static String ArgsProperty = "propertiesURL"; - public final static String ServerLocationProperty = "isl"; - /** - * The property to make the layer quiet. "quiet" - */ - public final static String QuietProperty = "quiet"; - /** - * The property to specify which grid generator to use for grid objects. - * "gridGenerator" - */ - public final static String GridGeneratorProperty = "gridGenerator"; - /** - * The property to set a pixel distance limit for gestures. "distanceLimit" - */ - public final static String DistanceLimitProperty = "distanceLimit"; - - public final static int DEFAULT_DISTANCE_LIMIT = 4; - - /** - * The maximum distance away a mouse event can happen away from a graphic in - * order for it to be considered to have touched. - */ - protected int distanceLimit = DEFAULT_DISTANCE_LIMIT; - - /** - * The property to set to true if the server should be able to decide when - * to kill the client, the overall application. False by default, only - * modified in setProperties. "exitOnCommand" - */ - public final static String ExitOnCommandProperty = "exitOnCommand"; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public LinkLayer() { - // We don't want to reset the OMGraphicsList automatically - // when the projection changes, now. With ansynchronous - // behavior, the current list should be reprojected and the - // server notified, and the server will update itself if - // needed. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy( - this) { - // Modified so it doesn't reset the OMGraphicList when - // the SwingWorker thread returns. The list has - // already been nulled out, will be reset when the - // asynchronous thread decides it is. - public void workerComplete(OMGraphicList list) { - } - }); - } - - /** - * Constructor to use when LinkLayer is not being used with OpenMap - * application. - * - * @param host - * the hostname of the server's computer. - * @param port - * the port number of the server. - * @param propertiesURL - * the URL of a properties file that contains parameters for the - * server. - */ - public LinkLayer(String host, int port, String propertiesURL) { - this(); - this.host = host; - this.port = port; - linkManager = new LinkManager(host, port); - - args = new LinkProperties(); - - if (propertiesURL != null) { - try { - URL propertiesFile = new URL(propertiesURL); - args.load(propertiesFile.openStream()); - } catch (java.net.MalformedURLException mue) { - System.err.println("LinkLayer: Properties URL isn't valid: " - + propertiesURL); - System.err.println(mue); - } catch (IOException ioe) { - System.err - .println("LinkLayer: IOException reading properties file:"); - System.err.println(ioe); - } - } - } - - /** - * Sets the current graphics list to the given list. - * - * @param aList - * a list of OMGraphics - */ - public synchronized void setGraphicList(LinkOMGraphicList aList) { - super.setList(aList); - } - - /** - * Retrieves the current graphics list. - */ - public synchronized LinkOMGraphicList getGraphicList() { - return (LinkOMGraphicList) getList(); - } - - /** - * Called when the layer is no longer part of the map. In this case, we - * should disconnect from the server if we have a link. - */ - public void removed(Container cont) { - linkManager.resetLink(); - } - - /** - * Sets the masked integer which indicates what types of events get sent to - * the server. - * - * @param descriptor - * masked int - * @see LinkActionRequest - */ - public synchronized void setGestureDescriptor(int descriptor) { - gestureDescriptor = descriptor; - } - - /** - * Gets the masked integer which indicates what types of events get sent to - * the server. - * - * @return descriptor masked int - * @see LinkActionRequest - */ - public synchronized int getGestureDescriptor() { - return gestureDescriptor; - } - - /** - * Set all the Link properties from a properties object. - * - * @param prefix - * the prefix to the properties that might individualize it to a - * particular layer. - * @param properties - * the properties for the layer. - */ - public void setProperties(String prefix, Properties properties) { - - super.setProperties(prefix, properties); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String quietString = properties.getProperty(realPrefix + QuietProperty); - if (quietString != null && quietString.intern().equals("true")) { - quiet = true; - } - - host = properties.getProperty(realPrefix + HostProperty); - - port = PropUtils.intFromProperties(properties, realPrefix - + PortProperty, LinkServerStarter.DEFAULT_PORT); - - linkManager = new LinkManager(host, port); - - linkManager.setObeyCommandToExit(PropUtils - .booleanFromProperties(properties, realPrefix - + ExitOnCommandProperty, false)); - - String propertiesURL = properties - .getProperty(realPrefix + ArgsProperty); - - args = new LinkProperties(); // Empty if not filled. - if (propertiesURL != null) { - try { - URL propertiesFile = new URL(propertiesURL); - args.load(propertiesFile.openStream()); - - // Need to do something here. The LinkPropertiesConstants have - // changed in LinkProtocol version .6, to much small strings - // that don't match up with the DrawingAttributes properties. We - // need to check for the old property names and replace them - // with the new property names. - - checkAndReplaceOldPropertyNames(args); - - } catch (java.net.MalformedURLException mue) { - System.err.println("LinkLayer: Properties URL isn't valid: " - + realPrefix + ArgsProperty); - System.err.println(mue); - } catch (IOException ioe) { - System.err - .println("LinkLayer: IOException reading properties file:"); - System.err.println(ioe); - } - } - - currentGenerator = (OMGridGenerator) PropUtils - .objectFromProperties(properties, realPrefix - + GridGeneratorProperty); - - if (currentGenerator == null) { - Debug.message("linkdetail", getName() - + "|LinkLayer: no generator for grid objects."); - } - - distanceLimit = PropUtils.intFromProperties(properties, realPrefix - + DistanceLimitProperty, distanceLimit); - - // listener = new LinkListener(linkManager, this, - // currentGenerator); - } - - /** - * The LinkPropertiesConstants have changed in LinkProtocol version .6, to - * much small strings that don't match up with the DrawingAttributes - * properties. We need to check for the old property names and replace them - * with the new property names. - * - * @param props - */ - public void checkAndReplaceOldPropertyNames(LinkProperties props) { - checkAndReplaceOldPropertyName(props, LPC_OLD_LINECOLOR, LPC_LINECOLOR); - checkAndReplaceOldPropertyName(props, LPC_OLD_LINESTYLE, LPC_LINESTYLE); - checkAndReplaceOldPropertyName(props, LPC_OLD_HIGHLIGHTCOLOR, - LPC_HIGHLIGHTCOLOR); - checkAndReplaceOldPropertyName(props, LPC_OLD_FILLCOLOR, LPC_FILLCOLOR); - checkAndReplaceOldPropertyName(props, LPC_OLD_FILLPATTERN, - LPC_FILLPATTERN); - checkAndReplaceOldPropertyName(props, LPC_OLD_LINEWIDTH, LPC_LINEWIDTH); - checkAndReplaceOldPropertyName(props, LPC_OLD_LINKTEXTSTRING, - LPC_LINKTEXTSTRING); - checkAndReplaceOldPropertyName(props, LPC_OLD_LINKTEXTFONT, - LPC_LINKTEXTFONT); - } - - public void checkAndReplaceOldPropertyName(LinkProperties props, - String oldPropertyName, - String newPropertyName) { - String property = props.getProperty(oldPropertyName); - if (property != null) { - props.remove(oldPropertyName); - props.put(newPropertyName, property); - } - } - - protected void setListener(LinkListener ll) { - listener = ll; - } - - protected LinkListener getListener() { - return listener; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the link. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - * @return a list of graphics. - */ - public synchronized OMGraphicList prepare() { - - OMGraphicList currentList = getList(); - - if (listener == null) { - listener = new LinkListener(linkManager, this, currentGenerator); - } - - if (listener != null && !listener.isListening()) { - // Call LinkListener to launch SwingWorker to kick off a - // thread for the listener. - listener.startUp(); - } - - if (Debug.debugging("link")) { - Debug.output(getName() + "|LinkLayer.prepare(): Listener " - + (listener == null ? "is null," : "is OK,") - + " listening (" - + (listener == null ? "nope" : "" + listener.isListening()) - + ")"); - } - - Projection projection = getProjection(); - if (projection == null) { - Debug - .error("Link Layer needs to be added to the MapBean before it can get graphics!"); - return currentList; - } else if (currentList != null) { - // If the list isn't empty, it isn't being cleared when a - // new projection is received, as dictated by the policy - // of the layer. Should regenerate it here. If it's - // understood that a new list will be sent by the server, - // then a different ProjectionChangePolicy should be used. - currentList.generate(projection); - } - - Debug.message("basic", getName() + "|LinkLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // LinkOMGraphicList is made up of OMGraphics, which are - // generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (Debug.debugging("link")) { - System.out.println(getName() + "|LinkLayer.prepare(): " - + "calling getRectangle " + " with projection: " - + projection + " ul = " + projection.getUpperLeft() - + " lr = " + projection.getLowerRight()); - } - - // LinkOMGraphicList omGraphicList; - - // //////////// Call getRectangle for server.... - try { - // We do want the link object here... If another thread is - // using the link, wait. - ClientLink l = linkManager.getLink(true); - - if (l == null) { - System.err - .println("LinkLayer: unable to get link in prepare()."); - return currentList; - } - - synchronized (l) { - // omGraphicList = getGraphics(l, projection); - sendMapRequest(l, projection); - } - - linkManager.finLink(); - - } catch (UnknownHostException uhe) { - System.err.println("LinkLayer: unknown host!"); - // return currentList; - } catch (java.io.IOException ioe) { - System.err - .println("LinkLayer: IOException contacting server for map request!"); - System.err.println(ioe); - - linkManager.resetLink(); - - if (!quiet) { - fireRequestMessage("Communication error between " + getName() - + " layer\nand Link Server: Host: " + host + ", Port: " - + port); - } - - System.err.println("LinkLayer: Communication error between " - + getName() + " layer\nand Link Server: Host: " + host - + ", Port: " + port); - // return currentList; - } - - // /////////////////////////////////////////////////// - // With asynchronous behavior, we don't listen to the reply - // now. The LinkListener will handle setting the new - // OMGraphicList if one is needed as decided by the server. - - // /////////////////// - // safe quit - // int size = 0; - // if (omGraphicList != null) { - // size = omGraphicList.size(); - - // if (Debug.debugging("basic")) { - // System.out.println(getName()+ - // "|LinkLayer.prepare(): finished with "+ - // size+" graphics"); - // } - - // // omGraphicList.project(projection); - // } - // else - // Debug.message("basic", getName()+ - // "|LinkLayer.prepare(): finished with null graphics list"); - - return currentList; - } - - /** - * Creates the LinkMapRequest. - * - * @param link - * the link to communicate over. - * @param proj - * the projection to give to the graphics. - * @throws IOException - */ - protected void sendMapRequest(ClientLink link, Projection proj) - throws IOException { - - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - float ulLat = (float) ul.getY(); - float ulLon = (float) ul.getX(); - float lrLat = (float) lr.getY(); - float lrLon = (float) lr.getX(); - - LinkBoundingPoly[] boundingPolys = null; - - if (ProjMath.isCrossingDateline(ulLon, lrLon, proj.getScale())) { - Debug.message("link", "Dateline is on screen"); - - float ymin = (float) Math.min(ulLat, lrLat); - float ymax = (float) Math.max(ulLat, lrLat); - - // xmin, ymin, xmax, ymax - boundingPolys = new LinkBoundingPoly[2]; - boundingPolys[0] = new LinkBoundingPoly(ulLon, ymin, 180.0f, ymax); - boundingPolys[1] = new LinkBoundingPoly(-180.0f, ymin, lrLon, ymax); - - } else { - boundingPolys = new LinkBoundingPoly[1]; - boundingPolys[0] = new LinkBoundingPoly(ulLon, lrLat, lrLon, ulLat); - } - - Point2D center = proj.getCenter(); - LinkMapRequest.write((float) center.getY(), (float) center.getX(), proj - .getScale(), proj.getHeight(), proj.getWidth(), boundingPolys, - args, link); - - // /////////////////////////////////////////////////// - // With asynchronous behavior, we don't listen to the reply - // now. The LinkListener will handle it. - - // link.readAndParse(proj, currentGenerator); - - // // While we are here, check for any change in gesture query - // // requests. - // LinkActionRequest lar = link.getActionRequest(); - // if (lar != null) { - // setGestureDescriptor(lar.getDescriptor()); - // } - - // handleLinkGraphicList(link.getGraphicList()); - // /////////////////////////////////////////////////// - } - - public void handleLinkGraphicList(LinkGraphicList lgl) { - Debug.message("link", "LinkLayer.handleLinkGraphicList()"); - - if (lgl != null) { - // Deal with all the messaging.... - handleMessages(lgl.getProperties()); - LinkOMGraphicList lomgl = lgl.getGraphics(); - setGraphicList(lomgl); - // Do we need to regenerate? - Projection proj = getProjection(); - if (lomgl.getNeedToRegenerate(proj)) { - // set to false in LinkGraphicList.readGraphics if the - // projection was there when the LinkGraphicList was - // created. If it wasn't there, we need to try to - // project them before calling repaint(). Projection - // will be null if the layer hasn't been added to the - // map. - lomgl.generate(proj); - } - - repaint(); - } - } - - public void handleLinkActionList(LinkActionList lal) { - Debug.message("link", "LinkLayer.handleLinkActionList()"); - - if (lal == null) { - return; - } - - handleMessages(lal.getProperties()); - - // The only thing we need to do is handle any gesture - // changes... - Vector updates = lal.getGraphicUpdates(); - Enumeration items = updates.elements(); - boolean needRepaint = false; - LinkOMGraphicList graphics = getGraphicList(); - - Projection proj = getProjection(); - - if (graphics == null) { - Debug - .message("link", - "LinkLayer.handleLinkActionList: null LinkOMGraphicList, making new one..."); - // Why ignore what the server has to say, set the new - // OMGraphicList and react accordingly. - graphics = new LinkOMGraphicList(); - setGraphicList(graphics); - } - - while (items.hasMoreElements()) { - needRepaint = true; // We do! - GraphicUpdate gu = (GraphicUpdate) items.nextElement(); - - if (gu == null) { - Debug - .message("link", - "LinkLayer.handleLinkActionList: null GraphicUpdate, skipping..."); - continue; - } - - // Take care of this first..... - if (LinkUtil.isMask(gu.action, MODIFY_DESELECTALL_GRAPHIC_MASK)) { - Debug - .message("link", - "LinkLayer.handleLinkActionList: deselecting all graphics"); - graphics.deselect(); - } - - // Find the graphic that we are talking about - if the - // ID is not "none", or if the id doesn't match the - // gesGraphic LinkGraphicID, then look for the new - // graphic. Otherwise, assume that the gesGraphic is - // the one that the action refers to. - - // This code was moved from handleGesture to here, the - // main difference being that in handleGesture any actual - // OMGraphic that was gestured over was already known at - // this point, and there was no sense looking for it if - // you already had it. Since we moved the code, and this - // method is being called from a different thread, we - // don't have that luxury - we have to look up the - // OMGraphic again... - - OMGraphic gug = gu.graphic; - OMGraphic reactionGraphic = null; - int reactionGraphicIndex = Link.UNKNOWN; - - if (LinkUtil.isMask(gu.action, UPDATE_ADD_GRAPHIC_MASK)) { - if (Debug.debugging("link")) { - Debug - .output("LinkLayer.handleLinkActionList: adding graphic, id:" - + gu.id); - } - if (gug != null) { - gug.generate(proj); - graphics.add(gug); - reactionGraphic = gug; - } else { - Debug.message("link", - "LinkLayer.handleLinkActionList: trying to add null OMGraphic, id: " - + gu.id); - } - } else if (gu.id != null) { - reactionGraphicIndex = graphics.getOMGraphicIndexWithId(gu.id); - if (reactionGraphicIndex == Link.UNKNOWN) { - // Must be an addition/new graphic - if (LinkUtil.isMask(gu.action, UPDATE_ADD_GRAPHIC_MASK)) { - // If gu.graphic is null, this will throw an - // exception - if (Debug.debugging("link")) { - Debug - .output("LinkLayer.handleLinkActionList: adding graphic " - + gu.id); - } - if (gug != null) { - gug.generate(proj); - graphics.add(gug); - reactionGraphic = gug; - } else { - Debug.message("link", - "LinkLayer.handleLinkActionList: trying to add null OMGraphic, id: " - + gu.id); - } - } else { - gu.action = 0; // No action... - Debug - .error("LinkLayer.handleLinkActionList: Gesture Response on an unknown graphic."); - } - } else if (LinkUtil.isMask(gu.action, UPDATE_GRAPHIC_MASK)) { - if (gug != null) { - gug.generate(proj); - reactionGraphic = gug; - } else { - Debug.message("link", - "LinkLayer.handleLinkActionList: trying to update null OMGraphic, id: " - + gu.id); - } - } else { - reactionGraphic = graphics.getOMGraphicWithId(gu.id); - } - } else { - Debug - .error("LinkLayer.handleLinkActionList: null ID for graphic"); - } - - // Now, perform the appropriate action on the graphic... - - // Delete a graphic... If you do this, nothing else - // gets done on the graphic... - if (LinkUtil.isMask(gu.action, MODIFY_DELETE_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: deleting graphic"); - graphics.remove(reactionGraphicIndex); - } else { - - // For properties updating, or graphic replacement - if (LinkUtil.isMask(gu.action, UPDATE_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: updating graphic"); - graphics.setOMGraphicAt(reactionGraphic, - reactionGraphicIndex); - } - - if (reactionGraphic != null) { - // For graphic selection and deselection - if (LinkUtil.isMask(gu.action, MODIFY_SELECT_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: selecting graphic"); - reactionGraphic.select(); - } else if (LinkUtil.isMask(gu.action, - MODIFY_DESELECT_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: deselecting graphic"); - reactionGraphic.deselect(); - } - } - - // Now, raising or lowering the graphic... - if (LinkUtil.isMask(gu.action, MODIFY_RAISE_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: raising graphic"); - graphics.moveIndexedToTop(reactionGraphicIndex); - } else if (LinkUtil - .isMask(gu.action, MODIFY_LOWER_GRAPHIC_MASK)) { - Debug.message("link", "LinkLayer: lowering graphic"); - graphics.moveIndexedToBottom(reactionGraphicIndex); - } - - } // else if not deleting it... - } // while - - if (lal.getNeedMapUpdate()) { - updateMap(lal.getMapProperties()); - lal.setNeedMapUpdate(false); - needRepaint = false; - } - - if (needRepaint) { - repaint(); - } - } - - public void handleLinkActionRequest(LinkActionRequest lar) { - Debug.message("link", "LinkLayer.handleLinkActionRequest()"); - if (lar != null) { - setGestureDescriptor(lar.getDescriptor()); - } - } - - /** - * Looks at a properties object, and checks for the pre-defined messaging - * attributes. Then, the information delegator is called to handle their - * display. - * - * @param props - * LinkProperties containing messages. - */ - public void handleMessages(LinkProperties props) { - String value = props.getProperty(LPC_INFO); - if (value != null) - fireRequestInfoLine(value); - - value = props.getProperty(LPC_URL); - if (value != null) { - fireRequestURL(value); - } else { - value = props.getProperty(LPC_HTML); - if (value != null) - fireRequestBrowserContent(value); - } - value = props.getProperty(LPC_MESSAGE); - if (value != null) - fireRequestMessage(value); - } - - // ---------------------------------------------------------------------- - // MapMouseListener interface implementation - // ---------------------------------------------------------------------- - /** Return the MapMouseListener for the layer. */ - public synchronized MapMouseListener getMapMouseListener() { - return this; - } - - /** - * Return the strings identifying the Mouse Modes that the MapMouseListener - * wants to receive gestures from. - */ - public String[] getMouseModeServiceList() { - String[] services = { SelectMouseMode.modeID }; - return services; - } - - public boolean mousePressed(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_PRESSED_MASK)) { - return handleGesture(MOUSE_PRESSED_MASK, e); - } - return false; - } - - public boolean mouseReleased(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_RELEASED_MASK)) { - return handleGesture(MOUSE_RELEASED_MASK, e); - } - return false; - } - - public boolean mouseClicked(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_CLICKED_MASK)) { - return handleGesture(MOUSE_CLICKED_MASK, e); - } - return false; - } - - public void mouseEntered(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_ENTERED_MASK)) { - handleGesture(MOUSE_ENTERED_MASK, e); - } - } - - public void mouseExited(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_EXITED_MASK)) { - handleGesture(MOUSE_EXITED_MASK, e); - } - } - - public boolean mouseDragged(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_DRAGGED_MASK)) { - return handleGesture(MOUSE_DRAGGED_MASK, e); - } - return false; - } - - public boolean mouseMoved(MouseEvent e) { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_MOVED_MASK)) { - return handleGesture(MOUSE_MOVED_MASK, e); - } - return false; - } - - public void mouseMoved() { - if (LinkUtil.isMask(getGestureDescriptor(), MOUSE_MOVED_MASK)) { - handleGesture(MOUSE_MOVED_MASK, null); - } - } - - /** - * Given a graphic and the type of gesture caught, react to it based on the - * properties object located in the Graphic. The default behavior here is - * that if the gesture is a MouseMoved, select the graphic, and if there is - * an info line, show it. If the gesture is a MouseRelease, display the info - * line, and also check the following, in this order: url and then html. If - * there is a message property, the message is sent in a pop-up window. - * - * @param graphic - * the graphic to check out. - * @param descriptor - * the type of gesture. - * @param e - * mouse event, to get location. - * @return true if the server still needs to be told - per descriptor bit - * 11. - */ - protected boolean graphicGestureReaction(OMGraphic graphic, int descriptor, - MouseEvent e) { - LinkProperties props = (LinkProperties) graphic.getAttribute(OMGraphic.APP_OBJECT); - - // Mouse clicked - boolean mc = LinkUtil.isMask(descriptor, MOUSE_CLICKED_MASK); - // Mouse released - boolean mr = LinkUtil.isMask(descriptor, MOUSE_RELEASED_MASK); - // Mouse moved - boolean mm = LinkUtil.isMask(descriptor, MOUSE_MOVED_MASK); - // server inform - boolean si = LinkUtil.isMask(getGestureDescriptor(), - SERVER_NOTIFICATION_MASK); - - boolean ret = true; - - if (mr || mc) { - String url = props.getProperty(LPC_URL); - if (url != null) { - if (Debug.debugging("link")) { - System.out - .println("LinkLayer:graphicGestureReaction: displaying url: " - + url); - } - fireRequestURL(url); - ret = si; - } else { - String html = props.getProperty(LPC_HTML); - if (html != null) { - fireRequestBrowserContent(html); - ret = si; - } - } - - // Just reuse url instead of declaring another string - // object - url = props.getProperty(LPC_MESSAGE); - if (url != null) { - fireRequestMessage(url); - ret = si; - } - } - - if (mr || mm || mc) { - String info = props.getProperty(LPC_INFO); - if (info != null) { - if (Debug.debugging("link")) { - System.out - .println("LinkLayer:graphicGestureReaction: displaying info line: " - + info); - } - fireRequestInfoLine(info); - ret = si; - } - } - - return ret; - } - - /** - * Send the query, act on the response, and tell the caller if the gesture - * was consumed. The Link actually gets a copy of the layer to handle - * communication with the InformationDelegator. The GraphicUpdates are - * handled in this method - the graphics list is modified. - * - * @param descriptor - * a masked integer telling the type of gesture. - * @param e - * the MouseEvent. - * @return true if the event was consumed. - */ - protected boolean handleGesture(int descriptor, MouseEvent e) { - Debug.message("link", "LinkLayer: handleGesture:"); - - try { - LinkOMGraphicList graphics = getGraphicList(); // Get old - // list - - OMGraphic gesGraphic = null; - if (graphics == null) { - // Nothing to search on - this condition occurs when - // the layer is already busy getting new graphics as a - // result of a changed projection. - // It also occurs when the layer does not have any graphics - // in it. - Debug.message("link", "LinkLayer: null graphics list."); - } else { - if (e == null) { - graphics.deselect(); - return false; - } - - // Find out if a graphic is closeby... - // int gesGraphicIndex = graphics.findIndexOfClosest(e.getX(), - // e.getY(), - // distanceLimit); - - // We need to do this to deselect everything else too. - gesGraphic = graphics.selectClosest(e.getX(), e.getY(), - distanceLimit); - } - - String id = null; - - // If there was a graphic, set the mask to indicate that, - // and keep track of the graphic and the list index of the - // graphic for the response. If a graphic modify command - // comes back without an ID, then we'll assume the server - // was referring to this graphic. - if (gesGraphic != null) { - - boolean tellServer = graphicGestureReaction(gesGraphic, - descriptor, e); - - if (!tellServer) { - repaint(); - return true; - } - - // needRepaint = true; // Why? At this point, we - // should wait to see what the server wants us to do, - // we should only repaint if a graphic update comes - // back. - - descriptor = LinkUtil.setMask(descriptor, GRAPHIC_ID_MASK); - id = ((LinkProperties) gesGraphic.getAttribute(OMGraphic.APP_OBJECT)) - .getProperty(LPC_GRAPHICID); - } else { - // clear out info line - fireRequestInfoLine(""); - } - - // server inform - if (!LinkUtil.isMask(getGestureDescriptor(), - SERVER_NOTIFICATION_MASK)) { - return false; - } - - // Get the lat/lon point of the event - Point2D llpoint = getProjection().inverse(e.getX(), e.getY()); - - // Don't need these anymore, look below for explaination - // for asynchronous operation. - // LinkActionList lal; - // LinkActionRequest lar; - - ClientLink l = linkManager.getLink(false); - - // We'll check this here because we don't want to wait if - // it is not available - it could be used for another - // graphics or gui fetch. - if (l == null) { - Debug - .message("link", - "LinkLayer: unable to get link in handleGesture()."); - return false; - } - - // Using the link - carefully prevent others from using it - // too! - synchronized (l) { - if (id != null) { - args.setProperty(LPC_GRAPHICID, id); - } else { - // Reset this to prevent sending the id of a previously - // selected graphic when no graphic is clicked on. - args.remove(LPC_GRAPHICID); - } - - // Send the query - LinkActionRequest.write(descriptor, e, (float) llpoint.getY(), - (float) llpoint.getX(), args, l); - - // /////////////////////////////////////////////////// - // With asynchronous behavior, we don't listen to the - // reply - // now. The LinkListener will handle it. - - // // Read the response - // l.readAndParse(getProjection(), currentGenerator, - // this); - - // lal = l.getActionList(); - // lar = l.getActionRequest(); - - // if (id != null) { - // args.remove(LPC_GRAPHICID); - // } - // /////////////////////////////////////////////////// - - } - - linkManager.finLink(); - - // /////////////////////////////////////////////////// - // With asynchronous behavior, we don't listen to the - // reply - // now. The LinkListener will handle it. - - // handleLinkActionRequest(lar); - - // // If nothing else was returned concerning the gesture - // query - // if (lal == null) { - // return false; - // } - - // handleLinkActionList(lal); - // return lal.consumedGesture(); - - // /////////////////////////////////////////////////// - - // I don't know what to answer here, we really don't know - // at this point. There may be something we can do to set - // up some lag circle to start returning true if we need - // to, but if we're not listening in this thread, we just - // don't know if the gesture is consumed here and we can't - // hold up the event thread to find out. - return false; - - } catch (IOException ioe) { - System.err - .println("LinkLayer: IOException contacting server during gesture handling!"); - System.err.println(ioe); - linkManager.resetLink(); - return false; - } - } - - // DrawingToolRequestor method - public void drawingComplete(OMGraphic omg, OMAction action) { - // //////////// send the new graphic, along with instructions - // on what to do with it, to the server. - String id = null; // unknown - - Object obj = omg.getAttribute(OMGraphic.APP_OBJECT); - LinkProperties lp = null; - if (obj instanceof LinkProperties) { - lp = (LinkProperties) obj; - id = lp.getProperty(LPC_GRAPHICID); - } - - if (id == null) { - // Doesn't look like it was a modified graphic already - // received from the server, so we should tell the server - // to add it to its list. - action.setMask(OMAction.ADD_GRAPHIC_MASK); - } - - try { - // We do want the link object here... If another thread is - // using the link, wait. - ClientLink l = linkManager.getLink(true); - - if (l == null) { - System.err - .println("LinkLayer.drawingComplete: unable to get link."); - return; - } - - synchronized (l) { - LinkActionList lal = new LinkActionList(l, new LinkProperties()); - - if (action.isMask(OMAction.ADD_GRAPHIC_MASK) - || action.isMask(OMAction.UPDATE_GRAPHIC_MASK)) { - lal.writeGraphicGestureHeader(action.getValue()); - LinkGraphic.write(omg, l); - } else { - // This shouldn't ever get called with a null lp - // properties object. If the object is new or - // doesn't have an ID, the upper paragraph will - // get called. - lal.modifyGraphic(action.getValue(), lp); - } - lal.end(Link.END_TOTAL); - } - - // /////////////////////////////////////////////////// - // With asynchronous behavior, we don't listen to the - // reply - // now. The LinkListener will handle it. - - // l.readAndParse(getProjection(), currentGenerator); - // /////////////////////////////////////////////////// - - linkManager.finLink(); - - } catch (UnknownHostException uhe) { - Debug.error("LinkLayer: unknown host!"); - return; - } catch (java.io.IOException ioe) { - Debug.error("LinkLayer: Communication error between " + getName() - + " layer\nand Link Server: Host: " + host + ", Port: " - + port + "LinkLayer: IOException contacting server!\n" - + ioe.getMessage()); - - linkManager.resetLink(); - - if (!quiet) { - fireRequestMessage("Communication error between " + getName() - + " layer\nand Link Server: Host: " + host + ", Port: " - + port); - } - - return; - } - } - - /** - * Set the search distance limit pixel distance for graphics searches. When - * the graphics list is checked for a graphic that is closest to a mouse - * event, this is the pixel limit within hits are considered. - * - * @param limit - * the pixel limit to consider something "closest". - */ - public void setDistanceLimit(int limit) { - if (limit < 0) { - distanceLimit = 0; - } else { - distanceLimit = limit; - } - } - - /** - * Get the search distance limit pixel distance for graphics searches. - */ - public int getDistanceLimit() { - return distanceLimit; - } - - /** - * Looks at a properties object, and checks for map updates. - * - * @param props - * LinkProperties containing map parameters. - */ - public void updateMap(LinkProperties props) { - - Proj projection = (Proj) getProjection(); - Point2D center = projection.getCenter(); - float latitude = PropUtils.floatFromProperties(props, LPC_CENTER_LAT, - (float) center.getY()); - float longitude = PropUtils.floatFromProperties(props, LPC_CENTER_LONG, - (float) center.getX()); - float scale = PropUtils.floatFromProperties(props, LPC_SCALE, - projection.getScale()); - int width = PropUtils.intFromProperties(props, LPC_WIDTH, projection - .getWidth()); - int height = PropUtils.intFromProperties(props, LPC_HEIGHT, projection - .getHeight()); - - String projType = props.getProperty(LPC_PROJECTION); - - float latmin = PropUtils - .floatFromProperties(props, LPC_LATMIN, -1000.f); - float latmax = PropUtils - .floatFromProperties(props, LPC_LATMAX, -1000.f); - float lonmin = PropUtils - .floatFromProperties(props, LPC_LONMIN, -1000.f); - float lonmax = PropUtils - .floatFromProperties(props, LPC_LONMAX, -1000.f); - - if (latmin >= -90.f && latmax <= 90.f && lonmin >= -180.f - && lonmax <= 180.f && latmin <= latmax && lonmin <= lonmax) { - // Calculate center point - double dist = 0.5f * GreatCircle.sphericalDistance(ProjMath - .degToRad(latmax), ProjMath.degToRad(lonmin), ProjMath - .degToRad(latmin), ProjMath.degToRad(lonmax)); - double azimuth = GreatCircle.sphericalAzimuth(ProjMath - .degToRad(latmax), ProjMath.degToRad(lonmin), ProjMath - .degToRad(latmin), ProjMath.degToRad(lonmax)); - center = GreatCircle.sphericalBetween(ProjMath.degToRad(latmax), - ProjMath.degToRad(lonmin), - dist, azimuth); - latitude = (float) center.getY(); - longitude = (float) center.getX(); - } - - MapHandler mapHandler = (MapHandler) getBeanContext(); - if (mapHandler == null) { - Debug.message("link", "Warning...mapHandler = null"); - } else { - MapBean mapBean = (MapBean) mapHandler - .get("com.bbn.openmap.MapBean"); - if (mapBean == null) { - Debug.message("link", "Warning...mapBean = null"); - } else { - center = new Point2D.Float(latitude, longitude); - ProjectionFactory projFactory = mapBean.getProjectionFactory(); - if (projType != null) { - Class projClass = projFactory - .getProjClassForName(projType); - if (projClass == null) { - projClass = Mercator.class; - } - projection = (Proj) projFactory.makeProjection(projClass, - center, - scale, - width, - height); - } else { - projection = (Proj) mapBean.getProjection(); - projection.setCenter(center); - projection.setScale(scale); - projection.setWidth(width); - projection.setHeight(height); - } - - if (latmin >= -90.f && latmax <= 90.f && lonmin >= -180.f - && lonmax <= 180.f && latmin <= latmax - && lonmin <= lonmax) { - Point2D upperLeft = new Point2D.Float(latmax, lonmin); - Point2D lowerRight = new Point2D.Float(latmin, lonmax); - scale = ProjMath - .getScale(upperLeft, lowerRight, projection); - projection.setScale(scale); - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - double factor1 = (latmax - latmin) - / (ul.getY() - lr.getY()); - double factor2 = (lonmax - lonmin) - / (lr.getX() - ul.getX()); - if (factor2 > factor1) - factor1 = factor2; - if (factor1 > 1.0) { - scale *= factor1; - projection.setScale(scale); - } - } - - mapBean.setProjection(projection); - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLine.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLine.java deleted file mode 100644 index ba434a8a0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkLine.java +++ /dev/null @@ -1,271 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkLine.java,v $ -// $RCSfile: LinkLine.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.util.Debug; - -/** - * Read and write a Link protocol version of a line. - */ -public class LinkLine implements LinkGraphicConstants, LinkPropertiesConstants { - - /** - * Write a line using lat/lon endpoints. The lat/lons are in decimal - * degrees. . - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param properties Properties containing attributes. - * @param dos DataOutputStream to write to. - * @throws IOException - */ - public static void write(float lat_1, float lon_1, float lat_2, - float lon_2, int lineType, - LinkProperties properties, DataOutputStream dos) - throws IOException { - LinkLine.write(lat_1, - lon_1, - lat_2, - lon_2, - lineType, - -1, - properties, - dos); - } - - /** - * Write a line using lat/lon endpoints. The lat/lons are in decimal - * degrees. This method gives you the option of specifying a number of - * segments to use in approximating a curved line. - * - * @param lat_1 latitude of placement of start of line. - * @param lon_1 longitude of placement of start of line. - * @param lat_2 latitude of placement of end of line. - * @param lon_2 longitude of placement of end of line. - * @param lineType type of line - straight, rhumb, great circle.. - * @param nsegs number of points to use to approximate curved line.. - * @param properties Properties containing attributes. - * @param dos DataOutputStream to write to. - * @throws IOException - */ - public static void write(float lat_1, float lon_1, float lat_2, - float lon_2, int lineType, int nsegs, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.LINE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_LINE); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(lineType); - dos.writeFloat(lat_1); - dos.writeFloat(lon_1); - dos.writeFloat(lat_2); - dos.writeFloat(lon_2); - dos.writeInt(nsegs); - properties.write(dos); - } - - /** - * Write a line with x/y pixel endpoints. - * - * @param x1 Horizontal pixel placement of start of line. - * @param y1 Vertical pixel placement of start of line. - * @param x2 Horizontal pixel placement of end of line. - * @param y2 Vertical pixel placement of end of line. - * @param properties Properties containing attributes. - * @param dos DataOutputStream to write to. - * @throws IOException - */ - public static void write(int x1, int y1, int x2, int y2, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.LINE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_LINE); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(x2); - dos.writeInt(y2); - properties.write(dos); - } - - /** - * Write a line located at an x/y pixel offset from a lat/lon location. - * - * @param lat_1 latitude of placement of line. - * @param lon_1 longitude of placement of line. - * @param x1 Horizontal pixel offset of start of line. - * @param y1 Vertical pixel offset of start of line. - * @param x2 Horizontal pixel offset of end of line. - * @param y2 Vertical pixel offset of end of line. - * @param properties Properties containing attributes. - * @param dos DataOutputStream to write to. - * @throws IOException - */ - public static void write(float lat_1, float lon_1, int x1, int y1, int x2, - int y2, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.LINE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_LINE); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(lat_1); - dos.writeFloat(lon_1); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(x2); - dos.writeInt(y2); - properties.write(dos); - } - - /** - * Write an OMLine to the link. - */ - public static void write(OMLine line, Link link, LinkProperties props) - throws IOException { - - switch (line.getRenderType()) { - case OMLine.RENDERTYPE_LATLON: - double[] ll = line.getLL(); - LinkLine.write((float) ll[0], - (float) ll[1], - (float) ll[2], - (float) ll[3], - line.getLineType(), - line.getNumSegs(), - props, - link.dos); - break; - case OMLine.RENDERTYPE_XY: - int[] pts = line.getPts(); - LinkLine.write(pts[0], pts[1], pts[2], pts[3], props, link.dos); - break; - case OMLine.RENDERTYPE_OFFSET: - ll = line.getLL(); - pts = line.getPts(); - LinkLine.write((float) ll[0], - (float) ll[1], - pts[0], - pts[1], - pts[2], - pts[3], - props, - link.dos); - break; - default: - Debug.error("LinkLine.write: line rendertype unknown."); - } - } - - /** - * Read the line Link protocol off a DataInputStream, and create an OMLine - * from it. Assumes that the header has already been read. - * - * @param dis DataInputStream to read from. - * @return OMLine - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMLine - */ - public static OMLine read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the line Link protocol off a DataInputStream, and create an OMLine - * from it. Assumes that the header has already been read. - * - * @param dis DataInputStream to read from. - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMLine being read. - * @return OMLine - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMLine - */ - public static OMLine read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMLine line = null; - - float lat_1 = 0.0f; - float lon_1 = 0.0f; - float lat_2 = 0.0f; - float lon_2 = 0.0f; - - int x1 = 0; - int y1 = 0; - int x2 = 0; - int y2 = 0; - int nsegs = -1; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - int lineType = dis.readByte(); - lat_1 = dis.readFloat(); - lon_1 = dis.readFloat(); - lat_2 = dis.readFloat(); - lon_2 = dis.readFloat(); - nsegs = dis.readInt(); - - line = new OMLine(lat_1, lon_1, lat_2, lon_2, lineType, nsegs); - break; - case RENDERTYPE_XY: - x1 = dis.readInt(); - y1 = dis.readInt(); - x2 = dis.readInt(); - y2 = dis.readInt(); - - line = new OMLine(x1, y1, x2, y2); - break; - case RENDERTYPE_OFFSET: - lat_1 = dis.readFloat(); - lon_1 = dis.readFloat(); - x1 = dis.readInt(); - y1 = dis.readInt(); - x2 = dis.readInt(); - y2 = dis.readInt(); - - line = new OMLine(lat_1, lon_1, x1, y1, x2, y2); - break; - default: - } - - if (line != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, - line, - propertiesBuffer); - } - return line; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkListener.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkListener.java deleted file mode 100644 index 3e46ee546..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkListener.java +++ /dev/null @@ -1,149 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkListener.java,v $ -// $RCSfile: LinkListener.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/* Java Core */ -import java.io.IOException; - -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.ISwingWorker; -import com.bbn.openmap.util.SwingWorker; - -/** - * The Link Listener is the object listening from input from the link - * server, asynchronously. It is launched within its own thread to - * handle a specific link layer. - */ -public class LinkListener extends Thread implements LinkPropertiesConstants { - /** The Link to use to talk to the client. */ - protected LinkManager linkManager; - /** The LinkLayer to use to do the work. */ - protected LinkLayer layer; - /** The generator to use with LinkGrid objects. */ - protected OMGridGenerator currentGenerator = null; - /** - * Used by outsiders to find out if the listener should be - * started. - */ - protected boolean listening = false; - - /** - * Default Constructor should not be used. - */ - private LinkListener() {} - - /** - * Create child thread that will handle the client. - * - * @param linkManager the LinkManager to communicate over. - * @param layer the LinkLayer to do the work. - * @param generator the OMGridGenerator. - */ - public LinkListener(LinkManager linkManager, LinkLayer layer, - OMGridGenerator generator) { - - this.linkManager = linkManager; - this.layer = layer; - this.currentGenerator = generator; - } - - /** - * A method used by outsiders to figure out if the LinkListener is - * listening to the server. If false, start() may need to be - * called to get the listener listening. - */ - public synchronized boolean isListening() { - return listening; - } - - protected synchronized void setListening(boolean value) { - listening = value; - } - - protected LinkListener getListener() { - return this; - } - - /** - * Use a SwingWorker to launch the listener. Calls start() on the - * LinkListener from a new thread. - */ - public void startUp() { - // Have to use a swing worker so that the calling thread - // doesn't get hung up on launching the runnable. - ISwingWorker sw = new SwingWorker() { - public Object construct() { - if (Debug.debugging("link")) { - Debug.output("LinkListener self-starting..."); - } - getListener().start(); - return null; - } - }; - sw.execute(); - } - - /** From the Runnable interface. The thread starts here... */ - public void run() { - try { - Debug.message("link", "*** LinkListener starting up ***"); - setListening(true); - listen(); - Debug.message("link", "...done listening"); - } catch (java.io.IOException ioe) { - if (Debug.debugging("link")) { - Debug.error(ioe.getMessage()); - } - Debug.message("link", "LinkListener: Server disconnected"); - } - layer.setListener(null); - } - - /** - * listen is a method that listens to the server and responds to - * requests that are made. - * - * @throws IOException - */ - public void listen() throws IOException { - - Debug.message("link", "LinkListener: Asynchronously listening..."); - - ClientLink link = linkManager.getLink(this); - - Debug.message("link", "LinkListener got link..."); - - while (link != null) { - Debug.message("link", "LinkListener: listening..."); - link.readAndParse(null, currentGenerator, layer); - Debug.message("link", "LinkListener: received content from server"); - - layer.handleLinkGraphicList(link.getGraphicList()); - layer.handleLinkActionRequest(link.getActionRequest()); - layer.handleLinkActionList(link.getActionList()); - - link = linkManager.getLink(this); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkManager.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkManager.java deleted file mode 100644 index 74a94e81e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkManager.java +++ /dev/null @@ -1,198 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkManager.java,v $ -// $RCSfile: LinkManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; -import java.net.Socket; - -import com.bbn.openmap.util.Debug; - -/** - * The LinkManager.. - */ -public class LinkManager { - - protected String host; - protected int port; - protected boolean obeyCommandToExit; - - /** - * volatile because we want internal methods to get the message - * that a link was nulled out. - */ - protected volatile ClientLink link; - - /** Constructor. */ - protected LinkManager() {} - - /** Constructor. */ - public LinkManager(String host, int port) { - this.host = host; - this.port = port; - } - - public void setObeyCommandToExit(boolean value) { - obeyCommandToExit = value; - } - - public boolean getObeyCommandToExit() { - return obeyCommandToExit; - } - - /** - * This should be the only method a multi-threaded object uses to - * gain use of the thread, i.e., on the client side where a GUI - * can start a lot of requests. If the link was not able to be - * retained for the requestor, then null will be returned. Null - * should be tested for by the callers, so that they can handle - * the rejection properly. - * - * @param waitForLock if true, the caller will block in this - * method until the link has been locked for the caller. If - * false, a null will be returned if the lock on the link - * couldn't be set for the caller's use. - * @return a link if the link is locked for the caller's use, null - * if the link is not available. - */ - public ClientLink getLink(boolean waitForLock) throws java.io.IOException { - - // NOTE: This should be the only place that the link - // object gets assigned. Otherwise, the layer can end up - // using two different links via different threads. - if (link == null) { - synchronized (this) { - if (link == null) { - link = getLink(); - link.setObeyCommandToExit(obeyCommandToExit); - } - } - } - - try { - while (!link.setLocked(true)) { - - // This handles the case where we don't want to wait - // for the link to become available. - if (!waitForLock) { - return null; - } - - // We will wait here for the link to not be in use. - // Catch a link == null in case the link was shut down - // in finLink() from another thread. IF we didn't - // catch the lock, we stay in the loop. - try { - Thread.sleep(300); - } catch (java.lang.InterruptedException ie) { - } - } - } catch (NullPointerException npe) { - // since probably means link is null, so just return null - // in case some other thread tries to do something - // tricky.. - return null; - } - - return link; - } - - /** - * Called for a LayerListener that will not write to the Link, - * only read from it. Doesn't effect the lock. - * - * @return a link if the link is locked for the caller's use, null - * if the link is not available. - */ - protected ClientLink getLink(LinkListener ll) throws java.io.IOException { - - // NOTE: This should be the only place that the link - // object gets assigned. Otherwise, the layer can end up - // using two different links via different threads. - if (link == null) { - synchronized (this) { - if (link == null) { - link = getLink(); - link.setObeyCommandToExit(obeyCommandToExit); - } - } - } - - return link; - } - - /** - * Get the ClientLink however it is appropriate for this - * LinkManager. In this case, the LinkManager will just use the - * host and port assigned. - */ - protected ClientLink getLink() throws java.io.IOException { - - ClientLink tmplink = null; - try { - if (Debug.debugging("link")) { - Debug.output("LinkManager.getLink(): establishing link to " - + host + " on port " + port); - } - Socket socket = new Socket(host, port); - tmplink = new ClientLink(socket); - } catch (java.net.UnknownHostException uhe) { - Debug.error("LinkLayer: error trying to contact host:" + host); - tmplink = null; - throw new java.io.IOException("No Contact with host:" + host - + " on port:" + port); - } - - return tmplink; - } - - /** - * When a getLink() is called, and the link is reserved for that - * caller, finLink() MUST be called to release the link for - * others. If it is not called, no one else will be able to use it. - */ - public void finLink() throws IOException { - if (link.isCloseLink()) { - Debug.message("link", "LinkManager.finLink: closing Link"); - link.close(); - link = null; - } else { - Debug.message("link", "LinkManager.finLink: releasing lock on Link"); - link.setLocked(false); - } - } - - /** - * Set the link to null. - */ - public void resetLink() { - if (link != null) { - try { - link.cleanUp(); - link.close(); - } catch (IOException ioe) { - // Nice try... - } - } - link = null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkMapRequest.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkMapRequest.java deleted file mode 100644 index 94420707b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkMapRequest.java +++ /dev/null @@ -1,236 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkMapRequest.java,v $ -// $RCSfile: LinkMapRequest.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 18:08:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * A LinkMapRequest presents a view onto a map. This view can be used - * to create a list of graphics that should be added to the map, or to - * query a spatial database engine for other graphics. - *

- * - * This object can be used to write the query to the link, and to read - * the query from the link. - */ -public class LinkMapRequest { - - /** The latitude/longitude of the center of the map. */ - protected LatLonPoint center; - /** The scale of the map. The value is interpreted as 1:scale */ - protected float scale; - /** - * A series of LinkBoundingPoly objects making up polygons of - * interest. NOTE: These polygons do not cover the poles, or cross - * the dateline. For areas like that that need to be described,, - * several LinkBoundingPolys must be used. - */ - protected LinkBoundingPoly[] boundingPolys; - /** Height of the map, in pixels. */ - protected int height; - /** Width of the map, in pixels. */ - protected int width; - /** Key value pairs of properties sent along with the map. */ - protected LinkProperties properties; - /** Version Number of request format. */ - protected static float version = Link.LINK_VERSION; - - /** The terminator of the graphics section when receiving graphics. */ - String linkStatus = Link.END_TOTAL; - - /** - * The constructor to use when reading the LinkMapRequest off the - * link. - * - * @param link the Link to read from. - * @throws IOException - */ - public LinkMapRequest(Link link) throws IOException { - linkStatus = read(link); - } - - /** - * Return the header for this object. - * - * @return the String representing the header. - */ - public String getType() { - return Link.MAP_REQUEST_HEADER; - } - - /** - * After reading the gesture response, this returns the section - * ending string terminating the gesture section, either - * Link.END_TOTAL or Link.END_SECTION. - * - * @return either Link.END_TOTAL or Link.END_SECTION. - */ - public String getLinkStatus() { - return linkStatus; - } - - /** - * Write the request to the link. - * - * @param centerLat center latitude, in decimal degrees. - * @param centerLon center longitude, in decimal degrees. - * @param scale scale of map. - * @param height height of map in pixels. - * @param width width of map in pixels. - * @param boundingPolys An array of polygons of interest. Each - * bounding polygon is a series of floats, alternating - * latitude and longitude values. - * @param props Properties object containing key-value attributes. - * @param link link to write to. - */ - public static void write(float centerLat, float centerLon, float scale, - int height, int width, - LinkBoundingPoly[] boundingPolys, - LinkProperties props, Link link) - throws IOException { - int i; - - link.start(Link.MAP_REQUEST_HEADER); - link.dos.writeFloat(version); - link.dos.writeFloat(centerLat); - link.dos.writeFloat(centerLon); - link.dos.writeFloat(scale); - link.dos.writeInt(height); - link.dos.writeInt(width); - link.dos.writeInt(boundingPolys.length); - for (i = 0; i < boundingPolys.length; i++) { - boundingPolys[i].write(link.dos); - } - - props.write(link); - - link.end(Link.END_TOTAL); - - if (Debug.debugging("link")) { - System.out.println("LinkMapRequest wrote:"); - System.out.println(" version = " + version); - System.out.println(" lat = " + centerLat); - System.out.println(" lon = " + centerLon); - System.out.println(" scale = " + scale); - System.out.println(" height = " + height); - System.out.println(" width = " + width); - System.out.println(" bounding polys:"); - for (i = 0; i < boundingPolys.length; i++) { - System.out.println(boundingPolys[i]); - } - System.out.println(" Args:"); - System.out.println(props); - } - } - - /** - * Read the link to create the request object. Assumes the header - * has already been read. - * - * @param link the link to read. - * @throws IOException - */ - public String read(Link link) throws IOException { - - Debug.message("link", "LinkMapRequest: read()"); - - float ver = link.dis.readFloat(); - - if (ver != version) { - if (ver == .1) {// Big difference.... - throw new IOException("LinkMapRequest: Versions do not match! DANGER!"); - } else { - Debug.message("link", "LinkMapRequest: Versions do not match"); - } - } - - float lat = link.dis.readFloat(); - float lon = link.dis.readFloat(); - - center = new LatLonPoint.Float(lat, lon); - - scale = link.dis.readFloat(); - height = link.dis.readInt(); - width = link.dis.readInt(); - int length = link.dis.readInt(); - - boundingPolys = new LinkBoundingPoly[length]; - for (int i = 0; i < boundingPolys.length; i++) { - boundingPolys[i] = new LinkBoundingPoly(link.dis); - } - - properties = new LinkProperties(link); - - return link.readDelimiter(false); - } - - /** Get the center of the map. */ - public LatLonPoint getCenter() { - return center; - } - - /** Get the scale of the map. */ - public float getScale() { - return scale; - } - - /** Get the height of map in pixels. */ - public int getHeight() { - return height; - } - - /** Get the width of the map in pixels. */ - public int getWidth() { - return width; - } - - /** Get an array of bounding polygons. */ - public LinkBoundingPoly[] getBoundingPolys() { - return boundingPolys; - } - - /** Get the key-value arguments for the request. */ - public LinkProperties getProperties() { - return properties; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("LinkMapRequest:\n"); - s.append("LinkMapRequest wrote:\n"); - s.append(" version = ").append(version).append("\n"); - s.append(" center = ").append(center).append("\n"); - s.append(" scale = ").append(scale).append("\n"); - s.append(" height = ").append(height).append("\n"); - s.append(" width = ").append(width).append("\n"); - s.append(" ").append(boundingPolys.length).append(" bounding polys:"); - int i; - for (i = 0; i < boundingPolys.length; i++) { - s.append("\n").append(boundingPolys[i]); - } - return s.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOMGraphicList.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOMGraphicList.java deleted file mode 100644 index febd54c12..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOMGraphicList.java +++ /dev/null @@ -1,260 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkOMGraphicList.java,v $ -// $RCSfile: LinkOMGraphicList.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/10/10 22:05:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.Graphics; -import java.util.HashMap; -import java.util.ListIterator; - -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * This class extends the OMGraphicList by allowing searches on the - * AppObject contained by the OMGraphics on the list. The AppObject is - * where the LinkGraphics store the graphic ID as defined by the - * server. It also returns indexes from searches instead of the - * graphic. This allows for deletions, replacements and graphic - * location movement from within the list. - */ -public class LinkOMGraphicList extends OMGraphicList implements - LinkPropertiesConstants { - - private HashMap hash = new HashMap(541); // Why 541? Hmm, don't - // know. - protected Projection currentProjection = null; - - /** - * Construct an OMGraphicList. - */ - public LinkOMGraphicList() { - super(10); - } - - /** - * Construct an OMGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public LinkOMGraphicList(int initialCapacity) { - super(initialCapacity); - } - - public void setProjection(Projection proj) { - currentProjection = proj; - } - - public Projection getProjection() { - return currentProjection; - } - - /** - * Check whether the list needs to be regenerated, considering the - * projection that the OMGraphics were projected with when the - * list was read. The projection equality projection is lazy, just - * checks objects. - */ - public boolean getNeedToRegenerate(Projection proj) { - return super.getNeedToRegenerate() || currentProjection != proj; - } - - /** - * Add an OMGraphic to the GraphicList. The OMGraphic must not be - * null. - * - * @param g the non-null OMGraphic to add - * @exception IllegalArgumentException if OMGraphic is null - */ - public synchronized boolean add(OMGraphic g) { - boolean ret = super.add(g); - String id = ((LinkProperties) g.getAttribute(OMGraphic.APP_OBJECT)).getProperty(LPC_GRAPHICID); - if (Debug.debugging("linkdetail")) { - Debug.output("LinkOMGraphicList: Adding graphic, id(" + id + ")"); - } - if (id != null) { - hash.put(id.intern(), g); - } - return ret; - } - - /** - * Remove the graphic at a location in the list. - * - * @param location the OMGraphic object to remove. - * @return true if graphic was on the list, false if otherwise. - */ - protected synchronized Object _remove(int location) { - Object ret = super.remove(location); - if (ret != null) { - String id = ((LinkProperties) ((OMGeometry) ret).getAttribute(OMGraphic.APP_OBJECT)).getProperty(LPC_GRAPHICID); - if (id != null) { - hash.remove(id.intern()); - if (Debug.debugging("link")) { - Debug.output("LinkOMGraphicList: Removing graphic " + id); - } - } - } - - return ret; - } - - /** - * Remove the graphic. If this list is not vague, it will also ask - * sub-OMGraphicLists to remove it if the geometry isn't found on - * this OMGraphicList. - * - * @param geometry the OMGeometry object to remove. - * @return true if geometry was on the list, false if otherwise. - */ - protected synchronized boolean _remove(OMGeometry geometry) { - boolean ret = super.remove(geometry); - if (ret != false) { - String id = ((LinkProperties) geometry.getAttribute(OMGraphic.APP_OBJECT)).getProperty(LPC_GRAPHICID); - hash.remove(id.intern()); - if (Debug.debugging("link")) { - Debug.output("LinkOMGraphicList: Removing graphic " + id); - } - } - return ret; - } - - /** - * Set the graphic at the specified location. The OMGraphic must - * not be null, the AppObject in the OMGraphic must be null or a - * LinkProperties object. This method is extended from - * OMGraphicList so the link id is added to the hashtable for - * faster searching. - * - * @param graphic OMGraphic - * @param index index of the OMGraphic to return - * @exception ArrayIndexOutOfBoundsException if index is - * out-of-bounds - */ - public synchronized void setOMGraphicAt(OMGraphic graphic, int index) { - LinkProperties linkp = null; - - try { - linkp = (LinkProperties) graphic.getAttribute(OMGraphic.APP_OBJECT); - - String id = null; - if (linkp != null) { - id = linkp.getProperty(LPC_GRAPHICID); - if (Debug.debugging("link")) { - Debug.output("LinkOMGraphicList.setOMGraphicAt(): Updating graphic " - + id + " at " + index); - } - if (id != null) { - hash.put(id.intern(), graphic); - } - } - - } catch (ClassCastException cce) { - Debug.error("LinkOMGraphicList.setOMGraphicAt(): Updated graphic doesn't have id"); - } - - super.setOMGraphicAt(graphic, index); - } - - /** - * Get the graphic with the graphic ID. - * - * @param gid graphic ID of the wanted graphic. - * @return OMGraphic or null if not found - */ - public OMGraphic getOMGraphicWithId(String gid) { - return (OMGraphic) hash.get(gid.intern()); - } - - /** - * Get the graphic with the graphic ID. Traverse mode doesn't - * matter. - * - * @param gid graphic ID of the wanted graphic. - * @return OMGraphic index or Link.UNKNOWN if not found - */ - public int getOMGraphicIndexWithId(String gid) { - OMGraphic graphic = getOMGraphicWithId(gid); - if (graphic != null) { - return super.indexOf(graphic); - } else { - return Link.UNKNOWN; - } - } - - /** - * Remove all elements from the graphic list. - */ - public synchronized void clear() { - super.clear(); - hash.clear(); - } - - /** - * Renders all the objects in the list a graphics context. This is - * the same as paint() for AWT components. The - * graphics are rendered in the order of traverseMode. Any - * graphics where isVisible() returns false are not - * rendered. - * - * @param gr the AWT Graphics context - */ - public synchronized void render(Graphics gr) { - - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = listIterator(size()); - while (iterator.hasPrevious()) { - OMGraphic graphic = iterator.previous(); - if (graphic.isVisible()) { - Object obj = graphic.getAttribute(OMGraphic.APP_OBJECT); - if (Debug.debugging("linkdetail") - && obj instanceof LinkProperties) { - String id = ((LinkProperties) obj).getProperty(LPC_GRAPHICID); - Debug.output("LinkOMGraphicList: Rendering graphic " - + id); - } - graphic.render(gr); - } - } - - } else { - ListIterator iterator = listIterator(); - - while (iterator.hasNext()) { - OMGraphic graphic = iterator.next(); - if (graphic.isVisible()) { - Object obj = graphic.getAttribute(OMGraphic.APP_OBJECT); - if (Debug.debugging("linkdetail") - && obj instanceof LinkProperties) { - String id = ((LinkProperties) obj).getProperty(LPC_GRAPHICID); - Debug.output("LinkOMGraphicList: Rendering graphic " - + id); - } - graphic.render(gr); - } - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOutputStream.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOutputStream.java deleted file mode 100644 index 8e771b488..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkOutputStream.java +++ /dev/null @@ -1,55 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkOutputStream.java,v $ -// $RCSfile: LinkOutputStream.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataOutputStream; -import java.io.OutputStream; - -/** - * Extend DataOutputStream so we can reset the written byte count. - * - * @see java.io.DataOutputStream - */ -public class LinkOutputStream extends DataOutputStream { - /** - * Creates a new link output stream to write data to the specified - * underlying output stream. - * - * @param out the underlying output stream, to be saved for later - * use. - */ - public LinkOutputStream(OutputStream out) { - super(out); - } - - /** - * Reset the written bytecount back to 0. - * - * @return the previous value of written - */ - public int clearWritten() { - int temp = written; - written = 0; - return temp; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoint.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoint.java deleted file mode 100644 index 56f51200c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoint.java +++ /dev/null @@ -1,242 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkPoint.java,v $ -// $RCSfile: LinkPoint.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Read and write the Link protocol for points. The protocol for the point has - * location information for the point, as well as a radius value indicating the - * size associated with this point. OMPoints also support whether the point - * should be rendered as a rectangle or an oval. That choice is specified as a - * property for the LinkPoint, along with any other rendering or attribute - * information that should be applied to the point. - */ -public class LinkPoint implements LinkGraphicConstants, LinkPropertiesConstants { - - /** - * The property for the LinkPoint to specify if the OMPoint should be - * rendered as an oval. The value should be true or false, depending if the - * point should be rendered as an oval. - */ - public final static String LPC_POINT_OVAL = "oval"; - - /** - * Create a lat/lon point. - * - * @param lt latitude of north edge, decimal degrees. - * @param ln longitude of west edge, decimal degrees. - * @param radius pixel radius of the point. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int radius, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POINT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POINT); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(radius); - properties.write(dos); - } - - /** - * Construct an XY point at a screen location.. - * - * @param px1 x pixel position of the first corner relative to the window - * origin - * @param py1 y pixel position of the first corner relative to the window - * origin - * @param radius pixel radius of the point. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int px1, int py1, int radius, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POINT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POINT); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(px1); - dos.writeInt(py1); - dos.writeInt(radius); - properties.write(dos); - } - - /** - * Construct an XY point relative to a lat/lon point (RENDERTYPE_OFFSET). It - * doesn't matter which corners of the point are used, as long as they are - * opposite from each other. - * - * @param lt latitude of the reference point, decimal degrees. - * @param ln longitude of the reference point, decimal degrees. - * @param px1 x pixel position of the first corner relative to the reference - * point - * @param py1 y pixel position of the first corner relative to the reference - * point - * @param radius a pixel radius of the point. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int px1, int py1, int radius, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POINT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POINT); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(px1); - dos.writeInt(py1); - dos.writeInt(radius); - properties.write(dos); - } - - /** - * Write an OMPoint to the Link. - */ - public static void write(OMPoint point, Link link, LinkProperties props) - throws IOException { - - props.setProperty(LinkPoint.LPC_POINT_OVAL, point.isOval() ? "true" - : "false"); - switch (point.getRenderType()) { - case OMPoint.RENDERTYPE_LATLON: - LinkPoint.write((float) point.getLat(), - (float) point.getLon(), - point.getRadius(), - props, - link.dos); - break; - case OMPoint.RENDERTYPE_XY: - LinkPoint.write(point.getX(), - point.getY(), - point.getRadius(), - props, - link.dos); - break; - case OMPoint.RENDERTYPE_OFFSET: - LinkPoint.write((float) point.getLat(), - (float) point.getLon(), - point.getX(), - point.getY(), - point.getRadius(), - props, - link.dos); - break; - default: - Debug.error("LinkPoint.write: point rendertype unknown."); - } - } - - /** - * Read the DataInputStream, and create an OMPoint. Assumes that the - * LinkPoint header has been read from the link. - * - * @param dis DataInputStream - * @return OMPoint - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMPoint - */ - public static OMPoint read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the DataInputStream, and create an OMPoint. Assumes that the - * LinkPoint header has been read from the link. - * - * @param dis DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoint being read. - * @return OMPoint - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMPoint - */ - public static OMPoint read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - OMPoint point = null; - int x1, y1, radius; - float lt, ln; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - lt = dis.readFloat(); - ln = dis.readFloat(); - radius = dis.readInt(); - - point = new OMPoint(lt, ln, radius); - break; - case RENDERTYPE_XY: - x1 = dis.readInt(); - y1 = dis.readInt(); - radius = dis.readInt(); - - point = new OMPoint(x1, y1, radius); - break; - case RENDERTYPE_OFFSET: - lt = dis.readFloat(); - ln = dis.readFloat(); - - x1 = dis.readInt(); - y1 = dis.readInt(); - radius = dis.readInt(); - - point = new OMPoint(lt, ln, x1, y1, radius); - break; - default: - } - - if (point != null) { - propertiesBuffer = LinkProperties.loadPropertiesIntoOMGraphic(dis, - point, - propertiesBuffer); - - if (propertiesBuffer != null) { - point.setOval(PropUtils.booleanFromProperties(propertiesBuffer, - LPC_POINT_OVAL, - OMPoint.DEFAULT_ISOVAL)); - } - } - - return point; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoly.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoly.java deleted file mode 100644 index c5596ace7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPoly.java +++ /dev/null @@ -1,392 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkPoly.java,v $ -// $RCSfile: LinkPoly.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.util.Debug; - -/** - * Read and write a Link protocol polyline/polygon. - */ -public class LinkPoly implements LinkGraphicConstants, LinkPropertiesConstants { - - /** - * Write a poly, with an array of alternating lat/lon points. Lat/lons in - * decimal degrees. - * - * @param llPoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(double[] llPoints, int units, int lType, - LinkProperties properties, DataOutputStream dos) - throws IOException { - LinkPoly.write(llPoints, units, lType, -1, properties, dos); - } - - /** - * Write a poly. - * - * @param llpoints alternating latitude and longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param nsegs number of segments to use to approximate curved poly lines.. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(double[] llpoints, int units, int lType, int nsegs, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(lType); - dos.writeInt(llpoints.length); - - for (int i = 0; i < llpoints.length; i++) { - dos.writeFloat((float) llpoints[i]); - } - - dos.writeByte(units); - dos.writeInt(nsegs); - - properties.write(dos); - } - - /** - * Write a poly. - * - * @param latpoints latitude points of poly. - * @param lonpoints longitude points of poly. - * @param units degrees or radians. - * @param lType straight, rhumb, great circle. - * @param nsegs number of segments to use to approximate curved poly lines.. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float[] latpoints, float[] lonpoints, int units, - int lType, int nsegs, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(lType); - - int length = latpoints.length; - // We only want to write out the points that have equal - // pairings. - if (lonpoints.length < latpoints.length) { - length = lonpoints.length; - } - - dos.writeInt(length); - - for (int i = 0; i < length; i++) { - dos.writeFloat(latpoints[i]); - dos.writeFloat(lonpoints[i]); - } - - dos.writeByte(units); - dos.writeInt(nsegs); - - properties.write(dos); - } - - /** - * Write a poly. - * - * @param xypoints alternating x and y pixel locations of poly. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int[] xypoints, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(xypoints.length); - - for (int i = 0; i < xypoints.length; i++) { - dos.writeInt(xypoints[i]); - } - properties.write(dos); - } - - /** - * Write a poly in the response. - * - * @param xpoints horizontal pixel locations of poly. - * @param ypoints vertical pixel locations of poly. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int[] xpoints, int[] ypoints, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_XY); - int numPoints = xpoints.length + ypoints.length; - dos.writeInt(numPoints); - - for (int i = 0; i < numPoints / 2; i++) { - dos.writeInt(xpoints[i]); - dos.writeInt(ypoints[i]); - } - - properties.write(dos); - } - - /** - * Write a poly. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xypoints alternating x and y offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int[] xypoints, - int cMode, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeInt(xypoints.length); - - for (int i = 0; i < xypoints.length; i++) { - dos.writeInt(xypoints[i]); - } - - dos.writeByte(cMode); - properties.write(dos); - } - - /** - * Write a poly. - * - * @param latPoint the latitude anchor point of the poly. - * @param lonPoint the longitude anchor point of the poly. - * @param xpoints horizontal pixel offset polygon points. - * @param ypoints vertical pixel offset polygon points. - * @param cMode Coordinate Mode (Origin or Previous) that indicate whether - * the x and y points are relative to the first point, or to the - * previous point. . - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int[] xpoints, - int[] ypoints, int cMode, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.POLY_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_POLY); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - int numPoints = xpoints.length + ypoints.length; - dos.writeInt(numPoints); - - for (int i = 0; i < numPoints / 2; i++) { - dos.writeInt(xpoints[i]); - dos.writeInt(ypoints[i]); - } - dos.writeByte(cMode); - properties.write(dos); - } - - /** - * Write a poly to the link. - */ - public static void write(OMPoly poly, Link link, LinkProperties props) - throws IOException { - - switch (poly.getRenderType()) { - case OMPoly.RENDERTYPE_LATLON: - write(poly.getLatLonArray(), - OMPoly.RADIANS, - poly.getLineType(), - poly.getNumSegs(), - props, - link.dos); - break; - case OMPoly.RENDERTYPE_XY: - write(poly.getXs(), poly.getYs(), props, link.dos); - break; - case OMPoly.RENDERTYPE_OFFSET: - write((float)poly.getLat(), - (float)poly.getLon(), - poly.getXs(), - poly.getYs(), - poly.getCoordMode(), - props, - link.dos); - break; - default: - Debug.error("LinkPoly.write: poly rendertype unknown."); - } - } - - /** - * Read the DataInputStream to create a OMPoly. Assumes the LinkPoly header - * has already been read. - * - * @param dis DataInputStream - * @return OMPoly - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMPoly - */ - public static OMPoly read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the DataInputStream to create a OMPoly. Assumes the LinkPoly header - * has already been read. - * - * @param dis DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMPoly - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMPoly - */ - public static OMPoly read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMPoly poly = null; - int numPoints; - int[] xpoints, ypoints; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - int lineType = dis.readByte(); - numPoints = dis.readInt(); - - double[] llpoints = new double[numPoints]; - for (int i = 0; i < numPoints; i++) { - llpoints[i] = dis.readFloat(); - } - int units = dis.readByte(); - int nsegs = dis.readInt(); - - if (Debug.debugging("linkdetail")) { - System.out.println(" Lat/Lon LinkPoly:"); - System.out.println(" linetype = " + lineType); - System.out.println(" number of points = " + numPoints / 2); - // for (int i = 0; i < numPoints; i+=2) { - // System.out.println(" Lat = " + llpoints[i] + - // ", Lon = " + llpoints[i+1]); - // } - System.out.println(" units = " + units); - System.out.println(" nsegs = " + nsegs); - } - - poly = new OMPoly(llpoints, units, lineType, nsegs); - break; - case RENDERTYPE_XY: - numPoints = dis.readInt(); - xpoints = new int[numPoints / 2]; - ypoints = new int[numPoints / 2]; - - for (int i = 0; i < numPoints / 2; i += 1) { - xpoints[i] = dis.readInt(); - ypoints[i] = dis.readInt(); - } - - if (Debug.debugging("linkdetail")) { - System.out.println(" X/Y LinkPoly:"); - System.out.println(" number of points = " + numPoints / 2); - // for (i = 0; i < numPoints; i++) { - // System.out.println(" X = " + xpoints[i] + - // ", Y = " + ypoints[i]); - // } - } - - poly = new OMPoly(xpoints, ypoints); - break; - case RENDERTYPE_OFFSET: - float lat_1 = dis.readFloat(); - float lon_1 = dis.readFloat(); - numPoints = dis.readInt(); - - xpoints = new int[numPoints / 2]; - ypoints = new int[numPoints / 2]; - - for (int i = 0; i < numPoints / 2; i += 1) { - xpoints[i] = dis.readInt(); - ypoints[i] = dis.readInt(); - } - int cMode = dis.readByte(); - - if (Debug.debugging("linkdetail")) { - System.out.println(" Offset LinkPoly:"); - System.out.println(" lat = " + lat_1); - System.out.println(" lon = " + lon_1); - System.out.println(" number of points = " + numPoints / 2); - // for (i = 0; i < numPoints; i+=2) { - // System.out.println(" Lat = " + llpoints[i] + - // ", Lon = " + llpoints[i+1]); - // } - System.out.println(" cMode = " + cMode); - } - - poly = new OMPoly(lat_1, lon_1, xpoints, ypoints, cMode); - break; - default: - } - - if (poly != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, poly, propertiesBuffer); - } - - return poly; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProperties.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProperties.java deleted file mode 100644 index 2d9c22898..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProperties.java +++ /dev/null @@ -1,448 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkProperties.java,v $ -// $RCSfile: LinkProperties.java,v $ -// $Revision: 1.9 $ -// $Date: 2008/02/26 17:39:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.Stroke; -import java.awt.TexturePaint; -import java.awt.geom.Line2D; -import java.awt.image.BufferedImage; -import java.io.DataInput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A LinkProperties object is a set of key-value strings that are going to be - * sent over the link. In java-land, they are handled with the Properties - * object. In link-land, they are handled like an array of strings. Requests - * have a properties section, and graphic objects have them as well. - */ -public class LinkProperties extends Properties implements LinkPropertiesConstants, - LinkGraphicConstants { - - /** - * Used by the graphics if no properties were sent with it. No properties - * can be set on this LinkProperties object. - */ - public static final LinkProperties EMPTY_PROPERTIES = new LinkProperties() { - public Object put(Object obj1, Object obj2) { - return null; - } - - public void putAll(Map map) { - } - }; - - protected Boolean reuseProperties; - - public LinkProperties() { - super(); - } - - public LinkProperties(LinkProperties settings) { - super(settings); - } - - /** - * Create a LinkProperties object with it's first pair. - * - * @param keyString the key for the pair. - * @param valueString the value for the pair. - */ - public LinkProperties(String keyString, String valueString) { - super(); - setProperty(keyString, valueString); - } - - /** - * Create a LinkProperties, and read it's contents off a link. Assumes the - * properties are the next thing to be read, starting with the string count. - * - * @param link the Link to read properties from - * @throws IOException - */ - public LinkProperties(Link link) throws IOException { - super(); - read(link.dis); - } - - /** - * Create a LinkProperties, and read it's contents off a link. - * - * @param dis DataInput to read from. - * @throws IOException - */ - public LinkProperties(DataInput dis) throws IOException { - read(dis); - } - - public Boolean getReuseProperties() { - return reuseProperties; - } - - /** - * A flag that controls how LinkProperties are managed. Setting this object - * to Boolean.TRUE will indicate that the LinkProperties object decoded - * previously should be reused, with any properties currently set in this - * object overwriting the same property previously received. Setting it to - * Boolean.FALSE, or setting it to null, will indicate than any buffered - * LinkProperty object should be cleared before these properties are read. - * - * @param reuseProperties - */ - public void setReuseProperties(Boolean reuseProperties) { - this.reuseProperties = reuseProperties; - } - - /** - * Calls the hashtable method put. Provided to provide a - * similar interface in jdk1.1.x or jdk1.2.x, enforcing that only strings - * can be in properties files. - */ - public synchronized Object setProperty(String key, String value) { - return put(key, value); - } - - /** - * Write the properties as several strings. There is a string count (Key - * count + value count), and then for each key and value string, a character - * count, and the characters. - * - * @param link the link to write to. - */ - public void write(Link link) throws IOException { - write(link.dos); - } - - /** - * Write the properties as several strings. There is a string count (Key - * count + value count), and then for each key and value string, a character - * count, and the characters. - * - * @param dos the DataOutputStream to write to. - */ - public void write(DataOutputStream dos) throws IOException { - - dos.writeInt((size() + 1) * 2); - - dos.writeInt(LPC_PROPERY_MANAGEMENT_POLICY.length()); - dos.writeChars(LPC_PROPERY_MANAGEMENT_POLICY); - if (reuseProperties == Boolean.TRUE) { - dos.writeInt(LPC_REUSE_PROPERTIES.length()); - dos.writeChars(LPC_REUSE_PROPERTIES); - } else { - dos.writeInt(LPC_CLEAR_PROPERTIES.length()); - dos.writeChars(LPC_CLEAR_PROPERTIES); - } - - for (Enumeration e = propertyNames(); e.hasMoreElements();) { - String key = (String) e.nextElement(); - String value = getProperty(key); - dos.writeInt(key.length()); - dos.writeChars(key); - dos.writeInt(value.length()); - dos.writeChars(value); - } - } - - /** - * Read the link to create the properties object. Assumes the properties are - * the next thing to be read, starting with the string count. - * - * @param dis DataInput to read from. - * @throws IOException - */ - public void read(DataInput dis) throws IOException { - int numArgs = dis.readInt(); - if (numArgs > 0) { - readArgs(numArgs, dis); - } - } - - /** - * Read the link to fetch properties for this LinkProperties object. Assumes - * the property count has been read and is being provided to this method - * - * @param numArgs the number of key + value strings to read. - * @param dis DataInput to read from. - * @throws IOException - */ - public void readArgs(int numArgs, DataInput dis) throws IOException { - - String[] argStrings = new String[numArgs]; - - for (int i = 0; i < numArgs; i += 2) { - int argLength = dis.readInt(); - - if (i == 0 && argLength == 1 && dis.readChar() == LPC_PROPERY_MANAGEMENT_POLICY_CHAR) { - argLength = dis.readInt(); - if (argLength == 1 && dis.readChar() == LPC_CLEAR_PROPERTIES_CHAR) { - clear(); - } - continue; - } - - argStrings[i] = LinkUtil.readString(dis, argLength); - argLength = dis.readInt(); - argStrings[i + 1] = LinkUtil.readString(dis, argLength); - - put(argStrings[i], argStrings[i + 1]); - } - - if (Debug.debugging("linkdetail")) { - System.out.println("LinkProperties | Read: " + this); - } - } - - /** - * New, static method for more efficient property handling. - * - * @param dis - * @param props - * @return if there are no properties, the EMPTY_PROPERTIES object is - * returned. If there are properties and props == null, then a new - * LinkProperties object is allocated and returned, otherwise, props - * is returned. - * @throws IOException - */ - public static LinkProperties read(DataInput dis, LinkProperties props) throws IOException { - - int numArgs = dis.readInt(); - - if (numArgs == 0) { - return EMPTY_PROPERTIES; - } - - if (props == null) { - props = new LinkProperties(); - } - - props.readArgs(numArgs, dis); - - return props; - } - - /** - * New, static method for more efficient property handling and loading the - * properties into the OMGraphic. - * - * @param dis - * @param omg - * @return if there are no properties, the EMPTY_PROPERTIES object is - * returned. If there are properties and props == null, then a new - * LinkProperties object is allocated and returned, otherwise, props - * is returned. The OMGraphic appObject is set with the read - * properties. - */ - public static LinkProperties loadPropertiesIntoOMGraphic(DataInput dis, OMGraphic omg, - LinkProperties propertiesBuffer) - throws IOException { - LinkProperties readProperties = (LinkProperties) read(dis, propertiesBuffer).clone(); - readProperties.setProperties(omg); // load them into OMGraphic.. - return readProperties; - } - - /** - * Method to call on the LinkProperties object to set the DrawingAttributes - * properties on an OMGraphic. Will set the line and select colors, fill - * paints (including patterns) and stroke based on the properties contained - * in this LinkProperties object. Will set default values in the OMGraphic - * if the applicable properties aren't defined, and will set the - * LinkProperties in the AppObject of the OMGraphic. - */ - public void setProperties(OMGraphic omg) { - if (omg == null) - return; - - omg.setLinePaint(getPaint(LPC_LINECOLOR, BLACK_COLOR_STRING)); - omg.setFillPaint(getFillPaint()); - omg.setSelectPaint(getPaint(LPC_HIGHLIGHTCOLOR, BLACK_COLOR_STRING)); - omg.setStroke(getStroke()); - - if (this != EMPTY_PROPERTIES) { - omg.putAttribute(OMGraphic.APP_OBJECT, this); - } - } - - protected Hashtable renderAttributesCache = new Hashtable(); - - public Stroke getStroke() { - int lineWidth = PropUtils.intFromProperties(this, LPC_LINEWIDTH, 1); - String strokeString = getProperty(LPC_LINESTYLE); - - int cap = BasicStroke.CAP_SQUARE; - int join = BasicStroke.JOIN_MITER; - float miterLimit = 10f; - float dashPhase = 0f; - Stroke stroke = null; - float[] dash = null; - - String strokeCode = "stroke" + lineWidth + strokeString; - - stroke = (Stroke) renderAttributesCache.get(strokeCode); - - if (stroke != null) { - return stroke; - } - - if (strokeString != null) { - if (strokeString.equalsIgnoreCase(LPC_LONG_DASH)) { - dash = new float[] { 10f, 10f }; - } else if (strokeString.equalsIgnoreCase(LPC_DASH)) { - dash = new float[] { 6f, 6f }; - } else if (strokeString.equalsIgnoreCase(LPC_DOT)) { - dash = new float[] { 3f, 6f }; - } else if (strokeString.equalsIgnoreCase(LPC_DASH_DOT)) { - dash = new float[] { 6f, 6f, 3f, 6f }; - } else if (strokeString.equalsIgnoreCase(LPC_DASH_DOT_DOT)) { - dash = new float[] { 6f, 6f, 3f, 6f, 3f, 6f }; - } - - if (dash != null) { - stroke = new BasicStroke(lineWidth, cap, join, miterLimit, dash, dashPhase); - } - } - - if (stroke == null) { - stroke = new BasicStroke(lineWidth); - } - - renderAttributesCache.put(strokeCode, stroke); - - return stroke; - } - - public Paint getPaint(String paintProperty, String defaultPaintString) { - Paint paint = null; - - String paintKey = "paint" + getProperty(paintProperty); - - if (paintProperty != null) { - paint = (Paint) renderAttributesCache.get(paintKey); - - if (paint == null) { - paint = (Paint) renderAttributesCache.get("paint" + defaultPaintString); - } - - if (paint != null) { - return paint; - } - } - - if (paintProperty != null && defaultPaintString != null) { - paint = ColorFactory.parseColorFromProperties(this, paintProperty, defaultPaintString, true); - } else { - paint = Color.black; - } - - renderAttributesCache.put(paintKey, paint); - - return paint; - } - - public Paint getFillPaint() { - - Paint fillPaint = getPaint(LPC_FILLCOLOR, CLEAR_COLOR_STRING); - String fillPatternString = getProperty(LPC_FILLPATTERN); - - if (fillPatternString == null || fillPatternString.equalsIgnoreCase(LPC_SOLID_PATTERN)) { - return fillPaint; - } else { - String fillPaintString = getProperty(LPC_FILLCOLOR); - String texturePaintKey = "fill" + fillPaintString + fillPatternString; - - if (fillPaintString == null) { - fillPaint = Color.black; - - TexturePaint ret = (TexturePaint) renderAttributesCache.get("fill" + fillPaint - + fillPatternString); - - if (ret != null) { - return ret; - } else { - ret = (TexturePaint) renderAttributesCache.get(texturePaintKey); - - if (ret != null) { - return ret; - } - } - } - - BufferedImage bi = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB); - Graphics2D big = bi.createGraphics(); - big.setColor(new Color(0, true)); // clear - big.fillRect(0, 0, 8, 8); - big.setPaint(fillPaint); - - if (fillPatternString.equalsIgnoreCase(LPC_HORIZONTAL_PATTERN)) { - big.draw(new Line2D.Double(0, 0, 7, 0)); - big.draw(new Line2D.Double(0, 4, 7, 4)); - } else if (fillPatternString.equalsIgnoreCase(LPC_VERTICAL_PATTERN)) { - big.draw(new Line2D.Double(0, 0, 0, 7)); - big.draw(new Line2D.Double(4, 0, 4, 7)); - } else if (fillPatternString.equalsIgnoreCase(LPC_CROSS_PATTERN)) { - big.draw(new Line2D.Double(0, 0, 7, 0)); - big.draw(new Line2D.Double(0, 4, 7, 4)); - big.draw(new Line2D.Double(0, 0, 0, 7)); - big.draw(new Line2D.Double(4, 0, 4, 7)); - } else if (fillPatternString.equalsIgnoreCase(LPC_DIAG_CROSS_PATTERN)) { - big.draw(new Line2D.Double(0, 0, 7, 7)); - big.draw(new Line2D.Double(0, 4, 3, 7)); - big.draw(new Line2D.Double(4, 0, 7, 3)); - big.draw(new Line2D.Double(0, 7, 7, 0)); - big.draw(new Line2D.Double(0, 3, 3, 0)); - big.draw(new Line2D.Double(4, 7, 7, 4)); - } else if (fillPatternString.equalsIgnoreCase(LPC_BACKWARD_DIAG_PATTERN)) { - big.draw(new Line2D.Double(0, 0, 7, 7)); - big.draw(new Line2D.Double(0, 4, 3, 7)); - big.draw(new Line2D.Double(4, 0, 7, 3)); - } else if (fillPatternString.equalsIgnoreCase(LPC_FORWARD_DIAG_PATTERN)) { - big.draw(new Line2D.Double(0, 7, 7, 0)); - big.draw(new Line2D.Double(0, 3, 3, 0)); - big.draw(new Line2D.Double(4, 7, 7, 4)); - } else { - // default to solid - big.fillRect(0, 0, 8, 8); - } - - Rectangle r = new Rectangle(0, 0, 8, 8); - TexturePaint texturePaint = new TexturePaint(bi, r); - - renderAttributesCache.put(texturePaintKey, texturePaint); - return texturePaint; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPropertiesConstants.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPropertiesConstants.java deleted file mode 100644 index 77473cbc3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkPropertiesConstants.java +++ /dev/null @@ -1,145 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkPropertiesConstants.java,v $ -// $RCSfile: LinkPropertiesConstants.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/02/26 17:12:46 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -/** - * A LinkPropertiesConstants interface defines the well known expected - * properties that may be coming over the link inside the properties. Other - * properties may be carried as well, but these are properties you can kind of - * expect to see. - */ -public interface LinkPropertiesConstants { - - // Constants that contain graphic attributes - /** - * The property, transmitted first, that dictates how LinkProperty memory is - * managed when a LinkProperties object is read. The value for this key - * dictates the policy. - */ - public final static String LPC_PROPERY_MANAGEMENT_POLICY = "p"; - public final static char LPC_PROPERY_MANAGEMENT_POLICY_CHAR = 'p'; - /** The line color attribute name. */ - public final static String LPC_LINECOLOR = "lc"; - /** The line style (dash attribute) attribute name. */ - public final static String LPC_LINESTYLE = "ls"; - /** The highlight color attribute name. */ - public final static String LPC_HIGHLIGHTCOLOR = "hc"; - /** The fill color attribute name. */ - public final static String LPC_FILLCOLOR = "fc"; - /** The fill pattern attribute name. */ - public final static String LPC_FILLPATTERN = "fp"; - /** The line width attribute name. */ - public final static String LPC_LINEWIDTH = "lw"; - /** The text graphic contents attribute name. */ - public final static String LPC_LINKTEXTSTRING = "ts"; - /** The font representation attribute name. */ - public final static String LPC_LINKTEXTFONT = "tf"; - - /** The line color attribute name. */ - public final static String LPC_OLD_LINECOLOR = "lineColor"; - /** The line style (dash attribute) attribute name. */ - public final static String LPC_OLD_LINESTYLE = "lineStyle"; - /** The highlight color attribute name. */ - public final static String LPC_OLD_HIGHLIGHTCOLOR = "highlightColor"; - /** The fill color attribute name. */ - public final static String LPC_OLD_FILLCOLOR = "fillColor"; - /** The fill pattern attribute name. */ - public final static String LPC_OLD_FILLPATTERN = "fillPattern"; - /** The line width attribute name. */ - public final static String LPC_OLD_LINEWIDTH = "lineWidth"; - /** The text graphic contents attribute name. */ - public final static String LPC_OLD_LINKTEXTSTRING = "textString"; - /** The font representation attribute name. */ - public final static String LPC_OLD_LINKTEXTFONT = "textFont"; - - /** - * The location of the text baseline relative to the specified text - * location. The property should be BASELINE_BOTTOM, BASELINE_MIDDLE, - * BASELINE_TOP. BASELINE_BOTTOM is the default. - */ - public final static String LPC_LINKTEXTBASELINE = "tbl"; - /** The rotation in degrees clockwise from North. */ - public final static String LPC_LINKROTATION = "rot"; - /** The url of an image to use in a LinkRaster, for some cases. */ - public final static String LPC_LINKRASTERIMAGEURL = "riu"; - /** The graphic identifier attribute name. */ - public final static String LPC_GRAPHICID = "gid"; - - // These constants are to affect the map as a whole - /** The latitude of the center of the map in decimal degrees. */ - public final static String LPC_CENTER_LAT = "lat"; - /** The longitude of the center of the map in decimal degrees. */ - public final static String LPC_CENTER_LONG = "lon"; - /** The scale or zoom level of the map */ - public final static String LPC_SCALE = "s"; - /** The width of the map (pixels) */ - public final static String LPC_WIDTH = "w"; - /** The height of the map (pixels) */ - public final static String LPC_HEIGHT = "h"; - /** The projection to use for the map */ - public final static String LPC_PROJECTION = "p"; - /** The lower left latitude */ - public final static String LPC_LATMIN = "latmin"; - /** The lower left longitude */ - public final static String LPC_LONMIN = "lonmin"; - /** The upper right latitude */ - public final static String LPC_LATMAX = "latmax"; - /** The upper right longitude */ - public final static String LPC_LONMAX = "lonmax"; - - // Constants that can fire a information delegator action. - - /** The URL text attribute name. */ - public final static String LPC_URL = "url"; - /** The HTML text (displayed in a browser) attribute name. */ - public final static String LPC_HTML = "html"; - /** The Information Line (status line) attribute name. */ - public final static String LPC_INFO = "info"; - /** The Message text (in a pop-up window) attribute name. */ - public final static String LPC_MESSAGE = "mess"; - /** The time in milliseconds since 1/1/1970 00:00:00. */ - public final static String LPC_TIME = "time"; - - /** Line styles */ - public final static String LPC_SOLID = "S"; - public final static String LPC_LONG_DASH = "LD"; - public final static String LPC_DASH = "DA"; - public final static String LPC_DOT = "D"; - public final static String LPC_DASH_DOT = "DAD"; - public final static String LPC_DASH_DOT_DOT = "DADD"; - - /** Fill patterns */ - public final static String LPC_SOLID_PATTERN = "S"; - public final static String LPC_VERTICAL_PATTERN = "V"; - public final static String LPC_HORIZONTAL_PATTERN = "H"; - public final static String LPC_CROSS_PATTERN = "C"; - public final static String LPC_DIAG_CROSS_PATTERN = "DC"; - public final static String LPC_FORWARD_DIAG_PATTERN = "FD"; - public final static String LPC_BACKWARD_DIAG_PATTERN = "BD"; - - public final static String LPC_CLEAR_PROPERTIES = "C"; - public final static char LPC_CLEAR_PROPERTIES_CHAR = 'C'; - public final static String LPC_REUSE_PROPERTIES = "R"; - public final static char LPC_REUSE_PROPERTIES_CHAR = 'R'; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProtocol.html b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProtocol.html deleted file mode 100644 index 0a7178950..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkProtocol.html +++ /dev/null @@ -1,5157 +0,0 @@ - - - - Link Protocol for Client-Server Communication - - - -

Link Protocol for Client-Server Communication, v0.5

-

Basic Description

- - This document will describe the Link Protocol for Link - client-server communication. Link client-server relationships - involve the exchange and modification of geographic and graphic - objects, called graphics, and information about those graphics. -

- The protocol is a set of requests and descriptions. A request or - description makes up a section of the communication between a - client and server. Each communication between the client and - server can consist of any combination of these sections. Each - section has a unique header, and one of two tail selections. - The tail is important because it indicates whether another - section follows the current one in the communication. -

- General Definitions -

    -
  • Byte order follows the Network Byte Order, or big endian. - -
  • Decimal degree longitude values are valid between -180.0 - and 180.0. Negative values represent locations in the Western - hemisphere, and positive values represent locations in the - Eastern hemisphere. Passing a value that is outside these - limits is allowed, but may result in unexpected behavior. - -
  • Decimal degree latitude values are valid between -90.0 and - +90.0. Negative values represent locations in the Southern - hemisphere, and positive values represent locations in the - Northern hemisphere. Passing a value that is outside these - limits is allowed, but may result in unexpected behavior. - -
  • Maximum/Minimum scale and maximum pixel size of the map are - determined by the client, and unknown to the server. -
- -

Versions

-
    -
  • v0.1 was the development version. -
  • v0.2 was the released version. -
  • v0.3 added the LinkPoint. The language in the Link - Protocol document has also been modified to emphasize that the - protocol doesn't dictate which sections should be sent by the - client, and which should be sent by the server. Any section can - be sent at any time. The receiver can then decide if it can - act on it, and disregard a section it is not prepared to - handle. With any transmission, some response is expected. -
  • v0.4 added the LinkArc and the MapUpdate Action. The - MapUpdate Action is used for a server to control a client's - display. There were also additional defined properties added to - enhance the rendering options passed through the properties, - include different line style and fill pattern definitions. -
  • v0.5 added the LinkEllipse. -
  • v0.6 changed the constants used for identifying different - sections of the protocol, in order to reduce the amount of bytes - sent over the wire. In some cases, ints were reduced to bytes - for attributes that have a possible set of values. The - LinkProperties object was adjusted to have an optional first set - of control properties that specify how the current set of - LinkProperties relates to the previous set. This allows for - more efficient caching of values. -
- -

- - - Number Notations and Definitions - - -
- - - - - - - - - - - - - - - - - - - - -
-

Number Type -

-

Definition -

ASCII char

- 8 bit ASCII character

Unicode char

- 16 bit Unicode character.

int

- 32 bit signed.

float

- 32 bit signed. Follows the IEEE 754 standard - for floating point numbers.
- -

Definitions

- - These are the byte definitions for the objects being passed over - the client-server connection. - -
- - - - - - - - - - -
-
- -

Headers

- - Headers are important because they serve several important - functions. They describe the section the precede, enabling the - proper parsing to begin on the object. They also serve as - reference markers on the communication socket in case the link - communication loses synchronization. The < and > symbols - combine to mark the location of a header. The client and server - are expected to look for these markers byte-by-byte, identify the - beginning of a section, and then parse the section accordingly. - -

- - - Header Definitions - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Query Sections -

-

Header -

Map Request

<MR>

Action Request

<AR>

GUI Request (Undefined)

<GUIR>
-

Description Sections -

-

Header -

Graphics Description

<G>

Gesture Description

<A>

GUI Description (Undefined)

<GUI>

No Action

<?>

Close Link

<C>
-

- Graphic Objects -

-

Header -

Arc

<A>

Bitmap

<B>

Circle

<C>

Ellipse

<E>

Grid

<GD>

Line

<L>

Point

<PO>

Poly

<PY>

Raster

<RA>

Rectangle

<RE>

Text

<T>
-

- Action Objects -

-

Header -

Update Graphics

<UG>

Update GUI (Undefined)

<UGUI>

Update Map (Server directed)

<UM>
- -

- - - Section Tail Definitions - - -
- - - - - - - - - - - -
-

Sections -

-

Tail -

End Section, more sections - following.(END_SECTION)

- Line Feed ASCII Character - '\n'

End Query/Description, nothing - following.(END_TOTAL)

- Carrige Return ASCII Character - '\r'
-

-


-

Query Definitions

- -

Map Request

- - Graphics queries are used by the client to ask the server for - graphics to draw on a map. The query provides several different - parameters that let the server get an idea of what the bounds of - the map are. -

- - - - - Map Request - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

byte

<MR>

4

float

- Version number of the map request format.

4

float

- The center latitude of the map, in decimal degrees.

4

float

- The center longitude of the map, in decimal degrees.

4

float

- The scale of the map, as in 1:<scale>.

4

int

- The height of the map, in pixels.

4

int

- The width of the map, in pixels.

4

int

- The number of bounding - polygons defining the areas of interest on the - map.

Var

- bounding polygon

- Bounding Polygons. A series of bounding polygons.

4

int

- The even number (N_FLTS) of 4 byte floats that follow - in BoundsArray. The floats represent the coordinates - of a bounding polygon, in pairs, each pair containing - first a latitude and then a longitude. The - coordinates of the polygon are defined to be listed in - the clockwise direction.

4n

float

- BoundsArray. A series of 4 byte floats, in pairs. - Each pair represents a latitude and then a longitude - in decimal degrees. There will be an even number - greater than four of these floats sent, since they - define a bounding polygon. If the number of points in - the polygon is N_PTS, there will be 2*N_PTS = N_FLTS - floats in BoundsArray.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.

1

byte

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
-

- - - - For the Map Request, the - bounding polygon holds polygons defined by latitude and - longitude values. These polygons are assumed to not cross over - the dateline (+-180 degrees longitude), and do not contain the - North or South pole. Areas that break these assumptions must be - defined by multiple bounding polygons.

- - - - - Bounding Polygon - - -
- - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

int

- The even number (N_FLTS) of 4 byte floats that follow - in BoundsArray. The floats represent the coordinates - of a bounding polygon, in pairs, each pair containing - first a latitude and then a longitude. The - coordinates of the polygon are defined to be listed in - the clockwise direction.

4n

float

- BoundsArray. A series of 4 byte floats, in pairs. - Each pair represents a latitude and then a longitude - in decimal degrees. There will be an even number - greater than four of these floats sent, since they - define a bounding polygon. If the number of points in - the polygon is N_PTS, there will be 2*N_PTS = N_FLTS - floats in BoundsArray.
-

-


- -

Action Request

- - Gesture queries are used by the client to tell the server that a - user event has happened, like a mouse movement or keyboard event. - When used by the client, it is understood that the client will - wait for some description from the server. The server can send a - Gesture Query as well, but that would usually happen to tell the - client what kind of events the server is interested in receiving. -

- - - - - Action Request for Mouse Events - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<AR>

4

float

- Version number of the action request format.

4

int

- descriptor contains bit - settings that mark this as a mouse event-generated - GestureLinkquery instead of a keyboard-generated - LinkActionRequest or client - notification.

4

int

- X - Horizontal map pixel location of event, from the top left - corner.

4

int

- Y - Vertical map pixel location of event from the top left - corner.

4

int

- Click count - number of times mouse button pressed and released - at current location.

4

int

- Modifiers for event, describing - keyboard keys and mouse keys pressed.

4

float

- Latitude, in decimal degrees, of event.

4

float

- Longitude, in decimal degrees, of event.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
-

- - - - Action Request for Key Events - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<AR>

4

float

- Version number of the action request format.

4

int

- descriptor contains bit - settings that mark this as a keyboard-generated - LinkActionRequest instead of a mouse event-generated - GestureLinkquery or client - notification.

2

Unicode char

- Keyboard character for event..

4

int

- Modifiers for event, describing - other keyboard keys pressed.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
- -

- - - - - Action Request for Client Notification of Server Interest - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<AR>

4

float

- Version number of the action request format.

4

int

- descriptor contains bit - settings that mark this as a client notification - instead of a mouse - event-generated GestureLinkquery or keyboard-generated - LinkActionRequest.

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
-

- - The gesture descriptor is a masked integer that - describes what kind of user event occured. -

- - - Gesture Descriptor Masking - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Bit Number -

-

Meaning -

0

- The mouse button was clicked (pressed and released).

1

- Mouse button pressed.

2

- Mouse button released.

3

- Mouse was moved with no mouse buttons pressed.

4

- Cursor entered the map area.

5

- Cursor exited the map area.

6

- Mouse moved with a mouse button down (dragged).

7

- A keyboard key was pressed.

8

- A keyboard key was released.

9

- A graphic is involved in the gesture. For example, a - mouse click occured on a graphic.

10

- Client notification flag. This is set if the server is - sending the query to let the client know what kind of - gestures the server is interested in receiving.

11

- Flag to set if the server should always be notified of - a gesture, even if a graphic has responded to it on - the client side. Since the graphics may contain - properties that allow client actions to take place - when a gesture occurs on a graphic, this flag - indicates that a Action Request should also be sent to - the server. Otherwise, the client determines what - actions occur locally..
-

- - - The modifier is a masked integer that describes if - additional keyboard buttons where pressed down when the gesture - occured. -

- - - Modifer Masking - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Bit Number -

-

Meaning -

0

- The Shift key on the keyboard was down.

1

- The Control key on the keyboard was down.

2

- The Meta key on the keyboard was down, or the mouse - button #3 state changed.

3

- The Alt key on the keyboard was down, or the mouse - button #2 state changed.

4

- The mouse button #1 state changed.

5

- The Alt-Graph key state changed.
-

- -


-
-

Description Definitions

- - Descriptions are sections that provide objects or actions across - the link. They can be answers to queries, but they can also be - sent to initiate communication. For example, a client can provide - a list of graphics to be added to a repository on the server.. In - general, if a client sends a query, it should expect some sort of - description. If a descrition is sent, some sort of response - should be expected. A 'No Action' response can be used as - acknowledgement. - - -

Graphics Description

- - A Graphics Description is the object that defines a list of graphics - being sent over the link. The Graphics Description has a header to - define the beginning of the list, and a tail to signify the end of - it. The graphics in between have their own headers and definitions. - -

- - - Graphics Description - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<G>

4

float

- Version number of the graphic list format.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.

Var

Graphics

- A sequence of graphics, each with - their own header and format.

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
- -

-


- -

Actions

- - Actions are descriptions to Action Requests. There are a number of - possible descriptions and any number of them can be included in this - transmission. It should be assumed that the client will act on - the descriptions in order. - -

- - - Action List - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<A>

4

float

- Version number of the action list format.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.

Var

Actions

- A sequence of actions, each with - their own header and format.

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
- -

-


-

No Action Response

- - A No Action section is set when a client or server either doesn't - know how to handle a query or definition set to it, or doesn't - have anything else to say. - -

- - - No Action - - -
- - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<?>

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
- -

-


-

Close Link Response

- - A Close Link response is sent when a client or server wants to sign off a - link connection. -

- - - Close Link - - -
- - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<Q>

1

ASCII char

- Tail marker describing the end of this section, or the end - of the entire communication (END_SECTION or END_TOTAL)
- -

-


-
- -

Graphic Definitions

- - The graphic formats are defined below for Graphic and Gesture - Descriptions. The green fields - represent the fields in the protocol that change for each graphic - depending on the render type of the graphic. The red fields represent the fields in the - raster protocol that change depending on the image format of the - raster. - -

-


- - - - - Link Arc at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<A>

1

byte

- This space is for a graphic type identifier. For - Arcs, the value is 10.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the arc's center, in decimal degrees.

4

float

- Longitude of the arc's center, in decimal degrees.

4

float

- Radius of the arc, in units defined in the next field.

1

byte

- Units of the radius measurement. Values can be:
- Decimal Degrees = -1
- Kilometers = 0
- Miles = 1
- Nautical Miles = 2

4

int

- Number of verticies to use to approximate the arc. - If this value is -1, the projection algorithm of the - client should decide the best value.

4

float

- Starting angle of the arc, in decimal degrees. 0 is North, - clockwise is positive.

4

float

- Ending angle of the arc, in decimal degrees.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Arc at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<A>

1

byte

- This space is for a graphic type identifier. For - Arcs, the value is 10.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - arc's center, in pixels.

4

int

- Vertical distance, from the top of the map, of the - arc's center, in pixels.

4

int

- Width of the arc, in pixels.

4

int

- Height of the arc, in pixels.

4

float

- Starting angle of the arc, in decimal degrees. 0 is North, - clockwise is positive.

4

float

- Ending angle of the arc, in decimal degrees.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Arc at X/Y Offset from Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<A>

1

byte

- This space is for a graphic type identifier. For - Arcs, the value is 10.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the arc's anchor point, in decimal degrees.

4

float

- Longitude of the arc's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the arc's center, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the arc's center, in pixels.

4

int

- Width of the arc, in pixels.

4

int

- Height of the arc, in pixels.

4

float

- Starting angle of the arc, in decimal degrees. 0 is North, - clockwise is positive.

4

float

- Ending angle of the arc, in decimal degrees.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

-


- - - - Link Bitmap at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<B>

1

byte

- This space is for a graphic type identifier. For - Bitmaps, the value is 1.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the bitmap's upper left corner, in decimal degrees.

4

float

- Longitude of the bitmap's upper left corner, in decimal degrees.

4

int

- Width of the bitmap, in pixels.

4

int

- Height of the bitmap, in pixels.

4

int

- Number of bitmap bytes.

1n

byte

- Bytes representing the bitmap.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Bitmap at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<B>

1

byte

- This space is for a graphic type identifier. For - Bitmaps, the value is 1.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - bitmap's upper left corner, in pixels.

4

int

- Vertical distance, from the top of the map, of the - bitmap's upper left corner, in pixels.

4

int

- Width of the bitmap, in pixels.

4

int

- Height of the bitmap, in pixels.

4

int

- Number of bitmap bytes.

1n

byte

- Bytes representing the bitmap.

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties.
-

- - - Link Bitmap at X/Y Offset from Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<B>

1

byte

- This space is for a graphic type identifier. For - Bitmaps, the value is 1.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the bitmap's anchor point, in decimal degrees.

4

float

- Longitude of the bitmap's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the bitmap's upper left corner, in - pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the bitmap's upper left corner, in - pixels.

4

int

- Width of the bitmap, in pixels.

4

int

- Height of the bitmap, in pixels.

4

int

- Number of bitmap bytes.

1n

byte

- Bytes representing the bitmap.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

-


- - - - - Link Circle at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<C>

1

byte

- This space is for a graphic type identifier. For - Circles, the value is 6.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the circle's center, in decimal degrees.

4

float

- Longitude of the circle's center, in decimal degrees.

4

float

- Radius of the circle, in units defined in the next field.

1

byte

- Units of the radius measurement. Values can be:
- Decimal Degrees = -1
- Kilometers = 0
- Miles = 1
- Nautical Miles = 2

4

int

- Number of verticies to use to approximate the circle. - If this value is -1, the projection algorithm of the - client should decide the best value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Circle at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<C>

1

byte

- This space is for a graphic type identifier. For - Circles, the value is 6.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - circle's center, in pixels.

4

int

- Vertical distance, from the top of the map, of the - circle's center, in pixels.

4

int

- Width of the circle, in pixels.

4

int

- Height of the circle, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Circle at X/Y Offset from Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<C>

1

byte

- This space is for a graphic type identifier. For - Circles, the value is 6.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the circle's anchor point, in decimal degrees.

4

float

- Longitude of the circle's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the circle's center, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the circle's center, in pixels.

4

int

- Width of the circle, in pixels.

4

int

- Height of the circle, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

-


- - - - - Link Ellipse at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<E>

1

byte

- This space is for a graphic type identifier. For - Ellipses, the value is 11.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the ellipse's center, in decimal degrees.

4

float

- Longitude of the ellipse's center, in decimal degrees.

4

float

- Major axis value of the ellipse, in units defined in the next field.

4

float

- Minor axis value of the ellipse, in units defined in the next field.

1

byte

- Units of the axis measurements. Values can be:
- Decimal Degrees = -1
- Kilometers = 0
- Miles = 1
- Nautical Miles = 2

4

float

- Rotation angle in radians.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Ellipse at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<E>

1

byte

- This space is for a graphic type identifier. For - Ellipses, the value is 11.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - ellipse's center, in pixels.

4

int

- Vertical distance, from the top of the map, of the - ellipse's center, in pixels.

4

int

- Major axis length of the ellipse, in pixels.

4

int

- Minor axis length of the ellipse, in pixels.

4

float

- Rotation angle in radians.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Ellipse at X/Y Offset from Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<E>

1

byte

- This space is for a graphic type identifier. For - Ellipses, the value is 11.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the ellipse's anchor point, in decimal degrees.

4

float

- Longitude of the ellipse's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the ellipse's center, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the ellipse's center, in pixels.

4

int

- Width of the ellipse, in pixels.

4

int

- Height of the ellipse, in pixels.

4

int

- Width of the ellipse, in pixels.

4

int

- Height of the ellipse, in pixels.

4

float

- Rotation angle in radians.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

-


- -

-The meaning of location attributes of the grid depend on the -rendertype of the grid. Likewise, the direction of increasing rows -also depends on the rendertype. The convention, howeverm is -consistant. The rows and columns always increase according to the -rendered background. For example, for Lat/Lon rendered grids, the -latitude and longitude of the location of the grid refers to the lower -right corner of the grid. The rows of the data increase as the -latitude increases, and the columns increase with the longitudes. For -X/Y and Offset rendertypes, the grid is located by the x/y point of -the upper left corner of the grid. The rows increase as the y pixel -count increases, which is actually down the screen. The column count -increases with the x pixel count, which is to the right. The -advantage of this is that the horizontal and vertical resolution -directly apply to the index of the columns and rows, when mapping -between lat/lon or x/y to the grid.

- - - - Link Grid at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<GD>

1

byte

- This space is for a graphic type identifier. For - Grids, the value is 8.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the grid's lower left corner, in decimal degrees.

4

float

- Longitude of the grid's lower left corner, in decimal degrees.

4

int

- Number of vertical rows in the grid.

4

int

- Number of horizontal columns in the grid.

4

float

- Orientation of the grid, in radians. North is 0.0, - where the columns are parallel to longitude lines.

4

float

- Vertical resolution of the rows, in degrees/point.

4

float

- Horizontal resolution of the columns, in degrees/point.

1

byte

- Major dimension designation, indicating the primary - dimension of the data. If the data is listed as columns - this value is 0 (COLUMN_MAJOR). If the data is listed - as rows, the value is 1 (ROW_MAJOR).

4

int

- Number of integer values to follow. Should equal rows*columns.

Var

int

- Integer data for the grid.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Grid at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<GD>

1

byte

- This space is for a graphic type identifier. For - Grids, the value is 8.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - grid's left side, in pixels.

4

int

- Vertical distance, from the top of the map, of the - grid's top, in pixels.

4

int

- Number of vertical rows in the grid.

4

int

- Number of horizontal columns in the grid.

4

float

- Orientation of the grid, in radians. Up is 0.0, - where the columns are parallel to the sides of the map.

4

float

- Vertical resolution of the rows, in pixels/point.

4

float

- Horizontal resolution of the columns, in pixels/point.

1

byte

- Major dimension designation, indicating the primary - dimension of the data. If the data is listed as columns - this value is 0 (COLUMN_MAJOR). If the data is listed - as rows, the value is 1 (ROW_MAJOR).

4

int

- Number of integer values to follow. Should equal rows*columns.

Var

int

- Integer data for the grid.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Grid at X/Y Offset from Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<GD>

1

byte

- This space is for a graphic type identifier. For - Grids, the value is 8.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the grid's anchor point, in decimal degrees.

4

float

- Longitude of the grid's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the grid's left side, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the grid's top, in pixels.

4

int

- Number of vertical rows in the grid.

4

int

- Number of horizontal columns in the grid.

4

float

- Orientation of the grid, in radians. Up is 0.0, - where the columns are parallel to the sides of the map.

4

float

- Vertical resolution of the rows, in pixels/point.

4

float

- Horizontal resolution of the columns, in pixels/point.

1

byte

- Major dimension designation, indicating the primary - dimension of the data. If the data is listed as columns - this value is 0 (COLUMN_MAJOR). If the data is listed - as rows, the value is 1 (ROW_MAJOR).

4

int

- Number of integer values to follow. Should equal rows*columns.

Var

int

- Integer data for the grid.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
- -

-


- - - - - Link Line with Lat/Lon Endpoints - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<L>

1

byte

- This space is for a graphic type identifier. For - Lines, the value is 4.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Line type definition. The possible values are:
- Unknown line type = 0
- Straight line = 1
- Rhumb line (constant bearing) = 2
- Great circle line = 3

4

float

- Latitude of the line's start point, in decimal degrees.

4

float

- Longitude of the line's start point, in decimal degrees.

4

float

- Latitude of the line's end point, in decimal degrees.

4

float

- Longitude of the line's end point, in decimal degrees.

4

int

- Number of segments to use in approximating a curved line - on the map. If the value is -1, the client's projection - algorithm should determine the best value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Line with X/Y Endpoints - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<L>

1

byte

- This space is for a graphic type identifier. For - Lines, the value is 4.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - line's start point, in pixels.

4

int

- Vertical distance, from the top of the map, of the - line's start point, in pixels.

4

int

- Horizontal distance, from the left side of the map, of the - line's end point, in pixels.

4

int

- Vertical distance, from the top of the map, of the - line's end point, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Line with X/Y EndPoints at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<L>

1

byte

- This space is for a graphic type identifier. For - Lines, the value is 4.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the line's anchor point, in decimal degrees.

4

float

- Longitude of the line's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the line's start point, in - pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the line's start point, in pixels.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the line's end point, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the line's end point, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
- -

-


- - - - Link Point at a Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PO>

1

byte

- This space is for a graphic type identifier. For - Points, the value is 9.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the point, in decimal degrees.

4

float

- Longitude of the point, in decimal degrees.

4

float

- Radius of the point, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. For - Points, a oval=true property can be added to specify - that the point should be rendered as a circle.
-

- - - Link Point at a X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PO>

1

byte

- This space is for a graphic type identifier. For - Points, the value is 9.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - point's location, in pixels.

4

int

- Vertical distance, from the top of the map, of the - point's location, in pixels.

4

float

- Radius of the point, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. For - Points, a oval=true property can be added to specify - that the point should be rendered as a circle.
-

- - - Link Point at a X/Y Distance from a Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PO>

1

byte

- This space is for a graphic type identifier. For - Points, the value is 9.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the point's anchor point, in decimal degrees.

4

float

- Longitude of the point's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the point's location, in - pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the point's location, in pixels.

4

float

- Radius of the point, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. For - Points, a oval=true property can be added to specify - that the point should be rendered as a circle.
- -

-

-


- - - Lat/Lon polygons, by definition, list their points in a - clockwise direction.

- - - - Link Poly with Lat/Lon Points - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PY>

1

byte

- This space is for a graphic type identifier. For - Polys, the value is 3.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Line type definition. The possible values are:
- Unknown line type = 0
- Straight line = 1
- Rhumb line (constant bearing) = 2
- Great circle line = 3

4

int

- Number of latitude and longitude values to follow. Each - latitude and longitude value contributes to this - count.

4n

float

- Each float represents alternating latitude and longitude - values, in decimal degrees.

1

byte

- Units of the lat/lon values. Possibilities include:
- Decimal degrees = 0
- Radians = 1

4

int

- Number of segments to use in approximating a curved poly - on the map. If the value is -1, the client's projection - algorithm should determine the best value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Poly with X/Y Points - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PY>

1

byte

- This space is for a graphic type identifier. For - Lines, the value is 3.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Number of x and y values to follow. Each x and y value - contributes to this count.

4n

int

- Each integer represents alternating x and y values, in - pixels. The x value represents the horizontal number of - pixels between the point and the left side of the map. - The y value represents the vertical number of pixels - between the point and the top of the map.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Poly with X/Y Points at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<PY>

1

byte

- This space is for a graphic type identifier. For - Lines, the value is 3.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the poly's anchor point, in decimal degrees.

4

float

- Longitude of the poly's anchor point, in decimal degrees.

4

int

- Number of x and y values to follow. Each x and y value - contributes to this count.

4n

int

- Each integer represents alternating x and y values, in - pixels. For the first point in the list, the x value - represents the horizontal number of pixels between the - first point and the anchor point location, while the y - value represents the vertical pixel distance. The - meaning of the remaining pixel values depends on the - coordinate mode, described next.

1

byte

- Coordinate mode of the x/y points. If the coordinate - mode is from the origin, then all the x values refer to - the horizontal pixel distance between the point and the - first point, and the y values refer to the vertical - pixel distance. If the mode is from the previous point, - then all the measurements are taken from the point - proceeding the current one. The possible values - are:
origin = 0
previous = 1

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
- -

-


- - -

Link Raster

- -Images can be transmitted in three different formats. Two of these -represent different colormodels, and the third format is indicates -that the image can be downloaded from an URL. The direct colormodel is -when the pixels are integers containing the RGB -integer values. The indexed colormodel is when the pixels are -bytes, and each byte refers to an index into a colortable. The -colortable is an array of RGB integers. -

- - - - Link Raster, Utilizing the Direct Colormodel, with Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Image format. This Raster is using the direct - colormodel, and the value is 0.

4

float

- Latitude of the upper left point of the image, in - decimal degrees.

4

float

- Longitude of the upper left point of the image, in - decimal degrees.

4

int

- Width of the image, in pixels.

4

int

- Height of the image, in pixels.

4

int

- Number of integer pixels in the image.

4n

int

- Pixel values of the image, each representing a RGB integer value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Utilizing the Direct Colormodel, with X/Y Points - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

1

byte

- Image format. This Raster is using the direct - colormodel, and the value is 0.

4

int

- Horizontal pixel offset, from the left side of the - map, of the upper left corner of the image.

4

int

- Vertical pixel offset, from the top of the map, of the - top left corner of the image.

4

int

- Width of the image, in pixels.

4

int

- Height of the image, in pixels.

4

int

- Number of integer pixels in the image.

4n

int

- Pixel values of the image, each representing a RGB integer value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Utilizing the Direct - Colormodel, with X/Y Offset at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

1

byte

- Image format. This Raster is using the direct - colormodel, and the value is 0. -

4

float

- Latitude of the raster's anchor point, in decimal degrees.

4

float

- Longitude of the raster's anchor point, in decimal degrees.

4

int

- Horizontal pixel offset, from the map location of - the anchor point, of the upper left corner of the - image.

4

int

- Vertical pixel offset, from the map location of the - anchor point, of the upper left corner of the image.

4

int

- Width of the image, in pixels.

4

int

- Height of the image, in pixels.

4

int

- Number of integer pixels in the image.

4n

int

- Pixel values of the image, each representing a RGB integer value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Utilizing the Indexed Colormodel, with Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Image format. This Raster is using the indexed - colormodel, and the value is 1.

4

float

- Latitude of the upper left point of the image, in - decimal degrees.

4

float

- Longitude of the upper left point of the image, in - decimal degrees.

4

int

- Width of the image, in pixels.

4

int

- Height of the image, in pixels.

4

int

- Number of bytes to create the Raster.

1n

byte

- Array of bytes used to create bitmap.

4

int

- Number of integers to create the colortable.

4n

int

- Array of RGB integers that - represent the colortable.

4

int

- The transparency of the image. This should be a value - between 0-255, where 255 means an opaque image.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Utilizing the Indexed Colormodel, with X/Y Points - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

1

byte

- Image format. This Raster is using the indexed - colormodel, and the value is 1.

4

int

- Horizontal pixel offset, from the left side of the - map, of the upper left corner of the image.

4

int

- Vertical pixel offset, from the top of the map, of the - top left corner of the image.

4

int

- Width of the image, in pixels.

4

int

- Number of bytes to create the image.

1n

byte

- Array of bytes used to create image.

4

int

- Number of integers to create the colortable.

4n

int

- Array of RGB integers that - represent the colortable.

4

int

- The transparency of the image. This should be a value - between 0-255, where 255 means an opaque image.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Utilizing the Indexed - Colormodel, with X/Y Offset at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

1

byte

- Image format. This Raster is using the indexed - colormodel, and the value is 1. -

4

float

- Latitude of the raster's anchor point, in decimal degrees.

4

float

- Longitude of the raster's anchor point, in decimal degrees.

4

int

- Horizontal pixel offset, from the map location of - the anchor point, of the upper left corner of the - image.

4

int

- Vertical pixel offset, from the map location of the - anchor point, of the upper left corner of the image.

4

int

- Width of the image, in pixels.

4

int

- Height of the image, in pixels.

4

int

- Number of bytes to create the Raster.

1n

byte

- Array of bytes used to create bitmap.

4

int

- Number of integers to create the colortable.

4n

int

- Array of RGB integers that - represent the colortable.

4

int

- The transparency of the image. This should be a value - between 0-255, where 255 means an opaque image.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Raster, Referencing an Image URL, with Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Image format. This Raster is referencing an URL, and - the value is 2.

4

float

- Latitude of the upper left point of the image, in - decimal degrees.

4

float

- Longitude of the upper left point of the image, in - decimal degrees.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. The URL - of the image to use is located in the Arg List.
-

- - - Link Raster, Referencing an URL, with X/Y Points - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

1

byte

- Image format. This Raster is referencing an URL, and - the value is 2.

4

int

- Horizontal pixel offset, from the left side of the - map, of the upper left corner of the image.

4

int

- Vertical pixel offset, from the top of the map, of the - top left corner of the image.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.. The URL - of the image to use is located in the Arg List.
-

- - - Link Raster, Referencing an URL, with X/Y Offset at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RA>

1

byte

- This space is for a graphic type identifier. For - Rasters, the value is 7.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

1

byte

- Image format. This Raster is referencing an URL, and - the value is 2. -

4

float

- Latitude of the raster's anchor point, in decimal degrees.

4

float

- Longitude of the raster's anchor point, in decimal degrees.

4

int

- Horizontal pixel offset, from the map location of - the anchor point, of the upper left corner of the - image.

4

int

- Vertical pixel offset, from the map location of the - anchor point, of the upper left corner of the image.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.. The URL - of the image to use is located in the Arg List.
-

-


- - - - - Link Rectangle with Lat/Lon Corners - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RE>

1

byte

- This space is for a graphic type identifier. For - Rectangles, the value is 5.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

1

byte

- Line type definition. The possible values are:
- Unknown line type = 0
- Straight line = 1
- Rhumb line (constant bearing) = 2
- Great circle line = 3

4

float

- Latitude of the rectangle's Northwest corner, in decimal degrees.

4

float

- Longitude of the rectangle's Northwest corner, in decimal degrees.

4

float

- Latitude of the rectangle's Southeast corner, in decimal degrees.

4

float

- Longitude of the rectangle's Southeast corner, in decimal degrees.

4

int

- Number of segments to use in approximating a curved rectangle - on the map. If the value is -1, the client's projection - algorithm should determine the best value.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Rectangle with X/Y Corners - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RE>

1

byte

- This space is for a graphic type identifier. For - Rectangles, the value is 5.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - rectangle's upper left corner, in pixels.

4

int

- Vertical distance, from the top of the map, of the - rectangle's upper left corner, in pixels.

4

int

- Horizontal distance, from the left side of the map, of the - rectangle's lower right corner, in pixels.

4

int

- Vertical distance, from the top of the map, of the - rectangle's lower right corner, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

- - - Link Rectangle with X/Y Corners at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<RE>

1

byte

- This space is for a graphic type identifier. For - Rectangles, the value is 5.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the rectangle's anchor point, in decimal degrees.

4

float

- Longitude of the rectangle's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the rectangle's upper left corner, in - pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the rectangle's upper left corner, in pixels.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the rectangle's lower right corner, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the rectangle's lower right corner, in pixels.

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties.
-

-


- -Text is anchored to a specified point on the map using the -baseline of the text. The justification parameter of the text -determines the left-to-right location of the charaters on the baseline. - -

- - - Link Text at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<T>

1

byte

- This space is for a graphic type identifier. For - Text, the value is 2.

1

byte

- This space is for a Rendertype identifier. For Lat/Lon - rendering, the value is 1.

4

float

- Latitude of the text, in decimal degrees.

4

float

- Longitude of the text, in decimal degrees.

1

byte

- Justification of text with regard to the Lat/Lon point. - Possible values:
left = 0
center = 1
right = - 2

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. The text - string and the font representation string are located in - the Arg List. -
-

- - - Link Text at X/Y Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<T>

1

byte

- This space is for a graphic type identifier. For - Text, the value is 5.

1

byte

- This space is for a Rendertype identifier. For X/Y - rendering, the value is 2.

4

int

- Horizontal distance, from the left side of the map, of the - text, in pixels.

4

int

- Vertical distance, from the top of the map, of the - text, in pixels.

1

byte

- Justification of text with regard to the Lat/Lon point. - Possible values:
left = 0
center = 1
right = - 2

Var

- Arg List

- A list of key-value pairs for attribute passing. See Defined Properties. The text - string and the font representation string are located in - the Arg List. -
-

- - - Link Text with X/Y Offset at Lat/Lon Location - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

3

ASCII char

<T>

1

byte

- This space is for a graphic type identifier. For - Text, the value is 2.

1

byte

- This space is for a Rendertype identifier. For offset - rendering, the value is 3.

4

float

- Latitude of the text's anchor point, in decimal degrees.

4

float

- Longitude of the text's anchor point, in decimal degrees.

4

int

- Horizontal distance, from the longitude map anchor - point location, of the text, in pixels.

4

int

- Vertical distance, from the latitude map anchor point - location, of the text, in pixels.

1

byte

- Justification of text with regard to the Lat/Lon point. - Possible values:
left = 0
center = 1
right = - 2

Var

- Arg List

- A list of key-value pairs for attribute passing. See - Defined Properties. The text - string and the font representation string are located in - the Arg List. -
-

-


- -

Defined Properties

- -The properties can contain information on how a graphic should be -drawn, or describing an action that the client should take. In -addition to these defined property names, any other property may be -defined and passed across the link. - -

- - -RGB Integers are used in the protocol to describe colors. The -colors should be passed as hex string representations of the desiired -color. Bits 23-16 represent the red value, bits 15-8 represent the -green value, and bits 7-0 represent the blue value. The range of -values in each color byte is 0 (weakest) to 255 (strongest). For -system implementations that support it, bits 31-24 represent a -tranparency value, where 255 is opaque. For instance, a color -representation of an opaque red should be passed as FFFF0000. - -

- - - Link Properties - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Property Name -

-

Meaning -

lc

- Property key describing the RGB Integer for the line color.

hc

- Property key describing the RGB Integer for the highlight line color.

fc

- Property key describing the RGB Integer for the fill color.

lw

- Property key describing the integer for the line width.

ts

- Property key describing the content string for LinkText objects.

tf

- Property key describing the font description string for - LinkText objects.

rot

- Property key describing the amount of rotation for - LinkGraphics that support rotation, like LinkText and - LinkRaster objects.

tbl

- Property key describing the location of the baseline for - LinkText objects (BASELINE_BOTTOM, BASELINE_MIDDLE or - BASELINE_TOP. BOTTOM is the default).

riu

- Property key describing the URL of an image that a - LinkRaster would use if configured to do that.

gid

- Property key describing graphic identifier for a Link - Graphic object.

url

- Property key describing a url to be used for a list or object.

html

- Property key describing html text to be displayed for a - list or object.

info

- Property key describing a short message to be displayed - for a list or object.

mess

- Property key describing text for a pop-up window or other - messaging tool for be used for a list or object.

time

- Property key describing a time entry.

lat

- Property key describing the decimal degree latitude for a - projection definition (Server directed).

lon

- Property key describing the decimal degree longitude for a - projection definition (Server directed).

s

- Property key describing the scale for a projection - definition (Server directed).

w

- Property key describing the pixel width of a - projection definition (Server directed).

h

- Property key describing the pixel height of a - projection definition (Server directed).

p

- Property key describing the projection type of a - projection definition (Server directed).

latmin

- Property key describing the lower latitude in decimal - degrees of a projection definition (Server directed).

lonmin

- Property key describing the westward longitude in decimal - degrees of a projection definition (Server directed).

latmax

- Property key describing the upper latitude in decimal - degrees of a projection definition (Server directed).

lonmax

- Property key describing the eastward longitude in decimal - degrees of a projection definition (Server directed).

S

- Property value describing the solid line style.

LD

- Property value describing the long dash line style.

DA

- Property value describing the dash line style.

D

- Property value describing the dot line style.

DAD

- Property value describing the dash-dot line style.

DADD

- Property value describing the dash-dot-dot line style.

S

- Property value describing the solid fill pattern.

V

- Property value describing the vertical stripe fill pattern.

H

- Property value describing the horizontal stripe fill pattern.

C

- Property value describing the cross-hatch fill pattern.

DC

- Property value describing the diagonal cross-hatch fill pattern.

FD

- Property value describing the forward diagonal cross fill pattern.

BD

- Property value describing the backward diagonal cross fill pattern.
-

-


-
- -

Action Definitions

- -Actions are tasks that the server gives to the client in order -to manipulate graphics as a result of user gestures or to display updated data. - -

-


- - -A Graphic action is the server requesting that the client -update the appearance of some or all of the graphics on the map. Any -part of the graphic can be modified, and the protocol also supports -the addition and deletion of graphics. -

- - - Graphic Action - - -
- - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<UG>

1

byte

- Action identifier. For graphic actions, the value is 0

4

int

- Graphic action descriptor, which is a - masked integer that describes the action to be taken on - the graphic.

Var

Graphic or - Arg List, depending on the graphic - action descriptor.

- If the graphic action descriptor - describes an action that requires more information - about the updates on a specific graphic, the graphic - is included here. Otherwise, a graphic ID property is - included in the Arg List
- -

- - -The graphic action descriptor is a masked integer that -describes what action should be taken on a graphic. Many actions can -be described with the descriptor. For example, a graphic may be -raised and selected at the same time. The two actions that require a -graphics object are adding a graphic, and updating a graphic. -

- - - Graphic Action Descriptor Masking - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Bit Number -

-

Meaning -

0

- Raise the graphic to be on top of all the other graphics - supplied by the server.

1

- Lower the graphic to be under all the other graphics - supplied by the server.

2

- Delete the graphic.

3

- Select the graphic.

4

- Deselect the graphic.

5

- Deselect all the graphics.

6

- Add the graphic. This requires a graphic - description.

7

- Update the graphic. This requires a graphic - description.
- -

-


- - -A Map Update action is the server requesting that the client -update the location (projection) of a map. - -

- - - Map Update - - -
- - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

ASCII char

<UM>

1

byte

- Action identifier. For graphic actions, the value is 2.

Var

- Arg List

- The Arg List set of properties which describe the new - map projection parameters, including center latitude and - longitude, scale, projection type and pixel size. See - the Defined Properties.
- -

-


- -Args are an array of strings which represent key-value -pairs. As of version 0.6, the args may contain a key-value pair at -the start of the list that advises if these args should overwrite the -last set of args (reuse) or be read without memory of previous args -(clear). This key-value pair is optional.

- - - - Link Args - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

# Bytes -

-

Type -

-

Description -

4

int

- Sum of the number of keys and values.

- The key-value pairs follow:

4

int

- Length of key (1) for management policy (to reuse or clear - any buffered properties).

1

byte

- Text representing management policy key, or 'p'.

4

int

- Length of value (1) for management policy setting.

1

byte

- Text representing management policy value ('R' to reuse, 'C' - to clear).

4

int

- Length of text (key or value), number of characters.

2n

Unicode char

- Text representing key or value.
-

-


-
OpenMap
- - -Last modified: Mon Feb 9 15:29:07 EST 2004 - - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRaster.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRaster.java deleted file mode 100644 index 74892b52b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRaster.java +++ /dev/null @@ -1,758 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkRaster.java,v $ -// $RCSfile: LinkRaster.java,v $ -// $Revision: 1.7 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.awt.Color; -import java.awt.Image; -import java.awt.image.PixelGrabber; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Read and write a Link protocol versions of a raster. - */ -public class LinkRaster implements LinkGraphicConstants, - LinkPropertiesConstants { - - /** - * Writes an image, Lat/Lon placement with a direct colormodel. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int w, int h, int[] pix, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(COLORMODEL_DIRECT); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(pix.length); - - for (int i = 0; i < pix.length; i++) { - dos.writeInt(pix[i]); - } - properties.write(dos); - } - - /** - * Write an image, XY placement with a direct colormodel. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, int w, int h, int[] pix, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_XY); - dos.writeByte(COLORMODEL_DIRECT); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(pix.length); - - for (int i = 0; i < pix.length; i++) { - dos.writeInt(pix[i]); - } - properties.write(dos); - } - - /** - * Write an image, Lat/lon placement with XY offset with a direct - * colormodel. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, int[] pix, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeByte(COLORMODEL_DIRECT); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(pix.length); - - for (int i = 0; i < pix.length; i++) { - dos.writeInt(pix[i]); - } - properties.write(dos); - } - - /** - * Write an image, Lat/Lon placement with an ImageIcon. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param image java.awt.Image to use for image. - * @param image_width width of image in pixels. - * @param image_height height of image in pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, Image image, int image_width, - int image_height, LinkProperties properties, - DataOutputStream dos) throws IOException, - InterruptedException { - - int[] pixels = new int[image_width * image_height]; - - PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, image_width, image_height, pixels, 0, image_width); - pixelgrabber.grabPixels(); - - LinkRaster.write(lt, - ln, - image_width, - image_height, - pixels, - properties, - dos); - } - - /** - * Write an image, X/Y placement with an ImageIcon. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param image java.awt.Image to use for image. - * @param image_width width of image in pixels. - * @param image_height height of image in pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, Image image, int image_width, - int image_height, LinkProperties properties, - DataOutputStream dos) throws IOException, - InterruptedException { - int[] pixels = new int[image_width * image_height]; - - PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, image_width, image_height, pixels, 0, image_width); - pixelgrabber.grabPixels(); - - LinkRaster.write(x1, - y1, - image_width, - image_height, - pixels, - properties, - dos); - } - - /** - * Write an image, Lat/Lon with X/Y placement with an ImageIcon. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param image java.awt.Image to use for image. - * @param image_width width of image in pixels. - * @param image_height height of image in pixels. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - Image image, int image_width, int image_height, - LinkProperties properties, DataOutputStream dos) - throws IOException, InterruptedException { - int[] pixels = new int[image_width * image_height]; - - PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, image_width, image_height, pixels, 0, image_width); - pixelgrabber.grabPixels(); - - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - image_width, - image_height, - pixels, - properties, - dos); - } - - /** - * Write an image, Lat/Lon placement with an ImageIcon. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param ii ImageIcon to use for image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, ImageIcon ii, - LinkProperties properties, DataOutputStream dos) - throws IOException, InterruptedException { - - int image_width, image_height; - Image image; - - image_width = ii.getIconWidth(); - image_height = ii.getIconHeight(); - image = ii.getImage(); - LinkRaster.write(lt, - ln, - image, - image_width, - image_height, - properties, - dos); - } - - /** - * Write an image, X/Y placement with an ImageIcon. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param ii ImageIcon to use for image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, ImageIcon ii, - LinkProperties properties, DataOutputStream dos) - throws IOException, InterruptedException { - - int image_width, image_height; - Image image; - - image_width = ii.getIconWidth(); - image_height = ii.getIconHeight(); - image = ii.getImage(); - LinkRaster.write(x1, - y1, - image, - image_width, - image_height, - properties, - dos); - } - - /** - * Write an image, Lat/Lon with X/Y placement with an ImageIcon. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param ii ImageIcon to use for image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - ImageIcon ii, LinkProperties properties, - DataOutputStream dos) throws IOException, - InterruptedException { - - int image_width, image_height; - Image image; - - image_width = ii.getIconWidth(); - image_height = ii.getIconHeight(); - image = ii.getImage(); - LinkRaster.write(lt, - ln, - offset_x1, - offset_y1, - image, - image_width, - image_height, - properties, - dos); - - } - - // //////////////////////////////////// IMAGEICON LOADED FROM AN - // URL - - /** - * Write an image, Lat/Lon placement with an ImageIcon. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param url URL to download the image from. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, String url, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(COLORMODEL_URL); - dos.writeFloat(lt); - dos.writeFloat(ln); - properties.setProperty(LPC_LINKRASTERIMAGEURL, url); - properties.write(dos); - } - - /** - * Write an image, X/Y placement with an ImageIcon. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param url URL to download the image from. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, String url, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_XY); - dos.writeByte(COLORMODEL_URL); - dos.writeInt(x1); - dos.writeInt(y1); - properties.setProperty(LPC_LINKRASTERIMAGEURL, url); - properties.write(dos); - } - - /** - * Write an image, Lat/Lon with X/Y placement with an ImageIcon. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param url URL to download the image from. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - String url, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeByte(COLORMODEL_URL); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - properties.setProperty(LPC_LINKRASTERIMAGEURL, url); - properties.write(dos); - } - - // //////////////////////////////////// BYTE PIXELS with - // COLORTABLE - - /** - * Lat/Lon placement with a indexed colormodel, which is using a colortable - * and a byte array to construct the int[] pixels. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(COLORMODEL_INDEXED); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - dos.writeInt(colorTable.length); - - int i; - for (i = 0; i < colorTable.length; i++) { - dos.writeInt(colorTable[i].getRGB()); - } - dos.writeInt(trans); - - properties.write(dos); - } - - /** - * XY placement with a indexed colormodel, which is using a colortable and a - * byte array to construct the int[] pixels. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, int w, int h, byte[] bytes, - Color[] colorTable, int trans, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_XY); - dos.writeByte(COLORMODEL_INDEXED); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - dos.writeInt(colorTable.length); - - int i; - for (i = 0; i < colorTable.length; i++) { - dos.writeInt(colorTable[i].getRGB()); - } - dos.writeInt(trans); - - properties.write(dos); - } - - /** - * Lat/lon placement with XY offset with a indexed colormodel, which is - * using a colortable and a byte array to construct the int[] pixels. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @param properties description of drawing attributes. Not used, but - * included to be consistent with the protocol graphics format. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt, float ln, int offset_x1, int offset_y1, - int w, int h, byte[] bytes, Color[] colorTable, - int trans, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.RASTER_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RASTER); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeByte(COLORMODEL_INDEXED); - dos.writeFloat(lt); - dos.writeFloat(ln); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(bytes.length); - dos.write(bytes, 0, bytes.length); - dos.writeInt(colorTable.length); - - int i; - - for (i = 0; i < colorTable.length; i++) { - dos.writeInt(colorTable[i].getRGB()); - } - dos.writeInt(trans); - - properties.write(dos); - } - - /** - * Write a raster to the link. - */ - public static void write(OMRaster raster, Link link, LinkProperties props) - throws IOException { - - switch (raster.getRenderType()) { - case OMRaster.RENDERTYPE_LATLON: - case OMRaster.RENDERTYPE_XY: - case OMRaster.RENDERTYPE_OFFSET: - default: - Debug.error("LinkRaster.write: raster not implemented."); - } - } - - /** - * Read the DataInputStream, and create an OMRaster. Assumes that the - * LinkRaster header has been read from the link. - * - * @param dis DataInputStream - * @return OMRaster - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMRaster - */ - public static OMRaster read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the DataInputStream, and create an OMRaster. Assumes that the - * LinkRaster header has been read from the link. - * - * @param dis DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMPoly being read. - * @return OMRaster - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMRaster - */ - public static OMRaster read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMRaster raster = null; - float lat = 0; - float lon = 0; - int x = 0; - int y = 0; - int w = 0; - int h = 0; - int length, i; - String url; - - Debug.message("link", "LinkRaster | Reading Raster graphic"); - - int renderType = dis.readByte(); - int colorModel = dis.readByte(); - - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Rendertype = " + renderType - + ", colorModel = " + colorModel); - } - - switch (renderType) { - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - // Fall through... - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - break; - case RENDERTYPE_LATLON: - default: - lat = dis.readFloat(); - lon = dis.readFloat(); - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Location: lat = " + lat - + ", lon = " + lon); - } - } - - // Now act differently depending on the colormodel - if (colorModel != COLORMODEL_URL) { - - w = dis.readInt(); - h = dis.readInt(); - - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Size: width = " + w - + ", height = " + h); - } - - if (colorModel == COLORMODEL_INDEXED) { - - length = dis.readInt(); - - byte[] bytes = new byte[length]; - - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Reading " + length - + " bytes."); - } - dis.readFully(bytes); - - if (Debug.debugging("link")) { - System.out.println("LinkRaster | read bytes."); - } - - length = dis.readInt(); - - if (Debug.debugging("link")) { - System.out.println("LinkRaster | " + length + " Colors."); - } - - Color[] colorTable = new Color[length]; - for (i = 0; i < length; i++) { - int colorvalue = dis.readInt(); - colorTable[i] = ColorFactory.createColor(colorvalue, true); - if (Debug.debugging("linkdetail")) { - System.out.println("LinkRaster | Color " + i + " = " - + colorTable[i] + " from " - + Integer.toHexString(colorvalue)); - } - } - - int trans = dis.readInt(); - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Transparency = " + trans); - } - - switch (renderType) { - case RENDERTYPE_OFFSET: - raster = new OMRaster(lat, lon, x, y, w, h, bytes, colorTable, trans); - break; - case RENDERTYPE_XY: - raster = new OMRaster(x, y, w, h, bytes, colorTable, trans); - break; - case RENDERTYPE_LATLON: - default: - raster = new OMRaster(lat, lon, w, h, bytes, colorTable, trans); - } - - } else { // must be COLORMODEL_DIRECT - length = dis.readInt(); - int[] pix = new int[length]; - if (Debug.debugging("link")) { - System.out.println("LinkRaster | Reading " + length - + " pixels."); - } - - for (i = 0; i < length; i++) { - pix[i] = dis.readInt(); - } - switch (renderType) { - case RENDERTYPE_OFFSET: - raster = new OMRaster(lat, lon, x, y, w, h, pix); - break; - case RENDERTYPE_XY: - raster = new OMRaster(x, y, w, h, pix); - break; - case RENDERTYPE_LATLON: - default: - raster = new OMRaster(lat, lon, w, h, pix); - } - } - } - - LinkProperties properties = (LinkProperties) LinkProperties.read(dis, propertiesBuffer).clone(); - - if (colorModel == COLORMODEL_URL) { - url = properties.getProperty(LPC_LINKRASTERIMAGEURL); - - if (url != null) { - switch (renderType) { - case RENDERTYPE_OFFSET: - raster = new OMRaster(lat, lon, x, y, new ImageIcon(url)); - break; - case RENDERTYPE_XY: - raster = new OMRaster(x, y, new ImageIcon(url)); - break; - case RENDERTYPE_LATLON: - default: - raster = new OMRaster(lat, lon, new ImageIcon(url)); - } - } - } - - if (raster != null) { - properties.setProperties(raster); - raster.setRotationAngle((double) ProjMath.degToRad(PropUtils.floatFromProperties(properties, - LPC_LINKROTATION, - 0.0f))); - } - - return raster; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRectangle.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRectangle.java deleted file mode 100644 index cd543aaf7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkRectangle.java +++ /dev/null @@ -1,267 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkRectangle.java,v $ -// $RCSfile: LinkRectangle.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.util.Debug; - -/** - * Read and write the Link protocol for rectangles. - */ -public class LinkRectangle implements LinkGraphicConstants, - LinkPropertiesConstants { - - /** - * Create a lat/lon rectangle. - * - * @param lt1 latitude of north edge, decimal degrees. - * @param ln1 longitude of west edge, decimal degrees. - * @param lt2 latitude of south edge, decimal degrees. - * @param ln2 longitude of east edge, decimal degrees. - * @param lType line type - see lineType. - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt1, float ln1, float lt2, float ln2, - int lType, LinkProperties properties, - DataOutputStream dos) throws IOException { - LinkRectangle.write(lt1, ln1, lt2, ln2, lType, -1, properties, dos); - } - - /** - * Create a lat/lon rectangle. - * - * @param lt1 latitude of north edge, decimal degrees. - * @param ln1 longitude of west edge, decimal degrees. - * @param lt2 latitude of south edge, decimal degrees. - * @param ln2 longitude of east edge, decimal degrees. - * @param lType line type - see lineType. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is generated - * internally) - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt1, float ln1, float lt2, float ln2, - int lType, int nsegs, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.RECTANGLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RECTANGLE); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeByte(lType); - dos.writeFloat(lt1); - dos.writeFloat(ln1); - dos.writeFloat(lt2); - dos.writeFloat(ln2); - - dos.writeInt(nsegs); - properties.write(dos); - } - - /** - * Construct an XY rectangle. It doesn't matter which corners of the - * rectangle are used, as long as they are opposite from each other. - * - * @param px1 x pixel position of the first corner relative to the window - * origin - * @param py1 y pixel position of the first corner relative to the window - * origin - * @param px2 x pixel position of the second corner relative to the window - * origin - * @param py2 y pixel position of the second corner relative to the window - * origin - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int px1, int py1, int px2, int py2, - LinkProperties properties, DataOutputStream dos) - throws IOException { - - dos.write(Link.RECTANGLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RECTANGLE); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(px1); - dos.writeInt(py1); - dos.writeInt(px2); - dos.writeInt(py2); - properties.write(dos); - } - - /** - * Construct an XY rectangle relative to a lat/lon point - * (RENDERTYPE_OFFSET). It doesn't matter which corners of the rectangle are - * used, as long as they are opposite from each other. - * - * @param lt1 latitude of the reference point, decimal degrees. - * @param ln1 longitude of the reference point, decimal degrees. - * @param px1 x pixel position of the first corner relative to the reference - * point - * @param py1 y pixel position of the first corner relative to the reference - * point - * @param px2 x pixel position of the second corner relative to the - * reference point - * @param py2 y pixel position of the second corner relative to the - * reference point - * @param properties description of drawing attributes. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float lt1, float ln1, int px1, int py1, int px2, - int py2, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.RECTANGLE_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_RECTANGLE); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(lt1); - dos.writeFloat(ln1); - dos.writeInt(px1); - dos.writeInt(py1); - dos.writeInt(px2); - dos.writeInt(py2); - properties.write(dos); - } - - /** - * Write an OMRect to the link. - */ - public static void write(OMRect rect, Link link, LinkProperties props) - throws IOException { - - switch (rect.getRenderType()) { - case OMRect.RENDERTYPE_LATLON: - LinkRectangle.write((float) rect.getNorthLat(), - (float) rect.getWestLon(), - (float) rect.getSouthLat(), - (float) rect.getEastLon(), - rect.getLineType(), - props, - link.dos); - break; - case OMRect.RENDERTYPE_XY: - LinkRectangle.write(rect.getLeft(), - rect.getTop(), - rect.getRight(), - rect.getBottom(), - props, - link.dos); - break; - case OMRect.RENDERTYPE_OFFSET: - LinkRectangle.write((float) rect.getNorthLat(), - (float) rect.getWestLon(), - rect.getLeft(), - rect.getTop(), - rect.getRight(), - rect.getBottom(), - props, - link.dos); - break; - default: - Debug.error("LinkRectangle.write: rect rendertype unknown."); - } - } - - /** - * Read the DataInputStream, and create an OMRect. Assumes that the - * LinkRectangle header has been read from the link. - * - * @param dis DataInputStream - * @return OMRect - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMRect - */ - public static OMRect read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the DataInputStream, and create an OMRect. Assumes that the - * LinkRectangle header has been read from the link. - * - * @param dis DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMRect being read. - * @return OMRect - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMRect - */ - public static OMRect read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - OMRect rect = null; - int x1, y1, x2, y2; - double lt1, ln1, lt2, ln2; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_LATLON: - int lineType = dis.readByte(); - lt1 = dis.readFloat(); - ln1 = dis.readFloat(); - lt2 = dis.readFloat(); - ln2 = dis.readFloat(); - int nsegs = dis.readInt(); - - rect = new OMRect(lt1, ln1, lt2, ln2, lineType, nsegs); - break; - case RENDERTYPE_XY: - x1 = dis.readInt(); - y1 = dis.readInt(); - x2 = dis.readInt(); - y2 = dis.readInt(); - - rect = new OMRect(x1, y1, x2, y2); - break; - case RENDERTYPE_OFFSET: - lt1 = dis.readFloat(); - ln1 = dis.readFloat(); - - x1 = dis.readInt(); - y1 = dis.readInt(); - x2 = dis.readInt(); - y2 = dis.readInt(); - - rect = new OMRect(lt1, ln1, x1, y1, x2, y2); - break; - default: - } - - if (rect != null) { - LinkProperties.loadPropertiesIntoOMGraphic(dis, - rect, - propertiesBuffer); - } - - return rect; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServer.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServer.java deleted file mode 100644 index f954f52c0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServer.java +++ /dev/null @@ -1,176 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkServer.java,v $ -// $RCSfile: LinkServer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 18:08:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; -import java.net.Socket; - -/** - * The Link Server is the object communicating with the LinkLayer. It - * is launched within its own thread to handle a specific client. If - * the server is accessing a database or an object that many - * LinkServers may be contacting, You'll need to ensure some amount of - * thread safety for the data if the data is being modified by the - * LinkServer. - */ -public class LinkServer extends Thread implements LinkPropertiesConstants { - /** The Link to use to talk to the client. */ - protected Link link; - - /** - * Constructor used by the LinkServerStarter in using this class - * as a LinkServerFactory. - */ - public LinkServer() {} - - /** - * Create child thread that will handle the client. - * - * @param s the socket to communicate over. - */ - public LinkServer(Socket s) { - try { - link = new Link(s); - } catch (java.io.IOException ioe) { - System.err.println("LinkServer: IOException while creating child server:"); - System.err.println(ioe); - } - } - - /** From the Runnable interface. The thread starts here... */ - public void run() { - try { - handleClient(); - } catch (IOException ioe) { - link.cleanUp(); - link = null; - if (com.bbn.openmap.util.Debug.debugging("link")) { - System.err.println(ioe); - } - com.bbn.openmap.util.Debug.output("LinkServer: Client disconnected"); - System.gc(); - } - } - - /** - * handleClient is a method that listens to the link to a client, - * and responds to requests that are made. - * - * @throws IOException - */ - public void handleClient() throws IOException { - boolean validQuery; - - while (true) { - link.readAndParse(); - validQuery = false; - - // For instance, you could do something like this... - - // LinkMapRequest graphicsQuery = link.getMapRequest(); - // LinkActionRequest gestureQuery = - // link.getActionRequest(); - - // if (graphicsQuery != null) { - // getRectangle(graphicsQuery, link); - // validQuery = true; - // } - // if (gestureQuery != null) { - // handleGesture(gestureQuery, link); - // validQuery = true; - // } - - if (!validQuery) { - huh(link); - } - } - } - - /** - * If a request is not handled, or not understood, reply with - * this. - * - * @throws IOException - */ - public void huh(Link link) throws IOException { - link.start(Link.HUH_HEADER); - link.end(Link.END_TOTAL); - } - - /** - * An example of how to handle GraphicsLinkQueries. - * - * @param query the GraphicsLinkQuery, so you can get more - * information about the parameters of the map screen of - * the client. - * @param link the link to communicate the response back to the - * client. - * @throws IOException - */ - public void getRectangle(LinkMapRequest query, Link link) - throws IOException { - - LinkGraphicList lgl = new LinkGraphicList(link, new LinkProperties()); - - // Send nothing - - lgl.end(Link.END_SECTION); - - int des = LinkUtil.setMask(0, LinkActionRequest.MOUSE_CLICKED_MASK); - new LinkActionRequest(link, des, Link.END_TOTAL); - } - - /** - * An example of how to handle LinkActionRequest. - * - * @param lar the LinkActionRequest, so you can get more - * information about the parameters of the gesture frome - * the client. - * @param link the link to communicate the response back to the - * client. - * @throws IOException - */ - public void handleGesture(LinkActionRequest lar, Link link) - throws IOException { - - LinkProperties properties = new LinkProperties(); - properties.setProperty(LPC_INFO, ("Mouse Clicked at: x = " + lar.getX() - + ", y = " + lar.getY())); - - LinkActionList lal = new LinkActionList(link, properties); -// int descriptor = lar.getDescriptor(); - - String gid = lar.getProperties().getProperty(LPC_GRAPHICID); - if (gid == null) { - System.out.println("Deselecting graphics"); - lal.deselectGraphics(); - } else { - System.out.println("Selecting graphic"); - lal.modifyGraphic(LinkActionList.MODIFY_SELECT_GRAPHIC_MASK, - lar.getProperties()); - } - - lal.end(Link.END_TOTAL); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServerStarter.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServerStarter.java deleted file mode 100644 index 08a27afd0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkServerStarter.java +++ /dev/null @@ -1,137 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkServerStarter.java,v $ -// $RCSfile: LinkServerStarter.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:57 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.net.ServerSocket; -import java.net.Socket; - -/** - * The LinkServerStarter is the object that listens for Link clients - * on a specific port. If a Link client contacts it, it uses the - * startNewServer method to create a LinkServer to serve the client on - * it's own thread. If you want to create a new type of LinkServer, - * you should also create a new LinkServerStarter to launch it - * properly. Generally, the main() and startNewServer() methods are - * the only thing you would need to modify. - */ -public class LinkServerStarter { - - /** Default port that the server starter listens to. */ - public static final int DEFAULT_PORT = 3031; - /** The port being listened to. */ - protected int serverPort; - - /** Starts the LinkServerStarter listening to the default port. */ - public LinkServerStarter() { - serverPort = DEFAULT_PORT; - } - - /** Starts the LinkServerStarter listening to the specified port. */ - public LinkServerStarter(int port) { - serverPort = port; - } - - /** Set the port to listen for a connection request. */ - public void setPort(int port) { - serverPort = port; - } - - /** Get the port that is being listened to. */ - public int getPort() { - return serverPort; - } - - /** - * The method of the parent server that is listening for clients. - * When a contact is made, a child thread is spawned off to handle - * the client. - */ - public void run() { - try { - ServerSocket serverSocket = new ServerSocket(serverPort); - Socket socket; - System.out.println("LinkServerStarter: running on port " - + serverPort); - - while (true) { - socket = serverSocket.accept(); - System.out.println("LinkServer: fielding connection"); - ((Thread) startNewServer(socket)).start(); - } - - } catch (java.io.IOException ioe) { - System.err.println("LinkServer: IOException while running:"); - System.err.println(ioe); - } - } - - /** - * This method gets called to create a new server to handle a new - * connection. Thread.start() will get called on the returned - * thread. This method should always get overridden. - * - * @param sock the socket connection - * @return a thread that will get started - * @see java.lang.Thread#start() - */ - public Thread startNewServer(Socket sock) { - return new LinkServer(sock); - } - - /** - * Start up the server. This is the method to change if you want - * to customize how the LinkServer will handle clients - port, - * arguments, etc. - */ - public static void main(String[] argv) { - - int pnumber = -1; - - com.bbn.openmap.util.Debug.init(); - - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-port") && argv.length > i + 1) { - try { - pnumber = Integer.parseInt(argv[i + 1]); - break; - } catch (NumberFormatException e) { - pnumber = -1; - } - } - } - - if (pnumber < 0) { - System.out.println("Need to start the server with a port number."); - System.out.println("Usage: java com.bbn.openmap.layer.link.LinkServerStarter -port "); - System.exit(0); - } - - System.out.println("LinkServerStarter: Starting up on port " + pnumber - + "."); - LinkServerStarter serverStarter = new LinkServerStarter(pnumber); - while (true) { - serverStarter.run(); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkText.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkText.java deleted file mode 100644 index c940a7cbe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkText.java +++ /dev/null @@ -1,263 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkText.java,v $ -// $RCSfile: LinkText.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - */ -public class LinkText implements LinkGraphicConstants, LinkPropertiesConstants { - - public static String DEFAULT_FONT = "-*-SansSerif-normal-o-normal--12-*-*-*-*-*-*"; - - /** - * Creates a text object, with Lat/Lon placement. - * - * @param latPoint latitude of the string, in decimal degrees. - * @param lonPoint longitude of the string, in decimal degrees. - * @param stuff the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string. - * @param properties attributes for the graphic. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, String stuff, - String font, int just, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.TEXT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_TEXT); - dos.writeByte(RENDERTYPE_LATLON); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeByte(just); - - properties.setProperty(LPC_LINKTEXTSTRING, stuff); - properties.setProperty(LPC_LINKTEXTFONT, font); - properties.write(dos); - } - - /** - * Creates a text object, with XY placement, and default SansSerif font. - * - * @param x1 horizontal window pixel location of the string. - * @param y1 vertical window pixel location of the string. - * @param stuff the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string - * @param properties attributes for the graphic. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(int x1, int y1, String stuff, String font, - int just, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.TEXT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_TEXT); - dos.writeByte(RENDERTYPE_XY); - dos.writeInt(x1); - dos.writeInt(y1); - dos.writeByte(just); - - properties.setProperty(LPC_LINKTEXTSTRING, stuff); - properties.setProperty(LPC_LINKTEXTFONT, font); - properties.write(dos); - } - - /** - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of text/ellipse. - * @param lonPoint longitude of center of text/ellipse. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param stuff the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string. - * @param properties attributes for the graphic. - * @param dos DataOutputStream - * @throws IOException - */ - public static void write(float latPoint, float lonPoint, int offset_x1, - int offset_y1, String stuff, String font, - int just, LinkProperties properties, - DataOutputStream dos) throws IOException { - - dos.write(Link.TEXT_HEADER.getBytes()); - dos.writeByte(GRAPHICTYPE_TEXT); - dos.writeByte(RENDERTYPE_OFFSET); - dos.writeFloat(latPoint); - dos.writeFloat(lonPoint); - dos.writeInt(offset_x1); - dos.writeInt(offset_y1); - dos.writeByte(just); - - properties.setProperty(LPC_LINKTEXTSTRING, stuff); - properties.setProperty(LPC_LINKTEXTFONT, font); - properties.write(dos); - } - - /** - * Write a text to the link. - */ - public static void write(OMText text, Link link, LinkProperties props) - throws IOException { - - switch (text.getRenderType()) { - case OMText.RENDERTYPE_LATLON: - write((float) text.getLat(), - (float) text.getLon(), - text.getData(), - OMText.fontToXFont(text.getFont()), - text.getJustify(), - props, - link.dos); - break; - case OMText.RENDERTYPE_XY: - write(text.getX(), - text.getY(), - text.getData(), - OMText.fontToXFont(text.getFont()), - text.getJustify(), - props, - link.dos); - break; - case OMText.RENDERTYPE_OFFSET: - write((float) text.getLat(), - (float) text.getLon(), - text.getX(), - text.getY(), - text.getData(), - OMText.fontToXFont(text.getFont()), - text.getJustify(), - props, - link.dos); - break; - default: - Debug.error("LinkText.write: text rendertype unknown."); - } - } - - /** - * Read the DataInputStream to create a OMText. Assumes the LinkText header - * has already been read. - * - * @param dis DataInputStream - * @return OMText - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMText - */ - public static OMText read(DataInputStream dis) throws IOException { - return read(dis, null); - } - - /** - * Read the DataInputStream to create a OMText. Assumes the LinkText header - * has already been read. - * - * @param dis DataInputStream - * @param propertiesBuffer a LinkProperties object used to cache previous - * settings that can be set on the OMText being read. - * @return OMText - * @throws IOException - * @see com.bbn.openmap.omGraphics.OMText - */ - public static OMText read(DataInputStream dis, - LinkProperties propertiesBuffer) - throws IOException { - - OMText text = null; - float lat = 0; - float lon = 0; - int x = 0; - int y = 0; - int just = 0; - String string, font; - - int renderType = dis.readByte(); - - switch (renderType) { - case RENDERTYPE_OFFSET: - lat = dis.readFloat(); - lon = dis.readFloat(); - // Fall through... - case RENDERTYPE_XY: - x = dis.readInt(); - y = dis.readInt(); - break; - case RENDERTYPE_LATLON: - default: - lat = dis.readFloat(); - lon = dis.readFloat(); - } - - just = dis.readByte(); - - LinkProperties properties = (LinkProperties) LinkProperties.read(dis, - propertiesBuffer).clone(); - - string = properties.getProperty(LPC_LINKTEXTSTRING); - font = properties.getProperty(LPC_LINKTEXTFONT); - - if (string == null) - string = ""; - if (font == null) - font = DEFAULT_FONT; - - switch (renderType) { - case RENDERTYPE_OFFSET: - text = new OMText(lat, lon, x, y, string, OMText.rebuildFont(font), just); - break; - case RENDERTYPE_XY: - text = new OMText(x, y, string, OMText.rebuildFont(font), just); - break; - case RENDERTYPE_LATLON: - default: - text = new OMText(lat, lon, string, OMText.rebuildFont(font), just); - } - - if (text != null) { - properties.setProperties(text); - text.setBaseline(PropUtils.intFromProperties(properties, - LPC_LINKTEXTBASELINE, - BASELINE_BOTTOM)); - text.setRotationAngle((double) ProjMath.degToRad(PropUtils.floatFromProperties(properties, - LPC_LINKROTATION, - 0.0f))); - } - - return text; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkUtil.java b/src/core/src/main/java/com/bbn/openmap/layer/link/LinkUtil.java deleted file mode 100644 index a23f428aa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/LinkUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/LinkUtil.java,v -// $ -// $RCSfile: LinkUtil.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:57 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.DataInput; -import java.io.IOException; - -public class LinkUtil { - - /** - * readString reads an expected number of characters off a - * DataInput and creates a String from it. - * - * @param length the number of characters to be read.. - */ - protected static String readString(DataInput dis, int length) - throws IOException, ArrayIndexOutOfBoundsException { - String ret = null; - char[] chars = new char[length]; - - for (int i = 0; i < length; i++) { - chars[i] = dis.readChar(); - } - ret = new String(chars); - return ret; - } - - /** Provided as a readability convenience. */ - public static int setMask(int value, int mask) { - return (value | mask); - } - - /** Provided as a readability convenience. */ - public static int unsetMask(int value, int mask) { - return (value & ~mask); - } - - /** Provided as a readability convenience. */ - public static boolean isMask(int value, int mask) { - if ((value & mask) == 0) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/TestLinkServer.java b/src/core/src/main/java/com/bbn/openmap/layer/link/TestLinkServer.java deleted file mode 100644 index 6eb783831..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/TestLinkServer.java +++ /dev/null @@ -1,238 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/TestLinkServer.java,v $ -// $RCSfile: TestLinkServer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/09 18:08:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.io.IOException; -import java.net.Socket; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * The TestLinkServer is my test implementation of a customized - * LinkServer. - */ -public class TestLinkServer extends LinkServer implements LinkActionConstants, - LinkPropertiesConstants { - - int newGraphicCounter = 0; - - LinkOMGraphicList clientCreatedGraphics = new LinkOMGraphicList(); - - /** - * Create child thread that will handle the client. - * - * @param s the socket to communicate over. - */ - public TestLinkServer(Socket s) { - super(s); - } - - /** - * handleClient is a method that listens to the link to a client, - * and responds to requests that are made. - */ - public void handleClient() throws IOException { - boolean validQuery; - - while (true) { - link.readAndParse(); - validQuery = false; - System.out.println("TestLinkServer: fielding request"); - - LinkMapRequest graphicsQuery = link.getMapRequest(); - LinkActionRequest gestureQuery = link.getActionRequest(); - LinkActionList actionList = link.getActionList(); - - if (graphicsQuery != null) { - System.out.println((LinkMapRequest) graphicsQuery); - getRectangle(graphicsQuery, link); - validQuery = true; - } - if (gestureQuery != null) { - System.out.println(gestureQuery); - handleGesture(gestureQuery, link); - validQuery = true; - } - if (actionList != null) { - Vector graphicUpdates = actionList.getGraphicUpdates(); - Iterator it = graphicUpdates.iterator(); - while (it.hasNext()) { - GraphicUpdate gu = (GraphicUpdate) it.next(); - if (gu != null) { - String id = gu.id; - System.out.println("TestLinkServer: graphic id = " + id); - - OMGraphic graphic = gu.graphic; - int index = clientCreatedGraphics.getOMGraphicIndexWithId(id); - if (index != Link.UNKNOWN) { - System.out.println("TestLinkServer: modifying graphic"); - clientCreatedGraphics.setOMGraphicAt(gu.graphic, - index); - } else { - System.out.println("TestLinkServer: new graphic"); - // Set the ID for it, so it can be - // referred to later. - LinkProperties props = (LinkProperties) graphic.getAttribute(OMGraphic.APP_OBJECT); - - props.setProperty(LPC_GRAPHICID, "graphic" - + (newGraphicCounter++)); - System.out.println("TestLinkServer: new graphic given id " - + props); - } - - clientCreatedGraphics.doAction(gu.graphic, - new OMAction(gu.action)); - - } - } - } - - if (!validQuery) { - huh(link); - } - } - } - - /** - * An example of how to handle GraphicsLinkQueries. - * - * @param query the GraphicsLinkQuery, so you can get more - * information about the parameters of the map screen of - * the client. - * @param link the link to communicate the response back to the - * client. - */ - public void getRectangle(LinkMapRequest query, Link link) - throws IOException { - - LinkProperties lineProperties = new LinkProperties(LPC_LINECOLOR, "FFFF0000"); - lineProperties.setProperty(LPC_GRAPHICID, "testline1"); - lineProperties.setProperty(LPC_FILLCOLOR, "FFFF0000"); - lineProperties.setProperty(LPC_HIGHLIGHTCOLOR, "FFFFFF00"); - lineProperties.setProperty(LPC_LINEWIDTH, "1"); - lineProperties.setProperty(LPC_INFO, "Testing info line."); - // lineProperties.setProperty(LPC_URL, - // "http://blatz.bbn.com/users/dietrick/LinkProtocol.html"); - - int count = 0; - LinkGraphicList gr = new LinkGraphicList(link, new LinkProperties()); - - LinkBoundingPoly[] bounds = query.getBoundingPolys(); - - for (int i = 0; i < bounds.length; i++) { - - gr.addLine(bounds[i].maxY, - bounds[i].minX, - bounds[i].minY, - bounds[i].maxX, - (int) OMGraphic.LINETYPE_STRAIGHT, - -1, - lineProperties); - count++; - - int[] data = new int[10000]; - - for (int j = 0; j < 10000; j++) { - if (j < 3000) { - data[j] = 0xFFFF0000; - } else if (j < 6000) { - data[j] = 0xFF00FF00; - } else if (j < 8000) { - data[j] = 0xFF0000FF; - } else { - data[j] = 0xFFAAAAAA; - } - } - - gr.addGrid(42.0f, - -70.0f, - 100, - 100, - 0.0f, - .001f, - .001f, - LinkGraphicConstants.COLUMN_MAJOR, - data, - new LinkProperties()); - count++; - - // for (int x = 10; x < 600; x+=2) { - // for (int y = 10; y < 500; y+=50) { - // link.addLine(x, y, x + 40, y + 40, lineSemantics); - // count++; - // } - // } - } - - // Handle any other graphics added by client. - LinkGraphic.write(clientCreatedGraphics, link); - - gr.end(Link.END_SECTION); - - System.out.println("TestLinkServer: Wrote " + count - + " graphics to output stream"); - - int des = LinkUtil.setMask(0, MOUSE_CLICKED_MASK); - // des = LinkUtil.setMask(des, MOUSE_MOVED_MASK); - des = LinkUtil.unsetMask(des, SERVER_NOTIFICATION_MASK); - new LinkActionRequest(link, des, Link.END_TOTAL); - System.out.println("TestLinkServer: Wrote gesture descriptor to output stream"); - - } - - /** - * An example of how to handle LinkActionRequest. - * - * @param glq the LinkActionRequest, so you can get more - * information about the parameters of the gesture frome - * the client. - * @param link the link to communicate the response back to the - * client. - */ - public void handleGesture(LinkActionRequest glq, Link link) - throws IOException { - -// int descriptor = glq.getDescriptor(); - - LinkProperties props = new LinkProperties(); - props.setProperty(LPC_INFO, ("Mouse Clicked at: x = " + glq.getX() - + ", y = " + glq.getY())); - LinkActionList glr = new LinkActionList(link, props); - String gid = glq.getGraphicID(); - if (gid == null) { - System.out.println("Deselecting graphic"); - glr.deselectGraphics(); - } else { - System.out.println("Selecting graphic"); - props.clear(); - props.setProperty(LPC_GRAPHICID, gid); - glr.modifyGraphic(MODIFY_SELECT_GRAPHIC_MASK, props); - } - - glr.end(Link.END_TOTAL); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/TestServerStarter.java b/src/core/src/main/java/com/bbn/openmap/layer/link/TestServerStarter.java deleted file mode 100644 index e334d7122..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/TestServerStarter.java +++ /dev/null @@ -1,87 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/TestServerStarter.java,v $ -// $RCSfile: TestServerStarter.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:57 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link; - -import java.net.Socket; - -/** - * The LinkServerStarter is the object that listens for Link clients - * on a specific port. If a Link client contacts it, it uses the - * LinkServerFactory to create a LinkServer to serve the client on - * it's own thread. If you want to create a new type of LinkServer, - * you should also create a new LinkServerStarter to launch it - * properly. Generally, the main() is the only thing youwould need to - * modify, to change the type of LinkServerFactory (and therefore, the - * LinkServer) used for the client. - */ -public class TestServerStarter extends LinkServerStarter { - - /** Starts the LinkServerStarter listening to the specified port. */ - public TestServerStarter(int port) { - super(port); - } - - /** - * From the LinkServerFactory interface, starts up a new - * LinkServer to handle a client. - * - * @param socket socket to use to communicate to the client. - */ - public Thread startNewServer(Socket socket) { - return (new TestLinkServer(socket)); - } - - /** - * Start up the server. This is the method to change if you want - * to customize how the LinkServer will handle clients - port, - * arguments, LinkServerFactory, etc. - */ - public static void main(String[] argv) { - int pnumber = -1; - - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-port") && argv.length > i + 1) { - try { - pnumber = Integer.parseInt(argv[i + 1]); - break; - } catch (NumberFormatException e) { - pnumber = -1; - } - } - } - - if (pnumber < 0) { - System.out.println("Need to start the server with a port number."); - System.out.println("Usage: java com.bbn.openmap.layer.link.TestServerStarter -port "); - System.exit(0); - } - - System.out.println("TestServerStarter: Starting up on port " + pnumber - + "."); - - TestServerStarter serverStarter = new TestServerStarter(pnumber); - while (true) { - serverStarter.run(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/package.html b/src/core/src/main/java/com/bbn/openmap/layer/link/package.html deleted file mode 100644 index 2e105e0fa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/package.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide classes to handle the link protocol: a layer that displays - link data, classes to assist in writing a link server, and methods - that read and write in the link protocol format. Documentation for - the link protocol can be found - on our website, - or in the OpenMap source code at - com/bbn/openmap/layer/link/LinkProtocol.html. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPointRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPointRecord.java deleted file mode 100644 index 8fd2e2eec..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPointRecord.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/ESRILinkPointRecord.java,v $ -// $RCSfile: ESRILinkPointRecord.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:58 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.io.IOException; - -import com.bbn.openmap.layer.link.LinkGraphicList; -import com.bbn.openmap.layer.link.LinkProperties; -import com.bbn.openmap.layer.shape.ESRIPointRecord; - -/** - * An ESRI Point record. - * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.4 $ $Date: 2004/10/14 18:05:58 $ - */ -public class ESRILinkPointRecord extends ESRIPointRecord implements - ESRILinkRecord { - - /** - * Initializes this point from the given point. - * - * @param x the x coordinate - * @param y the y coordinate - */ - public ESRILinkPointRecord(double x, double y) { - super(x, y); - } - - /** - * Initialize a point record from the given buffer. - * - * @param b the buffer - * @param off the offset into the buffer where the data starts - */ - public ESRILinkPointRecord(byte b[], int off) throws IOException { - super(b, off); - } - - /** - * Generates OMGraphics and adds them to the given list. - * - * @param lgl the graphics response to write the point to. - * @param properties the semantic description of how the point - * should be drawn. - */ - public void writeLinkGraphics(LinkGraphicList lgl, LinkProperties properties) - throws IOException { - lgl.addRectangle((float) y, (float) x, -1, -1, 1, 1, properties); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPolygonRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPolygonRecord.java deleted file mode 100644 index d82cfa04f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkPolygonRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/ESRILinkPolygonRecord.java,v $ -// $RCSfile: ESRILinkPolygonRecord.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:09:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.io.IOException; - -import com.bbn.openmap.layer.link.LinkGraphicList; -import com.bbn.openmap.layer.link.LinkProperties; -import com.bbn.openmap.layer.shape.ESRIPoly; -import com.bbn.openmap.layer.shape.ESRIPolygonRecord; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - */ -public class ESRILinkPolygonRecord extends ESRIPolygonRecord implements - ESRILinkRecord { - - public ESRILinkPolygonRecord() { - super(); - } - - public ESRILinkPolygonRecord(byte b[], int off) throws IOException { - super(b, off); - } - - /** - * Generates OMGraphics and adds them to the given list. - *

- * Copy the poly points array because the OMPoly converts from - * degrees to radians in place, trashing the shape. - * - * @param lgl the graphics response to write the graphic to. - * @param properties the semantic description of how the graphic - * should be drawn. - */ - public void writeLinkGraphics(LinkGraphicList lgl, LinkProperties properties) - throws IOException { - int nPolys = polygons.length; - if (nPolys <= 0) - return; - - for (int i = 0; i < nPolys; i++) { - // these points are already in RADIAN lat,lon order!... - lgl.addPoly(((ESRIPoly.ESRIFloatPoly) polygons[i]).getRadians(), - OMGraphic.RADIANS, - OMGraphic.LINETYPE_STRAIGHT, - properties); - - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkRecord.java deleted file mode 100644 index a7a6f2606..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ESRILinkRecord.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/ESRILinkRecord.java,v $ -// $RCSfile: ESRILinkRecord.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:58 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.io.IOException; - -import com.bbn.openmap.layer.link.LinkGraphicList; -import com.bbn.openmap.layer.link.LinkProperties; - -/** - */ -public interface ESRILinkRecord { - - /** - * Writes the record to the given list. - *

- * Copy the poly points array because the OMPoly converts from - * degrees to radians in place, trashing the shape. - * - * @param lgl the graphics response of the link to write the - * object to. - * @param properties the properties of the polys - */ - public void writeLinkGraphics(LinkGraphicList lgl, LinkProperties properties) - throws IOException; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/LinkSpatialIndex.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/LinkSpatialIndex.java deleted file mode 100644 index 17a5ef7ec..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/LinkSpatialIndex.java +++ /dev/null @@ -1,75 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/LinkSpatialIndex.java,v $ -// $RCSfile: LinkSpatialIndex.java,v $ -// $Revision: 1.4 $ -// $Date: 2008/07/20 05:46:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.io.IOException; - -import com.bbn.openmap.layer.shape.ESRIRecord; -import com.bbn.openmap.layer.shape.SpatialIndex; - -/** - */ -public class LinkSpatialIndex extends SpatialIndex { - - /** - * Opens a spatial index file for the given shp file. - * - * @param shpFilename the name of the shape file to base index file search off of. - * @exception IOException if something goes wrong opening the file - */ - public LinkSpatialIndex(String shpFilename) throws IOException { - super(shpFilename); - } - - /** - * Creates a record instance from the shape file data. Calls the - * appropriate record constructor based on the shapeType, and - * passes the buffer and offset to that constructor. - * - * @param shapeType the shape file's shape type, enumerated in - * ShapeUtils - * @param b the buffer pointing to the raw record data - * @param off the offset of the data starting point in the buffer - * @exception IOException if something goes wrong reading the file - * @see com.bbn.openmap.dataAccess.shape.ShapeUtils - */ - public ESRIRecord makeESRIRecord(int shapeType, byte[] b, int off) - throws IOException { - switch (shapeType) { - case SHAPE_TYPE_NULL: - return null; - case SHAPE_TYPE_POINT: - return new ESRILinkPointRecord(b, off); - case SHAPE_TYPE_POLYGON: - case SHAPE_TYPE_ARC: - // case SHAPE_TYPE_POLYLINE: - return new ESRILinkPolygonRecord(b, off); - case SHAPE_TYPE_MULTIPOINT: - System.out.println("SpatialIndex.makeESRIRecord: Arc NYI"); - return null; - // return new ESRIMultipointRecord(b, off); - default: - return null; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeLinkServer.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeLinkServer.java deleted file mode 100644 index b8057b993..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeLinkServer.java +++ /dev/null @@ -1,285 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/ShapeLinkServer.java,v $ -// $RCSfile: ShapeLinkServer.java,v $ -// $Revision: 1.6 $ -// $Date: 2008/07/20 05:46:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.net.Socket; -import java.util.List; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.layer.link.Link; -import com.bbn.openmap.layer.link.LinkBoundingPoly; -import com.bbn.openmap.layer.link.LinkGraphicList; -import com.bbn.openmap.layer.link.LinkMapRequest; -import com.bbn.openmap.layer.link.LinkProperties; -import com.bbn.openmap.layer.link.LinkPropertiesConstants; -import com.bbn.openmap.layer.link.LinkServer; -import com.bbn.openmap.layer.shape.ESRIRecord; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; - -/** - * This LinkServer provides graphics from ShapeFiles. The LinkLayer can provide - * several properties that can control how these graphics are to be rendered - * (defined in the .propertiesURL file for the layer): - *

- * - *

- *   
- *    
- *    # Graphic edge color
- *    lineColor=AARRGGBB
- *    # Graphic fill Color
- *    fillColor=AARRGGBB
- *    # Graphic selected edge color
- *    highlightColor=AARRGGBB
- *    # Graphic edge pixel width
- *    lineWidth=pixel width
- *    
- *    
- * 
- */ -public class ShapeLinkServer extends LinkServer implements - LinkPropertiesConstants { - - protected LinkSpatialIndex spatialIndex; - - /** The color to outline the shapes. */ - protected Color lineColor = Color.black; - - /** The color to fill the shapes. */ - protected Color fillColor = ColorFactory.createColor(0, 0, 0, 0, true); - - protected LinkProperties lineProperties; - - public ShapeLinkServer(Socket socket, String shapeFile) { - super(socket); - locateAndSetShapeData(shapeFile); - } - - protected void finalize() { - if (Debug.debugging("gc")) { - Debug.output("ShapeLinkServer instance gc'd - client gone"); - } - } - - /** - * handleClient is a method that listens to the link to a client, and - * responds to requests that are made. - */ - public void handleClient() throws IOException { - boolean validQuery; - try { - - while (true) { - if (Debug.debugging("shape")) { - link.clearBytesWritten(); - } - - link.readAndParse(); - validQuery = false; - - // For instance, you could do something like this... - - LinkMapRequest graphicsQuery = link.getMapRequest(); - // LinkActionRequest gestureQuery = - // link.getActionRequest(); - - if (graphicsQuery != null) { - getRectangle(graphicsQuery, link); - validQuery = true; - } - graphicsQuery = null; - - // if (gestureQuery != null){ - // handleGesture(gestureQuery, link); - // validQuery = true; - // } - - if (!validQuery) { - huh(link); - } - - if (Debug.debugging("shape")) { - System.out.println("ShapeLinkServer: bytes written for response: " - + link.getBytesWritten()); - } - } - - } catch (IOException ioe) { - spatialIndex = null; - lineColor = null; - fillColor = null; - lineProperties = null; - throw ioe; - } - } - - public void setFillColor(Color fColor) { - fillColor = fColor; - } - - public void setLineColor(Color lColor) { - lineColor = lColor; - } - - public Color getFillColor() { - return fillColor; - } - - public Color getLineColor() { - return lineColor; - } - - public void getRectangle(LinkMapRequest query, Link link) - throws IOException { - // String value; - - if (spatialIndex == null) - link.end(Link.END_TOTAL); - - LinkProperties args = query.getProperties(); - LinkGraphicList lgl = new LinkGraphicList(link, args); - // System.out.println(args); - lineProperties = new LinkProperties(); - // Tell the LinkProperties to reuse what has shown up previously, which - // will be set in the LinkGraphicList. - lineProperties.setReuseProperties(Boolean.TRUE); - - // value = args.getProperty(LPC_LINECOLOR); - // if (value != null) - // lineProperties.setProperty(LPC_LINECOLOR, value); - // value = args.getProperty(LPC_FILLCOLOR); - // if (value != null) - // lineProperties.setProperty(LPC_FILLCOLOR, value); - // value = args.getProperty(LPC_HIGHLIGHTCOLOR); - // if (value != null) - // lineProperties.setProperty(LPC_HIGHLIGHTCOLOR, value); - // value = args.getProperty(LPC_LINEWIDTH); - // if (value != null) - // lineProperties.setProperty(LPC_LINEWIDTH, value); - - LinkBoundingPoly[] bounds = query.getBoundingPolys(); - - for (int i = 0; i < bounds.length; i++) { - fetchGraphics((double) bounds[i].minX, - (double) bounds[i].minY, - (double) bounds[i].maxX, - (double) bounds[i].maxY, - lgl, - lineProperties); - } - - lgl.end(Link.END_TOTAL); - } - - /** - * - */ - protected void fetchGraphics(double xmin, double ymin, double xmax, - double ymax, LinkGraphicList lgl, - LinkProperties properties) throws IOException { - - Debug.message("shape", "fetchGraphics: " + xmin + ", " + ymin + ", " - + xmax + ", " + ymax); - - try { - ESRIRecord records[] = spatialIndex.locateRecords(xmin, - ymin, - xmax, - ymax); - int nRecords = records.length; - ESRILinkRecord rec; - for (int i = 0; i < nRecords; i++) { - if (records[i] instanceof ESRILinkRecord) { - rec = (ESRILinkRecord) records[i]; - rec.writeLinkGraphics(lgl, properties); - } - } - } catch (java.io.IOException ex) { - if (Debug.debugging("shape")) { - ex.printStackTrace(); - } - return; - } catch (com.bbn.openmap.io.FormatException fe) { - Debug.error("ShapeLinkServer caught FormatException in the file"); - fe.printStackTrace(); - } - } - - protected void locateAndSetShapeData(String shapeFileName) { - Debug.message("shape", "ShapeLinkServer: Reading shape file."); - - String spatialIndexFileName = shapeFileName.substring(0, - shapeFileName.indexOf(".shp")) - + ".ssx"; - - - File spatialIndexFile = new File(spatialIndexFileName); - - if (spatialIndexFile.isAbsolute()) { - // System.out.println("Absolute!"); - try { - spatialIndex = new LinkSpatialIndex(shapeFileName); - } catch (java.io.IOException e) { - if (Debug.debugging("shape")) { - e.printStackTrace(); - } - } - } else { - // System.out.println("Relative!"); - List dirs = Environment.getClasspathDirs(); - int nDirs = dirs.size(); - if (nDirs > 0) { - for (String dir : dirs) { - File sif = new File(dir, spatialIndexFileName); - if (sif.isFile()) { - File sf = new File(dir, shapeFileName); - try { - // System.out.println(sif.toString()); - // System.out.println(sf.toString()); - spatialIndex = new LinkSpatialIndex(sf.toString()); - break; - } catch (java.io.IOException e) { - if (Debug.debugging("shape")) { - e.printStackTrace(); - } - } - } - } - if (spatialIndex == null) { - System.err.println("Unable to find file: " + shapeFileName); - System.err.println("Unable to find file: " - + spatialIndexFileName); - } - } else { - System.err.println("No directories in CLASSPATH!"); - System.err.println("Unable to locate file: " + shapeFileName); - System.err.println("Unable to locate file: " - + spatialIndexFileName); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeServerStarter.java b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeServerStarter.java deleted file mode 100644 index 95b2a8f76..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/ShapeServerStarter.java +++ /dev/null @@ -1,89 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/shape/ShapeServerStarter.java,v $ -// $RCSfile: ShapeServerStarter.java,v $ -// $Revision: 1.4 $ -// $Date: 2008/07/20 05:46:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.shape; - -import java.net.Socket; -import java.util.Properties; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.layer.link.LinkServerStarter; -import com.bbn.openmap.util.Debug; - -/** - * This class starts ShapeLinkServers on a per-client basis. A usage - * statement is printed out if you run this class without arguments. - */ -public class ShapeServerStarter extends LinkServerStarter { - - protected String shapeFile; - - public ShapeServerStarter(int port, String shapeFile, String shapeIndex) { - this(port, shapeFile); - } - - public ShapeServerStarter(int port, String shapeFile) { - super(port); - this.shapeFile = shapeFile; - } - - public Thread startNewServer(Socket sock) { - return (new ShapeLinkServer(sock, shapeFile)); - } - - public static void main(String[] argv) { - Properties p = System.getProperties(); - // First initialize debugging - Debug.init(p); - Environment.init(p); - - int pnumber = -1; - String shp = null; - for (int i = 0; i < argv.length; i++) { - if (argv[i].equals("-port") && argv.length > i + 1) { - try { - pnumber = Integer.parseInt(argv[i + 1]); - break; - } catch (NumberFormatException e) { - pnumber = -1; - } - } else if (argv[i].indexOf(".shp") != -1 - || argv[i].indexOf(".SHP") != -1) { - shp = argv[i]; - } - } - - if (pnumber < 0 || shp == null) { - System.out.println("Need to start the server with a port number and shape file."); - System.err.println("Usage: java com.bbn.openmap.layer.link.shape.ShapeServerStarter -port "); - System.exit(-1); - } - - System.out.println("ShapeServerStarter: Starting up on port " + pnumber - + "."); - ShapeServerStarter serverStarter = new ShapeServerStarter(pnumber, shp); - - while (true) { - serverStarter.run(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/package.html b/src/core/src/main/java/com/bbn/openmap/layer/link/shape/package.html deleted file mode 100644 index b67e6a48f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/link/shape/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -A link server that reads ESRI shape file data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/AbstractLocationHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/AbstractLocationHandler.java deleted file mode 100644 index c7768656b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/AbstractLocationHandler.java +++ /dev/null @@ -1,395 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/AbstractLocationHandler.java,v $ -// $Revision: 1.10 $ $Date: 2006/02/13 16:54:18 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Logger; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.PropUtils; - -/** - * The AbstractLocationHandler class facilitates the implementation of - * a LocationHandler by implementing a number of methods. By - * extending this class, a developer need only implement get(), setProperties(), - * and reloadData(). - * - *
- * 
- *     locationhandler.location.lineColor=FF0000
- *     locationhandler.name.lineColor=008C54
- *     locationhandler.showNames=false
- *     locationhandler.showLocations=true
- *     locationhandler.override=true
- *     
- *     # optional, can be used if you override createLocation and need access to varying rendering attributes.
- *     # ra1, ra2 and ra3 would be used as keys in renderAttributes map.  All GraphicAttributes properties are available, not
- *     # just lineColor.
- *     
- *     locationhandler.renderAttributesList=ra1 ra2 ra3
- *     locationhandler.ra1.lineColor=0xFFFF0000
- *     locationhandler.ra2.lineColor=0xFF00FF00
- *     locationhandler.ra3.lineColor=0xFF00FFFF
- * 
- * 
- * - * @see com.bbn.openmap.layer.location.LocationHandler - * @version $Revision: 1.10 $ $Date: 2006/02/13 16:54:18 $ - * @author Michael E. Los D530/23448 - */ -public abstract class AbstractLocationHandler extends OMComponent implements LocationHandler { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.location.LocationHandler"); - - /** The parent layer. */ - protected LocationLayer zLayer; - - /** The default setting for the labels at startup. */ - private boolean showNames = false; - /** The rendering attributes for the names. */ - /** The default setting for the locations at startup. */ - private boolean showLocations = true; - - /** - * Property for properties to populate the renderAttributes HashMap. The - * property should contain a space separated list of keys that will be then - * used as a prefix for the properties and key for the Map. - */ - public final static String RenderAttributesListProperty = "renderAttributesList"; - - /** - * Map that holds rendering attribute objects, under a key. The "name" and - * "location" DrawingAttributes are stored here by default. - */ - Map renderAttributes = new HashMap(); - - /** - * Force global settings to override local Location settings for - * showLocation and showName. - */ - private boolean forceGlobal = true; - - private String prettyName = ""; - - protected AbstractLocationHandler() { - GraphicAttributes nAttributes = new GraphicAttributes(); - nAttributes.setRenderType(OMGraphic.RENDERTYPE_LATLON); - renderAttributes.put(NamePropertyPrefix, nAttributes); - - GraphicAttributes lAttributes = new GraphicAttributes(); - lAttributes.setRenderType(OMGraphic.RENDERTYPE_LATLON); - renderAttributes.put(LocationPropertyPrefix, lAttributes); - } - - /** - * Set the layer the handler is responding to. This is needed in case the - * handler has updates that it wants to show, and needs to trigger a - * repaint. It can also be used to communicate with the information - * delegator. - * - * @param l a LocationLayer - */ - public void setLayer(LocationLayer l) { - zLayer = l; - } - - /** Get the layer the handler is serving. */ - public LocationLayer getLayer() { - return zLayer; - } - - /** - * See if the handler is displaying labels at a global level. - */ - public boolean isShowNames() { - return showNames; - } - - /** - * Set the handler to show/hide labels at a global level. - */ - public void setShowNames(boolean set) { - showNames = set; - } - - /** - * See if the handler is displaying location graphics at a global level. - */ - public boolean isShowLocations() { - return showLocations; - } - - /** - * Set the handler to show/hide location graphics at a global level. - */ - public void setShowLocations(boolean set) { - showLocations = set; - } - - /** - * Find out whether global settings should override local ones. - */ - public boolean isForceGlobal() { - return forceGlobal; - } - - /** - * Set whether global settings should override local ones. - */ - public void setForceGlobal(boolean set) { - forceGlobal = set; - } - - /** - * Set the color used for the name label. - */ - public void setNameColor(Color nColor) { - renderAttributes.get(NamePropertyPrefix).setLinePaint(nColor); - } - - /** - * Get the color used for the name label. - */ - public Color getNameColor() { - return (Color) renderAttributes.get(NamePropertyPrefix).getLinePaint(); - } - - /** - * Set the color used for the location graphic. - */ - public void setLocationColor(Color lColor) { - renderAttributes.get(LocationPropertyPrefix).setLinePaint(lColor); - } - - /** - * Get the color used for the location graphic. - */ - public Color getLocationColor() { - return (Color) renderAttributes.get(LocationPropertyPrefix).getLinePaint(); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.location.LocationHandler#getItemsForPopupMenu(com - * .bbn.openmap.layer.location.Location) - */ - public List getItemsForPopupMenu(Location loc) { - return null; - } - - /** - * Called by the LocationLayer when the layer is removed from the map. The - * LocationHandler should release expensive resources if this is called. - */ - public void removed(java.awt.Container cont) { - } - - /** - * Sets the properties for the handler. This particular method assumes that - * the marker name is not needed, because all of the contents of this - * Properties object are to be used for this object, and scoping the - * properties with a prefix is unnecessary. - * - * @param props the Properties object. - */ - public void setProperties(Properties props) { - setProperties(null, props); - } - - /** - * Set up the properties of the handler. Part of the PropertyConsumer - * interface. - * - * Supported properties include: - *
    - *
  • locationColor - number of seconds between attempts to retrieve - * Features data - *
  • featuresSvcURL - URL to invoke to retrieve the XML Features document - *
- */ - public void setProperties(String prefix, Properties properties) { - propertyPrefix = prefix; - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - showLocations = PropUtils.booleanFromProperties(properties, prefix + ShowLocationsProperty, showLocations); - showNames = PropUtils.booleanFromProperties(properties, prefix + ShowNamesProperty, showNames); - - renderAttributes.get(NamePropertyPrefix).setProperties(prefix + NamePropertyPrefix, properties); - renderAttributes.get(LocationPropertyPrefix).setProperties(prefix + LocationPropertyPrefix, properties); - - forceGlobal = PropUtils.booleanFromProperties(properties, prefix + ForceGlobalProperty, forceGlobal); - setPrettyName(properties.getProperty(prefix + Layer.PrettyNameProperty, getPrettyName())); - - List renAttKeys = PropUtils.parseSpacedMarkers(properties.getProperty(prefix - + RenderAttributesListProperty)); - if (renAttKeys != null) { - for (String renAttKey : renAttKeys) { - String key = prefix + renAttKey; - renderAttributes.put(key, new GraphicAttributes(key, properties)); - } - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. This method takes care of - * the basic LocationHandler parameters, so any LocationHandlers that extend - * the AbstractLocationHandler should call this method, too, before adding - * any specific properties. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ShowNamesProperty, new Boolean(showNames).toString()); - props.put(prefix + ShowLocationsProperty, new Boolean(showLocations).toString()); - props.put(prefix + ForceGlobalProperty, new Boolean(forceGlobal).toString()); - props.put(prefix + Layer.PrettyNameProperty, getPrettyName()); - - StringBuilder renAttList = new StringBuilder(); - for (String key : renderAttributes.keySet()) { - // Only create a list if more than name/location in the list - if (!key.equals(NamePropertyPrefix) && !key.equals(LocationPropertyPrefix)) { - renAttList.append(key).append(" "); - } - // But still put name/location attributes in properties. - GraphicAttributes ga = renderAttributes.get(key); - ga.getProperties(props); - } - if (renAttList.length() > 0) { - props.put(prefix + RenderAttributesListProperty, renAttList.toString()); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - PropUtils.setI18NPropertyInfo(i18n, list, AbstractLocationHandler.class, ShowNamesProperty, "Show names", "Display all the location name labels.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, AbstractLocationHandler.class, ShowLocationsProperty, "Show locations", "Display all the location markers.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, AbstractLocationHandler.class, ForceGlobalProperty, "Layer Override", "Layer settings override map object settings.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, AbstractLocationHandler.class, Layer.PrettyNameProperty, "Pretty Name", "Name for Data Set.", null); - - renderAttributes.get(NamePropertyPrefix).getPropertyInfo(list); - renderAttributes.get(LocationPropertyPrefix).getPropertyInfo(list); - - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - public GraphicAttributes getLocationDrawingAttributes() { - return renderAttributes.get(LocationPropertyPrefix); - } - - public void setLocationDrawingAttributes(GraphicAttributes lda) { - renderAttributes.put(LocationPropertyPrefix, lda); - } - - public GraphicAttributes getNameDrawingAttributes() { - return renderAttributes.get(NamePropertyPrefix); - } - - public void setNameDrawingAttributes(GraphicAttributes nda) { - renderAttributes.put(NamePropertyPrefix, nda); - } - - /** - * Set the name used in the GUI to represent this data set. - * - * @param prettyName A GUI pretty name. - */ - public void setPrettyName(String prettyName) { - this.prettyName = prettyName; - } - - /** - * Get the GUI pretty name for the data set retrieved by this - * LocationHandler. - * - * @return pretty name for location handler, for GUI use. - */ - public String getPrettyName() { - return prettyName; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocation.java b/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocation.java deleted file mode 100644 index 282a2b8b2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocation.java +++ /dev/null @@ -1,123 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/BasicLocation.java,v $ -// $RCSfile: BasicLocation.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* OpenMap */ -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRect; - -/** - * A BasicLocation the standard Location - dot for the marker, text to the right - * of the dot. Other graphics can be substituted for the dot, but you should - * modify the setGraphicLocations methods accordingly. - */ -public class BasicLocation - extends Location { - - /** - * A plain constructor if you are planning on setting everything yourself. - */ - public BasicLocation() { - } - - /** - * Create a location at a latitude/longitude. If the locationMarker is null, - * a small rectangle (dot) will be created to mark the location. - * - * @param latitude the latitude, in decimal degrees, of the location. - * @param longitude the longitude, in decimal degrees, of the location. - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public BasicLocation(double latitude, double longitude, String name, OMGraphic locationMarker) { - super(latitude, longitude, name, locationMarker); - } - - /** - * Create a location at a map location. If the locationMarker is null, a - * small rectangle (dot) will be created to mark the location. - * - * @param x the pixel location of the object from the let of the map. - * @param y the pixel location of the object from the top of the map - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public BasicLocation(int x, int y, String name, OMGraphic locationMarker) { - super(x, y, name, locationMarker); - } - - /** - * Create a location at a pixel offset from a latitude/longitude. If the - * locationMarker is null, a small rectangle (dot) will be created to mark - * the location. - * - * @param latitude the latitude, in decimal degrees, of the location. - * @param longitude the longitude, in decimal degrees, of the location. - * @param xOffset the pixel location of the object from the longitude. - * @param yOffset the pixel location of the object from the latitude. - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public BasicLocation(double latitude, double longitude, int xOffset, int yOffset, String name, OMGraphic locationMarker) { - super(latitude, longitude, xOffset, yOffset, name, locationMarker); - } - - /** - * Called by setLocations(). Assumes the dot for the location marker, and a - * text object as the label, stored to the right. - */ - public void setGraphicLocations(double latitude, double longitude) { - if (location instanceof OMRect) { - ((OMRect) location).setLocation(latitude, longitude, -1, -1, 1, 1); - } - label.setLat(latitude); - label.setLon(longitude); - } - - /** - * Called by setLocations(). Assumes the dot for the location marker, and a - * text object as the label, stored to the right. - */ - public void setGraphicLocations(int x, int y) { - if (location instanceof OMRect) { - ((OMRect) location).setLocation(x - 1, y - 1, x + 1, y + 1); - } - label.setX(x); - label.setY(y); - } - - /** - * Called by setLocations(). Assumes the dot for the location marker, and a - * text object as the label, stored to the right. - */ - public void setGraphicLocations(double latitude, double longitude, int offsetX, int offsetY) { - if (location instanceof OMRect) { - ((OMRect) location).setLocation(latitude, longitude, offsetX - 1, offsetY - 1, offsetX + 1, offsetY + 1); - } - - label.setLat(latitude); - label.setLon(longitude); - label.setX(offsetX); - label.setY(offsetY); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocationHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocationHandler.java deleted file mode 100644 index 8a698cd95..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/BasicLocationHandler.java +++ /dev/null @@ -1,166 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/BasicLocationHandler.java,v $ -// $RCSfile: BasicLocationHandler.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:05:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.logging.Level; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; - -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * A basic location handler, that just returns simple testing locations. - */ -public class BasicLocationHandler extends AbstractLocationHandler { - - protected final OMGraphicList graphicList = new OMGraphicList(); - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public BasicLocationHandler() { - reloadData(); - } - - public void reloadData() { - Color[] colors = new Color[8]; - colors[0] = Color.red; - colors[1] = Color.green; - colors[2] = Color.yellow; - colors[3] = Color.blue; - colors[4] = Color.black; - colors[5] = Color.white; - colors[6] = Color.orange; - colors[7] = Color.pink; - - graphicList.clear(); - - for (int i = 0; i < 10; i++) { - // Sprinkle some randomness in the values - double ran = Math.random() * 10; - boolean dir = Math.random() > .5; - if (!dir) { - ran *= -1; - } - - Location location = new BasicLocation(42f + ran, -72f + ran, "testing" + i, null); - location.setLocationHandler(this); - location.getLabel().setLinePaint(colors[i % 8]); - // location.getLabel().setShowBounds(true); - location.setShowName(true); - location.setShowLocation(true); - graphicList.add(location); - } - } - - /** - * Called by the LocationLayer when the layer is removed from the map. The - * LocationHandler should release expensive resources if this is called. - */ - public void removed(java.awt.Container cont) { - } - - public OMGraphicList get(double nwLat, double nwLon, double seLat, double seLon, - OMGraphicList graphicList) { - graphicList.addAll(this.graphicList); - return graphicList; - } - - protected Box box = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public Component getGUI() { - if (box == null) { - JCheckBox showLocationCheck, showNameCheck; - JButton rereadFilesButton; - - showLocationCheck = new JCheckBox("Show Locations", isShowLocations()); - showLocationCheck.setActionCommand(showLocationsCommand); - showLocationCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox locationCheck = (JCheckBox) ae.getSource(); - setShowLocations(locationCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler::actionPerformed showLocations is " - + isShowLocations()); - } - getLayer().repaint(); - } - }); - showLocationCheck.setToolTipText("Show location markers on the map."); - - showNameCheck = new JCheckBox("Show Location Names", isShowNames()); - showNameCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox namesCheck = (JCheckBox) ae.getSource(); - setShowNames(namesCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler::actionPerformed showNames is " - + isShowNames()); - } - - LocationLayer ll = getLayer(); - if (namesCheck.isSelected() && ll.getDeclutterMatrix() != null - && ll.getUseDeclutterMatrix()) { - ll.doPrepare(); - } else { - ll.repaint(); - } - } - }); - showNameCheck.setToolTipText("Show location names on the map."); - - rereadFilesButton = new JButton("Reload Data From Source"); - rereadFilesButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Re-reading Locations file"); - } - reloadData(); - getLayer().doPrepare(); - } - }); - rereadFilesButton.setToolTipText("Reload the data file, and put these settings
on the individual map objects."); - - box = Box.createVerticalBox(); - box.add(showLocationCheck); - box.add(showNameCheck); - box.add(rereadFilesButton); - } - return box; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/ByteRasterLocation.java b/src/core/src/main/java/com/bbn/openmap/layer/location/ByteRasterLocation.java deleted file mode 100644 index 6d195bfe0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/ByteRasterLocation.java +++ /dev/null @@ -1,260 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/ByteRasterLocation.java,v $ -// $RCSfile: ByteRasterLocation.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.Point; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.layer.DeclutterMatrix; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.proj.Projection; - -/** - * A Location that takes a byte array and creates a Raster for a Location - * marker. The byte array should be the contents of an image file (gif, jpeg) - * that an ImageIcon object can use to create an Image object. - */ -public class ByteRasterLocation - extends Location { - /** The spacing between the label and the outside of the image. */ - public int SPACING = 0; - - /** - * Create a ByteRasterLocation at a latitude/longitude location. - * - * @param latitude latitide in decimal degrees - * @param longitude longitude in decimal degrees. - * @param name the label for the location. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public ByteRasterLocation(double latitude, double longitude, String name, byte bytearr[]) { - super(latitude, longitude, name, getIconRaster(latitude, longitude, bytearr)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - - } - - /** - * Create a ByteRasterLocation at a screen x/y location. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param name the label for the location. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public ByteRasterLocation(int x, int y, String name, byte bytearr[]) { - super(x, y, name, getIconRaster(x, y, bytearr)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create a ByteRasterLocation at a screen x/y location. - * - * @param latitude latitide in decimal degrees - * @param longitude longitude in decimal degrees. - * @param xOffset horizontal pixel screen location from the longitude map - * point. - * @param yOffset vertical pixel screen location, from the latitide map - * point. - * @param name the label for the location. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public ByteRasterLocation(double latitude, double longitude, int xOffset, int yOffset, String name, byte bytearr[]) { - super(latitude, longitude, xOffset, yOffset, name, getIconRaster(latitude, longitude, xOffset, yOffset, bytearr)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create an OMRaster at a latitude/longitude, from a image byte array. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public static OMRaster getIconRaster(double lat, double lon, byte bytearr[]) { - - ImageIcon icon = getIconRaster(bytearr); - if (icon == null) - return null; - - int offX = icon.getIconWidth() / 2; - int offY = icon.getIconHeight() / 2; - return new OMRaster(lat, lon, -offX, -offY, icon); - } - - /** - * Create a x/y OMRaster with an image byte array. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public static OMRaster getIconRaster(int x, int y, byte bytearr[]) { - ImageIcon icon = getIconRaster(bytearr); - if (icon == null) - return null; - - int offX = icon.getIconWidth() / 2; - int offY = icon.getIconHeight() / 2; - return new OMRaster(x - offX, y - offY, icon); - } - - /** - * Create a lat/lon OMRaster, pffset to a certain pixel location, with an - * image byte array. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param x horizontal pixel screen location from the longitude map point. - * @param y vertical pixel screen location, from the latitide map point. - * @param bytearr a byte array from an image file that an ImageIcon can use - * to create an Image icon. Can also be the binary contents of an - * image from a database query. - */ - public static OMRaster getIconRaster(double lat, double lon, int x, int y, byte bytearr[]) { - ImageIcon icon = getIconRaster(bytearr); - if (icon == null) - return null; - - int offX = icon.getIconWidth() / 2; - int offY = icon.getIconHeight() / 2; - return new OMRaster(lat, lon, x - offX, y - offY, icon); - } - - /** - * Create an ImageIcon from a byte array. The byte array should reflect the - * contents of a standard image file. - */ - public static ImageIcon getIconRaster(byte bytearr[]) { - if (bytearr == null) - return null; - ImageIcon icon = new ImageIcon(bytearr); - return icon; - } - - /** - * Given the label is this location has a height and width, find a clean - * place on the map for it. Assumes label is not null. - * - * @param declutter the DeclutterMatrix for the map. - */ - protected void declutterLabel(DeclutterMatrix declutter, Projection proj) { - - super.declutterLabel(declutter, proj); - - if (isShowLocation()) { - // Take up space with the label - if (location instanceof OMRasterObject) { - Point lp = ((OMRasterObject) location).getMapLocation(); - // This location is the upper left location of the - // declutter matrix. The declutter matrix works from - // lower left to upper right. - if (lp != null) { - int locHeight = ((OMRasterObject) location).getHeight(); - int locWidth = ((OMRasterObject) location).getWidth(); - // Need to get this right for the DeclutterMatrix - // space, but changing lp changes where the - // location will appear - fix this later. - lp.y += locHeight; - declutter.setTaken(lp, locWidth, locHeight); - // Reset it to the original projected location. - lp.y -= locHeight; - } - } - } - } - - /** - * Given a new latitude/longitude, reposition the graphic and label. - */ - public void setGraphicLocations(double latitude, double longitude) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setLat(latitude); - ras.setLon(longitude); - - label.setLat(latitude); - label.setLon(longitude); - setHorizontalLabelBuffer((ras.getWidth() / 2) + SPACING); - - } - } - - /** - * Given a new x/y screen location, reposition the graphic and label. - */ - public void setGraphicLocations(int x, int y) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setX(x); - ras.setY(y); - - label.setX(x); - label.setY(y); - setHorizontalLabelBuffer((ras.getWidth() / 2) + SPACING); - } - } - - /** - * Given a new latitude/longitude with x/y offset points, reposition the - * graphic and label. - */ - public void setGraphicLocations(double latitude, double longitude, int offsetX, int offsetY) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setLat(latitude); - ras.setLon(longitude); - ras.setX(offsetX); - ras.setY(offsetY); - - label.setLat(latitude); - label.setLon(longitude); - label.setX(offsetX); - label.setY(offsetY); - setHorizontalLabelBuffer((ras.getWidth() / 2) + SPACING); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/Link.java b/src/core/src/main/java/com/bbn/openmap/layer/location/Link.java deleted file mode 100644 index 30f1bd0a2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/Link.java +++ /dev/null @@ -1,198 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/Link.java,v $ -// $RCSfile: Link.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Paint; -import java.awt.Stroke; -import java.util.logging.Level; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMLine; - -/** - * A Link is a relationship between Locations, represented as a line between - * them. If you want to draw the endpoints, use a LocationHandler for them. - *

- * - * Although this class extends from Location, it doesn't handle displaying a - * name for the link that well. The name will appear as the first node's marker - * name, although it should declutter if needed. - */ -public class Link extends Location { - - /* - * The other endpoints of the link, in decimal degrees. The first endpoints - * are contained in the Location superclass. - */ - /** The lat of point 2. */ - public double lat2 = 0.0f; - /** The lon of point 2. */ - public double lon2 = 0.0f; - /** The x of point 2. */ - public int x2 = 0; - /** The y of point 2. */ - public int y2 = 0; - - // /** The x offset of point 2, never used. */ - // public int xOffset2 = 0; - // /** The y offset of point 2, never used. */ - // public int yOffset2 = 0; - - /** the default color is black */ - public static Color DEFAULT_COLOR = Color.black; - /** the default dash style - not dashed */ - public static boolean DEFAULT_DASHED = false; - /** the default line type - straight */ - public static int DEFAULT_LINETYPE = OMGraphic.LINETYPE_STRAIGHT; - /** the default line thickness - 1 */ - public static float DEFAULT_THICKNESS = 1.0f; - - /** - * A plain constructor if you are planning on setting everything yourself. - */ - public Link() { - } - - /** - * Construct a Link with the given attributes - * - * @param lat1 latitude of start-point - * @param lon1 longitude of start-point - * @param lat2 latitude of end-point - * @param lon2 longitude of endpoint - * @param details A string that gives information about this link - */ - public Link(double lat1, double lon1, double lat2, double lon2, String details) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Link(" + lat1 + ", " + lon1 + ", " + lat2 + ", " + lon2 + ", " + details - + ")"); - } - - this.lat = lat1; - this.lon = lon1; - this.lat2 = lat2; - this.lon2 = lon2; - - if (details != null) { - this.details = details; - } else { - this.details = ""; - } - - OMLine link = new OMLine(lat1, lon1, lat2, lon2, OMGraphic.LINETYPE_GREATCIRCLE); - setLocationMarker(link); - } - - /** - * Construct a Link with the given attribute - * - * @param x1 Starting x point of Link - * @param y1 Starting y point of Link - * @param x2 End x point of Link - * @param y2 End y point of Link - * @param details A string that gives information about this link - */ - public Link(int x1, int y1, int x2, int y2, String details) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Link(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")"); - } - - this.x = x1; - this.y = y1; - this.x2 = x2; - this.y2 = y2; - - if (details != null) { - this.details = details; - } else { - this.details = ""; - } - - OMLine link = new OMLine(x1, y1, x2, y2); - setLocationMarker(link); - } - - /** - * Set the location for the link - * - * @param lat1 the latitude of the first location - * @param lon1 the longitude of the first location - * @param lat2 the latitude of the second location - * @param lon2 the longitude of the second location - */ - public void setLocation(double lat1, double lon1, double lat2, double lon2) { - - this.lat = lat1; - this.lon = lon1; - this.lat2 = lat2; - this.lon2 = lon2; - - OMLine line = (OMLine) getLocationMarker(); - double[] locs = { lat1, lon1, lat2, lon2 }; - line.setLL(locs); - } - - /** - * Set new coordinates for this link. - * - * @param x1 the x coordinate of the first location - * @param y1 the y coordinate of the first location - * @param x2 the x coordinate of the second location - * @param y2 the y coordinate of the second location - */ - public void setLocation(int x1, int y1, int x2, int y2) { - - this.x = x1; - this.y = y1; - this.x2 = x2; - this.y2 = y2; - - int xy[] = new int[4]; - xy[0] = this.x = x1; - xy[1] = this.y = y1; - xy[2] = this.x2 = x2; - xy[3] = this.y2 = y2; - OMLine link = (OMLine) getLocationMarker(); - if (link instanceof OMLine) { - ((OMLine) link).setPts(xy); - ((OMLine) link).setRenderType(RENDERTYPE_XY); - } - } - - /** Does nothing - marker handled in setLocation methods. */ - public void setGraphicLocations(double latitude, double longitude) { - } - - /** Does nothing - marker handled in setLocation methods. */ - public void setGraphicLocations(int x, int y) { - } - - /** Does nothing - marker handled in setLocation methods. */ - public void setGraphicLocations(double latitude, double longitude, int offsetX, int offsetY) { - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/Location.java b/src/core/src/main/java/com/bbn/openmap/layer/location/Location.java deleted file mode 100644 index 63ea4b21b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/Location.java +++ /dev/null @@ -1,810 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/Location.java,v $ -// $RCSfile: Location.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.Graphics; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.geom.Point2D; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.layer.DeclutterMatrix; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicAdapter; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; - -/** - * A Location is a place. It can be thought of as a lat/lon place, with or - * without an pixel offset, or a place on the screen. A location is basically - * thought of as having a name, which get represented as a label, and some - * graphical representation. It is abstract because it doesn't really know what - * kind of markers or labels are being used or how they are being positioned - * around the particular point. Therefore, it should be extended, and the - * setGraphicLocations methods implemented to position the marker and text as - * desired. - *

- */ -public abstract class Location - extends OMGraphicAdapter { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.location.Location"); - - /** - * The main latitude of object, in decimal degrees, for RENDERTYPE_LATLON - * and RENDERTYPE_OFFSET locations. - */ - public double lat = 0.0f; - /** - * The main longitude of object, in decimal degrees, for RENDERTYPE_LATLON - * and RENDERTYPE_OFFSET locations. - */ - public double lon = 0.0f; - /** - * The x pixel offset from the longitude, for RENDERTYPE_OFFSET locations. - */ - public int xOffset = 0; - /** - * The y pixel offset from the latitude, for RENDERTYPE_OFFSET locations. - */ - public int yOffset = 0; - /** The x object location, in pixels, for RENDERTYPE_XY locations. */ - public int x = 0; - /** The y object location, in pixels, for RENDERTYPE_XY locations. */ - public int y = 0; - /** The name of the location. */ - public String name = null; - /** - * The LocationHandler that is handling the location. Need this to check for - * more global settings for rendering. - */ - public LocationHandler handler; - - public final static int DECLUTTER_LOCALLY = -1; - public final static int DECLUTTER_ANYWHERE = -2; - - /** The Label of the object. */ - protected OMText label = null; - /** The simple location marker of the object. */ - protected OMGraphic location = null; - /** The URL to display when the object is gestured upon. */ - protected String details = ""; - /** The flag for displaying the location marker. */ - protected boolean showLocation = true; - /** The flag for displaying the name label. */ - protected boolean showName = true; - /** - * The original offset/y location, kept for resetting the placement of the - * label after decluttering and/or location placement. - */ - public int origYLabelOffset = 0; - /** - * The original offset/x location, kept for resetting the placement of the - * label after decluttering and/or location placement. - */ - public int origXLabelOffset = 0; - /** - * the default distance away a label should be placed from a location - * marker. - */ - public final static int DEFAULT_SPACING = 6; - /** - * The pixel limit where the declutter matrix won't draw the name, if it - * can't put the name at least this close to the original place. - * DECLUTTER_LOCALLY keeps the limit to twice the height of the label. - * DECLUTTER_ANYWHERE will place the thing anywhere it fits. Anything else - * is the pixel limit. - */ - protected int declutterLimit = DECLUTTER_LOCALLY; - /** Set whether you want this location label decluttered. */ - protected boolean allowDecluttering = true; - /** - * The horizontal pixel distance you want to place the text away from the - * actual location - to put space between the graphic. - */ - protected int horizontalLabelBuffer = 0; - - /** - * A plain constructor if you are planning on setting everything yourself. - */ - public Location() { - } - - /** - * Create a location at a latitude/longitude. If the locationMarker is null, - * a small rectangle (dot) will be created to mark the location. - * - * @param latitude the latitude, in decimal degrees, of the location. - * @param longitude the longitude, in decimal degrees, of the location. - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public Location(double latitude, double longitude, String name, OMGraphic locationMarker) { - - setLocation(latitude, longitude); - this.name = name; - - if (logger.isLoggable(Level.FINER)) { - logger.finer("Location Lat/Lon(" + latitude + ", " + longitude + ", " + name + ")"); - } - - if (locationMarker == null) { - location = new OMPoint(lat, lon); - } else { - location = locationMarker; - } - - // We can do the x offset off the location here, we'll do the - // vertical offset later, when we can figure out the height of - // the text and can line the middle of the text up with the - // location. - - // If the caller has supplied a substitute graphic for - // the location spot, it's up to them to horizontally - // offset the label appropriately. They should do that - // here, or in an extended class. - label = new OMText(lat, lon, 0, 0, name, OMText.JUSTIFY_LEFT); - } - - /** - * Create a location at a map location. If the locationMarker is null, a - * small rectangle (dot) will be created to mark the location. - * - * @param x the pixel location of the object from the let of the map. - * @param y the pixel location of the object from the top of the map - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public Location(int x, int y, String name, OMGraphic locationMarker) { - - setLocation(x, y); - this.name = name; - - if (logger.isLoggable(Level.FINER)) { - logger.finer("Location XY(" + x + ", " + y + ", " + name + ")"); - } - - if (locationMarker == null) { - location = new OMPoint(x, y); - } else { - location = locationMarker; - } - - // We can do the x offset off the location here, we'll do the - // vertical offset later, when we can figure out the height of - // the text and can line the middle of the text up with the - // location. - - // If the caller has supplied a substitute graphic for - // the location spot, it's up to them to horizontally - // offset the label appropriately. They should do that - // here, or in an extended class. - label = new OMText(x, y, name, OMText.JUSTIFY_LEFT); - } - - /** - * Create a location at a pixel offset from a latitude/longitude. If the - * locationMarker is null, a small rectangle (dot) will be created to mark - * the location. - * - * @param latitude the latitude, in decimal degrees, of the location. - * @param longitude the longitude, in decimal degrees, of the location. - * @param xOffset the pixel location of the object from the longitude. - * @param yOffset the pixel location of the object from the latitude. - * @param name the name of the location, also used in the label. - * @param locationMarker the OMGraphic to use for the location mark. - */ - public Location(double latitude, double longitude, int xOffset, int yOffset, String name, OMGraphic locationMarker) { - setLocation(latitude, longitude, xOffset, yOffset); - this.name = name; - - if (logger.isLoggable(Level.FINER)) { - logger.finer("Location(" + latitude + ", " + longitude + ", offset " + x + ", " + y + ", " + name + ")"); - } - - if (locationMarker == null) { - location = new OMPoint(lat, lon, xOffset, yOffset); - } else { - location = locationMarker; - } - - // We can do the x offset off the location here, we'll do the - // vertical offset later, when we can figure out the height of - // the text and can line the middle of the text up with the - // location. - - // If the caller has supplied a substitute graphic for - // the location spot, it's up to them to horizontally - // offset the label appropriately. They should do that - // here, or in an extended class. - label = new OMText(lat, lon, xOffset, yOffset, name, OMText.JUSTIFY_LEFT); - } - - /** Set the placement of the location. */ - public void setLocation(double latitude, double longitude) { - lat = latitude; - lon = longitude; - - origYLabelOffset = 0; - origXLabelOffset = DEFAULT_SPACING; - - setRenderType(RENDERTYPE_LATLON); - if (location != null && label != null) { - setGraphicLocations(latitude, longitude); - } - } - - /** Set the placement of the location. */ - public void setLocation(int x, int y) { - this.x = x; - this.y = y; - - origYLabelOffset = y; - origXLabelOffset = x + DEFAULT_SPACING; - - setRenderType(RENDERTYPE_XY); - if (location != null && label != null) { - setGraphicLocations(x, y); - } - } - - /** Set the placement of the location. */ - public void setLocation(double latitude, double longitude, int xOffset, int yOffset) { - lat = latitude; - lon = longitude; - this.xOffset = xOffset; - this.yOffset = yOffset; - - origYLabelOffset = yOffset; - origXLabelOffset = xOffset + DEFAULT_SPACING; - - setRenderType(RENDERTYPE_OFFSET); - if (location != null && label != null) { - setGraphicLocations(latitude, longitude, xOffset, yOffset); - } - } - - /** - * Convenience method that lets you provide a screen x, y and a projection - * to the location, and let the location hash out how to place itself based - * on it's rendertype. - */ - public void setLocation(int x, int y, Projection proj) { - int renderType = getRenderType(); - - switch (renderType) { - case RENDERTYPE_LATLON: - if (proj != null) { - Point2D llp = proj.inverse(x, y); - setLocation((float) llp.getY(), (float) llp.getX()); - } else { - logger.fine("Location can't set lat/lon coordinates without a projection"); - } - break; - case RENDERTYPE_OFFSET: - if (proj != null) { - Point2D llp = proj.inverse(x, y); - setLocation((float) llp.getY(), (float) llp.getX(), this.xOffset, this.yOffset); - } else { - logger.fine("Location can't set lat/lon coordinates without a projection"); - } - break; - default: - setLocation(x, y); - } - } - - public abstract void setGraphicLocations(double latitude, double longitude); - - public abstract void setGraphicLocations(int x, int y); - - public abstract void setGraphicLocations(double latitude, double longitude, int offsetX, int offsetY); - - /** - * Set the location handler for the location. - */ - public void setLocationHandler(LocationHandler lh) { - handler = lh; - } - - /** - * Get the location handler for the location. - */ - public LocationHandler getLocationHandler() { - return handler; - } - - /** - * Set the edge java.awt.Paint for the marker graphic. - */ - public void setLocationPaint(Paint locationPaint) { - if (location != null) { - location.setLinePaint(locationPaint); - } - } - - /** - * Get the label for the location. - */ - public OMText getLabel() { - return label; - } - - /** - * Set the label for the location. - */ - public void setLabel(OMText lable) { - label = lable; - } - - /** - * Get the location marker for this location. - */ - public OMGraphic getLocationMarker() { - return location; - } - - /** - * Set the graphic for the location. - */ - public void setLocationMarker(OMGraphic graphic) { - location = graphic; - } - - /** - * Set whether this location should be shown on an individual basis. - */ - public void setShowLocation(boolean showLocations) { - showLocation = showLocations; - } - - /** See of the location is displaying it's location. */ - public boolean isShowLocation() { - return showLocation; - } - - /** Set the location to display it's label. */ - public void setShowName(boolean showNames) { - showName = showNames; - } - - /** See if the location is displaying it's label. */ - public boolean isShowName() { - return showName; - } - - /** Get the name of the location. */ - public String getName() { - return name; - } - - /** - * Set the name of this location. - */ - public void setName(String name) { - this.name = name; - if (label != null) { - label.setData(name); - } - } - - /** - * Set the details for the location. This should be the contents to be - * displayed in a web browser. - */ - public void setDetails(String det) { - details = det; - } - - /** - * Get the details for the location. - */ - public String getDetails() { - return details; - } - - /** - * Fire a browser to display the location details. - */ - public void showDetails() { - if (details != null) { - try { - getLocationHandler().getLayer().fireRequestBrowserContent(details); - } catch (NullPointerException npe) { - - } - } - } - - /** - * Set whether you want to allow the label for this location to be - * decluttered. - * - * @param allow if true, label will be decluttered if declutter matrix is - * available. - */ - public void setAllowDecluttering(boolean allow) { - allowDecluttering = allow; - } - - /** - * Get the decluttering allowance setting for this label. - */ - public boolean isAllowDecluttering() { - return allowDecluttering; - } - - /** - * Set the pixel distance that the label will be moved to the right, to - * clear space for the graphic marking the location. - */ - public void setHorizontalLabelBuffer(int buffer) { - horizontalLabelBuffer = buffer; - } - - /** - * Get the pixel distance that the label will be moved to the right, to - * clear space for the graphic marking the location. - */ - public int getHorizontalLabelBuffer() { - return horizontalLabelBuffer; - } - - // ////////////////////////////////////////////////// - // ///////// OMGraphic methods //////////////////// - // ////////////////////////////////////////////////// - - /** - * Generate the location, and use the declutter matrix to place the label is - * a spot so that it doesn't interset with other labels. - * - * @param proj projection of the map. - * @param declutterMatrix DeclutterMatrix for the map. - */ - public boolean generate(Projection proj, DeclutterMatrix declutterMatrix) { - - // Call generate(proj) first, to get the original position - // set. Then, declutter the text. - boolean ret = generate(proj); - - if (declutterMatrix != null && label != null && allowDecluttering) { - declutterLabel(declutterMatrix, proj); - } - return ret; - } - - /** - * Set the pixel distance that us used by the declutter matrix in trying to - * find a place for the label. If it can't find a place within this pixel - * limit, it wouldn't draw it. - */ - public void setDeclutterLimit(int value) { - if (value < 0 && value != DECLUTTER_LOCALLY) { - declutterLimit = DECLUTTER_ANYWHERE; - } else { - declutterLimit = value; - } - } - - /** - * Get the declutter pixel distance limit. - */ - public int getDeclutterLimit() { - return declutterLimit; - } - - protected int currentFontDescent = 0; - - /** - * Prepare the graphic for rendering. This must be done before calling - * render()! If a vector graphic has lat-lon components, then - * we project these vertices into x-y space. For raster graphics we prepare - * in a different fashion. - *

- * If the generate is unsuccessful, it's usually because of some oversight, - * (for instance if proj is null), and if debugging is enabled, - * a message may be output to the controlling terminal. - *

- * - * @param proj Projection - * @return boolean true if successful, false if not. - */ - public boolean generate(Projection proj) { - if (label != null) { - label.setY(origYLabelOffset); - label.setX(origXLabelOffset); - } - - java.awt.Graphics g = DeclutterMatrix.getGraphics(); - if (g != null && label != null) { - g.setFont(label.getFont()); - // Now set the vertical offset to the original place based - // off the height of the label, so that the location place - // is halfway up the text. That way, it looks like a - // label. - int height = g.getFontMetrics().getAscent(); - currentFontDescent = g.getFontMetrics().getDescent(); - label.setX(label.getX() + horizontalLabelBuffer); - label.setY(label.getY() + (height / 2) - 2); - } - - if (label != null) { - label.generate(proj); - label.prepareForRender(g); - } - if (location != null) - location.generate(proj); - - return true; - } - - /** - * Paint the graphic and the name of the location. This should only be used - * if the locations are pretty spread out from each other. If you think you - * need to declutter, you should render all the graphics, and then render - * the names, so that the graphics don't cover up the names. - *

- * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated, it will not be rendered. This render will - * take into account the layer showNames and showLocations settings. - * - * @param g Graphics context to render into. - */ - public void render(Graphics g) { - renderLocation(g); - renderName(g); - } - - /** - * Paint the graphic label (name) only. This paints the graphic into the - * Graphics context. This is similar to paint() function of - * java.awt.Components. Note that if the graphic has not been generated, it - * will not be rendered. This render will take into account the layer - * showNames and showLocations settings. - * - * @param g Graphics context to render into. - */ - public void renderName(Graphics g) { - if (shouldRenderName()) { - label.render(g); - } - } - - /** - * Paint the graphic location graphic only. This paints the graphic into the - * Graphics context. This is similar to paint() function of - * java.awt.Components. Note that if the graphic has not been generated, it - * will not be rendered. This render will take into account the layer - * showNames and showLocations settings. - * - * @param g Graphics context to render into. - */ - public void renderLocation(Graphics g) { - if (shouldRenderLocation()) { - location.render(g); - } - } - - /** - * Convenience method to see if handler/global settings dictate that the - * location label should be rendered. - * - * @return true if the name label should be rendered. - */ - protected boolean shouldRenderName() { - boolean globalShowNames = false; - boolean forceGlobal = false; - if (handler != null) { - globalShowNames = handler.isShowNames(); - forceGlobal = handler.isForceGlobal(); - } - - return label != null && ((forceGlobal && globalShowNames) || (!forceGlobal && showName)); - } - - /** - * Convenience method to see if handler/global settings dictate that the - * location icon should be rendered. - * - * @return true of the location marker should be rendered. - */ - protected boolean shouldRenderLocation() { - boolean globalShowLocations = false; - boolean forceGlobal = false; - if (handler != null) { - globalShowLocations = handler.isShowLocations(); - forceGlobal = handler.isForceGlobal(); - } - - return location != null && ((forceGlobal && globalShowLocations) || (!forceGlobal && showLocation)); - } - - /** - * Return the shortest distance from the graphic to an XY-point. - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance from graphic to the point - */ - public float distance(double x, double y) { - float labelDist = Float.MAX_VALUE; - float locationDist = Float.MAX_VALUE; - - if (shouldRenderLocation()) { - locationDist = location.distance(x, y); - } - - if (shouldRenderName()) { - labelDist = label.distance(x, y); - } - - return (locationDist > labelDist ? labelDist : locationDist); - } - - /** - * Given the label is this location has a height and width, find a clean - * place on the map for it. Assumes label is not null. - * - * @param declutter the DeclutterMatrix for the map. - */ - protected void declutterLabel(DeclutterMatrix declutter, Projection proj) { - - if (logger.isLoggable(Level.FINER)) { - logger.finer("\nLocation::RepositionText => " + label.getData()); - } - - // Right now, I think this method takes some presumptuous - // actions, assuming that you want the graphics to take up - // space in the declutter matrix. We might want to delete - // this showLocation code, and let people create their own - // location subclasses that define how the graphic should be - // handled in the declutter matrix. - - // I think I will. This stuff is commented out for the - // reasons stated above. - - // if (isShowLocation()) { - // Point lp; - // // Take up space with the label - // if (location instanceof OMRasterObject) { - // lp = ((OMRasterObject)location).getMapLocation(); - // // This location is the upper left location of the - // // declutter matrix. The declutter matrix works from - // // lower left to upper right. - // if (lp != null) { - // int locHeight = ((OMRasterObject)location).getHeight(); - // int locWidth = ((OMRasterObject)location).getWidth(); - // // Need to get this right for the DeclutterMatrix - // // space, but changing lp changes where the - // // location will appear - fix this later. - // lp.y += locHeight; - // declutter.setTaken(lp, locWidth, locHeight); - // // Reset it to the original projected location. - // lp.y -= locHeight; - // } - // } else if (renderType != RENDERTYPE_XY) { - // lp = proj.forward(lat,lon); - // lp.x += xOffset-1; - // lp.y += yOffset-1; - // declutter.setTaken(lp, 3, 3); - // } else { - // lp = new Point(x-1, y-1); - // declutter.setTaken(lp, 3, 3); - // } - // } - - if (isShowName() || (handler != null && handler.isShowNames())) { - - if (label == null || label.getPolyBounds() == null) { - // Why bother going further?? - return; - } - - Rectangle bounds = label.getPolyBounds().getBounds(); - int height = (int) ((float) (bounds.getHeight() - currentFontDescent / 2)); - int width = (int) bounds.getWidth(); - // Projected location of label on the screen - Point2D p = label.getMapLocation(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("old point X Y =>" + p.getX() + " " + p.getY() + " height = " + height + " width = " + width); - } - - int limit; - if (declutterLimit == DECLUTTER_LOCALLY) { - limit = height * 2; - } else { - limit = declutterLimit; - } - - // newpoint is the new place on the map to put the label - Point2D newpoint = declutter.setNextOpen(p, width, height, limit); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("new point X Y =>" + newpoint.getX() + " " + newpoint.getY()); - } - - label.setMapLocation(newpoint); - } - } - - /** - * A simple conversion method for the common String representation of - * decimal degree coordinates, which is a letter denoting the globle - * hemisphere (N or S for latitudes, W or E for longitudes, and then a - * number string. For latitudes, the first two numbers represent the whole - * degree value, and the rest of the numbers represent the fractional - * protion. For longitudes, the first three numbers represent the whole - * degree value. For instance N2443243 equals 24.43243 degrees North, and - * S2443243 results in -24.43243 degrees. Likewise, w12423443 results in - * -124.23443 degrees. - * - * @param coord the coordinate string representing the decimal degree value, - * following the format [NSEW]XXXXXXXXX. - * @return the decimal degrees for the string. There is no notation for you - * to know whether it's a latitude or longitude value. - */ - public static float convertCoordinateString(String coord) - throws NumberFormatException { - - float ret = 0f; - String mantissa; - char direction = coord.charAt(0); - if (direction == 'N' || direction == 'S' || direction == 'n' || direction == 's') { - float whole = new Float(coord.substring(1, 3)).floatValue(); - ret += whole; - mantissa = coord.substring(3); - } else if (direction == 'W' || direction == 'E' || direction == 'w' || direction == 'e') { - ret += new Float(coord.substring(1, 4)).floatValue(); - mantissa = coord.substring(4); - } else { - // Don't know the format!! - throw new NumberFormatException("Location.convertCoordinateString wants <[NSWE]XXXXXXXX>, not getting it."); - } - - ret += new Float(mantissa).floatValue() / (float) (Math.pow(10, mantissa.length())); - if (direction == 'W' || direction == 'S' || direction == 'w' || direction == 's') { - ret *= -1f; - } - - return ret; - } - - /** - * We're using the main function for Location to test the - * convertCoordinateString function. - */ - public static void main(String[] args) { - if (args.length < 1) { - logger.info(" usage: java com.bbn.openmap.layer.location.Location <[NSWE]XXXXXXXX>"); - return; - } - float ret = Location.convertCoordinateString(args[0]); - System.out.println(ret); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationCBMenuItem.java b/src/core/src/main/java/com/bbn/openmap/layer/location/LocationCBMenuItem.java deleted file mode 100644 index 1b278024d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationCBMenuItem.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/LocationCBMenuItem.java,v $ -// $RCSfile: LocationCBMenuItem.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -import java.awt.event.ActionListener; - -import javax.swing.JCheckBoxMenuItem; - -/** - * This is an checkbox item that sits on the popup menu. It knows how to get - * information it needs from the menu, and recenters the map, or brings up more - * information about the location. - */ -public class LocationCBMenuItem - extends JCheckBoxMenuItem - implements ActionListener { - - protected Location location; - - public LocationCBMenuItem(String text, Location loc) { - super(text); - setLoc(loc); - this.addActionListener(this); - setSelected(loc.isShowName()); - } - - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - - if (e.getSource().equals(this)) { - if (command.equals(LocationHandler.showname)) { - JCheckBoxMenuItem btn = (JCheckBoxMenuItem) e.getSource(); - try { - location.setShowName(btn.getState()); - location.getLocationHandler().getLayer().repaint(); - } catch (NullPointerException npe) { - - } - } - } - } - - /** - * @return the location - */ - public Location getLoc() { - return location; - } - - /** - * @param location the location to set - */ - public void setLoc(Location location) { - this.location = location; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/LocationHandler.java deleted file mode 100644 index 8eec9d2f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationHandler.java +++ /dev/null @@ -1,196 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/LocationHandler.java,v $ -// $Revision: 1.6 $ $Date: 2005/08/09 18:15:13 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -import java.awt.Component; -import java.util.List; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * The LocationHandler is the LocationLayer interface to the data. It is the - * bearer of knowledge about how the location data is stored, and has the smarts - * on creating the locations and links to represent the data on the map. It also - * provides controls for changing the display of the data, provided through the - * getGUI() method, and therefore controls how the data is displayed at a - * supervisory level. Each location handler should have its own set of - * properties: - * - *

- * 
- * 
- *     # Properties for LocationHandler
- *     # Show the graphics for all the locations.
- *     handler.showLocations=true
- *     # Show the labels for all the locations.
- *     handler.showNames=true
- * 
- * 
- * 
- */ -public interface LocationHandler extends PropertyConsumer { - - /** - * A default button name used to trigger more information about a location - * to come up in a web browser. - */ - public final static String showdetails = "Show Details"; - /** A button name used to turn a location label on/off. */ - public final static String showname = "Always Show Name"; - - /** Property setting to show name data on startup. (showNames) */ - public static final String ShowNamesProperty = "showNames"; - /** The default line color for names. (FF339159) */ - public final static String defaultNameColorString = "FF339159"; // greenish - - public static final String ForceGlobalProperty = "override"; - - /** - * Property setting to show location splots on startup. (showLocations) - */ - public static final String ShowLocationsProperty = "showLocations"; - /** The default line color for locations. (FFCE4F3F) */ - public final static String defaultLocationColorString = "FFCE4F3F"; // reddish - /** (showLocations) */ - public final static String showLocationsCommand = "showLocations"; - /** (showNames) */ - public final static String showNamesCommand = "showNames"; - /** (forceGlobal) */ - public final static String forceGlobalCommand = "forceGlobal"; - /** (readData) */ - public final static String readDataCommand = "readData"; - - /** - * Property prefix to use to scope properties to be used for name markers, - * including rendering properties. (name) - */ - public final static String NamePropertyPrefix = "name"; - /** - * Property prefix to use to scope properties to be used for location - * markers, including rendering properties. (location) - */ - public final static String LocationPropertyPrefix = "location"; - - /** - * Fill a vector of OMGraphics to represent the data from this handler. - * - * @param nwLat NorthWest latitude of area of interest. - * @param nwLon NorthWest longitude of area of interest. - * @param seLat SouthEast latitude of area of interest. - * @param seLon SouthEast longitude of area of interest. - * @param graphicList Vector to add Locations to. If null, the - * LocationHandler should create a new Vector to place graphics into. - * @return Either the OMGraphicList passed in, or the new one that was - * created if null. - */ - public OMGraphicList get(double nwLat, double nwLon, double seLat, double seLon, - OMGraphicList graphicList); - - /** - * A trigger function to tell the handler that new data is available. - */ - public void reloadData(); - - /** - * The location layer passes a LocationPopupMenu to the handler when on of - * its locations has been clicked on. This is an opportunity for the handler - * to add options to the menu that can bring up further information about - * the location, or to change the appearance of the location. - * - * @param loc Location that items should be provided for. - */ - public List getItemsForPopupMenu(Location loc); - - /** - * Return the layer that the handler is responding to. - */ - public LocationLayer getLayer(); - - /** - * Set the layer the handler is responding to. This is needed in case the - * handler has updates that it wants to show, and needs to trigger a - * repaint. It can also be used to communicate with the information - * delegator. - * - * @param layer a LocationLayer - */ - public void setLayer(LocationLayer layer); - - /** - * See if the handler is displaying labels at a global level. - */ - public boolean isShowNames(); - - /** - * Set the handler to show/hide labels at a global level. - */ - public void setShowNames(boolean set); - - /** - * See if the handler is displaying location graphics at a global level. - */ - public boolean isShowLocations(); - - /** - * Set the handler to show/hide location graphics at a global level. - */ - public void setShowLocations(boolean set); - - /** - * Find out whether global settings should override local ones. - */ - public boolean isForceGlobal(); - - /** - * Set whether global settings should override local ones. - */ - public void setForceGlobal(boolean set); - - /** - * A set of controls to manipulate and control the display of data from the - * handler. - * - * @return Components used for control. - */ - public java.awt.Component getGUI(); - - /** - * Called by the LocationLayer when the Layer has been removed from the Map. - * The LocationHandler should clear out memory/CPU intensive resources. - * - * @param cont Container being removed from. - */ - public void removed(java.awt.Container cont); - - /** - * Set the name used in the GUI to represent this data set. - * - * @param prettyName A GUI pretty name. - */ - public void setPrettyName(String prettyName); - - /** - * Get the GUI pretty name for the data set retrieved by this - * LocationHandler. - * - * @return a pretty name for LocationHandler, to be used in the GUI. - */ - public String getPrettyName(); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/location/LocationLayer.java deleted file mode 100644 index 08d98f185..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationLayer.java +++ /dev/null @@ -1,631 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/LocationLayer.java,v $ -// $RCSfile: LocationLayer.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/01/18 17:44:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.Box; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; - -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.layer.DeclutterMatrix; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The LocationLayer is a layer that displays graphics supplied by - * LocationHandlers. When the layer receives a new projection, it goes to each - * LocationHandler and asks it for additions to the layer's graphic list. The - * LocationHandlers maintain the graphics, and the layer maintains the overall - * list. - * - * The whole idea behind locations is that there are geographic places that are - * to be marked with a graphic, and/or a text label. The location handler - * handles the interface with the source and type of location to be displayed, - * and the LocationLayer deals with all the locations in a generic way. The - * LocationLayer is capable of using more than one LocationHandler. - *

- * - * As a side note, a Link is nothing more than a connection between Locations, - * and is an extension of the Location Class. They have a graphic representing - * the link, an optional label, and an extra set of location coordinates. - *

- * - * The layer responds to gestures with pop-up menus. Which menu appears depends - * if the gesture affects a graphic. - *

- * - * The properties for this layer are: - *

- * - *

- * 
- *   ####################################
- *   # Properties for LocationLayer
- *   # Use the DeclutterMatrix to declutter the labels.
- *   locationlayer.useDeclutter=false
- *   # Which declutter matrix class to use.
- *   locationlayer.declutterMatrix=com.bbn.openmap.layer.DeclutterMatrix
- *   # Let the DeclutterMatrix have labels that run off the edge of the map.
- *   locationlayer.allowPartials=true
- *   # The list of location handler prefixes - each prefix should then
- *   # be used to further define the location handler properties.
- *   locationlayer.locationHandlers=handler1 handler2
- *   # Then come the handler properties...
- *   # At the least, each handler should have a .class property
- *   handler1.class=<handler classname>
- *   # plus any other properties handler1 needs - check the handler1 documentation.
- *   ####################################
- * 
- * 
- */ -public class LocationLayer extends OMGraphicHandlerLayer { - - /** The declutter matrix to use, if desired. */ - protected DeclutterMatrix declutterMatrix = null; - /** Flag to use declutter matrix or not. */ - protected boolean useDeclutterMatrix = false; - /** - * Flag to let objects appear partially off the edges of the map, when - * decluttering through the declutter matrix. - */ - protected boolean allowPartials = true; - - /** Handlers load the data, and manage it for the layer. */ - protected final CopyOnWriteArrayList dataHandlers = new CopyOnWriteArrayList(); - - // /////////////////// - // Variables to manage the gesturing mechanisms - - static final public String recenter = "Re-center map"; - static final public String cancel = "Cancel"; - - public static final String UseDeclutterMatrixProperty = "useDeclutter"; - public static final String DeclutterMatrixClassProperty = "declutterMatrix"; - public static final String AllowPartialsProperty = "allowPartials"; - public static final String LocationHandlerListProperty = "locationHandlers"; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public LocationLayer() { - setRenderPolicy(new BufferedImageRenderPolicy(this)); - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the LocationLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - String realPrefix = ""; - - if (prefix != null) { - realPrefix = prefix + "."; - } - - setLocationHandlers(realPrefix, properties); - declutterMatrix = (DeclutterMatrix) PropUtils.objectFromProperties(properties, realPrefix - + DeclutterMatrixClassProperty); - allowPartials = PropUtils.booleanFromProperties(properties, realPrefix - + AllowPartialsProperty, true); - - if (declutterMatrix != null) { - useDeclutterMatrix = PropUtils.booleanFromProperties(properties, realPrefix - + UseDeclutterMatrixProperty, useDeclutterMatrix); - declutterMatrix.setAllowPartials(allowPartials); - Debug.message("location", "LocationLayer: Found DeclutterMatrix to use"); - // declutterMatrix.setXInterval(3); - // declutterMatrix.setYInterval(3); - } else { - useDeclutterMatrix = false; - } - } - - public void setDeclutterMatrix(DeclutterMatrix dm) { - declutterMatrix = dm; - } - - public DeclutterMatrix getDeclutterMatrix() { - return declutterMatrix; - } - - public void setUseDeclutterMatrix(boolean set) { - useDeclutterMatrix = set; - - if (declutterButton != null) { - declutterButton.setSelected(useDeclutterMatrix); - } - } - - public boolean getUseDeclutterMatrix() { - return useDeclutterMatrix; - } - - /** - * Tell the location handlers to reload their data from their sources. If - * you want these changes to appear on the map, you should call doPrepare() - * after this call. - */ - public void reloadData() { - if (dataHandlers != null) { - for (LocationHandler dataHandler : dataHandlers) { - dataHandler.reloadData(); - } - } - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the location. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public synchronized OMGraphicList prepare() { - - OMGraphicList omGraphicList = new OMGraphicList(); - omGraphicList.setTraverseMode(OMGraphicList.FIRST_ADDED_ON_TOP); - - Projection projection = getProjection(); - - if (projection == null) { - if (Debug.debugging("location")) { - Debug.output(getName() - + "|LocationLayer.prepare(): null projection, layer not ready."); - } - return omGraphicList; - } - - if (Debug.debugging("location")) { - Debug.output(getName() + "|LocationLayer.prepare(): doing it"); - } - - if (useDeclutterMatrix && declutterMatrix != null) { - declutterMatrix.setWidth(projection.getWidth()); - declutterMatrix.setHeight(projection.getHeight()); - declutterMatrix.create(); - } - - // Setting the OMGraphicsList for this layer. Remember, the - // Vector is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (Debug.debugging("location")) { - Debug.output(getName() + "|LocationLayer.prepare(): " - + "calling prepare with projection: " + projection + " ul = " - + projection.getUpperLeft() + " lr = " + projection.getLowerRight()); - } - - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - - if (Debug.debugging("location")) { - double delta = lr.getX() - ul.getX(); - Debug.output(getName() + "|LocationLayer.prepare(): " + " ul.lon =" + ul.getX() - + " lr.lon = " + lr.getY() + " delta = " + delta); - } - if (dataHandlers != null) { - for (LocationHandler dataHandler : dataHandlers) { - dataHandler.get((float) ul.getY(), (float) ul.getX(), (float) lr.getY(), (float) lr.getX(), omGraphicList); - } - } - - // /////////////////// - // safe quit - int size = 0; - if (omGraphicList != null) { - size = omGraphicList.size(); - if (Debug.debugging("basic")) { - Debug.output(getName() + "|LocationLayer.prepare(): finished with " + size - + " graphics"); - } - - // Don't forget to project them. Since they are only - // being recalled if the projection has changed, then - // we need to force a re-projection of all of them - // because the screen position has changed. - for (OMGraphic thingy : omGraphicList) { - if (useDeclutterMatrix && thingy instanceof Location) { - ((Location) thingy).generate(projection, declutterMatrix); - } else { - thingy.generate(projection); - } - } - } else if (Debug.debugging("basic")) { - Debug.output(getName() + "|LocationLayer.prepare(): finished with null graphics list"); - } - - return omGraphicList; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(java.awt.Graphics g) { - if (Debug.debugging("location")) { - Debug.output(getName() + "|LocationLayer.paint()"); - } - - OMGraphicList omgList = getList(); - - if (omgList != null) { - - // Draw from the bottom up, so it matches the palette, and - // the order in which the handlers were loaded - the first - // in the list is on top. - - // We need to go through list twice. The first time, draw - // all the regular OMGraphics, and also draw all of the - // graphics for the locations. The second time through, - // draw the labels. This way, the labels won't be covered - // up by graphics. - - // render locations - for (OMGraphic omg : omgList) { - if (omg instanceof Location) { - ((Location) omg).renderLocation(g); - } else { - omg.render(g); - } - } - - // Now render labels - for (OMGraphic omg : omgList) { - if (omg instanceof Location) { - ((Location) omg).renderName(g); - } - } - - } else { - if (Debug.debugging("location")) { - Debug.error(getName() + "|LocationLayer: paint(): Null list..."); - } - } - } - - /** - * Parse the properties and set up the location handlers. The prefix will - * should be null, or a prefix string with a period at the end, for scoping - * purposes. - */ - protected void setLocationHandlers(String prefix, Properties p) { - - String sPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String handlersValue = p.getProperty(sPrefix + LocationHandlerListProperty); - - if (Debug.debugging("location")) { - Debug.output(getName() + "| handlers = \"" + handlersValue + "\""); - } - - if (handlersValue == null) { - if (Debug.debugging("location")) { - Debug.output("No property \"" + prefix + LocationHandlerListProperty - + "\" found in application properties."); - } - return; - } - - List handlerNames = PropUtils.parseSpacedMarkers(handlersValue); - - for (String handlerName : handlerNames) { - String classProperty = handlerName + ".class"; - String className = p.getProperty(classProperty); - - if (className == null) { - Debug.error("Failed to locate property \"" + classProperty - + "\"\nSkipping handler \"" + handlerName + "\""); - continue; - } - try { - if (Debug.debugging("location")) { - Debug.output("OpenMap.getHandlers():instantiating handler \"" + className - + "\""); - } - - // Works for applet! - Object obj = Class.forName(className).newInstance(); - - if (obj instanceof LocationHandler) { - LocationHandler lh = (LocationHandler) obj; - lh.setProperties(handlerName, p); - lh.setLayer(this); - dataHandlers.add(lh); - } - - if (false) { - throw new java.io.IOException();// fool javac compiler - } - - } catch (java.lang.ClassNotFoundException e) { - Debug.error("Handler class not found: \"" + className + "\"\nSkipping handler \"" - + handlerName + "\""); - } catch (java.io.IOException e) { - Debug.error("IO Exception instantiating class \"" + className - + "\"\nSkipping handler \"" + handlerName + "\""); - } catch (Exception e) { - Debug.error("Exception instantiating class \"" + className + "\": " + e); - } - } - } - - /** - * Let the LocationHandlers know that the layer has been removed. - */ - public void removed(java.awt.Container cont) { - if (dataHandlers != null) { - for (LocationHandler dataHandler : dataHandlers) { - dataHandler.removed(cont); - } - } - } - - /** - * Set the LocationHandlers for the layer. Make sure you update the - * LocationHandler names, too, so the names correspond to these. - * - * @param handlers an array of LocationHandlers. - */ - public void setLocationHandlers(LocationHandler[] handlers) { - - for (LocationHandler handler : dataHandlers) { - handler.removed(null); - } - dataHandlers.clear(); - - // Need to set the layer on the handlers. - for (LocationHandler dataHandler : handlers) { - dataHandler.setLayer(this); - dataHandlers.add(dataHandler); - } - - resetPalette(); - } - - /** - * Get the LocationHandlers for this layer. - */ - public LocationHandler[] getLocationHandlers() { - return dataHandlers.toArray(new LocationHandler[dataHandlers.size()]); - } - - /** - * Called when the LocationHandlers are reset, or their names are reset, to - * refresh the palette with the new information. - */ - protected void resetPalette() { - box = null; - super.resetPalette(); - } - - /** - * Overridden from Layer because we are placing our own scroll pane around - * the LocationHandler GUIs. - */ - protected WindowSupport createWindowSupport() { - return new WindowSupport(getGUI(), getName()); - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - protected Box box = null; - protected JCheckBox declutterButton = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - if (box == null) { - box = Box.createVerticalBox(); - int nHandlers = 0; - - if (dataHandlers != null) { - nHandlers = dataHandlers.size(); - } - - Box box2 = Box.createVerticalBox(); - for (LocationHandler dataHandler : dataHandlers) { - Component guiComponent = dataHandler.getGUI(); - if (guiComponent != null) { - JPanel panel = PaletteHelper.createPaletteJPanel(dataHandler.getPrettyName()); - panel.add(dataHandler.getGUI()); - box2.add(panel); - } - } - - JScrollPane scrollPane = new JScrollPane(box2, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - - scrollPane.setAlignmentX(java.awt.Component.CENTER_ALIGNMENT); - scrollPane.setAlignmentY(java.awt.Component.TOP_ALIGNMENT); - - box.add(scrollPane); - - if (declutterMatrix != null) { - JPanel dbp = new JPanel(new GridLayout(0, 1)); - - declutterButton = new JCheckBox(i18n.get(LocationLayer.class, "declutterNames", "Declutter Names"), useDeclutterMatrix); - declutterButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - useDeclutterMatrix = jcb.isSelected(); - if (isVisible()) { - doPrepare(); - } - } - }); - declutterButton.setToolTipText(i18n.get(LocationLayer.class, "declutterNames", I18n.TOOLTIP, "Move location names so they don't overlap.
This may take awhile if you are zoomed out.")); - dbp.add(declutterButton); - box.add(dbp); - } - } - return box; - } - - public String getToolTipTextFor(OMGraphic omg) { - String ttText = null; - if (omg instanceof Location) { - ttText = ((Location) omg).getName(); - } - return ttText; - } - - public List getItemsForOMGraphicMenu(OMGraphic omg) { - if (omg instanceof Location) { - Location loc = (Location) omg; - LocationHandler lh = loc.getLocationHandler(); - if (lh != null) { - return lh.getItemsForPopupMenu(loc); - } - } - - return null; - } - - // protected void showLocationPopup(MouseEvent evt, Location loc, MapBean - // map) { - // if (locMenu == null) { - // locMenu = new LocationPopupMenu(); - // locMenu.setMap(map); - // } - // locMenu.removeAll(); - // - // locMenu.setEvent(evt); - // locMenu.setLoc(loc); - // - // locMenu.add(new LocationMenuItem(LocationLayer.recenter, locMenu, this)); - // locMenu.add(new LocationMenuItem(LocationLayer.cancel, locMenu, this)); - // locMenu.addSeparator(); - // - // - // locMenu.show(this, evt.getX(), evt.getY()); - // } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + UseDeclutterMatrixProperty, new Boolean(useDeclutterMatrix).toString()); - - if (declutterMatrix != null) { - props.put(prefix + DeclutterMatrixClassProperty, declutterMatrix.getClass().getName()); - props.put(prefix + AllowPartialsProperty, new Boolean(declutterMatrix.isAllowPartials()).toString()); - } - - StringBuffer handlerList = new StringBuffer(); - - // Need to hand this off to the location handlers, and build a - // list of marker names to use in the LocationLayer property - // list. - if (dataHandlers != null) { - for (LocationHandler dataHandler : dataHandlers) { - dataHandler.getProperties(props); - } - } - - props.put(prefix + LocationHandlerListProperty, handlerList.toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - PropUtils.setI18NPropertyInfo(i18n, list, LocationLayer.class, UseDeclutterMatrixProperty, "Use Declutter Matrix", "Flag for using the declutter matrix.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, LocationLayer.class, DeclutterMatrixClassProperty, "Declutter Matrix Class", "Class name of the declutter matrix to use (com.bbn.openmap.layer.DeclutterMatrix).", null); - PropUtils.setI18NPropertyInfo(i18n, list, LocationLayer.class, AllowPartialsProperty, "Allow partials", "Flag to allow labels to run off the edge of the map.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, LocationLayer.class, LocationHandlerListProperty, "Location Handlers", "Space-separated list of unique names to use to scope the LocationHandler property definitions.", null); - - if (dataHandlers != null) { - for (LocationHandler dataHandler : dataHandlers) { - dataHandler.getPropertyInfo(list); - } - } - - return list; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationMenuItem.java b/src/core/src/main/java/com/bbn/openmap/layer/location/LocationMenuItem.java deleted file mode 100644 index ad86af965..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/LocationMenuItem.java +++ /dev/null @@ -1,97 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/LocationMenuItem.java,v $ -// $RCSfile: LocationMenuItem.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -import java.awt.event.ActionListener; - -import javax.swing.JMenuItem; - -/** - * This is an item that sits on the popup menu. It knows how to get information - * it needs from the menu, and recenters the map, or brings up more information - * about the location. - */ -public class LocationMenuItem - extends JMenuItem - implements ActionListener { - - protected Location location; - - /** - * Construct an empty item - */ - public LocationMenuItem() { - } - - /** - * Construct a menuitem with a label - * - * @param text the text for the item - */ - public LocationMenuItem(String text) { - super(text); - this.addActionListener(this); - } - - /** - * Construct a menu item with a label and mnemonic - * - * @param text the text for the item - * @param mnemonic the mnemonic key for the item - */ - public LocationMenuItem(String text, int mnemonic) { - super(text, mnemonic); - this.addActionListener(this); - } - - public LocationMenuItem(String text, Location loc) { - this(text); - setLoc(loc); - } - - /** - * @return the location - */ - public Location getLoc() { - return location; - } - - /** - * @param location the location to set - */ - public void setLoc(Location location) { - this.location = location; - } - - public void actionPerformed(java.awt.event.ActionEvent e) { - // Debug.output("Action: " + e); - String command = e.getActionCommand(); - - if (command.equals(LocationHandler.showdetails)) { - try { - getLoc().showDetails(); - } catch (NullPointerException npe) { - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/TimerLocationLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/location/TimerLocationLayer.java deleted file mode 100644 index b8feaeb3b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/TimerLocationLayer.java +++ /dev/null @@ -1,366 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/TimerLocationLayer.java,v $ -// $RCSfile: TimerLocationLayer.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/01/18 17:44:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.util.Properties; - -import javax.swing.Box; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.Timer; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.util.PropUtils; - -/** - * The TimerLocationLayer is a LocationLayer that has a timer to automatically - * relod data at specified interval. - * - * The properties for this layer are the same as a LocationLayer, with the - * addition of two: - *

- * - *

- * 
- *  # Specify the interval (milliseconds) for the timer. Default is 10 seconds.
- *  layer.updateTimerInterval=10000
- *  # Auto-start/stop the timer when the layer is part of the Default
- *  # is true.  There is a control to start/stop the timer on the
- *  # palette.
- *  layer.automaticTimer=true;
- * 
- * 
- */ -public class TimerLocationLayer - extends LocationLayer { - - /** Reloading timer. */ - protected Timer timer; - - /** updateTimerInterval */ - public static final String UpdateTimerIntervalProperty = "updateTimerInterval"; - /** automaticTimer */ - public static final String AutoTimerProperty = "automaticTimer"; - /** - * Flag to note whether file reloading should only happen when the layer is - * visible. True by default. - */ - protected boolean autoTimer = true; - - private final com.bbn.openmap.Layer layer = this; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public TimerLocationLayer() { - addComponentListener(new ComponentAdapter() { - public void componentShown(ComponentEvent e) { - if (e.getComponent() == layer && getAutoTimer() && timerButton != null && !timerButton.isSelected()) { - - timerButton.doClick(); - } - } - - public void componentHidden(ComponentEvent e) { - if (e.getComponent() == layer && getAutoTimer() && timerButton != null && timerButton.isSelected()) { - - timerButton.doClick(); - } - } - }); - } - - public void projectionChanged(ProjectionEvent e) { - super.projectionChanged(e); - - if (autoTimer && timer != null - && ((timerButton != null && timerButton.isSelected()) || (timerButton == null && getUpdateInterval() > 0))) { - - timer.restart(); - updateTimerButton(); - } - } - - /** - * This method is called after the layer is removed from the MapBean and - * when the projection changes. If the autoTimer is set, the timer is - * stopped. - */ - public void removed(java.awt.Container cont) { - if (autoTimer) { - timer.stop(); - updateTimerButton(); - } - } - - protected JCheckBox timerButton = null; - protected JCheckBox autoTimerButton = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - box = null; - box = (Box) super.getGUI(); - - // Only want to do this once... - if (getTimer() != null) { - if (timerButton == null) { - String bTitle = "Run Update Timer"; - int interval = getUpdateInterval(); - if (interval > 0) { - bTitle = "Reload Data (" + (interval / 1000) + " sec)"; - } - timerButton = new JCheckBox(bTitle, getTimer().isRunning()); - timerButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox check = (JCheckBox) ae.getSource(); - Timer t = getTimer(); - if (t != null) { - if (check.isSelected()) { - t.restart(); - } else { - t.stop(); - } - } - } - }); - timerButton.setToolTipText("Reload the map data from the original source at specified intervals."); - } - - if (autoTimerButton == null) { - autoTimerButton = new JCheckBox("Reload Only When Visible", getAutoTimer()); - autoTimerButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox check = (JCheckBox) ae.getSource(); - setAutoTimer(check.isSelected()); - } - }); - autoTimerButton.setToolTipText("Only run the timer when the layer is active on the map."); - } - - JPanel tbp = new JPanel(new GridLayout(0, 1)); - tbp.add(timerButton); - tbp.add(autoTimerButton); - box.add(tbp); - } - return box; - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the LocationLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - String realPrefix = ""; - - if (prefix != null) { - realPrefix = prefix + "."; - } - - setUpdateInterval(PropUtils.intFromProperties(properties, realPrefix + UpdateTimerIntervalProperty, updateInterval)); - setAutoTimer(PropUtils.booleanFromProperties(properties, realPrefix + AutoTimerProperty, autoTimer)); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + UpdateTimerIntervalProperty, Integer.toString(updateInterval)); - props.put(prefix + AutoTimerProperty, new Boolean(autoTimer).toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - PropUtils.setI18NPropertyInfo(i18n, list, TimerLocationLayer.class, UpdateTimerIntervalProperty, "Timer interval", - "Number of milliseconds for automatic file reloading.", null); - - PropUtils.setI18NPropertyInfo(i18n, list, TimerLocationLayer.class, AutoTimerProperty, "Auto Timer", - "Flag to start/stop timer automatically when layer is on map.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - - return list; - } - - /** - * Sets whether the timer should automatically be turned on and off when the - * layer is added and removed from the map. - *

- * - * If the layer is not visible, the timer may be started or stopped when - * this method is called. If the autoTimer is turned off, and the layer has - * received a projection before, the timer is turned on. If the autoTimer is - * on, the timer will be stopped. - */ - public void setAutoTimer(boolean value) { - autoTimer = value; - if (autoTimerButton != null) { - autoTimerButton.setSelected(getAutoTimer()); - } - - if (!isVisible()) { - if (!value && getProjection() != null) { - timer.restart(); - } else if (value) { - timer.stop(); - } - } - } - - public boolean getAutoTimer() { - return autoTimer; - } - - /** - * Get the timer being used for automatic updates. May be null if a timer is - * not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, you can set - * the timer to do that. Set it to null to disable it. - */ - public void setTimer(Timer t) { - if (timer != null) { - timer.stop(); - } - - timer = t; - updateTimerButton(); - } - - /** - * What to do when the timer goes off. - */ - public void timerPing() { - reloadData(); - if (isVisible()) { - doPrepare(); - } - } - - /** - * Creates a timer with the current updateInterval and calls setTimer(). - */ - public void createTimer() { - Timer t = new Timer(updateInterval, new ActionListener() { - public void actionPerformed(ActionEvent ae) { - timerPing(); - } - }); - - t.setInitialDelay(0); - setTimer(t); - } - - /** - * The delay between timer pulses, in milliseconds. Default is 10 seconds. - */ - protected int updateInterval = 10000; - - /** - * Set how often the timer calls timerPing. If less than or equal to zero, - * the timer will be stopped, but the interval will not be affected. - */ - public void setUpdateInterval(int delay) { - if (delay > 0) { - updateInterval = delay; - if (timer == null) { - createTimer(); - } - timer.setDelay(updateInterval); - if (timer.isRunning()) { - timer.restart(); - } - } else if (timer != null) { - timer.stop(); - } - updateTimerButton(); - } - - public int getUpdateInterval() { - return updateInterval; - } - - /** - * Enable the timer button if there is a timer, check it on if the timer is - * running. - */ - protected void updateTimerButton() { - if (timerButton != null) { - timerButton.setEnabled(timer != null); - timerButton.setSelected(timer != null && timer.isRunning()); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/URLRasterLocation.java b/src/core/src/main/java/com/bbn/openmap/layer/location/URLRasterLocation.java deleted file mode 100644 index 52197b0af..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/URLRasterLocation.java +++ /dev/null @@ -1,314 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/URLRasterLocation.java,v $ -// $RCSfile: URLRasterLocation.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location; - -/* Java Core */ -import java.net.URL; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.util.PropUtils; - -/** - * A Location that takes an URL for an image and creates a Raster for a Location - * marker. The URL should be the contents of an image file (gif, jpeg) that an - * ImageIcon object can use to create an Image object. The string for an icon - * can be a path to a resource, file or URL, and the URLRasterLocation will - * convert it to a URL. - */ -public class URLRasterLocation - extends Location { - /** The spacing between the label and the outside of the image. */ - public int SPACING = 0; - - /** - * A constructor to enable creation of subclasses. - */ - public URLRasterLocation() { - } - - /** - * Create a URLRasterLocation at a latitude/longitude location. - * - * @param latitude latitide in decimal degrees - * @param longitude longitude in decimal degrees. - * @param name the label for the location. - * @param iconURL a string to a URL for an image - */ - public URLRasterLocation(double latitude, double longitude, String name, String iconURL) { - super(latitude, longitude, name, getIconRaster(latitude, longitude, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - - } - - /** - * Create a URLRasterLocation at a latitude/longitude location. - * - * @param latitude latitide in decimal degrees - * @param longitude longitude in decimal degrees. - * @param name the label for the location. - * @param iconURL a URL for an image - */ - public URLRasterLocation(double latitude, double longitude, String name, URL iconURL) { - super(latitude, longitude, name, getIconRaster(latitude, longitude, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - - } - - /** - * Create a URLRasterLocation at a screen x/y location. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param name the label for the location. - * @param iconURL a String for a URL for an image - */ - public URLRasterLocation(int x, int y, String name, String iconURL) { - super(x, y, name, getIconRaster(x, y, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create a URLRasterLocation at a screen x/y location. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param name the label for the location. - * @param iconURL a URL for an image - */ - public URLRasterLocation(int x, int y, String name, URL iconURL) { - super(x, y, name, getIconRaster(x, y, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create a URLRasterLocation at a lat/lon with a x/y pixel offset. - * - * @param latitude latitude in decimal degrees - * @param longitude longitude in decimal degrees. - * @param xOffset horizontal pixel screen location from the longitude map - * point. - * @param yOffset vertical pixel screen location, from the latitude map - * point. - * @param name the label for the location. - * @param iconURL a String for a URL for an image - */ - public URLRasterLocation(double latitude, double longitude, int xOffset, int yOffset, String name, String iconURL) { - super(latitude, longitude, xOffset, yOffset, name, getIconRaster(latitude, longitude, xOffset, yOffset, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create a URLRasterLocation at a lat/lon location with a screen x/y offset. - * - * @param latitude latitude in decimal degrees - * @param longitude longitude in decimal degrees. - * @param xOffset horizontal pixel screen location from the longitude map - * point. - * @param yOffset vertical pixel screen location, from the latitide map - * point. - * @param name the label for the location. - * @param iconURL a URL for an image - */ - public URLRasterLocation(double latitude, double longitude, int xOffset, int yOffset, String name, URL iconURL) { - super(latitude, longitude, xOffset, yOffset, name, getIconRaster(latitude, longitude, xOffset, yOffset, iconURL)); - - if (location instanceof OMRaster) { - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Create an OMRaster at a latitude/longitude, using an image URL. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param iconURL a URL for an image - */ - public static OMRaster getIconRaster(double lat, double lon, String iconURL) { - URL url = getIconRasterURL(iconURL); - if (url == null) - return null; - - return getIconRaster(lat, lon, url); - } - - /** - * Create an OMRaster at a latitude/longitude, using an image URL. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param iconURL a URL for an image - */ - public static OMRaster getIconRaster(double lat, double lon, URL iconURL) { - ImageIcon icon = new ImageIcon(iconURL); - - return new OMScalingIcon(lat, lon, icon); - } - - /** - * Create an OMRaster at a latitude/longitude, using an image URL. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param iconURL a String for a URL for an image - */ - public static OMRaster getIconRaster(int x, int y, String iconURL) { - URL url = getIconRasterURL(iconURL); - if (url == null) - return null; - - return getIconRaster(x, y, url); - } - - /** - * Create an OMRaster at an x, y screen location, using an image URL. - * - * @param x horizontal pixel screen location from the the left side of the - * map. - * @param y vertical pixel screen location, from the top of the map. - * @param iconURL a URL for an image - */ - public static OMRaster getIconRaster(int x, int y, URL iconURL) { - ImageIcon icon = new ImageIcon(iconURL); - - int offX = icon.getIconWidth() / 2; - int offY = icon.getIconHeight() / 2; - return new OMRaster(x - offX, y - offY, icon); - } - - /** - * Create an OMRaster at a latitude/longitude with an x/y pixel offset, using an image URL. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param x horizontal pixel screen location from the longitude map point. - * @param y vertical pixel screen location, from the latitide map point. - * @param iconURL a String for URL for an image - */ - public static OMRaster getIconRaster(double lat, double lon, int x, int y, String iconURL) { - URL url = getIconRasterURL(iconURL); - if (url == null) - return null; - - return getIconRaster(lat, lon, x, y, url); - } - - /** - * Create an OMRaster at a latitude/longitude, from a image URL. - * - * @param lat latitide in decimal degrees - * @param lon longitude in decimal degrees. - * @param x horizontal pixel screen location from the longitude map point. - * @param y vertical pixel screen location, from the latitide map point. - * @param iconURL a URL for an image - */ - public static OMRaster getIconRaster(double lat, double lon, int x, int y, URL iconURL) { - ImageIcon icon = new ImageIcon(iconURL); - - return new OMScalingIcon(lat, lon, x, y, icon, Float.MAX_VALUE); - } - - /** - * Create an ImageIcon from a String to an image URL. - * - * @param iconURL can be a path to a resource, file or URL. - */ - public static URL getIconRasterURL(String iconURL) { - try { - return PropUtils.getResourceOrFileOrURL(null, iconURL); - } catch (java.net.MalformedURLException mue) { - throw new com.bbn.openmap.util.HandleError(mue); - } - } - - /** - * Given a new latitude/longitude, reposition the graphic and label. - */ - public void setGraphicLocations(double latitude, double longitude) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setLat(latitude); - ras.setLon(longitude); - - label.setLat(latitude); - label.setLon(longitude); - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Given a new x/y screen location, reposition the graphic and label. - */ - public void setGraphicLocations(int x, int y) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setX(x); - ras.setY(y); - - label.setX(x); - label.setY(y); - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } - - /** - * Given a new latitude/longitude with x/y offset points, reposition the - * graphic and label. - */ - public void setGraphicLocations(double latitude, double longitude, int offsetX, int offsetY) { - if (location instanceof OMRaster) { - OMRaster ras = (OMRaster) location; - ras.setLat(latitude); - ras.setLon(longitude); - ras.setX(offsetX); - ras.setY(offsetY); - - label.setLat(latitude); - label.setLon(longitude); - label.setX(offsetX); - label.setY(offsetY); - setHorizontalLabelBuffer((((OMRaster) location).getWidth() / 2) + SPACING); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLinkHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLinkHandler.java deleted file mode 100644 index e96961fa1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLinkHandler.java +++ /dev/null @@ -1,284 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/csv/CSVLinkHandler.java,v $ -// $RCSfile: CSVLinkHandler.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:17:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.csv; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; - -import com.bbn.openmap.layer.location.Link; -import com.bbn.openmap.layer.location.Location; -import com.bbn.openmap.layer.location.URLRasterLocation; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.DataOrganizer; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * The CSVLinkHandler is designed to let you put data on the map based on - * information from a Comma Separated Value(CSV) file. It's assumed that the - * each row in the file refers to two locations, and that a link is to be shown - * between the two locations. It has the same basic properties as the - * CSVLocationHandler, with allowances for extra lat/lon per record to handle - * the other side of the link/line. - * - *

- * The individual fields must not have leading whitespace. - * - *

- * The locationFile property should contain a URL referring to the file. This - * can take the form of file:/myfile.csv for a local file or - * http://somehost.org/myfile.csv for a remote file - * - * If there is a lat/lon index, and a lat2/lon2 index, then the links' endpoints - * are in the link file. - *

- * - * The Link CSV file has to have certain fields, and the column number of those - * fields are set in the properties: - * - *

- * 
- *          # latitude and longitude indexes of the link end points.  The first two are the same as CSVLocationHandler.
- *          linkMarkerName.latIndex=column_number
- *          linkMarkerName.lonIndex=column_number
- *          linkMarkerName.lat2Index=column_number
- *          linkMarkerName.lon2Index=column_number
- *          
- *          #plus all the other optional properties. The marker parameters will work on the link OMGraphics.
- * 
- * 
- * - *

- * TODO: update the quadtree used to instead use a - * com.bbn.openmap.geo.ExtentIndex, so that lines that bisect the map will - * appear. Right now, one of the endpoints of the line has to be in the map - * window in order for the link to be displayed, and that's not quite right. - */ -public class CSVLinkHandler extends CSVLocationHandler { - - // ////////////////////// - // Link Variables - - /** - * Property to use to designate the column of the link file to use as the - * latitude of end "2". - */ - public static final String Lat2IndexProperty = "lat2Index"; - /** - * Property to use to designate the column of the link file to use as the - * longitude of end "2". - */ - public static final String Lon2IndexProperty = "lon2Index"; - - /** The names of the various link types on the map. Not used. */ - /** Index of column in CSV to use as latitude2 of link. */ - protected int lat2Index = -1; - /** Index of column in CSV to use as longitude2 of link. */ - protected int lon2Index = -1; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public CSVLinkHandler() { - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the CSVLinkHandler. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - - lat2Index = PropUtils.intFromProperties(properties, realPrefix + Lat2IndexProperty, lat2Index); - lon2Index = PropUtils.intFromProperties(properties, realPrefix + Lon2IndexProperty, lon2Index); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + Lat2IndexProperty, (lat2Index != -1 ? Integer.toString(lat2Index) : "")); - props.put(prefix + Lon2IndexProperty, (lon2Index != -1 ? Integer.toString(lon2Index) : "")); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.remove(LatIndexProperty); - list.remove(LonIndexProperty); - - list.put(LatIndexProperty, "The column index, in the location file, of the first node latitude."); - list.put(LonIndexProperty, "The column index, in the location file, of the first node longitude."); - list.put(Lat2IndexProperty, "The column index, in the location file, of the second node latitude."); - list.put(Lon2IndexProperty, "The column index, in the location file, of the second node longitude."); - - return list; - } - - protected boolean checkIndexSettings() { - - if (latIndex == -1 || lonIndex == -1 || lat2Index == -1 || lon2Index == -1) { - logger.warning("CSVLocationHandler: createData(): Index properties for Lat/Lon/Name are not set properly! lat index:" - + latIndex + ", lon index:" + lonIndex); - return false; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLinkHandler: Reading File:" + locationFile + " lat1Index: " + latIndex - + " lon1Index: " + lonIndex + " lat2Index: " + lat2Index + " lon2Index: " - + lon2Index); - } - - return true; - } - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - *

- * In this case, the palette widget only contains one button, which reloads - * the data files for the layer. - *

- * - * @return Component object representing the palette widgets. - */ - public Component getGUI() { - JButton rereadFilesButton; - JCheckBox showCSVLinkCheck; - - showCSVLinkCheck = new JCheckBox("Show Links", isShowLocations()); - showCSVLinkCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox locationCheck = (JCheckBox) ae.getSource(); - setShowLocations(locationCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler::actionPerformed showLocations is " - + isShowLocations()); - } - getLayer().repaint(); - } - }); - - rereadFilesButton = new JButton("Re-Read Data File"); - rereadFilesButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Re-reading Locations file"); - } - quadtree = null; - getLayer().doPrepare(); - } - }); - Box box = Box.createVerticalBox(); - box.add(showCSVLinkCheck); - box.add(rereadFilesButton); - return box; - } - - /** - * This is the method called by create data with a row's worth of - * information stuffed in the record List. The indexes set in the properties - * should describe what each entry is. - * - * @param recordList a record/row of data from the csv file. - * @param qt the Quadtree to add the Location object, created from the row - * contents. - */ - protected void createLocation(List recordList, QuadTree qt) { - - String name = tokenToString(recordList, nameIndex, ""); - double lat = tokenToDouble(recordList, latIndex, 0.0); - double lon = tokenToDouble(recordList, lonIndex, 0.0, eastIsNeg); - String iconURL = tokenToString(recordList, iconIndex, defaultIconURL); - - double lat2 = tokenToDouble(recordList, lat2Index, 0.0); - double lon2 = tokenToDouble(recordList, lon2Index, 0.0, eastIsNeg); - - Link link = new Link(lat, lon, lat2, lon2, "No details"); - getLocationDrawingAttributes().setTo(link); - - link.setLocationHandler(CSVLinkHandler.this); - - // What we really want to do is get the - // locationDrawingAttributes and set them on the link. - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLinkHandler: " + link.getDetails()); - } - - qt.put(lat, lon, link); - qt.put(lat2, lon2, link); - - qt.put(lat, lon, createLocation(lat, lon, name, iconURL, recordList)); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLocationHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLocationHandler.java deleted file mode 100644 index 8af42aa1a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/CSVLocationHandler.java +++ /dev/null @@ -1,771 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/csv/CSVLocationHandler.java,v $ -// $RCSfile: CSVLocationHandler.java,v $ -// $Revision: 1.12 $ -// $Date: 2005/08/09 18:17:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.csv; - -/* Java */ -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; - -import com.bbn.openmap.layer.location.AbstractLocationHandler; -import com.bbn.openmap.layer.location.BasicLocation; -import com.bbn.openmap.layer.location.Location; -import com.bbn.openmap.layer.location.LocationCBMenuItem; -import com.bbn.openmap.layer.location.LocationHandler; -import com.bbn.openmap.layer.location.LocationLayer; -import com.bbn.openmap.layer.location.LocationMenuItem; -import com.bbn.openmap.layer.location.URLRasterLocation; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.CSVTokenizer; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * The CSVLocationLayer is a LocationHandler designed to let you put data on the - * map based on information from a Comma Separated Value(CSV) file. It's assumed - * that the each row in the file refers to a certain location, and that location - * contains a name label, a latitude and a longitude (both in decimal degrees). - * - *

- * The individual fields must not have leading whitespace. - * - *

- * The CSVLocationLayer gives you some basic functionality. The properties file - * lets you set defaults on whether to draw the locations and the names by - * default. For crowded layers, having all the names displayed might cause a - * cluttering problem. In gesture mode, OpenMap will display the name of each - * location as the mouse is passed over it. Pressing the left mouse button over - * a location brings up a popup menu that lets you show/hide the name label, and - * also to display the entire row contents of the location CSV file in a Browser - * window that OpenMap launches. - * - *

- * If you want to extend the functionality of this LocationHandler, there are a - * couple of methods to focus your changes: The setProperties() method lets you - * add properties to set from the properties file. The createData() method, by - * default, is a one-time method that creates the graphic objects based on the - * CSV data. By modifying these methods, and creating a different combination - * graphic other than the CSVLocation, you can create different layer effects - * pretty easily. - * - *

- * The locationFile property should contain a URL referring to the file. This - * can take the form of file:/myfile.csv for a local file or - * http://somehost.org/myfile.csv for a remote file. - * - *

- * In the openmap.properties file (for instance):
- * - *

- * 
- * 
- * 
- *       # In the section for the LocationLayer:
- *       locationLayer.locationHandlers=csvlocationhandler
- *       
- *       csvlocationhandler.class=com.bbn.openmap.layer.location.csv.CSVLocationHandler
- *       csvlocationhandler.locationFile=/data/worldpts/WorldLocs_point.csv
- *       csvlocationhandler.csvFileHasHeader=true
- *       csvlocationhandler.showNames=false
- *       csvlocationhandler.showLocations=true
- *       csvlocationhandler.nameIndex=0
- *       csvlocationhandler.latIndex=8
- *       csvlocationhandler.lonIndex=10
- *       # Optional property, if you have a column in the file for URLs of
- *       # images to use for an icon.
- *       csvlocationhandler.iconIndex=11
- *       # Optional property, URL of image to use as marker for all entries in
- *       # csv file without a URL listed at the iconIndex.
- *       csvlocationhandler.defaultIconURL=/data/symbols/default.gif
- *       
- *       # optional property, if you have a column in the file for circle radius values.  Ignored if iconIndex set.
- *       csvlocationhandler.radiusIndex=12
- *       # optional property, if defined as Length value (miles, ft, yd, m, km, nm, dm, deg, rad).  Radius will be interpreted as pixels if units undefined.
- *       csvlocationhandler.radiusUnits=m
- *       
- *       # Optional property, if the eastern hemisphere longitudes are negative.  False by default.
- *       csvlocationhandler.eastIsNeg=false
- *       
- *       # CSVLocationHandler has been updated to have regular DrawingAttribute properties for both name and location.
- *      csvlocationhandler.name.lineColor=FF008C54
- *      csvlocationhandler.location.lineColor=FFFF0000
- *      csvlocationhandler.location.fillColor=FFaaaaaa
- *      csvlocationhandler.location.pointRadius=3
- *      csvlocationhandler.location.pointOval=true
- *      
- *      # optional, can be used if you override createLocation and need access to varying rendering attributes.
- *      # ra1, ra2 and ra3 would be used as keys in renderAttributes map.  All GraphicAttributes properties are available, not
- *      # just lineColor.
- *     
- *      csvlocationhandler.renderAttributesList=ra1 ra2 ra3
- *      csvlocationhandler.ra1.lineColor=0xFFFF0000
- *      csvlocationhandler.ra2.lineColor=0xFF00FF00
- *      csvlocationhandler.ra3.lineColor=0xFF00FFFF
- * 
- * 
- */ -public class CSVLocationHandler extends AbstractLocationHandler implements LocationHandler { - - public final static int UNDEFINED = -1; - - /** The path to the primary CSV file holding the locations. */ - protected String locationFile; - /** The property describing the locations of location data. */ - public static final String LocationFileProperty = "locationFile"; - /** Set if the CSVFile has a header record. Default is false. */ - public final static String csvHeaderProperty = "csvFileHasHeader"; - /** The storage mechanism for the locations. */ - protected QuadTree quadtree = null; - - /** The property describing whether East is a negative value. */ - public static final String eastIsNegProperty = "eastIsNeg"; - /** Are east values really negative with this file? */ - protected boolean eastIsNeg = false; - /** - * Flag that specifies that the first line consists of header information, - * and should not be mapped to a graphic. - */ - protected boolean csvHasHeader = false; - - // ///////////////////// - // Name label variables - - /** Index of column in CSV to use as name of location. */ - protected int nameIndex = UNDEFINED; - /** - * Property to use to designate the column of the CSV file to use as a name. - */ - public static final String NameIndexProperty = "nameIndex"; - - // ////////////////////// - // Location Variables - - /** - * Property to use to designate the column of the CSV file to use as the - * latitude. - */ - public static final String LatIndexProperty = "latIndex"; - /** - * Property to use to designate the column of the CSV file to use as the - * longitude. - */ - public static final String LonIndexProperty = "lonIndex"; - /** - * Property to use to designate the column of the CSV file to use as an icon - * URL - */ - public static final String IconIndexProperty = "iconIndex"; - /** - * Property used to designate the column in CSV file to use for circle - * radius. Ignored if IconIndexProperty is defined. - */ - public static final String RadiusIndexProperty = "radiusIndex"; - /** - * Property used to designate the units of radius values in CSV file. If - * undefined, default is pixels. Other values should match Length - * abbreviations (miles, ft, yd, m, km, nm, dm, deg, rad) - */ - public static final String RadiusUnitsProperty = "radiusUnits"; - - /** - * Property to set an URL for an icon image to use for all the locations - * that don't have an image defined in the csv file, or if there isn't an - * icon defined in the csv file for any of the locations and you want them - * all to have the same icon. - */ - public static final String DefaultIconURLProperty = "defaultIconURL"; - - /** Index of column in CSV to use as latitude of location. */ - protected int latIndex = UNDEFINED; - /** Index of column in CSV to use as longitude of location. */ - protected int lonIndex = UNDEFINED; - /** Index of column in CSV to use as URL of the icon. */ - protected int iconIndex = UNDEFINED; - /** Index of column in CSV to use as radius of circle of location. */ - protected int radiusIndex = UNDEFINED; - /** Units of radius. */ - protected Length radiusUnits; - - protected String defaultIconURL = null; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public CSVLocationHandler() { - } - - public boolean isDefined(int indexVal) { - return indexVal != UNDEFINED; - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the CSVLocationHandler. - * - * @param prefix - * string prefix used in the properties file for this layer. - * @param properties - * the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - locationFile = properties.getProperty(prefix + LocationFileProperty); - - latIndex = PropUtils.intFromProperties(properties, prefix + LatIndexProperty, latIndex); - lonIndex = PropUtils.intFromProperties(properties, prefix + LonIndexProperty, lonIndex); - iconIndex = PropUtils.intFromProperties(properties, prefix + IconIndexProperty, iconIndex); - nameIndex = PropUtils.intFromProperties(properties, prefix + NameIndexProperty, nameIndex); - eastIsNeg = PropUtils.booleanFromProperties(properties, prefix + eastIsNegProperty, eastIsNeg); - defaultIconURL = properties.getProperty(prefix + DefaultIconURLProperty); - if (defaultIconURL != null && defaultIconURL.trim().length() == 0) { - // If it's empty, it should be null, otherwise it causes - // confusion later when the empty string can't be - // interpreted as a valid URL to an image file. - defaultIconURL = null; - } - - radiusIndex = PropUtils.intFromProperties(properties, prefix + RadiusIndexProperty, radiusIndex); - String radiusUnitsString = properties.getProperty(prefix + RadiusUnitsProperty); - if (radiusUnitsString != null && radiusUnitsString.trim().length() != 0) { - radiusUnits = Length.get(radiusUnitsString.trim()); - } - - csvHasHeader = PropUtils.booleanFromProperties(properties, prefix + csvHeaderProperty, csvHasHeader); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler indexes:\n latIndex = " + latIndex + "\n lonIndex = " + lonIndex - + "\n nameIndex = " + nameIndex + "\n has header = " + csvHasHeader); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props - * a Properties object to load the PropertyConsumer properties - * into. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + "class", this.getClass().getName()); - props.put(prefix + LocationFileProperty, PropUtils.unnull(locationFile)); - - props.put(prefix + eastIsNegProperty, new Boolean(eastIsNeg).toString()); - props.put(prefix + csvHeaderProperty, new Boolean(csvHasHeader).toString()); - props.put(prefix + NameIndexProperty, (isDefined(nameIndex) ? Integer.toString(nameIndex) : "")); - props.put(prefix + LatIndexProperty, (isDefined(latIndex) ? Integer.toString(latIndex) : "")); - props.put(prefix + LonIndexProperty, (isDefined(lonIndex) ? Integer.toString(lonIndex) : "")); - props.put(prefix + IconIndexProperty, (isDefined(iconIndex) ? Integer.toString(iconIndex) : "")); - props.put(prefix + DefaultIconURLProperty, PropUtils.unnull(defaultIconURL)); - props.put(prefix + RadiusIndexProperty, (isDefined(radiusIndex) ? Integer.toString(radiusIndex) : "")); - if (radiusUnits != null) { - props.put(prefix + RadiusUnitsProperty, radiusUnits.getAbbr()); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list - * a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put("class" + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - list.put(LocationFileProperty, "URL of file containing location information."); - list.put(LocationFileProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - list.put(eastIsNegProperty, "Flag to note that negative latitude are over the eastern hemisphere."); - list.put(eastIsNegProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(NameIndexProperty, "The column index, in the location file, of the location label text."); - list.put(LatIndexProperty, "The column index, in the location file, of the latitudes."); - list.put(LonIndexProperty, "The column index, in the location file, of the longitudes."); - list.put(IconIndexProperty, "The column index, in the location file, of the icon for locations (optional)."); - list.put(DefaultIconURLProperty, - "The URL of an image file to use as a default for the location markers (optional)."); - list.put(csvHeaderProperty, - "Flag to note that the first line in the csv file is a header line and should be ignored."); - list.put(RadiusIndexProperty, - "The column index, in the location file, of the radius values for locations (optional)"); - list.put(RadiusUnitsProperty, - "The abbreviation of Length to paramatize radius values (miles, ft, yd, m, km, nm, dm, deg, rad)"); - - return list; - } - - public void reloadData() { - quadtree = createData(); - } - - protected boolean checkIndexSettings() { - if (!isDefined(latIndex) || !isDefined(lonIndex)) { - logger.warning( - "CSVLocationHandler: createData(): Index properties for Lat/Lon/Name are not set properly! lat index:" - + latIndex + ", lon index:" + lonIndex); - return false; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler: Reading File:" + locationFile + " NameIndex: " + nameIndex + " latIndex: " - + latIndex + " lonIndex: " + lonIndex + " iconIndex: " + iconIndex + " eastIsNeg: " + eastIsNeg); - } - - return true; - } - - /** - * Look at the CSV file and create the QuadTree holding all the Locations. - */ - protected QuadTree createData() { - - QuadTree qt = new QuadTree(90.0f, -180.0f, -90.0f, 180.0f, 100, 50f); - - if (!checkIndexSettings()) { - return null; - } - - int lineCount = 0; - Object token = null; - // TokenDecoder tokenHandler = getTokenDecoder(); - - // readHeader should be set to true if the first line has - // been read, or if the csvHasHeader is false. - boolean readHeader = !csvHasHeader; - - try { - - // This lets the property be specified as a file name - // even if it's not specified as file:/ in - // the properties file. - - URL csvURL = PropUtils.getResourceOrFileOrURL(null, locationFile); - if (csvURL != null) { - - BufferedReader streamReader = new BufferedReader(new InputStreamReader(csvURL.openStream())); - CSVTokenizer csvt = new CSVTokenizer(streamReader); - - token = csvt.token(); - - List recordList = Collections.synchronizedList(new ArrayList(10)); - - while (!csvt.isEOF(token)) { - int i = 0; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler| Starting a line | have" + (readHeader ? " " : "n't ") - + "read header"); - } - - // Prepare it for the new row/record - recordList.clear(); - - while (!csvt.isNewline(token) && !csvt.isEOF(token)) { - - if (readHeader) { - // tokenHandler.handleToken(token, i); - recordList.add(token); - } - - token = csvt.token(); - // For some reason, the check above doesn't always - // work - if (csvt.isEOF(token)) { - break; - } - i++; - } - - if (!readHeader) { - readHeader = true; - } else { - lineCount++; - createLocation(recordList, qt); - // tokenHandler.createAndAddObjectFromTokens(qt); - } - token = csvt.token(); - } - - csvt.close(); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("couldn't figure out file: " + locationFile); - } - } - } catch (java.io.IOException ioe) { - throw new com.bbn.openmap.util.HandleError(ioe); - } catch (ArrayIndexOutOfBoundsException aioobe) { - throw new com.bbn.openmap.util.HandleError(aioobe); - } catch (NumberFormatException nfe) { - throw new com.bbn.openmap.util.HandleError(nfe); - } catch (ClassCastException cce) { - logger.warning( - "Problem reading entries in " + locationFile + ", check your index settings, first column = 0."); - throw new com.bbn.openmap.util.HandleError(cce); - } catch (NullPointerException npe) { - logger.warning("Problem reading location file, check " + locationFile); - throw new com.bbn.openmap.util.HandleError(npe); - } catch (java.security.AccessControlException ace) { - throw new com.bbn.openmap.util.HandleError(ace); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler | Finished File:" + locationFile + ", read " + lineCount + " locations"); - } - - if (lineCount == 0 && readHeader) { - logger.fine( - "CSVLocationHandler has read file, but didn't find any data.\n Check file for a header line, and make sure that the\n properties (csvFileHasHeader) is set properly for this CSVLocationHandler. Trying again without header..."); - csvHasHeader = !csvHasHeader; - return createData(); - } - - return qt; - } - - /** - * This is the method called by create data with a row's worth of - * information stuffed in the record List. The indexes set in the properties - * should describe what each entry is. - * - * @param recordList - * a record/row of data from the csv file. - * @param qt - * the Quadtree to add the Location object, created from the row - * contents. - */ - protected void createLocation(List recordList, QuadTree qt) { - - String name = tokenToString(recordList, nameIndex, ""); - double lat = tokenToDouble(recordList, latIndex, 0.0); - double lon = tokenToDouble(recordList, lonIndex, 0.0, eastIsNeg); - String iconURL = tokenToString(recordList, iconIndex, defaultIconURL); - - qt.put(lat, lon, createLocation(lat, lon, name, iconURL, recordList)); - } - - /** - * When a new Location object needs to be created from data read in the CSV - * file, this method is called. This method lets you extend the - * CSVLocationLayer and easily set what kind of Location objects to use - * based on file contents. The lat/lon/name/icon path have already been - * decoded from the record List. - * - * @param lat - * latitude of location, decimal degrees. - * @param lon - * longitude of location, decimal degrees. - * @param name - * the label of the location. - * @param iconURL - * the String for a URL for an icon. Can be null. - * @param recordList - * the original List of Objects in case other entries in the row - * should affect how the Location object is configured. - * @return Location object for lat/lon/name/iconURL. - */ - protected Location createLocation(double lat, double lon, String name, String iconURL, List recordList) { - - Location loc; - - if (iconURL != null) { - // This will turn into a regular location if something goes wrong - // with iconURL. - loc = new URLRasterLocation(lat, lon, name, iconURL); - } else if (isDefined(radiusIndex)) { - double radius = tokenToDouble(recordList, radiusIndex, 1.0); - - OMCircle circle; - - if (radiusUnits != null) { - circle = new OMCircle(lat, lon, radius, radiusUnits); - } else { - int wh = (int) radius * 2; - circle = new OMCircle(lat, lon, wh, wh); - } - - loc = new BasicLocation(lat, lon, name, circle); - } else { - loc = new BasicLocation(lat, lon, name, null); - } - - // let the layer handler default set these initially... - loc.setShowName(isShowNames()); - loc.setShowLocation(isShowLocations()); - - loc.setLocationHandler(this); - getLocationDrawingAttributes().setTo(loc.getLocationMarker()); - getNameDrawingAttributes().setTo(loc.getLabel()); - - loc.setDetails(name + " is at lat: " + lat + ", lon: " + lon); - - if (iconURL != null) { - loc.setDetails(loc.getDetails() + " icon: " + iconURL); - } - - logger.fine("CSVLocationHandler " + loc.getDetails()); - - return loc; - } - - /** - * Scope object to String. If anything goes wrong the default is returned. - * - * @param recordList - * the List for the record. - * @param index - * the index of the object to fetch. - * @param def - * default value - * @return String value - */ - protected String tokenToString(List recordList, int index, String def) { - try { - Object obj = recordList.get(index); - if (obj != null) { - String str = obj.toString(); - if (!str.isEmpty()) { - return str; - } - } - } catch (Exception e) { - // just return default - } - return def; - } - - /** - * Scope object to double if it's a number, or return default. If anything - * goes wrong the default is returned. - * - * @param recordList - * the List for the record. - * @param index - * the index of the object to fetch. - * @param def - * default value - * @return double value - */ - protected double tokenToDouble(List recordList, int index, double def) { - try { - Object obj = recordList.get(index); - if (obj instanceof Double) { - return ((Double) obj).doubleValue(); - } - } catch (Exception e) { - - } - - return def; - } - - /** - * Scope object to double if it's a number, or return default. Swap the sign - * if needed, if east is supposed to be a negative number. If anything goes - * wrong the default is returned. - * - * @param recordList - * the List for the record. - * @param index - * the index of the object to fetch. - * @param def - * default value - * @param swapSign - * multiply value by -1, say, if you know that the file has - * negative values for eastern hemisphere longitudes (hey, I've - * seen it). - * @return double value - */ - protected double tokenToDouble(List recordList, int index, double def, boolean swapSign) { - Double ret = tokenToDouble(recordList, index, def); - return swapSign ? -1 * ret : ret; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method calls to build the OMGraphicList to draw. - */ - public OMGraphicList get(double nwLat, double nwLon, double seLat, double seLon, OMGraphicList graphicList) { - - if (graphicList == null) { - graphicList = new OMGraphicList(); - graphicList.setTraverseMode(OMGraphicList.FIRST_ADDED_ON_TOP); - } - - // IF the quadtree has not been set up yet, do it! - if (quadtree == null) { - logger.fine("CSVLocationHandler: Figuring out the locations and names! (This is a one-time operation!)"); - quadtree = createData(); - } - - if (quadtree != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler|CSVLocationHandler.get() ul.lon = " + nwLon + " lr.lon = " + seLon - + " delta = " + (seLon - nwLon)); - } - - List hits = new ArrayList(); - quadtree.get(nwLat, nwLon, seLat, seLon, hits); - - graphicList.addAll(hits); - } - - return graphicList; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.location.LocationHandler#getItemsForPopupMenu(com - * .bbn.openmap.layer.location.Location) - */ - public List getItemsForPopupMenu(Location loc) { - List menuItems = new ArrayList(); - menuItems.add(new LocationCBMenuItem(LocationHandler.showname, loc)); - menuItems.add(new LocationMenuItem(showdetails, loc)); - return menuItems; - } - - protected Box box = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public Component getGUI() { - if (box == null) { - JCheckBox showLocationCheck, showNameCheck, forceGlobalCheck; - JButton rereadFilesButton; - - showLocationCheck = new JCheckBox("Show Locations", isShowLocations()); - showLocationCheck.setActionCommand(showLocationsCommand); - showLocationCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox locationCheck = (JCheckBox) ae.getSource(); - setShowLocations(locationCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler::actionPerformed showLocations is " + isShowLocations()); - } - getLayer().repaint(); - } - }); - showLocationCheck.setToolTipText("Show location markers on the map."); - - showNameCheck = new JCheckBox("Show Location Names", isShowNames()); - showNameCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox namesCheck = (JCheckBox) ae.getSource(); - setShowNames(namesCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("CSVLocationHandler::actionPerformed showNames is " + isShowNames()); - } - - LocationLayer ll = getLayer(); - if (namesCheck.isSelected() && ll.getDeclutterMatrix() != null && ll.getUseDeclutterMatrix()) { - ll.doPrepare(); - } else { - ll.repaint(); - } - } - }); - showNameCheck.setToolTipText("Show location names on the map."); - - forceGlobalCheck = new JCheckBox("Override Location Settings", isForceGlobal()); - forceGlobalCheck.setActionCommand(forceGlobalCommand); - forceGlobalCheck.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox forceGlobalCheck = (JCheckBox) ae.getSource(); - setForceGlobal(forceGlobalCheck.isSelected()); - getLayer().repaint(); - } - }); - forceGlobalCheck.setToolTipText( - "Make these settings override those set
on the individual map objects."); - - rereadFilesButton = new JButton("Reload Data From Source"); - rereadFilesButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Re-reading Locations file"); - } - quadtree = null; - getLayer().doPrepare(); - } - }); - rereadFilesButton.setToolTipText( - "Reload the data file, and put these settings
on the individual map objects."); - - box = Box.createVerticalBox(); - box.add(showLocationCheck); - box.add(showNameCheck); - box.add(forceGlobalCheck); - box.add(rereadFilesButton); - } - return box; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/package.html b/src/core/src/main/java/com/bbn/openmap/layer/location/csv/package.html deleted file mode 100644 index 707262ad8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/csv/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Provides a LocationHandler that can retrieve data from CSV -(comma-separated values) files. For use with the location layer. - - @see com.bbn.openmap.layer.location - @see com.bbn.openmap.layer.location.LocationLayer - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/db/DBLocationHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/location/db/DBLocationHandler.java deleted file mode 100644 index 73396b3dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/db/DBLocationHandler.java +++ /dev/null @@ -1,465 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/db/DBLocationHandler.java,v $ -// $RCSfile: DBLocationHandler.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:06:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.db; - -/* Java */ -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; - -import com.bbn.openmap.layer.location.AbstractLocationHandler; -import com.bbn.openmap.layer.location.ByteRasterLocation; -import com.bbn.openmap.layer.location.Location; -import com.bbn.openmap.layer.location.LocationCBMenuItem; -import com.bbn.openmap.layer.location.LocationHandler; -import com.bbn.openmap.layer.location.LocationMenuItem; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * The DBLocationLayer is a LocationHandler designed to let you put data on the - * map based on information from a Database. The properties file lets you set - * defaults on whether to draw the locations and the names by default. For - * crowded layers, having all the names displayed might cause a cluttering - * problem. In gesture mode, OpenMap will display the name of each location as - * the mouse is passed over it. Pressing the left mouse button over a location - * brings up a popup menu that lets you show/hide the name label, and also to - * display attributes of the location in a Browser window that OpenMap launches. - * - *

- * If you want to extend the functionality of this LocationHandler, there are a - * couple of methods to focus your changes: The setProperties() method lets you - * add properties to set from the properties file. The createData() method, by - * default, is a one-time method that creates the graphic objects based on the - * data. By modifying these methods, and creating a different combination - * graphic other than the default LocationDataRecordSet, you can create - * different layer effects pretty easily. - * - *

- * In the openmap.properties file (for instance): - * - *

- * 
- *  # In the section for the LocationLayer:
- *  locationLayer.locationHandlers=dblocationhandler
- *  
- *  dblocationhandler.class=com.bbn.openmap.layer.location.db.DBLocationHandler
- *  dblocationhandler.locationColor=FF0000
- *  dblocationhandler.nameColor=008C54
- *  dblocationhandler.showNames=false
- *  dblocationhandler.showLocations=true
- *  dblocationhandler.jdbcDriver=oracle.jdbc.driver.OracleDriver
- *  dblocationhandler.jdbcString=jdbc login string
- *  dblocationhandler.userName=username
- *  dblocationhandler.userPassword=password
- *  dblocationhandler.locationQueryString=select statement the data
- *   object needs.  See each Data object (like LocationData) to see what
- *   kind of select statement it needs.
- * 
- * 
- * - * In addition, this particular location handler is using the LocationData - * object to handle the results from the location. - */ -public class DBLocationHandler - extends AbstractLocationHandler - implements LocationHandler, ActionListener { - - /** The storage mechanism for the locations. */ - protected QuadTree quadtree = null; - - // Database variables. - /* - * This String should be completely specified based on which Database is - * being used including username and password. Alternately, username and - * password can be specified by in properties file as jdbc.user=USERNAME - * jdbc.password=PASSWORD - */ - /** String that would be used for making a connection to Database */ - protected String jdbcString = null; - /** Property that should be specified for setting jdbc String */ - public static final String jdbcStringProperty = "jdbcString"; - /** - * This String would be used to load the driver. If this string is null, - * jdbc Connection Manager would try to load the appropriate driver. - */ - protected String jdbcDriver = null; - /** Property to specify jdbc driver to loaded. */ - public static final String jdbcDriverProperty = "jdbcDriver"; - /** User name to be used for connecting to DB. */ - protected String userName = null; - /** Password to be used with for connecting to DB. */ - protected String userPassword = null; - /** Property to specify userName for connecting to Database */ - public static final String userNameProperty = "userName"; - /** Property to specify password for connecting to Database */ - public static final String userPasswordProperty = "userPassword"; - /** Property to specify the query string passed to the database. */ - public static final String locationQueryStringProperty = "locationQueryString"; - - /** - * The string used to query the database for the location information. - */ - protected String locationQueryString = null; - - /** A copy of properties used to construct this Layer */ - protected Properties props; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DBLocationHandler() { - } - - /** - * The properties and prefix are managed and decoded here, for the standard - * uses of the DBLocationHandler. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - prefix = getPropertyPrefix(); - if (prefix != null) { - prefix = prefix + "."; - } else { - prefix = ""; - } - - props = properties; // Save it now. We would need it in future - - jdbcString = properties.getProperty(prefix + jdbcStringProperty); - jdbcDriver = properties.getProperty(prefix + jdbcDriverProperty); - userName = properties.getProperty(prefix + userNameProperty); - userPassword = properties.getProperty(prefix + userPasswordProperty); - - locationQueryString = properties.getProperty(prefix + locationQueryStringProperty); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = getPropertyPrefix(); - if (prefix != null) { - prefix = prefix + "."; - } else { - prefix = ""; - } - - props.put(prefix + "class", this.getClass().getName()); - props.put(prefix + jdbcStringProperty, PropUtils.unnull(jdbcString)); - props.put(prefix + jdbcDriverProperty, PropUtils.unnull(jdbcDriver)); - props.put(prefix + userNameProperty, PropUtils.unnull(userName)); - props.put(prefix + userPasswordProperty, PropUtils.unnull(userPassword)); - props.put(prefix + locationQueryStringProperty, PropUtils.unnull(locationQueryString)); - - // Put the properties in here for the RawDataRecordSet, which - // gets images that can be used for the locations. - props.put(prefix + RawDataRecordSet.tableNameProperty, - PropUtils.unnull(props.getProperty(prefix + RawDataRecordSet.tableNameProperty))); - props.put(prefix + RawDataRecordSet.rawDataColumnNameProperty, - PropUtils.unnull(props.getProperty(prefix + RawDataRecordSet.rawDataColumnNameProperty))); - props.put(prefix + RawDataRecordSet.rawDataKeyColumnNameProperty, - PropUtils.unnull(props.getProperty(prefix + RawDataRecordSet.rawDataKeyColumnNameProperty))); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put("class" + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - list.put(jdbcStringProperty, "JDBC login string"); - list.put(jdbcDriverProperty, "JDBC driver class name"); - list.put(userNameProperty, "User name"); - list.put(userPasswordProperty, "User password"); - list.put(locationQueryStringProperty, "Select statement that the data object needs."); - - list.put(RawDataRecordSet.tableNameProperty, "The name of the table in the database that holds the images."); - list.put(RawDataRecordSet.rawDataColumnNameProperty, - "The name of the column in the table in the database that holds the name (key) of the image."); - list.put(RawDataRecordSet.rawDataKeyColumnNameProperty, - "The name of the column in the table in the database that holds the raw image bytes."); - - return list; - } - - public void reloadData() { - quadtree = createData(); - } - - /** - * Look in the database and create the QuadTree holding all the Locations. - */ - protected QuadTree createData() { - - QuadTree qt = new QuadTree(90.0f, -180.0f, -90.0f, 180.0f, 100, 50f); - ByteRasterLocation loc; - byte bytearr[]; - - if (locationQueryString == null) { - return qt; - } - - // Code for reading from DB and pushing it into QuadTree. - try { - if (jdbcDriver != null) { - Class.forName(getJdbcDriver()); - } - - Connection connection = DriverManager.getConnection(getJdbcString(), getUserName(), getUserPassword()); - - RawDataRecordSet gifdataRS = new RawDataRecordSet(connection, getPropertyPrefix(), props); - - RecordSet locationdataRS = new RecordSet(connection, locationQueryString); - - while (locationdataRS.next()) { - - LocationData ld = new LocationData(locationdataRS); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("DBLocationHandler: location information:\n" + ld); - } - - bytearr = gifdataRS.getRawData(ld.getGraphicName()); - - float lat = ld.getLatitude(); - float lon = ld.getLongitude(); - - loc = new ByteRasterLocation(lat, lon, ld.getCityName(), bytearr); - - loc.setLocationHandler(this); - - // let the layer handler default set these - // initially... - loc.setShowName(isShowNames()); - loc.setShowLocation(isShowLocations()); - - loc.setLocationPaint(getLocationColor()); - loc.getLabel().setLinePaint(getNameColor()); - loc.setDetails(ld.getCityName() + " is at lat: " + lat + ", lon: " + lon); - - qt.put(lat, lon, loc); - - } - - locationdataRS.close(); - connection.close(); - - } catch (SQLException sqlE) { - logger.warning("DBLocationHandler:SQL Exception: " + sqlE.getMessage()); - sqlE.printStackTrace(); - } catch (ClassNotFoundException cnfE) { - logger.warning("DBLocationHandler: Class not found Exception: " + cnfE); - } - - return qt; - } - - public String getJdbcString() { - return jdbcString; - } - - public String getJdbcDriver() { - return jdbcDriver; - } - - public String getUserName() { - return userName; - } - - public String getUserPassword() { - return userPassword; - } - - public Properties getLocationProperties() { - return props; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the location. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - */ - public OMGraphicList get(double nwLat, double nwLon, double seLat, double seLon, - OMGraphicList graphicList) { - - if (graphicList == null) { - graphicList = new OMGraphicList(); - graphicList.setTraverseMode(OMGraphicList.FIRST_ADDED_ON_TOP); - } - - // IF the quadtree has not been set up yet, do it! - if (quadtree == null) { - logger.fine("DBLocationHandler: Figuring out the locations and names! (This is a one-time operation!)"); - quadtree = createData(); - } - - if (quadtree != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("DBLocationHandler|DBLocationHandler.get() ul.lon = " + nwLon + " lr.lon = " + seLon + " delta = " - + (seLon - nwLon)); - } - - Vector vec = new Vector(); - quadtree.get(nwLat, nwLon, seLat, seLon, vec); - - graphicList.addAll(vec); - } - - return graphicList; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.location.LocationHandler#getItemsForPopupMenu(com - * .bbn.openmap.layer.location.Location) - */ - public List getItemsForPopupMenu(Location loc) { - List menuItems = new ArrayList(); - menuItems.add(new LocationCBMenuItem(LocationHandler.showname, loc)); - menuItems.add(new LocationMenuItem(showdetails, loc)); - return menuItems; - } - - /** Box used for constructing the palette widgets */ - protected Box box = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public Component getGUI() { - if (box == null) { - JCheckBox showDBLocationCheck, showNameCheck; - JButton rereadFilesButton; - - showDBLocationCheck = new JCheckBox("Show Locations", isShowLocations()); - showDBLocationCheck.setActionCommand(showLocationsCommand); - showDBLocationCheck.addActionListener(this); - - showNameCheck = new JCheckBox("Show Location Names", isShowNames()); - showNameCheck.setActionCommand(showNamesCommand); - showNameCheck.addActionListener(this); - - rereadFilesButton = new JButton("Reload Data From Source"); - rereadFilesButton.setActionCommand(readDataCommand); - rereadFilesButton.addActionListener(this); - - box = Box.createVerticalBox(); - box.add(showDBLocationCheck); - box.add(showNameCheck); - box.add(rereadFilesButton); - } - return box; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * The Action Listener method, that reacts to the palette widgets actions. - */ - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - if (cmd == showLocationsCommand) { - JCheckBox locationCheck = (JCheckBox) e.getSource(); - setShowLocations(locationCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("DBLocationHandler::actionPerformed showLocations is " + isShowLocations()); - } - getLayer().repaint(); - } else if (cmd == showNamesCommand) { - JCheckBox namesCheck = (JCheckBox) e.getSource(); - setShowNames(namesCheck.isSelected()); - if (logger.isLoggable(Level.FINE)) { - logger.fine("DBLocationHandler::actionPerformed showNames is " + isShowNames()); - } - getLayer().repaint(); - } else if (cmd == readDataCommand) { - logger.fine("DBLocationHandler: Re-reading Locations file"); - quadtree = null; - getLayer().doPrepare(); - } else { - logger.warning("DBLocationHandler: Unknown action command \"" + cmd + "\" in actionPerformed()."); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/db/LocationData.java b/src/core/src/main/java/com/bbn/openmap/layer/location/db/LocationData.java deleted file mode 100644 index e99cb81f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/db/LocationData.java +++ /dev/null @@ -1,109 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/db/LocationData.java,v $ -// $RCSfile: LocationData.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * This class is responsible for retrieving Latitude and Longitude Data from a - * table in a Database given a City/Town name, State. Also it retrieves - * identifier of the object that would be used to represent this City/Town on - * Map. For instance, identifier can be either a url or a name that can be - * looked up somewhere else. - *

- * This class needs the RecordSet to be called with the following query:
- * select CITY (string), STATE (string), GRAPHIC (string, url or graphic name), - * LATITUDE (float), LONGITUDE (float) from LOCATION_TABLE (tablename where data - * is stored)
- * The class is expecting the results in this order. - */ -public class LocationData { - - /* variables that would hold current values of record set */ - protected String cityName, stateName, graphicName; - protected float latitude, longitude; - protected String queryString = null; - - - public LocationData(RecordSet drs) - throws SQLException { - - ResultSet rset = drs.getResultSet(); - - cityName = rset.getString(1); - stateName = rset.getString(2); - graphicName = rset.getString(3); - latitude = rset.getFloat(4); - longitude = rset.getFloat(5); - } - - /** - * @return city name of current record - */ - public String getCityName() { - return cityName; - } - - public String getStateName() { - return stateName; - } - - public String getGraphicName() { - return graphicName; - } - - public float getLatitude() { - return latitude; - } - - public float getLongitude() { - return longitude; - } - - public String getQueryString() { - return queryString; - } - - public void setQueryString(String inQueryString) { - queryString = inQueryString; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Location Data values:\n"); - s.append(" City Name = ").append(cityName).append("\n"); - s.append(" State Name = ").append(stateName).append("\n"); - s.append(" Graphic = ").append(graphicName).append("\n"); - s.append(" Latitude = ").append(latitude).append("\n"); - s.append(" Longitude = ").append(longitude).append("\n"); - return s.toString(); - } - - public static void main(String[] args) { - System.out.println("\n*** LocationData handles results from the following query: ***\n"); - System.out.println(" select CITY (string), STATE (string), GRAPHIC (string, url or graphic name), LATITUDE (float), LONGITUDE (float) from LOCATION_TABLE (tablename where data is stored)\n"); - System.out.println("Note: Column names and tablename should reflect whatever is stored in the database. Data types should match what this class is expecting, in the order listed here.\n"); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/db/RawDataRecordSet.java b/src/core/src/main/java/com/bbn/openmap/layer/location/db/RawDataRecordSet.java deleted file mode 100644 index 7dba44b84..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/db/RawDataRecordSet.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/db/RawDataRecordSet.java,v $ -// $RCSfile: RawDataRecordSet.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.db; - -import java.io.IOException; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Hashtable; -import java.util.Properties; - -/** - * This class is responsible for retrieving Raw Data from a table in a - * Database given a key. Users of this class should provide Database - * connection, Table name, Column name that has the key and column - * name that has the actual data. - *

- * If you are going to use this, there are a couple of properties to - * set:
- * prefix.rawDataTableName=table name
- * prefix.rawDataColumnName=data column name
- * prefix.rawDataKeyColumnName=data key name
- * - */ -public class RawDataRecordSet { - /** Connection object that will be used to retrieve data */ - protected Connection connection; - /** Table name from which data would be retrieved */ - protected String tableName; - /** Column name in the above table that has Raw Data */ - protected String rawDataColumnName; - /** Column name which has the key to lookup above data */ - protected String rawDataKeyColumnName; - - /** - * A hashtable to keep track of the byte arrays, using the key. - * This will reduce the calls to the database. - */ - protected Hashtable byteCache = new Hashtable(); - - public static final String tableNameProperty = "rawDataTableName"; - public static final String rawDataColumnNameProperty = "rawDataColumnName"; - public static final String rawDataKeyColumnNameProperty = "rawDataKeyColumnName"; - - public RawDataRecordSet() {} - - public RawDataRecordSet(Connection inConnection) { - setConnection(inConnection); - } - - public RawDataRecordSet(Connection inconnection, String prefix, - Properties properties) { - - if (prefix != null) { - prefix = prefix + "."; - } else { - prefix = ""; - } - - setConnection(inconnection); - setTableName(properties.getProperty(prefix + tableNameProperty)); - setRawDataColumnName(properties.getProperty(prefix - + rawDataColumnNameProperty)); - setRawDataKeyColumnName(properties.getProperty(prefix - + rawDataKeyColumnNameProperty)); - } - - /** Returns a byte[] array if successful, null otherwise */ - public byte[] getRawData(String lookUpKey) throws SQLException { - - byte[] foundit = (byte[]) byteCache.get(lookUpKey.toLowerCase() - .intern()); - - if (foundit != null) { - return foundit; - } - - String query = "Select " + rawDataColumnName + " from " + tableName - + " where " + rawDataKeyColumnName + " = '" - + lookUpKey.toLowerCase() + "' "; - - try { - Statement stmt = connection.createStatement(); - ResultSet rset = stmt.executeQuery(query); - rset.next(); - - // This is the only(first hence 1) - InputStream dbis = rset.getBinaryStream(1); - int chunksize = 4096; - byte barr[] = new byte[chunksize]; - int imagelength = 0; - - try { - imagelength = dbis.read(barr); - } catch (IOException ioE) { - System.err.println("ERROR - while reading raw data\n" - + ioE.getMessage()); - } - // System.out.println("image length = " + imagelength); - byte image[] = new byte[imagelength]; - System.arraycopy(barr, 0, image, 0, imagelength); - - // close the resultSet - rset.close(); - // Close the statement - stmt.close(); - byteCache.put(lookUpKey.toLowerCase().intern(), image); - return image; - - } catch (SQLException sqlE) { - // throw new SQLException(sqlE.getMessage() + "\n"+ - // "SQL String " + query); - System.err.println("ERROR - " + sqlE.getMessage() + "\n" - + "SQL String: " + query); - return null; - } - } - - public Connection getConnection() { - return connection; - } - - public void setConnection(Connection inConnection) { - connection = inConnection; - } - - public String getTableName() { - return tableName; - } - - public void setTableName(String inTableName) { - tableName = inTableName; - } - - public String getRawDataColumnName() { - return rawDataColumnName; - } - - public void setRawDataColumnName(String inrawDataColumnName) { - rawDataColumnName = inrawDataColumnName; - } - - public String getRawDataKeyColumnName() { - return rawDataKeyColumnName; - } - - public void setRawDataKeyColumnName(String inrawDataKeyColumnName) { - rawDataKeyColumnName = inrawDataKeyColumnName; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/db/RecordSet.java b/src/core/src/main/java/com/bbn/openmap/layer/location/db/RecordSet.java deleted file mode 100644 index f0b2952df..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/db/RecordSet.java +++ /dev/null @@ -1,153 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/location/db/RecordSet.java,v $ -// $RCSfile: RecordSet.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.location.db; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The RecordSet object handles all the generic database retrieval for a SQL - * query. The idea is that you set it up with a connection, and set the query - * string that it will use to give to the database. Then, you iterate through - * the result set to create the objects you want to: - *

    - *
  • Set the connection and query. - *
  • Call next() repeatedly to see if there is data for another object. - *
  • Use getResultSet(), which provides the result set containing the current - * record data. This can be done within the constructor of the data object you - * are trying to create. - *
- */ -public class RecordSet { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.location.db.RecordSet"); - - /** Connection object that will be used to retrieve data. */ - protected Connection connection = null; - /** The query string that will be executed on the database. */ - protected String queryString = null; - - private Statement stmt; - private ResultSet rset; - - /** - * Use this constructor if you want a little more control of the process. - * You have to remember to set the query string and call getAllQuery() - * before trying to iterate through the results. - */ - public RecordSet(Connection inConnection) throws SQLException { - this(inConnection, null); - } - - /** - * Does everything. If the connection and query are not null, then the - * result set is ready for iteration after this object is created. - */ - public RecordSet(Connection inConnection, String query) throws SQLException { - connection = inConnection; - queryString = query; - getAllQuery(); - } - - /** - * Executes "select * from 'tableName'", or whatever the queryString is set - * to. If the connection is not null, and the queryString is not null, the - * database is fed the query statement. The result is, hopefully, that the - * rset (ResultSet) will be full of responses. The caller should then call - * next() to iterate through the results and fetch the data. - * - * @throws SQLException - */ - public void getAllQuery() throws SQLException { - - if (queryString != null && connection != null) { - try { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("RecordSet calling database with query => " + queryString); - } - - stmt = connection.createStatement(); - rset = stmt.executeQuery(queryString); - } catch (SQLException sqlE) { - throw new SQLException(queryString + " | " + sqlE.getMessage()); - } - } else { - logger.warning("Database parameters faulty!\n query => " + queryString - + "\n connection => " + connection); - } - } - - /** - * This function should be called to prepare the result set with the next - * record set of data. Then you feed this RecordSet object to the - * constructor to a new data object. - */ - public boolean next() throws SQLException { - if (rset != null) { - return rset.next(); - } else { - return false; - } - } - - /** - * Get the result set, after calling next. It should contain the current - * record's data. You have to know how to call the items, and what the type - * of each index is - since you set the query, you should know. You have to - * pay attention to the return from the next() function, though. If next() - * returns false, the result set won't contain valid data, or may be null. - */ - public ResultSet getResultSet() { - return rset; - } - - public void close() throws SQLException { - if (rset != null) { - rset.close(); - } - if (stmt != null) { - stmt.close(); - } - } - - public Connection getConnection() { - return connection; - } - - public void setConnection(Connection inConnection) { - connection = inConnection; - } - - public String getQueryString() { - return queryString; - } - - public void setQueryString(String inQueryString) { - queryString = inQueryString; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/db/package.html b/src/core/src/main/java/com/bbn/openmap/layer/location/db/package.html deleted file mode 100644 index b53f99106..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/db/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Provides a LocationHandler that can retrieve data through JDBC. -For use with the location layer. - - @see com.bbn.openmap.layer.location - @see com.bbn.openmap.layer.location.LocationLayer - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/location/package.html b/src/core/src/main/java/com/bbn/openmap/layer/location/package.html deleted file mode 100644 index a79b81d7c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/location/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a layer that can display location data - data that represents -a location with a graphic and a name. The LocationLayer uses the -LocationHandlers to access the data source and to create the graphics. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFException.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFException.java deleted file mode 100644 index 6d5b70f36..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFException.java +++ /dev/null @@ -1,59 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFException.java,v $ -// $RCSfile: MIFException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -/** - * Custom Exception class for exceptions within the loading of MIF - * files - * - * @author Simon Bowen - */ -public class MIFException extends RuntimeException { - - public MIFException() { - super(); - } - - /** - * @param arg0 - */ - public MIFException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - * @param arg1 - */ - public MIFException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public MIFException(Throwable arg0) { - super(arg0); - } -} -/** Last Line of file * */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFGraphic.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFGraphic.java deleted file mode 100644 index a5817a565..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFGraphic.java +++ /dev/null @@ -1,43 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFGraphic.java,v $ -// $RCSfile: MIFGraphic.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -/** - * Interface that defines behavior specific to OMGraphics that are - * specific to primitives created from MapInfo MIF files - * - * @author Simon Bowen - */ -public interface MIFGraphic { - /** - * sets the scale at which the graphic becomes visible, if set to - * -1 the graphic is visible at all scale levels. - * - * @param visibleScale - */ - public void setVisibleScale(float visibleScale); - - public float getVisibleScale(); - -} -/** Last line of file * */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLayer.java deleted file mode 100644 index f482af02b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLayer.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFLayer.java,v $ -// $RCSfile: MIFLayer.java,v $ -// $Revision: 1.10 $ -// $Date: 2005/05/23 20:06:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Properties; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that displays MapInfo Interchange Format (MIF) - * files Currently only a subset of the possible MIF options is - * supported. Specifically the PLine and Region options with their - * associated parameters however maps will be reproduced exactly as - * they appear in the MapInfo Professional product. - * - * 26th January 2004 - added support for TEXT and POINT - */ -public class MIFLayer extends OMGraphicHandlerLayer { - public final static String MIF_FileProperty = "mifFile"; - public final static String textVisibleProperty = "textVisible"; - public final static String pointVisibleProperty = "pointVisible"; - - boolean accurate = true; - MIFLoader mifl = null; - - public MIFLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for - * this layer. Only the file property is used by the layer. - * This is the MIF file that we will decode. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String mifFileName = props.getProperty(prefix + MIF_FileProperty); - float textVisible = PropUtils.floatFromProperties(props, prefix - + textVisibleProperty, -1f); - float pointVisible = PropUtils.floatFromProperties(props, prefix - + pointVisibleProperty, -1f); - - try { - - URL fileURL = PropUtils.getResourceOrFileOrURL(null, mifFileName); - BufferedReader bfr = new BufferedReader(new InputStreamReader(fileURL - .openStream())); - - mifl = new MIFLoader(bfr, accurate, textVisible, pointVisible); - } catch (IOException ioe) { - Debug.error("MIFLayer: didn't find file " + mifFileName); - return; - } - } - - /** - * Sets the accuracy of the rendering. The default is true. If set - * to false then the regions will not always be drawn correctly - * (ie. as they appear in MapInfo) however processing will be much - * faster. This option effects the drawing of Regions which can - * have nested regions. Nested regions appear as holes in the - * outer region and it is this that can take a lot of processing - * time. Usually something like a street layout will take much - * more time to draw. The more holes then the longer it takes. By - * setting accuracy to false the regions are drawn as lines - * instead of filled which is much faster. - */ - public void setAccuracy(boolean accurate) { - this.accurate = accurate; - } - - /** - * OMGraphicHandlerLayer method for gathering data. - */ - public synchronized OMGraphicList prepare() { - if (mifl != null) { - OMGraphicList list = mifl.getList(); - if (list != null) { - list.generate(getProjection()); - } - return list; - } else { - return new OMGraphicList(); - } - } -} - -/* Last line of file */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLoader.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLoader.java deleted file mode 100644 index 658e52a5a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFLoader.java +++ /dev/null @@ -1,670 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFLoader.java,v $ -// $RCSfile: MIFLoader.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.io.BufferedReader; -import java.io.IOException; -import java.util.StringTokenizer; -import java.util.Vector; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.Debug; - -/** - * A loader class for MIF files. Each MIF layer loading a file will create an - * instance of this The class uses SwingWorker to do processing in a thread Only - * the MIF PLine and Region options are implemented - * - * 27th January 2004 - added some support for TEXT and POINT options - * - * @author Colin Mummery, modified January 2004 by Simon Bowen - */ -public class MIFLoader { - final static int PROCESS_HEADER = 0; - final static int PROCESS_DATA = 1; - final static int PROCESS_PLINE = 2; - final static int PROCESS_POST_PLINE = 3; - final static int PROCESS_MULTIPLE = 4; - final static int PROCESS_REGION = 5; - final static int PROCESS_REGION_HEADER = 6; - final static int PROCESS_POST_REGION = 7; - final static int PROCESS_POST_LINE = 8; - - final static String DATA_WORD = "Data"; - final static String VERSION_WORD = "Version"; - final static String DELIMITER_WORD = "Delimiter"; - final static String COORDSYS_WORD = "Coordsys"; - final static String PLINE_WORD = "PLine"; - final static String LINE_WORD = "Line"; - final static String MULTIPLE_WORD = "Multiple"; - final static String PEN_WORD = "Pen"; - final static String SMOOTH_WORD = "Smooth"; - final static String REGION_WORD = "Region"; - final static String BRUSH_WORD = "Brush"; - final static String CENTER_WORD = "Center"; - final static String POINT_WORD = "Point"; - final static String TEXT_WORD = "Text"; - - BufferedReader br; - OMGraphicList list; - - // if true we do a much faster line only rendering of the regions - boolean accurate; - - // MIF CoordSys value for a Latitude Longitude coordinate system - private static final String LATLONG_COORDSYS_DEF = "Earth Projection 1"; - - private float pointVisible = -1; // default is -1 - private float textVisible = -1; // default is -1 - - /** - * Loads a MIF file from the Reader and placing the appropriate OMGraphics - * on the OMGraphicList * Parsing is done by a simple loop and switch - * statements - * - * @param br - * BufferedReader to read the MIF file - * @param accurate - * if true we do a much faster line only rendering of the regions - * @param textVisible - * the scale at which TEXT primitives should be rendered - * @param pointVisible - * the scale at which POINT primitives should be rendered - */ - public MIFLoader(BufferedReader br, boolean accurate, float textVisible, - float pointVisible) { - super(); - this.br = br; - this.accurate = accurate; - this.pointVisible = pointVisible; - this.textVisible = textVisible; - } - - public boolean isLoaded() { - return list != null; - } - - /** - * Get the OMGraphicList from the loader, creating it from the file if it - * hasn't been created yet. - */ - public OMGraphicList getList() { - return getList(false); - } - - /** - * Get the OMGraphicList from the loader, with the option of forcing it to - * be recreated from the source file if desired. - */ - public OMGraphicList getList(boolean reloadList) { - try { - if (reloadList || !isLoaded()) { - if (isLoaded()) - list.clear(); - list = loadFile(); - } - return list; - } catch (IOException ioe) { - list = null; - // } catch(MIFException mex) { - // list = null; - // Debug.error(mex.getMessage()); - // mex.printStackTrace(); - } - return null; - } - - public OMGraphicList loadFile() throws IOException, MIFException { - double[] ptarray = null; - - // Used by region to do the polygon calculation - double[] latpts = null; - double[] lonpts = null; - - // Specifies the expected next action in the loop - int action = PROCESS_HEADER; - int number = 0; - int count = 0; - int multiple = 0; - int multicnt = 0; - - // setting to true means we don't read the same line again - boolean pushback; - StringTokenizer st = null; - String tok = null; - pushback = false; - int idx; - OMPoly omp = null; - OMLine oml = null; - MIFPoint ompoint = null; - OMText omtext = null; - boolean ismultiple = false; - - OMGraphicList aList = new OMGraphicList(); - - // a vector of omgraphics for regions that allows adding and - // deleting - Vector omgs = new Vector(); - - MAIN_LOOP: while (true) { - - if (!pushback) { - // if it's null then there's no more - if ((st = getTokens(br)) == null) - break MAIN_LOOP; - - tok = st.nextToken(); - } else { - pushback = false; // pushback was true so make it - // false so it doesn't happen twice - } - - SWITCH: switch (action) { - - case PROCESS_HEADER: - if (isSame(tok, DATA_WORD)) { - action = PROCESS_DATA; - } else if (isSame(tok, VERSION_WORD)) { - } else if (isSame(tok, DELIMITER_WORD)) { - } else if (isSame(tok, COORDSYS_WORD)) { - // check the CoordSys header, OpenMap only - // directly - // supports LatLong type of coordsys - StringBuilder sb = new StringBuilder(COORDSYS_WORD); - while (st != null && st.hasMoreElements()) { - sb.append(' ').append(st.nextElement()); - } - - String coordSysLine = sb.toString(); - String goodCoordSys = COORDSYS_WORD + " " - + LATLONG_COORDSYS_DEF; - if (goodCoordSys.length() < coordSysLine.length()) { - coordSysLine = coordSysLine.substring(0, goodCoordSys - .length()); - } else { - goodCoordSys = goodCoordSys.substring(0, coordSysLine - .length()); - } - - // check that the CoordSys header matches the MIF - // specification for LatLong type - if (!isSame(coordSysLine, goodCoordSys)) { - Debug.error("MIFLoader file has coordinate system: " - + coordSysLine + ", requires " + goodCoordSys); - // raise error, as the coordsys header was - // invalid - throw new MIFException( - "File appears to contain objects with an incompatible coordinate system (Must be Lat/Lon)."); - } - - } - break SWITCH; - - case PROCESS_DATA: - omgs.clear(); - if (st != null) { - if (isSame(tok, PLINE_WORD)) { - tok = st.nextToken(); - if (isSame(tok, MULTIPLE_WORD)) { - multiple = Integer.parseInt(st.nextToken()); - multicnt = 0; - action = PROCESS_MULTIPLE; - ismultiple = true; - } else { - number = Integer.parseInt(tok); - ptarray = new double[number + number]; - count = 0; - action = PROCESS_PLINE; - } - } else if (isSame(tok, REGION_WORD)) { - multiple = Integer.parseInt(st.nextToken()); - multicnt = 0; - action = PROCESS_REGION_HEADER; - } else if (isSame(tok, LINE_WORD)) { - float lon1 = Float.parseFloat(st.nextToken()); - float lat1 = Float.parseFloat(st.nextToken()); - float lon2 = Float.parseFloat(st.nextToken()); - float lat2 = Float.parseFloat(st.nextToken()); - - oml = new OMLine(lat1, lon1, lat2, lon2, - OMGraphicConstants.LINETYPE_STRAIGHT); - - action = PROCESS_POST_LINE; - } else if (isSame(tok, POINT_WORD)) // handle a MIF - // POINT primitive - { - // get the coordinates - float lon1 = Float.parseFloat(st.nextToken()); - float lat1 = Float.parseFloat(st.nextToken()); - - // construct the OM graphic - ompoint = new MIFPoint(lat1, lon1, pointVisible); - st = getTokens(br); - - // set the graphics attributes - this.processSymbolWord(st, ompoint); - - // add to the graphic list for this layer - aList.add(ompoint); - action = PROCESS_DATA; - } else if (isSame(tok, TEXT_WORD)) // handle a MIF - // TEXT primitive - { - StringBuilder sb = new StringBuilder(); - - // if the actual text is not on the same line as - // the primitive declaration - if (st.countTokens() < 1) { - // get the next line - st = getTokens(br); - } - // build up the display text string, - while (st != null && st.hasMoreTokens()) { - sb.append(st.nextToken()); - } - - String textString = sb.toString(); - if (textString.length() >= 1) { - // remove any surrounding " characters - textString = textString.substring(1, textString - .length() - 1); - } - // get the next line, it contains the coordinates - st = getTokens(br); - - float lon1 = Float.parseFloat(st.nextToken()); - float lat1 = Float.parseFloat(st.nextToken()); - /* float lon2 = */Float.parseFloat(st.nextToken()); - /* float lat2 = */Float.parseFloat(st.nextToken()); - // create the OMGraphic for the text object - omtext = new MIFText(lat1, lon1, textString, - OMText.JUSTIFY_CENTER, textVisible); - - // the next line contains the text attributes - st = getTokens(br); - // set the attributes agains the omgraphic - this.processFontWord(st, omtext); - // add to the layers graphic list - aList.add(omtext); - - action = PROCESS_DATA; - } - } - break SWITCH; - - // We have a line, tok is the first coord and the next - // token is the second - case PROCESS_PLINE: - idx = count + count; - if (ptarray != null && st != null) { - ptarray[idx + 1] = Float.parseFloat(tok); - ptarray[idx] = Float.parseFloat(st.nextToken()); - count++; - if (count == number) { - omp = new OMPoly(ptarray, OMGraphic.DECIMAL_DEGREES, - OMGraphic.LINETYPE_STRAIGHT); - - aList.add(omp); - if (!ismultiple) { - action = PROCESS_POST_PLINE; - } else { - omgs.add(omp); - action = PROCESS_MULTIPLE; - } - } - } - break SWITCH; - - case PROCESS_MULTIPLE: - multicnt++; - if (multicnt > multiple) { // No more multiples so we - // can pushback - pushback = true; - multiple = 0; - action = PROCESS_POST_PLINE; - break SWITCH; - } - number = Integer.parseInt(tok); - count = 0; - ptarray = new double[number + number]; - action = PROCESS_PLINE; - break SWITCH; - - case PROCESS_POST_PLINE: - if (isSame(tok, PEN_WORD)) { - if (ismultiple) { - processPenWord(st, omgs); - } else { - processPenWord(st, omp); - } - } else if (isSame(tok, SMOOTH_WORD)) { - // Smooth unimplemented - } else { - ismultiple = false; - pushback = true; - action = PROCESS_DATA; - } - break SWITCH; - - // SCN to support lines - case PROCESS_POST_LINE: - if (isSame(tok, PEN_WORD)) { - processPenWord(st, oml); - aList.add(oml); - } else { - ismultiple = false; - pushback = true; - action = PROCESS_DATA; - } - break SWITCH; - - case PROCESS_REGION_HEADER: // This processes the number - // at the top of each region - // sub-block - multicnt++; - if (multicnt > multiple) { - multiple = 0; - action = PROCESS_POST_REGION; - - // Add this point the region is finished so add - // the - // vector contents to list - int len = omgs.size(); - for (int i = 0; i < len; i++) { - aList.add((OMGraphic) omgs.elementAt(i)); - } - break SWITCH; - } - number = Integer.parseInt(tok); - count = 0; - ptarray = new double[number + number]; - latpts = new double[number]; - lonpts = new double[number]; - action = PROCESS_REGION; - break SWITCH; - - case PROCESS_REGION: - idx = count + count; - if (ptarray != null && lonpts != null && latpts != null - && st != null) { - lonpts[count] = ptarray[idx + 1] = Float.parseFloat(tok); - latpts[count] = ptarray[idx] = Float.parseFloat(st - .nextToken()); - count++; - if (count == number) { - // This polygon is complete so add it and process - // the next - - // Use this code if we just want polygons which is - // much - // faster - if (accurate) { - omgs.add(new OMSubtraction(latpts, lonpts)); - - } else { - // Produces accurate MapInfo type rendering - // but very - // slow with complex regions like streets - int end = latpts.length - 1; - - for (int i = 0; i < end; i++) { - omgs.add(new OMLine(latpts[i], lonpts[i], - latpts[i + 1], lonpts[i + 1], - OMGraphic.LINETYPE_STRAIGHT)); - } - omgs.add(new OMLine(latpts[end], lonpts[end], - latpts[0], lonpts[0], - OMGraphic.LINETYPE_STRAIGHT)); - } - action = PROCESS_REGION_HEADER; - } - } - break SWITCH; - - // There is one pen,brush,center block at the end of a - // region - case PROCESS_POST_REGION: - if (isSame(tok, PEN_WORD)) { - processPenWord(st, omgs); - } else if (isSame(tok, BRUSH_WORD)) { - processBrushWord(st, omgs); - } else if (isSame(tok, CENTER_WORD)) { - } else { - pushback = true; - action = PROCESS_DATA; - } - break SWITCH; - - } // end of switch - } // end of while loop - - br.close(); - - return aList; - } - - /* - * Processes an instance of the Pen directive for a single OMGraphic - */ - private void processPenWord(StringTokenizer st, OMGraphic omg) { - if (omg == null) - return; - int width = Integer.parseInt(st.nextToken()); - omg.setStroke(new BasicStroke(width)); - /* int pattern = */Integer.parseInt(st.nextToken()); - Color col = convertColor(Integer.parseInt(st.nextToken())); - omg.setLinePaint(col); - } - - /* - * Processes an instance of the Pen directive for a vector of OMGraphics - */ - private void processPenWord(StringTokenizer st, Vector vals) { - int width = Integer.parseInt(st.nextToken()); - /* int pattern = */Integer.parseInt(st.nextToken()); - Color col = convertColor(Integer.parseInt(st.nextToken())); - int len = vals.size(); - OMGraphic omg = null; - for (int i = 0; i < len; i++) { - omg = (OMGraphic) vals.elementAt(i); - omg.setLinePaint(col); - omg.setStroke(new BasicStroke(width)); - } - } - - /* - * Processes an instance of the Brush directive - */ - private void processBrushWord(StringTokenizer st, Vector vals) { - - int pattern = Integer.parseInt(st.nextToken()); - Color foreground = convertColor(Integer.parseInt(st.nextToken())); - - /* - * background appears to be ignored by MapInfo but I grab it anyway - */ - // Color background = null; - // if (st.hasMoreTokens()) { - // background = convertColor(Integer.parseInt(st.nextToken())); - // } - int len = vals.size(); - OMGraphic omg; - for (int i = 0; i < len; i++) { - omg = (OMGraphic) vals.elementAt(i); - omg.setLinePaint(foreground); - - switch (pattern) { - case 1: - break; // No fill so do nothing - case 2: - omg.setFillPaint(foreground); - break; - } - } - } - - /** - * process the MIF SYMBOL element. - * - * The MIF format for SYMBOL element is - * SYMBOL (shape, color, size, fontname, fontstyle, rotation) - * or - * SYMBOL (filename, color, size, customstyle) - * - * - * currently only the color attribute is considered and a default OMPoint - * symbol and size is adopted. - * - * @param st - * tokenizer containing the "SYMBOL" MIF elements - * @param omg - * the OMGraphic object to attribute with the setting from the - * MIF line - */ - private void processSymbolWord(StringTokenizer st, OMPoint omg) { - /* String symbolStr = */st.nextToken(); // should be "SYMBOL" - - /* int symbol = */Integer.parseInt(st.nextToken()); - Color color = convertColor(Integer.parseInt(st.nextToken())); - - /* int size = */Integer.parseInt(st.nextToken()); - - omg.setFillPaint(color); - } - - /** - * process the MIF FONT element. currently only PLAIN (0), BOLD(1), ITALIC - * (2) and BOLD ITALIC(3) are supported. Font size is hardcoded to 10, and - * backcolor is ignored. - * - * The MIF format for FONT is - * FONT ("fontname", style, size, forecolor [, backcolor] ) - * - * - * Within a MIF file size will always be 0, it's up to the renderer to - * determine the size. Background color is optional - * - * style is determined as follows, to specify 2 or more style attributes, add - * the values from each style, e.g. BOLD ALLCAPS = 513 - * - * value style =================== 0 PLAIN 1 BOLD 2 ITALIC 4 UNDERLINE 16 - * OUTLINE 32 SHADOW 256 HALO 512 ALL CAPS 1024 Expanded - * - * - * @param st - * tokenizer containing the "FONT" MIF elements - * @param omTxt - * the OMGraphic object to attribute with the setting from the - * MIF line - */ - private void processFontWord(StringTokenizer st, OMText omTxt) { - /* String fontStr = */st.nextToken(); // should be "FONT" - String fontName = st.nextToken(); - int style = Integer.parseInt(st.nextToken()); - /* int size = */Integer.parseInt(st.nextToken()); - Color foreColor = convertColor(Integer.parseInt(st.nextToken())); - - // last token is optional background color - // Color bgColor = null; - // if (st.hasMoreTokens()) { - // bgColor = convertColor(Integer.parseInt(st.nextToken())); - // } - - int fontStyle = Font.PLAIN; - switch (style) { - case 0: - fontStyle = Font.PLAIN; - break; - case 1: - fontStyle = Font.BOLD; - break; - case 2: - fontStyle = Font.ITALIC; - break; - case 3: - fontStyle = Font.BOLD & Font.ITALIC; - break; - } - - omTxt.setFillPaint(foreColor); - omTxt.setFont(new Font(fontName.substring(1, fontName.length() - 1), - fontStyle, 10)); - } - - /* - * Creates a tokenizer for each line of input - */ - private StringTokenizer getTokens(BufferedReader br) throws IOException { - String line; - WHILE: while ((line = br.readLine()) != null) { - - if (line.length() == 0) - continue WHILE; // skip blank lines - - // should return the tokenizer as soon as we have a line - return new StringTokenizer(line, " \t\n\r\f,()"); - } - return null; - } - - /* - * Utility for doing case independent string comparisons... it's neater this - * way - */ - private boolean isSame(String str1, String str2) { - return str1.equalsIgnoreCase(str2); - } - - /* - * Converts MIF file color to Java Color object - */ - private Color convertColor(int val) { - int red = 0; - int green = 0; - int blue = 0; - int rem = val; - if (rem >= 65536) { - red = rem / 65536; - rem -= red * 65536; - } - if (rem >= 255) { - green = rem / 256; - rem -= green * 256; - } - if (rem > 0) - blue = rem; - - return new Color(red, green, blue); - } -} - -/* Last line of file */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFPoint.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFPoint.java deleted file mode 100644 index 81224da2f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFPoint.java +++ /dev/null @@ -1,104 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFPoint.java,v $ -// $RCSfile: MIFPoint.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -import java.awt.Graphics; - -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.proj.Projection; - -/** - * Extension of OMPoint to provide basic support to ensure that the - * screen will not become cluttered This extension of OMPoint defines - * a property visibleScale. visibleScale is the OpenMap maximum scale - * at which the point will be rendered all scale values after the - * visibleScale value will result in the point to be rendered. - *

- * - * if visible scale is set to -1 the point will be rendered all all - * scale levels. - * - * @author Simon Bowen - */ -public class MIFPoint extends OMPoint implements MIFGraphic, - java.io.Serializable { - - /** - * default visibleScale value is -1 - */ - private float visibleScale = -1; - - private boolean renderPoint = true; - - /** - * @param lat the latitude to display the text string - * @param lon the longitude to display the text string - * @param visibleScale if visible scale is set to -1 the text will - * be rendered all all scale levels. - */ - public MIFPoint(float lat, float lon, float visibleScale) { - super(lat, lon); - this.visibleScale = visibleScale; - } - - /** - * sets the scale at which the graphic becomes visible, if set to - * -1 the graphic is visible at all scale levels. - * - * @param visibleScale - */ - public void setVisibleScale(float visibleScale) { - this.visibleScale = visibleScale; - } - - public float getVisibleScale() { - return this.visibleScale; - } - - /** - * Overriden from OMPoint so that we can handle a flag - * renderPoint to signal to the render method if - * the scale is appropriate to render the point or not. - */ - public synchronized boolean generate(Projection proj) { - if ((proj.getScale() <= getVisibleScale()) || (getVisibleScale() == -1)) { - this.renderPoint = true; - } else { - this.renderPoint = false; - } - - return super.generate(proj); - } - - /** - * Overriden from OMPoint so that we can handle a flag - * renderPoint to determine if the point should be - * rendered or not. - */ - public synchronized void render(Graphics g) { - if (renderPoint) { - super.render(g); - } - } -} -/** Last line of file * */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFText.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFText.java deleted file mode 100644 index d4f981a22..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/MIFText.java +++ /dev/null @@ -1,108 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/MIFText.java,v $ -// $RCSfile: MIFText.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -import java.awt.Graphics; - -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; - -/** - * Extension of OMText to provide basic support to ensure that the - * screen will not become cluttered This extension of OMText defines a - * property visibleScale. visibleScale is the OpenMap maximum scale at - * which the text will be rendered all scale values after the - * visibleScale value will result in the text to be rendered. - *

- * - * If visible scale is set to -1 the text will be rendered all all - * scale levels. - * - * @author Simon Bowen - */ -public class MIFText extends OMText implements MIFGraphic, java.io.Serializable { - /** - * default visibleScale value is -1 - */ - private float visibleScale = -1; - - private boolean renderText = true; - - /** - * @param lat the latitude to display the text string - * @param lon the longitude to display the text string - * @param txt the text string to display - * @param justification from OMText e.g. OMText.JUSTIFY_CENTER - * @param visibleScale if visible scale is set to -1 the text will - * be rendered all all scale levels. - */ - public MIFText(float lat, float lon, String txt, int justification, - float visibleScale) { - - super(lat, lon, txt, justification); - this.setVisibleScale(visibleScale); - } - - /** - * Sets the scale at which the graphic becomes visible, if set to - * -1 the graphic is visible at all scale levels. - * - * @param visibleScale - */ - public void setVisibleScale(float visibleScale) { - this.visibleScale = visibleScale; - } - - public float getVisibleScale() { - return this.visibleScale; - } - - /** - * Overriden from OMText so that we can handle a flag - * renderText to signal to the render method if the - * scale is appropriate to render the text or not. - */ - public synchronized boolean generate(Projection proj) { - if ((proj.getScale() <= getVisibleScale()) || (getVisibleScale() == -1)) { - - this.renderText = true; - } else { - this.renderText = false; - } - - return super.generate(proj); - } - - /** - * Overriden from OMText so that we can handle a flag - * renderText to determine if the text should be - * rendered or not. - */ - public synchronized void render(Graphics g) { - if (renderText) { - super.render(g); - } - } -} - -/** Last line of file * */ diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/OMSubtraction.java b/src/core/src/main/java/com/bbn/openmap/layer/mif/OMSubtraction.java deleted file mode 100644 index 113b2afd2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/OMSubtraction.java +++ /dev/null @@ -1,168 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/mif/OMSubtraction.java,v $ -// $RCSfile: OMSubtraction.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.mif; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.geom.Area; -import java.awt.geom.GeneralPath; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphicAdapter; -import com.bbn.openmap.proj.Projection; - -/** - * Defines a Region of a MIF file where when one region encloses another the - * enclosed region is subtracted from the enclosing region in order to create a - * hole Computationally this can be expensive to do on a complex layout like a - * streetmap of city - */ -public class OMSubtraction extends OMGraphicAdapter implements Serializable { - - SubArea outer; // The outer polygon of this region - transient Area area; // calculated - List subs; // An array of the subtractions to make - - public OMSubtraction(double[] lat, double[] lon) { - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - outer = new SubArea(lat, lon); - } - - boolean contains(double[] latp, double[] lonp) { - if (outer.contains(latp, lonp)) { - if (subs == null) { - subs = new ArrayList(); - } - subs.add(new SubArea(latp, lonp)); - return true; - } - return false; - } - - public boolean generate(Projection proj) { - - if (proj == null) { - System.err.println("OMText: null projection in generate!"); - return false; - } - - if (!outer.isPlotable(proj)) - return false; - - area = outer.getArea(proj); - - if (subs != null) { - for (SubArea sb : subs) { - area.subtract(sb.getArea(proj)); - } - } - - setNeedToRegenerate(false); - return true; - } - - public synchronized void render(Graphics g) { - - if (getNeedToRegenerate()) - return; - - if (area == null) - return; - - Graphics2D g2 = (Graphics2D) g; - g2.setPaint(getFillPaint()); - g2.fill(area); - } - - /** - * Return the shortest distance from the line to an XY-point - not relevant - * to this class. - * - * @param x X coordinate of the point. - * @param y Y coordinate fo the point. - * @return float always zero - */ - public float distance(double x, double y) { // return zero - return 0.0f; - } - - class SubArea implements Serializable { - - double[] lat; - double[] lon; - int[] x, y; - int len; - - // We use this to ask if a point lies inside this area, - // Polygon class is no good cos it needs ints - GeneralPath gpath; - - SubArea(double[] lat, double[] lon) { - this.lat = lat; - this.lon = lon; - len = lat.length; - x = new int[len]; - y = new int[len]; - } - - Area getArea(Projection proj) { - Point pt = new Point(); - for (int i = 0; i < len; i++) { - proj.forward(lat[i], lon[i], pt); - x[i] = pt.x; - y[i] = pt.y; - } - return new Area(new Polygon(x, y, len)); - } - - boolean isPlotable(Projection proj) { - return proj.isPlotable(lat[0], lon[0]); - } - - boolean contains(double[] latp, double[] lonp) { - - if (gpath == null) { - gpath = new GeneralPath(); - for (int i = 0; i < len; i++) { - if (i == 0) - gpath.moveTo((float) lat[0], (float) lon[0]); - gpath.lineTo((float) lat[i], (float) lon[i]); - } - gpath.closePath(); - } - - int len = latp.length; - for (int i = 0; i < len; i++) { - if (gpath.contains(latp[i], lonp[i])) { - return true; - } - } - return false; - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mif/package.html b/src/core/src/main/java/com/bbn/openmap/layer/mif/package.html deleted file mode 100644 index a10783e88..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mif/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains a Layer that displays MapInfo data (.mif files). - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlCollection.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlCollection.java deleted file mode 100755 index 9ba238313..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlCollection.java +++ /dev/null @@ -1,41 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ - -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL - * GeometryCollection. - * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlCollection extends MysqlMulti { - - public MysqlCollection() { - super(); - this.setType(MysqlGeometry.GEOMETRYCOLLECTIONTYPE); - } - - public void addElement(MysqlGeometry mg) { - super.elements.add(mg); - } - - public MysqlGeometry getElementByIndex(int i) { - return (MysqlGeometry) super.elements.elementAt(i); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometry.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometry.java deleted file mode 100755 index 47ab00a3a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometry.java +++ /dev/null @@ -1,57 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the base class of MySQL Geometry. Coordinate - * values are stored as values of double precision in arrays as a - * sequence of Latitude/Longitude pairs. This differs from the - * database where values are stored as X/Y or Easting/Northing pairs. - * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlGeometry { - - private String type; - - public final static String POINTTYPE = "POINT"; - public final static String LINESTRINGTYPE = "LINESTRING"; - public final static String POLYGONTTYPE = "POLYGON"; - public final static String MULTIPOINTTYPE = "MULTIPOINT"; - public final static String MULTILINESTRINGTYPE = "MULTILINESTRING"; - public final static String MULTIPOLYGONTYPE = "MULTIPOLYGON"; - public final static String GEOMETRYCOLLECTIONTYPE = "GEOMETRYCOLLECTION"; - - /** - * Returns the type. - * - * @return String - */ - public String getType() { - return type; - } - - /** - * Sets the type. - * - * @param type The type to set - */ - public void setType(String type) { - this.type = type; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometryLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometryLayer.java deleted file mode 100755 index ce03a99a6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlGeometryLayer.java +++ /dev/null @@ -1,340 +0,0 @@ -/* *********************************************************************** - * This layer is for the reading and display of any spatial data retrieved - * from a MySQL Database (Version 4.1). At this time MySQL 4.1 is available - * only as alfa release, and represents the first version with support for - * the Datatype Geometry. Therefore be careful expecting to much. - * Usefull information can be found in the chapter 9 of the MySQL Reference - * (Spatial Extensions in MySQL) - * http://www.mysql.com/documentation/mysql/bychapter/index.html#GIS_spatial_extensions_in_MySQL - * partially this layer is inspired by Ian Batley's OracleSpatialLayer which - * can be found on the on the Open Map website.Thanks Ian. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ - -package com.bbn.openmap.layer.mysql; - -/* Java Core */ -import java.awt.geom.Point2D; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * This layer is for the reading and display of any spatial data retrieved from - * a MySQL Database (Version 4.1). At this time MySQL 4.1 is available only as - * alfa release, and represents the first version with support for the Datatype - * Geometry. Therefore, be careful in expecting too much. Usefull information - * can be found in the chapter 9 of the MySQL Reference (Spatial Extensions in - * MySQL) http://www.mysql.com/documentation/mysql/bychapter/index.html# - * GIS_spatial_extensions_in_MySQL partially this layer is inspired by Ian - * Batley's OracleSpatialLayer which can be found on the on the OpenMap website. - * Thanks Ian. - *

- * - * MysqlGeometryLayer uses at this stage a set of Classes which wraps the - * Geometries retrieved from the database. They are thought to be a provisorium - * until a nice MySQL Geometry API is available. Coordinate values are stored as - * values of double precision in arrays as a sequence of Latitude/Longitude - * pairs. This differs from the database where values are stored as X/Y or - * Easting/Northing pairs. - * - *

- * Properties to be set: - * - *

- * 
- *   mygeo.prettyName=<Your Layer Name>
- *   mygeo.dbUrl=<Driver Class> eg.  "jdbc:mysql://localhost/openmap?user=me&password=secret"
- *   mygeo.dbClass=<Driver Class> eg. "com.mysql.jdbc.Driver"
- *   mygeo.geomTable=<Database Tablename>
- *   mygeo.geomColumn=<Column name which contains the geometry>
- *   mygeo.pointSymbol=<Filename and path for image to use for point objects>Default is null
- *   
- *   # Optional Properties - use as required
- *   # NOTE: There are default for each of these 
- *   mygeo.lineColor=<Color for lines> Default is red
- *   mygeo.lineWidth=<Pixel width of lines> Default is 0
- *   mygeo.fillColor=<Color of fill> Default is red
- * 
- * 
- * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net - * @version 1.0 - */ -public class MysqlGeometryLayer extends OMGraphicHandlerLayer { - - /** - * The connection String to use for the jdbc query, e.g. - * "jdbc:mysql://localhost/openmap?user=me&password=secret" - */ - protected String dbUrl = null; - - /** - * The Property to set for the query: dbUrl . - */ - public static final String dbUrlProperty = "dbUrl"; - - /** - * ; The driver to use. - */ - protected String dbClass = null; - - /** - * The property to use for specifying the driver: dbClass - */ - public static final String dbClassProperty = "dbClass"; - - /** Table name which contains the geometry to be used. */ - protected String geomTable = null; - - /** - * Property to specify geomTable in the Database: geomTable . - */ - public static final String geomTableProperty = "geomTable"; - - /** Column name which contains the geometry to be used. */ - protected String geomColumn = null; - - /** - * Property to specify geomColumn in the Database: geomColumn - */ - public static final String geomColumnProperty = "geomColumn"; - - /** The point Symbol set by the Properties */ - protected String pointSymbol = ""; - - /** - * Property to specify GIF or image file(symbol) to use for Points: - * pointSymbol . - */ - public static final String pointSymbolProperty = "pointSymbol"; - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - /** - * The properties and prefix are managed and decoded here. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - dbClass = properties.getProperty(prefix + dbClassProperty); - dbUrl = properties.getProperty(prefix + dbUrlProperty); - geomTable = properties.getProperty(prefix + geomTableProperty); - geomColumn = properties.getProperty(prefix + geomColumnProperty); - pointSymbol = properties.getProperty(prefix + pointSymbolProperty); - - if (Debug.debugging("mysql")) { - Debug.output("MysqlGeometryLayer (" + getName() + ") properties:"); - Debug.output(" " + dbClass); - Debug.output(" " + dbUrl); - Debug.output(" " + geomTable); - Debug.output(" " + geomColumn); - } - - drawingAttributes.setProperties(prefix, properties); - } - - public synchronized OMGraphicList prepare() { - - Projection proj = getProjection(); - - if (proj == null) { - Debug.output("MysqlGeometryLayer.prepare: null projection!"); - return null; - } - - OMGraphicList graphics = new OMGraphicList(); - - try { - - Class.forName(dbClass).newInstance(); - Connection conn = DriverManager.getConnection(dbUrl); - - Statement stmt = conn.createStatement(); - - Point2D ul = getProjection().getUpperLeft(); - Point2D lr = getProjection().getLowerRight(); - - String q = "SELECT ID, AsText(" + geomColumn + ") FROM " + geomTable - + " WHERE MBRIntersects(GEO, GeomFromText('Polygon(( " + ul.getX() + " " - + ul.getY() + ", " + ul.getX() + " " + lr.getY() + ", " + lr.getX() + " " - + lr.getY() + ", " + lr.getX() + " " + ul.getY() + ", " + ul.getX() + " " - + ul.getY() + "))'))"; - - if (Debug.debugging("mysql")) { - Debug.output("MysqlGeometryLayer query: " + q); - } - - ResultSet rs = stmt.executeQuery(q); - - graphics.clear(); - - while (rs.next()) { - - String result = rs.getString(2); - - if (Debug.debugging("mysql")) { - Debug.output("MysqlGeometryLayer result: " + result); - } - - MysqlGeometry mg = MysqlWKTGeometryFactory.createGeometry(result); - OMGraphic omg = createGraphic(mg); - omg.generate(proj); - graphics.add(omg); - } - - rs.close(); - conn.close(); - - } catch (SQLException sqlE) { - sqlE.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - - return graphics; - } - - /** - * Method createPoint. Renders a Point. - * - * @param myPoint - */ - protected OMGraphic createPoint(MysqlPoint myPoint) { - ImageIcon actualPointSymbol = new ImageIcon(pointSymbol); - OMRaster ompoint = new OMRaster((float) myPoint.getNorthings(), (float) myPoint.getEastings(), actualPointSymbol); - - drawingAttributes.setTo(ompoint); - - return ompoint; - } - - /** - * Method createLine. Renders a Linestring Geometry. ToDo: Holes - * - * @param myLine - Database object which will be rendered - */ - protected OMGraphic createLine(MysqlLine myLine) { - - OMPoly ompoly = new OMPoly(myLine.getCoordinateArray(), OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT); - - drawingAttributes.setTo(ompoly); - return ompoly; - } - - /** - * Method createPolygon. Renders a polygon geometry - * - * @param myPoly - Database object which will be rendered - */ - protected OMGraphic createPolygon(MysqlPolygon myPoly) { - Vector v = myPoly.getRings(); - int size = v.size(); - - OMGraphic ret = null; - OMPoly ompoly = null; - OMGraphicList subList = null; - - if (size > 1) { - subList = new OMGraphicList(); - ret = subList; - } - - for (int i = 0; i < size; i++) { - ompoly = new OMPoly((double[]) v.elementAt(i), OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT); - - drawingAttributes.setTo(ompoly); - - if (subList != null) { - subList.add(ompoly); - } else { - ret = ompoly; - } - } - - return ret; - } - - /** - * Method chooses what type of geometry to render. - * - * @param mg Database object which will be rendered - */ - protected OMGraphic createGraphic(MysqlGeometry mg) { - OMGraphic ret = null; - - if (mg != null) { - String type = mg.getType(); - - if (type.equals(MysqlGeometry.POINTTYPE)) { - ret = createPoint((MysqlPoint) mg); - } else if (type.equals(MysqlGeometry.LINESTRINGTYPE)) { - ret = createLine((MysqlLine) mg); - } else if (type.equals(MysqlGeometry.POLYGONTTYPE)) { - ret = createPolygon((MysqlPolygon) mg); - } else if (type.equals(MysqlGeometry.MULTIPOINTTYPE) - || type.equals(MysqlGeometry.MULTILINESTRINGTYPE) - || type.equals(MysqlGeometry.MULTIPOLYGONTYPE) - || type.equals(MysqlGeometry.GEOMETRYCOLLECTIONTYPE)) { - - MysqlMulti multi = (MysqlMulti) mg; - OMGraphicList subList = new OMGraphicList(); - for (int i = 0; i < multi.countElements(); i++) { - OMGraphic subRet = null; - if (type.equals(MysqlGeometry.MULTIPOINTTYPE)) { - subRet = createPoint((MysqlPoint) multi.getElementByIndex(i)); - } else if (type.equals(MysqlGeometry.MULTILINESTRINGTYPE)) { - subRet = createLine((MysqlLine) multi.getElementByIndex(i)); - } else if (type.equals(MysqlGeometry.MULTIPOLYGONTYPE)) { - subRet = createPolygon((MysqlPolygon) multi.getElementByIndex(i)); - } else if (type.equals(MysqlGeometry.GEOMETRYCOLLECTIONTYPE)) { - subRet = createGraphic((MysqlGeometry) multi.getElementByIndex(i)); - } - - if (subRet != null) { - subList.add(subRet); - } - } - ret = subList; - } else { - // Other types of geometry - if (Debug.debugging("mysql")) { - Debug.output("MysqlGeometryLayer.createGeometry: Geometry type not supported"); - } - } - } - return ret; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlLine.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlLine.java deleted file mode 100755 index 41e1d23ef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlLine.java +++ /dev/null @@ -1,56 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ - -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL - * GeometryLineString. Coordinate values are stored as values of - * double precision in arrays as a sequence of Latitude/Longitude - * pairs. This differs from the database where values are stored as - * X/Y or Easting/Northing pairs. - * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlLine extends MysqlGeometry { - - private double[] coordinateArray; - - public MysqlLine() { - super(); - this.setType(MysqlGeometry.LINESTRINGTYPE); - } - - /** - * Returns the coordinateArray. - * - * @return double[] - */ - public double[] getCoordinateArray() { - return coordinateArray; - } - - /** - * Sets the coordinateArray. - * - * @param coordinateArray The coordinateArray to set - */ - public void setCoordinateArray(double[] coordinateArray) { - this.coordinateArray = coordinateArray; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMulti.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMulti.java deleted file mode 100755 index 5246ca56e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMulti.java +++ /dev/null @@ -1,39 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -import java.util.Vector; - -/** - * This abstract class represents the base class of compound Mysql - * Geometry Objects. - *

- * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -abstract public class MysqlMulti extends MysqlGeometry { - - protected Vector elements = new Vector(); - - public int countElements() { - return elements.size(); - } - - abstract public void addElement(MysqlGeometry mg); - - abstract public MysqlGeometry getElementByIndex(int i); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiLineString.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiLineString.java deleted file mode 100755 index 059270658..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiLineString.java +++ /dev/null @@ -1,49 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL MultiLineString. - * Coordinate values are stored as values of double precision in - * arrays as a sequence of Latitude/Longitude pairs. This differs from - * the database where values are stored as X/Y or Easting/Northing - * pairs. - *

- * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlMultiLineString extends MysqlMulti { - - public MysqlMultiLineString() { - super(); - this.setType(MysqlGeometry.MULTILINESTRINGTYPE); - } - - /** - * @see com.bbn.openmap.layer.mysql.MysqlMulti#addElement(MysqlGeometry) - */ - public void addElement(MysqlGeometry l) { - if (l.getType().equals(MysqlGeometry.LINESTRINGTYPE)) { - super.elements.add((MysqlLine) l); - } - } - - public MysqlGeometry getElementByIndex(int i) { - return (MysqlLine) super.elements.elementAt(i); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPoint.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPoint.java deleted file mode 100755 index 8e752c787..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPoint.java +++ /dev/null @@ -1,46 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL MultiPoint - * Geometry. Coordinate values are stored as values of double - * precision in arrays as a sequence of Latitude/Longitude pairs. This - * differs from the database where values are stored as X/Y or - * Easting/Northing pairs. - * - *

- * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlMultiPoint extends MysqlMulti { - - public MysqlMultiPoint() { - super(); - this.setType(MysqlGeometry.MULTIPOINTTYPE); - } - - public void addElement(MysqlGeometry l) { - if (l.getType().equals(MysqlGeometry.POINTTYPE)) { - super.elements.add((MysqlPoint) l); - } - } - - public MysqlGeometry getElementByIndex(int i) { - return (MysqlPoint) super.elements.elementAt(i); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPolygon.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPolygon.java deleted file mode 100755 index cfbef12cb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlMultiPolygon.java +++ /dev/null @@ -1,46 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL MultiPolygon - * Geometry. Coordinate values are stored as values of double - * precision in arrays as a sequence of Latitude/Longitude pairs. This - * differs from the database where values are stored as X/Y or - * Easting/Northing pairs. - * - *

- * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlMultiPolygon extends MysqlMulti { - - public MysqlMultiPolygon() { - super(); - this.setType(MysqlGeometry.MULTIPOLYGONTYPE); - } - - public void addElement(MysqlGeometry l) { - if (l.getType().equals(MysqlGeometry.POLYGONTTYPE)) { - super.elements.add((MysqlPolygon) l); - } - } - - public MysqlGeometry getElementByIndex(int i) { - return (MysqlPolygon) super.elements.elementAt(i); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPoint.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPoint.java deleted file mode 100755 index fd923025a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPoint.java +++ /dev/null @@ -1,75 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -/** - * This class represents the encapsulation of a MySQL Point Geometry. - * Coordinate values are stored as values of double precision in - * arrays as a sequence of Latitude/Longitude pairs. This differs from - * the database where values are stored as X/Y or Easting/Northing - * pairs. - * - *

- * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlPoint extends MysqlGeometry { - - private double Eastings; - private double Northings; - - public MysqlPoint() { - super(); - this.setType(MysqlGeometry.POINTTYPE); - } - - /** - * Returns the eastings. - * - * @return double - */ - public double getEastings() { - return Eastings; - } - - /** - * Returns the northings. - * - * @return double - */ - public double getNorthings() { - return Northings; - } - - /** - * Sets the eastings. - * - * @param eastings The eastings to set - */ - public void setEastings(double eastings) { - Eastings = eastings; - } - - /** - * Sets the northings. - * - * @param northings The northings to set - */ - public void setNorthings(double northings) { - Northings = northings; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPolygon.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPolygon.java deleted file mode 100755 index b6038e61c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlPolygon.java +++ /dev/null @@ -1,58 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -import java.util.Vector; - -/** - * This class represents the encapsulation of a MySQL Polygon - * Geometry. Coordinate values are stored as values of double - * precision in arrays as a sequence of Latitude/Longitude pairs. This - * differs from the database where values are stored as X/Y or - * Easting/Northing pairs. - * - *

- * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class MysqlPolygon extends MysqlGeometry { - - private Vector rings; - - public MysqlPolygon() { - super(); - this.setType(MysqlGeometry.POLYGONTTYPE); - } - - /** - * Returns the rings. - * - * @return Vector - */ - public Vector getRings() { - return rings; - } - - /** - * Sets the rings. - * - * @param rings The rings to set - */ - public void setRings(Vector rings) { - this.rings = rings; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlWKTGeometryFactory.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlWKTGeometryFactory.java deleted file mode 100755 index 2c1afe9d0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/MysqlWKTGeometryFactory.java +++ /dev/null @@ -1,299 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -import java.util.Vector; - -import com.bbn.openmap.util.Debug; - -/** - * This class represents the Factory class do create the different - * Geometry Objects. It takes as input a WKT Representation (text) of - * the Geometry. It should have less performance than one which - * manipulates WKB (binary) (TODO). - *

- * - * Copyright 2003 by the Author - *

- * - * @author Uwe Baier uwe.baier@gmx.net - * @version 1.0 - */ -public class MysqlWKTGeometryFactory { - -// private Vector coordStringsVector = new Vector(); - - public static MysqlGeometry createGeometry(String geotext) { - WKTNode wktRoot = parseGeometryText(geotext); - String type = geotext.substring(0, geotext.indexOf("(")); - return util(wktRoot, type); - } - - protected static MysqlGeometry util(WKTNode wktRoot, String type) { - - if (type.equals(MysqlGeometry.POINTTYPE)) { - return createPoint(wktRoot.getChildByNumber(0).getGeoWKT()); - } else if (type.equals(MysqlGeometry.LINESTRINGTYPE)) { - return createLine(wktRoot.getChildByNumber(0).getGeoWKT()); - } else if (type.equals(MysqlGeometry.POLYGONTTYPE)) { - return createPolygon(wktRoot); - } else if (type.equals(MysqlGeometry.GEOMETRYCOLLECTIONTYPE)) { - MysqlCollection g = new MysqlCollection(); - WKTNode n = wktRoot.getChildByNumber(0); - String elementTypes = n.getGeoWKT(); - Vector typeVector = parseStringByToken(elementTypes, ','); - if (typeVector.size() == n.countChildren()) { - for (int i = 0; i < typeVector.size(); i++) { - WKTNode newRoot = new WKTNode(); - newRoot.setRoot(true); - newRoot.adChild(n.getChildByNumber(i)); - MysqlGeometry newGeometry = util(newRoot, - (String) typeVector.elementAt(i)); - g.addElement(newGeometry); - } - } else { - Debug.error("MysqlWKTGeometryFactory: Error in GeometryCollection"); - } - return g; - } else if (type.equals(MysqlGeometry.MULTIPOINTTYPE)) { - MysqlMultiPoint g = new MysqlMultiPoint(); - WKTNode n = wktRoot.getChildByNumber(0); - String pointString = n.getGeoWKT(); - Vector pointVector = parseStringByToken(pointString, ','); - for (int i = 0; i < pointVector.size(); i++) { - g.addElement(createPoint((String) pointVector.elementAt(i))); - } - - return g; - } else if (type.equals(MysqlGeometry.MULTILINESTRINGTYPE)) { - MysqlMultiLineString g = new MysqlMultiLineString(); - - WKTNode n = wktRoot.getChildByNumber(0); - - for (int i = 0; i < n.countChildren(); i++) { - String lineString = n.getChildByNumber(i).getGeoWKT(); - g.addElement(createLine(lineString)); - } - - return g; - } else if (type.equals(MysqlGeometry.MULTIPOLYGONTYPE)) { - MysqlMultiPolygon g = new MysqlMultiPolygon(); - - WKTNode n = wktRoot.getChildByNumber(0); - - for (int i = 0; i < n.countChildren(); i++) { - WKTNode newRoot = new WKTNode(); - newRoot.setRoot(true); - newRoot.adChild(n.getChildByNumber(i)); - g.addElement(createPolygon(newRoot)); - } - - return g; - } else { - Debug.output("MysqlWKTGeometryFactory: Type " + type - + " not implemented"); - return null; - } - } - - protected static MysqlPoint createPoint(String s) { - MysqlPoint g = new MysqlPoint(); - Vector v = parseStringByToken(s, ' '); - double[] d = createDoubleLatLongArray(v); - g.setNorthings(d[0]); - g.setEastings(d[1]); - return g; - } - - protected static MysqlLine createLine(String s) { - MysqlLine g = new MysqlLine(); - Vector v = parseStringByToken(s.replaceAll(",", " "), ' '); - double[] d = createDoubleLatLongArray(v); - g.setCoordinateArray(d); - return g; - } - - protected static MysqlPolygon createPolygon(WKTNode wktRoot) { - MysqlPolygon g = new MysqlPolygon(); - - WKTNode n = wktRoot.getChildByNumber(0); - - Vector rings = new Vector(); - for (int i = 0; i < n.countChildren(); i++) { - Vector v = parseStringByToken(n.getChildByNumber(i) - .getGeoWKT() - .replaceAll(",", " "), ' '); - double[] d = createDoubleLatLongArray(v); - rings.add(d); - } - g.setRings(rings); - - return g; - } - - protected static void iterateWKTNodeTree(WKTNode n) { - if (Debug.debugging("mysql")) { - Debug.output("------------"); - } - - for (int i = 0; i < n.countChildren(); i++) { - WKTNode child = n.getChildByNumber(i); - - if (Debug.debugging("mysql")) { - Debug.output(child.getGeoWKT() + " " + child.isLeaf()); - } - - iterateWKTNodeTree(child); - } - } - - protected static WKTNode parseGeometryText(String coordString) { - int i = coordString.indexOf("("); - int j = coordString.lastIndexOf(")") + 1; - coordString = coordString.substring(i, j); - char[] ca = coordString.toCharArray(); - - WKTNode rootnode = new WKTNode(); - rootnode.setRoot(true); - - WKTNode actualNode; - - actualNode = rootnode; - char actualDelimiter = '#'; - for (int k = 0; k < ca.length; k++) { - if (ca[k] == '(') { - - WKTNode n = new WKTNode(); - n.setParent(actualNode); - actualNode.adChild(n); - actualNode = n; - actualDelimiter = '('; - } else if (ca[k] == ')') { - if (actualDelimiter == '(') { - actualNode.setLeaf(true); - } - actualNode = actualNode.getParent(); - actualDelimiter = ')'; - } else { - char[] c = new char[1]; - c[0] = ca[k]; - actualNode.adToGeoWKT(c); - } - } - - return rootnode; - } - - // private static Vector iterateString(String s) { - - // int low = 0; - // int up = 0; - - // s = s.replaceAll(","," "); - // Vector coordVector = new Vector(); - - // while(up != -1) - // { - // up = s.indexOf(" "); - - // if (up != -1 ) { - // Double d = new Double(s.substring(low,up)); - // coordVector.addElement(d); - // s = s.substring(up+1,s.length()); - - // } - // else - // { - - // Double d = new Double(s); - // coordVector.addElement(d); - // } - - // } - - // return coordVector; - // } - - // private static double[] createDoubleLatLongArray(Vector v) { - // int i = v.size(); - // double[] darray = new double[i]; - - // for (int j = 0; j < i / 2; j++) { - - // for(int k = 0; k < 2; k++){ - // if (j == 0) { - // Double d = (Double) v.elementAt(1 - k); - // darray[k] = d.doubleValue(); - // } else { - // Double d = (Double) v.elementAt(2 * j + 1 - k); - // darray[2 * j + k] = d.doubleValue(); - - // } - - // } - - // } - // return darray; - // } - - protected static double[] createDoubleLatLongArray(Vector v) { - int i = v.size(); - double[] darray = new double[i]; - - for (int j = 0; j < i / 2; j++) { - for (int k = 0; k < 2; k++) { - if (j == 0) { - try { - Double d = new Double((String) v.elementAt(1 - k)); - darray[k] = d.doubleValue(); - } catch (Exception e) { - Debug.error((String) v.elementAt(1 - k)); - } - } else { - Double d = new Double((String) v.elementAt(2 * j + 1 - k)); - darray[2 * j + k] = d.doubleValue(); - } - } - } - return darray; - } - - protected static Vector parseStringByToken(String s, char token) { - - char[] ca = s.toCharArray(); - char[] charArray; - if (ca[ca.length - 1] != token) { - char[] tk = new char[1]; - tk[0] = token; - String s1 = s.concat(new String(tk)); - charArray = s1.toCharArray(); - } else { - charArray = ca; - } - - String t = new String(); - Vector v = new Vector(); - for (int i = 0; i < charArray.length; i++) { - if (charArray[i] == token) { - v.add(t); - t = ""; - } else { - char[] c = new char[1]; - c[0] = charArray[i]; - t = t.concat(new String(c)); - } - } - return v; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/mysql/WKTNode.java b/src/core/src/main/java/com/bbn/openmap/layer/mysql/WKTNode.java deleted file mode 100755 index afe1c4927..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/mysql/WKTNode.java +++ /dev/null @@ -1,122 +0,0 @@ -/* *********************************************************************** - * This is used by the MysqlGeometryLayer. - * This program is distributed freely and 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. - * - * Copyright 2003 by the Author - * - * Author name: Uwe Baier uwe.baier@gmx.net - * Version 1.0 - * *********************************************************************** - */ -package com.bbn.openmap.layer.mysql; - -import java.util.Vector; - -/** - * This class represents a Node used to construct a tree while parsing - * the WKT (text) representation of the Geometry. - * - * Copyright 2003 by the Author
- *

- * - * @author Uwe Baier uwe.baier@gmx.net
- * @version 1.0
- */ -public class WKTNode { - - private boolean root = false; - private boolean leaf = false; - - private Vector children = new Vector(); - private WKTNode parent; - private String geoWKT = ""; - - /** - * Returns the geoWKT. - * - * @return String - */ - public String getGeoWKT() { - return geoWKT; - } - - /** - * Returns the leaf. - * - * @return boolean - */ - public boolean isLeaf() { - return leaf; - } - - /** - * Returns the parent. - * - * @return WKTNode - */ - - public WKTNode getParent() { - return parent; - } - - /** - * Returns the root. - * - * @return boolean - */ - public boolean isRoot() { - return root; - } - - /** - * Sets the geoWKT. - * - * @param c The geoWKT to set - */ - public void adToGeoWKT(char[] c) { - this.geoWKT = geoWKT.concat(new String(c)); - } - - /** - * Sets the leaf. - * - * @param leaf The leaf to set - */ - public void setLeaf(boolean leaf) { - this.leaf = leaf; - } - - /** - * Sets the parent. - * - * @param parent The parent to set - */ - public void setParent(WKTNode parent) { - this.parent = parent; - } - - /** - * Sets the root. - * - * @param root The root to set - */ - public void setRoot(boolean root) { - this.root = root; - } - - public int countChildren() { - return this.children.size(); - } - - public void adChild(WKTNode n) { - this.children.add(n); - n.setParent(this); - } - - public WKTNode getChildByNumber(int i) { - return (WKTNode) this.children.elementAt(i); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/nexrad/NexradLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/nexrad/NexradLayer.java deleted file mode 100644 index a39c2af47..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/nexrad/NexradLayer.java +++ /dev/null @@ -1,249 +0,0 @@ -/* ********************************************************************** - * - * Ranching Systems Group - * Texas Agricultural Experiment Station - * Department of Rangeland Ecology and Management - * Mail Stop 212 - * College Station, TX 77801 - * - * Copyright (C) 2000 - * This software is subject to copyright protection under the laws of - * the United States and other countries. - * - * ********************************************************************** - * Fri Feb 4 10:20:34 CST 2000 Dan Schmitt (creation) - * ********************************************************************** - */ - -package com.bbn.openmap.layer.nexrad; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Properties; -import java.util.StringTokenizer; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; - -/** - * Implement a Layer that displays nexrad rainfall data. - *

- * 
- *  # zero value color (ARGB)
- *  nexrad.color.bg=ffb3b3b3
- *  # max value color (ARGB)
- *  nexrad.color.fg=ff000000
- *  # max rainfall value
- *  nexrad.rain.max=6000
- *  # min rainfall value
- *  nexrad.rain.min=0
- *  # URL for data file
- *  nexrad.url=http://a.b.gov/file
- *  
- * 
- *

- * NOTE: the color properties do not support alpha value if running on JDK 1.1. - */ -public class NexradLayer extends OMGraphicHandlerLayer { - - // property keys - public final static transient String plotColorProperty = ".color.plot"; - public final static transient String fontProperty = ".font"; - public final static transient String maxRainProperty = ".rain.max"; - public final static transient String minRainProperty = ".rain.min"; - public final static transient String dataURLProperty = ".url"; - - // properties - protected Color plotColor = new Color(0, 0, 200); - protected int maxRain = 1000; - protected int minRain = 0; - protected URL dataURL = null; - protected Font legendFont = Font.decode("SanSerif"); - - /** - * Construct the DateLayer. - */ - public NexradLayer() { - setName("Nexrad"); - } - - /** - * Sets the properties for the Layer. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - plotColor = ColorFactory.parseColorFromProperties(props, prefix - + plotColorProperty, "0000C8"); - - String tmpMaxRain = props.getProperty(prefix + maxRainProperty); - if (tmpMaxRain != null) { - try { - maxRain = Integer.valueOf(tmpMaxRain).intValue(); - } catch (NumberFormatException e) { - maxRain = 1000; - } - } - - String tmpMinRain = props.getProperty(prefix + minRainProperty); - if (tmpMinRain != null) { - try { - minRain = Integer.valueOf(tmpMinRain).intValue(); - } catch (NumberFormatException e) { - minRain = 0; - } - } - try { - dataURL = new URL(props.getProperty(prefix + dataURLProperty)); - loadData(dataURL); - } catch (java.net.MalformedURLException e) { - dataURL = null; - } - - legendFont = Font.decode(props.getProperty(prefix + fontProperty)); - - } - - public void loadData(URL theDataStream) { - try { - BufferedReader f = new BufferedReader(new InputStreamReader(theDataStream.openStream())); - StringTokenizer tok = new StringTokenizer(f.readLine()); - int ulhrapx = (new Integer(tok.nextToken())).intValue(); - int ulhrapy = (new Integer(tok.nextToken())).intValue(); - int maxx = (new Integer(tok.nextToken())).intValue(); - int maxy = (new Integer(tok.nextToken())).intValue(); - int rain[][] = new int[maxx][maxy]; - - if (Debug.debugging("nexrad")) { - Debug.output("NexradLayer: Reading " + theDataStream + " " - + maxx + " " + maxy); - } - for (int any = 0; any < maxy; any++) { - tok = new StringTokenizer(f.readLine()); - for (int anx = 0; anx < maxx; anx++) { - rain[anx][any] = (new Integer(tok.nextToken())).intValue(); - } - } - f.close(); - if (Debug.debugging("nexrad")) { - Debug.output("NexradLayer: Completed " + theDataStream + " " - + maxx + " " + maxy); - } - setList(createGraphics(ulhrapx, ulhrapy, maxx, maxy, rain)); - // } catch (java.io.IOException oops) { - } catch (Exception oops) { - Debug.error("NexradLayer.loadData: Failed to read " + theDataStream); - oops.printStackTrace(); - } - } - - public OMGraphicList createGraphics(int ulhrapx, int ulhrapy, int xcount, - int ycount, int rain[][]) { - - OMGraphicList graphics = new OMGraphicList(); - - double ul[] = { 0, 0 }; - double ur[] = { 0, 0 }; - double ll[] = { 0, 0 }; - double lr[] = { 0, 0 }; - - for (int x = 0; x < xcount; x++) { - ll = hrap2lonlat(ulhrapx + x, ulhrapy); - lr = hrap2lonlat(ulhrapx + x + 1, ulhrapy); - for (int y = 0; y < ycount; y++) { - ul = ll; - ur = lr; - ll = hrap2lonlat(ulhrapx + x, ulhrapy + y + 1); - lr = hrap2lonlat(ulhrapx + x + 1, ulhrapy + y + 1); - if (rain[x][y] > 0) { - - if (Debug.debugging("nexrad")) { - Debug.output("NexradLayer: Rain " + rain[x][y] + " " - + x + " " + y); - } - - double polypoints[] = { ul[0], ul[1], ur[0], ur[1], lr[0], - lr[1], ll[0], ll[1], ul[0], ul[1] }; - OMPoly poly = new OMPoly(polypoints, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT); - Color plotc = scaledColor(rain[x][y]); - poly.setFillPaint(plotc); - poly.setLinePaint(plotc); - graphics.add(poly); - } - } - } - return graphics; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(Graphics g) { - super.paint(g); - plotScale(g); - } - - public void plotScale(Graphics g) { - g.setColor(Color.red); - int nameMin = 1; - Font tmpFont = g.getFont(); - g.setFont(legendFont); - g.drawString(maxRain + " mm", 30, 30); - g.drawString(nameMin + " mm", 30, 450); - g.setFont(tmpFont); - int range = 430; - for (int k = 0; k <= range; k += 5) { - g.setColor(scaledColor(minRain + (k * (maxRain - minRain) / range))); - g.fillRect(10, 450 - k, 10, 5); - } - } - - public Color scaledColor(int value) { - int alphaValue = 15 * value / maxRain; - if (alphaValue > 15) - alphaValue = 15; - if (alphaValue < 0) - alphaValue = 0; - alphaValue *= 10; - alphaValue += 55; - return (new Color(plotColor.getRed(), plotColor.getGreen(), plotColor.getBlue(), alphaValue)); - } - - public double[] hrap2lonlat(int xhrap, int yhrap) { - float mesh = 4762.5f; - float earthr = 6371200.0f; - float stlond = -105.0f; - float stlatd = 60.0f; - float x = (xhrap - 401.0f) * mesh; - float y = (yhrap - 1601.0f) * mesh; - float arg = (float) (Math.pow(Math.pow(x, 2.0) + Math.pow(y, 2.0), 0.5) / (earthr * (1 + Math.sin(Math.toRadians(stlatd))))); - float latd = 90.0f - 2.0f * (float) Math.toDegrees(Math.atan(arg)); - float ang = (float) Math.toDegrees(Math.atan2(y, x)); - if (y > 0) { - ang = 270.0f - stlond - ang; - } else { - ang = -90.0f - stlond - ang; - } - float lond = 0f; - if (ang < 180) { - lond = -1.0f * ang; - } else { - lond = 360.0f - ang; - } - double res[] = { latd, lond }; - return res; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/nexrad/package.html b/src/core/src/main/java/com/bbn/openmap/layer/nexrad/package.html deleted file mode 100644 index 2fe944b31..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/nexrad/package.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Provides an OpenMap Layer that display Nexrad rainfall data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/nitf/NitfHeader.java b/src/core/src/main/java/com/bbn/openmap/layer/nitf/NitfHeader.java deleted file mode 100644 index d9af6eb10..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/nitf/NitfHeader.java +++ /dev/null @@ -1,301 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/nitf/NitfHeader.java,v $ -// $RCSfile: NitfHeader.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and to Theron Tock, who wrote the software, and - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used with permission. - */ - -package com.bbn.openmap.layer.nitf; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * The NitfHeader reads the header information in a NITF (National Imagery - * Transmission Format) and makes the section location information available. - */ -public class NitfHeader { - - public final static int NITF_IMAGE_DES_SIZE = 16; - public final static int NITF_SYMBOLS_DES_SIZE = 10; - public final static int NITF_LABELS_DES_SIZE = 7; - public final static int NITF_TEXT_DES_SIZE = 9; - public final static int NITF_DATAEXT_DES_SIZE = 13; - public final static int NITF_RESEXT_DES_SIZE = 11; - public final static int NITF_USERDEF_SIZE = 19; - - /** File type and Version */ - public String FHDR;// [9] - /** Compliance Level */ - public String CLEVEL;// [2] - /** System Type */ - public String STYPE;// [3] - /** Originating Station ID */ - public String OSTAID;// [10] - /** File Date and Time */ - public String FDT;// [14] - /** File Title */ - public String FTITLE;// [80] - /** File Security Classification */ - public String FSCLAS;// [1] - /** File Codewords */ - public String FSCODE;// [40] - /** File Control and Handling */ - public String FSCTLH;// [40] - /** File Releasing Instructions */ - public String FSREL;// [40] - /** File Classification Authority */ - public String FSCAUT;// [20] - /** File Security Control Number */ - public String FSCTLN;// [20] - /** File Security Downgrade */ - public String FSDWNG;// [6] - /** File Downgrading Event */ - public String FSDEVT;// [40] - /** Message Copy Number */ - public String FSCOP;// [5] - /** Message Number of Copies */ - public String FSCPYS;// [5] - /** Encryption */ - public String ENCRYP;// [1] - /** Originator's Name */ - public String ONAME;// [27] - /** Originator's Phone Number */ - public String OPHONE;// [18] - /** File Length */ - public String FL;// [12] - /** NITF File Header Length */ - public String HL;// [6] - - public NitfHeaderAmounts nha; - public NitfUserDef nud; - - public NitfHeader() { - nha = new NitfHeaderAmounts(); - nud = new NitfUserDef(); - } - - static public class NitfHeaderAmounts { - /** Number of Images */ - public String NUMI;// [3] - /** Number of Symbols */ - public String NUMS;// [3] - /** Number of Labels */ - public String NUML;// [3] - /** Number of Text Files */ - public String NUMT;// [3] - /** Number of Data Extensions */ - public String NUMDES;// [3] - /** Number of Reserved Extensions */ - public String NUMRES;// [3] - } - - static public class NitfImageDescription { - public String LISH;// [6] - public String LI;// [10] - } - - static public class NitfSymbolsDescription { - public String LSSH;// [4] - public String LS;// [6] - } - - static public class NitfLabelDescription { - public String LLSH;// [4] - public String LL;// [3] - } - - static public class NitfTextDescription { - public String LTSH;// [4] - public String LT;// [5] - } - - static public class NitfDataExtDescription { - public String LDSH;// [4] - public String LD;// [9] - } - - static public class NitfResExtDescription { - public String LRSH;// [4] - public String LR;// [7] - } - - static public class NitfUserDef { - public String UDHDL;// [5] - public String UDHOFL;// [3] - public String RETAG;// [6] - public String REL;// [5] - } - - /** - * Reads the header part of the file. Will seek automatically to the - * beginning of the file. - * - * @param binFile BinaryFile, opened on the NITF file. - */ - public boolean read(BinaryFile binFile) { - - try { - binFile.seek(0); - FHDR = binFile.readFixedLengthString(9); - if (!FHDR.startsWith("NITF")) - return false; /* Not an NITF file */ - - CLEVEL = binFile.readFixedLengthString(2); - STYPE = binFile.readFixedLengthString(4); - OSTAID = binFile.readFixedLengthString(10); - FDT = binFile.readFixedLengthString(14); - FTITLE = binFile.readFixedLengthString(80); - FSCLAS = binFile.readFixedLengthString(1); - FSCODE = binFile.readFixedLengthString(40); - FSCTLH = binFile.readFixedLengthString(40); - FSREL = binFile.readFixedLengthString(40); - FSCAUT = binFile.readFixedLengthString(20); - FSCTLN = binFile.readFixedLengthString(20); - FSDWNG = binFile.readFixedLengthString(6); - - if (FSDWNG.startsWith("999998")) - FSDEVT = binFile.readFixedLengthString(40); - - FSCOP = binFile.readFixedLengthString(5); - FSCPYS = binFile.readFixedLengthString(5); - ENCRYP = binFile.readFixedLengthString(1); - ONAME = binFile.readFixedLengthString(27); - OPHONE = binFile.readFixedLengthString(18); - FL = binFile.readFixedLengthString(12); - HL = binFile.readFixedLengthString(6); - - nha = readSectionInfo(binFile); - - nud.UDHDL = binFile.readFixedLengthString(5);// [5] - nud.UDHOFL = binFile.readFixedLengthString(3);// [3] - nud.RETAG = binFile.readFixedLengthString(6);// [6] - nud.REL = binFile.readFixedLengthString(5);// [5] - - } catch (IOException e) { - System.err.println("NitfHeader: File IO Error while reading header information:"); - System.err.println(e); - return false; - } catch (FormatException f) { - System.err.println("NitfHeader: File IO Format error while reading header information:"); - System.err.println(f); - return false; - } - - return true; - } - - protected NitfHeaderAmounts readSectionInfo(BinaryFile binFile) { - - try { - nha.NUMI = binFile.readFixedLengthString(3); - binFile.seek(binFile.getFilePointer() - + (Integer.parseInt(nha.NUMI) * NITF_IMAGE_DES_SIZE)); - - nha.NUMS = binFile.readFixedLengthString(3); - binFile.seek(binFile.getFilePointer() - + (Integer.parseInt(nha.NUMS) * NITF_SYMBOLS_DES_SIZE)); - - nha.NUML = binFile.readFixedLengthString(3); - binFile.seek(binFile.getFilePointer() - + (Integer.parseInt(nha.NUML) * NITF_LABELS_DES_SIZE)); - - nha.NUMT = binFile.readFixedLengthString(3); - binFile.seek(binFile.getFilePointer() - + (Integer.parseInt(nha.NUMT) * NITF_TEXT_DES_SIZE)); - - nha.NUMDES = binFile.readFixedLengthString(3); - binFile.seek(binFile.getFilePointer() - + (Integer.parseInt(nha.NUMDES) * NITF_DATAEXT_DES_SIZE)); - - nha.NUMRES = binFile.readFixedLengthString(3); - } catch (IOException e) { - System.err.println("NitfHeader: File IO Error while reading header information:"); - System.err.println(e); - return null; - } catch (FormatException f) { - System.err.println("NitfHeader: File IO Format error while reading header information:"); - System.err.println(f); - return null; - } - - return nha; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("\n\nNITF Information about ").append(FTITLE).append("\n"); - s.append("-------------------\n"); - s.append("File Type: ").append(FHDR).append("\n"); - s.append("Compliance Level: ").append(CLEVEL).append("\n"); - s.append("System Type: ").append(STYPE).append("\n"); - s.append("Originating Station: ").append(OSTAID).append("\n"); - s.append("File Date and Time: ").append(FDT).append("\n"); - s.append("Originator's Name: ").append(ONAME).append("\n"); - s.append("File Length: ").append(FL).append("\n\n"); - - s.append(nha.NUMI).append(" image\n"); - s.append(nha.NUMS).append(" symbol\n"); - s.append(nha.NUML).append(" label\n"); - s.append(nha.NUMT).append(" text\n"); - s.append(nha.NUMDES).append(" dataext\n"); - s.append(nha.NUMRES).append(" resext\n"); - return s.toString(); - } - - public final static void main(String[] args) { - if (args.length != 1) { - System.out.println("Usage: java NitfHeader "); - return; - } - - File file = new File(args[0]); - BinaryFile binFile = null; - try { - binFile = new BinaryBufferedFile(file); - // binFile = new BinaryFile(file); - - NitfHeader header = new NitfHeader(); - if (header.read(binFile)) { - System.out.println(header); - } else { - System.out.println("NitfHeader: NOT read successfully!"); - } - } catch (FileNotFoundException e) { - System.err.println("NitfHeader: file " + args[0] + " not found"); - System.exit(1); - } catch (IOException ioe) { - System.err.println("NitfHeader: File IO Error while handling NITF header:"); - System.err.println(ioe); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/nitf/package.html b/src/core/src/main/java/com/bbn/openmap/layer/nitf/package.html deleted file mode 100644 index 1b41d175a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/nitf/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides utility code for dealing with data in NITF (National Imagery -Transmission Format) data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/package.html b/src/core/src/main/java/com/bbn/openmap/layer/package.html deleted file mode 100644 index 4d548ee61..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Contains OpenMap layers that read and display a variety of data -formats, and a few that create their own data for display. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBEData.java b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBEData.java deleted file mode 100644 index 1103bdc06..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBEData.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBEData.java,v -// $ -// $RCSfile: GLOBEData.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -public abstract class GLOBEData { - - public GLOBEData() { - } - - public void loadData(InputStream instream) throws IOException { - readDataFromStream(instream); - } - - protected abstract void parseDataFromStream(String line); - - public void readDataFromStream(InputStream istream) throws IOException { - - BufferedReader buffstream = new BufferedReader(new InputStreamReader(istream), 65536); - - while (true) { - String line = buffstream.readLine(); - if (line == null) - break; - line = line.trim(); - // ignore comments - if (line.length() == 0 || line.startsWith("#")) { - continue; - } - parseDataFromStream(line); - } - } - - /* - * public static void main (String argv[]) { try { - * System.out.println("Getting URL: " + argv[0]); GLOBEData datafile = new - * GLOBEData(argv[0]); datafile.loadData(); } catch (IOException e) { - * System.err.println(e); } } - */ - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBESite.java b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBESite.java deleted file mode 100644 index ef683ee32..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBESite.java +++ /dev/null @@ -1,142 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBESite.java,v -// $ -// $RCSfile: GLOBESite.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 18:44:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; - -public class GLOBESite { - - private float lon, lat; - - private float maxYear = -9999; - private float minYear = 99999; - private float maxTemp = -99999; - private float minTemp = 99999; - - private Map temperatureTable = null; - - private String name; - - private OMGraphic omg; - - public GLOBESite(float lat, float lon) { - this.lon = lon; - this.lat = lat; - - name = "(" + lat + ", " + lon + ")"; - - // graphic_ = new OMCircle(lat, lon, 5,5, 11, 11, - // default_bits_); - omg = new OMCircle(lat, lon, 5, 5); - omg.setLinePaint(Color.red); - omg.setFillPaint(Color.red); - omg.setSelectPaint(Color.yellow); - omg.putAttribute(OMGraphic.APP_OBJECT, this); - - temperatureTable = new HashMap<>(); - } - - public String hash() { - return name; - } - - public void addCurrentTemp(float year, float temp) { - temperatureTable.put(new Float(year), new Float(temp)); - } - - public float getCurrentTemp(float year) { - return ((Number) temperatureTable.get(new Float(year))).floatValue(); - } - - public float getLatitude() { - return lat; - } - - public float getLongitude() { - return lon; - } - - public final OMGraphic getGraphic() { - return omg; - } - - public String getName() { - return name; - } - - public Map getAllYears() { - return temperatureTable; - } - - public float getMaxTemp() { - return maxTemp; - } - - public float getMinTemp() { - return minTemp; - } - - public float getMaxYear() { - return maxYear; - } - - public float getMinYear() { - return minYear; - } - - public float getValueForYear(float year) { - if (temperatureTable.containsKey(new Float(year))) { - return temperatureTable.get(year); - } - return -99; - } - - protected void recalcLimits() { - for (Float year : temperatureTable.keySet()) { - - float temp = temperatureTable.get(year); - if (year > maxYear) - maxYear = year; - if (year < minYear) - minYear = year; - - if (temp > maxTemp) - maxTemp = temp; - if (temp < minTemp) - maxTemp = temp; - } - } - - public String getInfo() { - int numpoints = temperatureTable.size(); - return name + " -- " + numpoints + " datapoints available"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBETempData.java b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBETempData.java deleted file mode 100644 index fbd288234..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/GLOBETempData.java +++ /dev/null @@ -1,173 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBETempData.java,v -// $ -// $RCSfile: GLOBETempData.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 18:44:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.text.DecimalFormat; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.StringTokenizer; - -public class GLOBETempData extends GLOBEData { - - protected static float NO_VALUE = -99; - - private Map siteTable = new HashMap<>(); - - public float overall_min_year_ = Float.NaN; - public float overall_max_year_ = Float.NaN; - public float overall_min_temp_ = Float.NaN; - public float overall_max_temp_ = Float.NaN; - - public GLOBETempData() { - super(); - } - - /* - * Data Format: - *

-     * Air Temperature:
-     * Field 1 = AT 
-     * Field 2 = GLOBE phase number (1 or 2)
-     * Field 3 = Site number
-     * Field 4 = Time the data was reported, YYYYMMDD where YYYY = Calendar year MM = Calendar month (starting with 1 = January) DD = Day of month (starting with 1) 
-     * Field 5 = Time the data was sampled, YYYYMMDDHH where YYYY = Calendar year MM = Calendar month (starting with 1 = January) DD = Day of month (starting with 1) HH = Hour of day (00-23)
-     * Field 6 = Decimal year
-     * Field 7 = Measurement location latitude
-     * Field 8 = Measurement location longitude (+ = East, - = West)
-     * Field 9 = Measurement location elevation (meters above sea level)
-     * Field 10 = Current air temperature (degrees Celsius) [Missing value = -99.0]
-     * Field 11 = Daily maximum air temperature (degrees Celsius) [Missing value = -99.0]
-     * Field 12 = Daily minimum air temperature (degrees Celsius) [Missing value = -99.0]
-     * 
-     * Example: AT 1 1 19961218 1996121814 1996.96334 44.1281 -68.8747 14 18 22 -2
-     *
- * - */ - protected void parseDataFromStream(String line) { - StringTokenizer tokenizer = new StringTokenizer(line); - DecimalFormat dec_format = new DecimalFormat(); - - try { - - for (int i = 0; i < 2; i++) - tokenizer.nextToken(); - /*int site_number = */dec_format.parse(tokenizer.nextToken()) - .intValue(); - - for (int i = 0; i < 2; i++) - tokenizer.nextToken(); - float time = dec_format.parse(tokenizer.nextToken()).floatValue(); - - float latitude = dec_format.parse(tokenizer.nextToken()) - .floatValue(); - float longitude = dec_format.parse(tokenizer.nextToken()) - .floatValue(); - - tokenizer.nextToken(); // ignore Field 9 - - float current_temp = dec_format.parse(tokenizer.nextToken()) - .floatValue(); - - // float max_temp = - // dec_format.parse( tokenizer.nextToken() ).floatValue(); - // float min_temp = - // dec_format.parse( tokenizer.nextToken() ).floatValue(); - - // Now process the data we just parsed. - - GLOBESite site = findSite(latitude, longitude); - - if (current_temp != NO_VALUE) { - site.addCurrentTemp(time, current_temp); - checkLimits(current_temp, time); - } - // if ( max_temp != NO_VALUE ) - // { site.addMinTemp(time, max_temp); } - // if ( min_temp != NO_VALUE ) - // { site.addMinTemp(time, min_temp); } - - // System.out.println(" site: " + site_number - // + " time: " + time - // + " lat: " + latitude - // + " lon: " + longitude - // + " t1-3: " + current_temp - // + " (" + max_temp - // + "," + min_temp + ")" ); - - } catch (NoSuchElementException e) { - System.err.println(e + ": " + e.getMessage()); - } catch (ParseException e) { - System.err.println(e); - } - } - - /** - * See if these values for temp and year are outside of our - * current notion of how large our data space is. - *

- * - * @param temp - * @param year - */ - - private void checkLimits(float temp, float year) { - if (Float.isNaN(overall_max_temp_) || temp > overall_max_temp_) - overall_max_temp_ = temp; - if (Float.isNaN(overall_min_temp_) || temp < overall_min_temp_) - overall_min_temp_ = temp; - - if (Float.isNaN(overall_max_year_) || year > overall_max_year_) - overall_max_year_ = year; - if (Float.isNaN(overall_min_year_) || year < overall_min_year_) - overall_min_year_ = year; - } - - private GLOBESite findSite(float latitude, float longitude) { - GLOBESite site = new GLOBESite(latitude, longitude); - GLOBESite hashed_site = siteTable.get(site.hash()); - - if (hashed_site == null) { - // System.out.println("hash_miss: " + latitude + " " + - // longitude); - siteTable.put(site.hash(), site); - hashed_site = site; - } - return hashed_site; - } - - public Map getAllSites() { - return siteTable; - } - - /* - * public static void main (String argv[]) { try { - * System.out.println("Getting URL: " + temp_data_source_); - * GLOBETempData datafile = new GLOBETempData(); - * datafile.loadData(); } catch (IOException e) { - * System.err.println(e); } } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/PlotLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/PlotLayer.java deleted file mode 100644 index 7a75f8c66..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/PlotLayer.java +++ /dev/null @@ -1,509 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/PlotLayer.java,v $ -// $RCSfile: PlotLayer.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 18:44:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * - */ -public class PlotLayer extends OMGraphicHandlerLayer implements MapMouseListener { - - private static final long serialVersionUID = 1L; - private ScatterGraph graph = null; - private boolean show_plot_ = false; - - // The currently selected graphic. - private OMGraphic selectedGraphic; - private List selectedGraphics = null; - - // Where do we get the data from? - // default to use GLOBE atmospheric temperature. - private String datasource = "com/bbn/openmap/layer/plotLayer/AT.gst_small.txt"; - - // "http://globe.ngdc.noaa.gov/sda/student_data/AT.gst.txt"; - - // The control palette - private JPanel pal = null; - - /** - * X position of the plot rectangle. - */ - protected int plotX = 100; - - /** - * Y position of the plot rectangle. - */ - protected int plotY = 100; - - /** - * Width of the plot rectangle. - */ - protected int plotWidth = 320; - - /** - * Height of the plot rectangle. - */ - protected int plotHeight = 200; - - /** - * Construct the PlotLayer. - */ - public PlotLayer() { - } - - public synchronized OMGraphicList prepare() { - if (graph == null) { - GLOBETempData temperatureData = getDataSource(); - if (temperatureData != null) { - graph = new ScatterGraph(678, 790, null, temperatureData.overall_min_year_, temperatureData.overall_max_year_, temperatureData.overall_min_temp_, temperatureData.overall_max_temp_); - - setList(plotDataSources(temperatureData)); - - } - } - - Projection proj = getProjection(); - if (proj != null && graph != null) { - // graph.resize(plotX, plotY, plotWidth, plotHeight); - graph.resize(0, 0, proj.getWidth(), proj.getHeight()); - } - return super.prepare(); - } - - /** - * Search for the data in the directories listing in the CLASSPATH. We - * should also check to see if the datafile is specified as a URL so that we - * can load it as such. - */ - private GLOBETempData getDataSource() { - - // load the data from the CLASSPATH - List dirs = Environment.getClasspathDirs(); - FileInputStream is = null; - int nDirs = dirs.size(); - if (nDirs > 0) { - for (String dir : dirs) { - File datafile = new File(dir, datasource); - if (datafile.isFile()) { - try { - is = new FileInputStream(datafile); - // System.out.println("datafile="+datafile); - break; - } catch (java.io.IOException e) { - e.printStackTrace(); - } - } - } - if (is == null) { - System.err.println("Unable to load datafile \"" + datasource + "\" from CLASSPATH"); - } - } else { - System.err.println("No directories in CLASSPATH!"); - System.err.println("Unable to load datafile \"" + datasource + "\" from CLASSPATH"); - } - if (is == null) - return null; - - // Parse the data - GLOBETempData temperature_data = null; - try { - temperature_data = new GLOBETempData(); - temperature_data.loadData(is); - } catch (IOException e) { - System.err.println(e); - } - return temperature_data; - } - - /** Put the data points on the map. */ - private OMGraphicList plotDataSources(GLOBETempData temperature_data) { - Debug.message("basic", "PlotLayer.plotDataSources()"); - int num_graphics = 0; - - OMGraphicList graphics = new OMGraphicList(); - graphics.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - Map site_enum = temperature_data.getAllSites(); - for (GLOBESite site : site_enum.values()) { - // Debug.message("basic", "PlotLayer adds " + site.getName()); - graphics.add(site.getGraphic()); - num_graphics++; - } - - Debug.message("basic", "Plotlayer found " + num_graphics + " distinct sites"); - - // Find the sites that are visible on the map. - return graphics; - } - - /** Build and display the plot. */ - private OMGraphic generatePlot() { - // System.out.println("Generating Plot "); - if (graph != null) { - graph.setDataPoints(selectedGraphics); - graph.plotData(); - return graph.getPlotGraphics(); - } - return null; - } - - private void showPlot() { - show_plot_ = true; - - OMGraphic plot = generatePlot(); - OMGraphicList list = getList(); - - if (plot != null && list != null) { - // System.out.println("Making plot visible.."); - list.add(plot); - // generate the graphics for rendering. - list.generate(getProjection(), false); - } - repaint(); - } - - private void hidePlot() { - // System.out.println("Making plot IN-visible.."); - show_plot_ = false; - if (graph != null) { - OMGraphic plot = graph.getPlotGraphics(); - OMGraphicList list = getList(); - - if (list != null && plot != null) { - list.remove(plot); - } - } - repaint(); - } - - /** - * Add the data from the clicked site to the list of things we are drawing. - */ - private void addSelectionToPlotList() { - if (selectedGraphic != null) { - // Change the color of the clicked ones - selectedGraphic.setLinePaint(Color.blue); - - if (selectedGraphics == null) { - selectedGraphics = new Vector(); - } - - Object app_obj = selectedGraphic.getAttribute(OMGraphic.APP_OBJECT); - - if (app_obj instanceof GLOBESite) { - GLOBESite site = (GLOBESite) app_obj; - if (!selectedGraphics.contains(app_obj)) { - Debug.message("basic", "Adding to plot list..."); - selectedGraphics.add(site); - selectedGraphic.setFillPaint(Color.yellow); - } else { - Debug.message("basic", "Removing from plot list..."); - selectedGraphics.remove(site); - selectedGraphic.setFillPaint(Color.red); - selectedGraphic.setLinePaint(Color.red); - } - - } - } else { - Debug.message("basic", "Nothing to add to plot list!"); - } - } - - /** - * Returns self as the MapMouseListener in order to receive - * MapMouseEvents. If the implementation would prefer to - * delegate MapMouseEvents, it could return the delegate from - * this method instead. - * - * @return The object to receive MapMouseEvent s or null if - * this layer isn't interested in MapMouseEvent s - */ - public MapMouseListener getMapMouseListener() { - return this; - } - - public Component getGUI() { - if (pal == null) { - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - int index = Integer.parseInt(e.getActionCommand(), 10); - switch (index) { - case 0: - if (show_plot_) - hidePlot(); - else - showPlot(); - break; - default: - throw new RuntimeException("argh!"); - } - } - }; - pal = PaletteHelper.createCheckbox("Plot Control", new String[] { "Show Temperature Plot" }, new boolean[] { show_plot_ }, al); - } - return pal; - } - - // ---------------------------------------------------------------------- - // MapMouseListener interface implementation - // ---------------------------------------------------------------------- - - /** - * Indicates which mouse modes should send events to this Layer - * . - * - * @return String[] of mouse mode names - * - * @see com.bbn.openmap.event.MapMouseListener - * @see com.bbn.openmap.MouseDelegator - */ - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - // graphic position variables when moving the plot graphic - private int prevX, prevY; - private boolean grabbed_plot_graphics_ = false; - - /** - * Called whenever the mouse is pressed by the user and one of the requested - * mouse modes is active. - * - * @param e the press event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mousePressed(MouseEvent e) { - if (show_plot_ && graph != null) { - int x = e.getX(); - int y = e.getY(); - if ((x >= plotX) && (x <= plotX + plotWidth) && (y >= plotY) - && (y <= plotY + plotWidth)) { - - grabbed_plot_graphics_ = true; - // grab the location - prevX = x; - prevY = y; - } - } - return false; - } - - /** - * Called whenever the mouse is released by the user and one of the - * requested mouse modes is active. - * - * @param e the release event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseReleased(MouseEvent e) { - grabbed_plot_graphics_ = false; - return false; - } - - /** - * Called whenever the mouse is clicked by the user and one of the requested - * mouse modes is active. - * - * @param e the click event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseClicked(MouseEvent e) { - // System.out.println("XY: " + e.getX() + " " + e.getY() ); - if (selectedGraphic != null && !show_plot_) { - switch (e.getClickCount()) { - case 1: - /** - * One click adds the site to our list of sites to plot. - */ - addSelectionToPlotList(); - generatePlot(); - repaint(); - break; - case 2: - /** - * Double click means generate the plot. - */ - // System.out.println("Saw DoubleClick!"); - repaint(); - break; - default: - break; - } - return true; - } else { - return false; - } - } - - /** - * Called whenever the mouse enters this layer and one of the requested - * mouse modes is active. - * - * @param e the enter event - * @see #getMouseModeServiceList - */ - public void mouseEntered(MouseEvent e) { - } - - /** - * Called whenever the mouse exits this layer and one of the requested mouse - * modes is active. - * - * @param e the exit event - * @see #getMouseModeServiceList - */ - public void mouseExited(MouseEvent e) { - } - - /** - * Called whenever the mouse is dragged on this layer and one of the - * requested mouse modes is active. - * - * @param e the drag event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseDragged(MouseEvent e) { - if (grabbed_plot_graphics_) { - int x = e.getX(); - int y = e.getY(); - int dx = x - prevX; - int dy = y - prevY; - - plotX += dx; - plotY += dy; - prevX = x; - prevY = y; - - graph.resize(plotX, plotY, plotWidth, plotHeight); - OMGraphicList plotGraphics = graph.getPlotGraphics(); - // regenerate the plot graphics - plotGraphics.generate(getProjection(), true); - repaint(); - } - return false; - } - - /** - * Called whenever the mouse is moved on this layer and one of the requested - * mouse modes is active. - *

- * Tries to locate a graphic near the mouse, and if it is found, it is - * highlighted and the Layer is repainted to show the highlighting. - * - * @param e the move event - * @return true if event was consumed (handled), false otherwise - * @see #getMouseModeServiceList - */ - public boolean mouseMoved(MouseEvent e) { - OMGraphic newSelectedGraphic; - - if (show_plot_ && graph != null) { - - newSelectedGraphic = graph.selectPoint(e.getX(), e.getY(), 4.0f); - - if (newSelectedGraphic != null) { - String infostring = (String) (newSelectedGraphic.getAttribute(OMGraphic.APP_OBJECT)); - if (infostring != null) { - fireRequestInfoLine(infostring); - } - } else { - fireRequestInfoLine(""); - } - - return true; - } else { - OMGraphicList list = getList(); - if (list != null) { - newSelectedGraphic = list.selectClosest(e.getX(), e.getY(), 4.0f); - - if (newSelectedGraphic != null - && (selectedGraphic == null || newSelectedGraphic != selectedGraphic)) { - - Debug.message("basic", "Making selection..."); - - selectedGraphic = newSelectedGraphic; - // selectedGraphic.setLineColor(Color.yellow); - selectedGraphic.regenerate(getProjection()); - - // display site info on map - GLOBESite site = (GLOBESite) (newSelectedGraphic.getAttribute(OMGraphic.APP_OBJECT)); - if (site != null) { - fireRequestInfoLine(site.getInfo()); - } - - repaint(); - } else if (selectedGraphic != null && newSelectedGraphic == null) { - - // revert color of un-moused object. - Debug.message("basic", "Clearing selection..."); - // selectedGraphic.setLineColor(Color.red); - selectedGraphic.regenerate(getProjection()); - fireRequestInfoLine(""); - selectedGraphic = null; - repaint(); - } - return true; - } - } - return false; - } - - /** - * Called whenever the mouse is moved on this layer and one of the requested - * mouse modes is active, and the gesture is consumed by another active - * layer. We need to deselect anything that may be selected. - * - * @see #getMouseModeServiceList - */ - public void mouseMoved() { - getList().deselect(); - repaint(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/ScatterGraph.java b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/ScatterGraph.java deleted file mode 100644 index 43321c45d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/ScatterGraph.java +++ /dev/null @@ -1,443 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/ScatterGraph.java,v -// $ -// $RCSfile: ScatterGraph.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:44:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Paint; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.Debug; - -public class ScatterGraph { - - // Color to display the plot in. - private final Paint plot_color_ = Color.black; - private final Paint graph_bg_color = Color.white; - private final Paint select_color_ = Color.red; - - protected OMGraphicList plot_graphics_ = null; - protected OMGraphicList plot_points_ = null; - protected OMGraphicList plot_background_ = null; - - // pixels from edge of frame to the Plot itself - private final int border_width_ = 50; - - private boolean axes_displayed_ = false; - private float temp_scale_ = Float.NaN; - private float year_scale_ = Float.NaN; - - private float max_year_ = Float.NaN; - private float min_year_ = Float.NaN; - - private float max_temp_ = Float.NaN; - private float min_temp_ = Float.NaN; - - /** List of the GLOBESites that are currently displayed on the map. */ - private List sites_displayed_ = null; - - // the size and position of the available drawing area - private int frame_x, frame_y; - private int frame_height_, frame_width_; - private int plot_height_, plot_width_; - - private void initialize(int height, int width, int xoffset, int yoffset, - List sites, float minyear, float maxyear, - float mintemp, float maxtemp) { - plot_graphics_ = new OMGraphicList(); - plot_points_ = new OMGraphicList(); - plot_background_ = new OMGraphicList(); - - plot_graphics_.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - plot_points_.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - plot_background_.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - max_year_ = maxyear; - min_year_ = minyear; - - max_temp_ = maxtemp; - min_temp_ = mintemp; - - resizeGraph(frame_x, frame_y, height, width); - setDataPoints(sites); - resetScale(); - - plotData(); - } - - /** - * Set up the size of the graph, and scale all the axes correctly. - */ - public ScatterGraph(int height, int width, List sites, float minyear, - float maxyear, float mintemp, float maxtemp) { - initialize(height, - width, - 0, - 0, - sites, - minyear, - maxyear, - mintemp, - maxtemp); - } - - public ScatterGraph(int height, int width, int xoffset, int yoffset, - List sites, float minyear, float maxyear, float mintemp, - float maxtemp) { - initialize(height, - width, - xoffset, - yoffset, - sites, - minyear, - maxyear, - mintemp, - maxtemp); - } - - public void resize(int x, int y, int newwidth, int newheight) { - plot_graphics_.clear(); - plot_points_.clear(); - plot_background_.clear(); - - resizeGraph(x, y, newheight, newwidth); - axes_displayed_ = false; - // replot everything on the graph - plotData(); - } - - // If the window changes size, we need to resize the graph, and - // replot. - private void resizeGraph(int x, int y, int height, int width) { - // Setup the sizes. - frame_x = x; - frame_y = y; - frame_width_ = width; - frame_height_ = height; - plot_width_ = frame_width_ - 2 * border_width_; - plot_height_ = frame_height_ - 2 * border_width_; - - resetScale(); - } - - /** - * Set the max and min points (as well as the scale factors) for - * the plot. - * - * @param minyear lowest year - * @param maxyear highest year - * @param mintemp lowest temperature - * @param maxtemp highest temperature - */ - private void setScale(float minyear, float maxyear, float mintemp, - float maxtemp) { - min_year_ = minyear; - max_year_ = maxyear; - min_temp_ = mintemp; - max_temp_ = maxtemp; - - temp_scale_ = ((float) plot_height_ / (maxtemp - mintemp)); - year_scale_ = ((float) plot_width_ / (maxyear - minyear)); - } - - private void resetScale() { - setScale(min_year_, max_year_, min_temp_, max_temp_); - } - - /** - * Give us new data points to plot. - * - * @param sites the sites - */ - public void setDataPoints(List sites) { - if (sites != null) { - sites_displayed_ = sites; - } else { - sites_displayed_ = new ArrayList<>(); - } - } - - /** - * Returns the location of the plot point for this value. This is - * just (value - offset) * scale - * - * @param value the value - * @param scale the scale - * @param offset the offset - * @return the pixel position on the plot (not on the whole - * frame). - */ - private int findPointOnScale(float value, float scale, float offset) { - float newvalue = (value - offset) * scale; - return (int) newvalue; - } - - // gets the Y coordinate of the plot - private int findTempPoint(float value) { - return frame_y - + frame_height_ - - (border_width_ + findPointOnScale(value, - temp_scale_, - min_temp_)); - } - - // gets the Y coordinate of the plot - private int findYearPoint(float value) { - return frame_x + border_width_ - + findPointOnScale(value, year_scale_, min_year_); - } - - /** - * This is used primarily for drawing the axes of the plot. - * - * @param x1 x coordinate - * @param y1 y coordinate - * @param x2 x coordinate - * @param y2 y coordinate - * @param color color - * @return an OMLine object, suitable for displaying on the map. - */ - - private OMLine createPlotLine(int x1, int y1, int x2, int y2, Paint color) { - OMLine line = new OMLine(x1, y1, x2, y2); - line.setLinePaint(color); - line.setSelectPaint(Color.white); - return line; - } - - private OMLine createGraphLine(float year1, float temp1, float year2, - float temp2) { - int x1 = findYearPoint(year1); - int y1 = findTempPoint(temp1); - - int x2 = findYearPoint(year2); - int y2 = findTempPoint(temp2); - - OMLine line = createPlotLine(x1, y1, x2, y2, plot_color_); - line.setLinePaint(plot_color_); - line.setSelectPaint(select_color_); - return line; - } - - private OMText createLabel(String text, int x, int y, Paint color, - int justification) { - Font default_font = new Font("TimesRoman", Font.PLAIN, 10); - OMText label = new OMText(x, y, text, default_font, justification); - - label.setLinePaint(color); - label.setSelectPaint(Color.white); - return label; - } - - private OMText createLabel(String text, int x, int y) { - return createLabel(text, x, y, plot_color_, OMText.JUSTIFY_LEFT); - } - - private Date GetDateFromFloat(float fdate) { - long mseconds = (long) ((fdate - 1970) * 365.25 // days per - // year - * 24 // hours per day - * 60 // minutes per hour - * 60 // seconds per minute - * 1000); // milliseconds per second - - Date date = new Date(mseconds); - return date; - } - - private String GetStringDateFromFloat(float fdate) { - Date date = GetDateFromFloat(fdate); - SimpleDateFormat sdf = new SimpleDateFormat("HH:mm MM/dd/yyyy"); - String datestring = sdf.format(date); - return datestring; - } - - /** - * Draw the axes of the Graph, and label them where appropriate - */ - private void drawGraphAxes() { - - // System.out.println("Plotting Axes"); - - int top = frame_y + border_width_; - int bottom = frame_y + frame_height_ - border_width_; - int left = frame_x + border_width_; - int right = frame_x + frame_width_ - border_width_; - - String min_year_string = GetStringDateFromFloat(min_year_); - String max_year_string = GetStringDateFromFloat(max_year_); - - OMLine year_axis = createPlotLine(left, - bottom, - right, - bottom, - plot_color_); - - OMLine temp_axis = createPlotLine(left, top, left, bottom, plot_color_); - - OMText year_min_label = createLabel(min_year_string + " ", - left, - bottom + 10); - - OMText year_max_label = createLabel(max_year_string + " ", - right - 30, - bottom + 10); - - OMText temp_min_label = createLabel(min_temp_ + " ", - left, - bottom, - plot_color_, - OMText.JUSTIFY_RIGHT); - - OMText temp_max_label = createLabel(max_temp_ + " ", - left, - top, - plot_color_, - OMText.JUSTIFY_RIGHT); - - OMText temp_axis_label = createLabel("Temp", left, frame_y - + (frame_height_ / 2), plot_color_, OMText.JUSTIFY_RIGHT); - OMText year_axis_label = createLabel("Year", frame_x - + (frame_width_ / 2), bottom + 15); - - // The background that the plot is drawn on. - OMRect background = new OMRect(frame_x, frame_y, frame_x + frame_width_, frame_y - + frame_height_); - - background.setFillPaint(graph_bg_color); - background.setLinePaint(graph_bg_color); - - year_axis.putAttribute(OMGraphic.APP_OBJECT, this); - temp_axis.putAttribute(OMGraphic.APP_OBJECT, this); - - plot_background_.add(background); - - plot_background_.add(year_axis); - plot_background_.add(temp_axis); - plot_background_.add(temp_axis_label); - plot_background_.add(year_axis_label); - - plot_background_.add(year_min_label); - plot_background_.add(year_max_label); - plot_background_.add(temp_min_label); - plot_background_.add(temp_max_label); - - // add the result to the plot - plot_graphics_.add(plot_background_); - - axes_displayed_ = true; - } - - public OMGraphicList getPlotGraphics() { - return plot_graphics_; - } - - private OMGraphic plotPoint(float year, float temp) { - int x = findYearPoint(year); - int y = findTempPoint(temp); - - String yearstring = GetStringDateFromFloat(year); - - String name = "Time: " + yearstring + ", Temperature: " + temp + "C (" - + (int) ((9.0 / 5.0) * temp + 32) + "F)"; - - OMGraphic graphic = new OMCircle(x, y, 2, 2); - graphic.setLinePaint(plot_color_); - graphic.setFillPaint(plot_color_); - graphic.setSelectPaint(select_color_); - graphic.putAttribute(OMGraphic.APP_OBJECT, name); - - return graphic; - } - - private List sortYears(Map yearData) { - List years = new ArrayList<>(yearData.keySet()); - Collections.sort(years); - return years; - } - - /** - * Create OMGraphics for all the data points on the plot - */ - public void plotData() { - Debug.message("basic", "ScatterGraph.plotData()"); - - plot_points_.clear(); - - // Do the Axes: - if (!axes_displayed_) { - drawGraphAxes(); - } - - for (GLOBESite site : sites_displayed_) { - - List sortedYears = sortYears(site.getAllYears()); - - float last_year = Float.NaN; - float last_temp = Float.NaN; - - for (Float year : sortedYears) { - float temp = site.getValueForYear(year); - OMGraphic point = plotPoint(year, temp); - - plot_points_.add(point); - - if (!Float.isNaN(last_year)) { - // Connect all the rest with a line. - OMGraphic line = createGraphLine(last_year, - last_temp, - year, - temp); - plot_points_.add(line); - } - - // remember the last point we looked at. - last_year = year; - last_temp = temp; - } - } - - plot_graphics_.add(plot_points_); - - } - - public OMGraphic selectPoint(int x, int y, float range) { - OMGraphic selection; - selection = plot_points_.selectClosest(x, y, range); - return selection; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/package.html b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/package.html deleted file mode 100644 index efa6611c2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide a demo layer for displaying non-geographic data over a map. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/thin.pl b/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/thin.pl deleted file mode 100755 index d7cfc42e1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/plotLayer/thin.pl +++ /dev/null @@ -1,79 +0,0 @@ -# ********************************************************************** -# -# -# -# BBN Technologies, a Verizon Company -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-8000 -# -# Copyright (C) BBNT Solutions LLC. All rights reserved. -# -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/thin.pl,v $ -# $RCSfile: thin.pl,v $ -# $Revision: 1.1.1.1 $ -# $Date: 2003/02/14 21:35:48 $ -# $Author: dietrick $ -# -# ********************************************************************** -#!/usr/local/bin/perl -w -## -###################################################################### -## -## FILE: thin.pl -## AUTH: George Keith -## -## DESC: Thin out a large data file -## -## USAGE: -## -## Created on: Wed Oct 14 11:03:15 1998 -## $Id: thin.pl,v 1.1.1.1 2003/02/14 21:35:48 dietrick Exp $ -## -## $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/thin.pl,v $ -## $RCSfile: thin.pl,v $ -## $Author: dietrick $ -## $Date: 2003/02/14 21:35:48 $ -## -## Modification history: -## $Log: thin.pl,v $ -## Revision 1.1.1.1 2003/02/14 21:35:48 dietrick -## Moving source code to new src directory, with directories to separate code that relies on non-J2SE packages -## -## Revision 1.2 2002/04/02 22:25:12 bmackiew -## Updated with revised copyright information. -## -## Revision 1.1 1998/10/15 19:36:37 gkeith -## initial checkin of the plotlayer -## -## -###################################################################### - - -open (INFILE, "AT.gst_thin.txt") or die "can't open inputfile\n"; - -my $linecount = 0; - -while (){ - @dataline = split / +/; -# print (join (":",@dataline)); -# print "$dataline[6], $dataline[7]\n"; - if (($dataline[6] > -30) - && ($dataline[7] < 0)){ - $linecount++; - print OUTFILE; - } - if ($linecount > 0 && - ($linecount / 1000) == 0){ - print "$linecount lines\n"; - } -} - -print "Yielded $linecount lines\n"; -close(INFILE); -close(OUTFILE); - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/AbstractProjectionChangePolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/AbstractProjectionChangePolicy.java deleted file mode 100644 index ccd2e723b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/AbstractProjectionChangePolicy.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.bbn.openmap.layer.policy; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import java.util.logging.Logger; - -/** - * Implements the common functionality of all projection change policies. - * - * @author dietrick - */ -public abstract class AbstractProjectionChangePolicy - implements ProjectionChangePolicy { - - protected OMGraphicHandlerLayer layer; - - protected AbstractProjectionChangePolicy() { - } - - public AbstractProjectionChangePolicy(OMGraphicHandlerLayer omghl) { - layer = omghl; - } - - public void setLayer(OMGraphicHandlerLayer omghl) { - this.layer = omghl; - } - - public OMGraphicHandlerLayer getLayer() { - return this.layer; - } - - /** - * This is a subtle call, that dictates what should happen when the LayerWorker has completed working in it's - * thread. The LayerWorker.get() method returns whatever was returned in the OMGraphicHandler.prepare() method, an - * OMGraphicList. In most cases, this object should be set as the Layer's list at this time. Some Layers, working - * asynchronously with their data sources, might want nothing to happen and should use a policy that overrides this - * method so that nothing does. - *

- * - * Modified as of 5.1.2/5.1 to control when layer.repaint() is called. If the previous OMGraphicList is null, and - * the current OMGraphicList is also null, then repaint is not called. This is to cut back on a flashing effect when - * layers that aren't doing anything call for repaints before those that are call for painting. - * - * @param aList the current OMGraphicList returned from the prepare() method via the SwingWorker thread. - */ - public void workerComplete(OMGraphicList aList) { - if (layer != null) { - boolean repaintIt = layer.getList() != null; - layer.setList(aList); - - // Don't call repaint if the layer list was null, and still is. - if (repaintIt || aList != null) { - layer.repaint(); - } else { - getLogger().fine("Not painting cause of nothin'"); - } - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of the logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(AbstractProjectionChangePolicy.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/BufferedImageRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/BufferedImageRenderPolicy.java deleted file mode 100644 index f6f0aa21b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/BufferedImageRenderPolicy.java +++ /dev/null @@ -1,379 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/BufferedImageRenderPolicy.java,v $ -// $RCSfile: BufferedImageRenderPolicy.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.AlphaComposite; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.logging.Level; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Projection; - -/** - * The BufferedImageRenderPolicy is a RenderPolicy that creates and uses an - * image buffer based on the painting times for the layer. If the time to paint - * exceeds the bufferTiggerDelay, an image buffer for the layer is used for - * paints as long as the projection doesn't change. A new buffer is used for a - * projection change because we need the image buffer to be transparent for - * parts of the map that are not used by the layer. - */ -public class BufferedImageRenderPolicy extends RenderingHintsRenderPolicy { - - protected ImageBuffer imageBuffer = new ImageBuffer(); - - /** - * Set the layer at some point before use. - */ - public BufferedImageRenderPolicy() { - super(); - } - - /** - * Don't pass in a null layer. - */ - public BufferedImageRenderPolicy(OMGraphicHandlerLayer layer) { - super(layer); - } - - /** - * Set the ImageBuffer, for subclasses to modify it's particular behavior - */ - protected void setImageBuffer(ImageBuffer iBuffer) { - imageBuffer = iBuffer; - } - - /** - * @return the imageBuffer - */ - protected ImageBuffer getImageBuffer() { - return imageBuffer; - } - - /** - * Called from the OMGraphicHandlerLayer's projectionChanged() method. This - * method updates the current image buffer so it can be re-projected for the - * current projection before the layer worker goes off to do more work. In - * case of rapid projection changes, the layer should be able to display the - * current buffer in the right place, at least. Ghah! Don't do a lot of work - * in this thread. - * - * @param newProj the newest projection known. - */ - public void prePrepare(Projection newProj) { - getImageBuffer().generate(newProj); - } - - public OMGraphicList prepare() { - if (layer != null) { - /* - * Grab a copy of the projection that the list is being made for, so - * the buffer gets placed for the right location. It's really - * important in case the projection height and width don't quite - * match up with the coordinate coverage area. Doesn't sound right, - * but that happens occasionally and the images appear stretched out - * if you don't match up the image to the projection. - */ - Projection proj = layer.getProjection(); - OMGraphicList list = layer.prepare(); - try { - getImageBuffer().update(list, proj); - } catch (NullPointerException npe) { - logger.fine("Caught NPE creating the image buffer for layer: " + layer.getName()); - if (logger.isLoggable(Level.FINE)) { - npe.printStackTrace(); - } - getImageBuffer().clear(); - } - return list; - } else { - logger.warning("NULL layer, can't do anything."); - } - return null; - } - - public void paint(Graphics g) { - if (layer == null) { - logger.warning("NULL layer, skipping..."); - return; - } - - Projection proj = layer.getProjection(); - - if (layer.isProjectionOK(proj)) { - - Graphics2D g2 = (Graphics2D) g.create(); - ImageBuffer imageBuffer = getImageBuffer(); - setCompositeOnGraphics(g2); - - if (!imageBuffer.paint(g2, proj)) { - OMGraphicList list = layer.getList(); - if (list != null) { - layer.getList().render(g2); - } - } - - g2.dispose(); - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() + " BufferedImageRenderPolicy.paint(): skipping due to projection."); - } - - } - - protected class ImageBuffer { - - BufferedImage imageBuffer; - OMScalingRaster imageRaster; - Projection currentProjection; - - protected ImageBuffer() { - } - - protected void generate(Projection proj) { - OMScalingRaster lImageRaster = getImageRaster(); - if (lImageRaster != null) { - if (proj instanceof Cylindrical) { - lImageRaster.setNeedToReposition(true); - lImageRaster.setNeedToRegenerate(true); - lImageRaster.generate(proj); - } else { - setImageRaster(null); - } - } - } - - /** - * Return true if something was rendered. - * - * @param g - * @param proj - * @return true if paint was successful for the OMScaling Raster - */ - public boolean paint(Graphics2D g, Projection proj) { - Projection currentProj = currentProjection; - OMScalingRaster omr = getImageRaster(); - - if (!proj.equals(currentProj)) { - currentProjection = proj; - if (omr != null) { - omr.generate(proj); - omr.render(g); - return true; - } - } - - /* - * We used to have a could of calls here that painted the current - * ImageBuffer if it wasn't null. Turns out, that's not a good idea. - * It causes the layer to paint itself in its old location for a - * flash before updating. So we're just going to let the - * OMScalingRaster handling painting. - */ - - return false; - } - - /** - * Get the updated BufferedImage, with current OMGraphics rendered into - * it. Called with the results of layer.prepare(). - * - * @param list OMGraphicList from layer's prepare method. - * @param proj current projection that has buffer size information. - */ - protected void update(OMGraphicList list, Projection proj) { - BufferedImage currentImageBuffer = null; - - if (proj != null && layer != null) { - - int w = proj.getWidth(); - int h = proj.getHeight(); - - currentImageBuffer = getImageBuffer(); - BufferedImage bufferedImage = scrubOrGetNewBufferedImage(currentImageBuffer, w, h); - - // Updated image for projection - if (bufferedImage != null) { - if (currentImageBuffer != null) { - currentImageBuffer.flush(); - } - - currentImageBuffer = bufferedImage; - } - - Graphics2D g2d = (Graphics2D) currentImageBuffer.getGraphics(); - setRenderingHints(g2d); - - if (list != null) { - list.render(g2d); - } - - g2d.dispose(); - - setImageRaster(updateRaster(currentImageBuffer, proj)); - } - - setImageBuffer(currentImageBuffer); - currentProjection = proj; - } - - protected OMScalingRaster updateRaster(BufferedImage imageBuffer, Projection proj) { - - if (proj instanceof Cylindrical) { - - int w = proj.getWidth(); - int h = proj.getHeight(); - - // If a buffer wasn't created, bail - if (imageBuffer == null) { - return null; - } - - Point2D llp1 = proj.getUpperLeft(); - /* - * The lower right point is w-1, h-1, the actual pixel index, - * starting at 0. The size of the image is one pixel more. Using - * getLowerRight() leaves one pixel on the bottom and right - * blank in the resulting image. - */ - Point2D llp2 = proj.inverse(w, h); - /* - * We're running into a problem here for the OMScalingRaster - * where the projection is providing a bad coordinate situation - * for OMScalingRasters when zoomed way out. The left pixel - * coordinate of the map, at some point in the OMScalingRaster - * calculations, is being placed to the right of the right pixel - * coordinate of the map. It's a 360 degree precision thing, and - * ever so slight. We're going to test for that here, and if - * that x test fails, we're just going to use a standard - * OMRaster for the Buffer. - */ - - /* - * The OMScalingRaster is cool because it can respond to the - * projection change immediately, and display what was there - * before while the layers are working. - */ - Point2D pnt1 = proj.forward(llp1); - Point2D pnt2 = proj.forward(llp2); - - if (pnt1.getX() < pnt2.getX() && h > 0 && w > 0) { - OMScalingRaster raster = getImageRaster(); - - if (raster == null) { - raster = new OMScalingRaster(llp1.getY(), llp1.getX(), llp2.getY(), llp2.getX(), imageBuffer); - } else { - raster.setImage(imageBuffer); - raster.setLat(llp1.getY()); - raster.setLon(llp1.getX()); - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } - - raster.generate(proj); - return raster; - } - } - - return null; - } - - /** - * Given the current image buffer, and the desired width and height of - * the new projection, return a fresh/refreshed image buffer ready for - * layer painting. Should be clear. - * - * @param currentImage the current BufferedImage - * @param width current projection width, pixels. - * @param height current projection height, pixels. - * @return new BufferedImage if one was needed, i.e. if size changed. - */ - protected BufferedImage scrubOrGetNewBufferedImage(BufferedImage currentImage, int width, - int height) { - int cWidth = -1; - int cHeight = -1; - - if (currentImage != null) { - cWidth = currentImage.getWidth(); - cHeight = currentImage.getHeight(); - } - - if (currentImage != null && cWidth == width && cHeight == height) { - - // scrub it, refresh the pixels. - Graphics2D graphics = (Graphics2D) currentImage.getGraphics(); - graphics.setComposite(AlphaComposite.Clear); - graphics.fillRect(0, 0, width, height); - graphics.setComposite(AlphaComposite.SrcOver); - return null; - - } - - return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - } - - protected void clear() { - BufferedImage bImage = getImageBuffer(); - if (bImage != null) { - Graphics2D graphics = (Graphics2D) bImage.getGraphics(); - graphics.setComposite(AlphaComposite.Clear); - graphics.fillRect(0, 0, bImage.getWidth(), bImage.getHeight()); - graphics.setComposite(AlphaComposite.SrcOver); - } - - setImageRaster(null); - } - - protected BufferedImage getImageBuffer() { - return imageBuffer; - } - - protected void setImageBuffer(BufferedImage bImage) { - if (imageBuffer != null && imageBuffer != bImage) { - imageBuffer.flush(); - } - - imageBuffer = bImage; - } - - /** - * @return the imageRaster - */ - protected OMScalingRaster getImageRaster() { - return imageRaster; - } - - /** - * @param imageRaster the imageRaster to set - */ - protected void setImageRaster(OMScalingRaster imageRaster) { - this.imageRaster = imageRaster; - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/FullProjectionRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/FullProjectionRenderPolicy.java deleted file mode 100644 index c0f4e762c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/FullProjectionRenderPolicy.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/FullProjectionRenderPolicy.java,v $ -// $RCSfile: FullProjectionRenderPolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.Graphics; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.proj.Projection; - -/** - * The FullProjectionRenderPolicy is a StandardRenderPolicy that sets - * the clip of the java.awt.Graphics passed into the paint method with - * the clipping area of the projection. You'll need to use this render - * policy if you want to paint into a buffer that is bigger than the - * layer size (and MapBean size), because Java sets the max clipping - * size to the size of the component. - *

- * This class seems useless, because it looks like the - * StandardRenderPolicy does the same thing automatically. - */ -public class FullProjectionRenderPolicy extends StandardRenderPolicy { - - public FullProjectionRenderPolicy() {} - - /** - * Don't pass in a null layer. - */ - public FullProjectionRenderPolicy(OMGraphicHandlerLayer layer) { - super(layer); - } - - public void paint(Graphics g) { - if (layer != null && layer.isProjectionOK(layer.getProjection())) { - Projection proj = layer.getProjection(); - // The proj shouldn't be null, because isProjectionOK - // checks for that, but that method may be overridden - if (proj != null) { - g.setClip(0, 0, proj.getWidth(), proj.getHeight()); - } - } - super.paint(g); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/ListResetPCPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/ListResetPCPolicy.java deleted file mode 100644 index 91e22076e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/ListResetPCPolicy.java +++ /dev/null @@ -1,145 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/ListResetPCPolicy.java,v $ -// $RCSfile: ListResetPCPolicy.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/09/13 14:33:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * ProjectionChangePolicy that uses a Layer SwingWorker to kick off a thread to - * call layer.prepare() and deletes the current OMGraphicList between projection - * changes. The standard behavior for layers that gather new OMGraphics for new - * projections. - */ -public class ListResetPCPolicy extends AbstractProjectionChangePolicy { - - /** - * You MUST set a layer at some point. - */ - public ListResetPCPolicy() { - } - - /** - * Don't pass in a null layer. - * - * @param layer OMGraphicHandlerLayer - */ - public ListResetPCPolicy(OMGraphicHandlerLayer layer) { - setLayer(layer); - } - - /** - * The method that is called when the projection changes. For the - * ListResetPCPolicy, the current OMGraphicList for the layer is cleared. - * - * @param pe the ProjectionEvent received from the MapBean when the - * projection changes. - */ - public void projectionChanged(ProjectionEvent pe) { - - Logger logger = getLogger(); - if (layer != null) { - Projection proj = layer.setProjection(pe); - // proj will be null if the projection hasn't changed, a - // signal that work does not need to be done. - if (proj != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getLayer().getName() - + ": projectionChanged with NEW projection, resetting list."); - } - - /* - * Check and see of the layer list is not null. If it isn't, - * just replace it with an empty list. We want a null list to - * mean the layer isn't contributing to the map. Later, in - * workerComplete, if a null list is to be replaced by an empty - * list, repaint will not be called. - */ - if (layer.getList() != null) { - layer.setList(new OMGraphicList()); - } - - // Check to see if the projection is worth reacting to. - if (layer.isProjectionOK(proj)) { - layer.doPrepare(); - } - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getLayer().getName() - + ": projectionChanged with OLD projection, repainting."); - } - if (!layer.isWorking()) { - // This repaint may look redundant, but it handles - // the situation where a layer is removed from a - // map and readded when the projection doesn't - // change. Since it already had the projection, - // and remove() hasn't been called yet, the proj - // == null. When the new layer is added, it - // receives a projectionChanged call, and even - // though it's all set, it still needs to call - // repaint to have itself show up on the map. - layer.repaint(); - layer.fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - } - } else { - logger.warning("NULL layer, can't do anything."); - } - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(ListResetPCPolicy.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/NullProjectionChangePolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/NullProjectionChangePolicy.java deleted file mode 100644 index 9aaa79687..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/NullProjectionChangePolicy.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.layer.policy; - -import com.bbn.openmap.event.ProjectionEvent; - -/** - * Dummy ProjectionChangePolicy, for those layers who prefer to ignore - * projection changes completely. - */ -public class NullProjectionChangePolicy extends AbstractProjectionChangePolicy { - - public void projectionChanged(ProjectionEvent pe) { - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/PanningImageRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/PanningImageRenderPolicy.java deleted file mode 100644 index 882b8b0aa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/PanningImageRenderPolicy.java +++ /dev/null @@ -1,192 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/BufferedImageRenderPolicy.java,v $ -// $RCSfile: BufferedImageRenderPolicy.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.logging.Level; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; - -/** - * The PanningImageRenderPolicy renders all OMGraphics into a buffering image, - * and responds to projection changes by immediately rendering a translated - * version of the image at a new projection location before calling prepare() on - * the layer to get the OMGraphics for the new projection and untranslated - * image. When the new image is ready, it will be painted. Using this policy on - * background layers eliminates the flashing effect seen when panning or zooming - * a map when a faster-responding layer is on top. - *

- * NOTE: The need for this RenderPolicy is superseded by using the - * PanningMouseMode on the MapBean instead. - * - *

- * You can set this object on an OMGraphicHandlerLayer through the API, or set - * it in the properties: - * - *

- * layer.renderPolicy=rp
- * layer.rp.class=com.bbn.openmap.layer.policy.PanningImageRenderPolicy
- * 
- */ -public class PanningImageRenderPolicy extends RenderingHintsRenderPolicy { - - protected BufferedImage buffer = null; - - protected Point2D offset = new Point2D.Double(); - protected Point2D oldUL; - protected float oldScale; - protected Class oldProjType = null; - - /** - * Set the layer at some point before use. - */ - public PanningImageRenderPolicy() { - super(); - } - - /** - * Don't pass in a null layer. - */ - public PanningImageRenderPolicy(OMGraphicHandlerLayer layer) { - super(layer); - } - - public OMGraphicList prepare() { - if (layer != null) { - // setBuffer(null); - Projection proj = layer.getProjection(); - if (layer.isProjectionOK(proj)) { - // set the offsets depending on how much the image moves - Point2D ul = proj.getUpperLeft(); - if (oldUL != null && !oldUL.equals(ul) && oldScale == proj.getScale() - && proj.getClass().equals(oldProjType)) { - Point2D currentPoint = proj.forward(ul); - Point2D oldPoint = proj.forward(oldUL); - - offset.setLocation(oldPoint.getX() - currentPoint.getX(), oldPoint.getY() - - currentPoint.getY()); - - layer.repaint(); - } - - oldUL = ul; - oldProjType = ((Proj) proj).getClass(); - oldScale = proj.getScale(); - - OMGraphicList list = layer.prepare(); - setBuffer(createAndPaintImageBuffer(list)); - - return list; - } else { - logger.warning("NULL projection, can't do anything."); - } - } else { - logger.warning("NULL layer, can't do anything."); - } - return null; - } - - public void paint(Graphics g) { - if (layer == null) { - logger.warning("NULL layer, skipping..."); - return; - } - - OMGraphicList list = layer.getList(); - Projection proj = layer.getProjection(); - Graphics2D g2 = (Graphics2D) g; - - if (layer.isProjectionOK(proj)) { - - if (getBuffer() == null) { - // Not sure how we get here, but it's here just in case so that - // the list might get painted if it exists and the buffered - // image wasn't created. - logger.fine("creating image buffer in paint"); - if (list != null) { - setBuffer(createAndPaintImageBuffer(list)); - } - } - - BufferedImage bufferedImage = getBuffer(); - - setCompositeOnGraphics(g2); - - if (bufferedImage != null) { - - AffineTransform af = new AffineTransform(); - af.translate(offset.getX(), offset.getY()); - g2.drawRenderedImage((BufferedImage) bufferedImage, af); - if (logger.isLoggable(Level.FINE)) { - logger.fine("RenderingPolicy:" + layer.getName() + ": rendering buffer"); - } - - } else if (list != null) { - super.setRenderingHints(g); - list.render(g); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() + ": rendering list directly"); - } - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() + ".paint(): " - + (list == null ? "NULL list, skipping..." : " skipping due to projection.")); - } - - } - - /** Get the BufferedImage for the layer. */ - protected BufferedImage getBuffer() { - return buffer; - } - - /** Set the BufferedImage for the layer. */ - protected void setBuffer(BufferedImage bi) { - offset.setLocation(0, 0); - buffer = bi; - } - - protected BufferedImage createAndPaintImageBuffer(OMGraphicList list) { - BufferedImage bufferedImage = null; - if (list != null && layer != null) { - int w = layer.getProjection().getWidth(); - int h = layer.getProjection().getHeight(); - bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics(); - super.setRenderingHints(g2d); - list.render(g2d); - if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() + ": rendering list into buffer"); - } - } - return bufferedImage; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/ProjectionChangePolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/ProjectionChangePolicy.java deleted file mode 100644 index dca5a3fe6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/ProjectionChangePolicy.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/ProjectionChangePolicy.java,v $ -// $RCSfile: ProjectionChangePolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * A ProjectionChangePolicy is a policy object that determines how an - * OMGraphicHandler layer reacts to a projectionChanged() method call. The - * OMGraphicHandlerLayer has been written to consult this object to control that - * activity. The reaction could include clearing out the current OMGraphicList - * or keeping it, or launching a SwingWorker with a doPrepare() call on the - * layer to have the layer's prepare() method called. - */ -public interface ProjectionChangePolicy { - - /** - * @param layer the OMGraphicHandlerLayer the policy is working for. - */ - public void setLayer(OMGraphicHandlerLayer layer); - - /** - * @return the OMGraphicHandlerLayer the policy is working for. - */ - public OMGraphicHandlerLayer getLayer(); - - /** - * The method that is called when the projection changes. The - * ProjectionChangePolicy should modify the OMGraphicList and do other - * functions as dictated by the policy, like starting threads to gather data - * and generating new OMGraphics for the layer. - * - * @param pe the ProjectionEvent received by the layer. - */ - public void projectionChanged(ProjectionEvent pe); - - /** - * The method that gets called when the SwingWorker thread finishes. The - * OMGraphicList is what is getting returned from the prepare() method on - * the layer, so it's most likely that this list should be set on the layer - * and repaint should be called on the layer. - * - * @param aList the OMGraphicList returned from the OMGraphicHandlerLayer - * prepare method via the SwingWorker. - */ - public void workerComplete(OMGraphicList aList); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderPolicy.java deleted file mode 100644 index fd7aaf984..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderPolicy.java +++ /dev/null @@ -1,85 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/RenderPolicy.java,v $ -// $RCSfile: RenderPolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.Composite; -import java.awt.Graphics; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * A policy object that can be used by an OMGraphicHandlerLayer to figure out - * the best way to paint on the map. - */ -public interface RenderPolicy { - - /** - * A method to set the parent layer on the RenderPolicy. - */ - public void setLayer(OMGraphicHandlerLayer layer); - - /** - * A method to get the parent layer on the RenderPolicy. - */ - public OMGraphicHandlerLayer getLayer(); - - /** - * Set a Composite object on a Graphics2D object before rendering. Set to - * null (default) to not do anything. - */ - public void setComposite(Composite composite); - - public Composite getComposite(); - - /** - * Be very careful with doing things in this method. It is called from the - * doPrepare() method in the calling thread, in order to allow any buffering - * to update itself outside of the LayerWorker thread. It allows the render - * policy to keep up with rapid projection changes even if the LayerWorker - * threads are getting backed up. Do not do a lot of work in this thread, it - * will slow down projection change notifications being received from other - * layers if you do. - * - * @param newProjection the new projection received in a projectionChanged - * method for the layer. - */ - void prePrepare(Projection newProjection); - - /** - * Called when an OMGraphicHandlerLayer should begin preparing OMGraphics - * for the map. This is a hook into the list to help RenderPolicy make - * decisions or set up the list for faster rendering. - */ - public OMGraphicList prepare(); - - /** - * Called from OMGraphicHandlerLayer.paint(Graphics), so the policy can - * handle the painting for the layer. If you are going to change the - * Graphics object in this method, you should make a copy of it first using - * the Graphics.create() method so the changes won't affect other layers. - */ - public void paint(Graphics g); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderingHintsRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderingHintsRenderPolicy.java deleted file mode 100644 index 9332ceef4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/RenderingHintsRenderPolicy.java +++ /dev/null @@ -1,223 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/RenderingHintsRenderPolicy.java,v $ -// $RCSfile: RenderingHintsRenderPolicy.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.RenderingHints.Key; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Level; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.util.PropUtils; - -/** - * The RenderingHintsRenderPolicy is a StandardRenderPolicy that lets you set - * RenderingHints on the java.awt.Graphics object before the layer is painted, - * and then simply paints the current graphic list. No conditions or deviations - * are considered. This class can be set with properties. - *

- * The properties have to look like: - * - *

- * 
- * 
- *  prefix.renderingHints=RENDERINGHINTS_KEY1 RENDERINGHINTS_KEY2
- *  prefix.RENDERINGHINTS_KEY1=RENDERINGHINTS_VALUE1
- *  prefix.RENDERINGHINTS_KEY2=RENDERINGHINTS_VALUE2
- * 
- * 
- * 
- * - * For example, for a GraticuleLayer in the properties file with a 'graticule' - * prefix: - * - *
- * 
- * 
- *  graticule.renderPolicy=textAliasing
- *  graticule.textAliasing.class=com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy
- *  graticule.textAliasing.renderingHints=KEY_TEXT_ANTIALIASING
- *  graticule.textAliasing.KEY_TEXT_ANTIALIASING=VALUE_TEXT_ANTIALIAS_ON
- * 
- * 
- * 
- * - * The HintsMapBeanRepaintPolicy uses a RenderingHintsRenderPolicy with - * properties that look like these, where 'repaintPolicy' is the prefix for the - * RenderingHintsRenderPolicy: - * - *
- * 
- * 
- *  repaintPolicy.class=com.bbn.openmap.HintsMapBeanRepaintPolicy
- *  repaintPolicy.renderingHints=KEY_ANTIALIASING
- *  repaintPolicy.KEY_ANTIALIASING=VALUE_ANTIALIAS_ON
- *  repaintPolicy.KEY_RENDERING=VALUE_RENDER_SPEED
- * 
- * 
- * 
- * - * See the java.awt.RenderingHints javadocs for the key-value pairs that can be - * used. - * - */ -public class RenderingHintsRenderPolicy extends StandardRenderPolicy { - - public final static String RenderingHintsProperty = "renderingHints"; - - protected RenderingHints renderingHints = null; - - /** - * The layer needs to be set at some point before use. - */ - public RenderingHintsRenderPolicy() { - super(); - setRenderingHints(new RenderingHints(null)); - } - - public RenderingHintsRenderPolicy(OMGraphicHandlerLayer layer) { - super(layer); - setRenderingHints(new RenderingHints(null)); - } - - /** - * Set the RenderingHints Map that should be used on the MapBean. If null, - * no modifications will be set on the MapBean's Graphics object. - */ - public void setRenderingHints(RenderingHints rh) { - renderingHints = rh; - } - - /** - * Get the RenderingHints Map that should be used on the MapBean. May be - * null (default). - */ - public RenderingHints getRenderingHints() { - if (renderingHints == null) { - renderingHints = new RenderingHints(null); - } - return renderingHints; - } - - /** - * Set a RenderingHint on this object. - * @param key RenderingHint KEY - * @param value RenderingHint VALUE - */ - public void put(Object key, Object value) { - getRenderingHints().put(key, value); - } - - /** - * If you are going to change the Graphics object in this method, you should - * make a copy of it first using the Graphics.create() method so the changes - * won't affect other layers. - */ - public void paint(Graphics g) { - g = g.create(); // Make a copy to use just for this layer. - setRenderingHints(g); - setCompositeOnGraphics((Graphics2D) g); - super.paint(g); - } - - public void setRenderingHints(Graphics g) { - if (renderingHints != null && g instanceof Graphics2D) { - Graphics2D g2 = (Graphics2D) g; - for (Map.Entry entry : renderingHints.entrySet()) { - Key key = (Key) entry.getKey(); - g2.setRenderingHint(key, entry.getValue()); - } - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String renderingHintsString = props.getProperty(prefix - + RenderingHintsProperty); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("RHRP: decoding rendering hints: " - + renderingHintsString); - } - - List renderingHintsVector = PropUtils.parseSpacedMarkers(renderingHintsString); - - if (renderingHintsVector != null) { - for (String renderingHintKeyString : renderingHintsVector) { - if (renderingHintKeyString != null) { - String renderingHintValueString = props.getProperty(prefix - + renderingHintKeyString); - - if (renderingHintValueString != null) { - Object key = null; - Object value = null; - - try { - key = RenderingHints.class.getField(renderingHintKeyString) - .get(null); - value = RenderingHints.class.getField(renderingHintValueString) - .get(null); - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - - if (key != null && value != null) { - put(key, value); if (logger.isLoggable(Level.FINE)) { - logger.fine("RHRP+++ adding " - + renderingHintKeyString + " | " - + renderingHintValueString); - } - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("RHRP--- NOT adding " - + renderingHintKeyString + " (" + key - + ") | " + renderingHintValueString - + " (" + value + ")"); - } - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("RHRP--- NOT adding " - + renderingHintKeyString); - } - } - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - return props; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/ShadowRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/ShadowRenderPolicy.java deleted file mode 100644 index 2aeda9285..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/ShadowRenderPolicy.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.bbn.openmap.layer.policy; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.awt.image.ConvolveOp; -import java.awt.image.Kernel; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The ShadowRenderPolicy uses a ConvolveOp to create a shadow of the - * OMGraphicList set on a layer. This is expensive, I think - the OMGraphicList - * is painted several times, depending on the dimensions of the Kernel used on - * the ConvolveOp. The idea is that the list is faintly painted with a wider - * dimension, and then the dimension is shrunk down as the list keeps getting - * repainted. The rendering becomes more bold/opaque as you get closer to the - * actual location of the OMGraphics. You can vary the effect by setting the - * dimension (the number of pixels away that you want the starting traces of - * shadow to take effect) and the value for the kernel data (how - * transparent/opaque you want the rendering to be, with 1f to ba opaque and - * something like .005 being really subtly transparent). - * - * @author dietrick - */ -public class ShadowRenderPolicy extends BufferedImageRenderPolicy { - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger - .getLogger(ShadowRenderPolicy.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - - /** - * This is the pixel dimension of the ConvolveOp, creates the evaluation - * area. - */ - int dimension = 14; - /** - * The kernelData assigns weight to the ConvolveOp area. - */ - float kernelValue = .004f; - /** - * Property from the property file to set kernel dimesion. - */ - public final static String DIM_PROPERTY = "dim"; - /** - * Property name for Kernel value. - */ - public final static String KERNEL_VAL_PROPERTY = "kernel"; - - /** - * The operation, created with dimension and kernelData settings. - */ - ConvolveOp convolveOp; - - public ShadowRenderPolicy() { - updateOp(dimension, kernelValue); - - setImageBuffer(new BufferedImageRenderPolicy.ImageBuffer() { - - /** - * Get the updated BufferedImage, with current OMGraphics rendered into - * it. Called with the results of layer.prepare(). - * - * @param list OMGraphicList from layer's prepare method. - * @param proj current projection that has buffer size information. - */ - protected void update(OMGraphicList list, Projection proj) { - BufferedImage currentImageBuffer = null; - - if (proj != null && layer != null) { - - int w = proj.getWidth(); - int h = proj.getHeight(); - - currentImageBuffer = getImageBuffer(); - BufferedImage bufferedImage = scrubOrGetNewBufferedImage(currentImageBuffer, w, h); - - // Updated image for projection - if (bufferedImage != null) { - if (currentImageBuffer != null) { - currentImageBuffer.flush(); - } - - currentImageBuffer = bufferedImage; - } - - Graphics2D g2d = (Graphics2D) currentImageBuffer.getGraphics(); - setRenderingHints(g2d); - - if (list != null) { - list.render(g2d); - - currentImageBuffer = convolveOp.filter(bufferedImage, null); - } - - g2d.dispose(); - - setImageRaster(updateRaster(currentImageBuffer, proj)); - } - - setImageBuffer(currentImageBuffer); - currentProjection = proj; - } - - }); - } - - /** - * Don't pass in a null layer. - */ - public ShadowRenderPolicy(OMGraphicHandlerLayer layer) { - this(); - setLayer(layer); - } - - /** - * Create the Kernel and ConvolveOp based on the basic settings. The Kernel - * float array will be created, all values matching the given value, the - * size of the dimension given. - * - * @param dim The edge size of the kernel data array. - * @param krnlValue the value to fill the kernel array with. - */ - protected void updateOp(int dim, float krnlValue) { - - float[] kernelData = new float[dim * dim]; - - for (int i = 0; i < kernelData.length; i++) { - kernelData[i] = krnlValue; - } - - setConvolveOp(new ConvolveOp(new Kernel(dim, dim, kernelData))); - } - - /** - * If you're going to do something fancy, set up your own Op. You can mess - * with the Kernel data and the dimension yourself. - * - * @param op - */ - public void setConvolveOp(ConvolveOp op) { - convolveOp = op; - } - - public ConvolveOp getConvolveOp() { - return convolveOp; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - dimension = PropUtils.intFromProperties(props, prefix + DIM_PROPERTY, dimension); - kernelValue = PropUtils.floatFromProperties(props, prefix + KERNEL_VAL_PROPERTY, kernelValue); - - updateOp(dimension, kernelValue); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.setProperty(prefix + DIM_PROPERTY, Float.toString(dimension)); - props.setProperty(prefix + KERNEL_VAL_PROPERTY, Float.toString(kernelValue)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, props, ShadowRenderPolicy.class, DIM_PROPERTY, "Kernel Dimension", "The size of the kernel array edge", null); - PropUtils.setI18NPropertyInfo(i18n, props, ShadowRenderPolicy.class, KERNEL_VAL_PROPERTY, "Kernel Data Value", "The value set in the kernel data", null); - - return props; - } - - - /** - * Assumes that the OMGraphicList to be rendered is set on the - * OMGraphicHandlerLayer, available via setList(). - */ - public void paint(Graphics g) { - Logger logger = getLogger(); - - if (layer == null) { - logger.warning("NULL layer, skipping..."); - return; - } - - Projection proj = layer.getProjection(); - - if (layer.isProjectionOK(proj)) { - - Graphics2D g2 = (Graphics2D) g.create(); - ImageBuffer imageBuffer = getImageBuffer(); - setCompositeOnGraphics(g2); - - if (!imageBuffer.paint(g2, proj)) { - OMGraphicList list = layer.getList(); - if (list != null) { - layer.getList().render(g2); - - BufferedImage srcImg = new BufferedImage(proj.getWidth(), - proj.getHeight(), BufferedImage.TYPE_INT_ARGB); - - list.render(srcImg.getGraphics()); - - BufferedImage dstImage = convolveOp.filter(srcImg, null); - - g2.drawImage(dstImage, 0, 0, null); - } - } - - g2.dispose(); - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() + " ShadowPolicy.paint(): skipping due to projection."); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardPCPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardPCPolicy.java deleted file mode 100644 index 318612863..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardPCPolicy.java +++ /dev/null @@ -1,216 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/StandardPCPolicy.java,v $ -// $RCSfile: StandardPCPolicy.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/05/19 16:44:57 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * ProjectionChangePolicy that uses a Layer SwingWorker to kick off a thread to - * call layer.prepare() and doesn't delete the OMGraphicList between projection - * changes. The standard behavior for simple layers that maintain a constant - * list of OMGraphics. - */ -public class StandardPCPolicy extends AbstractProjectionChangePolicy { - - /** - * The number of OMGraphics that have to be on the layer's OMGraphicList - * before a thread is spawned. The default is 50; - */ - protected int graphicCutoff = 50; - - /** - * A flag to tell the policy to always spawn a thread. - */ - protected boolean alwaysSpawnThread = false; - - /** - * You must set a layer at some point before using this class. - */ - public StandardPCPolicy() { - } - - /** - * Don't pass in a null layer. - */ - public StandardPCPolicy(OMGraphicHandlerLayer layer) { - this(layer, true); - } - - /** - * Don't pass in a null layer. - * - * @param layer layer to work for - * @param alwaysSpawnThreadForPrepare should be true if the layer's prepare - * method takes a while. Normally, the policy looks at the number of - * OMGraphics on the list to determine if a thread should be spawned. - * True by default. - */ - public StandardPCPolicy(OMGraphicHandlerLayer layer, boolean alwaysSpawnThreadForPrepare) { - setLayer(layer); - setAlwaysSpawnThread(alwaysSpawnThreadForPrepare); - } - - /** - * Tell the policy whether to spawn a thread when projectionChanged() is - * called with a new projection. - * - * @param val setting for always spawning thread for every projection - * change. - */ - public void setAlwaysSpawnThread(boolean val) { - alwaysSpawnThread = val; - } - - public boolean getAlwaysSpawnThread() { - return alwaysSpawnThread; - } - - /** - * When the projection changes, the StandardPCPolicy sets the current - * projection on the layer, and calls prepare() on the layer. repaint() will - * be automatically called. This method does not generate the OMGraphics in - * the list. The layer is still expected to do that in prepare(), as well as - * return that list from prepare. - *

- * If a Layer is using this PC policy, then it's kind of assumed that the - * layer is setting the list and generating the same list over and over - * again with the new projection. So, when we look at the min and max scales - * set on the layer, we don't want to clear out that list if the projection - * scale is outside of the acceptable range of good projection scales. - * Instead, we want to skip the prepare() method call as to not waste CPU - * cycles generating things we won't see, and let the RenderPolicy check to - * see if the list should be painted. - * - * @param pe The ProjectionEvent received from the MapBean. - */ - public void projectionChanged(ProjectionEvent pe) { - Logger logger = getLogger(); - if (layer != null) { - Projection proj = layer.setProjection(pe); - // proj will be null if the projection hasn't changed, a - // signal that work does not need to be done. - if (proj != null) { - // Some criteria can decide whether - // starting another thread is worth it... - if (shouldSpawnThreadForPrepare()) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getLayer().getName() - + ": StandardPCPolicy projectionChanged with NEW projection, spawning thread to handle it."); - } - - if (layer.isProjectionOK(proj)) { - layer.doPrepare(); - } - return; - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getLayer().getName() - + ": StandardPCPolicy projectionChanged with NEW projection, handling it within current thread."); - } - layer.fireStatusUpdate(LayerStatusEvent.START_WORKING); - if (layer.isProjectionOK(proj)) { - layer.setList(layer.prepare()); - } - - layer.repaint(); - } - } else { - layer.repaint(); - } - layer.fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } else { - Debug.error("StandardPCPolicy.projectionChanged(): NULL layer, can't do anything."); - } - } - - /** - * We're assuming that the list is somewhat constant for the layer. If the - * number of OMGraphics on the layer's list is more than the cutoff number, - * a thread should be launched to generate them with the new projection. You - * can extend this method so that different criteria may be considered. - * - * @return true of thread should always be spawned. - */ - protected boolean shouldSpawnThreadForPrepare() { - if (layer != null && !alwaysSpawnThread) { - OMGraphicList list = layer.getList(); - if (list != null) { - return layer.getList().size() > graphicCutoff; - } - } - // If we have to create a list, might as well assume that - // is should be done in a new thread. - return true; - } - - /** - * @param number Set the number of OMGraphics that have to be on the list - * before a thread gets spawned to call generate() on them. - */ - public void setGraphicCutoff(int number) { - graphicCutoff = number; - } - - public int getGraphicCutoff() { - return graphicCutoff; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(StandardPCPolicy.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardRenderPolicy.java b/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardRenderPolicy.java deleted file mode 100644 index f13b32115..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/StandardRenderPolicy.java +++ /dev/null @@ -1,135 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/policy/StandardRenderPolicy.java,v $ -// $RCSfile: StandardRenderPolicy.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/10/26 15:47:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.policy; - -import java.awt.Composite; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * The StandardRenderPolicy is a RenderPolicy that simply paints the current - * graphic list. No conditions or deviations are considered. - */ -public class StandardRenderPolicy extends OMComponent implements RenderPolicy { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.policy.RenderPolicy"); - - /** - * Don't let this be null, nothing will happen. At all. - */ - protected OMGraphicHandlerLayer layer; - - protected Composite composite; - - public StandardRenderPolicy() { - } - - /** - * Don't pass in a null layer. - */ - public StandardRenderPolicy(OMGraphicHandlerLayer layer) { - this(); - setLayer(layer); - } - - public void setLayer(OMGraphicHandlerLayer l) { - layer = l; - } - - public OMGraphicHandlerLayer getLayer() { - return layer; - } - - public Composite getComposite() { - return composite; - } - - /** - * Can be used to set Composite objects (like AlphaComposite) on Graphics2D - * objects before the layer is painted. - * - * @param composite - */ - public void setComposite(Composite composite) { - this.composite = composite; - } - - /** - * Call made by the policy from the paint(g) method in order to set the - * composite on the Graphics2D object. This method is meant to be overridden - * if needed. - * - * @param g Graphics2D that the Composite will be set on. - */ - protected void setCompositeOnGraphics(Graphics2D g) { - if (composite != null) { - g.setComposite(composite); - } - } - - /** - * The StandardRenderPolicy doesn't need to do anything before prepare() - * returns. - */ - public void prePrepare(Projection newProj) { - // NOOP - } - - public OMGraphicList prepare() { - if (layer != null) { - return layer.prepare(); - } else { - return null; - } - } - - /** - * Assumes that the OMGraphicList to be rendered is set on the - * OMGraphicHandlerLayer, available via setList(). - */ - public void paint(Graphics g) { - if (layer != null) { - OMGraphicList list = layer.getList(); - Projection proj = layer.getProjection(); - if (list != null && layer.isProjectionOK(proj)) { - - setCompositeOnGraphics((Graphics2D) g); - - list.render(g); - } else if (logger.isLoggable(Level.FINE)) { - logger.fine(layer.getName() - + " StandardRenderPolicy.paint(): " - + (list == null ? "NULL list, skipping..." : " skipping due to projection.")); - } - } else { - logger.fine("StandardRenderPolicy.paint(): NULL layer, skipping..."); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/policy/package.html b/src/core/src/main/java/com/bbn/openmap/layer/policy/package.html deleted file mode 100644 index 791c7a53e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/policy/package.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Contains policy objects that affect the behavior of -OMGraphicHandlerLayers. Policys can affect how projection changes -are managed and how rendering is accomplished by adjusting layer -parameters and handing a layer's OMGraphicList in special ways. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/FeatureQuery.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/FeatureQuery.java deleted file mode 100644 index 43df058d9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/FeatureQuery.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.postgis.PGgeometry; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * The object that builds a query for a particular feature type, and also - * contains information about how to render it. - * - * @author dietrick - */ -public class FeatureQuery { - - String geomSRID = "900913"; - String geomColumnName; - String geomTableName; - - List columnNames = new ArrayList(); - Map columnTypeMap = new HashMap(); - String queryColumnString = null; - DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - List whereRules = new ArrayList(); - - public FeatureQuery(String geometryTableName, String geometryColumnName, String geometrySrid) { - this.geomSRID = geometrySrid; - this.geomColumnName = geometryColumnName; - this.geomTableName = geometryTableName; - } - - /** - * Add a query rule that affects which geometries and attributes are - * returned. - * - * @param rule FeatureQueryRule - * @return this FeatureQuery, so addition of rules can be stacked on each - * other and on the constructor. - */ - public FeatureQuery addWhereRule(WhereRule rule) { - whereRules.add(rule); - return this; - } - - /** - * - * @param projInfo which will be in 4326 projection and specified as - * such, i.e. something like: ST_SetSRID('BOX3D(" + upperLeft.getX() - * + " " + lowerRight.getY() + "," + lowerRight.getX() + " " + - * upperLeft.getY() + ")'::box3d,4326) - * @return the select command for retrieving this feature, for a particular - * bounds if specified. - * @throws QueryException if where clauses detect a problem - */ - protected String getQuery(ProjectionInfo projInfo) throws QueryException { - StringBuilder ret = new StringBuilder("select"); - - // tell the query to transform successful results back to 4326 for - // conversion to OMGraphics - ret.append(" ST_Transform(").append(geomColumnName).append(",4326)"); - - if (queryColumnString != null) { - ret.append(queryColumnString); - } - - ret.append(" from ").append(geomTableName); - - if (whereRules != null && !whereRules.isEmpty()) { - StringBuilder ruleString = new StringBuilder(); - - for (WhereRule rule : whereRules) { - String queryCondition = rule.getWhereClauseSegment(this, projInfo); - - if (queryCondition != null && !queryCondition.isEmpty()) { - - if (ruleString.length() == 0) { - ruleString.append(" where "); - } else { - ruleString.append(" and "); - } - - ruleString.append("(").append(queryCondition).append(")"); - } - } - - ret.append(ruleString); - } - - /* - * When all put together, it should look like this: - * "select ST_Transform( " + geomColumn + ", 4326), osm_id from " + - * geomTable + " where (" + geomColumn + " && " + spatialQueryString + - * " = true) and (NOT planet_osm_roads.highway is NULL);"; - */ - - return ret.append(";").toString(); - } - - /** - * The main call into the FeatureQuery to gather OMGraphics from the - * database. - * - * @param stmt the sql Statement class; - * @param projInfo describes the current projection. - * @return OMGraphicList containing the results from the query. - * @throws SQLException - * @throws QueryException if where clauses detect a problem - */ - public OMGraphicList queryDatabaseAndMakeOMGraphics(Statement stmt, ProjectionInfo projInfo) - throws SQLException, QueryException { - - String query = getQuery(projInfo); - - System.out.println(query); - - stmt.executeQuery(query); - ResultSet rs = stmt.getResultSet(); - int resultCount = 0; - PostGISOMGraphicFactory factory = new PostGISOMGraphicFactory(projInfo.getProjection(), drawingAttributes); - OMGraphicList results = new OMGraphicList(); - - while (rs.next()) { - PGgeometry geom = (PGgeometry) rs.getObject(1); - results.add(factory.transformGeometryToOM(geom.getGeometry())); - resultCount++; - } - - rs.close(); - System.out.println("feature query resulted in hits: " + resultCount); - - return results; - } - - /** - * @return the drawingAttributes used to decorate the results of this - * feature query. - */ - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - /** - * Set the drawing attributes used to decorate the OMGraphics for this - * FeatureQuery. - * - * @param drawingAttributes the drawingAttributes to set - */ - public void setDrawingAttributes(DrawingAttributes drawingAttributes) { - this.drawingAttributes = drawingAttributes; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISGeometryLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISGeometryLayer.java deleted file mode 100644 index 5ff2aadcd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISGeometryLayer.java +++ /dev/null @@ -1,225 +0,0 @@ -/* *********************************************************************** - * This layer is for the reading and display of any spatial data - * retrieved from a PostGIS Database. - * The code is heavily copied by the MySQL layer and the PostGIS JDBC Driver - * - * Properties to be set: - * - * - * prettyName=<Your Layer Name> - * dbUrl=< Driver Class > eg. "jdbc:postgresql_postGIS://localhost/postgres?user=user&password=password" - * dbClass=< Driver Class > eg. "org.postgis.DriverWrapper" - * geomTable=<Database Tablename> - * geomColumn=<Column name which contains the geometry> - * pointSymbol=<Filename and path for image to use for point objects>Default is - * # Optional Properties - use as required - * # NOTE: There are default for each of these - * lineColor=<Color for lines>Default is red - * lineWidth=<Pixel width of lines>Default is 0 - * fillColor=<Color of fill>Default is red - * This program is distributed freely and 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. - * - * Coded in 2007 by Filippo Di Natale, Milano - Italy - * - * Author name: Filippo Di Natale - * - * *********************************************************************** - */ - -package com.bbn.openmap.layer.postgis; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/* POSTGIS */ -/* OpenMap */ - -/** - * This layer is for the reading and display of any spatial data retrieved from - * a PostGIS Database. - * - * Properties to be set: - * - *

- * prettyName=<Your Layer Name> 
- * dbUrl=<Driver Class>
- * 
- * eg.
- * "jdbc:postgresql_postGIS://localhost/postgres?user=user&password=password" 
- * dbClass=<Driver Class>
- * 
- * eg.
- * "org.postgis.DriverWrapper" 
- * geomTable=<Database Tablename> 
- * geomColumn=<Column name which contains the geometry> 
- * pointSymbol=<Filename and path for image to use for point objects>Default is 
- * # Optional Properties - use as required 
- * # NOTE: There are default for each of these 
- * lineColor=<Color for lines>Default is red 
- * lineWidth=<Pixel width of lines>Default is 1
- * fillColor=<Color of fill>Default is red
- * 
- * 
- * - * Example Usage: - * - * PostGISGeometryLayer postgisLayer = new PostGISGeometryLayer(); - * - *
- * Properties postgisLayerProps = new Properties();
- * postgisLayerProps.put("prettyName", "Province");
- * postgisLayerProps.put("dbUrl", "jdbc:postgresql_postGIS://localhost/postgres?user=user&password=password");
- * postgisLayerProps.put("dbClass", "org.postgis.DriverWrapper");
- * postgisLayerProps.put("geomTable", "my_spatial_table");
- * postgisLayerProps.put("geomColumn", "the_geom");
- * postgisLayer.setProperties(postgisLayerProps);
- * postgisLayer.setVisible(true);
- * mapHandler.add(postgisLayer);
- * 
- * - */ -public class PostGISGeometryLayer extends OMGraphicHandlerLayer { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.PostGISGeometryLayer"); - - private static final long serialVersionUID = 1L; - - /** - * The Property to set for the query: dbUrl . - */ - public static final String DB_URL_PROPERTY = "dbUrl"; - - /** - * The property to use for specifing the driver: dbClass - */ - public static final String DB_CLASS_PROPERTY = "dbClass"; - - /** - * ; The connection String to use for the jdbc query, e.g. - * "jdbc:mysql://localhost/openmap?user=me&password=secret" - */ - protected String dbUrl = null; - - /** - * The driver to use. The default class is org.postgis.DriverWrapper - */ - protected String dbClass = "org.postgis.DriverWrapper"; - - List featureQueryList = new ArrayList(); - - /** - * Property to specify GIF or image file(symbol) to use for Points: - * pointSymbol . - */ - public static final String POINT_SYMBOL_PROPERTY = "pointSymbol"; - - public PostGISGeometryLayer() { - setProjectionChangePolicy(new ListResetPCPolicy(this)); - setRenderPolicy(new BufferedImageRenderPolicy(this)); - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - - // This is a temporary feature query for testing.... - addFeatureQuery(new FeatureQuery("planet_osm_roads", "way", "900913").addWhereRule(new SpatialWhereRule()).addWhereRule(new StringWhereRule("NOT planet_osm_roads.highway is NULL"))); - } - - /** - * The properties and prefix are managed and decoded here. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - dbClass = properties.getProperty(prefix + DB_CLASS_PROPERTY, dbClass); - dbUrl = properties.getProperty(prefix + DB_URL_PROPERTY); - - if (logger.isLoggable(Level.FINE)) { - StringBuilder buf = new StringBuilder(); - buf.append("PostGISGeometryLayer (").append(getName()).append(") properties:"); - buf.append("\n\t").append(dbClass); - buf.append("\n\t").append(dbUrl); - logger.fine(buf.toString()); - } - } - - /** - * Set the provided Properties file with the properties of this layer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.setProperty(prefix + DB_CLASS_PROPERTY, dbClass); - props.setProperty(prefix + DB_URL_PROPERTY, dbUrl); - - return props; - } - - public synchronized OMGraphicList prepare() { - - Projection proj = getProjection(); - - if (proj == null) { - return null; - } - - OMGraphicList graphics = new OMGraphicList(); - - try { - - Class.forName(dbClass).newInstance(); - - Connection conn = DriverManager.getConnection(dbUrl); - Statement stmt = conn.createStatement(); - ProjectionInfo projInfo = new ProjectionInfo(getProjection()); - - for (FeatureQuery featureQuery : featureQueryList) { - try { - graphics.add(featureQuery.queryDatabaseAndMakeOMGraphics(stmt, projInfo)); - } catch (QueryException qe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("halting database query: " + qe.getMessage()); - } - } - } - - conn.close(); - - } catch (SQLException sqlE) { - sqlE.printStackTrace(); - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Problem with getting connection to " + dbUrl + " with the driver " - + dbClass); - e.printStackTrace(); - } - } - - return graphics; - } - - public void addFeatureQuery(FeatureQuery fQuery) { - featureQueryList.add(fQuery); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISOMGraphicFactory.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISOMGraphicFactory.java deleted file mode 100644 index 6393ce58f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/PostGISOMGraphicFactory.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -import org.postgis.Geometry; -import org.postgis.GeometryCollection; -import org.postgis.LineString; -import org.postgis.MultiLineString; -import org.postgis.MultiPoint; -import org.postgis.MultiPolygon; -import org.postgis.Point; -import org.postgis.Polygon; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Projection; - -/** - * Creates OMGraphics from PostGIS/PostGRES geometries. If you pass in a - * projection and DrawingAttributes, it will set those on the resulting - * OMGraphics as they are processed. - * - * @author dietrick - */ -public class PostGISOMGraphicFactory { - - Projection proj; - DrawingAttributes drawingAttributes; - - /** - * Create a factory to process PostGIS geometries. - * - * @param projection the OpenMap projection to use to generate OMGraphics. - * @param da the DrawingAttributes to set on the OMGraphics. - */ - public PostGISOMGraphicFactory(Projection projection, DrawingAttributes da) { - this.proj = projection; - this.drawingAttributes = da; - } - - /** - * Main call to transform Geometry into OMGraphics. - * - * @param geometry PostGIS geometry - * @return OMGraphic - */ - public OMGraphic transformGeometryToOM(Geometry geometry) { - int type = geometry.getType(); - switch (type) { - case Geometry.POINT: - return transformPointToOM((Point) geometry); - case Geometry.LINESTRING: - return transformLineStringToOM((LineString) geometry); - case Geometry.POLYGON: - return transformPolygonToOM((Polygon) geometry); - case Geometry.MULTIPOINT: - return transformMultiPointToOM((MultiPoint) geometry); - case Geometry.MULTILINESTRING: - return trasformMultiLineStringToOM((MultiLineString) geometry); - case Geometry.MULTIPOLYGON: - return transformMultiPolygonToOM((MultiPolygon) geometry); - case Geometry.GEOMETRYCOLLECTION: - return transformGeometryCollectionToOM((GeometryCollection) geometry); - default: - throw new IllegalArgumentException("Unknown Geometry Type: " + type); - } - - } - - /** - * Transform a GeometryCollection to an OMGraphicList, iterating through the - * collection and converting the contents to OMGraphics. - * - * @param collection GeometryCollection - * @return OMGraphicList - */ - private OMGraphicList transformGeometryCollectionToOM(GeometryCollection collection) { - Geometry[] geometries = collection.getGeometries(); - OMGraphicList list = new OMGraphicList(geometries.length); - for (int k = 0; k < geometries.length; k++) { - int type = geometries[k].getType(); - switch (type) { - case Geometry.POINT: - list.add(transformPointToOM((Point) geometries[k])); - break; - case Geometry.LINESTRING: - list.add(transformLineStringToOM((LineString) geometries[k])); - break; - case Geometry.POLYGON: - list.add(transformPolygonToOM((Polygon) geometries[k])); - break; - case Geometry.MULTIPOINT: - list.add(transformMultiPointToOM((MultiPoint) geometries[k])); - break; - case Geometry.MULTILINESTRING: - list.add(trasformMultiLineStringToOM((MultiLineString) geometries[k])); - break; - case Geometry.MULTIPOLYGON: - list.add(transformMultiPolygonToOM((MultiPolygon) geometries[k])); - break; - case Geometry.GEOMETRYCOLLECTION: - list.add(transformGeometryCollectionToOM((GeometryCollection) geometries[k])); - break; - default: - throw new IllegalArgumentException("Unknown Geometry Type: " + type); - } - } - return list; - } - - /** - * Apply DrawingAttributes and generate with projection, if they have been - * provided. - * - * @param omg OMGraphic to process - * @return OMGraphic - */ - private T process(T omg) { - if (drawingAttributes != null) { - drawingAttributes.setTo(omg); - } - if (proj != null) { - omg.generate(proj); - } - return omg; - } - - private OMPoint transformPointToOM(Point point) { - return process(new OMPoint(point.y, point.x)); - } - - private OMPoly transformLineStringToOM(LineString lineString) { - Point[] points = lineString.getPoints(); - int count = points.length; - - double[] lineCoords = new double[count * 2]; - for (int k = 0; k < count; k++) { - Point p = points[k]; - final double x = p.getX(); - final double y = p.getY(); - - lineCoords[2 * k] = y; - lineCoords[2 * k + 1] = x; - } - - return process(new OMPoly(lineCoords, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT)); - } - - /** - * Creates OMGraphics from Polygon. - * - * @param polygon - * @return OMPoly if polygon has 0 rings, OMGraphicList if there are more. - */ - private OMGraphic transformPolygonToOM(Polygon polygon) { - int nRings = polygon.numRings(); - OMGraphicList list = new OMGraphicList(nRings); - - for (int i = 0; i < nRings; i++) { - Point[] ringPoints = polygon.getRing(i).getPoints(); - int size = ringPoints.length; - - double[] ringCoords = new double[size * 2]; - for (int k = 0; k < size; k++) { - Point p = ringPoints[k]; - final double x = p.getX(); - final double y = p.getY(); - - ringCoords[2 * k] = y; - ringCoords[2 * k + 1] = x; - } - - OMPoly poly = process(new OMPoly(ringCoords, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_STRAIGHT)); - - if (nRings == 0) { - return poly; - } - - list.add(poly); - } - - return list; - } - - private OMGraphicList transformMultiPointToOM(MultiPoint multiPoint) { - Point[] points = multiPoint.getPoints(); - OMGraphicList list = new OMGraphicList(points.length); - for (Point p : points) { - list.add(process(new OMPoint(p.getY(), p.getX()))); - } - return list; - } - - private OMGraphicList trasformMultiLineStringToOM(MultiLineString multiLineString) { - LineString[] lines = multiLineString.getLines(); - OMGraphicList list = new OMGraphicList(lines.length); - for (LineString lineString : lines) { - list.add(transformLineStringToOM(lineString)); - } - return list; - } - - private OMGraphicList transformMultiPolygonToOM(MultiPolygon multiPolygon) { - Polygon[] polygons = multiPolygon.getPolygons(); - OMGraphicList list = new OMGraphicList(polygons.length); - for (Polygon polygon : polygons) { - list.add(transformPolygonToOM(polygon)); - } - return list; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/ProjectionInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/ProjectionInfo.java deleted file mode 100644 index 68eca9b99..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/ProjectionInfo.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform; -import com.bbn.openmap.proj.Projection; - -/** - * Handy class that contains different projection information. - * - * @author dietrick - */ -public class ProjectionInfo { - - Projection projection; - String sridBounds; - int zoomLevel; - - public ProjectionInfo(Projection proj) { - this.projection = proj; - - Point2D upperLeft = proj.getUpperLeft(); - Point2D lowerRight = proj.getLowerRight(); - - sridBounds = "ST_SetSRID('BOX3D(" + upperLeft.getX() + " " + lowerRight.getY() + "," - + lowerRight.getX() + " " + upperLeft.getY() + ")'::box3d,4326)"; - - zoomLevel = -1; - } - - /** - * Returns the projection object currently being handled by the layer. - * - * @return the projection - */ - public Projection getProjection() { - return projection; - } - - /** - * Returns the srid bounds string that can be used for PostGIS spatial - * filtering, looks something like: - * - *
-     * ST_SetSRID('BOX3D(upperLeftLon lowerRightLat,lowerRightLon upperLeftLat)'::box3d,4326)
-     * 
- * - * @return the sridBounds - */ - public String getSridBounds() { - return sridBounds; - } - - /** - * Return the zoom level that the projection represents. - * - * @return the zoomLevel - */ - public int getZoomLevel() { - if (zoomLevel < 0) { - zoomLevel = new OSMMapTileCoordinateTransform().getZoomLevelForProj(projection); - } - - return zoomLevel; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/QueryException.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/QueryException.java deleted file mode 100644 index 55fd33753..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/QueryException.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -/** - * An exception thrown when the where clauses detect failure conditions, such as - * a problem with projection. - * - * @author dietrick - */ -public class QueryException extends RuntimeException { - - public QueryException(String message) { - super(message); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/SpatialWhereRule.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/SpatialWhereRule.java deleted file mode 100644 index 07eaa7b67..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/SpatialWhereRule.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -/** - * Creates a spatial query part of a PostGIS where clause rule in the select statement. Assumes the - * {@link FeatureQuery#geomSRID} and {@link FeatureQuery#geomColumnName} are - * not null. - * - * @author dietrick - */ -public class SpatialWhereRule implements WhereRule { - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.postgis.FeatureQueryRule#getQueryCondition(com. - * bbn.openmap.layer.postgis.FeatureQuery, - * com.bbn.openmap.layer.postgis.ProjectionInfo) - */ - public String getWhereClauseSegment(FeatureQuery featureQuery, ProjectionInfo projInfo) throws QueryException { - String sridBounds = projInfo.getSridBounds(); - - if (sridBounds != null && !featureQuery.geomSRID.equalsIgnoreCase("4326")) { - // If the database contents are in a different coordinate - // system, we need to transform the bounding box to match. - StringBuilder boundsBuilder = new StringBuilder("ST_Transform("); - boundsBuilder.append(sridBounds); - boundsBuilder.append(",").append(featureQuery.geomSRID).append(")"); - sridBounds = boundsBuilder.toString(); - } - - if (sridBounds != null) { - // geometry column contents && (overridden operator matching - // bounds), this does the PostGIS bounds filtering - return new StringBuilder(featureQuery.geomColumnName).append(" && ").append(sridBounds).append(" = true").toString(); - } - - return null; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/StringWhereRule.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/StringWhereRule.java deleted file mode 100644 index 821ac8193..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/StringWhereRule.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -/** - * A simple fixed where clause rule that returns the String used in the - * constructor. - * - * @author dietrick - */ -public class StringWhereRule implements WhereRule { - - String stringRule; - - public StringWhereRule(String stringRule) { - this.stringRule = stringRule; - } - - public String getWhereClauseSegment(FeatureQuery featureQuery, ProjectionInfo projInfo) - throws QueryException { - return stringRule; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRule.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRule.java deleted file mode 100644 index 91d4c55a3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRule.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -/** - * A where clause segment, describing parameters for an attribute to pass a select test. - * - * @author dietrick - */ -public interface WhereRule { - - /** - * Return a String to be passed into the Statement query as a condition for evaluating geometries or attributes. - * @param featureQuery can be used to get srid, geometry tables or geometry column names. - * @param projInfo can be used to get information about the projection. - * @return the String to be inserted into the where clause. - * @throws QueryException if the where clause fails based on the featureQuery or projInfo settings. - */ - String getWhereClauseSegment(FeatureQuery featureQuery, ProjectionInfo projInfo) throws QueryException; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRuleImpl.java b/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRuleImpl.java deleted file mode 100644 index c586a64d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/postgis/WhereRuleImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.layer.postgis; - -/** - * A where clause segment, describing parameters for an attribute to pass a - * select test. - * - * @author dietrick - */ -public class WhereRuleImpl implements WhereRule { - - public String getWhereClauseSegment(FeatureQuery featureQuery, ProjectionInfo projInfo) - throws QueryException { - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeToc.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeToc.java deleted file mode 100644 index 51be62929..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeToc.java +++ /dev/null @@ -1,2137 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/MakeToc.java,v $ -// $RCSfile: MakeToc.java,v $ -// $Revision: 1.14 $ -// $Date: 2006/08/17 15:19:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by The MITRE - * Corporation, through the browse application source code. Many - * thanks to Nancy Markuson who provided BBN with the software, and to - * Theron Tock, who wrote the software, and Daniel Scholten, who - * revised it - (c) 1994 The MITRE Corporation for those parts, and - * used/distributed with permission. - */ -package com.bbn.openmap.layer.rpf; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.RandomAccessFile; -import java.util.Vector; - -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressListener; -import com.bbn.openmap.event.ProgressSupport; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.proj.coords.DMSLatLonPoint; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * This is a class that will generate A.TOC files that the RpfLayer requires. - * A.TOC files provide the RpfLayer with an idea of what data is available to - * it, its geographic coverage, and chart type. With the A.TOC contents, the - * RpfLayer is able to find which frames are appropriate for a given projection - * location. It is very important to have a valid A.TOC directory. - *

- * - * The RPF specification, MIL-STD-2411, has definitions for how frames are to be - * laid out and found within a RPF directory. All RPF data is supposed to lie - * under one RPF directory, and an A.TOC file, describing all the files and - * their groupings, should be directly within the RPF directory. That's why the - * RpfLayer needs a path to a RPF directory - it's really looking for the A.TOC - * file, and knows where to find it. It also needs a path to the RPF directory - * because it needs to prepend that path to the paths to the files that the - * A.TOC file knows about. - *

- * - * The A.TOC files that can be created with this MakeToc class can be created to - * contain absolute frame paths. The MakeToc class can take the paths to several - * RPF directories, and create a single A.TOC file that preserves all of their - * current file paths. You have to use a lot of caution with this capability, - * however. These A.TOCs containing absolute file paths will not work if the - * data is moved to another machine, or if referenced by a machine with a - * different type file system (i.e. Windows). They may not work for other - * implementations of code that display RPF data - the code in this package has - * been modified to test for absolute file names. - *

- * - * That said, absolute file names should be used instead of giving the RpfLayer - * several RPF directories. The RpfTocHandler does much less work when it is - * allowed to group coverages together to make bigger areas. - *

- * - * This code was ported from C code provided in the original Mitre RPF package - * that had limits to the number of frames that could make up the areas. I'll be - * working to eliminate those limits, but I wanted to get a working version of - * the code out there. I'm also planning on modifying this class so that it can - * load the RpfTocHandler directly, therefore eliminating the need for A.TOCs - * altogether when there is more than one RPF directory. - *

- * - *

- * 
- * 
- *   Usage:  java com.bbn.openmap.layer.rpf.MakeToc (RPF dir path) (RPF dir path) ...
- * 
- * 
- * 
- * - * This will create an A.TOC file in the current directory for the RPF files in - * the RPF directory paths. Use: - * - *
- * 
- * 
- *   java com.bbn.openmap.layer.rpf.MakeToc -help
- * 
- * 
- * 
- * - * for other options. - * - *

- * NOTE: Make sure that the RPF directories and their contents are in upper - * case. It's a spec requirement, although with CD copies and FTP downloads, the - * file name cases sometimes get switched. Use - * com.bbn.openmap.layer.rpf.ChangeCase to modify the file name cases. Also, if - * there is more than one RPF directory in the path to the image frames, use the - * absolute path option. Otherwise, the code will focus on making the top-most - * RPF directory the one to key the internal relative paths off of, and that - * might not be what you want. - *

- * - * @see com.bbn.openmap.util.wanderer.ChangeCase - */ -public class MakeToc { - - /** - * According to Dan Scholten's original code, this was 2 times the max - - * changed from 30 on 6/17/94 to 200 for 81 JNC's in zone 1. This might not - * be enough for world-wide coverage of larger scale maps that are now - * available. This number may have to be increased depending on how much - * data you need. - */ - public final static int DEFAULT_MAX_SIDE = 200; - - public final static double EPS = 0.01; - public final static double EPS2 = 0.0001; - /** Output file name of the A.TOC file. */ - public final static String ATOC_FILENAME = "A.TOC"; - /** The boundary edge frame length for groups. */ - protected int maxSide = DEFAULT_MAX_SIDE; - /** Flag to use relative frames paths - default is true. */ - protected boolean relativeFramePaths = true; - /** The producer name for the frame files. Default is DMAAC. */ - protected String producer = "DMAAC"; - - protected ProgressSupport progressSupport; - - /** An internal representation of a Frame file. */ - public class Frame { - double left; - double right; - double top; - double bottom; - /* New DKS: for computing GEOREF #'s over polar region */ - double swlat; - double swlon; - double h_interval; - double v_interval; - double h_resolution; - double v_resolution; - String scale; // length 12 - char zone; - boolean marked; - int group; - int x; - int y; - String filename; - boolean cib; - boolean cdted; - - public double EPS() { - return (Math.abs(right - left) * MakeToc.EPS); - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Frame - ").append(filename).append("\n"); - s.append(" zone = ").append(zone).append("\n"); - s.append(" marked = ").append(marked).append("\n"); - s.append(" scale = ").append(scale).append("\n"); - s.append(" group = ").append(group).append("\n"); - - if (Debug.debugging("maketocframe")) { - s.append(" top = ").append(top).append("\n"); - s.append(" bottom = ").append(bottom).append("\n"); - s.append(" left = ").append(left).append("\n"); - s.append(" right = ").append(right).append("\n"); - s.append(" h_interval = ").append(h_interval).append("\n"); - s.append(" v_interval = ").append(v_interval).append("\n"); - s.append(" h_resolution = ").append(h_resolution).append("\n"); - s.append(" v_resolution = ").append(v_resolution).append("\n"); - } - - return s.toString(); - } - } - - /** An internal representation of a boundary rectangle for frames. */ - public class Group { - double[] horiz_pos; - double[] vert_pos; - int left; - int right; - int top; - int bottom; - String scale; - char zone; - double h_interval; - double v_interval; - double h_resolution; - double v_resolution; - boolean cib; - boolean cdted; - - public Group() { - horiz_pos = new double[maxSide]; - vert_pos = new double[maxSide]; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Group - \n"); - s.append(" zone = ").append(zone).append("\n"); - s.append(" scale = ").append(scale).append("\n"); - s.append(" left = ").append(left).append("\n"); - s.append(" right = ").append(right).append("\n"); - s.append(" top = ").append(top).append("\n"); - s.append(" bottom = ").append(bottom).append("\n"); - s.append(" is cdted = ").append(cdted).append("\n"); - s.append(" is cib = ").append(cib).append("\n"); - return s.toString(); - } - } - - public MakeToc() { - progressSupport = new ProgressSupport(this); - } - - /** - * Create an A.TOC file. - * - * @param argv - * The arguments should at least include a path to a RPF file - * root directory. Other options can be found by using a -help - * option. - */ - public static void main(String[] argv) { - Debug.init(); - boolean Dchum = false; - - ArgParser ap = new ArgParser("MakeToc"); - ap.add("absolute", "Use absolute paths in A.TOC - Use for multiple RPF Directories"); - ap.add("boundary", "Maximum frames on a boundary edge (Default 200)", 1); - ap.add("dchum", "DCHUM files are included."); - ap.add("log", "Pathname of log file to list A.TOC creation output.", 1); - ap.add("output", "Path to directory to place A.TOC file. (Default is current directory)", 1); - ap.add("producer", "The producer of the frames (Default DMAAC). Five letter code.", 1); - ap.add("verbose", "Print out progress"); - ap.add("extraverbose", "Print out ALL progress"); - ap.add("nw", "Don't put up swing progress window (Use this if you are getting weird exceptions)"); - ap.add("paths", - "Space separated paths to RPF directory or directories. Should be last. If more than one directory is listed, then absolute paths are used in the A.TOC file.", - ArgParser.TO_END); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String outputFile = "." + File.separator + RpfTocHandler.RPF_TOC_FILE_NAME; - - String arg[]; - arg = ap.getArgValues("output"); - if (arg != null) { - outputFile = arg[0] + File.separator + RpfTocHandler.RPF_TOC_FILE_NAME; - } - - arg = ap.getArgValues("log"); - if (arg != null) { - String logfile = arg[0]; - Debug.directOutput(logfile, false, true); - Debug.output("MakeToc: Creating log at " + logfile + " at " + java.util.Calendar.getInstance().getTime()); - } - - arg = ap.getArgValues("dchum"); - if (arg != null) { - Dchum = true; - } - - arg = ap.getArgValues("verbose"); - if (arg != null) { - Debug.put("maketoc"); - } - - arg = ap.getArgValues("extraverbose"); - if (arg != null) { - Debug.put("maketoc"); - Debug.put("maketocdetail"); - } - - String[] paths = null; - arg = ap.getArgValues("paths"); - if (arg != null) { - paths = arg; - } else { - paths = ap.getRest(); - } - - if (paths == null || paths.length == 0) { - Debug.output("MakeToc: need a path to start searching for RPF frames."); - System.exit(0); - } - - MakeToc mt = new MakeToc(); - - // If the -nw argument was not used, add a progress gauge. - arg = ap.getArgValues("nw"); - if (arg == null) { - try { - mt.addProgressListener(new com.bbn.openmap.gui.ProgressListenerGauge("RPF A.TOC File Creation")); - } catch (RuntimeException re) { - - } - } - - boolean argFlagged = false; - arg = ap.getArgValues("absolute"); - if (arg != null) { - argFlagged = true; - } - - arg = ap.getArgValues("producer"); - if (arg != null) { - mt.setProducer(arg[0]); - } - - if ((paths != null && paths.length > 1) || argFlagged) { - Debug.output("MakeToc: creating A.TOC with absolute path names."); - mt.setRelativeFramePaths(false); - } - - arg = ap.getArgValues("boundary"); - int max_side = DEFAULT_MAX_SIDE; - if (arg != null) { - try { - max_side = Integer.parseInt(arg[0]); - if (max_side <= DEFAULT_MAX_SIDE) { - Debug.output("MakeToc: Boundary number specified (" + max_side - + ") is too small. Using default of 200."); - max_side = DEFAULT_MAX_SIDE; - } - } catch (NumberFormatException nfe) { - Debug.output("MakeToc: Tried to pass a bogus integer (" + arg[0] - + ") as a boundary limit. Using default of 200."); - max_side = DEFAULT_MAX_SIDE; - } - } - mt.setMaxSide(max_side); - mt.fireProgressUpdate(ProgressEvent.START, "Searching for RPF frames", 0, 100); - - paths = mt.searchForRpfFiles(paths); - - try { - - mt.create(paths, outputFile, Dchum); - - } catch (MakeTocException mte) { - Debug.error("Problem creating A.TOC file: \n" + mte.getMessage()); - } - - System.exit(0); - - } - - /** - * Create a A.TOC file specificed by the frame file list, at the location - * specified. - * - * @param rpfFilePaths - * An array of all RPF Frame file paths. If these paths are - * relative, the MakeToc class should be set for that. - * @param outputFile - * the complete pathname to an A.TOC file to be written. - * @exception MakeTocException - * if anything goes wrong. - */ - public void create(String[] rpfFilePaths, String outputFile) throws MakeTocException { - create(rpfFilePaths, outputFile, false); - } - - /** - * Create a A.TOC file specificed by the frame file list, at the location - * specified. - * - * @param rpfFilePaths - * An array of all RPF Frame file paths. If these paths are - * relative, the MakeToc class should be set for that. - * @param outputFile - * the complete pathname to an A.TOC file to be written. - * @param dchum - * If dchum is present, all frames get placed in their own group. - * False is default. Dchum are replacement subframes. - * @exception MakeTocException - * if anything goes wrong. - */ - public void create(String[] rpfFilePaths, String outputFile, boolean dchum) throws MakeTocException { - - RpfHeader head = new RpfHeader(); - Vector frames = new Vector(rpfFilePaths.length); - Vector groups = new Vector(); - - fireProgressUpdate(ProgressEvent.UPDATE, "Organizing frames", 0, 100); - - organizeFrames(rpfFilePaths, head, frames); - - if (head.standardNumber == null) { - throw new MakeTocException("MakeToc: No RPF frames found."); - } - - groupFrames(frames, groups, dchum); - fireProgressUpdate(ProgressEvent.UPDATE, "Writing A.TOC file", 100, 100); - writeTOCFile(outputFile, head, frames, groups); - fireProgressUpdate(ProgressEvent.DONE, "A.TOC file complete", 100, 100); - } - - /** - * Look for RPF frame files, given a bunch of places to start looking. The - * output of this can be passed to the create method. - * - * @param startDirs - * Directory paths. - * @return an array of strings representing path names to RPF frame files. - */ - public String[] searchForRpfFiles(String[] startDirs) { - RpfFileSearch search = new RpfFileSearch(); - for (int i = 0; i < startDirs.length; i++) { - search.handleEntry(startDirs[i]); - } - return search.getFiles(); - } - - /** - * Set whether to use relative frame paths in the A.TOC file. - */ - public void setRelativeFramePaths(boolean setting) { - relativeFramePaths = setting; - } - - public boolean getRelativeFramePaths() { - return relativeFramePaths; - } - - /** - * Set the 5 letter producer code for the frames. If you didn't make the - * frames, they DMA probably did, so the default is applicable - DMAAC. - * There are a bunch of accepted codes in the MIL-STD-2411 for producers. - */ - public void setProducer(String setting) { - if (setting.length() != 5) { - if (setting.length() >= 5) { - producer = setting.substring(0, 5); - } else { - producer = setting + createPadding(5 - setting.length(), false); - } - } else { - producer = setting; - } - } - - /** Get the producer code currently set. */ - public String getProducer() { - return producer; - } - - /** - * Set the Maximum number of frames along a group boundary edge. Don't - * change this after starting to group the frames. - */ - protected void setMaxSide(int set) { - maxSide = set; - } - - /** - * Get the Maximum number of frames along a group boundary edge. - */ - protected int getMaxSide() { - return maxSide; - } - - /** A little function to tell of one edge is near another. */ - protected boolean near(double a, double b, double eps) { - return (Math.abs(a - b) < eps); /* EPS was 0.0001 */ - } - - /** - * Get all the frame paths, and sort through them. This method sets up the - * frames vector and loads each Frame with it's attributes, so it can be - * grouped with its neighbors. - * - * @param framePaths - * the array of RPF file paths. - * @param head - * an RpfHeader object to load with production information, that - * will be put into the A.TOC file. - * @param frames - * the frame vector to load. - */ - public void organizeFrames(String[] framePaths, RpfHeader head, Vector frames) { - - int tail; - int i; - - /* New, DKS */ - // boolean Cib = false; /* CIB data flag: 1:I1(10M); 2:I2(5M) */ - // boolean Cdted = false; /* CDTED data flag: 1: DT1(100M) */ - boolean isoverview = false; - boolean islegend = false; - - Frame frame; - - RpfFileSections.RpfCoverageSection coverage; - - Debug.message("maketoc", "MakeToc.organizeFrames: *** initial look at frames ***"); - - /* # of frames = # of pathname records = #files */ - int nFrames = framePaths.length; - - if (Debug.debugging("maketoc")) { - Debug.output("Number of frames: " + nFrames); - } - - /* for each frame file */ - for (i = 0; i < nFrames; i++) { - isoverview = false; - islegend = false; - - String framePath = framePaths[i]; - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: frame number " + i + ", " + framePath); - } - - try { - BinaryFile binFile = new BinaryBufferedFile(framePath); - - // Frame file names are 8.3 notation, might want to - // check - // that here, to blow off dummy files. - String fn = binFile.getName(); - if (fn.length() != 12) { - // Not a RPF Frame file - if (Debug.debugging("maketoc")) { - Debug.error("MakeToc: " + framePath + " is not a RPF image file - ignoring"); - } - continue; - } - - RpfFileSections rfs = new RpfFileSections(); - - binFile.seek(0); - - if (!head.read(binFile)) { - // Not a RPF Frame file - if (Debug.debugging("maketoc")) { - Debug.error("MakeToc: " + framePath + " is not a RPF image file - ignoring"); - } - continue; - } - - binFile.seek(head.locationSectionLocation); - - rfs.parse(binFile); - coverage = rfs.parseCoverageSection(binFile); - - if (coverage == null) { - Debug.error( - "MakeToc: error reading coverage section for " + framePath + ", (file " + i + ") skipping"); - - binFile.close(); - continue; - } - - if (Debug.debugging("maketocframedetail")) { - Debug.output("MakeToc.organizeFrames: coverage section for " + framePath + ", " + coverage); - } - - binFile.close(); - binFile = null; - - } catch (FileNotFoundException e) { - Debug.error("MakeToc: " + framePath + " not found, being ignored."); - continue; - } catch (IOException ioe) { - Debug.error("MakeToc: File IO Error during read of: " + framePath + "! Being ignored. \n" + ioe); - continue; - } - - frame = new Frame(); - frames.add(frame); - - frame.filename = framePath; - - // This will be the actual file name, without parental - // path. - String framename; - - tail = frame.filename.lastIndexOf(File.separatorChar); - if (tail == -1) { - framename = frame.filename; - } else { - framename = frame.filename.substring(++tail); - } - - if (framename.length() != 12) { - Debug.error("filename must be 12 chars long - " + framename); - return; - } - - // 9 is the character after the period. - isoverview = (framename.charAt(9) == 'O'); - if (!isoverview) { - islegend = framename.regionMatches(true, 9, "LG", 0, 2); - } - - // Check and see of the file thinks it's name is the same - // as it actually is. If they differ, rule in favor of - // what the frame thinks it is. - - // Let's just be passive here, and name it to whatever it - // is. If we found the frame, then we'll find it later, - // too. -DFD - - // if (!framename.equals(head.filename)) { /* DKS */ - // File file = new File(frame.filename); - // File newFile = new File(frame.filename.substring(0, - // tail), - // head.filename); - // file.renameTo(newFile); - // framename = head.filename; - - // Debug.output("WARNING: File \"" + framename + - // "\" doesn't match internal name \"" + head.filename + - // "\" - Fixed."); - // } - - isoverview = false; - islegend = false; - String padding = null; - String seriesCode = head.filename.substring(9, 11); - RpfProductInfo rpi = RpfProductInfo.get(seriesCode); - - if (rpi == RpfProductInfo.UK) { - - String dblChkSeriesCode = framename.substring(9, 11); - RpfProductInfo rpi2 = rpi; - - if (!seriesCode.equals(dblChkSeriesCode)) { - rpi2 = RpfProductInfo.get(dblChkSeriesCode); - } - - if (rpi2 == RpfProductInfo.UK) { - - Debug.output("MakeToc: " + frame.filename + " / " + head.filename - + " (filename/header) unknown map type " + seriesCode + " / " + dblChkSeriesCode - + " - ignoring."); - frames.remove(frame); - continue; - } - } - - String scaleString = rpi.scaleString; - if (rpi.scale == RpfConstants.Various || scaleString == null || scaleString.length() == 0) { - // need to figure out how to consult the frame for - // what it is. - // RpfAttributes.chartSeriesCode might have something - // to base it off. - // GNC = GN, JNC = JN, ONC = ON, TPC = TP, JOG = 15, - // TLM50 = V7, - // But I'm not sure about the others. For now, prompt - // for scale. - - // Try something new, look it up if it exists. - scaleString = searchForATOCForScaleReference(framePath); - if (scaleString == null || scaleString.length() == 0) { - scaleString = promptForScale( - "What is the scale for " + frame.filename + "? (Answer should look like: 1:XXX,XXX)"); - if (scaleString == null || scaleString.length() == 0) { - Debug.error("Bad input for scale for " + frame.filename + ", skipping."); - frames.remove(frame); - continue; - } - } - } - - if (rpi.dataType.equalsIgnoreCase(RpfConstants.CIB)) { - frame.cib = true; - } else if (rpi.dataType.equalsIgnoreCase(RpfConstants.CDTED)) { - frame.cdted = true; - } // else do nothing for CADRG - - // Set the string to length 12, was 15 for some reason. - int scaleStringLength = 12; - if (scaleString.length() < scaleStringLength) { - padding = createPadding(scaleStringLength - scaleString.length(), false); - scaleString += padding; - } else if (scaleString.length() > scaleStringLength) { - scaleString = scaleString.substring(0, scaleStringLength); - } - - frame.scale = scaleString; - frame.zone = head.filename.charAt(11); - - if (isoverview) { - coverage.nwlat = coverage.nelat = coverage.nwlon = coverage.swlon = coverage.swlat = coverage.selat = coverage.nelon = coverage.selon = 0; - coverage.latInterval = coverage.lonInterval = coverage.nsVertRes = coverage.ewHorRes = 0; - } - - if (islegend) { - coverage.nwlat = coverage.nelat = coverage.nwlon = coverage.swlon = coverage.swlat = coverage.selat = coverage.nelon = coverage.selon = 0; - coverage.latInterval = coverage.lonInterval = coverage.nsVertRes = coverage.ewHorRes = 0; - } - - /* - * PBF 6-18-94 check for rectangular coverage or polar frame - */ - if (frame.zone == '9' || frame.zone == 'J') { - /* - * Polar. Convert boundary from lat-long degrees to pixels - */ - /* DKS 1/95: North pole: "9" code */ - if (frame.zone == '9') { - if (Debug.debugging("maketoc")) - Debug.output("Processing NORTH pole"); - - frame.left = (90.0 - coverage.nwlat) * Math.sin(coverage.nwlon * Math.PI / 180.0) - / coverage.latInterval; - - frame.right = (90.0 - coverage.selat) * Math.sin(coverage.selon * Math.PI / 180.0) - / coverage.latInterval; - - frame.top = -1 * (90.0 - coverage.nwlat) * Math.cos(coverage.nwlon * Math.PI / 180.0) - / coverage.latInterval; - - frame.bottom = -1 * (90.0 - coverage.selat) * Math.cos(coverage.selon * Math.PI / 180.0) - / coverage.latInterval; - } else { /* DKS 1/95: South pole: "J" code */ - if (Debug.debugging("maketoc")) - Debug.output("Processing SOUTH pole"); - - frame.left = (90.0 + coverage.nwlat) * Math.sin(coverage.nwlon * Math.PI / 180.0) - / coverage.latInterval; - - frame.right = (90.0 + coverage.selat) * Math.sin(coverage.selon * Math.PI / 180.0) - / coverage.latInterval; - - frame.top = (90.0 + coverage.nwlat) * Math.cos(coverage.nwlon * Math.PI / 180.0) - / coverage.latInterval; - - frame.bottom = (90.0 + coverage.selat) * Math.cos(coverage.selon * Math.PI / 180.0) - / coverage.latInterval; - } /* if South pole */ - - /* DKS 8/1/94: Added for GEOREF calc later */ - frame.swlat = coverage.swlat; - frame.swlon = coverage.swlon; - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: " + frame.filename + " is a Polar frame"); - } /* if Debug.debugging("maketoc") */ - - } else { - - frame.left = coverage.nwlon; - frame.right = coverage.selon; - - /* - * NEW, DKS 6/94. Correct for frame straddling 180 deg. - */ - if (coverage.selon < coverage.nwlon) { - frame.right = 180.0; - } - - frame.top = coverage.nwlat; - frame.bottom = coverage.selat; - } - - frame.h_interval = coverage.lonInterval; - frame.v_interval = coverage.latInterval; - frame.h_resolution = coverage.ewHorRes; - frame.v_resolution = coverage.nsVertRes; - - frame.marked = false; - - if (Debug.debugging("maketocframedetail")) { - Debug.output("MakeToc: nw_lon = " + coverage.nwlon + ", se_lon = " + coverage.selon - + "\n nwlat = " + coverage.nwlat + ", selat = " + coverage.selat + "\n NEW: swlat = " - + coverage.swlat + ", swlon = " + coverage.swlon + "\n vert_interval = " - + coverage.latInterval + ", horiz_interval = " + coverage.lonInterval - + "\n vertical resolution = " + coverage.nsVertRes + ", horizontal resolution = " - + coverage.ewHorRes + "\n left = " + frame.left + ", right = " + frame.right - + "\n top = " + frame.top + ", bottom = " + frame.bottom + "\n"); - - } - } /* for i: each input frame file */ - } - - protected String searchForATOCForScaleReference(String framePath) { - // System.out.println("looking for scale for " + framePath); - RpfTocHandler tocHandler = new RpfTocHandler(); - File frameFile = new File(framePath); - File parent = frameFile.getParentFile(); - while (parent.exists()) { - - // System.out.println("checking " + parent + " for A.TOC"); - File tocFile = tocHandler.getTocFile(parent.getAbsolutePath()); - - if (tocFile != null && tocHandler.loadFile(parent.getAbsolutePath())) { - // System.out.println("found it at :" + parent); - tocHandler.valid = true; - break; - } - - parent = parent.getParentFile(); - } - - if (tocHandler.valid) { - int pathLength = framePath.length(); - String frameChartCode = framePath.substring(pathLength - 3, pathLength - 1); - int frameZone = Integer.parseInt(new Character(framePath.charAt(pathLength - 1)).toString()); - for (RpfTocEntry entry : tocHandler.entries) { - String chartCode = entry.coverage.chartCode; - int zone = entry.coverage.zone; - - if (chartCode.equalsIgnoreCase(frameChartCode) && zone == frameZone) { - // System.out.println("Found matching chart code: " + - // frameChartCode + ", zone: " + frameZone); - // Lets look for the frame file in this entry - tocHandler.loadFrameInformation(entry); - for (RpfFrameEntry[] entryDim : entry.frames) { - for (RpfFrameEntry fEntry : entryDim) { - // System.out.println("comparing " + framePath + " - // to " + fEntry.framePath); - if (fEntry.framePath.endsWith(framePath)) { - System.out.println("setting " + entry.scale + " for " + framePath); - return entry.scale; - } - } - } - } - } - } - return null; - } - - /** - * Prompt for input. - */ - protected String promptForScale(String query) { - try { - String answer = null; - System.out.println(query); - InputStreamReader isr = new InputStreamReader(System.in); - BufferedReader bufr = new BufferedReader(isr); - answer = bufr.readLine(); - return answer; - } catch (IOException ioe) { - Debug.error("MakeToc: IOException trying to get an answer from you. Dang."); - return null; - } - } - - /** - * Create and write out an A.TOC file. - * - * @param filename - * the output filename. - * @param head - * the RpfHeader containing header information. - * @param frames - * the frame Vector. - * @param groups - * the file groups Vector. - */ - protected void writeTOCFile(String filename, RpfHeader head, Vector frames, Vector groups) - throws MakeTocException { - - short us; - int i, j, tail; - - /* - * DKS changed from left, right for polar zone: new left_bottom longit. - */ - double left_b, left_t, right_b, right_t, top, bottom; - double xleft, xright, ytop, ybottom; - - /* !! To be filled in later */ - int TOC_Nitf_hdr_size = 0; /* - * ?? Nitf header size for output TOC - */ - int Loc_sec_len; /* Location section length */ - int Bound_tbl_len; /* Boundary rectangle table length */ - int Frame_hdr_len = 13; /* Frame index header length */ - int Frame_index_rec_len = 33; /* - * Frame index record length (was 37) - */ - int Frame_sec_len; /* Frame section length */ - - RandomAccessFile fout = null; - int groupCount = groups.size(); - int nFrames = frames.size(); - - /* cumulative pathname positions */ - int[] pathname_pos = new int[nFrames]; - - /* List of pathnames: directories */ - String[] direct = new String[nFrames]; - - /* Allocations for uniq directories */ - int[] uniq_dir_ptr = new int[nFrames]; /* - * index from filename to uniq - * direct. - */ - int[] uniq_dir_pos = new int[nFrames]; /* - * position of direct. name in - * file - */ - - /* list of direct. names */ - String[] uniq_dir = new String[nFrames]; - - String georef = "AAAAAA"; /* GEOREF # */ - Frame frame; - Group group; - - // Right now, just write the new file locally. - try { - fout = new RandomAccessFile(filename, "rw"); - - /* WRITE TOC : */ - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: *** writing TOC ***\n at: " + filename); - } - - /* HEADER SECTION */ - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: *** writing header section ***"); - } - - String charString; - char[] nt = new char[1]; - nt[0] = '\0'; - - /* DKS. Can't write structure because of pad bytes */ - /* fwrite(&head, sizeof(head), 1, fout); */ - - fout.writeBoolean(head.endian); // Big Endian - should - // match head.endian - fout.writeShort(RpfHeader.HEADER_SECTION_LENGTH); - fout.writeBytes(" A.TOC"); // has to be padded. - fout.writeByte(head.neww); - - fout.writeBytes(head.standardNumber); - if (head.standardNumber.length() < 15) { - fout.writeBytes(createPadding(15 - head.standardNumber.length(), false)); - } - - fout.writeBytes(head.standardDate); - if (head.standardDate.length() < 8) { - fout.writeBytes(createPadding(8 - head.standardDate.length(), false)); - } - - // All this trouble just for a silly character. - char[] charArray = new char[1]; - charArray[0] = head.classification; - charString = new String(charArray); - fout.writeBytes(charString); - - Debug.message("maketoc", - "MakeToc: writing country(" + head.country + ") and release(" + head.release + ")"); - - fout.writeBytes(head.country); - fout.writeBytes(head.release); - - /* - * New, DKS. no longer head.loc_sec_phys_loc. Always write 48. - */ - /* - * DFD - This isn't true, but since we don't care about NITF - * formatting, it may be. Just write out where we are. - */ - int location_section_location = (int) fout.getFilePointer() + 4; - fout.writeInt(location_section_location); - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: location section location is : " + location_section_location); - } - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: *** writing location section ***"); - } - - /* LOCATION SECTION */ - int Loc_hdr_len = 14; /* Location section header length */ - int Loc_sec_comp_len = 10; /* - * Location section component length - */ - - /* 14 + 4 * 10 = 54 */ - Loc_sec_len = Loc_hdr_len + (RpfFileSections.TOC_LOCATION_KEY * Loc_sec_comp_len); - fout.writeShort(Loc_sec_len); - /* compon. loc tbl offset: location section hdr length */ - fout.writeInt(Loc_hdr_len); - /* # records in location section: 4 */ - fout.writeShort(RpfFileSections.TOC_LOCATION_KEY); - /* component location record length: 10 */ - fout.writeShort(Loc_sec_comp_len); - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc:\n location section length: " + Loc_sec_len + "\n location header length: " - + Loc_hdr_len + "\n number of location records: " + RpfFileSections.TOC_LOCATION_KEY - + "\n location section comp length: " + Loc_sec_comp_len); - } - - /* - * compon. aggregate len: unknown here. Fill in after doing all - * else. - */ - /* location component aggregate length file location */ - long agg_loc = fout.getFilePointer(); /* save for later */ - fout.writeInt(0); // place holder. - - /* Begin: location section, component location table */ - - int Bound_hdr_len = 8; /* Boundary section header length */ - int Bound_rec_len = 132; /* Boundary record length */ - - /* Boundary section length */ - int Bound_sec_len = Bound_hdr_len + (groupCount * Bound_rec_len); - - /* Compute frame section length, for later */ - pathname_pos[0] = 0; /* cum. offset */ - int uniq_dir_cnt = 0; /* # of unique directory paths. */ - - // Looking for the directory name for each file. - for (i = 0; i < nFrames; i++) { /* for each frame file */ - - /* - * set tail to ptr to last occurrence of '/' in filename - */ - /* frames[i].filename is full pathname */ - frame = (Frame) frames.elementAt(i); - - tail = frame.filename.lastIndexOf(File.separatorChar); - if (tail == -1) { - direct[i] = frame.filename; - } else { - // Java-cise the name, so it meets spec. - direct[i] = frame.filename.substring(0, ++tail).replace('\\', '/'); - } - - if (Debug.debugging("maketocdetail")) - Debug.output("MakeToc: Matching directory: " + direct[i]); - - /* Match direct. names with list of uniq direct. names */ - - /* flag for found name in list */ - boolean uniq_dir_match = false; - String tmpDir = null; - - if (relativeFramePaths) { - int rpfIndex = direct[i].lastIndexOf("RPF"); - if (rpfIndex == -1) { - rpfIndex = direct[i].lastIndexOf("rpf"); - } - if (rpfIndex != -1) { - rpfIndex += 3; - if (direct[i].length() > rpfIndex && direct[i].charAt(rpfIndex) == '/') { - - rpfIndex++; - } - tmpDir = "./" + direct[i].substring(rpfIndex); - } else { - if (Debug.debugging("maketoc")) { - Debug.output( - "RPF directory not found in directory path " + direct[i] + ", using absolute path"); - } - tmpDir = direct[i]; - } - - } else { - tmpDir = direct[i]; - } - - for (j = 0; j < uniq_dir_cnt; j++) { - if (tmpDir.equals(uniq_dir[j])) { - uniq_dir_ptr[i] = j; - uniq_dir_match = true; - if (Debug.debugging("maketocdetail")) - Debug.output("Found match with: " + uniq_dir[j]); - break; - } - } - - if (!uniq_dir_match) { - uniq_dir[uniq_dir_cnt] = tmpDir; - uniq_dir_ptr[i] = uniq_dir_cnt; - if (Debug.debugging("maketoc")) - Debug.output("Adding Unique directory: " + uniq_dir[uniq_dir_cnt]); - uniq_dir_cnt++; - } /* if */ - - } /* for i */ - - if (Debug.debugging("maketoc")) - Debug.output("Uniq_dir_cnt: " + uniq_dir_cnt); - - /* compute uniq dir pathname table length */ - int path_table_len = 0; - for (j = 0; j < uniq_dir_cnt; j++) { - /* 2 for path length var. in hdr */ - path_table_len += 2 + uniq_dir[j].length(); - } /* for j */ - - /* compute directory name positions in file */ - uniq_dir_pos[0] = 0; - for (j = 1; j < uniq_dir_cnt; j++) { - uniq_dir_pos[j] = uniq_dir_pos[j - 1] + 2 + uniq_dir[j - 1].length(); - } /* for j */ - - for (j = 0; j < uniq_dir_cnt; j++) { - if (Debug.debugging("maketocdetail")) - Debug.output("j: " + j + ", uniq_dir_pos[j]: " + uniq_dir_pos[j]); - } /* for j */ - - /* compute direct. positions for each input file pathname */ - for (i = 0; i < nFrames; i++) { - pathname_pos[i] = uniq_dir_pos[uniq_dir_ptr[i]]; - if (Debug.debugging("maketocdetail")) - Debug.output("i: " + i + ", pathname_pos[i]:" + pathname_pos[i]); - } /* for i */ - - /* - * frame file index record length: 9 + nFrames * 33 + path_table_len - */ - Frame_sec_len = Frame_hdr_len + nFrames * Frame_index_rec_len + path_table_len; - - /* START LOCATION RECORD 1 */ - /* ID #: */ - fout.writeShort((short) RpfFileSections.LOC_BOUNDARY_SECTION_SUBHEADER); - - // The boundary section subheader is the first part of the - // boundary rectangle section. The boundary section comes - // right after the header (in this program - the spec will - // allow it to be anywhere). - - /* Boundary section subheader length */ - fout.writeInt(Bound_hdr_len); - - /* DKS. Physical location */ - /* 0 + 48 + 54 */ - fout.writeInt(TOC_Nitf_hdr_size + RpfHeader.HEADER_SECTION_LENGTH + Loc_sec_len); - - /* START LOCATION RECORD 2 */ - /* ID #: */ - fout.writeShort((short) RpfFileSections.LOC_BOUNDARY_RECTANGLE_TABLE); - - /* Boundary rectangle table length */ - Bound_tbl_len = groupCount * Bound_rec_len; - fout.writeInt(Bound_tbl_len); - - /* DKS. Physical location */ - /* 0 + 48 + 54 + 8 */ - fout.writeInt(TOC_Nitf_hdr_size + RpfHeader.HEADER_SECTION_LENGTH + Loc_sec_len + Bound_hdr_len); - - Bound_sec_len = Bound_hdr_len + Bound_tbl_len; - - /* START LOCATION RECORD 3 */ - /* ID #: */ - fout.writeShort((short) RpfFileSections.LOC_FRAME_FILE_INDEX_SUBHEADER); - - /* length */ - fout.writeInt(Frame_hdr_len); - - /* physical index (offset) */ - fout.writeInt(TOC_Nitf_hdr_size + RpfHeader.HEADER_SECTION_LENGTH + Loc_sec_len + Bound_sec_len); - - /* START LOCATION RECORD 4 */ - /* ID #: */ - fout.writeShort((short) RpfFileSections.LOC_FRAME_FILE_INDEX_SUBSECTION); - - /* length */ - /* Frame_sec_len computed above */ - fout.writeInt(Frame_sec_len - Frame_hdr_len); - - /* physical index (offset) */ - fout.writeInt( - TOC_Nitf_hdr_size + RpfHeader.HEADER_SECTION_LENGTH + Loc_sec_len + Bound_sec_len + Frame_hdr_len); - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: boundary section at : " + fout.getFilePointer()); - } - - /* START BOUNDARY RECTANGLE SECTION */ - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: *** writing boundary rectangles ***"); - } - - /* Subheader */ - /* boundary rectangle table offset */ - fout.writeInt(0); - - /* # of boundary rectangle records */ - fout.writeShort((short) groupCount); - - /* boundary rectangle record length */ - fout.writeShort((short) Bound_rec_len); - - /* For each boundary rectangle record */ - for (i = 0; i < groupCount; i++) { - - group = (Group) groups.elementAt(i); - - /* - * Key off flag to write proper data to A.TOC for browse menu - * later - */ - if (group.cib) { - fout.writeBytes("CIB "); - fout.writeBytes("8:1 "); /* Compr. ratio */ - } else if (group.cdted) { - fout.writeBytes("CDTED"); - fout.writeBytes("6.5:1"); /* - * Compr. ratio: VARIABLE - */ - } else { - fout.writeBytes("CADRG"); - fout.writeBytes("55:1 "); - } /* else */ - - // Should be 12 padded chars, check just in case... - if (group.scale.length() < 12) { - fout.writeBytes(group.scale); - fout.writeBytes(createPadding(12 - group.scale.length(), false)); - } else { - fout.writeBytes(group.scale.substring(0, 12)); // Already - // 12 - // padded - // chars - } - - // All this trouble just for a silly character. - charArray[0] = group.zone; - charString = new String(charArray); - fout.writeBytes(charString); - - /* DKS changed from AFESC to DMAAC 8/2/94 */ - /* Producer: */ - // Should be OpenMap BBN, I guess. - fout.writeBytes(producer); - - /* - * PBF - If group is polar, change boundaries from rect - * coordinates to lat-lon -- 6-19-94 - */ - if (group.zone == '9' || group.zone == 'J') { /* - * polar zone - */ - /* - * DKS: switched x,y to match spec: x increases right, y up. - */ - ytop = group.horiz_pos[group.top]; - ybottom = group.horiz_pos[group.bottom]; - xleft = group.vert_pos[group.left]; - xright = group.vert_pos[group.right]; - - if (Debug.debugging("maketoc")) { - Debug.output("POLAR ZONE. ytop: " + ytop + ", ybottom: " + ybottom + ", xleft: " + xleft - + ", xright:" + xright); - } - /* see CADRG SPEC 89038, p. 50 */ - /* - * FIND LATITUDES from x,y. x increases right, y up. - */ - - /* DKS new 1/95 to handle South pole separately. */ - /* h_interval converts from pix to deg. */ - if (group.zone == '9') { /* "9": NORTH POLE */ - top = 90 - (Math.sqrt((ytop * ytop) + (xleft * xleft)) * (group.h_interval)); - bottom = 90 - (Math.sqrt((ybottom * ybottom) + (xright * xright)) * (group.h_interval)); - } /* North pole */ - - else { /* "J": South Pole */ - top = -90 + (Math.sqrt((ytop * ytop) + (xleft * xleft)) * (group.h_interval)); - bottom = -90 + (Math.sqrt((ybottom * ybottom) + (xright * xright)) * (group.h_interval)); - } /* South pole */ - - if (Debug.debugging("maketoc")) - Debug.output("LATS. top: " + top + ", bottom: " + bottom); - - /* - * Cvt from x,y to LONGITUDE; from radians to degrees - */ - - /* DKS added South pole case 1/95 */ - - if (group.zone == '9') { /* "9": NORTH POLE */ - left_t = 180.0 / Math.PI * Math.acos(-ytop / Math.sqrt((ytop * ytop) + (xleft * xleft))); - /* DKS fixed bug 1/95: from ytop to ybottom */ - left_b = 180.0 / Math.PI - * Math.acos(-ybottom / Math.sqrt((ybottom * ybottom) + (xleft * xleft))); - right_t = 180.0 / Math.PI * Math.acos(-ytop / Math.sqrt((ytop * ytop) + (xright * xright))); - /* DKS fixed bug 1/95: from ytop to ybottom */ - right_b = 180.0 / Math.PI - * Math.acos(-ybottom / Math.sqrt((ybottom * ybottom) + (xright * xright))); - } /* if North pole */ - - else { /* South Pole */ - left_t = 180.0 / Math.PI * Math.acos(ytop / Math.sqrt((ytop * ytop) + (xleft * xleft))); - /* DKS fixed bug 1/95: from ytop to ybottom */ - left_b = 180.0 / Math.PI - * Math.acos(ybottom / Math.sqrt((ybottom * ybottom) + (xleft * xleft))); - right_t = 180.0 / Math.PI * Math.acos(ytop / Math.sqrt((ytop * ytop) + (xright * xright))); - /* DKS fixed bug 1/95: from ytop to ybottom */ - right_b = 180.0 / Math.PI - * Math.acos(ybottom / Math.sqrt((ybottom * ybottom) + (xright * xright))); - } /* if South pole */ - - /* For both poles: */ - if (xleft < 0) { /* - * left half of earth has negative - * longits - */ - left_t = -left_t; - left_b = -left_b; - } - /* This will hardly ever happen: */ - if (xright < 0) { /* - * left half of earth has negative longs - */ - right_t = -right_t; - right_b = -right_b; - } - - if (Debug.debugging("maketoc")) - Debug.output("LONGS. left_t: " + left_t + ", right_t: " + right_t); - if (Debug.debugging("maketoc")) - Debug.output("LONGS. left_b: " + left_b + ", right_b: " + right_b); - - // #if 0 - // /* !!!!!!!!!!!!!!!!!!! Fix to getlat [80,90], - // longit. [-180,180] */ - // bottom = 80.0 ; - // top = 90.0 ; - // left = -180.0 ; - // right = 180.0 ; - // #endif - - } /* if polar zone */ - - /* end DKS portion */ - /* end PBF cvt from xy to lat-long */ - - else { /* non-polar zone */ - - left_t = group.vert_pos[group.left]; - left_b = left_t; - right_t = group.vert_pos[group.right]; - right_b = right_t; - top = group.horiz_pos[group.top]; - bottom = group.horiz_pos[group.bottom]; - - } /* else */ - - // Debug.output("For RpfTocEntry, writing: \n top = " - // + top + - // "\n bottom = " + bottom + "\n left = " + left_t + - // "\n right = " + right_t + "\n---------"); - - // Writing all doubles - - fout.writeDouble(top); - fout.writeDouble(left_t); - fout.writeDouble(bottom); - fout.writeDouble(left_b); - fout.writeDouble(top); - fout.writeDouble(right_t); - fout.writeDouble(bottom); - fout.writeDouble(right_b); - - fout.writeDouble(group.v_resolution); - fout.writeDouble(group.h_resolution); - fout.writeDouble(group.v_interval); - fout.writeDouble(group.h_interval); - - /* # frames */ - fout.writeInt((int) (group.bottom - group.top)); - fout.writeInt((int) (group.right - group.left)); - } - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: *** writing frame section ***"); - Debug.output("MakeToc: started with a 'U'"); - } - - /* START FRAME SECTION */ - /* Now write frames */ - - /* security classif */ - charArray[0] = 'U'; - charString = new String(charArray); - fout.writeBytes(charString); - - /* frame file index tbl offset */ - fout.writeInt(0); - - /* # of frame file index records */ - fout.writeInt(nFrames); - - /* # of pathname (directory) records */ - /* DKS NEW: was nFrames: */ - fout.writeShort(uniq_dir_cnt); - - /* frame file index record length : 33 */ - fout.writeShort(Frame_index_rec_len); - - /* Frame file index subsection */ - for (i = 0; i < nFrames; i++) { /* for each frame file */ - frame = (Frame) frames.elementAt(i); - group = (Group) groups.elementAt(frame.group); - - if (!frame.marked) { - Debug.error(frame.filename + ": not in a boundary rect??"); - // continue; - } - - /* NEW, DKS: +1 removed so range is [0,n]: */ - fout.writeShort(frame.group); /* Boundary rect. rec. # */ - - /* Frame location ROW number */ - /* - * DKS. Changed from top to bottom to fix bug in Theron's frame - * numbering - */ - /* - * Should start numbering at BOTTOM (southern-most part) of - * group - */ - /* !!! Changed back so row num is never <= 0 */ - /* Alternative is bottom-y, not y-bottom. Try later */ - /* - * us = frames[i].y - groups[frames[i].group].bottom + 1; - */ - /* NEW, DKS: START AT 0, NOT 1: REMOVE "+ 1": */ - /* us = frames[i].y - groups[frames[i].group].top; */ - - /* - * SMN The frames number are from the bottom left not top left - */ - us = (short) (group.bottom - frame.y - 1); - - if (Debug.debugging("maketocframedetail")) { - Debug.output("iframe: " + i + ", frame.y: " + frame.y); - Debug.output("frame.group: " + frame.group); - Debug.output("group.bottom:" + group.bottom); - Debug.output("group.top:" + group.top); - Debug.output("frame row #:" + us); - } - - fout.writeShort(us); - - /* Frame location Column number */ - /* NEW, DKS: START AT 0, NOT 1: REMOVE "+ 1": */ - fout.writeShort((short) (frame.x - group.left)); - - /* pathname record offset: */ - /* - * DKS 11/10: Now w.r.t. frame file index table subsection - */ - /* - * ui = head.HEADER_SECTION_LENGTH + Loc_sec_len + Bound_sec_len - * + Frame_hdr_len + nFrames*Frame_index_rec_len + - * pathname_pos[i] ; - */ - fout.writeInt((int) (nFrames * Frame_index_rec_len + pathname_pos[i])); - - String framename; - tail = frame.filename.lastIndexOf(File.separatorChar); - if (tail == -1) { - framename = frame.filename; - } else { - framename = frame.filename.substring(++tail); - } - if (framename.length() > 12) { - Debug.error("MakeToc: encountered a frame name that's too long!\n" + framename); - framename = framename.substring(0, 12); - } - - /* frame file name */ - fout.writeBytes(framename); - - String seriesCode = framename.substring(9, 11); - - /* Check for Overview image: affects GEOREF */ - if (!seriesCode.equalsIgnoreCase("OV") && !seriesCode.equalsIgnoreCase("LG") - && !seriesCode.equalsIgnoreCase("OI")) { - /* Not Overview or Lengend img */ - /* DKS 8/1/94: handle polar zone separately */ - if (frame.zone != '9' - || frame.zone != 'J') { /* - * polar zone - */ - georef = latlong2GEOREF(frame.swlat, frame.swlon); - } else { /* not polar */ - georef = latlong2GEOREF(frame.bottom, frame.left); - } /* else */ - - } else { /* Overview image has no GEOREF */ - if (Debug.debugging("maketoc")) - Debug.output("Overview image has no GEOREF"); - georef = "000000"; - } /* else */ - - fout.writeBytes(georef); - - /* classification */ - // HACK - assumes unclassified data. - fout.writeBytes(charString); - - fout.writeBytes(head.country); - fout.writeBytes(head.release); - } /* for i (each frame file) */ - - Debug.message("maketoc", "MakeToc: *** writing directory section ***"); - - /* Pathname table */ - /* - * Write UNIQUE pathnames: really Directory name, e.g. - * "./CENTRAL.USA/" - */ - for (j = 0; j < uniq_dir_cnt; j++) { - /* DKS new */ - /* - * write pathname length. !!?? may be padded in front to align - * on word boundary!!?? - */ - fout.writeShort((short) (uniq_dir[j].length())); - - /* pathname */ - fout.writeBytes(uniq_dir[j]); - } /* for j (each uniq directory) */ - - /* No color table index section */ - - /* - * Go back and fill in component aggregate length in location - * section - */ - fout.seek(agg_loc); - fout.writeInt((int) (Bound_sec_len + Frame_sec_len)); - - fout.close(); - Debug.message("maketoc", "MakeToc: *** Normal end of make-toc ***"); - - } catch (IOException ioe) { - throw new MakeTocException(ioe.getMessage()); - } - - } /* main */ - - /** - * Take the Vector of frames, and group them into boundary rectangles, - * represented by groups. If Dchum is present, all frames get placed in - * their own group. - * - * @param frames - * the frame Vector. - * @param groups - * the group Vector. - * @param isDchum - * flag to note if Dchum frames are present. - */ - protected void groupFrames(Vector frames, Vector groups, boolean isDchum) throws MakeTocException { - - Frame frame; - Group group; - int groupCount; - - int nFrames = frames.size(); - Debug.message("maketoc", "MakeToc: *** grouping frames ***"); - - /* For each frame file */ - for (int i = 0; i < nFrames; i++) { - Debug.message("maketocdetail", "MakeToc: group addition, starting outer loop"); - - // Assuming that the vector objects are in the same order - // as initially loaded. - frame = (Frame) frames.elementAt(i); - - if (!frame.marked) { - groupCount = groups.size(); - - group = new Group(); - - group.left = maxSide / 2; - group.right = group.left + 1; - group.top = maxSide / 2; - group.bottom = group.top + 1; - - group.horiz_pos[group.top] = frame.top; - group.horiz_pos[group.bottom] = frame.bottom; - group.vert_pos[group.left] = frame.left; - group.vert_pos[group.right] = frame.right; - - group.h_interval = frame.h_interval; - group.v_interval = frame.v_interval; - group.h_resolution = frame.h_resolution; - group.v_resolution = frame.v_resolution; - - group.scale = frame.scale; - group.zone = frame.zone; - group.cib = frame.cib; - group.cdted = frame.cdted; - - frame.x = group.left; - /* - * DKS. Changed from top to bottom to fix bug in Theron's frame - * numbering - */ - /* - * Should start numbering at BOTTOM (southern-most part) of - * group - */ - /* DKS. Switched back to fix row # <=0 bug */ - frame.y = group.top; - frame.group = groupCount; - frame.marked = true; - - Debug.message("maketocdetail", "Maketoc.groupFrames: created group " + groupCount + " for frame " + i - + ", - " + frame.filename + " checking other frames for neighbors"); - - /* - * If Dchum, create 1 group for each file. No need for call to - * "add". - */ - if (!isDchum) { - for (int j = 0; j < nFrames; j++) { - if (i == j) { - Debug.message("maketocdetail", "Maketoc.groupFrames: inner loop, i = j = " + i - + ", frame that created group added to group, expecting false return"); - continue; - } - Frame f = (Frame) frames.elementAt(j); - if (addFrameToGroup(group, f, groupCount)) { - Debug.message("maketocdetail", - "Maketoc.groupFrames: added frame " + j + " to group " + groupCount); - continue; - } - } - } - - Debug.message("maketocdetail", - "Maketoc.groupFrames: adding another group - " + groupCount + " *******************\n\n"); - - groups.add(group); - } /* if !frame.marked */ - - fireProgressUpdate(ProgressEvent.UPDATE, "Organizing frames", i, nFrames); - - } /* for (i = 0; i < nFrames; i++) */ - - if (Debug.debugging("maketoc")) { - Debug.output("MakeToc: Number of boundary rectangles (groups): " + groups.size()); - } - } - - /** - * Does the actual checking to see if the frame gets added to the group, by - * checking the frame's location with the group's current boundaries, and - * resizing the group boundary if the frame is touching it. Assumes - * everything has been allocated in the group and frame. Not prepared for - * either being null. - * - * @param grp - * the group - * @param frm - * the frame. - * @param index - * the group index, referring to it's position in the Group - * Vector. - */ - protected boolean addFrameToGroup(Group grp, Frame frm, int index) throws MakeTocException { - - int i; - int x; - int y; - - if (frm.scale == null || grp.scale == null) { - // This is a strange situation. The product codes in the file name - // or header aren't resolving into a scale. - - // if these aren't set up properly, then other parameters aren't set - // up properly either. - Debug.output("grp and frm scale is null for " + frm.filename + ", skipping"); - return false; - } else if (frm.marked || !frm.scale.equalsIgnoreCase(grp.scale) || frm.zone != grp.zone) { - Debug.message("maketocframedetail", - "\nMakeToc.addFrameToGroup: no action needed for frame, returning.\n frm.marked = " + frm.marked - + "\n frm.zone(" + frm.zone + ") = grp.zone(" + grp.zone + ")\n frm.scale(" + frm.scale - + ") = grp.scale(" + grp.scale + ")\n"); - return false; - } - - Debug.message("maketocframedetail", "MakeToc.addFrameToGroup: adding unmarked frame"); - - double eps = frm.EPS(); - - /* DKS. EPS TOLERANCE ADDED throughout */ - if (frm.left >= grp.vert_pos[grp.left] - eps && frm.right <= grp.vert_pos[grp.right] + eps - && frm.bottom >= grp.horiz_pos[grp.bottom] - eps && frm.top <= grp.horiz_pos[grp.top] + eps) { - - if (Debug.debugging("maketocdetail")) { - Debug.output(frm.filename + " is in group " + index); - } - - } else if (near(frm.right, grp.vert_pos[grp.left], eps) && frm.top <= grp.horiz_pos[grp.top] + eps - && frm.bottom >= grp.horiz_pos[grp.bottom] - eps) { - - if (Debug.debugging("maketocdetail")) { - Debug.output(frm.filename + " add frame to group " + index + ": left side"); - } - - if (grp.left == 0) { - throw new MakeTocException( - "Boundary rectangle too small - Increase the boundary size to be larger than " + maxSide); - } - - grp.left--; /* add to left side */ - grp.vert_pos[grp.left] = frm.left; - } else if (near(frm.left, grp.vert_pos[grp.right], eps) && frm.top <= grp.horiz_pos[grp.top] + eps - && frm.bottom >= grp.horiz_pos[grp.bottom] - eps) { - - if (Debug.debugging("maketocdetail")) { - Debug.output(frm.filename + ":add frame to group " + index + ": right side"); - } - - if (grp.right == maxSide) { - throw new MakeTocException( - "Boundary rectangle too small - Increase the boundary size to be larger than " + maxSide); - } - - grp.vert_pos[grp.right] = frm.left; - grp.right++; /* add to right */ - grp.vert_pos[grp.right] = frm.right; - - } else if (near(frm.bottom, grp.horiz_pos[grp.top], eps) && frm.right <= grp.vert_pos[grp.right] + eps - && frm.left >= grp.vert_pos[grp.left] - eps) { - - if (Debug.debugging("maketocdetail")) { - Debug.output(frm.filename + ":add frame to group " + index + ": top"); - } - - if (grp.top == 0) { - throw new MakeTocException( - "Boundary rectangle too small - Increase the boundary size to be larger than " + maxSide); - } - - grp.top--; /* add to top */ - grp.horiz_pos[grp.top] = frm.top; - } else if (near(frm.top, grp.horiz_pos[grp.bottom], eps) && frm.right <= grp.vert_pos[grp.right] + eps - && frm.left >= grp.vert_pos[grp.left] - eps) { - - if (Debug.debugging("maketocdetail")) { - Debug.output(frm.filename + ":add frame to group " + index + ": bottom"); - } - - if (grp.bottom == maxSide) { - throw new MakeTocException( - "Boundary rectangle too small - Increase the boundary size to be larger than " + maxSide); - } - - grp.horiz_pos[grp.bottom] = frm.top; - grp.bottom++; /* add to bottom */ - grp.horiz_pos[grp.bottom] = frm.bottom; - } else { - Debug.message("maketocframedetail", - "MakeToc.add: frame not close enough to anything else, not adding to group."); - return false; - } - - x = y = -1; - for (i = grp.left; i < grp.right; i++) { - /* - * PBF - Change from (==) to near function for polar 6-19-94 - */ - if (near(frm.left, grp.vert_pos[i], eps)) { - x = i; - break; - } - } - - for (i = grp.top; i < grp.bottom; i++) { - /* - * PBF - Change from (==) to near function for polar 6-19-94 - */ - if (near(frm.top, grp.horiz_pos[i], eps)) { - y = i; - break; - } - } - - if (x < 0 || y < 0) { - Debug.output("MakeToc: " + frm.filename + ": in rect but can't find boundary (horizontal" - + (x < 0 ? " bad" : " OK") + ", vertical" + (y < 0 ? " bad)" : " OK)")); - - if (Debug.debugging("maketocframedetail")) { - - Debug.output(" - For frame: \n " + frm.toString()); - - Debug.output(" - Group horizontal left: " + grp.left + " vs. right: " + grp.right); - - for (i = grp.left; i < grp.right; i++) { - /* - * PBF - Change from (==) to near function for polar 6-19-94 - */ - Debug.output(" - Checking horizontal: " + frm.left + " <-> " + grp.vert_pos[i]); - if (near(frm.left, grp.vert_pos[i], eps)) { - Debug.output(" Last one should have hit."); - } - } - - Debug.output(" - Group vertical top: " + grp.horiz_pos[grp.top] + " vs. bottom: " - + grp.horiz_pos[grp.bottom] + ", frame top = " + frm.top + " and frame bottom = " + frm.bottom); - - for (i = grp.top; i < grp.bottom; i++) { - /* - * PBF - Change from (==) to near function for polar 6-19-94 - */ - Debug.output(" - Checking vertical: " + frm.top + " <-> " + grp.horiz_pos[i]); - if (near(frm.top, grp.horiz_pos[i], eps)) { - Debug.output(" Last one should have hit."); - } - } - } - - throw new MakeTocException(frm.filename + " in rect but can't find boundary (horizontal" - + (x < 0 ? " bad" : " OK") + ", vertical" + (y < 0 ? " bad)" : " OK)")); - } - - /* DKS ABS, frm.EPS2 added */ - /* - * DKS 8/16/94: h_resolution (meters/pix) will vary from frame to frame - * NS - */ - /* Therefore don't check for a match here */ - if (Math.abs(frm.h_interval - grp.h_interval) > EPS2 || Math - .abs(frm.v_interval - grp.v_interval) > EPS2) /* - * deg / pix - */ - /* - * Math.abs (frm.h_resolution - grp.h_resolution) > EPS2 || Math.abs - * (frm.v_resolution - grp.v_resolution) > EPS2) - */ - { - Debug.error(frm.filename + ": interval mismatch\n frm.h_interval: " + frm.h_interval + ", grp.h_interval:" - + grp.h_interval + "\n frm.v_interval: " + frm.v_interval + ", grp.v_interval: " + grp.v_interval - + "\n frm.h_resolution: " + frm.h_resolution + ", grp.h_resolution: " + grp.h_resolution - + "\n frm.h_resolution: " + frm.h_resolution + ", grp.h_resolution: " + grp.h_resolution); - throw new MakeTocException(frm.filename + " has mismatched frame resolution"); - } - - frm.marked = true; - frm.group = index; - frm.x = x; - frm.y = y; - grp.cib = frm.cib; - grp.cdted = frm.cdted; - return true; - } /* add */ - - /** - * This program attempts to convert latitudes and longitudes given in a - * decimal format into a GEOREF alphanumeric designation code. The first - * letter of the code denotes the longitudinal 15 degree grid that contains - * the area of interest. The second letter denotes the latitudinal 15 degree - * grid. The third letter denotes the one degree longitudinal grid within - * the 15 degree longitudinal grid. The fourth letter denotes the one degree - * latitudinal grid within the 15 degree latitudinal grid. The fifth - * character is a number denoting the minutes longitudinally to the nearest - * 10. The sixth number denotes the minutes latitudinally to the nearest 10. - * Wouldn't it just have been easier to use the decimal latitudes and - * longitudes? - */ - protected String latlong2GEOREF(double latitude, double longitude) { - int i; - char tmp = 'A'; // no reason for 'A' - char tmp1 = 'A'; - char tmp2 = 'A'; - - // These serve as tmps in integer form. - int tmpi, tmpi1, tmpi2; - - /* - * this portion of the code calculates the longitudinal part of the - */ - /* - * GEOREF number. I can't explain the logic -- I don't understand - */ - /* how it works. All that I know is that it seems to. */ - LatLonPoint llp = new LatLonPoint.Double(latitude, longitude); - DMSLatLonPoint dmsp = new DMSLatLonPoint(llp); - - char[] GEOSTRING = new char[6]; - - if (longitude == 0.0000) { - tmp = 'N'; - tmp1 = 'A'; - tmp2 = '0'; - } else if (longitude == -180.0000) { - tmp = 'A'; - tmp1 = 'A'; - tmp2 = '0'; - } else if (longitude == 180.0000) { - tmp = 'Z'; - tmp1 = 'Q'; - tmp2 = '9'; - } else if (longitude > 0.0000) { - tmpi = dmsp.lon_degrees / 15; - tmpi += 78; - if (tmpi >= 79) { - tmpi += 1; - } - if (tmpi > 90) { - tmpi = 90; - } - tmp = (char) tmpi; - - // Setting i to a certain value, based on longitude. - for (i = 0; i * 15 < (int) (longitude + 0.9999); i++) { - } - tmpi1 = 15 * i - (int) (longitude); - if ((tmpi1 >= 3) && (tmpi1 < 8)) { - tmpi1 += 1; - } else if (tmpi1 >= 8) { - tmpi1 += 2; - } - - if (tmpi1 != 0) { - tmpi1 = 82 - tmpi1; - tmp1 = (char) tmpi1; - } else { - tmp1 = 'A'; - } - if (tmp1 == 'R') { - tmp1 = 'A'; - } - tmpi2 = (int) ('0') + (dmsp.lon_minutes / 10); - tmp2 = (char) tmpi2; - - } else if (longitude <= 0.0000) { - - tmpi = (int) (((double) dmsp.lon_degrees) / 15.0 - 0.999); - tmpi = 77 - Math.abs(tmpi); - if (tmpi >= 73) { - tmpi += 1; - } - if (tmpi > 77) { - tmpi = 77; - } - tmp = (char) tmpi; - - /* DKS changed from abs to fabs */ - for (i = 0; i * 15 < (int) (Math.abs((longitude - 0.9999))); i++) { - } - /* DKS changed from abs to fabs */ - tmpi1 = i * 15 - (int) (Math.abs((longitude - 0.9999))); - if ((tmpi1 >= 8) && (tmpi1 < 13)) { - tmpi1 += 1; - } else if (tmpi1 >= 13) { - tmpi1 += 2; - } - if (tmpi1 > 16) { - tmpi1 = 16; - } - tmpi1 += 65; - tmp1 = (char) tmpi1; - - if ((int) (dmsp.lon_minutes / 10) != 0) { - tmpi2 = ((int) '0') + (6 - (int) (dmsp.lon_minutes / 10)); - tmp2 = (char) tmpi2; - } else { - tmp2 = '0'; - } - } - - GEOSTRING[0] = tmp; - GEOSTRING[2] = tmp1; - GEOSTRING[4] = tmp2; - - /* - * this portion of the code calculates the latitudinal part of the - */ - /* - * GEOREF number. I can't explain the logic -- I don't understand - */ - /* how it works. All that I know is that it seems to. */ - - if (latitude == 0.0000) { - tmp = 'G'; - tmp1 = 'A'; - tmp2 = '0'; - } else if (latitude == 90.0000) { - tmp = 'M'; - tmp1 = 'Q'; - tmp2 = '9'; - } else if (latitude == -90.0000) { - tmp = 'A'; - tmp1 = 'A'; - tmp2 = '0'; - } else if (latitude > 0.0000) { - tmpi = dmsp.lat_degrees / 15; - tmpi += 71; - if (tmpi >= 73) { - tmpi += 1; - } - if (tmpi > 77) { - tmpi = 77; - } - tmp = (char) tmpi; - - for (i = 0; i * 15 < (int) (latitude + 0.9999); i++) { - } - tmpi1 = 15 * i - (int) (latitude); - if ((tmpi1 >= 3) && (tmpi1 < 8)) { - tmpi1 += 1; - } else if (tmpi1 >= 8) { - tmpi1 += 2; - } - tmpi1 = 82 - tmpi1; - tmp1 = (char) tmpi1; - - if (tmp1 == 'R') { - tmp1 = 'A'; - } - if ((dmsp.lat_minutes / 10) != 0) { - tmpi2 = ((int) '0') + (int) (dmsp.lat_minutes / 10); - tmp2 = (char) tmpi2; - } else { - tmp2 = '0'; - } - - } else if (latitude < 0.0000) { - - tmpi = (int) ((double) dmsp.lat_degrees / 15.0 - 0.999); - tmpi = 71 - Math.abs(tmpi); - if (tmpi < 65) { - tmpi = 65; - } - /* DKS changed from abs to fabs */ - for (i = 0; i * 15 < (int) (Math.abs((latitude - 0.9999))); i++) { - } - /* DKS changed from abs to fabs */ - tmpi1 = i * 15 - (int) (Math.abs((latitude - 0.9999))); - if ((tmpi1 >= 8) && (tmpi1 < 13)) { - tmpi1 += 1; - } else if (tmpi1 >= 13) { - tmpi1 += 2; - } - if (tmpi1 > 16) { - tmpi1 = 16; - } - tmpi1 = 65 + tmpi1; - tmp1 = (char) tmpi1; - - tmpi2 = ((int) '0') + (6 - (int) (dmsp.lat_minutes / 10)); - tmp2 = (char) tmpi2; - } - - GEOSTRING[1] = tmp; - GEOSTRING[3] = tmp1; - GEOSTRING[5] = tmp2; - - String ret = new String(GEOSTRING); - if (Debug.debugging("maketocdetail")) { - Debug.output("latlon2GEOREF: lat = " + latitude + ", lon = " + longitude + ", GEOREF = " + ret); - } - - return ret; - } /* latlong2GEOREF() */ - - public String createPadding(int length, boolean nullTerminated) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < length; i++) { - if (i == length - 1 && nullTerminated) { - sb.append("/0"); - } else { - sb.append(" "); - } - } - return sb.toString(); - } - - /** - * Add a ProgressListener that will display build progress. - */ - public void addProgressListener(ProgressListener list) { - progressSupport.add(list); - } - - /** - * Remove a ProgressListener that displayed build progress. - */ - public void removeProgressListener(ProgressListener list) { - progressSupport.remove(list); - } - - /** - * Clear all progress listeners. - */ - public void clearProgressListeners() { - progressSupport.clear(); - } - - /** - * Fire an build update to progress listeners. - * - * @param frameNumber - * the current frame count - * @param totalFrames - * the total number of frames. - */ - protected void fireProgressUpdate(int type, String task, int frameNumber, int totalFrames) { - progressSupport.fireUpdate(type, task, totalFrames, frameNumber); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeTocException.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeTocException.java deleted file mode 100644 index 538d06b3e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/MakeTocException.java +++ /dev/null @@ -1,40 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/MakeTocException.java,v $ -// $RCSfile: MakeTocException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -/** - * An exception that gets thrown if there is a problem with the A.TOC - * file is getting created from MakeToc. - */ -public class MakeTocException extends Exception { - - private static final long serialVersionUID = 1L; - - public MakeTocException() { - super(); - } - - public MakeTocException(String statement) { - super(statement); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfAttributes.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfAttributes.java deleted file mode 100644 index e18e293d9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfAttributes.java +++ /dev/null @@ -1,442 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfAttributes.java,v $ -// $RCSfile: RpfAttributes.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/07/21 03:41:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * This class knows how to read the attribute section of an RPF file. - * This section includes all the information about the image, - * including source and production information. - */ -public class RpfAttributes { - - public String currencyDate;// [8]; - public String productionDate; // [8]; - public String significantDate; // [8]; - public String chartSeriesCode; // [10]; - public String mapDesignationCode; // [8]; - public String oldHorDatum; // [4]; - public String edition; // [7]; - public String projectionCode; // [2]; - public float projectionA; - public float projectionB; - public float projectionC; - public float projectionD; - public String vertDatumCode; // [4]; - public String horDatumCode; // [4]; - public long vertAbsAccuracy; //uint - public int vertAbsUnits; //ushort - public long horAbsAccuracy; //uint - public int horAbsUnits; // ushort - public long vertRelAccuracy; //uint - public int vertRelUnits; // ushort - public long horRelAccuracy; //uint - public int horRelUnits; // ushort - public String ellipsoidCode; // [3]; - public String soundingDatumCode; // [4]; - public int navSystemCode; // ushort - public String gridCode; // [2]; - public float eMagChange; - public int eMagChangeUnits; // ushort - public float wMagChange; - public int wMagChangeUnits; // ushort - public float magAngle; //uint - public int magAngleUnits; // ushort - public float gridConver; //uint - public int gridConverUnits; // ushort - public double highElevation; - public int highElevationUnits; // ushort - public double highLat; - public double highLon; - public String legendFileName; // [12]; - public String dataSource; // [12]; - public long gsd; // uint - public int dataLevel; // ushort - - public RpfAttributes() {} - - /** - * Read the section in a file. The method will start reading from - * the offset provided. - * - * @param binFile the opened RPF file. - * @param attributeLocation the offset of the attribute section in - * the file. - */ - public boolean read(BinaryFile binFile, long attributeLocation) { - - try { - - long k; - long j = 0; - - AttributeSubheader attributeSubheader = new AttributeSubheader(); - // AttributeOffsetRecord attributeOffsetRecord = new - // AttributeOffsetRecord(); - AttributeOffsetRecord attributeOffsetRecord; - - binFile.seek(attributeLocation); - attributeSubheader.read(binFile); - - if (Debug.debugging("rpfdetail")) { - System.out.println(attributeSubheader); - } - - AttributeOffsetRecord[] attributeOffsetRecords = new AttributeOffsetRecord[attributeSubheader.numAttributes]; - - int i = attributeSubheader.numAttributes - 1; - - // OK, I know what you are thinking - two sequential - // loops? It's an optimization for the binFile, - // especially if we're reading from a URL - turns this - // into a couple of sequential reads. - - j = 0; - for (int attIndex = attributeSubheader.numAttributes; attIndex > 0; attIndex--) { - i = attIndex - 1; - k = attributeLocation - + 10/* sizeof(attribute_subheader) */ - + attributeSubheader.tableOffset - + ((attributeSubheader.numAttributes - attIndex) * 8/* sizeof(attributeOffsetRecord */); - - binFile.seek(k); - - attributeOffsetRecords[i] = new AttributeOffsetRecord(); - attributeOffsetRecords[i].read(binFile); - - if (Debug.debugging("rpfdetail")) { - Debug.output(" ##" + (++j) + " at " + k + " => attrib ID '" - + attributeOffsetRecords[i].attributeId - + "'|Param ID '" - + attributeOffsetRecords[i].parameterId - + "'|offset '" + attributeOffsetRecords[i].offset - + "'"); - } - } - - for (i = attributeOffsetRecords.length - 1; i >= 0; i--) { - - attributeOffsetRecord = attributeOffsetRecords[i]; - - binFile.seek(attributeLocation + 10 - + attributeOffsetRecord.offset); - switch (attributeOffsetRecord.attributeId) { - case 1: - currencyDate = binFile.readFixedLengthString(8);// [8]; - break; - case 2: - productionDate = binFile.readFixedLengthString(8); // [8]; - break; - case 3: - significantDate = binFile.readFixedLengthString(8); // [8]; - break; - case 4: - if ((int) attributeOffsetRecord.parameterId == 1) - chartSeriesCode = binFile.readFixedLengthString(10); // [10]; - else if ((int) attributeOffsetRecord.parameterId == 2) - mapDesignationCode = binFile.readFixedLengthString(8); // [8]; - else if ((int) attributeOffsetRecord.parameterId == 3) - oldHorDatum = binFile.readFixedLengthString(4); // [4]; - else if ((int) attributeOffsetRecord.parameterId == 4) - edition = binFile.readFixedLengthString(7); // [7]; - break; - case 5: - if ((int) attributeOffsetRecord.parameterId == 1) - projectionCode = binFile.readFixedLengthString(2); // [2]; - else if ((int) attributeOffsetRecord.parameterId == 2) - projectionA = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 3) - projectionB = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 4) - projectionC = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 5) - projectionD = binFile.readFloat(); - break; - case 6: - vertDatumCode = binFile.readFixedLengthString(4); // [4]; - break; - case 7: - horDatumCode = binFile.readFixedLengthString(4); // [4]; - break; - case 8: - if ((int) attributeOffsetRecord.parameterId == 1) - vertAbsAccuracy = (long) binFile.readInteger(); - else if ((int) attributeOffsetRecord.parameterId == 2) - vertAbsUnits = (int) binFile.readShort(); //ushort - break; - case 9: - if ((int) attributeOffsetRecord.parameterId == 1) - horAbsAccuracy = (long) binFile.readInteger(); - else if ((int) attributeOffsetRecord.parameterId == 2) - horAbsUnits = (int) binFile.readShort(); // ushort - break; - case 10: - if ((int) attributeOffsetRecord.parameterId == 1) - vertRelAccuracy = (long) binFile.readInteger(); - else if ((int) attributeOffsetRecord.parameterId == 2) - vertRelUnits = (int) binFile.readShort(); // ushort - break; - case 11: - if ((int) attributeOffsetRecord.parameterId == 1) - horRelAccuracy = (long) binFile.readInteger(); - else if ((int) attributeOffsetRecord.parameterId == 2) - horRelUnits = (int) binFile.readShort(); // ushort - break; - case 12: - ellipsoidCode = binFile.readFixedLengthString(3); // [3]; - break; - case 13: - soundingDatumCode = binFile.readFixedLengthString(4); // [4]; - break; - case 14: - navSystemCode = (int) binFile.readShort(); // ushort - break; - case 15: - gridCode = binFile.readFixedLengthString(2); // [2]; - break; - case 16: - if ((int) attributeOffsetRecord.parameterId == 1) - eMagChange = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 2) - eMagChangeUnits = (int) binFile.readShort(); // ushort - break; - case 17: - if ((int) attributeOffsetRecord.parameterId == 1) - wMagChange = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 2) - wMagChangeUnits = (int) binFile.readShort(); // ushort - break; - case 18: - if ((int) attributeOffsetRecord.parameterId == 1) - magAngle = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 2) - magAngleUnits = (int) binFile.readShort(); // ushort - break; - case 19: - if ((int) attributeOffsetRecord.parameterId == 1) - gridConver = binFile.readFloat(); - else if ((int) attributeOffsetRecord.parameterId == 2) - gridConverUnits = (int) binFile.readShort(); // ushort - break; - case 20: - if ((int) attributeOffsetRecord.parameterId == 1) - highElevation = binFile.readDouble(); - else if ((int) attributeOffsetRecord.parameterId == 2) - highElevationUnits = (int) binFile.readShort(); // ushort - else if ((int) attributeOffsetRecord.parameterId == 3) - highLat = binFile.readDouble(); - else if ((int) attributeOffsetRecord.parameterId == 4) - highLon = binFile.readDouble(); - break; - case 21: - legendFileName = binFile.readFixedLengthString(12); // [12]; - break; - case 22: - if ((int) attributeOffsetRecord.parameterId == 1) - dataSource = binFile.readFixedLengthString(12); // [12]; - else if ((int) attributeOffsetRecord.parameterId == 2) - gsd = (long) binFile.readInteger(); // uint - break; - case 23: - dataLevel = (int) binFile.readShort(); // ushort - break; - } - } - - } catch (IOException e) { - Debug.error("RpfAttributes: read(): File IO Error!\n" + e); - return false; - } catch (FormatException f) { - Debug.error("RpfAttributes: read(): File IO Format error!\n" + f); - return false; - } - - return true; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Attribute Section:\n"); - s.append(" currency date = ").append(currencyDate).append("\n"); - s.append(" production date = ").append(productionDate).append("\n"); - s.append(" significant date = ").append(significantDate).append("\n"); - s.append(" chart series code = ").append(chartSeriesCode).append("\n"); - s.append(" map designation code = ").append(mapDesignationCode).append("\n"); - s.append(" old horizontal datum = ").append(oldHorDatum).append("\n"); - s.append(" edition = ").append(edition).append("\n"); - s.append(" projection code = ").append(projectionCode).append("\n"); - s.append(" projection A = ").append(projectionA).append("\n"); - s.append(" projection B = ").append(projectionB).append("\n"); - s.append(" projection C = ").append(projectionC).append("\n"); - s.append(" projection D = ").append(projectionD).append("\n"); - s.append(" vertical datum code = ").append(vertDatumCode).append("\n"); - s.append(" horizontal datum code = ").append(horDatumCode).append("\n"); - s.append(" vertical absolute accuracy = ").append(vertAbsAccuracy).append("\n"); - s.append(" vertical absolute units = ").append(vertAbsUnits).append("\n"); - s.append(" horizontal absolute accuracy = ").append(horAbsAccuracy).append("\n"); - s.append(" horizontal absolute units = ").append(horAbsUnits).append("\n"); - s.append(" vertical relative accuracy = ").append(vertRelAccuracy).append("\n"); - s.append(" vertical relative units = ").append(vertRelUnits).append("\n"); - s.append(" horizontal relative accuracy = ").append(horRelAccuracy).append("\n"); - s.append(" horizontal relative units = ").append(horRelUnits).append("\n"); - s.append(" ellipsoid code = ").append(ellipsoidCode).append("\n"); - s.append(" sounding datum code = ").append(soundingDatumCode).append("\n"); - s.append(" nav system code = ").append(navSystemCode).append("\n"); - s.append(" grid code = ").append(gridCode).append("\n"); - s.append(" east mag change = ").append(eMagChange).append("\n"); - s.append(" east mag change units = ").append(eMagChangeUnits).append("\n"); - s.append(" west mag change = ").append(wMagChange).append("\n"); - s.append(" west mag units = ").append(wMagChangeUnits).append("\n"); - s.append(" magnetic angle = ").append(magAngle).append("\n"); - s.append(" magnetic angle units = ").append(magAngleUnits).append("\n"); - s.append(" grid conversion = ").append(gridConver).append("\n"); - s.append(" grid conversion units = ").append(gridConverUnits).append("\n"); - s.append(" high elevation = ").append(highElevation).append("\n"); - s.append(" high elevation units = ").append(highElevationUnits).append("\n"); - s.append(" high latitude = ").append(highLat).append("\n"); - s.append(" high longitude = ").append(highLon).append("\n"); - s.append(" legend file name = ").append(legendFileName).append("\n"); - s.append(" data source = ").append(dataSource).append("\n"); - s.append(" gsd = ").append(gsd).append("\n"); - s.append(" data level = ").append(dataLevel).append("\n"); - return s.toString(); - } - - /** - * Get the attributes from within a RPF Frame file. Returns null - * if something goes wrong. You do need to make sure that the - * Debug class is initialized before calling this class. For - * OpenMap, it usually is. - * - * @param filename the file path for the RPF frame file. - * @return a RpfAttributes object. - */ - public static RpfAttributes getAttributes(String filename) - throws IOException, FileNotFoundException { - - BinaryFile binFile = new BinaryBufferedFile(filename); - - RpfHeader head = new RpfHeader(); - head.read(binFile); - - RpfAttributes att = getAttributes(binFile); - binFile.close(); - head = null; - return att; - } - - /** - * Get the attributes from within a RPF Frame file, after the - * header has been read. Returns null if something goes wrong. You - * do need to make sure that the Debug class is initialized before - * calling this class. For OpenMap, it usually is. - * - * @param binFile BinaryFile. - * @return a RpfAttributes object. - */ - public static RpfAttributes getAttributes(BinaryFile binFile) - throws IOException, FileNotFoundException { - RpfFileSections rfs = new RpfFileSections(binFile); - RpfAttributes att = rfs.parseAttributes(binFile); - return att; - } - - public static void main(String[] args) { - if (args.length != 1) { - System.out.println("Usage: java RpfAttributes "); - return; - } - - Debug.init(System.getProperties()); - try { - RpfAttributes att = RpfAttributes.getAttributes(args[0]); - Debug.output(att.toString()); - } catch (FileNotFoundException e) { - Debug.error("RpfAttributes: file " + args[0] + " not found"); - } catch (IOException ioe) { - Debug.error("RpfAttributes: File IO Error while handling attributes: \n" - + ioe); - } - } - - static public class AttributeSubheader { - int numAttributes; //ushort - int numArealRecords; // ushort - long tableOffset; // ulong - int offsetRecordLength; // ushort - - public void read(BinaryFile binFile) { - try { - numAttributes = (int) binFile.readShort(); - numArealRecords = (int) binFile.readShort(); - tableOffset = (long) binFile.readInteger(); - offsetRecordLength = (int) binFile.readShort(); - } catch (IOException e) { - Debug.error("AttributeSubheader: read(): File IO Error!\n" + e); - } catch (FormatException f) { - Debug.error("AttributeSubheader: read(): File IO Format error!\n" - + f); - } - - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("## RPF ATTRIBUTE INFORMATION\n"); - s.append("Number of Attributes - ").append(numAttributes).append("\n"); - s.append("Number of Areal Records - ").append(numArealRecords).append("\n"); - s.append("Size of offset - ").append(tableOffset).append("\n"); - s.append("Record Length - ").append(offsetRecordLength).append("\n"); - return s.toString(); - } - } - - static public class AttributeOffsetRecord { - int attributeId; // ushort - int parameterId; //char - int sequenceNum; //char - long offset; //ulong - - public void read(BinaryFile binFile) { - try { - attributeId = (int) binFile.readShort(); - parameterId = binFile.read(); - sequenceNum = binFile.read(); - offset = (long) binFile.readInteger(); - } catch (IOException e) { - Debug.error("AttributeOffsetRecord: read(): File IO Error!\n" - + e); - } catch (FormatException f) { - Debug.error("AttributeOffsetRecord: read(): File IO Format error!\n" - + f); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheHandler.java deleted file mode 100644 index 5a97db450..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheHandler.java +++ /dev/null @@ -1,886 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCacheHandler.java,v $ -// $RCSfile: RpfCacheHandler.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/10/04 14:46:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/** - * Modifications : - * - * 1. Changed getSubframeFromOtherTOC(): changed offsets and prevent caching - * from other TOCs - */ - -/* - * Some of the ideas for this code is based on source code provided by - * The MITRE Corporation, through the browse application source code. - * Many thanks to Nancy Markuson who provided BBN with the software, - * and Theron Tock, who wrote the software, and to Daniel Scholten, - * who revised it - (c) 1994 The MITRE Corporation for those parts, - * and used/distributed with permission. Namely, the subframe caching - * mechanism is the part that has been modified. - */ -package com.bbn.openmap.layer.rpf; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The RpfCacheHandler handles everything to do with the decompressed subframes, - * which is what gets put up on the screen. It interfaces with the - * RpfFrameProvider to get the information about the data. It also is usually - * handled by the RpfCacheManager. - */ -public class RpfCacheHandler { - /* Lowered from 128 - used too much memory */ - public final static int SUBFRAME_CACHE_SIZE = 20; - /* # CHUM descriptor string */ - public final static int MAX_NUM_DESC = 20; - /* # CHUM descriptor string */ - public final static int MAX_DESC_LEN = 512; - public static final int DEFAULT_SUBFRAMEBUFFER = 5; - - /* DKS fix chum description problem : */ - /** subframe status constant. */ - public final static int NOT_CACHED = -1; - /** subframe status constant. */ - public final static int NOT_PRESENT = -2; - - /** Subframe scaling for map scales that don't match chart scale. */ - protected int scalingHeight = RpfSubframe.PIXEL_EDGE_SIZE; - /** Subframe scaling for map scales that don't match chart scale. */ - protected int scalingWidth = RpfSubframe.PIXEL_EDGE_SIZE; - /** The subframe cache. */ - protected SubframeCache cache; - /** - * The current description of the TOC entry that currently applies. - */ - protected List coverageBoxes; - /** - * The array of indexes for subframes contained in the RpfTocEntry. - */ - protected byte[][] subframeIndex; - /** - * The array of version markers for subframes contained in the RpfTocEntry. - */ - protected byte[][] subframeVersion; - - /** The size of the subframe cache. */ - protected int subframeCacheSize = SUBFRAME_CACHE_SIZE; - /** - * Description of how the frames should be constructed and displayed. - */ - protected RpfViewAttributes viewAttributes; - /** The place to look for for image data. */ - protected RpfFrameProvider frameProvider; - /** The upper left subframe index on screen. */ - protected Point start = new Point(); - /** The lower right subframe index on screen. */ - protected Point end = new Point(); - /** - * A flag to let the cache manager know that the subframes needed for the - * map make sense. - */ - protected boolean goodData = false; - /** - * The subframe cache is mapped by a 2D matrix based on the number of - * subframes that will fit in the RpfCoverageBox area. The subframeBuffer is - * used to put additional subframe entries in the matrix, so that subframes - * retrieved outside of the RpfCoverageBox area can still be cached. The - * subframeBuffer refers to the number of subframes added on each side of - * the matrix. - */ - protected int subframeBuffer = DEFAULT_SUBFRAMEBUFFER; - - /** - * Used in setCache to see if new coverage is needed with a projection - * change. - */ - // private float lastScaleDifference = -1f; - - protected boolean DEBUG_RPF = false; - protected boolean DEBUG_RPFDETAIL = false; - - /** The entire subframe cache */ - static public class SubframeCache { - RpfSubframe[] subframe; - int LRU_head, LRU_tail; - - public SubframeCache(int numSubframes) { - subframe = new RpfSubframe[numSubframes]; - } - } - - /** - * Constructor for a main cache, with the full size cache. - */ - public RpfCacheHandler(RpfFrameProvider provider, RpfViewAttributes rva) { - this(provider, rva, SUBFRAME_CACHE_SIZE); - } - - /** - * Constructor for an auxiliary cache, with a settable cache size. - */ - public RpfCacheHandler(RpfFrameProvider provider, RpfViewAttributes rva, int subframe_cache_size) { - DEBUG_RPF = Debug.debugging("rpf"); - DEBUG_RPFDETAIL = Debug.debugging("rpfdetail"); - - frameProvider = provider; - viewAttributes = rva; - updateViewAttributes(); - - if (subframe_cache_size > Byte.MAX_VALUE) { - subframeCacheSize = Byte.MAX_VALUE; - } else if (subframe_cache_size >= 0) { - subframeCacheSize = subframe_cache_size; - } - - initCache(true); // subframe cache, and it's new - - if (DEBUG_RPF) { - Debug.output("RpfCacheHandler: Created with cache size of " + subframeCacheSize); - } - - } - - // public void finalize() { - // Debug.message("gc", "RpfCacheHandler: getting GC'd"); - // } - - /** - * Set the view attributes for the layer. The frame provider view attributes - * are updated, and the cache is cleared. - * - * @param rva the RpfViewAttributes used for the layer. - */ - public void setViewAttributes(RpfViewAttributes rva) { - viewAttributes = rva; - updateViewAttributes(); - clearCache(); - } - - /** - * Get the view attributes or the layer. - * - * @return RpfViewAttributes. - */ - public RpfViewAttributes getViewAttributes() { - if (viewAttributes == null) { - viewAttributes = new RpfViewAttributes(); - } - return viewAttributes; - } - - /** - * Set the RpfFrameProvider for the layer. Clears out the cache, and the - * frame provider gets the RpfViewAttributes held by the layer. - * - * @param fp the frame provider. - */ - public void setFrameProvider(RpfFrameProvider fp) { - frameProvider = fp; - if (frameProvider != null) { - frameProvider.setViewAttributes(getViewAttributes()); - } - clearCache(); - } - - /** - * Return RpfFrameProvider used by the layer. - */ - public RpfFrameProvider getFrameProvider() { - return frameProvider; - } - - /** - * This only needs to be called if the frame provider is not local. In that - * case, updates to the view attributes object will not be reflected on the - * server side. This will update the parameters. - */ - public void updateViewAttributes() { - if (frameProvider != null) { - frameProvider.setViewAttributes(getViewAttributes()); - } - } - - /** - * Returns the Vector containing RpfCoverageBoxes that was returned from the - * RpfFrameProvider as a result of the last setCache call. These provide - * rudimentary knowledge about what is being displayed. - * - * @return Vector of RpfCoverageBoxes. - */ - public List getCoverageBoxes() { - return coverageBoxes; - } - - /** - * Called to prepare the cache for subframes that will fit into the next - * request. The subframe entry from the TOC is known and tracked, and if it - * changes, the frame cache gets tossed and recreated via - * setScreenSubframes. - * - * @param ullat NW latitude. - * @param ullon NW longitude. - * @param lrlat SE latitude. - * @param lrlon SE longitude - * @param proj projection to use for zone decisions. - */ - public synchronized void setCache(float ullat, float ullon, float lrlat, float lrlon, - Projection proj) { - - if (DEBUG_RPF) { - Debug.output("RpfCacheHandler: Need new Coverage."); - } - - if (frameProvider != null) { - coverageBoxes = frameProvider.getCoverage(ullat, ullon, lrlat, lrlon, proj); - } else { - coverageBoxes = null; - } - - // See if anything came back... - if (coverageBoxes == null || coverageBoxes.isEmpty()) { - // Guess not. - goodData = false; - return; - } - - // The percent coverage should be greater than zero here. - // That should be checked by the RpfTocHandler. - - // Base the cache off the coverage in the first box. It's - // supposed to have the best coverage. - RpfCoverageBox currentBox = coverageBoxes.get(0); - - resetSubframeIndex(currentBox.verticalSubframes(), currentBox.horizontalSubframes()); - initCache(false); - - start = currentBox.startIndexes; - end = currentBox.endIndexes; - goodData = true; - - // Set the backup indexes, just in case. - for (int i = 1; i < coverageBoxes.size(); i++) { - coverageBoxes.get(i).setPercentCoverage(ullat, ullon, lrlat, lrlon); - } - - if (DEBUG_RPF) { - Debug.output("RpfCachehandler: ####################"); - Debug.output("" + currentBox); - Debug.output(" Starting point " + start); - Debug.output(" Ending point " + end); - } - - // Figure out how much to scale the cached images. This would - // be one of the big problems if we were going to merge - // different data types. - if (getViewAttributes().scaleImages) { - // Do the work for a great scaling factor here... - - // Need to figure how much this will change for this scale - // chart at this screen scale - // Reference at 0, 0 - Point2D refllpt = (Point2D) proj.getUpperLeft(); - refllpt.setLocation(refllpt.getX() + (float) currentBox.subframeLonInterval, refllpt.getY() - - (float) currentBox.subframeLatInterval); - - Point refpt = (Point) proj.forward(refllpt, new Point()); - - scalingWidth = refpt.x; - scalingHeight = refpt.y; - } else { - scalingWidth = RpfSubframe.PIXEL_EDGE_SIZE; - scalingHeight = RpfSubframe.PIXEL_EDGE_SIZE; - } - - } - - protected OMGraphicList getSubframes(float ullat, float ullon, float lrlat, float lrlon, - Projection proj, OMGraphicList omGraphics) { - setCache(ullat, ullon, lrlat, lrlon, proj); - - int subframeRunningCount = 0; - - if (omGraphics == null) { - omGraphics = new OMGraphicList(); - } - - for (int subx = start.x; subx <= end.x; subx++) { - for (int suby = start.y; suby <= end.y; suby++) { - - // ///// - RpfSubframe subframe = getCached(subx, suby, subframeRunningCount); - // ///// - - if (subframe == null) { - if (Debug.debugging("rpf")) { - Debug.output("RpfCacheManager: checking other TOCs for subframe."); - } - subframe = getSubframeFromOtherTOC(subx, suby, subframeRunningCount); - } - - if (subframe != null) { - OMGraphic image = subframe.getImage(proj); - if (image != null) { - image.setSelected(viewAttributes.showInfo); - omGraphics.add(image); - - if (Debug.debugging("rpf")) { - Debug.output("RpfCacheManager: Adding subframe " + subx + ", " + suby); - } - } - } else { - if (Debug.debugging("rpf")) { - Debug.output("RpfCacheManager: subframe " + subx + ", " + suby + " empty"); - } - } - - subframeRunningCount++; - } - } - - return omGraphics; - } - - /** - * Resets the indicators in the subframe cache, so that none of the current - * contents will be used - they'll have to be loaded with data first. The - * cache management is also set for the current main RpfCoverageBox. - */ - protected void resetSubframeIndex(int vertFrames, int horizFrames) { - - if (subframeCacheSize > 0) { - /* Allocate the indices into the subframe cache */ - int matrixheight = (vertFrames * 6) + (subframeBuffer * 2); - int matrixwidth = (horizFrames * 6) + (subframeBuffer * 2); - - subframeIndex = new byte[matrixheight][matrixwidth]; - subframeVersion = new byte[matrixheight][matrixwidth]; - clearCache(); - } else { - subframeIndex = null; - subframeVersion = null; - } - } - - /** - * Clear the subframes in the cache, marking them as NOT_CACHED. - */ - public void clearCache() { - if (subframeIndex != null && subframeVersion != null) { - /* Initialize the subframe indices */ - for (int i = 0; i < subframeIndex.length; i++) { - for (int j = 0; j < subframeIndex[0].length; j++) { - subframeIndex[i][j] = NOT_CACHED; - subframeVersion[i][j] = -1; - } - } - } - - // TODO see if this makes a difference - initCache(false); - } - - /** - * Return true if the cache handler knows about good data in the current - * situation. - */ - public boolean getGoodData() { - return goodData; - } - - // ///////////////////////////////////////////////////////// - // SUBFRAME CACHE HANDLING - // ///////////////////////////////////////////////////////// - - protected void initCache(boolean newCache) { - int i; - - // Don't have a cache. - if (subframeCacheSize <= 0) { - cache = null; - return; - } - - if (newCache || cache == null) { - cache = new SubframeCache(subframeCacheSize); - } - - cache.LRU_head = 0; - cache.LRU_tail = subframeCacheSize - 1; - - for (i = 0; i < subframeCacheSize; i++) { - if (newCache) { - try { - cache.subframe[i] = new RpfSubframe(); - } catch (java.lang.OutOfMemoryError oome) { - Debug.error("RpfCacheHandler: \n\tRan out of memory allocating the image cache.\tConsider increasing the java memory heap using the -Xmx option."); - - cache = null; - - subframeCacheSize = i; - if (DEBUG_RPF) { - Debug.output("RpfCacheHandler: resetting cache size to " - + subframeCacheSize); - } - initCache(true); - return; - } - } - - RpfSubframe subframe = cache.subframe[i]; - subframe.version = 0; - - // Here's where I messed up - forgot to hook up the ends - // of the chain... - if (i < subframeCacheSize - 1) { - subframe.nextSubframe = i + 1; - } else { - subframe.nextSubframe = 0; - } - if (i > 0) { - subframe.prevSubframe = i - 1; - } else { - subframe.prevSubframe = subframeCacheSize - 1; - } - } - } - - /** - * Get the index of the least recently used entry from the subframe cache. - */ - protected int getLRU() { - if (cache != null) { - return cache.LRU_tail; - } else { - return NOT_CACHED; - } - } - - protected void freeCache(int index) { - - if (cache == null) { - return; - } - - if (index == cache.LRU_tail) { - return; - } else if (index == cache.LRU_head) { - cache.LRU_head = cache.subframe[cache.LRU_head].nextSubframe; - } else { - int next = cache.subframe[index].nextSubframe; - int prev = cache.subframe[index].prevSubframe; - - cache.subframe[next].prevSubframe = prev; - cache.subframe[prev].nextSubframe = next; - } - - cache.subframe[cache.LRU_tail].nextSubframe = index; - cache.subframe[index].prevSubframe = cache.LRU_tail; - cache.LRU_tail = index; - } - - /** - * Mark a cache entry as being recently used. - */ - protected void referenceCache(int index) { - if (cache == null) { - return; - } - - /* First unlink the cache entry from the list */ - if (index == cache.LRU_head) { - return; - } else if (index == cache.LRU_tail) { - cache.LRU_tail = cache.subframe[cache.LRU_tail].prevSubframe; - } else { - int next = cache.subframe[index].nextSubframe; - int prev = cache.subframe[index].prevSubframe; - - cache.subframe[next].prevSubframe = prev; - cache.subframe[prev].nextSubframe = next; - } - - /* Now add the entry as the most recently referenced */ - cache.subframe[cache.LRU_head].prevSubframe = index; - cache.subframe[index].nextSubframe = cache.LRU_head; - cache.LRU_head = index; - } - - /** - * Find out the size of the subframe cache. From the start and end indexes, - * you can figure out the number of subframes the map needs. If that number - * is bigger than this cache size, you'll need to use the getCached that - * lets you supply the subframe number that you are requesting, so that the - * RpfCacheHandler knows when to stop caching subframes during a retrival.. - * Otherwise, the cache will overwrite data and subframes will not show up - * on the map. - */ - public int getCacheSize() { - return subframeCacheSize; - } - - /** - * Get a subframe from one of the other RpfCoverageBoxes. Keep going through - * them until there is a subframe returned, or if there's nothing. Use this - * method when you are sure that the subframe cache is big enough to handle - * all the subframes on the map. - * - * @param x the x index of subframe in the FIRST RpfCoverageBox space - - * translation needed. - * @param y the y index of subframe in the FIRST RpfCoverageBox space - - * translation needed. - */ - protected RpfSubframe getSubframeFromOtherTOC(int x, int y) { - return getSubframeFromOtherTOC(x, y, -1); - } - - /** - * Get a subframe from one of the other RpfCoverageBoxes. Keep going through - * them until there is a subframe returned, or if there nothing. If you are - * not sure that the number of subframes that go on the map is less than or - * equal to the size of the subframe cache, then use this method to provide - * a running count of how many subframes you've already called for to use in - * the current map. If this number gets bigger than the cache size, then the - * RpfCacheHandler will keep fetching data without storing the extra - * subframes in the cache. Otherwise, the previous images in the cache would - * be replaced before they were painted, and they would not appear on the - * map. If subframeCount is less than subframe size, then the latest - * retrieved subframe will be stored in the cache. - * - * @param x the x index of subframe in the FIRST RpfCoverageBox space - - * translation needed. - * @param y the y index of subframe in the FIRST RpfCoverageBox space - - * translation needed. - * @param subframeCount a running count of the number of subframes retrieved - * so far for the current map. Should be used it there is concern - * that the number of subframes needed for the map is greater than - * the size of the subframe. - */ - protected RpfSubframe getSubframeFromOtherTOC(int x, int y, int subframeCount) { - int size = coverageBoxes.size(); - RpfCoverageBox currentBox = null; - - // Decision to never cache if it's coming from another TOC. - // Problems arose in areas that had 3 coverage boxes - // converging. - // They kept writing over each others' cache. - boolean cacheIt = false; - - RpfSubframe ret = null; - int index = 0; - - // There isn't anything else to check. - if (size < 2) { - return null; - } else { - - /* If beyond the cache boundary, don't cache it. */ - if (subframeIndex == null || y < 0 || x < 0 || y >= subframeIndex.length - || x >= subframeIndex[0].length || subframeCount >= subframeCacheSize) { - cacheIt = false; - } - - for (int i = 1; i < size; i++) { - - try { - currentBox = (RpfCoverageBox) coverageBoxes.get(i); - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } - // Changed offsets because they were - // incorrect, and this was preventing other RCBs from - // finding the box - int offsetX = x - start.x; - int offsetY = y - start.y; - // previous values were: - // int offsetX = start.x - x; - // int offsetY = start.y - y; - - int newX = currentBox.startIndexes.x + offsetX; - int newY = currentBox.startIndexes.y + offsetY; - - if (cacheIt) { - /* - * Subframe isn't cached; allocate new entry and decompress - * it - */ - index = getLRU(); - if (index < 0 || index >= subframeCacheSize - || subframeCount >= subframeCacheSize) { - ret = null; - } else { - referenceCache(index); - RpfSubframe subframe = cache.subframe[index]; - // DFD - not sure we need to do this. It seems like it's - // more important to make sure the version changes to - // some other value that matches what's in the subframe, - // rather than keep it stuck on MAX_VALUE. - // if (subframe.version < Byte.MAX_VALUE) { - // subframe.version++; - // } - subframeIndex[y][x] = (byte) index; - subframeVersion[y][x] = subframe.version; - ret = cache.subframe[index]; - } - } - - if (ret == null) { - try { - ret = new RpfSubframe(); - } catch (java.lang.OutOfMemoryError oome) { - Debug.error("RpfCacheHandler: Out of memory! No subframe for you! Next up!"); - return null; - } - } - if (loadSubframe(ret, currentBox, newX, newY)) { - return ret; - } else if (cacheIt) { - freeCache(index); - subframeIndex[y][x] = NOT_PRESENT; - } - - } - } - return null; - } - - /** - * Get a subframe from the cache if possible, otherwise allocate a new cache - * entry and decompress it. Each cache entry has a version number that is - * incremented whenever it is replaced by a new subframe. This ensures the - * replacement is detected. Use this method when you are sure that the - * subframe cache is big enough to handle all the subframes on the map. - * - * @param cbx the x index of subframe in the rcbIndex A.TOC space. - * @param cby the y index of subframe in the rcbIndex A.TOC space. - */ - protected RpfSubframe getCached(int cbx, int cby) { - return getCached(cbx, cby, -1); - } - - /** - * Get a subframe from the cache if possible, otherwise allocate a new cache - * entry and decompress it. Each cache entry has a version number that is - * incremented whenever it is replaced by a new subframe. This ensures the - * replacement is detected. If you are not sure that the number of subframes - * that go on the map is less than or equal to the size of the subframe - * cache, then use this method to provide a running count of how many - * subframes you've already called for to use in the current map. If this - * number gets bigger than the cache size, then the RpfCacheHandler will - * keep fetching data without storing the extra subframes in the cache. - * Otherwise, the previous images in the cache would be replaced before they - * were painted, and they would not appear on the map. If subframeCount is - * less than subframe size, then the latest retrieved subframe will be - * stored in the cache. - * - * @param cbx the x index of subframe in the rcbIndex A.TOC space. - * @param cby the y index of subframe in the rcbIndex A.TOC space. - * @param subframeCount a running count of the number of subframes retrieved - * so far for the current map. Should be used if there is concern - * that the number of subframes needed for the map is greater than - * the size of the cache. - */ - protected RpfSubframe getCached(int cbx, int cby, int subframeCount) { - - RpfSubframe ret; - RpfCoverageBox currentBox = null; - RpfViewAttributes viewAttributes = getViewAttributes(); - // x, y are the subframe indexes in the cache matrix - int x = cbx + subframeBuffer; - int y = cby + subframeBuffer; - - /* If beyond the image boundary, forget it */ - if (subframeIndex != null - && (coverageBoxes == null || coverageBoxes.isEmpty() || y < 0 || x < 0 - || y >= subframeIndex.length || x >= subframeIndex[0].length)) { - return null; - } - - try { - currentBox = (RpfCoverageBox) coverageBoxes.get(0); - } catch (IndexOutOfBoundsException aioobe) { - return null; - } - - int index = NOT_CACHED; - - if (subframeIndex != null) { - index = subframeIndex[y][x]; - } - - if (index == NOT_PRESENT) { - return null; - - } else if (index != NOT_CACHED && cache != null - && cache.subframe[index].version == subframeVersion[y][x] - && subframeCount < subframeCacheSize) { - /* We found it and it's ours; return the cached image */ - referenceCache(index); - ret = cache.subframe[index]; - - if (DEBUG_RPF) { - Debug.output("RpfCacheHandler: found subframe " + x + ", " + y + " in cache."); - } - - ret.setTransparent(viewAttributes.opaqueness); - - // Check to see if the attribute text has even been - // retrieved from the RpfFrameProvider. If it hasn't, and - // needs to be, get it. - if (frameProvider != null && viewAttributes.showInfo - && (ret.getAttributeText() == null || ret.getAttributeText().length() == 0)) { - - // It's needed but not here. - ret.setAttributeText(frameProvider.getSubframeAttributes(currentBox.tocNumber, currentBox.entryNumber, x, y)); - } - - return ret; - - } else { - - /* - * Subframe isn't cached; allocate new entry and decompress it - */ - index = getLRU(); - // Meet the requirements for not caching... - if (index < 0 || index >= subframeCacheSize || subframeCount >= subframeCacheSize) { - try { - ret = new RpfSubframe(); - if (DEBUG_RPF) { - Debug.output("RpfCacheHandler: using uncached subframe."); - } - } catch (java.lang.OutOfMemoryError oome) { - Debug.error("RpfCacheHandler: Out of memory! No subframe for you! Next up!"); - return null; - } - } else { // or set the cache for the new subframe - referenceCache(index); - // DFD - I'm not sure it ever gets to the point where version - // gets bigger than a byte can hold, and we don't - // want the byte overrunning, do we? Then again, does it matter, - // if the frame version number matches the array setting for it, - // even - // if it's negative? - cache.subframe[index].version++; - subframeIndex[y][x] = (byte) index; - subframeVersion[y][x] = cache.subframe[index].version; - ret = cache.subframe[index]; - } - - if (loadSubframe(ret, currentBox, cbx, cby)) { - return ret; - } else { - freeCache(index); - if (subframeIndex != null) { - subframeIndex[y][x] = NOT_PRESENT; - } - } - } - return null; - } - - /** - * Contacts the frame provider to put the subframe image in the RpfSubframe. - * - * @param subframe the RpfSubframe to load the image data into. - * @param coverageBox that has toc and entry numbers to use. - * @param x the coveragebox x index for the subframe. - * @param y the coveragebox y index for the subframe. - * @return true if successful. - */ - protected boolean loadSubframe(RpfSubframe subframe, RpfCoverageBox coverageBox, int x, int y) { - boolean good = false; - int[] pixels = null; - - if (frameProvider == null) { - Debug.message("rpf", "RpfCacheHandler.loadSubframes(): null frameProvider"); - return false; - } - - RpfViewAttributes viewAttributes = getViewAttributes(); - - subframe.opaqueness = viewAttributes.opaqueness; - - if (viewAttributes.colorModel == OMRasterObject.COLORMODEL_DIRECT) { - pixels = frameProvider.getSubframeData(coverageBox.tocNumber, coverageBox.entryNumber, x, y); - if (pixels != null) { - subframe.setPixels(pixels); - good = true; - } - } else if (viewAttributes.colorModel == OMRasterObject.COLORMODEL_INDEXED) { - RpfIndexedImageData riid = frameProvider.getRawSubframeData(coverageBox.tocNumber, coverageBox.entryNumber, x, y); - - if (riid != null && riid.imageData != null && riid.colortable != null) { - subframe.setBitsAndColors(riid.imageData, riid.colortable); - subframe.setTransparent(viewAttributes.opaqueness); - good = true; - } - - } else { - Debug.error("RpfCacheHandler: Frame Provider colormodel not handled."); - return false; - } - - if (good) { - // LOAD UP the geographic stuff into - // cache.subframe[index].image - double lat, lon, lat2, lon2; - double xlloffset, ylloffset; - - ylloffset = (double) (y * coverageBox.subframeLatInterval); - xlloffset = (double) (x * coverageBox.subframeLonInterval); - lat = coverageBox.nw_lat - ylloffset; - lon = coverageBox.nw_lon + xlloffset; - lat2 = lat - coverageBox.subframeLatInterval; - lon2 = lon + coverageBox.subframeLonInterval; - - String data; - if (viewAttributes != null - && (viewAttributes.autofetchAttributes || viewAttributes.showInfo)) { - data = frameProvider.getSubframeAttributes(coverageBox.tocNumber, coverageBox.entryNumber, x, y); - } else { - data = ""; - } - - if (DEBUG_RPFDETAIL) { - Debug.output("Attribute data for subframe " + x + ", " + y + ":\n" + data); - } - - // fill in the information for the subframe. - subframe.setLocation(lat, lon, lat2, lon2); - subframe.setAttributeText(data); - return true; - - } else { - subframe.setAttributeText(""); - } - - return false; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheManager.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheManager.java deleted file mode 100644 index 0b59771cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCacheManager.java +++ /dev/null @@ -1,361 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCacheManager.java,v $ -// $RCSfile: RpfCacheManager.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.io.Serializable; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The RpfCacheManager is the object you need if you want to retrieve RPF files. - * You set it up with a RpfFrameProvider, and it gives that provider to the - * RpfCacheHandler it creates. The RpfCacheManager then handles working with the - * RpfCacheHandlers to get subframes to display. - *

- * - * RPF data comes with a Table of Contents, which sits at the root of the RPF - * file system structure and contains information about the frame files. When - * the RpfFrameProvider gets created, it creates an array of RpfTocHandlers. - * These Table of Contents readers know how to take a geographic area and figure - * out which frames and subframes are needed to put on the screen. An array of - * RpfTocHandlers are needed in case there are many places where there is RPF - * data. - *

- * - * The RpfCacheManager also manages objects called RpfCacheHandlers. Cache - * handlers take the information from a frame provider, and create a subframe - * cache for that zone and map type. The situation gets pretty tricky when the - * screen has the equator and/or the dateline on it, and a different cache - * handler is needed for each quadrant of the earth. This situation is - * relatively rare, though, and the RpfCacheManager automatically checks for - * these situations and creates the cache handlers needed. - *

- * There are two calls to the Cache that you need to use. The constructor sets - * up the cache with the location of the data. The getRectangle() call returns - * an OMGraphicList of objects to draw, that cover the area asked for. - */ -public class RpfCacheManager implements Serializable { - - private static final long serialVersionUID = 1L; - /** - * The size of the smaller caches, when more cachehandlers are needed to - * cover the equator and the dateline. Lowered from 20 to try to conserve - * memory. - */ - public final static int SMALL_CACHE_SIZE = 10; - /** A box is a earth quadrant. */ - public final static int MAX_NUM_BOXES = 4; - /** - * The cache handlers needed to cover the screen. Need one for each earth - * quadrant, and for each RPF directory, in case coverage is spread out over - * different sources. - */ - protected transient RpfCacheHandler[] caches = new RpfCacheHandler[MAX_NUM_BOXES]; - /** The place to look for for image data. */ - protected RpfFrameProvider frameProvider; - /** - * Contains information about displaying the RPF data. Also passed to the - * RpfTocHandlers to determine chart selection. - * - * @see RpfViewAttributes - */ - protected RpfViewAttributes viewAttributes; - /** - * The size of the aux caches, which are used when the map crosses the - * equator or dateline. - */ - protected int auxCacheSize; - - public RpfCacheManager() { - } - - /** - * Constructor that lets you set the RPF frame provider - * - * @param fp the object supplying the data. - */ - public RpfCacheManager(RpfFrameProvider fp) { - this(fp, new RpfViewAttributes()); - } - - /** - * Constructor that lets you set the RPF frame provider, the view attributes - * and the subframe cache size. - * - * @param rfp the object supplying the data. - * @param rva the view attributes for the images. - */ - public RpfCacheManager(RpfFrameProvider rfp, RpfViewAttributes rva) { - this(rfp, rva, RpfCacheHandler.SUBFRAME_CACHE_SIZE, SMALL_CACHE_SIZE); - } - - /** - * Constructor that lets you set the RPF frame provider, the view attributes - * and the subframe cache sizes. - * - * @param rfp the object supplying the data. - * @param rva the view attributes for the images. - * @param mainCacheSize the number of subframes held in the large main - * cache. - * @param auxSubframeCacheSize the number of subframes held in the aux - * caches. - */ - public RpfCacheManager(RpfFrameProvider rfp, RpfViewAttributes rva, int mainCacheSize, - int auxSubframeCacheSize) { - frameProvider = rfp; - viewAttributes = rva; - caches[0] = new RpfCacheHandler(rfp, rva, mainCacheSize); - auxCacheSize = auxSubframeCacheSize; - } - - // public void finalize() { - // Debug.message("gc", "RpfCacheManager: getting GC'd"); - // } - - /** - * Reset the caches in the RpfCacheHandlers. - */ - public void clearCaches() { - for (int i = 0; i < caches.length; i++) { - if (caches[i] != null) { - caches[i].clearCache(); - } - } - } - - /** - * Set the view attributes for the layer. The frame provider view attributes - * are updated, and the cache is cleared. - * - * @param rva the RpfViewAttributes used for the layer. - */ - public void setViewAttributes(RpfViewAttributes rva) { - viewAttributes = rva; - for (int i = 0; i < caches.length; i++) { - if (caches[i] != null) { - caches[i].setViewAttributes(viewAttributes); - } - } - } - - /** - * Get the view attributes or the layer. - * - * @return RpfViewAttributes. - */ - public RpfViewAttributes getViewAttributes() { - return viewAttributes; - } - - /** - * Set the RpfFrameProvider for the layer. Clears out the cache, and the - * frame provider gets the RpfViewAttributes held by the layer. - * - * @param fp the frame provider. - */ - public void setFrameProvider(RpfFrameProvider fp) { - frameProvider = fp; - - for (int i = 0; i < caches.length; i++) { - if (caches[i] != null) { - caches[i].setFrameProvider(fp); - } - } - } - - /** - * Return RpfFrameProvider used by the layer. - */ - public RpfFrameProvider getFrameProvider() { - return frameProvider; - } - - /** - * Returns the Vector containing RpfCoverageBoxes from the primary - * RpfCacheHandler. The Vector is the same that was returned to the cache - * handler from the RpfFrameProvider as a result of the last setCache call. - * These provide rudimentary knowledge about what is being displayed. - * - * @return Vector of RpfCoverageBoxes. - */ - public List getCoverageBoxes() { - return caches[0].getCoverageBoxes(); - } - - /** - * The call to the cache that lets you choose what kind of information is - * returned. This function also figures out what part of the earth is - * covered on the screen, and creates auxiliary cache handlers as needed. - * The CADRG projection held inside the view attributes, used by the - * RpfTocHandlers, is set here. If the projection passed in is not CADRG, - * and the caller doesn't care, then a new CADRG projection is created. - * - * @param proj the projection of the screen. - */ - public synchronized OMGraphicList getRectangle(Projection proj) { - - float[] lat = new float[3]; - float[] lon = new float[3]; - - // This should be checked by the caller. - // if (!(proj instanceof CADRG)) { - // if (viewAttributes.requireProjection) { - // return new OMGraphicList(); - // } else { - // viewAttributes.proj = - // new CADRG((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), - // proj.getScale(), proj.getWidth(), - // proj.getHeight()); - // } - // } else { - // viewAttributes.proj = (CADRG) proj; - // } - - // Need to update the view attributes of the frame provider if - // it is remote. - if (frameProvider != null && frameProvider.needViewAttributeUpdates()) { - frameProvider.setViewAttributes(viewAttributes); - } - - // Hand off coordinates and scale to RpfCacheHandler. - // Then the RpfCacheHandler will figure out the frames to load - // and add to the display list. - - // This next bit of mumbo jumbo is to handle the equator and - // dateline: Worst case, crossing both, treat each area - // separately, so it is the same as handling four requests for - // data - above and below the equator, and left and right of - // the dateline. Normal case, there is only one box. Two - // boxes if crossing only one of the boundaries. - - int xa = 2; - int ya = 2; - int lat_minus = 2; - int lon_minus = 2; - // Set up checks for equator and dateline - LatLonPoint ll1 = (LatLonPoint) proj.getUpperLeft(); - LatLonPoint ll2 = (LatLonPoint) proj.getLowerRight(); - - lat[0] = ll1.getLatitude(); - lon[0] = ll1.getLongitude(); - lat[1] = ll2.getLatitude(); - lon[1] = ll2.getLongitude(); - lat[2] = ll2.getLatitude(); - lon[2] = ll2.getLongitude(); - - if (lon[0] > 0 && lon[2] < 0) { - lon[1] = -179.999f; // put a little breather on the - // dateline - lon_minus = 1; - } - if (lat[0] > 0 && lat[2] < 0) { - lat[1] = -0.0001f; // put a little breather on the - // equator - lat_minus = 1; - } - - if (Debug.debugging("rpf")) { - Debug.output("RpfCacheManager - for:"); - Debug.output("\tlat[0] " + lat[0]); - Debug.output("\tlon[0] " + lon[0]); - Debug.output("\tlat[1] " + lat[1]); - Debug.output("\tlon[1] " + lon[1]); - Debug.output("\tlat[2] " + lat[2]); - Debug.output("\tlon[2] " + lon[2]); - Debug.output("\tlat_minus = " + lat_minus); - Debug.output("\tlon_minus = " + lon_minus); - } - - /* - * Worst case, there are four boxes on the screen. Best case, there is - * one. The things that create boxes and dictates how large they are are - * the equator and the dateline. When the screen straddles one or both - * of these lat/lon lines, lon_minus and lat_minus get adjusted, causing - * two or four different calls to the tochandler to get the data - * above/below the equator, and left/right of the dateline. Plus, each - * path gets checked until the required boxes are filled. - */ - - OMGraphicList list = new OMGraphicList(); - - // Normal (maybe) box[0] gets filled every time - bottom right - // box. - caches[0].getSubframes(lat[ya - lat_minus], lon[xa - - lon_minus], lat[ya], lon[xa], proj, list); - - if (Debug.debugging("rpf")) - Debug.output("RpfCacheManager: main (1) cache used."); - - // Dateline split - if (lon_minus == 1) { - if (caches[1] == null) { - caches[1] = new RpfCacheHandler(frameProvider, viewAttributes, auxCacheSize); - } - caches[1].getSubframes(lat[ya - lat_minus], lon[0], lat[ya], -1f * lon[1], proj, list); // -1 - // to - // make - // it - // 180 - - if (Debug.debugging("rpf")) - Debug.output("-- second cache used"); - } else { - caches[1] = null; - } - - // Equator Split - if (lat_minus == 1) { - if (caches[2] == null) { - caches[2] = new RpfCacheHandler(frameProvider, viewAttributes, auxCacheSize); - } - caches[2].getSubframes(lat[0], lon[xa - lon_minus], -1f * lat[1], // flip - // breather - lon[xa], proj, list); - - if (Debug.debugging("rpf")) - Debug.output("-- third cache used"); - } else { - caches[2] = null; - } - - // Both!! - if (lon_minus == 1 && lat_minus == 1) { - if (caches[3] == null) { - caches[3] = new RpfCacheHandler(frameProvider, viewAttributes, auxCacheSize); - } - // Flip breather to make it 180, not -180. - caches[3].getSubframes(lat[0], lon[0], -1f * lat[1], -1f * lon[1], proj, list); - - if (Debug.debugging("rpf")) - Debug.output("-- fourth cache used"); - } else { - caches[3] = null; - } - - return list; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfColortable.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfColortable.java deleted file mode 100644 index ac17d8c63..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfColortable.java +++ /dev/null @@ -1,769 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfColortable.java,v $ -// $RCSfile: RpfColortable.java,v $ -// $Revision: 1.5 $ -// $Date: 2007/02/26 17:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and Theron Tock, who wrote the software, and to - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used/distributed with permission. - */ - -package com.bbn.openmap.layer.rpf; - -import java.awt.Color; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * Set up the colors used in creating the images. They are created from RGB - * value arrays read in from the RPF file. If the number of colors that are - * allowed is less than 216, then the RpfColortable looks inside the RpfFile and - * uses the color conversion tables inside. There will still be 216 color - * indexes, but some of the colors will be duplicates. - */ -public class RpfColortable { - - public final static int CADRG_COLORS = 216; - public final static int COLORS_216 = 0; - public final static int COLORS_32 = 1; - public final static int COLORS_16 = 2; - public final static int CIB_SPEC_CODE_ID = 3; - public final static int DEFAULT_OPAQUENESS = 255; - - /** - * Color conversion table (to be filled) from within frame, colortable - * section. The colortable is always 216 entries long. If you want fewer - * colors, some of the entries are duplicated. - */ - public int[] colorConvTable = new int[CADRG_COLORS]; - /** Index to use a color conversion table, and if so, which one. */ - protected int reducedColorTable = COLORS_216; - protected int numColors = 0; - protected boolean Cib = false; - protected int opaqueness = DEFAULT_OPAQUENESS; - /** The actual OMColors to use in the image construction. */ - public Color[] colors = null; - /** Zone ID for these colors. */ - public char zone; - /** Chart Series Code for these colors. */ - public String seriesCode; - /** - * The index of the A.TOC file in the RpfTocHandler being used for the - * current colors. - */ - protected int tocNumber = -1; - /** - * The index of the RpfEntry in the A.TOC file being used for the current - * colors. - */ - protected int entryNumber = -1; - - public RpfColortable() { - this(CADRG_COLORS, DEFAULT_OPAQUENESS, false); - } - - public RpfColortable(int nColors) { - this(nColors, DEFAULT_OPAQUENESS, false); - } - - public RpfColortable(int nColors, int opaque, boolean cib) { - setNumColors(nColors); - setOpaqueness(opaque); - setCib(cib); - } - - /** - * Load the provided colortable with the color values of this colortable. - * The A.TOC values that are set by the RpfFrameCacheHandler are not set, - * just the color table information read from the RPF frame file. - * - * @param colortable - */ - public void setFrom(RpfColortable colortable) { - colors = colortable.colors; - reducedColorTable = colortable.reducedColorTable; - colorConvTable = colortable.colorConvTable; - Cib = colortable.Cib; - opaqueness = colortable.opaqueness; - zone = colortable.zone; - } - - /** - * Set the alpha values of the OMColors, which governs the - * transparency/opaqueness of the images. - * - * @param value index between 0-255 (0 is transparent, 255 is opaque) - */ - public void setOpaqueness(int value) { - opaqueness = value; - - if (colors != null) { - for (int i = 0; i < colors.length; i++) { - Color tmp = colors[i]; - colors[i] = new Color(tmp.getRed(), tmp.getGreen(), tmp.getBlue(), opaqueness); - } - } - } - - public int getOpaqueness() { - return opaqueness; - } - - /** - * Set the alpha values of the OMColors, which governs the - * transparency/opaqueness of the images. This method lets you set the value - * as a percentage between 0-100. - * - * @param percent index between 0-100 (0 is transparent, 100 is opaque) - */ - public void setOpaquePercent(int percent) { - setOpaqueness((int) ((float) (percent * 2.55))); - } - - public int getOpaquePercent() { - return (int) ((float) opaqueness * 100.0 / 255.0); - } - - public void setNumColors(int numColorsValue) { - numColors = numColorsValue; - - if (numColors >= 216) - reducedColorTable = COLORS_216; - else if (numColors >= 32) - reducedColorTable = COLORS_32; - else - reducedColorTable = COLORS_16; - } - - /** Returns the number of colors. */ - public int getNumColors() { - return numColors; - } - - /** - * Returns the color reduction index. These values correspond to the - * constants defined in this class. - */ - public int getColorTableReduction() { - return reducedColorTable; - } - - /** - * If this object is going to provide colors for CIB imagery, you have to - * let this object know that. Set this to true. It is false by default. - * - * @param value true if the colortable will be used for greyscale images. - */ - public void setCib(boolean value) { - Cib = value; - } - - public boolean isCib() { - return Cib; - } - - /** - * Should be set when a new colortable is read in, so that you can tell when - * you don't have to read a new one. - */ - public void setATOCIndexes(int tocIndex, int entryIndex) { - tocNumber = tocIndex; - entryNumber = entryIndex; - } - - /** - * Return true of the toc index and entry index are the same as what the - * colortable is currently holding. - */ - public boolean isSameATOCIndexes(int tocIndex, int entryIndex) { - return (tocIndex == tocNumber && entryIndex == entryNumber); - } - - /** - * Not really used, but someone might need them. Returns the A.TOC index - * number of the colors, to compare to see if a new colortable is needed. - */ - public int getTocNumber() { - return tocNumber; - } - - /** - * Not really used, but someone might need them. Returns the A.TOC entry - * number of the colors, to compare to see if a new colortable is needed. - */ - public int getEntryNumber() { - return entryNumber; - } - - /** - * The method to call to read in the colortable from within the RPF file. - * The method will use the input to determine where in the file to read - * from. - * - * @param binFile the file to read it in from. - * @param loc the RpfLocationRecord that tells you where the sections are. - * @return an array of OMColors to use in images. - */ - public Color[] parseColorLookUpTable(BinaryFile binFile, - RpfFileSections.RpfLocationRecord[] loc) { - - if (Debug.debugging("rpfcolortable")) { - Debug.output("RpfColortable: creating new colors for colortable."); - } - - // change this to the proper color structure - Color[] rgb = new Color[CADRG_COLORS]; /* DKS NEW: 216 */ - int i, j; - - long ncr; - int red, green, blue, alpha; - - int numColorOffsetRecs; // uchar, # of color/gray offset - // records */ - int numColorConvOffsetRecs; // uchar - int offsetRecordLength = 17; // ushort - - /* see frame.h */ - ColorOffset[] colorOffset; - - long colormapOffsetTableOffset; // uint - - /* color converter subsection hdr */ - long colorConvOffsetTableOffset; // uint - int colorConvOffsetRecl; // ushort - int colorConvRecl; // ushort - - boolean foundLUT; /* found lut flag */ - - if (Debug.debugging("rpfdetail")) { - Debug.output("ENTER PARSE Colortable"); - } - - try { - /* Go find the color table: loc[0].id=LOC_CLUT */ - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: Color/gray section subheader (ID=134) location: " - + loc[0].componentLocation); - } - binFile.seek(loc[0].componentLocation); - - /* Read section subheader */ - /* Number of offset records: 2 */ - numColorOffsetRecs = binFile.read(); - /* Number of cc offset records: 3 */ - numColorConvOffsetRecs = binFile.read(); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: numColorOffsetRecs(3): " - + numColorOffsetRecs); - Debug.output("RpfColortable: numColorConvOffsetRecs(2): " - + numColorConvOffsetRecs); - } - - /* DKS. New, read array of structures */ - /* Read colormap offset table */ - colorOffset = new ColorOffset[numColorOffsetRecs]; - - /* - * DKS. Read color/gray offset records (colormap subsection) - */ - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: Colormap subsection loc[1]: " - + loc[1].componentLocation); - } - - binFile.seek(loc[1].componentLocation); - - /* colormap offset table offset: length 4 */ - colormapOffsetTableOffset = (long) binFile.readInteger(); - - /* offset record length:17? length 2 */ - offsetRecordLength = (int) binFile.readShort(); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: colormapOffsetTableOffset: " - + colormapOffsetTableOffset); - Debug.output("RpfColortable: offsetRecordLength:" - + offsetRecordLength); - } - - if (reducedColorTable == COLORS_216 || Cib) { /* - * 216 or 217 colors - * desired. No cct - * reading needed - */ - /* Read colormap offset table */ - for (i = 0; i < numColorOffsetRecs; i++) { /* 3 */ - colorOffset[i] = new ColorOffset(); - - colorOffset[i].tableId = (int) binFile.readShort(); - colorOffset[i].numColorRecords = (long) (binFile.readInteger() & 0xFFFFFFFFL); - colorOffset[i].colorElementLength = binFile.read(); - colorOffset[i].histogramRecordLength = (int) binFile.readShort(); - colorOffset[i].colorTableOffset = (long) binFile.readInteger() & 0xFFFFFFFFL; - colorOffset[i].histogramTableOffset = (long) binFile.readInteger() & 0xFFFFFFFFL; - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: Parse_clut: " + i); - Debug.output(colorOffset[i].toString()); - } - - // May look hackish, but 3 is the specification - // number for CIB - if (colorOffset[i].tableId == CIB_SPEC_CODE_ID) { - Cib = true; - } else { - Cib = false; - } - - /* look for numColorRecords[i] == 216 or 217 */ - ncr = colorOffset[i].numColorRecords; - if ((ncr == 216) || (ncr == 217)) - foundLUT = true; - else - foundLUT = false; - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: foundLUT of desired 216?: " - + foundLUT); - } - - if (foundLUT) { - - /* - * Read the color/gray records: 216 or 217 (transp) - * color table. - */ - /* loc[1] is colormap subsection */ - binFile.seek(loc[1].componentLocation - + colorOffset[i].colorTableOffset); - if (ncr >= CADRG_COLORS) { - if (Debug.debugging("rpf")) { - Debug.error("RpfColortable: ncr is not correct, wingin' it (" - + ncr + ")"); - } - ncr = CADRG_COLORS; - } - for (j = 0; j < ncr; j++) { /* 216 or 217 */ - colorConvTable[j] = j; - // Allocate the OMColor here...... - if (Cib) { - red = binFile.read() & 0x00ff; /* - * read mono - * byte value - */ - alpha = opaqueness; - green = red; - blue = red; - } else { - red = binFile.read() & 0x00ff; /* - * read byte - * value - */ - green = binFile.read() & 0x00ff; /* - * read byte - * value - */ - blue = binFile.read() & 0x00ff; /* - * read byte - * value - */ - alpha = binFile.read(); /* - * read byte value - */ - - alpha = opaqueness; - - /* DKS NEW TRANSP */ - if (ncr == 217 && rgb[(int) (ncr - 1)] == null) { /* - * transp - * exists - */ - alpha = 255; - red = 255; - green = 255; - blue = 255; - rgb[(int) (ncr - 1)] = new Color(red, green, blue, alpha); - } /* if */ - } /* else */ - - rgb[j] = new Color(red, green, blue, alpha); - - if (Debug.debugging("rpfcolortable")) { - if (j == 0) - Debug.output("RpfColortable:\n\n---Full color table---\n"); - Debug.output("RpfColortable:red: " + red - + ", green: " + green + ", blue: " - + blue + ", alpha: " + alpha); - } - } /* for j */ - break; /* out of for i */ - } /* if foundLUT */ - } /* for i */ - } /* if reducedColorTable == COLOR_216 */ - - else { /* cct needed */ - - /* DKS. Read cct records */ - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: color converter subsection loc[2]:" - + loc[2].componentLocation); - } - binFile.seek(loc[2].componentLocation); - - colorConvOffsetTableOffset = (long) binFile.readInteger(); - colorConvOffsetRecl = (int) binFile.readShort(); - colorConvRecl = (int) binFile.readShort(); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: colorConvOffsetTableOffset:" - + colorConvOffsetTableOffset); - Debug.output("RpfColortable: colorConvOffsetRecl:" - + colorConvOffsetRecl); - Debug.output("RpfColortable: colorConvRecl:" - + colorConvRecl); - } - - ColorConversionTable[] cct = new ColorConversionTable[numColorConvOffsetRecs]; - - /* Color Converter offset table */ - for (i = 0; i < numColorConvOffsetRecs; i++) { /* - * 2 cct recs - */ - - cct[i] = new ColorConversionTable(); - cct[i].colorConvTableId = (int) binFile.readShort(); - cct[i].colorConvNumRecs = (long) binFile.readInteger(); - cct[i].colorConvTableOffset = (long) binFile.readInteger(); - cct[i].colorConvSourceTableOffset = (long) binFile.readInteger(); - cct[i].colorConvTargetTableOffset = (long) binFile.readInteger(); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: color conversion table - " - + i); - Debug.output(cct[i].toString()); - } - - } /* for i */ - - colorOffset = new ColorOffset[numColorConvOffsetRecs]; - - for (i = 0; i < numColorConvOffsetRecs; i++) { /* 2 */ - /* - * Read colormap subsection for this target table: find # - * color/gray recs. - */ - binFile.seek(loc[1].componentLocation - + cct[i].colorConvTargetTableOffset); - - colorOffset[i] = new ColorOffset(); - - colorOffset[i].tableId = (int) binFile.readShort(); - colorOffset[i].numColorRecords = (long) binFile.readInteger(); - - /* look for numColorRecords[i] == 216 or 217 */ - ncr = colorOffset[i].numColorRecords; - - /* numColorRecords[0] can't be 216 for a cct */ - /* Read, use 32 or 33 clrs */ - if ((((ncr == 32) || (ncr == 33)) && (reducedColorTable == COLORS_32)) - || (((ncr == 16) || (ncr == 17)) && (reducedColorTable == COLORS_16))) { - /* Read, use 16 or 17 clrs */ - foundLUT = true; - } else { - foundLUT = false; - } - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: foundLUT?:" + foundLUT); - } - - if (foundLUT) { /* - * continue reading colormap subsection - */ - colorOffset[i].colorElementLength = binFile.read(); - colorOffset[i].histogramRecordLength = (int) binFile.readShort(); - colorOffset[i].colorTableOffset = (long) binFile.readInteger(); - colorOffset[i].histogramTableOffset = (long) binFile.readInteger(); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: Parse_clut: " + i); - Debug.output(colorOffset[i].toString()); - } - - // //////////////////////////// - /* - * loc[1] is colormap subsection. Seek to color/gray - * table. - */ - binFile.seek(loc[1].componentLocation - + colorOffset[i].colorTableOffset); - - /* - * Read the color/gray records: 32 or 33, or 16 or 17 - * color tables - */ - for (j = 0; j < ncr; j++) { /* - * 32 or 33, or 16 or 17 - */ - red = binFile.read() & 0x00ff; /* - * read byte value - */ - green = binFile.read() & 0x00ff; /* - * read byte - * value - */ - blue = binFile.read() & 0x00ff; /* - * read byte value - */ - alpha = binFile.read(); /* read byte value */ - - alpha = opaqueness; - - /* DKS NEW TRANSP */ - if (ncr == 217 && rgb[(int) (ncr - 1)] == null) { /* - * transp - * exists - */ - alpha = opaqueness; - red = 255; - green = 255; - blue = 255; - rgb[(int) (ncr - 1)] = new Color(red, green, blue, alpha); - } /* if */ - - rgb[j] = new Color(red, green, blue, alpha); - - if (Debug.debugging("rpfcolortable")) { - if (j == 0) - Debug.output("RpfColortable:\n\n---CCT color table---\n"); - Debug.output("RpfColortable: red:" + red - + ", green:" + green + ", blue:" + blue - + ", alpha: " + alpha); - } - } /* for j */ - - /* go to start of color converter table */ - /* loc[2] is color converter subsection */ - binFile.seek(loc[2].componentLocation - + cct[i].colorConvTableOffset); - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: i:" + i - + ", colorConvTableOffset[i]:" - + cct[i].colorConvTableOffset); - Debug.output("RpfColortable: Read cct values at file location:" - + binFile.getFilePointer()); - } - - for (j = 0; j < cct[i].colorConvNumRecs; j++) { - colorConvTable[j] = binFile.readInteger(); - if (Debug.debugging("rpfcolortable")) - Debug.output("RpfColortable: j:" + j - + ", colorConvTable[j]:" - + colorConvTable[j]); - } - - break; /* for i */ - } /* if foundLUT */ - } /* for i = numColorConvOffsetRecs */ - } /* else CCT needed */ - - if (reducedColorTable == COLORS_216) { /* - * 216 colors chosen - */ - if (Debug.debugging("rpfdetail")) - Debug.output("RpfColortable: WARNING - Full 216 colors being used\n"); - for (j = 0; j < CADRG_COLORS; j++) { /* 216 */ - colorConvTable[j] = j; - } /* for j */ - } - - // Since the CIB doesn't contain ccts, we need to fake - // it... - if (Cib && reducedColorTable != COLORS_216) { - int divisor, midoffset; - if (reducedColorTable == COLORS_32) { - divisor = 8; - midoffset = 4; - } else { - divisor = 16; - midoffset = 8; - } - - for (j = 0; j < CADRG_COLORS; j++) { /* 216 */ - red = (int) (rgb[j].getRed() / divisor) * divisor - + midoffset; - green = (int) (rgb[j].getGreen() / divisor) * divisor - + midoffset; - blue = (int) (rgb[j].getBlue() / divisor) * divisor - + midoffset; - alpha = rgb[j].getAlpha(); - - rgb[j] = new Color(red, green, blue, alpha); - - if (Debug.debugging("rpfcolortable")) { - if (j == 0) - Debug.output("RpfColortable:\n\n---Final color table CIB---\n"); - Debug.output("RpfColortable: Color " + j + " red: " - + rgb[j].getRed() + ", green: " - + rgb[j].getGreen() + ", blue: " - + rgb[j].getBlue()); - } - } - - } // if Cib - // For CADRG that has a cct or also Cib that doesn't - /* DKS. cct added here instead of load_frame */ - else if (reducedColorTable != COLORS_216) { - for (j = 0; j < CADRG_COLORS; j++) { /* 216 */ - red = rgb[colorConvTable[j]].getRed(); - green = rgb[colorConvTable[j]].getGreen(); - blue = rgb[colorConvTable[j]].getBlue(); - alpha = rgb[colorConvTable[j]].getAlpha(); - - rgb[j] = new Color(red, green, blue, alpha); - - if (Debug.debugging("rpfcolortable")) { - if (j == 0) - Debug.output("RpfColortable:\n\n---Final color table---\n"); - - Debug.output("RpfColortable: Color " + j + " red: " - + rgb[j].getRed() + ", green: " - + rgb[j].getGreen() + ", blue: " - + rgb[j].getBlue()); - } - } /* for j */ - } - - if (Debug.debugging("rpfdetail")) { - Debug.output("RpfColortable: LEAVE PARSE Colortable"); - } - } catch (IOException ioe) { - Debug.error("RpfTocHandler: IO ERROR parsing file!\n" + ioe); - return null; - } catch (FormatException fe) { - Debug.error("RpfTocHandler: Format ERROR parsing file!\n" + fe); - return null; - } - - colors = rgb; - return rgb; - } /* parse_clut.c */ - - static public class ColorOffset { - public int tableId; - public long numColorRecords; - public int colorElementLength; // uchar - public int histogramRecordLength; - public long colorTableOffset; - public long histogramTableOffset; - - public ColorOffset() {} - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfColortable: tableId 2:CADRG; 3:CIB): ").append(tableId) - .append("\n"); - s.append("RpfColortable: numColorRecords: ").append(numColorRecords) - .append("\n"); - s.append("RpfColortable: colorElementLength: ") - .append(colorElementLength).append("\n"); - s.append("RpfColortable: histogramRecordLength: ") - .append(histogramRecordLength).append("\n"); - s.append("RpfColortable: colorTableOffset: ") - .append(colorTableOffset).append("\n"); - s.append("RpfColortable: histogramTableOffset: ") - .append(histogramTableOffset); - return s.toString(); - } - } - - static public class ColorConversionTable { - - public int colorConvTableId; // ushort - public long colorConvNumRecs; // uint - public long colorConvTableOffset; // uint - public long colorConvSourceTableOffset; // uint - public long colorConvTargetTableOffset; // uint - - public ColorConversionTable() {} - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfColortable: colorConvTableId: ") - .append(colorConvTableId).append("\n"); - s.append("RpfColortable: colorConvNumRecs: ") - .append(colorConvNumRecs).append("\n"); - s.append("RpfColortable: colorConvTableOffset: ") - .append(colorConvTableOffset).append("\n"); - s.append("RpfColortable: colorConvSourceTableOffset: ") - .append(colorConvSourceTableOffset).append("\n"); - s.append("RpfColortable: colorConvTargetTableOffset: ") - .append(colorConvTargetTableOffset); - return s.toString(); - } - } - - public static void main(String[] args) { - - Debug.init(System.getProperties()); - - if (args.length != 1) { - Debug.output("Usage: java RpfColortable "); - return; - } - - File file = new File(args[0]); - BinaryFile binFile = null; - try { - binFile = new BinaryBufferedFile(file); - } catch (FileNotFoundException e) { - Debug.error("RpfHeader: file " + args[0] + " not found"); - System.exit(1); - } catch (IOException ioe) { - Debug.error("RpfHeader: File IO Error while handling colortable:\n" - + ioe); - System.exit(1); - } - - RpfColortable tbl = new RpfColortable(); - RpfFileSections rfs = new RpfFileSections(); - RpfHeader head = new RpfHeader(); - - head.read(binFile); - rfs.parse(binFile); - Color[] colors = rfs.parseColorSection(binFile, tbl); - - if (colors == null) - Debug.output("RpfColortable: NOT read successfully!"); - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfConstants.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfConstants.java deleted file mode 100644 index 8bbfe1c33..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfConstants.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfConstants.java,v $ -// $RCSfile: RpfConstants.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:03 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.rpf; - -/** - * The properties and constants used for RPF data and RPF Coverages. - */ -public interface RpfConstants { - - /** - * Property to use for images or rectangles (when java supports it). - * "opaque" - */ - public static final String OpaquenessProperty = "opaque"; - /** - * Property to use to fill rectangles. "fill" - */ - public static final String FillProperty = "fill"; - /** - * Paths to the A.TOC properties. "paths" - */ - public static final String RpfPathsProperty = "paths"; - /** - * Number of colors to use in images. "numberColors" - */ - public static final String NumColorsProperty = "numberColors"; - /** - * Show the images. "showMaps" - */ - public static final String ShowMapsProperty = "showMaps"; - /** - * Show the attribute information for the RPF data. "showInfo" - */ - public static final String ShowInfoProperty = "showInfo"; - /** - * Scale toe images to match the map scale. "scaleImages" - */ - public static final String ScaleImagesProperty = "scaleImages"; - /** - * Delete the cache is the layer is removed from the map. "killCache" - */ - public static final String KillCacheProperty = "killCache"; - /** - * Set a limit on which chart types are displayed. "chartSeries" - */ - public static final String ChartSeriesProperty = "chartSeries"; - /** - * Tell the RpfLayer you want the coverage tool available. "coverage" - */ - public static final String CoverageProperty = "coverage"; - /** - * Tell the RpfLayer which colormodel to use (INDEXED or DIRECT (default)). - * "colormodel" - */ - public static final String ColormodelProperty = "colormodel"; - /** - * Tell the RpfLayer how big to make the subframe cache.. - * "subframeCacheSize" - */ - public static final String CacheSizeProperty = "subframeCacheSize"; - /** - * Tell the RpfLayer how big to make the subframe cache.. - * "auxSubframeCacheSize" - */ - public static final String AuxCacheSizeProperty = "auxSubframeCacheSize"; - /** - * Tell the RpfLayer to get the detailed subframe attributes for each - * subframe. - */ - public static final String AutoFetchAttributeProperty = "autofetchAttributes"; - /** - * The amount of scaling to allow on images. Default is 4x, which also means - * 1/4th - */ - public static final String ImageScaleFactorProperty = "imageScaleFactor"; - /** - * Property to specify that matching scale is more important that maximizing - * coverage. Default is true, so you can see the smaller coverage that might - * match map scale. This setting is more important for layer being used to - * create smaller tile images, and you might prefer fill coverage over small - * blank spaces. - */ - public static final String ScaleOverCoverageProperty = "scaleOverCoverage"; - - // GUI button commands - public static final String showMapsCommand = "mapsCheckCmd"; - public static final String showInfoCommand = "infoCheckCmd"; - public static final String lockSeriesCommand = "lockSeriesCmd"; - public static final String showCoverageCommand = "coverageCheckCmd"; - public final static String showCGCommand = "showCG"; - - public final static String unlockedButtonTitle = "Limit Chart Selection"; - public final static String lockedButtonTitle = "Displaying Only"; - - /** - * Used to turn a particular coverage on or off. Well, off, really. All - * coverages are turned on by default. - */ - public final static String ShowCoverageProperty = "showcov"; - /** - * Use this property to change the color used for a particular chart type, - * i.e. propertyPrefix.chartSeriesAbbr.color = hexColorValue. - */ - public final static String ColorProperty = "color"; - - public static final String DefaultRPFCoveragePrefix = "rpfcov"; - - public final static float Various = -1f; - public final static String BLANK = ""; - public final static String VARIOUS = "Various"; - public final static String CADRG = "CADRG"; - public final static String CIB = "CIB"; - public final static String CDTED = "CDTED"; - public final static String CITYGRAPHICS = "City Graphics"; - public final static String TOPOLINEMAP = "Topographic Line Map"; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverage.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverage.java deleted file mode 100644 index 90e69ee6c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverage.java +++ /dev/null @@ -1,638 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverage.java,v $ -// $RCSfile: RpfCoverage.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/12/09 21:09:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * This is a tool that provides coverage information on the Rpf data. It is - * supposed to be a simple tool that lets you see the general location of data, - * to guide you to the right place and scale of coverage. The layer really uses - * the properties passed in to it to determine which RPF/A.TOC should be scanned - * for the data. There is a palette for this layer, that lets you turn off the - * coverage for different levels of Rpf. Right now, only City Graphics, TLM, - * JOG, TPC, ONC, JNC, GNC and 5/10 meter CIB scales are are handled. All other - * scales are tossed together under the misc setting. The City Graphics setting - * shows all charts for scales greater than than 1:15k. - *

- * - *

- *       The properties for this file are:
- *        # Java Rpf properties
- *        # Number between 0-255: 0 is transparent, 255 is opaque
- *        jrpf.coverageOpaque=255
- *        #Default is true, don't need this entry if you like it...
- *        jrpf.CG.showcov=true
- *        #Default colors don't need this entry
- *        jrpf.CG.color=CE4F3F
- *        # Other types can be substituted for CG (TLM, JOG, TPC, ONC, JNC, GNC, CIB10, CIB5, MISC)
- *        # Fill the rectangle, default is true
- *        jrpf.coverageFill=true
- * 
- */ -public class RpfCoverage extends OMGraphicList implements RpfConstants, PropertyConsumer { - - /** Property to use for filled rectangles (when java supports it). */ - public static final String CoverageOpaquenessProperty = "coverageOpaque"; - /** Property to use to fill rectangles. */ - public static final String FillProperty = "coverageFill"; - - private static final long serialVersionUID = 1L; - protected RpfCoverageManager coverageManager = null; - protected RpfFrameProvider frameProvider = null; - protected Map coverages = new TreeMap( - new RCCScaleComparator()); - protected String propertyPrefix = null; - /** - * A setting for how transparent to make the images. The default is 255, - * which is totally opaque. Not used right now. - */ - protected int opaqueness = RpfColortable.DEFAULT_OPAQUENESS; - /** Flag to fill the coverage rectangles. */ - protected boolean fillRects = true; - /** The parent layer. */ - protected Layer layer; - /** Flag to track when the RpfCoverage is active. */ - protected boolean inUse = false; - /** - * Show the palette when showing coverage. Probably not needed for layers - * limiting chart seriestypes for display. - */ - protected boolean showPalette = true; - - protected I18n i18n = Environment.getI18n(); - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public RpfCoverage(Layer l, RpfFrameProvider frameProvider) { - this.layer = l; - setFrameProvider(frameProvider); - - super.setTraverseMode(LAST_ADDED_ON_TOP); - } - - public void setFrameProvider(RpfFrameProvider frameProvider) { - this.frameProvider = frameProvider; - - if (frameProvider != null) { - List rpfCoverages = frameProvider.getCatalogCoverage(90f, -180f, -90f, 180f, - new CADRG(new LatLonPoint.Double(), 10000000f, 200, 200), null); - for (RpfCoverageBox rcb : rpfCoverages) { - RpfProductInfo rpfPI = RpfProductInfo.get(rcb.chartCode); - if (rpfPI != null) { - RpfCoverageControl control = coverages.get(RpfProductInfo.get(rcb.chartCode)); - if (control == null) { - control = new RpfCoverageControl(rpfPI, layer); - coverages.put(rpfPI, control); - control.setFilled(fillRects); - control.setFillPaint(getModifiedColor((Color) control.getFillPaint())); - } - } - - } - } - } - - /** Method that sets all the variables to the default values. */ - protected void setDefaultValues() { - allCoveragesOn(); - opaqueness = RpfColortable.DEFAULT_OPAQUENESS / 2; - fillRects = true; - } - - public boolean isInUse() { - return inUse; - } - - public void setInUse(boolean iu) { - inUse = iu; - this.setVisible(iu); // Show OMGraphics or not - if (showPalette || !inUse) { - // Always want it hidden if not in use. - JFrame covPalette = getPaletteWindow(); - covPalette.setLocationRelativeTo(layer.getPalette()); - covPalette.setVisible(inUse); - } - } - - public boolean isShowPalette() { - return showPalette; - } - - public void setShowPalette(boolean sp) { - showPalette = sp; - if (!showPalette) { - allCoveragesOn(); - } - } - - public void allCoveragesOn() { - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setVisible(true); - } - } - - public void setProperties(java.util.Properties props) { - setProperties(null, props); - } - - /** - * Set all the Rpf properties from a properties object. - * - * @param prefix - * string prefix used in the properties file for this layer. - * @param properties - * the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - setPropertyPrefix(prefix); - - setDefaultValues(); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - fillRects = PropUtils.booleanFromProperties(properties, prefix + FillProperty, fillRects); - - showPalette = PropUtils.booleanFromProperties(properties, prefix + CoverageProperty, showPalette); - - opaqueness = PropUtils.intFromProperties(properties, prefix + CoverageOpaquenessProperty, opaqueness); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbrdot = PropUtils.getScopedPropertyPrefix(rcc.rpfProduct.abbr.replace(' ', '_')); - rcc.setColorValue(properties.getProperty(prefix + abbrdot + ColorProperty, rcc.getColorValue())); - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - rcc.setVisible(PropUtils.booleanFromProperties(properties, prefix + abbrdot + ShowCoverageProperty, - rcc.isVisible())); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props - * a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - - props.put(prefix + FillProperty, new Boolean(fillRects).toString()); - props.put(prefix + CoverageProperty, new Boolean(showPalette).toString()); - props.put(prefix + CoverageOpaquenessProperty, Integer.toString(opaqueness)); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbr = rcc.rpfProduct.abbr.replace(' ', '_'); - String abbrdot = PropUtils.getScopedPropertyPrefix(abbr); - props.put(prefix + abbrdot + ColorProperty, Integer.toHexString(((Color) rcc.getLinePaint()).getRGB())); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list - * a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, FillProperty, "Fill Coverage Rectangles", - "Flag to set if the coverage rectangles should be filled.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, CoverageProperty, "Show Coverage Palette", - "Flag to set the coverage palette should be shown.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, CoverageOpaquenessProperty, "Coverage Opaqueness", - "Integer representing opaqueness level (0-255, 0 is clear) of coverage rectangles.", null); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbr = rcc.rpfProduct.abbr.replace(' ', '_'); - String abbrdot = PropUtils.getScopedPropertyPrefix(abbr); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, abbrdot + ColorProperty, - rcc.rpfProduct.abbr + " Coverage Color", "Color for " + abbr + " chart coverage.", - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - } - - return list; - } - - /** - * Specify what order properties should be presented in an editor. - */ - public String getInitPropertiesOrder() { - StringBuilder sb = new StringBuilder(" " + FillProperty + " " + CoverageOpaquenessProperty); - for (RpfProductInfo rpi : coverages.keySet()) { - sb.append(" ").append(rpi.abbr.replace(' ', '_')).append(".").append(ColorProperty); - } - return sb.toString(); - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix - * the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the rpfcov. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public void prepare(Projection projection, String chartSeries) { - - double ullat = 90; - double ullon = -180; - double lrlat = -90; - double lrlon = 180; - - if (projection != null) { - ullat = projection.getUpperLeft().getY(); - ullon = projection.getUpperLeft().getX(); - lrlat = projection.getLowerRight().getY(); - lrlon = projection.getLowerRight().getX(); - } - - Debug.message("basic", "RpfCoverage.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // IF the data arrays have not been set up yet, do it! - if (coverageManager == null) { - coverageManager = new RpfCoverageManager(frameProvider); - } - - clearLayerAndCoverages(); - coverageManager.getCatalogCoverage(ullat, ullon, lrlat, lrlon, projection, chartSeries, coverages); - resetCoveragesOnLayer(); - } - - protected void clearLayerAndCoverages() { - this.clear(); - for (RpfCoverageControl rcc : coverages.values()) { - rcc.clear(); - } - } - - protected void resetCoveragesOnLayer() { - this.clear(); - for (RpfCoverageControl rcc : coverages.values()) { - if (rcc.getVisibilityToggle().isSelected()) { - this.addAll(rcc); - } - } - } - - /** - * @return Returns the opaqueness. - */ - public int getOpaqueness() { - return opaqueness; - } - - /** - * @param opaqueness - * The opaqueness to set. - */ - public void setOpaqueness(int opaqueness) { - this.opaqueness = opaqueness; - - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - } - - } - - /** - * @return the fillRects - */ - public boolean isFillRects() { - return fillRects; - } - - /** - * @param fillRects - * the fillRects to set - */ - public void setFillRects(boolean fillRects) { - this.fillRects = fillRects; - - if (coverages != null) { - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - } - } - } - - protected Color getModifiedColor(Color color) { - if (opaqueness < 255) { - int opa = opaqueness << 24; - return ColorFactory.createColor(((color.getRGB() & 0x00FFFFFF) | opa), true); - } else { - return ColorFactory.createColor(color.getRGB(), true); - } - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - Box box = Box.createVerticalBox(); - - box.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Coverage Controls")); - - if (coverages != null) { - for (RpfProductInfo rpi : coverages.keySet()) { - box.add(coverages.get(rpi).getVisibilityToggle()); - } - } - - return box; - } - - public static class RpfCoverageControl extends OMGraphicList { - - private static final long serialVersionUID = 1L; - - RpfProductInfo rpfProduct; - Layer layer; - JCheckBox controlToggle; - String colorValue; - - public RpfCoverageControl(RpfProductInfo rpfPro, Layer layer) { - this.rpfProduct = rpfPro; - this.layer = layer; - - Color c = DefaultColors.getColor(rpfPro); - setLinePaint(c); - setColorValue(Integer.toHexString(c.getRGB())); - } - - public JCheckBox getVisibilityToggle() { - if (controlToggle == null) { - StringBuilder title = new StringBuilder("Show "); - title.append(rpfProduct.abbr).append(" Coverage"); - - controlToggle = new JCheckBox(title.toString(), true); - controlToggle.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - RpfCoverageControl.this.setVisible(((JCheckBox) ae.getSource()).isSelected()); - if (layer != null) { - if (layer instanceof RpfLayer && ((RpfLayer)layer).coverage != null) { - ((RpfLayer)layer).coverage.resetCoveragesOnLayer(); - } - layer.repaint(); - } - } - }); - - } - return controlToggle; - } - - public boolean add(OMGraphic omg) { - omg.setLinePaint(getLinePaint()); - omg.setFillPaint(getFillPaint()); - return super.add(omg); - } - - public void setFilled(boolean filled) { - if (filled) { - setFillPaint(getLinePaint()); - } else { - setFillPaint(OMColor.clear); - } - } - - public boolean isFilled() { - Paint fPaint = getFillPaint(); - return fPaint == null || fPaint == OMColor.clear; - } - - public void setVisible(boolean set) { - super.setVisible(set); - if (controlToggle != null) { - controlToggle.setSelected(set); - } - } - - /** - * @return the colorValue - */ - public String getColorValue() { - return colorValue; - } - - /** - * @param colorValue - * the colorValue to set - */ - public void setColorValue(String colorValue) { - try { - this.colorValue = colorValue; - setLinePaint(PropUtils.parseColor(colorValue)); - } catch (NumberFormatException nfe) { - } - } - - } - - public static class RCCScaleComparator implements Comparator { - public int compare(RpfProductInfo c1, RpfProductInfo c2) { - double diff = c1.scale - c2.scale; - if (diff == 0) { - return 0; - } else if (diff < 0) { - return 1; - } else { - return -1; - } - } - } - - protected JFrame paletteWindow = null; - - /** - * Get RpfCoverage's associated palette as a top-level window - * - * @return the frame that the palette is in - */ - public JFrame getPaletteWindow() { - - if (paletteWindow == null) { - // create the palette's scroll pane - Component pal = getGUI(); - - if (pal == null) { - pal = new JLabel("No Coverage Information Available."); - } - - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - p.setAlignmentX(Component.LEFT_ALIGNMENT); - p.setAlignmentY(Component.BOTTOM_ALIGNMENT); - p.add(pal); - - JScrollPane scrollPane = new JScrollPane(p, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - - // create the palette internal window - paletteWindow = new JFrame("RPF Coverage Palette"); - - paletteWindow.setContentPane(scrollPane); - paletteWindow.pack();// layout all the components - } - return paletteWindow; - } - - protected enum DefaultColors { - - CG(RpfProductInfo.CG, 0xAC4853), - TLM(RpfProductInfo.TL, 0xCE4F3F), - JOG(RpfProductInfo.JG, 0xAC7D74), - TPC(RpfProductInfo.TP, 0xACCD10), - ONC(RpfProductInfo.ON, 0xFCCDE5), - JNC(RpfProductInfo.JN, 0x7386E5), - GNC(RpfProductInfo.GN, 0x55866B), - CIB10(RpfProductInfo.I1, 0x07516B), - CIB5(RpfProductInfo.I2, 0x071CE0), - MISC(RpfProductInfo.MM, 0xF2C921); - - private RpfProductInfo rpi; - private int defaultColorInt; - - DefaultColors(RpfProductInfo rpi, int defaultColorInt) { - this.rpi = rpi; - this.defaultColorInt = defaultColorInt; - } - - static int getColorInt(RpfProductInfo rpi) { - for (DefaultColors dc : DefaultColors.values()) { - if (dc.rpi.equals(rpi)) { - return dc.defaultColorInt; - } - } - return MISC.defaultColorInt; - } - - static Color getColor(RpfProductInfo rpi) { - return new Color(DefaultColors.getColorInt(rpi)); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageBox.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageBox.java deleted file mode 100644 index 85da86e94..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageBox.java +++ /dev/null @@ -1,317 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageBox.java,v $ -// $RCSfile: RpfCoverageBox.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/12/13 16:45:24 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/** - * Modifications : - * - * 1. Changed getId() to make more unique - * 2. Changed horizontalSubframes() and verticalSubframes(); need to round up - * in certain cases. - */ - -package com.bbn.openmap.layer.rpf; - -import java.awt.Point; - -import com.bbn.openmap.util.Debug; - -/** - * The RpfCoverageBox describes the coverage provided by a RpfTocEntry - * within a table of contents file. This should be enough information - * that lets you tell what you need to ask for the proper subframes to - * put on a screen. - */ -public class RpfCoverageBox { - public double nw_lat; - public double nw_lon; - public double se_lat; - public double se_lon; - /** Lat degrees/subframe; vertInterval*256. */ - public double subframeLatInterval; - /** Lon degrees/subframe; horizInterval*256. */ - public double subframeLonInterval; - /** Two letter code for chart type. */ - public String chartCode; - /** - * The starting index for coverage subframes. If it's null, it - * hasn't been figured out yet. - */ - public Point startIndexes; - /** - * The ending index for coverage subframes. If it's null, it - * hasn't been figured out yet. - */ - public Point endIndexes; - /** - * For the coverage queries, the CADRG zone becomes important. - * This is not the zone from the RpfTocEntry - its the translated - * zone for use with the CADRG projection. - */ - public int zone; - /** - * The TOC number that a frame provider can use to get to the - * right entry number. Used internally. - */ - public int tocNumber; - /** - * The RpfTocEntry index to use to get more information about the - * frame files to use to get data for a subframe. Used internally. - */ - public int entryNumber; - /** The scale of the maps of this coverage rectangle. */ - public float scale; - /** - * Of the number of subframes that can fit on the screen, the - * percentage of them that are on the screen. Should be set via - * setPercentCoverage, unless you are copying all values as well. - */ - public float percentCoverage; - /** A semi unique string descriptor. */ - protected String id; - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append(" nw_lat ").append(nw_lat).append(", nw_lon ").append(nw_lon).append("\n"); - s.append(" se_lat ").append(se_lat).append(", se_lon ").append(se_lon).append("\n"); - s.append(" chart code ").append(chartCode).append("\n"); - s.append(" scale (parsed and decoded) ").append(scale).append("\n"); - s.append(" vertical subframes ").append(verticalSubframes()).append("\n"); - s.append(" horizontal subframes ").append(horizontalSubframes()).append("\n"); - s.append(" percent coverage ").append(percentCoverage); - return s.toString(); - } - - /** - * Modified to make the semi-unique ID more unique. The former - * method of generating these ID numbers was causing some coverage - * boxes that are geographically close to each other to have the - * same ID, which resulted in caching problems. In particular, if - * two non-identical boxes had the same ID, they could invalidate - * each others' caches in certain regions. Modified these IDs so - * that the numbers would be more unique. This was a major cause - * of gaps at zone boundaries. - * - * @return a unique ID for the coverage box - */ - public String getID() { - if (id == null) { - // This should be enough to tell that the box is not the - // same. Even if it isn't the same, the subframes from - // this source should be the same. - - // NOTE: added +se_lat+se_lon because of - // uniqueness problems - id = tocNumber + entryNumber + nw_lat + nw_lon + se_lat + se_lon - + chartCode; - - } - return id; - } - - /** - * The number of subframes vertically within this coverage box. - * - * NOTE: Empirically noticed that # of subframes sometimes - * underreported because these cast to an int. Rounding would - * sometimes overreport, however. Observed that a tolerance of - * .000001 would define when to round up. This appeared to be - * causing gaps at zone boundaries, since a coverage box could - * think it doesn't have a certain subframe, when it actually - * does. - */ - public int verticalSubframes() { - double value = Math.abs((nw_lat - se_lat) / subframeLatInterval); - int lower = (int) value; - int upper = lower + 1; - if (upper - value < .000001) { - return upper; - } else - return lower; - } - - /** - * The number of subframes horizontally within this coverage box. - * - * NOTE: Empirically noticed that # of subframes sometimes - * underreported because these cast to an int. Rounding would - * sometimes overreport, however. Observed that a tolerance of - * .000001 would define when to round up. This appeared to be - * causing gaps at zone boundaries, since a coverage box could - * think it doesn't have a certain subframe, when it actually - * does. - */ - public int horizontalSubframes() { - double value = Math.abs((se_lon - nw_lon) / subframeLonInterval); - int lower = (int) value; - int upper = lower + 1; - if (upper - value < .000001) { - return upper; - } else - return lower; - } - - /** - * This is only good for a preliminary check to see of the - * boundaries are within the range of each other. - * - * @return how many of the edges of this coverage box fall within - * the queried box. - */ - public int setBoundaryHits(double ullat, double ullon, double lrlat, double lrlon) { - int boundaryHits = 0; - if (lrlat < nw_lat) - boundaryHits++; - if (ullat > se_lat) - boundaryHits++; - if (lrlon > nw_lon) - boundaryHits++; - if (ullon < se_lon) - boundaryHits++; - - if (ullat < nw_lat) - boundaryHits++; - if (lrlat > se_lat) - boundaryHits++; - if (ullon > nw_lon) - boundaryHits++; - if (lrlon < se_lon) - boundaryHits++; - return boundaryHits; - } - - /** - * The percentage of subframes that actually fill the queried - * rectangle, compared to the number of subframes that could fit. - * As a bonus, the start and end suframe indexes are set. - * - * @return the percentage of coverage over the queried rectangle. - */ - public float setPercentCoverage(double ullat, double ullon, double lrlat, double lrlon) { - startIndexes = new Point(); - endIndexes = new Point(); - return setPercentCoverage(ullat, - ullon, - lrlat, - lrlon, - startIndexes, - endIndexes); - } - - /** - * The percentage of subframes that actually fill the queried - * rectangle, compared to the number of subframes that could fit. - * As a bonus, the start and end suframe indexes are set. - * - * @return the percentage of coverage over the queried rectangle. - */ - public float setPercentCoverage(double ullat, double ullon, double lrlat, double lrlon, Point start, Point end) { - - startIndexes = start; - endIndexes = end; - - // Set the subframes that are on the screen, in the matrix of - // subframes that make up the overall boundary rectangle. - // Upper left is 0, 0 - double tempInterval = (ullon - nw_lon) / subframeLonInterval; - start.x = (int) tempInterval; - if (tempInterval < 0 && tempInterval < (double) start.x) - start.x--; - tempInterval = (nw_lat - ullat) / subframeLatInterval; - start.y = (int) tempInterval; - if (tempInterval < 0 && tempInterval < (double) start.y) - start.y--; - tempInterval = (lrlon - nw_lon) / subframeLonInterval; - end.x = (int) tempInterval; - if (tempInterval < 0 && tempInterval < (double) end.x) - end.x--; - tempInterval = (nw_lat - lrlat) / subframeLatInterval; - end.y = (int) tempInterval; - if (tempInterval < 0 && tempInterval < (double) end.y) - end.y--; - //(int) (Math.abs(lrlon - ullon)/subframeLonInterval); - int num_horiz_subframes = horizontalSubframes(); - //(int) (Math.abs(ullat - lrlat)/subframeLatInterval); - int num_vert_subframes = verticalSubframes(); - - if ((start.y >= 0 || end.y >= 0) - && (start.x >= 0 || end.x >= 0) - && (start.x < num_horiz_subframes || end.x < num_horiz_subframes) - && (start.y < num_vert_subframes || end.y < num_vert_subframes)) { - - // So now here, either the lesser side is less than zero, - // the greater side is greater than the Max. - int left = start.x < 0 ? 0 : start.x; - int right = end.x >= num_horiz_subframes ? (num_horiz_subframes - 1) - : end.x; - int top = start.y < 0 ? 0 : start.y; - int bottom = end.y >= num_vert_subframes ? (num_vert_subframes - 1) - : end.y; - - percentCoverage = ((float) ((Math.abs(right - left) + 1f) * (Math.abs(bottom - - top) + 1f)) / (float) ((Math.abs(end.x - start.x) + 1f) * (Math.abs(end.y - - start.y) + 1))) * 100f; - - if (percentCoverage > 100f) - percentCoverage = 100f; - - if (Debug.debugging("rpf")) { - System.out.println("Calculated percentage = " - + percentCoverage - + " <= " - + ((Math.abs(right - left) + 1) * (Math.abs(bottom - - top) + 1)) - + " subframes / " - + ((Math.abs(end.x - start.x) + 1) * (Math.abs(end.y - - start.y) + 1)) + " subframes\n (" + right - + " - " + left + ") * (" + bottom + " - " + top - + ") / (" + end.x + " - " + start.x + ") * (" + end.y - + " - " + start.y + ")"); - } - - } else { - percentCoverage = 0f; - } - - return percentCoverage; - } - - /** Return the percent coverage of the last queried rectangle. */ - public float getPercentCoverage() { - return percentCoverage; - } - - /** - * Location within box. True if it is; - */ - public boolean within(float lat, float lon) { - double y = (double) lat; - double x = (double) lon; - return (y < nw_lat && y > se_lat && x < se_lon && x > nw_lon); - } - - /** Reset the coverage percentage and scale difference. */ - public void reset() { - percentCoverage = 0f; - scale = 0; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageManager.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageManager.java deleted file mode 100644 index ea6803485..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfCoverageManager.java +++ /dev/null @@ -1,124 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageManager.java,v $ -// $RCSfile: RpfCoverageManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2007/06/21 21:39:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * This is an object that provides coverage information on the Rpf data. It is - * supposed to be a simple tool that lets you see the general location of data, - * to guide you to the right place and scale of coverage. The layer really uses - * the properties passed in to it to determine which RPF/A.TOC should be scanned - * for the data. There is a palette for this layer, that lets you turn off the - * coverage for different levels of Rpf. Right now, only City Graphics, TLM, - * JOG, TPC, ONC, JNC, GNC and 5/10 meter CIB scales are are handled. All other - * scales are tossed together under the misc setting. The City Graphics setting - * shows all charts for scales greater than than 1:15k. - */ -public class RpfCoverageManager { - - /** - * The last line type of the edge of the rectangles. Used to determine - * whether the line needs to be re-projected based on a projection change. - */ - protected int currentLineType = OMGraphic.LINETYPE_RHUMB; - - /** The place to get the coverage information, */ - protected RpfFrameProvider frameProvider; - - /** Don't use this. */ - public RpfCoverageManager(RpfFrameProvider rfp) { - frameProvider = rfp; - } - - /** - * Get the map coverage - * - * @param ullat - * @param ullon - * @param lrlat - * @param lrlon - * @param proj projection for display - * @param chartSeries the chart series to query for, may be null for all coverages - * @param coverages The Map to be modified - */ - protected void getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection proj, - String chartSeries, Map coverages) { - - Debug.message("rpfcov", "RpfCoverageManager: Getting catalog coverage from RpfFrameProvider"); - if (proj == null || frameProvider == null) { - return; - } - - CADRG cadrg; - if (proj instanceof CADRG) { - cadrg = (CADRG) proj; - } else { - cadrg = new CADRG((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), proj.getWidth(), - proj.getHeight()); - } - - List hemisphereData = new ArrayList(); - - if (ProjMath.isCrossingDateline(ullon, lrlon, proj.getScale())) { - - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, ullon, lrlat, 180f, cadrg, chartSeries)); - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, -180f, lrlat, lrlon, cadrg, chartSeries)); - } else { - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, ullon, lrlat, lrlon, cadrg, chartSeries)); - } - - boolean checkSeries = !(chartSeries == null || chartSeries.equals(RpfViewAttributes.ANY) || chartSeries.equals(RpfViewAttributes.ALL)); - - for (RpfCoverageBox box : hemisphereData) { - - OMRect rect = new OMRect(box.nw_lat, box.nw_lon, box.se_lat, box.se_lon, currentLineType); - - RpfProductInfo rpi = RpfProductInfo.get(box.chartCode); - - - if (rpi != null) { - - if (checkSeries && !rpi.seriesCode.equalsIgnoreCase(chartSeries)) { - continue; - } - - RpfCoverage.RpfCoverageControl control = coverages.get(rpi); - if (control != null) { - control.add(rect); - rect.generate(proj); - } - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfDataPathWanderer.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfDataPathWanderer.java deleted file mode 100644 index d1ea671a4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfDataPathWanderer.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.bbn.openmap.layer.rpf; - -import java.io.File; - -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.wanderer.DataPathWanderer; - -/** - * Adds RPF directories with a A.TOC file inside them to the data paths. - * - * @author dfdietrick - */ -public class RpfDataPathWanderer - extends DataPathWanderer { - - public RpfDataPathWanderer() { - setCallback(this); - } - - public Class getDataUserClass() { - return RpfLayer.class; - } - - /** - * Management method for the wanderer, that steps through the children of - * the directory and calls handleEntry for them. - * - * @param directory the directory to handle - * @param contentNames an array of Strings representing children of the - * directory - * @return true if the wandering should continue. - * @throws SecurityException - */ - protected boolean handleDirectory(File directory, String[] contentNames) - throws SecurityException { - - if (directory.getName().equalsIgnoreCase("RPF")) { - boolean foundRPFDir = false; - for (String childName : contentNames) { - if (childName.equalsIgnoreCase("A.TOC")) { - foundRPFDir = true; - break; - } - } - - if (foundRPFDir) { - addDataPath(directory.getAbsolutePath()); - // This stops the search from continuing on down in this RPF - // directory. - return true; - } - } - - return super.handleDirectory(directory, contentNames); - } - - /** - * NOOP, handle things in the overridden handleDirectory method, more - * efficient. - */ - public boolean handleDirectory(File directory) { - return true; - } - - /** - * NOOP, work done in handleDirectory method. - */ - public boolean handleFile(File file) { - return true; - } - - @Override - public String getPrettyName() { - return "RPF Layer"; - } - - @Override - public boolean isMultiPathLayer() { - return true; - } - - /** - * Given a set of files or directories, search them to find the parent RPF - * directories to use for an RPF layer. - * - * @param argv paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - Debug.init(); - - ArgParser ap = new ArgParser("RpfDataPathWanderer"); - - if (argv.length == 0) { - ap.bail("", true); - } - - String[] dirs = argv; - - RpfDataPathWanderer wanderer = new RpfDataPathWanderer(); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - wanderer.handleEntry(new File(dirs[i])); - } - - for (String path : wanderer.getDataPaths()) { - System.out.println("found: " + path); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSearch.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSearch.java deleted file mode 100644 index c602a0dc4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSearch.java +++ /dev/null @@ -1,186 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFileSearch.java,v $ -// $RCSfile: RpfFileSearch.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/08/17 15:19:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.io.File; -import java.util.Vector; - -import com.bbn.openmap.util.Debug; - -/** - * This class rummages through a file structure looking for RPF files. If there - * isn't a RPF directory somewhere in the absolute path for a file, it's not - * considered to be a RPF file. - */ -public class RpfFileSearch { - - /** The list of RPF frame files. */ - protected Vector files = new Vector(); - - public RpfFileSearch() { - } - - /** Construct and go, starting with the given directory pathname. */ - public RpfFileSearch(String startingDir) { - handleEntry(startingDir); - } - - /** Search, starting with the given directory pathname. */ - public boolean handleEntry(String startingDir) { - File startingFile = null; - - // This line, if included, wipes out files received from - // previous dirs. Yikes! - // files.clear(); - - if (startingDir != null) { - startingFile = new File(startingDir); - if (!startingFile.exists()) { - startingFile = null; - Debug.output("RpfFileSearch: " + startingDir - + " doesn't exist."); - return false; - } - } - - if (startingFile == null) { - return false; - } - - boolean rpfDir = false; - String start = startingFile.getAbsolutePath(); - if ((start.indexOf("RPF") != -1) || (start.indexOf("rpf") != -1)) { - rpfDir = true; - } - - if (Debug.debugging("maketoc")) { - Debug.output("RpfFileSearch: Starting RPF file search from " - + startingDir + ", RPF directory " - + (rpfDir ? "found." : "not found.")); - } - - handleEntry(startingFile, rpfDir); - return true; - } - - /** - * Search, given a file, plus a flag to let it know if the RPF directory is - * somewhere above the file in the file sytem. - */ - public void handleEntry(File file, boolean RPFDirFound) { - try { - - String[] filenames = file.list(); - boolean dirTest = false; - boolean not14 = false; - - try { - java.lang.reflect.Method method = file.getClass() - .getDeclaredMethod("isDirectory", (Class[]) null); - Object obj = method.invoke(file, (Object[]) null); - if (obj instanceof Boolean) { - dirTest = ((Boolean) obj).booleanValue(); - } - } catch (NoSuchMethodException nsme) { - not14 = true; - } catch (SecurityException se) { - not14 = true; - } catch (IllegalAccessException iae) { - not14 = true; - } catch (IllegalArgumentException iae2) { - not14 = true; - } catch (java.lang.reflect.InvocationTargetException ite) { - not14 = true; - } - - if ((dirTest || not14) && filenames != null) { - if (Debug.debugging("maketocdetail")) { - Debug.output("RpfFileSearch.handleEntry(" + file + ", " - + RPFDirFound + "), file is a directory"); - } - File[] contents = new File[filenames.length]; // file.listFiles(); - for (int i = 0; i < contents.length; i++) { - contents[i] = new File(file, filenames[i]); - } - - for (int i = 0; i < contents.length; i++) { - boolean rpf = false; - if (!RPFDirFound) { - rpf = filenames[i].equalsIgnoreCase("RPF"); - } - handleEntry(contents[i], RPFDirFound || rpf); - } - } else { - if (Debug.debugging("maketocdetail")) { - Debug.output("RpfFileSearch.handleEntry(" + file + ", " - + RPFDirFound + "), adding to list..."); - } - - String parent = file.getParent(); - if (RPFDirFound) { - if (parent != null) { - files.add(file.getParent() + File.separator - + file.getName()); - } else { - files.add("." + File.separator + file.getName()); - } - } - } - - } catch (NullPointerException npe) { - } catch (SecurityException se) { - } - } - - /** - * Get the file list as a String[]. - */ - public String[] getFiles() { - String[] fs = new String[files.size()]; - files.toArray(fs); - return fs; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfFileSearch:\n"); - for (int i = 0; i < files.size(); i++) { - s.append(" file ").append(i).append(": ").append(files.elementAt(i)).append("\n"); - } - return s.toString(); - } - - public static void main(String[] argv) { - - Debug.init(); - RpfFileSearch search = new RpfFileSearch(); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < argv.length; i++) { - search.handleEntry(argv[i]); - } - - System.out.println(search); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSections.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSections.java deleted file mode 100644 index 8e450aca7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFileSections.java +++ /dev/null @@ -1,377 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFileSections.java,v $ -// $RCSfile: RpfFileSections.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and to Theron Tock, who wrote the software, and - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used with permission. - */ - -package com.bbn.openmap.layer.rpf; - -import java.awt.Color; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * The class to use to get the locations of different sections of the - * RPF files. This class will find out the section locations, and then - * let you use it later to get to and read those sections. - */ -public class RpfFileSections { - /* DKS switched 3 and 4 to match handbook */ - public static final int LOC_BOUNDARIES = 3; - public static final int LOC_FRAMES = 4; - public static final int LOC_COVERAGE = 6; - public static final int LOC_COMPRESSION = 8; - public static final int LOC_CLUT = 9; - public static final int LOC_IMAGE = 10; - - /* DKS. New Location ID's for SUBsections */ - public static final int LOC_HEADER_SECTION = 128; - public static final int LOC_LOCATION_SECTION = 129; - public static final int LOC_COVERAGE_SECTION = 130; - public static final int LOC_COMPRESSION_SECTION = 131; - public static final int LOC_COMPRESSION_LOOKUP_SUBSECTION = 132; - public static final int LOC_COMPRESSION_PARAMETER_SUBSECTION = 133; - public static final int LOC_COLORGRAY_SECTION_SUBHEADER = 134; - public static final int LOC_COLORMAP_SUBSECTION = 135; - public static final int LOC_IMAGE_DESCR_SUBHEADER = 136; - public static final int LOC_IMAGE_DISPLAY_PARAM_SUBHEADER = 137; - public static final int LOC_MASK_SUBSECTION = 138; - public static final int LOC_COLOR_CONVERTER_SUBSECTION = 139; - public static final int LOC_SPATIAL_DATA_SUBSECTION = 140; - public static final int LOC_ATTRIBUTE_SECTION_SUBHEADER = 141; - public static final int LOC_ATTRIBUTE_SUBSECTION = 142; - public static final int LOC_EXPLICIT_AREAL_TABLE = 143; - public static final int LOC_RELATED_IMAGE_SECTION_SUBHEADER = 144; - public static final int LOC_RELATED_IMAGE_SUBSECTION = 145; - public static final int LOC_REPLACE_UPDATE_SECTION_SUBHEADER = 146; - public static final int LOC_REPLACE_UPDATE_TABLE = 147; - public static final int LOC_BOUNDARY_SECTION_SUBHEADER = 148; - public static final int LOC_BOUNDARY_RECTANGLE_TABLE = 149; - public static final int LOC_FRAME_FILE_INDEX_SUBHEADER = 150; - public static final int LOC_FRAME_FILE_INDEX_SUBSECTION = 151; - public static final int LOC_COLOR_TABLE_SECTION_SUBHEADER = 152; - public static final int LOC_COLOR_TABLE_INDEX_RECORD = 153; - - // the key represents the number of records for the key - public static final int TOC_LOCATION_KEY = 4; - public static final int FRAME_LOCATION_KEY = 8; - public static final int COLOR_LOCATION_KEY = 3; - - RpfLocationSection locationSection; // created in init() - RpfLocationRecord[] locationRecords; // created as found in the - // file - - protected boolean DEBUG_RPFDETAIL = false; - - public RpfFileSections() {} - - /** - * Create the file sections object, and then go ahead and parse - * the file section section of the RPF file. Assumes, the file - * pointer is in the right place, at the - * Rpfheader.locationSectionLocation. - * - * @param binFile the binaryFile of the RPF frame file. - */ - public RpfFileSections(BinaryFile binFile) { - parse(binFile); - } - - public void parse(BinaryFile binFile) { - DEBUG_RPFDETAIL = Debug.debugging("rpfdetail"); - // Location section - parseLocationSection(binFile); - } - - public RpfLocationRecord[] getLocations(int key) { - - if (locationRecords == null) - return null; - - RpfLocationRecord[] locations = new RpfLocationRecord[key]; - int[] ids = new int[key]; - - switch (key) { - case TOC_LOCATION_KEY: - ids[0] = LOC_BOUNDARY_SECTION_SUBHEADER; /* 148 */ - ids[1] = LOC_BOUNDARY_RECTANGLE_TABLE; /* 149 */ - ids[2] = LOC_FRAME_FILE_INDEX_SUBHEADER; /* 150 */ - ids[3] = LOC_FRAME_FILE_INDEX_SUBSECTION; /* 151 */ - break; - case FRAME_LOCATION_KEY: - ids[0] = LOC_COMPRESSION_SECTION; /* 131 */ - ids[1] = LOC_IMAGE_DESCR_SUBHEADER; /* 136 */ - ids[2] = LOC_COMPRESSION_LOOKUP_SUBSECTION; /* 132 */ - ids[3] = LOC_SPATIAL_DATA_SUBSECTION; /* 140 */ - ids[4] = LOC_IMAGE_DISPLAY_PARAM_SUBHEADER; /* 137 */ - ids[5] = LOC_MASK_SUBSECTION; /* 138 */ - ids[6] = LOC_ATTRIBUTE_SECTION_SUBHEADER; /* 141 */ - ids[7] = LOC_ATTRIBUTE_SUBSECTION; /* 142 */ - break; - case COLOR_LOCATION_KEY: - ids[0] = LOC_COLORGRAY_SECTION_SUBHEADER; /* 134 */ - ids[1] = LOC_COLORMAP_SUBSECTION; /* 135 */ - ids[2] = LOC_COLOR_CONVERTER_SUBSECTION; /* 139 */ - break; - default: - } - - for (int i = 0; i < key; i++) - locations[i] = getRpfLocationRecord(ids[i]); - - return locations; - } - - /** - * This function returns the location record, which provides the - * file location for a particular section. The LOC ids are in this - * file. - */ - public RpfLocationRecord getRpfLocationRecord(int locationRecordId) { - if (locationRecords != null) { - for (int i = 0; i < locationRecords.length; i++) { - if (locationRecordId == locationRecords[i].id) { - return locationRecords[i]; - } - } - } - return null; - } - - /** - * This function returns the RpfLocationSection for the file. - * Since we don't really know the location of the location section - * yet, we really have to have the file pointer set to the right - * place. This function should be called right after the RpfHeader - * has been read. - */ - protected boolean parseLocationSection(BinaryFile binFile) { - - locationSection = new RpfLocationSection(); - - try { - locationSection.length = (int) binFile.readShort(); - locationSection.tableOffset = (long) binFile.readInteger(); - locationSection.numberRecords = (int) binFile.readShort(); - locationSection.recordLength = (int) binFile.readShort(); - locationSection.aggregateLength = (long) binFile.readInteger(); - - if (DEBUG_RPFDETAIL) { - Debug.output(locationSection.toString()); - } - - locationRecords = new RpfLocationRecord[locationSection.numberRecords]; - - // Now go find the ones we want - for (int i = 0; i < locationSection.numberRecords; i++) { - locationRecords[i] = new RpfLocationRecord(); - locationRecords[i].id = binFile.readShort(); - locationRecords[i].componentLength = (long) binFile.readInteger(); - locationRecords[i].componentLocation = (long) (binFile.readInteger()); - - if (DEBUG_RPFDETAIL) { - Debug.output("** record " + i + ": " - + locationRecords[i].toString()); - } - - } - - } catch (IOException ioe) { - Debug.error("RpfFileSections: IO ERROR parsing locations!\n" + ioe); - return false; - } catch (FormatException fe) { - Debug.error("RpfFileSections: Format ERROR parsing locations!\n" - + fe); - return false; - } - - return true; - } - - /** - * Read the location and information about the coverage section. - * The method will find out where to start reading from inside the - * file. - */ - public RpfCoverageSection parseCoverageSection(BinaryFile binFile) { - RpfLocationRecord lr = getRpfLocationRecord(LOC_COVERAGE_SECTION); - if (lr == null) - return null; - - try { - binFile.seek(lr.componentLocation); - - RpfCoverageSection coverage = new RpfCoverageSection(); - - if (coverage.read(binFile)) { - if (DEBUG_RPFDETAIL) - Debug.output(coverage.toString()); - return coverage; - } - } catch (IOException ioe) { - Debug.error("RpfFileSections: IO ERROR parsing coverage!\n" + ioe); - } - return null; - - } - - /** - * Read the location and information about the attribute section. - * The method will find out where to start reading from inside the - * file. - */ - public RpfAttributes parseAttributes(BinaryFile binFile) { - RpfLocationRecord lr = getRpfLocationRecord(LOC_ATTRIBUTE_SECTION_SUBHEADER); - if (lr == null) { - if (DEBUG_RPFDETAIL) { - Debug.error("RpfFileSections: attribute section not found!"); - } - return null; - } - RpfAttributes attributes = new RpfAttributes(); - if (attributes.read(binFile, lr.componentLocation)) { - if (DEBUG_RPFDETAIL) - Debug.output(attributes.toString()); - return attributes; - } - return null; - } - - /** - * This kicks back an array of OMColors, representing the - * colortable. By going through the RpfFileSections function, the - * file locations for the color sections are taken care of, and - * the RpfColortable.parseColorLookUpTable function is called - * correctly. - */ - public Color[] parseColorSection(BinaryFile binFile, - RpfColortable colortable) { - if (locationRecords == null) - return null; - return colortable.parseColorLookUpTable(binFile, - getLocations(COLOR_LOCATION_KEY)); - } - - static public class RpfCoverageSection { - public double nwlat; - public double nwlon; - public double swlat; - public double swlon; - public double nelat; - public double nelon; - public double selat; - public double selon; - public double nsVertRes; - public double ewHorRes; - public double latInterval; - public double lonInterval; - - public synchronized boolean read(BinaryFile binFile) { - try { - - nwlat = binFile.readDouble(); - nwlon = binFile.readDouble(); - swlat = binFile.readDouble(); - swlon = binFile.readDouble(); - nelat = binFile.readDouble(); - nelon = binFile.readDouble(); - selat = binFile.readDouble(); - selon = binFile.readDouble(); - nsVertRes = binFile.readDouble(); - ewHorRes = binFile.readDouble(); - latInterval = binFile.readDouble(); - lonInterval = binFile.readDouble(); - - } catch (IOException ioe) { - Debug.error("RpfFileSections: IO ERROR parsing coverage!\n" - + ioe); - return false; - } catch (FormatException fe) { - Debug.error("RpfFileSections: Format ERROR parsing coverage!\n" - + fe); - return false; - } - return true; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Coverage Section:\n"); - s.append(" nwlat = ").append(nwlat).append("\n"); - s.append(" nwlon = ").append(nwlon).append("\n"); - s.append(" swlat = ").append(swlat).append("\n"); - s.append(" swlon = ").append(swlon).append("\n"); - s.append(" nelat = ").append(nelat).append("\n"); - s.append(" nelon = ").append(nelon).append("\n"); - s.append(" selat = ").append(selat).append("\n"); - s.append(" selon = ").append(selon).append("\n"); - s.append(" ns vertical resolution = ").append(nsVertRes).append("\n"); - s.append(" ew horizontal resolution = ").append(ewHorRes).append("\n"); - s.append(" lat interval = ").append(latInterval).append("\n"); - s.append(" lon interval = ").append(lonInterval).append("\n"); - return s.toString(); - } - } - - static public class RpfLocationSection { - public int length; // ushort - public long tableOffset; // ulong - public int numberRecords; //ushort - public int recordLength; //ushort - public long aggregateLength; //ulong - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfLocationSection:\n"); - s.append(" length = ").append(length).append("\n"); - s.append(" table offset = ").append(tableOffset).append("\n"); - s.append(" number of records = ").append(numberRecords).append("\n"); - s.append(" record length = ").append(recordLength).append("\n"); - s.append(" aggregate length = ").append(aggregateLength).append("\n"); - return s.toString(); - } - } - - static public class RpfLocationRecord { - public short id; - public long componentLength; - public long componentLocation; - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfLocationRecord:\n"); - s.append(" id = ").append(id).append("\n"); - s.append(" component length = ").append(componentLength).append("\n"); - s.append(" component location = ").append(componentLocation).append("\n"); - return s.toString(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrame.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrame.java deleted file mode 100644 index 7c9ac8718..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrame.java +++ /dev/null @@ -1,1053 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFrame.java,v $ -// $RCSfile: RpfFrame.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/08/17 15:19:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * Some of the ideas for this code is based on source code provided by - * The MITRE Corporation, through the browse application source code. - * Many thanks to Nancy Markuson who provided BBN with the software, - * to Theron Tock, who wrote the software, and Daniel Scholten, who - * revised it - (c) 1994 The MITRE Corporation for those parts, and - * used/distributed with permission. Namely, the frame file reading - * mechanism is the part that has been modified. - */ - -package com.bbn.openmap.layer.rpf; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.GraphicsEnvironment; -import java.awt.Toolkit; -import java.awt.image.BufferedImage; -import java.awt.image.MemoryImageSource; -import java.io.FileNotFoundException; -import java.io.IOException; - -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.nitf.NitfHeader; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.util.Debug; - -/** - * The object that organizes the information found within the RPF frame file. - * The RpfFrame handles reading through the different sections, and holds on to - * the compressed subframe data. The cache handler gets the compressed subframe - * data and decompresses it before storing the uncompressed subframe in the - * cache. - */ -public class RpfFrame { - - boolean valid = false; - - protected NitfHeader nitfHeader; - protected RpfHeader header; - protected RpfFileSections fileSections; - protected RpfAttributes attributes; - protected RpfFileSections.RpfCoverageSection coverage; - protected RpfColortable colortable; - String report; - - byte[][][] compressedSubframe = new byte[6][6][]; - byte[][][] table = new byte[4][4096][4]; - /* DKS NEW for CHUMMED subfr info. [y][x] */ - boolean[][] chummed = new boolean[6][6]; - /* DKS NEW for masked subfr info: WAS EXTERNAL. */ - boolean[][] masked = new boolean[6][6]; - - /** Want to bother with Dchum? */ - boolean Dchum = false; - int chumVersion; /* Chum version: 2,3,etc. */ - - int numCharsInDesc; // ushort, # chars in DCHUM descriptor string - // */ - int descCount; /* # descriptors */ - /** Array of descriptor strings */ - String[] descriptors; // char - // desc_str[MAX_NUM_DESC][MAX_DESC_LEN]; - /** Array of descriptor dates */ - String[] descriptorDates; // char desc_date[MAX_NUM_DESC][9]; - - protected boolean DEBUG_RPFDETAIL = false; - protected boolean DEBUG_RPFFRAME = false; - - /** Loads the RpfFrame, given a complete path to the file. */ - public RpfFrame(String framePath) { - DEBUG_RPFDETAIL = Debug.debugging("rpfdetail"); - DEBUG_RPFFRAME = Debug.debugging("rpfframe"); - initFile(framePath); - } - - /** - * Loads the RpfFrame, given the RpfFrameEntry that the RpfCacheHandler got - * from the RpfTocHandler. - */ - public RpfFrame(RpfFrameEntry rfe) { - this(rfe.framePath); - - if (!isValid() && rfe.exists && rfe.rpfdirIndex != -1) { - // Check lower case, if we think it exists and the rpf dir - // is not null. If it is null, then the path we tried is - // a complete file path (not a relative one) and should be - // right. - - String lowerCaseFramePath = rfe.framePath.substring(rfe.rpfdirIndex + 3); - lowerCaseFramePath = lowerCaseFramePath.toLowerCase(); - - String rpfDir = rfe.framePath.substring(0, rfe.rpfdirIndex + 3); - - if (DEBUG_RPFFRAME) { - Debug.output("RpfFrame " + rfe.framePath + " not found, checking " + rpfDir + lowerCaseFramePath); - } - - if (initFile(rpfDir + lowerCaseFramePath)) { - // Update it for the next time we check - rfe.framePath = rpfDir + lowerCaseFramePath; - } else { - // Update check so we don't keep looking again. - rfe.exists = false; - } - } - - Dchum = true; - } - - // public void finalize() { - // Debug.message("gc", "RpfFrame: getting GC'd"); - // } - - protected boolean initFile(String framePath) { - try { - BinaryFile binFile = new BinaryBufferedFile(framePath); - read(binFile); - binFile.close(); - } catch (FileNotFoundException e) { - Debug.error("RpfFrame: file " + framePath + " not found"); - valid = false; - } catch (IOException ioe) { - Debug.error("RpfFrame: File IO Error while handling NITF header:\n" + ioe); - valid = false; - } catch (NullPointerException npe) { - Debug.error("RpfFrame: File IO Error NPE:\n" + npe); - npe.printStackTrace(); - valid = false; - } - return valid; - } - - public boolean isValid() { - return valid; - } - - /** - * Create the screen text used on a subframe. The internal string is set. - * - * @param Cib whether the frame is a Cib frame. The report is different if it - * is. - */ - protected void setReport(boolean Cib) { - if (attributes != null) { - StringBuffer s = new StringBuffer(); - s.append("
RPF Currency Date: ").append(attributes.currencyDate); - s.append("
RPF Production Date: ").append(attributes.productionDate); - s.append("
Source Significant Date: ").append(attributes.significantDate); - if (Cib) { - s.append("
Map Source: ").append(attributes.dataSource); - } else { - s.append("
Map Designation: ").append(attributes.mapDesignationCode); - s.append("
Map Series: ").append(attributes.chartSeriesCode); - s.append("
Map Edition: ").append(attributes.edition); - } - report = s.toString(); - } - } - - /** - * Get the attribute html text to display on the screen. This goes to the - * RpfSubframe object. The RpfCacheHandler knows about the four variables. - * - * @param x subframe index within the array from the TocEntry. - * @param y subframe index within the array from the TocEntry - * @param entry the RpfFrameEntry describing the frame. - * @param Cib whether the frame is an imagery frame. - */ - public String getReport(int x, int y, RpfFrameEntry entry, boolean Cib) { - StringBuffer s = new StringBuffer(""); - - x %= 6; - y %= 6; - if (entry != null) { - s.append("
Frame Name: "); - // s.append(entry.filename); - s.append(entry.framePath.substring(entry.filenameIndex)); - } else { - s.append("
Frame Name: Unavailable."); - } - s.append("
Subframe ").append(x).append(", ").append(y).append("
"); - - if (report == null) - setReport(Cib); // preset the attribute part of the info. - if (report != null) - s.append(report); - - if (entry != null) { - s.append("
From Frame Dir: "); - - String actualFilePath = entry.framePath.substring(0, entry.filenameIndex); - - if (actualFilePath.length() > 20) { - int start = 0; - int index = actualFilePath.indexOf("/", 15); - while (index != -1) { - s.append(actualFilePath.substring(start, index)); - s.append("/
"); - start = index + 1; - index = actualFilePath.indexOf("/", start + 15); - } - s.append(actualFilePath.substring(start)); - } - - else - s.append(actualFilePath); - } - s.append("
"); - return s.toString().trim(); - } - - /** - * Get the NitfFile header. - */ - public NitfHeader getNitfHeader() { - return nitfHeader; - } - - /** - * Get the RpfFrame header. - */ - public RpfHeader getHeader() { - return header; - } - - /** - * Get the different file sections. - */ - public RpfFileSections getFileSections() { - return fileSections; - } - - /** - * Get the attributes for the RpfFrame. - */ - public RpfAttributes getAttributes() { - return attributes; - } - - /** - * Get the coverage section. - */ - public RpfFileSections.RpfCoverageSection getCoverage() { - return coverage; - } - - /** - * The only reason to call this is to read the colortable that is within the - * frame file, and set the colors that you will be using for all the frames - * accordingly. The RpfColortable is passed in so you can set the opaqueness, - * number of colors, and other colortable variables inside your own - * colortable object, and then read the color conversion tables as they apply - * (inside the frame file). Since the frame file is read when the RpfFrame is - * created, the fileSections object will (should) be valid. - */ - public Color[] getColors(BinaryFile binFile, RpfColortable ct) { - - fileSections.parseColorSection(binFile, ct); - return ct.colors; - } - - /** - * Load the colortable with the colors from a particular frame file. Not - * needed, really, since the frame file is now loading it's own colortable at - * loadtime. - */ - public static Color[] getColors(String framePath, RpfColortable ct) { - BinaryFile binFile = null; - try { - binFile = new BinaryBufferedFile(framePath); - // binFile = new BinaryFile(framePath); - RpfFileSections rfs = new RpfFileSections(); - RpfHeader head = new RpfHeader(); - - head.read(binFile); - binFile.seek(head.locationSectionLocation); - rfs.parse(binFile); - - Color[] ret = rfs.parseColorSection(binFile, ct); - - binFile.close(); - return ret; - } catch (FileNotFoundException e) { - Debug.error("RpfFrame: getColortable(): file " + framePath + " not found"); - } catch (IOException ioe) { - Debug.error("RpfFrame: getColortable(); File IO Error!\n" + ioe); - } - return null; - } - - /** - * Get the colortable stored inside this RpfFrame. - * - * @return RpfColortable - */ - public RpfColortable getColortable() { - return colortable; - } - - /** Read the RPF frame. */ - public boolean read(BinaryFile binFile) { - - Compression compression; - LookupTable[] lookupTable = new LookupTable[4]; - Image image; - - int[][] indices = new int[6][6]; // ushort - int i, j; - - /* bool (uchar) */ - /* all subframes present indicator */ - boolean allSubframes; - long currentPos; // uint - long lookupOffsetTableOffset; // uint - int lookupTableOffsetRecLen; // ushort - - long subframeMaskTableOffset; // uint - /* subframe offset (mask section) */ - long[][] subframeOffset = new long[6][6];// uint[][] - - /* for DCHUM */ - long fsave; /* saved file loc */ - int chummedSubframe; // uint - int attributeId; // ushort - int attributeParamId; // uchar - long attributeRecOffset; // uint - int numAttributeOffsetRecs; // ushort - int numSubframesChummed; // ushort - - if (DEBUG_RPFDETAIL) { - Debug.output("ENTER RPFFRAME.READ"); - } - - try { - // Let's start at the beginning, shall we? - binFile.seek(0); - - // Read the NITF part of the file... - nitfHeader = new NitfHeader(); - // If false, it might not be a NITF file, start over... - if (!nitfHeader.read(binFile)) - binFile.seek(0); - - header = new RpfHeader(); - // Now, read the RPF header... - if (!header.readHeader(binFile)) - return false; - - if (DEBUG_RPFDETAIL) - Debug.output(header.toString()); - - /* Check date for validity: date should be "1993xxxx" */ - if (!header.standardDate.startsWith("199") && !header.standardDate.startsWith("20")) { - Debug.output("RpfFrame.read: Invalid date in header: " + header.standardDate); - return false; - } - - // Need to do this right after the header... - binFile.seek(header.locationSectionLocation); - fileSections = new RpfFileSections(binFile); - - RpfFileSections.RpfLocationRecord[] loc = fileSections.getLocations(RpfFileSections.FRAME_LOCATION_KEY); - - attributes = fileSections.parseAttributes(binFile); - coverage = fileSections.parseCoverageSection(binFile); - - colortable = new RpfColortable(); - getColors(binFile, colortable); - - /* DKS: from index to componentLocation */ - if (loc[0] == null) { - Debug.output("RpfFrame: No compression section!"); - return false; - } - - /* Read the compression tables */ - binFile.seek(loc[0].componentLocation); - compression = new Compression(binFile); - if (DEBUG_RPFDETAIL) - Debug.output(compression.toString()); - - if (loc[2] == null) { - Debug.output("Warning: Can't find compr. lookup subsection in FrameFile:"); - Debug.output(" Using alternate computation"); - /* length of compr. sect. subhdr = 10 */ - binFile.seek(loc[0].componentLocation + 10); - } else { - /* - * DKS: Position at start of compression lookup table offset record - */ - if (DEBUG_RPFDETAIL) { - Debug.output("Comp lkup subsect: loc[2].componentLocation(264?): " + loc[2].componentLocation); - } - binFile.seek(loc[2].componentLocation); - } - - /* 2 new hdr fields */ - - lookupOffsetTableOffset = (long) binFile.readInteger(); - lookupTableOffsetRecLen = (int) binFile.readShort(); - - if (DEBUG_RPFDETAIL) { - Debug.output("lookupOffsetTableOffset(6): " + lookupOffsetTableOffset); - Debug.output("lookupTableOffsetRecLen(14): " + lookupTableOffsetRecLen); - } - - /* For each compression table */ - for (i = 0; i < 4; i++) { - lookupTable[i] = new LookupTable(binFile); - if (DEBUG_RPFDETAIL) { - Debug.output("Compression lookup table offset record " + i); - Debug.output(lookupTable[i].toString()); - } - - if (lookupTable[i].records != 4096 || lookupTable[i].values != 4 || lookupTable[i].bitLength != 8) { - Debug.output("RpfFrame: Bad VQ info in compression record"); - return false; - } - } /* for i */ - - for (i = 0; i < 4; i++) { /* Read compression lookup table */ - /* - * new position from compression lookup subsection: loc[2] - */ - binFile.seek(loc[2].componentLocation + lookupTable[i].offset); - if (DEBUG_RPFDETAIL) { - currentPos = binFile.getFilePointer(); - Debug.output("Read compr. lookup table (4x4096) at position: " + currentPos); - } - for (j = 0; j < 4096; j++) - table[i][j] = binFile.readBytes(4, false); - - } /* - * for i=1 to 4 (# compression tables, 1 for each pixel row) - */ - - /* seek to LOC_ATTRIB_SUBHEADER, ID=141 */ - if ((Dchum) && (chumVersion > 1)) { /* - * Chum selected and file version > - * 1 - */ - if (loc[6] == null) { - Debug.output("RpfFrame: Can't find ATTRIBUTE_SUBHEADER section!"); - return false; - } - if (DEBUG_RPFDETAIL) - Debug.output("ATTRIBUTE SUBHEADER location: " + loc[6].componentLocation); - - binFile.seek(loc[6].componentLocation); - - numAttributeOffsetRecs = (int) binFile.readShort(); - if (DEBUG_RPFDETAIL) - Debug.output("numAttributeOffsetRecs: " + numAttributeOffsetRecs); - - /* Go to Attrib subsection */ - if (loc[7] == null) { - Debug.output("RpfFrame: Can't find ATTRIBUTE_SECTION in Frame file"); - return false; - } - - if (DEBUG_RPFDETAIL) - Debug.output("ATTRIBUTE SECTION location: " + loc[7].componentLocation); - - binFile.seek(loc[7].componentLocation); - - descCount = 0; /* # descriptor strings so far */ - - for (i = 0; i < numAttributeOffsetRecs; i++) { - attributeId = (int) binFile.readShort(); - attributeParamId = binFile.read(); - /* tempc = */binFile.read(); - attributeRecOffset = (long) binFile.readInteger(); - - /* # subframes impacted */ - if ((attributeId == 24) && (attributeParamId == 4)) { - /* save file loc */ - fsave = binFile.getFilePointer(); - /* Go to proper spot in attrib section */ - binFile.seek(loc[7].componentLocation + attributeRecOffset); - /* read # subframes impacted */ - numSubframesChummed = (int) binFile.readShort(); - - if (DEBUG_RPFDETAIL) { - Debug.output("n_attrib_chummedSubframe: " + numSubframesChummed); - } - /* Read list of subframes chummed */ - /* Assume these are next in file */ - for (j = 0; j < numSubframesChummed; j++) { - chummedSubframe = (int) binFile.readShort(); - - if (DEBUG_RPFDETAIL) { - Debug.output("chummedSubframe: " + chummedSubframe); - } - - /* y,x */ - chummed[chummedSubframe / 6][chummedSubframe % 6] = true; - } /* for j */ - binFile.seek(fsave); /* restore file pos */ - } /* if 24,4 */ - - /* Update date */ - if ((attributeId == 24) && (attributeParamId == 3)) { - /* save file loc */ - fsave = binFile.getFilePointer(); - /* Go to proper spot in attrib section */ - binFile.seek(loc[7].componentLocation + attributeRecOffset); - /* read date */ - descriptorDates[descCount] = binFile.readFixedLengthString(8); - - if (DEBUG_RPFDETAIL) - Debug.output("descriptorDate: " + descriptorDates[descCount]); - - binFile.seek(fsave); /* restore file pos */ - } /* if 24,3 */ - - /* # chars in descriptor */ - if ((attributeId == 24) && (attributeParamId == 6)) { - /* save file loc */ - fsave = binFile.getFilePointer(); - /* Go to proper spot in attrib section */ - binFile.seek(loc[7].componentLocation + attributeRecOffset); - /* read # chars in descriptor */ - - numCharsInDesc = (int) binFile.readShort(); - - if (DEBUG_RPFDETAIL) { - Debug.output("Prepare to fread descriptors[descCount]"); - Debug.output("RpfFrame.read: descCount: " + descCount); - } - - descriptors[descCount] = binFile.readFixedLengthString(numCharsInDesc); - - /* Array of strings, not 2-d array !!!!???? */ - if (DEBUG_RPFDETAIL) { - Debug.output("descriptors[descCount]: " + descriptors[descCount]); - } - descCount++; /* string number */ - - binFile.seek(fsave); /* restore file pos */ - } /* if 24,6 */ - } /* for i */ - } /* if Dchum */ - - /* READ THE IMAGE DATA */ - if (DEBUG_RPFDETAIL) { - Debug.output("Image descr. subheader location: loc[1].componentLocation(68576?): " + loc[1].componentLocation); - } - binFile.seek(loc[1].componentLocation); - image = new Image(binFile); - - /* New, DKS. NULL (FF) if no subfr mask table */ - subframeMaskTableOffset = binFile.readInteger(); - - if (DEBUG_RPFDETAIL) { - Debug.output(image.toString()); - Debug.output("subframeMaskTableOffset: " + subframeMaskTableOffset); - } - - if (subframeMaskTableOffset == 0) { /* ERROR Check */ - Debug.error("RpfFrame.read(): subframeMaskTableOffset==0."); - return false; - } - - if (subframeMaskTableOffset == 0xFFFFFFFF) - allSubframes = true; - else - allSubframes = false; - - if (Debug.debugging("rpfframe")) { - Debug.output("allSubframes: " + allSubframes); - } - - if (!allSubframes) { /* Read mask data */ - /* fseek to LOC_MASK_SUBSECTION, ID=138 */ - if (loc[5] == null) { - Debug.error("RpfFrame.read(): Can't find MASK_SUBSECTION section in Frame file"); - return false; - } - if (DEBUG_RPFDETAIL) { - Debug.output("MASK SUBSECTION location: " + loc[5].componentLocation); - } - - binFile.seek(loc[5].componentLocation + subframeMaskTableOffset); - - for (i = 0; i < 6; i++) { /* y */ - for (j = 0; j < 6; j++) { - subframeOffset[i][j] = (long) binFile.readInteger(); - if (subframeOffset[i][j] == 0xFFFFFFFF) - masked[i][j] = true; /* subfr masked */ - - if (DEBUG_RPFDETAIL) { - Debug.output("i:" + i + ", j:" + j + ", masked[i][j]: " + masked[i][j]); - } - - } /* for j */ - } /* for i */ - } /* if !allSubframes */ - - if (image.vertSubframes != 6 || image.horizSubframes != 6) { - Debug.output("Not 6x6 subframes per frame: must be masked."); - } - - // rowBytes = 256 / 4 * 3 / 2; - - // Is this section needed?? - /* fseek to LOC_IMAGE_DISPLAY_PARAM_SUBHEADER, ID=137 */ - if (loc[4] == null) { - Debug.error("RpfFrame.read(): Can't find IMAGE_DISPLAY_PARAM_SUBHEADER section!"); - return false; - } - - /* Image Display Parameters Subheader */ - if (DEBUG_RPFDETAIL) { - Debug.output("IMAGE Display params subheader location: " + loc[4].componentLocation); - } - binFile.seek(loc[4].componentLocation); - - /* Go to start of image spatial data subsection */ - if (loc[3] == null) { - Debug.output("WARNING: Can't find Image spatial data subsection in FrameFile:"); - Debug.output(" Using alternate computation"); - /* - * DKS. skip 14 bytes of image display parameters subheader instead - */ - binFile.seek(loc[4].componentLocation + 14); - } else { - /* - * DKS: Position at start of image spatial data subsection - */ - currentPos = binFile.getFilePointer(); - if (DEBUG_RPFDETAIL) { - Debug.output("Current frame file position(68595?): " + currentPos); - Debug.output("Image spatial data subsect: loc[3](68609?): " + loc[3].componentLocation); - } - - binFile.seek(loc[3].componentLocation); - } /* else */ - - /* Read subframes from top left, row-wise */ - for (i = 0; i < 6; i++) { /* row */ - for (j = 0; j < 6; j++) { /* col */ - /* DKS. New: init indices to valid subframes */ - indices[i][j] = i * 6 + j; - /* (256/4)=64. 64*64 * 12bits / 8bits = 6144 bytes */ - if (!masked[i][j]) { - compressedSubframe[i][j] = binFile.readBytes(6144, false); - if (DEBUG_RPFDETAIL) - Debug.output(" i:" + i + ", j:" + j + ", read image data. rc(6144):" + compressedSubframe[i][j].length); - } else - compressedSubframe[i][j] = new byte[6144]; - } - } - - } catch (IOException e) { - Debug.error("RpfFrame: read(): File IO Error!\n" + e); - return false; - } catch (FormatException f) { - Debug.error("RpfFrame: read(): File IO Format error!" + f); - return false; - } - - if (DEBUG_RPFDETAIL) { - Debug.output("LEAVE RPFFRAME.READ"); - } - - valid = true; - return valid; - } /* read */ - - static public class Compression { - public int algorithm;// ushort - /* New, dks */ - public int numOffsetRecs;// ushort - public int numParmOffRecs;// ushort - - public Compression(BinaryFile binFile) { - try { - algorithm = (int) binFile.readShort(); - numOffsetRecs = (int) binFile.readShort(); - numParmOffRecs = (int) binFile.readShort(); - } catch (IOException e) { - Debug.error("Compression: File IO Error!\n" + e); - } catch (FormatException f) { - Debug.error("Compression: File IO Format error!\n" + f); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Compression.algorithm: ").append(algorithm).append("\n"); - s.append("Compression.numOffsetRecs: ").append(numOffsetRecs).append("\n"); - s.append("Compression.numParmOffRecs: ").append(numParmOffRecs).append("\n"); - return s.toString(); - } - } - - static public class LookupTable { - int id; // ushort - long records; // uint - int values; // ushort - int bitLength; // ushort - long offset; // uint - - public LookupTable(BinaryFile binFile) { - try { - id = (int) binFile.readShort(); - records = (long) binFile.readInteger(); - values = (int) binFile.readShort(); - bitLength = (int) binFile.readShort(); - offset = (long) binFile.readInteger(); - } catch (IOException e) { - Debug.error("Compression: File IO Error!\n" + e); - } catch (FormatException f) { - Debug.error("Compression: File IO Format error!\n" + f); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("LookupTable.id: ").append(id).append("\n"); - s.append("LookupTable.records: ").append(records).append("\n"); - s.append("LookupTable.values: ").append(values).append("\n"); - s.append("LookupTable.bitLength: ").append(bitLength).append("\n"); - s.append("LookupTable.offset: ").append(offset).append("\n"); - return s.toString(); - } - } - - static public class Image { - int spectralGroups; // ushort - int subframeTables;// ushort - int spectralTables;// ushort - int spectralLines;// ushort - int horizSubframes, vertSubframes;// ushort - long outputColumns, outputRows;// uint - - public Image(BinaryFile binFile) { - try { - spectralGroups = (int) binFile.readShort(); - subframeTables = (int) binFile.readShort(); - spectralTables = (int) binFile.readShort(); - spectralLines = (int) binFile.readShort(); - horizSubframes = (int) binFile.readShort(); - vertSubframes = (int) binFile.readShort(); - outputColumns = (long) binFile.readInteger(); - outputRows = (long) binFile.readInteger(); - } catch (IOException e) { - Debug.error("Compression: File IO Error!\n" + e); - } catch (FormatException f) { - Debug.error("Compression: File IO Format error!\n" + f); - } - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Image.spectralGroups: ").append(spectralGroups).append("\n"); - s.append("Image.subframeTables: ").append(subframeTables).append("\n"); - s.append("Image.spectralTables: ").append(spectralTables).append("\n"); - s.append("Image.spectralLines: ").append(spectralLines).append("\n"); - s.append("Image.horizSubframes: ").append(horizSubframes).append("\n"); - s.append("Image.vertSubframes: ").append(vertSubframes).append("\n"); - s.append("Image.outputColumns: ").append(outputColumns).append("\n"); - s.append("Image.outputRows: ").append(outputRows).append("\n"); - return s.toString(); - } - } - - /** - * Decompress a subframe into a cache entry OMRaster (RpfSubframe). The - * RpfSubframe is returned, too, to emphasize what's happening. - * - * @param x the x coord for the subframe - * @param y the y coord for the subframe - * @param subframe the subframe to create the image for. The resulting image - * will be loaded into the RpfSubframe. If null, a new RpfSubframe - * will be created. - * @param colortable the colortable to use with this image. If null, the - * colortable from this RpfFrame will be used. - * @param viewAttributes our image generation parameters. - * @return RpfSubframe containing the image data. - */ - public RpfSubframe decompressSubframe(int x, int y, RpfSubframe subframe, RpfColortable colortable, - RpfViewAttributes viewAttributes) { - - boolean isDirectColorModel = (viewAttributes.colorModel == OMRasterObject.COLORMODEL_DIRECT); - - if (subframe == null) { - subframe = new RpfSubframe(); - } - -// if (viewAttributes != null) { -// subframe.setColorModel(viewAttributes.colorModel); -// } - - if (colortable == null) { - colortable = this.colortable; - } - - if (!isDirectColorModel) { - if (DEBUG_RPFDETAIL) { - Debug.output("RpfFrame: decompress to byte[]"); - } - byte[] pixels = decompressSubframe(x, y); - subframe.setBitsAndColors(pixels, colortable.colors); - } else { - int[] pixels = decompressSubframe(x, y, colortable); - subframe.setPixels(pixels); - } - return subframe; - } - - /** - * Decompress a subframe into an array of bytes suitable for in indexed color - * model image. - * - * @param x the x coord for the subframe - * @param y the y coord for the subframe - */ - public byte[] decompressSubframe(int x, int y) { - // Convert x,y to the subframe index in the frame - they come - // in as - // cache subframe indexes - x %= 6; - y %= 6; - - // used to keep track of location into compressedSubframe - // array. - int readptr = 0; - - // and the compressedSubframe array - byte[] compressedSubframe = this.compressedSubframe[y][x]; - - /* - * This should never occur since all subframes should be present - */ - /* - * But if it does occur, just put up black pixels on the screen - */ - if ((compressedSubframe == null) || masked[y][x]) { - return null; - } else { // Normal pixel */ - byte[] pixels = new byte[256 * 256]; - for (int i = 0; i < 256; i += 4) { - for (int j = 0; j < 256; j += 8) { - int firstByte = compressedSubframe[readptr++] & 0xff; - int secondByte = compressedSubframe[readptr++] & 0xff; - int thirdByte = compressedSubframe[readptr++] & 0xff; - - // because dealing with half-bytes is hard, we - // uncompress two 4x4 tiles at the same time. (a - // 4x4 tile compressed is 12 bits ) - - /* Get first 12-bit value as index into VQ table */ - int val1 = (firstByte << 4) | (secondByte >> 4); - /* Get second 12-bit value as index into VQ table */ - int val2 = ((secondByte & 0x000F) << 8) | thirdByte; - for (int t = 0; t < 4; t++) { - for (int e = 0; e < 4; e++) { - int tableVal1 = table[t][val1][e] & 0xff; - int tableVal2 = table[t][val2][e] & 0xff; - if (tableVal1 >= RpfColortable.CADRG_COLORS) { - tableVal1 = RpfColortable.CADRG_COLORS - 1; - } - if (tableVal2 >= RpfColortable.CADRG_COLORS) { - tableVal2 = RpfColortable.CADRG_COLORS - 1; - } - int pixindex = (i + t) * 256 + j + e; - pixels[pixindex] = (byte) tableVal1; - pixels[pixindex + 4] = (byte) tableVal2; - } // for e - } // for t - } /* for j */ - } // for i - return pixels; - } /* else */ - } - - /** - * Decompress a subframe into an array of ints suitable for a direct color - * model image. (argb format) - * - * @param x the x coord for the subframe - * @param y the y coord for the subframe - * @param colortable the colortable to use with this image. If null, the - * RpfColortable from the frame will be used. - */ - public int[] decompressSubframe(int x, int y, RpfColortable colortable) { - // Convert x,y to the subframe index in the frame - they come - // in as - // cache subframe indexes - x %= 6; - y %= 6; - - // used to keep track of location into compressedSubframe - // array. - int readptr = 0; - - // and the compressedSubframe array - byte[] compressedSubframe = this.compressedSubframe[y][x]; - - if (colortable == null) { - colortable = this.colortable; - } - - /* - * This should never occur since all subframes should be present - */ - /* - * But if it does occur, just put up black pixels on the screen - */ - if ((compressedSubframe == null) || masked[y][x]) { - return null; - } else { // Normal pixel */ - int[] pixels = new int[256 * 256]; - for (int i = 0; i < 256; i += 4) { - for (int j = 0; j < 256; j += 8) { - int firstByte = compressedSubframe[readptr++] & 0xff; - int secondByte = compressedSubframe[readptr++] & 0xff; - int thirdByte = compressedSubframe[readptr++] & 0xff; - - // because dealing with half-bytes is hard, we - // uncompress two 4x4 tiles at the same time. (a - // 4x4 tile compressed is 12 bits ) - - /* Get first 12-bit value as index into VQ table */ - int val1 = (firstByte << 4) | (secondByte >> 4); - /* Get second 12-bit value as index into VQ table */ - int val2 = ((secondByte & 0x000F) << 8) | thirdByte; - for (int t = 0; t < 4; t++) { - for (int e = 0; e < 4; e++) { - int tableVal1 = table[t][val1][e] & 0xff; - int tableVal2 = table[t][val2][e] & 0xff; - if (tableVal1 >= RpfColortable.CADRG_COLORS) { - tableVal1 = RpfColortable.CADRG_COLORS - 1; - } - if (tableVal2 >= RpfColortable.CADRG_COLORS) { - tableVal2 = RpfColortable.CADRG_COLORS - 1; - } - int pixindex = (i + t) * 256 + j + e; - pixels[pixindex] = colortable.colors[tableVal1].getRGB(); - pixels[pixindex + 4] = colortable.colors[tableVal2].getRGB(); - } // for e - } // for t - } /* for j */ - } // for i - return pixels; - } /* else */ - } - - public static void main(String[] argv) { - Debug.init(); - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("RpfFrame"); - - ap.add("attributes", "Only write out the attributes for this frame."); - ap.add("view", "Only bring up a window with the frame image."); - ap.add("frame", "Path to the frame to view. \"-frame\" only needed if other arguments are used.", 1); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String arg[]; - boolean viewAttributes = false; - arg = ap.getArgValues("attributes"); - if (arg != null) { - viewAttributes = true; - Debug.put("rpfframe"); - Debug.put("rpfdetail"); - } - - boolean viewFrame = false; - arg = ap.getArgValues("view"); - if (arg != null) { - viewFrame = true; - } - - RpfFrame rpfFrame; - - arg = ap.getArgValues("frame"); - if (arg != null) { - rpfFrame = new RpfFrame(arg[0]); - if (viewFrame) { - rpfFrame.view(); - } - } else { - if (viewAttributes == false) { - Debug.put("rpfframe"); - Debug.put("rpfdetail"); - } - rpfFrame = new RpfFrame(argv[0]); - rpfFrame.view(); - } - } - - /** - * A quick hack to pop up a window that displays the entire frame image. - */ - public void view() { - int height = 256; - int width = 256; - - BufferedImage bigImage = new BufferedImage(width * 6, height * 6, BufferedImage.TYPE_INT_RGB); - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - Graphics g = ge.createGraphics(bigImage); - Toolkit tk = Toolkit.getDefaultToolkit(); - - for (int x = 0; x < 6; x++) { - for (int y = 0; y < 6; y++) { - int[] pixels = decompressSubframe(x, y, colortable); - - java.awt.Image bitmap = tk.createImage(new MemoryImageSource(width, height, pixels, 0, width)); - - g.drawImage(bitmap, x * 256, y * 256, null); - } - } - - JLabel picture = new JLabel(new ImageIcon(bigImage)); - JFrame frame = com.bbn.openmap.util.PaletteHelper.getPaletteWindow(picture, "RPF Frame", null); - frame.setSize(new Dimension(500, 500)); - frame.setVisible(true); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameCacheHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameCacheHandler.java deleted file mode 100644 index f432a2473..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameCacheHandler.java +++ /dev/null @@ -1,718 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameCacheHandler.java,v $ -// $RCSfile: RpfFrameCacheHandler.java,v $ -// $Revision: 1.13 $ -// $Date: 2007/02/26 17:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/** - * Modifications: - * - * 1. Changed getCoverage() - * - */ - -package com.bbn.openmap.layer.rpf; - -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The RpfFrameCacheHandler does everything involved with handling RAW RPF - * frames. If used locally, it can also deal with filling the role of - * RpfFrameProvider. You create one of these with the paths to the RPF - * directories, and then hand it to something that needs a RpfFrameProvider, or - * that acts like one. - */ -public class RpfFrameCacheHandler - extends CacheHandler - implements RpfFrameProvider { - - /* Default frame cache size. */ - public final static int FRAME_CACHE_SIZE = 5; - /** Colortable used on the frames. */ - protected RpfColortable colortable; - - /** For future use... */ - protected boolean Dchum = true; - /** Special outlining for chummed subframes */ - protected boolean outlineChum = false; - /** The Table of Contents files, parsed and ready to use. */ - protected RpfTocHandler[] tocs; - /** View and display attributes for the data. */ - protected RpfViewAttributes viewAttributes = new RpfViewAttributes(); - - /** - * The default constructor. - * - * @param RpfPaths the directory paths to the RPF directories. - */ - public RpfFrameCacheHandler(String[] RpfPaths) { - this(RpfPaths, FRAME_CACHE_SIZE); - } - - /** - * The constructor to use if you want to modify the number of frames held in - * the cache.. - * - * @param RpfPaths the directory paths to the RPF directories. - */ - public RpfFrameCacheHandler(String[] RpfPaths, int max_size) { - super(max_size); - tocs = createTocHandlers(RpfPaths); - colortable = new RpfColortable(); - } - - /** - * When you pre-initialize the RpfTocHandlers before giving them to the - * RpfFrameCacheHandler. - */ - public RpfFrameCacheHandler(RpfTocHandler[] tocHandlers) { - tocs = tocHandlers; - colortable = new RpfColortable(); - } - - // public void finalize() { - // Debug.message("gc", "RpfFrameCacheHandler: getting GC'd"); - // } - - /** - * RpfFrameProvider interface method. If this is being used as a frame - * provider, it's local, right? - */ - public boolean needViewAttributeUpdates() { - return false; - } - - /** - * Should only be set via the object it is sending frame data to. Don't send - * in a null value, since this is assumed to be valid in other parts of the - * code. - */ - public void setViewAttributes(RpfViewAttributes va) { - viewAttributes = va; - - if (va != null && colortable != null) { - colortable.setOpaqueness(va.opaqueness); - colortable.setNumColors(va.numberOfColors); - } - } - - /** - * RpfFrameProvider interface method. Return all the RpfCoverageBoxes that - * fall in the area of interest. - * - * @param ullat NW latitude. - * @param ullon NW longitude. - * @param lrlat SE latitude. - * @param lrlon SE longitude - * @param proj projection to use for zone decisions. - * @param chartSeries RpfProductInfo.seriesCode entry. - * @return Vector of RpfCoverageBoxes. - */ - public Vector getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection proj, String chartSeries) { - - Vector coverages = new Vector(); - for (RpfTocHandler toc : tocs) { - - // Check the tochandlers for differences, and reload them - // if necessary. - if (toc.hasChanged()) - toc.reload(); - if (!toc.isValid()) - continue; - - toc.getCatalogCoverage(ullat, ullon, lrlat, lrlon, proj, chartSeries, coverages); - } - - return coverages; - } - - /** - * Given an area and a two-letter chart series code, find the percentage of - * coverage on the map that that chart series can offer. If you want specific - * coverage information, use the getCatalogCoverage call. Don't send a chart - * series code of ANY, since that doesn't make sense. - * - * @param ullat NW latitude. - * @param ullon NW longitude. - * @param lrlat SE latitude. - * @param lrlon SE longitude - * @param p projection to use for zone decisions. - * @param chartSeries RpfProductInfo.seriesCode entry. - * @return percentage of map covered by specific chart type. - * @see #getCatalogCoverage - */ - public float getCalculatedCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p, String chartSeries) { - - if (chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY)) { - return 0f; - } - - Vector results = getCatalogCoverage(ullat, ullon, lrlat, lrlon, p, chartSeries); - - int size = results.size(); - - if (size == 0) { - return 0f; - } - - // Now interpret the results and figure out the real total - // percentage coverage for the chartSeries. First need to - // figure out the current size of the subframes. Then create - // a boolean matrix of those subframes that let you figure out - // how many of them are available. Calculate the percentage - // off that. - int i, x, y; - - double frameLatInterval = Double.MAX_VALUE; - double frameLonInterval = Double.MAX_VALUE; - RpfCoverageBox rcb; - for (i = 0; i < size; i++) { - rcb = (RpfCoverageBox) results.elementAt(i); - if (rcb.subframeLatInterval < frameLatInterval) { - frameLatInterval = rcb.subframeLatInterval; - } - if (rcb.subframeLonInterval < frameLonInterval) { - frameLonInterval = rcb.subframeLonInterval; - } - } - - if (frameLatInterval == Double.MAX_VALUE || frameLonInterval == Double.MAX_VALUE) { - return 0.0f; - } - - int numHFrames = (int) Math.ceil((lrlon - ullon) / frameLonInterval); - int numVFrames = (int) Math.ceil((ullat - lrlat) / frameLatInterval); - - boolean[][] coverage = new boolean[numHFrames][numVFrames]; - for (i = 0; i < size; i++) { - - rcb = (RpfCoverageBox) results.elementAt(i); - if (rcb.percentCoverage == 100) { - return 1.0f; - } - - for (y = 0; y < numVFrames; y++) { - for (x = 0; x < numHFrames; x++) { - // degree location of indexs - float yFrameLoc = (float) (lrlat + (y * frameLatInterval)); - float xFrameLoc = (float) (ullon + (x * frameLonInterval)); - if (coverage[x][y] == false) { - if (rcb.within(yFrameLoc, xFrameLoc)) { - coverage[x][y] = true; - } - } - } - } - } - - float count = 0; - - for (y = 0; y < numVFrames; y++) { - for (x = 0; x < numHFrames; x++) { - if (coverage[x][y] == true) { - // System.out.print("X"); - count++; - } else { - // System.out.print("."); - } - } - // System.out.println(); - } - - return count / (float) (numHFrames * numVFrames); - } - - /** - * Given a projection which describes the map (or area of interest), return - * the best RpfTocEntry, from all the A.TOC, that covers the area. - * RpfFrameProvider method. - * - * 1. Fixed bug that was preventing it from actually returning the best - * coverage box in the first position of the Vector. 2. Prevented the method - * from returning early when it found a box that claimed perfect coverage. - * This was causing problems in some areas, where boxes that claimed coverage - * didn't actually have it. This could be a data problem, so maybe we can add - * the early return back in in the future. 3. Changed < to <= below. 4. - * Iterates thru list returned by RpcTocHandler since the return type for - * getBestCoverageEntry changed from RpfTocEntry to List. - * - * @param ullat NW latitude. - * @param ullon NW longitude. - * @param lrlat SE latitude. - * @param lrlon SE longitude - * @param proj CADRG projection to use for zone decisions. - * @return Vector of RpfCoverageBoxes. - */ - public Vector getCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection proj) { - - Debug.message("rpf", "RpfFrameCacheHandler: getCoverage()"); - - Vector coverageBoxes = new Vector(); - - int count = -1; - - for (RpfTocHandler toc : tocs) { - count++; - - // Check the toc handlers for differences, and reload them - // if necessary. - if (toc.hasChanged()) - toc.reload(); - - if (!toc.isValid()) - continue; - - // NOTE: returning a list of best coverage entries. - // Added inner loop to deal with iterating over list of - // results. - List coverageEntries = toc.getBestCoverageEntry(ullat, ullon, lrlat, lrlon, proj, viewAttributes); - - for (RpfTocEntry currentEntry : coverageEntries) { - - // This is a test for total coverage. If we get total - // coverage of an exact scale match, just return this - // coverage box right away. If the scale is not a - // perfect - // match, then we will return the box that has - // complete - // coverage with the best scale. A boundaryHit of 8 - // means - // total coverage. Trust me. - if (currentEntry != null) { - - if (Debug.debugging("rpftoc")) { - System.out.println("RFCH: Toc " + count + " returned an entry"); - } - - RpfCoverageBox currentCoverage = currentEntry.coverage; - - // NOTE: - // removed because some areas had boxes that - // claimed perfect - // coverage but didn't actually have it. - // This could be a data problem, but in any case, - // this work-around returns all relevant coverage - // boxes. - // if (currentCoverage.percentCoverage >= 100f && - // scaleDifference(proj, currentCoverage) == 0) { - // coverageBoxes.removeAllElements(); - // coverageBoxes.addElement(currentCoverage); - // return coverageBoxes; - // } else { - - // You now ought to at least make sure that the - // scales are the same for all A.TOCs. That way, - // the subframe spacing will be the same. Put the - // best coverage (smallest scale difference) at - // the front of the list, and whittle it down from - // there. - - Object[] coverageArray = new Object[coverageBoxes.size()]; - coverageBoxes.copyInto(coverageArray); - coverageBoxes.removeAllElements(); - int size = coverageArray.length; - - // Set this here in case the vector is empty... - // float currentScale = currentEntry.info.scale; - - if (size == 0) { - coverageBoxes.addElement(currentCoverage); - - } else { - boolean addedCurrent = false; - boolean okToAddCurrent = true; - for (int j = 0; j < size; j++) { - RpfCoverageBox rcb = (RpfCoverageBox) coverageArray[j]; - - if (!addedCurrent) { - if (j == 0) { - - // So first, check to see if the - // current - // coverage is a better match than - // the - // current best, first considering - // scale, and then considering - // coverage. - - // NOTE: - // Changed < to <=, because < - // gives - // higher priority to whatever is - // first in the - // list. I.e. if 2 boxes had the - // same - // scale difference but the second - // one actually - // had better coverage, it would - // have gotten - // discarded. - if (scaleDifference(proj, currentCoverage) <= scaleDifference(proj, rcb) - && currentCoverage.percentCoverage >= rcb.percentCoverage) { - coverageBoxes.addElement(currentCoverage); - addedCurrent = true; - if (currentCoverage.scale == rcb.scale) { - coverageBoxes.addElement(rcb); - } else { - // if these scales don't - // match, none of the - // subsequent rcbs will - // either. We're done. - break; - } - } else { // rcb percent coverage - // is better - coverageBoxes.addElement(rcb); - } - } else { // j!= 0 - if (currentCoverage.percentCoverage >= rcb.percentCoverage) { - if (((RpfCoverageBox) coverageBoxes.get(0)).scale == currentCoverage.scale) { - - coverageBoxes.add(currentCoverage); - addedCurrent = true; - } else { - - okToAddCurrent = false; - } - coverageBoxes.add(rcb); - } else { // rcb percent coverage - // is better - // we already know that scale - // matches since it was - // added previously - coverageBoxes.add(rcb); - } - } - } else { // currentCoverage already added; - // all we need to do is add current - // rcb if scale matches - if (((RpfCoverageBox) coverageBoxes.get(0)).scale == rcb.scale) { - coverageBoxes.add(rcb); - } else { - } - } - } - // Add current if not added already and if - // scale matches. - // It's possible that we performed this check - // already -- - // i.e. if currentCoverage had better % - // coverage - // than someone else but wasn't added because - // of the scale. - // If that happened, then okToAddCurrent is - // false. - if (!addedCurrent && okToAddCurrent) { - if (((RpfCoverageBox) coverageBoxes.get(0)).scale == currentCoverage.scale) { - coverageBoxes.add(currentCoverage); - } else { - } - } - } - // } - } else { - if (Debug.debugging("rpftoc")) { - System.out.println("RFCH: Toc " + count + " did NOT return an entry"); - } - } - } - } - - return coverageBoxes; - } - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame and return the attribute information. The tocNumber and - * entryNumber are given within the RpfCoverageBox received from a - * getCoverage call. - * - * @param tocNumber the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber the RpfTocEntry id for a RpfTocHandler for a particular - * frame provider. - * @param x the horizontal subframe index, from the left side of a boundary - * rectangle of the entry. - * @param y the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage - * @return string. - */ - public String getSubframeAttributes(int tocNumber, int entryNumber, int x, int y) { - - if (!tocs[tocNumber].isValid()) - return null; - - RpfTocEntry entry = tocs[tocNumber].entries[entryNumber]; - - /* If beyond the image boundary, forget it */ - if (y < 0 || x < 0 || entry == null || y >= entry.vertFrames * 6 || x >= entry.horizFrames * 6) { - - return null; - } - - if (!entry.isFramesLoaded()) { - tocs[tocNumber].loadFrameInformation(entry); - } - RpfFrameEntry frameEntry = entry.getFrame(y / 6, x / 6); - - /* Get the right frame from the frame cache */ - RpfFrame frame = (RpfFrame) get(frameEntry); - - if (frame == null) - return null; - - /* - * This should never fail, since all subframes should be present - */ - return frame.getReport(x, y, frameEntry, entry.Cib); - } - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame/subframe data, decompress it, and return image pixels. The - * tocNumber and entryNumber are given within the RpfCoverageBox received - * from a getCoverage call. - * - * @param tocNumber the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber the RpfTocEntry id for a RpfTocHandler for a particular - * frame provider. - * @param x the horizontal subframe index, from the left side of a boundary - * rectangle of the entry. - * @param y the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage - * @return integer pixel data. - */ - public int[] getSubframeData(int tocNumber, int entryNumber, int x, int y) { - - if (!tocs[tocNumber].isValid()) { - return null; - } - - RpfTocEntry entry = tocs[tocNumber].entries[entryNumber]; - - /* If beyond the image boundary, forget it */ - if (y < 0 || x < 0 || entry == null || y >= entry.vertFrames * 6 || x >= entry.horizFrames * 6) { - return null; - } - - if (!entry.isFramesLoaded()) { - tocs[tocNumber].loadFrameInformation(entry); - } - RpfFrameEntry frameEntry = entry.getFrame(y / 6, x / 6); - - /* Get the right frame from the frame cache */ - RpfFrame frame = (RpfFrame) get(frameEntry); - - if (frame == null) { - return null; - } - - checkColortable(frame, frameEntry, entry, tocNumber, entryNumber); - - /* - * This should never fail, since all subframes should be present - */ - return frame.decompressSubframe(x, y, colortable); - } - - public RpfIndexedImageData getRawSubframeData(int tocNumber, int entryNumber, int x, int y) { - if (!tocs[tocNumber].isValid()) { - return null; - } - - RpfTocEntry entry = tocs[tocNumber].entries[entryNumber]; - - /* If beyond the image boundary, forget it */ - if (y < 0 || x < 0 || entry == null || y >= entry.vertFrames * 6 || x >= entry.horizFrames * 6) { - - return null; - } - if (!entry.isFramesLoaded()) { - tocs[tocNumber].loadFrameInformation(entry); - } - RpfFrameEntry frameEntry = entry.getFrame(y / 6, x / 6); - - /* Get the right frame from the frame cache */ - RpfFrame frame = (RpfFrame) get(frameEntry); - - if (frame == null) - return null; - - checkColortable(frame, frameEntry, entry, tocNumber, entryNumber); - - RpfIndexedImageData riid = new RpfIndexedImageData(); - riid.imageData = frame.decompressSubframe(x, y); - riid.colortable = colortable.colors; - return riid; - } - - /** - * Take a bunch of stuff that has already been calculated, and then figure - * out if a new colortable is needed. If it is, load it up with info. Called - * from two different places, which is why it exists. - * - * It's been determined that, for each subframe, the colortable from it's - * parent frame should be used. Although RPF was designed and specified that - * the colortable should be constant across zones, that's not always the - * case. - */ - protected void checkColortable(RpfFrame frame, RpfFrameEntry frameEntry, RpfTocEntry entry, int tocNumber, int entryNumber) { - // Colortables are constant across chart types and zones. If - // the current chart type and zone don't match the colortable, - // read the proper one from the frame. All the frames inside - // an entry, which is a boundary box, will certainly share a - // colortable. - // if (colortable.colors == null || - // !colortable.isSameATOCIndexes(tocNumber, entryNumber)) { - - // You know, we don't need to make the check - we should just - // do this every time - the colortable is already created for - // the frame, so we might as well use what we know to be good - // for each subframe. - - if (true) { - - if (Debug.debugging("rpf")) { - Debug.output("RpfFrameCacheHandler: getting new colors"); - Debug.output("RpfFrameCacheHandler: getting CIB colors = " + entry.Cib); - } - // Seems like there ought to be a better way to do this. - colortable.setFrom(frame.getColortable()); - colortable.setCib(entry.Cib); - colortable.setATOCIndexes(tocNumber, entryNumber); - colortable.zone = entry.zone; - colortable.seriesCode = entry.info.seriesCode; - } - - if (viewAttributes != null) { - // this is useless... - // colortable.setNumColors(viewAttributes.numberOfColors); - - colortable.setOpaqueness(viewAttributes.opaqueness); - } - } - - /** - * Set up the A.TOC files, to find out what coverage there is. - * - * @param RpfPaths the paths to the RPF directories. - * @return the RpfTocHandlers for the A.TOCs. - */ - public static RpfTocHandler[] createTocHandlers(String[] RpfPaths) { - - RpfTocHandler[] tocs = new RpfTocHandler[(RpfPaths != null ? RpfPaths.length : 0)]; - if (RpfPaths != null) { - for (int i = 0; i < tocs.length; i++) { - tocs[i] = new RpfTocHandler(RpfPaths[i], i); - } - } - return tocs; - } - - /** - * A customized way to retrieve a frame from the cache, using a - * RpfFrameEntry. A RpfFrameEntry is the way to get the Dchum capability - * kicked off in the frame. If you don't care about Dchum, use the other get - * method. CacheHandler method. - */ - public Object get(RpfFrameEntry rfe) { - - CacheObject ret = searchCache(rfe.framePath); - if (ret != null) - return ret.obj; - - ret = load(rfe); - if (ret == null) - return null; - - if (Debug.debugging("rpfdetail")) { - System.out.println(rfe); - } - - replaceLeastUsed(ret); - return ret.obj; - } - - public CacheObject load(Object key) { - - if (key instanceof RpfFrameEntry) { - - RpfFrameEntry rfe = (RpfFrameEntry) key; - if (!rfe.exists) { - if (Debug.debugging("rpf")) { - System.out.println("RpfFrameCacheHandler: Frame doesn't exist!: " + rfe.framePath); - } - return null; - } - - if (Debug.debugging("rpf")) { - Debug.output("RpfFrameCacheHandler: Loading Frame " + rfe.framePath); - } - - RpfFrame frame = new RpfFrame(rfe); - if (frame.isValid()) { - return new CacheObject(rfe.framePath, frame); - } else { - if (Debug.debugging("rpf")) { - Debug.error("RpfFrameCacheHandler: Couldn't find frame /" + rfe.framePath + "/ (" + rfe.framePath.length() - + " chars)"); - } - rfe.exists = false; - } - } - return null; - } - - /** - * Cachehandler method. - */ - public void resizeCache(int max_size) { - resetCache(max_size); - } - - /** - * CacheHandler method. Need to clear memory, get gc moving, and ready for - * new objects - */ - public void resetCache() { - super.resetCache(); - Debug.message("rpf", "RpfFrameCacheHandler: reset frame cache."); - } - - public static float scaleDifference(Projection proj, RpfCoverageBox box) { - return (float) (Math.abs(proj.getScale() - box.scale)); - } - - public RpfColortable getColortable() { - return colortable; - } - - public void setColortable(RpfColortable colortable) { - this.colortable = colortable; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameEntry.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameEntry.java deleted file mode 100644 index bb6f6ad3a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameEntry.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameEntry.java,v $ -// $RCSfile: RpfFrameEntry.java,v $ -// $Revision: 1.4 $ -// $Date: 2006/08/17 15:19:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -/** - * The RpfFrameEntry is a description of a RPF frame file that can be used to - * quickly gain status about the frame. It is mainly created by the table of - * contents handler (RpfTocHandler), and passed, in an array of brothers in a - * RpfTocEntry, to the cache handler. The cache handler will use the RpfTocEntry - * to figure out which frames are needed to get the subframes it wants, and the - * RpfFrameEntry supplies information to assist in loading that frame file. - */ -public class RpfFrameEntry { - - /** Whether the file exists or not. */ - public boolean exists; - /** Real path to the frame file. */ - public String framePath; - - /** - * Index of the start of the frame file. To get the frame name, call - * framePath.substring(filenameIndex). - */ - public short filenameIndex = 0; - /** - * Index to the start of the RPF directory in the name. To get the RPF - * directory without the following slash, call framePath.substring(0, - * rpfdirIndex + 2). Use 3 to get the slash. You can use this index + 3 as - * the startIndex to get the relative path to the file from the RPF dir, - * without the slash. - *

- * If this index is -1, that means that the complete pathname was specified - * in the OpenMap-generated A.TOC file, and you'll have to do a search for - * the last RPF instance yourself to get that index. - */ - public short rpfdirIndex = -1; - - public RpfFrameEntry() { - exists = false; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("Is Located At: ").append(framePath).append("\n"); - s.append("Exists: ").append(exists).append("\n"); - return s.toString(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameProvider.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameProvider.java deleted file mode 100644 index 1c9f154cd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfFrameProvider.java +++ /dev/null @@ -1,133 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameProvider.java,v $ -// $RCSfile: RpfFrameProvider.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/05/23 20:08:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.util.List; - -import com.bbn.openmap.proj.Projection; - -/** - * The RpfFrameProvider describes an interface to an object that can provide - * information about RPF coverage over a certain area, and also retrieve data - * from the RPF frame files. - */ -public interface RpfFrameProvider { - - /** - * Returns true if the view attributes should be set if they change at the - * RpfCacheHandler/RpfCacheManager. If the source of the data is a server, - * this should return yes. If the source is local, the view attributes will - * be a shared object and updates are not necessary. - */ - public boolean needViewAttributeUpdates(); - - /** - * Set the RpfViewAttribute object parameters, which describes a lot about - * what you'll be asking for later. - */ - public void setViewAttributes(RpfViewAttributes rva); - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know how to locate and ask for - * RpfSubframes. - */ - public List getCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p); - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know what bounding boxes of data are - * available. - * - * @param ullat - * upper lat - * @param ullon - * left lon - * @param lrlat - * lower lat - * @param lrlon - * right lon - * @param chartSeries - * can be null to see all/any. - */ - public List getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p, - String chartSeries); - - /** - * Given an area and a two-letter chart series code, find the percentage of - * coverage on the map that that chart series can offer. If you want - * specific coverage information, use the getCatalogCoverage call. - * - * @see #getCatalogCoverage(double, double, double, double, Projection, String) - */ - public float getCalculatedCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p, - String chartSeries); - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame/subframe data, decompress it, and return image pixels. The - * tocNumber and entryNumber are given within the RpfCoverageBox received - * from a getCoverage call. - * - * @param tocNumber - * the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber - * the RpfTocEntry id for a RpfTocHandler for a particular frame - * provider. - * @param x - * the horizontal subframe index, from the left side of a - * boundary rectangle of the entry. - * @param y - * the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(double, double, double, double, Projection) - * @return integer pixel data. - */ - public int[] getSubframeData(int tocNumber, int entryNumber, int x, int y); - - public RpfIndexedImageData getRawSubframeData(int tocNumber, int entryNumber, int x, int y); - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame and return the attribute information. The tocNumber and - * entryNumber are given within the RpfCoverageBox received from a - * getCoverage call. - * - * @param tocNumber - * the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber - * the RpfTocEntry id for a RpfTocHandler for a particular frame - * provider. - * @param x - * the horizontal subframe index, from the left side of a - * boundary rectangle of the entry. - * @param y - * the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(double, double, double, double, Projection) - * @return string. - */ - public String getSubframeAttributes(int tocNumber, int entryNumber, int x, int y); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfHeader.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfHeader.java deleted file mode 100644 index 6154a3340..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfHeader.java +++ /dev/null @@ -1,240 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfHeader.java,v $ -// $RCSfile: RpfHeader.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and to Theron Tock, who wrote the software, and - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used with permission. - */ - -package com.bbn.openmap.layer.rpf; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * Reads the part of the RpfFrame that gives a basic location map to the - * locations of the file. - */ -public class RpfHeader { - - public static final int RPF_DATE_LOCATION = 31; - public static final int HEADER_SECTION_LENGTH = 48; - public static final int TOC_NITF_HEADER_LENGTH = 410; - public static final int FRAME_SHORT_NITF_HEADER_LENGTH = 413; - public static final int FRAME_LONG_NITF_HEADER_LENGTH = 426; - - public boolean endian = false; - public short headerSectionLength; - public String filename; // 12 chars - public byte neww; // new/replacement/update indicator - public String standardNumber; // 15 chars - public String standardDate; // 8 chars - public char classification; // 1 char - public String country; // 2 chars - public String release; // 2 chars - public int locationSectionLocation; - - public RpfHeader() { - } - - /** - * Starts at the beginning of the file and handles the NITF header if it is - * there. - */ - public boolean read(BinaryFile binFile) { - - boolean nitf = new com.bbn.openmap.layer.nitf.NitfHeader().read(binFile); - - // If something failed, try it the old way... - if (!nitf) { - try { - binFile.seek(0); - int headerOffset = handleNITFHeader(binFile); - - if (headerOffset < 0) - return false; - else - binFile.seek(headerOffset); - - } catch (IOException e) { - Debug.error("RpfHeader: File IO Error while reading header information:\n" + e); - return false; - } - } - - return readHeader(binFile); - } - - /** Assumes that the binFile is set to the header location. */ - public boolean readHeader(BinaryFile binFile) { - - try { - // Read header - byte[] endianByte = binFile.readBytes(1, false); - if (endianByte[0] > 0) - endian = true; - - binFile.byteOrder(!endian); // opposite meanings - - headerSectionLength = binFile.readShort(); - - byte[] filenameArray = binFile.readBytes(12, false); - filename = new String(filenameArray); - - // Read rest of header so we can write it later - byte[] newwByte = binFile.readBytes(1, false); - neww = newwByte[0]; - - byte[] standardNumberArray = binFile.readBytes(15, false); - standardNumber = new String(standardNumberArray); - - byte[] standardDateArray = binFile.readBytes(8, false); - standardDate = new String(standardDateArray); - - classification = binFile.readChar(); - - byte[] countryArray = binFile.readBytes(2, false); - country = new String(countryArray); - - byte[] releaseArray = binFile.readBytes(2, false); - release = new String(releaseArray); - - locationSectionLocation = binFile.readInteger(); - - if (Debug.debugging("rpfheader")) { - Debug.output(this.toString()); - } - - } catch (IOException e) { - Debug.error("RpfHeader: File IO Error while reading header information:\n" + e); - return false; - } catch (FormatException f) { - Debug.error("RpfHeader: File IO Format error while reading header information:\n" + f); - return false; - } - - return true; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfHeader: endian is ").append(endian).append("\n"); - s.append("RpfHeader: header section length = ").append(headerSectionLength).append("\n"); - s.append("RpfHeader: filename = ").append(filename).append("\n"); - s.append("RpfHeader: neww = ").append(neww).append("\n"); - s.append("RpfHeader: standard number = ").append(standardNumber).append("\n"); - s.append("RpfHeader: standard date = ").append(standardDate).append("\n"); - s.append("RpfHeader: classification = ").append(classification).append("\n"); - s.append("RpfHeader: country = ").append(country).append("\n"); - s.append("RpfHeader: release = ").append(release).append("\n"); - s.append("RpfHeader: location section location = ").append(locationSectionLocation).append("\n"); - return s.toString(); - } - - /** - * Checks to see if the file is in NITF or not, and then puts the file - * pointer in the right place to start reading the header for the file. If - * the file is in NITF format, it skips the NITF header, and if it isn't, it - * resets the pointer to the beginning. - */ - public int handleNITFHeader(BinaryFile binFile) { - try { - - byte[] nitfArray = binFile.readBytes(4, false); - String nitf = new String(nitfArray); - - binFile.seek(RPF_DATE_LOCATION); - nitfArray = binFile.readBytes(2, false); - nitf = new String(nitfArray); - - if (nitf.equalsIgnoreCase("19") || nitf.equalsIgnoreCase("20")) - return 0; - - binFile.seek(RPF_DATE_LOCATION + TOC_NITF_HEADER_LENGTH); - nitfArray = binFile.readBytes(2, false); - nitf = new String(nitfArray); - - if (nitf.equalsIgnoreCase("19") || nitf.equalsIgnoreCase("20")) - return TOC_NITF_HEADER_LENGTH; - - binFile.seek(RPF_DATE_LOCATION + FRAME_SHORT_NITF_HEADER_LENGTH); - nitfArray = binFile.readBytes(2, false); - nitf = new String(nitfArray); - - if (nitf.equalsIgnoreCase("19") || nitf.equalsIgnoreCase("20")) - return FRAME_SHORT_NITF_HEADER_LENGTH; - - binFile.seek(RPF_DATE_LOCATION + FRAME_LONG_NITF_HEADER_LENGTH); - nitfArray = binFile.readBytes(2, false); - nitf = new String(nitfArray); - - if (nitf.equalsIgnoreCase("19") || nitf.equalsIgnoreCase("20")) - return FRAME_LONG_NITF_HEADER_LENGTH; - - } catch (IOException e) { - Debug.error("RpfHeader: File IO Error while handling NITF header:\n" + e); - return -1; - } catch (FormatException f) { - Debug.error("RpfHeader: File IO Format error while reading header information:\n" + f); - return -1; - } - - return -1; - } - - public static void main(String[] args) { - if (args.length != 1) { - System.out.println("Usage: java RpfHeader "); - return; - } - - File file = new File(args[0]); - BinaryFile binFile = null; - try { - binFile = new BinaryBufferedFile(file); - // binFile = new BinaryFile(file); - RpfHeader header = new RpfHeader(); - if (header.read(binFile)) - System.out.println(header); - else { - System.out.println("RpfHeader: NOT read successfully!"); - } - } catch (FileNotFoundException e) { - System.err.println("RpfHeader: file " + args[0] + " not found"); - System.exit(1); - } catch (IOException ioe) { - System.err.println("RpfHeader: File IO Error while handling NITF header:"); - System.err.println(ioe); - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfIndexedImageData.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfIndexedImageData.java deleted file mode 100644 index 28811862e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfIndexedImageData.java +++ /dev/null @@ -1,32 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfIndexedImageData.java,v -// $ -// $RCSfile: RpfIndexedImageData.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.awt.Color; - -public class RpfIndexedImageData { - public byte[] imageData; - public Color[] colortable; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfLayer.java deleted file mode 100644 index 3b11f5e25..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfLayer.java +++ /dev/null @@ -1,801 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfLayer.java,v $ -// $RCSfile: RpfLayer.java,v $ -// $Revision: 1.23 $ -// $Date: 2008/09/17 20:47:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; - -/** - * The RpfLayer fills the screen with RPF data. There is also a tool available - * that allows you to see the coverage of the available data. To view theimages, - * the projection of the map has to be set in the ARC projection, which OpenMap - * calls the CADRG projection. The RpfLayer can use several RPF directories at - * the same time, and doesn't require that the data actually be there at - * runtime. That way, you can give a location where the data may be mouted - * during runtime(i.e. CDROM) and the layer will still use the data. The scale - * of the projection does not necessarily have to match the scale of a map - * series for that series to be displayed. There are options, set in the - * RpfViewAttributes, that allow scaling of the RPF images to match the map - * scale. - *

- * - * The RpfLayer uses the RpfCacheManager to get the images it needs to display. - * Whenever the projection changes, the cache manager takes the new projection - * and creates a OMGraphicList with the new image frames and attribute text. - *

- * - * The RpfLayer gets its initial settings from properties. This should be done - * right after the RpfLayer is created. The properties list contains the - * location of the RPF directories, the opaqueness of the images, the number of - * colors to use, and whether to show the images and/or attributes by default. - * An example of the RpfLayer properties: - *

- * - *

- * 
- * 
- *           #-----------------------------
- *           # Properties for RpfLayer
- *           #-----------------------------
- *           # Mandatory properties
- *           # This property should reflect the paths to the RPF directories
- *           rpf.paths=/usr/local/matt/data/RPF;/usr/local/matt/data/CIB/RPF
- *           
- *           # Optional Properties - the default will be set if these are not 
- *           # included in the properties file: 
- *           # Number between 0-255: 0 is transparent, 255 is opaque.  255 is default.
- *           rpf.opaque=128
- *           
- *           # Number of colors to use on the maps - 16, 32, 216.  216 is default.
- *           rpf.numberColors=216
- *           
- *           # Display maps on startup.  Default is true.
- *           rpf.showMaps=true
- *           
- *           # Display attribute information on startup.  Default is false.
- *           rpf.showInfo=false
- *           
- *           # Scale charts to match display scale.  Default is true.
- *           rpf.scaleImages=true
- *           
- *           # The scale factor to allow when scaling images (2x, 4x, also mean 1/2, 1/4).  Default is 4.
- *           rpf.imageScaleFactor=4
- *           
- *           # Delete the cache if the layer is removed from the map.  Default is false.
- *           rpf.killCache=true
- *           # Limit the display to the chart code specified. (GN, JN, ON, TP, etc.).
- *           # Default is ANY
- *           rpf.chartSeries=ANY
- *           # Get the subframe attribute data from the Frame provider.
- *           rpf.autofetchAttributes=false
- *           # Set to true if you want the coverage tool available.
- *           rpf.coverage=true
- *           # Set the subframe cache size. (Number of subframes to hold on to, 256x256 pixels)
- *           rpf.subframeCacheSize=128
- *           # Then also include coverage properties, which are available in the RpfConstants.
- *           #------------------------------------
- *           # End of properties for RpfLayer
- *           #------------------------------------
- * 
- * 
- * 
- * - */ -public class RpfLayer extends OMGraphicHandlerLayer implements ActionListener, RpfConstants, Serializable { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.rpf.RpfLayer"); - protected static Logger rpfLogger = Logger.getLogger("RPF"); - - private static final long serialVersionUID = 1L; - /** - * The main source for the images and attribute information. All requests - * for graphic objects should go through this cache, and it will - * automatically handle getting the frame files, decoding them, and - * returning an object list. - */ - protected transient RpfCacheManager cache = null; - /** The paths to the RPF directories, telling where the data is. */ - protected String[] paths; - /** - * The display attributes for the maps. This object should not be replaced, - * because the caches all look at it, too. Just adjust the parameters within - * it. - * - * @see RpfViewAttributes - */ - protected RpfViewAttributes viewAttributes; - /** Flag to delete the cache if the layer is removed from the map. */ - protected boolean killCache = true; - /** The supplier of frame data. */ - protected RpfFrameProvider frameProvider; - /** The coverage tool for the layer. */ - protected RpfCoverage coverage; - /** Subframe cache size. Default is 40. */ - protected int subframeCacheSize = RpfCacheHandler.SUBFRAME_CACHE_SIZE; - /** Auxiliary subframe cache size. Default is 10. */ - protected int auxSubframeCacheSize = RpfCacheManager.SMALL_CACHE_SIZE; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. Use this construct if you are going to use a - * standard properties file, which will set the paths. - */ - public RpfLayer() { - setName("RPF"); - viewAttributes = new RpfViewAttributes(); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - // setRenderPolicy(new BufferedImageRenderPolicy(this)); - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - - showSubframes(false); - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - * - * @param pathsToRPFDirs - * paths to the RPF directories that hold A.TOC files. - */ - public RpfLayer(String[] pathsToRPFDirs) { - this(); - setPaths(pathsToRPFDirs); - } - - /** - * Set the paths to the RPF directories, which are by default the parents of - * the A.TOC table of contents files. Creates the RpfFrameProvider. - * - * @param pathsToRPFDirs - * Array of strings that list the paths to RPF directories. - */ - public void setPaths(String[] pathsToRPFDirs) { - if (paths != null && pathsToRPFDirs != null && paths.length == pathsToRPFDirs.length) { - // If the paths haven't changed, don't do anything. - boolean same = true; - for (int i = 0; i < paths.length; i++) { - same = same && paths[i].equals(pathsToRPFDirs[i]); - } - - if (same && frameProvider != null) { - return; - } - } - - if (pathsToRPFDirs != null) { - setFrameProvider(new RpfFrameCacheHandler(pathsToRPFDirs)); - } else { - logger.warning("Need RPF directory paths."); - frameProvider = null; - } - paths = pathsToRPFDirs; - - setCoverage(new RpfCoverage(this, frameProvider)); - - this.cache = null; - } - - /** - * Get the paths to the RPF directories. - * - * @return String[] - */ - public String[] getPaths() { - return paths; - } - - /** - * Called when the layer is no longer part of the map. In this case, we - * should disconnect from the server if we have a link. - */ - public void removed(java.awt.Container cont) { - if (killCache) { - rpfLogger.fine("emptying cache!"); - clearCache(); - } - - // need to reset this for when it gets added again, if it was - // removed without the projection actually changing. This - // helps when the cache needs to be rebuilt. - setProjection((Projection) null); - } - - protected void setDefaultValues() { - // defaults - paths = null; - } - - /** - * Set all the RPF properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - setPaths(PropUtils.initPathsFromProperties(properties, prefix + RpfPathsProperty, paths)); - - viewAttributes.setProperties(prefix, properties); - showSubframes(viewAttributes.showInfo); - - subframeCacheSize = PropUtils.intFromProperties(properties, prefix + CacheSizeProperty, subframeCacheSize); - - auxSubframeCacheSize = PropUtils.intFromProperties(properties, prefix + CacheSizeProperty, - auxSubframeCacheSize); - - if (viewAttributes.chartSeries == null) - viewAttributes.chartSeries = RpfViewAttributes.ANY; - - killCache = PropUtils.booleanFromProperties(properties, prefix + KillCacheProperty, killCache); - - if (coverage != null) { - coverage.setProperties(prefix, properties); - } - - resetPalette(); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props - * a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - // find out paths... - String[] p = getPaths(); - StringBuffer pathString = new StringBuffer(); - if (p != null) { - for (int i = 0; i < p.length; i++) { - if (p[i] != null) { - pathString.append(p[i]); - if (i < p.length - 1) { - pathString.append(";"); // separate paths with - // ; - } - } - } - props.put(prefix + RpfPathsProperty, pathString.toString()); - } else { - props.put(prefix + RpfPathsProperty, ""); - } - - props.put(prefix + KillCacheProperty, new Boolean(killCache).toString()); - props.put(prefix + CacheSizeProperty, Integer.toString(subframeCacheSize)); - props.put(prefix + AuxCacheSizeProperty, Integer.toString(auxSubframeCacheSize)); - - viewAttributes.setPropertyPrefix(prefix); - viewAttributes.getProperties(props); - - if (coverage == null) { - RpfCoverage cov = new RpfCoverage(this, frameProvider); - cov.setProperties(prefix, new Properties()); - cov.getProperties(props); - } else { - coverage.getProperties(props); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list - * a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - String interString; - - interString = i18n.get(RpfLayer.class, RpfPathsProperty, I18n.TOOLTIP, - "Paths to RPF directories. Semi-colon separated paths."); - list.put(RpfPathsProperty, interString); - list.put(RpfPathsProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.MultiDirectoryPropertyEditor"); - interString = i18n.get(RpfLayer.class, RpfPathsProperty, "Data Path"); - list.put(RpfPathsProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, KillCacheProperty, I18n.TOOLTIP, - "Flag to trigger the cache to be cleared when layer is removed from the map."); - list.put(KillCacheProperty, interString); - list.put(KillCacheProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, KillCacheProperty, "Clear Cache"); - list.put(KillCacheProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, CacheSizeProperty, I18n.TOOLTIP, - "Number of frames to hold in the frame cache."); - list.put(CacheSizeProperty, interString); - interString = i18n.get(RpfLayer.class, CacheSizeProperty, "Frame Cache Size"); - list.put(CacheSizeProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, AuxCacheSizeProperty, I18n.TOOLTIP, - "Number of frames to hold in aux. frame caches."); - list.put(AuxCacheSizeProperty, interString); - interString = i18n.get(RpfLayer.class, AuxCacheSizeProperty, "Aux Frame Cache Size"); - list.put(AuxCacheSizeProperty + LabelEditorProperty, interString); - - viewAttributes.getPropertyInfo(list); - - RpfCoverage tmpCov = coverage; - if (tmpCov == null) { - tmpCov = new RpfCoverage(this, frameProvider); - } - - tmpCov.getPropertyInfo(list); - - list.put(initPropertiesProperty, - RpfPathsProperty + " " + KillCacheProperty + " " + CacheSizeProperty + " " + AuxCacheSizeProperty + " " - + viewAttributes.getInitPropertiesOrder() + " " + AddToBeanContextProperty + " " - + AddAsBackgroundProperty + " " + RemovableProperty + " " + CoverageProperty + " " - + tmpCov.getInitPropertiesOrder()); - - return list; - } - - public void resetPalette() { - box = null; - // if (coverage != null) { - // if (coverage.isInUse()) { - // coverage.resetColors(); - // } - // } - - super.resetPalette(); - } - - /** - * Clear the frame cache. - */ - public void clearCache() { - - if (frameProvider instanceof CacheHandler) { - ((CacheHandler) frameProvider).resetCache(); - } - - if (this.cache != null) { - this.cache.setViewAttributes(null); - this.cache.setFrameProvider(null); - this.cache.clearCaches(); - } - - frameProvider = null; - - setList(null); - this.cache = null; - } - - /** - * Set the view attributes for the layer. The frame provider view attributes - * are updated, and the cache is cleared. - * - * @param rva - * the RpfViewAttributes used for the layer. - */ - public void setViewAttributes(RpfViewAttributes rva) { - viewAttributes = rva; - if (this.cache != null) { - this.cache.setViewAttributes(rva); - } - } - - /** - * Get the view attributes or the layer. - * - * @return RpfViewAttributes. - */ - public RpfViewAttributes getViewAttributes() { - return viewAttributes; - } - - /** - * Set the RpfCoverage tool used by the layer. If the view attributes chart - * series setting is not equal to RpfViewAttributes.ANY, then the palette of - * the tool is not shown. - * - * @param cov - * the RpfCoverage tool. - */ - public void setCoverage(RpfCoverage cov) { - coverage = cov; - if (coverage != null) { - if (viewAttributes != null && !viewAttributes.chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY)) { - coverage.setShowPalette(false); - } - coverage.coverageManager = null; - } - } - - /** - * Return the coverage tool used by the layer. - * - * @return RpfCoverage tool. - */ - public RpfCoverage getCoverage() { - return coverage; - } - - /** - * Set the RpfFrameProvider for the layer. Clears out the cache, and the - * frame provider gets the RpfViewAttributes held by the layer. - * - * @param fp - * the frame provider. - */ - public void setFrameProvider(RpfFrameProvider fp) { - frameProvider = fp; - if (this.cache != null) { - this.cache.setFrameProvider(frameProvider); - } - } - - /** - * Return RpfFrameProvider used by the layer. - */ - public RpfFrameProvider getFrameProvider() { - return frameProvider; - } - - /** - * Returns the Vector containing RpfCoverageBoxes that was returned from the - * RpfFrameProvider as a result of the last setCache call. These provide - * rudimentary knowledge about what is being displayed. This vector is from - * the primary cache handler. - * - * @return Vector of RpfCoverageBoxes. - */ - public List getCoverageBoxes() { - return this.cache.getCoverageBoxes(); - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the rpf. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - * @return graphics list of images and attributes. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - OMGraphicList retList = new OMGraphicList(); - retList.setTraverseMode(OMList.FIRST_ADDED_ON_TOP); - - if (frameProvider == null) { - // Assuming running locally - otherwise the - // frameProvider should be set before we get here, - // like in setProperties or in the constructor. - setPaths(paths); - if (frameProvider == null) { - // Doh! no paths were set! - logger.warning(getName() - + ": null frame provider - either no RPF paths were set, or no frame provider was assigned. The RpfLayer has no way to get RPF data."); - return retList; - } - } - - if (coverage != null && coverage.isInUse()) { - coverage.prepare(projection, viewAttributes.chartSeries); - retList.add(coverage); - } - - // Check the current minScale and maxScale set on the layer, ignore if - // projection scale is out of range. - if (!isProjectionOK(projection)) { - return retList; - } - - if (this.cache == null) { - rpfLogger.fine(getName() + ": Creating cache!"); - this.cache = new RpfCacheManager(frameProvider, viewAttributes, subframeCacheSize, auxSubframeCacheSize); - } - - // Check to make sure the projection is CADRG - if (!(projection instanceof EqualArc) && (viewAttributes.showMaps || viewAttributes.showInfo)) { - // fireRequestInfoLine("RpfLayer runs faster with an Equal Arc - // projection (CADRG/LLXY)."); - } - - rpfLogger.fine(getName() + " doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (rpfLogger.isLoggable(Level.FINE)) { - rpfLogger.fine(getName() + "calling getRectangle " + " with projection: " + projection + " ul = " - + projection.getUpperLeft() + " lr = " + projection.getLowerRight()); - } - - if (frameProvider.needViewAttributeUpdates()) { - frameProvider.setViewAttributes(viewAttributes); - } - - try { - - // OMGraphics are generated by the RpfCacheHandlers when fetched - retList.addAll(this.cache.getRectangle(projection)); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": finished with " + retList.size() + " graphics"); - } - - } catch (java.lang.NullPointerException npe) { - logger.warning(getName() + ": Something really bad happened - \n " + npe); - npe.printStackTrace(); - retList = new OMGraphicList(); - this.cache = null; - } - - return retList; - } - - public boolean isHighlightable(OMGraphic omg) { - return viewAttributes.showInfo && omg instanceof OMRaster && omg.isSelected(); - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - /** - * Overridden to do nothing because we want nothing to happen. - */ - public void highlight(OMGraphic omg) { - - } - - /** - * Overridden to do nothing because we want nothing to happen. - */ - public void unhighlight(OMGraphic omg) { - - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - private transient JPanel box = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - if (box == null) { - JCheckBox showInfoCheck, lockSeriesCheck; - - box = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - box.setLayout(gridbag); - - c.anchor = GridBagConstraints.NORTHWEST; - c.gridx = GridBagConstraints.REMAINDER; - - showInfoCheck = new JCheckBox("Show Attributes", viewAttributes.showInfo); - showInfoCheck.setActionCommand(showInfoCommand); - showInfoCheck.addActionListener(this); - - String tmpCS = viewAttributes.chartSeries; - if (tmpCS == null) { - tmpCS = RpfViewAttributes.ANY; - } - - boolean locked = !tmpCS.equalsIgnoreCase(RpfViewAttributes.ANY); - String lockedTitle = locked ? (lockedButtonTitle + " - " + tmpCS) : unlockedButtonTitle; - - lockSeriesCheck = new JCheckBox(lockedTitle, locked); - lockSeriesCheck.setActionCommand(lockSeriesCommand); - lockSeriesCheck.addActionListener(this); - - // box1.add(showMapsCheck); - gridbag.setConstraints(showInfoCheck, c); - box.add(showInfoCheck); - gridbag.setConstraints(lockSeriesCheck, c); - box.add(lockSeriesCheck); - - if (coverage != null) { - JCheckBox showCoverageCheck = new JCheckBox("Show Coverage", coverage.isInUse()); - showCoverageCheck.setActionCommand(showCoverageCommand); - showCoverageCheck.addActionListener(this); - gridbag.setConstraints(showCoverageCheck, c); - box.add(showCoverageCheck); - } - - JPanel layerStuff = getDefaultSettingsPanel(RpfLayer.class, viewAttributes.opaqueness / 255f); - gridbag.setConstraints(layerStuff, c); - box.add(layerStuff); - } - return box; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * The Action Listener method, that reacts to the palette widgets actions. - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String cmd = e.getActionCommand(); - if (cmd == showMapsCommand) { - JCheckBox mapCheck = (JCheckBox) e.getSource(); - viewAttributes.showMaps = mapCheck.isSelected(); - repaint(); - } else if (cmd == showInfoCommand) { - JCheckBox infoCheck = (JCheckBox) e.getSource(); - boolean showInfo = infoCheck.isSelected(); - viewAttributes.showInfo = showInfo; - showSubframes(showInfo); - doPrepare(); - } else if (cmd == lockSeriesCommand) { - JCheckBox lockCheck = (JCheckBox) e.getSource(); - boolean locked = lockCheck.isSelected(); - if (locked) { - List coverageBoxes = getCoverageBoxes(); - String seriesName; - - if (coverageBoxes == null || coverageBoxes.isEmpty()) { - seriesName = RpfViewAttributes.ANY; - } else { - seriesName = coverageBoxes.get(0).chartCode; - } - - if (seriesName == null) { - seriesName = RpfViewAttributes.ANY; - fireRequestMessage("The " + getName() - + " Layer is having trouble determining what kind\nof charts are being displayed. Can't establish lock for charts\ncurrently being viewed."); - } - - lockCheck.setText(lockedButtonTitle + " - " + seriesName); - viewAttributes.chartSeries = seriesName; - - } else { - lockCheck.setText(unlockedButtonTitle); - viewAttributes.chartSeries = RpfViewAttributes.ANY; - } - - } else if (cmd == showCoverageCommand) { - if (coverage != null) { - JCheckBox coverageCheck = (JCheckBox) e.getSource(); - coverage.setInUse(coverageCheck.isSelected()); - doPrepare(); - } - } else { - // logger.warning("RpfLayer: Unknown action command \"" + cmd - // + - // "\" in RpfLayer.actionPerformed()."); - - // OK, not really sure what happened, just act like a - // reset. - doPrepare(); - } - } - - protected void showSubframes(boolean show) { - OMGraphicList list = getList(); - if (list != null) { - list.setSelected(show); - } - - MapMouseInterpreter mmi = getMouseEventInterpreter(); - if (mmi != null) { - mmi.setActive(show); - } - } - - /** Print out the contents of a properties file. */ - public static void main(String[] argv) { - System.out.println("#########################################"); - System.out.println("# Properties for the JAVA RpfLayer"); - System.out.println("# Mandatory properties:"); - System.out.println("layer.class=com.bbn.openmap.layer.rpf.RpfLayer"); - System.out.println("layer.prettyName=CADRG"); - System.out.println("# This property should reflect the paths to the RPF directories"); - System.out.println("layer.paths=;/cdrom/cdrom0/RPF"); - System.out.println( - "# Optional properties - Defaults will be set for properties not included (defaults are listed):"); - System.out.println("# Number between 0-255: 0 is transparent, 255 is opaque"); - System.out.println("layer.opaque=255"); - System.out.println("# Number of colors to use on the maps - 16, 32, 216"); - System.out.println("layer.numberColors=216"); - System.out.println("# Display maps on startup"); - System.out.println("layer.showMaps=true"); - System.out.println("# Display attribute information on startup"); - System.out.println("layer.showInfo=false"); - System.out.println("# Scale images to match map scale"); - System.out.println("layer.scaleImages=true"); - System.out.println( - "# The scale factor to allow when scaling images (2x, 4x, also mean 1/2, 1/4). Default is 4."); - System.out.println("rpf.imageScaleFactor=4"); - System.out.println("# Reset the cache if layer is removed from map"); - System.out.println("layer.killCache=false"); - System.out.println("# Limit the display to the chart code specified. (GN, JN, ON, TP, etc.)"); - System.out.println("layer.chartSeries=ANY"); - System.out.println("# Set the subframe cache size. (Number of subframes to hold on to, 256x256 pixels"); - System.out.println("layer.subframeCacheSize=128"); - System.out.println("# Get the subframe attribute data from the frame provider."); - System.out.println("rpf.autofetchAttributes=false"); - System.out.println("#If you want the coverage tool to be available"); - System.out.println("layer.coverage=true"); - System.out.println("#Then add coverage constants as needed."); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfProductInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfProductInfo.java deleted file mode 100644 index 68810d1ed..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfProductInfo.java +++ /dev/null @@ -1,317 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfProductInfo.java,v $ -// $RCSfile: RpfProductInfo.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/02/11 22:34:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * This class describes the attributes of the different RPF products available. - */ -package com.bbn.openmap.layer.rpf; - -/** - * Contains basic information about the different map and imagery types - * supported by the RPF format. This information is based on the specification - * released by NIMA and contains the conventions they have listed in the RPF - * specification. - */ -public enum RpfProductInfo implements RpfConstants { - - GN("GN", "GNC", "1:5,000,000", 5000000f, "Global Navigation Chart", CADRG), - JN("JN", "JNC", "1:2,000,000", 2000000f, "Jet Navigation Chart", CADRG), - ON("ON", "ONC", "1:1,000,000", 1000000f, "Operational Navigation Chart", CADRG), - TP("TP", "TPC", "1:500,000", 500000f, "Tactical Pilotage Chart", CADRG), - LF("LF", "LFC-FR (Day)", "1:500,000", 500000f, "Low Flying Chart (Day) - Host Nation", CADRG), - JG("JG", "JOG", "1:250,000", 250000f, "Joint Operations Graphic", CADRG), - JA("JA", "JOG-A", "1:250,000", 250000f, "Joint Operations Graphic - Air", CADRG), - JR("JR", "JOG-R", "1:250,000", 250000f, "Joint Operations Graphic - Radar", CADRG), - TF("TF", "TFC", "1:250,000", 250000f, "Transit Flying Chart (UK)", CADRG), - AT("AT", "ATC", "1:200,000", 200000f, "Series 200 Air Target Chart", CADRG), - TC("TC", "TLM 100", "1:100,000", 100000f, "Topographic Line Map 1:100,000 scale", CADRG), - TL("TL", "TLM 50", "1:50,000", 50000f, TOPOLINEMAP, CADRG), - TT("TT", "TLM 25", "1:25,000", 25000f, "Topographic Line Map 1:25,000 scale", CADRG), - TQ("TQ", "TLM 24", "1:24,000", 24000f, "Topographic Line Map 1:24,000 scale", CADRG), - HA("HA", "HA", VARIOUS, Various, "Harbor and Approach Charts", CADRG), - CO("CO", "CO", VARIOUS, Various, "Coastal Charts", CADRG), - OA("OA", "OPEAREA", VARIOUS, Various, "Naval Range Operating Area Chart", CADRG), - CG("CG", "CG", VARIOUS, Various, CITYGRAPHICS, CADRG), - C1("C1", "CG", "1:10,000", 10000f, CITYGRAPHICS, CADRG), - C2("C2", "CG", "1:10,560", 10560f, CITYGRAPHICS, CADRG), - C3("C3", "CG", "1:11,000", 11000f, CITYGRAPHICS, CADRG), - C4("C4", "CG", "1:11,800", 11800f, CITYGRAPHICS, CADRG), - C5("C5", "CG", "1:12,000", 12000f, CITYGRAPHICS, CADRG), - C6("C6", "CG", "1:12,500", 12500f, CITYGRAPHICS, CADRG), - C7("C7", "CG", "1:12,800", 12800f, CITYGRAPHICS, CADRG), - C8("C8", "CG", "1:14,000", 14000f, CITYGRAPHICS, CADRG), - C9("C9", "CG", "1:14,700", 14700f, CITYGRAPHICS, CADRG), - CA("CA", "CG", "1:15,000", 15000f, CITYGRAPHICS, CADRG), - CB("CB", "CG", "1:15,500", 15500f, CITYGRAPHICS, CADRG), - CC("CC", "CG", "1:16,000", 16000f, CITYGRAPHICS, CADRG), - CD("CD", "CG", "1:16,666", 16666f, CITYGRAPHICS, CADRG), - CE("CE", "CG", "1:17,000", 17000f, CITYGRAPHICS, CADRG), - CF("CF", "CG", "1:17,500", 17500f, CITYGRAPHICS, CADRG), - CH("CH", "CG", "1:18,000", 18000f, CITYGRAPHICS, CADRG), - CJ("CJ", "CG", "1:20,000", 20000f, CITYGRAPHICS, CADRG), - CK("CK", "CG", "1:21,000", 21000f, CITYGRAPHICS, CADRG), - CL("CL", "CG", "1:21,120", 21120f, CITYGRAPHICS, CADRG), - CN("CN", "CG", "1:22,000", 22000f, CITYGRAPHICS, CADRG), - CP("CP", "CG", "1:23,000", 23000f, CITYGRAPHICS, CADRG), - CQ("CQ", "CG", "1:25,000", 25000f, CITYGRAPHICS, CADRG), - CR("CR", "CG", "1:26,000", 26000f, CITYGRAPHICS, CADRG), - CS("CS", "CG", "1:35,000", 35000f, CITYGRAPHICS, CADRG), - CT("CT", "CG", "1:36,000", 36000f, CITYGRAPHICS, CADRG), - CM("CM", "CM", VARIOUS, Various, "Combat Charts", CADRG), - A1("A1", "CM", "1:10,000", 10000f, "Combat Graphics, 1:10,000 scale", CADRG), - A2("A2", "CM", "1:25,000", 25000f, "Combat Graphics, 1:25,000 scale", CADRG), - A3("A3", "CM", "1:50,000", 50000f, "Combat Graphics, 1:50,000 scale", CADRG), - A4("A4", "CM", "1:100,000", 100000f, "Combat Graphics, 1:100,000 scale", CADRG), - MM("MM", BLANK, VARIOUS, Various, "(Miscellaneous Maps & Charts)", CADRG), - IM("IM", BLANK, "10m", 66666f, "Imagery, 10 meter resolution", CIB), - I1("I1", BLANK, "10m", 66666f, "Imagery, 10 meter resolution", CIB), - I2("I2", BLANK, "5m", 33333f, "Imagery, 5 meter resolution", CIB), - I3("I3", BLANK, "2m", 13333.2f, "Imagery, 2 meter resolution", CIB), - I4("I4", BLANK, "1m", 6666f, "Imagery, 1 meter resolution", CIB), - D1("D1", BLANK, "100m", Various, "Elevation Data from DTED level 1", CDTED), - D2("D2", BLANK, "30m", Various, "Elevation Data from DTED level 2", CDTED), - OV("OV", "Overview", VARIOUS, Various, "Overview Image", CADRG), - OI("OI", "Overview", VARIOUS, Various, "Overview Image", CADRG), - LG("LG", "Legend", VARIOUS, Various, "Legend Data", CADRG), - UK("UK", "Unknown", VARIOUS, Various, "Unknown", CADRG), - DT("DT", "CDTED", "100M", 666666f, "Compressed DTED", CDTED), - - /** - * New as of MIL-STD-2411-1 Change 3 - */ - EG("EG", "NARC", "1:11M", 11000000f, "North Atlantic Route Chart", CADRG), - ES("ES", "SEC", "1:500,000", 500000f, "VFR Sectional", CADRG), - ET("ET", "SEC", "1:250,000", 250000f, "VFR Sectional Insets", CADRG), - F1("F1", "TFC-1", "1:250,000", 250000f, "Transit Flying Chart (TBD #1)", CADRG), - F2("F2", "TFC-2", "1:250,000", 250000f, "Transit Flying Chart (TBD #2)", CADRG), - F3("F3", "TFC-3", "1:250,000", 250000f, "Transit Flying Chart (TBD #3)", CADRG), - F4("F4", "TFC-4", "1:250,000", 250000f, "Transit Flying Chart (TBD #4)", CADRG), - F5("F5", "TFC-5", "1:250,000", 250000f, "Transit Flying Chart (TBD #5)", CADRG), - I5("I5", BLANK, ".5m", 3333f, "Imagery, .5 (half) meter resolution", CIB), - IV("IV", BLANK, VARIOUS, Various, "Imagery, > 10 meter resolution", CIB), - JO("JO", "OPG", "1:250,000", 250000f, "Operations Planning Graphic", CADRG), - K1("K1", "ICM", "1:8,000", 8000f, "Image City Maps", CADRG), - K2("K2", "ICM", "1:10,000", 10000f, "Image City Maps", CADRG), - K3("K3", "ICM", "1:10,560", 10560f, "Image City Maps", CADRG), - K7("K7", "ICM", "1:12,500", 12500f, "Image City Maps", CADRG), - K8("K8", "ICM", "1:12,800", 12000f, "Image City Maps", CADRG), - KB("KB", "ICM", "1:15,000", 15000f, "Image City Maps", CADRG), - KE("KE", "ICM", "1:16,666", 16666f, "Image City Maps", CADRG), - KM("KM", "ICM", "1:21,120", 21120f, "Image City Maps", CADRG), - KR("KR", "ICM", "1:25,000", 25000f, "Image City Maps", CADRG), - KS("KS", "ICM", "1:26,000", 26000f, "Image City Maps", CADRG), - KU("KU", "ICM", "1:36,000", 36000f, "Image City Maps", CADRG), - L1("L1", "LFC-1", "1:500,000", 500000f, "Low Flying Chart (TBD #1)", CADRG), - L2("L2", "LFC-2", "1:500,000", 500000f, "Low Flying Chart (TBD #2)", CADRG), - L3("L3", "LFC-3", "1:500,000", 500000f, "Low Flying Chart (TBD #3)", CADRG), - L4("L4", "LFC-4", "1:500,000", 500000f, "Low Flying Chart (TBD #4)", CADRG), - L5("L5", "LFC-5", "1:500,000", 500000f, "Low Flying Chart (TBD #5)", CADRG), - LN("LN", "LFC (Night)", "1:500,000", 500000f, "Low Flying Chart (Night) - Host Nation", CADRG), - M1("M1", "MIM", VARIOUS, Various, "Military Installation Map (TBD #1)", CADRG), - M2("M2", "MIM", VARIOUS, Various, "Military Installation Map (TBD #2)", CADRG), - MH("MH", "MIM", "1:25,000", 25000f, "Military Installation Maps", CADRG), - MI("MI", "MIM", "1:50,000", 50000f, "Military Installation Maps", CADRG), - MJ("MJ", "MIM", "1:100,000", 100000f, "Military Installation Maps", CADRG), - OH("OH", "VHRC", "1:1,000,000", 1000000f, "VFR Helicopter Route Chart", CADRG), - OW("OW", "WAC", "1:1,000,000", 1000000f, "High Flying Chart - Host Nation", CADRG), - P1("P1", BLANK, "1:25,000", 25000f, "Special Military Map - Overlay", CADRG), - P2("P2", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P3("P3", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P4("P4", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P5("P5", BLANK, "1:50,000", 50000f, "Special Military Map - Overlay", CADRG), - P6("P6", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P7("P7", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P8("P8", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P9("P9", BLANK, "1:100,000", 100000f, "Special Military Map - Overlay", CADRG), - PA("PA", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PB("PB", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PC("PC", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PD("PD", BLANK, "1:250,000", 250000f, "Special Military Map - Overlay", CADRG), - PE("PE", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PF("PF", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PG("PG", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PH("PH", BLANK, "1:500,000", 500000f, "Special Military Map - Overlay", CADRG), - PI("PI", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PJ("PJ", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PK("PK", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PL("PL", BLANK, "1:1,000,000", 1000000f, "Special Military Map - Overlay", CADRG), - PM("PM", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PN("PN", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PO("PO", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PP("PP", BLANK, "1:2,000,000", 2000000f, "Special Military Map - Overlay", CADRG), - PQ("PQ", BLANK, "1:2,000,000", 2000000f, "Special Military Purpose", CADRG), - PR("PR", BLANK, "1:2,000,000", 2000000f, "Special Military Purpose", CADRG), - PS("PS", BLANK, "1:5,000,000", 5000000f, "Special Military Map - Overlay", CADRG), - PT("PT", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - PU("PU", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - PV("PV", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - R1("R1", BLANK, "1:50,000", 50000f, "Range Charts", CADRG), - R2("R2", BLANK, "1:100,000", 100000f, "Range Charts", CADRG), - R3("R3", BLANK, "1:250,000", 250000f, "Range Charts", CADRG), - R4("R4", BLANK, "1:500,000", 500000f, "Range Charts", CADRG), - R5("R5", BLANK, "1:1,000,000", 1000000f, "Range Charts", CADRG), - RC("RC", "RGS-100", "1:10,000", 10000f, "Russian General Staff Maps", CADRG), - RL("RL", "RGS-50", "1:50,000", 50000f, "Russian General Staff Maps", CADRG), - RR("RR", "RGS-200", "1:200,000", 200000f, "Russian General Staff Maps", CADRG), - RV("RV", "Riverine", "1:50,000", 50000f, "Riverine Map 1:50,000 scale", CADRG), - TN("TN", "TFC (Night)", "1:250,000", 250000f, "Transit Flying Chart (Night) - Host nation", CADRG), - TR("TR", "TLM 100", "1:200,000", 200000f, "Topographic Line Map 1:200,000 scale", CADRG), - UL("UL", "TLM50-Other", "1:50,000", 50000f, "Topographic Line Map (other 1:50,000 scale)", CADRG), - V1("V1", "HRC Inset", "1:50,000", 50000f, "Helicopter Route Chart Inset", CADRG), - V2("V2", "HRC Inset", "1:62,500", 62500f, "Helicopter Route Chart Inset", CADRG), - V3("V3", "HRC Inset", "1:90,000", 90000f, "Helicopter Route Chart Inset", CADRG), - V4("V4", "HRC Inset", "1:250,000", 250000f, "Helicopter Route Chart Inset", CADRG), - VH("VH", "HRC", "1:125,000", 125000f, "Helicopter Route Chart", CADRG), - VN("VN", "VNC", "1:500,000", 500000f, "Visual Navigation Charts", CADRG), - VT("VT", "VTAC", "1:250,000", 250000f, "VFR Terminal Area Chart", CADRG), - WA("WA", BLANK, "1:250,000", 250000f, "IFR Enroute Low", CADRG), - WB("WB", BLANK, "1:500,000", 500000f, "IFR Enroute Low", CADRG), - WC("WC", BLANK, "1:750,000", 750000f, "IFR Enroute Low", CADRG), - WD("WD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute Low", CADRG), - WE("WE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute Low", CADRG), - WF("WF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute Low", CADRG), - WG("WG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute Low", CADRG), - WH("WH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute Low", CADRG), - WI("WI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute Low", CADRG), - WK("WK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute Low", CADRG), - XD("XD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute High", CADRG), - XE("XE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute High", CADRG), - XF("XF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute High", CADRG), - XG("XG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute High", CADRG), - XH("XH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High", CADRG), - XI("XI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute High", CADRG), - XJ("XJ", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High", CADRG), - XK("XK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute High", CADRG), - Y9("Y9", BLANK, "1:16,500,000", 16500000f, "IFR Enroute Area", CADRG), - YA("YA", BLANK, "1:250,000", 250000f, "IFR Enroute Area", CADRG), - YB("YB", BLANK, "1:500,000", 500000f, "IFR Enroute Area", CADRG), - YC("YC", BLANK, "1:750,000", 750000f, "IFR Enroute Area", CADRG), - YD("YD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute Area", CADRG), - YE("YE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute Area", CADRG), - YF("YF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute Area", CADRG), - YI("YI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute Area", CADRG), - YJ("YJ", BLANK, "1:4,000,000", 4000000f, "IFR Enroute Area", CADRG), - YZ("YZ", BLANK, "1:12,000,000", 12000000f, "IFR Enroute Area", CADRG), - Z8("Z8", BLANK, "1:16,000,000", 16000000f, "IFR Enroute High/Low", CADRG), - ZA("ZA", BLANK, "1:250,000", 250000f, "IFR Enroute High/Low", CADRG), - ZB("ZB", BLANK, "1:500,000", 500000f, "IFR Enroute High/Low", CADRG), - ZC("ZC", BLANK, "1:750,000", 750000f, "IFR Enroute High/Low", CADRG), - ZD("ZD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute High/Low", CADRG), - ZE("ZE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute High/Low", CADRG), - ZF("ZF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute High/Low", CADRG), - ZG("ZG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute High/Low", CADRG), - ZH("ZH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High/Low", CADRG), - ZI("ZI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute High/Low", CADRG), - ZJ("ZJ", BLANK, "1:4,000,000", 4000000f, "IFR Enroute High/Low", CADRG), - ZK("ZK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute High/Low", CADRG), - ZT("ZT", BLANK, "1:9,000,000", 9000000f, "IFR Enroute High/Low", CADRG), - ZV("ZV", BLANK, "1:10,000,000", 10000000f, "IFR Enroute High/Low", CADRG), - ZZ("ZZ", BLANK, "1:12,000,000", 12000000f, "IFR Enroute High/Low", CADRG); - - /** The two-letter code for a particular map type. */ - public final String seriesCode; - /** The three-letter common abbreviation for the map type. */ - public final String abbr; - /** A String scale representation of the map type. */ - public final String scaleString; - /** The float number representation of the map type - 1:XXX . */ - public final float scale; - /** A Descriptive name for the map type. */ - public final String name; - /** The category of the map type - CADRG/CIB/DTED. */ - public final String dataType; - - /** - * Create a RpfProductInfo object. - * - * @param sc - * the two-letter series code. - * @param a - * the three letter acroynm. - * @param ss - * the scale string. - * @param s - * the display scale of the map. - * @param n - * descriptive name of the map. - * @param dt - * data type - CADRG-CIB-DTED. - */ - private RpfProductInfo(String sc, String a, String ss, float s, String n, String dt) { - seriesCode = sc; - abbr = a; - scaleString = ss; - scale = s; - name = n; - dataType = dt; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("RPF Product: ").append(name).append("\n"); - sb.append(" Series Code: ").append(seriesCode).append("\n"); - sb.append(" Abbreviation: ").append(abbr).append("\n"); - sb.append(" Scale: ").append(scaleString); - if (scale == RpfConstants.Various) { - sb.append(" (Various)\n"); - } else { - sb.append(" (").append(scale).append(")\n"); - } - sb.append(" Data Type: ").append(dataType).append("\n"); - return sb.toString(); - } - - /** - * Returns the RpfProductInfo that has the given two-letter series code. If - * the code passed in is not recognized by the catalog, the UNKNOWN - * RpfProductInfo is returned. - * - * @param seriesCode - * needs to be the two letter code, in uppercase. - */ - public static RpfProductInfo get(String seriesCode) { - - if (seriesCode == null) { - return UK; - } - - for (RpfProductInfo rpi : RpfProductInfo.values()) { - if (rpi.seriesCode.equalsIgnoreCase(seriesCode)) { - return rpi; - } - } - - return UK; - } - - /** - * The main function prints out the RPF catalog, describing all the - * different map types handled by the RPF package. - */ - public static void main(String[] argv) { - System.out.println("RPF Catalog:\n\n"); - for (RpfProductInfo rpi : RpfProductInfo.values()) { - System.out.println("----------------------"); - System.out.println(rpi); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfSubframe.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfSubframe.java deleted file mode 100644 index b60f7119d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfSubframe.java +++ /dev/null @@ -1,276 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfSubframe.java,v $ -// $RCSfile: RpfSubframe.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/10/04 14:46:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * Some of the ideas for this code is based on source code provided by - * The MITRE Corporation, through the browse application source code. - * Many thanks to Nancy Markuson who provided BBN with the software, - * and to Theron Tock, who wrote the software, and Daniel Scholten, - * who revised it - (c) 1994 The MITRE Corporation for those parts, - * and used with permission. Namely, the subframe caching mechanism - * is the part that has been modified. - */ - -package com.bbn.openmap.layer.rpf; - -import java.awt.Color; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.DataBounds; - -/** - * The RpfSubframe is a holder for images and attributes within the cache. - */ -public class RpfSubframe { - /** - * The version of the subframe, used by the cache for marking how recently - * used the subframe was. - */ - public byte version; - /** The pointers to the surrounding subframes in the cache. */ - public int nextSubframe, prevSubframe; - /** The original pixel size of RPF Subframes. */ - public final static int PIXEL_EDGE_SIZE = 256; - /** The actual attribute information. */ - protected String data = ""; - /** The opaqueness of the image. */ - protected int opaqueness; - protected DataBounds bounds = null; - /** - * The object that creates the image from either pixels or bytes and colors. - * Also handles selecting warping or scaling images based on the projection - * type. - */ - protected ImageCreator imageCreator = null; - - public RpfSubframe() { - } - - /** - * Set the lat/lon of the frame and attribute text. - * - * @param ulat latitude of upper left point, in decimal degrees. - * @param wlon longitude of upper left point, in decimal degrees. - * @param llat latitude of lower right point, in decimal degrees. - * @param elon longitude of lower right point, in decimal degrees. - */ - public void setLocation(double ulat, double wlon, double llat, double elon) { - bounds = new DataBounds(); - bounds.add(wlon, ulat); - bounds.add(elon, llat); - } - - /** - * setScalingTo has to be called after this for the changes to take place, - * or else you need to call the information.setData() methods directly. - */ - public void setAttributeText(String text) { - data = text; - } - - /** - * getAttributeText retrieves the text that would be displayed as attribute - * information about the subframe. - */ - public String getAttributeText() { - return data; - } - - public void setPixels(int[] pixels) { - imageCreator = new Pixels(pixels); - } - - public void setBitsAndColors(byte[] bits, Color[] colors) { - imageCreator = new BitsAndColors(bits, colors); - } - - public void setTransparent(int opaqueness) { - if (this.opaqueness != opaqueness) { - this.opaqueness = opaqueness; - imageCreator.setTransparent(opaqueness); - } - // Check new setting vs old - if changed, then set new member variable - // value, & - // setNeedToRegenerate(true); - } - - public OMGraphic getImage(Projection proj) { - if (imageCreator != null) { - return imageCreator.getImage(proj); - } - return null; - } - - public abstract class ImageCreator { - /** - * The OMGraphic holding the image. - */ - OMGraphic image; - - /** - * Get the proper OMGraphic given the projection type. - * - * @param proj - * @return a projected OMGraphic for the image. - */ - protected abstract OMGraphic getImage(Projection proj); - - /** - * Set the transparent color index or opaqueness setting, depending on - * color model. - * - * @param opaqueness - */ - protected abstract void setTransparent(int opaqueness); - - } - - /** - * Direct colormodel implementation. - * - * @author ddietrick - */ - public class Pixels - extends ImageCreator { - - int[] pixels = null; - - protected Pixels(int[] pixels) { - this.pixels = pixels; - } - - protected void setTransparent(int opaqueness) { - if (pixels != null) { - for (int i = 0; i < pixels.length; i++) { - pixels[i] = (0x00FFFFFF & pixels[i]) | (opaqueness << 24); - } - // image = null; ?? - } - } - - protected OMGraphic getImage(Projection proj) { - - boolean scaling = proj instanceof EqualArc; - - if (bounds == null || pixels == null) { - return null; - } - - if (image == null) { - if (scaling) { - image = - new OMScalingRaster(bounds.getMax().getY(), bounds.getMin().getX(), bounds.getMin().getY(), - bounds.getMax().getX(), PIXEL_EDGE_SIZE, PIXEL_EDGE_SIZE, pixels); - } else { - image = new OMWarpingImage(pixels, PIXEL_EDGE_SIZE, PIXEL_EDGE_SIZE, new LatLonGCT(), bounds); - } - } else { - if (scaling) { - if (!(image instanceof OMScalingRaster)) { - image = - new OMScalingRaster(bounds.getMax().getY(), bounds.getMin().getX(), bounds.getMin().getY(), - bounds.getMax().getX(), PIXEL_EDGE_SIZE, PIXEL_EDGE_SIZE, pixels); - } - } else { - if (image instanceof OMScalingRaster) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } - } - - image.setSelectPaint(Color.yellow); - image.generate(proj); - if (data != null) { - image.putAttribute(OMGraphic.TOOLTIP, data); - } - - return image; - } - - } - - /** - * Indexed colormodel implementation. - * - * @author ddietrick - */ - public class BitsAndColors - extends ImageCreator { - - byte[] bits = null; - Color[] colors = null; - - protected BitsAndColors(byte[] bits, Color[] colors) { - this.bits = bits; - this.colors = colors; - } - - protected void setTransparent(int opaqueness) { - // setTransparent has to be set on the resulting OMScalingRaster and - // regenerated - } - - protected OMGraphic getImage(Projection proj) { - boolean scaling = proj instanceof EqualArc; - - if (bounds == null || bits == null || colors == null) { - return null; - } - - if (image == null) { - image = - new OMScalingRaster(bounds.getMax().getY(), bounds.getMin().getX(), bounds.getMin().getY(), bounds.getMax() - .getX(), - PIXEL_EDGE_SIZE, PIXEL_EDGE_SIZE, bits, colors, opaqueness); - image.generate(proj); - if (!scaling) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } else { - if (scaling) { - if (!(image instanceof OMScalingRaster)) { - image = - new OMScalingRaster(bounds.getMax().getY(), bounds.getMin().getX(), bounds.getMin().getY(), - bounds.getMax().getX(), PIXEL_EDGE_SIZE, PIXEL_EDGE_SIZE, bits, colors, - opaqueness); - } - } else { - if (image instanceof OMScalingRaster) { - image = new OMWarpingImage((OMScalingRaster) image, null); - } - } - } - image.setSelectPaint(Color.yellow); - image.generate(proj); - if (data != null) { - image.putAttribute(OMGraphic.TOOLTIP, data); - } - - return image; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocEntry.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocEntry.java deleted file mode 100644 index 493b93af3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocEntry.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfTocEntry.java,v $ -// $RCSfile: RpfTocEntry.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/12/13 16:45:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and to Theron Tock, who wrote the software, and - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used/distributed with permission. - */ - -package com.bbn.openmap.layer.rpf; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Reads and holds an entry in the RPF table of contents file. - */ -public class RpfTocEntry { - - /** Degrees/pixel. */ - public double vertInterval, horizInterval; - /** meters/pixel. */ - public double vertResolution, horizResolution; - public int horizFrames, vertFrames; - public RpfFrameEntry[][] frames; - public char zone; /* DKS new 7/94 */ - public char version; /* 1-9: DKS new 5/3/95 for Dchum */ - public boolean Cib; /* Cib vs. cadrg flag */ - public String compressionRatio; - public String producer; - public String scale; - public RpfCoverageBox coverage; - - /* - * Since RpfProductInfo changed to enum, there are times where the scale and - * scale string can be read out of the A.TOC file and set for entries where - * the chart series has those values as VARIOUS or UNDEFINED. They used to - * be stored in the RpfProductInfo class, but as it is now an enum, these are - * new member variables to hold the A.TOC values. - */ - public float altScale = 0f; - public String altScaleString; - - /** - * Not determined at read-time. RpfTocHandler sets this later, when the - * frames are evaluated for their existence. - */ - public RpfProductInfo info; - - public RpfTocEntry(BinaryFile binFile, int entryNumber) throws java.io.EOFException, FormatException { - this(binFile, 0, entryNumber); - } - - public RpfTocEntry(BinaryFile binFile, int TOCNumber, int entryNumber) - throws java.io.EOFException, FormatException { - coverage = new RpfCoverageBox(); - coverage.tocNumber = TOCNumber; - coverage.entryNumber = entryNumber; - read(binFile); - - // Figure out the CADRG projection zone for the coverage. - coverage.zone = com.bbn.openmap.proj.CADRG.getProjZone(zone); - } - - public void setInfo(String seriesCode) { - info = RpfProductInfo.get(seriesCode.toUpperCase()); - if (info != null) { - Cib = info.dataType.equalsIgnoreCase("CIB"); - coverage.chartCode = info.seriesCode; - } else { - info = RpfProductInfo.UK; - } - } - - public void read(BinaryFile binFile) throws java.io.EOFException, FormatException { - /* - * e.g. "CADRG" , for type - deduced later, via framename of entry, and - * using RpfProductInfo. - */ - /* String type = */binFile.readFixedLengthString(5); - compressionRatio = binFile.readFixedLengthString(5); - /* - * Same as type - deduced via RpfProductInfo. There is a float scale - * inside the info, and a scaleString. - */ - scale = binFile.readFixedLengthString(12); - coverage.scale = RpfTocHandler.textScaleToLong(scale); - - zone = binFile.readChar(); /* char: 1-9 A-J */ - producer = binFile.readFixedLengthString(5); - - coverage.nw_lat = binFile.readDouble(); - coverage.nw_lon = binFile.readDouble(); - /* double sw_lat = */binFile.readDouble(); - /* double sw_lon = */binFile.readDouble(); - /* double ne_lat = */binFile.readDouble(); - /* double ne_lon = */binFile.readDouble(); - coverage.se_lat = binFile.readDouble(); - coverage.se_lon = binFile.readDouble(); - vertResolution = binFile.readDouble(); - horizResolution = binFile.readDouble(); - vertInterval = binFile.readDouble(); - horizInterval = binFile.readDouble(); - vertFrames = binFile.readInteger(); - horizFrames = binFile.readInteger(); - - coverage.subframeLatInterval = vertInterval * 256.0; - coverage.subframeLonInterval = horizInterval * 256.0; - } - - protected boolean isFramesLoaded() { - return frames != null; - } - - protected RpfFrameEntry[][] getFrames() { - if (frames == null) { - frames = new RpfFrameEntry[vertFrames][horizFrames]; - - for (int j = 0; j < vertFrames; j++) { - for (int k = 0; k < horizFrames; k++) { - frames[j][k] = new RpfFrameEntry(); - } - } - } - - return frames; - } - - protected RpfFrameEntry getFrame(int row, int column) { - RpfFrameEntry[][] frames = getFrames(); - return frames[row][column]; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfTocEntry ##################").append("\n"); - s.append(" vertInterval ").append(vertInterval).append(", horizInterval ").append(horizInterval).append("\n"); - s.append(" vertResolution ").append(vertResolution).append(", horizResolution ").append(horizResolution) - .append("\n"); - s.append(" horizFrames ").append(horizFrames).append(", vertFrames ").append(vertFrames).append("\n"); - s.append(" zone ").append(zone).append("\n"); - s.append(" scale ").append(scale).append("\n"); - s.append(" version ").append(version).append("\n"); - s.append(" Cib ").append(Cib).append("\n"); - s.append(" compressionRatio ").append(compressionRatio).append("\n"); - s.append(" producer ").append(producer).append("\n"); - s.append(coverage); - return s.toString(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocHandler.java deleted file mode 100644 index 18ea76a04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfTocHandler.java +++ /dev/null @@ -1,1252 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfTocHandler.java,v $ -// $RCSfile: RpfTocHandler.java,v $ -// $Revision: 1.16 $ -// $Date: 2006/12/13 16:45:24 $ -// $Author: dietrick $ -// -// ********************************************************************** -/** - * Modifications: 1. Changed getBestCoverageEntry() to consider more than one zone. 2. Changed getBestCoverageEntry() to - * return multiple entries. - */ - -/* - * The meat of this code is based on source code provided by The MITRE - * Corporation, through the browse application source code. Many - * thanks to Nancy Markuson who provided BBN with the software, and to - * Theron Tock, who wrote the software, and Daniel Scholten, who - * revised it - (c) 1994 The MITRE Corporation for those parts, and - * used/distributed with permission. The RPF TOC reading mechanism is - * the contributed part. - */ -package com.bbn.openmap.layer.rpf; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The RpfTocHandler knows how to read A.TOC files for RPF raster data. The A.TOC file describes the coverage found in - * the tree of data that accompanies it. This coverage is described as a series of rectangles describing the frame of - * groups of coverage, with common-scale maps, types for different CADRG zones. The RpfTocHandler can also provide a - * description of the frames and subframes to use for a screen with a given projection. - *

- * - * The RPF specification says that the frame paths and file names, from the RPF directory, should be in upper-case - * letters. The paths and file names are stored in the A.TOC file this way. Sometimes, however, through CDROM and - * downloading quirks, the paths and file names, as stored on the hard drive, are actually transferred to lower-case - * letters. This RpfTocHandler will check for lower case letter paths, but only for all the letters to be lower case. - * The frame will be marked as non-existent if some of the directories or filenames have be transformed to uppercase. - */ -public class RpfTocHandler { - - public final static String RPF_TOC_FILE_NAME = "A.TOC"; - public final static String LITTLE_RPF_TOC_FILE_NAME = "a.toc"; - public final static int DEFAULT_FRAME_SPACE = 300; // frame file - // in kilobytes - - protected RpfHeader head; - protected String aTocFilePath; - protected boolean aTocByteOrder; - protected BinaryFile binFile; - protected RpfFileSections.RpfLocationRecord[] locations; - /** - * The boundary rectangles in the A.TOC file. - */ - protected RpfTocEntry[] entries; - protected String dir; - protected boolean Dchum; - protected long estimateDiskSpace; // uint - protected int numBoundaries; - protected long numFrameIndexRecords; // uint # frame file index records - protected int indexRecordLength; // ushort, frame file index record - // length - protected long currencyTime; - protected boolean valid = false; - /** - * Set by the RpfFrameProvider, and used to track down this particular TOC to get to the frames offered by it's - * coverages. - */ - private int tocNumber = 0; - - /** - * Flag to tell the TOC handler to not consider matching zones when evaluating coverage boxes for which one provides - * the best coverage for a projection. Because the subframes are being scaled and warped, it's better to get - * coverage from any zone rather than to limit the entry responses with zone matching the projection. - */ - private boolean ignoreZonesForCoverageBoxes = true; - - /** - * Flag to note whether absolute pathnames are used in the A.TOC. Set to false, because it's not supposed to be that - * way, according to the specification. This is reset automatically when the A.TOC file is read. If the first two - * characters of the directory paths are ./, then it stays false. - */ - protected boolean fullPathsInATOC = false; - - protected boolean DEBUG_RPF = false; - protected boolean DEBUG_RPFTOC = false; - protected boolean DEBUG_RPFTOCDETAIL = false; - protected boolean DEBUG_RPFTOCFRAMEDETAIL = false; - - // Added zone extents - private static final int CADRG_zone_extents[] = { - 0, - 32, - 48, - 56, - 64, - 68, - 72, - 76, - 80, - 90 - }; - - public RpfTocHandler() { - - DEBUG_RPF = Debug.debugging("rpf"); - DEBUG_RPFTOC = Debug.debugging("rpftoc"); - DEBUG_RPFTOCDETAIL = Debug.debugging("rpftocdetail"); - DEBUG_RPFTOCFRAMEDETAIL = Debug.debugging("rpftocframedetail"); - - estimateDiskSpace = DEFAULT_FRAME_SPACE; - - if (Debug.debugging("rpftoc")) { - Debug.error("RpfTocHandler: No TOC parent directory name in constructor"); - } - } - - /** - * Should be used in situations where it is certain that this is the only A.TOC in town. - */ - public RpfTocHandler(String parentDir) { - this(parentDir, 0); - } - - /** - * Used when there is more than one A.TOC being used, or where there is a possibility of that happening, like in the - * RPF layer. The TOC number should be unique for a certain RpfFrameProvider. - * - * @param parentDir the RPF directory - * @param TOCNumber a unique number to identify this TOC for a RpfFrameProvider. - */ - public RpfTocHandler(String parentDir, int TOCNumber) { - tocNumber = TOCNumber; - estimateDiskSpace = DEFAULT_FRAME_SPACE; - - /* DKS. Open input "A.TOC" */ - valid = loadFile(parentDir); - if (!valid) { - Debug.error("RpfTocHandler: Invalid TOC File in " + parentDir); - } - } - - /** - * Given a parent RPF directory, find the a.toc file directly inside it, as dictated by the specification. Not - * called anymore - the BinaryFile does the searching, and can find URL and jar files. - * - * @param parentDir Path to the RPF directory. - * @return File - */ - public File getTocFile(String parentDir) { - /* DKS. Open input "A.TOC" */ - File file = new File(parentDir + "/" + RPF_TOC_FILE_NAME); - if (!file.exists()) { - file = new File(parentDir + "/" + LITTLE_RPF_TOC_FILE_NAME); - if (!file.exists()) { - // Debug.error("RpfTocHandler: getTocFile(): file in - // "+ - // parentDir + " not found"); - return null; - } - } - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: getTocFile(): TOC file is " + file); - } - - return file; - } - - /** - * True if the A.TOC file is readable/present/good. - */ - public boolean isValid() { - return valid; - } - - /** - * A way to check if the status of the A.TOC file is different, in case another one has taken its place. Handy if - * the A.TOC is on a CDROM drive and the disk has been swapped. Not valid anymore, with the advent of the new - * BinaryFile, where the file information may not be available. - */ - public boolean hasChanged() { - // File tmpFile = getTocFile(dir); - // if (tmpFile == null) { - // return valid; - // } - // if (tmpFile.lastModified() != currencyTime && valid) { - // valid = false; - // return true; - // } - return false; - } - - /** - * Re-read the A.TOC file in the parent directory. - */ - public boolean reload() { - return loadFile(dir); - } - - /** - * Read the file and load its parameters into this object. - */ - public boolean loadFile(String parentDir) { - - boolean ret = true; - - String upperCaseVersion = parentDir + "/" + RPF_TOC_FILE_NAME; - String lowerCaseVersion = parentDir + "/" + LITTLE_RPF_TOC_FILE_NAME; - - try { - - if (BinaryFile.exists(upperCaseVersion)) { - binFile = new BinaryBufferedFile(upperCaseVersion); - aTocFilePath = upperCaseVersion; - } else if (BinaryFile.exists(lowerCaseVersion)) { - binFile = new BinaryBufferedFile(lowerCaseVersion); - aTocFilePath = lowerCaseVersion; - } - - if (binFile == null) { - return false; - } - - if (DEBUG_RPFTOC) { - Debug.output("RpfTocHandler: TOC file is in " + parentDir); - } - - dir = parentDir + "/"; - - // With the new BinaryFile, we can't get to this - // info, because we aren't using File objects anymore. - // currencyTime = file.lastModified(); - if (!parseToc(binFile)) { - ret = false; - Debug.error("RpfTocHandler: loadFile(): error parsing A.TOC file!!"); - } - - aTocByteOrder = binFile.byteOrder(); - - binFile.close(); - } catch (IOException e) { - ret = false; - } - binFile = null; - return ret; - } - - protected boolean parseToc(BinaryFile binFile) { - - if (DEBUG_RPFTOC) { - Debug.output("ENTER TOC parsing..."); - } - - try { - // binFile should be set to the beginning at this point - binFile.seek(0); - - // Read header - head = new RpfHeader(); - if (!head.read(binFile)) { - return false; - } - - if (DEBUG_RPFTOC) { - Debug.output("RpfTocHandler.parseToc: read header:\n" + head); - } - - binFile.seek(head.locationSectionLocation); - RpfFileSections rfs = new RpfFileSections(binFile); - - // Everything must be OK to reach here... - // DKS. fseek to start of location section: 48 - // DFD not necessarily 48! New A.TOCs are different. - locations = rfs.getLocations(RpfFileSections.TOC_LOCATION_KEY); - - // Read boundary rectangles - // Number of Boundary records - // DKS: now phys_index, not index - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): fseek to Boundary section subheader: " - + locations[0].componentLocation); - } - - binFile.seek(locations[0].componentLocation); - - // NEW - long boundRectTableOffset = (long) binFile.readInteger(); - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): BoundRectTableOffset: " + boundRectTableOffset); - } - - int n = (int) binFile.readShort(); - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): # Boundary rect. recs: " + n); - } - - numBoundaries = n; - - // DKS new - // Boundary record length - int boundaryRecordLength = (int) binFile.readShort(); - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): should be 132: " + boundaryRecordLength); - } - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): fseek to Boundary Rectangle Table: " - + locations[1].componentLocation); - } - binFile.seek(locations[1].componentLocation); - - entries = new RpfTocEntry[numBoundaries]; - - // Read Boundary rectangle records - for (int i = 0; i < n; i++) { - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): read boundary rec#: " + i); - } - - // All this stuff moved to RpfTocEntry.java - DFD - // 8/18/99 - entries[i] = new RpfTocEntry(binFile, tocNumber, i); - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): entry " + i + " has scale " + entries[i].scale + ", type " - + (entries[i].Cib ? "CIB" : "CADRG") + " in zone " + entries[i].zone); - if (entries[i].Cib) { - Debug.output("RpfTocHandler: parseToc(): entry noted as a Cib entry."); - } - } - } - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): Read frame file index section subheader at loc: " - + locations[2].componentLocation); - } - - // Read # of frame file index records - // Skip 1 byte security classification - // locations[2] is loc of frame file index section - // subheader - binFile.seek(locations[2].componentLocation + 1); - - // NEW - long frameIndexTableOffset = (long) binFile.readInteger(); - numFrameIndexRecords = (long) binFile.readInteger(); - int numPathnameRecords = (int) binFile.readShort(); - // indexRecordLength should now be 33, not 35 - indexRecordLength = (int) binFile.readShort(); - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("RpfTocHandler: parseToc(): frameIndexTableOffset: " + frameIndexTableOffset); - Debug.output("RpfTocHandler: parseToc(): # Frame file index recs: " + numFrameIndexRecords); - Debug.output("RpfTocHandler: parseToc(): # pathname records: " + numPathnameRecords); - Debug.output("RpfTocHandler: parseToc(): Index rec len(33): " + indexRecordLength); - } - - // In previous version of the RpfTocHandler, we went ahead and read - // in all of the RPF frame file paths. For very large collections of - // data, expecially with large scale charts and imagery, this turns - // out to use a huge amount of data. The code has been reorganized - // to skip this part until it's been determined that those files are - // actually going to be used by the layer. - // readFrameInformation(binFile); - // One thing that we still need to do at this point, is query some - // of the frame file paths to find out what chart type is being held - // for each RpfTocEntry, so during the coverage determination we can - // decide whether to use an RpfTocEntry or not. - figureOutChartSeriesForEntries(binFile); - - } catch (IOException ioe) { - Debug.error("RpfTocHandler: IO ERROR parsing file!\n\t" + ioe); - return false; - } catch (FormatException fe) { - Debug.error("RpfTocHandler: Format ERROR parsing file!\n\t" + fe); - return false; - } - - if (DEBUG_RPFTOC) { - Debug.output("LEAVE TOC parsing..."); - } - return true; - } - - /** - * Method that looks at one frame file for each RpfTocEntry, in order to check the suffix and load the chart series - * information into the RpfTocEntry. This is needed for when the RpfTocHandler is asked for matching RpfTocEntries - * for a given scale and location when the chart type has been limited to a certain chart code. - * - * @param binFile - * @throws IOException - * @throws FormatException - */ - protected void figureOutChartSeriesForEntries(BinaryFile binFile) - throws IOException, FormatException { - - RpfTocEntry[] entriesAlreadyChecked = new RpfTocEntry[entries.length]; - System.arraycopy(entries, 0, entriesAlreadyChecked, 0, entries.length); - - // We just need the name of one file, just to see what the series code - // is. - for (int i = 0; i < numFrameIndexRecords; i++) { - // Read frame file index records - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("RpfTocHandler: parseToc(): Read frame file index rec #: " + i); - } - - // Index_subhdr_len (9) instead of table_offset (11) - // indexRecordLength (33) instead of 35 - // componentLocation, not index - // locations[3] is frame file index table subsection - binFile.seek(locations[3].componentLocation + indexRecordLength * i); - - int boundaryId = (int) binFile.readShort(); - - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("boundary id for frame: " + i + " is " + boundaryId); - } - - if (boundaryId > numBoundaries - 1) { - throw new FormatException("Bad boundary id in FF index record " + i); - } - - RpfTocEntry entry = entriesAlreadyChecked[boundaryId]; - - if (entry == null) { - continue; // already checked. - } else { - entriesAlreadyChecked[boundaryId] = null; - } - - /* int frameRow = (int) */ binFile.readShort(); - /* int frameCol = (int) */ - binFile.readShort(); - /* long pathOffset = (long) */ - binFile.readInteger(); - String filename = binFile.readFixedLengthString(12); - - // Figure out the chart series ID - int dot = filename.lastIndexOf('.'); - // Interned so we can look it up in the catalog - // later... - entry.setInfo(filename.substring(dot + 1, dot + 3).intern()); - } /* for i = numFrameIndexRecords */ - - } - - /** - * Should be called by the RpfFrameCacheHandler before any frame files are loaded from a RpfTocEntry. The - * RpfFrameCacheHandler should ask the RpfTocEntry if the frames have been loaded, and call this if they have not. - */ - protected void loadFrameInformation(RpfTocEntry rpfTocEntry) { - try { - if (binFile == null && aTocFilePath != null) { - binFile = new BinaryBufferedFile(aTocFilePath); - binFile.byteOrder(aTocByteOrder); - readFrameInformation(binFile, rpfTocEntry); - binFile.close(); - binFile = null; - } - } catch (IOException ioe) { - Debug.error("RpfTocHandler: IO ERROR parsing file for frame information!\n\t" + ioe); - } catch (FormatException fe) { - Debug.error("RpfTocHandler: Format ERROR parsing file for frame information!\n\t" + fe); - } - } - - /** - * Reads the BinaryFile to retrieve the Frame file information for the entry. - * - * @param binFile a valid, open BinaryFile. - * @param entry the RpfTocEntry to fill. - * @throws IOException - * @throws FormatException - */ - protected void readFrameInformation(BinaryFile binFile, RpfTocEntry entry) - throws IOException, FormatException { - int boundaryId, frameRow, frameCol; // ushort - int currentPosition; - int pathLength; - long pathOffset; // uint, offset of frame file pathname - RpfFrameEntry frame; - - int currentBoundaryIdForEntry = entry.coverage.entryNumber; - - // Read frame file index records - for (int i = 0; i < numFrameIndexRecords; i++) { - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("RpfTocHandler: parseToc(): Read frame file index rec #: " + i); - } - - // Index_subhdr_len (9) instead of table_offset (11) - // indexRecordLength (33) instead of 35 - // componentLocation, not index - // locations[3] is frame file index table subsection - binFile.seek(locations[3].componentLocation + indexRecordLength * i); - - boundaryId = (int) binFile.readShort(); - - if (boundaryId != currentBoundaryIdForEntry) { - // Only load the frame names of the entry we are using... - continue; - } - - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("boundary id for frame: " + i + " is " + boundaryId); - } - - // DKS NEW: changed from 1 to 0 to agree w/ spec. -1 - // added also. - // if (boundaryId < 0 || boundaryId > numBoundaries - - // 1 ) - if (boundaryId > numBoundaries - 1) { - throw new FormatException("Bad boundary id in FF index record " + i); - } - - frameRow = (int) binFile.readShort(); - frameCol = (int) binFile.readShort(); - - // DKS. switched from horizFrames to vertFrames - // DKS NEW: CHANGED FROM 1 to 0 to agree w/spec. ALSO - // COL below - // if (frameRow < 1 || frameRow > entry->vertFrames) - if (frameRow > entry.vertFrames - 1) { - throw new FormatException("Bad row number: " + frameRow + ", in FF index record " + i - + ", Min row num=0; Max. row num:" + (entry.horizFrames - 1)); - } - - // DKS. switched from vertFrames to horizFrames - if (frameCol > entry.horizFrames - 1) { - throw new FormatException(" Bad col number in FF index record " + i); - } - - // DKS NEW: -1 removed on frameRow, col - // JRB - // frame = &entry->frames[frameRow][frameCol]; - // [(entry->vertFrames - 1L)-frameRow] flips the array - // over, so that the frames can be referenced - // correctly from the top left, instead of the - // specification notation of bottom left. - frame = entry.getFrame((entry.vertFrames - 1) - frameRow, frameCol); - - if (frame.exists && DEBUG_RPFTOCDETAIL) { - Debug.output("FF " + i + " is a duplicate"); - } - - // DKS: phys_loc deleted - // pathname offset - pathOffset = (long) binFile.readInteger(); - - if (pathOffset < 0) { - continue; - } - - // Save file position for later - currentPosition = (int) binFile.getFilePointer(); - - // Go to start of pathname record - // DKS. New pathOffset offset from start of frame file - // index section of TOC?? - // DKS. Add pathoffset wrt frame file index table - // subsection (loc[3]) - binFile.seek(locations[3].componentLocation + pathOffset); - - pathLength = (int) binFile.readShort(); - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("RpfTocHandler: parseToc(): pathLength:" + pathLength); - } - - // 1st part of directory name is passed as arg: - // e.g. "../RPF2/" - String rpfdir = dir; - StringBuffer sBuf = new StringBuffer(pathLength); - - // read rest of directory name from toc - // DKS: skip 1st 2 chars: "./": - String pathTest = binFile.readFixedLengthString(2); - if (pathTest.equals("./")) { - fullPathsInATOC = false; - } else { - fullPathsInATOC = true; - } - - if (!fullPathsInATOC) { - // DKS: Make up for skipped 2 chars - sBuf.append(binFile.readFixedLengthString(pathLength - 2)); - } else { - sBuf.append(pathTest); - sBuf.append(binFile.readFixedLengthString(pathLength - 2)); - } - - // Add the trim because it looks like NIMA doesn't - // always get the pathLength correct... - String directory = sBuf.toString().trim(); - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("RpfTocHandler: parseToc(): frame directory: " + directory); - } - - /* Go back to get filename tail */ - binFile.seek(currentPosition); - - String filename = binFile.readFixedLengthString(12); - if (DEBUG_RPFTOCFRAMEDETAIL) { - Debug.output("RpfTocHandler: parseToc(): frame filename: " + filename); - } - - // Figure out the chart series ID - int dot = filename.lastIndexOf('.'); - // Interned so we can look it up in the catalog - // later... - entry.setInfo(filename.substring(dot + 1, dot + 3).intern()); - - // We duplicate this below!!! - // frame.framePath = new String(frame.rpfdir + - // frame.directory + - // "/" + frame.filename); - // DKS new DCHUM. Fill in last digit v of vv version - // #. fffffvvp.JNz or ffffffvp.IMz for CIB boundaryId - // will equal frame file number: 1 boundary rect. per - // frame. - // if (Dchum) - // entries[boundaryId].version = - // frame.filename.charAt(6); - String tempPath; - - if (!fullPathsInATOC) { - tempPath = rpfdir + directory + filename; - frame.rpfdirIndex = (short) (rpfdir.length() - 3); - frame.filenameIndex = (short) (rpfdir.length() + directory.length()); - } else { - tempPath = directory + filename; - frame.filenameIndex = (short) directory.length(); - } - - frame.framePath = tempPath; - frame.exists = true; - - // You don't want to check for the existance of frames here, do - // it at load time, and then mark the entry if the load fails. - // If you do the check here, you waste a lot of I/O time and - // effort. Assume it's there, the RPFFrame has been modified - // to try lower case names if needed. - if (frame.framePath == null) { - Debug.output("RpfTocHandler: Frame " + tempPath - + " doesn't exist. Please rebuild A.TOC file using MakeToc, or check read permissions for the file."); - } - } /* for i = numFrameIndexRecords */ - - } - - /** - * Util-like function that translates a long to the string representation found in the A.TOC file. - */ - public static String translateScaleToSeries(long scale) { - if (scale == 0) { - return "Various "; - } else if (scale == 50000L) { - return "1:50K "; - } else if (scale == 100000L) { - return "1:100K "; - } else if (scale == 200000L) { - return "1:200K "; - } else if (scale == 250000L) { - return "1:250K "; - } else if (scale == 500000L) { - return "1:500K "; - } else if (scale == 1000000L) { - return "1:1M "; - } else if (scale == 2000000L) { - return "1:2M "; - } else if (scale == 5000000L) { - return "1:5M "; - } else if (scale == 66666L) { - return "10M "; - } else if (scale == 33333L) { - return "5M "; - } else { - return (String) null; - } - } - - /** - * Given the scale string found in the A.TOC file, decode it into a 'long' scale. - */ - public static long textScaleToLong(String textScale) { - - long resolution = 1l; - long realValue; - int expLetter; // location of m, M, K - int expLetterSmall; - - // Make sure there are no commas, commas seem to kill Long parsing. - int commaIndex = textScale.indexOf(','); - while (commaIndex != -1) { - StringBuffer buf = new StringBuffer(textScale.substring(0, commaIndex)); - buf.append(textScale.substring(commaIndex + 1)); - textScale = buf.toString(); - commaIndex = textScale.indexOf(','); - } - - int colon = textScale.indexOf(":"); - - try { - if (colon == -1) { - // dealing with an imagery scale - expLetter = textScale.indexOf("m"); - if (expLetter == -1) { - expLetter = textScale.indexOf("M"); - } - - if (expLetter != -1) { - resolution = Long.parseLong(textScale.substring(0, expLetter)); - return (long) (resolution / .000150); - } - - // If we get here, we're dealing with a chart scale that doesn't - // have a 1: at the front of it, so continue on... - } - - // dealing with a map scale - String expValue = ""; - - expLetter = textScale.lastIndexOf('K'); - expLetterSmall = textScale.lastIndexOf('k'); - - if (expLetter == -1 && expLetterSmall == -1) { - expLetter = textScale.lastIndexOf('M'); - expLetterSmall = textScale.lastIndexOf('m'); - - if (expLetter != -1 || expLetterSmall != -1) { - expValue = "000000"; - } - } else { - expValue = "000"; - } - - StringBuffer buf; - if (expValue.length() > 0) { - // make sure we have the right index variable - if (expLetter == -1) { - expLetter = expLetterSmall; - } - // If there isn't a colon, this should be OK - buf = new StringBuffer(textScale.substring(colon + 1, expLetter)); - buf.append(expValue); - } else { - buf = new StringBuffer(textScale.substring(colon + 1)); - } - - String longString = buf.toString().trim(); - realValue = Long.parseLong(longString); - - } catch (NumberFormatException nfe) { - if (Debug.debugging("rpftoc")) { - Debug.output("textScaleToLong: Number Format Exception!!!!" + textScale); - } - return (long) RpfConstants.Various; - } catch (StringIndexOutOfBoundsException sioobe) { - if (Debug.debugging("rpftoc")) { - Debug.output("textScaleToLong: String index out of bounds:\n" + sioobe.getMessage()); - } - return (long) RpfConstants.Various; - } - - if (colon != -1) { - resolution = Long.parseLong(textScale.substring(0, colon)); - } - - long ret = (realValue / resolution); - - if (Debug.debugging("rpftoc")) { - Debug.output("RpfTocHandler: textScaleToLong converted " + textScale + " to " + ret); - } - - return ret; - - } - - protected int getASCIIZone(double ullat, int zone) { - int z = zone; - // Now convert it to ASCII to compare - if (ullat > 0) { - z += 48; // for ASCII compare next - } else { - z += 64; - if (z == 73) { - z++; // Can't be equal to I -> J - } - } - return z; - } - - /** - * Given a coordinate box and a scale, return the entries that have coverage over the given area. The chart types - * returned are dictated by the chartSeriesCode passed in, which must be an entry from an RpfProductInfo.seriesCode. - * - * @param ullat upper left latitude, in decimal degrees - * @param ullon upper left longitude, in decimal degrees - * @param lrlat lower right latitude, in decimal degrees - * @param lrlon lower right longitude, in decimal degrees - * @param proj CADRG projection describing map. - * @param chartSeriesCode chart selection. If null, all coverage boxes fitting on the screen will be returned. - * @param coverages a list of potential coverages - */ - public void getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection proj, - String chartSeriesCode, - Vector coverages) { - if (!valid) { - return; - } - - String chartSeries; - - for (int i = 0; i < numBoundaries; i++) { - - // Try to get the boundary rectangle with the most - // coverage, so reset the entry for this particular query. - entries[i].coverage.reset(); - - if (chartSeriesCode == null) { - chartSeries = RpfViewAttributes.ANY; - } else { - chartSeries = chartSeriesCode; - } - - if (chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY) || chartSeries.equalsIgnoreCase( - entries[i].info.seriesCode)) { - - if (entries[i].coverage.setPercentCoverage(ullat, ullon, lrlat, lrlon) > 0f) { - coverages.addElement(entries[i].coverage); - } - } - } - } - - /** - * Given a coordinate box and a scale, find the entry in the table of contents file with the right data. Zone is - * always of the northern hemisphere, and is transformed to southern inside if needed. The box will get filled in - * with the correct information. The subframe description will have scaling information for the subframes to be - * scaled to match the scale. If proj is null, only exact matches will be found - * - * NOTE: method getZone() of the CADRG projection is only relevant (according to OpenMap documentation) when you're - * viewing a map type (ONC, etc) at its proper scale (i.e. 1:1mil for ONC). There was a method in RpfTocHandler that - * only checked a TOC for coverage if the TOC zone matched the zone of the projection. This caused gaps of coverage - * when viewing the maps at large scales that were different from their proper scale (e.g. viewing JNC at 1:10mil). - * Modified this method so that it obtains all the possible zones the current map projection could be in, and - * compares the TOC zones to that set. - * - * Note that this now returns a list of coverage entries instead of just one. - * - * @param ullat upper left latitude, in decimal degrees - * @param ullon upper left longitude, in decimal degrees - * @param lrlat lower right latitude, in decimal degrees - * @param lrlon lower right longitude, in decimal degrees - * @param proj CADRG projection describing map. - * @param viewAtts view attributes determine chart selection. - * @return a Vector of applicable RpfCoverageBoxes. - */ - public List getBestCoverageEntry(double ullat, double ullon, double lrlat, double lrlon, Projection proj, - RpfViewAttributes viewAtts) { - if (!valid) { - return null; - } - - List coverageEntries = new Vector(); - double scaleFactor = 0; - double lowerScaleFactorLimit = 1.0; - double upperScaleFactorLimit = 1.0; - - // Good for a preliminary check. It has to start at least as - // 4 to have one corner matching. - int prevBoundaryHits = 0; - - if (viewAtts != null) { - lowerScaleFactorLimit = (double) (1.0 / viewAtts.imageScaleFactor); - upperScaleFactorLimit = (double) viewAtts.imageScaleFactor; - } - - int nscale = 0; - int scale = (int) proj.getScale(); - - RpfTocEntry bestEntry = null; - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("getBestCoverageEntry(): Checking for coverage"); - Debug.output(" nw_lat: " + ullat); - Debug.output(" se_lat: " + lrlat); - Debug.output(" nw_lon: " + ullon); - Debug.output(" se_lon: " + lrlon); - } - - CADRG cadrg = CADRG.convertProjection(proj); - - int zone = getASCIIZone(ullat, cadrg.getZone()); - char okZones[] = getOkZones(ullat, lrlat, (char) zone); - - for (RpfTocEntry currentEntry : entries) { - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("********************"); - Debug.output(" tochandler: Boundary #" + currentEntry.coverage.entryNumber); - Debug.output(currentEntry.toString()); - } - - // Try to get the boundary rectangle with the most - // coverage, so reset the entry for this particular query. - currentEntry.coverage.reset(); - - // Find the scale of the boundary rectangle - if (currentEntry.info == null || currentEntry.info.scale == RpfConstants.Various) { - - nscale = (int) textScaleToLong(currentEntry.scale); - - // Reset the RpfProductInfo to the listed parameters - // in the A.TOC file. - currentEntry.altScale = (float) nscale; - currentEntry.altScaleString = currentEntry.scale; - currentEntry.coverage.scale = (float) nscale; - - } else { - currentEntry.coverage.scale = currentEntry.info.scale; - nscale = (int) currentEntry.info.scale; - } - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("getBestCoverageEntry(): Query scale = " + scale + " vs. brect scale = " + nscale); - } - - // if you want an exact match for scale... - if (viewAtts != null && !viewAtts.scaleImages) { - if (scale == nscale) { - scaleFactor = 1.0; - } else { - scaleFactor = lowerScaleFactorLimit - 1.0; - } - } else { - scaleFactor = (double) nscale / (double) scale; - } - - String chartSeries; - if (viewAtts == null) { - chartSeries = RpfViewAttributes.ANY; - } else { - chartSeries = viewAtts.chartSeries; - } - - if (scaleFactor >= lowerScaleFactorLimit - && scaleFactor <= upperScaleFactorLimit - && (chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY) || chartSeries.equalsIgnoreCase( - currentEntry.info.seriesCode))) { - - if (ignoreZonesForCoverageBoxes || isOkZone(currentEntry.zone, okZones)) { - // sets currentEntry.coverage.boundaryHits - int hits = currentEntry.coverage.setBoundaryHits(ullat, ullon, lrlat, lrlon); - - if (DEBUG_RPFTOCDETAIL) { - Debug.output("getBestCoverageEntry(): Boundary Hits = " + hits); - } - - if (bestEntry != null) { - - boolean betterScale = false; - - float newScaleDiff = RpfFrameCacheHandler.scaleDifference(proj, currentEntry.coverage); - float bestScaleDiff = RpfFrameCacheHandler.scaleDifference(proj, bestEntry.coverage); - - float currentEntryPercentCoverage = currentEntry.coverage - .setPercentCoverage(ullat, ullon, lrlat, lrlon); - - if ((currentEntryPercentCoverage == 100f - || (viewAtts != null && viewAtts.scaleMoreImportantThanCoverage)) - && newScaleDiff <= bestScaleDiff) { - betterScale = true; - } - - if (betterScale - && (currentEntryPercentCoverage >= bestEntry.coverage.getPercentCoverage()) - && (hits >= prevBoundaryHits || hits >= 6)) { - - // Add to list if has any hits and is - // the best possible scale. If new scale - // difference - // is strictly better, remove other - // entries - if (newScaleDiff < bestScaleDiff) { - coverageEntries.clear(); - } - coverageEntries.add(currentEntry); - - bestEntry = currentEntry; - prevBoundaryHits = hits; - - if (DEBUG_RPFTOC) { - Debug.output("getBestCoverageEntry(): Found a match in a BR with coverage of " - + currentEntry.coverage.getPercentCoverage() + "%."); - } - } else if (betterScale && currentEntry.coverage.getPercentCoverage() > 0f) { - - if (newScaleDiff < bestScaleDiff) { - coverageEntries.clear(); - } - coverageEntries.add(currentEntry); - bestEntry = currentEntry; - prevBoundaryHits = hits; - } - - } else if (hits > prevBoundaryHits - && (currentEntry.coverage.setPercentCoverage(ullat, ullon, lrlat, lrlon) > 0f)) { - bestEntry = currentEntry; - prevBoundaryHits = hits; - - // Add to list of coverageEntries - coverageEntries.add(currentEntry); - - if (DEBUG_RPFTOC) { - Debug.output("getBestCoverageEntry(): Found a match in a BR with coverage of " - + currentEntry.coverage.getPercentCoverage() + "%."); - - } - } - } - } - } - - if (DEBUG_RPFTOC) { - if (bestEntry != null) { - Debug.output("getBestCoverageEntry(): found the best"); - Debug.output("################"); - Debug.output(bestEntry.toString()); - Debug.output("Returning the following coverage boxes: "); - - for (int i = 0; i < coverageEntries.size(); i++) { - Debug.output(coverageEntries.get(i).toString()); - } - } else { - Debug.output("getBestCoverageEntry(): no box found"); - } - } - - return coverageEntries; - } - - public static char[] getOkZones(double ullat, double lrlat, char zone) { - // allow a maximum of 3 additional zones in either direction - char[] okZones = new char[7]; - // add zone from projection - okZones[0] = zone; - // check above - char currentZone = zone; - char backupZone; - int i = 0; - for (; i < 3; i++) { - if (isAboveZone(ullat, currentZone)) { - backupZone = getHigherZone(currentZone); - okZones[i + 1] = backupZone; - currentZone = backupZone; - } else { - break; - } - } - // check below - int k = i; - currentZone = zone; - for (; k < i + 3; k++) { - if (isBelowZone(ullat, currentZone)) { - backupZone = getLowerZone(currentZone); - okZones[k + 1] = backupZone; - currentZone = backupZone; - } else { - break; - } - } - int size = 0; - for (int j = 0; j < okZones.length; j++) { - if (okZones[j] != 0) { - size++; - } - } - char[] returnZones = new char[size]; - System.arraycopy(okZones, 0, returnZones, 0, size); - return returnZones; - } - - public static boolean isOkZone(char zone, char[] okZones) { - boolean ok = false; - for (int i = 0; i < okZones.length; i++) { - if (zone == okZones[i]) { - ok = true; - } - } - return ok; - } - - protected static boolean isBelowZone(double lowerLat, char zone) { - float zoneLowerLat = getLowerZoneExtent(zone); - if (lowerLat < zoneLowerLat) { - return true; - } else { - return false; - } - } - - protected static boolean isAboveZone(double upperLat, char zone) { - float zoneUpperLat = getUpperZoneExtent(zone); - if (upperLat > zoneUpperLat) { - return true; - } else { - return false; - } - } - - public static float getUpperZoneExtent(char zone) { - - if (zone >= '0' && zone <= '9') { - int i = zone - 49; - return CADRG_zone_extents[i + 1]; - } else { - int i = zone - 65; - if (i == 9) { - i--; // Special care for j - } - return -1 * CADRG_zone_extents[i]; - } - } - - public static float getLowerZoneExtent(char zone) { - if (zone >= '0' && zone <= '9') { - int i = zone - 49; - return CADRG_zone_extents[i]; - } else { - int i = zone - 65; - if (i == 9) { - i--; // Special care for J - } - return -1 * CADRG_zone_extents[i + 1]; - } - } - - public static char getLowerZone(char zone) { - // if zone = 'J' do nothing - if (zone >= '2' && zone <= '9') { - zone--; - } else if (zone == '1') { - zone = 'A'; - } else if (zone >= 'A' && zone < 'H') { - zone++; - } else if (zone == 'H') { - zone = 'J'; - } - return zone; - } - - public static char getHigherZone(char zone) { - // if zone = '9' do nothing - if (zone >= '1' && zone < '9') { - zone++; - } else if (zone >= 'B' && zone < 'J' || zone >= 'b' && zone < 'j') { - zone--; - } else if (zone == 'J' || zone == 'j') { - zone -= 2; - } else if (zone == 'A' || zone == 'a') { - zone = '1'; - } - return zone; - } - - /** - * Return the list of grouped frames. - */ - public RpfTocEntry[] getEntries() { - return entries; - } - - public String getATocFilePath() { - return aTocFilePath; - } - - public void setATocFilePath(String tocFilePath) { - aTocFilePath = tocFilePath; - } - - public boolean isFullPathsInATOC() { - return fullPathsInATOC; - } - - public void setFullPathsInATOC(boolean fullPathsInATOC) { - this.fullPathsInATOC = fullPathsInATOC; - } - - /** - * @return the ignoreZonesForCoverageBoxes - */ - public boolean isIgnoreZonesForCoverageBoxes() { - return ignoreZonesForCoverageBoxes; - } - - /** - * @param ignoreZonesForCoverageBoxes the ignoreZonesForCoverageBoxes to set - */ - public void setIgnoreZonesForCoverageBoxes(boolean ignoreZonesForCoverageBoxes) { - this.ignoreZonesForCoverageBoxes = ignoreZonesForCoverageBoxes; - } - - public static void main(String[] args) { - if (args.length != 1) { - Debug.output("Usage: java RpfTocHandler "); - return; - } - - Debug.init(System.getProperties()); - - RpfTocHandler toc = new RpfTocHandler(); - if (!toc.loadFile(args[0])) { - Debug.output("RpfTocHandler: NOT read successfully!"); - } else { - RpfTocEntry[] e = toc.getEntries(); - Debug.output("For A.TOC: " + args[0]); - for (int i = 0; i < e.length; i++) { - Debug.output(e[i].toString()); - } - } - - System.exit(0); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfUtil.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfUtil.java deleted file mode 100644 index 314cceec0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfUtil.java +++ /dev/null @@ -1,674 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: RpfUtil.java,v $ -//$Revision: 1.4 $ -//$Date: 2007/03/12 20:52:46 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; - -/** - * The RpfUtil is a program that will allow you to manage RPF data - * geographically. You can copy and delete RPF data frames from RPF - * data directories, make an A.TOC file for a RPF directory (even - * after copying and/or deleting), and you can zip an RPF directory - * into an archive if you like. You can limit the commands to only - * affect those frames completely inside or outside a specified area, - * or for those frames that intersect and are contained by that area - * (default). You can also limit the charts affected based on their - * map scales, providing a scale and indicating that you only want - * those frames that match the scale, do not match the scale, are - * greater or less than the scale. Greater than or less than refers to - * the scale number of the chart being greater or less than the scale - * number provided, NOT whether the resulting scale ratio is greater or - * less than. These things are opposite if each other, and we're just - * working with the numbers. - *

- * - * When you call RpfUtil.setRpfDir, that calls organizeFrames(rpfDir), - * which creates a list of the frames affected by the scale and - * boundary settings. Then, the operation runs on those frames. - *

- * - * It is important that the A.TOC file in the source RPF directory - * reflects the current state of the data in that directory. If you - * are not sure, run this program with the -maketoc option on that - * directory to update it. - * - * @author dietrick - */ -public class RpfUtil { - - public final static char SCALE_EQUALS = 'e'; - public final static char SCALE_NOTEQUALS = 'n'; - public final static char SCALE_GREATERTHAN = 'g'; - public final static char SCALE_LESSTHAN = 'l'; - public final static float ALL_SCALES = 0f; - - public final static int BOUNDED = 0; - public final static int INSIDE = 1; - public final static int OUTSIDE = 2; - - protected int boundaryLimits = BOUNDED; - protected float scale = ALL_SCALES; - protected char scaleDelim = SCALE_EQUALS; - protected float upperLat = 90f; - protected float leftLon = -180; - protected float lowerLat = -90f; - protected float rightLon = 180f; - protected String rpfDir; - - protected boolean verbose = false; - - protected List frameList; - - /** - * Create a default RpfUtil considering all data. - */ - public RpfUtil() {} - - /** - * Create a RpfUtil considering data intersecting the provided - * boundary. The RPF data directory still needs to be set. - * - * @param ulat upper latitude - * @param llon left longitude - * @param llat lower latitude - * @param rlon right longitude - */ - public RpfUtil(float ulat, float llon, float llat, float rlon) { - this(null, ulat, llon, llat, rlon, 0f, SCALE_EQUALS, BOUNDED); - } - - /** - * Create a RpfUtil considering data intersecting the provided - * boundary, involving the provided RPF directory. - * - * @param rpfDir the RPF directory to search and consider frames - * over. - * @param ulat upper latitude - * @param llon left longitude - * @param llat lower latitude - * @param rlon right longitude - */ - public RpfUtil(String rpfDir, float ulat, float llon, float llat, float rlon) { - this(rpfDir, ulat, llon, llat, rlon, 0f, SCALE_EQUALS, BOUNDED); - } - - /** - * Full control over the RpfUtil settings. - * - * @param rpfDir the RPF directory to search and consider frames - * over. - * @param ulat upper latitude - * @param llon left longitude - * @param llat lower latitude - * @param rlon right longitude - * @param scale the scale of the charts to consider. - * @param scaleDelimiter character 'g'reater than, 'l'ess than, - * 'n'ot equal to, 'e'qual to. e is the default. - * @param boundaryLimits INSIDE, OUTSIDE or BOUNDARY - */ - public RpfUtil(String rpfDir, float ulat, float llon, float llat, - float rlon, float scale, char scaleDelimiter, int boundaryLimits) { - this.upperLat = ulat; - this.lowerLat = llat; - this.leftLon = llon; - this.rightLon = rlon; - this.scale = scale; - this.scaleDelim = scaleDelimiter; - this.boundaryLimits = boundaryLimits; - - setRpfDir(rpfDir); - } - - /** - * Creates the list of frames to consider, based on settings. This - * method does a cursory check of scale settings before moving to - * geographical settings. - * - * @param rpfDir - * @return List of relative path names to frames. - */ - protected List organizeFrames(String rpfDir) { - RpfTocHandler toc = new RpfTocHandler(rpfDir); - List frameList = new LinkedList(); - - if (toc.isValid()) { - RpfTocEntry[] entries = toc.getEntries(); - if (verbose) { - Debug.output("Figuring out which frames fit the criteria..."); - } - for (int i = 0; i < entries.length; i++) { - RpfTocEntry entry = entries[i]; - toc.loadFrameInformation(entry); - - double udinterval = (entry.coverage.nw_lat - entry.coverage.se_lat) - / entry.vertFrames; - double rlinterval = (entry.coverage.se_lon - entry.coverage.nw_lon) - / entry.horizFrames; - - if (scale > 0) { - float rectScale = (float) RpfTocHandler.textScaleToLong(entry.scale); - - if (rectScale == RpfProductInfo.UK.scale) { - if (verbose) { - Debug.output(" RpfTocEntry[" + i - + "] scale unknown (" - + entry.coverage.chartCode + "), skipping"); - } - continue; - } - - switch (scaleDelim) { - case SCALE_EQUALS: - if (scale == rectScale) - frameList.addAll(getFrameList(entry, - rlinterval, - udinterval)); - break; - case SCALE_GREATERTHAN: - if (scale >= rectScale) - frameList.addAll(getFrameList(entry, - rlinterval, - udinterval)); - break; - case SCALE_LESSTHAN: - if (scale <= rectScale) - frameList.addAll(getFrameList(entry, - rlinterval, - udinterval)); - break; - case SCALE_NOTEQUALS: - if (scale != rectScale) - frameList.addAll(getFrameList(entry, - rlinterval, - udinterval)); - default: - break; - } // switch - - } else { - frameList.addAll(getFrameList(entry, rlinterval, udinterval)); - } - - } - } - - return frameList; - - } - - /** - * Middle management for frames for A.TOC entry box. - * - * @param entry RpfTocEntry to consider. - * @param rlinterval right to left decimal degree interval for - * entry. - * @param udinterval up to down decimal degree interval for entry - * @return List of frame strings that pass current settings. - */ - protected List getFrameList(RpfTocEntry entry, double rlinterval, - double udinterval) { - List frameList = new LinkedList(); - - for (int hor = 0; hor < entry.horizFrames; hor++) { - for (int ver = 0; ver < entry.vertFrames; ver++) { - - RpfFrameEntry frame = entry.getFrame(ver, hor); - - double left = entry.coverage.nw_lon + (rlinterval * hor); - double right = left + rlinterval; - double up = entry.coverage.nw_lat - (udinterval * ver); - double down = up - udinterval; - - if (frame.exists - && frameFitsCriteria(left, - right, - up, - down, - rlinterval, - udinterval)) { - String name = frame.framePath.substring(frame.rpfdirIndex + 3); - - frameList.add(name); - - if (verbose) { - Debug.output(" getFrameList: adding file " + name); - } - } - - } - } - - return frameList; - } - - /** - * Geographical evaluation of frame file - * - * @return true if file should be added to the list. - */ - protected boolean frameFitsCriteria(double left, double right, double up, - double down, double rlinterval, - double udinterval) { - - switch (boundaryLimits) { - case OUTSIDE: - return (left < leftLon && right < leftLon) - || (left > rightLon && right > rightLon) - || (up < lowerLat && down < lowerLat) - || (up > upperLat && down > upperLat); - case INSIDE: - return (left > leftLon && right > leftLon && left < rightLon - && right < rightLon && up > lowerLat && down > lowerLat - && up < upperLat && down < upperLat); - default: - return (((right <= rightLon && left >= leftLon - rlinterval) - || (left >= leftLon && right <= rightLon + rlinterval) || (left <= leftLon && right >= rightLon)) && ((up <= upperLat - + udinterval && down >= lowerLat) - || (down >= lowerLat - udinterval && up <= upperLat) || (up >= upperLat && down <= lowerLat))); - } - } - - /** - * Copy the frame files currently set on the FrameList to the - * provided RPF directory. - * - * @param toRpfDir - * @return true if it works. - */ - public boolean copy(String toRpfDir) { - File toDir = new File(toRpfDir); - boolean ret = false; - String sourceRpfDir = getRpfDir(); - if ((toDir.exists() || toDir.mkdirs()) && frameList != null) { - if (verbose) { - Debug.output("From " + sourceRpfDir + " to " + toRpfDir + ":"); - } - for (Iterator it = frameList.iterator(); it.hasNext();) { - String relativeFilePath = "/" + it.next(); - File fromFile = new File(sourceRpfDir + relativeFilePath); - File toFile = new File(toRpfDir + relativeFilePath); - File toParent = toFile.getParentFile(); - if (!toParent.exists()) { - toParent.mkdirs(); - } - if (verbose) { - Debug.output("Copying " + relativeFilePath); - } - - try { - FileUtils.copy(fromFile, toFile, 400000); - } catch (IOException ioe) { - Debug.error("RpfUtil.copy: IOExeption copying files: " - + ioe.getMessage()); - return false; - } - } - ret = true; - } - - return ret; - } - - /** - * Create an A.TOC file for the provided RPF directory. - * - * @param rpfDir - * @return true if it works. - */ - public boolean maketoc(String rpfDir) { - boolean ret = false; - - MakeToc mt = new MakeToc(); - String[] paths = new String[] { rpfDir }; - - // paths is going to be reset to list all of the RPF frame - // file paths. - paths = mt.searchForRpfFiles(paths); - - try { - mt.create(paths, - rpfDir + "/" + RpfTocHandler.RPF_TOC_FILE_NAME, - false); - ret = true; - } catch (MakeTocException mte) { - Debug.error("Problem creating A.TOC file: \n" + mte.getMessage()); - } - - return ret; - } - - /** - * Delete the files in the provided RPF directory that match the - * current scale and boundary settings. - * - * @param rpfDir - * @return true if it works. - */ - public boolean delete(String rpfDir) { - boolean ret = false; - - List frameList = organizeFrames(rpfDir); - if (frameList != null) { - for (Iterator it = frameList.iterator(); it.hasNext();) { - String relativeFilePath = "/" + it.next(); - File fromFile = new File(rpfDir + relativeFilePath); - if (fromFile.exists() && fromFile.delete() && verbose) { - Debug.output("Deleting " + fromFile.getPath()); - } - } - ret = true; - } - - return ret; - } - - /** - * Store the contents of the toBeZippedName directory into a zip - * file with the provided name. If the zip file name doesn't end - * in .zip, it will. - * - * @param zipLocation - * @param toBeZippedName - * @return true if it works. - */ - public boolean zip(String zipLocation, String toBeZippedName) { - boolean ret = false; - - if (verbose) - Debug.put("zip"); - - File toBeZipped = new File(toBeZippedName); - if (toBeZipped.exists()) { - try { - FileUtils.saveZipFile(zipLocation, toBeZipped); - ret = true; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return ret; - } - - /** - * Just run a query on the provided directory, listing the names - * of the frames that will be affected by the current scale and - * boundary settings. - * - * @param rpfDir - */ - public void query(String rpfDir) { - List frameList = organizeFrames(rpfDir); - if (frameList != null) { - for (Iterator it = frameList.iterator(); it.hasNext();) { - Debug.output(it.next().toString()); - } - } - } - - /** - * The RpfUtil class can be run as a java program. This program - * will allow commands to be stacked, but will execute them in - * this order - copy, delete, maketoc, zip. Only one version of - * each argument is allowed per execution. - * - * @param args - */ - public static void main(String[] args) { - Debug.init(); - ArgParser ap = new ArgParser("RpfUtil"); - ap.add("copy", - "Copy RPF data from one RPF directory to another. (-copy from to)", - 2); - ap.add("delete", - "Delete RPF data from a RPF directory. (-delete from)", - 1); - ap.add("maketoc", - "Create an A.TOC file in a RPF directory. (-maketoc from).", - 1); - ap.add("zip", - "Create a zip file from a RPF directory. (-zip zipFileName from)", - 2); - ap.add("query", - "Print the paths of files that fit the criteria, but do nothing", - 1); - ap.add("scale", - "The scale to use for criteria in matching chart types, followed by a letter describing the relationship of matching frame scales to give scale ('g'reater than, 'l'ess than, 'n'ot equal to, 'e'qual to). (optional)", - 2); - ap.add("boundary", - "Coordinates of bounding box (upper lat, left lon, lower lat, right lon) (optional)", - 4, - true); - ap.add("inside", - "Flag to manage RPF frames inside bounding box. (default, optional)"); - ap.add("outside", - "Flag to manage RPF frames outside bounding box. (optional)"); - ap.add("verbose", "Print out progress"); - ap.add("extraverbose", "Print out ALL progress"); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - float ulat = 90f; - float llat = -90f; - float llon = -180f; - float rlon = 180f; - - String arg[]; - arg = ap.getArgValues("boundary"); - if (arg != null) { - boolean boundaryCoordinateProblem = true; - try { - ulat = Float.parseFloat(arg[0]); - llon = Float.parseFloat(arg[1]); - llat = Float.parseFloat(arg[2]); - rlon = Float.parseFloat(arg[3]); - - boundaryCoordinateProblem = ulat > 90 || llon < -180 - || llat < -90 || rlon > 180 || ulat <= llat - || llon >= rlon; - - } catch (NumberFormatException nfe) { - Debug.error("Parsing error for boundary coordinates"); - } - - if (boundaryCoordinateProblem) { - Debug.error("Boundary coordinates are screwy..."); - ap.printUsage(); - System.exit(0); - } - } - - RpfUtil rpfUtil = new RpfUtil(ulat, llon, llat, rlon); - - rpfUtil.verbose = (ap.getArgValues("verbose") != null); - - arg = ap.getArgValues("outside"); - if (arg != null) { - rpfUtil.setBoundaryLimits(RpfUtil.OUTSIDE); - } - - arg = ap.getArgValues("inside"); - if (arg != null) { - rpfUtil.setBoundaryLimits(RpfUtil.INSIDE); - } - - arg = ap.getArgValues("scale"); - if (arg != null) { - try { - rpfUtil.setScale(Float.parseFloat(arg[0])); - rpfUtil.setScaleDelim(arg[1].charAt(0)); - } catch (NumberFormatException nfe) { - Debug.error("Scale value is screwy..."); - ap.printUsage(); - System.exit(0); - } - } - - arg = ap.getArgValues("query"); - if (arg != null) { - rpfUtil.query(arg[0]); - System.exit(0); - } - - arg = ap.getArgValues("copy"); - if (arg != null) { - rpfUtil.setRpfDir(arg[0]); - if (!rpfUtil.copy(arg[1])) { - Debug.output("Problem copying frames"); - } - } - - arg = ap.getArgValues("delete"); - if (arg != null && !rpfUtil.delete(arg[0])) { - Debug.output("Problem deleting files."); - } - - arg = ap.getArgValues("maketoc"); - if (arg != null && !rpfUtil.maketoc(arg[0])) { - Debug.output("Problem creating A.TOC file for frames."); - } - - arg = ap.getArgValues("zip"); - if (arg != null && !rpfUtil.zip(arg[0], arg[1])) { - Debug.output("Problem creating zip file: " + arg[0]); - } - } - - public int getBoundaryLimits() { - return boundaryLimits; - } - - /** - * Set whether the frames need to be INSIDE, OUTSIDE or inside and - * touching the BOUNDARY of the geographical area set in the - * RpfUtil object. - * - * @param boundaryLimits - */ - public void setBoundaryLimits(int boundaryLimits) { - this.boundaryLimits = boundaryLimits; - } - - public List getFrameList() { - return frameList; - } - - public void setFrameList(List frameList) { - this.frameList = frameList; - } - - public float getLeftLon() { - return leftLon; - } - - public void setLeftLon(float leftLon) { - this.leftLon = leftLon; - } - - public float getLowerLat() { - return lowerLat; - } - - public void setLowerLat(float lowerLat) { - this.lowerLat = lowerLat; - } - - public float getRightLon() { - return rightLon; - } - - public void setRightLon(float rightLon) { - this.rightLon = rightLon; - } - - public String getRpfDir() { - return rpfDir; - } - - /** - * Creates the list of frames matching the geographical and scale - * parameters of the frames within the directory. - * - * @param rpfDir - */ - public void setRpfDir(String rpfDir) { - this.rpfDir = rpfDir; - if (rpfDir != null) { - frameList = organizeFrames(rpfDir); - } - } - - public float getScale() { - return scale; - } - - public void setScale(float scale) { - this.scale = scale; - } - - public char getScaleDelim() { - return scaleDelim; - } - - /** - * Set whether the frames considered should have scale numbers - * greater than (g), less than (l), not equal to (n) or equal to - * (e). Equal to is the default, and that's set if any other value - * os provided. - * - * @param scaleDelim - */ - public void setScaleDelim(char scaleDelim) { - if (scaleDelim == SCALE_NOTEQUALS || scaleDelim == SCALE_GREATERTHAN - || scaleDelim == SCALE_LESSTHAN) { - this.scaleDelim = scaleDelim; - } else { - this.scaleDelim = SCALE_EQUALS; - } - } - - public float getUpperLat() { - return upperLat; - } - - public void setUpperLat(float upperLat) { - this.upperLat = upperLat; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfViewAttributes.java b/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfViewAttributes.java deleted file mode 100644 index 3bb167efa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/RpfViewAttributes.java +++ /dev/null @@ -1,347 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfViewAttributes.java,v $ -// $RCSfile: RpfViewAttributes.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/08/09 19:25:47 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.rpf; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.OptionPropertyEditor; -import java.io.Serializable; -import java.util.Properties; - -/** - * This class contains information to pass through the RpfCacheManager and RpfCacheHandlers to describe limitations and - * parameters desired for data view. It contains information about the numbers of colors to use, how opaque to make the - * images, the chart series to retrieve, etc. - */ -public class RpfViewAttributes - implements RpfConstants, PropertyConsumer, Serializable { - - public final static String ANY = "ANY"; - public final static String ALL = "ALL"; - public final static String COLORMODEL_DIRECT_STRING = "direct"; - public final static String COLORMODEL_INDEXED_STRING = "indexed"; - - protected String propertyPrefix = null; - - /** - * Number of colors to use - 16, 32, 216 - */ - public int numberOfColors; - /** - * The opaqueness of the image (transparency) 0-255: 0 is clear, 255 is opaque. - */ - public int opaqueness; - /** - * The image colormodel to use, indexed or colortable, for the OMRasters. - */ - public int colorModel; - /** - * Flag to use to scale images or not. This will cause the caches to scale the images to match the map scale, - * instead of requiring the map to be at the same scale as the desired image. - */ - public boolean scaleImages; - /** - * The limiting factor for image scaling. Make this too big, and you will run out of memory. - */ - public float imageScaleFactor; - /** - * The data series two-letter code to limit responses to. If you want any data that is the closest match for the - * current map, use ANY (default). If you want all of the RpfCoverageBoxes that have some coverage, use ALL. - */ - public String chartSeries; - /** - * Flag to set if the CADRG projection is required. Might not be, if we start warping images. - */ - public boolean requireProjection; - /** - * Flag to display images. - */ - public boolean showMaps; - /** - * Flag to display attribute information about the subframes. - */ - public boolean showInfo; - /** - * Flag to tell TOC handler to use scale over percent coverage when choosing the best coverage box. If false, you'll - * get the best match with the most coverage, rather than coverage most appropriate for the map scale. The - * traditional behavior is true, as is the default setting. However, when the layer is used for creating tiles, you - * get better background results by setting this to false, and the gaps are filled in with different level coverage. - */ - protected boolean scaleMoreImportantThanCoverage = true; - - /** - * Autofetch the subframe attributes from the FrameProvider. Use only if you are interested in background - * information about the images. - */ - public boolean autofetchAttributes; - - protected transient I18n i18n = Environment.getI18n(); - - public RpfViewAttributes() { - setDefaults(); - } - - public void setDefaults() { - numberOfColors = RpfColortable.CADRG_COLORS; - opaqueness = RpfColortable.DEFAULT_OPAQUENESS; - scaleImages = true; - imageScaleFactor = 4.0f; - colorModel = OMRasterObject.COLORMODEL_DIRECT; - chartSeries = ANY; - requireProjection = true; - showMaps = true; - showInfo = false; - autofetchAttributes = false; - scaleMoreImportantThanCoverage = true; - } - - /** - * - * @return true of scale is used as a determining factor over coverage percentage when choosing best entry. - */ - public boolean isScaleMoreImportantThanCoverage() { - return scaleMoreImportantThanCoverage; - } - - /** - * Set whether scale is more of a determining factor over percent coverage when choosing best entry for a map - * projection. - * - * @param scaleMoreImportantThanCoverage - */ - public void setScaleMoreImportantThanCoverage(boolean scaleMoreImportantThanCoverage) { - this.scaleMoreImportantThanCoverage = scaleMoreImportantThanCoverage; - } - - // ======================================== - // PropertyConsumer interface - // ======================================== - /** - * Sets the properties. This particular method assumes that the marker name is not needed, because all of the - * contents of this Properties object are to be used for this object, and scoping the properties with a prefix is - * unnecessary. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(null, props); - } - - /** - */ - public void setProperties(String prefix, java.util.Properties props) { - propertyPrefix = prefix; - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - opaqueness = PropUtils.intFromProperties(props, prefix + OpaquenessProperty, opaqueness); - - numberOfColors = PropUtils.intFromProperties(props, prefix + NumColorsProperty, numberOfColors); - - showMaps = PropUtils.booleanFromProperties(props, prefix + ShowMapsProperty, showMaps); - - showInfo = PropUtils.booleanFromProperties(props, prefix + ShowInfoProperty, showInfo); - - scaleImages = PropUtils.booleanFromProperties(props, prefix + ScaleImagesProperty, scaleImages); - - chartSeries = props.getProperty(prefix + ChartSeriesProperty); - - autofetchAttributes = PropUtils.booleanFromProperties(props, prefix - + AutoFetchAttributeProperty, autofetchAttributes); - - imageScaleFactor = PropUtils.floatFromProperties(props, prefix + ImageScaleFactorProperty, imageScaleFactor); - - this.scaleMoreImportantThanCoverage = PropUtils.booleanFromProperties(props, prefix + ScaleOverCoverageProperty, - scaleMoreImportantThanCoverage); - - String colormodel = props.getProperty(prefix + ColormodelProperty); - if (colormodel != null && colormodel.equalsIgnoreCase(COLORMODEL_INDEXED_STRING)) { - colorModel = OMRasterObject.COLORMODEL_INDEXED; - } else { - colorModel = OMRasterObject.COLORMODEL_DIRECT; - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the current values of the layer. If the layer - * has a propertyPrefix set, the property keys should have that prefix plus a separating '.' prepended to each - * property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties into. If props equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - - props.put(prefix + OpaquenessProperty, Integer.toString(opaqueness)); - props.put(prefix + NumColorsProperty, Integer.toString(numberOfColors)); - props.put(prefix + ShowMapsProperty, Boolean.toString(showMaps)); - props.put(prefix + ShowInfoProperty, Boolean.toString(showInfo)); - props.put(prefix + ScaleImagesProperty, Boolean.toString(scaleImages)); - props.put(prefix + ChartSeriesProperty, chartSeries); - props.put(prefix + AutoFetchAttributeProperty, Boolean.toString(autofetchAttributes)); - props.put(prefix + ImageScaleFactorProperty, Float.toString(imageScaleFactor)); - props.put(prefix + ScaleOverCoverageProperty, Boolean.toString(scaleMoreImportantThanCoverage)); - - if (colorModel == OMRasterObject.COLORMODEL_INDEXED) { - props.put(prefix + ColormodelProperty, COLORMODEL_INDEXED_STRING); - } else { - props.put(prefix + ColormodelProperty, COLORMODEL_DIRECT_STRING); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the properties able to be set on this - * PropertyConsumer. The key for each property should be the raw property name (without a prefix) with a value that - * is a String that describes what the property key represents, along with any other information about the property - * that would be helpful (range, default value, etc.). For Layer, this method should at least return the - * 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - String interString; - - interString = i18n.get(RpfLayer.class, OpaquenessProperty, I18n.TOOLTIP, - "Integer representing opaqueness level (0-255, 0 is clear)."); - list.put(OpaquenessProperty, interString); - interString = i18n.get(RpfLayer.class, OpaquenessProperty, "Opaqueness"); - list.put(OpaquenessProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, NumColorsProperty, I18n.TOOLTIP, - "Number of colors to use for the map images."); - list.put(NumColorsProperty, interString); - list.put(NumColorsProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - list.put(NumColorsProperty + OptionPropertyEditor.ScopedOptionsProperty, "sixteen thirtytwo twosixteen"); - list.put(NumColorsProperty + ".sixteen", "16"); - list.put(NumColorsProperty + ".thirtytwo", "32"); - list.put(NumColorsProperty + ".twosixteen", "216"); - interString = i18n.get(RpfLayer.class, NumColorsProperty, "Number of Colors"); - list.put(NumColorsProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ShowMapsProperty, I18n.TOOLTIP, "Flag to display map images."); - list.put(ShowMapsProperty, interString); - list.put(ShowMapsProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, ShowMapsProperty, "Display Images"); - list.put(ShowMapsProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ShowInfoProperty, I18n.TOOLTIP, "Flag to show data attributes."); - list.put(ShowInfoProperty, interString); - list.put(ShowInfoProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, ShowInfoProperty, "Display Attributes"); - list.put(ShowInfoProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ScaleImagesProperty, I18n.TOOLTIP, - "Flag to scale the images to fit the map scale. If false, images appear when map scale fits the chart scale."); - list.put(ScaleImagesProperty, interString); - list.put(ScaleImagesProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, ScaleImagesProperty, "Scale Images"); - list.put(ScaleImagesProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ScaleOverCoverageProperty, I18n.TOOLTIP, - "Flag to consider matching map scale over percent coverage, when choosing which maps to display."); - list.put(ScaleOverCoverageProperty, interString); - list.put(ScaleOverCoverageProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, ScaleOverCoverageProperty, "Scale Images"); - list.put(ScaleOverCoverageProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ChartSeriesProperty, I18n.TOOLTIP, - "The two-letter chart code to display. ANY is default."); - list.put(ChartSeriesProperty, interString); - interString = i18n.get(RpfLayer.class, ChartSeriesProperty, "Chart Series Code"); - list.put(ChartSeriesProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, AutoFetchAttributeProperty, I18n.TOOLTIP, - "Flag to tell the layer to automatically fetch the attribute data for the images."); - list.put(AutoFetchAttributeProperty, interString); - list.put(AutoFetchAttributeProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, AutoFetchAttributeProperty, "Auto-fetch Attributes"); - list.put(AutoFetchAttributeProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ImageScaleFactorProperty, I18n.TOOLTIP, - "Multiplier to limit the scale differential that a given chart will be displayed for a map (4.0 is the default)."); - list.put(ImageScaleFactorProperty, interString); - interString = i18n.get(RpfLayer.class, ImageScaleFactorProperty, "Image Scaling Factor"); - list.put(ImageScaleFactorProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, ColormodelProperty, I18n.TOOLTIP, - "If 'indexed', the images will be built using a colortable. This is not the default."); - list.put(ColormodelProperty, interString); - list - .put(ColormodelProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - list.put(ColormodelProperty + OptionPropertyEditor.ScopedOptionsProperty, "dir ind"); - list.put(ColormodelProperty + ".dir", COLORMODEL_DIRECT_STRING); - list.put(ColormodelProperty + ".ind", COLORMODEL_INDEXED_STRING); - interString = i18n.get(RpfLayer.class, ColormodelProperty, "Image Colormodel Type"); - list.put(ColormodelProperty + LabelEditorProperty, interString); - - return list; - } - - /** - * Specify what order properties should be presented in an editor. - */ - public String getInitPropertiesOrder() { - return " " + ShowMapsProperty + " " + ShowInfoProperty + " " + ScaleImagesProperty + " " - + ImageScaleFactorProperty + " " + OpaquenessProperty + " " + NumColorsProperty - + " " + ChartSeriesProperty + " " + AutoFetchAttributeProperty + " " - + ColormodelProperty; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. The prefix, along with a '.', should be - * prepended to the property keys known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/rpf/package.html b/src/core/src/main/java/com/bbn/openmap/layer/rpf/package.html deleted file mode 100644 index ca36c10cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/rpf/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Provides a layer that displays RPF (Raster Product Format) data. -

-The javadoc for the {@link com.bbn.openmap.layer.rpf.RpfLayer RpfLayer} -has a description of the properties the layer uses. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/BufferedShapeLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/BufferedShapeLayer.java deleted file mode 100644 index 51c966478..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/BufferedShapeLayer.java +++ /dev/null @@ -1,218 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/BufferedShapeLayer.java,v $ -// $RCSfile: BufferedShapeLayer.java,v $ -// $Revision: 1.11 $ -// $Date: 2008/10/16 03:26:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.awt.event.ActionEvent; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.util.Iterator; -import java.util.Properties; -import java.util.logging.Level; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.shape.SpatialIndex.Entry; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; - -/** - * An OpenMap Layer that displays shape files. This loads the data up front and - * then just reprojects/repaints when needed. Note that the ESRIRecords have - * been updated so that the OMGraphics that get created from them are loaded - * with an Integer object that notes the number of the record as it was read - * from the .shp file. This lets you align the object with the correct attribute - * data in the .dbf file. - */ -public class BufferedShapeLayer extends ShapeLayer { - - private static final long serialVersionUID = 1L; - protected OMGraphicList bufferedList = null; - - /** - * Initializes an empty shape layer. - */ - public BufferedShapeLayer() { - super(); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this)); - } - - /** - * Creates a ShapeLayer that reads the give shape file. - * - * @param pathToShpFile - */ - public BufferedShapeLayer(String pathToShpFile) { - super(pathToShpFile); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this)); - } - - /** - * Get the graphics for the entire planet. - */ - protected OMGraphicList getWholePlanet() throws IOException, FormatException { - spatialIndex.readIndexFile(null, coordTransform); - return spatialIndex.getAllOMGraphics((OMGraphicList) null, drawingAttributes, (Projection) null, coordTransform); - } - - /** - * This overridden method checks to see if the buffered OMGraphicList is - * created, and then returns a subset of OMGraphics that are actually on the - * map. If the buffered OMGraphicList hasn't been created yet, it gets - * created here. - */ - public synchronized OMGraphicList prepare() { - - OMGraphicList list = getList(); - - if (list != null) { - list.clear(); - } else { - list = new OMGraphicList(); - } - - if (spatialIndex == null) - return list; - - try { - if (bufferedList == null) { - bufferedList = getWholePlanet(); - } - } catch (FormatException fe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(fe.getMessage()); - } - return list; - } catch (IOException ioe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(ioe.getMessage()); - } - return list; - } - - // grab local - Projection proj = getProjection(); - - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - double ulLat = ul.getY(); - double ulLon = ul.getX(); - double lrLat = lr.getY(); - double lrLon = lr.getX(); - - // check for dateline anomaly on the screen. we check for - // ulLon >= lrLon, but we need to be careful of the check for - // equality because of floating point arguments... - try { - if (ProjMath.isCrossingDateline(ulLon, lrLon, proj.getScale())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": Dateline is on screen"); - } - - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - - checkSpatialIndexEntries(ulLon, ymin, 180.0d, ymax, list, proj); - checkSpatialIndexEntries(-180.0d, ymin, lrLon, ymax, list, proj); - - } else { - - double xmin = Math.min(ulLon, lrLon); - double xmax = Math.max(ulLon, lrLon); - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - checkSpatialIndexEntries(xmin, ymin, xmax, ymax, list, proj); - } - } catch (FormatException fe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(fe.getMessage()); - } - } catch (IOException ioe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(ioe.getMessage()); - } - } - - return list; - } - - protected void checkSpatialIndexEntries(double xmin, double ymin, double xmax, double ymax, - OMGraphicList retList, Projection proj) - throws IOException, FormatException { - // There should be the same number of objects in both iterators. - Iterator entryIt = spatialIndex.entryIterator(); - Iterator omgIt = bufferedList.iterator(); - - OMGraphicList labels = null; - if (spatialIndex.getDbf() != null) { - labels = new OMGraphicList(); - retList.add(labels); - } - - while (entryIt.hasNext() && omgIt.hasNext()) { - Entry entry = (Entry) entryIt.next(); - OMGraphic omg = (OMGraphic) omgIt.next(); - if (entry.intersects(xmin, ymin, xmax, ymax)) { - // We want to set attributes before the evaluate method is - // called, since there might be special attributes set on the - // omg based on dbf contents. - drawingAttributes.setTo(omg); - omg = spatialIndex.evaluate(omg, labels, proj); - - // omg can be null from the evaluate method, if the omg doesn't - // pass proj and rule tests. - if (omg != null) { - omg.generate(proj); - retList.add(omg); - } - } - } - } - - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - if (cmd == RedrawCmd) { - setList(null); - } - super.actionPerformed(e); - } - - /** - * This method gets called from setProperties. - * - * @param realPrefix This prefix has already been scoped, which means it is - * an empty string if setProperties was called with a null prefix, or - * it's a String ending with a period if it was defined with - * characters. - * @param props Properties containing information about files and the layer. - */ - protected void setFileProperties(String realPrefix, Properties props) { - bufferedList = null; - super.setFileProperties(realPrefix, props); - } - - public void setSpatialIndex(SpatialIndex si) { - bufferedList = null; - super.setSpatialIndex(si); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/CSVShapeInfoFile.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/CSVShapeInfoFile.java deleted file mode 100644 index 6c31c6ba0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/CSVShapeInfoFile.java +++ /dev/null @@ -1,92 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/CSVShapeInfoFile.java,v $ -// $RCSfile: CSVShapeInfoFile.java,v $ -// $Revision: 1.4 $ -// $Date: 2007/06/21 21:39:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.net.MalformedURLException; -import java.net.URL; - -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; - -/** - * The CSVShapeInfoFile holds on to the contents of a CSV file, with - * the intent of cross referencing the contents of the file with the - * contents of a shape file. The order that the contents are read - * should correspond to the order that the shapefile contents are - * read. - *

- * NOTE: By default, the numbers that are found in the CSV file are - * converted to Doubles. Use the load(boolean) method to control this, - * especially if you are using the fields later as the key in a - * Hashtable. - */ -public class CSVShapeInfoFile extends CSVFile { - - /** - * Don't do anything special, since all defaults are set already - */ - public CSVShapeInfoFile(String name) throws MalformedURLException { - super(name); - } - - /** - * Don't do anything special, since all defaults are set already - */ - public CSVShapeInfoFile(URL url) throws MalformedURLException { - super(url); - } - - /** - * This function takes an OMGraphicList and loads each one with - * the vector representing the records in the csv file. Each - * graphics stores the graphic in its object slot. - */ - public void loadIntoGraphics(OMGraphicList list) { - if (list != null && infoRecords != null) { - int numgraphics = list.size(); - - for (int i = 0; i < numgraphics; i++) { - try { - OMGraphic omg = list.getOMGraphicAt(i); - Integer recnum = (Integer) (omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - // OFF BY ONE!!! The shape record numbers - // assigned to the records start with 1, while - // everything else we do starts with 0... - Object inforec = getRecord(recnum.intValue() - 1); - omg.putAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE, - inforec); - } catch (ClassCastException cce) { - if (Debug.debugging("shape")) { - cce.printStackTrace(); - } - } catch (NullPointerException npe) { - npe.printStackTrace(); - } - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIBoundingBox.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIBoundingBox.java deleted file mode 100644 index 3c3d2140b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIBoundingBox.java +++ /dev/null @@ -1,175 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIBoundingBox.java,v $ -// $RCSfile: ESRIBoundingBox.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import com.bbn.openmap.util.HashCodeUtil; - -/** - * A bounding box is a rectangle that fully encloses some number of shapes. The - * rectangle is represented as four doubles, xmin ymin, xmax, and ymax. - * - * - *

To Do

- *
    - *
  • Make addPoint take two doubles to avoid unnecessarily consing ESRIPoints - * to add to the box.
  • - *
- * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.3 $ $Date: 2004/10/14 18:06:04 $ - */ -public class ESRIBoundingBox { - - /** The minimum point. */ - public ESRIPoint min; - - /** The maximum point. */ - public ESRIPoint max; - - /** - * Initialize a null bounding box. All coordinates are set to zero. - */ - public ESRIBoundingBox() { - } - - /** - * Initialize a bounding box from a point. The bounding box is initialized - * to encompass the given point. - * - * @param point the point to enclose - */ - public ESRIBoundingBox(ESRIPoint point) { - this(point.x, point.y); - } - - /** - * Initialize a bounding box from two doubles representing a point. The - * bounding box is initialized to encompass the given location. - * - * @param x the x coordinate - * @param y the y coordinate - */ - public ESRIBoundingBox(double x, double y) { - addPoint(x, y); - } - - /** - * Initialize a bounding box to encompass a minimum and maximum point. The - * bounding box is initialized to fully encompass both points. - * - * @param _min a point to enclose - * @param _max another point to enclose - */ - public ESRIBoundingBox(ESRIPoint _min, ESRIPoint _max) { - addPoint(_min); - addPoint(_max); - } - - /** - * Increase the extents of this bounding box to enclose the given bounding - * box. - * - * @param bb a bounding box to be enclosed - */ - public void addBounds(ESRIBoundingBox bb) { - addPoint(bb.min); - addPoint(bb.max); - } - - /** - * Increase the extents of this bounding box to enclose all of the given - * points. - * - * @param points a set of points to enclose - */ - public void addPoints(ESRIPoint[] points) { - for (int j = 0; j < points.length; j++) { - addPoint(points[j]); - } - } - - /** - * Increase the extents of this bounding box to enclose the given point. - * - * @param point a point to enclose - */ - public void addPoint(ESRIPoint point) { - addPoint(point.x, point.y); - } - - /** - * - */ - public void addPoint(double x, double y) { - if (min == null) { - min = new ESRIPoint(x, y); - max = new ESRIPoint(x, y); - } else { - if (min.x > x) - min.x = x; - if (min.y > y) - min.y = y; - if (max.x < x) - max.x = x; - if (max.y < y) - max.y = y; - } - } - - /** - * Determines equality with another bounding box - * - * @param obj a candidate object - * @return true if obj is of type - * ESRIBoundingBox and the extents of - * that bounding box match this box's extents. false - * otherwise. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ESRIBoundingBox bb = (ESRIBoundingBox) obj; - return (min.equals(bb.min) && max.equals(bb.max)); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, min.x); - result = HashCodeUtil.hash(result, min.y); - result = HashCodeUtil.hash(result, max.x); - result = HashCodeUtil.hash(result, max.y); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIMultiPointRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIMultiPointRecord.java deleted file mode 100644 index 76fa23402..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIMultiPointRecord.java +++ /dev/null @@ -1,117 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIMultiPointRecord.java,v $ -// $RCSfile: ESRIMultiPointRecord.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; - -/** - * This is a skeleton of the MultiPoint record type. No methods are - * implemented. - * - *

To Do

- *
    - *
  • Implement the methods of this class.
  • - *
- * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.4 $ $Date: 2005/12/09 21:09:09 $ - */ -public class ESRIMultiPointRecord extends ESRIRecord { - - /** - * Constructor skeleton. - * - * @param b the buffer - * @param off the offset - */ - public ESRIMultiPointRecord(byte b[], int off) {} - - /** - * Generates 2D OMGraphics and adds them to the given list. If you - * are using jdk1.1.X, you'll have to comment out this method, - * because jdk1.1.X doesn't know about the java.awt.Stroke and - * java.awt.Paint interfaces. - * - * @param list the graphics list - * @param drawingAttributes Attributes for rendering. - */ - public void addOMGraphics(OMGraphicList list, - DrawingAttributes drawingAttributes) { - - } - - /** - * Generates OMGeometry and adds it to the list. - * - * @param list the graphics list - */ - public OMGeometry addOMGeometry(OMGeometryList list) { - return null; - } - - /** - * Gets this record's bounding box. - * - * @return a bounding box - */ - public ESRIBoundingBox getBoundingBox() { - return null; - } - - /** - * Gets this record's shape type as an int. Shape types are - * enumerated on the ShapeUtils class. - * - * @return the shape type as an int - */ - public int getShapeType() { - return SHAPE_TYPE_MULTIPOINT; - } - - /** - * Yields the length of this record's data portion. - * - * @return number of bytes equal to the size of this record's data - */ - public int getRecordLength() { - Debug.output("HACK: ESIRMultiPointRecord.getRecordLength: NYI"); - return 0; - } - - /** - * Writes this multipoint record to the given buffer at the given - * offset. - * - * @param b the buffer - * @param off the offset - * @return the number of bytes written - */ - public int write(byte[] b, int off) { - return 0; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoint.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoint.java deleted file mode 100644 index bac4b4fc1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoint.java +++ /dev/null @@ -1,156 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIPoint.java,v $ -// $RCSfile: ESRIPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.text.NumberFormat; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.util.HashCodeUtil; - -/** - * A class representing an x,y coordinate. - * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.3 $ $Date: 2004/10/14 18:06:04 $ - */ -public class ESRIPoint { - - /** A formatting instance for string conversion. */ - static NumberFormat format = NumberFormat.getInstance(); - - /** Static initializer for format */ - static { - format.setMaximumFractionDigits(6); - format.setMinimumFractionDigits(6); - } - - /** The X coordinate. */ - public double x; - - /** The Y coordinate. */ - public double y; - - /** Null constructor. */ - public ESRIPoint() { - } - - /** - * Initializes a point with the given coordinates. - * - * @param _x the x coordinate - * @param _y the y coordinate - */ - public ESRIPoint(double _x, double _y) { - x = _x; - y = _y; - } - - /** - * Returns the X coordinate of this point. - * - * @return the x coordinate - */ - public double getX() { - return x; - } - - /** - * Returns the Y coordinate of this point. - * - * @return the y coordinate - */ - public double getY() { - return y; - } - - /** - * Converts this point to an appropriate string representation. - * - * @return a string representing this point - */ - public String toString() { - return "ESRIPoint[" + format.format(x) + "," + format.format(y) + "]"; - } - - /** - * - */ - // public int binaryStoreSize() { - // return 28; // Constant for Point records - // } - /** - * Constructs a point from the given data buffer. - * - * @param b the data buffer - * @param off the offset into the buffer - */ - public ESRIPoint(byte b[], int off) { - x = ShapeUtils.readLEDouble(b, off); - y = ShapeUtils.readLEDouble(b, off + 8); - } - - /** - * Writes this point to the given buffer at the given offset. - * - * @param b the data buffer - * @param off the offset into the buffer - * @return then number of bytes written - */ - public int write(byte[] b, int off) { - int nBytes = ShapeUtils.writeLEDouble(b, off, x); - nBytes += ShapeUtils.writeLEDouble(b, off + nBytes, y); - return nBytes; - } - - /** - * Determines equality of this instance with any other instance. - * - * @param obj another instance - * @return true if equal, false otherwise - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ESRIPoint pt = (ESRIPoint) obj; - return (x == pt.x && y == pt.y); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, x); - result = HashCodeUtil.hash(result, y); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPointRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPointRecord.java deleted file mode 100644 index 1405fb641..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPointRecord.java +++ /dev/null @@ -1,208 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIPointRecord.java,v $ -// $RCSfile: ESRIPointRecord.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/08/09 21:08:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.io.IOException; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMRaster; - -/** - * An ESRI Point record. - * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.9 $ $Date: 2006/08/09 21:08:41 $ - */ -public class ESRIPointRecord extends ESRIRecord { - - /** The x coordinate. */ - protected double x; - - /** The y coordinate. */ - protected double y; - - /** A BufferedImage to use at the point. */ - protected ImageIcon ii; - - /** - * Initializes this point from the given point. - * - * @param x the x coordinate - * @param y the y coordinate - */ - public ESRIPointRecord(double x, double y) { - this.x = x; - this.y = y; - } - - /** - * Initialize a point record from the given buffer. - * - * @param b the buffer - * @param off the offset into the buffer where the data starts - */ - public ESRIPointRecord(byte b[], int off) throws IOException { - super(b, off); - - int ptr = off + 8; - - int shapeType = readLEInt(b, ptr); - ptr += 4; - if (shapeType != SHAPE_TYPE_POINT) { - throw new IOException("Invalid point record. Expected shape " - + "type " + SHAPE_TYPE_POINT + " but found " + shapeType); - } - - x = readLEDouble(b, ptr); - ptr += 8; - - y = readLEDouble(b, ptr); - ptr += 8; - } - - /** - * Initialize a point record from the given buffer. - * - * @param b the buffer - * @param off the offset into the buffer where the data starts - */ - public ESRIPointRecord(byte b[], int off, ImageIcon imageIcon) - throws IOException { - super(b, off); - - int ptr = off + 8; - - int shapeType = readLEInt(b, ptr); - ptr += 4; - if (shapeType != SHAPE_TYPE_POINT && shapeType != SHAPE_TYPE_NULL) { - throw new IOException("Invalid point record. Expected shape " - + "type " + SHAPE_TYPE_POINT + " but found " + shapeType); - } - - x = readLEDouble(b, ptr); - ptr += 8; - - y = readLEDouble(b, ptr); - ptr += 8; - - ii = imageIcon; - } - - /** - * Gets this record's bounding box. - * - * @return a bounding box - */ - public ESRIBoundingBox getBoundingBox() { - return new ESRIBoundingBox(x, y); - } - - /** - * Yields the length of this record's data portion. Always 20. - * - * @return number of bytes equal to the size of this record's data - */ - public int getRecordLength() { - return 20; - } - - /** - * Writes this point to the given buffer at the given offset. - * - * @param b the buffer - * @param off the offset - * @return the number of bytes written - */ - public int write(byte[] b, int off) { - int nBytes = super.write(b, off); - nBytes += writeLEInt(b, off + nBytes, SHAPE_TYPE_POINT); - nBytes += writeLEDouble(b, off + nBytes, x); - nBytes += writeLEDouble(b, off + nBytes, y); - return nBytes; - } - - /** - * Generates Points and adds them to the given list. - * - * @param list the graphics list - * @param drawingAttributes DrawingAttributes to describe how to - * represent the points, if an ImageIcon is not defined. - */ - public void addOMGraphics(OMGraphicList list, - DrawingAttributes drawingAttributes) { - if (ii == null) { - OMPoint r = new OMPoint((float) y, (float) x); - if (drawingAttributes != null) { - drawingAttributes.setTo(r); - } - list.add(r); - r.putAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE, new Integer(getRecordNumber())); // added - // by - // DGK - } else { - list.add(new OMRaster((float) y, (float) x, -ii.getIconWidth() / 2, -ii.getIconHeight() / 2, ii)); - } - } - - /** - * Generates Points and adds them to the given list. - * - * @param list the graphics list - */ - public OMGeometry addOMGeometry(OMGeometryList list) { - // Don't have a point geometry yet. - return null; - } - - /** - * Gets this record's shape type as an int. Shape types are - * enumerated on the ShapeUtils class. - * - * @return the shape type as an int - */ - public int getShapeType() { - return SHAPE_TYPE_POINT; - } - - /** - * Get the x coordinate for this record. - */ - public double getX() { - return x; - } - - /** - * Get the y coordinate for this record. - */ - public double getY() { - return y; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoly.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoly.java deleted file mode 100644 index 9d5a510da..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPoly.java +++ /dev/null @@ -1,220 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIPoly.java,v $ -// $RCSfile: ESRIPoly.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.Debug; - -/** - * A representation of a shape file polygon, subordinate to an - * ESRIPolygonRecord. This is an abstract class, - * please use one of the fully derived internal classes to do your - * bidding. - * - *

TODO

- *
    - *
  • Write double-floating point representation of an ESRIPoly. - *
  • Make sure to abstract float point vs double float in other - * objects of the ShapeFile reading code. - *
- * - * @author Ray Tomlinson - * @author Tom Mitchell - * @author HACK-author blame it on aculline - * @version $Revision: 1.5 $ $Date: 2009/01/21 01:24:42 $ - */ -public abstract class ESRIPoly extends ShapeUtils { - - /** - * The number of (y,x) pairs of the ESRIPoly. This value should be - * the points.length>>1. - */ - public int nPoints; - - /** - * Poly with data stored in floating point format. This ESRIPoly - * has been optimized for reading data in the OpenMap environment. - * By default, The internal points are stored in y,x,y,x - * (lat,lon,...) order as radian values. There have been - * allowances made to allow internal coordinates to be stored as - * decimal degree values, but this is not the best way to do - * things. The projection libraries are tuned for polygons holding - * radian point coordinates. - */ - public static class ESRIFloatPoly extends ESRIPoly { - - /** - * A vector of vertices, stored as RADIAN y,x,y,x, - * (lat,lon,...). This is to allow for optimized processing by - * OpenMap. - */ - protected double[] radians; - - /** - * Flag noting if the internal representation of coordinates - * is in RADIANS, or DECIMAL_DEGREES. By default, the - * coordinates are in radians. But, a constructor is available - * to let them be noted as DECIMAL_DEGREES. Also, if you ask - * for the coordinates as radians, they get converted to - * radians internally, and this flag gets set accordingly. - * Likewise, if you as for recimal degrees coordinates, the - * coordinates internally will be changed to reflect that. - */ - protected boolean isRadians = true; - - /** - * Construct a poly with the given number of points. Remember - * to `+2' if you want all vertices for a polygon. - * - * @param nPts the number of (y,x) pairs - */ - public ESRIFloatPoly(int nPts) { - if (Debug.debugging("shape") && (nPts > 50000)) { - Debug.output("ESRIPoly w/" + nPts + " points"); - } - nPoints = nPts; - radians = new double[nPoints * 2]; - } - - /** - * Construct an ESRIFloatPoly. Remember to `+2' if you want - * all vertices for a polygon. - * - * @param radians float[] coordinates: y,x,y,x,... (lat,lon) - * order in RADIANS! - */ - public ESRIFloatPoly(double[] radians) { - this.radians = radians; - this.isRadians = true; - nPoints = radians.length / 2; - } - - /** - * Construct an ESRIFloatPoly. Remember to `+2' if you want - * all vertices for a polygon. - * - * @param radians float[] coordinates: y,x,y,x,... (lat,lon) - * order in RADIANS! - */ - public ESRIFloatPoly(double[] radians, boolean isRadians) { - this.radians = radians; - nPoints = radians.length / 2; - this.isRadians = isRadians; - } - - /** - * Get the internal points array. If the internal points are - * not presently stored as radians, they will be permanently - * converted. - * - * @return float[] RADIAN y,x,y,x,... (lat,lon) - */ - public double[] getRadians() { - if (!isRadians) { - ProjMath.arrayDegToRad(radians); - isRadians = true; - } - return radians; - } - - /** - * Get the internal points array. If the internal points are - * not presently stored as decimal degree values, the will be - * permanently. - * - * @return float[] DECIMAL_DEGREES y,x,y,x,... (lat,lon) - */ - public double[] getDecimalDegrees() { - if (isRadians) { - ProjMath.arrayRadToDeg(radians); - isRadians = false; - } - return radians; - } - - /** - * Reads a polygon from the given buffer starting at the given - * offset. - * - * @param b the buffer - * @param off the offset - * @param connect connect the points (polygon) - * @return the number of bytes read - */ - public int read(byte b[], int off, boolean connect) { - int i, ptr = off; - int end = (connect) ? radians.length - 2 : radians.length; - for (i = 0; i < end; i += 2) { - // REMEMBER: y,x order (lat,lon order) - radians[i + 1] = ProjMath.degToRad((float) readLEDouble(b, ptr));//x - // (lon) - ptr += 8; - - radians[i] = ProjMath.degToRad((float) readLEDouble(b, ptr));//y - // (lat) - ptr += 8; - } - // cap the points if polygon, assuming enough space in - // array... - if (connect) { - radians[i] = radians[0]; - radians[i + 1] = radians[1]; - } - return ptr - off; - } - - /** - * Returns the x coordinate of the indicated vertex. - * - * @param index the ordinal of the vertex of interest - * @return the x (longitude) coordinate in decimal degrees - */ - public double getX(int index) { - // REMEMBER: y,x order (lat,lon order) - return ProjMath.radToDeg(radians[(index * 2) + 1]);//x - // (lon) - } - - /** - * Returns the y coordinate of the indicated vertex. - * - * @param index the ordinal of the vertex of interest - * @return the y (latitude) coordinate in decimal degrees - */ - public double getY(int index) { - // REMEMBER: y,x order (lat,lon order) - return ProjMath.radToDeg(radians[(index * 2)]);//y (lat) - } - } - - /** - * Reads a polygon from the given buffer starting at the given - * offset. - * - * @param b the buffer - * @param off the offset - * @return the number of bytes read - */ - public abstract int read(byte b[], int off, boolean connect); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPolygonRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPolygonRecord.java deleted file mode 100644 index 3c096d3cb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIPolygonRecord.java +++ /dev/null @@ -1,355 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIPolygonRecord.java,v $ -// $RCSfile: ESRIPolygonRecord.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.geom.PolygonGeometry; -import com.bbn.openmap.omGraphics.geom.PolylineGeometry; -import com.bbn.openmap.proj.ProjMath; - -/** - * The Polygon record type. This class implements the ESRI Shapefile polygon AND - * arc/polyline record types. - * - * @author Ray Tomlinson - * @author Tom Mitchell - * @author HACK-author blame it on aculline - * @version $Revision: 1.8 $ $Date: 2009/01/21 01:24:42 $ - */ -public class ESRIPolygonRecord extends ESRIRecord { - - /** Polygon or arc/polyline?. */ - protected int shapeType = SHAPE_TYPE_POLYGON; - - /** The bounding box. */ - public ESRIBoundingBox bounds; - - /** An array of polygons. */ - public ESRIPoly[] polygons; - - public ESRIPolygonRecord() { - bounds = new ESRIBoundingBox(); - polygons = new ESRIPoly[0]; - } - - /** - * Initialize a polygon record from the given buffer. - * - * @param b - * the buffer - * @param off - * the offset into the buffer where the data starts - */ - public ESRIPolygonRecord(byte b[], int off) throws IOException { - super(b, off); - - int ptr = off + 8; - - shapeType = readLEInt(b, ptr); - ptr += 4; - if ((shapeType != SHAPE_TYPE_POLYGON) && (shapeType != SHAPE_TYPE_ARC)) { - throw new IOException("Invalid polygon record. Expected shape " - + "type " + SHAPE_TYPE_POLYGON + " or type " - + SHAPE_TYPE_ARC + ", but found " + shapeType); - } - boolean ispolyg = isPolygon(); - - bounds = readBox(b, ptr); - ptr += 32; // A box is 4 doubles (4 x 8bytes) - - int numParts = readLEInt(b, ptr); - ptr += 4; - - int numPoints = readLEInt(b, ptr); - ptr += 4; - - if (numParts <= 0) { - polygons = new ESRIPoly[0]; - return; - } - - polygons = new ESRIPoly[numParts]; - int origin = 0; - int _len; - for (int i = 0; i < numParts; i++) { - - int nextOrigin = readLEInt(b, ptr); - ptr += 4; - - if (i > 0) { - _len = nextOrigin - origin; - if (ispolyg) - ++_len;// connect pairs - polygons[i - 1] = new ESRIPoly.ESRIFloatPoly(_len); - } - origin = nextOrigin; - } - _len = numPoints - origin; - if (ispolyg) - ++_len;// connect pairs - polygons[numParts - 1] = new ESRIPoly.ESRIFloatPoly(_len); - for (int i = 0; i < numParts; i++) { - ptr += polygons[i].read(b, ptr, ispolyg); - } - } - - /** - * Is this a polygon or a arc/polyline? - * - * @return boolean - */ - public boolean isPolygon() { - return shapeType == SHAPE_TYPE_POLYGON; - } - - /** - * Set the poly type (polygon or arc/polyline). - */ - public void setPolygon(boolean isPolygon) { - shapeType = isPolygon ? SHAPE_TYPE_POLYGON : SHAPE_TYPE_ARC; - } - - /** - * Add a poly to the record. - * - * @param radians - * coordinates: y,x,y,x,... (lat,lon) order in RADIANS! - */ - public void add(double radians[]) { - ESRIPoly newPoly = new ESRIPoly.ESRIFloatPoly(radians); - - int numParts = polygons.length; - ESRIPoly oldPolys[] = polygons; - polygons = new ESRIPoly[numParts + 1]; - System.arraycopy(oldPolys, 0, polygons, 0, numParts); - polygons[numParts] = newPoly; - - int len = radians.length; - for (int i = 0; i < len; i += 2) { - // REMEMBER: switch to x,y order - bounds.addPoint(ProjMath.radToDeg(radians[i + 1]),// x - // (lon) - ProjMath.radToDeg(radians[i]));// y (lat) - } - } - - /** - * Generates 2D OMGraphics and adds them to the given list. If you are using - * jdk1.1.X, you'll have to comment out this method, because jdk1.1.X - * doesn't know about the java.awt.Stroke and java.awt.Paint interfaces. - * - * @param list - * the graphics list - * @param drawingAttributes - * the drawingAttributes to paint the poly. - */ - public void addOMGraphics(OMGraphicList list, - DrawingAttributes drawingAttributes) { - - int nPolys = polygons.length; - if (nPolys <= 0) - return; - OMPoly p = null; - double[] pts; - boolean ispolyg = isPolygon(); - /* - * modifications in the next 4 lines marked with as: allow to treat - * ESRIPolygonRecord with holes correctly (ESRIPolys with - * counterclockwise order of vertices) - */ - OMList sublist = null; - - if (nPolys > 1) { - // Only want the OMAreaList if the shape type is for - // polygons - if (false && ispolyg) { - // There's a problem here with OMPolys that wrap - // around the earth, putting them in OMAreaLists makes - // them draw lines through the map. Need to sort that - // out before enabling this code by removing 'false' - // in if statement. - sublist = new OMAreaList(); - ((OMAreaList) sublist).setConnectParts(false); - } else { - sublist = new OMGraphicList(); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(sublist); - } - - sublist.setVague(true); // Treat list as one object. - list.add(sublist); - sublist.putAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE, new Integer(getRecordNumber())); - } - - for (int i = 0; i < nPolys; i++) { - // these points are already in RADIAN lat,lon order!... - pts = ((ESRIPoly.ESRIFloatPoly) polygons[i]).getRadians(); - p = new OMPoly(pts, OMGraphic.RADIANS, OMGraphic.LINETYPE_STRAIGHT); - - if (drawingAttributes != null) { - drawingAttributes.setTo(p); - } - if (!ispolyg) { - p.setIsPolygon(false); - } - - if (sublist != null) { - sublist.add(p); - } else { - // There should be only one. - p.putAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE, new Integer(getRecordNumber())); - list.add(p); - } - } - } - - /** - * Generates OMGeometry and adds them to the given list. - * - * @param list - * the geometry list - */ - public OMGeometry addOMGeometry(OMGeometryList list) { - - int nPolys = polygons.length; - if (nPolys <= 0) { - return null; - } - - double[] pts; - boolean ispolyg = isPolygon(); - OMGeometry geom = null; - - for (int i = 0; i < nPolys; i++) { - // these points are already in RADIAN lat,lon order!... - pts = ((ESRIPoly.ESRIFloatPoly) polygons[i]).getRadians(); - if (ispolyg) { - geom = new PolygonGeometry.LL(pts, OMGraphic.RADIANS, - OMGraphic.LINETYPE_STRAIGHT); - } else { - geom = new PolylineGeometry.LL(pts, OMGraphic.RADIANS, - OMGraphic.LINETYPE_STRAIGHT); - } - list.add(geom); - } - return geom; - } - - /** - * Gets this record's bounding box. - * - * @return a bounding box - */ - public ESRIBoundingBox getBoundingBox() { - return bounds; - } - - /** - * Gets this record's shape type as an int. Shape types are enumerated on - * the ShapeUtils class. - * - * @return the shape type as an int (either SHAPE_TYPE_POLYGON or - * SHAPE_TYPE_ARC) - */ - public int getShapeType() { - return shapeType; - } - - /** - * Yields the length of this record's data portion. - *

- * (44 + (numParts * 4) + (numPoints * 16))
- * 3 Integers + 4 doubles == 3 * 4bytes + 4 * 8bytes == 12 + 32 == 44. - * - * @return number of bytes equal to the size of this record's data - */ - public int getRecordLength() { - int numParts = polygons.length; - int numPoints = 0; - for (int i = 0; i < numParts; i++) { - numPoints += polygons[i].nPoints; - } - return (44 + (numParts * 4) + (numPoints * 16)); - } - - /** - * Writes this polygon to the given buffer at the given offset. - * - * @param b - * the buffer - * @param off - * the offset - * @return the number of bytes written - */ - public int write(byte[] b, int off) { - int nBytes = super.write(b, off); - nBytes += writeLEInt(b, off + nBytes, shapeType); - // bounds - nBytes += writeBox(b, off + nBytes, bounds); - // numparts - int numParts = polygons.length; - nBytes += writeLEInt(b, off + nBytes, numParts); - // numpoints - int numPoints = 0; - for (int i = 0; i < numParts; i++) { - numPoints += polygons[i].nPoints; - } - nBytes += writeLEInt(b, off + nBytes, numPoints); - // parts - int ptr = 0; - for (int i = 0; i < numParts; i++) { - nBytes += writeLEInt(b, off + nBytes, ptr); - ptr += polygons[i].nPoints; - } - - // points - for (int i = 0; i < numParts; i++) { - // REMEMBER: stored internally as y,x order (lat,lon - // order) - double[] pts = ((ESRIPoly.ESRIFloatPoly) polygons[i]).getRadians(); - int nPts = pts.length; - for (int j = 0; j < nPts; j += 2) { - nBytes += writeLEDouble(b, off + nBytes, (double) ProjMath - .radToDeg(pts[j + 1]));// x - // (lon) - nBytes += writeLEDouble(b, off + nBytes, (double) ProjMath - .radToDeg(pts[j]));// y (lat) - } - } - - // return number of bytes written - return nBytes; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIRecord.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIRecord.java deleted file mode 100644 index 86e231c82..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ESRIRecord.java +++ /dev/null @@ -1,161 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ESRIRecord.java,v $ -// $RCSfile: ESRIRecord.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * This is the base class for all shape record classes. It stores the - * record number and content length of a record, also known as the - * record header. - * - * @author Ray Tomlinson - * @author Tom Mitchell - * @version $Revision: 1.4 $ $Date: 2005/12/09 21:09:10 $ - */ -public abstract class ESRIRecord extends ShapeUtils { - - /** The ordinal of this record. */ - public int recordNumber; - - /** The length of the data portion of this record. */ - public int contentLength; - - /** - * Initialize an empty record. Used when constructing a record to - * be written to a shape file. - */ - public ESRIRecord() { - recordNumber = 0; - contentLength = 0; - } - - /** - * Initialize a record from a buffer. Reads the record header - * fields from the given buffer at the given offset. - * - * @param b the buffer - * @param off the offset - */ - public ESRIRecord(byte b[], int off) { - recordNumber = readBEInt(b, off); - contentLength = readBEInt(b, off + 4); - } - - /** - * Generates 2D OMGraphics and adds them to the given list. If you - * are using jdk1.1.X, you'll have to comment out this method, - * because jdk1.1.X doesn't know about the java.awt.Stroke and - * java.awt.Paint interfaces. - * - * @param list the graphics list - * @param drawingAttributes Attributes that describe how to render - * the graphics. - */ - public abstract void addOMGraphics(OMGraphicList list, - DrawingAttributes drawingAttributes); - - /** - * Generates OMGeometry and adds them to the given list. The list - * takes care of DrawingAttributes. - * - * @param list the geometry list - */ - public abstract OMGeometry addOMGeometry(OMGeometryList list); - - /** - * Gets this record's bounding box. - * - * @return a bounding box - */ - public abstract ESRIBoundingBox getBoundingBox(); - - /** - * Gets this record's shape type as an int. Shape types are - * enumerated on the ShapeUtils class. - * - * @return the shape type as an int - */ - public abstract int getShapeType(); - - /** - * Yields the length of this record's data portion. - * - * @return number of bytes equal to the size of this record's data - */ - public abstract int getRecordLength(); - - /** - * Returns the number of bytes needed to store the record header - * and record data. - * - * @return number of bytes equal to the size of this record - */ - public int getBinaryStoreSize() { - return getRecordLength() + 8; // Constant for record headers - } - - /** - * Writes this record to the given buffer at the given offset. - * - * @param b the buffer - * @param off the offset - * @return the number of bytes written - */ - public int write(byte[] b, int off) { - int nBytes = writeBEInt(b, off, recordNumber); - nBytes += writeBEInt(b, off + nBytes, (getRecordLength() / 2)); - return nBytes; - } - - // public ESRIArcRecord getArcShape() { - // if (getShapeType() == SHAPE_TYPE_ARC) { - // return (ESRIArcRecord) this; - // } else { - // return null; - // } - // } - - /** - * Accessor for record number field. - * - * @return the ordinal of this record in the file - */ - public int getRecordNumber() { - return recordNumber; - } - - /** - * Accessor for the content length of this record. That's the size - * of this record in 16 bit words. - * - * @return the number of 16 bit words that this record takes up - */ - public int getContentLength() { - return contentLength; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/EsriLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/EsriLayer.java deleted file mode 100644 index 9ad5b7e66..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/EsriLayer.java +++ /dev/null @@ -1,834 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/plugin/esri/EsriPlugIn.java,v $ -// $RCSfile: EsriPlugIn.java,v $ -// $Revision: 1.17 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.shape; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.DrawingAttributesUtility; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.dataAccess.shape.EsriPointList; -import com.bbn.openmap.dataAccess.shape.EsriPolygonList; -import com.bbn.openmap.dataAccess.shape.EsriPolylineList; -import com.bbn.openmap.dataAccess.shape.EsriShapeExport; -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Properties; -import javax.swing.DefaultListSelectionModel; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -/** - * EsriPlugIn loads Esri shape file sets from web servers or local file systems, and it enables the creation of shape - * file sets. It needs to be inserted into a PlugInLayer to use within OpenMap. - *

- * To create a file from a remote location: - *


- *
- * URL shp = new URL("http://www.webserver.com/file.shp");
- * URL dbf = new URL("http://www.webserver.com/file.dbf");
- * URL shx = new URL("http://www.webserver.com/file.shx");
- * EsriPlugIn epi = new EsriPlugIn("name", dbf, shp, shx);
- * PlugInLayer pil = new PlugInLayer();
- * pil.setPlugIn(epi);
- *
- * 
- * - * To open a shape file set from the local file system: - *

- *
- * File dbf = new File("c:/data/file.dbf");
- * File shp = new File("c:/data/file.shp");
- * File shx = new File("c:/data/file.shx");
- * EsriPlugIn epi = new EsriPlugIn("name", dbf.toURI().toURL(), shp.toURI().toURL(), shx.toURI().toURL());
- * PlugInLayer pil = new PlugInLayer();
- * pil.setPlugIn(epi);
- * 
- * 
- * - * To create a zero content shape file set from which the user can add shapes at runtime: - *

- * EsriPlugIn epi = new EsriPlugIn("name", EsriLayer.TYPE_POLYLINE);
- * 
- * - * To add features to an EsriLayer: - *

- *
- * OMGraphicList shapeData = new OMGraphicList();
- * ArrayList tabularData = new ArrayList();
- * float[] part0 = new float[] { 35.0f, -120.0f, -25.0f, -95.0f, 56.0f, -30.0f };
- * float[] part1 = new float[] { -15.0f, -110.0f, 13.0f, -80.0f, -25.0f, 10.0f };
- * OMPoly poly0 = new OMPoly(part0, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB);
- * OMPoly poly1 = new OMPoly(part1, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB);
- * shapeData.add(poly0); //part 1
- * shapeData.add(poly1); //part 2
- * shapeData.generate(_mapBean.getProjection());
- * tabularData.add(0, "a value");
- * plugin.addRecord(shapeData, tabularData);
- * plugin.repaint(); // assumes that plugin added to PlugInLayer
- *
- * 
- * 
- * - * To configure an EsriLayer through a properties file, specify file references in terms of URLs, full or relative file - * paths. - * - * To reference a file on Windows 2000: - *

- *
- *       esri.class = com.bbn.openmap.plugin.esri.EsriPlugIn
- *       esri.prettyName = Esri Example
- *       esri.shp = file:///c:/data/shapefile.shp
- *     # -or-
- *       esri.shp = c:/data/shapefile.shp
- *
- *       esri.dbf = file:///c:/data/shapefile.dbf
- *       esri.shx = file:///c:/data/shapefile.shx
- *
- *
- * 
- * - * To reference a file on RedHat Linux 6.2: - * - *

- *
- *       esri.class = com.bbn.openmap.plugin.esri.EsriPlugIn
- *       esri.prettyName = Esri Example
- *       esri.shp = file:///home/dvanauke/resources/shapefile.shp
- *     # - or -
- *       esri.shp = /home/dvanauke/resources/shapefile.shp
- *
- *       esri.dbf = file:///home/dvanauke/resources/shapefile.dbf
- *       esri.shx = file:///home/dvanauke/resources/shapefile.shx
- *
- *
- * 
- * - * To reference a file on a web server: - * - *

- *
- *       esri.class = com.bbn.openmap.plugin.esri.EsriPlugIn
- *       esri.prettyName = Esri Example
- *       esri.shp = http://www.webserver.com/shapefile.shp
- *       esri.dbf = http://www.webserver.com/shapefile.dbf
- *       esri.shx = http://www.webserver.com/shapefile.shx
- *
- *
- * 
- * - * The PlugIn has been updated to use the properties from the DrawingAttributes object in order to specify how it's - * objects should be rendered: - *

- *
- *       esri.class = com.bbn.openmap.plugin.esri.EsriPlugIn
- *       esri.prettyName = Esri Example
- *       esri.lineColor = AARRGGBB (hex ARGB color)
- *       esri.fillColor = AARRGGBB (hex ARGB color)
- *       esri.selectColor = AARRGGBB (hex ARGB color)
- *       esri.lineWidth = AARRGGBB (hex ARGB color)
- *
- * 
- * - * See DrawingAttributes for more options. Also, as of OpenMap 4.5.4, you don't have to specify the location of the .dbf - * and .shx files. If you don't, the plugin assumes that those files are next to the .shp file. - * - * @author Doug Van Auken - * @author Don Dietrick - * @author Lonnie Goad from OptiMetrics provided selection bug solution and GUI interaction. - */ -public class EsriLayer - extends OMGraphicHandlerLayer - implements ShapeConstants, DataBoundsProvider { - - private static final long serialVersionUID = 1L; - private EsriGraphicList _list = null; - private DbfTableModel _model = null; - private int _type = -1; - - private String dbf; - private String shx; - private String shp; - - /** - * A simple list mechanism that will let selected OMGraphics to be drawn on top of all the others. Using this list - * instead of changing the order of the esri graphic list maintains the order of that list. We clear out this and - * add to it as necessary. - */ - protected OMGraphicList selectedGraphics = new OMGraphicList(); - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Creates an EsriPlugIn that will be configured through the setProperties() method - */ - public EsriLayer() { - Debug.message("esri", "EsriPlugIn: default constructor"); - setMouseModeIDsForEvents(new String[]{ - SelectMouseMode.modeID - }); - } - - /** - * Creates an empty EsriPlugIn, usable for adding features at run-time. - * - * @param name The name of the layer - * @param type The type of layer - * @param columnCount The number of columns in the dbf model - */ - public EsriLayer(String name, int type, int columnCount) - throws Exception { - - switch (type) { - case SHAPE_TYPE_POINT: - _list = new EsriPointList(); - break; - case SHAPE_TYPE_POLYGON: - _list = new EsriPolygonList(); - break; - case SHAPE_TYPE_POLYLINE: - _list = new EsriPolylineList(); - break; - default: - _list = null; - } - - _model = new DbfTableModel(columnCount); - setName(name); - } - - /** - * Creates an EsriPlugIn from a set of shape files - * - * @param name The name of the layer that may be used to reference the layer - * @param dbf The url referencing the dbf extension file - * @param shp The url referencing the shp extension file - * @param shx The url referencing the shx extension file - */ - public EsriLayer(String name, URL dbf, URL shp, URL shx) { - - this.dbf = dbf.toString(); - this.shp = shp.toString(); - this.shx = shx.toString(); - - _list = getGeometry(shp); - _model = getDbfTableModel(dbf); - _list.putAttribute(DBF_ATTRIBUTE, _model); - setName(name); - } - - /** - * Set the drawing attributes for the graphics on the list. - */ - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - - if (_list != null) { - drawingAttributes.setTo(_list); - } - } - - /** - * Get the drawing attributes for the graphics on the list. - */ - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - /** - * Handles adding records to the geometry list and the DbfTableModel. - * - * @param graphic An OMGraphic to add the graphics list - * @param record A record to add to the DbfTableModel - */ - public void addRecord(OMGraphic graphic, ArrayList record) { - OMGraphicList list = getEsriGraphicList(); - - // Associate the record directly in the OMGraphic - graphic.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, record); - - // If list == null, model will be too. - if (list != null) { - // Might as well set the index - graphic.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(list.size())); - list.add(graphic); - _model.addRecord(record); - } else { - Debug.error("EsriPlugIn.addRecord(): invalid data files!"); - } - } - - /** - * Creates a DbfTableModel for a given .dbf file - * - * @param dbf The url of the file to retrieve. - * @return The DbfTableModel for this layer, null if something went badly. - */ - private DbfTableModel getDbfTableModel(URL dbf) { - return DbfTableModel.getDbfTableModel(dbf); - } - - /** - * Returns the EsriGraphicList for this layer - * - * @return The EsriGraphicList for this layer - */ - public EsriGraphicList getEsriGraphicList() { - if (_list == null) { - try { - // _model = getDbfTableModel(new URL(dbf)); - // _list = getGeometry(new URL(shp), new URL(shx)); - - // Changed so that shp, dbf and shx can be named as - // resource, a file path, or a URL. Also, if the dbf - // and shx file are not provided, look for them next - // to the shape file. - DFD - if ((shx == null || shx.length() == 0) && shp != null) { - shx = shp.substring(0, shp.lastIndexOf('.') + 1) + PARAM_SHX; - } - - if ((dbf == null || dbf.length() == 0) && shp != null) { - dbf = shp.substring(0, shp.lastIndexOf('.') + 1) + PARAM_DBF; - } - - _model = getDbfTableModel(PropUtils.getResourceOrFileOrURL(dbf)); - _list = getGeometry(PropUtils.getResourceOrFileOrURL(shp)); - - if (_model != null) { - DrawingAttributesUtility.setDrawingAttributes(_list, _model, getDrawingAttributes()); - } - } catch (MalformedURLException murle) { - Debug.error("EsriPlugIn|" + getName() + " Malformed URL Exception\n" - + murle.getMessage()); - } catch (Exception exception) { - Debug.error("EsriPlugIn|" + getName() + " Exception\n" + exception.getMessage()); - exception.printStackTrace(); - } - } - - return _list; - } - - public static void main(String[] argv) { - if (argv.length == 0) { - System.out.println("Give EsriPlugIn a path to a shape file, and it'll print out the graphics."); - System.exit(0); - } - - Debug.init(); - - EsriLayer epi = new EsriLayer(); - Properties props = new Properties(); - props.put(PARAM_SHP, argv[0]); - epi.setProperties(props); - - OMGraphicList list = epi.getEsriGraphicList(); - - if (list != null) { - Debug.output(list.getDescription()); - - } - - String dbfFileName = argv[0].substring(0, argv[0].lastIndexOf('.') + 1) + "dbf"; - - try { - DbfTableModel dbf = epi.getDbfTableModel(PropUtils.getResourceOrFileOrURL(epi, dbfFileName)); - if (list != null) { - list.putAttribute(DBF_ATTRIBUTE, dbf); - } - Debug.output("Set list in table"); - dbf.showGUI(dbfFileName, 0); - } catch (Exception e) { - Debug.error("Can't read .dbf file for .shp file: " + dbfFileName + "\n" - + e.getMessage()); - System.exit(0); - } - - EsriShapeExport ese = new EsriShapeExport(list, null, "./ese"); - Debug.output("Exporting..."); - ese.export(); - Debug.output("Done."); - } - - /** - * Standard OMGraphicHandlerLayer prepare called when the projection changes. - * - * @return OMGraphicList that should be painted on the map. - */ - public OMGraphicList prepare() { - OMGraphicList list = getEsriGraphicList(); - - if (list != null) { - list.generate(getProjection()); - - // Setting the list up so that if anything is "selected", - // it will also be drawn on top of all the other - // OMGraphics. This maintains order while also making any - // line edge changes more prominent. - OMGraphicList parent = new OMGraphicList(); - parent.add(selectedGraphics); - parent.add(list); - list = parent; - } - - return list; - } - - /** - * Reads the contents of the SHP file. - * - * @param shp The url of the SHP file - * @return A new EsriGraphicList, null if something went badly. - */ - public EsriGraphicList getGeometry(URL shp) { - GeoCoordTransformation coordTransform = getCoordTransform(); - - return EsriGraphicList.getEsriGraphicList(shp, getDrawingAttributes(), getModel(), coordTransform); - } - - /** - * Returns the associated table model for this layer - * - * @return The associated table model for this layer - */ - public DbfTableModel getModel() { - return _model; - } - - /** - * Returns whether this layer is of type 0 (point), 3 (polyline), or 5(polygon) - * - * @return An int representing the type of layer, as specified in Esri's shape file format specification - */ - public int getType() { - return _type; - } - - /** - * Filters the DbfTableModel given a SQL like string - * - * @param query A SQL like string to filter the DbfTableModel - */ - public void query(String query) { - // to be implemented - } - - /** - * Sets the DbfTableModel - * - * @param model The DbfModel to set for this layer - */ - public void setModel(DbfTableModel model) { - if (model != null) { - _model = model; - _list.putAttribute(DBF_ATTRIBUTE, model); - } - } - - /** - * Sets the properties for the Layer. - * - * @param prefix the token to prefix the property names - * @param properties the Properties object - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - drawingAttributes.setProperties(prefix, properties); - - // This fixes a hole that was exposed when the PlugIn had the - // files set directly, and then had properties set for drawing - // attributes later. - if (_list != null) { - if (_model != null) { - DrawingAttributesUtility.setDrawingAttributes(_list, _model, drawingAttributes); - } else { - drawingAttributes.setTo(_list); - } - } - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - shp = properties.getProperty(prefix + PARAM_SHP); - shx = properties.getProperty(prefix + PARAM_SHX); - dbf = properties.getProperty(prefix + PARAM_DBF); - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + PARAM_SHP, PropUtils.unnull(shp)); - props.put(prefix + PARAM_SHX, PropUtils.unnull(shx)); - props.put(prefix + PARAM_DBF, PropUtils.unnull(dbf)); - - // Need to make sure they line up. - drawingAttributes.setPropertyPrefix(getPropertyPrefix()); - drawingAttributes.getProperties(props); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - props.put(initPropertiesProperty, PARAM_SHP + " " + PARAM_DBF + " " + PARAM_SHX - + drawingAttributes.getInitPropertiesOrder() + " " + Layer.AddToBeanContextProperty); - - props.put(PARAM_SHP, "Location of a shape (.shp) file (path or URL)"); - props.put(PARAM_SHX, "Location of a index file (.shx) for the shape file (path or URL, optional)"); - props.put(PARAM_DBF, "Location of a database file (.dbf) for the shape file (path or URL, optional)"); - props.put(PARAM_SHP + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FDUPropertyEditor"); - props.put(PARAM_DBF + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FDUPropertyEditor"); - props.put(PARAM_SHX + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FDUPropertyEditor"); - - drawingAttributes.getPropertyInfo(props); - - return props; - } - - public Component getGUI() { - - JPanel holder = new JPanel(new BorderLayout()); - - holder.add(drawingAttributes.getGUI(), BorderLayout.CENTER); - - JPanel btnPanel = new JPanel(new GridLayout(3, 1)); - - JButton redrawSelected = new JButton("Set Colors for Selected"); - btnPanel.add(redrawSelected); - - JButton redrawAll = new JButton("Set Colors For All"); - btnPanel.add(redrawAll); - - JButton tableTrigger = new JButton("Show Data Table"); - btnPanel.add(tableTrigger); - - holder.add(btnPanel, BorderLayout.SOUTH); - - redrawSelected.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (!(graphicIndex < 0)) { - OMGraphic omg = getEsriGraphicList().getOMGraphicAt(graphicIndex); - repaintGraphics(omg); - } - } - }); - - redrawAll.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - repaintGraphics(getEsriGraphicList()); - } - }); - - tableTrigger.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - showTable(); - } - }); - return holder; - } - - /** - * Sets the drawing attributes to those of a particular OMGraphic. - */ - public void setDrawingAttributes(OMGraphic omg) { - if (drawingAttributes != null && omg != null) { - drawingAttributes.setFrom(omg); - } - } - - /** - * Repaints the currently selected OMGraphic or the OMGraphicList to the current DrawingAttributes - * - * @param omg the OMGraphic to repaint - */ - private void repaintGraphics(OMGraphic omg) { - drawingAttributes.setTo(omg); - doPrepare(); - } - - protected JTable table = null; - protected ListSelectionModel lsm = null; - - /** - * Needs to be called before displaying the DbfTableModel. - */ - public JTable getTable() { - - if (table == null) { - lsm = new DefaultListSelectionModel(); - table = new JTable(); - table.setModel(getModel()); - table.setSelectionModel(lsm); - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - - lsm.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - // Ignore extra messages. - if (e.getValueIsAdjusting()) { - return; - } - ListSelectionModel lsm2 = (ListSelectionModel) e.getSource(); - if (lsm2.isSelectionEmpty()) { - // no rows are selected - } else { - int index = lsm2.getMinSelectionIndex(); - selectGraphic(index); - repaint(); - } - } - }); - } - - return table; - } - - /** - * Mark a graphic as selected on the map. - * - * @param index the index, from 0, of the graphic on the list. - */ - public void selectGraphic(int index) { - EsriGraphicList list = getEsriGraphicList(); - list.deselect(); - // Clear out the selected graphics list - selectedGraphics.clear(); - selectGraphic(list.getOMGraphicAt(index)); - graphicIndex = index; - list.regenerate(getProjection()); - } - - /** - * Mark the graphic as selected, and generate if necessary. - */ - public void selectGraphic(OMGraphic graphic) { - if (graphic != null) { - graphic.select(); - graphic.regenerate(getProjection()); - // Set the selected OMGraphic on the selected list. - selectedGraphics.add(graphic); - } - } - - /** - * Given a graphic, highlight its entry in the table. - */ - public void selectEntry(OMGraphic graphic) { - if (lsm == null) { - getTable(); - } - - lsm.setSelectionInterval(graphicIndex, graphicIndex); - // scroll to the appropriate row in the table - getTable().scrollRectToVisible(getTable().getCellRect(graphicIndex, 0, true)); - } - - /** - * Show the table in its own frame. - */ - public void showTable() { - if (tableFrame == null) { - String tableTitle = PropUtils.unnull(getName()); - tableFrame = new JFrame(tableTitle + " Shape Data Attributes"); - - JScrollPane pane = new JScrollPane(getTable(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - - tableFrame.getContentPane().add(pane, BorderLayout.CENTER); - - tableFrame.setSize(400, 300); - } - - tableFrame.setVisible(true); - tableFrame.toFront(); - } - - // Instead of mouseClick(), replace with these three methods. - public boolean isSelectable(OMGraphic omg) { - return true; - } - - public void select(OMGraphicList omgl) { - EsriGraphicList list = getEsriGraphicList(); - graphicIndex = -1; - - OMGraphic omg = omgl.get(0); - if (omg != null) { - graphicIndex = list.indexOf(omg); - selectEntry(omg); - } - } - - public void deselect(OMGraphic omg) { - EsriGraphicList list = getEsriGraphicList(); - graphicIndex = -1; - - if (lsm == null) { - getTable(); - } - lsm.clearSelection(); - list.deselect(); - selectedGraphics.clear(); - repaint(); - } - - /** - * Handle a mouse click on the map. - */ - /* - public boolean mouseClicked(MouseEvent e) { - EsriGraphicList list = getEsriGraphicList(); - boolean ret = false; - graphicIndex = -1; - - if (list != null) { - OMGraphic omg = list.selectClosest(e.getX(), e.getY(), 4); - if (omg != null) { - // graphicIndex has to be set before selectEntry - // called. - graphicIndex = list.indexOf(omg); - selectEntry(omg); - - ret = true; - } else { - if (lsm == null) { - getTable(); - } - lsm.clearSelection(); - list.deselect(); - selectedGraphics.clear(); - repaint(); - } - } - return ret; - } - */ - // To handle tooltips on mouseMoved, use getToolTipTextFor(OMGraphic) - public String getToolTipTextFor(OMGraphic omg) { - EsriGraphicList list = getEsriGraphicList(); - Integer I = ((Integer) omg.getAttribute(SHAPE_INDEX_ATTRIBUTE)); - if (I != null) { - return getDescription(I.intValue()); - } else { - return getDescription(list.indexOf(omg)); - } - } - - /** - * Handle mouse moved events (Used for firing tool tip descriptions over graphics) - */ - /* - public boolean mouseMoved(MouseEvent e) { - EsriGraphicList list = getEsriGraphicList(); - boolean ret = false; - if (list != null) { - OMGraphic omg = list.findClosest(e.getX(), e.getY(), 4); - if (omg != null) { - int index; - - Integer I = ((Integer) omg.getAttribute(SHAPE_INDEX_ATTRIBUTE)); - if (I != null) { - index = I.intValue(); - } else { - index = list.indexOf(omg); - } - - fireRequestToolTip(getDescription(index)); - - ret = true; - } else { - fireHideToolTip(); - } - } - return ret; - } - */ - /** - * Builds a description in HTML for a tool tip for the specified OMGraphic - * - * @param index the index of the graphic in the table - */ - public String getDescription(int index) { - StringBuffer v = new StringBuffer(); - - v.append(""); - for (int i = 0; i < getTable().getColumnCount(); i++) { - try { - String column = getTable().getColumnName(i); - String value = (String) (getTable().getValueAt(index, i) + ""); - v.append((i == 0 ? "" : "
")).append(column).append(": ").append(value); - } catch (NullPointerException npe) { - } catch (IndexOutOfBoundsException obe) { - } - } - - v.append(""); - - return v.toString(); - } - - protected JPanel daGUI = null; - protected JFrame tableFrame = null; - /** - * This marks the index of the OMGraphic that is "selected" - */ - protected int graphicIndex = -1; - - /** - * DataBoundsInformer interface. - */ - public DataBounds getDataBounds() { - DataBounds box = null; - if (_list == null) { - _list = getEsriGraphicList(); - } - - if (_list != null) { - double[] extents = _list.getExtents(); - box = new DataBounds((double) extents[1], (double) extents[0], (double) extents[3], (double) extents[2]); - } - return box; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiRoadLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiRoadLayer.java deleted file mode 100644 index 12e2528c9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiRoadLayer.java +++ /dev/null @@ -1,264 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBN Technologies - * A Division of - * BBN Corporation - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright 1998 by BBN Technologies, A Division of - * BBN Corporation, all rights reserved. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/MultiRoadLayer.java,v $ - * $RCSfile: MultiRoadLayer.java,v $ - * $Revision: 1.4 $ - * $Date: 2005/08/12 21:47:49 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.layer.shape; - -import java.awt.Graphics; -import java.awt.Point; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.roads.LayerView; -import com.bbn.openmap.tools.roads.RoadFinder; -import com.bbn.openmap.tools.roads.RoadServices; -import com.bbn.openmap.tools.roads.Route; -import com.bbn.openmap.tools.roads.Segment; -import com.bbn.openmap.util.PropUtils; - -/** - * Imposes a road layer on the multi shape layer. - * - * The important method here is getPathOnRoad(implemented for the - * RoadServices interface) which returns a list of points on the road - * found between a start and an end point. - * - * You can see more about what the road layer is doing by setting - * drawIntersections to true, which will reveal what the road finder - * thinks are roads on the road layer, and drawResults to true, which - * will show each road path request and its result. The results shown - * accumulate over time. - * - * @see com.bbn.openmap.tools.roads.RoadServices - */ -public class MultiRoadLayer extends MultiShapeLayer implements RoadServices, - ProjectionListener, LayerView { - - private static final long serialVersionUID = 1L; - Logger logger = Logger.getLogger(this.getClass().getName()); - RoadFinder helper; - - /** - * list of extra OMGraphics that represent intersections or - * results - */ - OMGraphicList toDraw = new OMGraphicList(); - boolean drawIntersections = false; - boolean drawResults = false; - - /** - * Property 'drawIntersections' will display the intersections on - * the road layer False by default. - */ - public static final String DrawIntersectionsProperty = "drawIntersections"; - - /** - * Property 'drawResults' will display the results of each road - * request on the road layer False by default. - */ - public static final String DrawResultsProperty = "drawResults"; - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - setDrawIntersections(PropUtils.booleanFromProperties(props, realPrefix - + DrawIntersectionsProperty, drawIntersections)); - setDrawResults(PropUtils.booleanFromProperties(props, realPrefix - + DrawResultsProperty, drawResults)); - setHelper(); - } - - protected void setDrawIntersections(boolean val) { - drawIntersections = val; - } - - protected void setDrawResults(boolean val) { - drawResults = val; - } - - protected void setHelper() { - logger.info("draw inter " + drawIntersections); - helper = new RoadFinder((LayerView) this, drawIntersections, drawResults); - } - - /** - * Get points on the road between start and end - * - * Implemented for the RoadService interface - * - * @param start from here - * @param end to there - * @param segments populated with road segments - * @return list of points on path - */ - public List getPathOnRoad(Point start, Point end, List segments) { - return helper.getPathOnRoad(start, end, segments); - } - - /** - * @see RoadServices#getPathOnRoad(LatLonPoint, LatLonPoint) - */ - public Route getPathOnRoad(LatLonPoint start, LatLonPoint end) { - return helper.getPathOnRoad(start, end); - } - - /** - * @see RoadServices#displayPathOnRoad(Point, Point, Route, List) - */ - public List displayPathOnRoad(Point start, Point end, Route route, List segments) { - return helper.displayPathOnRoad(start, end, route, segments); - } - - /** - * Returns the RoadServices instance. - *

- * - * @return the RoadServices instance. - */ - public RoadServices getRoadServices() { - return helper; - } - - /** - * Implemented for ProjectionListener - */ - public void projectionChanged(ProjectionEvent e) { - super.projectionChanged(e); - logger.info("calling helper - projection changed."); - synchronized (this) { - if (helper == null) { - setHelper(); - } - helper.projectionChanged(e); - } - } - - /** - * Flattens nested OMGraphicLists of lists into one level list of - * OMGraphic items. Gets the original list of graphics items from - * getList. - * - * @return List of OMGraphic items that will be used to create - * roads - */ - public OMGraphicList getOMGraphicsFromSource() { - OMGraphicList list = getList(); - OMGraphicList out = new OMGraphicList(); - - Set seen = new HashSet<>(); - - if (list != null) { - if (logger.isLoggable(Level.INFO)) - logger.info("size is " + list.size()); - - for (int i = 0; i < list.size(); i++) { - OMGraphic graphic = list.getOMGraphicAt(i); - if (seen.contains(graphic)) - continue; // let's not re-add it - - seen.add(graphic); - - if (logger.isLoggable(Level.INFO)) - logger.info(i + " - " + graphic); - - if (graphic instanceof OMGraphicList) { - if (logger.isLoggable(Level.INFO)) - logger.info("size of " + graphic + " is " - + ((OMGraphicList) graphic).size()); - - for (OMGraphic inner : ((OMGraphicList) graphic)) { - - if (inner instanceof OMGraphicList) { - if (logger.isLoggable(Level.INFO)) - logger.info("size of " + inner + " is " - + ((OMGraphicList) inner).size()); - - for (OMGraphic inner2 : ((OMGraphicList) inner)) { - - if (logger.isLoggable(Level.INFO)) - logger.info("1) adding - " + inner2); - - out.add(inner2); - } - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("2) adding - " + inner); - - out.add(inner); - } - } - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("3) adding " + graphic); - - out.add(graphic); - } - } - } - - return out; - } - - /** - * Called from RoadFinder to tell it what extra to render (e.g. - * intersections, roads). - */ - public void setExtraGraphics(OMGraphicList toDraw) { - if (logger.isLoggable(Level.INFO)) { - logger.info("setting to draw " + toDraw.size() + " new graphics."); - } - - this.toDraw = toDraw; - } - - /** - * If drawIntersections or drawResults is true, will add - * intersection markers or returned road lines to what is - * rendered. - */ - public void paint(Graphics g) { - super.paint(g); - if (drawIntersections || drawResults) { - OMGraphicList graphics; - graphics = new OMGraphicList(toDraw); - graphics.generate(getProjection(), true);//all new - // graphics - if (logger.isLoggable(Level.INFO)) { - logger.info("rendering toDraw " + toDraw.size() + " items"); - } - graphics.render(g); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiShapeLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiShapeLayer.java deleted file mode 100644 index 5d8125db1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/MultiShapeLayer.java +++ /dev/null @@ -1,361 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/MultiShapeLayer.java,v $ -// $RCSfile: MultiShapeLayer.java,v $ -// $Revision: 1.17 $ -// $Date: 2008/10/16 03:26:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.awt.Component; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that displays multiple shape files. Note that the - * ESRIRecords have been updated so that the OMGraphics that get created from - * them are loaded with an Integer object that notes the number of the record as - * it was read from the .shp file. This lets you align the object with the - * correct attribute data in the .dbf file. - * - *


- * 
- *  
- *   ############################
- *   # Properties for a multiple shape file layer
- *   shapeLayer.class=com.bbn.openmap.layer.shape.MultiShapeLayer
- *   shapeLayer.prettyName=Name_for_Menu
- *   shapeLayer.shapeFileList=marker_name1 marker_name2 ...
- *  
- *   shapeLayer.marker_name1.shapeFile=&ltpath to shapefile (.shp)&gt
- *   shapeLayer.marker_name1.spatialIndex=&ltpath to generated spatial index file (.ssx)&gt
- *   shapeLayer.marker_name1.lineColor=ff000000
- *   shapeLayer.marker_name1.fillColor=ff000000
- *   # plus any other properties used by the DrawingAttributes object.
- *   shapeLayer.marker_name1.pointImageURL=&ltURL for image to use for point objects&gt
- *   shapeLayer.marker_name1.enabled=true/false
- *  
- *   shapeLayer.marker_name2.shapeFile=&ltpath to shapefile (.shp)&gt
- *   shapeLayer.marker_name2.spatialIndex=&ltpath to generated spatial index file (.ssx)&gt
- *   shapeLayer.marker_name2.lineColor=ff000000
- *   shapeLayer.marker_name2.fillColor=ff000000
- *   # plus any other properties used by the DrawingAttributes object.
- *   shapeLayer.marker_name2.pointImageURL=&ltURL for image to use for point objects&gt
- *   shapeLayer.marker_name2.enabled=true/false
- *   ############################
- *   
- * 
- * - * @version $Revision: 1.17 $ $Date: 2008/10/16 03:26:50 $ - * @see SpatialIndex - */ -public class MultiShapeLayer - extends ShapeLayer { - - public final static String ShapeFileListProperty = "shapeFileList"; - protected Collection spatialIndexes; - - /** - * Initializes an empty shape layer. - */ - public MultiShapeLayer() { - super(); - } - - public void setSpatialIndexes(Collection siv) { - spatialIndexes = siv; - } - - public Collection getSpatialIndexes() { - return spatialIndexes; - } - - /** - * This method gets called from setProperties. - * - * @param prefix This prefix has already been scoped, which means it is an - * empty string if setProperties was called with a null prefix, or - * it's a String ending with a period if it was defined with - * characters. - * @param props Properties containing information about files and the layer. - */ - protected void setFileProperties(String prefix, Properties props) { - setSpatialIndexes(prefix, props); - } - - /** - * This method gets called from setFileProperties. - * - * @param prefix This prefix has already been scoped, which means it is an - * empty string if setProperties was called with a null prefix, or - * it's a String ending with a period if it was defined with - * characters. - * @param p Properties containing information about files and the layer. - */ - protected void setSpatialIndexes(String prefix, Properties p) { - - String shapeFileList = p.getProperty(prefix + ShapeFileListProperty); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + "| list = \"" + shapeFileList + "\""); - } - - List shapeFileStrings = PropUtils.parseSpacedMarkers(shapeFileList); - - if (shapeFileStrings != null) { - - spatialIndexes = new Vector(shapeFileStrings.size()); - - for (String listName : shapeFileStrings) { - SpatialIndexHandler sih = new SpatialIndexHandler(prefix + listName, p); - spatialIndexes.add(sih); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": MultiShapeLayer adding: " + sih); - } - } - } else { - logger.fine(getName() + ": " + prefix + ShapeFileListProperty + " not set in properties"); - } - } - - /** - * PropertyConsumer method. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.remove(prefix + shapeFileProperty); - props.remove(prefix + pointImageURLProperty); - - Iterator sis = spatialIndexes.iterator(); - StringBuffer list = new StringBuffer(); - while (sis.hasNext()) { - SpatialIndexHandler sih = sis.next(); - sih.getProperties(props); - String pp = sih.getPropertyPrefix(); - // Can't be null, if they are part of this layer... - pp = pp.substring(pp.lastIndexOf('.') + 1); - list.append(" ").append(pp); - } - - props.put(prefix + ShapeFileListProperty, list.toString()); - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - props.remove(shapeFileProperty); - props.remove(pointImageURLProperty); - props.remove(shapeFileProperty + ScopedEditorProperty); - props.remove(pointImageURLProperty + ScopedEditorProperty); - - Iterator sis = spatialIndexes.iterator(); - while (sis.hasNext()) { - sis.next().getPropertyInfo(props); - } - - props.put(ShapeFileListProperty, "List of marker names for SpatialIndexHandlers"); - - return props; - } - - /** - * Creates an OMGraphicList containing graphics from all SpatialIndex - * objects and shapefiles. - * - * @return OMGraphicList containing an OMGraphicList containing shapes from - * a particular shape file. - */ - public synchronized OMGraphicList prepare() { - - if (spatialIndexes == null || spatialIndexes.isEmpty()) { - logger.fine(getName() + ": spatialIndexes is empty!"); - return new OMGraphicList(); - } - - Projection projection = getProjection(); - - if (projection == null) { - // This can happen if the layer is part of a - // ScaleFilterLayer, and the redraw button for this layer - // is pressed before the ScaleFilterLayer gives it a - // projection (which only happens if the layer is the - // active one). - logger.fine(getName() + ": prepare called with null projection"); - return new OMGraphicList(); - } - - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - double ulLat = ul.getY(); - double ulLon = ul.getX(); - double lrLat = lr.getY(); - double lrLon = lr.getX(); - - OMGraphicList masterList = new OMGraphicList(); - OMGraphicList list = null; - - // check for dateline anomaly on the screen. we check for - // ulLon >= lrLon, but we need to be careful of the check for - // equality because of floating point arguments... - if (ProjMath.isCrossingDateline(ulLon, lrLon, projection.getScale())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": Dateline is on screen"); - } - - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - - Iterator sii = spatialIndexes.iterator(); - while (sii.hasNext()) { - SpatialIndexHandler sih = (SpatialIndexHandler) sii.next(); - if (!sih.enabled) - continue; - - try { - - list = sih.getGraphics(ulLon, ymin, 180.0d, ymax, list, projection); - list = sih.getGraphics(-180.0d, ymin, lrLon, ymax, list, projection); - } catch (java.io.IOException ex) { - ex.printStackTrace(); - } catch (FormatException fe) { - fe.printStackTrace(); - } - masterList.add(list); - } - } else { - - double xmin = (double) Math.min(ulLon, lrLon); - double xmax = (double) Math.max(ulLon, lrLon); - double ymin = (double) Math.min(ulLat, lrLat); - double ymax = (double) Math.max(ulLat, lrLat); - - Iterator sii = spatialIndexes.iterator(); - while (sii.hasNext()) { - SpatialIndexHandler sih = (SpatialIndexHandler) sii.next(); - - if (!sih.enabled) - continue; - - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": Getting graphics from " + sih.prettyName + " spatial index"); - } - try { - list = sih.getGraphics(xmin, ymin, xmax, ymax, list, projection); - } catch (java.io.IOException ex) { - ex.printStackTrace(); - } catch (FormatException fe) { - fe.printStackTrace(); - } - masterList.add(list); - } - } - - // OMGraphics already projected in SpatialIndexHandlers - // if (masterList != null) { - // masterList.generate(projection, true);//all new graphics - // } - return masterList; - } - - public Component getGUI() { - if (box == null) { - - box = new JPanel(); - JTabbedPane tabs = new JTabbedPane(); - - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setAlignmentX(Component.LEFT_ALIGNMENT); - - Iterator sii = spatialIndexes.iterator(); - while (sii.hasNext()) { - SpatialIndexHandler sih = sii.next(); - JPanel stuff = (JPanel) sih.getGUI(); - if (stuff != null) { - tabs.addTab(sih.getPrettyName(), stuff); - } - } - - box.add(tabs); - - JPanel pal2 = new JPanel(); - JButton redraw = new JButton("Redraw Layer"); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - pal2.add(redraw); - box.add(pal2); - } - return box; - } - - /** - * DataBoundsInformer interface. - */ - public DataBounds getDataBounds() { - - ESRIBoundingBox bounds = new ESRIBoundingBox(); - - for (Iterator sii = spatialIndexes.iterator(); sii.hasNext();) { - SpatialIndexHandler sih = sii.next(); - if (sih != null && sih.spatialIndex != null) { - ESRIBoundingBox boundingBox = sih.spatialIndex.getBounds(); - if (boundingBox != null) { - bounds.addBounds(boundingBox); - } - } - } - - return new DataBounds(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/NumAndBox.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/NumAndBox.java deleted file mode 100644 index 900e09494..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/NumAndBox.java +++ /dev/null @@ -1,54 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/NumAndBox.java,v $ -// $RCSfile: NumAndBox.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -/** - * A class used as a application object by OMGeometry objects, letting - * them keep track of their record number (noted by their place in the - * Shape file) and bounding box. - */ -public class NumAndBox { - protected int recNum; - protected ESRIBoundingBox bbox; - - public NumAndBox(int recordNumber, ESRIBoundingBox box) { - recNum = recordNumber; - bbox = box; - } - - public void setRecNum(int number) { - recNum = number; - } - - public int getRecNum() { - return recNum; - } - - public void setBoundingBox(ESRIBoundingBox box) { - bbox = box; - } - - public ESRIBoundingBox getBoundingBox() { - return bbox; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFile.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFile.java deleted file mode 100644 index 14ce8cd11..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFile.java +++ /dev/null @@ -1,532 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ShapeFile.java,v $ -// $RCSfile: ShapeFile.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 18:48:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Vector; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.util.Debug; - -/** - * Class representing an ESRI Shape File. - *

- *

- * Usage:
- * 
- * To verify a shape file:
- * java com.bbn.openmap.layer.shape.ShapeFile -v shapeFile
- * 
- * Append records from srcShapeFile to destShapeFile:
- * java com.bbn.openmap.layer.shape.ShapeFile -a destShapeFile srcShapeFile
- * 
- * Print information about the header and the number of records:
- * java com.bbn.openmap.layer.shape.ShapeFile shapeFile
- * 
- * 
- * - * @author Tom Mitchell - * @author Ray Tomlinson - * @author Geoffrey Knauth - * @version $Revision: 1.4 $ $Date: 2005/08/09 18:48:03 $ - */ -public class ShapeFile - extends ShapeUtils { - - /** A Shape File's magic number. */ - public static final int SHAPE_FILE_CODE = 9994; - - /** The currently handled version of Shape Files. */ - public static final int SHAPE_FILE_VERSION = 1000; - - /** A default record size. Automatically increased on demand. */ - public static final int DEFAULT_RECORD_BUFFER_SIZE = 50000; - - /** The read/write class for shape files. */ - protected RandomAccessFile raf; - - /** The buffer that holds the 100 byte header. */ - protected byte header[]; - - /** Holds the length of the file, in bytes. */ - protected long fileLength; - - /** Holds the version of the file, as an int. */ - protected int fileVersion; - - /** Holds the shape type of the file. */ - protected int fileShapeType; - - /** Holds the bounds of the file (four doubles). */ - protected ESRIBoundingBox fileBounds; - - /** A buffer for current record's header. */ - protected byte recHdr[]; - - /** A buffer for the current record's data. */ - protected byte recBuf[]; - - /** - * Construct a ShapeFile from a file name. - * - * @exception IOException if something goes wrong opening or reading the - * file. - */ - public ShapeFile(String name) - throws IOException { - raf = new RandomAccessFile(name, "rw"); - recHdr = new byte[ShapeUtils.SHAPE_FILE_RECORD_HEADER_LENGTH]; - recBuf = new byte[DEFAULT_RECORD_BUFFER_SIZE]; - initHeader(); - } - - /** - * Construct a ShapeFile from the given File. - * - * @param file A file object representing an ESRI Shape File - * - * @exception IOException if something goes wrong opening or reading the - * file. - */ - public ShapeFile(File file) - throws IOException { - this(file.getPath()); - } - - /** - * Reads or writes the header of a Shape file. If the file is empty, a blank - * header is written and then read. If the file is not empty, the header is - * read. - *

- * After this function runs, the file pointer is set to byte 100, the first - * byte of the first record in the file. - * - * @exception IOException if something goes wrong reading or writing the - * shape file - */ - protected void initHeader() - throws IOException { - int result = raf.read(); - if (result == -1) { - // File is empty, write a new header into the file - writeHeader(); - } - readHeader(); - } - - /** - * Writes a blank header into the shape file. - * - * @exception IOException if something goes wrong writing the shape file - */ - protected void writeHeader() - throws IOException { - header = new byte[SHAPE_FILE_HEADER_LENGTH]; - writeBEInt(header, 0, SHAPE_FILE_CODE); - writeBEInt(header, 24, 50); // empty shape file size in 16 bit - // words - writeLEInt(header, 28, SHAPE_FILE_VERSION); - writeLEInt(header, 32, SHAPE_TYPE_NULL); - writeLEDouble(header, 36, 0.0); - writeLEDouble(header, 44, 0.0); - writeLEDouble(header, 52, 0.0); - writeLEDouble(header, 60, 0.0); - raf.seek(0); - raf.write(header, 0, SHAPE_FILE_HEADER_LENGTH); - } - - /** - * Reads and parses the header of the file. Values from the header are stored - * in the fields of this class. - * - * @exception IOException if something goes wrong reading the file - * @see #header - * @see #fileVersion - * @see #fileLength - * @see #fileShapeType - * @see #fileBounds - */ - protected void readHeader() - throws IOException { - header = new byte[ShapeUtils.SHAPE_FILE_HEADER_LENGTH]; - raf.seek(0); // Make sure we're at the beginning of - // the file - raf.read(header, 0, ShapeUtils.SHAPE_FILE_HEADER_LENGTH); - int fileCode = ShapeUtils.readBEInt(header, 0); - if (fileCode != SHAPE_FILE_CODE) { - throw new IOException("Invalid file code, " + "probably not a shape file"); - } - - fileVersion = ShapeUtils.readLEInt(header, 28); - if (fileVersion != SHAPE_FILE_VERSION) { - throw new IOException("Unable to read shape files with version " + fileVersion); - } - - fileLength = ShapeUtils.readBEInt(header, 24); - fileLength *= 2; // convert from 16-bit words to 8-bit - // bytes - fileShapeType = ShapeUtils.readLEInt(header, 32); - fileBounds = ShapeUtils.readBox(header, 36); - } - - /** - * Returns the length of the file in bytes. - * - * @return the file length - */ - public long getFileLength() { - return fileLength; - } - - /** - * Returns the version of the file. The only currently supported version is - * 1000 (which represents version 1). - * - * @return the file version - */ - public int getFileVersion() { - return fileVersion; - } - - /** - * Returns the shape type of the file. Shape files do not mix shape types; - * all the shapes are of the same type. - * - * @return the file's shape type - */ - public int getShapeType() { - return fileShapeType; - } - - /** - * Sets the shape type of the file. If the file has a shape type already, it - * cannot be set. If it does not have a shape type, it is set and written to - * the file in the header. - *

- * Shape types are enumerated in the class ShapeUtils. - * - * @param newShapeType the new shape type - * @exception IOException if something goes wrong writing the file - * @exception IllegalArgumentException if file already has a shape type - * @see ShapeUtils - */ - public void setShapeType(int newShapeType) - throws IOException, IllegalArgumentException { - if (fileShapeType == SHAPE_TYPE_NULL) { - fileShapeType = newShapeType; - long filePtr = raf.getFilePointer(); - writeLEInt(header, 32, fileShapeType); - raf.seek(0); - raf.write(header, 0, 100); - raf.seek(filePtr); - } else { - throw new IllegalArgumentException("file already has a valid" + " shape type: " + fileShapeType); - } - } - - /** - * Returns the bounding box of this shape file. The bounding box is the - * smallest rectangle that encloses all the shapes in the file. - * - * @return the bounding box - */ - public ESRIBoundingBox getBoundingBox() { - return fileBounds; - } - - /** - * Returns the next record from the shape file as an ESRIRecord. - * Each successive call gets the next record. There is no way to go back a - * record. When there are no more records, null is returned. - * - * @return a record, or null if there are no more records - * @exception IOException if something goes wrong reading the file - */ - public ESRIRecord getNextRecord() - throws IOException { - // Debug.output("getNextRecord: ptr = " + - // raf.getFilePointer()); - int result = raf.read(recHdr, 0, ShapeUtils.SHAPE_FILE_RECORD_HEADER_LENGTH); - if (result == -1) { // EOF - // Debug.output("getNextRecord: EOF"); - return null; - } - - int contentLength = ShapeUtils.readBEInt(recHdr, 4); - int bytesToRead = contentLength * 2; - int fullRecordSize = bytesToRead + 8; - if (recBuf.length < fullRecordSize) { - if (Debug.debugging("shape")) { - Debug.output("record size: " + fullRecordSize); - } - recBuf = new byte[fullRecordSize]; - } - System.arraycopy(recHdr, 0, recBuf, 0, ShapeUtils.SHAPE_FILE_RECORD_HEADER_LENGTH); - raf.read(recBuf, ShapeUtils.SHAPE_FILE_RECORD_HEADER_LENGTH, bytesToRead); - - switch (fileShapeType) { - - case ShapeUtils.SHAPE_TYPE_NULL: - throw new IOException("Can't parse NULL shape type"); - - case ShapeUtils.SHAPE_TYPE_POINT: - return new ESRIPointRecord(recBuf, 0); - - case ShapeUtils.SHAPE_TYPE_ARC: - // case ShapeUtils.SHAPE_TYPE_POLYLINE: - return new ESRIPolygonRecord(recBuf, 0); - - case ShapeUtils.SHAPE_TYPE_POLYGON: - return new ESRIPolygonRecord(recBuf, 0); - - case ShapeUtils.SHAPE_TYPE_MULTIPOINT: - throw new IOException("Multipoint shape not yet implemented"); - - default: - throw new IOException("Unknown shape type: " + fileShapeType); - } - - } - - /** - * Adds a record to the end of this file. The record is written to the file - * at the end of the last record. - * - * @param r the record to be added - * @exception IOException if something goes wrong writing to the file - */ - public void add(ESRIRecord r) - throws IOException { - if (r.getShapeType() == fileShapeType) { - verifyRecordBuffer(r.getBinaryStoreSize()); - int nBytes = r.write(recBuf, 0); - // long len = raf.length(); - // Debug.output("seek to " + len); - raf.seek(raf.length()); - raf.write(recBuf, 0, nBytes); - } else { - Debug.error("ShapeFile.add(): type=" + r.getShapeType() + " does not match file type=" + fileShapeType); - } - } - - /** - * Closes the shape file and disposes of resources. - * - * @exception IOException if something goes wrong closing the file - */ - public void close() - throws IOException { - raf.close(); - raf = null; - } - - /** - * Verifies the contents of a shape file. The header is verified for file - * length, bounding box, and shape type. The records are verified for shape - * type and record number. The file is verified for proper termination (EOF - * at the end of a record). - * - * @param repair NOT CURRENTLY USED - would signal that the file should be - * repaired if possible - * @param verbose NOT CURRENTLY USED - would cause the verifier to display - * progress and status - * @exception IOException if something goes wrong reading or writing the file - */ - public void verify(boolean repair, boolean verbose) - throws IOException { - // Is file length stored in header correctly? - // Is file bounding box correct? - // Does file have a valid shape type? - // Is each record the correct shape type? - // Does each record header have the correct record number? - // Do we reach EOF at the end of a record? - boolean headerChanged = false; - long fLen = raf.length(); - if (verbose) { - Debug.output("Checking file length..."); - System.out.flush(); - } - if (fileLength == fLen) { - if (verbose) { - Debug.output("correct."); - } - } else { - if (verbose) { - Debug.output("incorrect (got " + fileLength + ", should be " + fLen + ")"); - } - if (repair) { - fileLength = fLen; - writeBEInt(header, 24, ((int) fLen / 2)); - headerChanged = true; - if (verbose) { - Debug.output("...repaired."); - } - } - } - - // loop through file to verify: - // record numbers - // Shape types - // bounding box - // correct EOF - - raf.seek(100); - ESRIRecord r; - int nRecords = 0; - Vector v = new Vector(); - ESRIBoundingBox bounds = new ESRIBoundingBox(); - long recStart = raf.getFilePointer(); - byte intBuf[] = new byte[4]; - while ((r = getNextRecord()) != null) { - long recEnd = raf.getFilePointer(); - // Debug.output("verify - start: " + recStart + - // "; end: " + recEnd); - nRecords++; - v.addElement(r); - if (r.getRecordNumber() != nRecords) { - // Debug.output("updating record number for record " - // + nRecords); - writeBEInt(intBuf, 0, nRecords); - raf.seek(recStart); - raf.write(intBuf, 0, 4); - raf.seek(recEnd); - } - if (fileShapeType == SHAPE_TYPE_NULL) { - Debug.output("updating shape type in header."); - fileShapeType = r.getShapeType(); - writeLEInt(header, 32, fileShapeType); - headerChanged = true; - } - if (r.getShapeType() != fileShapeType) { - Debug.output("invalid shape type " + r.getShapeType() + ", expecting " + fileShapeType); - } - - bounds.addBounds(r.getBoundingBox()); - recStart = recEnd; - } - - if (!fileBounds.equals(bounds)) { - Debug.output("adjusting bounds"); - Debug.output("from min: " + fileBounds.min); - Debug.output("to min: " + bounds.min); - Debug.output("from max: " + fileBounds.max); - Debug.output("to max: " + bounds.max); - writeBox(header, 36, bounds); - headerChanged = true; - fileBounds = bounds; - } - - if (headerChanged) { - Debug.output("writing changed header"); - raf.seek(0); - raf.write(header, 0, 100); - } - } - - /** - * Verifies that the record buffer is big enough to hold the given number of - * bytes. If it is not big enough a new buffer is created that can hold the - * given number of bytes. - * - * @param size the number of bytes the buffer needs to hold - */ - protected void verifyRecordBuffer(int size) { - if (recBuf.length < size) { - recBuf = new byte[size]; - } - } - - /** - * The driver for the command line interface. Reads the command line - * arguments and executes appropriate calls. - *

- * See the file documentation for usage. - * - * @param args the command line arguments - * @exception IOException if something goes wrong reading or writing the file - */ - public static void main(String args[]) - throws IOException { - Debug.init(System.getProperties()); - int argc = args.length; - if (argc == 1) { - ShapeFile sf = new ShapeFile(args[0]); - Debug.output("Shape file: " + args[0]); - Debug.output("version: " + sf.getFileVersion()); - Debug.output("length: " + sf.getFileLength()); - Debug.output("bounds:"); - Debug.output("\tmin: " + sf.getBoundingBox().min); - Debug.output("\tmax: " + sf.getBoundingBox().max); - int nRecords = 0; - ESRIRecord record = sf.getNextRecord(); - while (record != null) { - if (record instanceof ESRIPointRecord) { - double lat = ((ESRIPointRecord)record).getY(); - double lon = ((ESRIPointRecord)record).getX(); - Debug.output("record: " + lat + ", " + lon); - } else { - Debug.output("record: " + record.getClass().getName()); - } - nRecords++; - record = sf.getNextRecord(); - } - Debug.output("records: " + nRecords); - } else if ("-a".equals(args[0])) { - // Append a shape file to another shape file - String destFile = args[1]; - String srcFile = args[2]; - - ShapeFile in = new ShapeFile(srcFile); - ShapeFile out = new ShapeFile(destFile); - - if (in.getShapeType() != out.getShapeType()) { - try { - out.setShapeType(in.getShapeType()); - } catch (IllegalArgumentException e) { - Debug.error("Incompatible shape types."); - System.exit(1); - } - } - - ESRIRecord r; - while ((r = in.getNextRecord()) != null) { - out.add(r); - } - out.verify(true, true); - } else if ("-v".equals(args[0])) { - // Verify a shape file - String shpFile = args[1]; - - ShapeFile s = new ShapeFile(shpFile); - - s.verify(true, true); - } else { - Debug.output("Usage:"); - Debug.output("ShapeFile file.shp -- displays information about file.shp"); - Debug.output("ShapeFile -a dest.shp src.shp -- appends records from src.shp to dest.shp"); - Debug.output("ShapeFile -v file.shp -- verifies file.shp"); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFileCrop.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFileCrop.java deleted file mode 100644 index bcf2a5c23..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeFileCrop.java +++ /dev/null @@ -1,222 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ShapeFileCrop.java,v $ -// $RCSfile: ShapeFileCrop.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* ShapeFileCrop class - written by Eliot T. Lebsack of the MITRE Corp. 10/16/2002. */ - -package com.bbn.openmap.layer.shape; - -import java.io.IOException; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; - -/** - * Class that supports cropping of ESRI Shapefiles with a simple bounding box. - * Does not yet update the .shx or .dbf files. - * - *

- * Usage:
- * 
- * java com.bbn.openmap.layer.shape.ShapeFileCrop -ul lat,lon -lr lat,lon -i srcShapeFile -o destShapeFile
- * 
- * Crops the srcShapeFile, dumps the output into destShapeFile. 
- * Note that this does simple rejection of entities based on their bounding
- * boxes.
- * 
- * A better scheme (unimplemented) would be to actually crop the line
- * segments.
- * 
- * 
- * - * @author Eliot Lebsack - * @version $Revision: 1.5 $ $Date: 2005/12/09 21:09:10 $ - */ -public class ShapeFileCrop { - - /** Input ShapeFile object. */ - public ShapeFile sfin = null; - - /** Output ShapeFile object. */ - public ShapeFile sfout = null; - - /** Bounding Box Object used for cropping */ - ESRIBoundingBox ebb = null; - - /** - * Construct a ShapeFileCrop object from a pair of file names. - * - * @exception IOException - * if something goes wrong opening or reading the file. - */ - public ShapeFileCrop(String namein, String nameout) throws IOException { - sfin = new ShapeFile(namein); - sfout = new ShapeFile(nameout); - } - - /** - * Read the input ShapeFile object, and apply cropping rules to - * the read entities. Writes the output ShapeFile object, and - * then invokes the ShapeFile .verify method to fix the output - * file header. - * - * @exception IOException - * if something goes wrong opening or reading the file. - */ - public void cropShapeFile() throws IOException { - ESRIPolygonRecord pr; - int nRecordNum = 0; - int nRecords = 0; - - sfin.readHeader(); - - sfout.setShapeType(sfin.fileShapeType); - - switch (sfin.fileShapeType) { - case (ShapeUtils.SHAPE_TYPE_ARC): - case (ShapeUtils.SHAPE_TYPE_POLYGON): - while ((pr = (ESRIPolygonRecord) sfin.getNextRecord()) != null) { - nRecords++; - if (overlapBBTest(pr.bounds) != 0) { - pr.recordNumber = nRecordNum + 1; - sfout.add(pr); - nRecordNum++; - nRecords++; - } - } - } - - System.out.println("Number of input records = " + (nRecords + 1)); - System.out.println("Number of candidate records = " + nRecordNum); - - if (nRecordNum > 0) - sfout.verify(true, true); - - sfin.close(); - sfout.close(); - } - - private int overlapBBTest(ESRIBoundingBox bb) { - int result = 0; - - result += boundaryTest(bb.min.x, bb.min.y); - result += boundaryTest(bb.max.x, bb.min.y); - result += boundaryTest(bb.min.x, bb.max.y); - result += boundaryTest(bb.max.x, bb.max.y); - - return result; - } - - private int boundaryTest(double x, double y) { - int ns = 0; - int ew = 0; - - if ((x >= ebb.min.x) && (x < ebb.max.x)) - ew++; - - if ((y >= ebb.min.y) && (y < ebb.max.y)) - ns++; - - return ns * ew; - } - - public static void usage() { - System.out - .println("Usage: java ShapeFileCrop [args] -i -o "); - System.out.println("Arguments:"); - System.out - .println("-ul lat,lon Coordinates of upper-left corner of the bounding box to use for cropping"); - System.out - .println("-lr lat,lon Coordinates of lower-right corner of the bounding box to use for cropping"); - System.exit(1); - } - - /** - * The driver for the command line interface. Reads the command line - * arguments and executes appropriate calls. - *

- * See the file documentation for usage. - * - * @param args - * the command line arguments - * @exception IOException - * if something goes wrong reading or writing the file - */ - - public static void main(String[] args) throws IOException { - String inpath = ""; - String outpath = ""; - String sllp; - String[] sllpa; - - ShapeFileCrop sfc = null; - - ESRIPoint ul = null; - ESRIPoint lr = null; - int index = 0; - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-i")) { - inpath = args[++i]; - } else if (args[i].equals("-o")) { - outpath = args[++i]; - } else if (args[i].equals("-ul")) { - sllp = args[++i]; - // sllpa = sllp.split(","); // jdk 1.4 - index = sllp.indexOf(","); - - if (index != -1) { - sllpa = new String[2]; - sllpa[0] = sllp.substring(0, index); - sllpa[1] = sllp.substring(index + 1); - ul = new ESRIPoint(Double.valueOf(sllpa[1]).doubleValue(), - Double.valueOf(sllpa[0]).doubleValue()); - } - - } else if (args[i].equals("-lr")) { - sllp = args[++i]; - // sllpa = sllp.split(","); // jdk 1.4 - index = sllp.indexOf(","); - if (index != -1) { - sllpa = new String[2]; - sllpa[0] = sllp.substring(0, index); - sllpa[1] = sllp.substring(index + 1); - lr = new ESRIPoint(Double.valueOf(sllpa[1]).doubleValue(), - Double.valueOf(sllpa[0]).doubleValue()); - } - - } else { - usage(); - } - } - - if ((ul == null) || (lr == null) || (inpath.length() == 0) - || (outpath.length() == 0)) { - usage(); - } else { - sfc = new ShapeFileCrop(inpath, outpath); - sfc.ebb = new ESRIBoundingBox(ul, lr); - } - - if (sfc != null) { - sfc.cropShapeFile(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeIndex.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeIndex.java deleted file mode 100644 index 52fbd1ab0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeIndex.java +++ /dev/null @@ -1,114 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ShapeIndex.java,v $ -// $RCSfile: ShapeIndex.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.io.IOException; -import java.io.RandomAccessFile; - -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.util.Debug; - -/** - * A class representing a shape index file. - *

- * Currently this class has limited capabilities. It can dump the - * index information to stdout. This is useful for verification of a - * spatial index. - *

- * 
- * Usage
- * 
- * 
- * java com.bbn.openmap.shape.ShapeIndex file.shx
- * 
- * 
- * 
- * - * Dumps spatial index information, excluding bounding boxes - * to stdout. Useful for comparing to a shape index. - * - * - * @author Tom Mitchell - * @version $Revision: 1.6 $ $Date: 2005/12/09 21:09:10 $ - * @see SpatialIndex - */ -public class ShapeIndex extends ShapeUtils { - - /** Size of the shape index record, value is 8 bytes. */ - public final static int SHAPE_INDEX_RECORD_LENGTH = 8; - - /** The shape index file. */ - protected RandomAccessFile shx; - - /** - * Opens a shape index file for reading. - * - * @param shxFilename the name of the spatial index file - * @exception IOException if something goes wrong opening the file - */ - public ShapeIndex(String shxFilename) throws IOException { - shx = new RandomAccessFile(shxFilename, "r"); - } - - /** - * Displays the contents of this index. - * - * @exception IOException if something goes wrong reading the file - */ - public void dumpIndex() throws IOException { - boolean atEOF = false; - byte ixRecord[] = new byte[SHAPE_INDEX_RECORD_LENGTH]; - int recNum = 0; - - shx.seek(100); // skip the file header - while (!atEOF) { - int result = shx.read(ixRecord, 0, SHAPE_INDEX_RECORD_LENGTH); - if (result == -1) { - atEOF = true; - Debug.output("Processed " + recNum + " records"); - } else { - recNum++; - int offset = readBEInt(ixRecord, 0); - int length = readBEInt(ixRecord, 4); - Debug.output("Record " + recNum + ": " + offset + ", " + length); - } - } - - } - - /** - * The driver for the command line interface. Reads the command - * line arguments and executes appropriate calls. - *

- * See the file documentation for usage. - * - * @param args the command line arguments - * @exception IOException if something goes wrong reading or - * writing the file - */ - public static void main(String args[]) throws IOException { - String name = args[0]; - ShapeIndex si = new ShapeIndex(name); - si.dumpIndex(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeLayer.java deleted file mode 100644 index 0a08c3fa5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeLayer.java +++ /dev/null @@ -1,529 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/ShapeLayer.java,v $ -// $RCSfile: ShapeLayer.java,v $ -// $Revision: 1.29 $ -// $Date: 2008/10/16 17:58:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.dataAccess.shape.DbfHandler; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.DataBoundsProvider; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that displays shape files. Note that the ESRIRecords have - * been updated so that the OMGraphics that get created from them are loaded - * with an Integer object that notes the number of the record as it was read - * from the .shp file. This lets you align the object with the correct attribute - * data in the .dbf file. - *

- *

- *       
- * ############################
- * # Properties for a shape layer
- * shapeLayer.class=com.bbn.openmap.layer.shape.ShapeLayer
- * shapeLayer.prettyName=Name_for_Menu
- * shapeLayer.shapeFile=&ltpath to shapefile (.shp)&gt
- * shapeLayer.spatialIndex=&ltpath to generated spatial index file (.ssx)&gt
- * shapeLayer.lineColor=ff000000
- * shapeLayer.fillColor=ff000000
- * # plus any other properties used by the DrawingAttributes object.
- * shapeLayer.pointImageURL=&ltURL for image to use for point objects&gt
- *        
- *        
- * # Optionally, Rule marker names specified in space-separated list
- * shapeLayer.rules=rule0 rule1
- * # global scale settings can be used so work is only performed within scale range of minScale/maxScale
- * shapeLayer.maxScale=1000000f
- * 
- * # rule0 definition:
- * # CLASS_RTE is a DBF column name
- * shapeLayer.rule0.key=CLASS_RTE
- * # operation, if key value is less than 2
- * shapeLayer.rule0.op=lt
- * shapeLayer.rule0.val=2
- * # If rule is met, then actions can be performed:
- * # DBF Column names can be added together in a label by specifying them in a space-separated list
- * shapeLayer.rule0.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * # Labels can have scale limits imposed, so they don't appear if map scale is 
- * # greater than maxScale or less than minScale
- * shapeLayer.rule0.label.maxScale=1000000
- * # Visibility can be controlled with respect to scale as well
- * shapeLayer.rule0.render=true
- * shapeLayer.rule0.render.maxScale=1000000
- * # Rendering attributes can be specified.
- * shapeLayer.rule0.lineColor=FFFA73
- * shapeLayer.rule0.lineWidth=4
- * shapeLayer.rule0.mattingColor=55AAAAAA
- * 
- * # rule1 definition:
- * shapeLayer.rule1.key=CLASS_RTE
- * shapeLayer.rule1.op=all
- * shapeLayer.rule1.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * shapeLayer.rule1.label.maxScale=200000
- * shapeLayer.rule1.render=true
- * shapeLayer.rule1.render.maxScale=500000
- * shapeLayer.rule1.lineColor=FFFFFF
- * shapeLayer.rule1.lineWidth=3
- * shapeLayer.rule1.mattingColor=55AAAAAA
- * ############################
- * 
- * 
- * - * @author Tom Mitchell - * @version $Revision: 1.29 $ $Date: 2008/10/16 17:58:15 $ - * @see SpatialIndex - */ -public class ShapeLayer extends OMGraphicHandlerLayer implements ActionListener, DataBoundsProvider { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.shape.ShapeLayer"); - - /** The name of the property that holds the name of the shape file. */ - public final static String shapeFileProperty = "shapeFile"; - - /** The URL of an image to use for point objects. */ - public final static String pointImageURLProperty = "pointImageURL"; - - /** The spatial index of the shape file to be rendered. */ - protected SpatialIndex spatialIndex; - - /** - * The DrawingAttributes object to describe the rendering of graphics. - */ - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - // For writing out to properties file later. - String shapeFileName = null; - String imageURLString = null; - - /** - * Initializes an empty shape layer. - */ - public ShapeLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setRenderPolicy(new BufferedImageRenderPolicy(this)); - } - - public ShapeLayer(String shapeFileName) { - this(); - spatialIndex = SpatialIndex.locateAndSetShapeData(shapeFileName); - } - - public void setSpatialIndex(SpatialIndex si) { - spatialIndex = si; - } - - public SpatialIndex getSpatialIndex() { - return spatialIndex; - } - - /** - * A call-back method to override in case you want to change the BinaryFile - * used to in the DbfHandler. - * - * @param dbfFileName path to DBF file. - * @return DbfHandler with BinaryFile set in it. - * @throws FormatException - * @throws IOException - */ - protected DbfHandler createDbfHandler(String dbfFileName) throws FormatException, IOException { - BinaryBufferedFile bbf = new BinaryBufferedFile(dbfFileName); - return new DbfHandler(bbf); - } - - /** - * This method gets called from setProperties. - * - * @param realPrefix This prefix has already been scoped, which means it is - * an empty string if setProperties was called with a null prefix, or - * it's a String ending with a period if it was defined with - * characters. - * @param props Properties containing information about files and the layer. - */ - protected void setFileProperties(String realPrefix, Properties props) { - shapeFileName = props.getProperty(realPrefix + shapeFileProperty); - shapeFileName = prependDataPathPrefix(shapeFileName); - - if (shapeFileName != null && shapeFileName.length() > 0) { - - spatialIndex = SpatialIndex.locateAndSetShapeData(shapeFileName); - String dbfFileName = SpatialIndex.dbf(shapeFileName); - - try { - if (BinaryFile.exists(dbfFileName)) { - DbfHandler dbfh = createDbfHandler(dbfFileName); - dbfh.setProperties(realPrefix, props); - spatialIndex.setDbf(dbfh); - } - } catch (FormatException fe) { - if (logger.isLoggable(Level.FINE)) { - logger.warning(getName() + ": Couldn't create DBF handler for " + dbfFileName - + ", FormatException: " + fe.getMessage()); - } - } catch (IOException ioe) { - if (logger.isLoggable(Level.FINE)) { - logger.warning(getName() + ": Couldn't create DBF handler for " + dbfFileName - + ", IOException: " + ioe.getMessage()); - } - } - - imageURLString = props.getProperty(realPrefix + pointImageURLProperty); - - try { - if (imageURLString != null && imageURLString.length() > 0) { - URL imageURL = PropUtils.getResourceOrFileOrURL(this, imageURLString); - ImageIcon imageIcon = new ImageIcon(imageURL); - spatialIndex.setPointIcon(imageIcon); - } - } catch (MalformedURLException murle) { - logger.warning(getName() + ": point image URL not so good: \n\t" + imageURLString); - } catch (NullPointerException npe) { - // May happen if not connected to the internet. - fireRequestMessage("Can't access icon image: \n " + imageURLString); - } - - setSpatialIndex(spatialIndex); - - } else { - logger.warning(getName() + ": No Shape file was specified:\n\t" + realPrefix - + shapeFileProperty); - } - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for this layer - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - drawingAttributes.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - setFileProperties(realPrefix, props); - } - - - /** - * PropertyConsumer method. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + shapeFileProperty, (shapeFileName == null ? "" : shapeFileName)); - props.put(prefix + pointImageURLProperty, (imageURLString == null ? "" : imageURLString)); - - if (drawingAttributes != null) { - drawingAttributes.setPropertyPrefix(getPropertyPrefix()); - drawingAttributes.getProperties(props); - } else { - DrawingAttributes da = (DrawingAttributes) DrawingAttributes.DEFAULT.clone(); - da.setPropertyPrefix(getPropertyPrefix()); - da.getProperties(props); - } - - if (spatialIndex != null) { - DbfHandler dbfh = spatialIndex.getDbf(); - if (dbfh != null) { - dbfh.getProperties(props); - } - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - String dummyMarker = PropUtils.getDummyMarkerForPropertyInfo(getPropertyPrefix(), null); - - PropUtils.setI18NPropertyInfo(i18n, list, ShapeLayer.class, dummyMarker, "Rendering Attributes", "Attributes that determine how the shapes will be drawn.", "com.bbn.openmap.omGraphics.DrawingAttributesPropertyEditor"); - - list.put(initPropertiesProperty, shapeFileProperty + " " + " " + pointImageURLProperty - + " " + dummyMarker + " " - + AddToBeanContextProperty + " " + MinScaleProperty + " " + MaxScaleProperty); - - PropUtils.setI18NPropertyInfo(i18n, list, ShapeLayer.class, shapeFileProperty, shapeFileProperty, "Location of Shape file - .shp (File, CURL or relative file path).", "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, ShapeLayer.class, pointImageURLProperty, pointImageURLProperty, "Image file to use for map location of point data (optional).", "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - return list; - } - - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - public String getInfoText(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.INFOLINE); - } - - /** - * If applicable, should return a tool tip for the OMGraphic. Return null if - * nothing should be shown. - */ - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - /** - * Create the OMGraphics using the shape file and SpatialIndex. - * - * @return OMGraphicList - * @deprecated use prepare() instead. - */ - protected OMGraphicList computeGraphics() { - return prepare(); - } - - /** - * Create the OMGraphics using the shape file and SpatialIndex. - * - * @return OMGraphicList - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - boolean DEBUG_FINE = logger.isLoggable(Level.FINE); - - if (projection == null) { - if (DEBUG_FINE) { - logger.fine(getName() + ": prepare called with null projection"); - } - return new OMGraphicList(); - } - - if (spatialIndex == null) { - if (DEBUG_FINE) { - logger.fine(getName() + ": spatialIndex is null!"); - } - - OMGraphicList list = getList(); - if (list != null) { - list.generate(projection, true);// all new graphics - return list; - } else { - // What we'd really like to do is make this a buffered layer at - // this point, if we can't find an ssx file and can't create - // one. - return new OMGraphicList(); - } - } - - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - double ulLat = ul.getY(); - double ulLon = ul.getX(); - double lrLat = lr.getY(); - double lrLon = lr.getX(); - - OMGraphicList list = new OMGraphicList(); - - // check for date line anomaly on the screen. we check for - // ulLon >= lrLon, but we need to be careful of the check for - // equality because of floating point arguments... - if (ProjMath.isCrossingDateline(ulLon, lrLon, projection.getScale())) { - if (DEBUG_FINE) { - logger.fine("ShapeLayer.computeGraphics(): Dateline is on screen"); - } - - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - - try { - - list = spatialIndex.getOMGraphics(ulLon, ymin, 180.0d, ymax, list, drawingAttributes, projection, coordTransform); - list = spatialIndex.getOMGraphics(-180.0d, ymin, lrLon, ymax, list, drawingAttributes, projection, coordTransform); - - } catch (InterruptedIOException iioe) { - // This means that the thread has been interrupted, - // probably due to a projection change. Not a big - // deal, just return, don't do any more work, and let - // the next thread solve all problems. - list = null; - } catch (IOException ex) { - if (DEBUG_FINE) { - ex.printStackTrace(); - } - } catch (FormatException fe) { - if (DEBUG_FINE) { - fe.printStackTrace(); - } - } catch (NullPointerException npe) { - // Have seen a NPE as a timing issue on startup that resolves - // itself quickly - the shp file is null - if (DEBUG_FINE) { - npe.printStackTrace(); - } - } - } else { - - double xmin = Math.min(ulLon, lrLon); - double xmax = Math.max(ulLon, lrLon); - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - - try { - list = spatialIndex.getOMGraphics(xmin, ymin, xmax, ymax, list, drawingAttributes, projection, coordTransform); - } catch (InterruptedIOException iioe) { - // This means that the thread has been interrupted, - // probably due to a projection change. Not a big - // deal, just return, don't do any more work, and let - // the next thread solve all problems. - list = null; - } catch (java.io.IOException ex) { - if (DEBUG_FINE) { - ex.printStackTrace(); - } - } catch (FormatException fe) { - if (DEBUG_FINE) { - fe.printStackTrace(); - } - } catch (NullPointerException npe) { - // Have seen a NPE as a timing issue on startup that resolves - // itself quickly - the shp file is null - if (DEBUG_FINE) { - npe.printStackTrace(); - } - } - } - - return list; - } - - protected transient JPanel box; - - public Component getGUI() { - - if (box == null) { - - box = new JPanel(); - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setAlignmentX(Component.LEFT_ALIGNMENT); - - JPanel stuff = new JPanel(); - JLabel label = new JLabel(i18n.get(ShapeLayer.class, "rendering_attributes", "Rendering Attributes: ")); - stuff.add(label); - // stuff.setLayout(new BoxLayout(stuff, - // BoxLayout.X_AXIS)); - // stuff.setAlignmentX(Component.LEFT_ALIGNMENT); - - DrawingAttributes da = getDrawingAttributes(); - if (da != null) { - stuff.add(da.getGUI()); - } - box.add(stuff); - - JPanel pal2 = new JPanel(); - JButton redraw = new JButton(i18n.get(ShapeLayer.class, "redrawLayerButton", "Redraw Layer")); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - pal2.add(redraw); - - box.add(pal2); - - } - return box; - } - - /** - * DataBoundsInformer interface. - */ - public DataBounds getDataBounds() { - DataBounds box = null; - if (spatialIndex != null) { - ESRIBoundingBox bounds = spatialIndex.getBounds(); - if (bounds != null) { - box = new DataBounds(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y); - } - } - return box; - } - - /** - * Called when the Layer is removed from the MapBean, giving an opportunity - * to clean up. - */ - public void removed(Container cont) { - OMGraphicList list = getList(); - if (list != null) { - list.clear(); - list = null; - } - - if (spatialIndex != null) { - spatialIndex.close(true); - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeRibbonLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeRibbonLayer.java deleted file mode 100644 index 3168f38a4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/ShapeRibbonLayer.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * 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 com.bbn.openmap.layer.shape; - -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Area; -import java.awt.geom.GeneralPath; -import java.io.File; -import java.net.MalformedURLException; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.dataAccess.shape.EsriPolygon; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMShape; -import com.bbn.openmap.omGraphics.util.RibbonMaker; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that displays outlines of a shapefile, extended or shrunk by - * some amount ["ribbon"]. You can tell it which specific shape you want in a - * shapefile with dbfcolumnchoice and defaultdbfcolumnvalue or includeAllShapes - * to avoid filtering. The gui for the layer is populated with values from the - * requested DBF column. - * - *

- *
- * ############################
- * # Example Properties for a shape ribbon layer, using political boundaries
- * # Common properties for all layers
- * shapeRibbonLayer.class=com.bbn.openmap.layer.shape.ShapeRibbonLayer
- * shapeRibbonLayer.prettyName=Country Ribbons
- * 
- * # Properties for configuring shape and layer choices
- * # Assumes that .shp is accompanied by .dbf and .ssx files
- * shapeRibbonLayer.shapeFile=data/shape/cntry02/cntry02.shp
- * shapeRibbonLayer.dbfColumnChoice=CNTRY_NAME
- * shapeRibbonLayer.defaultdbfColumnValue=United States
- * # Be warned that on big complex sets of shapes, this can take a while
- * includeAllShapes=false
- * 
- * # Properties for editing the ribbon itself
- * shapeRibbonLayer.rangeunits=km
- * shapeRibbonLayer.range=100
- * shapeRibbonLayer.lineColor=0000ff
- * shapeRibbonLayer.fillColor=330000ff
- * shapeRibbonLayer.fillRibbon=true
- * # If a filled color is set, this can remove the shape itself from the filled area
- * shapeRibbonLayer.removeShapeFromFill=true
- *
- * ############################
- * 
- * 
- * - * @author Gary Briggs - */ -public class ShapeRibbonLayer extends OMGraphicHandlerLayer { - - // Use EsriLayer to do all the legwork loading files for us - EsriLayer esriLayer = null; - - Double rangeRadians = Length.KM.toRadians(100.0); - boolean removeShapeFromFill = true; - boolean fillRibbon = true; - String shapeFile = "data/shape/cntry02/cntry02.shp"; - String dbfColumnChoice = "CNTRY_NAME"; - String chosenColumnName = "United States"; - Boolean includeAllShapes = false; - Length units = Length.KM; - DrawingAttributes da = null; - - // Numerical range from the shape - public final static String rangePropertyProperty = "range"; - public final static String rangeUnitsProperty = "rangeunits"; - public final static String shapeFileProperty = "shapeFile"; - public final static String removeShapeFromFillProperty = "removeShapeFromFill"; - public final static String fillRibbonProperty = "fillRibbon"; - public final static String chosendbfColumnNameProperty = "defaultdbfColumnValue"; - public final static String dbfColumnChoiceProperty = "dbfColumnChoice"; - public final static String includeAllShapesProperty = "includeAllShapes"; - - @Override - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - - String lengthUnitProp = props.getProperty(realPrefix + rangeUnitsProperty, units.getAbbr()); - Length testLengthUnit = Length.get(lengthUnitProp); - if (null != testLengthUnit) { - units = testLengthUnit; - } - - shapeFile = props.getProperty(realPrefix + shapeFileProperty, shapeFile); - dbfColumnChoice = props.getProperty(realPrefix + dbfColumnChoiceProperty, dbfColumnChoice); - chosenColumnName = props.getProperty(realPrefix + chosendbfColumnNameProperty, chosenColumnName); - - double originalRangeValue = PropUtils.doubleFromProperties(props, realPrefix + rangePropertyProperty, - units.fromRadians(rangeRadians)); - rangeRadians = units.toRadians(originalRangeValue); - - removeShapeFromFill = PropUtils.booleanFromProperties(props, realPrefix + removeShapeFromFillProperty, - removeShapeFromFill); - includeAllShapes = PropUtils.booleanFromProperties(props, realPrefix + includeAllShapesProperty, - includeAllShapes); - fillRibbon = PropUtils.booleanFromProperties(props, realPrefix + fillRibbonProperty, fillRibbon); - - da = new DrawingAttributes(realPrefix, props); - loadEsriData(); - } - - /** - * Create the esriLayer object. Assume that .shp is accompanied by .dbf and - * .shx files - */ - private void loadEsriData() { - - String prefix = shapeFile.replaceAll(".shp$", ""); - File dbf = new File(prefix.concat(".dbf")); - File shp = new File(prefix.concat(".shp")); - File shx = new File(prefix.concat(".shx")); - String name = shp.getName(); - - try { - esriLayer = new EsriLayer(name, dbf.toURI().toURL(), shp.toURI().toURL(), shx.toURI().toURL()); - } catch (MalformedURLException ex) { - Logger.getLogger(ShapeRibbonLayer.class.getName()).log(Level.SEVERE, null, ex); - } - - } - - @Override - public Component getGUI() { - JPanel guiPanel = new JPanel(new GridLayout(0, 2)); - if (null == esriLayer) { - guiPanel.add(new JLabel("No data loaded")); - return guiPanel; - } - - guiPanel.add(new JLabel(String.format("Choose Range (%s)", units.getAbbr()))); - final JSpinner rangeSpinner = new JSpinner( - new SpinnerNumberModel(units.fromRadians(rangeRadians), -1000.0, 1000.0, 100.0)); - guiPanel.add(rangeSpinner); - - DbfTableModel model = esriLayer.getModel(); - - int columnIndexForName = model.getColumnIndexForName(dbfColumnChoice); - String[] knownValues = new String[model.getRowCount()]; - for (int i = 0; i < model.getRowCount(); i++) { - List record = model.getRecord(i); - String value = (String) record.get(columnIndexForName); - knownValues[i] = value; - } - Arrays.sort(knownValues); - int chosenidx = Arrays.binarySearch(knownValues, chosenColumnName); - - final JComboBox combo = new JComboBox(knownValues); - combo.setSelectedIndex(chosenidx); - guiPanel.add(new JLabel("Choose a shape:")); - guiPanel.add(combo); - - guiPanel.add(new JLabel("Fill Ribbon")); - final JCheckBox fillRibbonCheck = new JCheckBox("", fillRibbon); - guiPanel.add(fillRibbonCheck); - - guiPanel.add(new JLabel("Remove Shape From Fill")); - final JCheckBox removeShapeFromFillCheck = new JCheckBox("", removeShapeFromFill); - guiPanel.add(removeShapeFromFillCheck); - - guiPanel.add(new JLabel("Include All Shapes")); - final JCheckBox includeAllShapesCheck = new JCheckBox("", includeAllShapes); - guiPanel.add(includeAllShapesCheck); - - // Set up listeners so the gui elements update the screen automatically - ActionListener actionListener = new ActionListener() { - public void actionPerformed(ActionEvent e) { - chosenColumnName = (String) combo.getSelectedItem(); - fillRibbon = fillRibbonCheck.isSelected(); - removeShapeFromFill = removeShapeFromFillCheck.isSelected(); - includeAllShapes = includeAllShapesCheck.isSelected(); - doPrepare(); - } - }; - ChangeListener changeListener = new ChangeListener() { - public void stateChanged(ChangeEvent e) { - Double val = (Double) rangeSpinner.getValue(); - rangeRadians = units.toRadians(val); - doPrepare(); - } - }; - rangeSpinner.addChangeListener(changeListener); - fillRibbonCheck.addActionListener(actionListener); - includeAllShapesCheck.addActionListener(actionListener); - removeShapeFromFillCheck.addActionListener(actionListener); - combo.addActionListener(actionListener); - return guiPanel; - } - - /** - * Pass a distRadians of zero to generate an Area - * - * @param g - * @param distRadians - * @return - */ - public Area createAreaFromEsri(OMGraphic g, double distRadians) { - Area a = new Area(); - if (g instanceof EsriGraphicList) { - // Recurse if necessary - EsriGraphicList esriList = (EsriGraphicList) g; - for (OMGraphic omg : esriList) { - a.add(createAreaFromEsri(omg, distRadians)); - } - } else if (g instanceof EsriPolygon) { - EsriPolygon esriGraphic = (EsriPolygon) g; - double epsilon = 4.778825E-10; // Borrowed from ribbonmaker - - if (Math.abs(distRadians) <= epsilon) { - esriGraphic.generate(getProjection()); - GeneralPath shape = esriGraphic.getShape(); - Area oneArea = new Area(shape); - a.add(oneArea); - } else { - double[] ll_arr = esriGraphic.getLatLonArray(); - // Wind the array backwards for negative values. This costs no - // extra memory - if (distRadians < 0) { - distRadians = -distRadians; - // Flip the poly so it winds the other way - final int numPoints = ll_arr.length / 2; - for (int i = 0; i < numPoints / 2; i++) { - double tmplat = ll_arr[2 * i]; - double tmplon = ll_arr[2 * i + 1]; - ll_arr[2 * i] = ll_arr[2 * (numPoints - i - 1)]; - ll_arr[2 * i + 1] = ll_arr[2 * (numPoints - i - 1) + 1]; - ll_arr[2 * (numPoints - i - 1)] = tmplat; - ll_arr[2 * (numPoints - i - 1) + 1] = tmplon; - } - } - final RibbonMaker ribbon = RibbonMaker.createFromRadians(ll_arr); - OMAreaList outerRing = ribbon.getOuterRing(distRadians); - outerRing.generate(getProjection()); - final GeneralPath oneRingShape = outerRing.getShape(); - if (null != oneRingShape) { - a.add(new Area(oneRingShape)); - } - } - } - return a; - } - - @Override - public synchronized OMGraphicList prepare() { - OMGraphicList l = new OMGraphicList(); - if (null == esriLayer) { - // Don't actually have any data - return l; - } - - Area a = null; - - DbfTableModel model = esriLayer.getModel(); - if (includeAllShapes) { - a = new Area(); - for (int i = 0; i < model.getRowCount(); i++) { - System.out.println(String.format("%d/%d", i, model.getRowCount())); - a.add(getOneRibbonedAreaFromShapeFile(i)); - } - } else { - // Find the row index we need in the shape data - int columnIndexForName = model.getColumnIndexForName(dbfColumnChoice); - int rownum = -1; - for (int row = 0; row < model.getRowCount(); row++) { - Object valueAt = model.getValueAt(row, columnIndexForName); - if (valueAt.equals(chosenColumnName)) { - rownum = row; - break; - } - } - - // Assuming we found it... - if (rownum >= 0) { - a = getOneRibbonedAreaFromShapeFile(rownum); - } - } - l.add(new OMShape.PROJECTED(a)); - if (fillRibbon) { - l.setFillPaint(da.getFillPaint()); - } - l.setLinePaint(da.getLinePaint()); - - return l; - } - - /** - * From the esri layer, create an Area using the current settings - * - * @param rownum - * @return - */ - private Area getOneRibbonedAreaFromShapeFile(int rownum) { - OMGraphic sourceGraphic = esriLayer.getEsriGraphicList().get(rownum); - - // Create the graphics representing the ribbon - Area ribbonArea = createAreaFromEsri(sourceGraphic, rangeRadians); - - if (null != ribbonArea) { - if (removeShapeFromFill || rangeRadians < 0) { - Area countryArea = createAreaFromEsri(sourceGraphic, 0.0); - if (rangeRadians > 0) { - ribbonArea.subtract(countryArea); - } else { - // If the ribbon is inside, always subtract the ribbon from - // the shape - countryArea.subtract(ribbonArea); - ribbonArea = countryArea; - } - } - } - return ribbonArea; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndex.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndex.java deleted file mode 100644 index dac6af025..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndex.java +++ /dev/null @@ -1,1657 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/SpatialIndex.java,v $ -// $RCSfile: SpatialIndex.java,v $ -// $Revision: 1.19 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.awt.geom.Point2D; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.dataAccess.shape.DbfHandler; -import com.bbn.openmap.dataAccess.shape.EsriGraphicFactory; -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * A Spatial Index is a variation on a Shape Index, adding the bounding box of - * the shape to the index. - *

- * The file has a 100 byte header identical to a Shape Index followed by n - * records. - * - * Usage - *

- * 
- * Dumps spatial index information, excluding bounding boxes to stdout.
- * Useful for comparing to a shape index.
- * java com.bbn.openmap.layer.shape.SpatialIndex -d file.ssx
- *
- * Dumps spatial index information including bounding boxes to stdout.
- * java com.bbn.openmap.layer.shape.SpatialIndex -d -b file.ssx
- *
- * Creates spatial index file.ssx from shape file.shp
- * java com.bbn.openmap.layer.shape.SpatialIndex -c file.shp
- * 
- * 
- * - * Notes

- * When reading the Shape file, the content length is the length of the record's - * contents, exclusive of the record header (8 bytes). So the size that we need - * to read in from the Shape file is actually denoted as ((contentLength * 2) + - * 8). This converts from 16bit units to 8 bit bytes and adds the 8 bytes for - * the record header. - * - * @author Tom Mitchell - * @version $Revision: 1.19 $ $Date: 2009/02/25 22:34:04 $ - * @see ShapeIndex - */ -public class SpatialIndex extends ShapeUtils { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.shape.SpatialIndex"); - - /** Size of a shape file header in bytes. */ - public final static int SHAPE_FILE_HEADER_LENGTH = 100; - - /** Size of a shape file record header in bytes. */ - public final static int SHAPE_RECORD_HEADER_LENGTH = 8; - - /** Size of the spatial index header in bytes. */ - public final static int SPATIAL_INDEX_HEADER_LENGTH = 100; - - /** Size of the spatial index record in bytes. */ - public final static int SPATIAL_INDEX_RECORD_LENGTH = 40; - - /** Default size for shape record buffer. */ - public final static int DEFAULT_SHAPE_RECORD_SIZE = 50000; - - /** The shape file. */ - protected BinaryFile shp; - - /** - * The handler for dbf file information. - */ - protected DbfHandler dbf; - - /** The icon to use for point objects. */ - protected ImageIcon pointIcon; - - /** The bounds of all the shapes in the shape file. */ - protected ESRIBoundingBox bounds = null; - - /** - * The file name for the shape file, for opening/reopening. - */ - protected String shpFileName; - - /** - * A cached list of the SpatialIndex file entries, for repeated reference. - */ - protected List entries; - - /** - * A factory object to use to create OMGraphics from the shp file. - */ - EsriGraphicFactory factory = new EsriGraphicFactory(); - - /** - * Opens a spatial index file for reading based on the location of the - * provided shp file. - * - * @param shpFilename the name of the spatial index file - * @exception IOException if something goes wrong opening the file - */ - public SpatialIndex(String shpFilename) throws IOException { - this.shpFileName = shpFilename; - if (logger.isLoggable(Level.FINE)) { - logger.fine("SpatialIndex(" + shpFilename + ");"); - } - } - - /** - * Opens a spatial index file and it's associated shape file. - * - * @param ssxFilename the name of the spatial index file - * @param shpFilename the name of the shape file - * @exception IOException if something goes wrong opening the files - * @deprecated ssx file is figured based on the shp file path - */ - public SpatialIndex(String ssxFilename, String shpFilename) throws IOException { - this(shpFilename); - } - - /** - * Figures out the ssx file name from the shp file name. - * - * @param shpFileName - * @return ssx file name from shape file name - */ - public static String ssx(String shpFileName) { - String ret = null; - if (shpFileName != null) { - ret = shpFileName.substring(0, shpFileName.indexOf(".shp")) + ".ssx"; - } - return ret; - } - - /** - * Figures out the dbf file name from the shp file name. - * - * @param shpFileName - * @return dbf file name created from shp file name. - */ - public static String dbf(String shpFileName) { - String ret = null; - if (shpFileName != null) { - ret = shpFileName.substring(0, shpFileName.indexOf(".shp")) + ".dbf"; - } - return ret; - } - - /** - * Get the box boundary containing all the shapes. - */ - public ESRIBoundingBox getBounds() { - return getBounds(null); - } - - /** - * Method that can be overridden to adjust how the BinaryFile is created for - * shp files. - * - * @param shapeFileName The path to shape file, absolute, relative or URL - * @return BinaryFile - * @throws IOException if the shapeFileName can't be found. - */ - protected synchronized BinaryFile getShpFile(String shapeFileName) throws IOException { - return new BinaryBufferedFile(shapeFileName); - } - - /** - * Returns the bounds of the shape file. If bounds don't exist, they are - * read from the shape file header. - * - * @param coordTransform - * @return null if bounds can't been read, otherwise ESRIBoundingBox. - */ - public ESRIBoundingBox getBounds(GeoCoordTransformation coordTransform) { - if (bounds == null) { - try { - if (shpFileName != null) { - BinaryFile shpFile = getShpFile(shpFileName); - EsriGraphicFactory.Header header = new EsriGraphicFactory.Header(shpFile, coordTransform); - DataBounds dataBounds = header.getDataBounds(); - if (dataBounds != null) { - Point2D min = dataBounds.getMin(); - Point2D max = dataBounds.getMax(); - bounds = new ESRIBoundingBox(min.getX(), min.getY()); - bounds.addPoint(max.getX(), max.getY()); - } - shpFile.close(); - } - } catch (IOException ioe) { - bounds = null; - } catch (FormatException fe) { - bounds = null; - } - } - return bounds; - } - - /** - * Reset the bounds so they will be recalculated the next time a file is - * read. - */ - public void resetBounds() { - bounds = null; - } - - /** - * Creates a record instance from the shape file data. Calls the appropriate - * record constructor based on the shapeType, and passes the buffer and - * offset to that constructor. - * - * @param shapeType the shape file's shape type, enumerated in - * ShapeUtils - * @param b the buffer pointing to the raw record data - * @param off the offset of the data starting point in the buffer - * @exception IOException if something goes wrong reading the file - * @see ShapeUtils - */ - public ESRIRecord makeESRIRecord(int shapeType, byte[] b, int off) throws IOException { - switch (shapeType) { - case SHAPE_TYPE_NULL: - return null; - case SHAPE_TYPE_POINT: - // return new ESRIPointRecord(b, off); - return new ESRIPointRecord(b, off, pointIcon); - case SHAPE_TYPE_POLYGON: - case SHAPE_TYPE_ARC: - // case SHAPE_TYPE_POLYLINE: - return new ESRIPolygonRecord(b, off); - case SHAPE_TYPE_MULTIPOINT: - logger.fine("SpatialIndex.makeESRIRecord: Arc NYI"); - return null; - // return new ESRIMultipointRecord(b, off); - default: - return null; - } - } - - /** - * Locates records in the shape file that intersect with the given - * rectangle. The spatial index is searched for intersections and the - * appropriate records are read from the shape file. Not really used - * anymore, except for old code. Use EsriGraphicList or EsriGraphicFactory - * instead. - * - * @param xmin the smaller of the x coordinates - * @param ymin the smaller of the y coordinates - * @param xmax the larger of the x coordinates - * @param ymax the larger of the y coordinates - * @return an array of records that intersect the given rectangle - * @exception IOException if something goes wrong reading the files - */ - public ESRIRecord[] locateRecords(double xmin, double ymin, double xmax, double ymax) - throws IOException, FormatException { - - boolean gatherBounds = false; - - if (bounds == null) { - bounds = new ESRIBoundingBox(); - gatherBounds = true; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("locateRecords:\n\txmin: " + xmin + "; ymin: " + ymin + "\n\txmax: " + xmax - + "; ymax: " + ymax); - } - - byte ixRecord[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - int recNum = 0; - Vector v = new Vector(); - int sRecordSize = DEFAULT_SHAPE_RECORD_SIZE; - byte sRecord[] = new byte[sRecordSize]; - - if (shpFileName == null) { - return null; - } - - BinaryBufferedFile ssx = new BinaryBufferedFile(ssx(shpFileName)); - if (shp == null) { - shp = getShpFile(shpFileName); - } - - // Need to figure out what the shape type is... - ssx.seek(32); - - // int shapeType = readLEInt(ssx); - // / - ssx.byteOrder(false); - int shapeType = ssx.readInteger(); - // / - ssx.seek(100); // skip the file header - - while (true) { - int result = ssx.read(ixRecord, 0, SPATIAL_INDEX_RECORD_LENGTH); - // if (result == -1) { - if (result <= 0) { - break;// EOF - } else { - recNum++; - double xmin2 = readLEDouble(ixRecord, 8); - double ymin2 = readLEDouble(ixRecord, 16); - double xmax2 = readLEDouble(ixRecord, 24); - double ymax2 = readLEDouble(ixRecord, 32); - if (logger.isLoggable(Level.FINER)) { - logger.finer("Looking at rec num " + recNum); - logger.finer(" " + xmin2 + ", " + ymin2 + "\n " + xmax2 + ", " + ymax2); - } - - if (gatherBounds) { - bounds.addPoint(xmin2, ymin2); - bounds.addPoint(xmax2, ymax2); - } - - if (intersects(xmin, ymin, xmax, ymax, xmin2, ymin2, xmax2, ymax2)) { - - int offset = readBEInt(ixRecord, 0); - int byteOffset = offset * 2; - int contentLength = readBEInt(ixRecord, 4); - int recordSize = (contentLength * 2) + 8; - // System.out.print("."); - // System.out.flush(); - - if (recordSize < 0) { - logger.warning("SpatialIndex: supposed to read record size of " - + recordSize); - break; - } - - if (recordSize > sRecordSize) { - sRecordSize = recordSize; - if (logger.isLoggable(Level.FINER)) { - logger.finer("Shapefile SpatialIndex record size: " + sRecordSize); - } - sRecord = new byte[sRecordSize]; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("going to shp byteOffset = " + byteOffset - + " for record size = " + recordSize + ", offset = " + offset - + ", shape type = " + shapeType); - } - - try { - shp.seek(byteOffset); - int nBytes = shp.read(sRecord, 0, recordSize); - if (nBytes < recordSize) { - logger.warning("Shapefile SpatialIndex expected " + recordSize - + " bytes, but got " + nBytes + " bytes instead."); - } - - ESRIRecord record = makeESRIRecord(shapeType, sRecord, 0); - v.addElement(record); - } catch (IOException ioe) { - logger.warning("SpatialIndex.locateRecords: IOException. "); - ioe.printStackTrace(); - break; - } - } - } - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Processed " + recNum + " records"); - logger.fine("Selected " + v.size() + " records"); - } - int nRecords = v.size(); - - ssx.close(); - shp.close(); - shp = null; - ESRIRecord result[] = new ESRIRecord[nRecords]; - v.copyInto(result); - return result; - - } - - /** - * The factory is used to filter and create OMGraphics from a shape file. - * This accessor is provided in order to allow you to modify the data - * projection it uses, or the line type. - * - * @return EsriGraphicFactory being used to create EsriGraphics from shape - * file. - */ - public EsriGraphicFactory getFactory() { - if (factory == null) { - factory = new EsriGraphicFactory(); - // You can set this in the ShapeLayer if you want, replacing - // DrawingAttributes with GraphicAttributes with a LINETYPE set. - - // factory.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - return factory; - } - - public void setFactory(EsriGraphicFactory factory) { - this.factory = factory; - } - - /** - * Locates OMGraphics in the shape file that intersect with the given - * rectangle. The spatial index is searched for intersections and the - * appropriate OMGraphics are created from the shape file. - * - * @param xmin the smaller of the x coordinates - * @param ymin the smaller of the y coordinates - * @param xmax the larger of the x coordinates - * @param ymax the larger of the y coordinates - * @param list OMGraphicList to add OMGraphics to and return, if null one - * will be created. - * @param drawingAttributes DrawingAttributes to set on the OMGraphics. - * @param mapProj the Map Projection for the OMGraphics so they can be - * generated right after creation. - * @param dataProj for pre-projected data, a coordinate translator for the - * data's projection to use to translate the coordinates to decimal - * degree lat/lon. Can be null to leave the coordinates untouched. - * @return an OMGraphicList containing OMGraphics that intersect the given - * rectangle - * @exception IOException if something goes wrong reading the files - */ - public OMGraphicList getOMGraphics(double xmin, double ymin, double xmax, double ymax, - OMGraphicList list, DrawingAttributes drawingAttributes, - Projection mapProj, GeoCoordTransformation dataProj) - throws IOException, FormatException { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("locateRecords:\n\txmin: " + xmin + "; ymin: " + ymin + "\n\txmax: " + xmax - + "; ymax: " + ymax); - } - - if (list == null) { - list = new OMGraphicList(); - } - - BinaryFile shpFile = shp; - DbfHandler dbfFile = dbf; - - if (shpFile == null) { - shp = getShpFile(shpFileName); - shpFile = shp; - } - - if (shpFile == null) { - return list; - } - - EsriGraphicFactory.ReadByteTracker byteTracker = new EsriGraphicFactory.ReadByteTracker(); - EsriGraphicFactory factory = getFactory(); - factory.setDataCoordTransformation(dataProj); - - OMGraphicList labels = new OMGraphicList(); - list.add(labels); - - for (Iterator it = entryIterator(dataProj); it.hasNext();) { - Entry entry = (Entry) it.next(); - - if (entry.intersects(xmin, ymin, xmax, ymax)) { - - try { - - OMGraphic omg = (OMGraphic) factory.makeEsriGraphicFromRecord(entry.getByteOffset(), shpFile, drawingAttributes, pointIcon, byteTracker); - - if (omg != null) { - - if (dbfFile != null) { - omg = dbfFile.evaluate(omg, labels, mapProj); - - if (omg == null) { - // Failed dbf test, should be ignored. - continue; - } - } - - if (mapProj != null) { - omg.generate(mapProj); - } - list.add(omg); - } - - } catch (IOException ioe) { - logger.warning("IOException message: " + ioe.getMessage()); - ioe.printStackTrace(); - break; - } - } - } - - if (shpFile != null) { - shpFile.close(); - // Not sure why we want to set this null here. It's cleaner, but a - // new - // BinaryFile object is created for every projection change. - // shp = null; - } - - if (dbfFile != null) { - dbfFile.close(); - } - - return list; - - } - - /** - * Retrieves all OMGraphics in the shape file. - * - * @param retList OMGraphicList to add OMGraphics to and return, if null one - * will be created. - * @param drawingAttributes DrawingAttributes to set on the OMGraphics. - * @param mapProj the Map Projection for the OMGraphics so they can be - * generated right after creation. This will also be used by the - * DbfHandler, to determine if some OMGraphics should not be returned - * based on attribute settings. - * @param dataProj for preprojected data, a coordinate translator for the - * data's projection to use to translate the coordinates to decimal - * degree lat/lon. Can be null to leave the coordinates untouched. - * @return an OMGraphicList containing OMGraphics that intersect the given - * rectangle - * @exception IOException if something goes wrong reading the files - */ - public OMGraphicList getAllOMGraphics(OMGraphicList retList, - DrawingAttributes drawingAttributes, Projection mapProj, - GeoCoordTransformation dataProj) - throws IOException, FormatException { - - if (retList == null) { - retList = new OMGraphicList(); - } - - if (shp == null) { - shp = getShpFile(shpFileName); - } - - if (shp == null) { - return retList; - } - - EsriGraphicFactory factory = getFactory(); - factory.setDataCoordTransformation(dataProj); - factory.getEsriGraphics(shp, drawingAttributes, pointIcon, mapProj, retList); - - shp.close(); - - return retList; - } - - /** - * Takes the contents of the list and evaluates them against the information - * contained in the DbfHandler set in this SpatialIndex class. - * - * @param retList the list of OMGraphics to evaluate. - * @param mapProj the current map projection to be used by the DbfHandler to - * determine if some OMGraphics should be visible. - * @return OMGraphicList containing OMGraphics modified/passing evaluations - * rules in the DbfHandler. - */ - public OMGraphicList evaluateDbf(OMGraphicList retList, Projection mapProj) { - - if (dbf != null) { - OMGraphicList labels = new OMGraphicList(); - retList.add(labels); - - OMGraphicList testList = new OMGraphicList(); - for (OMGraphic omg : retList) { - - if (omg != null) { - - omg = dbf.evaluate(omg, labels, mapProj); - - if (mapProj != null) { - omg.generate(mapProj); - } - testList.add(omg); - } - } - retList = testList; - } - - return retList; - } - - /** - * Evaluates the OMGraphic against the DbfHandler rules. - * - * @param omg the OMGraphic to evaluate. - * @param labels for DbfHandler label rules. Assumes that you are managing - * display of the labels list. - * @param mapProj for DbfHandler scale rules. - * @return OMGraphic if it passes the rules. - */ - public OMGraphic evaluate(OMGraphic omg, OMGraphicList labels, Projection mapProj) { - if (dbf != null) { - omg = dbf.evaluate(omg, labels, mapProj); - } - - return omg; - } - - /** - * Skips the BinaryFile for the shp data to the offset and reads the record - * data there, creating an OMGraphic from that data. - * - * @param byteOffset , usually gotten from an Entry object. - * @param drawingAttributes - * @return OMGraphic from entry object. - * @throws IOException - * @throws FormatException - */ - public OMGraphic getOMGraphicAtOffset(int byteOffset, DrawingAttributes drawingAttributes) - throws IOException, FormatException { - return (OMGraphic) getFactory().makeEsriGraphicFromRecord(byteOffset, shp, drawingAttributes, pointIcon, new EsriGraphicFactory.ReadByteTracker()); - } - - /** - * Provides an iterator over the SpatialIndex entries. - * - * @return iterator over entries - * @throws IOException - * @throws FormatException - */ - public Iterator entryIterator() throws IOException, FormatException { - return entryIterator(null); - } - - /** - * Provides an iterator over the SpatialIndex entries. - * - * @param dataTransform GeoCoordTransform for pre-projected data. - * @return iterator over entries, data transformed. - * @throws IOException - * @throws FormatException - */ - public Iterator entryIterator(GeoCoordTransformation dataTransform) - throws IOException, FormatException { - List entriesHandle = entries; - if (entriesHandle == null) { - boolean gatherBounds = false; - if (bounds == null) { - bounds = new ESRIBoundingBox(); - gatherBounds = true; - } - - entriesHandle = readIndexFile(gatherBounds ? bounds : null, dataTransform); - entries = entriesHandle; - } - - return new ArrayList(entriesHandle).iterator(); - } - - /** - * - * @param bounds if not null, add min/max values to them. - * @return list of entries. - * @throws IOException - * @throws FormatException - */ - protected List readIndexFile(ESRIBoundingBox bounds) throws IOException, FormatException { - return readIndexFile(bounds, null); - } - - /** - * - * @param bounds if not null, add min/max values to them. - * @param dataTransform GeoCoordTransform for pre-projected data. - * @return list of entries - * @throws IOException - * @throws FormatException - */ - protected List readIndexFile(ESRIBoundingBox bounds, GeoCoordTransformation dataTransform) - throws IOException, FormatException { - List entries = new ArrayList(); - - byte ixRecord[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - - if (shpFileName == null) { - return entries; - } - - String ssxFileName = ssx(shpFileName); - - if (!BinaryBufferedFile.exists(ssxFileName)) { - // If we got this far without an ssx existing, then we should just - // create one in memory. - return SpatialIndex.MemoryIndex.create(shpFileName); - } - - BinaryBufferedFile ssx = new BinaryBufferedFile(ssxFileName); - - ssx.byteOrder(false); - ssx.seek(100); // skip the file header - - LatLonPoint llp = null; - if (dataTransform != null) { - llp = new LatLonPoint.Double(); - } - - while (true) { - int result = ssx.read(ixRecord, 0, SPATIAL_INDEX_RECORD_LENGTH); - if (result <= 0) { - break;// EOF - } else { - double xmin = readLEDouble(ixRecord, 8); - double ymin = readLEDouble(ixRecord, 16); - double xmax = readLEDouble(ixRecord, 24); - double ymax = readLEDouble(ixRecord, 32); - int byteOffset = readBEInt(ixRecord, 0) * 2; - - if (dataTransform != null) { - llp = dataTransform.inverse(xmin, ymin, llp); - xmin = llp.getX(); - ymin = llp.getY(); - llp = dataTransform.inverse(xmax, ymax, llp); - xmax = llp.getX(); - ymax = llp.getY(); - } - - if (logger.isLoggable(Level.FINER)) { - logger.finer("entry:\t" + xmin + ", " + ymin + "\n\t" + xmax + ", " + ymax); - } - - Entry entry = new Entry(xmin, ymin, xmax, ymax, byteOffset); - entries.add(entry); - - if (bounds != null) { - bounds.addPoint(xmin, ymin); - bounds.addPoint(xmax, ymax); - } - } - } - - ssx.close(); - - return entries; - - } - - /** - * Determines if two rectangles intersect. Actually, this method determines - * if two rectangles don't intersect, and then returns a negation of that - * result. But the bottom line is the same. - * - * @param xmin1 the small x of rectangle 1 - * @param ymin1 the small y of rectangle 1 - * @param xmax1 the big x of rectangle 1 - * @param ymax1 the big y of rectangle 1 - * @param xmin2 the small x of rectangle 2 - * @param ymin2 the small y of rectangle 2 - * @param xmax2 the big x of rectangle 2 - * @param ymax2 the big y of rectangle 2 - * @return true if the rectangles intersect, false - * if they do not - */ - protected static final boolean intersects(double xmin1, double ymin1, double xmax1, - double ymax1, double xmin2, double ymin2, - double xmax2, double ymax2) { - return !((xmax1 <= xmin2) || (ymax1 <= ymin2) || (xmin1 >= xmax2) || (ymin1 >= ymax2)); - } - - /** - * Displays the contents of this index. - * - * @param showBounds true to show bounding box, false to skip it - * @exception IOException if something goes wrong reading the file - */ - public void dumpIndex(boolean showBounds) throws IOException { - byte ixRecord[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - int recNum = 0; - - if (shpFileName == null) { - return; - } - - BinaryBufferedFile ssx = new BinaryBufferedFile(ssx(shpFileName)); - ssx.seek(100); // skip the file header - while (true) { - int result = ssx.read(ixRecord, 0, SPATIAL_INDEX_RECORD_LENGTH); - // if (result == -1) { - if (result <= 0) { - logger.info("Processed " + recNum + " records"); - break;// EOF - } else { - recNum++; - int offset = readBEInt(ixRecord, 0); - int length = readBEInt(ixRecord, 4); - logger.info("Record " - + recNum - + ": " - + offset - + ", " - + length - + (showBounds ? ("; " + readLEDouble(ixRecord, 8) + ", " - + readLEDouble(ixRecord, 16) + ", " + readLEDouble(ixRecord, 24) - + ", " + readLEDouble(ixRecord, 32)) : "")); - } - } - ssx.close(); - } - - /** - * Prints a usage statement describing how to use this class from the - * command line. - * - * @param out The output stream to use for output - */ - public static void printUsage(PrintStream out) { - String className = SpatialIndex.class.getName(); - - out.println("Usage:"); - out.println(); - out.println("java " + className + " -c file.shp"); - out.println("Creates spatial index from " + "shape file ."); - out.println(); - out.println("java " + className + " -d file.shp"); - out.println("Dumps spatial index information, excluding " - + "bounding boxes to stdout. Useful for " + "comparing to a shape index."); - out.println(); - out.println("java " + className + " -d -b file.shp"); - out.println("Dumps spatial index information including " + "bounding boxes to stdout."); - out.println(); - } - - /** - * Locate file 'fileName' in classpath, if it is not an absolute file name. - * - * @return absolute name of the file as a string if found, null otherwise. - */ - public static String locateFile(String name) { - File file = new File(name); - if (file.exists()) { - return name; - } else { - java.net.URL url = ClassLoader.getSystemResource(name); - - // OK, now we want to look around for the file, in the - // classpaths, and as a resource. It may be a file in - // a classpath, available for direct access. - if (url != null) { - String newname = url.getFile(); - file = new File(newname); - if (file.exists()) { - return newname; - } - } - } - return null; - } - - /** - * Create a SpatialIndex object with just a shape file name. If the shape - * file is local, this method will attempt to build the spatial index file - * and place it next to the shape file. - */ - public static SpatialIndex locateAndSetShapeData(String shapeFileName) { - SpatialIndex spi = null; - - if (shapeFileName == null) { - return null; - } - - int appendixIndex = shapeFileName.indexOf(".shp"); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("created with just the shape file " + shapeFileName); - } - - if (appendixIndex != -1) { - - if (BinaryFile.exists(shapeFileName)) { - // OK, the shape files exists - now look for spatial - // index file next to it. - String spatialIndexFileName = ssx(shapeFileName); - - // Now, see if the spatialIndexFileName exists, and if - // not, create it. - if (logger.isLoggable(Level.FINE)) { - logger.fine("Trying to locate spatial index file " + spatialIndexFileName); - } - - try { - spi = new SpatialIndex(shapeFileName); - - } catch (java.io.IOException ioe) { - logger.warning(ioe.getMessage()); - ioe.printStackTrace(); - spi = null; - } - } else { - logger.warning("Couldn't locate shape file " + shapeFileName); - } - - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("file " + shapeFileName + " doesn't look like a shape file"); - } - } - - return spi; - } - - /** - * The driver for the command line interface. Reads the command line - * arguments and executes appropriate calls. - *

- * See the file documentation for usage. - * - * @param argv the command line arguments - * @exception IOException if something goes wrong reading or writing the - * file - */ - public static void main(String argv[]) throws IOException { - int argc = argv.length; - - if (argc == 0) { - // No arguments, give the user some help - printUsage(System.out); - System.exit(0); - } - - logger.setLevel(Level.FINER); - - if (argv[0].equals("-d")) { - if (argc == 2) { - String name = argv[1]; - SpatialIndex si = new SpatialIndex(name); - si.dumpIndex(false); - } else if ((argc == 3) && (argv[1].equals("-b"))) { - String name = argv[2]; - SpatialIndex si = new SpatialIndex(name); - si.dumpIndex(true); - } else { - printUsage(System.err); - System.exit(1); - } - } else if ((argc == 2) && argv[0].equals("-c")) { - String shapeFile = argv[1]; - SpatialIndex.FileIndex.create(shapeFile); - } else { - printUsage(System.err); - System.exit(1); - } - } - - /** - * Set the icon to use for point objects, in general. - * - * @param ii ImageIcon to use for icon. - */ - public synchronized void setPointIcon(ImageIcon ii) { - pointIcon = ii; - } - - /** - * Get the icon used for general point objects. - * - * @return ImageIcon, null if not set. - */ - public synchronized ImageIcon getPointIcon() { - return pointIcon; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.io.Closable#close(boolean) - */ - public boolean close(boolean done) { - try { - if (shp != null) { - shp.close(); - } - - if (done) { - shp = null; - } - - if (done && entries != null) { - entries.clear(); - entries = null; - } - - return true; - } catch (IOException ioe) { - - } - - return false; - } - - /** - * The spatial information for each shp entry is held in one of these. - * - * @author dietrick - */ - public static class Entry { - - double xMin; - double yMin; - double xMax; - double yMax; - int byteOffset; - - public Entry(double xMin, double yMin, double xMax, double yMax, int byteOffset) { - this.xMin = xMin; - this.yMin = yMin; - this.xMax = xMax; - this.yMax = yMax; - this.byteOffset = byteOffset; - } - - public boolean intersects(double xmin, double ymin, double xmax, double ymax) { - return SpatialIndex.intersects(xmin, ymin, xmax, ymax, xMin, yMin, xMax, yMax); - } - - public int getByteOffset() { - return byteOffset; - } - - public void addToBounds(ESRIBoundingBox bounds) { - bounds.addPoint(xMin, yMin); - bounds.addPoint(xMax, yMax); - } - - } - - public DbfHandler getDbf() { - return dbf; - } - - public void setDbf(DbfHandler dbf) { - this.dbf = dbf; - } - - public static class FileIndex { - - protected FileIndex() { - } - - public static void create(String shpFile) { - FileIndex fi = new FileIndex(); - fi.createIndex(shpFile); - } - - /** - * Writes the spatial index for a polygon shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param os the spatial index file output stream - */ - protected void indexPolygons(InputStream is, long ptr, OutputStream os) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - byte outBuf[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - int result; - int shapeType; - int nRecords = 0; - int recLengthWords, recLengthBytes /* , recNumber */; - long recOffset; - int recBufSize = 100000; - byte recBuf[] = new byte[recBufSize]; - ESRIBoundingBox polyBounds; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + nRecords + " records"); - logger.fine("recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - // Null shapes are allowed in any shape file, at any - // time. - shapeType = readLEInt(recBuf, 0); - if (shapeType != SHAPE_TYPE_NULL) { - polyBounds = readBox(recBuf, 4); - } else { - polyBounds = new ESRIBoundingBox(); - } - ptr += recLengthBytes + 8; - - writeBEInt(outBuf, 0, (int) (recOffset / 2)); - writeBEInt(outBuf, 4, recLengthWords); - writeLEDouble(outBuf, 8, polyBounds.min.x); - writeLEDouble(outBuf, 16, polyBounds.min.y); - writeLEDouble(outBuf, 24, polyBounds.max.x); - writeLEDouble(outBuf, 32, polyBounds.max.y); - os.write(outBuf, 0, SPATIAL_INDEX_RECORD_LENGTH); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Writes the spatial index for a point shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param os the spatial index file output stream - */ - protected void indexPoints(InputStream is, long ptr, OutputStream os) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - byte outBuf[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - int result; - int nRecords = 0; - int recLengthWords, recLengthBytes/* , recNumber */; - long recOffset; - int shapeType; - int recBufSize = 20; - byte recBuf[] = new byte[recBufSize]; - double x = 0; - double y = 0; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + nRecords + " records"); - logger.fine("recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - // Null shapes are allowed in any shape file, at any - // time. - shapeType = readLEInt(recBuf, 0); - if (shapeType != SHAPE_TYPE_NULL) { - x = readLEDouble(recBuf, 4); - y = readLEDouble(recBuf, 12); - } - ptr += recLengthBytes + 8; - - writeBEInt(outBuf, 0, (int) (recOffset / 2)); - writeBEInt(outBuf, 4, recLengthWords); - writeLEDouble(outBuf, 8, x); - writeLEDouble(outBuf, 16, y); - writeLEDouble(outBuf, 24, x); - writeLEDouble(outBuf, 32, y); - os.write(outBuf, 0, SPATIAL_INDEX_RECORD_LENGTH); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Writes the spatial index for a null shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param os the spatial index file output stream - */ - protected void indexNulls(InputStream is, long ptr, OutputStream os) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - byte outBuf[] = new byte[SPATIAL_INDEX_RECORD_LENGTH]; - int result; - int nRecords = 0; - int recLengthWords, recLengthBytes/* , recNumber */; - long recOffset; - int recBufSize = 20; - byte recBuf[] = new byte[recBufSize]; - double x; - double y; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + nRecords + " records"); - logger.fine("recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - x = 0; - y = 0; - ptr += recLengthBytes + 8; - - writeBEInt(outBuf, 0, (int) (recOffset / 2)); - writeBEInt(outBuf, 4, recLengthWords); - writeLEDouble(outBuf, 8, x); - writeLEDouble(outBuf, 16, y); - writeLEDouble(outBuf, 24, x); - writeLEDouble(outBuf, 32, y); - os.write(outBuf, 0, SPATIAL_INDEX_RECORD_LENGTH); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Creates a spatial index for a shape file. Reads the records from the - * shape file, writing appropriate index records to the spatial index - * file. - * - * @param inFile the shape file or spatial index file, the method will - * figure it out based on the file name extension. - */ - public void createIndex(String inFile) { - String ssxFile = null; - String shpFile = null; - if (inFile.endsWith(".shp")) { - shpFile = inFile; - ssxFile = ssx(shpFile); - } else if (inFile.endsWith(".ssx")) { - ssxFile = inFile; - shpFile = ssxFile.substring(0, ssxFile.indexOf(".ssx")) + ".shp"; - } else { - return; - } - - byte fileHeader[] = new byte[SHAPE_FILE_HEADER_LENGTH]; - FileInputStream shp = null; - FileOutputStream ssx = null; - int shapeType; - try { - shp = new FileInputStream(shpFile); - ssx = new FileOutputStream(ssxFile); - shp.read(fileHeader, 0, SHAPE_FILE_HEADER_LENGTH); - ssx.write(fileHeader, 0, SHAPE_FILE_HEADER_LENGTH); - shapeType = readLEInt(fileHeader, 32); - switch (shapeType) { - case SHAPE_TYPE_NULL: - indexNulls(shp, SHAPE_FILE_HEADER_LENGTH, ssx); - break; - case SHAPE_TYPE_POINT: - case SHAPE_TYPE_POINTZ: - case SHAPE_TYPE_POINTM: - indexPoints(shp, SHAPE_FILE_HEADER_LENGTH, ssx); - break; - case SHAPE_TYPE_MULTIPOINT: - case SHAPE_TYPE_MULTIPOINTZ: - case SHAPE_TYPE_MULTIPOINTM: - // case SHAPE_TYPE_ARC: - case SHAPE_TYPE_POLYLINE: - case SHAPE_TYPE_POLYLINEZ: - case SHAPE_TYPE_POLYLINEM: - case SHAPE_TYPE_POLYGON: - case SHAPE_TYPE_POLYGONZ: - case SHAPE_TYPE_POLYGONM: - indexPolygons(shp, SHAPE_FILE_HEADER_LENGTH, ssx); - break; - default: - logger.warning("Unknown shape type: " + shapeType); - } - - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - if (shp != null) - shp.close(); - if (ssx != null) - ssx.close(); - } catch (java.io.IOException e) { - } - } - } - } - - public static class MemoryIndex { - - protected MemoryIndex() { - } - - public static List create(String shpFile) { - MemoryIndex mi = new MemoryIndex(); - return mi.createIndex(shpFile); - } - - /** - * Writes the spatial index for a polygon shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param entries a List of Entries to add to - */ - protected void indexPolygons(InputStream is, long ptr, List entries) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - int result; - int shapeType; - int nRecords = 0; - int recLengthWords, recLengthBytes /* , recNumber */; - long recOffset; - int recBufSize = 100000; - byte recBuf[] = new byte[recBufSize]; - ESRIBoundingBox polyBounds; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex Found " + nRecords + " records"); - logger.fine("Shapefile SpatialIndex recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - // Null shapes are allowed in any shape file, at any - // time. - shapeType = readLEInt(recBuf, 0); - if (shapeType != SHAPE_TYPE_NULL) { - polyBounds = readBox(recBuf, 4); - } else { - polyBounds = new ESRIBoundingBox(); - } - ptr += recLengthBytes + 8; - - Entry entry = new Entry(polyBounds.min.x, polyBounds.min.y, polyBounds.max.x, polyBounds.max.y, (int) recOffset); - entries.add(entry); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Writes the spatial index for a point shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param entries a List of Entries to add to - */ - protected void indexPoints(InputStream is, long ptr, List entries) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - int result; - int nRecords = 0; - int recLengthWords, recLengthBytes/* , recNumber */; - long recOffset; - int shapeType; - int recBufSize = 20; - byte recBuf[] = new byte[recBufSize]; - double x = 0; - double y = 0; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + nRecords + " records"); - logger.fine("recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - // Null shapes are allowed in any shape file, at any - // time. - shapeType = readLEInt(recBuf, 0); - if (shapeType != SHAPE_TYPE_NULL) { - x = readLEDouble(recBuf, 4); - y = readLEDouble(recBuf, 12); - } - ptr += recLengthBytes + 8; - - Entry entry = new Entry(x, y, x, y, (int) recOffset); - entries.add(entry); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Writes the spatial index for a null shape file. - * - * @param is the shape file input stream - * @param ptr the current position in the file - * @param entries a List of Entries to add to - */ - protected void indexNulls(InputStream is, long ptr, List entries) { - boolean moreRecords = true; - byte rHdr[] = new byte[SHAPE_RECORD_HEADER_LENGTH]; - int result; - int nRecords = 0; - int recLengthWords, recLengthBytes/* , recNumber */; - long recOffset; - int recBufSize = 20; - byte recBuf[] = new byte[recBufSize]; - double x; - double y; - - try { - while (moreRecords) { - result = is.read(rHdr, 0, SHAPE_RECORD_HEADER_LENGTH); - if (result < 0) { - moreRecords = false; - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + nRecords + " records"); - logger.fine("recBufSize = " + recBufSize); - } - } else { - nRecords++; - recOffset = ptr; - /* recNumber = */readBEInt(rHdr, 0); - recLengthWords = readBEInt(rHdr, 4); - recLengthBytes = recLengthWords * 2; - - if (recLengthBytes > recBufSize) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Shapefile SpatialIndex increasing recBufSize to " - + recLengthBytes); - } - recBufSize = recLengthBytes; - recBuf = new byte[recBufSize]; - } - - result = is.read(recBuf, 0, recLengthBytes); - x = 0; - y = 0; - ptr += recLengthBytes + 8; - - Entry entry = new Entry(x, y, x, y, (int) recOffset); - entries.add(entry); - } - } - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (java.io.IOException e) { - } - } - } - - /** - * Creates a spatial index for a shape file. Reads the records from the - * shape file, writing appropriate index records to the spatial index - * file. - * - * @param inFile the shape file. - */ - public List createIndex(String inFile) { - String shpFile = null; - List entries = new ArrayList(); - if (inFile.endsWith(".shp")) { - shpFile = inFile; - } else { - logger.warning("can't create spatial index entries from non-shape file: " + inFile); - return entries; - } - - byte fileHeader[] = new byte[SHAPE_FILE_HEADER_LENGTH]; - BufferedInputStream shp = null; - int shapeType; - try { - URL shpURL = PropUtils.getResourceOrFileOrURL(shpFile); - if (shpURL == null) { - return entries; - } - if (logger.isLoggable(Level.FINE)) { - logger.fine("creating spatial index entries for " + inFile); - } - shp = new BufferedInputStream(shpURL.openStream()); - shp.read(fileHeader, 0, SHAPE_FILE_HEADER_LENGTH); - shapeType = readLEInt(fileHeader, 32); - switch (shapeType) { - case SHAPE_TYPE_NULL: - indexNulls(shp, SHAPE_FILE_HEADER_LENGTH, entries); - break; - case SHAPE_TYPE_POINT: - case SHAPE_TYPE_POINTZ: - case SHAPE_TYPE_POINTM: - indexPoints(shp, SHAPE_FILE_HEADER_LENGTH, entries); - break; - case SHAPE_TYPE_MULTIPOINT: - case SHAPE_TYPE_MULTIPOINTZ: - case SHAPE_TYPE_MULTIPOINTM: - // case SHAPE_TYPE_ARC: - case SHAPE_TYPE_POLYLINE: - case SHAPE_TYPE_POLYLINEZ: - case SHAPE_TYPE_POLYLINEM: - case SHAPE_TYPE_POLYGON: - case SHAPE_TYPE_POLYGONZ: - case SHAPE_TYPE_POLYGONM: - indexPolygons(shp, SHAPE_FILE_HEADER_LENGTH, entries); - break; - default: - logger.warning("Unknown shape type: " + shapeType); - } - - } catch (java.io.IOException e) { - e.printStackTrace(); - } finally { - try { - if (shp != null) - shp.close(); - } catch (java.io.IOException e) { - } - } - - return entries; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndexHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndexHandler.java deleted file mode 100644 index 2943aafb1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/SpatialIndexHandler.java +++ /dev/null @@ -1,534 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/SpatialIndexHandler.java,v $ -// $RCSfile: SpatialIndexHandler.java,v $ -// $Revision: 1.13 $ -// $Date: 2008/10/16 03:26:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape; - -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.Properties; - -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.shape.DbfHandler; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.shape.SpatialIndex.Entry; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The SpatialIndexHandler keeps track of all the stuff dealing with a - * particular shape file - file names, colors, etc. You can ask it to create - * OMGraphics based on a bounding box, and make adjustments to it through its - * GUI. This is the object to use if you just want to deal with the contents of - * a shape file but not display them. - */ -public class SpatialIndexHandler implements PropertyConsumer { - protected SpatialIndex spatialIndex; - protected String shapeFileName = null; - protected String imageURLString = null; - protected GeoCoordTransformation coordTranslator; - protected String prettyName = null; - protected DrawingAttributes drawingAttributes; - protected boolean enabled = true; - protected boolean buffered = false; - protected String propertyPrefix; - - public final static String EnabledProperty = "enabled"; - public final static String BufferedProperty = "buffered"; - - // for internationalization - protected I18n i18n = Environment.getI18n(); - - public SpatialIndexHandler() { - } - - public SpatialIndexHandler(String prefix, Properties props) { - setProperties(prefix, props); - } - - public static SpatialIndex create(String prefix, Properties props) { - SpatialIndexHandler sih = new SpatialIndexHandler(prefix, props); - return sih.getSpatialIndex(); - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("For ").append(prettyName).append(":\n"); - sb.append(" Shape file name: ").append(shapeFileName).append("\n"); - sb.append(" Spatal index file name: ").append(SpatialIndex.ssx(shapeFileName)).append("\n"); - sb.append(" image URL: ").append(imageURLString).append("\n"); - sb.append(" drawing attributes: ").append(drawingAttributes).append("\n"); - return sb.toString(); - } - - /** - * Get the GUI that controls the attributes of the handler. - */ - public JComponent getGUI() { - JPanel stuff = new JPanel(); - stuff.setBorder(BorderFactory.createRaisedBevelBorder()); - // stuff.add(new JLabel(prettyName)); - stuff.add(drawingAttributes.getGUI()); - - JPanel checks = new JPanel(new GridLayout(0, 1)); - JCheckBox enableButton = new JCheckBox(i18n.get(SpatialIndexHandler.class, "enableButton", "Show")); - enableButton.setSelected(enabled); - enableButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - enabled = jcb.isSelected(); - } - }); - checks.add(enableButton); - - JCheckBox bufferButton = new JCheckBox(i18n.get(SpatialIndexHandler.class, "bufferButton", "Buffer")); - bufferButton.setSelected(buffered); - bufferButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JCheckBox jcb = (JCheckBox) ae.getSource(); - buffered = jcb.isSelected(); - } - }); - checks.add(bufferButton); - stuff.add(checks); - - return stuff; - } - - /** Property Consumer method. */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** Property Consumer method. */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** Property Consumer method. */ - public void setProperties(Properties props) { - setProperties(null, props); - } - - /** Property Consumer method. */ - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - prettyName = props.getProperty(realPrefix + Layer.PrettyNameProperty); - String dataPathPrefix = props.getProperty(prefix + Layer.DataPathPrefixProperty); - - if (dataPathPrefix != null && dataPathPrefix.length() > 0) { - dataPathPrefix += "/"; - } else { - dataPathPrefix = ""; - } - - shapeFileName = dataPathPrefix - + props.getProperty(realPrefix + ShapeLayer.shapeFileProperty); - - if (shapeFileName != null && shapeFileName.endsWith(".shp")) { - - spatialIndex = SpatialIndex.locateAndSetShapeData(shapeFileName); - String dbfFileName = SpatialIndex.dbf(shapeFileName); - - try { - if (BinaryFile.exists(dbfFileName)) { - BinaryBufferedFile bbf = new BinaryBufferedFile(dbfFileName); - DbfHandler dbfh = new DbfHandler(bbf); - dbfh.setProperties(realPrefix, props); - spatialIndex.setDbf(dbfh); - } - } catch (FormatException fe) { - if (Debug.debugging("shape")) { - Debug.error("ShapeLayer: Couldn't create DBF handler for " + dbfFileName - + ", FormatException: " + fe.getMessage()); - } - } catch (IOException ioe) { - if (Debug.debugging("shape")) { - Debug.error("ShapeLayer: Couldn't create DBF handler for " + dbfFileName - + ", IOException: " + ioe.getMessage()); - } - } - - imageURLString = props.getProperty(realPrefix + ShapeLayer.pointImageURLProperty); - - try { - if (imageURLString != null && imageURLString.length() > 0) { - URL imageURL = PropUtils.getResourceOrFileOrURL(this, imageURLString); - ImageIcon imageIcon = new ImageIcon(imageURL); - spatialIndex.setPointIcon(imageIcon); - } - } catch (MalformedURLException murle) { - Debug.error("MultiShapeLayer.setProperties(" + realPrefix - + ": point image URL not so good: \n\t" + imageURLString); - - } catch (NullPointerException npe) { - // May happen if not connected to the internet. - Debug.error("Can't access icon image: \n" + imageURLString); - } - - } else { - Debug.error(realPrefix + ": No shape file name provided:"); - Debug.error("\t" + realPrefix + ShapeLayer.shapeFileProperty); - } - - drawingAttributes = new DrawingAttributes(realPrefix, props); - - enabled = PropUtils.booleanFromProperties(props, realPrefix + EnabledProperty, enabled); - buffered = PropUtils.booleanFromProperties(props, realPrefix + BufferedProperty, buffered); - - String transClassName = props.getProperty(realPrefix + ShapeLayer.TransformProperty); - if (transClassName != null) { - try { - coordTranslator = (GeoCoordTransformation) ComponentFactory.create(transClassName, realPrefix - + ShapeLayer.TransformProperty, props); - } catch (ClassCastException cce) { - - } - } - } - - /** Property Consumer method. */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + ShapeLayer.shapeFileProperty, (shapeFileName == null ? "" - : shapeFileName)); - props.put(prefix + ShapeLayer.pointImageURLProperty, (imageURLString == null ? "" - : imageURLString)); - - if (drawingAttributes != null) { - drawingAttributes.getProperties(props); - } else { - DrawingAttributes da = (DrawingAttributes) DrawingAttributes.DEFAULT.clone(); - da.setPropertyPrefix(prefix); - da.getProperties(props); - } - props.put(prefix + EnabledProperty, new Boolean(enabled).toString()); - props.put(prefix + BufferedProperty, new Boolean(buffered).toString()); - - if (spatialIndex != null) { - DbfHandler dbfh = spatialIndex.getDbf(); - if (dbfh != null) { - dbfh.getProperties(props); - } - } - - return props; - } - - /** Property Consumer method. */ - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - String interString; - - // those strings are already internationalized in ShapeLayer. - // So only thing to do is use - // keys and values from there.The main question is: what about - // .class? - // What should I use as requestor field when calling - // i18n.get(...) ? DFD - use the ShapeLayer class, so you - // only have to modify one properties file with the - // translation. - - interString = i18n.get(ShapeLayer.class, ShapeLayer.shapeFileProperty, I18n.TOOLTIP, "Location of Shape file - .shp (File, URL or relative file path)."); - props.put(ShapeLayer.shapeFileProperty, interString); - interString = i18n.get(ShapeLayer.class, ShapeLayer.shapeFileProperty, ShapeLayer.shapeFileProperty); - props.put(ShapeLayer.shapeFileProperty + LabelEditorProperty, interString); - props.put(ShapeLayer.shapeFileProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - // interString = i18n.get(ShapeLayer.class, - // ShapeLayer.spatialIndexProperty, - // I18n.TOOLTIP, - // "Location of Spatial Index file - .ssx (File, URL or relative file - // path)."); - // props.put(ShapeLayer.spatialIndexProperty, interString); - // interString = i18n.get(ShapeLayer.class, - // ShapeLayer.spatialIndexProperty, - // ShapeLayer.spatialIndexProperty); - // props.put(ShapeLayer.spatialIndexProperty + LabelEditorProperty, - // interString); - // props.put(ShapeLayer.spatialIndexProperty + ScopedEditorProperty, - // "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - interString = i18n.get(ShapeLayer.class, ShapeLayer.pointImageURLProperty, I18n.TOOLTIP, "Image file to use for map location of point data (optional)."); - props.put(ShapeLayer.pointImageURLProperty, interString); - interString = i18n.get(ShapeLayer.class, ShapeLayer.pointImageURLProperty, ShapeLayer.pointImageURLProperty); - props.put(ShapeLayer.pointImageURLProperty + LabelEditorProperty, interString); - props.put(ShapeLayer.pointImageURLProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - if (drawingAttributes != null) { - drawingAttributes.getPropertyInfo(props); - } else { - DrawingAttributes.DEFAULT.getPropertyInfo(props); - } - interString = i18n.get(SpatialIndexHandler.class, EnabledProperty, I18n.TOOLTIP, "Show file contents"); - props.put(EnabledProperty, interString); - interString = i18n.get(SpatialIndexHandler.class, EnabledProperty, EnabledProperty); - props.put(EnabledProperty + LabelEditorProperty, interString); - props.put(EnabledProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(SpatialIndexHandler.class, BufferedProperty, I18n.TOOLTIP, "Read and hold entire file contents (may be faster)"); - props.put(BufferedProperty, interString); - interString = i18n.get(SpatialIndexHandler.class, BufferedProperty, BufferedProperty); - props.put(BufferedProperty + LabelEditorProperty, interString); - props.put(BufferedProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } - - public GeoCoordTransformation getCoordTranslator() { - return coordTranslator; - } - - public void setCoordTranslator(GeoCoordTransformation coordTranslator) { - this.coordTranslator = coordTranslator; - } - - /** - * Create the OMGraphics out of the records that fall inside the bounding - * box. - * - * @param xmin double for the min horizontal limit of the bounding box. - * @param ymin double for the min vertical limit of the bounding box. - * @param xmax double for the max horizontal limit of the bounding box. - * @param ymax double for the max vertical limit of the bounding box. - */ - public OMGraphicList getGraphics(double xmin, double ymin, double xmax, double ymax) - throws IOException, FormatException { - return getGraphics(xmin, ymin, xmax, ymax, (OMGraphicList) null, (Projection) null); - } - - /** - * Given a bounding box, create OMGraphics from the ESRI records in the - * shape file. - * - * @param xmin double for the min horizontal limit of the bounding box. - * @param ymin double for the min vertical limit of the bounding box. - * @param xmax double for the max horizontal limit of the bounding box. - * @param ymax double for the max vertical limit of the bounding box. - * @param list OMGraphic list to add the new OMGraphics too. If null, a new - * OMGraphicList will be created. - * @return OMGraphicList containing the new OMGraphics. - */ - public OMGraphicList getGraphics(double xmin, double ymin, double xmax, double ymax, - OMGraphicList list) throws IOException, FormatException { - return getGraphics(xmin, ymin, xmax, ymax, list, (Projection) null); - } - - /** - * Given a bounding box, create OMGraphics from the ESRI records in the - * shape file. - * - * @param xmin double for the min horizontal limit of the bounding box. - * @param ymin double for the min vertical limit of the bounding box. - * @param xmax double for the max horizontal limit of the bounding box. - * @param ymax double for the max vertical limit of the bounding box. - * @param list OMGraphic list to add the new OMGraphics too. If null, a new - * OMGraphicList will be created. - * @param proj the projection to use to generate the OMGraphics. - * @return OMGraphicList containing the new OMGraphics. - */ - public OMGraphicList getGraphics(double xmin, double ymin, double xmax, double ymax, - OMGraphicList list, Projection proj) - throws IOException, FormatException { - if (list == null) { - list = new OMGraphicList(); - } - - if (!buffered) { - - // Clean up if buffering turned off. - if (bufferedList != null) { - bufferedList = null; - } - - spatialIndex.getOMGraphics(xmin, ymin, xmax, ymax, list, drawingAttributes, proj, coordTranslator); - - } else { - - if (bufferedList == null) { - bufferedList = getWholePlanet(coordTranslator); - } - - checkSpatialIndexEntries(xmin, ymin, xmax, ymax, list, proj); - - } - - return list; - } - - /** - * Checks the buffered list of OMGraphics from the shp file and figures out - * of they intersect the provided bounds. - * - * @param xmin minimum longitude, decimal degrees. - * @param ymin minimum latitude, decimal degrees. - * @param xmax maximum longitude, decimal degrees. - * @param ymax maximum latitude, decimal degrees. - * @param retList the list that passing OMGraphics will be added to. - * @param proj the current map projection. - */ - protected void checkSpatialIndexEntries(double xmin, double ymin, double xmax, double ymax, - OMGraphicList retList, Projection proj) - throws IOException, FormatException { - // There should be the same number of objects in both iterators. - Iterator entryIt = spatialIndex.entryIterator(); - Iterator omgIt = bufferedList.iterator(); - - OMGraphicList labels = null; - if (spatialIndex.getDbf() != null) { - labels = new OMGraphicList(); - retList.add(labels); - } - - while (entryIt.hasNext() && omgIt.hasNext()) { - Entry entry = (Entry) entryIt.next(); - OMGraphic omg = (OMGraphic) omgIt.next(); - if (entry.intersects(xmin, ymin, xmax, ymax)) { - // We want to set attributes before the evaluate method is - // called, since there might be special attributes set on the - // omg based on dbf contents. - drawingAttributes.setTo(omg); - omg = spatialIndex.evaluate(omg, labels, proj); - - // omg can be null from the evaluate method, if the omg doesn't - // pass proj and rule tests. - if (omg != null) { - omg.generate(proj); - retList.add(omg); - } - } - } - } - - /** - * Master list for buffering. Only used if buffering is enabled. - */ - protected OMGraphicList bufferedList = null; - - /** - * Get the graphics for the entire planet. - */ - protected OMGraphicList getWholePlanet() throws IOException, FormatException { - return getWholePlanet(coordTranslator); - } - - /** - * Get the graphics for the entire planet. - */ - protected OMGraphicList getWholePlanet(GeoCoordTransformation dataTransform) - throws IOException, FormatException { - // Sets the entries - spatialIndex.readIndexFile(null, dataTransform); - return spatialIndex.getAllOMGraphics((OMGraphicList) null, drawingAttributes, (Projection) null, dataTransform); - } - - public void setPrettyName(String set) { - prettyName = set; - } - - public String getPrettyName() { - return prettyName; - } - - public void setBuffered(boolean set) { - buffered = set; - } - - public boolean getBuffered() { - return buffered; - } - - public void setDrawingAttributes(DrawingAttributes set) { - drawingAttributes = set; - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - public SpatialIndex getSpatialIndex() { - return spatialIndex; - } - - public void setSpatialIndex(SpatialIndex spatialIndex) { - this.spatialIndex = spatialIndex; - } - - public String getShapeFileName() { - return shapeFileName; - } - - public void setShapeFileName(String shapeFileName) { - this.shapeFileName = shapeFileName; - } - - public String getImageURLString() { - return imageURLString; - } - - public void setImageURLString(String imageURLString) { - this.imageURLString = imageURLString; - } - - public void setEnabled(boolean set) { - enabled = set; - } - - public boolean getEnabled() { - return enabled; - } - - public boolean close(boolean done) { - if (spatialIndex != null) { - return spatialIndex.close(done); - } - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaHandler.java deleted file mode 100644 index a9f81bdbf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaHandler.java +++ /dev/null @@ -1,1077 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/areas/AreaHandler.java,v $ -// $RCSfile: AreaHandler.java,v $ -// $Revision: 1.4.2.8 $ -// $Date: 2009/03/03 04:59:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape.areas; - -import java.awt.Color; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.StringTokenizer; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.dataAccess.shape.input.DbfInputStream; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.shape.CSVShapeInfoFile; -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.layer.shape.SpatialIndex; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * An object to organize graphics in a shapefile and their corresponding - * attributes in OpenMap. A properties object can determine how areas/graphics - * are to be colored, or you can grab the graphics directly and color them - * yourself. It's called AreaHandler because it was originally intended to be a - * management tool for political boundary areas, but it should work for all - * shapefiles, really. This object uses a CSV file created from the DBF file - * that usually accompanies the shapefile. Also, this class does inflict a - * startup burden on the map. Because all the organizational effort occurs in - * setProperties(), it occurs even if the handler isn't used in an active Layer. - *

- * Here is a sample of what this thing is looking for by way of properties: - *

- * - *

- * 
- * 
- *                  layer.class=com.bbn.openmap.layer.shape.areas.AreaShapeLayer
- *                  layer.prettyName=Layer Name
- *                  layer.shapeFile=/usr/local/data/shape/shapefile.shp
- *                  layer.spatialIndex=/usr/local/data/shape/shapefile.ssx
- *                 
- *                  # Now, provide a data file that says what the shapes in the .shp
- *                  # file are.  You can use the DBF file:
- *                  layer.dbfFile=/usr/local/data/shape/shapefile.dbf
- *                  # OR a csv file, created yourself or from the .dbf file.  There
- *                  # should be the same number of entries in the .csv file that are in
- *                  # the .shp file.
- *                  layer.csvFile=/usr/local/data/shape/shapefile.csv
- *                  # An attribute to tell the AreaHandler to skip over the first row
- *                  # of the csv file if it contains descriptive column header names.
- *                  layer.csvFileHasHeader=true
- *                 
- *                  # Default DrawingAttributes properties for everything not defined
- *                  # specifically:
- *                  layer.lineColor=ff000000
- *                  layer.fillColor=ffff00ff
- *                 
- *                  # Now add any other attributes accepted by the DrawingAttributes
- *                  # object, with the prefix as stated above, i.e. layer.lineColor)
- *                  #
- *                  # The first column index is 0, not 1.
- *                  #
- *                  # The key index specifies which column in the csv file contains
- *                  # unique area names that are listed in the areas list here in the
- *                  # properties.  In this case, it's the column that contains MA in one
- *                  # of its rows.
- *                  layer.keyIndex=4
- *                 
- *                  # The name index is the column in the csv file that contains what
- *                  # should be displayed in the application when a shape is chosen - the
- *                  # object's proper name.
- *                  layer.nameIndex=4
- *                  layer.areas=MA RI
- *                  layer.areas.MA.fillColor=ffff0000
- *                  layer.areas.MA.lineColor=ff00ff00
- *                  layer.areas.RI.fillColor=ffff0000
- *                  layer.areas.RI.lineColor=ff00ff00
- * 
- * 
- * 
- * - *

- */ -public class AreaHandler implements PropertyConsumer { - - /** - * The known political areas, based on the list of OMGraphics each entry - * contains. - */ - protected Map politicalAreas; - /** The property that lists special colored areas. */ - public static final String areasProperty = "areas"; - /** - * A property that sets an image URL to use for point objects. Only one image - * for all point objects. - */ - public static final String pointImageURLProperty = "pointImageURL"; - /** - * The property that specifies an index location for the area search key for a - * shape graphic in the database file. Default is 1. The contents of this column - * should match the area key used to specify the drawingattributes of that - * particular object as listed in these properties. - */ - public static final String keyIndexProperty = "keyIndex"; - /** - * The property that specifies an index location for the area name for a shape - * graphic in the database file. Default is 0. - */ - public static final String nameIndexProperty = "nameIndex"; - /** - * The resource name, URL or file name of the serialized graphics file. - */ - public static final String CacheFileProperty = "cacheFile"; - /** - * The name of the property that holds the name of the CSV file with the area - * attributes, like the name and the abbreviation (or search Key). - */ - public final static String csvFileProperty = "csvFile"; - /** Set if the CSVFile has a header record. Default is true. */ - public final static String csvHeaderProperty = "csvFileHasHeader"; - /** - * The name of the property that holds the name of the DBF file with the area - * attributes, like the name and the abbreviation (or search Key). - */ - public final static String dbfFileProperty = "dbfFile"; - /** - * The list of areas that have special coloring needs. Used to write the - * properties back out. - */ - protected List areasItems = new ArrayList<>(); - /** - * The index of the column that holds the name of the area. This name will be - * used for display in the GUI for a particular map object. - */ - protected int nameIndex = 0; - /** - * The index of the column that holds the search key of the area. This is the - * field that is the key to use for the Hashtable holding all the area - * descriptions, and should be unique for each named area. - */ - protected int keyIndex = 1; - /** The URL location of the cached graphics file. */ - protected URL cacheURL = null; - /** The graphics list */ - protected OMGraphicList omgraphics = null; - - /** - * Default draw parameters of the graphics that don't have something specific - * set for it. - */ - protected DrawingAttributes drawingAttributes; - - /** The location of the CSV attribute file. */ - protected CSVShapeInfoFile infoFile = null; - - /** The DBF attribute file table model. */ - protected DbfTableModel dbfModel = null; - - /** - * Flag that specifies that the first line consists of header information, and - * should not be mapped to a graphic. - */ - protected boolean csvHasHeader = true; - - protected Properties originalProperties = null; - protected String originalPrefix = null; - protected SpatialIndex spatialIndex = null; - protected GeoCoordTransformation coordTransform = null; - - // public AreaHandler() {} - - /** - * Construct an AreaHandler. Needs an external SpatialIndex, and default - * DrawingAttributes. - */ - public AreaHandler(SpatialIndex si, DrawingAttributes da) { - setDrawingAttributes(da); - setSpatialIndex(si); - } - - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - public void setSpatialIndex(SpatialIndex si) { - spatialIndex = si; - } - - public SpatialIndex getSpatialIndex() { - return spatialIndex; - } - - public Map getPoliticalAreas() { - return politicalAreas; - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - /** - * Initializes this object from the given properties - * - * @param props the Properties holding settings for this object - */ - public void setProperties(String prefix, Properties props) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: setting properties"); - } - - setPropertyPrefix(prefix); - originalProperties = props; - - // These will get initialized when someone asks for it. - // Otherwise, it delays the startup of the map. - politicalAreas = null; - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String transClassName = props.getProperty(realPrefix + ShapeLayer.TransformProperty); - if (transClassName != null) { - try { - coordTransform = (GeoCoordTransformation) ComponentFactory.create(transClassName, - realPrefix + ShapeLayer.TransformProperty, props); - } catch (ClassCastException cce) { - - } - } - } - - /** PropertyConsumer method. */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - if (coordTransform instanceof PropertyConsumer) { - ((PropertyConsumer) coordTransform).getProperties(props); - } - - return props; - } - - /** PropertyConsumer method. */ - public Properties getPropertyInfo(Properties props) { - if (props == null) { - props = new Properties(); - } - - return props; - } - - /** PropertyConsumer method. */ - public void setPropertyPrefix(String pre) { - originalPrefix = pre; - } - - /** PropertyConsumer method. */ - public String getPropertyPrefix() { - return originalPrefix; - } - - /** - * Go through the properties, loading the shapefile, information file and - * attributes files, and resolve how everything should be drawn. Might take - * awhile if the files are large. Called from getRectangle, which is called when - * the AreaShapeLayer is added to the map. - * - * @param prefix property file entry header name - * @param props the properties to look through. - */ - public void initialize(String prefix, Properties props) { - - if (props == null) { - Debug.error("AreaHandler: initialize received bad input:\n\tprefix: " + prefix + "\n\tproperties: " - + (props == null ? "null" : "OK")); - politicalAreas = null; - return; - } - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - politicalAreas = new HashMap(); - - // OK, Get the graphics. We are not expecting that all the - // graphics in the file are not too much to handle. Also, we - // test for the serialized graphics file first, and if it - // isn't designated, then look for a shapefile and spatial - // index file to create an OMGraphicsList. - String cacheFile = props.getProperty(prefix + CacheFileProperty); - - // First find the resource, if not, then try as a file-URL... - try { - cacheURL = PropUtils.getResourceOrFileOrURL(this, cacheFile); - - if (cacheURL != null) { - omgraphics = readCachedGraphics(cacheURL); - } else { - // We'll use the spatial index set from the - // ShapeLayer. - - // Now, get the attribute file - String dbfFile = props.getProperty(prefix + dbfFileProperty); - URL dbfFileURL = null; - if (dbfFile != null) { - dbfFileURL = PropUtils.getResourceOrFileOrURL(this, dbfFile); - } - if (dbfFileURL != null) { - InputStream is = dbfFileURL.openStream(); - dbfModel = new DbfTableModel(new DbfInputStream(is)); - } - if (dbfModel == null) { - String csvFile = props.getProperty(prefix + csvFileProperty); - URL infofileURL = null; - if (csvFile != null) { - infofileURL = PropUtils.getResourceOrFileOrURL(this, csvFile); - } - - // Read them in. - if (infofileURL != null) { - infoFile = new CSVShapeInfoFile(csvFile); - infoFile.setHeadersExist( - PropUtils.booleanFromProperties(props, prefix + csvHeaderProperty, true)); - infoFile.loadData(true); - } - } - } - } catch (java.net.MalformedURLException murle) { - omgraphics = new OMGraphicList(); - } catch (java.io.IOException ioe) { - omgraphics = new OMGraphicList(); - } catch (Exception exc) { - omgraphics = new OMGraphicList(); - } - - // This is handled properly yet. The PoliticalArea should be - // updated to handle URLs for area points, and have different - // icons for different areas. - // String defaultPointImageURLString = - // props.getProperty(prefix + pointImageURLProperty); - - // Now, match the attributes to the graphics. Find the - // indexes of the name and the search key. Also figure out - // which areas have special coloring needs. - keyIndex = PropUtils.intFromProperties(props, prefix + keyIndexProperty, keyIndex); - nameIndex = PropUtils.intFromProperties(props, prefix + nameIndexProperty, nameIndex); - String areas = props.getProperty(prefix + areasProperty); - - if (areas == null) - areas = ""; - - StringTokenizer tokenizer = new StringTokenizer(areas, " "); - // All this uses the properties to set the individual colors - // of any area - String currentArea; - - while (tokenizer.hasMoreTokens()) { - currentArea = tokenizer.nextToken(); - - PoliticalArea newParams = new PoliticalArea(currentArea); - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: setting SPECIALIZED attributes for \"" + newParams.id + "\""); - } - - areasItems.add(currentArea); - - newParams.drawingAttributes = new DrawingAttributes(prefix + areasProperty + "." + currentArea, props); - - politicalAreas.put(newParams.id.toUpperCase().intern(), newParams); - } - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: finished initialization"); - } - } - - /** - * Read a cache of OMGraphics - */ - public OMGraphicList readCachedGraphics(URL url) throws java.io.IOException { - - if (Debug.debugging("areas")) { - Debug.output("Reading cached graphics"); - } - - OMGraphicList omgraphics = new OMGraphicList(); - - if (url != null) { - omgraphics.readGraphics(url); - } - return omgraphics; - } - - /** - * Get all the graphics from the shapefile, colored appropriately. - */ - public OMGraphicList getGraphics() { - if (omgraphics == null) { - omgraphics = new OMGraphicList(); - try { - spatialIndex.getOMGraphics(-180, -90, 180, 90, omgraphics, drawingAttributes, (Projection) null, - coordTransform); - - updateDrawingParameters(omgraphics); - - } catch (IOException ioe) { - Debug.error(ioe.getMessage()); - } catch (FormatException fe) { - Debug.error(fe.getMessage()); - } - } - return omgraphics; - } - - protected void updateDrawingParameters(OMGraphicList omgl) { - if (omgl != null) { - for (OMGraphic omg : omgl) { - Integer recNum = (Integer) omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - if (recNum != null) { - getDrawParams(recNum.intValue()).setTo(omg); - omg.putAttribute(OMGraphic.INFOLINE, getName(recNum)); - } - } - } - } - - /** - * Get the graphics for a particular lat/lon area. - * - * @param ulLat upper left latitude, in decimal degrees. - * @param ulLon upper left longitude, in decimal degrees. - * @param lrLat lower right latitude, in decimal degrees. - * @param lrLon lower right longitude, in decimal degrees. - * @return OMGraphicList - */ - public OMGraphicList getGraphics(double ulLat, double ulLon, double lrLat, double lrLon) { - return getGraphics(ulLat, ulLon, lrLat, lrLon, (Projection) null); - } - - /** - * Get the graphics for a particular lat/lon area. - * - * @param ulLat upper left latitude, in decimal degrees. - * @param ulLon upper left longitude, in decimal degrees. - * @param lrLat lower right latitude, in decimal degrees. - * @param lrLon lower right longitude, in decimal degrees. - * @param proj the current map projection. - * @return OMGraphicList - */ - public OMGraphicList getGraphics(double ulLat, double ulLon, double lrLat, double lrLon, Projection proj) { - - if (cacheURL != null) { - return omgraphics; - } - - if (spatialIndex == null) { - return new OMGraphicList(); - } - - if (politicalAreas == null) { - initialize(originalPrefix, originalProperties); - } - - OMGraphicList list = new OMGraphicList(); - - // check for dateline anomaly on the screen. we check for - // ulLon >= lrLon, but we need to be careful of the check for - // equality because of floating point arguments... - if (ProjMath.isCrossingDateline(ulLon, lrLon, proj.getScale())) { - if (Debug.debugging("areas")) { - Debug.output("AreaHander.getGraphics(): Dateline is on screen"); - } - - double ymin = Math.min(ulLat, lrLat); - double ymax = Math.max(ulLat, lrLat); - - try { - - list = spatialIndex.getOMGraphics(ulLon, ymin, 180.0d, ymax, list, drawingAttributes, proj, - coordTransform); - list = spatialIndex.getOMGraphics(-180.0d, ymin, lrLon, ymax, list, drawingAttributes, proj, - coordTransform); - - } catch (InterruptedIOException iioe) { - // This means that the thread has been interrupted, - // probably due to a projection change. Not a big - // deal, just return, don't do any more work, and let - // the next thread solve all problems. - list = null; - } catch (IOException ex) { - ex.printStackTrace(); - } catch (FormatException fe) { - fe.printStackTrace(); - } - - } else { - - double xmin = (double) Math.min(ulLon, lrLon); - double xmax = (double) Math.max(ulLon, lrLon); - double ymin = (double) Math.min(ulLat, lrLat); - double ymax = (double) Math.max(ulLat, lrLat); - try { - list = spatialIndex.getOMGraphics(xmin, ymin, xmax, ymax, list, drawingAttributes, proj, - coordTransform); - } catch (InterruptedIOException iioe) { - // This means that the thread has been interrupted, - // probably due to a projection change. Not a big - // deal, just return, don't do any more work, and let - // the next thread solve all problems. - list = null; - } catch (java.io.IOException ex) { - ex.printStackTrace(); - } catch (FormatException fe) { - fe.printStackTrace(); - } - } - - updateDrawingParameters(list); - return list; - } - - /** - * Return the graphic name, given the infofile vector on the graphic. The - * AreaHandler knows which one is the name. Returns an empty string if something - * goes wrong. - */ - public String getName(List vector) { - if (vector != null) { - Object name = vector.get(nameIndex); - if (name != null) { - name.toString(); - } - } - return ""; - } - - /** - * Get the name of the object at the index of the list. This is a zero-based - * index. Remember, the record number out of the shape file is one-based. The - * index stored in the OMGraphic attribute created from the shape files is - * zero-based to help with lookups. - * - * @param integer a zero-based index. - * @return an empty string if something goes wrong, or the name as a String. - */ - public String getName(Integer integer) { - try { - if (infoFile != null) { - return getName(infoFile.getRecord(integer.intValue())); - } else if (dbfModel != null) { - Object obj = dbfModel.getValueAt(integer.intValue(), nameIndex); - if (obj != null) { - return obj.toString(); - } - } - } catch (ClassCastException cce) { - } - return ""; - } - - /** - * Given the shapefile record number, find the drawing parameters that should be - * used for the shape. - * - * @param recordNumber the zero-based record number from the OMGraphicList. - */ - public DrawingAttributes getDrawParamsFromCSV(int recordNumber) { - if (infoFile == null) { - return drawingAttributes; - } - - // OFF BY ONE!!! The shape record numbers - // assigned to the records start with 1, while - // everything else we do starts with 0... - List info = infoFile.getRecord(recordNumber); - - if (info == null) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has no info"); - } - return drawingAttributes; - } - - Object keyObj = info.get(keyIndex); - String key = null; - PoliticalArea pa = null; - - if (keyObj != null) { - key = createStringFromKeyObject(keyObj); - pa = politicalAreas.get(key); - } - - if (pa == null) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has key \"" + key - + "\" and DEFAULT attributes"); - } - return drawingAttributes; - } else { - // Only bother with this the first time around. - if (pa.name == null) { - Object name = info.get(nameIndex); - if (name != null) { - pa.name = name.toString(); - } else { - pa.name = ""; - } - } - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has key \"" + key - + "\" and SPECIALIZED attributes"); - } - return pa.drawingAttributes; - } - } - - /** - * Given the shapefile record number, find the drawing parameters from the DBF - * model that should be used for the shape. Returns the default coloring if the - * key for the drawing parameters isn't found. - * - * @param recordNumber the zero-based record number from the OMGraphicList - */ - public DrawingAttributes getDrawParamsFromDBF(int recordNumber) { - if (dbfModel == null) { - return drawingAttributes; - } - - if (dbfModel == null || dbfModel.getRowCount() < recordNumber) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has no info"); - } - return drawingAttributes; - } - - Object keyObj = dbfModel.getValueAt(recordNumber, keyIndex); - String key = null; - PoliticalArea pa = null; - - if (keyObj != null) { - key = createStringFromKeyObject(keyObj); - pa = politicalAreas.get(key); - } - - if (pa == null) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has key \"" + key - + "\" and DEFAULT attributes"); - } - return drawingAttributes; - } else { - // Only bother with this the first time around. - if (pa.name == null) { - // String name = (String) info.elementAt(nameIndex); - String name = (String) dbfModel.getValueAt(recordNumber, nameIndex); - if (name != null) { - pa.name = name; - } else { - pa.name = ""; - } - } - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has key \"" + key - + "\" and SPECIALIZED attributes"); - } - return pa.drawingAttributes; - } - } - - /** - * OK, we can't assume that we are assigning a string as a key, you might want - * to key in on a specific attribute that is a number, like the country coloring - * code that ESRI has in the country file. We're going to assume that if the - * number has an integer value, it shouldn't have decimal places. That is, a 1.0 - * will be truncated to 1, because that makes more sense in a data file where - * you are using a key as a factor. If the double value doesn't match the - * integer value, though, we'll assume that's what was meant and leave it alone. - *

- */ - protected String createStringFromKeyObject(Object keyObj) { - String key = null; - if (keyObj instanceof String) { - key = ((String) keyObj).toUpperCase().intern(); - } else if (keyObj instanceof Number) { - Number keyNum = (Number) keyObj; - if (keyNum.doubleValue() == (double) keyNum.intValue()) { - // Strips off empty decimal places, for sure - key = Integer.toString(keyNum.intValue()).intern(); - } else { - key = Double.toString(keyNum.doubleValue()).intern(); - } - } else { - try { - key = keyObj.toString().toUpperCase().intern(); - } catch (Exception e) { - Debug.error("AreaHandler.createStringFromKeyObject: bad key object:" + keyObj); - } - } - return key; - } - - /** - * Given the shapefile record number, find the drawing parameters that should be - * used for the shape. Returns the default coloring if the key for the drawing - * parameters isn't found. - * - * @param recordNumber the zero-based record number from the OMGraphics. - */ - public DrawingAttributes getDrawParams(int recordNumber) { - if (dbfModel != null) - return getDrawParamsFromDBF(recordNumber); - else - return getDrawParamsFromCSV(recordNumber); - } - - /** - * This function takes an OMGraphicList and loads each one with the array - * representing the records in the dbf file. Each graphics stores the graphic in - * its object slot. - */ - public void loadDbfModelIntoGraphics(OMGraphicList list) { - if (list != null && dbfModel.getRowCount() > 0) { - int numgraphics = list.size(); - - for (int i = 0; i < numgraphics; i++) { - try { - OMGraphic omg = list.getOMGraphicAt(i); - Integer recnum = (Integer) (omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - // OFF BY ONE!!! The shape record numbers - // assigned to the records start with 0, while - // everything else we do starts with 0. The DbfTableModel - // follows java convention and starts at 0. The integer - // stored in the OMG should know it too. - Object inforec = dbfModel.getRecord(recnum.intValue()); - omg.putAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE, inforec); - } catch (ClassCastException cce) { - if (Debug.debugging("shape")) { - cce.printStackTrace(); - } - } catch (NullPointerException npe) { - npe.printStackTrace(); - } - } - } - } - - /** - * Find a PoliticalArea named by the search key. If the shapefile is large, the - * first query will take a little extra time on the first query to read in the - * files. - * - * @param area_key the lookup key, of which the index for the column was - * designated in the properties file. - */ - public PoliticalArea findPoliticalArea(String area_key) { - - // Right now, this method gathers all the graphics in the - // shape file, groups them, and then returns the PoliticalArea - // for the key. In the future, it would be nice to have the - // option to actually search through the data file, find the - // indexes of the graphics that go to the area, and assemble a - // temporary list to pass back. - - if (politicalAreas == null) { - Debug.message("areas", "AreaHandler: initializing graphic attributes"); - initialize(originalPrefix, originalProperties); - - if (omgraphics == null) { - omgraphics = getGraphics(); - if (dbfModel != null) { - loadDbfModelIntoGraphics(omgraphics); - } else { - infoFile.loadIntoGraphics(omgraphics); - } - } - - politicalAreas = determinePoliticalAreas(omgraphics); - Debug.message("areas", "AreaHandler: completed initialization"); - } - - if (politicalAreas != null) { - String key = area_key.toUpperCase().intern(); // Just to - // be sure. - - return politicalAreas.get(key); - } else { - Debug.error("AreaHandler: initialization failed for " + originalPrefix + "\n\tNo data will be displayed"); - return null; - } - } - - /** - * Find the graphics that are represented by an search key. If the shapefile is - * large, the first query will take a little extra time on the first query to - * read in the files. - * - * @param area_key the lookup key, of which the index for the column was - * designated in the properties file. - */ - public OMGeometryList findGraphics(String area_key) { - PoliticalArea area = findPoliticalArea(area_key); - if (area == null) { - return null; - } else { - return area.getGeometry(); - } - } - - /** - * DeterminePoliticalAreas goes over a list of omgraphics, and spits out a - * hashtable that holds PoliticalArea objects for every area key. - * - * @param graphicList the list of graphics. The top level graphic entries on the - * list represent areas. - */ - public Map determinePoliticalAreas(OMGraphicList graphicList) { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: Determining political areas from OMGraphicList"); - } - - return determinePoliticalAreas(graphicList, new HashMap()); - } - - /** - * DeterminePoliticalAreas goes over a list of omgraphics, and spits out a - * hashtable that holds PoliticalArea objects for every area key. When an ID is - * found in the graphics, it is checked in the hashtable for like graphics, and - * added to that PoliticalArea if found. If not found, a new PoliticalArea is - * created and placed in the Hashtable. This will duplicate graphics if you call - * it more than once for the same graphic list. - * - * @param graphicList the list of graphics. The top level graphic entries on the - * list represent areas. - */ - public Map determinePoliticalAreas(OMGraphicList graphicList, - Map poliAreas) { - - // Simple case. No graphics means an empty list of regions. - String name = null; - String key = null; - - if (graphicList != null) { - int size = graphicList.size(); - for (int i = 0; i < size; i++) { - OMGraphic graphic = graphicList.getOMGraphicAt(i); - // below should be a vector like [ "Massachusetts", - // "MA" ]; - - Object obj = graphic.getAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE); - if (obj == null) { - if (Debug.debugging("areas")) { - Debug.error("AreaHandler: No attributes for graphic #" + i); - } - continue; - } - - if (obj instanceof List) { - List pair = (List) obj; - - name = (String) pair.get(nameIndex); - key = ((String) pair.get(keyIndex)).toUpperCase().intern(); - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: looking at " + name + ", " + key); - } - } else if (obj instanceof String) { - // Assume that the key is stored here, I guess. - key = obj.toString(); - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: String app object, looking at " + key); - } - } else { - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: Unidentified app object type " + obj); - } - } - - // Get the political area object for this keyiation. - PoliticalArea area = poliAreas.get(key); - - if (area == null) { // key is not in table - area = new PoliticalArea(name, key); - poliAreas.put(key, area); // add it to the table - // AreaDrawParams adp = - // (AreaDrawParams)drawingParams.get(key); - // if (adp != null) { - // area.setDrawingAttributes(adp.drawingAttributes); - // } - } - - // Add the graphic to the list for this political - // area. - area.addGraphic(graphic); - } - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: Finished determinePoliticalAreas: " + poliAreas.size() + " areas defined."); - } - } - - return poliAreas; - } - - protected Color getColor(String colorString) { - Color result = Color.black; - try { - result = PropUtils.parseColor(colorString); - } catch (NumberFormatException nfe) { - result = GetColorFromString(colorString); - } - return result; - } - - /** - * This function would return a Color object for string such as red, green,.. - * (all that are available from java.awt.color class). It can also return a - * specific color represented by HEX or Octal number like 0xffeeffee - */ - protected Color GetColorFromString(String token) { - String tokstring = (String) token; - - Color result = Color.black; - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler: GetColorFromString(" + tokstring + ")"); - } - - // Thank the heavens for Emacs macros! - if (tokstring.equals("black")) - result = Color.black; - else if (tokstring.equals("blue")) - result = Color.blue; - else if (tokstring.equals("cyan")) - result = Color.cyan; - else if (tokstring.equals("darkGray")) - result = Color.darkGray; - else if (tokstring.equals("gray")) - result = Color.gray; - else if (tokstring.equals("green")) - result = Color.green; - else if (tokstring.equals("lightGray")) - result = Color.lightGray; - else if (tokstring.equals("magenta")) - result = Color.magenta; - else if (tokstring.equals("orange")) - result = Color.orange; - else if (tokstring.equals("pink")) - result = Color.pink; - else if (tokstring.equals("red")) - result = Color.red; - else if (tokstring.equals("white")) - result = Color.white; - else if (tokstring.equals("yellow")) - result = Color.yellow; - else - // decode a hex color string. - result = Color.decode(tokstring); - - if (Debug.debugging("areas")) { - Debug.output("AreaHandler.GetColorFromToken returns (" + result + ")"); - } - return result; - } - - public GeoCoordTransformation getCoordTransform() { - return coordTransform; - } - - public void setCoordTransform(GeoCoordTransformation dataTransform) { - this.coordTransform = dataTransform; - } - - /** - * This main function basically reads in the data sources (the shape file and - * the csv information file, and creates a serialized graphics file that will - * act like a cache later. - */ - public static void main(String[] argv) { - String propertiesFile = null; - String prefix = null; - String outputFile = null; - - Debug.init(); - - if (argv.length < 6) - printUsage(); - - for (int i = 0; i < argv.length; i++) { - if (argv[i].equalsIgnoreCase("-props")) { - propertiesFile = argv[++i]; - } else if (argv[i].equalsIgnoreCase("-prefix")) { - prefix = argv[++i]; - } else if (argv[i].equalsIgnoreCase("-file")) { - outputFile = argv[++i]; - } - } - - if (propertiesFile == null || prefix == null || outputFile == null) { - printUsage(); - } - - try { - Properties properties = new Properties(); - // Read in the properties. - URL propertiesURL = new URL(propertiesFile); - InputStream is = propertiesURL.openStream(); - properties.load(is); - - // Let's make a file - ShapeLayer sl = new ShapeLayer(); - sl.setProperties(prefix, properties); - - AreaHandler ah = new AreaHandler(sl.getSpatialIndex(), sl.getDrawingAttributes()); - - // Set the properties in the handler. - ah.setProperties(prefix, properties); - // Write the saved graphics. - ah.getGraphics().writeGraphics(outputFile); - - } catch (java.net.MalformedURLException murle) { - Debug.error("Bad URL for properties file : " + propertiesFile); - printUsage(); - } catch (java.io.IOException ioe) { - Debug.error("IOException creating cached graphics file: " + outputFile); - printUsage(); - } - } - - public static void printUsage() { - Debug.output( - "Usage: java com.bbn.openmap.layer.shape.areas.AreaHandler -props -prefix -file "); - System.exit(-1); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaShapeLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaShapeLayer.java deleted file mode 100644 index 358d6a3a3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/AreaShapeLayer.java +++ /dev/null @@ -1,137 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/areas/AreaShapeLayer.java,v $ -// $RCSfile: AreaShapeLayer.java,v $ -// $Revision: 1.4.2.5 $ -// $Date: 2009/03/03 04:59:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape.areas; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * A Layer to use an AreaHandler to display geographic regions on OpenMap. See - * the AreaHandler for more information on how to set this layer up. - * - * @see com.bbn.openmap.layer.shape.areas.AreaHandler - */ -public class AreaShapeLayer extends ShapeLayer { - - private static final long serialVersionUID = 1L; - protected AreaHandler areas; - - /** - */ - public AreaShapeLayer() { - super(); - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for this - * layer - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - areas = new AreaHandler(spatialIndex, drawingAttributes); - areas.setProperties(prefix, props); - areas.setCoordTransform(super.getCoordTransform()); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - if (areas != null) { - areas.getProperties(props); - } - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - if (areas != null) { - areas.getPropertyInfo(props); - } - return props; - } - - /** - * Set the AreaHandler. - */ - public void setAreas(AreaHandler a) { - areas = a; - } - - /** - * Get the AreaHandler. - */ - public AreaHandler getAreas() { - return areas; - } - - /** - * Gets the layer graphics. - * - * @return OMGraphicList - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - Point2D ul = projection.getUpperLeft(); - Point2D lr = projection.getLowerRight(); - double ulLat = ul.getY(); - double ulLon = ul.getX(); - double lrLat = lr.getY(); - double lrLon = lr.getX(); - - OMGraphicList list = areas.getGraphics(ulLat, - ulLon, - lrLat, - lrLon, - getProjection()); - return list; - } - - public void setDrawingAttributes(DrawingAttributes da) { - areas.setDrawingAttributes(da); - } - - public DrawingAttributes getDrawingAttributes() { - return areas.getDrawingAttributes(); - } - - /** - * Find a PoliticalArea named by the abbreviation - */ - public PoliticalArea findPoliticalArea(String area_abbrev) { - return areas.findPoliticalArea(area_abbrev); - } - - public boolean isHighlightable(OMGraphic omg) { - return true; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/PoliticalArea.java b/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/PoliticalArea.java deleted file mode 100644 index 264587fc1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/PoliticalArea.java +++ /dev/null @@ -1,218 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/shape/areas/PoliticalArea.java,v $ -// $RCSfile: PoliticalArea.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/08/25 15:36:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.shape.areas; - -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.TexturePaint; -import java.awt.image.BufferedImage; -import java.net.URL; - -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGeometryList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.Debug; - -/** - * A PoliticalArea is a region that has a name (like "Oklahoma"), an identifier - * (like "OK"), and a list of OMGraphics that define its geography (ie: the - * polygons that define it's borders). - *

- * NOTE: The name of this class is somewhat misleading - the graphic doesn't - * have to represent an area - the graphic can be any graphic created from the - * shapefile. This class just provides a way to associate an id with the - * graphic. - */ -public class PoliticalArea { - public final String id; - - public String name = null; - protected OMGeometryList geometry; - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - public PoliticalArea(String identifier) { - this(null, identifier); - } - - /** - * Create a political area with a name, and an identifier which is used as a - * key by the AreaHandler. - */ - public PoliticalArea(String name, String identifier) { - this.id = identifier; - this.name = name; - geometry = new OMGeometryList(); - } - - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - da.setTo(geometry); - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - /** - * Set the fill-paint of all the graphics in the List - * - * @param c java.awt.Paint - */ - public void setFillPaint(Paint c) { - drawingAttributes.setFillPaint(c); - drawingAttributes.setTo(geometry); - } - - /** - * Get the paint used for the fill paint for all the graphics in the - * political area, if one was set. - * - * @return Paint if set, null if it wasn't. - */ - public Paint getFillPaint() { - return drawingAttributes.getFillPaint(); - } - - /** - * Set the fill pattern of all the graphics in the List. This will override - * the fill paint, if you've set that as well. There are sections of code in - * this method that need to be commented out if you are not using jdk 1.2.x. - * - * @param fillPatternURL url of image file to use as fill. - */ - public void setFillPattern(URL fillPatternURL) { - // This is kind of tricky. Look at the list, find out which - // members are OMGraphic2D objects, and set the Paint for - // those graphics. - - TexturePaint texture = null; - try { - - if (fillPatternURL != null) { - BufferedImage bi = BufferedImageHelper.getBufferedImage(fillPatternURL, - 0, - 0, - -1, - -1); - texture = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); - } - } catch (InterruptedException ie) { - Debug.error("PoliticalArea.setFillPattern(): error getting texture image - \n" - + ie); - } - - setFillPattern(texture); - } - - /** - * Set the fill pattern of all the graphics in the List. This will override - * the fill paint, if you've set that as well. There are sections of code in - * this method that need to be commented out if you are not using jdk 1.2.x. - * - * @param texture TexturePaint object to use as fill. - */ - public void setFillPattern(TexturePaint texture) { - drawingAttributes.setFillPaint(texture); - drawingAttributes.setTo(geometry); - } - - /** - * Get the TexturePaint used as fill for all the graphics in the political - * area, if one was set. - * - * @return TexturePaint if set, null if it wasn't. - */ - public TexturePaint getFillPattern() { - return drawingAttributes.getFillPattern(); - } - - /** - * Set the line-paint of all the graphics in the List - * - * @param c java.awt.Paint - */ - public void setLinePaint(Paint c) { - drawingAttributes.setLinePaint(c); - drawingAttributes.setTo(geometry); - } - - /** - * Get the paint used for the line paint for all the graphics in the - * political area, if one was set. - * - * @return Paint if set, null if it wasn't. - */ - public Paint getLinePaint() { - return drawingAttributes.getLinePaint(); - } - - /** - * Set the select-paint of all the graphics in the List - * - * @param c java.awt.Paint - */ - public void setSelectPaint(Paint c) { - drawingAttributes.setSelectPaint(c); - drawingAttributes.setTo(geometry); - } - - /** - * Get the paint used for the select paint for all the graphics in the - * political area, if one was set. - * - * @return Paint if set, null if it wasn't. - */ - public Paint getSelectPaint() { - return drawingAttributes.getSelectPaint(); - } - - /** - * Get the value of geometry. - * - * @return Value of geometry. - */ - public OMGeometryList getGeometry() { - return geometry; - } - - /** - * Set the value of geometry. - * - * @param v Value to assign to geometry. - */ - public void setGeometry(OMGeometryList v) { - this.geometry = v; - drawingAttributes.setTo(v); - } - - /** - * Add a new omgraphic to the list of graphics in this area - */ - public void addGraphic(OMGraphic g) { - this.geometry.add((OMGeometry) g); - drawingAttributes.setTo(g); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/package.html b/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/package.html deleted file mode 100644 index 1873eb953..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/areas/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Provides an extension to the ShapeLayer that deals with attributes files -for shapefiles. - - @see com.bbn.openmap.layer.shape - @see com.bbn.openmap.layer.shape.ShapeLayer - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/shape/package.html b/src/core/src/main/java/com/bbn/openmap/layer/shape/package.html deleted file mode 100644 index 19189b29c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/shape/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides an OpenMap layer for dealing with shape files. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDefinedState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDefinedState.java deleted file mode 100644 index 7eedbd909..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDefinedState.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSDefinedState.java,v -// $ -// $RCSfile: LOSDefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.util.stateMachine.State; -class LOSDefinedState extends State { - - protected LOSGenerator LOSTool; - - public LOSDefinedState(LOSGenerator tool) { - LOSTool = tool; - } - - public boolean mousePressed(MouseEvent e) { - LOSTool.reset(); - LOSTool.layer.repaint(); - LOSTool.setCenter(e); - LOSTool.stateMachine.setState(LOSStateMachine.TOOL_DRAW); - return true; - } - - public boolean mouseReleased(MouseEvent e) { - LOSTool.reset(); - return true; - } - - public boolean mouseClicked(MouseEvent e) { - LOSTool.reset(); - return true; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(TerrainLayer.createCommand)) { - LOSTool.doImage(); - LOSTool.stateMachine.setState(LOSStateMachine.TOOL_VIEW); - } else - LOSTool.reset(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDoNothingState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDoNothingState.java deleted file mode 100644 index 43c1536da..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDoNothingState.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSDoNothingState.java,v -// $ -// $RCSfile: LOSDoNothingState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.util.stateMachine.State; - -class LOSDoNothingState extends State { - - protected LOSGenerator LOSTool; - - public LOSDoNothingState(LOSGenerator tool) { - LOSTool = tool; - } - - public boolean mousePressed(MouseEvent e) { - LOSTool.setCenter(e); - LOSTool.stateMachine.setState(LOSStateMachine.TOOL_DRAW); - return true; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDrawState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDrawState.java deleted file mode 100644 index c1c9c226d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSDrawState.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSDrawState.java,v -// $ -// $RCSfile: LOSDrawState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.util.stateMachine.State; - -class LOSDrawState extends State { - - protected LOSGenerator LOSTool; - - public LOSDrawState(LOSGenerator tool) { - LOSTool = tool; - } - - public boolean mouseReleased(MouseEvent e) { - LOSTool.addLOSEvent(e); - LOSTool.layer.repaint(); - LOSTool.stateMachine.setState(LOSStateMachine.TOOL_DEFINED); - return true; - } - - public boolean mouseDragged(MouseEvent e) { - LOSTool.addLOSEvent(e); - LOSTool.layer.repaint(); - return true; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSGenerator.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSGenerator.java deleted file mode 100644 index b9ba2b7dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSGenerator.java +++ /dev/null @@ -1,594 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSGenerator.java,v $ -// $RCSfile: LOSGenerator.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/12/09 21:09:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.Color; -import java.awt.Point; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.dataAccess.dted.DTEDFrameCache; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressListener; -import com.bbn.openmap.event.ProgressSupport; -import com.bbn.openmap.gui.ProgressListenerGauge; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.SwingWorker; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The LOSGenerator uses gestures to create a mask over the map. The - * circular mask of green pixels shows what places are within the - * sight of the center of the circle. Additional height can be added - * to the center of the circle via the TerrainLayer palette, to - * represent a tower, building, or aircraft. - */ -public class LOSGenerator implements TerrainTool { - - // These are used to control the algorithm type. Right now, the - // first two are eliminated, since the azimuth algorithm is - // faster - // and more precise. - final static int PRECISE = 0; - final static int GOODENOUGH = 1; - final static int AZIMUTH = 2; - - // RED - Color toolColor = new Color(255, 0, 0); - - // The colors of pixels - final static int INVISIBLE = 0; - final static int VISIBLE = 1; - final static int MAYBEVISIBLE = 2; - int[] colortable; - - Projection proj; - protected LOSStateMachine stateMachine; - TerrainLayer layer; - - /** Lat lon of the center of hte circle. */ - LatLonPoint LOScenterLLP; - /** The xy of the center of the circle. */ - Point LOScenterP = new Point(); - /** The height of the earth at the center point. */ - int LOScenterHeight; - /** The height of the object at the center point. */ - int LOSobjectHeight = 0; - /** The diameter of the circle of interest. */ - int LOSedge; - protected OMGraphicList graphics = new OMGraphicList(); - OMRaster LOSimage; // The image for the mask - OMCircle LOScirc; // The circle modified for the image definition - int LOSprecision; // The flag for the algorithm type - LatLonPoint LOSOffPagell = new LatLonPoint.Double(-79f, -170f); - Point LOSOffPagep1 = new Point(-10, -10); - - /** The thread worker used to create the Terrain images. */ - LOSWorker currentWorker; - /** - * Set when the projection has changed while a swing worker is - * gathering graphics, and we want him to stop early. - */ - protected boolean cancelled = false; - - protected ProgressSupport progressSupport; - - class LOSWorker extends SwingWorker { - /** Constructor used to create a worker thread. */ - public LOSWorker() {} - - /** - * Compute the value to be returned by the get - * method. - */ - public Object construct() { - Debug.message("terrain", layer.getName() + "|LOSWorker.construct()"); - layer.fireStatusUpdate(LayerStatusEvent.START_WORKING); - createLOSImage(); - return null; - } - - /** - * Called on the event dispatching thread (not on the worker - * thread) after the construct method has - * returned. - */ - public void finished() { - layer.fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - workerComplete(); - } - } - - /** - * Not the preferred way to create one of these. It's full of - * defaults. - */ - private LOSGenerator() { - init(); - } - - /** - * The creation of the tool starts here. The DTED data cache is - * passed in, along with a path to the dted directory to get more - * data if needed. - */ - public LOSGenerator(TerrainLayer tLayer) { - layer = tLayer; - init(); - } - - public synchronized OMGraphicList getGraphics() { - return graphics; - } - - public State getState() { - return stateMachine.getState(); - } - - public void init() { - progressSupport = new ProgressSupport(this); - addProgressListener(new ProgressListenerGauge("LOS Mask Creation")); - - // colortable - colortable = new int[3]; - colortable[INVISIBLE] = new Color(0, 0, 0, 0).getRGB(); - colortable[VISIBLE] = new Color(0, 255, 0, 255).getRGB(); - colortable[MAYBEVISIBLE] = new Color(255, 255, 0, 255).getRGB(); - - stateMachine = new LOSStateMachine(this); - - // set the graphics - reset(true, true); - graphics.add(LOSimage); - graphics.add(LOScirc); - - } - - public void doImage() { - // If there isn't a worker thread working on this already, - // create a thread that will do the real work. If there is - // a thread working on this, then set the cancelled flag - // in the layer. - if (currentWorker == null) { - currentWorker = new LOSWorker(); - currentWorker.execute(); - } else - setCancelled(true); - } - - /** - * The TerrainWorker calls this method on the layer when it is - * done working. If the calling worker is not the same as the - * "current" worker, then a new worker is created. - */ - protected synchronized void workerComplete() { - if (!isCancelled()) { - currentWorker = null; - layer.repaint(); - } else { - setCancelled(false); - currentWorker = new LOSWorker(); - currentWorker.execute(); - } - } - - /** - * Used to set the cancelled flag in the layer. The swing worker - * checks this once in a while to see if the projection has - * changed since it started working. If this is set to true, the - * swing worker quits when it is safe. - */ - public synchronized void setCancelled(boolean set) { - cancelled = set; - } - - /** Check to see if the cancelled flag has been set. */ - public synchronized boolean isCancelled() { - return cancelled; - } - - /** - * Without arguments, the reset() call makes both graphics go - * offscreen in their smallest size. - */ - public void reset() { - reset(true, true); - } - - /** - * Circ is for the circle to be reset, and image is for the image - * to be reset. Sometimes you only want one to be moved. - */ - public void reset(boolean circ, boolean image) { - graphics.clear(); - if (image) { - LOSimage = new OMRaster(LOSOffPagell.getLatitude(), LOSOffPagell.getLongitude(), LOSOffPagep1.x, LOSOffPagep1.y, 1, 1, new int[1]); - } - if (circ) { - LOScirc = new OMCircle(LOSOffPagell.getLatitude(), LOSOffPagell.getLongitude(), 1, 1); - LOScirc.setLinePaint(toolColor); - } - layer.repaint(); - stateMachine.reset(); - } - - /** - * Called on every getRectangle, in order to let the cache get - * sized right, and to reset the graphics if the scale changed - * (since they won't make sense. - */ - public void setScreenParameters(Projection p) { - //reset(true, true); - proj = p; - LOSprecision = AZIMUTH; - graphics.generate(proj); - } - - /** - * Takes the member settings and manages the creation of the - * image. A large vector of slope values are created, depending on - * the size of the circle, and how many pixels are around it. Each - * entry in the vector is the value of the largest slope value in - * that direction. The image is created from the inside out, pixel - * by pixel. The slope from the pixel to the center is calculated, - * and then compared with the value for that direction (in the - * vector). If the pixel's slope is larger, the point is visible, - * and is colored that way. The vector is updated, and the cycle - * continues. - */ - public synchronized void createLOSImage() { - if (Debug.debugging("los")) { - Debug.output("createLOSimage: Entered with diameter = " + LOSedge); - } - - if (layer == null || layer.frameCache == null) { - Debug.error("LOSGenerator: can't access the DTED data through the terrain layer."); - return; - } - - int squareRadius = LOSedge / 2 + 1; - int[] newPixels = new int[LOSedge * LOSedge]; - float[] azimuthVals = new float[8 * (squareRadius - 1)]; - // center point of raster - newPixels[((LOSedge / 2) * LOSedge) + squareRadius] = MAYBEVISIBLE; - - if (Debug.debugging("los")) { - Debug.output("createLOSimage: size of azimuth array = " - + azimuthVals.length); - } - - fireProgressUpdate(ProgressEvent.START, - "Building LOS Image Mask...", - 0, - 100); - int x, y; - boolean mark = false; - int markColor = colortable[INVISIBLE]; - int range; - float pix_arc_interval = (float) (2 * Math.PI / azimuthVals.length); - // Do this in a spiral, around the center point. - for (int round = 1; round < squareRadius; round++) { - if (Debug.debugging("los")) { - Debug.output("createLOSimage: round " + round); - } - y = LOScenterP.y - round; - x = LOScenterP.x - round; - - if (round == 1) { - mark = true; - markColor = colortable[MAYBEVISIBLE]; - } - - else - mark = false; - - if (LOSprecision == AZIMUTH) { // As of now, this is the - // only option - range = ((LOSedge * 4) - 4) / (round * 16); - for (; x < LOScenterP.x + round; x++) - // top - resolveImagePoint(x, - y, - newPixels, - azimuthVals, - range, - pix_arc_interval, - mark, - markColor); - for (; y < LOScenterP.y + round; y++) - // right - resolveImagePoint(x, - y, - newPixels, - azimuthVals, - range, - pix_arc_interval, - mark, - markColor); - for (; x > LOScenterP.x - round; x--) - // bottom - resolveImagePoint(x, - y, - newPixels, - azimuthVals, - range, - pix_arc_interval, - mark, - markColor); - for (; y > LOScenterP.y - round; y--) - // left - resolveImagePoint(x, - y, - newPixels, - azimuthVals, - range, - pix_arc_interval, - mark, - markColor); - } - - int whereWeAre = (int) (100f * ((float) round / (float) squareRadius)); - fireProgressUpdate(ProgressEvent.UPDATE, - "Analyzing data...", - whereWeAre, - 100); - - } - - fireProgressUpdate(ProgressEvent.UPDATE, "Creating Mask", 100, 100); - - LOSimage = new OMRaster(LOScenterLLP.getLatitude(), LOScenterLLP.getLongitude(), (-1 - LOSedge / 2), (-1 - LOSedge / 2), LOSedge, LOSedge, newPixels); - LOSimage.generate(proj); - graphics.clear(); - graphics.add(LOSimage); - - fireProgressUpdate(ProgressEvent.DONE, "LOS mask complete", 100, 100); - - if (Debug.debugging("los")) { - Debug.output("createLOSimage: Done..."); - } - } - - /** - * Calculates the color for each pixel. After is gets the slope - * value for that pixel, it manages the comparison to get the - * pixel colored correctly. - */ - protected void resolveImagePoint(int x, int y, int[] newPixels, - float[] azimuthVals, int range, - float pix_arc_interval, boolean mark, - int colorForMark) { - - int ox = LOScenterP.x - LOSedge / 2; - int oy = LOScenterP.y - LOSedge / 2; - int dist = TerrainLayer.numPixelsBetween(LOScenterP.x, - LOScenterP.y, - x, - y); - if (dist > (LOSedge - 1) / 2) { - mark = true; - colorForMark = INVISIBLE; - } - if (dist == (LOSedge - 1) / 2) { - mark = true; - colorForMark = MAYBEVISIBLE; - } - - // This needs to be before the next two lines after this - LatLonPoint cord = proj.inverse(x, y, new LatLonPoint.Double()); - x -= ox; - y -= oy; - - if (Debug.debugging("losdetail")) { - Debug.output("resolveImagePoint x = " + x + ", y = " + y); - } - - if (mark == true) { - newPixels[x + y * LOSedge] = colorForMark; - mark = false; - return; - } - - double arc_dist = LOScenterLLP.distance(cord); - double arc_angle = LOScenterLLP.azimuth(cord); - - double slope = calculateLOSslope(cord, arc_dist); - - int index = (int) Math.round(arc_angle / pix_arc_interval); - int maxIndex = (LOSedge * 4) - 4; // 4 corners out for - // redundancy - if (index < 0) - index += maxIndex; - else if (index >= maxIndex) - index -= maxIndex; - - if (Debug.debugging("losdetail")) { - Debug.output(" angle = " + arc_angle + ", index/maxIndex = " - + index + "/" + maxIndex + ", slope = " + slope - + " compared to slope[index]=" + azimuthVals[index]); - } - int color = colortable[INVISIBLE]; - if (azimuthVals[index] < slope) { - for (int i = (index - range); i < index + range - 1; i++) { - if (i < 0) - azimuthVals[maxIndex + i] = (float)slope; - else if (i >= maxIndex) - azimuthVals[i - maxIndex] = (float)slope; - else - azimuthVals[i] = (float)slope; - } - color = colortable[VISIBLE]; - } - if (Debug.debugging("losdetail")) { - Debug.output(" color = " + color); - } - newPixels[x + y * LOSedge] = color; - } - - /** - * CalculateLOSslope figures out the slope from the pixel to the - * center, in radians. The arc_dist is in radians, and is the - * radian arc distance of the point from the center point of the - * image, on the earth. This slope calculation does take the - * earth's curvature into account, based on the spherical model. - */ - protected double calculateLOSslope(LatLonPoint cord, double arc_dist) { - DTEDFrameCache frameCache = layer.frameCache; - - if (frameCache == null) { - return 0; - } - - int xyheight = frameCache.getElevation(cord.getLatitude(), - cord.getLongitude()); - double ret = 0; - double P = Math.sin(arc_dist) - * (xyheight + Planet.wgs84_earthEquatorialRadiusMeters); - - double xPrime = Math.cos(arc_dist) - * (xyheight + Planet.wgs84_earthEquatorialRadiusMeters); - - double bottom; - double cutoff = LOScenterHeight - + Planet.wgs84_earthEquatorialRadiusMeters; - - // Suggested changes, submitted by Mark Wigmore. Introduces - // use of doubles, and avoidance of PI/2 tan() calculations. - - bottom = cutoff - xPrime; - ret = MoreMath.HALF_PI_D - Math.atan(bottom / P); - return ret; - - // Old way... - // if (xPrime < cutoff) { - // bottom = cutoff - xPrime; - // ret = Math.atan(P/bottom); - - // } else if (xPrime == cutoff) { - // ret = MoreMath.HALF_PI_D; - - // } else if (xPrime > cutoff) { - // double C = xPrime - cutoff; - // double gamma = Math.atan(P/C); - // ret = Math.PI - gamma; - // } - - // return ret; - } - - /** - * Called when the circle is started. It starts the circle to be - * drawn, and sets the parameters that will be needed to figure - * out the image. - * - * @param event mouse event where the circle should be started. - */ - public void setCenter(MouseEvent event) { - graphics.clear(); - LOScenterP.x = event.getX(); - LOScenterP.y = event.getY(); - LOScenterLLP = proj.inverse(LOScenterP.x, LOScenterP.y, new LatLonPoint.Double()); - LOScenterHeight = LOSobjectHeight; - if (layer.frameCache != null) { - LOScenterHeight += layer.frameCache.getElevation(LOScenterLLP.getLatitude(), - LOScenterLLP.getLongitude()); - } - LOScirc.setLatLon(LOScenterLLP.getLatitude(), - LOScenterLLP.getLongitude()); - LOScirc.generate(proj); - - graphics.add(LOScirc); - } - - /** - * Used to modify the circle parameters with another mouse event. - * Takes care of resetting hte circle parameters and regenerating - * the circle. - */ - public void addLOSEvent(MouseEvent event) { - graphics.clear(); - LOSedge = TerrainLayer.numPixelsBetween(LOScenterP.x, - LOScenterP.y, - event.getX(), - event.getY()) * 2 + 1; - - LOScirc.setWidth(LOSedge); - LOScirc.setHeight(LOSedge); - LOScirc.generate(proj); - graphics.add(LOScirc); - } - - /** - * Sets the new object height to use at the center of the circle. - * The old object is subtracted out first to get the center height - * of the ground before the new value is added. - * - * @param value height of the object in meters. - */ - public void setLOSobjectHeight(int value) { - LOScenterHeight -= LOSobjectHeight; - LOSobjectHeight = value; - LOScenterHeight += LOSobjectHeight; - } - - /** - * Add a ProgressListener that will display build progress. - */ - public void addProgressListener(ProgressListener list) { - progressSupport.add(list); - } - - /** - * Remove a ProgressListener that displayed build progress. - */ - public void removeProgressListener(ProgressListener list) { - progressSupport.remove(list); - } - - /** - * Clear all progress listeners. - */ - public void clearProgressListeners() { - progressSupport.clear(); - } - - /** - * Fire an build update to progress listeners. - * - * @param frameNumber the current frame count - * @param totalFrames the total number of frames. - */ - protected void fireProgressUpdate(int type, String task, int frameNumber, - int totalFrames) { - progressSupport.fireUpdate(type, task, totalFrames, frameNumber); - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java deleted file mode 100644 index 3e0c17979..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java +++ /dev/null @@ -1,60 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSStateMachine.java,v -// $ -// $RCSfile: LOSStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import com.bbn.openmap.util.stateMachine.State; -import com.bbn.openmap.util.stateMachine.StateMachine; - -class LOSStateMachine extends StateMachine { - - public LOSGenerator losg; - public static final int TOOL_DO_NOTHING = 0; - public static final int TOOL_DRAW = 1; - public static final int TOOL_DEFINED = 2; - public static final int TOOL_VIEW = 3; - - public LOSStateMachine(LOSGenerator generator) { - losg = generator; - State[] losStates = init(); - setStates(losStates); - - // set reset state - setResetState(TOOL_DO_NOTHING); - reset(); - setMapMouseListenerResponses(true); - } - - protected State[] init() { - State[] LOSStates = new State[4]; - - LOSStates[TOOL_DO_NOTHING] = new LOSDoNothingState(losg); - LOSStates[TOOL_DRAW] = new LOSDrawState(losg); - LOSStates[TOOL_DEFINED] = new LOSDefinedState(losg); - LOSStates[TOOL_VIEW] = new LOSViewState(losg); - - return LOSStates; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSViewState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSViewState.java deleted file mode 100644 index f0ae544c9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/LOSViewState.java +++ /dev/null @@ -1,48 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSViewState.java,v -// $ -// $RCSfile: LOSViewState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.ActionEvent; - -import com.bbn.openmap.util.stateMachine.State; - -class LOSViewState extends State { - - protected LOSGenerator LOSTool; - - public LOSViewState(LOSGenerator tool) { - LOSTool = tool; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(TerrainLayer.createCommand)) { - LOSTool.doImage(); - } else if (ac.equalsIgnoreCase(TerrainLayer.clearCommand)) { - LOSTool.reset(); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDefinedState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDefinedState.java deleted file mode 100644 index 3ae44787d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDefinedState.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileDefinedState.java,v -// $ -// $RCSfile: ProfileDefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.util.stateMachine.State; - -class ProfileDefinedState extends State { - - protected ProfileGenerator profileTool; - - public ProfileDefinedState(ProfileGenerator tool) { - profileTool = tool; - } - - public boolean mousePressed(MouseEvent e) { - profileTool.reset(); - return true; - } - - public boolean mouseReleased(MouseEvent e) { - profileTool.reset(); - return true; - } - - public boolean mouseClicked(MouseEvent e) { - profileTool.reset(); - return true; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(TerrainLayer.createCommand)) { - profileTool.layer.fireStatusUpdate(LayerStatusEvent.START_WORKING); - profileTool.createProfileImage(); - profileTool.stateMachine.setState(ProfileStateMachine.TOOL_VIEW); - profileTool.layer.fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } else - profileTool.reset(); - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDoNothingState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDoNothingState.java deleted file mode 100644 index 4fa66e780..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDoNothingState.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileDoNothingState.java,v -// $ -// $RCSfile: ProfileDoNothingState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.util.stateMachine.State; - -class ProfileDoNothingState extends State { - - protected ProfileGenerator profileTool; - - public ProfileDoNothingState(ProfileGenerator tool) { - profileTool = tool; - } - - public boolean mousePressed(MouseEvent e) { - profileTool.addProfileEvent(e); - profileTool.stateMachine.setState(ProfileStateMachine.TOOL_DRAW); - return true; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDrawState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDrawState.java deleted file mode 100644 index 263c5908a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileDrawState.java +++ /dev/null @@ -1,72 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileDrawState.java,v -// $ -// $RCSfile: ProfileDrawState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.util.stateMachine.State; - -class ProfileDrawState extends State { - - protected ProfileGenerator profileTool; - - public ProfileDrawState(ProfileGenerator tool) { - profileTool = tool; - } - - public boolean mouseReleased(MouseEvent e) { - profileTool.addProfileEvent(e); - profileTool.layer.repaint(); - return true; - } - - public boolean mouseDragged(MouseEvent e) { - profileTool.addProfileEvent(e); - profileTool.layer.repaint(); - return true; - } - - public boolean mouseClicked(MouseEvent e) { - if (e.getClickCount() > 1) { - profileTool.stateMachine.setState(ProfileStateMachine.TOOL_DEFINED); - } - return true; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(TerrainLayer.createCommand)) { - profileTool.layer.fireStatusUpdate(LayerStatusEvent.START_WORKING); - profileTool.createProfileImage(); - profileTool.stateMachine.setState(ProfileStateMachine.TOOL_VIEW); - profileTool.layer.fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } else if (ac.equalsIgnoreCase(TerrainLayer.clearCommand)) { - profileTool.reset(); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileGenerator.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileGenerator.java deleted file mode 100644 index 9b82d5e77..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileGenerator.java +++ /dev/null @@ -1,455 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileGenerator.java,v $ -// $RCSfile: ProfileGenerator.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.Color; -import java.awt.FontMetrics; -import java.awt.Point; -import java.awt.event.ComponentListener; -import java.awt.event.MouseEvent; -import java.util.Vector; - -import com.bbn.openmap.dataAccess.dted.DTEDFrameCache; -import com.bbn.openmap.image.AcmeGifFormatter; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * This tool lets the user draw a line on the map, and then presents - * the profile of the path in a GIF picture. The line can be drawn in - * a series if clicks, or the mouse button can be held down as the - * mouse is dragged around. The lines are drawn as great circle lines, - * which represent the straight geographical line between clicks. - * - *

- * The profile tool uses the ProfileStateMachine, and the Profile - * States, to keep track of the proper actions and reactions of user - * input. - */ -public class ProfileGenerator implements TerrainTool { - /** The color of the line that is drawn on the screen. */ - Color toolColor = new Color(255, 0, 0); - /** The state machine for user gestures. */ - protected ProfileStateMachine stateMachine; - /** The layer that the tool is serving. */ - protected TerrainLayer layer; - /** The list of graphics to draw. Contains the drawn line. */ - protected OMGraphicList graphics = new OMGraphicList(); - /** - * Array of LatLonPoints. The points are the clicked points, and - * the points in between, on a great circle. Have to figure these - * points out, and not rely only on the poly line points, because - * we need to get the elevations for all the points for the - * profile. - */ - public Vector coords; - /** - * These are the raw x-y points of the gestures, for the great - * circle line points, too. These are used to construct the - * profile image. An array of java.awt.Points. - */ - public Vector xypoints; - /** - * The line drawn on the screen representing the profile line - * path. - */ - public OMPoly profileLine; - /** - * General gesture tracking, Used to track the last place of - * interest on the screen for the creation of hte profile. - */ - MouseEvent lastMouse; - /** - * A copy of the most current projection to use to update the - * drawn line. - */ - Projection proj; - - public ProfileGenerator(TerrainLayer tLayer) { - layer = tLayer; - init(); - } - - public synchronized OMGraphicList getGraphics() { - profileLine.setLocation(setLLPoints(), OMGraphic.RADIANS); - profileLine.generate(proj); - return graphics; - } - - /** - * Create the line object, the state machine, and the vectors used - * to keep track of the line being drawn. - */ - public void init() { - lastMouse = null; - - coords = new Vector(); - xypoints = new Vector(); - - profileLine = new OMPoly(setLLPoints(), OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - profileLine.setLinePaint(toolColor); - - graphics.add(profileLine); - // System.loadLibrary("com_bbn_openmap_terrain_ProfileGenerator"); - - stateMachine = new ProfileStateMachine(this); - } - - /** - * Clears the line from the screen, and resets the state machine. - */ - public void reset() { - coords.removeAllElements(); - xypoints.removeAllElements(); - profileLine.setLocation(setLLPoints(), OMGraphic.RADIANS); - stateMachine.reset(); - layer.repaint(); - lastMouse = null; - } - - public void setScreenParameters(Projection p) { - proj = p; - graphics.generate(p); - } - - /** - * Returns a set of lat lon points that represent the line as it - * was drawn. The lat lon points are in an array of floats, that - * alternate, lat, lon, etc. - */ - public double[] setLLPoints() { - double[] points; - int num_points = coords.size(); - - if (num_points <= 1) { - - points = new double[4]; - if (num_points == 0) { - points[0] = 0f; - points[1] = -6f; - } else { - points[0] = ((LatLonPoint) coords.elementAt(0)).getRadLat(); - points[1] = ((LatLonPoint) coords.elementAt(0)).getRadLon(); - } - - points[2] = points[0]; - points[3] = points[1]; - } else { - points = new double[coords.size() * 2]; - for (int i = 0; i < coords.size(); i++) { - points[i * 2] = (float)((LatLonPoint) coords.elementAt(i)).getRadLat(); - points[(i * 2) + 1] = (float)((LatLonPoint) coords.elementAt(i)).getRadLon(); - } - } - return points; - } - - /** - * Returns the current state of the state machine. - */ - public State getState() { - return stateMachine.getState(); - } - - /** - * Creates the line points for the path drawn on the screen, and - * collects the elevation values for those points. Makes the call - * to write the new gif file to disk. - */ - public void createProfileImage() { - - Debug.message("terrain", - "ProfileGenerator:createProfileImage(): Creating image"); - - if (layer == null || layer.frameCache == null) { - Debug.error("ProfileGenerator: can't access the DTED data through the terrain layer."); - return; - } - - // Set the final line, as it was drawn. - profileLine.setLocation(setLLPoints(), OMGraphic.RADIANS); - - int total_distance = 0; - int[] distances = new int[xypoints.size()]; - Point tmpPoint1, tmpPoint2; - distances[0] = 0; - for (int j = 1; j < xypoints.size(); j++) { - tmpPoint1 = (Point) xypoints.elementAt(j); - tmpPoint2 = (Point) xypoints.elementAt(j - 1); - // Needed for the GIF, the number of pixels (distance) - // between points of the line. The distances array is the - // distance between this point and the next in the xy - // point array. - distances[j] = TerrainLayer.numPixelsBetween(tmpPoint1.x, - tmpPoint1.y, - tmpPoint2.x, - tmpPoint2.y); - total_distance += distances[j]; - } - - int tmp = 0; - int max = 0; - int[] heights = new int[xypoints.size()]; - // Go through the points and get the heights - for (int i = 0; i < heights.length; i++) { - LatLonPoint llp = ((LatLonPoint) coords.elementAt(i)); - // Ask the cache for the elevation - tmp = layer.frameCache.getElevation(llp.getLatitude(), - llp.getLongitude()); - - if (tmp == DTEDFrameCache.NO_DATA) - tmp = -1; - if (tmp > max) - max = tmp; - heights[i] = tmp; - } - // get the picture drawn and written - createGIFFile(total_distance, max, distances, heights); - } - - /** - * Create the image and write it the location. - * - * @param distance total length of line, in pixels - * @param max highest point, in meters of all the heights in the - * line. - * @param post_dist array of pixel distances between the points - * @param post_height the array of heights - */ - protected void createGIFFile(int distance, int max, int[] post_dist, - int[] post_height) { - - int box_height_buffer = 20; - int gif_height_buffer = 20; - int gif_width_buffer = 20; - int text_width = 100; - - int box_height = max + (box_height_buffer * 2); - int box_width = distance; - int gif_height = box_height + (gif_height_buffer * 2); - int gif_width = box_width + (gif_width_buffer * 2) + text_width; - - AcmeGifFormatter formatter = new AcmeGifFormatter(); - java.awt.Graphics graphics = formatter.getGraphics(gif_width, - gif_height); - -// Color gray10 = new Color(25, 25, 25); - Color gray50 = new Color(128, 128, 128); -// Color gray75 = new Color(191, 191, 191); - Color gray90 = new Color(230, 230, 230); - - Debug.message("terrain", - "ProfileGenerator gif creation: drawing boundaries"); - /* Fill in the generic colors */ - graphics.setColor(gray90); - graphics.fillRect(0, 0, gif_width, gif_height); - - graphics.setColor(gray50); - graphics.fillRect(gif_width_buffer, - gif_height_buffer, - box_width, - box_height); - - Debug.message("terrain", "ProfileGenerator gif creation: drawing edges"); - // outside edge - graphics.setColor(Color.black); - graphics.drawRect(0, 0, gif_width - 1, gif_height - 1); - // inside edge - graphics.drawRect(gif_width_buffer, - gif_height_buffer, - box_width, - box_height); - - graphics.setColor(Color.yellow); - // 0 height line - graphics.drawLine(gif_width_buffer + 1, - gif_height_buffer + box_height - box_height_buffer, - gif_width_buffer + box_width - 1, - gif_height_buffer + box_height - box_height_buffer); - - // These are the horizontal reference lines in the image. - graphics.setColor(Color.black); - FontMetrics f = graphics.getFontMetrics(); - - Debug.message("terrain", - "ProfileGenerator gif creation: drawing level lines"); - for (int i = 1; i < 9; i++) { - - graphics.drawLine(gif_width_buffer, gif_height_buffer + box_height - - box_height_buffer - (max * i / 8), gif_width_buffer - + box_width + 5, gif_height_buffer + box_height - - box_height_buffer - (max * i / 8)); - - int meters = max * i / 8; - int feet = (int) (meters * 3.2); - String lineLabel = meters + "m / " + feet + "ft"; -// byte[] lineLabelBytes = lineLabel.getBytes(); - - graphics.drawString(lineLabel, - gif_width_buffer + box_width + 10, - gif_height_buffer + box_height - box_height_buffer - - (max * i / 8) + (f.getAscent() / 2)); - } - -// int last_x = gif_width_buffer + 1; -// int last_height = gif_height_buffer + box_height - box_height_buffer -// - post_height[0]; - - int total_distance = 0; - Debug.message("terrain", - "ProfileGenerator gif creation: drawing profile"); - - graphics.setColor(Color.red); - for (int i = 1; i < post_height.length; i++) { - graphics.drawLine(gif_width_buffer + total_distance, - gif_height_buffer + box_height - box_height_buffer - - post_height[i - 1], - gif_width_buffer + post_dist[i] + total_distance, - gif_height_buffer + box_height - box_height_buffer - - post_height[i]); - - total_distance += post_dist[i]; - } - - javax.swing.ImageIcon ii = new javax.swing.ImageIcon(formatter.getBufferedImage()); - javax.swing.JFrame jf = com.bbn.openmap.util.PaletteHelper.getPaletteWindow(new javax.swing.JLabel(ii), - "Path Profile", - (ComponentListener) null); - - jf.setVisible(true); - - // byte[] imageBytes = formatter.getImageBytes(); - // String tmppath = null; - // try { - // String tmpDir = Environment.get(Environment.TmpDir); - // if (tmpDir != null) { - // tmppath = tmpDir + File.separator + "openmap-" + - // Environment.timestamp() + ".gif"; - // FileOutputStream fs = new FileOutputStream(tmppath); - // fs.write(imageBytes); - // fs.close(); // close the streams - - // String url = "file://" + tmppath; - // layer.fireRequestURL(url); - // } else { - // Debug.error("ProfileGenerator: can't create image file, - // because the openmap.TempDirectory was not set."); - // } - // } catch (IOException e) { - // Debug.error("ProfileGenerator: Cannot write to temp file:" - // + - // Environment.get("line.separator") + - // "\"" + tmppath + "\""); - // } - // String imageString = new String(imageBytes); - // layer.fireRequestBrowserContent(imageString); - } - - /** - * Used to keep track of another point for the line, as determined - * by the state machine. - * - * @param event Mouse event that supplies the location - */ - protected void addProfileEvent(MouseEvent event) { - LatLonPoint llp = proj.inverse(event.getX(), event.getY(), new LatLonPoint.Double()); - if (lastMouse != null) { - // Check for proximity of the click, since a double - // click means the end of the line. - if ((Math.abs(lastMouse.getX() - event.getX()) > MAX_SPACE_BETWEEN_PIXELS) - || (Math.abs(lastMouse.getY() - event.getY()) > MAX_SPACE_BETWEEN_PIXELS)) { - // The line may need to be broken up into smaller - // segments in order for it to be a true straight - // line, to figure out the segments. The interior - // points are added to the vector. - addGreatCirclePoints(lastMouse, event); - // Now add the end point to the vector - coords.addElement(llp); - // The xy points don't need the interior points, the - // line gets these points and figures them out for - // itself. This may be redundant is some way. - xypoints.addElement(event.getPoint()); - } - } else { - coords.addElement(llp); - xypoints.addElement(event.getPoint()); - } - lastMouse = event; - // Reset the line to have all the new points - profileLine.setLocation(setLLPoints(), OMGraphic.RADIANS); - profileLine.generate(proj); - } - - /** - * Figure out the internal points to create a great circle line - * between two points on the screen. The interior points are added - * to the coords array, but not to the xy points array. - * - * @param beginning the starting mouse event - * @param ending the ending mouse event - */ - protected void addGreatCirclePoints(MouseEvent beginning, MouseEvent ending) { - LatLonPoint beg = proj.inverse(beginning.getX(), beginning.getY(), new LatLonPoint.Double()); - LatLonPoint end = proj.inverse(ending.getX(), ending.getY(), new LatLonPoint.Double()); - - int num_points = (TerrainLayer.numPixelsBetween(beginning.getX(), - beginning.getY(), - ending.getX(), - ending.getY()) - 2) - / MAX_SPACE_BETWEEN_PIXELS; - - float[] radPoints = GreatCircle.greatCircle((float)beg.getRadLat(), - (float)beg.getRadLon(), - (float)end.getRadLat(), - (float)end.getRadLon(), - num_points, - true); - boolean geoProj = proj instanceof GeoProj; - for (int i = 0; i < radPoints.length; i++) { - coords.addElement(new LatLonPoint.Double(radPoints[i], radPoints[i + 1], true)); - Point pt = new Point(); - if (geoProj) { - ((GeoProj)proj).forward(radPoints[i], radPoints[i + 1], pt, true); - } else { - proj.forward(Math.toDegrees(radPoints[i]), Math.toDegrees(radPoints[i + 1]), pt); - } - xypoints.addElement(pt); - - // System.out.println("addCGPoints: point " + i + " lat=" - // + - // RadianPoint.radToDeg(radPoints[i].lat) + ", lon=" + - // RadianPoint.radToDeg(radPoints[i].lon) + ", x=" + - // (short)pt.x + ", y=" + (short)pt.y); - i++; - } - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileStateMachine.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileStateMachine.java deleted file mode 100644 index c8a0ded4e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileStateMachine.java +++ /dev/null @@ -1,60 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileStateMachine.java,v -// $ -// $RCSfile: ProfileStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import com.bbn.openmap.util.stateMachine.State; -import com.bbn.openmap.util.stateMachine.StateMachine; - -class ProfileStateMachine extends StateMachine { - - public ProfileGenerator pg; - public static final int TOOL_DO_NOTHING = 0; - public static final int TOOL_DRAW = 1; - public static final int TOOL_DEFINED = 2; - public static final int TOOL_VIEW = 3; - - public ProfileStateMachine(ProfileGenerator generator) { - pg = generator; - State[] profileStates = init(); - setStates(profileStates); - - // set reset state - setResetState(TOOL_DO_NOTHING); - reset(); - setMapMouseListenerResponses(true); - } - - protected State[] init() { - State[] pStates = new State[4]; - - pStates[TOOL_DO_NOTHING] = new ProfileDoNothingState(pg); - pStates[TOOL_DRAW] = new ProfileDrawState(pg); - pStates[TOOL_DEFINED] = new ProfileDefinedState(pg); - pStates[TOOL_VIEW] = new ProfileViewState(pg); - - return pStates; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileViewState.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileViewState.java deleted file mode 100644 index 00f935384..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/ProfileViewState.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/ProfileViewState.java,v -// $ -// $RCSfile: ProfileViewState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import java.awt.event.ActionEvent; - -import com.bbn.openmap.util.stateMachine.State; - -class ProfileViewState extends State { - - protected ProfileGenerator profileTool; - - public ProfileViewState(ProfileGenerator tool) { - profileTool = tool; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(TerrainLayer.clearCommand)) { - profileTool.reset(); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainLayer.java deleted file mode 100644 index 0f98b1e7a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainLayer.java +++ /dev/null @@ -1,404 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/TerrainLayer.java,v $ -// $RCSfile: TerrainLayer.java,v $ -// $Revision: 1.10 $ -// $Date: 2005/08/09 18:50:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; - -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.dataAccess.dted.DTEDFrameCache; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The Terrain Layer is an example of creating a layer that acts as a tool that - * defines and area (via user gestures) and presents a result of the analysis of - * the data. In this case, Elevation data is used in two different ways. The - * Profile tool lets you draw a line on the map, and then uses DTED data to - * create a GIF image that shows the terrain profile along the drawn line. The - * LOS (line-of-sight) tool lets you define a circle, and then calculates the - * places on the ground that are within sight of the center of the circle. The - * result is shown with the visible points being colored green, and all other - * points being clear. The LOS tool lets you use a height slider on its palette - * to define additional height at the point, representing a tower, building, or - * location of an aircraft. - * - *

- * The tools require you to be in the gesture mode of OpenMap. - * - *

- * The TerrainLayer needs a DTEDFrameCache. It can be added to the layer - * programmatically, or the layer will find it if the DTEDFrameCache is added to - * the MapHandler. To do that in the OpenMap application, add the DTEDFrameCache - * to the openmap.components property in the openmap.properties file. - * - *

- * 
- *  #----------------------------------------------------------------------
- *  # Properties file for TerrainLayer
- *  #----------------------------------------------------------------------
- *  # The default tool to use for the terrain layer.  Can be PROFILE or LOS.  
- *  terrain.default.mode=PROFILE
- *  #----------------------------------------------------------------------
- *  # End of properties file for TerrainLayer
- *  #----------------------------------------------------------------------
- * 
- * 
- * - * @see com.bbn.openmap.dataAccess.dted.DTEDFrameCache - */ -public class TerrainLayer extends OMGraphicHandlerLayer implements ActionListener, MapMouseListener { - /** The cache that knows how to handle DTED requests. */ - public DTEDFrameCache frameCache; - - /** Which tool is being used. */ - protected int mode; - /** The code number for the profile tool. */ - public final static int PROFILE = 0; - /** The code number for the perspective tool (unimplemented). */ - public final static int PERSPECTIVE = 1; - /** The code number for the LOS tool. */ - public final static int LOS = 2; - /** The current tool being used. */ - public TerrainTool currentTool; - public ProfileGenerator profileTool; - public LOSGenerator LOSTool; - - public static final String defaultModeProperty = "default.mode"; - - public final static String clearCommand = "clearTool"; - public final static String createCommand = "createTool"; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public TerrainLayer() { - setName("Terrain"); - init(); - } - - /** Creates new tools. */ - public void init() { - profileTool = new ProfileGenerator(this); - LOSTool = new LOSGenerator(this); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - } - - /** - * Sets the default values for the variables, if the properties are not - * found, or are invalid. Usually not a good idea. - */ - protected void setDefaultValues() { - mode = PROFILE; - } - - public void setFrameCache(DTEDFrameCache dfc) { - frameCache = dfc; - } - - public DTEDFrameCache getFrameCache() { - return frameCache; - } - - /** - * Set all the TerrainLayer properties from a properties object - * - * @param prefix a string that gets set to individualize the properties to a - * specific layer. - * @param properties the properties object - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - setDefaultValues(); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String defaultModeString = properties.getProperty(prefix + defaultModeProperty, "PROFILE"); - if (defaultModeString.equalsIgnoreCase("LOS")) { - setMode(LOS); - } else { - setMode(PROFILE); - } - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the dted. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - System.err.println("Terrain Layer needs to be added to the MapBean before it can be used!"); - return new OMGraphicList(); - } - - Debug.message("basic", getName() + "|TerrainLayer.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - profileTool.setScreenParameters(projection); - LOSTool.setScreenParameters(projection); - return currentTool.getGraphics(); - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - - /** The user interface palette for the Terrain layer. */ - protected Box paletteBox = null; - private String profileCommand = "setModeToProfile"; - private String losCommand = "setModeToLos"; - - /** Creates the interface palette. */ - public java.awt.Component getGUI() { - - if (paletteBox == null) { - if (Debug.debugging("terrain")) - System.out.println("TerrainLayer: creating Terrain Palette."); - - paletteBox = Box.createVerticalBox(); - - // palette = new JPanel(); - // palette.setLayout(new GridLayout(0, 1)); - - // The Terrain Level selector - JPanel modePanel = PaletteHelper.createPaletteJPanel("Tool Mode"); - ButtonGroup modes = new ButtonGroup(); - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(losCommand)) { - setMode(LOS); - } else { - setMode(PROFILE); - } - } - }; - - JRadioButton profileModeButton = new JRadioButton("Profile"); - profileModeButton.addActionListener(al); - profileModeButton.setActionCommand(profileCommand); - JRadioButton losModeButton = new JRadioButton("LOS"); - losModeButton.addActionListener(al); - losModeButton.setActionCommand(losCommand); - - modes.add(profileModeButton); - modes.add(losModeButton); - - switch (mode) { - case LOS: - losModeButton.setSelected(true); - break; - case PROFILE: - default: - profileModeButton.setSelected(true); - } - - modePanel.add(profileModeButton); - modePanel.add(losModeButton); - - // The LOS Height Adjuster - JPanel centerHeightPanel = PaletteHelper.createPaletteJPanel("LOS Center Object Height"); - JSlider centerHeightSlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 500/* max */, 0/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(0), new JLabel("0 ft")); - dict.put(new Integer(500), new JLabel("500 ft")); - centerHeightSlide.setLabelTable(dict); - centerHeightSlide.setPaintLabels(true); - centerHeightSlide.setMajorTickSpacing(50); - centerHeightSlide.setPaintTicks(true); - centerHeightSlide.setSnapToTicks(false); - centerHeightSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - fireRequestInfoLine("TerrainLayer - center height value = " - + slider.getValue()); - LOSTool.setLOSobjectHeight(slider.getValue()); - } - } - }); - centerHeightPanel.add(centerHeightSlide); - - JPanel profileControlPanel = PaletteHelper.createPaletteJPanel("Tool Commands"); - JButton clearButton = new JButton("Clear/Reset Tool"); - clearButton.setActionCommand(clearCommand); - clearButton.addActionListener(this); - JButton createButton = new JButton("Create"); - createButton.setActionCommand(createCommand); - createButton.addActionListener(this); - - profileControlPanel.add(clearButton); - profileControlPanel.add(createButton); - - JButton redraw = new JButton("Redraw Terrain Layer"); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - - paletteBox.add(modePanel); - paletteBox.add(centerHeightPanel); - paletteBox.add(profileControlPanel); - // palette.add(redraw); - } - - return paletteBox; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * The reaction handler for the buttons being pressed on the palette. - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String ac = e.getActionCommand(); - if (ac.equalsIgnoreCase(RedrawCmd)) { - doPrepare(); - } else { - currentTool.getState().actionPerformed(e); - } - } - - // ---------------------------------------------------------------------- - // MapMouseListener interface implementation - // ---------------------------------------------------------------------- - - public synchronized MapMouseListener getMapMouseListener() { - return this; - } - - /** - * Tells the MouseDelegator which Mouse Modes we're interested in receiving - * events from. In this case, just the "Gestures" mode. - */ - public String[] getMouseModeServiceList() { - String[] services = { SelectMouseMode.modeID }; - return services; - } - - public boolean mousePressed(MouseEvent e) { - return currentTool.getState().mousePressed(e); - } - - public boolean mouseReleased(MouseEvent e) { - return currentTool.getState().mouseReleased(e); - } - - public boolean mouseClicked(MouseEvent e) { - return currentTool.getState().mouseClicked(e); - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public boolean mouseDragged(MouseEvent e) { - return currentTool.getState().mouseDragged(e); - } - - public boolean mouseMoved(MouseEvent e) { - return false; - } - - public void mouseMoved() { - } - - /** - * Little math utility that both tools use, that just implements the - * pythagorean theorem to do the number of pixels between two screen points. - */ - public static int numPixelsBetween(int x1, int y1, int x2, int y2) { - return (int) Math.sqrt(Math.pow((double) (x1 - x2), 2.0) - + Math.pow((double) (y1 - y2), 2.0)); - } - - /** Set the current tool to be used. */ - public void setMode(int m) { - mode = m; - if (currentTool != null) - currentTool.reset(); - if (m == PROFILE) { - currentTool = profileTool; - // System.out.println("Changing mode to PROFILE"); - } - if (m == LOS) { - currentTool = LOSTool; - // System.out.println("Changing mode to LOS"); - } - if (currentTool != null) { - currentTool.reset(); - setList(currentTool.getGraphics()); - } - } - - public int getMode() { - return mode; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof DTEDFrameCache) { - setFrameCache((DTEDFrameCache) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj == getFrameCache()) { - setFrameCache(null); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainTool.java b/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainTool.java deleted file mode 100644 index 51be08fd0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/TerrainTool.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/TerrainTool.java,v $ -// $RCSfile: TerrainTool.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.terrain; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.stateMachine.State; - -/** - * This is a interface that defines common functionality among tools - * (generators) used by the TerrainLayer. - */ -public interface TerrainTool { - - final static int MAX_SPACE_BETWEEN_PIXELS = 5; - - /** Tell the tool to initialize. */ - public void init(); - - /** Tell the tool to reset. */ - public void reset(); - - /** Get the current list of graphics from the tool. */ - public OMGraphicList getGraphics(); - - /** Let the tool know what the screen looks like. */ - public void setScreenParameters(Projection p); - - /** Get the current state from the state machine of the tool. */ - public State getState(); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/terrain/package.html b/src/core/src/main/java/com/bbn/openmap/layer/terrain/package.html deleted file mode 100644 index 71dad650e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/terrain/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains the TerrainLayer, which lets you run LOS and -path elevation profile queries over the map. - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/BoundsTestLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/BoundsTestLayer.java deleted file mode 100644 index 61d8fcf94..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/BoundsTestLayer.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.bbn.openmap.layer.test; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.DataBounds; - -/** - * A little layer to test out the DataBounds intersections. You draw OMRects - * using the drawing tool, and any rectangles that overlap fill up with red. - * - * @author dietrick - */ -public class BoundsTestLayer extends OMGraphicHandlerLayer implements DrawingToolRequestor { - - /** - * - */ - private static final long serialVersionUID = 1L; - OMGraphicList holder = new OMGraphicList(); - OMDrawingTool drawingTool = null; - String BOUNDS = "bounds"; - String HIT = "hit"; - - public BoundsTestLayer() { - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - public OMGraphicList prepare() { - - OMGraphicList list = new OMGraphicList(); - list.addAll(holder); - - for (OMGraphic omg : holder) { - omg.removeAttribute(HIT); - omg.setFillPaint(OMColor.clear); - } - - for (OMGraphic omg : holder) { - if (omg instanceof OMRect) { - DataBounds bnds = (DataBounds) omg.getAttribute(BOUNDS); - - for (OMGraphic omg2 : list) { - if (omg2 instanceof OMRect && !omg.equals(omg2)) { - DataBounds bnds2 = (DataBounds) omg2.getAttribute(BOUNDS); - - if (bnds.intersects(bnds2)) { - omg.putAttribute(HIT, true); - omg2.putAttribute(HIT, true); - } - } - } - } - } - - for (OMGraphic omg : holder) { - if (omg.getAttribute(HIT) != null) { - omg.setFillPaint(OMColor.red); - } - } - - list.generate(getProjection()); - return list; - } - - public void findAndInit(Object obj) { - super.findAndInit(obj); - - if (obj instanceof OMDrawingTool) { - drawingTool = (OMDrawingTool) obj; - } - } - - public boolean isSelectable(OMGraphic omg) { - return (drawingTool != null && drawingTool.canEdit(omg.getClass())); - } - - /** - * Called if isSelectable(OMGraphic) was true, so the list has the - * OMGraphic. A list is used in case underlying code is written to handle - * more than one OMGraphic being selected at a time. - */ - public void select(OMGraphicList list) { - if (list != null && !list.isEmpty()) { - OMGraphic omg = list.getOMGraphicAt(0); - - if (drawingTool != null && drawingTool.canEdit(omg.getClass())) { - drawingTool.setBehaviorMask(OMDrawingTool.QUICK_CHANGE_BEHAVIOR_MASK); - if (drawingTool.edit(omg, this) == null) { - // Shouldn't see this because we checked, but ... - fireRequestInfoLine("Can't figure out how to modify this object."); - } - } - } - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.tools.drawing.DrawingToolRequestor#drawingComplete(com - * .bbn.openmap.omGraphics.OMGraphic, com.bbn.openmap.omGraphics.OMAction) - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - if (omg instanceof OMRect) { - OMRect rect = (OMRect) omg; - DataBounds bounds = new DataBounds(rect.getWestLon(), rect.getNorthLat(), rect.getEastLon(), rect.getSouthLat()); - rect.putAttribute(BOUNDS, bounds); - } - holder.doAction(omg, action); - doPrepare(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/DemoLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/DemoLayer.java deleted file mode 100644 index 2bfabb21b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/DemoLayer.java +++ /dev/null @@ -1,1176 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/DemoLayer.java,v $ -// $RCSfile: DemoLayer.java,v $ -// $Revision: 1.25 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.test; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.GeneralPath; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JSeparator; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.BufferedImageRenderPolicy; -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.FontSizer; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMArc; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMArrowHead; -import com.bbn.openmap.omGraphics.OMBitmap; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMDecoratedSpline; -import com.bbn.openmap.omGraphics.OMEllipse; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.omGraphics.OMShape; -import com.bbn.openmap.omGraphics.OMSpline; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextBalloon; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.omGraphics.awt.CircleShapeDecoration; -import com.bbn.openmap.omGraphics.awt.LineShapeDecoration; -import com.bbn.openmap.omGraphics.awt.ShapeDecorator; -import com.bbn.openmap.omGraphics.labeled.LabeledOMSpline; -import com.bbn.openmap.omGraphics.meteo.IceAreaShapeDecoration; -import com.bbn.openmap.omGraphics.meteo.OMHotSurfaceFront; -import com.bbn.openmap.omGraphics.meteo.OMOcclusion; -import com.bbn.openmap.omGraphics.util.ArcCalc; -import com.bbn.openmap.omGraphics.util.RibbonMaker; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.drawing.DrawingTool; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.tools.symbology.milStd2525.SymbolPart; -import com.bbn.openmap.tools.symbology.milStd2525.SymbolReferenceLibrary; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * This layer demonstrates interactive capabilities of OpenMap. Instantiating - * this layer should show an icon loaded using HTTP Protocol, which represents - * Boston, MA in USA. Above Boston it should show a square that would change - * color when mouse is moved over it in 'Gesture' mode. Also clicking once - * brings up a message box and more than once brings up browser. - *

- * - * The DemoLayer has also been modified to demonstrate the first uses of the - * OMDrawingTool. The Palette has buttons that can be used to start the tool in - * several different ways. - * - * @see com.bbn.openmap.layer.test.DemoLayer - * - * Just added some decorated splines to test them. EL - */ -public class DemoLayer extends OMGraphicHandlerLayer implements DrawingToolRequestor { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected JPanel legend; - /** - * Found in the findAndInit() method, in the MapHandler. - */ - protected DrawingTool drawingTool; - /** - * Found in the findAndInit() method, in the MapHandler. - */ - protected SymbolReferenceLibrary srl; - /** - * Used by the internal ActionListeners for a callback, see getGUI(). - */ - protected final com.bbn.openmap.tools.drawing.DrawingToolRequestor layer = this; - /** - * Used by geometries created in GUI for specify if the spatial filter is - * for objects inside the drawn shape. - */ - protected final static String internalKey = "ik"; - /** - * Used by geometries created in GUI for specify if the spatial filter is - * for objects outside the drawn shape. - */ - protected final static String externalKey = "ek"; - protected final static String FILTER_KEY_ATTRIBUTE = "fka"; - protected GraphicAttributes filterGA = null; - /** - * This is a list to hold the non-changing OMGraphics to display on the - * layer. It is used to load the OMGraphicList that the layer actually - * paints. - */ - protected OMGraphicList objects; - - public DemoLayer() { - setName("Demo"); - // This is how to set the ProjectionChangePolicy, which - // dictates how the layer behaves when a new projection is - // received. - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setRenderPolicy(new BufferedImageRenderPolicy(this)); - // Making the setting so this layer receives events from the - // SelectMouseMode, which has a modeID of "Gestures". Other - // IDs can be added as needed. - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - public void paint(java.awt.Graphics g) { - // Super calls the RenderPolicy that makes decisions on how to - // paint the OMGraphicList. The only reason we have this - // method overridden is to paint the legend if it exists. - super.paint(g); - if (legend != null) { - legend.paint(g); - } - } - - public OMGraphicList init() { - - // This layer keeps a pointer to an OMGraphicList that it uses - // for painting. It's initially set to null, which is used as - // a flag in prepare() to signal that the OMGraphcs need to be - // created. The list returned from prepare() gets set in the - // layer. - // This layer uses the StandardPCPolicy for new - // projections, which keeps the list intact and simply calls - // generate() on it with the new projection, and repaint() - // which calls paint(). - - OMGraphicList omList = new OMGraphicList(); - - // Location loc = new - // URLRasterLocation(42.3583f,-71.06f,"Boston,Massachusetts,USA","http://javamap.bbn.com:4711/appletimages/city.gif"); - // //loc.setLocationColor(Color.blue); - // loc.setShowLocation(true); - // loc.setShowName(true); - // //loc.setDetails("Details"); - // omList.add(loc); - - int bytearrsize = (16 * 16) / 8; - byte[] bytearr = new byte[bytearrsize]; - - for (int i = 0; i < bytearr.length; i++) { - bytearr[i] = (byte) 0xffffffff; - } - - OMBitmap omb = new OMBitmap(45.3583f, -71.06f, 16, 16, bytearr); - omb.setLinePaint(Color.red); - omb.setFillPaint(null); - omb.setSelectPaint(Color.blue); - omb.setRotationAngle(Math.PI / 2); - omb.putAttribute(RCT, "bitmap"); - omList.add(omb); - - OMPoint point = new OMPoint(42f, -72f, 14); - point.setFillPaint(Color.green); - point.setOval(true); - omList.add(point); - - OMCircle circle = new OMCircle(40f, -70f, 50, 200); - circle.setRotationAngle(com.bbn.openmap.util.MoreMath.HALF_PI / 2f); - circle.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("Circle Label", OMText.JUSTIFY_CENTER)); - circle.putAttribute(RCT, "circle"); - omList.add(circle); - - int[] llPointsx = new int[5]; - int[] llPointsy = new int[5]; - llPointsy[0] = 10; - llPointsx[0] = 170; - llPointsy[1] = 42; - llPointsx[1] = 273; - llPointsy[2] = 38; - llPointsx[2] = 374; - llPointsy[3] = 78; - llPointsx[3] = 468; - llPointsy[4] = 84; - llPointsx[4] = 369; - - LabeledOMSpline spline = new LabeledOMSpline(40f, -72, llPointsx, llPointsy, OMPoly.COORDMODE_ORIGIN); - spline.setText("Testing"); - spline.setLocateAtCenter(true); - spline.putAttribute(RCT, "spline 1"); - // spline.setIndex(2); - omList.add(spline); - - OMSpline spline2 = new OMSpline(llPointsx, llPointsy); - spline2.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("Spline Label")); - spline2.setLinePaint(Color.green); - spline2.putAttribute(RCT, "spline 2"); - omList.add(spline2); - - double[] llPoints = { 55.0f, -10.0f, 50.0f, -5.0f, 45.0f, -7.0f, 43.0f, -12.0f, 55.0f, - -10.0f }; - OMDecoratedSpline omds = new OMDecoratedSpline(llPoints, OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT); - ShapeDecorator sd = new ShapeDecorator(); - sd.addDecoration(new LineShapeDecoration(5, com.bbn.openmap.omGraphics.OMColor.clear)); - sd.addDecoration(new IceAreaShapeDecoration(7, 7, IceAreaShapeDecoration.RIGHT)); - omds.setDecorator(sd); - omList.add(omds); - - llPoints = new double[] { 56.0f, -11.0f, 51.0f, -6.0f, 46.0f, -8.0f, 44.0f, -13.0f, 56.0f, - -11.0f }; - omds = new OMDecoratedSpline(llPoints, OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT); - sd = new ShapeDecorator(); - sd.addDecoration(new LineShapeDecoration(3, com.bbn.openmap.omGraphics.OMColor.clear)); - sd.addDecoration(new CircleShapeDecoration(5, 5, Color.blue)); - omds.setDecorator(sd); - omList.add(omds); - - llPoints = new double[] { 57.0f, -12.0f, 52.0f, -7.0f, 47.0f, -9.0f, 45.0f, -14.0f, 57.0f, - -12.0f }; - omds = new OMDecoratedSpline(llPoints, OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT); - sd = new ShapeDecorator(); - sd.addDecoration(new LineShapeDecoration(2, com.bbn.openmap.omGraphics.OMColor.clear)); - sd.addDecoration(new CircleShapeDecoration(5, 5, Color.red)); - sd.addDecoration(new LineShapeDecoration(2, com.bbn.openmap.omGraphics.OMColor.clear)); - sd.addDecoration(new LineShapeDecoration(15, Color.red)); - omds.setDecorator(sd); - omList.add(omds); - - double[] llPoints2 = { 55.0f, -12.0f, 50.0f, -7.0f, 45.0f, -9.0f, 43.0f, -14.0f }; - OMHotSurfaceFront hf = new OMHotSurfaceFront(llPoints2, OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT); - hf.putAttribute(OMGraphic.TOOLTIP, "OMHotSurfaceFront"); - omList.add(hf); - double[] llPoints3 = { 55.0f, -14.0f, 50.0f, -9.0f, 45.0f, -11.0f, 43.0f, -16.0f }; - OMOcclusion oc = new OMOcclusion(llPoints3, OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT); - oc.putAttribute(OMGraphic.TOOLTIP, "OMOcclusion"); - omList.add(oc); - - // float[] llPoints4 = { 55.0f, -16.0f, 50.0f, -11.0f, 45.0f, - // -13.0f, - // 43.0f, -18.0f }; - // OMSpline spline3 = new OMDecoratedSpline(llPoints4, - // OMSpline.DECIMAL_DEGREES, OMSpline.LINETYPE_STRAIGHT) { - // protected void initDecorations() { - // - // getDecorator().addDecoration(new TextShapeDecoration(" This - // one has a text ", new Font("arial", Font.PLAIN, 10), - // TextShapeDecoration.LEFT_TO_RIGHT - // + TextShapeDecoration.FOLLOW_POLY, - // TextShapeDecoration.CENTER)); - // } - // }; - // omList.add(spline3); - - OMLine line = new OMLine(40f, -75f, 42f, -70f, OMGraphic.LINETYPE_GREATCIRCLE); - // line.addArrowHead(true); - line.addArrowHead(OMArrowHead.ARROWHEAD_DIRECTION_BOTH); - line.setStroke(new BasicStroke(2)); - line.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("Line Label")); - - omList.add(line); - - OMLine arcLine = new OMLine(0d, 0d, -20d, 30d, OMGraphic.LINETYPE_GREATCIRCLE); - arcLine.setLinePaint(Color.green); - arcLine.setArc(new ArcCalc(Math.PI, true)); - omList.add(arcLine); - - OMGraphicList pointList = new OMGraphicList(); - for (int i = 0; i < 100; i++) { - point = new OMPoint((float) (Math.random() * 89f), (float) (Math.random() * -179f), 3); - point.setSelectPaint(Color.yellow); - point.putAttribute(RCT, "Point " + i); - pointList.add(point); - } - omList.add(pointList); - - OMEllipse ell = new OMEllipse(new LatLonPoint.Double(60, -110), 1000, 300, Length.NM, com.bbn.openmap.util.MoreMath.HALF_PI / 2.0); - - ell.setLinePaint(Color.blue); - // ell.setFillPaint(Color.yellow); - omList.add(ell); - - ell = new OMEllipse(new LatLonPoint.Double(40, -75), 800, 250, Length.MILE, 0); - - ell.setFillPaint(Color.yellow); - omList.add(ell); - - double[] llp2 = new double[] { 0.41789755f, -1.435303f, 0.41813868f, -1.3967744f }; - - OMPoly p2 = new OMPoly(llp2, OMGraphic.RADIANS, OMGraphic.LINETYPE_RHUMB); - p2.setLinePaint(Color.yellow); - omList.add(p2); - - // OMArc arc = new OMArc(40f, 65f, 750f, Length.MILE, 20f, - // 95f); - OMArc arc = new OMArc((float) 40.0, (float) 65.0, (float) 750.0, Length.MILE, (float) 20.0, (float) 95.0); - arc.setLinePaint(Color.red); - arc.setFillPaint(new Color(120, 0, 0, 128)); - arc.setArcType(java.awt.geom.Arc2D.OPEN); - arc.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("Arc Label", OMText.JUSTIFY_CENTER)); - omList.add(arc); - - OMAreaList combo = new OMAreaList(); - - combo.addOMGraphic(new OMLine((float) 50.453333, (float) 5.223889, (float) 50.375278, (float) 4.873889, 2)); - combo.addOMGraphic(new OMLine((float) 50.375278, (float) 4.873889, (float) 50.436944, (float) 4.860556, 2)); - // combo.addOMGraphic(new OMLine((float) 50.436944, (float) - // 4.860556, (float) 50.436667, (float) 4.860833, 2)); - // combo.addOMGraphic(new OMLine((float) 50.436667, (float) - // 4.860833, (float) 50.490833, (float) 4.847778, 2)); - // combo.addOMGraphic(new OMLine((float) 50.491269, (float) - // 4.704239, (float) 50.490833, (float) 4.847778, 3)); - combo.addOMGraphic(new OMArc((float) 50.491269, (float) 4.704239, (float) 0.09168520552327833, (float) (28.201865385183652 + 90.21758717585848), (float) -90.21758717585848)); - combo.addOMGraphic(new OMLine((float) 50.534167, (float) 4.831111, (float) 50.640833, (float) 4.832222, 2)); - combo.addOMGraphic(new OMLine((float) 50.640833, (float) 4.832222, (float) 50.547778, (float) 5.223889, 2)); - combo.addOMGraphic(new OMLine((float) 50.547778, (float) 5.223889, (float) 50.453333, (float) 5.223889, 2)); - - // combo.setConnectParts(true); - // combo.addOMGraphic(new OMLine(30f, -125f, 30f, -100f, - // OMGraphic.LINETYPE_RHUMB)); - // combo.addOMGraphic(new OMLine(30f, -100f, 40f, -95f, - // OMGraphic.LINETYPE_GREATCIRCLE)); - // combo.addOMGraphic(new OMLine(40f, -95f, 50f, -145f, - // OMGraphic.LINETYPE_GREATCIRCLE)); - // combo.addOMGraphic(new OMLine(50f, -145f, 30f, -125f, - // OMGraphic.LINETYPE_STRAIGHT)); - combo.setLinePaint(Color.blue); - combo.setFillPaint(Color.green); - omList.add(combo); - - OMAreaList combo1 = new OMAreaList(); - combo1.addOMGraphic(new OMLine(66.618519f, 141.563497f, 66.028244f, 140.193964f, OMGraphic.LINETYPE_GREATCIRCLE)); - combo1.addOMGraphic(new OMLine(66.028244f, 140.193964f, 66.968058f, 137.611042f, OMGraphic.LINETYPE_RHUMB)); - combo1.addOMGraphic(new OMLine(66.968058f, 137.611042f, 67.558261f, 139.033958f, OMGraphic.LINETYPE_GREATCIRCLE)); - combo1.addOMGraphic(new OMLine(67.558261f, 139.033958f, 66.618519f, 141.563497f, OMGraphic.LINETYPE_RHUMB)); - combo1.setLinePaint(Color.red); - combo1.setFillPaint(Color.blue); - omList.add(combo1); - - combo1 = new OMAreaList(); - combo1.addOMGraphic(new OMLine(65.495278f, 55.488889f, 65.022778f, 55.749167f, OMGraphic.LINETYPE_GREATCIRCLE)); - combo1.addOMGraphic(new OMLine(65.022778f, 55.749167f, 64.970278f, 55.208611f, OMGraphic.LINETYPE_RHUMB)); - combo1.addOMGraphic(new OMLine(64.970278f, 55.208611f, 65.442778f, 54.948889f, OMGraphic.LINETYPE_GREATCIRCLE)); - combo1.addOMGraphic(new OMLine(65.442778f, 54.948889f, 65.495278f, 55.488889f, OMGraphic.LINETYPE_RHUMB)); - combo1.setLinePaint(Color.blue); - combo1.setFillPaint(Color.red); - omList.add(combo1); - - // OMArc arc1 = new OMArc(100, 100, 200, 200, 0f, -45f); - // arc1.setLinePaint(Color.blue); - // arc1.setFillPaint(Color.yellow); - // arc1.setArcType(java.awt.geom.Arc2D.PIE); - // omList.add(arc1); - - OMText text = new OMText(30f, 80f, "Testing FontSizer", OMText.JUSTIFY_CENTER); - text.setFontSizer(new FontSizer(30000000f, 1, 5, 40)); - omList.add(text); - - if (srl != null) { - ImageIcon ii = srl.getIcon("SFPPV-----*****", new Dimension(200, 200)); - if (ii != null) { - OMScalingIcon omsi = new OMScalingIcon(20f, -50f, ii); - omsi.setBaseScale(4000000); - omsi.setMinScale(1000000); - omsi.setMaxScale(6000000); - omsi.setRotationAngle(Math.PI / 4); - omsi.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("SFPPV-----*****", OMText.JUSTIFY_LEFT, OMTextLabeler.ANCHOR_RIGHT)); - omsi.putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - omList.add(omsi); - - SymbolPart sp = srl.getSymbolPartForCode("SFPPV-----*****"); - if (sp != null) { - omsi.putAttribute(OMGraphic.TOOLTIP, sp.getDescription()); - } - - omsi = new OMScalingIcon(43f, -70f, ii); - omsi.setBaseScale(500000); - omsi.setMinScale(500000); - omsi.setMaxScale(500000); - omsi.setRotationAngle(-Math.PI / 4); - omsi.putAttribute(OMGraphicConstants.LABEL, new OMTextLabeler("SFPPV-----*****", OMText.JUSTIFY_LEFT, OMTextLabeler.ANCHOR_RIGHT)); - omsi.putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - omList.add(omsi); - - if (sp != null) { - omsi.putAttribute(OMGraphic.TOOLTIP, sp.getDescription()); - } - - } else { - Debug.output("DemoLayer: couldn't create symbol from SymbolReferenceLibrary"); - } - } - - GeneralPath gp = new GeneralPath(); - gp.moveTo(20, 20); - gp.lineTo(20, -20); - gp.lineTo(-20, -20); - gp.lineTo(-20, 20); - gp.lineTo(20, 20); - gp.moveTo(10, 10); - gp.lineTo(10, -10); - gp.lineTo(-10, -10); - gp.lineTo(-10, 10); - gp.lineTo(10, 10); - OMShape oms = new OMShape(gp); - oms.setFillPaint(Color.orange); - - omList.add(oms); - - OMGraphicList geoTest = new OMGraphicList(); - LatLonPoint pnt1 = new LatLonPoint.Double(42.0, -71.0); - LatLonPoint pnt2 = new LatLonPoint.Double(42.3, -70.678); - double gspacing = Length.MILE.toRadians(5); - - OMCircle ompoint1 = new OMCircle(pnt1.getLatitude(), pnt1.getLongitude(), gspacing, Length.RADIAN); - OMCircle ompoint2 = new OMCircle(pnt2.getLatitude(), pnt2.getLongitude(), gspacing, Length.RADIAN); - - LatLonPoint int1 = GreatCircle.pointAtDistanceBetweenPoints(pnt1.getRadLat(), pnt1.getRadLon(), pnt2.getRadLat(), pnt2.getRadLon(), gspacing, -1); - LatLonPoint int2 = GreatCircle.pointAtDistanceBetweenPoints(pnt2.getRadLat(), pnt2.getRadLon(), pnt1.getRadLat(), pnt1.getRadLon(), gspacing, -1); - - OMLine geoline = new OMLine(int1.getLatitude(), int1.getLongitude(), int2.getLatitude(), int2.getLongitude(), OMGraphic.LINETYPE_GREATCIRCLE); - ompoint1.setLinePaint(Color.red); - ompoint2.setLinePaint(Color.red); - geoline.setLinePaint(Color.red); - geoTest.add(ompoint1); - geoTest.add(ompoint2); - geoTest.add(geoline); - - omList.add(geoTest); - - OMText omtest = new OMText(42.0, -71.0, "Testing how this looks\nwhen doing multiple lines", OMText.JUSTIFY_LEFT); - omtest.setBaseline(OMText.BASELINE_TOP); - omtest.setFillPaint(Color.red); - - omList.add(omtest); - - llPoints = new double[] { -5.856972964554054E-4, 7.181106520146243E-5, - -5.856972964554055E-4, -7.181106520146255E-5, -2.9284864843698565E-4, - -7.18110652014625E-5, 5.856972969587945E-4, -5.756442432493538E-4, - 5.856972969587943E-4, 5.756442432493541E-4, -2.9284864843698565E-4, - 7.181106520146243E-5, -5.856972964554054E-4, 7.181106520146243E-5, }; - - double buffer = 0.1645788336933045; - - for (int i = 0; i < llPoints.length - 1; i += 2) { - double lat = Math.toDegrees(llPoints[i]); - double lon = Math.toDegrees(llPoints[i + 1]); - - OMText txt = new OMText(lat, lon, Integer.toString(i / 2), OMText.JUSTIFY_LEFT); - omList.add(txt); - } - - RibbonMaker ribbonMaker = RibbonMaker.createFromRadians(llPoints); - - OMGraphic omg = ribbonMaker.getOuterRing(Length.NM.toRadians(buffer)); - omg.setLinePaint(Color.red); - omList.add(omg); - - OMPoly ribbonPoly = new OMPoly(llPoints, OMPoly.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - ribbonPoly.setLinePaint(Color.orange); - omList.add(ribbonPoly); - - OMEllipse ome1 = new OMEllipse(new LatLonPoint.Double(20.0, -110.0), 600, 300, Length.MILE, 0); - ome1.setLinePaint(Color.cyan); - omList.add(ome1); - - OMEllipse ome4 = new OMEllipse(new LatLonPoint.Double(20.0, -110.0), 600, 300, Length.MILE, Math.toRadians(45)); - ome4.setLinePaint(Color.red); - omList.add(ome4); - - OMEllipse ome2 = new OMEllipse(new LatLonPoint.Double(20.0, -110.0), 600, 300, Length.MILE, Math.toRadians(60)); - ome2.setLinePaint(Color.orange); - omList.add(ome2); - - OMEllipse ome3 = new OMEllipse(new LatLonPoint.Double(20.0, -110.0), 600, 300, Length.MILE, Math.toRadians(115)); - ome3.setLinePaint(Color.green); - omList.add(ome3); - - OMEllipse ome5 = new OMEllipse(new LatLonPoint.Double(20.0, -110.0), 600, 300, Length.MILE, Math.toRadians(135)); - ome5.setLinePaint(Color.MAGENTA); - omList.add(ome5); - - OMTextBalloon balloon = new OMTextBalloon(34, -85, "This is a test of a OMTextBalloon.", OMText.JUSTIFY_LEFT); - balloon.setFillPaint(Color.white); - - omList.add(balloon); - - return omList; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - setAddToBeanContext(true); - } - - /** - * This is an important Layer method to override. The prepare method gets - * called when the layer is added to the map, or when the map projection - * changes. We need to make sure the OMGraphicList returned from this method - * is what we want painted on the map. The OMGraphics need to be generated - * with the current projection. We test for a null OMGraphicList in the - * layer to see if we need to create the OMGraphics. This layer doesn't - * change it's OMGraphics for different projections, if your layer does, you - * need to clear out the OMGraphicList and add the OMGraphics you want for - * the current projection. - */ - public synchronized OMGraphicList prepare() { - if (objects == null) { - objects = init(); - } - OMGraphicList list = new OMGraphicList(); - // Return new list of the objects to mange for the projection change. - list.addAll(objects); - list.generate(getProjection()); - return list; - } - - protected GraphicAttributes getFilterGA() { - if (filterGA == null) { - filterGA = new GraphicAttributes(); - filterGA.setLinePaint(Color.red); - filterGA.setRenderType(OMGraphic.RENDERTYPE_LATLON); - filterGA.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - BasicStroke filterStroke = new BasicStroke(1f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10f, new float[] { - 3, 3 }, 0f); - filterGA.setStroke(filterStroke); - } - return (GraphicAttributes) filterGA.clone(); - } - - public java.awt.Component getGUI() { - - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - panel.setLayout(gridbag); - - JPanel box = PaletteHelper.createVerticalPanel(" Create Filters for Map "); - box.setLayout(new java.awt.GridLayout(0, 1)); - - // JButton button = new JButton("Add and Edit Offset Line"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // if (dt != null) { - - // OMLine line = new OMLine(42f, -72f, -50, -70, 200, 200); - // line.setStroke(new java.awt.BasicStroke(5)); - // line.setLinePaint(java.awt.Color.red); - // line.setFillPaint(java.awt.Color.green); - - // line = (OMLine) getDrawingTool().edit(line, layer); - // if (line != null) { - // getList().add(line); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMLine"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Add and Edit XY Line"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // if (dt != null) { - - // OMLine line = new OMLine(200, 200, 420, 520); - // line.setLinePaint(java.awt.Color.blue); - // line.setFillPaint(java.awt.Color.green); - - // line = (OMLine) getDrawingTool().edit(line, layer); - // if (line != null) { - // getList().add(line); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMLine"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Add and Edit LatLon Line, no GUI"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // if (dt != null) { - // OMLine line = new OMLine(30f, -60f, 42f, -72f, - // OMGraphic.LINETYPE_GREATCIRCLE); - // line.setStroke(new java.awt.BasicStroke(5)); - // line.setLinePaint(java.awt.Color.red); - // line.setFillPaint(java.awt.Color.green); - - // line = (OMLine) getDrawingTool().edit(line, layer, false); - // if (line != null) { - // getList().add(line); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMLine"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create XY Line"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // if (dt != null) { - // OMLine line = (OMLine) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMLine", - // layer); - // if (line != null) { - // getList().add(line); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMLine"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create Offset Line"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - // if (dt != null) { - // OMLine line = (OMLine) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMLine", - // ga, layer); - // if (line != null) { - // getList().add(line); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMLine"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create Lat/Lon Circle"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - // if (dt != null) { - // OMCircle circle = (OMCircle) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMCircle", - // ga, layer); - // if (circle != null) { - // getList().add(circle); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create - // OMCircle"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create XY Circle"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_XY); - // if (dt != null) { - // OMCircle circle = (OMCircle) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMCircle", - // ga, layer); - // if (circle != null) { - // getList().add(circle); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create - // OMCircle"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create Offset Circle"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - // ga.setFillPaint(Color.red); - // if (dt != null) { - // OMCircle circle = (OMCircle) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMCircle", - // ga, layer); - // if (circle != null) { - // getList().add(circle); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create - // OMCircle"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - JButton button = new JButton("Create Containing Rectangle Filter"); - button.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent event) { - DrawingTool dt = getDrawingTool(); - if (dt != null) { - GraphicAttributes fga = getFilterGA(); - fga.setFillPaint(new OMColor(0x0c0a0a0a)); - - OMRect rect = (OMRect) getDrawingTool().create("com.bbn.openmap.omGraphics.OMRect", fga, layer, false); - if (rect != null) { - rect.putAttribute(FILTER_KEY_ATTRIBUTE, internalKey); - } else { - Debug.error("DemoLayer: Drawing tool can't create OMRect"); - } - } else { - Debug.output("DemoLayer can't find a drawing tool"); - } - } - }); - box.add(button); - - button = new JButton("Create Containing Polygon Filter"); - button.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent event) { - DrawingTool dt = getDrawingTool(); - if (dt != null) { - GraphicAttributes fga = getFilterGA(); - fga.setFillPaint(OMColor.clear); - - EditableOMPoly eomp = new EditableOMPoly(fga); - eomp.setEnclosed(true); - eomp.setShowGUI(false); - - dt.setBehaviorMask(OMDrawingTool.QUICK_CHANGE_BEHAVIOR_MASK); - OMPoly poly = (OMPoly) getDrawingTool().edit(eomp, layer); - - if (poly != null) { - poly.setIsPolygon(true); - poly.putAttribute(FILTER_KEY_ATTRIBUTE, internalKey); - } else { - Debug.error("DemoLayer: Drawing tool can't create OMPoly"); - } - } else { - Debug.output("DemoLayer can't find a drawing tool"); - } - } - }); - box.add(button); - - button = new JButton("Create Excluding Rectangle Filter"); - button.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent event) { - DrawingTool dt = getDrawingTool(); - if (dt != null) { - GraphicAttributes fga = getFilterGA(); - fga.setFillPaint(OMColor.clear); - - OMRect rect = (OMRect) getDrawingTool().create("com.bbn.openmap.omGraphics.OMRect", fga, layer, false); - if (rect != null) { - rect.putAttribute(FILTER_KEY_ATTRIBUTE, externalKey); - } else { - Debug.error("DemoLayer: Drawing tool can't create OMRect"); - } - } else { - Debug.output("DemoLayer can't find a drawing tool"); - } - } - }); - box.add(button); - - button = new JButton("Reset filter"); - button.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent event) { - resetFiltering(); - repaint(); - } - }); - box.add(button); - - // button = new JButton("Create XY Rect"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_XY); - // if (dt != null) { - // OMRect rect = (OMRect) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMRect", - // ga, layer); - // if (rect != null) { - // getList().add(rect); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMRect"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create Offset Rect"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - // ga.setFillPaint(Color.red); - // if (dt != null) { - // OMRect rect = (OMRect) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMRect", - // ga, layer); - // if (rect != null) { - // getList().add(rect); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMRect"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create RangeRings"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setLinePaint(Color.yellow); - // if (dt != null) { - // OMRangeRings rr = (OMRangeRings) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMRangeRings", - // ga, layer); - // if (rr != null) { - // // rr.setInterval(25, Length.MILE); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create - // OMRangeRings"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create XY Poly"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_XY); - // ga.setLinePaint(Color.red); - // ga.setFillPaint(Color.red); - // if (dt != null) { - // OMPoly point = (OMPoly) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMPoly", - // ga, layer); - // if (point != null) { - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMPoly"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create LatLon Labeled Poly"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - // ga.setLinePaint(Color.green); - // ga.setFillPaint(Color.green); - // if (dt != null) { - - // LabeledOMPoly point = (LabeledOMPoly) - // getDrawingTool().create("com.bbn.openmap.omGraphics.labeled.LabeledOMPoly", - // ga, layer); - - // if (point != null) { - // // point.setOval(true); - // // point.setRadius(8); - // point.setText("Active Testing"); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMPoly"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - // button = new JButton("Create LatLon Offset Poly"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent event) { - // DrawingTool dt = getDrawingTool(); - // GraphicAttributes ga = new GraphicAttributes(); - // ga.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - // ga.setLinePaint(Color.green); - // ga.setFillPaint(Color.green); - // if (dt != null) { - // OMPoly point = (OMPoly) - // getDrawingTool().create("com.bbn.openmap.omGraphics.OMPoly", - // ga, layer); - // if (point != null) { - // // rr.setInterval(25, Length.MILE); - // } else { - // Debug.error("DemoLayer: Drawing tool can't create OMPoly"); - // } - // } else { - // Debug.output("DemoLayer can't find a drawing tool"); - // } - // } - // }); - // box.add(button); - - gridbag.setConstraints(box, c); - panel.add(box); - return panel; - } - - public DrawingTool getDrawingTool() { - // Usually set in the findAndInit() method. - return drawingTool; - } - - public void setDrawingTool(DrawingTool dt) { - // Called by the findAndInit method. - drawingTool = dt; - } - - /** - * Called when the DrawingTool is complete, providing the layer with the - * modified OMGraphic. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - Debug.message("demo", "DemoLayer: DrawingTool complete"); - - Object obj = omg.getAttribute(FILTER_KEY_ATTRIBUTE); - - if (obj != null && (obj == internalKey || obj == externalKey) - && !action.isMask(OMGraphicConstants.DELETE_GRAPHIC_MASK)) { - - java.awt.Shape filterShape = omg.getShape(); - OMGraphicList filteredList = filter(filterShape, (omg.getAttribute(FILTER_KEY_ATTRIBUTE) == internalKey)); - if (Debug.debugging("demo")) { - Debug.output("DemoLayer filter: " + filteredList.getDescription()); - } - } else { - if (!doAction(omg, action)) { - // null OMGraphicList on failure, should only occur if - // OMGraphic is added to layer before it's ever been - // on the map. - setList(new OMGraphicList()); - doAction(omg, action); - } - } - - repaint(); - } - - /** - * Called when a component that is needed, and not available with an - * appropriate iterator from the BeanContext. This lets this object hook up - * with what it needs. For Layers, this method doesn't do anything by - * default. If you need your layer to get ahold of another object, then you - * can use the Iterator to go through the objects to look for the one you - * need. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof DrawingTool) { - Debug.message("demo", "DemoLayer: found a drawing tool"); - setDrawingTool((DrawingTool) someObj); - } - - if (someObj instanceof SymbolReferenceLibrary) { - setSymbolReferenceLibrary((SymbolReferenceLibrary) someObj); - } - } - - /** - * Set the MilStd2525 SymbolReferenceLibrary object used to create symbols. - * - * @param library - */ - public void setSymbolReferenceLibrary(SymbolReferenceLibrary library) { - srl = library; - } - - public SymbolReferenceLibrary getSymbolReferenceLibrary() { - return srl; - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof DrawingTool) { - if (getDrawingTool() == (DrawingTool) someObj) { - setDrawingTool(null); - } - } - } - - /** - * Query that an OMGraphic can be highlighted when the mouse moves over it. - * If the answer is true, then highlight with this OMGraphics will be - * called. - */ - public boolean isHighlightable(OMGraphic omg) { - return true; - } - - /** - * Query that an OMGraphic is selectable. - */ - public boolean isSelectable(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - return (dt != null && dt.canEdit(omg.getClass())); - } - - /** - * Query for what text should be placed over the information bar when the - * mouse is over a particular OMGraphic. - */ - public String getInfoText(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - if (dt != null && dt.canEdit(omg.getClass())) { - return "Click to edit graphic."; - } else { - return null; - } - } - - /** - * Query for what tooltip to display for an OMGraphic when the mouse is over - * it. - */ - public String getToolTipTextFor(OMGraphic omg) { - Object tt = omg.getAttribute(OMGraphic.TOOLTIP); - if (tt instanceof String) { - return (String) tt; - } - - String classname = omg.getClass().getName(); - int lio = classname.lastIndexOf('.'); - if (lio != -1) { - classname = classname.substring(lio + 1); - } - - return "Demo Layer Object: " + classname; - } - - /** - * Called if isSelectable(OMGraphic) was true, so the list has the - * OMGraphic. A list is used in case underlying code is written to handle - * more than one OMGraphic being selected at a time. - */ - public void select(OMGraphicList list) { - if (list != null && !list.isEmpty()) { - OMGraphic omg = list.getOMGraphicAt(0); - DrawingTool dt = getDrawingTool(); - - if (dt != null && dt.canEdit(omg.getClass())) { - dt.setBehaviorMask(OMDrawingTool.QUICK_CHANGE_BEHAVIOR_MASK); - if (dt.edit(omg, this) == null) { - // Shouldn't see this because we checked, but ... - fireRequestInfoLine("Can't figure out how to modify this object."); - } - } - } - } - - public List getItemsForMapMenu(MapMouseEvent me) { - List l = new ArrayList(); - l.add(new JMenuItem("When")); - l.add(new JMenuItem("Where")); - l.add(new JMenuItem("How")); - - return l; - } - - private String RCT = "rightClickTest"; - - public List getItemsForOMGraphicMenu(OMGraphic omg) { - - String rightClickTest = (String) omg.getAttribute(RCT); - - logger.info("right click test: " + rightClickTest); - - List l = new ArrayList(); - l.add(new JMenuItem("Which")); - l.add(new JMenuItem("Why")); - l.add(new JSeparator()); - l.add(new JMenuItem(rightClickTest)); - return l; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/GeoCrossDemoLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/GeoCrossDemoLayer.java deleted file mode 100644 index ea78ee2c1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/GeoCrossDemoLayer.java +++ /dev/null @@ -1,232 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoCrossDemoLayer.java,v $ -//$Revision: 1.3 $ -//$Date: 2009/01/21 01:24:42 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.test; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.layer.editor.DrawingEditorTool; -import com.bbn.openmap.layer.editor.EditorLayer; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.tools.drawing.OMLineLoader; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * This layer was developed to provide a simple picture of how vector cross - * products work with Geos to solve intersection problems. The best way to use - * this class is to turn off all other layers and put the map in Orthographic - * projection. When the layer is active, a series of buttons will appear in the - * ToolPanel, allowing you to draw Great Circle lines. It's helpful to change - * the color of each line before you create it, so you can see the relationship - * of the line to the previous one drawn. - *

- * - * This layer will iterate through the list if drawn lines, looking for the - * intersection point between consecutive lines. For each line, a point will be - * drawn in that line's color representing the cross-normalized point for the - * line's enpoints - that is, it's the point perpendicular to the great circle - * plane created by the line. You can also think of it as the point that is 90 - * degrees away from every point on the line. The dotted lines are the path from - * the previous line's crossNornmalized point and the current line's - * crossNormalized point. Lastly, the cross-normalization of the end points of - * the dashed line will result in the point where the original lines would - * intersect if they are close enough. Depending on the direction that the lines - * were drawn, that point may actually be the antipode (on the other side of the - * sphere) of the point you are interested in, but this layer doesn't bother to - * investigate that yet. - *

- * - * That's all this layer does. The properties for this layer are: - * - *

- *          geocross.class=com.bbn.openmap.layer.test.GeoCrossDemoLayer
- *          geocross.prettyName=GEO Cross Demonstration
- *          geocross.editor=com.bbn.openmap.layer.editor.DrawingEditorTool
- *          geocross.showAttributes=true
- *          geocross.loaders=lines
- *          geocross.mouseModes=Gestures
- *          geocross.lines.class=com.bbn.openmap.tools.drawing.OMLineLoader
- * 
- * - * @author dietrick - */ - -public class GeoCrossDemoLayer extends EditorLayer { - - private static final long serialVersionUID = 1L; - protected OMGraphicList lines = new OMGraphicList(); - - /** - * - */ - public GeoCrossDemoLayer() { - super(); - - DrawingEditorTool drawingEditorTool = new DrawingEditorTool(this); - drawingEditorTool.addEditToolLoader(new OMLineLoader()); - setEditorTool(drawingEditorTool); - setFaceOnPalette(true); - } - - public synchronized OMGraphicList prepare() { - OMGraphicList list = getList(); - - if (list == null) { - list = new OMGraphicList(); - } else { - list.clear(); - } - - OMLine oldLine = null; - Geo ogc = null; - - for (OMGraphic omg : lines) { - - OMLine line = (OMLine) omg; - double[] ll = line.getLL(); - Geo g1 = new Geo(ll[0], ll[1]); - Geo g2 = new Geo(ll[2], ll[3]); - - Geo gc = g1.crossNormalize(g2); - - OMPoint p = new OMPoint((float) gc.getLatitude(), (float) gc.getLongitude(), 3); - p.setLinePaint(line.getLinePaint()); - p.setFillPaint(line.getFillPaint()); - p.setStroke(line.getStroke()); - - line.addArrowHead(true); - - list.add(line); - list.add(p); - - if (oldLine != null && ogc != null) { - - double[] ll2 = oldLine.getLL(); - Geo g3 = new Geo(ll2[0], ll2[1]); - Geo g4 = new Geo(ll2[2], ll2[3]); - - OMLine line2 = new OMLine((float) ogc.getLatitude(), (float) ogc.getLongitude(), - (float) gc.getLatitude(), (float) gc.getLongitude(), OMGraphic.LINETYPE_GREATCIRCLE); - line2.setLinePaint(line.getLinePaint()); - line2.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, - new float[] { 10, 10 }, 0f)); - line2.addArrowHead(true); - list.add(line2); - - Geo i = gc.crossNormalize(ogc); - Color iColor = Color.white; - if (!(Intersection.isOnSegment(g1, g2, i) || Intersection.isOnSegment(g3, g4, i))) { - i = i.antipode(); - iColor = Color.black; - } - - p = new OMPoint((float) i.getLatitude(), (float) i.getLongitude(), 3); - p.setOval(true); - p.setLinePaint(line.getLinePaint()); - p.setFillPaint(iColor); - p.setStroke(line.getStroke()); - - list.add(p); - } - - oldLine = line; - ogc = gc; - } - - list.generate(getProjection()); - - return list; - - } - - /** - * We're assuming that faceOnPalette is true, so the drawing tool for this layer is in the palette, not in the ToolPanel. - */ - public Component getGUI() { - if (box == null && editorTool != null) { - - String interString = i18n.get(GeoCrossDemoLayer.class, "DRAW_LINES", "Draw lines to calculate intersections"); - - box = PaletteHelper.createHorizontalPanel(interString); - - Container fce = editorTool.getFace(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - box.setLayout(gridbag); - - c.gridx = GridBagConstraints.REMAINDER; - gridbag.setConstraints(fce, c); - box.add(fce); - - interString = i18n.get(GeoCrossDemoLayer.class, "CLEAR_LINES", "Clear Lines"); - JButton button = new JButton(interString); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - lines.clear(); - doPrepare(); - } - }); - box.add(button); - } - - return box; - } - - public void drawingComplete(OMGraphic omg, OMAction action) { - - releaseProxyMouseMode(); - - if (omg instanceof OMLine && lines != null) { - lines.doAction(omg, action); - deselect(lines); - doPrepare(); - } else { - Debug.error("Layer " + getName() + " received " + omg + " and " + action + " with no list ready"); - } - - // This is important!! - if (editorTool != null) { - editorTool.drawingComplete(omg, action); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/GeoIntersectionLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/GeoIntersectionLayer.java deleted file mode 100644 index 6002a0a99..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/GeoIntersectionLayer.java +++ /dev/null @@ -1,1107 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoIntersectionLayer.java,v $ -//$Revision: 1.7 $ -//$Date: 2009/01/21 01:24:42 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.test; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.net.MalformedURLException; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.filechooser.FileFilter; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.geo.BoundaryCrossing; -import com.bbn.openmap.geo.ExtentIndex; -import com.bbn.openmap.geo.ExtentIndexImpl; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.geo.GeoArray; -import com.bbn.openmap.geo.GeoExtent; -import com.bbn.openmap.geo.GeoPath; -import com.bbn.openmap.geo.GeoPoint; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.geo.OMGeo; -import com.bbn.openmap.layer.editor.DrawingEditorTool; -import com.bbn.openmap.layer.editor.EditorLayer; -import com.bbn.openmap.layer.editor.EditorTool; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.drawing.OMLineLoader; -import com.bbn.openmap.tools.drawing.OMPointLoader; -import com.bbn.openmap.tools.drawing.OMPolyLoader; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * This layer demonstrates the use of the com.bbn.openmap.geo package to do - * intersection calculations in lat/lon space. It allows you to load shape files - * for sample data sets, and then draw lines, polygons and points on the map to - * as test cases for intersections on the sample data sets. The ToolPanel will - * hold controls for choosing what kind of things to draw, and how they should - * be rendered. The palette for this layer controls the sample data sets, - * letting you add and remove data files and change their colors. - *

- * - * If you draw a line, polyline or point, the shapes in the data sets that - * intersect with them will be rendered in the 'select' colors. If you draw a - * closed polygon with a fill color, the data set shapes inside the polygon will - * also be selected. The palette has controls for showing the actual points of - * intersection for paths and their sample data regions. There is also an option - * to allow mouse clicks on a data set region to create an image over the - * bounding rectangle for that region, checking the Geo point intersection - * algorithm against the Java 2D algorithm for the shape in projected pixel - * space. An all-green image is good, pixels where the algorithms differ will be - * red. - *

- * - * The properties for this layer are: - * - *

- *        geo.class=com.bbn.openmap.layer.test.GeoIntersectionLayer
- *        geo.prettyName=GEO Intersections
- *        geo.editor=com.bbn.openmap.layer.editor.DrawingEditorTool
- *        geo.showAttributes=true
- *        geo.loaders=lines polys points
- *        geo.mouseModes=Gestures
- *        geo.lines.class=com.bbn.openmap.tools.drawing.OMLineLoader
- *        geo.polys.class=com.bbn.openmap.tools.drawing.OMPolyLoader
- *        geo.points.class=com.bbn.openmap.tools.drawing.OMPointLoader
- *        geo.shapeFileList=geocounties geolakes geocountries
- *        geo.geocounties=/data/shape/usa/counties.shp
- *        geo.geolakes=/data/shape/world/lakes.shp
- *        geo.geocountries=/data/shape/world/cntry02/cntry02.shp
- *        # Colors for drawing intersecting shapes (lines, polys)
- *        geo.fillColor=33333333
- *        geo.selectColor=33333333
- *        geo.mattingColor=33aaaa33
- *        # Colors for regular, unselected data shapes
- *        geo.shape.fillColor=FF333399
- *        geo.shape.selectColor=ffff9900
- *        geo.shape.mattingColor=ffff9900
- *        # Colors for data shapes intersected by drawn shapes
- *        geo.selected.fillColor=FFFFFF00
- *        geo.selected.selectColor=ffff9900
- *        geo.selected.mattingColor=ffff9900
- * 
- * - * @author dietrick - */ -public class GeoIntersectionLayer extends EditorLayer implements PropertyChangeListener { - - /** - * - */ - private static final long serialVersionUID = -2218459678346543731L; - /** This list holds the OMGraphics that have been drawn. */ - protected OMGraphicList drawnList = new OMGraphicList(); - /** This list holds the EsriGraphicLists from the Shape files. */ - protected OMGraphicList fileDataList; - /** - * This list holds the BoundaryCrossings and the image masks created from - * Intersection queries. - */ - protected OMGraphicList intersectionResultList = new OMGraphicList(); - /** The RegionIndex organizing the Shape OMGraphics for searching. */ - protected ExtentIndexImpl regionIndex = null; - - protected DrawingAttributes shapeDA = new DrawingAttributes(); - protected DrawingAttributes shapeDASelected = new DrawingAttributes(); - - public final static String ShapeFileListProperty = "shapeFileList"; - public final static String ShapeFileProperty = "shapeFile"; - public final static String ShowCrossingPointsProperty = "showCrossingPoints"; - public final static String PointCheckProperty = "pointCheck"; - - public final static String SHAPE_FILE_NAME_ATTRIBUTE = "SHAPE_FILE_NAME"; - public final static String SHAPE_VISIBILITY_CONTROL_ATTRIBUTE = "SHAPE_VISIBILITY_CONTROL"; - public final static String SHAPE_CONTROL_ATTRIBUTE = "SHAPE_CONTROL"; - - protected boolean showCrossingPoints = false; - protected boolean createPointCheck = false; - - public static boolean DEBUG = false; - - /** - * - */ - public GeoIntersectionLayer() { - super(); - DEBUG = Debug.debugging("geo") || true; - shapeDA.getPropertyChangeSupport().addPropertyChangeListener(this); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - setFaceOnPalette(true); - - DrawingEditorTool editorTool = new DrawingEditorTool(this); - editorTool.addEditToolLoader(new OMLineLoader()); - editorTool.addEditToolLoader(new OMPolyLoader()); - editorTool.addEditToolLoader(new OMPointLoader()); - setEditorTool(editorTool); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - EditorTool editorTool = getEditorTool(); - if (editorTool instanceof PropertyConsumer) { - ((PropertyConsumer) editorTool).setProperties(prefix, props); - } - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - shapeDA.setProperties(prefix + "shape", props); - shapeDASelected.setProperties(prefix + "selected", props); - - List v = PropUtils.parseSpacedMarkers(props.getProperty(prefix + ShapeFileListProperty)); - - for (String markerName : v) { - String shapeFileName = props.getProperty(prefix + markerName); - if (shapeFileName != null) { - File sf = new File(shapeFileName); - if (sf.exists()) { - addShapeFile(sf, false); - } - } - } - - } - - public synchronized OMGraphicList prepare() { - OMGraphicList list = getList(); - - if (list == null) { - list = new OMGraphicList(); - } else { - list.clear(); - } - - // If we created any pixel intersection images before, time to - // get rid of them. - - calculateIntersectionsWithDrawnList(); - - list.add(intersectionResultList); - list.add(drawnList); - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Adding lines to main list"); - } - - if (fileDataList != null) { - list.add(fileDataList); - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Adding shapes to main list"); - } - } - - list.generate(getProjection()); - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Projected main list, returning"); - } - - return list; - - } - - public void calculateIntersectionsWithDrawnList() { - intersectionResultList.clear(); - ExtentIndex rIndex = getRegionIndex(true); - - if (DEBUG) { - Debug.output("checking against index with " + rIndex.size() + " objects"); - } - - for (OMGraphic omg : drawnList) { - - if (omg instanceof OMLine || (omg instanceof OMPoly && !((OMPoly) omg).isPolygon())) { - - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Checking line against RegionIndex"); - } - - GeoPath path = getPathFromOMGraphic(omg); - - Iterator intrsctns = null; - Iterator crssngs = null; - - if (showCrossingPoints) { - BoundaryCrossing.Collector results = BoundaryCrossing.getCrossings(path, rIndex); - intrsctns = results.iterator(); - - crssngs = results.getCrossings(); - int num = 0; - while (crssngs.hasNext()) { - BoundaryCrossing bc = crssngs.next(); - Geo geo = bc.getGeo(); - - OMPoint pgeo = new OMPoint((float) geo.getLatitude(), (float) geo.getLongitude()); - pgeo.setFillPaint(Color.WHITE); - pgeo.putAttribute(OMGraphic.LABEL, new OMTextLabeler(Integer.toString(num++))); - intersectionResultList.add(pgeo); - } - - if (DEBUG) { - Debug.output("have " + intersectionResultList + " crossing points"); - } - } else { - intrsctns = Intersection.intersect(path, rIndex); - } - - while (intrsctns.hasNext()) { - GeoExtent extent = intrsctns.next(); - if (extent instanceof OMGeo) { - setOMGeoAsSelected((OMGeo) extent); - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Set Poly for hit"); - } - } - } - - } else if (omg instanceof OMPoly) { - double[] latlonrad = ((OMPoly) omg).getLatLonArray(); - for (Iterator hits = Intersection - .intersect(new OMGeo.Polygon(GeoArray.Double.createFromLatLonRadians(latlonrad)), rIndex); hits - .hasNext();) { - setOMGeoAsSelected((OMGeo) hits.next()); - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Set Poly for hit"); - } - } - } else if (omg instanceof OMPoint) { - OMPoint omp = (OMPoint) omg; - for (Iterator hits = Intersection.intersect(new GeoPoint.Impl(omp.getLat(), omp.getLon()), - rIndex); hits.hasNext();) { - setOMGeoAsSelected((OMGeo) hits.next()); - - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Set Poly for hit"); - } - } - } - } - } - - protected void setOMGeoAsSelected(OMGeo ompr) { - shapeDASelected.setTo(ompr); - } - - protected GeoPath getPathFromOMGraphic(OMGraphic omg) { - GeoPath path = null; - - if (omg instanceof OMLine) { - path = getPath((OMLine) omg); - } else if (omg instanceof OMPoly) { - path = getPath((OMPoly) omg); - } - - return path; - } - - protected GeoPath getPath(OMLine oml) { - GeoPath ret = null; - if (oml.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - ret = new GeoPath.Impl(oml.getLL()); - } - return ret; - } - - protected GeoPath getPath(OMPoly omp) { - GeoPath ret = null; - if (omp.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - ret = new GeoPath.Impl(omp.getLatLonArray(), false); - } - return ret; - } - - /** - * Query the user for a shape file, and add the contents to the region list - * or line list if a valid file is selected. - */ - public void addShapeFileFromUser(boolean callDoPrepare) { - - String shpFileName = FileUtils.getFilePathToOpenFromUser("Pick Shape File", new FileFilter() { - - public boolean accept(File f) { - return f.isDirectory() || f.getName().endsWith("shp"); - } - - public String getDescription() { - return "ESRI Shape (.shp) file"; - } - - }); - - if (shpFileName != null) { - addShapeFile(new File(shpFileName), callDoPrepare); - } - } - - /** - * Add the data from a shape file to the region list or edge list, depending - * on the content type. - * - * @param shpFile - */ - public void addShapeFile(File shpFile, boolean callDoPrepare) { - if (shpFile != null) { - try { - - if (fileDataList == null) { - fileDataList = new OMGraphicList(); - } - - String shpFilePath = shpFile.getAbsolutePath(); - String shpFileName = shpFile.getName(); - - DrawingAttributes da = new DrawingAttributes(); - da.setSelectPaint(new Color(200, 100, 100, 200)); - - EsriGraphicList shapeList = EsriGraphicList - .getEsriGraphicList(shpFile.toURI().toURL(), shapeDA, - DbfTableModel.getDbfTableModel( - new File(shpFilePath.replaceAll(".shp", ".dbf")).toURI().toURL()), - coordTransform); - - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Adding shapes from " + shpFileName); - } - - JCheckBox visibilityControl = new JCheckBox("Show", true); - visibilityControl.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setShapeListVisibilityForCheckbox(); - repaint(); - } - }); - - int type = shapeList.getType(); - if (type != EsriGraphicList.SHAPE_TYPE_POLYGON && type != EsriGraphicList.SHAPE_TYPE_POLYLINE) { - fireRequestMessage("The type of shapes contained in the file\n" + shpFileName - + "\nisn't handled by this layer. Choose a file that\ncontains lines or polygons."); - return; - } - - // Convert to GeoExtents and add to regionIndex - OMGraphicList geoExtentList = addListToRegionIndex(shapeList, getRegionIndex(false), - new OMGraphicList()); - - JButton removeButton = new JButton("Remove"); - removeButton.addActionListener(new RemoveShapesActionListener(fileDataList, geoExtentList)); - - JLabel label = new JLabel(shpFileName, JLabel.LEFT); - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - panel.setLayout(gridbag); - GridBagConstraints c = new GridBagConstraints(); - c.weightx = 1.0; - c.insets = new Insets(2, 2, 2, 2); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(label, c); - panel.add(label); - c.weightx = 0; - c.anchor = GridBagConstraints.EAST; - c.fill = GridBagConstraints.NONE; - gridbag.setConstraints(visibilityControl, c); - panel.add(visibilityControl); - gridbag.setConstraints(removeButton, c); - panel.add(removeButton); - - geoExtentList.putAttribute(SHAPE_FILE_NAME_ATTRIBUTE, shpFileName); - geoExtentList.putAttribute(SHAPE_VISIBILITY_CONTROL_ATTRIBUTE, visibilityControl); - geoExtentList.putAttribute(SHAPE_CONTROL_ATTRIBUTE, panel); - - fileDataList.add(geoExtentList); - rebuildFileListControl(); - - getWindowSupport().repack(); - - if (callDoPrepare && getProjection() != null) { - doPrepare(); - } - - } catch (MalformedURLException murle) { - } - } - } - - protected void setShapeListVisibilityForCheckbox() { - if (fileDataList != null) { - for (OMGraphic obj : fileDataList) { - if (obj instanceof OMGraphicList) { - OMGraphicList omgl = (OMGraphicList) obj; - JCheckBox jcb = (JCheckBox) omgl.getAttribute(SHAPE_VISIBILITY_CONTROL_ATTRIBUTE); - if (jcb != null) { - omgl.setVisible(jcb.isSelected()); - } - } - } - } - } - - public ExtentIndex getRegionIndex(boolean resetRegionSelection) { - - if (regionIndex == null) { - regionIndex = new ExtentIndexImpl(); - } - - if (resetRegionSelection) { - for (Iterator reset = regionIndex.iterator(); reset.hasNext();) { - GeoExtent nxt = reset.next(); - if (nxt instanceof OMGeo) { - shapeDA.setTo((OMGeo) nxt); - } - } - - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): Reset region colors for " + regionIndex.size()); - } - } - - return regionIndex; - } - - protected void addToRegionIndex(OMGraphic omg, ExtentIndex regionIndex, OMGraphicList addResult) { - OMGeo geoExtent = OMGeo.create(omg); - - if (geoExtent != null) { - addResult.add(geoExtent); - DrawingAttributes.sTransfer(omg, geoExtent); - boolean added = regionIndex.addExtent(geoExtent); - - if (DEBUG) { - Debug.output("GeoIntersectLayer(" + getName() + "): " + (added ? "added" : "skipped") - + " OMGeo to RegionIndex (" + regionIndex.size() + ")"); - } - } - } - - /** - * Add the contents of the list to the ExtentIndex for intersections. - * - * @param omgl The OMGraphicList you want to add - * @param regionIndex the index to add it to - * @param addResult another OMGraphicList you want as the result. This - * should be null if the OMGraphicList is full of OMGeos. Provide - * a new list if you need OMGraphics converted to OMGeos, the - * OMGeos will be on the new list. - * @return the list provided - */ - protected OMGraphicList addListToRegionIndex(OMGraphicList omgl, ExtentIndex regionIndex, OMGraphicList addResult) { - for (OMGraphic omg : omgl) { - if (omg instanceof OMGraphicList) { - if (addResult != null) { - OMGraphicList newOmgl = new OMGraphicList(); - newOmgl.getAttributes().putAll(omg.getAttributes()); - addResult.add(addListToRegionIndex((OMGraphicList) omg, regionIndex, newOmgl)); - } else { - addListToRegionIndex((OMGraphicList) omg, regionIndex, null); - } - } else { - addToRegionIndex(omg, regionIndex, addResult); - } - } - return addResult; - } - - protected void resetRegionIndex() { - ExtentIndex regionIndex = getRegionIndex(false); - regionIndex.clear(); - addListToRegionIndex(fileDataList, regionIndex, null); - } - - public void drawingComplete(OMGraphic omg, OMAction action) { - - releaseProxyMouseMode(); - - if ((omg instanceof OMLine || omg instanceof OMPoly || omg instanceof OMPoint) && drawnList != null) { - drawnList.doAction(omg, action); - deselect(drawnList); - doPrepare(); - } else { - Debug.error("GeoIntersectLayer(" + getName() + "): received " + omg + " and " + action - + " with no list ready"); - } - - // This is important!! - if (editorTool != null) { - editorTool.drawingComplete(omg, action); - } - } - - public OMGraphicList getDrawnIntersectorList() { - return drawnList; - } - - public boolean receivesMapEvents() { - return false; - } - - public boolean mouseOver(MapMouseEvent mme) { - - if (regionIndex != null) { - Point2D llp = mme.getLatLon(); - GeoPoint geop = new GeoPoint.Impl((float) llp.getY(), (float) llp.getX()); - for (Iterator hits = Intersection.intersect(geop, regionIndex); hits.hasNext();) { - GeoExtent extent = hits.next(); - if (extent instanceof OMGeo.Polygon) { - OMGeo.Polygon ompr = (OMGeo.Polygon) extent; - ompr.select(); - ompr.generate(getProjection()); - } - } - repaint(); - } - - return true; - } - - public boolean isHighlightable(OMGraphic omg) { - return createPointCheck || (drawnList != null && drawnList.contains(omg)); - } - - public String getToolTipTextFor(OMGraphic omg) { - if (drawnList != null && drawnList.contains(omg)) { - return super.getToolTipTextFor(omg); - } else if (createPointCheck) { - return "Click to create point test image mask"; - } - return null; - } - - public void highlight(OMGraphic omg) { - omg.setMatted(true); - super.highlight(omg); - } - - public void unhighlight(OMGraphic omg) { - omg.setMatted(false); - super.unhighlight(omg); - } - - public boolean isSelectable(OMGraphic omg) { - return createPointCheck || (drawnList != null && drawnList.contains(omg)); - } - - public void select(OMGraphicList omgl) { - for (OMGraphic omg : omgl) { - if (drawnList != null && drawnList.contains(omg)) { - super.select(omgl); - } - - if (createPointCheck) { - intersectionResultList.add(getPointIntersectionImage(omg)); - } - } - repaint(); - } - - public void deselect(OMGraphicList omgl) { - intersectionResultList.clear(); - repaint(); - } - - public OMGraphic getPointIntersectionImage(OMGraphic omg) { - Shape s = omg.getShape(); - Projection p = getProjection(); - if (s != null && p != null && omg instanceof OMGeo.Polygon) { - Rectangle r = s.getBounds(); - - double x = r.getX(); - double y = r.getY(); - double h = r.getHeight(); - double w = r.getWidth(); - - OMGeo.Polygon poly = (OMGeo.Polygon) omg; - - Point2D llHolder = new Point2D.Double(); - Geo g = new Geo(0, 0); - int[] pix = new int[(int) (h * w)]; - - for (double j = 0; j < h; j++) { - for (double i = 0; i < w; i++) { - - boolean inShape = s.contains(i + x, j + y); - p.inverse((int) (i + x), (int) (j + y), llHolder); - - g.initialize(llHolder.getY(), llHolder.getX()); - boolean inGeo = Intersection.isPointInPolygon(g, poly.getPoints()); - - int val = 0; - if (inShape == inGeo) { - val = 0x6200FF00; - } else { - val = 0x62ff0000; - } - pix[(int) (w * j + i)] = val; - } - } - - OMRaster omr = new OMRaster((int) x, (int) y, (int) w, (int) h, pix); - omr.setSelectPaint(OMColor.clear); - // omr.setSelected(true); - omr.generate(p); - return omr; - } - - return SinkGraphic.getSharedInstance(); - } - - protected JPanel getFileListControl() { - if (fileListControl == null) { - fileListControl = PaletteHelper.createHorizontalPanel("Shape Files Being Used for Intersections"); - rebuildFileListControl(); - } - return fileListControl; - } - - public void rebuildFileListControl() { - JPanel p = getFileListControl(); - p.setBackground(Color.white); - Color light = Color.white; - Color dark = Color.LIGHT_GRAY; - Color current = dark; - - p.removeAll(); - GridBagLayout gridbag = new GridBagLayout(); - p.setLayout(gridbag); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.NORTHWEST; - c.gridx = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0; - - if (fileDataList != null) { - - for (OMGraphic obj : fileDataList) { - - JPanel control = (JPanel) obj.getAttribute(SHAPE_CONTROL_ATTRIBUTE); - - if (control != null) { - control.setBackground(current); - Component[] comps = control.getComponents(); - for (int i = 0; i < comps.length; i++) { - comps[i].setBackground(current); - } - if (current == dark) { - current = light; - } else { - current = dark; - } - gridbag.setConstraints(control, c); - p.add(control); - } - } - } - - if (fileDataList == null || fileDataList.isEmpty()) { - JLabel label = new JLabel("No Shape Files Loaded", JButton.CENTER); - label.setForeground(dark); - c.anchor = GridBagConstraints.CENTER; - gridbag.setConstraints(label, c); - p.add(label); - } - - c.fill = GridBagConstraints.BOTH; - c.weighty = 1; - JLabel filler = new JLabel(""); - gridbag.setConstraints(filler, c); - p.add(filler); - - p.revalidate(); - } - - JPanel fileListControl; - JPanel panel = null; - JCheckBox showCrossingsButton; - JCheckBox pointCheckButton; - - public Component getGUI() { - if (panel == null) { - panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - panel.setLayout(gridbag); - c.gridx = GridBagConstraints.REMAINDER; - c.weightx = 1.0; - c.insets = new Insets(1, 5, 1, 5); - c.fill = GridBagConstraints.HORIZONTAL; - - if (faceOnPalette) { - Container face = editorTool.getFace(); - if (face != null) { - - String interString = i18n.get(GeoCrossDemoLayer.class, "TOOLS", - "Draw shapes to calculate intersections"); - JPanel box = PaletteHelper.createHorizontalPanel(interString); - GridBagLayout boxgridbag = new GridBagLayout(); - GridBagConstraints boxc = new GridBagConstraints(); - - box.setLayout(boxgridbag); - boxc.gridx = GridBagConstraints.REMAINDER; - boxc.weightx = 1.0; - boxc.fill = GridBagConstraints.HORIZONTAL; - boxgridbag.setConstraints(face, boxc); - box.add(face); - - c.insets = new Insets(5, 5, 10, 5); - gridbag.setConstraints(box, c); - panel.add(box); - } - } - - - JPanel checkPanel = new JPanel(); - GridBagLayout gb = new GridBagLayout(); - checkPanel.setLayout(gb); - GridBagConstraints c2 = new GridBagConstraints(); - - c2.anchor = GridBagConstraints.WEST; - c2.gridx = 0; - c2.gridy = 0; - c2.fill = GridBagConstraints.HORIZONTAL; - c2.weightx = 0.0; - showCrossingsButton = new JCheckBox("Show Crossing Points", showCrossingPoints); - showCrossingsButton.setToolTipText("Show ordered points where drawn lines cross Shapes."); - showCrossingsButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setShowCrossingPoints(((JCheckBox) ae.getSource()).isSelected()); - doPrepare(); - } - }); - gb.setConstraints(showCrossingsButton, c2); - checkPanel.add(showCrossingsButton); - - c2.gridx = 1; - c2.weightx = 1.0; - JLabel fillerPanel1 = new JLabel(" "); - gb.setConstraints(fillerPanel1, c2); - checkPanel.add(fillerPanel1); - - c2.gridx = 0; - c2.gridy = 1; - c2.weightx = 0.0; - pointCheckButton = new JCheckBox("Click Creates Image Mask", showCrossingPoints); - pointCheckButton.setToolTipText( - "When clicking on Shape, create image mask that shows Geo point
intersection vs. Java 2D. Green is good."); - pointCheckButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setCreatePointCheck(((JCheckBox) ae.getSource()).isSelected()); - doPrepare(); - } - }); - gb.setConstraints(pointCheckButton, c2); - checkPanel.add(pointCheckButton); - - c2.gridx = 1; - c2.weightx = 1.0; - JLabel fillerPanel2 = new JLabel(" "); - gb.setConstraints(fillerPanel2, c2); - checkPanel.add(fillerPanel2); - - c.weightx = 1.0; - c.weighty = 0; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(checkPanel, c); - panel.add(checkPanel); - - String interString = i18n.get(GeoCrossDemoLayer.class, "SHAPES", "Manage Shapes"); - JPanel facebox = PaletteHelper.createHorizontalPanel(interString); - - GridBagLayout faceboxgridbag = new GridBagLayout(); - GridBagConstraints faceboxc = new GridBagConstraints(); - facebox.setLayout(faceboxgridbag); - - faceboxc.weightx = 1.0; - faceboxc.weighty = 1.0; - faceboxc.gridx = 0; - faceboxc.gridy = 0; - faceboxc.gridwidth = 4; - faceboxc.fill = GridBagConstraints.BOTH; - faceboxc.insets = new Insets(5, 1, 1, 1); - JPanel tablePanel = getFileListControl(); - faceboxgridbag.setConstraints(tablePanel, faceboxc); - facebox.add(tablePanel); - - Component sdaGUI = shapeDA.getGUI("Shapes"); - Component sdasGUI = shapeDASelected.getGUI("Intersected Shapes"); - - faceboxc.gridy = 1; - faceboxc.gridx = 0; - faceboxc.weighty = 0; - faceboxc.weightx = 0; - faceboxc.gridwidth = 1; - faceboxc.fill = GridBagConstraints.NONE; - faceboxc.anchor = GridBagConstraints.WEST; - faceboxc.insets = new Insets(5, 5, 5, 5); - - faceboxgridbag.setConstraints(sdaGUI, faceboxc); - faceboxc.gridx = 1; - faceboxgridbag.setConstraints(sdasGUI, faceboxc); - facebox.add(sdaGUI); - facebox.add(sdasGUI); - - JLabel fill = new JLabel(); - faceboxc.gridx = 2; - faceboxc.fill = GridBagConstraints.HORIZONTAL; - faceboxc.weightx = 1.0; - faceboxgridbag.setConstraints(fill, faceboxc); - facebox.add(fill); - - JButton addButton = new JButton("Add Shape File..."); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - addShapeFileFromUser(true); - } - }); - faceboxc.anchor = GridBagConstraints.EAST; - faceboxc.fill = GridBagConstraints.NONE; - faceboxc.weightx = 0; - faceboxc.gridx = 3; - faceboxgridbag.setConstraints(addButton, faceboxc); - facebox.add(addButton); - - c.insets = new Insets(10, 5, 5, 5); - c.weightx = 1.0; - c.weighty = 1.0; - c.fill = GridBagConstraints.BOTH; - gridbag.setConstraints(facebox, c); - panel.add(facebox); - - } - return panel; - } - - protected class RemoveShapesActionListener implements ActionListener { - protected OMGraphicList mainDataList; - protected OMGraphicList toBeRemoved; - - public RemoveShapesActionListener(OMGraphicList mdl, OMGraphicList tbr) { - mainDataList = mdl; - toBeRemoved = tbr; - } - - public void actionPerformed(ActionEvent ae) { - mainDataList.remove(toBeRemoved); - resetRegionIndex(); - rebuildFileListControl(); - GeoIntersectionLayer.this.doPrepare(); - } - } - - public boolean isShowCrossingPoints() { - return showCrossingPoints; - } - - public void setShowCrossingPoints(boolean showCrossingPoints) { - this.showCrossingPoints = showCrossingPoints; - } - - public void propertyChange(PropertyChangeEvent evt) { - if (fileDataList != null) { - shapeDA.setTo(fileDataList); - repaint(); - } - } - - public DrawingAttributes getShapeDA() { - return shapeDA; - } - - public void setShapeDA(DrawingAttributes shapeDA) { - this.shapeDA = shapeDA; - } - - public DrawingAttributes getShapeDASelected() { - return shapeDASelected; - } - - public void setShapeDASelected(DrawingAttributes shapeDASelected) { - this.shapeDASelected = shapeDASelected; - } - - public boolean isCreatePointCheck() { - return createPointCheck; - } - - public void setCreatePointCheck(boolean createPointCheck) { - this.createPointCheck = createPointCheck; - } - - public void runGeoTests(int numIterations, int numToSkipAtStart) { - Projection proj = new Mercator(new LatLonPoint.Float(35f, -90f), 100000000, 800, 800); - - double[] results = new double[7]; - - for (int i = 0; i < numIterations; i++) { - - boolean countThisIteration = (i >= numToSkipAtStart); - - long startTime = System.currentTimeMillis(); - setProjection(proj.makeClone()); - calculateIntersectionsWithDrawnList(); - long endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[0] += endTime - startTime; - } - - OMGraphic omg = new OMLine(20f, -125f, 30f, -70f, OMGraphic.LINETYPE_GREATCIRCLE); - getDrawnIntersectorList().add(omg); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[1] += endTime - startTime; - } - - setShowCrossingPoints(true); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[2] += endTime - startTime; - } - - getDrawnIntersectorList().clear(); - setShowCrossingPoints(false); - double[] coords = new double[] { 33.4f, -77.2f, 34f, -79.5f, 35f, -90f, 40f, -100f, 45f, -101f, 50f, -83.2f, - 35f, -65.7f, -34f, -70.5f, 33.4f, -77.2f }; - - omg = new OMPoly(coords, OMPoly.DECIMAL_DEGREES, OMGraphic.LINETYPE_GREATCIRCLE); - getDrawnIntersectorList().add(omg); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[3] += endTime - startTime; - } - - setShowCrossingPoints(true); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[4] += endTime - startTime; - } - - omg.setFillPaint(Color.red); - setShowCrossingPoints(false); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[5] += endTime - startTime; - } - - setShowCrossingPoints(true); - startTime = System.currentTimeMillis(); - calculateIntersectionsWithDrawnList(); - endTime = System.currentTimeMillis(); - if (countThisIteration) { - results[6] += endTime - startTime; - } - - System.out.print("."); - System.out.flush(); - - } - - double numIterationsCounted = numIterations - numToSkipAtStart; - Debug.output("For " + numIterationsCounted + " iterations"); - Debug.output(" avg time to calculate without Intersection: " + (results[0] / numIterationsCounted) + " ms"); - Debug.output(" avg time to calculate with Intersection line: " + (results[1] / numIterationsCounted) + " ms"); - Debug.output(" avg time to calculate with Intersection line with crossing points: " - + (results[2] / numIterationsCounted) + " ms"); - Debug.output(" avg time to calculate with Intersection poly: " + (results[3] / numIterationsCounted) + " ms"); - Debug.output(" avg time to calculate with Intersection poly with crossing points: " - + (results[4] / numIterationsCounted) + " ms"); - Debug.output(" avg time to calculate with Intersection Containment poly: " + (results[5] / numIterationsCounted) - + " ms"); - Debug.output(" avg time to calculate with Intersection Containment poly and crossing points: " - + (results[6] / numIterationsCounted) + " ms"); - - } - - public static void main(String[] argv) { - Debug.init(); - ArgParser argp = new ArgParser("GeoIntersectionLayer"); - - argp.add("shape", "Shape file to use for GeoRegions in index.", 1); - - argp.parse(argv); - String[] files = argp.getArgValues("shape"); - if (files != null && files.length > 0 && files[0].endsWith(".shp")) { - File file = new File(files[0]); - - GeoIntersectionLayer gil = new GeoIntersectionLayer(); - Debug.output("Loading shape file: " + file.getName()); - long startTime = System.currentTimeMillis(); - gil.addShapeFile(file, false); - long endTime = System.currentTimeMillis(); - - Debug.output(" time to load file: " + (endTime - startTime) + " ms"); - - gil.runGeoTests(25, 3); - - } else { - argp.printUsage(); - System.exit(0); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/HelloWorldLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/HelloWorldLayer.java deleted file mode 100644 index c24a22606..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/HelloWorldLayer.java +++ /dev/null @@ -1,221 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/test/HelloWorldLayer.java,v $ -// $RCSfile: HelloWorldLayer.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.test; - -import java.awt.Color; -import java.awt.Graphics; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * Layer objects are components which can be added to the MapBean to - * make a map. - *

- * Layers implement the ProjectionListener interface to listen for - * ProjectionEvents. When the projection changes, they may need to - * refetch, regenerate their graphics, and then repaint themselves - * into the new view. - */ -public class HelloWorldLayer extends Layer { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected OMGraphicList graphics; - - /** - * Construct the layer. - */ - public HelloWorldLayer() { - super(); - graphics = new OMGraphicList(10); - createGraphics(graphics); - } - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than - * the setArgs method. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - super.setProperties(prefix, props); - } - - /** - * Invoked when the projection has changed or this Layer has been - * added to the MapBean. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - graphics.generate(e.getProjection()); - repaint(); - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(Graphics g) { - graphics.render(g); - } - - /** - * Create graphics. - */ - protected void createGraphics(OMGraphicList list) { - // NOTE: all this is very non-optimized... - - OMPoly poly; - - // H - poly = new OMPoly(new double[] { 10f, -150f, 35f, -150f, 35f, -145f, - 25f, -145f, 25f, -135f, 35f, -135f, 35f, -130f, 10f, -130f, - 10f, -135f, 20f, -135f, 20f, -145f, 10f, -145f, 10f, -150f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // E - poly = new OMPoly(new double[] { 10f, -120f, 35f, -120f, 35f, -100f, - 30f, -100f, 30f, -115f, 25f, -115f, 25f, -105f, 20f, -105f, - 20f, -115f, 15f, -115f, 15f, -100f, 10f, -100f, 10f, -120f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // L - poly = new OMPoly(new double[] { 10f, -90f, 35f, -90f, 35f, -85f, 15f, - -85f, 15f, -75f, 10f, -75f, 10f, -90f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // L - poly = new OMPoly(new double[] { 10f, -70f, 35f, -70f, 35f, -65f, 15f, - -65f, 15f, -55f, 10f, -55f, 10f, -70f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // O - poly = new OMPoly(new double[] { 10f, -50f, 35f, -50f, 35f, -30f, 10f, - -30f, 10f, -50f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { 15f, -45f, 30f, -45f, 30f, -35f, 15f, - -35f, 15f, -45f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { 10f, -50f, 35f, -50f, 35f, -30f, 10f, - -30f, 10f, -45f, 15f, -45f, 15f, -35f, 30f, -35f, 30f, -45f, - 10f, -45f, 10f, -50f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(OMGraphic.clear); - poly.setFillPaint(Color.green); - list.add(poly); - - // W - poly = new OMPoly(new double[] { -35f, -5f, -10f, -5f, -10f, 0f, -25f, - 0f, -25f, 5f, -20f, 5f, -20f, 10f, -25f, 10f, -25f, 15f, -10f, - 15f, -10f, 20f, -35f, 20f, -35f, 10f, -30f, 10f, -30f, 5f, - -35f, 5f, -35f, -5f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // O - poly = new OMPoly(new double[] { -35f, 30f, -10f, 30f, -10f, 50f, -35f, - 50f, -35f, 30f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -30f, 35f, -15f, 35f, -15f, 45f, -30f, - 45f, -30f, 35f, }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -35f, 30f, -10f, 30f, -10f, 50f, -35f, - 50f, -35f, 35f, -30f, 35f, -30f, 45f, -15f, 45f, -15f, 35f, - -35f, 35f, -35f, 30f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(OMGraphic.clear); - poly.setFillPaint(Color.green); - list.add(poly); - - // R - poly = new OMPoly(new double[] { -35f, 60f, -10f, 60f, -10f, 75f, -20f, - 75f, -25f, 70f, -30f, 80f, -35f, 80f, -35f, 75f, -30f, 70f, - -30f, 65f, -35f, 65f, -35f, 60f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -20f, 65f, -15f, 65f, -15f, 70f, -20f, - 70f, -20f, 65f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -35f, 60f, -10f, 60f, -10f, 75f, -20f, - 75f, -25f, 70f, -30f, 80f, -35f, 80f, -35f, 75f, -30f, 70f, - -30f, 65f, -20f, 65f, -20f, 70f, -15f, 70f, -15f, 65f, -35f, - 65f, -35f, 60f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(OMGraphic.clear); - poly.setFillPaint(Color.green); - list.add(poly); - - // L - poly = new OMPoly(new double[] { -35f, 90f, -10f, 90f, -10f, 95f, -30f, - 95f, -30f, 105f, -35f, 105f, -35f, 90f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(Color.green); - list.add(poly); - - // D - poly = new OMPoly(new double[] { -35f, 110f, -10f, 110f, -10f, 125f, - -15f, 130f, -30f, 130f, -35f, 125f, -35f, 110f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -30f, 115f, -15f, 115f, -15f, 120f, - -20f, 125f, -25f, 125f, -30f, 120f, -30f, 115f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(Color.black); - poly.setFillPaint(OMGraphic.clear); - list.add(poly); - poly = new OMPoly(new double[] { -35f, 110f, -10f, 110f, -10f, 125f, - -15f, 130f, -30f, 130f, -35f, 125f, -35f, 115f, -30f, 115f, - -30f, 120f, -25f, 125f, -20f, 125f, -15f, 120f, -15f, 115f, - -35f, 115f, -35f, 110f }, OMGraphic.DECIMAL_DEGREES, OMGraphic.LINETYPE_RHUMB, 32); - poly.setLinePaint(OMGraphic.clear); - poly.setFillPaint(Color.green); - list.add(poly); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/TestLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/test/TestLayer.java deleted file mode 100644 index e62cd596b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/TestLayer.java +++ /dev/null @@ -1,1283 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/test/TestLayer.java,v $ -// $RCSfile: TestLayer.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.test; - -import java.awt.Color; -import java.awt.Component; -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.FocusAdapter; -import java.awt.event.FocusEvent; -import java.awt.event.MouseEvent; -import java.util.StringTokenizer; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMArrowHead; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - * A Layer for testing different types of graphics. The GUI code is - * very large and ugly. Maybe break this off into several classes. - *

- * This layer responds to the following properties: - *

- * 
- *  # initial visibility settings:
- *  test.line.visible=true
- *  test.circ.visible=true
- *  test.rect.visible=true
- *  test.text.visible=true
- *  test.poly.visible=true
- *  # latlon vertices of the poly
- *  #test.poly.vertices=80 -180 80 -90 80 0 80 90 80 180 70 180 70 90 70 0 70 -90 70 -180
- *  
- * 
- * 
- * In addition, you can get this layer to work with the - * OpenMap viewer by editing your openmap.properties file: - *
- * 
- *  # layers
- *  openmap.layers=test ...
- *  # class
- *  test.class=com.bbn.openmap.layer.TestLayer
- *  # name
- *  test.prettyName=Graticule
- * 
- * 
- */ -public class TestLayer extends OMGraphicHandlerLayer implements - MapMouseListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - public final static transient String LineVisibleProperty = ".line.visible"; - public final static transient String CircVisibleProperty = ".circ.visible"; - public final static transient String RectVisibleProperty = ".rect.visible"; - public final static transient String TextVisibleProperty = ".text.visible"; - public final static transient String PolyVisibleProperty = ".poly.visible"; - public final static transient String PolyVertsProperty = ".poly.vertices"; - - // colors - protected final static transient String[] colorNames = new String[] { - "white", "lightGray", "gray", "darkGray", "black", "red", "pink", - "orange", "yellow", "green", "magenta", "cyan", "blue", "clear" }; - protected final static transient Color[] colors = new Color[] { - Color.white, Color.lightGray, Color.gray, Color.darkGray, - Color.black, Color.red, Color.pink, Color.orange, Color.yellow, - Color.green, Color.magenta, Color.cyan, Color.blue, OMGraphic.clear }; - protected final static transient int NCOLORS = colors.length; - - // graphics and peers - protected OMCircle omcircle = new OMCircle(); - protected Circle circle = new Circle(); - - protected OMLine omline = new OMLine(); - protected Line line = new Line(); - - protected OMRect omrect = new OMRect(); - protected Rect rect = new Rect(); - - protected OMText omtext = new OMText(); - protected Text text = new Text(); - - protected OMPoly ompoly = new OMPoly(); - protected Poly poly = new Poly(); - - protected JPanel gui = null;// the GUI - - /** - * Construct the TestLayer. - */ - public TestLayer() {} - - /** - * The properties and prefix are managed and decoded here, for the - * standard uses of the GraticuleLayer. - * - * @param prefix string prefix used in the properties file for - * this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - - line.visible = Boolean.valueOf(properties.getProperty(prefix - + LineVisibleProperty, "true")).booleanValue(); - - circle.visible = Boolean.valueOf(properties.getProperty(prefix - + CircVisibleProperty, "true")).booleanValue(); - - rect.visible = Boolean.valueOf(properties.getProperty(prefix - + RectVisibleProperty, "true")).booleanValue(); - - text.visible = Boolean.valueOf(properties.getProperty(prefix - + TextVisibleProperty, "true")).booleanValue(); - - poly.visible = Boolean.valueOf(properties.getProperty(prefix - + PolyVisibleProperty, "true")).booleanValue(); - - String verts = properties.getProperty(prefix + PolyVertsProperty); - if (verts != null) { - poly.setVertices(verts); - } - } - - public synchronized OMGraphicList prepare() { - if (getList() == null) { - setList(generateGraphics()); - } - return super.prepare(); - } - - /** - * Create and project the graphics. - */ - protected OMGraphicList generateGraphics() { - OMGraphicList graphics = new OMGraphicList(); - - // create OMLine from internal line representation - switch (line.rt) { - case OMGraphic.RENDERTYPE_LATLON: - omline = new OMLine(line.llpts[0], line.llpts[1], line.llpts[2], line.llpts[3], line.type, line.nsegs); - break; - case OMGraphic.RENDERTYPE_XY: - omline = new OMLine(line.xypts[0], line.xypts[1], line.xypts[2], line.xypts[3]); - break; - case OMGraphic.RENDERTYPE_OFFSET: - omline = new OMLine(line.llpts[0], line.llpts[1], line.xypts[0], line.xypts[1], line.xypts[2], line.xypts[3]); - break; - default: - System.err.println("ARRRR!"); - break; - } - if (line.arrowhead) { - omline.addArrowHead(line.arrowtype); - } - - // create OMCircle from internal circle representation - switch (circle.rt) { - case OMGraphic.RENDERTYPE_LATLON: - omcircle = new OMCircle(circle.llpts[0], circle.llpts[1], circle.radius, Length.KM, circle.nsegs); - omcircle.setPolarCorrection(true); - break; - case OMGraphic.RENDERTYPE_XY: - omcircle = new OMCircle(circle.xypts[0], circle.xypts[1], circle.width, circle.height); - break; - case OMGraphic.RENDERTYPE_OFFSET: - omcircle = new OMCircle(circle.llpts[0], circle.llpts[1], circle.xypts[0], circle.xypts[1], circle.width, circle.height); - break; - default: - System.err.println("ARRRR!"); - break; - } - - // create OMRect from internal rect representation - switch (rect.rt) { - case OMGraphic.RENDERTYPE_LATLON: - omrect = new OMRect(rect.llpts[0], rect.llpts[1], rect.llpts[2], rect.llpts[3], rect.type, rect.nsegs); - break; - case OMGraphic.RENDERTYPE_XY: - omrect = new OMRect(rect.xypts[0], rect.xypts[1], rect.xypts[2], rect.xypts[3]); - break; - case OMGraphic.RENDERTYPE_OFFSET: - omrect = new OMRect(rect.llpts[0], rect.llpts[1], rect.xypts[0], rect.xypts[1], rect.xypts[2], rect.xypts[3]); - break; - default: - System.err.println("ARRRR!"); - break; - } - - // create OMText from internal text representation - switch (text.rt) { - case OMGraphic.RENDERTYPE_LATLON: - omtext = new OMText(text.llpts[0], text.llpts[1], text.data, Font.decode(text.font), text.just); - break; - case OMGraphic.RENDERTYPE_XY: - omtext = new OMText(text.xypts[0], text.xypts[1], text.data, Font.decode(text.font), text.just); - break; - case OMGraphic.RENDERTYPE_OFFSET: - omtext = new OMText(text.llpts[0], text.llpts[1], text.xypts[0], text.xypts[1], text.data, Font.decode(text.font), text.just); - break; - default: - System.err.println("ARRRR!"); - break; - } - - // create OMPoly from internal poly representation - switch (poly.rt) { - case OMGraphic.RENDERTYPE_LATLON: - int len = poly.llpts.length; - double[] llpts = new double[len]; - System.arraycopy(poly.llpts, 0, llpts, 0, len); - ompoly = new OMPoly(llpts, OMPoly.DECIMAL_DEGREES, poly.type, poly.nsegs); - break; - case OMGraphic.RENDERTYPE_XY: - ompoly = new OMPoly(poly.xypts); - break; - case OMGraphic.RENDERTYPE_OFFSET: - ompoly = new OMPoly(poly.lat, poly.lon, poly.xypts, poly.cMode); - break; - default: - System.err.println("ARRRR!"); - break; - } - - // generic - omline.setVisible(line.visible); - omline.setLinePaint(colors[line.lineColor]); - omcircle.setVisible(circle.visible); - omcircle.setLinePaint(colors[circle.lineColor]); - omrect.setVisible(rect.visible); - omrect.setLinePaint(colors[rect.lineColor]); - ompoly.setVisible(poly.visible); - ompoly.setLinePaint(colors[poly.lineColor]); - omtext.setVisible(text.visible); - omtext.setLinePaint(colors[text.lineColor]); - if (circle.isFilled) - omcircle.setFillPaint(colors[circle.fillColor]); - if (rect.isFilled) - omrect.setFillPaint(colors[rect.fillColor]); - if (poly.isFilled) - ompoly.setFillPaint(colors[poly.fillColor]); - - graphics.add(omline); - graphics.add(omcircle); - graphics.add(omrect); - graphics.add(omtext); - graphics.add(ompoly); - graphics.generate(getProjection()); - - return graphics; - } - - /** - * Gets the palette associated with the layer. - *

- * - * @return Component or null - */ - public Component getGUI() { - if (gui == null) { - JPanel pal; - - gui = PaletteHelper.createPaletteJPanel("Test"); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints constraints = new GridBagConstraints(); - gui.setLayout(gridbag); - constraints.fill = GridBagConstraints.HORIZONTAL; // fill - // horizontally - constraints.gridwidth = GridBagConstraints.REMAINDER; //another - // row - constraints.anchor = GridBagConstraints.EAST; // tack to - // the left - // edge - // constraints.weightx = 0.0; - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - int index = Integer.parseInt(e.getActionCommand(), 10); - switch (index) { - case 0: - line.visible = !line.visible; - omline.setVisible(line.visible); - repaint(); - break; - case 1: - circle.visible = !circle.visible; - omcircle.setVisible(circle.visible); - repaint(); - break; - case 2: - rect.visible = !rect.visible; - omrect.setVisible(rect.visible); - repaint(); - break; - case 3: - text.visible = !text.visible; - omtext.setVisible(text.visible); - repaint(); - break; - case 4: - poly.visible = !poly.visible; - ompoly.setVisible(poly.visible); - repaint(); - break; - default: - System.out.println("TestLayer: Unimplemented..."); - } - } - }; - pal = PaletteHelper.createCheckbox("Graphics", new String[] { - "Line", "Circle", "Rect", "Text", "Poly" }, new boolean[] { - line.visible, circle.visible, rect.visible, text.visible, - poly.visible }, al); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - - // line controls - pal = getGraphicPalette(line, "Line"); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - - // circle controls - pal = getGraphicPalette(circle, "Circle"); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - - // rect controls - pal = getGraphicPalette(rect, "Rect"); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - - // text controls - pal = getGraphicPalette(text, "Text"); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - - // poly controls - pal = getGraphicPalette(poly, "Poly"); - gridbag.setConstraints(pal, constraints); - gui.add(pal); - } - return gui; - } - - /** - * Create the sub-palette for a particular graphic type. - * - * @param obj GraphicObj - * @param title panel title - * @return JPanel sub-palette - */ - protected JPanel getGraphicPalette(final GraphicBase obj, final String title) { - - final JComboBox jcb; - final JFrame jframe; - final JRootPane main; - final JPanel parent; - - parent = PaletteHelper.createVerticalPanel(title); - jframe = new JFrame(); - main = jframe.getRootPane(); - - // different controls for different render types - jcb = new JComboBox(); - jcb.addItem("LatLon");// indices correspond to LineType.java - jcb.addItem("XY"); - jcb.addItem("Offset"); - jcb.setSelectedIndex(obj.rt - 1); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - obj.setRender(jcb); - switch (obj.rt) { - case OMGraphic.RENDERTYPE_LATLON: - jframe.setTitle(title + " - LatLon"); - main.getContentPane().removeAll(); - main.getContentPane().add(obj.getGUI()); - jframe.pack(); - jframe.setVisible(true); - break; - case OMGraphic.RENDERTYPE_XY: - jframe.setTitle(title + " - XY"); - main.getContentPane().removeAll(); - main.getContentPane().add(obj.getGUI()); - jframe.pack(); - jframe.setVisible(true); - break; - case OMGraphic.RENDERTYPE_OFFSET: - jframe.setTitle(title + " - XY Offset"); - main.getContentPane().removeAll(); - main.getContentPane().add(obj.getGUI()); - jframe.pack(); - jframe.setVisible(true); - break; - default: - System.err.println("ARRRR!"); - break; - } - } - }); - parent.add(jcb); - - return parent; - } - - /** - * Returns self as the MapMouseListener in order to - * receive MapMouseEvents. If the implementation - * would prefer to delegate MapMouseEvents, it - * could return the delegate from this method instead. - * - * @return MapMouseListener this - */ - public MapMouseListener getMapMouseListener() { - return this; - } - - /** - * Return a list of the modes that are interesting to the - * MapMouseListener. The source MouseEvents will only get sent to - * the MapMouseListener if the mode is set to one that the - * listener is interested in. Layers interested in receiving - * events should register for receiving events in "select" mode. - *


-     * 
-     * return new String[1] { SelectMouseMode.modeID };
-     * 
-     * 
- * @see com.bbn.openmap.event.NavMouseMode#modeID - * @see com.bbn.openmap.event.SelectMouseMode#modeID - * @see com.bbn.openmap.event.NullMouseMode#modeID - */ - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mousePressed()"); - } - return true; - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseReleased()"); - } - return true; - } - - /** - * Invoked when the mouse has been clicked on a component. The - * listener will receive this event if it successfully processed - * mousePressed(), or if no other listener - * processes the event. If the listener successfully processes - * mouseClicked(), then it will receive the next mouseClicked() - * notifications that have a click count greater than one. - * - * @param e MouseListener MouseEvent to handle. - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseClicked()"); - } - return true; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseListener MouseEvent to handle. - */ - public void mouseEntered(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseEntered()"); - } - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseListener MouseEvent to handle. - */ - public void mouseExited(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseExited()"); - } - } - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. The listener will receive these events if it - * successfully processes mousePressed(), or if no other listener - * processes the event. - * - * @param e MouseMotionListener MouseEvent to handle. - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseDragged()"); - } - return true; - } - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons no down). - * - * @param e MouseListener MouseEvent to handle. - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e) { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseMoved()"); - } - return true; - } - - /** - * Handle a mouse cursor moving without the button being pressed. - * This event is intended to tell the listener that there was a - * mouse movement, but that the event was consumed by another - * layer. This will allow a mouse listener to clean up actions - * that might have happened because of another motion event - * response. - */ - public void mouseMoved() { - if (Debug.debugging("TestLayer")) { - System.out.println("TestLayer.mouseMoved()[alt]"); - } - } - - ////////////////////////////////////////////////////////////////// - - /* - * The GUI code is implemented here. - */ - protected abstract class GraphicBase { - // ll data - protected double[] llpts = new double[4]; - protected float radius = 4000f; - protected int type = OMGraphic.LINETYPE_GREATCIRCLE; - protected int nsegs = 360; - - // xy data - protected int[] xypts = new int[4]; - protected int width, height; - - // generic - protected int lineColor = NCOLORS - 2; - protected int fillColor = NCOLORS - 1; - protected boolean visible = true; - protected boolean isFilled = false; - protected int rt = OMGraphic.RENDERTYPE_LATLON; - - // GUI code - protected abstract JPanel getGUI(); - - protected void setXYCoordinate(JTextField jtf, int i) { - try { - xypts[i] = Integer.parseInt(jtf.getText().trim()); - } catch (NumberFormatException ex) { - return; - } - } - - protected void setLLCoordinate(JTextField jtf, int i) { - try { - llpts[i] = Double.valueOf(jtf.getText().trim()).doubleValue(); - } catch (NumberFormatException ex) { - return; - } - } - - protected void setType(JComboBox jcb) { - type = jcb.getSelectedIndex() + 1; - setList(generateGraphics()); - repaint(); - } - - protected void setRender(JComboBox jcb) { - rt = jcb.getSelectedIndex() + 1; - setList(generateGraphics()); - repaint(); - } - - protected void setSegs(JTextField jtf) { - try { - nsegs = Integer.parseInt(jtf.getText().trim()); - } catch (NumberFormatException ex) { - return; - } - } - - protected void makeFillCheckBox(JComponent parent) { - JPanel pal = PaletteHelper.createCheckbox(null, - new String[] { "Filled" }, - new boolean[] { isFilled }, - new ActionListener() { - public void actionPerformed(ActionEvent e) { - isFilled = !isFilled; - setList(generateGraphics()); - repaint(); - } - }); - parent.add(pal); - } - - protected void makeColorBox(JComponent parent, String title, - final boolean isFill) { - JPanel pal = PaletteHelper.createVerticalPanel(title); - final JComboBox jcb = new JComboBox(); - for (int i = 0; i < NCOLORS; i++) { - jcb.addItem(colorNames[i]); - } - jcb.setSelectedIndex(isFill ? fillColor : lineColor); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (isFill) - fillColor = jcb.getSelectedIndex(); - else - lineColor = jcb.getSelectedIndex(); - setList(generateGraphics()); - repaint(); - } - }); - pal.add(jcb); - parent.add(pal); - } - - // get an OK button which refreshes the display. - protected JButton getOKButton() { - // add reset button - JButton jb = new JButton("OK"); - jb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - setList(generateGraphics()); - repaint(); - } - }); - return jb; - } - } - - protected class Line extends GraphicBase { - - protected int arrowtype = -1; - protected boolean arrowhead = false; - - public Line() { - llpts[0] = 45.0; - llpts[1] = -90.0; - llpts[2] = 0.0; - llpts[3] = -180.0; - xypts[0] = 45; - xypts[1] = 90; - xypts[2] = 0; - xypts[3] = 180; - lineColor = 5; - } - - // makes arrow head selection - protected void makeArrowHeadGUI(JComponent parent) { - JPanel pal; - pal = PaletteHelper.createVerticalPanel(null); - final JComboBox jcb = new JComboBox(); - jcb.addItem("None"); - jcb.addItem("Arrow Forward"); - jcb.addItem("Arrow Back"); - jcb.addItem("Arrow Both"); - jcb.setSelectedIndex(arrowtype + 1); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - switch (jcb.getSelectedIndex()) { - case 0: - System.out.println("TestLayer: no arrows"); - omline.addArrowHead(false); - arrowhead = false; - arrowtype = -1; - break; - case 1: - System.out.println("TestLayer: arrows forward"); - arrowhead = true; - arrowtype = OMArrowHead.ARROWHEAD_DIRECTION_FORWARD; - break; - case 2: - System.out.println("TestLayer: arrows backward"); - arrowhead = true; - arrowtype = OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD; - break; - case 3: - System.out.println("TestLayer: arrows both"); - arrowhead = true; - arrowtype = OMArrowHead.ARROWHEAD_DIRECTION_BOTH; - break; - } - setList(generateGraphics()); - repaint(); - } - }); - pal.add(jcb); - parent.add(pal); - } - - public JPanel getGUI() { - // request focus - requestFocus(); - - JTextField tf; - JPanel pal; - final JPanel pop; - pop = PaletteHelper.createVerticalPanel(null); - - // add arrowheads - if (!(this instanceof Rect)) - makeArrowHeadGUI(pop); - - if (rt == OMGraphic.RENDERTYPE_LATLON) { - pal = PaletteHelper.createVerticalPanel(null); - JComboBox jcb = new JComboBox(); - jcb.addItem("Straight");// indices correspond to - // LineType.java - jcb.addItem("Rhumb"); - jcb.addItem("Great Circle"); - jcb.setSelectedIndex(type - 1); - jcb.addActionListener(new ActionListener() { - @SuppressWarnings("unchecked") - public void actionPerformed(ActionEvent e) { - setType((JComboBox) e.getSource()); - } - }); - pal.add(jcb); - pop.add(pal); - tf = PaletteHelper.createTextEntry("nsegs", "" + nsegs, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setSegs((JTextField) e.getSource()); - } - }); - } - if (rt != OMGraphic.RENDERTYPE_XY) { - tf = PaletteHelper.createTextEntry("lat1", "" + llpts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("lon1", "" + llpts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 1); - } - }); - } - - if (rt == OMGraphic.RENDERTYPE_LATLON) { - tf = PaletteHelper.createTextEntry("lat2", "" + llpts[2], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 2); - } - }); - tf = PaletteHelper.createTextEntry("lon2", "" + llpts[3], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 3); - } - }); - } else { - tf = PaletteHelper.createTextEntry("x1", "" + xypts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("y1", "" + xypts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 1); - } - }); - tf = PaletteHelper.createTextEntry("x2", "" + xypts[2], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 2); - } - }); - tf = PaletteHelper.createTextEntry("y2", "" + xypts[3], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 3); - } - }); - } - - // line color - makeColorBox(pop, "line", false); - - // fill color - if (this instanceof Rect) - makeColorBox(pop, "fill", true); - - // filled? - if (this instanceof Rect) - makeFillCheckBox(pop); - - // add ok button - pop.add(getOKButton()); - - return pop; - } - } - - protected class Rect extends Line { - public Rect() { - llpts[0] = -80.0; - llpts[1] = 0.0; - llpts[2] = 10.0; - llpts[3] = 45.0; - xypts[0] = 250; - xypts[1] = 100; - xypts[2] = 150; - xypts[3] = 380; - lineColor = 0; - fillColor = 9; - type = OMGraphic.LINETYPE_RHUMB; - } - } - - protected class Circle extends GraphicBase { - - public Circle() { - xypts[0] = 10; - xypts[1] = 20; - width = 10; - height = 20; - fillColor = 0; - } - - public JPanel getGUI() { - // request focus - requestFocus(); - - final JPanel pop; - JTextField tf; - pop = PaletteHelper.createVerticalPanel(null); - - if (rt != OMGraphic.RENDERTYPE_XY) { - tf = PaletteHelper.createTextEntry("lat", "" + llpts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("lon", "" + llpts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 1); - } - }); - } else { - tf = PaletteHelper.createTextEntry("x", "" + xypts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("y", "" + xypts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 1); - } - }); - } - - if (rt == OMGraphic.RENDERTYPE_OFFSET) { - tf = PaletteHelper.createTextEntry("off_x", "" + xypts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("off_y", "" + xypts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 1); - } - }); - } else if (rt == OMGraphic.RENDERTYPE_LATLON) { - tf = PaletteHelper.createTextEntry("R (km)", "" + radius, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - JTextField jtf = (JTextField) e.getSource(); - float f = radius; - try { - f = Float.valueOf(jtf.getText().trim()) - .floatValue(); - } catch (NumberFormatException ex) { - return; - } - radius = f; - System.out.println("TestLayer: radius=" + radius); - } - }); - tf = PaletteHelper.createTextEntry("nverts", "" + nsegs, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setSegs((JTextField) e.getSource()); - } - }); - } - - if (rt != OMGraphic.RENDERTYPE_LATLON) { - tf = PaletteHelper.createTextEntry("width", "" + width, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - JTextField jtf = (JTextField) e.getSource(); - try { - width = Integer.parseInt(jtf.getText().trim()); - } catch (NumberFormatException ex) { - return; - } - } - }); - tf = PaletteHelper.createTextEntry("height", "" + height, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - JTextField jtf = (JTextField) e.getSource(); - try { - height = Integer.parseInt(jtf.getText().trim()); - } catch (NumberFormatException ex) { - return; - } - } - }); - } - - // line color - makeColorBox(pop, "line", false); - - // fill color - makeColorBox(pop, "fill", true); - - // filled? - makeFillCheckBox(pop); - - // add ok button - pop.add(getOKButton()); - - return pop; - } - } - - protected class Poly extends GraphicBase { - - protected float lat = 0f; - protected float lon = 0f; - protected int cMode = OMPoly.COORDMODE_ORIGIN; - - public Poly() { - llpts = new double[8]; - xypts = new int[6]; - llpts[0] = 10.0; - llpts[1] = -20.0; - llpts[2] = 45.0; - llpts[3] = -70.0; - llpts[4] = 0.0; - llpts[5] = -90.0; - llpts[6] = -15.0; - llpts[7] = -40.0; - xypts[0] = 145; - xypts[1] = 190; - xypts[2] = 160; - xypts[3] = 210; - xypts[2] = 135; - xypts[3] = 215; - lineColor = 4; - fillColor = 9; - type = OMGraphic.LINETYPE_GREATCIRCLE; - } - - // set latlon vertices - protected void setVertices(String verts) { - try { - String str; - StringTokenizer tok = new StringTokenizer(verts, "\n\r"); - - // clean out comments - StringBuilder sb = new StringBuilder(); - while (tok.hasMoreTokens()) { - str = tok.nextToken().trim(); - if (str.charAt(0) != '#') { - sb.append(str).append(" "); - } - } - - // extract vertices - tok = new StringTokenizer(sb.toString()); - int size = tok.countTokens(); - System.out.println("ll size=" + size); - llpts = new double[size]; - for (int i = 0; i < size; i += 2) { - str = tok.nextToken(); - System.out.print("lat=" + str); - llpts[i] = Double.valueOf(str).doubleValue(); - str = tok.nextToken(); - System.out.println(" lon=" + str); - llpts[i + 1] = Double.valueOf(str).doubleValue(); - } - } catch (NumberFormatException ex) { - return; - } - } - - protected void setXY(JTextArea jta) { - try { - // throw new NumberFormatException("foo"); - } catch (NumberFormatException ex) { - return; - } - } - - protected void setLL(JTextArea jta) { - setVertices(jta.getText().trim()); - } - - protected void setLLCoordinate(JTextField jtf, int i) { - try { - if (i == 0) - lat = Float.valueOf(jtf.getText().trim()).floatValue(); - else - lon = Float.valueOf(jtf.getText().trim()).floatValue(); - } catch (NumberFormatException ex) { - return; - } - } - - public JPanel getGUI() { - // request focus - requestFocus(); - - final JPanel pop; - JPanel pal; - JTextField tf; - JTextArea ta; - pop = PaletteHelper.createVerticalPanel(null); - - if (rt == OMGraphic.RENDERTYPE_LATLON) { - pal = PaletteHelper.createVerticalPanel(null); - JComboBox jcb = new JComboBox(); - jcb.addItem("Straight");// indices correspond to - // LineType.java - jcb.addItem("Rhumb"); - jcb.addItem("Great Circle"); - jcb.setSelectedIndex(type - 1); - jcb.addActionListener(new ActionListener() { - @SuppressWarnings("unchecked") - public void actionPerformed(ActionEvent e) { - setType((JComboBox) e.getSource()); - } - }); - pal.add(jcb); - pop.add(pal); - tf = PaletteHelper.createTextEntry("nsegs", "" + nsegs, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setSegs((JTextField) e.getSource()); - } - }); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < llpts.length; i += 2) { - sb.append(llpts[i]).append(" ").append(llpts[i + 1]).append("\n"); - } - ta = PaletteHelper.createTextArea("llpts", sb.toString(), pop, 5, 8); - ta.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLL((JTextArea) e.getSource()); - } - }); - } else { - if (rt == OMGraphic.RENDERTYPE_OFFSET) { - tf = PaletteHelper.createTextEntry("lat", - "" + llpts[0], - pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("lon", - "" + llpts[1], - pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 1); - } - }); - } - StringBuilder entry = new StringBuilder(); - for (int i = 0; i < xypts.length; i += 2) { - entry.append(xypts[i]).append(" ").append(xypts[i + 1]).append("\n"); - } - ta = PaletteHelper.createTextArea("xypts", entry.toString(), pop, 0, 0); - ta.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXY((JTextArea) e.getSource()); - } - }); - } - - // line color - makeColorBox(pop, "line", false); - - // fill color - makeColorBox(pop, "fill", true); - - // filled? - makeFillCheckBox(pop); - - // add ok button - pop.add(getOKButton()); - - return pop; - } - } - - protected class Text extends GraphicBase { - protected String data; - protected String font = "SansSerif-Bold-18"; - protected int just = OMText.JUSTIFY_CENTER; - - public Text() { - llpts[0] = 42.35; - llpts[1] = -70.5; - xypts[0] = 20; - xypts[1] = 10; - lineColor = 10; - data = "Boston"; - } - - public JPanel getGUI() { - // request focus - requestFocus(); - - final JPanel pop; - JPanel pal; - JTextField tf; - final JComboBox jcb; - pop = PaletteHelper.createVerticalPanel(null); - - tf = PaletteHelper.createTextEntry("text", data, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - data = ((JTextField) (e.getSource())).getText().trim(); - } - }); - - tf = PaletteHelper.createTextEntry("font", font, pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - font = ((JTextField) (e.getSource())).getText().trim(); - } - }); - - pal = PaletteHelper.createVerticalPanel(null); - jcb = new JComboBox(); - jcb.addItem("right");// indices correspond to values in - // OMText - jcb.addItem("center"); - jcb.addItem("left"); - jcb.setSelectedIndex(just); - jcb.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - just = jcb.getSelectedIndex(); - setList(generateGraphics()); - repaint(); - } - }); - pal.add(jcb); - pop.add(pal); - - if (rt != OMGraphic.RENDERTYPE_XY) { - tf = PaletteHelper.createTextEntry("lat", "" + llpts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("lon", "" + llpts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setLLCoordinate((JTextField) e.getSource(), 1); - } - }); - } - - if (rt != OMGraphic.RENDERTYPE_LATLON) { - tf = PaletteHelper.createTextEntry("off_x", "" + xypts[0], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 0); - } - }); - tf = PaletteHelper.createTextEntry("off_y", "" + xypts[1], pop); - tf.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent e) { - setXYCoordinate((JTextField) e.getSource(), 1); - } - }); - } - - // line color - makeColorBox(pop, "text", false); - - // add ok button - pop.add(getOKButton()); - - return pop; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/package.html b/src/core/src/main/java/com/bbn/openmap/layer/test/package.html deleted file mode 100644 index 0a9e140fc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a test layer for OpenMap. - - diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts1.txt b/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts1.txt deleted file mode 100644 index d8f2a713f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts1.txt +++ /dev/null @@ -1,68 +0,0 @@ -# Test polygon vertices to be used with the TestLayer. This poly is -# best viewed with a RHUMBLINE linetype. If you want to add your own -# test polygon, remember to specify the vertices in clockwise order. -# -# To see this poly without having to type in the vertices, run the -# OpenMap viewer like this: -# "-Dtest.poly.vertices=`/bin/cat `" -# - -60.0 -170.0 -80.0 -170.0 -80.0 -90.0 -80.0 0.0 -80.0 90.0 -80.0 170.0 -70.0 170.0 -70.0 90.0 -70.0 0.0 -70.0 -90.0 -70.0 -150.0 -50.0 -150.0 -50.0 -180.0 -50.0 90.0 -50.0 0.0 -50.0 -90.0 -50.0 -130.0 -30.0 -130.0 -30 -180 -0 -180 --30 -180 --30 -90 --30 0 --30 90 --30 160 --60 160 --60 90 --60 0 --60 -90 --60 -180 --70 -180 --70 -90 --70 0 --70 90 --70 160 --80 160 --80 90 --80 0 --80 -90 --80 170 --50 170 --50 -90 --50 0 --50 90 --50 150 --40 150 --40 90 --40 0 --40 -90 --40 170 -0 170 -30.0 170.0 -40.0 170.0 -40.0 -140.0 -60.0 -140.0 -60.0 -90.0 -60.0 0.0 -60.0 90.0 -60.0 -170.0 diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts2.txt b/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts2.txt deleted file mode 100644 index a764b0090..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts2.txt +++ /dev/null @@ -1,22 +0,0 @@ -# Problematic Poly: -# View this poly with a fillcolor, with either rhumb or greatcircle -# linetype, in an azimuthal projection centered over either pole to -# see a rendering problem. -# -# * These vertices mark a poly band around the tropical regions. -# -# * In order to draw a band like this correctly you must break -# it up into 3 or more sections. -# - --20 0 --20 -90 --20 -180 --20 90 --20 0 -20 0 -20 90 -20 180 -20 -90 -20 0 --20 0 diff --git a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts3.txt b/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts3.txt deleted file mode 100644 index 322f8e548..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/test/test-verts3.txt +++ /dev/null @@ -1,38 +0,0 @@ -# Another valid poly. -# Note that vertices are in clockwise order! -# This is best viewed with either rhumbline or greatcircle linetype in -# any projection. - -5 -5 -10 -5 -10 5 --5 5 --5 -5 --5 -15 -20 -15 -20 15 --15 15 --15 -25 -30 -25 -30 25 --25 25 --25 -35 -40 -35 -40 35 --30 35 --30 30 -35 30 -35 -30 --20 -30 --20 20 -25 20 -25 -20 --10 -20 --10 10 -15 10 -15 -10 -0 -10 -0 -5 -0 0 -5 0 -5 -5 diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/AreaTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/AreaTable.java deleted file mode 100644 index a3ddce694..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/AreaTable.java +++ /dev/null @@ -1,229 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/AreaTable.java,v $ -// $Revision: 1.5 $ $Date: 2005/12/09 21:08:58 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Read VPF format edge, face, and ring tables to generate filled polygon - * graphics for OpenMap. - */ -public class AreaTable extends PrimitiveTable { - - /** the ring table for the tile we are working on */ - final private DcwRecordFile rings; - - /** the edge table for the tile we are working on */ - final private EdgeTable edges; - - /** if the edgetable is private or shared */ - final private boolean privateEdgeTable; - - /** the column number of our ring ID column */ - final private int ringIDColumn; - - /** the column number of our face ID column */ - final private int faceIDColumn; - - /** the column number of our start_edge column */ - final private int ringStartColumn; - - /** TilingAdapters used to retrieve edge table information */ - final private TilingAdapter edgeRightFaceAdapter, edgeLeftFaceAdapter, edgeRightEdgeAdapter, - edgeLeftEdgeAdapter; - - /** - * Construct an AreaTable for a tile. - * - * @param cov the coverage table that is our "parent" - * @param edg the edge table for the same tile as us (can be null) - * @param tile the tile to parse - * @exception FormatException if something goes wrong reading the area - */ - public AreaTable(CoverageTable cov, EdgeTable edg, TileDirectory tile) throws FormatException { - super(cov, tile, Constants.faceTableName); - - ringIDColumn = whatColumn(Constants.FAC_RINGPTR); - privateEdgeTable = (edg == null); - edges = privateEdgeTable ? new EdgeTable(cov, tile) : edg; - - edgeRightFaceAdapter = edges.getRightFaceTilingAdapter(); - edgeLeftFaceAdapter = edges.getLeftFaceTilingAdapter(); - edgeRightEdgeAdapter = edges.getRightEdgeTilingAdapter(); - edgeLeftEdgeAdapter = edges.getLeftEdgeTilingAdapter(); - - if (edges.topologyLevel() != 3) { - throw new FormatException("AreaTable: need level 3 topology: " + edges.topologyLevel()); - } - - rings = new DcwRecordFile(cov.getDataPath() + tile.getPath() + Constants.ringTableName - + (cov.appendDot ? "." : "")); - - if ((ringStartColumn = rings.whatColumn(Constants.RNG_STARTEDGE)) == -1) { - throw new FormatException("ring has no start edge: " + rings.filename); - } - - if ((faceIDColumn = rings.whatColumn(Constants.RNG_FACEID)) == -1) { - throw new FormatException("ring has no face_id: " + rings.filename); - } - } - - /** - * Close the files associated with this tile. If an edgetable was passed to - * the constructor, that table is NOT closed. If this instance created its - * own edgetable, it IS closed. - */ - public void close() { - if (privateEdgeTable) { - edges.close(); - } - rings.close(); - super.close(); - } - - /** - * Computes the full set of points that determine the edge of the area. - * - * @param facevec a row from the VPF face table for this area - * @param allLLPoints a List that gets modified to contain CoordFloatString - * objects defining the area. CoordFloatString objects with a - * negative element count (e.g. -3) contain the absolute value of the - * count (e.g. 3), but must be traversed in reverse order. - * @return the total number of points that define the polygon - * @exception FormatException may throw FormatExceptions - */ - public int computeEdgePoints(List facevec, List allLLPoints) - throws FormatException { - int ring_ptr = ((Number) facevec.get(ringIDColumn)).intValue(); - List ring1 = new ArrayList(rings.getColumnCount()); - rings.getRow(ring1, ring_ptr); - int fac_id = ((Number) ring1.get(faceIDColumn)).intValue(); - - int startedgeid = ((Number) ring1.get(ringStartColumn)).intValue(); - if (startedgeid <= 0) { - return 0; - } - int nextedgeid = startedgeid; - boolean firsttime = true; - allLLPoints.clear(); - int polySize = 0; - int prev_node = -1; - final List edge = new ArrayList(edges.getColumnCount()); - - do { - edges.getRow(edge, nextedgeid); - int start_node = edges.getStartNode(edge); - int end_node = edges.getEndNode(edge); - int rht_face = edgeRightFaceAdapter.getPrimId(edge); - int lft_face = edgeLeftFaceAdapter.getPrimId(edge); - int right_edge = edgeRightEdgeAdapter.getPrimId(edge); - int left_edge = edgeLeftEdgeAdapter.getPrimId(edge); - if (firsttime) { - prev_node = start_node; - firsttime = false; - } - - // Debug.message("dcwSpecialist", - // "edge: " + nextedgeid + " start->end: " - // + start_node + "->" + end_node); - CoordFloatString cfs = edges.getCoordinates(edge); - - if ((fac_id == rht_face) && (fac_id == lft_face)) { - if (start_node == prev_node) { - nextedgeid = right_edge; - prev_node = end_node; - } else if (end_node == prev_node) { - nextedgeid = left_edge; - prev_node = start_node; - } else { - throw new FormatException(" node matching assertion failed "); - } - } else if (fac_id == rht_face) { - nextedgeid = right_edge; - prev_node = end_node; - polySize += cfs.tcount; - allLLPoints.add(cfs); - } else if (fac_id == lft_face) { // reverse direction - nextedgeid = left_edge; - prev_node = start_node; - polySize += cfs.tcount; - cfs.tcount *= -1;// flag reverse - allLLPoints.add(cfs); - } else { - throw new FormatException("Node Assertion failed"); - } - } while (nextedgeid != startedgeid); - return polySize; - } - - /** - * Parse the area records for this tile, calling warehouse.createArea once - * for each record. - * - * @param warehouse the warehouse used for createArea calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @see VPFGraphicWarehouse#createArea - */ - public void drawTile(VPFGraphicWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2) { - try { - for (List area = new ArrayList(getColumnCount()); parseRow(area);) { - warehouse.createArea(covtable, this, area, ll1, ll2, dpplat, dpplon); - } - } catch (FormatException f) { - System.out.println("Exception: " + f.getClass() + " " + f.getMessage()); - } - } - - /** - * Use the warehouse to create a graphic from a feature in the AreaTable. - * - * @param warehouse the warehouse used for createArea calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinning (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param area a List containing the AreaTable row contents. - * @param featureType the string representing the feature type, in case the - * warehouse wants to do some intelligent rendering. - * @param primID the primitive ID of the feature, in order to gather attributes if - * necessary. - * @see VPFGraphicWarehouse#createEdge - */ - public OMGraphic drawFeature(VPFFeatureWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2, List area, - String featureType, int primID) { - - if (warehouse == null) { - return null; - } - - return warehouse.createArea(covtable, this, area, ll1, ll2, dpplat, dpplon, featureType, primID); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/Constants.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/Constants.java deleted file mode 100644 index 4de4c9925..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/Constants.java +++ /dev/null @@ -1,130 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/Constants.java,v $ -// $RCSfile: Constants.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -/** - * This class provides numerous string constants (typically column - * names for VPF tables) from the VPF Specification. - */ -public interface Constants { - - /** name of the VPF integer value description table */ - public final static String intVDTTableName = "int.vdt"; - /** name of the VPF character value description table */ - public final static String charVDTTableName = "char.vdt"; - /** the name of VPF Face Tables */ - public static final String faceTableName = "fac"; - /** the name of VPF Ring tables */ - public static final String ringTableName = "rng"; - /** the name of VPF entity node tables */ - public static final String endTableName = "end"; - /** the name of VPF connected node tables */ - public static final String cndTableName = "cnd"; - - /** the id column name for any VPF table */ - public static final String ID = DcwRecordFile.ID_COLUMN_NAME; - - /** the ring file start_edge column name */ - public static final String RNG_STARTEDGE = "start_edge"; - /** the ring file face_id column name */ - public static final String RNG_FACEID = "face_id"; - /** the face file ring_ptr column name */ - public static final String FAC_RINGPTR = "ring_ptr"; - - /** the edge file start_node column name */ - public static final String EDG_START_NODE = "start_node"; - /** the edge file end_node column name */ - public static final String EDG_END_NODE = "end_node"; - /** the edge file right_face column name */ - public static final String EDG_RIGHT_FACE = "right_face"; - /** the edge file left_face column name */ - public static final String EDG_LEFT_FACE = "left_face"; - /** the edge file right_edge column name */ - public static final String EDG_RIGHT_EDGE = "right_edge"; - /** the edge file left_edge column name */ - public static final String EDG_LEFT_EDGE = "left_edge"; - /** the edge file coordinates column name */ - public static final String EDG_COORDINATES = "coordinates"; - - /* the node file (end or cnd) containing_face column name */ - public static final String ND_CONTAININGFACE = "containing_face"; - /* the node file (end or cnd) first_edge column name */ - public static final String ND_FIRSTEDGE = "first_edge"; - /* the node file (end or cnd) coordinate column name */ - public static final String ND_COORDINATE = "coordinate"; - - /** int.vdt and char.vdt table column */ - public static final String VDT_TABLE = "table"; - /** int.vdt and char.vdt attribute column */ - public static final String VDT_ATTRIBUTE = "attribute"; - /** int.vdt and char.vdt value column */ - public static final String VDT_VALUE = "value"; - /** int.vdt and char.vdt description column */ - public static final String VDT_DESC = "description"; - - /** coverage attribute table coverage_name column */ - public static final String CAT_COVNAME = "coverage_name"; - /** coverage attribute table description column */ - public static final String CAT_DESC = "description"; - /** coverage attribute table (topology) level column */ - public static final String CAT_LEVEL = "level"; - - /** face bounding rectangle xmin column */ - public static final String FBR_XMIN = "xmin"; - /** face bounding rectangle ymin column */ - public static final String FBR_YMIN = "ymin"; - /** face bounding rectangle xmax column */ - public static final String FBR_XMAX = "xmax"; - /** face bounding rectangle ymax column */ - public static final String FBR_YMAX = "ymax"; - - /** library attribute table library_name column */ - public static final String LAT_LIBNAME = "library_name"; - /** library attribute table xmin column */ - public static final String LAT_XMIN = FBR_XMIN; - /** library attribute table ymin column */ - public static final String LAT_YMIN = FBR_YMIN; - /** library attribute table xmax column */ - public static final String LAT_XMAX = FBR_XMAX; - /** library attribute table ymax column */ - public static final String LAT_YMAX = FBR_YMAX; - - /** the feature class schema (fcs) table feature_class column */ - public static final String FCS_FEATURECLASS = "feature_class"; - /** the feature class schema (fcs) table table1 column */ - public static final String FCS_TABLE1 = "table1"; - /** the feature class schema (fcs) table table1_key column */ - public static final String FCS_TABLE1KEY = "table1_key"; - /** the feature class schema (fcs) table table2 column */ - public static final String FCS_TABLE2 = "table2"; - /** the feature class schema (fcs) table table2_key column */ - public static final String FCS_TABLE2KEY = "table2_key"; - - /** the feature class schema (fcs) table table1_key column for DCW */ - public static final String DCW_FCS_TABLE1KEY = "foreign_key"; - /** the feature class schema (fcs) table table2_key column for DCW */ - public static final String DCW_FCS_TABLE2KEY = "primary_key"; - - /** A string array with 0 elements */ - public static final String[] EMPTY_STRING_ARRAY = new String[0]; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordDoubleString.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordDoubleString.java deleted file mode 100644 index 5dcd5792a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordDoubleString.java +++ /dev/null @@ -1,215 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/CoordDoubleString.java,v $ -// $RCSfile: CoordDoubleString.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Encapsulate the VPF Double Coordinate String primitive datatype. - */ - -public class CoordDoubleString implements CoordTupleString { - - /** where we store the data */ - final private double vals[][]; - - /** - * Construct a CoordDoubleString from a file input - * - * @param tuplecount the number of tuples to read from the input - * stream - * @param tuplesize the number of doubles in the tuple - * @param input the input stream to read everything from - * @exception FormatException if we have IO errors or premature - * end-of-file - */ - public CoordDoubleString(int tuplecount, int tuplesize, BinaryFile input) - throws FormatException { - try { - vals = new double[tuplecount][tuplesize]; - for (int i = 0; i < tuplecount; i++) - for (int j = 0; j < tuplesize; j++) - vals[i][j] = input.readDouble(); - } catch (EOFException e) { - throw new FormatException("CoordDoubleString EOFException"); - } - } - - /** - * The maximum indexable tuple value - * - * @return the maximum valid tuple index - */ - public int maxIndex() { - return vals.length; - } - - /** - * Accessor for the underlying primitive type - * - * @return a Double, since that's what we manage - */ - public Number getPrimitiveType() { - return new Double(0.0); - } - - /** - * A pretty formatter for the doublestring - * - * @return a pretty string of the tuple - */ - public String toString() { - StringBuffer retval = new StringBuffer("CDS:"); - retval.append(vals.length).append("["); - - for (int i = 0; i < vals.length; i++) { - retval.append("("); - for (int j = 0; j < vals[i].length; j++) - retval.append(vals[i][j]).append(", "); - retval.append(") "); - } - retval.append("]"); - return retval.toString(); - } - - /** - * Get the first value of a tuple - * - * @param tuple the index of the tuple - * @return the first value of the tuple given by - * tuple - */ - public float getXasFloat(int tuple) { - return (float) vals[tuple][0]; - } - - /** - * Get the first value of a tuple - * - * @param tuple the index of the tuple - * @return the first value of the tuple given by - * tuple - */ - public double getXasDouble(int tuple) { - return vals[tuple][0]; - } - - /** - * Get the second value of a tuple - * - * @param tuple the index of the tuple - * @return the second value of the tuple given by - * tuple - */ - public float getYasFloat(int tuple) { - return (float) vals[tuple][1]; - } - - /** - * Get the second value of a tuple - * - * @param tuple the index of the tuple - * @return the second value of the tuple given by - * tuple - */ - public double getYasDouble(int tuple) { - return vals[tuple][1]; - } - - /** - * Get the third value of a tuple - * - * @param tuple the index of the tuple - * @return the third value of the tuple given by - * tuple - */ - public float getZasFloat(int tuple) { - if (vals[tuple].length >= 3) { - return (float) vals[tuple][2]; - } - return 0.0f; - } - - /** - * Get the third value of a tuple - * - * @param tuple the index of the tuple - * @return the third value of the tuple given by - * tuple - */ - public double getZasDouble(int tuple) { - if (vals[tuple].length >= 3) { - return vals[tuple][2]; - } - return 0.0; - } - - /** - * Get a tuple - * - * @param tuple the index of the tuple - * @return the tuple given by tuple - */ - public float[] getasFloat(int tuple) { - int tusize = vals[tuple].length; - float rv[] = new float[tusize]; - for (int i = 0; i < tusize; i++) - rv[i] = (float) vals[tuple][i]; - return rv; - } - - /** - * Get a tuple - * - * @param tuple the index of the tuple - * @return the tuple given by tuple - */ - public double[] getasDouble(int tuple) { - return vals[tuple]; - } - - /** - * Get a value in a tuple - * - * @param tuple the index of the tuple - * @param val the index of the value - * @return the tuple given by tuple - */ - public float getasFloat(int tuple, int val) { - return (float) vals[tuple][val]; - } - - /** - * Get a value in a tuple - * - * @param tuple the index of the tuple - * @param val the index of the value - * @return the tuple given by tuple - */ - public double getasDouble(int tuple, int val) { - return vals[tuple][val]; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordFloatString.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordFloatString.java deleted file mode 100644 index a80df1a18..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordFloatString.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/CoordFloatString.java,v $ -// $RCSfile: CoordFloatString.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Encapsulate the VPF Float Coordinate String primitive datatype. - */ -public class CoordFloatString { - - /** the number of tuples */ - public int tcount; - /** the number of elements in a tuple */ - public int tsize; - /** where we store the data as x1,y1,z1,x2,y2,z2,... */ - public double vals[]; - - /** - * Construct a CoordFloatString from a file input - * - * @param tuplecount the number of tuples to read from the input - * stream - * @param tuplesize the number of floats in the tuple - * @param input the input stream to read everything from - * @exception FormatException if we have IO errors or premature - * end-of-file - */ - public CoordFloatString(int tuplecount, int tuplesize, BinaryFile input) - throws FormatException { - tcount = tuplecount; - tsize = tuplesize; - int totallen = tcount * tsize; - vals = new double[totallen]; - try { - input.readFloatArray(vals, 0, totallen); - } catch (EOFException e) { - throw new FormatException("CoordFloatString EOFException"); - } - } - - /** - * The maximum indexable tuple value - * - * @return the maximum valid tuple index - */ - public int maxIndex() { - return tcount; - } - - /** - * A pretty formatter for the floatstring - * - * @return a pretty string of the tuple - */ - public String toString() { - boolean singleCoord = (vals.length == tsize); - StringBuffer retval = new StringBuffer(singleCoord ? "" : "CFS:"); - if (!singleCoord) { - retval.append(tcount).append("["); - } - - if (vals.length > 0) { - retval.append("(").append(vals[0]); - for (int j = 1; j < tsize; j++) { - retval.append(", ").append(vals[j]); - } - retval.append(")"); - } - if (vals.length > tsize) { - retval.append(" ... (").append(vals[vals.length - tsize]); - for (int j = tsize - 1; j > 0; j--) { - retval.append(", ").append(vals[vals.length - j]); - } - retval.append(")"); - } - - if (!singleCoord) { - retval.append("]"); - } - return retval.toString(); - } - - /** - * Get the first value of a tuple - * - * @param tuple the index of the tuple - * @return the first value of the tuple given by - * tuple - */ - public double getXasFloat(int tuple) { - return vals[tuple * tsize]; - } - - /** - * Get the second value of a tuple - * - * @param tuple the index of the tuple - * @return the second value of the tuple given by - * tuple - */ - public double getYasFloat(int tuple) { - return vals[tuple * tsize + 1]; - } - - /** - * Get the third value of a tuple - * - * @param tuple the index of the tuple - * @return the third value of the tuple given by - * tuple - */ - public double getZasFloat(int tuple) { - return vals[tuple * tsize + 2]; - } - - /** - * Get a tuple - * - * @param tuple the index of the tuple - * @return the tuple given by tuple - */ - public double[] getasFloatV(int tuple) { - double rv[] = new double[tsize]; - for (int i = 0; i < tsize; i++) { - rv[i] = vals[tsize * tuple + i]; - } - return rv; - } - - /** - * Get a value in a tuple - * - * @param tuple the index of the tuple - * @param val the index of the value - * @return the tuple given by tuple - */ - public double getasFloat(int tuple, int val) { - return vals[tuple * tsize + val]; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordTupleString.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordTupleString.java deleted file mode 100644 index cf2c4c9d4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoordTupleString.java +++ /dev/null @@ -1,86 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/CoordTupleString.java,v $ -// $RCSfile: CoordTupleString.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -/** - * Describe a common schema for accessing either double or float based - * coordinate tuple strings (arrays of tuples). - */ -public interface CoordTupleString { - - /** - * Accessor for the max tuple index - * - * @return the max tuple index - */ - public abstract int maxIndex(); - - /** - * Accessor to determine the actual type managed. - * - * @return a Number the most directly corresponds to the - * underlying managed type (Float for a float tuplestring, - * Double for a double tuplestring, etc) - */ - public abstract Number getPrimitiveType(); - - /** - * Accessor to retrieve a tuple - * - * @param tuple the tuple to retrieve (the first tuple is index 0) - * @return the tuple at index tuple, coerced into - * a float[] - */ - public abstract float[] getasFloat(int tuple); - - /** - * Accessor to retrieve a tuple - * - * @param tuple the tuple to retrieve (the first tuple is index 0) - * @return the tuple at index tuple, coerced into - * a double[] - */ - public abstract double[] getasDouble(int tuple); - - /** - * Accessor to retrieve a single value in a tuple - * - * @param tuple the tuple to retrieve (the first tuple is index 0) - * @param val the index of the value in the tuple (the first val - * is index 0) - * @return the tuple at index tuple, coerced into - * a float - */ - public abstract float getasFloat(int tuple, int val); - - /** - * Accessor to retrieve a single value in a tuple - * - * @param tuple the tuple to retrieve (the first tuple is index 0) - * @param val the index of the value in the tuple (the first val - * is index 0) - * @return the tuple at index tuple, coerced into - * a double - */ - public abstract double getasDouble(int tuple, int val); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageAttributeTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageAttributeTable.java deleted file mode 100644 index 007f58daa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageAttributeTable.java +++ /dev/null @@ -1,551 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/CoverageAttributeTable.java,v $ -// $Revision: 1.8 $ $Date: 2005/08/09 19:29:39 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.Debug; - -/** - * Handle the library level VPF directory. "noamer" in DCW is an example of the - * library level data. This class loads the associated tiling information, and - * the coverage types, and make them available to the client. - */ -public class CoverageAttributeTable { - - /** the name of the library we are, for example "noamer" in DCW */ - final protected String libraryname; - /** the path to our directory */ - final protected String dirpath; - /** are we tiled or untiled coverage */ - private boolean isTiled = false; - /** coverage name to CoverageEntry map */ - final private Map coverages = new HashMap(); - protected DataBounds bounds; - /** - * The tiles that compose our coverage area. The size of the array is going - * to be set to record count + 1, and the tiles will have their ID number as - * their index. - */ - private TileDirectory containedTiles[]; - /** the column names in the cat. file */ - private final static String CATColumns[] = { - Constants.CAT_COVNAME, - Constants.CAT_DESC, - Constants.CAT_LEVEL - }; - /** expected schema types for the cat. file */ - private final static char CATschematype[] = { - DcwColumnInfo.VPF_COLUMN_TEXT, - DcwColumnInfo.VPF_COLUMN_TEXT, - DcwColumnInfo.VPF_COLUMN_INT_OR_SHORT - }; - /** expected schema lengths for cat. file */ - private final static int CATschemalength[] = { - -1 /* 8 */, - -1 /* 50 */, - 1 - }; - - /** - * Construct a new coverage attribute table - * - * @param libname the name of the library - * @param dcwpath the path to the library - * @exception FormatException may throw FormatExceptions - */ - public CoverageAttributeTable(String dcwpath, String libname) - throws FormatException { - libraryname = libname; - dirpath = dcwpath + "/" + libraryname; - String cat = dirpath + "/cat"; - if (!BinaryFile.exists(cat)) { - cat += "."; - } - - DcwRecordFile rf = new DcwRecordFile(cat); - int catcols[] = rf.lookupSchema(CATColumns, true, CATschematype, CATschemalength, false); - - List l = new ArrayList(rf.getColumnCount()); - while (rf.parseRow(l)) { - int topL = ((Number) l.get(catcols[2])).intValue(); - String desc = (String) l.get(catcols[1]); - String covtype = ((String) l.get(catcols[0])).toLowerCase().intern(); - coverages.put(covtype, new CoverageEntry(topL, desc)); - } - rf.close(); - rf = null; - - doTileRefStuff(dirpath + "/tileref"); - } - - /** - * is this library tiled - * - * @return true for tiled coverage. false else - */ - public final boolean isTiledCoverage() { - return isTiled; - } - - /** - * the name of the library - * - * @return the name of the library - */ - public String getLibraryName() { - return libraryname; - } - - /** the columns we need in fbr for tiling */ - private static final String[] fbrColumns = { - Constants.FBR_XMIN, - Constants.FBR_YMIN, - Constants.FBR_XMAX, - Constants.FBR_YMAX - }; - /** the columns we need in fcs for tiling */ - private static final String[] fcsColumns = { - Constants.FCS_FEATURECLASS, - Constants.FCS_TABLE1, - Constants.FCS_TABLE1KEY, - Constants.FCS_TABLE2, - Constants.FCS_TABLE2KEY - }; - /** the columns we need in fcs for tiling for DCW */ - private static final String[] fcsColumnsDCW = { - Constants.FCS_FEATURECLASS, - Constants.FCS_TABLE1, - Constants.DCW_FCS_TABLE1KEY, - Constants.FCS_TABLE2, - Constants.DCW_FCS_TABLE2KEY - }; - - /** - * an internal function to load the tiling information - * - * @param pathname the path to the tile directory - */ - private void doTileRefStuff(String pathname) { - doTileRefStuff(pathname, false); - } - - /** - * an internal function to load the tiling information, with an option to use - * DCW column names. - * - * @param pathname the path to the tile directory - * @param DCW use DCW column names. - */ - private void doTileRefStuff(String pathname, boolean DCW) { - String faceIDColumnName = null; - // Figure out how files names should be constructed... - boolean addSlash = true; - // if (pathname.endsWith(File.separator)) { - if (pathname.endsWith("/") || pathname.endsWith(File.separator)) { - addSlash = false; - } - - // read fcs to figure out what column in tileref.aft we need - // to use to - // read the fbr (face bounding rectangle) table - try { - - String fcsFile = pathname + (addSlash ? "/" : "") + "fcs"; - - if (!BinaryFile.exists(fcsFile)) { - fcsFile += "."; - } - - DcwRecordFile fcs = new DcwRecordFile(fcsFile); - List fcsv = new ArrayList(fcs.getColumnCount()); - - int fcscols[]; - - if (!DCW) { - fcscols = fcs.lookupSchema(fcsColumns, true); - } else { - fcscols = fcs.lookupSchema(fcsColumnsDCW, true); - } - - while (fcs.parseRow(fcsv)) { - String fclass = (String) fcsv.get(fcscols[0]); - String table1 = (String) fcsv.get(fcscols[1]); - String table1_key = (String) fcsv.get(fcscols[2]); - /* - * Not used String table2 = (String) fcsv.get(fcscols[3]); String - * table2_key = (String) fcsv.get(fcscols[4]); - */ - if ("tileref".equalsIgnoreCase(fclass) && "tileref.aft".equalsIgnoreCase(table1)) { - faceIDColumnName = table1_key.toLowerCase(); - break; - } - } - fcs.close(); - } catch (FormatException f) { - // If DCW, we'll get here, need to try lookupSchema with - // proper column names - if (!DCW) - doTileRefStuff(pathname, true); - return; - // either way, return. The recursive call may have worked. - - } catch (NullPointerException npe) { - return; // file wasn't found... - } - - if (faceIDColumnName == null) { - return; // won't be able to read the tiling info. abort - } - - isTiled = true; - - // Okay, we've got info on what column we use from tileref.aft - // to index into the fbr. - try { - DcwRecordFile aft = new DcwRecordFile(pathname + (addSlash ? "/" : "") + "tileref.aft"); - int faceIDColumn = aft.whatColumn(faceIDColumnName.toLowerCase()); - int tileNameColumn = aft.whatColumn("tile_name"); - if ((faceIDColumn == -1) || (tileNameColumn == -1)) { - aft.close(); - return; - } - - String fbrFile = pathname + (addSlash ? "/" : "") + "fbr"; - if (!BinaryFile.exists(fbrFile)) { - fbrFile += "."; - } - DcwRecordFile fbr = new DcwRecordFile(fbrFile); - int fbrIDColumn = fbr.whatColumn(Constants.ID); - - List aftv = new ArrayList(aft.getColumnCount()); - List fbrv = new ArrayList(fbr.getColumnCount()); - int fbrcols[] = fbr.lookupSchema(fbrColumns, true); - - // set the array size to record count + 1, to be able to - // use the tileID as the index into the array - - // aft.getRecordCount() is not reliable if file is being - // read with a network input stream. So, we have to - // create the TileDirectory[] a different way. - // containedTiles = new TileDirectory[aft.getRecordCount() - // + 1]; - // This is part of that solution... - ArrayList tileArrayList = new ArrayList(500); - Object nullTile = new Object(); - - while (aft.parseRow(aftv)) { - int fac_num = ((Number) aftv.get(faceIDColumn)).intValue(); - fbr.getRow(fbrv, fac_num); // mutates fbrv - int tileid = ((Number) aftv.get(fbrIDColumn)).intValue(); - String tilename = (String) aftv.get(tileNameColumn); - - char chs[] = tilename.toCharArray(); - boolean goodTile = false; - for (int i = 0; i < chs.length; i++) { - if ((chs[i] != '\\') && (chs[i] != ' ')) { - goodTile = true; - } - if (chs[i] == '\\') { - // chs[i] = File.separatorChar; - chs[i] = '/'; // we're using BinaryFile, in - // java land... - } - } - tilename = new String(chs); - - // Part of the URL solution... - // This makes sure that the tileid can be used - // for the index. If the tile is not good, then - // nullTile will be set. If it is good, it will be - // replaced. This will end up putting nullTile at - // index 1 if the tileid is 1. - while (tileid > tileArrayList.size() - 1) { - tileArrayList.add(nullTile); - } - // End of solution addition part... - - if (!goodTile) { - // Commenting out line is part of the solution, - // the - // spot is already marked with a nullTile object. - // containedTiles[tileid] = null; - continue; - } - - float westlon = ((Number) fbrv.get(fbrcols[0])).floatValue(); - float southlat = ((Number) fbrv.get(fbrcols[1])).floatValue(); - float eastlon = ((Number) fbrv.get(fbrcols[2])).floatValue(); - float northlat = ((Number) fbrv.get(fbrcols[3])).floatValue(); - - if (bounds == null) { - bounds = new DataBounds(westlon, southlat, eastlon, northlat); - } else { - bounds.add(westlon, southlat); - bounds.add(eastlon, northlat); - } - - // Again, URL solution... - // containedTiles[tileid] = new - // TileDirectory(tilename, tileid, - // northlat, southlat, - // eastlon, westlon); - - tileArrayList.set(tileid, new TileDirectory(tilename, tileid, northlat, southlat, eastlon, westlon)); - - } - aft.close(); - fbr.close(); - - // And this is the resolution of the solution, taking - // the ArrayList and converting it to a TileDirectory - // array. - containedTiles = new TileDirectory[tileArrayList.size()]; - Iterator it = tileArrayList.iterator(); - int cnt = 0; - while (it.hasNext()) { - Object obj = it.next(); - if (obj == nullTile) { - containedTiles[cnt++] = null; - } else { - containedTiles[cnt++] = (TileDirectory) obj; - } - } - - } catch (FormatException f) { - // probably (hopefully?) untiled coverage... - containedTiles = null; - } - } - - /** - * Get the description of a coverage type - * - * @param covname the name of the coverage type - * @return the coverage description from the VPF database. A null return - * value indicates an unknown coverage type - */ - public String getCoverageDescription(String covname) { - CoverageEntry ce = (CoverageEntry) coverages.get(covname); - return (ce == null) ? null : ce.getDescription(); - } - - /** - * Get the topology level of a coverage. - * - * @param covname the name of the coverage type - * @return the topology level of the coverage (-1 if not a valid coverage) - */ - public int getCoverageTopologyLevel(String covname) { - CoverageEntry ce = (CoverageEntry) coverages.get(covname); - return (ce == null) ? -1 : ce.getTopologyLevel(); - } - - /** - * Get the CoverageTable for a particular coverage type - * - * @param covname the name of the coverage type - * @return the associated coverage table (possibly null) - */ - public CoverageTable getCoverageTable(String covname) { - CoverageEntry ce = (CoverageEntry) coverages.get(covname); - if (ce != null) { - if (ce.getCoverageTable() == null) { - ce.setCoverageTable(new CoverageTable(dirpath, covname.intern(), this)); - if (Debug.debugging("vpf")) { - Debug.output("Created new CoverageTable for " + covname + ": " + ce.description); - } - } else { - if (Debug.debugging("vpf")) { - Debug.output("Using cached CoverageTable for " + covname + ": " + ce.description); - } - } - return ce.getCoverageTable(); - } - return null; - } - - public CoverageTable getCoverageTableForFeature(String featureName) { - for (String key : coverages.keySet()) { - CoverageEntry ce = coverages.get(key); - Debug.output("CoverageTable: got " + ce + " for " + key); - CoverageTable ct = ce.getCoverageTable(); - if (ct != null) { - if (ct.getFeatureClassInfo(featureName) != null) { - return ct; - } - } else { - Debug.output("no coverage table for " + ce); - } - } - return null; - } - - /** - * get a list of tiles in the bounding region - * - * @param n northern boundary - * @param s southern boundary - * @param e eating foundry - * @param w wheat bread - * @return a vector of TileDirectories - */ - public List tilesInRegion(float n, float s, float e, float w) { - if (containedTiles == null) { - return null; - } - List retval = new ArrayList(); - int numTiles = containedTiles.length; - for (int i = 0; i < numTiles; i++) { - TileDirectory tile = containedTiles[i]; - if (tile != null && tile.inRegion(n, s, e, w)) { - retval.add(tile); - } - } - return retval; - } - - /** - * Get the TileDirectory with the given ID number. - */ - public TileDirectory getTileWithID(int id) { - try { - return containedTiles[id]; - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } catch (NullPointerException npe) { - return null; - } - } - - /** - * Know that the tile id are the integers used in the tileref.aft file. May - * return null if the format of the id is bad, or if the tile doesn't really - * exist (that really shouldn't happen). - */ - public TileDirectory getTileWithID(String id) { - try { - return getTileWithID(Integer.parseInt(id)); - } catch (NumberFormatException nfe) { - return null; - } - } - - /** - * Find out if this library uses tiled data - * - * @return true for tiled data - */ - public boolean isTiledData() { - return (containedTiles != null); - - } - - /** - * Return the list of coverages this library has - * - * @return the list of coverages (DCW would include "po", "dn"; VMAP would - * have "bnd", "tran", etc.) - */ - public String[] getCoverageNames() { - return (String[]) coverages.keySet().toArray(Constants.EMPTY_STRING_ARRAY); - } - - /** - * Gets a DataBounds object that specifies what the CAT covers. - * - * @return DataBounds - */ - public DataBounds getBounds() { - return bounds; - } - - /** - * A utility class to hold information about one coverage type. Only the - * associated coverage table may be modified after construction. - */ - public static class CoverageEntry { - /** the VPF topology level of this coverage type */ - private final int tLevel; - /** the VPF description string of this coverage type */ - private final String description; - /** the CoverageTable for this coverage type */ - private CoverageTable covtable; - - /** - * Create a coverage entry without a coverage table - * - * @param topologyLevel the topology level for this coverageentry - * @param desc the description for this entry - */ - public CoverageEntry(int topologyLevel, String desc) { - this(topologyLevel, desc, null); - } - - /** - * Create a coverage entry with an initial coverage table - * - * @param topologyLevel the topology level for this coverageentry - * @param desc the description for this entry - * @param covtable the coveragetable for this entry - */ - public CoverageEntry(int topologyLevel, String desc, CoverageTable covtable) { - this.tLevel = topologyLevel; - this.description = desc; - this.covtable = covtable; - } - - /** - * Get the topology level for this entry - */ - public int getTopologyLevel() { - return tLevel; - } - - /** - * Get the description for this entry - */ - public String getDescription() { - return description; - } - - /** - * Get the associated coveragetable - */ - public CoverageTable getCoverageTable() { - return covtable; - } - - /** - * Set the associated coveragetable - * - * @param covtable the new coveragetable - */ - /* package */void setCoverageTable(CoverageTable covtable) { - this.covtable = covtable; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageTable.java deleted file mode 100644 index f785f3240..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/CoverageTable.java +++ /dev/null @@ -1,1421 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/CoverageTable.java,v $ -// $Revision: 1.13 $ $Date: 2005/12/09 21:08:58 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.VPFAutoFeatureGraphicWarehouse.FeaturePriorityHolder; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Encapsulate a VPF coverage directory. This class handles requests that happen - * for a particular coverage type (political boundary, road, etc.) for a - * particular library (north america, browse, etc.). - */ -public class CoverageTable { - - protected final static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.CoverageTable"); - - /** our coverage type - such as "po", "bnd", "hydro" */ - final public String covtype; - /** the directory for our coverage type */ - final protected String tablepath; - /** a table to cache int.vdt information */ - final private Map intvdtrec = new HashMap(); - /** a table to cache char.vdt information */ - final private Map charvdtrec = new HashMap(); - - /** hack - used by EdgeTable */ - public int cachedLineSchema[] = null; - /** hack - used by AreaTable */ - public int cachedAreaSchema[] = null; - /** hack - used by TextTable */ - public int cachedTextSchema[] = null; - /** hack - used by nodetable */ - public int cachedEPointSchema[] = null; - /** hack - used by nodetable */ - public int cachedCPointSchema[] = null; - - /** featureclasses used for the line feature type */ - public FeatureClassInfo lineinfo[] = new FeatureClassInfo[0]; - /** featureclasses used for the area feature type */ - public FeatureClassInfo areainfo[] = new FeatureClassInfo[0]; - /** featureclasses used for the text feature type */ - public FeatureClassInfo textinfo[] = new FeatureClassInfo[0]; - /** featureclasses used for the entity node feature type */ - public FeatureClassInfo epointinfo[] = new FeatureClassInfo[0]; - /** featureclasses used for the connected node feature type */ - public FeatureClassInfo cpointinfo[] = new FeatureClassInfo[0]; - - /** - * Feature classes to look up FeatureClassInfo via feature name. - */ - protected Hashtable featureTypes = new Hashtable(); - protected Hashtable featureTypeInfo; - - /** do we need to append a '.' to three-character file names */ - public boolean appendDot = false; - /** - * Need this in case we have to go from the coverage type-<feature - * type-<tile - */ - protected CoverageAttributeTable cat; - - /** hackage for the antarctica polygon in DCW browse coverage */ - final public boolean doAntarcticaWorkaround; - - public static final char EDGE_FEATURETYPE = 'L'; - public static final char AREA_FEATURETYPE = 'A'; - public static final char TEXT_FEATURETYPE = 'T'; - public static final char UPOINT_FEATURETYPE = 'P'; - public static final char EPOINT_FEATURETYPE = 'E'; - public static final char CPOINT_FEATURETYPE = 'N'; - public static final char COMPLEX_FEATURETYPE = 'C'; - public static final char SKIP_FEATURETYPE = 'S'; - - /** - * Construct a CoverageTable object. Data is expected to be in a directory - * called path/covtype. - * - * @param path the path to the parent directory of where our data resides - * @param covtype the subdirectory name for the coverage data - */ - public CoverageTable(String path, String covtype) { - this.covtype = covtype; - tablepath = path + "/" + covtype + "/"; - - doAntarcticaWorkaround = (tablepath.indexOf("browse") >= 0); - - internSchema(); - - loadIntVDT(); - loadCharVDT(); - - featureTypeInfo = getFeatureTypeInfo(); - } - - /** - * Construct a CoverageTable object. Data is expected to be in a directory - * called path/covtype. - * - * @param path the path to the parent directory of where our data resides - * @param covtype the subdirectory name for the coverage data - * @param cat the CoverageAttributeTable reference, in case we need to - * backtrack the tiles through the feature tables. - */ - public CoverageTable(String path, String covtype, CoverageAttributeTable cat) { - - this(path, covtype); - this.cat = cat; - } - - /** required column names for char.vdt and int.vdt files */ - public final static String VDTColumnNames[] = { Constants.VDT_TABLE, Constants.VDT_ATTRIBUTE, - Constants.VDT_VALUE, Constants.VDT_DESC }; - - /** expected schema types for int.vdt files */ - public final static char intVDTschematype[] = { DcwColumnInfo.VPF_COLUMN_INT, - DcwColumnInfo.VPF_COLUMN_TEXT, DcwColumnInfo.VPF_COLUMN_TEXT, - DcwColumnInfo.VPF_COLUMN_INT_OR_SHORT, DcwColumnInfo.VPF_COLUMN_TEXT }; - /** expected schema lengths for int.vdt files */ - public final static int intVDTschemalength[] = { 1, -1, -1, 1, -1 }; - - private void loadIntVDT() { - try { - String vdt = tablepath + Constants.intVDTTableName; - if (BinaryFile.exists(vdt)) { - DcwRecordFile intvdt = new DcwRecordFile(vdt); - int cols[] = intvdt.lookupSchema(VDTColumnNames, true, intVDTschematype, intVDTschemalength, false); - - for (List l = new ArrayList(intvdt.getColumnCount()); intvdt.parseRow(l);) { - String tab = (String) l.get(cols[0]); - String attr = (String) l.get(cols[1]); - int val = ((Number) l.get(cols[2])).intValue(); - String desc = ((String) l.get(cols[3])).intern(); - intvdtrec.put(new CoverageIntVdt(tab, attr, val), desc); - } - intvdt.close(); - } - } catch (FormatException f) { - } - - } - - /** expected schema types for char.vdt files */ - public final static char charVDTschematype[] = { DcwColumnInfo.VPF_COLUMN_INT, - DcwColumnInfo.VPF_COLUMN_TEXT, DcwColumnInfo.VPF_COLUMN_TEXT, - DcwColumnInfo.VPF_COLUMN_TEXT, DcwColumnInfo.VPF_COLUMN_TEXT }; - /** expected schema lengths for char.vdt files */ - public final static int charVDTschemalength[] = { 1, -1, -1, -1, -1 }; - - private void loadCharVDT() { - try { - String vdt = tablepath + Constants.charVDTTableName; - if (BinaryFile.exists(vdt)) { - DcwRecordFile charvdt = new DcwRecordFile(vdt); - int cols[] = charvdt.lookupSchema(VDTColumnNames, true, charVDTschematype, charVDTschemalength, false); - - for (List l = new ArrayList(charvdt.getColumnCount()); charvdt.parseRow(l);) { - String tab = (String) l.get(cols[0]); - String attr = (String) l.get(cols[1]); - String val = (String) l.get(cols[2]); - String desc = ((String) l.get(cols[3])).intern(); - charvdtrec.put(new CoverageCharVdt(tab, attr, val), desc); - } - charvdt.close(); - } - } catch (FormatException f) { - } - } - - private FeatureClassInfo[] internSchema(FeatureClassInfo[] fti, String foreign_key, - String tablename) throws FormatException { - FeatureClassInfo rv[] = new FeatureClassInfo[fti.length + 1]; - System.arraycopy(fti, 0, rv, 0, fti.length); - rv[fti.length] = new FeatureClassInfo(this, foreign_key.intern(), tablepath, tablename.intern()); - return rv; - } - - /** the columns of the fcs file we are interested in */ - private static final String[] fcsColumns = { Constants.FCS_FEATURECLASS, Constants.FCS_TABLE1, - Constants.FCS_TABLE1KEY, Constants.FCS_TABLE2, Constants.FCS_TABLE2KEY }; - /** the columns we need in fcs for tiling for DCW */ - private static final String[] fcsColumnsDCW = { Constants.FCS_FEATURECLASS, - Constants.FCS_TABLE1, Constants.DCW_FCS_TABLE1KEY, Constants.FCS_TABLE2, - Constants.DCW_FCS_TABLE2KEY }; - - /** - * This method reads the feature class schema (fcs) file to discover the - * inter-table relations (joins, in database parlance). As a side effect, - * this method also sets the appendDot member. - */ - private void internSchema() { - internSchema(false); - } - - /** - * This method reads the feature class schema (fcs) file to discover the - * inter-table relations (joins, in database parlance). As a side effect, - * this method also sets the appendDot member. The DCW option refers to if - * the DCW column names should be used, for DCW data. This is only true if a - * problem occurs, and then this method is called recursively. - */ - private void internSchema(boolean DCW) { - - // Figure out how files names should be constructed... - boolean addSlash = true; - // if (tablepath.endsWith(File.separator)) { - if (tablepath.endsWith("/") || tablepath.endsWith(File.separator)) { - addSlash = false; - } - - try { - String filename = tablepath + (addSlash ? "/" : "") + "fcs"; - if (!BinaryFile.exists(filename)) { - filename += "."; - appendDot = true; - } - DcwRecordFile fcs = new DcwRecordFile(filename); - - int[] fcscols = fcs.lookupSchema(DCW ? fcsColumnsDCW : fcsColumns, true); - - for (List fcsrec = new ArrayList(fcs.getColumnCount()); fcs.parseRow(fcsrec);) { - String feature_class = (String) fcsrec.get(fcscols[0]); - String table1 = (String) fcsrec.get(fcscols[1]); - String foreign_key = (String) fcsrec.get(fcscols[2]); - String table2 = (String) fcsrec.get(fcscols[3]); - String primary_key = (String) fcsrec.get(fcscols[4]); - internSchema(feature_class.toLowerCase(), table1.toLowerCase(), foreign_key.toLowerCase(), table2.toLowerCase(), primary_key.toLowerCase()); - } - fcs.close(); - } catch (FormatException f) { - if (!DCW) { - internSchema(true); - } else { - System.out.println("CoverageTable: " + f.getMessage()); - } - } - } - - private void internSchema(String feature_class, String table1, String foreign_key, - String table2, String primary_key) { - try { - if (table1.equals("fac")) { - areainfo = internSchema(areainfo, foreign_key, table2); - } else if (table1.equals("edg")) { - lineinfo = internSchema(lineinfo, foreign_key, table2); - } else if (table1.equals("end")) { - epointinfo = internSchema(epointinfo, foreign_key, table2); - } else if (table1.equals("cnd")) { - cpointinfo = internSchema(cpointinfo, foreign_key, table2); - } else if (table1.equals("txt")) { - textinfo = internSchema(textinfo, foreign_key, table2); - } else if (table1.startsWith(feature_class) - && (foreign_key.equals("end_id") || foreign_key.equals("cnd_id") - || foreign_key.equals("fac_id") || foreign_key.equals("edg_id") || foreign_key.equals("txt_id"))) { - if (Debug.debugging("vpf")) { - Debug.output("CoverageTable: Found entry for: " + feature_class + ": " + table1 - + "|" + foreign_key + "|" + table2 + "|" + primary_key); - } - - FeatureClassInfo featureClass = new FeatureClassInfo(this, foreign_key.intern(), tablepath.intern(), table1.intern(), table2.intern(), foreign_key.intern()); - featureClass.close(false); // releases file descriptors - featureTypes.put(feature_class.intern(), featureClass); - - } else { - // nothing else that we care about for now - // symbol.rat could show up here, for example - } - } catch (FormatException f) { - System.out.println("internSchema: " + f.getMessage()); - } - } - - /** - * Get the path for this coverage - */ - public String getDataPath() { - return tablepath; - } - - /** - * Returns all the feature classes - */ - public Map getFeatureClasses() { - return Collections.unmodifiableMap(featureTypes); - } - - /** - * Returns the FeatureClassInfo object corresponding to the feature type. - * Returns null if the featureType doesn't exist. - * - * @return the feature class object for the feature type - * @param featureType the name of the feature to get - */ - public FeatureClassInfo getFeatureClassInfo(String featureType) { - return featureTypes.get(featureType); - } - - public String getDescription(String t, String a, int v) { - CoverageIntVdt civ = new CoverageIntVdt(t, a, v); - return intvdtrec.get(civ); - } - - public String getDescription(String t, String a, String v) { - CoverageCharVdt civ = new CoverageCharVdt(t, a, v); - return charvdtrec.get(civ); - } - - private String getDescription(List id, FeatureClassInfo fti[], MutableInt ret) { - if ((fti == null) || (fti.length == 0)) { - return null; - } - StringBuffer foo = null; - for (int i = 0; i < fti.length; i++) { - String desc = fti[i].getDescription(id, ret); - if (desc != null) { - if (foo == null) { - foo = new StringBuffer(desc); - } else { - foo.append(";; ").append(desc); - } - } - } - return ((foo == null) ? null : foo.toString()); - } - - public String getLineDescription(List lineid, MutableInt retval) { - return getDescription(lineid, lineinfo, retval); - } - - public String getTextDescription(List textid, MutableInt retval) { - return getDescription(textid, textinfo, retval); - } - - public String getEPointDescription(List pointid, MutableInt retval) { - return getDescription(pointid, epointinfo, retval); - } - - public String getCPointDescription(List pointid, MutableInt retval) { - return getDescription(pointid, cpointinfo, retval); - } - - public String getAreaDescription(List areaid, MutableInt retval) { - return getDescription(areaid, areainfo, retval); - } - - public void setCoverateAttributeTable(CoverageAttributeTable cat) { - this.cat = cat; - } - - public CoverageAttributeTable getCoverageAttributeTable() { - return cat; - } - - /** - * Given a tile directory, go through the entries in the edg/fac/txt files, - * and send those entries to the warehouse. The warehouse will check their - * feature names with the feature names given to it in its properties, and - * eliminate the ones that it shouldn't draw. - */ - public void drawTile(TileDirectory drawtd, VPFGraphicWarehouse warehouse, LatLonPoint ll1, - LatLonPoint ll2, float dpplat, float dpplon) { - if (Debug.debugging("vpf.tile")) { - Debug.output("Drawtile for " + drawtd); - } - - TableHolder tables = new TableHolder(this); - tables.drawTile(drawtd, warehouse, ll1, ll2, dpplat, dpplon); - } - - /** - * This function uses the warehouse to get a list of features, and then - * looks in the featureList to see what feature tables handle those - * features. Using the appropriate feature table, the function then tracks - * down the tile that contains that feature, and the feature index into that - * tile file, and then contacts the warehouse to get that feature created - * into a graphic. - */ - public boolean drawFeatures(VPFFeatureWarehouse warehouse, LatLonPoint ll1, LatLonPoint ll2, - float dpplat, float dpplon) { - - boolean didSomething = false; - - TableHolder tables = new TableHolder(this); - - // First, find the list of features, and iterate through - // them. Use each one to go through it's feature table, if it - // exists. Then, from the feature table (perhaps check the - // FACC code, too), get the tile number and feature ID. - // Access the CoverageAttributeTable to get the tile (using a - // table from above), and check if it is within bounds. If it - // is, seek to get the feature. Once the feature has been - // read, contact the warehouse to use the row to build a - // graphic. Hold on to the tile in case (and it's likely) - // that the next feature desired is in the same tile). If it - // isn't, then dump the tile. - - // Should sort the feature types by area, text and then lines, - // to do them in that order. - - List featureList = warehouse.getFeatures(); - - for (String currentFeature : featureList) { - - // Figure out if the feature should be rendered, depending - // on what the warehouse settings are (drawedges, - // drawareas, drawtext). - char featureType = whatFeatureType(warehouse, currentFeature); - - if (featureType == SKIP_FEATURETYPE) { - // Blow off this feature type. - continue; - } - - if (Debug.debugging("vpf")) { - Debug.output("CoverageTable getting " + currentFeature + " features"); - } - - // Get the feature class for this feature type. - FeatureClassInfo fci = getFeatureClassInfo(currentFeature); - int fciFeatureIDCol = fci.whatColumn(DcwRecordFile.ID_COLUMN_NAME); - // Don't know why currentFeature would be null, but reports from - // users demonstrate that it might be. - if ((fci == null) || (cat == null) || currentFeature == null) { - continue; // don't have enough info to proceed - // in an untiled coverage, we could probably work - // without the cat - } - - // This looks like where most features get processed. - if (drawFeaturesFromThematicIndex(fci, warehouse, tables, ll1, ll2, dpplat, dpplon, currentFeature, featureType)) { - didSomething = true; - continue; - } - // couldn't use the tile_id thematic index, so just parse - // the whole file. This looks like the lessor case, trying to do - // something if the thematic index didn't work. - - boolean needToFindOurselves = true; - - TilingAdapter fciTilingAdapter = fci.getTilingAdapter(); - if (fciTilingAdapter == null) { - // no way to find primitives - continue; - } - - TileDirectory currentTile = null; - - // There are going to be a variable number of columns. - // We're interested in the f_code, tile_id, and the - // primitive id (fci independent depending on type). - - int oldTileID = -2; // -1 is "untiled" tile_id - // int faccIndex = fci.getFaccIndex() - - // OK, now we are looking in the Feature class file. - try { - int getrow = 1; - for (List fcirow = new ArrayList(); fci.getRow(fcirow, getrow++);) { - - if (Debug.debugging("vpfdetail")) { - Debug.output("CoverageTable new feature " + fcirow); - } - - int tileID = fciTilingAdapter.getTileId(fcirow); - - // String facc = (String)fcirow.get(faccIndex); - - // With tileID, find the tile and figure out if it - // is needed. - if (tileID != oldTileID) { - tables.close(); - - if (Debug.debugging("vpf.tile")) { - Debug.output("CoverageTable.drawFeatures(): opening new tile (" - + tileID + ")"); - } - - currentTile = (tileID == -1) ? new TileDirectory() - : cat.getTileWithID(tileID); - - if (currentTile == null) { - Debug.error("VPFLayer|CoverageTable.drawFeatures: null tile from bogus ID (" - + tileID + ") from " + fci.filename + ", skipping..."); - continue; - } - - if ((tileID == -1) - || currentTile.inRegion(ll1.getLatitude(), ll2.getLatitude(), ll2.getLongitude(), ll1.getLongitude())) { - - // We should only be in here once, I - // think, if the tile IDs are all stored - // in order. If the tile IDs are laid out - // in the FCI in jumbled order, only the - // first group of features will be - // gathered because the tile will appear - // cached. - String libraryname = ""; - if (cat != null) { - libraryname = cat.libraryname; - } - - if (!warehouse.needToFetchTileContents(libraryname, currentFeature, currentTile)) { - if (Debug.debugging("vpf")) { - Debug.output("CoverageTable: Loaded Cached List for " - + currentFeature + " and " + currentTile.getPath()); - } - continue; - } - - if (Debug.debugging("vpf.tile")) { - Debug.output("CoverageTable: Drawing " + featureType - + " features for " + currentTile); - } - - tables.setTables(featureType, currentTile); - - // Only need to do this once for a new - // fci... - if (needToFindOurselves) { - needToFindOurselves = false; - tables.findYourself(fci); - } - - } else { - tables.close(); - } - oldTileID = tileID; - } - - // If currentTile == null, then the tile - // wasn't found, or it is outside the area of - // interest. The tables in the TableHolder - // (tables) will all be null, and the tables - // drawFeature will return false... - - int primitiveID = fciTilingAdapter.getPrimId(fcirow); - int featureID = ((Number) fcirow.get(fciFeatureIDCol)).intValue(); - - if (tables.drawFeature(primitiveID, warehouse, ll1, ll2, dpplat, dpplon, currentFeature, featureID) != null) { - didSomething = true; - } - - } - - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("CoverageTable: Creating table: " + f.getClass() + " " - + f.getMessage()); - } - } - fci.close(); - } - tables.close(); - - return didSomething; - } - - /** - * This function gets the thematic index from the FeatureClassInfo object, - * and uses it to look up the tiles that contain the currentFeature. Then, - * that tile is checked to see if it is on the map. If it is, then that row - * in the thematic index is read to get the feature id numbers. The feature - * table is referenced for the feature ID number in the tile, and then the - * feature is drawn. - * - * @param fci the FeatureClassInfo (feature table) - * @param warehouse the VPFFeatureGraphicWarehouse to use to draw the - * graphics. - * @param ll1 the upper left corner of the map. - * @param ll2 the lower right corner of the map. - * @param dpplat degrees per pixel latitude direction. - * @param dpplon degrees per pixel longitude direction. - * @param currentFeature the feature string (roadl) - * @param featureType the CoverageTable letter representation of the feature - * type. - */ - protected boolean drawFeaturesFromThematicIndex(FeatureClassInfo fci, - VPFFeatureWarehouse warehouse, - TableHolder tables, LatLonPoint ll1, - LatLonPoint ll2, float dpplat, float dpplon, - String currentFeature, char featureType) { - - if (!fci.initThematicIndex(tablepath)) { - return false; - } - - List v = new ArrayList(); // hold fci row contents - - try { - int primitiveIdColIndex = fci.getTilePrimitiveIdColIndex(); - DcwThematicIndex thematicIndex = fci.getThematicIndex(); - Object[] indexes = thematicIndex.getValueIndexes(); - - fci.reopen(1); - - // We just know that these values are tile IDs. - for (int i = 0; i < indexes.length; i++) { - int tileID = VPFUtil.objectToInt(indexes[i]); - TileDirectory currentTile = cat.getTileWithID(tileID); - - if (currentTile == null) { - Debug.error("VPFLayer|CoverageTable.drawFeatures: null tile from bogus ID (" - + tileID + ") from " + fci.filename + ", skipping..."); - continue; - } - - if (currentTile.inRegion(ll1.getLatitude(), ll2.getLatitude(), ll2.getLongitude(), ll1.getLongitude())) { - - tables.setTables(featureType, currentTile); - tables.findYourself(fci); - - int[] featureID = thematicIndex.get(indexes[i]); - - if (Debug.debugging("vpf.tile")) { - Debug.output("Drawing " + featureID.length + " " + featureType - + " features for " + tileID + " " + currentTile); - } - - String libraryname = cat.libraryname; - - if (!warehouse.needToFetchTileContents(libraryname, currentFeature, currentTile)) { - if (Debug.debugging("vpf")) { - Debug.output("Loaded Cached List for " + currentFeature + " and " - + currentTile.getPath()); - } - continue; - } - - for (int j = 0; j < featureID.length; j++) { - // featurePrimID is the unique ID of this feature. The - // primitiveID looks like it's the fac_id of the feature - // in the tile. - int featurePrimID = featureID[j]; - if (!fci.getRow(v, featurePrimID)) { - // couldn't get row for some reason - continue; - } - - int primitiveID = VPFUtil.objectToInt(v.get(primitiveIdColIndex)); - // for attribute retrieval, we need the featurePrimID. - tables.drawFeature(primitiveID, warehouse, ll1, ll2, dpplat, dpplon, currentFeature, featurePrimID); - } - - tables.close(); - } else { - if (Debug.debugging("vpf.tile")) { - Debug.output("Skipping " + featureType + " features for " + tileID - + ", not on map"); - } - } - } - return true; - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("CoverageTable.DFFTI: Format Exception creating features: " - + f.getClass() + " " + f.getMessage()); - } - return false; - } finally { - fci.close(); - } - } - - /** - * This is a method specifically designed for the - * VPFAutoFeatureGraphicWarehouse, and the CoverageTable knows to check with - * the warehouse and use the PriorityHolders to fetch features. - * - * @param warehouse VPFAutoFeatureGraphicWarehouse - * @param ll1 upper left of coverage area - * @param ll2 lower right of coverage area - * @param dpplat degrees/pixel vertically - * @param dpplon degrees/pixel horizontally - * @param omgList The OMGraphicList to add OMGraphics, representing - * features. - * @throws FormatException if something goes wrong reading files, this - * exception will be thrown. - */ - public void getFeatures(VPFAutoFeatureGraphicWarehouse warehouse, LatLonPoint ll1, - LatLonPoint ll2, double dpplat, double dpplon, OMGraphicList omgList) - throws FormatException { - - // The map of feature names versus their table information - Map featureInfo = getFeatureClasses(); - TableHolder tables = new TableHolder(this); - - // Loop through the features, one by one. - for (Entry entry : featureInfo.entrySet()) { - - String featureName = entry.getKey(); - FeatureClassInfo fci = entry.getValue(); - - if (fci == null) { - continue; - } - - int fciFeatureIDCol = fci.whatColumn(DcwRecordFile.ID_COLUMN_NAME); - char featureType = whatFeatureType(warehouse, featureName); - - fci.checkInit(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(" for " + featureName + ": " + fci.getDescription()); - } - - /** - * The features are made up of various FACC codes, that more - * precisely categorize what each feature is. We're going to look at - * each entry of this particular feature type, and use the - * PriorityHolders from the warehouse to determine when it gets - * drawn. - */ - int faccIndex = fci.getFaccIndex(); - - if (faccIndex < 0) { - continue; - } - - int primitiveIDIndex = fci.getTilePrimitiveIdColIndex(); - int tileIDIndex = fci.getTileIdIndex(); - - TileDirectory currentTile = null; - - boolean needToFindOurselves = true; - - TilingAdapter fciTilingAdapter = fci.getTilingAdapter(); - if (fciTilingAdapter == null) { - // no way to find primitives - continue; - } - - // There are going to be a variable number of columns. - // We're interested in the f_code, tile_id, and the - // primitive id (fci independent depending on type). - int oldTileID = -2; // -1 is "untiled" tile_id - int getrow = 1; - - /** - * fcirow holds all the information for a particular feature. The - * fci lets you know what each column represents. - */ - for (List fcirow = new ArrayList(); fci.getRow(fcirow, getrow++);) { - - String facc = (String) fcirow.get(faccIndex); - - /** - * Get the list of FeaturePriorityHolders that correspond to - * this particlar facc. This list is just an organizational tool - * so we don't have to run through all of the FPHs. - */ - List list = warehouse.faccLookup.get(facc); - if (list != null) { - boolean foundMatch = false; - for (FeaturePriorityHolder ph : list) { - /** - * Checking to see if the attributes for a particular - * feature match this particular FPH. - */ - if (ph.matches(facc, fci, fcirow)) { - foundMatch = true; - if (logger.isLoggable(Level.FINE)) { - logger.fine("+++ MATCH FOUND for " + facc + " tileid:" - + fcirow.get(tileIDIndex) + ", primID:" - + fcirow.get(primitiveIDIndex)); - } - - // Now we have the PriorityHolder that should - // receive the OMGraphic created for this feature. - // Use the CoverageTable to create it via the - // warehouse, - - if (logger.isLoggable(Level.FINER)) { - logger.finer("CoverageTable new feature " + fcirow); - } - - int tileID = fciTilingAdapter.getTileId(fcirow); - - // With tileID, find the tile and figure out if it - // is needed. - if (tileID != oldTileID) { - tables.close(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("opening new tile (" + tileID + ")"); - } - - currentTile = (tileID == -1) ? new TileDirectory() - : cat.getTileWithID(tileID); - - if (currentTile == null) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("VPFLayer|CoverageTable.drawFeatures: null tile from bogus ID (" - + tileID - + ") from " - + fci.filename - + ", skipping..."); - } - continue; - } - - if ((tileID == -1) - || currentTile.inRegion(ll1.getLatitude(), ll2.getLatitude(), ll2.getLongitude(), ll1.getLongitude())) { - - // We should only be in here once, I - // think, if the tile IDs are all stored - // in order. If the tile IDs are laid out - // in the FCI in jumbled order, only the - // first group of features will be - // gathered because the tile will appear - // cached. - String libraryname = ""; - if (cat != null) { - libraryname = cat.libraryname; - } - - if (!warehouse.needToFetchTileContents(libraryname, featureName, currentTile)) { - if (Debug.debugging("vpf")) { - Debug.output("CoverageTable: Loaded Cached List for " - + featureName + " and " + currentTile.getPath()); - } - continue; - } - - if (Debug.debugging("vpf.tile")) { - Debug.output("CoverageTable: Drawing " + featureType - + " features for " + currentTile); - } - - try { - tables.setTables(featureType, currentTile); - } catch (FormatException fe) { - System.out.println("missing tile, let's ignore that"); - continue; - } - - // Only need to do this once for a new - // fci... - if (needToFindOurselves) { - needToFindOurselves = false; - tables.findYourself(fci); - } - - } else { - tables.close(); - } - oldTileID = tileID; - } - - // If currentTile == null, then the tile - // wasn't found, or it is outside the area of - // interest. The tables in the TableHolder - // (tables) will all be null, and the tables - // drawFeature will return false... - - int primitiveID = fciTilingAdapter.getPrimId(fcirow); - int featureID = ((Number) fcirow.get(fciFeatureIDCol)).intValue(); - - OMGraphic omg = tables.drawFeature(primitiveID, warehouse, ll1, ll2, dpplat, dpplon, featureName, featureID); - - if (omg != null) { - - warehouse.handleInformationForOMGraphic(omg, fci, fcirow); - ph.add(omg); - - if (logger.isLoggable(Level.FINEST)) { - StringBuffer pout = new StringBuffer(); - for (Object obj : fcirow) { - pout.append(obj).append(','); - } - logger.finest(pout.toString()); - } - } - } else { - // NOTE, this else statement is just for checking - // buoys. - // if (ph.facc.equals(facc)) { - // logger.info("something is getting blown off"); - // ph.matches(facc, fci, fcirow); - // } - } - - // And add it to the ph omgraphic list for - // retrieval a little bit later. - - } - - if (!foundMatch) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("--- NO MATCH FOUND for " + facc + ", type:" + featureType - + ", tileid:" + fcirow.get(tileIDIndex) + ", primID:" - + fcirow.get(primitiveIDIndex)); - } - } - } else if (warehouse.debugFacc == null) { - if (logger.isLoggable(Level.FINE)) { - logger.info("didn't find facc list for: " + facc); - } - } - } - fci.close(); - } - tables.close(); - } - - protected OMGraphic getOMGraphicForFeature() { - OMGraphic omg = null; - - return omg; - } - - /** - * Given a feature type name, figure out if the warehouse thinks it should - * *NOT* be drawn. - * - * @param warehouse the warehouse to build the graphics. - * @param featureName the VPF name of the feature (polbndl, for example). - * @return SKIP_FEATURETYPE if the feature should not be drawn. - */ - protected char whatFeatureType(VPFWarehouse warehouse, String featureName) { - // Test for the feature kind (edge, area, text, points) and - // don't continue if that type is not needed. - - char featureType = SKIP_FEATURETYPE; - - // Get the feature class for this feature type. - FeatureClassInfo fci = getFeatureClassInfo(featureName); - - if (fci == null) { - return featureType; - } - - char type = fci.getFeatureType(); - - if ((type == AREA_FEATURETYPE && warehouse.drawAreaFeatures()) - || (type == TEXT_FEATURETYPE && warehouse.drawTextFeatures()) - || (type == EDGE_FEATURETYPE && warehouse.drawEdgeFeatures()) - || (type == EPOINT_FEATURETYPE && warehouse.drawEPointFeatures()) - || (type == CPOINT_FEATURETYPE && warehouse.drawCPointFeatures())) { - featureType = type; - } - - return featureType; - } - - /** - * Feature Type Information read from VPF fca files. - */ - public static class FeatureClassRec { - /** the name of the feature class */ - final public String feature_class; - /** the type of the feature */ - final public char type; - /** a short text description */ - final public String description; - - /** - * Construct an instance of the class - * - * @param fclass the feature class name - * @param type the feature type - * @param desc the feature description - */ - public FeatureClassRec(String fclass, char type, String desc) { - feature_class = fclass; - this.type = type; - description = desc; - } - } - - /** - * Returns a map from feature name to FeatureClassRec - */ - public Hashtable getFeatureTypeInfo() { - if (featureTypeInfo == null) { - featureTypeInfo = new Hashtable(); - - String path = getDataPath(); - boolean addSlash = true; - // if (path.endsWith(File.separator)) { - if (path.endsWith("/") || path.endsWith(File.separator)) { - addSlash = false; - } - - String fca = path + (addSlash ? "/" : "") + "fca"; - if (!BinaryFile.exists(fca)) { - fca = fca + "."; - } - - if (BinaryFile.exists(fca)) { - try { - DcwRecordFile fcadesc = new DcwRecordFile(fca); - int fclass = fcadesc.whatColumn("fclass"); - int type = fcadesc.whatColumn("type"); - int descr = fcadesc.whatColumn("descr"); - for (ArrayList al = new ArrayList(fcadesc.getColumnCount()); fcadesc.parseRow(al);) { - String fname = ((String) al.get(fclass)).toLowerCase().intern(); - char ftype = ((String) al.get(type)).charAt(0); - String fdesc = (String) al.get(descr); - FeatureClassRec fcr = new FeatureClassRec(fname, ftype, fdesc); - featureTypeInfo.put(fname, fcr); - } - fcadesc.close(); - } catch (FormatException fe) { - // nevermind, skip it - } - } - } - return featureTypeInfo; - } - - public static void main(String[] args) { - if (args.length != 5) { - System.out.println("This main() is just assorted test code."); - System.out.println("Usage: java classname librarypath coveragename"); - System.out.println(" tablename attribute value"); - System.out.println("Result: Prints the corresponding value in int.vdt"); - } else { - CoverageTable ct = new CoverageTable(args[0], args[1]); - String desc = ct.getDescription(args[2], args[3], Integer.parseInt(args[4])); - System.out.println(desc); - } - } -} - -/** - * The TableHolder is a utility class that manages the EdgeTable, TextTable and - * AreaTable that are needed by the CoverageTable to use the warehouse to create - * graphics. - */ - -class TableHolder { - - EdgeTable edg = null; - TextTable tft = null; - AreaTable aft = null; - NodeTable ent = null; - NodeTable cnt = null; - - /** Used as a preallocated list to read feature tables. */ - List primitiveVector = new ArrayList(); - CoverageTable coverageTable; - - /** - * Construct the TableHandler with the CoverageTable it is helping. - */ - protected TableHolder(CoverageTable ct) { - coverageTable = ct; - } - - /** - * When drawing features (CoverageTable.drawFeatures()), sets up the - * TableHolder tables so that the right types are used. - * - * @param featureType from the CoverageTable, either AREA_FEATURETYPE, - * EDGE_FEATURETYPE or TEXT_FEATURETYPE. - * @param tile the tile directory that needs to be used when fetching - * graphics from the appropriate files. - */ - protected void setTables(char featureType, TileDirectory tile) throws FormatException { - - if (featureType == CoverageTable.EDGE_FEATURETYPE) { - edg = new EdgeTable(coverageTable, tile); - } - if (featureType == CoverageTable.TEXT_FEATURETYPE) { - tft = new TextTable(coverageTable, tile); - } - if (featureType == CoverageTable.AREA_FEATURETYPE) { - aft = new AreaTable(coverageTable, null, tile); - edg = null; - } - if (featureType == CoverageTable.EPOINT_FEATURETYPE) { - ent = new NodeTable(coverageTable, tile, true); - } - if (featureType == CoverageTable.CPOINT_FEATURETYPE) { - cnt = new NodeTable(coverageTable, tile, false); - } - - if (CoverageTable.logger.isLoggable(Level.FINE)) { - int activeTableCount = 0; - if (edg != null) - activeTableCount++; - if (tft != null) - activeTableCount++; - if (aft != null) - activeTableCount++; - if (ent != null) - activeTableCount++; - if (cnt != null) - activeTableCount++; - if (activeTableCount > 1) { - CoverageTable.logger.warning("TableHolder has more than one feature type"); - } - } - - } - - /** - * Should be called once per FeatureClassInfo, after the tables have been - * set. Lets the tables figure out which columns to use as an index. - */ - protected void findYourself(FeatureClassInfo fci) { - if (aft != null) { - fci.findYourself(aft); - } else if (tft != null) { - fci.findYourself(tft); - } else if (edg != null) { - fci.findYourself(edg); - } else if (ent != null) { - fci.findYourself(ent); - } - } - - /** - * Should be called once per feature, after the tables have been set - * (setTables()), and findYourself() has been called. The appropriate table - * will use the warehouse to create proper OMGraphic. - */ - protected OMGraphic drawFeature(int primitiveID, VPFFeatureWarehouse warehouse, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon, - String currentFeature, int featurePrimID) - throws FormatException { - - if (aft != null || tft != null || edg != null || ent != null || cnt != null) { - // OK, now check to see what table is being - // used. if the tile is being reused, the - // table will be reused. - - if ((aft != null) && aft.getRow(primitiveVector, primitiveID)) { - return aft.drawFeature(warehouse, dpplat, dpplon, ll1, ll2, primitiveVector, currentFeature, featurePrimID); - } - if ((tft != null) && tft.getRow(primitiveVector, primitiveID)) { - return tft.drawFeature(warehouse, dpplat, dpplon, ll1, ll2, primitiveVector, currentFeature, featurePrimID); - } - if ((ent != null) && ent.getRow(primitiveVector, primitiveID)) { - return ent.drawFeature(warehouse, dpplat, dpplon, ll1, ll2, primitiveVector, currentFeature, featurePrimID); - } - if ((cnt != null) && cnt.getRow(primitiveVector, primitiveID)) { - return cnt.drawFeature(warehouse, dpplat, dpplon, ll1, ll2, primitiveVector, currentFeature, featurePrimID); - } - if ((edg != null) && edg.getRow(primitiveVector, primitiveID)) { - return edg.drawFeature(warehouse, dpplat, dpplon, ll1, ll2, primitiveVector, currentFeature, featurePrimID); - } - } - - return null; - } - - /** - * Only call once per tile. It will parse all the needed data in the tile. - * Does not require setTables() or findYourself(). - */ - protected void drawTile(TileDirectory tile, VPFGraphicWarehouse warehouse, LatLonPoint ll1, - LatLonPoint ll2, float dpplat, float dpplon) { - - boolean drawedge = warehouse.drawEdgeFeatures(); - boolean drawtext = warehouse.drawTextFeatures(); - boolean drawarea = warehouse.drawAreaFeatures(); - boolean drawepoint = warehouse.drawEPointFeatures(); - boolean drawcpoint = warehouse.drawCPointFeatures(); - close(); - - try { - if (drawedge || drawarea) { - edg = new EdgeTable(coverageTable, tile); - } - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("EdgeTable: " + f.getClass() + " " + f.getMessage()); - } - } - - try { - if (drawtext) { - tft = new TextTable(coverageTable, tile); - } - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("TextTable: " + f.getClass() + " " + f.getMessage()); - } - } - - try { - if (drawepoint) { - ent = new NodeTable(coverageTable, tile, true); - } - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("NodeTable: " + f.getClass() + " " + f.getMessage()); - } - } - - try { - if (drawcpoint) { - cnt = new NodeTable(coverageTable, tile, false); - } - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("NodeTable: " + f.getClass() + " " + f.getMessage()); - } - } - - try { - if (drawarea && (edg != null)) { - aft = new AreaTable(coverageTable, edg, tile); - } - } catch (FormatException f) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("AreaTable: " + f.getClass() + " " + f.getMessage()); - } - } - - if ((aft != null) && drawarea) { - for (int i = 0; i < coverageTable.areainfo.length; i++) { - coverageTable.areainfo[i].findYourself(aft); - } - aft.drawTile(warehouse, dpplat, dpplon, ll1, ll2); - } - if ((tft != null) && drawtext) { - for (int i = 0; i < coverageTable.textinfo.length; i++) { - coverageTable.textinfo[i].findYourself(tft); - } - tft.drawTile(warehouse, dpplat, dpplon, ll1, ll2); - } - if ((edg != null) && drawedge) { - for (int i = 0; i < coverageTable.lineinfo.length; i++) { - coverageTable.lineinfo[i].findYourself(edg); - } - edg.drawTile(warehouse, dpplat, dpplon, ll1, ll2); - } - if ((ent != null) && drawepoint) { - for (int i = 0; i < coverageTable.epointinfo.length; i++) { - coverageTable.epointinfo[i].findYourself(ent); - } - ent.drawTile(warehouse, dpplat, dpplon, ll1, ll2); - } - if ((cnt != null) && drawcpoint) { - for (int i = 0; i < coverageTable.cpointinfo.length; i++) { - coverageTable.cpointinfo[i].findYourself(cnt); - } - cnt.drawTile(warehouse, dpplat, dpplon, ll1, ll2); - } - // if (Debug.On && Debug.debugging("vpf.tile")) - // Debug.output(drawtd.toString() + " " + edgecount[0] + - // " polys with " + edgecount[1] + - // " points (cumulative)\n" + - // drawtd.toString() + " " + textcount[0] + - // " texts with " + textcount[1] + - // " points (cumulative)\n" + - // drawtd.toString() + " " + areacount[0] + - // " areas with " + areacount[1] + - // " points (cumulative)"); - close(); - } - - /** - * Close any of these tables that may be in use. - */ - protected void close() { - if (Debug.debugging("vpf.tile")) { - Debug.output("CoverageTable closing tile tables"); - } - if (edg != null) { - edg.close(); - } - if (tft != null) { - tft.close(); - } - if (aft != null) { - aft.close(); - } - if (ent != null) { - ent.close(); - } - if (cnt != null) { - cnt.close(); - } - aft = null; - tft = null; - edg = null; - ent = null; - cnt = null; - } - -} - -/** - * A utility class used to map information from a VPF feature table to its - * associated value in an int.vdt file. - */ - -class CoverageIntVdt { - /** the name of the table we are looking up (table is interned) */ - final String table; - /** - * the name of the attribute we are looking up (attribute is interned) - */ - final String attribute; - /** the integer value we are looking up */ - final int value; - - /** - * Construct a new object - * - * @param t value for the table member - * @param a the value for the attribute member - * @param v the value for the value member - */ - public CoverageIntVdt(String t, String a, int v) { - table = t.toLowerCase().intern(); - attribute = a.toLowerCase().intern(); - value = v; - } - - /** - * Override the equals method. Two CoverageIntVdts are equal if and only iff - * their respective table, attribute and value members are equal. - */ - public boolean equals(Object o) { - if (o == null) { - return false; - } - if (getClass() != o.getClass()) { - return false; - } - final CoverageIntVdt civ = (CoverageIntVdt) o; - // we can use == rather than String.equals(String) since - // table and attribute are interned. - return ((table == civ.table) && (attribute == civ.attribute) && (value == civ.value)); - } - - /** - * Override hashcode. Compute a hashcode based on our member values, rather - * than our (base class) object identity. - */ - public int hashCode() { - return ((table.hashCode() ^ attribute.hashCode()) ^ value); - } -} - -/** - * A utility class used to map information from a VPF feature table to its - * associated value in an char.vdt file. - */ - -class CoverageCharVdt { - /** the name of the table we are looking up (table is interned) */ - final String table; - /** - * the name of the attribute we are looking up (attribute is interned) - */ - final String attribute; - /** the character value we are looking up (value is interned) */ - final String value; - - /** - * Construct a new object - * - * @param t value for the table member - * @param a the value for the attribute member - * @param v the value for the value member - */ - public CoverageCharVdt(String t, String a, String v) { - table = t.toLowerCase().intern(); - attribute = a.toLowerCase().intern(); - value = v.intern(); - } - - /** - * Override the equals method. Two CoverageIntVdts are equal if and only iff - * their respective table, attribute and value members are equal. - */ - public boolean equals(Object o) { - if (o == null) { - return false; - } - if (getClass() != o.getClass()) { - return false; - } - final CoverageCharVdt civ = (CoverageCharVdt) o; - // we can use == rather than String.equals(String) since - // table, attribute, and value are interned. - return ((table == civ.table) && (attribute == civ.attribute) && (value == civ.value)); - } - - /** - * Override hashcode. Compute a hashcode based on our member values, rather - * than our (base class) object identity. - */ - public int hashCode() { - return ((table.hashCode() ^ attribute.hashCode()) ^ value.hashCode()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwColumnInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwColumnInfo.java deleted file mode 100644 index 842c9ec04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwColumnInfo.java +++ /dev/null @@ -1,585 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwColumnInfo.java,v $ -// $Revision: 1.6 $ $Date: 2007/01/26 15:57:18 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Encapsulate the information about a particular column in a vpf - * table. This class can read both VPF V1 (MIL-STD-600006, dated 1992) - * and VPF V2 (MIL-STD-2407, dated 1996, supercedes V1) - */ -public class DcwColumnInfo { - /** the name of the column */ - final private String columnName; - /** the fieldtype of the contained data */ - final private char fieldType; - /** the number of values (-1 indicates variable) */ - final private int numberOfElements; - /** the keytype (primary key, non-key, foreign key) */ - final private char keyType; - /** optional text description of what the column is for */ - final private String columnDescription; - /** - * optional table that provides descriptions of what the values in - * this column are - */ - private String valueDescriptionTable = null; - /** name of the optional thematic index created for this column */ - private String thematicIndexName = null; - /** name of the optional narrative table for this column */ - private String narrativeTable = null; - - /** VPF Column Type Constants */ - public static final char VPF_COLUMN_TEXT = 'T'; - public static final char VPF_COLUMN_TEXTL1 = 'L'; - public static final char VPF_COLUMN_TEXTL2 = 'M'; - public static final char VPF_COLUMN_TEXTL3 = 'N'; - public static final char VPF_COLUMN_FLOAT = 'F'; - public static final char VPF_COLUMN_DOUBLE = 'R'; - public static final char VPF_COLUMN_SHORT = 'S'; - public static final char VPF_COLUMN_INT = 'I'; - public static final char VPF_COLUMN_FLOAT_2COORD = 'C'; - public static final char VPF_COLUMN_DOUBLE_2COORD = 'B'; - public static final char VPF_COLUMN_FLOAT_3COORD = 'Z'; - public static final char VPF_COLUMN_DOUBLE_3COORD = 'Y'; - public static final char VPF_COLUMN_DATE = 'D'; - public static final char VPF_COLUMN_NULL = 'X'; - public static final char VPF_COLUMN_TRIPLET = 'K'; - /** - * VPF Column Type Constant for a column that can be either int or - * short. This value will never be read from a VPF file, its a - * special value that is accepted by lookupSchema - */ - public static final char VPF_COLUMN_INT_OR_SHORT = 'i'; - - /** VPF Column Key Type Constants */ - public static final char VPF_COLUMN_PRIMARY_KEY = 'P'; - public static final char VPF_COLUMN_FOREIGN_KEY = 'F'; - public static final char VPF_COLUMN_NON_KEY = 'N'; - - /** - * Construct a DcwColumnInfo from the specified input stream. - * - * @param inputFile the filestream to construct from - * @exception EOFException when the first character read is a ';', - * indicating that we've reached the end of the column - * list; also thrown for an end of file - * @exception FormatException some error was detected while - * reading the info for the column. - */ - public DcwColumnInfo(BinaryFile inputFile) throws EOFException, - FormatException { - char delim = inputFile.readChar(); - if (delim == ';') - throw new EOFException(); - - StringBuffer buildstring = new StringBuffer(); - do { - buildstring.append(Character.toLowerCase(delim)); - } while ((delim = inputFile.readChar()) != '='); - - columnName = buildstring.toString().trim().intern();// Collapse all blanks - - fieldType = inputFile.readChar(); - - delim = inputFile.readChar(); - if (delim != ',') { //only legal delimiter - if (delim != ' ') { //one DCW file uses this instead - throw new com.bbn.openmap.io.InvalidCharException("Illegal delimiter character", delim); - } - } - - buildstring = new StringBuffer(); - while ((delim = inputFile.readChar()) != ',') { - // field length occasionally has trailing whitespace... - if (!Character.isWhitespace(delim)) { - buildstring.append(delim); //assumes not like "1 4" - } - } - String nEls = buildstring.toString(); - numberOfElements = (nEls.equals("*")) ? -1 : Integer.parseInt(nEls); - - // Sanity check the column schema... a few VPF primitives are - // not - // allowed to show up in arrays. complain about that now... - if (numberOfElements != 1) { - switch (fieldType) { - case VPF_COLUMN_FLOAT: - case VPF_COLUMN_DOUBLE: - case VPF_COLUMN_SHORT: - case VPF_COLUMN_INT: - case VPF_COLUMN_DATE: - case VPF_COLUMN_NULL: - case VPF_COLUMN_TRIPLET: - throw new FormatException("Illegal array type: " + fieldType - + "for column " + columnName); - default: - //legal - break; - } - } - - String tmpkeyType = readColumnText(inputFile); - if (tmpkeyType == null) { - throw new FormatException("keyType is required column info"); - } - tmpkeyType = tmpkeyType.trim(); - if (tmpkeyType.length() == 1) { - keyType = tmpkeyType.charAt(0); - } else { - throw new FormatException("keyType is supposed to be 1 character"); - } - columnDescription = readColumnText(inputFile); - if (columnDescription == null) { - return; - } - - valueDescriptionTable = readColumnTextLowerCase(inputFile); - if (valueDescriptionTable == null) { - return; - } - if (valueDescriptionTable.equals("-")) { - valueDescriptionTable = null; - } else { - valueDescriptionTable = valueDescriptionTable.intern(); - } - - thematicIndexName = readColumnTextLowerCase(inputFile); - if (thematicIndexName == null) { - return; - } - if (thematicIndexName.equals("-")) { - thematicIndexName = null; - } else { - thematicIndexName = thematicIndexName.intern(); - } - - narrativeTable = readColumnTextLowerCase(inputFile); - if (narrativeTable == null) { - return; - } - if (narrativeTable.equals("-")) { - narrativeTable = null; - } else { - narrativeTable = narrativeTable.intern(); - } - - inputFile.assertChar(':'); - } - - /** - * Reads a string until the field separator is detected, the - * column record separator is detected, or and end-of-file is hit. - * - * @return the string read from the file - * @param inputFile the file to read the field from - * @param toLower convert the string to lower-case - * @exception FormatException ReadChar IOExceptions rethrown as - * FormatExceptions - */ - private String readColumnText(BinaryFile inputFile) throws FormatException { - StringBuffer buildretval = new StringBuffer(); - boolean skipnext = false; - char tmp; - try { - while ((tmp = inputFile.readChar()) != ',') { - if ((tmp == ':') && !skipnext) { - return null; - } - if (tmp == '\\') { - skipnext = true; - } else { - skipnext = false; - buildretval.append(tmp); - } - } - } catch (EOFException e) { - //allowable - } - return buildretval.toString(); - } - - /** - * Reads a string until the field separator is detected, the - * column record separator is detected, or and end-of-file is hit, - * and converts in to lowercase. - * - * @return the string read from the file, all in lowercase - * @param inputFile the file to read the field from - * @param toLower convert the string to lower-case - * @exception FormatException ReadChar IOExceptions rethrown as - * FormatExceptions - */ - private String readColumnTextLowerCase(BinaryFile inputFile) - throws FormatException { - StringBuffer buildretval = new StringBuffer(); - boolean skipnext = false; - char tmp; - try { - while ((tmp = inputFile.readChar()) != ',') { - if ((tmp == ':') && !skipnext) { - return null; - } - if (tmp == '\\') { - skipnext = true; - } else { - skipnext = false; - buildretval.append(Character.toLowerCase(tmp)); - } - } - } catch (EOFException e) { - //allowable - } - return buildretval.toString(); - } - - /** - * Claim that the column has a particular schema - * - * @param type the FieldType (datatype) this column is expected to - * contain legal values are specified by the VPF standard. - * the non-standard value 'i' is also accepted (equivalent - * to 'I' or 'S'), indicating an integral type. - * @param length the number of elements in this column - * @param strictlength false means that variable length columns - * can be fixed length instead - * @exception FormatException the column is not of the particular - * type/length - */ - public void assertSchema(char type, int length, boolean strictlength) - throws FormatException { - if ((type != fieldType) - && !((type == 'i') && ((fieldType == VPF_COLUMN_INT) || (fieldType == VPF_COLUMN_SHORT)))) { - throw new FormatException("AssertSchema failed on fieldType!"); - } - if ((strictlength && (length != numberOfElements)) - || (!strictlength && (length != -1) && (length != numberOfElements))) { - throw new FormatException("AssertSchema failed on length!"); - } - } - - /** - * the number of bytes a field of this type takes in the input - * file - * - * @return the number of bytes (-1 for a variable-length field) - * @exception FormatException the FieldType of this Column is not - * a valid VPF fieldtype - */ - public int fieldLength() throws FormatException { - if (numberOfElements == -1) { - return -1; - } - - switch (fieldType) { - case VPF_COLUMN_TEXT: - case VPF_COLUMN_TEXTL1: - case VPF_COLUMN_TEXTL3: - case VPF_COLUMN_TEXTL2: //various text string types - return numberOfElements; - case VPF_COLUMN_FLOAT: //floats - return 4; - case VPF_COLUMN_DOUBLE: //doubles - return 8; - case VPF_COLUMN_SHORT: //shorts - return 2; - case VPF_COLUMN_INT: //ints - return 4; - case VPF_COLUMN_FLOAT_2COORD: //2-coord floats - return numberOfElements * 8; - case VPF_COLUMN_DOUBLE_2COORD: //2-coord doubles - return numberOfElements * 16; - case VPF_COLUMN_FLOAT_3COORD: //3-coord floats - return numberOfElements * 12; - case VPF_COLUMN_DOUBLE_3COORD: //3-coord doubles - return numberOfElements * 24; - case VPF_COLUMN_DATE: //dates - return 20; - case VPF_COLUMN_NULL: //nulls - return 0; - case VPF_COLUMN_TRIPLET: //cross-tile identifiers - return -1; //variable length - default: { - throw new FormatException("Unknown field type: " + fieldType); - } - } - //unreached - } - - /** - * get the name of the column - * - * @return the name of the column - */ - public String getColumnName() { - return columnName; - } - - /** - * get the VPF datatype of the column - * - * @return the VPF datatype - */ - public char getFieldType() { - return fieldType; - } - - /** - * get the number of elements - * - * @return the number of elements - */ - public int getNumberOfElements() { - return numberOfElements; - } - - /** - * get the VPF key type (one of VPF_COLUMN_PRIMARY_KEY, - * VPF_COLUMN_FOREIGN_KEY, or VPF_COLUMN_NON_KEY) - * - * @return the vpf key type - */ - public char getKeyType() { - return keyType; - } - - /** - * Return true if this column is a primary key. For - * any valid column, exactly one of isPrimaryKey, isForeignKey and - * isNonKey will be true. - * - * @return true for a primary key, false otherwise. - * @see #isForeignKey() - * @see #isNonKey() - */ - public boolean isPrimaryKey() { - return (keyType == VPF_COLUMN_PRIMARY_KEY); - } - - /** - * Return true if this column is a foreign key. For - * any valid column, exactly one of isPrimaryKey, isForeignKey and - * isNonKey will be true. - * - * @return true for a foreign key, false otherwise. - * @see #isPrimaryKey() - * @see #isNonKey() - */ - public boolean isForeignKey() { - return (keyType == VPF_COLUMN_FOREIGN_KEY); - } - - /** - * Return true if this column is not a key column. - * For any valid column, exactly one of isPrimaryKey, isForeignKey - * and isNonKey will be true. - * - * @return false for a primary or foreign key, true otherwise. - * @see #isForeignKey() - * @see #isPrimaryKey() - */ - public boolean isNonKey() { - return (keyType == VPF_COLUMN_NON_KEY); - } - - /** - * Get the column description - * - * @return the column description (possibly null) - */ - public String getColumnDescription() { - return columnDescription; - } - - /** - * Get the name of the value description table - * - * @return the name of the value description table (possibly - * null). The same as getVDT() - * @see #getVDT() - */ - public String getValueDescriptionTable() { - return valueDescriptionTable; - } - - /** - * Get the name of the value description table - * - * @return the name of the value description table (possibly - * null). The same as - * getValueDescriptionTable - * @see #getValueDescriptionTable() - */ - public String getVDT() { - return valueDescriptionTable; - } - - /** - * get the name of the thematic index - * - * @return the thematic index name (possibly null) - */ - public String getThematicIndexName() { - return thematicIndexName; - } - - /** - * get the name of the narrative table - * - * @return the name of the narrative table (possibly - * null) - */ - public String getNarrativeTable() { - return narrativeTable; - } - - /** - * Read an element of the type specified by the column - * - * @return the value read from the input file - * @exception EOFException an end-of-file was encountered before - * reading any of the field - * @exception FormatException some data-consistency check failed - * while reading the data, or an end-of-file condition - * popped up in the middle of reading a field (partial - * read) - */ - public Object parseField(BinaryFile inputFile) throws EOFException, - FormatException { - // See table 56, p 79 of MIL-STD-600006 (1992 VPF Standard) - // See table 10, p 51 of MIL-STD-2407 (1996 VPF Standard - // supercedes 600006) - boolean haveElements = (numberOfElements != -1); - int numels = numberOfElements; - - switch (fieldType) { - case VPF_COLUMN_TEXT: { - if (!haveElements) {//Variable length string - numels = inputFile.readInteger(); - } - if (numels == 0) { - return ""; - } - String s = inputFile.readFixedLengthString(numels); - if (haveElements) {//Fixed Length Strings loose trailing - // whitespace - s = s.trim(); - } - return s; - } - case VPF_COLUMN_TEXTL1: { - if (!haveElements) {//Variable length string - numels = inputFile.readInteger(); - } - if (numels == 0) { - return ""; - } - byte[] str = inputFile.readBytes(numels, false); - try { - String s = new String(str, "ISO8859_1"); - if (haveElements) {//Fixed Length Strings loose - // trailing whitespace - s = s.trim(); - } - return s; - } catch (java.io.UnsupportedEncodingException uee) { - return str; - } - } - case VPF_COLUMN_TEXTL2: - case VPF_COLUMN_TEXTL3: { - if (!haveElements) {//Variable length string - numels = inputFile.readInteger(); - } - if (numels == 0) { - return new byte[0]; - } - return inputFile.readBytes(numels, false); - } - case VPF_COLUMN_FLOAT: { - return new Float(inputFile.readFloat()); - } - case VPF_COLUMN_DOUBLE: { - return new Double(inputFile.readDouble()); - } - case VPF_COLUMN_SHORT: { - return new Short(inputFile.readShort()); - } - case VPF_COLUMN_INT: { - return new Integer(inputFile.readInteger()); - } - case VPF_COLUMN_FLOAT_2COORD: { //2-coord floats - if (!haveElements) { - numels = inputFile.readInteger(); - } - return new CoordFloatString(numels, 2, inputFile); - } - case VPF_COLUMN_DOUBLE_2COORD: { //2-coord doubles - if (!haveElements) { - numels = inputFile.readInteger(); - } - return new CoordDoubleString(numels, 2, inputFile); - } - case VPF_COLUMN_FLOAT_3COORD: { //3-coord floats - if (!haveElements) { - numels = inputFile.readInteger(); - } - return new CoordFloatString(numels, 3, inputFile); - } - case VPF_COLUMN_DOUBLE_3COORD: { //3-coord doubles - if (!haveElements) { - numels = inputFile.readInteger(); - } - return new CoordDoubleString(numels, 3, inputFile); - } - case VPF_COLUMN_DATE: { - inputFile.readBytes(20, false); - return "[skipped date]"; - } - case VPF_COLUMN_NULL: { - return "[Null Field Type]"; - } - case VPF_COLUMN_TRIPLET: { - return new DcwCrossTileID(inputFile); - } - default: { - throw new FormatException("Unknown field type: " + fieldType); - } - } - //unreached - } - - /** - * produce a nice printed version of all our contained information - * - * @return a nice little string - */ - public String toString() { - StringBuffer output = new StringBuffer(); - output.append(columnName).append(" ").append(fieldType).append(" "); - output.append(numberOfElements).append(" "); - output.append(keyType).append(" "); - output.append(columnDescription).append(" ").append(valueDescriptionTable).append(" "); - output.append(thematicIndexName).append(" ").append(narrativeTable); - return output.toString(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwCrossTileID.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwCrossTileID.java deleted file mode 100644 index 1ead81ae5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwCrossTileID.java +++ /dev/null @@ -1,144 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwCrossTileID.java,v $ -// $RCSfile: DcwCrossTileID.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 19:29:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; -import java.io.IOException; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.MoreMath; - -/** - * Encapsulate the VPF Cross-Tile identifier primitive datatype. The - * cross-tile identifier relates map features that cross multiple - * tiles.
- * Note: Mil-Std-2407 cross tile ids have a fourth, unused field. This - * class will read that field, but does not use it. - */ -public class DcwCrossTileID { - /** the 1-byte length specifier for the rest of the values... */ - //private int funkyDcwKeyValue = -1; - /** the key for this tile */ - final public int currentTileKey; - /** the id for the connected tile */ - final public int nextTileID; - /** the key in the adjoining tile */ - final public int nextTileKey; - - /** unused value in VPF... */ - //private int unusedDcwKey = -1; - /** - * Construct a DcwCrossTileID - * - * @param currentTileKey primitive ID in current tile - * @param nextTileID tile ID - * @param nextTileKey primitive ID in nextTileID - */ - public DcwCrossTileID(int currentTileKey, int nextTileID, int nextTileKey) { - this.currentTileKey = currentTileKey; - this.nextTileID = nextTileID; - this.nextTileKey = nextTileKey; - } - - /** - * Construct a DcwCrossTileID from the specified input stream. - * - * @param in the filestream to construct from - * @exception FormatException some error was detected while - * reading the info for the column. - * @exception EOFException EOF was encountered before reading any - * data - */ - public DcwCrossTileID(BinaryFile in) throws FormatException, EOFException { - int format; - try { - format = in.read(); - } catch (IOException ioe) { - throw new FormatException(ioe.getMessage()); - } - if (format == -1) { - throw new EOFException(); - } - - try { - currentTileKey = readIntegerByKey(in, format >> 6); - nextTileID = readIntegerByKey(in, format >> 4); - nextTileKey = readIntegerByKey(in, format >> 2); - /*int unusedDcwKey = */readIntegerByKey(in, format); - } catch (EOFException e) { - throw new FormatException("DcwCrossTileID: unexpected EOD " - + e.getMessage()); - } - } - - /** - * Reads an integer from the input stream - * - * @param in the stream to read from - * @param key specifies the number of bytes to read (based on - * bottom 2 bits) - * @return the integer read. (-1 for a zero-length field) - * @exception FormatException internal consistency failure - * @exception EOFException hit end-of-file while reading data - */ - private int readIntegerByKey(BinaryFile in, int key) - throws FormatException, EOFException { - switch (key & 0x3) { - case 0: - return -1; - case 1: { - int byteval; - try { - byteval = in.read(); - } catch (IOException ioe) { - throw new FormatException(ioe.getMessage()); - } - if (byteval == -1) { - throw new EOFException(); - } - return byteval; - } - case 2: - return MoreMath.signedToInt(in.readShort()); - case 3: - return in.readInteger(); - } - throw new FormatException("This can't happen"); - } - - /** - * produce a nice printed version of all our contained information - * - * @return a nice little string - */ - public String toString() { - StringBuffer output = new StringBuffer(); - output.append(currentTileKey).append("/"); - if ((nextTileID != -1) && (nextTileKey != -1)) { - output.append(nextTileID).append(","); - output.append(nextTileKey); - } - return output.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwRecordFile.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwRecordFile.java deleted file mode 100644 index 81c45e447..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwRecordFile.java +++ /dev/null @@ -1,692 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwRecordFile.java,v $ -// $Revision: 1.6 $ $Date: 2005/01/10 16:36:21 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.MoreMath; - -/** - * Read and encapsulate VPF table files. - */ -public class DcwRecordFile { - - /** input is read from this file */ - protected BinaryFile inputFile = null; - /** the description of the table [read from the file] */ - protected String tableDescription = null; - /** the name of another table that describes what this one is for */ - protected String documentationFileName = null; - /** number of bytes consumed by the table header */ - private int headerLength = 4; //for the 4 bytes of the - // headerlength field - /** - * big-endian (true) or little-endian ( - * false) - */ - protected boolean MSBFirst = false; - /** ordered set of columns (read from table header) */ - protected DcwColumnInfo[] columnInfo = null; - /** - * length of a record (-1 indicates - * variable-length record) - */ - protected int recordLength = 0; - /** - * for tables with variable-length records, the corresponding - * variable-length index - */ - protected DcwVariableLengthIndexFile vli = null; - /** the name of the file */ - final protected String filename; - /** the name of the table */ - protected String tablename = null; - /** - * remember the byte order for later file openings, true for MSB - * first - */ - protected boolean byteorder = true; - /** the record number that a call to parseRow() will return */ - int cursorRow = -1; - - /** the name of the row identifier column "id" */ - public static final String ID_COLUMN_NAME = "id"; - - /** - * Open a DcwRecordFile and completely initialize it - * - * @param name the name of the file to use for input - * @exception FormatException some problem was encountered dealing - * with the file - */ - public DcwRecordFile(String name) throws FormatException { - this(name, false); - } - - /** - * Open a DcwRecordFile - * - * @param name the name of the file to use for input - * @param deferInit if true, don't actually open - * files and initialize the object. In this state, the only - * method that should be called is finishInitialization. - * @exception FormatException some problem was encountered dealing - * with the file - * @see #finishInitialization() - */ - public DcwRecordFile(String name, boolean deferInit) throws FormatException { - this.filename = name; - if (!deferInit) { - finishInitialization(); - } - } - - /** - * Strip the tablename out of the filename. Strips both path - * information and the trailing '.', if it exists. - */ - private void internTableName() { - int strlen = filename.length(); - int firstchar = filename.lastIndexOf('/'); - int lastchar = filename.endsWith(".") ? strlen - 1 : strlen; - tablename = filename.substring(firstchar + 1, lastchar) - .toLowerCase() - .intern(); - } - - /** - * Returns the File this instance is using - * - * @return the File being read - */ - public String getTableFile() { - return filename; - } - - /** - * return the name of the table - */ - public String getTableName() { - return tablename; - } - - /** - * Complete initialization of this object. This function should - * only be called once, and only if the object was constructed - * with deferred initialization. - * - * @exception FormatException some problem was encountered dealing - * with the file - */ - public synchronized void finishInitialization() throws FormatException { - internTableName(); - try { - inputFile = new BinaryBufferedFile(filename); - } catch (IOException e) { - throw new FormatException(e.toString()); - } - try { - byte preHeaderLen[] = inputFile.readBytes(4, false); - - char delim = inputFile.readChar(); - switch (delim) { - case 'L': - case 'l': - delim = inputFile.readChar(); - //Intentional fall through to set byteorder - case ';': //default is LSB first - byteorder = false; - inputFile.byteOrder(byteorder); - break; - case 'M': - case 'm': //alternatively, it can be MSB first - byteorder = true; - inputFile.byteOrder(byteorder); - delim = inputFile.readChar(); - break; - default: - throw new FormatException("Invalid Byte Encoding Format"); - } - headerLength += MoreMath.BuildInteger(preHeaderLen, byteorder); - if (delim != ';') {//Sanity check the input - throw new FormatException("Unexpected character in header"); - } - tableDescription = inputFile.readToDelimiter(';'); - documentationFileName = inputFile.readToDelimiter(';'); - if ("-".equals(documentationFileName)) { - documentationFileName = null; - } - - ArrayList tmpcols = new ArrayList(); - try { - while (true) { - DcwColumnInfo dci = new DcwColumnInfo(inputFile); - int collen = dci.fieldLength(); - if ((collen == -1) || (recordLength == -1)) { - recordLength = -1; - } else { - recordLength += collen; - } - tmpcols.add(dci); - } - } catch (EOFException e) { - } - - columnInfo = new DcwColumnInfo[tmpcols.size()]; - tmpcols.toArray(columnInfo); - - cursorRow = 1; - } catch (EOFException e) { - throw new FormatException("Caught EOFException: " + e.getMessage()); - } catch (NullPointerException npe) { - } - } - - /** - * Returns a TilingAdapter for the selected column. - * - * @param primColumnName the name of the primitive column - * @return an appropriate TilingAdapter instance or null - */ - public TilingAdapter getTilingAdapter(String primColumnName) { - return getTilingAdapter(-1, whatColumn(primColumnName)); - } - - /** - * Returns a TilingAdapter for the selected column. - * - * @param primColumnName the name of the primitive column - * @param tileColumnName the name of the tile_id column - * @return an appropriate TilingAdapter instance or null - */ - public TilingAdapter getTilingAdapter(String tileColumnName, - String primColumnName) { - return getTilingAdapter(whatColumn(tileColumnName), - whatColumn(primColumnName)); - } - - /** - * Returns a TilingAdapter for the selected column. - * - * @param primColumn the position of the primitive column - * @param tileColumn the position of the tile_id column - * @return an appropriate TilingAdapter instance or null - */ - public TilingAdapter getTilingAdapter(int tileColumn, int primColumn) { - DcwColumnInfo tile = (tileColumn != -1) ? columnInfo[tileColumn] : null; - if (primColumn == -1) { - return null; - } - DcwColumnInfo prim = columnInfo[primColumn]; - TilingAdapter retval = null; - char primFieldType = prim.getFieldType(); - if (tile == null) { - if (primFieldType == 'K') { - retval = new TilingAdapter.CrossTileAdapter(primColumn); - } else if ((primFieldType == 'I') || (primFieldType == 'S')) { - retval = new TilingAdapter.UntiledAdapter(primColumn); - } - } else { - if (primFieldType == 'K') { - //error??? duplicate tile data - retval = new TilingAdapter.CrossTileAdapter(primColumn); - } else if ((primFieldType == 'I') || (primFieldType == 'S')) { - retval = new TilingAdapter.TiledAdapter(tileColumn, primColumn); - } - } - return retval; - } - - /** - * Get the column number for a set of column names. - * - * @param names the names of the columns - * @return an array of column numbers - * @exception FormatException the table does not match the - * specified schema - */ - public int[] lookupSchema(String[] names, boolean mustExist) - throws FormatException { - int retval[] = new int[names.length]; - for (int i = 0; i < retval.length; i++) { - retval[i] = whatColumn(names[i]); - if ((retval[i] == -1) && mustExist) { - throw new FormatException("Column " + names[i] - + " doesn't exist"); - } - } - return retval; - } - - /** - * Get the column number for a set of column names. - * - * @param names the names of the columns - * @param type in same order as names - * @param length in same order as names (-1 for a variable length - * column) - * @param strictlength false means that variable length columns - * can be fixed-length instead - * @param mustExist if true and a column doesn't exist, method - * returns null - * @return an array of column numbers - * @exception FormatException the table does not match the - * specified schema - */ - public int[] lookupSchema(String[] names, boolean mustExist, char type[], - int length[], boolean strictlength) - throws FormatException { - int retval[] = lookupSchema(names, mustExist); - if ((type.length == names.length) && (length.length == names.length)) { - for (int i = 0; i < retval.length; i++) { - if (retval[i] != -1) { - columnInfo[retval[i]].assertSchema(type[i], - length[i], - strictlength); - } - } - } - return retval; - } - - /** - * Good for looking at the contents of a data file, this method - * dumps a bunch of rows to System.out. It parses all the lines of - * the file. - * - * @exception FormatException some kind of data format error was - * encountered while parsing the file - */ - public void parseAllRowsAndPrintSome() throws FormatException { - int row_id_column = whatColumn(ID_COLUMN_NAME); - String vectorString = null; - int rowcount = 0; - for (List l = new ArrayList(getColumnCount()); parseRow(l);) { - int cnt = ((Number) (l.get(row_id_column))).intValue(); - if (cnt != ++rowcount) { - System.out.println("Non-consecutive row number. Expected " - + rowcount + " got " + cnt); - } - vectorString = VPFUtil.listToString(l); - if ((rowcount < 20) || (rowcount % 100 == 0)) { - System.out.println(vectorString); - } - } - if (rowcount > 20) - System.out.println(vectorString); - } - - /** - * Good for looking at the contents of a data file, this method - * dumps a bunch of rows to System.out. (Using seekToRow to move - * between records - * - * @exception FormatException some kind of data format error was - * encountered while parsing the file - */ - public void parseSomeRowsAndPrint() throws FormatException { - int row_id_column = whatColumn(ID_COLUMN_NAME); - int rowcount = getRecordCount(); - for (int i = 1; i <= rowcount; i++) { - if ((i > 10) && ((i % 100) != 0) && (i != rowcount)) { - continue; - } - seekToRow(i); - List l = parseRow(); - int cnt = ((Integer) (l.get(row_id_column))).intValue(); - if (cnt != i) { - System.out.println("Possible incorrect seek for row number " - + i + " got " + cnt); - } - System.out.println(VPFUtil.listToString(l)); - } - } - - /** - * Return a row from the table. repeatedly calling parseRow gets - * consecutive rows. - * - * @return a List of fields read from the table - * @exception FormatException an error was encountered reading the - * row - */ - public List parseRow() throws FormatException { - List retval = new ArrayList(getColumnCount()); - return parseRow(retval) ? retval : null; - } - - /** - * Return a row from the table. repeatedly calling parseRow gets - * consecutive rows. - * - * @param retval append the fields from a row in the table. - * clear() is called before any real work is done. - * @return true is we read a row, false if no more rows are - * available - * @exception FormatException an error was encountered reading the - * row - * @see java.util.List#clear() - */ - public synchronized boolean parseRow(List retval) throws FormatException { - retval.clear(); - try { - for (int i = 0; i < columnInfo.length; i++) { - Object newobj = columnInfo[i].parseField(inputFile); - retval.add(newobj); - } - cursorRow++; - return true; - } catch (FormatException f) { - throw new FormatException("DcwRecordFile: parserow on table " - + filename + ": " + f.getMessage()); - } catch (EOFException e) { - if (!retval.isEmpty()) { - throw new FormatException("DcwRecordFile: hit EOF when list = " - + VPFUtil.listToString(retval)); - } - try { - if (inputFile.available() > 0) { - throw new FormatException("DcwRecordFile: hit EOF with available = " - + inputFile.available() - + " when list = " - + VPFUtil.listToString(retval)); - } - } catch (IOException i) { - throw new FormatException("IOException calling available()"); - } - return false; - } - } - - /** - * Returns the documentation file associated with this table. - * - * @return the doc file - may be null - */ - public String getDocumentationFilename() { - return documentationFileName; - } - - /** - * Returns the table description for this table. - * - * @return the table description - may be null - */ - public String getDescription() { - return tableDescription; - } - - /** - * get the length of a single record - * - * @return -1 indicates a variably sized record - */ - public int getRecordLength() { - return recordLength; - } - - /** - * Gets the number of records in the table. - * - * @return the number of records - * @exception FormatException some problem was encountered dealing - * with the file - */ - public int getRecordCount() throws FormatException { - try { - if (recordLength == -1) { - return vli().getRecordCount(); - } else { - return (int) (inputFile.length() - headerLength) / recordLength; - } - } catch (IOException i) { - System.out.println("RecordCount: io exception " + i.getMessage()); - } catch (NullPointerException npe) { - } - return -1; - } - - final private DcwVariableLengthIndexFile vli() throws FormatException, - IOException { - if (vli == null) { - openVLI(); - } - return vli; - } - - /** - * Opens the associated variable length index for the file - * - * @exception FormatException an error. - */ - private void openVLI() throws FormatException, IOException { - String realfname = filename; - boolean endwithdot = realfname.endsWith("."); - String fopen; - if (endwithdot) { - StringBuffer newf = new StringBuffer(realfname.substring(0, - realfname.length() - 2)); - fopen = newf.append("x.").toString(); - } else { - StringBuffer newf = new StringBuffer(realfname.substring(0, - realfname.length() - 1)); - fopen = newf.append("x").toString(); - } - - vli = new DcwVariableLengthIndexFile(new BinaryBufferedFile(fopen), byteorder); - } - - /** - * Parses the row specified by rownumber - * - * @param rownumber the number of the row to return - * [1..recordCount] - * @return the values contained in the row - * @exception FormatException data format errors - */ - public List getRow(int rownumber) throws FormatException { - List l = new ArrayList(getColumnCount()); - return getRow(l, rownumber) ? l : null; - } - - /** - * Parses the row specified by rownumber - * - * @param rownumber the number of the row to return - * [1..recordCount] - * @param retval values contained in the row - * @exception FormatException data format errors - * @see #parseRow() - */ - public synchronized boolean getRow(List retval, int rownumber) - throws FormatException { - if (inputFile == null) { - reopen(rownumber); - } else { - seekToRow(rownumber); - } - return parseRow(retval); - } - - /** - * moves the input cursor to the specified row [affects subsequent - * calls parseRow.] - * - * @param recordNumber the number of the row to seek to - * @exception FormatException data format errors - * @exception IllegalArgumentException recordNumber less than 1 - */ - public synchronized void seekToRow(int recordNumber) throws FormatException { - if (recordNumber <= 0) { - throw new IllegalArgumentException("DcwRecordFile: seekToRow(" - + recordNumber + "," + getRecordCount() + "," + filename - + ")"); - } - if (recordNumber == cursorRow) { - return; - } - cursorRow = recordNumber; - int offset = 0; - try { - if ((recordLength == -1) && (recordNumber != 1)) { - offset = vli().recordOffset(recordNumber); - } else { - offset = (recordLength * (recordNumber - 1)) + headerLength; - } - - inputFile.seek(offset); - } catch (IOException io) { - throw new FormatException("SeekToRow IOException " - + io.getMessage() + " offset: " + offset + " " + tablename - + " " + filename); - } - } - - /** - * Returns the index into columnInfo of the column with the - * specified name - * - * @param columnname the column name to match - * @return an index into columnInfo (-1 indicates no such column) - */ - public int whatColumn(String columnname) { - for (int i = 0; i < columnInfo.length; i++) { - if (columnInfo[i].getColumnName().equals(columnname)) { - return i; - } - } - return -1; - } - - /** - * Returns the name of a column - * - * @param index the column to get the name for - * @return the columnName - */ - public String getColumnName(int index) { - return columnInfo[index].getColumnName(); - } - - /** - * Prints the table information to System.out. - * - * @exception FormatException some problem was encountered dealing - * with the file - */ - public void printSchema() throws FormatException { - System.out.println("File Name: " + filename + "\nTable name: " - + tablename + "\nTable Description: " + tableDescription - + "\nDocumentation File Name: " + documentationFileName - + "\nRecord Length: " + recordLength + " Record Count: " - + getRecordCount()); - for (int i = 0; i < columnInfo.length; i++) { - System.out.println("Column " + i + " " + columnInfo[i].toString()); - } - } - - /** Closes the associated input file. (may later get reopened) */ - public synchronized void close() { - cursorRow = -1; - try { - if (inputFile != null) { - inputFile.close(); - } - inputFile = null; - } catch (IOException i) { - System.out.println("Caught ioexception " + i.getMessage()); - } - } - - /** - * Reopen the associated input file. - * - * @param seekRow the row to seek to upon reopening the file. If - * seekRow is invalid (less than 1), then the input stream - * is in an undefined location, and seekToRow (or - * getRow(int)) must be called before parseRow - * @exception FormatException some error was encountered in - * reopening file or seeking to the desired row. - * @see #parseRow() - * @see #getRow(int) - * @see #close() - */ - public synchronized void reopen(int seekRow) throws FormatException { - try { - if (inputFile == null) { - inputFile = new BinaryBufferedFile(filename); - inputFile.byteOrder(byteorder); - } - if (seekRow > 0) { - seekToRow(seekRow); - } - } catch (IOException i) { - throw new FormatException(i.getClass() + ": " + i.getMessage()); - } - } - - /** - * Returns the number of columns this table has - */ - final public int getColumnCount() { - return columnInfo.length; - } - - /** - * Return the column info for this table. - *

- * NOTE: modifying this array is likely to cause problems... - */ - final public DcwColumnInfo[] getColumnInfo() { - return columnInfo; - } - - /** releases associated resources */ - protected void finalize() { - close(); - } - - /** - * An test main for parsing VPF table files. - * - * @param args file names to be read - */ - public static void main(String args[]) { - for (int i = 0; i < args.length; i++) { - System.out.println(args[i]); - try { - DcwRecordFile foo = new DcwRecordFile(args[i]); - foo.printSchema(); - foo.close(); - foo.reopen(1); - for (List l = new ArrayList(); foo.parseRow(l);) { - System.out.println(VPFUtil.listToString(l)); - } - foo.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwSpatialIndex.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwSpatialIndex.java deleted file mode 100644 index ae9c468bb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwSpatialIndex.java +++ /dev/null @@ -1,279 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwSpatialIndex.java,v $ -// $RCSfile: DcwSpatialIndex.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; -import java.io.IOException; -import java.util.BitSet; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** Read a VPF spatial index file. (VPF *.?si files) */ -public class DcwSpatialIndex { - /** the vpf file with the data */ - private BinaryFile inputFile = null; - /** the number of primitive features that are indexed */ - final private int numberOfPrimitives; - /** the boundaries of the spatial index */ - final private float boundingRectx1, boundingRecty1, boundingRectx2, - boundingRecty2; - /** the number of splits in the spatial index */ - final private int nodesInTree; - /** node info */ - int nodeinfo[][]; - - /** - * Construct an index for a filename. Prints a bunch of - * information about what it read. - */ - public DcwSpatialIndex(String filename, boolean border) - throws FormatException { - try { - inputFile = new BinaryBufferedFile(filename); - } catch (IOException e) { - throw new FormatException("Can't open file " + filename + ": " - + e.getMessage()); - } - inputFile.byteOrder(border); - - try { - numberOfPrimitives = inputFile.readInteger(); - boundingRectx1 = inputFile.readFloat(); - boundingRecty1 = inputFile.readFloat(); - boundingRectx2 = inputFile.readFloat(); - boundingRecty2 = inputFile.readFloat(); - nodesInTree = inputFile.readInteger(); - - if (Debug.debugging("vpfserver")) { - System.out.println("NumberOfPrimitives = " + numberOfPrimitives); - System.out.println("Bounding Rect = (" + boundingRectx1 + ", " - + boundingRecty1 + ") - (" + boundingRectx2 + ", " - + boundingRecty2 + ")"); - System.out.println("Nodes in Tree = " + nodesInTree); - } - - nodeinfo = new int[nodesInTree][2]; //offset, count - - for (int i = 0; i < nodesInTree; i++) { - inputFile.readIntegerArray(nodeinfo[i], 0, 2); - } - - if (Debug.debugging("vpfserver")) { - int baseOffset = 24 + nodesInTree * 8; - BitSet b = new BitSet(nodesInTree); - int actprimcnt = 0; - b.set(0); - for (int i = 0; i < nodesInTree; i++) { - if ((baseOffset + nodeinfo[i][0]) != inputFile.getFilePointer()) { - throw new FormatException("SI Input appears to be out-of-sync"); - } - StringBuffer pr = new StringBuffer("i=").append(i + 1); - pr.append(" offset=").append(nodeinfo[i][0]); - pr.append(" count=").append(nodeinfo[i][1]); - for (int j = 0; j < nodeinfo[i][1]; j++) { - actprimcnt++; - PrimitiveRecord prim = new PrimitiveRecord(inputFile); - pr.append("\n\t").append(prim.toString()); - } - if (nodeinfo[i][1] != 0) { - if ((i < 15) || ((i + 1) == nodesInTree)) { - System.out.println(pr); - } - b.set(i + 1); - if (!b.get((i + 1) / 2)) { - throw new FormatException("condition failed"); - } - } - } - if (actprimcnt == numberOfPrimitives) { - System.out.println("Got the right number of primitives"); - } else { - System.out.println("!!Got the wrong number of primitives"); - } - if (inputFile.available() != 0) { - throw new FormatException("Bytes left at end of file " - + inputFile.available()); - } - } - } catch (EOFException e) { - throw new FormatException("Hit Premature EOF in thematic index"); - } catch (IOException i) { - throw new FormatException("Encountered IO Exception: " - + i.getMessage()); - } - } - - /** - * Returns the number of primitives included in the spatial index - * - * @return the number of primitives included in the spatial index - */ - public int getNumberOfPrimitives() { - return numberOfPrimitives; - } - - /** - * Returns the west boundary - * - * @return the west boundary - */ - public float getBoundingX1() { - return boundingRectx1; - } - - /** - * Returns the east boundary - * - * @return the east boundary - */ - public float getBoundingX2() { - return boundingRectx2; - } - - /** - * Returns the south boundary - * - * @return the south boundary - */ - public float getBoundingY1() { - return boundingRecty1; - } - - /** - * Returns the north boundary - * - * @return the north boundary - */ - public float getBoundingY2() { - return boundingRecty2; - } - - /** - * Returns the number of nodes in the spatial index - * - * @return the number of nodes in the spatial index - */ - public int getNodesInTree() { - return nodesInTree; - } - - /** - * Returns the number of primitives listed in the node - * - * @param node the node index - * @return the number of primitives listed in the node - */ - public int getPrimitiveCount(int node) { - return nodeinfo[node][1]; - } - - /** - * Returns the relative byte offset of the node primitive list - * from the header - * - * @param node the node index - * @return the byte offset of the record in the file - */ - public int getPrimitiveOffset(int node) { - return nodeinfo[node][0]; - } - - /** - * Returns an array of primitive records - * - * @param node the node index - * @exception FormatException an error was encountered reading the - * file - * @return the array of primitive records - */ - public PrimitiveRecord[] getPrimitiveRecords(int node) - throws FormatException { - int count = getPrimitiveCount(node); - int offset = getPrimitiveOffset(node); - PrimitiveRecord[] ret = new PrimitiveRecord[count]; - try { - //offset measures from the end of the header - inputFile.seek(offset + 24 + nodesInTree * 8); - for (int i = 0; i < count; i++) { - ret[i] = new PrimitiveRecord(inputFile); - } - } catch (IOException ioe) { - throw new FormatException("Error reading spatial index file"); - } - return ret; - } - - /** - * A class that wraps an entry in the spatial index. - */ - public static class PrimitiveRecord { - /** see the VPF spec for what these mean */ - final public short x1, y1, x2, y2; - /** the id of the primitive this record is for */ - final public int primId; - - /** - * construct a new primitive record - * - * @param inputFile the file to read the record from - * @exception FormatException an error was encountered reading - * the record - * @exception EOFException an error was encountered reading - * the record - */ - public PrimitiveRecord(BinaryFile inputFile) throws FormatException, - EOFException { - x1 = (short) (inputFile.readChar() & 0xff); - y1 = (short) (inputFile.readChar() & 0xff); - x2 = (short) (inputFile.readChar() & 0xff); - y2 = (short) (inputFile.readChar() & 0xff); - //foo[] = inputFile.readBytes(4, false); //x1 y1 x2 y2 - primId = inputFile.readInteger(); - } - - /** - * Returns a pretty string representation of the record - * - * @return a string version of the record - */ - public String toString() { - return ("(" + primId + ": \t" + x1 + " \t" + x2 + " \t" + y1 - + " \t" + y2 + ")"); - } - } - - /** - * Closes the files associated with the spatial index - */ - public void close() { - try { - inputFile.close(); - } catch (IOException i) { - System.out.println("Caught ioexception " + i.getClass() + " " - + i.getMessage()); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwThematicIndex.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwThematicIndex.java deleted file mode 100644 index 790f45959..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwThematicIndex.java +++ /dev/null @@ -1,471 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwThematicIndex.java,v $ -// $RCSfile: DcwThematicIndex.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 19:29:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.EOFException; -import java.io.IOException; -import java.util.Arrays; -import java.util.BitSet; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** Read a VPF thematic index file. (VPF *.?ti files) */ -public class DcwThematicIndex { - /** the file we read from */ - private BinaryFile inputFile = null; - /** read from file - length of header */ - final private int headerSize; - /** read from file - number of indexes (codes) */ - final private int numberOfCodes; - /** read from file - total number of rows indexed */ - final private int numberOfRows; - /** read from file - type of index */ - final private char typeOfIndex; // T hematic - /** read from file - field type of index */ - final private char fieldTypeOfIndex; - /** read from file - number of elements composing the index value */ - final private int numberOfDataElement; - /** read from file - the type of the index */ - final private char dataTypeSpecifier; - /** read from file - the table indexed */ - final private String tableIndexed; - /** read from file - the column indexed */ - final private String columnIndexed; - /** read from file (vpf 2407 only) - are the codes sorted */ - final private boolean sorted; - /** the list of index records */ - private IndexRecord[] indexData; - /** the name of the file being read */ - // final protected File filename; - final protected String filename; - /** the byte order of the file */ - protected boolean byteOrder; - - /** - * A utility class used to record index records. - */ - public static class IndexRecord - implements Comparable { - /** the index (code) */ - final Object index; - /** the offset of the data */ - final int offset; - /** the number of values - 0 means the offset is the only value */ - final int numvals; - - /** - * Construct an index record - * - * @param index the index object - * @param offset the offset of the data - * @param numvals the number of values - */ - public IndexRecord(Object index, int offset, int numvals) { - this.index = index; - this.offset = offset; - this.numvals = numvals; - } - - @SuppressWarnings("unchecked") - public int compareTo(Object obj) { - Object realobj = (obj instanceof IndexRecord) ? ((IndexRecord) obj).index : obj; - return ((Comparable) index).compareTo(realobj); - } - } - - /** - * Construct an index, assumes this is pre-VPF2407 format. - * - * @param filename the file to oped - * @param border the byteorder - */ - public DcwThematicIndex(String filename, boolean border) - throws FormatException { - this(filename, border, false); - } - - /** - * Construct an index, assumes this is pre-VPF2407 format. - * - * @param filename the file to oped - * @param border the byteorder - * @param vpf2407 true for MILSTD-2407 format thematic index. false will - * properly read a VPF2407 format index, but will ignore one header - * field (sorted). true will improperly read old-style data. - */ - public DcwThematicIndex(String filename, boolean border, boolean vpf2407) - throws FormatException { - - this.filename = filename; - byteOrder = border; - - reopen(0); - - if (Debug.debugging("vpfserver")) { - System.out.println("DTI: opened the file " + filename); - } - - try { - headerSize = inputFile.readInteger(); - numberOfCodes = inputFile.readInteger(); - numberOfRows = inputFile.readInteger(); - typeOfIndex = inputFile.readChar(); - fieldTypeOfIndex = inputFile.readChar(); - numberOfDataElement = inputFile.readInteger(); - dataTypeSpecifier = inputFile.readChar(); - tableIndexed = trim(inputFile.readFixedLengthString(12)).toLowerCase(); - columnIndexed = trim(inputFile.readFixedLengthString(25)).toLowerCase(); - sorted = (inputFile.readChar() == 'S') && vpf2407; - inputFile.seek(60); // skips 3 unused bytes - - indexData = new IndexRecord[numberOfCodes]; - - if (Debug.debugging("vpfserver")) { - System.out.println("HeaderSize = " + headerSize); - System.out.println("Number of Codes = " + numberOfCodes); - System.out.println("Number of Rows = " + numberOfRows); - System.out.println("Type of Index = " + typeOfIndex); - // if (typeOfIndex != 'T') - // System.out.println(" *** Strange - dcw spec says it - // will be T ***"); - System.out.println("Field Type of Index = " + fieldTypeOfIndex); - System.out.println("Number of Data Element = " + numberOfDataElement); - System.out.println("Data Type Specifier = " + dataTypeSpecifier); - System.out.println("Table Indexed = " + tableIndexed); - System.out.println("Column Indexed = " + columnIndexed); - System.out.println("Sorted = " + sorted); - } - - StringBuffer pr = new StringBuffer(); - for (int i = 0; i < numberOfCodes; i++) { - indexData[i] = - new IndexRecord(readIndexField(fieldTypeOfIndex, numberOfDataElement), inputFile.readInteger(), - inputFile.readInteger()); - - if (Debug.debugging("vpfserver")) { - pr = new StringBuffer("i = ").append(i); - pr.append("; val = ").append(indexData[i].index.toString()); - pr.append("; offset = ").append(indexData[i].offset); - pr.append("; number of elts = ").append(indexData[i].numvals); - if (i < 40) { - System.out.println(pr.toString()); - } - } - } - - if (!sorted) { - Arrays.sort(indexData); - } - - if (Debug.debugging("vpfserver") && (numberOfCodes > 40)) { - System.out.println(pr.toString()); - } - - Debug.message("vpfserver", "*** Finished Header Read ***"); - - if (Debug.debugging("vpfserver")) { - if ((typeOfIndex == 'T') || (typeOfIndex == 'I')) { - Debug.output("Normal Inverted Index Format"); - } else if ((typeOfIndex == 'B') || (typeOfIndex == 'G')) { - Debug.output("Scary Bitmap Index Format"); - } else { - throw new FormatException("Unidentified TMI format"); - } - - Object[] indexes = getValueIndexes(); - // We just know that these values are tile IDs. - for (int j = 0; j < indexes.length; j++) { - // int[] row = get(indexes[j]); - // If you want to do some scary printout, code it - // up here. - } - } - close(); - } catch (EOFException e) { - throw new FormatException("Hit Premature EOF in thematic index"); - } catch (IOException i) { - throw new FormatException("Encountered IO Exception: " + i.getMessage()); - } - } - - /** - * Returns the set of values indexed by this thematic index. - * - * @return the set of values indexed - */ - public Object[] getValueIndexes() { - Object[] values = null; - - if (indexData != null) { - values = new Object[indexData.length]; - - for (int i = 0; i < indexData.length; i++) { - values[i] = indexData[i].index; - } - } - return values; - } - - /** - * Returns the list of rows listed for this index - * - * @return an array of rows - * @param valueIndex the value to look up - */ - public synchronized int[] get(Object valueIndex) - throws FormatException { - int[] values = null; - - try { - int index = Arrays.binarySearch(indexData, valueIndex); - if (index >= 0) { - IndexRecord ir = indexData[index]; - int offset = ir.offset; - int numvals = ir.numvals; - - if ((typeOfIndex == 'T') || (typeOfIndex == 'I')) { - if (numvals == 0) { - values = new int[1]; - values[0] = offset; - } else { - values = new int[numvals]; - reopen(offset); - - for (int j = 0; j < numvals; j++) { - values[j] = readIndexWithFieldType(dataTypeSpecifier); - } - } - - return values; - - } else if ((typeOfIndex == 'B') || (typeOfIndex == 'G')) { - // Don't really do anything with this type of - // index... - - int shortread = numberOfRows / 16; - if ((numberOfRows % 16) != 0) { - shortread++; - } - if (Debug.debugging("vpfserver")) { - System.out.println("Reading a bunch of shorts: " + shortread); - System.out.println("Starting at offset: " + inputFile.getFilePointer()); - } - - BitSet bits = new BitSet(numberOfRows); - int cnt = 0; - for (int shortcnt = 0; shortcnt < shortread; shortcnt++) { - short s = inputFile.readShort(); - - for (int k = 0; k < 16; k++) { - cnt++; - if ((s & 0x1) == 1) { - bits.set(cnt); - } - s >>= 1; - } - } - StringBuffer prt = new StringBuffer(); - for (int j = 1; j <= bits.size(); j++) { - if (bits.get(j)) { - prt.append(", ").append(j); - } - } - System.out.println(prt); - - } else { - throw new FormatException("Unidentified TMI format"); - } - } - } catch (EOFException e) { - throw new FormatException("Hit Premature EOF in thematic index"); - } catch (IOException i) { - throw new FormatException("Encountered IO Exception: " + i.getMessage()); - } - - return values; - } - - /** - * Utility method to read rows. - * - * @param ft the field type - * @returns the value read from the file - */ - private int readIndexWithFieldType(char ft) - throws EOFException, FormatException { - switch (ft) { - case 'S': - return (int) inputFile.readShort(); - case 'I': - return inputFile.readInteger(); - } - throw new FormatException("Unrecognized FieldTypeOfIndex"); - } - - private Object readIndexField(char dts, int textlen) - throws EOFException, FormatException { - switch (dts) { - case 'I': - return new Integer(inputFile.readInteger()); - case 'T': - return inputFile.readFixedLengthString(textlen); - case 'S': - return new Short(inputFile.readShort()); - case 'F': - return new Float(inputFile.readFloat()); - case 'R': - return new Double(inputFile.readDouble()); - } - throw new FormatException("Unrecognized field index type"); - } - - private String trim(String s) { - StringBuffer ns = new StringBuffer(); - char foo[] = s.toCharArray(); - for (int i = 0; i < foo.length; i++) { - if ((foo[i] == ' ') || (foo[i] == 0)) { - break; - } - ns.append(foo[i]); - } - return ns.toString(); - } - - /** - * Returns the number of distinct indexed values - * - * @return the number of distinct indexed values - */ - public int getNumberOfCodes() { - return numberOfCodes; - } - - /** - * Returns the number of rows indexed - * - * @return the number of rows indexed - */ - public int getNumberOfRows() { - return numberOfRows; - } - - /** - * Returns the type of index (refer to VPF spec for valid values) - * - * @return the type of index (refer to VPF spec for valid values) - */ - public char getTypeOfIndex() { - return typeOfIndex; - } - - /** - * Returns the type of the field being indexed - * - * @return the type of the field being indexed - */ - public char getFieldTypeOfIndex() { - return fieldTypeOfIndex; - } - - /** - * Returns the number of elements in the index field - * - * @return the number of elements in the index field - */ - public int getNumberOfDataElements() { - return numberOfDataElement; - } - - /** - * Returns the datatype specifier - * - * @return the datatype specifier - */ - public char getDataTypeSpecifier() { - return dataTypeSpecifier; - } - - /** - * Returns the name of the table being indexed - * - * @return the name of the table being indexed - */ - public String getTableIndexed() { - return tableIndexed; - } - - /** - * Returns the name of the column being indexed - * - * @return the name of the column being indexed - */ - public String getColumnIndexed() { - return columnIndexed; - } - - public boolean getSorted() { - return sorted; - } - - /** Closes the associated input file. (may later get reopened) */ - public synchronized void close() - throws FormatException { - try { - if (inputFile != null) { - inputFile.close(); - } - inputFile = null; - } catch (IOException i) { - throw new FormatException("DcwThematicIndex: Can't close file " + filename + ": " + i.getMessage()); - } - } - - /** - * Reopen the associated input file. - * - * @param offset the byte offset to seek to upon reopening the file. If - * offset is invalid (less than 1), then the input stream is in an - * undefined location. - * @exception FormatException some error was encountered in reopening file or - * seeking to the desired row. - * @see #close() - */ - public synchronized void reopen(int offset) - throws FormatException { - try { - if (inputFile == null) { - inputFile = new BinaryBufferedFile(filename); - inputFile.byteOrder(byteOrder); - } - if (offset > 0) { - inputFile.seek(offset); - } - } catch (IOException i) { - throw new FormatException("DcwThematicIndex: Can't open file " + filename + ": " + i.getMessage()); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwVariableLengthIndexFile.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwVariableLengthIndexFile.java deleted file mode 100644 index 9eb4a7d74..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DcwVariableLengthIndexFile.java +++ /dev/null @@ -1,118 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DcwVariableLengthIndexFile.java,v $ -// $RCSfile: DcwVariableLengthIndexFile.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 19:29:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.IOException; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Read in a VPF variable length index file, and allows access to - * individual records. - */ -public class DcwVariableLengthIndexFile { - /** holds all the offset,size pairs */ - final private int offsettable[]; - /** the number of records */ - final private int recordCount; - /** the end of the file offset */ - final private int endOfFileOffset; - - /** - * Construct a new index file. - * - * @param filename the name of the file to read in. - * @param msbfirst the byte order of the file to be read. - * @exception FormatException some error was encountered in trying - * to read the file. - */ - public DcwVariableLengthIndexFile(String filename, boolean msbfirst) - throws FormatException, IOException { - this(new BinaryBufferedFile(filename), msbfirst); - } - - /** - * Construct a new index file. - * - * @param inputstream BinaryBufferedFile handle. - * @param msbfirst the byte order of the file to be read. - * @exception FormatException some error was encountered in trying - * to read the file. - */ - public DcwVariableLengthIndexFile(BinaryFile inputstream, boolean msbfirst) - throws FormatException { - - try { - inputstream.byteOrder(msbfirst); - - recordCount = inputstream.readInteger(); - /*int HeaderLength = */inputstream.readInteger(); - offsettable = new int[recordCount * 2]; - inputstream.readIntegerArray(offsettable, 0, recordCount * 2); - endOfFileOffset = offsettable[offsettable.length - 2] - + offsettable[offsettable.length - 1]; - inputstream.close(); - // com.bbn.openmap.util.Debug.output("VLI.init(): number - // of entries(" + recordCount + - // ") HeaderLength(" + HeaderLength + ")"); - - } catch (IOException i) { - throw new FormatException("IOException with " - + inputstream.getName() + ": " + i.getMessage()); - } - } - - /** - * get the offset byte offset of the record in the associated - * table file. If recordNumber is greater than the number of - * records, this returns the offset of the end-of-file. - * - * @param recordNumber the record to retrieve the offset for - */ - public int recordOffset(int recordNumber) { - return (recordCount < recordNumber) ? endOfFileOffset - : offsettable[(recordNumber - 1) * 2]; - } - - /** - * get the size of the record in the associated table file If - * recordNumber is greater than the number of records, this - * returns a record size of 0. - * - * @param recordNumber the record to retrieve the offset for - */ - public int recordSize(int recordNumber) { - return (recordCount < recordNumber) ? 0 - : offsettable[(recordNumber - 1) * 2 + 1]; - } - - /** get the number of records in the index file */ - public int getRecordCount() { - return recordCount; - } - - /** close the associated input file */ - public void close() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DescribeDB.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/DescribeDB.java deleted file mode 100644 index 7de3a3cc6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/DescribeDB.java +++ /dev/null @@ -1,190 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/DescribeDB.java,v $ -// $RCSfile: DescribeDB.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/12/08 01:04:24 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.Hashtable; -import java.util.List; - -import com.bbn.openmap.io.FormatException; - -/** - * This class will print out some basic information about a VPF - * database. - * - *
- * 
- *  Usage:
- *  java com.bbn.openmap.layer.vpf.DescribeDB /path/to/vpf/database
- *  
- * 
- * - * It will then print out a description of the coverages for the - * database to the command line. (no GUI) - */ - -public class DescribeDB { - /** - * Prints a newline to System.out - */ - public static void println() { - System.out.println(); - } - - /** - * Prints a string to System.out with a newline - * - * @param s the string to print - */ - public static void println(String s) { - System.out.println(s); - } - - /** - * Prints two strings to System.out with a newline - * - * @param s1 the string to print - * @param s2 the string to print - */ - public static void println(String s1, String s2) { - println(s1 + s2); - } - - /** - * Prints two strings to System.out without a newline - * - * @param s1 the string to print - * @param s2 the string to print - */ - public static void print(String s1, String s2) { - print(s1); - print(s2); - } - - /** - * Prints a string to System.out without a newline - * - * @param s the string to print - */ - public static void print(String s) { - System.out.print(s); - } - - /** - * The main program. Takes path arguments, and prints the DB it - * finds - * - * @param args the paths to print - */ - public static void main(String[] args) throws FormatException { - for (int argsi = 0; argsi < args.length; argsi++) { - String rootpath = args[argsi]; - LibrarySelectionTable lst = new LibrarySelectionTable(rootpath); - println("Path to database: " + rootpath); - println("Database Name: " + lst.getDatabaseName()); - println("Database Description: " + lst.getDatabaseDescription()); - List libraries = lst.getLibraryNames(); - print("Database Libraries: "); - for (String libraryName : libraries) { - print(libraryName, " "); - } - println(); - println(); - for (String libraryName : libraries) { - String prefix = libraryName + ":"; - printLibrary(prefix, lst.getCAT(libraryName)); - println(); - } - } - } - - /** - * Prints a VPF Library - * - * @param prefix lines get printed with this prefix - * @param cat the CoverageAttributeTable (Library) to print - */ - public static void printLibrary(String prefix, CoverageAttributeTable cat) { - if (cat == null) { - println(prefix, "Library doesn't exist"); - return; - } - println(prefix); - String[] coverages = cat.getCoverageNames(); - println(prefix, "uses " + (cat.isTiledData() ? "tiled" : "untiled") - + " data"); - print(prefix, "Coverage names:"); - for (int i = 0; i < coverages.length; i++) { - print(coverages[i]); - print(" "); - } - println(); - for (int i = 0; i < coverages.length; i++) { - printCoverage(prefix + coverages[i] + ":", cat, coverages[i]); - } - } - - /** - * Prints a VPF Coverage - * - * @param prefix lines get printed with this prefix - * @param covname the name of the coverage to print - * @param cat the CoverageAttributeTable to get the Coverage from - */ - public static void printCoverage(String prefix, CoverageAttributeTable cat, - String covname) { - println(prefix, "Coverage Description: " - + cat.getCoverageDescription(covname)); - println(prefix, "Coverage Topology Level: " - + cat.getCoverageTopologyLevel(covname)); - CoverageTable ct = cat.getCoverageTable(covname); - print(prefix, "FeatureClassNames: "); - println(); - Hashtable info = ct.getFeatureTypeInfo(); - for (CoverageTable.FeatureClassRec fcr : info.values()) { - - String tstring = "[unknown] "; - if (fcr.type == CoverageTable.TEXT_FEATURETYPE) { - tstring = "[text feature] "; - } else if (fcr.type == CoverageTable.EDGE_FEATURETYPE) { - tstring = "[edge feature] "; - } else if (fcr.type == CoverageTable.AREA_FEATURETYPE) { - tstring = "[area feature] "; - } else if (fcr.type == CoverageTable.UPOINT_FEATURETYPE) { - FeatureClassInfo fci = ct.getFeatureClassInfo(fcr.feature_class); - if (fci == null) { - tstring = "[point feature] "; - } else if (fci.getFeatureType() == CoverageTable.EPOINT_FEATURETYPE) { - tstring = "[entity point feature] "; - } else if (fci.getFeatureType() == CoverageTable.CPOINT_FEATURETYPE) { - tstring = "[connected point feature] "; - } else { - tstring = "[point feature] "; - } - } else if (fcr.type == CoverageTable.COMPLEX_FEATURETYPE) { - tstring = "[complex feature] "; - } - println(prefix, fcr.feature_class + ": " + tstring - + fcr.description); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/EdgeTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/EdgeTable.java deleted file mode 100644 index f91179a8f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/EdgeTable.java +++ /dev/null @@ -1,199 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/EdgeTable.java,v $ -// $Revision: 1.7 $ $Date: 2005/12/09 21:08:57 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Read VPF format edge tables to generate polyline graphics for OpenMap. - */ -public class EdgeTable extends PrimitiveTable { - - /** The set of columns that we need */ - private static final String[] edgcolumns = { Constants.ID, Constants.EDG_START_NODE, - Constants.EDG_END_NODE, Constants.EDG_RIGHT_FACE, Constants.EDG_LEFT_FACE, - Constants.EDG_RIGHT_EDGE, Constants.EDG_LEFT_EDGE, Constants.EDG_COORDINATES }; - - /** - * Construct an EdgeTable object for a tile of a coverage. - * - * @param cov the coverage table that this tile is part of - * @param tile the tile to parse - * @throws FormatException a problem was encountered initializing this tile - */ - public EdgeTable(CoverageTable cov, TileDirectory tile) throws FormatException { - - super(cov, tile, "edg"); - if (Debug.debugging("vpf")) { - Debug.output("EdgeTable(): " + filename); - } - if (cov.cachedLineSchema == null) { - cov.cachedLineSchema = lookupSchema(edgcolumns, false); - } - } - - /** - * Get the value of the ID column - * - * @param l the list to retrieve the value from - */ - public final int getID(List l) { - return l.get(covtable.cachedLineSchema[0]).intValue(); - } - - /** - * Get the value of the start_node column - * - * @param l the list to retrieve the value from - */ - public final int getStartNode(List l) { - return ((Number) l.get(covtable.cachedLineSchema[1])).intValue(); - } - - /** - * Get the value of the end_node column - * - * @param l the list to retrieve the value from - */ - public final int getEndNode(List l) { - return ((Number) l.get(covtable.cachedLineSchema[2])).intValue(); - } - - /** - * Get the TilingAdapter for the right_face column - */ - public final TilingAdapter getRightFaceTilingAdapter() { - return getTilingAdapter(Constants.EDG_RIGHT_FACE); - } - - /** - * Get the TilingAdapter for the left_face column - */ - public final TilingAdapter getLeftFaceTilingAdapter() { - return getTilingAdapter(Constants.EDG_LEFT_FACE); - } - - /** - * Get the TilingAdapter for the right_edge column - */ - public final TilingAdapter getRightEdgeTilingAdapter() { - return getTilingAdapter(Constants.EDG_RIGHT_EDGE); - } - - /** - * Get the TilingAdapter for the left_edge column - */ - public final TilingAdapter getLeftEdgeTilingAdapter() { - return getTilingAdapter(Constants.EDG_LEFT_EDGE); - } - - /** - * Get the value of the coordinates column - * - * @param l the list to retrieve the value from - */ - public final CoordFloatString getCoordinates(List l) { - return (CoordFloatString) l.get(covtable.cachedLineSchema[7]); - } - - /** - * get the topology level of the edge table - * - * @return the vpf topology level - */ - public int topologyLevel() { - if (covtable.cachedLineSchema[1] == -1) {// no start_node, - // topology level 0 - return 0; - } - if (covtable.cachedLineSchema[3] == -1) {// no right_face, - // level 1 or 2 - return 2; - } - return 3; - } - - /** - * get the coverage table that this edge is in - */ - public CoverageTable getCoverageTable() { - return covtable; - } - - /** - * Parse the edge records for this tile, calling warehouse.createEdge once - * for each record. - * - * @param warehouse the warehouse used for createEdge calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @see VPFGraphicWarehouse#createEdge - */ - public void drawTile(VPFGraphicWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2) { - - if (warehouse == null) { - return; - } - - try { - seekToRow(1); - for (List edge = new ArrayList(); parseRow(edge);) { - warehouse.createEdge(covtable, this, edge, ll1, ll2, dpplat, dpplon, getCoordinates(edge)); - } - } catch (FormatException f) { - System.out.println("Exception: " + f.getClass() + " " + f.getMessage()); - } - } - - /** - * Use the warehouse to create a graphic from the edge feature, if you - * already have the line from the edgetable. - * - * @param warehouse the warehouse used for createEdge calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param edge list containing the EdgeTable row contents. - * @param featureType the name of the feature. The warehouse may want to do - * some intelligent rendering. - * @param primID the primitive ID of the feature, in order to gather attributes if - * necessary. - * @see VPFGraphicWarehouse#createEdge - */ - public OMGraphic drawFeature(VPFFeatureWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2, List edge, - String featureType, int primID) { - if (warehouse != null) { - return warehouse.createEdge(covtable, this, edge, ll1, ll2, dpplat, dpplon, getCoordinates(edge), featureType, primID); - } - return null; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureCacheGraphicList.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureCacheGraphicList.java deleted file mode 100644 index 6d30fd98e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureCacheGraphicList.java +++ /dev/null @@ -1,229 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/FeatureCacheGraphicList.java,v $ -// $RCSfile: FeatureCacheGraphicList.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 19:29:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Paint; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * The FeatureCacheGraphicList is an extended OMGraphicList that knows what - * types of VPF features it holds. This allows it to be able to use a - * VPFFeatureGraphicWarehouse to set the proper DrawingAttributes on its - * contents. - */ -public abstract class FeatureCacheGraphicList - extends OMGraphicList - implements Cloneable { - - private static final long serialVersionUID = 1L; - /** - * The identifying code for the features held in this list. - */ - protected String featureName = null; - - public FeatureCacheGraphicList() { - } - - public FeatureCacheGraphicList(int initSize) { - super(initSize); - } - - public void setFeatureName(String name) { - featureName = name; - } - - public String getFeatureName() { - return featureName; - } - - public synchronized void setTo(DrawingAttributes da) { - if (da != null) { - for (OMGraphic omg : this) { - da.setTo(omg); - } - } - } - - /** - * A factory method for creating the proper FeatureCacheGraphicList for a - * particular feature type, VPFUtil.Edge, VPFUtil.Area, VPFUtil.Text, and/or - * VPFUtil.Point, with each list subclass tuned to help properly color - * features when they are set based on layer requirements. If featureType is - * null or isn't one of the types listed above, the DEFAULT version will be - * returned. - */ - public static FeatureCacheGraphicList createForType(String featureType) { - - if (featureType != null) { - - int lastCharIndex = featureType.length() - 1; - if (lastCharIndex >= 0) { - // char lastLetter = featureType.charAt(lastCharIndex); - - if (VPFUtil.Edge.equals(featureType)) { - return new FeatureCacheGraphicList.EDGE(); - } - - if (VPFUtil.Area.equals(featureType)) { - return new FeatureCacheGraphicList.AREA(); - } - - if (VPFUtil.Text.equals(featureType)) { - return new FeatureCacheGraphicList.TEXT(); - } - - if (VPFUtil.EPoint.equals(featureType) || VPFUtil.CPoint.equals(featureType)) { - return new FeatureCacheGraphicList.POINT(); - } - } - } - - return new FeatureCacheGraphicList.DEFAULT(); - } - - /** - * @return a duplicate list full of shallow copies of each of the OMGraphics - * contained on the list. - */ - public synchronized Object clone() { - try { - FeatureCacheGraphicList omgl = getClass().newInstance(); - omgl.setFeatureName(getFeatureName()); - - for (OMGraphic omg : this) { - if (omg instanceof OMGraphicList) { - omgl.add((OMGraphic) ((OMGraphicList) omg).clone()); - } else { - omgl.graphics.add(omg); - } - } - - return omgl; - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return new DEFAULT(); - } - - /** - * Different implementations depending on type. - */ - public abstract void setDrawingAttributes(VPFFeatureGraphicWarehouse vfgw); - - public static class AREA - extends FeatureCacheGraphicList { - - private static final long serialVersionUID = 1L; - - public AREA() { - super(); - } - - public AREA(int size) { - super(size); - } - - public synchronized void setDrawingAttributes(VPFFeatureGraphicWarehouse vfgw) { - DrawingAttributes da = vfgw.getAttributesForFeature(featureName); - Paint fillPaint = da.getFillPaint(); - da.setLinePaint(fillPaint); - da.setSelectPaint(fillPaint); - setTo(da); - } - } - - public static class EDGE - extends FeatureCacheGraphicList { - - private static final long serialVersionUID = 1L; - - public EDGE() { - super(); - } - - public EDGE(int size) { - super(size); - } - - public synchronized void setDrawingAttributes(VPFFeatureGraphicWarehouse vfgw) { - DrawingAttributes da = vfgw.getAttributesForFeature(featureName); - da.setFillPaint(OMColor.clear); - setTo(da); - } - } - - public static class DEFAULT - extends FeatureCacheGraphicList { - - private static final long serialVersionUID = 1L; - - public DEFAULT() { - super(); - } - - public DEFAULT(int size) { - super(size); - } - - public synchronized void setDrawingAttributes(VPFFeatureGraphicWarehouse vfgw) { - setTo(vfgw.getAttributesForFeature(featureName)); - } - } - - public static class TEXT - extends DEFAULT { - - private static final long serialVersionUID = 1L; - - public TEXT() { - super(); - } - - public TEXT(int size) { - super(size); - } - } - - public static class POINT - extends DEFAULT { - - private static final long serialVersionUID = 1L; - - public POINT() { - super(); - } - - public POINT(int size) { - super(size); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureClassInfo.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureClassInfo.java deleted file mode 100644 index 93ec4e991..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureClassInfo.java +++ /dev/null @@ -1,488 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/FeatureClassInfo.java,v $ -// $RCSfile: FeatureClassInfo.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/06/20 20:14:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * This class wraps a feature type file (potext.tft, polbndl.lft, etc) from VPF. - * It maintains sufficient information about the table it is indexed from so - * that it can take a List of values, rather than a single value. It also knows - * about its containing CoverageTable so it can look up information in int.vdt - * and char.vdt. - */ -public class FeatureClassInfo extends DcwRecordFile implements TerminatingRunnable, - com.bbn.openmap.io.Closable { - - /** the table to look up .vdt info from */ - final private CoverageTable ctable; - /** - * The name of our column from the primitive table (e.g. potext.tft_id). - * This is the name of the column that will let you know, in the primitive - * file (like edg), what type of primitive (featurewise) is being - * represented on that row. This field does not always exist! If it doesn't, - * all the features in the file are rendered. - */ - final private String columnname; - - /** the column number in the primitive table for columnname */ - private int mycolumn = -1; - /** true means the object has run(), false otherwise */ - private boolean fullInit = false; - - /** things constructed with deferred initialization get queued here */ - // private static RunQueue tq = new RunQueue(true, Thread.MIN_PRIORITY, - // true); - - /** temporary list for use in getDescription() */ - final private List tmpVec = new ArrayList(); - - // Feature Classes cross reference each other. For any feature - // class name, you can have: - // - // 1) a DcwRecordFile (EdgeTable, NodeTable, AreaTable, - // TextTable), with a certain column used as an ID, reference a - // FeatureTable with a column that uses that ID. - // - // 2) a FeatureTable (.pft, .aft, .lft, .tft) using a column - // holding an ID, referencing a DcwRecordFile with a column - // holding that ID. - // - // The FeatureTable shows, for a particular feature type, the - // individual primitive features for that particular feature type, - // their FACC code, what tile that feature resides in, and the - // feature ID number in that tile. - // - // The DcwRecordFile contains the actual data for the primitive, - // and each DceRecordFile contains like feature primitives (edges, - // areas, text, points). Each line in the DcwRecordFile contains - // the ID number of the primitive, - - /** - * Construct a FeatureClassInfo. - * - * @param cthis the CoverageTable to use for vdt lookups - * @param colname the column name from the primitive table - * @param tablepath the directory of the feature table - * @param ftname the name of the feature type - * @exception FormatException some error was encountered - */ - public FeatureClassInfo(CoverageTable cthis, String colname, String tablepath, String ftname) - throws FormatException { - super(tablepath + ftname, true); // defer initialization - - if (Debug.debugging("vpf.fci")) { - Debug.output("FCI: set to peruse (" + filename + ")\n\tcreated with colname (" - + colname + ")\n\ttablepath (" + tablepath + ")\n\tftname (" + ftname + ")"); - } - - ctable = cthis; - columnname = colname.toLowerCase().intern(); - } - - /** the name of the primitive file: edg, fac, end, cnd */ - protected String tileFileName; - /** the name of the column with the primitive id */ - protected String tileFileColName; - /** the type of feature this table represents */ - protected char featureType; - - /** - * Construct a FeatureClassInfo that can be used for feature search - * - * @param cthis the CoverageTable to use for vdt lookups - * @param colname the column name from the primitive table - * @param tablepath the directory of the feature table - * @param ftname the name of the feature type - * @param tileDirFile the name of the primitive file - * @param tileDirFileColName the name of the primitive id column - * @exception FormatException some error was encountered - */ - public FeatureClassInfo(CoverageTable cthis, String colname, String tablepath, String ftname, - String tileDirFile, String tileDirFileColName) throws FormatException { - - super(tablepath + ftname, false); // don't defer - // initialization - fullInit = true; - - ctable = cthis; - columnname = colname.toLowerCase().intern(); - - tileFileName = tileDirFile; - tileFileColName = tileDirFileColName; - - if ("fac".equals(tileFileName)) { - featureType = CoverageTable.AREA_FEATURETYPE; - } else if ("end".equals(tileFileName)) { - featureType = CoverageTable.EPOINT_FEATURETYPE; - } else if ("cnd".equals(tileFileName)) { - featureType = CoverageTable.CPOINT_FEATURETYPE; - } else if ("txt".equals(tileFileName)) { - featureType = CoverageTable.TEXT_FEATURETYPE; - } else if ("edg".equals(tileFileName)) { - featureType = CoverageTable.EDGE_FEATURETYPE; - } else { - featureType = CoverageTable.SKIP_FEATURETYPE; - } - - if (Debug.debugging("vpf.fci")) { - Debug.output("FCI: set to peruse (" + filename + ")\n\tcreated with column name (" - + colname + ")\n\ttile directory file (" + tileDirFile - + ")\n\ttile id column (" + tileDirFileColName + ")"); - } - } - - /** - * Returns a TilingAdapter suitable for retrieving primitive ids from - * records in this feature table. - * - * @return a tilingadapter or null - */ - public TilingAdapter getTilingAdapter() { - return getTilingAdapter(TILE_ID_COLUMN_NAME, tileFileColName); - } - - /** the name of the column where tiling information lives */ - public final static String TILE_ID_COLUMN_NAME = "tile_id"; - - /** - * Returns the file name (no path info) of the thematic index for the - * tile_id column. - */ - public String getTileThematicFileName() { - if (columnInfo != null) { - int colId = getTileIdIndex(); - if (colId != -1) { - return columnInfo[colId].getThematicIndexName(); - } - } - return null; - } - - /** the thematic index for the tile_id column */ - protected DcwThematicIndex thematicIndex = null; - - /** - * Causes the thematic index for the tile_id column to be initialized. - * - * @param path the path to the directory where the index lives - * @return true if a thematic index is available, false if not - */ - public synchronized boolean initThematicIndex(String path) { - try { - if (thematicIndex == null) { - // See if we can use the thematic index to see which - // tiles - // have the features we want. - String thematicIndexName = getTileThematicFileName(); - if (thematicIndexName != null) { - thematicIndex = new DcwThematicIndex(path + thematicIndexName, byteorder); - } - } - } catch (FormatException fe) { - if (Debug.debugging("vpf.FormatException")) { - Debug.output("FeatureClassInfo.initTI: " + fe.getClass() + " " + fe.getMessage()); - } - return false; - } - return (thematicIndex != null); - } - - /** - * Returns the thematic index for the tile_id column, if it has been - * initialized. - * - * @return null or a themaitc index for the column - */ - public DcwThematicIndex getThematicIndex() { - return thematicIndex; - } - - /** - * Returns the column position of the tile_id column. - * - * @see DcwRecordFile#whatColumn(String) - */ - public int getTileIdIndex() { - return whatColumn(TILE_ID_COLUMN_NAME); - } - - /** - * Returns the column position of the f_code column. - * - * @see DcwRecordFile#whatColumn(String) - */ - public int getFaccIndex() { - return whatColumn("f_code"); - } - - /** - * Returns the column position of the primitive id column. - * - * @see DcwRecordFile#whatColumn(String) - */ - public int getTilePrimitiveIdColIndex() { - return whatColumn(tileFileColName); - } - - /** - * Return the type of feature this table is for. Returns one of the - * featuretype codes in CoverageTable. - * - * @see CoverageTable#AREA_FEATURETYPE - */ - public char getFeatureType() { - return featureType; - } - - /** - * Complete the initialization of the FeatureClassInfo. This function can be - * called more than once. - */ - public synchronized void run() { - if (fullInit == true) {// run already ran, or the file didn't - // exist - return; - } - - try { - fullInit = true; - finishInitialization(); // finish initialization of table - - // The list isn't be closed as it's supposed to, and this - // is causing a leak. We'll just avoid the list for now - // and just close the files after we've read them. - - // BinaryFile.addClosable(this); - } catch (FormatException f) { - // close(); //invalidate some stuff - } - close(); - } - - /** - * Implement the Closable interface - */ - public boolean close(boolean done) { - close(); - if (thematicIndex != null) { - try { - thematicIndex.close(); - } catch (FormatException fe) { - // ignored - } - } - return true; - } - - /** - * Probe the DcwRecordFile looking for what column we are in. (Info needed - * later to getDescription with the data list.) - * - * @param rf the primitive data table we'll get rows from - */ - public void findYourself(DcwRecordFile rf) { - mycolumn = rf.whatColumn(columnname); - } - - /** - * Given a row from the primitive table, this function returns a full string - * description of the row - * - * @param l the record list from the primitive table - * @param type the first integral type - * @return the description string for the list - */ - public synchronized String getDescription(List l, MutableInt type) { - checkInit(); - if (mycolumn == -1) { - return null; - } - int i = VPFUtil.objectToInt(l.get(mycolumn)); - if (i <= 0) { - return null; - } - return getDescription(i, type); - } - - /** - * Given a row from the primitive table, this function returns a full string - * description of the row - * - * @param ftid the record list from the primitive table - * @param colIndex column index for attribute to return - * @param type the first integral type - * @return the description string for the list - */ - // public synchronized String getAttribute(List l, int colIndex, - public synchronized String getAttribute(int ftid, int colIndex, MutableInt type) { - checkInit(); - // if (mycolumn == -1) { - // return null; - // } - // int ftid = VPFUtil.objectToInt(l.get(mycolumn)); - if (ftid <= 0) { - return null; - } - - try { - if (!getRow(tmpVec, ftid)) { - return null; - } - } catch (FormatException fe) { - if (Debug.debugging("vpf")) { - fe.printStackTrace(); - } - } - - return getAttribute(columnInfo[colIndex], tmpVec.get(colIndex), type); - } - - /** - * Check to see if the file has been fully initialized, call run() to do - * that if needed. - */ - public synchronized void checkInit() { - if (fullInit == false) { - if (Debug.debugging("vpf")) { - Debug.output("FCI.checkInit() forcing init " + columnname + " " + tablename); - } - run(); - } - } - - /** - * Given an primary key (row id) for the feature table, return the string - * description. If made public, this function would need to be synchronized - * and check for proper initialization. But since it is always called from a - * method that does that, its okay. - * - * @param ftid the row id for our feature table - * @param type the first integral type - * @return the description string for the list - */ - private synchronized String getDescription(int ftid, MutableInt type) { - StringBuffer retval = null; - try { - if (!getRow(tmpVec, ftid)) { - return null; - } - - // boolean haveivdtindex = false; - - for (int i = 0; i < columnInfo.length; i++) { - DcwColumnInfo dci = columnInfo[i]; - - String s = getAttribute(dci, tmpVec.get(i), type); - // //////// - // String s = null; - // String dciVDT = dci.getVDT(); - // if (dciVDT == Constants.intVDTTableName) { - // int val = VPFUtil.objectToInt(tmpVec.get(i)); - // if (val == Integer.MIN_VALUE) {//VPF null - // continue; - // } - // if (!haveivdtindex) { - // type.value = (short) val; - // haveivdtindex = true; - // } - // s = ctable.getDescription(tablename, - // dci.getColumnName(), - // val); - // if (s == null) { - // s = "[" + val + "]"; - // } - // } else if (dciVDT == Constants.charVDTTableName) { - // String val = (String) tmpVec.get(i); - // s = ctable.getDescription(tablename, - // dci.getColumnName(), - // val); - // if (s == null) { - // s = "[" + val + "]"; - // } - // } else if (dci.isNonKey()) { - // s = tmpVec.get(i).toString(); - // } - // ////// - - if (s != null) { - if (retval == null) { - retval = new StringBuffer(s); - } else { - retval.append("; ").append(s); - } - } - } - } catch (FormatException e) { - if (Debug.debugging("vpf")) { - e.printStackTrace(); - } - } - return ((retval == null) ? null : retval.toString()); - } - - protected String getAttribute(DcwColumnInfo dci, Object colObj, MutableInt type) { - - if (colObj == null) { - return null; - } - - String dciVDT = dci.getVDT(); - if (Constants.intVDTTableName.equals(dciVDT)) { - int val = VPFUtil.objectToInt(colObj); - if (val == Integer.MIN_VALUE) {// VPF null - return null; - } - - if (type != null) { - type.value = (short) val; - } - - return ctable.getDescription(tablename, dci.getColumnName(), val); - - } else if (Constants.charVDTTableName.equals(dciVDT)) { - return (String) colObj; - // } else if (dci.isNonKey()) { - // s = colObj.toString(); - } - - return colObj.toString(); - } - - /** - * @return space separated list of column names, used mostly for debugging - * feature attribute lookups. - */ - public String columnNameString() { - StringBuffer sBuf = new StringBuffer(); - for (DcwColumnInfo dci : getColumnInfo()) { - sBuf.append(dci.getColumnName()).append(' '); - } - return sBuf.toString().trim(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureDrawingAttributes.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureDrawingAttributes.java deleted file mode 100644 index b85e9851d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/FeatureDrawingAttributes.java +++ /dev/null @@ -1,452 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: FeatureDrawingAttributes.java,v $ -//$Revision: 1.5 $ -//$Date: 2006/03/06 16:13:59 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.BorderFactory; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.OptionPropertyEditor; - -/** - * The FeatureDrawingAttributes class is used by the VPFFeatureGraphicWarehouse - * to control the fetching and display of feature attributes out of the feature - * attribute file, controlled by the FeatureClassInfo class. - * - * @author dietrick - */ -public class FeatureDrawingAttributes extends DrawingAttributes { - - private static final long serialVersionUID = 1L; - /** - * The main GUI panel containing the superclass GUI and attribute-fetching GUI. - */ - protected JPanel guiPanel; - /** - * The GUI panel containing the attribute fetching choices. - */ - protected JPanel attributePanel; - /** - * A handle to the FeatureClassInfo class containing the attribute information. - */ - protected FeatureClassInfo fci; - /** - * The GUI combo box for attribute choices. - */ - protected JComboBox attributeJCB; - /** - * The GUI combo box for choices on how to display the attributes. - */ - protected JComboBox displayTypeJCB; - /** - * The chosen display type, which gets set as a property in each OMGraphic for - * retrieval by the layer. - */ - protected String displayType; - /** - * The chosen attribute column index in the FCI file. - */ - protected int attributeCol; - /** - * The desired attribute column name as specified in properties. - */ - protected String attributeColName; - - public static final String DisplayTypeProperty = "attributeDisplay"; - public static final String AttributeProperty = "attribute"; - - /** - * Default creation of the FeatureDrawingAttributes. - */ - public FeatureDrawingAttributes() { - super(); - } - - /** - * @param props - */ - public FeatureDrawingAttributes(Properties props) { - super(props); - } - - /** - * @param prefix - * @param props - */ - public FeatureDrawingAttributes(String prefix, Properties props) { - super(prefix, props); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - if (props == null) { - return; - } - prefix = PropUtils.getScopedPropertyPrefix(prefix); - setDisplayType(props.getProperty(prefix + DisplayTypeProperty)); - attributeColName = props.getProperty(prefix + AttributeProperty, attributeColName); - } - - /** - * PropertyConsumer method that retrieves the current values of settable - * properties. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + DisplayTypeProperty, PropUtils.unnull(displayType)); - props.put(prefix + AttributeProperty, PropUtils.unnull(attributeColName)); - - return props; - } - - /** - * PropertyConsumer method that gathers information about the settable - * properties. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - props.put(DisplayTypeProperty, "How the property should be displayed."); - props.put(DisplayTypeProperty + LabelEditorProperty, "Attribute display type"); - props.put(DisplayTypeProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - props.put(DisplayTypeProperty + OptionPropertyEditor.ScopedOptionsProperty, "none tt il l"); - props.put(DisplayTypeProperty + ".none", "None"); - props.put(DisplayTypeProperty + ".tt", "Tooltip"); - props.put(DisplayTypeProperty + ".il", "Information Line"); - props.put(DisplayTypeProperty + ".l", "Label"); - - props.put(AttributeProperty, "The Name of the Attribute to display."); - props.put(AttributeProperty + LabelEditorProperty, "Attribute name"); - return props; - } - - /** - * Set the attributes chosen in the GUI on the OMGraphic. - * - * @param omg the OMGraphic to set the attribute information on. - * @param id The ID number of the map feature that the OMGraphic represents. - */ - public void setTo(OMGraphic omg, int id) { - super.setTo(omg); - - // now set the attributes on the OMGraphic based on the - // GUI/property settings. - if (fci != null) { - String dt = getDisplayType(); - if (dt != null) { - String tooltip = fci.getAttribute(id, getAttributeCol(), null); - // Might want to to .equals here, test for speed effect. - // if (dt.equals(OMGraphicConstants.LABEL)) { - if (dt == OMGraphicConstants.LABEL) { - OMTextLabeler omtl = new OMTextLabeler(tooltip); - super.setTo(omtl); - omg.putAttribute(dt, omtl); - } else { - omg.putAttribute(dt, tooltip); - } - } - } - } - - /** - * Retrieve the column index number out of the feature class info file that is - * being used/displayed. - * - * @return column index of attribute information. - */ - protected int getAttributeCol() { - return attributeCol; - } - - /** - * Set the column index number in the feature class info file that will be - * used/displayed. - */ - protected void setAttributeCol(int col) { - attributeCol = col; - } - - /** - * Return the GUI controls for this feature = the basic DrawingAttributes GUI - * from the superclass, plus the other attribute display controls. - */ - public Component getGUI() { - if (guiPanel == null) { - guiPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - guiPanel.setLayout(gridbag); - - c.gridwidth = GridBagConstraints.REMAINDER; - - Component sgui = super.getGUI(); - gridbag.setConstraints(sgui, c); - guiPanel.add(sgui); - - // Attribute GUI - attributePanel = new JPanel(); - attributePanel.setBorder( - BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), " Attribute Control ")); - GridBagLayout gridbag2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - attributePanel.setLayout(gridbag2); - - c2.gridwidth = GridBagConstraints.RELATIVE; - c2.anchor = GridBagConstraints.WEST; - - JLabel label = new JLabel("Name: "); - label.setToolTipText("Choose which attribute to display for each instance of this feature type."); - gridbag2.setConstraints(label, c2); - attributePanel.add(label); - - c2.gridwidth = GridBagConstraints.REMAINDER; - - attributeJCB = new JComboBox(); - attributeJCB.setToolTipText("Choose which attribute to display for each instance of this feature type."); - attributeJCB.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) ae.getSource(); - FCIChoice fcic = (FCIChoice) jcb.getSelectedItem(); - if (fcic != null) { - setAttributeCol(fcic.getColumn()); - setAttributeColName(fcic.getAttribute()); - } - } - }); - gridbag2.setConstraints(attributeJCB, c2); - attributePanel.add(attributeJCB); - - c2.gridwidth = GridBagConstraints.RELATIVE; - - label = new JLabel("How: "); - label.setToolTipText("Choose how to display the attribute."); - gridbag2.setConstraints(label, c2); - attributePanel.add(label); - - c2.gridwidth = GridBagConstraints.REMAINDER; - - DisplayTypeChoice[] dtc = new DisplayTypeChoice[] { new DisplayTypeChoice("None", null), - new DisplayTypeChoice(OMGraphicConstants.TOOLTIP, OMGraphicConstants.TOOLTIP), - new DisplayTypeChoice(OMGraphicConstants.INFOLINE, OMGraphicConstants.INFOLINE), - new DisplayTypeChoice(OMGraphicConstants.LABEL, OMGraphicConstants.LABEL) }; - - displayTypeJCB = new JComboBox(dtc); - displayTypeJCB.setToolTipText("Choose how to display the attribute."); - displayTypeJCB.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) ae.getSource(); - DisplayTypeChoice dtc = (DisplayTypeChoice) jcb.getSelectedItem(); - setDisplayType(dtc.getDisplayCommand()); - } - }); - - if (OMGraphicConstants.TOOLTIP.equalsIgnoreCase(displayType)) { - displayTypeJCB.setSelectedIndex(1); - } else if (OMGraphicConstants.INFOLINE.equalsIgnoreCase(displayType)) { - displayTypeJCB.setSelectedIndex(2); - } else if (OMGraphicConstants.LABEL.equalsIgnoreCase(displayType)) { - displayTypeJCB.setSelectedIndex(3); - } - - gridbag2.setConstraints(displayTypeJCB, c2); - attributePanel.add(displayTypeJCB); - - updateAttributeGUI(); - // End attribute GUI - - gridbag.setConstraints(attributePanel, c); - guiPanel.add(attributePanel); - } - return guiPanel; - } - - /** - * - */ - protected void updateAttributeGUI() { - if (attributePanel != null && attributeJCB != null && displayTypeJCB != null) { - - if (fci != null) { - attributeJCB.removeAllItems(); - - DcwColumnInfo[] dci = fci.getColumnInfo(); - int colCount = dci.length; - - // StringBuffer sb = new StringBuffer(); - - // Need to save current attributeColName, because - // setting a new choice on an empty combo box will set - // it to that first added attribute automatically. - String cacn = attributeColName; - for (int i = 0; i < colCount; i++) { - FCIChoice fcic = new FCIChoice(dci[i].getColumnName(), dci[i].getColumnDescription(), i); - attributeJCB.addItem(fcic); - if (dci[i].getColumnName().equalsIgnoreCase(cacn)) { - attributeJCB.setSelectedItem(fcic); - } - } - attributePanel.setVisible(true); - attributeJCB.setEnabled(true); - displayTypeJCB.setEnabled(true); - } else { - attributePanel.setVisible(false); - attributeJCB.setEnabled(false); - displayTypeJCB.setEnabled(false); - } - } - } - - /** - * @return Returns the displayType. - */ - public String getDisplayType() { - return displayType; - } - - /** - * @param displayType The displayType to set. - */ - public void setDisplayType(String displayType) { - this.displayType = displayType; - - // Check and update for not-null, so that equality check can be used - // later - if (displayType != null) { - if (displayType.equalsIgnoreCase(OMGraphicConstants.TOOLTIP)) { - displayType = OMGraphicConstants.TOOLTIP; - } else if (displayType.equalsIgnoreCase(OMGraphicConstants.LABEL)) { - displayType = OMGraphicConstants.LABEL; - } else if (displayType.equalsIgnoreCase(OMGraphicConstants.INFOLINE)) { - displayType = OMGraphicConstants.INFOLINE; - } - } - } - - /** - * @return Returns the fci. - */ - public FeatureClassInfo getFci() { - return fci; - } - - /** - * @param fci The fci to set. - */ - public void setFci(FeatureClassInfo fci) { - this.fci = fci; - if (attributeColName != null) { - int col = fci.whatColumn(attributeColName); - if (col >= 0) { - setAttributeCol(col); - } - } - updateAttributeGUI(); - } - - /** - * @return Returns the attributeColName. - */ - public String getAttributeColName() { - return attributeColName; - } - - /** - * @param attributeColName The attributeColName to set. - */ - public void setAttributeColName(String attributeColName) { - this.attributeColName = attributeColName; - } - - public class DisplayTypeChoice { - - protected String displayName; - protected String displayCommand; - - public DisplayTypeChoice(String dn, String dc) { - displayName = dn; - displayCommand = dc; - } - - public String getDisplayCommand() { - return displayCommand; - } - - public String getDisplayName() { - return displayName; - } - - public String toString() { - return getDisplayName(); - } - - } - - public class FCIChoice { - protected String attribute; - protected String description; - protected int column; - - public FCIChoice(String att, String desc, int col) { - attribute = att; - description = desc; - column = col; - } - - public String getAttribute() { - return attribute; - } - - public String getDescription() { - return description; - } - - public int getColumn() { - return column; - } - - public String toString() { - return getDescription() + " (" + getAttribute() + ")"; - } - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/GenerateVPFProperties.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/GenerateVPFProperties.java deleted file mode 100644 index bb1333064..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/GenerateVPFProperties.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ********************************************************************** - * :vim ts=4 sts=4 sw=4 et ai: - * Copyright 2000 Intevation GmbH - * This class is free software under the GNU LGPL - * - * useful with OpenMap by BBN Technologies, tested with version 3.6.2. - * Add this file to openmap-3.6.2/com/bbn/openmap/layer/vpf/ - * and add a line to the Makefile - * - * 20.12.2000 Bernhard Reiter - * version=1.0 - * 24.02.2002 Don Dietrick - * version 1.1 updated to work with OpenMap 4.5, added to OpenMap package. - * - * $Id: GenerateVPFProperties.java,v 1.6 2005/08/09 19:29:39 dietrick Exp $ - * ********************************************************************** - */ - -package com.bbn.openmap.layer.vpf; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.Debug; - -/** - * This class will print out some basic information about a VPF database, - * suitable for inclusion into the openmap.properties file. - * - *
- * 
- *  Usage:
- *  java com.bbn.openmap.layer.vpf.GenerateVPFproperties /path/to/vpf/database
- * 
- * 
- * - * It will then print out VPFlayer descriptions which you can use to view the - * VPF layers with the openmap application, to the standard output. There is no - * GUI. - * - * If you add the output to the openmap.properties files, pay attention to the - * Summary: lines. They make it easy to add all the layernames to the recognised - * ones. - * - */ -public class GenerateVPFProperties - extends DescribeDB { - static String rootpath; - - /** - * The main program. Takes path arguments, and prints the DB it finds - * - * @param args the paths to print - */ - public static void main(String[] args) - throws FormatException { - Debug.init(); - - if (args.length == 0) { - Debug.output("Usage: java com.bbn.openmap.layer.vpf.GenerateVPFProperties ..."); - System.exit(0); - } - - for (int argsi = 0; argsi < args.length; argsi++) { - rootpath = args[argsi]; - LibrarySelectionTable lst = new LibrarySelectionTable(rootpath); - if (Debug.debugging("vpf")) { - Debug.output("Path to database: " + rootpath); - Debug.output("Database Name: " + lst.getDatabaseName()); - } - println("### Generated openmap.properties for"); - println("# VPF Data at: " + rootpath); - println("# Description: " + lst.getDatabaseDescription()); - List libraries = lst.getLibraryNames(); - if (Debug.debugging("vpf")) { - print("Database Libraries: "); - for (String libraryName : libraries) { - print(libraryName, " "); - } - println(); - println(); - } - for (String libraryName : libraries) { - String prefix = lst.getDatabaseName() + "_" + libraryName; - println("# Library: " + prefix); - printLibrary(prefix, lst.getCAT(libraryName)); - println(); - } - } - } - - /** - * Prints a VPF Library - * - * @param prefix lines get printed with this prefix - * @param cat the CoverageAttributeTable (Library) to print - */ - public static void printLibrary(String prefix, CoverageAttributeTable cat) { - StringBuffer printedlayers = new StringBuffer(); - String printedlayername = null; - - if (cat == null) { - System.err.println(prefix + "Library doesn't exist"); - return; - } - String[] coverages = cat.getCoverageNames(); - if (Debug.debugging("vpf")) { - Debug.output(prefix + "uses " + (cat.isTiledData() ? "tiled" : "untiled") + " data"); - } - for (int i = 0; i < coverages.length; i++) { - printedlayername = printCoverageProperties(prefix, cat, coverages[i]); - if (printedlayername != null) { - printedlayers.append(" ").append(printedlayername); - } - } - println("# Summary:" + printedlayers); - } - - /** - * Prints a VPF Coverage - * - * @param prefix this will be the prefix of the generated layer name - * @param covname the name of the coverage to print - * @param cat the CoverageAttributeTable to get the Coverage from - */ - public static String printCoverageProperties(String prefix, CoverageAttributeTable cat, String covname) { - String layername = prefix + "_" + covname; - List text_features = new ArrayList(); - List edge_features = new ArrayList(); - List area_features = new ArrayList(); - List point_features = new ArrayList(); - - // add topology level - CoverageTable ct = cat.getCoverageTable(covname); - - String path = ct.getDataPath(); - String fcaPath = path + "/fca"; - - File fca = new File(fcaPath); - if (!fca.exists()) { - fcaPath = path + "/fca."; - fca = new File(fcaPath); - } - if (!fca.canRead()) { - println(); - return null; - } - try { - DcwRecordFile fcadesc = new DcwRecordFile(fcaPath); - int fclass = fcadesc.whatColumn("fclass"); - int type = fcadesc.whatColumn("type"); - // int descr = fcadesc.whatColumn("descr"); - List v = new ArrayList(); - while (fcadesc.parseRow(v)) { - String name = (String) v.get(fclass); - String t = (String) v.get(type); - // String desc = (String) v.get(descr); - // String tstring = "[unknown] "; - if (t.equals("T")) { - text_features.add(name); - } else if (t.equals("L")) { - edge_features.add(name); - } else if (t.equals("A")) { - area_features.add(name); - } else if (t.equals("P")) { - point_features.add(name); - } - } - } catch (FormatException fe) { - // nevermind, skip it - } - - // only print something, if we really found features - if (!(text_features.isEmpty() && edge_features.isEmpty() && area_features.isEmpty() && point_features.isEmpty())) { - - println("### VPF " + cat.getCoverageDescription(covname) + " Layer"); - println(layername + ".class=com.bbn.openmap.layer.vpf.VPFLayer"); - println(layername + ".prettyName=" + "VPF " + cat.getCoverageDescription(covname) + " " + prefix); - println(layername + ".vpfPath=" + rootpath); - println(layername + ".coverageType=" + covname); - println(layername + ".featureTypes=" + "area edge text point"); - - printFeatures("text", text_features, layername); - printFeatures("edge", edge_features, layername); - printFeatures("area", area_features, layername); - printFeatures("point", point_features, layername); - println(); - - } else { - return null; - } - - return layername; - - } - - /** - * Print some featureclass names - */ - public static void printFeatures(String fname, List features, String layername) { - if (!features.isEmpty()) { - print(layername + "." + fname + "="); - for (Object obj : features) { - print(obj.toString()); - } - println(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/GeoSymAttExpression.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/GeoSymAttExpression.java deleted file mode 100644 index a14206c64..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/GeoSymAttExpression.java +++ /dev/null @@ -1,957 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.io.FormatException; - -/** - * This parser class takes a string representing a logic statement and parses it - * into objects that can be used for evaluating attributes of features. It's - * based on expressions specified in the GeoSym Handbook MIL-HDBK-857A. - *

- * It can parse the expression given per the specification, such as - * 42|1|bfc|1|0|1, or the strings specified in the symbol tables in the - * MIL-DTL-89045A, like bfc=81 AND sta<>0and<>1and<>2and<>3and<>5and<>6and<>11. - *

- * - * @author dietrick - */ -public class GeoSymAttExpression { - - private static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.GeoSymAttExpr"); - - public final static int NO_OP = 0; - public final static int EQUALS_OP = 1; - public final static int NOT_EQUALS_OP = 2; - public final static int LESS_THAN_OP = 3; - public final static int GREATER_THAN_OP = 4; - public final static int LT_EQUALS_OP = 5; - public final static int GT_EQUALS_OP = 6; - - public final static int NONE_CONN = 0; - public final static int or_CONN = 1; // same attribute can be this or that - public final static int AND_CONN = 2; // different attributes must all be - // this and this - public final static int and_CONN = 3; // same attribute must be this and that - public final static int OR_CONN = 4; // one attribute can be this or a - // different attribute can be that - - protected VPFAutoFeatureGraphicWarehouse warehouse; - protected Expression exp; - /** - * The NOOP goes first to preserve the index value of each operator, as - * specifed in the GeoSym spec. - */ - protected static String[] ops = new String[] { - "", - "=", - "<>", - "<", - ">", - "<=", - ">=" - }; - - /** - * Create the expression object given a text representation of it. - * - * @param source - * @param warehouse used to resolve the ECDIS variables. - */ - public GeoSymAttExpression(String source, VPFAutoFeatureGraphicWarehouse warehouse) { - // Warehouse must be set first. - this.warehouse = warehouse; - exp = findExpression(source); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("Parsing: " + source); - logger.finer(this.toString()); - } - } - - protected Connector findOp(String source) { - int ANDIndex = source.lastIndexOf("AND"); - int ORIndex = source.lastIndexOf("OR"); - - if (ANDIndex == ORIndex) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("connector not found in " + source); - } - // both -1; - return null; - } - - if (ANDIndex > ORIndex) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("found AND in " + source); - } - return new Connector(AND_CONN, ANDIndex); - } else { - if (logger.isLoggable(Level.FINER)) { - logger.finer("found OR in " + source); - } - return new Connector(OR_CONN, ORIndex); - } - } - - public String toString() { - if (exp != null) { - return exp.toString(); - } else { - return "No Expression Defined"; - } - } - - protected Connector findMiniOp(String source) { - int ANDIndex = source.lastIndexOf("and"); - int ORIndex = source.lastIndexOf("or"); - - if (ANDIndex == ORIndex) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("connector not found in " + source); - } - // both -1; - return null; - } - - if (ANDIndex > ORIndex) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("found and in " + source); - } - return new Connector(and_CONN, ANDIndex); - } else { - if (logger.isLoggable(Level.FINER)) { - logger.finer("found or in " + source); - } - return new Connector(or_CONN, ORIndex); - } - } - - protected Expression findMathOp(String source) { - int opIndex = 1, locIndex = -1; - Expression exp = null; - - // Need to make sure that the finding one op doesn't obscure another, - // i.e. finding = but missing <=. - - while (opIndex < 7) { - locIndex = source.indexOf(ops[opIndex]); - - if (locIndex >= 0) { - if (opIndex == 1 || opIndex == 3 || opIndex == 4) { - if (source.contains("<=") || source.contains(">=")) { - opIndex++; - continue; - } else { - break; - } - } else { - break; - } - } - opIndex++; - } - - if (locIndex != -1) { - // Check out right side. If string, then create CompareExpression. If - // number, ValueExpression - String rightSide = source.substring(locIndex + ops[opIndex].length()); - - String leftSide = null; - if (locIndex > 0) { - leftSide = source.substring(0, locIndex); - } - - if (logger.isLoggable(Level.FINER)) { - logger.finer("got left side: " + leftSide + " op: " + ops[opIndex] + " and right side: " + rightSide); - } - - /** - * So here, We need to make a determination of whether the the left - * side is a column name from the data, as specified in the FCI, or if - * it's a ECDIS check. If the right side is a numerical value, we're - * just looking to test attribute data against hard numbers. We're - * going to push this decision into the ValueExpression, let it figure - * out what it should do. - */ - try { - - Double val = Double.parseDouble(rightSide); - - /** - * We need to check the length of this String to see if it's 4, - * which means it's an ECDIS variable, set by the user. On the left - * side it's just a straight number value comparison that will be - * provided for the right side. - */ - if (leftSide != null && leftSide.length() == 4) { - exp = new ECDISExpression(leftSide, val, opIndex, warehouse); - } else { - exp = new ValueExpression(leftSide, val, opIndex); - } - - } catch (NumberFormatException nfe) { - - /** - * This expression gets set up here for when a table value is - * compared against an ECDIS value. - * - * Turns out, there's never a need for the ColumnExpression because - * any time right side is text, it's actually referring to the value - * of the ECDIS External Attribute Name, which can be looked up and - * set as a variable. - * - * exp = new ColumnExpression(leftSide, rightSide, opIndex); - */ - - // TODO Need to handle UNK and NULL! - - double val = warehouse.getExternalAttribute(rightSide); - if (val < 0) { - // try to handle some string arguments - if (rightSide.equalsIgnoreCase("NULL")) { - exp = new StringExpression(leftSide, null, opIndex); - } else { - exp = new StringExpression(leftSide, rightSide, opIndex); - } - - } else { - - exp = new ValueExpression(leftSide, val, opIndex); - } - } - - } - - return exp; - } - - /** - * Recursive parsing statement. Keys on Connectors (AND, OR) and builds - * Expressions based on those. Then looks for mini connectors (and, or) and - * builds on those. Of course, there might just be one expression here, one - * that is separated by an operator. - * - * @param source - * @return Expression tree - */ - protected Expression findExpression(String source) { - - if (source != null && source.length() > 0) { - source = source.trim(); - if (source.length() == 0) { - return null; - } - - String leftSide = source; - String rightSide = null; - - Connector op = findOp(leftSide); - - if (op != null) { - rightSide = op.getRightSide(leftSide); - leftSide = leftSide.substring(0, op.sourceLoc); - - Expression leftExpression = findExpression(leftSide); - Expression rightExpression = findExpression(rightSide); - - if (leftExpression != null) { - op.addExpr(leftExpression); - } - if (rightExpression != null) { - op.addExpr(rightExpression); - } - - return op; - } - - // Look for mini ops - - op = findMiniOp(leftSide); - - if (op != null) { - rightSide = op.getRightSide(leftSide); - leftSide = leftSide.substring(0, op.sourceLoc); - - Expression leftExpression = findExpression(leftSide); - Expression rightExpression = findExpression(rightSide); - - if (leftExpression != null) { - op.addExpr(leftExpression); - } - if (rightExpression != null) { - op.addExpr(rightExpression); - } - - return op; - } - - // OK, here we are with the base expressions... - if (logger.isLoggable(Level.FINER)) { - logger.finer("need to break up: " + source); - } - - return findMathOp(source); - - } - - return null; - } - - /** - * Does the feature in row of fci pass the conditions of this expression. - * - * @param fci - * @param row - * @return true if row contents passes evaluation - */ - public boolean evaluate(FeatureClassInfo fci, int row) { - boolean ret = true; - StringBuffer reasoning = null; - if (logger.isLoggable(Level.FINE)) { - reasoning = new StringBuffer(); - } - - if (exp != null) { - ret = exp.evaluate(fci, row, reasoning); - } - if (reasoning != null) { - reasoning.append("\n--------"); - logger.fine(reasoning.toString()); - } - return ret; - } - - /** - * This one is used by the CoverageTable. Does the feature in row of fci pass - * the conditions of this expression. - * - * @param fci - * @param row - * @return true if row passes evaluation - */ - public boolean evaluate(FeatureClassInfo fci, List row) { - boolean ret = true; - StringBuffer reasoning = null; - if (logger.isLoggable(Level.FINE)) { - reasoning = new StringBuffer(); - logger.fine(toString()); - } - if (exp != null) { - ret = exp.evaluate(fci, row, reasoning); - } - if (reasoning != null) { - reasoning.append("\n--------"); - logger.fine(reasoning.toString()); - } - - return ret; - } - - /** - * Connector class is the part of the expression that contains the logic - * operation, AND, OR, and and or. - * - * @author dietrick - */ - public static class Connector - implements Expression { - List exp; - int op; - int sourceLoc; - - public Connector(int op, int sLoc) { - this.op = op; - this.sourceLoc = sLoc; - } - - public void addExpr(Expression expr) { - if (exp == null) { - exp = new LinkedList(); - } - - if (expr != null) { - exp.add(expr); - updateColumnNamesIfNeeded(); - } - } - - protected void updateColumnNamesIfNeeded() { - String colName = null; - - for (Expression e : exp) { - if (e instanceof CompareExpression) { - String cName = ((CompareExpression) e).colName; - if (cName != null) { - colName = cName; - break; - } - } - } - - if (colName != null) { - for (Expression e : exp) { - if (e instanceof CompareExpression) { - if (((CompareExpression) e).colName == null) { - ((CompareExpression) e).colName = colName; - break; - } - } - } - } - } - - public String getRightSide(String source) { - switch (op) { - case NONE_CONN: - break; - case and_CONN: - case AND_CONN: - return source.substring(sourceLoc + 3).trim(); - case or_CONN: - case OR_CONN: - return source.substring(sourceLoc + 2).trim(); - default: - } - - return null; - } - - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning) { - boolean ret = false; - switch (op) { - case NONE_CONN: - break; - case or_CONN: - break; - case AND_CONN: - ret = true; - for (Expression e : exp) { - ret = e.evaluate(fci, row, reasoning); - if (!ret) { - break; - } - } - break; - case and_CONN: - break; - case OR_CONN: - for (Expression e : exp) { - ret = ret || e.evaluate(fci, row, reasoning); - if (ret) { - break; - } - } - break; - default: - } - - if (reasoning != null) { - reasoning.append("\n-> " + toString() + ": evaluates " + ret); - } - return ret; - } - - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning) { - boolean ret = false; - switch (op) { - case NONE_CONN: - break; - case AND_CONN: - case and_CONN: - ret = true; - for (Expression e : exp) { - ret = e.evaluate(fci, row, reasoning); - if (!ret) { - break; - } - } - break; - case or_CONN: - case OR_CONN: - for (Expression e : exp) { - ret = e.evaluate(fci, row, reasoning); - if (ret) { - break; - } - } - break; - default: - } - - if (reasoning != null) { - reasoning.append("\n-> " + toString() + ": evaluates " + ret); - } - return ret; - } - - public String toString() { - StringBuffer sb = new StringBuffer("Connector["); - boolean addConn = false; - - String conn = " AND "; - if (op == OR_CONN) { - conn = " OR "; - } - - for (Expression e : exp) { - if (addConn) { - sb.append(conn); - } - sb.append(e.toString()); - addConn = true; - } - sb.append("]"); - return sb.toString(); - } - } - - /** - * The ECDISExpression checks the warehouse for user set values when - * evaluating. - * - * @author dietrick - */ - public static class StringExpression - extends CompareExpression { - - protected String val; - - public StringExpression(String colName, String val, int op) { - super(colName, op); - if (val == null) { - val = ""; - } - this.val = val; - } - - /** - * - */ - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning) { - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - List fcirow = new ArrayList(); - try { - if (fci.getRow(fcirow, row)) { - - if (colIndex < 0) { - if (reasoning != null) { - reasoning.append("\n col ").append(colName).append(" not found in FCI[").append(fci.columnNameString()).append("]"); - } - logger.info("col " + colName + " not found in FCI[" + fci.columnNameString() + "]"); - return false; - } - - String realVal = fcirow.get(colIndex).toString().trim(); - return test(realVal, val, reasoning); - } else { - if (reasoning != null) { - reasoning.append("\n Can't read row ").append(row); - } - } - } catch (FormatException fe) { - if (reasoning != null) { - reasoning.append("\n FormatException reading row ").append(row); - } - } - return false; - } - - /** - * For ECDISExpressions, none of the arguments matter. - */ - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning) { - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - // The columns aren't found - if (colIndex == -1) { - logger.finer("col " + colName + " not found in FCI[" + fci.columnNameString() + "]"); - return false; - } - - Object realVal = row.get(colIndex); - if (realVal == null) { - realVal = ""; - } - return test(realVal.toString().trim(), val, reasoning); - } - - /** - * The basic test for the operator, returning val1 op val2. - * - * @param val1 NOT NULL - * @param val2 NOT NULL - * @param buf - * @return true if operation passes - */ - protected boolean test(String val1, String val2, StringBuffer buf) { - boolean ret = false; - switch (op) { - case 1: - ret = val1.equals(val2); - break; - case 2: - ret = !val1.equals(val2); - break; - - } - - if (buf != null) { - String operation = null; - switch (op) { - case 1: - operation = (ret + "=" + val1 + "==" + val2); - break; - case 2: - operation = (ret + "=" + val1 + "!=" + val2); - break; - } - - buf.append("\n " + toString() + ":" + operation); - } - - return ret; - } - - public String toString() { - return "StringExpression[" + colName + " " + ops[op] + " " + val + "]"; - } - - } - - /** - * The ECDISExpression checks the warehouse for user set values when - * evaluating. - * - * @author dietrick - */ - public static class ECDISExpression - extends ValueExpression { - - VPFAutoFeatureGraphicWarehouse warehouse = null; - - public ECDISExpression(String colName, double val, int op, VPFAutoFeatureGraphicWarehouse warehouse) { - super(colName, val, op); - this.warehouse = warehouse; - } - - /** - * For ECDISExpressions, none of the arguments matter. - */ - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning) { - return evaluate(reasoning); - } - - /** - * For ECDISExpressions, none of the arguments matter. - */ - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning) { - return evaluate(reasoning); - } - - public boolean evaluate(StringBuffer reasoning) { - double realVal = warehouse.getExternalAttribute(colName); - return test(realVal, val, reasoning); - } - - public String toString() { - return "ECDISExpression[" + colName + " " + ops[op] + " " + val + "]"; - } - - } - - /** - * The ValueExpression is a comparison of a FCI value to a numerical value. - * - * @author dietrick - */ - public static class ValueExpression - extends CompareExpression { - - double val; - - public ValueExpression(String colName, double val, int op) { - super(colName, op); - this.val = val; - } - - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning) { - - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - List fcirow = new ArrayList(); - try { - if (fci.getRow(fcirow, row)) { - - if (colIndex < 0) { - if (reasoning != null) { - reasoning.append("\n col ").append(colName).append(" not found in FCI[").append(fci.columnNameString()).append("]"); - } - - return false; - } - - Double realVal = Double.parseDouble(fcirow.get(colIndex).toString()); - return test(realVal, val, reasoning); - } else { - if (reasoning != null) { - reasoning.append("\n Can't read row ").append(row); - } - } - } catch (FormatException fe) { - if (reasoning != null) { - reasoning.append("\n FormatException reading row ").append(row); - } - } catch (NumberFormatException nfe) { - if (reasoning != null) { - reasoning.append("\n NumberFormatException reading ").append(fcirow.get(colIndex)); - } - } - - return false; - } - - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning) { - - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - try { - - if (colIndex < 0) { - if (reasoning != null) { - reasoning.append("\n col ").append(colName).append(" not found in FCI[").append(fci.columnNameString()).append("]"); - } - return false; - } - - Double realVal = Double.parseDouble(row.get(colIndex).toString()); - return test(realVal, val, reasoning); - } catch (NumberFormatException nfe) { - if (reasoning != null) { - reasoning.append("\n NumberFormatException reading ").append(row.get(colIndex)); - } - } - - return false; - } - - public String toString() { - return "ValueExpression[" + colName + " " + ops[op] + " " + val + "]"; - } - } - - /** - * A ColumnExpression is the comparison of an FCI column value against - * another column value. - * - * @author dietrick - */ - public static class ColumnExpression - extends CompareExpression - implements Expression { - - protected String otherColName; - protected int otherColIndex = -1; - - public ColumnExpression(String colName, String otherName, int op) { - super(colName, op); - this.otherColName = otherName; - } - - protected void setIndexes(FeatureClassInfo fci) { - this.fci = fci; - int columnCount = fci.getColumnCount(); - colIndex = -1; - otherColIndex = -1; - - for (int column = 0; column < columnCount; column++) { - if (fci.getColumnName(column).equalsIgnoreCase(colName)) { - colIndex = column; - } - if (fci.getColumnName(column).equalsIgnoreCase(otherColName)) { - otherColIndex = column; - } - } - } - - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning) { - - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || otherColIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - // The columns aren't found - if (colIndex == -1 || otherColIndex == -1) { - logger.finer("col " + colName + " or " + otherColName + " not found in FCI[" + fci.columnNameString() + "]"); - return false; - } - - List fcirow = new ArrayList(); - try { - if (fci.getRow(fcirow, row)) { - Double realVal1 = Double.parseDouble(fcirow.get(colIndex).toString()); - Double realVal2 = Double.parseDouble(fcirow.get(otherColIndex).toString()); - return test(realVal1, realVal2, reasoning); - } - } catch (FormatException fe) { - } catch (NumberFormatException nfe) { - } - - return false; - } - - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning) { - - // Pre-cache column index so we don't have to do lookup for each entry. - if (colIndex == -1 || otherColIndex == -1 || this.fci != fci) { - setIndexes(fci); - } - - // The columns aren't found - if (colIndex == -1 || otherColIndex == -1) { - logger.finer("col " + colName + " or " + otherColName + " not found in FCI[" + fci.columnNameString() + "]"); - return false; - } - - try { - - Double realVal1 = Double.parseDouble(row.get(colIndex).toString()); - Double realVal2 = Double.parseDouble(row.get(otherColIndex).toString()); - return test(realVal1, realVal2, reasoning); - - } catch (NumberFormatException nfe) { - } - - return false; - } - - public String toString() { - return "ValueExpression[" + colName + " " + ops[op] + " " + otherColName + "]"; - } - } - - public static abstract class CompareExpression - implements Expression { - protected int op; - protected FeatureClassInfo fci = null; - protected String colName; - protected int colIndex = -1; - - protected CompareExpression(String colName, int op) { - this.colName = colName; - this.op = op; - } - - protected void setIndexes(FeatureClassInfo fci) { - this.fci = fci; - colIndex = -1; - int columnCount = fci.getColumnCount(); - for (int column = 0; column < columnCount; column++) { - if (fci.getColumnName(column).equalsIgnoreCase(colName)) { - colIndex = column; - break; - } - } - } - - /** - * The basic test for the operator, returning val1 op val2. - * - * @param val1 - * @param val2 - * @param buf - * @return true of operation passes. - */ - protected boolean test(double val1, double val2, StringBuffer buf) { - boolean ret = false; - switch (op) { - case 1: - ret = val1 == val2; - break; - case 2: - ret = val1 != val2; - break; - case 3: - ret = val1 < val2; - break; - case 4: - ret = val1 > val2; - break; - case 5: - ret = val1 <= val2; - break; - case 6: - ret = val1 >= val2; - } - - if (buf != null) { - String operation = null; - switch (op) { - case 1: - operation = (ret + "=" + val1 + "==" + val2); - break; - case 2: - operation = (ret + "=" + val1 + "!=" + val2); - break; - case 3: - operation = (ret + "=" + val1 + "<" + val2); - break; - case 4: - operation = (ret + "=" + val1 + ">" + val2); - break; - case 5: - operation = (ret + "=" + val1 + "<=" + val2); - break; - case 6: - operation = (ret + "=" + val1 + ">=" + val2); - } - - buf.append("\n " + toString() + ":" + operation); - } - - return ret; - } - - } - - /** - * The Expression interface allows for the recursive queries of Connectors - * and Value/CompareExpressions. - * - * @author dietrick - */ - public interface Expression { - - public boolean evaluate(FeatureClassInfo fci, int row, StringBuffer reasoning); - - public boolean evaluate(FeatureClassInfo fci, List row, StringBuffer reasoning); - - } - - public static void main(String[] args) { - new GeoSymAttExpression("mac=2 AND idsm=0 AND hdp>=msscand -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/LayerGraphicWarehouseSupport.java,v $ -// $Revision: 1.13 $ $Date: 2009/01/21 01:24:41 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.util.List; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FanCompress; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics. - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public abstract class LayerGraphicWarehouseSupport - implements VPFGraphicWarehouse { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFGraphicWarehouse"); - - protected DrawingAttributes drawingAttributes; - - /** HACK around antarctica display problem. */ - final transient protected static float antarcticaThreshold = ProjMath.degToRad(-89.9f); - - /** hang on to the graphics that we build */ - protected OMGraphicList graphics; - - /** remember if we draw edge features */ - private boolean drawEdgeFeatures; - /** remember if we draw text features */ - private boolean drawTextFeatures; - /** remember if we draw area features */ - private boolean drawAreaFeatures; - /** remember if we draw entity point features */ - private boolean drawEPointFeatures; - /** remember if we draw connected point features */ - private boolean drawCPointFeatures; - - /** - * thinning variables. note that thinning is meant to be done offline, so - * this is not optimized... - */ - private static boolean doThinning = false; - private static double fan_eps = 0.01f; - - /** - * Construct an object, initializes graphiclist - */ - public LayerGraphicWarehouseSupport() { - initDrawingAttributes(); - graphics = new OMGraphicList(); - graphics.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - } - - /** - * Called from super class constructor. - * - */ - protected void initDrawingAttributes() { - drawingAttributes = new DrawingAttributes(); - } - - /** - * Get the current graphics list. - * - * @return the OMGraphicList. - */ - public synchronized OMGraphicList getGraphics() { - return getGraphics(graphics); - } - - /** - * Add the area, edge, text and point sublists to the provided list. - */ - protected synchronized OMGraphicList getGraphics(OMGraphicList addToList) { - if (areaSubList != null) { - addToList.add(areaSubList); - } - if (edgeSubList != null) { - addToList.add(edgeSubList); - } - if (pointSubList != null) { - addToList.add(pointSubList); - } - if (textSubList != null) { - addToList.add(textSubList); - } - - return addToList; - } - - /** - * Get the DrawingAttributes used for the coverage type. - */ - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - /** - * Set the drawing attributes for the coverage type. - */ - public void setDrawingAttributes(DrawingAttributes da) { - drawingAttributes = da; - } - - /** - * Lets the warehouse know that a different CoverageAttributeTable will be - * using it. Default action is to do nothing. - */ - public void resetForCAT() { - } - - /** - * Set which library to use. If null, all applicable libraries in database - * will be searched. - */ - private List useLibrary = null; - - /** - * Set the VPF library names to use. If null, all libraries will be searched. - * Null is default. - */ - public void setUseLibraries(List lib) { - useLibrary = lib; - } - - /** - * Get the VPF library names to use. - */ - public List getUseLibraries() { - return useLibrary; - } - - /** - * Utility method to check if the specified library name has been set by the - * configuration as one to use. - * - * @param libName the library name to test - * @return true if the useLibrary list has not been set, is empty, or if the - * provided name starts with a useList entry on it (good for sets of - * libraries). - */ - public boolean checkLibraryForUsage(String libName) { - boolean useLibrary = true; - List libraryNames = getUseLibraries(); - if (libraryNames != null && !libraryNames.isEmpty()) { - useLibrary = false; - for (String libraryName : libraryNames) { - if (libName.startsWith(libraryName)) { - useLibrary = true; - break; - } - } - } - return useLibrary; - } - - /** - * Return the GUI for certain warehouse attributes. By default, return the - * GUI for the DrawingAttributes object being used for rendering attributes - * of the graphics. - * - * @param lst LibrarySelectionTable to use to get information about the data, - * if needed. Not needed here. - */ - public Component getGUI(LibrarySelectionTable lst) { - if (drawingAttributes != null) { - return drawingAttributes.getGUI(); - } else { - return null; - } - } - - protected OMGraphicList areaSubList; - protected OMGraphicList edgeSubList; - protected OMGraphicList textSubList; - protected OMGraphicList pointSubList; - - /** - * Clears the contained list of graphics. - */ - public void clear() { - graphics.clear(); - if (areaSubList != null) { - areaSubList.clear(); - areaSubList = null; - } - if (edgeSubList != null) { - edgeSubList.clear(); - edgeSubList = null; - } - if (textSubList != null) { - textSubList.clear(); - textSubList = null; - } - if (pointSubList != null) { - pointSubList.clear(); - pointSubList = null; - } - } - - protected void addArea(OMGraphic area) { - if (areaSubList == null) { - areaSubList = new OMGraphicList(); - } - areaSubList.add(area); - } - - protected void addEdge(OMGraphic edge) { - if (edgeSubList == null) { - edgeSubList = new OMGraphicList(); - } - edgeSubList.add(edge); - } - - protected void addText(OMGraphic text) { - if (textSubList == null) { - textSubList = new OMGraphicList(); - } - textSubList.add(text); - } - - protected void addPoint(OMGraphic point) { - if (pointSubList == null) { - pointSubList = new OMGraphicList(); - } - pointSubList.add(point); - } - - /** - * set if we draw edge features - * - * @param newvalue true for drawing, false otherwise - */ - public void setEdgeFeatures(boolean newvalue) { - drawEdgeFeatures = newvalue; - } - - /** - * Return true if we may draw some edge features. - */ - public boolean drawEdgeFeatures() { - return drawEdgeFeatures; - } - - /** - * set if we draw text features - * - * @param newvalue true for drawing, false otherwise - */ - public void setTextFeatures(boolean newvalue) { - drawTextFeatures = newvalue; - } - - /** - * Return true if we may draw some text features. - */ - public boolean drawTextFeatures() { - return drawTextFeatures; - } - - /** - * set if we draw area features - * - * @param newvalue true for drawing, false otherwise - */ - public void setAreaFeatures(boolean newvalue) { - drawAreaFeatures = newvalue; - } - - /** - * Return true if we may draw some area features. - */ - public boolean drawAreaFeatures() { - return drawAreaFeatures; - } - - /** - * set if we draw entity point features - * - * @param newvalue true for drawing, false otherwise - */ - public void setEPointFeatures(boolean newvalue) { - drawEPointFeatures = newvalue; - } - - /** - * Return true if we may draw some entity point features. - */ - public boolean drawEPointFeatures() { - return drawEPointFeatures; - } - - /** - * set if we draw connected point features - * - * @param newvalue true for drawing, false otherwise - */ - public void setCPointFeatures(boolean newvalue) { - drawCPointFeatures = newvalue; - } - - /** - * Return true if we may draw some connected point features. - */ - public boolean drawCPointFeatures() { - return drawCPointFeatures; - } - - /** - * Sets the features (lines, areas, text, points) that get displayed - * - * @param features a whitespace-separated list of features to display - */ - public void setFeatures(String features) { - // If someone gives us a list of features, we need to make - // sure thats - // what we use. - setAreaFeatures(false); - setEdgeFeatures(false); - setTextFeatures(false); - setEPointFeatures(false); - setCPointFeatures(false); - StringTokenizer t = new StringTokenizer(features); - while (t.hasMoreTokens()) { - String token = t.nextToken(); - if (token.equalsIgnoreCase(VPFUtil.Area)) { - setAreaFeatures(true); - } else if (token.equalsIgnoreCase(VPFUtil.Edge)) { - setEdgeFeatures(true); - } else if (token.equalsIgnoreCase(VPFUtil.EPoint)) { - setEPointFeatures(true); - } else if (token.equalsIgnoreCase(VPFUtil.CPoint)) { - setCPointFeatures(true); - } else if (token.equalsIgnoreCase(VPFUtil.Text)) { - setTextFeatures(true); - } else { - Debug.output("LayerGraphicsWarehouseSupport: ignoring feature: " + token); - } - } - - } - - public String getFeatureString() { - StringBuffer features = new StringBuffer(); - - if (drawAreaFeatures) - features.append(VPFUtil.Area.toLowerCase()).append(" "); - if (drawEdgeFeatures) - features.append(VPFUtil.Edge.toLowerCase()).append(" "); - if (drawEPointFeatures) - features.append(VPFUtil.EPoint.toLowerCase()).append(" "); - if (drawCPointFeatures) - features.append(VPFUtil.CPoint.toLowerCase()).append(" "); - if (drawTextFeatures) - features.append(VPFUtil.Text.toLowerCase()).append(" "); - return features.toString(); - } - - /** - * set drawing attribute properties - * - * @param prefix the prefix for our properties - * @param props the Properties object we use to look up values - */ - public void setProperties(String prefix, Properties props) { - String features; - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - features = props.getProperty(realPrefix + VPFLayer.featureTypesProperty); - drawingAttributes.setProperties(prefix, props); - - if (features != null) { - setFeatures(features); - } - } - - /** - * set drawing attribute properties - * - * @param props the Properties object. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String realPrefix = PropUtils.getScopedPropertyPrefix(drawingAttributes); - - props.put(realPrefix + VPFLayer.featureTypesProperty, getFeatureString()); - drawingAttributes.getProperties(props); - return props; - } - - /** - * create a filled polygon - * - * @param ipts a list of CoordFloatString objects - * @param totalSize the total number of points - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param doAntarcticaWorkaround hack for funny DCW antarctica data (passed - * to warehouse) - */ - public static OMPoly createAreaOMPoly(List ipts, int totalSize, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon, boolean doAntarcticaWorkaround) { - - // thin the data - // if (doThinning) { - // totalSize = doThinning(ipts); - // } - - // *2 for pairs - double[] llpts = new double[totalSize * 2]; - - // only do it if we're in the vicinity - if (doAntarcticaWorkaround) { - doAntarcticaWorkaround = (ll2.getLatitude() < -62f); - } - - int npts = 0; - for (CoordFloatString cfs : ipts) { - int cfscnt = cfs.tcount; - int cfssz = cfs.tsize; - double cfsvals[] = cfs.vals; - if (cfscnt > 0) { // normal - for (int i = 0; i < cfscnt; i++) { - llpts[npts++] = ProjMath.degToRad(cfsvals[i * cfssz + 1]);// lat - llpts[npts++] = ProjMath.degToRad(cfsvals[i * cfssz]);// lon - } - } else { // reverse - cfscnt *= -1; - for (int i = cfscnt - 1; i >= 0; i--) { - llpts[npts++] = ProjMath.degToRad(cfsvals[i * cfssz + 1]);// lat - llpts[npts++] = ProjMath.degToRad(cfsvals[i * cfssz]);// lon - } - } - } - - // HACK: we will rewrite the data for the Antarctica polygon - // so that - // it will display "correctly" in the cylindrical projections. - // only check if bottom edge of screen below a certain - // latitude - if (doAntarcticaWorkaround) { - double[] newllpts = new double[llpts.length]; - for (int i = 0; i < newllpts.length; i += 2) { - newllpts[i] = llpts[i]; - newllpts[i + 1] = llpts[i + 1]; - - if (newllpts[i] < antarcticaThreshold) { - Debug.message("vpf", "AreaTable.generateOMPoly(): Antarctica!"); - // HACK: we're assuming data is going from west to - // east, - // so we wrap the other way - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(179.99f); - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(90f); - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(0f); - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(-90f); - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(-179.99f); - // HACK: advance to western hemisphere where we - // pick up the real data again - while (llpts[i + 1] > 0) {// lon - newllpts[i++] = ProjMath.degToRad(-89.99f); - newllpts[i++] = ProjMath.degToRad(-179.99f); - } - i -= 2; - } - } - llpts = newllpts; - } - - // create polygon - change to OMPoly for jdk 1.1.x compliance. - OMPoly py = new OMPoly(llpts, OMGraphic.RADIANS, OMGraphic.LINETYPE_STRAIGHT); - - return py; - } - - /** - * Create an OMPoly corresponding to a VPF edge feature - * - * @param coords the coordinates to use for the poly - * @param ll1 upper left, used for clipping - * @param ll2 lower right, used for clipping - * @param dpplat used for latitude thinning - * @param dpplon used for longitude thinning - */ - public static OMPoly createEdgeOMPoly(CoordFloatString coords, LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon) { - // thin the data - // if (doThinning) { - // List ipts = new ArrayList(1); - // ipts.add(coords); - // doThinning(ipts); - // } - - double[] llpts = coords.vals; // NOTE: lon,lat order! - - // handle larger tuples (do extra O(n) loop to extract only - // lon/lats. - if (coords.tsize > 2) {// assume 3 - /* - * if (Debug.debugging("vpf")) { - * Debug.output("EdgeTable.drawTile: big tuple size: " + coords.tsize); - * } - */ - double[] newllpts = new double[coords.tcount * 2];// *2 for - // pairs - int len = newllpts.length; - for (int i = 0, j = 0; i < len; i += 2, j += 3) { - newllpts[i] = ProjMath.degToRad(llpts[j + 1]);// lat - newllpts[i + 1] = ProjMath.degToRad(llpts[j]);// lon - } - llpts = newllpts; - } else { - double lon; - int len = llpts.length; - for (int i = 0; i < len; i += 2) { - lon = ProjMath.degToRad(llpts[i]); - llpts[i] = ProjMath.degToRad(llpts[i + 1]);// lat - llpts[i + 1] = lon;// lon - } - } - - // create polyline - change to OMPoly for jdk 1.1.x - // compliance. - OMPoly py = new OMPoly(llpts, OMGraphic.RADIANS, OMGraphic.LINETYPE_STRAIGHT); - return py; - } - - /** - * Set doThinning. - * - * @param value boolean - */ - public static void setDoThinning(boolean value) { - doThinning = value; - } - - /** - * Are we thinning?. - * - * @return boolean - */ - public static boolean isDoThinning() { - return doThinning; - } - - /** - * Set fan compression epsilon. - * - * @param value double - */ - public static void setFanEpsilon(double value) { - fan_eps = value; - } - - /** - * Get fan compression epsilon. - * - * @return double - */ - public static double getFanEpsilon() { - return fan_eps; - } - - /** - * do fan compression of raw edge points - */ - protected static int doThinning(List ipts) { - int size = ipts.size(); - int totalSize = 0; - for (int j = 0; j < size; j++) { - - // get poly - CoordFloatString cfs = (CoordFloatString) ipts.get(j); - int cfscnt = cfs.tcount; - int cfssz = cfs.tsize; - double[] cfsvals = cfs.vals; - int npts = 0; - - // handle reverse - boolean rev = (cfscnt < 0); - if (rev) { - cfscnt = -cfscnt; - } - - // copy points - double[] llpts = new double[cfscnt << 1]; - for (int i = 0; i < cfscnt; i++) { - llpts[npts++] = cfsvals[i * cfssz];// lon - llpts[npts++] = cfsvals[i * cfssz + 1];// lat - } - - // thin points - FanCompress.FloatCompress fan = new FanCompress.FloatCompress(llpts); - FanCompress.fan_compress(fan, fan_eps); - - // install new points - cfs.vals = fan.getArray(); // install thinned 2-tuple - // array - cfs.tcount = cfs.vals.length >>> 1;// num pairs - cfs.tsize = 2;// HACK lossy... - totalSize += cfs.tcount; - if (rev) { - cfs.tcount *= -1; - } - } - return totalSize; - } - - /** - * Create an OMText object corresponding to a VPF text feature - * - * @param text the text - * @param latitude the latitude of where to place the text - * @param longitude the longitude of where to place the text - */ - public static OMText createOMText(String text, double latitude, double longitude) { - - OMText txt = new OMText(latitude, longitude, text, OMText.JUSTIFY_LEFT); - return txt; - } - - /** - * Create an OMPoint object corresponding to a VPF node feature - * - * @param latitude the latitude of where to place the text - * @param longitude the longitude of where to place the text - */ - public static OMPoint createOMPoint(double latitude, double longitude) { - - return new OMPoint(latitude, longitude); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibraryBean.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibraryBean.java deleted file mode 100644 index 30d11be86..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibraryBean.java +++ /dev/null @@ -1,208 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/LibraryBean.java,v $ -// $RCSfile: LibraryBean.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.Serializable; -import java.util.Properties; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A bean to be used for sharing LibrarySelectionTable objects between instances - * of VPFLayer. - * - *
- * 
- * # Assuming that you have a VPF Layer specifying a .libraryBean property
- * # with a value of "VMAPData", you need to specify the following properties:
- * # Required - the java class information
- * VMAPData.class=com.bbn.openmap.layer.vpf.LibraryBean
- * # as in the layer .vpfPath, a ';' separated list of paths to VPF data
- * VMAPData.vpfPath=e:/VMAPLV0
- * # the name of the library bean, used by the VPFLayers to identify
- * # this bean as the one they want to use.
- * VMAPData.name=VMAPLEVEL0
- * # Maximum number of tiles to cache.
- * VMAPData.cacheSize=25
- * 
- * 
- * - * The VMAPData maker name, or whatever other name you decide to name it, has to - * be added to the openmap.components property list so the LibraryBean will be - * created and added to the MapHandler. Of course, you could add the LibraryBean - * to the MapHandler programmatically if you wanted to. - */ -public class LibraryBean - implements PropertyConsumer, Serializable { - - private static final long serialVersionUID = 1L; - - /** used for explicitly naming a library bean (name). */ - public static final String nameProperty = "name"; - - /** - * property extension used to set the VPF root directory (vpfPath). - */ - public static final String pathProperty = "vpfPath"; - - /** Maximum size of tile cache (cacheSize). */ - public static final String cacheSizeProperty = "cacheSize"; - - /** the lst for the path */ - private transient LibrarySelectionTable lst = null; - - /** the name of the bean set in properties, or the marker name */ - String beanName; - - /** used by set/getPropertyPrefix */ - private String propertyPrefix = null; - - /** the paths used in constructing the lst */ - private String[] paths; - - /** - * The VPFFeatureCache to use for cached features. - */ - protected transient VPFFeatureCache featureCache; - - /** - * Construct an empty bean. - */ - public LibraryBean() { - featureCache = new VPFFeatureCache(); - } - - public void setProperties(Properties setList) { - setProperties(getPropertyPrefix(), setList); - } - - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - paths = PropUtils.initPathsFromProperties(setList, realPrefix + pathProperty, paths); - - String beanName = setList.getProperty(realPrefix + nameProperty); - this.beanName = (beanName == null) ? prefix : beanName; - - if (Debug.debugging("vpf")) { - Debug.output("LibraryBean.setProperties(): " + prefix + " " + this.beanName + " initialized"); - } - try { - if (paths == null) { - Debug.output("VPF LibraryBean: path not set - expected " + realPrefix + pathProperty + " property"); - } else { - lst = new LibrarySelectionTable(paths); - } - } catch (com.bbn.openmap.io.FormatException f) { - Debug.output(f.getMessage()); - } catch (NullPointerException npe) { - Debug.output("LibraryBean.setProperties:" + prefix + ": path name not valid"); - } - - int cacheSize = PropUtils.intFromProperties(setList, realPrefix + cacheSizeProperty, featureCache.getCacheSize()); - featureCache.resetCache(cacheSize); - } - - /** - * Gets the name of the component - if the name was explicitly set, then - * return that, otherwise return the property prefix. - */ - public String getName() { - return beanName; - } - - /** - * Not a good PropertyConsumer yet, doesn't return values. - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - String prefix = PropUtils.getScopedPropertyPrefix(this); - getList.put(prefix + nameProperty, beanName); - getList.put(prefix + cacheSizeProperty, Integer.toString(featureCache.getCacheSize())); - return getList; - } - - /** - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(nameProperty, "Name of Library Bean."); - list.put(pathProperty, "List of VPF directories."); - list.put(pathProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.MultiDirectoryPropertyEditor"); - list.put(cacheSizeProperty, "Maximun number of tiles to cache (25 is default)."); - - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * Returns the LST for the path of this object. - * - * @return an LST, null if the object didn't construct properly - */ - public LibrarySelectionTable getLibrarySelectionTable() { - return lst; - } - - /** - * Creates a new VPFFeatureWarehouse every time, with the shared - * featureCache. - * - * @return VPFCachedFeatureGraphicWarehouse used by LibraryBean - */ - public VPFCachedFeatureGraphicWarehouse getWarehouse() { - if (Debug.debugging("vpf")) { - Debug.output("LibraryBean.getWarehouse(): creating warehouse."); - } - - return new VPFCachedFeatureGraphicWarehouse(featureCache); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibrarySelectionTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibrarySelectionTable.java deleted file mode 100644 index 95e588ac2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/LibrarySelectionTable.java +++ /dev/null @@ -1,552 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/LibrarySelectionTable.java,v $ -// $Revision: 1.13 $ $Date: 2005/12/09 21:08:57 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Reads the VPF LibraryAttribute table and constructs CoverageAttributeTables - * for each of the library coverages (north america, browse, etc) that exist. - * - *

- * NOTE: This class maintains a whole bunch of cached information, and also - * hangs onto references to classes that cache even more information. When using - * this class, you are much better off sharing an instance of this class, rather - * than creating multiple instantiations of it for the same VPF data directory. - * - * @see CoverageAttributeTable - */ -public class LibrarySelectionTable { - - /** cutoff scale for browse coverage. */ - public final static int DEFAULT_BROWSE_CUTOFF = 31000000; - - protected int BROWSE_CUTOFF = DEFAULT_BROWSE_CUTOFF; - - /** - * the names of the VPF libraries listed in the library attribute table - */ - // private String libraryname[] = null; //library [i] - /** the bounding rectangle of the respective libraries */ - private Map boundrec = new HashMap();// bounding - // rect - // as - // [W,S,E,N] - /** the CoverageAttributeTables corresponding to the different libs */ - private Map CATs = new HashMap(); - /** - * A list of libraries in the same order as their data paths were added. - */ - private List orderedLibraryNameList = new ArrayList(); - - /** the names of the lat columns */ - final private static String LATColumns[] = { Constants.LAT_LIBNAME, Constants.LAT_XMIN, Constants.LAT_YMIN, - Constants.LAT_XMAX, Constants.LAT_YMAX }; - /** the expected schema types for the library attribute table */ - final private static char LATschematype[] = { 'T', 'F', 'F', 'F', 'F' }; - /** the expected schema lengths for the library attribute table */ - final private static int LATschemalength[] = { -1 /* 8 */, 1, 1, 1, 1 }; - /** the name of the database */ - private String databaseName; - /** the database description of itself */ - private String databaseDesc; - - /** - * Construct a LibrarySelectionTable without a path to data. - */ - public LibrarySelectionTable() { - } - - /** - * Construct a LibrarySelectionTable with a path to data. - * - * @param vpfpath - * the path to the base data directory; the file opened is - * vpfpath /lat. - * @exception FormatException - * some error was encountered while trying to handle the - * file. - */ - public LibrarySelectionTable(String vpfpath) throws FormatException { - addDataPath(vpfpath); - } - - /** - * Construct a LibrarySelectionTable with a path to data. - * - * @param vpfPaths - * the paths to the data directories; the file opened is - * vpfpath /lat. - * @exception FormatException - * some error was encountered while trying to handle the - * file. - */ - public LibrarySelectionTable(String vpfPaths[]) throws FormatException { - withDataPath(vpfPaths); - } - - /** - * Set the cutoff scale where if the map scale number is larger (smaller - * overall map scale), the coverage won't be returned. For example, if the - * scale cutoff is 30000000, if the map scale is 1:31000000, no map data - * will be returned. - */ - public void setCutoffScale(int scale) { - BROWSE_CUTOFF = scale; - } - - /** - * Get the cutoff scale where data will be retrieved. - */ - public int getCutoffScale() { - return BROWSE_CUTOFF; - } - - /** - * Add a path to a vpf library and return this LST. - * @param vpfPath path - * @return this LST - * @throws FormatException if there is a problem with the path. - */ - public LibrarySelectionTable withDataPath(String vpfPath) throws FormatException { - addDataPath(vpfPath); - return this; - } - - /** - * Add a set of vpf library paths and return this LST. - * @param vpfPaths array of paths - * @return this LST - * @throws FormatException if there is a problem with any one of the paths. - */ - public LibrarySelectionTable withDataPath(String[] vpfPaths) throws FormatException { - for (String p: vpfPaths) { - addDataPath(p); - } - - return this; - } - - /** - * add a path to LibrarySelectionTable. Adding different types of VPF - * libraries to the same LST is likely to cause trouble. (e.g. it would be - * bad to add both DCW and VMAP paths to the same LST. adding each DCW disk - * separately is why this method exists.) - * - * @param vpfpath - * the path to the base DCW directory; the file opened is - * vpfpath /lat. - * @exception FormatException - * some error was encountered while trying to handle the - * file. - */ - public void addDataPath(String vpfpath) throws FormatException { - VPFLayer.logger.fine("LST.addDataPath(" + vpfpath + ")"); - - // Figure out how files names should be constructed... - boolean addSlash = true; - - if (vpfpath.endsWith("/") || vpfpath.endsWith(File.separator)) { - addSlash = false; - } - - String latf = vpfpath + (addSlash ? "/" : "") + "lat"; - String dhtf = vpfpath + (addSlash ? "/" : "") + "dht"; - - if (!BinaryFile.exists(latf)) { - latf += "."; - dhtf += "."; - } - - DcwRecordFile latrf = new DcwRecordFile(latf); - DcwRecordFile dhtrf = new DcwRecordFile(dhtf); - - List databaseVec = dhtrf.parseRow(); - int dcol = dhtrf.whatColumn("database_name"); - if (dcol != -1) { - databaseName = (String) databaseVec.get(dcol); - } - dcol = dhtrf.whatColumn("database_desc"); - if (dcol != -1) { - databaseDesc = (String) databaseVec.get(dcol); - } - dhtrf.close(); - dhtrf = null; - - int latcols[] = latrf.lookupSchema(LATColumns, true, LATschematype, LATschemalength, false); - - final List libDirectories = searchLibraryDirectories(vpfpath); - - VPFLayer.logger.fine("lst.adp: looked up schema"); - for (final List l = new ArrayList<>(latrf.getColumnCount()); latrf.parseRow(l);) { - final String lname = ((String) l.get(latcols[0])).toLowerCase(); - - if (!libDirectories.contains(lname.toUpperCase())) { - continue; - } - - final float br[] = new float[] { ((Float) l.get(latcols[1])).floatValue(), - ((Float) l.get(latcols[2])).floatValue(), ((Float) l.get(latcols[3])).floatValue(), - ((Float) l.get(latcols[4])).floatValue() }; - try { - CoverageAttributeTable table = new CoverageAttributeTable(vpfpath, lname); - CATs.put(lname, table); - boundrec.put(lname, br); - orderedLibraryNameList.add(lname); - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine(lname + " " + br[0] + " " + br[1] + " " + br[2] + " " + br[3]); - } - } catch (FormatException fe) { - if (VPFLayer.logger.isLoggable(Level.FINER)) { - VPFLayer.logger.finer( - "*****\nVPFLayer.LST: Couldn't create CoverageAttributeTable for " + vpfpath + " " + lname - + " " + fe.getMessage() + "\n--- Not a problem if you have multiple paths, and " - + lname + " is included in another path ---\n*****"); - fe.printStackTrace(); - } else { - VPFLayer.logger - .fine("VPFLayer.LST: CAT discrepancy (run with finer logging level for more details)"); - } - } - } - latrf.close(); - latrf = null; - } - - private List searchLibraryDirectories(final String vpfpath) { - final ArrayList subDirLibWithCat = new ArrayList(); - - final File vpfDirectory = new File(vpfpath); - final File[] vpfSubDirectory = vpfDirectory.listFiles(new FileFilter() { - public boolean accept(final File file) { - return file.isDirectory(); - } - }); - - for (int i = 0; i < vpfSubDirectory.length; i++) { - final File subDir = vpfSubDirectory[i]; - String cat = subDir + "/cat"; - if (BinaryFile.exists(cat)) { - subDirLibWithCat.add(subDir.getName().toUpperCase()); - continue; - } - cat = cat + "."; - if (BinaryFile.exists(cat)) { - subDirLibWithCat.add(subDir.getName().toUpperCase()); - } - } - - return subDirLibWithCat; - } - - /** - * Return the list of libraries that this database has. - * - * @return the list of libraries. for DCW, this is typically NOAMER, BROWSE, - * etc. - */ - public List getLibraryNames() { - return new ArrayList(orderedLibraryNameList); - } - - /** - * Return the name of the database we are reading from. - */ - public String getDatabaseName() { - return databaseName; - } - - /** - * Return the description of the database we are reading from. - */ - public String getDatabaseDescription() { - return databaseDesc; - } - - /** - * Return the coverage attribute table (list of coverages available for the - * given library) for the given library name. - * - * @param library - * the name of the library to get the CAT for - * @return the CoverageAttributeTable requested (null if the library - * requested doesn't exist in the database) - * @exception FormatException - * exceptions from opening the CAT for the library - */ - public CoverageAttributeTable getCAT(String library) throws FormatException { - return CATs.get(library); - } - - /** - * - */ - public void drawTile(int scale, int screenwidth, int screenheight, String covname, VPFGraphicWarehouse warehouse, - LatLonPoint ll1, LatLonPoint ll2) { - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("Library selection table coverage: " + covname); - VPFLayer.logger.fine("Library selection table - edges: " + warehouse.drawEdgeFeatures()); - VPFLayer.logger.fine("Library selection table - text: " + warehouse.drawTextFeatures()); - VPFLayer.logger.fine("Library selection table - areas: " + warehouse.drawAreaFeatures()); - VPFLayer.logger.fine("Warehouse: " + warehouse); - VPFLayer.logger.fine("Warehouse: cutoff scale " + BROWSE_CUTOFF); - } - - // handle Dateline - if ((scale < BROWSE_CUTOFF) && (ll1.getLongitude() > ll2.getLongitude())) { - drawTile(scale, screenwidth, screenheight, covname, warehouse, ll1, new LatLonPoint.Float(ll2.getLatitude(), - 180f - .00001f)/* - * 180 - epsilon - */); - drawTile(scale, screenwidth, screenheight, covname, warehouse, - new LatLonPoint.Float(ll1.getLatitude(), -180f), ll2); - return; - } - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST.drawTile() with scale of " + scale); - } - - float dpplat = Math.abs((ll1.getLatitude() - ll2.getLatitude()) / screenheight); - float dpplon = Math.abs((ll1.getLongitude() - ll2.getLongitude()) / screenwidth); - - int inArea = 0; - CoverageTable redrawUntiled = null; - - for (CoverageAttributeTable cat : CATs.values()) { - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST: checking library: " + cat.getLibraryName()); - } - - if (!warehouse.checkLibraryForUsage(cat.getLibraryName())) { - continue; - } - - warehouse.resetForCAT(); - - List tiles = cat.tilesInRegion(ll1.getLatitude(), ll2.getLatitude(), ll2.getLongitude(), - ll1.getLongitude()); - - if (tiles == null) { - redrawUntiled = cat.getCoverageTable(covname); - } else if (cat.isTiledData() && (scale < BROWSE_CUTOFF)) { - - if (!tiles.isEmpty()) { - CoverageTable c = cat.getCoverageTable(covname); - if (c == null) { - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("|LST.drawTile(): Couldn't get coverage table for " + covname + " " - + cat.getLibraryName()); - } - continue; - } - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("Using coverage table for " + covname + " " + cat.getLibraryName()); - } - - inArea++; - for (TileDirectory tileDirectory : tiles) { - c.drawTile(tileDirectory, warehouse, ll1, ll2, dpplat, dpplon); - } - } - } - } - if ((redrawUntiled != null) && (inArea == 0)) { - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST drawing untiled browse data"); - } - redrawUntiled.drawTile(new TileDirectory(), warehouse, ll1, ll2, dpplat, dpplon); - } - } - - /** - * - */ - public void drawFeatures(int scale, int screenwidth, int screenheight, String covname, - VPFFeatureWarehouse warehouse, LatLonPoint ll1, LatLonPoint ll2) { - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST.drawFeatures(): Coverage name: " + covname); - VPFLayer.logger.fine("Library selection table - edges: " + warehouse.drawEdgeFeatures()); - VPFLayer.logger.fine("Library selection table - text: " + warehouse.drawTextFeatures()); - VPFLayer.logger.fine("Library selection table - areas: " + warehouse.drawAreaFeatures()); - VPFLayer.logger.fine("Warehouse: " + warehouse); - } - - // handle Dateline - if ((scale < BROWSE_CUTOFF) && (ll1.getLongitude() > ll2.getLongitude())) { - drawFeatures(scale, screenwidth, screenheight, covname, warehouse, ll1, - new LatLonPoint.Float(ll2.getLatitude(), 180f - .00001f)// 180-epsilon - ); - drawFeatures(scale, screenwidth, screenheight, covname, warehouse, - new LatLonPoint.Float(ll1.getLatitude(), -180f), ll2); - return; - } - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST.drawFeatures() with scale of " + scale); - } - - float dpplat = Math.abs((ll1.getLatitude() - ll2.getLatitude()) / screenheight); - float dpplon = Math.abs((ll1.getLongitude() - ll2.getLongitude()) / screenwidth); - -// int inArea = 0; - CoverageTable redrawUntiled = null; - - for (CoverageAttributeTable cat : CATs.values()) { - - if (!warehouse.checkLibraryForUsage(cat.getLibraryName())) { - continue; - } - - if (cat.isTiledCoverage() && scale < BROWSE_CUTOFF) { - - CoverageTable c = cat.getCoverageTable(covname); - if (c == null) { - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST.getFeatures(): Couldn't get coverage table for " + covname + " " - + cat.getLibraryName()); - } - continue; - } - - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("Using coverage table for " + covname + " " + cat.getLibraryName()); - } - - c.drawFeatures(warehouse, ll1, ll2, dpplat, dpplon); -// inArea++; - } else { - // Set up to draw browse coverage, or non-tiled coverage - if (VPFLayer.logger.isLoggable(Level.FINE)) { - VPFLayer.logger.fine("LST.drawTile(): Scale too small (probably) or no tiles in region."); - } - redrawUntiled = cat.getCoverageTable(covname); - - if (redrawUntiled != null) { - redrawUntiled.drawFeatures(warehouse, ll1, ll2, dpplat, dpplon); - } - } - } - - // Moved this code up into the redrawUntiled section directly above - // this. It looks like the code wanted to restrict how many un-tiled - // coverage attribute tables would be consulted, but for certain kinds - // of VPF data that gets distributed as a bunch of little libraries, - // this seems to limit rendering to only one small area. - - // if ((redrawUntiled != null) && (inArea == 0)) { - // redrawUntiled.drawFeatures(warehouse, ll1, ll2, dpplat, dpplon); - // } - } - - /** - * Given a string for a coverage type or feature type, return the - * description for that string. Return null if the code string isn't found. - * - * @param coverageOrFeatureType - * string ID for coverage or Feature type. - */ - public String getDescription(String coverageOrFeatureType) throws FormatException { - boolean DEBUG = VPFLayer.logger.isLoggable(Level.FINE); - - if (DEBUG) - VPFLayer.logger.fine("LST.getDescription: " + coverageOrFeatureType); - - for (String libraryName : getLibraryNames()) { - CoverageAttributeTable cat = getCAT(libraryName); - if (cat == null) { - continue; - } - String[] coverages = cat.getCoverageNames(); - for (int j = 0; j < coverages.length; j++) { - String covname = coverages[j]; - if (coverageOrFeatureType.equalsIgnoreCase(covname)) { - if (DEBUG) - VPFLayer.logger.fine("** Matches coverage " + covname); - return cat.getCoverageDescription(covname); - } else { - if (DEBUG) - VPFLayer.logger.fine(" Checking in coverage table " + covname); - CoverageTable ct = cat.getCoverageTable(covname); - Hashtable info = ct.getFeatureTypeInfo(); - for (CoverageTable.FeatureClassRec fcr : info.values()) { - String name = fcr.feature_class; - if (coverageOrFeatureType.equalsIgnoreCase(name)) { - if (DEBUG) - VPFLayer.logger.fine("** Found feature " + name); - return fcr.description; - } - if (DEBUG) - VPFLayer.logger.fine(" checked " + name); - } - } - } - } - if (DEBUG) - VPFLayer.logger.fine("-- No matches found."); - return null; - } - - /** - * Just a test main to parse vpf datafiles param args files to parse, plus - * other command line flags - * - * @param args - * command line arguments args[0] is a path to the VPF root - */ - public static void main(String[] args) { - String dcwbase = null; - if (args.length > 0) { - dcwbase = args[0]; - - try { - LibrarySelectionTable lst = new LibrarySelectionTable(dcwbase); - System.out.println("Database Name " + lst.getDatabaseName()); - - for (String libraryName : lst.getLibraryNames()) { - System.out.println("Library " + libraryName); - lst.getCAT(libraryName); - } - } catch (FormatException f) { - System.err.println("*****************************************"); - System.err.println("*---------------------------------------*"); - System.err.println("Format error in dealing with LST"); - System.err.println(f.getMessage()); - System.err.println("*---------------------------------------*"); - System.err.println("*****************************************"); - } - } else { - System.out.println("Need a path to the VPF lat. file"); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/MutableInt.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/MutableInt.java deleted file mode 100644 index b3b75ba70..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/MutableInt.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/MutableInt.java,v $ -// $RCSfile: MutableInt.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -/** - * Implement a wrapper class to allow mutable ints. - */ -public class MutableInt { - /** our value */ - public int value; - - /** - * Construct a object with a value - * - * @param newval our value - */ - public MutableInt(int newval) { - value = newval; - } - - /** - * Construct an object with the default value. - */ - public MutableInt() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/NodeTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/NodeTable.java deleted file mode 100644 index af978d6b7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/NodeTable.java +++ /dev/null @@ -1,147 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/NodeTable.java,v $ -// $Revision: 1.7 $ $Date: 2009/01/21 01:24:41 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Read VPF format node tables to generate point graphics for OpenMap. - */ -public class NodeTable extends PrimitiveTable { - - /** the column that our coordinates are in */ - final private int coordColumn; - /** the column that the first_edge info is in */ - final private int firstEdgeColumn; - /** the column that containing_face info is in */ - final private int containingFaceColumn; - /* if true, parse 'end' file; false, parse 'cnd' file */ - final private boolean isEntityNode; - - /** - * Construct a NodeTable for reading VPF text features. - * - * @param cov the CoverageTable for the tile - * @param tile the tile to parse - * @param isEntityNode if true, parse end file; false, parse cnd file - * @exception FormatException if something goes wrong reading the text - */ - public NodeTable(CoverageTable cov, TileDirectory tile, boolean isEntityNode) - throws FormatException { - super(cov, tile, isEntityNode ? Constants.endTableName : Constants.cndTableName); - this.isEntityNode = isEntityNode; - if ((coordColumn = whatColumn(Constants.ND_COORDINATE)) == -1) { - throw new FormatException("nodetable couldn't get " + Constants.ND_COORDINATE - + " column"); - } - firstEdgeColumn = whatColumn(Constants.ND_FIRSTEDGE); - containingFaceColumn = whatColumn(Constants.ND_CONTAININGFACE); - } - - /** - * Returns the column that contains first_edge. May return -1 indicating the - * column doesn't exist. - */ - public int getFirstEdgeColumn() { - return firstEdgeColumn; - } - - /** - * Returns the column that contains containing_face. May return -1 - * indicating the column doesn't exist. - */ - public int getContainingFaceColumn() { - return containingFaceColumn; - } - - /** - * Parse the node records for this tile, calling warehouse.createNode once - * for each record in the selection region. - * - * @param warehouse the warehouse used for createNode calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinning (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @see VPFGraphicWarehouse#createNode - */ - public void drawTile(VPFGraphicWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2) { - - double ll1lat = ll1.getY(); - double ll1lon = ll1.getX(); - double ll2lat = ll2.getY(); - double ll2lon = ll2.getX(); - - try { - for (List node = new ArrayList(); parseRow(node);) { - CoordFloatString coords = (CoordFloatString) node.get(coordColumn); - double lat = coords.getYasFloat(0); - double lon = coords.getXasFloat(0); - if ((lat > ll2lat) && (lat < ll1lat) && (lon > ll1lon) && (lon < ll2lon)) { - - warehouse.createNode(covtable, this, node, lat, lon, isEntityNode); - } - } - } catch (FormatException f) { - System.out.println("Exception: " + f.getClass() + " " + f.getMessage()); - } - } - - /** - * Use the warehouse to create a graphic from a feature in a NodeTable. - * - * @param warehouse the warehouse used for createNode calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param node a list with the NodeTable row contents. - * @param featureType the string representing the feature type, in case the - * warehouse wants to do some intelligent rendering. - * @param primID the primitive ID of the feature, in order to gather attributes if - * necessary. - * @see VPFGraphicWarehouse#createNode - */ - public OMGraphic drawFeature(VPFFeatureWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2, List node, - String featureType, int primID) { - - if (warehouse != null) { - double ll1lat = ll1.getY(); - double ll1lon = ll1.getX(); - double ll2lat = ll2.getY(); - double ll2lon = ll2.getX(); - - CoordFloatString coords = (CoordFloatString) node.get(coordColumn); - double lat = coords.getYasFloat(0); - double lon = coords.getXasFloat(0); - if ((lat > ll2lat) && (lat < ll1lat) && (lon > ll1lon) && (lon < ll2lon)) { - return warehouse.createNode(covtable, this, node, lat, lon, isEntityNode, featureType, primID); - } - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/PrimitiveTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/PrimitiveTable.java deleted file mode 100644 index 54c6f580f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/PrimitiveTable.java +++ /dev/null @@ -1,118 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/PrimitiveTable.java,v $ -// $RCSfile: PrimitiveTable.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:08:58 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Parent class for reading VPF primitive tables. - */ -public abstract class PrimitiveTable extends DcwRecordFile { - - /** the coverage table that we are working for */ - final protected CoverageTable covtable; - - /** the id column position */ - final protected int idColumn; - - /** the tile we are for */ - final protected TileDirectory tile; - - /** - * Construct a PrimitiveTable. - * - * @param cov the coverage table that is our "parent" - * @param tile the tile for the table - * @param tablename must be a 3 character VPF tablename - * @exception FormatException if something goes wrong opening the file - */ - public PrimitiveTable(CoverageTable cov, TileDirectory tile, - String tablename) throws FormatException { - super(cov.getDataPath() + tile.getPath() + tablename - + (cov.appendDot ? "." : "")); - this.idColumn = whatColumn(Constants.ID); - this.covtable = cov; - this.tile = tile; - } - - /** - * Get the coverage table that we are working on. - */ - public CoverageTable getCoverageTable() { - return covtable; - } - - /** - * Gets the id column value for the row. - */ - public int getID(List l) { - return l.get(idColumn).intValue(); - } - - /** - * Gets the tile we are for. - */ - public TileDirectory getTileDirectory() { - return tile; - } - - /** - * Parse the records for this tile, calling warehouse.createXXXX once for - * each record. - * - * @param warehouse the warehouse used for createArea calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) (passed - * to warehouse) - * @see VPFGraphicWarehouse - */ - abstract public void drawTile(VPFGraphicWarehouse warehouse, double dpplat, - double dpplon, LatLonPoint ll1, LatLonPoint ll2); - - /** - * Use the warehouse to create a graphic from a feature in the AreaTable. - * - * @param warehouse the warehouse used for createXXXX calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param area a List containing the AreaTable row contents. - * @param featureType the string representing the feature type, in case the - * warehouse wants to do some intelligent rendering. - * @param primID the primitive ID of the feature, in order to gather attributes if necessary. - * @see VPFGraphicWarehouse#createEdge - */ - abstract public OMGraphic drawFeature(VPFFeatureWarehouse warehouse, - double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2, - List area, String featureType, int primID); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/RunQueue.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/RunQueue.java deleted file mode 100644 index 697862422..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/RunQueue.java +++ /dev/null @@ -1,152 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/RunQueue.java,v $ -// $RCSfile: RunQueue.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -/** - * Implement a very basic thread scheduling mechanism. - * - * TerminatingRunnable objects get added to the queue. As the thread - * gets cpu time, it will sequentially dequeue and run the objects in - * the queue in a LIFO order. Duplicates are allowed in the queue. Run - * will get called exactly once for each enqueue call. Only one thread - * will run at a time. (The next object won't run until the previous - * one completes.) - * - * @see java.lang.Runnable#run() - */ -public class RunQueue extends java.lang.Thread { - /** the queue of objects to run */ - final private List queue = new ArrayList(); //fixed, unique - /** used to give threads unique names */ - static private int tcount = 0; - - /** - * default constructor. priority and daemon status inherited from - * the calling thread. This thread is NOT started - */ - public RunQueue() { - this(null); //call constructor with ThreadGroup arg - } - - /** - * construct this thread in a particular ThreadGroup - * - * @param tg the ThreadGroup to be in. null means - * the current ThreadGroup - */ - public RunQueue(ThreadGroup tg) { - super((tg != null) ? tg : Thread.currentThread().getThreadGroup(), - nextThreadName()); - } - - /** - * construct a thread in the default ThreadGroup with a few - * options set - * - * @param isDaemon true means be a daemon thread, - * false means don't. - * @param priority the value to use when calling setPriority - * @param autoStart true means call this.start() - * @see java.lang.Thread#start() - */ - public RunQueue(boolean isDaemon, int priority, boolean autoStart) { - this(null, isDaemon, priority, autoStart); - } - - /** - * construct a thread in the default ThreadGroup with a few - * options set - * - * @param tg the ThreadGroup to be in - * @param isDaemon true means be a daemon thread, - * false means don't. - * @param priority the value to use when calling setPriority - * @param autoStart true means call this.start() - * @see java.lang.Thread#start() - */ - public RunQueue(ThreadGroup tg, boolean isDaemon, int priority, - boolean autoStart) { - super(tg, nextThreadName()); - setDaemon(isDaemon); - setPriority(priority); - if (autoStart) { - start(); - } - } - - /** - * start going. This function locks the queue, dequeues and item, - * unlocks the queue, and calls run on the object that was - * dequeued. if no object was on the queue, it waits on the queue. - * this function never exits. - */ - public void run() { - while (true) { - Runnable r = null; - synchronized (queue) { //lock the queue - while (queue.isEmpty()) { - try { - queue.wait(); //wait for an enqueue to happen - } catch (java.lang.InterruptedException e) { - e.printStackTrace(); - } - } - r = queue.remove(queue.size() - 1); - - } - try { - r.run(); - } catch (Exception e) { - //Since this happens asynchronously to the thread who - // enqueued - //the object, there isn't a whole lot we can do... - e.printStackTrace(); - } - } - } - - /** - * Add an object to the queue of threads to run - * - * @param r the object to add - */ - public void enqueue(TerminatingRunnable r) { - synchronized (queue) { - queue.add(r); - queue.notifyAll(); //notify the running thread that the - // queue - // has stuff in it now - } - } - - /** - * if we use threadgroups, we need names. So here's where we make - * them - */ - private static synchronized String nextThreadName() { - return ("RunQueueThread-" + tcount++); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/Server.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/Server.java deleted file mode 100644 index 294f7a6ab..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/Server.java +++ /dev/null @@ -1,130 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/Server.java,v $ -// $Revision: 1.4 $ $Date: 2004/10/14 18:06:09 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.util.Debug; - -/** - * Poorly named, this class just parses VPF format files and dumps them to - * System.out(). If you want output to come from the applicable objects that - * parse the format files, and you only want that output to come when this - * Server is run, use the Debug flag "vpfserver" in those object classes. - */ -public class Server { - - /** - * Just a test main to parse vpf datafiles - * - * @param args files to parse, plus other command line flags - */ - public static void main(String[] args) { - Debug.init(System.getProperties()); - boolean schemaonly = false; - boolean printall = false; - boolean parseall = false; - - System.out.println("This class just decodes and print VPF files."); - System.out.println("use the DcwSpecialist class to run the specialist"); - - Debug.put("vpfserver"); - - if (Debug.debugging("vpf")) { - Debug.output("This file doesn't have debugging info."); - } - - for (int i = 0; i < args.length; i++) { - System.out.println(args[i]); - if (args[i].equals("-schemaOnly")) { - schemaonly = !schemaonly; - } else if (args[i].equals("-printAll")) { - printall = !printall; - } else if (args[i].equals("-parseAll")) { - parseall = !parseall; - } else if (args[i].equals("-help")) { - System.out.println(" -schemaOnly -printAll -parseAll -help [files]"); - } - if (args[i].startsWith("-")) { - continue; - } - try { - String f = args[i]; - if (args[i].endsWith("x") || args[i].endsWith("x.")) { - System.out.println("Skipping VLI format"); - } else if (args[i].endsWith("ti")) { - System.out.println("Trying Thematic Index format"); - DcwThematicIndex ff = new DcwThematicIndex(f, false); - ff.close(); - } else if (args[i].endsWith("si") || args[i].endsWith("si.")) { - System.out.println("Trying Spatial Index format"); - DcwSpatialIndex ff = new DcwSpatialIndex(f, false); - ff.close(); - } else if (args[i].endsWith(".doc")) { - DcwRecordFile foo = new DcwRecordFile(f); - String colname[] = { - "text" - }; - char tschema[] = { - 'T' - }; - int lschema[] = { - -1 - }; - int cols[]; - try { - cols = foo.lookupSchema(colname, true, tschema, lschema, false); - } catch (com.bbn.openmap.io.FormatException e) { - foo.printSchema(); - throw e; - } - - for (List l = new ArrayList(); foo.parseRow(l);) { - System.out.println(l.get(cols[0])); - } - System.out.println(); - foo.close(); - } else { - DcwRecordFile foo = new DcwRecordFile(f); - foo.printSchema(); - if (!schemaonly) { - if (printall) { - - for (List l = new ArrayList(); foo.parseRow(l);) { - System.out.println(VPFUtil.listToString(l)); - } - } else if (parseall) { - foo.parseAllRowsAndPrintSome(); - } else { - foo.parseSomeRowsAndPrint(); - } - } - foo.close(); - } - } catch (com.bbn.openmap.io.FormatException f) { - System.err.println("****************************************"); - System.err.println("*--------------------------------------*"); - System.err.println("Format error in dealing with " + args[i]); - System.err.println(f.getMessage()); - System.err.println("*--------------------------------------*"); - System.err.println("****************************************"); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TTFeatureInfoHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/TTFeatureInfoHandler.java deleted file mode 100644 index 0bc758892..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TTFeatureInfoHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; - -/** - * A feature info handler that displays attribute information as an html - * formatted tooltip. - * - * @author dietrick - */ -public class TTFeatureInfoHandler - implements VPFFeatureInfoHandler { - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.vpf.VPFFeatureInfoHandler#updateInfoForOMGraphic - * (com.bbn.openmap.omGraphics.OMGraphic, - * com.bbn.openmap.layer.vpf.FeatureClassInfo, java.util.List) - */ - public void updateInfoForOMGraphic(OMGraphic omg, FeatureClassInfo fci, List fcirow) { - - - DcwColumnInfo[] colInfo = fci.getColumnInfo(); - int columnCount = colInfo.length; - StringBuffer sBuf = new StringBuffer(""); - for (int i = 0; i < columnCount; i++) { - sBuf.append("" + colInfo[i].getColumnDescription() + ": " + fcirow.get(i).toString() + "
"); - } - sBuf.append(""); - - omg.putAttribute(OMGraphicConstants.TOOLTIP, sBuf.toString()); - } - - public boolean isHighlightable(OMGraphic omg) { - return true; - } - - public boolean shouldPaintHighlight(OMGraphic omg) { - return false; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TerminatingRunnable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/TerminatingRunnable.java deleted file mode 100644 index 79aee5ca0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TerminatingRunnable.java +++ /dev/null @@ -1,34 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/TerminatingRunnable.java,v $ -// $RCSfile: TerminatingRunnable.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -/** - * Classes that implement this interface are Runnable (in the Thread - * sense), but have run() methods that will terminate in a bounded - * amount of time. - * - * @see java.lang.Thread - * @see java.lang.Runnable#run() - */ -public interface TerminatingRunnable extends Runnable { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TextTable.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/TextTable.java deleted file mode 100644 index 375537d31..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TextTable.java +++ /dev/null @@ -1,138 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/TextTable.java,v $ -// $Revision: 1.7 $ $Date: 2009/01/21 01:24:41 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Read VPF format text tables to generate text graphics for OpenMap. - */ -public class TextTable extends PrimitiveTable { - - /** the column that our coordinates are in */ - final private int coordColumn; - - /** the column that the text info is in */ - final private int textColumn; - - /** - * Construct a TextTable for reading VPF text features. - * - * @param cov the CoverageTable for the tile - * @param tile the tile to parse - * @exception FormatException if something goes wrong reading the text - */ - public TextTable(CoverageTable cov, TileDirectory tile) throws FormatException { - super(cov, tile, "txt"); - if ((coordColumn = whatColumn("shape_line")) == -1) { - throw new FormatException("texttable couldn't get " + "shape_line column"); - } - if ((textColumn = whatColumn("string")) == -1) { - throw new FormatException("texttable couldn't get " + "string column"); - } - } - - /** - * Returns the coordinate string for the text primitive - * - * @param textprim the text primitive - */ - public CoordFloatString getCoordinates(List textprim) { - return (CoordFloatString) textprim.get(coordColumn); - } - - /** - * Parse the text records for this tile, calling warehouse.createText once - * for each record in the selection region. - * - * @param warehouse the warehouse used for createText calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @see VPFGraphicWarehouse#createText - */ - public void drawTile(VPFGraphicWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2) { - - double ll1lat = ll1.getY(); - double ll1lon = ll1.getX(); - double ll2lat = ll2.getY(); - double ll2lon = ll2.getX(); - - try { - for (List text = new ArrayList(); parseRow(text);) { - String textval = (String) text.get(textColumn); - CoordFloatString coords = (CoordFloatString) text.get(coordColumn); - double lat = coords.getYasFloat(0); - double lon = coords.getXasFloat(0); - - if ((lat > ll2lat) && (lat < ll1lat) && (lon > ll1lon) && (lon < ll2lon)) { - warehouse.createText(covtable, this, text, lat, lon, textval); - } - } - } catch (FormatException f) { - System.out.println("Exception: " + f.getClass() + " " + f.getMessage()); - } - } - - /** - * Use the warehouse to create a graphic from a feature in the TextTable. - * - * @param warehouse the warehouse used for createText calls (must not be - * null) - * @param dpplat threshold for latitude thinning (passed to warehouse) - * @param dpplon threshold for longitude thinngin (passed to warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - * @param text a list with the TextTable row contents. - * @param featureType the string representing the feature type, in case the - * warehouse wants to do some intelligent rendering. - * @param primID the primitive ID of the feature, in order to gather attributes if - * necessary. - * @see VPFGraphicWarehouse#createText - */ - public OMGraphic drawFeature(VPFFeatureWarehouse warehouse, double dpplat, double dpplon, - LatLonPoint ll1, LatLonPoint ll2, List text, - String featureType, int primID) { - - if (warehouse != null) { - - double ll1lat = ll1.getY(); - double ll1lon = ll1.getX(); - double ll2lat = ll2.getY(); - double ll2lon = ll2.getX(); - - String textval = (String) text.get(textColumn); - CoordFloatString coords = (CoordFloatString) text.get(coordColumn); - - double lat = coords.getYasFloat(0); - double lon = coords.getXasFloat(0); - if ((lat > ll2lat) && (lat < ll1lat) && (lon > ll1lon) && (lon < ll2lon)) { - return warehouse.createText(covtable, this, text, lat, lon, textval, featureType, primID); - } - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TileDirectory.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/TileDirectory.java deleted file mode 100644 index d22a13602..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TileDirectory.java +++ /dev/null @@ -1,125 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/TileDirectory.java,v $ -// $RCSfile: TileDirectory.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -/** - * This class maps latitudes and longitudes to a particular tile - * directory. - */ -public class TileDirectory { - - /** the name of the subdirectory */ - final private String tilename; - /** the boundaries */ - final private float westlon, southlat, eastlon, northlat; - /** the tile ID of this object */ - final private int tileID; - - /** - * Construct a TileDirectory with a path and boundaries. - * - * @param path the directory path - * @param n the northern boundary - * @param s the southern boundary - * @param e the eastern boundary - * @param w the western boundary - * @param tileID our tile identifier - */ - public TileDirectory(String path, int tileID, float n, float s, float e, - float w) { - StringBuffer strbuf = new StringBuffer(path.toLowerCase()); - // strbuf.append(File.separator); - strbuf.append("/"); // in Java land with the BinaryFile. - tilename = strbuf.toString().intern(); - this.tileID = tileID; - if (e < w) { - e += 360.0; - } - westlon = w; - eastlon = e; - northlat = n; - southlat = s; - } - - /** - * Construct an untiled TileDirectory. Since this object does not - * have valid boundaries, it is an error to call inRegion on it - * - * @see #inRegion(float, float, float, float) - */ - public TileDirectory() { - tilename = ""; - this.tileID = -1; - westlon = eastlon = northlat = southlat = Float.NaN; - } - - /** - * Return the path for this tile - * - * @return a string path - */ - public String getPath() { - return tilename; - } - - /** - * Return the tile identifier for this tile - * - * @return the tile id (-1 for untiled coverage) - */ - public int getTileID() { - return tileID; - } - - /** - * Return a string describing ourselves - * - * @return a string usable as a directory path component - */ - public String toString() { - return (tilename); - } - - /** - * Figure out if our region overlaps the passed in region - * - * @return true if the regions overlap - * @param n the northern boundary - * @param s the southern boundary - * @param e the eastern boundary - * @param w the western boundary - */ - public boolean inRegion(float n, float s, float e, float w) { - // take care of the easy case first... - if ((s > northlat) || (n < southlat)) { - return false; - } - if (e < w) { - e += 360.0f; - } - if ((w > eastlon) || (e < westlon)) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TilingAdapter.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/TilingAdapter.java deleted file mode 100644 index a51794000..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/TilingAdapter.java +++ /dev/null @@ -1,153 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/TilingAdapter.java,v $ -// $Revision: 1.5 $ $Date: 2004/10/14 18:06:09 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -/** - * An interface class for a set of adapter classes that hide the - * tiling format of a VPF table. None of the methods taking a List - * parameter may modify the passed in list. - * - * @see DcwRecordFile#getTilingAdapter(String,String) - */ -public interface TilingAdapter { - /** - * Get the tile identifier for the alternate tile - * - * @param l a row of the table this adapter was created for - * @return the tile id of the alternate tile - */ - public int getTileId(List l); - - /** - * Get the primitive identifier in the current tile - * - * @param l a row of the table this adapter was created for - * @return the primitive id in the current tile - */ - public int getPrimId(List l); - - /** - * Get the primitive identifier in the alternate tile - * - * @param l a row of the table this adapter was created for - * @return the primitive id in the alternate tile - */ - public int getTilePrimId(List l); - - /** - * Get the full set of primitive information - * - * @param l a row of the table this adapter was created for - * @return the full cross tile identifier information - */ - public DcwCrossTileID getPrim(List l); - - /** - * A TilingAdapter for untiled data. (The tile_id column doesn't - * exist, and the primitive column is not a cross-tile - * identifier.) Alternate tile will always return -1. - */ - public static class UntiledAdapter implements TilingAdapter { - /** the primitive column */ - final private int column; - - public UntiledAdapter(int column) { - this.column = column; - } - - public int getTileId(List l) { - return -1; - } - - public int getPrimId(List l) { - return ((Number) l.get(column)).intValue(); - } - - public int getTilePrimId(List l) { - return ((Number) l.get(column)).intValue(); - } - - public DcwCrossTileID getPrim(List l) { - return new DcwCrossTileID(getPrimId(l), -1, getTilePrimId(l)); - } - } - - /** - * A TilingAdapter for tiled data where the primitive column is a - * cross-tile identifier. - */ - public static class CrossTileAdapter implements TilingAdapter { - /** the primitive column */ - final private int column; - - public CrossTileAdapter(int column) { - this.column = column; - } - - public int getTileId(List l) { - return getPrim(l).nextTileID; - } - - public int getPrimId(List l) { - return getPrim(l).currentTileKey; - } - - public int getTilePrimId(List l) { - return getPrim(l).nextTileKey; - } - - public DcwCrossTileID getPrim(List l) { - return (DcwCrossTileID) l.get(column); - } - } - - /** - * A TilingAdapter where the tile identifier is retrieved from the - * tile_id column, and the primitive identifier comes from a - * numeric column. - */ - public static class TiledAdapter implements TilingAdapter { - /** the tile column */ - final private int tilecolumn; - /** the primitive column */ - final private int primcolumn; - - public TiledAdapter(int tilecolumn, int primcolumn) { - this.tilecolumn = tilecolumn; - this.primcolumn = primcolumn; - } - - public int getTileId(List l) { - return ((Number) l.get(tilecolumn)).intValue(); - } - - public int getPrimId(List l) { - return getTilePrimId(l); - } - - public int getTilePrimId(List l) { - return ((Number) l.get(primcolumn)).intValue(); - } - - public DcwCrossTileID getPrim(List l) { - return new DcwCrossTileID(getPrimId(l), getTileId(l), getTilePrimId(l)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VMAP2Shape.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VMAP2Shape.java deleted file mode 100644 index 8d6de2175..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VMAP2Shape.java +++ /dev/null @@ -1,540 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VMAP2Shape.java,v $ -// $RCSfile: VMAP2Shape.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -import com.bbn.openmap.dataAccess.shape.EsriShapeExport; -import com.bbn.openmap.dataAccess.shape.ShapeUtils; -import com.bbn.openmap.layer.shape.ShapeFile; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; -import com.bbn.openmap.util.PropUtils; - -/** - * Convert NIMA VMAP geospatial data into ESRI shapefile format. - */ -public class VMAP2Shape { - - protected static final String DEF_VMAP_TYPE = "bnd"; - protected static final String DEF_PROPS_FILE_NAME = System.getProperty("user.home") - + System.getProperty("file.separator") + "openmap.properties"; - protected static final String DEF_PREFIX = "vmapref"; - protected static final boolean DEF_DO_THINNING = false; - protected static final float DEF_FAN_EPS = 0.1f; - protected static final float DEF_ZERO_EPS = 0.0001f; - protected static final float DEF_THRESHOLD = 0.5f; - - protected String vmaptype = DEF_VMAP_TYPE; - protected String propsFileName = DEF_PROPS_FILE_NAME; - protected String prefix = DEF_PREFIX; - protected boolean doThinning = DEF_DO_THINNING; - protected float fan_eps = DEF_FAN_EPS; - protected float zero_eps = DEF_ZERO_EPS; - protected float threshold = DEF_THRESHOLD; - - protected LibrarySelectionTable lst; - protected transient LayerGraphicWarehouseSupport warehouse; - - protected boolean joinPolylines = false; - - public VMAP2Shape() {} - - /** - * Will load the properties set in the VPF2Shape object, fetch the - * OMGraphics from the VPF database, and write the shape file. - * - * @param shapeFileName - */ - public void writeShapeFile(String shapeFileName) { - setProperties(prefix, loadProperties()); - writeShapeFile(shapeFileName, getRectangle()); - } - - /** - * Write the shape file, assumes that the properties have been loaded and - * the graphics fetched from the VPF database. - * - * @param shapeFileName the file name to write the shapes into. - * @param graphics OMGraphics from VPF database to write to shape file. - */ - public void writeShapeFile(String shapeFileName, OMGraphicList graphics) { - try { - ShapeFile s = new ShapeFile(shapeFileName); - int nGraphics = graphics.size(); - if (nGraphics > 0) { - OMGraphic omg = graphics.get(0); - if ((omg instanceof OMPoly) - && (omg.getRenderType() == OMGraphic.RENDERTYPE_LATLON)) { - int shapeType = ((OMPoly) omg).isPolygon() ? ShapeUtils.SHAPE_TYPE_POLYGON - : ShapeUtils.SHAPE_TYPE_ARC; - System.out.println("shapeType=" + shapeType); - s.setShapeType(shapeType); - } - } - - System.out.println(nGraphics + " candidates."); - - if (doThinning) { - OMGraphicList saveGraphics = new OMGraphicList(); - for (int i = 0; i < nGraphics; i++) { - OMGraphic omg = graphics.get(i); - if ((omg instanceof OMPoly) - && (omg.getRenderType() == OMGraphic.RENDERTYPE_LATLON)) { - OMPoly poly = (OMPoly) omg; - - if (maybeThrowAwayPoly(poly)) { - continue; - } - - saveGraphics.add(poly); - } else { - System.out.println("Skipping candidate: " - + omg.getClass().toString() + ", " - + omg.getRenderType()); - } - } - - graphics = saveGraphics; - - if (joinPolylines) { - nGraphics = graphics.size(); - System.out.println("Joining " + nGraphics - + " polyline candidates."); - graphics = joinCommonLines(graphics, zero_eps); - } - } - - // Using com.bbn.openmap.dataAccess.shape package to write - // shape file: - EsriShapeExport ese = new EsriShapeExport(graphics, (Projection) null, shapeFileName); - ese.export(); - - // Instead of using com.bbn.openmap.layer.shape package to - // write shape file: - - // int nDumped = 0; - // nGraphics = graphics.size(); - // System.out.println("Dumping " + nGraphics + " - // graphics."); - // for (int i = 0; i < nGraphics; i++) { - // OMPoly poly = (OMPoly) graphics.getOMGraphicAt(i); - // float[] radians = poly.getLatLonArray(); - // ESRIPolygonRecord epr = new ESRIPolygonRecord(); - // epr.add(radians); - // epr.setPolygon(poly.isPolygon());//set POLYGON vs ARC - // s.add(epr); - // ++nDumped; - // } - // - // s.verify(true, true); - // s.verify(true, true); - // s.close(); - // System.out.println("Wrote " + nDumped + " Graphics."); - - } catch (java.io.IOException e) { - e.printStackTrace(); - } - } - - /** - * Iterates through graphic list finding non-connected polylines. iterates - * over these to find lines with common endpoints and joining them. - * - * @param list - * @param zero_eps - * @return OMGraphicList of polylines of joined segments - */ - protected static OMGraphicList joinCommonLines(OMGraphicList list, - float zero_eps) { - int size = list.size(); - int len1, len2; - double lat1, lon1, lat2, lon2; - OMGraphic obj; - OMGraphicList newGraphics = new OMGraphicList(); - OMGraphicList plineGraphics = new OMGraphicList(); - - // check for non-connected polylines - System.out.println("finding polylines..."); - for (int i = 0; i < size; i++) { - obj = list.getOMGraphicAt(i); - if ((obj instanceof OMPoly) && !((OMPoly) obj).isPolygon()) { - plineGraphics.add(obj); - } else { - newGraphics.add(obj); - } - } - - // iterate through the polylines and join lines with common - // endpoints - size = plineGraphics.size(); - OMPoly poly1, poly2; - double[] rads1, rads2, radians; - System.out.println("maybe joining " + size + " polylines..."); - // nasty!: > O(n^2) - for (int i = 0; i < size; i++) { - if (i % 500 == 0) { - System.out.println("checking pline i=" + i); - } - for (int j = 0; j < size; j++) { - if (i == j) { - continue; - } - obj = plineGraphics.getOMGraphicAt(i); - if (obj instanceof SinkGraphic) { - continue; - } - poly1 = (OMPoly) obj; - rads1 = poly1.getLatLonArray(); - len1 = rads1.length; - lat1 = ProjMath.radToDeg(rads1[len1 - 2]); - lon1 = ProjMath.radToDeg(rads1[len1 - 1]); - - obj = plineGraphics.getOMGraphicAt(j); - if (obj instanceof SinkGraphic) { - continue; - } - poly2 = (OMPoly) obj; - rads2 = poly2.getLatLonArray(); - len2 = rads2.length; - lat2 = ProjMath.radToDeg(rads2[0]); - lon2 = ProjMath.radToDeg(rads2[1]); - - if (MoreMath.approximately_equal(lat1, lat2, zero_eps) - && MoreMath.approximately_equal(lon1, lon2, zero_eps)) { - // System.out.println("joining..."); - radians = new double[len1 + len2 - 2]; - System.arraycopy(rads1, 0, radians, 0, len1); - System.arraycopy(rads2, 0, radians, len1 - 2, len2); - poly1.setLocation(radians, OMGraphic.RADIANS); - plineGraphics.setOMGraphicAt(SinkGraphic.getSharedInstance(), - j); - j = -1;// redo search - } - } - } - - // add the joined lines back to the data set - size = plineGraphics.size(); - for (int i = 0; i < size; i++) { - obj = plineGraphics.getOMGraphicAt(i); - if (obj instanceof OMPoly) { - newGraphics.add(obj); - } - } - return newGraphics; - } - - /** traverse array and coalesce adjacent points which are the same */ - public static double[] coalesce_points(double[] radians, double eps, - boolean ispolyg) { - int write = 2; - int len = radians.length; - for (int i = write - 2, j = write; j < len; j += 2) { - double lat1 = ProjMath.radToDeg(radians[i]); - double lon1 = ProjMath.radToDeg(radians[i + 1]); - double lat2 = ProjMath.radToDeg(radians[j]); - double lon2 = ProjMath.radToDeg(radians[j + 1]); - if (MoreMath.approximately_equal(lat1, lat2, eps) - && MoreMath.approximately_equal(lon1, lon2, eps)) { - continue; - } - i = write; - radians[write++] = radians[j]; - radians[write++] = radians[j + 1]; - } - // check for mid-phase line - if (ispolyg && (write == 6) - && MoreMath.approximately_equal(radians[0], radians[4], eps) - && MoreMath.approximately_equal(radians[1], radians[5], eps)) { - write -= 2;// eliminate wrapped vertex - } - double[] newrads = new double[write]; - System.arraycopy(radians, 0, newrads, 0, write); - return newrads; - } - - /** return true if we should throw away the poly */ - protected boolean maybeThrowAwayPoly(OMPoly poly) { - double[] radians = poly.getLatLonArray(); - double lat, lon, thresh = ProjMath.degToRad(threshold); - radians = coalesce_points(radians, 0.0001f, poly.isPolygon()); - poly.setLocation(radians, OMGraphic.RADIANS);// install new - if (radians.length < 4) { - return true;// throw away - } - if (poly.isPolygon() && (radians.length < 6)) { - return true; - } - int len = radians.length; - double d; - for (int i = 0; i < len; i += 2) { - // test for proximity to 1-degree marks. this hopefully - // avoids the problem of throwing away tiled slivers. - // (don't throw away poly) - lat = ProjMath.radToDeg(radians[i]); - lon = ProjMath.radToDeg(radians[i + 1]); - if (MoreMath.approximately_equal(lat, - (float) (Math.round(lat)), - zero_eps)) { - return false; - } - if (MoreMath.approximately_equal(lon, - (float) (Math.round(lon)), - zero_eps)) { - return false; - } - - // check to see if all points fit within a certain - // threshold. this should eliminate small islands and - // countries like Luxembourg. sorry. - for (int j = i + 2; j < radians.length; j += 2) { - d = DrawUtil.distance(radians[i], - radians[i + 1], - radians[j], - radians[j + 1]); - // outside threshold, don't throw away - if (!MoreMath.approximately_equal(d, 0f, thresh)) { - return false; - } - } - } - - if (poly.isPolygon()) { - return true;// throw away - } - - // throw away polyline if it's connected (island) - return (MoreMath.approximately_equal(ProjMath.radToDeg(radians[0]), - ProjMath.radToDeg(radians[radians.length - 2]), - zero_eps) && MoreMath.approximately_equal(ProjMath.radToDeg(radians[1]), - ProjMath.radToDeg(radians[radians.length - 1]), - zero_eps)); - } - - protected Properties loadProperties() { - Properties props = new Properties(); - try { - props.load(new FileInputStream(propsFileName)); - } catch (IOException e) { - e.printStackTrace(); - System.exit(1); - } - return props; - } - - protected void setProperties(String prefix, Properties props) { - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String[] paths = PropUtils.initPathsFromProperties(props, realPrefix - + VPFLayer.pathProperty); - - String defaultProperty = props.getProperty(realPrefix - + VPFLayer.defaultLayerProperty); - - if (defaultProperty != null) { - System.out.println("defaultProperty=" + defaultProperty); - realPrefix = defaultProperty + "."; - props = VPFUtil.getDefaultProperties(); - } - - String coverage = props.getProperty(realPrefix - + VPFLayer.coverageTypeProperty); - if (coverage != null) { - vmaptype = coverage; - System.out.println("vmaptype=" + vmaptype); - } - initLST(paths); - if (lst.getDatabaseName().equals("DCW")) { - System.out.println("creating VPFLayerDCWWarehouse"); - warehouse = new VPFLayerDCWWarehouse(); - } else { - System.out.println("creating VPFLayerGraphicWarehouse"); - warehouse = new VPFLayerGraphicWarehouse(); - } - - LayerGraphicWarehouseSupport.setDoThinning(doThinning); - LayerGraphicWarehouseSupport.setFanEpsilon(fan_eps); - warehouse.setProperties(realPrefix, props); - } - - protected void initLST(String[] paths) { - try { - if (lst == null) { - lst = new LibrarySelectionTable(paths); - } - } catch (com.bbn.openmap.io.FormatException f) { - throw new java.lang.IllegalArgumentException(f.getMessage()); - } - } - - public OMGraphicList getRectangle() { - int scale = 30000000; - int width = 640; - int height = 480; - LatLonPoint upperLeft = new LatLonPoint.Double(90.0, -180.0); - LatLonPoint lowerRight = new LatLonPoint.Double(-90.0, 180.0); - - warehouse.clear(); - - System.out.println("VMAP2Shape.getRectangle(): " - + "calling drawTile with boundaries: " + upperLeft + lowerRight); - long start = System.currentTimeMillis(); - lst.drawTile(scale, - width, - height, - vmaptype, - warehouse, - upperLeft, - lowerRight); - long stop = System.currentTimeMillis(); - System.out.println("VMAP2Shape.getRectangle(): read time: " - + ((stop - start) / 1000d) + " seconds"); - - return warehouse.getGraphics(); - } - - public boolean isDoThinning() { - return doThinning; - } - - public void setDoThinning(boolean doThinning) { - this.doThinning = doThinning; - } - - public float getFan_eps() { - return fan_eps; - } - - public void setFan_eps(float fan_eps) { - this.fan_eps = fan_eps; - } - - public LibrarySelectionTable getLst() { - return lst; - } - - public void setLst(LibrarySelectionTable lst) { - this.lst = lst; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getPropsFileName() { - return propsFileName; - } - - public void setPropsFileName(String propsFileName) { - this.propsFileName = propsFileName; - } - - public float getThreshold() { - return threshold; - } - - public void setThreshold(float threshold) { - this.threshold = threshold; - } - - public String getVmaptype() { - return vmaptype; - } - - public void setVmaptype(String vmaptype) { - this.vmaptype = vmaptype; - } - - public LayerGraphicWarehouseSupport getWarehouse() { - return warehouse; - } - - public void setWarehouse(LayerGraphicWarehouseSupport warehouse) { - this.warehouse = warehouse; - } - - public float getZero_eps() { - return zero_eps; - } - - public void setZero_eps(float zero_eps) { - this.zero_eps = zero_eps; - } - - public static void usage() { - System.out.println("Usage: java VMAP2Shape [args] "); - System.out.println("Arguments:"); - System.out.println("\t-props path to properties file"); - System.out.println(" default: " - + DEF_PROPS_FILE_NAME); - System.out.println("\t-prefix vmap properties prefix"); - System.out.println(" default: " + DEF_PREFIX); - System.out.println("\t-thin do thinning"); - System.out.println(" default eps=" - + DEF_FAN_EPS + " thresh=" + DEF_THRESHOLD); - System.exit(1); - } - - public static void main(String args[]) { - if ((args.length == 0) - || ((args.length == 1) && (args[0].startsWith("-")))) { - usage(); - } - - com.bbn.openmap.util.Debug.init(System.getProperties()); - - VMAP2Shape c = new VMAP2Shape(); - - for (int i = 0; i < args.length - 1; i++) { - if (args[i].equalsIgnoreCase("-props")) { - c.setPropsFileName(args[++i]); - } else if (args[i].equalsIgnoreCase("-prefix")) { - c.setPrefix(args[++i]); - } else if (args[i].equalsIgnoreCase("-thin")) { - c.setDoThinning(true); - c.setFan_eps(Float.valueOf(args[++i]).floatValue()); - c.setThreshold(Float.valueOf(args[++i]).floatValue()); - } else { - usage(); - } - } - - c.writeShapeFile(args[args.length - 1]); - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java deleted file mode 100644 index 5579c0ec7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java +++ /dev/null @@ -1,1305 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java,v $ -// $RCSfile: VPFFeatureGraphicWarehouse.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.BasicStroke; -import java.awt.Component; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.cgm.CGM; -import com.bbn.openmap.dataAccess.cgm.CGMDisplay; -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics from VPF. Designed to work - * closely with the VPFFeatureLayer, using GeoSymAttExpression objects to figure - * out how features are rendered. Uses two files to help manage features. The - * first file is a symbol lookup file that ties FACC codes and attribute - * settings with a set of CGM files. This file should cover entries for a - * particular data set. The second file is a priority file, that lists the order - * that features should be rendered, by feature type, facc code and attribute - * settings. If you want to change which features are displayed, or the order in - * which they are displayed, this is the file to modify. - *

- * - * Both of these files are CSV files, and their fields are important. The lookup - * file is of the format: - * - *

- * facc,type,symbol,conditions
- * AK160,A,0804,
- * AL005,A,0081 0734,
- * AL015,P,0002,bfc=81ANDsta=0or2or3or6or11
- * AL015,P,0010,bfc=7ANDhwt=0or2or3or4or7or22
- * AL015,P,0011,bfc=7ANDhwt=11or14or15or16or20or21
- * 
- * - * Note that the conditions field can be empty.The first field is the 5 - * character FACC code, the second field is the type (P, A, L) and the third - * field is the CGM file name. - *

- * - * The priority file is similar: - * - *

- * priority,type,facc,conditions,description
- * 0,Area,BA040,
- * 0,Area,BE010,cvl=99999
- * 0,Area,BE010,idsm=0 AND cvl>=msdcand<>99999
- * 0,Area,BE010,idsm=0 AND cvl>=ssdcand<msdc
- * 
- * - * The priority field really isn't important, the order of the overall file is. - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public class VPFAutoFeatureGraphicWarehouse implements VPFFeatureWarehouse, PropertyConsumer { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFAutoFeatureGraphicWarehouse"); - - public final static String CGM_DIR_PROPERTY = "cgmDirectory"; - public final static String SYMBOL_LOOKUP_FILE_PROPERTY = "faccLookupFile"; - public final static String PRIORITY_FILE_PROPERTY = "priorityFile"; - public final static String FEATURE_INFO_HANDLER_PROPERTY = "featureInfoHandler"; - public final static String FACC_DEBUG_PROPERTY = "debug"; - public final static String ICON_SIZE_PROPERTY = "iconSize"; - - public final static int DEFAULT_ICON_SIZE = 20; - - protected List priorities; - protected Hashtable> faccLookup; - protected String priorityFilePath; - protected String faccLookupFilePath; - protected String geoSymDirectory; - protected VPFFeatureInfoHandler featInfoHandler; - protected int iconSize = DEFAULT_ICON_SIZE; - - protected String[] compositeFeatureFaccs = new String[] { "BC010", "BC020", "BC040", "BC070" }; - - /** - * If set, the warehouse will limit visibility to specified facc and print out - * decision making process. - */ - protected String debugFacc = null; - - /** - * Set which library to use. If null, all applicable libraries in database will - * be searched. - */ - private List useLibrary = null; - /** - * The property prefix for scoping properties. - */ - protected String prefix; - - public final static String EV_ISDM = "isdm"; - public final static String EV_IDSM = "idsm"; - public final static String EV_SSDC = "ssdc"; - public final static String EV_MSDC = "msdc"; - public final static String EV_MSSC = "mssc"; - - /** - * Interactive Shallow Display Mode:ECDIS defines the display mode of shallow - * water areas (shallow depth zones) to be one of two symbology scenarios. The - * attribute values are 1 and 0, which toggle the shallow display mode to be on - * or off respectively. When ISDM is set on (1), the display of all depth zones - * shallower than the defined values of the Ships Safety Depth Contour (SSDC) - * are overprinted with a lattice pattern. This mode can be initiated in the - * four- or two-depth zone display modes (not including the drying line), - * defined by the Interactive Display Selection Mode, (IDSM). The shallow - * display mode is made available due to viewing limitations of the shallow - * depth zones in night displays. - */ - protected double isdm = 0; - /** - * Interactive Display Selection Mode:ECDIS defines the display of depth zones - * to be divided into two or four depth areas. This variable allows for the - * mariner to interactively set either display mode. The two-zone mode uses only - * the ships safety depth contour (SSDC) as a zone separator, whereas the - * four-zone mode further divides zones based on the mariner selected deep and - * shallow contours (MSDC, MSSC). Attribute values are 0 and 1 meaning four- and - * two-zone modes respectively. - */ - protected double idsm = 0; - /** - * Ship's Safety Depth Contour: The ships safety depth contour represents a safe - * contour based on the draft of the ship. This value must be entered by the - * mariner using an application interface. This interface must ensure that if a - * contour value does not exist within the data, that a next deeper value is - * specified as the SSDC. This checking must be dynamic as one traverses tile - * boundaries within the data.. - */ - protected double ssdc = 5; - /** - * Mariner Specified Deep Contour: The four-zone display mode requires the - * establishment of a deep contour that must be specified by the mariner through - * application inquiry. A default value may be implemented at 30m according to - * the ISO Color and Symbol Specification directives. - */ - protected double msdc = 30; - /** - * Mariner Specified Shallow Contour - The four-zone display mode requires the - * establishment of a shallow contour that must be specified by the mariner - * through application inquiry. A default value may be implemented at 2m - * according to the ISO Color and Symbol Specification directives. - */ - protected double mssc = 1; - - /** - * - */ - public VPFAutoFeatureGraphicWarehouse() { - - } - - /** - * The warehouse is initialized the first time features are fetched. - */ - protected void init() { - - CSVFile priorityFile; - CSVFile symbolLookupFile; - try { - - symbolLookupFile = new CSVFile(faccLookupFilePath); - symbolLookupFile.setHeadersExist(true); - symbolLookupFile.loadData(true); - - priorityFile = new CSVFile(priorityFilePath); - priorityFile.setHeadersExist(true); - priorityFile.loadData(true); - - faccLookup = new Hashtable>(); - Hashtable composites = new Hashtable(); - - // Build up the priority holder list - this keeps the features in - // proper rendering order, according to the priority csv file. - // composite features are just held once at the first location they - // are - // found. - - int numPriorities = priorityFile.getNumberOfRecords(); - priorities = new ArrayList(); - for (List row : priorityFile) { - String lineCheck = null; - String type = null; - String facc = null; - String conditions = null; - - try { - lineCheck = row.get(0).toString(); - - if (lineCheck.startsWith("#")) { - continue; - } - - type = row.get(1).toString(); - facc = row.get(2).toString(); - conditions = row.get(3).toString(); - - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.warning( - "Bad entry in priority file: " + lineCheck + "," + type + "," + facc + "," + conditions); - continue; - } - - // If the debugFacc is defined, just add that particular facc - // type - if (debugFacc != null && !debugFacc.equals(facc)) { - continue; - } - - // Now we need to check if the facc is a composite symbol, like - // a - // buoy. - boolean composite = false; - if (type.charAt(0) == CoverageTable.UPOINT_FEATURETYPE) { - for (String compFacc : compositeFeatureFaccs) { - if (compFacc.equals(facc)) { - composite = true; - break; - } - } - } - - FeaturePriorityHolder.Basic ph = new FeaturePriorityHolder.Basic(type, facc, conditions, this); - ph.setCGMPath(geoSymDirectory, ".cgm"); - - // If it is a composite, we need to add it to a - // FeaturePriorityHolder.Compound object, so that all the little - // parts will be added to any symbols, based on how the parts - // conditions match up to the feature entry in the attribute - // table. - if (composite) { - - FeaturePriorityHolder.Compound compound = composites.get(facc); - if (compound == null) { - compound = new FeaturePriorityHolder.Compound(type, facc, this); - composites.put(facc, compound); - priorities.add(compound); - - // faccLookup doesn't have this facc if we're here... - List list = new ArrayList(); - faccLookup.put(facc, list); - list.add(compound); - } - - compound.addPart(ph); - - } else { - priorities.add(ph); - - List list = faccLookup.get(facc); - if (list == null) { - list = new ArrayList(); - faccLookup.put(facc, list); - } - list.add(ph); - } - } - - // The priority file doesn't know anything about the symbol that is - // going to be used for the different conditions in the feature - // holders. Need to disperse the symbol information to the feature - // holders. - - // OK, time killer - loop through - int numSymbols = symbolLookupFile.getNumberOfRecords(); - int foundRecords = 0; - for (List row : symbolLookupFile) { - int numArgs = row.size(); - String facc = row.get(0).toString(); - if (numArgs != 7) { - logger.warning("Problem with facc entry, not correct number of args in csv file:" + facc); - continue; - } - - char type = getType(row.get(1).toString()); - String symbolCode = row.get(2).toString(); - String conditions = row.get(3).toString().trim(); - String size = row.get(4).toString().trim(); - String xoff = row.get(5).toString().trim(); - String yoff = row.get(6).toString().trim(); - - if (conditions.length() > 0) { - conditions = conditions.replace(" ", ""); - } - - List faccList = faccLookup.get(facc); - if (faccList != null) { - boolean found = false; - for (FeaturePriorityHolder ph : faccList) { - if (ph.matches(facc, type, conditions, symbolCode, size, xoff, yoff)) { - found = true; - foundRecords++; - break; - } - } - - if (!found) { - // This really shouldn't be triggered, if it is, - // something - // happened to the data files. But that might be - // intentional, - // to keep some feature types off the map. - if (logger.isLoggable(Level.FINE)) { - logger.fine("didn't find matching PriorityHolder for " + facc + "|" + type + "|" - + symbolCode + "|" + conditions); - } - } - - } else { - // Since we've turned off loading faccs for everything but - // the - // debug facc, of course other things will complain. - if (debugFacc == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("can't find faccLookup for " + facc + " for" + type + "|" + symbolCode + "|" - + conditions); - } - } - } - - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("matched up " + foundRecords + " of " + numSymbols + " symbols, " + numPriorities - + " priority entries"); - } - - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - public static char getType(String type) { - if (type == null) { - logger.warning("unknown type!"); - } else { - switch (type.charAt(0)) { - case 'P': - return CoverageTable.UPOINT_FEATURETYPE; - case 'A': - return CoverageTable.AREA_FEATURETYPE; - case 'L': - return CoverageTable.EDGE_FEATURETYPE; - default: - } - } - return CoverageTable.SKIP_FEATURETYPE; - } - - /** - * Set the VPF libraries to use, by name. If null, all libraries will be - * searched. Null is default. - */ - public void setUseLibraries(List libNames) { - useLibrary = libNames; - } - - /** - * Get a list of VPF library names that should be used, specified at - * configuration. - */ - public List getUseLibraries() { - return useLibrary; - } - - /** - * Utility method to check if the specified library name has been set by the - * configuration as one to use. - * - * @param libName the library name to test - * @return true if the useLibrary list has not been set, is empty, or if the - * provided name starts with the specified string entry (Good for - * specifying sets of like-libraries). - */ - public boolean checkLibraryForUsage(String libName) { - boolean useLibrary = true; - List libraryNames = getUseLibraries(); - if (libraryNames != null && !libraryNames.isEmpty()) { - useLibrary = false; - for (String libraryName : libraryNames) { - if (libName.startsWith(libraryName)) { - useLibrary = true; - break; - } - } - } - return useLibrary; - } - - /** - * Create an OMPoly for an area described by the facevec. - */ - public OMGraphic createArea(CoverageTable covtable, AreaTable areatable, List facevec, LatLonPoint ll1, - LatLonPoint ll2, double dpplat, double dpplon, String featureType, int primID) { - - List ipts = new ArrayList(); - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return null; - } - if (totalSize == 0) { - return null; - } - - OMPoly py = LayerGraphicWarehouseSupport.createAreaOMPoly(ipts, totalSize, ll1, ll2, dpplat, dpplon, - covtable.doAntarcticaWorkaround); - py.setIsPolygon(true); - return py; - } - - protected String info = null; - - /** - * - */ - public OMGraphic createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, LatLonPoint ll1, - LatLonPoint ll2, double dpplat, double dpplon, CoordFloatString coords, String featureType, int primID) { - - OMPoly py = LayerGraphicWarehouseSupport.createEdgeOMPoly(coords, ll1, ll2, dpplat, dpplon); - py.setFillPaint(OMColor.clear); - py.setIsPolygon(false); - return py; - } - - /** - * - */ - public OMGraphic createText(CoverageTable c, TextTable texttable, List textvec, double latitude, - double longitude, String text, String featureType, int primID) { - - OMText txt = LayerGraphicWarehouseSupport.createOMText(text, latitude, longitude); - return txt; - } - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public OMGraphic createNode(CoverageTable c, NodeTable t, List nodeprim, double latitude, double longitude, - boolean isEntityNode, String featureType, int primID) { - // OMPoint pt = new OMPoint.Image(latitude, longitude); - - OMScalingIcon pt = new OMScalingIcon(latitude, longitude, (Image) null); - pt.setBaseScale(500000); - pt.setMinScale(500000); - pt.setMaxScale(2000000); - return pt; - } - - public boolean needToFetchTileContents(String libraryName, String currentFeature, TileDirectory currentTile) { - return true; - } - - /** - * This is where the magic happens. - * - * @param lst LibrarySelectionTable that lets the warehouse know where the - * data is and what's in it. - * @param ll1 upper left coordinate of the desired area. - * @param ll2 lower right coordinate of the desired area. - * @param proj the projection for the area, used to generate OMGraphics added - * to the list. - * @param omgList the list to add OMGraphics to. One will be created and - * returned if this is null. - * @return the OMGraphicList with OMGraphics for features over desired area. - * @throws FormatException - */ - public OMGraphicList getFeatures(LibrarySelectionTable lst, LatLonPoint ll1, LatLonPoint ll2, Projection proj, - OMGraphicList omgList) throws FormatException { - - if (priorities == null) { - init(); - } - - // handle Dateline - if (ll1.getX() > ll2.getX()) { - omgList = getFeatures(lst, ll1, new LatLonPoint.Double(ll2.getY(), 180 - .00001), // 180-epsilon - proj, omgList); - omgList = getFeatures(lst, new LatLonPoint.Double(ll1.getY(), -180f), ll2, proj, omgList); - return omgList; - } - - if (omgList == null) { - omgList = new OMGraphicList(); - } - - omgList.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - int screenheight = proj.getHeight(); - int screenwidth = proj.getWidth(); - double dpplat = Math.abs((ll1.getY() - ll2.getY()) / screenheight); - double dpplon = Math.abs((ll1.getX() - ll2.getX()) / screenwidth); - - /* - * BoundingCircle screenBounds = new GeoSegment.Impl(new Geo[] { new - * Geo(ll1.getLatitude(), ll1.getLongitude()), new Geo(ll2.getLatitude(), - * ll2.getLongitude()) }).getBoundingCircle(); - */ - - DataBounds screenBounds = new DataBounds(ll1, ll2); - - for (String libraryName : lst.getLibraryNames()) { - - if (!checkLibraryForUsage(libraryName)) { - continue; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("reading library: " + libraryName); - - } - - CoverageAttributeTable cat = lst.getCAT(libraryName); - - if (cat == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("no CoverageAttributeTable for " + libraryName + ", skipping..."); - } - continue; - } - - // Do a quick bounds check, so we can just skip the tiles for this - // CAT - // if nothing is on the map. - DataBounds bounds = cat.getBounds(); - if (bounds != null) { - /* - * Point2D min = bounds.getMin(); Point2D max = bounds.getMax(); BoundingCircle - * catCircle = new GeoSegment.Impl(new Geo[] { new Geo(min.getY(), min.getX()), - * new Geo(max.getY(), max.getX()) }).getBoundingCircle(); - */ - if (!screenBounds.intersects(bounds)) { - logger.fine("CoverageAttributeTable for " + libraryName + " not on map, skipping..."); - continue; - } - } - - for (String covname : cat.getCoverageNames()) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("for coverage: " + covname + ", coverage topology level: " - + cat.getCoverageTopologyLevel(covname)); - } - - CoverageTable coverageTable = cat.getCoverageTable(covname); - - coverageTable.getFeatures(this, ll1, ll2, dpplat, dpplon, omgList); - - } - } - - // Go through PriorityHolders and build up OMGraphicList, in order for - // rendering to map. Moved this from inside the for loop above, so that - // feature order is preserved across libraries. - for (FeaturePriorityHolder ph : priorities) { - OMGraphicList list = ph.getList(); - if (list != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Adding features from " + ph.toString() + ": " + list.size() + " features"); - } - list.generate(proj); - omgList.addAll(list); - - list.setVisible(debugFacc == null || ph.getDebugFacc() != null); - - // Now that the OMGraphics are part of the main list, clean them - // out for the next request. Doing it here saves from having to - // do another loop through at the beginning of getFeatures. - ph.resetList(); - } - } - - logger.fine("returning from prepare ************"); - - return omgList; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawEdgeFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawTextFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawAreaFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawEPointFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawCPointFeatures() { - return true; - } - - /** - * @param rightSide the string pulled out of the VPF data for attribute - * comparisons. - * @return value greater than 0 for valid strings. - */ - public double getExternalAttribute(String rightSide) { - double ret = -1; - if (rightSide != null) { - if (rightSide.equals(EV_IDSM)) { - ret = idsm; - } else if (rightSide.equals(EV_ISDM)) { - ret = isdm; - } else if (rightSide.equals(EV_MSDC)) { - ret = msdc; - } else if (rightSide.equals(EV_MSSC)) { - ret = mssc; - } else if (rightSide.equals(EV_SSDC)) { - ret = ssdc; - } - } - - return ret; - } - - /** - * Given an OMGraphic that is going to be added to the map, use the - * FeatureClassInfo to gather attribute information from the fcirow contents. - * - * @param omg The OMGraphic representing a feature. - * @param fci The Description of the columns of the fcirow. - * @param fcirow The attributes for the feature. - */ - public void handleInformationForOMGraphic(OMGraphic omg, FeatureClassInfo fci, List fcirow) { - - if (featInfoHandler != null) { - featInfoHandler.updateInfoForOMGraphic(omg, fci, fcirow); - } - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#setProperties(java.util.Properties) - */ - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - /** - * Set properties of the warehouse. - * - * @param prefix the prefix to use for looking up properties. - * @param props the properties file to look at. - */ - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - faccLookupFilePath = props.getProperty(prefix + SYMBOL_LOOKUP_FILE_PROPERTY, faccLookupFilePath); - priorityFilePath = props.getProperty(prefix + PRIORITY_FILE_PROPERTY, priorityFilePath); - debugFacc = props.getProperty(prefix + FACC_DEBUG_PROPERTY, debugFacc); - geoSymDirectory = props.getProperty(prefix + CGM_DIR_PROPERTY, geoSymDirectory); - - iconSize = PropUtils.intFromProperties(props, prefix + ICON_SIZE_PROPERTY, iconSize); - - String fihString = props.getProperty(prefix + FEATURE_INFO_HANDLER_PROPERTY); - if (fihString != null) { - Object obj = ComponentFactory.create(fihString, prefix, props); - if (obj instanceof VPFFeatureInfoHandler) { - featInfoHandler = (VPFFeatureInfoHandler) obj; - } - } - - isdm = PropUtils.doubleFromProperties(props, prefix + EV_ISDM, isdm); - idsm = PropUtils.doubleFromProperties(props, prefix + EV_IDSM, idsm); - msdc = PropUtils.doubleFromProperties(props, prefix + EV_MSDC, msdc); - mssc = PropUtils.doubleFromProperties(props, prefix + EV_MSSC, mssc); - ssdc = PropUtils.doubleFromProperties(props, prefix + EV_SSDC, ssdc); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#getProperties(java.util.Properties) - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - getList.put(prefix + SYMBOL_LOOKUP_FILE_PROPERTY, faccLookupFilePath); - getList.put(prefix + PRIORITY_FILE_PROPERTY, priorityFilePath); - getList.put(prefix + CGM_DIR_PROPERTY, geoSymDirectory); - if (featInfoHandler != null) { - getList.put(prefix + FEATURE_INFO_HANDLER_PROPERTY, featInfoHandler.getClass().getName()); - - if (featInfoHandler instanceof PropertyConsumer) { - ((PropertyConsumer) featInfoHandler).getProperties(getList); - } - } - - getList.put(prefix + ICON_SIZE_PROPERTY, Integer.toString(iconSize)); - - if (debugFacc != null && debugFacc.length() > 0) { - getList.put(prefix + FACC_DEBUG_PROPERTY, debugFacc); - } - - getList.put(prefix + EV_ISDM, Double.toString(isdm)); - getList.put(prefix + EV_IDSM, Double.toString(idsm)); - getList.put(prefix + EV_MSDC, Double.toString(msdc)); - getList.put(prefix + EV_MSSC, Double.toString(mssc)); - getList.put(prefix + EV_SSDC, Double.toString(ssdc)); - - return getList; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#getPropertyInfo(java.util.Properties) - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, SYMBOL_LOOKUP_FILE_PROPERTY, - "Symbol Lookup File", "The path to the file containing symbol lookup information", - "com.bbn.openmap.util.propertyEditor.FilePropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, PRIORITY_FILE_PROPERTY, - "Priority File", "The path to the file containing feature type and order to use for display", - "com.bbn.openmap.util.propertyEditor.FilePropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, CGM_DIR_PROPERTY, - "CGM Directory Path", "The path to the directory containing GeoSym CGM files", - "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, FACC_DEBUG_PROPERTY, - "FACC Debug", "A FACC code to use to debug problems with data set", null); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, ICON_SIZE_PROPERTY, "Icon Size", - "The pixel size of icons for point features", null); - return list; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#setPropertyPrefix(java.lang.String) - */ - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#getPropertyPrefix() - */ - public String getPropertyPrefix() { - return prefix; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.layer.vpf.VPFWarehouse#resetForCAT() - */ - public void resetForCAT() { - // NOOP - } - - public int getIconSize() { - return iconSize; - } - - public void setIconSize(int iconSize) { - this.iconSize = iconSize; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.layer.vpf.VPFWarehouse#getGUI(com.bbn.openmap.layer.vpf - * .LibrarySelectionTable) - */ - public Component getGUI(LibrarySelectionTable lst) { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) NOOP - * - * @see com.bbn.openmap.layer.vpf.VPFWarehouse#getFeatures() - */ - public List getFeatures() { - return Collections.emptyList(); - } - - /** - * Set the object used to manage attribute formatting and display for features - * on the map. - * - * @return VPFFeatureInfoHandler being used. - */ - public VPFFeatureInfoHandler getFeatInfoHandler() { - return featInfoHandler; - } - - public void setFeatInfoHandler(VPFFeatureInfoHandler featInfoHandler) { - this.featInfoHandler = featInfoHandler; - } - - /** - * - * A FeaturePriorityHolder represents a rendering order slot in a list of - * feature types to be rendered. It is responsible for evaluating attributes of - * a VPF feature and determining if a particular feature matches what this - * priority holder represents. It can then provide an OMGraphicList for those - * features that match its attribute conditions. - * - * @author dietrick - */ - protected static abstract class FeaturePriorityHolder { - /** - * The type of the feature, i.e. point, line, area - */ - protected char type; - /** - * The feature code FACC for this kind of feature. - */ - protected String facc; - /** - * The OMGraphicList containing all the matching feature OMGraphics. - */ - protected OMGraphicList list; - /** - * The dimension of icons created for point OMGraphics. - */ - protected int dim = DEFAULT_ICON_SIZE; - - protected float sizePercent = 1f; - protected float xoffPercent = 0f; - protected float yoffPercent = 0f; - - /** - * A handle to any debug FACC code listed by the warehouse, so that a specific - * type of feature can be singled out for debugging. - */ - protected String debugFacc = null; - - protected FeaturePriorityHolder(String type, String facc, VPFAutoFeatureGraphicWarehouse warehouse) { - this.type = getType(type); - this.facc = facc; - this.dim = warehouse.getIconSize(); - - if (warehouse.debugFacc != null && warehouse.debugFacc.equals(facc)) { - debugFacc = warehouse.debugFacc; - } - } - - public OMGraphicList getList() { - if (debugFacc != null && list != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(list.getDescription()); - } - } - return list; - } - - public String getFacc() { - return facc; - } - - String getDebugFacc() { - return debugFacc; - } - - public void resetList() { - if (list != null) { - list.clear(); - } - } - - public void updateLocation(String size, String xoff, String yoff) { - sizePercent = getValue(size, 1f); - xoffPercent = getValue(xoff, 0f); - yoffPercent = getValue(yoff, 0f); - } - - protected float getValue(String s, float def) { - float ret = def; - if (s != null) { - try { - ret = Float.parseFloat(s); - } catch (NumberFormatException nfe) { - } - } - return ret; - } - - /** - * Used to match feature entries with PriorityHolder. - * - * @param facc - * @param fci - * @param row - * @return true if feature entry matches PriorityHolder conditions. - */ - public abstract boolean matches(String facc, FeatureClassInfo fci, List row); - - /** - * Used to match symbol codes with PriorityHolder during initialization of - * PriorityHolders. - * - * @param facc - * @param type - * @param conditions - * @param size percent of dim setting to use for size of symbol (0-1f) - * @param xoff percent off center of dim setting to use for x origin of - * symbol (0 is centered, positive is right) - * @param yoff percent off center of dim setting to use for x origin of - * symbol (0 is centered, positive is down) - * @return true of feature entry matches PriorityHolder conditions. - */ - public abstract boolean matches(String facc, char type, String conditions, String symbolFileName, String size, - String xoff, String yoff); - - protected abstract void add(OMGraphic omg); - - protected static class Basic extends FeaturePriorityHolder { - - protected GeoSymAttExpression expression; - protected String conditions; - protected String symbolParentDir; - protected String symbolExt; - - protected String[] cgmTitle; - protected CGMDisplay[] cgmDisplay; - protected BufferedImage icon; - - protected Basic(String type, String facc, String cond, VPFAutoFeatureGraphicWarehouse warehouse) { - super(type, facc, warehouse); - - if (cond != null && cond.trim().length() > 0) { - this.conditions = cond.replace(" ", ""); - expression = new GeoSymAttExpression(this.conditions, warehouse); - } - - } - - public String toString() { - return type + "|" + facc + "|" + conditions; - } - - /** - * Needs to be called before matches is called in init(). - */ - public void setCGMPath(String parent, String append) { - symbolParentDir = parent; - symbolExt = append; - } - - public Image getIcon() { - if (icon == null) { - try { - if (debugFacc != null) { - logger.info("initializing cgm for " + toString()); - } - - if (cgmTitle == null) { - logger.fine("no title for " + toString()); - } else { - - cgmDisplay = new CGMDisplay[cgmTitle.length]; - for (int i = 0; i < cgmTitle.length; i++) { - CGM cgm = new CGM(cgmTitle[i]); - if (debugFacc != null) { - logger.info(" using " + cgmTitle[i]); - } - cgmDisplay[i] = new CGMDisplay(cgm); - // Rendering the icon will load cgmDisplay with - // cgm - // parameters - // (fill paint, line paint, etc); - icon = cgmDisplay[i].getBufferedImage((int) (dim * sizePercent), - (int) (dim * sizePercent)); - } - } - } catch (IOException ioe) { - logger.fine("Couldn't load CGM files: " + cgmTitle[0] + "; first of " + cgmTitle.length); - } - } - - return icon; - } - - /** - * Used to match feature entries with PriorityHolder. - * - * @param facc - * @param fci - * @param row - * @return true of feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, FeatureClassInfo fci, List row) { - boolean ret = false; - char type = fci.getFeatureType(); - if (type == CoverageTable.EPOINT_FEATURETYPE || type == CoverageTable.CPOINT_FEATURETYPE) { - type = CoverageTable.UPOINT_FEATURETYPE; - } - if (facc.equals(this.facc) && this.type == type) { - if (expression != null) { - ret = expression.evaluate(fci, row); - } else { - ret = true; - } - } - return ret; - } - - /** - * Used to match symbol codes with PriorityHolder. - * - * @param facc - * @param type - * @param conditions - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, char type, String conditions, String symbolFileName, String size, - String xoff, String yoff) { - boolean basicMatch = this.facc.equals(facc) && type == this.type; - - boolean conditionMatch = ((this.conditions == null || this.conditions.trim().length() == 0) - && (conditions == null || conditions.trim().length() == 0)) - || (this.conditions != null && this.conditions.equals(conditions)); - - boolean ret = basicMatch && conditionMatch; - - if (ret) { - List names = PropUtils.parseSpacedMarkers(symbolFileName); - cgmTitle = new String[names.size()]; - for (int i = 0; i < names.size(); i++) { - cgmTitle[i] = symbolParentDir + "/" + names.get(i) + symbolExt; - updateLocation(size, xoff, yoff); - } - } - - return ret; - } - - public void add(OMGraphic omg) { - if (list == null) { - list = new OMGraphicList(); - } - - // Also makes sure cgmDisplay is initialized - Image icon = getIcon(); - - if (cgmDisplay != null) { - if (omg instanceof OMPoint.Image) { - ((OMPoint.Image) omg).setImage(icon); - } else if (omg instanceof OMRasterObject) { - ((OMRasterObject) omg).setImage(icon); - } else if (omg instanceof OMPoly) { - OMPoly omp = (OMPoly) omg; - if (!omp.isPolygon()) { - // This check is necessary of the cgms are not found - if (cgmDisplay[0] != null) { - omp.setLinePaint(cgmDisplay[0].getLineColor()); - omp.setStroke(new BasicStroke(1)); - omp.setFillPaint(OMColor.clear); - } - } else { - - if (cgmDisplay.length == 1 && cgmDisplay[0] != null) { - omp.setFillPaint(cgmDisplay[0].getFillColor()); - omp.setLinePaint(cgmDisplay[0].getFillColor()); - } else if (cgmDisplay.length > 1 && cgmDisplay[1] != null) { - omp.setFillPaint(cgmDisplay[1].getFillColor()); - omp.setLinePaint(cgmDisplay[1].getFillColor()); - } - } - } - } - - list.add(omg); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.layer.vpf.VPFAutoFeatureGraphicWarehouse. PriorityHolder - * #getConditions() - */ - public String getConditions() { - return conditions; - } - } - - /** - * A Compound FeaturePriorityHolder is used for buoys and other features that - * have parts added to their representation based on their feature attributes. - * It contains a list of Basic FeaturePriorityHolders, and each one adds its - * touch to the resulting OMGraphic as needed. - * - * @author dietrick - */ - protected static class Compound extends FeaturePriorityHolder implements ImageObserver { - - protected List parts = new ArrayList(); - protected BufferedImage icon; - - protected Compound(String type, String facc, VPFAutoFeatureGraphicWarehouse warehouse) { - super(type, facc, warehouse); - - } - - public String toString() { - return "Compound: " + type + "|" + facc; - } - - public void addPart(FeaturePriorityHolder.Basic part) { - parts.add(part); - } - - /** - * Used to match features with PriorityHolder. We need to do a little more work - * here, to build up an image that matches the all of the attributes set on this - * feature. So if the feature matches at the first level, walk through the parts - * and draw on top of it. - * - * @param facc - * @param fci - * @param row - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, FeatureClassInfo fci, List row) { - boolean ret = false; - - char type = fci.getFeatureType(); - if (type == CoverageTable.EPOINT_FEATURETYPE || type == CoverageTable.CPOINT_FEATURETYPE) { - type = CoverageTable.UPOINT_FEATURETYPE; - } - - /** - * Building up the current image based on the attributes. Give each part a - * chance to evaluate whether it should be rendered into the image or not. - */ - if (facc.equals(this.facc) && this.type == type) { - - BufferedImage image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) image.getGraphics(); - for (FeaturePriorityHolder.Basic part : parts) { - - if (part.expression != null) { - boolean partRet = part.expression.evaluate(fci, row); - - if (partRet) { - Image im = part.getIcon(); - g.drawImage(im, (int) (part.xoffPercent * dim), (int) (part.yoffPercent * dim), this); - ret = true; - } - - } else { - Image im = part.getIcon(); - g.drawImage(im, (int) (part.xoffPercent * dim), (int) (part.yoffPercent * dim), this); - ret = true; - } - - } - - icon = image; - } - - return ret; - } - - /** - * Used to match symbol codes with PriorityHolder. - * - * @param facc - * @param type - * @param conditions - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, char type, String conditions, String symbolFileName, String size, - String xoff, String yoff) { - boolean basicMatch = this.facc.equals(facc) && type == this.type; - - boolean conditionMatch = false; - - /** - * We need to step through each part so that each part can find it's symbol. - */ - for (FeaturePriorityHolder.Basic part : parts) { - - conditionMatch = part.matches(facc, type, conditions, symbolFileName, size, xoff, yoff); - - if (conditionMatch) { - break; - } - } - - return basicMatch && conditionMatch; - } - - public void add(OMGraphic omg) { - - if (list == null) { - list = new OMGraphicList(); - } - - if (icon != null) { - if (omg instanceof OMPoint.Image) { - ((OMPoint.Image) omg).setImage(icon); - list.add(omg); - } else if (omg instanceof OMRasterObject) { - ((OMRasterObject) omg).setImage(icon); - list.add(omg); - } - } - } - - /* - * (non-Javadoc) - * - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, - * int, int) - */ - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - return false;// all set - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFCachedFeatureGraphicWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFCachedFeatureGraphicWarehouse.java deleted file mode 100644 index 84f308f41..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFCachedFeatureGraphicWarehouse.java +++ /dev/null @@ -1,247 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFCachedFeatureGraphicWarehouse.java,v $ -// $RCSfile: VPFCachedFeatureGraphicWarehouse.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The VPFFeatureGraphicWarehouse extension that knows how to use a - * VPFFeatureCache. The cached lists are cloned and the drawing attributes for - * the clones are set based on the warehouse settings. - */ -public class VPFCachedFeatureGraphicWarehouse - extends VPFFeatureGraphicWarehouse { - - protected VPFFeatureCache featureCache = null; - - /** - */ - public VPFCachedFeatureGraphicWarehouse() { - super(); - } - - /** - */ - public VPFCachedFeatureGraphicWarehouse(VPFFeatureCache vfc) { - this(); - setFeatureCache(vfc); - } - - public void setFeatureCache(VPFFeatureCache vfc) { - featureCache = vfc; - } - - public VPFFeatureCache getFeatureCache() { - return featureCache; - } - - /** - * - */ - public OMGraphic createArea(CoverageTable covtable, AreaTable areatable, List facevec, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon, String featureType) { - - List ipts = new ArrayList(); - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return null; - } - if (totalSize == 0) { - return null; - } - - OMPoly py = createAreaOMPoly(ipts, totalSize, ll1, ll2, dpplat, dpplon, covtable.doAntarcticaWorkaround); - - DrawingAttributes da = getAttributesForFeature(featureType); - // Must make sure that line paint equals fill paint, the - // boundary for areas isn't always the sum of the areas. - // da.setLinePaint(da.getFillPaint()); - // da.setSelectPaint(da.getFillPaint()); - da.setTo(py); - py.setLinePaint(da.getFillPaint()); - py.setSelectPaint(da.getFillPaint()); - addToCachedList(py, featureType, areatable, VPFUtil.Area); - return py; - } - - /** - * - */ - public OMGraphic createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, LatLonPoint ll1, LatLonPoint ll2, double dpplat, - double dpplon, CoordFloatString coords, String featureType) { - - OMPoly py = createEdgeOMPoly(coords, ll1, ll2, dpplat, dpplon); - DrawingAttributes da = getAttributesForFeature(featureType); - // da.setFillPaint(OMColor.clear); // Just to make sure that - // it is always set in the DA. - da.setTo(py); - py.setFillPaint(OMColor.clear); - py.setIsPolygon(false); - - addToCachedList(py, featureType, edgetable, VPFUtil.Edge); - return py; - } - - /** - * - */ - public OMGraphic createText(CoverageTable c, TextTable texttable, List textvec, double latitude, double longitude, String text, - String featureType) { - - OMText txt = createOMText(text, latitude, longitude); - getAttributesForFeature(featureType).setTo(txt); - addToCachedList(txt, featureType, texttable, VPFUtil.Text); - return txt; - } - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public OMGraphic createNode(CoverageTable c, NodeTable t, List nodeprim, double latitude, double longitude, - boolean isEntityNode, String featureType) { - OMPoint pt = createOMPoint(latitude, longitude); - getAttributesForFeature(featureType).setTo(pt); - addToCachedList(pt, featureType, t, isEntityNode ? VPFUtil.EPoint : VPFUtil.CPoint); - return pt; - } - - protected FeatureCacheGraphicList cacheList; - - /** - * Calls addToCachedList on the feature cache if it's available. - */ - protected synchronized void addToCachedList(OMGraphic omg, String featureType, PrimitiveTable pt, String type) { - if (featureCache != null && cacheList != null) { - - // this might be causing problems in the cache, if the list has - // already be replaced by another library or layer. We're going to - // keep track of the list returned from the cache from before and - // add it to the list here if it exists. - cacheList.add(omg); - - // We don't do this anymore... - // featureCache.addToCachedList(omg, featureType, pt, type); - } else { - // Main OMGraphicList stored in super class - - if (VPFUtil.Area.equals(type)) - addArea(omg); - else if (VPFUtil.Edge.equals(type)) - addEdge(omg); - else if (VPFUtil.Text.equals(type)) - addText(omg); - else - addPoint(omg); - - // Sorting by type, now. - // graphics.add(omg); - } - } - - /** - * Calls VPFFeatureCache.needToFetchTileContents(). - */ - public boolean needToFetchTileContents(String libraryName, String currentFeature, TileDirectory currentTile) { - if (featureCache != null) { - // The cached graphics list will be added to the graphics - // list provided. If it was just created, it will also be passed - // back from the needToFetchTileContents and should be loaded by the - // CoverageTable. We're going to hold on to it inside the warehouse - // and just add OMGraphics to it while it is set. - - cacheList = featureCache.needToFetchTileContents(libraryName, currentFeature, currentTile, graphics); - - return cacheList != null; - - } else { - return super.needToFetchTileContents(libraryName, currentFeature, currentTile); - } - } - - /** - * Overridden method of VPFFeatureGraphicWarehouse, clones cached - * OMGraphicLst and sets the proper DrawingAttributes settings for the - * particular features. - */ - public synchronized OMGraphicList getGraphics() { - // Clone from the cache... - if (featureCache != null) { - // The main graphics object is made up of - // FeatureCacheGraphicLists for features for applicable - // tiles. All of the other warehouses are filling up the - // area, edge, text and point lists, but the cache is - // filling up the main list with these feature cache - // graphic lists. We need to sort them, reorganize and - // then return the newly sorted list so the areas are on - // the bottom. We're going to assume that the area, edge, - // text, point sublists are null and empty, since the - // cached stuff has been added directly to graphics. - OMGraphicList ret = new OMGraphicList(); - ret.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - logger.fine("checking for cached lists"); - for (OMGraphic omg :graphics) { - if (omg instanceof FeatureCacheGraphicList) { - FeatureCacheGraphicList fcgl = (FeatureCacheGraphicList) ((FeatureCacheGraphicList) omg).clone(); - fcgl.setDrawingAttributes(this); - - if (fcgl instanceof FeatureCacheGraphicList.AREA) { - addArea(fcgl); - } else if (fcgl instanceof FeatureCacheGraphicList.EDGE) { - addEdge(fcgl); - } else if (fcgl instanceof FeatureCacheGraphicList.TEXT) { - addText(fcgl); - } else { - addPoint(fcgl); - } - - } else { - // Add on top - addPoint(omg); - } - } - - getGraphics(ret); - - return ret; - } else { - return super.getGraphics(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFConfig.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFConfig.java deleted file mode 100644 index c123bd991..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFConfig.java +++ /dev/null @@ -1,779 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFConfig.java,v $ -// $RCSfile: VPFConfig.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/03/06 16:13:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.TreeMap; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreeSelectionModel; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * A component that can look at the VPF configuration files at the top level of - * the VPF directory structure, and provide an interface for defining an OpenMap - * VPFLayer for chosen features. - *

- * - * If the VPFConfig is provided a LayerHandler, it will have a button that will - * create a layer with selected features. If it doesn't have a LayerHandler, it - * will provide a button to print out the properties for a VPFLayer for the - * selected features. This class can be run in stand-alone mode to create - * properties. - */ -public class VPFConfig extends JPanel implements ActionListener { - - // private static boolean DEBUG = false; - - private static final long serialVersionUID = 1L; - // Optionally play with line styles. Possible values are - // "Angled", "Horizontal", and "None" (the default). - private boolean playWithLineStyle = false; - private String lineStyle = "Angled"; - protected boolean showAll = false; - protected boolean standAlone = false; - - public final static String AddFeatureCmd = "AddFeatureCommand"; - public final static String ClearFeaturesCmd = "ClearFeaturesCommand"; - public final static String CreateLayerCmd = "CreateLayerCommand"; - public final static String EMPTY_FEATURE_LIST = null; - - DefaultMutableTreeNode currentFeature = null; - - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - protected boolean searchByFeature = true; - protected String paths = ""; - - protected HashSet layerCoverageTypes = new HashSet(); - protected HashSet layerFeatureTypes = new HashSet(); - - public final static String AREA = "area"; - public final static String TEXT = "text"; - public final static String EDGE = "edge"; - public final static String POINT = "point"; - public final static String CPOINT = "cpoint"; - public final static String EPOINT = "epoint"; - public final static String COMPLEX = "complex"; - public final static String UNKNOWN = "unknown"; - - protected Hashtable> layerFeatures; - protected Properties layerProperties; - protected LayerHandler layerHandler; - protected LibraryBean libraryBean; - protected String layerName; - protected VPFLayer layer; - - JButton addFeatureButton; - JButton clearFeaturesButton; - JButton createLayerButton; - JTextArea currentFeatureList; - JTextField nameField; - - LinkedList featureList = new LinkedList(); - - public VPFConfig(String[] dataPaths, String layerName) { - this(dataPaths, null, layerName); - } - - public VPFConfig(String[] dataPaths, LayerHandler layerHandler, String layerName) { - this(dataPaths, layerHandler, layerName, false); - } - - protected VPFConfig(String[] dataPaths, LayerHandler layerHandler, String layerName, boolean standAlone) { - - this.layerHandler = layerHandler; - this.standAlone = standAlone; - this.layerName = layerName; - - paths = formatPaths(dataPaths); - - if (paths != null && paths.length() > 0) { - // Create the nodes. - DefaultMutableTreeNode top = new DefaultMutableTreeNode("VPF Data Libraries"); - try { - createNodes(top, dataPaths); - } catch (FormatException fe) { - Debug.output("Caught FormatException reading data: " + fe.getMessage()); - if (standAlone) { - System.exit(0); - } - } - - init(top); - } - } - - public VPFConfig(LibraryBean lb, LayerHandler layerHandler, String layerName) { - this.layerHandler = layerHandler; - this.layerName = layerName; - - // Create the nodes. - DefaultMutableTreeNode top = new DefaultMutableTreeNode("VPF Data Libraries"); - try { - createNodes(top, lb.getLibrarySelectionTable()); - } catch (FormatException fe) { - Debug.output("Caught FormatException reading data: " + fe.getMessage()); - } - - init(top); - } - - public VPFConfig(VPFLayer layer) { - if (layer != null && layer.lst != null) { - this.layer = layer; - this.layerName = layer.getName(); - // Create the nodes. - DefaultMutableTreeNode top = new DefaultMutableTreeNode("VPF Data Libraries"); - try { - createNodes(top, layer.lst); - } catch (FormatException fe) { - Debug.output("Caught FormatException reading data: " + fe.getMessage()); - } - init(top); - } - } - - public String formatPaths(String[] dataPaths) { - - if (dataPaths != null && dataPaths.length > 0) { - - // Take the time to replace any \ with /, it matters if - // the properties get printed out for later. - // Permanently set them from \ to / for when they get - // passed to BinaryFile. - dataPaths[0] = dataPaths[0].replace('\\', '/'); - StringBuffer buf = new StringBuffer(dataPaths[0]); - - for (int i = 1; i < dataPaths.length; i++) { - buf.append(";"); - // Permanently set them from \ to / for when they get - // passed to BinaryFile. - dataPaths[i] = dataPaths[i].replace('\\', '/'); - buf.append(dataPaths[i]); - } - return buf.toString(); - } - return null; - } - - public void init(DefaultMutableTreeNode top) { - - layerFeatures = new Hashtable>(); - - // Create a tree that allows one selection at a time. - final JTree tree = new JTree(top); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setVisibleRowCount(10); - - // Listen for when the selection changes. - tree.addTreeSelectionListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); - - if (node == null) - return; - - Object nodeInfo = node.getUserObject(); - if (node.isLeaf() && nodeInfo instanceof FeatureInfo) { - currentFeature = node; - // enable addToLayer button here. - addFeatureButton.setEnabled(true); - } else { - // disable addToLayer button here. - addFeatureButton.setEnabled(false); - } - } - }); - - if (playWithLineStyle) { - tree.putClientProperty("JTree.lineStyle", lineStyle); - } - - // Create the scroll pane and add the tree to it. - GridBagLayout outergridbag = new GridBagLayout(); - GridBagConstraints outerc = new GridBagConstraints(); - - JScrollPane treeView = new JScrollPane(tree); - - setLayout(outergridbag); - - outerc.fill = GridBagConstraints.BOTH; - outerc.anchor = GridBagConstraints.WEST; - outerc.insets = new Insets(10, 10, 10, 10); - outerc.gridx = GridBagConstraints.REMAINDER; - outerc.weighty = .75; - outerc.weightx = 1.0; - outergridbag.setConstraints(treeView, outerc); - add(treeView); - - // Create the configuration pane - JPanel configPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - configPanel.setLayout(gridbag); - - c.gridheight = GridBagConstraints.REMAINDER; - Component da = drawingAttributes.getGUI(); - gridbag.setConstraints(da, c); - configPanel.add(da); - - c.gridx = 1; - c.gridheight = 1; - c.gridy = 0; - c.fill = GridBagConstraints.HORIZONTAL; - c.insets = new Insets(0, 5, 0, 5); - addFeatureButton = new JButton("Add Feature"); - addFeatureButton.addActionListener(this); - addFeatureButton.setActionCommand(AddFeatureCmd); - gridbag.setConstraints(addFeatureButton, c); - configPanel.add(addFeatureButton); - addFeatureButton.setEnabled(false); - - clearFeaturesButton = new JButton("Clear Features"); - clearFeaturesButton.addActionListener(this); - clearFeaturesButton.setActionCommand(ClearFeaturesCmd); - c.gridy = GridBagConstraints.RELATIVE; - gridbag.setConstraints(clearFeaturesButton, c); - configPanel.add(clearFeaturesButton); - clearFeaturesButton.setEnabled(false); - - if (layer != null) { - createLayerButton = new JButton("Set Features on Layer"); - } else if (layerHandler != null) { - createLayerButton = new JButton("Create Layer"); - } else { - createLayerButton = new JButton("Print Properties"); - } - createLayerButton.addActionListener(this); - createLayerButton.setActionCommand(CreateLayerCmd); - gridbag.setConstraints(createLayerButton, c); - configPanel.add(createLayerButton); - createLayerButton.setEnabled(false); - - JPanel currentFeatureListPanel = PaletteHelper.createVerticalPanel(" Current Features: "); - currentFeatureList = new JTextArea(EMPTY_FEATURE_LIST); - currentFeatureList.setEditable(false); - JScrollPane featureListScrollPane = new JScrollPane(currentFeatureList); - featureListScrollPane.setPreferredSize(new Dimension(150, 10)); - currentFeatureListPanel.add(featureListScrollPane); - - c.gridx = 2; - c.gridy = 0; - c.weightx = 1.0; - c.anchor = GridBagConstraints.NORTHWEST; - c.gridheight = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.BOTH; - gridbag.setConstraints(currentFeatureListPanel, c); - configPanel.add(currentFeatureListPanel); - - GridBagLayout gridbag2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - JPanel namePanel = new JPanel(); - namePanel.setLayout(gridbag2); - - c2.weightx = 0; - c2.weighty = 0; - c2.anchor = GridBagConstraints.WEST; - JLabel nameLabel = new JLabel("Layer Name: "); - gridbag2.setConstraints(nameLabel, c2); - namePanel.add(nameLabel); - - c2.fill = GridBagConstraints.HORIZONTAL; - c2.weightx = 1.0; - c2.weighty = 1.0; - nameField = new JTextField(layerName); - gridbag2.setConstraints(nameField, c2); - namePanel.add(nameField); - - outerc.anchor = GridBagConstraints.WEST; - outerc.weighty = 0; - outergridbag.setConstraints(namePanel, outerc); - add(namePanel); - - outerc.fill = GridBagConstraints.HORIZONTAL; - outerc.weighty = .25; - outerc.anchor = GridBagConstraints.CENTER; - outergridbag.setConstraints(configPanel, outerc); - add(configPanel); - - DrawingAttributes oldDrawingAttributes = (DrawingAttributes) drawingAttributes.clone(); - - if (layer != null) { - // initialize currentFeatures list with anything the layer might - // have - // already. - LayerGraphicWarehouseSupport warehouse = layer.getWarehouse(); - List initialFeatureList = warehouse.getFeatures(); - - for (String initialFeature : initialFeatureList) { - // For each feature, find the corresponding tree node - // and perform the AddFeatureCmd command - loadCurrentFeatures(top, initialFeature, warehouse); - } - } - - oldDrawingAttributes.setTo(drawingAttributes); - } - - protected void loadCurrentFeatures(DefaultMutableTreeNode top, String featureName, - LayerGraphicWarehouseSupport warehouse) { - @SuppressWarnings("rawtypes") - Enumeration treeEnum = top.children(); - while (treeEnum.hasMoreElements()) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeEnum.nextElement(); - Object obj = node.getUserObject(); - // Debug.output(node.getUserObject().getClass().getName() - // + ", " + node.getUserObject()); - if (obj instanceof FeatureInfo) { - FeatureInfo fi = (FeatureInfo) obj; - if (fi.featureName.equals(featureName)) { - currentFeature = node; - - if (warehouse instanceof VPFFeatureGraphicWarehouse) { - FeatureDrawingAttributes fda = ((VPFFeatureGraphicWarehouse) warehouse) - .getAttributesForFeature(featureName); - if (fda != null) { - fda.setTo(drawingAttributes); - } - } - - actionPerformed(new ActionEvent(this, 0, AddFeatureCmd)); - } - } else { - loadCurrentFeatures(node, featureName, warehouse); - } - } - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - - if (command == AddFeatureCmd) { - - if (currentFeature != null) { - FeatureInfo feature = (FeatureInfo) currentFeature.getUserObject(); - // Save the current DrawingAttributes - // settings for the feature. - feature.drawingAttributes = (DrawingAttributes) drawingAttributes.clone(); - featureList.add(currentFeature); - - String cfl = currentFeatureList.getText(); - if (featureList.size() == 1) { - cfl = feature.toString(); - } else { - cfl += "\n" + feature.toString(); - } - - currentFeatureList.setText(cfl); - - currentFeature = null; - createLayerButton.setEnabled(true); - addFeatureButton.setEnabled(false); - clearFeaturesButton.setEnabled(true); - } else { - Debug.error("No feature selected"); - } - } else if (command == ClearFeaturesCmd) { - featureList.clear(); - layerFeatures.clear(); - - createLayerButton.setEnabled(false); - addFeatureButton.setEnabled(false); - clearFeaturesButton.setEnabled(false); - currentFeatureList.setText(EMPTY_FEATURE_LIST); - } else if (command == CreateLayerCmd) { - if (featureList.isEmpty()) { - Debug.error("No features selected for new VPFLayer"); - createLayerButton.setEnabled(false); - clearFeaturesButton.setEnabled(false); - return; - } - - String name = nameField.getText(); - if (name == null) { - name = "VPFLayer"; - } - - String propertyPrefix; - if (layer != null) { - propertyPrefix = PropUtils.getScopedPropertyPrefix(layer); - } else { - propertyPrefix = PropUtils.getScopedPropertyPrefix(name.replace(' ', '_').toLowerCase()); - } - - if (layer != null) { - layerProperties = layer.getProperties(null); - } else { - layerProperties = new Properties(); - } - - layerCoverageTypes.clear(); - layerFeatureTypes.clear(); - layerFeatures.clear(); - - if (standAlone) { - layerProperties.put(propertyPrefix + "class", "com.bbn.openmap.layer.vpf.VPFLayer"); - } - - layerProperties.put(propertyPrefix + Layer.PrettyNameProperty, name); - layerProperties.put(propertyPrefix + VPFLayer.pathProperty, paths); - layerProperties.put(propertyPrefix + VPFLayer.searchByFeatureProperty, - new Boolean(searchByFeature).toString()); - - // Now, build up coverageTypeProperty and - // featureTypesProperty - // from the linked list of featureNodes... - for (DefaultMutableTreeNode node : featureList) { - addPropertiesForFeature(node, propertyPrefix, layerProperties); - } - - // coverageTypeProperty and featureTypesProperty should - // be built from above iteration, should push them into - // properties... - // List the coverages - layerProperties.put(propertyPrefix + VPFLayer.coverageTypeProperty, - stringTogether(layerCoverageTypes.iterator())); - // List area/edge/point/text, whatever has been set up - // with the chosen features. - layerProperties.put(propertyPrefix + VPFLayer.featureTypesProperty, - stringTogether(layerFeatureTypes.iterator())); - - // OK, now go through the layerFeature lists for - // area/edge/text/point and add the property listing the - // features associated with each type. - for (String key : layerFeatures.keySet()) { - HashSet featureSet = layerFeatures.get(key); - layerProperties.put(propertyPrefix + key, stringTogether(featureSet.iterator())); - } - - if (layer != null) { - layer.setConfigSettings(layer.getPropertyPrefix(), layerProperties); - } else if (layerHandler != null) { - VPFLayer layer = new VPFLayer(); - layer.setProperties(propertyPrefix, layerProperties); - layerHandler.addLayer(layer); - } else { - printProperties(layerProperties); - } - - // featureList.clear(); - // - // currentFeatureList.setText(EMPTY_FEATURE_LIST); - // createLayerButton.setEnabled(false); - // addFeatureButton.setEnabled(false); - // clearFeaturesButton.setEnabled(false); - } - } - - private void addPropertiesForFeature(DefaultMutableTreeNode featureNode, String propertyPrefix, - Properties layerProperties) { - FeatureInfo feature = (FeatureInfo) featureNode.getUserObject(); - CoverageInfo coverage = (CoverageInfo) ((DefaultMutableTreeNode) featureNode.getParent()).getUserObject(); - - // Adding to coverage list - layerCoverageTypes.add(coverage.coverageName); - // Adding area, edge, text, point to list if it doesn't exist. - layerFeatureTypes.add(feature.featureTypeString); - - // adding feature name to appropriate edge/area/text/point - // list - HashSet featureSet = layerFeatures.get(feature.featureTypeString); - - if (featureSet == null) { - // If it's the first category type for the feature - featureSet = new HashSet(); - layerFeatures.put(feature.featureTypeString, featureSet); - } - // Add feature to feature type list for edge/area/text/point - featureSet.add(feature.featureName); - feature.drawingAttributes.setPropertyPrefix(propertyPrefix + feature.featureName); - feature.drawingAttributes.getProperties(layerProperties); - } - - private void printProperties(Properties props) { - Enumeration keys = props.propertyNames(); - System.out.println("######## START Properties ########"); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - System.out.println(key + "=" + props.getProperty(key)); - } - System.out.println("######## END Properties ########"); - } - - private String stringTogether(Iterator it) { - StringBuffer buf = null; - - while (it.hasNext()) { - String val = it.next(); - - if (buf == null) { - buf = new StringBuffer(val); - } else { - buf.append(" ").append(val); - } - } - - if (buf == null) { - return ""; - } else { - return buf.toString(); - } - } - - protected static class FeatureInfo { - public String featureName; - public String featureDescription; - public String featureTypeString; - public int featureType; - public CoverageTable.FeatureClassRec record; - public DrawingAttributes drawingAttributes; - - public FeatureInfo(CoverageTable ct, CoverageTable.FeatureClassRec fcr) { - record = fcr; - - featureTypeString = UNKNOWN; - if (fcr.type == CoverageTable.TEXT_FEATURETYPE) { - featureTypeString = TEXT; - } else if (fcr.type == CoverageTable.EDGE_FEATURETYPE) { - featureTypeString = EDGE; - } else if (fcr.type == CoverageTable.AREA_FEATURETYPE) { - featureTypeString = AREA; - } else if (fcr.type == CoverageTable.UPOINT_FEATURETYPE) { - FeatureClassInfo fci = ct.getFeatureClassInfo(fcr.feature_class); - if (fci == null) { - featureTypeString = POINT; - } else if (fci.getFeatureType() == CoverageTable.EPOINT_FEATURETYPE) { - featureTypeString = EPOINT; - } else if (fci.getFeatureType() == CoverageTable.CPOINT_FEATURETYPE) { - featureTypeString = CPOINT; - } else { - featureTypeString = POINT; - } - } else if (fcr.type == CoverageTable.COMPLEX_FEATURETYPE) { - featureTypeString = COMPLEX; - } - - featureType = fcr.type; - featureName = fcr.feature_class; - featureDescription = fcr.description; - } - - public String toString() { - return featureDescription + " (" + featureTypeString + ")"; - } - } - - protected static class CoverageInfo { - public String coverageName; - public String coverageDescription; - - public CoverageInfo(CoverageAttributeTable cat, String covName) { - coverageName = covName; - coverageDescription = cat.getCoverageDescription(covName); - } - - public String toString() { - return coverageDescription; - } - } - - private boolean addFeatureNodes(DefaultMutableTreeNode coverageNode, CoverageTable ct) { - int numFeatures = 0; - Hashtable info = ct.getFeatureTypeInfo(); - for (CoverageTable.FeatureClassRec fcr : info.values()) { - - if (fcr.type == CoverageTable.SKIP_FEATURETYPE) { - continue; - } - - coverageNode.add(new DefaultMutableTreeNode(new FeatureInfo(ct, fcr))); - numFeatures++; - } - return numFeatures > 0; - } - - private void addCoverageNodes(DefaultMutableTreeNode libraryNode, CoverageAttributeTable cat) { - String[] coverages = cat.getCoverageNames(); - for (int covi = 0; covi < coverages.length; covi++) { - String coverage = coverages[covi]; - CoverageInfo covInfo = new CoverageInfo(cat, coverage); - DefaultMutableTreeNode covNode = new DefaultMutableTreeNode(covInfo); - if (showAll || addFeatureNodes(covNode, cat.getCoverageTable(coverage)) || !cat.isTiledData()) { - libraryNode.add(covNode); - } - } - } - - private void createNodes(DefaultMutableTreeNode top, LibrarySelectionTable lst) throws FormatException { - - DefaultMutableTreeNode category = null; - - for (String library : lst.getLibraryNames()) { - category = new DefaultMutableTreeNode(library); - CoverageAttributeTable cat = lst.getCAT(library); - top.add(category); - addCoverageNodes(category, cat); - } - } - - private void createNodes(DefaultMutableTreeNode top, String[] dataPaths) throws FormatException { - - for (int i = 0; i < dataPaths.length; i++) { - String rootpath = dataPaths[i]; - LibrarySelectionTable lst = new LibrarySelectionTable(rootpath); - createNodes(top, lst); - } - } - - public static void printFeatures(String[] dataPaths) { - TreeMap features = new TreeMap(); - - for (int i = 0; i < dataPaths.length; i++) { - String rootpath = dataPaths[i]; - try { - LibrarySelectionTable lst = new LibrarySelectionTable(rootpath); - - for (String libraryName : lst.getLibraryNames()) { - - CoverageAttributeTable cat = lst.getCAT(libraryName); - - String[] coverages = cat.getCoverageNames(); - for (int covi = 0; covi < coverages.length; covi++) { - String coverage = coverages[covi]; - - CoverageTable ct = cat.getCoverageTable(coverage); - Hashtable info = ct.getFeatureTypeInfo(); - for (CoverageTable.FeatureClassRec fcr : info.values()) { - - if (fcr.type == CoverageTable.SKIP_FEATURETYPE) { - continue; - } - - FeatureInfo fi = new FeatureInfo(ct, fcr); - if (!features.containsKey(fi.featureName)) { - features.put(fi.featureName, fi); - } - } - } - } - - } catch (FormatException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - if (!features.isEmpty()) { - for (Entry entry : features.entrySet()) { - System.out.println(entry.getKey() + ": " + entry.getValue()); - } - } - - } - - public static void createLayer(String[] vpfPaths, LayerHandler layerHandler, String layerName) { - launchFrame(new VPFConfig(vpfPaths, layerHandler, layerName), false); - } - - public static void createLayer(LibraryBean libraryBean, LayerHandler layerHandler, String layerName) { - launchFrame(new VPFConfig(libraryBean, layerHandler, layerName), false); - } - - protected static void launchFrame(JComponent content, boolean exitOnClose) { - JFrame frame = new JFrame("Create VPF Data Layer"); - - frame.getContentPane().add(content); - if (exitOnClose) { - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - } - - frame.pack(); - frame.setVisible(true); - } - - public static void main(String[] args) { - ArgParser argParser = new ArgParser("VPFConfig"); - argParser.add("features", "print available feature codes and descriptions, given paths to VPF directories", - ArgParser.TO_END); - argParser.add("path", "space-separated paths to VPF directories", ArgParser.TO_END); - - if (!argParser.parse(args)) { - argParser.printUsage(); - System.exit(0); - } - - String arg[]; - arg = argParser.getArgValues("features"); - if (arg != null) { - VPFConfig.printFeatures(arg); - System.exit(0); - } - - arg = argParser.getArgValues("path"); - if (arg != null) { - VPFConfig vpfc = new VPFConfig(arg, null, "VPF Layer", true); - launchFrame(vpfc, true); - } else { - argParser.printUsage(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureCache.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureCache.java deleted file mode 100644 index 4ae490d0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureCache.java +++ /dev/null @@ -1,227 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFFeatureCache.java,v $ -// $RCSfile: VPFFeatureCache.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.logging.Level; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The VPFFeatureCache is an extended CacheHandler that caches OMGraphicLists - * representing a specific feature contained in a CoverageTile. It's used by the - * VPFCachedFeatureGraphicWarehouse, which in turn is used by the LibraryBean as - * a central warehouse. - */ -public class VPFFeatureCache extends CacheHandler { - - /** - * Create a VPFFeatureCache of the default maximum size. - */ - public VPFFeatureCache() { - super(); - } - - /** - * Create a VPFFeatureCache of the specified maximum size. - */ - public VPFFeatureCache(int maxSize) { - super(maxSize); - } - - /** - * Adds an OMGraphic to a list, signified by the feature type and the table. - * The PrimitiveTable provides an identifying tile path. - * - * @param omg OMGraphic to add - * @param featureType the feature code of the OMGraphic - * @param pt the PrimitiveTable containing the path to the CoverageTile. - */ - protected synchronized void addToCachedList(String libraryName, OMGraphic omg, - String featureType, - PrimitiveTable pt, String type) { - String key = createTableCacheKey(libraryName, featureType, pt.getTileDirectory() - .getPath()); - FeatureCacheGraphicList omgl = (FeatureCacheGraphicList) get(key); - omgl.add(omg); - } - - /** - * Create an identifying key from the feature type and tile path. - */ - public static String createTableCacheKey(String libraryName, String featureType, String tilePath) { - return libraryName + "-" + featureType + "-" + tilePath; - } - - /** - * Returns true if the features from a tile (as described by the key) - * existed and was added to the warehouse graphics list. Returns false if - * the list needs to be created and the contents read in from data files. In - * both cases the OMGraphicList for the tile/feature is loaded into the - * cache, the return value is a signal to the caller that the list must be - * populated or not. - * - * @param featureType the feature type code. - * @param tilePath the relative path to the tile file. - * @param requestor the OMGraphicList used to contain cached lists. The - * cached list will for the featureType/path code will be added to - * this list, regardless of whether it's been populated or not. The - * requestor list will be returned when the warehouse is asked for - * the graphics list. - * @return OMGraphicList instead of returning a boolean, we should return - * the empty cache OMGraphicList that needs to be loaded. A returned - * list is the signal that the tile needs to be read. Also, the - * cached list has just been added to the requestor list. If the - * list is in the cache, it will not be returned from this method - * but only added to the requestor list. - */ - public synchronized FeatureCacheGraphicList loadCachedGraphicList(String libraryName, - String featureType, - String tilePath, - OMGraphicList requestor) { - - String key = createTableCacheKey(libraryName, featureType, tilePath); - boolean exists = (searchCache(key) != null); - - // Will retrieve the old list if it exists, create a new one - // if it doesn't. - - FeatureCacheGraphicList fcgl = (FeatureCacheGraphicList) get(key, - VPFUtil.getTypeForFeatureCode(featureType)); - if (fcgl.getFeatureName() == null) { - fcgl.setFeatureName(featureType); - } - requestor.add(fcgl); - - // Might want to set the current attributes for the existing - // contents of the list in case they were changed by the user. - - FeatureCacheGraphicList ret = null; - if (!exists) { - logger.fine("tile list didn't exist in cache, returning it to be loaded."); - ret = fcgl; - } - return ret; - } - - /** - * Query that the CoverageTable makes to decide whether to read the file - * contents or to used the cached version. - * - * @param currentFeature the feature type - * @param currentTile the tile directory - * @param requestor the OMGraphicList to add the cached list to. If the - * CoverageTable reads the data files, the OMGraphics created from - * the files will be added to the list added to the requestor. - * @return true if the CoverageTable needs to read the data files. - */ - public synchronized FeatureCacheGraphicList needToFetchTileContents(String libraryName, - String currentFeature, - TileDirectory currentTile, - OMGraphicList requestor) { - - // Instead of returning a boolean, loadCachedGraphicList is going - // to return a cache object (empty OMGraphicList) that has just been - // created and needs to be filled. This list should be returned so it - // can be loaded. - FeatureCacheGraphicList listThatNeedsToBeLoaded = loadCachedGraphicList(libraryName, currentFeature, - currentTile.getPath(), - requestor); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Loaded Cached List: " - + createTableCacheKey(libraryName, currentFeature, currentTile.getPath()) - + (listThatNeedsToBeLoaded == null ? ", cached" - : ", not cached")); - } - - return listThatNeedsToBeLoaded; - } - - /** - * Additional get method that will call a load() method that takes into - * account the featureType. The regular get() method will not be used, - * unless something else calls it, which is not advised. - * - * @param key the created key for cached list, see createTableCacheKey - * @param featureType the kind of feature, VPFUtil.Area, VPFUtil.Edge, - * VPFUtil.Point or VPFUtil.Text. - */ - public Object get(String key, String featureType) { - CacheObject ret = searchCache(key); - if (ret != null) - return ret.obj; - - ret = load(key, featureType); - if (ret == null) - return null; - - replaceLeastUsed(ret); - return ret.obj; - } - - /** - * CacheHandler method to load the new OMGraphicLists - * (FeatureCacheGraphicLists). Shouldn't be used because the - * FeatureCacheGraphicList type will be unknown. This method is only defined - * to implement the CacheHandler abstract method. - */ - public CacheObject load(Object key) { - return load(key.toString(), null); - } - - /** - * CacheHandler method to load the new OMGraphicLists - * (FeatureCacheGraphicLists). - */ - public CacheObject load(String key, String featureType) { - if (key != null && featureType != null) { - return new VPFListCacheObject(key, FeatureCacheGraphicList.createForType(featureType)); - } - return null; - } - - /** - * CacheObject used by VPFFeatureCache. - */ - public static class VPFListCacheObject extends CacheObject { - /** - * Construct a VPFListCacheObject, just calls superclass constructor - * - * @param id passed to superclass - * @param obj passed to superclass - */ - public VPFListCacheObject(String id, OMGraphicList obj) { - super(id, obj); - } - - /** - */ - protected void finalize() { - ((OMGraphicList) obj).clear(); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java deleted file mode 100644 index 3d719c456..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java +++ /dev/null @@ -1,303 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java,v $ -// $RCSfile: VPFFeatureGraphicWarehouse.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics. It's different in that it - * expects that the feature type has already been checked at the CoverageTable - * level, and should just build whatever graphic is sent to it. Called from - * within CoverageTable.drawFeatures(). - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public class VPFFeatureGraphicWarehouse extends VPFLayerGraphicWarehouse implements - VPFFeatureWarehouse { - - public final static String DEFAULT = "DEFAULT"; - protected Hashtable featureDrawingAttributes; - - /** - * - */ - public VPFFeatureGraphicWarehouse() { - super(); - } - - /** - * Called from super class constructor. - * - */ - protected void initDrawingAttributes() { - drawingAttributes = new FeatureDrawingAttributes(); - } - - /** - * Set properties of the warehouse. - * - * @param prefix the prefix to use for looking up properties. - * @param props the properties file to look at. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - createFeatureDrawingAttributes(prefix, props, getFeatures()); - } - - /** - * From the initial properties, create the hashtable that holds the - * DrawingAttributes object for each feature type. The feature name is the - * key to the drawing attributes for that feature (roadl). - * - * @param prefix the prefix used for the properties - * @param props the properties object - * @param features a List of Strings, each representing a feature type that - * when appended to the prefix, will serve as a prefix for the - * drawing attributes settings for that feature. With a layer prefix - * of vmapRoads, and a feature type of roadl, the line color - * attribute property looked for will be vmapRoads.roadl.lineColor. - */ - public void createFeatureDrawingAttributes(String prefix, Properties props, - List features) { - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - featureDrawingAttributes = new Hashtable(); - if (drawingAttributes != null) { - featureDrawingAttributes.put(DEFAULT, drawingAttributes); - } else { - drawingAttributes = new FeatureDrawingAttributes(); - } - - for (String feature : features) { - FeatureDrawingAttributes da = (FeatureDrawingAttributes) drawingAttributes.clone(); - da.setStroke(drawingAttributes.cloneBasicStroke()); - da.setProperties(realPrefix + feature, props); - featureDrawingAttributes.put(feature, da); - } - } - - /** - * Don't do this lightly, or everything will be colored the default value. - * The keys to the Hashtable should be the feature type names, and the - * values should be the DrawingAttributes for that feature. - */ - public void setFeatureDrawingAttributes(Hashtable attributes) { - featureDrawingAttributes = attributes; - } - - /** - * Get the Hashtable used for the feature DrawingAttributes lookup. - */ - public Hashtable getFeatureDrawingAttributes() { - return featureDrawingAttributes; - } - - /** - * Return the GUI for certain warehouse attributes. By default, return the - * GUI for the DrawingAttributes object being used for rendering attributes - * of the graphics. - * - * @param lst LibrarySelectionTable to use to get information about the - * data, if needed. - */ - public Component getGUI(LibrarySelectionTable lst) { - - JTabbedPane jtp = new JTabbedPane(); - - jtp.addTab(DEFAULT, null, drawingAttributes.getGUI(), "General Attributes"); - - for (String currentFeature : getFeatures()) { - DrawingAttributes da = getAttributesForFeature(currentFeature); - - if (da != null) { - String desc = null; - try { - desc = lst.getDescription(currentFeature); - } catch (FormatException fe) { - } - - if (desc == null) { - desc = "Feature Description Unavailable"; - } - JPanel featurePanel = new JPanel(); - featurePanel.add(da.getGUI()); - - jtp.addTab(currentFeature, null, featurePanel, desc); - } - } - return jtp; - } - - /** - * Given a feature type, get the DrawingAttributes for that feature. Should - * be very unlikely to get a null value back. - */ - public FeatureDrawingAttributes getAttributesForFeature(String featureType) { - if (featureType != null) { - FeatureDrawingAttributes ret; - - if (featureDrawingAttributes != null) { - ret = (FeatureDrawingAttributes) featureDrawingAttributes.get(featureType); - if (ret == null) { - ret = (FeatureDrawingAttributes) drawingAttributes; - } - - } else { - ret = (FeatureDrawingAttributes) drawingAttributes; - } - - return ret; - - } else { - return (FeatureDrawingAttributes) drawingAttributes; - } - } - - /** - * - */ - public OMGraphic createArea(CoverageTable covtable, AreaTable areatable, List facevec, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon, - String featureType, int primID) { - - List ipts = new ArrayList(); - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return null; - } - if (totalSize == 0) { - return null; - } - - OMPoly py = createAreaOMPoly(ipts, totalSize, ll1, ll2, dpplat, dpplon, covtable.doAntarcticaWorkaround); - - // getAttributesForFeature(featureType).setTo(py); - //int id = ((Integer) facevec.get(0)).intValue(); - setAttributesForFeature(py, covtable, featureType, primID); - // HACK to get tile boundaries to not show up for areas. - // py.setLinePaint(py.getFillPaint()); - // py.setSelectPaint(py.getFillPaint()); - py.setLinePaint(OMColor.clear); - py.setSelectPaint(OMColor.clear); - - addArea(py); - return py; - } - - protected String info = null; - - /** - * - */ - public OMGraphic createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon, - CoordFloatString coords, String featureType, int primID) { - - //int id = ((Integer) edgevec.get(0)).intValue(); - - OMPoly py = createEdgeOMPoly(coords, ll1, ll2, dpplat, dpplon); - setAttributesForFeature(py, c, featureType, primID); - py.setFillPaint(OMColor.clear); - py.setIsPolygon(false); - addEdge(py); - return py; - } - - /** - * @param omg The OMGraphic owning the attributes. - * @param c the CoverageTable for the feature. - * @param featureType the type of Feature. - * @param id ID of the OMGraphic. - */ - protected void setAttributesForFeature(OMGraphic omg, CoverageTable c, String featureType, - int id) { - FeatureDrawingAttributes fda = getAttributesForFeature(featureType); - - if (fda.getFci() == null) { - fda.setFci(c.getFeatureClassInfo(featureType)); - } - - fda.setTo(omg, id); - } - - /** - * - */ - public OMGraphic createText(CoverageTable c, TextTable texttable, List textvec, - double latitude, double longitude, String text, String featureType, - int primID) { - - OMText txt = createOMText(text, latitude, longitude); - //int id = ((Integer) textvec.get(0)).intValue(); - setAttributesForFeature(txt, c, featureType, primID); - // getAttributesForFeature(featureType).setTo(txt); - addText(txt); - return txt; - } - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public OMGraphic createNode(CoverageTable c, NodeTable t, List nodeprim, - double latitude, double longitude, boolean isEntityNode, - String featureType, int primID) { - OMPoint pt = createOMPoint(latitude, longitude); - // int id = ((Integer) nodeprim.get(0)).intValue(); - setAttributesForFeature(pt, c, featureType, primID); - // getAttributesForFeature(featureType).setTo(pt); - addPoint(pt); - return pt; - } - - public boolean needToFetchTileContents(String libraryName, String currentFeature, - TileDirectory currentTile) { - return true; - } - - public static void main(String argv[]) { - new VPFFeatureGraphicWarehouse(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureInfoHandler.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureInfoHandler.java deleted file mode 100644 index 196d56e84..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureInfoHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * An object the VPFFeatureLayer can use to manage how attribute information is - * displayed for OMGraphics representing the feature. - * - * @author dietrick - */ -public interface VPFFeatureInfoHandler { - - void updateInfoForOMGraphic(OMGraphic omg, FeatureClassInfo fci, List fcirow); - - /** - * Check to see if the omg should react to mouse movement events. - * - * @param omg - * @return true for tooltips, infoline, highlight actions. - */ - boolean isHighlightable(OMGraphic omg); - - /** - * Check to see if the OMGraphic should be specially painted in a mouse over. - * - * @param omg - * @return true if omg should be repainted with its select color. - */ - boolean shouldPaintHighlight(OMGraphic omg); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureLayer.java deleted file mode 100644 index c86568746..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureLayer.java +++ /dev/null @@ -1,395 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFLayer.java,v $ -// $RCSfile: VPFLayer.java,v $ -// $Revision: 1.21 $ -// $Date: 2006/03/06 16:13:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * The VPFFeaureLayer renders VPF data with features being rendered in the order - * and style specified by the GeoSym specification. It uses the - * VPFAutoFeatureWarehouse, which knows how to use GeoSym data files to manage - * desired features. These data files can be modified to adjust which features - * are displayed. - * - * The properties for this layer are: - * - *
- * vpfPath=path to vpf library directory, parent of DHT/LAT file.  Multiple paths can be specified, separated by ;
- * libraryName=name of library to use, since multiple libraries can be specified in a top level vpf directory.  Wildcards accepted.
- * 
- * # VFPAutoFeatureGraphicWarehouse options:
- * cgmDirectory=parent directory of cgm files used for symbology
- * faccLookupFile=path to csv file that ties FACC codes to symbol file names
- * # The priority file is the file to adjust to customize display...
- * priorityFile=path to csv file specifying which FACC codes, types should be rendered and in what order.
- * featureInfoHandler=class of object to handle attributes
- * 
- * - * @author dietrick - */ -public class VPFFeatureLayer extends OMGraphicHandlerLayer implements ProjectionListener, ActionListener, Serializable { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFFeatureLayer"); - - /** property extension used to set the VPF root directory */ - public static final String pathProperty = "vpfPath"; - /** Property for setting VPF cutoff scale */ - public static final String cutoffScaleProperty = "cutoffScale"; - /** Property for setting VPF library name to use */ - public static final String LibraryNameProperty = "libraryName"; - /** the object that knows all the nitty-gritty vpf stuff */ - protected transient LibrarySelectionTable lst; - /** our own little graphics factory */ - protected transient VPFAutoFeatureGraphicWarehouse warehouse; - - /** - * hang onto prefix used to initialize warehouse in setProperties() - */ - protected String prefix; - /** hang onto properties file used to initialize warehouse */ - protected Properties props; - - /** the path to the root VPF directory */ - protected String[] dataPaths = null; - - protected int cutoffScale = LibrarySelectionTable.DEFAULT_BROWSE_CUTOFF; - /** the library name to focus on */ - protected String libraryName = null; - - /** - * Construct a VPF layer. - */ - public VPFFeatureLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setMouseModeIDsForEvents(new String[] { "Gestures" }); - warehouse = new VPFAutoFeatureGraphicWarehouse(); - } - - /** - * Construct a VPFLayer, and sets its name. - * - * @param name the name of the layer. - */ - public VPFFeatureLayer(String name) { - this(); - setName(name); - } - - /** - * Another way to set the parameters of the VPFLayer. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - setAddToBeanContext(true); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - cutoffScale = PropUtils.intFromProperties(props, realPrefix + cutoffScaleProperty, cutoffScale); - - libraryName = props.getProperty(realPrefix + LibraryNameProperty, libraryName); - - String path[] = PropUtils.initPathsFromProperties(props, realPrefix + pathProperty); - - if (path != null && path.length != 0) { - setPath(path); - } - - // need to save these so we can call setProperties on the - // warehouse, - // which we probably can't construct yet - this.prefix = prefix; - this.props = props; - - if (warehouse != null) { - warehouse.setProperties(prefix, props); - warehouse.setUseLibraries(PropUtils.parseSpacedMarkers(libraryName)); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(realPrefix + cutoffScaleProperty, Integer.toString(cutoffScale)); - - StringBuffer paths = new StringBuffer(); - String[] ps = getPath(); - - for (int i = 0; ps != null && i < ps.length; i++) { - paths.append(ps[i]); - if (i < ps.length - 1) - paths.append(";"); - } - - props.put(realPrefix + pathProperty, paths.toString()); - - // For the library in a vpf package - props.put(realPrefix + LibraryNameProperty, PropUtils.unnull(libraryName)); - - if (warehouse != null) { - warehouse.getProperties(props); - } - - return props; - } - - /** Where we store our default properties once we've loaded them. */ - private Properties defaultProps; - - /** - * Return our default properties for vpf land. - */ - public Properties getDefaultProperties() { - if (defaultProps == null) { - try { - InputStream in = VPFFeatureLayer.class.getResourceAsStream("defaultVPFlayers.properties"); - // use a temporary so other threads won't see an - // empty properties file - Properties tmp = new Properties(); - if (in != null) { - tmp.load(in); - in.close(); - } else { - logger.warning("can't load default properties file"); - // just use an empty properties file - } - defaultProps = tmp; - } catch (IOException io) { - logger.warning("can't load default properties: " + io); - defaultProps = new Properties(); - } - } - return defaultProps; - } - - /** - * Set the data path to a single place. - */ - public void setPath(String newPath) { - logger.fine("setting paths to " + newPath); - setPath(new String[] { newPath }); - } - - /** - * Set the data path to multiple places. - */ - public void setPath(String[] newPaths) { - dataPaths = newPaths; - - lst = null; - initLST(); - } - - /** - * Returns the list of paths we use to look for data. - * - * @return the list of paths. Don't modify the array! - */ - public String[] getPath() { - return dataPaths; - } - - /** - * initialize the library selection table. - */ - protected void initLST() { - logger.fine("initializing Library Selection Table (LST)"); - - if (lst == null) { - if (dataPaths == null) { - logger.info("VPFLayer|" + getName() + ": path not set"); - } else { - logger.fine("VPFLayer.initLST(dataPaths)"); - lst = new LibrarySelectionTable(); - lst.setCutoffScale(cutoffScale); - } - } - - try { - lst.withDataPath(dataPaths); - } catch (com.bbn.openmap.io.FormatException f) { - StringBuilder sb = new StringBuilder("VPFLayer|").append(getName()).append(": problem with path: "); - - if (dataPaths != null) { - for (String dPath : dataPaths) { - sb.append("\n\t").append(dPath); - } - } else { - sb.append(" NO DATA PATHS SPECIFIED"); - } - - logger.warning(sb.toString()); - } - } - - public VPFAutoFeatureGraphicWarehouse getWarehouse() { - return warehouse; - } - - /** - * If the warehouse gets set as a result of this method being called, the - * properties will beed to be reset on it. - * - * @param sbf Search by features. - */ - public void checkWarehouse(boolean sbf) { - if (warehouse == null) { - logger.fine("need to create warehouse"); - warehouse = new VPFAutoFeatureGraphicWarehouse(); - } - } - - /** - * Create the OMGraphicList to use on the map. OMGraphicHandler methods call - * this. - */ - public synchronized OMGraphicList prepare() { - if (lst == null) { - try { - initLST(); - } catch (IllegalArgumentException iae) { - logger.warning( - "VPFLayer.prepare: Illegal Argument Exception.\n\nPerhaps a file not found. Check to make sure that the paths to the VPF data directories are the parents of \"lat\" or \"lat.\" files. \n\n" - + iae); - return null; - } - - if (lst == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("VPFLayer| " + getName() + " prepare(), Library Selection Table not set."); - } - - return null; - } - } - - if (warehouse == null) { - StringBuffer dpb = new StringBuffer(); - if (dataPaths != null) { - for (int num = 0; num < dataPaths.length; num++) { - if (num > 0) { - dpb.append(":"); - } - dpb.append(dataPaths[num]); - } - } - - logger.warning("VPFLayer.getRectangle: Data path probably wasn't set correctly (" + dpb.toString() - + "). The warehouse not initialized."); - return null; - } - - Projection p = getProjection(); - - if (p == null || !(p instanceof GeoProj)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("VPFLayer.getRectangle() called with a projection (" + p - + ") set in the layer, which isn't being handled."); - } - return new OMGraphicList(); - } - - LatLonPoint ll1 = p.getUpperLeft(); - LatLonPoint ll2 = p.getLowerRight(); - - // Check both dynamic args and palette values when - // deciding what to draw. - if (logger.isLoggable(Level.FINE)) { - logger.fine("calling draw with boundaries: " + ll1 + " " + ll2); - } - long start = System.currentTimeMillis(); - - OMGraphicList omgList = new OMGraphicList(); - try { - omgList = warehouse.getFeatures(lst, ll1, ll2, p, omgList); - } catch (FormatException fe) { - logger.warning("Caught FormatException reading features: " + fe.getMessage()); - } - - long stop = System.currentTimeMillis(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("read time: " + ((stop - start) / 1000d) + " seconds"); - } - - return omgList; - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphicConstants.TOOLTIP); - } - - public String getInfoText(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphicConstants.INFOLINE); - } - - public boolean isHighlightable(OMGraphic omg) { - VPFFeatureInfoHandler vfih = warehouse.getFeatInfoHandler(); - if (vfih != null) { - return vfih.isHighlightable(omg); - } - - return false; - } - - /** - * Fleeting change of appearance for mouse movements over an OMGraphic. - */ - public void highlight(OMGraphic omg) { - VPFFeatureInfoHandler vfih = warehouse.getFeatInfoHandler(); - if (vfih != null && vfih.shouldPaintHighlight(omg)) { - super.highlight(omg); - } - } - - /** - * Notification to set OMGraphic to normal appearance. - */ - public void unhighlight(OMGraphic omg) { - VPFFeatureInfoHandler vfih = warehouse.getFeatInfoHandler(); - if (vfih != null && vfih.shouldPaintHighlight(omg)) { - super.unhighlight(omg); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureWarehouse.java deleted file mode 100644 index 57891d395..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFFeatureWarehouse.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFFeatureWarehouse.java,v $ -// $RCSfile: VPFFeatureWarehouse.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Define an interface for a Graphic Factory for graphics read from VPF. - */ -public interface VPFFeatureWarehouse extends VPFWarehouse { - - public boolean needToFetchTileContents(String libraryName, String currentFeature, - TileDirectory currentTile); - - /** - * - */ - public OMGraphic createArea(CoverageTable covtable, AreaTable areatable, List facevec, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon, - String featureType, int primID); - - /** - * - */ - public OMGraphic createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, double dpplon, - CoordFloatString coords, String featureType, int primID); - - /** - * - */ - public OMGraphic createText(CoverageTable c, TextTable texttable, List textvec, - double latitude, double longitude, String text, String featureType, - int primID); - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public OMGraphic createNode(CoverageTable c, NodeTable t, List nodeprim, - double latitude, double longitude, boolean isEntityNode, - String featureType, int primID); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java deleted file mode 100644 index a3c82e390..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java +++ /dev/null @@ -1,98 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFGraphicWarehouse.java,v $ -// $RCSfile: VPFGraphicWarehouse.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.List; - -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Define an interface for a Graphic Factory for graphics read from - * VPF. - */ -public interface VPFGraphicWarehouse extends VPFWarehouse { - /** - * Method called by the VPF reader code to construct an area - * feature. - * - * @param c the coverage table for this area - * @param a the areatable being parsed - * @param l the record read from the area table - * @param dpplat threshold for latitude thinning (passed to - * warehouse) - * @param dpplon threshold for longitude thinngin (passed to - * warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - */ - public void createArea(CoverageTable c, AreaTable a, List l, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, - double dpplon); - - /** - * Method called by the VPF reader code to construct an edge - * feature. - * - * @param c the coverage table for this edge - * @param e the edgetable being parsed - * @param l the record read from the edge table - * @param dpplat threshold for latitude thinning (passed to - * warehouse) - * @param dpplon threshold for longitude thinngin (passed to - * warehouse) - * @param ll1 upperleft of selection region (passed to warehouse) - * @param ll2 lowerright of selection region (passed to warehouse) - */ - public void createEdge(CoverageTable c, EdgeTable e, List l, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, - double dpplon, CoordFloatString coords); - - /** - * Method called by the VPF reader code to construct a text - * feature. - * - * @param c the coverage table for this text - * @param t the texttable being parsed - * @param textprim the record read from the text table - * @param latitude the latitude of the text - * @param longitude the longitude of the text - * @param text the text string - */ - public void createText(CoverageTable c, TextTable t, List textprim, - double latitude, double longitude, String text); - - /** - * Method called by the VPF reader code to construct a node - * feature. - * - * @param c the coverage table for this node - * @param t the nodetable being parsed - * @param nodeprim the record read from the node table - * @param latitude the latitude of the node - * @param longitude the longitude of the node - * @param isEntityNode true if we are reading entity notes, false - * if we are reading connected nodes - */ - public void createNode(CoverageTable c, NodeTable t, List nodeprim, - double latitude, double longitude, boolean isEntityNode); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayer.java deleted file mode 100644 index 056b7b9cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayer.java +++ /dev/null @@ -1,842 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFLayer.java,v $ -// $RCSfile: VPFLayer.java,v $ -// $Revision: 1.21 $ -// $Date: 2006/03/06 16:13:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.beancontext.BeanContext; -import java.io.Serializable; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement an OpenMap Layer for display of NIMA data sources in the VPF - * (Mil-Std 2407) format. - *

- * The properties needed to configure this layer to display VPF data include - * some "magic" strings specific to the VPF database you are trying to display. - * {@link com.bbn.openmap.layer.vpf.DescribeDB DescribeDB}is a utility to help - * you figure out what those strings are. - * - *

- * 
- * 
- * 
- *     #-----------------------------
- *     # Properties for a VMAP political layer
- *     #-----------------------------
- *     # Mandatory properties
- *     # Mandatory for all layers
- *     vmapPol.class= com.bbn.openmap.layer.vpf.VPFLayer
- *     vmapPol.prettyName= Political Boundaries from VMAP
- *     # Mandatory - choose .vpfPath or .libraryBean
- *     # .vpfPath specifies a ';' separated list of paths to data, each of these
- *     #directories should have a "lat" or "lat." file in them.
- *     vmapPol.vpfPath= e:/VMAPLV0
- *     # .libraryBean specifies a separate object in the properties file that
- *     # locates vpf data.  You should use this option if you have multiple VPF
- *     # layers displaying the same VPF database.  (For example, you have 3 VMAP
- *     # layers, displaying coastlines, railroads and rivers.  Each layer would
- *     # then specify the same libraryBean name.  This reduces the memory 
- *     # consumption of the VPF layers.)
- *     # See {@link com.bbn.openmap.layer.vpf.LibraryBean LibraryBean javadoc} for properties info. (Example below)
- *     vmapPol.libraryBean= VMAPdata
- *     VMAPData.class=com.bbn.openmap.layer.vpf.LibraryBean
- *     VMAPData.vpfPath=e:/VMAPLV0
- *     # Don't forget to add VMAPData to the openmap.components property list, too.
- *     #
- *     #Optional (default is true) changes how features are located.  Should
- *     #use this option for multiple coverage types, or when null pointer errors
- *     #are encountered.
- *     vmapPol.searchByFeature=true
- *    
- *     #Limit which VPF library is used (optional).  If not specified,
- *     #all available libraries will be checked and used.
- *     vmapPol.libraryName=noamer
- *     #
- *     # Choose either .defaultLayer or .coverageType
- *     #
- *     # .defaultLayer results in the layer looking up the remainder of the
- *     # properties in the defaultVPFLayers.properties files.
- *     vmapPol.defaultLayer= vmapPolitical
- *     #
- *     # .coverageType continues in this property file - chose the VMAP bnd
- *     # (Boundary) coverage
- *     vmapPol.coverageType= bnd
- *     # Select if we want edges (polylines), areas (filled polygons) or text
- *     # This is a space-separated list of "edge" "area" "text" "epoint" and "cpoint"
- *     vmapPol.featureTypes= edge area
- *     #For DCW, the remaining 3 properties are ignored
- *     #Select the text featureclasses we'd like to display.  Since we didn't
- *     #select text above, this is ignored
- *     vmapPol.text= 
- *     #Select the edge featureclasses we'd like to display. In this case,
- *     #draw political boundaries and coastline, but skip anything else.
- *     vmapPol.edge=polbndl coastl
- *     #Select the area featureclasses we'd like to display. In this case,
- *     #draw politcal areas, but skip anything else.
- *     vmapPol.area=polbnda
- *     #Selectable drawing attributes - for default values, they don't need to
- *     #be included.  A hex ARGB color looks like FF000000 for black.
- *     vmapPol.lineColor=hex ARGB color value - Black is default.
- *     vmapPol.fillColor=hex ARGB color value - Clear is default.
- *     vmapPol.lineWidth=float value, 1f is the default, 10f is the max.
- *    
- *     # The column name in the feature table that should be displayed.  The easiest 
- *     # way to find out what these columns should be for an application is to run the 
- *     # application with the other properties set for the layer, and then bring up 
- *     # the layer's palette.  When the feature is selected, there are additional 
- *     # controls that let you display the coverage column names and display type, 
- *     # and the coverage column names in the popup are the ones that can be used 
- *     # in the properties (the column names are in parenthesis).  NOTE:   The features 
- *     # have to be added to the map and visible (proper scale setting < 30,000,000) 
- *     # in order for the palette controls to be visible.
- *     vmapPol.attribute=na2
- *     # How the attributes should be displayed, either 'label', 'tooltip', or 'information line'
- *     vmapPol.attributeDisplay=label
- *    
- *     #------------------------------------
- *     # End of properties for a VMAP political layer
- *     #------------------------------------
- *     
- *     ### Now a VMAP Coastline layer
- *     vmapCoast.class=com.bbn.openmap.layer.vpf.VPFLayer
- *     vmapCoast.prettyName=VMAP Coastline Layer
- *     vmapCoast.vpfPath=/u5/vmap/vmaplv0
- *     ## a predefined layer from the VPF predefined layer set found in
- *     ## com/bbn/openmap/layer/vpf/defaultVPFLayers.properties
- *     vmapCoast.defaultLayer=vmapCoastline
- *     
- *     ### Now a DCW Political layer
- *     # Basic political boundaries with DCW
- *     dcwPolitical.class=com.bbn.openmap.layer.vpf.VPFLayer
- *     dcwPolitical.prettyName=DCW Political Boundaries
- *     dcwPolitical.vpfPath=path to data
- *     dcwPolitical.coverageType=po
- *     dcwPolitical.featureTypes=edge area
- * 
- * 
- * 
- * 
- */ - -public class VPFLayer extends OMGraphicHandlerLayer implements ProjectionListener, ActionListener, Serializable { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFLayer"); - - /** property extension used to set the VPF root directory */ - public static final String pathProperty = "vpfPath"; - /** - * property extension used to set the desired coverage type. Examples of - * coverage types include "po" for DCW and "hyd" for VMAP Level 0. - */ - public static final String coverageTypeProperty = "coverageType"; - /** - * Property extension used to set the desired feature types. e.g. line area text - */ - public static final String featureTypesProperty = "featureTypes"; - /** property extension used to specify a default property set */ - public static final String defaultLayerProperty = "defaultLayer"; - /** - * Property that lets you search for graphics via feature type. Dangerously slow - * for features that have many graphics spread out over several tiles. Set to - * true to search by feature, false (default) to get the tiles first, and then - * look for graphics. - */ - public static final String searchByFeatureProperty = "searchByFeature"; - /** Property method for setting VPF data path */ - public static final String libraryProperty = "libraryBean"; - /** Property for setting VPF cutoff scale */ - public static final String cutoffScaleProperty = "cutoffScale"; - /** Property for setting VPF library name to use */ - public static final String LibraryNameProperty = "libraryName"; - /** the object that knows all the nitty-gritty vpf stuff */ - protected transient LibrarySelectionTable lst; - /** our own little graphics factory */ - protected transient LayerGraphicWarehouseSupport warehouse; - /** are we searching by feature table (true) or tile (false) */ - protected boolean searchByFeatures = false; - /** the name of the data bean to look for in beancontext */ - protected String libraryBeanName = null; - - /** - * hang onto prefix used to initialize warehouse in setProperties() - */ - protected String prefix; - /** hang onto properties file used to initialize warehouse */ - protected Properties props; - - /** the path to the root VPF directory */ - protected String[] dataPaths = null; - /** the coverage type that we display */ - protected String coverageType = "po"; - - protected int cutoffScale = LibrarySelectionTable.DEFAULT_BROWSE_CUTOFF; - /** the library name to focus on */ - protected String libraryName = null; - - /** - * Construct a VPF layer. - */ - public VPFLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setMouseModeIDsForEvents(new String[] { "Gestures" }); - } - - /** - * Construct a VPFLayer, and sets its name. - * - * @param name the name of the layer. - */ - public VPFLayer(String name) { - this(); - setName(name); - } - - /** - * Sets the features (lines, areas, text, points) that get displayed. - * - * @param features a whitespace-separated list of features to display. - */ - public void setFeatures(String features) { - warehouse.setFeatures(features); - } - - /** - * Another way to set the parameters of the DcwLayer. - * - * @see #pathProperty - * @see #coverageTypeProperty - * @see #featureTypesProperty - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - setAddToBeanContext(true); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - cutoffScale = PropUtils.intFromProperties(props, realPrefix + cutoffScaleProperty, cutoffScale); - - libraryBeanName = props.getProperty(realPrefix + libraryProperty, libraryBeanName); - - libraryName = props.getProperty(realPrefix + LibraryNameProperty, libraryName); - - String path[] = PropUtils.initPathsFromProperties(props, realPrefix + pathProperty); - - if (path != null && path.length != 0) { - setPath(path); - } - String defaultProperty = props.getProperty(realPrefix + defaultLayerProperty); - - if (defaultProperty != null) { - prefix = defaultProperty; - props = VPFUtil.getDefaultProperties(); - } - - // need to save these so we can call setProperties on the - // warehouse, - // which we probably can't construct yet - this.prefix = prefix; - this.props = props; - - String coverage = props.getProperty(realPrefix + coverageTypeProperty); - if (coverage != null) { - setDataTypes(coverage); - } - - searchByFeatures = PropUtils.booleanFromProperties(props, realPrefix + searchByFeatureProperty, - searchByFeatures); - - checkWarehouse(searchByFeatures); - if (warehouse != null) { - warehouse.setProperties(prefix, props); - warehouse.setUseLibraries(PropUtils.parseSpacedMarkers(libraryName)); - - box = null; - resetPalette(); - } - - try { - // force lst and warehosue to re-init with current - // properties - - // LST now set when paths are set. - } catch (IllegalArgumentException iae) { - logger.warning( - "Illegal Argument Exception.\n\nPerhaps a file not found. Check to make sure that the paths to the VPF data directories are the parents of \"lat\" or \"lat.\" files. \n\n" - + iae); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(realPrefix + cutoffScaleProperty, Integer.toString(cutoffScale)); - - if (libraryBeanName != null) { - props.put(realPrefix + libraryProperty, libraryBeanName); - } else { - StringBuffer paths = new StringBuffer(); - String[] ps = getPath(); - - for (int i = 0; ps != null && i < ps.length; i++) { - paths.append(ps[i]); - if (i < ps.length - 1) - paths.append(";"); - } - - props.put(realPrefix + pathProperty, paths.toString()); - } - - // For the library in a vpf package - props.put(realPrefix + LibraryNameProperty, PropUtils.unnull(libraryName)); - - props.put(realPrefix + coverageTypeProperty, getDataTypes()); - props.put(realPrefix + searchByFeatureProperty, Boolean.toString(searchByFeatures)); - - if (warehouse != null) { - warehouse.getProperties(props); - } - - return props; - } - - /** - * Set the data path to a single place. - */ - public void setPath(String newPath) { - logger.fine("setting paths to " + newPath); - setPath(new String[] { newPath }); - } - - /** - * Set the data path to multiple places. - */ - public void setPath(String[] newPaths) { - dataPaths = newPaths; - - lst = null; - initLST(); - } - - /** - * Returns the list of paths we use to look for data. - * - * @return the list of paths. Don't modify the array! - */ - public String[] getPath() { - return dataPaths; - } - - /** - * Set the coveragetype of the layer. - * - * @param dataTypes the coveragetype to display. - */ - public void setDataTypes(String dataTypes) { - coverageType = dataTypes; - } - - /** - * Get the current coverage type. - * - * @return the current coverage type. - */ - public String getDataTypes() { - return coverageType; - } - - /** - * Enable/Disable the display of areas. - */ - public void setAreasEnabled(boolean value) { - warehouse.setAreaFeatures(value); - } - - /** - * Find out if areas are enabled. - */ - public boolean getAreasEnabled() { - return warehouse.drawAreaFeatures(); - } - - /** - * Enable/Disable the display of edges. - */ - public void setEdgesEnabled(boolean value) { - warehouse.setEdgeFeatures(value); - } - - /** - * Find out if edges are enabled. - */ - public boolean getEdgesEnabled() { - return warehouse.drawEdgeFeatures(); - } - - /** - * Enable/Disable the display of entity points. - */ - public void setEPointsEnabled(boolean value) { - warehouse.setEPointFeatures(value); - } - - /** - * Find out if entity points are enabled. - */ - public boolean getEPointsEnabled() { - return warehouse.drawEPointFeatures(); - } - - /** - * Enable/Disable the display of connected points. - */ - public void setCPointsEnabled(boolean value) { - warehouse.setCPointFeatures(value); - } - - /** - * Find out if connected points are enabled. - */ - public boolean getCPointsEnabled() { - return warehouse.drawCPointFeatures(); - } - - /** - * Enable/Disable the display of text. - */ - public void setTextEnabled(boolean value) { - warehouse.setTextFeatures(value); - } - - /** - * Find out if text is enabled. - */ - public boolean getTextEnabled() { - return warehouse.drawTextFeatures(); - } - - /** - * Get the DrawingAttributes used for the coverage type. - */ - public DrawingAttributes getDrawingAttributes() { - return warehouse.getDrawingAttributes(); - } - - /** - * Set the drawing attributes for the coverage type. - */ - public void setDrawingAttributes(DrawingAttributes da) { - warehouse.setDrawingAttributes(da); - } - - /** - * initialize the library selection table. - */ - protected void initLST() { - logger.fine("initializing Library Selection Table (LST)"); - - if (lst == null) { - if (libraryBeanName != null) { - LibraryBean libraryBean = null; - BeanContext beanContext = getBeanContext(); - if (beanContext == null) { - // no bean context yet - return; - } - for (Object obj : beanContext) { - if (obj instanceof LibraryBean) { - LibraryBean lb = (LibraryBean) obj; - if (libraryBeanName.equals(lb.getName())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": setting library bean to " + lb.getName()); - } - libraryBean = lb; - break; - } - } - } - if (libraryBean != null) { - lst = libraryBean.getLibrarySelectionTable(); - warehouse = libraryBean.getWarehouse(); - // Set the warehouse with the properties - // received when the layer was created. - warehouse.setProperties(getPropertyPrefix(), props); - searchByFeatures = true; // because it is. - box = null;// force GUI to rebuild - - logger.fine("VPFLayer.initLST(libraryBean)"); - } else { - if (logger.isLoggable(Level.FINE)) { - // Encasing it in a debug statement, - // because we could get here by adding the - // LayerHandler to the MapHandler before - // the LibraryBean. - logger.fine("Couldn't find libraryBean " + libraryBeanName + " to read VPF data"); - } - } - } else { - if (dataPaths == null) { - logger.info("VPFLayer|" + getName() + ": path not set"); - } else { - logger.fine("VPFLayer.initLST(dataPaths)"); - lst = new LibrarySelectionTable(); - lst.setCutoffScale(cutoffScale); - - try { - lst.withDataPath(dataPaths); - } catch (com.bbn.openmap.io.FormatException f) { - StringBuilder buf = new StringBuilder("VPFLayer|").append(getName()).append(": problem with path: "); - if (dataPaths != null) { - for (String dPath : dataPaths) { - buf.append("\n\t").append(dPath); - } - } else { - buf.append(" NO DATA PATHS SPECIFIED"); - } - - logger.warning(buf.toString()); - } - - } - } - } - - } - - public void setWarehouse(LayerGraphicWarehouseSupport wh) { - warehouse = wh; - } - - public LayerGraphicWarehouseSupport getWarehouse() { - return warehouse; - } - - /** - * If the warehouse gets set as a result of this method being called, the - * properties will beed to be reset on it. - * - * @param sbf Search by features. - */ - public void checkWarehouse(boolean sbf) { - if (warehouse == null) { - logger.fine("need to create warehouse"); - if (lst != null && lst.getDatabaseName() != null && lst.getDatabaseName().equals("DCW")) { - warehouse = new VPFLayerDCWWarehouse(); - } else if (sbf) { - warehouse = new VPFFeatureGraphicWarehouse(); - } else { - warehouse = new VPFLayerGraphicWarehouse(); - } - } else if ((sbf && !(warehouse instanceof VPFFeatureGraphicWarehouse)) - || (!sbf && warehouse instanceof VPFFeatureGraphicWarehouse)) { - warehouse = null; - checkWarehouse(sbf); - } - } - - /** - * Use doPrepare() method instead. This was the old method call to do the same - * thing doPrepare is now doing, from the OMGraphicHandler superclass. - * doPrepare() launches a thread to do the work. - * - * @deprecated use doPrepare() instead of computeLayer(); - */ - public void computeLayer() { - doPrepare(); - } - - /** - * Use prepare instead. This was the old method call to do the same thing - * prepare() is now doing. - * - * @deprecated use prepare() instead of getRectangle(); - */ - public OMGraphicList getRectangle() { - return prepare(); - } - - /** - * Create the OMGraphicList to use on the map. OMGraphicHandler methods call - * this. - */ - public synchronized OMGraphicList prepare() { - if (lst == null) { - try { - initLST(); - } catch (IllegalArgumentException iae) { - logger.warning( - "VPFLayer.prepare: Illegal Argument Exception.\n\nPerhaps a file not found. Check to make sure that the paths to the VPF data directories are the parents of \"lat\" or \"lat.\" files. \n\n" - + iae); - return null; - } - - if (lst == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("VPFLayer| " + getName() + " prepare(), Library Selection Table not set."); - } - - return null; - } - } - - if (warehouse == null) { - StringBuffer dpb = new StringBuffer(); - if (dataPaths != null) { - for (int num = 0; num < dataPaths.length; num++) { - if (num > 0) { - dpb.append(":"); - } - dpb.append(dataPaths[num]); - } - } - - logger.warning("VPFLayer.getRectangle: Data path probably wasn't set correctly (" + dpb.toString() - + "). The warehouse not initialized."); - return null; - } - - Projection p = getProjection(); - - if (p == null || !(p instanceof GeoProj)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("VPFLayer.getRectangle() called with a projection (" + p - + ") set in the layer, which isn't being handled."); - } - return new OMGraphicList(); - } - - LatLonPoint upperleft = (LatLonPoint) p.getUpperLeft(); - LatLonPoint lowerright = (LatLonPoint) p.getLowerRight(); - if (logger.isLoggable(Level.FINER)) { - logger.finer("VPFLayer.getRectangle: " + coverageType /* - * + " " + dynamicArgs - */); - } - - warehouse.clear(); - - // int edgecount[] = new int[] { 0 , 0 }; - // int textcount[] = new int[] { 0 , 0 }; - // int areacount[] = new int[] { 0 , 0 }; - - // Check both dynamic args and palette values when - // deciding what to draw. - if (logger.isLoggable(Level.FINE)) { - logger.fine("calling draw with boundaries: " + upperleft + " " + lowerright); - } - long start = System.currentTimeMillis(); - - StringTokenizer t = new StringTokenizer(coverageType); - while (t.hasMoreTokens()) { - String currentCoverage = t.nextToken(); - if (searchByFeatures) { - lst.drawFeatures((int) p.getScale(), p.getWidth(), p.getHeight(), currentCoverage, - (VPFFeatureWarehouse) warehouse, upperleft, lowerright); - } else { - lst.drawTile((int) p.getScale(), p.getWidth(), p.getHeight(), currentCoverage, warehouse, upperleft, - lowerright); - } - } - long stop = System.currentTimeMillis(); - - // if (Debug.debugging("vpfdetail")) { - // Debug.output("Returned " + edgecount[0] + - // " polys with " + edgecount[1] + " points\n" + - // "Returned " + textcount[0] + - // " texts with " + textcount[1] + " points\n" + - // "Returned " + areacount[0] + - // " areas with " + areacount[1] + " points"); - // } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("read time: " + ((stop - start) / 1000d) + " seconds"); - } - - OMGraphicList omglist = warehouse.getGraphics(); - - // Don't forget to project. - start = System.currentTimeMillis(); - omglist.project(p); - stop = System.currentTimeMillis(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("proj time: " + ((stop - start) / 1000d) + " seconds"); - } - return omglist; - } - - private transient JPanel box; - - /** - * Gets the palette associated with the layer. - * - * @return Component or null - */ - public Component getGUI() { - - if (lst == null) { - try { - initLST(); - } catch (IllegalArgumentException iie) { - logger.warning(iie.getMessage()); - } - } - - if (warehouse == null) { - return (new javax.swing.JLabel("VPF Layer data not loaded properly.")); - } - - if (box == null) { - - box = new JPanel(); - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setAlignmentX(Component.LEFT_ALIGNMENT); - - JPanel stuff = new JPanel(); - - JPanel pal = null; - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - int index = Integer.parseInt(e.getActionCommand(), 10); - switch (index) { - case 0: - warehouse.setEdgeFeatures(!warehouse.drawEdgeFeatures()); - break; - case 1: - warehouse.setTextFeatures(!warehouse.drawTextFeatures()); - break; - case 2: - warehouse.setAreaFeatures(!warehouse.drawAreaFeatures()); - break; - case 3: - warehouse.setEPointFeatures(!warehouse.drawEPointFeatures()); - break; - case 4: - warehouse.setCPointFeatures(!warehouse.drawCPointFeatures()); - break; - default: - throw new RuntimeException("argh!"); - } - } - }; - - pal = PaletteHelper.createCheckbox("Show:", - new String[] { VPFUtil.Edges, VPFUtil.Text, VPFUtil.Area, VPFUtil.EPoint, VPFUtil.CPoint }, - new boolean[] { warehouse.drawEdgeFeatures(), warehouse.drawTextFeatures(), - warehouse.drawAreaFeatures(), warehouse.drawEPointFeatures(), - warehouse.drawCPointFeatures() }, - al); - - stuff.add(pal); - - if (lst != null) { - Component warehouseGUI = warehouse.getGUI(lst); - if (warehouseGUI != null) { - stuff.add(warehouseGUI); - } - } - box.add(stuff); - - JPanel pal2 = new JPanel(); - JButton config = new JButton("Configure Layer"); - config.setActionCommand(ConfigCmd); - config.addActionListener(this); - pal2.add(config); - - JButton redraw = new JButton("Redraw Layer"); - redraw.setActionCommand(RedrawCmd); - redraw.addActionListener(this); - pal2.add(redraw); - box.add(pal2); - } - return box; - } - - public final static String ConfigCmd = "CONFIGURE"; - protected WindowSupport configWindowSupport = null; - - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - if (cmd == RedrawCmd) { - setList(null); - if (isVisible()) { - doPrepare(); - } - } else if (cmd == ConfigCmd) { - if (configWindowSupport == null) { - configWindowSupport = new WindowSupport(new VPFConfig(this), "Configure " + getName() + " Features"); - } else { - configWindowSupport.setTitle(getName()); - } - configWindowSupport.displayInWindow(); - } else { - super.actionPerformed(e); - } - } - - protected void setConfigSettings(String prefix, Properties props) { - lst = null; - setProperties(prefix, props); - if (isVisible()) { - doPrepare(); - } - - if (configWindowSupport != null) { - configWindowSupport.setTitle(getName()); - configWindowSupport.killWindow(); - } - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphicConstants.TOOLTIP); - } - - public String getInfoText(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphicConstants.INFOLINE); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerDCWWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerDCWWarehouse.java deleted file mode 100644 index 6a8b15220..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerDCWWarehouse.java +++ /dev/null @@ -1,287 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFLayerDCWWarehouse.java,v $ -// $Revision: 1.7 $ $Date: 2009/01/21 01:24:41 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics. This one handles DCW - * databases. It has some properties that can be added to the VPFLayer property - * list that further control which types of features will not be displayed for a - * coverage type. - *

- * - * If you use the com.bbn.openmap.layer.vpf.Server class, and run it on a - * (coverage type)/int.vdt file: - * - *

- * 
- * 
- *   java com.bbn.openmap.layer.vpf.Server /dcw/noamer/po/int.vdt
- * 
- * 
- * 
- * - * You can use the values in column 3 to add to a list to have that attribute - * type *NOT* show up. - * - *
- * 
- * 
- *   vpflayer.areaTypeExclude=
- *   vpflayer.lineTypeExclude=9 (for po coverages, gets rid of tile boundaries)
- *   vpflayer.textTypeExclude=
- * 
- * 
- * - * These are space-separated lists. - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public class VPFLayerDCWWarehouse - extends LayerGraphicWarehouseSupport { - - public final static String AreaTypeExcludeProperty = "areaTypeExclude"; - public final static String LineTypeExcludeProperty = "lineTypeExclude"; - public final static String TextTypeExcludeProperty = "textTypeExclude"; - - protected int[] areaTypeExcludes = null; - protected int[] lineTypeExcludes = null; - protected int[] textTypeExcludes = null; - - protected boolean DEBUG = false; - - /** - * - */ - public VPFLayerDCWWarehouse() { - super(); - DEBUG = Debug.debugging("DCW"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String list = props.getProperty(realPrefix + AreaTypeExcludeProperty); - if (list != null) { - areaTypeExcludes = getNumbersFromPropertyList(list); - } else { - areaTypeExcludes = getNumbersFromPropertyList("0 2"); - // topology artifacts and oceans, by default - } - - if (DEBUG) - Debug.output("Excluding area types: " + getDebugNumbers(areaTypeExcludes)); - - list = props.getProperty(realPrefix + LineTypeExcludeProperty); - if (list != null) { - lineTypeExcludes = getNumbersFromPropertyList(list); - } - - if (DEBUG) - Debug.output("Excluding area types: " + getDebugNumbers(lineTypeExcludes)); - - list = props.getProperty(realPrefix + TextTypeExcludeProperty); - if (list != null) { - textTypeExcludes = getNumbersFromPropertyList(list); - } - - if (DEBUG) - Debug.output("Excluding area types: " + getDebugNumbers(textTypeExcludes)); - } - - protected String getDebugNumbers(int[] arr) { - StringBuffer strBuf = new StringBuffer(); - if (arr != null) { - for (int i : arr) { - strBuf.append(i).append(" "); - } - } - return strBuf.toString(); - } - - /** - * From a string of space separated numbers, creates an int[]. - */ - protected int[] getNumbersFromPropertyList(String list) { - List realList = new ArrayList(); - - List excludes = PropUtils.parseSpacedMarkers(list); - - for (String number : excludes) { - try { - realList.add(Integer.valueOf(number)); - } catch (NumberFormatException nfe) { - } - } - - int[] numbers = null; - - if (!realList.isEmpty()) { - numbers = new int[realList.size()]; - int count = 0; - for (Integer realInt : realList) { - numbers[count++] = realInt.intValue(); - } - } - - return numbers; - } - - /** - * returns true if the num is a number somewhere on the list. - */ - protected boolean onList(int[] list, int num) { - if (list != null) { - for (int i = 0; i < list.length; i++) { - if (num == list[i]) { - return true; - } - } - } - return false; - } - - /** - * Returns the list of features to draw - DCW doesn't have features, so - * returns an empty List - */ - public List getFeatures() { - return Collections.emptyList(); - } - - /** - * - */ - public void createArea(CoverageTable covtable, AreaTable areatable, List facevec, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon) { - List ipts = new ArrayList(); - - if (areaTypeExcludes != null) { - - MutableInt areatype = new MutableInt(-1); - // String descript = covtable.getAreaDescription(facevec, areatype); - - if (onList(areaTypeExcludes, areatype.value)) { - return; - } - } - - // if (areatype.value == 0) {//topology artifact - // return; - // } - - // if (areatype.value == 2) { - // if (Debug.debugging("vpf")) { - // Debug.output("Skipping open ocean: " + descript); - // } - // return; - // } - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return; - } - if (totalSize == 0) { - return; - } - - OMPoly py = createAreaOMPoly(ipts, totalSize, ll1, ll2, dpplat, dpplon, covtable.doAntarcticaWorkaround); - - // if (areatype.value == -1) { - // areatype.value = 0; - // } - - drawingAttributes.setTo(py); - - // HACK to get tile boundaries to not show up for areas. - py.setLinePaint(py.getFillPaint()); - py.setSelectPaint(py.getFillPaint()); - - graphics.add(py); - } - - /** - * - */ - public void createEdge(CoverageTable covtable, EdgeTable edgetable, List edgevec, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon, CoordFloatString coords) { - // Kept these here to keep in mind that it may be possible to - // further figure out what exactly we have here. - if (lineTypeExcludes != null) { - - MutableInt lineType = new MutableInt(-1); - // String desc = covtable.getLineDescription(edgevec, lineType); - - if (onList(lineTypeExcludes, lineType.value)) { - return; - } - } - - OMPoly py = createEdgeOMPoly(coords, ll1, ll2, dpplat, dpplon); - drawingAttributes.setTo(py); - py.setIsPolygon(false); - graphics.add(py); - } - - /** - * - */ - public void createText(CoverageTable covtable, TextTable texttable, List textvec, double latitude, double longitude, String text) { - // Kept these here to keep in mind that it may be possible to - // further figure out what exactly we have here. - if (textTypeExcludes != null) { - - MutableInt textType = new MutableInt(-1); - // String desc = covtable.getTextDescription(textvec, textType); - - if (onList(textTypeExcludes, textType.value)) { - return; - } - } - - OMText txt = createOMText(text, latitude, longitude); - drawingAttributes.setTo(txt); - graphics.add(txt); - } - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public void createNode(CoverageTable c, NodeTable t, List nodeprim, double latitude, double longitude, boolean isEntityNode) { - OMPoint pt = createOMPoint(latitude, longitude); - drawingAttributes.setTo(pt); - graphics.add(pt); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerGraphicWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerGraphicWarehouse.java deleted file mode 100644 index 643094836..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFLayerGraphicWarehouse.java +++ /dev/null @@ -1,408 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFLayerGraphicWarehouse.java,v $ -// $RCSfile: VPFLayerGraphicWarehouse.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics. - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public class VPFLayerGraphicWarehouse extends LayerGraphicWarehouseSupport { - - /** - * the properties file string that tells us what area features to - * draw - */ - String areaFeatures = null; - /** one of these columns must be non-null to draw area features */ - int areaSkipFeatures[] = null; - /** - * the properties file string that tells us what edge features to - * draw - */ - String edgeFeatures = null; - /** one of these columns must be non-null to draw edge features */ - int edgeSkipFeatures[] = null; - /** - * the properties file string that tells us what text features to - * draw - */ - String textFeatures = null; - /** one of these columns must be non-null to draw text features */ - int textSkipFeatures[] = null; - /** - * the properties file string that tells us what entity point - * features to draw - */ - String epointFeatures = null; - /** - * one of these columns must be non-null to draw entity point - * features - */ - int epointSkipFeatures[] = null; - /** - * the properties file string that tells us what connected point - * features to draw - */ - String cpointFeatures = null; - /** - * one of these columns must be non-null to draw connected point - * features - */ - int cpointSkipFeatures[] = null; - - /** - * - */ - public VPFLayerGraphicWarehouse() { - super(); - } - - /** - * Set properties of the warehouse. - * - * @param prefix the prefix to use for looking up properties. - * @param props the properties file to look at. - */ - public void setProperties(String prefix, java.util.Properties props) { - super.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - areaFeatures = props.getProperty(realPrefix + "area"); - if (areaFeatures == null) { - areaSkipFeatures = new int[0]; - } else { - areaSkipFeatures = null; - } - - textFeatures = props.getProperty(realPrefix + "text"); - if (textFeatures == null) { - textSkipFeatures = new int[0]; - } else { - textSkipFeatures = null; - } - - edgeFeatures = props.getProperty(realPrefix + "edge"); - if (edgeFeatures == null) { - edgeSkipFeatures = new int[0]; - } else { - edgeSkipFeatures = null; - } - - epointFeatures = props.getProperty(realPrefix + "epoint"); - if (epointFeatures == null) { - epointSkipFeatures = new int[0]; - } else { - epointSkipFeatures = null; - } - - cpointFeatures = props.getProperty(realPrefix + "cpoint"); - if (cpointFeatures == null) { - cpointSkipFeatures = new int[0]; - } else { - cpointSkipFeatures = null; - } - - } - - /** - * Get a List of Strings listing all the feature types wanted. - * Returned with the area features first, then text features, then - * line features, then point features. - */ - public List getFeatures() { - List retval = new ArrayList(); - - StringTokenizer t; - if (areaFeatures != null) { - t = new StringTokenizer(areaFeatures); - while (t.hasMoreTokens()) { - retval.add(t.nextToken()); - } - } - if (textFeatures != null) { - t = new StringTokenizer(textFeatures); - while (t.hasMoreTokens()) { - retval.add(t.nextToken()); - } - } - if (edgeFeatures != null) { - t = new StringTokenizer(edgeFeatures); - while (t.hasMoreTokens()) { - retval.add(t.nextToken()); - } - } - if (epointFeatures != null) { - t = new StringTokenizer(epointFeatures); - while (t.hasMoreTokens()) { - retval.add(t.nextToken()); - } - } - if (cpointFeatures != null) { - t = new StringTokenizer(cpointFeatures); - while (t.hasMoreTokens()) { - retval.add(t.nextToken()); - } - } - - return retval; - } - - /** - * Build an array that lists the columns we require the record to - * have. - * - * @param featureString the (space-separated) list of required - * columns - * @param table the table we use to find the column numbers - * @param colAppend the (possibly null) string we append to the - * entries in featureString to build the real column name - */ - protected int[] getSkipArray(String featureString, DcwRecordFile table, - String colAppend) { - List tmpvec = new ArrayList(); - if (featureString != null) { - StringTokenizer t = new StringTokenizer(featureString); - while (t.hasMoreTokens()) { - String colname = t.nextToken(); - if (colAppend != null) { - colname += colAppend; - } - int colnum = table.whatColumn(colname); - if (colnum != -1) { - tmpvec.add(new Integer(colnum)); - } - } - } - - int[] retval = new int[tmpvec.size()]; - for (int i = 0; i < retval.length; i++) { - retval[i] = tmpvec.get(i).intValue(); - } - return retval; - } - - /** - * Lets the warehouse know that a different CoverageAttributeTable - * will be using it. The skip arrays need to be reset. - */ - public void resetForCAT() { - areaSkipFeatures = null; - textSkipFeatures = null; - edgeSkipFeatures = null; - epointSkipFeatures = null; - cpointSkipFeatures = null; - } - - /** - * Determine if this primitive should be drawn or skipped. - * - * @param prim the list for the primitive feature object. - * @param skipArray a list of columns. - * @return true if any of the columns listed in skipArray is - * non-null. - */ - protected boolean createFeature(List prim, int[] skipArray) { - //length==0 --> user wants everything - if (skipArray.length == 0) { - return true; - } - for (int i = 0; i < skipArray.length; i++) { - int val = VPFUtil.objectToInt(prim.get(skipArray[i])); - if (val != Integer.MIN_VALUE) { - return true; - } - } - return false; - } - - final transient static java.awt.Color aaronscolor = new java.awt.Color(0xBDDE83); - - /** - * - */ - public void createArea(CoverageTable covtable, AreaTable areatable, - List facevec, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon) { - if (areaSkipFeatures == null) { - areaSkipFeatures = getSkipArray(areaFeatures, areatable, ".aft_id"); - } - - if (!createFeature(facevec, areaSkipFeatures)) { - return; - } - - List ipts = new ArrayList(); - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return; - } - if (totalSize == 0) { - //System.out.println("No edged: " + descript); - return; - } - - OMPoly py = createAreaOMPoly(ipts, - totalSize, - ll1, - ll2, - dpplat, - dpplon, - covtable.doAntarcticaWorkaround); - - // final MutableInt areatype = new MutableInt(-1); - // String descript = covtable.getAreaDescription(facevec, - // areatype); - // if (areatype.value == -1) { - // areatype.value = 0; - // } - - drawingAttributes.setTo(py); - - // HACK to get tile boundaries to not show up for areas. - // py.setLinePaint(py.getFillPaint()); - // py.setSelectPaint(py.getFillPaint()); - py.setLinePaint(OMColor.clear); - py.setSelectPaint(OMColor.clear); - - addArea(py); - } - - /** - * - */ - public void createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, - LatLonPoint ll1, LatLonPoint ll2, double dpplat, - double dpplon, CoordFloatString coords) { - - if (edgeSkipFeatures == null) { - if (Debug.debugging("vpf")) { - Debug.output("Warehouse.createEdge(): edgeFeatures = " - + edgeFeatures); - - final MutableInt lineType = new MutableInt(-1); - Debug.output("Warehouse: " - + c.getLineDescription(edgevec, lineType)); - - } - - String columnName = ".lft_id"; - edgeSkipFeatures = getSkipArray(edgeFeatures, edgetable, columnName); - } - - // HACK remove crufty dateline. This HACK may require - // additional hackage in FeatureClassInfo.java In particular, - // you may need to initialize the class during construction. - /* - * FeatureClassInfo[] lineinfo = c.lineinfo; int len = - * lineinfo.length; for (int i=0; i textvec, - double latitude, double longitude, String text) { - - if (textSkipFeatures == null) { - textSkipFeatures = getSkipArray(textFeatures, texttable, ".tft_id"); - } - - if (!createFeature(textvec, textSkipFeatures)) { - return; - } - - OMText txt = createOMText(text, latitude, longitude); - - drawingAttributes.setTo(txt); - addText(txt); - } - - public void createNode(CoverageTable c, NodeTable nt, List nodeprim, - double latitude, double longitude, boolean isEntityNode) { - int[] skipFeatures = null; - if (isEntityNode) { - if (epointSkipFeatures == null) { - epointSkipFeatures = getSkipArray(epointFeatures, nt, ".pft_id"); - } - skipFeatures = epointSkipFeatures; - } else { - if (cpointSkipFeatures == null) { - cpointSkipFeatures = getSkipArray(cpointFeatures, nt, ".pft_id"); - } - skipFeatures = cpointSkipFeatures; - } - - if (!createFeature(nodeprim, skipFeatures)) { - return; - } - - OMPoint pt = createOMPoint(latitude, longitude); - - drawingAttributes.setTo(pt); - addPoint(pt); - } - - public static void main(String argv[]) { - new VPFLayerGraphicWarehouse(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFRoadLayer.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFRoadLayer.java deleted file mode 100644 index 531a4ce78..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFRoadLayer.java +++ /dev/null @@ -1,198 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBN Technologies - * A Division of - * BBN Corporation - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright 1998 by BBN Technologies, A Division of - * BBN Corporation, all rights reserved. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFRoadLayer.java,v $ - * $RCSfile: VPFRoadLayer.java,v $ - * $Revision: 1.3 $ - * $Date: 2005/08/12 21:47:49 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.layer.vpf; - -import java.awt.Graphics; -import java.awt.Point; -import java.util.List; -import java.util.Properties; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.tools.roads.LayerView; -import com.bbn.openmap.tools.roads.RoadFinder; -import com.bbn.openmap.tools.roads.RoadServices; -import com.bbn.openmap.tools.roads.Route; -import com.bbn.openmap.tools.roads.Segment; -import com.bbn.openmap.util.PropUtils; - -/** - * Imposes a road layer on the VPF layer. - * - * The important method here is getPathOnRoad (implemented for the RoadServices - * interface) which returns a list of points on the road found between a start - * and an end point. - * - * You can see more about what the road layer is doing by setting - * drawIntersections to true, which will reveal what the road finder thinks are - * roads on the road layer, and drawResults to true, which will show each road - * path request and its result. The results shown accumulate over time. - */ -public class VPFRoadLayer extends VPFLayer implements ProjectionListener, RoadServices, LayerView { - - private static final long serialVersionUID = 1L; - Logger logger = Logger.getLogger(this.getClass().getName()); - RoadFinder helper; - - /** - * list of extra OMGraphics that represent intersections or results - */ - OMGraphicList toDraw = new OMGraphicList(); - boolean drawIntersections = false; - boolean drawResults = false; - - /** - * Property 'drawIntersections' will display the intersections on the road layer - * False by default. - */ - public static final String DrawIntersectionsProperty = "drawIntersections"; - - /** - * Property 'drawResults' will display the results of each road request on the - * road layer False by default. - */ - public static final String DrawResultsProperty = "drawResults"; - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - setDrawIntersections( - PropUtils.booleanFromProperties(props, realPrefix + DrawIntersectionsProperty, drawIntersections)); - setDrawResults(PropUtils.booleanFromProperties(props, realPrefix + DrawResultsProperty, drawResults)); - setHelper(); - } - - protected void setDrawIntersections(boolean val) { - drawIntersections = val; - } - - protected void setDrawResults(boolean val) { - drawResults = val; - } - - protected void setHelper() { - logger.info("draw inter " + drawIntersections); - helper = new RoadFinder((LayerView) this, drawIntersections, drawResults); - } - - /** - * Get points on the road between start and end - * - * Implemented for the RoadService interface - * - * @param start from here - * @param end to there - * @param segments populated with road segments - * @return list of points on path - */ - public List getPathOnRoad(Point start, Point end, List segments) { - return helper.getPathOnRoad(start, end, segments); - } - - /** - * @see com.bbn.openmap.tools.roads.RoadServices#getPathOnRoad(LatLonPoint, - * LatLonPoint) - */ - public Route getPathOnRoad(LatLonPoint start, LatLonPoint end) { - return helper.getPathOnRoad(start, end); - } - - /** - * @see RoadServices#displayPathOnRoad(Point, Point, Route, List) - */ - public List displayPathOnRoad(Point start, Point end, Route route, List segments) { - return helper.displayPathOnRoad(start, end, route, segments); - } - - /** - * Returns the RoadServices instance. - *

- * - * @return the RoadServices instance. - */ - public RoadServices getRoadServices() { - return helper; - } - - /** - * Implemented for ProjectionListener - */ - public void projectionChanged(ProjectionEvent e) { - super.projectionChanged(e); - logger.info("calling helper - projection changed."); - synchronized (this) { - if (helper == null) - setHelper(); - helper.projectionChanged(e); - } - } - - /** - * Called from RoadFinder to tell it what extra to render (e.g. intersections, - * roads). - */ - public void setExtraGraphics(OMGraphicList toDraw) { - logger.info("setting to draw " + toDraw.size() + " new graphics."); - this.toDraw = toDraw; - } - - /** - * If drawIntersections or drawResults is true, will add intersection markers or - * returned road lines to what is rendered. - */ - public void paint(Graphics g) { - super.paint(g); - if (drawIntersections || drawResults) { - // Create a new OMGraphicList in case toDraw changes while we render - OMGraphicList graphics = new OMGraphicList(toDraw); - graphics.generate(getProjection(), true); - logger.info("rendering toDraw " + toDraw.size() + " items"); - graphics.render(g); - } - } - - - /** - * Gets the original list of graphics items from getRectangle. - * - * @return List of OMGraphic items that will be used to create roads - */ - public OMGraphicList getOMGraphicsFromSource() { - OMGraphicList ret = new OMGraphicList(); - - OMGraphicList omgl = getList(); - if (omgl != null) { - ret.addAll(omgl); - } - return ret; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFUtil.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFUtil.java deleted file mode 100644 index bce74253b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFUtil.java,v $ -// $RCSfile: VPFUtil.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; - -/** - * Miscellaneous utility functions in dealing with VPF data. - */ -public class VPFUtil { - /** - * all methods are static, no reason to construct - */ - private VPFUtil() { - } - - /** - * returns a string with the elements of l separated by spaces - * - * @param l the list to stringize - * @return the string version of the list - * @deprecated use listToString(List) instead - */ - public static final String vectorToString(List l) { - return listToString(l); - } - - /** - * returns a string with the elements of l separated by spaces - * - * @param l the list to convert to string - * @return the string version of the list - */ - public static final String listToString(List l) { - StringBuffer row = new StringBuffer(); - for (Object obj : l) { - row.append(obj.toString()).append(" "); - } - return (row.toString()); - } - - /** - * get the value contained in the object. - * - * @param val returns the value of Shorts and Integers as an int. VPF null - * values get returned as Integer.MIN_VALUE, as do all other types - * @return the value contained in val - */ - public static final int objectToInt(Object val) { - int v = Integer.MIN_VALUE; - if (val instanceof Integer) { - v = ((Integer) val).intValue(); - if (v == Integer.MIN_VALUE + 1) { - v = Integer.MIN_VALUE; - } - } else if (val instanceof Short) { - v = ((Short) val).shortValue(); - if (v == Short.MIN_VALUE + 1) { - v = Integer.MIN_VALUE; - } - } - return v; - } - - /** some strings */ - public final static String Edge = "Edge"; - public final static String Edges = "Edges"; - public final static String Text = "Text"; - public final static String Area = "Area"; - // public final static String Point = "Point"; - public final static String EPoint = "EPoint"; - public final static String CPoint = "CPoint"; - - /** - * Parses dynamic args passed by specialist client. A Hashtable - * is returned as a unified holder of all dynamic arguments. - */ - public static Hashtable parseDynamicArgs(String args) { - Hashtable dynArgs = new Hashtable(); - if (args != null) { - String lowerArgs = args.toLowerCase(); - - dynArgs.put(Edges, new Boolean(lowerArgs.indexOf(Edges) != -1)); - dynArgs.put(Text, new Boolean(lowerArgs.indexOf(Text) != -1)); - dynArgs.put(Area, new Boolean(lowerArgs.indexOf(Area) != -1)); - dynArgs.put(EPoint, new Boolean(lowerArgs.indexOf(EPoint) != -1)); - dynArgs.put(CPoint, new Boolean(lowerArgs.indexOf(CPoint) != -1)); - } - return dynArgs; - } - - /** - * If arg maps to a Boolean in the Hashtable, that - * value is returned, false otherwise. - * - * @param dynArgs the Hashtable to look in - * @param arg the argument to return - */ - public static boolean getHashedValueAsBoolean(Hashtable dynArgs, String arg) { - Object obj = dynArgs.get(arg); - if (obj == null) { - return false; - } else if (obj instanceof Boolean) { - return ((Boolean) obj).booleanValue(); - } else { - return false; - } - } - - public static String getTypeForFeatureCode(String featureCode) { - int lastCharIndex = featureCode.length() - 1; - if (lastCharIndex >= 0) { - char lastLetter = featureCode.charAt(lastCharIndex); - - if (lastLetter == 'l') { - return VPFUtil.Edge; - } - - if (lastLetter == 'a') { - return VPFUtil.Area; - } - - if (lastLetter == 't') { - return VPFUtil.Text; - } - - // if (lastLetter == 'p') { - // // Can't tell at this point, it shouldn't matter for - // // the feature cache stuff since the points are - // return VPFUtil.EPoint; - // } - } - - return null; - } - - /** - * Return our default properties for vpf land. - */ - public static Properties getDefaultProperties() { - try { - InputStream in = VPFLayer.class.getResourceAsStream("defaultVPFlayers.properties"); - // use a temporary so other threads won't see an - // empty properties file - Properties tmp = new Properties(); - if (in != null) { - tmp.load(in); - in.close(); - } else { - Debug.error("VPFUtil.getDefaultProperties: can't load default properties file"); - // just use an empty properties file - } - return tmp; - } catch (IOException io) { - Debug.error("VPFUtil.getDefaultProperties: can't load default properties: " + io); - return new Properties(); - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFWarehouse.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFWarehouse.java deleted file mode 100644 index e8fe3777e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VPFWarehouse.java +++ /dev/null @@ -1,111 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFWarehouse.java,v $ -// $RCSfile: VPFWarehouse.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.Component; -import java.util.List; - -/** - * Define an interface for a Graphic Factory for graphics read from - * VPF. - */ -public interface VPFWarehouse { - - /** - * Return true if we may draw some edge features. - */ - public boolean drawEdgeFeatures(); - - /** - * Return true if we may draw some text features. - */ - public boolean drawTextFeatures(); - - /** - * Return true if we may draw some area features. - */ - public boolean drawAreaFeatures(); - - /** - * To let the warehouse know that a new CoverageAttributeTable - * will be using the warehouse. Some warehouses need to reset - * some tables for this situation. - */ - public void resetForCAT(); - - /** - * Get the GUI to control different aspects of the warehouse. - * - * @param lst LibrarySelectionTable to use to get information - * about the data, if needed. - */ - public Component getGUI(LibrarySelectionTable lst); - - /** - * Return true if we may draw some entity node(point) features. - */ - public boolean drawEPointFeatures(); - - /** - * Return true if we may draw some connected node(point) features. - */ - public boolean drawCPointFeatures(); - - /** - * Get a List of Strings listing all the feature types wanted. - * Returned with the area features first, then text features, then - * line features, then point features. - */ - public List getFeatures(); - - /** - * Get a library name to limit selections from. Used by the - * LibrarySelectionTable to find out if selection from database - * should be limitied to tiles or feature from certain libraries. - * Specified here instead of the LibrarySelectionTable in case the - * LST is shared among layers, since the warehouse is specific to - * a particular layer. - */ - public List getUseLibraries(); - - /** - * Set a library name to limit selections from. Used by the - * LibrarySelectionTable to find out if selection from database - * should be limitied to tiles or feature from certain libraries. - * Specified here instead of the LibrarySelectionTable in case the - * LST is shared among layers, since the warehouse is specific to - * a particular layer. If null the warehouse should use all - * libraries available to it to gather features. - */ - public void setUseLibraries(List lib); - - /** - * Utility method to check if the specified library name has been set by the - * configuration as one to use. - * - * @param libName the library name to test - * @return true if the useLibrary list has not been set, is empty, or if the - * provided name matches an entry on it. - */ - public boolean checkLibraryForUsage(String libName); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VpfCoverageTrimmer.java b/src/core/src/main/java/com/bbn/openmap/layer/vpf/VpfCoverageTrimmer.java deleted file mode 100644 index cea8795d1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/VpfCoverageTrimmer.java +++ /dev/null @@ -1,238 +0,0 @@ -package com.bbn.openmap.layer.vpf; - -import java.awt.geom.Rectangle2D; -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.EsriGraphic; -import com.bbn.openmap.dataAccess.shape.EsriGraphicList; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; - -public class VpfCoverageTrimmer { - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(VpfCoverageTrimmer.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - - private String sourceVpfLibLoc; - private LibrarySelectionTable lst; - private File outputLocation; - private List filters; - - private VpfCoverageTrimmer(Builder builder) { - this.sourceVpfLibLoc = builder.vpfPath; - this.lst = builder.lst; - this.outputLocation = builder.outputLocation; - this.filters = builder.filters; - } - - public void go() throws IOException { - - for (Rectangle2D filter : filters) { - trim(filter); - } - - copyFilesNotDirectories(new File(sourceVpfLibLoc)); - } - - protected void copyTileDirectories(File sourceLoc) throws IOException { - - if (sourceLoc.isDirectory()) { - for (File currentFile : sourceLoc.listFiles()) { - String localPath = currentFile.getAbsolutePath().substring(sourceVpfLibLoc.length() + 1); - - String destFilePath = outputLocation.getAbsolutePath() + "/" + localPath; - - if (currentFile.isDirectory()) { - File subDir = new File(destFilePath); - subDir.mkdirs(); - copyTileDirectories(subDir); - } else { - File destFile = new File(destFilePath); - if (destFile.exists()) { - continue; - } - destFile.getParentFile().mkdirs(); - FileUtils.copy(currentFile, destFile, 1028); - } - - } - } - } - - protected void copyFilesNotDirectories(File sourceLoc) throws IOException { - if (sourceLoc.isDirectory()) { - for (File currentFile : sourceLoc.listFiles()) { - String localPath = currentFile.getAbsolutePath().substring(sourceVpfLibLoc.length() + 1); - String destFilePath = outputLocation.getAbsolutePath() + "/" + localPath; - - if (currentFile.isDirectory()) { - File subDir = new File(destFilePath); - if (subDir.exists()) { - copyFilesNotDirectories(currentFile); - } - } else { - File destFile = new File(destFilePath); - if (destFile.exists()) { - continue; - } - destFile.getParentFile().mkdirs(); - FileUtils.copy(currentFile, destFile, 1028); - } - - } - } - } - - protected void trim(Rectangle2D filter) throws IOException { - - double ulx = filter.getX(); - double uly = filter.getY(); - double lrx = ulx + filter.getWidth(); - double lry = uly - filter.getHeight(); - - uly = Math.toDegrees(ProjMath.normalizeLatitude(Math.toRadians(uly), Math.toRadians(10.0))); - lry = Math.toDegrees(ProjMath.normalizeLatitude(Math.toRadians(lry), Math.toRadians(10.0))); - ulx = Math.toDegrees(ProjMath.wrapLongitude(Math.toRadians(ulx))); - lrx = Math.toDegrees(ProjMath.wrapLongitude(Math.toRadians(lrx))); - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine("filtering on: " + uly + ", " + lry + ", " + lrx + ", " + ulx); - } - - try { - - for (String libName : lst.getLibraryNames()) { - CoverageAttributeTable cat = lst.getCAT(libName); - List td = cat.tilesInRegion((float) uly, (float) lry, (float) lrx, (float) ulx); - if (td != null) { - for (TileDirectory t : td) { - for (String covName : cat.getCoverageNames()) { - copyTileDirectories(new File(sourceVpfLibLoc, libName + "/" + covName + "/" + t.getPath())); - } - - copyTileDirectories(new File(sourceVpfLibLoc, libName + "/tileref")); - copyTileDirectories(new File(sourceVpfLibLoc, libName + "/libref")); - } - } - } - - } catch (FormatException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static class Builder { - private String vpfPath; - private LibrarySelectionTable lst; - private File outputLocation; - private List filters = new ArrayList(); - - public Builder(String vpfPath) throws FormatException { - this.lst = new LibrarySelectionTable(vpfPath); - this.vpfPath = vpfPath; - } - - /** - * rect defined in decimal degrees, x, y is upper left corner. - * - * @param rect - * @return Builder - */ - public Builder addFilterRect(Rectangle2D rect) { - filters.add(rect); - return (Builder) this; - } - - public Builder addFilterRect(String shpFile, String column, String attribute) throws MalformedURLException, FormatException { - - URL shpURL = PropUtils.getResourceOrFileOrURL(shpFile); - if (shpURL != null) { - EsriGraphicList graphicList = EsriGraphicList.getEsriGraphicList(shpURL, null, null); - DbfTableModel dbf = graphicList.getTable(); - int colIndex = dbf.findColumn(column); - if (colIndex != -1) { - int recordCount = 0; - for (List record : dbf) { - if (record.get(colIndex).equals(attribute)) { - EsriGraphic eg = (EsriGraphic) graphicList.get(recordCount); - // miny, minx, maxy, maxx - double[] extents = eg.getExtents(); - Rectangle2D rect = new Rectangle2D.Double(extents[1], extents[2], extents[3] - extents[1], extents[2] - extents[0]); - addFilterRect(rect); - getLogger().fine("Adding rect for " + attribute + " :" + rect); - } - recordCount++; - } - } else { - throw new FormatException("Column " + column + " not found"); - } - - } - - return (Builder) this; - } - - public VpfCoverageTrimmer create(String outputLocationDirectory) { - - File vpfPathDir = new File(vpfPath); - outputLocation = new File(outputLocationDirectory, vpfPathDir.getName()); - - if (filters.isEmpty()) { - // If no filters have been added, do whole world - filters.add(new Rectangle2D.Double(-180.0, 90.0, 360.0, 180.0)); - } - - return new VpfCoverageTrimmer(this); - } - } - - public static void main(String[] args) { - String vpfPath = "/Volumes/data/vpf/dnc/dnc01"; - - try { - new VpfCoverageTrimmer.Builder(vpfPath).addFilterRect("/Volumes/data/shape/world/cntry02/cntry02.shp", "CNTRY_NAME", "Gabon").create("/Users/dietrick/Desktop").go(); - - } catch (FormatException fe) { - System.out.println(fe.getMessage()); - } catch (IOException ioe) { - System.out.println(ioe.getMessage()); - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/layer/vpf/package.html b/src/core/src/main/java/com/bbn/openmap/layer/vpf/package.html deleted file mode 100644 index bd1f8312b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/layer/vpf/package.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - -This package contains code for dealing with NIMA data distributed in -Vector Product Format. (Mil-Std 2407) - -

-The javadoc for the {@link com.bbn.openmap.layer.vpf.VPFLayer VPFLayer} -has a description of the properties the layer uses. - - @see com.bbn.openmap.layer.vpf.DescribeDB - @see com.bbn.openmap.layer.vpf.Server - @see com.bbn.openmap.layer.vpf.VPFLayer - @see com.bbn.openmap.layer.vpf.LibrarySelectionTable - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditor.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditor.java deleted file mode 100644 index edc1499e6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditor.java +++ /dev/null @@ -1,412 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/BasicStrokeEditor.java,v $ -// $RCSfile: BasicStrokeEditor.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 20:01:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/* Java Core */ -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.FlowLayout; -import java.awt.Graphics2D; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeSupport; -import java.util.List; - -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * The BasicStrokeEditor provides a GUI to adjust BasicStroke - * parameters. It can provide a default button to launch itself, or a - * button can be set. This class is being replaced by the - * BasicStrokeEditorMenu. - */ -public class BasicStrokeEditor extends JDialog implements ActionListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected BasicStroke basicStroke = null; - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - protected float width; // must be >= 0f - protected int endCaps; //CAP_ROUND, CAP_BUTT, CAP_SQUARE - protected int lineJoins; //JOIN_BEVEL, JOIN_MITER, JOIN_ROUND - protected float miterLimit; // 10f default, must be >= 1f - protected float[] dash; - protected float dashPhase; - - public BasicStrokeEditor() { - basicStroke = new BasicStroke(1f); - } - - public BasicStrokeEditor(BasicStroke bs) { - if (bs != null) { - basicStroke = bs; - } else { - basicStroke = new BasicStroke(1f); - } - - setStrokeWidth(basicStroke.getLineWidth()); - setMiterLimit(basicStroke.getMiterLimit()); - setDash(basicStroke.getDashArray()); - setDashPhase(basicStroke.getDashPhase()); - setEndCaps(basicStroke.getEndCap()); - setLineJoins(basicStroke.getLineJoin()); - } - - public void resetStroke() { - BasicStroke oldStroke = basicStroke; - setMiterLimit(miterLimit); - basicStroke = new BasicStroke(width, endCaps, lineJoins, miterLimit, dash, dashPhase); - pcs.firePropertyChange("line", oldStroke, basicStroke); - } - - protected void widgetsToSettings() { - try { - float w = new Float(widthField.getText()).floatValue(); - if (w < 0) - w = 0; - width = w; - } catch (NumberFormatException nfe) { - width = 1f; - } - - try { - setMiterLimit(new Float(miterLimitField.getText()).floatValue()); - } catch (NumberFormatException nfe) { - setMiterLimit(10f); - } - - dash = stringToDashArray(dashField.getText()); - - try { - float dp = new Float(dashPhaseField.getText()).floatValue(); - if (dp < 0f) - dp = 0f; - dashPhase = dp; - } catch (NumberFormatException nfe) { - dashPhase = 0f; - } - - endCaps = capBox.getSelectedIndex(); - lineJoins = joinBox.getSelectedIndex(); - } - - protected transient JTextField widthField, miterLimitField, dashField, - dashPhaseField; - protected transient JPanel palette = null; - protected transient JButton closebutton; - protected transient JButton applybutton; - protected transient JComboBox capBox; - protected transient JComboBox joinBox; - - public void setGUI() { - - if (palette == null) { - setTitle("Modify Line Stroke Parameters"); - palette = new JPanel(); - palette.setLayout(new BoxLayout(palette, BoxLayout.Y_AXIS)); - - JPanel capPanel = PaletteHelper.createPaletteJPanel("Line Cap Decoration"); - String[] capStrings = { "Butt", "Round", "Square" }; - capBox = new JComboBox<>(capStrings); - capBox.addActionListener(this); - capPanel.add(capBox); - palette.add(capPanel); - - JPanel joinPanel = PaletteHelper.createPaletteJPanel("Line Joint Decoration"); - - String[] joinStrings = { "Miter", "Round", "Bevel" }; - joinBox = new JComboBox<>(joinStrings); - joinBox.addActionListener(this); - joinPanel.add(joinBox); - palette.add(joinPanel); - - JPanel widthPanel = new JPanel(); - widthPanel.setLayout(new GridLayout(0, 1)); - - JLabel widthLabel = new JLabel("Line Width"); - widthField = new JTextField(Float.toString(basicStroke.getLineWidth()), 4); - widthField.setToolTipText("Enter pixel width of line."); - widthPanel.add(widthLabel); - widthPanel.add(widthField); - - JPanel mlPanel = new JPanel(); - mlPanel.setLayout(new GridLayout(0, 1)); - - JLabel miterLimitLabel = new JLabel("Miter Limit"); - miterLimitField = new JTextField(Float.toString(basicStroke.getMiterLimit()), 4); - miterLimitField.setToolTipText("Min angle for corner decorations."); - - mlPanel.add(miterLimitLabel); - mlPanel.add(miterLimitField); - - JPanel dlPanel = new JPanel(); - dlPanel.setLayout(new FlowLayout()); - - JLabel dashLabel = new JLabel("Dash Pattern"); -// float[] da = basicStroke.getDashArray(); -// String dashArrayString = dashArrayToString(da); - - dashField = new JTextField(dashArrayToString(basicStroke.getDashArray()), 15); - dashField.setToolTipText("Number of pixels on off on ..."); - dlPanel.add(dashLabel); - dlPanel.add(dashField); - - JPanel dpPanel = new JPanel(); - dpPanel.setLayout(new GridLayout(0, 1)); - - JLabel dashPhaseLabel = new JLabel("Dash Phase"); - dashPhaseField = new JTextField(Float.toString(basicStroke.getDashPhase()), 4); - dashPhaseField.setToolTipText("Phase to start dash array."); - dpPanel.add(dashPhaseLabel); - dpPanel.add(dashPhaseField); - - JPanel textFieldPanel = new JPanel(); - textFieldPanel.setLayout(new GridLayout(0, 3)); - textFieldPanel.add(widthPanel); - textFieldPanel.add(dpPanel); - textFieldPanel.add(mlPanel); - palette.add(textFieldPanel); - palette.add(dlPanel); - - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout(new GridLayout(0, 2)); - closebutton = new JButton("Cancel"); - closebutton.addActionListener(this); - applybutton = new JButton("OK"); - applybutton.addActionListener(this); - buttonPanel.add(applybutton); - buttonPanel.add(closebutton); - - palette.add(buttonPanel); - - getContentPane().add(palette); - this.pack(); - - } else { - widthField.setText(Float.toString(basicStroke.getLineWidth())); - miterLimitField.setText(Float.toString(basicStroke.getMiterLimit())); - dashField.setText(dashArrayToString(basicStroke.getDashArray())); - dashPhaseField.setText(Float.toString(basicStroke.getDashPhase())); - } - - // Set palette to current conditions; - capBox.setSelectedIndex(basicStroke.getEndCap()); - joinBox.setSelectedIndex(basicStroke.getLineJoin()); - } - - public final static String NONE = "No Dash Pattern"; - - public static String dashArrayToString(float[] da) { - if (da == null) { - return NONE; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < da.length; i++) { - sb.append(Float.toString(da[i])).append(" "); - } - return sb.toString(); - } - - public static float[] stringToDashArray(String das) { - if (das == null || das.equals(NONE) || das.length() == 0) { - return null; - } - - List floats = PropUtils.parseSpacedMarkers(das); - float[] ret = new float[floats.size()]; - int index = 0; - for (String f : floats) { - try { - ret[index++] = Float.parseFloat(f); - } catch (NumberFormatException nfe) { - return null; - } - } - - return ret; - } - - public final static String LaunchCmd = "LAUNCH"; - - public void actionPerformed(ActionEvent event) { - if (event.getSource() == applybutton) { - widgetsToSettings(); - resetStroke(); - this.setVisible(false); - } else if (event.getSource() == closebutton) { - this.setVisible(false); - } else if (event.getActionCommand() == LaunchCmd) { - setGUI(); - this.setVisible(true); - } else { - widgetsToSettings(); - resetStroke(); - } - } - - public BasicStroke getBasicStroke() { - return basicStroke; - } - - public void setBasicStroke(BasicStroke bs) { - basicStroke = bs; - if (launchButton != null) { - // float buttonHeight = (bs == null?11:bs.getLineWidth() + - // 10f); - float buttonHeight = 20; - launchButton.setIcon(createIcon(getBasicStroke(), - 40, - (int) buttonHeight, - true)); - } - } - - JButton launchButton; - - public void setLaunchButton(JButton lb) { - launchButton = lb; - } - - public JButton getLaunchButton() { - if (launchButton == null) { -// BasicStroke bs = getBasicStroke(); -// float buttonHeight = (bs == null ? 11 : bs.getLineWidth() + 10f); - float buttonHeight = 20; - ImageIcon icon = createIcon(getBasicStroke(), - 40, - (int) buttonHeight, - true); - launchButton = new JButton(icon); - launchButton.setToolTipText("Modify Line Stroke"); - launchButton.addActionListener(this); - launchButton.setActionCommand(LaunchCmd); - } - return launchButton; - } - - public void setPropertyChangeSupport( - PropertyChangeSupport propertyChangeSupport) { - pcs = propertyChangeSupport; - } - - public PropertyChangeSupport getPropertyChangeSupport() { - return pcs; - } - - /** - * Given a BasicStroke, create an ImageIcon that shows it. - * - * @param stroke the BasicStroke to draw on the Icon. - * @param width the width of the icon. - * @param height the height of the icon. - * @param horizontalOrientation if true, draw line on the icon - * horizontally, else draw it vertically. - */ - public static ImageIcon createIcon(BasicStroke stroke, int width, - int height, boolean horizontalOrientation) { - - BufferedImage bigImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) bigImage.getGraphics(); - - g.setBackground(OMColor.clear); - g.setPaint(OMColor.clear); - g.fillRect(0, 0, width, height); - g.setPaint(Color.black); - g.setStroke(stroke); - if (horizontalOrientation) { - g.drawLine(0, height / 2, width, height / 2); - } else { - g.drawLine(width / 2, 0, width / 2, height); - } - - return new ImageIcon(bigImage); - } - - public void setStrokeWidth(float w) { - if (w < 1) - w = 1; - width = w; - } - - public float getStrokeWidth() { - return width; - } - - public void setMiterLimit(float ml) { - if (ml < 1f) - miterLimit = 10f; - else - miterLimit = ml; - } - - public float getMiterLimit() { - return miterLimit; - } - - public void setDash(float[] da) { - dash = da; - } - - public float[] getDash() { - return dash; - } - - public void setDashPhase(float dp) { - dashPhase = dp; - } - - public float getDashPhase() { - return dashPhase; - } - - public void setEndCaps(int ec) { - endCaps = ec; - } - - public int getEndCaps() { - return endCaps; - } - - public void setLineJoins(int lj) { - lineJoins = lj; - } - - public int getLineJoins() { - return lineJoins; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditorMenu.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditorMenu.java deleted file mode 100644 index d970409f4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/BasicStrokeEditorMenu.java +++ /dev/null @@ -1,438 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/BasicStrokeEditorMenu.java,v $ -// $RCSfile: BasicStrokeEditorMenu.java,v $ -// $Revision: 1.8 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/* Java Core */ -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeSupport; -import java.util.List; - -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JMenu; -import javax.swing.JPopupMenu; -import javax.swing.JRadioButtonMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - */ -public class BasicStrokeEditorMenu extends JPopupMenu { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected BasicStroke basicStroke = null; - protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - protected float width; // must be >= 0f - protected int endCaps; //CAP_ROUND, CAP_BUTT, CAP_SQUARE - protected int lineJoins; //JOIN_BEVEL, JOIN_MITER, JOIN_ROUND - protected float miterLimit; // 10f default, must be >= 1f - protected float[] dash; - protected float dashPhase; - - private I18n i18n = Environment.getI18n(); - - protected JButton launchButton; - - public BasicStrokeEditorMenu() { - this(new BasicStroke(1f)); - } - - public BasicStrokeEditorMenu(BasicStroke bs) { - if (bs != null) { - basicStroke = bs; - } else { - basicStroke = new BasicStroke(1f); - } - - setBasicStroke(basicStroke); - } - - public void setLaunchButton(JButton lb) { - launchButton = lb; - } - - public JButton getLaunchButton() { - if (launchButton == null) { - float buttonHeight = 20; - ImageIcon icon = createIcon(getBasicStroke(), - 50, - (int) buttonHeight, - true); - launchButton = new JButton(icon); - launchButton.setToolTipText(i18n.get(BasicStrokeEditorMenu.class, "Modify_Line_Parameters", "Modify Line Parameters")); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JButton button = getLaunchButton(); - JPopupMenu popup = new JPopupMenu(); - setGUI(popup); - popup.show(button, button.getWidth(), 0); - } - }); - } - return launchButton; - } - - public void resetStroke() { - BasicStroke oldStroke = basicStroke; - setMiterLimit(miterLimit); - basicStroke = new BasicStroke(width, endCaps, lineJoins, miterLimit, dash, dashPhase); - if (launchButton != null) { - launchButton.setIcon(createIcon(basicStroke, 50, 20, true)); - } - pcs.firePropertyChange("line", oldStroke, basicStroke); - } - - public void show(java.awt.Component invoker, int x, int y) { - this.removeAll(); - setGUI(this); - super.show(invoker, x, y); - } - - public JComponent setGUI(JComponent popup) { - - //////// Line Cap - JMenu capMenu = new JMenu(i18n.get(BasicStrokeEditorMenu.class, "Cap_Decoration", "Cap Decoration")); - - ActionListener listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setEndCaps(Integer.parseInt(command)); - resetStroke(); - } catch (NumberFormatException e) { - } - } - }; - - ButtonGroup group = new ButtonGroup(); - JRadioButtonMenuItem button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Butt", "Butt"), endCaps == BasicStroke.CAP_BUTT); - button.setActionCommand(String.valueOf(BasicStroke.CAP_BUTT)); - group.add(button); - button.addActionListener(listener); - capMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Round", "Round"), endCaps == BasicStroke.CAP_ROUND); - button.setActionCommand(String.valueOf(BasicStroke.CAP_ROUND)); - group.add(button); - button.addActionListener(listener); - capMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Square", "Square"), endCaps == BasicStroke.CAP_SQUARE); - button.setActionCommand(String.valueOf(BasicStroke.CAP_SQUARE)); - group.add(button); - button.addActionListener(listener); - capMenu.add(button); - - //////// Line Joins - - JMenu joinMenu = new JMenu(i18n.get(BasicStrokeEditorMenu.class, "Joint_Decoration", "Joint Decoration")); - - listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setLineJoins(Integer.parseInt(command)); - resetStroke(); - } catch (NumberFormatException e) { - } - } - }; - - group = new ButtonGroup(); - button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Miter", "Miter"), lineJoins == BasicStroke.JOIN_MITER); - button.setActionCommand(String.valueOf(BasicStroke.JOIN_MITER)); - group.add(button); - button.addActionListener(listener); - joinMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Round", "Round"), lineJoins == BasicStroke.JOIN_ROUND); - button.setActionCommand(String.valueOf(BasicStroke.JOIN_ROUND)); - group.add(button); - button.addActionListener(listener); - joinMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(BasicStrokeEditorMenu.class, "Bevel", "Bevel"), lineJoins == BasicStroke.JOIN_BEVEL); - button.setActionCommand(String.valueOf(BasicStroke.JOIN_BEVEL)); - group.add(button); - button.addActionListener(listener); - joinMenu.add(button); - - //////// Line Width - - JMenu widthMenu = new JMenu(i18n.get(BasicStrokeEditorMenu.class, "Line_Width", "Line_Width")); - - listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setStrokeWidth((float) Integer.parseInt(command)); - resetStroke(); - } catch (NumberFormatException e) { - } - } - }; - - group = new ButtonGroup(); - ImageIcon ii; - int i; - for (i = 1; i < 13; i++) { - ii = createIcon(new BasicStroke(i), 50, 20, true); - button = new JRadioButtonMenuItem(" ", ii, (int) width == i);//without the space as a parameter these instances look strange with some Look&Feel - button.setActionCommand(String.valueOf(i)); - group.add(button); - button.addActionListener(listener); - button.setMargin( new java.awt.Insets(0,10,0,10)); - button.setPreferredSize(new java.awt.Dimension(70,20)); - widthMenu.add(button); - } - - //////// Dash Pattern - - JMenu dashMenu = new JMenu(i18n.get(BasicStrokeEditorMenu.class, "Dash_Pattern", "Dash Pattern")); - - listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setDash(stringToDashArray(command)); - resetStroke(); - } catch (NumberFormatException e) { - } - } - }; - - group = new ButtonGroup(); - - String[] patterns = new String[] { NONE, "1.0 3.0", "3.0 3.0", "12.0 10.0", - "12.0 10.0 6.0 10.0", "20.0 10.0", "20.0 10.0 6.0 10.0", "20.0 10.0 6.0 10.0 6.0 10.0" }; - - String currentDash = dashArrayToString(getDash()); - for (i = 0; i < patterns.length; i++) { - BasicStroke dashStroke = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, stringToDashArray(patterns[i]), 0.0f); - ii = createIcon(dashStroke, 90, 10, true); - - button = new JRadioButtonMenuItem(" ", ii, currentDash.equals(patterns[i])); - button.setActionCommand(patterns[i]); - group.add(button); - button.addActionListener(listener); - button.setMargin( new java.awt.Insets(0,10,0,10)); - button.setPreferredSize(new java.awt.Dimension(110,20)); - dashMenu.add(button); - } - - popup.add(widthMenu); - popup.add(dashMenu); - popup.add(capMenu); - popup.add(joinMenu); - - return popup; - } - - public final static String NONE = "No Dash Pattern"; - - public static String dashArrayToString(float[] da) { - if (da == null) { - return NONE; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < da.length; i++) { - sb.append(Float.toString(da[i])).append(" "); - } - return sb.toString().trim(); - } - - public static float[] stringToDashArray(String das) { - if (das == null || das.equals(NONE) || das.length() == 0) { - return null; - } - - List floats = PropUtils.parseSpacedMarkers(das); - float[] ret = new float[floats.size()]; - int index = 0; - for (String f : floats) { - try { - ret[index++] = Float.parseFloat(f); - } catch (NumberFormatException nfe) { - return null; - } - } - - return ret; - } - - public BasicStroke getBasicStroke() { - return basicStroke; - } - - public void setBasicStroke(BasicStroke bs) { - basicStroke = bs; - setStrokeWidth(basicStroke.getLineWidth()); - setMiterLimit(basicStroke.getMiterLimit()); - setDash(basicStroke.getDashArray()); - setDashPhase(basicStroke.getDashPhase()); - setLineJoins(basicStroke.getLineJoin()); - setEndCaps(basicStroke.getEndCap()); - } - - public void setPropertyChangeSupport( - PropertyChangeSupport propertyChangeSupport) { - pcs = propertyChangeSupport; - } - - public PropertyChangeSupport getPropertyChangeSupport() { - return pcs; - } - - /** - * Given a BasicStroke, create an ImageIcon that shows it. - * - * @param stroke the BasicStroke to draw on the Icon. - * @param width the width of the icon. - * @param height the height of the icon. - * @param horizontalOrientation if true, draw line on the icon - * horizontally, else draw it vertically. - */ - public static ImageIcon createIcon(BasicStroke stroke, int width, - int height, boolean horizontalOrientation) { - - BufferedImage bigImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) bigImage.getGraphics(); - - g.setBackground(OMColor.clear); - g.setPaint(OMColor.clear); - g.fillRect(0, 0, width, height); - g.setPaint(Color.black); - g.setStroke(stroke); - if (horizontalOrientation) { - g.drawLine(0, height / 2, width, height / 2); - } else { - g.drawLine(width / 2, 0, width / 2, height); - } - - return new ImageIcon(bigImage); - } - - /** - * Given a BasicStroke, create an ImageIcon that shows it. - * - * @param stroke the BasicStroke to draw on the Icon. - * @param width the width of the icon. - * @param height the height of the icon. - * @param horizontalOrientation if true, draw line on the icon - * horizontally, else draw it vertically. - */ - public static ImageIcon createColorIcon(BasicStroke stroke, int width, - int height, boolean horizontalOrientation, - Color color, Color background, Color matting) { - - BufferedImage bigImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) bigImage.getGraphics(); - - g.setBackground(OMColor.clear); - g.setPaint(OMColor.clear); - g.fillRect(0, 0, width, height); - - g.setPaint(background); - g.fillRect(0, 0, width, height); - if (matting != null) { - BasicStroke mattedStroke=new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f); - g.setStroke(mattedStroke); - g.setPaint(matting); - g.drawLine(0,height/2,width,height/2); - } - g.setPaint(color); - g.setStroke(stroke); - if (horizontalOrientation) { - g.drawLine(0, height / 2, width, height / 2); - } else { - g.drawLine(width / 2, 0, width / 2, height); - } - return new ImageIcon(bigImage); - } - - public void setStrokeWidth(float w) { - if (w < 1) - w = 1; - width = w; - } - - public float getStrokeWidth() { - return width; - } - - public void setMiterLimit(float ml) { - if (ml < 1f) - miterLimit = 10f; - else - miterLimit = ml; - } - - public float getMiterLimit() { - return miterLimit; - } - - public void setDash(float[] da) { - dash = da; - } - - public float[] getDash() { - return dash; - } - - public void setDashPhase(float dp) { - dashPhase = dp; - } - - public float getDashPhase() { - return dashPhase; - } - - public void setEndCaps(int ec) { - endCaps = ec; - } - - public int getEndCaps() { - return endCaps; - } - - public void setLineJoins(int lj) { - lineJoins = lj; - } - - public int getLineJoins() { - return lineJoins; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributes.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributes.java deleted file mode 100644 index b045caa38..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributes.java +++ /dev/null @@ -1,2206 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/DrawingAttributes.java,v $ -// $RCSfile: DrawingAttributes.java,v $ -// $Revision: 1.28 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.omGraphics; - -/* - * Java Core - */ -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.GradientPaint; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.TexturePaint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JSeparator; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.awt.ShapeRenderer; -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.tools.icon.IconPartList; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.tools.icon.OpenMapAppPartCollection; -import com.bbn.openmap.util.HashCodeUtil; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.OptionPropertyEditor; - -/** - * DrawingAttributes provides a mechanism for loading and managing different - * drawing attributes that may be used. Several layers need to be able to have - * Properties define how objects should be drawn, and the list of these drawing - * attributes tend to be the same. The DrawingAttributes class fishes out the - * applicable properties for you, creates the objects needed, and then lets you - * get those objects when needed. - *

- * - * The list of properties that the DrawingAttributes object can handle are - * listed below. If a property is not set, the default value will be used. - * - *

- * 
- *     # The Edge or Line color
- *     lineColor=AARRGGBB (Hex ARGB Color, black is default)
- *     # The Fill color for 2D shapes
- *     fillColor=AARRGGBB (Hex ARGB Color, clean is default)
- *     # A highlight color to switch a graphic to when "selected".
- *     selectColor=AARRGGBB (Hex ARGB Color, black is default)
- *     # A file or URL that can be used for a fill pattern, in place of the fill color.
- *     fillPattern=file://file (default is N/A)
- *     # The line width of the edge of the graphic
- *     lineWidth=int (1 is default)
- *     # A pattern to use for a dashed line, reflected as a
- *     # space-separated list of numbers, which are interpreted as on dash
- *     # length, off dash length, on dash length, etc.
- *     dashPattern=10 5 3 5 (5 5 is the default if an error occurs reading the numbers, a non-dashed line is the default.)
- *     The phase for the dash pattern,
- *     dashPhase=0.0f (0 is the default)
- *     # The scale to use for certain measurements, so that fill patterns
- *     # can be scaled depending on the map scale compared to the
- *     # baseScale.
- *     baseScale=XXXXXX (where 1:XXXXXX is the scale to use.  N/A for the default).
- *     # Set whether any OMPoints that are given to the DrawingAttributes object are oval or rectangle.
- *     pointOval=false
- *     # Set the pixel radius of any OMPoint given to the DrawingAttributes object.
- *     pointRadius=2
- * 
- * 
- */ -public class DrawingAttributes implements ActionListener, Serializable, Cloneable, - PropertyConsumer, PropertyChangeListener, ShapeRenderer { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.DrawingAttributes"); - /** - * - */ - private static final long serialVersionUID = -3375553175496133974L; - /** - * The name of the property that holds the line paint of the graphics. - */ - public final static String linePaintProperty = "lineColor"; - // /** - // * The name of the property that holds the text paint for Text, - // * in case that should be different for labels, etc. - // */ - // public final static String textPaintProperty = "textColor"; - /** - * The name of the property that holds the fill paint of the graphics. - */ - public final static String fillPaintProperty = "fillColor"; - /** - * The name of the property that holds the select paint of the graphics, - * which is the line paint that gets set with the default OMGraphic.select() - * action. - */ - public final static String selectPaintProperty = "selectColor"; - /** - * The name of the property that holds the matting paint of the graphics, - * which is the wider line paint that gets set when matting is enabled. - */ - public final static String mattingPaintProperty = "mattingColor"; - /** - * The property that specifies an URL or file a image file to be used to - * construct the Paint object for a texture fill pattern. If the fillPattern - * is null, the fillPaint will be used. - */ - public static final String fillPatternProperty = "fillPattern"; - /** - * The name of the property that holds the lineWidth of the graphics. - */ - public final static String lineWidthProperty = "lineWidth"; - /** - * The name of the property that holds a dashed pattern for lines. This will - * be used to build the stroke object for lines. This pattern should be two - * space-separated numbers, the first representing the pixel length of the - * line in the dash, the second being the space pixel length of the dash. - */ - public final static String dashPatternProperty = "dashPattern"; - /** - * The name of the property that holds a dashed phase for lines. This will - * be used to build the stroke object for lines. - */ - public final static String dashPhaseProperty = "dashPhase"; - /** - * The name of the property that holds the cap for the ends of lines. - * BasicStroke values apply, CAP_BUTT, CAP_ROUND, CAP_SQUARE. - */ - public final static String capProperty = "cap"; - /** - * The name of the property that holds the join for lines. BasicStroke - * values apply, JOIN_MITER, JOIN_ROUND, JOIN_BEVEL. - */ - public final static String joinProperty = "join"; - /** - * The name of the property that controls miterLimits. - */ - public final static String miterLimitProperty = "miterLimit"; - /** - * The base scale to use for the image provided for the fill pattern. As the - * scale of the map changes, the base scale can be used as a reference to - * change the resolution of the pattern. This scale will also be used for - * strokes. - */ - public static final String baseScaleProperty = "baseScale"; - /** - * Set whether a thin black matting should be drawing around the OMGraphic. - */ - public static final String mattedProperty = "matted"; - /** - * Property for whether OMPoints should be oval. "pointOval" - */ - public static final String PointOvalProperty = "pointOval"; - /** - * Property for the pixel radius of OMPoints. "pointRadius" - */ - public static final String PointRadiusProperty = "pointRadius"; - public final static int NONE = -1; - /** - * The default line paint. (black) - */ - public final static String defaultLinePaintString = "0"; // black - /** - * The default fill paint. (none) - */ - public final static String defaultFillPaintString = "-1"; // none - /** - * The default fill paint. (black) - */ - public final static String defaultSelectPaintString = "0"; // black - /** - * The default matting paint. (black) - */ - public final static String defaultMattingPaintString = "0"; // black - /** - * The default line width - */ - public final static float defaultLineWidth = 1f; - /** - * The default dash phase, which is zero. - */ - public final static float defaultDashPhase = 0f; - /** - * The default dash length, for opaque and transparent parts. - */ - public final static float defaultDashLength = 5f; - /** - * The paint to outline the shapes. - */ - protected Paint linePaint = Color.black; - // /** The paint for text. Default to black. */ - // protected Paint textPaint = linePaint; - /** - * The select paint for the shapes. - */ - protected Paint selectPaint = Color.black; - /** - * The paint to fill the shapes. - */ - protected Paint fillPaint = OMColor.clear; - /** - * The paint to use for matting. - */ - protected Paint mattingPaint = Color.black; - /** - * A TexturePaint pattern, if defined. Overrules fillPaint if fillPaint is - * null or clear. - */ - protected TexturePaint fillPattern = null; - /** - * The line stroke, for dashes, etc. - */ - protected transient Stroke stroke = new BasicStroke(1); - /** - * The base scale for scaling the fill pattern image. If NONE, then the - * resolution of the raw image will always be used. - */ - protected float baseScale = NONE; - /** - * Whether a thin black matting line should be rendered around the - * OMGraphic. - */ - protected boolean matted = false; - protected String propertyPrefix = null; - protected String fPattern = null; // for writing out the - // properties - /** - * The isOval setting to set on OMPoints. - */ - protected boolean pointOval = OMPoint.DEFAULT_ISOVAL; - /** - * The pixel radius to set on OMPoints. - */ - protected int pointRadius = OMPoint.DEFAULT_RADIUS; - /** - * A good ol' generic DrawingAttributes object for all to use. Black lines, - * clear fill paint. - */ - public final static DrawingAttributes DEFAULT = new DrawingAttributes(); - /** - * Support object to notify listeners when something has changed. - */ - protected PropertyChangeSupport propertyChangeSupport = null; - /** - * For internationalization. - */ - protected I18n i18n = Environment.getI18n(); - /** - * Command for line color string adjustments. - */ - public final static String LineColorCommand = "LineColor"; - /** - * Command for fill color string adjustments. - */ - public final static String FillColorCommand = "FillColor"; - /** - * Command for select color string adjustments. - */ - public final static String SelectColorCommand = "SelectColor"; - /** - * Command for matting color string adjustments. - */ - public final static String MattingColorCommand = "MattingColor"; - /** - * Command for adding matting. - */ - public final static String MattedCommand = "MattedCommand"; - private JButton lineColorButton; - private JButton fillColorButton; - private JButton selectColorButton; - private JButton mattingColorButton; - private JToggleButton mattedCheckBox; - protected JMenuItem lineColorItem; - protected JMenuItem fillColorItem; - protected JMenuItem selectColorItem; - protected JMenuItem mattingColorItem; - protected JCheckBoxMenuItem mattedEnabledItem; - protected final static int icon_width = 20; - protected final static int icon_height = 20; - /** - * Flag to disable choice of fill paint selection, from an external source. - */ - protected boolean enableFillPaintChoice = true; - public static boolean alwaysSetTextToBlack = false; - protected transient BasicStrokeEditorMenu bse; - protected int orientation = SwingConstants.HORIZONTAL; - - /** - * Any additional JMenu items that should be added to the line menu. - */ - protected JMenu[] lineMenuAdditions = null; - - /** - * Create a DrawingAttributes with the default settings - clear fill paint - * and pattern, sold black edge line of width 1. - */ - public DrawingAttributes() { - propertyChangeSupport = new PropertyChangeSupport(this); - } - - /** - * Create the DrawingAttributes and call setProperties without a prefix for - * the properties. Call setProperties without a prefix for the properties. - * - * @param props the Properties to look in. - */ - public DrawingAttributes(Properties props) { - this(); - setProperties(null, props); - } - - /** - * Create the DrawingAttributes and call setProperties with a prefix for the - * properties. - * - * @param prefix the prefix marker to use for a property, like - * prefix.propertyName. The period is added in this function. - * @param props the Properties to look in. - */ - public DrawingAttributes(String prefix, Properties props) { - this(); - setProperties(prefix, props); - } - - /** - * Shallow clone. - */ - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - return null; - } - } - - public Stroke cloneBasicStroke() { - if (stroke instanceof BasicStroke) { - BasicStroke bs = (BasicStroke) stroke; - return new BasicStroke(bs.getLineWidth(), bs.getEndCap(), bs.getLineJoin(), bs.getMiterLimit(), bs.getDashArray(), bs.getDashPhase()); - } else { - return new BasicStroke(1); - } - } - - /** - * Shallow. - */ - public void setTo(DrawingAttributes clone) { - clone.linePaint = linePaint; - // clone.textPaint = textPaint; - clone.selectPaint = selectPaint; - clone.fillPaint = fillPaint; - clone.mattingPaint = mattingPaint; - clone.fillPattern = fillPattern; - clone.setStroke(stroke); - clone.baseScale = baseScale; - clone.matted = matted; - clone.pointOval = pointOval; - clone.pointRadius = pointRadius; - clone.enableFillPaintChoice = enableFillPaintChoice; - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DrawingAttributes da = (DrawingAttributes) obj; - return eqTest(da.linePaint, linePaint) && eqTest(da.selectPaint, selectPaint) - && eqTest(da.fillPaint, fillPaint) && eqTest(da.mattingPaint, mattingPaint) - && eqTest(da.fillPattern, fillPattern) && eqTest(da.stroke, stroke) - && eqTest(da.baseScale, baseScale) && eqTest(da.matted, matted) - && da.pointOval == pointOval && da.pointRadius == pointRadius; - } - - /** - * Space saver method used by equals(Object). - * - * @param obj1 - * @param obj2 - * @return true if objects are equal. Object equivalence and equals() test. - */ - private boolean eqTest(Object obj1, Object obj2) { - // Should handle object equivalence and nulls - if (obj1 == obj2) { - return true; - } - return obj1 != null && obj1.equals(obj2); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, linePaint); - result = HashCodeUtil.hash(result, fillPaint); - result = HashCodeUtil.hash(result, selectPaint); - result = HashCodeUtil.hash(result, mattingPaint); - result = HashCodeUtil.hash(result, fillPattern); - result = HashCodeUtil.hash(result, pointOval); - result = HashCodeUtil.hash(result, pointRadius); - result = HashCodeUtil.hash(result, fillPattern); - result = HashCodeUtil.hash(result, stroke); - result = HashCodeUtil.hash(result, matted); - return result; - } - - /** - * If you want to get a DEFAULT DrawingAttributes object that you may - * modify, get your own copy. - */ - public static DrawingAttributes getDefaultClone() { - return (DrawingAttributes) DEFAULT.clone(); - } - - /** - * Simple push of OMGraphic attributes from one to another. - */ - public void transfer(OMGraphic from, OMGraphic to) { - setFrom(from); - setTo(to); - } - - /** - * Simple push of OMGraphic attributes from one to another. Don't put in a - * loop, creates a DrawingAttributes object to do the transfer. If in a - * loop, create one and reuse it with the none-static method. - * - * @param from - * @param to - */ - public static void sTransfer(OMGraphic from, OMGraphic to) { - DrawingAttributes da = getDefaultClone(); - da.transfer(from, to); - } - - /** - * Call setProperties without a prefix for the properties. - * - * @param props the Properties to look in. - * @deprecated use setProperties(props). - */ - public void init(Properties props) { - setProperties(null, props); - } - - /** - * Look at the Properties, and fill in the drawing attributes based in it's - * contents. If a property is not in the properties, it's set to its default - * setting. - * - * @param prefix the prefix marker to use for a property, like - * prefix.propertyName. The period is added in this function. - * @param props the Properties to look in. - * @deprecated use setProperties(prefix, props). - */ - public void init(String prefix, Properties props) { - setProperties(prefix, props); - } - - /** - * Set the Stroke to use for the edge of a graphic. - */ - public void setStroke(Stroke stroke) { - Stroke oldStroke = this.stroke; - this.stroke = stroke; - - // We don't want to call getBasicStrokeEditor, that creates - // the editor if it doesn't exist, which may be problematic - // for cases where there is no Graphics Display. - if (stroke instanceof BasicStroke && bse != null) { - bse.setBasicStroke((BasicStroke) stroke); - // This requires that the JRE has a display, which may be - // unnecessary in some situations where the editor is - // never used. - // BasicStrokeEditorMenu tmpbse = getBasicStrokeEditor(); - // if (tmpbse != null) { - // tmpbse.setBasicStroke((BasicStroke) stroke); - // } - } - - if (propertyChangeSupport != null) { - propertyChangeSupport.firePropertyChange("stroke", oldStroke, stroke); - } - } - - /** - * Get the Stroke used for the lines of a graphic. - */ - public Stroke getStroke() { - return stroke; - } - - /** - * Get the Stroke object, scaled for comparison to the base scale. If the - * base scale equals NONE, it's the same as getStroke(). - * - * @param scale scale to compare to the base scale. - */ - public Stroke getStrokeForScale(float scale) { - if (baseScale != NONE && stroke instanceof BasicStroke) { - BasicStroke bs = (BasicStroke) stroke; - float lineWidth = bs.getLineWidth(); - float[] dash = bs.getDashArray(); - float scaleFactor = scale / baseScale; - int endCaps = bs.getEndCap(); - int lineJoins = bs.getLineJoin(); - float miterLimit = bs.getMiterLimit(); - - lineWidth *= scaleFactor; - for (int i = 0; i < dash.length; i++) { - dash[i] *= scaleFactor; - } - - return new BasicStroke(lineWidth, endCaps, lineJoins, miterLimit, dash, bs.getDashPhase()); - } - return stroke; - } - - /** - * Get the Paint for these attributes, and scale it for the scale compared - * to the base scale set if the fill Paint is a TexturePattern. If the base - * scale equals NONE, or if the Paint is not a TexturePaint, it's the same - * as getFillPaint(). - * - * @param scale scale to compare to the base scale. - * @return a Paint object to use for the fill, scaled if necessary. - */ - public Paint getFillPaintForScale(float scale) { - if (fillPattern != null) { - if (baseScale != NONE) { - BufferedImage bi = fillPattern.getImage(); - float scaleFactor = scale / baseScale; - Image image = bi.getScaledInstance((int) (bi.getWidth() * scaleFactor), (int) (bi.getHeight() * scaleFactor), Image.SCALE_SMOOTH); - try { - bi = BufferedImageHelper.getBufferedImage(image, 0, 0, -1, -1); - - return new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("DrawingAttributes: Interrupted Exception scaling texture paint"); - } - } - } - return fillPattern; - } else { - return fillPaint; - } - } - - /** - * Set the edge paint for the graphics created for the coverage type. - * - * @param lPaint the paint. - */ - public void setLinePaint(Paint lPaint) { - if (lPaint == linePaint) { - return; - } - - Paint oldPaint = linePaint; - linePaint = lPaint; - - if (lineColorButton != null) { - lineColorButton.setIcon(getIconForPaint(linePaint, false)); - } - - if (mattedCheckBox != null) { - mattedCheckBox.setIcon(getMattedIcon(mattingPaint, linePaint)); - } - - propertyChangeSupport.firePropertyChange("linePaint", oldPaint, linePaint); - } - - /** - * Get the line paint for the graphics created for the coverage type. - * - * @return the line paint to use for the edges. - */ - public Paint getLinePaint() { - return linePaint; - } - - /** - * Set the selected edge paint for the graphics created for the coverage - * type. - * - * @param sPaint the paint. - */ - public void setSelectPaint(Paint sPaint) { - if (sPaint == selectPaint) { - return; - } - - Paint oldPaint = selectPaint; - selectPaint = sPaint; - - if (selectColorButton != null) { - selectColorButton.setIcon(getIconForPaint(selectPaint, false)); - } - - propertyChangeSupport.firePropertyChange("selectPaint", oldPaint, selectPaint); - } - - /** - * Get the line paint for the graphics created for the coverage type. - * - * @return the select line paint to use for the edges. - */ - public Paint getSelectPaint() { - return selectPaint; - } - - /** - * Set the fill paint for the graphics created for the coverage type. - * - * @param fPaint the paint. - */ - public void setFillPaint(Paint fPaint) { - if (fPaint == fillPaint) { - return; - } - - Paint oldPaint = fillPaint; - fillPaint = fPaint; - - if (fillColorButton != null) { - fillColorButton.setIcon(getIconForPaint(fillPaint, true)); - } - - propertyChangeSupport.firePropertyChange("fillPaint", oldPaint, fillPaint); - } - - /** - * Get the fill paint for the graphics created for the coverage type. This - * used to return the fillPattern if it was defined. Now, it always returns - * the fillPaint. - * - * @return the fill paint to use for the areas. - */ - public Paint getFillPaint() { - return fillPaint; - } - - /** - * Set the matting paint for the graphics created for the coverage type. The - * matting paint is the paint used for the matting line painted around the - * edge, two pixels wider than the edge line width. Black by default, only - * painted when the matting variable is set to true. - * - * @param mPaint the paint. - */ - public void setMattingPaint(Paint mPaint) { - if (mPaint == mattingPaint) { - return; - } - - Paint oldPaint = mattingPaint; - mattingPaint = mPaint; - - if (mattingColorButton != null) { - mattingColorButton.setIcon(getMattingIconForPaint()); - } - - if (mattedCheckBox != null) { - mattedCheckBox.setIcon(getMattedIcon(mattingPaint, linePaint)); - } - - propertyChangeSupport.firePropertyChange("mattingPaint", oldPaint, mattingPaint); - } - - /** - * Get the matting paint for the OMGraphics - * - * @return the matting paint to use for the areas. - */ - public Paint getMattingPaint() { - return mattingPaint; - } - - /** - * Set the fill pattern TexturePaint to be used as the fill color. If not - * null, the fillPattern will be returned from getFillPaint() instead of - * fillPaint. - * - * @param fPattern the TexturePaint to set. - */ - public void setFillPattern(TexturePaint fPattern) { - Paint oldPattern = fPattern; - fillPattern = fPattern; - - if (fillColorButton != null) { - // GUI doesn't handle fill patterns yet. - } - - propertyChangeSupport.firePropertyChange("fillPattern", oldPattern, fillPattern); - } - - /** - * Get the TexturePaint set as the fill pattern. - * - * @return TexturePaint. - */ - public TexturePaint getFillPattern() { - return fillPattern; - } - - /** - * Set the base scale to use for the texture paint and stroke. If this is - * set to a negative number, then no scaling of the paint or stroke will be - * performed. - * - * @param bScale the base scale to use - 1:bScale. - */ - public void setBaseScale(float bScale) { - if (bScale > 0) { - baseScale = bScale; - } else { - baseScale = NONE; - } - } - - /** - * Get the base scale that the texture paint and dashes are set for. If the - * texture paint and stroke are asked for with a scale, those values will be - * adjusted accordingly. - * - * @return base scale for paint and stroke. - */ - public float getBaseScale() { - return baseScale; - } - - /** - * Return whether the OMGraphic has matting around the edge. - */ - public boolean isMatted() { - return matted; - } - - /** - * Set whether the OMGraphic should have matting around the edge. - */ - public void setMatted(boolean set) { - boolean oldMatted = matted; - matted = set; - - if (mattedCheckBox != null) { - mattedCheckBox.setSelected(matted); - } - - propertyChangeSupport.firePropertyChange("matted", oldMatted, matted); - } - - /** - * Set the pixel radius given to OMPoint objects. - */ - public void setPointRadius(int radius) { - pointRadius = radius; - } - - /** - * Get the pixel radius given to OMPoint objects. - */ - public int getPointRadius() { - return pointRadius; - } - - /** - * Set the oval setting given to OMPoint objects. - */ - public void setPointOval(boolean value) { - pointOval = value; - } - - /** - * Get the oval setting given to OMPoint objects. - */ - public boolean isPointOval() { - return pointOval; - } - - /** - * Set the DrawingAttributes parameters based on the current settings of an - * OMGraphic. - */ - public void setFrom(OMGraphic graphic) { - setFrom(graphic, false); - } - - /** - * Set the DrawingAttributes parameters based on the current settings of an - * OMGraphic, and reset the GUI of the DrawingAttributes object if desired. - */ - public void setFrom(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) { - return; - } - - matted = graphic.isMatted(); - mattingPaint = graphic.getMattingPaint(); - - linePaint = graphic.getLinePaint(); - selectPaint = graphic.getSelectPaint(); - fillPaint = graphic.getFillPaint(); - fillPattern = graphic.getTextureMask(); - - // Need to put this in to keep the gui up to date. Calling - // setStroke fires off a propertyChange reaction that - // potentially harms other parameters, like renderType. - stroke = graphic.getStroke(); - - if (graphic instanceof OMPoint) { - pointRadius = ((OMPoint) graphic).getRadius(); - pointOval = ((OMPoint) graphic).isOval(); - } - - enableFillPaintChoice = !(graphic instanceof NonRegional); - - // Don't want to call this here, it is CPU intensive. - // resetGUI should be called only when the GUI needs to be - // updated. - if (resetGUI) { - resetGUI(); - } - - if (propertyChangeSupport != null) { - propertyChangeSupport.firePropertyChange("all", true, true); - } - } - - /** - * Set all the attributes for the graphic that are contained within this - * DrawingAttributes class. - *

- * - * If the fillPattern is set to a TexturePaint, and the fillPaint is null or - * clear, then the fillPattern will be set as the fill paint. Otherwise, the - * fillPaint will be set in the OMGraphic, and the fillPattern will be set - * too. If the OMGraphic.textureMask is != null, then it will get painted on - * top of the fillPaint. Makes for effects if the fillPattern has some - * transparent spots. - * - * @param graphic OMGraphic. - */ - public void setTo(OMGraphic graphic) { - setTo(graphic, false); - } - - /** - * Set all the attributes for the graphic that are contained within this - * DrawingAttributes class. - *

- * - * If the fillPattern is set to a TexturePaint, and the fillPaint is null or - * clear, then the fillPattern will be set as the fill paint. Otherwise, the - * fillPaint will be set in the OMGraphic, and the fillPattern will be set - * too. If the OMGraphic.textureMask is != null, then it will get painted on - * top of the fillPaint. Makes for effects if the fillPattern has some - * transparent spots. - * - * @param graphic OMGraphic. - * @param resetGUI reset the GUI if desired, set the enableFillPaintChoice - * option if OMGraphic allows it. - */ - public void setTo(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) { - return; - } - - // More efficient to touch each OMGraphic once if this is a list, - // instead of cycling through for each parameter. - if (graphic instanceof OMGraphicList) { - for (OMGraphic omg : ((OMGraphicList) graphic)) { - setTo(omg, resetGUI); - } - return; - } - - setOMGraphicEdgeAttributes(graphic); - - // If the fillPattern is set to a TexturePaint, and the - // fillPaint is null or clear, then the fillPattern will be - // set as the fill paint. Otherwise, the fillPaint will be - // set in the OMGraphic, and the fillPattern will be set too. - // If the OMGraphic.textureMask is != null, then it will get - // painted on top of the fillPaint. Makes for effects if the - // fillPattern has some transparent spots. - if (fillPattern != null && (fillPaint == null || isClear(fillPaint))) { - graphic.setFillPaint(fillPattern); - } else { - graphic.setFillPaint(fillPaint); - graphic.setTextureMask(fillPattern); - } - - graphic.setMatted(matted); - graphic.setMattingPaint(mattingPaint); - - if (graphic instanceof OMPoint) { - ((OMPoint) graphic).setRadius(pointRadius); - ((OMPoint) graphic).setOval(pointOval); - } - - // The GraphicAttribute might be rendering options for this graphic, - // needs to know if fill paint choices are available. - if (resetGUI) { - enableFillPaintChoice = !(graphic instanceof NonRegional); - resetGUI(); - } - } - - /** - * Set the graphic attributes that only pertain to boundaries. This is good - * for polylines, where setting the fill paint will close up the polyline - * making it a polygon. So if you want to paint edge data, use this - * function. Sets line paint, line width, and stroke if graphic is a - * OMGraphic - * - * @param graphic OMGraphic - */ - public void setOMGraphicEdgeAttributes(OMGraphic graphic) { - graphic.setLinePaint(linePaint); - graphic.setSelectPaint(selectPaint); - - if (stroke != null) { - graphic.setStroke(stroke); - } else { - graphic.setStroke(OMGraphic.BASIC_STROKE); - } - } - - /** - * Set all the attributes for the graphic that are contained within this - * DrawingAttributes class. Get the TexturePaint for these attributes, and - * scale it for the scale compared to the base scale set. If the base scale - * equals NONE, the fill pattern is not changed with relation to scale. - * - * @param graphic OMGraphic. - * @param scale scale to compare to the base scale. - */ - public void setOMGraphicAttributesForScale(OMGraphic graphic, float scale) { - setOMGraphicEdgeAttributesForScale(graphic, scale); - graphic.setFillPaint(getFillPaintForScale(scale)); - } - - /** - * Set the graphic attributes that only pertain to boundaries. This is good - * for polylines, where setting the fill paint will close up the polyline - * making it a polygon. So if you want to paint edge data, use this - * function. Sets line paint, line width, and stroke if graphic is a - * OMGraphic The stroke, if the base scale is set, is adjusted accordingly. - * - * @param graphic OMGraphic. - * @param scale scale to compare to the base scale. - */ - public void setOMGraphicEdgeAttributesForScale(OMGraphic graphic, float scale) { - - graphic.setLinePaint(linePaint); - graphic.setSelectPaint(selectPaint); - if (stroke != null) { - graphic.setStroke(getStrokeForScale(scale)); - } else { - graphic.setStroke(OMGraphic.BASIC_STROKE); - } - } - - /** - * A lock to use to limit the number of JColorChoosers that can pop up for a - * given DrawingAttributes GUI. - */ - private boolean colorChooserLock = false; - - /** - * Get the lock to use a JColorChooser. Returns true if you got the lock, - * false if you didn't. - */ - protected synchronized boolean getLock() { - if (colorChooserLock == false) { - colorChooserLock = true; - return colorChooserLock; - } else { - return false; - } - } - - /** - * Release the lock on the JColorChooser. - */ - protected synchronized void releaseLock() { - colorChooserLock = false; - } - - /** - * The DrawingAttributes method for handling ActionEvents. Used to handle - * the GUI actions, like changing the colors, line widths, etc. - */ - public void actionPerformed(ActionEvent e) { - Object source = e.getSource(); - String command = e.getActionCommand(); - String interString; - Paint tmpPaint; - if (command == LineColorCommand && linePaint instanceof Color) { - interString = i18n.get(DrawingAttributes.class, "chooseLineColor", "Choose Line Color"); - tmpPaint = getNewPaint((Component) source, interString, (Color) linePaint); - if (tmpPaint != null) { - setLinePaint(tmpPaint); - } - - } else if (command == FillColorCommand && fillPaint instanceof Color) { - interString = i18n.get(DrawingAttributes.class, "chooseFillColor", "Choose Fill Color"); - tmpPaint = getNewPaint((Component) source, interString, (Color) fillPaint); - if (tmpPaint != null) { - setFillPaint(tmpPaint); - } - - } else if (command == SelectColorCommand && selectPaint instanceof Color) { - interString = i18n.get(DrawingAttributes.class, "chooseSelectColor", "Choose Select Color"); - tmpPaint = getNewPaint((Component) source, interString, (Color) selectPaint); - if (tmpPaint != null) { - setSelectPaint(tmpPaint); - } - } else if (command == MattingColorCommand && mattingPaint instanceof Color) { - interString = i18n.get(DrawingAttributes.class, "chooseMattingColor", "Choose Matting Color"); - tmpPaint = getNewPaint((Component) source, interString, (Color) mattingPaint); - if (tmpPaint != null) { - setMattingPaint(tmpPaint); - } - } else if (command == MattedCommand) { - setMatted(mattedEnabledItem.getState()); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("unrecognized command > " + command); - } - } - } - - /** - * A convenience method to get a color from a JColorChooser. Null will be - * returned if the JColorChooser lock is in place, or if something else is - * done where the JColorChooser would normally return null. - * - * @param source the source component for the JColorChooser. - * @param title the String to label the JColorChooser window. - * @param startingColor the color to give to the JColorChooser to start - * with. Returned if the cancel button is pressed. - * @return Color chosen from the JColorChooser, null if lock for chooser - * can't be acquired. - */ - protected Color getNewPaint(Component source, String title, Color startingColor) { - Color newPaint = null; - if (getLock()) { - newPaint = OMColorChooser.showDialog(source, title, startingColor); - releaseLock(); - } - return newPaint; - } - - /** - * Get the GUI components that control the DrawingAttributes. - * - * @return JButton returns a JButton that triggers a pop-up menu. - */ - public Component getGUI() { - return getGUI(null); - } - - public Component getGUI(String buttonText) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("DrawingAttributes: creating palette."); - } - - return getALineButton(buttonText); - } - - /** - * Callout method to add stuff to popup menu before the stroke editor is - * consulted for additions. Adds colors and line menu additions (arrowhead - * controls for lines, for instance). - * - * @param popup - */ - protected void setPreStrokeMenuOptions(JComponent popup) { - popup.add(getColorMenu()); - - JMenu[] menus = getLineMenuAdditions(); - - if (menus != null) { - for (int i = 0; i < menus.length; i++) { - JMenu menu = menus[i]; - if (menu != null) { - popup.add(menu); - } - } - } - } - - /** - * Calls the editor for strokes to get popup menu addition for stroke - * editing. - * - * @param popup - */ - protected void setStrokeMenuOptions(JComponent popup) { - if (stroke instanceof BasicStroke) { - BasicStrokeEditorMenu tmpbse = getBasicStrokeEditor(); - if (tmpbse != null) { - tmpbse.setGUI(popup); - } - } - } - - /** - * Callout method to add stuff to menu after the stroke menus. - * - * @param popup - */ - protected void setPostStrokeMenuOptions(JComponent popup) { - // Nothing to add here... - } - - /** - * Get a JButton used to bring up the line menu. An ActionListener is added - * that will bring up line/color popup menu. - * - * @return a new JButton is created, every time. - */ - public JButton getALineButton() { - return getALineButton(null); - } - - public JButton getALineButton(String buttonText) { - JButton lineButton = new DrawingAttributesGUIButton(buttonText, this); - - lineButton.setToolTipText(i18n.get(DrawingAttributes.class, "drawingAttributesButton", I18n.TOOLTIP, "Modify Drawing Parameters")); - - lineButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent ae) { - JButton button = (JButton) ae.getSource(); - JPopupMenu popup = new JPopupMenu(); - - setPreStrokeMenuOptions(popup); - setStrokeMenuOptions(popup); - setPostStrokeMenuOptions(popup); - - popup.show(button, button.getWidth(), 0); - } - }); - - return lineButton; - } - - public JMenu getColorAndLineMenu() { - JMenu menu = new JMenu(i18n.get(DrawingAttributes.class, "drawingAttributesButton", "Colors and Lines")); - - setPreStrokeMenuOptions(menu); - setStrokeMenuOptions(menu); - setPostStrokeMenuOptions(menu); - - return menu; - } - - /** - * Gets the JMenu that has the color control options. - * - * @return JMenu with options to bring up color interfaces. - */ - public JMenu getColorMenu() { - JMenu colorMenu = null; - colorMenu = new JMenu(i18n.get(GraphicAttributes.class, "Color", "Color")); - - if (lineColorItem == null) { - resetGUI(); - } - - colorMenu.add(lineColorItem); - colorMenu.add(fillColorItem); - colorMenu.add(selectColorItem); - colorMenu.add(mattingColorItem); - colorMenu.add(new JSeparator()); - colorMenu.add(mattedEnabledItem); - - fillColorItem.setEnabled(enableFillPaintChoice); - return colorMenu; - } - - /** - * A hook to add to the line menu brought up in the GUI for the - * DrawingAttributes. - */ - public void setLineMenuAdditions(JMenu[] lma) { - lineMenuAdditions = lma; - } - - public JMenu[] getLineMenuAdditions() { - return lineMenuAdditions; - } - - /** - * Updates the color and line stroke control buttons to match the current - * settings. - */ - public void resetGUI() { - String interString; - - if (lineColorItem == null) { - interString = i18n.get(DrawingAttributes.class, "lineColorItem", "Change Edge Color"); - lineColorItem = new JMenuItem(interString); - lineColorItem.setActionCommand(LineColorCommand); - lineColorItem.addActionListener(this); - interString = i18n.get(DrawingAttributes.class, "lineColorItem", I18n.TOOLTIP, "Change edge color for rendering."); - lineColorItem.setToolTipText(interString); - } - - if (fillColorItem == null) { - interString = i18n.get(DrawingAttributes.class, "fillColorItem", "Change Fill Color"); - fillColorItem = new JMenuItem(interString); - fillColorItem.setActionCommand(FillColorCommand); - fillColorItem.addActionListener(this); - interString = i18n.get(DrawingAttributes.class, "fillColorItem", I18n.TOOLTIP, "Change fill color for rendering."); - fillColorItem.setToolTipText(interString); - } - - if (selectColorItem == null) { - interString = i18n.get(DrawingAttributes.class, "selectColorItem", "Change Highlight Edge Color"); - selectColorItem = new JMenuItem(interString); - selectColorItem.setActionCommand(SelectColorCommand); - selectColorItem.addActionListener(this); - interString = i18n.get(DrawingAttributes.class, "selectColorItem", I18n.TOOLTIP, "Change highlight edge color rendered during selection."); - selectColorItem.setToolTipText(interString); - } - - if (mattingColorItem == null) { - interString = i18n.get(DrawingAttributes.class, "mattingColorItem", "Change Matted Edge Color"); - mattingColorItem = new JMenuItem(interString); - mattingColorItem.setActionCommand(MattingColorCommand); - mattingColorItem.addActionListener(this); - interString = i18n.get(DrawingAttributes.class, "mattingColorItem", I18n.TOOLTIP, "Change the color of the border around the edge."); - mattingColorItem.setToolTipText(interString); - } - - if (mattedCheckBox == null) { - interString = i18n.get(DrawingAttributes.class, "mattedEnableItem", "Enable Matting on Edge"); - mattedEnabledItem = new JCheckBoxMenuItem(interString, matted); - mattedEnabledItem.setActionCommand(MattedCommand); - mattedEnabledItem.addActionListener(this); - interString = i18n.get(DrawingAttributes.class, "mattedEnableItem", I18n.TOOLTIP, "Enable/Disable matting on edge."); - mattedEnabledItem.setToolTipText(interString); - } - - if (stroke instanceof BasicStroke) { - BasicStrokeEditorMenu tmpbse = getBasicStrokeEditor(); - if (tmpbse != null) { - tmpbse.setBasicStroke((BasicStroke) stroke); - } - } - } - - /** - * Create an ImageIcon from a java.awt.Paint. - * - * @param paint java.awt.Paint - * @param width icon pixel width - * @param height icon pixel height - */ - public static ImageIcon getPaletteIcon(Paint paint, int width, int height) { - BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics(); - graphics.setPaint(paint); - graphics.fillRect(0, 0, width, height); - - return new ImageIcon(bufferedImage); - } - - /** - * Get the PropertyChangeSupport object to register anything that is - * interested in finding out when some parameter has changed. - */ - public PropertyChangeSupport getPropertyChangeSupport() { - return propertyChangeSupport; - } - - public void setPropertyChangeSupport(PropertyChangeSupport support) { - propertyChangeSupport = support; - } - - public static Color calculateTextColor(Color color) { - if (alwaysSetTextToBlack) // Mac OS X - { - return Color.black; - } - - int red = color.getRed(); - int green = color.getGreen(); - int blue = color.getBlue(); - int alpha = color.getAlpha(); - - if (alpha < 128) { - return Color.black; - } - - int newred, newgreen, newblue; - - newred = normalizeOn128(red); - newgreen = normalizeOn128(green); - newblue = normalizeOn128(blue); - - return new Color(newred, newgreen, newblue); - } - - public static int normalizeOn128(int value) { - if (value >= 255) { - return 0; - } else if (value <= 0) { - return 255; - } else if (value <= 128) { - return 192; - } - return 64; - } - - /** - * Sets the properties for the DrawingAttributes. This - * particular method assumes that the marker name is not needed, because all - * of the contents of this Properties object are to be used for this object, - * and scoping the properties with a prefix is unnecessary. - * - * @param props the Properties object. - */ - public void setProperties(java.util.Properties props) { - setProperties(getPropertyPrefix(), props); - } - - public BasicStrokeEditorMenu getBasicStrokeEditor() { - if (bse == null && stroke instanceof BasicStroke) { - try { - bse = new BasicStrokeEditorMenu((BasicStroke) getStroke()); - bse.getPropertyChangeSupport().addPropertyChangeListener(this); - } catch (Exception e) { - // This happens if a java Toolkit is not available. - bse = null; - } - } - return bse; - } - - /** - * Sets the properties for the DrawingAttributes. Part of the - * PropertyConsumer interface. DrawingAttributess which override this method - * should do something like: - * - *

-     * public void setProperties(String prefix, Properties props) {
-     *     super.setProperties(prefix, props);
-     *     // do local stuff
-     * }
-     * 
- * - * If the addToBeanContext property is not defined, it is set to false here. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - - setPropertyPrefix(prefix); - - if (props == null) { - return; - } - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - // Set up the drawing attributes. - linePaint = PropUtils.parseColorFromProperties(props, realPrefix + linePaintProperty, linePaint); - - selectPaint = PropUtils.parseColorFromProperties(props, realPrefix + selectPaintProperty, selectPaint); - - mattingPaint = PropUtils.parseColorFromProperties(props, realPrefix + mattingPaintProperty, mattingPaint); - - // textPaint = - // PropUtils.parseColorFromProperties( - // props, realPrefix + textPaintProperty, - // textPaint); - - fillPaint = PropUtils.parseColorFromProperties(props, realPrefix + fillPaintProperty, fillPaint); - - matted = PropUtils.booleanFromProperties(props, realPrefix + mattedProperty, matted); - - pointRadius = PropUtils.intFromProperties(props, realPrefix + PointRadiusProperty, pointRadius); - pointOval = PropUtils.booleanFromProperties(props, realPrefix + PointOvalProperty, pointOval); - - float lineWidth; - boolean basicStrokeDefined = false; - - if (stroke instanceof BasicStroke) { - basicStrokeDefined = true; - } - - lineWidth = PropUtils.floatFromProperties(props, realPrefix + lineWidthProperty, (basicStrokeDefined ? ((BasicStroke) stroke).getLineWidth() - : defaultLineWidth)); - - baseScale = PropUtils.floatFromProperties(props, realPrefix + baseScaleProperty, baseScale); - - // Look for a dash pattern properties to come up with a stroke - String dPattern = props.getProperty(realPrefix + dashPatternProperty); - if (basicStrokeDefined && dPattern != null && dPattern.length() > 0) { - float dashPhase; - float[] lineDash; - // OK, it exists, come up with a stroke. - try { - StringTokenizer t = new StringTokenizer(dPattern); - int arraySize = t.countTokens(); - lineDash = new float[arraySize]; - - int dashCount = 0; - while (t.hasMoreTokens()) { - String segment = t.nextToken(); - lineDash[dashCount++] = Float.parseFloat(segment); - if (logger.isLoggable(Level.FINE)) { - logger.fine("read " + segment); - } - } - - } catch (NoSuchElementException nsee) { - logger.fine("DrawingAttributes.init: dash pattern attributes wrong - should be dashPattern=(number pixels on) (number pixels off)"); - lineDash = null; - } catch (NumberFormatException nfe) { - logger.fine("DrawingAttributes.init: Number format exception for dashPattern"); - lineDash = null; - } catch (NullPointerException npe) { - logger.fine("DrawingAttributes.init: Caught null pointer exception - probably resulting from non-float number format exception for dashPattern"); - lineDash = null; - } - - if (lineDash == null) { - if (basicStrokeDefined) { - lineDash = ((BasicStroke) stroke).getDashArray(); - } else { - lineDash = new float[2]; - lineDash[0] = defaultDashLength; - lineDash[1] = defaultDashLength; - } - } - - int dashCount = 0; - for (int x = 0; x < lineDash.length; x++) { - dashCount += lineDash[x]; - } - if (dashCount == 0) { - lineDash = null; - } - - String dPhase = props.getProperty(realPrefix + dashPhaseProperty); - if (dPhase != null && dPhase.length() > 0) { - try { - dashPhase = Float.valueOf(dPhase).floatValue(); - } catch (NumberFormatException nfe) { - logger.fine("DrawingAttributes.init: Number format exception for dashPhase"); - dashPhase = defaultDashPhase; - } - } else { - if (basicStrokeDefined) { - dashPhase = ((BasicStroke) stroke).getDashPhase(); - } else { - dashPhase = defaultDashPhase; - } - } - - String capPropertyString = props.getProperty(realPrefix + capProperty); - int cap = BasicStroke.CAP_BUTT; - if (capPropertyString != null) { - try { - cap = java.awt.BasicStroke.class.getField(capPropertyString).getInt(null); - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - } - - String joinPropertyString = props.getProperty(realPrefix + capProperty); - int join = BasicStroke.JOIN_MITER; - if (joinPropertyString != null) { - try { - join = java.awt.BasicStroke.class.getField(joinPropertyString).getInt(null); - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - } - - float miterLimit = PropUtils.floatFromProperties(props, realPrefix + miterLimitProperty, 10.0f); - - setStroke(new BasicStroke(lineWidth, cap, join, miterLimit, lineDash, dashPhase)); - - } else if (basicStrokeDefined) { - BasicStroke currentStroke = (BasicStroke) getStroke(); - setStroke(new BasicStroke(lineWidth, currentStroke.getEndCap(), currentStroke.getLineJoin(), currentStroke.getMiterLimit(), currentStroke.getDashArray(), currentStroke.getDashPhase())); - } - - // OK, Fill pattern next... - fPattern = props.getProperty(realPrefix + fillPatternProperty); - if (fPattern != null && fPattern.length() != 0) { - - try { - - URL textureImageURL = PropUtils.getResourceOrFileOrURL(fPattern); - - if (textureImageURL != null) { - - BufferedImage bi = BufferedImageHelper.getBufferedImage(textureImageURL, 0, 0, -1, -1); - - fillPattern = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); - } - } catch (MalformedURLException murle) { - logger.fine("DrawingAttributes.init: bad texture URL - \n " + realPrefix - + fillPatternProperty); - fillPattern = null; - } catch (InterruptedException ie) { - logger.fine("DrawingAttributes.init: bad problems getting texture URL - \n" + ie); - fillPattern = null; - } - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - if (linePaint instanceof Color) { - props.put(prefix + linePaintProperty, PropUtils.getProperty((Color) linePaint)); - } - // if (textPaint instanceof Color) { - // props.put(prefix + textPaintProperty, - // PropUtils.getProperty((Color)textPaint)); - // } - if (fillPaint instanceof Color) { - props.put(prefix + fillPaintProperty, PropUtils.getProperty((Color) fillPaint)); - } - if (selectPaint instanceof Color) { - props.put(prefix + selectPaintProperty, PropUtils.getProperty((Color) selectPaint)); - } - if (mattingPaint instanceof Color) { - props.put(prefix + mattingPaintProperty, PropUtils.getProperty((Color) mattingPaint)); - } - - props.put(prefix + PointRadiusProperty, Integer.toString(pointRadius)); - props.put(prefix + PointOvalProperty, new Boolean(pointOval).toString()); - - props.put(prefix + fillPatternProperty, (fPattern == null ? "" : fPattern)); - - Stroke bs = getStroke(); - - if (bs == null) { - bs = new BasicStroke(); - } - - if (bs instanceof BasicStroke) { - props.put(prefix + lineWidthProperty, Float.toString(((BasicStroke) bs).getLineWidth())); - - float[] fa = ((BasicStroke) bs).getDashArray(); - if (fa != null) { - StringBuffer dp = new StringBuffer(); - for (int i = 0; i < fa.length; i++) { - dp.append(" ").append(Float.toString(fa[i])); - } - props.put(prefix + dashPatternProperty, dp.toString().trim()); - props.put(prefix + dashPhaseProperty, Float.toString(((BasicStroke) bs).getDashPhase())); - } else { - props.put(prefix + dashPatternProperty, ""); - props.put(prefix + dashPhaseProperty, ""); - } - - props.put(prefix + capProperty, Integer.toString(((BasicStroke) bs).getEndCap())); - props.put(prefix + joinProperty, Integer.toString(((BasicStroke) bs).getLineJoin())); - props.put(prefix + miterLimitProperty, Float.toString(((BasicStroke) bs).getMiterLimit())); - - } - - if (baseScale != NONE) { - props.put(prefix + baseScaleProperty, Float.toString(baseScale)); - } - - props.put(prefix + mattedProperty, new Boolean(matted).toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - String interString; - - interString = i18n.get(DrawingAttributes.class, linePaintProperty, I18n.TOOLTIP, "Edge color for graphics."); - list.put(linePaintProperty, interString); - interString = i18n.get(DrawingAttributes.class, linePaintProperty, linePaintProperty); - list.put(linePaintProperty + LabelEditorProperty, interString); - list.put(linePaintProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - // list.put(textPaintProperty, "Text color for graphics."); - // list.put(textPaintProperty + ScopedEditorProperty, - // "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, fillPaintProperty, I18n.TOOLTIP, "Fill color for graphics."); - list.put(fillPaintProperty, interString); - interString = i18n.get(DrawingAttributes.class, fillPaintProperty, fillPaintProperty); - list.put(fillPaintProperty + LabelEditorProperty, interString); - list.put(fillPaintProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, selectPaintProperty, I18n.TOOLTIP, "Selected edge color for graphics."); - list.put(selectPaintProperty, interString); - interString = i18n.get(DrawingAttributes.class, selectPaintProperty, selectPaintProperty); - list.put(selectPaintProperty + LabelEditorProperty, interString); - list.put(selectPaintProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, mattingPaintProperty, I18n.TOOLTIP, "Matting edge color for graphics."); - list.put(mattingPaintProperty, interString); - interString = i18n.get(DrawingAttributes.class, mattingPaintProperty, mattingPaintProperty); - list.put(mattingPaintProperty + LabelEditorProperty, interString); - list.put(mattingPaintProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, fillPatternProperty, I18n.TOOLTIP, "Image file to use for fill pattern for graphics (optional)."); - list.put(fillPatternProperty, interString); - interString = i18n.get(DrawingAttributes.class, fillPatternProperty, fillPatternProperty); - list.put(fillPatternProperty + LabelEditorProperty, interString); - list.put(fillPatternProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, lineWidthProperty, I18n.TOOLTIP, "Line width for edges of graphics"); - list.put(lineWidthProperty, interString); - interString = i18n.get(DrawingAttributes.class, lineWidthProperty, lineWidthProperty); - list.put(lineWidthProperty + LabelEditorProperty, interString); - - // list.put(dashPatternProperty, "Line dash - // pattern, represented by
space separated numbers
(on - // off on ...)"); - interString = i18n.get(DrawingAttributes.class, dashPatternProperty, I18n.TOOLTIP, "Line dash pattern, represented by space separated numbers (on off on ...)"); - list.put(dashPatternProperty, interString); - interString = i18n.get(DrawingAttributes.class, dashPatternProperty, dashPatternProperty); - list.put(dashPatternProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingAttributes.class, dashPhaseProperty, I18n.TOOLTIP, "Phase for dash pattern (Default is 0)"); - list.put(dashPhaseProperty, interString); - interString = i18n.get(DrawingAttributes.class, dashPhaseProperty, dashPhaseProperty); - list.put(dashPhaseProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingAttributes.class, baseScaleProperty, I18n.TOOLTIP, "Scale which should be used as the base scale for the
patterns and line width. If set, size of pattern and
widths will be adjusted to the map scale"); - list.put(baseScaleProperty, interString); - interString = i18n.get(DrawingAttributes.class, baseScaleProperty, baseScaleProperty); - list.put(baseScaleProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingAttributes.class, mattedProperty, I18n.TOOLTIP, "Flag to enable a thin black matting to be drawn around graphics."); - list.put(mattedProperty, interString); - interString = i18n.get(DrawingAttributes.class, mattedProperty, mattedProperty); - list.put(mattedProperty + LabelEditorProperty, interString); - list.put(mattedProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - - interString = i18n.get(DrawingAttributes.class, PointRadiusProperty, I18n.TOOLTIP, "Pixel radius of point objects."); - list.put(PointRadiusProperty, interString); - interString = i18n.get(DrawingAttributes.class, PointRadiusProperty, "Point pixel radius"); - list.put(PointRadiusProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingAttributes.class, PointOvalProperty, I18n.TOOLTIP, "Set points to be oval or rectangular."); - list.put(PointOvalProperty, interString); - interString = i18n.get(DrawingAttributes.class, PointOvalProperty, "Points are oval"); - list.put(PointOvalProperty + LabelEditorProperty, interString); - list.put(PointOvalProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, list, DrawingAttributes.class, capProperty, "Line Cap", "Type of cap to use on end of lines.", "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - - list.put(capProperty + OptionPropertyEditor.ScopedOptionsProperty, "butt round square"); - list.put(capProperty + ".butt", "CAP_BUTT"); - list.put(capProperty + ".round", "CAP_ROUND"); - list.put(capProperty + ".square", "CAP_SQUARE"); - - PropUtils.setI18NPropertyInfo(i18n, list, DrawingAttributes.class, joinProperty, "Line Join", "Type of joint to use on corner of line joins.", "com.bbn.openmap.util.propertyEditor.ComboBoxPropertyEditor"); - - list.put(joinProperty + OptionPropertyEditor.ScopedOptionsProperty, "miter round bevel"); - list.put(joinProperty + ".miter", "JOIN_MITER"); - list.put(joinProperty + ".round", "JOIN_ROUND"); - list.put(joinProperty + ".bevel", "JOIN_BEVEL"); - - PropUtils.setI18NPropertyInfo(i18n, list, DrawingAttributes.class, miterLimitProperty, "Miter Limit", "Number of pixels to use for line joints.", null); - - // This line messes order up when called by classes using - // DrawingAttributes. - // list.put(initPropertiesProperty, getInitPropertiesOrder()); - - return list; - } - - public String getInitPropertiesOrder() { - return " " + linePaintProperty + " " + selectPaintProperty + " " + fillPaintProperty + " " - + /* - * textPaintProperty + " " + - */mattingPaintProperty + " " + fillPatternProperty + " " + mattedProperty + " " - + lineWidthProperty + " " + dashPatternProperty + " " + dashPhaseProperty + " " - + capProperty + " " + joinProperty + " " + miterLimitProperty + " " - + PointRadiusProperty + " " + PointOvalProperty; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the prefix String. - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getSource() instanceof BasicStrokeEditorMenu) { - setStroke((BasicStroke) pce.getNewValue()); - } - } - - public String toString() { - StringBuffer sb = new StringBuffer("DrawingAttributes["); - sb.append("linePaint(").append(linePaint).append("), "); - sb.append("selectPaint(").append(selectPaint).append("), "); - // sb.append("textPaint(").append(textPaint).append("), "); - sb.append("mattingPaint(").append(mattingPaint).append("), "); - sb.append("fillPaint(").append(fillPaint).append("), "); - sb.append("fillPattern(").append(fillPattern).append("), "); - sb.append("stroke(").append(stroke).append("), "); - sb.append("baseScale(").append(baseScale).append("), "); - sb.append("matted(").append(new Boolean(matted).toString()).append(")]"); - return sb.toString(); - } - - /** - * Render the Shape into the Graphics2D object, using the mattingPaint, - * fillPaint, fillPattern, linePaint and stroke contained in this - * DrawingAttributes object. - */ - public void render(Graphics2D g, Shape shape) { - render(g, shape, false); - } - - /** - * Render the Shape into the Graphics2D object, using the mattingPaint, - * fillPaint, fillPattern, linePaint and stroke contained in this - * DrawingAttributes object. - * - * @param g java.awt.Graphics2D object to render into - * @param shape java.awt.Shape to draw - * @param replaceColorWithGradient flag to specify replacement of fill and - * edge colors with a GradientPaint to give a light to dark look. You - * can set the Paints in the DrawingAttributes object with - * GradientPaints if you want more control over the GradientPaint, - * but this will let the DrawingAttributes object take a shot at - * creating one for a Color that fits the shape given. - */ - public void render(Graphics2D g, Shape shape, boolean replaceColorWithGradient) { - - if (shape == null) { - return; - } - - if (matted) { - if (stroke instanceof BasicStroke) { - g.setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - g.setPaint(mattingPaint); - g.draw(shape); - } - } - - if (!isClear(fillPaint)) { - g.setStroke(OMGraphicConstants.BASIC_STROKE); - - if (replaceColorWithGradient) { - g.setPaint(getGradientPaintForShape(shape, fillPaint)); - } else { - g.setPaint(fillPaint); - } - - g.fill(shape); - // Seems to help with a rendering problem, not sure why. - // Without this the DrawingAttributes fill icon would not - // be drawn until it was set again. This way, it always - // appears. Might be a Mac thing. - g.draw(shape); - - if (fillPattern != null && fillPattern != fillPaint) { - g.setPaint(fillPattern); - g.fill(shape); - } - } - - if (linePaint != fillPaint) { - g.setStroke(getStroke()); - if (replaceColorWithGradient) { - g.setPaint(getGradientPaintForShape(shape, linePaint)); - } else { - g.setPaint(linePaint); - } - g.draw(shape); - } - } - - /** - * Create a GradientPaint object for the given shape. - * - * @param shape shape to take measurements from to set GradientPaint - * settings - .3 h/w lighter to .7 h/w darker. - * @param paint the base color to use for gradient. - * @return GradientPaint for shape. - */ - public static Paint getGradientPaintForShape(Shape shape, Paint paint) { - if (paint instanceof Color) { - Color color = (Color) paint; - Rectangle rect = shape.getBounds(); - paint = new GradientPaint((float) rect.getWidth() * .3f, (float) rect.getHeight() * .3f, color.brighter().brighter(), (float) rect.getWidth() * .7f, (float) rect.getHeight() * .7f, color.darker().darker()); - } - return paint; - } - - /** - * @return a matting paint choice icon for the current settings of this - * DrawingAttributes object, with the matting paint used. - */ - public ImageIcon getMattingIconForPaint() { - - Paint paint = getMattingPaint(); - - DrawingAttributes da = new DrawingAttributes(); - da.setLinePaint(paint); - da.setStroke(new BasicStroke(3)); - - DrawingAttributes innerda = new DrawingAttributes(); - innerda.setLinePaint(Color.white); - innerda.setStroke(new BasicStroke(1)); - - OpenMapAppPartCollection collection = OpenMapAppPartCollection.getInstance(); - IconPartList parts = new IconPartList(); - - if (paint instanceof Color) { - Color color = (Color) paint; - Paint opaqueColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), 255); - DrawingAttributes opaqueDA = new DrawingAttributes(); - opaqueDA.setLinePaint(opaqueColor); - opaqueDA.setStroke(new BasicStroke(3)); - - parts.add(collection.get("LR_TRI", opaqueDA)); - parts.add(collection.get("UL_TRI", da)); - parts.add(collection.get("LR_TRI", innerda)); - parts.add(collection.get("UL_TRI", innerda)); - } else { - parts.add(collection.get("BIG_BOX", da)); - parts.add(collection.get("BIG_BOX", innerda)); - } - - return OMIconFactory.getIcon(icon_width, icon_height, parts); - } - - /** - * @param paint the paint to use for the icon. - * @param fill if fill color should be used. - * @return an ImageIcon for the provided paint object, two triangles in - * upper left and lower right. Upper left version has transparency - * set. - */ - public static ImageIcon getIconForPaint(Paint paint, boolean fill) { - - if (paint == null) { - paint = Color.black; - } - - DrawingAttributes da = new DrawingAttributes(); - da.setLinePaint(paint); - da.setStroke(new BasicStroke(2)); - if (fill) { - da.setFillPaint(paint); - } - - OpenMapAppPartCollection collection = OpenMapAppPartCollection.getInstance(); - IconPartList parts = new IconPartList(); - - if (paint instanceof Color || paint == OMColor.clear) { - Color color = (Color) paint; - Color opaqueColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); - DrawingAttributes opaqueDA = new DrawingAttributes(); - opaqueDA.setLinePaint(opaqueColor); - opaqueDA.setStroke(new BasicStroke(2)); - - if (fill) { - opaqueDA.setFillPaint(opaqueColor); - } - - parts.add(collection.get("LR_TRI", opaqueDA)); - parts.add(collection.get("UL_TRI", da)); - } else { - parts.add(collection.get("BIG_BOX", da)); - } - - return OMIconFactory.getIcon(icon_width, icon_height, parts); - } - - /** - * @param mattingPaint - * @param linePaint - * @return an ImageIcon that shows a square with the matting paint and line - * paint. - */ - public static ImageIcon getMattedIcon(Paint mattingPaint, Paint linePaint) { - DrawingAttributes da = new DrawingAttributes(); - da.setMattingPaint(mattingPaint); - da.setStroke(new BasicStroke(2)); - - DrawingAttributes fillda = new DrawingAttributes(); - fillda.setLinePaint(linePaint); - fillda.setFillPaint(linePaint); - da.setStroke(new BasicStroke(2)); - - OpenMapAppPartCollection collection = OpenMapAppPartCollection.getInstance(); - - IconPartList parts = new IconPartList(); - parts.add(collection.get("FILL_BOX", fillda)); - parts.add(collection.get("BIG_BOX", da)); - parts.add(collection.get("SMALL_BOX", da)); - - return OMIconFactory.getIcon(icon_width, icon_height, parts); - } - - /** - * Given a BasicStroke, create an ImageIcon that shows it. - * - * @param attributes attributes to use for drawing the icon for the stroke. - * @param width the width of the icon. - * @param height the height of the icon. - * @param horizontalOrientation if true, draw line on the icon horizontally, - * else draw it vertically. - */ - public static ImageIcon getDrawingAttributesIcon(DrawingAttributes attributes, int width, - int height, boolean horizontalOrientation) { - - BufferedImage bigImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) bigImage.getGraphics(); - - g.setBackground(OMColor.clear); - - if (attributes.enableFillPaintChoice) { - g.setPaint(attributes.fillPaint); - g.fillRect(0, 0, width, height); - } - - if (attributes.matted) { - BasicStroke mattedStroke = new BasicStroke(((BasicStroke) attributes.stroke).getLineWidth() + 2f); - g.setStroke(mattedStroke); - g.setPaint(attributes.mattingPaint); - g.drawLine(0, height / 2, width, height / 2); - } - - g.setPaint(attributes.linePaint); - g.setStroke(attributes.stroke); - if (horizontalOrientation) { - g.drawLine(0 + 3, height / 2, width - 3, height / 2); - } else { - g.drawLine(width / 2, 0 + 3, width / 2, height - 3); - } - - return new ImageIcon(bigImage); - } - - public boolean isEnableFillPaintChoice() { - return enableFillPaintChoice; - } - - public void setEnableFillPaintChoice(boolean enableFillPaintChoice) { - this.enableFillPaintChoice = enableFillPaintChoice; - } - - public int getOrientation() { - return orientation; - } - - public void setOrientation(int orientation) { - this.orientation = orientation; - } - - /** - * Checks if the Paint is clear. - * - * @param paint Paint or null. - * @return true if Paint is null or is a Color with a 0 alpha value. - */ - public static boolean isClear(Paint paint) { - if (paint instanceof Color) { - return ((((Color) paint).getRGB() & 0xff000000) == 0); - } else { - return false; - } - } - - /** - * A JButton that listens for PropertyChange notifications from a - * DrawingAttributes object, so it can update its icon. - * - * @author dietrick - */ - protected static class DrawingAttributesGUIButton extends JButton implements - PropertyChangeListener { - - private static final long serialVersionUID = 1L; - DrawingAttributes parentDA; - - protected DrawingAttributesGUIButton(DrawingAttributes da) { - this(null, da); - } - - protected DrawingAttributesGUIButton(String buttonText, DrawingAttributes da) { - super(buttonText, getDrawingAttributesIcon(da, icon_width, icon_height, true)); - da.propertyChangeSupport.addPropertyChangeListener(DrawingAttributesGUIButton.this); - parentDA = da; - } - - /* - * (non-Javadoc) - * - * @see java.beans.PropertyChangeListener#propertyChange(java.beans. - * PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent evt) { - DrawingAttributesGUIButton.this.setIcon(getDrawingAttributesIcon(parentDA, icon_width, icon_height, true)); - } - } - - /** - * Builders are usually for immutable objects, but it seems kinda handy to - * have one for this class, to eliminate lines of code. - * - * @author ddietrick - */ - public static class Builder { - - DrawingAttributes da = null; - - public Builder() { - da = DrawingAttributes.getDefaultClone(); - } - - public Builder setLinePaint(Paint lPaint) { - da.setLinePaint(lPaint); - return this; - } - - public Builder setFillPaint(Paint fPaint) { - da.setFillPaint(fPaint); - return this; - } - - public Builder setSelectPaint(Paint sPaint) { - da.setSelectPaint(sPaint); - return this; - } - - public Builder setStroke(Stroke s) { - da.setStroke(s); - return this; - } - - public Builder setLineWidth(int lineWidth) { - da.setStroke(new BasicStroke(lineWidth)); - return this; - } - - public Builder setFillPattern(TexturePaint tPaint) { - da.setFillPattern(tPaint); - return this; - } - - public Builder setMattingPaint(Paint mPaint) { - da.setMattingPaint(mPaint); - return this; - } - - public Builder setMatted(boolean matted) { - da.setMatted(matted); - return this; - } - - public Builder setPointOval(boolean oval) { - da.setPointOval(oval); - return this; - } - - public Builder setPointRadius(int radius) { - da.setPointRadius(radius); - return this; - } - - public Builder setOrientation(int orientation) { - da.setOrientation(orientation); - return this; - } - - public Builder setFrom(DrawingAttributes anotherDa) { - anotherDa.setTo(da); - return this; - } - - public Builder setFrom(OMGraphic omg) { - da.setFrom(omg); - return this; - } - - public DrawingAttributes build() { - return da; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributesPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributesPropertyEditor.java deleted file mode 100644 index 7ab8abb01..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/DrawingAttributesPropertyEditor.java +++ /dev/null @@ -1,118 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/DrawingAttributesPropertyEditor.java,v $ -// $RCSfile: DrawingAttributesPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/12/15 18:39:54 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.FocusEvent; -import java.util.Properties; - -import javax.swing.JPanel; - -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.PropertyConsumerPropertyEditor; - -/** - * A PropertyEditor for a set of DrawingAttributes properties, providing the - * standard DrawingAttributes GUI for property configuration. - */ -public class DrawingAttributesPropertyEditor - extends PropertyConsumerPropertyEditor { - - protected DrawingAttributes drawingAttributes; - - public DrawingAttributesPropertyEditor() { - } - - public boolean supportsCustomEditor() { - return true; - } - - public void setCustomEditor(Component comp) { - } - - /** Returns the editor GUI. */ - public Component getCustomEditor() { - JPanel panel = new JPanel(); - GridBagLayout layout = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - c.anchor = GridBagConstraints.WEST; - - panel.setLayout(layout); - Component comp = getDrawingAttributes().getGUI(); - if (comp != null) { - layout.setConstraints(comp, c); - panel.add(comp); - } - - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - JPanel filler = new JPanel(); - layout.setConstraints(filler, c); - panel.add(filler); - - return panel; - } - - public DrawingAttributes getDrawingAttributes() { - if (drawingAttributes == null) { - drawingAttributes = DrawingAttributes.getDefaultClone(); - } - return drawingAttributes; - } - - public void setDrawingAttributes(DrawingAttributes drawingAttributes) { - this.drawingAttributes = drawingAttributes; - } - - public void focusGained(FocusEvent e) { - } - - public void focusLost(FocusEvent e) { - firePropertyChange(); - } - - public String getAsText() { - return ""; - } - - /** - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - prefix = PropUtils.decodeDummyMarkerFromPropertyInfo(prefix); - getDrawingAttributes().setProperties(prefix, props); - } - - public Properties getProperties(Properties props) { - if (drawingAttributes != null) { - return drawingAttributes.getProperties(props); - } else { - return props; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMAbstractLine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMAbstractLine.java deleted file mode 100644 index 2d59fa7e7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMAbstractLine.java +++ /dev/null @@ -1,155 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMAbstractLine.java,v $ -// $RCSfile: EditableOMAbstractLine.java,v $ -// $Revision: 1.2 $ -// $Date: 2005/08/10 22:25:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics2D; -import java.awt.Polygon; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.image.BufferedImage; - -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JMenu; -import javax.swing.JRadioButtonMenuItem; - -/** - * The EditableOMAbstractLine encompasses an OMAbstractLine, providing - * a mechanism for adding an arrowhead menu in the line editor menu. - */ -public abstract class EditableOMAbstractLine extends EditableOMGraphic { - - protected JMenu arrowheadMenu = null; - - public Component getGUI(GraphicAttributes graphicAttributes) { - if (graphicAttributes != null) { - JMenu ahm = getArrowHeadMenu(); - graphicAttributes.setLineMenuAdditions(new JMenu[] { ahm }); - } - return null; - } - - public JMenu getArrowHeadMenu() { - - if (arrowheadMenu == null) { - arrowheadMenu = new JMenu(i18n.get(EditableOMAbstractLine.class, "Arrows", "Arrows")); - - ActionListener listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - int what = Integer.parseInt(command); - if (what < 0) { - ((OMAbstractLine) getGraphic()).addArrowHead(false); - } else { - ((OMAbstractLine) getGraphic()).addArrowHead(what); - } - generate(getProjection()); - repaint(); - } catch (NumberFormatException e) { - } - } - }; - - boolean doArrowHead = ((OMAbstractLine) getGraphic()).hasArrowHead(); - int currentDirection = OMArrowHead.ARROWHEAD_DIRECTION_FORWARD; - - if (doArrowHead) { - currentDirection = ((OMAbstractLine) getGraphic()).getArrowHead().getArrowDirectionType(); - } - - int descDir = -1; // this description direction - - ButtonGroup group = new ButtonGroup(); - ImageIcon ii = createArrowIcon(new BasicStroke(1), 50, 20, descDir); - JRadioButtonMenuItem button = new JRadioButtonMenuItem(ii, !doArrowHead); - button.setActionCommand(String.valueOf(descDir)); - group.add(button); - button.addActionListener(listener); - arrowheadMenu.add(button); - - for (descDir = OMArrowHead.ARROWHEAD_DIRECTION_FORWARD; descDir <= OMArrowHead.ARROWHEAD_DIRECTION_BOTH; descDir++) { - ii = createArrowIcon(new BasicStroke(1), 50, 20, descDir); - button = new JRadioButtonMenuItem(ii, doArrowHead - && currentDirection == descDir); - button.setActionCommand(String.valueOf(descDir)); - group.add(button); - button.addActionListener(listener); - arrowheadMenu.add(button); - } - } - return arrowheadMenu; - } - - /** - * Given some arrowhead parameters, create an ImageIcon that shows - * it. - * - * @param stroke the BasicStroke to draw on the Icon. - * @param width the width of the icon. - * @param height the height of the icon. - * @param arrowHeadType -1 for no arrowhead, use the OMArrowHead - * directions for other versions. - */ - public ImageIcon createArrowIcon(BasicStroke stroke, int width, int height, - int arrowHeadType) { - - BufferedImage bigImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) bigImage.getGraphics(); - - int middleY = height / 2; - - g.setBackground(OMColor.clear); - g.setPaint(OMColor.clear); - g.fillRect(0, 0, width, height); - g.setPaint(Color.black); - g.setStroke(stroke); - g.drawLine(0, middleY, width, middleY); - - int upTip = (int) ((float) height * .25); - int downTip = (int) ((float) height * .75); - Polygon poly = null; - if (arrowHeadType == OMArrowHead.ARROWHEAD_DIRECTION_FORWARD - || arrowHeadType == OMArrowHead.ARROWHEAD_DIRECTION_BOTH) { - int rightWingX = (int) ((float) width * .75); - poly = new Polygon(new int[] { width, rightWingX, rightWingX }, new int[] { - middleY, upTip, downTip }, 3); - g.fill(poly); - g.draw(poly); // Seems to help with rendering problem. - } - - if (arrowHeadType == OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD - || arrowHeadType == OMArrowHead.ARROWHEAD_DIRECTION_BOTH) { - int leftWingX = (int) ((float) width * .25); - poly = new Polygon(new int[] { 0, leftWingX, leftWingX }, new int[] { - middleY, upTip, downTip }, 3); - g.fill(poly); - g.draw(poly); // Seems to help with rendering problem. - } - - return new ImageIcon(bigImage); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMCircle.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMCircle.java deleted file mode 100755 index 53451fd7a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMCircle.java +++ /dev/null @@ -1,712 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMCircle.java,v $ -// $RCSfile: EditableOMCircle.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.editable.CircleStateMachine; -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.GraphicSetOffsetState; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The EditableOMCircle encompasses an OMCircle, providing methods for modifying - * or creating it. This class only modifies circles in lat/lon space - * (RENDERTYPE_LATLON) - and ellipses in screen space (RENDERTYPE_XY or - * RENDERTYPE_OFFSET). When you grab at the circle, you change the radius of the - * entire circle. Grabbing the center point moves the circle. If there is an - * offset point, moving the center point changes the circle's position in - * relation to the offset point. Moving the offset point moves the circle, - * keeping the distance to the center point constant. - */ -public class EditableOMCircle extends EditableOMGraphic { - - protected VerticalGrabPoint gpn; - protected HorizontalGrabPoint gpw; - protected VerticalGrabPoint gps; - protected HorizontalGrabPoint gpe; - protected GrabPoint gpnw; - protected GrabPoint gpne; - protected GrabPoint gpsw; - protected GrabPoint gpse; - protected OffsetGrabPoint gpc; - protected GrabPoint gpr; - protected OffsetGrabPoint gpo; // offset - protected OffsetGrabPoint gpm; // for grabbing the circle and - // changing the radius during creation. - - protected OMCircle circle; - - public final static int CENTER_POINT_INDEX = 0; - public final static int NW_POINT_INDEX = 1; - public final static int N_POINT_INDEX = 2; - public final static int NE_POINT_INDEX = 3; - public final static int W_POINT_INDEX = 4; - public final static int E_POINT_INDEX = 5; - public final static int SW_POINT_INDEX = 6; - public final static int S_POINT_INDEX = 7; - public final static int SE_POINT_INDEX = 8; - public final static int RADIUS_POINT_INDEX = 9; - public final static int OFFSET_POINT_INDEX = 10; - - /** - * Create the EditableOMCircle, setting the state machine to create the - * circle off of the gestures. - */ - public EditableOMCircle() { - createGraphic(null); - } - - /** - * Create an EditableOMCircle with the circleType and renderType parameters - * in the GraphicAttributes object. - */ - public EditableOMCircle(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMCircle with an OMCircle already defined, ready for - * editing. - * - * @param omc OMCircle that should be edited. - */ - public EditableOMCircle(OMCircle omc) { - setGraphic(omc); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMCircle. - */ - public void init() { - setCanGrabGraphic(false); - Debug.message("eomg", "EditableOMCircle.init()"); - setStateMachine(new CircleStateMachine(this)); - gPoints = new GrabPoint[11]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMCircle) { - circle = (OMCircle) graphic; - stateMachine.setSelected(); - setGrabPoints(circle); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of circle to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - - if (ga != null) { - renderType = ga.getRenderType(); - } - - if (Debug.debugging("eomc")) { - Debug.output("EditableOMCircle.createGraphic(): rendertype = " + renderType); - } - - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - circle = new OMCircle(90f, -180f, 0f); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - circle = new OMCircle(90f, -180f, 0, 0, 1, 1); - break; - default: - circle = new OMCircle(-1, -1, 1, 1); - } - - if (ga != null) { - ga.setTo(circle, true); - } - } - - /** - * Get whether a graphic can be manipulated by its edges, rather than just - * by its grab points. - */ - public boolean getCanGrabGraphic() { - return canGrabGraphic || circle.renderType == OMGraphic.RENDERTYPE_LATLON; - } - - /** - * Get the OMGraphic being created/modified by the EditableOMCircle. - */ - public OMGraphic getGraphic() { - return circle; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - public void setMovingPoint(GrabPoint gp) { - super.setMovingPoint(gp); - // set as a flag that the graphic is being moved, and it's - // parameters should not be adjusted. - gpm = null; - } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the - * moving point to that GrabPoint. - * - * @param e MouseEvent - * @return GrabPoint that is touched by the MouseEvent, null if none are. - */ - public GrabPoint getMovingPoint(MouseEvent e) { - - movingPoint = null; - - GrabPoint[] gb = getGrabPoints(); - - Point2D pnt = getProjectionPoint(e); - int x = (int) pnt.getX(); - int y = (int) pnt.getY(); - - for (int i = gb.length - 1; i >= 0; i--) { - - if (i != RADIUS_POINT_INDEX && gb[i] != null && gb[i].distance(x, y) == 0) { - - setMovingPoint(gb[i]); - // in case the points are on top of each other, the - // last point in the array will take precedence. - break; - } - } - return movingPoint; - } - - protected int lastRenderType = -1; - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - int rt = getGraphic().getRenderType(); - if (rt != lastRenderType) { - clearGrabPoints(); - lastRenderType = rt; - } - - if (gpr == null) { - gpr = new GrabPoint(-1, -1); - gPoints[RADIUS_POINT_INDEX] = gpr; - } - if (gpnw == null) { - gpnw = new GrabPoint(-1, -1); - gPoints[NW_POINT_INDEX] = gpnw; - } - if (gpn == null) { - gpn = new VerticalGrabPoint(-1, -1); - gPoints[N_POINT_INDEX] = gpn; - } - if (gpne == null) { - gpne = new GrabPoint(-1, -1); - gPoints[NE_POINT_INDEX] = gpne; - } - if (gpw == null) { - gpw = new HorizontalGrabPoint(-1, -1); - gPoints[W_POINT_INDEX] = gpw; - } - if (gpe == null) { - gpe = new HorizontalGrabPoint(-1, -1); - gPoints[E_POINT_INDEX] = gpe; - } - if (gpsw == null) { - gpsw = new GrabPoint(-1, -1); - gPoints[SW_POINT_INDEX] = gpsw; - } - if (gps == null) { - gps = new VerticalGrabPoint(-1, -1); - gPoints[S_POINT_INDEX] = gps; - } - if (gpse == null) { - gpse = new GrabPoint(-1, -1); - gPoints[SE_POINT_INDEX] = gpse; - } - - if (gpc == null) { - gpc = new OffsetGrabPoint(-1, -1); - gPoints[CENTER_POINT_INDEX] = gpc; - if (getGraphic().getRenderType() != OMGraphic.RENDERTYPE_LATLON) { - gpc.addGrabPoint(gpnw); - gpc.addGrabPoint(gpn); - gpc.addGrabPoint(gpne); - gpc.addGrabPoint(gpw); - gpc.addGrabPoint(gpe); - gpc.addGrabPoint(gpsw); - gpc.addGrabPoint(gps); - gpc.addGrabPoint(gpse); - } - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gpc); - } - } - - protected void clearGrabPoints() { - - gpc = null; - gpr = null; - gpnw = null; - gpn = null; - gpne = null; - gpw = null; - gpe = null; - gpsw = null; - gps = null; - gpse = null; - gpo = null; - - gPoints[CENTER_POINT_INDEX] = gpc; - gPoints[RADIUS_POINT_INDEX] = gpr; - gPoints[NW_POINT_INDEX] = gpnw; - gPoints[N_POINT_INDEX] = gpn; - gPoints[NE_POINT_INDEX] = gpne; - gPoints[W_POINT_INDEX] = gpw; - gPoints[E_POINT_INDEX] = gpe; - gPoints[SW_POINT_INDEX] = gpsw; - gPoints[S_POINT_INDEX] = gps; - gPoints[SE_POINT_INDEX] = gpse; - gPoints[OFFSET_POINT_INDEX] = gpo; - - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - if (!(graphic instanceof OMCircle)) { - return; - } - - assertGrabPoints(); - - OMCircle circle = (OMCircle) graphic; - boolean ntr = circle.getNeedToRegenerate(); - int renderType = circle.getRenderType(); - - int centerx = 0; - int centery = 0; - - if (ntr == false) { - - if (renderType == OMGraphic.RENDERTYPE_LATLON - || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - if (projection != null) { - LatLonPoint center = circle.getLatLon(); - Point2D p = projection.forward(center); - centerx = (int) p.getX(); - centery = (int) p.getY(); - } - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - gpo.setX(centerx); - gpo.setY(centery); - - centerx += circle.getOffX(); - centery += circle.getOffY(); - } - - } else if (renderType == OMGraphic.RENDERTYPE_XY) { - centerx = circle.getX(); - centery = circle.getY(); - } - - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - Debug.message("eomg", "EditableOMCircle: modifying lat/lon circle"); - if (projection != null) { - gpc.set(centerx, centery); - } - - // Note that we really don't handle this situation - // well, if there isn't a projection. We kind of - // assume later that there is one, and although there - // shouldn't be massive meltdowns, data could look - // funky on the screen if the projection is - // unavailable. - - } else { - // Grab the projected endpoints - Debug.message("eomg", "EditableOMCircle: modifying x/y or offset standard circle"); - int height = circle.getHeight() / 2; - int width = circle.getWidth() / 2; - gpc.set(centerx, centery); - - gpe.set(centerx + width, centery, true); - gps.set(centerx, centery + height, true); - gpw.set(centerx - width, centery, true); - gpn.set(centerx, centery - height, true); - - gpne.set(gpe.getX(), gpn.getY()); - gpnw.set(gpw.getX(), gpn.getY()); - gpse.set(gpe.getX(), gps.getY()); - gpsw.set(gpw.getX(), gps.getY()); - gpc.updateOffsets(); - - // Debug.output("***\nheight:" + height + ", width:" + - // width + - // "\n EditableOMCircle: east at x: " + gpe.getX() + - // ", y:" + gpe.getY()); - // Debug.output(" EditableOMCircle: north at x: " + - // gpn.getX() + - // ", y:" + gpn.getY()); - // Debug.output(" EditableOMCircle: northeast at x: " - // + gpne.getX() + - // ", y:" + gpne.getY()); - // Debug.output(" EditableOMCircle: center at x: " + - // centerx + - // ", y:" + centery); - } - - // Check to see if the circle is a offset circle, and set - // the - // offset grab point offsets accordingly. - if (circle.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - gpo.updateOffsets(); - } - - } else { - Debug.message("eomg", "EditableOMCircle.setGrabPoints: graphic needs to be regenerated"); - } - - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMCircle with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = circle.getRenderType(); - - // If the gpm is a movement GP or the gpc, then we need to - // update all the grab points relative location to the gpm, - // and then use the code below. - - // If the gpm is the gpo, then the circle moves, too. That's - // OK, because if the gpo is moving, then the other points - // have been moved already. - - // If the gpm is one of the other GPs, then we need to update - // the radius or height and width based on that point, as well - // as the other GP locations. - - Debug.message("eomg", "EditableOMCircle.setGrabPoints()"); - - // Do center point for lat/lon or offset circles - if (renderType == OMGraphic.RENDERTYPE_LATLON || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - GrabPoint llgp; - // OK, to set the center, if the rendertype is offset, - // then the center lat/lon has to be set to the offset - // point. When the circle is initially defined, this is - // OK because the offset x and y are 0, and the render - // method knows not to render the point yet. - if (// movingPoint == gpo || - renderType == OMGraphic.RENDERTYPE_OFFSET) { - llgp = gpo; - } else { - // If the moving point is the radius, the the center - // grab point is the lat/lon point. - llgp = gpc; - } - - if (projection != null) { - - LatLonPoint llp = (LatLonPoint) projection.inverse(llgp.getX(), llgp.getY(), new LatLonPoint.Double()); - - circle.setCenter(llp); - - // Do the radius for LATLON circles. - if (renderType == OMGraphic.RENDERTYPE_LATLON && movingPoint == gpr) { - - LatLonPoint llpm = (LatLonPoint) projection.inverse(gpr.getX(), gpr.getY(), new LatLonPoint.Double()); - - double radius; - - if (projection instanceof GeoProj) { - radius = Length.DECIMAL_DEGREE.fromRadians(llpm.distance(llp)); - } else { - radius = DrawUtil.distance(llpm.getX(), llpm.getY(), llp.getX(), llp.getY()); - } - - setRadius(radius); - - } - - } else { - Debug.message("eomg", "EditableOMCircle.setGrabPoints: projection is null, can't figure out LATLON points for circle."); - } - } - - boolean settingOffset = getStateMachine().getState() instanceof GraphicSetOffsetState - && movingPoint == gpo; - - // If the center point is moving, the offset distance changes - if (renderType == OMGraphic.RENDERTYPE_OFFSET && (settingOffset || movingPoint == gpc)) { - // Do the offset point. - circle.setOffX(gpc.getX() - gpo.getX()); - circle.setOffY(gpc.getY() - gpo.getY()); - Debug.message("eomg", "EditableOMCircle: updating offset distance, ox:" - + circle.getOffX() + ", oy:" + circle.getOffY()); - } - - // Do the circle height and width for XY and OFFSET render - // types. - if (renderType == OMGraphic.RENDERTYPE_XY - || (renderType == OMGraphic.RENDERTYPE_OFFSET && !settingOffset)) { - - if (renderType == OMGraphic.RENDERTYPE_XY) { - circle.setX(gpc.getX()); - circle.setY(gpc.getY()); - } - - if (movingPoint instanceof HorizontalGrabPoint) { - // Must be the left or right... - circle.setWidth(Math.abs(movingPoint.getX() - gpc.getX()) * 2); - - } else if (movingPoint instanceof VerticalGrabPoint) { - // Must be the top or bottom... - circle.setHeight(Math.abs(movingPoint.getY() - gpc.getY()) * 2); - - } else if (movingPoint != gpo && movingPoint != gpc) { - // Must be one of the corners... - circle.setWidth(Math.abs(movingPoint.getX() - gpc.getX()) * 2); - circle.setHeight(Math.abs(movingPoint.getY() - gpc.getY()) * 2); - } - - // Debug.output("EditableOMCircle.setGrabPoints(): - // movingPoint x:" + - // movingPoint.getX() + ", y:" + movingPoint.getY() + - // ", gpc.x:" + gpc.getX() + ", gpc.y:" + gpc.getY()); - } - - if (projection != null) { - regenerate(projection); - } - } - - /** - * To be overloaded if needed when setting circle's radius. - * - * @param radius in DECIMAL_DEGREES - */ - protected void setRadius(double radius) { - if (circle != null) { - circle.setRadius(radius); - } - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(MouseEvent e) { - if (getGraphic().getRenderType() == OMGraphic.RENDERTYPE_LATLON - && isMouseEventTouchingTheEdge(e)) { - if (gpr == null) { - gpr = new GrabPoint(-1, -1); - } - gpr.set(e.getX(), e.getY()); - movingPoint = gpr; - } - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomg", "EditableOMCircle.generate()"); - if (circle != null) - circle.generate(proj); - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - gp.generate(proj); - - // Why is this here??? - // if (gp instanceof OffsetGrabPoint) { - // ((OffsetGrabPoint)gpo).updateOffsets(); - // } - } - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMCircle.regenerate()"); - if (circle != null) - circle.regenerate(proj); - - setGrabPoints(circle); - generate(proj); - } - - /** - * Draw the EditableOMCircle parts into the java.awt.Graphics object. The - * grab points are only rendered if the circle machine state is - * CircleSelectedState.CIRCLE_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomg", "EditableOMCircle.render()"); - - State state = getStateMachine().getState(); - - // All the rotation stuff isn't ready for primetime, yet. - // Need to translate the mouse events, too. - - // graphics = graphics.create(); - // double rotationAngle = OMGraphic.DEFAULT_ROTATIONANGLE; - - if (circle == null) { - Debug.message("eomg", "EditableOMCircle.render: null circle."); - return; - } - - circle.setVisible(true); - circle.render(graphics); - circle.setVisible(false); - - // rotationAngle = circle.getRotationAngle(); - - int renderType = circle.getRenderType(); - - // if (rotationAngle != OMGraphic.DEFAULT_ROTATIONANGLE) { - // ((java.awt.Graphics2D)graphics).rotate(rotationAngle, - // circle.getX(), circle.getY()); - // } - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState) { - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - if (i == RADIUS_POINT_INDEX) - continue; - - if (renderType == OMGraphic.RENDERTYPE_LATLON && i != CENTER_POINT_INDEX) - continue; - - if ((i == OFFSET_POINT_INDEX && renderType == OMGraphic.RENDERTYPE_OFFSET && movingPoint == gpo) - || (state instanceof GraphicSelectedState && ((i != OFFSET_POINT_INDEX && renderType != OMGraphic.RENDERTYPE_OFFSET) || (renderType == OMGraphic.RENDERTYPE_OFFSET)))) { - - gp.setVisible(true); - gp.render(graphics); - gp.setVisible(false); - } - } - } - } - } - - /** - * If this EditableOMGraphic has parameters that can be manipulated that are - * independent of other EditableOMGraphic types, then you can provide the - * widgets to control those parameters here. By default, returns the - * GraphicAttributes GUI widgets. If you don't want a GUI to appear when a - * widget is being created/edited, then don't call this method from the - * EditableOMGraphic implementation, and return a null Component from - * getGUI. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return java.awt.Component to use to control parameters for this EOMG. - */ - public java.awt.Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMCircle.getGUI"); - // if (graphicAttributes != null) { - // return graphicAttributes.getColorAndLineGUI(); - // } else { - return null; - // } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDecoratedSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDecoratedSpline.java deleted file mode 100644 index 9e945beb9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDecoratedSpline.java +++ /dev/null @@ -1,88 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMDecoratedSpline.java,v $ -//$RCSfile: EditableOMDecoratedSpline.java,v $ -//$Revision: 1.5 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -/** - * EditableOMDecoratedSpline. Nothing created, code adapted from - * EditableOMPoly We just need to edit the generating points as an - * OMPoly - * - * @author Eric LEPICIER - * @version 29 juil. 2002 - */ -public class EditableOMDecoratedSpline extends EditableOMSpline { - - /** - * Constructor. - */ - public EditableOMDecoratedSpline() { - super(); - } - - /** - * Constructor. - * - * @param ga - */ - public EditableOMDecoratedSpline(GraphicAttributes ga) { - super(ga); - } - - /** - * Constructor. - * - * @param omp - */ - public EditableOMDecoratedSpline(OMSpline omp) { - super(omp); - } - - /** - * Extendable method to create specific subclasses of OMPolys. - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - g = new OMDecoratedSpline(new double[0], OMGraphic.RADIANS, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - g = new OMSpline(90f, -180f, new int[0], OMDecoratedSpline.COORDMODE_ORIGIN); - break; - default: - g = new OMDecoratedSpline(new int[0]); - } - ((OMSpline) g).setDoShapes(true); - return g; - } - - public java.net.URL getImageURL(String imageName) { - try { - return Class.forName("com.bbn.openmap.omGraphics.EditableOMPoly") - .getResource(imageName); - } catch (ClassNotFoundException cnfe) { - } - return null; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDistance.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDistance.java deleted file mode 100644 index 64b443a98..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMDistance.java +++ /dev/null @@ -1,133 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMDistance.java,v $ -// $RCSfile: EditableOMDistance.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.Debug; - -/** - * The EditableOMDistance encompasses an OMDistance, providing methods for - * modifying or creating it. - */ -public class EditableOMDistance extends EditableOMPoly { - - /** - * Create the EditableOMDistance, setting the state machine to create the - * poly off of the gestures. - */ - public EditableOMDistance() { - super(); - } - - /** - * Create an EditableOMDistance with the polyType and renderType parameters - * in the GraphicAttributes object. - */ - public EditableOMDistance(GraphicAttributes ga) { - super(ga); - } - - /** - * Create the EditableOMDistance with an OMDistance already defined, ready - * for editing. - * - * @param omp - * OMDistance that should be edited. - */ - public EditableOMDistance(OMDistance omp) { - super(omp); - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of poly to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_LATLON; - int lineType = OMGraphic.LINETYPE_GREATCIRCLE; - - if (ga != null) { - renderType = ga.getRenderType(); - lineType = ga.getLineType(); - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMDistance.createGraphic(): rendertype = " - + renderType); - } - - if (lineType == OMGraphic.LINETYPE_UNKNOWN) { - lineType = OMGraphic.LINETYPE_GREATCIRCLE; - if (ga != null) { - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - } - - this.poly = (OMDistance) createGraphic(renderType, lineType); - - if (ga != null) { - ga.setRenderType(poly.getRenderType()); - ga.setTo(poly, true); - } - } - - /** - * Extendable method to create specific subclasses of OMDistances. - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_OFFSET): - System.err.println("Offset type not supported for OMDistance"); - } - g = new OMDistance(new double[0], OMGraphic.RADIANS, lineType, - Length.NM); - ((OMDistance) g).setDoShapes(true); - return g; - } - - /** - * A convenience method that gives an EditableOMGraphic a chance to modify - * the OMGraphic so it can be drawn quickly, by turning off labels, etc, - * right before the XORpainting happens. The OMGraphic should be configured - * so that the render method does the least amount of painting possible. - * Note that the DrawingAttributes for the OMGraphic have already been set - * to DrawingAttributes.DEFAULT (black line, clear fill). - */ - protected void modifyOMGraphicForEditRender() { - ((OMDistance) getGraphic()).paintOnlyPoly = true; - } - - /** - * A convenience method that gives an EditableOMGraphic a chance to reset - * the OMGraphic so it can be rendered normally, after it has been modified - * for quick paints. The DrawingAttributes for the OMGraphic have already - * been reset to their normal settings, from the DrawingAttributes.DEFAULT - * settings that were used for the quick paint. - */ - protected void resetOMGraphicAfterEditRender() { - ((OMDistance) getGraphic()).paintOnlyPoly = false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphic.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphic.java deleted file mode 100644 index 1a98d745f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphic.java +++ /dev/null @@ -1,1017 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMGraphic.java,v $ -// $RCSfile: EditableOMGraphic.java,v $ -// $Revision: 1.11 $ -// $Date: 2005/12/09 21:09:04 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Graphics; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.util.MissingResourceException; - -import javax.swing.JComponent; -import javax.swing.JToolBar; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.event.MapMouseAdapter; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.UndoEvent; -import com.bbn.openmap.event.UndoStack; -import com.bbn.openmap.gui.GridBagToolBar; -import com.bbn.openmap.omGraphics.editable.EOMGStateMachine; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.omGraphics.event.EOMGListener; -import com.bbn.openmap.omGraphics.event.EOMGListenerSupport; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * The EditableOMGraphic is a shell that controls actions to edit or create a graphic. This class contains a state - * machine that defines how mouse events will be interpreted to modify the OMGraphic contained within. Any class that - * extends this one is responsible for assigning the appropriate state machine and OMGraphic to itself. Also, an - * EditableOMGraphic has a notion of a list of GrabPoints, which can be used as handles to the OMGraphic to provide - * controlled modifications. - */ -public abstract class EditableOMGraphic - extends MapMouseAdapter { - - /** - * If the grab points should be rendered differently than the default, the DrawingAttributes should be stored in the - * edited OMGraphic under this attribute key. - */ - public final static String GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE = "gpdaa"; - /** - * If the EditableOMGraphic supports the notion of a selected GrabPoint (to highlight a node), and that selection - * should change the appearance of a GrabPoint, the DrawingAttributes for that selection appearance should be stored - * in the edited OMGraphic attributes under this attribute key. - */ - public final static String SELECTED_GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE = "sgpdaa"; - /** - * The state machine that interprets the mouse events (and other events) and modifies the OMGraphics accordingly. - * - * @see com.bbn.openmap.util.stateMachine.StateMachine - */ - protected EOMGStateMachine stateMachine; - /** - * This is here for the MapMouseListener interface. This may not be important, depending on what is funneling mouse - * events to the graphic. - */ - protected String[] mouseModeServiceList; - /** - * The array of GrabPoints. - */ - protected GrabPoint[] gPoints; - /** - * The projection of the map. This can be retrieved from the mouse events, provided that the mouse events source is - * the MapBean. - */ - protected Projection projection; - /** - * This GrabPoint is one that has been grabbed by the mouse, and is being moved. - */ - protected GrabPoint movingPoint = null; - protected EOMGListenerSupport listeners = null; - /** - * Flag to indicate whether a GUI for this EOMG should be presented to allow edits to it's attributes. - */ - protected boolean showGUI = true; - /** - * Flag to let states know if the edges of the graphic can be grabbed directly, for movement or manipulation, as - * opposed to just allowing those actions through the grab points. - */ - protected boolean canGrabGraphic = true; - /** - * The component to notify for changes made to the OMGraphic, so they can be undone if desired. - */ - protected UndoStack undoStack; - protected I18n i18n = Environment.getI18n(); - /** - * A little flag to let the EOMG that a popup menu is up on the map. If the menu is up, and the menu is not clicked - * on, we don't really want to deactivate the drawing tool right then - let a free click go by first, which will - * dismiss the menu. - */ - protected boolean popupIsUp = false; - /** - * Action mask for this graphic. Used as a holder for modifying objects to let this EditableOMGraphic know what is - * being done to it. - */ - protected int actionMask = 0; - protected boolean DEBUG = false; - protected boolean DEBUG_DETAIL = false; - protected boolean xorRendering = true; - - protected EditableOMGraphic() { - DEBUG = Debug.debugging("eomg"); - DEBUG_DETAIL = Debug.debugging("eomgdetail"); - } - - /** - * Set the StateMachine for this EditableOMGraphic. - * - * @param sm StateMachine. - * @see com.bbn.openmap.util.stateMachine.StateMachine - */ - public void setStateMachine(EOMGStateMachine sm) { - stateMachine = sm; - } - - /** - * Get the state machine for this EditableOMGraphic. - */ - public EOMGStateMachine getStateMachine() { - return stateMachine; - } - - /** - * Set the list of MouseMode names that this EditableOMGraphic will respond to, if it is dealing directly with a - * MouseDelegator. - */ - public void setMouseModeServiceList(String[] list) { - mouseModeServiceList = list; - } - - /** - * Get the list of MouseMode names that this EditableOMGraphic will respond to, if it is dealing directly with a - * MouseDelegator. - */ - public String[] getMouseModeServiceList() { - return mouseModeServiceList; - } - - /** - * Set whether this EOMG should provide a user interface to have the attributes modified. - * - * @param set true if the GUI should be shown. - */ - public void setShowGUI(boolean set) { - showGUI = set; - OMGraphic graphic = getGraphic(); - if (graphic != null) { - graphic.setShowEditablePalette(set); - } - } - - public boolean getShowGUI() { - if (getGraphic() != null) { - return getGraphic().getShowEditablePalette(); - } else { - return showGUI; - } - } - - /** - * Set whether a graphic can be manipulated by its edges, rather than just by its grab points. Used internally. - */ - public void setCanGrabGraphic(boolean set) { - canGrabGraphic = set; - } - - /** - * Get whether a graphic can be manipulated by its edges, rather than just by its grab points. - */ - public boolean getCanGrabGraphic() { - return canGrabGraphic; - } - - /** - * Set the OMGraphic that is being modified by the EditableOMGraphic. The type of OMGraphic needs to match what the - * EditableOMGraphic is expecting. Assume that if the graphic passed in is null, that a proper graphic will be - * created. - * - * @param graphic OMGraphic. - */ - public abstract void setGraphic(OMGraphic graphic); - - /** - * Create the OMGraphic that is to be modified by the EditableOMGraphic. - * - * @param ga GraphicAttributes, describing the graphic to be created. - */ - public abstract void createGraphic(GraphicAttributes ga); - - /** - * Get the OMGraphic that is being created/modified by the EditableOMGraphic. - */ - public abstract OMGraphic getGraphic(); - - /** - * Remove all changes and put graphic as it was before modifications. If the graphic is being created, start over. - */ - public void reset() { - Debug.output("EditableOMGraphic.reset(): not yet supported"); - } - - /** - * Set the grab point objects within the EditableOMGraphic array. The size and layout of the points in the array are - * carefully determined by the EditableOMGraphic, so this method merely replaces objects within the array, not - * replacing the array itself, so that you cannot reset the number of grab points an EditableOMGraphic uses for a - * particular OMGraphic. - * - * @param points a GrabPoint[] - * @return true if the grab point array was exactly what the EditableOMGraphic was expecting, in terms of length of - * the GrabPoint array length. The method copies the array values that fit into the resident array. - */ - public boolean setGrabPoints(GrabPoint[] points) { - if (points == null || gPoints == null) { - return false; - } - - System.arraycopy(points, 0, gPoints, 0, Math.min(points.length, gPoints.length)); - - return (points.length == gPoints.length); - } - - /** - * Method to allow objects to set OMAction masks on this editable graphic. - */ - public void setActionMask(int mask) { - actionMask = mask; - } - - /** - * Get the OMAction mask for this graphic. - */ - public int getActionMask() { - return actionMask; - } - - /** - * Tells the EditableOMGraphic that the locations of the grab points have been modified, and that the parameters of - * the OMGraphic need to be modified accordingly. - */ - public abstract void setGrabPoints(); - - /** - * Get the array of grab points used for the EditableOMGraphic. Given a mouse event, you can see if one of these is - * affected, and move it accordingly. Call setGrabPoints() when modifications are done, so that the OMGraphic is - * modified. - */ - public GrabPoint[] getGrabPoints() { - return gPoints; - } - - /** - * Set the GrabPoint at a particule index of the array. This can be used to tie two different grab points together. - * - * @param gb GrabPoint to assign within array. - * @param index the index of the array to put the GrabPoint. The EditableOMGraphic should be able to provide the - * description of the proper placement indexes. - * @return If the grab point or array is null, or if the index is outside the range of the array, false is returned. - * If everything goes OK, then true is returned. - */ - public boolean setGrabPoint(GrabPoint gb, int index) { - if (gPoints != null && gb != null && index >= 0 && index < gPoints.length) { - - gPoints[index] = gb; - return true; - } else { - return false; - } - } - - /** - * Return a particular GrabPoint at a particular point in the array. The EditableOMGraphic should describe which - * indexes refer to which grab points in the EOMG GrabPoint array. If the index is outside the range of the array, - * null is returned. - */ - public GrabPoint getGrabPoint(int index) { - if (gPoints != null && index >= 0 && index < gPoints.length) { - return gPoints[index]; - } else { - return null; - } - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this EditableOMGraphic with it. - * EditableOMGraphic version doesn't do anything, each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version doesn't do anything, each subclass should - * remove whatever GrabPoint it would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of a mouseDragged event, or other - * selection. - */ - public void setMovingPoint(GrabPoint gp) { - movingPoint = gp; - } - - /** - * Get the GrabPoint that is being moved. If it's null, then there isn't one. - */ - public GrabPoint getMovingPoint() { - return movingPoint; - } - - /** - * Notification that a MouseEvent was used to trigger creation or edit of this EditableOMGraphic, and this is the - * first MouseEvent received. If the EditableOMGraphic can handle it, it should. Otherwise, it should put itself in - * the right state to let the user know it's active. - */ - public void handleInitialMouseEvent(MouseEvent e) { - getStateMachine().setEdit(); - if (e != null) { - GrabPoint gp = getMovingPoint(e); - if (gp == null) { - move(e); - } else { - getStateMachine().setSelected(); - } - } else { - getStateMachine().setSelected(); - } - } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the moving point to that GrabPoint. Called when - * a MouseEvent happens like a mousePressed or mouseReleased, and you want to find out if a GrabPoint should be used - * to make modifications to the graphic or its position. This method should only be called to establish a moving - * point. getMovingPoint() should be called to check to see if one has been established, and then redraw(MouseEvent) - * would be called to move that moving point. - * - * @param e MouseEvent - * @return GrabPoint that is touched by the MouseEvent, null if none are. - */ - public GrabPoint getMovingPoint(MouseEvent e) { - return _getMovingPoint(e); - } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the moving point to that GrabPoint. A version - * for grandchild classes. - * - * @param e MouseEvent that the GrabPoint should attach to. - * @see #getMovingPoint(MouseEvent) - */ - public GrabPoint _getMovingPoint(MouseEvent e) { - movingPoint = null; - - GrabPoint[] gb = getGrabPoints(); - Point2D pnt = getProjectionPoint(e); - - double x = pnt.getX(); - double y = pnt.getY(); - - for (int i = gb.length - 1; i >= 0; i--) { - if (gb[i] != null && gb[i].distance(x, y) == 0) { - setMovingPoint(gb[i]); - // in case the points are on top of each other, the - // last point in the array will take precedence. - return gb[i]; - } - } - - setMovingPoint(null); - return null; - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and update the OffsetGrabPoint with all the other - * GrabPoint locations, so everything can shift smoothly. Should also set the OffsetGrabPoint to the movingPoint. - */ - public abstract void move(MouseEvent e); - - /** - * Clean the surface all the painting is taking place over. - */ - public void cleanMap(MouseEvent e) { - Object obj = e.getSource(); - if (!(obj instanceof MapBean)) { - return; - } - - // Could call repaint(), but I think we should paint in this - // thread... - MapBean map = (MapBean) obj; - // Gets the buffer cleaned out. - map.setBufferDirty(true); - map.paintChildren(map.getGraphics(true)); - } - - /** - * Same as redraw(e, false) - */ - public void redraw(MouseEvent e) { - redraw(e, false); - } - - public void redraw(MouseEvent e, boolean firmPaint) { - redraw(e, firmPaint, true); - } - /** - * A DrawingAttributes object used to hold OMGraphic settings while it is being moved. When an OMGraphic is being - * moved, basic (DEFAULT) settings are put on the OMGraphic to make it as light and uncomplicated as possible. - */ - protected DrawingAttributes holder = new DrawingAttributes(); - - /** - * Given a MouseEvent, check the source, and if it's a MapBean, then grab the projection and java.awt.Graphics from - * it to use for generation and rendering of the EditableOMGraphic objects. - * - * @param e MouseEvent - * @param firmPaint true if the graphic is being rendered at rest, with fill colors and true colors, with the grab - * point if the state allows it. If false, then the fill color will not be used, and just the graphic will be drawn. - * Use false for graphics that are moving. - */ - public void redraw(MouseEvent e, boolean firmPaint, boolean drawXOR) { - if (DEBUG) { - Debug.output("EditableOMGraphic.redraw(" + (firmPaint ? "firmPaint)" : ")")); - } - - drawXOR = drawXOR && isXorRendering(); - - if (e == null) { - if (lastMouseEvent == null) { - return; - } - e = lastMouseEvent; - } - - Object obj = e.getSource(); - if (!(obj instanceof MapBean)) { - return; - } - - MapBean map = (MapBean) obj; - Graphics g = map.getGraphics(true); - - OMGraphic graphic = getGraphic(); - - // Seeing if we can make for a better rendering look by repainting the - // mapBean all the time. With tiling, it works. - if (!isXorRendering()) { - map.repaint(); - } - - if (firmPaint) { - // So, with a firm paint, we want to clean the screen. If - // the map is being buffered, we need to clean out the - // buffer, which is why we set the Request paint to true, - // to get the image rebuilt. Otherwise, a copy of the - // graphic remains. - map.setBufferDirty(true); - graphic.generate(getProjection()); - map.repaint(); - } else { - // If we get here, we are painting a moving object, so we - // only want to do the outline to make it as fast as - // possible. - holder.setFrom(graphic); - DrawingAttributes.DEFAULT.setTo(graphic); - - modifyOMGraphicForEditRender(); - graphic.regenerate(getProjection()); - - if (drawXOR) { - g.setXORMode(Color.lightGray); - g.setColor((Color) graphic.getDisplayPaint()); - - render(g); - } - - GrabPoint gp = getMovingPoint(); - if (gp != null) { - Point2D pnt = getProjectionPoint(e); - double x = pnt.getX(); - double y = pnt.getY(); - - gp.set((int) x, (int) y); - - if (gp instanceof OffsetGrabPoint) { - ((OffsetGrabPoint) gp).moveOffsets(); - } - setGrabPoints(); - } - } - - if (!firmPaint) { - generate(getProjection()); - render(g); - holder.setTo(graphic); - } - - resetOMGraphicAfterEditRender(); - g.dispose(); - - lastMouseEvent = e; - } - protected MouseEvent lastMouseEvent; - - /** - * A convenience method that gives an EditableOMGraphic a chance to modify the OMGraphic so it can be drawn quickly, - * by turning off labels, etc, right before the XORpainting happens. The OMGraphic should be configured so that the - * render method does the least amount of painting possible. Note that the DrawingAttributes for the OMGraphic have - * already been set to DrawingAttributes.DEFAULT (black line, clear fill). - */ - protected void modifyOMGraphicForEditRender() { - } - - /** - * A convenience method that gives an EditableOMGraphic a chance to reset the OMGraphic so it can be rendered - * normally, after it has been modified for quick paints. The DrawingAttributes for the OMGraphic have already been - * reset to their normal settings, from the DrawingAttributes.DEFAULT settings that were used for the quick paint. - */ - protected void resetOMGraphicAfterEditRender() { - } - - public void repaint() { - if (lastMouseEvent != null) { - redraw(lastMouseEvent, true); - } - } - - protected void finalize() { - if (getGraphic() != null) { - getGraphic().setVisible(true); - } - if (Debug.debugging("gc")) { - Debug.output("EditableOMGraphic gone."); - } - } - - /** - * Use the current projection to place the graphics on the screen. Has to be called to at least assure the graphics - * that they are ready for rendering. Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public abstract boolean generate(Projection proj); - - /** - * Given a new projection, the grab points may need to be repositioned off the current position of the graphic. - * Called when the projection changes. IMPORTANT! Set the GrabPoints for the graphic here. - */ - public abstract void regenerate(Projection proj); - - public void repaintRender(Graphics g) { - render(g); - } - - /** - */ - public abstract void render(Graphics g); - - public boolean isXorRendering() { - return xorRendering; - } - - /** - * Set whether the painting will occur using XOR rendering. If false, the mapbean will be repainted on every - * movement. Looks better, but you need to make sure the repaint burden on the mapbean doesn't slow the drawing down - * too much. - * - * @param xorRendering if true, XOR rendering will be used. Otherwise, the old location won't be drawn. - */ - public void setXorRendering(boolean xorRendering) { - this.xorRendering = xorRendering; - } - - /** - * Set the current projection. - */ - public void setProjection(Projection proj) { - projection = proj; - // This is important. In the EditableOMGraphics, the - // GrabPoints are set when regenerate is called. - regenerate(proj); - } - - /** - * Get the current projection. - */ - public Projection getProjection() { - return projection; - } - - // Mouse Listener events - // ////////////////////// - /** - */ - public boolean mousePressed(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mousePressed()"); - } - if (!mouseOnMap) { - return false; - } - return stateMachine.getState().mousePressed(e); - } - - /** - */ - public boolean mouseReleased(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseReleased()"); - } - if (!mouseOnMap) { - return false; - } - return stateMachine.getState().mouseReleased(e); - } - - /** - */ - public boolean mouseClicked(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseClicked()"); - } - if (!mouseOnMap) { - return false; - } - return stateMachine.getState().mouseClicked(e); - } - boolean mouseOnMap = true; - - /** - */ - public void mouseEntered(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseEntered()"); - } - mouseOnMap = true; - stateMachine.getState().mouseEntered(e); - } - - /** - */ - public void mouseExited(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseExited()"); - } - mouseOnMap = false; - stateMachine.getState().mouseExited(e); - } - - // Mouse Motion Listener events - // ///////////////////////////// - /** - */ - public boolean mouseDragged(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseDragged()"); - } - if (!mouseOnMap) { - return false; - } - return stateMachine.getState().mouseDragged(e); - } - - /** - */ - public boolean mouseMoved(MouseEvent e) { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseMoved()"); - } - if (!mouseOnMap) { - return false; - } - return stateMachine.getState().mouseMoved(e); - } - - /** - */ - public void mouseMoved() { - if (DEBUG_DETAIL) { - Debug.output(getClass().getName() + ".mouseMoved()"); - } - if (!mouseOnMap) { - return; - } - stateMachine.getState().mouseMoved(); - } - - /** - * Add a EOMGListener. - * - * @param l EOMGListener - */ - public synchronized void addEOMGListener(EOMGListener l) { - if (listeners == null) { - listeners = new EOMGListenerSupport(this); - } - listeners.add(l); - } - - /** - * Remove a EOMGListener. - * - * @param l EOMGListener - */ - public synchronized void removeEOMGListener(EOMGListener l) { - if (listeners == null) { - return; - } - listeners.remove(l); - } - - /** - * The method to call if you want to let listeners know that the state has changed. Usually called when a graphic is - * selected or not, so that GUIs can be directed. - */ - public void fireEvent(EOMGEvent event) { - if (listeners != null) { - listeners.fireEvent(event); - } - - if (event.getStatus() == EOMGEvent.EOMG_UNDO) { - updateCurrentState(null); - } - } - - /** - * Create the event with a Cursor and/or message, and then fire it. - * - * @param cursor Cursor to be used. - * @param message an instruction/error to be displayed to the user. - * @param status the current status of the EditableOMGraphic. - */ - public void fireEvent(Cursor cursor, String message, int status) { - fireEvent(cursor, message, null, status); - } - - /** - * Create the event with the Cursor, message and/or MouseEvent. - * - * @param cursor Cursor to be used. - * @param message an instruction/error to be displayed to the user. - * @param mouseEvent where that caused the EOMGEvent. May be null. - * @param status the current status of the EditableOMGraphic. - */ - public void fireEvent(Cursor cursor, String message, MouseEvent mouseEvent, int status) { - if (listeners != null) { - EditableOMGraphic theSource = listeners.getEOMG(); - EOMGEvent event = new EOMGEvent(theSource, cursor, message, mouseEvent, status); - fireEvent(event); - } - } - - /** - * Create the event with no cursor change or message to be displayed. - */ - public void fireEvent(int status) { - fireEvent(null, null, null, status); - } - - /** - * If this EditableOMGraphic has parameters that can be manipulated that are independent of other EditableOMGraphic - * types, then you can provide the widgets to control those parameters here. By default, this method returns null, - * which indicates that you can extend this method to return a Component that controls parameters for the - * EditableOMGraphic other than the GraphicAttribute parameters. Should return something like a toolbar, small. - * - * @return Component to control EOMG parameters, without the GraphicAttribute GUI. - */ - public Component getGUI() { - return getGUI(null); - } - - /** - * If this EditableOMGraphic has parameters that can be manipulated that are independent of other EditableOMGraphic - * types, then you can provide the widgets to control those parameters here. By default, returns the - * GraphicAttributes GUI widgets. If you don't want a GUI to appear when a widget is being created/edited, then don't - * call this method from the EditableOMGraphic implementation, and return a null Component from getGUI. - * - * @param graphicAttributes the GraphicAttributes that could be used to get the GUI widget from to control those - * parameters for this EOMG. The GraphicAttributes used to provide the GUI widget, but it doesn't anymore. Subclasses - * can take this opportunity to reset the GraphicAttributes interface for a new OMGraphic. - * - * @return Component to use to control parameters for this EOMG, generally a JPanel with a toolbar. - */ - public Component getGUI(GraphicAttributes graphicAttributes) { - if (graphicAttributes != null) { - graphicAttributes.setLineMenuAdditions(null); - // Used to return the toolbar gui, now the color and line options provided on the right click menu. - // return graphicAttributes.getGUI(); - } - return null; - } - - public Point2D getProjectionPoint(MouseEvent e) { - - Point2D pnt = null; - if (e instanceof MapMouseEvent && ((MapMouseEvent) e).mapIsRotated()) { - MapMouseEvent mme = (MapMouseEvent) e; - pnt = mme.getProjectedLocation(); - } - - if (pnt == null) { - pnt = new Point2D.Double(e.getX(), e.getY()); - } - - return pnt; - } - - public boolean isMouseEventTouching(MouseEvent e) { - Point2D pnt = getProjectionPoint(e); - return getGraphic().distance(pnt.getX(), pnt.getY()) <= 2; - } - - public boolean isMouseEventTouchingTheEdge(MouseEvent e) { - Point2D pnt = getProjectionPoint(e); - return getGraphic().distanceToEdge(pnt.getX(), pnt.getY()) <= 2; - } - - /** - * This method should be overwritten for each EditableOMGraphic to save the state of the current OMGraphic, in case - * the user wants to revert to this state. Called from the updateCurrentState method. - * - * @param whatHappened String describing what got you here. You can leave this null if you just want to go with the default. - * @return UndoEvent reflecting current state. May be null if undo isn't handled. Returning null is the default - * action. - */ - protected UndoEvent createUndoEventForCurrentState(String whatHappened) { - if (whatHappened == null) { - whatHappened = i18n.get(this.getClass(), "omgraphicUndoString", "Edit"); - } - try { - return new OMGraphicUndoEvent(this, whatHappened); - } catch (MissingResourceException mre) { - // Return null so event won't be registered. - return null; - } - } - - /** - * Called by anything that knows that the EOMG has arrived at a stable state that should be kept for Undo actions. - * - * @param whatHappened a description of was done to get to this state. If null, the EOMG will create a default string - * to use. - */ - public void updateCurrentState(String whatHappened) { - UndoEvent undoEvent = createUndoEventForCurrentState(whatHappened); - - if (undoEvent != null && undoStack != null) { - undoStack.setTheWayThingsAre(undoEvent); - } - } - - /** - * @return the undoStack - */ - public UndoStack getUndoStack() { - return undoStack; - } - - /** - * @param undoStack the undoStack to set - */ - public void setUndoStack(UndoStack undoStack) { - this.undoStack = undoStack; - } - - /** - * A little flag to let the EOMG that a popup menu is up on the map. If the menu is up, and the menu is not clicked - * on, we don't really want to deactivate the drawing tool right then - let a free click go by first, which will - * dismiss the menu. - * - * @param popupIsUp - */ - public void setPopupIsUp(boolean popupIsUp) { - this.popupIsUp = popupIsUp; - } - - public boolean isPopupIsUp() { - return this.popupIsUp; - } - - public JComponent createAttributePanel(GraphicAttributes graphicAttributes) { -// JPanel palette = new JPanel(); - -// GridBagLayout gridbag = new GridBagLayout(); -// GridBagConstraints c = new GridBagConstraints(); -// palette.setLayout(gridbag); - - JToolBar toolbar = new GridBagToolBar(); - - if (graphicAttributes != null) { - int orientation = graphicAttributes.getOrientation(); - toolbar.setOrientation(orientation); -// if (orientation == SwingConstants.VERTICAL) { -// c.gridwidth = GridBagConstraints.REMAINDER; -// } - } - - -// gridbag.setConstraints(toolbar, c); -// palette.add(toolbar); - return toolbar; - } - - /** - * Generic undo event for basic OMGraphics. - * - * @author dietrick - */ - public static class OMGraphicUndoEvent - implements UndoEvent { - - protected EditableOMGraphic eomg; - protected OMGraphic stateHolder; - protected String description; - - public OMGraphicUndoEvent(EditableOMGraphic eomg, String description) - throws MissingResourceException { - this.eomg = eomg; - this.description = description; - - OMGraphic omg = eomg.getGraphic(); - stateHolder = (OMGraphic) ComponentFactory.create(omg.getClass().getName()); - - if (stateHolder != null) { - // stateHolder = new OMPoly(); - stateHolder.restore(eomg.getGraphic()); - } else { - throw new MissingResourceException(eomg.getClass().getName() + " can't provide UndoEvents", eomg.getClass().getName(), ""); - } - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.UndoEvent#getDescription() - */ - public String getDescription() { - return description; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.event.UndoEvent#setState() - */ - public void setState() { - this.eomg.getGraphic().restore(stateHolder); - setSubclassState(); - this.eomg.regenerate(this.eomg.getProjection()); - this.eomg.repaint(); - } - - /** - * Called from setState before repaint() is called, so subclasses can update anything in their EditableOMGraphic - * state for the restored OMGraphic. - */ - protected void setSubclassState() { - // noop, for subclasses to use so we don't waste a repaint. - } - - /** - * @return the stateHolder - */ - public OMGraphic getStateHolder() { - return stateHolder; - } - - /** - * @param stateHolder the stateHolder to set - */ - public void setStateHolder(OMGraphic stateHolder) { - this.stateHolder = stateHolder; - } - - /** - * @return the eomg - */ - public EditableOMGraphic getEomg() { - return eomg; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphicList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphicList.java deleted file mode 100644 index 9e05a62b4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMGraphicList.java +++ /dev/null @@ -1,417 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMGraphicList.java,v $ -// $RCSfile: EditableOMGraphicList.java,v $ -// $Revision: 1.4 $ -// $Date: 2006/08/09 21:08:36 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.event.MouseEvent; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.omGraphics.editable.ListStateMachine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; - -/** - * An EditableOMGraphic list encapsulates an OMGraphicList to move the - * editable ones around when they are selected as a group. - */ -public class EditableOMGraphicList extends EditableOMGraphic { - - /** - * For grabbing the list objects and moving them. - */ - protected OffsetGrabPoint gpm; - - /** - * The list of OMGraphics being selected and moved. - */ - protected OMGraphicList list; - - /** - * The list of editables wrapping the list contents. - */ - protected List editables; - - /** - * Create an empty EditableOMGraphicList, ready to have OMGraphics - * added to it. - */ - public EditableOMGraphicList() { - this(new OMGraphicList()); - } - - /** - * Create the EditableOMGraphicList with an OMGraphicList already - * defined, ready for editing. - * - * @param oml OMGraphicList that should be handled. - */ - public EditableOMGraphicList(OMGraphicList oml) { - setGraphic(oml); - } - - public List getEditables() { - if (editables == null) { - editables = new LinkedList(); - } - return editables; - } - - /** - * Create and initialize the state machine that interprets the - * modifying gestures/commands, as well as initialize the grab - * points. Also allocates the grab point array needed by the - * EditableOMGraphicList. - */ - public void init() { - Debug.message("eomg", "EditableOMGraphicList.init()"); - getEditables(); - setStateMachine(new ListStateMachine(this)); - } - - /** - * Must be called on a EditableOMGraphicList that is created from - * an OMGraphicList containing OMGraphics. - * - * @param drawingTool OMDrawingTool used to create - * EditableOMGraphics for other OMGraphics on the list, - * which will in turn be managed by this - * EditableOMGraphicList. If this is null, nothing will get - * done. If this drawing tool doesn't know how to create an - * EditableOMGraphic for anything on the list, those things - * will not be managed. - */ - public void init(OMDrawingTool drawingTool) { - if (list != null) { - for (OMGraphic omg: list) { - // Do we need to handle OMGraphicLists in a special - // way? - if (omg.isVisible()) { - add(omg, drawingTool); - } - } - } - } - - public GrabPoint[] getGrabPoints() { - return new GrabPoint[] { gpm }; - } - - /** - * Set the graphic within the state machine. If the graphic is - * null, then one shall be created, and located off screen until - * the gestures driving the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMGraphicList) { - list = (OMGraphicList) graphic; - list.setProcessAllGeometries(true); - stateMachine.setSelected(); - gpm = new OffsetGrabPoint(-10, -10); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of line to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - - OMGraphicList tmpList = new OMGraphicList(); - - if (ga != null) { - ga.setTo(tmpList); - } - - setGraphic(tmpList); - } - - /** - * Get the OMGraphic being created/modified by the - * EditableOMGraphicList. - */ - public OMGraphic getGraphic() { - return list; - } - - public void add(OMGraphicList list, OMDrawingTool drawingTool) { - for (OMGraphic omg : list) { - add(omg, drawingTool); - } - } - - /** - * Create an EditableOMGraphic and add it to the list. - * - * @param omg OMGraphic to add. - * @param drawingTool to use to figure out what EditableOMGraphic - * to use for the OMGraphic. - * @return EditableOMGraphic if successful, null if not. - */ - public EditableOMGraphic add(OMGraphic omg, OMDrawingTool drawingTool) { - EditableOMGraphic editable = null; - - if (omg instanceof OMGraphicList) { - add((OMGraphicList) omg, drawingTool); - return editable; - } - - if (omg != null && drawingTool != null) { - // The OMDrawingTool knows how to create an - // EditableOMGraphic for the omg - editable = drawingTool.getEditableGraphic(omg); - if (editable != null) { - add(editable); - } else { - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList can't handle " - + omg.getClass().getName()); - } - } - } else { - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList told to add null OMGraphic or null OMDrawingTool"); - } - } - - return editable; - } - - /** - * Add the EditableOMGraphic to the list. - */ - public void add(EditableOMGraphic editable) { - if (editable == null) { - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList adding null EditableOMGraphic"); - } - return; - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList adding " - + editable.getClass().getName() + " " + editable); - } - - OMGraphic graphic = editable.getGraphic(); - - if (!list.contains(graphic)) { - getEditables().add(editable); - editable.setProjection(getProjection()); - - // Need this for distance measurements. - list.add(graphic); - editable.attachToMovingGrabPoint(gpm); - } else { - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList.add(" - + editable.getClass().getName() - + ") not added, duplicate"); - } - } - } - - /** - * Remove an OMGraphic from being moved. - */ - public void remove(OMGraphic omg) { - EditableOMGraphic eomg = null; - for (EditableOMGraphic eomgraphic : getEditables()) { - eomg = eomgraphic; - if (eomg.getGraphic() == omg) { - break; - } - eomg = null; - } - - // If we found the eomg for the omg, we broke out of the loop above and - // eomg is set to something. - if (eomg != null) { - remove(eomg); - list.remove(omg); - } - } - - /** - * Remove the EditableOMGraphic from the list. - */ - public boolean remove(EditableOMGraphic editable) { - if (editable == null) { - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList removing null EditableOMGraphic"); - } - return false; - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMGraphicList removing " - + editable.getClass().getName()); - } - - editable.setProjection(null); - editable.detachFromMovingGrabPoint(gpm); - boolean ret = getEditables().remove(editable); - return ret; - } - - /** - * Remove all EditableOMGraphics and clear out. - */ - public void clear() { - // list.processAllGeometries(false); - // list.clear(); - // list = null; - getEditables().clear(); - gpm.clear(); - } - - /** - * Set the current projection. - */ - public void setProjection(Projection proj) { - if (Debug.debugging("eomg")) { - Debug.output("EOMGL: setProjection(" + proj + ")"); - } - super.setProjection(proj); - for (EditableOMGraphic eomg : getEditables()) { - eomg.setProjection(proj); - } - } - - /** - * Take the current location of the GrabPoints, and modify the - * location parameters of the OMLine with them. Called when you - * want the graphic to change according to the grab points. - */ - public void setGrabPoints() { - for (EditableOMGraphic eomg : getEditables()) { - eomg.setGrabPoints(); - // if (Debug.debugging("eomg")) { - // Debug.output(" -- setting GrabPoints on " + - // editable.getClass().getName()); - // } - } - } - - public GrabPoint getMovingPoint(MouseEvent me) { - // For the EdtiableOMGraphicList, this should just go ahead - // and test for contact for anything on the OMGraphicList, and - // return the gpm for that point. - if (list != null) { - float distance = list.distance(me.getX(), me.getY()); - if (distance <= 4) { - // will set movingPoint - move(me); - } else { - // int count = 0; - // for (Iterator it = list.iterator(); it.hasNext();) - // { - // OMGraphic omg = (OMGraphic)it.next(); - // Debug.output(" graphic " + (count++) + " distance(" - // + - // omg.distance(me.getX(), me.getY()) + ") ntbr: " + - // omg.getNeedToRegenerate()); - // } - movingPoint = null; - } - } else { - // Debug.output("EOMGL.getMovingPoint() null list"); - movingPoint = null; - } - - return movingPoint; - } - - /** - * Called to set the OffsetGrabPoint to the current mouse - * location, and update the OffsetGrabPoint with all the other - * GrabPoint locations, so everything can shift smoothly. Should - * also set the OffsetGrabPoint to the movingPoint. Should be - * called only once at the beginning of the general movement, in - * order to set the movingPoint. After that, redraw(e) should just - * be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(MouseEvent e) { - if (gpm != null) { - gpm.set(e.getX(), e.getY()); - gpm.updateOffsets(); - movingPoint = gpm; - } - } - - /** - * Use the current projection to place the graphics on the screen. - * Has to be called to at least assure the graphics that they are - * ready for rendering. Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomg", "EditableOMGraphicList.generate()"); - - for (EditableOMGraphic eomg : getEditables()) { - eomg.generate(proj); - } - - if (gpm != null) - gpm.generate(proj); - - return true; - } - - /** - * Given a new projection, the grab points may need to be - * repositioned off the current position of the graphic. Called - * when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMGraphicList.regenerate()"); - - for (EditableOMGraphic eomg : getEditables()) { - eomg.regenerate(proj); - } - - if (gpm != null) - gpm.generate(proj); - } - - /** - * Draw the EditableOMGraphicList parts into the java.awt.Graphics - * object. The grab points are only rendered if the line machine - * state is LineSelectedState.LINE_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - for (EditableOMGraphic eomg : getEditables()) { - eomg.render(graphics); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMLine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMLine.java deleted file mode 100644 index b7204d6f0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMLine.java +++ /dev/null @@ -1,450 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMLine.java,v $ -// $RCSfile: EditableOMLine.java,v $ -// $Revision: 1.13 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.LineStateMachine; -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The EditableOMLine encompasses an OMLine, providing methods for modifying or - * creating it. - */ -public class EditableOMLine extends EditableOMAbstractLine implements NonRegional { - - protected GrabPoint gp1; - protected GrabPoint gp2; - protected OffsetGrabPoint gpo; // offset - protected OffsetGrabPoint gpm; // for grabbing the line and moving - // it. - - protected OMLine line; - - public final static int STARTING_POINT_INDEX = 0; - public final static int ENDING_POINT_INDEX = 1; - public final static int OFFSET_POINT_INDEX = 2; - - /** - * Create the EditableOMLine, setting the state machine to create the line - * off of the gestures. - */ - public EditableOMLine() { - createGraphic(null); - } - - /** - * Create an EditableOMLine with the lineType and renderType parameters in - * the GraphicAttributes object. - */ - public EditableOMLine(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMLine with an OMLine already defined, ready for - * editing. - * - * @param oml OMLine that should be edited. - */ - public EditableOMLine(OMLine oml) { - setGraphic(oml); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMLine. - */ - public void init() { - Debug.message("eomg", "EditableOMLine.init()"); - setStateMachine(new LineStateMachine(this)); - gPoints = new GrabPoint[3]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMLine) { - line = (OMLine) graphic; - stateMachine.setSelected(); - setGrabPoints(line); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of line to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - int lineType = OMGraphic.LINETYPE_GREATCIRCLE; - - if (ga != null) { - renderType = ga.getRenderType(); - lineType = ga.getLineType(); - } - - if (Debug.debugging("eoml")) { - Debug.output("EditableOMLine.createGraphic(): rendertype = " + renderType); - } - - if (lineType == OMGraphic.LINETYPE_UNKNOWN) { - lineType = OMGraphic.LINETYPE_GREATCIRCLE; - if (ga != null) - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - line = new OMLine(90f, -180f, 90f, -180f, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - line = new OMLine(90d, -180d, 0, 0, 0, 0); - break; - default: - line = new OMLine(-1, -1, -1, -1); - } - - if (ga != null) { - ga.setTo(line, true); - } - } - - /** - * Get the OMGraphic being created/modified by the EditableOMLine. - */ - public OMGraphic getGraphic() { - return line; - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - public void setMovingPoint(GrabPoint gp) { - super.setMovingPoint(gp); - gpm = null; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - if (gp1 == null) { - gp1 = new GrabPoint(-1, -1); - gPoints[STARTING_POINT_INDEX] = gp1; - } - if (gp2 == null) { - gp2 = new GrabPoint(-1, -1); - gPoints[ENDING_POINT_INDEX] = gp2; - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gp1); - gpo.addGrabPoint(gp2); - } - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - if (!(graphic instanceof OMLine)) { - return; - } - - assertGrabPoints(); - - OMLine line = (OMLine) graphic; - boolean ntr = line.getNeedToRegenerate(); - int renderType = line.getRenderType(); - if (ntr == false) { - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - Debug.message("eomg", "EditableOMLine: modifying lat/lon line"); - - // Complicated lines!!!! Need to grab the end points - // that are on the map! See, for very large lines - // that go around the earth, they are actually drawn - // in OpenMap as an array of lines that are clipped as - // they go offscreen. Eventually, one of the points - // should appear on the map somewhere. If they don't, - // then then the end points may not be on the screen. - if (projection != null) { - - double[] ll = line.getLL(); - Point2D p = projection.forward(ll[0], ll[1]); - gp1.set((int) p.getX(), (int) p.getY()); - - projection.forward(ll[2], ll[3], p); - gp2.set((int) p.getX(), (int) p.getY()); - } - - } else { - // Grab the projected endpoints - Debug.message("eomg", "EditableOMLine: modifying x/y or offset standard line"); - gp1.set(line.xpoints[0][0], line.ypoints[0][0]); - - int last = line.xpoints[0].length - 1; - gp2.set(line.xpoints[0][last], line.ypoints[0][last]); - } - - // Check to see if the line is a offset line, and set the - // offset grab point accordingly. - if (line.getRenderType() == OMGraphic.RENDERTYPE_OFFSET && projection != null) { - - double[] ll = line.getLL(); - Point2D p = projection.forward(ll[0], ll[1]); - - gpo.set((int) p.getX(), (int) p.getY()); - gpo.updateOffsets(); - } - } else { - Debug.message("eomg", "EditableOMLine.setGrabPoints: graphic needs to be regenerated"); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMLine with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = line.getRenderType(); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - if (projection != null) { - double[] coords = new double[4]; - LatLonPoint llp = (LatLonPoint) projection.inverse(gp1.getX(), gp1.getY(), new LatLonPoint.Double()); - - coords[0] = llp.getY(); - coords[1] = llp.getX(); - - projection.inverse(gp2.getX(), gp2.getY(), llp); - coords[2] = llp.getY(); - coords[3] = llp.getX(); - line.setLL(coords); - } else { - Debug.message("eomg", "EditableOMLine.setGrabPoints: projection is null, can't figure out LATLON points for line."); - } - } else if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - // Do the offset point. - if (projection != null) { - double[] coords = new double[4]; - LatLonPoint llp = (LatLonPoint) projection.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - - coords[0] = llp.getY(); - coords[1] = llp.getX(); - coords[2] = 0;// not used - coords[3] = 0;// not used - line.setLL(coords); - } else { - Debug.message("eomg", "EditableOMLine.setGrabPoints: projection is null, can't figure out LATLON points for line offset."); - } - } - - if (renderType == OMGraphic.RENDERTYPE_XY || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - int[] ints = new int[4]; - if (renderType == OMGraphic.RENDERTYPE_OFFSET && gpo != null) { - // If offset rendertype, the x-y have to be offset - // distances, not screen pixel locations. - ints[0] = gp1.getX() - gpo.getX(); - ints[1] = gp1.getY() - gpo.getY(); - ints[2] = gp2.getX() - gpo.getX(); - ints[3] = gp2.getY() - gpo.getY(); - } else { - ints[0] = gp1.getX(); - ints[1] = gp1.getY(); - ints[2] = gp2.getX(); - ints[3] = gp2.getY(); - } - line.setPts(ints); - } - - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(MouseEvent e) { - // Need to check to see if the OffsetGrabPoint is currently - // being used. If not, just use it, otherwise, will need to - // create a special one for the move. - - Point2D pnt = getProjectionPoint(e); - int x = (int) pnt.getX(); - int y = (int) pnt.getY(); - - if (line.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - gpm = new OffsetGrabPoint(x, y); - - gpm.addGrabPoint(gp1); - gpm.addGrabPoint(gp2); - - } else { - gpm = gpo; - gpm.set(x, y); - gpm.updateOffsets(); - } - movingPoint = gpm; - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomg", "EditableOMLine.generate()"); - if (line != null) - line.generate(proj); - - if (gp1 != null) - gp1.generate(proj); - if (gp2 != null) - gp2.generate(proj); - if (gpo != null) { - gpo.generate(proj); - gpo.updateOffsets(); - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMLine.regenerate()"); - if (line != null) - line.generate(proj); - setGrabPoints(line); - - if (gp1 != null) - gp1.generate(proj); - if (gp2 != null) - gp2.generate(proj); - if (gpo != null) { - gpo.generate(proj); - gpo.updateOffsets(); - } - } - - /** - * Draw the EditableOMLine parts into the java.awt.Graphics object. The grab - * points are only rendered if the line machine state is - * LineSelectedState.LINE_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomg", "EditableOMLine.render()"); - - State state = getStateMachine().getState(); - - if (line != null) { - line.setVisible(true); - line.render(graphics); - line.setVisible(false); - } else { - Debug.message("eomg", "EditableOMLine.render: null line."); - } - - if (state instanceof GraphicSelectedState) { - if (gp1 != null) { - gp1.setVisible(true); - gp1.render(graphics); - gp1.setVisible(false); - } - - if (gp2 != null) { - gp2.setVisible(true); - gp2.render(graphics); - gp2.setVisible(false); - } - } - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState /* - * || - * state - * instanceof - * LineSetOffsetState - */) { - if (gpo != null && line.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - gpo.setVisible(true); - gpo.render(graphics); - gpo.setVisible(false); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoint.java deleted file mode 100644 index a0a83a568..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoint.java +++ /dev/null @@ -1,499 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMPoint.java,v $ -// $RCSfile: EditableOMPoint.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Component; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import javax.swing.JComponent; -import javax.swing.JToolBar; - -import com.bbn.openmap.gui.GridBagToolBar; -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.GraphicSetOffsetState; -import com.bbn.openmap.omGraphics.editable.GraphicUndefinedState; -import com.bbn.openmap.omGraphics.editable.PointStateMachine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * An EditableOMGraphic that encapsulates an OMPoint. - */ -public class EditableOMPoint extends EditableOMGraphic { - - protected GrabPoint gpc; - protected OffsetGrabPoint gpo; // offset - - protected OMPoint point; - - public final static String OffsetResetCmd = "OffsetResetCmd"; - public final static int CENTER_POINT_INDEX = 0; - public final static int OFFSET_POINT_INDEX = 1; - - /** - * Create the EditableOMPoint, setting the state machine to create the point - * off of the gestures. - */ - public EditableOMPoint() { - createGraphic(null); - } - - /** - * Create an EditableOMPoint with the pointType and renderType parameters in - * the GraphicAttributes object. - */ - public EditableOMPoint(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMPoint with an OMPoint already defined, ready for - * editing. - * - * @param omc OMPoint that should be edited. - */ - public EditableOMPoint(OMPoint omc) { - setGraphic(omc); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMPoint. - */ - public void init() { - Debug.message("eomg", "EditableOMPoint.init()"); - setCanGrabGraphic(false); - setStateMachine(new PointStateMachine(this)); - gPoints = new GrabPoint[2]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMPoint) { - point = (OMPoint) graphic; - stateMachine.setSelected(); - setGrabPoints(point); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of point to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - - if (ga != null) { - renderType = ga.getRenderType(); - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMPoint.createGraphic(): rendertype = " + renderType); - } - - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - point = new OMPoint(90f, -180f); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - point = new OMPoint(90f, -180f, 0, 0); - break; - default: - point = new OMPoint(-1, -1); - } - - if (ga != null) { - ga.setTo(point); - } - - assertGrabPoints(); - } - - /** - * Get the OMGraphic being created/modified by the EditableOMPoint. - */ - public OMGraphic getGraphic() { - return point; - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - // public void setMovingPoint(GrabPoint gp) { - // super.setMovingPoint(gp); - // } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the - * moving point to that GrabPoint. - * - * @param e MouseEvent - * @return GrabPoint that is touched by the MouseEvent, null if none are. - */ - public GrabPoint getMovingPoint(MouseEvent e) { - - movingPoint = null; - GrabPoint[] gb = getGrabPoints(); - - Point2D pnt = getProjectionPoint(e); - double x = pnt.getX(); - double y = pnt.getY(); - - for (int i = gb.length - 1; i >= 0; i--) { - - if (gb[i] != null && gb[i].distance(x, y) == 0) { - - setMovingPoint(gb[i]); - // in case the points are on top of each other, the - // last point in the array will take precedence. - break; - } - } - return movingPoint; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - protected int lastRenderType = -1; - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - int rt = getGraphic().getRenderType(); - if (rt != lastRenderType) { - clearGrabPoints(); - lastRenderType = rt; - } - - if (gpc == null) { - gpc = new GrabPoint(-1, -1); - gPoints[CENTER_POINT_INDEX] = gpc; - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gpc); - } - } - - protected void clearGrabPoints() { - - gpc = null; - gpo = null; - - gPoints[CENTER_POINT_INDEX] = gpc; - gPoints[OFFSET_POINT_INDEX] = gpo; - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - Debug.message("eomg", "EditableOMPoint.setGrabPoints(graphic)"); - if (!(graphic instanceof OMPoint)) { - return; - } - - assertGrabPoints(); - - OMPoint point = (OMPoint) graphic; - boolean ntr = point.getNeedToRegenerate(); - int renderType = point.getRenderType(); - - LatLonPoint llp; - int latoffset = 0; - int lonoffset = 0; - - boolean doStraight = true; - - if (ntr == false) { - - if (renderType == OMGraphic.RENDERTYPE_LATLON - || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - if (projection != null) { - double lon = point.getLon(); - double lat = point.getLat(); - - llp = new LatLonPoint.Double(lat, lon); - Point2D p = projection.forward(llp); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - doStraight = false; - gpc.set((int) p.getX(), (int) p.getY()); - } else { - latoffset = (int) p.getY(); - lonoffset = (int) p.getX(); - gpo.set(lonoffset, latoffset); - } - } - } - - if (doStraight) { - gpc.set(lonoffset + point.getX(), latoffset + point.getY()); - } - - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - gpo.updateOffsets(); - } - - } else { - Debug.message("eomg", "EditableOMPoint.setGrabPoints: graphic needs to be regenerated"); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMPoint with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = point.getRenderType(); - LatLonPoint llp1; - - Debug.message("eomg", "EditableOMPoint.setGrabPoints()"); - - // Do center point for lat/lon or offset points - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - - if (projection != null) { - // movingPoint == gpc - llp1 = (LatLonPoint) projection.inverse(gpc.getX(), gpc.getY(), new LatLonPoint.Double()); - point.set(llp1.getY(), llp1.getX()); - // point.setNeedToRegenerate set - } - } - - boolean settingOffset = getStateMachine().getState() instanceof GraphicSetOffsetState - && movingPoint == gpo; - - // If the center point is moving, the offset distance changes - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - - llp1 = (LatLonPoint) projection.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - - point.setLat(llp1.getY()); - point.setLon(llp1.getX()); - - if (settingOffset || movingPoint == gpc) { - // Don't call point.setLocation because we only want - // to - // setNeedToRegenerate if !settingOffset. - point.setX(gpc.getX() - gpo.getX()); - point.setY(gpc.getY() - gpo.getY()); - } - - if (!settingOffset) { - Debug.message("eomg", "EditableOMPoint: updating offset point"); - point.set(gpc.getX() - gpo.getX(), gpc.getY() - gpo.getY()); - } - - // Set Location has reset the rendertype, but provides - // the convenience of setting the max and min values - // for us. - point.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - } - - // Do the point height and width for XY and OFFSET render - // types. - if (renderType == OMGraphic.RENDERTYPE_XY) { - Debug.message("eomg", "EditableOMPoint: updating x/y point"); - - if (movingPoint == gpc) { - point.set(gpc.getX(), gpc.getY()); - } - } - - if (projection != null) { - regenerate(projection); - } - } - - /** - * Get whether a graphic can be manipulated by its edges, rather than just - * by its grab points. - */ - public boolean getCanGrabGraphic() { - return false; - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(java.awt.event.MouseEvent e) { - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomgdetail", "EditableOMPoint.generate()"); - if (point != null) - point.generate(proj); - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - gp.generate(proj); - } - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMPoint.regenerate()"); - if (point != null) - point.generate(proj); - - setGrabPoints(point); - generate(proj); - } - - /** - * Draw the EditableOMPoint parts into the java.awt.Graphics object. The - * grab points are only rendered if the point machine state is - * PointSelectedState.POINT_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomgdetail", "EditableOMPoint.render()"); - - if (point == null) { - Debug.message("eomg", "EditableOMPoint.render: null point."); - return; - } - - State state = getStateMachine().getState(); - - if (!(state instanceof GraphicUndefinedState)) { - point.setVisible(true); - point.render(graphics); - point.setVisible(false); - - int renderType = point.getRenderType(); - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState) { - - for (int i = 0; i < gPoints.length; i++) { - - GrabPoint gp = gPoints[i]; - if (gp != null) { - if ((i == OFFSET_POINT_INDEX && renderType == OMGraphic.RENDERTYPE_OFFSET && movingPoint == gpo) - || (state instanceof GraphicSelectedState && ((i != OFFSET_POINT_INDEX && renderType != OMGraphic.RENDERTYPE_OFFSET) || (renderType == OMGraphic.RENDERTYPE_OFFSET))) - - ) { - - gp.setVisible(true); - gp.render(graphics); - gp.setVisible(false); - } - } - } - } - } - } - - /** - * Modifies the gui to not include line type adjustments, and adds widgets - * to control point settings. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return java.awt.Component to use to control parameters for this EOMG. - */ - public Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMPoint.getGUI"); - if (graphicAttributes != null) { - // JComponent panel = graphicAttributes.getColorAndLineGUI(); - JComponent panel = createAttributePanel(graphicAttributes); - panel.add(getPointGUI()); - return panel; - } else { - return getPointGUI(); - } - } - - protected JToolBar pToolBar = null; - - protected JToolBar getPointGUI() { - if (pToolBar == null) { - pToolBar = new GridBagToolBar(); - // Add buttons to toggle oval/rect, radius of point. - } - - return pToolBar; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoly.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoly.java deleted file mode 100644 index 29bb72525..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMPoly.java +++ /dev/null @@ -1,1527 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMPoly.java,v $ -// $RCSfile: EditableOMPoly.java,v $ -// $Revision: 1.19 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.net.URL; -import java.util.List; -import java.util.Vector; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JMenu; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; - -import com.bbn.openmap.event.UndoEvent; -import com.bbn.openmap.gui.GridBagToolBar; -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.PolyAddNodeState; -import com.bbn.openmap.omGraphics.editable.PolyDeleteNodeState; -import com.bbn.openmap.omGraphics.editable.PolyStateMachine; -import com.bbn.openmap.omGraphics.editable.PolyUndefinedState; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The EditableOMPoly encompasses an OMPoly, providing methods for modifying or - * creating it. - */ -public class EditableOMPoly extends EditableOMAbstractLine { - - protected List polyGrabPoints; - protected OffsetGrabPoint gpo; // offset - protected OffsetGrabPoint gpm; // for grabbing the poly and - // moving - // it. - - protected OMPoly poly; - /** - * Whether the poly is a polygon, as opposed to a polyline. If the poly - * color is not clear (OMColor.clear) then it will be a polygon. If it is - * clear, then it can be set as a polygon - it's otherwise assumed to be a - * polyline. - */ - protected boolean manualEnclosed = false; - - /** - * Set the index of the grab point that should be rendered differently, in - * order to highlight a specific node. - */ - protected int selectNodeIndex = 3; - - // We'll have to handle this differently... - public static int OFFSET_POINT_INDEX = -1; - - /** - * Create the EditableOMPoly, setting the state machine to create the poly - * off of the gestures. - */ - public EditableOMPoly() { - createGraphic(null); - } - - /** - * Create an EditableOMPoly with the polyType and renderType parameters in - * the GraphicAttributes object. - */ - public EditableOMPoly(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMPoly with an OMPoly already defined, ready for - * editing. - * - * @param omp OMPoly that should be edited. - */ - public EditableOMPoly(OMPoly omp) { - setGraphic(omp); - } - - /** - * Create and initialize the state machine that interprets the - * - * modifying gestures/commands, as well as initialize the grab points. Also - * allocates the grab point array needed by the EditableOMPoly. - */ - public void init() { - Debug.message("eomg", "EditableOMPoly.init()"); - setStateMachine(new PolyStateMachine(this)); - gPoints = new GrabPoint[1]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMPoly) { - poly = (OMPoly) graphic; - poly.setDoShapes(true); - stateMachine.setSelected(); - setGrabPoints(poly); - } else { - createGraphic(null); - } - } - - /** - * Method checks if the polygon should be enclosed, and then adds an - * addition point to the end of the polygon, setting the end point on top of - * the beginning point. The two points are OffsetGrabPoints that are tied to - * each other's position. - */ - public boolean evaluateEnclosed() { - deletePoint(); - boolean enclosed = false; - - if (isEnclosed()) { - enclose(true); - enclosed = true; - } - return enclosed; - } - - /** - * Method connects the last point to the first point. Make sure they are - * both OffsetGrabPoints. Return true if the points cover the same pixel and - * if they were successfully joined. - */ - protected boolean syncEnclosed() { - try { - if (polyGrabPoints == null || polyGrabPoints.isEmpty()) { - return false; - } - - OffsetGrabPoint gb0 = (OffsetGrabPoint) polyGrabPoints.get(0); - OffsetGrabPoint ogb = (OffsetGrabPoint) polyGrabPoints.get(polyGrabPoints.size() - 1); - - // Check to see if they are over the same point. - if (gb0.getX() == ogb.getX() && gb0.getY() == ogb.getY()) { - - // Cross connect them... - gb0.addGrabPoint(ogb); - ogb.addGrabPoint(gb0); - return true; - } - } catch (ClassCastException cce) { - } catch (IndexOutOfBoundsException ioobe) { - } - return false; - } - - /** - * Method disconnects the last point from the first point. Make sure they - * are both OffsetGrabPoints. - */ - protected boolean unsyncEnclosed() { - try { - OffsetGrabPoint gb0 = (OffsetGrabPoint) polyGrabPoints.get(0); - OffsetGrabPoint ogb = (OffsetGrabPoint) polyGrabPoints.get(polyGrabPoints.size() - 1); - - // disconnect them... - if (gb0.getX() == ogb.getX() && gb0.getY() == ogb.getY()) { - gb0.removeGrabPoint(ogb); - ogb.removeGrabPoint(gb0); - return true; - } - } catch (ClassCastException cce) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - return false; - } - - public void enclose(boolean e) { - setEnclosed(e); - - if (polyGrabPoints == null || polyGrabPoints.isEmpty()) { - return; - } - - OffsetGrabPoint gb0 = (OffsetGrabPoint) polyGrabPoints.get(0); - OffsetGrabPoint ogb; - - if (e) { - // If they should be enclosed... - if (!syncEnclosed()) { - // And they are not already, then add a point, joined - // to the beginning. - ogb = new OffsetGrabPoint(gb0.getX(), gb0.getY()); - - // Add the new point to end of the poly - addPoint(ogb); - syncEnclosed(); - repaint(); - } // Else nothing to do... - } else { - // They shouldn't be hooked up, so check to see if they - // are, and disconnect if necessary. - if (unsyncEnclosed()) { - deletePoint(); // Delete attached duplicate point - repaint(); - } // else nothing to do. - } - } - - /** - * Set the flag to make the polygon enclosed, which automatically connects - * the last point with the first point. - */ - public void setEnclosed(boolean set) { - manualEnclosed = set; - } - - /** - * Returns whether the graphic will be a polygon, instead of a polyline. - */ - public boolean isEnclosed() { - return manualEnclosed; - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of poly to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_LATLON; - int lineType = OMGraphic.LINETYPE_GREATCIRCLE; - - if (ga != null) { - renderType = ga.getRenderType(); - lineType = ga.getLineType(); - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMPoly.createGraphic(): rendertype = " + renderType); - } - - if (lineType == OMGraphic.LINETYPE_UNKNOWN) { - lineType = OMGraphic.LINETYPE_GREATCIRCLE; - if (ga != null) - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - - this.poly = (OMPoly) createGraphic(renderType, lineType); - - if (ga != null) { - ga.setRenderType(poly.getRenderType()); - ga.setTo(poly, true); - } - } - - /** - * Extendable method to create specific subclasses of OMPolys. - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - g = new OMPoly(new double[0], OMGraphic.RADIANS, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - g = new OMPoly(90f, -180f, new int[0], OMPoly.COORDMODE_ORIGIN); - break; - default: - g = new OMPoly(new int[0]); - } - ((OMPoly) g).setDoShapes(true); - return g; - } - - /** - * Get the OMGraphic being created/modified by the EditableOMPoly. - */ - public OMGraphic getGraphic() { - return poly; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - public void setMovingPoint(GrabPoint gp) { - super.setMovingPoint(gp); - gpm = null; - } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the - * moving point to that GrabPoint. Called when a MouseEvent happens, and you - * want to find out if a GrabPoint should be used to make modifications to - * the graphic or its position. - * - * @param e MouseEvent - * @return GrabPoint that is touched by the MouseEvent, null if none are. - */ - public GrabPoint getMovingPoint(MouseEvent e) { - GrabPoint gb = super.getMovingPoint(e); - - // Since there may be an extra point enclosing the polygon, we - // want to make sure that the start of the polygon is - // returned, instead of the duplicate ending point. - int lastPointIndex = polyGrabPoints.size() - 1; - - if (gb != null && gb == polyGrabPoints.get(lastPointIndex) && isEnclosed()) { - - gb = polyGrabPoints.get(0); - setMovingPoint(gb); - } - return gb; - } - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - - // This gets called a lot. Usually, for EditableOMGraphics - // that have the same number of GrabPoints, they can just be - // allocated here. I think we'll have to look at the OMPoly, - // find out how many points have been defined for it (since - // it's variable), and make sure everything's OK. - - if (polyGrabPoints == null) { - polyGrabPoints = new Vector(); - } - - // At least we know about this one. - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - } - } - - /** - * An internal method that tries to make sure that the grab point for the - * first node, and for the last, in case of an enclosed polygon, are - * OffsetGrabPoints. All of the other points will be regular GrabPoints. - * Usually called when assigning points to a previously defined poly. - * - * @param x the horizontal pixel location of the grab point. - * @param y the vertical pixel location of the grab point. - * @param index the index of the grab point. - * @param last the index of the last point. - */ - protected GrabPoint createGrabPoint(int x, int y, int index, int last) { - if (index == 0 || (index == last && (isEnclosed()))) { - return new OffsetGrabPoint(x, y); - } else { - return new GrabPoint(x, y); - } - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * points of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - if (!(graphic instanceof OMPoly)) { - return; - } - - assertGrabPoints(); - polyGrabPoints.clear(); - arrayCleared = true; - gpo.clear(); - - OMPoly poly = (OMPoly) graphic; - boolean ntr = poly.getNeedToRegenerate(); - int renderType = poly.getRenderType(); - Point2D p = new Point2D.Double(); - Projection proj = getProjection(); - GrabPoint gb; - int i; - int npts; - boolean geoProj = proj instanceof GeoProj; - - if (ntr == false) { - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - Debug.message("eomg", "EditableOMPoly: modifying lat/lon line"); - - if (proj != null) { - - double[] ll = poly.getLatLonArray(); - boolean rads = poly.getUnits() == OMGraphic.RADIANS; - gb = null; // reset for this loop - - for (i = 0; i < ll.length - 1; i += 2) { - if (geoProj) { - ((GeoProj) proj).forward(ll[i], ll[i + 1], p, rads); - } else { - proj.forward(ll[i], ll[i + 1], p); - } - // Need to add a grab point for this - // coordinate - gb = new OffsetGrabPoint((int) p.getX(), (int) p.getY()); - polyGrabPoints.add(gb); - } - } - - } else if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - // Grab the projected endpoints - Debug.message("eomg", "EditableOMPoly: modifying offset poly"); - - int x; - int y; - npts = poly.xs.length; - - // Check to see if the poly is a offset poly, and set - // the - // offset grab point accordingly. - if (proj != null) { - if (geoProj) { - ((GeoProj) proj).forward(poly.lat, poly.lon, p, true); - } else { - proj.forward(poly.lat, poly.lon, p); - } - gpo.set((int) p.getX(), (int) p.getY()); - - if (poly.coordMode == OMPoly.COORDMODE_ORIGIN) { - for (i = 0; i < npts; i++) { - x = (int) (poly.xs[i] + p.getX()); - y = (int) (poly.ys[i] + p.getY()); - gb = new OffsetGrabPoint(x, y); - polyGrabPoints.add(gb); - } - } else { // CMode Previous offset deltas - int lastX = (int) p.getX(); - int lastY = (int) p.getY(); - - for (i = 0; i < npts; i++) { - x = poly.xs[i] + lastX; - y = poly.ys[i] + lastY; - - gb = new OffsetGrabPoint(x, y); - polyGrabPoints.add(gb); - - lastX += x; - lastY += y; - } - } - } - - } else { - npts = poly.xs.length; - - Debug.message("eomg", "EditableOMPoly: modifying x/y poly"); - for (i = 0; i < npts; i++) { - gb = new OffsetGrabPoint(poly.xs[i], poly.ys[i]); - polyGrabPoints.add(gb); - } - } - - // Add the || to maintain manualEnclosed if it was - // externally set before the OMPoly is actually defined, - // indicating that the user wants to draw a polygon. - setEnclosed(syncEnclosed() || isEnclosed()); - addPolyGrabPointsToOGP(gpo); - - } else { - Debug.message("eomg", "EditableOMPoly.setGrabPoints: graphic needs to be regenerated "); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMPoly with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = poly.getRenderType(); - Projection proj = getProjection(); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - if (proj != null) { - - double[] newCoords = new double[polyGrabPoints.size() * 2]; - - // OK, this code resets the location of every point slightly to - // the inverse location of the grab points. So if you grab one - // node and move it, all of the precise values of each node - // actually changes. As we go through the array of grab points, - // we can check the corresponding projected location of the - // current node and it matches the grab point, just use the - // current poly value. - double[] currentCoords = ProjMath.arrayRadToDeg(poly.getLatLonArrayCopy()); - - Point2D polyPoint = new Point2D.Double(); - LatLonPoint movedPoint = new LatLonPoint.Double(); - - for (int i = 0; i < polyGrabPoints.size(); i++) { - GrabPoint gb = polyGrabPoints.get(i); - - int latIndex = i * 2; - int lonIndex = i * 2 + 1; - - // Set the current coordinate to the GP coordinate - the - // logic is easier this way - proj.inverse(gb.getX(), gb.getY(), movedPoint); - newCoords[latIndex] = movedPoint.getY(); - newCoords[lonIndex] = movedPoint.getX(); - - if (lonIndex < currentCoords.length && gpm != gb) { - - double lat = currentCoords[latIndex]; - double lon = currentCoords[lonIndex]; - polyPoint = proj.forward(lat, lon, polyPoint); - - // if the grab point, forward projected, is in the same - // pixel as the old point, then use the previous value. - boolean pointUnmoved = polyPoint.getX() == gb.getX() - && polyPoint.getY() == gb.getY(); - if (pointUnmoved) { - newCoords[latIndex] = currentCoords[latIndex]; - newCoords[lonIndex] = currentCoords[lonIndex]; - } - } - } - - double[] oldCoords = ProjMath.arrayRadToDeg(poly.getLatLonArrayCopy()); - //int changeCount = 0; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < oldCoords.length - 1; i += 2) { - if (oldCoords[i] != newCoords[i] || oldCoords[i + 1] != newCoords[i + 1]) { - sb.append(i / 2).append(" "); - //changeCount++; - } - } - - /* - * Debug.output("EOMP.SGP: " + changeCount + - * " points changed out of " + (oldCoords.length / 2) + ", " + - * sb.toString()); - */ - poly.setLocation(ProjMath.arrayDegToRad(newCoords), OMGraphic.RADIANS); - - } else { - Debug.message("eomg", "EditableOMPoly.setGrabPoints: projection is null, can't figure out LATLON points for poly."); - } - } - - if (renderType == OMGraphic.RENDERTYPE_XY || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - int[] ints = new int[polyGrabPoints.size() * 2]; - if (renderType == OMGraphic.RENDERTYPE_OFFSET && gpo != null) { - // If offset rendertype, the x-y have to be offset - // distances, not screen pixel locations. For the - // polygon, you also need to take into account that - // the ints can represent 2 different things: distance - // from the origin (Offset) or distance from the - // previous point. Need to check with the poly to - // find out which to do. - GrabPoint previous = gpo; - - for (int i = 0; i < polyGrabPoints.size(); i++) { - GrabPoint gb = polyGrabPoints.get(i); - - if (poly.coordMode == OMPoly.COORDMODE_PREVIOUS) { - - ints[2 * i] = gb.getX() - previous.getX(); - ints[2 * i + 1] = gb.getY() - previous.getY(); - - previous = gb; - - } else { - ints[2 * i] = gb.getX() - gpo.getX(); - ints[2 * i + 1] = gb.getY() - gpo.getY(); - } - } - - if (proj != null) { - - LatLonPoint llp = proj.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - poly.setLocation(llp.getRadLat(), llp.getRadLon(), OMGraphic.RADIANS, ints); - - } else { - Debug.message("eomg", "EditableOMPoly.setGrabPoints: projection is null, can't figure out LATLON points for poly offset."); - } - } else { - - for (int i = 0; i < polyGrabPoints.size(); i++) { - GrabPoint gb = polyGrabPoints.get(i); - - ints[2 * i] = gb.getX(); - ints[2 * i + 1] = gb.getY(); - } - - poly.setLocation(ints); - } - } - - } - - /** - * Add a point to the end of the polyline/polygon and then make it the - * moving one. - * - * @return the index for the point in the polygon, starting with 0. - */ - public int addMovingPoint(int x, int y) { - int position = addPoint(x, y); - setMovingPoint(polyGrabPoints.get(position)); - return position; - } - - /** - * Add a point to the end of the polyline/polygon. - * - * @return the index for the point in the polygon, starting with 0. - */ - public int addPoint(int x, int y) { - return addPoint(x, y, Integer.MAX_VALUE); - } - - /** - * Add a point at a certain point in the polygon coordinate list. If the - * position is less than zero, the point will be the starting point. If the - * position is greater than the list of current points, the point will be - * added to the end of the poly. - * - * @return the index for the point in the polygon, starting with 0. - */ - public int addPoint(int x, int y, int position) { - return addPoint(new OffsetGrabPoint(x, y), position); - } - - /** - * Add a point at a certain point in the polygon coordinate list. If the - * position is less than zero, the point will be the starting point. If the - * position is greater than the list of current points, the point will be - * added to the end of the poly. This method is convenient because it lets - * you define the GrabPoint object to use for the node, in case you need a - * special type of GrabPoint. - * - * @param gp the GrabPoint set to the screen coordinates of the point to be - * added. - * @return the index for the point in the polygon, starting with 0. - */ - public int addPoint(GrabPoint gp) { - return addPoint(gp, Integer.MAX_VALUE); - } - - /** - * Add a point at a certain point in the polygon coordinate list. If the - * position is less than zero, the point will be the starting point. If the - * position is greater than the list of current points, the point will be - * added to the end of the poly. This method is convenient because it lets - * you define the GrabPoint object to use for the node, in case you need a - * special type of GrabPoint. - * - * @return the index for the point in the polygon, starting with 0. - */ - public int addPoint(GrabPoint gp, int position) { - - if (gp == null) { - return -1; - } - - int x = gp.getX(); - int y = gp.getY(); - - int renderType = poly.getRenderType(); - Projection proj = getProjection(); - - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - Debug.message("eomg", "EditableOMPoly: adding point to lat/lon poly"); - - if (proj != null) { - - double[] ll = poly.getLatLonArray(); - int actualPosition = (position == Integer.MAX_VALUE ? ll.length : position * 2); - - LatLonPoint llpnt = proj.inverse(x, y, new LatLonPoint.Double()); - - if (Debug.debugging("eomp")) { - Debug.output("EditableOMPoly: adding point to lat/lon poly at " + x + ", " + y - + ": " + llpnt + ", at the end of "); - - for (int j = 0; j < ll.length; j += 2) { - Debug.output(ll[j] + ", " + ll[j + 1]); - } - } - - double[] newll = new double[ll.length + 2]; - - double newlat = llpnt.getRadLat(); - double newlon = llpnt.getRadLon(); - - if (actualPosition >= ll.length) { - // Put the new points at the end - if (ll.length != 0) { - System.arraycopy(ll, 0, newll, 0, ll.length); - } - - newll[ll.length] = newlat; - newll[ll.length + 1] = newlon; - - position = ll.length / 2; - - } else if (actualPosition <= 0) { - // Put the new point at the beginning - System.arraycopy(ll, 0, newll, 2, ll.length); - newll[0] = newlat; - newll[1] = newlon; - position = 0; - } else { - // actualPosition because there are 2 floats for every - // position. - newll[actualPosition] = newlat; - newll[actualPosition + 1] = newlon; - System.arraycopy(ll, 0, newll, 0, actualPosition); - System.arraycopy(ll, actualPosition, newll, actualPosition + 2, ll.length - - actualPosition); - } - - poly.setLocation(newll, OMGraphic.RADIANS); - } - } else if (renderType == OMGraphic.RENDERTYPE_XY) { - // Grab the projected endpoints - Debug.message("eomg", "EditableOMPoly: adding point to x/y poly"); - int currentLength = poly.xs.length; - int[] newxs = new int[currentLength + 1]; - int[] newys = new int[currentLength + 1]; - - if (position >= currentLength) { - // Put the new points at the end - System.arraycopy(poly.xs, 0, newxs, 0, currentLength); - System.arraycopy(poly.ys, 0, newys, 0, currentLength); - newxs[currentLength] = x; - newys[currentLength] = y; - - position = currentLength; - - } else if (position <= 0) { - // Put the new points at the beginning - System.arraycopy(poly.xs, 0, newxs, 1, currentLength); - System.arraycopy(poly.ys, 0, newys, 1, currentLength); - newxs[0] = x; - newys[0] = y; - - position = 0; - - } else { - newxs[position] = x; - newys[position] = y; - - System.arraycopy(poly.xs, 0, newxs, 0, position); - System.arraycopy(poly.xs, position, newxs, position + 1, currentLength - position); - - System.arraycopy(poly.ys, 0, newys, 0, position); - System.arraycopy(poly.ys, position, newys, position + 1, currentLength - position); - } - - poly.setLocation(newxs, newys); - - } else { - // Rendertype is offset... - // Grab the projected endpoints - Debug.message("eomg", "EditableOMPoly: adding point to offset poly"); - int currentLength = poly.xs.length; - int[] newxs = new int[currentLength + 1]; - int[] newys = new int[currentLength + 1]; - - if (position >= currentLength) { - // Put the new points at the end - position = currentLength; - - System.arraycopy(poly.xs, 0, newxs, 0, currentLength); - System.arraycopy(poly.ys, 0, newys, 0, currentLength); - - } else if (position <= 0) { - // Put the new points at the beginning - position = 0; - - System.arraycopy(poly.xs, 0, newxs, 1, currentLength); - System.arraycopy(poly.ys, 0, newys, 1, currentLength); - - } else { - - System.arraycopy(poly.xs, 0, newxs, 0, position); - System.arraycopy(poly.xs, position, newxs, position + 1, currentLength - position); - - System.arraycopy(poly.ys, 0, newys, 0, position); - System.arraycopy(poly.ys, position, newys, position + 1, currentLength - position); - } - - int offsetX; - int offsetY; - - if (gpo.getX() == -1 && gpo.getY() == -1) { - offsetX = proj.getWidth() / 2; - offsetY = proj.getHeight() / 2; - } else { - offsetX = gpo.getX(); - offsetY = gpo.getY(); - } - - if (poly.coordMode == OMPoly.COORDMODE_ORIGIN || position == 0) { // cover - // the first point - newxs[position] = x - offsetX; - newys[position] = y - offsetY; - } else { // CMode Previous offset deltas - newxs[position] = x - offsetX - newxs[position - 1]; - newys[position] = y - offsetY - newys[position - 1]; - } - - if (position == 0) { - // Could call projection.getCenter() but that might - // break if/when we make other projection - // libraries/paradigms active. - LatLonPoint llpnt = proj.inverse(offsetX, offsetY, new LatLonPoint.Double()); - - poly.lat = llpnt.getRadLat(); - poly.lon = llpnt.getRadLon(); - } - - poly.setLocation(poly.lat, poly.lon, OMGraphic.RADIANS, newxs, newys); - } - - // Need to reset the arrowhead when an end point is added, - // removing it from the shape when the point gets added. - // Otherwise, you end up with a arrowhead at each junction of - // the polygon. - OMArrowHead omah = poly.getArrowHead(); - poly.setArrowHead(null); - - // Reset the arrowhead so it will get drawn on the new - // segment. - poly.setArrowHead(omah); - polyGrabPoints.add(position, gp); - - if (gpo != null) { - gpo.addGrabPoint(gp); - } - - // This is the standard call that needs to be made here, the - // arrowhead changes are around this. - poly.regenerate(proj); - gp.generate(proj); - - return position; - } - - /** - * Delete a point off the end of the polyline/polygon. - */ - public void deletePoint() { - deletePoint(Integer.MAX_VALUE); - } - - /** - * Delete a point at a certain point in the polygon coordinate list. If the - * position is less than zero, the deleted point will be the starting point. - * If the position is greater than the list of current points, the point - * will be deleted from the end of the poly. - */ - public void deletePoint(int position) { - - int renderType = poly.getRenderType(); - Projection proj = getProjection(); - - boolean needToHookUp = false; - if (position <= 0 && isEnclosed()) { - // if the position is 0 and the polygon is enclosed, we - // need to disengage the two points, then reattach. - enclose(false); - needToHookUp = true; - } - - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - Debug.message("eomg", "EditableOMPoly: removing point from lat/lon poly"); - - if (proj != null) { - - double[] ll = poly.getLatLonArray(); - double[] newll = new double[ll.length - 2]; - - int actualPosition = (position == Integer.MAX_VALUE ? ll.length : position * 2); - - if (actualPosition >= ll.length) { - // Pull the new points off the end - System.arraycopy(ll, 0, newll, 0, ll.length - 2); - position = (ll.length - 2) / 2; - } else if (actualPosition <= 0) { - // Pull the new points off the beginning - System.arraycopy(ll, 2, newll, 0, ll.length - 2); - position = 0; - } else { - // actualPosition because there are 2 floats for - // every - // position. - System.arraycopy(ll, 0, newll, 0, actualPosition); - System.arraycopy(ll, actualPosition + 2, newll, actualPosition, ll.length - - actualPosition - 2); - } - poly.setLocation(newll, poly.getUnits()); - } - } else { - // Grab the projected endpoints - Debug.message("eomg", "EditableOMPoly: removing point from x/y or offset poly"); - int currentLength = poly.xs.length; - int[] newxs = new int[currentLength - 1]; - int[] newys = new int[currentLength - 1]; - - if (position >= currentLength) { - // Pull the points from the end... - System.arraycopy(poly.xs, 0, newxs, 0, currentLength - 1); - System.arraycopy(poly.ys, 0, newys, 0, currentLength - 1); - position = currentLength - 1; - } else if (position <= 0) { - // Pull the points from the beginning... - System.arraycopy(poly.xs, 1, newxs, 0, currentLength - 1); - System.arraycopy(poly.ys, 1, newys, 0, currentLength - 1); - position = 0; - } else { - - System.arraycopy(poly.xs, 0, newxs, 0, position); - System.arraycopy(poly.xs, position + 1, newxs, position, currentLength - position - - 1); - - System.arraycopy(poly.ys, 0, newys, 0, position); - System.arraycopy(poly.ys, position + 1, newys, position, currentLength - position - - 1); - - } - - if (poly.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - poly.setLocation(poly.lat, poly.lon, poly.getUnits(), newxs, newys); - } else { - poly.setLocation(newxs, newys); - } - } - - if (proj != null) { - poly.regenerate(proj); - } - - // Remove the GrabPoint for the deleted spot. - GrabPoint gp = polyGrabPoints.remove(position); - if (gpo != null && gp != null) { - gpo.removeGrabPoint(gp); - } - - if (needToHookUp) { - enclose(true); - } - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(MouseEvent e) { - // Need to check to see if the OffsetGrabPoint is currently - // being used. If not, just use it, otherwise, will need to - // create a special one for the move. - - Point2D pnt = getProjectionPoint(e); - int x = (int) pnt.getX(); - int y = (int) pnt.getY(); - - if (poly.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - gpm = new OffsetGrabPoint(x, y); - gpm.clear(); - } else { - gpm = gpo; - gpm.clear(); - gpm.set(x, y); - } - - // Move all the other points along with the offset point... - addPolyGrabPointsToOGP(gpm); - - movingPoint = gpm; - } - - /** - * This method adds all the GrabPoints associated with the polygon nodes and - * adds them to the offset GrabPoint representing the lat/lon anchor point. - */ - protected void addPolyGrabPointsToOGP(OffsetGrabPoint ogp) { - - if (ogp == null) - return; - - // Reset the points to the offset point. - for (GrabPoint gb : polyGrabPoints) { - if (gb != null) { - ogp.addGrabPoint(gb); - } - } - - ogp.updateOffsets(); - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomg", "EditableOMPoly.generate()"); - if (poly != null) { - poly.generate(proj); - } - generateGrabPoints(proj); - return true; - } - - /** - * Generate the grab points, checking the OMGraphic to see if it contains - * information about what the grab points should look like. - * - * @param proj - */ - protected void generateGrabPoints(Projection proj) { - - DrawingAttributes grabPointDA = null; - Object obj = poly.getAttribute(EditableOMGraphic.GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE); - if (obj instanceof DrawingAttributes) { - grabPointDA = (DrawingAttributes) obj; - } - - int index = 0; - // Generate all the grab points, but also check to make sure the drawing - // attributes are right - for (GrabPoint gb : polyGrabPoints) { - if (gb != null) { - - if (selectNodeIndex == index) { - Object daobj = poly.getAttribute(EditableOMGraphic.SELECTED_GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE); - if (daobj instanceof DrawingAttributes) { - ((DrawingAttributes) daobj).setTo(gb); - } - } else if (grabPointDA != null) { - grabPointDA.setTo(gb); - } else { - gb.setDefaultDrawingAttributes(GrabPoint.DEFAULT_RADIUS); - } - - gb.generate(proj); - } - - index++; - } - - if (gpo != null) { - - if (grabPointDA != null) { - grabPointDA.setTo(gpo); - } else { - gpo.setDefaultDrawingAttributes(GrabPoint.DEFAULT_RADIUS); - } - - gpo.generate(proj); - gpo.updateOffsets(); - } - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMPoly.regenerate()"); - if (poly != null) { - poly.generate(proj); - setGrabPoints(poly); - } - - generateGrabPoints(proj); - } - - /** - * Draw the EditableOMPoly parts into the java.awt.Graphics object. The grab - * points are only rendered if the poly machine state is - * PolySelectedState.POLY_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomg", "EditableOMPoly.render()"); - - State state = getStateMachine().getState(); - - if (poly != null && !(state instanceof PolyUndefinedState)) { - poly.setVisible(true); - poly.render(graphics); - poly.setVisible(false); - } else { - Debug.message("eomg", "EditableOMPoly.render: null or undefined poly."); - return; - } - - // Render the points actually on the polygon - if (state instanceof GraphicSelectedState || state instanceof PolyAddNodeState - || state instanceof PolyDeleteNodeState) { - for (GrabPoint gb : polyGrabPoints) { - if (gb != null) { - gb.setVisible(true); - gb.render(graphics); - gb.setVisible(false); - } - } - } - - // In certain conditions, render the offset grab point. - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState /* - * || - * state - * instanceof - * PolySetOffsetState - */) { - if (gpo != null && poly.getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - gpo.setVisible(true); - gpo.render(graphics); - gpo.setVisible(false); - } - } - } - - // ///////////// Special Grab Point functions - // ///////////////////// - // Since the GrabPoints only refer to the points actually on the - // polygon, we have to make sure that the generic - // EditableOMGraphic grab point methods handle that. The - // OffsetGrabPointIndex is -1, so we have to look out for that and - // use the gpo when appropriate. - // ///////////////////////////////////////////////////////////////// - - /** - * Set the grab point objects within the EditableOMGraphic array. For the - * EditableOMPoly, with its variable number of GrabPoints, this just sets up - * a new list of all the grab points to look at. It's different than the - * polyGrabPoints, which are the grab points just on the polygon. This list - * includes the offset grab point. This method should be called when a new - * point gets added to the polygon, and should take an array of all the - * GrabPoints created. It will add the offsetGrabPoint to the end of the - * array. - * - * @param points a GrabPoint[] for the points on the polygon. - * @return true if the grab point array was exactly what the - * EditableOMGraphic was expecting, in terms of length of the - * GrabPoint array length. The method copies the array values that - * fit into the resident array. - */ - public boolean setGrabPoints(GrabPoint[] points) { - gPoints = new GrabPoint[points.length + 1]; - System.arraycopy(gPoints, 0, points, 0, points.length); - gPoints[points.length] = gpo; - - return true; - } - - /** - * Flag to keep track of when the grab point array has been rebuilt in - * setGrabPoints(). - */ - boolean arrayCleared = true; - - /** - * Get the array of grab points used for the EditableOMGraphic. Creates the - * array by copying all the grab points out of the List, and tacking - * the offset grab point to the end. - */ - public GrabPoint[] getGrabPoints() { - - int size = polyGrabPoints.size(); - - // The second half of the test is the fix to the bug that caused - // OMEditablePolys to be unresponsive when the colors changed. Thanks, - // Stephane! - // if (gPoints.length != size + 1 - // || ((size > 0) && (!gPoints[0].equals(polyGrabPoints.get(0))))) { - - if (gPoints.length != size + 1 || arrayCleared) { - arrayCleared = false; - Debug.message("eomg", "EditableOMPoly.getGrabPoints(): recreating grab points"); - gPoints = new GrabPoint[size + 1]; - int counter = 0; - for (GrabPoint gb : polyGrabPoints) { - gPoints[counter++] = gb; - } - gPoints[counter] = gpo; - } - - return gPoints; - } - - /** - * Set the GrabPoint at a particule index of the array. This can be used to - * tie two different grab points together. This used to work with the - * gPoints array declared in EditableOMGraphic - no longer. If the index is - * -1, the offset grab point is set, and any other index refers to the - * concurrent polygon point. - * - * @param gb GrabPoint to assign within array. - * @param index the index of the array to put the GrabPoint. This index - * should be -1 for the offset grab point, or the index of the corner - * of the poly, in order starting from 0. - * @return If the grab point or array is null, or if the index is outside - * the range of the array, false is returned. If everything goes OK, - * then true is returned. - */ - public boolean setGrabPoint(GrabPoint gb, int index) { - // We might have to take care of the offset grab point - // connections here... - - if (index == OFFSET_POINT_INDEX) { - gpo = (OffsetGrabPoint) gb; - return true; - } else { - return super.setGrabPoint(gb, index); - } - } - - /** - * Given a grab point, return its index into the polygon array. If its not - * in the array, the next available index is returned. - */ - public int whichGrabPoint(GrabPoint gp) { - GrabPoint[] points = getGrabPoints(); - for (int i = 0; i < points.length; i++) { - if (gp == points[i]) { - if (gp == gpo) { - return OFFSET_POINT_INDEX; - } else { - return i; - } - } - } - return points.length; - } - - /** - * Return a particular GrabPoint at a particular point in the array. The - * EditableOMGraphic should describe which indexes refer to which grab - * points in the EOMG GrabPoint array. If the index is OFFSET_POINT_INDEX, - * the offset point is returned. If the index is otherwise outside the range - * of the array, null is returned. - */ - public GrabPoint getGrabPoint(int index) { - if (index == OFFSET_POINT_INDEX) { - return gpo; - } else { - return super.getGrabPoint(index); - } - } - - /** - * Adds widgets to modify polygon. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return Component to use to control parameters for this EOMG. - */ - public Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMPoly.getGUI"); - if (graphicAttributes != null) { - JMenu ahm = getArrowHeadMenu(); - graphicAttributes.setLineMenuAdditions(new JMenu[] { ahm }); - // JComponent gaGUI = (JComponent) graphicAttributes.getGUI(); - JComponent toolbar = createAttributePanel(graphicAttributes); - getPolyGUI(graphicAttributes.getOrientation(), toolbar); - return toolbar; - } else { - return getPolyGUI(); - } - } - - JToggleButton polygonButton = null; - JButton extButton = null; - JButton addButton = null; - JButton deleteButton = null; - - public void enablePolygonButton(boolean enable) { - if (polygonButton != null) { - polygonButton.setEnabled(enable); - } - } - - public void enablePolygonEditButtons(boolean enable) { - if (extButton != null) { - extButton.setEnabled(enable); - } - if (addButton != null) { - addButton.setEnabled(enable); - } - if (deleteButton != null) { - deleteButton.setEnabled(enable); - } - } - - public JComponent getPolyGUI() { - return getPolyGUI(true, true, true, true, SwingConstants.HORIZONTAL); - } - - public JComponent getPolyGUI(int orientation, JComponent toolbar) { - return getPolyGUI(true, true, true, true, orientation, toolbar); - } - - public JComponent getPolyGUI(boolean includeEnclose, boolean includeExt, boolean includeAdd, - boolean includeDelete, int orientation) { - return getPolyGUI(includeEnclose, includeExt, includeAdd, includeDelete, orientation, null); - } - - public JComponent getPolyGUI(boolean includeEnclose, boolean includeExt, boolean includeAdd, - boolean includeDelete, int orientation, JComponent buttonBox) { - - if (buttonBox == null) { - buttonBox = new GridBagToolBar(); - ((GridBagToolBar) buttonBox).setOrientation(orientation); - } - - buttonBox.add(PaletteHelper.getToolBarFill(orientation)); - - URL url; - ImageIcon imageIcon; - if (polygonButton == null) { - url = getImageURL("enclosepoly.gif"); - imageIcon = new ImageIcon(url); - polygonButton = new JToggleButton(imageIcon); - polygonButton.setToolTipText(i18n.get(EditableOMPoly.class, "polygonButton.tooltip", "Automatically link first and last nodes")); - - polygonButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (getStateMachine().getState() instanceof GraphicSelectedState) { - enclose(((JToggleButton) e.getSource()).isSelected()); - } else { - setEnclosed(((JToggleButton) e.getSource()).isSelected()); - } - updateCurrentState(null); - } - }); - } - - polygonButton.setSelected(isEnclosed()); - - if (includeEnclose) { - buttonBox.add(polygonButton); - } - - if (extButton == null) { - url = getImageURL("addpoint.gif"); - imageIcon = new ImageIcon(url); - extButton = new JButton(imageIcon); - extButton.setToolTipText(i18n.get(EditableOMPoly.class, "extButton.tooltip", "Add a point to the polygon")); - extButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - // If an enclosed poly is having nodes added to it, we need - // to - // remove the connection, but make a note to reconnect after - // editing. - if (isEnclosed()) { - enclose(false); - setEnclosed(true); - } - ((PolyStateMachine) stateMachine).setAddPoint(); - enablePolygonEditButtons(false); - } - }); - } - - extButton.setEnabled(false); - if (includeExt) { - buttonBox.add(extButton); - } - - if (addButton == null) { - url = getImageURL("addnode.gif"); - imageIcon = new ImageIcon(url); - addButton = new JButton(imageIcon); - addButton.setToolTipText(i18n.get(EditableOMPoly.class, "addButton.tooltip", "Add a node to the polygon")); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - ((PolyStateMachine) stateMachine).setAddNode(); - enablePolygonEditButtons(false); - } - }); - } - - addButton.setEnabled(false); - if (includeAdd) { - buttonBox.add(addButton); - } - - if (deleteButton == null) { - url = getImageURL("deletepoint.gif"); - imageIcon = new ImageIcon(url); - deleteButton = new JButton(imageIcon); - deleteButton.setToolTipText(i18n.get(EditableOMPoly.class, "deleteButton.tooltip", "Delete a node from the polygon")); - deleteButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - ((PolyStateMachine) stateMachine).setDeleteNode(); - enablePolygonEditButtons(false); - } - }); - } - - deleteButton.setEnabled(false); - if (includeDelete) { - buttonBox.add(deleteButton); - } - - return buttonBox; - } - - public java.net.URL getImageURL(String imageName) { - return EditableOMPoly.class.getResource(imageName); - } - - /** - * @return the selectNodeIndex - */ - public int getSelectNodeIndex() { - return selectNodeIndex; - } - - /** - * @param selectNodeIndex the selectNodeIndex to set - */ - public void setSelectNodeIndex(int selectNodeIndex) { - this.selectNodeIndex = selectNodeIndex; - } - - /** - * Make sure no node is highlighted. - */ - public void clearSelectedNode() { - this.selectNodeIndex = -1; - } - - /** - * Create an UndoEvent that can get an OMPoly back to what it looks like - * right now. - */ - protected UndoEvent createUndoEventForCurrentState(String whatHappened) { - if (whatHappened == null) { - whatHappened = i18n.get(this.getClass(), "polygonUndoString", "Edit"); - } - return new OMPolyUndoEvent(this, whatHappened); - } - - /** - * Subclass for undoing edits for OMPoly classes, handles enclose/unenclose - * events. - * - * @author ddietrick - */ - public static class OMPolyUndoEvent extends OMGraphicUndoEvent implements UndoEvent { - - protected boolean enclosed = false; - - public OMPolyUndoEvent(EditableOMPoly eomp, String description) { - super(eomp, description); - enclosed = eomp.manualEnclosed; - } - - protected void setSubclassState() { - ((EditableOMPoly) eomg).polygonButton.setSelected(enclosed); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRangeRings.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRangeRings.java deleted file mode 100755 index 163dd21a2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRangeRings.java +++ /dev/null @@ -1,496 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMRangeRings.java,v $ -// $RCSfile: EditableOMRangeRings.java,v $ -// $Revision: 1.15 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.text.DecimalFormat; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToolBar; -import javax.swing.SwingConstants; -import javax.swing.border.EmptyBorder; - -import com.bbn.openmap.event.UndoEvent; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; - -/** - */ -public class EditableOMRangeRings extends EditableOMCircle { - - // TODO need to update the memory mechanism between OMRangeRings that are - // being edited/created so that statics aren't being used. The only other - // place this info could be held is either in the drawing tool or in the - // OMRangeRingsLoader (OMCircleLoader), and I don't think we have a handle - // to - // either of them from here. Gah! I hate using statics, they make me feel - // dirty. - protected static int lastInterval; - protected static Length lastUnit; - protected static boolean snapToInterval = false; - - /** - * Create the EditableOMRangeRings, setting the state machine to create the - * circle off of the gestures. - */ - public EditableOMRangeRings() { - createGraphic(null); - } - - /** - * Create an EditableOMRangeRings with the circleType and renderType - * parameters in the GraphicAttributes object. - */ - public EditableOMRangeRings(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMRangeRings with an OMCircle already defined, ready - * for editing. - * - * @param omc OMCircle that should be edited. - */ - public EditableOMRangeRings(OMRangeRings omc) { - setGraphic(omc); - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of circle to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_LATLON; - - if (ga != null) { - renderType = ga.getRenderType(); - } - - if (Debug.debugging("eomc")) { - Debug.output("EditableOMRangeRings.createGraphic(): rendertype = " + renderType); - } - - circle = new OMRangeRings(90f, -180f, 0f); - - if (ga != null) { - ga.setTo(circle, true); - } - } - - /** - * Modifies the gui to not include line type adjustments, and adds widgets - * to control range ring settings. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return java.awt.Component to use to control parameters for this EOMG. - */ - public Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMRangeRings.getGUI"); - if (graphicAttributes != null) { - // JComponent panel = graphicAttributes.getColorAndLineGUI(); - JComponent toolbar = createAttributePanel(graphicAttributes); - // panel.add(getRangeRingGUI()); - getRangeRingGUI(graphicAttributes.getOrientation(), toolbar); - return toolbar; - } else { - return getRangeRingGUI(); - } - } - - public void updateInterval(int val) { - int oldInterval = ((OMRangeRings) circle).getInterval(); - ((OMRangeRings) circle).setInterval(val); - lastInterval = val; - if (intervalField != null) { - intervalField.setText(Integer.toString(val)); - } - - if (snapToInterval) { - setRadius(circle.getRadius()); - } - if (oldInterval != val) { - updateCurrentState(null); - } - redraw(null, true); - } - - public void updateInterval(String intervalStr) { - int oldValue = ((OMRangeRings) circle).getInterval(); - int value = interpretValue(intervalStr); - - if (value <= 0) { - value = oldValue; - } - - updateInterval(value); - } - - public int interpretValue(String intervalStr) { - int value = -1; - try { - if (intervalStr.toLowerCase().endsWith("m")) { - intervalStr = intervalStr.substring(0, intervalStr.length() - 1); - value = (int) df.parse(intervalStr).intValue() * 1000000; - } else if (intervalStr.toLowerCase().endsWith("k")) { - intervalStr = intervalStr.substring(0, intervalStr.length() - 1); - value = df.parse(intervalStr).intValue() * 1000; - } else if (intervalStr.trim().length() == 0) { - // do nothing - } else { - value = df.parse(intervalStr).intValue(); - } - } catch (java.text.ParseException e) { - Debug.error("RangeRing interval value not valid: " + intervalStr); - } catch (NumberFormatException e) { - Debug.error("RangeRing interval value not valid: " + intervalStr); - } - return value; - } - - // Need these three for UndoEvents to be able to update them if an update - // event gets implemented. - protected JTextField intervalField = null; - protected JComboBox unitsCombo = null; - protected JCheckBox snapCheckBox = null; - - protected JToolBar rrToolBar = null; - protected transient DecimalFormat df = new DecimalFormat(); - protected JComponent attributeBox; - - protected JComponent getRangeRingGUI() { - return getRangeRingGUI(SwingConstants.HORIZONTAL, (JComponent) null); - } - - /** - * Get the GUI associated with changing the Text. - * - * @param orientation SwingConstants.HORIZONTAL/VERTICAL - * @param guiComp the JComponent to add stuff to. If the orientation is - * HORIZONTAL, the components will be added directly to this - * component, or to a new JComponent that is returned if null. If the - * orientation is Vertical, a button will be added to the guiComp, or - * returned. This button will call up a dialog box with the settings, - * since they don't really lay out vertically. - * @return JComponent for controlling range-ring specific attributes. - */ - protected JComponent getRangeRingGUI(int orientation, JComponent guiComp) { - attributeBox = null; - - if (guiComp == null || orientation == SwingConstants.VERTICAL) { - attributeBox = javax.swing.Box.createHorizontalBox(); - - attributeBox.setAlignmentX(Component.CENTER_ALIGNMENT); - attributeBox.setAlignmentY(Component.CENTER_ALIGNMENT); - - if (orientation == SwingConstants.HORIZONTAL) { - guiComp = attributeBox; - } - } else if (orientation == SwingConstants.HORIZONTAL) { - attributeBox = guiComp; - } - - if (guiComp == null) { - guiComp = new JPanel(); - } - - guiComp.add(PaletteHelper.getToolBarFill(orientation)); - - if (orientation == SwingConstants.VERTICAL) { - JButton launchButton = new JButton("RR"); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (attributeBox != null) { - JDialog dialog = new JDialog(); - dialog.setContentPane(attributeBox); - dialog.setModal(true); - dialog.pack(); - dialog.setLocationRelativeTo((JButton) ae.getSource()); - dialog.setVisible(true); - } - } - }); - guiComp.add(launchButton); - } - - configureRangeRings(); - intervalField = makeIntervalField(); - attributeBox.add(intervalField); - - unitsCombo = makeUnitsCombo(); - attributeBox.add(unitsCombo); - snapCheckBox = makeSnapCheckBox(); - attributeBox.add(snapCheckBox); - - return guiComp; - } - - private void configureRangeRings() { - ((OMRangeRings) circle).setInterval(getInterval()); - ((OMRangeRings) circle).setIntervalUnits(getUnits()); - } - - private int getInterval() { - return (!isNewRing()) ? ((OMRangeRings) circle).getInterval() - : haveUserSpecifiedValue() ? lastInterval : OMRangeRings.DEFAULT_INTERVAL; - } - - private Length getUnits() { - return (!isNewRing()) ? ((OMRangeRings) circle).getIntervalUnits() - : haveUserSpecifiedValue() ? lastUnit : null; - } - - private boolean isNewRing() { - // we rely on interval units not being initialized during construction - return (((OMRangeRings) circle).getIntervalUnits() == null); - } - - private boolean haveUserSpecifiedValue() { - // lastUnit is not null if the user made a selection with the comboBox - return (lastUnit != null); - } - - private JTextField makeIntervalField() { - JTextField field = new JTextField(Integer.toString(((OMRangeRings) circle).getInterval()), 5); - field.setMargin(new Insets(0, 1, 0, 1)); - // without minimum size set, field can be too small to use - field.setMinimumSize(new Dimension(40, 18)); - field.setHorizontalAlignment(JTextField.RIGHT); - field.setToolTipText(i18n.get(this, "intervalField.tooltip", "Value for interval between rings.")); - field.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - updateInterval(((JTextField) (ae.getSource())).getText()); - } - }); - // Users forget to hit Enter, which is required for an action event, - // then wonder why the rings they draw don't have the desired value. - // Adding a focus listener addresses this issue. - field.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent event) { - if (!event.isTemporary()) { - updateInterval(((JTextField) (event.getSource())).getText()); - } - } - }); - return field; - } - - private JComboBox makeUnitsCombo() { - Length[] available = Length.values(); - String[] unitStrings = new String[available.length + 1]; - - String current = null; - Length l = ((OMRangeRings) circle).getIntervalUnits(); - if (l != null) { - current = l.toString(); - } - - int currentIndex = unitStrings.length - 1; - - for (int i = 0; i < available.length; i++) { - unitStrings[i] = available[i].toString(); - if (unitStrings[i] != null && unitStrings[i].equals(current)) { - currentIndex = i; - } - } - unitStrings[unitStrings.length - 1] = i18n.get(this, "unitStrings.concentric", "concentric"); - - JComboBox combo = new JComboBox(unitStrings); - combo.setBorder(new EmptyBorder(0, 1, 0, 1)); - combo.setSelectedIndex(currentIndex); - combo.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - OMRangeRings rr = (OMRangeRings) circle; - Length newLength = Length.get((String) jcb.getSelectedItem()); - Length oldLength = rr.getIntervalUnits(); - - /* - * If newLength is not null and oldLength is not null, just - * translate the distance that is current specified. If - * newLength is null, then find out how many rings are on the - * range ring and set the interval to that. If oldLength is - * null, find out the radius and divide it by the number of - * rings - 1. - */ - - int value = interpretValue(intervalField.getText()); - if (value <= 0) { - value = 4; - } - - if (newLength != null && oldLength != null) { - value = (int) newLength.fromRadians(oldLength.toRadians(value)); - } else { - int numSubCircles; - if (rr.subCircles == null || rr.subCircles.length == 0) { - numSubCircles = 1; - } else { - numSubCircles = rr.subCircles.length; - } - - if (newLength == null) { - value = numSubCircles; - } else if (oldLength == null) { - value = (int) Math.ceil(newLength.fromRadians(Length.DECIMAL_DEGREE.toRadians(rr.getRadius())) - / numSubCircles); - } - } - - ((OMRangeRings) circle).setIntervalUnits(newLength); - lastUnit = newLength; - updateInterval(value); - } - }); - return combo; - } - - private JCheckBox makeSnapCheckBox() { - String snapText = i18n.get(this, "snapToInterval", "Snap"); - JCheckBox snapBox = new JCheckBox(snapText, isSnapToInterval()); - snapText = i18n.get(this, "snapToInterval", I18n.TOOLTIP, "Round radius to nearest interval value."); - snapBox.setToolTipText(snapText); - snapBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setSnapToInterval(((JCheckBox) ae.getSource()).isSelected()); - if (snapToInterval) { - setRadius(circle.getRadius()); - } - updateCurrentState(null); - redraw(null, true); - } - }); - return snapBox; - } - - protected boolean drawLabelsHolder = true; - - /** - * A convenience method that gives an EditableOMGraphic a chance to modify - * the OMGraphic so it can be drawn quickly, by turning off labels, etc, - * right before the XORpainting happens. The OMGraphic should be configured - * so that the render method does the least amount of painting possible. - * Note that the DrawingAttributes for the OMGraphic have already been set - * to DrawingAttributes.DEFAULT (black line, clear fill). - */ - protected void modifyOMGraphicForEditRender() { - OMRangeRings omrr = (OMRangeRings) getGraphic(); - drawLabelsHolder = omrr.getDrawLabels(); - omrr.setDrawLabels(false); - } - - /** - * A convenience method that gives an EditableOMGraphic a chance to reset - * the OMGraphic so it can be rendered normally, after it has been modified - * for quick paints. The DrawingAttributes for the OMGraphic have already - * been reset to their normal settings, from the DrawingAttributes.DEFAULT - * settings that were used for the quick paint. - */ - protected void resetOMGraphicAfterEditRender() { - ((OMRangeRings) getGraphic()).setDrawLabels(drawLabelsHolder); - } - - public boolean isSnapToInterval() { - return snapToInterval; - } - - public void setSnapToInterval(boolean sti) { - snapToInterval = sti; - } - - protected void setRadius(double radius) { - if (circle != null) { - if (snapToInterval) { - OMRangeRings rr = (OMRangeRings) circle; - Length units = rr.getIntervalUnits(); - if (units != null) { - double rds = units.fromRadians(Length.DECIMAL_DEGREE.toRadians(radius)); - radius = Math.round(rds / rr.getInterval()) * rr.getInterval(); - radius = Length.DECIMAL_DEGREE.fromRadians(units.toRadians(radius)); - } - } - circle.setRadius(radius); - } - } - - /** - * Create an UndoEvent that can get an OMRangeRing back to what it looks - * like right now. - */ - protected UndoEvent createUndoEventForCurrentState(String whatHappened) { - if (whatHappened == null) { - whatHappened = i18n.get(this.getClass(), "rangeRingUndoString", "Edit"); - } - return new OMRangeRingUndoEvent(this, whatHappened); - } - - /** - * Subclass for undoing edits for OMRangeRing classes, handles events that - * may affect the extra GUI widgets. - * - * @author ddietrick - */ - public static class OMRangeRingUndoEvent extends OMGraphicUndoEvent implements UndoEvent { - - boolean snap; - - public OMRangeRingUndoEvent(EditableOMRangeRings eomp, String description) { - super(eomp, description); - snap = eomp.isSnapToInterval(); - } - - protected void setSubclassState() { - OMRangeRings rrStateHolder = (OMRangeRings) stateHolder; - EditableOMRangeRings eomrr = (EditableOMRangeRings) eomg; - if (eomrr.snapCheckBox != null) { - eomrr.snapCheckBox.setSelected(snap); - eomrr.setSnapToInterval(snap); - } - - if (eomrr.intervalField != null) { - eomrr.intervalField.setText(Integer.toString(rrStateHolder.getInterval())); - } - - Length intervalUnits = rrStateHolder.getIntervalUnits(); - if (eomrr.unitsCombo != null && intervalUnits != null) { - eomrr.unitsCombo.setSelectedItem(intervalUnits.toString()); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRect.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRect.java deleted file mode 100644 index 7dca73e0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMRect.java +++ /dev/null @@ -1,595 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMRect.java,v $ -// $RCSfile: EditableOMRect.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.GraphicSetOffsetState; -import com.bbn.openmap.omGraphics.editable.RectStateMachine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The EditableOMRect encompasses an OMRect, providing methods for modifying or - * creating it. This class only modifies rects in lat/lon space - * (RENDERTYPE_LATLON) - and ellipses in screen space (RENDERTYPE_XY or - * RENDERTYPE_OFFSET). When you grab at the rect, you change the radius of the - * entire rect. Grabbing the center point moves the rect. If there is an offset - * point, moving the center point changes the rect's position in relation to the - * offset point. Moving the offset point moves the rect, keeping the distance to - * the center point constant. - */ -public class EditableOMRect extends EditableOMGraphic { - - protected GrabPoint gpnw; - protected GrabPoint gpne; - protected GrabPoint gpsw; - protected GrabPoint gpse; - protected OffsetGrabPoint gpc; - protected OffsetGrabPoint gpo; // offset - - protected OMRect rect; - - public final static String OffsetResetCmd = "OffsetResetCmd"; - public final static int CENTER_POINT_INDEX = 0; - public final static int NW_POINT_INDEX = 1; - public final static int NE_POINT_INDEX = 2; - public final static int SW_POINT_INDEX = 3; - public final static int SE_POINT_INDEX = 4; - public final static int OFFSET_POINT_INDEX = 5; - - /** - * Create the EditableOMRect, setting the state machine to create the rect - * off of the gestures. - */ - public EditableOMRect() { - createGraphic(null); - } - - /** - * Create an EditableOMRect with the rectType and renderType parameters in - * the GraphicAttributes object. - */ - public EditableOMRect(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMRect with an OMRect already defined, ready for - * editing. - * - * @param omc OMRect that should be edited. - */ - public EditableOMRect(OMRect omc) { - setGraphic(omc); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMRect. - */ - public void init() { - Debug.message("eomg", "EditableOMRect.init()"); - setCanGrabGraphic(false); - setStateMachine(new RectStateMachine(this)); - gPoints = new GrabPoint[6]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMRect) { - rect = (OMRect) graphic; - stateMachine.setSelected(); - setGrabPoints(rect); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of rect to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - int lineType = OMGraphic.LINETYPE_GREATCIRCLE; - - if (ga != null) { - renderType = ga.getRenderType(); - lineType = ga.getLineType(); - } - - if (Debug.debugging("eomg")) { - Debug.output("EditableOMRect.createGraphic(): rendertype = " + renderType); - Debug.output("EditableOMRect.createGraphic(): linetype = " + lineType); - } - - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - if (lineType == OMGraphic.LINETYPE_UNKNOWN) { - lineType = OMGraphic.LINETYPE_GREATCIRCLE; - if (ga != null) { - ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - } - } - - rect = new OMRect(90f, -180f, 90f, -180f, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - rect = new OMRect(90d, -180d, -1, -1, 1, 1); - break; - default: - rect = new OMRect(-1, -1, -1, -1); - } - - if (ga != null) { - ga.setTo(rect, true); - } - - assertGrabPoints(); - } - - /** - * Get the OMGraphic being created/modified by the EditableOMRect. - */ - public OMGraphic getGraphic() { - return rect; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - // public void setMovingPoint(GrabPoint gp) { - // super.setMovingPoint(gp); - // } - - double diffx; - double diffy; - - // Called from the state machine... - public void initRectSize() { - diffx = Math.abs(rect.getEastLon() - rect.getWestLon()) / 2f; - diffy = Math.abs(rect.getNorthLat() - rect.getSouthLat()) / 2f; - // Debug.output("initRectSize(): diffx:" + diffx + ", diffy:" - // + diffy); - } - - protected int lastRenderType = -1; - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - int rt = getGraphic().getRenderType(); - if (rt != lastRenderType) { - clearGrabPoints(); - lastRenderType = rt; - } - - if (gpnw == null) { - gpnw = new GrabPoint(-1, -1); - gPoints[NW_POINT_INDEX] = gpnw; - // gpnw.setFillPaint(Color.yellow); - } - if (gpne == null) { - gpne = new GrabPoint(-1, -1); - gPoints[NE_POINT_INDEX] = gpne; - // gpne.setFillPaint(Color.blue); - } - if (gpsw == null) { - gpsw = new GrabPoint(-1, -1); - gPoints[SW_POINT_INDEX] = gpsw; - // gpsw.setFillPaint(Color.green); - } - if (gpse == null) { - gpse = new GrabPoint(-1, -1); - gPoints[SE_POINT_INDEX] = gpse; - // gpse.setFillPaint(Color.orange); - } - - if (gpc == null) { - gpc = new OffsetGrabPoint(-1, -1); - // gpc.setFillPaint(Color.red); - gPoints[CENTER_POINT_INDEX] = gpc; - if (getGraphic().getRenderType() != OMGraphic.RENDERTYPE_LATLON) { - gpc.addGrabPoint(gpnw); - gpc.addGrabPoint(gpne); - gpc.addGrabPoint(gpsw); - gpc.addGrabPoint(gpse); - } - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gpc); - } - } - - protected void clearGrabPoints() { - - gpc = null; - gpnw = null; - gpne = null; - gpsw = null; - gpse = null; - gpo = null; - - gPoints[CENTER_POINT_INDEX] = gpc; - gPoints[NW_POINT_INDEX] = gpnw; - gPoints[NE_POINT_INDEX] = gpne; - gPoints[SW_POINT_INDEX] = gpsw; - gPoints[SE_POINT_INDEX] = gpse; - gPoints[OFFSET_POINT_INDEX] = gpo; - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - Debug.message("eomg", "EditableOMRect.setGrabPoints(graphic)"); - if (!(graphic instanceof OMRect)) { - return; - } - - assertGrabPoints(); - - OMRect rect = (OMRect) graphic; - boolean ntr = rect.getNeedToRegenerate(); - int renderType = rect.getRenderType(); - - int top = 0; - int bottom = 0; - int left = 0; - int right = 0; - LatLonPoint llp; - int latoffset = 0; - int lonoffset = 0; - - boolean doStraight = true; - - if (ntr == false) { - - if (renderType == OMGraphic.RENDERTYPE_LATLON - || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - if (projection != null) { - double wlon = rect.getWestLon(); - double nlat = rect.getNorthLat(); - double elon = rect.getEastLon(); - double slat = rect.getSouthLat(); - - llp = new LatLonPoint.Double(nlat, wlon); - Point2D p = projection.forward(llp); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - doStraight = false; - top = (int) p.getY(); - left = (int) p.getX(); - gpnw.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(slat, elon); - gpse.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(nlat, elon); - gpne.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(slat, wlon); - gpsw.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(nlat - (nlat - slat) / 2f, wlon + (elon - wlon) / 2f); - gpc.set((int) p.getX(), (int) p.getY()); - - } else { - latoffset = (int) p.getY(); - lonoffset = (int) p.getX(); - gpo.set(lonoffset, latoffset); - } - } - } - - if (doStraight) { - - Debug.message("eomg", "EditableOMRect: drawing straight line rectangle"); - - top = (int) (rect.getTop() + latoffset); - bottom = (int) (rect.getBottom() + latoffset); - right = (int) (rect.getRight() + lonoffset); - left = (int) (rect.getLeft() + lonoffset); - - // We have to do some fancy point wrangling to keep - // from messing up the next setGrabPoints(). - if (movingPoint == gpc || movingPoint == gpo || movingPoint == null) { - gpne.set(right, top); - gpnw.set(left, top); - gpse.set(right, bottom); - gpsw.set(left, bottom); - } else if (movingPoint == gpnw) { - gpne.set(gpse.getX(), gpnw.getY()); - gpsw.set(gpnw.getX(), gpse.getY()); - } else if (movingPoint == gpse) { - gpne.set(gpse.getX(), gpnw.getY()); - gpsw.set(gpnw.getX(), gpse.getY()); - } else if (movingPoint == gpsw) { - gpnw.set(gpsw.getX(), gpne.getY()); - gpse.set(gpne.getX(), gpsw.getY()); - } else if (movingPoint == gpne) { - gpnw.set(gpsw.getX(), gpne.getY()); - gpse.set(gpne.getX(), gpsw.getY()); - } - - int middlex = (right - left) / 2; - int middley = (bottom - top) / 2; - gpc.set(left + middlex, top + middley); - gpc.updateOffsets(); - // Debug.output("Center setting x: " + gpc.getX() + ", - // y:" + gpc.getY()); - } - - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - gpo.updateOffsets(); - } - - } else { - Debug.message("eomg", "EditableOMRect.setGrabPoints: graphic needs to be regenerated"); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMRect with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = rect.getRenderType(); - LatLonPoint llp1; - - Debug.message("eomg", "EditableOMRect.setGrabPoints()"); - - // Do center point for lat/lon or offset rects - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - - if (projection != null) { - - // Need to figure out which point was moved, and then - // set the upper left and lower right points - // accordingly. - if (movingPoint == gpne) { - llp1 = projection.inverse(gpne.getX(), gpne.getY(), new LatLonPoint.Double()); - rect.lat1 = llp1.getY(); - rect.lon2 = llp1.getX(); - } else if (movingPoint == gpnw) { - llp1 = projection.inverse(gpnw.getX(), gpnw.getY(), new LatLonPoint.Double()); - rect.lat1 = llp1.getY(); - rect.lon1 = llp1.getX(); - } else if (movingPoint == gpsw) { - llp1 = projection.inverse(gpsw.getX(), gpsw.getY(), new LatLonPoint.Double()); - rect.lat2 = llp1.getY(); - rect.lon1 = llp1.getX(); - } else if (movingPoint == gpse) { - llp1 = projection.inverse(gpse.getX(), gpse.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpnw.getX(), gpnw.getY(), new LatLonPoint.Double()); - rect.lat1 = llp2.getY(); - rect.lon1 = llp2.getX(); - rect.lat2 = llp1.getY(); - rect.lon2 = llp1.getX(); - } else { - // movingPoint == gpc - llp1 = projection.inverse(gpc.getX(), gpc.getY(), new LatLonPoint.Double()); - rect.lat1 = llp1.getY() + diffy; - rect.lon1 = llp1.getX() - diffx; - rect.lat2 = llp1.getY() - diffy; - rect.lon2 = llp1.getX() + diffx; - } - rect.setNeedToRegenerate(true); - } - } - - boolean settingOffset = getStateMachine().getState() instanceof GraphicSetOffsetState - && movingPoint == gpo; - - // If the center point is moving, the offset distance changes - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - - llp1 = projection.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - - rect.lat1 = llp1.getY(); - rect.lon1 = llp1.getX(); - - if (settingOffset || movingPoint == gpc) { - int halfheight = (gpse.getY() - gpnw.getY()) / 2; - int halfwidth = (gpse.getX() - gpnw.getX()) / 2; - - // Don't call rect.setLocation because we only want to - // setNeedToRegenerate if !settingOffset. - rect.x1 = gpc.getX() - halfwidth - gpo.getX(); - rect.y1 = gpc.getY() - halfheight - gpo.getY(); - rect.x2 = gpc.getX() + halfwidth - gpo.getX(); - rect.y2 = gpc.getY() + halfheight - gpo.getY(); - } - - if (!settingOffset) { - Debug.message("eomg", "EditableOMRect: updating offset rect"); - if (movingPoint == gpnw || movingPoint == gpse) { - rect.setLocation(gpnw.getX() - gpo.getX(), gpnw.getY() - gpo.getY(), gpse.getX() - - gpo.getX(), gpse.getY() - gpo.getY()); - } else if (movingPoint == gpne || movingPoint == gpsw) { - rect.setLocation((int) (rect.x1 = gpsw.getX() - gpo.getX()), gpne.getY() - - gpo.getY(), gpne.getX() - gpo.getX(), gpsw.getY() - gpo.getY()); - } - rect.setNeedToRegenerate(true); - } - - // Set Location has reset the rendertype, but provides - // the convenience of setting the max and min values - // for us. - rect.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - } - - // Do the rect height and width for XY and OFFSET render - // types. - if (renderType == OMGraphic.RENDERTYPE_XY) { - Debug.message("eomg", "EditableOMRect: updating x/y rect"); - - if (movingPoint == gpc) { - int halfheight = (gpse.getY() - gpnw.getY()) / 2; - int halfwidth = (gpse.getX() - gpnw.getX()) / 2; - rect.setLocation(gpc.getX() - halfwidth, gpc.getY() - halfheight, gpc.getX() - + halfwidth, gpc.getY() + halfheight); - } else if (movingPoint == gpnw || movingPoint == gpse) { - rect.setLocation(gpnw.getX(), gpnw.getY(), gpse.getX(), gpse.getY()); - } else if (movingPoint == gpne || movingPoint == gpsw) { - rect.setLocation(gpsw.getX(), gpne.getY(), gpne.getX(), gpsw.getY()); - } - } - - if (projection != null) { - regenerate(projection); - } - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(java.awt.event.MouseEvent e) { - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomgdetail", "EditableOMRect.generate()"); - if (rect != null) - rect.generate(proj); - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - gp.generate(proj); - } - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMRect.regenerate()"); - if (rect != null) - rect.regenerate(proj); - - setGrabPoints(rect); - generate(proj); - } - - /** - * Draw the EditableOMRect parts into the java.awt.Graphics object. The grab - * points are only rendered if the rect machine state is - * RectSelectedState.RECT_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomgdetail", "EditableOMRect.render()"); - - State state = getStateMachine().getState(); - - if (rect == null) { - Debug.message("eomg", "EditableOMRect.render: null rect."); - return; - } - - rect.setVisible(true); - rect.render(graphics); - rect.setVisible(false); - - int renderType = rect.getRenderType(); - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState) { - - for (int i = 0; i < gPoints.length; i++) { - - GrabPoint gp = gPoints[i]; - if (gp != null) { - if ((i == OFFSET_POINT_INDEX && renderType == OMGraphic.RENDERTYPE_OFFSET && movingPoint == gpo) - || (state instanceof GraphicSelectedState && ((i != OFFSET_POINT_INDEX && renderType != OMGraphic.RENDERTYPE_OFFSET) || (renderType == OMGraphic.RENDERTYPE_OFFSET))) - - ) { - - gp.setVisible(true); - gp.render(graphics); - gp.setVisible(false); - } - } - } - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMScalingRaster.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMScalingRaster.java deleted file mode 100644 index 2949e7409..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMScalingRaster.java +++ /dev/null @@ -1,676 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMScalingRaster.java,v $ -// $RCSfile: EditableOMScalingRaster.java,v $ -// $Revision: 1.13 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; - -import javax.swing.JOptionPane; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.GraphicSetOffsetState; -import com.bbn.openmap.omGraphics.editable.ScalingRasterStateMachine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -/** - * The EditableOMScalingRaster encompasses an OMScalingRaster, providing methods - * for modifying or creating it. This class only modifies OMScaling Rasters in - * lat/lon space (RENDERTYPE_LATLON). When you grab at the raster, you change - * the size of the entire rect. Grabbing the center point moves the raster. If - * there is an offset point, moving the center point changes the rect's position - * in relation to the offset point. Moving the offset point moves the rect, - * keeping the distance to the center point constant. - */ -public class EditableOMScalingRaster extends EditableOMGraphic { - - protected GrabPoint gpnw; - protected GrabPoint gpne; - protected GrabPoint gpsw; - protected GrabPoint gpse; - protected OffsetGrabPoint gpc; - protected OffsetGrabPoint gpo; // offset - - protected OMScalingRaster raster; - - public final static String OffsetResetCmd = "OffsetResetCmd"; - public final static int CENTER_POINT_INDEX = 0; - public final static int NW_POINT_INDEX = 1; - public final static int NE_POINT_INDEX = 2; - public final static int SW_POINT_INDEX = 3; - public final static int SE_POINT_INDEX = 4; - public final static int OFFSET_POINT_INDEX = 5; - - /** - * Create the EditableOMRect, setting the state machine to create the rect - * off of the gestures. - */ - public EditableOMScalingRaster() { - createGraphic(null); - } - - /** - * Create an EditableOMScalingRaster with the rectType and renderType - * parameters in the GraphicAttributes object. - */ - public EditableOMScalingRaster(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMScalingRaster with an OMScalingRaster already - * defined, ready for editing. - * - * @param omsr OMScalingRaster that should be edited. - */ - public EditableOMScalingRaster(OMScalingRaster omsr) { - setGraphic(omsr); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMScalingRaster. - */ - public void init() { - Debug.message("eomg", "EditableOMScalingRaster.init()"); - setCanGrabGraphic(false); - setStateMachine(new ScalingRasterStateMachine(this)); - gPoints = new GrabPoint[6]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMScalingRaster) { - raster = (OMScalingRaster) graphic; - stateMachine.setSelected(); - setGrabPoints(raster); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of rect to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - - String pathToFile = null; - - // / This would be an ideal place to bring up a chooser! - if (!Environment.isApplet()) { - pathToFile = com.bbn.openmap.util.FileUtils.getFilePathToOpenFromUser("Choose Image File for Raster"); - } else { - JOptionPane.showMessageDialog(null, "Can't search for images in an applet!", "Can't Choose Image", JOptionPane.ERROR_MESSAGE); - } - - if (pathToFile == null) - return; - - try { - javax.swing.ImageIcon ii = new javax.swing.ImageIcon(pathToFile); - raster = new OMScalingRaster(90f, -180f, 89f, -179f, ii); - - } catch (IllegalArgumentException iae) { - // Not an image file, punch - Debug.error("EditableOMScalingRaster: " + pathToFile - + " doesn't appear to be an image file"); - raster = new OMScalingRaster(90f, -180f, 89f, -179f, new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)); - } - - if (ga != null) { - ga.setTo(raster, true); - } - - assertGrabPoints(); - } - - /** - * Get the OMGraphic being created/modified by the EditableOMScalingRaster. - */ - public OMGraphic getGraphic() { - return raster; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - // public void setMovingPoint(GrabPoint gp) { - // super.setMovingPoint(gp); - // } - - double diffx; - double diffy; - - // Called from the state machine... - public void initRectSize() { - diffx = Math.abs(raster.getLRLon() - raster.getULLon()) / 2; - diffy = Math.abs(raster.getULLat() - raster.getLRLat()) / 2; - // Debug.output("initRectSize(): diffx:" + diffx + ", diffy:" - // + diffy); - } - - protected int lastRenderType = -1; - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - OMGraphic omg = getGraphic(); - if (omg == null) - return; - - int rt = omg.getRenderType(); - if (rt != lastRenderType) { - clearGrabPoints(); - lastRenderType = rt; - } - - if (gpnw == null) { - gpnw = new GrabPoint(-1, -1); - gPoints[NW_POINT_INDEX] = gpnw; - // gpnw.setFillPaint(Color.yellow); - } - if (gpne == null) { - gpne = new GrabPoint(-1, -1); - gPoints[NE_POINT_INDEX] = gpne; - // gpne.setFillPaint(Color.blue); - } - if (gpsw == null) { - gpsw = new GrabPoint(-1, -1); - gPoints[SW_POINT_INDEX] = gpsw; - // gpsw.setFillPaint(Color.green); - } - if (gpse == null) { - gpse = new GrabPoint(-1, -1); - gPoints[SE_POINT_INDEX] = gpse; - // gpse.setFillPaint(Color.orange); - } - - if (gpc == null) { - gpc = new OffsetGrabPoint(-1, -1); - // gpc.setFillPaint(Color.red); - gPoints[CENTER_POINT_INDEX] = gpc; - if (getGraphic().getRenderType() != OMGraphic.RENDERTYPE_LATLON) { - gpc.addGrabPoint(gpnw); - gpc.addGrabPoint(gpne); - gpc.addGrabPoint(gpsw); - gpc.addGrabPoint(gpse); - } - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gpc); - } - } - - protected void clearGrabPoints() { - - gpc = null; - gpnw = null; - gpne = null; - gpsw = null; - gpse = null; - gpo = null; - - gPoints[CENTER_POINT_INDEX] = gpc; - gPoints[NW_POINT_INDEX] = gpnw; - gPoints[NE_POINT_INDEX] = gpne; - gPoints[SW_POINT_INDEX] = gpsw; - gPoints[SE_POINT_INDEX] = gpse; - gPoints[OFFSET_POINT_INDEX] = gpo; - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - Debug.message("eomg", "EditableOMScalingRaster.setGrabPoints(graphic)"); - if (!(graphic instanceof OMScalingRaster)) { - return; - } - - assertGrabPoints(); - - OMScalingRaster raster = (OMScalingRaster) graphic; - - if (graphic instanceof OMScalingIcon) { - setGrabPointsForOMSI((OMScalingIcon) graphic); - return; - } - - boolean ntr = raster.getNeedToRegenerate(); - int renderType = raster.getRenderType(); - - int top = 0; - int bottom = 0; - int left = 0; - int right = 0; - LatLonPoint llp; - int latoffset = 0; - int lonoffset = 0; - - boolean doStraight = true; - - if (ntr == false) { - - if (renderType == OMGraphic.RENDERTYPE_LATLON - || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - if (projection != null) { - double wlon = raster.getULLon(); - double nlat = raster.getULLat(); - double elon = raster.getLRLon(); - double slat = raster.getLRLat(); - - llp = new LatLonPoint.Double(nlat, wlon); - Point2D p = projection.forward(llp); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - doStraight = false; - top = (int) p.getY(); - left = (int) p.getX(); - gpnw.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(slat, elon); - gpse.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(nlat, elon); - gpne.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(slat, wlon); - gpsw.set((int) p.getX(), (int) p.getY()); - - p = projection.forward(nlat - (nlat - slat) / 2f, wlon + (elon - wlon) / 2f); - gpc.set((int) p.getX(), (int) p.getY()); - - } else { - latoffset = (int) p.getY(); - lonoffset = (int) p.getX(); - gpo.set(lonoffset, latoffset); - } - } - } - - if (doStraight) { - - Debug.message("eomg", "EditableOMScalingRaster: drawing straight line rectangle"); - - top = raster.getY() + latoffset; - bottom = raster.getY() + raster.getHeight() + latoffset; - right = raster.getX() + raster.getWidth() + lonoffset; - left = raster.getX() + lonoffset; - - // We have to do some fancy point wrangling to keep - // from messing up the next setGrabPoints(). - if (movingPoint == gpc || movingPoint == gpo || movingPoint == null) { - gpne.set(right, top); - gpnw.set(left, top); - gpse.set(right, bottom); - gpsw.set(left, bottom); - } else if (movingPoint == gpnw) { - gpne.set(gpse.getX(), gpnw.getY()); - gpsw.set(gpnw.getX(), gpse.getY()); - } else if (movingPoint == gpse) { - gpne.set(gpse.getX(), gpnw.getY()); - gpsw.set(gpnw.getX(), gpse.getY()); - } else if (movingPoint == gpsw) { - gpnw.set(gpsw.getX(), gpne.getY()); - gpse.set(gpne.getX(), gpsw.getY()); - } else if (movingPoint == gpne) { - gpnw.set(gpsw.getX(), gpne.getY()); - gpse.set(gpne.getX(), gpsw.getY()); - } - - int middlex = (right - left) / 2; - int middley = (bottom - top) / 2; - gpc.set(left + middlex, top + middley); - gpc.updateOffsets(); - // Debug.output("Center setting x: " + gpc.getX() + ", - // y:" + gpc.getY()); - } - - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - gpo.updateOffsets(); - } - - } else { - Debug.message("eomg", "EditableOMScalingRaster.setGrabPoints: graphic needs to be regenerated"); - } - } - - /** - * @param icon - */ - protected void setGrabPointsForOMSI(OMScalingIcon icon) { - if (projection != null) { - double lon = icon.getLon(); - double lat = icon.getLat(); - int renderType = icon.getRenderType(); - LatLonPoint llp = new LatLonPoint.Double(lat, lon); - Point2D p = projection.forward(llp); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - gpc.set((int) p.getX(), (int) p.getY()); - } - } - } - - protected void setGrabPointsForOMSI() { - - if (projection != null) { - // movingPoint == gpc - LatLonPoint llp1 = projection.inverse(gpc.getX(), gpc.getY(), new LatLonPoint.Double()); - raster.setLat(llp1.getY()); - raster.setLon(llp1.getX()); - // point.setNeedToRegenerate set - } - - if (projection != null) { - regenerate(projection); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMScalingRaster with them. Called when you want the - * graphic to change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = raster.getRenderType(); - LatLonPoint llp1; - - Debug.message("eomg", "EditableOMScalingRaster.setGrabPoints()"); - - // Do center point for lat/lon or offset rects - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - - if (projection != null) { - if (raster instanceof OMScalingIcon) { - setGrabPointsForOMSI(); - return; - } - - // Need to figure out which point was moved, and then - // set the upper left and lower right points - // accordingly. - if (movingPoint == gpne) { - llp1 = projection.inverse(gpne.getX(), gpne.getY(), new LatLonPoint.Double()); - raster.setULLat(llp1.getY()); - raster.setLRLon(llp1.getX()); - } else if (movingPoint == gpnw) { - llp1 = projection.inverse(gpnw.getX(), gpnw.getY(), new LatLonPoint.Double()); - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - } else if (movingPoint == gpsw) { - llp1 = projection.inverse(gpsw.getX(), gpsw.getY(), new LatLonPoint.Double()); - raster.setLRLat(llp1.getY()); - raster.setULLon(llp1.getX()); - } else if (movingPoint == gpse) { - llp1 = projection.inverse(gpse.getX(), gpse.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpnw.getX(), gpnw.getY(), new LatLonPoint.Double()); - raster.setULLat(llp2.getY()); - raster.setULLon(llp2.getX()); - raster.setLRLat(llp1.getY()); - raster.setLRLon(llp1.getX()); - } else { - // movingPoint == gpc - llp1 = projection.inverse(gpc.getX(), gpc.getY(), new LatLonPoint.Double()); - raster.setULLat(llp1.getY() + diffy); - raster.setULLon(llp1.getX() - diffx); - raster.setLRLat(llp1.getY() - diffy); - raster.setLRLon(llp1.getX() + diffx); - } - raster.setNeedToRegenerate(true); - } - } - - boolean settingOffset = getStateMachine().getState() instanceof GraphicSetOffsetState - && movingPoint == gpo; - - // If the center point is moving, the offset distance changes - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - - llp1 = projection.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - if (settingOffset || movingPoint == gpc) { - int halfheight = (gpse.getY() - gpnw.getY()) / 2; - int halfwidth = (gpse.getX() - gpnw.getX()) / 2; - - // Don't call rect.setLocation because we only want to - // setNeedToRegenerate if !settingOffset. - llp1 = projection.inverse(gpc.getX() - halfwidth - gpo.getX(), gpc.getY() - - halfheight - gpo.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpc.getX() + halfwidth - gpo.getX(), gpc.getY() - + halfheight - gpo.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } - - if (!settingOffset) { - Debug.message("eomg", "EditableOMScalingRaster: updating offset rect"); - if (movingPoint == gpnw || movingPoint == gpse) { - llp1 = projection.inverse(gpnw.getX() - gpo.getX(), gpnw.getY() - gpo.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpse.getX() - gpo.getX(), gpse.getY() - - gpo.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } else if (movingPoint == gpne || movingPoint == gpsw) { - llp1 = projection.inverse(gpsw.getX() - gpo.getX(), gpne.getY() - gpo.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpne.getX() - gpo.getX(), gpsw.getY() - - gpo.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } - raster.setNeedToRegenerate(true); - } - - // Set Location has reset the rendertype, but provides - // the convenience of setting the max and min values - // for us. - raster.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - } - - // Do the rect height and width for XY and OFFSET render - // types. - if (renderType == OMGraphic.RENDERTYPE_XY) { - Debug.message("eomg", "EditableOMScalingRaster: updating x/y rect"); - - if (movingPoint == gpc) { - int halfheight = (gpse.getY() - gpnw.getY()) / 2; - int halfwidth = (gpse.getX() - gpnw.getX()) / 2; - - llp1 = projection.inverse(gpc.getX() - halfwidth, gpc.getY() - halfheight, new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpc.getX() + halfwidth, gpc.getY() - + halfheight, new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } else if (movingPoint == gpnw || movingPoint == gpse) { - llp1 = projection.inverse(gpnw.getX(), gpnw.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpse.getX(), gpse.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } else if (movingPoint == gpne || movingPoint == gpsw) { - llp1 = projection.inverse(gpsw.getX(), gpne.getY(), new LatLonPoint.Double()); - LatLonPoint llp2 = projection.inverse(gpne.getX(), gpsw.getY(), new LatLonPoint.Double()); - - raster.setULLat(llp1.getY()); - raster.setULLon(llp1.getX()); - - raster.setLRLat(llp2.getY()); - raster.setLRLon(llp2.getX()); - } - } - - if (projection != null) { - regenerate(projection); - } - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(java.awt.event.MouseEvent e) { - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - Debug.message("eomgdetail", "EditableOMScalingRaster.generate()"); - if (raster != null) - raster.generate(proj); - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - gp.generate(proj); - } - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - Debug.message("eomg", "EditableOMScalingRaster.regenerate()"); - if (raster != null) - raster.regenerate(proj); - - setGrabPoints(raster); - generate(proj); - } - - /** - * Draw the EditableOMScalingRaster parts into the java.awt.Graphics object. - * The grab points are only rendered if the rect machine state is - * RectSelectedState.RECT_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - Debug.message("eomgdetail", "EditableOMScalingRaster.render()"); - - State state = getStateMachine().getState(); - - if (raster == null) { - Debug.message("eomg", "EditableOMScalingRaster.render: null rect."); - return; - } - - raster.setVisible(true); - raster.render(graphics); - raster.setVisible(false); - - int renderType = raster.getRenderType(); - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState) { - - for (int i = 0; i < gPoints.length; i++) { - - GrabPoint gp = gPoints[i]; - if (gp != null) { - if ((i == OFFSET_POINT_INDEX && renderType == OMGraphic.RENDERTYPE_OFFSET && movingPoint == gpo) - || (state instanceof GraphicSelectedState && ((i != OFFSET_POINT_INDEX && renderType != OMGraphic.RENDERTYPE_OFFSET) || (renderType == OMGraphic.RENDERTYPE_OFFSET)))) { - - gp.setVisible(true); - gp.render(graphics); - gp.setVisible(false); - } - } - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMSpline.java deleted file mode 100644 index fbc205bb1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMSpline.java +++ /dev/null @@ -1,97 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMSpline.java,v $ -//$RCSfile: EditableOMSpline.java,v $ -//$Revision: 1.6 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -/** - * EditableOMSpline. Nothing created, code adapted from EditableOMPoly - * We just need to edit the generating points as an OMPoly - * - * @author Eric LEPICIER - * @version 22 juil. 2002 - */ -public class EditableOMSpline extends EditableOMPoly { - - /** - * Constructor. - */ - public EditableOMSpline() { - super(); - } - - /** - * Constructor. - * - * @param ga - */ - public EditableOMSpline(GraphicAttributes ga) { - super(ga); - } - - /** - * Constructor. - * - * @param omp - */ - public EditableOMSpline(OMSpline omp) { - super(omp); - } - - /** - * Extendable method to create specific subclasses of OMPolys. - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - g = new OMSpline(new double[0], OMGraphic.RADIANS, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - g = new OMSpline(90f, -180f, new int[0], OMSpline.COORDMODE_ORIGIN); - break; - default: - g = new OMSpline(new int[0]); - } - ((OMSpline) g).setDoShapes(true); - return g; - } - - /** - * Overridden to overcome some repainting unpleasantness that - * occurs when a point is added. Slows things down, however. - */ - public int addMovingPoint(int x, int y) { - int position = super.addMovingPoint(x, y); - redraw(null, true); - return position; - } - - public java.net.URL getImageURL(String imageName) { - try { - return Class.forName("com.bbn.openmap.omGraphics.EditableOMPoly") - .getResource(imageName); - } catch (ClassNotFoundException cnfe) { - } - return null; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMText.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMText.java deleted file mode 100644 index c4f69ea22..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/EditableOMText.java +++ /dev/null @@ -1,678 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMText.java,v $ -// $RCSfile: EditableOMText.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; - -import com.bbn.openmap.omGraphics.editable.GraphicEditState; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.editable.GraphicSetOffsetState; -import com.bbn.openmap.omGraphics.editable.GraphicUndefinedState; -import com.bbn.openmap.omGraphics.editable.TextStateMachine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.stateMachine.State; - -/** - * Wrapper class to edit OMText objects. This component is used by the - * OMDrawingTool. - */ -public class EditableOMText extends EditableOMGraphic implements ActionListener { - - protected GrabPoint gpc; - protected OffsetGrabPoint gpo; // offset - - protected OMText text; - - public final static int CENTER_POINT_INDEX = 0; - public final static int OFFSET_POINT_INDEX = 1; - - /** - * Create the EditableOMText, setting the state machine to create the point - * off of the gestures. - */ - public EditableOMText() { - createGraphic(null); - } - - /** - * Create an EditableOMText with the pointType and renderType parameters in - * the GraphicAttributes object. - */ - public EditableOMText(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMText with an OMText already defined, ready for - * editing. - * - * @param omc OMText that should be edited. - */ - public EditableOMText(OMText omc) { - setGraphic(omc); - } - - /** - * Create and initialize the state machine that interprets the modifying - * gestures/commands, as well as initialize the grab points. Also allocates - * the grab point array needed by the EditableOMText. - */ - public void init() { - setCanGrabGraphic(false); - setStateMachine(new TextStateMachine(this)); - gPoints = new GrabPoint[2]; - } - - /** - * Set the graphic within the state machine. If the graphic is null, then - * one shall be created, and located off screen until the gestures driving - * the state machine place it on the map. - */ - public void setGraphic(OMGraphic graphic) { - init(); - if (graphic instanceof OMText) { - text = (OMText) graphic; - stateMachine.setSelected(); - setGrabPoints(text); - } else { - createGraphic(null); - } - } - - /** - * Create and set the graphic within the state machine. The - * GraphicAttributes describe the type of point to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - - if (ga != null) { - renderType = ga.getRenderType(); - } - - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - text = new OMText(90f, -180f, "Text", OMText.JUSTIFY_LEFT); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - text = new OMText(90f, -180f, 0, 0, "Text", OMText.JUSTIFY_LEFT); - break; - default: - text = new OMText(0, 0, "Text", OMText.JUSTIFY_LEFT); - } - - if (ga != null) { - ga.setTo(text, true); - text.setLinePaint(ga.getLinePaint()); - } - - assertGrabPoints(); - } - - /** - * Get the OMGraphic being created/modified by the EditableOMText. - */ - public OMGraphic getGraphic() { - return text; - } - - /** - * Attach to the Moving OffsetGrabPoint so if it moves, it will move this - * EditableOMGraphic with it. EditableOMGraphic version doesn't do anything, - * each subclass has to decide which of its OffsetGrabPoints should be - * attached to it. - */ - public void attachToMovingGrabPoint(OffsetGrabPoint gp) { - gp.addGrabPoint(gpo); - } - - /** - * Detach from a Moving OffsetGrabPoint. The EditableOMGraphic version - * doesn't do anything, each subclass should remove whatever GrabPoint it - * would have attached to an OffsetGrabPoint. - */ - public void detachFromMovingGrabPoint(OffsetGrabPoint gp) { - gp.removeGrabPoint(gpo); - } - - /** - * Set the GrabPoint that is in the middle of being modified, as a result of - * a mouseDragged event, or other selection process. - */ - // public void setMovingPoint(GrabPoint gp) { - // super.setMovingPoint(gp); - // } - - /** - * Given a MouseEvent, find a GrabPoint that it is touching, and set the - * moving point to that GrabPoint. - * - * @param e MouseEvent - * @return GrabPoint that is touched by the MouseEvent, null if none are. - */ - public GrabPoint getMovingPoint(MouseEvent e) { - - movingPoint = null; - GrabPoint[] gb = getGrabPoints(); - - Point2D pnt = getProjectionPoint(e); - double x = pnt.getX(); - double y = pnt.getY(); - - for (int i = gb.length - 1; i >= 0; i--) { - - if (gb[i] != null && gb[i].distance(x, y) == 0) { - - setMovingPoint(gb[i]); - // in case the points are on top of each other, the - // last point in the array will take precedence. - break; - } - } - return movingPoint; - } - - protected int lastRenderType = -1; - - /** - * Check to make sure the grab points are not null. If they are, allocate - * them, and them assign them to the array. - */ - public void assertGrabPoints() { - int rt = getGraphic().getRenderType(); - if (rt != lastRenderType) { - clearGrabPoints(); - lastRenderType = rt; - } - - if (gpc == null) { - gpc = new GrabPoint(-1, -1); - gPoints[CENTER_POINT_INDEX] = gpc; - } - - if (gpo == null) { - gpo = new OffsetGrabPoint(-1, -1); - gPoints[OFFSET_POINT_INDEX] = gpo; - gpo.addGrabPoint(gpc); - } - } - - protected void clearGrabPoints() { - - gpc = null; - gpo = null; - - gPoints[CENTER_POINT_INDEX] = gpc; - gPoints[OFFSET_POINT_INDEX] = gpo; - } - - /** - * Set the grab points for the graphic provided, setting them on the extents - * of the graphic. Called when you want to set the grab points off the - * location of the graphic. - */ - public void setGrabPoints(OMGraphic graphic) { - if (!(graphic instanceof OMText)) { - return; - } - assertGrabPoints(); - - OMText text = (OMText) graphic; - boolean ntr = text.getNeedToRegenerate(); - int renderType = text.getRenderType(); - - LatLonPoint llp; - int latoffset = 0; - int lonoffset = 0; - - boolean doStraight = true; - - if (ntr == false) { - - if (renderType == OMGraphic.RENDERTYPE_LATLON - || renderType == OMGraphic.RENDERTYPE_OFFSET) { - - if (projection != null) { - double lon = text.getLon(); - double lat = text.getLat(); - - llp = new LatLonPoint.Double(lat, lon); - Point2D p = projection.forward(llp); - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - doStraight = false; - gpc.set((int) p.getX(), (int) p.getY()); - } else { - latoffset = (int) p.getY(); - lonoffset = (int) p.getX(); - gpo.set(lonoffset, latoffset); - } - } - } - - if (doStraight) { - gpc.set(lonoffset + text.getX(), latoffset + text.getY()); - } - - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - gpo.updateOffsets(); - } - - } else { - System.out.println("EditableOMText.setGrabPoint: graphic needs to be regenerated"); - } - } - - /** - * Take the current location of the GrabPoints, and modify the location - * parameters of the OMPoint with them. Called when you want the graphic to - * change according to the grab points. - */ - public void setGrabPoints() { - - int renderType = text.getRenderType(); - LatLonPoint llp1; - - Debug.message("eomt", "EditableOMText.setGrabPoints()"); - - // Do center point for lat/lon or offset points - if (renderType == OMGraphic.RENDERTYPE_LATLON) { - - if (projection != null) { - // movingPoint == gpc - llp1 = projection.inverse(gpc.getX(), gpc.getY(), new LatLonPoint.Double()); - text.setLat(llp1.getY()); - text.setLon(llp1.getX()); - // text.setNeedToRegenerate set - } - } - - boolean settingOffset = getStateMachine().getState() instanceof GraphicSetOffsetState - && movingPoint == gpo; - - // If the center point is moving, the offset distance changes - if (renderType == OMGraphic.RENDERTYPE_OFFSET) { - - llp1 = projection.inverse(gpo.getX(), gpo.getY(), new LatLonPoint.Double()); - - text.setLat(llp1.getY()); - text.setLon(llp1.getX()); - - if (settingOffset || movingPoint == gpc) { - // Don't call point.setLocation because we only want - // to - // setNeedToRegenerate if !settingOffset. - text.setX(gpc.getX() - gpo.getX()); - text.setY(gpc.getY() - gpo.getY()); - } - - if (!settingOffset) { - text.setX(gpc.getX() - gpo.getX()); - text.setY(gpc.getY() - gpo.getY()); - } - - // Set Location has reset the rendertype, but provides - // the convenience of setting the max and min values - // for us. - text.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - } - - // Do the point height and width for XY and OFFSET render - // types. - if (renderType == OMGraphic.RENDERTYPE_XY) { - - if (movingPoint == gpc) { - text.setX(gpc.getX()); - text.setY(gpc.getY()); - } - } - - if (projection != null) { - regenerate(projection); - } - - } - - /** - * Get whether a graphic can be manipulated by its edges, rather than just - * by its grab points. - */ - public boolean getCanGrabGraphic() { - return false; - } - - /** - * Called to set the OffsetGrabPoint to the current mouse location, and - * update the OffsetGrabPoint with all the other GrabPoint locations, so - * everything can shift smoothly. Should also set the OffsetGrabPoint to the - * movingPoint. Should be called only once at the beginning of the general - * movement, in order to set the movingPoint. After that, redraw(e) should - * just be called, and the movingPoint will make the adjustments to the - * graphic that are needed. - */ - public void move(java.awt.event.MouseEvent e) { - } - - /** - * Use the current projection to place the graphics on the screen. Has to be - * called to at least assure the graphics that they are ready for rendering. - * Called when the graphic position changes. - * - * @param proj com.bbn.openmap.proj.Projection - * @return true - */ - public boolean generate(Projection proj) { - if (text != null) - text.regenerate(proj); - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - gp.generate(proj); - } - } - return true; - } - - /** - * Given a new projection, the grab points may need to be repositioned off - * the current position of the graphic. Called when the projection changes. - */ - public void regenerate(Projection proj) { - if (text != null) - text.regenerate(proj); - - setGrabPoints(text); - generate(proj); - } - - /** - * Draw the EditableOMtext parts into the java.awt.Graphics object. The grab - * points are only rendered if the point machine state is - * TextSelectedState.TEXT_SELECTED. - * - * @param graphics java.awt.Graphics. - */ - public void render(java.awt.Graphics graphics) { - - State state = getStateMachine().getState(); - - if (!(state instanceof GraphicUndefinedState)) { - if (text == null) { - Debug.message("eomg", "EditableOMText.render: null point."); - return; - } - text.setVisible(true); - text.render(graphics); - text.setVisible(false); - - int renderType = text.getRenderType(); - - if (state instanceof GraphicSelectedState || state instanceof GraphicEditState) { - - for (int i = 0; i < gPoints.length; i++) { - GrabPoint gp = gPoints[i]; - if (gp != null) { - if ((i == OFFSET_POINT_INDEX && renderType == OMGraphic.RENDERTYPE_OFFSET && movingPoint == gpo) - || (state instanceof GraphicSelectedState && ((i != OFFSET_POINT_INDEX && renderType != OMGraphic.RENDERTYPE_OFFSET) || (renderType == OMGraphic.RENDERTYPE_OFFSET)))) { - - gp.setVisible(true); - gp.render(graphics); - gp.setVisible(false); - } - } - } - } - } - } - - /** - * If this EditableOMGraphic has parameters that can be manipulated that are - * independent of other EditableOMGraphic types, then you can provide the - * widgets to control those parameters here. By default, returns the - * GraphicAttributes GUI widgets. If you don't want a GUI to appear when a - * widget is being created/edited, then don't call this method from the - * EditableOMGraphic implementation, and return a null Component from - * getGUI. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return java.awt.Component to use to control parameters for this EOMG. - */ - public java.awt.Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMPoly.getGUI"); - if (graphicAttributes != null) { - // JComponent gaGUI = (JComponent) graphicAttributes.getGUI(); - JComponent toolbar = createAttributePanel(graphicAttributes); - // ((JComponent) gaGUI).add(getTextGUI()); - - getTextGUI(graphicAttributes.getOrientation(), toolbar); - - return toolbar; - } else { - return getTextGUI(); - } - } - - JComboBox sizesFont; - JToggleButton boldFont; - JToggleButton italicFont; - - /** Command for text string adjustments. */ - public final static String TextFieldCommand = "TextField"; - public final static String TextFontCommand = "TextFont"; - public final static String TextRotationCommand = "TextRotation"; - - protected JComponent getTextGUI() { - return getTextGUI(SwingConstants.HORIZONTAL, (JComponent) null); - } - - JComponent attributeBox; - - /** - * Get the GUI associated with changing the Text. - * - * @param orientation SwingConstants.HORIZONTAL/VERTICAL - * @param guiComp the JComponent to add stuff to. If the orientation is - * HORIZONTAL, the components will be added directly to this - * component, or to a new JComponent that is returned if null. If the - * orientation is Vertical, a button will be added to the guiComp, or - * returned. This button will call up a dialog box with the settings, - * since they don't really lay out vertically. - * @return JComponent with text controls. - */ - protected JComponent getTextGUI(int orientation, JComponent guiComp) { - attributeBox = null; - - if (guiComp == null || orientation == SwingConstants.VERTICAL) { - attributeBox = javax.swing.Box.createHorizontalBox(); - - attributeBox.setAlignmentX(Component.CENTER_ALIGNMENT); - attributeBox.setAlignmentY(Component.CENTER_ALIGNMENT); - - } else if (orientation == SwingConstants.HORIZONTAL) { - attributeBox = guiComp; - } - - if (guiComp == null) { - guiComp = new JPanel(); - } - - guiComp.add(PaletteHelper.getToolBarFill(orientation)); - - if (orientation == SwingConstants.VERTICAL) { - JButton launchButton = new JButton(getTextAccentToggleButtonImage(DrawingAttributes.icon_width, DrawingAttributes.icon_height, text.getFont(), "T")); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (attributeBox != null) { - JDialog dialog = new JDialog(); - dialog.setContentPane(attributeBox); - dialog.setModal(true); - dialog.pack(); - dialog.setLocationRelativeTo((JButton) ae.getSource()); - dialog.setVisible(true); - } - } - }); - guiComp.add(launchButton); - } - - String textString = "Text"; - if (text != null) { - textString = text.getData(); - } - - attributeBox.add(PaletteHelper.getToolBarFill(SwingConstants.HORIZONTAL)); - - JTextField textField = new JTextField(textString, 25); - textField.setActionCommand(TextFieldCommand); - textField.addActionListener(this); - textField.setMinimumSize(new java.awt.Dimension(100, 20)); - textField.setPreferredSize(new java.awt.Dimension(100, 20)); - attributeBox.add(textField); - - attributeBox.add(PaletteHelper.getToolBarFill(SwingConstants.HORIZONTAL)); - // JPanel palette = - // PaletteHelper.createHorizontalPanel("Rotation"); - javax.swing.Box palette = javax.swing.Box.createHorizontalBox(); - textField = new JTextField(String.valueOf((int) Math.toDegrees(text.getRotationAngle())), 5); - textField.setActionCommand(TextRotationCommand); - textField.setToolTipText(i18n.get(EditableOMText.class, "textField", I18n.TOOLTIP, "Text rotation in degrees")); - textField.addActionListener(this); - textField.setMinimumSize(new java.awt.Dimension(30, 20)); - textField.setPreferredSize(new java.awt.Dimension(30, 20)); - palette.add(textField); - palette.add(new JLabel("\u00b0 ")); - attributeBox.add(palette); - - String[] sizesStrings = { "3", "5", "8", "10", "12", "14", "18", "20", "24", "36", "48" }; - sizesFont = new JComboBox(sizesStrings); - sizesFont.setToolTipText(i18n.get(EditableOMText.class, "sizesFont", I18n.TOOLTIP, "Font Size")); - sizesFont.setSelectedItem("" + (text.getFont()).getSize()); - sizesFont.setActionCommand(TextFontCommand); - sizesFont.addActionListener(this); - - int textButtonWidth = 10; - int textButtonHeight = 15; - - boldFont = new JToggleButton(); - boldFont.setIcon(getTextAccentToggleButtonImage(textButtonWidth, textButtonHeight, new Font(boldFont.getFont().getName(), Font.BOLD, boldFont.getFont().getSize()), "B")); - - // Too wide margins for 1 letter look unnatural - Insets insets = boldFont.getInsets(); - insets.left /= 2; - insets.right /= 2; - boldFont.setMargin(insets); - boldFont.setSelected(text.getFont().isBold()); - boldFont.setToolTipText(i18n.get(EditableOMText.class, "boldFont", I18n.TOOLTIP, "Bold Font")); - boldFont.setActionCommand(TextFontCommand); - boldFont.addActionListener(this); - - italicFont = new JToggleButton(); - italicFont.setIcon(getTextAccentToggleButtonImage(textButtonWidth, textButtonHeight, new Font(italicFont.getFont().getName(), Font.ITALIC, italicFont.getFont().getSize()), "I")); - italicFont.setMargin(insets); - italicFont.setSelected(text.getFont().isItalic()); - italicFont.setToolTipText(i18n.get(EditableOMText.class, "italicFont", I18n.TOOLTIP, "Italic Font")); - italicFont.setActionCommand(TextFontCommand); - italicFont.addActionListener(this); - - attributeBox.add(sizesFont); - attributeBox.add(PaletteHelper.getToolBarFill(SwingConstants.HORIZONTAL)); - attributeBox.add(boldFont); - attributeBox.add(italicFont); - - return guiComp; - } - - private ImageIcon getTextAccentToggleButtonImage(int width, int height, Font f, String s) { - BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics g = bi.getGraphics(); - g.setFont(f); - g.setColor(Color.black); - FontMetrics fm = g.getFontMetrics(); - - int stringWidth = fm.stringWidth(s); - int stringHeight = f.getSize() - 2; - g.drawString(s, (width - stringWidth) / 2, height - (height - stringHeight) / 2); - return new ImageIcon(bi); - } - - public void actionPerformed(ActionEvent e) { - Object source = e.getSource(); - String command = e.getActionCommand(); - - if (command == TextFontCommand) { - String FontString = OMText.fontToXFont(text.getFont()); - FontString = FontString.substring(0, FontString.indexOf("-", 3)); - StringBuffer ret = new StringBuffer(FontString); - if (boldFont.isSelected()) - ret.append("-bold"); - else - ret.append("-normal"); - if (italicFont.isSelected()) - ret.append("-i"); - else - ret.append("-o"); - ret.append("-normal"); - ret.append("--").append(sizesFont.getSelectedItem()); - ret.append("-*-*-*-*-*-*"); - ret.toString(); - text.setFont(OMText.rebuildFont(ret.toString())); - repaint(); - } else if (command == TextFieldCommand) { - text.setData(((JTextField) source).getText()); - text.regenerate(projection); - repaint(); - } else if (command == TextRotationCommand) { - Integer rotation = new Integer(((JTextField) source).getText()); - text.setRotationAngle(Math.toRadians(rotation.intValue())); - text.regenerate(projection); - repaint(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/FilterSupport.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/FilterSupport.java deleted file mode 100644 index 457e6b94f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/FilterSupport.java +++ /dev/null @@ -1,354 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/FilterSupport.java,v $ -// $RCSfile: FilterSupport.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Shape; -import java.awt.geom.Area; -import java.io.Serializable; - -import com.bbn.openmap.util.Debug; - -/** - * This class provides support for implementing the OMGraphicHandler - * interface. If you already calculate an OMGraphicList, you can use - * this class to apply filtering to it. The graphics on the list you - * provide it will be made visible or not depending on whether they - * meet the filter criteria. - *

- * - * The visibility of the graphics is affected when a filter is - * applied, and visibility is used as the test if whether a graphic is - * added to a returned list. Use resetFiltering() to turn visibility - * back on for all the OMGraphics. If a graphic is not visible when a - * filter is applied, then the filter test will automatically fail. - */ -public class FilterSupport implements OMGraphicHandler, Serializable { - - /** - * The source graphic list. - */ - protected OMGraphicList list = null; - - /** - * A flag to use the Area.intersect(Area) test, which may be a - * performance hit. - */ - protected boolean precise = true; - - protected boolean DEBUG = Debug.debugging("list"); - - public FilterSupport() {} - - public FilterSupport(OMGraphicList omgl) { - setList(omgl); - } - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * within the given shape will be visible. Returns an - * OMGraphicList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. Same as calling - * filter(withinThisShape, true). - * - * @param withinThisShape java.awt.Shape object defining a - * boundary. - * @return OMGraphicList containing OMGraphics that are within the - * Shape. - */ - public OMGraphicList filter(Shape withinThisShape) { - return filter(withinThisShape, true); - } - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * inside or outside the given shape will be visible. Returns an - * OMGraphicList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. - * - * @param shapeBoundary java.awt.Shape object defining a boundary. - * @param getInsideBoundary if true, the filter will look for - * shapes inside and contacting the boundary. If false, the - * filter will look for shapes outside the boundary. - * @return OMGraphicList containing OMGraphics that are within the - * Shape. - */ - public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary) { - Area area = null; - if (shapeBoundary != null) { - area = new Area(shapeBoundary); - } - - if (Debug.debugging("filtersupportdetail")) { - Debug.output(getList().getDescription()); - } - - return filterList(getList(), area, getInsideBoundary); - } - - /** - * Method that provides a recursive mechanism to go through - * OMGraphicsLists to filter out areas, inside or outside another. - */ - protected OMGraphicList filterList(OMGraphicList omgl, Area area, - boolean getInsideArea) { - OMGraphicList ret = new OMGraphicList(); - boolean DEBUG_DETAIL = Debug.debugging("filtersupportdetail"); - boolean DEBUG = Debug.debugging("filtersupport") || DEBUG_DETAIL; - - if (DEBUG) { - Debug.output("FilterSupport.filterList"); - } - - int count = 0; // for debugging - - if (area != null && omgl != null) { // just checking - - for (OMGraphic omg : omgl) { - - if (DEBUG) { - Debug.output("FilterSupport.filterList evaluating " - + (count++) + " OMGraphic, " + omg); - } - - boolean outsideFilter = true; - - // If not visible, automatically fails... - if (!omg.isVisible()) { - if (DEBUG) { - Debug.output(" OMGraphic not visible, ignoring"); - } - continue; - } - - if (omg instanceof OMGraphicList) { - if (omg == omgl) { - Debug.output(" OMGraphic is parent list (points to itself), ignoring..."); - continue; - } - - if (DEBUG) { - Debug.output(" (filterList recursiving handing OMGraphicList)"); - } - - OMGraphicList subList = filterList((OMGraphicList) omg, - area, - getInsideArea); - - if (!subList.isEmpty()) { - if (DEBUG) { - Debug.output(" +++ OMGraphicList's contents (" - + subList.size() - + ") pass filter, adding..."); - } - - if (((OMGraphicList)omg).isVague()) { - passedFilter(omg); - omg.setVisible(true); - ret.add(omg); - } else { - passedFilter(subList); - ret.add(subList); - } - } else { - if (DEBUG) { - Debug.output(" --- OMGraphicList's contents fail filter, ignoring..."); - } - - failedFilter(omg); - } - continue; - } else { - Shape omgShape = omg.getShape(); - if (omgShape != null) { - if (omgShape.getBounds2D().getWidth() == 0 && omgShape.getBounds2D().getHeight() == 0) { - if (area.contains(omgShape.getBounds2D().getX(), omgShape.getBounds2D().getY())) { - if (DEBUG_DETAIL) { - Debug.output(" +++ omg contains position"); - } - - outsideFilter = false; - } - } - else if (area.intersects(omgShape.getBounds2D())) { - if (DEBUG_DETAIL) { - Debug.output(" +++ omg intersects bounds"); - } - - // The area.interects() method above is a - // general case. If you care about - // preciseness, set the precise flag. - // Depending on the performance cost, we might - // want to make it permanent. - - if (precise) { - Area omgArea = new Area(omgShape); - if (!omgArea.isSingular()) { - Area clone = (Area) area.clone(); - clone.intersect(omgArea); - if (!clone.isEmpty()) { - outsideFilter = false; - } - } else { - outsideFilter = false; - } - } else { - outsideFilter = false; - } - } - } - - // decide what to do depending on filteredOut and - // getInsideArea - if ((outsideFilter && !getInsideArea) - || (!outsideFilter && getInsideArea)) { - - if (DEBUG) { - Debug.output(" +++ OMGraphic passes filter, adding..."); - } - - passedFilter(omg); - ret.add(omg); - } else { - if (DEBUG) { - Debug.output(" --- OMGraphic fails filter, hiding..."); - } - - failedFilter(omg); - } - } - } - } - - return ret; - } - - /** - * Returns true if the OMGraphicHandler can handle SQL statements - * for filtering. - */ - public boolean supportsSQL() { - return false; - } - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * meeting the SQL query statement will be visible. Returns an - * OMGraphicList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. - * - * @param SQLQuery a SELECT SQL statement - * @return OMGraphicList containing OMGraphics that meet the - * SELECT statement criteria. - */ - public OMGraphicList filter(String SQLQuery) { - return new OMGraphicList(); - } - - /** - * Allows the OMGraphicHandler to receive graphics or take some - * action on one. - * - * @param graphic the OMGraphic to do the action on. - * @param action the OMAction describing what to do to the - * graphic. - * @return true if the action was able to be carried out. - */ - public boolean doAction(OMGraphic graphic, OMAction action) { - OMGraphicList list = getList(); - if (list != null) { - list.doAction(graphic, action); - } - return true; // we can handle it. - } - - /** - * Return the graphic list currently being used by the - * OMGraphicHandler. If filters have been applied, then the - * OMGraphics that have made it through the filter are visible. - * List may be null, if it hasn't been set. - * - * @see OMGraphic#isVisible() - */ - public synchronized OMGraphicList getList() { - if (DEBUG) { - Debug.output("FilterSupport.getList() with " - + (list != null ? list.size() + " graphics." : "null list.")); - } - return list; - } - - /** - * Indicates if the OMGraphicHandler can have its OMGraphicList - * set. - */ - public boolean canSetList() { - return true; - } - - /** - * Set the OMGraphicList within this OMGraphicHandler. Works if - * canSetGraphicList == true. - */ - public synchronized void setList(OMGraphicList omgl) { - if (DEBUG) { - Debug.output("FilterSupport.setList() with " - + (omgl != null ? omgl.size() + " graphics." : "null list.")); - } - list = omgl; - } - - /** - * Remove all filters, and reset all graphics to be visible. - */ - public void resetFiltering() { - OMGraphicList list = getList(); - if (list != null) - list.setVisible(true); - } - - /** - * Method called when FilterSupport finds an OMGraphic that fails - * the filter test. The OMGraphic is not being added to a list - * that is being returned for passing OMGraphics in another - * method, this call-out is an opportunity to make settings on - * OMGraphics that pass the filter. By default, the visibility of - * the OMGraphic is set to false. - */ - protected void failedFilter(OMGraphic omg) { - omg.setVisible(false); - } - - /** - * Method called when FilterSupport finds an OMGraphic that passes - * the filter test. The OMGraphic is already being added to a list - * that is being returned in another method, this call-out is an - * opportunity to make settings on OMGraphics that pass the - * filter. - */ - protected void passedFilter(OMGraphic omg) { - // NO-OP, by default - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/FontSizer.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/FontSizer.java deleted file mode 100644 index 122391e49..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/FontSizer.java +++ /dev/null @@ -1,200 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/FontSizer.java,v $ -// $RCSfile: FontSizer.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/09/06 20:02:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Font; -import java.awt.geom.AffineTransform; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -/** - * Helper class to OMText object that resizes font when scale changes. - * Font gets bigger as you zoom in. - */ -public class FontSizer implements Serializable { - - protected transient Font font = OMText.DEFAULT_FONT; - protected transient Font lastFont = OMText.DEFAULT_FONT; - protected float baseScale = -1; - protected transient float lastScale = -1; - protected transient float curScale = -1; - protected int minPointSize = font.getSize(); - protected int maxPointSize = font.getSize(); - - /** - * Default of 1. Used against the base scale/current scale ratio - * to speed up or slow down font size changes based on scale. - */ - protected int multiplier = 1; - - /** - * Create a FontSizer with the same settings as the source. - * @param source - */ - public FontSizer(FontSizer source) { - restore(source); - } - - /** - * @param font the font to use as the base font. - * @param baseScale the scale where the base font is shown at its - * natural size. - * @param multiplier to use against the ratio of base - * scale:current scale. - * @param minPointSize the minimum point size to use for the - * scaled font. - * @param maxPointSize the maximum point size to use for the - * scaled font. - */ - public FontSizer(Font font, float baseScale, int multiplier, - int minPointSize, int maxPointSize) { - this(baseScale, multiplier, minPointSize, maxPointSize); - this.font = font; - } - - /** - * Constructor that uses the OMText DEFAULT_FONT as the base font. - * - * @param baseScale the scale where the base font is shown at its - * natural size. - * @param multiplier to use against the ratio of base - * scale:current scale. - * @param minPointSize the minimum point size to use for the - * scaled font. - * @param maxPointSize the maximum point size to use for the - * scaled font. - */ - public FontSizer(float baseScale, int multiplier, int minPointSize, - int maxPointSize) { - this.baseScale = baseScale; - this.multiplier = multiplier; - this.minPointSize = minPointSize; - this.maxPointSize = maxPointSize; - } - - /** - * Set the base font. - */ - public void setFont(Font font) { - this.font = font; - } - - /** - * Get a font sized for the scale, given the size restrictions. - */ - public Font getFont(float scale) { - curScale = scale; - return getScaledFont(); - } - - protected Font getScaledFont() { - if (lastScale != curScale) { - lastScale = curScale; - - if (baseScale < 0 || curScale < 0) { - lastFont = font; - } else { - - int newFontSize = multiplier - * (int) ((baseScale / curScale) * (float) font.getSize()); - - if (newFontSize > maxPointSize) { - newFontSize = maxPointSize; - } else if (newFontSize < minPointSize) { - newFontSize = minPointSize; - } - - lastFont = new Font(font.getName(), font.getStyle(), newFontSize); - } - } - - return lastFont; - } - - /** - * Get the base font. - */ - public Font getFont() { - return font; - } - - public void setMultiplier(int mul) { - lastScale = -1; - multiplier = mul; - } - - public int getMultiplier() { - return multiplier; - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - - // Write the Font. Take into account the font member could be - // null, although this is unlikely it never hurts to - // protect one's self. - boolean writeFont = (font != OMText.DEFAULT_FONT); - // First write a flag indicating if a Font is on the stream. - oos.writeBoolean(writeFont); - - // Write the Font data if a font is on this object. - if (writeFont) { - oos.writeObject(font.getName()); - oos.writeInt(font.getSize()); - oos.writeInt(font.getStyle()); - } - } - - /** - * Reconstitute from an ObjectInputStream. - */ - private void readObject(ObjectInputStream ois) - throws ClassNotFoundException, IOException { - ois.defaultReadObject(); - - // Get the flag form the stream - boolean hasFont = ois.readBoolean(); - - if (hasFont) { - String name = (String) ois.readObject(); - int size = ois.readInt(); - int style = ois.readInt(); - font = new Font(name, style, size); - } else { - font = OMText.DEFAULT_FONT; - } - } - - public void restore(FontSizer source) { - this.font = source.font.deriveFont(AffineTransform.TYPE_IDENTITY); - this.lastFont = source.font.deriveFont(AffineTransform.TYPE_IDENTITY); - this.baseScale = source.baseScale; - this.lastScale = source.lastScale; - this.curScale = source.curScale; - this.minPointSize = source.minPointSize; - this.maxPointSize = source.maxPointSize; - this.multiplier = source.multiplier; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/GrabPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/GrabPoint.java deleted file mode 100644 index be22f52a7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/GrabPoint.java +++ /dev/null @@ -1,54 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/GrabPoint.java,v $ -// $RCSfile: GrabPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; - -/** - * A GrabPoint is used by editable graphics to show a location that can be - * adjusted. Some GrabPoints are limited in the direction that they are able to - * move. - */ -public class GrabPoint - extends OMPoint { - - public final static int DEFAULT_RADIUS = 3; - - public GrabPoint(int x, int y) { - this(x, y, DEFAULT_RADIUS); - } - - public GrabPoint(int x, int y, int radius) { - super(x, y); - setDefaultDrawingAttributes(radius); - setVisible(false); - } - - public void set(double x, double y) { - set((int) x, (int) y); - } - - public void setDefaultDrawingAttributes(int pointRadius) { - new DrawingAttributes.Builder().setLinePaint(Color.black).setFillPaint(Color.white).setPointRadius(pointRadius).build().setTo(this); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/GraphicAttributes.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/GraphicAttributes.java deleted file mode 100644 index 5c2c057a6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/GraphicAttributes.java +++ /dev/null @@ -1,326 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/GraphicAttributes.java,v $ -// $RCSfile: GraphicAttributes.java,v $ -// $Revision: 1.12 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.Properties; - -import javax.swing.ButtonGroup; -import javax.swing.JMenu; -import javax.swing.JPopupMenu; -import javax.swing.JRadioButtonMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.proj.LineType; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The GraphicAttributes provides an extension to DrawingAttributes by - * provideing a mechanism for loading and managing different graphic attributes - * that may be used, such as line type (LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE, - * LINETYPE_RHUMB, or LINETYPE_UNKNOWN), or render type (RENDERTYPE_XY, - * RENDERTYPE_LATLON, RENDERTYPE_OFFSET, or RENDERTYPE_UNKNOWN). The - * DrawingAttributes class fishes out the applicable properties for you, creates - * the objects needed, and then lets you get those objects when needed. - */ -public class GraphicAttributes extends DrawingAttributes implements ActionListener, Serializable, OMGraphicConstants { - - /** - * The name of the property that holds the line type of the graphic. - */ - public final static String lineTypeProperty = "lineType"; - /** - * The name of the property that holds the render type of the graphic. - */ - public final static String renderTypeProperty = "renderType"; - - /** The line type of a graphic, defaults to LINETYPE_STRAIGHT. */ - protected int lineType = LINETYPE_STRAIGHT; - /** The rendertype of a graphic. Default is RENDERTYPE_XY. */ - protected int renderType = RENDERTYPE_XY; - /** Flag to disable choice of line type, from an external source. */ - protected boolean enableLineTypeChoice = true; - - public final static GraphicAttributes DEFAULT = new GraphicAttributes(); - - private I18n i18n = Environment.getI18n(); - - /** - * Create a GraphicAttributes with the default settings - clear fill paint - * and pattern, sold black edge line of width 1. - */ - public GraphicAttributes() { - super(); - } - - /** - * Create the GraphicAttributes and call init without a prefix for the - * properties. Call init without a prefix for the properties. - * - * @param props - * the Properties to look in. - */ - public GraphicAttributes(Properties props) { - super(props); - } - - /** - * Create the GraphicAttributes and call init with a prefix for the - * properties. - * - * @param prefix - * the prefix marker to use for a property, like - * prefix.propertyName. The period is added in this function. - * @param props - * the Properties to look in. - */ - public GraphicAttributes(String prefix, Properties props) { - super(prefix, props); - } - - /** - * If you want to get a DEFAULT DrawingAttributes object that you may - * modify, get your own copy. - */ - public static GraphicAttributes getGADefaultClone() { - return (GraphicAttributes) DEFAULT.clone(); - } - - /** - * PropertyConsumer method. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - if (props == null) { - return; - } - - // Set up the Graphic attributes. - lineType = PropUtils.intFromProperties(props, prefix + lineTypeProperty, lineType); - renderType = PropUtils.intFromProperties(props, prefix + renderTypeProperty, renderType); - } - - public Object clone() { - GraphicAttributes clone = new GraphicAttributes(); - setTo(clone); - return clone; - } - - public void setTo(GraphicAttributes clone) { - super.setTo(clone); - clone.renderType = renderType; - clone.lineType = lineType; - clone.enableLineTypeChoice = enableLineTypeChoice; - } - - /** - * Get the lineType. - */ - public int getLineType() { - return lineType; - } - - /** - * Set the line type. If it isn't straight, great circle or rhumb, it's set - * to unknown. - */ - public void setLineType(int lt) { - int oldLineType = lineType; - - if (lt == LINETYPE_STRAIGHT || lt == LINETYPE_GREATCIRCLE || lt == LINETYPE_RHUMB) { - lineType = lt; - } else { - lineType = LINETYPE_UNKNOWN; - } - - propertyChangeSupport.firePropertyChange("lineType", oldLineType, lineType); - } - - /** - * Get the renderType. - */ - public int getRenderType() { - return renderType; - } - - /** - * Set the render type. If it isn't xy, lat/lon, or lat/lon with offset, - * it's set to unknown. - */ - public void setRenderType(int rt) { - int oldRenderType = renderType; - - if (rt == RENDERTYPE_XY || rt == RENDERTYPE_LATLON || rt == RENDERTYPE_OFFSET) { - renderType = rt; - - } else { - renderType = RENDERTYPE_UNKNOWN; - } - - propertyChangeSupport.firePropertyChange("renderType", oldRenderType, renderType); - } - - /** - * Set the GraphicAttributes parameters based on the current settings of an - * OMGraphic. - */ - public void setFrom(OMGraphic graphic) { - setFrom(graphic, false); - } - - /** - * Set the GraphicAttributes parameters based on the current settings of an - * OMGraphic. - * - * @param graphic - * OMGraphic to gather settings from. - * @param resetGUI - * flag to cause GraphicAttribute GUI reset. - */ - public void setFrom(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) - return; - - super.setFrom(graphic, false); - lineType = graphic.getLineType(); - renderType = graphic.getRenderType(); - enableLineTypeChoice = graphic.hasLineTypeChoice(); - - if (resetGUI) { - resetGUI(); - } - } - - /** - * Set all the attributes for the graphic that are contained within this - * GraphicAttributes class. - * - * @param graphic - * OMGraphic. - */ - public void setTo(OMGraphic graphic) { - setTo(graphic, false); - } - - /** - * Set all the attributes for the graphic that are contained within this - * GraphicAttributes class. - * - * @param graphic - * OMGraphic. - * @param resetGUI - * reset the GraphicAttributes GUI if desired. - */ - public void setTo(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) - return; - - super.setTo(graphic, false); - graphic.setLineType(lineType); - - // Render type is dictated by coordinate settings. Changing this messes - // with fundamental rendering location. Only set it if the graphic rendertype is unknown. - if (graphic.getRenderType() == RENDERTYPE_UNKNOWN && renderType != RENDERTYPE_UNKNOWN) { - graphic.setRenderType(renderType); - } - - if (resetGUI) { - // The GraphicAttribute might be rendering options for this graphic, - // needs to know if line type choices are available. - enableLineTypeChoice = graphic.hasLineTypeChoice(); - enableFillPaintChoice = !(graphic instanceof NonRegional); - resetGUI(); - } - } - - /** - * Method should be called on this GraphicAttributes object if the OMGraphic - * type doesn't support line types to disable the choice from the line menu. - * Circles, range rings, points, etc. are all examples of shapes that - * disable linetype choice. - */ - public void setEnableLineTypeChoice(boolean value) { - enableLineTypeChoice = value; - } - - public boolean getEnableLineTypeChoice() { - return enableLineTypeChoice; - } - - protected void setPreStrokeMenuOptions(JPopupMenu popup) { - super.setPreStrokeMenuOptions(popup); - JMenu ltm = getLineTypeMenu(); - if (ltm != null) { - popup.add(ltm); - } - } - - public JMenu getLineTypeMenu() { - JMenu lineTypeMenu = null; - - if (renderType == RENDERTYPE_LATLON && enableLineTypeChoice) { - lineTypeMenu = new JMenu(i18n.get(GraphicAttributes.class, "Line_Type", "Line Type")); - - ActionListener listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setLineType(Integer.parseInt(command)); - } catch (NumberFormatException e) { - } - } - }; - - ButtonGroup group = new ButtonGroup(); - JRadioButtonMenuItem button = new JRadioButtonMenuItem( - i18n.get(DrawingAttributes.class, "Great_Circle", "Great Circle"), - lineType == LineType.GreatCircle); - button.setActionCommand(String.valueOf(LineType.GreatCircle)); - button.addActionListener(listener); - lineTypeMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(GraphicAttributes.class, "Rhumb", "Rhumb"), - lineType == LineType.Rhumb); - button.setActionCommand(String.valueOf(LineType.Rhumb)); - group.add(button); - button.addActionListener(listener); - lineTypeMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(GraphicAttributes.class, "Straight", "Straight"), - lineType == LineType.Straight); - button.setActionCommand(String.valueOf(LineType.Straight)); - group.add(button); - button.addActionListener(listener); - lineTypeMenu.add(button); - } - return lineTypeMenu; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/HorizontalGrabPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/HorizontalGrabPoint.java deleted file mode 100644 index 759214531..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/HorizontalGrabPoint.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/HorizontalGrabPoint.java,v $ -// $RCSfile: HorizontalGrabPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/** - * A GrabPoint that can only move in the horizontal direction. - */ -public class HorizontalGrabPoint extends GrabPoint { - - public HorizontalGrabPoint(int x, int y) { - super(x, y); - } - - /** - * y is ignored, since it can't affect the vertical movement of a - * HorizontalGrabPoint. - */ - public void set(int x, int y) { - setX(x); - } - - /** - * Move the point. - * - * @param x the new x location - * @param y the new y location - * @param override true if the vertical limitation should be - * ignored. - */ - public void set(int x, int y, boolean override) { - if (override) { - super.set(x, y); - } else { - setX(x); - } - } - - /** - * No action, because vertical movement is limited. - */ - public void setY(int y) {} - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/NatCubicSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/NatCubicSpline.java deleted file mode 100644 index 85d547ebf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/NatCubicSpline.java +++ /dev/null @@ -1,526 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/NatCubicSpline.java,v $ -//$RCSfile: NatCubicSpline.java,v $ -//$Revision: 1.5 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Polygon; - -import com.bbn.openmap.util.MoreMath; - -/** - * A natural cubic spline calculation. - * - * @author Eric LEPICIER - * @see Splines - * @version 21 juil. 2002 - */ -public class NatCubicSpline { - - /** - * The proper access for these classes, using default steps. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static float[][] calc(int[] xpoints, int[] ypoints, boolean geometryClosed) { - return calc(xpoints, ypoints, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static float[][] calc(int[] xpoints, int[] ypoints, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(xpoints, ypoints); - } - return new NatCubicSpline().withSteps(steps).calc(xpoints, ypoints); - } - - /** - * The proper access for these classes, using default steps. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static float[][] calc(float[] xpoints, float[] ypoints, boolean geometryClosed) { - return calc(xpoints, ypoints, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static float[][] calc(float[] xpoints, float[] ypoints, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(xpoints, ypoints); - } - return new NatCubicSpline().withSteps(steps).calc(xpoints, ypoints); - } - - /** - * The proper access for these classes, using default steps. - * - * @param llpoints - * @param precision - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static double[] calc(double[] llpoints, double precision, boolean geometryClosed) { - return calc(llpoints, precision, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param llpoints - * @param precision - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static double[] calc(double[] llpoints, double precision, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(llpoints, precision); - } - return new NatCubicSpline().withSteps(steps).calc(llpoints, precision); - } - - /** - * Calculates the natural cubic spline that interpolates y[0], y[1], ... - * y[n]. The first segment is returned as C[0].a + C[0].b*u + C[0].c*u^2 + - * C[0].d*u^3 0 <=u <1 the other segments are in C[1], C[2], ... C[n-1] - * - * @param n - * @param x - * @return Cubic[] - */ - Cubic[] calcNaturalCubic(int n, int[] x) { - float[] gamma = new float[n + 1]; - float[] delta = new float[n + 1]; - float[] D = new float[n + 1]; - int i; - /* - * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| - * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 - * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] by using - * row operations to convert the matrix to upper triangular and then - * back substitution. The D[i] are the derivatives at the knots. - */ - - gamma[0] = 1.0f / 2.0f; - for (i = 1; i < n; i++) { - gamma[i] = 1 / (4 - gamma[i - 1]); - } - gamma[n] = 1 / (2 - gamma[n - 1]); - - delta[0] = 3 * (x[1] - x[0]) * gamma[0]; - for (i = 1; i < n; i++) { - delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i]; - } - delta[n] = (3 * (x[n] - x[n - 1]) - delta[n - 1]) * gamma[n]; - - D[n] = delta[n]; - for (i = n - 1; i >= 0; i--) { - D[i] = delta[i] - gamma[i] * D[i + 1]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n]; - for (i = 0; i < n; i++) { - C[i] = new Cubic((float) x[i], D[i], 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1], - 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1]); - } - return C; - } - - /** - * Calculates the natural cubic spline that interpolates y[0], y[1], ... - * y[n]. The first segment is returned as C[0].a + C[0].b*u + C[0].c*u^2 + - * C[0].d*u^3 0 <=u <1 the other segments are in C[1], C[2], ... C[n-1] - * - * @param n - * @param x - * @return Cubic[] - */ - Cubic[] calcNaturalCubic(int n, float[] x) { - float[] gamma = new float[n + 1]; - float[] delta = new float[n + 1]; - float[] D = new float[n + 1]; - int i; - /* - * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| - * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 - * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] by using - * row operations to convert the matrix to upper triangular and then - * back substitution. The D[i] are the derivatives at the knots. - */ - - gamma[0] = 1.0f / 2.0f; - for (i = 1; i < n; i++) { - gamma[i] = 1 / (4 - gamma[i - 1]); - } - gamma[n] = 1 / (2 - gamma[n - 1]); - - delta[0] = 3 * (x[1] - x[0]) * gamma[0]; - for (i = 1; i < n; i++) { - delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i]; - } - delta[n] = (3 * (x[n] - x[n - 1]) - delta[n - 1]) * gamma[n]; - - D[n] = delta[n]; - for (i = n - 1; i >= 0; i--) { - D[i] = delta[i] - gamma[i] * D[i + 1]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n]; - for (i = 0; i < n; i++) { - C[i] = new Cubic((float) x[i], D[i], 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1], - 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1]); - } - return C; - } - - /** - * Calculates a cubic spline polyline - * - * @param xpoints - * @param ypoints - * @return float[][] - */ - public float[][] calc(int[] xpoints, int[] ypoints) { - float[][] res = new float[2][0]; - if (xpoints.length > 2) { - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - // copy polygon points to the return array - res[0] = new float[p.npoints]; - res[1] = new float[p.npoints]; - - for (int i = 0; i < p.npoints; i++) { - res[0][i] = p.xpoints[i]; - res[1][i] = p.ypoints[i]; - } - - p = null; - } else { - // Need to convert to float[] - float[] xfs = new float[xpoints.length]; - float[] yfs = new float[ypoints.length]; - - for (int i = 0; i < xpoints.length; i++) { - xfs[i] = xpoints[i]; - yfs[i] = ypoints[i]; - } - - res[0] = xfs; - res[1] = yfs; - } - return res; - } - - /** - * Calculates a cubic spline polyline - * - * @param xpoints in float precision. - * @param ypoints in float precision. - * @return float[][] - */ - public float[][] calc(float[] xpoints, float[] ypoints) { - float[][] res = new float[2][0]; - if (xpoints.length > 2) { - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - // copy polygon points to the return array - res[0] = new float[p.npoints]; - res[1] = new float[p.npoints]; - - for (int i = 0; i < p.npoints; i++) { - res[0][i] = p.xpoints[i]; - res[1][i] = p.ypoints[i]; - } - - p = null; - } else { - res[0] = xpoints; - res[1] = ypoints; - } - return res; - } - - /** - * Calculates a float lat/lon cubic spline - * - * @param llpoints - * @param precision for dividing floating coordinates to become int, e.g - * 0.01 means spline to be calculated with coordinates * 100 - * @return float[] - */ - public double[] calc(double[] llpoints, double precision) { - double[] res; - if (llpoints.length > 4) { // 2 points - - int[] xpoints = new int[(int) (llpoints.length / 2)]; - int[] ypoints = new int[xpoints.length]; - for (int i = 0, j = 0; i < llpoints.length; i += 2, j++) { - xpoints[j] = (int) (llpoints[i] / precision); - ypoints[j] = (int) (llpoints[i + 1] / precision); - } - - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - res = new double[p.npoints * 2]; - for (int i = 0, j = 0; i < p.npoints; i++, j += 2) { - res[j] = (double) p.xpoints[i] * precision; - res[j + 1] = (double) p.ypoints[i] * precision; - } - - p = null; - } else { - res = llpoints; - } - return res; - } - - /** - * Returns the steps. - * - * @return int - */ - public int getSteps() { - return steps; - } - - /** - * Sets the number of points (steps) interpolated on the curve between the - * original points to draw it as a polyline. - * - * @param steps The steps to set - */ - public void setSteps(int steps) { - this.steps = steps > 0 ? steps : 12; - } - - /** - * Set the steps and return this object. - * - * @param steps - * @return this - */ - public NatCubicSpline withSteps(int steps) { - setSteps(steps); - return this; - } - - private int steps = 12; - - /** - * Moved from an outside class, the closed case of a NatCubicSpline. - */ - public static class CLOSED extends NatCubicSpline { - - /** - * Calculates the closed natural cubic spline that interpolates x[0], - * x[1], ... x[n]. The first segment is returned as C[0].a + C[0].b*u + - * C[0].c*u^2 + C[0].d*u^3 0 <=u <1 the other segments are in C[1], - * C[2], ... C[n] - * - * @see com.bbn.openmap.omGraphics.NatCubicSpline#calcNaturalCubic(int, - * int[]) - */ - Cubic[] calcNaturalCubic(int n, int[] x) { - float[] w = new float[n + 1]; - float[] v = new float[n + 1]; - float[] y = new float[n + 1]; - float[] D = new float[n + 1]; - float z, F, G, H; - int k; - /* - * We solve the equation [4 1 1] [D[0]] [3(x[1] - x[n]) ] |1 4 1 | - * |D[1]| |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | - * | . | | 1 4 1| | . | |3(x[n] - x[n-2])| [1 1 4] [D[n]] [3(x[0] - - * x[n-1])] by decomposing the matrix into upper triangular and - * lower matrices and then back substitution. See Spath "Spline - * Algorithms for Curves and Surfaces" pp 19--21. The D[i] are the - * derivatives at the knots. - */ - w[1] = v[1] = z = 1.0f / 4.0f; - y[0] = z * 3 * (x[1] - x[n]); - H = 4; - F = 3 * (x[0] - x[n - 1]); - G = 1; - for (k = 1; k < n; k++) { - v[k + 1] = z = 1 / (4 - v[k]); - w[k + 1] = -z * w[k]; - y[k] = z * (3 * (x[k + 1] - x[k - 1]) - y[k - 1]); - H -= G * w[k]; - F -= G * y[k - 1]; - G = -v[k] * G; - } - H -= (G + 1) * (v[n] + w[n]); - y[n] = F - (G + 1) * y[n - 1]; - - D[n] = y[n] / H; - D[n - 1] = y[n - 1] - (v[n] + w[n]) * D[n]; - /* This equation is WRONG! in my copy of Spath */ - for (k = n - 2; k >= 0; k--) { - D[k] = y[k] - v[k + 1] * D[k + 1] - w[k + 1] * D[n]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n + 1]; - for (k = 0; k < n; k++) { - C[k] = new Cubic((float) x[k], D[k], 3 * (x[k + 1] - x[k]) - 2 * D[k] - D[k + 1], - 2 * (x[k] - x[k + 1]) + D[k] + D[k + 1]); - } - C[n] = new Cubic((float) x[n], D[n], 3 * (x[0] - x[n]) - 2 * D[n] - D[0], 2 * (x[n] - x[0]) + D[n] + D[0]); - return C; - } - - /** - * @see com.bbn.openmap.omGraphics.NatCubicSpline#calc(int[], int[]) - */ - public float[][] calc(int[] xpoints, int[] ypoints) { - - int[] xpts = xpoints; - int[] ypts = ypoints; - int l = xpoints.length; - if (xpoints.length > 2) { - if (xpoints[0] == xpoints[l - 1] && ypoints[0] == ypoints[l - 1]) { - xpts = new int[l - 1]; - System.arraycopy(xpoints, 0, xpts, 0, l - 1); - ypts = new int[l - 1]; - System.arraycopy(ypoints, 0, ypts, 0, l - 1); - } - } - return super.calc(xpts, ypts); - } - - /** - * @see NatCubicSpline#calc(double[], double) - */ - public double[] calc(double[] llpoints, double precision) { - - double[] llpts = llpoints; - int l = llpoints.length; - if (l > 4) { - if (MoreMath.approximately_equal(llpoints[0], llpoints[l - 2]) - && MoreMath.approximately_equal(llpoints[1], llpoints[l - 1])) { - llpts = new double[l - 2]; - System.arraycopy(llpoints, 0, llpts, 0, l - 2); - } - } - - return super.calc(llpts, precision); - } - } - - /** - * A cubic polynomial - */ - class Cubic { - - float a, b, c, d; /* a + b*u + c*u^2 +d*u^3 */ - - /** - * Constructor. - * - * @param a - * @param b - * @param c - * @param d - */ - public Cubic(float a, float b, float c, float d) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - } - - /** - * evaluate cubic for this value. - * - * @param u - * @return float - */ - public float eval(float u) { - return (((d * u) + c) * u + b) * u + a; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAbstractLine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAbstractLine.java deleted file mode 100644 index e6b8ec4c7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAbstractLine.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Created on Jul 13, 2005 - * - * @author srosset - * @version $Revision: 1.3 $ - */ -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.geom.GeneralPath; - -/** - * The abstract base class of OMPoly and OMLine. - * - * @see OMLine - * @see OMPoly - * - * @author Sebastien Rosset - */ -public abstract class OMAbstractLine extends OMGraphicAdapter implements OMGraphic { - - /** - * X coordinate arrays of the projected points. - */ - protected float[][] xpoints = new float[0][0]; - - /** - * Y coordinate arrays of the projected points. - */ - protected float[][] ypoints = new float[0][0]; - - /** - * Number of segments to draw (used only for LINETYPE_GREATCIRCLE - * or LINETYPE_RHUMB lines). - */ - protected int nsegs = -1; - - /** - * The awt object representing the arrowhead. - */ - protected OMArrowHead arrowhead = null; - - /** - * Construct a default OMAbstractLine. - */ - public OMAbstractLine() { - super(); - } - - /** - * Construct an OMAbstractLine. Standard simple constructor that - * the child OMAbstractLine usually call. All of the other - * parameters get set to their default values. - * - * @param rType render type - * @param lType line type - * @param dcType declutter type - */ - public OMAbstractLine(int rType, int lType, int dcType) { - super(rType, lType, dcType); - } - - /** - * Construct an OMAbstractLine. More complex constructor that lets - * you set the rest of the parameters. - * - * @param rType render type - * @param lType line type - * @param dcType declutter type - * @param lc line color - * @param fc fill color - * @param sc select color - */ - public OMAbstractLine(int rType, int lType, int dcType, Color lc, Color fc, - Color sc) { - super(rType, lType, dcType, lc, fc, sc); - } - - /** - * Turn the ArrowHead on/off. The ArrowHead is placed on the - * finishing end. - * - * @param value on/off - */ - public void addArrowHead(boolean value) { - if (value) { - setArrowHead(new OMArrowHead(OMArrowHead.ARROWHEAD_DIRECTION_FORWARD, 100)); - } else { - arrowhead = null; - } - } - - /** - * Set the OMArrowHead object on the OMAbstractLine. - * - * @param omah - */ - public void setArrowHead(OMArrowHead omah) { - arrowhead = omah; - } - - public OMArrowHead getArrowHead() { - return arrowhead; - } - - public boolean hasArrowHead() { - return arrowhead != null; - } - - /** - * Turn the ArrowHead on. The ArrowHead is placed on the finishing - * end (OMArrowHead.ARROWHEAD_DIRECTION_FORWARD), beginning end - * (OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD), or both - * ends(OMArrowHead.ARROWHEAD_DIRECTION_BOTH). - * - * @param directionType which way to point the arrow head. - */ - public void addArrowHead(int directionType) { - setArrowHead(new OMArrowHead(directionType, 100)); - } - - /** - * Turn the ArrowHead on. The ArrowHead is placed on the finishing - * end (OMArrowHead.ARROWHEAD_DIRECTION_FORWARD), beginning end - * (OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD), or both - * ends(OMArrowHead.ARROWHEAD_DIRECTION_BOTH). - * - * @param directionType which way to point the arrow head. - * @param location where on the line to put the arrow head - 0 for - * the starting point, 100 for the end. - */ - public void addArrowHead(int directionType, int location) { - setArrowHead(new OMArrowHead(directionType, location)); - } - - /** - * Turn the ArrowHead on. The ArrowHead is placed on the finishing - * end (OMArrowHead.ARROWHEAD_DIRECTION_FORWARD), beginning end - * (OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD), or both - * ends(OMArrowHead.ARROWHEAD_DIRECTION_BOTH). - * - * @param directionType which way to point the arrow head. - * @param location where on the line to put the arrow head - 0 for - * the starting point, 100 for the end. - * @param tipWidth the width factor for the base of the arrowhead, - * on one side of the line. (Default is 5) - * @param arrowLength the length factor of the arrowhead, from the - * tip of the line to the base of the arrowhead. (Default - * is 20) - */ - public void addArrowHead(int directionType, int location, int tipWidth, - int arrowLength) { - setArrowHead(new OMArrowHead(directionType, location, tipWidth, arrowLength)); - } - - /** - * Arrowhead function, to find out the wing tip width. - */ - public int getWingTip() { - if (arrowhead != null) { - return arrowhead.getWingTip(); - } - return 0; - } - - /** - * Arrowhead function, to find out the arrowhead length. - */ - public int getWingLength() { - if (arrowhead != null) { - return arrowhead.getWingLength(); - } - return 0; - } - - /** - * Arrowhead function, to find out the arrowhead location. - */ - public int getArrowLocation() { - if (arrowhead != null) { - return arrowhead.getLocation(); - } - return 0; - } - - /** - * Arrowhead function, to find out the arrowhead direction. - */ - public int getArrowDirectionType() { - if (arrowhead != null) { - return arrowhead.getArrowDirectionType(); - } - return 0; - } - - /** - * This is a method that you can extend to create the GeneralPath - * for the arrowheads, if you want a different way of doing it. By - * default, it calls OMArrowHead.createArrowHeads(), using the - * different arrowhead variables set in the OMLine. - * - * @deprecated Create an OMArrowHead and set it on the - * OMAbstractLine instead. - */ - public GeneralPath createArrowHeads() { - return OMArrowHead.createArrowHeads(OMArrowHead.ARROWHEAD_DIRECTION_FORWARD, - 100, - this, - OMArrowHead.DEFAULT_WINGTIP, - OMArrowHead.DEFAULT_WINGLENGTH); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.omGraphics.OMGraphic#restore(com.bbn.openmap.omGraphics - * .OMGraphic) - */ - public void restore(OMGraphic source) { - super.restore(source); - if (source instanceof OMAbstractLine) { - OMAbstractLine lineSource = (OMAbstractLine) source; - OMArrowHead sah = lineSource.getArrowHead(); - if (sah != null) { - OMArrowHead destArrowHead = new OMArrowHead(sah.getArrowDirectionType(), sah.getLocation(), sah.getWingTip(), sah.getWingLength()); - setArrowHead(destArrowHead); - } - - nsegs = lineSource.nsegs; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAction.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAction.java deleted file mode 100755 index cffac513a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAction.java +++ /dev/null @@ -1,168 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMAction.java,v $ -// $RCSfile: OMAction.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 20:01:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - - -package com.bbn.openmap.omGraphics; - -import com.bbn.openmap.util.Debug; - -/** - * The OMAction class provides a way to describe one or more actions - * that should be performed on an OMGraphic. Each digit of the - * internal integer represents an action, and the action masks are - * defined in OMGraphicsConstances. The class holds the action value, - * and can respond to queries to check if certain masks are set, or - * can also set certain masks on the internal value. There are also - * static methods provided as a convenience. - */ -public class OMAction implements OMGraphicConstants { - /** - * The internal value of the action, representing 0 or more - * actions to be performed on a graphic, depending on the bits - * set. - */ - protected int value; - - /** - * Create an OMAction that represents no action (No bits are set). - */ - public OMAction() { - this.value = 0; - } - - /** - * Create an OMAction with the provided actions. - */ - public OMAction(int value) { - this.value = value; - } - - public void setValue(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - /** - * Set a particular mask bit in the internal value. - * @param mask an OMGraphicConstant mask constant. - * @return the changed integer value. - */ - public int setMask(int mask) { - value = OMAction.setMask(value, mask); - return value; - } - - /** - * Unset a particular mask bit in the internal value. - * @param mask an OMGraphicConstant mask constant. - * @return the changed integer value. - */ - public int unsetMask(int mask) { - value = unsetMask(value, mask); - return value; - } - - /** - * Return whether a mask value is set in the internal value. - * @param mask an OMGraphicConstant mask constant. - * @return whether the value bit is set on the internal value. - */ - public boolean isMask(int mask) { - return isMask(value, mask); - } - - /** - * Set a particular mask bit in the provided integer. - * @param value the integer to set the value(bit) on. - * @param mask an OMGraphicConstant mask constant. - * @return the changed integer value. - */ - public static int setMask(int value, int mask) { - return (value | mask); - } - - /** - * Unset a particular mask bit in the provided integer. - * @param value the integer to unset the value(bit) on. - * @param mask an OMGraphicConstant mask constant. - * @return the changed integer value. - */ - public static int unsetMask(int value, int mask) { - return (value & ~mask); - } - - /** - * Check to see if a mask bit is set in an integer. - * @param value the integer to check for the value(bit) on. - * @param mask an OMGraphicConstant mask constant. - * @return whether the value bit is set. - */ - public static boolean isMask(int value, int mask) { - // Used to be == 0, but this way it returns true if all of the - // mask bits are set. - if ((value & mask) < mask) { - return false; - } - return true; - } - - /** - * Provide a String that describes what the Action is all about. - */ - public String toString() { - StringBuffer sb = new StringBuffer("OMAction (").append(value).append(") [ "); - - if (value == 0) { - sb.append("add "); - } else { - if (isMask(RAISE_TO_TOP_GRAPHIC_MASK)) sb.append("raise_to_top "); - if (isMask(LOWER_TO_BOTTOM_GRAPHIC_MASK)) sb.append("lower_to_bottom "); - if (isMask(DELETE_GRAPHIC_MASK)) sb.append("delete "); - if (isMask(SELECT_GRAPHIC_MASK)) sb.append("select "); - if (isMask(DESELECT_GRAPHIC_MASK)) sb.append("deselect "); - if (isMask(DESELECTALL_GRAPHIC_MASK)) sb.append("deselect_all "); - if (isMask(ADD_GRAPHIC_MASK)) sb.append("add "); - if (isMask(UPDATE_GRAPHIC_MASK)) sb.append("update "); - if (isMask(RAISE_GRAPHIC_MASK)) sb.append("raise "); - if (isMask(LOWER_GRAPHIC_MASK)) sb.append("lower "); - if (isMask(SORT_GRAPHICS_MASK)) sb.append("sort "); - } - sb.append("]"); - return sb.toString(); - } - - public final static void main(String[] argv) { - - OMAction action = new OMAction(); - Debug.init(); - Debug.output("Setting add mask..."); - action.setMask(ADD_GRAPHIC_MASK); - if (action.isMask(ADD_GRAPHIC_MASK)) { - Debug.output("ADD mask set."); - } else { - Debug.output("ADD mask *NOT* set"); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArc.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArc.java deleted file mode 100644 index 65aab3105..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArc.java +++ /dev/null @@ -1,925 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMArc.java,v $ -// $RCSfile: OMArc.java,v $ -// $Revision: 1.13 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Graphic object that represents an arc. - *

- *

NOTE:

- * See the - * RESTRICTIONS on Lat/Lon polygons/polylines which apply to arcs as well. - * Not following the guidelines listed may result in ambiguous/undefined shapes! - * Similar assumptions apply to the other vector graphics that we define: polys, - * rects, lines. - *

- * These assumptions are virtually the same as those on the more generic OMPoly - * graphic type. - *

- * - * @see OMPoly - */ -public class OMArc extends OMGraphicAdapter implements OMGraphic { - - /** Horizontal pixel location of the center. */ - protected double x1 = 0; - /** Vertical pixel location of the center. */ - protected double y1 = 0; - - /** Horizontal pixel offset. */ - protected double off_x = 0; - /** Vertical pixel offset. */ - protected double off_y = 0; - /** - * Center point. - */ - protected Point2D center; - /** - * Radius of arc in radians. For LATLON arc. Note that the methods for this - * class use Decimal Degrees, or ask for a Length object to use for units. - * The radius is converted to radians for internal use. - */ - protected double radius = 0.0f; - /** - * The pixel horizontal diameter of the arc. For XY and OFFSET arcs. - */ - protected double width = 0; - /** - * The pixel vertical diameter of the arc. For XY and OFFSET arcs. - */ - protected double height = 0; - - /** - * The starting angle of the arc in decimal degrees. This is defined in - * decimal degrees because the java.awt.geom.Arc object wants it in decimal - * degrees. 0 is North? - */ - protected double start = 0.0f; - - /** - * The angular extent of the arc in decimal degrees. - */ - protected double extent = 360.0f; - - /** - * For Arcs, how the arc should be closed when rendered. Arc2D.OPEN is the - * default, Arc2D.PIE and Arc2D.CHORD are options. - * - * @see java.awt.geom.Arc2D - */ - protected int arcType = Arc2D.OPEN; - - /** - * Used to render arc in Cylindrical projections when the arc encompasses a - * pole. - */ - private transient GeneralPath polarShapeLine = null; - /** - * Indicates that the polarShapeLine should be used for rendering. - */ - private transient boolean correctFill = false; - /** Force the correct polar hack. */ - private transient boolean correctPolar = false; - - /** - * Number of vertices to draw for lat/lon poly-arcs. - */ - protected int nverts; - - /** - * The angle by which the circle/ellipse is to be rotated, in radians - */ - protected double rotationAngle = DEFAULT_ROTATIONANGLE; - - /** - * The simplest constructor for an OMArc, and it expects that all fields - * will be filled in later. Rendertype is RENDERTYPE_UNKNOWN. - */ - public OMArc() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Create an OMArc, positioned with a lat-lon center and x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees - */ - public OMArc(double latPoint, double lonPoint, int w, int h, double s, double e) { - this(latPoint, lonPoint, 0, 0, w, h, s, e); - } - - /** - * Create a OMArc, positioned with a x-y center with x-y axis. Rendertype is - * RENDERTYPE_XY. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param w horizontal diameter of arc, pixels - * @param h vertical diameter of arc, pixels - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees. For XY rendertype arcs, - * positive extents go in the counter-clockwise direction, matching - * the java.awt.geom.Arc2D convention. - */ - public OMArc(int x1, int y1, int w, int h, double s, double e) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - this.x1 = x1; - this.y1 = y1; - width = w; - height = h; - start = s; - extent = e; - } - - /** - * Create a OMArc, positioned at a Lat-lon location, x-y offset, x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of arc. - * @param lonPoint longitude of center of arc. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of arc, pixels. - * @param h vertical diameter of arc, pixels. - * @param s starting angle of arc, decimal degrees. - * @param e angular extent of arc, decimal degrees. For Offset rendertype - * arcs, positive extents go in the counter-clockwise direction, - * matching the java.awt.geom.Arc2D convention. - */ - public OMArc(double latPoint, double lonPoint, int offset_x1, int offset_y1, int w, int h, - double s, double e) { - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - center = new LatLonPoint.Double(latPoint, lonPoint); - off_x = offset_x1; - off_y = offset_y1; - width = w; - height = h; - start = s; - extent = e; - } - - /** - * Creates an OMArc with a Lat-lon center and a lat-lon axis. Rendertype is - * RENDERTYPE_LATLON. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees (converted to radians - * internally). - * @param s starting angle of arc, decimal degrees - * @param e angular extent of arc, decimal degrees. For LATLON rendertype - * arcs, positive extents go in the clockwise direction, matching the - * OpenMap convention in coordinate space. - */ - public OMArc(double latPoint, double lonPoint, double radius, double s, double e) { - - this(new LatLonPoint.Double(latPoint, lonPoint), radius, Length.DECIMAL_DEGREE, -1, s, e); - } - - /** - * Create an OMArc with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object. - * @param s starting angle of arc, decimal degrees. - * @param e angular extent of arc, decimal degrees. For LATLON rendertype - * arcs, positive extents go in the clockwise direction, matching the - * OpenMap convention in coordinate space. - */ - public OMArc(double latPoint, double lonPoint, double radius, Length units, double s, double e) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, units, -1, s, e); - } - - /** - * Create an OMArc with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of arc in decimal degrees - * @param lonPoint longitude of center of arc in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units. - * @param nverts number of vertices for the poly-arc (if < 3, value is - * generated internally) - * @param s starting angle of arc, decimal degrees. - * @param e angular extent of arc, decimal degrees. For LATLON rendertype - * arcs, positive extents go in the clockwise direction, matching the - * OpenMap convention in coordinate space. - */ - public OMArc(double latPoint, double lonPoint, double radius, Length units, int nverts, - double s, double e) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, units, nverts, s, e); - } - - /** - * Create an OMArc with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param center LatLon center of arc - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units for - * distance. - * @param nverts number of vertices for the poly-arc(if < 3, value is - * generated internally) - * @param s starting angle of arc, decimal degrees. - * @param e angular extent of arc, decimal degrees. For LATLON rendertype - * arcs, positive extents go in the clockwise direction, matching the - * OpenMap convention in coordinate space. - */ - public OMArc(LatLonPoint center, double radius, Length units, int nverts, double s, double e) { - - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - this.radius = units.toRadians(radius); - this.center = center; - this.nverts = nverts; - this.start = s; - this.extent = e; - } - - /** - * Get the x position of the center. This is always meaningful only if the - * render type is RENDERTYPE_XY or RENDERTYPE_OFFSET, and meaningful after - * generation if the RENDERTYPE_LATLON. - * - * @return x position of center. - */ - public int getX() { - return (int) x1; - } - - /** - * Get the y position of the center. This is always meaningful only if the - * render type is RENDERTYPE_XY or RENDERTYPE_OFFSET, and meaningful after - * generation if the RENDERTYPE_LATLON. - * - * @return y position of center. - */ - public int getY() { - return (int) y1; - } - - /** - * Get the x offset from the center. This is meaningful only if the render - * type is RENDERTYPE_OFFSET. - * - * @return x offset from center. - */ - public int getOffX() { - return (int) off_x; - } - - /** - * Get the y position of the center. This is meaningful only if the render - * type is RENDERTYPE_OFFSET. - * - * @return y offset from center. - */ - public int getOffY() { - return (int) off_y; - } - - /** - * Get the center LatLonPoint. This is meaningful only if the rendertype is - * RENDERTYPE_LATLON or RENDERTYPE_OFFSET. - * - * @return LatLonPoint position of center. - */ - public LatLonPoint getLatLon() { - return LatLonPoint.getDouble(center); - } - - /** - * Get the radius. This is meaningful only if the render type is - * RENDERTYPE_LATLON. - * - * @return double radius in decimal degrees - */ - public double getRadius() { - return Length.DECIMAL_DEGREE.fromRadians(radius); - } - - /** - * Get the horizontal pixel diameter of the arc. This is meaningful only if - * the render type is RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @return the horizontal pixel diameter of the arc. - */ - public int getWidth() { - return (int) width; - } - - /** - * Get the vertical pixel diameter of the arc. This is meaningful only if - * the render type is RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @return the vertical pixel diameter of the arc. - */ - public int getHeight() { - return (int) height; - } - - /** - * Get the starting angle of the arc. - * - * @return the starting angle of the arc in decimal degrees. - */ - public double getStartAngle() { - return start; - } - - /** - * Get the extent angle of the arc. - * - * @return the angular extent of the arc in decimal degrees. For LATLON - * rendertype arcs, positive extents go in the clockwise direction, - * matching the OpenMap convention in coordinate space. For XY and - * OFFSET rendertype arcs, positive extents go in the clockwise - * direction, matching the java.awt.geom.Arc2D convention. - */ - public double getExtentAngle() { - return extent; - } - - /** - * Get the number of vertices of the lat/lon arc. This will be meaningful - * only if the render type is RENDERTYPE_XY or RENDERTYPE_OFFSET and for - * LINETYPE_GREATARC or LINETYPE_RHUMB line types. - * - * @return int number of segment points - */ - public int getNumVerts() { - return nverts; - } - - /** - * Set the x position of the center. This will be meaningful only if the - * render type is RENDERTYPE_XY. - * - * @param value the x position of center. - */ - public void setX(int value) { - if (((int) x1) == value) - return; - x1 = value; - setNeedToRegenerate(true); - } - - /** - * Set the y position of the center. This will be meaningful only if the - * render type is RENDERTYPE_XY. - * - * @param value the y position of center. - */ - public void setY(int value) { - if (((int) y1) == value) - return; - y1 = value; - setNeedToRegenerate(true); - } - - /** - * Set the x offset from the center. This will be meaningful only if the - * render type is RENDERTYPE_OFFSET. - * - * @param value the x position of center. - */ - public void setOffX(int value) { - if (off_x == value) - return; - off_x = value; - setNeedToRegenerate(true); - } - - /** - * Set the y offset from the center. This will be meaningful only if the - * render type is RENDERTYPE_OFFSET. - * - * @param value the y position of center. - */ - public void setOffY(int value) { - if (off_y == value) - return; - off_y = value; - setNeedToRegenerate(true); - } - - /** - * Set the latitude and longitude of the center point. This is meaningful - * only if the rendertype is RENDERTYPE_LATLON or RENDERTYPE_OFFSET. - * - * @param lat latitude in decimal degrees - * @param lon longitude in decimal degrees - */ - public void setLatLon(double lat, double lon) { - setCenter(new LatLonPoint.Double(lat, lon)); - } - - /** - * Set the latitude and longitude of the center point. This is meaningful - * only if the rendertype is RENDERTYPE_LATLON or RENDERTYPE_OFFSET. - * - * @param p LatLonPoint of center. - */ - public void setCenter(LatLonPoint p) { - if (p.equals(center)) - return; - center = p; - setNeedToRegenerate(true); - } - - /** - * Get the center Point. - */ - public Point2D getCenter() { - return center; - } - - /** - * Set the radius. This is meaningful only if the render type is - * RENDERTYPE_LATLON. Note that while the radius is specified as decimal - * degrees, it only means the distance along the ground that that number of - * degrees represents at the equator, *NOT* a radius of a number of degrees - * around a certain location. There is a difference. - * - * @param radius float radius in decimal degrees - */ - public void setRadius(double radius) { - this.radius = Length.DECIMAL_DEGREE.toRadians(radius); - setNeedToRegenerate(true); - } - - /** - * Set the radius with units. This is meaningful only if the render type is - * RENDERTYPE_LATLON. - * - * @param radius float radius - * @param units Length specifying unit type. - */ - public void setRadius(double radius, Length units) { - this.radius = units.toRadians(radius); - setNeedToRegenerate(true); - } - - /** - * Set the horizontal pixel diameter of the arc. This is meaningful only if - * the render type is RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @param value the horizontal pixel diameter of the arc. - */ - public void setWidth(int value) { - if (width == value) - return; - width = value; - setNeedToRegenerate(true); - } - - /** - * Set the vertical pixel diameter of the arc. This is meaningful only if - * the render type is RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @param value the vertical pixel diameter of the arc. - */ - public void setHeight(int value) { - if (height == value) - return; - height = value; - setNeedToRegenerate(true); - } - - /** - * Set the starting angle the arc. - * - * @param value the starting angle of the arc in decimal degrees. - */ - public void setStart(double value) { - if (start == value) - return; - start = value; - setNeedToRegenerate(true); - } - - /** - * Set the angular extent of the arc. - * - * @param value the angular extent of the arc in decimal degrees. For LATLON - * rendertype arcs, positive extents go in the clockwise direction, - * matching the OpenMap convention in coordinate space. For XY and - * OFFSET rendertype arcs, positive extents go in the clockwise - * direction, matching the java.awt.geom.Arc2D convention. - */ - public void setExtent(double value) { - if (extent == value) - return; - extent = value; - setNeedToRegenerate(true); - } - - /** - * Set the number of vertices of the lat/lon arc. This is meaningful only if - * the render type is RENDERTYPE_LATLON and for LINETYPE_GREATARC or - * LINETYPE_RHUMB line types. If < 1, this value is generated internally. - * - * @param nverts number of segment points - */ - public void setNumVerts(int nverts) { - this.nverts = nverts; - } - - /** - * Set the ArcType, either Arc2D.OPEN (default), Arc2D.PIE or Arc2D.CHORD. - * - * @see java.awt.geom.Arc2D - */ - public void setArcType(int type) { - if (type == Arc2D.PIE || type == Arc2D.CHORD) { - arcType = type; - } else { - arcType = Arc2D.OPEN; - } - } - - /** - * Get the ArcType. - * - * @see java.awt.geom.Arc2D - */ - public int getArcType() { - return arcType; - } - - /** - * Set the angle by which the arc is to rotated. - * - * @param angle the number of radians the arc is to be rotated. Measured - * clockwise from horizontal. Positive numbers move the positive x - * axis toward the positive y axis. - */ - public void setRotationAngle(double angle) { - this.rotationAngle = angle; - setNeedToRegenerate(true); - } - - /** - * Get the current rotation of the arc. - * - * @return the arc rotation. - */ - public double getRotationAngle() { - return rotationAngle; - } - - public void setNeedToRegenerate(boolean value) { - super.setNeedToRegenerate(value); - if (value) { - polarShapeLine = null; - correctFill = false; - } - } - - /** - * Get the polar-fill-correction-flag. - * - * @return boolean - * @see #setPolarCorrection - */ - public boolean getPolarCorrection() { - return correctPolar; - } - - /** - * Set the polar-fill-correction-flag. We don't correctly render *filled* - * arcs/polygons which encompass a pole in Cylindrical projections. This - * method will toggle support for correcting this problem. You should only - * set this on arcs that encompass a pole and are drawn with a fill color. - * You do not need to set this if you're only drawing the arc outline. - * - * @param value boolean - * @see OMGraphic#setLinePaint - * @see OMGraphic#setFillPaint - */ - public void setPolarCorrection(boolean value) { - correctPolar = value; - setNeedToRegenerate(true); - } - - /** - * Helper function that helps the generate method figure out if the center - * point should be in the generate shape - if it's not, the code knows that - * there is a problem with the poles, and the polar correction code needs to - * be run. - */ - protected boolean shouldCenterBeInShape() { - // It won't be for CHORD or OPEN arcs - return arcType == Arc2D.PIE; - } - - /** - * Prepare the arc for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - polarShapeLine = null; - correctFill = false; - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMArc: null projection in generate!"); - return false; - } - - GeneralPath projectedShape = null; - - switch (renderType) { - case RENDERTYPE_OFFSET: - if (!proj.isPlotable(center)) { - setNeedToRegenerate(true);// HMMM not the best flag - return false; - } - - Point2D p1 = proj.forward(center, new Point2D.Double()); - - x1 = p1.getX() + off_x; - y1 = p1.getY() + off_y; - // Fall through... - case RENDERTYPE_XY: - double x = x1 - width / 2d; - double y = y1 - height / 2d; - - Shape arcShape = createArcShape(x, y, width, height); - - AffineTransform af = null; - if (rotationAngle != DEFAULT_ROTATIONANGLE) { - af = new AffineTransform(); - af.rotate(rotationAngle, x1, y1); - } - PathIterator pi = arcShape.getPathIterator(af); - projectedShape = new GeneralPath(); - projectedShape.append(pi, false); - - break; - - case RENDERTYPE_LATLON: - - GeneralPath specialCaseShape = null; - - if (proj instanceof GeoProj) { - - LatLonPoint llCenter = LatLonPoint.getDouble(center); - - Point2D p = proj.forward(llCenter.getY(), llCenter.getX(), new Point2D.Double()); - - x1 = p.getX(); - y1 = p.getY(); - - ArrayList coordLists = getCoordLists(((GeoProj) proj), llCenter, radius, nverts); - int size = coordLists.size(); - - for (int i = 0; i < size; i += 2) { - float[] xpoints = (float[]) coordLists.get(i); - float[] ypoints = (float[]) coordLists.get(i + 1); - - GeneralPath gp = createShape(xpoints, ypoints, (arcType != Arc2D.OPEN || (arcType == Arc2D.OPEN && !isClear(fillPaint)))); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - - correctFill = proj instanceof Cylindrical - && ((shouldCenterBeInShape() && projectedShape != null && !projectedShape.contains(x1, y1)) || correctPolar); - - if (correctFill) { - float[][] alts = doPolarFillCorrection(xpoints, ypoints, (llCenter.getRadLat() > 0f) ? -1 - : proj.getWidth() + 1); - - int gp2length = alts[0].length - 2; - - GeneralPath gp1 = createShape(alts[0], alts[1], true); - GeneralPath gp2 = createShape(alts[0], alts[1], 0, gp2length, false); - - if (specialCaseShape == null || polarShapeLine == null) { - specialCaseShape = gp1; - polarShapeLine = gp2; - } else { - specialCaseShape.append(gp1, false); - polarShapeLine.append(gp2, false); - } - } - } - - } else { - double degRadius = Math.toDegrees(radius); - // Create shape for non-GeoProj in lat/lon space... - specialCaseShape = new GeneralPath(proj.forwardShape(new Arc2D.Double(center.getX() - - degRadius, center.getY() - degRadius, 2 * degRadius, 2 * degRadius, start, extent, arcType))); - } - - if (specialCaseShape != null) { - projectedShape = specialCaseShape; - } - - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMArc.generate(): invalid RenderType"); - return false; - } - - setShape(projectedShape); - setLabelLocation(projectedShape, proj); - setNeedToRegenerate(false); - return true; - } - - /** - * An internal method designed to fetch the Shape to be used for an XY or - * OFFSET OMArc. This method is smart enough to take the calculated position - * information and make a call to Arc2D.Double with start, extent and - * arcType information. - */ - protected Shape createArcShape(double x, double y, double fwidth, double fheight) { - return new Arc2D.Double(x, y, fwidth, fheight, start, extent, arcType); - } - - /** - * An internal method designed to fetch the ArrayList for LATLON OMArcs. - * This method is smart enough to take the calculated position information - * and make a call to Projection.forwardArc() with start, extent and arcType - * information. - */ - protected ArrayList getCoordLists(GeoProj proj, LatLonPoint center, double radius, - int nverts) { - - int at = (arcType == Arc2D.OPEN && !isClear(fillPaint) ? Arc2D.CHORD : arcType); - - return proj.forwardArc(center, /* radians */ - true, radius, nverts, ProjMath.degToRad(start), ProjMath.degToRad(extent), at); - } - - /** - * Return the java.awt.Shape (GeneralPath) that reflects a arc that - * encompasses a pole. Used when the projection is Cylindrical. - * - * @return a GeneralPath object, or null if it's not needed (which is - * probably most of the time, if the arc doesn't include a pole or - * the projection isn't Cylindrical). - */ - public GeneralPath getPolarShapeLine() { - return polarShapeLine; - } - - /** - * Create alternate x,y coordinate arrays for rendering graphics the - * encompass a pole in the Cylindrical projection. - * - * @return a two dimensional array of points. The [0] array is the x points, - * the [1] is the y points. - */ - private float[][] doPolarFillCorrection(float[] xpoints, float[] ypoints, int y1) { - float[][] ret = new float[2][]; - - int len = xpoints.length; - float[] alt_xpts = new float[len + 2]; - float[] alt_ypts = new float[len + 2]; - System.arraycopy(xpoints, 0, alt_xpts, 0, len); - System.arraycopy(ypoints, 0, alt_ypts, 0, len); - alt_xpts[len] = alt_xpts[len - 1]; - alt_xpts[len + 1] = alt_xpts[0]; - alt_ypts[len] = y1; - alt_ypts[len + 1] = alt_ypts[len]; - - ret[0] = alt_xpts; - ret[1] = alt_ypts; - return ret; - } - - /** - * Paint the arc. - * - * @param g Graphics context to render into - */ - public void render(Graphics g) { - - if (!correctFill) { - // super will catch a null shape... - super.render(g); - } else { - - Shape s = getShape(); - - if (!isRenderable(s)) { - return; - } - - // The polarShapeLine will be there only if a shape was - // generated. - // This is getting kicked off because the arc is - // encompassing a pole, so we need to handle it a little - // differently. - if (shouldRenderFill()) { - setGraphicsForFill(g); - fill(g, s); - // draw texture - if (textureMask != null && textureMask != fillPaint) { - setGraphicsColor(g, textureMask); - fill(g, s); - } - } - - // BUG There is still a bug apparent when, in a - // cylindrical projection, and drawing a arc around the - // south pole. If the center of the arc is below any - // part of the edge of the arc, with the left lower dip - // of the arc on the screen, you get a line drawn from - // the right dip to the left dip. Not sure why. It's an - // unusual case, however. - if (shouldRenderEdge()) { - setGraphicsForEdge(g); - ((Graphics2D) g).draw(polarShapeLine); - } - } - } - - /** - * @see com.bbn.openmap.omGraphics.OMGraphic#clone() - */ - public Object clone() { - OMArc clone = (OMArc) super.clone(); - clone.setNeedToRegenerate(true); - if (center != null) - clone.center = (LatLonPoint) center.clone(); - return clone; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMArc) { - OMArc arc = (OMArc) source; - this.x1 = arc.x1; - this.y1 = arc.y1; - this.off_x = arc.off_x; - this.off_y = arc.off_y; - Point2D center = arc.getCenter(); - if (center != null) { - this.center = new LatLonPoint.Double(center); - } - this.radius = arc.radius; - this.width = arc.width; - this.height = arc.height; - this.start = arc.start; - this.extent = arc.extent; - this.arcType = arc.arcType; - this.nverts = arc.nverts; - this.rotationAngle = arc.rotationAngle; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAreaList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAreaList.java deleted file mode 100644 index bb02f252d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMAreaList.java +++ /dev/null @@ -1,168 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMAreaList.java,v $ -// $RCSfile: OMAreaList.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/01/10 16:58:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.geom.GeneralPath; -import java.io.Serializable; - -import com.bbn.openmap.proj.Projection; - -/** - * This class encapsulates a list of OMGeometries that are connected to form one - * area. Different types of vector OMGeometries can be combined and used to - * create a unique shape over the map. OMRasterObjects will contribute their - * shape/size, but not their images. The OMGeometries should be added in a - * clockwise format. - * - *

- * KNOWN ISSUES: OMAreaLists that wrap around the back of the earth and showing - * up on both edges of the map are not handled well - you'll end up with lines - * going horizontally across the map. It's on the to-do list to fix this. - */ -public class OMAreaList extends OMGeometryList implements Serializable { - - /** - * Construct an OMAreaList. - */ - public OMAreaList() { - super(10); - init(); - } - - /** - * Construct an OMAreaList with a capacity to be combined from an initial - * amount of OMGeometries. - * - * @param initialCapacity the initial capacity of the list - */ - public OMAreaList(int initialCapacity) { - super(initialCapacity); - init(); - } - - /** - * Construct an OMAreaList around a List of OMGeometries. The OMAreaList - * assumes that all the objects on the list are vector OMGeometries, and - * never does checking. Live with the consequences if you put other stuff in - * there. - * - * @param list List of vector OMGeometries. - */ - public OMAreaList(java.util.List list) { - addAll(list); - init(); - } - - /** - * Initialization that sets the OMAreaList, which is a modified - * OMGraphicList, to be vague and constructed in a first added, first used - * order. connectParts, a variable from OMGeometryList, is also set to true. - */ - protected void init() { - setVague(true); - setTraverseMode(LAST_ADDED_ON_TOP); - setConnectParts(true); - } - - /** - * Create the GeneralPath used for the internal Shape objects held by the - * OMGeometries added. With the OMAreaList, all of the components are - * combined to make a single area. So updateShape, which is called from - * super.generate(), calls appendShapeEdge() instead of appending each part - * Shape to the main Shape. This method closes off the GeneralPath Shape, so - * it will be considered a polygon. - */ - public synchronized boolean generate(Projection p, boolean forceProjectAll) { - boolean isGenerated = super.generate(p, forceProjectAll); - GeneralPath projectedShape = getShape(); - if (projectedShape != null) { - projectedShape.closePath(); - } - return isGenerated; - } - - /** - * Given a OMGeometry, it calls generate/regenerate on it, and then adds the - * GeneralPath shape within it to the OMGeometryList shape object. The edges - * of each part are combined to make one big polygon. - */ - protected void updateShape(OMGeometry geometry, Projection p, - boolean forceProject) { - if (forceProject) { - geometry.generate(p); - } else { - geometry.regenerate(p); - } - - if (geometry.isVisible()) { - GeneralPath gp = geometry.getShape(); - - if (gp == null) { - return; - } - - setShape(appendShapeEdge(getShape(), gp, connectParts)); - // save memory?? by deleting the shape in each part, since - // they are each contributing to the whole. - geometry.setShape((GeneralPath) null); - } - - setLabelLocation(getShape(), p); - } - - /** - * Overrides the OMGeometryList and OMGraphicList methods to just call - * _distance() on the internal shape object. - * - * @param x x coordinate - * @param y y coordinate - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @param resetSelect deselect any OMGraphic touched. - * @return OMDist - */ - public synchronized OMDist findClosest(double x, double y, - float limit, - boolean resetSelect) { - - OMDist omd = new OMDist(); - float currentDistance = Float.MAX_VALUE; - - // cannot select a graphic which isn't visible - if (!isVisible()) { - omd.omg = null; - } else { - if (resetSelect) - deselect(); - currentDistance = _distance(x, y); - } - - if (currentDistance < limit) { - omd.omg = this; - omd.d = currentDistance; - } - - return omd; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArrowHead.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArrowHead.java deleted file mode 100644 index 207d2be82..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMArrowHead.java +++ /dev/null @@ -1,545 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMArrowHead.java,v $ -// $RCSfile: OMArrowHead.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/12/08 21:12:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.io.Serializable; -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.omGraphics.geom.BasicGeometry; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.util.Debug; - -/** - * Basic implementation of arrowhead graphics. This class expects intimate - * knowledge of an OMLine, and is used to add Arrowhead shapes to the actual - * OMLine internal Shape object. You don't have to know about this class, just - * call the OMLine methods that create arrowheads and the OMLine will take care - * of the rest. - */ -public class OMArrowHead - implements Serializable { - - public static final int ARROWHEAD_DIRECTION_FORWARD = 0; - public static final int ARROWHEAD_DIRECTION_BACKWARD = 1; - public static final int ARROWHEAD_DIRECTION_BOTH = 2; - - // These are base settings. - protected static int DEFAULT_WINGTIP = 5; - protected static int DEFAULT_WINGLENGTH = 20; - - protected transient Shape shape = null; - protected int arrowDirectionType = ARROWHEAD_DIRECTION_FORWARD; - protected int location = 100; - protected int wingTip = 5; - protected int wingLength = 20; - - public OMArrowHead(int arrowDirectionType, int location) { - this(arrowDirectionType, location, DEFAULT_WINGTIP, DEFAULT_WINGLENGTH); - } - - public OMArrowHead(int arrowDirectionType, int location, int wingtip, int winglength) { - this.arrowDirectionType = arrowDirectionType; - setLocation(location); - this.wingTip = wingtip; - this.wingLength = winglength; - } - - public void generate(OMAbstractLine omal) { - if (wingTip > 0 && wingLength > 0 && omal != null) { - shape = createArrowHeads(arrowDirectionType, location, omal, wingTip, wingLength); - } else { - shape = null; - } - } - - public void render(Graphics g) { - if (shape != null) { - ((java.awt.Graphics2D) g).fill(shape); - } - } - - /** - * Create an arrowhead for the provided line - * - * @param arrowDirectionType ARROWHEAD_DIRECTION_FORWARD for the arrowhead - * pointing to the last coordinate of the OMLine, - * ARROWHEAD_DIRECTION_BACKWARD for the arrowhead pointing to the - * first coordinate in the OMLine, and ARROWHEAD_DIRECTION_BOTH for - * the arrowhead on both ends. - * @param location A number between 0-100, reflecting the percentage of the - * line traversed before placing the arrowhead. For - * ARROWHEAD_DIRECTION_FORWARD and a location of 100, the arrowhead - * will be placed all the way at the end of the line. For a location - * of 50, the arrowhead will be placed in the middle of the line. - * @param line OMLine to use to place arrowhead. - * @return the GeneralPath for the arrowhead. - */ - public static GeneralPath createArrowHeads(int arrowDirectionType, int location, OMAbstractLine line) { - return createArrowHeads(arrowDirectionType, location, line, DEFAULT_WINGTIP, DEFAULT_WINGLENGTH); - } - - /** - * Create an arrowhead for the provided line - * - * @param arrowDirectionType ARROWHEAD_DIRECTION_FORWARD for the arrowhead - * pointing to the last coordinate of the OMLine, - * ARROWHEAD_DIRECTION_BACKWARD for the arrowhead pointing to the - * first coordinate in the OMLine, and ARROWHEAD_DIRECTION_BOTH for - * the arrowhead on both ends. - * @param location A number between 0-100, reflecting the percentage of the - * line traversed before placing the arrowhead. For - * ARROWHEAD_DIRECTION_FORWARD and a location of 100, the arrowhead - * will be placed all the way at the end of the line. For a location - * of 50, the arrowhead will be placed in the middle of the line. - * @param line OMLine to use to place arrowhead. - * @param wingTip Number of pixels to push the side of the arrowhead away - * from the line. - * @param wingLength Number of pixels reflecting the arrowhead length. - * @return the GeneralPath for the arrowhead. - */ - public static GeneralPath createArrowHeads(int arrowDirectionType, int location, OMAbstractLine line, int wingTip, - int wingLength) { - - Point2D[] locPoints = locateArrowHeads(arrowDirectionType, location, line); - - if (locPoints == null) { - return null; - } - - Stroke stroke = line.getStroke(); - float lineWidth = 1f; - if (stroke instanceof BasicStroke) { - lineWidth = ((BasicStroke) stroke).getLineWidth(); - wingTip += lineWidth; - wingLength += lineWidth * 2; - } - - GeneralPath shape = createArrowHead(locPoints[0], locPoints[1], wingTip, wingLength); - - int numLocPoints = locPoints.length; - for (int i = 2; i < numLocPoints - 1; i += 2) { - shape.append(createArrowHead(locPoints[i], locPoints[i + 1], wingTip, wingLength), false); - } - - return shape; - } - - public static void addArrowHeads(int arrowDirectionType, int location, OMAbstractLine line) { - - Shape arrowHeads = createArrowHeads(arrowDirectionType, location, line); - if (arrowHeads != null) { - line.getShape().append(arrowHeads, false); - } - } - - protected static GeneralPath createArrowHead(Point2D from, Point2D to, int wingTip, int wingLength) { - double dx = to.getX() - from.getX(); - double dy = to.getY() - from.getY(); - - int dd = (int) DrawUtil.distance(to.getX(), to.getY(), from.getX(), from.getY()); - - if (dd < 6) - dd = 6; - - float[] xpts = new float[3]; - float[] ypts = new float[3]; - xpts[0] = (int) (to.getX() + (dy * (wingTip) - dx * wingLength) / dd); - ypts[0] = (int) (to.getY() + (dx * (-wingTip) - dy * wingLength) / dd); - xpts[1] = (int) (to.getX()); - ypts[1] = (int) (to.getY()); - xpts[2] = (int) (to.getX() + (dy * (-wingTip) - dx * wingLength) / dd); - ypts[2] = (int) (to.getY() + (dx * (wingTip) - dy * wingLength) / dd); - - return BasicGeometry.createShape(xpts, ypts, true); - } - - /** - * Create the ArrowHead objects for the lines, based on the settings. This - * function is called while OMLine is being generated. User's don't need to - * call this function. In fact, it assumes that generate() has been called - * (or is being called) on the OMLine. It adds the ArrowHeads to the - * GeneralPath Shape object. - */ - protected static Point2D[] locateArrowHeads(int arrowDirection, int arrowLocation, OMAbstractLine line) { - - // NOTE: xpoints[0] refers to the original copy of the - // xpoints, as opposed to the [1] copy, which gets used when the line - // needs to wrap around the screen and show up on the other - // side. Might have to think about the [1] points, and adding - // a arrowhead there if it shows up in the future. - - if (line.xpoints == null || line.xpoints.length == 0 || line.xpoints[0].length == 0) { - // line doesn't know where it is... - return null; - } - - int pointIndex = line.xpoints[0].length - 1; - if (Debug.debugging("arrowheads")) { - Debug.output("createArrowHeads(): Number of points = " + pointIndex); - } - - int drawingLinetype = OMLine.STRAIGHT_LINE; // default - if (pointIndex > 1) { - drawingLinetype = OMLine.CURVED_LINE; - } - - // Used as the index for points in the xy point array to use - // as anchors for the arrowheads - int[] end = new int[2]; - int[] start = new int[2]; - end[0] = pointIndex; - start[0] = 0; - end[1] = 0; - start[1] = pointIndex; - - // better names: - int origEnd = pointIndex; - int origStart = 0; - - int numArrows = 1; // default - if (arrowDirection == OMArrowHead.ARROWHEAD_DIRECTION_BOTH) { - numArrows = 2; - } - - // one for the start and end of each arrowhead (there could be - // two) - Point2D sPoint1 = new Point2D.Float(); - Point2D ePoint1 = new Point2D.Float(); - Point2D sPoint2 = new Point2D.Float(); - Point2D ePoint2 = new Point2D.Float(); - - // do we have to reverse the arrows? - - if (line instanceof OMLine) { - OMLine omLine = (OMLine) line; - if (omLine.arc != null && omLine.arc.getReversed() == true) { - if (arrowDirection == OMArrowHead.ARROWHEAD_DIRECTION_FORWARD) { - arrowDirection = OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD; - } else if (arrowDirection == OMArrowHead.ARROWHEAD_DIRECTION_BACKWARD) { - arrowDirection = OMArrowHead.ARROWHEAD_DIRECTION_FORWARD; - } - } - } - - List pointVec = new Vector(); - - // The for loop is needed in case the projection library - // created several projected versions of the line, those used - // for wrapping around to the other side of the map. - for (int lineNum = 0; lineNum < line.xpoints.length; lineNum++) { - float[] xpoints = line.xpoints[lineNum]; - float[] ypoints = line.ypoints[lineNum]; - - switch (drawingLinetype) { - - case OMLine.STRAIGHT_LINE: - Debug.message("arrowheads", "createArrowHeads(): Inside x-y space"); - float newEndX; - float newEndY; - float dx; - float dy; - float dd; - - // backwards arrow - - if (needBackwardArrow(arrowDirection)) { - - // need to have the newEndX/Y point at the - // original start. - - newEndX = xpoints[origStart]; - newEndY = ypoints[origStart]; - - if (arrowLocation != 100) { - // find out where the location should be, but - // in - // reverse. - dx = xpoints[origStart] - xpoints[origEnd]; - dy = ypoints[origStart] - ypoints[origEnd]; - int offset = 0; - // Straight up or down - if (dx == 0) { - // doesn't matter, start and end the same - newEndX = xpoints[origEnd]; - // calculate the percentage from start of line - offset = (int) ((float) dy * (arrowLocation / 100.0f)); - // set the end at the beginning... - newEndY = ypoints[origEnd] + offset; - - } else { - - dd = Math.abs((float) dy / (float) dx); - // If the line moves more x than y - if (Math.abs(dx) > Math.abs(dy)) { - // set the x - newEndX = xpoints[origEnd] + (int) ((float) dx * (arrowLocation / 100.0)); - // find the y for that x and set that - newEndY = ypoints[origEnd]; - offset = (int) ((float) Math.abs(xpoints[origEnd] - newEndX) * dd); - - if (dy < 0) { - newEndY -= offset; - } else { - newEndY += offset; - } - - } else { - // switch everything...set y end - newEndY = ypoints[origEnd] + (int) ((float) dy * (arrowLocation / 100.0)); - // initialize the x to beginning - newEndX = xpoints[origEnd]; - // calculate the difference x has to - // move based on y end - offset = (int) ((float) Math.abs(ypoints[origEnd] - newEndY) / dd); - // set the end - if (dx < 0) { - newEndX -= offset; - } else { - newEndX += offset; - } - } - - } - - } // if (arrowLocation != 100) - - if (start[1] < 0) { - start[1] = 0; - } - - // which point do we copy to? - if (numArrows == 2) { - // we copy the backwards arrow to - // sPoint2/ePoint2 - - sPoint2.setLocation(xpoints[origEnd], ypoints[origEnd]); - ePoint2.setLocation(newEndX, newEndY); - - } else { - // we copy the backwards arrow to - // sPoint1/ePoint1 - - sPoint1.setLocation(xpoints[origEnd], ypoints[origEnd]); - ePoint1.setLocation(newEndX, newEndY); - - } - - } // end if needBackwardArrow. - - if (needForwardArrow(arrowDirection)) { - - newEndX = xpoints[origEnd]; - newEndY = ypoints[origEnd]; - - if (arrowLocation != 100) { - // find out where the location should be. - dx = xpoints[origEnd] - xpoints[origStart]; - dy = ypoints[origEnd] - ypoints[origStart]; - int offset = 0; - // Straight up or down - if (dx == 0) { - // doesn't matter, start and end the same - newEndX = xpoints[origStart]; - // calculate the percentage from start of - // line - offset = (int) ((float) dy * (arrowLocation / 100.0f)); - // set the end at the beginning... - newEndY = ypoints[origStart] + offset; - - } else { - - dd = Math.abs((float) dy / (float) dx); - // If the line moves more x than y - if (Math.abs(dx) > Math.abs(dy)) { - // set the x - newEndX = xpoints[origStart] + (int) ((float) dx * (arrowLocation / 100.0f)); - // find the y for that x and set that - newEndY = ypoints[origStart]; - offset = (int) ((float) Math.abs(xpoints[origStart] - newEndX) * dd); - - if (dy < 0) { - newEndY -= offset; - } else { - newEndY += offset; - } - - } else { - // switch everything...set y end - newEndY = ypoints[origStart] + (int) ((float) dy * (arrowLocation / 100.0)); - // initialize the x to beginning - newEndX = xpoints[origStart]; - // calculate the difference x has to - // move - // based on y end - offset = (int) ((float) Math.abs(ypoints[origStart] - newEndY) / dd); - // set the end - if (dx < 0) { - newEndX -= offset; - } else { - newEndX += offset; - } - } - - } - - } // end if (arrowLocation != 100) - - // finally, copy the results to sPoint1/ePoint1 - - // no longer needed: if (start[0] < 0) { start[0] - // = 0; - // } - - sPoint1.setLocation(xpoints[origStart], ypoints[origStart]); - ePoint1.setLocation(newEndX, newEndY); - - } - - break; - case OMLine.CURVED_LINE: - Debug.message("arrowheads", "createArrowHeads(): Curved line arrowhead"); - - if (needBackwardArrow(arrowDirection)) { - - Debug.message("arrowheads", "createArrowHeads(): direction backward and"); - - // compute the backward index.... - int bindex = pointIndex - (int) ((float) pointIndex * (float) (arrowLocation / 100.0)); - if (bindex == 0) { - bindex = 1; - } - - if (numArrows == 2) { - // copy it to s/ePoint2 - - sPoint2.setLocation(xpoints[bindex], ypoints[bindex]); - ePoint2.setLocation(xpoints[bindex - 1], ypoints[bindex - 1]); - } else { - // copy it to s/ePoint1 - - sPoint1.setLocation(xpoints[bindex], ypoints[bindex]); - ePoint1.setLocation(xpoints[bindex - 1], ypoints[bindex - 1]); - - } - - } // end if (needBackwardArrow(arrowDirection)) - - if (needForwardArrow(arrowDirection)) { - - int findex = (int) ((float) pointIndex * (float) (arrowLocation / 100.0)); - if (findex == pointIndex) { - findex = findex - 1; - } - - if (findex > xpoints.length - 2) { - findex = xpoints.length - 2; - } - - sPoint1.setLocation(xpoints[findex], ypoints[findex]); - ePoint1.setLocation(xpoints[findex + 1], ypoints[findex + 1]); - - } // end if (needForwardArrow(arrowDirection)) - - break; - } // end switch(drawingLinetype) - - pointVec.add((Point2D) sPoint1.clone()); - pointVec.add((Point2D) ePoint1.clone()); - - if (numArrows > 1) { - pointVec.add((Point2D) sPoint2.clone()); - pointVec.add((Point2D) ePoint2.clone()); - } - - } - - Point2D[] ret = new Point2D[pointVec.size()]; - int i = 0; - for (Point2D point : pointVec) { - ret[i++] = point; - } - - return ret; - } - - private static boolean needBackwardArrow(int arrowDir) { - return (arrowDir == ARROWHEAD_DIRECTION_BACKWARD || arrowDir == ARROWHEAD_DIRECTION_BOTH); - } - - private static boolean needForwardArrow(int arrowDir) { - return (arrowDir == ARROWHEAD_DIRECTION_FORWARD || arrowDir == ARROWHEAD_DIRECTION_BOTH); - } - - public int getArrowDirectionType() { - return arrowDirectionType; - } - - public void setArrowDirectionType(int arrowDirectionType) { - this.arrowDirectionType = arrowDirectionType; - } - - public int getLocation() { - return location; - } - - public void setLocation(int location) { - if (location < 1) - this.location = 1; - else if (location > 100) - this.location = 100; - else - this.location = location; - } - - public Shape getShape() { - return shape; - } - - public void setShape(Shape shape) { - this.shape = shape; - } - - public int getWingLength() { - return wingLength; - } - - public void setWingLength(int wingLength) { - this.wingLength = wingLength; - } - - public int getWingTip() { - return wingTip; - } - - public void setWingTip(int wingTip) { - this.wingTip = wingTip; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMBitmap.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMBitmap.java deleted file mode 100644 index faa68ced6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMBitmap.java +++ /dev/null @@ -1,351 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMBitmap.java,v $ -// $RCSfile: OMBitmap.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.image.BufferedImage; -import java.io.Serializable; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The OMBitmap lets you create a two color image. The display color is the - * foreground color, and the fill color is the background color. OMColors can be - * used, and their transparency values will be implemented. - *

- * The array of bytes is used to create the picture. Each bit, representing a - * pixel, is examined, and the color is set to the display or fill color, - * depending on the bit value. - * - * There isn't a height and width restriction on OMBitmaps, but you do have to - * be careful about the byte array that is used for one. The OMBitmap is based - * on an X bitmap, not a Windows bmp file. Again, each bit of the bytes - * corresponds to a pixel. If the height and/or width of the bitmap isn't a - * multiple of 8, you have to round up the number of bytes used so that the - * excess bits are covered in that extra byte for the row. - *

- * - * So, for a 4x4 bitmap, you need: - * - *

- * 
- * 
- *  ooooxxxx|ooooxxxx|ooooxxxx|ooooxxxx -> 1 by 4 bytes, 4 bytes total
- * 
- * 
- * 
- * - * where x's are the bits being used for the bitmap ( and whether they are 1 or - * 0 dictates either foreground or background color), and o's are the leftover - * bits (they are ignored). The '|' are byte boundaries. - *

- * - * The bits, per byte, look like they are used in reverse order because they are - * - least significant bit, per byte, is used in that order. - *

- * - * For a 6x6 bitmap: - * - *

- * 
- * ooxxxxxx|ooxxxxxx|ooxxxxxx|ooxxxxxx|ooxxxxxx|ooxxxxxx -> 1 x 6
- * bytes, 6 bytes total
- * 
- * 
- * - * for a 10x10 bitmap: - * - *
- * 
- * xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx|xxxxxxxx|ooooooxx ->
- * 2 by 10 bytes, 20 bytes total
- * 
- * 
- * - * There is the ability to add a filter to the OMBitmap, to change it's - * appearance for rendering. The most common filter, which is included as a kind - * of default, is the scale filter. Filtering the OMRasterObject replaces the - * bitmap variable, which is the internal java.awt.Image used for rendering. - */ -public class OMBitmap extends OMRasterObject implements Serializable { - - /** Create empty, and add parameters later. */ - public OMBitmap() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Created a OMBitmap with a Lat/lon placement. - * - * @param lt latitude of upper left corner of bitmap. - * @param ln longitude of upper left corner of bitmap. - * @param w width of bitmap. - * @param h height of bitmap. - * @param bytes byte array of bitmap, each bit representing a pixel. - */ - public OMBitmap(double lt, double ln, int w, int h, byte[] bytes) { - - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - lat = lt; - lon = ln; - width = w; - height = h; - bits = bytes; - } - - /** - * Create an OMBitmap with a X/Y window placement. - * - * @param x1 window pixel x location of upper left corner of bitmap. - * @param y1 window pixel y location of upper left corner of bitmap. - * @param w width of bitmap. - * @param h height of bitmap. - * @param bytes byte array of bitmap, each bit representing a pixel. - */ - public OMBitmap(int x1, int y1, int w, int h, byte[] bytes) { - - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - x = x1; - y = y1; - width = w; - height = h; - bits = bytes; - } - - /** - * Create an OMBitmap, located at a Lat/lon with a X/Y offset placement. - * - * @param lt latitude of upper left corner of bitmap. - * @param ln longitude of upper left corner of bitmap. - * @param offset_x1 window pixel x location from ln of upper left corner of - * bitmap. - * @param offset_y1 window pixel y location from lt of upper left corner of - * bitmap. - * @param w width of bitmap. - * @param h height of bitmap. - * @param bytes byte array of bitmap, each bit representing a pixel. - */ - public OMBitmap(double lt, double ln, int offset_x1, int offset_y1, int w, int h, byte[] bytes) { - - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - lat = lt; - lon = ln; - x = offset_x1; - y = offset_y1; - width = w; - height = h; - bits = bytes; - } - - /** - * Set the bytes used to create the pixels used to create the image. Checks - * to see of the length*8 matches the height * width, but doesn't do - * anything if they don't match, except print out a warning. Make sure it - * does. - * - * @param values byte values containing bit pixel values. - */ - public void setBits(byte[] values) { - super.setBits(values); - if ((values.length * 8) != (height * width)) - Debug.output("OMBitmap: new byte[] size (" + +values.length + ") (*8) doesn't" - + " match [height*width (" + height * width + ")]"); - } - - /** - * Create the image pixels from the display color and the fill color values, - * and the bitmap bytes. All of these attributes should have been filled in. - * - * @return true if the pixels were successfully created. - */ - protected int[] computePixels(byte[] bits) { - - int foreground, background; - int npix, i, j, k, w; - int[] masks = { 1, 2, 4, 8, 16, 32, 64, 128 }; - - int nPixels = width * height; - - int[] iPixels = new int[nPixels]; - - if (bits == null || (bits.length * 8) < nPixels) { - System.err.println("OMBitmap.computePixels(): not enough bits!"); - return iPixels; - } - - // Init colors. - Paint paint = getDisplayPaint(); - if (paint instanceof Color) { - foreground = ((Color) paint).getRGB(); - } else { - foreground = Color.black.getRGB(); - } - - paint = getFillPaint(); - if (paint instanceof Color) { - background = ((Color) paint).getRGB(); - } else { - background = OMGraphic.clear.getRGB(); - } - - int defaultColor = 128 << 24; - - // Now, using the foreground and background colors, build a - // set of pixels by traversing bitwise through the bitmap data. - - // Determine the excess number of bits at the end of each row. - int excess = width % 8; // Remainder - - // And how many bytes will be used represent each row? - int bytes_per_row = width / 8; - - if (excess > 0) { - Debug.message("omGraphics", "OMBitmap.computePixels(): excess byte"); - bytes_per_row++; - } - - Debug.message("omGraphics", "OMBitmap.computePixels(): bits.length = " + bits.length); - - for (npix = 0, i = 0; i < height; i++) { // for each row - for (j = 0, w = 0; j < bytes_per_row; j++) { // for each - // row's byte - int idx = (i * bytes_per_row) + j; - for (k = 0; // for each byte's bits - (k < 8) & // bits per byte - (w < width) & // bits per row - (npix < nPixels); // bits per bitmap - k++, w++, npix++) { - int set = masks[k] & bits[idx]; - if (set > 0) { - iPixels[npix] = foreground; - } else { - iPixels[npix] = background; - } - } - } - } - - if (npix < nPixels - 1) { - for (i = npix; i < nPixels; i++) { - iPixels[i] = defaultColor; - } - } - - return iPixels; - } - - /** - * Create the rendered image from the pixel values. - * - * @return true if the OMBitmap has enough information and generates the - * rendered image successfully. - */ - public boolean generate(Projection proj) { - - // Position() sets the bitmap location on the screen!!!! - if (!position(proj)) { - Debug.message("omgraphic", "OMBitmap: positioning failed in generate!"); - return false; - } - - if (getNeedToRegenerate() || bitmap == null) { - int[] imagePixels = computePixels(bits); - pixels = imagePixels; - - BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - bi.setRGB(0, 0, width, height, imagePixels, 0, width); - setImage(bi); - } - - if (imageFilter != null) { - setImage(filterImage(bitmap)); - } - - setShape(); - - setNeedToRegenerate(false); - return true; - } - - /** - * This sets the bitmap to recompute the pixels if the foreground paint is - * changed. - * - * @param value the new line color. - */ - public void setLinePaint(Paint value) { - super.setLinePaint(value); - if (!selected) { - setNeedToRegenerate(true); - } - } - - /** - * This sets the bitmap to recompute the pixels if the foreground paint is - * changed. - * - * @param value the new select color. - */ - public void setSelectPaint(Paint value) { - super.setSelectPaint(value); - if (selected) { - setNeedToRegenerate(true); - } - } - - /** - * This sets the bitmap to recompute the pixels if the background color is - * changed. - * - * @param value the new background color - */ - public void setFillPaint(Paint value) { - super.setFillPaint(value); - setNeedToRegenerate(true); - } - - /** - * Set the selected attribute to true, and sets the color to the select - * color. - */ - public void select() { - if (!isSelected()) { - super.select(); - setNeedToRegenerate(true); - } - } - - /** - * Set the selected attribute to false, sets the color to the line color. - */ - public void deselect() { - if (isSelected()) { - super.deselect(); - setNeedToRegenerate(true); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMCircle.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMCircle.java deleted file mode 100644 index 5d6a3425b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMCircle.java +++ /dev/null @@ -1,197 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMCircle.java,v $ -// $RCSfile: OMCircle.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Graphic object that represents a circle or an ellipse. - *

- *

NOTE:

- * See the - * RESTRICTIONS on Lat/Lon polygons/polylines which apply to circles as - * well. Not following the guidelines listed may result in ambiguous/undefined - * shapes! Similar assumptions apply to the other vector graphics that we - * define: polys, rects, lines. - *

- * We currently do not allow LatLon ellipses, only XY. - *

- * These assumptions are virtually the same as those on the more generic OMPoly - * graphic type. - *

- * - * @see OMPoly - */ -public class OMCircle extends OMArc implements Serializable { - - /** - * The simplest constructor for an OMCircle, and it expects that all fields - * will be filled in later. Rendertype is RENDERTYPE_UNKNOWN. - */ - public OMCircle() { - super(); - } - - /** - * Create a OMCircle, positioned with a lat-lon center and x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - */ - public OMCircle(double latPoint, double lonPoint, int w, int h) { - this(latPoint, lonPoint, 0, 0, w, h); - } - - /** - * Create a OMCircle, positioned with a x-y center with x-y axis. Rendertype - * is RENDERTYPE_XY. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - */ - public OMCircle(int x1, int y1, int w, int h) { - super(x1, y1, w, h, 0f, 360f); - } - - /** - * Create a OMCircle, positioned at a Lat-lon location, x-y offset, x-y - * axis. Rendertype is RENDERTYPE_OFFSET. - * - * @param latPoint latitude of center of circle/ellipse. - * @param lonPoint longitude of center of circle/ellipse. - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - */ - public OMCircle(double latPoint, double lonPoint, int offset_x1, - int offset_y1, int w, int h) { - super(latPoint, lonPoint, offset_x1, offset_y1, w, h, 0f, 360f); - } - - /** - * Creates an OMCircle with a Lat-lon center and a lat-lon axis. Rendertype - * is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees (converted to radians - * internally). - */ - public OMCircle(double latPoint, double lonPoint, double radius) { - this(latPoint, lonPoint, radius, Length.DECIMAL_DEGREE, -1); - } - - /** - * Create an OMCircle with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object. - */ - public OMCircle(double latPoint, double lonPoint, double radius, - Length units) { - this(latPoint, lonPoint, radius, units, -1); - } - - /** - * Create an OMCircle with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units. - * @param nverts number of vertices for the poly-circle (if < 3, value is - * generated internally) - */ - public OMCircle(double latPoint, double lonPoint, double radius, - Length units, int nverts) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, units, nverts); - } - - /** - * Create an OMCircle with a lat/lon center and a physical distance radius. - * Rendertype is RENDERTYPE_LATLON. - * - * @param center LatLon center of circle - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units for - * distance. - * @param nverts number of vertices for the poly-circle(if < 3, value is - * generated internally) - */ - public OMCircle(LatLonPoint center, double radius, Length units, int nverts) { - super(center, radius, units, nverts, 0f, 360f); - } - - /** - * Helper function that helps the generate method figure out if the center - * point should be in the generate shape - if it's not, the code knows that - * there is a problem with the poles, and the polar correction code needs to - * be run. - */ - protected boolean shouldCenterBeInShape() { - return true; - } - - /** - * An internal method designed to fetch the Shape to be used for an XY or - * OFFSET OMCircles. This method is smart enough to take the calculated - * position information and make a call to Ellipse2D.Float. - */ - protected Shape createArcShape(float x, float y, float fwidth, float fheight) { - return new Ellipse2D.Float(x, y, fwidth, fheight); - } - - /** - * An internal method designed to fetch the ArrayList for LATLON OMCircles. - * This method is smart enough to take the calculated position information - * and make a call to Projection.forwardCircle. - */ - protected ArrayList getCoordLists(GeoProj proj, LatLonPoint center, - float radius, int nverts) { - return proj.forwardCircle(center, /* radians */ - true, radius, nverts, !isClear(fillPaint)); - } - - public boolean hasLineTypeChoice() { - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColor.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColor.java deleted file mode 100644 index 0d7c6bc80..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColor.java +++ /dev/null @@ -1,345 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMColor.java,v $ -// $RCSfile: OMColor.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; - -/** - * The OMColor exists to provide a way to make a color that can have - * some degree of transparency. The class lets you set the alpha value - * of the color which lets the color be invisible (0) to opaque (255). - * A while ago, the java.awt.Graphics class did not support - * transparency for drawing objects (OMLines, OMRects, OMCircles, - * etc.) but the transparent colors work for OMBitmap and OMRaster - * pixel values. - *

- * - * The OMColor object captures all calls that reference the - * package-internal java.awt.Color.value slot, and - * re-route them through the local argb slot. - *

- * - * NOTE concerning the OpenMap 4.0 release. As of 4.0, OpenMap now has - * a minimum jdk 1.2 requirement, which means that OMColor seems to - * duplicate java.awt.Color. We're going to keep this class around, - * however, in case someone needs a mutable Color. - * - * @see com.bbn.openmap.util.ColorFactory - */ -public class OMColor extends Color { - - /** - * Does this Java version support alpha for java.awt.Colors?. This - * is true if java.version >= 1.2, and false otherwise. - */ -// public final static transient boolean nativeAlpha; - - /** - * Default transparent color. Clear is a standard color that has - * all the bit values set to zero. This will give you a - * transparent pixel for images, and black for situations where - * transparency is not supported. - */ - public final static transient Color clear = new Color(0, true); - /** - * We need ALMOST_CLEAR so that the buffered image has a slight - * background to it if any of the layers are semi-transparent. If there - * is no background, the semi-transparent layers get washed out. Adding - * a touch of something to the background of the buffer lets them render - * normally. - */ - public final static transient Color ALMOST_CLEAR = new Color(0x01FFFFFF, true); - - /** - * A constructor object which can be used to create new - * java.awt.Colors for java.version >= 1.2. - */ -// public final static transient Constructor alphaValueConstructor; - - // check to see if alpha values are supported by the underlying - // java.awt.Color class. -// static { -// Color c; -// Constructor cons; -// boolean b; -// try { -// // we prefer the Java 2 solution (java.awt.Color supports -// // alpha) -// cons = Color.class.getConstructor(new Class[] { Integer.TYPE, -// Boolean.TYPE }); -// if (com.bbn.openmap.util.Debug.debugging("env")) { -// System.out.println("Alpha supported by java.awt.Color"); -// } -// c = (Color) cons.newInstance(new Object[] { new Integer(0), -// new Boolean(true) }); -// b = true; -// } catch (Exception e) { -// // this means we need to hack alphas. -// if (com.bbn.openmap.util.Debug.debugging("env")) { -// System.out.println("Alpha NOT SUPPORTED by java.awt.Color"); -// } -// cons = null; -// c = new OMColor(0); -// b = false; -// } -// clear = c; -// alphaValueConstructor = cons; -// nativeAlpha = b; -// } - - /** - * The 32bit ARGB value used. - */ - protected int argb; - - /** - * Create a color with the specified alpha, red, green, and blue - * components. The four arguments must each be in the range 0-255. // * - * - * @deprecated This function does not correctly override the JDK // * - * 1.2 java.awt.Color constructor with the same - * type/number of // * arguments. It should be - * OMColor(int r, int g, int b, int a). - */ - public OMColor(int a, int r, int g, int b) { - super(r, g, b);//HACK unnecessary?... - argb = (a << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) - | ((b & 0xFF) << 0); - } - - /** - * Create a color with the specified ARGB (Alpha, Red, Green, and - * Blue) values. The alpha component is in bits 24-31 of the - * argument, the red component is in bits 16-23 of the argument, - * the green component is in bits 8-15 of the argument, and the - * blue component is in bits 0-7. - * - * @param argb 32bit Hex ARGB value - */ - public OMColor(int argb) { - super(argb);//HACK unnecessary?... - this.argb = argb; - } - - /** - * Create a color with the specified red, green, and blue values, - * where each of the values is in the range 0.0-1.0. The value 0.0 - * indicates no contribution from the primary color component. The - * value 1.0 indicates the maximum intensity of the primary color - * component. // * - * - * @deprecated This function does not correctly override the JDK // * - * 1.2 java.awt.Color constructor with the same - * type/number of // * arguments. It should be - * OMColor(float r, float g, float b, float a). - */ - public OMColor(float a, float r, float g, float b) { - super(r, g, b);//HACK unnecessary?... - argb = (((int) (a * 255)) << 24) | (((int) (r * 255) & 0xFF) << 16) - | (((int) (g * 255) & 0xFF) << 8) - | (((int) (b * 255) & 0xFF) << 0); - } - - /** - * Get the ARGB (alpha, red, green and blue) value representing - * the color in the default RGB ColorModel. The alpha, red, green, - * and blue components of the color are each scaled to be a value - * between 0 (absence of the color) and 255 (complete - * saturation). Bits 24-31 of the returned integer are the alpha - * value, bits 16-23 are the red value, bit 8-15 are the green - * value, and bits 0-7 are the blue value. - * - * @return the integer value of the color. - */ - public int getRGB() { - return argb; - } - - /** - * Change the ARGB value of the color the input value. See the - * constructor comments that accepts the int parameter. - * - * @param value the transparency value between 0-255. - */ - public void setRGB(int value) { - argb = value; - } - - /** - * Return the red value of the color (the value of the 16-23 - * bits). - * - * @return the integer red value. - */ - public int getRed() { - return (argb >> 16) & 0xff; - } - - /** - * Set the red value of the OMColor. - * - * @param value the red value between 0-255. - */ - public void setRed(int value) { - argb = (argb & 0xFF00FFFF) | ((value & 0xff) << 16); - } - - /** - * Return the green value of the color (the value of the 8-15 - * bits). - * - * @return the integer green value. - */ - public int getGreen() { - return (argb >> 8) & 0xff; - } - - /** - * Set the green value of the OMColor. - * - * @param value the green value between 0-255. - */ - public void setGreen(int value) { - argb = (argb & 0xFFFF00FF) | ((value & 0xff) << 8); - } - - /** - * Return the blue value of the color (the value of the 0-7 bits). - * - * @return the integer blue value. - */ - public int getBlue() { - return argb & 0xff; - } - - /** - * Set the blue value of the OMColor. - * - * @param value the blue value between 0-255. - */ - public void setBlue(int value) { - argb = (argb & 0xFFFFFF00) | (value & 0xff); - } - - /** - * Return the transparency value of the color (the value of the - * 24-31 bits). - * - * @return the integer transparency value. - */ - public int getAlpha() { - return argb >>> 24; - } - - /** - * Set the transparency value of the OMColor. - * - * @param value the transparency value between 0-255. - */ - public void setAlpha(int value) { - argb = (argb & 0x00FFFFFF) | (value << 24); - } - - /** - * Return a color integer that has the transparency alpha value - * set to a value between 0-255. It cleans out the old alpha - * setting, and inserts the new one. - * - * @param colorValue the ARGB value of a color to be changed. - * @param transValue the integer (0-255) representing the - * opaqueness of the return value. 0 is transparent, 255 is - * opaque. - * @return the integer color value with the transparency value. - */ - public static int setTransparentValue(int colorValue, int transValue) { - return ((0x00FFFFFF & colorValue) | (transValue << 24)); - } - - /** - * Return a color value that has the transparency alpha value set - * to a percentage value between 0.0 and 1.0. - * - * @param colorValue the RGB value of a color to be changed. - * @param transValue the percentage of opaqueness (0-1) of the - * return value. 0 is transparent, 1 is opaque. - * @return the integer color value with the transparency value. - */ - public static int setTransparentValue(int colorValue, float transValue) { - return ((0x00FFFFFF & colorValue) | (((int) (transValue * 255)) << 24)); - } - - /** - * Checks if the color is transparent. The alpha bits (31-24) of - * the color determine this. - * - * @param value Color to be checked - * @return true if Color is null or transparent - */ - public static boolean isClear(Color value) { - return (value == null) || ((value.getRGB() >>> 24) == 0); - } - - /** - * Computes the hash code for this color. - * - * @return a hash code value for this object. - */ - public int hashCode() { - return getRGB(); - } - - /** - * Determines whether another object is equal to this color. - *

- * The result is true if and only if the argument - * is not null and is a Color object - * that has the same alpha, red, green, and blue values as this - * object. - * - * @param obj the Color to compare. - * @return true if the objects are the same, false otherwise. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - return (((Color) obj).getRGB() == this.getRGB()); - } - - /** - * Returns a string representation of this color. This method is - * intended to be used only for debugging purposes, and the - * content and format of the returned string may vary between - * implementations. The returned string may be empty but may not - * be null. - * - * @return a string representation of this color. - */ - public String toString() { - return "{" + super.toString() + " a=" + getAlpha() + "}"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColorChooser.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColorChooser.java deleted file mode 100644 index 3688e06c3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMColorChooser.java +++ /dev/null @@ -1,258 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $RCSfile: OMColorChooser.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/02/27 15:11:37 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.JColorChooser; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.colorchooser.ColorSelectionModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A wrapper class that pops up a modified JColorChooser class. The - * modification involves replacing the preview panel with a slider - * that modifies the alpha transparency part of the color. - * - * @author dietrick - * @author Oliver Hinds added preview panel to see color with - * transparency. - */ -public class OMColorChooser { - /** - * Displays a dialog that lets you change a color. Locks up the - * application until a choice is made, returning the chosen color, - * or null if nothing was chosen. - * - * @param component the source component. - * @param title the String title for the window. - * @param startingColor the initial color. - */ - public static Color showDialog(Component component, String title, - Color startingColor) { - Color initColor = startingColor != null ? startingColor : Color.white; - - final JColorChooser jcc = new JColorChooser(initColor); - ColorTracker ok = new ColorTracker(jcc); - - jcc.getSelectionModel().addChangeListener(ok); - /* WORKAROUND for Java bug #5029286 and #6199676 */ - // jcc.setPreviewPanel(ok.getTransparancyAdjustment(initColor.getAlpha())); - JComponent previewPanel = ok.getTransparancyAdjustment(initColor.getAlpha()); - previewPanel.setSize(previewPanel.getPreferredSize()); - previewPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 1, 0)); - jcc.setPreviewPanel(previewPanel); - - JDialog colorDialog = JColorChooser.createDialog(component, - title, - true, - jcc, - ok, - null); - colorDialog.setVisible(true); - return ok.getColor(); - } - - public static void main(String[] argv) { - Color testColor = showDialog(null, "Choose a Color", Color.white); - System.out.println("Color: " + testColor + ", hex value: " - + Integer.toHexString(testColor.getRGB())); - System.exit(0); - } -} - -/** - * A modified ActionListener used by the JColorChooser. Based on the - * one used in javax.swing.JColorChooser, but with the extended - * capability to handle transparancy. - */ - -class ColorTracker implements ActionListener, ChangeListener, Serializable { - - ColorRect preview; - JColorChooser chooser; - Color color; - int transparency; - private I18n i18n = Environment.getI18n(); - boolean isOK = false;//added because method getColor does not return null if action was not performed - - public ColorTracker(JColorChooser c) { - chooser = c; - preview = new ColorRect(chooser.getColor()); - } - - /** - * ActionListener interface. Sets the color from the - * JColorChooser. - */ - public void actionPerformed(ActionEvent e) { - color = chooser.getColor(); - setPreviewColor(color); - isOK = true; - } - - /** - * ChangeListener interface. Called when the color changes - */ - public void stateChanged(ChangeEvent e) { - if (!(e.getSource() instanceof ColorSelectionModel)) - return; - - setPreviewColor(((ColorSelectionModel) e.getSource()).getSelectedColor()); - } - - /** - * sets the preview color - */ - public void setPreviewColor(Color c) { - c = new Color(c.getRed(), c.getGreen(), c.getBlue(), transparency); - preview.setColor(c); - preview.repaint(); - color = c; - } - - /** - * Get the Color set in the JColorChooser, and set the alpha value - * based on the transparency slider. - */ - public Color getColor() { - if (!isOK) { - return null; - } - if (color != null) { - color = new Color(color.getRed(), color.getGreen(), color.getBlue(), transparency); - } - return color; - } - - /** - * Create the Swing components that let you change the - * transparency of the color received from the JColorChooser. - * - * @param initialValue the starting alpha value for the color. - * @return JComponent to adjust the transparency value. - */ - public JComponent getTransparancyAdjustment(int initialValue) { - transparency = initialValue; - // This sets initial transparency effect in preview... - setPreviewColor(preview.getColor()); - JPanel slidePanel = new JPanel(); - Box slideBox = Box.createHorizontalBox(); - - JSlider opaqueSlide = new JSlider(JSlider.HORIZONTAL, 0/* min */, 255/* max */, initialValue/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - String opaqueLabel = i18n.get(ColorTracker.class, "opaque", "opaque"); - String clearLabel = i18n.get(ColorTracker.class, "clear", "clear"); - if (opaqueLabel == null || opaqueLabel.length() == 0) { - // translations are too long :( - dict.put(new Integer(126), new JLabel(clearLabel)); - } else { - dict.put(new Integer(50), new JLabel(clearLabel)); - dict.put(new Integer(200), new JLabel(opaqueLabel)); - } - //commented because polish translations are too long - opaqueSlide.setLabelTable(dict); - opaqueSlide.setPaintLabels(true); - opaqueSlide.setMajorTickSpacing(50); - opaqueSlide.setPaintTicks(true); - opaqueSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - transparency = slider.getValue(); - } - // This sets transparency in preview... - setPreviewColor(preview.getColor()); - } - }); - - preview.setPreferredSize(new Dimension(100, slideBox.getHeight())); - slideBox.add(preview); - slideBox.add(Box.createGlue()); - slideBox.add(opaqueSlide); - slideBox.add(Box.createGlue()); - slidePanel.add(slideBox); - // You know what, it just has to be something, so the - // UIManager will think it's valid. It will get resized as - // appropriate when the JDialog gets packed. - slidePanel.setSize(new Dimension(50, 50)); - return slidePanel; - } - -} - -// class to display the currently selected color - -class ColorRect extends JPanel { - Color c; // color to display - - /** - * constructor - */ - public ColorRect(Color _c) { - setBackground(Color.white); - c = _c; - } - - /** - * set the color to tht specified - * - * @param _c color to paint - */ - public void setColor(Color _c) { - c = _c; - } - - /** - * get the color - */ - public Color getColor() { - return c; - } - - /** - * paints this panel - */ - public void paint(Graphics g) { - super.paint(g); - - g.setColor(c); - ((Graphics2D) g).fill(g.getClip()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDecoratedSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDecoratedSpline.java deleted file mode 100644 index 593917774..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDecoratedSpline.java +++ /dev/null @@ -1,247 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMDecoratedSpline.java,v $ -//$RCSfile: OMDecoratedSpline.java,v $ -//$Revision: 1.8 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Shape; -import java.awt.geom.GeneralPath; - -import com.bbn.openmap.omGraphics.awt.Revertable; -import com.bbn.openmap.omGraphics.awt.ShapeDecorator; -import com.bbn.openmap.util.Debug; - -/** - * A decorated splined OMPoly. Decoration list is empty, but accessible via - * getDecorator() Code from OMPoly, few changes : render() just need to delegate - * the drawing of the polyline to the ShapeDecorator - * - * @author Eric LEPICIER - * @version 27 juil. 2002 - */ -public class OMDecoratedSpline - extends OMSpline - implements Revertable { - - private ShapeDecorator decorator = new ShapeDecorator(); - - /** - * Constructor. - */ - public OMDecoratedSpline() { - super(); - initDecorations(); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - */ - public OMDecoratedSpline(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - initDecorations(); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - * @param nsegs - */ - public OMDecoratedSpline(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - initDecorations(); - } - - /** - * Constructor. - * - * @param xypoints - */ - public OMDecoratedSpline(int[] xypoints) { - super(xypoints); - initDecorations(); - } - - /** - * Constructor. - * - * @param xPoints - * @param yPoints - */ - public OMDecoratedSpline(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - initDecorations(); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xypoints - * @param cMode - */ - public OMDecoratedSpline(double latPoint, double lonPoint, int[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - initDecorations(); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xPoints - * @param yPoints - * @param cMode - */ - public OMDecoratedSpline(double latPoint, double lonPoint, int[] xPoints, int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - initDecorations(); - } - - /** - * Paint the poly. This works if generate() has been successful. Same code - * than OMPoly, just delegates the drawing of the polyline to the - * ShapeDecorator - * - * @param g java.awt.Graphics to paint the poly onto. - */ - public void render(Graphics g) { - if (decorator == null) { - super.render(g); - return; - } - - Shape projectedShape = getShape(); - if (projectedShape != null) { - decorator.draw(g, projectedShape); - return; - } - - if (getNeedToRegenerate() || !isVisible()) - return; - - // safety: grab local reference of projected points - float[][] xpts = xpoints; - float[][] ypts = ypoints; - int len = xpts.length; - - Paint displayPaint = getDisplayPaint(); - Paint fillPaint = getFillPaint(); - boolean isFillClear = isClear(fillPaint); - boolean isLineClear = isClear(displayPaint); - - // If shapes are null, then we have to do things the old way. - try { - for (int i = 0; i < len; i++) { - float[] _x = xpts[i]; - float[] _y = ypts[i]; - - // render polygon - if (isPolygon()) { - - // fill main polygon - if (!isFillClear) { - // set the interior coloring parameters - setGraphicsForFill(g); - GeneralPath poly = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - poly.moveTo(_x[0], _y[0]); - } else { - poly.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).fill(poly); - // g.fillPolygon(_x, _y, _x.length); - } - - // only draw outline if different color - if (!isLineClear || !edgeMatchesFill) { - setGraphicsForEdge(g); - // for some reason, this used to be - // drawPolygon - decorator.draw(g, _x, _y); - } - } - - // render polyline - else { - // draw main outline - setGraphicsForEdge(g); - decorator.draw(g, _x, _y); - } - } - } catch (Exception e) { - // Trying to catch any clipping problems from within a JRE - Debug.output("OMDecoratedSpline: caught Java rendering exception\n" + e.getMessage()); - } - } - - /** - * Returns the decorator. - * - * @return ShapeDecorator - */ - public ShapeDecorator getDecorator() { - return decorator; - } - - /** - * Sets the decorator. - * - * @param decorator The decorator to set - */ - public void setDecorator(ShapeDecorator decorator) { - this.decorator = decorator; - } - - /** - * Called by constructor, may be overriden. - */ - protected void initDecorations() { - } - - /** - * @see com.bbn.openmap.omGraphics.awt.Revertable#revert() - */ - public void revert() { - decorator.revert(); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMDecoratedSpline) { - OMDecoratedSpline spline = (OMDecoratedSpline) source; - this.decorator = spline.decorator; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDistance.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDistance.java deleted file mode 100644 index 2ca375f28..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMDistance.java +++ /dev/null @@ -1,370 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMDistance.java,v $ -// $RCSfile: OMDistance.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Paint; -import java.awt.geom.AffineTransform; -import java.text.DecimalFormat; -import java.util.Iterator; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.LineCoordinateGenerator; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * OMGraphic object that represents a polyline, labeled with distances. - */ -public class OMDistance extends OMPoly { - - protected OMGraphicList labels = new OMGraphicList(); - protected OMGraphicList points = new OMGraphicList(); - - protected Length distUnits = Length.NM; - public DecimalFormat df = new DecimalFormat("0.#"); - /** - * Paint used for labels - */ - protected Paint labelPaint; - /** - * Font used for labels - */ - protected Font labelFont; - - /** - * Construct a default OMDistance. - */ - public OMDistance() { - super(); - setRenderType(RENDERTYPE_LATLON); - } - - /** - * Create an OMDistance from a list of double lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public OMDistance(double[] llPoints, int units, int lType, Length distanceUnits) { - this(llPoints, units, lType, -1, distanceUnits); - } - - /** - * Create an OMDistance from a list of double lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is - * generated internally) - */ - public OMDistance(double[] llPoints, int units, int lType, int nsegs, Length distanceUnits) { - super(llPoints, units, lType, nsegs); - setDistUnits(distanceUnits); - } - - /** - * Set the Length object used to represent distances. - */ - public void setDistUnits(Length distanceUnits) { - distUnits = distanceUnits; - } - - /** - * Get the Length object used to represent distances. - */ - public Length getDistUnits() { - return distUnits; - } - - public void setLocation(double[] llPoints, int units) { - this.units = OMGraphic.RADIANS; - if (units == OMGraphic.DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(llPoints); - } - rawllpts = llPoints; - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_LATLON); - } - - public void createLabels() { - labels.clear(); - points.clear(); - - if (rawllpts == null) { - return; - } - if (rawllpts.length < 4) { - return; - } - - Geo lastGeo = new Geo(rawllpts[0], rawllpts[1], units == DECIMAL_DEGREES); - double latpnt = rawllpts[0]; - double lonpnt = rawllpts[1]; - if (units == RADIANS) { - latpnt = ProjMath.radToDeg(latpnt); - lonpnt = ProjMath.radToDeg(lonpnt); - } - points.add(new OMPoint(latpnt, lonpnt, 1)); - Geo curGeo = null; - double cumulativeDist = 0.0; - for (int p = 2; p < rawllpts.length; p += 2) { - if (curGeo == null) { - curGeo = new Geo(rawllpts[p], rawllpts[p + 1], units == DECIMAL_DEGREES); - } else { - if (units == DECIMAL_DEGREES) { - curGeo.initialize(rawllpts[p], rawllpts[p + 1]); - } else { - curGeo.initializeRadians(rawllpts[p], rawllpts[p + 1]); - } - } - - double dist = getDist(lastGeo, curGeo); - cumulativeDist += dist; - - labels.add(createLabel(lastGeo, curGeo, dist, cumulativeDist, distUnits)); - latpnt = rawllpts[p]; - lonpnt = rawllpts[p + 1]; - if (units == RADIANS) { - latpnt = ProjMath.radToDeg(latpnt); - lonpnt = ProjMath.radToDeg(lonpnt); - } - - points.add(new OMPoint(latpnt, lonpnt, 1)); - lastGeo.initialize(curGeo); - } - } - - /** - * Get an OMText label for a segments between the given lat/lon points whose - * given distance and cumulative distance is specified. - */ - public OMText createLabel(Geo g1, Geo g2, double dist, double cumulativeDist, Length distanceUnits) { - Geo mid; - switch (getLineType()) { - case LINETYPE_STRAIGHT: - double lat = (g1.getLatitude() + g2.getLatitude()) / 2.0; - double lon = (g1.getLongitude() + g2.getLongitude()) / 2.0; - mid = new Geo(lat, lon); - break; - case LINETYPE_RHUMB: - System.err.println("Rhumb distance calculation not implemented."); - case LINETYPE_GREATCIRCLE: - case LINETYPE_UNKNOWN: - default: - mid = g1.midPoint(g2); - } - - // String text = ((int)dist) + " (" + ((int)cumulativeDist) + - // ")"; - - String text = (df.format(distanceUnits.fromRadians(dist))) + " (" - + (df.format(distanceUnits.fromRadians(cumulativeDist))) + ") " + distanceUnits.getAbbr(); - OMText omtext = new OMText(mid.getLatitude(), mid.getLongitude(), text, OMText.JUSTIFY_LEFT); - // omtext.setLinePaint(new Color(200, 200, 255)); - return omtext; - } - - /** - * Return the distance between that lat/lons defined in radians. The - * returned value is in radians and LINETYPE is taken into consideration. - * LINETYPE_STRAIGHT returns same as LINETYPE_GREATCIRCLE, the ground - * distance between all nodes and not the degree distance of the lines. - */ - public double getDist(Geo g1, Geo g2) { - switch (getLineType()) { - case LINETYPE_RHUMB: - - double[] coords = new double[] { g1.getLatitudeRadians(), g1.getLongitudeRadians(), g2.getLatitudeRadians(), - g2.getLongitudeRadians() }; - return ProjMath.distance(LineCoordinateGenerator.fromRadians(coords).rhumbLineDoubles()); - - case LINETYPE_STRAIGHT: - case LINETYPE_GREATCIRCLE: - case LINETYPE_UNKNOWN: - default: - return g1.distance(g2); - } - } - - /** - * Prepare the poly for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - boolean ret = super.generate(proj); - createLabels(); - labels.generate(proj); - points.generate(proj); - return ret; - } - - /** - * Flag used by the EditableOMDistance to do quick movement paints in a - * cleaner way. - */ - protected boolean paintOnlyPoly = false; - - /** - * Paint the poly. This works if generate() has been successful. - * - * @param g java.awt.Graphics to paint the poly onto. - */ - public void render(Graphics g) { - super.render(g); - - if (!paintOnlyPoly) { - renderPoints(g); - renderLabels(g); - } - } - - /** - * render points - */ - protected void renderPoints(Graphics g) { - Paint pointPaint = getLabelPaint(); - - for (Iterator it = points.iterator(); it.hasNext();) { - OMGraphic point = (OMPoint) it.next(); - point.setLinePaint(pointPaint); - point.setFillPaint(pointPaint); - point.render(g); - } - } - - /** - * render labels - */ - protected void renderLabels(Graphics g) { - Font f = getFont(); - Paint labelPaint = getLabelPaint(); - Paint mattingPaint = getMattingPaint(); - boolean isMatted = isMatted(); - for (Iterator it = labels.iterator(); it.hasNext();) { - OMText text = (OMText) it.next(); - text.setFont(f); - text.setLinePaint(labelPaint); - if (isMatted) { - text.setFillPaint(mattingPaint); - } - text.render(g); - } - } - - /** - * Set paint used for labels - * - * @param lPaint paint used for labels - */ - public void setLabelPaint(Paint lPaint) { - labelPaint = lPaint; - } - - /** - * @return normal paint used for labels - */ - public Paint getLabelPaint() { - if (labelPaint == null) { - return getLinePaint(); - } - return labelPaint; - } - - /** - * @param font font used for labels - */ - public void setFont(Font font) { - if (font == null) { - labelFont = OMText.DEFAULT_FONT; - } else { - labelFont = font; - } - } - - /** - * @return font used for labels - */ - public Font getFont() { - if (labelFont == null) { - labelFont = OMText.DEFAULT_FONT; - } - return labelFont; - } - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - stream.defaultWriteObject(); - stream.writeObject(distUnits.getAbbr()); - } - - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - stream.defaultReadObject(); - distUnits = Length.get((String) stream.readObject()); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMDistance) { - OMDistance dist = (OMDistance) source; - this.labels = DeepCopyUtil.deepCopy(dist.labels); - this.points = DeepCopyUtil.deepCopy(dist.points); - this.distUnits = dist.distUnits; - this.df = new DecimalFormat(dist.df.toLocalizedPattern()); - this.labelPaint = dist.labelPaint; - if (dist.labelFont != null) { - this.labelFont = dist.labelFont.deriveFont(AffineTransform.TYPE_IDENTITY); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMEllipse.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMEllipse.java deleted file mode 100644 index cf24aa67c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMEllipse.java +++ /dev/null @@ -1,277 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMEllipse.java,v $ -// $RCSfile: OMEllipse.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.util.ArrayList; - -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The OMEllipse is a lat/lon ellipse, made up of a center lat/lon point, and - * some length described for the x and y axis. If you want to create ellipses in - * X/Y space, use OMCircle. Ellipse arcs are not available yet, and this class - * doesn't really work with the EditableOMCircle. You can use EditableOMCircles - * to move and delete OMEllipses, but you can't change the axis dimensions. - */ -public class OMEllipse extends OMCircle { - - protected double majorAxisSpan; - protected double minorAxisSpan; - protected transient double[] rawllpts; - - /** - * Create a OMEllipse, positioned with a lat-lon center and a lat-lon axis. - * Rendertype is RENDERTYPE_LATLON. - * - * @param centerPoint latitude/longitude of center point, decimal degrees - * @param majorAxisSpan horizontal diameter of circle/ellipse, pixels - * @param minorAxisSpan vertical diameter of circle/ellipse, in given units - * @param units com.bbn.openmap.proj.Length object. - * @param rotateAngle angle of rotation in Radians - */ - public OMEllipse(LatLonPoint centerPoint, double majorAxisSpan, double minorAxisSpan, - Length units, double rotateAngle) { - setRenderType(RENDERTYPE_LATLON); - setLineType(LINETYPE_GREATCIRCLE); - - setCenter(centerPoint); - setAxis(majorAxisSpan, minorAxisSpan, units); - setRotationAngle(rotateAngle); - } - - /** - * Create a OMEllipse, positioned with a x-y center with x-y axis. - * Rendertype is RENDERTYPE_XY. - * - * @param x1 window position of center point from left of window, in pixels - * @param y1 window position of center point from top of window, in pixels - * @param majorAxisSpan horizontal diameter of circle/ellipse, pixels - * @param minorAxisSpan vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - */ - public OMEllipse(int x1, int y1, int majorAxisSpan, int minorAxisSpan, double rotateAngle) { - super(x1, y1, majorAxisSpan, minorAxisSpan); - setRotationAngle(rotateAngle); - } - - /** - * Create a OMEllipse, positioned with a lat-lon center and x-y axis. - * Rendertype is RENDERTYPE_OFFSET. - * - * @param centerPoint latitude/longitude of center point, decimal degrees - * @param w horizontal diameter of circle/ellipse, pixels - * @param h vertical diameter of circle/ellipse, pixels - * @param rotateAngle angle of rotation in Radians - */ - public OMEllipse(LatLonPoint centerPoint, int w, int h, double rotateAngle) { - // Use circle constructor - super(centerPoint.getY(), centerPoint.getX(), 0, 0, w, h); - setRotationAngle(rotateAngle); - } - - /** - * Create a OMEllipse, positioned at a Lat-lon location, x-y offset, x-y - * axis. Rendertype is RENDERTYPE_OFFSET. - * - * @param centerPoint latitude/longitude of center point, decimal degrees - * @param offset_x1 # pixels to the right the center will be moved from - * lonPoint. - * @param offset_y1 # pixels down that the center will be moved from - * latPoint. - * @param w horizontal diameter of circle/ellipse, pixels. - * @param h vertical diameter of circle/ellipse, pixels. - */ - public OMEllipse(LatLonPoint centerPoint, int offset_x1, int offset_y1, int w, int h, - double rotateAngle) { - super(centerPoint.getY(), centerPoint.getX(), offset_x1, offset_y1, w, h); - setRotationAngle(rotateAngle); - } - - /** - * Set the axis lengths of the ellipse. - * - * @param majorAxis x direction of ellipse. - * @param minorAxis y direction of ellipse. - * @param units com.bbn.openmap.proj.Length object describing units of axis - * values. - */ - public void setAxis(double majorAxis, double minorAxis, Length units) { - if (units == null) { - units = Length.RADIAN; - } - - this.majorAxisSpan = units.toRadians(majorAxis); - this.minorAxisSpan = units.toRadians(minorAxis); - rawllpts = null; - setNeedToRegenerate(true); - } - - public void setCenter(LatLonPoint llp) { - super.setCenter(llp); - rawllpts = null; - } - - /** - * Get the x axis value. - */ - public double getMajorAxis() { - return majorAxisSpan; - } - - /** - * Get the y axis value. - */ - public double getMinorAxis() { - return minorAxisSpan; - } - - /** - * Get the float[] of points that make up the ellipse. In radians, lat, lon, - * lat, lon, etc. May be null if generate hasn't been called. - */ - public double[] getLatLonPoints() { - return rawllpts; - } - - /** - * Given that the center point and the axis are set, calculate the new - * lat/lon points all around the ellipse from the center. - */ - public double[] createLatLonPoints() { - // First, need to calculate the lat/lon points for the - // ellipse. - int i; - int nMax = 72; - double angle = -Math.PI; - double angleInc = 2.0 * Math.PI / nMax; - double[] distance = new double[nMax + 1]; - double x; - double y; - double a; - double b; - double[] azimuth = new double[nMax + 1]; - double[] llPoints = new double[2 * (nMax + 1)]; - - a = majorAxisSpan / 2.0; - b = minorAxisSpan / 2.0; - - for (i = 0; i < nMax; i++) { - - x = Math.sqrt((a * a * b * b) / ((b * b) + ((a * a) * Math.pow(Math.tan(angle), 2)))); - double yt = (x * x) / (a * a); - if (yt > 1.0) { - yt = 1.0; - } - y = Math.sqrt((1.0 - yt) * (b * b)); - - distance[i] = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); - azimuth[i] = angle + com.bbn.openmap.util.MoreMath.HALF_PI + getRotationAngle(); - - if (Debug.debugging("ellipse")) { - Debug.output(" " - + i - + " " - + Math.toDegrees(azimuth[i]) - + " ( " - + distance[i] - + " ) " - + (Debug.debugging("ellipsedetail") ? ("[from x:" + x + ", y:" + y + ", a:" - + a + ", b:" + b + "]") : "")); - } - angle += angleInc; - } - - distance[nMax] = distance[0]; - azimuth[nMax] = azimuth[0]; - int nCounter = 0; - - for (i = 0; i < nMax + 1; i++) { - - LatLonPoint llPt = LatLonPoint.getDouble(center).getPoint((float) distance[i], azimuth[i]); - llPoints[nCounter++] = llPt.getRadLat(); - llPoints[nCounter++] = llPt.getRadLon(); - } - - return llPoints; - } - - public boolean generate(Projection proj) { - if (renderType == RENDERTYPE_XY || renderType == RENDERTYPE_OFFSET) { - return super.generate(proj); // generate using circle's generate - } - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMEllipse: null projection in generate!"); - return false; - } - - if (rawllpts == null) { - rawllpts = createLatLonPoints(); - } - - ArrayList vector = null; - - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians.ArrayList vector; - if (proj instanceof GeoProj) { - vector = ((GeoProj) proj).forwardPoly(rawllpts, getLineType(), -1, true); - - int size = vector.size(); - GeneralPath projectedShape = null; - // We could call create shape, but this is more efficient. - for (int i = 0; i < size; i += 2) { - GeneralPath gp = createShape(vector.get(i), vector.get(i + 1), true); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - setShape(projectedShape); - } else { - // Create an ellipse in projected space using java2d - Ellipse2D ellipse = new Ellipse2D.Float((float) center.getX(), (float) center.getY(), (float) majorAxisSpan, (float) minorAxisSpan); - setShape(new GeneralPath(proj.forwardShape(ellipse))); - } - - setLabelLocation(getShape(), proj); - - setNeedToRegenerate(false); - return true; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMEllipse) { - OMEllipse ellipse = (OMEllipse) source; - this.majorAxisSpan = ellipse.majorAxisSpan; - this.minorAxisSpan = ellipse.minorAxisSpan; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometry.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometry.java deleted file mode 100644 index 666b1c7bd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometry.java +++ /dev/null @@ -1,385 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGeometry.java,v $ -// $RCSfile: OMGeometry.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.util.Map; - -import com.bbn.openmap.proj.Projection; - -/** - * Base class of OpenMap OMGraphics geometry. - *

- * - * The geometry classes are intended to pull the object location data out of the - * OMGraphics. If you have a bunch of OMGraphics that are all rendered with - * common attributes, you can create a bunch of OMGeometry objects to plavce in - * a OMGeometryList that will render them all alike. - * - * @see OMGeometryList - * @see Projection - */ -public interface OMGeometry { - - /** - * Set the line type for the graphic, which will affect how the lines will - * be drawn. See the definition of the lineType parameter. Accepts - * LINETYPE_RHUMB, LINETYPE_STRAIGHT and LINETYPE_GREATCIRCLE. Any weird - * values get set to LINETYPE_STRAIGHT. - * - * @param value the line type of the graphic. - */ - public void setLineType(int value); - - /** - * Return the line type. - * - * @return the linetype - LINETYPE_RHUMB, LINETYPE_STRAIGHT, - * LINETYPE_GREATCIRCLE or LINETYPE_UNKNOWN. - */ - public int getLineType(); - - /** - * Return the render type. - * - * @return the rendertype of the object - RENDERTYPE_LATLON, RENDERTYPE_XY, - * RENDERTYPE_OFFSET and RENDERTYPE_UNKNOWN. - */ - public int getRenderType(); - - /** - * Sets the regenerate flag for the graphic. This flag is used to determine - * if extra work needs to be done to prepare the object for rendering. - * - * @param value boolean - */ - public void setNeedToRegenerate(boolean value); - - /** - * Return the regeneration status. - * - * @return boolean - */ - public boolean getNeedToRegenerate(); - - /** - * Set the visibility variable. NOTE:
- * This is checked by the OMGeometryList when it iterates through its list - * for render and gesturing. It is not checked by the internal OMGeometry - * methods, although maybe it should be... - * - * @param visible boolean - */ - public void setVisible(boolean visible); - - /** - * Get the visibility variable. - * - * @return boolean - */ - public boolean isVisible(); - - /** - * Let the geometry object know that it is selected. No action mandated. - */ - public void select(); - - /** - * Let the geometry object know that it is not selected. No action mandated. - */ - public void deselect(); - - /** - * Set an attribute in an OMGeometry. - */ - public void putAttribute(Object key, Object value); - - /** - * Get an attribute from an OMGeometry. - */ - public Object getAttribute(Object key); - - /** - * Remove an attribute from the OMGeometry. - */ - public Object removeAttribute(Object key); - - /** - * Clear attributes from the OMGeometry. - */ - public void clearAttributes(); - - /** - * Set all attributes on the OMGeometry. - */ - public void setAttributes(Map attributes); - - /** - * Get all attributes from the OMGeometry. - */ - public Map getAttributes(); - - // //////////////////////////////////////////////////////////////////////// - - /** - * Prepare the geometry for rendering. This must be done before calling - * render()! If a vector graphic has lat-lon components, then - * we project these vertices into x-y space. For raster graphics we prepare - * in a different fashion. - *

- * If the generate is unsuccessful, it's usually because of some oversight, - * (for instance if proj is null), and if debugging is enabled, - * a message may be output to the controlling terminal. - *

- * - * @param proj Projection - * @return boolean true if successful, false if not. - * @see #regenerate - */ - public boolean generate(Projection proj); - - /** - * Self-discovery of internal Shape object used for check, or implemented if - * a Shape object doesn't matter. - * - * @return true if the OMGeometry should be rendered - it's visible and the - * projected shape is created and reflects the current location - * settings of the geometry. - */ - public boolean isRenderable(); - - /** - * Shape object provided for Shape-readiness check. - * - * @param s Shape to check if ready for rendering - * @return true if the OMGeometry should be rendered - it's visible and the - * projected shape is created and reflects the current location - * settings of the geometry. - */ - public boolean isRenderable(Shape s); - - /** - * Paint the graphic. This paints the graphic into the Graphics context. - * This is similar to paint() function of java.awt.Components. - * Note that if the graphic has not been generated, it should not be - * rendered. - *

- * - * It's expected that this method will call fill and draw, respectively. - * - * @param g Graphics2D context to render into. - */ - public void render(Graphics g); - - /** - * Paint the graphic, as a filled shape. This method has been broken out of - * render as a way to allow OMGeometries to fine-tune their rendering - * process. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - * @param s Shape object to use for fill. - */ - public void fill(Graphics g, Shape s); - - /** - * Paint the graphic. This method has been broken out of render as a way to - * allow OMGeometries to fine-tune their rendering process. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - */ - public void fill(Graphics g); - - /** - * Paint the graphic, as an outlined shape. This method has been broken out - * of render as a way to allow OMGeometries to fine-tune their rendering - * process. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - * @param s Shape object to use for drawing. - */ - public void draw(Graphics g, Shape s); - - /** - * Paint the graphic. This method has been broken out of render as a way to - * allow OMGeometries to fine-tune their rendering process. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - */ - public void draw(Graphics g); - - /** - * Return the shortest distance from the graphic to an XY-point. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own distance method. - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - public float distance(double x, double y); - - /** - * Return the shortest distance from the edge of a geometry to an XY-point. - *

- * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the geometry isn't ready - * (ungenerated). - */ - public float distanceToEdge(double x, double y); - - /** - * Answsers the question whether or not the OMGeometry contains the given - * pixel point. - *

- * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own contains method. - *

- * This method duplicates a java.awt.Shape method, with some protection - * wrapped around it. If you have other queries for the internal Shape - * object, just ask for it and then ask it directly. This method is provided - * because it is the most useful, used when determining if a mouse event is - * occurring over an object on the map. - * - * @param x X pixel coordinate of the point. - * @param y Y pixel coordinate of the point. - * @return getShape().contains(x, y), false if the OMGraphic hasn't been - * generated yet. - */ - public boolean contains(double x, double y); - - /** - * Invoke this to regenerate a "dirty" graphic. This method is a wrapper - * around the generate() method. It invokes - * generate() only if needToRegenerate() on the - * graphic returns true. To force a graphic to be generated, call - * generate() directly. - * - * @param proj the Projection - * @return true if generated, false if didn't do it (maybe a problem). - * @see #generate - */ - public boolean regenerate(Projection proj); - - /** - * Get the java.awt.Shape object that represents the projected graphic. - *

- * - * The java.awt.Shape object gives you the ability to do a little spatial - * analysis on the graphics. - * - * @return java.awt.geom.GeneralPath (Shape), or null if the graphic needs - * to be generated with the current map projection, or null if the - * OMGeometry hasn't been updated to use Shape objects for its - * internal representation. - */ - public GeneralPath getShape(); - - /** - * Set the java.awt.Shape object that represents the projected graphic. - * Ideally, the OMGeometry will set this internally. This method is provided - * to clear out the object to save memory, or to allow manipulations if the - * situation dictates. - *

- * - * The java.awt.Shape object gives you the ability to do a little spatial - * analysis on the graphics. - * - * @param gp java.awt.geom.GeneralPath (Shape), or null if the graphic needs - * to be cleared or regenerated. - */ - public void setShape(GeneralPath gp); - - /** - * OMGeometry method for returning a simple description of itself, for - * debugging purposes. - */ - public String getDescription(); - - /** - * Replace the member variables of this OMGraphic with copies of member - * variables from another one. - * - * @param source - */ - void restore(OMGeometry source); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometryList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometryList.java deleted file mode 100644 index a97c0f1e2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGeometryList.java +++ /dev/null @@ -1,451 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGeometryList.java,v $ -// $RCSfile: OMGeometryList.java,v $ -// $Revision: 1.10 $ -// $Date: 2005/08/09 20:01:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.io.EOFException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.OptionalDataException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.ListIterator; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * This class encapsulates a List of OMGeometries. It's an OMGraphic, so it - * contains information on how to draw them. It's also a subclass to the - * OMGraphicList, and relies on many OMGraphicList methods. - * - *

- * The OMGeometryList assumes that all OMGeometries on it should be rendered the - * same - same fill color, same edge color and stroke, and will create one - * java.awt.Shape object from all the projected OMGeometries for more efficient - * rendering. If your individual OMGeometries have independent rendering - * characteristics, use the OMGraphicList and OMGraphics. - * - *

- * Because the OMGeometryList creates a single java.awt.Shape object for all of - * its contents, it needs to be generated() if an OMGeometry is added or removed - * from the list. If you don't regenerate the OMGeometryList, the list will - * iterate through its contents and render each piece separately. - */ -public class OMGeometryList extends OMList implements Serializable { - - /** - * Flag to mark that the parts should be connected, making this - * OMGeometryList a combination OMGraphic that sums disparate parts. False - * by default. - */ - protected boolean connectParts = false; - - /** - * Construct an OMGeometryList. - */ - public OMGeometryList() { - } - - /** - * Construct an OMGeometryList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public OMGeometryList(int initialCapacity) { - super(initialCapacity); - } - - public OMGeometryList(Collection c) { - graphics.addAll(c); - } - - /** - * Add an OMGeometry to the GraphicList. The OMGeometry must not be null. - * - * @param g the non-null OMGeometry to add - * @exception IllegalArgumentException if OMGeometry is null - */ - public boolean add(OMGeometry g) { - setNeedToRegenerate(true); - return super.add(g); - } - - /** - * For backward compatibility. - * - * @param omg - * @return true if add was successful - */ - public boolean addOMGraphic(OMGraphic omg) { - return super.add(omg); - } - - /** - * Remove the geometry from the list. - * - * @param geometry the geometry to remove. - * @return true if geometry was on the list, false if otherwise. - */ - public boolean remove(OMGeometry geometry) { - setNeedToRegenerate(true); - return super.remove(geometry); - } - - /** - * Set the geometry at the specified location. The OMGeometry must not be - * null. - * - * @param geometry OMGeometry - * @param index index location of the OMGeometry placement. - * @exception ArrayIndexOutOfBoundsException if index is out-of-bounds - */ - public OMGeometry set(int index, OMGeometry geometry) { - setNeedToRegenerate(true); - synchronized (graphics) { - return graphics.set(index, geometry); - } - } - - /** - * Remove the geometry at the location number. - * - * @param location the location of the OMGeometry to remove - */ - public OMGeometry remove(int location) { - OMGeometry obj = super.remove(location); - if (obj != null) { - setNeedToRegenerate(true); - } - return obj; - } - - /** - * Renders all the objects in the list a geometries context. This is the - * same as paint() for AWT components. The geometries are - * rendered in the order of traverseMode. Any geometries where - * isVisible() returns false are not rendered. - * - * @param gr the AWT Graphics context - */ - public void render(Graphics gr) { - - if (isVague() && !isVisible()) - return; - - Shape shp = getShape(); - if (shp != null) { - - if (matted) { - if (gr instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) gr).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - setGraphicsColor(gr, mattingPaint); - ((Graphics2D) gr).draw(shp); - } - } - - setGraphicsForFill(gr); - ((Graphics2D) gr).fill(shp); - setGraphicsForEdge(gr); - ((Graphics2D) gr).draw(shp); - - } else { - - synchronized (graphics) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(graphics.size()); - while (iterator.hasPrevious()) { - renderGeometry(iterator.previous(), gr); - } - } else { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - renderGeometry(iterator.next(), gr); - } - } - } - } - - renderLabel(gr); - } - - protected void renderGeometry(OMGeometry geometry, Graphics gr) { - - Shape shp = geometry.getShape(); - - boolean isRenderable = !geometry.getNeedToRegenerate() && geometry.isVisible() - && shp != null; - - if (isRenderable) { - if (matted) { - if (gr instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) gr).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - setGraphicsColor(gr, mattingPaint); - draw(gr, shp); - } - } - - setGraphicsForFill(gr); - fill(gr, shp); - setGraphicsForEdge(gr); - draw(gr, shp); - } - } - - /** - * Renders all the objects in the list a geometry's context, in their - * 'selected' mode. This is the same as paint() for AWT - * components. The geometries are rendered in the order of traverseMode. Any - * geometries where isVisible() returns false are not rendered. - * All of the geometries on the list are returned to their deselected state. - * - * @param gr the AWT Graphics context - */ - public void renderAllAsSelected(Graphics gr) { - Shape shape = getShape(); - if (shape != null) { - - setGraphicsForFill(gr); - ((Graphics2D) gr).fill(shape); - select(); - setGraphicsForEdge(gr); - ((Graphics2D) gr).draw(shape); - deselect(); - - } - } - - /** - * Prepare the geometries for rendering. This must be done before calling - * render()! This recursively calls generate() on the - * OMGeometries on the list. - * - * @param p a Projection - * @param forceProjectAll if true, all the geometries on the list are - * generated with the new projection. If false they are only - * generated if getNeedToRegenerate() returns true - * @see OMGeometry#generate - * @see OMGeometry#regenerate - */ - public boolean generate(Projection p, boolean forceProjectAll) { - - setNeedToRegenerate(true); - - GeneralPath projectedShape = null; - - synchronized (graphics) { - - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - projectedShape = updateShape(projectedShape, (OMGeometry) iterator.previous(), p, forceProjectAll); - } - } else { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - projectedShape = updateShape(projectedShape, (OMGeometry) iterator.next(), p, forceProjectAll); - } - } - } - - setShape(projectedShape); - setLabelLocation(projectedShape, p); - setNeedToRegenerate(false); - - return projectedShape != null; - } - - /** - * Given a OMGeometry, it calls generate/regenerate on it, and then adds the - * GeneralPath shape within it to the OMGeometryList shape object. Calls - * setShape() with the new current shape, which is a synchronized method. - * - * @param geometry the geometry to append - * @param p the current projection - * @param forceProject flag to force re-generation - * @deprecated use the new paradigm from the other updateShape - */ - protected void updateShape(OMGeometry geometry, Projection p, boolean forceProject) { - - if (geometry.isVisible()) { - if (forceProject) { - geometry.generate(p); - } else { - geometry.regenerate(p); - } - - setShape(appendShapeEdge(getShape(), geometry.getShape(), connectParts)); - } - } - - /** - * Given an OMGeometry, check its visibility and if visible, generate it if - * required and add the result to the provided current shape. Does not call - * setShape(). - * - * @param currentShape the current shape - * @param geometry the geometry to test - * @param p the current projection - * @param forceProject flag to force regeneration - * @return the newly combined shape. - */ - protected GeneralPath updateShape(GeneralPath currentShape, OMGeometry geometry, Projection p, - boolean forceProject) { - - GeneralPath newShapePart = null; - if (geometry != null && geometry.isVisible()) { - if (forceProject) { - geometry.generate(p); - } else { - geometry.regenerate(p); - } - - newShapePart = geometry.getShape(); - } - - return appendShapeEdge(currentShape, newShapePart, connectParts); - } - - /** - * Read a cache of OMGeometries, given a ObjectInputStream. - * - * @param objstream ObjectInputStream of geometry list. - */ - public void readGraphics(ObjectInputStream objstream) throws IOException { - - Debug.message("omgraphics", "OMGeometryList: Reading cached geometries"); - - try { - while (true) { - try { - OMGeometry omg = (OMGeometry) objstream.readObject(); - this.add(omg); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (OptionalDataException ode) { - ode.printStackTrace(); - } - } - } catch (EOFException e) { - } - } - - /** - * Set whether the OMGeometries on the list should be connected to make a - * one-part shape object (if true), or a multi-part shape object (if false). - */ - public void setConnectParts(boolean value) { - connectParts = value; - } - - /** - * Get whether the OMGeometries on the list should be connected to make a - * one-part shape object (if true), or a multi-part shape object (if false). - */ - public boolean getConnectParts() { - return connectParts; - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public Iterator iteratorCopy() { - return new OMGeometryList(graphics).iterator(); - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public ListIterator listIteratorCopy() { - return new OMGeometryList(graphics).listIterator(); - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public ListIterator listIteratorCopy(int size) { - return new OMGeometryList(graphics).listIterator(size); - } - - @Override - public OMList create() { - return new OMGeometryList(); - } - - @Override - protected com.bbn.openmap.omGraphics.OMList.OMDist createDist() { - return new OMDist(); - } - - public void clear() { - setNeedToRegenerate(true); - super.clear(); - } - - public void add(int index, OMGeometry element) { - setNeedToRegenerate(true); - super.add(index, element); - } - - public boolean addAll(Collection c) { - setNeedToRegenerate(true); - synchronized (graphics) { - return graphics.addAll(c); - } - } - - public boolean addAll(int index, Collection c) { - setNeedToRegenerate(true); - synchronized (graphics) { - return graphics.addAll(index, c); - } - } - - public boolean removeAll(Collection c) { - setNeedToRegenerate(true); - return super.removeAll(c); - } - - public boolean retainAll(Collection c) { - setNeedToRegenerate(true); - return super.retainAll(c); - } - - public OMGeometry get(int index) { - synchronized (graphics) { - return graphics.get(index); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphic.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphic.java deleted file mode 100644 index 2c9668909..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphic.java +++ /dev/null @@ -1,418 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphic.java,v $ -// $RCSfile: OMGraphic.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Paint; -import java.awt.Stroke; -import java.awt.TexturePaint; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Projection; - -/** - * Used to be the base class of OpenMap graphics, but now inherits from - * BasicGeometry, which now contains all the information about the geometry of - * the OMGraphic. The OMGraphic also contains information about how the geometry - * should be drawn. - *

- * The OMGraphics are raster and vector graphic objects that know how to - * position and render themselves on a given x-y window or lat-lon map - * projection. All you have to do is supply the location data (x/y, lat/lon) and - * drawing information (color, line width) and the graphic handles the rest. - *

- * - * This class contains parameters that are common to most types of graphics. If - * a parameter doesn't make sense for a particular graphic type, it is ignored. - *

- * - * The OMGraphics are being updated to be able to provide java.awt.Shape - * representations of themselves after they have been generated(). The - * getShape() method returns a java.awt.Shape object. With the Shape object, you - * can do some spatial analysis (object operations) on the projected OMGraphics. - * - * NOTES: - *

    - *
  • Color values cannot be set to null, but can be set to OMGraphic.clear. - * Actually, if you set them to null, they will set themselves to be clear. - *
  • XY Rendering: Java specifies that the origin is the top left of the - * window, x increases to the right, y increases down. - *
  • LatLon Rendering: Defined by the Projection object. The center of the - * window usually corresponds to the center of the projection. OMGraphics should - * project themselves using the appropriate forward() method listed in the - * Projection interface - *
  • Offset Rendering: same as XY, but with origin set to a projected LatLon - * point. - *
- * - * @see OMBitmap - * @see OMCircle - * @see OMLine - * @see OMPoly - * @see OMRect - * @see OMRaster - * @see OMText - * @see OMGraphicList - * @see Projection - */ -public interface OMGraphic extends OMGeometry, OMGraphicConstants, Cloneable { - - /** - * Set the render type of the graphic. Accepts RENDERTYPE_LATLON, - * RENDERTYPE_XY and RENDERTYPE_OFFSET. All weird values get set to - * RENDERTYPE_XY. See the definition on the renderType parameter. - * - * @param value the rendertype for the object. - */ - void setRenderType(int value); - - /** - * Return the render type. - * - * @return the rendertype of the object - RENDERTYPE_LATLON, RENDERTYPE_XY, - * RENDERTYPE_OFFSET and RENDERTYPE_UNKNOWN. - */ - int getRenderType(); - - /** - * Set the declutter setting for the graphic. Accepts DECLUTTERTYPE_SPACE, - * DECLUTTERTYPE_MOVE, DECLUTTERTYPE_LINE, and DECLUTTERTYPE_NONE. All weird - * values are set to DECLUTTERTYPE_NONE. - *

- * Right now, this is unimplemented in OpenMap. But for information, - * DECLUTTERTYPE_NONE means the object has no impact on the placement of - * objects. DECLUTTERTYPE_SPACE means the object shouldn't have things - * placed on it, but to draw it where the coordinates dictate. - * DECLUTTERTYPE_MOVE means to put the object in an open space, and - * DELCUTTERTYPE_LINE adds the feature that if the object is not drawn where - * it's coordinates say it should be, then a line should be drawn showing - * where the original position is. - *

- * Decluttering of geometries is not supported. This flag is not used. - * - * @param value the declutter type value. - */ - void setDeclutterType(int value); - - /** - * Return the declutter type. - * - * @return declutter type, see above. - */ - int getDeclutterType(); - - /** - * Given a java.awt.Graphics object, set the Stroke and Paint parameters of - * it to match the OMGraphic's edge settings. - * - * @param g java.awt.Graphics - * @see #setGraphicsColor - */ - void setGraphicsForEdge(Graphics g); - - /** - * Given a java.awt.Graphics object, set the Paint to be the OMGraphic's - * fillPaint setting. - * - * @param g java.awt.Graphics - * @see #setGraphicsColor - */ - void setGraphicsForFill(Graphics g); - - /** - * Set the Paint in the given Graphics. If the Graphics is not an instance - * of Graphics2D, then the Color of the graphics is set if the Paint is an - * instance of Color. - * - * @param g java.awt.Graphics - * @param paint java.awt.Paint - */ - void setGraphicsColor(Graphics g, Paint paint); - - /** - * Return the normal foreground color of the object. - * - * @return the line color. Returns null if the Paint is not a Color. - */ - Color getLineColor(); - - /** - * Set the line Paint. The line Paint is the normal display edge paint of - * the graphic. This Paint is used as the display Paint when the object is - * NOT selected (highlighted). The display Paint is set to the select Paint - * in this method if selected boolean attribute is false. - * - * @param paint the real line Paint - */ - void setLinePaint(Paint paint); - - /** - * Get the normal line Paint used for the graphic. - * - * @return Line Paint. - */ - Paint getLinePaint(); - - /** - * Return the selected color, which is the line or foreground color used - * when the graphic is "selected". - * - * @return the selected mode line color. Returns null if the select Paint is - * not a Color. - */ - Color getSelectColor(); - - /** - * Set the select Paint. The select Paint is the display edge paint of the - * graphic. This Paint is used as the display Paint when the object IS - * selected (highlighted). The display Paint is set to the select Paint in - * this method if selected boolean attribute is true. - * - * @param paint the real select Paint - */ - void setSelectPaint(Paint paint); - - /** - * Get the normal select Paint used for the graphic. - * - * @return Select Paint. - */ - Paint getSelectPaint(); - - /** - * Return the color that should be used for display. This color changes, - * depending on whether the object is selected or not. The display color is - * also set when the line color or the select color is set, depending on the - * statue of the selected boolean attribute. - * - * @return the color used as the edge color or foreground color, in the - * present selected state. If the displayPaint is not a Color, this - * method returns null. - */ - Color getDisplayColor(); - - /** - * Return the Paint that should be used for display. This Paint changes, - * depending on whether the object is selected or not. The display Paint is - * also set when the line Paint or the select Paint is set, depending on the - * statue of the selected boolean attribute. - * - * @return the Paint used as the edge Paint or foreground Paint, in the - * present selected state. - */ - Paint getDisplayPaint(); - - /** - * Set the selected attribute to true, and sets the color to the select - * color. - */ - void select(); - - /** - * Set the selected attribute to false, sets the color to the line color. - */ - void deselect(); - - /** - * Return whether the OMGraphic is selected. - */ - boolean isSelected(); - - /** - * Calls select() or deselect() depending on the boolean (select is true). - */ - void setSelected(boolean set); - - /** - * Return whether the OMGraphic has matting around the edge. - */ - boolean isMatted(); - - /** - * Set whether the OMGraphic should have matting around the edge. - */ - void setMatted(boolean set); - - /** - * Return the background color of the graphic object. If the fill Paint is - * not a color, this method will return null. - * - * @return the color used for the background. - */ - Color getFillColor(); - - /** - * Set the fill Paint for this graphic. If the paint value is null, it will - * be set to OMGraphicConstants.clear. - * - * @param paint the Paint object. - */ - void setFillPaint(Paint paint); - - /** - * Set the texture mask for the OMGraphic. If not null, then it will be - * rendered on top of the fill paint. If the fill paint is clear, the - * texture mask will not be used. If you just want to render the texture - * mask as is, set the fill paint of the graphic instead. This is really to - * be used to have a texture added to the graphic, with the fill paint still - * influencing appearance. - */ - void setTextureMask(TexturePaint texture); - - /** - * Return the fill Paint for this graphic. - */ - Paint getFillPaint(); - - /** - * Return the texture mask Paint for this graphic. - */ - TexturePaint getTextureMask(); - - /** - * Set the Paint used for matting. - */ - void setMattingPaint(Paint mPaint); - - /** - * Get the Paint used for matting. - */ - Paint getMattingPaint(); - - /** - * Set the Stroke that should be used for the graphic edges. Using a - * BasicStroke, you can set a stroke that defines the line width, the dash - * interval and phase. If a null value is passed in, a default BasicStroke - * will be used. - * - * @param s the stroke to use for the graphic edge. - * @see java.awt.Stroke - * @see java.awt.BasicStroke - */ - void setStroke(Stroke s); - - /** - * Get the Stroke used for the graphic edge. - */ - Stroke getStroke(); - - /** - * Set whether an EditableOMGraphic modifying this graphic should show it's - * palette. - */ - void setShowEditablePalette(boolean set); - - /** - * Get whether an EditableOMGraphic modifying this graphic should show it's - * palette. - */ - boolean getShowEditablePalette(); - - /** - * A function that takes a float distance, which presumably represents the - * pixel distance from a point to a graphic, and subtracts half of the line - * width of the graphic from the distance if the graphic line width is - * greater than one. This should give a true pixel distance from the - * graphic, taking into account an embellished line. - * - * @param distance pixel distance to the graphic edge with a line width of - * one. - * @return the pixel distance to the true display edge of the graphic. - */ - float normalizeDistanceForLineWidth(float distance); - - // //////////////////////////////////////////////////////////////////////// - - /** - * Sets the label location at the center of the polygon points. If the - * hasLabel variable hasn't been set, it no-ops. - * - * @param xpoints - * @param ypoints - */ - void setLabelLocation(int[] xpoints, int[] ypoints); - - /** - * Sets the label location at the given point. If the hasLabel variable - * hasn't been set, it no-ops. - * - * @param p - */ - void setLabelLocation(Point2D p); - - /** - * Sets the label location at the center of the bounding box of the path. If - * the hasLabel variable hasn't been set, it no-ops. - * - * @param gp - */ - void setLabelLocation(GeneralPath gp); - - /** - * Checks to see if a label should be painted based on what methods were - * called in generate(), and renders the label if necessary. If the label - * wasn't set up, a quick no-op occurs. - * - * @param g - */ - void renderLabel(Graphics g); - - /** - * Return true of the fill color/paint should be rendered (not clear). - */ - boolean shouldRenderFill(); - - /** - * Return true if the edge color/paint should be rendered (not clear, or - * doesn't match the fill color). - */ - boolean shouldRenderEdge(); - - /** - * Invoke this to regenerate a "dirty" graphic. This method is a wrapper - * around the generate() method. It invokes - * generate() only if needToRegenerate() on the - * graphic returns true. To force a graphic to be generated, call - * generate() directly. - * - * @param proj the Projection - * @return true if generated, false if didn't do it (maybe a problem). - * @see #generate - */ - boolean regenerate(Projection proj); - - /** - * Used by the GraphicAttributes object to provide a choice on whether the - * line type choice can be changed. - */ - boolean hasLineTypeChoice(); - - /** - * To support clone operations. Might not be implemented to the depth desired. - * @return Object cloned from this OMGraphic - */ - Object clone(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicAdapter.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicAdapter.java deleted file mode 100644 index 9b181283d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicAdapter.java +++ /dev/null @@ -1,1211 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphic.java,v $ -// $RCSfile: OMGraphic.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.TexturePaint; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import com.bbn.openmap.omGraphics.geom.BasicGeometry; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * Used to be the base class of OpenMap graphics, but now inherits from - * BasicGeometry, which now contains all the information about the geometry of - * the OMGraphic. The OMGraphic also contains information about how the geometry - * should be drawn. - *

- * The OMGraphics are raster and vector graphic objects that know how to - * position and render themselves on a given x-y window or lat-lon map - * projection. All you have to do is supply the location data (x/y, lat/lon) and - * drawing information (color, line width) and the graphic handles the rest. - *

- * - * This class contains parameters that are common to most types of graphics. If - * a parameter doesn't make sense for a particular graphic type, it is ignored. - *

- * - * The OMGraphics are being updated to be able to provide java.awt.Shape - * representations of themselves after they have been generated(). The - * getShape() method returns a java.awt.Shape object. With the Shape object, you - * can do some spatial analysis (object operations) on the projected OMGraphics. - * - * NOTES: - *

    - *
  • Color values cannot be set to null, but can be set to OMGraphic.clear. - * Actually, if you set them to null, they will set themselves to be clear. - *
  • XY Rendering: Java specifies that the origin is the top left of the - * window, x increases to the right, y increases down. - *
  • LatLon Rendering: Defined by the Projection object. The center of the - * window usually corresponds to the center of the projection. OMGraphics should - * project themselves using the appropriate forward() method listed in the - * Projection interface - *
  • Offset Rendering: same as XY, but with origin set to a projected LatLon - * point. - *
- * - * @see OMBitmap - * @see OMCircle - * @see OMLine - * @see OMPoly - * @see OMRect - * @see OMRaster - * @see OMText - * @see OMGraphicList - * @see Projection - */ -public abstract class OMGraphicAdapter extends BasicGeometry implements OMGraphic, - OMGraphicConstants, Cloneable, Serializable { - - /** - * The Java2D Stroke. This is used for lineWidth, and dashing of the lines - * and polygon edges. - */ - protected transient Stroke stroke = BASIC_STROKE; - - /** - * This color is the real foreground color of the object. It is kept so that - * the object knows how to de-highlight itself. It defaults to black. - */ - protected Paint linePaint = Color.black; - - /** - * This paint is used for the matting area around the edge of an OMGraphic - * painted when the matted variable is set to true. - */ - protected Paint mattingPaint = Color.black; - - /** - * The color that the object is displayed with. This color changes back and - * forth between the selectColor and the lineColor, depending on the if the - * object is selected or not. - */ - protected Paint displayPaint = linePaint; - - /** - * This color is the fill color of the object. It defaults to a black color - * that is transparent. - */ - protected Paint fillPaint = clear; - - /** - * This Paint object is the fill texture mask of the object. It defaults to - * null. If this texture mask is set, the fill paint will still be used to - * fill the OMGraphic shape, but then this paint will be rendered on top. If - * the textureMask has transparency, the fill paint still influences - * appearance. - */ - protected transient TexturePaint textureMask = null; - - /** - * This color is the highlight color that can be used when the object is - * selected. The default color is black, just like the line color. - */ - protected Paint selectPaint = Color.black; - - /** - * Flag to indicate that the object has/hasnot been put in a special mode as - * a result of some event. Set through the select()/deselect methods(). - */ - protected boolean selected = false; - - /** - * A flag for whether an EditableOMGraphic should show it's palette if the - * OMGraphic is modified. - */ - protected boolean showEditablePalette = true; - - /** - * Flag to note if the current edge color matches the fill color. Can be - * used to save from rendering the edge if rendering the filled area already - * takes care of it. - */ - protected boolean edgeMatchesFill = false; - - /** - * The renderType describes the relation of the object to the window. - * RENDERTYPE_LATLON means the object is positioned relative to lat/lon - * points. RENDERTYPE_XY means the object is positioned relative to window - * pixel coordinates. RENDERTYPE_OFFSET means the object is drawn at a pixel - * offset to a lat/lon point. - */ - protected int renderType = RENDERTYPE_UNKNOWN; - - /** - * Decluttering is not supported by OpenMap yet. But, when it is, these - * parameters will describe the way the object is manipulated on the window - * relative to its neighbors. DECLUTTERTYPE_NONE means the object will be - * drawn where its attributes say it should be. DECLUTTERTYPE_SPACE - * indicates that the window space of the object should be marked as taken, - * but the object should not be moved. DECLUTTERTYPE_MOVE means the object - * should be moved to the nearest open location closest to the position - * indicated by its attributes. DECLUTTERTYPE_LINE is the same as MOVE, but - * in addition, a line is drawn from the current position to its original - * position. - */ - protected int declutterType = DECLUTTERTYPE_NONE; - - /** - * Flag for determining when the matting around the edge of an OMGraphic. - * Matting is a line, two pixels wider than the edge, painted under the - * edge. It makes the OMGraphic stand out on busy backgrounds. - */ - protected boolean matted = false; - - /** - * The flag set in generate that causes the OMGraphic to look for an - * OMLabeler attribute in render. This flag prevents an unnecessary - * hashtable lookup every render call. - */ - protected transient boolean hasLabel = false; - - /** - * Checks if the Paint is clear. - * - * @param paint Paint or null. - * @return true if Paint is null or is a Color with a 0 alpha value. - */ - public boolean isClear(Paint paint) { - return DrawingAttributes.isClear(paint); - // if (paint instanceof Color) { - // return ((((Color) paint).getRGB() & 0xff000000) == 0); - // } else { - // return false; - // } - } - - // //////////////////////////////////////////////////////// - - /** - * Construct a default OMGraphic. - */ - protected OMGraphicAdapter() { - } - - /** - * Construct an OMGraphic. Standard simple constructor that the child - * OMGraphics usually call. All of the other parameters get set to their - * default values. - * - * @param rType render type - * @param lType line type - * @param dcType declutter type - */ - protected OMGraphicAdapter(int rType, int lType, int dcType) { - setRenderType(rType); - setLineType(lType); - setDeclutterType(dcType); - } - - /** - * Construct an OMGraphic. More complex constructor that lets you set the - * rest of the parameters. - * - * @param rType render type - * @param lType line type - * @param dcType declutter type - * @param lc line color - * @param fc fill color - * @param sc select color - */ - public OMGraphicAdapter(int rType, int lType, int dcType, Color lc, Color fc, Color sc) { - this(rType, lType, dcType); - setLinePaint(lc); - setSelectPaint(sc); - setFillPaint(fc); - } - - /** - * Set the render type of the graphic. Accepts RENDERTYPE_LATLON, - * RENDERTYPE_XY and RENDERTYPE_OFFSET. All weird values get set to - * RENDERTYPE_XY. See the definition on the renderType parameter. - * - * @param value the rendertype for the object. - */ - public void setRenderType(int value) { - if (renderType == value) - return; - setNeedToRegenerate(true); // flag dirty - - renderType = value; - } - - /** - * Return the render type. - * - * @return the rendertype of the object - RENDERTYPE_LATLON, RENDERTYPE_XY, - * RENDERTYPE_OFFSET and RENDERTYPE_UNKNOWN. - */ - public int getRenderType() { - return renderType; - } - - /** - * Set the declutter setting for the graphic. Accepts DECLUTTERTYPE_SPACE, - * DECLUTTERTYPE_MOVE, DECLUTTERTYPE_LINE, and DECLUTTERTYPE_NONE. All weird - * values are set to DECLUTTERTYPE_NONE. - *

- * Right now, this is unimplemented in OpenMap. But for information, - * DECLUTTERTYPE_NONE means the object has no impact on the placement of - * objects. DECLUTTERTYPE_SPACE means the object shouldn't have things - * placed on it, but to draw it where the coordinates dictate. - * DECLUTTERTYPE_MOVE means to put the object in an open space, and - * DELCUTTERTYPE_LINE adds the feature that if the object is not drawn where - * it's coordinates say it should be, then a line should be drawn showing - * where the original position is. - *

- * Decluttering of geometries is not supported. This flag is not used. - * - * @param value the declutter type value. - */ - public void setDeclutterType(int value) { - if (declutterType == value) - return; - setNeedToRegenerate(true); // flag dirty - - declutterType = value; - } - - /** - * Return the declutter type. - * - * @return declutter type, see above. - */ - public int getDeclutterType() { - return declutterType; - } - - /** - * Given a java.awt.Graphics object, set the Stroke and Paint parameters of - * it to match the OMGraphic's edge settings. - * - * @param g java.awt.Graphics - * @see #setGraphicsColor - */ - public void setGraphicsForEdge(Graphics g) { - if (g instanceof Graphics2D) { - ((Graphics2D) g).setStroke(getStroke()); - } - setGraphicsColor(g, getDisplayPaint()); - } - - /** - * Given a java.awt.Graphics object, set the Paint to be the OMGraphic's - * fillPaint setting. - * - * @param g java.awt.Graphics - * @see #setGraphicsColor - */ - public void setGraphicsForFill(Graphics g) { - if (g instanceof Graphics2D) { - ((Graphics2D) g).setStroke(BASIC_STROKE); - } - setGraphicsColor(g, getFillPaint()); - } - - /** - * Set the Paint in the given Graphics. If the Graphics is not an instance - * of Graphics2D, then the Color of the graphics is set if the Paint is an - * instance of Color. - * - * @param g java.awt.Graphics - * @param paint java.awt.Paint - */ - public void setGraphicsColor(Graphics g, Paint paint) { - if (g instanceof Graphics2D) { - ((Graphics2D) g).setPaint(paint); - } else if (paint instanceof Color) { - g.setColor((Color) paint); - } - } - - /** - * Set the line color of the graphic object. The line color is the normal - * display edge color of the object. This color is used as the display color - * when the object is NOT selected (highlighted). The display color is set - * to the select color in this method if selected boolean - * attribute is false. - * - * @param value the real line color - * @deprecated Use setLinePaint instead. Now taking advantage of the Java2D - * API. - */ - public void setLineColor(Color value) { - setLinePaint(value); - } - - /** - * Return the normal foreground color of the object. - * - * @return the line color. Returns null if the Paint is not a Color. - */ - public Color getLineColor() { - if (linePaint instanceof Color) { - return (Color) linePaint; - } else { - return null; - } - } - - /** - * Set the line Paint. The line Paint is the normal display edge paint of - * the graphic. This Paint is used as the display Paint when the object is - * NOT selected (highlighted). The display Paint is set to the select Paint - * in this method if selected boolean attribute is false. - * - * @param paint the real line Paint - */ - public void setLinePaint(Paint paint) { - if (paint != null) { - linePaint = paint; - } else { - linePaint = Color.black; - } - - if (!selected) { - displayPaint = linePaint; - } - setEdgeMatchesFill(); - } - - /** - * Get the normal line Paint used for the graphic. - * - * @return Line Paint. - */ - public Paint getLinePaint() { - return linePaint; - } - - /** - * Set the select color of the graphic object. The selected color is used as - * the display color when the object is selected (highlighted). The display - * color is set to the select color in this method if selected - * boolean attribute is true. - * - * @param value the selected color. - * @deprecated Use setSelectPaint instead. Now taking advantage of the - * Java2D API. - */ - public void setSelectColor(Color value) { - setSelectPaint(value); - } - - /** - * Return the selected color, which is the line or foreground color used - * when the graphic is "selected". - * - * @return the selected mode line color. Returns null if the select Paint is - * not a Color. - */ - public Color getSelectColor() { - if (selectPaint instanceof Color) { - return (Color) selectPaint; - } else { - return null; - } - } - - /** - * Set the select Paint. The select Paint is the display edge paint of the - * graphic. This Paint is used as the display Paint when the object IS - * selected (highlighted). The display Paint is set to the select Paint in - * this method if selected boolean attribute is true. - * - * @param paint the real select Paint - */ - public void setSelectPaint(Paint paint) { - if (paint != null) { - selectPaint = paint; - } else { - selectPaint = Color.black; - } - - if (selected) { - displayPaint = selectPaint; - } - setEdgeMatchesFill(); - } - - /** - * Get the normal select Paint used for the graphic. - * - * @return Select Paint. - */ - public Paint getSelectPaint() { - return selectPaint; - } - - /** - * Return the color that should be used for display. This color changes, - * depending on whether the object is selected or not. The display color is - * also set when the line color or the select color is set, depending on the - * statue of the selected boolean attribute. - * - * @return the color used as the edge color or foreground color, in the - * present selected state. If the displayPaint is not a Color, this - * method returns null. - */ - public Color getDisplayColor() { - if (displayPaint instanceof Color) { - return (Color) displayPaint; - } else { - return null; - } - } - - /** - * Return the Paint that should be used for display. This Paint changes, - * depending on whether the object is selected or not. The display Paint is - * also set when the line Paint or the select Paint is set, depending on the - * statue of the selected boolean attribute. - * - * @return the Paint used as the edge Paint or foreground Paint, in the - * present selected state. - */ - public Paint getDisplayPaint() { - return displayPaint; - } - - /** - * Set the selected attribute to true, and sets the color to the select - * color. - */ - public void select() { - selected = true; - displayPaint = getSelectPaint(); - setEdgeMatchesFill(); - } - - /** - * Set the selected attribute to false, sets the color to the line color. - */ - public void deselect() { - selected = false; - displayPaint = getLinePaint(); - setEdgeMatchesFill(); - } - - /** - * Return whether the OMGraphic is selected. - */ - public boolean isSelected() { - return selected; - } - - /** - * Calls select() or deselect() depending on the boolean (select is true). - */ - public void setSelected(boolean set) { - if (set) { - select(); - } else { - deselect(); - } - } - - /** - * Return whether the OMGraphic has matting around the edge. - */ - public boolean isMatted() { - return matted; - } - - /** - * Set whether the OMGraphic should have matting around the edge. - */ - public void setMatted(boolean set) { - matted = set; - } - - /** - * Set the background color of the graphic object. - * - * @param value java.awt.Color. - * @deprecated Use setFillPaint instead. Now taking advantage of the Java2D - * API. - */ - public void setFillColor(Color value) { - setFillPaint(value); - } - - /** - * Return the background color of the graphic object. If the fill Paint is - * not a color, this method will return null. - * - * @return the color used for the background. - */ - public Color getFillColor() { - if (fillPaint instanceof Color) { - return (Color) fillPaint; - } else { - return null; - } - } - - /** - * Set the fill Paint for this graphic. If the paint value is null, it will - * be set to OMGraphicConstants.clear. - * - * @param paint the Paint object. - */ - public void setFillPaint(Paint paint) { - if (paint != null) { - fillPaint = paint; - if (Debug.debugging("omGraphics")) { - Debug.output("OMGraphic.setFillPaint(): fillPaint= " + fillPaint); - } - } else { - fillPaint = clear; - if (Debug.debugging("omGraphics")) { - Debug.output("OMGraphic.setFillPaint(): fillPaint is clear"); - } - } - setEdgeMatchesFill(); - } - - /** - * Set the texture mask for the OMGraphic. If not null, then it will be - * rendered on top of the fill paint. If the fill paint is clear, the - * texture mask will not be used. If you just want to render the texture - * mask as is, set the fill paint of the graphic instead. This is really to - * be used to have a texture added to the graphic, with the fill paint still - * influencing appearance. - */ - public void setTextureMask(TexturePaint texture) { - textureMask = texture; - } - - /** - * Return the fill Paint for this graphic. - */ - public Paint getFillPaint() { - return fillPaint; - } - - /** - * Return the texture mask Paint for this graphic. - */ - public TexturePaint getTextureMask() { - return textureMask; - } - - protected void setEdgeMatchesFill() { - Paint paint = getDisplayPaint(); - if (fillPaint instanceof Color && paint instanceof Color && !isClear(fillPaint)) { - edgeMatchesFill = ((Color) fillPaint).equals((Color) paint); - } else { - edgeMatchesFill = false; - } - } - - public boolean getEdgeMatchesFill() { - return edgeMatchesFill; - } - - /** - * Set the Paint used for matting. - */ - public void setMattingPaint(Paint mPaint) { - mattingPaint = mPaint; - } - - /** - * Get the Paint used for matting. - */ - public Paint getMattingPaint() { - return mattingPaint; - } - - /** - * Set the Stroke that should be used for the graphic edges. Using a - * BasicStroke, you can set a stroke that defines the line width, the dash - * interval and phase. If a null value is passed in, a default BasicStroke - * will be used. - * - * @param s the stroke to use for the graphic edge. - * @see java.awt.Stroke - * @see java.awt.BasicStroke - */ - public void setStroke(Stroke s) { - if (s != null) { - stroke = s; - } else { - stroke = BASIC_STROKE; - } - } - - /** - * Get the Stroke used for the graphic edge. - */ - public Stroke getStroke() { - if (stroke == null) { - stroke = BASIC_STROKE; - } - return stroke; - } - - /** - * Set whether an EditableOMGraphic modifying this graphic should show it's - * palette. - */ - public void setShowEditablePalette(boolean set) { - showEditablePalette = set; - } - - /** - * Get whether an EditableOMGraphic modifying this graphic should show it's - * palette. - */ - public boolean getShowEditablePalette() { - return showEditablePalette; - } - - /** - * A function that takes a float distance, which presumably represents the - * pixel distance from a point to a graphic, and subtracts half of the line - * width of the graphic from the distance if the graphic line width is - * greater than one. This should give a true pixel distance from the - * graphic, taking into account an embellished line. - * - * @param distance pixel distance to the graphic edge with a line width of - * one. - * @return the pixel distance to the true display edge of the graphic. - */ - public float normalizeDistanceForLineWidth(float distance) { - - float lineWidth = 1; - - if (stroke instanceof BasicStroke) { - lineWidth = ((BasicStroke) stroke).getLineWidth(); - } - - if (lineWidth > 1) { - // extra calculation for lineWidth - distance -= lineWidth / 2; - if (distance < 0f) { - distance = 0f; - } - } - return distance; - } - - // //////////////////////////////////////////////////////////////////////// - - /** - * Prepare the graphic for rendering. This must be done before calling - * render()! If a vector graphic has lat-lon components, then - * we project these vertices into x-y space. For raster graphics we prepare - * in a different fashion. - *

- * If the generate is unsuccessful, it's usually because of some oversight, - * (for instance if proj is null), and if debugging is enabled, - * a message may be output to the controlling terminal. - *

- * - * @param proj Projection - * @return boolean true if successful, false if not. - * @see #regenerate - */ - public abstract boolean generate(Projection proj); - - /** - * Paint the graphic. This paints the graphic into the Graphics context. - * This is similar to paint() function of java.awt.Components. - * Note that if the graphic has not been generated, it will not be rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGraphics to - * internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGraphic hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - */ - public void render(Graphics g) { - renderShape(g); - renderLabel(g); - } - - /** - * Called from render, just handles rendering of the java.awt.Shape of the - * OMGraphic, as it is currently stored in this OMGraphic. - * - * @param g java.awt.Graphics to render into. - */ - protected void renderShape(Graphics g) { - Shape s = getShape(); - - if (!isRenderable(s)) { - return; - } - - if (matted) { - if (g instanceof Graphics2D && stroke instanceof BasicStroke) { - BasicStroke bs = (BasicStroke) stroke; - ((Graphics2D) g).setStroke(new BasicStroke(bs.getLineWidth() + 2f, bs.getEndCap(), bs.getLineJoin())); - - setGraphicsColor(g, mattingPaint); - draw(g, s); - } - } - - if (shouldRenderFill()) { - setGraphicsForFill(g); - fill(g, s); - - if (textureMask != null && textureMask != fillPaint) { - setGraphicsColor(g, textureMask); - fill(g, s); - } - } - - if (shouldRenderEdge()) { - setGraphicsForEdge(g); - draw(g, s); - } - } - - protected void setHasLabel(boolean val) { - hasLabel = val; - } - - /** - * Quick check of the flag to see if a label attribute has been set. Labels - * are stored in the attribute table, and that table should only be checked - * in a generate() method call, and not in the render(). The setShape() and - * initLabelingDuringGenerate() method calls set this flag which is used to - * opt-out of labeling methods for better performance. - * - * @return true if OMGraphic has label set. - */ - public boolean getHasLabel() { - return hasLabel; - } - - /** - * The method only needs to be called in an OMGraphic's generate method if - * the setShape() method isn't called there. The appropriate - * setLabelLocation method for where the label should be set should be - * called if this method is going to be used. - */ - protected void initLabelingDuringGenerate() { - setHasLabel(getAttribute(LABEL) != null); - } - - /** - * Sets the label location at the center of the polygon points. If the - * hasLabel variable hasn't been set, it no-ops. - * - * @param xpoints - * @param ypoints - * @deprecated use the version with the projection. - */ - public void setLabelLocation(int[] xpoints, int[] ypoints) { - setLabelLocation(xpoints, ypoints, null); - } - - /** - * @see #setLabelLocation(int[], int[]) - * @deprecated use the version with the projection. - */ - public void setLabelLocation(float[] xpoints, float[] ypoints) { - setLabelLocation(xpoints, ypoints, null); - } - - /** - * Checks the attributes for a label and moves the label accordingly. The - * label will be placed in the center of the bounding box around the path. - * - * @param xpoints int[] describing the projected location of the OMGraphic. - * @param ypoints int[] describing the projected location of the OMGraphic. - * @param proj the current projection to do further evaluating of placement. - */ - protected void setLabelLocation(int[] xpoints, int[] ypoints, Projection proj) { - hasLabel = false; - Object obj = getAttribute(LABEL); - if (obj instanceof OMLabeler) { - OMLabeler labeler = (OMLabeler) obj; - - // Go ahead and set the label location if the shape exists. - if (xpoints != null && ypoints != null) { - labeler.setLocation(xpoints, ypoints); - hasLabel = true; - } - - if (proj != null) { - labeler.evaluateRotationAngle(proj); - } - } - } - - /** - * @see #setLabelLocation(int[], int[]) - */ - public void setLabelLocation(float[] xpoints, float[] ypoints, Projection proj) { - int[] xs = new int[xpoints.length]; - int[] ys = new int[ypoints.length]; - for (int i = 0; i < xpoints.length; i++) { - xs[i] = (int) xpoints[i]; - ys[i] = (int) ypoints[i]; - } - setLabelLocation(xs, ys, proj); - } - - /** - * Sets the label location at the given point. If the hasLabel variable - * hasn't been set, it no-ops. - * - * @param p - * @deprecated use the version with Projection. - */ - public void setLabelLocation(Point2D p) { - setLabelLocation(p, null); - } - - /** - * Checks the attributes for a label and moves the label accordingly. The - * label will be placed in the center of the bounding box around the path. - * - * @param p Point2D describing the projected location of the label. - * @param proj the current projection to do further evaluating of placement. - */ - protected void setLabelLocation(Point2D p, Projection proj) { - hasLabel = false; - Object obj = getAttribute(LABEL); - if (obj instanceof OMLabeler) { - OMLabeler labeler = (OMLabeler) obj; - - // Go ahead and set the label location if the shape exists. - if (p != null) { - labeler.setLocation(p); - hasLabel = true; - } - - if (proj != null) { - labeler.evaluateRotationAngle(proj); - } - } - } - - /** - * Sets the label location at the center of the bounding box of the path. If - * the hasLabel variable hasn't been set, it no-ops. - * - * @param gp GeneralPath - * @deprecated use the version with the Projection - */ - public void setLabelLocation(GeneralPath gp) { - setLabelLocation(gp, null); - } - - /** - * Checks the attributes for a label and moves the label accordingly. The - * label will be placed in the center of the bounding box around the path. - * - * @param gp GeneralPath describing the projected location of the OMGraphic. - * @param proj the current projection to do further evaluating of placement. - */ - protected void setLabelLocation(GeneralPath gp, Projection proj) { - hasLabel = false; - Object obj = getAttribute(LABEL); - if (obj instanceof OMLabeler) { - OMLabeler labeler = (OMLabeler) obj; - - // Go ahead and set the label location if the shape exists. - if (gp != null) { - labeler.setLocation(gp); - hasLabel = true; - } - - if (proj != null) { - labeler.evaluateRotationAngle(proj); - } - } - } - - /** - * Checks to see if a label should be painted based on what methods were - * called in generate(), and renders the label if necessary. If the label - * wasn't set up, a quick no-op occurs. - * - * @param g - */ - public void renderLabel(Graphics g) { - if (hasLabel) { - OMLabeler labeler = (OMLabeler) getAttribute(LABEL); - if (labeler != null) { - labeler.render(g); - } - } - } - - /** - * Return true of the fill color/paint should be rendered (not clear). - */ - public boolean shouldRenderFill() { - return !isClear(getFillPaint()); - } - - /** - * Return true if the edge color/paint should be rendered (not clear, or - * doesn't match the fill color). - */ - public boolean shouldRenderEdge() { - // OK, so isClear on the displayPaitn could be inaccurate if - // another thread changes the display paint on the graphic - // before it actually gets rendered. - return !isClear(getDisplayPaint()) || !edgeMatchesFill; - } - - /** - * Return the shortest distance from the graphic to an XY-point. - *

- * - * This method used to be abstract, but with the conversion of OMGraphics to - * internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGraphic hasn't been updated to use Shape - * objects, it should have its own distance method. - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - public float distance(double x, double y) { - float distance = Float.POSITIVE_INFINITY; - if (shouldRenderFill()) { - distance = super.distance(x, y); - } else { - distance = super.distanceToEdge(x, y); - } - - if (distance != Float.POSITIVE_INFINITY) { - distance = normalizeDistanceForLineWidth(distance); - } - - if (hasLabel) { - OMLabeler labeler = (OMLabeler) getAttribute(LABEL); - if (labeler != null) { - float lDistance = labeler.distance(x, y); - if (lDistance < distance) { - distance = lDistance; - } - } - } - - return distance; - } - - /** - * Invoke this to regenerate a "dirty" graphic. This method is a wrapper - * around the generate() method. It invokes - * generate() only if needToRegenerate() on the - * graphic returns true. To force a graphic to be generated, call - * generate() directly. - * - * @param proj the Projection - * @return true if generated, false if didn't do it (maybe a problem). - * @see #generate - */ - public boolean regenerate(Projection proj) { - boolean ret = false; - - if (proj != null) { - ret = super.regenerate(proj); - } - - return ret; - } - - /** - * Used by the GraphicAttributes object to provide a choice on whether the - * line type choice can be changed. - */ - public boolean hasLineTypeChoice() { - return true; - } - - /** - * Generic return of SinkGraphic for subclasses that don't implement clone - * properly. - */ - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - return SinkGraphic.getSharedInstance(); - } - } - - /** - * Write this object to a stream. - */ - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - - // Now write the Stroke and TexturePaint mask. Take into account they - // each could be null. - writeStroke(oos, stroke, OMGraphicAdapter.BASIC_STROKE); - writeTextureMask(oos, textureMask); - } - - protected void writeStroke(ObjectOutputStream oos, Stroke stroke, Stroke defStroke) - throws IOException { - - boolean writeStroke = (stroke != defStroke) && stroke != null; - - if (writeStroke) { - // First write a flag indicating if a Stroke is on the - // stream. - oos.writeBoolean(true); - if (stroke instanceof BasicStroke) { - BasicStroke s = (BasicStroke) stroke; - - // Then write flag indicating stroke is a BasicStroke - oos.writeBoolean(true); - - // Write the Stroke data if a Stroke is on this - // object. - if (s != null) { - oos.writeFloat(s.getLineWidth()); - oos.writeInt(s.getEndCap()); - oos.writeInt(s.getLineJoin()); - oos.writeFloat(s.getMiterLimit()); - oos.writeObject(s.getDashArray()); - oos.writeFloat(s.getDashPhase()); - } - } else if (stroke instanceof Serializable) { - oos.writeBoolean(false); - oos.writeObject((Serializable) stroke); - } - - } else { - oos.writeBoolean(false); - } - } - - /** - * Will only write TexturePaint objects that are Serializable. - * - * @param oos the ObjectOutputStream to write on - * @param tMask the TexturePaint mask - * @throws IOException - */ - protected void writeTextureMask(ObjectOutputStream oos, TexturePaint tMask) throws IOException { - - boolean writeMask = (tMask instanceof Serializable); - - if (writeMask) { - // First write a flag indicating if the Mask is on the - // stream. - oos.writeBoolean(true); - oos.writeObject((Serializable) tMask); - - } else { - oos.writeBoolean(false); - } - } - - /** - * Read this object from a stream. - */ - private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { - ois.defaultReadObject(); - - // Read the Stroke - stroke = readStroke(ois, OMGraphicAdapter.BASIC_STROKE); - textureMask = readTextureMask(ois); - } - - protected Stroke readStroke(ObjectInputStream ois, Stroke defStroke) - throws ClassNotFoundException, IOException { - Stroke stroke = defStroke; - - // Get the flag indicating a stroke was streamed - boolean streamHasStroke = ois.readBoolean(); - - // Read and create the stroke - if (streamHasStroke) { - boolean isBasicStroke = ois.readBoolean(); - if (isBasicStroke) { - float linewidth = ois.readFloat(); - int endcap = ois.readInt(); - int linejoin = ois.readInt(); - float miterlimit = ois.readFloat(); - float dasharray[] = (float[]) ois.readObject(); - float dashphase = ois.readFloat(); - stroke = new BasicStroke(linewidth, endcap, linejoin, miterlimit, dasharray, dashphase); - } else { - stroke = (Stroke) ois.readObject(); - } - } - - return stroke; - } - - protected TexturePaint readTextureMask(ObjectInputStream ois) - throws ClassNotFoundException, IOException { - TexturePaint tPaint = null; - - // Get the flag indicating a stroke was streamed - boolean streamHasTPaint = ois.readBoolean(); - - // Read and create the stroke - if (streamHasTPaint) { - tPaint = (TexturePaint) ois.readObject(); - } - - return tPaint; - } - - /** - * Takes the generic OMGraphic settings from another OMGraphic and pushes - * them to this one. - */ - public void restore(OMGeometry source) { - super.restore(source); - - this.renderType = source.getRenderType(); - if (source instanceof OMGraphic) { - OMGraphic omgSource = (OMGraphic) source; - this.declutterType = omgSource.getDeclutterType(); - this.selected = omgSource.isSelected(); - this.showEditablePalette = omgSource.getShowEditablePalette(); - DrawingAttributes.sTransfer(omgSource, this); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicConstants.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicConstants.java deleted file mode 100644 index 6915f5ae0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicConstants.java +++ /dev/null @@ -1,231 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphicConstants.java,v $ -// $RCSfile: OMGraphicConstants.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/10/10 22:05:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; - -import com.bbn.openmap.proj.LineType; - -/** - * An interface that contains all the constants associated with OMGraphics. - */ -public interface OMGraphicConstants { - - /** Line type is unknown. */ - public final static int LINETYPE_UNKNOWN = 0; - /** Line will be drawn straight between window points. */ - public final static int LINETYPE_STRAIGHT = LineType.Straight; - /** - * Line will be drawn on a constant bearing between two points. - */ - public final static int LINETYPE_RHUMB = LineType.Rhumb; - /** - * Line will be drawn on the shortest geographical path between two - * locations. - */ - public final static int LINETYPE_GREATCIRCLE = LineType.GreatCircle; - - /** Render type is unknown. */ - public final static int RENDERTYPE_UNKNOWN = 0; - /** - * The graphic should be projected relative to its lat/lon position. - */ - public final static int RENDERTYPE_LATLON = 1; - /** - * The graphic should be projected relative to its window position. - */ - public final static int RENDERTYPE_XY = 2; - /** - * The graphic should be projected in window space relative to a lat/lon - * position. - */ - public final static int RENDERTYPE_OFFSET = 3; - - /** - * The graphic should not be moved or be considered in the placement of - * other graphics. - */ - public final static int DECLUTTERTYPE_NONE = 0; - /** - * The graphic should not be moved, but its position should be considered - * when placing other graphics. - */ - public final static int DECLUTTERTYPE_SPACE = 1; - /** - * The graphic should be moved if it is going to share window space with - * another graphic. - */ - public final static int DECLUTTERTYPE_MOVE = 2; - /** - * The graphic should be moved if it is going to share window space with - * another graphic, and a line should be drawn from the new position to the - * original position. - */ - public final static int DECLUTTERTYPE_LINE = 3; - - /** The generic graphic type. */ - public final static int GRAPHICTYPE_GRAPHIC = 0; - /** A bitmap type - OMBitmap. */ - public final static int GRAPHICTYPE_BITMAP = 1; - /** A text type - OMText. */ - public final static int GRAPHICTYPE_TEXT = 2; - /** A polygon/polyline type - OMPoly. */ - public final static int GRAPHICTYPE_POLY = 3; - /** A line type - OMLine. */ - public final static int GRAPHICTYPE_LINE = 4; - /** A rectangle type - OMRect. */ - public final static int GRAPHICTYPE_RECTANGLE = 5; - /** A ellipse/circle type - OMCircle. */ - public final static int GRAPHICTYPE_CIRCLE = 6; - /** A raster type - OMRaster. */ - public final static int GRAPHICTYPE_RASTER = 7; - /** A grid type - OMGrid. */ - public final static int GRAPHICTYPE_GRID = 8; - /** A point type - OMPoint */ - public final static int GRAPHICTYPE_POINT = 9; - /** An arc type - OMArc. */ - public final static int GRAPHICTYPE_ARC = 10; - /** A ellipse type - OMEllipse. */ - public final static int GRAPHICTYPE_ELLIPSE = 11; - - /** - * The float coordinates are in decimal degrees. Should not be used - - * switching over to com.bbn.openmap.proj.Length. - */ - public final static int DECIMAL_DEGREES = 0; - /** - * The float coordinates are in radians. Should not be used - switching over - * to com.bbn.openmap.proj.Length. - */ - public final static int RADIANS = 1; - - /** A transparent color. */ - public final static Color clear = com.bbn.openmap.util.ColorFactory.createColor(0, true); - - /** A Basic Stroke. */ - public final static java.awt.Stroke BASIC_STROKE = new java.awt.BasicStroke(); - - /** - * The default rotation andle to use for java.awt.Graphics2D objects. - */ - public static final double DEFAULT_ROTATIONANGLE = 0.0; - - /** - * Graphic action descriptor mask - raise the graphic on top of others. - */ - public static final int RAISE_TO_TOP_GRAPHIC_MASK = 1 << 0; - /** Graphic action descriptor mask - lower graphics below others. */ - public static final int LOWER_TO_BOTTOM_GRAPHIC_MASK = 1 << 1; - /** Graphic action descriptor mask - delete the graphic. */ - public static final int DELETE_GRAPHIC_MASK = 1 << 2; - /** Graphic action descriptor mask - select the graphic. */ - public static final int SELECT_GRAPHIC_MASK = 1 << 3; - /** Graphic action descriptor mask - deselect the graphic. */ - public static final int DESELECT_GRAPHIC_MASK = 1 << 4; - /** Graphic action descriptor mask - deselect all graphics. */ - public static final int DESELECTALL_GRAPHIC_MASK = 1 << 5; - /** Graphic action descriptor mask - add a graphic. */ - public static final int ADD_GRAPHIC_MASK = 1 << 6; - /** - * Graphic action descriptor mask - update the graphic. Really for - * client/server notification to update. - */ - public static final int UPDATE_GRAPHIC_MASK = 1 << 7; - /** - * Graphic action descriptor mask - raise the graphic relative to others by - * one. - */ - public static final int RAISE_GRAPHIC_MASK = 1 << 8; - /** - * Graphic action descriptor mask - lower down relative to other graphics by - * one. - */ - public static final int LOWER_GRAPHIC_MASK = 1 << 9; - /** - * Graphic action descriptor mask - sort the graphics. The sorting criteria - * depends on local criteria as implemented in the object doing the sorting. - */ - public static final int SORT_GRAPHICS_MASK = 1 << 10; - - /** - * A string that can be used for a keyword into the OMGraphic attribute - * hashtable to designate a tooltip for an OMGraphic. The layer would then - * look for a value for this keyword to display as a tooltip for an - * OMGraphic. - */ - public static final String TOOLTIP = "Tooltip"; - /** - * A string that can be used for a keyword into the OMGraphic attribute - * hashtable to designate something that would be displayed on the - * InformationDelegator's information line for an OMGraphic. The layer would - * then look for a value for this keyword to display in the information line - * for an OMGraphic. - */ - public static final String INFOLINE = "Information Line"; - /** - * A string that can be used for a keyword into the OMGraphic attribute - * hashtable to designate something that would be displayed as a label for - * an OMGraphic. - */ - public static final String LABEL = "Label"; - - /** - * A string that can be used for a keyword into the OMGraphic attribute - * hashtable. If the value exists and is false it means graphic can't be - * removed (there won't be menu item "delete") - */ - public static final String REMOVABLE = "Removable"; - - /** - * A string that can be used for a keyword into the OMGraphic attribute - * hashtable. If the value exists and is false it means graphic change - * appearance can't be changed (there won't be menu item "Change - * appearance") - */ - public static final String CHANGE_APPEARANCE = "ChangeAppearance"; - - /** - * A string that can be used in the attributes to make a note that the - * OMGraphic has changed, and its state should be updated somewhere. - */ - public static final String UPDATED = "Updated"; - - public static final String OMGRAPHIC_ELT = "omgraphic"; - - public static final String OMGRAPHIC_TYPE_ATTR = "type"; - /** - * An attribute that can be set on OMGraphics that can be rotated, so that - * they are not rotated when the map is. - */ - public static final String NO_ROTATE = "norotate"; - /** - * Generic attribute key for index attributes. - */ - public static final String INDEX = "index"; - /** - * Handy attribute key for app object, to speed up updating code that used - * the old app object in OMGraphics instead of using the attributes map. - */ - public static final String APP_OBJECT = "APP_OBJECT"; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHandler.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHandler.java deleted file mode 100644 index 6bcb39570..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHandler.java +++ /dev/null @@ -1,125 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphicHandler.java,v $ -// $RCSfile: OMGraphicHandler.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Shape; - -/** - * This interface describes an object that manages OMGraphics. It - * provides a mechanism to filter what OMGraphics are displayed based - * on some criteria, and can also return graphics based on those - * criteria. - * - * It's assumed that when a filter is applied to an OMGraphicHandler, - * that it stays in place until resetFiltering() is called. Calling - * multiple filters sets a chain. - */ -public interface OMGraphicHandler { - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * within the given shape will be visible. Returns an - * OMGeometryList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. Same as calling - * filter(withinThisShape, true). - * - * @param withinThisShape java.awt.Shape object defining a - * boundary. - * @return OMGraphicList containing OMGraphics that are within the - * Shape. - */ - public OMGraphicList filter(Shape withinThisShape); - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * inside or outside the given shape will be visible. Returns an - * OMGraphicList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. - * - * @param shapeBoundary java.awt.Shape object defining a boundary. - * @param getInsideBoundary if true, the filter will look for - * shapes inside and contacting the boundary. If false, the - * filter will look for shapes outside the boundary. - * @return OMGraphicList containing OMGraphics that are within the - * Shape. - */ - public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary); - - /** - * Returns true if the OMGraphicHandler can handle SQL statements - * for filtering. - */ - public boolean supportsSQL(); - - /** - * Filters the OMGraphicHandler graphic list so that graphics - * meeting the SQL query statement will be visible. Returns an - * OMGraphicList with those visible shapes. The returned list - * should not be assumed to be the same OMGraphicList object that - * is maintained inside the OMGraphicHandler. - * - * @param SQLQuery a SELECT SQL statement - * @return OMGraphicList containing OMGraphics that meet the - * SELECT statement criteria. - */ - public OMGraphicList filter(String SQLQuery); - - /** - * Allows the OMGraphicHandler to receive graphics or take some - * action on one. - * - * @param graphic the OMGraphic to do the action on. - * @param action the OMAction describing what to do to the - * graphic. - * @return true if the action was able to be carried out. - */ - public boolean doAction(OMGraphic graphic, OMAction action); - - /** - * Return the graphic list currently being used by the - * OMGraphicHandler. If filters have been applied, then the - * OMGraphics that have made it through the filter are visible. - * - * @see OMGraphic#isVisible() - */ - public OMGraphicList getList(); - - /** - * Indicates if the OMGraphicHandler can have its OMGraphicList - * set. - */ - public boolean canSetList(); - - /** - * Set the OMGraphicList within this OMGraphicHandler. Works if - * canSetGraphicList == true. - */ - public void setList(OMGraphicList omgl); - - /** - * Remove all filters, and reset all graphics to be visible. - */ - public void resetFiltering(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHash.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHash.java deleted file mode 100644 index 3587dec4b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicHash.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * OMGraphicHash.java - * - * Created on August 18, 2006, 9:29 AM - * - * To change this template, choose Tools | Options and locate the template under - * the Source Creation and Management node. Right-click the template and choose - * Open. You can then make changes to the template in the Source Editor. - */ - -package com.bbn.openmap.omGraphics; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * This is an OMGraphicsList sub-class with a Map interface. Access is backed by - * a HashMap. Insertion and removal of OMGraphics is through the Map interface. - *

- * The add(OMGraphic), addOMGraphic(OMGraphic), remove(OMGraphic), and - * removeOMGraphicAt(int) method are disabled and will throw a RuntimeException - * if called. - *

- * This class is suited for use as the top OMGraphicList in an OMHandlerLayer - * that has a large number of OMGraphic objects and needs to access those - * objects using a unique key. - *

- * - * @see com.bbn.openmap.omGraphics.OMGraphicList - * @author David J. Ward - */ -public class OMGraphicHash - extends OMGraphicList { - - private HashMap graphicHash = new HashMap(); - - /** - * Creates a new instance of OMGraphicHash - */ - public OMGraphicHash() { - super(); - } - - /** - * Construct an OMGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public OMGraphicHash(int initialCapacity) { - super(initialCapacity); - } - - /** - * Returns the value to which this map maps the specified key. Returns - * null if the map contains no mapping for this key. A return value - * of null does not necessarily indicate that the map - * contains no mapping for the key; it's also possible that the map - * explicitly maps the key to null. The containsKey - * operation may be used to distinguish these two cases. - * - *

- * More formally, if this map contains a mapping from a key k to a - * value v such that (key==null ? k==null : - * key.equals(k)), then this method returns v; otherwise it - * returns null. (There can be at most one such mapping.) - * - * @param obj key whose associated value is to be returned. - * @return the value to which this map maps the specified key, or - * null if the map contains no mapping for this key. - * - * @throws ClassCastException if the key is of an inappropriate type for - * this map (optional). - * @throws NullPointerException if the key is null and this map - * does not permit null keys (optional). - * - * @see #containsKey(Object) - */ - public OMGraphic get(Object obj) { - return graphicHash.get(obj); - } - - /** - * Returns true if this map contains a mapping for the specified - * key. More formally, returns true if and only if this map - * contains a mapping for a key k such that - * (key==null ? k==null : key.equals(k)). (There can be at most one - * such mapping.) - * - * @param obj key whose presence in this map is to be tested. - * @return true if this map contains a mapping for the specified - * key. - * - * @throws ClassCastException if the key is of an inappropriate type for - * this map (optional). - * @throws NullPointerException if the key is null and this map - * does not permit null keys (optional). - */ - public boolean containsKey(Object obj) { - return graphicHash.containsKey(obj); - } - - /** - * Returns true if this map maps one or more keys to the specified - * value. More formally, returns true if and only if this map - * contains at least one mapping to a value v such that - * (value==null ? v==null : value.equals(v)). This operation will - * probably require time linear in the map size for most implementations of - * the Map interface. - * - * @param obj value whose presence in this map is to be tested. - * @return true if this map maps one or more keys to the specified - * value. - * @throws ClassCastException if the value is of an inappropriate type for - * this map (optional). - * @throws NullPointerException if the value is null and this map - * does not permit null values (optional). - */ - public boolean containsValue(OMGraphic obj) { - return graphicHash.containsValue(obj); - } - - /** - * Returns a set view of the mappings contained in this map. Each element in - * the returned set is a {@link java.util.Map.Entry}. The set is backed by the map, so - * changes to the map are reflected in the set, and vice-versa. If the map - * is modified while an iteration over the set is in progress (except - * through the iterator's own remove operation, or through the - * setValue operation on a map entry returned by the iterator) the - * results of the iteration are undefined. The set supports element removal, - * which removes the corresponding mapping from the map, via the - * Iterator.remove, Set.remove, removeAll, - * retainAll and clear operations. It does not support the - * add or addAll operations. - * - * @return a set view of the mappings contained in this map. - */ - public java.util.Set> entrySet() { - return graphicHash.entrySet(); - } - - /** - * Returns a set view of the keys contained in this map. The set is backed - * by the map, so changes to the map are reflected in the set, and - * vice-versa. If the map is modified while an iteration over the set is in - * progress (except through the iterator's own remove operation), - * the results of the iteration are undefined. The set supports element - * removal, which removes the corresponding mapping from the map, via the - * Iterator.remove, Set.remove, removeAll - * retainAll, and clear operations. It does not support - * the add or addAll operations. - * - * @return a set view of the keys contained in this map. - */ - public java.util.Set keySet() { - return graphicHash.keySet(); - } - - /** - * Associates the specified value with the specified key in this map - * (optional operation). If the map previously contained a mapping for this - * key, the old value is replaced by the specified value. (A map m - * is said to contain a mapping for a key k if and only if - * {@link #containsKey(Object) m.containsKey(k)} would return true - * .)) - * - * @param key key with which the specified value is to be associated. - * @param graphic value to be associated with the specified key. - * @return previous value associated with specified key, or null if - * there was no mapping for key. A null return can also - * indicate that the map previously associated null with - * the specified key, if the implementation supports null - * values. - * - * @throws UnsupportedOperationException if the put operation is - * not supported by this map. - * @throws ClassCastException if the class of the specified key or value - * prevents it from being stored in this map. - * @throws IllegalArgumentException if some aspect of this key or value - * prevents it from being stored in this map. - * @throws NullPointerException if this map does not permit null - * keys or values, and the specified key or value is null. - */ - public Object put(Object key, OMGraphic graphic) { - - // first remove the OMGraphic from the list - // Don't allow duplicate graphics in hash, that is multiple - // key resolving to a single graphic. This would be very bad. - if (graphicHash.containsValue(graphic)) { - // now we know that we have this graphic in the - // hash, now lets find the associated key. - // This requires walkin the keySet. - ArrayList keysToRemove = new ArrayList(); - for (Map.Entry entry : graphicHash.entrySet()) { - if (entry.getValue().equals(graphic)) { - keysToRemove.add((Object) entry.getKey()); - } - } - for (Object obj : keysToRemove) { - graphicHash.remove(obj); - } - - super.remove((OMGraphic) graphic); - } - - if (graphicHash.containsKey(key)) { - super.remove((OMGraphic) graphic); - } - - super.add(graphic); - return graphicHash.put(key, graphic); - } - - /** - * Copies all of the mappings from the specified map to this map (optional - * operation). The effect of this call is equivalent to that of calling - * {@link #put(Object,OMGraphic) put(k, v)} on this map once for each - * mapping from key k to value v in the specified map. The - * behavior of this operation is unspecified if the specified map is - * modified while the operation is in progress. - * - * @param map Mappings to be stored in this map. - * - * @throws UnsupportedOperationException if the putAll method is - * not supported by this map. - * - * @throws ClassCastException if the class of a key or value in the - * specified map prevents it from being stored in this map. - * - * @throws IllegalArgumentException some aspect of a key or value in the - * specified map prevents it from being stored in this map. - * @throws NullPointerException if the specified map is null, or if - * this map does not permit null keys or values, and the - * specified map contains null keys or values. - */ - public void putAll(Map map) { - graphicHash.putAll(map); - } - - /** - * Removes the mapping for this key from this map if it is present (optional - * operation). More formally, if this map contains a mapping from key - * k to value v such that - * (key==null ? k==null : key.equals(k)), that mapping is - * removed. (The map can contain at most one such mapping.) - * - *

- * Returns the value to which the map previously associated the key, or - * null if the map contained no mapping for this key. (A - * null return can also indicate that the map previously associated - * null with the specified key if the implementation supports - * null values.) The map will not contain a mapping for the - * specified key once the call returns. - * - * @param key key whose mapping is to be removed from the map. - * @return previous value associated with specified key, or null if - * there was no mapping for key. - * - * @throws ClassCastException if the key is of an inappropriate type for - * this map (optional). - * @throws NullPointerException if the key is null and this map - * does not permit null keys (optional). - * @throws UnsupportedOperationException if the remove method is - * not supported by this map. - */ - public boolean remove(Object key) { - OMGraphic graphic = graphicHash.remove(key); - return super.remove(graphic); - } - - /** - * Returns a collection view of the values contained in this map. The - * collection is backed by the map, so changes to the map are reflected in - * the collection, and vice-versa. If the map is modified while an iteration - * over the collection is in progress (except through the iterator's own - * remove operation), the results of the iteration are undefined. - * The collection supports element removal, which removes the corresponding - * mapping from the map, via the Iterator.remove, - * Collection.remove, removeAll, retainAll and - * clear operations. It does not support the add or addAll - * operations. - * - * @return a collection view of the values contained in this map. - */ - public java.util.Collection values() { - return graphicHash.values(); - } - - /** used to hold off the IllegalArgumentException during cloning */ - private boolean cloningInProgress; - - /** - * @return a duplicate list full of shallow copies of each of the OMGraphics - * contained on the list. - */ - public synchronized Object clone() { - cloningInProgress = true; - OMGraphicHash omgl = (OMGraphicHash) super.clone(); - omgl.graphicHash = (HashMap) graphicHash.clone(); - cloningInProgress = false; - return omgl; - } - - /** - * Add an OMGraphic to the list. - *

- * For OMGraphicHash this method will throw an - * IllegalArgumentException because adding a graphic must be - * done through put(key,value). - */ - public boolean add(OMGraphic g) { - // Prevent adding a graphic using the OMGraphic List. - // OMGraphicHash entry must be added through the Map interface. - if (cloningInProgress) { - return super.add(g); - } - throw new RuntimeException("addOMGraphic() not permitted for OMGraphicHash(). Use put(key, OMGraphic) instead."); - } - - /** - * Remove the graphic at the location number. - * - *

- * For OMGraphicHash this method will throw an - * IllegalArgumentException because removing a graphic must be - * done through remove(key). - * - * @param location the location of the OMGraphic to remove. - */ - public OMGraphic remove(int location) { - // Prevent removing a specific graphic using the OMGraphic List. - // OMGraphicHash entry must be remove using remove(Object). - throw new RuntimeException("removeOMGraphicAt() not permitted for OMGraphicHash(). Use remove(key) instead."); - } - - /** - * Remove the graphic. - * - *

- * For OMGraphicHash this method will throw an - * IllegalArgumentException because removing a graphic must be - * done through remove(key). - * - * @param graphic the OMGraphic object to remove. - * @return true if graphic was on the list, false if otherwise. - */ - public boolean remove(OMGraphic graphic) { - // Prevent removing a specific graphic using the OMGraphic List. - // OMGraphicHash entry must be remove using remove(Object). - throw new RuntimeException("remove(OMGraphic) not permitted for OMGraphicHash(). Use remove(key) instead."); - } - - /** - * Remove all elements from the graphic list. - */ - public void clear() { - super.clear(); - graphicHash.clear(); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMGraphicHash) { - this.putAll(((OMGraphicHash)source).graphicHash); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicList.java deleted file mode 100644 index 0c8243fad..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGraphicList.java +++ /dev/null @@ -1,483 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphicList.java,v $ -// $RCSfile: OMGraphicList.java,v $ -// $Revision: 1.22 $ -// $Date: 2009/02/20 17:15:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Paint; -import java.awt.TexturePaint; -import java.io.EOFException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OptionalDataException; -import java.io.Serializable; -import java.net.URL; -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 com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * This class encapsulates a List of OMGraphics. - *

- * There are several things that this list does that make it better that any ol' - * List. You can make several common OMGraphic modification calls on the list, - * and the list handles the iteration and changing of all the graphics while - * taking into account a travese order. - *

- * An additional benefit is that because the OMGraphicList extends OMGraphic it - * can contain other instances of OMGraphicList. This way you can manage - * groupings of graphics, (for instance, an OMGraphicList of OMGraphicLists - * which each have an OMRaster and OMText). - *

- * Many methods, such as generate() and findClosest() traverse the items in the - * GraphicsList recursively. The direction that the list is traversed is - * controlled by then traverseMode variable. The traverseMode mode lets you set - * whether the first or last object added to the list (FIRST_ADDED_ON_TOP or - * LAST_ADDED_ON_TOP) is drawn on top of the list and considered first for - * searches. - */ -public class OMGraphicList extends OMList implements Serializable { - - /** - * Construct an OMGraphicList. - */ - public OMGraphicList() { - this(10); - } - - /** - * Construct an OMGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public OMGraphicList(int initialCapacity) { - graphics = Collections.synchronizedList(new ArrayList(initialCapacity)); - } - - /** - * Construct an OMGraphicList to include a Collection of OMGraphics. - * - * @param c Collection of OMGraphics. - */ - public OMGraphicList(Collection c) { - graphics.addAll(c); - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public Iterator iteratorCopy() { - return new OMGraphicList(graphics).iterator(); - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public ListIterator listIteratorCopy() { - return new OMGraphicList(graphics).listIterator(); - } - - /** - * Returns a iterator of a shallow copy of the current list, to avoid - * concurrent modification exceptions if the list is being generated or - * rendered while the list is being reviewed for other reasons. - */ - public ListIterator listIteratorCopy(int size) { - return new OMGraphicList(graphics).listIterator(size); - } - - /** - * Add an OMGraphic to the list. - */ - public boolean add(OMGraphic g) { - checkForDuplicate(g); - return graphics.add(g); - } - - /** - * Set the graphic at the specified location. The OMGraphic must not be - * null. - * - * @param graphic OMGraphic - * @param index index of the OMGraphic to return - * @exception ArrayIndexOutOfBoundsException if index is out-of-bounds - */ - public void setOMGraphicAt(OMGraphic graphic, int index) { - graphics.set(index, graphic); - } - - public OMGraphic getOMGraphicAt(int index) { - return get(index); - } - - /** - * Get the geometry at the location number on the list. - * - * @param location the location of the OMGraphic to return - * @return OMGraphic or null if location > list size - * @exception ArrayIndexOutOfBoundsException if location < 0 - * or location >= - * this.size() - */ - public OMGraphic get(int location) { - return graphics.get(location); - } - - /** - * Set the stroke of all the graphics on the list. - * - * @param stroke the stroke object to use. - */ - public void setStroke(java.awt.Stroke stroke) { - super.setStroke(stroke); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setStroke(stroke); - } - } - } - - /** - * Set the fill paint for all the objects on the list. - * - * @param paint java.awt.Paint - */ - public void setFillPaint(Paint paint) { - super.setFillPaint(paint); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setFillPaint(paint); - } - } - } - - /** - * Set the texture mask for the OMGraphics on the list. If not null, then it - * will be rendered on top of the fill paint. If the fill paint is clear, - * the texture mask will not be used. If you just want to render the texture - * mask as is, set the fill paint of the graphic instead. This is really to - * be used to have a texture added to the graphic, with the fill paint still - * influencing appearance. - */ - public void setTextureMask(TexturePaint texture) { - super.setTextureMask(texture); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setTextureMask(texture); - } - } - } - - /** - * Set the line paint for all the objects on the list. - * - * @param paint java.awt.Paint - */ - public void setLinePaint(Paint paint) { - super.setLinePaint(paint); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setLinePaint(paint); - } - } - } - - /** - * Set the selection paint for all the objects on the list. - * - * @param paint java.awt.Paint - */ - public void setSelectPaint(Paint paint) { - super.setSelectPaint(paint); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setSelectPaint(paint); - } - } - } - - /** - * Set the matting paint for all the objects on the list. - * - * @param paint java.awt.Paint - */ - public void setMattingPaint(Paint paint) { - super.setMattingPaint(paint); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setMattingPaint(paint); - } - } - } - - /** - * Set the matting flag for all the objects on the list. - */ - public void setMatted(boolean value) { - super.setMatted(value); - synchronized (graphics) { - for (OMGraphic omg : graphics) { - omg.setMatted(value); - } - } - } - - /** - * Goes through the list, finds the OMGrid objects, and sets the generator - * for all of them. If a projection is passed in, the generator will be used - * to create a displayable graphic within the grid. - * - * @param generator an OMGridGenerator to create a renderable graphic from - * the OMGrid. - * @param proj a projection to use to generate the graphic. If null, the - * generator will create a renderable graphic the next time a - * projection is handed to the list. - */ - public void setGridGenerator(OMGridGenerator generator, - Projection proj) { - synchronized (graphics) { - for (OMGraphic graphic : graphics) { - if (graphic instanceof OMGrid) { - ((OMGrid) graphic).setGenerator(generator); - if (proj != null) { - graphic.generate(proj); - } - } - } - } - } - - /** - * Get a reference to the graphics vector. This method is meant for use by - * methods that need to iterate over the graphics vector, or make at least - * two invocations on the graphics vector. - *

- * HACK this method should either return a clone of the graphics list or a - * quick reference. Currently it returns the latter for simplicity and minor - * speed improvement. We should allow a way for the user to set the desired - * behavior, depending on whether they want responsibility for list - * synchronization. Right now, the user is responsible for synchronizing the - * OMGraphicList if it's being used in two or more threads... - * - * @return a reference of the graphics List. - */ - public List getTargets() { - if (graphics == null) { - // make sure that the graphics vector is not null, - // since all of the internal methods rely on it. - graphics = Collections.synchronizedList(new ArrayList(10)); - } - - return graphics; - } - - /** - * Set the List used to hold the OMGraphics. The OMGraphicList assumes that - * this list contains OMGraphics. Make *SURE* this is the case. The - * OMGraphicList will behave badly if there are non-OMGraphics on the list. - */ - public void setTargets(List list) { - graphics = Collections.synchronizedList(new ArrayList(list)); - } - - /** - * Read a cache of OMGraphics, given an URL. - * - * @param cacheURL URL of serialized graphic list. - */ - public void readGraphics(URL cacheURL) throws IOException { - - try { - ObjectInputStream objstream = new ObjectInputStream(cacheURL.openStream()); - - if (Debug.debugging("omgraphics")) { - Debug.output("OMGraphicList: Opened " + cacheURL.toString()); - } - - readGraphics(objstream); - objstream.close(); - - if (Debug.debugging("omgraphics")) { - Debug.output("OMGraphicList: closed " + cacheURL.toString()); - } - - } catch (ArrayIndexOutOfBoundsException aioobe) { - throw new com.bbn.openmap.util.HandleError(aioobe); - } catch (ClassCastException cce) { - cce.printStackTrace(); - } - } - - /** - * Read a cache of OMGraphics, given a ObjectInputStream. - * - * @param objstream ObjectInputStream of graphic list. - */ - public void readGraphics(ObjectInputStream objstream) - throws IOException { - - Debug.message("omgraphics", "OMGraphicList: Reading cached graphics"); - - try { - while (true) { - try { - OMGraphic omg = (OMGraphic) objstream.readObject(); - graphics.add(omg); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (OptionalDataException ode) { - ode.printStackTrace(); - } - } - } catch (EOFException e) { - } - } - - /** - * Write the graphics out to a file - * - * @param graphicsSaveFile - */ - public void writeGraphics(String graphicsSaveFile) throws IOException { - - FileOutputStream ostream = new FileOutputStream(graphicsSaveFile); - ObjectOutputStream objectstream = new ObjectOutputStream(ostream); - writeGraphics(objectstream); - objectstream.close(); - } - - /** - * Write the graphics out to a ObjectOutputStream - * - * @param objectstream ObjectOutputStream - */ - public void writeGraphics(ObjectOutputStream objectstream) - throws IOException { - - synchronized (graphics) { - for (Iterator it = iterator(); it.hasNext();) { - OMGraphic g = it.next(); - try { - objectstream.writeObject(g); - } catch (IOException e) { - Debug.error("OMGraphicList: Couldn't write object " + g - + "\nOMGraphicList: Reason: " + e.toString()); - } - } - } - objectstream.close(); - } - - /** - * This sort method is a place-holder for OMGraphicList extensions to - * implement their own particular criteria for sorting an OMGraphicList. - * Does nothing for a generic OMGraphicList. - */ - public void sort() {} - - /** - * Convenience method to cast an object to an OMGraphic if it is one. - * Returns null if it isn't. - */ - protected OMGraphic objectToOMGraphic(Object obj) { - if (obj instanceof OMGraphic) { - return (OMGraphic) obj; - } else { - return null; - } - } - - /** - * @return a duplicate list full of shallow copies of each of the OMGraphics - * contained on the list. - */ - public Object clone() { - OMGraphicList omgl = (OMGraphicList) super.clone(); - synchronized(graphics){ - for (OMGraphic omg : graphics) { - // If the OMGraphic doesn't provide a copy (providing a - // SinkGraphic instead), oh well. - if (omg instanceof OMGraphicList) { - omgl.add((OMGraphic) ((OMGraphicList) omg).clone()); - } else { - omgl.graphics.add(omg); - } - } - } - return omgl; - } - - @Override - public OMList create() { - return new OMGraphicList(); - } - - @Override - protected com.bbn.openmap.omGraphics.OMList.OMDist createDist() { - return new OMDist(); - } - - public void add(int index, OMGraphic element) { - setNeedToRegenerate(true); - super.add(index, element); - } - - public boolean addAll(Collection c) { - setNeedToRegenerate(true); - return graphics.addAll(c); - } - - public boolean addAll(int index, Collection c) { - setNeedToRegenerate(true); - return graphics.addAll(index, c); - } - - public OMGraphic set(int index, OMGraphic element) { - setNeedToRegenerate(true); - return graphics.set(index, element); - } - - /** - * Remove the geometry at the location number. - * - * @param location the location of the OMGeometry to remove - */ - public OMGraphic remove(int location) { - OMGraphic obj = super.remove(location); - if (obj != null) { - setNeedToRegenerate(true); - } - return obj; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGrid.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGrid.java deleted file mode 100644 index 0335477b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMGrid.java +++ /dev/null @@ -1,938 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGrid.java,v $ -// $RCSfile: OMGrid.java,v $ -// $Revision: 1.11 $ -// $Date: 2006/02/16 16:22:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.Point; - -import com.bbn.openmap.omGraphics.grid.GridData; -import com.bbn.openmap.omGraphics.grid.OMGridData; -import com.bbn.openmap.omGraphics.grid.OMGridGenerator; -import com.bbn.openmap.omGraphics.grid.OMGridObjects; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * An OMGrid object is a two-dimensional container object for data. The grid can - * be laid out in geographic or pixel space. There are two different ways that - * the OMGrid can be used. - *

- * The data placed in the array can represent the attributes of what you want - * the grid to represent - elevation values, temperatures, etc. In order to - * render the data on the screen, you'll need to set the OMGridGenerator object, - * and let it interpret the data to create the desired OMGraphics for you. - *

- * The OMGrid data values can also contain integer ID keys for objects contained - * in the OMGridObjects object held by the OMGrid. By using the OMGrid in this - * way, the OMGrid becomes a placeholder for other graphics, and will manage the - * generate() function calls to those objects that are on the screen. - *

- * The OMGridGenerator object will take precedence over the OMGridObjects - If - * the OMGridGenerator is set within the grid, the OMGridGenerator will create - * the OMGraphics to be displayed for the grid, as opposed the OMGridObjects - * getting a chance to generate themselves. The OMGrid extends OMGraphicList, - * and the OMGraphics that the OMGridGenerator creates are added to the OMGrid. - * If you want the OMGrid to hide the OMGraphics that are created, make it - * vague. - */ -public class OMGrid - extends OMGraphicList { - - /** - * The orientation angle of the grid, in radians. Up/North is zero. - */ - protected double orientation; - /** - * Number of rows in the data array. Gets set by the OMGrid depending on the - * major of the grid. - */ - protected int rows; - /** - * Number of columns in the data array. Gets set by the OMGrid depending on - * the major of the grid. - */ - protected int columns; - /** - * The starting latitude point of the grid. Only relevant when the data - * points are laid out in a lat/lon grid, or when an x/y grid is anchored to - * a lat/lon location. DOES NOT follow the OpenMap convention where area - * object locations are defined by the upper left location - the location of - * the grid is noted by the lower left corner, because grid data is usually - * defined by the lower left location. Makes it easier to deal with overlap - * rows and columns, and to calculate the locations of the rows and columns. - */ - protected double latitude; - /** - * The starting longitude point of the grid. Only relevant when the data - * points are laid out in a lat/lon grid, or when an x/y grid is anchored to - * a lat/lon location. DOES NOT follow the OpenMap convention where area - * object locations are defined by the upper left location - the location of - * the grid is noted by the lower left corner, because grid data is usually - * defined by the lower left location. Makes it easier to deal with overlap - * rows and columns, and to calculate the locations of the rows and columns. - */ - protected double longitude; - /** - * The vertical/latitude interval, the distance between row data points in - * the vertical direction. For x/y grids, this can server as a pixel - * multiplier. For lat/lon grids, it represents the decimal degrees between - * grid points. - */ - protected double verticalResolution; - /** - * The horizontal/longitude interval, the distance between column data - * points in the horizontal direction. For x/y grids, this can server as a - * pixel multiplier. For lat/lon grids, it represents the decimal degrees - * between grid points. - */ - protected double horizontalResolution; - /** - * The Object holding the data for the OMGrid. The GridData abstracts the - * type of data that is held by the OMGrid. Note: the 0 index of the array - * in both directions is in the lower left corner of the matrix. As you - * increase indexes in both dimensions, you go up-right. - */ - public GridData data; - /** - * If needed, the data array can hold numerical identifiers, which are keys - * to objects stored in this hashtable. That way, the grid can be used to - * hold an array of objects. If the objs are set, then the OMGrid object - * automatically assumes that all graphic operations are supposed to involve - * the objs. - */ - protected OMGridObjects gridObjects = null; - /** - * Horizontal screen location of the upper left corner of the grid in - * pixels, before projection, of XY and OFFSET grids. - */ - protected Point point = null; - /** - * Horizontal screen location of the upper left corner of the grid in - * pixels, after projection. - */ - public Point point1 = null; - /** - * Horizontal screen location of the lower right corner of the grid in - * pixels, after projection. - */ - public Point point2 = null; - /** - * Pixel height of grid, set after generate. For non-equidistant - * projections, this will be a bounding box height. - */ - public int height = 0; - /** - * Pixel width of grid, set after generate. For non-equidistant projections, - * this will be a bounding box width. - */ - public int width = 0; - - /** - * Value of a bad/invalid point in the grid. Has roots in the DTED way of - * doing things. - */ - public final static int GRID_NULL = -32767; - - /** An object that knows how to generate graphics for the matrix. */ - protected OMGridGenerator generator = null; - - /** - * Means that the first dimension of the array refers to the column count. - */ - public static final boolean COLUMN_MAJOR = true; - /** - * Means that the first dimension of the array refers to the row count. - */ - public static final boolean ROW_MAJOR = false; - /** - * Keep track of which dimension different parts of the double array - * represent. COLUMN_MAJOR is the default, meaning that the first dimension - * of the array represents the vertical location in the array, and the - * second is the horizontal location in the array. - */ - protected boolean major = COLUMN_MAJOR; - - /** - * The units, if needed, of the values contained in the grid data array. - * Null value is default and acceptable. - */ - protected Length units = null; - - /** Default constructor. */ - public OMGrid() { - } - - /** - * Create a OMGrid that covers a lat/lon area. Column major by default. If - * your data is row major, use null for the data, set the major direction, - * and then set the data. - * - * @param lat latitude of lower left corner of the grid, in decimal degrees. - * @param lon longitude of lower left corner of the grid, in decimal - * degrees. - * @param vResolution the vertical resolution of the data, as decimal - * degrees per row. - * @param hResolution the horizontal resolution of the data, as decimal - * degrees per column. - * @param data a double array of integers, representing the rows and columns - * of data. - */ - public OMGrid(double lat, double lon, double vResolution, double hResolution, int[][] data) { - setRenderType(RENDERTYPE_LATLON); - set(lat, lon, 0, 0, vResolution, hResolution, data); - } - - /** - * Create a OMGrid that covers a x/y screen area.Column major by default. If - * your data is row major, use null for the data, set the major direction, - * and then set the data. - * - * @param x horizontal location, in pixels, of the left side of the grid - * from the left side of the map. - * @param y vertical location, in pixels, of the top of the grid from the - * top side of the map. - * @param vResolution the vertical resolution of the data, as pixels per - * row. - * @param hResolution the horizontal resolution of the data, as pixels per - * column. - * @param data a double array of integers, representing the rows and columns - * of data. - */ - public OMGrid(int x, int y, double vResolution, double hResolution, int[][] data) { - setRenderType(RENDERTYPE_XY); - set(0.0f, 0.0f, x, y, vResolution, hResolution, data); - } - - /** - * Create a OMGrid that covers a x/y screen area, anchored to a lat/lon - * point. Column major by default. If your data is row major, use null for - * the data, set the major direction, and then set the data. - * - * @param lat latitude of the anchor point of the grid, in decimal degrees. - * @param lon longitude of the anchor point of the grid, in decimal degrees. - * @param x horizontal location, in pixels, of the left side of the grid - * from the longitude anchor point. - * @param y vertical location, in pixels, of the top of the grid from the - * latitude anchor point. - * @param vResolution the vertical resolution of the data, as pixels per - * row. - * @param hResolution the horizontal resolution of the data, as pixels per - * column. - * @param data a double array of integers, representing the rows and columns - * of data. - */ - public OMGrid(double lat, double lon, int x, int y, double vResolution, double hResolution, int[][] data) { - setRenderType(RENDERTYPE_OFFSET); - set(lat, lon, x, y, vResolution, hResolution, data); - } - - /** - * Create a OMGrid that covers a lat/lon area. Column major by default. If - * your data is row major, use null for the data, set the major direction, - * and then set the data. - * - * @param lat latitude of lower left corner of the grid, in decimal degrees. - * @param lon longitude of lower left corner of the grid, in decimal - * degrees. - * @param vResolution the vertical resolution of the data, as decimal - * degrees per row. - * @param hResolution the horizontal resolution of the data, as decimal - * degrees per column. - * @param data GridData object holding rows and columns of grid data. - */ - public OMGrid(double lat, double lon, double vResolution, double hResolution, GridData data) { - setRenderType(RENDERTYPE_LATLON); - set(lat, lon, 0, 0, vResolution, hResolution, data); - } - - /** - * Create a OMGrid that covers a x/y screen area.Column major by default. If - * your data is row major, use null for the data, set the major direction, - * and then set the data. - * - * @param x horizontal location, in pixels, of the left side of the grid - * from the left side of the map. - * @param y vertical location, in pixels, of the top of the grid from the - * top side of the map. - * @param vResolution the vertical resolution of the data, as pixels per - * row. - * @param hResolution the horizontal resolution of the data, as pixels per - * column. - * @param data GridData object holding rows and columns of grid data. - */ - public OMGrid(int x, int y, double vResolution, double hResolution, GridData data) { - setRenderType(RENDERTYPE_XY); - set(0.0f, 0.0f, x, y, vResolution, hResolution, data); - } - - /** - * Create a OMGrid that covers a x/y screen area, anchored to a lat/lon - * point. Column major by default. If your data is row major, use null for - * the data, set the major direction, and then set the data. - * - * @param lat latitude of the anchor point of the grid, in decimal degrees. - * @param lon longitude of the anchor point of the grid, in decimal degrees. - * @param x horizontal location, in pixels, of the left side of the grid - * from the longitude anchor point. - * @param y vertical location, in pixels, of the top of the grid from the - * latitude anchor point. - * @param vResolution the vertical resolution of the data, as pixels per - * row. - * @param hResolution the horizontal resolution of the data, as pixels per - * column. - * @param data GridData object holding rows and columns of grid data. - */ - public OMGrid(double lat, double lon, int x, int y, double vResolution, double hResolution, GridData data) { - setRenderType(RENDERTYPE_OFFSET); - set(lat, lon, x, y, vResolution, hResolution, data); - } - - /** - * Set the parameters of the OMGrid after construction. - */ - protected void set(double lat, double lon, int x, int y, double vResolution, double hResolution, int[][] data) { - set(lat, lon, x, y, vResolution, hResolution, new OMGridData.Int(data)); - } - - /** - * Set the parameters of the OMGrid after construction. - */ - protected void set(double lat, double lon, int x, int y, double vResolution, double hResolution, GridData data) { - latitude = lat; - longitude = lon; - point = new Point(x, y); - verticalResolution = vResolution; - horizontalResolution = hResolution; - setData(data); - } - - /** - * Set the vertical number of data points. Should correspond to the the - * data, and to the major setting of the OMGrid. Will be set automatically - * when the data is set. - * - * @deprecated set when data is set. - */ - public void setRows(int rows) { - // this.rows = rows; - } - - /** - * Get the vertical number of data points. - */ - public int getRows() { - if (data != null) { - return data.getNumRows(); - } else { - return 0; - } - } - - public void setLatitude(double lat) { - if (latitude == lat) - return; - latitude = lat; - setNeedToRegenerate(true); - } - - /** - * Get the latitude of the lower left anchor point of the grid, in decimal - * degrees. - */ - public double getLatitude() { - return latitude; - } - - public void setLongitude(double lon) { - if (longitude == lon) - return; - longitude = lon; - setNeedToRegenerate(true); - } - - /** - * Get the latitude of the lower left anchor point of the grid, in decimal - * degrees. - */ - public double getLongitude() { - return longitude; - } - - /** - * Get the screen location, or x/y offset from the lat/lon anchor point, of - * the lower left corner of the grid. - */ - public Point getPoint() { - return point; - } - - /** - * Set the horizontal number of data points. Should correspond to the the - * data, and to the major setting of the OMGrid. Will be set automatically - * when the data is set. Does nothing. - * - * @deprecated set when the data is set - */ - public void setColumns(int columns) { - // this.columns = columns; - } - - /** - * Set the horizontal number of data points. - */ - public int getColumns() { - if (data != null) { - return data.getNumColumns(); - } else { - return 0; - } - } - - /** - * Set which dimension is defined first in the two dimensional array. If - * COLUMN_MAJOR (true and the default), the first dimension of the data - * array will represent the horizontal location of the data, and the second - * dimension will represent the vertical location. Vice versa for - * COLUMN_ROW. Calling this method will reset the column and row count to - * match the data to the new orientation. - */ - public void setMajor(boolean maj) { - if (data != null && maj != data.getMajor()) { - data.setMajor(maj); - } - } - - /** - * Set which dimension is defined first in the two dimensional array. - */ - public boolean getMajor() { - if (data != null) { - return data.getMajor(); - } - return major; - } - - /** - * Set the angle that the grid should be rotated. May not be implemented for - * some OMGridGenerators. - * - * @param orient is the angle of the grid, in radians. Up/North is zero. - */ - public void setOrientation(double orient) { - orientation = orient; - } - - /** - * Get the angle that was set for the grid to be rotated. In radians, - * up/north is zero. - */ - public double getOrientation() { - return orientation; - } - - /** - * Set the data of the grid. The major setting will cause this method to set - * the number of rows and columns accordingly. The values in the array will - * be interpreted to the OMGridGenerator that you provide to this OMGrid. - * The OMGridGenerator will create what gets drawn on the map based on this - * data. The int[][] will be wrapped by a GridData.Int object. - */ - public void setData(int[][] data) { - setData(new OMGridData.Int(data)); - } - - /** - * Set the data of the grid. The major setting will cause this method to set - * the number of rows and columns accordingly. The values in the array will - * be interpreted to the OMGridGenerator that you provide to this OMGrid. - * The OMGridGenerator will create what gets drawn on the map based on this - * data. - */ - public void setData(GridData data) { - this.data = data; - } - - /** - * Get the data array for the OMGrid. What these numbers represent depends - * on what OMGridGenerator is being used. - */ - public GridData getData() { - return data; - } - - /** - * There is an option in the OMGrid where the data array contains ID numbers - * for a set of other objects. So the grid holds onto the location of these - * objects, and the OMGridObjects provides the ID mapping to the actual - * object. - */ - public void setGridObjects(OMGridObjects someGridObjs) { - gridObjects = someGridObjs; - } - - /** - * Get the OMGridObjects containing the mapping of the data array IDs to a - * set of Objects. - */ - public OMGridObjects getGridObjects() { - return gridObjects; - } - - /** - * Set the OMGridGenerator that will interpret the data array and create - * OMGraphics for it. - */ - public void setGenerator(OMGridGenerator aGenerator) { - generator = aGenerator; - } - - /** - * Get the OMGridGenerator being used to interpret the data array. - */ - public OMGridGenerator getGenerator() { - return generator; - } - - /** - * Set the number of decimal degrees between horizontal rows. - */ - public void setVerticalResolution(double vRes) { - verticalResolution = vRes; - } - - /** - * Get the number of decimal degrees between horizontal rows. - */ - public double getVerticalResolution() { - return verticalResolution; - } - - /** - * Set the number of decimal degrees between vertical columns. - */ - public void setHorizontalResolution(double hRes) { - horizontalResolution = hRes; - } - - /** - * Get the number of decimal degrees between vertical columns. - */ - public double getHorizontalResolution() { - return horizontalResolution; - } - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - /** - * Set the units for the grid data. - */ - public void setUnits(Length length) { - units = length; - } - - /** - * Get the units for the grid data. - */ - public Length getUnits() { - return units; - } - - /** - * Generate OMGraphics based on the data array. If there is an - * OMGridGenerator, it will be used to generate OMGraphics from the data - * array. If not, the OMGridObjects will be used to create OMGraphics for - * the map. - */ - public synchronized boolean generate(Projection proj) { - - double upLat; - int columns = getColumns(); - int rows = getRows(); - // Clear out the OMGraphicList part - super.clear(); - setShape(null); - - /** - * Let's figure out the dimensions and location of the grid, relative to - * the screen. - */ - if (renderType == RENDERTYPE_LATLON) { - /** - * Means that the latitudeResolution and horizontalResolution refer - * to degrees/datapoint. - */ - double rightLon; - - rightLon = longitude + columns * horizontalResolution; - upLat = latitude + rows * verticalResolution; - - point1 = (Point) proj.forward(upLat, longitude, new Point()); - point2 = (Point) proj.forward(latitude, rightLon, new Point()); - - /** For later... */ - height = point2.y - point1.y; - width = point2.x - point1.x; - - if (Debug.debugging("grid")) { - Debug.output("OMGrid.generate: height = " + height + ", width = " + width); - } - - } else if (renderType == RENDERTYPE_XY || renderType == RENDERTYPE_OFFSET) { - - width = (int) Math.round(columns * horizontalResolution); - height = (int) Math.round(rows * verticalResolution); - - if (renderType == RENDERTYPE_OFFSET) { - upLat = latitude + columns * verticalResolution; - point1 = (Point) proj.forward(upLat, longitude, new Point()); - point1.x += point.x; - point1.y += point.y; - } else { - point1 = point; - } - - point2 = new Point(point1.x + width, point1.y + height); - } else { - return false; - } - - if (Debug.debugging("grid")) { - Debug.output("OMGrid generated grid, at " + point1 + " and " + point2 + " with height " + height + " and width " - + width); - } - - // THis has to happen here, in case the generator wants to - // check the OMGrid coverage before deciding to do the work - // for creating OMGraphics. - setShape(); - - /** Now generate the grid in the desired way... */ - if (generator != null && generator.needGenerateToRender()) { - add(generator.generate(this, proj)); - } else if (gridObjects != null) { - add(generateGridObjects(proj)); - } - - setLabelLocation(getShape(), proj); - - setNeedToRegenerate(false); - - return true; - } - - /** - * Set a bounding rectangle as this OMGrid's shape, based on the location - * and size of the coverage of the grid. - */ - public void setShape() { - // If nothing is available as the shape, generate shape - // that is a boundary of the generated image. - // We'll make it a GeneralPath rectangle. - int w = width; - int h = height; - - setShape(createBoxShape(point1.x, point1.y, w, h)); - } - - /** - * Render the OMGraphics created to represent the grid data. - */ - public void render(Graphics g) { - if (generator != null) { - if ((needToRegenerate && generator.needGenerateToRender()) || !isVisible()) { - Debug.message("grid", "OMGrid: need to generate or is not visible!"); - return; - } - } - - super.render(g); - } - - /** - * Called from generate() if there isn't a OMGridGenerator. Goes through the - * grid, figuring out which data array indexes are on the map, and then - * calls generate on those grid objects. - */ - public OMGraphic generateGridObjects(Projection proj) { - - OMGraphicList graphiclist = new OMGraphicList(); - - /** - * There could be some way to optimize the search for objects in the - * grid that are actually visible, but that would require knowledge of - * the specifics of projections. Keeping this as generic as possible at - * this point. - */ - - // Since GridObjects only work with a int array, we need to - // check to see if the GridObject is of type GridData.Int and - // only bother returning if it is. - GridData gd = getData(); - if (gd instanceof GridData.Int) { - GridData.Int gdi = (GridData.Int) gd; - - Point pt = new Point(); - boolean major = gdi.getMajor(); - int[][] data = gdi.getData(); - - for (int x = 0; x < data.length; x++) { - for (int y = 0; y < data[0].length; y++) { - - // First, calculate if the grid post is even on - // the map - if (major == COLUMN_MAJOR) { - if (renderType == RENDERTYPE_LATLON) { - pt = (Point) proj.forward(latitude + y * verticalResolution, longitude + x * horizontalResolution, pt); - } else { - pt.y = point1.y + (int) (y * verticalResolution); - pt.x = point1.x + (int) (x * horizontalResolution); - } - } else { - if (renderType == RENDERTYPE_LATLON) { - pt = (Point) proj.forward(latitude + x * verticalResolution, longitude + y * horizontalResolution, pt); - } else { - pt.y = point1.y + (int) (x * verticalResolution); - pt.x = point1.x + (int) (y * horizontalResolution); - } - } - - if ((pt.x >= 0 || pt.x <= proj.getWidth()) && (pt.y >= 0 || pt.y <= proj.getHeight())) { - // It's on the map! Get a graphic from it! - graphiclist.add(gridObjects.generate(data[x][y], proj)); - } - } - } - } - return graphiclist; - } - - /** - * The value at the closest SW post to the given lat/lon. This is just a - * go-to-the-closest-post solution. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - * @param proj map projection, which is needed for XY or OFFSET grids. - * @return value found at the nearest grid point. This is an object returned - * from the GridObject data object, so what it is depends on that. - * You can test if it's a java.lang.Number object to get different - * values out of it if it is. - */ - public Object valueAt(double lat, double lon, Projection proj) { - - int lat_index = -1; - int lon_index = -1; - - if (renderType == RENDERTYPE_LATLON) { - - lat_index = (int) Math.round((lat - latitude) / verticalResolution); - lon_index = (int) Math.round((lon - longitude) / horizontalResolution); - - } else if (renderType == RENDERTYPE_XY || renderType == RENDERTYPE_OFFSET) { - if (getNeedToRegenerate()) { - /** Only care about this if we need to... */ - if (proj == null) { - return null; - } - generate(proj); - } - - Point pt = (Point) proj.forward(lat, lon, new Point()); - - lat_index = (int) Math.round((pt.y - point1.y) / verticalResolution); - lon_index = (int) Math.round((pt.x - point1.x) / horizontalResolution); - } - - GridData gd = getData(); - - if (gd != null && (lat_index >= 0 || lat_index < rows) && (lon_index >= 0 || lon_index < columns)) { - Object obj = null; - if (major == COLUMN_MAJOR) { - obj = gd.get(lon_index, lat_index); - } else { - obj = gd.get(lat_index, lon_index); - } - - return obj; - } - - return null; - } - - /** - * Interpolated value at a given lat/lon - should be more precise than - * valueAt(), but that depends on the resolution of the data. Works with - * GridData.Int data objects. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - * @param proj map projection, which is needed for XY or OFFSET grids. - * @return value at lat/lon - */ - public int interpValueAt(double lat, double lon, Projection proj) { - double lat_index = -1; - double lon_index = -1; - - GridData gridData = getData(); - - if (!(gridData instanceof GridData.Int)) { - Debug.error("OMGrid.interpValueAt only works for integer data."); - return 0; - } - - int[][] data = ((GridData.Int) gridData).getData(); - boolean major = gridData.getMajor(); - - if (renderType == RENDERTYPE_LATLON) { - - lat_index = (lat - latitude) / verticalResolution; - lon_index = (lon - longitude) / horizontalResolution; - - } else if (renderType == RENDERTYPE_XY || renderType == RENDERTYPE_OFFSET) { - if (getNeedToRegenerate()) { - /** Only care about this if we need to... */ - if (proj == null) { - return GRID_NULL; - } - generate(proj); - } - - Point pt = (Point) proj.forward(lat, lon, new Point()); - - lat_index = (pt.y - point1.y) / verticalResolution; - lon_index = (pt.x - point1.x) / horizontalResolution; - } - - if ((lat_index >= 0 || lat_index < rows) && (lon_index >= 0 || lon_index < columns)) { - - int lflon_index = (int) Math.floor(lon_index); - int lclon_index = (int) Math.ceil(lon_index); - int lflat_index = (int) Math.floor(lat_index); - int lclat_index = (int) Math.ceil(lat_index); - - // //////////////////////////////////////////////////// - // Print out grid of 20x20 elevations with - // the "asked for" point being in the middle - if (Debug.debugging("grid")) { - System.out.println("***Elevation Map***"); - for (int l = lclat_index + 5; l > lflat_index - 5; l--) { - System.out.println(); - for (int k = lflon_index - 5; k < lclon_index + 5; k++) { - if ((l >= 0 || l < rows) && (k >= 0 || k < columns)) { - if (major == COLUMN_MAJOR) { - System.out.print(data[k][l] + " "); - } else { - System.out.print(data[l][k] + " "); - } - } - } - } - System.out.println(); - System.out.println(); - } - // //////////////////////////////////////////////////// - - int ul, ur, ll, lr; - - if (major == COLUMN_MAJOR) { - ul = data[lflon_index][lclat_index]; - ur = data[lclon_index][lclat_index]; - ll = data[lflon_index][lclat_index]; - lr = data[lclon_index][lclat_index]; - } else { - ul = data[lclat_index][lflon_index]; - ur = data[lclat_index][lclon_index]; - ll = data[lclat_index][lflon_index]; - lr = data[lclat_index][lclon_index]; - } - - double answer = resolve_four_points(ul, ur, lr, ll, lat_index, lon_index); - return (int) Math.round(answer); - } - - return GRID_NULL; // Considered a null value - } - - /** - * A try at interpolating the corners of the surrounding posts, given a lat - * lon. Called from a function where the data for the lon has been read in. - */ - private double resolve_four_points(int ul, int ur, int lr, int ll, double lat_index, double lon_index) { - double top_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (float) (ur - ul)) + ul; - double bottom_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (float) (lr - ll)) + ll; - double right_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (float) (ur - lr)) + lr; - double left_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (float) (ul - ll)) / 100.0F + ll; - - double lon_avg = ((lat_index - new Double(Math.floor(lat_index)).floatValue()) * (top_avg - bottom_avg)) + bottom_avg; - double lat_avg = ((lon_index - new Double(Math.floor(lon_index)).floatValue()) * (right_avg - left_avg)) + left_avg; - - double result = (lon_avg + lat_avg) / 2.0; - return result; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMGrid) { - OMGrid grid = (OMGrid) source; - this.orientation = grid.orientation; - this.rows = grid.rows; - this.columns = grid.columns; - this.latitude = grid.latitude; - this.longitude = grid.longitude; - this.verticalResolution = grid.verticalResolution; - this.horizontalResolution = grid.horizontalResolution; - this.height = grid.height; - this.width = grid.width; - this.major = grid.major; - this.units = grid.units; - - if (grid.data != null) { - this.data = grid.data.deepCopy(); - } - if (grid.point != null) { - this.point = new Point(grid.point); - } - if (grid.point1 != null) { - this.point1 = new Point(grid.point1); - } - if (grid.point2 != null) { - this.point2 = new Point(grid.point2); - } - // Not sure how to handle this, since gridObjects are pretty vague. - if (grid.gridObjects != null) { - this.gridObjects = grid.gridObjects; - } - if (grid.generator != null) { - this.generator = grid.generator; - } - - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLabeler.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLabeler.java deleted file mode 100644 index 2dc566b5f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLabeler.java +++ /dev/null @@ -1,92 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: OMLabeler.java,v $ -//$Revision: 1.1 $ -//$Date: 2005/01/10 16:58:33 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Projection; - -/** - * An OMLabeler is used by OMGraphics to handle their labels. It can draw the - * text on the map, and tell how far away an x,y pixel location is away from - * where it's drawing itself on the map. - * - * @author dietrick - */ -public interface OMLabeler { - - /** - * The OMLabeler should render the text label onto the Graphics object. - * - * @param g - */ - void render(Graphics g); - - /** - * The OMLabler should return the pixel distance from any part of the label - * to the given x, y pixel distance. - * - * @param x pixel distance from left side of map window. - * @param y pixel distance from top of map window. - * @return distance in pixels from label text to given point. - */ - float distance(double x, double y); - - /** - * The OMLabeler should be able to determine its pixel location based on the - * GeneralPath of the OMGraphic. This will generally cause the label to be - * placed in the center of the bounds of the shape. - * - * @param gp - */ - void setLocation(GeneralPath gp); - - /** - * The OMLabeler should be able to determine its pixel location based on a - * set of x and y pixel coordinates common in OMGraphics. - * - * @param xpoints - * @param ypoints - */ - void setLocation(int[] xpoints, int[] ypoints); - - /** - * The OMLabeler should be able to set its pixel location directly. - * - * @param p - */ - void setLocation(Point2D p); - - /** - * Evaluate the current projection in case it has information that affects - * placement, like rotation. - * - * @param proj Projection - */ - void evaluateRotationAngle(Projection proj); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLine.java deleted file mode 100644 index eaa16df50..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMLine.java +++ /dev/null @@ -1,493 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMLine.java,v $ -// $RCSfile: OMLine.java,v $ -// $Revision: 1.15 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.omGraphics.util.ArcCalc; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * Graphic object that represents a simple line. - *

- * The OMLine is used to create simple lines, from one point on the window to - * the other. If you want to have a line with several parts, use OMPoly as a - * polyline with no fillColor. - *

NOTE:

See the - * RESTRICTIONS on - * Lat/Lon lines. Not following the guidelines listed may result in - * ambiguous/undefined shapes! Similar assumptions apply to the other vector - * graphics that we define: circles, ellipses, rects, polys. - *

- * - * @see OMPoly - */ -public class OMLine extends OMAbstractLine implements Serializable, NonRegional { - - /** - * Figured out after generation, based on what's going on with the map. - */ - protected transient boolean isPolyline = false; - - /** latlons is a array of 4 doubles - lat1, lon1, lat2, lon2. */ - protected double[] latlons = null; - - /** pts is an array of 4 ints - px1, py1, px2, py2. */ - protected int[] pts = null; - - /** - * For x-y and offset lines, there is the ability to put a curve in the - * line. This setting is the amount of an angle, limited to a semi-circle - * (PI) that the curve will represent. In other words, the arc between the - * two end points is going to look like a 0 degrees of a circle (straight - * line, which is the default), or 180 degrees of a circle (full - * semi-circle). Given in radians, though, not degrees. The ArcCalc object - * handles all the details. - */ - protected ArcCalc arc = null; - - public final static int STRAIGHT_LINE = 0; - public final static int CURVED_LINE = 1; - - /** Generic constructor, attributes need to filled later. */ - public OMLine() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Create a line from lat lon points. - * - * @param lat_1 latitude of first point, decimal degrees. - * @param lon_1 longitude of first point, decimal degrees. - * @param lat_2 latitude of second point, decimal degrees. - * @param lon_2 longitude of second point, decimal degrees. - * @param lineType a choice between LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE - * or LINETYPE_RHUMB. - */ - public OMLine(double lat_1, double lon_1, double lat_2, double lon_2, int lineType) { - this(lat_1, lon_1, lat_2, lon_2, lineType, -1); - } - - /** - * Create a line from lat lon points. - * - * @param lat_1 latitude of first point, decimal degrees. - * @param lon_1 longitude of first point, decimal degrees. - * @param lat_2 latitude of second point, decimal degrees. - * @param lon_2 longitude of second point, decimal degrees. - * @param lineType a choice between LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE - * or LINETYPE_RHUMB. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is - * generated internally) - */ - public OMLine(double lat_1, double lon_1, double lat_2, double lon_2, int lineType, int nsegs) { - super(RENDERTYPE_LATLON, lineType, DECLUTTERTYPE_NONE); - latlons = new double[4]; - latlons[0] = lat_1; - latlons[2] = lat_2; - latlons[1] = lon_1; - latlons[3] = lon_2; - this.nsegs = nsegs; - } - - /** - * Create a line between two xy points on the window. - * - * @param x1 the x location of the first point, in pixels from the left of - * the window. - * @param y1 the y location of the first point, in pixels from the top of - * the window. - * @param x2 the x location of the second point, in pixels from the left of - * the window. - * @param y2 the y location of the second point, in pixels from the top of - * the window. - */ - public OMLine(int x1, int y1, int x2, int y2) { - super(RENDERTYPE_XY, LINETYPE_STRAIGHT, DECLUTTERTYPE_NONE); - pts = new int[4]; - pts[0] = x1; - pts[1] = y1; - pts[2] = x2; - pts[3] = y2; - } - - /** - * Create a line between two x-y points on the window, where the x-y points - * are offsets from a lat-lon point. It assumes that you'll want a straight - * window line between the points, so if you don't, use the setLineType() - * method to change it. - * - * @param lat_1 the latitude of the reference point of the line, in decimal - * degrees. - * @param lon_1 the longitude of the reference point of the line, in decimal - * degrees. - * @param x1 the x location of the first point, in pixels from the longitude - * point. - * @param y1 the y location of the first point, in pixels from the latitude - * point. - * @param x2 the x location of the second point, in pixels from the - * longitude point. - * @param y2 the y location of the second point, in pixels from the latitude - * point. - */ - public OMLine(double lat_1, double lon_1, int x1, int y1, int x2, int y2) { - - super(RENDERTYPE_OFFSET, LINETYPE_STRAIGHT, DECLUTTERTYPE_NONE); - latlons = new double[4]; - pts = new int[4]; - latlons[0] = lat_1; - latlons[1] = lon_1; - pts[0] = x1; - pts[1] = y1; - pts[2] = x2; - pts[3] = y2; - } - - /** - * Set the lat lon values of the end points of the line from an array of - * doubles - lat1, lon1, lat2, lon2. This does not look at the line render - * type, so it acts accordingly. LL1 is only used in RENDERTYPE_LATLON, - * RENDERTYPE_OFFSET, and LL2 is only used in RENDERTYPE_LATLON. - * - * @param lls array of doubles - lat1, lon1, lat2, lon2 - */ - public void setLL(double[] lls) { - latlons = lls; - setNeedToRegenerate(true); - } - - /** - * Get the lat lon values of the end points of the line in an array of - * doubles - lat1, lon1, lat2, lon2. Again, this does not look at the line - * render type, so it acts accordingly. LL1 is only used in - * RENDERTYPE_LATLON, RENDERTYPE_OFFSET, and LL2 is only used in - * RENDERTYPE_LATLON. - * - * @return the lat lon array, and all are decimal degrees. - */ - public double[] getLL() { - return latlons; - } - - /** - * Set the xy values of the end points of the line from an array of ints - - * x1, y1, x2, y2 . This does not look at the line render type, so it acts - * accordingly. p1 and p2 are only used in RENDERTYPE_XY, RENDERTYPE_OFFSET. - * - * @param xys array of ints for the points - x1, y1, x2, y2 - */ - public void setPts(int[] xys) { - pts = xys; - setNeedToRegenerate(true); - } - - /** - * Get the xy values of the end points of the line in an array of ints - x1, - * y1, x2, y2 . This does not look at the line render type, so it acts - * accordingly. p1 and p2 are only used in RENDERTYPE_XY, RENDERTYPE_OFFSET. - * - * @return the array of x-y points, and all are pixel values - */ - public int[] getPts() { - return pts; - } - - /** - * Check to see if this line is a polyline. This is a polyline if it is - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB for RENDERTYPE_LATLON polys. - * - * @return true if polyline false if not - */ - public boolean isPolyline() { - return isPolyline; - } - - /** - * Set the number of segments of the lat/lon line. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, and if < 1, this - * value is generated internally). - * - * @param nsegs number of segment points - */ - public void setNumSegs(int nsegs) { - this.nsegs = nsegs; - } - - /** - * Get the number of segments of the lat/lon line. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types). - * - * @return int number of segment points - */ - public int getNumSegs() { - return nsegs; - } - - /** - * Set the arc that is drawn between the points of a x-y or offset line. - */ - public void setArc(ArcCalc ac) { - arc = ac; - } - - /** - * Return the arc angle set for this line. Will only be set if it was set - * externally. - * - * @return arc angle in radians. - */ - public ArcCalc getArc() { - return arc; - } - - /** - * Prepare the line for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMLine: null projection in generate!"); - return false; - } - - // reset the internals - isPolyline = false; - initLabelingDuringGenerate(); - GeneralPath projectedShape = null; - - switch (renderType) { - case RENDERTYPE_XY: - - if (pts == null) { - return false; - } - - if (arc != null) { - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(pts[0], pts[1], pts[2], pts[3]); - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - } else { - xpoints = new float[1][2]; - ypoints = new float[1][2]; - - xpoints[0][0] = pts[0]; - ypoints[0][0] = pts[1]; - xpoints[0][1] = pts[2]; - ypoints[0][1] = pts[3]; - } - projectedShape = createShape(xpoints[0], ypoints[0], false); - break; - case RENDERTYPE_OFFSET: - if (pts == null || latlons == null || !proj.isPlotable(latlons[0], latlons[1])) { - setNeedToRegenerate(true); - return false; - } - - Point p1 = (Point) proj.forward(latlons[0], latlons[1], new Point()); - if (arc != null) { - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(p1.x + pts[0], p1.y + pts[1], p1.x + pts[2], p1.y + pts[3]); - - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - } else { - xpoints = new float[1][2]; - ypoints = new float[1][2]; - - xpoints[0][0] = p1.x + pts[0]; - ypoints[0][0] = p1.y + pts[1]; - xpoints[0][1] = p1.x + pts[2]; - ypoints[0][1] = p1.y + pts[3]; - } - projectedShape = createShape(xpoints[0], ypoints[0], false); - break; - case RENDERTYPE_LATLON: - if (latlons == null) { - setNeedToRegenerate(true); - return false; - } - - if (arc != null) { - p1 = (Point) proj.forward(latlons[0], latlons[1], new Point()); - Point p2 = (Point) proj.forward(latlons[2], latlons[3], new Point()); - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(p1.x, p1.y, p2.x, p2.y); - - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - - projectedShape = createShape(xpoints[0], ypoints[0], false); - - isPolyline = true; - - } else { - ArrayList lines = null; - if (proj instanceof GeoProj) { - lines = ((GeoProj) proj).forwardLine(new LatLonPoint.Double(latlons[0], latlons[1]), - new LatLonPoint.Double(latlons[2], latlons[3]), lineType, nsegs); - } else { - lines = proj.forwardLine(new Point2D.Double(latlons[1], latlons[0]), - new Point2D.Double(latlons[3], latlons[2])); - } - - int size = lines.size(); - - xpoints = new float[(int) (size / 2)][0]; - ypoints = new float[xpoints.length][0]; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - float[] xps = (float[]) lines.get(i); - float[] yps = (float[]) lines.get(i + 1); - - xpoints[j] = xps; - ypoints[j] = yps; - - GeneralPath gp = createShape(xps, yps, false); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - isPolyline = (lineType != LINETYPE_STRAIGHT); - } - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMLine.generate: invalid RenderType"); - setNeedToRegenerate(true); - return false; - } - - // label location is set in setShape - setShape(projectedShape); - setLabelLocation(projectedShape, proj); - - if (arrowhead != null) { - arrowhead.generate(this); - } - - if (arc != null) { - // This will only do something if debugging is on. - arc.generate(proj); - } - - setNeedToRegenerate(false); - return true; - } - - /** - * Paint the line. - * - * @param g Graphics context to render into - */ - public void render(Graphics g) { - - if (!isRenderable(getShape())) { - return; - } - - // Just to draw the matting for the arrowhead. The matting - // for the rest of the line will be taken care of in - // super.render(). - if (arrowhead != null && isMatted() && g instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) g).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - setGraphicsColor(g, Color.black); - arrowhead.render(g); - } - - super.render(g); - - if (arrowhead != null) { - setGraphicsForEdge(g); - arrowhead.render(g); - } - - if (arc != null) { - // This is a debugging thing, most times does nothing. - arc.render(g); - } - - } - - /** - * The OMLine should never render fill. It can think it does, if the - * geometry turns out to be curved. Returning false affects distance() and - * contains() methods. - */ - public boolean shouldRenderFill() { - return false; - } - - /** - * This takes the area out of OMLines that may look like they have area, - * depending on their shape. Checks to see what shouldRenderFill() returns - * (false by default) to decide how to measure this. If shouldRenderFill == - * true, the super.contains() method is returned, which assumes the line - * shape has area if it is curved. Otherwise, it returns true if the point - * is on the line. - */ - public boolean contains(double x, double y) { - if (shouldRenderFill()) { - return super.contains(x, y); - } else { - return (distance(x, y) == 0); - } - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMLine) { - OMLine line = (OMLine) source; - - this.latlons = DeepCopyUtil.deepCopy(line.latlons); - this.pts = DeepCopyUtil.deepCopy(line.pts); - if (line.arc != null) { - this.arc = new ArcCalc(line.arc.getArcAngle(), line.arc.isArcUp()); - } else { - this.arc = null; - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMList.java deleted file mode 100644 index a7ed5c545..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMList.java +++ /dev/null @@ -1,1457 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMGraphicList.java,v $ -// $RCSfile: OMGraphicList.java,v $ -// $Revision: 1.22 $ -// $Date: 2009/02/20 17:15:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -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 com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; - -/** - * This class encapsulates a List of OMGraphics. - *

- * There are several things that this list does that make it better that any ol' - * List. You can make several common OMGraphic modification calls on the list, - * and the list handles the iteration and changing of all the graphics while - * taking into account a traverse order. - *

- * An additional benefit is that because the OMGraphicList extends OMGraphic it - * can contain other instances of OMGraphicList. This way you can manage - * groupings of graphics, (for instance, an OMGraphicList of OMGraphicLists - * which each have an OMRaster and OMText). - *

- * Many methods, such as generate() and findClosest() traverse the items in the - * GraphicsList recursively. The direction that the list is traversed is - * controlled by then traverseMode variable. The traverseMode mode lets you set - * whether the first or last object added to the list (FIRST_ADDED_ON_TOP or - * LAST_ADDED_ON_TOP) is drawn on top of the list and considered first for - * searches. - */ -public abstract class OMList extends OMGraphicAdapter implements List, - OMGraphic { - - /** - * Used to set the order in which the list is traversed to draw or search - * the objects. This means that the last things on the list will be on top - * of the map because they are drawn last, on top of everything else. For - * searches, objects added last to the list will be considered first for a - * search match. - */ - public final transient static int LAST_ADDED_ON_TOP = 0; - - /** - * Used to set the order in which the list is traversed to draw or search - * the objects. This means that the first things on the list will appear on - * top because they are drawn last, on top of everything else. For searches, - * objects added first to the list will be considered first for a search - * match. This is the default mode for the list. - */ - public final transient static int FIRST_ADDED_ON_TOP = 1; - - /** - * Used for searches, when OMDist doesn't have a graphic. The index of a - * null graphic is NONE. If you try to remove or insert a graphic at NONE, - * an exception will be thrown. If you try to get a graphic at NONE, you'll - * get null; - */ - public final static int NONE = -1; - - /** - * List traversal mode. The default is FIRST_ADDED_ON_TOP. - */ - protected int traverseMode = FIRST_ADDED_ON_TOP; - - /** - * Flag to adjust behavior of OMGraphicList for certain queries. If - * OMGraphicList should act as OMGraphic, the entire list will be treated as - * one object. Otherwise, the list will act as a pass-through container, and - * internal OMGraphics will be returned. This applies to distance(), - * selectClosest(), findClosest(), getOMGraphicThatContains(), etc. This - * flag becomes really helpful for embedded OMGraphicLists, not so much for - * top-level OMGraphicLists. - */ - protected boolean vague = false; - - /** - * Flag used to allow duplicates in the OMGraphicList. True by default - - * this prevents the list from doing the extra work for checking for - * duplicates at addition time. - */ - protected boolean allowDuplicates = true; - - /** - * The List that actually contains the the OMGeometry/OMGraphic objects. - */ - protected List graphics; - - /** - * Construct an OMGraphicList. - */ - public OMList() { - graphics = Collections.synchronizedList(new ArrayList()); - } - - public OMList(int initialCapacity) { - graphics = Collections.synchronizedList(new ArrayList(initialCapacity)); - } - - /** - * OMGraphicList method for returning a simple description of the list. This - * is really a debugging method. - */ - public String getDescription() { - return getDescription(0); - } - - /** - * OMGraphic method, for returning a simple description if the contents of - * the list. This method handles the spacing of sub-member descriptions. - * This is really a debugging method. - * - * @return String that represents the structure of the OMGraphicList. - */ - public String getDescription(int level) { - StringBuffer sb = new StringBuffer(); - - if (level > 0) { - sb.append("|--> "); - } - - sb.append("OMList with ").append(size()).append(" object").append((size() == 1 ? "\n" - : "s\n")); - - synchronized (graphics) { - StringBuffer sb1 = new StringBuffer(); - - for (int i = 0; i < level; i++) { - sb1.append(" "); - } - String spacer = sb1.toString(); - - String levelHeader = level == 0 ? "" : "|--> "; - - for (OMGeometry omg : graphics) { - String description = ""; - if (omg instanceof OMList) { - description = ((OMList) omg).getDescription(level + 1); - } else { - description = levelHeader + omg.getDescription(); - } - - sb.append(spacer).append(description).append("\n"); - } - } - return sb.toString(); - } - - /** - * Set whether the list returns the specific OMGraphic in response to a - * query, or itself. - */ - public void setVague(boolean value) { - vague = value; - } - - /** - * Get whether the list returns the specific OMGraphic in response to a - * query, or itself. - */ - public boolean isVague() { - return vague; - } - - public Iterator iterator() { - return getCopy().iterator(); - } - - public ListIterator listIterator() { - return getCopy().listIterator(); - } - - public ListIterator listIterator(int size) { - return getCopy().listIterator(size); - } - - public List subList(int fromIndex, int toIndex) { - return graphics.subList(fromIndex, toIndex); - } - - public int size() { - return graphics.size(); - } - - public boolean isEmpty() { - return graphics.isEmpty(); - } - - public void clear() { - graphics.clear(); - } - - public int indexOf(Object o) { - return graphics.indexOf(o); - } - - public int lastIndexOf(Object o) { - return graphics.lastIndexOf(o); - } - - public boolean removeAll(Collection c) { - boolean ret = false; - for (Object o : c) { - if (remove(o)) { - ret = true; - } - } - return ret; - } - - public boolean retainAll(Collection c) { - boolean ret = false; - for (Object o : c) { - if (!contains(o)) { - remove(o); - ret = true; - } - } - return ret; - } - - public boolean contains(Object o) { - boolean ret = false; - if (o != null) { - synchronized (graphics) { - for (T omg : graphics) { - - if (o == omg - || (omg instanceof OMList && ((OMList) omg).contains(o))) { - - ret = true; - break; - } - } - } - } - - return ret; - } - - public boolean containsAll(Collection c) { - for (Object o : c) { - if (!contains(o)) { - return false; - } - } - return true; - } - - /** - * Add an OMGraphic to the list. - */ - public boolean add(T g) { - checkForDuplicate(g); - return graphics.add(g); - } - - public void add(int index, T g) { - checkForDuplicate(g); - graphics.add(index, g); - } - - public Object[] toArray() { - return graphics.toArray(); - } - - public E[] toArray(E[] a) { - return graphics.toArray(a); - } - - /** - * Set the order in which the list is traversed to draw or search the - * objects. The possible modes for the list are FIRST_ADDED_ON_TOP or - * LAST_ADDED_ON_TOP. - * - * @param mode traversal mode - */ - public void setTraverseMode(int mode) { - traverseMode = mode; - } - - /** - * Get the order in which the list is traversed to draw or search the - * objects. The possible modes for the list are FIRST_ADDED_ON_TOP or - * LAST_ADDED_ON_TOP. - * - * @return int traversal mode - */ - public int getTraverseMode() { - return traverseMode; - } - - /** - * Remove the graphic. If this list is not vague, it will also ask - * sub-OMGraphicLists to remove it if the geometry isn't found on this - * OMGraphicList. - * - * @param geometry the object to remove. - * @return true if geometry was on the list, false if otherwise. - */ - public boolean remove(Object geometry) { - boolean found = false; - - synchronized (graphics) { - found = graphics.remove(geometry); - - if (!found && !isVague()) { - for (OMGeometry graphic : graphics) { - if (graphic instanceof OMList) { - found = ((OMList) graphic).remove(geometry); - } - } - } - } - - return found; - } - - public T remove(int index) { - return graphics.remove(index); - } - - /** - * @return an unmodifiable copy of this list. - */ - public final List getCopy() { - final List listCopy; - listCopy = new ArrayList(graphics); - return Collections.unmodifiableList(listCopy); - } - - /** - * Moves the graphic at the given index to the part of the list where it - * will be drawn on top of one of the other graphics which is its neighbor - * on the list. This method does check to see what the traverseMode of the - * list is, and calls either moveIndexedToLast or moveIndexedToFirst, - * depending on what is appropriate. - * - * @param location the index location of the graphic to move. - * @see #moveIndexedOneToFront(int) - * @see #moveIndexedOneToBack(int) - */ - public void moveIndexedOneToTop(int location) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - moveIndexedOneToFront(location); - } else { - moveIndexedOneToBack(location); - } - } - - /** - * Moves the graphic at the given index to the part of the list where it - * will be drawn on top of the other graphics. This method does check to see - * what the traverseMode of the list is, and calls either moveIndexedToLast - * or moveIndexedToFirst, depending on what is appropriate. - * - * @param location the index location of the graphic to move. - */ - public void moveIndexedToTop(int location) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - moveIndexedToFirst(location); - } else { - moveIndexedToLast(location); - } - } - - /** - * Moves the graphic at the given index to the part of the list where it - * will be drawn under one of the other graphics, its neighbor on the list. - * This method does check to see what the traverseMode of the list is, and - * calls either moveIndexedOneToBack or moveIndexedOneToFront, depending on - * what is appropriate. - * - * @param location the index location of the graphic to move. - * @see #moveIndexedOneToFront(int) - * @see #moveIndexedOneToBack(int) - */ - public void moveIndexedOneToBottom(int location) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - moveIndexedOneToBack(location); - } else { - moveIndexedOneToFront(location); - } - } - - /** - * Moves the graphic at the given index to the part of the list where it - * will be drawn under all of the other graphics. This method does check to - * see what the traverseMode of the list is, and calls either - * moveIndexedToLast or moveIndexedToFirst, depending on what is - * appropriate. - * - * @param location the index location of the graphic to move. - */ - public void moveIndexedToBottom(int location) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - moveIndexedToLast(location); - } else { - moveIndexedToFirst(location); - } - } - - /** - * Moves the graphic at the given index to the front of the list, sliding - * the other graphics back on in the list in order. If the location is - * already at the beginning or beyond the end, nothing happens. - * - * @param location the index of the graphic to move. - * @see #moveIndexedToBottom(int) - * @see #moveIndexedToTop(int) - */ - public void moveIndexedToFirst(int location) { - int listSize = size(); - if (location > 0 && location < listSize) { - T tmpGraphic = get(location); - for (int i = location; i > 0; i--) { - set(i, get(i - 1)); - } - graphics.set(0, tmpGraphic); - } - } - - /** - * Moves the graphic at the given index toward the front of the list by one - * spot, sliding the other graphic back on in the list in order. If the - * location is already at the beginning or beyond the end, nothing happens. - * - * @param location the index of the graphic to move. - */ - public void moveIndexedOneToFront(int location) { - int listSize = size(); - if (location > 0 && location < listSize) { - T tmpGraphic = get(location); - graphics.set(location, get(location - 1)); - graphics.set(location - 1, tmpGraphic); - } - } - - /** - * Moves the graphic at the given index to the end of the list, sliding the - * other graphics up on in the list in order. If the location is already at - * the end or less than zero, nothing happens. - * - * @param location the index of the graphic to move. - * @see #moveIndexedToBottom(int) - * @see #moveIndexedToTop(int) - */ - public void moveIndexedToLast(int location) { - int listSize = size(); - if (location < listSize - 1 && location >= 0) { - T tmpGraphic = get(location); - for (int i = location; i < listSize - 1; i++) { - set(i, get(i + 1)); - } - graphics.set(listSize - 1, tmpGraphic); - } - } - - /** - * Moves the graphic at the given index toward the back of the list by one - * spot, sliding the other graphic up on in the list in order. If the - * location is already at the end or less than zero, nothing happens. - * - * @param location the index of the graphic to move. - */ - public void moveIndexedOneToBack(int location) { - int listSize = size(); - if (location < listSize - 1 && location >= 0) { - T tmpGraphic = get(location); - graphics.set(location, get(location + 1)); - graphics.set(location + 1, tmpGraphic); - } - } - - /** - * Projects any graphics needing projection. Use this method to project any - * new or changed OMGraphics before painting. to re-project the whole list, - * use generate(Projection, boolean) with - * forceProjectAll set to true. This is the same - * as calling generate(p, false) - * - * @param p a Projection - * @see #generate(Projection, boolean) - */ - public void project(Projection p) { - generate(p, false); - } - - /** - * Projects the OMGraphics on the list. This is the same as calling - * generate(p, forceProjectAll). - * - * @param p a Projection - * @param forceProjectAll if true, all the graphics on the list are - * generated with the new projection. If false they are only - * generated if getNeedToRegenerate() returns true - * @see #generate(Projection, boolean) - */ - public void project(Projection p, boolean forceProjectAll) { - generate(p, forceProjectAll); - } - - /** - * Prepare the graphics for rendering. This is the same as calling - * project(p, true). - * - * @param p a Projection - * @return boolean true - * @see #generate(Projection, boolean) - */ - public boolean generate(Projection p) { - return generate(p, true); - } - - /** - * Prepare the graphics for rendering. This must be done before calling - * render()! This recursively calls generate() on the - * OMGraphics on the list. - * - * @param p a Projection - * @param forceProjectAll if true, all the graphics on the list are - * generated with the new projection. If false they are only - * generated if getNeedToRegenerate() returns true - * @return true if generation was successful for all objects on list. - * @see OMGraphic#generate - * @see OMGraphic#regenerate - */ - public boolean generate(Projection p, boolean forceProjectAll) { - boolean ret = true; - synchronized (graphics) { - Iterator iterator = iterator(); - // Check forceProjectAll outside the loop for slight - // performance improvement. - if (forceProjectAll) { - while (iterator.hasNext()) { - ret &= iterator.next().generate(p); - } - } else { - while (iterator.hasNext()) { - ret &= iterator.next().regenerate(p); - } - } - } - return ret; - } - - /** - * Renders all the objects in the list a graphics context. This is the same - * as paint() for AWT components. The graphics are rendered in - * the order of traverseMode. Any graphics where isVisible() - * returns false are not rendered. - * - * @param gr the AWT Graphics context - */ - public void render(Graphics gr) { - - if (isVague() && !isVisible()) - return; - - synchronized (graphics) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - OMGeometry graphic = iterator.previous(); - if (shouldProcess(graphic)) { - graphic.render(gr); - } - } - - } else { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - OMGeometry graphic = iterator.next(); - if (shouldProcess(graphic)) { - graphic.render(gr); - } - } - } - } - - renderLabel(gr); - } - - /** - * Renders all the objects in the list a graphics context, in their - * 'selected' mode. This is the same as paint() for AWT - * components. The graphics are rendered in the order of traverseMode. Any - * graphics where isVisible() returns false are not rendered. - * All of the graphics on the list are returned to their deselected state. - * - * @param gr the AWT Graphics context - */ - public void renderAllAsSelected(Graphics gr) { - - synchronized (graphics) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - OMGeometry graphic = iterator.previous(); - if (shouldProcess(graphic)) { - graphic.select(); - graphic.render(gr); - graphic.deselect(); - } - } - - } else { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - OMGeometry graphic = iterator.next(); - if (shouldProcess(graphic)) { - graphic.select(); - graphic.render(gr); - graphic.deselect(); - } - } - } - } - } - - /** - * Override flag for shouldProcess method. The setting will override the - * OMGraphicList from using the OMGraphic's visibility settings in - * determining which OMGraphics should be used in different distance, - * generate and render methods. - */ - protected boolean processAllGeometries = true; - - /** - * This method is called internally for those methods where skipping - * invisible OMGeometries would save processing time and effort. If you - * don't want visibility to be considered when processing - * OMGeometries/OMGraphics, override this method and return true. - */ - protected boolean shouldProcess(OMGeometry graphic) { - return processAllGeometries || graphic.isVisible(); - } - - /** - * Set the programmatic override for shouldProcess method to always process - * geometries. - */ - public void setProcessAllGeometries(boolean set) { - processAllGeometries = set; - } - - /** - * Get the settings for the programmatic override for shouldProcess method - * to always process geometries. - */ - public boolean getProcessAllGeometries() { - return processAllGeometries; - } - - /** - * Finds the distance to the closest OMGraphic. - * - * @param x x coordinate - * @param y y coordinate - * @return float distance - * @see #findClosest(double, double, float) - */ - public float distance(double x, double y) { - return findClosest(x, y, Float.MAX_VALUE, false).d; - } - - /** - * RetVal for closest object/distance calculations. - */ - protected static class OMDist { - public T omg = null; - public float d = Float.POSITIVE_INFINITY; - public int index = NONE; // unknown - - public String toString() { - return "OMDist: omg=" + (omg == null ? "null" : omg.getClass().getName()) + ", d=" + d - + ", index=" + index; - } - } - - protected abstract OMDist createDist(); - - /** - * Find the closest Object and its distance. The search is always conducted - * from the topmost graphic to the bottom-most, depending on the - * traverseMode. - * - * @param x x coordinate - * @param y y coordinate - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @param resetSelect deselect any OMGraphic touched. - * @return OMDist - */ - public OMDist findClosest(double x, double y, float limit, boolean resetSelect) { - OMDist omd = new OMDist(); - OMDist tomd; - int i; - - synchronized (graphics) { - if (!isEmpty()) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - i = 0; - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - tomd = findClosestTest(omd, i++, iterator.next(), x, y, limit, resetSelect); - if (tomd == null) - continue; - omd = tomd; // for style - if (omd.d == 0) - break; - } - } else { - i = size(); - ListIterator iterator = graphics.listIterator(i); - while (iterator.hasPrevious()) { - tomd = findClosestTest(omd, i--, iterator.previous(), x, y, limit, resetSelect); - if (tomd == null) - continue; - omd = tomd; // for style - if (omd.d == 0) - break; - } - } - } - - } - if (Debug.debugging("omgraphics")) { - int size = size(); - if (omd.omg != null && isVague()) { - omd.omg = (T) this; - Debug.output(this.getClass().getName() + "(" + size - + ") detecting hit and vagueness, returning " + omd); - } else if (omd.omg != null && !isVague()) { - Debug.output(this.getClass().getName() + "(" + size - + ") detecting hit, no vagueness, returning contained " + omd); - } else { - Debug.output(this.getClass().getName() + "(" + size + ") omd.omg " - + (omd.omg == null ? "== null" : "!= null")); - } - } - - return omd; - } - - /** - * Test the graphic distance away from the x, y point, and compare it to the - * current OMDist passed in. If the graphic is the new closest, return the - * same OMDist object filled in with the new value. Otherwise, return null. - * - * @param current the OMDist that contains the current best result of a - * search. - * @param index the index in the graphic list of the provided OMGraphic - * @param graphic the OMGraphic to test - * @param x the window horizontal pixel value. - * @param y the window vertical pixel value. - * @param resetSelect flag to call deselect on any OMGraphic contacted. Used - * here to pass on in case the OMGraphic provided is an - * OMGraphicList, and to use to decide if deselect should be called - * on the provided graphic. - * @return OMDist with an OMGraphic if the graphic passed in is the current - * closest. OMDist.graphic could be null, OMDist.d could be - * Infinity. - */ - protected OMDist findClosestTest(OMDist current, int index, OMGeometry graphic, double x, - double y, float limit, boolean resetSelect) { - - if (current == null) { - current = createDist(); - } - - OMList omgl; - float currentDistance = Float.MAX_VALUE; - - // cannot select a graphic which isn't visible - if (!shouldProcess(graphic)) { - return current; - } - - if (graphic instanceof OMList) { - omgl = (OMList) graphic; - OMDist dist = (OMDist) omgl.findClosest(x, y, limit, resetSelect); - if (dist.omg != null) { - currentDistance = dist.d; - graphic = dist.omg; - } - } else { - if (resetSelect) - graphic.deselect(); - currentDistance = graphic.distance(x, y); - } - - if (currentDistance < limit && currentDistance < current.d) { - if (!isVague()) { - current.omg = (T) graphic; - } else { - current.omg = (T) this; - } - current.index = index; - current.d = currentDistance; - } - - return current; - } - - /** - * Finds the object located the closest to the point, if the object distance - * away is within the limit. The search is always conducted from the topmost - * graphic to the bottom-most, depending on the traverseMode. Any graphics - * where isVisible() returns false are not considered. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @return OMGraphic the closest on the list within the limit, or null if - * not found. - */ - public T findClosest(double x, double y, float limit) { - return findClosest(x, y, limit, false).omg; - } - - /** - * Find all of the OMGraphics on this list that are located within the pixel - * limit of the x, y pixel location. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @return OMGraphicList containing all of the OMGraphics within the limit. - */ - public OMList findAll(int x, int y, float limit) { - return findAll(x, y, limit, false, null); - } - - /** - * Find all of the OMGraphics on this list that are located within the pixel - * limit of the x, y pixel location. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @param resetSelect call deselect on OMGraphics not within limit. - * @param addTo OMGraphicList to add found OMGraphics to, if null a list - * will be created. - * @return OMGraphicList containing all of the OMGraphics within the limit, - * empty if none are found. - */ - public OMList findAll(int x, int y, float limit, boolean resetSelect, - OMList addTo) { - if (addTo == null) { - addTo = create(); - } - - OMDist omd = createDist(); - if (!isEmpty()) { - synchronized (graphics) { - - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - if (!findAllTest(x, y, limit, resetSelect, addTo, iterator.next(), omd)) { - break; - } - } - } else { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - if (!findAllTest(x, y, limit, resetSelect, addTo, iterator.previous(), omd)) { - break; - } - - } - } - } - } - - if (Debug.debugging("omgraphics")) { - Debug.output(this.getClass().getName() + "(" + size() - + ") detecting hits and vagueness, returning list with " + addTo.size() - + " graphics."); - } - - return addTo; - } - - public abstract OMList create(); - - /** - * Test to find out if an OMGraphic is located within the pixel limit of the - * x, y pixel location. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @param resetSelect call deselect on OMGraphic not within limit. - * @param addTo OMGraphicList to add found OMGeometries to, if null a list - * will be created. - * @param geometry OMGraphic to test. - * @param omd OMDist to use for test, provided to avoid recurring memory - * allocations for loops. - * @return true of this method should still be called again in a loop, false - * of this list is vague and we have a hit. - */ - protected boolean findAllTest(int x, int y, float limit, boolean resetSelect, OMList addTo, - OMGeometry geometry, OMDist omd) { - - if (geometry instanceof OMList) { - OMList tempList = create(); - ((OMList) geometry).findAll(x, y, limit, resetSelect, tempList); - - if (!tempList.isEmpty()) { - if (isVague()) { - addTo.add((T) this); - // Vague with hit, no need to check further on this list... - return false; - } else { - addTo.addAll(tempList); - // Move on to check next T on this list... - return true; - } - } - - } else { - - omd = findClosestTest(omd, 0 /* doesn't matter */, geometry, x, y, limit, resetSelect); - - if (omd == null || omd.omg == null) { - // no hit, but continue testing... - return true; - } - - // Measurements passed, add OMGraphic to addTo list and - // continue - if (isVague()) { - addTo.add((T) this); - return false; - } - - addTo.add(omd.omg); - omd.d = Float.MAX_VALUE; // reset for next OMGraphic - omd.omg = null; - } - return true; - } - - /** - * Finds the object located the closest to the point, regardless of how far - * away it is. This method returns null if the list is not valid. The search - * starts at the first-added graphic.
- * This is the same as calling - * findClosest(x, y, Float.MAX_VALUE). - * - * @param x the horizontal pixel position of the window, from the left of - * the window. - * @param y the vertical pixel position of the window, from the top of the - * window. - * @return the closest graphic to the xy window point. - * @see #findClosest(double, double, float) - */ - public T findClosest(int x, int y) { - return findClosest(x, y, Float.MAX_VALUE); - } - - /** - * Finds the object located the closest to the point, if the object distance - * away is within the limit. The search is always conducted from the topmost - * graphic to the bottom-most, depending on the traverseMode. Any graphics - * where isVisible() returns false are not considered. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @return index of the closest on the list within the limit, or - * OMGraphicList.NONE if not found. - */ - public int findIndexOfClosest(int x, int y, float limit) { - return findClosest(x, y, limit, false).index; - } - - /** - * Finds the object located the closest to the point, regardless of how far - * away it is. This method returns null if the list is not valid. The search - * starts at the first-added graphic.
- * This is the same as calling - * findClosest(x, y, Float.MAX_VALUE). - * - * @param x the horizontal pixel position of the window, from the left of - * the window. - * @param y the vertical pixel position of the window, from the top of the - * window. - * @return index of the closest graphic to the xy window point, or - * OMGraphicList.NONE if not found. - * @see #findIndexOfClosest(int, int, float) - */ - public int findIndexOfClosest(int x, int y) { - return findClosest(x, y, Float.MAX_VALUE, false).index; - } - - /** - * Finds the object located the closest to the coordinates, regardless of - * how far away it is. Sets the select paint of that object, and resets the - * paint of all the other objects. The search starts at the first-added - * graphic. - * - * @param x the x coordinate on the component the graphics are displayed on. - * @param y the y coordinate on the component the graphics are displayed on. - * @return the closest OMGraphic on the list, with selected having been - * called on that OMGraphics. This OMGraphic will be within the - * limit or null if none found. Will return this list if this list - * is set to be vague. - */ - public T selectClosest(int x, int y) { - return selectClosest(x, y, Float.MAX_VALUE); - } - - /** - * Finds the object located the closest to the point, if the object distance - * away is within the limit, and sets the paint of that graphic to its - * select paint. It sets the paints to all the other objects to the regular - * paint. The search starts at the first-added graphic. Any graphics where - * isVisible() returns false are not considered. - * - * @param x the horizontal pixel position of the window, from the left of - * the window. - * @param y the vertical pixel position of the window, from the top of the - * window. - * @param limit the max distance that a graphic has to be within to be - * returned, in pixels. - * @return the closest OMGraphic on the list, with selected having been - * called on that OMGraphics. This OMGraphic will be within the - * limit or null if none found. Will return this list if this list - * is set to be vague. - */ - public T selectClosest(int x, int y, float limit) { - OMDist omd = null; - OMDist tomd; - T ret = null; - - // Handle vagueness. - if (isVague()) { - omd = findClosest(x, y, limit, true); - if (omd != null) { - select(); - return (T) this; - } - } - - synchronized (graphics) { - if (!isEmpty()) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - tomd = selectClosestTest(omd, 0, iterator.next(), x, y, limit); - if (tomd == null) - continue; - omd = tomd; // for style - if (omd.d == 0) - break; - } - } else { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - tomd = selectClosestTest(omd, 0, iterator.previous(), x, y, limit); - if (tomd == null) - continue; - omd = tomd; // for style - if (omd.d == 0) - break; - } - } - } - } - - if (omd != null) { - ret = omd.omg; - } - - return ret; - } - - /** - * A variation on findClosestTest, manages select() and deselect(). - * - * @param current the OMDist that contains the current best result of a - * search. - * @param index the index in the graphic list of the provided OMGraphic - * @param graphic the OMGraphic to test - * @param x the window horizontal pixel value. - * @param y the window vertical pixel value. - * @return OMDist if the graphic passed in is the current closest. OMGraphic - * will be set in OMDist and selected(). OMGraphic will be - * de-selected if not the closest, and the OMDist will be null. This - * method will return this list if it is set to be vague and one of - * its children meet the criteria. - */ - protected OMDist selectClosestTest(OMDist current, int index, OMGeometry graphic, int x, - int y, float limit) { - if (current == null) { - current = createDist(); - } - - T oldGraphic = current.omg; - OMDist ret = findClosestTest(current, index, graphic, x, y, limit, true); - - // Test for the OMDist still holding the same OMGraphicList, - // which will be the case if this list is vague. The distance - // will be updated, though. - if (ret != null && oldGraphic != ret.omg) { - if (oldGraphic != null) { - oldGraphic.deselect(); - } - ret.omg.select(); - } - - return ret; - } - - /** - * Finds the first OMGraphic (the one on top) that is under this pixel. If - * an OMGraphic is an OMGraphicList, its contents will be checked. If that - * check is successful and OMGraphicList is not vague, its OMGraphic will be - * returned - otherwise the list will be returned. - * - * @param x the horizontal pixel position of the window, from the left of - * the window. - * @param y the vertical pixel position of the window, from the top of the - * window. - * @return the graphic that contains the pixel, NONE (null) if none are - * found. - */ - public T getContains(int x, int y) { - - T ret = null; - - synchronized (graphics) { - - if (!isEmpty()) { - if (traverseMode == FIRST_ADDED_ON_TOP) { - ListIterator iterator = graphics.listIterator(); - while (iterator.hasNext()) { - OMGeometry graphic = iterator.next(); - - // cannot select a graphic which isn't visible - if (!shouldProcess(graphic)) - continue; - - if (graphic instanceof OMList) { - OMList tomgl = (OMList) graphic; - ret = (T) tomgl.getContains(x, y); - if (ret != null) { - if (tomgl.isVague()) { - ret = (T) graphic; - } - break; - } - } else if (graphic.contains(x, y)) { - ret = (T) graphic; - break; - } - } - } else { - ListIterator iterator = graphics.listIterator(size()); - while (iterator.hasPrevious()) { - OMGeometry graphic = iterator.previous(); - - // cannot select a graphic which isn't visible - if (!shouldProcess(graphic)) - continue; - - if (graphic instanceof OMList) { - OMList tomgl = (OMList) graphic; - ret = (T) tomgl.getContains(x, y); - if (ret != null) { - if (tomgl.isVague()) { - ret = (T) graphic; - } - break; - } - } else if (graphic.contains(x, y)) { - ret = (T) graphic; - break; - } - } - } - } - } - if (ret != null && this.isVague()) { - ret = (T) this; - } - - return ret; - } - - /** - * If you call deselect() on an OMGraphicList, it calls deselect() all the - * graphics it contains, as well as the deselect method on it's super class. - */ - public void deselect() { - super.deselect(); - synchronized (graphics) { - for (OMGeometry omg : graphics) { - omg.deselect(); - } - } - } - - /** - * Calls select() on all the items on the graphic list, as well as select() - * on the super class. - */ - public void select() { - super.select(); - synchronized (graphics) { - for (OMGeometry omg : graphics) { - omg.select(); - } - } - } - - /** - * Perform an action on the provided geometry. If the geometry is not - * currently on the list, it is added (if the action doesn't say to delete - * it). If the geometry is null, the list checks for an action to take on - * the list (deselectAll). - */ - public void doAction(T graphic, OMAction action) { - - Debug.message("omgl", "OMList.doAction()"); - - if (graphic == null) { - return; - } - - int i = indexOf(graphic); - - boolean alreadyOnList = (i != -1); - - if (action == null || action.getValue() == 0 && !alreadyOnList) { - Debug.message("omgl", "OMGraphicList.doAction: adding graphic with null action"); - add(graphic); - return; - } - - if (action.isMask(ADD_GRAPHIC_MASK) || action.isMask(UPDATE_GRAPHIC_MASK) && !alreadyOnList) { - Debug.message("omgl", "OMGraphicList.doAction: adding graphic"); - add(graphic); - } - - if (action.isMask(DELETE_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: removing graphic"); - remove(graphic); - } - - if (action.isMask(RAISE_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: raising graphic"); - moveIndexedOneToTop(i); - } - - if (action.isMask(RAISE_TO_TOP_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: raising graphic to top"); - moveIndexedToTop(i); - } - - if (action.isMask(LOWER_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: lowering graphic"); - moveIndexedOneToBottom(i); - } - - if (action.isMask(LOWER_TO_BOTTOM_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: lowering graphic to bottom"); - moveIndexedOneToBottom(i); - } - - if (action.isMask(DESELECTALL_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: deselecting all graphics."); - deselect(); - } - - if (action.isMask(SORT_GRAPHICS_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: sorting the list"); - sort(); - } - - if (action.isMask(SELECT_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: selecting graphic"); - graphic.select(); - } - - if (action.isMask(DESELECT_GRAPHIC_MASK)) { - Debug.message("omgl", "OMGraphicList.doAction: deselecting graphic"); - graphic.deselect(); - } - } - - /** - * Set the visibility variable. NOTE:
- * This is checked by the OMGraphicList when it iterates through its list - * for render and gesturing. It is not checked by the internal OMGraphic - * methods, although maybe it should be... - * - * @param visible boolean - */ - public void setVisible(boolean visible) { - super.setVisible(visible); - if (!isVague()) { - synchronized (graphics) { - for (Iterator it = iterator(); it.hasNext();) { - it.next().setVisible(visible); - } - } - } - } - - /** - * Get the visibility variable. For the OMGraphicList, if any part of it is - * visible, then it is considered visible. - * - * @return boolean - */ - public boolean isVisible() { - if (!isVague()) { - synchronized (graphics) { - for (T omg : graphics) { - if (omg.isVisible()) { - return true; - } - } - } - return false; - } else { - return super.isVisible(); - } - } - - /** - * Set whether the list will allow duplicate entries added. If not, then the - * copy will be added, and the previous version removed. - */ - public void setAllowDuplicates(boolean set) { - allowDuplicates = set; - } - - /** - * Get whether the list will allow duplicate entries added. If not, then the - * copy will be added, and the previous version removed. - */ - public boolean getAllowDuplicates() { - return allowDuplicates; - } - - /** - * Convenience function for methods that may add a OMGraphic. Method checks - * to see if duplicates are allowed, and if they are not, it will remove the - * OMGraphic from the list. The calling method can be confident that it will - * be adding a unique OMGraphic. Internal methods that call this method - * should be synchronized on the graphics list. - */ - protected void checkForDuplicate(T g) { - if (!allowDuplicates) { - // Why check first, just remove it if it's found?! - // if (graphics.contains(g)) { - remove(g); - // } - } - } - - /** - * Checks if an OMGraphic is on this list. Checks sublists, too. - */ - public boolean contains(OMGraphic g) { - if (g != null) { - synchronized (graphics) { - for (OMGeometry omg : graphics) { - if (g == omg - || (omg instanceof OMList && ((OMList) omg).contains(g))) { - - return true; - } - } - } - } - - return false; - } - - /** - * This sort method is a place-holder for OMGraphicList extensions to - * implement their own particular criteria for sorting an OMGraphicList. - * Does nothing for a generic OMGraphicList. - */ - public void sort() { - } - - /** - * Convenience method to cast an object to an OMGraphic if it is one. - * Returns null if it isn't. - */ - protected OMGraphic objectToOMGraphic(Object obj) { - if (obj instanceof OMGraphic) { - return (OMGraphic) obj; - } else { - return null; - } - } - - /** - * You need to make sure that the Generic type of the source matches the - * generic type of this list. Will fail silently. Not sure if this is the - * right way to handle it, though. - */ - public void restore(OMGeometry source) { - super.restore(source); - try { - if (source instanceof OMList) { - OMList list = (OMList) source; - for (T omg : list) { - T newCopy = (T) ComponentFactory.create(omg.getClass().getName()); - if (newCopy != null) { - newCopy.restore(source); - } - } - } - } catch (ClassCastException cce) { - // Should really check better. Duh. - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoint.java deleted file mode 100644 index a72bb9a80..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoint.java +++ /dev/null @@ -1,470 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMPoint.java,v $ -// $RCSfile: OMPoint.java,v $ -// $Revision: 1.13 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.Point; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.io.Serializable; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * A OMPoint is used to mark a specific point. You can set this point as a - * lat/lon position, a screen X/Y position, or a lat/lon position with a screen - * X/Y offset. The position can be marked with a rectangle or circle with an - * adjusted radius. The radius is the pixel distance from the center of the - * location to each edge of the marking rectangle or circle. - */ -public class OMPoint - extends OMGraphicAdapter - implements OMGraphic, Serializable { - - public final static int DEFAULT_RADIUS = 2; - public final static boolean DEFAULT_ISOVAL = false; - /** - * The number of pixels in the radius for the point representation. - */ - protected int radius = DEFAULT_RADIUS; - /** - * Horizontal window position of point, in pixels from left side of window. - */ - protected int x = 0; - /** - * Vertical window position of point, in pixels from the top of the window. - */ - protected int y = 0; - /** Latitude of point, decimal degrees. */ - protected double lat1 = 0.0f; - /** Longitude of point, decimal degrees. */ - protected double lon1 = 0.0f; - - /** Set to true if you want little circles marking the point. */ - protected boolean oval = DEFAULT_ISOVAL; - - /** Default constructor, waiting to be filled. */ - public OMPoint() { - super(); - } - - /** - * Create an OMPoint at a lat/lon position, with the default radius. - */ - public OMPoint(double lat, double lon) { - this(lat, lon, DEFAULT_RADIUS); - } - - /** - * Create an OMPoint at a lat/lon position, with the specified radius. - */ - public OMPoint(double lat, double lon, int radius) { - setRenderType(RENDERTYPE_LATLON); - set(lat, lon); - this.radius = radius; - } - - /** - * Create an OMPoint at a lat/lon position with a screen X/Y pixel offset, - * with the default radius. - */ - public OMPoint(double lat, double lon, int offsetx, int offsety) { - this(lat, lon, offsetx, offsety, DEFAULT_RADIUS); - } - - /** - * Create an OMPoint at a lat/lon position with a screen X/Y pixel offset, - * with the specified radius. - */ - public OMPoint(double lat, double lon, int offsetx, int offsety, int radius) { - setRenderType(RENDERTYPE_OFFSET); - set(lat, lon, offsetx, offsety); - this.radius = radius; - } - - /** - * Put the point at a screen location, marked with a rectangle with edge - * size DEFAULT_RADIUS * 2 + 1. - */ - public OMPoint(int x, int y) { - this(x, y, DEFAULT_RADIUS); - } - - /** - * Put the point at a screen location, marked with a rectangle with edge - * size radius * 2 + 1. - */ - public OMPoint(int x, int y, int radius) { - setRenderType(RENDERTYPE_XY); - set(x, y); - this.radius = radius; - } - - /** For lat/lon rendertype points, to move the point location. */ - public void set(double lat, double lon) { - setLat(lat); - setLon(lon); - } - - /** For offset rendertype points, to move the point location. */ - public void set(double lat, double lon, int offsetx, int offsety) { - setLat(lat); - setLon(lon); - set(offsetx, offsety); - } - - /** - * For screen x/y rendertype points, to move the point location. This method - * does not call setX() and setY(). - */ - public void set(int x, int y) { - // You have to set these directly, or you can mess up the grab - // points by using set methods - VerticalGrabPoints and - // HorizontalGrabPoints disable some methods. This method is - // used to override them, for initialization purposes. - this.x = x; - this.y = y; - setNeedToRegenerate(true); - } - - /** Set the latitude of the point, in decimal degrees. */ - public void setLat(double lat) { - this.lat1 = lat; - setNeedToRegenerate(true); - } - - /** Get the latitude of the point, in decimal degrees. */ - public double getLat() { - return lat1; - } - - /** Set the longitude of the point, in decimal degrees. */ - public void setLon(double lon) { - this.lon1 = lon; - setNeedToRegenerate(true); - } - - /** Get the longitude of the point, in decimal degrees. */ - public double getLon() { - return lon1; - } - - /** For screen x/y rendertype points. */ - public void setX(int x) { - this.x = x; - setNeedToRegenerate(true); - } - - /** For screen x/y rendertype points. */ - public int getX() { - return x; - } - - /** For screen x/y rendertype points. */ - public void setY(int y) { - this.y = y; - setNeedToRegenerate(true); - } - - /** For screen x/y rendertype points. */ - public int getY() { - return y; - } - - /** - * Set the radius of the marking rectangle. The edge size of the marking - * rectangle will be radius * 2 + 1. - */ - public void setRadius(int radius) { - this.radius = radius; - setNeedToRegenerate(true); - } - - /** - * Get the radius for the point. - */ - public int getRadius() { - return radius; - } - - /** - * Set whether little circles should be marking the point. - * - * @param set true for circles. - */ - public void setOval(boolean set) { - if (oval != set) { - setNeedToRegenerate(true); - oval = set; - } - } - - /** - * Get whether little circles should be marking the point. - */ - public boolean isOval() { - return oval; - } - - /** - * Prepare the point for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMPoint: null projection in generate!"); - return false; - } - - // reset the internals - int x1 = 0; - int x2 = 0; - int y1 = 0; - int y2 = 0; - - switch (renderType) { - case RENDERTYPE_XY: - x1 = x - radius; - y1 = y - radius; - x2 = x + radius; - y2 = y + radius; - - break; - case RENDERTYPE_OFFSET: - case RENDERTYPE_LATLON: - if (!proj.isPlotable(lat1, lon1)) { - setNeedToRegenerate(true);// HMMM not the best flag - return false; - } - Point p1 = (Point) proj.forward(lat1, lon1, new Point()); - - x1 = p1.x + x - radius; - y1 = p1.y + y - radius; - x2 = p1.x + x + radius; - y2 = p1.y + y + radius; - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMPoint.generate(): invalid RenderType"); - return false; - } - - if (oval) { - setShape(new GeneralPath(new Ellipse2D.Float((float) Math.min(x2, x1), (float) Math.min(y2, y1), (float) Math.abs(x2 - - x1), (float) Math.abs(y2 - y1)))); - } else { - setShape(createBoxShape((int) Math.min(x2, x1), (int) Math.min(y2, y1), (int) Math.abs(x2 - x1), - (int) Math.abs(y2 - y1))); - } - - initLabelingDuringGenerate(); - setLabelLocation(new Point(x2, y1), proj); - - setNeedToRegenerate(false); - return true; - } - - public boolean hasLineTypeChoice() { - return false; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMPoint) { - OMPoint point = (OMPoint) source; - this.radius = point.radius; - this.x = point.x; - this.y = point.y; - this.lat1 = point.lat1; - this.lon1 = point.lon1; - this.oval = point.oval; - } - } - - public static class Image - extends OMPoint { - protected java.awt.Image image; - protected boolean useImage = true; - protected int imageX = 0; - protected int imageY = 0; - - /** - * Create an OMPoint at a lat/lon position, with the default radius. - */ - public Image(double lat, double lon) { - super(lat, lon); - } - - /** - * Create an OMPoint at a lat/lon position, with the specified radius. - */ - public Image(double lat, double lon, int radius) { - super(lat, lon, radius); - } - - /** - * Create an OMPoint at a lat/lon position with a screen X/Y pixel - * offset, with the default radius. - */ - public Image(double lat, double lon, int offsetx, int offsety) { - this(lat, lon, offsetx, offsety, DEFAULT_RADIUS); - } - - /** - * Create an OMPoint at a lat/lon position with a screen X/Y pixel - * offset, with the specified radius. - */ - public Image(double lat, double lon, int offsetx, int offsety, int radius) { - super(lat, lon, offsetx, offsety, radius); - } - - /** - * Put the point at a screen location, marked with a rectangle with edge - * size DEFAULT_RADIUS * 2 + 1. - */ - public Image(int x, int y) { - this(x, y, DEFAULT_RADIUS); - } - - /** - * Put the point at a screen location, marked with a rectangle with edge - * size radius * 2 + 1. - */ - public Image(int x, int y, int radius) { - super(x, y, radius); - } - - public java.awt.Image getImage() { - return image; - } - - public void setImage(java.awt.Image image) { - this.image = image; - } - - public boolean isUseImage() { - return useImage; - } - - public void setUseImage(boolean useImage) { - setNeedToRegenerate(this.useImage != useImage); - this.useImage = useImage; - } - - /** - * Prepare the point image for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - if (!isUseImage() || image == null) { - return super.generate(proj); - } - - if (proj == null) { - Debug.message("omgraphic", "OMPoint: null projection in generate!"); - setNeedToRegenerate(true); - return false; - } - - // reset the internals - int imageHeight = image.getHeight(null); - int imageWidth = image.getWidth(null); - int imageOffsetX = imageWidth / 2; - int imageOffsetY = imageHeight / 2; - switch (renderType) { - case RENDERTYPE_XY: - imageX = x - imageOffsetX; - imageY = y - imageOffsetY; - - break; - case RENDERTYPE_OFFSET: - case RENDERTYPE_LATLON: - if (!proj.isPlotable(lat1, lon1)) { - setNeedToRegenerate(true);// HMMM not the best flag - return false; - } - Point2D p1 = proj.forward(lat1, lon1); - - imageX = (int) p1.getX() + x - imageOffsetX; - imageY = (int) p1.getY() + y - imageOffsetY; - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMPoint.Image.generate(): invalid RenderType"); - return false; - } - - setShape(createBoxShape(imageX, imageY, imageWidth, imageHeight)); - - initLabelingDuringGenerate(); - setLabelLocation(new Point(imageX + imageWidth, imageY + imageOffsetY), proj); - - setNeedToRegenerate(false); - return true; - } - - /** - * Render the image when useImage is true, or calls super implementation - * otherwise - * - * @see com.bbn.openmap.omGraphics.OMGraphic#render(java.awt.Graphics) - */ - public void render(Graphics g) { - if (!isRenderable(getShape())) - return; - - if (isUseImage()) { - g.drawImage(image, imageX, imageY, null); - renderLabel(g); - } else - super.render(g); - } - - /** - * Overriding this method will get mouse events to work over any part of - * the image. - */ - public boolean shouldRenderFill() { - return isUseImage() || super.shouldRenderFill(); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMPoint.Image) { - OMPoint.Image pntImage = (OMPoint.Image) source; - this.image = pntImage.image; - this.useImage = pntImage.useImage; - this.imageX = pntImage.imageX; - this.imageY = pntImage.imageY; - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoly.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoly.java deleted file mode 100644 index 1ba6f5deb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMPoly.java +++ /dev/null @@ -1,1277 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMPoly.java,v $ -// $RCSfile: OMPoly.java,v $ -// $Revision: 1.20 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.DeepCopyUtil; -import com.bbn.openmap.util.MoreMath; - -/** - * Graphic object that represents a polygon or polyline - * (multi-line-segment-object). - *

- * - * The differentiators between polygons and polylines is the fill color. If the - * fillPaint is equal to OMColor.clear, then the poly will be considered a - * polyline. There are methods to override this in the OMPoly class, but they do - * play around with the fillPaint, depending on the order in which the methods - * are called. If you know it's a polyline, call setIsPolygon(false) if you - * think that the fillPaint could be set to anything other than the default, - * OMColor.clear. - *

- * - * All of the OMGraphics are moving to having their internal representation as - * java.awt.Shape objects. Unfortunately, this has the side effect of slowing - * OMPolys down, because the way that the projection classes handle - * transformations cause more objects to be allocated and more loops to be run - * through. So, by default, the OMPoly does NOT use Shape objects internally, to - * keep layers that throw down many, many polys running quickly. If you want to - * do some spatial analysis on an OMPoly, call setDoShapes(true) on it, then - * generate(Projection), and then call getShapes() to get the java.awt.Shape - * objects for the poly. You can then run the different Shape spatial analysis - * methods on the Shape objects. - * - *

NOTES:

- *
    - *
  • See the - * RESTRICTIONS on Lat/Lon polygons/polylines. Not following the guidelines - * listed may result in ambiguous/undefined shapes! Similar assumptions apply to - * the other vector graphics that we define: circles, ellipses, rects, lines. - *
  • LatLon OMPolys store latlon coordinates internally in radian format for - * efficiency in projecting. Subclasses should follow this model. - *
  • Holes in the poly are not supported. - *

    - *

- *

TODO:

- *
    - *
  • Polar filled-polygon correction for Cylindrical projections (like - * OMCircle). - *
- * - * @see OMCircle - * @see OMRect - * @see OMLine - */ -public class OMPoly extends OMAbstractLine implements Serializable { - - /** - * Translation offsets. For RENDERTYPE_OFFSET, the xy points are relative to - * the position of fixed latlon point. - */ - public final static int COORDMODE_ORIGIN = 0; - - /** - * Delta offsets. For RENDERTYPE_OFFSET, each xy point in the array is - * relative to the previous point, and the first point is relative to the - * fixed latlon point. - */ - public final static int COORDMODE_PREVIOUS = 1; - - /** - * Radians or decimal degrees. After construction and conversion, this - * should always be radians. - */ - protected int units = -1;// this should be set correctly at - // construction - - /** - * For RENDERTYPE_OFFSET, the latitude of the starting point of the poly. - * Stored as radians! - */ - protected double lat = 0.0f; - - /** - * For RENDERTYPE_OFFSET, the longitude of the starting point of the poly. - * Stored as radians! - */ - protected double lon = 0.0f; - - /** - * For RENDERTYPE_OFFSET, type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - protected int coordMode = COORDMODE_ORIGIN; - - /** - * The x array of ints, representing pixels, used for x/y or offset polys. - */ - protected int[] xs = null; - - /** - * The y array of ints, representing pixels, used for x/y or offset polys. - */ - protected int[] ys = null; - - /** - * Poly is a polygon or a polyline. This is true if the fillColor is not - * clear, false if it is. - */ - protected boolean isPolygon = false; - - /** raw float lats and lons stored internally in radians. */ - protected double[] rawllpts = null; - - /** - * Flag for telling the OMPoly to use the Shape objects to represent itself - * internally. See intro for more info. - */ - protected boolean doShapes = false; - - /** - * Construct a default OMPoly. - */ - public OMPoly() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Create an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public OMPoly(double[] llPoints, int units, int lType) { - this(llPoints, units, lType, -1); - } - - /** - * Create an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is generated - * internally) - */ - public OMPoly(double[] llPoints, int units, int lType, int nsegs) { - super(RENDERTYPE_LATLON, lType, DECLUTTERTYPE_NONE); - setLocation(llPoints, units); - this.nsegs = nsegs; - } - - /** - * Create an OMPoly from a list of xy pairs. If you want the poly to be - * connected, you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param xypoints array of x/y points, arranged x, y, x, y, etc. - */ - public OMPoly(int[] xypoints) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setLocation(xypoints); - } - - /** - * Create an x/y OMPoly. If you want the poly to be connected, you need to - * ensure that the first and last coordinate pairs are the same. - * - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public OMPoly(int[] xPoints, int[] yPoints) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - setLocation(xPoints, yPoints); - } - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want the poly to - * be connected, you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xypoints float[] of x,y pairs - * @param cMode offset coordinate mode - */ - public OMPoly(double latPoint, double lonPoint, int[] xypoints, int cMode) { - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - setLocation(latPoint, lonPoint, OMGraphic.DECIMAL_DEGREES, xypoints); - coordMode = cMode; - } - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want the poly to - * be connected, you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - * @param cMode offset coordinate mode - */ - public OMPoly(double latPoint, double lonPoint, int[] xPoints, int[] yPoints, int cMode) { - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - setLocation(latPoint, lonPoint, OMGraphic.DECIMAL_DEGREES, xPoints, yPoints); - coordMode = cMode; - } - - /** - * Set an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! If you don't want the - * array to be changed, send in a copy. - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * This is for RENDERTYPE_LATLON polys. - * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - */ - public void setLocation(double[] llPoints, int units) { - this.units = OMGraphic.RADIANS; - if (units == OMGraphic.DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(llPoints); - } - rawllpts = llPoints; - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_LATLON); - } - - /** - * Set an OMPoly from a list of xy pixel pairs. If you want the poly to be - * connected, you need to ensure that the first and last coordinate pairs - * are the same. This is for RENDERTYPE_XY polys. - * - * @param xypoints array of x/y points, arranged x, y, x, y, etc. - */ - public void setLocation(int[] xypoints) { - int end = xypoints.length >> 1; - xs = new int[end]; - ys = new int[end]; - for (int i = 0, j = 0; i < end; i++, j += 2) { - xs[i] = xypoints[j]; - ys[i] = xypoints[j + 1]; - } - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_XY); - } - - /** - * Set an OMPoly from a x/y coordinates. If you want the poly to be - * connected, you need to ensure that the first and last coordinate pairs - * are the same. This is for RENDERTYPE_XY polys. - * - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public void setLocation(int[] xPoints, int[] yPoints) { - xs = xPoints; - ys = yPoints; - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_XY); - } - - /** - * Set the location based on a latitude, longitude, and some xy points. The - * coordinate mode and the polygon setting are the same as in the - * constructor used. This is for RENDERTYPE_OFFSET polys. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param xypoints array of x/y points, arranged x, y, x, y, etc. - */ - public void setLocation(double latPoint, double lonPoint, int units, int[] xypoints) { - this.units = OMGraphic.RADIANS; - if (units == OMGraphic.DECIMAL_DEGREES) { - lat = ProjMath.degToRad(latPoint); - lon = ProjMath.degToRad(lonPoint); - } else { - lat = latPoint; - lon = lonPoint; - } - int end = xypoints.length >> 1; - xs = new int[end]; - ys = new int[end]; - for (int i = 0, j = 0; i < end; i++, j += 2) { - xs[i] = xypoints[j]; - ys[i] = xypoints[j + 1]; - } - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_OFFSET); - } - - /** - * Set the location based on a latitude, longitude, and some xy points. The - * coordinate mode and the polygon setting are the same as in the - * constructor used. This is for RENDERTYPE_OFFSET polys. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public void setLocation(double latPoint, double lonPoint, int units, int[] xPoints, - int[] yPoints) { - this.units = OMGraphic.RADIANS; - if (units == OMGraphic.DECIMAL_DEGREES) { - lat = ProjMath.degToRad(latPoint); - lon = ProjMath.degToRad(lonPoint); - } else { - lat = latPoint; - lon = lonPoint; - } - xs = xPoints; - ys = yPoints; - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_OFFSET); - } - - /** - * Return the rawllpts array. NOTE: this is an unsafe method to access the - * rawllpts array. Use with caution. These are RADIANS! For - * RENDERTYPE_LATLON polys. - * - * @return double[] rawllpts of lat, lon, lat, lon - */ - public double[] getLatLonArray() { - // If the OMPoly has been generated with a non GeoProj projection, these - // coordinates are going to be in decimal degrees, to make that that - // generation easier. They should be translated back into radians, for - // consistency. - if (units == DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(rawllpts); - units = RADIANS; - } - return rawllpts; - } - - /** - * Use this if you want to play around with the values without messing with - * the OMPoly. This is safe to mess with, allocates new double[], in - * radians. If you want decimal degrees, use ProjMath.arrayRadToDeg with the - * returned array. For RENDERTYPE_LATLON polys - * - * @return copy of lat/lons, in lat/lon/lat/lon order. RADIANS! - */ - public double[] getLatLonArrayCopy() { - return DeepCopyUtil.deepCopy(getLatLonArray()); - } - - /** - * Set the latitude of the offset point, in decimal degrees. For - * RENDERTYPE_OFFSET Polygons. - */ - public void setLat(double lat) { - this.lat = ProjMath.degToRad(lat); - setNeedToRegenerate(true); - } - - /** - * Get the latitude of the offset point, in decimal degrees. For - * RENDERTYPE_OFFSET Polygons. - */ - public double getLat() { - return ProjMath.radToDeg(lat); - } - - /** - * Set the longitude of the offset point, in decimal degrees. For - * RENDERTYPE_OFFSET Polygons. - */ - public void setLon(double lon) { - this.lon = ProjMath.degToRad(lon); - setNeedToRegenerate(true); - } - - /** - * Get the longitude of the offset point, in decimal degrees. For - * RENDERTYPE_OFFSET Polygons. - */ - public double getLon() { - return ProjMath.radToDeg(lon); - } - - /** - * Set the array of x points. For RENDERTYPE_OFFSET, RENDERTYPE_XY polys. - */ - public void setXs(int[] x) { - xs = x; - setNeedToRegenerate(true); - } - - /** - * Get the array of x points. For RENDERTYPE_OFFSET, RENDERTYPE_XY polys. - */ - public int[] getXs() { - return xs; - } - - /** - * Set the array of y points. For RENDERTYPE_OFFSET, RENDERTYPE_XY polys. - */ - public void setYs(int[] y) { - ys = y; - setNeedToRegenerate(true); - } - - /** - * Get the array of y points. For RENDERTYPE_OFFSET, RENDERTYPE_XY polys. - */ - public int[] getYs() { - return ys; - } - - /** - * Set the fill Paint of the poly. If the color value is non-clear, then the - * poly is a polygon (connected and filled), otherwise it's a polyline - * (non-filled). - * - * @param paint value Color - */ - public void setFillPaint(Paint paint) { - super.setFillPaint(paint); - isPolygon = !isClear(paint); - } - - /** - * Check if this is a polygon or a polyline. A polygon is a multi-segment - * line that has a non-clear fill color. A polyline is a multi-segment line - * that has no fill color. - * - * @return true if polygon false if polyline - */ - public boolean isPolygon() { - return isPolygon; - } - - /** - * Set the Polyline/Polygon setting, if you know better. If the fillPaint is - * set after this method is called, then the fillPaint isPolygon rules - * apply. If the fillPaint is opaque, then it is assumed to be a Polygon and - * isPolygon will be set to true. If this is set to be false, the fillPaint - * will be set to clear. - */ - public void setIsPolygon(boolean set) { - if (!set) { - // This is important for the rendering, especially if the - // shapes are being created and OMGraphic.render() will be - // used. The fillPaint being == OMColor.clear will - // prevent the filled area from being drawn. - fillPaint = OMColor.clear; - } - isPolygon = set; - } - - /** - * Set the number of subsegments for each segment in the poly. (This is only - * for LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, and if < 1, - * this value is generated internally). - * - * @param nsegs number of segment points - */ - public void setNumSegs(int nsegs) { - this.nsegs = nsegs; - } - - /** - * Get the number of subsegments for each segment in the poly. (This is only - * for LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types). - * - * @return int number of segment points - */ - public int getNumSegs() { - return nsegs; - } - - /** - * For RENDERTYPE_OFFSET, type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - public void setCoordMode(int coordMode) { - this.coordMode = coordMode; - } - - /** - * For RENDERTYPE_OFFSET, type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - public int getCoordMode() { - return coordMode; - } - - public void setDoShapes(boolean set) { - doShapes = set; - } - - public boolean getDoShapes() { - return doShapes; - } - - /** - * Prepare the poly for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMPoly: null projection in generate!"); - return false; - } - - // answer the question now, saving calculation for future - // calculations. The set method forces the calculation for - // the query. - - isGeometryClosed(); - - switch (renderType) { - - case RENDERTYPE_XY: - if (xs == null) { - Debug.message("omgraphic", "OMPoly x/y rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - // Need to convert the int[] to float[] and assign them to - // xpoints/ypoints. - float[] xfs = new float[xs.length]; - float[] yfs = new float[ys.length]; - for (int i = 0; i < xs.length; i++) { - xfs[i] = xs[i]; - yfs[i] = ys[i]; - } - - // Need to keep these around for the LabeledOMPoly - xpoints = new float[1][0]; - ypoints = new float[1][0]; - xpoints[0] = xfs; - ypoints[0] = yfs; - - break; - - case RENDERTYPE_OFFSET: - if (xs == null) { - Debug.message("omgraphic", "OMPoly offset rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - int npts = xs.length; - float[] _x = new float[npts]; - float[] _y = new float[npts]; - - // forward project the radian point - Point origin = new Point(); - if (proj instanceof GeoProj) { - ((GeoProj) proj).forward(lat, lon, origin, true);// radians - } else { - proj.forward(Math.toDegrees(lat), Math.toDegrees(lon), origin); - } - - if (coordMode == COORDMODE_ORIGIN) { - for (int i = 0; i < npts; i++) { - _x[i] = xs[i] + origin.x; - _y[i] = ys[i] + origin.y; - } - } else { // CModePrevious offset deltas - _x[0] = xs[0] + origin.x; - _y[0] = ys[0] + origin.y; - - for (int i = 1; i < npts; i++) { - _x[i] = xs[i] + _x[i - 1]; - _y[i] = ys[i] + _y[i - 1]; - } - } - // Need to keep these around for the LabeledOMPoly - xpoints = new float[1][0]; - xpoints[0] = _x; - ypoints = new float[1][0]; - ypoints[0] = _y; - - break; - - case RENDERTYPE_LATLON: - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians. - ArrayList vector; - if (proj instanceof GeoProj) { - if (units == DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(rawllpts); - units = RADIANS; - } - vector = ((GeoProj) proj).forwardPoly(rawllpts, lineType, nsegs, isPolygon()); - } else { - if (units == RADIANS) { - ProjMath.arrayRadToDeg(rawllpts); - units = DECIMAL_DEGREES; - } - vector = proj.forwardPoly(rawllpts, isPolygon()); - } - - int size = vector.size(); - - float[][] loc_xpoints = new float[(int) (size / 2)][0]; - float[][] loc_ypoints = new float[loc_xpoints.length][0]; - xpoints = loc_xpoints; - ypoints = loc_ypoints; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - loc_xpoints[j] = vector.get(i); - loc_ypoints[j] = vector.get(i + 1); - } - - if (!doShapes) { - if (size > 1) { - if (arrowhead != null) { - arrowhead.generate(this); - } - setNeedToRegenerate(false); - initLabelingDuringGenerate(); - if (checkPoints(loc_xpoints, loc_ypoints)) { - setLabelLocation(loc_xpoints[0], loc_ypoints[0], proj); - } - return true; - } else { - return false; - } - } - - break; - - case RENDERTYPE_UNKNOWN: - Debug.error("OMPoly.generate: invalid RenderType"); - setNeedToRegenerate(true); - return false; - } - - if (arrowhead != null) { - arrowhead.generate(this); - } - - setNeedToRegenerate(false); - setShape(createShape()); - setLabelLocation(getShape(), proj); - return true; - } - - /** - * Return true if the xpoints and ypoints are not null and contain - * coordinates. - * - * @param xpoints2 - * @param ypoints2 - */ - protected boolean checkPoints(float[][] xpoints2, float[][] ypoints2) { - if (xpoints == null || ypoints == null || xpoints.length == 0 || ypoints.length == 0) { - return false; - } - return true; - } - - /** - * Return true of the fill color/paint should be rendered (not clear). - */ - public boolean shouldRenderFill() { - return !isClear(getFillPaint()) && isPolygon(); - } - - /** - * Paint the poly. This works if generate() has been successful. - * - * @param g java.awt.Graphics to paint the poly onto. - */ - public void render(Graphics g) { - - if (getShape() != null) { - super.render(g); - - if (arrowhead != null) { - arrowhead.render(g); - } - - return; - } - - if (getNeedToRegenerate() || !isVisible()) - return; - - // safety: grab local reference of projected points - float[][] xpts = xpoints; - float[][] ypts = ypoints; - - if (xpts == null || ypts == null) { - // Shouldn't get here, but crazy EditableOMPoly events - // sometimes cause this to happen. Catch and wait to - // paint later. - setNeedToRegenerate(true); - return; - } - - float[] _x, _y; - int i; - int len = xpts.length; - - Paint displayPaint = getDisplayPaint(); - Paint fillPaint = getFillPaint(); - boolean isFillClear = isClear(fillPaint); - boolean isLineClear = isClear(displayPaint); - - Paint tm = getTextureMask(); - - // If shapes are null, then we have to do things the old way. - try { - for (i = 0; i < len; i++) { - _x = xpts[i]; - _y = ypts[i]; - - if (_x == null || _y == null) { - continue; - } - - // render polygon - if (isPolygon()) { - - // fill main polygon - - if (!isFillClear) { - // set the interior coloring parameters - setGraphicsForFill(g); - GeneralPath polyGon = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - polyGon.moveTo(_x[j], _y[j]); - } else { - polyGon.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).fill(polyGon); - - if (tm != null && tm != fillPaint) { - setGraphicsColor(g, tm); - ((Graphics2D) g).fill(polyGon); - } - } - - // only draw outline if different color or matted - if (matted || !isLineClear || !edgeMatchesFill) { - - if (matted) { - if (g instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) g).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - setGraphicsColor(g, mattingPaint); - GeneralPath polyLine = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - polyLine.moveTo(_x[j], _y[j]); - } else { - polyLine.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).draw(polyLine); - } - } - - setGraphicsForEdge(g); - GeneralPath polyGon = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - polyGon.moveTo(_x[j], _y[j]); - } else { - polyGon.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).draw(polyGon); - } - } - - // render polyline - else { - - if (matted) { - if (g instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) g).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - // Just to draw the matting for the - // arrowhead. - if (arrowhead != null) { - setGraphicsColor(g, mattingPaint); - arrowhead.render(g); - } - setGraphicsColor(g, mattingPaint); - GeneralPath polyLine = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - polyLine.moveTo(_x[j], _y[j]); - } else { - polyLine.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).draw(polyLine); - } - } - - // draw main outline - setGraphicsForEdge(g); - GeneralPath polyLine = new GeneralPath(); - for (int j = 0; j < _x.length; j++) { - if (j == 0) { - polyLine.moveTo(_x[j], _y[j]); - } else { - polyLine.lineTo(_x[j], _y[j]); - } - } - ((Graphics2D) g).draw(polyLine); - - if (arrowhead != null) { - arrowhead.render(g); - } - } - } - - renderLabel(g); - - } catch (Exception e) { - // Trying to catch any clipping problems from within a JRE - Debug.output("OMPoly: caught Java rendering exception\n" + e.getMessage()); - if (Debug.debugging("ompoly")) { - e.printStackTrace(); - } - } - } - - /** - * Return the shortest distance from the graphic to an XY-point. This works - * if generate() has been successful. - * - * @param x horizontal pixel location. - * @param y vertical pixel location. - * @return the distance of the object to the location given. - */ - public float distance(double x, double y) { - Shape shape = getShape(); - if (shape != null) { - return super.distance(x, y); - } - - // If shape is null, then we have to do things the old way. - - float temp, distance = Float.POSITIVE_INFINITY; - - if (getNeedToRegenerate()) { - return distance; - } - - // safety: grab local reference of projected points - float[][] xpts = xpoints; - float[][] ypts = ypoints; - float[] _x, _y; - int len = xpts.length; - - for (int i = 0; i < len; i++) { - _x = xpts[i]; - _y = ypts[i]; - - // check if point inside polygon - if (isPolygon() && DrawUtil.inside_polygon(_x, _y, x, y)) - return 0f; // close as can be - - // get the closest point - temp = DrawUtil.closestPolyDistance(_x, _y, x, y, false); - if (temp < distance) - distance = temp; - } - - return normalizeDistanceForLineWidth(distance); - } - - /** - * Get the array of java.awt.Shape objects that represent the projected - * graphic. The array will contain more than one Shape object of the object - * wraps around the earth and needs to show up in more than one place on the - * map. - *

- * - * The java.awt.Shape object gives you the ability to do a little spatial - * analysis on the graphics. - * - * @return java.awt.geom.GeneralPath (Shape), or null if the graphic needs - * to be generated with the current map projection, or null if the - * OMGeometry hasn't been updated to use Shape objects for its - * internal representation. - */ - public GeneralPath getShape() { - GeneralPath shape = super.getShape(); - if (shape == null) { - // Since polygons have the option of not creating shape - // objects, should create one if asked. - shape = createShape(); - setShape(shape); - setLabelLocation(shape, null); - } - return shape; - } - - /** - * Since OMPoly has the option to not create a Shape, this method is here to - * create it if it is asked for. The OMPoly needs to be generated. - */ - protected GeneralPath createShape() { - - GeneralPath shape = null; - - if (getNeedToRegenerate() || !checkPoints(xpoints, ypoints)) { - return shape; - } - - initLabelingDuringGenerate(); - - switch (renderType) { - - case RENDERTYPE_XY: - case RENDERTYPE_OFFSET: - shape = createShape(xpoints[0], ypoints[0], isPolygon()); - break; - case RENDERTYPE_LATLON: - int size = xpoints.length; - - for (int i = 0; i < size; i++) { - GeneralPath gp = createShape(xpoints[i], ypoints[i], isPolygon()); - - shape = appendShapeEdge(shape, gp, false); - } - - break; - - default: - } - - setLabelLocation(xpoints[0], ypoints[0]); - return shape; - } - - protected boolean geometryClosed = false; - - /** - * Is the geometry closed ? - * - * @return boolean - */ - protected boolean isGeometryClosed() { - geometryClosed = false; - switch (renderType) { - case RENDERTYPE_XY: - case RENDERTYPE_OFFSET: - if (xs != null && xs.length > 2) { - geometryClosed = (xs[0] == xs[xs.length - 1] && ys[0] == ys[ys.length - 1]); - } - break; - case RENDERTYPE_LATLON: - if (rawllpts != null) { - int l = rawllpts.length; - if (l > 4) { - geometryClosed = (MoreMath.approximately_equal(rawllpts[0], rawllpts[l - 2]) && MoreMath.approximately_equal(rawllpts[1], rawllpts[l - 1])); - } - } - break; - case RENDERTYPE_UNKNOWN: - Debug.error("OMPoly.generate: invalid RenderType"); - break; - } - - return geometryClosed; - } - - /** For XMLEncoder */ - public double[] getRawllpts() { - return this.rawllpts; - } - - /** For XMLEncoder */ - public int getUnits() { - return this.units; - } - - /** - * Convenience function for adding some coordinates to the polygon, for - * lat/lon polygons. Might be tricky for closed polygons, you might want to - * consider the index and not make them the starting or end point to - * preserve closed property. - * - * @param latlons the set of coordinates to add, in radians. Use - * ProjMath.arrayDegToRad() if you need to convert decimal degrees. - * @param coordPairIndex index of the coordinate pair to insert coordinates. - * 0 is the start of the polygon, 1 means the latlons will be - * inserted after the first original coordinate pair, etc. - * @param replaceEndsOfInsertedAtJoin flad to indicate whether the - * coordinates at the end of the inserted latlons array should be - * removed before insertion. If the coordinate list is being added to - * the start or end of the polygon, only the coordinate pair - * connecting to the original poly will be removed. - */ - public void insertRadians(double[] latlons, int coordPairIndex, - boolean replaceEndsOfInsertedAtJoin) { - int minPntsNeededForInsertion = 2; - boolean atEnd = false; - // Test for closed polygon to adjust the insertion point a little to - // preserve closedness. - boolean isClosed = isGeometryClosed(); - - int insertionPoint = coordPairIndex * 2; - if (insertionPoint >= rawllpts.length) { - if (isClosed) { - insertionPoint = rawllpts.length - 2; - } else { - insertionPoint = rawllpts.length; - atEnd = true; - } - } else if (insertionPoint <= 0) { - if (isClosed) { - insertionPoint = 2; - } else { - insertionPoint = 0; - atEnd = true; - } - } - - int newCoordStart = 0; - int newCoordLength = latlons.length; - - if (replaceEndsOfInsertedAtJoin) { - newCoordStart = 2; - minPntsNeededForInsertion = 6; - - if (atEnd) { - minPntsNeededForInsertion -= 2; - newCoordLength -= 2; - - if (insertionPoint == 0) { - newCoordStart = 0; - } - - } else { - newCoordLength -= 4; - } - - } - - if (renderType == OMGraphic.RENDERTYPE_LATLON - && latlons.length >= minPntsNeededForInsertion && latlons.length % 2 == 0) { - double[] oldrawllpnts = rawllpts; - int oldCoordsRemaining = oldrawllpnts.length - insertionPoint; - - rawllpts = new double[oldrawllpnts.length + newCoordLength]; - - System.arraycopy(oldrawllpnts, 0, rawllpts, 0, insertionPoint); - System.arraycopy(latlons, newCoordStart, rawllpts, insertionPoint, newCoordLength); - System.arraycopy(oldrawllpnts, insertionPoint, rawllpts, insertionPoint - + newCoordLength, oldCoordsRemaining); - - setNeedToRegenerate(true); - } - } - - /** - * Get the index of the leading node of an edge that is intersecting the - * given location. Coordinates should be in pixels from upper left corner of - * map for RENDERTYPE_XY/RENDERTYPE_OFFSET, and in decimal degrees for - * RENDERTYPE_LATLON. - * - * @param x horizontal coordinate - * @param y vertical coordinate - * @param maxDist maximum pixel distance from segment to be considered an - * intersect. - * @return index of first node of intersecting segment, or -1 if not - * intersecting. - */ - public int getIndexOfFirstNodeOfSegIntersect(double x, double y, double maxDist) { - int ret = -1; - if (!getNeedToRegenerate()) { - if (renderType == RENDERTYPE_LATLON) { - Geo geo1 = new Geo(); - Geo geo2 = new Geo(); - Geo testGeom = new Geo(y, x); - - double[] ll = getLatLonArray(); - - int index = 0; - for (int i = 0; i < ll.length - 3; i += 2, index++) { - geo1.initializeRadians(ll[i], ll[i + 1]); - geo2.initializeRadians(ll[i + 2], ll[i + 3]); - - if (Intersection.isOnSegment(geo1, geo2, testGeom)) { - return index; - } - } - - } else if (renderType == RENDERTYPE_XY || renderType == RENDERTYPE_OFFSET) { - - if (xpoints != null) { - for (int copy = 0; copy < xpoints.length; copy++) { - int index = 0; - for (int node = 0; node < xpoints[copy].length - 1; node++, index++) { - - double startPntX = xpoints[copy][node]; - double startPntY = ypoints[copy][node]; - double endPntX = xpoints[copy][node + 1]; - double endPntY = ypoints[copy][node + 1]; - - float dist = (float) Line2D.ptSegDist(startPntX, startPntY, endPntX, endPntY, (double) x, (double) y); - - if (dist <= maxDist) { - return index; - } - - } - } - } - - } - } - return ret; - } - - public static void main(String[] argv) { - double[] origPoints = new double[] { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 }; - double[] insertionPoints = new double[] { 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 }; - OMPoly poly = new OMPoly(origPoints, OMGraphic.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - poly.insertRadians(insertionPoints, 2, true); - double[] pnts = poly.getLatLonArray(); - System.out.println("--------- in middle, replacing join points"); - for (int i = 0; i < pnts.length; i++) { - System.out.println("pnt[" + i + "]: " + pnts[i]); - } - - poly.setLocation(origPoints, OMGraphic.RADIANS); - poly.insertRadians(insertionPoints, 0, true); - pnts = poly.getLatLonArray(); - System.out.println("--------- at start, replacing join points"); - for (int i = 0; i < pnts.length; i++) { - System.out.println("pnt[" + i + "]: " + pnts[i]); - } - - poly.setLocation(origPoints, OMGraphic.RADIANS); - poly.insertRadians(insertionPoints, origPoints.length / 2, true); - pnts = poly.getLatLonArray(); - System.out.println("--------- at end, replacing join points"); - for (int i = 0; i < pnts.length; i++) { - System.out.println("pnt[" + i + "]: " + pnts[i]); - } - - poly.setLocation(origPoints, OMGraphic.RADIANS); - poly.insertRadians(insertionPoints, 6, false); - pnts = poly.getLatLonArray(); - System.out.println("--------- overrun end, not replacing join points"); - for (int i = 0; i < pnts.length; i++) { - System.out.println("pnt[" + i + "]: " + pnts[i]); - } - - poly.setLocation(origPoints, OMGraphic.RADIANS); - poly.insertRadians(insertionPoints, -2, false); - pnts = poly.getLatLonArray(); - System.out.println("--------- overrun start, not replacing join points"); - for (int i = 0; i < pnts.length; i++) { - System.out.println("pnt[" + i + "]: " + pnts[i]); - } - - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.omGraphics.OMGraphic#restore(com.bbn.openmap.omGraphics - * .OMGraphic) - */ - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMPoly) { - OMPoly polySource = (OMPoly) source; - this.units = polySource.units; - // These two things are in radians! - this.lat = polySource.lat; - this.lon = polySource.lon; - this.coordMode = polySource.coordMode; - this.xs = DeepCopyUtil.deepCopy(polySource.xs); - this.ys = DeepCopyUtil.deepCopy(polySource.ys); - this.isPolygon = polySource.isPolygon; - this.rawllpts = DeepCopyUtil.deepCopy(polySource.getLatLonArray()); - this.doShapes = polySource.doShapes; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRangeRings.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRangeRings.java deleted file mode 100755 index 5b39a4839..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRangeRings.java +++ /dev/null @@ -1,399 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMRangeRings.java,v $ -// $RCSfile: OMRangeRings.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/02/25 22:34:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.text.DecimalFormat; -import java.text.NumberFormat; - -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * An object that manages a series of range circles. It is really an OMCircle - * that manages a set of inner circles and an OMPOint. The location of these - * inner circles depend on two new variables, the interval and intervalUnits. If - * the intervalUnits are null, then the interval represents the number of inner - * circles, not including the outer ring and the innermost point, that are - * spaced evenly between them. If the intervalUnits are not null, then the - * interval represents the number of intervalUnits where inner circles are - * placed. For example, if the intervalUnits is Length.MILE, and the interval is - * 5, then inner circles will be placed every 5 miles. If the intervalUnits is - * null, then there will be 5 inner circles drawn between the center point and - * the outer ring. - * - * @see OMCircle - */ -public class OMRangeRings - extends OMCircle { - /** The inner ring of circles. */ - protected OMCircle[] subCircles = null; - /** The labels for the circles. */ - protected OMText[] labels = null; - - /** By default, there are 3 inner rings, 4 total. */ - public final static int DEFAULT_INTERVAL = 4; - /** - * The number of rings, or the unit interval, depending on whether - * intervalUnits is null or not. - */ - protected int interval = DEFAULT_INTERVAL; - /** The unit object specifying the interval meaning. */ - protected Length intervalUnits = null; - /** - * The DrawingAttributes object used to reflect the outer circle properties - * to the inner circles. Only used in render(), and allocated to save - * repeated allocation during render. - */ - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - /** The center point of the range rings. */ - protected OMPoint centerPoint; - /** The default format. */ - public final static DecimalFormat DEFAULT_FORMAT = new DecimalFormat(); - /** Formatting for the labels with units. */ - protected NumberFormat form = DEFAULT_FORMAT; - - protected boolean drawLabels = true; - - /** - * Used for UndoEvents. Otherwise, don't use this unless you set all other - * parameters befitting an OMGraphic of such resplendent information. - */ - public OMRangeRings() { - } - - /** - * Creates an OMRangeRings with a Lat-lon center and a lat-lon axis. - * Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center point, decimal degrees - * @param lonPoint longitude of center point, decimal degrees - * @param radius distance in decimal degrees (converted to radians - * internally). - */ - public OMRangeRings(double latPoint, double lonPoint, double radius) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, Length.DECIMAL_DEGREE, -1); - } - - /** - * Create an OMRangeRings with a lat/lon center and a physical distance - * radius. Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object. - */ - public OMRangeRings(double latPoint, double lonPoint, double radius, Length units) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, units, -1); - } - - /** - * Create an OMRangeRings with a lat/lon center and a physical distance - * radius. Rendertype is RENDERTYPE_LATLON. - * - * @param latPoint latitude of center of circle in decimal degrees - * @param lonPoint longitude of center of circle in decimal degrees - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units. - * @param nverts number of vertices for the poly-circle (if < 3, value is - * generated internally) - */ - public OMRangeRings(double latPoint, double lonPoint, double radius, Length units, int nverts) { - this(new LatLonPoint.Double(latPoint, lonPoint), radius, units, nverts); - } - - /** - * Create an OMRangeRings with a lat/lon center and a physical distance - * radius. Rendertype is RENDERTYPE_LATLON. - * - * @param center LatLon center of circle - * @param radius distance - * @param units com.bbn.openmap.proj.Length object specifying units for - * distance. - * @param nverts number of vertices for the poly-circle(if < 3, value is - * generated internally) - */ - public OMRangeRings(LatLonPoint center, double radius, Length units, int nverts) { - super(center, radius, units, nverts); - centerPoint = createCenterPoint(); - form.setMaximumFractionDigits(2); - } - - protected OMPoint createCenterPoint() { - return new OMPoint(center.getY(), center.getX()); - } - - /** - * Set the interval. If the interval units are null, then this interval - * represents the number of circles within the external, defined circle. If - * the interval units are not null, then this interval represents the unit - * intervals where range rings are placed. - */ - public void setInterval(int interval) { - this.interval = interval; - setNeedToRegenerate(true); - } - - /** Convenience method to set both at one time. */ - public void setInterval(int interval, Length units) { - setInterval(interval); - setIntervalUnits(units); - } - - /** - * Get the interval number. - */ - public int getInterval() { - return interval; - } - - /** - * Set the interval units. If this is null, then the interval value will - * represent the number of rings drawn within the defined outer ring. If this - * is not null, then it represents the units of the interval where the range - * rings are drawn. - */ - public void setIntervalUnits(Length units) { - intervalUnits = units; - setNeedToRegenerate(true); - } - - /** - * Get the interval units. - */ - public Length getIntervalUnits() { - return intervalUnits; - } - - /** - * Flag for whether the rings should be labeled. - */ - public void setDrawLabels(boolean dl) { - drawLabels = dl; - } - - public boolean getDrawLabels() { - return drawLabels; - } - - /** - * Set the format for the number labels. If null, the default will be used. - * This only applies to the labels with units. - */ - public void setFormat(java.text.NumberFormat nf) { - if (nf != null) { - form = nf; - } else { - form = DEFAULT_FORMAT; - } - } - - /** - * Get the format used for the labeling of unit rings. - */ - public java.text.NumberFormat getFormat() { - return form; - } - - /** - * Set the radius. This is meaningful only if the render type is - * RENDERTYPE_LATLON. Note that while the radius is specified as decimal - * degrees, it only means the distance along the ground that that number of - * degrees represents at the equator, *NOT* a radius of a number of degrees - * around a certain location. There is a difference. - * - * @param radius float radius in decimal degrees - */ - public void setRadius(float radius) { - setRadius(radius, Length.DECIMAL_DEGREE); - } - - /** - * Set the radius with units. This is meaningful only if the render type is - * RENDERTYPE_LATLON. - * - * @param radius float radius - * @param units Length specifying unit type. - */ - public void setRadius(float radius, Length units) { - this.radius = units.toRadians(radius); - setNeedToRegenerate(true); - } - - /** - * Take the interval and intervalUnits, and then create the proper inner - * circles. - */ - public OMCircle[] createCircles() { - OMCircle[] circles; - OMText[] t; - int i; - double rad; - String value; - if (intervalUnits == null) { - int noUnitInterval = interval - 1; - circles = new OMCircle[noUnitInterval]; - t = new OMText[noUnitInterval]; - - for (i = 0; i < noUnitInterval; i++) { - rad = (i + 1) * radius / (noUnitInterval + 1); - circles[i] = new OMCircle(LatLonPoint.getDouble(center), rad, Length.RADIAN, -1); - value = ((i + 1) + "/" + (noUnitInterval + 1)); - t[i] = new OMText(center.getY() + Length.DECIMAL_DEGREE.fromRadians(rad), center.getX(), value, OMText.JUSTIFY_CENTER); - } - } else { - double realDistanceInterval = intervalUnits.toRadians(interval); - int number = (int) (radius / realDistanceInterval); - circles = new OMCircle[number]; - t = new OMText[number + 1]; - for (i = 0; i < number; i++) { - rad = (i + 1) * realDistanceInterval; - circles[i] = new OMCircle(LatLonPoint.getDouble(center), rad, Length.RADIAN, -1); - value = (form.format((double) (i + 1) * interval) + " " + intervalUnits.getAbbr()); - t[i] = new OMText(center.getY() + Length.DECIMAL_DEGREE.fromRadians(rad), center.getX(), value, OMText.JUSTIFY_CENTER); - } - value = (form.format((double) intervalUnits.fromRadians(radius)) + " " + intervalUnits.getAbbr()); - t[i] = new OMText(center.getY() + Length.DECIMAL_DEGREE.fromRadians(radius), center.getX(), value, OMText.JUSTIFY_CENTER); - } - labels = t; - return circles; - } - - /** - * Prepare the circles for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - if (getNeedToRegenerate() == true) { - if (interval > 0) { - subCircles = createCircles(); - } else { - subCircles = null; - } - } - - centerPoint = createCenterPoint(); - centerPoint.generate(proj); - - setRenderType(RENDERTYPE_LATLON); // Can't be anything else. - int i; - if (subCircles != null) { - for (i = 0; i < subCircles.length; i++) { - subCircles[i].generate(proj); - labels[i].generate(proj); - } - - // do the one for the outer ring if there are units. - if (labels.length > i) { - labels[i].generate(proj); - } - } - - return super.generate(proj); - } - - /** - * Paint the circles. - * - * @param g Graphics context to render into - */ - public void render(Graphics g) { - super.render(g); - drawingAttributes.setFrom(this); - - if (subCircles != null) { - // Draw from the larger to the smaller, so the lines of - // the smaller circles will appear on top of the bigger - // ones. - for (int i = subCircles.length - 1; i >= 0; i--) { - drawingAttributes.setTo(subCircles[i]); - drawingAttributes.setTo(labels[i]); - labels[i].setLinePaint(drawingAttributes.getLinePaint()); - subCircles[i].render(g); - if (drawLabels) { - labels[i].render(g); - } - } - // do the one for the outer ring if there are units. - if (labels.length > subCircles.length && drawLabels) { - drawingAttributes.setTo(labels[subCircles.length]); - labels[subCircles.length].setLinePaint(drawingAttributes.getLinePaint()); - labels[subCircles.length].render(g); - } - } - if (centerPoint != null) { - drawingAttributes.setTo(centerPoint); - centerPoint.render(g); - } - } - - /** - * Return the shortest distance from the circle to an XY-point. - * - * @param x X coordinate of the point. - * @param y Y coordinate fo the point. - * @return float distance from circle to the point - */ - public float distance(double x, double y) { - float dist = normalizeDistanceForLineWidth(super.distance(x, y)); - - // Not sure whether the inner circles should be queried for - // distance measurements. - float tmpDist; - // if (dist != 0 && subCircles != null) { - // for (int i = 0; i < subCircles.length; i++) { - // tmpDist = subCircles[i].distance(x, y); - // if (tmpDist == 0) return tmpDist; - - // if (tmpDist < dist) { - // dist = tmpDist; - // } - // } - // } - tmpDist = centerPoint.distance(x, y); - if (tmpDist < dist) { - dist = tmpDist; - } - - return dist; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMRangeRings) { - OMRangeRings rings = (OMRangeRings) source; - this.subCircles = DeepCopyUtil.deepCopy(rings.subCircles); - this.labels = DeepCopyUtil.deepCopy(rings.labels); - this.interval = rings.interval; - this.intervalUnits = rings.intervalUnits; - this.centerPoint = DeepCopyUtil.deepCopy(rings.centerPoint); - this.form = (NumberFormat) rings.form.clone(); - this.drawLabels = true; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRaster.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRaster.java deleted file mode 100644 index 19a221c83..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRaster.java +++ /dev/null @@ -1,873 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMRaster.java,v $ -// $RCSfile: OMRaster.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.WritableRaster; -import java.io.Serializable; -import java.util.logging.Level; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DeepCopyUtil; -import com.bbn.openmap.util.MoreMath; - -/** - * The OMRaster object lets you create multi-colored images. An image is a two - * dimensional array of pixel values that correspond to some color values. The - * pixels are used from the top left, across each row to the right, down to the - * bottom row. - *

- * There are two colormodels that are implemented in OMRaster - the direct - * colormodel and the indexed colormodel. The direct colormodel is implemented - * when the pixel values contain the actual java.awt.Color values for the image. - * The indexed colormodel is implemented when the pixel values are actually - * indexes into an array of java.awt.Colors. NOTE: The direct colormodel - * OMRaster is faster to display, because it doesn't need to take the time to - * resolve the colortable values into pixels. - *

- * - * For direct colormodel images: If you pass in a null pix or a pix with a zero - * length, the object will create the pixels for you but will not general a - * renderable version of the object. You will need to call render before - * generate after the pixels have been set. This feature is for cached rasters, - * where the content may be changed later. Use this (null pix) if you are - * building images in a cache, for tiled mapping data or something else where - * the data is not yet known. The memory for the pixels will be allocated, and - * then they can be set with image data later when a database is accessed. - *

- * - * For ImageIcon OMRasters: Using an ImageIcon to create an OMRaster gives you - * the ability to put an image on the screen based on an ImageIcon made from - * file or URL. The OMRaster uses this ImageIcon as is - there is no opportunity - * to change any parameters of this image. So set the colors, transparency, etc. - * before you create the OMRaster. - *

- * - * For indexed colormodel images: If you pass in an empty byte array, a byte - * array will be created based on the width and height. You will have to resolve - * empty colortables and set the pixels later. Use this method (null bytes) if - * you are building images in a cache, for tiled mapping data or something else - * where the data is not yet known. The memory for the pixels will be allocated, - * and then they can be set with image data later when a database is accessed. - * - * There is the ability to add a filter to the image, to change it's appearance - * for rendering. The most common filter, which is included as a kind of - * default, is the scale filter. Filtering the OMRasterObject replaces the - * bitmap variable, which is the internal java.awt.Image used for rendering. For - * OMRasters created with pixels, or with the colortable and the colortable - * index, the original data is left intact, and can be recreated later, or - * rescaled on the fly, because the internal bitmap will be recreated prior to - * re-scaling. For OMRasters created by ImageIcons or Images, though, you'll - * need to hold on to the original Image. The internal version is replaced by - * the filtered version. - * - * @see OMRasterObject - */ -public class OMRaster extends OMRasterObject implements Serializable { - - /** - * The integer colors that are needed in a java colortable. The Color[] that - * gets passed into some of the constructors goes to build this, but this - * array is really used to build the image pixel array. - */ - protected int[] colors = null; - - /** - * The transparency of the image. If this is set to anything less than 255, - * this value is used for all colors in the image. If it is set to 255, then - * the alpha value in each Color regulates the transparency of the image. - * The value of this variable should stay in the range: - * 0 <= transparent <= 255 - */ - protected int transparent = 255; - - /** - * Construct a blank OMRaster, to be filled in with setX calls. - */ - public OMRaster() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - // /////////////////////////////////// INT PIXELS - DIRECT - // COLORMODEL - - /** - * Creates an OMRaster images, Lat/Lon placement with a direct colormodel. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @see #setPixel - */ - public OMRaster(double lt, double ln, int w, int h, int[] pix) { - - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_DIRECT); - lat = lt; - lon = ln; - width = w; - height = h; - pixels = pix; - - if (pixels == null || pixels.length == 0) - pixels = new int[height * width]; - } - - /** - * Create an OMRaster image, XY placement with a direct colormodel. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @see #setPixel - */ - public OMRaster(int x1, int y1, int w, int h, int[] pix) { - - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_DIRECT); - x = x1; - y = y1; - width = w; - height = h; - pixels = pix; - - if (pixels == null || pixels.length == 0) - pixels = new int[height * width]; - } - - /** - * Create an OMRaster, Lat/lon placement with XY offset with a direct - * colormodel. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @see #setPixel - */ - public OMRaster(double lt, double ln, int offset_x1, int offset_y1, int w, int h, int[] pix) { - - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_DIRECT); - lat = lt; - lon = ln; - x = offset_x1; - y = offset_y1; - width = w; - height = h; - pixels = pix; - - if (pixels == null || pixels.length == 0) { - pixels = new int[height * width]; - } - } - - // //////////////////////////////////// IMAGEICON - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param ii ImageIcon used for the image. - */ - public OMRaster(double lt, double ln, ImageIcon ii) { - this(lt, ln, ii.getImage()); - } - - /** - * Create an OMRaster, Lat/Lon placement with an Image. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param ii Image used for the image. - */ - public OMRaster(double lt, double ln, Image ii) { - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_IMAGEICON); - lat = lt; - lon = ln; - setImage(ii); - } - - /** - * Create an OMRaster image, X/Y placement with an ImageIcon. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param ii ImageIcon used for the image. - */ - public OMRaster(int x1, int y1, ImageIcon ii) { - this(x1, y1, ii.getImage()); - } - - /** - * Create an OMRaster image, X/Y placement with an Image. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param ii Image used for the image. - */ - public OMRaster(int x1, int y1, Image ii) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_IMAGEICON); - x = x1; - y = y1; - setImage(ii); - } - - /** - * Create an OMRaster, Lat/Lon with X/Y placement with an ImageIcon. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param ii ImageIcon used for the image. - */ - public OMRaster(double lt, double ln, int offset_x1, int offset_y1, ImageIcon ii) { - this(lt, ln, offset_x1, offset_y1, ii.getImage()); - } - - /** - * Create an OMRaster, Lat/Lon with X/Y placement with an Image. Make sure - * that the Image is complete( if being loaded over the internet) and ready - * to be drawn. Otherwise, you have to figure out when the Image is - * complete, so that you can get the layer to paint it! Use the ImageIcon - * constructor if you don't mind blocking to wait for the pixels to arrive. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param ii Image used for the image. - */ - public OMRaster(double lt, double ln, int offset_x1, int offset_y1, Image ii) { - - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_IMAGEICON); - lat = lt; - lon = ln; - x = offset_x1; - y = offset_y1; - setImage(ii); - } - - // //////////////////////////////////// BYTE PIXELS with - // COLORTABLE - - /** - * Lat/Lon placement with a indexed colormodel, which is using a colortable - * and a byte array to construct the int[] pixels. - * - * @param lt latitude of the top of the image. - * @param ln longitude of the left side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @see #setPixel - */ - public OMRaster(double lt, double ln, int w, int h, byte[] bytes, Color[] colorTable, int trans) { - - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_INDEXED); - lat = lt; - lon = ln; - width = w; - height = h; - bits = bytes; - transparent = trans; - if (colorTable != null) { - setColors(colorTable); - } - - if (bits != null && bits.length != 0) { - if (colorTable != null && colors.length != 0) { - pixels = computePixels(bits); - } - } else { - bits = new byte[height * width]; - } - } - - /** - * XY placement with a indexed colormodel, which is using a colortable and a - * byte array to construct the int[] pixels. - * - * @param x1 window location of the left side of the image. - * @param y1 window location of the top of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @see #setPixel - */ - public OMRaster(int x1, int y1, int w, int h, byte[] bytes, Color[] colorTable, int trans) { - - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_INDEXED); - x = x1; - y = y1; - width = w; - height = h; - bits = bytes; - transparent = trans; - if (colorTable != null) { - setColors(colorTable); - } - - if (bits != null && bits.length != 0) { - if (colorTable != null && colors.length != 0) { - pixels = computePixels(bits); - } - } else { - bits = new byte[height * width]; - } - } - - /** - * Lat/lon placement with XY offset with a indexed colormodel, which is - * using a colortable and a byte array to construct the int[] pixels. - * - * @param lt latitude of the top of the image, before the offset. - * @param ln longitude of the left side of the image, before the offset. - * @param offset_x1 number of pixels to move image to the right. - * @param offset_y1 number of pixels to move image down. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @see #setPixel - */ - public OMRaster(double lt, double ln, int offset_x1, int offset_y1, int w, int h, byte[] bytes, - Color[] colorTable, int trans) { - - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - setColorModel(COLORMODEL_INDEXED); - lat = lt; - lon = ln; - x = offset_x1; - y = offset_y1; - width = w; - height = h; - transparent = trans; - bits = bytes; - if (colorTable != null) { - setColors(colorTable); - } - - if (bits != null && bits.length != 0) { - if (colorTable != null && colors.length != 0) { - pixels = computePixels(bits); - } - } else { - bits = new byte[height * width]; - } - } - - // //////////////////////////////////////////////////// - /** - * Just a simple check to see if the x, y pair actually fits into the pixel - * array. - * - * @param x x location of pixel, from the left side of image. - * @param y y location of pixel, from the top of image. - * @return true if location within pixel array. - */ - private boolean boundsSafe(int x, int y) { - if ((y < 0) || (y >= height) || (x < 0) || (x >= width)) { - return false; - } - return true; - } - - /** - * Set the ImageIcon. - * - * @param img ImageIcon - */ - public void setImageIcon(ImageIcon img) { - setImage(img.getImage()); - } - - /** - * Set the image pixel value at a location. - * - * @param x Horizontal location of pixel from left. - * @param y Vertical location of pixel from top. - * @param colorValue the color value of the pixel. - * @return true if x, y location valid. - */ - public boolean setPixel(int x, int y, int colorValue) { - - if (boundsSafe(x, y)) { - pixels[(y * width) + x] = colorValue; - setNeedToRegenerate(true); - return true; - } - return false; // fail - } - - /** - * Get the image pixel value at a location. - * - * @param x Horizontal location of pixel from left. - * @param y Vertical location of pixel from top. - * @return the integer color value of the image at x, y - */ - public int getPixel(int x, int y) { - if (boundsSafe(x, y)) { - return pixels[(y * width) + x]; - } - return 0; // fail - but also the ct[0] - hmmmmm. - } - - /** - * Set image byte data, for index frame using colortable. - * - * @param x Horizontal location of pixel from left. - * @param y Vertical location of pixel from top. - * @param ctIndex The array index of the applicable color in the color - * table. - * @return true if x, y location valid. - */ - public boolean setByte(int x, int y, byte ctIndex) { - if (boundsSafe(x, y) && bits != null) { - bits[(y * width) + x] = ctIndex; - setNeedToRegenerate(true); - return true; - } - return false; // fail - } - - /** - * Get image byte data, which the index to a colortable for indexed images. - * - * @param x Horizontal location of pixel from left. - * @param y Vertical location of pixel from top. - * @return byte value of bytes(x, y) - */ - public byte getByte(int x, int y) { - if (boundsSafe(x, y) && bits != null) { - return bits[(y * width) + x]; - } - return 0; // fail - but also the ct[0] - hmmmmm. - } - - /** - * Set the bytes used to create the pixels used to create the image. Checks - * to see of the length matches the height * width, but doesn't do anything - * if they don't match, except print out a warning. Make sure it does. - * - * @param values byte values containing bit pixel values. - */ - public void setBits(byte[] values) { - super.setBits(values); - if ((values.length) != (height * width)) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("OMBitmap: new byte[] size (" + +values.length + ") doesn't" - + " match [height*width (" + height * width + ")]"); - } - } - } - - /** - * Set the transparency of the index type images. For the Direct Colormodel - * the pixel data needs to be reconstructed, so this is an O(pixels.length) - * operation. For an indexed colormodel, the data still needs to be - * reconstructed, but it will cost you the time in generate(). The - * transparency value should be a number between 0-255. - * - * @param value New value of the alpha value for the image. - */ - public void setTransparent(int value) { - value &= 0x000000ff; - if (transparent == value) - return; - transparent = value; - setNeedToRegenerate(true); - if (bits != null) { - pixels = computePixels(bits); - } else { - value <<= 24;// move to alpha position - // direct color model, touch each pixel in the image - for (int i = 0; i < pixels.length; i++) { - - // Do this if we want to support images that have - // transparent pixels, and we want each pixel to have - // the most transparent pixel. - - // Why don't we want to do this??? DFD - - // int pixAlpha = 0xFF000000 & pixels[i]; - // pixAlpha = (pixAlpha < value)?pixAlpha:value; - // pixels[i] = (0x00ffffff & pixels[i]) | pixAlpha; - - pixels[i] = (0x00ffffff & pixels[i]) | value; - } - } - } - - /** - * Get the transparent setting of the image. - * - * @return the transparent value (0-255) of the image. - */ - public int getTransparent() { - return transparent; - } - - /** - * Set the color table to the int RGB values passed in. Valid for the - * indexed colormodel only. The pixels will be colored according to these - * values. - * - * @param values array of color RGB values. - */ - public void setColors(int[] values) { - if (colorModel != COLORMODEL_INDEXED) { - logger.fine("OMRaster: Setting colors for final colortable when a colortable isn't needed!"); - } else { - colors = values; - setNeedToRegenerate(true); - } - } - - /** - * Set the color table according to the java.awt.Color array passed in. - * Valid for the indexed colormodel only. The pixels will be colored - * according to these values. The transparency values of these colors will - * only take effect of they are less than the transparency value of the - * images' value. - * - * @param values array of java.awt.Color colors. - */ - public void setColors(Color[] values) { - - if (colorModel != COLORMODEL_INDEXED) { - logger.fine("Setting colors for final colortable when a colortable isn't needed!"); - return; - - } else if (values == null || values.length == 0) { - colors = new int[0]; - logger.fine("What are you trying to do to me?!? The colortables gots to have values!"); - return; - - } else { - - if (values.length > 0) { - colors = new int[values.length]; - boolean allTransparent = true; - int trans = (transparent << 24) & 0xff000000; - - // Turn the color table into a table using the - // default OMava color model. - for (int i = 0; i < values.length; i++) { - - // The transparent field can be set for the whole - // image, while the open part of the colortable - // entry - // structure is the transparent setting for that - // particular color. - if (transparent < 255) { - int argb = values[i].getRGB(); - - if (values[i].getAlpha() > transparent) { - // If the transparent value of the pixel - // is - // lower than the transparency value, keep - // that instead - don't make things more - // visible then they were. - colors[i] = (0x00ffffff & argb) | trans; - } else { - colors[i] = argb; - } - - } else { - colors[i] = values[i].getRGB(); - } - - // Just check if all the colors are transparent - - // this is a pain to figure out if you are - // getting colors from some server that doesn't - // know about alpha values. - if (allTransparent && ((colors[i] >>> 24) != 0)) { - allTransparent = false; - } - } - if (DEBUG && allTransparent) { - logger.fine("OMRaster: **Whasamatta?** Image created with all transparent pixels!"); - } - } - - // This is wrong - we do need to force a computePixels, - // but in generate... - // computePixels(); - // This will do it.... - pixels = null; - setNeedToRegenerate(true); - } - } - - /** - * Get the array of colors used in the indexed color model. If the image is - * not a indexed colormodel, the int[] will be null. - * - * @return color int[] if index colormodel, null otherwise. - */ - public int[] getColors() { - return colors; - } - - // /////////////////////////////////////////////////////// - /** - * Compute pixels is the function that resolves the color table into pixel - * integer values used in the Image. It uses the bits as indexes into the - * color table, and builds a big array of ints to use in the bitmap image. - * If the bits are null, then the object was created in the direct color - * model where the colors are already built into the pixels. So, if you call - * this, the pixels have to be null and the bits good indexes into the - * colortable. - * - * @return new int[] for image pixels, null if there was a problem or if the - * colormodel is not COLORMODEL_INDEXED. - */ - protected int[] computePixels(byte[] bits) { - - if (DEBUG) { - logger.fine("OMRaster.compute pixels!"); - } - - if (colorModel != COLORMODEL_INDEXED) { - // I don't like this... DFD - return new int[0]; - } - - if (colors == null || colors.length == 0 || bits == null || bits.length == 0) { - logger.fine("OMRaster: attempting to compute pixels without color table or proper indexes!"); - return null; - } - - int nPixels = width * height; - if (DEBUG) { - logger.fine("Computing pixels for image size:" + width + ", " + height); - } - - int[] iPixels = new int[nPixels]; - - // Now, using the new constructed color table, build a set of - // pixels. alpha is a ready, shifted version of the overall - // transparency value; - int alpha = (transparent << 24) & 0xff000000; - int numColors = colors.length; - int bitsLength = bits.length; - - for (int i = 0; i < bitsLength && i < nPixels; i++) { - byte b = bits[i]; - int color = 0; - - // make the alpha for this color the lessor of what the - // colortable is, versus the transparent value - // int pixAlpha; - - if (b < 0) { - color = colors[MoreMath.signedToInt(b)]; - } else if (b < numColors) { - color = colors[b]; - } - - // OK, got an int value, argb, for the color to be put on - // the pixel. Now we need to straighten out the - // transparency. - if (transparent < 255 && ((color >> 24) > transparent)) { - // this means that the overall transparency should be - // more (lower number, more transparent) than the - // pixel color. - color = alpha | (0x00FFFFFF & color); - } // Otherwise, just go with the alpha value set on the - // color... - - iPixels[i] = color; - - } - - return iPixels; - } - - /** - * Prepare the graphics for rendering. For all image types, it positions the - * image relative to the projection. For direct and indexed colormodel - * images, it creates the ImageIcon used for drawing to the window (internal - * to object). For indexed colormodel images, it also calls computePixels, - * to resolve the colortable and the bytes to create the image pixels. - * - * @param proj Projection used to position the image on the window. - * @return true if the image is ready to paint. - */ - public boolean generate(Projection proj) { - renderRotationAngle = null; - - // Position sets the position for the OMRaster!!!! - if (!position(proj)) { - if (DEBUG) { - logger.fine("OMRaster.generate(): positioning failed!"); - } - return false; - } - - // We used to just return here if the OMRaster didn't need to - // be regenerated, but that didn't create the shape properly. - - if (getNeedToRegenerate()) { - bitmap = getBitmapFromInternalData(); - if (bitmap == null) { - return false; - } - } - - evaluateRotationAngle(proj); - - // generate shape that is a boundary of the generated image. - // We'll make it a GeneralPath rectangle. - setShape(); - - setLabelLocation(getShape(), proj); - - setNeedToRegenerate(false); - return true; - } - - /** - * Set the renderRotationAngle based on the projection angle and OMRaster - * settings. - * - * @param proj the current projection. - */ - protected void evaluateRotationAngle(Projection proj) { - renderRotationAngle = null; - double projRotation = proj.getRotationAngle(); - - if (projRotation != 0.0) { - // Only do the attribute check if the projection is rotated. - Object noRotationAtt = getAttribute(OMGraphicConstants.NO_ROTATE); - boolean compensateForProjRot = noRotationAtt != null - && !noRotationAtt.equals(Boolean.FALSE); - - if (compensateForProjRot) { - renderRotationAngle = rotationAngle - projRotation; - return; - } - } - - if (rotationAngle != DEFAULT_ROTATIONANGLE) { - renderRotationAngle = rotationAngle; - } - } - - protected Image getBitmapFromInternalData() { - Image bi = bitmap; - int[] iPixels = this.pixels; - byte[] iBits = this.bits; - int iWidth = this.width; - int iHeight = this.height; - java.awt.image.ImageFilter iImageFilter = this.imageFilter; - - if (colorModel != COLORMODEL_IMAGEICON) { - - // This section is for the indexed color model rasters - // that need to resolve the color map to the bit array - // indexes. - - // If pixels == null, then computePixels has not been - // called - if (iPixels == null) { - - if (iBits != null) { - iPixels = computePixels(iBits); - pixels = iPixels; - } - - if (iPixels != null) { - logger.fine("attempted to generate without pixels defined!"); - return null; - } - } - - if (iWidth <= 0 || iHeight <= 0 || iPixels == null) { - // NeedToRegenerate should still be true, so it won't - // render. - return null; - } - - bi = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_ARGB); - - /** - * Looking at the standard BufferedImage code, an int[0] is - * allocated for every pixel. Maybe the memory usage is optimized - * for that, but it goes through a call stack for every pixel to do - * it. Let's just cycle through the data and write the pixels - * directly into the raster. - */ - WritableRaster raster = (WritableRaster) ((BufferedImage) bi).getRaster(); - try { - raster.setDataElements(0, 0, iWidth, iHeight, iPixels); - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.fine("w: " + iWidth + ", h: " + iHeight + ", p.l: " + (iPixels != null? (iPixels.length + ", diff " + (iWidth * iHeight - iPixels.length)) : "null")); - } - } - - /* - * REPLACING bitmap with the filtered version - keep a copy yourself if - * you need the original!!! i.e. for COLORMODEL_IMAGEICON - */ - if (iImageFilter != null) { - bi = filterImage(bi); - } - - return bi; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMRaster) { - OMRaster raster = (OMRaster) source; - this.colors = DeepCopyUtil.deepCopy(raster.colors); - this.transparent = raster.transparent; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRasterObject.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRasterObject.java deleted file mode 100644 index d53dbee51..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRasterObject.java +++ /dev/null @@ -1,1104 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMRasterObject.java,v $ -// $RCSfile: OMRasterObject.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.image.AreaAveragingScaleFilter; -import java.awt.image.BufferedImage; -import java.awt.image.FilteredImageSource; -import java.awt.image.ImageConsumer; -import java.awt.image.ImageFilter; -import java.awt.image.ImageObserver; -import java.awt.image.ImageProducer; -import java.awt.image.MemoryImageSource; -import java.awt.image.PixelGrabber; -import java.awt.image.RenderedImage; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.image.ImageHelper; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * The OMRasterObject is the parent class for OMRaster and OMBitmap objects. It - * manages some of the same functions that both classes require in order to - * create image pixel data from bytes or integers. - * - *

- * An ImageFilter may be applied to OMRasterObjects. These can be scale filters, - * color filters, or maybe (?hopefully?) projection filters. These filters won't - * change the original image data, and the original can be reconstructed by - * resetting the filter to null, and generating the object. - *

- * - * For all classes in the OMRasterObject family, a java.awt.Shape object is - * created for the border of the image. This Shape object is used for distance - * calculations. If the OMRasterObject is selected(), however, this Shape will - * be rendered with the OMGraphic parameters that are set in the OMGraphic. - */ -public abstract class OMRasterObject extends OMGraphicAdapter implements OMGraphic, ImageObserver { - - private static final long serialVersionUID = 1L; - /** - * The direct colormodel, for OMRasters, means the integer values passed in - * as pixels, already reflect the RGB color values each pixel should - * display. - */ - public final static int COLORMODEL_DIRECT = 0; - /** - * The indexed colormodel, for OMRasters, means that the byte array passed - * in for the pixels has to be resolved with a colortable in order to create - * a integer array of RGB pixels. - */ - public final static int COLORMODEL_INDEXED = 1; - /** - * The ImageIcon colormodel means that the image is externally set, and we - * just want to to display the image at the given location. - */ - public final static int COLORMODEL_IMAGEICON = 2; - /** If scaling the image, use the slower, smoothing algorithm. */ - public final static int SMOOTH_SCALING = 0; - /** - * If scaling the image, use the faster, replicating/clipping algorithm. - */ - public final static int FAST_SCALING = 1; - /** - * colorModel helps figure out what kind of updates are necessary, by - * knowing what kind of image we're dealing with. For the images created - * with a ImageIcon, the attribute updates that don't relate to position - * will not take affect. - */ - protected int colorModel = COLORMODEL_DIRECT; - /** - * The pixels are used for the image that is drawn on the window. The pixels - * are either passed in as an int[] in some constructors of the OMRaster, or - * it is constructed in the OMBitmap and in OMRasters that have a - * colortable. - */ - protected int[] pixels = null; - - /** - * Horizontal location of the upper left corner of the image, or the x - * offset from the lon for that corner, in pixels. - */ - protected int x = 0; - - /** - * Vertical location of the upper left corner of the image, or the y offset - * from the lat for that corner, in pixels. - */ - protected int y = 0; - - /** - * The latitude of the upper left corner for the image, in decimal degrees. - */ - protected double lat = 0.0f; - - /** - * The longitude of the upper left corner for the image, in decimal degrees. - */ - protected double lon = 0.0f; - - /** - * The width of the image, in pixels. This always reflects the width of the - * original image, even if a filter is applied to the image. - */ - protected int width = 0; - - /** - * The height of the image, in pixels. This always reflects the height of - * the original image, even if a filter is applied to the image. - */ - protected int height = 0; - - /** - * The byte info for the image. OMBitmaps use each bit as an indication to - * use the lineColor or the fillColor for each pixel (like a XBitmap). - * OMRasters only use the bits when the image being created follows the - * indexed colormodel. Then, the bits hold the colortable indexes that each - * pixel needs to have a color substituted in later. - */ - protected byte[] bits = null; - - /** The bitmap is drawn to the graphics. */ - protected transient Image bitmap = null; - - /** - * Projected window pixel location of the upper left corner of the image. - */ - protected transient Point point1 = null; - - /** - * Projected window pixel location of the lower right corner of the image. - */ - protected transient Point point2 = null; - - /** - * The width of the image after scaling, if you want the image to be a - * different size than the source. - */ - protected int filteredWidth = 0; - - /** - * The height of the image after scaling, if you want the image to be a - * different size than the source. - */ - protected int filteredHeight = 0; - - /** The image filter to use on the constructed image. */ - protected ImageFilter imageFilter = null; - - /** - * Set if the projection has had attributes change that require a - * repositioning of the image, not a regeneration. - */ - protected boolean needToReposition = true; - - /** - * Pixel height of the current projection. Used for efficient zoom-in - * scaling. - */ - transient int projHeight; - - /** - * Pixel width of the current projection. Used for efficient zoom-in - * scaling. - */ - transient int projWidth; - - /** the angle by which the image is to be rotated, in radians */ - protected double rotationAngle; - - /** - * The angle, perhaps taking into account NO_ROTATE, that the image is - * rotated at render-time. - */ - protected Double renderRotationAngle = null; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.OMRasterObject"); - - protected transient boolean DEBUG = logger.isLoggable(Level.FINE); - - /** - * A Constructor that sets the graphic type to raster, render type to - * unknown, line type to unknown, and the declutter type to none. - */ - public OMRasterObject() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * A Constructor that sets the graphic type, render type, line type and the - * declutter type to the values you pass in. See OMGraphic for the - * definitions of these attributes. - * - * @param rType render type - * @param lType line type - * @param dcType declutter type - */ - public OMRasterObject(int rType, int lType, int dcType) { - super(rType, lType, dcType); - } - - /** - * The color model is set based on the constructor. This setting controls - * what parameter changes are possible for different models of images. - * - * @param cm the colormode that describes how the colors are being set - - * COLORMODEL_DIRECT, COLORMODEL_INDEXED, or COLORMODEL_IMAGEICON. - */ - protected void setColorModel(int cm) { - colorModel = cm; - } - - /** - * Get the color model type of the image. - * - * @return COLORMODEL_DIRECT, COLORMODEL_INDEXED, or COLORMODEL_IMAGEICON. - */ - public int getColorModel() { - return colorModel; - } - - /** - * Set the flag for the object that lets the render method (which draws the - * object) know that the object needs to be repositioned first. - */ - public void setNeedToReposition(boolean value) { - needToReposition = value; - } - - /** Return the reposition status. */ - public boolean getNeedToReposition() { - return needToReposition; - } - - /** - * Set the angle by which the image is to rotated. - * - * @param angle the number of radians the image is to be rotated. Measured - * clockwise from horizontal. - */ - public void setRotationAngle(double angle) { - this.rotationAngle = angle; - setNeedToRegenerate(true); - } - - /** - * Get the current rotation of the image. - * - * @return the image rotation. - */ - public double getRotationAngle() { - return rotationAngle; - } - - /** - * Compute the raster objects pixels, based on the color model and the byte - * values. - * - * @return int[] where things are OK (height*width = pixel.length), null if - * there is a problem. - */ - protected abstract int[] computePixels(byte[] bits); - - /** - * Called from within render(). This method should call rotate() on the - * provided Graphics2D object, setting the rotation angle and the rotation - * point. By default, the rotation angle is whatever is set in the - * OMRasterObject, and the rotation point is the offset point plus half the - * image width in the horizontal direction, and half the image in the - * vertical direction. - */ - protected void rotate(Graphics2D g) { - Double angle = renderRotationAngle; - if (angle != null) { - int w = width; - int h = height; - - // Note that this rotation is based on height and width of the - // image, which is not the right thing to do for scaled images. - ((Graphics2D) g).rotate(angle, point1.x + w / 2, point1.y + h / 2); - } - } - - /** - * Render the raster on the java.awt.Graphics - * - * @param graphics java.awt.Graphics to draw the image on. - */ - public void render(Graphics graphics) { - if (getNeedToRegenerate() || getNeedToReposition() || !isVisible()) { - if (DEBUG) { - logger.fine("OMRasterObject.render(): need to regenerate or not visible!"); - } - return; - } - - // copy the graphic, so our transform doesn't cascade to - // others... - Graphics g = graphics.create(); - - // Just a little check to find out if someone is rushing - // things. If a Image isn't fully loaded, the getWidth will - // return -1. This is just a courtesy notification in case - // someone isn't seeing their image, and don't know why. - if (colorModel == COLORMODEL_IMAGEICON && (getWidth() == -1)) { - logger.fine("OMRasterObject.render: Attempting to draw a Image that is not ready! Image probably wasn't available."); - } - - if (g instanceof Graphics2D && renderRotationAngle != null) { - // rotate about our image center point - rotate((Graphics2D) g); - } - - renderImage(g, bitmap, point1); - - if (isSelected() || logger.isLoggable(Level.FINER)) { - renderShape(g); - } - - renderLabel(graphics); - } - - /** - * Render the image at the given pixel location. This method should be - * overridden for special Image handling. - * - * @param g the Graphics object to render the image into. Assumes this is a - * derivative of the Graphics passed into the OMGraphic, and can be - * modified without worrying about passing settings on to other - * OMGraphics. - * @param loc the pixel location of the image. - */ - protected void renderImage(Graphics g, Image image, Point loc) { - if (image != null) { - - if (DEBUG) { - logger.fine("drawing " + width + "x" + height + " image at " + loc.x + ", " + loc.y); - } - - if (g instanceof Graphics2D && image instanceof RenderedImage) { - // Affine translation for placement... - ((Graphics2D) g).drawRenderedImage((RenderedImage) image, new AffineTransform(1f, 0f, 0f, 1f, loc.x, loc.y)); - } else { - g.drawImage(image, loc.x, loc.y, this); - } - } else if (DEBUG) { - logger.fine("ignoring null bitmap image"); - } - } - - /** - * Set the rectangle, based on the location and size of the image. - */ - public void setShape() { - - // generate shape that is a boundary of the generated image. - // We'll make it a GeneralPath rectangle. - int w = width; - int h = height; - - if (imageFilter != null) { - w = filteredWidth; - h = filteredHeight; - } - - GeneralPath projectedShape = createBoxShape(point1.x, point1.y, w, h); - double anchorX = point1.x + w / 2; - double anchorY = point1.y + h / 2; - setShape(adjustShapeForRotation(projectedShape, anchorX, anchorY)); - } - - /** - * Internally evaluates renderRotationAngle and if necessary, applies the - * rotation to the shape. If no rotation modifications are needed, the gp is - * returned as is. - * - * @param projectedShape The GeneralPath to rotate, if necessary. - * @param anchorX the x coordinate of the rotation point. - * @param anchorY the y coordinate of the rotation point. - * @return A rotated path if renderRotationAngle is not null, gp otherwise. - */ - protected GeneralPath adjustShapeForRotation(GeneralPath projectedShape, double anchorX, - double anchorY) { - if (renderRotationAngle != null) { - AffineTransform at = new AffineTransform(); - at.rotate(rotationAngle, anchorX, anchorY); - PathIterator pi = projectedShape.getPathIterator(at); - - GeneralPath rotPath = new GeneralPath(); - rotPath.append(pi, false); - // Replace shape with rotated version - return rotPath; - } - return projectedShape; - } - - /** - * Since the image doesn't necessarily need to be regenerated when it is - * merely moved, raster objects have this function, called from generate() - * and when a placement attribute is changed. - * - * @return true if enough information is in the object for proper placement. - * @param proj projection of window. - */ - protected boolean position(Projection proj) { - - if (proj == null) { - logger.fine("OMRasterObject: null projection in position!"); - return false; - } - - projWidth = proj.getWidth(); - projHeight = proj.getHeight(); - - switch (renderType) { - - case RENDERTYPE_LATLON: - if (!proj.isPlotable(lat, lon)) { - if (DEBUG) { - logger.fine("OMRasterObject: point is not plotable!"); - } - setNeedToReposition(true);// so we don't render it! - return false; - } - point1 = (Point) proj.forward(lat, lon, new Point()); - break; - case RENDERTYPE_XY: - point1 = new Point(x, y); - break; - case RENDERTYPE_OFFSET: - if (!proj.isPlotable(lat, lon)) { - if (DEBUG) { - logger.fine("OMRasterObject: point is not plotable!"); - } - setNeedToReposition(true);// so we don't render it! - return false; - } - point1 = (Point) proj.forward(lat, lon, new Point()); - point1.x += x; - point1.y += y; - break; - case RENDERTYPE_UNKNOWN: - if (DEBUG) { - logger.fine("OMRasterObject.position(): ignoring unknown rendertype, wingin' it"); - } - if (lat == 0 && lon == 0) { - if (x == 0 && y == 0) { - if (DEBUG) { - logger.fine("OMRasterObject.position(): Not enough info in object to place it reasonably."); - } - point1 = new Point(-width, -height); - point2 = new Point(0, 0); - return false; - } else { - point1 = new Point(x, y); - } - - } else { - if (!proj.isPlotable(lat, lon)) { - logger.fine("OMRasterObject: point is not plotable!"); - return false; - } - point1 = (Point) proj.forward(lat, lon, new Point()); - } - break; - } - - point2 = new Point(0, 0); - point2.x = point1.x + width; - point2.y = point1.y + height; - setNeedToReposition(false); - return true; - } - - /** - * Set the image to be drawn, if the color model is COLORMODEL_IMAGEICON. - * - * @param ii the image icon to use. - */ - public void setImage(Image ii) { - if (ii == null) { - logger.fine("OMRasterObject.setImage(): image is null!"); - return; - } - colorModel = COLORMODEL_IMAGEICON; - bitmap = ii; - // Make sure the image is ready to draw. If not, this method - // will be called again by the ImageObserver method - // imageUpdate. Set the height and width anyway. If they are - // -1, you know the image isn't ready - another way to find - // out. - if (bitmap instanceof BufferedImage) { - width = ((BufferedImage) bitmap).getWidth(); - height = ((BufferedImage) bitmap).getHeight(); - } else { - width = bitmap.getWidth(this); - height = bitmap.getHeight(this); - } - - if (!(ii instanceof RenderedImage)) { - Toolkit.getDefaultToolkit().prepareImage(bitmap, -1, -1, this); - } - } - - /** - * Overrides OMGraphicAdapter version to handle OMRasterObject - * getNeedToReposition. - * - * @param proj the Projection - * @return true if generated, false if didn't do it (maybe a problem). - * @see #generate - */ - public boolean regenerate(Projection proj) { - boolean ret = super.regenerate(proj); - - // handle extra case: OMRasterObject.getNeedToReposition() - if (proj != null && !ret) { - ret = generate(proj); - } - - return ret; - } - - /** - * Get the image that will be put on the window. - * - * @return the Image created by computePixels and generate(). - */ - public Image getImage() { - return bitmap; - } - - /** - * Always true for images, affects distance measurements. Forces the - * omGraphics package to treat the OMRasterObject as a filled shape. - */ - public boolean shouldRenderFill() { - return true; - } - - /** - * Set the pixels for the image for direct color model images. Checks to see - * of the length matches the height * width, but doesn't do anything if they - * don't match. Make sure it does. - * - * @param values the pixel values. - */ - public void setPixels(int[] values) { - if (values.length != (height * width)) - logger.fine("OMRasterObject: new pixel[] size (" + +values.length + ") doesn't" - + " match [height*width (" + height * width + ")]"); - pixels = values; - setNeedToRegenerate(true); - } - - /** - * Return the pixels used for the image. - * - * @return the integer array of ints used as integer colors for each pixel - * of the image. - */ - public int[] getPixels() { - return pixels; - } - - /** - * Change the x attribute, which matters only if the render type is - * RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @param value the x location in pixels. - */ - public void setX(int value) { - if (x == value) - return; - x = value; - setNeedToReposition(true); - } - - /** - * Returns the x attribute. - * - * @return the x value, pixels from left of window or image origin. - */ - public int getX() { - return x; - } - - /** - * Change the y attribute, which matters only if the render type is - * RENDERTYPE_XY or RENDERTYPE_OFFSET. - * - * @param value the y location in pixels - */ - public void setY(int value) { - if (y == value) - return; - y = value; - setNeedToReposition(true); - } - - /** - * Return the y attribute. - * - * @return the y value, pixels from top or image origin. - */ - public int getY() { - return y; - } - - /** - * Return the map location of the image, after generation. - * - * @return Point, null if not projected yet. - */ - public Point getMapLocation() { - return point1; - } - - /** - * Change the latitude attribute, which matters only if the render type is - * RENDERTYPE_LATLON or RENDERTYPE_OFFSET. - * - * @param value latitude in decimal degrees. - */ - public void setLat(double value) { - if (lat == value) - return; - lat = value; - setNeedToReposition(true); - } - - /** - * Get the latitude. - * - * @return the latitude in decimal degrees. - */ - public double getLat() { - return lat; - } - - /** - * Change the longitude attribute, which matters only if the render type is - * RENDERTYPE_LATLON or RENDERTYPE_OFFSET. - * - * @param value the longitude in decimal degrees. - */ - public void setLon(double value) { - if (lon == value) - return; - lon = value; - setNeedToReposition(true); - } - - /** - * Get the longitude. - * - * @return longitude in decimal degrees. - */ - public double getLon() { - return lon; - } - - /** - * Set the height of the image, in pixels. - * - * @param value height in pixels. - */ - public void setHeight(int value) { - if (height == value) - return; - setNeedToRegenerate(true); - height = value; - } - - /** - * Get the height of image. - * - * @return height in pixels. - */ - public int getHeight() { - return height; - } - - /** - * Get the height of image after a filter was applied. - * - * @return filteredHeight in pixels. - */ - public int getFilteredHeight() { - return filteredHeight; - } - - /** - * Set width of image. - * - * @param value width in pixels. - */ - public void setWidth(int value) { - if (width == value) - return; - setNeedToRegenerate(true); - width = value; - } - - /** - * Get width of image. - * - * @return width of image in pixels. - */ - public int getWidth() { - return width; - } - - /** - * Get width of image, after a filter is applied. - * - * @return filteredWidth of image in pixels. - */ - public int getFilteredWidth() { - return filteredWidth; - } - - /** - * Set the bytes used to create the pixels used to create the image. Used - * for indexed color model images in OMRaster, and OMBitmaps. - * - * @param values byte values - */ - public void setBits(byte[] values) { - setNeedToRegenerate(true); - bits = values; - } - - /** - * Get the byte values for indexed color model images and OMBitmaps. - * - * @return the bytes used to create the pixels. - */ - public byte[] getBits() { - return bits; - } - - /** - * Set a filter to be used on the constructed image. Applied at generate(). - * - * @param filter Image filter to apply to constructed raster. - */ - public void setImageFilter(ImageFilter filter) { - imageFilter = filter; - filteredWidth = width; - filteredHeight = height; - - setNeedToRegenerate(true); - } - - /** - * Return the image filter used on the image. - * - * @return imagefilter, null if one wasn't set. - */ - public ImageFilter getImageFilter() { - return imageFilter; - } - - /** - * Convenience function to scale the Image to the xy size. Sets the - * imageFilter to a ReplicateScaleFilter or AreaAveragingScaleFilter, - * depending on the algorithm type. - * - * @param w width to scale to, in pixels - * @param h height to scale to, in pixels - * @param algorithmType OMRasterObject parameter describing which scaling - * algorithm to use. - */ - public void scaleTo(int w, int h, int algorithmType) { - filteredWidth = w; - filteredHeight = h; - - imageFilter = new TrimScaleFilter(filteredWidth, filteredHeight, algorithmType); - setNeedToRegenerate(true); - } - - /** - * A method used to manipulate the image according to the parameters set by - * the imageFilter in the OMRasterObject. Called from generate() if the - * filteredWidth and filteredHeight differ from width and height. - * - * @param image the Image to filter - * @return the filtered image. - */ - protected Image filterImage(Image image) { - - // Can we do a little clipping here?? If it's been projected, - // maybe. - - // See if the frame is getting blown up, probably by at - // least a certain margin, so we know that there will be time - // savings as well as memory savings. - - java.awt.image.ImageFilter iImageFilter = imageFilter; - - if (iImageFilter instanceof TrimScaleFilter) { - TrimScaleFilter tf = (TrimScaleFilter) iImageFilter; - Image img = tf.trimExcessPixels(); - - if (img != null) { - image = img; - iImageFilter = tf.getFilterWithChanges(); - // we can play around with point1, since that is where - // the - // image is getting laid out. If point1.x or point1.y - // < 0, we - // can set it to zero. Assumes that the image has - // already - // been positioned. - if (point1.x < 0) - point1.x = 0; - if (point1.y < 0) - point1.y = 0; - - if (DEBUG) { - logger.fine("OMRasterObject: newly located at " + point1); - } - } else if (DEBUG) { - logger.fine("OMRasterObject: not being trimmed due to projection"); - } - } - - if (Toolkit.getDefaultToolkit() != null && image != null && iImageFilter != null) { - ImageProducer prod = new FilteredImageSource(image.getSource(), iImageFilter); - return Toolkit.getDefaultToolkit().createImage(prod); - } - - return image; - } - - /** - * From the Image Observer Interface. Called when the image bits have - * arrived, and therefore calls setImage() to reset all the OMRasterObject - * parameters.
- * Don't call this method! - */ - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - - if ((infoflags & ImageObserver.ALLBITS) != 0) { - if (colorModel == COLORMODEL_IMAGEICON) { - setImage(img); - } - } - if ((infoflags & ImageObserver.WIDTH) != 0) { - this.width = width; - } - if ((infoflags & ImageObserver.HEIGHT) != 0) { - this.height = height; - } - return !(this.bitmap != null && this.width > 0 && this.height > 0); - } - - /** - * This is an effort to create an scaling ImageFilter that will trim off the - * unused pixels, lessoning the load on the display server. It depends on - * knowing several things about the projection and the current image - * parameters, which is why it's not a stand-alone filter class. - */ - protected class TrimScaleFilter extends AreaAveragingScaleFilter { - ImageFilter actualFilter = null; - int algorithmType; - - /** - * Constructs an TrimScaleFilter that scales the pixels from its source - * Image as specified by the width and height parameters. - * - * @param width the target width to scale the image - * @param height the target height to scale the image - */ - public TrimScaleFilter(int width, int height) { - super(width, height); - algorithmType = FAST_SCALING; - } - - /** - * Constructs an AreaAveragingScaleFilter that scales the pixels from - * its source Image as specified by the width and height parameters. - * - * @param width the target width to scale the image - * @param height the target height to scale the image - * @param algorithmType FAST_SCALING or SMOOTH_SCALING - FAST is much - * faster! - */ - protected TrimScaleFilter(int width, int height, int algorithmType) { - super(width, height); - this.algorithmType = algorithmType; - } - - /** - * Detect if the data is being delivered with the necessary hints to - * allow the averaging algorithm to do its work. If the algorithmType is - * set to FAST, I manipulate the hints to force the filter to act like a - * ReplicateScaleFilter. - * - * @see ImageConsumer#setHints - */ - public void setHints(int hints) { - int passthrough = hints; - if (algorithmType == FAST_SCALING) { - // / XOR - passthrough = hints ^ ImageConsumer.TOPDOWNLEFTRIGHT; - } - super.setHints(passthrough); - } - - /** - * The filter must change if the requested image size changes because of - * clipping. Get the good filter here, after calling trimExcessPixels(). - */ - protected ImageFilter getFilterWithChanges() { - if (actualFilter == null) { - return this; - } - return actualFilter; - } - - /** - * Get a trimmed-down image to expand to the map, that contains all the - * pixels that will be visible after expansion. Returns null if the - * image should be used as is, and the filter as well. - */ - protected Image trimExcessPixels() { - - if (filteredWidth <= width && filteredHeight <= height) { - if (DEBUG) { - logger.fine("TrimScaleFilter.trimExcessPixels(): image not enlarged, using entire image."); - } - return null; - } - - if (DEBUG) { - logger.fine("TrimScaleFilter.trimExcessPixels(): clipping enlarged image."); - } - - // Figure out the pixels of the old image being used in - // the new image. Figure out the proj location of the - // upper - // left pixel of the new image. We want to substitute this - // proj location for the projection location already - // calculated. This should get overwritten later for any - // projection changes. - float widthScale = (float) filteredWidth / (float) width; - float heightScale = (float) filteredHeight / (float) height; - - int startXPixelInSource = point1.x < 0 ? (int) ((-1.0 * point1.x) / widthScale) : 0; - int startYPixelInSource = point1.y < 0 ? (int) ((-1 * point1.y) / heightScale) : 0; - Point scaledDim = new Point((int) (point1.x + (width * widthScale)), (int) (point1.y + (height * heightScale))); - int endXPixelInSource = (scaledDim.x > projWidth ? (int) ((projWidth - point1.x) / widthScale) + 1 - : width); - int endYPixelInSource = scaledDim.y > projHeight ? (int) ((projHeight - point1.y) / heightScale) + 1 - : height; - - if (DEBUG) { - logger.fine("TrimScaleFilter.trimExcessPixels(): image contributes " - + startXPixelInSource + ", " + startYPixelInSource + " to " - + endXPixelInSource + ", " + endYPixelInSource); - } - - // Create a buffered image out of the old image, clipping - // out the unused pixels. - - if (DEBUG) { - logger.fine("TrimScaleFilter.trimExcessPixels(): " - + " new dimensions of scaled image " - + (int) ((endXPixelInSource - startXPixelInSource) * widthScale) + ", " - + (int) ((endYPixelInSource - startYPixelInSource) * heightScale)); - } - - // Get only the pixels you need. - // Use a pixel grabber to get the right pixels. - PixelGrabber pg = new PixelGrabber(bitmap, startXPixelInSource, startYPixelInSource, endXPixelInSource - - startXPixelInSource, endYPixelInSource - startYPixelInSource, true); - int[] pix = ImageHelper.grabPixels(pg); - if (pix == null) { - return null; - } - - // Set the filter to the dimensions. Need to remember to - // ask for this!!! - actualFilter = new TrimScaleFilter((int) ((endXPixelInSource - startXPixelInSource) * widthScale), (int) ((endYPixelInSource - startYPixelInSource) * heightScale), algorithmType); - - // create the new bitmap, which holds the image that gets - // drawn - Toolkit tk = Toolkit.getDefaultToolkit(); - Image image = tk.createImage(new MemoryImageSource(endXPixelInSource - - startXPixelInSource, endYPixelInSource - startYPixelInSource, pix, 0, endXPixelInSource - - startXPixelInSource)); - return image; - } - } - - /** - * Code derived from - * http://www.dcs.shef.ac.uk/~tom/Java/Power/image_serialization.html - */ - private void writeObject(ObjectOutputStream objectstream) throws IOException { - - // write non-transient, non-static data - objectstream.defaultWriteObject(); - PixelGrabber grabber = new PixelGrabber(bitmap, 0, 0, -1, -1, true); - - if (colorModel == COLORMODEL_IMAGEICON && bitmap != null) { - try { - grabber.grabPixels(); - } catch (InterruptedException e) { - logger.fine("error grabbing pixels"); - } - - Object pix = grabber.getPixels(); - Dimension dim = new Dimension(bitmap.getWidth(this), bitmap.getHeight(this)); - objectstream.writeObject(dim); - objectstream.writeObject(pix); - } - } - - /** - * Code derived from - * http://www.dcs.shef.ac.uk/~tom/Java/Power/image_serialization.html - */ - private void readObject(ObjectInputStream objectstream) - throws IOException, ClassNotFoundException { - - Toolkit toolkit = Toolkit.getDefaultToolkit(); - try { - // read non-transient, non-static data - objectstream.defaultReadObject(); - - if (colorModel == COLORMODEL_IMAGEICON) { - Dimension dim = (Dimension) objectstream.readObject(); - Object img = objectstream.readObject(); - int[] pix = (int[]) img; - bitmap = toolkit.createImage(new MemoryImageSource(dim.width, dim.height, pix, 0, dim.width)); - setImage(bitmap); - } - - } catch (ClassNotFoundException ce) { - System.out.println("class not found"); - } - } - - public boolean hasLineTypeChoice() { - return false; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMRasterObject) { - OMRasterObject rasterO = (OMRasterObject) source; - this.colorModel = rasterO.colorModel; - this.pixels = DeepCopyUtil.deepCopy(rasterO.pixels); - this.x = rasterO.x; - this.y = rasterO.y; - this.lat = rasterO.lat; - this.lon = rasterO.lon; - this.width = rasterO.width; - this.height = rasterO.height; - this.bits = DeepCopyUtil.deepCopy(rasterO.bits); - this.filteredWidth = rasterO.filteredWidth; - this.filteredHeight = rasterO.filteredHeight; - this.rotationAngle = rasterO.rotationAngle; - // OKOK, again, not a deep copy. - this.imageFilter = rasterO.imageFilter; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRect.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRect.java deleted file mode 100644 index 785787c67..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMRect.java +++ /dev/null @@ -1,420 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMRect.java,v $ -// $RCSfile: OMRect.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Point; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Graphic type that lets you draw four-sided polygons that have corners that - * share coordinates or window points. - *

- *

NOTE:

- * See the - * RESTRICTIONS on Lat/Lon polygons/polylines which apply to rectangles as - * well. Not following the guidelines listed may result in ambiguous/undefined - * shapes! Similar assumptions apply to the other vector graphics that we - * define: circles, ellipses, polys, lines. - *

- * These assumptions are virtually the same as those on the more generic OMPoly - * graphic type. - *

- * - * @see OMPoly - * - */ -public class OMRect extends OMGraphicAdapter implements OMGraphic { - - /** - * Horizontal window position of first corner, in pixels from left side of - * window. - */ - protected int x1 = 0; - /** - * Vertical window position of first corner, in pixels from the top of the - * window. - */ - protected int y1 = 0; - /** Latitude of first corner, decimal degrees. */ - protected double lat1 = 0.0f; - /** Longitude of first corner, decimal degrees. */ - protected double lon1 = 0.0f; - /** - * Horizontal window position of second corner, in pixels from left side of - * window. - */ - protected int x2 = 0; - /** - * Vertical window position of second corner, in pixels from the top of the - * window. - */ - protected int y2 = 0; - /** Latitude of second corner, decimal degrees. */ - protected double lat2 = 0.0f; - /** Longitude of second corner, decimal degrees. */ - protected double lon2 = 0.0f; - - /** - * Number of segments to draw (used only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB lines). - */ - protected int nsegs = -1; - - /** Default constructor, waiting to be filled. */ - public OMRect() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Create a lat/lon rectangle. - * - * @param lt1 latitude of north edge, decimal degrees. - * @param ln1 longitude of west edge, decimal degrees. - * @param lt2 latitude of south edge, decimal degrees. - * @param ln2 longitude of east edge, decimal degrees. - * @param lType line type - see OMGraphic.lineType. - */ - public OMRect(double lt1, double ln1, double lt2, double ln2, int lType) { - this(lt1, ln1, lt2, ln2, lType, -1); - } - - /** - * Create a lat/lon rectangle. - * - * @param lt1 latitude of north edge, decimal degrees. - * @param ln1 longitude of west edge, decimal degrees. - * @param lt2 latitude of south edge, decimal degrees. - * @param ln2 longitude of east edge, decimal degrees. - * @param lType line type - see OMGraphic.lineType. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is generated - * internally) - */ - public OMRect(double lt1, double ln1, double lt2, double ln2, int lType, int nsegs) { - super(RENDERTYPE_LATLON, lType, DECLUTTERTYPE_NONE); - lat1 = lt1; - lon1 = ln1; - lat2 = lt2; - lon2 = ln2; - this.nsegs = nsegs; - } - - /** - * Construct an XY rectangle. It doesn't matter which corners of the - * rectangle are used, as long as they are opposite from each other. - * - * @param px1 x pixel position of the first corner relative to the window - * origin - * @param py1 y pixel position of the first corner relative to the window - * origin - * @param px2 x pixel position of the second corner relative to the window - * origin - * @param py2 y pixel position of the second corner relative to the window - * origin - */ - public OMRect(int px1, int py1, int px2, int py2) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - x1 = px1; - y1 = py1; - x2 = px2; - y2 = py2; - } - - /** - * Construct an XY rectangle relative to a lat/lon point - * (RENDERTYPE_OFFSET). It doesn't matter which corners of the rectangle are - * used, as long as they are opposite from each other. - * - * @param lt1 latitude of the reference point, decimal degrees. - * @param ln1 longitude of the reference point, decimal degrees. - * @param px1 x pixel position of the first corner relative to the reference - * point - * @param py1 y pixel position of the first corner relative to the reference - * point - * @param px2 x pixel position of the second corner relative to the - * reference point - * @param py2 y pixel position of the second corner relative to the - * reference point - */ - public OMRect(double lt1, double ln1, int px1, int py1, int px2, int py2) { - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - lat1 = lt1; - lon1 = ln1; - x1 = px1; - y1 = py1; - x2 = px2; - y2 = py2; - } - - /** - * Set a lat/lon rectangle. - * - * @param lt1 latitude of north edge, decimal degrees. - * @param ln1 longitude of west edge, decimal degrees. - * @param lt2 latitude of south edge, decimal degrees. - * @param ln2 longitude of east edge, decimal degrees. - * @param lType line type - see OMGraphic.lineType. - */ - public void setLocation(double lt1, double ln1, double lt2, double ln2, int lType) { - setRenderType(RENDERTYPE_LATLON); - setLineType(lType); - lat1 = lt1; - lon1 = ln1; - lat2 = lt2; - lon2 = ln2; - setNeedToRegenerate(true); - } - - /** - * Set an XY rectangle. It doesn't matter which corners of the rectangle are - * used, as long as they are opposite from each other. - * - * @param px1 x pixel position of the first corner relative to the window - * origin - * @param py1 y pixel position of the first corner relative to the window - * origin - * @param px2 x pixel position of the second corner relative to the window - * origin - * @param py2 y pixel position of the second corner relative to the window - * origin - */ - public void setLocation(int px1, int py1, int px2, int py2) { - setRenderType(RENDERTYPE_XY); - setLineType(LINETYPE_UNKNOWN); - x1 = Math.min(px1, px2); - y1 = Math.min(py1, py2); - x2 = Math.max(px1, px2); - y2 = Math.max(py1, py2); - setNeedToRegenerate(true); - } - - /** - * Set an XY rectangle relative to a lat/lon point (RENDERTYPE_OFFSET). It - * doesn't matter which corners of the rectangle are used, as long as they - * are opposite from each other. - * - * @param lt1 latitude of the reference point, decimal degrees. - * @param ln1 longitude of the reference point, decimal degrees. - * @param px1 x pixel position of the first corner relative to the reference - * point - * @param py1 y pixel position of the first corner relative to the reference - * point - * @param px2 x pixel position of the second corner relative to the - * reference point - * @param py2 y pixel position of the second corner relative to the - * reference point - */ - public void setLocation(double lt1, double ln1, int px1, int py1, int px2, int py2) { - setRenderType(RENDERTYPE_OFFSET); - setLineType(LINETYPE_UNKNOWN); - lat1 = lt1; - lon1 = ln1; - x1 = px1; - y1 = py1; - x2 = px2; - y2 = py2; - setNeedToRegenerate(true); - } - - /** - * Get the latitude of the north edge in a LatLon rectangle. It also happens - * to be the latitude of the offset point. - * - * @return float latitude - */ - public double getNorthLat() { - return lat1; - } - - /** - * Get the longitude of the west edge in a LatLon rectangle. It also happens - * to be the longitude of the offset point. - * - * @return float longitude - */ - public double getWestLon() { - return lon1; - } - - /** - * Get the latitude of the south edge in a LatLon rectangle. - * - * @return float latitude - */ - public double getSouthLat() { - return lat2; - } - - /** - * Get the longitude of the east edge in a LatLon rectangle. - * - * @return float longitude - */ - public double getEastLon() { - return lon2; - } - - /** - * Get the top of XY rectangle. - * - * @return int - */ - public int getTop() { - return y1; - } - - /** - * Get the left of XY rectangle. - * - * @return int - */ - public int getLeft() { - return x1; - } - - /** - * Get the bottom of XY rectangle. - * - * @return int - */ - public int getBottom() { - return y2; - } - - /** - * Get the right of XY rectangle. - * - * @return int - */ - public int getRight() { - return x2; - } - - /** - * Set the number of segments of the lat/lon lines. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, and if < 1, this - * value is generated internally). - * - * @param nsegs number of segment points - */ - public void setNumSegs(int nsegs) { - this.nsegs = nsegs; - } - - /** - * Get the number of segments of the lat/lon lines. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types). - * - * @return int number of segment points - */ - public int getNumSegs() { - return nsegs; - } - - /** - * Prepare the rectangle for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMRect: null projection in generate!"); - return false; - } - - // reset the internals - - switch (renderType) { - case RENDERTYPE_XY: - setShape(createBoxShape((int) Math.min(x2, x1), (int) Math.min(y2, y1), (int) Math.abs(x2 - - x1), (int) Math.abs(y2 - y1))); - break; - case RENDERTYPE_OFFSET: - if (!proj.isPlotable(lat1, lon1)) { - setNeedToRegenerate(true);// HMMM not the best flag - return false; - } - Point p1 = (Point) proj.forward(lat1, lon1, new Point()); - - setShape(createBoxShape((int) Math.min(p1.x + x1, p1.x + x2), (int) Math.min(p1.y + y1, p1.y - + y2), (int) Math.abs(x2 - x1), (int) Math.abs(y2 - y1))); - break; - case RENDERTYPE_LATLON: - ArrayList rects; - - if (proj instanceof GeoProj) { - rects = ((GeoProj) proj).forwardRect(new LatLonPoint.Double(lat1, lon1), // NW - new LatLonPoint.Double(lat2, lon2), // SE - lineType, nsegs, !isClear(fillPaint)); - } else { - rects = proj.forwardRect(new Point2D.Double(lon1, lat1), new Point2D.Double(lon2, lat2)); - } - int size = rects.size(); - GeneralPath projectedShape = null; - for (int i = 0; i < size; i += 2) { - GeneralPath gp = createShape(rects.get(i), rects.get(i + 1), true); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - setShape(projectedShape); - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMRect.generate(): invalid RenderType"); - return false; - } - - setLabelLocation(getShape(), proj); - - setNeedToRegenerate(false); - return true; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMRect) { - OMRect rect = (OMRect) source; - this.x1 = rect.x1; - this.y1 = rect.y1; - this.lat1 = rect.lat1; - this.lon1 = rect.lon1; - this.x2 = rect.x2; - this.y2 = rect.y2; - this.lat2 = rect.lat2; - this.lon2 = rect.lon2; - this.nsegs = rect.nsegs; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingIcon.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingIcon.java deleted file mode 100644 index 3ae5df1f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingIcon.java +++ /dev/null @@ -1,424 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMScalingIcon.java,v $ -// $RCSfile: OMScalingIcon.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.image.AffineTransformOp; -import java.awt.image.BufferedImage; -import java.io.Serializable; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * This is an extension to OMScalingRaster that scales an icon. The icon is - * automatically centered over the lat/lon location. The offsets push the icon - * away from the lat/lon. - * - * @see OMScalingRaster - */ -public class OMScalingIcon extends OMScalingRaster implements Serializable { - - protected float baseScale; - protected float maxScale = Float.MAX_VALUE; - protected float minScale = 0f; - - /** - * Shortcut flag for position/scaleTo/rendering for images that don't need - * scaling. Preserves rendering quality. - */ - protected boolean noScalingRequired = false; - - /** - * Construct a blank OMRaster, to be filled in with set calls. - */ - public OMScalingIcon() { - super(); - } - - // /////////////////////////////////// INT PIXELS - DIRECT - // COLORMODEL - - /** - * Creates an OMRaster images, Lat/Lon placement with a direct colormodel - * image. - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param offsetX horizontal pixel offset of icon (positive pushes east). - * @param offsetY vertical pixel offset of icon (positive pushes south). - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @param baseScale the scale where the icon will be show regular size. - * @see #setPixel - */ - public OMScalingIcon(double centerLat, double centerLon, int offsetX, int offsetY, int w, - int h, int[] pix, float baseScale) { - - super(centerLat, centerLon, 0f, 0f, w, h, pix); - setX(offsetX); - setY(offsetY); - this.baseScale = baseScale; - } - - // //////////////////////////////////// IMAGEICON - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param offsetX horizontal pixel offset of icon (positive pushes east). - * @param offsetY vertical pixel offset of icon (positive pushes south). - * @param ii ImageIcon used for the image. - * @param baseScale the scale where the icon will be show regular size. - */ - public OMScalingIcon(double centerLat, double centerLon, int offsetX, int offsetY, - ImageIcon ii, float baseScale) { - this(centerLat, centerLon, offsetX, offsetY, ii.getImage(), baseScale); - } - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. Doesn't scale, - * because baseScale, minScale and maxScale are all set to the same number - * (4000000). - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param ii ImageIcon used for the image. - */ - public OMScalingIcon(double centerLat, double centerLon, ImageIcon ii) { - this(centerLat, centerLon, ii.getImage()); - } - - /** - * Create an OMRaster, Lat/Lon placement with an Image. - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param offsetX horizontal pixel offset of icon (positive pushes east). - * @param offsetY vertical pixel offset of icon (positive pushes south). - * @param ii Image used for the image. - * @param baseScale the scale where the icon will be show regular size. - */ - public OMScalingIcon(double centerLat, double centerLon, int offsetX, int offsetY, Image ii, - float baseScale) { - super(); - setRenderType(OMGraphic.RENDERTYPE_LATLON); - setColorModel(COLORMODEL_IMAGEICON); - - lat = centerLat; - lon = centerLon; - setImage(ii); - setX(offsetX); - setY(offsetY); - this.baseScale = baseScale; - } - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. Doesn't scale, - * because baseScale, minScale and maxScale are all set to the same number - * (4000000). - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param image ImageIcon used for the image. - */ - public OMScalingIcon(double centerLat, double centerLon, Image image) { - this(centerLat, centerLon, 0, 0, image, 4000000); - setMaxScale(4000000); - setMinScale(4000000); - } - - // //////////////////////////////////// BYTE PIXELS with - // COLORTABLE - - /** - * Lat/Lon placement with a indexed colormodel, which is using a colortable - * and a byte array to construct the int[] pixels. - * - * @param centerLat latitude of the top of the image. - * @param centerLon longitude of the left side of the image. - * @param offsetX horizontal pixel offset of icon (positive pushes east). - * @param offsetY vertical pixel offset of icon (positive pushes south). - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @param baseScale the scale where the icon will be show regular size. - * @see #setPixel - */ - public OMScalingIcon(float centerLat, float centerLon, int offsetX, int offsetY, int w, int h, - byte[] bytes, Color[] colorTable, int trans, float baseScale) { - - super(centerLat, centerLon, 0f, 0f, w, h, bytes, colorTable, trans); - setX(offsetX); - setY(offsetY); - this.baseScale = baseScale; - } - - /** - * Since the image doesn't necessarily need to be regenerated when it is - * merely moved, raster objects have this function, called from generate() - * and when a placement attribute is changed. - * - * @return true if enough information is in the object for proper placement. - * @param proj projection of window. - */ - protected boolean position(Projection proj) { - - if (proj == null) { - Debug.error("OMScalingIcon: null projection in position!"); - return false; - } - - if (bitmap == null) { - // Debug.error("OMScalingIcon: null sourceImage in position!"); - // XXX: For now fail silently. - return false; - } - - float shrinkScale = proj.getScale(); - - if (shrinkScale > maxScale) { - shrinkScale = maxScale; - } - if (shrinkScale < minScale) { - shrinkScale = minScale; - } - - noScalingRequired = baseScale == shrinkScale; - - float scaleFactor = baseScale / shrinkScale; - - point1 = (Point) proj.forward(lat, lon, new Point()); - point2 = (Point) proj.forward(lat, lon, new Point()); - - int halfImageWidth = width / 2; - int halfImageHeight = height / 2; - // Mindful of pixel offset icons - int myX = getX(); - int myY = getY(); - - double p1x = point1.getX(); - double p1y = point1.getY(); - double newP1x = p1x + (scaleFactor * (myX - halfImageWidth)); - double newP1y = p1y + (scaleFactor * (myY - halfImageHeight)); - point1.setLocation((int) newP1x, (int) newP1y); - - double p2x = point2.getX(); - double p2y = point2.getY(); - double newP2x = p2x + (scaleFactor * (myX + halfImageWidth)); - double newP2y = p2y + (scaleFactor * (myY + halfImageHeight)); - point2.setLocation((int) newP2x, (int) newP2y); - - setNeedToReposition(false); - return true; - } - - public boolean isOnMap(Projection proj) { - generate(proj); // Should only generate if needed... - - Shape shape = getShape(); - if (shape == null) { - return false; - } - - Point2D p1 = proj.forward(proj.getUpperLeft()); - Point2D p2 = proj.forward(proj.getLowerRight()); - int h = (int) (p2.getY() - p1.getY()); - int w = (int) (p2.getX() - p1.getX()); - - Rectangle mapRect = new Rectangle((int) p1.getX(), (int) p1.getY(), w, h); - - return mapRect.intersects(shape.getBounds()); - } - - /** - * Over-riding this so we don't clip rotated icons near the edge of the map. - * Just display icons as whole. - */ - protected void scaleTo(Projection thisProj) { - - if (DEBUG) { - logger.fine("OMScalingRaster: scaleTo()"); - } - - if (bitmap == null) { - if (DEBUG) { - logger.fine("scaleTo() source image is null"); - } - return; - } - - if (noScalingRequired) { - return; - } - - // Get image projection rectangle - Rectangle projRect = new Rectangle(); - projRect.setLocation(point1); - projRect.setSize(point2.x - point1.x, point2.y - point1.y); - - Rectangle sourceRect = new Rectangle(); - sourceRect.width = width; - sourceRect.height = height; - - // Now we have everything we need to sort out this new projection. - // boolean currentVisibility = isVisible(); - clipRect = null; - - if (!projRect.isEmpty()) { - - // Assume will need whole image, set the clipRect so it's - // on the map, somewhere. - - // If big enough to see - if ((projRect.width >= 1) && (projRect.height >= 1)) { - - // check width and height of clipRect, in case it got - // rounded down to zero. - if (sourceRect.width <= 0) { - sourceRect.width = 1; - } - if (sourceRect.height <= 0) { - sourceRect.height = 1; - } - // Now we can grab the bit we want out of the source - // and scale it to fit the intersection. - - // Calc width adjustment - double widthAdj = (double) projRect.width / (double) sourceRect.width; - // Calc height adjustment - double heightAdj = (double) projRect.height / (double) sourceRect.height; - // Create the transform - AffineTransform xform = new AffineTransform(); - // Specify scaling - xform.setToScale(widthAdj, heightAdj); - - // Create the transform op. - this.scalingXFormOp = new AffineTransformOp(xform, getScaleTransformType()); - } - } - } - - /** - * Render the image at the given pixel location. This method should be - * overridden for special Image handling. - * - * @param g the Graphics object to render the image into. Assumes this is a - * derivative of the Graphics passed into the OMGraphic, and can be - * modified without worrying about passing settings on to other - * OMGraphics. - * @param image the image to render. - * @param loc the pixel location of the image. - */ - protected void renderImage(Graphics g, Image image, Point loc) { - - if (image != null) { - - if (DEBUG) { - logger.fine("drawing icon image at " + loc.x + ", " + loc.y); - } - - if (noScalingRequired) { - g.drawImage(image, loc.x, loc.y, null); - return; - } - - if (g instanceof Graphics2D) { - if (image instanceof BufferedImage) { - ((Graphics2D) g).drawImage((BufferedImage) image, scalingXFormOp, loc.x, loc.y); - } else { - - int dx1 = loc.x; - int dy1 = loc.y; - int dx2 = point2.x; - int dy2 = point2.y; - - ((Graphics2D) g).drawImage(image, dx1, dy1, dx2, dy2, 0, 0, width, height, this); - } - } // else what? Never seen this test fail with Java2D - - } else if (DEBUG) { - logger.fine("ignoring null bitmap image"); - } - } - - public void setBaseScale(float bs) { - baseScale = bs; - } - - public float getBaseScale() { - return baseScale; - } - - /** - * Set the scale that limits how small an icon will shrink. Should be a - * number larger than the base scale. If the map scale gets larger than this - * number, the icon will stop shrinking. - */ - public void setMaxScale(float ms) { - maxScale = ms; - } - - public float getMaxScale() { - return maxScale; - } - - /** - * Set the scale that limits how big an icon should grow. Should be a number - * smaller than the base scale. If the map scale gets smaller than this - * number, the icon will stop growing. - */ - public void setMinScale(float ms) { - minScale = ms; - } - - public float getMinScale() { - return minScale; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMScalingIcon) { - OMScalingIcon icon = (OMScalingIcon) source; - this.baseScale = icon.baseScale; - this.maxScale = icon.maxScale; - this.minScale = icon.minScale; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingRaster.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingRaster.java deleted file mode 100644 index b54023c7c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMScalingRaster.java +++ /dev/null @@ -1,821 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMScalingRaster.java,v $ -// $RCSfile: OMScalingRaster.java,v $ -// $Revision: 1.16 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.awt.image.AffineTransformOp; -import java.awt.image.BufferedImage; -import java.io.Serializable; -import java.util.ArrayList; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.util.ImageWarp; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.DataBounds; - -/** - * This is an extension to OMRaster that automatically scales itelf to match the - * current projection. It is only lat/lon based, and takes the coordinates of - * the upper left and lower right corners of the image. It does straight scaling - * - it does not force the image projection to match the map projection! So, - * your mileage may vary - you have to understand the projection of the image, - * and know how it fits the projection type of the map. Of course, at larger - * scales, it might not matter so much. - * - * This class was inspired by, and created from parts of the ImageLayer - * submission from Adrian Lumsden@sss, on 25-Jan-2002. Used the scaling and - * trimming code from that submission. That code was also developed with - * assistance from Steve McDonald at SiliconSpaceships.com. - * - * @see OMRaster - * @see OMRasterObject - */ -public class OMScalingRaster extends OMRaster implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * The latitude of the lower right corner for the image, in decimal degrees. - */ - protected double lat2 = 0.0f; - - /** - * The longitude of the lower right corner for the image, in decimal - * degrees. - */ - protected double lon2 = 0.0f; - - /** - * AffineTransformOp applied to the bitmap at render time. - */ - protected AffineTransformOp scalingXFormOp; - /** - * The rectangle in screen coordinates that the scaled image projects to - * after clipping. - */ - protected transient Rectangle clipRect; - - protected transient ArrayList corners; - - /** - * Transform type for AffineTransformOp to use to scale images. - */ - protected int scaleTransformType = AffineTransformOp.TYPE_BILINEAR; - - /** - * This lastProjection is used to keep track of the last projection used to - * warp or scale the image, an used during the rendering process to check if - * we should rework the image to be displayed. - */ - protected Projection lastProjection = null; - - /** - * Construct a blank OMRaster, to be filled in with set calls. - */ - public OMScalingRaster() { - super(); - } - - // /////////////////////////////////// INT PIXELS - DIRECT - // COLORMODEL - - /** - * Creates an OMRaster images, Lat/Lon placement with a direct colormodel - * image. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - */ - public OMScalingRaster(double ullat, double ullon, double lrlat, double lrlon, int w, int h, - int[] pix) { - - super(ullat, ullon, w, h, pix); - lat2 = lrlat; - lon2 = lrlon; - } - - // //////////////////////////////////// IMAGEICON - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param ii ImageIcon used for the image. - */ - public OMScalingRaster(double ullat, double ullon, double lrlat, double lrlon, ImageIcon ii) { - this(ullat, ullon, lrlat, lrlon, ii.getImage()); - } - - /** - * Create an OMRaster, Lat/Lon placement with an Image. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param ii Image used for the image. - */ - public OMScalingRaster(double ullat, double ullon, double lrlat, double lrlon, Image ii) { - super(); - setRenderType(OMGraphic.RENDERTYPE_LATLON); - setColorModel(COLORMODEL_IMAGEICON); - - lat = ullat; - lon = ullon; - lat2 = lrlat; - lon2 = lrlon; - setImage(ii); - } - - // //////////////////////////////////// BYTE PIXELS with - // COLORTABLE - - /** - * Lat/Lon placement with a indexed colormodel, which is using a colortable - * and a byte array to construct the int[] pixels. - * - * @param ullat latitude of the top of the image. - * @param ullon longitude of the left side of the image. - * @param lrlat latitude of the bottom of the image. - * @param lrlon longitude of the right side of the image. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - */ - public OMScalingRaster(double ullat, double ullon, double lrlat, double lrlon, int w, int h, - byte[] bytes, Color[] colorTable, int trans) { - - super(ullat, ullon, w, h, bytes, colorTable, trans); - lat2 = lrlat; - lon2 = lrlon; - } - - /** - * Since the image doesn't necessarily need to be regenerated when it is - * merely moved, raster objects have this function, called from generate() - * and when a placement attribute is changed. - * - * @return true if enough information is in the object for proper placement. - * @param proj projection of window. - */ - protected boolean position(Projection proj) { - - if (proj == null) { - if (DEBUG) { - logger.fine("OMScalingRaster: null projection in position!"); - } - return false; - } - - point1 = (Point) proj.forward(lat, lon, new Point()); - point2 = (Point) proj.forward(lat2, lon2, new Point()); - - corners = null; - - if (point1.x > point2.x) { - - double[] coords = new double[] { lat, lon, lat, lon2, lat2, lon2, lat2, lon, lat, lon }; - - if (proj instanceof GeoProj) { - corners = ((GeoProj) proj).forwardPoly(ProjMath.arrayDegToRad(coords), OMGraphic.LINETYPE_STRAIGHT, -1, true); - } else { - corners = proj.forwardPoly(coords, true); - } - - if (corners != null && corners.size() > 2) { - float[] xs = corners.get(0); - float[] ys = corners.get(1); - point1.setLocation(xs[0], ys[0]); - point2.setLocation(xs[2], ys[2]); - } - } - - setNeedToReposition(false); - return true; - } - - /** - * Prepare the graphics for rendering. For all image types, it positions the - * image relative to the projection. For direct and indexed colormodel - * images, it creates the ImageIcon used for drawing to the window (internal - * to object). For indexed colormodel images, it also calls computePixels, - * to resolve the colortable and the bytes to create the image pixels. - * - * @param proj Projection used to position the image on the window. - * @return true if the image is ready to paint. - */ - public boolean generate(Projection proj) { - - if (!updateImageForProjection(proj)) { - - if (getNeedToReposition()) { - position(proj); - setShape(); - } else { - // Nothing changed with image placement, image is ready, we can - // return at this point. - setShape(); - setNeedToRegenerate(false); - return true; - } - } - - setShape(null); - - // Position sets the position for the OMRaster!!!! - if (!position(proj)) { - if (DEBUG) { - logger.fine("OMRaster.generate(): positioning failed!"); - } - return false; - } - - if (colorModel != COLORMODEL_IMAGEICON) { - // If the sourceImage hasn't been created, and needs to - // be, then just do what we normally do in OMRaster. - if (bitmap == null || getNeedToRegenerate()) { - if (DEBUG) { - logger.fine("OMScalingRaster: generating image"); - } - super.generate(proj); - // bitmap is set to a BufferedImage, but this does some other - // stuff, too. - setImage(bitmap); - - // Since we have a source image that is going to be reused, - // let's get rid of the memory that we won't use anymore. - pixels = null; - bits = null; - } - } - - // point1 and point2 are already set in position() - - // We assume that the image doesn't cross the dateline, and - // that p1 is upper left corner, and p2 is lower right. - // scaleTo modifies the internal bitmap image for display. - scaleTo(proj); - - if (bitmap != null) { - if (corners == null) { - GeneralPath projectedShape = createBoxShape(point1.x, point1.y, point2.x - - point1.x, point2.y - point1.y); - int w = bitmap.getWidth(this); - int h = bitmap.getHeight(this); - double anchorX = point1.x + w / 2; - double anchorY = point1.y + h / 2; - setShape(adjustShapeForRotation(projectedShape, anchorX, anchorY)); - } else { - int numRects = corners.size(); - GeneralPath projectedShape = null; - for (int i = 0; i < numRects; i += 2) { - GeneralPath gp = createShape(corners.get(i), corners.get(i + 1), true); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - if (projectedShape != null) { - Rectangle rect = projectedShape.getBounds(); - double anchorX = rect.getX() + rect.getWidth() / 2; - double anchorY = rect.getY() + rect.getHeight() / 2; - projectedShape = adjustShapeForRotation(projectedShape, anchorX, anchorY); - } - - setShape(projectedShape); - } - - setLabelLocation(getShape(), proj); - - setNeedToRegenerate(false); - } else { - // Make the label go away if it is off-screen. - hasLabel = false; - } - return true; - } - - /** - * Called from within generate. Some render buffering calls generate to make - * sure the latest projection is called on an OMGraphic before it's put into - * a buffer. We're keeping track of the last projection used to generate the - * warped image, and if it's the same, don't bother regenerating, use the - * raster we have. This method is a question: do we need to update the image - * because of a projection change? - * - * @param proj current projection. - * @return false if the projection shouldn't cause anything to change for - * the image. - */ - protected boolean updateImageForProjection(Projection proj) { - boolean projUnchanged = proj.equals(lastProjection); - boolean ret = bitmap != null && projUnchanged && !getNeedToRegenerate(); - if (!projUnchanged) { - lastProjection = proj.makeClone(); - } - - evaluateRotationAngle(proj); - return !ret; - } - - /** - * Since the OMScalingRaster changes height and width depending on scale, we - * need to rotate the image over that point and factor in the scaled height - * and width of the image. Called from within OMRasterObject.render(). - * - * @param g Graphics2D object to rotate and translate. - */ - protected void rotate(Graphics2D g) { - Double angle = renderRotationAngle; - if (angle != null) { - int rotOffsetX = point1.x + (point2.x - point1.x) / 2; - int rotOffsetY = point1.y + (point2.y - point1.y) / 2; - g.rotate(angle, rotOffsetX, rotOffsetY); - } - } - - /** - * Take the current projection and the sourceImage, and make the image that - * gets displayed fit the projection. If the source image isn't over the - * map, then this OMGraphic is set to be invisible. If part of the image is - * on the map, only that part is used. The OMRaster bitmap variable is set - * with an image that is created from the source image, and the point1 - * variable is set to the point where the image should be placed. For - * instance, if the source image upper left corner is off the map to the - * NorthWest, then the OMRaster bitmap is set to a image, clipped from the - * source, that is entirely on the map. The OMRaster point1 is set to 0, 0, - * since that is where the clipped image should be placed. - * - * @param thisProj the projection that the image should be scaled to. - */ - protected void scaleTo(Projection thisProj) { - - if (DEBUG) { - logger.fine("starting scaling evaluation."); - } - - if (bitmap == null) { - if (DEBUG) { - logger.fine("source image is null"); - } - return; - } - - // Get the projection window rectangle in pix - Rectangle winRect = new Rectangle(thisProj.getWidth(), thisProj.getHeight()); - // Get image projection rectangle - Rectangle projRect = new Rectangle(); - projRect.setLocation(point1); - projRect.setSize(point2.x - point1.x, point2.y - point1.y); - - Rectangle sourceRect = new Rectangle(); - sourceRect.width = bitmap.getWidth(this); - sourceRect.height = bitmap.getHeight(this); - - // Now we have everything we need to sort out this new projection. - // boolean currentVisibility = isVisible(); - - // Assume we will not see it, in order to see if any part of - // the image will appear on map. If so, then reset visibility to - // what's needed. - // setVisible(false); - clipRect = null; - - Rectangle iRect = projRect; - // <= 2 is limiting this intersection to regular world - small world - // will have multiple rects, corners We don't want to clip the bitmap - // if we have to draw it on different parts of the map window (if it - // wraps). - if (corners == null || corners.size() <= 2) { - iRect = winRect.intersection(projRect); - } - - if (!iRect.isEmpty()) { - // Now we have the visible rectangle of the projected - // image we need to figure out which pixels from the - // source image get scaled to produce it. - - // Assume will need whole image, set the clipRect so it's - // on the map, somewhere. - Rectangle nClipRect = new Rectangle(); - nClipRect.setBounds(sourceRect); - - // If big enough to see - if ((iRect.width >= 1) && (iRect.height >= 1)) { - - // If it didn't all fit - if (!winRect.contains(projRect)) { - // calc X scale factor - double xScaleFactor = (double) sourceRect.width / (double) projRect.width; - // and Y scale factor - double yScaleFactor = (double) sourceRect.height / (double) projRect.height; - // and the x offset - int xOffset = iRect.x - projRect.x; - // the y offset - int yOffset = iRect.y - projRect.y; - // Scale the x position - nClipRect.x = (int) Math.floor(xOffset * xScaleFactor); - // scale the y position - nClipRect.y = (int) Math.floor(yOffset * yScaleFactor); - - // Do Math.ceil because the icon was getting - // clipped a little if it started to move off the - // screen a little. - nClipRect.width = (int) Math.ceil(iRect.width * xScaleFactor); // scale - // the width - nClipRect.height = (int) Math.ceil(iRect.height * yScaleFactor); // scale - // the height - - // Make sure the rounding doesn't exceed the - // original icon bounds - if (nClipRect.width + nClipRect.x > sourceRect.width) { - nClipRect.width = sourceRect.width - nClipRect.x; - } - if (nClipRect.height + nClipRect.y > sourceRect.height) { - nClipRect.height = sourceRect.height - nClipRect.y; - } - } - - // check width and height of clipRect, in case it got - // rounded down to zero. - if (nClipRect.width <= 0) { - nClipRect.width = 1; - } - if (nClipRect.height <= 0) { - nClipRect.height = 1; - } - // Now we can grab the bit we want out of the source - // and scale it to fit the intersection. - - // Calc width adjustment - double widthAdj = (double) iRect.width / (double) nClipRect.width; - // Calc height adjustment - double heightAdj = (double) iRect.height / (double) nClipRect.height; - // Create the transform - AffineTransform xform = new AffineTransform(); - // Specify scaling - xform.setToScale(widthAdj, heightAdj); - clipRect = nClipRect; - - // Create the transform op. - // AffineTransformOp xformOp = new AffineTransformOp(xform, - // AffineTransformOp.TYPE_NEAREST_NEIGHBOR); - this.scalingXFormOp = new AffineTransformOp(xform, getScaleTransformType()); - - point1.setLocation(iRect.x, iRect.y); - point2.setLocation(iRect.x + iRect.width, iRect.y + iRect.height); - } - } - } - - /** - * Render the raster on the java.awt.Graphics. Overrides the raster method - * because it checks to see if the raster is in a small-world situation, - * where the image must wrap around the world. - * - * @param graphics java.awt.Graphics to draw the image on. - */ - public void render(Graphics graphics) { - - if (getNeedToRegenerate() || getNeedToReposition() || !isVisible()) { - return; - } - - boolean smallWorld = bitmap != null && corners != null && corners.size() >= 4; - - if (smallWorld) { - float[] xs = corners.get(2); - float[] ys = corners.get(3); - Point point1 = new Point(); - point1.setLocation((double) xs[0], (double) ys[0]); - Point point2 = new Point(); - point2.setLocation((double) xs[2], (double) ys[2]); - - // copy the graphic, so our transform doesn't cascade to - // others... - Graphics g = graphics.create(); - if (g instanceof Graphics2D && renderRotationAngle != null) { - // rotate about our image center point - rotate((Graphics2D) g); - } - - renderImage(g, bitmap, point1); - } - - // render the location that is always set. - super.render(graphics); - } - - /** - * Render the image at the given pixel location. This method should be - * overridden for special Image handling. - * - * @param g the Graphics object to render the image into. Assumes this is a - * derivative of the Graphics passed into the OMGraphic, and can be - * modified without worrying about passing settings on to other - * OMGraphics. - * @param image the image to render. - * @param loc the pixel location of the image. - */ - protected void renderImage(Graphics g, Image image, Point loc) { - - Rectangle visibleImageArea = getClippedRectangle(); - - if (image != null) { - - if (visibleImageArea != null) { - - if (DEBUG) { - logger.fine("drawing " + visibleImageArea + " image at " + loc.x + ", " - + loc.y); - } - - if (g instanceof Graphics2D) { - if (image instanceof BufferedImage) { - ((Graphics2D) g).drawImage(((BufferedImage) image).getSubimage(visibleImageArea.x, visibleImageArea.y, visibleImageArea.width, visibleImageArea.height), scalingXFormOp, loc.x, loc.y); - } else { - - int sx1 = visibleImageArea.x; - int sy1 = visibleImageArea.y; - int sx2 = sx1 + visibleImageArea.width; - int sy2 = sy1 + visibleImageArea.height; - - int dx1 = loc.x; - int dy1 = loc.y; - Point2D d2 = scalingXFormOp.getPoint2D(new Point2D.Double(dx1 - + visibleImageArea.width, dy1 - + visibleImageArea.height), new Point2D.Double()); - int dx2 = (int) d2.getX(); - int dy2 = (int) d2.getY(); - - ((Graphics2D) g).drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, this); - } - } // else what? Never seen this test fail with Java2D - - } else if (DEBUG) { - logger.fine("visible image area not on the map"); - } - - } else if (DEBUG) { - logger.fine("ignoring null bitmap image"); - } - } - - /** - * Return the rectangle in screen co-ordinates that the scaled image has - * been clipped to. This may return a null rectangle (i.e. the image is out - * of the window). Otherwise the returned rectangle should always at least - * partially lie within the bounds of the window. - */ - public Rectangle getClippedRectangle() { - return clipRect; - } - - /** - * Change the upper latitude attribute. - * - * @param value latitude in decimal degrees. - */ - public void setULLat(double value) { - setLat(value); - } - - /** - * Get the upper latitude. - * - * @return the latitude in decimal degrees. - */ - public double getULLat() { - return getLat(); - } - - /** - * Change the western longitude attribute. - * - * @param value the longitude in decimal degrees. - */ - public void setULLon(double value) { - setLon(value); - } - - /** - * Get the western longitude. - * - * @return longitude in decimal degrees. - */ - public double getULLon() { - return getLon(); - } - - /** - * Change the southern latitude attribute. - * - * @param value latitude in decimal degrees. - */ - public void setLRLat(double value) { - if (lat2 == value) - return; - lat2 = value; - setNeedToReposition(true); - } - - /** - * Get the southern latitude. - * - * @return the latitude in decimal degrees. - */ - public double getLRLat() { - return lat2; - } - - /** - * Change the eastern longitude attribute. - * - * @param value the longitude in decimal degrees. - */ - public void setLRLon(double value) { - if (lon2 == value) - return; - lon2 = value; - setNeedToReposition(true); - } - - /** - * Get the eastern longitude. - * - * @return longitude in decimal degrees. - */ - public double getLRLon() { - return lon2; - } - - /** - * Set the rectangle, based on the location and size of the image after - * scaling. - */ - public void setShape() { - if (point2 != null && point1 != null) { - // generate shape that is a boundary of the generated image. - // We'll make it a GeneralPath rectangle. - int w = point2.x - point1.x; - int h = point2.y - point1.y; - - setShape(createBoxShape(point1.x, point1.y, w, h)); - } - } - - /** - * Test to see if projected image is on map. - * - * @param proj current projection - * @return true of projected image location intersects map area. - */ - public boolean isOnMap(Projection proj) { - Point2D p1 = proj.forward(lat, lon); - Point2D p2 = proj.forward(lat2, lon2); - int h = (int) Math.abs(p2.getY() - p1.getY()); - int w = (int) Math.abs(p2.getX() - p1.getX()); - - Rectangle imageRect = new Rectangle((int) p1.getX(), (int) p1.getY(), w, h); - - proj.forward(proj.getUpperLeft(), p1); - proj.forward(proj.getLowerRight(), p2); - h = (int) Math.abs(p2.getY() - p1.getY()); - w = (int) Math.abs(p2.getX() - p1.getX()); - - Rectangle mapRect = new Rectangle((int) p1.getX(), (int) p1.getY(), w, h); - - return mapRect.intersects(imageRect); - } - - public int getScaleTransformType() { - return scaleTransformType; - } - - /** - * Set the AffineTransformOp used for scaling images. Default is - * AffineTransformOp.TYPE_BILINEAR. Can also be - * AffineTransformOp.TYPE_BICUBIC or - * AffineTransformOp.TYPE_NEAREST_NEIGHBOR. - * - * @param scaleTransformType - */ - public void setScaleTransformType(int scaleTransformType) { - if (scaleTransformType == AffineTransformOp.TYPE_BILINEAR - || scaleTransformType == AffineTransformOp.TYPE_BICUBIC - || scaleTransformType == AffineTransformOp.TYPE_NEAREST_NEIGHBOR) { - this.scaleTransformType = scaleTransformType; - } - } - - /** - * Creates an ImageWarp object from the contents of the OMScalingRaster. - * This can be used in an OMWarpingImage to be used for display in - * projections that don't match the raster's projection. - * - * @param transform the OMScalingImage assumes that the coordinates/pixel - * transformation of the image is equal arc. If it's not, the correct - * transformation should be provided for this query. The - * OMScalingRaster doesn't really know what it is, it just plots the - * corner coordinates and scales the image accordingly. - * @return ImageWarp an ImageWarp if all the required information was - * provided, null if not. - */ - public ImageWarp getImageWarp(GeoCoordTransformation transform) { - ImageWarp imageWarp = null; - - DataBounds imageBounds = new DataBounds(); - imageBounds.add(lon, lat); - imageBounds.add(lon2, lat2); - - if (pixels != null) { - imageWarp = new ImageWarp(pixels, width, height, transform, imageBounds); - } else { - Image image = bitmap; - if (image != null) { - - if (transform == null) { - transform = new LatLonGCT(); - } - - BufferedImage bi = null; - if (image instanceof BufferedImage) { - bi = (BufferedImage) image; - } else { - int w = image.getWidth(null); - int h = image.getHeight(null); - - if (w <= 0 || h <= 0) { - // Can't create image if one of these is -1 - // (Interrupted). - return imageWarp; - } - - bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); - bi.getGraphics().drawImage(image, 0, 0, null); - } - - imageWarp = new ImageWarp(bi, transform, imageBounds); - } - } - - return imageWarp; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMScalingRaster) { - OMScalingRaster omsr = (OMScalingRaster) source; - this.lat2 = omsr.lat2; - this.lon2 = omsr.lon2; - this.scaleTransformType = omsr.scaleTransformType; - // OK, OK, I know this isn't a deep copy. TODO - // this.sourceImage = omsr.sourceImage; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMShape.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMShape.java deleted file mode 100644 index b52535e4a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMShape.java +++ /dev/null @@ -1,205 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMShape.java,v $ -// $RCSfile: OMShape.java,v $ -// $Revision: 1.3 $ -// $Date: 2006/04/07 15:38:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Shape; -import java.awt.geom.FlatteningPathIterator; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; - -import com.bbn.openmap.proj.Projection; - -/** - * The OMShape object is an OMGraphic intended to be used with non-GeoProj - * projections, defining projected map object to be modified for different - * views. You can use it to provide OMGraphic functionality, with respect to - * colors and strokes and OMGraphicLists, to java.awt.Shape objects. - *

- * GeoProj projections will be able to display them, but they will be rendered - * as OMGraphic.RENDERTYPE_LATLON with OMGraphic.LINETYPE_STRAIGHT settings. - * Rendering can be unpredictable for large coordinate values. - */ -public class OMShape extends OMGraphicAdapter implements OMGraphic { - private static final long serialVersionUID = 1L; - protected Shape origShape = null; - - protected OMShape() { - } - - public OMShape(Shape shapeIn) { - origShape = shapeIn; - } - - public Shape getOrigShape() { - return origShape; - } - - public void setOrigShape(Shape origShape) { - this.origShape = origShape; - setNeedToRegenerate(true); - } - - public boolean generate(Projection proj) { - setNeedToRegenerate(true); - - if (origShape != null) { - setShape(new GeneralPath(proj.forwardShape(origShape))); - setLabelLocation(getShape(), proj); - setNeedToRegenerate(false); - return true; - } - - return false; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMShape) { - OMShape shape = (OMShape) source; - - this.origShape = new GeneralPath(shape.origShape); - } - } - - /** - * This is a subclass that uses the provided shape as the generated shape. - * Takes advantage of the rendering mechanism of OMGraphics. Mainly used for - * rendering features already projected for vector tiles. - * - * @author dietrick - * - */ - public static class PROJECTED extends OMShape { - private static final long serialVersionUID = 1L; - - public PROJECTED(Shape s) { - super(s); - setShape(new GeneralPath(origShape)); - setNeedToRegenerate(false); - } - - public boolean generate(Projection proj) { - // NOOP - return true; - } - } - - public static class GAPPED extends OMShape { - private static final long serialVersionUID = 2L; - - float strokeWidth; - float gapWidth; - - public GAPPED(Shape s, float strokeWidth, float gapWidth) { - super(s); - this.strokeWidth = strokeWidth; - this.gapWidth = gapWidth; - - this.setStroke(new BasicStroke(strokeWidth)); - setShape(getGappedShape(origShape)); - setNeedToRegenerate(false); - } - - public boolean generate(Projection proj) { - // NOOP - return true; - } - - protected GeneralPath getGappedShape(Shape s) { - GeneralPath gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - GeneralPath inside = null; - GeneralPath outside = null; - //GeneralPath middle = null; - - PathIterator pi2 = s.getPathIterator(null); - FlatteningPathIterator pi = new FlatteningPathIterator(pi2, .25); - double[] coords = new double[6]; - - double xcoord1 = 0; - double ycoord1 = 0; - double xcoord2 = 0; - double ycoord2 = 0; - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - if (inside == null) { - // Need to set up the first point. We can't calculate the - // position of the perpendicular points until we know the - // location of the second point. - inside = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - outside = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - //middle = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - xcoord1 = coords[0]; - ycoord1 = coords[1]; - - continue; - } - - xcoord2 = coords[0]; - ycoord2 = coords[1]; - - // Compute cosinus and sinus of rotation angle - double dx = xcoord2 - xcoord1; - double dy = ycoord2 - ycoord1; - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = .25;//getLength() / 2.0; // x radius before rotation - double w = (gapWidth + strokeWidth) / 2; - - - double x1 = xcoord1 + r * rcos; - double y1 = ycoord1 + r * rsin; - - switch (type) { - case PathIterator.SEG_LINETO: - inside.lineTo(x1 - w * rsin, y1 + w * rcos); - outside.lineTo(x1 + w * rsin, y1 - w * rcos); - //middle.lineTo(xcoord1, ycoord1); - break; - case PathIterator.SEG_MOVETO: - inside.moveTo(x1 - w * rsin, y1 + w * rcos); - outside.moveTo(x1 + w * rsin, y1 - w * rcos); - //middle.moveTo(xcoord1, ycoord1); - break; - default: - } - - xcoord1 = xcoord2; - ycoord1 = ycoord2; - - pi.next(); - } - - gp.append(inside, false); - //gp.append(middle, false); - gp.append(outside, false); - return gp; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMSpline.java deleted file mode 100644 index a6d268e29..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMSpline.java +++ /dev/null @@ -1,278 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMSpline.java,v $ -//$RCSfile: OMSpline.java,v $ -//$Revision: 1.11 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Point; -import java.util.ArrayList; - -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * A splined OMPoly. With RENDERTYPE_LATLON mode, spline is computed on - * geographic locations, and then projected. Very few changes from OMPoly source - * code, just needed to calculate the spline before projecting in generate(). - * Look for HACK in source code ... - * - * @author Eric LEPICIER - * @version 15 juil. 2002 - */ -public class OMSpline extends OMPoly { - - /** - * Default constructor. - */ - public OMSpline() { - super(); - } - - /** - * Create an OMSpline from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the curve to be connected (as a potato), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public OMSpline(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Create an OMSpline from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the curve to be connected (as a potato), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is - * generated internally) - */ - public OMSpline(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Create an OMSpline from a list of xy pairs. If you want the curve to be - * connected, you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param xypoints array of x/y points, arranged x, y, x, y, etc. - */ - public OMSpline(int[] xypoints) { - super(xypoints); - } - - /** - * Create an x/y OMSpline. If you want the curve to be connected, you need - * to ensure that the first and last coordinate pairs are the same. - * - * @param xPoints int[] of x coordinates - * @param yPoints int[] of y coordinates - */ - public OMSpline(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Create an x/y OMSpline at an offset from lat/lon. If you want the curve - * to be connected, you need to ensure that the first and last coordinate - * pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xypoints int[] of x,y pairs - * @param cMode offset coordinate mode - */ - public OMSpline(double latPoint, double lonPoint, int[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Create an x/y OMSpline at an offset from lat/lon. If you want the curve - * to be connected, you need to ensure that the first and last coordinate - * pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xPoints int[] of x coordinates - * @param yPoints int[] of y coordinates - * @param cMode offset coordinate mode - */ - public OMSpline(double latPoint, double lonPoint, int[] xPoints, int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * Prepare the spline for rendering. - * - * @see com.bbn.openmap.omGraphics.OMGeometry#generate(Projection) - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omspline", "OMSpline: null projection in generate!"); - return false; - } - - // NatCubicSpline spline = isGeometryClosed() ? natCubicClosed : - // natCubic; - // HACK : should use something else than nsegs - // spline.setSteps(nsegs); - - float[][] splinePoints; - - switch (renderType) { - - case RENDERTYPE_XY: - if (xs == null) { - Debug.message("omspline", "OMSpline x/y rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - splinePoints = NatCubicSpline.calc(xs, ys, isGeometryClosed(), nsegs); - xpoints = new float[1][0]; - xpoints[0] = splinePoints[0]; - ypoints = new float[1][0]; - ypoints[0] = splinePoints[1]; - - break; - - case RENDERTYPE_OFFSET: - if (xs == null) { - Debug.message("omspline", "OMSpline offset rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - int npts = xs.length; - float[] _x = new float[npts]; - float[] _y = new float[npts]; - - // forward project the radian point - Point origin = new Point(); - if (proj instanceof GeoProj) { - ((GeoProj) proj).forward(lat, lon, origin, true);// radians - } else { - proj.forward(Math.toDegrees(lat), Math.toDegrees(lon), origin); - } - - if (coordMode == COORDMODE_ORIGIN) { - for (int i = 0; i < npts; i++) { - _x[i] = (float) (xs[i] + origin.getX()); - _y[i] = (float) (ys[i] + origin.getY()); - } - } else { // CModePrevious offset deltas - _x[0] = xs[0] + origin.x; - _y[0] = ys[0] + origin.y; - - for (int i = 1; i < npts; i++) { - _x[i] = xs[i] + _x[i - 1]; - _y[i] = ys[i] + _y[i - 1]; - } - } - - splinePoints = NatCubicSpline.calc(_x, _y, isGeometryClosed(), nsegs); - - xpoints = new float[1][0]; - xpoints[0] = splinePoints[0]; - ypoints = new float[1][0]; - ypoints[0] = splinePoints[1]; - - break; - - case RENDERTYPE_LATLON: - if (rawllpts == null) { - Debug.message("omspline", "OMSpline latlon rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - // spline creation ; precision 1e-8 rad = 0.002" - double[] splinellpts = NatCubicSpline.calc(rawllpts, 1e-8f, isGeometryClosed(), nsegs); - - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians. - ArrayList vector; - if (proj instanceof GeoProj) { - vector = ((GeoProj) proj).forwardPoly(splinellpts, lineType, nsegs, isPolygon()); - } else { - vector = proj.forwardPoly(rawllpts, isPolygon()); - } - int size = vector.size(); - - xpoints = new float[(int) (size / 2)][0]; - ypoints = new float[xpoints.length][0]; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - xpoints[j] = vector.get(i); - ypoints[j] = vector.get(i + 1); - } - - if (!doShapes && size > 1) { - setNeedToRegenerate(false); - initLabelingDuringGenerate(); - setLabelLocation(xpoints[0], ypoints[0], proj); - return true; - } - - break; - - case RENDERTYPE_UNKNOWN: - Debug.error("OMSpline.generate: invalid RenderType"); - return false; - } - - setNeedToRegenerate(false); - setShape(createShape()); - setLabelLocation(getShape(), proj); - return true; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMText.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMText.java deleted file mode 100644 index 4f3e1d4c7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMText.java +++ /dev/null @@ -1,1437 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMText.java,v $ -// $RCSfile: OMText.java,v $ -// $Revision: 1.19 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The OMText graphic type lets you put text on the screen. The location of the - * string is really the location of the lower left corner of the first letter of - * the string. - */ -public class OMText extends OMGraphicAdapter implements OMGraphic { - - // ---------------------------------------------------------------------- - // Static constants - // ---------------------------------------------------------------------- - - /** Align the text to the right of the location. */ - public final static transient int JUSTIFY_LEFT = 0; - - /** Align the text centered on the location. */ - public final static transient int JUSTIFY_CENTER = 1; - - /** Align the text to the left of the location. */ - public final static transient int JUSTIFY_RIGHT = 2; - - /** - * Parameter of Font to count toward footprint of height of Text. This - * indicates that the ascent, descent and leading of the text should count - * toward the footprint of the text. This is the same as the full height of - * the FontMetric, and is the default. - */ - public final static transient int HEIGHT = 0; - - /** - * Parameter of Font to count toward footprint of height of Text. This - * indicates that the ascent and the descent of the text should count toward - * the footprint of the text. - */ - public final static transient int ASCENT_DESCENT = 1; - - /** - * Parameter of Font to count toward footprint of height of Text. This - * indicates that the ascent and the leading of the text should count toward - * the footprint of the text. - */ - public final static transient int ASCENT_LEADING = 2; - - /** - * Parameter of Font to count toward footprint of height of Text. This - * indicates that just the ascent of the text should count toward the - * footprint of the text. - */ - public final static transient int ASCENT = 3; - - /** - * Parameter that dictates where the font baseline will be set compared to - * the location of the OMText. The BASELINE_BOTTOM setting, the default, - * means that the location will be set along the normal bottom edge of the - * text where the letters rest. - */ - public final static transient int BASELINE_BOTTOM = 0; - - /** - * Parameter that dictates where the font baseline will be set compared to - * the location of the OMText. The BASELINE_MIDDLE setting means that the - * location will be set along the middle of the height of the text. - */ - public final static transient int BASELINE_MIDDLE = 1; - - /** - * Parameter that dictates where the font baseline will be set compared to - * the location of the OMText. The BASELINE_TOP setting means that the - * location will be set along the top of the height of the text. - */ - public final static transient int BASELINE_TOP = 2; - - public static final transient Font DEFAULT_FONT = new Font("SansSerif", java.awt.Font.PLAIN, 12); - - /** - * The default text matte stroke that is used to surround each character - * with the color set in the textMatteColor attribute. - */ - public static final transient Stroke DEFAULT_TEXT_MATTE_STROKE = new BasicStroke(2f); - // ---------------------------------------------------------------------- - // Fields - // ---------------------------------------------------------------------- - - /** - * The projected xy window location of the bottom left corner of the first - * letter of the text string. - */ - protected Point2D pt; - - /** The X/Y point or the offset amount depending on render type. */ - protected Point point; - - /** The Font type that the string should be displayed with. */ - protected Font f; - /** - * The FontSizer set in the OMText, changing the font size appropriate for a - * projection scale. - */ - protected FontSizer fontSizer = null; - /** - * The latitude location for the text, used for lat/lon or offset rendertype - * texts, in decimal degrees. - */ - protected double lat = 0.0f; - - /** - * The longitude location for the text, used for lat/lon or offset - * rendertype texts, in decimal degrees. - */ - protected double lon = 0.0f; - - /** The string to be displayed. */ - protected String data = null; - - /** - * Justification of the string. Will let you put the text to the right, - * centered or to the left of the given location. - */ - protected int justify = JUSTIFY_LEFT; - - /** - * Location of the baseline of the text compared to the location point of - * the OMText object. You can set this to be BASELINE_BOTTOM (default), - * BASELINE_MIDDLE or BASELINE_TOP, depending on if you want the bottom of - * the letters to be lined up to the location, or the middle or the top of - * them. - */ - protected int baseline = BASELINE_BOTTOM; - - /** - * The fmHeight is the FontMetric height to use for calculating the - * footprint for the line. This becomes important for multi-line text and - * text in decluttering, because it dictates the amount of space surrounding - * the text. The default height is to take into account the ascent, descent - * and leading of the font. - */ - protected int fmHeight = HEIGHT; - - protected boolean useMaxWidthForBounds = false; - - /** The angle by which the text is to be rotated, in radians */ - protected double rotationAngle = DEFAULT_ROTATIONANGLE; - /** - * The rotation angle used at render time, depending on rotate-ability. - * Radians. If null, no rotation should be applied at render time. - */ - protected Double renderRotationAngle = null; - - /** - * The text matte color surrounds each character of the string with this - * color. If the color is null, the text matte is not used. - */ - protected Color textMatteColor; - - /** - * The stroke used to paint the outline of each character. The stroke should - * be larger than 1 to give proper effect. - */ - protected transient Stroke textMatteStroke = DEFAULT_TEXT_MATTE_STROKE; - - // ---------------------------------------------------------------------- - // Caches - // These fields cache computed data. - // ---------------------------------------------------------------------- - - /** The bounding rectangle of this Text. */ - protected transient Polygon polyBounds; - - /** The Metrics of the current font. */ - protected transient FontMetrics fm; - - /** The text split by newlines. */ - protected transient String parsedData[]; - - /** cached string widths. */ - protected transient int widths[]; - - // ---------------------------------------------------------------------- - // Constructors - // ---------------------------------------------------------------------- - - /** - * Default constructor. Produces an instance with no location and an empty - * string for text. For this instance to be useful it needs text (setData), - * a location (setX, setY, setLat, setLon) and a renderType (setRenderType). - */ - public OMText() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - point = new Point(0, 0); - setData(""); - f = DEFAULT_FONT; - } - - /** - * Creates a text object, with Lat/Lon placement, and default SansSerif - * font. - * - * @param lt latitude of the string, in decimal degrees. - * @param ln longitude of the string, in decimal degrees. - * @param stuff the string to be displayed. - * @param just the justification of the string - */ - public OMText(double lt, double ln, String stuff, int just) { - this(lt, ln, stuff, DEFAULT_FONT, just); - } - - /** - * Creates a text object, with Lat/Lon placement. - * - * @param lt latitude of the string, in decimal degrees. - * @param ln longitude of the string, in decimal degrees. - * @param stuff the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string - */ - public OMText(double lt, double ln, String stuff, Font font, int just) { - - super(RENDERTYPE_LATLON, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - - lat = lt; - lon = ln; - setData(stuff); - f = font; - justify = just; - } - - /** - * Creates a text object, with XY placement, and default SansSerif font. - * - * @param px1 horizontal window pixel location of the string. - * @param py1 vertical window pixel location of the string. - * @param stuff the string to be displayed. - * @param just the justification of the string - */ - public OMText(int px1, int py1, String stuff, int just) { - this(px1, py1, stuff, DEFAULT_FONT, just); - } - - /** - * Creates a text object, with XY placement. - * - * @param px1 horizontal window pixel location of the string. - * @param py1 vertical window pixel location of the string. - * @param stuff the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string - */ - public OMText(int px1, int py1, String stuff, Font font, int just) { - super(RENDERTYPE_XY, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - point = new Point(px1, py1); - setData(stuff); - f = font; - justify = just; - } - - /** - * Creates a Text object, with lat/lon placement with XY offset, and default - * SansSerif font. - * - * @param lt latitude of the string, in decimal degrees. - * @param ln longitude of the string, in decimal degrees. - * @param offX horizontal offset of string - * @param offY vertical offset of string - * @param aString the string to be displayed. - * @param just the justification of the string - */ - public OMText(double lt, double ln, float offX, float offY, String aString, int just) { - this(lt, ln, offX, offY, aString, DEFAULT_FONT, just); - } - - /** - * Creates a Text object, with lat/lon placement with XY offset. - * - * @param lt latitude of the string, in decimal degrees. - * @param ln longitude of the string, in decimal degrees. - * @param offX horizontal offset of string - * @param offY vertical offset of string - * @param aString the string to be displayed. - * @param font the Font description for the string. - * @param just the justification of the string - */ - public OMText(double lt, double ln, float offX, float offY, String aString, Font font, int just) { - super(RENDERTYPE_OFFSET, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - lat = lt; - lon = ln; - point = new Point((int) offX, (int) offY); - setData(aString); - f = font; - justify = just; - } - - /** - * Get the font of the text object, which might have been scaled by the font - * sizer. - * - * @return the font of the object. - */ - public Font getFont() { - if (f == null) { - f = DEFAULT_FONT; - } - return f; - } - - /** - * Set the base font. Will take effect on the next render. If the font sizer - * is not null, this font will be set in that object as well, and the active - * font will come from the font sizer. To make the set font the constant - * font, set the font sizer to null. Flushes the cache fields - * fm , widths, and currentPolyBounds - * . Calls setScaledFont. - * - * @param aFont font to be used for the text. - * - * @see #fm - * @see #widths - * @see #polyBounds - */ - public void setFont(Font aFont) { - if (fontSizer != null) { - fontSizer.setFont(aFont); - setScaledFont(fontSizer.getScaledFont()); - } else { - setScaledFont(aFont); - } - } - - /** - * Sets the scaled font, which is the one that is used for rendering. - */ - protected void setScaledFont(Font aFont) { - f = aFont; - - // now flush the cached information about the old font - fm = null; // flush existing metrics. - widths = null; // flush existing width table. - polyBounds = null; // flush existing bounds. - } - - /** - * If the font sizer is not null, sets the scaled font with the proper value - * for the given scale. - */ - public void setFont(float scale) { - if (fontSizer != null) { - setScaledFont(fontSizer.getFont(scale)); - } - } - - /** - * Set the FontSizer object, which provides different font sizes at - * different scales. If set to null, the font size will remain constant - * regardless of projection scale. - */ - public void setFontSizer(FontSizer fs) { - Font bf = getFont(); - if (fs != null) { - bf = fs.getFont(); - } - - fontSizer = fs; - setFont(bf); - } - - /** - * Get the FontSizer object, which provides different font sizes at - * different scales. If set to null, the font size will remain constant - * regardless of projection scale. - */ - public FontSizer getFontSizer() { - return fontSizer; - } - - /** - * Get the x location. Applies to XY and OFFSET text objects. - * - * @return the horizontal window location of the string, from the left of - * the window. - */ - public int getX() { - if (point != null) { - return point.x; - } else { - return 0; - } - } - - /** - * Set the x location. Applies to XY and OFFSET text objects. - * - * @param newX the horizontal pixel location of the window to place the - * string. - */ - public void setX(int newX) { - if (point == null && getRenderType() == RENDERTYPE_LATLON) { - point = new Point(); - setRenderType(RENDERTYPE_OFFSET); - } - point.x = newX; - setNeedToRegenerate(true); - } - - /** - * Get the y location. Applies to XY and OFFSET text objects. - * - * @return the vertical pixel location of the string, from the top of the - * window. - */ - public int getY() { - if (point != null) { - return point.y; - } else { - return 0; - } - } - - /** - * Set the y location. Applies to XY and OFFSET text objects. - * - * @param newY the vertical pixel location of the window to place the - * string. - */ - public void setY(int newY) { - if (point == null && getRenderType() == RENDERTYPE_LATLON) { - point = new Point(); - setRenderType(RENDERTYPE_OFFSET); - } - point.y = newY; - setNeedToRegenerate(true); - } - - /** - * Get the latitude location of the string. Applies to LATLON and OFFSET - * text objects. - * - * @return the latitude, in decimal degrees. - */ - public double getLat() { - return lat; - } - - /** - * Set the latitude. Applies to LATLON and OFFSET text objects. - * - * @param l latitude for new location, in decimal degrees. - */ - public void setLat(double l) { - lat = l; - setNeedToRegenerate(true); - } - - /** - * Return the longitude. Applies to LATLON and OFFSET text objects. - * - * @return the longitude location of the string, in decimal degrees. - */ - public double getLon() { - return lon; - } - - /** - * Set the longitude. Applies to LATLON and OFFSET text objects. - * - * @param l the longitude location for the string, in decimal degrees. - */ - public void setLon(double l) { - lon = l; - setNeedToRegenerate(true); - } - - /** - * Not for the faint hearted. Used by the DeclutterMatrix to replace text on - * the map after it has been projected. This method lets the declutter - * matrix find out where the text should go. - * - * @return Point on the map where the text has been projected to go. - */ - public Point2D getMapLocation() { - return pt; - } - - /** - * Not for the faint hearted. Used by the DeclutterMatrix to replace text on - * the map after it has been projected. This method lets the declutter - * matrix put the text in an uncluttered place. - * - * @param point the point on the map where the text being placed. - */ - public void setMapLocation(Point2D point) { - pt = point; - polyBounds = null; - } - - /** - * Returns the color used to matte the actual text of this class. - * - * @return the text matte color, null if not used - */ - public Color getTextMatteColor() { - return textMatteColor; - } - - /** - * Sets the color used to paint the outline of the characters in this text. - * The thickness of the outline is decided by the textMatteStroke. If the - * color is null, the outline will not be painted. - * - * The default value is null. - * - * @param textMatteColor - */ - public void setTextMatteColor(Color textMatteColor) { - this.textMatteColor = textMatteColor; - } - - /** - * Returns the stroke used to paint the outline of the characters in this - * text. - * - * @return the stroke used to paint the outline - */ - public Stroke getTextMatteStroke() { - return textMatteStroke; - } - - /** - * Sets the stroke used to paint the outline of the characters in this text - * For best effect the stroke thickness should be larger than 1 and it - * should be continuous. - * - * The default thickness is 2. - * - * @param textMatteStroke the new stroke - */ - public void setTextMatteStroke(Stroke textMatteStroke) { - this.textMatteStroke = textMatteStroke; - } - - /** - * Return the string. - * - * @return the string - */ - public synchronized java.lang.String getData() { - return data; - } - - /** - * Sets the string contents that are presented. Flushes the cache fields - * parsedData,widths, and - * currentPolyBounds. HACK synchronized so that it doesn't - * interfere with other methods that are using parsedData. - * - * @param d the text to be displayed - * - * @see #parsedData - * @see #widths - * @see #polyBounds - */ - public synchronized void setData(java.lang.String d) { - data = d; - - // now flush the cached information about the old text - parsedData = null; // flush existing parsed line table. - widths = null; // flush existing width table. - polyBounds = null; // flush existing bounds. - } - - /** - * Gets the justification of this OMText. - * - * @return one of JUSTIFY_LEFT, JUSTIFY_CENTER, JUSTIFY_RIGHT - */ - public int getJustify() { - return justify; - } - - /** - * Sets the justification of this OMText. Flushes the cache fields - * fm,widths, and currentPolyBounds. - * - * @param j one of JUSTIFY_LEFT, JUSTIFY_CENTER, JUSTIFY_RIGHT - * @see #polyBounds - */ - public void setJustify(int j) { - justify = j; - - // now flush cached information - polyBounds = null; // flush existing bounds. - } - - /** - * Gets the baseline location of this OMText. - * - * @return one of BASELINE_BOTTOM, BASELINE_MIDDLE or BASELINE_TOP. - */ - public int getBaseline() { - return baseline; - } - - /** - * Sets the location of the baseline of this OMText. Flushes the cache - * fields fm,widths, and - * currentPolyBounds. - * - * @param b one of BASELINE_BOTTOM, BASELINE_MIDDLE or BASELINE_TOP. - * @see #polyBounds - */ - public void setBaseline(int b) { - baseline = b; - - // now flush cached information - polyBounds = null; // flush existing bounds. - } - - /** - * Set flag to specify that the bounds, if displayed, should be rectangular. - * Only really affects multi-line text. - * - * @param value if true, bounds for multi-line text will be rectangular - * instead of closely following text. - */ - public void setUseMaxWidthForBounds(boolean value) { - useMaxWidthForBounds = value; - } - - /** - * Get flag to specify that the bounds, if displayed, should be rectangular. - * Only really affects mult-line text. - * - * @return true if bounds for multi-line text will be retangular instead of - * closely following text. - */ - public boolean getUseMaxWidthForBounds() { - return useMaxWidthForBounds; - } - - /** - * Get the text bounds. - * - * @return Polygon or null if bounds not calculated yet - */ - public Polygon getPolyBounds() { - polyBounds = computeBounds(polyBounds); - - return polyBounds; - } - - /** - * Set the fmHeight to use for the footprint. - * - * @param fmh the setting for fmHeight, out of the parameters stated above. - */ - public void setFMHeight(int fmh) { - fmHeight = fmh; - } - - /** - * Get the fmHeight used for the footprint. - * - * @return the setting for fmHeight, out of the parameters stated above. - */ - public int getFMHeight() { - return fmHeight; - } - - /** - * Set the angle by which the text is to rotated. - * - * @param angle the number of radians the text is to be rotated. Measured - * clockwise from horizontal. Positive numbers move the positive x - * axis toward the positive y axis. - */ - public void setRotationAngle(double angle) { - this.rotationAngle = angle; - setNeedToRegenerate(true); - } - - /** - * Get the current rotation of the text. - * - * @return the text rotation. - */ - public double getRotationAngle() { - return rotationAngle; - } - - /** - * Prepares the text for rendering. Determines the location based on the - * renderType and possibly the projection. Sets the field pt. - * Flushes the cache field currentPolyBounds. - * - * @param proj the projection of the window. - * @return true if the placement of the string on the window is valid. - * - * @see #pt - */ - public synchronized boolean generate(Projection proj) { - /* - * HACK synchronized because of various race conditions that need to be - * sorted out. - */ - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMText: null projection in generate!"); - return false; - } - - // flush the cached information about the bounding box. - polyBounds = null; - renderRotationAngle = null; - - /* - * Although it most definitely has bounds, OMText is considered a point - * object by the projection code. We need to check to make sure the - * point is plot-able: if not then don't display it. This might occur, - * for instance, if we're using the Orthographic and the point is on the - * other side of the world. - */ - switch (renderType) { - case RENDERTYPE_XY: - pt = point; - break; - case RENDERTYPE_OFFSET: - if (!proj.isPlotable(lat, lon)) { - if (Debug.debugging("omgraphic")) - System.err.println("OMText.generate(): offset point is not plotable!"); - setNeedToRegenerate(true);// so we don't render it! - return false; - } - pt = proj.forward(lat, lon, new Point2D.Double()); - pt.setLocation(pt.getX() + point.x, pt.getY() + point.y); - break; - case RENDERTYPE_LATLON: - if (!proj.isPlotable(lat, lon)) { - if (Debug.debugging("omgraphic")) - System.err.println("OMText.generate(): llpoint is not plotable!"); - setNeedToRegenerate(true);// so we don't render it! - return false; - } - pt = proj.forward(lat, lon, new Point2D.Double()); - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMText.render.generate(): invalid RenderType"); - return false; - } - - setFont(proj.getScale()); - evaluateRotationAngle(proj); - - // Compliance with Shape additions to OMGeometry/OMGraphic. - // If font metrics are set, we can take care of this now. If - // this is the first time this OMText is drawn, then we have - // to put this off until render. There will be a - // one-projection lag for font metrics to catch up with any - // change. - polyBounds = computeBounds(null); - setLabelLocation(getShape(), proj); - setNeedToRegenerate(false); - return true; - } - - /** - * Set the renderRotationAngle based on the projection angle and OMText - * settings. - * - * @param proj the current projection. - */ - public void evaluateRotationAngle(Projection proj) { - renderRotationAngle = null; - double projRotation = proj.getRotationAngle(); - Object noRotationAtt = getAttribute(OMGraphicConstants.NO_ROTATE); - boolean compensateForProjRot = noRotationAtt != null - && !noRotationAtt.equals(Boolean.FALSE); - - if (compensateForProjRot) { - renderRotationAngle = rotationAngle - projRotation; - } else if (rotationAngle != DEFAULT_ROTATIONANGLE) { - renderRotationAngle = rotationAngle; - } - } - - /** - * Build a font out of an X Font description string. This function take this - * common string format, and pulls the font type, style, and size out of it. - * - * @param fontString the X font description. - */ - public static Font rebuildFont(String fontString) { - if (fontString.length() == 0) - return DEFAULT_FONT; - int fontStyle = Font.PLAIN; - int fontSize = 12; - // Taking the X Font-type string and converting the - // essential parts to a java Font object. - - int start = fontString.indexOf("-", 1) + 1; // skipping first - // field - int end = fontString.indexOf("-", start + 1); - String name = fontString.substring(start, end); - // System.out.println("rebuildFont: Name is " + name); - if (fontString.indexOf("-bold-") >= 0) - fontStyle = Font.BOLD; - if (fontString.indexOf("-i-") >= 0) - fontStyle += Font.ITALIC; - // System.out.println("rebuildFont: Style is " + fontStyle); - start = fontString.indexOf("--") + 2; - end = fontString.indexOf("-", start + 1); - String tmpFontSize = fontString.substring(start, end); - if (tmpFontSize.indexOf("*") < 0) - fontSize = Integer.parseInt(tmpFontSize); - // System.out.println("rebuildFont: Size is " + fontSize); - return new Font(name, fontStyle, fontSize); - } - - /** - * In some applications, fonts are represented by a string. Traditionally, - * with MATT, the font was a X representation of a font. That's what is - * being done here - we're taking the Font structure, and then going to - * XFont type text structure. Dashes need to be included, line feeds are - * not. They are here only for readability. The rebuildFont method brings - * this back to a java Font. - * - * @param font the Java font to convert to an XFont string. - * @return the font as a string. - */ - public static String fontToXFont(java.awt.Font font) { - // -foundry(who made it) - StringBuffer ret = new StringBuffer("-*"); - // -font family(name) - ret.append("-").append(font.getName()); - // -weight(bold, medium) - if (font.isBold()) - ret.append("-bold"); - else - ret.append("-normal"); - // -slant(o,i) - if (font.isItalic()) - ret.append("-i"); - else - ret.append("-o"); - // -set width(normal, condensed, narrow, double width) - ret.append("-normal"); - // --pixels(height) - ret.append("--").append(font.getSize()); - // -points(in tenths of a point, related to screen) - ret.append("-*"); - // -horizontal resolution in dpi - ret.append("-*"); - // -vertical resolution in dpi - ret.append("-*"); - // -spacing(m-monospace or p-proportional) - ret.append("-*"); - // -average width(of each letter, in tenths of a pixel) - ret.append("-*"); - // -character set(like an ISO designation. - ret.append("-*"); - // System.out.println("SText.fontString: " + ret); - return ret.toString(); - } - - /** - * Counts occurrences of a character in a string. - * - * @param str the String - * @param ch the character to count - * @return the number of occurrences - */ - protected int countChar(String str, int ch) { - int fromIndex = 0; - int count = 0; - - while ((fromIndex = str.indexOf(ch, fromIndex)) != -1) { - count++; - fromIndex++; // increment past current index - // so we don't pick up the same - // instance again. - } - return count; - } - - /** - * Breaks the text down into separate lines. Sets the cache field - * parsedData. - * - * @see #parsedData - */ - protected void parseData() { - if (parsedData == null) { - - if (data == null) - data = ""; - - int nLines = countChar(data, '\n') + 1; - if (nLines <= 1) { - parsedData = new String[1]; - parsedData[0] = data; - } else { - int i = 0; - int fromIndex = 0; - int toIndex = 0; - parsedData = new String[nLines]; - - while ((toIndex = data.indexOf('\n', fromIndex)) != -1) { - parsedData[i] = data.substring(fromIndex, toIndex); - fromIndex = toIndex + 1; - i++; - } - parsedData[nLines - 1] = data.substring(fromIndex, data.length()); - } - } - } - - /** - * Computes the widths of each line of the text. Sets the cache field - * widths. - * - * @param fm the metrics to use for computation. - * - * @see #widths - */ - protected void computeStringWidths(FontMetrics fm) { - if (widths == null && fm != null) { - int nLines = parsedData.length; - widths = new int[nLines]; - for (int i = 0; i < nLines; i++) { - widths[i] = fm.stringWidth(parsedData[i]); - } - } - } - - /** - * This function can be called to initialize the internals such as height - * and width of OMText. Lets you use the graphics, and thus the FontMetrics - * object, to figure out the dimensions of the text in order to manipulate - * the placement of the text on the map. These internals were otherwise - * initialized only when render function was called. - * - * @param g the java.awt.Graphics to put the string on. - */ - public synchronized void prepareForRender(Graphics g) { - parseData(); - g.setFont(getFont()); - - if (fm == null) { - fm = g.getFontMetrics(); - } - polyBounds = computeBounds(polyBounds); - } - - /** - * Renders the text onto the given graphics. Sets the cache field - * fm. - * - * @param g the java.awt.Graphics to put the string on. - * - * @see #fm - */ - public synchronized void render(Graphics g) { - // copy the graphic, so our transform doesn't cascade to - // others... - - if (getNeedToRegenerate() || pt == null || !isVisible()) - return; - - g = g.create(); - - g.setFont(getFont()); - setGraphicsForEdge(g); - - if (fm == null) { - fm = g.getFontMetrics(); - } - - Polygon currentPolyBounds = computeBounds(this.polyBounds); - this.polyBounds = currentPolyBounds; - - // If there is a rotation angle, the shape will be calculated - // for that rotation. Don't need to rotate the Graphics for - // the shape. - - Shape s = getShape(); - - if (isRenderable(s)) { - if (shouldRenderFill()) { - setGraphicsForFill(g); - fill(g, s); - - if (textureMask != null && textureMask != fillPaint) { - setGraphicsColor(g, textureMask); - fill(g, s); - } - } - - if (isMatted()) { - if (isSelected()) { - setGraphicsColor(g, getSelectPaint()); - } else { - setGraphicsColor(g, getMattingPaint()); - } - draw(g, s); - } - } - - // to use later to unset the transform, if used. - double rx = 0.0; - double rw = 0.0; - double woffset = 0.0; - - Double currentRenderRotationAngle = renderRotationAngle; - if (g instanceof Graphics2D && currentRenderRotationAngle != null) { - - Rectangle rect = currentPolyBounds.getBounds(); - - rx = rect.getX(); - rw = rect.getWidth(); - woffset = 0.0; - - switch (justify) { - case JUSTIFY_LEFT: - // woffset = 0.0; - break; - case JUSTIFY_CENTER: - woffset = rw / 2; - break; - case JUSTIFY_RIGHT: - woffset = rw; - } - - // rotate about our text anchor point - ((Graphics2D) g).rotate(currentRenderRotationAngle, rx + woffset, pt.getY()); - } - - setGraphicsForEdge(g); - - int height; - if (fmHeight == HEIGHT) { - height = fm.getHeight(); - } else if (fmHeight == ASCENT_LEADING) { - height = fm.getHeight() - fm.getDescent(); - } else if (fmHeight == ASCENT_DESCENT) { - height = fm.getAscent() + fm.getDescent(); - } else { - height = fm.getAscent(); - } - - int baselineLocation = (int) pt.getY(); // baseline == - // BASELINE_BOTTOM, - // normal. - - if (baseline == BASELINE_MIDDLE) { - baselineLocation += (fm.getAscent() - fm.getDescent()) / 2; - } else if (baseline == BASELINE_TOP) { - baselineLocation += (fm.getAscent() - fm.getDescent()); - } - - switch (justify) { - case JUSTIFY_LEFT: - // Easy case, just draw them. - for (int i = 0; i < parsedData.length; i++) { - renderString(g, parsedData[i], pt.getX(), baselineLocation + (height * i)); - } - break; - case JUSTIFY_CENTER: - computeStringWidths(fm); - for (int i = 0; i < parsedData.length; i++) { - renderString(g, parsedData[i], pt.getX() - (widths[i] / 2), baselineLocation - + (height * i)); - } - break; - case JUSTIFY_RIGHT: - computeStringWidths(fm); - for (int i = 0; i < parsedData.length; i++) { - renderString(g, parsedData[i], pt.getX() - widths[i], baselineLocation - + (height * i)); - } - break; - } - } - - protected void renderString(Graphics g, String string, double x, double y) { - if (g instanceof Graphics2D) { - Graphics2D g2 = (Graphics2D) g; - if (getTextMatteColor() != null) { - FontRenderContext context = g2.getFontRenderContext(); - GlyphVector glyphVector = g2.getFont().createGlyphVector(context, string); - Shape outline = glyphVector.getOutline(); - g2.translate(x, y); - g2.setStroke(getTextMatteStroke()); - g2.setColor(getTextMatteColor()); - g2.draw(outline); - g2.translate(-x, -y); - - g2.setColor(getLineColor()); - } - } - - g.drawString(string, (int) x, (int) y); - } - - /** - * Computes the bounding polygon. Sets the cache field - * currentPolyBounds. - * - * @param currentPolyBounds the current polygon bounds, new ones will be - * created if it's null - * @return new poly bounds if needed, or the current polygon bounds if - * already set. - * @see #polyBounds - */ - protected Polygon computeBounds(Polygon currentPolyBounds) { - if (parsedData == null) { - parseData(); - } - - if (currentPolyBounds == null && pt != null && fm != null) { - - // System.out.println("\tcomputing poly bounds"); - - int xoffset = 0; - int i; - - int height; - int descent; - if (fmHeight == HEIGHT) { - height = fm.getHeight(); - descent = fm.getDescent(); - } else if (fmHeight == ASCENT_DESCENT) { - height = fm.getAscent(); - descent = fm.getDescent(); - } else if (fmHeight == ASCENT_LEADING) { - height = fm.getHeight() - fm.getDescent(); - descent = 0; - } else { - height = fm.getAscent(); - descent = 0; - } - - int nLines = parsedData.length; - currentPolyBounds = new Polygon(); - - computeStringWidths(fm); - - int baselineOffset = 0; // baseline == BASELINE_BOTTOM, - // normal. - - if (baseline == BASELINE_MIDDLE) { - baselineOffset = (fm.getAscent() - fm.getDescent()) / 2; - } else if (baseline == BASELINE_TOP) { - baselineOffset = fm.getAscent() - fm.getDescent(); - } - - // or, baselineOffset = height - (baseline * height /2); - // But that depends on the actual values of the BASELINE - // values, which doesn't seem safe. - - /* - * pt.y is bottom of first line, currenty is initialized to top of - * first line, minus any offset introduced by baseline adjustments. - */ - int currenty = (int) pt.getY() + descent - height + baselineOffset; - - // First, all the line endpoints. - for (i = 0; i < nLines; i++) { - - switch (justify) { - case JUSTIFY_LEFT: - xoffset = widths[i]; - break; - case JUSTIFY_CENTER: - xoffset = widths[i] / 2; - break; - case JUSTIFY_RIGHT: - xoffset = 0; - break; - } - - // top of line - currentPolyBounds.addPoint((int) pt.getX() + xoffset, currenty); - currenty += height; - // bottom of line - currentPolyBounds.addPoint((int) pt.getX() + xoffset, currenty); - } - - // Next, all line startpoints (the left side) - for (i = nLines - 1; i >= 0; i--) { - switch (justify) { - case JUSTIFY_LEFT: - xoffset = 0; - break; - case JUSTIFY_CENTER: - xoffset = -widths[i] / 2; - break; - case JUSTIFY_RIGHT: - xoffset = -widths[i]; - break; - } - currentPolyBounds.addPoint((int) pt.getX() + xoffset, currenty); - currenty -= height; - currentPolyBounds.addPoint((int) pt.getX() + xoffset, currenty); - } - - GeneralPath projectedShape = null; - - if (useMaxWidthForBounds) { - projectedShape = new GeneralPath(currentPolyBounds.getBounds()); - } else { - projectedShape = new GeneralPath(currentPolyBounds); - } - - // Make sure the shape takes into account the current - // rotation angle. Code taken from generate() method, - // so it should match up with the drawn text. - Double angle = renderRotationAngle; - if (angle != null) { - - Rectangle rect = currentPolyBounds.getBounds(); - - double rx = rect.getX(); - double rw = rect.getWidth(); - double woffset = 0.0; - - switch (justify) { - case JUSTIFY_LEFT: - // woffset = 0.0; - break; - case JUSTIFY_CENTER: - woffset = rw / 2; - break; - case JUSTIFY_RIGHT: - woffset = rw; - } - - AffineTransform at = new AffineTransform(); - at.rotate(angle, rx + woffset, pt.getY()); - PathIterator pi = projectedShape.getPathIterator(at); - GeneralPath gp = new GeneralPath(); - gp.append(pi, false); - // Replace shape with rotated version - projectedShape = gp; - } - - setShape(projectedShape); - - } else { - if (Debug.debugging("omtext")) { - Debug.output("OMText.computeBounds() didn't compute because polybounds = " - + currentPolyBounds + " or pt = " + pt + " or fm = " + fm - + ", (only polybounds should be null)"); - } - } - - return currentPolyBounds; - } - - /** - * Return the shortest distance from the OMText to an XY-point. - *

- * - * This method uses the OMText's internal Shape object, created from the - * boundary of the text, as its boundary. - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - public float distance(double x, double y) { - return _distance(x, y); - } - - public boolean hasLineTypeChoice() { - return false; - } - - /** - * Return a copy of the pixel lengths of the text line(s). - * - * @return array of ints. Returns null if the widths haven't been calculated - * yet. - */ - public int[] getLineWidths() { - int[] ret = null; - if (widths != null) { - ret = new int[widths.length]; - System.arraycopy(widths, 0, ret, 0, widths.length); - } - return ret; - } - - /** - * Get the pixel width of the longest line. - * - * @return pixels, returns null if the widths haven't been calculated yet, - * zero minimum if they have. - */ - public Integer getMaxLineWidth() { - if (widths != null) { - int result = 0; - for (int i : widths) { - result = Math.max(result, i); - } - return new Integer(result); - } - return null; - } - - /** - * Write this object to a stream. - */ - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - - // Write the Font. Take into account the font member could be - // null, although this is unlikely it never hurts to - // protect one's self. - - boolean writeFont = (f != OMText.DEFAULT_FONT); - - // First write a flag indicating if a Font is on the stream. - oos.writeBoolean(writeFont); - - // Write the Font data if a font is on this object. - if (writeFont) { - oos.writeObject(f.getName()); - oos.writeInt(f.getSize()); - oos.writeInt(f.getStyle()); - } - - writeStroke(oos, stroke, OMGraphic.BASIC_STROKE); - writeStroke(oos, textMatteStroke, DEFAULT_TEXT_MATTE_STROKE); - } - - /** - * Reconstitute from an ObjectInputStream. - */ - private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { - ois.defaultReadObject(); - - // Get the flag form the stream - boolean hasFont = ois.readBoolean(); - - if (hasFont) { - String name = (String) ois.readObject(); - int size = ois.readInt(); - int style = ois.readInt(); - f = new Font(name, style, size); - } else { - f = OMText.DEFAULT_FONT; - } - - stroke = readStroke(ois, OMGraphic.BASIC_STROKE); - textMatteStroke = readStroke(ois, DEFAULT_TEXT_MATTE_STROKE); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMText) { - OMText text = (OMText) source; - this.lat = text.lat; - this.lon = text.lon; - this.justify = text.justify; - this.baseline = text.baseline; - this.fmHeight = text.fmHeight; - this.useMaxWidthForBounds = text.useMaxWidthForBounds; - this.rotationAngle = text.rotationAngle; - if (text.pt != null) { - this.pt = new Point2D.Double(text.pt.getX(), text.pt.getY()); - } - if (text.point != null) { - this.point = new Point(text.point); - } - if (text.f != null) { - this.f = text.f.deriveFont(AffineTransform.TYPE_IDENTITY); - } - if (text.fontSizer != null) { - this.fontSizer = new FontSizer(text.fontSizer); - } - if (text.data != null) { - this.data = new String(text.data); - } - if (textMatteColor != null) { - this.textMatteColor = new Color(textMatteColor.getRGB(), true); - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextBalloon.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextBalloon.java deleted file mode 100644 index bb0be6e02..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextBalloon.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Projection; - -/** - * A simple OMText object that acts like a pretty information balloon, complete - * with little pointer to actual location. Fill color is balloon color. The - * balloon will move to the center of the map based on the location of the point - * referenced. - * - * @author dietrick - */ -public class OMTextBalloon extends OMText { - - Point2D llLoc; - - /** - * Can only make these tied to a lat/lon point, internally, they will be - * LATLON_OFFSET OMTexts. - * - * @param lt - * @param ln - * @param stuff - * @param just - */ - public OMTextBalloon(double lt, double ln, String stuff, int just) { - super(lt, ln, 0, 0, stuff, just); - } - - /** - * Can only make these tied to a lat/lon point, internally, they will be - * LATLON_OFFSET OMTexts. - * - * @param lt - * @param ln - * @param stuff - * @param font - * @param just - */ - public OMTextBalloon(double lt, double ln, String stuff, Font font, int just) { - super(lt, ln, 0, 0, stuff, font, just); - setUseMaxWidthForBounds(true); - setBaseline(BASELINE_TOP); - } - - /** - * Override this to figure out the offset to use for positioning based on - * screen location of lat/lon - */ - public boolean generate(Projection proj) { - llLoc = setOffsets(proj); - // Special handling for the first rendering, before font metrics are - // known. You'll see further on down. - if (fm == null) { - putAttribute(OMGraphic.APP_OBJECT, proj); - } - return super.generate(proj); - } - - /** - * Set the offset points based on relative screen location of lat/lon point - * after projection. - * - * @param proj current projection - * @return the current projected location for use in render. - */ - protected Point2D setOffsets(Projection proj) { - Point2D loc = proj.forward(lat, lon); - - double x = loc.getX(); - double y = loc.getY(); - boolean west = x <= proj.getWidth() / 2; - boolean north = y <= proj.getHeight() / 2; - - Polygon p = getPolyBounds(); - Point newPt = new Point(); - if (p != null) { - Rectangle r = p.getBounds(); - - if (west) { - newPt.x = (int) (-r.width * .25); - } else { - newPt.x = (int) (-r.width * .75); - } - - if (north) { - newPt.y = (int) (YOFFSET); - } else { - newPt.y = -(int) (YOFFSET + r.height); - } - - point = newPt; - } - return loc; - } - - int BBUFFER = 10; - int DBBUFFER = BBUFFER * 2; - int XOFFSET = 30; - int YOFFSET = 50; - - /** - * Special handling needed for first render, if font metrics aren't known - * yet. - */ - public void prepareForRender(Graphics g) { - boolean doCheck = fm == null; - super.prepareForRender(g); - if (doCheck) { - // First render, need to reset projected location. - Object obj = getAttribute(OMGraphic.APP_OBJECT); - if (obj instanceof Projection) { - setOffsets((Projection) obj); - generate((Projection) obj); - removeAttribute(OMGraphic.APP_OBJECT); - } - } - } - - public void render(Graphics g) { - - // This is to allow the polybounds to work on the first paint. - prepareForRender(g); - - Polygon polyBounds = getPolyBounds(); - if (polyBounds != null) { - Rectangle r = polyBounds.getBounds(); - - // Shadow - Graphics2D g2 = (Graphics2D) g.create(); - g2.setColor(new Color(0x66000000, true)); - g2.setTransform(AffineTransform.getTranslateInstance(3, 3)); - g2.fillRoundRect(r.x - BBUFFER, r.y - BBUFFER, r.width + DBBUFFER, r.height + DBBUFFER, DBBUFFER, DBBUFFER); - - if (llLoc != null) { - g2.fillPolygon(getPointer(r)); - } - g2.dispose(); - // - - setGraphicsForFill(g); - ((Graphics2D) g).fillRoundRect(r.x - BBUFFER, r.y - BBUFFER, r.width + DBBUFFER, r.height - + DBBUFFER, DBBUFFER, DBBUFFER); - if (llLoc != null) { - ((Graphics2D) g).fillPolygon(getPointer(r)); - } - } - - super.render(g); - } - - /** - * Create simple triangle to point to actual location. - * - * @param r bounding rectangle of text - * @return Polygon to fill with matching color of balloon. - */ - protected Polygon getPointer(Rectangle r) { - int centerX = r.x + r.width / 2; - int centerY = r.y + r.height / 2; - int[] xPoints = new int[] { (int) llLoc.getX(), centerX - r.width / BBUFFER, - centerX + r.width / BBUFFER, (int) llLoc.getX() }; - int[] yPoints = new int[] { (int) llLoc.getY(), centerY, centerY, (int) llLoc.getY() }; - - return new Polygon(xPoints, yPoints, 4); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextLabeler.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextLabeler.java deleted file mode 100644 index f3e178514..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMTextLabeler.java +++ /dev/null @@ -1,245 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: OMTextLabeler.java,v $ -//$Revision: 1.4 $ -//$Date: 2007/06/21 21:38:59 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Font; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; - -/** - * A default implementation of OMLabeler that extends from OMText. One thing - * going on with OMTextLabelers is that they are set to be non-rotating by - * default, which means they preserve their set orientation even when the map - * rotates. If you want them to rotate with the map, unset the - * OMGraphicConstants.NO_ROTATE attribute, or set it to Boolean.FALSE. - * - *

- * Usage:
- * 
- *  OMTextLabeler label = new OMTextLabeler(labelString, OMText.JUSTIFY_CENTER);
- *  omgraphic.putAttribute(OMGraphicConstants.LABEL, label);
- * 
- * - * @author dietrick - */ -public class OMTextLabeler extends OMText implements OMLabeler { - - public final static int ANCHOR_TOPLEFT = 0; - public final static int ANCHOR_TOP = 1; - public final static int ANCHOR_TOPRIGHT = 2; - public final static int ANCHOR_LEFT = 3; - public final static int ANCHOR_CENTER = 4; - public final static int ANCHOR_RIGHT = 5; - public final static int ANCHOR_BOTTOMLEFT = 6; - public final static int ANCHOR_BOTTOM = 7; - public final static int ANCHOR_BOTTOMRIGHT = 8; - - protected int anchor = ANCHOR_CENTER; - - /** - * - */ - public OMTextLabeler(String stuff) { - this(stuff, DEFAULT_FONT, JUSTIFY_LEFT); - } - - /** - * @param stuff - * @param just - */ - public OMTextLabeler(String stuff, int just) { - this(stuff, DEFAULT_FONT, just, ANCHOR_CENTER); - } - - public OMTextLabeler(String stuff, int just, int loc) { - this(stuff, DEFAULT_FONT, just, loc); - } - - /** - * @param stuff - * @param font - * @param just - */ - public OMTextLabeler(String stuff, Font font, int just) { - this(stuff, font, just, ANCHOR_CENTER); - } - - public OMTextLabeler(String stuff, Font font, int just, int loc) { - setRenderType(RENDERTYPE_XY); - setData(stuff); - setFont(font); - setJustify(just); - setAnchor(loc); - - putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - } - - public void setLocation(GeneralPath gp) { - if (gp != null) { - Rectangle rect = gp.getBounds(); - - double x = rect.getX(); - double y = rect.getY(); - - if (anchor == ANCHOR_TOP || anchor == ANCHOR_CENTER || anchor == ANCHOR_BOTTOM) { - x += rect.getWidth() / 2; - } else if (anchor == ANCHOR_TOPRIGHT || anchor == ANCHOR_RIGHT || anchor == ANCHOR_BOTTOMRIGHT) { - x += rect.getWidth(); - } - - if (anchor == ANCHOR_LEFT || anchor == ANCHOR_CENTER || anchor == ANCHOR_RIGHT) { - y += rect.getHeight() / 2; - } else if (anchor == ANCHOR_BOTTOMLEFT || anchor == ANCHOR_BOTTOM || anchor == ANCHOR_BOTTOMRIGHT) { - y += rect.getHeight(); - } - - setLocation(new Point((int) x, (int) y)); - } - } - - /* - * (non-Javadoc) - * @see - * com.bbn.openmap.omGraphics.OMLabeler#setLocation(java.awt.geom.Point2D) - */ - public void setLocation(Point2D p) { - polyBounds = null; - setX((int) p.getX()); - setY((int) p.getY()); - setMapLocation(p); - polyBounds = computeBounds(null); - setNeedToRegenerate(false); - } - - /* - * (non-Javadoc) - * @see com.bbn.openmap.omGraphics.OMLabeler#setLocation(int[][], int[][]) - */ - public void setLocation(int[] xpoints, int[] ypoints) { - setLocation(getCenter(xpoints, ypoints)); - } - - /** - * Calculate the projected area of the poly. Algorithm used is from some - * australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - protected static double calculateProjectedArea(int[] xpts, int[] ypts) { - int j = 0; - double area = 0.0; - - int npoints = xpts.length; - - for (int i = 0; i < npoints; ++i) { - j = (i + 1) % npoints; - area += xpts[i] * ypts[j]; - area -= ypts[i] * xpts[j]; - } - - return area / 2.0; - } - - /** - * Get the calculated center where the label string is drawn. Algorithm used - * is from some australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - protected static Point getCenter(int[] xpts, int[] ypts) { - - int npoints = xpts.length; - if (npoints == 1) { - Point center = new Point(xpts[0], ypts[0]); - return center; - } - if (npoints == 2) { - // rmcneil - two points, A=0, div zero below - int x; - if (xpts[1] > xpts[0]) - x = xpts[0] + ((xpts[1] - xpts[0]) / 2); - else - x = xpts[1] + ((xpts[0] - xpts[1]) / 2); - int y; - if (ypts[1] > ypts[0]) - y = ypts[0] + ((ypts[1] - ypts[0]) / 2); - else - y = ypts[1] + ((ypts[0] - ypts[1]) / 2); - Point center = new Point(x, y); - return center; - } - - double factor = 0; - double cx = 0.0f; - double cy = 0.0f; - - for (int i = 0; i < npoints; ++i) { - int j = (i + 1) % npoints; - - factor = xpts[i] * ypts[j] - xpts[j] * ypts[i]; - cx += (xpts[i] + xpts[j]) * factor; - cy += (ypts[i] + ypts[j]) * factor; - } - - double A = calculateProjectedArea(xpts, ypts); - A *= 6.0; - factor = 1.0 / A; - - // bbenyo: take the absolute value cause I was getting - // negative values - // for polys with all positive vertices - // cx = Math.abs(cx * factor); - // cy = Math.abs(cy * factor); - - // DFD and RS - let the area calculation return negative - // values, and don't do this absolute value calculation. - // Negative values get returned when the points are - // counterclockwise, indicating holes. We may want labels - // offscreen however, and the abs pushes them onscreen. - - cx *= factor; - cy *= factor; - - Point center = new Point((int) Math.round(cx), (int) Math.round(cy)); - return center; - } - - public int getAnchor() { - return anchor; - } - - public void setAnchor(int anchor) { - this.anchor = anchor; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMTextLabeler) { - OMTextLabeler labeler = (OMTextLabeler) source; - this.anchor = labeler.anchor; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMWarpingImage.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OMWarpingImage.java deleted file mode 100644 index debb63d2f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OMWarpingImage.java +++ /dev/null @@ -1,343 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.image.BufferedImage; -import java.net.MalformedURLException; -import java.net.URL; - -import com.bbn.openmap.dataAccess.image.WorldFile; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.util.ImageWarp; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * An OMGraphic that wraps an ImageWarp object to display the resulting - * OMRaster, in any projection. For use as a background object, doesn't react to - * mouse events, distance queries, etc. - * - *
- * try {
- * 	String imageFile = "/data/geoimages/NBenguela.2004357.aqua.250m.jpg";
- * 	WorldFile worldFile = WorldFile.get(PropUtils.getResourceOrFileOrURL(imageFile));
- * 	OMWarpingImage omwi = new OMWarpingImage(imageFile, LatLonGCT.INSTANCE, worldFile);
- * 	omList.add(omwi);
- * } catch (MalformedURLException e) {
- * 	e.printStackTrace();
- * } catch (InterruptedException e) {
- * 	e.printStackTrace();
- * }
- * 
- * try {
- * 	String imageFile = "/data/images/earthmap4k.jpg";
- * 	OMWarpingImage omwi = new OMWarpingImage(imageFile);
- * 	omList.add(omwi);
- * } catch (MalformedURLException e) {
- * 	e.printStackTrace();
- * } catch (InterruptedException e) {
- * 	e.printStackTrace();
- * }
- * 
- * 
- * - * @author dietrick - */ -public class OMWarpingImage extends OMGraphicAdapter implements OMGraphic { - - private static final long serialVersionUID = 1L; - protected ImageWarp warp; - protected OMRaster raster; - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath) throws MalformedURLException, InterruptedException { - setWarp(imagePath, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath, GeoCoordTransformation transform, DataBounds imageBounds) - throws MalformedURLException, InterruptedException { - setWarp(imagePath, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath, GeoCoordTransformation transform, WorldFile worldfile) - throws MalformedURLException, InterruptedException { - setWarp(imagePath, transform, worldfile); - } - - /** - * Takes an image, assumed to be a world image in the LLXY projection (equal - * arc) covering -180, 180 longitude to -90, 90 latitude. - * - * @param bi - */ - public OMWarpingImage(BufferedImage bi) { - setWarp(bi, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param bi a BufferedImage - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - */ - public OMWarpingImage(BufferedImage bi, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(bi, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param bi BufferedImage - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - */ - public OMWarpingImage(BufferedImage bi, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(bi, transform, worldfile); - } - - /** - * Takes an array of ARGB integer values representing an image, assumed to - * be a world image in the LLXY projection (equal arc) covering -180, 180 - * longitude to -90, 90 latitude. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - */ - public OMWarpingImage(int[] pix, int width, int height) { - setWarp(pix, width, height, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - */ - public OMWarpingImage(int[] pix, int width, int height, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(pix, width, height, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - */ - public OMWarpingImage(int[] pix, int width, int height, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(pix, width, height, transform, worldfile); - } - - /** - * Create an OMWarpingImage from an OMScalingRaster - useful for when the - * projection being used on the map doesn't match the projection of the - * raster, and it needs to be transformed. - * - * @param omsr OMScalingRaster - * @param transform a GeoCoordTransform if the OMScalingRaster image isn't a - * WGS84 image. - */ - public OMWarpingImage(OMScalingRaster omsr, GeoCoordTransformation transform) { - if (omsr != null) { - ImageWarp iw = omsr.getImageWarp(transform); - if (iw != null) { - setWarp(iw); - } - } - } - - /** - * Set all the information needed. - * - * @param imagePath - * @param transform - * @param imageBounds - * @throws MalformedURLException - * @throws InterruptedException - */ - public void setWarp(String imagePath, GeoCoordTransformation transform, DataBounds imageBounds) - throws MalformedURLException, InterruptedException { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - setWarp(new ImageWarp(bi, transform, imageBounds)); - } - - public void setWarp(String imagePath, GeoCoordTransformation transform, WorldFile worldfile) - throws MalformedURLException, InterruptedException { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - setWarp(new ImageWarp(bi, transform, worldfile)); - } - - /** - * Set all the information needed. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform - * @param imageBounds - */ - public void setWarp(int[] pix, int width, int height, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(new ImageWarp(pix, width, height, transform, imageBounds)); - } - - /** - * Set all the information needed. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform - * @param worldfile describes projection of image - */ - public void setWarp(int[] pix, int width, int height, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(new ImageWarp(pix, width, height, transform, worldfile)); - } - - public void setWarp(BufferedImage bi, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(new ImageWarp(bi, transform, imageBounds)); - } - - public void setWarp(BufferedImage bi, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(new ImageWarp(bi, transform, worldfile)); - } - - public void setWarp(ImageWarp wrp) { - warp = wrp; - setNeedToRegenerate(true); - } - - public ImageWarp getWarp() { - return warp; - } - - @Override - public boolean generate(Projection proj) { - if (warp != null) { - if (updateImageForProjection(proj) || raster == null) { - raster = warp.getOMRaster(proj, getAttribute(OMGraphic.LABEL)); - if (raster != null) { - DrawingAttributes.sTransfer(this, raster); - // Need to transfer label to raster for display - raster.putAttribute(OMGraphic.LABEL, getAttribute(OMGraphic.LABEL)); - } - } - } - - setNeedToRegenerate(false); - return true; - } - - protected Projection lastProjection = null; - - /** - * Called from within generate. Some render buffering calls generate to make - * sure the latest projection is called on an OMGraphic before it's put into - * a buffer. We're keeping track of the last projection used to generate the - * warped image, and if it's the same, don't bother regenerating, use the - * raster we have. - * - * @param proj current projection. - * @return false if the rest of generate() should be skipped. - */ - protected boolean updateImageForProjection(Projection proj) { - boolean ret = proj.equals(lastProjection); - lastProjection = proj; - return !ret; - } - - @Override - public void render(Graphics g) { - if (raster != null && isRenderable(raster.getShape())) { - raster.setSelected(isSelected()); - raster.setMatted(isMatted()); - raster.render(g); - } - } - - @Override - public float distance(double x, double y) { - if (raster != null) { - return raster.distance(x, y); - } - return super.distance(x, y); - } - - @Override - public float distanceToEdge(double x, double y) { - if (raster != null) { - return raster.distanceToEdge(x, y); - } - return super.distanceToEdge(x, y); - } - - @Override - public boolean contains(double x, double y) { - if (raster != null) { - return raster.contains(x, y); - } - return super.contains(x, y); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/OffsetGrabPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/OffsetGrabPoint.java deleted file mode 100644 index 25992733a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/OffsetGrabPoint.java +++ /dev/null @@ -1,214 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OffsetGrabPoint.java,v $ -// $RCSfile: OffsetGrabPoint.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:06:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.util.Hashtable; - -/** - * An OffsetGrabPoint is one that manages other grab points. When it is moved, - * the other GrabPoints on its internal list are moved the same amount in pixel - * space. - */ -public class OffsetGrabPoint extends GrabPoint { - /** The list of GrabPoints to move when this point moves. */ - protected Hashtable offsetPoints; - - /** - * Create the OffsetGrabPoint at a certain window location. - * - * @param x horizontal pixel location from left side of window. - * @param y vertical pixel location from top side of window. - */ - public OffsetGrabPoint(int x, int y) { - this(x, y, DEFAULT_RADIUS); - } - - /** - * Create the OffsetGrabPoint at a certain window location. - * - * @param x horizontal pixel location from left side of window. - * @param y vertical pixel location from top side of window. - * @param radius the pixel radius of the point. - */ - public OffsetGrabPoint(int x, int y, int radius) { - super(x, y, radius); - offsetPoints = new Hashtable(); - } - - /** - * Add a GrabPoint to the internal list. - */ - public GrabPoint addGrabPoint(GrabPoint gp) { - - if (gp == null) { - com.bbn.openmap.util.Debug.error("OffsetGrabPoint: adding null grab point!"); - return null; - } - - if (offsetPoints == null) { - offsetPoints = new Hashtable(); - } - offsetPoints.put(gp, new Offset(gp)); - - return gp; - } - - /** - * Remove a GrabPoint to the internal list. - */ - public GrabPoint removeGrabPoint(GrabPoint rgp) { - if (offsetPoints != null) { - Offset offset = offsetPoints.remove(rgp); - if (offset != null) { - return offset.gp; - } - } - return null; - } - - /** - * Called when the position of the OffsetGrabPoint has moved. Does not - * adjust the offsets. - */ - public void set(int x, int y) { - super.set(x, y); - } - - /** - * Called when the X position of the OffsetGrabPoint has moved. Does not - * adjust the offsets. - */ - public void setX(int x) { - super.setX(x); - } - - /** - * Called when the Y position of the OffsetGrabPoint has moved. Does not - * adjust the offsets. - */ - public void setY(int y) { - super.setY(y); - } - - /** - * Called when the other grab points may have moved, and the offset - * distances should be changed internally for the Offset objects. - */ - public void set() { - updateOffsets(); - } - - /** - * Flag used as a lock to prevent StackOverflowErrors, in case this - * OffetGrabPoint is unwittingly a child of itself. - */ - protected boolean overflowLock = false; - - /** - * Go through all the Offset elements and changes their position on the map. - * Should be called when the OffsetGrabPoint has been moved and you want to - * move all the GrabPoints in its list. - */ - public synchronized void moveOffsets() { - if (!overflowLock) { - overflowLock = true; - for (Offset offset : offsetPoints.values()) { - offset.move(); - } - overflowLock = false; - } - } - - /** - * Go through all the Offset elements and update the relative position to - * this grab point. Should be called when you set the position of the - * OffsetGrabPoint and you want to set the offset distances of all the - * GrabPoints in the internal list. - */ - public synchronized void updateOffsets() { - if (!overflowLock) { - overflowLock = true; - for (Offset offset : offsetPoints.values()) { - offset.update(); - } - overflowLock = false; - } - } - - public void clear() { - offsetPoints.clear(); - } - - protected void finalize() { - offsetPoints.clear(); - } - - /** - * A wrapper class of the internal GrabPoints. Contains their pixel offset - * distance from the OffsetGrabPoint. - */ - public class Offset { - public GrabPoint gp; - public int offsetX; - public int offsetY; - - public Offset(GrabPoint grabPoint) { - gp = grabPoint; - update(); - } - - /** - * Update resets the pixel offsets from the OffsetGrabPoint, to the - * current distances between the GrabPoint and the OffsetGrabPoint. - */ - public void update() { - offsetX = gp.getX() - getX(); - offsetY = gp.getY() - getY(); - if (gp instanceof OffsetGrabPoint) { - ((OffsetGrabPoint) gp).updateOffsets(); - } - } - - /** - * Move relocates the GrabPoint to the current position of the - * OffsetGrabPoint plus the offset distances. - */ - public void move() { - int newX = getX() + offsetX; - int newY = getY() + offsetY; - - if (gp instanceof HorizontalGrabPoint) { - ((HorizontalGrabPoint) gp).set(newX, newY, true); - } else if (gp instanceof VerticalGrabPoint) { - ((VerticalGrabPoint) gp).set(newX, newY, true); - } else { - gp.set(newX, newY); - } - - if (gp instanceof OffsetGrabPoint) { - ((OffsetGrabPoint) gp).moveOffsets(); - } - } - - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/SinkGraphic.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/SinkGraphic.java deleted file mode 100644 index 6f150e759..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/SinkGraphic.java +++ /dev/null @@ -1,99 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/SinkGraphic.java,v $ -// $RCSfile: SinkGraphic.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; - -import com.bbn.openmap.proj.Projection; - -/** - * This graphic is a Sink. You can use it as a placeholder, say in an - * OMGraphicList. It is never visible, and you can use the single - * shared instance in as many places as you want. This shared instance - * is multithreaded safe. - * - * @see OMGraphic - */ -public class SinkGraphic extends OMGraphicAdapter implements OMGraphic { - - // the shared instance - private static transient SinkGraphic sharedInstance; - - // cannot construct - private SinkGraphic() {} - - /** - * Get a shared instance of the SinkGraphic. - * - * @return SinkGraphic shared instance - */ - public final static SinkGraphic getSharedInstance() { - if (sharedInstance == null) - sharedInstance = new SinkGraphic(); - return sharedInstance; - } - - /** - * This graphic is not visible. - * - * @param visible IGNORED - */ - public void setVisible(boolean visible) {} - - /** - * This graphic is not visible. - * - * @return false - */ - public boolean isVisible() { - return false; - } - - /** - * This graphic generates nothing, successfully. - * - * @param proj IGNORED - * @return true - */ - public boolean generate(Projection proj) { - return true; - } - - /** - * This graphic does not render. - * - * @param g IGNORED - */ - public void render(Graphics g) {} - - /** - * This graphic is at Float.POSITIVE_INFINITY. - * - * @param x IGNORED - * @param y IGNORED - * @return Float.POSITIVE_INFINITY - */ - public float distance(double x, double y) { - return Float.POSITIVE_INFINITY; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/VerticalGrabPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/VerticalGrabPoint.java deleted file mode 100644 index 8a6048d47..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/VerticalGrabPoint.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/VerticalGrabPoint.java,v $ -// $RCSfile: VerticalGrabPoint.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/** - * A GrabPoint that can only move in the vertical direction. - */ -public class VerticalGrabPoint extends GrabPoint { - - public VerticalGrabPoint(int x, int y) { - super(x, y); - } - - /** - * x is ignored, since it can't affect the horizontal movement of - * a VerticalGrabPoint. - */ - public void set(int x, int y) { - setY(y); - } - - /** - * Move the point. - * - * @param x the new x location - * @param y the new y location - * @param override true if the horizontal limitation should be - * ignored. - */ - public void set(int x, int y, boolean override) { - if (override) { - super.set(x, y); - } else { - setY(y); - } - } - - /** - * No action, because horizontal movement is limited. - */ - public void setX(int x) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/AbstractShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/AbstractShapeDecoration.java deleted file mode 100644 index be0031c22..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/AbstractShapeDecoration.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Stroke; - -/** - * A minimal implementation of ShapeDecoration, adds members and - * accessors for graphic attributes : - *
    - *
  • length : the decoration length, along the path to decorate - *
  • - *
  • width : the decoration width, normal to the path to decorate - *
  • - *
  • orientation : the decoration is on the left or on the right of - * the path
  • - *
  • stroke, paint : the stroke and paint to be used
  • - *
- * - * @author Eric LEPICIER - * @version 27 juil. 2002 - */ -public abstract class AbstractShapeDecoration implements ShapeDecoration { - - private float width; - private float length; - private int orientation; - private Stroke stroke; - private Paint paint; - - private Stroke saveStroke; - private Paint savePaint; - - /** - * Constructor. - * - * @param length - * @param width - * @param orientation - */ - public AbstractShapeDecoration(float length, float width, int orientation) { - this.length = length; - this.width = width; - this.orientation = orientation; - } - - /** - * Returns the length. - * - * @return float - */ - public float getLength() { - return length; - } - - /** - * Sets the length. - * - * @param length The length to set - */ - public void setLength(float length) { - this.length = length; - } - - /** - * Returns the width. - * - * @return float - */ - public float getWidth() { - return width; - } - - /** - * Sets the width. - * - * @param width The width to set - */ - public void setWidth(float width) { - this.width = width; - } - - /** - * Returns the orientation. - * - * @return int - */ - public int getOrientation() { - return orientation; - } - - /** - * Sets the orientation. - * - * @param orientation The orientation to set - */ - public void setOrientation(int orientation) { - this.orientation = orientation; - } - - /** - * Reverts the orientation - * - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#revert() - */ - public void revert() { - orientation = orientation == RIGHT ? LEFT : RIGHT; - } - - /** - * Returns the paint. - * - * @return Paint - */ - public Paint getPaint() { - return paint; - } - - /** - * Returns the stroke. - * - * @return Stroke - */ - public Stroke getStroke() { - return stroke; - } - - /** - * Sets the paint. - * - * @param paint The paint to set - */ - public void setPaint(Paint paint) { - this.paint = paint; - } - - /** - * Sets the stroke. - * - * @param stroke The stroke to set - */ - public void setStroke(Stroke stroke) { - this.stroke = stroke; - } - - /** - * Applies stroke and paint to the Graphics, saving previous - * settings - * - * @param g - */ - protected void setGraphics(Graphics g) { - Graphics2D g2D = (Graphics2D) g; - saveStroke = g2D.getStroke(); - savePaint = g2D.getPaint(); - if (stroke != null) - g2D.setStroke(stroke); - if (paint != null) - g2D.setPaint(paint); - } - - /** - * Restores previous settings to the Graphics. Beware : no - * verification is made to be sure that it is the same Graphics - * ... - * - * @param g - */ - protected void restoreGraphics(Graphics g) { - Graphics2D g2D = (Graphics2D) g; - g2D.setStroke(saveStroke); - g2D.setPaint(savePaint); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/CircleShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/CircleShapeDecoration.java deleted file mode 100644 index 49b2bb668..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/CircleShapeDecoration.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.Paint; -import java.awt.geom.Point2D; - -/** - * A ShapeDecoration that draws a circle on the path. - */ -public class CircleShapeDecoration extends AbstractShapeDecoration { - - /** - */ - private boolean filled = true; - - /** - * Constructor. - * - * @param length number of pixels of segment to draw circle in. - * @param radius number of pixels for radius of circle. - */ - public CircleShapeDecoration(int length, int radius) { - super(length, radius, RIGHT); - } - - /** - * Constructor. - * - * @param length number of pixels of segment to draw circle in. - * @param radius number of pixels for radius of circle. - * @param paint the Paint to use for the circle. - */ - public CircleShapeDecoration(int length, int radius, Paint paint) { - super(length, radius, RIGHT); - setPaint(paint); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - - int nbpts = points.length; - - double xcoord1 = points[0].getX(); - double ycoord1 = points[0].getY(); - double xcoord2 = points[nbpts - 1].getX(); - double ycoord2 = points[nbpts - 1].getY(); - - if (complete) { - - // Compute cosinus and sinus of rotation angle - double dx = xcoord2 - xcoord1; - double dy = ycoord2 - ycoord1; - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = getLength() / 2.0; // x radius before rotation - double w = getWidth(); - // rotate - - int x = (int) (xcoord1 + r * rcos); - int y = (int) (ycoord1 + r * rsin); - - if (filled) { - g.fillOval((int) (x - w / 2), - (int) (y - w / 2), - (int) (w), - (int) (w)); - } else { - g.drawOval((int) (x - w / 2), - (int) (y - w / 2), - (int) (w), - (int) (w)); - } - } - - restoreGraphics(g); - } - - /** - * Returns the filled boolean. - * - * @return boolean - */ - public boolean isFilled() { - return filled; - } - - /** - * Sets the filled (draw a half disk or a half circle ?). - * - * @param filled The filled to set - */ - public void setFilled(boolean filled) { - this.filled = filled; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/GapDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/GapDecoration.java deleted file mode 100644 index 2b021fe04..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/GapDecoration.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.BasicStroke; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.util.logging.Logger; - -/** - * A decoration that attempts to draw a line on either side of a source line. - * The stroke width is the overall sideways coverage of the two lines, and the - * gap width is the space between them. - * - *
- * sd.addDecoration(new GapDecoration(8f, 5f, Color.gray));
- * 
- * - * TODO - seems a little shakey, but kinda provides the desired effect. Just saving work... - * - * @author dietrick - */ -public class GapDecoration extends AbstractShapeDecoration { - float gapWidth; - - public GapDecoration(float strokeWidth, float gapWidth, Paint color) { - super(2, strokeWidth, RIGHT); - this.gapWidth = gapWidth; - setStroke(new BasicStroke((strokeWidth - gapWidth) / 2)); - setPaint(color); - } - - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - ((Graphics2D) g).setStroke(getStroke()); - - int nbpts = points.length; - - double xcoord1 = points[0].getX(); - double ycoord1 = points[0].getY(); - double xcoord2 = points[nbpts - 1].getX(); - double ycoord2 = points[nbpts - 1].getY(); - - if (complete) { - - // Compute cosinus and sinus of rotation angle - double dx = xcoord2 - xcoord1; - double dy = ycoord2 - ycoord1; - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = getLength() / 2.0; // x radius before rotation - double w = -getWidth(); // y radius before rotation - - // rotate - // This is the middle point of the line that goes across. - int x2 = (int) (xcoord2 + r * rcos); - int y2 = (int) (ycoord2 + r * rsin); - - int x1 = (int) (xcoord1 + r * rcos); - int y1 = (int) (ycoord1 + r * rsin); - - g.drawLine((int) (x1 - w * rsin), (int) (y1 + w * rcos), (int) (x2 - w * rsin), (int) (y2 + w * rcos)); - - w = getWidth(); // y radius before rotation - g.drawLine((int) (x1 - w * rsin), (int) (y1 + w * rcos), (int) (x2 - w * rsin), (int) (y2 + w * rcos)); - } - - restoreGraphics(g); - - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(GapDecoration.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineShapeDecoration.java deleted file mode 100644 index 6f1283e9c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineShapeDecoration.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Stroke; -import java.awt.geom.Point2D; - -/** - * A decoration which is just a line. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class LineShapeDecoration extends SpacingShapeDecoration { - - /** - * Constructor. - * - * @param length - */ - public LineShapeDecoration(float length) { - super(length); - } - - /** - * Constructor. - * - * @param length - * @param paint - */ - public LineShapeDecoration(float length, Paint paint) { - super(length); - setPaint(paint); - } - - /** - * Constructor. - * - * @param length - * @param paint - * @param stroke - */ - public LineShapeDecoration(float length, Paint paint, Stroke stroke) { - super(length); - setPaint(paint); - setStroke(stroke); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - Graphics2D g2D = (Graphics2D) g; - setGraphics(g2D); - // we just need to draw the poly line - for (int i = 0; i < points.length - 1; i++) - g2D.drawLine((int) points[i].getX(), - (int) points[i].getY(), - (int) points[i + 1].getX(), - (int) points[i + 1].getY()); - restoreGraphics(g2D); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineUtil.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineUtil.java deleted file mode 100644 index 15f7d79e0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/LineUtil.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.geom.Point2D; -import java.util.LinkedList; - -import com.bbn.openmap.util.MoreMath; - -/** - * Various computations about plane geometry. - * - * @author Eric LEPICIER from Pascal HAURIE 1997 - * @version 11 aot 2002 - */ -public class LineUtil { - - private static float FLT_EPSILON = 1.192092896E-07F; - - /** - * Computes the segment square length - * - * @param A the begin point - * @param B the end point - * @return double the square distance between A and B - */ - public static double norm2(Point2D A, Point2D B) { - return (A.getX() - B.getX()) * (A.getX() - B.getX()) + (A.getY() - B.getY()) * (A.getY() - B.getY()); - } - - /** - * Computes the segment length - * - * @param A the begin point - * @param B the end point - * @return double the distance between A and B - */ - public static double norm(Point2D A, Point2D B) { - return Math.sqrt(norm2(A, B)); - } - - /** - * Interpolates a point on a segment. - * - * @param A the begin point - * @param B the end point - * @param d the distance from A to the wanted point - * @return Point2D the point at distance d from A on the segment AB, the - * point B if d>AB - */ - public static Point2D interpolatedPoint(Point2D A, Point2D B, double d) { - - double r = Math.sqrt(d * d / norm2(A, B)); - - if (r < FLT_EPSILON) - return A; - if (1 - r < FLT_EPSILON) - return B; - - Point2D P = new Point2D.Double(r * B.getX() + (1 - r) * A.getX(), r * B.getY() + (1 - r) * A.getY()); - return P; - } - - /** - * Extract a length on a polyline. - * - * @param length the curve length to extract from points - * @param points the original points - * @param polysegment the returned points - * @return true if we got the desired length, false otherwise - */ - protected static boolean retrievePoints(float length, LinkedList points, LinkedList polysegment) { - polysegment.clear(); - - // first point - Point2D point = points.removeFirst(); - polysegment.add(point); - - double consumedLength = 0.0; - double norm = 0.0; - Point2D nextPoint = null; - - while (consumedLength < length && !points.isEmpty()) { - // consume points while distance is not reached - nextPoint = (Point2D) points.removeFirst(); - polysegment.add(nextPoint); - norm = LineUtil.norm(point, nextPoint); - consumedLength += norm; - point = nextPoint; - } - - if (MoreMath.approximately_equal(consumedLength, length)) { - // we got the exact distance with an existing point. - // we need to copy the last point back: it will be the - // first for the next call - points.addFirst(point); - return true; - } else { - if (consumedLength > length) { - // we went too far, we need to put back the last point - points.addFirst(polysegment.removeLast()); - consumedLength -= norm; - // and interpolate a new point - point = (Point2D) polysegment.getLast(); - double d = length - consumedLength; - // between point and nextPoint at distance d - Point2D interp = LineUtil.interpolatedPoint(point, nextPoint, d); - polysegment.add(interp); - points.addFirst(interp); - return true; - } else { - // no more points ! - return false; - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/Revertable.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/Revertable.java deleted file mode 100644 index 6a147434c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/Revertable.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -/** - * Something that can be reverted ! - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public interface Revertable { - /** - * Should reverts it. - */ - public void revert(); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SerializableTexturePaint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SerializableTexturePaint.java deleted file mode 100644 index 1eb37f27f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SerializableTexturePaint.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Copyright 2014 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.TexturePaint; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.lang.reflect.Field; - -import javax.imageio.ImageIO; - -/** - * A wrapper around TexturePaint objects that can be used to serialize them. Use - * these in OMGraphics if you set it in one of the paint attributes. - * - * @author carsten madsen - */ -public class SerializableTexturePaint extends TexturePaint implements Serializable { - - public SerializableTexturePaint(BufferedImage txtr, Rectangle2D anchor) { - super(txtr, anchor); - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - try { - - Field field = TexturePaint.class.getDeclaredField("tx"); - field.setAccessible(true); - double ttx = (Double) field.get(this); - oos.writeDouble(ttx); - - field = TexturePaint.class.getDeclaredField("ty"); - field.setAccessible(true); - double tty = (Double) field.get(this); - oos.writeDouble(tty); - - field = TexturePaint.class.getDeclaredField("sx"); - field.setAccessible(true); - double tsx = (Double) field.get(this); - oos.writeDouble(tsx); - - field = TexturePaint.class.getDeclaredField("sy"); - field.setAccessible(true); - double tsy = (Double) field.get(this); - oos.writeDouble(tsy); - - field = TexturePaint.class.getDeclaredField("bufImg"); - field.setAccessible(true); - BufferedImage img = (BufferedImage) field.get(this); - ImageIO.write(img, "jpeg", ImageIO.createImageOutputStream(oos)); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { - try { - Field field = TexturePaint.class.getDeclaredField("tx"); - field.setAccessible(true); - field.set(this, ois.readDouble()); - - field = TexturePaint.class.getDeclaredField("ty"); - field.setAccessible(true); - field.set(this, ois.readDouble()); - - field = TexturePaint.class.getDeclaredField("sx"); - field.setAccessible(true); - field.set(this, ois.readDouble()); - - field = TexturePaint.class.getDeclaredField("sy"); - field.setAccessible(true); - field.set(this, ois.readDouble()); - - field = TexturePaint.class.getDeclaredField("bufImg"); - field.setAccessible(true); - field.set(this, ImageIO.read(ImageIO.createImageInputStream(ois))); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java deleted file mode 100644 index 2b879823f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.geom.Point2D; - -/** - * A ShapeDecoration is a basic element to be drawn along a path by a - * ShapeDecorator. The decoration length is measured along the path to decorate, - * the width, on a normal to the path. The decoration may be on the left or on - * the right of the path. - * - * - * @author Eric LEPICIER - * @version 26 juil. 2002 - */ -public interface ShapeDecoration extends Revertable { - - /** - * The right orientation constant - */ - public static final int RIGHT = 1; - /** - * The left orientation constant - */ - public static final int LEFT = 2; - - /** - * Returns the length. - * - * @return float - */ - public float getLength(); - - /** - * Returns the width. - * - * @return float - */ - public float getWidth(); - - /** - * Returns the orientation. - * - * @return int - */ - public int getOrientation(); - - /** - * Sets the orientation. - * - * @param orientation The orientation to set - */ - public void setOrientation(int orientation); - - /** - * reverts the orientation - */ - public void revert(); - - /** - * Draws itself along the specified polyline Called by ShapeDecorator - * - * @see com.bbn.openmap.omGraphics.awt.ShapeDecorator#draw(Graphics, - * Point2D[]) - * @param g - * @param points the polyline - * @param complete true if the polyline length equals the decoration length - */ - public void draw(Graphics g, Point2D[] points, boolean complete); -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecorator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecorator.java deleted file mode 100644 index f64e6e0e0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeDecorator.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.Shape; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * The ShapeDecorator class : in charge of drawing repeatedly several - * stored decorations along a path (a polyline or a complex shape) - * - * @author Eric LEPICIER - * @version 26 juil. 2002 - */ -public class ShapeDecorator implements Revertable { - - /** - * The list of decorations (instances of ShapeDecoration) - */ - private List decorations = new ArrayList(); - - /** - * The flatness used for Shape.getPathIterator() - */ - public static double FLATNESS = 0.1; - - /** - * Default constructor - */ - public ShapeDecorator() {} - - /** - * Returns the decorations. - * - * @return List the list of decorations - */ - public List getDecorations() { - return decorations; - } - - /** - * Inserts a Decoration. - * - * @param index the index where to insert the new decoration - * @param decoration the new decoration - */ - public void insertDecoration(int index, ShapeDecoration decoration) { - decorations.add(index, decoration); - } - - /** - * Adds a Decoration at the end of the list. - * - * @param decoration the new decoration - */ - public void addDecoration(ShapeDecoration decoration) { - decorations.add(decoration); - } - - /** - * Removes a Decoration. - * - * @param index the index of the Decoration to be removed - * @return ShapeDecoration the removed Decoration - */ - public ShapeDecoration removeDecoration(int index) { - return decorations.remove(index); - } - - /** - * Removes a Decoration. - * - * @param decoration the decoration to remove - * @return boolean true if it was removed - */ - public boolean removeDecoration(ShapeDecoration decoration) { - return decorations.remove(decoration); - } - - /** - * Reverts all the decorations - * - * @see com.bbn.openmap.omGraphics.awt.Revertable#revert() - */ - public void revert() { - for (ShapeDecoration shapeDecoration : decorations) { - shapeDecoration.revert(); - } - } - - /** - * Draws a decorated shape - * - * @param g the Graphics to use - * @param s the shape to render - */ - public void draw(Graphics g, Shape s) { - - if (decorations.isEmpty()) - return; - - PathIterator pi = s.getPathIterator(null, FLATNESS); - int segType; - double[] segCoords = new double[6]; - - LinkedList points = new LinkedList(); - Point2D firstPoint = null; - Point2D point; - - // split path in polylines - do { - segType = pi.currentSegment(segCoords); - point = new Point2D.Double(segCoords[0], segCoords[1]); - - switch (segType) { - case PathIterator.SEG_MOVETO: - if (firstPoint == null) - firstPoint = point; - - if (!points.isEmpty()) { - // draw decorations for the previous polyline - draw(g, points); - } - // init a new polyline - points.clear(); - points.add(point); - break; - case PathIterator.SEG_LINETO: - points.add(point); - break; - case PathIterator.SEG_CLOSE: - points.add(firstPoint); - break; - } - pi.next(); - } while (!pi.isDone()); - - // draw decorations for the last poly - if (!points.isEmpty()) { - draw(g, points); - } - } - - /** - * Draws a decorated polyline - * - * @param g the Graphics to use - * @param xcoords array of x floating coordinates - * @param ycoords array of y floating coordinates - */ - public void draw(Graphics g, float xcoords[], float[] ycoords) { - LinkedList points = new LinkedList(); - for (int i = 0; i < xcoords.length; i++) { - points.add(new Point2D.Double(xcoords[i], ycoords[i])); - } - draw(g, points); - } - - /** - * Draws a decorated polyline - * - * @param g the Graphics to use - * @param xcoords array of x integer coordinates - * @param ycoords array of y integer coordinates - */ - public void draw(Graphics g, int xcoords[], int[] ycoords) { - LinkedList points = new LinkedList(); - for (int i = 0; i < xcoords.length; i++) - points.add(new Point2D.Double(xcoords[i], ycoords[i])); - draw(g, points); - } - - /** - * Draws a decorated polyline - * - * @param g the Graphics to use - * @param points array of points - */ - public void draw(Graphics g, Point2D[] points) { - LinkedList pointlist = new LinkedList(); - for (int i = 0; i < points.length; i++) - pointlist.add(points[i]); - draw(g, pointlist); - } - - /** - * Draws a decorated polyline Calls ShapeDecoration.draw(...) for - * each decoration on an subsetted polyline with the same length - * than the decoration, cycling until all the path is consumed. - * - * @param g the Graphics to use - * @param points array of points (instances of Point2D) - */ - protected void draw(Graphics g, LinkedList points) { - - if (decorations.isEmpty()) - throw new NullPointerException("No decorations"); - - Iterator decorationIterator = decorations.listIterator(); - LinkedList polysegment = new LinkedList(); - Point2D[] point2DArrayType = new Point2D.Double[1]; - - while (!points.isEmpty()) { - if (!decorationIterator.hasNext()) { - decorationIterator = decorations.listIterator(); - } - ShapeDecoration decor = decorationIterator.next(); - - boolean complete = LineUtil.retrievePoints(decor.getLength(), - points, - polysegment); - // drawing is delegated to the decoration - decor.draw(g, - (Point2D[]) polysegment.toArray(point2DArrayType), - complete); - } - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeRenderer.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeRenderer.java deleted file mode 100644 index 7708679f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/ShapeRenderer.java +++ /dev/null @@ -1,47 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ShapeRenderer.java,v $ -//$Revision: 1.1 $ -//$Date: 2009/01/21 01:24:42 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics2D; -import java.awt.Shape; - -public interface ShapeRenderer { - - /** - * Render the Shape into the Graphics2D object. - */ - public void render(Graphics2D g, Shape shape); - - /** - * Render the Shape into the Graphics2D object. - * - * @param g java.awt.Graphics2D object to render into - * @param shape java.awt.Shape to draw - * @param replaceColorWithGradient flag to specify replacement of fill and - * edge colors with a GradientPaint to give a light to dark look. - */ - public void render(Graphics2D g, Shape shape, - boolean replaceColorWithGradient); -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SpacingShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SpacingShapeDecoration.java deleted file mode 100644 index c6eb660c2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/SpacingShapeDecoration.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.geom.Point2D; - -/** - * The most simple decoration : space. - * - * @author Eric LEPICIER - * @version 27 juil. 2002 - */ -public class SpacingShapeDecoration extends AbstractShapeDecoration { - - /** - * Constructor. - * - * @param length - */ - public SpacingShapeDecoration(float length) { - super(length, 0.0f, LEFT); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - // nothing to do, it's space ! - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/TextShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/TextShapeDecoration.java deleted file mode 100644 index 39fdf4ae4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/TextShapeDecoration.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.LinkedList; - -/** - * A ShapeDecoration that draws a text along a path - * - * @author Eric LEPICIER - * @version 16 aot 2002 - */ -public class TextShapeDecoration - extends AbstractShapeDecoration { - private String text; - private Font font = null; - private int verticalAlignment = BASELINE; - - /** Baseline vertical alignment */ - public final static int BASELINE = 1; - /** Center vertical alignment */ - public final static int CENTER = 2; - /** Top vertical alignment */ - public final static int TOP = 3; - /** Bottom vertical alignment */ - public final static int BOTTOM = 4; - - /** Orientation for the shape text decoration: use poly direction */ - public final static int FORWARD = LEFT; - /** - * Orientation for the shape text decoration: use reverse poly direction - */ - public final static int BACKWARD = RIGHT; - /** Orientation for the shape text decoration: force left to right */ - public final static int LEFT_TO_RIGHT = 3; - /** Orientation for the shape text decoration: force right to left */ - public final static int RIGHT_TO_LEFT = 4; - /** Orientation for the shape text decoration: force top to bottom */ - public final static int TOP_TO_BOTTOM = 5; - /** Orientation for the shape text decoration: force bottom to top */ - public final static int BOTTOM_TO_TOP = 6; - /** - * Orientation for the shape text decoration: occidental reading use - */ - public final static int MOST_READABLE = 7; - - /** - * Text will follow the poly instead of being written on the segment from - * begin to end of the poly, also allow text to be uncomplete. You may add - * this one to the other constants - */ - public final static int FOLLOW_POLY = 16; - - private transient FontMetrics metrics; - private transient Graphics2D g2D = null; - - /** - * Constructor. - * - * @param text - * @param font - * @param orientation - * @param verticalAlignment - */ - public TextShapeDecoration(String text, Font font, int orientation, int verticalAlignment) { - super(0.0f, 0.0f, orientation); - setVerticalAlignment(verticalAlignment); - setFont(font); - setText(text); - initMetrics(); - } - - /** - * Constructor. - * - * @param text - */ - public TextShapeDecoration(String text) { - super(0.0f, 0.0f, FORWARD); - setVerticalAlignment(BASELINE); - setText(text); - initMetrics(); - } - - /** - * init Metrics used to get string graphic length. - * - * @param object - */ - private void initMetrics() { - if (g2D == null) - g2D = (Graphics2D) new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB).getGraphics(); - if (font == null) - font = g2D.getFont(); - metrics = g2D.getFontMetrics(font); - } - - /** - * Draws the text along the polyline - * - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - - g2D = (Graphics2D) g; - initMetrics(); - g.setFont(font); - - int x1 = (int) points[0].getX(); - int y1 = (int) points[0].getY(); - int x2 = (int) points[points.length - 1].getX(); - int y2 = (int) points[points.length - 1].getY(); - - boolean reverse = needToReverse(x1, y1, x2, y2); - - // draw the text exactly on the curve, even uncomplete - if ((getOrientation() & FOLLOW_POLY) > 0) { - drawFollow(g, points, reverse); - return; - } - - // if there's not enough room, do nothing - if (!complete) - return; - - // else plot the text straight on the half segment - // from start to end point and away - int x, y; - double angle; - if (reverse) { - x = x2; - y = y2; - angle = Math.atan2(y1 - y2, x1 - x2); - } else { - x = x1; - y = y1; - angle = Math.atan2(y2 - y1, x2 - x1); - } - - // adjust vertical alignment - switch (verticalAlignment) { - case TOP: - y += metrics.getAscent(); - break; - case BOTTOM: - y -= metrics.getDescent(); - break; - case CENTER: - y += metrics.getAscent() - (metrics.getHeight()) / 2; - break; - case BASELINE: - break; - } - - drawAngledString(g, text, x, y, angle); - } - - /** - * Returns true if the polyline need to be reverted for the text to be drawn - * with the specified orientation. - * - * @param x1 starting point x coordinate - * @param y1 starting point y coordinate - * @param x2 ending point x coordinate - * @param y2 ending point y coordinate - * @return boolean - */ - protected boolean needToReverse(int x1, int y1, int x2, int y2) { - boolean reverse = false; - switch (getOrientation() & ~FOLLOW_POLY) { - case FORWARD: - break; - case BACKWARD: - reverse = true; - break; - case LEFT_TO_RIGHT: - reverse = x1 > x2; - break; - case RIGHT_TO_LEFT: - reverse = x1 < x2; - break; - case TOP_TO_BOTTOM: - reverse = y1 > y2; - break; - case BOTTOM_TO_TOP: - reverse = y1 < y2; - break; - case MOST_READABLE: - reverse = x2 < x1 || y1 > y2; - break; - } - return reverse; - } - - /** - * Draws the text character per character to follow the polyline - * - * @param g - * @param pts - * @param reverse - */ - protected void drawFollow(Graphics g, Point2D[] pts, boolean reverse) { - LinkedList points = new LinkedList(); - if (reverse) { - for (int i = pts.length - 1; i >= 0; i--) - points.add(pts[i]); - } else { - for (int i = 0; i < pts.length; i++) - points.add(pts[i]); - } - - LinkedList polysegment = new LinkedList(); - int l, x1, y1, x2, y2; - String c; - Point2D p1, p2; - double angle; - for (int i = 0; i < text.length(); i++) { - c = text.substring(i, i + 1); - l = metrics.stringWidth(c); - if (points.isEmpty()) - break; - LineUtil.retrievePoints(l, points, polysegment); - - p1 = (Point2D) polysegment.getFirst(); - x1 = (int) p1.getX(); - y1 = (int) p1.getY(); - p2 = (Point2D) polysegment.getLast(); - x2 = (int) p2.getX(); - y2 = (int) p2.getY(); - - angle = Math.atan2(y2 - y1, x2 - x1); - drawAngledString(g, c, x1, y1, angle); - } - } - - /** - * Draws the text from a starting point with an angle - * - * @param g - * @param text - * @param x - * @param y - * @param angle - */ - public static void drawAngledString(Graphics g, String text, int x, int y, double angle) { - - Graphics2D g2D = (Graphics2D) g; - AffineTransform oldAt = g2D.getTransform(); - AffineTransform at = new AffineTransform(oldAt); - at.rotate(angle, x, y); - g2D.setTransform(at); - g2D.drawString(text, x, y); - g2D.setTransform(oldAt); - } - - /** - * Returns the font. - * - * @return Font - */ - public Font getFont() { - return font; - } - - /** - * Returns the text. - * - * @return String - */ - public String getText() { - return text; - } - - /** - * Sets the font. - * - * @param font The font to set - */ - public void setFont(Font font) { - this.font = font; - initMetrics(); - } - - /** - * Sets the text. - * - * @param text The text to set - */ - public void setText(String text) { - this.text = text; - initMetrics(); - setLength(metrics.stringWidth(text)); - setWidth(metrics.getHeight()); - } - - /** - * Returns the verticalAlignment. - * - * @return int - */ - public int getVerticalAlignment() { - return verticalAlignment; - } - - /** - * Sets the verticalAlignment. - * - * @param verticalAlignment The verticalAlignment to set (TOP, CENTER, - * BASELINE, BOTTOM) - */ - public void setVerticalAlignment(int verticalAlignment) { - this.verticalAlignment = verticalAlignment; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/package.uml b/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/package.uml deleted file mode 100644 index e118de520..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/awt/package.uml +++ /dev/null @@ -1,15 +0,0 @@ -V[1.1:com.bbn.openmap.awt] -S[com.bbn.openmap.awt:LineShapeDecoration,com.bbn.openmap.awt:SpacingShapeDecoration]{2:(862,382),(1872,100)} -S[com.bbn.openmap.awt:SpacingShapeDecoration,com.bbn.openmap.awt:AbstractShapeDecoration]{2:(1944,100),(1370,440)} -S[com.bbn.openmap.awt:TextShapeDecoration,com.bbn.openmap.awt:AbstractShapeDecoration]{2:(1922,440),(1370,516)} -S[com.bbn.openmap.awt:AbstractShapeDecoration,com.bbn.openmap.awt:ShapeDecoration]{2:(1270,346),(1324,200)} -S[com.bbn.openmap.awt:ShapeDecoration,com.bbn.openmap.awt:Revertable]{2:(1208,72),(1190,68)} -S[com.bbn.openmap.awt:ShapeDecorator,com.bbn.openmap.awt:Revertable]{2:(1532,124),(1190,64)} -P[com.bbn.openmap.awt:AbstractShapeDecoration]{1044,346} -P[com.bbn.openmap.awt:LineShapeDecoration]{558,368} -P[com.bbn.openmap.awt:LineUtil]{734,168} -P[com.bbn.openmap.awt:Revertable]{1108,20} -P[com.bbn.openmap.awt:ShapeDecoration]{1208,20} -P[com.bbn.openmap.awt:ShapeDecorator]{1532,20} -P[com.bbn.openmap.awt:SpacingShapeDecoration]{1864,20} -P[com.bbn.openmap.awt:TextShapeDecoration]{1922,146} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSelectedState.java deleted file mode 100644 index b640c10ea..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSelectedState.java +++ /dev/null @@ -1,117 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/CircleSelectedState.java,v -// $ -// $RCSfile: CircleSelectedState.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMCircle; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class CircleSelectedState - extends GraphicSelectedState { - - public CircleSelectedState(EditableOMCircle eomc) { - super(eomc); - } - - /** - * In this state, we need to change states only if the graphic, or anyplace - * off the graphic is pressed down on. If the end points are clicked on, - * then we do nothing except set the moving point and go to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed"); - GrabPoint mp = graphic.getMovingPoint(e); - - int renderType = graphic.getGraphic().getRenderType(); - - // If the latlon circle is so small that all you can see is the center - // grab point, assume that we're grabbing the edge. We can do this by - // nulling out the moving point, if it's the same as the center grab - // point. - if (renderType == OMGraphic.RENDERTYPE_LATLON && mp == graphic.getGrabPoints()[EditableOMCircle.CENTER_POINT_INDEX] - && graphic.isMouseEventTouchingTheEdge(e)) { - mp = null; - } - - // If no grab point was selected, need to check if the graphic itself - // was clicked on. If so, then just go to selected mode. - if (mp == null) { - if ((renderType != OMGraphic.RENDERTYPE_LATLON && graphic.isMouseEventTouching(e)) - || graphic.isMouseEventTouchingTheEdge(e)) { - - if (graphic.getCanGrabGraphic()) { - // No point was selected, but the graphic was. Get - // ready - // to move the graphic. - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed - graphic held"); - graphic.getStateMachine().setEdit(); - - // This is the only difference in this method from - // the - // GraphicSelectedState.mousePressed method. - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - // ////// - - graphic.move(e); - } - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - graphic.redraw(e, true); - } - } else { - // else, if the moving point is set, go to edit mode. If - // the mouse is released, we'll consider ourselves - // unselected agin. - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", "CircleStateMachine|selected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp == null) { - if (graphic.getCanGrabGraphic() && graphic.isMouseEventTouchingTheEdge(e)) { - - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(CircleSelectedState.class, "Click_and_Drag_edge_to_resize.", - "Click and Drag edge to resize."), EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } - - } else { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(CircleSelectedState.class, "Click_and_Drag_to_change_the_graphic.", - "Click and Drag to change the graphic."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSetOffsetState.java deleted file mode 100644 index aa5d1cf36..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleSetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/CircleSetOffsetState.java,v -// $ -// $RCSfile: CircleSetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMCircle; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class CircleSetOffsetState extends GraphicSetOffsetState { - - public CircleSetOffsetState(EditableOMCircle eomc) { - super(eomc); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMCircle.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMCircle.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(CircleSetOffsetState.class, - "Click_to_place_offset_point_for_circle.", - "Click to place offset point for circle."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleStateMachine.java deleted file mode 100755 index e894d049a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleStateMachine.java +++ /dev/null @@ -1,57 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/CircleStateMachine.java,v -// $ -// $RCSfile: CircleStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMCircle; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class CircleStateMachine - extends EOMGStateMachine { - - public CircleStateMachine(EditableOMCircle circle) { - super(circle); - } - - protected State[] init() { - State[] states = super.init(); - Debug.message("eomc", "CircleStateMachine.init()"); - - // These are the only two states that need something special - // to happen. - states[GRAPHIC_UNDEFINED] = new CircleUndefinedState((EditableOMCircle) graphic); - states[GRAPHIC_SELECTED] = new CircleSelectedState((EditableOMCircle) graphic); - states[GRAPHIC_SETOFFSET] = new CircleSetOffsetState((EditableOMCircle) graphic); - states[GRAPHIC_EDIT] = new GraphicUndefinedEditState((EditableOMCircle) graphic); - states[GRAPHIC_EDIT] = new GraphicEditState((EditableOMCircle) graphic); - return states; - } - - protected void setInitialEdit() { - setEdit(); - if (getState(GRAPHIC_EDIT) instanceof GraphicUndefinedEditState) { - ((GraphicUndefinedEditState)getState(GRAPHIC_EDIT)).needAnotherPoint = true; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleUndefinedState.java deleted file mode 100644 index 79ace142f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/CircleUndefinedState.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/CircleUndefinedState.java,v -// $ -// $RCSfile: CircleUndefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.Debug; - -public class CircleUndefinedState extends ClckOrDrgUndefinedState { - - public CircleUndefinedState(EditableOMCircle eomc) { - super(eomc); - - } - - /** - * In this state, we need to draw a circle from scratch. So, we listen for a - * mouse down, and set both points there, and then set the mode to circle - * edit. This method is overridden because of weirdness with drawing - * circles and that EditableOMCircle/CircleStateMachine. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomc", "CircleStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - if (point1 == null) { - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - indexOfFirstPoint = EditableOMCircle.CENTER_POINT_INDEX; - indexOfSecondPoint = EditableOMCircle.RADIUS_POINT_INDEX; - } else if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - indexOfFirstPoint = EditableOMCircle.OFFSET_POINT_INDEX; - indexOfSecondPoint = EditableOMCircle.SE_POINT_INDEX; - } else { - indexOfFirstPoint = EditableOMCircle.CENTER_POINT_INDEX; - indexOfSecondPoint = EditableOMCircle.SE_POINT_INDEX; - } - } - return super.mousePressed(e); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ClckOrDrgUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ClckOrDrgUndefinedState.java deleted file mode 100644 index 3737153f4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ClckOrDrgUndefinedState.java +++ /dev/null @@ -1,124 +0,0 @@ -// ********************************************************************** -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/RectUndefinedState.java,v -// $ -// $RCSfile: RectUndefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.Point; -import java.awt.event.MouseEvent; - -import javax.swing.SwingUtilities; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -/** - * This is a new GraphicUndefinedState for OMGraphics that can handle being - * defined with click or press setting the initial point, and then a mouse move - * or drag, respectively, causing placement of the second point. Good for lines, - * circles, rectangles. - * - * @author dietrick - */ -public class ClckOrDrgUndefinedState extends GraphicUndefinedState { - - public ClckOrDrgUndefinedState(EditableOMGraphic eomg) { - super(eomg); - } - - Point point1 = null; - int indexOfFirstPoint; - int indexOfSecondPoint; - - /** - * In this state, we need to draw a rect from scratch. So, we listen for a - * mouse down, and set both points there, and then set the mode to rect - * edit. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - - if (point1 == null) { - graphic.getGrabPoint(indexOfFirstPoint).set(e.getX(), e.getY()); - point1 = new Point(e.getX(), e.getY()); - - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - graphic.getStateMachine().setOffsetNeeded(true); - Debug.message("eomg", "GraphicStateMachine|undefined state| *offset needed*"); - } - - graphic.getGrabPoint(indexOfSecondPoint).set(e.getX(), e.getY()); - graphic.setMovingPoint(graphic.getGrabPoint(indexOfSecondPoint)); - } else { - graphic.redraw(e); - } - - return getMapMouseListenerResponse(); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|undefined state|mouseReleased = " - + graphic.getGraphic().getRenderType()); - // C'mon, point1 has to be set here, right? - if (point1.distance(e.getX(), e.getY()) > 5) { - - if ((graphic.getStateMachine()).isOffsetNeeded() == true) { - graphic.getStateMachine().setOffset(); - graphic.getStateMachine().setOffsetNeeded(false); - } else { - graphic.getStateMachine().setSelected(); - GrabPoint mp = graphic.getMovingPoint(); - - // If right mouse button not pressed, then it's a valid end to a - // modification. - if (!SwingUtilities.isRightMouseButton(e)) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNDO); - } - - if (mp == null && !graphic.getCanGrabGraphic()) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_SELECTED); - } else { - graphic.fireEvent(EOMGCursors.EDIT, "", e, EOMGEvent.EOMG_SELECTED); - } - } - - graphic.redraw(e, true); - graphic.setMovingPoint(null); - } - - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|undefined state|mouseMoved = " - + graphic.getGraphic().getRenderType()); - if (point1 != null) { - graphic.redraw(e); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|undefined state|mouseDragged = " - + graphic.getGraphic().getRenderType()); - if (point1 != null) { - graphic.redraw(e); - } - - return getMapMouseListenerResponse(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGAuxState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGAuxState.java deleted file mode 100644 index 5e518458f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGAuxState.java +++ /dev/null @@ -1,28 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGAuxState.java,v -// $ -// $RCSfile: EOMGAuxState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -public interface EOMGAuxState { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGCursors.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGCursors.java deleted file mode 100644 index bd9054f53..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGCursors.java +++ /dev/null @@ -1,77 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGCursors.java,v -// $ -// $RCSfile: EOMGCursors.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.Cursor; -import java.awt.Point; -import java.awt.Toolkit; -import java.net.URL; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.util.Debug; - -public class EOMGCursors { - - public final static Cursor DEFAULT = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); - - // public final static Cursor EDIT = create("edit.gif", new - // Point(0, 0), "EOMG_EDIT"); - // public final static Cursor PUTNODE = create("putnode.gif", new - // Point(0, 0), "EOMG_PUTNODE"); - // public final static Cursor MOVE = create("move.gif", new - // Point(8, 8), "EOMG_MOVE"); - - // public final static Cursor EDIT = - // Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); - // public final static Cursor PUTNODE = - // Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); - // public final static Cursor MOVE = - // Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - // public final static Cursor GRAB = - // Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - - public final static Cursor EDIT = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - public final static Cursor PUTNODE = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - public final static Cursor MOVE = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); - public final static Cursor GRAB = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); - - public EOMGCursors() { - } - - public static Cursor create(String resource, Point hotspot, String name) { - Cursor cursor = DEFAULT; - try { - - URL url = (new EOMGCursors()).getClass().getResource(resource); - ImageIcon image = new ImageIcon(url); - cursor = Toolkit.getDefaultToolkit().createCustomCursor(image.getImage(), hotspot, name); - - } catch (IndexOutOfBoundsException ioobe) { - Debug.error("LineStateMachine creating cursor:\n " + ioobe.getMessage()); - } - return cursor; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGDefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGDefinedState.java deleted file mode 100644 index a990c0a52..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGDefinedState.java +++ /dev/null @@ -1,28 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGDefinedState.java,v -// $ -// $RCSfile: EOMGDefinedState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -public interface EOMGDefinedState { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGEditState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGEditState.java deleted file mode 100644 index f549d8f89..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGEditState.java +++ /dev/null @@ -1,28 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGEditState.java,v -// $ -// $RCSfile: EOMGEditState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -public interface EOMGEditState { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGSelectedState.java deleted file mode 100644 index 3119d9b77..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGSelectedState.java +++ /dev/null @@ -1,28 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGSelectedState.java,v -// $ -// $RCSfile: EOMGSelectedState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -public interface EOMGSelectedState { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGStateMachine.java deleted file mode 100644 index cfce9c488..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGStateMachine.java +++ /dev/null @@ -1,126 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGStateMachine.java,v -// $ -// $RCSfile: EOMGStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -import com.bbn.openmap.util.stateMachine.StateMachine; -public class EOMGStateMachine extends StateMachine { - - public EditableOMGraphic graphic; - protected boolean offsetNeeded = false; - - /** The state when a graphic is not there yet, about to be drawn. */ - public final static int GRAPHIC_UNDEFINED = EOMGEvent.EOMG_UNDEFINED; // 0 - /** - * The state when an existing graphic is present, but has not been - * selected. At this point, the point nodes should not be visible, - * but the graphic is. - */ - public final static int GRAPHIC_UNSELECTED = EOMGEvent.EOMG_DEFINED; // 1 - /** - * The state when an existing graphic is selected, ready for - * change given the correct input. The point nodes and the graphic - * are visible. - */ - public final static int GRAPHIC_SELECTED = EOMGEvent.EOMG_SELECTED; // 2 - /** - * The state when the graphic points are in the process of - * changing. - */ - public final static int GRAPHIC_EDIT = EOMGEvent.EOMG_EDIT; // 3 - /** The state where an offset point needs to be defined. */ - public final static int GRAPHIC_SETOFFSET = EOMGEvent.EOMG_AUX; // 4 - - public final static int DEFAULT_NUMBER_STATES = 5; - - public int NUMBER_STATES = DEFAULT_NUMBER_STATES; - - public EOMGStateMachine(EditableOMGraphic graphic) { - this.graphic = graphic; - setStates(init()); - - // set reset state - setResetState(GRAPHIC_UNSELECTED); - reset(); - setMapMouseListenerResponses(true); - - Debug.message("eomg", "EOMGStateMachine created"); - } - - protected State[] init() { - Debug.message("eomg", "EOMGStateMachine.init()"); - State[] states = new State[NUMBER_STATES]; - - states[GRAPHIC_UNDEFINED] = new GraphicUndefinedState(graphic); - states[GRAPHIC_UNSELECTED] = new GraphicUnselectedState(graphic); - states[GRAPHIC_SELECTED] = new GraphicSelectedState(graphic); - states[GRAPHIC_EDIT] = new GraphicEditState(graphic); - states[GRAPHIC_SETOFFSET] = new GraphicSetOffsetState(graphic); - return states; - } - - /** - * Check to see if the graphic offset point needs to be defined. - */ - public boolean isOffsetNeeded() { - return offsetNeeded; - } - - /** - * The state machine, from the edit mode, tests this to see if an - * offset point needs to be defined. This is set to true when the - * OMGraphic (offset rendertype) is undefined. Can't be set every - * time the state machine gets in edit mode, because we may be - * just moving the graphic. Set to true if you want to define the - * offset point after defining the actual graphic, which should be - * done only for offset graphics. - */ - public void setOffsetNeeded(boolean set) { - offsetNeeded = set; - } - - public void setUndefined() { - setState(GRAPHIC_UNDEFINED); - } - - public void setUnselected() { - setState(GRAPHIC_UNSELECTED); - } - - public void setSelected() { - setState(GRAPHIC_SELECTED); - } - - public void setEdit() { - setState(GRAPHIC_EDIT); - } - - public void setOffset() { - setState(GRAPHIC_SETOFFSET); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGUndefinedState.java deleted file mode 100644 index e7f786820..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/EOMGUndefinedState.java +++ /dev/null @@ -1,28 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/EOMGUndefinedState.java,v -// $ -// $RCSfile: EOMGUndefinedState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -public interface EOMGUndefinedState { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicEditState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicEditState.java deleted file mode 100644 index 98d1cd1e5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicEditState.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicEditState.java,v -// $ -// $RCSfile: GraphicEditState.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import javax.swing.SwingUtilities; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class GraphicEditState - extends State - implements EOMGEditState { - - protected EditableOMGraphic graphic; - - public GraphicEditState(EditableOMGraphic eomg) { - graphic = eomg; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|edit state|mouseDragged"); - if (graphic.getMovingPoint() != null) { - graphic.redraw(e); - } else { - graphic.getStateMachine().setSelected(); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|edit state|mouseReleased"); - - if ((graphic.getStateMachine()).isOffsetNeeded() == true) { - graphic.getStateMachine().setOffset(); - graphic.getStateMachine().setOffsetNeeded(false); - } else { - graphic.getStateMachine().setSelected(); - GrabPoint mp = graphic.getMovingPoint(); - - // If right mouse button not pressed, then it's a valid end to a modification. - if (!SwingUtilities.isRightMouseButton(e)) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNDO); - } - - if (mp == null && !graphic.getCanGrabGraphic()) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_SELECTED); - } else { - graphic.fireEvent(EOMGCursors.EDIT, "", e, EOMGEvent.EOMG_SELECTED); - } - } - - graphic.redraw(e, true); - graphic.setMovingPoint(null); - - return getMapMouseListenerResponse(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSelectedState.java deleted file mode 100644 index d319b7d22..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSelectedState.java +++ /dev/null @@ -1,149 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicSelectedState.java,v -// $ -// $RCSfile: GraphicSelectedState.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import javax.swing.SwingUtilities; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class GraphicSelectedState - extends State - implements EOMGSelectedState { - - protected EditableOMGraphic graphic; - - public GraphicSelectedState(EditableOMGraphic eomg) { - graphic = eomg; - } - - /** - * In this state, we need to change states only if the graphic, or anyplace - * off the graphic is pressed down on. If the end points are clicked on, - * then we do nothing except set the moving point and go to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed"); - - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just go to - // selected - // mode. - if (mp == null) { - if (graphic.isMouseEventTouching(e)) { - if (graphic.getCanGrabGraphic()) { - - // No point was selected, but the graphic was. Get - // ready - // to move the graphic. - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed - graphic held"); - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.MOVE, "", EOMGEvent.EOMG_EDIT); - graphic.move(e); - } else { - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed - graphic can't be held"); - } - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } else { - Debug.message("eomg", "GraphicStateMachine|selected state|mousePressed - click off graphic"); - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - // Preparing for deactivation, why bother - // repainting... - // graphic.redraw(e, true); - } - } else { - // else, if the moving point is set, go to edit mode. If - // the mouse is released, we'll consider ourselves - // unselected again. - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - } - return getMapMouseListenerResponse(); - } - - /** - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|selected state|mouseReleased"); - - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just stay in - // selected mode. - if (mp == null) { - if (graphic.isMouseEventTouching(e) || SwingUtilities.isRightMouseButton(e)) { - if (graphic.getCanGrabGraphic()) { - - graphic.fireEvent(EOMGCursors.EDIT, "", e, EOMGEvent.EOMG_UNCHANGED); - graphic.redraw(e, true); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNCHANGED); - } - } else { - if (graphic.isPopupIsUp()) { - graphic.setPopupIsUp(false); - } else { - Debug.message("eomg", " deactivating with fired event"); - // If the graphic isn't picked, then need to - // deactivate with a deactivation event. - graphic.fireEvent(new EOMGEvent()); - } - } - } else { - // If the moving point was valid, just stay in selected - // mode. - graphic.fireEvent(EOMGCursors.EDIT, "", e, EOMGEvent.EOMG_UNCHANGED); - graphic.redraw(e, true); - } - - graphic.setMovingPoint(null); - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", "GraphicStateMachine|selected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp == null) { - if (graphic.isMouseEventTouching(e)) { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(GraphicSelectedState.class, "Click_and_Drag_to_move_the_graphic.", - "Click and Drag to move the graphic."), EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } - } else { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(GraphicSelectedState.class, "Click_and_Drag_to_change_the_graphic.", - "Click and Drag to change the graphic."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSetOffsetState.java deleted file mode 100644 index 55db1bc4b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicSetOffsetState.java +++ /dev/null @@ -1,87 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicSetOffsetState.java,v -// $ -// $RCSfile: GraphicSetOffsetState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class GraphicSetOffsetState extends State implements EOMGAuxState { - - protected EditableOMGraphic graphic; - - public GraphicSetOffsetState(EditableOMGraphic eomg) { - graphic = eomg; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomg", - "GraphicStateMachine|set offset state|mouseDragged"); - setGrabPoint(e); - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(CircleSetOffsetState.class, - "Click_to_place_offset_point.", - "Click to place offset point."), EOMGEvent.EOMG_UNCHANGED); - return getMapMouseListenerResponse(); - } - - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|set offset state|mousePressed"); - setGrabPoint(e); - return getMapMouseListenerResponse(); - } - - protected void setGrabPoint(MouseEvent e) { - // Each editable omgraphic should handle this. - - // OffsetGrabPoint ogb = - // (OffsetGrabPoint)graphic.getGrabPoint(EditableOMGraphic.OFFSET_POINT_INDEX); - // ogb.set(e.getX(), e.getY()); - // ogb.updateOffsets(); - - // graphic.setMovingPoint(graphic.getGrabPoint(EditableOMGraphic.OFFSET_POINT_INDEX)); - - // graphic.redraw(e); - // graphic.fireEvent(EOMGCursors.PUTNODE, "Click to place offset - // point for graphic."); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|edit state|mouseReleased"); - graphic.getStateMachine().setSelected(); - graphic.redraw(e, true); - graphic.setMovingPoint(null); - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_SELECTED); - return getMapMouseListenerResponse(); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedEditState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedEditState.java deleted file mode 100644 index 54a22b935..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedEditState.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicEditState.java,v -// $ -// $RCSfile: GraphicEditState.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; - -/** - * The GraphicUndefinedEditState is for a couple of OMGraphics that are still - * undefined when they are created after a first click. We can have the - * OMGraphic in an edit state, but we need to have a mouse released away from - * the first mouse pressed in order to have an OMGraphic that makes sense. For - * instance, circles and rectangles can't have just one point defined, so if - * only one point is defined, the mouse dragged and mouse moved actions should - * be the same, and then mouse release should mark the second definition point - * of the OMGraphic. - * - * @author ddietrick - */ -public class GraphicUndefinedEditState - extends GraphicEditState - implements EOMGEditState { - - protected boolean needAnotherPoint = false; - - public GraphicUndefinedEditState(EditableOMGraphic eomg) { - super(eomg); - } - - public boolean mouseDragged(MouseEvent e) { - needAnotherPoint = false; - return super.mouseDragged(e); - } - - public boolean mouseReleased(MouseEvent e) { - - if (needAnotherPoint) { - return false; - } - - return super.mouseReleased(e); - } - - public boolean mouseMoved(MouseEvent e) { - needAnotherPoint = false; - return super.mouseMoved(e); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedState.java deleted file mode 100644 index ff6a88818..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUndefinedState.java +++ /dev/null @@ -1,78 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicUndefinedState.java,v -// $ -// $RCSfile: GraphicUndefinedState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class GraphicUndefinedState extends State implements EOMGUndefinedState { - - protected EditableOMGraphic graphic; - - public GraphicUndefinedState(EditableOMGraphic eomg) { - graphic = eomg; - } - - /** - * In this state, we need to draw a graphic from scratch. So, we - * listen for a mouse down, and set both points there, and then - * set the mode to graphic edit. - */ - public boolean mousePressed(MouseEvent e) { - if (Debug.debugging("eomg")) { - Debug.output("GraphicStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - } - - // graphic.getGrabPoint(EditableOMGraphic.STARTING_POINT_INDEX).set(e.getX(), - // e.getY()); - // graphic.getGrabPoint(EditableOMGraphic.ENDING_POINT_INDEX).set(e.getX(), - // e.getY()); - // graphic.setMovingPoint(graphic.getGrabPoint(EditableOMGraphic.ENDING_POINT_INDEX)); - - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - graphic.getStateMachine().setOffsetNeeded(true); - Debug.message("eomg", - "GraphicStateMachine|undefined state| *offset needed*"); - } - graphic.getStateMachine().setEdit(); - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "GraphicStateMachine|undefined state|mouseMoved"); - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(GraphicUndefinedState.class, - "Click_and_Drag_to_define_graphic.", - "Click and Drag to define graphic."), EOMGEvent.EOMG_UNCHANGED); - return false; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUnselectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUnselectedState.java deleted file mode 100644 index bf0e3c9ca..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/GraphicUnselectedState.java +++ /dev/null @@ -1,134 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/GraphicUnselectedState.java,v -// $ -// $RCSfile: GraphicUnselectedState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class GraphicUnselectedState extends State implements EOMGDefinedState { - - protected EditableOMGraphic graphic; - - public GraphicUnselectedState(EditableOMGraphic eomg) { - graphic = eomg; - } - - /** - * In this state, we need to change states only if the graphic, or it's grab - * points are clicked on. If a point is clicked on, then it should become - * the moving point, and the graphic should be changed to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", - "GraphicStateMachine|unselected state|mousePressed"); - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just go to - // selected - // mode. - if (mp == null) { - if (graphic.isMouseEventTouching(e)) { - if (graphic.getCanGrabGraphic()) { - // OK, so a grab point has not been selected, but - // the graphic has been, and the button is down. - // We should be moving the end grab points of the - // graphic. If the graphic is not a - // RENDERTYPE_OFFSET graphic, then the - // OffsetGrabPoint is available to use for this. - // If the graphic is RENDERTYPE_OFFSET, then we - // need to create a OffsetGrabPoint to use - // temporarily to move just the end points. - Debug.message("eomg", - "GraphicStateMachine|unselected state|mousePressed - graphic held"); - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - // Prepare the graphic to move - graphic.move(e); - } else { - graphic.getStateMachine().setSelected(); - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_SELECTED); - } - // Clean up the map and redraw. - graphic.redraw(e, true); - } - } else { - // Else, set the moving point, and go to edit mode. If - // the mouse is released, we'll consider ourselves - // unselected again. - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - graphic.redraw(e, true); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", - "GraphicStateMachine|unselected state|mouseReleased"); - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just go to - // selected - // mode. - if (mp == null) { - if (graphic.isMouseEventTouching(e)) { - graphic.getStateMachine().setSelected(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_SELECTED); - } else { - graphic.setMovingPoint(new GrabPoint(e.getX(), e.getY())); - // OK, we're done, or at a crossroad. Give the - // listeners - // the MouseEvent so they can determine what to do, to - // end, or provide options... - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNCHANGED); - graphic.setMovingPoint(null); - } - graphic.redraw(e, true); - } else { - graphic.setMovingPoint(null); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "GraphicStateMachine|unselected state|mouseMoved"); - - if (graphic.isMouseEventTouching(e)) { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(GraphicUnselectedState.class, - "Click_to_select_the_graphic.", - "Click to select the graphic."), EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineSetOffsetState.java deleted file mode 100644 index 22978fc59..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineSetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/LineSetOffsetState.java,v -// $ -// $RCSfile: LineSetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMLine; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class LineSetOffsetState extends GraphicSetOffsetState { - - public LineSetOffsetState(EditableOMLine eoml) { - super(eoml); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMLine.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMLine.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(LineSetOffsetState.class, - "Click_to_place_offset_point_for_line.", - "Click to place offset point for line."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineStateMachine.java deleted file mode 100644 index 0c9ec488d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineStateMachine.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/LineStateMachine.java,v -// $ -// $RCSfile: LineStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMLine; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class LineStateMachine extends EOMGStateMachine { - - public LineStateMachine(EditableOMLine l) { - super(l); - } - - protected State[] init() { - State[] states = super.init(); - Debug.message("eoml", "LineStateMachine.init()"); - - // These are the only two states that need something special - // to happen. - states[GRAPHIC_UNDEFINED] = new LineUndefinedState((EditableOMLine) graphic); - states[GRAPHIC_SETOFFSET] = new LineSetOffsetState((EditableOMLine) graphic); - return states; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineUndefinedState.java deleted file mode 100644 index e6f6c53b4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/LineUndefinedState.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/LineUndefinedState.java,v -// $ -// $RCSfile: LineUndefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMLine; - -public class LineUndefinedState extends ClckOrDrgUndefinedState { - - public LineUndefinedState(EditableOMLine eoml) { - super(eoml); - indexOfFirstPoint = EditableOMLine.STARTING_POINT_INDEX; - indexOfSecondPoint = EditableOMLine.ENDING_POINT_INDEX; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListSelectedState.java deleted file mode 100644 index 519f3a123..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListSelectedState.java +++ /dev/null @@ -1,113 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ListSelectedState.java,v -// $ -// $RCSfile: ListSelectedState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class ListSelectedState extends GraphicSelectedState { - - public ListSelectedState(EditableOMGraphic eomg) { - super(eomg); - } - - /** - * In this state, we need to change states only if the graphic, or - * anyplace off the graphic is pressed down on. If the end points - * are clicked on, then we do nothing except set the moving point - * and go to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "ListStateMachine|selected state|mousePressed"); - - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just go to - // selected - // mode. - if (mp == null) { - // List is making a GrabPoint with a distance check, so if - // we get here, we don't have to do anything. - if (Debug.debugging("eomg")) { - float distance = graphic.getGraphic().distance(e.getX(), - e.getY()); - Debug.output("ListStateMachine|selected state|mousePressed - click off list, " - + distance + " away"); - } - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } else { - // else, if the moving point is set, go to edit mode. If - // the mouse is released, we'll consider ourselves - // unselected agin. - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_UNCHANGED); - } - return getMapMouseListenerResponse(); - } - - /** - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "ListStateMachine|selected state|mouseReleased"); - - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp == null) { - Debug.message("eomg", " deactivating with fired event"); - // If the graphic isn't picked, then need to - // deactivate with a deactivation event. - graphic.fireEvent(new EOMGEvent()); - } else { - // If the moving point was valid, just stay in selected - // mode. - graphic.fireEvent(EOMGCursors.EDIT, "", e, EOMGEvent.EOMG_UNCHANGED); - graphic.redraw(e, true); - } - - graphic.setMovingPoint(null); - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "ListStateMachine|selected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp == null) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(ListSelectedState.class, - "Click_and_Drag_to_change_the_graphic.", - "Click and Drag to change the graphic."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListStateMachine.java deleted file mode 100644 index 8340394c7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListStateMachine.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ListStateMachine.java,v -// $ -// $RCSfile: ListStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.util.Iterator; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMGraphicList; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class ListStateMachine extends EOMGStateMachine { - - public ListStateMachine(EditableOMGraphicList list) { - super(list); - } - - protected State[] init() { - Debug.message("eomg", "ListStateMachine.init()"); - State[] states = super.init(); - states[GRAPHIC_SELECTED] = new ListSelectedState(graphic); - states[GRAPHIC_UNSELECTED] = new ListUnselectedState(graphic); - return states; - } - - /** - * Check to see if the graphic offset point needs to be defined. - */ - public boolean isOffsetNeeded() { - return offsetNeeded; - } - - public void setState(int state) { - super.setState(state); - if (Debug.debugging("eomg")) { - Debug.output("ListStateMachine.setState: Setting state to " - + states.elementAt(state).getClass().getName()); - } - for (Iterator it = ((EditableOMGraphicList) graphic).getEditables() - .iterator(); it.hasNext();) { - try { - EditableOMGraphic editable = (EditableOMGraphic) it.next(); - editable.getStateMachine().setState(state); - - if (Debug.debugging("eomg")) { - Debug.debugging(" on " + editable.getClass().getName()); - } - } catch (NullPointerException npe) { - Debug.output("ListStateMachine: something's not right setting ListStateMachine.setState()"); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListUnselectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListUnselectedState.java deleted file mode 100644 index 9648f2b15..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ListUnselectedState.java +++ /dev/null @@ -1,88 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ListUnselectedState.java,v -// $ -// $RCSfile: ListUnselectedState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class ListUnselectedState extends GraphicUnselectedState { - - public ListUnselectedState(EditableOMGraphic eomg) { - super(eomg); - } - - /** - * In this state, we need to change states only if the graphic, or - * it's grab points are clicked on. If a point is clicked on, then - * it should become the moving point, and the graphic should be - * changed to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "ListStateMachine|unselected state|mousePressed"); - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp != null) { - // Else, set the moving point, and go to edit mode. If - // the mouse is released, we'll consider ourselves - // unselected again. - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_EDIT); - graphic.redraw(e, true); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "ListStateMachine|unselected state|mouseReleased"); - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp != null) { - graphic.getStateMachine().setSelected(); - graphic.fireEvent(EOMGCursors.EDIT, "", EOMGEvent.EOMG_SELECTED); - graphic.setMovingPoint(null); - } - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "ListStateMachine|unselected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - if (mp != null) { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(ListUnselectedState.class, - "Click_to_select_the_graphic.", - "Click to select the graphic."), EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointEditState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointEditState.java deleted file mode 100644 index 65e6cd21d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointEditState.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PointEditState.java,v -// $ -// $RCSfile: PointEditState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMPoint; -import com.bbn.openmap.util.Debug; - -public class PointEditState extends GraphicEditState implements EOMGEditState { - - public PointEditState(EditableOMPoint eomp) { - super(eomp); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "PointStateMachine|edit state|mouseReleased"); - graphic.setGrabPoints(); // Needed for OMPoints that are point - // and clicked for placement. - return super.mouseReleased(e); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointSetOffsetState.java deleted file mode 100644 index dcaf9aa1c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointSetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PointSetOffsetState.java,v -// $ -// $RCSfile: PointSetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMPoint; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class PointSetOffsetState extends GraphicSetOffsetState { - - public PointSetOffsetState(EditableOMPoint eomc) { - super(eomc); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMPoint.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMPoint.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(PointSetOffsetState.class, - "Click_to_place_offset_point.", - "Click to place offset point."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java deleted file mode 100644 index 9236d1b5d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java +++ /dev/null @@ -1,47 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PointStateMachine.java,v -// $ -// $RCSfile: PointStateMachine.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class PointStateMachine extends EOMGStateMachine { - - public PointStateMachine(EditableOMPoint point) { - super(point); - } - - protected State[] init() { - State[] states = super.init(); - Debug.message("eomg", "PointStateMachine.init()"); - - // These are the only two states that need something special - // to happen. - states[GRAPHIC_EDIT] = new PointEditState((EditableOMPoint) graphic); - states[GRAPHIC_UNDEFINED] = new PointUndefinedState((EditableOMPoint) graphic); - states[GRAPHIC_SETOFFSET] = new PointSetOffsetState((EditableOMPoint) graphic); - return states; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointUndefinedState.java deleted file mode 100644 index 091514ba6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PointUndefinedState.java +++ /dev/null @@ -1,73 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PointUndefinedState.java,v -// $ -// $RCSfile: PointUndefinedState.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMPoint; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class PointUndefinedState extends GraphicUndefinedState { - - public PointUndefinedState(EditableOMPoint eomp) { - super(eomp); - } - - /** - * In this state, we need to draw a rect from scratch. So, we - * listen for a mouse down, and set both points there, and then - * set the mode to rect edit. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", - "PointStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - - GrabPoint gb = graphic.getGrabPoint(EditableOMPoint.CENTER_POINT_INDEX); - gb.set(e.getX(), e.getY()); - graphic.setMovingPoint(gb); - - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - graphic.getGrabPoint(EditableOMPoint.OFFSET_POINT_INDEX) - .set(e.getX(), e.getY()); - graphic.getStateMachine().setOffsetNeeded(true); - Debug.message("eomg", - "PointStateMachine|undefined state| *offset needed*"); - } - - graphic.getStateMachine().setEdit(); - return getMapMouseListenerResponse(); - } - - public boolean mouseMoved(MouseEvent e) { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(PointUndefinedState.class, - "Click_to_define_the_point_location.", - "Click to define the point location."), EOMGEvent.EOMG_UNCHANGED); - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddNodeState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddNodeState.java deleted file mode 100644 index 1f249f4bd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddNodeState.java +++ /dev/null @@ -1,123 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolyAddNodeState.java,v -// $ -// $RCSfile: PolyAddNodeState.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class PolyAddNodeState - extends State { - protected EditableOMGraphic graphic; - - public PolyAddNodeState(EditableOMPoly eomg) { - graphic = eomg; - } - - /** - * In this state, we need to change states only if the graphic, or anyplace - * off the graphic is pressed down on. If the end points are clicked on, - * then we do nothing except set the moving point and go to edit mode. - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|add node state|mouseReleased"); - - GrabPoint mp = graphic.getMovingPoint(e); - - // If a node itself was clicked on, then just go to selected mode. - if (mp == null) { - - /** - * We need to find the segment that was clicked on, and then add a - * node between them. So, index needs to point to the grab point of - * the first grab point of the segment. - */ - if (graphic.isMouseEventTouching(e)) { - OMPoly poly = (OMPoly) graphic.getGraphic(); - double x = e.getX(); - double y = e.getY(); - if (poly.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - Point2D llp = graphic.getProjection().inverse(x, y); - x = llp.getX(); - y = llp.getY(); - } - - int index = poly.getIndexOfFirstNodeOfSegIntersect(x, y, 2); - // int index = ((EditableOMPoly) graphic).whichGrabPoint(mp); - - if (index != -1) { - ((EditableOMPoly) graphic).addPoint(e.getX(), e.getY(), index + 1); - - graphic.fireEvent(EOMGEvent.EOMG_SELECTED); - } - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNDO); - } - } - - graphic.getStateMachine().setSelected(); - graphic.redraw(e, true); - return false; - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|add node state|mouseMoved"); - - if (graphic.isMouseEventTouching(e)) { // Only change the cursor over - // graphic between nodes - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(PolyAddNodeState.class, "Click_between_nodes_to_add_another_node.", - "Click between nodes to add another node."), e, EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, i18n.get(PolyAddNodeState.class, "Click_between_nodes_to_add_another_node.", - "Click between nodes to add another node."), e, - EOMGEvent.EOMG_UNCHANGED); - } - - // graphic.redraw(e); - return false; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|add node state|mouseDragged"); - - if (graphic.getGraphic().distance(e.getX(), e.getY()) < 2) { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(PolyAddNodeState.class, "Release_between_nodes_to_add_a_node.", - "Release between nodes to add a node."), e, EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, i18n.get(PolyAddNodeState.class, "Release_between_nodes_to_add_a_node.", - "Release between nodes to add a node."), e, EOMGEvent.EOMG_UNCHANGED); - } - - // graphic.redraw(e); - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddPointState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddPointState.java deleted file mode 100644 index d217f1450..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyAddPointState.java +++ /dev/null @@ -1,87 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolyAddPointState.java,v -// $ -// $RCSfile: PolyAddPointState.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import javax.swing.SwingUtilities; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class PolyAddPointState - extends State { - protected EditableOMGraphic graphic; - - public PolyAddPointState(EditableOMPoly eomg) { - graphic = eomg; - } - - /** - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "PointStateMachine|add point state|mouseReleased"); - - if (SwingUtilities.isRightMouseButton(e)) { - ((EditableOMPoly) graphic).evaluateEnclosed(); - if ((graphic.getStateMachine()).isOffsetNeeded() == true) { - graphic.getStateMachine().setOffset(); - graphic.getStateMachine().setOffsetNeeded(false); - } else { - graphic.getStateMachine().setSelected(); - } - // Save state - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNDO); - graphic.redraw(e, true); - return false; - } - - // If we are in this state, the moving point should be set to - // the new point, which actually hasn't been placed yet. So, - // we need to check the click count. If it is 1, then we need - // to set the point, and create a new one and stay in this - // state. If it is more than 1, we need to set the point, - // then change state to the selected state because we are done - // drawing the poly. - ((EditableOMPoly) graphic).addMovingPoint(e.getX(), e.getY()); - graphic.fireEvent(EOMGEvent.EOMG_SELECTED); - return false; - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|add point state|mouseMoved"); - graphic.redraw(e); - return false; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|add point state|mouseDragged"); - graphic.redraw(e); - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyDeleteNodeState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyDeleteNodeState.java deleted file mode 100644 index ce687c99b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyDeleteNodeState.java +++ /dev/null @@ -1,102 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolyDeleteNodeState.java,v -// $ -// $RCSfile: PolyDeleteNodeState.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; - -public class PolyDeleteNodeState - extends State { - protected EditableOMGraphic graphic; - - public PolyDeleteNodeState(EditableOMPoly eomg) { - graphic = eomg; - } - - /** - * In this state, we need to change states only if the graphic, or anyplace - * off the graphic is pressed down on. If the end points are clicked on, - * then we do nothing except set the moving point and go to edit mode. - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "GraphicStateMachine|delete node state|mouseReleased"); - - GrabPoint mp = graphic.getMovingPoint(e); - - // If the graphic itself was clicked on, then just go to - // selected - // mode. - if (mp != null) { - int index = ((EditableOMPoly) graphic).whichGrabPoint(mp); - if (index != EditableOMPoly.OFFSET_POINT_INDEX) { - ((EditableOMPoly) graphic).deletePoint(index); - graphic.fireEvent(EOMGCursors.DEFAULT, "", e, EOMGEvent.EOMG_UNDO); - graphic.fireEvent(EOMGEvent.EOMG_SELECTED); - } - } - - graphic.getStateMachine().setSelected(); - graphic.redraw(e, true); - - return false; - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|delete node state|mouseMoved"); - GrabPoint mp = graphic.getMovingPoint(e); - - if (mp != null) { // Only change the cursor over a node - // if (graphic.getGraphic().distance(e.getX(), e.getY()) < - // 2) - // { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(PolyDeleteNodeState.class, "Click_a_node_to_delete_it.", "Click a node to delete it."), - EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, - i18n.get(PolyDeleteNodeState.class, "Click_a_node_to_delete_it.", "Click a node to delete it."), - EOMGEvent.EOMG_UNCHANGED); - } - return false; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomgdetail", "PolyStateMachine|delete node state|mouseDragged"); - if (graphic.getGraphic().distance(e.getX(), e.getY()) < 2) { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(PolyDeleteNodeState.class, "Release_over_a_node_to_delete_it.", - "Release over a node to delete it."), EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.DEFAULT, i18n.get(PolyDeleteNodeState.class, "Release_over_a_node_to_delete_it.", - "Release over a node to delete it."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolySetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolySetOffsetState.java deleted file mode 100644 index 05faeab09..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolySetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolySetOffsetState.java,v -// $ -// $RCSfile: PolySetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class PolySetOffsetState extends GraphicSetOffsetState { - - public PolySetOffsetState(EditableOMPoly eomp) { - super(eomp); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMPoly.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMPoly.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(PolySetOffsetState.class, - "Click_to_place_offset_point_for_poly.", - "Click to place offset point for poly."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyStateMachine.java deleted file mode 100644 index 44456aca3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyStateMachine.java +++ /dev/null @@ -1,88 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolyStateMachine.java,v -// $ -// $RCSfile: PolyStateMachine.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class PolyStateMachine extends EOMGStateMachine { - - public static final int POLY_ADD_POINT = DEFAULT_NUMBER_STATES; - public static final int POLY_ADD_NODE = DEFAULT_NUMBER_STATES + 1; - public static final int POLY_DELETE_NODE = DEFAULT_NUMBER_STATES + 2; - - public PolyStateMachine(EditableOMPoly p) { - super(p); - } - - protected State[] init() { - Debug.message("eomg", "PolyStateMachine.init()"); - NUMBER_STATES = DEFAULT_NUMBER_STATES + 3; - - State[] states = new State[NUMBER_STATES]; - - states[GRAPHIC_UNDEFINED] = new PolyUndefinedState((EditableOMPoly) graphic); - states[GRAPHIC_UNSELECTED] = new GraphicUnselectedState(graphic); - states[GRAPHIC_SELECTED] = new GraphicSelectedState(graphic); - states[GRAPHIC_EDIT] = new GraphicEditState(graphic); - states[GRAPHIC_SETOFFSET] = new PolySetOffsetState((EditableOMPoly) graphic); - states[POLY_ADD_POINT] = new PolyAddPointState((EditableOMPoly) graphic); - states[POLY_ADD_NODE] = new PolyAddNodeState((EditableOMPoly) graphic); - states[POLY_DELETE_NODE] = new PolyDeleteNodeState((EditableOMPoly) graphic); - return states; - - } - - /** - * State where points are added to the end of the polyline. - */ - public void setAddPoint() { - setState(POLY_ADD_POINT); - } - - /** - * State where a node is duplicated if you click on it. - */ - public void setAddNode() { - setState(POLY_ADD_NODE); - } - - /** - * State where a node is deleted if you click on it. - */ - public void setDeleteNode() { - setState(POLY_DELETE_NODE); - } - - public void setSelected() { - super.setSelected(); - ((EditableOMPoly) graphic).enablePolygonEditButtons(true); - } - - public void setUnselected() { - super.setUnselected(); - ((EditableOMPoly) graphic).enablePolygonEditButtons(false); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyUndefinedState.java deleted file mode 100644 index 332f84083..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/PolyUndefinedState.java +++ /dev/null @@ -1,104 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PolyUndefinedState.java,v -// $ -// $RCSfile: PolyUndefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class PolyUndefinedState extends GraphicUndefinedState { - - public PolyUndefinedState(EditableOMPoly eomp) { - super(eomp); - } - - int initX; - int initY; - - /** - * In this state, we need to draw a poly from scratch. So, we - * listen for a mouse down, and set both points there, and then - * set the mode to poly edit. - */ - public boolean mousePressed(MouseEvent e) { - if (Debug.debugging("eomg")) { - Debug.output("PolyStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - } - - // Need to set these up for the polygon - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - graphic.getStateMachine().setOffsetNeeded(true); - Debug.message("eoml", - "PolyStateMachine|undefined state| *offset needed*"); - } - - initX = e.getX(); - initY = e.getY(); - - ((EditableOMPoly) graphic).addPoint(initX, initY); - graphic.fireEvent(EOMGEvent.EOMG_SELECTED); - return getMapMouseListenerResponse(); - } - - /** - * In this state, we need to change states only if the graphic, or - * anyplace off the graphic is pressed down on. If the end points - * are clicked on, then we do nothing except set the moving point - * and go to edit mode. - */ - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", - "GraphicStateMachine|undefined state|mouseReleased"); - - ((EditableOMPoly) graphic).addMovingPoint(e.getX(), e.getY()); - ((PolyStateMachine) graphic.getStateMachine()).setAddPoint(); - graphic.fireEvent(EOMGEvent.EOMG_AUX); - graphic.redraw(e); - return false; - } - - public boolean mouseDragged(MouseEvent e) { - Debug.message("eomgdetail", - "PolyStateMachine|undefined state|mouseDragged"); - - // Set another point if the mouse was dragged a little - // before releasing. Assume that the motion can be a click - // and mouseMove, or a press and mouseDrag. Either way, we - // want the number of nodes to be the right one. - if ((Math.abs(e.getX() - initX) > 2) - || (Math.abs(e.getY() - initY) > 2)) { - - ((EditableOMPoly) graphic).addMovingPoint(e.getX(), e.getY()); - ((PolyStateMachine) graphic.getStateMachine()).setAddPoint(); - } - - graphic.redraw(e); - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSelectedState.java deleted file mode 100644 index e4d11bc5f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSelectedState.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/RectSelectedState.java,v -// $ -// $RCSfile: RectSelectedState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class RectSelectedState extends GraphicSelectedState { - - public RectSelectedState(EditableOMRect eomr) { - super(eomr); - } - - /** - * In this state, we need to change states only if the graphic, or - * anyplace off the graphic is pressed down on. If the end points - * are clicked on, then we do nothing except set the moving point - * and go to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", "RectStateMachine|selected state|mousePressed"); - // This is added for Rectangles: - ((EditableOMRect) graphic).initRectSize(); - return super.mousePressed(e); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "RectStateMachine|selected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - if (mp == null) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(RectSelectedState.class, - "Click_and_Drag_to_change_the_graphic.", - "Click and Drag to change the graphic."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSetOffsetState.java deleted file mode 100644 index aec3c2a75..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectSetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/RectSetOffsetState.java,v -// $ -// $RCSfile: RectSetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class RectSetOffsetState extends GraphicSetOffsetState { - - public RectSetOffsetState(EditableOMRect eomc) { - super(eomc); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMRect.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMRect.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(RectSetOffsetState.class, - "Click_to_place_offset_point.", - "Click to place offset point."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectStateMachine.java deleted file mode 100644 index 2ac9497d2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectStateMachine.java +++ /dev/null @@ -1,56 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/RectStateMachine.java,v -// $ -// $RCSfile: RectStateMachine.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class RectStateMachine - extends EOMGStateMachine { - - public RectStateMachine(EditableOMRect rect) { - super(rect); - } - - protected State[] init() { - State[] states = super.init(); - Debug.message("eomc", "RectStateMachine.init()"); - - // These are the only two states that need something special - // to happen. - states[GRAPHIC_UNDEFINED] = new RectUndefinedState((EditableOMRect) graphic); - states[GRAPHIC_SELECTED] = new RectSelectedState((EditableOMRect) graphic); - states[GRAPHIC_SETOFFSET] = new RectSetOffsetState((EditableOMRect) graphic); - states[GRAPHIC_EDIT] = new GraphicUndefinedEditState(graphic); - return states; - } - - protected void setInitialEdit() { - setEdit(); - if (getState(GRAPHIC_EDIT) instanceof GraphicUndefinedEditState) { - ((GraphicUndefinedEditState) getState(GRAPHIC_EDIT)).needAnotherPoint = true; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectUndefinedState.java deleted file mode 100644 index 336e594be..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/RectUndefinedState.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/RectUndefinedState.java,v -// $ -// $RCSfile: RectUndefinedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMRect; - -public class RectUndefinedState extends ClckOrDrgUndefinedState { - - public RectUndefinedState(EditableOMRect eomr) { - super(eomr); - indexOfFirstPoint = EditableOMRect.NW_POINT_INDEX; - indexOfSecondPoint = EditableOMRect.SE_POINT_INDEX; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSelectedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSelectedState.java deleted file mode 100644 index 6f2dd3ed9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSelectedState.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ScalingRasterSelectedState.java,v -// $ -// $RCSfile: ScalingRasterSelectedState.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMScalingRaster; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class ScalingRasterSelectedState extends GraphicSelectedState { - - public ScalingRasterSelectedState(EditableOMScalingRaster eomr) { - super(eomr); - } - - /** - * In this state, we need to change states only if the graphic, or - * anyplace off the graphic is pressed down on. If the end points - * are clicked on, then we do nothing except set the moving point - * and go to edit mode. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", - "ScalingRasterStateMachine|selected state|mousePressed"); - // This is added for Rectangles: - ((EditableOMScalingRaster) graphic).initRectSize(); - return super.mousePressed(e); - } - - public boolean mouseMoved(MouseEvent e) { - Debug.message("eomgdetail", - "ScalingStateMachine|selected state|mouseMoved"); - - GrabPoint mp = graphic.getMovingPoint(e); - if (mp == null) { - graphic.fireEvent(EOMGCursors.DEFAULT, "", EOMGEvent.EOMG_UNCHANGED); - } else { - graphic.fireEvent(EOMGCursors.EDIT, - i18n.get(ScalingRasterSelectedState.class, - "Click_and_Drag_to_change_the_graphic.", - "Click and Drag to change the graphic."), EOMGEvent.EOMG_UNCHANGED); - } - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSetOffsetState.java deleted file mode 100644 index 884b62aee..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterSetOffsetState.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ScalingRasterSetOffsetState.java,v -// $ -// $RCSfile: ScalingRasterSetOffsetState.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.omGraphics.EditableOMScalingRaster; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class ScalingRasterSetOffsetState extends GraphicSetOffsetState { - - public ScalingRasterSetOffsetState(EditableOMScalingRaster eomc) { - super(eomc); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMScalingRaster.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMRect.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(ScalingRasterSetOffsetState.class, - "Click_to_place_offset_point.", - "Click to place offset point."), EOMGEvent.EOMG_UNCHANGED); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterStateMachine.java deleted file mode 100644 index 8122ded32..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterStateMachine.java +++ /dev/null @@ -1,47 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ScalingRasterStateMachine.java,v -// $ -// $RCSfile: ScalingRasterStateMachine.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMScalingRaster; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.stateMachine.State; -public class ScalingRasterStateMachine extends EOMGStateMachine { - - public ScalingRasterStateMachine(EditableOMScalingRaster raster) { - super(raster); - } - - protected State[] init() { - State[] states = super.init(); - Debug.message("eomc", "ScalingRasterStateMachine.init()"); - - // These are the only two states that need something special - // to happen. - states[GRAPHIC_UNDEFINED] = new ScalingRasterUndefinedState((EditableOMScalingRaster) graphic); - states[GRAPHIC_SELECTED] = new ScalingRasterSelectedState((EditableOMScalingRaster) graphic); - states[GRAPHIC_SETOFFSET] = new ScalingRasterSetOffsetState((EditableOMScalingRaster) graphic); - return states; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterUndefinedState.java deleted file mode 100644 index 9b3b4d1f9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/ScalingRasterUndefinedState.java +++ /dev/null @@ -1,70 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/ScalingRasterUndefinedState.java,v -// $ -// $RCSfile: ScalingRasterUndefinedState.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMScalingRaster; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.util.Debug; - -public class ScalingRasterUndefinedState extends GraphicUndefinedState { - - public ScalingRasterUndefinedState(EditableOMScalingRaster eomr) { - super(eomr); - } - - /** - * In this state, we need to draw a rect from scratch. So, we - * listen for a mouse down, and set both points there, and then - * set the mode to rect edit. - */ - public boolean mousePressed(MouseEvent e) { - Debug.message("eomg", - "ScalingRasterStateMachine|undefined state|mousePressed = " - + graphic.getGraphic().getRenderType()); - - graphic.getGrabPoint(EditableOMScalingRaster.NW_POINT_INDEX) - .set(e.getX(), e.getY()); - GrabPoint gb; - gb = graphic.getGrabPoint(EditableOMScalingRaster.SE_POINT_INDEX); - gb.set(e.getX(), e.getY()); - graphic.setMovingPoint(gb); - - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - // graphic.getGrabPoint(EditableOMRect.OFFSET_POINT_INDEX).set(e.getX(), - // e.getY()); - graphic.getStateMachine().setOffsetNeeded(true); - Debug.message("eomg", - "ScalingRasterStateMachine|undefined state| *offset needed*"); - } - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGEvent.EOMG_EDIT); - return getMapMouseListenerResponse(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextEditState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextEditState.java deleted file mode 100644 index 3149e745e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextEditState.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/TextEditState.java,v -// $ -// $RCSfile: TextEditState.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:16 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMText; -import com.bbn.openmap.util.Debug; - -public class TextEditState extends GraphicEditState implements EOMGEditState { - - public TextEditState(EditableOMText eomt) { - super(eomt); - } - - public boolean mouseReleased(MouseEvent e) { - Debug.message("eomg", "TextStateMachine|edit state|mouseReleased"); - graphic.setGrabPoints(); // Needed for OMText that are point - // and clicked for placement. - return super.mouseReleased(e); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextSetOffsetState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextSetOffsetState.java deleted file mode 100644 index efc860418..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextSetOffsetState.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/TextSetOffsetState.java,v -// $ -// $RCSfile: TextSetOffsetState.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:27:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMText; -import com.bbn.openmap.omGraphics.OffsetGrabPoint; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class TextSetOffsetState extends GraphicSetOffsetState { - - public TextSetOffsetState(EditableOMText eomc) { - super(eomc); - } - - protected void setGrabPoint(MouseEvent e) { - OffsetGrabPoint ogb = (OffsetGrabPoint) graphic.getGrabPoint(EditableOMText.OFFSET_POINT_INDEX); - ogb.set(e.getX(), e.getY()); - ogb.updateOffsets(); - - graphic.setMovingPoint(graphic.getGrabPoint(EditableOMText.OFFSET_POINT_INDEX)); - graphic.redraw(e); - graphic.fireEvent(EOMGCursors.PUTNODE, - i18n.get(TextSetOffsetState.class, - "Click_to_place_offset_point.", - "Click to place offset point."), EOMGEvent.EOMG_UNCHANGED); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextStateMachine.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextStateMachine.java deleted file mode 100644 index c4d1a798d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextStateMachine.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/TextStateMachine.java,v -// $ -// $RCSfile: TextStateMachine.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import com.bbn.openmap.omGraphics.EditableOMText; -import com.bbn.openmap.util.stateMachine.State; -public class TextStateMachine extends EOMGStateMachine { - - public TextStateMachine(EditableOMText text) { - super(text); - } - - protected State[] init() { - State[] states = super.init(); - - // These are the only three states that need something special - // to happen. - states[GRAPHIC_UNDEFINED] = new TextUndefinedState((EditableOMText) graphic); - states[GRAPHIC_EDIT] = new TextEditState((EditableOMText) graphic); - states[GRAPHIC_SETOFFSET] = new TextSetOffsetState((EditableOMText) graphic); - return states; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextUndefinedState.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextUndefinedState.java deleted file mode 100644 index 39aaa5e5d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/TextUndefinedState.java +++ /dev/null @@ -1,80 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/TextUndefinedState.java,v -// $ -// $RCSfile: TextUndefinedState.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/11 20:39:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.editable; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMText; -import com.bbn.openmap.omGraphics.GrabPoint; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.event.EOMGEvent; - -public class TextUndefinedState extends GraphicUndefinedState { - - // ~ Constructors - // --------------------------------------------------------------------------------------------------- - - /** - * Creates a new TextUndefinedState object. - * - * @param eomc - */ - public TextUndefinedState(EditableOMText eomc) { - super(eomc); - } - - // ~ Methods - // -------------------------------------------------------------------------------------------------------- - - /** - */ - public boolean mousePressed(MouseEvent e) { - GrabPoint gb = graphic.getGrabPoint(EditableOMText.CENTER_POINT_INDEX); - - gb.set(e.getX(), e.getY()); - - graphic.setMovingPoint(gb); - - if (graphic.getGraphic().getRenderType() == OMGraphic.RENDERTYPE_OFFSET) { - graphic.getGrabPoint(EditableOMText.OFFSET_POINT_INDEX) - .set(e.getX(), e.getY()); - - graphic.getStateMachine().setOffsetNeeded(true); - } - - graphic.getStateMachine().setEdit(); - graphic.fireEvent(EOMGEvent.EOMG_EDIT); - return getMapMouseListenerResponse(); - } - - /** - */ - public boolean mouseMoved(MouseEvent e) { - graphic.fireEvent(EOMGCursors.EDIT, i18n.get(TextUndefinedState.class, - "Click_to_define_the_text_location.", - "Click to define the text location."), EOMGEvent.EOMG_UNCHANGED); - return false; - } -} // end class TextUndefinedState diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/package.html deleted file mode 100644 index 261ee030b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/editable/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - -Provides classes to implement editable graphics. - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/DBLClickSelectMapMouseInterpreter.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/DBLClickSelectMapMouseInterpreter.java deleted file mode 100644 index 44c70ec03..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/DBLClickSelectMapMouseInterpreter.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java,v $ -// $RCSfile: StandardMapMouseInterpreter.java,v $ -// $Revision: 1.18 $ -// $Date: 2007/10/01 21:43:38 $ -// $Author: epgordon $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.Debug; - -/** - * The DBLClickSelectMapMouseInterpreter is an extension of the - * StandardMapMouseInterpreter that limits selection to map objects that have - * been double clicked on, instead of the single click used by default in the - * super class. - */ -public class DBLClickSelectMapMouseInterpreter - extends StandardMapMouseInterpreter { - - /** - * The OMGraphicLayer should be set at some point before use. - */ - public DBLClickSelectMapMouseInterpreter() { - DEBUG = Debug.debugging("grp"); - } - - /** - * The standard constructor. - */ - public DBLClickSelectMapMouseInterpreter(OMGraphicHandlerLayer l) { - this(); - setLayer(l); - } - - // Mouse Listener events - // ////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false if nothing was pressed over, or the consumeEvents setting if - * something was. - */ - public boolean mousePressed(MouseEvent e) { - if (DEBUG) { - Debug.output("SMMI: mousePressed()"); - } - setCurrentMouseEvent(e); - boolean ret = false; - - GeometryOfInterest goi = getClickInterest(); - OMGraphic omg = getGeometryUnder(e); - - if (goi != null && !goi.appliesTo(omg, e)) { - // If the click doesn't match the geometry or button - // of the geometry of interest, need to tell the goi - // that is was clicked off, and set goi to null. - if (goi.isLeftButton()) { - leftClickOff(goi.getGeometry(), e); - } else { - rightClickOff(goi.getGeometry(), e); - } - setClickInterest(null); - } - - if (omg != null) { - setClickInterest(new GeometryOfInterest(omg, e)); - } - - ret = testForAndHandlePopupTrigger(e); - - // if (omg != null && !ret) { - // select(omg); - // ret = true; - // } - - return ret && consumeEvents; - } - - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Handle a left-click on an OMGraphic. Does nothing by default. - * - * @return true - */ - public boolean leftClick(OMGraphic omg, MouseEvent e) { - boolean ret = false; - - if (omg != null && !ret && e.getClickCount() > 1) { - select(omg); - ret = true; - } - - return ret && consumeEvents; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGEvent.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGEvent.java deleted file mode 100644 index 29c17cd1f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGEvent.java +++ /dev/null @@ -1,185 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/EOMGEvent.java,v -// $ -// $RCSfile: EOMGEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.Cursor; -import java.awt.event.InputEvent; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; - -/** - * The EOMGEvent describes a change in state of an EditableOMGraphic. State, - * that is, in terms of what the StateMachine is interested in. Whenever a EOMG - * state changes, the EOMG fires a chance through one of these events so that - * any interested party can find out what's going on. - * - * @author ddietrick - */ -public class EOMGEvent { - /** - * The status of the EditableOMGraphic hasn't changed. - */ - public final static int EOMG_UNCHANGED = -1; - /** Nothing about the graphic is known or defined. */ - public final static int EOMG_UNDEFINED = 0; - /** - * The Graphic is defined and in a stable state without the grab points - * active. - */ - public final static int EOMG_DEFINED = 1; - /** - * The Graphic is defined, in a stable state with the grab points active. - * Receiving an event with this status means that the EditableOMGraphic has - * returned to the stable state, and can be used as a trigger for other GUI - * updates. - */ - public final static int EOMG_SELECTED = 2; - /** - * The Graphic is defined, in a state of flux. The GrabPoints are being - * manipulated, and the graphic parameters are being modified as a result of - * this. - */ - public final static int EOMG_EDIT = 3; - /** - * This is a state where something different or extra is being done. Grab - * point being added/defined, some other parameter of the graphic being - * modified where an extra state warrants it. There may be other auxillary - * states defined, and they should be defined to be greater than - * EOMG_COMPLETE. - */ - public final static int EOMG_AUX = 4; - /** - * The state where the editing is complete. - */ - public final static int EOMG_COMPLETE = 5; - - /** - * A state where the current OMGraphic state should be saved for an Undo operation. - */ - public final static int EOMG_UNDO = 6; - - /** The EOMG in question. */ - protected EditableOMGraphic source; - /** - * The Cursor that should be active after this event is received. If null, - * then the cursor should be unchanged. - */ - protected Cursor cursor; - /** - * An instructional/error message that should be presented to the user. If - * null, nothing should be displayed. Send an empty string to clear out what - * is currently being displayed. - */ - protected String message; - /** - * A java MouseEvent that might have caused this EOMGEvent. Can be used by - * the listener to determine what type of action to take, to check if an - * option key was held down, etc. May be null! - */ - protected MouseEvent mouseEvent = null; - - /** - * The status of the EOMG as this event is sent. Will be EOMG_UNDEFINED, - * EOMG_DEFINED, EOMG_SELECTED, EOMG_EDIT or EOMG_COMPLETE. - */ - protected int status = EOMG_UNDEFINED; - - /** - * Create an Event. - */ - public EOMGEvent(EditableOMGraphic source, Cursor cursor, String message, MouseEvent me, int status) { - this.source = source; - this.cursor = cursor; - this.message = message; - this.mouseEvent = me; - this.status = status; - } - - /** - * Deactivation event. - */ - public EOMGEvent() { - this.source = null; - this.cursor = null; - this.message = null; - this.mouseEvent = null; - this.status = EOMG_COMPLETE; - } - - public void setSource(EditableOMGraphic eomg) { - source = eomg; - } - - public EditableOMGraphic getSource() { - return source; - } - - public void setCursor(Cursor cur) { - cursor = cur; - } - - public Cursor getCursor() { - return cursor; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - - public void setMouseEvent(MouseEvent me) { - mouseEvent = me; - } - - /** - * @return the MouseEvent that started the EOMG changing. May be null! - */ - public MouseEvent getMouseEvent() { - return mouseEvent; - } - - public boolean shouldShowGUI() { - if (mouseEvent != null) { - return (mouseEvent.isControlDown() || (mouseEvent.getModifiers() & InputEvent.BUTTON3_MASK) > 0); - } - return false; - } - - public boolean shouldDeactivate() { - return this.status == EOMG_COMPLETE; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListener.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListener.java deleted file mode 100644 index eb442a3a1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListener.java +++ /dev/null @@ -1,31 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/EOMGListener.java,v -// $ -// $RCSfile: EOMGListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -public interface EOMGListener { - - public void eomgChanged(EOMGEvent event); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListenerSupport.java deleted file mode 100644 index 7b5c382bf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/EOMGListenerSupport.java +++ /dev/null @@ -1,90 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/EOMGListenerSupport.java,v $ -// $RCSfile: EOMGListenerSupport.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.util.Debug; - -/** - * This is a utility class that can be used by beans that need support - * for handling EOMGListeners and calling the EOMGListener method. You - * can use an instance of this class as a member field of your bean - * and delegate work to it. - */ -public class EOMGListenerSupport extends ListenerSupport { - - /** - * Construct a EOMGListenerSupport. - */ - public EOMGListenerSupport() { - this(null); - } - - /** - * Construct a EOMGListenerSupport. - * - * @param graphic source graphic - */ - public EOMGListenerSupport(EditableOMGraphic graphic) { - super(graphic); - } - - /** - * Set the source object. - * - * @param graphic source EditableOMGraphic - */ - public synchronized void setEOMG(EditableOMGraphic graphic) { - setSource(graphic); - } - - /** - * Get the source object. - * - * @return EditableOMGraphic - */ - public synchronized EditableOMGraphic getEOMG() { - return (EditableOMGraphic) getSource(); - } - - /** - * Send a eomgChanged event to all registered listeners. - * - * @param event EOMGEvent - */ - public synchronized void fireEvent(EOMGEvent event) { - - if (isEmpty()) - return; - - for (EOMGListener target : this) { - target.eomgChanged(event); - - if (Debug.debugging("eomgdetail")) { - Debug.output("EOMGListenerSupport.fireStatusChanged(): target is: " - + target); - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/GestureResponsePolicy.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/GestureResponsePolicy.java deleted file mode 100644 index eac377be3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/GestureResponsePolicy.java +++ /dev/null @@ -1,194 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/GestureResponsePolicy.java,v $ -// $RCSfile: GestureResponsePolicy.java,v $ -// $Revision: 1.10 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.Component; -import java.util.List; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; - -/** - * The GestureResponsePolicy interface describes an object that - * receives interpreted events from a MapMouseInterpreter. The - * interpreter receives the MouseEvents and does the work of deciding - * what has happened concerning the OMGraphics on an - * OMGraphicHandlerLayer, and notifies the GestureResponsePolicy what - * it thinks happened. The GRP is free to respond as it needs. - * - * @see com.bbn.openmap.omGraphics.event.MapMouseInterpreter - * @see com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter - * @see com.bbn.openmap.layer.OMGraphicHandlerLayer - */ -public interface GestureResponsePolicy { - - /** - * A query from the MapMouseInterpreter wondering if it should ask - * any questions about the given OMGraphic concerning mouse - * movement and mouse dragged gestures. Highlighting is usually - * means reactions in anticipation of selection. - */ - public boolean isHighlightable(OMGraphic omgr); - - /** - * A query from the MapMouseInterpreter wondering if the OMGraphic - * is selectable. Returns true if the OMGraphic is able to be - * selected for modification, deletion or movement. Selection may - * happen to an OMGraphic by itself or in a group of other - * OMGraphics. - */ - public boolean isSelectable(OMGraphic omgr); - - /** - * A query from the MapMouseInterpreter wondering if the - * GestureResponsePolicy wants events pertaining to mouse - * movements over the map that are not over an OMGraphic. If the - * GestureResponsePolicy responds true, then the mouseOver and - * leftClick methods will be called on the GestureResponsePolicy - * by the interpreter. There is no rightClick method that is - * called, because a right click will always cause a - * getItemsForMapMenu() method to be called. - */ - public boolean receivesMapEvents(); - - /** - * A query to get a list of all the OMGraphics that are current - * selected. - */ - public OMGraphicList getSelected(); - - /** - * A notification that the OMGraphics on the list should be - * considered to be selected. - */ - public void select(OMGraphicList omgl); - - /** - * A notification that the OMGraphics on the list should be - * considered to be deselected. - */ - public void deselect(OMGraphicList omgl); - - /** - * A notification that the OMGraphics on the list should be cut - * (deleted and returned) from the list and deselected. If the GRP - * doesn't want to provide that capability, it should return null. - */ - public OMGraphicList cut(OMGraphicList omgl); - - /** - * A notification that the OMGraphics on the list should be copied - * (duplicated and returned) and deselected. If the GRP doesn't - * want to provide that capability, it should return null. - */ - public OMGraphicList copy(OMGraphicList omgl); - - /** - * A notification that the OMGraphics on the list should be added - * to the list and selected. - */ - public void paste(OMGraphicList omgl); - - /** - * A notification that the OMGraphic should be highlighted in some - * way if the layer wants, to give the impression that something - * would happen to the OMGraphic if it were clicked upon or that a - * tooltip or information line information applies to this - * specific OMGraphic. - */ - public void highlight(OMGraphic omg); - - /** - * A notification that the OMGraphic is no longer needed to be - * highlighted and that its appearance can go back to normal. - */ - public void unhighlight(OMGraphic omg); - - /** - * A request for a string to be provided to use as a tool tip for - * an OMGraphic. If a tool tip should not be displayed, null - * should be returned. - */ - public String getToolTipTextFor(OMGraphic omg); - - /** - * A request for a string to be provided to use in the information - * line of the InformationDelegator, for instance. If no - * information should be presented on behalf of this OMGraphic, - * null should be returned. - */ - public String getInfoText(OMGraphic omg); - - /** - * Return a JMenu with contents applicable to a popup menu for a - * location over the map. The popup doesn't concern any - * OMGraphics, and should be presented for a click on the map - * background. - * - * @param mme a MapMouseEvent describing the location over where - * the menu items should apply, in case different options - * are appropriate for different places. - * @return a List containing java.awt.Component options over the - * provided place on the map. Return null or empty List if - * no input required. - */ - public List getItemsForMapMenu(MapMouseEvent mme); - - /** - * Return a java.util.List containing input for a JMenu with - * contents applicable to a popup menu for a location over an - * OMGraphic. - * - * @return a List containing java.awt.Component options for the - * given OMGraphic. Return null or empty list if there are - * no options. - */ - public List getItemsForOMGraphicMenu(OMGraphic omg); - - /** - * A notification that the mouse cursor has been moved over the - * map, not over any of the OMGraphics on the - * GestureResponsePolicy. This only gets called if the response to - * receivesMapEvents is true. - * - * @param mme MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed - * and should not be passed to anybody else. - */ - public boolean mouseOver(MapMouseEvent mme); - - /** - * A notification that the mouse has been clicked with the left - * mouse button on the map, and not on any of the OMGraphics. This - * only gets called if the response to receivesMapEvents is true. - * Right clicks on the map are always reported to the - * getItemsForMapMenu method. - * - * @param mme MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed - * and should not be passed to anybody else. - */ - public boolean leftClick(MapMouseEvent mme); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/MapMouseInterpreter.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/MapMouseInterpreter.java deleted file mode 100644 index d0ba86c63..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/MapMouseInterpreter.java +++ /dev/null @@ -1,128 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/MapMouseInterpreter.java,v $ -// $RCSfile: MapMouseInterpreter.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * A MapMouseInterpreter is an extension of the MapMouseListener that - * has some understanding how MouseEvents on a Map relate to an - * OMGraphicList, and what kind of actions should be taken on the - * OMGraphics on a list. This interface describes specific actions - * being taken on OMGraphics over a map, and the implementing class - * can then take this information to make more abstract calls on its - * GestureResponsePolicy. - */ -public interface MapMouseInterpreter extends MapMouseListener { - - /** - * A method for the GestureResponsePolicy to find out what the - * last MouseEvent was, in case it needs it to react to the GRP - * notifications. - */ - public MouseEvent getCurrentMouseEvent(); - - /** - * Notification that the background was left-clicked upon. - */ - public boolean leftClick(MouseEvent me); - - /** - * Notification that a particular OMGraphic was left-clicked upon. - */ - public boolean leftClick(OMGraphic omg, MouseEvent me); - - /** - * Notification that a particular OMGraphic, previously - * left-clicked upon, has been un-clicked. Most likely due to the - * user clicking on another OMGraphic, using a different mouse - * button to click on this same OMGraphic, or when the background - * map was clicked upon. - */ - public boolean leftClickOff(OMGraphic omg, MouseEvent me); - - /** - * Notification that the background was right-clicked upon. - */ - public boolean rightClick(MouseEvent me); - - /** - * Notification that a particular OMGraphic was right-clicked - * upon. - */ - public boolean rightClick(OMGraphic omg, MouseEvent me); - - /** - * Notification that a particular OMGraphic, previously - * right-clicked upon, has been un-clicked. Most likely due to the - * user clicking on another OMGraphic, using a different mouse - * button to click on this same OMGraphic, or when the background - * map was clicked upon. - */ - public boolean rightClickOff(OMGraphic omg, MouseEvent me); - - /** - * Notification that the mouse is being moved over the map at a - * certain location, and is not over any OMGraphics. - */ - public boolean mouseOver(MouseEvent me); - - /** - * Notification that the mouse is over a particluar OMGraphic. - */ - public boolean mouseOver(OMGraphic omg, MouseEvent me); - - /** - * Notification that the mouse has moved off of an OMGraphic it - * was previously over. - */ - public boolean mouseNotOver(OMGraphic omg); - - /** - * Set the GestureResponsePolicy to notify when MouseEvents have - * been interpreted. - */ - public void setGRP(GestureResponsePolicy urp); - - /** - * Get the GestureResponsePolicy to notify when MouseEvents have - * been interpreted. - */ - public GestureResponsePolicy getGRP(); - - /** - * Check whether the MapMouseInterpreter is responding to events. - * @return true if willing to respond to MouseEvents. - */ - public boolean isActive(); - - /** - * Set whether the MapMouseInterpreter responds to mouse events. - * @param active true if it should respond to mouse events. - */ - public void setActive(boolean active); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionEvent.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionEvent.java deleted file mode 100644 index 524520c0b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/SelectionEvent.java,v $ -// $RCSfile: SelectionEvent.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; - -/** - * An event that a SelectionProvider gives to a SelectionListener, in - * order to notify it of OMGraphics that have been selected and - * deselected. - */ -public class SelectionEvent { - - protected Object source; - protected OMGraphic graphic; - protected DrawingToolRequestor requestor; - protected boolean selected; - - public SelectionEvent(Object source, OMGraphic omg, - DrawingToolRequestor dtr, boolean selectionStatus) { - - this.source = source; - graphic = omg; - requestor = dtr; - selected = selectionStatus; - } - - public Object getSource() { - return source; - } - - public OMGraphic getOMGraphic() { - return graphic; - } - - public DrawingToolRequestor getRequestor() { - return requestor; - } - - public boolean isSelected() { - return selected; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionListener.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionListener.java deleted file mode 100644 index 0fc37a836..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionListener.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/SelectionListener.java,v $ -// $RCSfile: SelectionListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -/** - * An interface defining an object that is interested in receiving - * SelectionEvents. - */ -public interface SelectionListener { - - /** - * The method that catches SelectionEvents. - */ - public void selectionNotification(SelectionEvent se); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionProvider.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionProvider.java deleted file mode 100644 index 07c10b0fa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/SelectionProvider.java,v $ -// $RCSfile: SelectionProvider.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -/** - * An interface to define an object that can generate SelectionEvents - * for OMGraphics. A SelectionListener would hook up to a - * SelectionProvider to find out when OMGraphics are selected and - * deselected. - */ -public interface SelectionProvider { - - public void addSelectionListener(SelectionListener listener); - - public void removeSelectionListener(SelectionListener listener); - - public void clearSelectionListeners(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionSupport.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionSupport.java deleted file mode 100644 index 7e81da755..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/SelectionSupport.java +++ /dev/null @@ -1,102 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/SelectionSupport.java,v $ -// $RCSfile: SelectionSupport.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.util.Vector; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; - -/** - * A class to help SelectionProviders manage SelectionListeners, and - * to help with firing SelectionEvents to those listeners. - */ -public class SelectionSupport { - - transient private Vector listeners; - private Object source; - - public SelectionSupport(Object src) { - source = src; - } - - /** - * Add a SelectionListener to the listener list. - * - * @param listener The SelectionListener to be added - */ - public synchronized void addSelectionListener(SelectionListener listener) { - if (listeners == null) { - listeners = new Vector(); - } - listeners.addElement(listener); - } - - /** - * Remove a SelectionListener from the listener list. - * - * @param listener The SelectionListener to be removed - */ - public synchronized void removeSelectionListener(SelectionListener listener) { - if (listeners != null) { - listeners.removeElement(listener); - } - } - - /** - * Remove all listeners from the list. - */ - public synchronized void clearSelectionListeners() { - if (listeners != null) { - listeners.clear(); - } - } - - /** - * Send a selection event to all registered listeners. - * - * @param omg the graphic in the selection event - * @param dtr the drawingtoolrequestor in the selection event - * @param isSelected the selection state in the selection event - * @see SelectionEvent - */ - public void fireSelection(OMGraphic omg, DrawingToolRequestor dtr, - boolean isSelected) { - - Vector targets; - synchronized (this) { - if (listeners == null) { - return; - } - targets = (java.util.Vector) listeners.clone(); - } - - SelectionEvent evt = new SelectionEvent(source, omg, dtr, isSelected); - - for (int i = 0; i < targets.size(); i++) { - SelectionListener target = targets.elementAt(i); - target.selectionNotification(evt); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java deleted file mode 100644 index dc3081eef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java +++ /dev/null @@ -1,930 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java,v $ -// $RCSfile: StandardMapMouseInterpreter.java,v $ -// $Revision: 1.18 $ -// $Date: 2007/10/01 21:43:38 $ -// $Author: epgordon $ -// -// ********************************************************************** -package com.bbn.openmap.omGraphics.event; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.util.Debug; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.util.List; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.ToolTipManager; - -/** - * The StandardMapMouseInterpreter is a basic implementation of the MapMouseInterpreter, working with an - * OMGraphicHandlerLayer to handle MouseEvents on it. This class allows the OMGraphicHandlerLayer, which implements the - * GestureResponsePolicy, to not have to deal with MouseEvents and the OMGraphicList, but to just react to the meanings - * of the user's gestures. - *

- * - * The StandardMapMouseInterpreter uses highlighting to indicate that mouse movement is occurring over an OMGraphic, and - * gives the layer three ways to react to that movement. After finding out if the OMGraphic is highlightable, the SMMI - * will tell the layer to highlight the OMGraphic (which usually means to call select() on it), provide a tool tip - * string for the OMGraphic, and provide a string to use on the InformationDelegator info line. The layer can reply or - * ignore any and all of these notifications, depending on how it's supposed to act. - *

- * - * For left mouse clicks, the SMMI uses selection as a notification that the user is choosing an OMGraphic, and that the - * OMGraphic should be prepared to be moved, modified or deleted. For a single OMGraphic, this is usually handled by - * handing the OMGraphic off to the OMDrawingTool. However the GestureResponsPolicy handles the situation where the - * selection is of multiple OMGraphics, and the layer should prepare to handle those situations as movement or deletion - * notifications. This usually means to change the OMGraphic's display to indicate that the OMGraphics have been - * selected. Selection notifications can come in series, and the GestureResponsePolicy is expected to keep track of - * which OMGraphics it has been told are selected. Deselection notifications may come as well, or other action - * notifications such as cut or copy may arrive. For cut and copy notifications, the OMGraphics should be removed from - * any selection list. For pastings, the OMGraphics should be added to the selection list. - *

- * - * For right mouse clicks, the layer will be provided with a JPopupMenu to use to populate with options for actions over - * a OMGraphic or over the map. - *

- * - * The StandardMapMouseInterpreter uses a timer to pace how mouse movement actions are responded to. Highlight reactions - * only occur after the mouse has paused over the map for the timer interval, so the application doesn't try to respond - * to constantly changing mouse locations. You can disable this delay by setting the timer interval to zero. - */ -public class StandardMapMouseInterpreter - implements MapMouseInterpreter { - - protected boolean DEBUG = false; - protected OMGraphicHandlerLayer layer = null; - protected String[] mouseModeServiceList = null; - protected String lastToolTip = null; - protected GestureResponsePolicy grp = null; - protected GeometryOfInterest clickInterest = null; - protected GeometryOfInterest movementInterest = null; - protected boolean consumeEvents = false; - - protected boolean active = true; - - /** - * The OMGraphicLayer should be set at some point before use. - */ - public StandardMapMouseInterpreter() { - DEBUG = Debug.debugging("grp"); - } - - /** - * The standard constructor. - * - * @param l OMGraphicHandlerLayer this interpreter is serving. - */ - public StandardMapMouseInterpreter(OMGraphicHandlerLayer l) { - this(); - setLayer(l); - } - - /** - * Helper class used to keep track of OMGraphics of interest. Interest means that a MouseEvent that occurred over an - * OMGraphic that combined with another MouseEvent, may be interpreted as a significant event. - */ - public class GeometryOfInterest { - - OMGraphic omg; - int button; - boolean leftButton; - - /** - * Create a Geometry of Interest with the OMGraphic and the first mouse event. - * - * @param geom geometry of interest. - * @param me the mouse event making the geom interesting. - */ - public GeometryOfInterest(OMGraphic geom, MouseEvent me) { - omg = geom; - button = getButton(me); - leftButton = isLeftMouseButton(me); - } - - /** - * A check to see if an OMGraphic is the same as the one of interest. - * - * @param geom the OMGraphic to check if it applies against this GOI. - * @return true if geom isn't null and equals this GOI - */ - public boolean appliesTo(OMGraphic geom) { - return (geom != null && geom.equals(omg)); - } - - /** - * A check to see if a mouse event that is occurring over an OMGraphic is in fact occurring over the one of - * interest, and with the same mouse button. - * - * @param geom the OMGraphic to check if it applies against this GOI. - * @param me MouseEvent for more info. - * @return true if geom isn't null and equals this GOI, matching mouse buttons - */ - public boolean appliesTo(OMGraphic geom, MouseEvent me) { - return (geom != null && geom.equals(omg) && sameButton(me)); - } - - /** - * A check to see if the current mouse event concerns the same mouse button as the original. - * - * @param me the MouseEvent to check button on - * @return true if buttons match the original settings. - */ - public boolean sameButton(MouseEvent me) { - return button == getButton(me); - } - - /** - * Return the OMGraphic of interest. - * - * @return OMGraphic - */ - public OMGraphic getGeometry() { - return omg; - } - - /** - * Return the button that caused the interest. - */ - public int getButton() { - return button; - } - - /** - * Utility method to get around MouseEvent.getButton 1.4 requirement. - * - * @param me get the button selection for this MouseEvent - * @return SWING int for button. - */ - protected int getButton(MouseEvent me) { - // jdk 1.4 version - // return me.getButton(); - - // jdk 1.3 version Don't know if the numbers are the same - // as in me.getButton, shouldn't make a difference. - if (me.isControlDown() /* PopupTrigger() */ - || SwingUtilities.isRightMouseButton(me)) { - return 1; - } else if (SwingUtilities.isLeftMouseButton(me)) { - return 0; - } else { - return 2; - } - } - - /** - * Return if the current button is the left one. - * - * @return true if left button. - */ - public boolean isLeftButton() { - return leftButton; - } - - /** - * Called when the popup trigger is known to have been triggered and a click interest has been set by it. - * - * @param b is it the left button? - */ - public void setLeftButton(boolean b) { - leftButton = b; - } - } - - /** - * A flag to tell the interpreter to be selfish about consuming MouseEvents it receives. If set to true, it will - * consume events so that other MapMouseListeners will not receive the events. If false, lower layers will also - * receive events, which will let them react too. Intended to let other layers provide information about what the - * mouse is over when editing is occurring. - * - * @param consume true to consume events - */ - public void setConsumeEvents(boolean consume) { - consumeEvents = consume; - } - - public boolean getConsumeEvents() { - return consumeEvents; - } - - public void setLayer(OMGraphicHandlerLayer l) { - layer = l; - } - - public OMGraphicHandlerLayer getLayer() { - return layer; - } - - /** - * Set the ID's of the mouse modes that this interpreter should be listening to. If set to null, this SMMI won't - * receive MouseEvents. - * - * @param list String array of MouseMode ID that this interpreter should receive events from. - */ - public void setMouseModeServiceList(String[] list) { - mouseModeServiceList = list; - } - - /** - * A method to set how a left mouse button is interpreted. We count control-clicks as not a left mouse click. - * - * @param me checking event for button press - * @return true if left mouse button pressed. - */ - public boolean isLeftMouseButton(MouseEvent me) { - return SwingUtilities.isLeftMouseButton(me); - } - - /** - * Return a list of the modes that are interesting to the MapMouseListener. You MUST override this with the modes - * you're interested in, or set the mouse mode service list, or you won't receive mouse events. - */ - public String[] getMouseModeServiceList() { - return mouseModeServiceList; - } - - /** - * Set the GeometryOfInterest as one that could possibly be in the process of being clicked upon. - */ - protected void setClickInterest(GeometryOfInterest goi) { - clickInterest = goi; - } - - /** - * Get the GeometryOfInterest as one that could possibly be in the process of being clicked upon. - */ - protected GeometryOfInterest getClickInterest() { - return clickInterest; - } - - /** - * Set the GeometryOfInterest for something that the mouse is over. Prevents excessive modifications of the GUI if - * this remains constant. - */ - protected void setMovementInterest(GeometryOfInterest goi) { - movementInterest = goi; - } - - /** - * Get the GeometryOfInterest for something that the mouse is over. Prevents excessive modifications of the GUI if - * this remains constant. - */ - protected GeometryOfInterest getMovementInterest() { - return movementInterest; - } - - /** - * Return the OMGraphic object that is under a mouse event occurrence on the map, null if nothing applies. - */ - public OMGraphic getGeometryUnder(MouseEvent me) { - OMGraphic omg = null; - OMGraphicList list = null; - if (layer != null) { - list = layer.getList(); - if (list != null) { - int x = me.getX(); - int y = me.getY(); - if (me instanceof MapMouseEvent) { - Point2D pnt = ((MapMouseEvent) me).getProjectedLocation(); - x = (int) pnt.getX(); - y = (int) pnt.getY(); - } - - omg = list.findClosest(x, y, 4); - } else { - if (DEBUG) { - Debug.output("SMMI: no layer to evaluate mouse event"); - } - } - } else { - if (DEBUG) { - Debug.output("SMMI: no layer to evaluate mouse event"); - } - } - - return omg; - } - - // Mouse Listener events - // ////////////////////// - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false if nothing was pressed over, or the consumeEvents setting if something was. - */ - public boolean mousePressed(MouseEvent e) { - if (DEBUG) { - Debug.output("SMMI:mousePressed()"); - } - return setClickInterestFromMouseEvent(e); - } - - /** - * Set the GeometryOfInterest based on MouseEvent. The default behavior of mousePressed. - * - * @param e MouseEvent - * @return whether mouse event was consumed. - */ - protected boolean setClickInterestFromMouseEvent(MouseEvent e) { - if (!active) { - return false; - } - - if (DEBUG) { - Debug.output("SMMI: setClickInterestFromMouseEvent()"); - } - setCurrentMouseEvent(e); - boolean ret = false; - - GeometryOfInterest goi = getClickInterest(); - OMGraphic omg = getGeometryUnder(e); - - if (goi != null && !goi.appliesTo(omg, e)) { - // If the click doesn't match the geometry or button - // of the geometry of interest, need to tell the goi - // that is was clicked off, and set goi to null. - if (goi.isLeftButton()) { - leftClickOff(goi.getGeometry(), e); - } else { - rightClickOff(goi.getGeometry(), e); - } - setClickInterest(null); - } - - if (omg != null) { - setClickInterest(new GeometryOfInterest(omg, e)); - } - - ret = testForAndHandlePopupTrigger(e); - - if (omg != null && !ret) { - select(omg); - ret = true; - } - - return ret && consumeEvents; - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - if (!active) { - return false; - } - - setCurrentMouseEvent(e); - return testForAndHandlePopupTrigger(e) && consumeEvents; - } - - /** - * Tests the MouseEvent to see if it's a popup trigger, and calls rightClick appropriately if there is an OMGraphic - * involved. - * - * @param e MouseEvent - * @return true if the MouseEvent is a popup trigger and has been consumed. - */ - public boolean testForAndHandlePopupTrigger(MouseEvent e) { - boolean ret = false; - if (e.isPopupTrigger()) { - GeometryOfInterest goi = getClickInterest(); - // If there is a click interest - if (goi != null) { - // Tell the policy it an OMGraphic was clicked. - goi.setLeftButton(false); - ret = rightClick(goi.getGeometry(), e); - } else { - ret = rightClick(e); - } - } - return ret; - } - - /** - * Invoked when the mouse has been clicked. Notifies the left click methods for the applicable OMGraphic or the map. - * Right click methods are handled when the testForAndHandlePopupTrigger method is called in mousePressed and - * mouseReleased. - * - * @param e MouseEvent - * @return the consumeEvents setting. - */ - public boolean mouseClicked(MouseEvent e) { - if (!active) { - return false; - } - - // Should have been done already from the MousePressed, but different - // OS Java implementations have the pressed occur after click. Gah! - setClickInterestFromMouseEvent(e); - - if (isLeftMouseButton(e)) { - GeometryOfInterest goi = getClickInterest(); - // If there is a click interest - if (goi != null) { - // Tell the policy it an OMGraphic was clicked. - if (goi.isLeftButton()) { - leftClick(goi.getGeometry(), e); - } else { - rightClick(goi.getGeometry(), e); - } - } else { - leftClick(e); - } - - return consumeEvents; - } - - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - if (!active) { - return; - } - setCurrentMouseEvent(e); - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - if (!active) { - return; - } - setCurrentMouseEvent(e); - } - - // Mouse Motion Listener events - // ///////////////////////////// - /** - * Invoked when a mouse button has been pressed and is moving. Resets the click geometry of interest to null. - * - * @param e MouseEvent - * @return the result from mouseMoved (also called from this method) combined with the consumeEvents setting. - */ - public boolean mouseDragged(MouseEvent e) { - if (!active) { - return false; - } - setCurrentMouseEvent(e); - GeometryOfInterest goi = getClickInterest(); - if (goi != null) { - setClickInterest(null); - } - - return mouseMoved(e) && consumeEvents; - } - - /** - * Invoked when the mouse has been moved. Sets the movement geometry of interest and updates the movement timer. - * - * @param e MouseEvent - * @return the result of updateMouseMoved() if the timer isn't being used, or false. - */ - public boolean mouseMoved(MouseEvent e) { - if (!active) { - return false; - } - setCurrentMouseEvent(e); - - if (getMovementInterest() == null || noTimerOverOMGraphic || mouseTimerInterval <= 0) { - return updateMouseMoved(e); - } else { - if (mouseTimer == null) { - mouseTimer = new Timer(mouseTimerInterval, mouseTimerListener); - mouseTimer.setRepeats(false); - } - - mouseTimerListener.setEvent(e); - mouseTimer.restart(); - return false; - } - } - - protected boolean noTimerOverOMGraphic = true; - - /** - * Set whether to ignore the timer when movement is occurring over an OMGraphic. Sometimes unhighlight can be - * inappropriately delayed when timer is enabled. - */ - public void setNoTimerOverOMGraphic(boolean val) { - noTimerOverOMGraphic = val; - } - - /** - * Get whether the timer should be ignored when movement is occurring over an OMGraphic. - */ - public boolean getNoTimerOverOMGraphic() { - return noTimerOverOMGraphic; - } - - /** - * The wait interval before a mouse over event gets triggered. - */ - protected int mouseTimerInterval = 150; - - /** - * Set the time interval that the mouse timer waits before calling upateMouseMoved. A negative number or zero will - * disable the timer. - */ - public void setMouseTimerInterval(int interval) { - mouseTimerInterval = interval; - } - - public int getMouseTimerInterval() { - return mouseTimerInterval; - } - - /** - * The timer used to track the wait interval. - */ - protected Timer mouseTimer = null; - - /** - * The timer listener that calls updateMouseMoved. - */ - protected MouseTimerListener mouseTimerListener = new MouseTimerListener(); - - /** - * The definition of the listener that calls updateMouseMoved when the timer goes off. - */ - protected class MouseTimerListener - implements ActionListener { - - private MouseEvent event; - - public synchronized void setEvent(MouseEvent e) { - event = e; - } - - public synchronized void actionPerformed(ActionEvent ae) { - if (event != null) { - updateMouseMoved(event); - } - } - } - - /** - * The real mouseMoved call, called when mouseMoved is called and, if there is a mouse timer interval set, that - * interval time has passed. - * - * @param e mouse event (actually MapMouseEvent) being evaluated. - * @return the consumeEvents setting of the mouse event concerns an OMGraphic, false if it didn't. - */ - protected boolean updateMouseMoved(MouseEvent e) { - boolean ret = false; - OMGraphic omg = getGeometryUnder(e); - GeometryOfInterest goi = getMovementInterest(); - - boolean mouseOverCurrentGOI = (goi != null && goi.appliesTo(omg)); - - if (goi != null && !mouseOverCurrentGOI) { - // We already had a GOI from preious event, but it's not under the event now... - mouseNotOver(goi.getGeometry()); - setMovementInterest(null); - } else { - ret = (goi != null); - } - - if (omg != null) { - // Mouse over OMGraphic - if (!mouseOverCurrentGOI) { - // We get in here if the GOI should be changed to a new OMGraphic. - setMovementInterest(new GeometryOfInterest(omg, e)); - - // Add a specialized check for OMPoint because it shouldn't have a delayed unhighlight. - setNoTimerOverOMGraphic(!omg.shouldRenderFill() || omg instanceof OMPoint); - ret = mouseOver(omg, e); - } - } else { - // Current mouse event not over an OMGraphic - ret = mouseOver(e); - } - - ret = ret && consumeEvents; - - if (ret) { - e.consume(); - } - - return ret; - } - - /** - * Handle notification that another layer consumed a mouse moved event. Sets movement interest to null. - */ - public void mouseMoved() { - if (!active) { - return; - } - GeometryOfInterest goi = getMovementInterest(); - if (goi != null) { - mouseNotOver(goi.getGeometry()); - setMovementInterest(null); - } - } - - /** - * Handle a left-click on the map. Does nothing by default. - * - * @return false - */ - public boolean leftClick(MouseEvent me) { - if (DEBUG) { - Debug.output("leftClick(MAP) at " + me.getX() + ", " + me.getY()); - } - - if (grp != null && grp.receivesMapEvents() && me instanceof MapMouseEvent) { - return grp.leftClick((MapMouseEvent) me); - } - - return false; - } - - /** - * Handle a left-click on an OMGraphic. Does nothing by default. - * - * @return true - */ - public boolean leftClick(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("leftClick(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - return false; - } - - /** - * Notification that the user clicked on something else other than the provided OMGraphic that was previously - * left-clicked on. Calls deselect(omg). - * - * @return false - */ - public boolean leftClickOff(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("leftClickOff(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - deselect(omg); - - return false; - } - - /** - * Notification that the map was right-clicked on. - * - * @return false - */ - public boolean rightClick(MouseEvent me) { - if (DEBUG) { - Debug.output("rightClick(MAP) at " + me.getX() + ", " + me.getY()); - } - - if (me instanceof MapMouseEvent && grp != null) { - return displayPopup(grp.getItemsForMapMenu((MapMouseEvent) me), me); - } - - return false; - } - - /** - * Notification that an OMGraphic was right-clicked on. - * - * @return true - */ - public boolean rightClick(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("rightClick(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - if (grp != null) { - return displayPopup(grp.getItemsForOMGraphicMenu(omg), me); - } - - return false; - } - - /** - * Create a pop-up menu from GRP requests, over the mouse event location. - * - * @return true if pop-up was presented, false if not. - */ - protected boolean displayPopup(List contents, MouseEvent me) { - if (DEBUG) { - Debug.output("displayPopup(" + contents + ") " + me); - } - if (contents != null && !contents.isEmpty()) { - JPopupMenu jpm = new JPopupMenu(); - for (Component comp : contents) { - jpm.add(comp); - } - jpm.show((Component) me.getSource(), me.getX(), me.getY()); - return true; - } - return false; - } - - /** - * Notification that the user clicked on something else other than the provided OMGraphic that was previously - * right-clicked on. - * - * @return false - */ - public boolean rightClickOff(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("rightClickOff(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - return false; - } - - /** - * Notification that the mouse is not over an OMGraphic, but over the map at some location. - * - * @return false - */ - public boolean mouseOver(MouseEvent me) { - if (DEBUG) { - Debug.output("mouseOver(MAP) at " + me.getX() + ", " + me.getY()); - } - if (grp != null && grp.receivesMapEvents() && me instanceof MapMouseEvent) { - return grp.mouseOver((MapMouseEvent) me); - } - - return false; - } - - /** - * Notification that the mouse is over an OMGraphic. Makes all the highlight calls. - * - * @return true - */ - public boolean mouseOver(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("mouseOver(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - if (grp != null && !me.isConsumed()) { - handleToolTip(grp.getToolTipTextFor(omg), me); - handleInfoLine(grp.getInfoText(omg)); - if (grp.isHighlightable(omg)) { - grp.highlight(omg); - } - } - return true; - } - - /** - * Given a tool tip String, use the layer to get it displayed. - */ - protected void handleToolTip(String tip, MouseEvent me) { - if (lastToolTip != null && lastToolTip.equals(tip)) { - return; - } - lastToolTip = tip; - if (layer != null) { - if (lastToolTip != null && lastToolTip.trim().length() > 0) { - layer.fireRequestToolTip(lastToolTip); - // forward the event to the tool tip manager so it will popup - // the tool tip right away, otherwise an additional event is - // required to trigger it - ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); - toolTipManager.mouseMoved(me); - } else { - layer.fireHideToolTip(); - } - } - } - - /** - * Given an information line, use the layer to get it displayed on the InformationDelegator. - */ - protected void handleInfoLine(String line) { - if (layer != null) { - layer.fireRequestInfoLine((line == null) ? "" : line); - } - } - - /** - * Notification that the mouse has moved off of an OMGraphic. - */ - public boolean mouseNotOver(OMGraphic omg) { - if (DEBUG) { - Debug.output("mouseNotOver(" + omg.getClass().getName() + ")"); - } - - if (grp != null) { - grp.unhighlight(omg); - } - handleToolTip(null, null); - handleInfoLine(null); - return false; - } - - /** - * Notify the GRP that the OMGraphic has been selected. Wraps the OMGraphic in an OMGraphicList. - */ - public void select(OMGraphic omg) { - if (grp != null && grp.isSelectable(omg)) { - OMGraphicList omgl = new OMGraphicList(); - omgl.add(omg); - grp.select(omgl); - } - } - - /** - * Notify the GRP that the OMGraphic has been deselected. Wraps the OMGraphic in an OMGraphicList. - */ - public void deselect(OMGraphic omg) { - if (grp != null && grp.isSelectable(omg)) { - OMGraphicList omgl = new OMGraphicList(); - omgl.add(omg); - grp.deselect(omgl); - } - } - - /** - * The last MouseEvent received, for later reference. - */ - protected MouseEvent currentMouseEvent; - - /** - * Set the last MouseEvent received. - */ - protected void setCurrentMouseEvent(MouseEvent me) { - currentMouseEvent = me; - } - - /** - * Get the last MouseEvent received. - */ - public MouseEvent getCurrentMouseEvent() { - return currentMouseEvent; - } - - /** - * Set the GestureResponsePolicy to notify of the mouse actions over the layer's OMGraphicList. - */ - public void setGRP(GestureResponsePolicy grp) { - this.grp = grp; - } - - /** - * Get the GestureResponsePolicy that is being notified of the mouse actions over the layer's OMGraphicList. - */ - public GestureResponsePolicy getGRP() { - return grp; - } - - /** - * Check whether the MapMouseInterpreter is responding to events. - * - * @return true if willing to respond to MouseEvents. - */ - public boolean isActive() { - return active; - } - - /** - * Set whether the MapMouseInterpreter responds - * - * @param active - */ - public void setActive(boolean active) { - this.active = active; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/TestResponsePolicy.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/TestResponsePolicy.java deleted file mode 100644 index a649f3283..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/TestResponsePolicy.java +++ /dev/null @@ -1,133 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/TestResponsePolicy.java,v -// $ -// $RCSfile: TestResponsePolicy.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.Component; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.JMenuItem; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; - -public class TestResponsePolicy implements GestureResponsePolicy { - - protected OMGraphicList selected; - - public TestResponsePolicy() {} - - ////// Queries - - public boolean isHighlightable(OMGraphic omg) { - Debug.output("isHighlightable(" + omg.getClass().getName() + ")"); - return true; - } - - public boolean isSelectable(OMGraphic omg) { - Debug.output("isSelectable(" + omg.getClass().getName() + ")"); - return true; - } - - public boolean receivesMapEvents() { - Debug.output("receivesMapEvents"); - return true; - } - - public OMGraphicList getSelected() { - Debug.output("getSelected()"); - return selected; - } - - ////// Reactions - - /** Fleeting change of appearance. */ - public void highlight(OMGraphic omg) { - Debug.output("highlight(" + omg.getClass().getName() + ")"); - } - - public void unhighlight(OMGraphic omg) { - Debug.output("unhighlight(" + omg.getClass().getName() + ")"); - } - - public void select(OMGraphicList omgl) { - Debug.output("select(" + omgl.getDescription() + ")"); - selected = omgl; - } - - public void deselect(OMGraphicList omgl) { - Debug.output("deselect(" + omgl.getDescription() + ")"); - selected = null; - } - - public OMGraphicList cut(OMGraphicList omgl) { - Debug.output("cut(" + omgl.getDescription() + ")"); - return omgl; - } - - public OMGraphicList copy(OMGraphicList omgl) { - Debug.output("copy(" + omgl.getDescription() + ")"); - return omgl; - } - - public void paste(OMGraphicList omgl) { - Debug.output("paste(" + omgl.getDescription() + ")"); - } - - public String getInfoText(OMGraphic omg) { - Debug.output("getInfoTextFor(" + omg.getClass().getName() + ")"); - return omg.getClass().getName(); - } - - public String getToolTipTextFor(OMGraphic omg) { - Debug.output("getToolTipTextFor(" + omg.getClass().getName() + ")"); - return "TextResponsePolicy ToolTipText"; - } - - public List getItemsForMapMenu(MapMouseEvent me) { - Debug.output("getMenuForMap(MAP)"); - return null; - } - - public List getItemsForOMGraphicMenu(OMGraphic omg) { - Debug.output("getMenuFor(" + omg.getClass().getName() + ")"); - List list = new LinkedList(); - list.add(new JMenuItem(omg.getClass().getName())); - return list; - } - - public boolean mouseOver(MapMouseEvent mme) { - Debug.output("mouseOver(" + mme + ")"); - return true; - } - - public boolean leftClick(MapMouseEvent mme) { - Debug.output("leftClick(" + mme + ")"); - return true; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/event/package.html deleted file mode 100644 index ba5cb04be..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/event/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - -Provides classes for event notification of OMGraphic changes. - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/BasicGeometry.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/BasicGeometry.java deleted file mode 100644 index 25ff1a34e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/BasicGeometry.java +++ /dev/null @@ -1,882 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/geom/BasicGeometry.java,v $ -// $RCSfile: BasicGeometry.java,v $ -// $Revision: 1.19 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.geom; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.FlatteningPathIterator; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.PathIterator; -import java.io.Serializable; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * Base class implementation of OpenMap OMGeometry, the super class for all - * OMGraphics. - *

- * - * The geometry classes are intended to pull the object location data out of the - * OMGraphics. If you have a bunch of OMGraphics that are all rendered with - * common attributes, you can create a bunch of OMGeometry objects to plavce in - * a OMGeometryList that will render them all alike. - *

- * - * The BasicGeometry can hold attributes. Traditionally, there has been an - * appObject (Application Object) that could be set in the OMGeometry/OMGraphic - * to maintain a pointer for additional information about the shape. This has - * been modified so that an attribute Map can be maintained for the - * BasicGeometry to let it hold on to a bunch of organized attributes. To - * maintain backward compatibility, the setAppObject() and getAppObject() - * methods have been modified to manage a java.util.Map along with any Objects - * stored in the appObject. Using the setAppObject() and getAppObject() methods - * in conjunction with other attributes will cause that object to be stored in - * the attribute Map under the APP_OBJECT_KEY Map key. - * - * @see PolygonGeometry - * @see PolylineGeometry - * @see com.bbn.openmap.omGraphics.OMGeometryList - * @see Projection - */ -public abstract class BasicGeometry implements OMGeometry, Serializable, OMGraphicConstants { - - /** - * The lineType describes the way a line will be drawn between points. - * LINETYPE_STRAIGHT will mean the line is drawn straight between the pixels - * of the endpoints of the line, across the window. LINETYPE_GREATCIRCLE - * means the line will be drawn on the window representing the shortest line - * along the land. LINETYPE_RHUMB means a line will be drawn along a - * constant bearing between the two points. - */ - protected int lineType = LINETYPE_UNKNOWN; - - /** Flag to indicate that the object needs to be re-projected. */ - protected transient boolean needToRegenerate = true; - - /** - * Attribute Map for this Geometry/OMGraphic. - */ - protected Map attributes; - - /** - * A flag to render this geometry visible. - */ - protected boolean visible = true; - - /** - * The Java 2D containing the Shape of the Graphic. There may be several - * paths appended to each other, in case the graphic wraps around the earth, - * and we need to show the other edge of the graphic on the other side of - * the earth. - */ - protected transient GeneralPath shape = null; - - // //////////////////////////////////////////////////////// - - /** - * Set the line type for the graphic, which will affect how the lines will - * be drawn. See the definition of the lineType parameter. Accepts - * LINETYPE_RHUMB, LINETYPE_STRAIGHT and LINETYPE_GREATCIRCLE. Any weird - * values get set to LINETYPE_STRAIGHT. - * - * @param value the line type of the graphic. - */ - public void setLineType(int value) { - if (lineType == value) - return; - setNeedToRegenerate(true); // flag dirty - - lineType = value; - } - - /** - * Return the line type. - * - * @return the linetype - LINETYPE_RHUMB, LINETYPE_STRAIGHT, - * LINETYPE_GREATCIRCLE or LINETYPE_UNKNOWN. - */ - public int getLineType() { - return lineType; - } - - /** - * Return the render type. - * - * @return the rendertype of the object - RENDERTYPE_LATLON, RENDERTYPE_XY, - * RENDERTYPE_OFFSET and RENDERTYPE_UNKNOWN. - */ - public abstract int getRenderType(); - - /** - * Sets the regenerate flag for the graphic. This flag is used to determine - * if extra work needs to be done to prepare the object for rendering. This - * also sets the shape to null; - * - * @param value boolean - */ - public void setNeedToRegenerate(boolean value) { - needToRegenerate = value; - if (value == true) { - setShape(null); - } - } - - /** - * Return the regeneration status. - * - * @return boolean - */ - public boolean getNeedToRegenerate() { - return needToRegenerate; - } - - /** - * Set the visibility variable. NOTE:
- * This is checked by the OMGeometryList when it iterates through its list - * for render and gesturing. It is not checked by the internal OMGeometry - * methods, although maybe it should be... - * - * @param visible boolean - */ - public void setVisible(boolean visible) { - this.visible = visible; - } - - /** - * Get the visibility variable. - * - * @return boolean - */ - public boolean isVisible() { - return visible; - } - - /** - * Let the geometry object know it's selected. No action mandated. - */ - public void select() { - } - - /** - * Let the geometry object know it's deselected. No action mandated. - */ - public void deselect() { - } - - /** - * Method to extend if you don't like Hashtables used for attribute table. - */ - protected Map createAttributeMap() { - return Collections.synchronizedMap(new LinkedHashMap()); - } - - /** - * Adds a key-value pair to the attribute Map. The Map will be created if it - * doesn't exist. - */ - public void putAttribute(Object key, Object value) { - if (key != null) { - getAttributes().put(key, value); - } - } - - /** - * Returns the object stored in a Map stored in the appObject. If the - * appObject is a Map, the key will be passed to it even if the Map isn't - * considered to be the 'official' attribute Map. - */ - public Object getAttribute(Object key) { - if (key != null) { - return getAttributes().get(key); - } - return null; - } - - /** - * Removes the object stored in a Map stored in the appObject. If the - * appObject is a Map, the key will be passed to it even if the Map isn't - * considered to be the 'official' attribute Map. Returns the removed value - * from the Map, or null if there wasn't a value for the given key. - */ - public Object removeAttribute(Object key) { - if (key != null) { - return getAttributes().remove(key); - } - return null; - } - - /** - * Removes all of the objects stored in a Map stored in the appObject. If - * the appObject is a Map, the clear command will be passed to it even if - * the Map isn't considered to be the 'official' attribute Map. - */ - public void clearAttributes() { - getAttributes().clear(); - } - - /** - * Returns the 'official' attribute Map. - */ - public Map getAttributes() { - if (attributes == null) { - attributes = createAttributeMap(); - } - return attributes; - } - - /** - * Sets the 'official' attribute Map, moving any appObject that isn't - * currently the 'official' attribute Map into the map under the - * APP_OBJECT_KEY. - */ - public void setAttributes(Map atts) { - attributes = atts; - } - - /** - * OMGeometry method for returning a simple description of the OMGraphic. - */ - public String getDescription() { - String cname = getClass().getName(); - int lastPeriod = cname.lastIndexOf('.'); - if (lastPeriod != -1) { - cname = cname.substring(lastPeriod + 1); - } - return cname; - } - - // //////////////////////////////////////////////////////////////////////// - - /** - * Prepare the geometry for rendering. This must be done before calling - * render()! If a vector graphic has lat-lon components, then - * we project these vertices into x-y space. For raster graphics we prepare - * in a different fashion. - *

- * If the generate is unsuccessful, it's usually because of some oversight, - * (for instance if proj is null), and if debugging is enabled, - * a message may be output to the controlling terminal. - *

- * - * @param proj Projection - * @return boolean true if successful, false if not. - * @see #regenerate - */ - public abstract boolean generate(Projection proj); - - /** - * A check to see if the OMGeometry is ready for rendering. Calls getShape() - * to pass to other isRenderable() method. - */ - public boolean isRenderable() { - return isRenderable(getShape()); - } - - /** - * A check to see if the OMGeometry is ready for rendering. This is the - * method you should call, with a the handle to the shape object you're - * interested in rendering. - * - * @param shape the projected shape of the OMGraphic - * @return true if draw/fill should be called. - */ - public boolean isRenderable(Shape shape) { - return (!getNeedToRegenerate() && isVisible() && shape != null); - } - - /** - * Paints the graphic, as a filled shape. The Graphics object should be set - * for rendering. Calls the getShape() method, which is synchronized, before - * calling the other fill method. It's better to call the other one after - * doing renderable check, and then call draw, with a single handle to the - * current shape object. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - */ - public void fill(Graphics g) { - fill(g, getShape()); - } - - /** - * Paint the graphic, as a filled shape. The Graphics object should be set - * for rendering. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - * @param s Shape object to fill for rendering. - */ - public void fill(Graphics g, Shape s) { - if (s != null) { - ((Graphics2D) g).fill(s); - } - } - - /** - * Paint the graphic, as an outlined shape. The Graphics object should be - * ready for rendering (paint, stroke). - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - * @param s Shape object to render. - */ - public void draw(Graphics g, Shape s) { - if (s != null) { - ((Graphics2D) g).draw(s); - } - } - - /** - * Paint the graphic, as an outlined shape. The Graphics object should be - * ready for rendering (paint, stroke). Calls the getShape() method, which - * is synchronized, before calling the other fill method. It's better to - * call the other one after doing renderable check and fill, with a single - * handle to the current shape object. - *

- * - * This paints the graphic into the Graphics context. This is similar to - * paint() function of java.awt.Components. Note that if the - * graphic has not been generated or if it isn't visible, it will not be - * rendered. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own render method. - * - * @param g Graphics2D context to render into. - */ - public void draw(Graphics g) { - draw(g, getShape()); - } - - /** - * Sure it renders, but not with any controllable rendering attributes - the - * colors and strokes are what are set in the Graphics. The OMGeometryList - * controls this better, this method shouldn't really be called directly. - */ - public void render(Graphics g) { - Shape s = getShape(); - if (isRenderable(s)) { - fill(g, s); - draw(g, s); - } - } - - /** - * Return the shortest distance from the edge of a graphic to an XY-point. - *

- * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - public float distanceToEdge(double x, double y) { - float distance = Float.POSITIVE_INFINITY; - - GeneralPath shape = getShape(); - if (!getNeedToRegenerate() && shape != null) { - distance = BasicGeometry.distanceToEdge(x, y, shape); - } - - return distance; - } - - /** - * Return the shortest distance from the edge of a Shape object to an - * XY-point. - *

- * Method taken and adapted from - * {@link BasicGeometry#distanceToEdge(double, double)} - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @param shape Shape object to test. - * @return float distance, in pixels, from Shape to the point. Returns - * Float.POSITIVE_INFINITY if the Shape is null. - */ - public static float distanceToEdge(final double x, final double y, final Shape shape) { - float distance = Float.POSITIVE_INFINITY; - - if (shape == null) { - return distance; - } - - final PathIterator pi2 = shape.getPathIterator(null); - final FlatteningPathIterator pathIt = new FlatteningPathIterator(pi2, .25); - final double[] coords = new double[6]; - double endPntX = Double.NaN; - double endPntY = Double.NaN; - - double lastMovedToPntX = Double.NaN; - double lastMovedToPntY = Double.NaN; - - while (!pathIt.isDone()) { - final int type = pathIt.currentSegment(coords); - - if (type == PathIterator.SEG_LINETO) { - final double startPntX = endPntX; - final double startPntY = endPntY; - endPntX = coords[0]; - endPntY = coords[1]; - - final float dist = (float) Line2D.ptSegDist(startPntX, startPntY, endPntX, endPntY, x, y); - - if (dist < distance) { - distance = dist; - } - } else if (type == PathIterator.SEG_MOVETO) { - endPntX = coords[0]; - endPntY = coords[1]; - lastMovedToPntX = coords[0]; - lastMovedToPntY = coords[1]; - } else if (type == PathIterator.SEG_CLOSE) { - final double startPntX = lastMovedToPntX; - final double startPntY = lastMovedToPntY; - endPntX = coords[0]; - endPntY = coords[1]; - - final float dist = (float) Line2D.ptSegDist(startPntX, startPntY, endPntX, endPntY, x, y); - - if (dist < distance) { - distance = dist; - } - } - - pathIt.next(); - } - - return distance; - } - - /** - * Return the shortest distance from the graphic to an XY-point. Checks to - * see of the point is contained within the OMGraphic, which may, or may not - * be the right thing for clear OMGraphics or lines. - *

- * - * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own distance method. - *

- * - * Calls _distance(x, y); - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - public float distance(double x, double y) { - return _distance(x, y); - } - - /** - * Return the shortest distance from the graphic to an XY-point. Checks to - * see of the point is contained within the OMGraphic, which may, or may not - * be the right thing for clear OMGraphics or lines. - *

- * - * _distance was added so subclasses could make this call if their - * geometries/attributes require this action (when fill color doesn't - * matter). - * - * @param x X coordinate of the point. - * @param y Y coordinate of the point. - * @return float distance, in pixels, from graphic to the point. Returns - * Float.POSITIVE_INFINITY if the graphic isn't ready (ungenerated). - */ - protected float _distance(double x, double y) { - float distance = Float.POSITIVE_INFINITY; - - GeneralPath shape = getShape(); - - if (getNeedToRegenerate() || shape == null) { - return distance; - } - - if (shape.contains(x, y)) { - // if (Debug.debugging("omgraphicdetail")) { - // Debug.output(" contains " + x + ", " + y); - // } - return 0f; - } else { - return distanceToEdge(x, y); - } - } - - /** - * Answers the question whether or not the OMGeometry contains the given - * pixel point. - *

- * This method used to be abstract, but with the conversion of OMGeometrys - * to internally represent themselves as java.awt.Shape objects, it's a more - * generic method. If the OMGeometry hasn't been updated to use Shape - * objects, it should have its own contains method. - *

- * This method duplicates a java.awt.Shape method, with some protection - * wrapped around it. If you have other queries for the internal Shape - * object, just ask for it and then ask it directly. This method is provided - * because it is the most useful, used when determining if a mouse event is - * occurring over an object on the map. - * - * @param x X pixel coordinate of the point. - * @param y Y pixel coordinate of the point. - * @return getShape().contains(x, y), false if the OMGraphic hasn't been - * generated yet. - */ - public boolean contains(double x, double y) { - Shape shape = getShape(); - boolean ret = false; - - if (shape != null) { - ret = shape.contains(x, y); - } - - return ret; - } - - /** - * Invoke this to regenerate a "dirty" graphic. This method is a wrapper - * around the generate() method. It invokes - * generate() only if needToRegenerate() on the - * graphic returns true. To force a graphic to be generated, call - * generate() directly. - * - * @param proj the Projection - * @return true if generated, false if didn't do it (maybe a problem). - * @see #generate - */ - public boolean regenerate(Projection proj) { - if (proj == null) { - return false; - } - - if (getNeedToRegenerate()) { - return generate(proj); - } - - return false; - } - - /** - * Get the java.awt.Shape object that represents the projected graphic. The - * array will one Shape object even if the object wraps around the earth and - * needs to show up in more than one place on the map. In conditions like - * that, the Shape will have multiple parts. - *

- * - * The java.awt.Shape object gives you the ability to do a little spatial - * analysis on the graphics. - * - * @return java.awt.geom.GeneralPath (a java.awt.Shape object), or null if - * the graphic needs to be generated with the current map - * projection, or null if the OMGeometry hasn't been updated to use - * Shape objects for its internal representation. - */ - public synchronized GeneralPath getShape() { - return shape; - } - - /** - * Set the java.awt.Shape object that represents the projected graphic. This - * Shape object should be internally generated, but this method is provided - * to clear out the object to save memory, or to allow a little - * customization if your requirements dictate. - *

- * - * The java.awt.Shape object gives you the ability to do a little spatial - * analysis on the graphics. - * - * @param gp java.awt.geom.GeneralPath, or null if the graphic needs to be - * generated with the current map projection or to clear out the - * object being held by the OMGeometry. - */ - public synchronized void setShape(GeneralPath gp) { - shape = gp; - } - - /** - * Create a Shape object given an array of x points and y points. The x - * points a y points should be projected. This method is used by subclasses - * that get projected coordinates out of the projection classes, and they - * need to build a Shape object from those coordinates. - * - * @param xpoints projected x coordinates - * @param ypoints projected y coordinates - * @param isPolygon whether the points make up a polygon, or a polyline. If - * it's true, the Shape object returned is a Polygon. If false, the - * Shape returned is a GeneralPath object. - * @return The Shape object for the points. - */ - public static GeneralPath createShape(float[] xpoints, float[] ypoints, boolean isPolygon) { - return createShape(xpoints, ypoints, 0, xpoints.length, isPolygon); - } - - /** - * Create a Shape object given an array of x points and y points. The x - * points a y points should be projected. This method is used by subclasses - * that get projected coordinates out of the projection classes, and they - * need to build a Shape object from those coordinates. - * - * @param xpoints projected x coordinates - * @param ypoints projected y coordinates - * @param startIndex the starting coordinate index in the array. - * @param length the number of points to use from the array for the shape. - * @param isPolygon whether the points make up a polygon, or a polyline. If - * it's true, the Shape object returned is a Polygon. If false, the - * Shape returned is a GeneralPath object. - * @return The Shape object for the points. - */ - public static GeneralPath createShape(float[] xpoints, float[] ypoints, int startIndex, - int length, boolean isPolygon) { - // used to return a Shape - - if (xpoints == null || ypoints == null) { - return null; - } - - if (startIndex < 0) { - startIndex = 0; - } - - if (length > xpoints.length - startIndex) { - // Do as much as you can... - length = xpoints.length - startIndex - 1; - } - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, length); - - if (length > startIndex) { - path.moveTo(xpoints[startIndex], ypoints[startIndex]); - for (int j = startIndex + 1; j < length; j++) { - path.lineTo(xpoints[j], ypoints[j]); - } - - if (isPolygon) { - path.closePath(); - } - } - - return path; - } - - /** - * Utility method that iterates over a Shape object and prints out the - * points. - */ - public static void describeShapeDetail(Shape shape) { - describeShapeDetail(shape, .25); - } - - /** - * Utility method that iterates over a Shape object and prints out the - * points. The flattening is used for a FlatteningPathIterator, controlling - * the scope of the path traversal. - */ - public static void describeShapeDetail(Shape shape, double flattening) { - PathIterator pi2 = shape.getPathIterator(null); - FlatteningPathIterator pi = new FlatteningPathIterator(pi2, flattening); - double[] coords = new double[6]; - int pointCount = 0; - - Debug.output(" -- start describeShapeDetail with flattening[" + flattening + "]"); - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - Debug.output(" Shape point [" + type + "] (" + (pointCount++) + ") " + coords[0] + ", " - + coords[1]); - pi.next(); - } - - Debug.output(" -- end (" + pointCount + ")"); - } - - /** - * Convenience method to add the coordinates to the given GeneralPath. You - * need to close the path yourself if you want it to be a polygon. - * - * @param toShape the GeneralPath Shape object to add the coordinates to. - * @param xpoints horizontal pixel coordinates. - * @param ypoints vertical pixel coordinates. - * @return toShape, with coordinates appended. - */ - public static GeneralPath appendShapeEdge(GeneralPath toShape, float[] xpoints, - float[] ypoints) { - return appendShapeEdge(toShape, xpoints, ypoints, 0, xpoints.length); - } - - /** - * Convenience method to add the coordinates to the given GeneralPath. You - * need to close the path yourself if you want it to be a polygon. - * - * @param toShape the GeneralPath Shape object to add the coordinates to. - * @param xpoints horizontal pixel coordinates. - * @param ypoints vertical pixel coordinates. - * @param startIndex the index into pixel coordinate array to start reading - * from. - * @param length the number of coordinates to add. - * @return toShape, with coordinates appended. - */ - public static GeneralPath appendShapeEdge(GeneralPath toShape, float[] xpoints, float[] ypoints, - int startIndex, int length) { - return appendShapeEdge(toShape, createShape(xpoints, ypoints, startIndex, length, false)); - } - - /** - * Convenience method to append the edge of a GeneralPath Shape to another - * GeneralPath Shape. A PathIterator is used to figure out the points to use - * to add to the toShape. You need to close the path yourself if you want it - * to be a polygon. Assumes that the two paths should be connected. - * - * @param toShape the GeneralPath Shape object to add the edge to. - * @param addShape the GeneralPath Shape to add to the toShape. - * @return toShape, with coordinates appended. Returns addShape if toShape - * was null. - */ - public static GeneralPath appendShapeEdge(GeneralPath toShape, GeneralPath addShape) { - return appendShapeEdge(toShape, addShape, true); - } - - /** - * Convenience method to append the edge of a GeneralPath Shape to another - * GeneralPath Shape. A PathIterator is used to figure out the points to use - * to add to the toShape. You need to close the path yourself if you want it - * to be a polygon. - * - * @param toShape the GeneralPath Shape object to add the edge to. - * @param addShape the GeneralPath Shape to add to the toShape. - * @param lineTo specify whether the first point of the appended path is - * connected to the original path. True to connect. - * @return toShape, with coordinates appended. Returns addShape if toShape - * was null. - */ - public static GeneralPath appendShapeEdge(GeneralPath toShape, GeneralPath addShape, - boolean lineTo) { - - boolean DEBUG = Debug.debugging("arealist"); - int pointCount = 0; - - // If both null, return null. - if (addShape == null) { - return toShape; - } - - if (toShape == null) { - return addShape; - } - - toShape.append(addShape, lineTo); - return toShape; - - /* - * - * PathIterator pi2 = addShape.getPathIterator(null); - * FlatteningPathIterator pi = new FlatteningPathIterator(pi2, .25); - * double[] coords = new double[6]; - * - * while (!pi.isDone()) { int type = pi.currentSegment(coords); if - * (lineTo) { if (DEBUG) { Debug.output(" adding point [" + type + "] (" - * + (pointCount++) + ") " + (float) coords[0] + ", " + (float) - * coords[1]); } toShape.lineTo((float) coords[0], (float) coords[1]); - * - * } else { if (DEBUG) { Debug.output("Creating new shape, first point " - * + (float) coords[0] + ", " + (float) coords[1]); } - * toShape.moveTo((float) coords[0], (float) coords[1]); lineTo = true; - * } pi.next(); } - * - * if (DEBUG) { Debug.output(" -- end point (" + pointCount + ")"); } - * - * return toShape; - */ - } - - /** - * Create a general path from a point plus a height and width; - */ - public static GeneralPath createBoxShape(float x, float y, int width, int height) { - float[] xs = new float[4]; - float[] ys = new float[4]; - - xs[0] = x; - ys[0] = y; - xs[1] = x + width; - ys[1] = y; - xs[2] = x + width; - ys[2] = y + height; - xs[3] = x; - ys[3] = y + height; - - return createShape(xs, ys, true); - } - - public void restore(OMGeometry source) { - this.lineType = source.getLineType(); - this.visible = source.isVisible(); - this.attributes = source.getAttributes(); - this.needToRegenerate = true; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/NonRegional.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/NonRegional.java deleted file mode 100644 index aa5817501..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/NonRegional.java +++ /dev/null @@ -1,27 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -/** - * This interface is used to distinguish editable shapes that do not have - * fillable regions, ie lines and points - */ -package com.bbn.openmap.omGraphics.geom; - -/** - * @author phelinek - * Indicates that a shape does not have an internal region - i.e. a point or line - * - */ -public interface NonRegional { - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolygonGeometry.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolygonGeometry.java deleted file mode 100644 index 3ddd72fbe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolygonGeometry.java +++ /dev/null @@ -1,773 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/geom/PolygonGeometry.java,v $ -// $RCSfile: PolygonGeometry.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.geom; - -import java.awt.Point; -import java.awt.geom.GeneralPath; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.DrawUtil; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * Graphic object that represents a polygon. - *

- * All of the OMGraphics are moving to having their internal - * representation as java.awt.Shape objects. Unfortunately, this has - * the side effect of slowing OMPolys down, because the way that the - * projection classes handle transformations cause more objects to be - * allocated and more loops to be run through. So, by default, the - * OMPoly does NOT use Shape objects internally, to keep layers that - * throw down many, many polys running quickly. If you want to do some - * spatial analysis on an OMPoly, call setDoShapes(true) on it, then - * generate(Projection), and then call getShapes() to get the - * java.awt.Shape objects for the poly. You can then run the different - * Shape spatial analysis methods on the Shape objects. - * - *

NOTES:

- *
    - *
  • See the - * RESTRICTIONS on Lat/Lon polygons/polylines. Not following the - * guidelines listed may result in ambiguous/undefined shapes! Similar - * assumptions apply to the other vector graphics that we define: - * circles, ellipses, rects, lines. - *
  • LatLon OMPolys store latlon coordinates internally in radian - * format for efficiency in projecting. Subclasses should follow this - * model. - *
  • Holes in the poly are not supported. If you want holes, use - * multiple PolyGeometrys in a OMGeometryList. - *

    - *

- *

TODO:

- *
    - *
  • Polar filled-polygon correction for Cylindrical projections - * (like OMCircle). - *
- */ -public abstract class PolygonGeometry extends BasicGeometry implements - Serializable, OMGeometry { - - /** Internal array of projected x coordinate arrays. */ - protected float[][] xpoints = new float[0][0]; - - /** Internal array of projected y coordinate arrays. */ - protected float[][] ypoints = new float[0][0]; - - /** - * Whether it is a polygon, as opposed to a polyline. Should be a - * polygon, since that is what is being created. The - * PolylineGeometry subclasses set this to false. - */ - protected boolean isPolygon = true; - - /** - * Flag for telling the PolygonGeometry to use the Shape objects - * to represent itself internally. See intro for more info. - */ - protected boolean doShapes = true; - - protected PolygonGeometry() {} - - public void setDoShapes(boolean set) { - doShapes = set; - } - - public boolean getDoShapes() { - return doShapes; - } - - protected void setIsPolygon(boolean set) { - isPolygon = set; - } - - public boolean getIsPolygon() { - return isPolygon; - } - - /** - * Since OMPoly has the option to not create a Shape, this method - * is here to create it if it is asked for. The OMPoly needs to be - * generated. - */ - protected abstract GeneralPath createShape(); - - /** - * Return the shortest distance from the graphic to an XY-point. - * This works if generate() has been successful. - * - * @param x horizontal pixel location. - * @param y vertical pixel location. - * @return the distance of the object to the location given. - */ - public float distance(double x, double y) { - if (getShape() != null) { - return super.distance(x, y); - } - - // If shape is null, then we have to do things the old way. - - float temp, distance = Float.POSITIVE_INFINITY; - - if (getNeedToRegenerate()) { - return distance; - } - - // safety: grab local reference of projected points - float[][] xpts = xpoints; - float[][] ypts = ypoints; - float[] _x, _y; - int len = xpts.length; - - for (int i = 0; i < len; i++) { - _x = xpts[i]; - _y = ypts[i]; - - // check if point inside polygon - if (DrawUtil.inside_polygon(_x, _y, x, y)) - return 0f; // close as can be - - // get the closest point - temp = DrawUtil.closestPolyDistance(_x, _y, x, y, false); - if (temp < distance) - distance = temp; - } - - return distance; - } - - /** - * Get the array of java.awt.Shape objects that represent the - * projected graphic. The array will contain more than one Shape - * object of the object wraps around the earth and needs to show - * up in more than one place on the map. - *

- * - * The java.awt.Shape object gives you the ability to do a little - * spatial analysis on the graphics. - * - * @return java.awt.Shape[], or null if the graphic needs to be - * generated with the current map projection, or null if - * the OMGeometry hasn't been updated to use Shape objects - * for its internal representation. - */ - public synchronized GeneralPath getShape() { - GeneralPath shape = super.getShape(); - if (shape == null && !getNeedToRegenerate() && !doShapes) { - // Since polygons have the option of not creating shape - // objects, should create one if asked. - shape = createShape(); - setShape(shape); - } - return shape; - } - - public static class LL extends PolygonGeometry { - - /** raw float lats and lons stored internally in radians. */ - protected double[] rawllpts = null; - - /** - * Number of segments to draw (used only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB lines). - */ - protected int nsegs = -1; - - /** - * Create an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for - * more efficient handling internally if it's not already in - * radians! For even better performance, you should send us an - * array already in radians format! - *
  • If you want the poly to be connected (as a polygon), - * you need to ensure that the first and last coordinate pairs - * are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, - * lat, lon, etc. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, - * and if < 1, this value is generated internally) - */ - public LL(double[] llPoints, int units, int lType, int nsegs) { - setLineType(lType); - setLocation(llPoints, units); - setNumSegs(nsegs); - } - - /** - * Create an LL PolygonGeometry from a list of float lat/lon - * pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for - * more efficient handling internally if it's not already in - * radians! For even better performance, you should send us an - * array already in radians format! - *
  • If you want the poly to be connected (as a polygon), - * you need to ensure that the first and last coordinate pairs - * are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, - * lat, lon, etc. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public LL(double[] llPoints, int units, int lType) { - this(llPoints, units, lType, -1); - } - - /** - * Set an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for - * more efficient handling internally if it's not already in - * radians! If you don't want the array to be changed, send in - * a copy. - *
  • If you want the poly to be connected (as a polygon), - * you need to ensure that the first and last coordinate pairs - * are the same. - *
- * This is for RENDERTYPE_LATLON polys. - * - * @param llPoints array of lat/lon points, arranged lat, lon, - * lat, lon, etc. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - */ - public void setLocation(double[] llPoints, int units) { - if (units == OMGraphic.DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(llPoints); - } - rawllpts = llPoints; - setNeedToRegenerate(true); - } - - /** - * Return the rawllpts array. NOTE: this is an unsafe method - * to access the rawllpts array. Use with caution. These are - * RADIANS! - * - * @return float[] rawllpts of lat, lon, lat, lon - */ - public double[] getLatLonArray() { - return rawllpts; - } - - /** - * Set the number of subsegments for each segment in the poly. - * (This is only for LINETYPE_GREATCIRCLE or LINETYPE_RHUMB - * line types, and if < 1, this value is generated - * internally). - * - * @param nsegs number of segment points - */ - public void setNumSegs(int nsegs) { - this.nsegs = nsegs; - } - - /** - * Get the number of subsegments for each segment in the poly. - * (This is only for LINETYPE_GREATCIRCLE or LINETYPE_RHUMB - * line types). - * - * @return int number of segment points - */ - public int getNumSegs() { - return nsegs; - } - - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", - "OMPoly: null projection in generate!"); - return false; - } - - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians. - ArrayList vector; - if (proj instanceof GeoProj) { - vector = ((GeoProj) proj).forwardPoly(rawllpts, - lineType, - nsegs, - isPolygon); - } else { - vector = proj.forwardPoly(rawllpts, isPolygon); - } - int size = vector.size(); - - if (!doShapes) { - xpoints = new float[(int) (size / 2)][0]; - ypoints = new float[xpoints.length][0]; - } - - // We could call create shape, but this is more efficient. - GeneralPath projectedShape = null; - for (int i = 0, j = 0; i < size; i += 2, j++) { - if (doShapes) { - GeneralPath gp = BasicGeometry.createShape((float[]) vector.get(i), - (float[]) vector.get(i + 1), - isPolygon); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - - } else { - xpoints[j] = (float[]) vector.get(i); - ypoints[j] = (float[]) vector.get(i + 1); - } - } - - setShape(projectedShape); - setNeedToRegenerate(false); - return true; - } - - protected GeneralPath createShape() { - - if (getNeedToRegenerate()) { - return null; - } - - int size = xpoints.length; - GeneralPath projectedShape = null; - for (int i = 0; i < size; i++) { - GeneralPath gp = BasicGeometry.createShape(xpoints[i], - ypoints[i], - isPolygon); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - return projectedShape; - } - - public int getRenderType() { - return RENDERTYPE_LATLON; - } - } - - public static class XY extends PolygonGeometry { - - /** The array of x pixel coordinates. */ - protected float[] xs = null; - - /** The array of y pixel coordinates. */ - protected float[] ys = null; - - /** - * To satify the Offset constructor complaint. - */ - protected XY() {} - - /** - * Create an OMPoly from a list of xy pairs. If you want the - * poly to be connected, you need to ensure that the first and - * last coordinate pairs are the same. - * - * @param xypoints array of x/y points, arranged x, y, x, y, - * etc. - */ - public XY(float[] xypoints) { - setLocation(xypoints); - } - - /** - * Create an x/y OMPoly. If you want the poly to be connected, - * you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public XY(float[] xPoints, float[] yPoints) { - setLocation(xPoints, yPoints); - } - - /** - * Set an OMPoly from a list of xy pixel pairs. If you want - * the poly to be connected, you need to ensure that the first - * and last coordinate pairs are the same. This is for - * RENDERTYPE_XY polys. - * - * @param xypoints array of x/y points, arranged x, y, x, y, - * etc. - */ - public void setLocation(float[] xypoints) { - int end = xypoints.length >> 1; - xs = new float[end]; - ys = new float[end]; - for (int i = 0, j = 0; i < end; i++, j += 2) { - xs[i] = xypoints[j]; - ys[i] = xypoints[j + 1]; - } - setNeedToRegenerate(true); - } - - /** - * Set an OMPoly from a x/y coordinates. If you want the poly - * to be connected, you need to ensure that the first and last - * coordinate pairs are the same. This is for RENDERTYPE_XY - * polys. - * - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public void setLocation(float[] xPoints, float[] yPoints) { - xs = xPoints; - ys = yPoints; - setNeedToRegenerate(true); - } - - /** - * Set the array of x points. - */ - public void setXs(float[] x) { - xs = x; - setNeedToRegenerate(true); - } - - /** - * Get the array of x points. - */ - public float[] getXs() { - return xs; - } - - /** - * Set the array of y points. - */ - public void setYs(float[] y) { - ys = y; - setNeedToRegenerate(true); - } - - /** - * Get the array of y points. - */ - public float[] getYs() { - return ys; - } - - public boolean generate(Projection proj) { - - if (proj == null) { - Debug.message("omgraphic", - "OMPoly: null projection in generate!"); - setNeedToRegenerate(true); - return false; - } - - if (xs == null) { - Debug.message("omgraphic", - "OMPoly x/y rendertype null coordinates"); - return false; - } - - // Need to keep these around for the LabeledOMPoly - xpoints = new float[1][0]; - xpoints[0] = xs; - ypoints = new float[1][0]; - ypoints[0] = ys; - - if (doShapes) { - setShape(createShape()); - } else { - setShape(null); - } - setNeedToRegenerate(false); - return true; - } - - protected GeneralPath createShape() { - - if (getNeedToRegenerate()) { - return null; - } - - return BasicGeometry.createShape(xpoints[0], ypoints[0], isPolygon); - } - - public int getRenderType() { - return RENDERTYPE_XY; - } - } - - public static class Offset extends XY { - - /** - * Translation offsets. The xy points are relative to the - * position of fixed latlon point. - */ - public final static int COORDMODE_ORIGIN = 0; - - /** - * Delta offsets. Each xy point in the array is relative to - * the previous point, and the first point is relative to the - * fixed latlon point. - */ - public final static int COORDMODE_PREVIOUS = 1; - - /** - * The latitude of the starting point of the poly. Stored as - * radians! - */ - protected double lat = 0.0f; - - /** - * The longitude of the starting point of the poly. Stored as - * radians! - */ - protected double lon = 0.0f; - - /** - * Type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - protected int coordMode = COORDMODE_ORIGIN; - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want - * the poly to be connected, you need to ensure that the first - * and last coordinate pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xypoints float[] of x,y pairs - * @param cMode offset coordinate mode - */ - public Offset(double latPoint, double lonPoint, float[] xypoints, int cMode) { - setLocation(latPoint, lonPoint, OMGraphic.DECIMAL_DEGREES, xypoints); - setCoordMode(cMode); - } - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want - * the poly to be connected, you need to ensure that the first - * and last coordinate pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - * @param cMode offset coordinate mode - */ - public Offset(double latPoint, double lonPoint, float[] xPoints, - float[] yPoints, int cMode) { - - setLocation(latPoint, - lonPoint, - OMGraphic.DECIMAL_DEGREES, - xPoints, - yPoints); - setCoordMode(cMode); - } - - /** - * Set the location based on a latitude, longitude, and some - * xy points. The coordinate mode and the polygon setting are - * the same as in the constructor used. - * - * @param latPoint latitude in decimal degrees. - * @param lonPoint longitude in decimal degrees. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param xypoints array of x/y points, arranged x, y, x, y, - * etc. - */ - public void setLocation(double latPoint, double lonPoint, int units, - float[] xypoints) { - if (units == OMGraphic.DECIMAL_DEGREES) { - lat = ProjMath.degToRad(latPoint); - lon = ProjMath.degToRad(lonPoint); - } else { - lat = latPoint; - lon = lonPoint; - } - int end = xypoints.length >> 1; - xs = new float[end]; - ys = new float[end]; - for (int i = 0, j = 0; i < end; i++, j += 2) { - xs[i] = xypoints[j]; - ys[i] = xypoints[j + 1]; - } - setNeedToRegenerate(true); - } - - /** - * Set the location based on a latitude, longitude, and some - * xy points. The coordinate mode and the polygon setting are - * the same as in the constructor used. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public void setLocation(double latPoint, double lonPoint, int units, - float[] xPoints, float[] yPoints) { - if (units == OMGraphic.DECIMAL_DEGREES) { - lat = ProjMath.degToRad(latPoint); - lon = ProjMath.degToRad(lonPoint); - } else { - lat = latPoint; - lon = lonPoint; - } - xs = xPoints; - ys = yPoints; - setNeedToRegenerate(true); - } - - /** - * Type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - public void setCoordMode(int coordMode) { - this.coordMode = coordMode; - } - - /** - * Type of offset. - * - * @see #COORDMODE_ORIGIN - * @see #COORDMODE_PREVIOUS - */ - public int getCoordMode() { - return coordMode; - } - - /** - * Set the latitude of the offset point, in decimal degrees. - */ - public void setLat(double lat) { - this.lat = ProjMath.degToRad(lat); - setNeedToRegenerate(true); - } - - /** - * Get the latitude of the offset point, in decimal degrees. - */ - public double getLat() { - return ProjMath.radToDeg(lat); - } - - /** - * Set the longitude of the offset point, in decimal degrees. - */ - public void setLon(double lon) { - this.lon = ProjMath.degToRad(lon); - setNeedToRegenerate(true); - } - - /** - * Get the longitude of the offset point, in decimal degrees. - */ - public double getLon() { - return ProjMath.radToDeg(lon); - } - - public boolean generate(Projection proj) { - - if (proj == null) { - Debug.message("omgraphic", - "OMPoly: null projection in generate!"); - setNeedToRegenerate(true); - return false; - } - - if (xs == null) { - Debug.message("omgraphic", - "OMPoly offset rendertype null coordinates"); - return false; - } - - int npts = xs.length; - float[] _x = new float[npts]; - float[] _y = new float[npts]; - - // forward project the radian point - Point origin = new Point(); - if (proj instanceof GeoProj) { - ((GeoProj)proj).forward(lat, lon, origin, true);//radians - } else { - proj.forward(Math.toDegrees(lat), Math.toDegrees(lon), origin); - } - - if (coordMode == COORDMODE_ORIGIN) { - for (int i = 0; i < npts; i++) { - _x[i] = xs[i] + origin.x; - _y[i] = ys[i] + origin.y; - } - } else { // CModePrevious offset deltas - _x[0] = xs[0] + origin.x; - _y[0] = ys[0] + origin.y; - - for (int i = 1; i < npts; i++) { - _x[i] = xs[i] + _x[i - 1]; - _y[i] = ys[i] + _y[i - 1]; - } - } - // Need to keep these around for the LabeledOMPoly - xpoints = new float[1][0]; - xpoints[0] = _x; - ypoints = new float[1][0]; - ypoints[0] = _y; - - setShape(doShapes? this.createShape() : null); - - setNeedToRegenerate(false); - return true; - } - - public int getRenderType() { - return RENDERTYPE_OFFSET; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolylineGeometry.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolylineGeometry.java deleted file mode 100644 index 043502086..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/PolylineGeometry.java +++ /dev/null @@ -1,228 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/geom/PolylineGeometry.java,v $ -// $RCSfile: PolylineGeometry.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.geom; - -import java.io.Serializable; - -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.proj.DrawUtil; - -/** - * Graphic object that represents a polygon. - *

- * All of the OMGraphics are moving to having their internal - * representation as java.awt.Shape objects. Unfortunately, this has - * the side effect of slowing OMPolys down, because the way that the - * projection classes handle transformations cause more objects to be - * allocated and more loops to be run through. So, by default, the - * OMPoly does NOT use Shape objects internally, to keep layers that - * throw down many, many polys running quickly. If you want to do some - * spatial analysis on an OMPoly, call setDoShapes(true) on it, then - * generate(Projection), and then call getShapes() to get the - * java.awt.Shape objects for the poly. You can then run the different - * Shape spatial analysis methods on the Shape objects. - * - *

NOTES:

- *
    - *
  • See the - * RESTRICTIONS on Lat/Lon polygons/polylines. Not following the - * guidelines listed may result in ambiguous/undefined shapes! Similar - * assumptions apply to the other vector graphics that we define: - * circles, ellipses, rects, lines. - *
  • LatLon OMPolys store latlon coordinates internally in radian - * format for efficiency in projecting. Subclasses should follow this - * model. - *
  • Holes in the poly are not supported. If you want holes, use - * multiple PolyGeometrys in a OMGeometryList. - *

    - *

- *

TODO:

- *
    - *
  • Polar filled-polygon correction for Cylindrical projections - * (like OMCircle). - *
- */ -public abstract class PolylineGeometry extends PolygonGeometry implements - Serializable, OMGeometry { - - /** - * Return the shortest distance from the graphic to an XY-point. - * This works if generate() has been successful. - * - * @param x horizontal pixel location. - * @param y vertical pixel location. - * @return the distance of the object to the location given. - */ - public float distance(double x, double y) { - if (getShape() != null) { - return super.distance(x, y); - } - - // If shape is null, then we have to do things the old way. - - float temp, distance = Float.POSITIVE_INFINITY; - - if (getNeedToRegenerate()) { - return distance; - } - - // safety: grab local reference of projected points - float[][] xpts = xpoints; - float[][] ypts = ypoints; - int len = xpts.length; - - for (int i = 0; i < len; i++) { - float[] _x = xpts[i]; - float[] _y = ypts[i]; - - // get the closest point - temp = DrawUtil.closestPolyDistance(_x, _y, x, y, false); - if (temp < distance) - distance = temp; - } - - return distance; - } - - public static class LL extends PolygonGeometry.LL { - - /** - * Create an LL PolygonGeometry from a list of float lat/lon - * pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for - * more efficient handling internally if it's not already in - * radians! For even better performance, you should send us an - * array already in radians format! - *
  • If you want the poly to be connected (as a polygon), - * you need to ensure that the first and last coordinate pairs - * are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, - * lat, lon, etc. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public LL(double[] llPoints, int units, int lType) { - this(llPoints, units, lType, -1); - } - - /** - * Create an OMPoly from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for - * more efficient handling internally if it's not already in - * radians! For even better performance, you should send us an - * array already in radians format! - *
  • If you want the poly to be connected (as a polygon), - * you need to ensure that the first and last coordinate pairs - * are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, - * lat, lon, etc. - * @param units radians or decimal degrees. Use - * OMGraphic.RADIANS or OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, - * and if < 1, this value is generated internally) - */ - public LL(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - setIsPolygon(false); - } - } - - public static class XY extends PolygonGeometry.XY { - - /** - * Create an OMPoly from a list of xy pairs. If you want the - * poly to be connected, you need to ensure that the first and - * last coordinate pairs are the same. - * - * @param xypoints array of x/y points, arranged x, y, x, y, - * etc. - */ - public XY(float[] xypoints) { - super(xypoints); - setIsPolygon(false); - } - - /** - * Create an x/y OMPoly. If you want the poly to be connected, - * you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - */ - public XY(float[] xPoints, float[] yPoints) { - super(xPoints, yPoints); - setIsPolygon(false); - } - } - - public static class Offset extends PolygonGeometry.Offset { - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want - * the poly to be connected, you need to ensure that the first - * and last coordinate pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xypoints float[] of x,y pairs - * @param cMode offset coordinate mode - */ - public Offset(double latPoint, double lonPoint, float[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - setIsPolygon(false); - } - - /** - * Create an x/y OMPoly at an offset from lat/lon. If you want - * the poly to be connected, you need to ensure that the first - * and last coordinate pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xPoints float[] of x coordinates - * @param yPoints float[] of y coordinates - * @param cMode offset coordinate mode - */ - public Offset(double latPoint, double lonPoint, float[] xPoints, - float[] yPoints, int cMode) { - - super(latPoint, lonPoint, xPoints, yPoints, cMode); - setIsPolygon(false); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/package.html deleted file mode 100644 index 56eb5e0ef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/geom/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains the basic foundation classes for OMGraphics, -classes that describe the geometry of OMGraphics without any -reference to rendering attributes. The OMGraphic classes have -additional information about how the geometry should be rendered. - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColorGeneratorLoader.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColorGeneratorLoader.java deleted file mode 100644 index cc8879e2e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColorGeneratorLoader.java +++ /dev/null @@ -1,91 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java,v -// $ -// $RCSfile: ColorGeneratorLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2005/12/22 18:46:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -public class ColorGeneratorLoader extends GeneratorLoader { - - public final static String ColorsClassProperty = "colorsClass"; - public final static String COLORS_PROPERTY = "COLORS"; - - public final static String DEFAULT_COLORS_CLASS = "com.bbn.openmap.omGraphics.grid.GreyscaleSlopeColors"; - - protected ElevationColors colors; - - public ColorGeneratorLoader() { - setPrettyName(i18n.get(ColorGeneratorLoader.class, "name", "Color Shading")); //default - } - - public void setColors(ElevationColors cols) { - ElevationColors oldColors = colors; - colors = cols; - if (oldColors != colors) { - firePropertyChange(COLORS_PROPERTY, oldColors, colors); - } - } - - public ElevationColors getColors() { - if (colors == null) { - try { - colors = (ElevationColors) Class.forName(DEFAULT_COLORS_CLASS) - .newInstance(); - } catch (InstantiationException ie) { - } catch (IllegalAccessException iae) { - } catch (ClassNotFoundException cnfe) { - } - } - return colors; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String colorsClassProperty = props.getProperty(prefix - + ColorsClassProperty); - if (colorsClassProperty != null) { - try { - setColors((ElevationColors) ComponentFactory.create(colorsClassProperty)); - } catch (ClassCastException cce) { - Debug.output("SlopeGeneratorLoader created a " - + colorsClassProperty - + ", but it's not a ElevationColors object"); - } - } - } - - public void addPropertyChangeListener(PropertyChangeListener pcl) { - super.addPropertyChangeListener(COLORS_PROPERTY, pcl); - } - - public void removePropertyChangeListener(PropertyChangeListener pcl) { - super.removePropertyChangeListener(COLORS_PROPERTY, pcl); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColoredShadingColors.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColoredShadingColors.java deleted file mode 100644 index 29d619792..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ColoredShadingColors.java +++ /dev/null @@ -1,192 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/ColoredShadingColors.java,v $ -// $RCSfile: ColoredShadingColors.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Color; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.Length; - -/** - * A holder for handling colors for elevations. This ElevationColors object also - * takes into account slope when providing pixel int values. - */ -public class ColoredShadingColors implements ElevationColors { - - protected ColorHelper[] colors; - public Color waterColor = OMColor.clear; - - public final int[] DEFAULT_COLOR_CUTOFFS = { 0, 50, 100, 200, 400, 800, - 1200, 1600, 2000, 3000, 4000, 6000, 8000, 10000, 12000, 33000 }; - - public final int[] DEFAULT_COLORS = { 0x00bfeffa, 0xff145f46, 0xff286650, - 0xff3c8064, 0xff6e9982, 0xff8caf96, 0xffbec896, 0xffe1c89b, - 0xffb39e4d, 0xff9f8e33, 0xffa39833, 0xffb2a54d, 0xffb9a570, - 0xffd7cd8c, 0xffd9d9d9, 0xfff3f3e6 }; - - /** - * Slope color adjustment, gets subtracted from the color for slopes of zerp - * or less. Default is 0x0a0a0a. - */ - protected int slopeColorAdjustment = 0x000a0a0a; - - /* - * Default constructor, used default elevation cutoffs and color values. - */ - public ColoredShadingColors() { - getColors(); - } - - /** - * Constructor to provide unique elevation cutoffs and colors. - */ - public ColoredShadingColors(ColorHelper[] colors) { - this.colors = colors; - } - - /** - * Set the color factor to subtract from the colors for level or negative - * slopes. Should be the same for each byte, or the colors will change - * drastically. - */ - public void setSlopeColorAdjustment(int adj) { - slopeColorAdjustment = adj; - } - - public int getSlopeColorAdjustment() { - return slopeColorAdjustment; - } - - /** - * Get an array of colors with elevation values. - */ - public ColorHelper[] getColors() { - if (colors == null) { - colors = createDefaultColors(); - } - return colors; - } - - /** - * Set the list of ColorHelpers. The elevations of the ColorHelpers should - * be in order, from lowest to highest. - */ - public void setColors(ColorHelper[] clrs) { - colors = clrs; - } - - public int[] getColortable() { - ColorHelper[] helpers = getColors(); - int[] cs = new int[helpers.length]; - for (int i = 0; i < helpers.length; i++) { - cs[i] = helpers[i].value; - } - return cs; - } - - /** - * Set the color to use for water/invalid data, zero elevation. - */ - public void setWaterColor(Color water) { - waterColor = water; - } - - /** - * Get the color to use for water/invalid data, zero elevation. - */ - public Color getWaterColor() { - return waterColor; - } - - /** - * Get the Color for the given elevation, with the provided units. The slope - * of the land, from the northwest to the southeast, is provided. - */ - public Color getColor(int elevation, Length units, double slope) { - return new Color(getARGB(elevation, units, slope)); - } - - /** - * Get the int argb value for a given elevation, with the provided units. - * The slope of the land, from the northwest to the southeast, is provided - * in case that should matter. It's not used in this version of the - * algorithm. - */ - public int getARGB(int elevation, Length units, double slope) { - - if (elevation < 0 || colors == null) { - return waterColor.getRGB(); - } - - float elev = units.toRadians(elevation); - float numCutoffs = colors.length; - int i = 0; - - while (i < numCutoffs && colors[i] != null - && colors[i].height < elev) { - i++; - } - - int value = colors[i].value; - - if (slope < 0) { - value -= 2 * slopeColorAdjustment; - } else if (slope == 0) { - value -= slopeColorAdjustment; - } - - return value; - } - - public ColorHelper[] createDefaultColors() { - int number = DEFAULT_COLOR_CUTOFFS.length; - ColorHelper[] helpers = new ColorHelper[number]; - - for (int i = 0; i < number; i++) { - helpers[i] = new ColorHelper(Length.FEET.toRadians((float) DEFAULT_COLOR_CUTOFFS[i]), DEFAULT_COLORS[i]); - } - return helpers; - } - - /** - * A helper class that associates an int color value with an elevation. - * Elevation has to be in radians. - */ - public static class ColorHelper { - /** height value in radians. */ - public double height = 0; // in radians - /** Integer ARGB color value. */ - public int value = 0; - - /** - * Create a ColorHelper. - * - * @param radianHeight minimum elevation for color use, in radians. - * @param val integer ARGB color value - */ - public ColorHelper(double radianHeight, int val) { - height = radianHeight; - value = val; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGenerator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGenerator.java deleted file mode 100644 index 0be633bf2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGenerator.java +++ /dev/null @@ -1,147 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/ElevationBandGenerator.java,v $ -// $RCSfile: ElevationBandGenerator.java,v $ -// $Revision: 1.2 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.proj.Length; - -/** - * The ElevationBandGenerator is an OMGridGenerator that creates an OMRaster out - * of OMGrid data. The OMgrid data is assumed to be meter elevation points, and - * the colors given to the pixels in the raster reflect the values as dictated - * by the Length units. The colortable given to the generator determines the - * colors used, and the band height sets the elevation range for each color. - */ -public class ElevationBandGenerator extends SimpleColorGenerator { - - public static final int DEFAULT_BANDHEIGHT = 100; - public static final int DEFAULT_ADJUST = 3; - - /** - * The colors to use. The colors[0] is assumed to be the 0 elevation color, - * and by default, is a light blue color. - */ - protected int[] colors; - /** - * A number between 1-5 to adjust the contrast a little between the colors. - */ - protected int adjust = DEFAULT_ADJUST; - /** - * The elevation difference between the edges of a color - or how much the - * elevation must change before a pixel gets the next color. - */ - protected int bandHeight = DEFAULT_BANDHEIGHT; // meters - - protected Length dataUnits = Length.METER; - - protected Length displayUnits = Length.METER; - - public ElevationBandGenerator() { - setColortable(createGreyscaleColors(216, 255)); - } - - /** - * Takes the value assigned to a pixel, as determined by it's location in - * the grid, and gives it a color to be painted by. In this case, the pixel - * is colored according to the elevation value. - * - * @param source a grid point value assigned to the raster pixel. - * @return the ARGB to color the pixel. - */ - public int calibratePointValue(int source) { - if (source < -500) { - return 0; // clear, nothing is that low... - } - - if (source == 0) { - return colors[0]; // water blue, assumed. - } - - if (displayUnits != dataUnits) { - source = (int) displayUnits.fromRadians(dataUnits.toRadians(source)); - } - - // I'm not really sure how all this works out - I wrote it a - // while ago, and it works, so I'm leaving well enough alone. - // Some notes from before: - - // Start at the darkest color, and then go up through the - // colormap for each band height, the start back at the - // darkest when you get to the last color. To make this - // more useful, I limit the number of colors (10) used - if - // there isn;t enough contrast between the colors, you can't - // see the bands. The contrast adjustment in 24-bit color - // mode(216 colors) lets you add a few colors. - int assignment = (int) (((source / bandHeight) - % (10 - 2 * (3 - adjust)) * (colors.length / (10 - 2 * (3 - adjust)))) + 6); - - return colors[assignment]; - } - - public void setColortable(int[] colors) { - this.colors = colors; - } - - public int[] getColortable() { - return colors; - } - - public void setColors(ElevationColors ec) { - setColortable(ec.getColortable()); - } - - public void setBandHeight(int height) { - if (height <= 0) - height = DEFAULT_BANDHEIGHT; - bandHeight = height; - } - - public int getBandHeight() { - return bandHeight; - } - - public void setAdjust(int value) { - if (value <= 0 || value > 5) - value = DEFAULT_ADJUST; - adjust = value; - } - - public int getAdjust() { - return adjust; - } - - public Length getDataUnits() { - return dataUnits; - } - - public void setDataUnits(Length units) { - this.dataUnits = units; - } - - public Length getDisplayUnits() { - return displayUnits; - } - - public void setDisplayUnits(Length displayUnits) { - this.displayUnits = displayUnits; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGeneratorLoader.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGeneratorLoader.java deleted file mode 100644 index f5d2a3d3c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationBandGeneratorLoader.java +++ /dev/null @@ -1,161 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java,v -// $ -// $RCSfile: ElevationBandGeneratorLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeListener; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.PaletteHelper; - -public class ElevationBandGeneratorLoader extends ColorGeneratorLoader { - - public final static String DISPLAY_UNITS_PROPERTY = "DISPLAY_UNITS"; - public final static String BANDHEIGHT_PROPERTY = "BANDHEIGHT"; - - protected Length displayUnits = Length.METER; - protected int bandHeight = ElevationBandGenerator.DEFAULT_BANDHEIGHT; - - public void setDisplayUnits(Length units) { - Length oldValue = displayUnits; - displayUnits = units; - if (oldValue != displayUnits) { - firePropertyChange(DISPLAY_UNITS_PROPERTY, oldValue, displayUnits); - } - } - - public Length getDisplayUnits() { - return displayUnits; - } - - public int getBandHeight() { - return bandHeight; - } - - public void setBandHeight(int bh) { - int oldValue = bandHeight; - bandHeight = bh; - if (oldValue != bandHeight) { - firePropertyChange(BANDHEIGHT_PROPERTY, - new Integer(oldValue), - new Integer(bandHeight)); - } - } - - private final static Integer sliderLabelKey = new Integer(250); - - protected String getUnitAdjustmentTitle() { - return "Band Height Units"; - } - - protected String getValueAdjustmentTitle() { - return "Band Height Value"; - } - - public Component getGUI() { - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.gridwidth = GridBagConstraints.REMAINDER; - c.weightx = 1f; - c.fill = GridBagConstraints.HORIZONTAL; - panel.setLayout(gridbag); - - JPanel unitPanel = PaletteHelper.createPaletteJPanel(getUnitAdjustmentTitle()); - Object[] units = new Object[] { Length.METER, Length.FEET }; - JComboBox unitBox = new JComboBox(units); - unitBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - JComboBox unitBox = (JComboBox) ae.getSource(); - setDisplayUnits((Length) unitBox.getSelectedItem()); - } - }); - unitPanel.add(unitBox); - gridbag.setConstraints(unitPanel, c); - panel.add(unitPanel); - - // The DTED Bandheight Adjuster - JPanel contrastPanel = PaletteHelper.createPaletteJPanel(getValueAdjustmentTitle()); - JSlider contrastSlide = new JSlider(JSlider.HORIZONTAL, 1/* min */, 500/* max */, getBandHeight()/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(1), new JLabel("1")); - dict.put(new Integer(500), new JLabel("500")); - dict.put(sliderLabelKey, new JLabel("(" + getBandHeight() + ")")); - contrastSlide.setLabelTable(dict); - contrastSlide.setPaintLabels(true); - contrastSlide.setMajorTickSpacing(50); - contrastSlide.setPaintTicks(true); - contrastSlide.setSnapToTicks(false); - contrastSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (!slider.getValueIsAdjusting()) { - int value = slider.getValue(); - JLabel label = (JLabel) slider.getLabelTable() - .get(sliderLabelKey); - label.setText("(" + value + ")"); - setBandHeight(value); - } - } - }); - contrastPanel.add(contrastSlide); - gridbag.setConstraints(contrastPanel, c); - panel.add(contrastPanel); - - return panel; - } - - public OMGridGenerator getGenerator() { - ElevationBandGenerator gen = new ElevationBandGenerator(); - gen.setColors(getColors()); - gen.setDisplayUnits(displayUnits); - gen.setBandHeight(getBandHeight()); - return gen; - } - - public void addPropertyChangeListener(PropertyChangeListener pcl) { - super.addPropertyChangeListener(DISPLAY_UNITS_PROPERTY, pcl); - super.addPropertyChangeListener(BANDHEIGHT_PROPERTY, pcl); - super.addPropertyChangeListener(COLORS_PROPERTY, pcl); - } - - public void removePropertyChangeListener(PropertyChangeListener pcl) { - super.removePropertyChangeListener(DISPLAY_UNITS_PROPERTY, pcl); - super.removePropertyChangeListener(BANDHEIGHT_PROPERTY, pcl); - super.removePropertyChangeListener(COLORS_PROPERTY, pcl); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationColors.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationColors.java deleted file mode 100644 index af0e5e542..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/ElevationColors.java +++ /dev/null @@ -1,54 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/ElevationColors.java,v $ -// $RCSfile: ElevationColors.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/22 18:46:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Color; - -import com.bbn.openmap.proj.Length; - -/** - * An interface that the SlopeGenerator uses to get colors for - * different elevations and slopes. - */ -public interface ElevationColors { - - /** - * Get the Color for the given elevation, with the provided units. - * The slope of the land, from the northwest to the southeast, is - * provided. - */ - public Color getColor(int elevation, Length units, double slope); - - /** - * Get the int argb value for a given elevation, with the provided - * units. The slope of the land, from the northwest to the - * southeast, is provided in case that should matter. - */ - public int getARGB(int elevation, Length units, double slope); - - /** - * Get a colortable as an array of ints. - */ - public int[] getColortable(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GeneratorLoader.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GeneratorLoader.java deleted file mode 100644 index fb5197f57..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GeneratorLoader.java +++ /dev/null @@ -1,82 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/GeneratorLoader.java,v $ -// $RCSfile: GeneratorLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Component; -import java.beans.PropertyChangeListener; -import java.util.Properties; - -import javax.swing.JPanel; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.PropUtils; - -/** - * A GeneratorLoader is a component that can provide an - * OMGridGenerator. It can provide a GUI to control the settings on - * the next generator it provides. This is a basic GeneratorLoader - * that doesn't do anything. - */ -public class GeneratorLoader extends OMComponent { - - protected String prettyName = ""; - - public String getPrettyName() { - return prettyName; - } - - public void setPrettyName(String name) { - prettyName = name; - } - - public Component getGUI() { - return new JPanel(); - } - - public OMGridGenerator getGenerator() { - return new SinkGenerator(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - setPrettyName(props.getProperty(prefix - + com.bbn.openmap.Layer.PrettyNameProperty, prettyName)); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + com.bbn.openmap.Layer.PrettyNameProperty, - PropUtils.unnull(getPrettyName())); - - return props; - } - - /** - * You should override this so the listener receives any - * particular events that the GeneratorLoader sends out. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl) {} - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GreyscaleSlopeColors.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GreyscaleSlopeColors.java deleted file mode 100644 index be36c4cdf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GreyscaleSlopeColors.java +++ /dev/null @@ -1,142 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/GreyscaleSlopeColors.java,v $ -// $RCSfile: GreyscaleSlopeColors.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Color; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.proj.Length; - -/** - * Creates the colors used for displaying the DTED images. The default - * mode is to use greyscale colors. - */ -public class GreyscaleSlopeColors implements ElevationColors { - - public final static int NUM_COLORS = 256; - public final static int NUM_ELEVATION_COLORS = 25; - public final static int DEFAULT_OPAQUENESS = 255; - public Color waterColor = new OMColor(0x00bfefff); - - /** the colors in use right now, ARGB values. */ - public int[] colors; - /** adjustment is set up for values between 1-5. */ - public int adjustment = 3; - - /** Default setting is 216 colors, and greyscale. */ - public GreyscaleSlopeColors() { - getColors(); - } - - /** - * Get a List of colors. - */ - public int[] getColors() { - if (colors == null) { - colors = createGreyscaleColors(NUM_ELEVATION_COLORS, - DEFAULT_OPAQUENESS); - } - return colors; - } - - /** - * Set the List of colors. - */ - public void setColors(int[] clrs) { - colors = clrs; - } - - public int[] getColortable() { - return getColors(); - } - - /** - * Set the color to use for water/invalid data, zero elevation. - */ - public void setWaterColor(Color water) { - waterColor = water; - } - - /** - * Get the color to use for water/invalid data, zero elevation. - */ - public Color getWaterColor() { - return waterColor; - } - - /** - * Get the Color for the given elevation, with the provided units. - * The slope of the land, from the northwest to the southeast, is - * provided. - */ - public Color getColor(int elevation, Length units, double slope) { - return new Color(getARGB(elevation, units, slope)); - } - - /** - * Get the int argb value for a given elevation, with the provided - * units. The slope of the land, from the northwest to the - * southeast, is provided in case that should matter. - */ - public int getARGB(int elevation, Length units, double slope) { - // Debug.output("slope = " + slope + ", elevation = " + - // elevation); - - float value = (float) (((colors.length - 1) / 2) + slope); - - // not water, but close in the colormap - max dark - if (slope != 0 && value < 1) - value = 1; - if (elevation == 0) - value = 0; // water?!? - - if (value > (colors.length - 1)) { - value = colors.length - 1; // max bright - } - - return colors[(int) value]; - } - - public int numColors() { - return colors.length; - } - - public int[] createGreyscaleColors(int num_colors, int opaqueness) { - int[] tempColors = new int[num_colors]; - if (num_colors == 0) { - num_colors = NUM_ELEVATION_COLORS; - } - - int grey_interval = 256 / num_colors; - - for (int i = 0; i < num_colors; i++) { - if (i == 0) { - tempColors[i] = waterColor.getRGB(); - } else { - int color = (i * grey_interval) + (grey_interval / 2); - tempColors[i] = new Color(color, color, color, opaqueness).getRGB(); - } - } - return tempColors; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GridData.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GridData.java deleted file mode 100644 index 4f6c21099..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/GridData.java +++ /dev/null @@ -1,85 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/GridData.java,v $ -// $RCSfile: GridData.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -/** - * The GridData interface is a wrapper class for data stored and used - * in an OMGrid object. It holds a two-dimensional array of data. They - * type of array is determined my the type of GridData used. - */ -public interface GridData { - - public Object get(int x, int y); - - public int getNumColumns(); - - public int getNumRows(); - - public void setMajor(boolean value); - - public boolean getMajor(); - - public GridData deepCopy(); - - public interface Boolean extends GridData { - public boolean getBooleanValue(int x, int y); - - public boolean[][] getData(); - } - - public interface Byte extends GridData { - public byte getByteValue(int x, int y); - - public byte[][] getData(); - } - - public interface Char extends GridData { - public char getCharValue(int x, int y); - - public char[][] getData(); - } - - public interface Short extends GridData { - public short getShortValue(int x, int y); - - public short[][] getData(); - } - - public interface Int extends GridData { - public int getIntValue(int x, int y); - - public int[][] getData(); - } - - public interface Float extends GridData { - public float getFloatValue(int x, int y); - - public float[][] getData(); - } - - public interface Double extends GridData { - public double getDoubleValue(int x, int y); - - public double[][] getData(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridData.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridData.java deleted file mode 100644 index b2c821321..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridData.java +++ /dev/null @@ -1,412 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/OMGridData.java,v -// $ -// $RCSfile: OMGridData.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.util.DeepCopyUtil; - -public abstract class OMGridData - implements GridData { - - /** - * Keep track of which dimension different parts of the double array - * represent. COLUMN_MAJOR is the default, meaning that the first dimension - * of the array represents the vertical location in the array, and the - * second is the horizontal location in the array. - */ - protected boolean major = OMGrid.COLUMN_MAJOR; - - public void setMajor(boolean value) { - major = value; - } - - public boolean getMajor() { - return major; - } - - /** - * Boolean is a GridData object that contains booleans. - */ - public static class Boolean - extends OMGridData - implements GridData.Boolean { - - protected boolean[][] data; - - public Boolean(boolean[][] d) { - setData(d); - } - - public void setData(boolean[][] d) { - data = d; - } - - public boolean[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new java.lang.Boolean(getBooleanValue(x, y)); - } - - public boolean getBooleanValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Boolean(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Byte is a GridData object that contains bytes. - */ - public static class Byte - extends OMGridData - implements GridData.Byte { - - protected byte[][] data; - - public Byte(byte[][] d) { - setData(d); - } - - public void setData(byte[][] d) { - data = d; - } - - public byte[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new java.lang.Byte(getByteValue(x, y)); - } - - public byte getByteValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Byte(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Char is a GridData object that contains chars. - */ - public static class Char - extends OMGridData - implements GridData.Char { - - protected char[][] data; - - public Char(char[][] d) { - setData(d); - } - - public void setData(char[][] d) { - data = d; - } - - public char[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new Character(getCharValue(x, y)); - } - - public char getCharValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Char(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Float is a GridData object that contains floats. - */ - public static class Float - extends OMGridData - implements GridData.Float { - - protected float[][] data; - - public Float(float[][] d) { - setData(d); - } - - public void setData(float[][] d) { - data = d; - } - - public float[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new java.lang.Float(getFloatValue(x, y)); - } - - public float getFloatValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Float(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Int is a GridData object that contains ints. - */ - public static class Int - extends OMGridData - implements GridData.Int { - - protected int[][] data; - - public Int(int[][] d) { - setData(d); - } - - public void setData(int[][] d) { - data = d; - } - - public int[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new Integer(getIntValue(x, y)); - } - - public int getIntValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Int(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Short is a GridData object that contains shorts. - */ - public static class Short - extends OMGridData - implements GridData.Short { - - protected short[][] data; - - public Short(short[][] d) { - setData(d); - } - - public void setData(short[][] d) { - data = d; - } - - public short[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new java.lang.Short(getShortValue(x, y)); - } - - public short getShortValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Short(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } - - /** - * Double is a GridData object that contains doubles. - */ - public static class Double - extends OMGridData - implements GridData.Double { - - protected double[][] data; - - public Double(double[][] d) { - setData(d); - } - - public void setData(double[][] d) { - data = d; - } - - public double[][] getData() { - return data; - } - - public Object get(int x, int y) { - return new java.lang.Double(getDoubleValue(x, y)); - } - - public double getDoubleValue(int x, int y) { - return data[x][y]; - } - - public int getNumColumns() { - if (major == OMGrid.COLUMN_MAJOR) { - return data.length; - } else { - return data[0].length; - } - } - - public int getNumRows() { - if (major == OMGrid.COLUMN_MAJOR) { - return data[0].length; - } else { - return data.length; - } - } - - public GridData deepCopy() { - GridData copy = new OMGridData.Double(DeepCopyUtil.deepCopy(data)); - copy.setMajor(major); - return copy; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridGenerator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridGenerator.java deleted file mode 100644 index 08a7eefe6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridGenerator.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/OMGridGenerator.java,v -// $ -// $RCSfile: OMGridGenerator.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.proj.Projection; - -public interface OMGridGenerator { - - public OMGraphic generate(OMGrid grid, Projection proj); - - public boolean needGenerateToRender(); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridObjects.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridObjects.java deleted file mode 100644 index 2fda22141..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/OMGridObjects.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/OMGridObjects.java,v -// $ -// $RCSfile: OMGridObjects.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; - -public interface OMGridObjects { - - public Object find(int id); - - public OMGraphic generate(int id, Projection proj); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SimpleColorGenerator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SimpleColorGenerator.java deleted file mode 100644 index bd0c7604c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SimpleColorGenerator.java +++ /dev/null @@ -1,265 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SimpleColorGenerator.java,v $ -// $RCSfile: SimpleColorGenerator.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * The SimpleColorGenerator is an OMGridGenerator that creates an OMRaster out - * of OMGrid data. The OMgrid data is assumed to be color ARGB integer values. - * Each pixel is colored according to the closest grid data point value. - */ -public class SimpleColorGenerator implements OMGridGenerator { - - /** - * Going to return an OMRaster, sized to the current projection, and colored - * according to the colortable. The grid values are indexes into the - * colortable. The grid should already be generated when it gets here - - * meaning that the bounds and parameters of the grid, as they apply to the - * projection, are figured out. - * - * @param grid the grid to create a raster for. - * @param proj description of the map. - */ - public OMGraphic generate(OMGrid grid, Projection proj) { - - Debug.message("grid", - "SimpleColorGenerator: generating OMRaster from grid"); - - if (grid.height <= 0 || grid.width <= 0) { - Debug.message("grid", - "SimpleColorGenerator: grid height/width ZERO!"); - return SinkGraphic.getSharedInstance(); - } - - OMRaster raster = new OMRaster(grid.point1.x, grid.point1.y, grid.width, grid.height, new int[grid.width - * grid.height]); - - int rows = grid.getRows(); - int columns = grid.getColumns(); - RasterHelper rasterHelper = getRasterHelper(grid.getData()); - boolean major = grid.getMajor(); - - /** lat and lon_intervals are grid point/pixel.. */ - double y_interval = (double) rows / (double) grid.height; - double x_interval = (double) columns / (double) grid.width; - - Debug.message("grid", "SimpleColorGenerator: y_point_interval = " - + y_interval + ", x_point_interval = " + x_interval); - - /** - * Right now, if the rendertype of the grid is RENDERTYPE_LATLON, we - * limit sensible rendering to the CADRG/LLXY projections. No warping - * done. - */ - - int post_x, post_y, value; - /** Do this pixel by pixel. */ - for (int x = 0; x < grid.width; x++) { - for (int y = 0; y < grid.height; y++) { - - post_x = (int) Math.round(x_interval * (double) x); - if (grid.getRenderType() == OMGraphic.RENDERTYPE_LATLON) { - post_y = (int) Math.round(y_interval - * (grid.height - 1 - (double) y)); - } else { - post_y = (int) Math.round(y_interval * (double) y); - } - - if (major == OMGrid.COLUMN_MAJOR) { - if (post_x >= columns) - post_x = columns - 1; - if (post_y >= rows) - post_y = rows - 1; - - value = calibratePointValue(rasterHelper.get(post_x, post_y)); - } else { - if (post_y >= columns) - post_y = columns - 1; - if (post_x >= rows) - post_x = rows - 1; - - value = calibratePointValue(rasterHelper.get(post_y, post_x)); - } - - raster.setPixel(x, y, value); - } - } - raster.generate(proj); - - return raster; - } - - /** - * Takes the value assigned to a pixel, as determined by it's location in - * the grid, and gives a color to paint the pixel. In this case, the grid - * point value IS the color value. - * - * @param source a grid point value assigned to the raster pixel. - * @return the ARGB to color the pixel. - */ - public int calibratePointValue(int source) { - return source; - } - - /** - * We at least need one generate for XY and OFFSET grids. We will need a - * generate every time the projection changes for LATLON rendertype grids. - * So return true for everything. - */ - public boolean needGenerateToRender() { - return true; - } - - /** - * This method creates a set of greyscale colors. It isn't used in this - * class (SimpleColorGenerator), but it probably will be used in extended - * classes. - * - * @param num_colors the number of greys needed. - * @param opaqueness how clear the color should be (0-255, where 0 is - * clear). - * @return an array of color ARGB integers. - */ - public int[] createGreyscaleColors(int num_colors, int opaqueness) { - int[] tempColors = new int[num_colors]; - if (num_colors == 0) { - num_colors = 216; - } - - int grey_interval = 256 / num_colors; - - for (int i = 0; i < num_colors; i++) { - - if (i == 0) { - tempColors[i] = ((opaqueness & 0xFF) << 24) - | ((191 & 0xFF) << 16) | ((239 & 0xFF) << 8) - | ((255 & 0xFF)); - } - - else { - int color = (i * grey_interval) + (grey_interval / 2); - tempColors[i] = ((opaqueness & 0xFF) << 24) - | ((color & 0xFF) << 16) | ((color & 0xFF) << 8) - | ((color & 0xFF)); - } - } - return tempColors; - } - - protected RasterHelper getRasterHelper(GridData gd) { - if (gd instanceof GridData.Short) { - return new ShortRasterHelper(((GridData.Short) gd).getData()); - } else if (gd instanceof GridData.Int) { - return new IntRasterHelper(((GridData.Int) gd).getData()); - } else if (gd instanceof GridData.Float) { - return new FloatRasterHelper(((GridData.Float) gd).getData()); - } else if (gd instanceof GridData.Byte) { - return new ByteRasterHelper(((GridData.Byte) gd).getData()); - } else if (gd instanceof GridData.Char) { - return new CharRasterHelper(((GridData.Char) gd).getData()); - } - return new DoubleRasterHelper(((GridData.Double) gd).getData()); - } - - protected interface RasterHelper { - public int get(int x, int y); - } - - protected class IntRasterHelper implements RasterHelper { - int[][] data; - - public IntRasterHelper(int[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return data[x][y]; - } - } - - protected class ShortRasterHelper implements RasterHelper { - short[][] data; - - public ShortRasterHelper(short[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return data[x][y]; - } - } - - protected class ByteRasterHelper implements RasterHelper { - byte[][] data; - - public ByteRasterHelper(byte[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return data[x][y]; - } - } - - protected class FloatRasterHelper implements RasterHelper { - float[][] data; - - public FloatRasterHelper(float[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return (int) data[x][y]; - } - } - - protected class DoubleRasterHelper implements RasterHelper { - double[][] data; - - public DoubleRasterHelper(double[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return (int) data[x][y]; - } - } - - protected class CharRasterHelper implements RasterHelper { - char[][] data; - - public CharRasterHelper(char[][] intData) { - data = intData; - } - - public int get(int x, int y) { - return data[x][y]; - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SinkGenerator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SinkGenerator.java deleted file mode 100644 index 227859e74..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SinkGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SinkGenerator.java,v -// $ -// $RCSfile: SinkGenerator.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.Projection; - -public class SinkGenerator implements OMGridGenerator { - - public OMGraphic generate(OMGrid grid, Projection proj) { - return SinkGraphic.getSharedInstance(); - } - - public boolean needGenerateToRender() { - return false; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGenerator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGenerator.java deleted file mode 100644 index 34fb37c0d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGenerator.java +++ /dev/null @@ -1,321 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SlopeGenerator.java,v $ -// $RCSfile: SlopeGenerator.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/12/22 18:46:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Point; -import java.awt.Shape; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGrid; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The SlopeGenerator is an OMGridGenerator that looks at elevation - * data and creates shading images from it. It currently works for - * short data only, since that what DTED elevation data is. Making it - * work with different data types is on the to-do list. - */ -public class SlopeGenerator implements OMGridGenerator { - - protected int contrast = 5; - protected ElevationColors colors = new ColoredShadingColors(); - - public SlopeGenerator() {} - - public SlopeGenerator(ElevationColors elevColors) { - setColors(elevColors); - } - - public void setColors(ElevationColors elevColors) { - colors = elevColors; - } - - public ElevationColors getColors() { - return colors; - } - - public void setContrast(int val) { - if (val > 10 || val < 1) { - val = 5; - } - contrast = val; - } - - public int getContrast() { - return contrast; - } - - /** - * Called from within generate to create an OMRaster object for - * the OMGrid. This method exists to make it easier to extend this - * class to create an OMRaster as needed. - */ - protected OMRaster getRaster(OMGrid grid) { - return new OMRaster(grid.point1.x, grid.point1.y, grid.width, grid.height, new int[grid.width - * grid.height]); - } - - protected boolean incomplete = false; - - /** - * A method to check if the last image created was a complete one. - * If it was incomplete, then that means some pixels of the image - * were not set because they were outside of the projection. - */ - public boolean isIncompleteImage() { - return incomplete; - } - - /** - * A more defining API method to get what this SlopeGenerator can - * create. An OMGridGenerator generates an OMGraphic, this method - * lets you specifically ask for an OMRaster if that's what you - * want. If SlopeGenerator is extended so that it doesn't - * necessarily return an OMRaster from generate, this method - * checks for that and will return null if generate returns - * something other than an OMRaster. - * - * @param grid - * @param proj - * @return OMRaster that reflects slope information. - */ - public OMRaster generateRasterForProjection(OMGrid grid, Projection proj) { - OMGraphic omg = generate(grid, proj); - if (omg instanceof OMRaster) { - return (OMRaster) omg; - } else { - return null; - } - } - - /** - * Called from the OMGrid.generate() method to tell the generator - * to create something to represent the grid contents. - */ - public OMGraphic generate(OMGrid grid, Projection proj) { - - Shape gridShape = grid.getShape(); - - // Don't generate the raster if the grid is off-map... - if (gridShape == null - || !gridShape.intersects(0, - 0, - proj.getWidth(), - proj.getHeight())) { - if (Debug.debugging("grid")) { - Debug.output("SlopeGenerator: OMGrid does not overlap map, skipping generation."); - } - return SinkGraphic.getSharedInstance(); - } - - OMRaster raster = getRaster(grid); - incomplete = false; - - if (grid.height == 0 || grid.width == 0) { - Debug.message("grid", "SlopeGenerator: grid height/width ZERO!"); - return raster; - } - - GridData gd = grid.getData(); - - if (!(gd instanceof GridData.Short)) { - Debug.message("grid", - "SlopeGenerator: grid doesn't contain short data."); - return SinkGraphic.getSharedInstance(); - } - - int rows = grid.getRows(); - int columns = grid.getColumns(); - short[][] data = ((GridData.Short) gd).getData(); -// boolean major = grid.getMajor(); - - double distance = getSlopeRun(grid, getContrast()); - - // Used for projections of image coordinates. Reused in the - // loops to save memory. - LatLonPoint llp = new LatLonPoint.Double(); - Point point = new Point(); - ElevationColors colors = getColors(); - - if (colors == null) { - return SinkGraphic.getSharedInstance(); - } - - // x is the horizontal pixel being modified - for (short x = 0; x < grid.width; x++) { - // Check to make sure the pixels we're calculating are on - // the map. - int screenx = (int) grid.point1.getX() + x; - if (screenx < 0 || screenx > proj.getWidth()) { - incomplete = true; - continue; - } - - for (short y = 0; y < grid.height; y++) { - - // Check to make sure the pixels we're calculating are - // on the map. - int screeny = (int) grid.point1.getY() + y; - if (screeny < 0 || screeny > proj.getHeight()) { - incomplete = true; - continue; - } - - // OK, on the map. - point.setLocation(screenx, screeny); - llp = proj.inverse(point.x, point.y, new LatLonPoint.Double()); - - int yc = (int) Math.round((llp.getLatitude() - grid.getLatitude()) - / grid.getVerticalResolution()); - int xc = (int) Math.round((llp.getLongitude() - grid.getLongitude()) - / grid.getHorizontalResolution()); - - // If the calculated index is out of the data ranges, - // push it to the end. Don't blow it off, it will - // cause unfilled data pixel lines to appear. You - // only want to blow off pixels that are not on the - // map, or are never going to be on the map. - if (yc < 0) - yc = 0; - if (yc > rows - 1) - yc = rows - 1; - if (xc < 0) - xc = 0; - if (xc > columns - 1) - xc = columns - 1; - - int elevation = 0; - - // Otherwise, get the elevation for the data point. - try { - elevation = (int) data[xc][yc]; - } catch (ArrayIndexOutOfBoundsException aioobe) { - Debug.output("Error Accessing data array:\n\txc: " + xc - + ", yc: " + yc + " for x: " + x + ", y: " + y); - } - - // Slope shading calculations, get the upper left and - // lower right data points. - - int xnw = xc - 1; - int xse = xc + 1; - // trying to smooth out the edge of the frame - if (xc == 0 || xnw < 0) { - xnw = xc; - } - if (xc == columns - 1 || xse > columns - 1) { - xse = columns - 1; - } - - int yse = yc - 1; - int ynw = yc + 1; - // trying to smooth out the edge of the frame by - // handling the - // frame limits - if (yse < 0) { - yse = 0; - } - if (yc == rows - 1 || ynw > rows - 1) { - ynw = rows - 1; - } - - // Get the elevation points for the slope measurement - // points. - try { - short e2 = data[xse][yse]; // down & right - // elevation - short e1 = data[xnw][ynw]; // up and left - // elevation - - // colormap value darker for negative slopes, - // brighter for - // positive slopes. - // slope relative to nw sun - double slope = (e2 - e1) / distance; - - raster.setPixel(x, y, colors.getARGB(elevation, - grid.getUnits(), - slope)); - - } catch (ArrayIndexOutOfBoundsException aioobe) { - Debug.output("Error Accessing data array:\n\txse: " + xse - + ", yse: " + yse + "\n\txnw: " + xnw + ", ynw: " - + ynw + "\n\tfor x: " + x + ", y: " + y); - } - } - } - - raster.generate(proj); - if (Debug.debugging("grid")) - Debug.output("SlopeGenerator: leaving generate"); - return raster; - } - - public boolean needGenerateToRender() { - return true; - } - - /** - * Method to calculate the run part of the slope (rise over run, - * right?). The rise is calculated with the elevations of the - * points to the northwest and southeast of the point of concern, - * the run is some factor of the distance between those two posts. - * - * @param grid the OMGrid that contains the data, need to get - * units. - * @param contrastAdj contrast adjustment from 1-10, 5 being no - * adjustment. 10 is high contrast, 1 is low contrast. - */ - protected double getSlopeRun(OMGrid grid, int contrastAdj) { - double modifier = (double) .045; - - for (int h = 0; h < contrastAdj; h++) { - modifier -= .005; - } - - // Smaller modifiers result in more contrast. .025, by - // testing and judgement, looks like a good average, and the - // values have been set up to provide that with an adjustment - // of 5. 0 is very high contrast. - - double vRes = grid.getVerticalResolution(); // Degrees per data - // point - double hRes = grid.getHorizontalResolution(); - - double vResRad = Length.DECIMAL_DEGREE.toRadians(vRes); - double hResRad = Length.DECIMAL_DEGREE.toRadians(hRes); - - Length units = grid.getUnits(); - double vDist = Math.pow(2.0 * units.fromRadians(vResRad), 2); - double hDist = Math.pow(2.0 * units.fromRadians(hResRad), 2); - - return modifier * Math.sqrt(vDist + hDist); - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java deleted file mode 100644 index 68d9a3898..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java +++ /dev/null @@ -1,106 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/grid/SlopeGeneratorLoader.java,v -// $ -// $RCSfile: SlopeGeneratorLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/22 18:46:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.grid; - -import java.awt.Component; -import java.beans.PropertyChangeListener; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.util.PaletteHelper; - -public class SlopeGeneratorLoader extends ColorGeneratorLoader { - - public final static String CONTRAST_PROPERTY = "CONTRAST"; - - protected int contrast = 5; - - public SlopeGeneratorLoader() { - setPrettyName(i18n.get(SlopeGeneratorLoader.class, "name", "Greyscale Slope")); //default - } - - public void setContrast(int cont) { - int oldValue = contrast; - contrast = cont; - if (oldValue != contrast) { - firePropertyChange(CONTRAST_PROPERTY, - new Integer(oldValue), - new Integer(contrast)); - } - } - - public int getContrast() { - return contrast; - } - - public Component getGUI() { - JPanel panel = new JPanel(); - // The DTED Contrast Adjuster - JPanel contrastPanel = PaletteHelper.createPaletteJPanel("Contrast Adjustment"); - JSlider contrastSlide = new JSlider(JSlider.HORIZONTAL, 1/* min */, 10/* max */, getContrast()/* initial */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(1), new JLabel("min")); - dict.put(new Integer(10), new JLabel("max")); - contrastSlide.setLabelTable(dict); - contrastSlide.setPaintLabels(true); - contrastSlide.setMajorTickSpacing(1); - contrastSlide.setPaintTicks(true); - contrastSlide.setSnapToTicks(true); - contrastSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (!slider.getValueIsAdjusting()) { - setContrast(slider.getValue()); - } - } - }); - contrastPanel.add(contrastSlide); - panel.add(contrastPanel); - - return panel; - } - - public OMGridGenerator getGenerator() { - SlopeGenerator gen = new SlopeGenerator(); - gen.setColors(getColors()); - gen.setContrast(contrast); - return gen; - } - - public void addPropertyChangeListener(PropertyChangeListener pcl) { - super.addPropertyChangeListener(CONTRAST_PROPERTY, pcl); - super.addPropertyChangeListener(COLORS_PROPERTY, pcl); - } - - public void removePropertyChangeListener(PropertyChangeListener pcl) { - super.removePropertyChangeListener(CONTRAST_PROPERTY, pcl); - super.removePropertyChangeListener(COLORS_PROPERTY, pcl); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/package.html deleted file mode 100644 index 2733021b0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/grid/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a number of generator classes for OMGrid data. - - @see com.bbn.openmap.omGraphics.OMGrid - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMPoly.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMPoly.java deleted file mode 100644 index ef59ee9fe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMPoly.java +++ /dev/null @@ -1,90 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMPoly.java,v $ -// $RCSfile: EditableLabeledOMPoly.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.labeled; - -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; - -/** - * The EditableLabeledOMPoly encompasses an LabeledOMPoly, providing - * methods for modifying or creating it. - */ -public class EditableLabeledOMPoly extends EditableOMPoly { - - /** - * Create the EditableLabeledOMPoly, setting the state machine to - * create the poly off of the gestures. - */ - public EditableLabeledOMPoly() { - createGraphic(null); - } - - /** - * Create an EditableLabeledOMPoly with the polyType and - * renderType parameters in the GraphicAttributes object. - */ - public EditableLabeledOMPoly(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableLabeledOMPoly with a LabeledOMPoly already - * defined, ready for editing. - * - * @param omp LabeledOMPoly that should be edited. - */ - public EditableLabeledOMPoly(LabeledOMPoly omp) { - setGraphic(omp); - } - - /** - * Extendable method to create specific subclasses of OMPolys. - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - g = new LabeledOMPoly(new double[0], OMGraphic.RADIANS, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - g = new LabeledOMPoly(90f, -180f, new int[0], OMPoly.COORDMODE_ORIGIN); - break; - default: - g = new LabeledOMPoly(new int[0]); - } - ((LabeledOMPoly) g).setDoShapes(true); - return g; - } - - public java.net.URL getImageURL(String imageName) { - try { - return Class.forName("com.bbn.openmap.omGraphics.EditableOMPoly") - .getResource(imageName); - } catch (ClassNotFoundException cnfe) { - } - return null; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMSpline.java deleted file mode 100644 index c4ff7173a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/EditableLabeledOMSpline.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.bbn.openmap.omGraphics.labeled; - -import com.bbn.openmap.omGraphics.EditableOMSpline; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMSpline; - -/** - * The EditableLabeledOMSpline encompasses an LabeledOMSpline, - * providing methods for modifying or creating it. Nothing created, - * code adapted from EditableLabeledOMPoly We just need to edit the - * generating points as an OMSpline - * - * @author Eric LEPICIER - * @version 22 juil. 2002 - */ -public class EditableLabeledOMSpline extends EditableOMSpline { - - /** - * Create the EditableLabeledOMSpline, setting the state machine - * to create the poly off of the gestures. - * - * @see com.bbn.openmap.omGraphics.EditableOMPoly#EditableOMPoly() - */ - public EditableLabeledOMSpline() { - super(); - } - - /** - * Create an EditableLabeledOMSpline with the polyType and - * renderType parameters in the GraphicAttributes object. - * - * @param ga - * @see com.bbn.openmap.omGraphics.EditableOMPoly#EditableOMPoly(GraphicAttributes) - */ - public EditableLabeledOMSpline(GraphicAttributes ga) { - super(ga); - } - - /** - * Create the EditableLabeledOMSpline with a LabeledOMSpline - * already defined, ready for editing. - * - * @param omls LabeledOMSpline that should be edited. - * @see com.bbn.openmap.omGraphics.EditableOMPoly#EditableOMPoly(GraphicAttributes) - */ - public EditableLabeledOMSpline(LabeledOMSpline omls) { - super(omls); - } - - /** - * Extendable method to create specific subclasses of OMSplines. - * - * @see com.bbn.openmap.omGraphics.EditableOMPoly#createGraphic(int, - * int) - */ - public OMGraphic createGraphic(int renderType, int lineType) { - OMGraphic g = null; - switch (renderType) { - case (OMGraphic.RENDERTYPE_LATLON): - g = new LabeledOMSpline(new double[0], OMGraphic.RADIANS, lineType); - break; - case (OMGraphic.RENDERTYPE_OFFSET): - g = new LabeledOMSpline(90f, -180f, new int[0], OMSpline.COORDMODE_ORIGIN); - break; - default: - g = new LabeledOMSpline(new int[0]); - } - ((LabeledOMSpline) g).setDoShapes(true); - return g; - } - - public java.net.URL getImageURL(String imageName) { - try { - return Class.forName("com.bbn.openmap.omGraphics.EditableOMPoly") - .getResource(imageName); - } catch (ClassNotFoundException cnfe) { - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMGraphic.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMGraphic.java deleted file mode 100644 index 81e776c1c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMGraphic.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMGraphic.java,v $ -// $RCSfile: LabeledOMGraphic.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/11 20:39:18 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.labeled; - -import java.awt.Font; -import java.awt.Point; - -/** - * The LabeledOMGraphic is a simple extension to the OMGraphic where a - * text string can be set for the graphic on the map. It provides - * basic functionality. If you need more control, try the Location - * object or use a OMText object for your label. - */ -public interface LabeledOMGraphic { - - /** - * Set the String for the label. - */ - public void setText(String label); - - /** - * Get the String for the label. - */ - public String getText(); - - /** - * Set the Font for the label. - */ - public void setFont(Font f); - - /** - * Get the Font for the label. - */ - public Font getFont(); - - /** - * Set the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - - public void setJustify(int just); - - /** - * Get the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - public int getJustify(); - - /** - * Tell the LabeledOMGraphic to calculate the location of the - * String that would put it in the middle of the OMGraphic. - */ - public void setLocateAtCenter(boolean set); - - /** - * Get whether the LabeledOMGraphic is placing the label String in - * the center of the OMGraphic. - */ - public boolean isLocateAtCenter(); - - /** - * Get the calculated center where the label string is drawn. - */ - public Point getCenter(); - - /** - * Set the index of the OMGraphic coordinates where the drawing - * point of the label should be attached. The meaning of the point - * differs between OMGraphic types. - */ - public void setIndex(int index); - - /** - * Get the index of the OMGraphic where the String will be - * rendered. The meaning of the index differs from OMGraphic type - * to OMGraphic type. - */ - public int getIndex(); - - /** - * Set the x, y pixel offsets where the String should be rendered, - * from the location determined from the index point, or from the - * calculated center point. Point.x is the horizontal offset, - * Point.y is the vertical offset. - */ - public void setOffset(Point p); - - /** - * Get the x, y pixel offsets set for the rendering of the point. - */ - public Point getOffset(); - - /** - * Set the angle by which the text is to rotated. - * - * @param angle the number of radians the text is to be rotated. - * Measured clockwise from horizontal. Positive numbers - * move the positive x axis toward the positive y axis. - */ - public void setRotationAngle(double angle); - - /** - * Get the current rotation of the text. - * - * @return the text rotation. - */ - public double getRotationAngle(); - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java deleted file mode 100644 index 526e845ff..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java +++ /dev/null @@ -1,432 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/labeled/LabeledOMPoly.java,v $ -// $RCSfile: LabeledOMPoly.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.labeled; - -import java.awt.Font; -import java.awt.Paint; -import java.awt.Point; - -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * This is an OMPoly that has been extended to manage a text label. - */ -public class LabeledOMPoly - extends OMPoly - implements LabeledOMGraphic { - - protected OMText label; - protected Point offset; - protected boolean locateAtCenter = false; - protected int index = 0; - - public LabeledOMPoly() { - super(); - } - - /** - * Create an LabeledOMPoly from a list of float lat/lon pairs. - * - * @see OMPoly#OMPoly(double[], int, int) - */ - public LabeledOMPoly(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Create an LabeledOMPoly from a list of float lat/lon pairs. - * - * @see OMPoly#OMPoly(double[], int, int, int) - */ - public LabeledOMPoly(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Create an LabeledOMPoly from a list of xy pairs. - * - * @see com.bbn.openmap.omGraphics.OMPoly#OMPoly(int[]) - */ - public LabeledOMPoly(int[] xypoints) { - super(xypoints); - } - - /** - * Create an x/y LabeledOMPoly. - * - * @see OMPoly#OMPoly(int[], int[]) - */ - public LabeledOMPoly(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Create an x/y LabeledOMPoly at an offset from lat/lon. - * - * @see OMPoly#OMPoly(double, double, int[], int) - */ - public LabeledOMPoly(double latPoint, double lonPoint, int[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Create an x/y LabeledOMPoly at an offset from lat/lon. - * - * @see OMPoly#OMPoly(double, double, int[], int[], int) - */ - public LabeledOMPoly(double latPoint, double lonPoint, int[] xPoints, int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * Set the String for the label. - */ - public void setText(String label) { - getLabel().setData(label); - } - - /** - * Get the String for the label. - */ - public String getText() { - return getLabel().getData(); - } - - protected OMText getLabel() { - if (label == null) { - label = new OMText(-1, -1, "", OMText.JUSTIFY_LEFT); - } - return label; - } - - /** - * Set the Font for the label. - */ - public void setFont(Font f) { - getLabel().setFont(f); - } - - /** - * Get the Font for the label. - */ - public Font getFont() { - return getLabel().getFont(); - } - - /** - * Set the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - public void setJustify(int just) { - getLabel().setJustify(just); - } - - /** - * Get the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - public int getJustify() { - return getLabel().getJustify(); - } - - /** - * Tell the LabeledOMGraphic to calculate the location of the String that - * would put it in the middle of the OMGraphic. - */ - public void setLocateAtCenter(boolean set) { - locateAtCenter = set; - if (set) { - setJustify(OMText.JUSTIFY_CENTER); - getLabel().setFMHeight(OMText.ASCENT); - } - } - - /** - * Get whether the LabeledOMGraphic is placing the label String in the - * center of the OMGraphic. - */ - public boolean isLocateAtCenter() { - return locateAtCenter; - } - - /** - * Calculate the projected area of the poly. Algorithm used is from some - * australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - protected double calculateProjectedArea() { - int j = 0; - double area = 0.0; - float[] xpts = xpoints[0]; - float[] ypts = ypoints[0]; - int npoints = xpts.length; - - for (int i = 0; i < npoints; ++i) { - j = (i + 1) % npoints; - area += xpts[i] * ypts[j]; - area -= ypts[i] * xpts[j]; - } - - return area / 2.0; - - // area = area / 2.0; - // return (area < 0.0 ? -area : area); - } - - /** - * Get the calculated center where the label string is drawn. Algorithm used - * is from some australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - public Point getCenter() { - // if the OMPoly isn't generated, then you can't calculate it. - // We're working in x/y space here, so it looks right. - if (getNeedToRegenerate()) { - return null; - } - - float cx = 0.0f; - float cy = 0.0f; - float A = (float) calculateProjectedArea(); - int j = 0; - float factor = 0; - - float[] xpts = xpoints[0]; - float[] ypts = ypoints[0]; - int npoints = xpts.length; - - for (int i = 0; i < npoints; ++i) { - j = (i + 1) % npoints; - - factor = xpts[i] * ypts[j] - xpts[j] * ypts[i]; - cx += (xpts[i] + xpts[j]) * factor; - cy += (ypts[i] + ypts[j]) * factor; - } - - A *= 6.0f; - factor = 1 / A; - - // bbenyo: take the absolute value cause I was getting - // negative values - // for polys with all positive vertices - // cx = Math.abs(cx * factor); - // cy = Math.abs(cy * factor); - - // DFD and RS - let the area calculation return negative - // values, and don't do this absolute value calculation. - // Negative values get returned when the points are - // counterclockwise, indicating holes. We may want labels - // offscreen however, and the abs pushes them onscreen. - - cx *= factor; - cy *= factor; - - Point center = new Point(Math.round(cx), Math.round(cy)); - return center; - } - - /** - * Set the index of the OMGraphic coordinates where the drawing point of the - * label should be attached. The meaning of the point differs between - * OMGraphic types. - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Get the index of the OMGraphic where the String will be rendered. The - * meaning of the index differs from OMGraphic type to OMGraphic type. - */ - public int getIndex() { - return index; - } - - /** - * Set the x, y pixel offsets where the String should be rendered, from the - * location determined from the index point, or from the calculated center - * point. Point.x is the horizontal offset, Point.y is the vertical offset. - */ - public void setOffset(Point p) { - offset = p; - } - - /** - * Get the x, y pixel offsets set for the rendering of the point. - */ - public Point getOffset() { - if (offset == null) { - offset = new Point(); - } - return offset; - } - - /** - * Set the angle by which the text is to rotated. - * - * @param angle the number of radians the text is to be rotated. Measured - * clockwise from horizontal. Positive numbers move the positive x - * axis toward the positive y axis. - */ - public void setRotationAngle(double angle) { - getLabel().setRotationAngle(angle); - } - - /** - * Get the current rotation of the text. - * - * @return the text rotation. - */ - public double getRotationAngle() { - return getLabel().getRotationAngle(); - } - - boolean matchPolyPaint = true; - - /** - * Set the line paint for the polygon. If the text paint hasn't been - * explicitly set, then the text paint will be set to this paint, too. - */ - public void setLinePaint(Paint paint) { - super.setLinePaint(paint); - if (matchPolyPaint) { - getLabel().setLinePaint(paint); - } - } - - /** - * If not set to null, the text will be painted in a different color. If set - * to null, the text paint will match the poly edge paint. - * - * @param paint the Paint object for the text - */ - public void setTextPaint(Paint paint) { - if (paint != null) { - matchPolyPaint = false; - getLabel().setLinePaint(paint); - } - } - - /** - * Used for the actual text location. - */ - Point handyPoint = new Point(); - - /** - * Calculate where the text point ought to go. - */ - protected Point getTextPoint(Projection proj) { - - // Assuming that the rendertype is not unknown... - if (renderType == RENDERTYPE_LATLON && proj instanceof GeoProj) { - int numPoints = rawllpts.length / 2; - if (rawllpts.length < 2) { - // off screen... - handyPoint.setLocation(-10, -10); - return handyPoint; - } - if (locateAtCenter) { - handyPoint = getCenter(); - - // New getCenter algorithm works better. - // for (i = 0; i < rawllpts.length; i+=2) { - // proj.forward(rawllpts[i], rawllpts[i+1], - // handyPoint, true); - - // avgy += handyPoint.getY(); - // avgx += handyPoint.getX(); - // } - // avgy = avgy/numPoints; - // avgx = avgx/numPoints; - // handyPoint.setLocation(avgx, avgy); - } else { - if (index < 0) - index = 0; - if (index > numPoints) - index = numPoints - 1; - ((GeoProj) proj).forward(rawllpts[2 * index], rawllpts[2 * index + 1], handyPoint, true); - } - } else { - float[][] x = xpoints; - float[][] y = ypoints; - - if (x[0].length < 2) { - // off screen... - handyPoint.setLocation(-10, -10); - return handyPoint; - } - - if (locateAtCenter) { - handyPoint = getCenter(); - - // New getCenter algorithm works better. - // for (i = 0; i < x[0].length; i++) { - // avgx += x[0][i]; - // avgy += y[0][i]; - // } - // handyPoint.setLocation(avgx/x[0].length, - // avgy/x[0].length); - } else { - if (index < 0) - index = 0; - if (index >= x[0].length) - index = x[0].length - 1; - handyPoint.setLocation(x[0][index], y[0][index]); - } - } - return handyPoint; - } - - public boolean generate(Projection proj) { - boolean ret = super.generate(proj); - - Point p = getTextPoint(proj); - - if (p != null) { - label.setX((int) (p.getX() + getOffset().getX())); - label.setY((int) (p.getY() + getOffset().getY())); - - if (Debug.debugging("labeled")) { - Debug.output("Setting label(" + label.getData() + ") to " + p); - } - - label.generate(proj); - } - return ret; - } - - public void render(java.awt.Graphics g) { - super.render(g); - label.render(g); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMSpline.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMSpline.java deleted file mode 100644 index 71002c53a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/LabeledOMSpline.java +++ /dev/null @@ -1,333 +0,0 @@ -package com.bbn.openmap.omGraphics.labeled; - -import java.awt.Font; -import java.awt.Paint; -import java.awt.Point; - -import com.bbn.openmap.omGraphics.OMSpline; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * LabeledOMSpline Copied from LabeledOMPoly, because both OMSpline - * and LabeledOMPoly inherits from OMPoly - * - * @author Eric LEPICIER - * @version 15 juil. 2002 - */ -public class LabeledOMSpline extends OMSpline implements LabeledOMGraphic { - - protected OMText label; - protected Point offset; - protected boolean locateAtCenter = false; - protected int index = 0; - - /** - * Default constructor. - */ - public LabeledOMSpline() { - super(); - } - - /** - * Create an LabeledOMSpline from a list of float lat/lon pairs. - */ - public LabeledOMSpline(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Create an LabeledOMSpline from a list of float lat/lon pairs. - */ - public LabeledOMSpline(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Create an LabeledOMSpline from a list of xy pairs. - */ - public LabeledOMSpline(int[] xypoints) { - super(xypoints); - } - - /** - * Create an x/y LabeledOMSpline. - */ - public LabeledOMSpline(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Create an x/y LabeledOMSpline at an offset from lat/lon. - */ - public LabeledOMSpline(float latPoint, float lonPoint, int[] xypoints, - int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Create an x/y LabeledOMSpline at an offset from lat/lon. - */ - public LabeledOMSpline(float latPoint, float lonPoint, int[] xPoints, - int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * Set the String for the label. - */ - public void setText(String label) { - getLabel().setData(label); - } - - /** - * Get the String for the label. - */ - public String getText() { - return getLabel().getData(); - } - - protected OMText getLabel() { - if (label == null) { - label = new OMText(-1, -1, "", OMText.JUSTIFY_LEFT); - } - return label; - } - - /** - * Set the Font for the label. - */ - public void setFont(Font f) { - getLabel().setFont(f); - } - - /** - * Get the Font for the label. - */ - public Font getFont() { - return getLabel().getFont(); - } - - /** - * Set the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - public void setJustify(int just) { - getLabel().setJustify(just); - } - - /** - * Get the justification setting for the label. - * - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_LEFT - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_CENTER - * @see com.bbn.openmap.omGraphics.OMText#JUSTIFY_RIGHT - */ - public int getJustify() { - return getLabel().getJustify(); - } - - /** - * Tell the LabeledOMGraphic to calculate the location of the - * String that would put it in the middle of the OMGraphic. - */ - public void setLocateAtCenter(boolean set) { - locateAtCenter = set; - if (set) { - setJustify(OMText.JUSTIFY_CENTER); - getLabel().setFMHeight(OMText.ASCENT); - } - } - - /** - * Get whether the LabeledOMGraphic is placing the label String in - * the center of the OMGraphic. - */ - public boolean isLocateAtCenter() { - return locateAtCenter; - } - - /** - * Get the calculated center where the label string is drawn. - */ - public Point getCenter() { - return new Point(); - } - - /** - * Set the index of the OMGraphic coordinates where the drawing - * point of the label should be attached. The meaning of the point - * differs between OMGraphic types. - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Get the index of the OMGraphic where the String will be - * rendered. The meaning of the index differs from OMGraphic type - * to OMGraphic type. - */ - public int getIndex() { - return index; - } - - /** - * Set the x, y pixel offsets where the String should be rendered, - * from the location determined from the index point, or from the - * calculated center point. Point.x is the horizontal offset, - * Point.y is the vertical offset. - */ - public void setOffset(Point p) { - offset = p; - } - - /** - * Get the x, y pixel offsets set for the rendering of the point. - */ - public Point getOffset() { - if (offset == null) { - offset = new Point(); - } - return offset; - } - - /** - * Set the angle by which the text is to rotated. - * - * @param angle the number of radians the text is to be rotated. - * Measured clockwise from horizontal. Positive numbers - * move the positive x axis toward the positive y axis. - */ - public void setRotationAngle(double angle) { - getLabel().setRotationAngle(angle); - } - - /** - * Get the current rotation of the text. - * - * @return the text rotation. - */ - public double getRotationAngle() { - return getLabel().getRotationAngle(); - } - - boolean matchPolyPaint = true; - - /** - * Set the line paint for the polygon. If the text paint hasn't - * been explicitly set, then the text paint will be set to this - * paint, too. - */ - public void setLinePaint(Paint paint) { - super.setLinePaint(paint); - if (matchPolyPaint) { - getLabel().setLinePaint(paint); - } - } - - /** - * If not set to null, the text will be painted in a different - * color. If set to null, the text paint will match the poly edge - * paint. - * - * @param paint the Paint object for the text - */ - public void setTextPaint(Paint paint) { - if (paint != null) { - matchPolyPaint = false; - getLabel().setLinePaint(paint); - } - } - - Point handyPoint = new Point(); - - protected Point getTextPoint(Projection proj) { - int i; - int avgx = 0; - int avgy = 0; - - // Assuming that the rendertype is not unknown... - if (renderType == RENDERTYPE_LATLON && proj instanceof GeoProj) { - int numPoints = rawllpts.length / 2; - if (rawllpts.length < 2) { - // off screen... - handyPoint.setLocation(-10, -10); - return handyPoint; - } - if (locateAtCenter) { - for (i = 0; i < rawllpts.length; i += 2) { - ((GeoProj) proj).forward(rawllpts[i], - rawllpts[i + 1], - handyPoint, - true); - - avgy += handyPoint.getY(); - avgx += handyPoint.getX(); - } - avgy /= numPoints; - avgx /= numPoints; - handyPoint.setLocation(avgx, avgy); - } else { - if (index < 0) - index = 0; - if (index > numPoints) - index = numPoints - 1; - ((GeoProj) proj).forward(rawllpts[2 * index], - rawllpts[2 * index + 1], - handyPoint, - true); - } - } else { - float[][] x = xpoints; - float[][] y = ypoints; - - if (x[0].length < 2) { - // off screen... - handyPoint.setLocation(-10, -10); - return handyPoint; - } - - if (locateAtCenter) { - for (i = 0; i < x[0].length; i++) { - avgx += x[0][i]; - avgy += y[0][i]; - } - handyPoint.setLocation(avgx / x[0].length, avgy / x[0].length); - } else { - if (index < 0) - index = 0; - if (index >= x[0].length) - index = x[0].length - 1; - handyPoint.setLocation(x[0][index], y[0][index]); - } - } - return handyPoint; - } - - public boolean generate(Projection proj) { - boolean ret = super.generate(proj); - - Point p = getTextPoint(proj); - label.setX((int) (p.getX() + getOffset().getX())); - label.setY((int) (p.getY() + getOffset().getY())); - - if (Debug.debugging("labeled")) { - Debug.output("Setting label(" + label.getData() + ") to " + p); - } - - label.generate(proj); - return ret; - } - - public void render(java.awt.Graphics g) { - super.render(g); - label.render(g); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/package.html deleted file mode 100644 index 730691d5c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/labeled/package.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a simple extension to the OMGraphics, where a text string can -be attached to a graphic object. These classes only provide basic -functionality for adding text - you can attach the text to certain -points of the OMGraphics, or have the LabeledOMGraphic try to figure -out where the center of the graphic is. You can also set a pixel -offset from the specified calculated point. -

-These graphics have not been updated to have the text parameters -modified via the GUI - the modifications can only be done programmatically. - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/ColdFrontShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/ColdFrontShapeDecoration.java deleted file mode 100644 index 5bfc27fb5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/ColdFrontShapeDecoration.java +++ /dev/null @@ -1,124 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/ColdFrontShapeDecoration.java,v $ -//$RCSfile: ColdFrontShapeDecoration.java,v $ -//$Revision: 1.7 $ -//$Date: 2005/08/09 20:11:32 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.awt.AbstractShapeDecoration; - -/** - * A ShapeDecoration for meteorological cold fronts. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class ColdFrontShapeDecoration extends AbstractShapeDecoration { - - /** We use to draw them blue ! */ - public static Color COLOR = Color.blue; - - /** - * Filled half triangles for surface fronts, empty ones for - * altitude fronts - */ - private boolean filled = true; - - /** - * Constructor. - * - * @param length - * @param width - * @param orientation - */ - public ColdFrontShapeDecoration(int length, int width, int orientation) { - super(length, width, orientation); - setPaint(COLOR); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - - int nbpts = points.length; - int xcoord[] = new int[nbpts + 2]; - int ycoord[] = new int[nbpts + 2]; - - for (int i = 0; i < nbpts; i++) { - xcoord[i] = (int) points[i].getX(); - ycoord[i] = (int) points[i].getY(); - } - - if (complete) { - int orient = getOrientation() == LEFT ? -1 : 1; - - // Compute cosinus and sinus of rotation angle - double dx = points[nbpts - 1].getX() - points[0].getX(); - double dy = points[nbpts - 1].getY() - points[0].getY(); - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = getLength() / 2.0; // x radius before rotation - double w = orient * getWidth(); // y radius before - // rotation - // rotate - xcoord[nbpts] = (int) (points[0].getX() + r * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + r * rsin + w * rcos); - - // link to start - xcoord[nbpts] = (int) points[0].getX(); - ycoord[nbpts++] = (int) points[0].getY(); - - if (filled) - g.fillPolygon(xcoord, ycoord, nbpts); - } - g.drawPolyline(xcoord, ycoord, nbpts); - restoreGraphics(g); - } - - /** - * Returns the filled boolean. - * - * @return boolean - */ - public boolean isFilled() { - return filled; - } - - /** - * Sets the filled (draw a polygon or a polyline ?). - * - * @param filled The filled to set - */ - public void setFilled(boolean filled) { - this.filled = filled; - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/HotFrontShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/HotFrontShapeDecoration.java deleted file mode 100644 index be5ddd493..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/HotFrontShapeDecoration.java +++ /dev/null @@ -1,140 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/HotFrontShapeDecoration.java,v $ -//$RCSfile: HotFrontShapeDecoration.java,v $ -//$Revision: 1.6 $ -//$Date: 2005/08/09 20:11:32 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.awt.AbstractShapeDecoration; - -/** - * A ShapeDecoration for meteorological hot fronts. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class HotFrontShapeDecoration extends AbstractShapeDecoration { - - /** We use to draw them red ! */ - public static Color COLOR = Color.red; - - /** - * Filled half circles for surface fronts, empty ones for altitude - * fronts - */ - private boolean filled = true; - - /** - * Constructor. - * - * @param length - * @param width - * @param orientation - */ - public HotFrontShapeDecoration(int length, int width, int orientation) { - super(length, width, orientation); - setPaint(COLOR); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - - int nbpts = points.length; - int xcoord[] = new int[nbpts + 6]; - int ycoord[] = new int[nbpts + 6]; - - for (int i = 0; i < nbpts; i++) { - xcoord[i] = (int) points[i].getX(); - ycoord[i] = (int) points[i].getY(); - } - - if (complete) { - int orient = getOrientation() == LEFT ? -1 : 1; - - // Compute cosinus and sinus of rotation angle - double dx = points[nbpts - 1].getX() - points[0].getX(); - double dy = points[nbpts - 1].getY() - points[0].getY(); - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices (6 lines to approximate) - double ll = getLength(); // en x avant rotation - double ww = orient * getWidth(); // en y avant rotation - double l, w; - l = 0.9330127 * ll; // i.e. (2 + sqrt(3))/4 - w = 0.5 * ww; - xcoord[nbpts] = (int) (points[0].getX() + l * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + l * rsin + w * rcos); - l = 0.85355339 * ll; // i.e. (2 + sqrt(2))/4 - w = 0.70710678 * ww; - xcoord[nbpts] = (int) (points[0].getX() + l * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + l * rsin + w * rcos); - l = 0.5 * ll; - w = ww; - xcoord[nbpts] = (int) (points[0].getX() + l * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + l * rsin + w * rcos); - l = 0.14644661 * ll; // i.e. (2 - sqrt(2))/4 - w = 0.70710678 * ww; - xcoord[nbpts] = (int) (points[0].getX() + l * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + l * rsin + w * rcos); - l = 0.066987298 * ll; // i.e. (2 - sqrt(3))/4 - w = 0.5 * ww; - xcoord[nbpts] = (int) (points[0].getX() + l * rcos - w * rsin); - ycoord[nbpts++] = (int) (points[0].getY() + l * rsin + w * rcos); - - // link to start - xcoord[nbpts] = (int) points[0].getX(); - ycoord[nbpts++] = (int) points[0].getY(); - - if (filled) - g.fillPolygon(xcoord, ycoord, nbpts); - } - g.drawPolyline(xcoord, ycoord, nbpts); - restoreGraphics(g); - } - - /** - * Returns the filled boolean. - * - * @return boolean - */ - public boolean isFilled() { - return filled; - } - - /** - * Sets the filled (draw a half disk or a half circle ?). - * - * @param filled The filled to set - */ - public void setFilled(boolean filled) { - this.filled = filled; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/IceAreaShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/IceAreaShapeDecoration.java deleted file mode 100644 index 02be8297d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/IceAreaShapeDecoration.java +++ /dev/null @@ -1,118 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/IceAreaShapeDecoration.java,v $ -//$RCSfile: IceAreaShapeDecoration.java,v $ -//$Revision: 1.3 $ -//$Date: 2005/08/09 20:11:32 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.awt.AbstractShapeDecoration; - -/** - * A ShapeDecoration for meteorological icy conditions. - */ -public class IceAreaShapeDecoration extends AbstractShapeDecoration { - - /** We use to draw them red ! */ - public static Color COLOR = new Color(102, 51, 0); - - /** - * Filled half circles for surface fronts, empty ones for altitude - * fronts - */ - private boolean filled = false; - - /** - * Constructor. - * - * @param length - * @param width - * @param orientation - */ - public IceAreaShapeDecoration(int length, int width, int orientation) { - super(length, width, orientation); - setPaint(COLOR); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - - int nbpts = points.length; - - double xcoord1 = points[0].getX(); - double ycoord1 = points[0].getY(); - double xcoord2 = points[nbpts - 1].getX(); - double ycoord2 = points[nbpts - 1].getY(); - - g.drawLine((int) xcoord1, (int) ycoord1, (int) xcoord2, (int) ycoord2); - - if (complete) { - int orient = getOrientation() == LEFT ? -1 : 1; - - // Compute cosinus and sinus of rotation angle - double dx = xcoord2 - xcoord1; - double dy = ycoord2 - ycoord1; - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = getLength() / 2.0; // x radius before rotation - double w = orient * getWidth(); // y radius before - // rotation - // rotate - - int x2 = (int) (xcoord1 + r * rcos); - int y2 = (int) (ycoord1 + r * rsin); - int x1 = (int) (x2 - w * rsin); - int y1 = (int) (y2 + w * rcos); - - g.drawLine((int) x2, (int) y2, (int) x1, (int) y1); - } - - restoreGraphics(g); - } - - /** - * Returns the filled boolean. - * - * @return boolean - */ - public boolean isFilled() { - return filled; - } - - /** - * Sets the filled (draw a half disk or a half circle ?). - * - * @param filled The filled to set - */ - public void setFilled(boolean filled) { - this.filled = filled; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMColdSurfaceFront.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMColdSurfaceFront.java deleted file mode 100644 index a8bf65fd0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMColdSurfaceFront.java +++ /dev/null @@ -1,124 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/OMColdSurfaceFront.java,v $ -//$RCSfile: OMColdSurfaceFront.java,v $ -//$Revision: 1.4 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import com.bbn.openmap.omGraphics.OMDecoratedSpline; -import com.bbn.openmap.omGraphics.awt.LineShapeDecoration; - -/** - * OMColdSurfaceFront. Just need to init the decorations. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class OMColdSurfaceFront extends OMDecoratedSpline { - - public static int LENGTH = 10; - public static int WIDTH = 10; - public static int SPACING = 36; - - /** - * Constructor. - */ - public OMColdSurfaceFront() { - super(); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - */ - public OMColdSurfaceFront(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - * @param nsegs - */ - public OMColdSurfaceFront(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Constructor. - * - * @param xypoints - */ - public OMColdSurfaceFront(int[] xypoints) { - super(xypoints); - } - - /** - * Constructor. - * - * @param xPoints - * @param yPoints - */ - public OMColdSurfaceFront(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xypoints - * @param cMode - */ - public OMColdSurfaceFront(float latPoint, float lonPoint, int[] xypoints, - int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xPoints - * @param yPoints - * @param cMode - */ - public OMColdSurfaceFront(float latPoint, float lonPoint, int[] xPoints, - int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * @see com.bbn.openmap.omGraphics.OMDecoratedSpline#initDecorations() - */ - protected void initDecorations() { - getDecorator().addDecoration(new LineShapeDecoration(SPACING, ColdFrontShapeDecoration.COLOR)); - getDecorator().addDecoration(new ColdFrontShapeDecoration(LENGTH, WIDTH, ColdFrontShapeDecoration.LEFT)); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMHotSurfaceFront.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMHotSurfaceFront.java deleted file mode 100644 index 54d59d2e7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMHotSurfaceFront.java +++ /dev/null @@ -1,124 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/OMHotSurfaceFront.java,v $ -//$RCSfile: OMHotSurfaceFront.java,v $ -//$Revision: 1.4 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import com.bbn.openmap.omGraphics.OMDecoratedSpline; -import com.bbn.openmap.omGraphics.awt.LineShapeDecoration; - -/** - * OMHotSurfaceFront Just need to init the decorations. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class OMHotSurfaceFront extends OMDecoratedSpline { - - public static int LENGTH = 10; - public static int WIDTH = 5; - public static int SPACING = 36; - - /** - * Constructor. - */ - public OMHotSurfaceFront() { - super(); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - */ - public OMHotSurfaceFront(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Constructor. - * - * @param llPoints - * @param units - * @param lType - * @param nsegs - */ - public OMHotSurfaceFront(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Constructor. - * - * @param xypoints - */ - public OMHotSurfaceFront(int[] xypoints) { - super(xypoints); - } - - /** - * Constructor. - * - * @param xPoints - * @param yPoints - */ - public OMHotSurfaceFront(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xypoints - * @param cMode - */ - public OMHotSurfaceFront(float latPoint, float lonPoint, int[] xypoints, - int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Constructor. - * - * @param latPoint - * @param lonPoint - * @param xPoints - * @param yPoints - * @param cMode - */ - public OMHotSurfaceFront(float latPoint, float lonPoint, int[] xPoints, - int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * @see com.bbn.openmap.omGraphics.OMDecoratedSpline#initDecorations() - */ - protected void initDecorations() { - getDecorator().addDecoration(new LineShapeDecoration(SPACING, HotFrontShapeDecoration.COLOR)); - getDecorator().addDecoration(new HotFrontShapeDecoration(LENGTH, WIDTH, HotFrontShapeDecoration.LEFT)); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMOcclusion.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMOcclusion.java deleted file mode 100644 index 0a6713e31..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/OMOcclusion.java +++ /dev/null @@ -1,131 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/OMOcclusion.java,v $ -//$RCSfile: OMOcclusion.java,v $ -//$Revision: 1.6 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import java.awt.Color; - -import com.bbn.openmap.omGraphics.OMDecoratedSpline; -import com.bbn.openmap.omGraphics.awt.LineShapeDecoration; - -/** - * OMOcclusion Just need to init the decorations. - * - * @author Eric LEPICIER - * @version 28 juil. 2002 - */ -public class OMOcclusion extends OMDecoratedSpline { - - public static Color COLOR = new Color(255, 0, 255); - public static int LENGTH = 10; - public static int WIDTH = 5; - public static int SPACING = 36; - - /** - * Constructor for OMOcclusion. - */ - public OMOcclusion() { - super(); - } - - /** - * Constructor for OMOcclusion. - * - * @param llPoints - * @param units - * @param lType - */ - public OMOcclusion(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Constructor for OMOcclusion. - * - * @param llPoints - * @param units - * @param lType - * @param nsegs - */ - public OMOcclusion(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Constructor for OMOcclusion. - * - * @param xypoints - */ - public OMOcclusion(int[] xypoints) { - super(xypoints); - } - - /** - * Constructor for OMOcclusion. - * - * @param xPoints - * @param yPoints - */ - public OMOcclusion(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Constructor for OMOcclusion. - * - * @param latPoint - * @param lonPoint - * @param xypoints - * @param cMode - */ - public OMOcclusion(float latPoint, float lonPoint, int[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Constructor for OMOcclusion. - * - * @param latPoint - * @param lonPoint - * @param xPoints - * @param yPoints - * @param cMode - */ - public OMOcclusion(float latPoint, float lonPoint, int[] xPoints, - int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * @see com.bbn.openmap.omGraphics.OMDecoratedSpline#initDecorations() - */ - protected void initDecorations() { - getDecorator().addDecoration(new LineShapeDecoration(SPACING, COLOR)); - ColdFrontShapeDecoration cdec = new ColdFrontShapeDecoration(LENGTH, WIDTH * 2, ColdFrontShapeDecoration.LEFT); - cdec.setPaint(COLOR); - getDecorator().addDecoration(cdec); - HotFrontShapeDecoration hdec = new HotFrontShapeDecoration(LENGTH, WIDTH, ColdFrontShapeDecoration.LEFT); - hdec.setPaint(COLOR); - getDecorator().addDecoration(hdec); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/TurbulanceShapeDecoration.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/TurbulanceShapeDecoration.java deleted file mode 100644 index 11b325bed..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/meteo/TurbulanceShapeDecoration.java +++ /dev/null @@ -1,115 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/meteo/TurbulanceShapeDecoration.java,v $ -//$RCSfile: TurbulanceShapeDecoration.java,v $ -//$Revision: 1.4 $ -//$Date: 2005/08/11 20:39:14 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.meteo; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.awt.AbstractShapeDecoration; - -/** - * A ShapeDecoration for meteorological turbulance conditions. - */ -public class TurbulanceShapeDecoration extends AbstractShapeDecoration { - - /** We use to draw them red ! */ - public static Color COLOR = Color.blue; - - /** - * Filled half circles for surface fronts, empty ones for altitude - * fronts - */ - private boolean filled = true; - - /** - * Constructor. - * - * @param length - * @param radius - */ - public TurbulanceShapeDecoration(int length, int radius) { - super(length, radius, 1); - setPaint(COLOR); - } - - /** - * @see com.bbn.openmap.omGraphics.awt.ShapeDecoration#draw(Graphics, - * Point2D[], boolean) - */ - public void draw(Graphics g, Point2D[] points, boolean complete) { - setGraphics(g); - - int nbpts = points.length; - - double xcoord1 = points[0].getX(); - double ycoord1 = points[0].getY(); - double xcoord2 = points[nbpts - 1].getX(); - double ycoord2 = points[nbpts - 1].getY(); - - if (complete) { - - // Compute cosinus and sinus of rotation angle - double dx = xcoord2 - xcoord1; - double dy = ycoord2 - ycoord1; - double norm = Math.sqrt(dx * dx + dy * dy); - double rcos = dx / norm; - double rsin = dy / norm; - - // Compute vertices - double r = getLength() / 2.0; // x radius before rotation - double w = getWidth(); - // rotate - - int x = (int) (xcoord1 + r * rcos); - int y = (int) (ycoord1 + r * rsin); - - g.fillOval((int) (x - w / 2), - (int) (y - w / 2), - (int) (w), - (int) (w)); - } - - restoreGraphics(g); - - } - - /** - * Returns the filled boolean. - * - * @return boolean - */ - public boolean isFilled() { - return filled; - } - - /** - * Sets the filled (draw a half disk or a half circle ?). - * - * @param filled The filled to set - */ - public void setFilled(boolean filled) { - this.filled = filled; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/package.html deleted file mode 100644 index 8ea826170..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides geographically based graphics classes. - - diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/IndexRule.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/IndexRule.java deleted file mode 100644 index 5f889d6dc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/IndexRule.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * A Rule is an attribute inspector that makes decisions about rendering - * attributes, information line contents, tooltips and visibility based on - * scale. - * - * @author dietrick - */ -public abstract class IndexRule extends Rule> { - /** - * The column index where the testing value can be found for the rule to - * compare against the value. - */ - protected int keyIndex = -1; - protected int[] tooltipIndicies; - protected int[] infolineIndicies; - protected int[] labelIndicies; - - /** - * A record List for the attributes of an OMGraphic might have a name for - * each entry. Given a name, provide the index into the List to get that - * attribute value. NOTE: This method will be overridden by subclasses that - * read data and create attribute data structures. - * - * @param columnName name of a attribute in a List, like a column name of a - * list of lists. - * @return the int index of the entry in the record List. - */ - public abstract int getRecordColumnIndexForName(String columnName); - - /** - * Provide the title of the attribute at a specific entry. NOTE: This method - * will be overridden by subclasses that read data and create attribute data - * structures. - * - * @param index into the record List. - * @return the record List name for that index. - */ - public abstract String getRecordColumnName(int index); - - /** - * Asks the Op class to evaluate the provided value against the Rules value. - * - * @param record list of objects to evaluate, the keyIndex will be used to - * fetch the appropriate object from the List. - * @return true of the operation passed - */ - public boolean evaluate(List record) { - Object recVal = record.get(keyIndex); - return op.evaluate(this.val, recVal); - } - - /** - * Returns a String of concatenated record values. This method will work, - * but another method can be called that takes indices that will save a - * lookup step. - * - * @param fieldNames name of columns - * @param record List to use for return value - * @return String of content - */ - public String getContent(List fieldNames, List record) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - int index = getRecordColumnIndexForName(field); - buf.append(PropUtils.unnull(record.get(index))).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String key = props.getProperty(prefix + RuleKeyProperty); - keyIndex = getRecordColumnIndexForName(key); - - tooltipIndicies = getIndicies(tooltipFields); - infolineIndicies = getIndicies(infolineFields); - labelIndicies = getIndicies(labelFields); - } - - /** - * Evaluate the record against this rule. - * - * @param record A List of attributes for a particular OMGraphic/map object. - * The indices for the rule are indexes into this record. - * @param omg The OMGraphic to evaluate. - * @param proj The current map projection. - * @return the OMGraphic if it should be drawn, null if it shouldn't. - */ - public OMGraphic evaluate(List record, OMGraphic omg, Projection proj) { - - if (evaluate(record)) { - - float scale = 0f; - - if (proj != null) { - scale = proj.getScale(); - - if (scale < displayMinScale || scale > displayMaxScale) { - // We met the rule, it's telling us not to display. - return null; - } - } - - if (infolineIndicies != null) { - omg.putAttribute(OMGraphicConstants.INFOLINE, getContentFromIndicies(infolineIndicies, record)); - } - if (tooltipIndicies != null) { - omg.putAttribute(OMGraphicConstants.TOOLTIP, getContentFromIndicies(tooltipIndicies, record)); - } - if (labelIndicies != null && scale >= labelMinScale && scale <= labelMaxScale) { - String curLabel = getContentFromIndicies(labelIndicies, record); - - OMTextLabeler label = new OMTextLabeler(curLabel, OMText.JUSTIFY_CENTER); - // Needs to get added to the OMGraphic so it gets - // generated with the projection at the right point. - omg.putAttribute(OMGraphicConstants.LABEL, label); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(omg); - } - omg.setVisible(drawingAttributes != null); - - return omg; - } - - return null; - } - - /** - * Returns a String of concatenated record values. - * - * @param indicies column indexes of values to be concatenated in return - * value - * @param record List to use for return value - * @return String of content - */ - public String getContentFromIndicies(int[] indicies, List record) { - int numIndicies = indicies.length; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < numIndicies; i++) { - int val = indicies[i]; - if (val != -1) { - buf.append((String) record.get(val)).append(" "); - } - } - return buf.toString().trim(); - } - - /** - * Given a prefix + ActionProperty, get the column names listed as the - * property value and figure out what the indexes of the columns are. - * - * @param fieldNames a List of Strings for property title - * @return int array of column indexes in the dbf file reflecting the order - * and number of column names listed as the property value. - */ - public int[] getIndicies(List fieldNames) { - int[] indicies = null; - if (fieldNames != null) { - int numCols = fieldNames.size(); - indicies = new int[numCols]; - int i = 0; - for (String columnName : fieldNames) { - indicies[i++] = getRecordColumnIndexForName(columnName); - } - } - - return indicies; - } - - /** - * Given a prefix + ActionProperty, get the column names listed as the - * property value and figure out what the indexes of the columns are. - * - * @param indicies int[] of column indexes in the dbf file reflecting the - * order and number of column names to be listed as a property - * value. - * @return String for use in properties of space-separated column names. - */ - public String getColumnNamesFromIndicies(int[] indicies) { - StringBuffer buf = new StringBuffer(); - int numCols = indicies.length; - for (int i = 0; i < numCols; i++) { - buf.append(getRecordColumnName(indicies[i])).append(" "); - } - - return buf.toString().trim(); - } - - public int[] getInfolineIndicies() { - return infolineIndicies; - } - - public void setInfolineIndicies(int[] infolineIndicies) { - this.infolineIndicies = infolineIndicies; - } - - public int getKeyIndex() { - return keyIndex; - } - - public void setKeyIndex(int keyIndex) { - this.keyIndex = keyIndex; - } - - public int[] getLabelIndicies() { - return labelIndicies; - } - - public void setLabelIndicies(int[] labelIndicies) { - this.labelIndicies = labelIndicies; - } - - public int[] getTooltipIndicies() { - return tooltipIndicies; - } - - public void setTooltipIndicies(int[] tooltipIndicies) { - this.tooltipIndicies = tooltipIndicies; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/MapRule.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/MapRule.java deleted file mode 100644 index e3ec34e9c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/MapRule.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.util.PropUtils; - -/** - * Implementation of Rule that uses a Map for attributes. - * - * @author dietrick - */ -public class MapRule extends Rule> { - - /** - * Asks the Op class to evaluate the provided value against the Rules value. - * - * @param record - * @return true of the operation passed - */ - public boolean evaluate(Map record) { - Object recVal = record.get(keyField); - return op.evaluate(this.val, recVal); - } - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames column names - * @param record Map to use to fetch values - * @return String of content - */ - public String getContent(List fieldNames, Map record) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - buf.append(PropUtils.unnull(record.get(field))).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/Rule.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/Rule.java deleted file mode 100644 index 015f04edf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/Rule.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A Rule is an attribute inspector that makes decisions about rendering - * attributes, information line contents, tooltips and visibility based on - * scale. - * - * @author dietrick - */ -public abstract class Rule extends OMComponent { - /** - * The property name where the testing value can be found for the rule to - * compare against the value. - */ - protected String keyField; - protected List tooltipFields; - protected List infolineFields; - protected List labelFields; - - /** - * The value that the query runs the operation against. - */ - protected Object val; - protected RuleOp op = RuleOp.NONE; - - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - - protected float displayMinScale = Float.MIN_VALUE; - protected float displayMaxScale = Float.MAX_VALUE; - protected float labelMinScale = Float.MIN_VALUE; - protected float labelMaxScale = Float.MAX_VALUE; - - /** - *

-     * layer.rules=rule1 rule2 rule3 
-     * layer.rule1.key=CAPITAL
-     * layer.rule1.op=equals
-     * layer.rule1.val=Y
-     * layer.rule1.actions=render tooltip infoline 
-     * layer.rule1.lineColor=FFFF0000
-     * layer.rule1.minScale=10000
-     * layer.rule1.maxScale=50000
-     * layer.rule1.infoline=CITY_NAME
-     * layer.rule1.tooltip=ELEVATION
-     * 
- */ - public final static String RuleListProperty = "rules"; - public final static String RuleKeyProperty = "key"; - public final static String RuleOperatorProperty = "op"; - public final static String RuleValueProperty = "val"; - - public final static String RuleActionRender = "render"; - public final static String RuleActionTooltip = "tooltip"; - public final static String RuleActionInfoline = "infoline"; - public final static String RuleActionLabel = "label"; - public final static String RuleActionMinScale = "minScale"; - public final static String RuleActionMaxScale = "maxScale"; - - /** - * Asks the Op class to evaluate the retrieved value against the Rules - * value. The implementation will use the key to pull the testing value out - * of the record. - * - * @param record object to evaluate - * @return true of the operation passed - */ - public abstract boolean evaluate(T record); - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames a list of string keys for fields to be used. - * @param record The record object to look up values for the list of keys. - * @return String of content - */ - public abstract String getContent(List fieldNames, T record); - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - keyField = props.getProperty(prefix + RuleKeyProperty, keyField); - tooltipFields = getStringFromFields(props.getProperty(prefix + RuleActionTooltip)); - infolineFields = getStringFromFields(props.getProperty(prefix + RuleActionInfoline)); - labelFields = getStringFromFields(props.getProperty(prefix + RuleActionLabel)); - - RuleOp op = RuleOp.resolve(props.getProperty(prefix + RuleOperatorProperty)); - if (op != null) { - this.op = op; - } - - Object newVal = props.getProperty(prefix + RuleValueProperty); - if (newVal != null) { - val = newVal; - } - - if (keyField == null) { - Debug.output("No key for rule (" + prefix + ") found in properties."); - } - - displayMinScale = PropUtils.floatFromProperties(props, prefix + RuleActionRender + "." - + RuleActionMinScale, displayMinScale); - displayMaxScale = PropUtils.floatFromProperties(props, prefix + RuleActionRender + "." - + RuleActionMaxScale, displayMaxScale); - labelMinScale = PropUtils.floatFromProperties(props, prefix + RuleActionLabel + "." - + RuleActionMinScale, labelMinScale); - labelMaxScale = PropUtils.floatFromProperties(props, prefix + RuleActionLabel + "." - + RuleActionMaxScale, labelMaxScale); - - // Assume that the OMGraphic will be rendered, with defaults if not - // specified. render has to be set to false to hide OMGraphic - boolean renderProperties = PropUtils.booleanFromProperties(props, prefix + RuleActionRender, drawingAttributes != null); - if (renderProperties) { - if (drawingAttributes == null) { - drawingAttributes = new DrawingAttributes(); - } - drawingAttributes.setProperties(prefix, props); - } else { - drawingAttributes = null; - } - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + RuleKeyProperty, PropUtils.unnull(keyField)); - - if (tooltipFields != null && !tooltipFields.isEmpty()) { - props.put(prefix + RuleActionTooltip, getFieldsAsString(tooltipFields)); - } - if (infolineFields != null && !infolineFields.isEmpty()) { - props.put(prefix + RuleActionInfoline, getFieldsAsString(infolineFields)); - } - if (labelFields != null && !labelFields.isEmpty()) { - props.put(prefix + RuleActionLabel, getFieldsAsString(labelFields)); - } - - if (this.op != null) { - props.put(prefix + RuleOperatorProperty, this.op.getPropertyNotation()); - } - if (val != null) { - props.put(prefix + RuleValueProperty, PropUtils.unnull(val.toString())); - } - - if (displayMinScale != Float.MIN_VALUE) { - props.put(prefix + RuleActionRender + "." + RuleActionMinScale, Float.toString(displayMinScale)); - } - if (displayMaxScale != Float.MAX_VALUE) { - props.put(prefix + RuleActionRender + "." + RuleActionMaxScale, Float.toString(displayMaxScale)); - } - if (labelMinScale != Float.MIN_VALUE) { - props.put(prefix + RuleActionLabel + "." + RuleActionMinScale, Float.toString(labelMinScale)); - } - if (labelMaxScale != Float.MAX_VALUE) { - props.put(prefix + RuleActionLabel + "." + RuleActionMaxScale, Float.toString(labelMaxScale)); - } - - if (drawingAttributes != null) { - props.put(prefix + RuleActionRender, Boolean.toString(true)); - drawingAttributes.getProperties(props); - } - - return props; - } - - /** - * Evaluate the record against this rule. - * - * @param record A Map of attributes for a particular OMGraphic/map object. - * The indices for the rule are indexes into this record. - * @param omg The OMGraphic to evaluate. - * @param proj The current map projection. - * @return the OMGraphic if it should be drawn, null if it shouldn't. - */ - public OMGraphic evaluate(T record, OMGraphic omg, Projection proj) { - - if (evaluate(record)) { - - float scale = 0f; - - if (proj != null) { - scale = proj.getScale(); - - if (scale < displayMinScale || scale > displayMaxScale) { - // We met the rule, it's telling us not to display. - return null; - } - } - - if (infolineFields != null) { - omg.putAttribute(OMGraphicConstants.INFOLINE, getContent(infolineFields, record)); - } - if (tooltipFields != null) { - omg.putAttribute(OMGraphicConstants.TOOLTIP, getContent(tooltipFields, record)); - } - if (labelFields != null && scale >= labelMinScale && scale <= labelMaxScale) { - String curLabel = getContent(labelFields, record); - - OMTextLabeler label = new OMTextLabeler(curLabel, OMText.JUSTIFY_CENTER); - // Needs to get added to the OMGraphic so it gets - // generated with the projection at the right point. - omg.putAttribute(OMGraphicConstants.LABEL, label); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(omg); - } - omg.setVisible(drawingAttributes != null); - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine(this.getPropertyPrefix() + " being assigned to " - + op.getClass().getName() + " " + keyField + " " + val + " vs " - + ((Map) record).get(keyField)); - - omg.putAttribute("RULE", getPropertyPrefix()); - } - - return omg; - } - - return null; - } - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames names of field properties - * @return fields as single string - */ - public String getFieldsAsString(List fieldNames) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - buf.append(PropUtils.unnull(field)).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } - - /** - * Create a List of Strings from a list of space separated strings. - * - * @param fieldString - * @return List if fieldString can be parsed, null if fieldString is null. - */ - public List getStringFromFields(String fieldString) { - if (fieldString != null && !fieldString.isEmpty()) { - return PropUtils.parseSpacedMarkers(fieldString); - } - return null; - } - - public DrawingAttributes getDrawingAttribtues() { - return drawingAttributes; - } - - public void setDrawingAttributes(DrawingAttributes da) { - this.drawingAttributes = da; - } - - public float getDisplayMaxScale() { - return displayMaxScale; - } - - public void setDisplayMaxScale(float displayMaxScale) { - this.displayMaxScale = displayMaxScale; - } - - public float getDisplayMinScale() { - return displayMinScale; - } - - public void setDisplayMinScale(float displayMinScale) { - this.displayMinScale = displayMinScale; - } - - public String getKeyName() { - return keyField; - } - - public void setKeyName(String keyName) { - this.keyField = keyName; - } - - public List getLabelFields() { - return labelFields; - } - - public void setLabelFields(List labelFields) { - this.labelFields = labelFields; - } - - public List getInfolineFields() { - return infolineFields; - } - - public void setInfolineFields(List infolineFields) { - this.infolineFields = infolineFields; - } - - public List getTooltipFields() { - return tooltipFields; - } - - public void setTooltipFields(List tooltipFields) { - this.tooltipFields = tooltipFields; - } - - public float getLabelMaxScale() { - return labelMaxScale; - } - - public void setLabelMaxScale(float labelMaxScale) { - this.labelMaxScale = labelMaxScale; - } - - public float getLabelMinScale() { - return labelMinScale; - } - - public void setLabelMinScale(float labelMinScale) { - this.labelMinScale = labelMinScale; - } - - public RuleOp getOp() { - return op; - } - - public void setOp(RuleOp op) { - this.op = op; - } - - public Object getVal() { - return val; - } - - public void setVal(Object val) { - this.val = val; - } - - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Rule.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleHandler.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleHandler.java deleted file mode 100644 index 8b7990ba4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleHandler.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The RuleHandler manages a set of Rules and will evaluate OMGraphics against - * them for a current projection. - *

- * For List rules, something like this: - * - *

- * # Rule marker names specified in space-separated list
- * neroads.rules=rule0 rule1
- * # global scale settings can be used so work is only performed within scale range of minScale/maxScale
- * neroads.maxScale=1000000f
- * 
- * # rule0 definition:
- * # CLASS_RTE is a DBF column name
- * neroads.rule0.key=CLASS_RTE
- * # operation, if key value is less than 2
- * neroads.rule0.op=lt
- * neroads.rule0.val=2
- * # If rule is met, then actions can be performed:
- * # Column names can be added together in a label by specifying them in a space-separated list
- * neroads.rule0.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * # Labels can have scale limits imposed, so they don't appear if map scale is 
- * # greater than maxScale or less than minScale
- * neroads.rule0.label.maxScale=1000000
- * # Visibility can be controlled with respect to scale as well
- * neroads.rule0.render.maxScale=1000000
- * # Rendering attributes can be specified.
- * neroads.rule0.lineColor=FFFA73
- * neroads.rule0.lineWidth=4
- * neroads.rule0.mattingColor=55AAAAAA
- * 
- * # rule1 definition:
- * neroads.rule1.key=CLASS_RTE
- * neroads.rule1.op=all
- * neroads.rule1.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * neroads.rule1.label.maxScale=200000
- * neroads.rule1.render.maxScale=500000
- * neroads.rule1.lineColor=FFFFFF
- * neroads.rule1.lineWidth=3
- * neroads.rule1.mattingColor=55AAAAAA
- * 
- * # The render attribute is assumed to be true.  You can hide OMGraphics by setting it to false.
- * 
- * - * @author dietrick - */ -public abstract class RuleHandler extends OMComponent { - - List> rules; - - /** - * Create a Rule object that knows how to interpret properties to create the - * proper indices into the record List. - */ - public abstract Rule createRule(); - - /** - * Return a record Map for a particular OMGraphic, like a properties table. - * - * @param omg OMGraphic being queried - * @return Map of objects as attributes for the OMGraphic. - */ - public abstract T getRecordDataForOMGraphic(OMGraphic omg); - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String rulesString = props.getProperty(prefix + Rule.RuleListProperty); - List keysV = PropUtils.parseSpacedMarkers(rulesString); - - if (keysV != null && !keysV.isEmpty()) { - List> rules = Collections.synchronizedList(new LinkedList>()); - - for (String ruleMarker : keysV) { - Rule rule = createRule(); - rule.setProperties(prefix + ruleMarker, props); - rules.add(rule); - } - - setRules(rules); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer ruleList = new StringBuffer(); - int createdRuleNum = 1; - - for (Rule rule : getRules()) { - String rulePrefix = rule.getPropertyPrefix(); - - // For rules created programmatically without a prefix, need to - // create one. - if (rulePrefix == null) { - rulePrefix = "createdRulePrefix" + (createdRuleNum++); - rule.setPropertyPrefix(prefix + rulePrefix); - } - - if (rulePrefix.startsWith(prefix)) { - rulePrefix = rulePrefix.substring(prefix.length()); - if (rulePrefix.startsWith(".")) { - rulePrefix = rulePrefix.substring(1); - } - } - - ruleList.append(rulePrefix).append(" "); - - rule.getProperties(props); - } - - if (ruleList.length() > 0) { - props.put(prefix + Rule.RuleListProperty, ruleList.toString()); - } - - return props; - } - - public void setRules(List> rules) { - this.rules = rules; - } - - public void addRule(Rule rule) { - if (rule != null) { - getRules().add(rule); - } - } - - public boolean removeRule(Rule rule) { - if (rule != null) { - return getRules().remove(rule); - } - - return false; - } - - public void clearRules() { - getRules().clear(); - } - - public List> getRules() { - if (rules == null) { - rules = Collections.synchronizedList(new LinkedList>()); - } - return rules; - } - - /** - * Used to help prevent consecutive repeat label values. - */ - protected String lastLabel; - - /** - * This is the main call that a layer would use to modify/update an - * OMGraphic based on dbf file contents. Tries to retrieve the index from - * the attributes of the OMGraphic, and then checks the index and OMGraphic - * to see how/if it should be rendered, as determined by the rules. - * - * @param omg the OMGraphic in question - * @param labelList an OMGraphicList to add the label to, so it gets - * rendered on top. - * @param proj the current map projection, for scale appropriateness - * determinations. - * @return OMGraphic if it should be displayed, null if it shouldn't. - */ - public OMGraphic evaluate(OMGraphic omg, OMGraphicList labelList, Projection proj) { - - // Just check for rules first - if no rules defined, don't bother - // reading the attributes. - List> rules = getRules(); - if (rules.isEmpty()) { - return omg; - } - - T record = getRecordDataForOMGraphic(omg); - if (record == null) { - return omg; - } - - OMGraphic passedEval = null; - - for (Rule rule : rules) { - - passedEval = rule.evaluate(record, omg, proj); - - if (passedEval != null) { - - /** - * Let's do some stuff with a label to minimize the number of - * labels that might show up. - */ - Object labelObj = omg.getAttribute(OMGraphic.LABEL); - if (labelObj instanceof OMTextLabeler) { - String curLabel = ((OMTextLabeler) labelObj).getData(); - - if (lastLabel == null - || (lastLabel != null && !lastLabel.equalsIgnoreCase(curLabel))) { - labelList.add((OMTextLabeler) labelObj); - } else { - // The Rule adds the label to the OMGraphic, we'll - // remove it so it doesn't get rendered underneath - omg.removeAttribute(OMGraphic.LABEL); - } - - lastLabel = curLabel; - } - break; - } - - } - - // Might be null - return passedEval; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleOp.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleOp.java deleted file mode 100644 index faf1ec72f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/rule/RuleOp.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -/** - * The RuleOp class (operation) is used by the Rules to evaluate a rule key - * value against a OMGraphics key value. - * - * @author dietrick - */ -public enum RuleOp { - - /** - * equals: equals - */ - EQUALS("equals", "equals") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - }, - /** - * lt: less than - */ - LESS_THAN("less than", "lt") { - public boolean compare(int kvcr) { - return kvcr > 0; - } - }, - /** - * lte: less than or equals - */ - LESS_THAN_EQUALS("less than or equals", "lte") { - public boolean compare(int kvcr) { - return kvcr == 0 || kvcr > 0; - } - }, - /** - * gt: greater than - */ - GREATER_THAN("greater than", "gt") { - public boolean compare(int kvcr) { - return kvcr < 0; - } - }, - /** - * gte: greater than or equals - */ - GREATER_THAN_EQUALS("greater than or equals", "gte") { - public boolean compare(int kvcr) { - return kvcr == 0 || kvcr < 0; - } - }, - /** - * ne: not equals - */ - NOT_EQUALS("not equals", "ne") { - public boolean compare(int kvcr) { - return kvcr != 0; - } - }, - /** - * noop: no-op (nothing passes rule) - */ - NONE("no-op", "noop") { - public boolean compare(int kvcr) { - return false; - } - }, - /** - * all: all (everything passes rule) - */ - ALL("all", "all") { - public boolean compare(int kvcr) { - return true; - } - }, - /** - * starts: starts with - */ - STARTS_WITH("starts with", "starts") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - - public boolean evaluate(Object key, Object val) { - return (val.toString()).startsWith(key.toString()); - } - }, - /** - * ends: ends with - */ - ENDS_WITH("ends with", "ends") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - - public boolean evaluate(Object key, Object val) { - return (val.toString()).endsWith(key.toString()); - } - }; - - protected String description; - protected String propertyNotation; - - private RuleOp(String desc, String propNotation) { - this.description = desc; - this.propertyNotation = propNotation; - } - - public boolean evaluate(Object key, Object val) { - if (key == null) { - return compare(-1); - } - - if (val instanceof Number) { - if (!(key instanceof Double)) { - java.text.DecimalFormat df = new java.text.DecimalFormat(); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH); - df.setDecimalFormatSymbols(dfs); - try { - key = new Double(df.parse(key.toString()).doubleValue()); - } catch (java.text.ParseException pe) { - return compare(-1); - } - } - - return compare(((Double) key).compareTo(((Number) val).doubleValue())); - } - - return compare(((String) key.toString()).compareTo(val.toString())); - } - - public abstract boolean compare(int keyValcompareResult); - - public static RuleOp resolve(String opString) { - if (opString != null) { - for (RuleOp op : values()) { - if (op.propertyNotation.equalsIgnoreCase(opString)) { - return op; - } - } - } - return null; - } - - public String getDescription() { - return description; - } - - public String getPropertyNotation() { - return propertyNotation; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphic.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphic.java deleted file mode 100644 index ed1f96b81..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphic.java +++ /dev/null @@ -1,53 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; - -/** - * A TemporalOMGraphic object represents an OMGraphic that changes over time. - * The time is expected to be based on some offset from a time origin, like the - * starting time of some greater set of events. - */ -public interface TemporalOMGraphic extends OMGraphic { - - /** - * Add a location at a time. - */ - public void addTimeStamp(TemporalRecord timeStamp); - - /** - * Remove a location at a certain time. - */ - public boolean removeTimeStamp(TemporalRecord timeStamp); - - /** - * Clear all time stamps. - */ - public void clearTimeStamps(); - - public void generate(Projection proj, long time); -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphicList.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphicList.java deleted file mode 100644 index 53499c053..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMGraphicList.java +++ /dev/null @@ -1,116 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * A TemporalOMGeometryList object contains OMGeometries that change over time. - * The time is milliseconds, generally from the unix epoch. This list can also hold regular - * OMGeometries. - */ -public class TemporalOMGraphicList extends OMGraphicList implements - TemporalOMGraphic { - /** - * Construct an TemporalOMGraphicList. - */ - public TemporalOMGraphicList() { - super(10); - } - - /** - * Construct an TemporalOMGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public TemporalOMGraphicList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an TemporalOMGraphicList around a List of OMGraphics. The - * TemporalOMGraphicList assumes that all the objects on the list are - * OMGraphics, and never does checking. Live with the consequences if you - * put other stuff in there. - * - * @param list List of OMGraphics. - */ - public TemporalOMGraphicList(List list) { - super(list); - } - - /** - * Calls generate(proj, time) on temporal geometries, regular generate(proj) - * on non-temporal OMGeometries. - */ - public void generate(Projection proj, long time) { - for (OMGraphic geom : this) { - if (geom instanceof TemporalOMGraphic) { - ((TemporalOMGraphic) geom).generate(proj, time); - } else { - geom.generate(proj); - } - } - } - - /** - * Add a location at a time to every TemporalGeometry contained within. - */ - public void addTimeStamp(TemporalRecord timeStamp) { - for (OMGraphic geom: this) { - if (geom instanceof TemporalOMGraphic) { - ((TemporalOMGraphic)geom).addTimeStamp(timeStamp); - } - } - } - - /** - * Remove a location at a certain time. - */ - public boolean removeTimeStamp(TemporalRecord timeStamp) { - for (OMGraphic geom: this) { - if (geom instanceof TemporalOMGraphic) { - ((TemporalOMGraphic)geom).removeTimeStamp(timeStamp); - } - } - return true; - } - - /** - * Clear all time stamps. - */ - public void clearTimeStamps() { - for (OMGraphic geom: this) { - if (geom instanceof TemporalOMGraphic) { - ((TemporalOMGraphic)geom).clearTimeStamps(); - } - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMPoint.java deleted file mode 100644 index 25a8fe33c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMPoint.java +++ /dev/null @@ -1,138 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/scenario/ScenarioPoint.java,v $ -// $RCSfile: ScenarioPoint.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.proj.Projection; - -/** - * A ScenarioPoint is a ScenarioGraphic representing an object on the map. It - * takes TimeStamps and works out its location for a specific time, or it can - * also represent its plan for the entire scenario. If the URL provided for the - * point is not available, it will describe itself as an OMPoint. ScenarioPoint - * is a Location, however, so any location marker OMGraphic can be used. Make - * sure setGraphicLocations is updated if the marker OMGraphic is something - * other than OMPoint or OMRaster. - */ -public class TemporalOMPoint extends OMPoint implements TemporalOMGraphic { - - protected Object id; - - /** - * A list of points where this point should be. - */ - protected TemporalPointSupport timeStamps; - - /** - * Flag to indicate that intermediate positions between locations should be - * interpolated. - */ - protected boolean interpolate = false; - - public Object getId() { - return id; - } - - public void setId(Object id) { - this.id = id; - } - - public boolean isInterpolate() { - return interpolate; - } - - public void setInterpolate(boolean interpolate) { - this.interpolate = interpolate; - } - - /** - * Create a ScenarioLocation at a latitude/longitude location. - * - * @param id the identifier for the location. - */ - public TemporalOMPoint(Object id, int renderType, boolean interpolate) { - this.id = id; - this.interpolate = interpolate; - setRenderType(renderType); - timeStamps = new TemporalPointSupport(renderType); - } - - /** - * Checks the internal id against the given one. - */ - public boolean thisIsYou(Object n) { - return id.equals(n); - } - - /** - * Add a TimeStamp to the point. - */ - public void addTimeStamp(TemporalRecord timeStamp) { - timeStamps.add(timeStamp); - setNeedToRegenerate(true); - } - - public boolean removeTimeStamp(TemporalRecord timeStamp) { - return timeStamps.remove(timeStamp); - } - - public void clearTimeStamps() { - timeStamps.clear(); - } - - /** - * Given a time, figure out the location. If the time is before the earliest - * time or after the latest time, the location will be set to the first or - * last known location, but the marker will made invisible. If the time is - * in between the first and last time, the position will be interpolated. - */ - public TemporalPoint setPosition(long time) { - return timeStamps.getPosition(time, interpolate); - } - - /** - * Prepare the ScenarioPoint to be rendered in its position at a certain - * time. - */ - public void generate(Projection p, long time) { - - TemporalPoint tp = setPosition(time); - - if (tp == null) { - return; - } - - Point2D pt = tp.getLocation(); - switch (renderType) { - case RENDERTYPE_XY: - set((int) pt.getX(), (int) pt.getY()); - break; - default: - set(pt.getY(), pt.getX()); - } - - super.generate(p); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMScalingIcon.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMScalingIcon.java deleted file mode 100644 index 070a288f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalOMScalingIcon.java +++ /dev/null @@ -1,269 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.awt.Color; -import java.awt.Image; -import java.awt.geom.Point2D; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.proj.Projection; - -public class TemporalOMScalingIcon - extends OMScalingIcon - implements TemporalOMGraphic { - - /** - * Construct a blank TemporalOMScalingIcon, to be filled in with set calls. - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate) { - this.id = id; - this.interpolate = interpolate; - setRenderType(renderType); - timeStamps = new TemporalPointSupport(renderType); - } - - // /////////////////////////////////// INT PIXELS - DIRECT - // COLORMODEL - - /** - * Creates an TemporalOMScalingIcon from images, Lat/Lon placement with a - * direct colormodel image. - * - * @param id the id of the TemporalOMScalingIcon - * @param renderType rendertype of coordinates to be used in moving this - * around - * @param interpolate flag to interpolate position between TemporalRecords. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param pix color values for the pixels. - * @param baseScale the scale where the icon will be show regular size. - * @see #setPixel - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, int w, int h, int[] pix, float baseScale) { - this(id, renderType, interpolate); - setColorModel(OMRasterObject.COLORMODEL_DIRECT); - setWidth(w); - setHeight(h); - setPixels(pix); - this.baseScale = baseScale; - } - - // //////////////////////////////////// IMAGEICON - - /** - * Create an OMRaster, Lat/Lon placement with an ImageIcon. - * - * @param id the id of the TemporalOMScalingIcon - * @param renderType rendertype of coordinates to be used in moving this - * around - * @param interpolate flag to interpolate position between TemporalRecords. - * @param ii ImageIcon used for the image. - * @param baseScale the scale where the icon will be show regular size. - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, ImageIcon ii, float baseScale) { - this(id, renderType, interpolate); - setWidth(ii.getIconWidth()); - setHeight(ii.getIconHeight()); - setColorModel(OMRasterObject.COLORMODEL_IMAGEICON); - setImage(ii.getImage()); - setBaseScale(baseScale); - } - - /** - * Create an scaling icon that will be moved around. - * - * @param id the id of the TemporalOMScalingIcon - * @param renderType rendertype of coordinates to be used in moving this - * around - * @param interpolate flag to interpolate position between TemporalRecords. - * @param ii ImageIcon used for the image. - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, ImageIcon ii) { - this(id, renderType, interpolate, ii.getImage(), 4000000); - setMaxScale(4000000); - setMinScale(4000000); - } - - /** - * Create an scaling icon that will be moved around. - * - * @param id ID of object. - * @param renderType the interpreted path between known positions - * @param interpolate whether the positions between known timestamps should - * be interpolated. - * @param ii ImageIcon used for image - * @param baseScale - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, Image ii, float baseScale) { - this(id, renderType, interpolate); - setColorModel(OMRasterObject.COLORMODEL_IMAGEICON); - setImage(ii); - setBaseScale(baseScale); - } - - /** - * Create a scaling icon that moves. - * - * @param id ID of icon - * @param renderType how position will be interpolated between know - * positions - * @param interpolate whether position should be interpolated between known - * positions. - * @param image java Image to use for icon. - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, Image image) { - this(id, renderType, interpolate); - setColorModel(OMRasterObject.COLORMODEL_IMAGEICON); - setImage(image); - setBaseScale(40000000); - setMaxScale(4000000); - setMinScale(4000000); - } - - // //////////////////////////////////// BYTE PIXELS with - // COLORTABLE - - /** - * Lat/Lon placement with a indexed colormodel, which is using a colortable - * and a byte array to construct the int[] pixels. - * - * @param id the id of the TemporalOMScalingIcon - * @param renderType rendertype of coordinates to be used in moving this - * around - * @param interpolate flag to interpolate position between TemporalRecords. - * @param w width of the image, in pixels. - * @param h height of the image, in pixels. - * @param bytes colortable index values for the pixels. - * @param colorTable color array corresponding to bytes - * @param trans transparency of image. - * @param baseScale the scale where the icon will be show regular size. - * @see #setPixel - */ - public TemporalOMScalingIcon(Object id, int renderType, boolean interpolate, int w, int h, byte[] bytes, Color[] colorTable, - int trans, float baseScale) { - - this(id, renderType, interpolate); - setColorModel(OMRasterObject.COLORMODEL_INDEXED); - setBaseScale(baseScale); - setWidth(w); - setHeight(h); - setBits(bytes); - setColors(colorTable); - setTransparent(trans); - } - - protected Object id; - - /** - * A list of points where this point should be. - */ - protected TemporalPointSupport timeStamps; - - /** - * Flag to indicate that intermediate positions between locations should be - * interpolated. - */ - protected boolean interpolate = false; - - public Object getId() { - return id; - } - - public void setId(Object id) { - this.id = id; - } - - public boolean isInterpolate() { - return interpolate; - } - - public void setInterpolate(boolean interpolate) { - this.interpolate = interpolate; - } - - /** - * Checks the internal id against the given one. - */ - public boolean thisIsYou(Object n) { - return id.equals(n); - } - - /** - * Add a TimeStamp to the point. - */ - public void addTimeStamp(TemporalRecord timeStamp) { - timeStamps.add(timeStamp); - setNeedToRegenerate(true); - } - - public boolean removeTimeStamp(TemporalRecord timeStamp) { - return timeStamps.remove(timeStamp); - } - - public void clearTimeStamps() { - timeStamps.clear(); - } - - /** - * Given a time, figure out the location. If the time is before the earliest - * time or after the latest time, the location will be set to the first or - * last known location, but the marker will made invisible. If the time is - * in between the first and last time, the position will be interpolated. - */ - public TemporalPoint setPosition(long time) { - return timeStamps.getPosition(time, interpolate); - } - - /** - * Prepare the ScenarioPoint to be rendered in its position at a certain - * time. - */ - public void generate(Projection p, long time) { - - TemporalPoint tp = setPosition(time); - - if (tp == null) { - return; - } - - Point2D pt = tp.getLocation(); - switch (renderType) { - case RENDERTYPE_XY: - setX((int) pt.getX()); - setY((int) pt.getY()); - break; - default: - setLat(pt.getY()); - setLon(pt.getX()); - } - - super.generate(p); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPoint.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPoint.java deleted file mode 100644 index 06be5a8fc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPoint.java +++ /dev/null @@ -1,96 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/graphicLoader/scenario/TimeStamp.java,v $ -// $RCSfile: TimeStamp.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.util.HashCodeUtil; - -/** - * A TemporalPoint is a representation of something occurring at a location and - * time. The time is expected to be millisecond offsets from some starting time. - */ -public class TemporalPoint - implements TemporalRecord { - - protected Point2D location; - protected long time; - - /** - * Create a TimeStamp to be used as a position by ScenarioPoints. - */ - public TemporalPoint(Point2D location, long t) { - this.location = location; - time = t; - } - - public String toString() { - return "TimeStamp [" + location + ", time=" + time + " ]"; - } - - public void setTime(long t) { - time = t; - } - - public long getTime() { - return time; - } - - public void setLocation(Point2D loc) { - location = loc; - } - - public Point2D getLocation() { - return location; - } - - /** - * Indicates whether some other object is "equal to" this Comparator. Assumes - * that the other object is a TimeStamp object. Compares time fields. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TemporalPoint other = (TemporalPoint) obj; - return other.time == time; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - if (location != null) { - result = HashCodeUtil.hash(result, location); - } - result = HashCodeUtil.hash(result, time); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPointSupport.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPointSupport.java deleted file mode 100644 index a00ca1758..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalPointSupport.java +++ /dev/null @@ -1,109 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.awt.geom.Point2D; -import java.util.Iterator; -import java.util.TreeSet; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class TemporalPointSupport extends TemporalSupport { - - protected int renderType = OMGraphic.RENDERTYPE_UNKNOWN; - - public TemporalPointSupport(int renderType) { - this.renderType = renderType; - } - - @Override - public TreeSet createTemporalSet() { - if (temporals == null) { - temporals = new TreeSet(new TemporalRecordComparator()); - } - return (TreeSet) temporals; - } - - @Override - public Iterator iterator() { - return (Iterator) temporals.iterator(); - } - - /** - * Just returns the TemporalRecord that is closes to the current time. - * Assumes neither previous or next are null. - * - * @param time the current time. - * @param previous TemporalRecord that occurred before current time. - * @param next TemporalRecord that occurred after current time. - * @return closest one. - */ - protected TemporalRecord interpolate(long time, TemporalRecord previous, - TemporalRecord next) { - TemporalRecord ret = null; - double top = time - previous.getTime(); - double bottom = next.getTime() - previous.getTime(); - double percent = top / bottom; - - switch (renderType) { - case OMGraphic.RENDERTYPE_XY: - // TODO - simple geometric interpolation instead of choosing closest - // record. - ret = super.interpolate(time, previous, next); - break; - default: - // assume lat/lons - Point2D prevPt = ((TemporalPoint) previous).getLocation(); - Point2D nextPt = ((TemporalPoint) next).getLocation(); - LatLonPoint prevLL; - LatLonPoint nextLL; - if (prevPt instanceof LatLonPoint) { - prevLL = (LatLonPoint) prevPt; - } else { - prevLL = new LatLonPoint.Double(prevPt); - } - if (nextPt instanceof LatLonPoint) { - nextLL = (LatLonPoint) nextPt; - } else { - nextLL = new LatLonPoint.Double(nextPt); - } - - double[] pts = GreatCircle.greatCircle(prevLL.getRadLat(), - prevLL.getRadLon(), - nextLL.getRadLat(), - nextLL.getRadLon(), - 100, - true); - - int index = (int) (2 * Math.floor(100 * percent)); - - ret = new TemporalPoint(new LatLonPoint.Double(pts[index], pts[index + 1], true), time); - } - - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecord.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecord.java deleted file mode 100644 index 7ab561acf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecord.java +++ /dev/null @@ -1,39 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -/** - * A TemporalRecord object represents something that happened at a given time. - * The time is expected to be based on some offset from a time origin, like the - * starting time of some greater set of events. The TemporalRecord is the basis - * for comparing whether something happened before another. - * - * @author dietrick - */ -public interface TemporalRecord { - long getTime(); - - void setTime(long t); -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecordComparator.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecordComparator.java deleted file mode 100644 index 2a77dde8c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalRecordComparator.java +++ /dev/null @@ -1,43 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.util.Comparator; - -public class TemporalRecordComparator implements Comparator { - - public int compare(TemporalRecord o1, TemporalRecord o2) { - long time1 = o1.getTime(); - long time2 = o2.getTime(); - if (time1 < time2) { - return -1; - } else if (time1 > time2) { - return 1; - } else { - return 0; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalSupport.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalSupport.java deleted file mode 100644 index d8eb66bef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/time/TemporalSupport.java +++ /dev/null @@ -1,196 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.time; - -import java.util.Iterator; -import java.util.TreeSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The TemporalSupport object is intended to provide rudimentary support for - * choosing the right temporal status for a given time. A list of TemporalRecord - * objects are managed by this support object and given a time, it will return - * the applicable TemporalRecord for that time. The updateForTemporalRecord - * method allows this object to be extended to keep track of what happens to an - * object from the start of time, so that an object's status can be observed and - * calculated based on everything that might have changed in the TemporalRecord - * list before a given time. - */ -public abstract class TemporalSupport { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.time.TemporalSupport"); - - protected TreeSet temporals; - - /** - * - * @param time in milliseconds - * @param interpolate flag to signal that the returned Temporal object - * should be interpolated (in whatever way needed) if the time falls - * between Temporal objects. - */ - public T getPosition(long time, boolean interpolate) { - T previous = null; - T next = null; - - // Find out where the timestamp is in relation to the reported - // positions - synchronized (temporals) { - - Iterator it = iterator(); - while (it.hasNext()) { - T temporal = it.next(); - long recTimeStamp = temporal.getTime(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("evaluating: " + temporal + " vs " + time); - } - - if (recTimeStamp < time) { - previous = temporal; - updateForTemporal(time, temporal); - } else if (recTimeStamp > time) { - next = temporal; - break; - } else { - // Hit a time right at a position. - updateForTemporal(time, temporal); - return temporal; - } - } - } - - T pos = null; - - // OK, now's the opportunity to leave if - // interpolation is not wanted. - - if (previous != null && !interpolate) { - return previous; - } else if (previous == null) { - // time is before MissionFeature is placed. - // Don't want to set pos here, should be null to set - // visibility properly. - if (next != null) { - // Just for fun, put location where it will be. We - // still want to get here if interpolation is not - // wanted if the current time is before the first - // position report. - if (logger.isLoggable(Level.FINER)) { - logger.finer("premature time, invisible: " + next.toString()); - } - // We're displaying this position before we're - // supposed to know it's there. - // pos = createPosition(time, next); - - } else { - // no timestamps - // Returning null Position - } - - } else if (next == null) { - - // time is after last temporal - - // We're displaying this position after the last position - // report, assuming that the object is just going to sit - // there. - pos = previous; - - } else { - - // Need to interpolate between the two, previous and next. - // This may not be exact, but it's close. - - pos = (T) interpolate(time, previous, next); - } - - return pos; - } - - /** - * Override this method to use the TemporalRecord's contents to affect the - * status of whatever you like. - * - * @param time milliseconds reflecting the current time. - * @param temporal record that reflects something that has happened. - */ - protected void updateForTemporal(long time, TemporalRecord temporal) { - - } - - /** - * Just returns the TemporalRecord that is closes to the current time. - * Assumes neither previous or next are null. - * - * @param time the current time. - * @param previous TemporalRecord that occurred before current time. - * @param next TemporalRecord that occurred after current time. - * @return closest one. - */ - protected TemporalRecord interpolate(long time, TemporalRecord previous, TemporalRecord next) { - long midTime = previous.getTime() + (next.getTime() - previous.getTime()) / 2l; - - if (time < midTime) { - return previous; - } - - return next; - } - - public TreeSet getTemporals() { - if (temporals == null) { - temporals = createTemporalSet(); - } - return (TreeSet) temporals; - } - - public void setTemporals(TreeSet temporals) { - this.temporals = temporals; - } - - public abstract TreeSet createTemporalSet(); - - public abstract Iterator iterator(); - - public void add(TemporalRecord tr) { - getTemporals().add(tr); - } - - /** - * Return true if the TemporalRecord was contained in the list. - * - * @param tr - * @return true if removal was successful. - */ - public boolean remove(TemporalRecord tr) { - return getTemporals().remove(tr); - } - - public void clear() { - temporals.clear(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ArcCalc.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ArcCalc.java deleted file mode 100644 index 3abfbe637..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ArcCalc.java +++ /dev/null @@ -1,432 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/util/ArcCalc.java,v $ -// $RCSfile: ArcCalc.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/10 22:28:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.util; - -import java.awt.Graphics; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.io.Serializable; - -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * A class that calculates an arc between two points, given the point - * coordinates, and an arc measurement that represents, in radians, - * the length of the part of the circle that should be represented by - * the arc. - */ -public class ArcCalc implements Serializable { - - /** Debugging list showing algorithm points. */ - protected transient OMGraphicList arcGraphics = null; - - protected transient float[] xpoints; - protected transient float[] ypoints; - - /** - * This setting is the amount of an angle, limited to a - * semi-circle (PI) that the curve will represent. In other words, - * the arc between the two end points is going to look like a 0 - * degrees of a circle (straight line, which is the default), or - * 180 degrees of a circle (full semi-circle). Given in radians, - * though, not degrees. OK? - */ - protected double arcAngle = 0; - - /** - * For x-y and offset lines that have an arc drawn between them, - * tell which way the arc should be drawn, toward the Equator, or - * away from it, generally. Default is true, to make it look like - * great circle line for northern hemisphere lines. - */ - protected boolean arcUp = true; - - /** - * Set to true if the points for the arc line up from x2, y2 to - * x1, y1 - */ - protected boolean reversed = false; - - /** - * Set the arc that is drawn between the points of a x-y or offset - * line. If the arc amount is negative, the arc will be flipped - * over. - * - * @param aa arcAngle, in radians, between 0-PI. - * @param putArcUp arc peak above points. - */ - public ArcCalc(double aa, boolean putArcUp) { - arcAngle = aa; - arcUp = putArcUp; - - // If it's negative, flip it over... - if (aa < 0) { - arcAngle *= -1.0; - arcUp = !arcUp; - } - - if (arcAngle > Math.PI) { - arcAngle = Math.PI; - } - } - - /** - * Return the arc angle set for this line. Will only be set if it - * was set externally. - * - * @return arc angle in radians. - */ - public double getArcAngle() { - return arcAngle; - } - - /** - * Returns true if the arc direction setting is upward, meaning - * that the peak of the arc is above (or more so) the line that - * goes between the two points. - */ - public boolean isArcUp() { - return arcUp; - } - - /** - * Generate the points that will generate the curved line between - * two points. The arcAngle is the number of radians of a circle - * that the arc should represent. Math.PI is the Max. The - * setArcAngle should be called before this method is called, so - * that the method knows what to create. - */ - public void generate(int x1, int y1, int x2, int y2) { - - // The algorithm. - // - // Draw a straight line between the points, and figure out the - // center point between them on the line. Then, on another - // line that is perpendicular to the first line, figure out - // where the point is that will act as a center of a circle. - // That circle needs to pass through both points, and the - // radius is such that the arc angle of the circle between the - // points is the same as the arcAngle set for the ArcCalc. - // Then, the arc needs to be generated. This is done by - // looking at the circle, and figuring out the angle (from 0 - // to 2PI) that the line from the center to point 1, and then - // the center to point 2. This gives us the angular extents - // of the arc. Then we need to figure out the angle - // increments needed to get good coordinates for the arc. - // Then, starting at the low arc angle, we increment it to get - // the coordinates for the arced line, a given radius away - // from the circle center, between the arc angle extents. - - Point midPoint = new Point(); - Point arcCenter = new Point(); - Point2D peakPoint = new Point2D.Float(); - - // pixel distance between points. - double distance = Math.sqrt(Math.pow(Math.abs(y2 - y1), 2.0) - + Math.pow(Math.abs(x2 - x1), 2.0)); - // slope of straight line between points. - double straightLineSlope = Math.atan((double) (y2 - y1) - / (double) (x2 - x1)); - - // slope of line that the arc focus will reside on. - double inverseSlope = straightLineSlope - (Math.PI / 2.0); - - if (Debug.debugging("arc")) { - Debug.output("ArcCalc.generate: Slope is " - + Math.toDegrees(straightLineSlope) - + " degrees, distance = " + distance + " pixels."); - } - - // centerX/Y is the midpoint between the two points. - midPoint.setLocation(x1 + ((x2 - x1) / 2), y1 + ((y2 - y1) / 2)); - - if (Debug.debugging("arc")) { - Debug.output("ArcCalc.generate: Center point for (" + x1 + ", " - + y1 + ") to (" + x2 + ", " + y2 + ") is (" + midPoint.x - + ", " + midPoint.y + ")"); - } - - double arccos = Math.cos(arcAngle); - double arcRadius; - - if (arccos != 1.0) { - arcRadius = distance / Math.sqrt(2.0 * (1.0 - Math.cos(arcAngle))); - } else { - arcRadius = distance / Math.sqrt(2.0); - } - - if (Debug.debugging("arc")) { - Debug.output("ArcCalc.generate: radius of arc = " + arcRadius); - } - - // R' is the distance down the inverse negative slope of the - // line that the focus of the arc is located. - - // x is the distance along the right leg of the arc that is - // left over after Rcos(arcAngle) is subtracted from it, in - // order to derive the angle of the straight line between the - // two points. - - double x = arcRadius - arcRadius * Math.cos(arcAngle); - - double rPrime = (distance / 2.0) - * (Math.sqrt(1.0 - Math.pow(x / distance, 2.0))) - / Math.sin(arcAngle / 2.0); - - if (Debug.debugging("arc")) { - Debug.output("ArcCalc.generate: rPrime = " + rPrime); - } - - int direction = 1; - if (arcUp) - direction = -1; - - // arcCenter.x and arcCenter.y are the coordinates of the - // focus of the Arc. - arcCenter.x = midPoint.x - + (direction * (int) (rPrime * Math.cos(inverseSlope))); - arcCenter.y = midPoint.y - + (direction * (int) (rPrime * Math.sin(inverseSlope))); - - if (Debug.debugging("arc")) { - - Debug.output("ArcCalc.generateArc: creating supplimental graphics list"); - arcGraphics = new OMGraphicList(); - - double dist1 = Math.sqrt(Math.pow((double) (arcCenter.x - x1), 2.0) - + Math.pow((double) (arcCenter.y - y1), 2.0)); - double dist2 = Math.sqrt(Math.pow((double) (arcCenter.x - x2), 2.0) - + Math.pow((double) (arcCenter.y - y2), 2.0)); - - Debug.output("ArcCalc.generate: Center focus for arc is (" - + arcCenter.x + ", " + arcCenter.y - + ") along slope line of " - + Math.toDegrees(inverseSlope) + " degrees)."); - Debug.output("ArcCalc.generate: Distance to point 1 from arc focus = " - + dist1 - + "\n Distance to point 2 from arc focus = " - + dist2); - - // Let's highlight the end points. - OMRect point1 = new OMRect(x1 - 1, y1 - 1, x1 + 1, y1 + 1); - OMRect point2 = new OMRect(x2 - 1, y2 - 1, x2 + 1, y2 + 1); - OMRect arcPoint = new OMRect(arcCenter.x - 1, arcCenter.y - 1, arcCenter.x + 1, arcCenter.y + 1); - - point1.setLinePaint(OMColor.red); - point2.setLinePaint(OMColor.red); - arcPoint.setLinePaint(OMColor.blue); - arcGraphics.add(point1); - arcGraphics.add(point2); - arcGraphics.add(arcPoint); - - OMLine line1 = new OMLine(x1, y1, x2, y2); - OMLine line2 = new OMLine(midPoint.x, midPoint.y, arcCenter.x, arcCenter.y); - arcGraphics.add(line1); - arcGraphics.add(line2); - } - - int realCount = 0; - - // Figure out the arc extents for each endpoint. I think - // it's easier to keep track of the angles if they are always - // positive, and we always go from smaller to larger. - double startSlope = getRealAngle((float)arcCenter.getX(), (float)arcCenter.getY(), x1, y1); - double endSlope = getRealAngle((float)arcCenter.getX(), (float)arcCenter.getY(), x2, y2); - - double smallSlope, largeSlope; - double angleIncrement; - - smallSlope = (startSlope > endSlope) ? endSlope : startSlope; - largeSlope = (smallSlope == startSlope) ? endSlope : startSlope; - - // Have to make sure we take the smaller arc around the - // circle. - while (Math.abs(smallSlope - largeSlope) > Math.PI) { - if (Math.abs(largeSlope - smallSlope - Math.PI) < .001) { - // Catch 180 degree angles that are close enough... - break; - } - - Debug.message("arc", - "ArcCalc.generate: Modifying the starting slope."); - double tmpSlope = smallSlope + MoreMath.TWO_PI; - smallSlope = largeSlope; - largeSlope = tmpSlope; - } - - // Experienced some trouble with vertical and horizontal half - // circles. This took care of that. - if (MoreMath.approximately_equal(arcAngle, Math.PI) && arcUp) { - Debug.message("arc", - "ArcCalc.generate: Modifying 180 angle points."); - double tmpSlope = smallSlope + MoreMath.TWO_PI; - smallSlope = largeSlope; - largeSlope = tmpSlope; - } - - // Figure out the angle increment for grabbing coordinates - - // use the larger dimension of the arc end point differences. - if (Math.abs(y2 - y1) < Math.abs(x2 - x1)) { - angleIncrement = Math.PI / Math.abs(x2 - x1); - } else { - angleIncrement = Math.PI / Math.abs(y2 - y1); - } - - int numPoints = (int) (Math.abs(smallSlope - largeSlope) - / angleIncrement + 2); - float[] xPoints = new float[numPoints]; - float[] yPoints = new float[numPoints]; - - if (Debug.debugging("arc")) { - Debug.output("ArcCalc.generate: angle to x1, y1 is " + startSlope - + " (" + Math.toDegrees(startSlope) - + " degrees), angle to x2, y2 is " + endSlope + " (" - + Math.toDegrees(endSlope) + " degrees)"); - - Debug.output("ArcCalc.generate: Starting angle is " + smallSlope - + "(" + Math.toDegrees(smallSlope) - + " degrees), end angle is " + largeSlope + " (" - + Math.toDegrees(largeSlope) - + " degrees), incrementing by " + angleIncrement + " (" - + Math.toDegrees(angleIncrement) + " degrees)"); - } - - reversed = false; - // Get the coordinates of the arc from the arc extents. - while (smallSlope < largeSlope && realCount < numPoints) { - - xPoints[realCount] = arcCenter.x - + (int) (arcRadius * Math.cos(smallSlope)); - yPoints[realCount] = arcCenter.y - + (int) (arcRadius * Math.sin(smallSlope)); - - if (realCount == 0 && xPoints[realCount] == x2) { - Debug.message("arc", "ArcCalc: line reversed"); - reversed = true; - } - - if (Debug.debugging("arc") && realCount == 0) { - OMLine startLine = new OMLine(arcCenter.x, arcCenter.y, (int) xPoints[0], (int) yPoints[0]); - startLine.setLinePaint(OMColor.white); - arcGraphics.add(startLine); - } else if (Debug.debugging("arcdetail")) { - Debug.output(" angle " + smallSlope + " (" + smallSlope * 180 - / Math.PI + " degrees) = " + xPoints[realCount] + ", " - + yPoints[realCount]); - } - - if (Math.abs(largeSlope - smallSlope - (arcAngle / 2.0)) < angleIncrement) { - // Found the halfway point, mark it... - peakPoint.setLocation(xPoints[realCount], yPoints[realCount]); - Debug.message("arc", "ArcCalc: Found a midpoint."); - } - - smallSlope += angleIncrement; - realCount++; - } - - // Give the coordinates to the OMLine. - xpoints = new float[realCount]; - ypoints = new float[realCount]; - - - System.arraycopy(xPoints, 0, xpoints, 0, realCount); - System.arraycopy(yPoints, 0, ypoints, 0, realCount); - } - - /** - * Given the straight line between two points, figure out the - * angle, in radians, of that line in relation to the coordinate - * system on the screen. Always returns a positive value, and the - * angle is from point 1 to point 2. - */ - protected double getRealAngle(float x1, float y1, float x2, float y2) { - double angle = 0; - - double horDiff = (double) (x2 - x1); - double vertDiff = (double) (y2 - y1); - - // If there is no horizontal difference, then it's pointing - // up or down. - if (horDiff == 0) { - if (vertDiff > 0) { - angle = MoreMath.HALF_PI; - } else if (vertDiff < 0) { - angle = -MoreMath.HALF_PI; - } - } else { - angle = Math.atan(vertDiff / horDiff); - - // It's pointed in the wrong direction... fix it here. - if (horDiff < 0) { - angle += Math.PI; - } - } - - // Either way, I think we want to make the angle positive. - while (angle < 0) { - angle += MoreMath.TWO_PI; - } - return angle; - } - - public float[] getXPoints() { - return xpoints; - } - - public float[] getYPoints() { - return ypoints; - } - - public void generate(Projection proj) { - if (proj != null && arcGraphics != null) { - arcGraphics.generate(proj); - } - } - - public void render(Graphics g) { - if (arcGraphics != null) { - Debug.output("OMLine rendering " + arcGraphics.size() - + " arcGraphics."); - arcGraphics.render(g); - } - } - - public OMGraphicList getArcGraphics() { - if (arcGraphics == null) { - return new OMGraphicList(); - } else { - return arcGraphics; - } - } - - public boolean getReversed() { - return reversed; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ImageWarp.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ImageWarp.java deleted file mode 100644 index c3d43f143..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/ImageWarp.java +++ /dev/null @@ -1,591 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics.util; - -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.awt.image.PixelGrabber; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.image.WorldFile; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMLabeler; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.Debug; - -/** - * The ImageTranslator is the object that takes a BufferedImage and creates an - * OMRaster from it based on a Projection object. - */ -public class ImageWarp { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.util.ImageWarp"); - - /** - * Source image pixels. - */ - protected int[] pixels = null; - - /** Image width, */ - protected int iwidth; - /** Image height, */ - protected int iheight; - /** - * Horizontal units/pixel in the source BufferedImage projection. Assumed to - * be constant across the image. - */ - protected double hor_upp; - /** - * Vertical units/pixel in the source BufferedImage projection. Assumed to - * be constant across the image. - */ - protected double ver_upp; - /** - * The vertical origin pixel location in the source image for the coordinate - * system origin. - */ - protected double verOrigin; - /** - * The horizontal origin pixel location in the source image for the - * coordinate system origin. - */ - protected double horOrigin; - - /** - * A transformation for the projection of the source image. If not set, the - * image is assumed to be equal arc projection. - */ - protected GeoCoordTransformation geoTrans = new LatLonGCT(); - - /** - * The coordinate bounds of the image, represented in the coordinate system - * of the image. - */ - protected DataBounds sourceImageBounds; - - /** - * The coordinate image bounds of the projected image on the map window. - */ - protected DataBounds projectedImageBounds; - - /** - * Create an image warp for an image assumed to be world wide coverage, with - * the top at 90 degrees, the bottom at -90, the left side at -180 and the - * right side at 180. Assumes the origin point is in the middle of the - * image. - */ - public ImageWarp(BufferedImage bi) { - this(bi, LatLonGCT.INSTANCE, new DataBounds(-180.0, -90.0, 180.0, 90.0)); - } - - /** - * Create an image warp with some additional transform information. - * - * @param bi BufferedImage of the source - * @param transform the GeoCoordTransformation for the projection of the - * image. - * @param imageBounds the bounds of the image in the image's coordinate - * system. - */ - public ImageWarp(BufferedImage bi, GeoCoordTransformation transform, DataBounds imageBounds) { - if (bi != null) { - iwidth = bi.getWidth(); - iheight = bi.getHeight(); - setGeoTrans(transform); - setImageBounds(imageBounds); - - pixels = getPixels(bi, 0, 0, iwidth, iheight); - - // See if this saves on memory. Seems to. - bi = null; - } - } - - /** - * Create an image warp with some additional transform information. - * - * @param bi BufferedImage of the source - * @param transform the GeoCoordTransformation for the projection of the - * image. - * @param worldFile the WorldFile describing the image's location. - */ - public ImageWarp(BufferedImage bi, GeoCoordTransformation transform, WorldFile worldFile) { - if (bi != null) { - iwidth = bi.getWidth(); - iheight = bi.getHeight(); - setGeoTrans(transform); - - setImageBounds(worldFile); - - pixels = getPixels(bi, 0, 0, iwidth, iheight); - - // See if this saves on memory. Seems to. - bi = null; - } - } - - /** - * Create an image warp for an image assumed to be world wide coverage, with - * the top at 90 degrees, the bottom at -90, the left side at -180 and the - * right side at 180. Assumes the origin point is in the middle of the - * image. - * - * @param pix ARGB array of pixel values for image. - * @param width pixel width of image. - * @param height pixel height of image. - */ - public ImageWarp(int[] pix, int width, int height) { - this(pix, width, height, LatLonGCT.INSTANCE, new DataBounds(-180.0, -90.0, 180.0, 90.0)); - } - - /** - * Create an image warp with some additional transform information. - * - * @param pix ARGB array of pixel values for image. - * @param width pixel width of image. - * @param height pixel height of image. - * @param transform the GeoCoordTransformation for the projection of the - * image. - * @param imageBounds the bounds of the image in the image's coordinate - * system. - */ - public ImageWarp(int[] pix, int width, int height, GeoCoordTransformation transform, DataBounds imageBounds) { - if (pix != null) { - iwidth = width; - iheight = height; - setGeoTrans(transform); - setImageBounds(imageBounds); - pixels = pix; - } - } - - /** - * Create an image warp with some additional transform information. - * - * @param pix ARGB array of pixel values for image. - * @param width pixel width of image. - * @param height pixel height of image. - * @param transform the GeoCoordTransformation for the projection of the - * image. - * @param worldFile the WorldFile describing the image's location. - */ - public ImageWarp(int[] pix, int width, int height, GeoCoordTransformation transform, WorldFile worldFile) { - if (pix != null) { - iwidth = width; - iheight = height; - setGeoTrans(transform); - setImageBounds(worldFile); - pixels = pix; - } - } - - /** - * The pixels used in the OMRaster. - */ - // int[] tmpPixels = new int[0]; - /** - * Return an OMRaster that covers the given projection, with the image - * warped for the projection. - * - * @param p map projection - * @return OMRaster or null if the image isn't within the current - * projection. - */ - public OMRaster getOMRaster(Projection p) { - return getOMRaster(p, null); - } - - /** - * Return an OMRaster that covers the given projection, with the image - * warped for the projection. - * - * @param p map projection - * @param labeler optional OMLabel that will be stored in the raster before - * generation, in case a label is desired. - * @return OMRaster or null if the image isn't within the current - * projection. - */ - public OMRaster getOMRaster(Projection p, Object labeler) { - int[] pixels = getImagePixels(p); - if (pixels != null && projectedImageBounds != null) { - int width = (int) Math.ceil(projectedImageBounds.getWidth()); - int height = (int) Math.ceil(projectedImageBounds.getHeight()); - int x = (int) Math.floor(projectedImageBounds.getMin().getX()); - int y = (int) Math.floor(projectedImageBounds.getMin().getY()); - OMRaster raster = new OMRaster(x, y, width, height, pixels); - if (labeler != null) { - raster.putAttribute(OMGraphic.LABEL, labeler); - } - raster.generate(p); - return raster; - } - - return null; - } - - /** - * Given a projection, return the pixels for an image that will cover the - * projection area. - * - * @param p map projection - * @return int[] of ARGB pixels for an image covering the given projection. - */ - public int[] getImagePixels(Projection p) { - if (pixels != null && p != null) { - - projectedImageBounds = calculateProjectedImageBounds(p); - - if (projectedImageBounds == null) { - // image isn't on the map. - return null; - } - - int projHeight = (int) Math.ceil(projectedImageBounds.getHeight()); - int projWidth = (int) Math.ceil(projectedImageBounds.getWidth()); - - // See if we can reuse the pixel array we have. - - int[] tmpPixels = new int[projWidth * projHeight]; - int numTmpPixels = tmpPixels.length; - logger.fine("tmpPixels[" + numTmpPixels + "]"); - int clear = 0x00000000; - - Point2D ctp = new Point2D.Double(); - Point2D ddll = new Point2D.Double(); - Point2D imageCoord = new Point2D.Double(); - Point2D center = p.getCenter(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(projectedImageBounds.toString()); - } - - int minx = (int) Math.floor(projectedImageBounds.getMin().getX()); - int miny = (int) Math.floor(projectedImageBounds.getMin().getY()); - int maxx = (int) Math.ceil(projectedImageBounds.getMax().getX()); - int maxy = (int) Math.ceil(projectedImageBounds.getMax().getY()); - - // i and j are map window pixel values. - for (int i = minx; i < maxx; i++) { - for (int j = miny; j < maxy; j++) { - - // ix and iy are pixel coordinates of the destination image. - int ix = i - minx; - int iy = j - miny; - - // index into the OMRaster pixel array - int tmpIndex = (ix + (iy * projWidth)); - - if (tmpIndex >= numTmpPixels) { - continue; - } - - ddll = p.inverse(i, j, ddll); - - // If the llp calculated isn't on the map, - // don't bother drawing it. Could be a space - // point in Orthographic projection, for - // instance. - if (ddll.equals(center)) { - p.forward(ddll, ctp); - if (ctp.getX() != i || ctp.getY() != j) { - tmpPixels[tmpIndex] = clear; - continue; - } - } - - if (geoTrans != null) { - geoTrans.forward(ddll.getY(), ddll.getX(), imageCoord); - } else { - imageCoord = ddll; - } - - if (!sourceImageBounds.contains(imageCoord)) { - tmpPixels[tmpIndex] = clear; - continue; - } - - // Find the corresponding pixel location in - // the source image. - int horIndex = (int) Math.round(horOrigin + (imageCoord.getX() / hor_upp)); - int verIndex = (int) Math.round(verOrigin + (imageCoord.getY() / ver_upp)); - - if (horIndex < 0 || horIndex >= iwidth || verIndex < 0 || verIndex >= iheight) { - // pixel not on the source image. This - // happens if the image doesn't cover the - // entire earth. - continue; - } - - int imageIndex = horIndex + (verIndex * iwidth); - - if (imageIndex >= 0 && imageIndex < pixels.length) { - tmpPixels[tmpIndex] = pixels[imageIndex]; - } - } - } - - logger.fine("finished creating image"); - return tmpPixels; - } - - logger.warning("problem creating image, no pixels: " + (pixels == null ? "true" : "false") + ", no projection:" - + (p == null ? "true" : "false")); - - // If you get here, something's not right. - return null; - } - - /** - * Returns the image bounds of the image as it would be warped to the - * provided projection. - * - * @param p Projection the image will be displayed on - * @return DataBounds, in the projected coordinate space. - */ - public DataBounds calculateProjectedImageBounds(Projection p) { - - // This doesn't seem to do anything but slow things down. - // if (geoTrans.equals(LatLonGCT.INSTANCE)) { - // // whole earth - // logger.fine("just using whole screen image"); - // return new DataBounds(0, 0, p.getWidth(), p.getHeight()); - // } - - DataBounds db = null; - if (sourceImageBounds != null) { - int pw = p.getWidth(); - int ph = p.getHeight(); - Point2D min = sourceImageBounds.getMin(); - Point2D max = sourceImageBounds.getMax(); - double x1 = Math.floor(min.getX()); - double y1 = Math.floor(min.getY()); - double x2 = Math.ceil(max.getX()); - double y2 = Math.ceil(max.getY()); - double width = sourceImageBounds.getWidth(); - double height = sourceImageBounds.getHeight(); - - // These are just memory savers, reused for every calculation. - LatLonPoint tmpG = new LatLonPoint.Double(); - Point2D tmpP = new Point2D.Double(); - - db = new DataBounds(); - db.setHardLimits(new DataBounds(0, 0, pw, ph)); - db.add(p.forward(geoTrans.inverse(x1, y1, tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(x1, y2, tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(x2, y1, tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(x2, y2, tmpG), tmpP)); - - double numSplits = 4; - - double xSpacer = width / numSplits; - double ySpacer = height / numSplits; - - for (int i = 1; i < numSplits; i++) { - db.add(p.forward(geoTrans.inverse(Math.ceil(x1 + xSpacer * i), y1, tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(x1, Math.ceil(y1 + ySpacer * i), tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(Math.ceil(x1 + xSpacer * i), y2, tmpG), tmpP)); - db.add(p.forward(geoTrans.inverse(x2, Math.ceil(y1 + ySpacer * i), tmpG), tmpP)); - } - - if (db.getWidth() <= 0 || db.getHeight() <= 0) { - logger.fine("dimensions of data bounds bad, returning null " + db); - return null; - } - - } - return db; - - } - - /** - * Convenience function to get projected image bounds for an image that has - * been warped for a given projection. If you've grabbed the pixel ints, - * this is how you get the projected image bounds for those ints. - * - * @return Rectangle for bounds - */ - public Rectangle getProjectedImageBoundsForLastProjection() { - - DataBounds projImageBounds = projectedImageBounds; - Rectangle rect = null; - - if (projImageBounds != null) { - int minx = (int) Math.floor(projImageBounds.getMin().getX()); - int miny = (int) Math.floor(projImageBounds.getMin().getY()); - int maxx = (int) Math.ceil(projImageBounds.getMax().getX()); - int maxy = (int) Math.ceil(projImageBounds.getMax().getY()); - - rect = new Rectangle(minx, miny, maxx - minx, maxy - miny); - } - return rect; - } - - /** - * Get the pixels from the BufferedImage. If anything goes wrong, returns a - * int[0]. - */ - protected int[] getPixels(Image img, int x, int y, int w, int h) { - int[] pixels = new int[w * h]; - PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w); - try { - pg.grabPixels(); - } catch (InterruptedException e) { - Debug.error("ImageTranslator: interrupted waiting for pixels!"); - return new int[0]; - } - - if ((pg.getStatus() & ImageObserver.ABORT) != 0) { - System.err.println("ImageTranslator: image fetch aborted or errored"); - return new int[0]; - } - - return pixels; - } - - public int getIwidth() { - return iwidth; - } - - public void setIwidth(int iwidth) { - this.iwidth = iwidth; - } - - public int getIheight() { - return iheight; - } - - public void setIheight(int iheight) { - this.iheight = iheight; - } - - public double getHor_dpp() { - return hor_upp; - } - - public void setHor_dpp(double hor_dpp) { - this.hor_upp = hor_dpp; - } - - public double getVer_dpp() { - return ver_upp; - } - - public void setVer_dpp(double ver_dpp) { - this.ver_upp = ver_dpp; - } - - public double getVerOrigin() { - return verOrigin; - } - - public void setVerOrigin(double verOrigin) { - this.verOrigin = verOrigin; - } - - public double getHorOrigin() { - return horOrigin; - } - - public void setHorOrigin(double horOrigin) { - this.horOrigin = horOrigin; - } - - public GeoCoordTransformation getGeoTrans() { - return geoTrans; - } - - public void setGeoTrans(GeoCoordTransformation geoTrans) { - this.geoTrans = geoTrans; - } - - public DataBounds getImageBounds() { - return sourceImageBounds; - } - - public void setImageBounds(DataBounds imageBounds) { - this.sourceImageBounds = imageBounds; - - hor_upp = imageBounds.getWidth() / iwidth; - // need the negative sign because latitudes increase in the opposite - // direction as y pixel values. - boolean yDirUp = imageBounds.isyDirUp(); - - ver_upp = imageBounds.getHeight() / iheight; - if (yDirUp) { - ver_upp *= -1; - } - - // We should be able to just go from the lower left corner of the image - // and find zero from there, the min of both bounds values. - - double leftX = imageBounds.getMin().getX(); - double upperY = yDirUp ? imageBounds.getMax().getY() : imageBounds.getMin().getY(); - - verOrigin = -upperY / ver_upp; // number of Y pixels to origin. - horOrigin = -leftX / hor_upp; // number of X pixels to origin. - - if (logger.isLoggable(Level.FINE)) { - logger.fine("getting image pixels w:" + iwidth + ", h:" + iheight + ", hor upp:" + hor_upp + ", ver upp:" - + ver_upp + ", verOrigin:" + verOrigin + ", horOrigin:" + horOrigin); - logger.fine(imageBounds.toString()); - } - } - - public void setImageBounds(WorldFile worldFile) { - hor_upp = worldFile.getXDim(); - // world file dimensions have direction, negative for going down - ver_upp = worldFile.getYDim(); - - double leftX = worldFile.getX(); - double upperY = worldFile.getY(); - - verOrigin = -worldFile.getY() / ver_upp; // number of Y pixels to - // origin. - horOrigin = -leftX / hor_upp; // number of X pixels to origin. - - sourceImageBounds = new DataBounds(leftX, worldFile.getY() + ver_upp * iheight, leftX + hor_upp * iwidth, - upperY); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("getting image pixels w:" + iwidth + ", h:" + iheight + ", hor upp:" + hor_upp + ", ver upp:" - + ver_upp + ", verOrigin:" + verOrigin + ", horOrigin:" + horOrigin); - logger.fine(sourceImageBounds.toString()); - } - } - - public static void main(String[] args) { - new ImageWarp(new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB), LatLonGCT.INSTANCE, - new DataBounds(25, -90, 180, 90)); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/RibbonMaker.java b/src/core/src/main/java/com/bbn/openmap/omGraphics/util/RibbonMaker.java deleted file mode 100644 index a5b6e18e6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/RibbonMaker.java +++ /dev/null @@ -1,601 +0,0 @@ -package com.bbn.openmap.omGraphics.util; - -import java.util.LinkedList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.geo.GeoArray; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.geo.Ribbon; -import com.bbn.openmap.geo.RibbonIterator; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.MoreMath; - -/** - * The RibbonMaker class takes polygon coordinates and creates another polygon - * from it, a buffer region based on ground distance, around the original poly. - * It assumes that the polygon coordinates are going in a clockwise direction. - * The returned polygon is actually an OMAreaList made up of OMPolys, OMArcs and - * OMLines, depending on the shape of the original polygon. - *

- * - * The RibbonMaker is created from one of the factory methods that designates - * whether the coordinates are radians or decimal degrees. FYI - OMPoly - * coordinates retrieved from the getLatLonArray method are in radians. After - * the RibbonMaker is created, call the method that creates the appropriate - * shape. For now, getOuterRing is your only option. To use: - * - *

- * 
- * llPoints = new double[] { 40.0f, -92.0f, 42.0f, -87.0f, 38.57, -90.825, 37.0f, -89.0f, 35.0f, -94.0f, 40.0f,
- * 		-92.0f };
- * 
- * OMGraphic omg = RibbonMaker.createFromDecimalDegrees(llPoints).getOuterRing(Length.MILE.toRadians(100));
- * 
- * 
- * - * - * @author ddietrick - */ -public class RibbonMaker { - - protected GeoArray geoCoords; - // If a negative distance is passed to getOuterRing, then we'll construct - // this with opposite winding - protected GeoArray geoCoords_reversed = null; - private static final Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.util.RibbonMaker"); - protected final static int STRAIGHT = 0; - protected final static int BENDS_LEFT = -1; - protected final static int BENDS_RIGHT = 1; - protected double bufferLimit = 4.778825E-10; - - protected RibbonMaker(GeoArray gCoords) { - geoCoords = gCoords; - } - - /** - * Create a RibbonMaker from decimal degree coordinates. - * - * @param coords lat,lon,lat,lon in decimal degrees. - * @return RibbonMaker - */ - public static RibbonMaker createFromDecimalDegrees(double[] coords) { - return new RibbonMaker(GeoArray.Double.createFromLatLonDegrees(coords)); - } - - /** - * Create a RibbonMaker from radian coordinates. - * - * @param coords lat,lon,lat,lon in radians. - * @return RibbonMaker - */ - public static RibbonMaker createFromRadians(double[] coords) { - return new RibbonMaker(GeoArray.Double.createFromLatLonRadians(coords)); - } - - /** - * Assumes coords represent a polygon, returns an OMAreaList representing - * buffer zone around the outside of a polygon. - * - * @param dist distance of buffer area, in radians. Use Length to convert. - * @return OMAreaList of a polygon that is a distance away from the - * coordinate polygon's edges. - */ - public OMAreaList getOuterRing(double dist) { - OMAreaList ret = new OMAreaList(); - - if (Math.abs(dist) <= bufferLimit) { - return ret; - } - - GeoArray localGeoCoords = this.geoCoords; - if (dist < 0) { - // Construct a version of this shape wound the other way - dist = -dist; - if (geoCoords_reversed == null) { - double[] reversed = new double[2 * geoCoords.getSize()]; - for (int i = geoCoords.getSize() - 1; i >= 0; i--) { - Geo thisGeo = geoCoords.get(geoCoords.getSize() - i - 1); - reversed[2 * i] = thisGeo.getLatitudeRadians(); - reversed[2 * i + 1] = thisGeo.getLongitudeRadians(); - } - geoCoords_reversed = GeoArray.Double.createFromLatLonRadians(reversed); - } - localGeoCoords = geoCoords_reversed; - } - - int numCoords = localGeoCoords.getSize(); - - if (numCoords >= 3) { - - Geo g1 = localGeoCoords.get(0); - Geo g2 = localGeoCoords.get(1); - Geo g3 = localGeoCoords.get(2); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - - for (int i = 3; i < numCoords; i++) { - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(i); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - } - - // test, and close it off if needed - if (!localGeoCoords.get(0).equals(localGeoCoords.get(numCoords - 1))) { - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(0); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - } - - // Now round out the first and last segment, centering on the first - // coordinate - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(1); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - - } - return ret; - } - - /** - * Takes a corner represented by the three geos, and adds OMGraphics to the - * OMAreaList depending on which way the corner bends - for right turns, - * it'll add an OMLine, OMArc and OMLine. The OMLines will go from half the - * distance of the legs to the rounded corner. The left turn will have a - * polygon added. - * - * @param g1 point 1 - * @param g2 point 2 - * @param g3 point 3 - * @param dist buffer distance in radians - * @param ret OMAreaList to add OMGraphics to. - */ - protected void handlePointsForOuterRing(Geo g1, Geo g2, Geo g3, double dist, OMAreaList ret) { - int bend = bends(g1, g2, g3); - - Geo gret = g3; - RibbonIterator leg1 = new RibbonIterator(g1, g2, dist); - OMPoly poly1 = getHalfPoly(leg1, Ribbon.LEFT, false); - - RibbonIterator leg2 = new RibbonIterator(g2, g3, dist); - OMPoly poly2 = getHalfPoly(leg2, Ribbon.LEFT, true); - - // Oh dear... - if (poly1 == null || poly2 == null) { - return; - } - - if (bend == STRAIGHT || g2.equals(g3)) { - ret.add(poly1); - ret.add(poly2); - } else { - if (bend == BENDS_LEFT) { - // short, need to find intersection of two legs and remove - // points - // from polys to only go to intersection - - double dg12 = g1.distance(g2); - double dg23 = g2.distance(g3); - double legTestDist = dist * 2; - - if (dg12 < legTestDist || dg23 < legTestDist) { - addShortLegPolyForIntersection(g1, g2, g3, Ribbon.LEFT, dist, ret); - } else { - addPolyForIntersection(poly1, poly2, dist, ret); - } - - } else { - OMGraphic omp = getPushbackPoly(poly1, dist); - if (omp != null) { - ret.add(omp); - } - // Add OMArc in the middle, rounding around a corner - OMGraphic oma = getArc(g2, poly1, poly2); - if (oma != null) { - ret.add(oma); - } - omp = getPushbackPoly(poly2, dist); - if (omp != null) { - ret.add(omp); - } - } - } - - } - - /** - * Method that determines which way the angle between the three points - * bends. - * - * @param g1 - * @param g2 - * @param g3 - * @return STRAIGHT if no bend, BENDS_LEFT if bends less than PI, - * BENDS_RIGHT if bends more than PI. - */ - protected int bends(Geo g1, Geo g2, Geo g3) { - double bend = g1.crossNormalize(g2).distance(g3) - (Math.PI / 2.0); - - if (Math.abs(bend) < .0001) { - return STRAIGHT; // essentially straight - } else { - if (bend < 0) { - return BENDS_LEFT; - } - } - - return BENDS_RIGHT; - } - - /** - * Checks to see if a point is too close to any side of the original - * polygon. - * - * @param pnt - * @param distance - * @return true if is too close and should not be added to the buffer - * polygon. - */ - protected boolean tooClose(Geo pnt, double distance) { - return Intersection.isPointNearPoly(pnt, geoCoords, distance - bufferLimit); - } - - /** - * Takes a poly that's going to be added to the buffer and removes any - * points that may be too close to the original poly. - * - * @param omp the buffer poly to be added later - * @param dist the distance all points should be from the original - * @return the OMGraphic with good points. - */ - protected OMGraphic getPushbackPoly(OMPoly omp, double dist) { - double[] coords = omp.getLatLonArray(); - List results = new LinkedList(); - for (int i = 0; i < coords.length - 2; i += 2) { - Geo g = new Geo(coords[i], coords[i + 1], false); - if (!tooClose(g, dist)) { - results.add(g); - } - } - - if (results.size() == 1) { - results.add(new Geo(results.get(0))); - } - - if (results.size() > 1) { - return getOMPolyFromGeos(results); - } - - return null; - - } - - /** - * Called when it's known that one of the legs between the corner is smaller - * than the buffer depth. Does some extra work to figure out what points - * should be added to the buffer. - * - * @param g1 point 1 - * @param g2 point 2, the corner - * @param g3 point 3 - * @param ribbonSide which side of the ribbon should be calculated. - * @param dist the distance the buffer should be from the legs - * @param ret the OMGraphicList to add the resulting poly to. - */ - protected void addShortLegPolyForIntersection(Geo g1, Geo g2, Geo g3, int ribbonSide, double dist, OMAreaList ret) { - - /** - * We need to do some extra work here. Since one of the legs is shorter - * than 2*dist of the buffer, half of the buffer polygon won't reach the - * intersection point between the two legs. So, we need to recalculate - * the polys so the represent the entire legs, in order to find the - * intersection point. - * - * Once we have that, we can go back to the half polygons, and test for - * that intersection point against each little segment. If any of those - * points are further away than buffer distance to the opposite poly, - * they should be included on the polygon added to the list. If a point - * is inside that distance, it should be disregarded. If there is only - * one point (i.e. the original intersection point), then a duplicate - * intersection point should be added, so the OMAreaList will handle it - * properly. - */ - List results = new LinkedList(); - RibbonIterator leg1 = new RibbonIterator(g1, g2, dist); - OMPoly fullPoly1 = getPoly(leg1, ribbonSide); - - RibbonIterator leg2 = new RibbonIterator(g2, g3, dist); - OMPoly fullPoly2 = getPoly(leg2, ribbonSide); - - if (fullPoly1 == null || fullPoly2 == null) { - return; - } - - // Intersection is the point on both polys that is buffer distance away - // from corner - Geo intersection = getPolyIntersection(fullPoly1, fullPoly2); - - if (intersection == null) { - // GAAH! This shouldn't happen - return; - } - - leg1 = new RibbonIterator(g1, g2, dist); - OMPoly halfPoly1 = getHalfPoly(leg1, ribbonSide, false); - if (halfPoly1 != null) { - GeoArray geoPoly2 = GeoArray.Double.createFromLatLonRadians(fullPoly2.getLatLonArray()); - - double[] leg1Coords = halfPoly1.getLatLonArray(); - for (int i = 0; i < leg1Coords.length - 1; i += 2) { - Geo pnt = new Geo(leg1Coords[i], leg1Coords[i + 1], false); - - if (!tooClose(pnt, dist)) { - results.add(pnt); - } - } - - if (!tooClose(intersection, dist)) { - results.add(intersection); - } - } - - leg2 = new RibbonIterator(g2, g3, dist); - OMPoly halfPoly2 = getHalfPoly(leg2, ribbonSide, true); - if (halfPoly2 != null) { - GeoArray geoPoly1 = GeoArray.Double.createFromLatLonRadians(fullPoly1.getLatLonArray()); - - double[] leg2Coords = halfPoly2.getLatLonArray(); - for (int i = 0; i < leg2Coords.length - 1; i += 2) { - Geo pnt = new Geo(leg2Coords[i], leg2Coords[i + 1], false); - - if (!tooClose(pnt, dist)) { - results.add(pnt); - } - } - } - - if (results.size() == 1 && !tooClose(intersection, dist)) { - results.add(intersection); - } - - if (results.size() > 1) { - ret.add(getOMPolyFromGeos(results)); - } - } - - /** - * Just return the point where the two polygons cross. - * - * @param poly1 - * @param poly2 - * @return null if no point found. - */ - protected Geo getPolyIntersection(OMPoly poly1, OMPoly poly2) { - double[] p1Coords = poly1.getLatLonArray(); - double[] p2Coords = poly2.getLatLonArray(); - - Geo a1, a2, b1, b2; - Geo intersect = null; - int index1 = 0, index2 = 0; - for (; index2 + 3 < p2Coords.length; index2 += 2) { - b1 = new Geo(p2Coords[index2], p2Coords[index2 + 1], false); - b2 = new Geo(p2Coords[index2 + 2], p2Coords[index2 + 3], false); - - if (intersect == null) { - for (; index1 + 3 < p1Coords.length; index1 += 2) { - - a1 = new Geo(p1Coords[index1], p1Coords[index1 + 1], false); - a2 = new Geo(p1Coords[index1 + 2], p1Coords[index1 + 3], false); - - intersect = Intersection.segmentsIntersect(a1, a2, b1, b2); - - if (intersect != null) { - return intersect; - } - } - } - } - - return intersect; - } - - /** - * Converts Vector of Geos to an OMPoly with linetype great_circle. Assumes - * that the List has valid coordinates on it. Does not do a closeness check - * to the original poly, expected that's been done. - * - * @param geos a set of coordinates - * @return OMPoly - */ - protected OMPoly getOMPolyFromGeos(List geos) { - double[] tmpCoords = new double[geos.size() * 2]; - int index = 0; - for (Geo geo : geos) { - tmpCoords[index++] = geo.getLatitudeRadians(); - tmpCoords[index++] = geo.getLongitudeRadians(); - } - - return new OMPoly(tmpCoords, OMPoly.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - } - - /** - * Called to handle BENDS_LEFT, concave corners. RuntimeException is thrown - * when one of the legs is much shorter than the other and the mid-point is - * still in the buffer of one of the legs. In that special case, the - * intersection point is not found. - * - * @param poly1 - * @param poly2 - * @param ret - */ - protected void addPolyForIntersection(OMPoly poly1, OMPoly poly2, double dist, OMAreaList ret) { - double[] p1Coords = poly1.getLatLonArray(); - double[] p2Coords = poly2.getLatLonArray(); - - List results = new LinkedList(); - - Geo a1, a2, b1, b2; - Geo intersect = null; - int index1 = 0, index2 = 0; - for (; index2 + 3 < p2Coords.length; index2 += 2) { - b1 = new Geo(p2Coords[index2], p2Coords[index2 + 1], false); - b2 = new Geo(p2Coords[index2 + 2], p2Coords[index2 + 3], false); - - if (intersect == null) { - for (; index1 + 3 < p1Coords.length; index1 += 2) { - - a1 = new Geo(p1Coords[index1], p1Coords[index1 + 1], false); - a2 = new Geo(p1Coords[index1 + 2], p1Coords[index1 + 3], false); - - intersect = Intersection.segmentsIntersect(a1, a2, b1, b2); - - if (!tooClose(a1, dist)) { - results.add(a1); - } - - if (intersect != null) { - if (!tooClose(intersect, dist)) { - results.add(intersect); - } - break; - } - } - } - - if (intersect != null && !tooClose(b2, dist)) { - results.add(b2); - } - } - - if (results.size() > 1) { - ret.add(getOMPolyFromGeos(results)); - } - } - - /** - * Given a RibbonIterator created from two Geos, create a poly from half of - * that buffer path. Points are not checked for closeness to original poly. - * - * @param rIterator RibbonIterator for one of the legs of corner - * @param side which RibbonIterator side - * @param first which half you want, true for first part - * @return OMPoly that represents half of the buffered path. - */ - protected OMPoly getHalfPoly(RibbonIterator rIterator, int side, boolean first) { - List results = new LinkedList(); - for (Ribbon rib : rIterator) { - Geo g = rib.get(side); - results.add(g); - } - - int numCoords = results.size(); - - if (numCoords > 0) { - - int startingIndex = 0; - int copyLength = numCoords / 2; - - if (numCoords % 2 == 0) { - if (!first) { - startingIndex = copyLength; // middle - } - } else { - if (!first) { - startingIndex = copyLength; - } - copyLength++; - } - - List newGeoCoords = new LinkedList(); - for (int index = 0; index < copyLength; index++) { - Geo g = results.get(startingIndex + index); - newGeoCoords.add(g); - } - - return getOMPolyFromGeos(newGeoCoords); - } - return null; - } - - /** - * Given a RibbonIterator created from two Geos, create a poly from that - * buffer path. - * - * @param rIterator RibbonIterator for one of the legs of corner - * @param side which RibbonIterator side - * @return OMPoly that represents buffered path between geos. - */ - protected OMPoly getPoly(RibbonIterator rIterator, int side) { - List bufferCoords = new LinkedList(); - for (Ribbon rib : rIterator) { - bufferCoords.add(rib.get(side)); - } - - if (bufferCoords.size() > 1) { - return getOMPolyFromGeos(bufferCoords); - } - return null; - } - - /** - * Given two polylines, with the end point of poly1 being the same distance - * from a point as the starting point of poly2, create an arc that connects - * them. - * - * @param gc point - * @param poly1 polyline where the last end point is used - * @param poly2 polyline where the first end point is used. - * @return OMArc - */ - public OMGraphic getArc(Geo gc, OMPoly poly1, OMPoly poly2) { - - double[] poly1Coords = poly1.getLatLonArray(); - Geo pt1 = new Geo(poly1Coords[poly1Coords.length - 2], poly1Coords[poly1Coords.length - 1], false); - double radAngle1 = gc.azimuth(pt1); - - double[] poly2Coords = poly2.getLatLonArray(); - Geo pt2 = new Geo(poly2Coords[0], poly2Coords[1], false); - double radAngle2 = gc.azimuth(pt2); - - double dist = gc.distance(pt1); - - if (radAngle2 < radAngle1) { - radAngle2 += MoreMath.TWO_PI_D; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine( - new StringBuilder("Making arg starting at ").append(Length.DECIMAL_DEGREE.fromRadians(radAngle1)) - .append(", ").append(Length.DECIMAL_DEGREE.fromRadians(radAngle2 - radAngle1)).toString()); - } - - List points = new LinkedList(); - double inc = Length.DECIMAL_DEGREE.toRadians(2.0); - double angle = radAngle1 + inc; - - while (angle < radAngle2 - inc) { - Geo g = gc.offset(dist, angle); - if (!tooClose(g, dist)) { - points.add(g); - } - angle += inc; - } - - return getOMPolyFromGeos(points); - // return new OMArc(gc.getLatitude(), gc.getLongitude(), dist, - // Length.RADIAN, 100, Length.DECIMAL_DEGREE.fromRadians(radAngle1), - // Length.DECIMAL_DEGREE.fromRadians(radAngle2 - radAngle1)); - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/package.html b/src/core/src/main/java/com/bbn/openmap/omGraphics/util/package.html deleted file mode 100644 index b9aba29c0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/omGraphics/util/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains simple utility classes used specifically for OMGraphics. - diff --git a/src/core/src/main/java/com/bbn/openmap/package.html b/src/core/src/main/java/com/bbn/openmap/package.html deleted file mode 100644 index b18716d69..000000000 --- a/src/core/src/main/java/com/bbn/openmap/package.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The com.bbn.openmap package contains the core OpenMap classes. The -classes in this package provide the main map management functionality -of OpenMap.

- -The main mapping window is the MapBean, which is a JComponent. It -contains Layers, each layer providing a thematic overlay to -the map. There are three flavors of MapBeans: MapBean, BufferedMapBean, -and BufferedLayerMapBean. You should use the BufferedLayerMapBean, it -is an extension of BufferedMapBean with the added feature of putting -'background' layers into a single buffer at the back of the map, -and controlling map paints to occur when those layers are -ready. This feature prevents the map from having a flashing effect -observed when slower layers with more things on the map paint after -faster layers with less. The MapBeanRepaintPolicy components let you -make modifications to the MapBean rendering - adding anti-aliasing, etc. -

- -The other main component is the MapHandler. The MapHandler is an -extended BeanContext, and can be thought of as the widget holding to -all the components that make up a map. As a BeanContext, the -MapHandler keeps a handle to any object that is put in it, providing -access to all components of the map. Any component can be added to -the MapHandler. Any component added to the MapHandler that is a -BeanContextMembershipListener will be automatically notified when any -component is added or removed from the MapHandler. See the -MapHandlerChild abstract class for more information about creating a -class that uses the MapHandler to locate other needed components.

- -The extensions to the MapHandler that separate it from a regular -BeanContext really center on the notion that some components can -implement the SoloMapComponent interface. SoloMapComponents classes -are objects where only one instance of them can be found in a -MapHandler. The SoloMapComponentPolicy assigned to the MapHandler -lets it know what to do when a duplicate instance of a -SoloMapComponent is given to the MapHandler - either rejection or -replacement are the only options currently provided.

- -Other components of real interest are: -

    -
  • LayerHandler - manages all layers for the map, those active or -not. -
  • MouseDelegator - manages how MouseEvents over the map are directed -to layers or other components. -
  • PropertyConsumer - components that can be configured using Java -Properties. The OpenMap application uses a properties file to configure -its components, allowing you to add or change components and their -behavior without having to update code. -
  • PropertyHandler - uses properties to configure the application -
  • InformationDelegator - an object that other components can use to -provide information to the user. -
  • OMComponent - a base class for classes that are PropertyConsumers -and also use the MapHandler to locate other components. -
  • ProjectionPainter - interface for objects that want to draw on top -of the map after the layers have been rendered. Useful for quickly rendering -things on top of the map. -
- - - diff --git a/src/core/src/main/java/com/bbn/openmap/proj/AspectRatioProjection.java b/src/core/src/main/java/com/bbn/openmap/proj/AspectRatioProjection.java deleted file mode 100644 index 0e3131817..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/AspectRatioProjection.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -/** - * A Projection that wraps another projection, but stretch the image to another - * aspect ratio. - *

- * The motivation for this projection is to support the following clause in wms - * 1.1.1. - *

- * OGC 01-068r3 (wms 1.1.1) 7.2.3.8. "In the case where the aspect ratio of the - * BBOX and the ratio width/height are different, the WMS shall stretch the - * returned map so that the resulting pixels could themselves be rendered in the - * aspect ratio of the BBOX" - * - * @author halset - */ -public class AspectRatioProjection extends GeoProj { - - private GeoProj wrappedProjection; - - private float xFactor; - - private float yFactor; - - private float halfWidth; - - private float halfWrappedWidth; - - private float halfHeight; - - private float halfWrappedHeight; - - private boolean xHasFactor; - - private boolean yHasFactor; - - /** - * Constructor that takes a projection and the new width/height. - * - * @param proj a projection to wrap - * @param w a int with the new width - * @param h a int with the new height - */ - public AspectRatioProjection(GeoProj proj, int w, int h) { - super(proj.getCenter(), proj.getScale(), w, h); - wrappedProjection = proj; - xHasFactor = proj.getWidth() != w; - yHasFactor = proj.getHeight() != h; - computeParameters(); - } - - private Point2D fromWrapped(Point2D pt) { - pt.setLocation(xFromWrapped((float) pt.getX()), - yFromWrapped((float) pt.getY())); - return pt; - } - - private float xFromWrapped(float x) { - if (!xHasFactor) - return x; - return ((x - halfWrappedWidth) * xFactor + halfWidth); - } - - private float yFromWrapped(float y) { - if (!yHasFactor) - return y; - return ((y - halfWrappedHeight) * yFactor + halfHeight); - } - - private float xToWrapped(float x) { - if (!xHasFactor) - return x; - return ((x - halfWidth) / xFactor + halfWrappedWidth); - } - - private float yToWrapped(float y) { - if (!yHasFactor) - return y; - return ((y - halfHeight) / yFactor + halfWrappedHeight); - } - - protected ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - ArrayList stuff = wrappedProjection._forwardPoly(rawllpts, - ltype, - nsegs, - isFilled); - int size = stuff.size(); - for (int i = 0; i < size; i += 2) { - float[] xpts = stuff.get(i); - if (xHasFactor) { - for (int j = 0; j < xpts.length; j++) - xpts[j] = xFromWrapped(xpts[j]); - } - if (yHasFactor) { - float[] ypts = stuff.get(i + 1); - for (int j = 0; j < ypts.length; j++) - ypts[j] = yFromWrapped(ypts[j]); - } - } - return stuff; - } - - protected void computeParameters() { - if (wrappedProjection != null) { - wrappedProjection.computeParameters(); - xFactor = (float) ((double) getWidth() / (double) wrappedProjection.getWidth()); - yFactor = (float) ((double) getHeight() / (double) wrappedProjection.getHeight()); - halfWidth = (float) getWidth() / 2.0F; - halfHeight = (float) getHeight() / 2.0F; - halfWrappedWidth = (float) wrappedProjection.getWidth() / 2.0F; - halfWrappedHeight = (float) wrappedProjection.getHeight() / 2.0F; - } - } - - public void drawBackground(Graphics2D g, Paint p) { - wrappedProjection.drawBackground(g, p); - } - - public void drawBackground(Graphics g) { - wrappedProjection.drawBackground(g); - } - - public double normalizeLatitude(double lat) { - if (wrappedProjection == null) { - if (lat > NORTH_POLE) { - return NORTH_POLE; - } else if (lat < SOUTH_POLE) { - return SOUTH_POLE; - } - return lat; - } - return wrappedProjection.normalizeLatitude(lat); - } - - @Override - public Point2D forward(Point2D llp, Point2D pt) { - return fromWrapped(wrappedProjection.forward(llp, pt)); - } - - @Override - public Point2D forward(double lat, double lon, Point2D pt) { - return fromWrapped(wrappedProjection.forward(lat, lon, pt)); - } - - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, - float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - boolean r = wrappedProjection.forwardRaw(rawllpts, - rawoff, - xcoords, - ycoords, - visible, - copyoff, - copylen); - int end = copylen + copyoff; - for (int i = copyoff; i < end; i++) { - if (xHasFactor) - xcoords[i] = xFromWrapped(xcoords[i]); - if (yHasFactor) - ycoords[i] = yFromWrapped(ycoords[i]); - } - return r; - } - - public Point2D getLowerRight() { - return wrappedProjection.getLowerRight(); - } - - public Point2D getUpperLeft() { - return wrappedProjection.getUpperLeft(); - } - - @Override - public Point2D inverse(Point2D point, Point2D llpt) { - return inverse(point.getX(), point.getY(), llpt); - } - - @Override - protected ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - ArrayList stuff = wrappedProjection._forwardPoly(rawllpts, - ltype, - nsegs, - isFilled); - int size = stuff.size(); - for (int i = 0; i < size; i += 2) { - float[] xpts = stuff.get(i); - if (xHasFactor) { - for (int j = 0; j < xpts.length; j++) - xpts[j] = xFromWrapped(xpts[j]); - } - if (yHasFactor) { - float[] ypts = stuff.get(i + 1); - for (int j = 0; j < ypts.length; j++) - ypts[j] = yFromWrapped(ypts[j]); - } - } - return stuff; - } - - @Override - public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian) { - return fromWrapped(wrappedProjection.forward(lat, lon, pt, isRadian)); - } - - @Override - public Point2D inverse(double x, double y, Point2D llpt) { - return wrappedProjection.inverse(xToWrapped((float) x), - yToWrapped((float) y), - llpt); - } - - public boolean isPlotable(double lat, double lon) { - return wrappedProjection.isPlotable(lat, lon); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/AziDist.java b/src/core/src/main/java/com/bbn/openmap/proj/AziDist.java deleted file mode 100644 index b8c7fe2fd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/AziDist.java +++ /dev/null @@ -1,33 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/AziDist.java,v $ -// $RCSfile: AziDist.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * Structure contains azimuth and distance values. Distance units are - * determined by the operation. - */ -public class AziDist { - public double faz;// forward azimuth - public double baz;// backward azimuth - public double distance;// distance -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Azimuth.java b/src/core/src/main/java/com/bbn/openmap/proj/Azimuth.java deleted file mode 100644 index 0602cc3cd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Azimuth.java +++ /dev/null @@ -1,1322 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Azimuth.java,v $ -// $RCSfile: Azimuth.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Base of all azimuthal projections. - *

- * - * @see Orthographic - * @see Gnomonic - */ -public abstract class Azimuth extends GeoProj { - - // encapsules extra variables to forward() method call - protected static class AzimuthVar { - // invalid_forward - flag value marks a forward() of a point - // which - // is not visible. - boolean invalid_forward = false; // last forward() was - // invalid - // current_azimuth - azimuth (direction from center) of last - // invalid - // forwarded point. - double current_azimuth = Double.NaN; // azimuth of last - // forward - // extra slot - int index; - } - - // HACK - final static float ACCEPTABLE_AZ = ProjMath.degToRad(5); - - protected transient Point world; // world width and height in pixels. - - /** - * Traverse poly vertices in clockwise order. - */ - protected boolean clockwise = true; - - /** - * Construct an azimuthal projection. - *

- * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public Azimuth(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - } - - /** - * Return stringified description of this projection. - *

- * - * @return String - * @see Projection#getProjectionID - */ - public String toString() { - return " world(" + world.x + "," + world.y + ") " + super.toString(); - } - - protected void init() { - super.init(); - - // minscale is the minimum scale allowable (before integer - // wrapping can occur) - minscale = Math.ceil((2 * planetPixelRadius) / (int) Integer.MAX_VALUE); - if (minscale < 1) - minscale = 1; - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- * - */ - protected void computeParameters() { - - if (scale < minscale) - scale = minscale; - - // maxscale = scale at which a world hemisphere fits in the - // window - maxscale = (width < height) ? (planetPixelRadius * 2) / width : (planetPixelRadius * 2) / height; - if (maxscale < minscale) { - maxscale = minscale; - } - if (scale > maxscale) { - scale = maxscale; - } - scaled_radius = planetPixelRadius / scale; - - if (world == null) - world = new Point(0, 0); - - // width of the world in pixels at current scale. We see only - // one hemisphere. - world.x = (int) ((planetPixelRadius * 2) / scale); - - // calculate cutoff scale for XWindows workaround - XSCALE_THRESHOLD = (int) ((planetPixelRadius * 2) / 64000);// fudge - // it a - // little - // bit - - if (Debug.debugging("proj")) { - Debug.output("Azimuth.computeParameters(): " + "world.x = " + world.x + " XSCALE_THRESHOLD = " - + XSCALE_THRESHOLD); - } - } - - /** - * Toggle clockwise traversal of poly vertices. - * - * @param value boolean - */ - public void setClockwiseTraversal(boolean value) { - clockwise = value; - } - - /** - * Get poly-traversal setting (clockwise or counter-clockwise). - * - * @return boolean - */ - public boolean isClockwiseTraversal() { - return clockwise; - } - - /** - * Forward project a point. Wrapper around Azimuth-specific forwarding. - */ - public final Point2D forward(double lat, double lon, Point2D pt, boolean isRadian) { - if (!isRadian) { - lat = Math.toRadians(lat); - lon = Math.toRadians(lon); - } - return _forward(normalizeLatitude(lat), wrapLongitude(lon), pt, null); - } - - /** - * Forward project a point. If the point is not within the viewable - * hemisphere, return flags in AzimuthVar variable if specified. - * - * @param lat latitude in radians - * @param lon longitude in radians - * @param pt Point2D - * @param azVar AzimuthVar or null - * @return Point2D pt - */ - protected abstract Point2D _forward(double lat, double lon, Point2D pt, AzimuthVar azVar); - - /** - * Pan the map/projection. We check for N,S,E,W,SE,NE,SW,NW and manage those - * directions a bit, so that going back and forth between them will put the - * map back where it was, instead of inching toward the equator. For other - * Az values, we go to the inverse of the x, y point in that direction - * (superclass behavior). - *

    - *
  • pan(180, c) pan south - *
  • pan(-90, c) pan west - *
  • pan(0, c) pan north - *
  • pan(90, c) pan east - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - public void pan(float Az) { - if (MoreMath.approximately_equal(Math.abs(Az), 180f, 0.01f)) { - _panS(); - } else if (MoreMath.approximately_equal(Az, -135f, 0.01f)) { - _panSW(); - } else if (MoreMath.approximately_equal(Az, -90f, 0.01f)) { - _panW(); - } else if (MoreMath.approximately_equal(Az, -45f, 0.01f)) { - _panNW(); - } else if (MoreMath.approximately_equal(Az, 0f, 0.01f)) { - _panN(); - } else if (MoreMath.approximately_equal(Az, 45f, 0.01f)) { - _panNE(); - } else if (MoreMath.approximately_equal(Az, 90f, 0.01f)) { - _panE(); - } else if (MoreMath.approximately_equal(Az, 135f, 0.01f)) { - _panSE(); - } else { - super.pan(Az); - } - } - - /** - * Pan the map northwest. - */ - protected void _panNW() { - if (overNorthPole()) { - setCenter(NORTH_POLE, centerX - (Math.PI / 4), true); - } else { - LatLonPoint to = new LatLonPoint.Double(); - inverse((int) (width / 2), 0, to); - double lat = to.getRadLat();// center - - inverse(0, 0, to); - // lat - to.setLatitude(ProjMath.radToDeg(lat)); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, -(Math.PI / 4)); - } - setCenter(to); - } - } - - /** - * Pan the map north. - */ - protected void _panN() { - if (overNorthPole()) { - setCenter(NORTH_POLE, centerX, true); - } else { - LatLonPoint to = (LatLonPoint) inverse((int) (width / 2), 0); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLat(), centerY, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, 0); - } - setCenter(to); - } - } - - /** - * Pan the map northeast. - */ - protected void _panNE() { - if (overNorthPole()) { - setCenter(NORTH_POLE, centerX + (Math.PI / 4), true); - } else { - LatLonPoint to = new LatLonPoint.Double(); - inverse((int) (width / 2), 0, to); - double lat = to.getRadLat();// center - - inverse(width - 1, 0, to); - - // lat - to.setLatitude(ProjMath.radToDeg(lat)); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, (Math.PI / 4)); - } - setCenter(to); - } - } - - /** - * Pan the map east. - */ - protected void _panE() { - // when we're over the poles, then pan by 45 degrees each time - if (overNorthPole() || overSouthPole()) - setCenter(centerY, centerX + (Math.PI / 4), true); - // otherwise approximate something good - else { - LatLonPoint to = (LatLonPoint) inverse(new Point(width - 1, (int) (height / 2))); - to.setLatitude(ProjMath.radToDeg(centerY));// keep - // the - // same - // latitude - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, (Math.PI / 2)); - } - setCenter(to); - } - } - - /** - * Pan the map southeast. - */ - protected void _panSE() { - if (overSouthPole()) { - setCenter(SOUTH_POLE, centerX + (Math.PI / 4), true); - } else { - - LatLonPoint to = new LatLonPoint.Double(); - inverse((int) (width / 2), height - 1, to); - double lat = to.getRadLat();// center - - inverse(width - 1, height - 1, to); - - // lat - to.setLatitude(ProjMath.radToDeg(lat)); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, (0.75 * Math.PI)); - } - setCenter(to); - } - } - - /** - * Pan the map south. - */ - protected void _panS() { - if (overSouthPole()) { - setCenter(SOUTH_POLE, centerX, true); - } else { - LatLonPoint to = (LatLonPoint) inverse((int) (width / 2), height); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLat(), centerY, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, Math.PI); - } - setCenter(to); - } - } - - /** - * Pan the map southwest. - */ - protected void _panSW() { - if (overSouthPole()) { - setCenter(SOUTH_POLE, centerX - (Math.PI / 4.0), true); - } else { - - LatLonPoint to = new LatLonPoint.Double(); - inverse((int) (width / 2), height - 1, to); - double lat = to.getRadLat();// center - - inverse(0, height - 1, to); - - // lat - to.setLatitude(ProjMath.radToDeg(lat)); - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, (-0.75 * Math.PI)); - } - setCenter(to); - } - } - - /** - * Pan the map west. - */ - protected void _panW() { - // when we're over the poles, then pan by 45 degrees each time - if (overNorthPole() || overSouthPole()) - setCenter(centerY, centerX - (Math.PI / 4), true); - // otherwise approximate something good - else { - LatLonPoint to = (LatLonPoint) inverse(new Point(0, (int) (height / 2))); - // keep the same latitude - to.setLatitude(ProjMath.radToDeg(centerY)); - - // check for large planet - if (MoreMath.approximately_equal(to.getRadLon(), centerX, 0.0001f)) { - // cast out to hemisphere edge - to = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, -MoreMath.HALF_PI_D); - } - setCenter(to); - } - } - - /** - * Checks if the north pole is visible on the screen. - *

- * - * @return boolean - */ - public boolean overNorthPole() { - return overPoint(NORTH_POLE, 0f); - } - - /** - * Checks if the south pole is visible on the screen. - *

- * - * @return boolean - */ - public boolean overSouthPole() { - return overPoint(SOUTH_POLE, 0f); - } - - /** - * Checks if the point is visible on the screen. - * - * @param lat latitude in radians - * @param lon longitude in radians - * @return boolean true if visible, false if not - */ - public boolean overPoint(float lat, float lon) { - AzimuthVar azVar = new AzimuthVar(); - Point2D pt = _forward(lat, lon, new Point2D.Float(), azVar); - if (azVar.invalid_forward) { - return false; - } - if ((pt.getX() < 0) || (pt.getX() > width) || (pt.getY() < 0) || (pt.getY() > height)) { - return false; - } - return true; - } - - /** - * Forward project a lat/lon Poly. This is a complex method. Please read the - * in-code documentation for an explanation of the algorithm. - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return List float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - // Idea: - // The azimuthal projection family (mostly) shows one - // hemisphere only. - // A Poly can be projected in 3 ways: - // 1) fully inside hemisphere - // 2) fully outside hemisphere - // 3) partially inside/outside hemisphere - // Case 3 is the hard one to deal with. A Poly which is - // partially inside will be projected into 1 or more - // subsections. If the poly isn't filled, we can just - // return the subsections. If the poly is filled, then - // we need to add points that lie on the hemisphere edge - // in order to complete the polygon. - // - // Algorithm: - // * Iterate through rawllpts, projecting as we go. If - // we see any inside->outside and outside->inside - // transitions, mark them and save them. - // - // * Return all projected points if case 1, or nothing - // if case 2. - // - // * For case 3: - // - // * If poly isn't filled, just return the - // subsections determined while iterating. For - // example return four projected subsections in - // the following ways: - // - // - // AA - // /--------------------------------------------\ - // | 1 |xx| 2 |xxxx| 3 |xx| 4 | - // \--------------------------------------------/ - // ^---^ ^---------^ ^------^ ^----^ - // - // BB - // /--------------------------------------------\ - // |xx| 1 |x| 2 |xxxxx| 3 |xx| 4 |x| - // \--------------------------------------------/ - // ^--^ ^-------^ ^-----^ ^----^ - // - // CC - // /--------------------------------------------\ - // |x| 1 |xx| 2 |xxxx| 3 |xxxx| 4 | - // \--------------------------------------------/ - // ^--^ ^-------^ ^-----^ ^-----^ - // - // DD - // /--------------------------------------------\ - // | 1 |xxx| 2 |xxxxx| 3 |xx| 4 |x| - // \--------------------------------------------/ - // ^---^ ^-------^ ^-----^ ^----^ - // - // * Otherwise poly is filled. There is a - // special case of AA above where we need to wrap - // the vertices so that the coloring is done - // correctly for 3 subsections: - // - // AA with wrap - // /--------------------------------------------\ - // | 1b |xx| 2 |xxxx| 3 |xx| 1a | - // \--------------------------------------------/ - // ----^ ^---------^ ^------^ ^----- - // - // We wrap by copying the finishing 1b section to - // the back: - // - // /--------------------------------------------+-----\ - // | 1b |xx| 2 |xxxx| 3 |xx| 1a | 1b | - // \--------------------------------------------+-----/ - // ^---------^ ^------^ ^----------^ - // - // * For filled polys, we also need to add vertices along - // the horizon edge in order to make sure the rendering - // is done properly along the horizon edge. The - // interested hacker (the one who's still reading this - // comment at this point!) should refer to the method - // following this one for a description of the caveats - // and the extra processing needed for filled polys. - // - - boolean DEBUG = Debug.debugging("proj"); - - int len = rawllpts.length >>> 1; - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - - int invalid_count = 0;// number of invalid points - boolean curr_invalid, prev_invalid = false;// previous - // invalid - // forward - Point temp = new Point(); - AzimuthVar az_first = null, az_save = null, azVar = new AzimuthVar(); - ArrayList sections = new ArrayList(128); - float[] x_, xs = new float[len]; - float[] y_, ys = new float[len]; - - // handle first point - _forward(rawllpts[0], rawllpts[1], temp, azVar); - xs[0] = temp.x; - ys[0] = temp.y; - prev_invalid = azVar.invalid_forward; - if (prev_invalid) { - ++invalid_count; - } else { - // save beginning of subsection if not filled - azVar.index = 0; - azVar.current_azimuth = GreatCircle.sphericalAzimuth((float) centerY, (float) centerX, rawllpts[0], - rawllpts[1]); - // Debug.output("marker0="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - if (!isFilled) { - sections.add(azVar); - } else { - az_first = azVar; - } - azVar = new AzimuthVar(); - } - - // iterate through all rawllpts - int i = 0, j = 0; - for (i = 1, j = 2; i < len; i++, j += 2) { - azVar.invalid_forward = false;// reset forward flag - _forward(rawllpts[j], rawllpts[j + 1], temp, azVar); - curr_invalid = azVar.invalid_forward; - xs[i] = temp.x; - ys[i] = temp.y; - if (!curr_invalid && prev_invalid) { - // record transition (outside -> inside) - azVar.index = i - 1;// include outside point - azVar.current_azimuth = GreatCircle.sphericalAzimuth((float) centerY, (float) centerX, rawllpts[j - 2], - rawllpts[j - 1]); - // Debug.output("marker oi="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - azVar = new AzimuthVar(); - } else if (curr_invalid) { - if (!prev_invalid) { - // record transition (inside -> outside) - azVar.index = i;// include outside point - if (isFilled && (invalid_count == 0)) { - az_save = azVar;// save wrap-end - } else { - // Debug.output("marker io="+azVar.index+ - // " - // az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - } - azVar = new AzimuthVar(); - } - ++invalid_count; - } - prev_invalid = curr_invalid; - } - - // poly completely inside - if (invalid_count == 0) { - ArrayList ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - return ret_val; - } - // poly completely outside - if (invalid_count == len) { - return new ArrayList(0); - } - - // handle poly that is partially inside hemisphere - - // cases AA & CC - if (!prev_invalid) { - // special case AA wrapping: - if (isFilled && (az_save != null)) { - // copy the wrapped portion into - int l = az_save.index; - x_ = new float[len + l]; - y_ = new float[len + l]; - System.arraycopy(xs, 0, x_, 0, len); - System.arraycopy(ys, 0, y_, 0, len); - System.arraycopy(xs, 0, x_, len, l); - System.arraycopy(ys, 0, y_, len, l); - az_save.index = len + l; - // Debug.output("wrap end="+az_save.index+ - // " az="+ProjMath.radToDeg(az_save.current_azimuth)); - sections.add(az_save);// complete section - xs = x_; - ys = y_; - // case CC or AA (non-wrapping): - } else { - if (DEBUG && isFilled && (az_save == null)) { - Debug.output("AA, filled, no-wrap!"); - } - azVar.index = i; - j = rawllpts.length; - azVar.current_azimuth = GreatCircle.sphericalAzimuth((float) centerY, (float) centerX, rawllpts[j - 2], - rawllpts[j - 1]); - // Debug.output("marker end="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - } - // special case DD - } else if (az_save != null) { - if (DEBUG) - Debug.output("DD, filled!"); - sections.add(az_first); - sections.add(az_save); - } - - int size = sections.size(); - ArrayList ret_val = new ArrayList(size); - - // filled poly: handle fill problems - if (isFilled && (len > 2)) { - generateFilledPoly(xs, ys, sections, ret_val); - return ret_val; - } - - // non-filled poly: just extract the subsections - for (j = 0; j < size; j += 2) { - AzimuthVar az1 = (AzimuthVar) sections.get(j); - AzimuthVar az2 = (AzimuthVar) sections.get(j + 1); - int off1 = az1.index; - int off2 = az2.index; - int l = off2 - off1; - x_ = new float[l]; - y_ = new float[l]; - System.arraycopy(xs, off1, x_, 0, l); - System.arraycopy(ys, off1, y_, 0, l); - ret_val.add(x_); - ret_val.add(y_); - } - return ret_val; - }// _forwardPoly() - - /** - * Forward project a lat/lon Poly. This is a complex method. Please read the - * in-code documentation for an explanation of the algorithm. - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - boolean DEBUG = Debug.debugging("proj"); - - int len = rawllpts.length >>> 1; - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - - int invalid_count = 0;// number of invalid points - boolean curr_invalid, prev_invalid = false;// previous - // invalid - // forward - Point temp = new Point(); - AzimuthVar az_first = null, az_save = null, azVar = new AzimuthVar(); - ArrayList sections = new ArrayList(128); - float[] x_, xs = new float[len]; - float[] y_, ys = new float[len]; - - // handle first point - _forward(rawllpts[0], rawllpts[1], temp, azVar); - xs[0] = temp.x; - ys[0] = temp.y; - prev_invalid = azVar.invalid_forward; - if (prev_invalid) { - ++invalid_count; - } else { - // save beginning of subsection if not filled - azVar.index = 0; - azVar.current_azimuth = (float) GreatCircle.sphericalAzimuth(centerY, centerX, rawllpts[0], rawllpts[1]); - // Debug.output("marker0="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - if (!isFilled) { - sections.add(azVar); - } else { - az_first = azVar; - } - azVar = new AzimuthVar(); - } - - // iterate through all rawllpts - int i = 0, j = 0; - for (i = 1, j = 2; i < len; i++, j += 2) { - azVar.invalid_forward = false;// reset forward flag - _forward(rawllpts[j], rawllpts[j + 1], temp, azVar); - curr_invalid = azVar.invalid_forward; - xs[i] = temp.x; - ys[i] = temp.y; - if (!curr_invalid && prev_invalid) { - // record transition (outside -> inside) - azVar.index = i - 1;// include outside point - azVar.current_azimuth = (float) GreatCircle.sphericalAzimuth(centerY, centerX, rawllpts[j - 2], - rawllpts[j - 1]); - // Debug.output("marker oi="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - azVar = new AzimuthVar(); - } else if (curr_invalid) { - if (!prev_invalid) { - // record transition (inside -> outside) - azVar.index = i;// include outside point - if (isFilled && (invalid_count == 0)) { - az_save = azVar;// save wrap-end - } else { - // Debug.output("marker io="+azVar.index+ - // " - // az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - } - azVar = new AzimuthVar(); - } - ++invalid_count; - } - prev_invalid = curr_invalid; - } - - // poly completely inside - if (invalid_count == 0) { - ArrayList ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - return ret_val; - } - // poly completely outside - if (invalid_count == len) { - return new ArrayList(0); - } - - // handle poly that is partially inside hemisphere - - // cases AA & CC - if (!prev_invalid) { - // special case AA wrapping: - if (isFilled && (az_save != null)) { - // copy the wrapped portion into - int l = az_save.index; - x_ = new float[len + l]; - y_ = new float[len + l]; - System.arraycopy(xs, 0, x_, 0, len); - System.arraycopy(ys, 0, y_, 0, len); - System.arraycopy(xs, 0, x_, len, l); - System.arraycopy(ys, 0, y_, len, l); - az_save.index = len + l; - // Debug.output("wrap end="+az_save.index+ - // " az="+ProjMath.radToDeg(az_save.current_azimuth)); - sections.add(az_save);// complete section - xs = x_; - ys = y_; - // case CC or AA (non-wrapping): - } else { - if (DEBUG && isFilled && (az_save == null)) { - Debug.output("AA, filled, no-wrap!"); - } - azVar.index = i; - j = rawllpts.length; - azVar.current_azimuth = (float) GreatCircle.sphericalAzimuth(centerY, centerX, rawllpts[j - 2], - rawllpts[j - 1]); - // Debug.output("marker end="+azVar.index+ - // " az="+ProjMath.radToDeg(azVar.current_azimuth)); - sections.add(azVar); - } - // special case DD - } else if (az_save != null) { - if (DEBUG) - Debug.output("DD, filled!"); - sections.add(az_first); - sections.add(az_save); - } - - int size = sections.size(); - ArrayList ret_val = new ArrayList(size); - - // filled poly: handle fill problems - if (isFilled && (len > 2)) { - generateFilledPoly(xs, ys, sections, ret_val); - return ret_val; - } - - // non-filled poly: just extract the subsections - for (j = 0; j < size; j += 2) { - AzimuthVar az1 = (AzimuthVar) sections.get(j); - AzimuthVar az2 = (AzimuthVar) sections.get(j + 1); - int off1 = az1.index; - int off2 = az2.index; - int l = off2 - off1; - x_ = new float[l]; - y_ = new float[l]; - System.arraycopy(xs, off1, x_, 0, l); - System.arraycopy(ys, off1, y_, 0, l); - ret_val.add(x_); - ret_val.add(y_); - } - return ret_val; - }// _forwardPoly() - - // This is meant to be called from _forwardPoly() after - // determining that a FILLED polygon straddles the edge of the - // projection/hemisphere. - // - // IDEA: - // - // We already have a bunch of sections of the poly. Connect the - // sections by adding extra edge points along the - // projection/hemisphere edge. From 1 polygon we can potentially - // get N sub-sections, each of which needs to be connected and - // filled. To create the hemisphere edge points we need to know - // the orientation of the fill (vertices in clockwise or - // counter-clockwise order). - // - // The following ASCII picture indicates a simple case where a - // polygon straddles the hemisphere. - // - // - // | - // Inside | Outside - // Hemisphere _____| <- in->out Hemisphere - // ___x + - // x | Add vertices `+' along hemisphere - // Clockwise | Fill | edge (in clockwise order for this - // Vertices | Color + example to complete filled poly - // `x' x Here / subsection. - // \ / - // x + - // / / <-- Hemisphere Edge - // / / - // ________x___+__+ - // ^ - // \ - // out->in - // - // PROBLEMS: - // - // Unfortunately the previous example is one of the simple cases, - // and the algorithm quickly runs into difficulty with certain - // polys. The core of the algorithm is to take the azimuth of the - // inside->outside vertex, find the next closest outside->inside - // azimuth (in the indicated order), and add vertices between them - // to complete the edge. - // - // The assumption is that the azimuths of the in->out and the - // out->in vertices remain in the indicated order (clockwise or - // counter-clockwise). Unfortunately this is a faulty assumption - // in many cases, and leads to a HACK! The azimuth values of the - // edge points may actually appear to switch order, which blows up - // our hemisphere edge calculations. The algorithm corrects - // (hacks-around) this problem by disallowing excessively wide - // polygons (in->out and out->in azimuth difference of > 180). - // (Thus, we stamp out one problem only to introduce another, but - // this problem as easier to work around as we shall see below). - // - // PROBLEMATIC WIDE POLYS: - // - // Consider a polygon band around the world following east-west - // rhumblines at latitudes 20: - // (-20,-10),(-20,-90),(-20,180),(-20,90),(-20,10), - // (20,10),(20,90),(20,180),(20,-90),(20,-10),(-20,-10) - // - // Obviously we want to draw color INSIDE this band, but as we - // will see, this doesn't happen in certain viewing positions. - // Imagine viewing this polygon in an orthographic projection - // centered at the north pole: you would see the northern edge of - // the poly enter the hemisphere at 10E, circle around the long - // way going east and leave the hemisphere at 10W. Although the - // polyline is drawn correctly, the fill side will be rendered - // incorrectly since the algorithm will connect the polygon the - // short way around the projection edge. Here's the picture: - // - // __________________ - // / \ - // / _____x______ \ - // / / \ \ - // / / \ \ - // / / \ \ - // / / \ \ - // / / Azimuth \ \ - // | / 180 | | - // | | | | | - // | | | | | - // | x -90--N--90 x | - // | | | | | - // | | | | | - // | | 0 / | - // \ \ / / - // \ \ / / - // \ \ in-> out-> / / - // \ \ out in / / - // \ \__ __/ / - // \ x x / - // \_____|______|_____/ - // ^^^^^^ - // - // POLY WORKAROUNDS: - // - // You may need to break large polygons like the example one into - // smaller subsections. So for the example above, break it into 3 - // or 4 swaths (poly1 from 10W-90W, poly2 from 90W-180W, poly 3 - // from 10E-90E, poly4 from 90E-180E). You may then choose to use - // these polygons to draw the FILL ONLY, and also include the - // original poly to draw the bounding outline (remember that - // polylines don't have the fill problem just described!) - // - private void generateFilledPoly(float[] xs, float[] ys, ArrayList sections, - ArrayList ret_vec) { - AzimuthVar beginAz, oiAz, ioAz; - /* - * the merged list is going to end up being series of lists of two - * AzimuthVar objects, then a double[] - */ - ArrayList merged = null; - /* - * The masterList is going to end up holding a merged ArrayList and an - * Integer count of vertexes. - */ - ArrayList masterList = new ArrayList(); - double[] edgePoints = null; - - // begin, in->out, out->in, end indices - int bg = 0, io = 1, oi, en; - int vertexCount = 0; - - // iterate over the sections - while (!sections.isEmpty()) { - beginAz = (AzimuthVar) sections.get(bg);// out->in begin - // section - ioAz = (AzimuthVar) sections.get(io);// in->out end - // section - - // find next closest out->in section - oi = findClosestAzimuth(sections, ioAz.current_azimuth, clockwise); - oiAz = (AzimuthVar) sections.get(oi); - en = oi + 1; - - // closed a section - if (oi == bg) { - // finished a complex section - if (merged != null) { - // close the polygon - edgePoints = getHemisphereEdge(oiAz.current_azimuth, ioAz.current_azimuth); - vertexCount += (edgePoints.length >>> 1); - merged.add(edgePoints); - masterList.add(new Integer(vertexCount)); - merged = null; - vertexCount = 0; - } - - // otherwise doing a simple section - else { - hemisphereClip(xs, ys, oiAz, ioAz, ret_vec); - } - sections.remove(io); - sections.remove(bg); - bg = 0; - io = 1;// restart parse - continue; - } - - // merge complex section - - if (merged == null) { - // Debug.output("complex-edge filled poly"); - // start new complex section - merged = new ArrayList(); - masterList.add(merged); - merged.add(beginAz); - merged.add(ioAz); - vertexCount += ioAz.index - beginAz.index; - } - // connect the sections - edgePoints = getHemisphereEdge(oiAz.current_azimuth, ioAz.current_azimuth); - vertexCount += (edgePoints.length >>> 1); - merged.add(edgePoints); - AzimuthVar endAz = (AzimuthVar) sections.get(en); - merged.add(oiAz); - merged.add(endAz); - vertexCount += endAz.index - oiAz.index; - - // remove intermediary azvars - sections.set(io, endAz); - sections.remove(en); - sections.remove(oi); - } - - // Create closed polys from the merged sections (if any) - Point temp = new Point(); - int masterSize = masterList.size(); - for (int i = 0; i < masterSize; i += 2) { - merged = (ArrayList) masterList.get(i); - vertexCount = ((Integer) masterList.get(i + 1)).intValue(); - - // allocate space for all vertices - float[] x_ = new float[vertexCount]; - float[] y_ = new float[vertexCount]; - int off = 0, off1, off2, l, edgelen; - - int size = merged.size(); - for (int j = 0; j < size; j += 3) { - - // extract section - off1 = ((AzimuthVar) merged.get(j)).index; - off2 = ((AzimuthVar) merged.get(j + 1)).index; - l = off2 - off1; - System.arraycopy(xs, off1, x_, off, l); - System.arraycopy(ys, off1, y_, off, l); - off += l; - - // project horizon edge - edgePoints = (double[]) merged.get(j + 2); - edgelen = edgePoints.length; - for (int k = 0; k < edgelen; k += 2) { - _forward(edgePoints[k], edgePoints[k + 1], temp, null); - x_[off] = temp.x; - y_[off] = temp.y; - ++off; - } - } - - // store the fully-closed vertices in return ArrayList - ret_vec.add(x_); - ret_vec.add(y_); - } - } - - // Find the closest azimuth value to the one listed. Check in - // appropriate clockwise or counter-clockwise direction. This is - // called from generateFilledPoly(). - private int findClosestAzimuth(ArrayList sections, double az, boolean clockwise) { - double delta; - double closest = (clockwise) ? -MoreMath.TWO_PI_D : MoreMath.TWO_PI_D; - int id = -1; - AzimuthVar oiAz; - // determine closest out->in azimuth - for (int k = sections.size() - 2; k >= 0; k -= 2) { - oiAz = (AzimuthVar) sections.get(k);// out->in azimuth - delta = az - oiAz.current_azimuth;// az delta along - // horizon - if (delta > Math.PI) - delta = -MoreMath.TWO_PI_D + delta; - else if (delta < -Math.PI) - delta = MoreMath.TWO_PI_D + delta; - if (clockwise) { - if (delta > 0) - delta = -MoreMath.TWO_PI_D + delta; - if (closest <= delta) { - closest = delta; - id = k; - } - } else { - if (delta < 0) - delta = MoreMath.TWO_PI_D + delta; - if (closest >= delta) { - closest = delta; - id = k; - } - } - } - // save distance and index of closest az - return id; - } - - // Calculate radian points along the hemisphere edge between two - // azimuths. (Azimuths "East-of-North" relative to center point - // of projection). This is called from generateFilledPoly(). - private double[] getHemisphereEdge(double oiAz, double ioAz) { - // Debug.output( - // "oiAz="+ProjMath.radToDeg(oiAz)+" - // ioAz="+ProjMath.radToDeg(ioAz)); - // get the azimuth delta, and normalize it - double delta = oiAz - ioAz; - if (delta > Math.PI) - delta = -MoreMath.TWO_PI_D + delta; - else if (delta < -Math.PI) - delta = MoreMath.TWO_PI_D + delta; - delta = Math.abs(delta); - - // Debug.output("delta="+ProjMath.radToDeg(delta)); - - // get the two LatLonPoints on the edge. - LatLonPoint ll1 = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, ioAz); - LatLonPoint ll2 = GreatCircle.sphericalBetween(centerY, centerX, MoreMath.HALF_PI_D, oiAz); - - // Debug.output("ll1="+ll1+" ll2="+ll2); - - // calculate an acceptable number of points along horizon - // edge from ioAz to oiAz. - int npts = (int) (Math.abs(delta) / ACCEPTABLE_AZ); - if (npts == 0) - ++npts; - double[] radpts = GreatCircle.greatCircle(ll1.getRadLat(), ll1.getRadLon(), ll2.getRadLat(), ll2.getRadLon(), - npts, true); - - return radpts; - } - - // Clip filled poly section along the hemisphere edge. Add the - // closed poly coordinates to the return ArrayList. This is called - // from generateFilledPoly(). - private void hemisphereClip(float[] xs, float[] ys, AzimuthVar oiAz, AzimuthVar ioAz, ArrayList ret_vec) { - double[] radpts = getHemisphereEdge(oiAz.current_azimuth, ioAz.current_azimuth); - int len = radpts.length; - int m = len >>> 1; - int off1 = oiAz.index; - int off2 = ioAz.index; - int l = off2 - off1; - - float[] x_ = new float[l + m]; - float[] y_ = new float[l + m]; - System.arraycopy(xs, off1, x_, 0, l); - System.arraycopy(ys, off1, y_, 0, l); - - // add the hemisphere edge points to the list - Point temp = new Point(); - for (int i = l, j = 0; j < len; i++, j += 2) { - _forward(radpts[j], radpts[j + 1], temp, null); - x_[i] = temp.x; - y_[i] = temp.y; - } - ret_vec.add(x_); - ret_vec.add(y_); - } - - /** - * Forward project a raw array of radian points. This assumes nothing about - * the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of lat,lon,... in radians - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, - int copyoff, int copylen) { - Point temp = new Point(); - AzimuthVar azVar = new AzimuthVar(); - boolean ok = true; - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - _forward(rawllpts[j], rawllpts[j + 1], temp, azVar); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - ok = !azVar.invalid_forward; - visible[i] = ok; - } - return ok; - } - - /** - * Forward project a raw array of radian points. This assumes nothing about - * the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of lat,lon,... in radians - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, - int copyoff, int copylen) { - Point temp = new Point(); - AzimuthVar azVar = new AzimuthVar(); - boolean ok = true; - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - _forward(rawllpts[j], rawllpts[j + 1], temp, azVar); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - ok = !azVar.invalid_forward; - visible[i] = ok; - } - return ok; - } - - // print out polygon - // private static final void dumpPoly (float[] rawllpts) { - // Debug.output("poly:"); - // for (int i=0; i -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/BasicProjectionLoader.java,v $ -// $RCSfile: BasicProjectionLoader.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * The BasicProjectionLoader is a base implementation of the - * ProjectionLoader interface that conveniently handles the - * PropertyConsumer methods for the ProjectionLoader. There are two - * basic properties built into this base class that can be modified in - * a properties file. You can add ProjectionLoaders to the MapHandler, - * and if the ProjectionFactory singleton instance has been added to - * it as well, it will be picked up and the projection made available - * to the application. For example, the BasicProjectionFactory allows - * you to set thse properties for the Mercator projection: - * - *

- *   
- *    
- *    
- *     projLoader.class=com.bbn.openmap.proj.MercatorLoader
- *     projLoader.prettyName=Mercator
- *     projLoader.description=Mercator Projection.
- *    
- *     
- *    
- * 
- * - * The prettyName and description properties should have defaults, but - * internationalized strings can be substituted as needed. - */ -public abstract class BasicProjectionLoader extends OMComponent implements - ProjectionLoader { - - protected Class projClass; - protected String prettyName; - protected String description; - - public final static String PrettyNameProperty = "prettyName"; - public final static String DescriptionProperty = "description"; - - /** - * Set the basic parameters needed for a ProjectionLoader. - */ - public BasicProjectionLoader(Class pClass, String pName, String pDescription) { - projClass = pClass; - prettyName = pName; - description = pDescription; - } - - /** - * Get a class name to use for the projection. This will be used - * as a key in the projection factory. - */ - public Class getProjectionClass() { - return projClass; - } - - /** - * Get a pretty name for the projection. - */ - public String getPrettyName() { - return prettyName; - } - - /** - * Set a pretty name for the projection. - */ - public void setPrettyName(String pn) { - prettyName = pn; - } - - /** - * Get a description for the projection. - */ - public String getDescription() { - return description; - } - - /** - * Set a description for the projection. - */ - public void setDescription(String desc) { - description = desc; - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public abstract Projection create(Properties props) - throws ProjectionException; - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - prettyName = props.getProperty(prefix + PrettyNameProperty, prettyName); - description = props.getProperty(prefix + DescriptionProperty, - description); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + PrettyNameProperty, prettyName); - props.put(prefix + DescriptionProperty, description); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String internString = i18n.get(BasicProjectionLoader.class, - PrettyNameProperty, - "Projection Name"); - props.put(PrettyNameProperty + LabelEditorProperty, internString); - - internString = i18n.get(BasicProjectionLoader.class, - PrettyNameProperty, - I18n.TOOLTIP, - "Presentable name for Projection"); - props.put(PrettyNameProperty, internString); - - internString = i18n.get(BasicProjectionLoader.class, - DescriptionProperty, - "Projection Description"); - props.put(DescriptionProperty + LabelEditorProperty, internString); - - internString = i18n.get(ProjectionLoader.class, - DescriptionProperty, - I18n.TOOLTIP, - "Presentable description name for Projection"); - props.put(DescriptionProperty, internString); - - props.put(initPropertiesProperty, PrettyNameProperty + " " - + DescriptionProperty); - - return props; - } - - public LatLonPoint convertToLLP(Point2D pt) { - return LatLonPoint.getDouble(pt); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/CADRG.java b/src/core/src/main/java/com/bbn/openmap/proj/CADRG.java deleted file mode 100644 index d1341a369..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/CADRG.java +++ /dev/null @@ -1,721 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/CADRG.java,v $ -// $RCSfile: CADRG.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Implements the CADRG projection. This is really an Equal Arc Projection with - * pixel spacings as dictated by the RPF specification. - */ -public class CADRG extends Cylindrical implements EqualArc { - - private static final long serialVersionUID = 1L; - - /** - * The CADRG name. - */ - public final static transient String CADRGName = "CADRG"; - - public final static transient double epsilon = 0.0001; - - // HACK -degrees - private static final double NORTH_LIMIT = ProjMath.degToRad(80.0f); - private static final double SOUTH_LIMIT = -NORTH_LIMIT; - - private double spps_x, spps_y; // scaled pixels per SCoord - private static final int CADRG_ARC_A[] = { 369664, 302592, 245760, 199168, 163328, 137216, - 110080, 82432 }; - private static final double CADRG_SCALE_LIMIT = 2000.0; - private static final int CADRG_get_zone_old_extents[] = { 32, 48, 56, 64, 68, 72, 76, 80, 90 }; - private int /* ox, */oy; - private double x_pix_constant, y_pix_constant; - private Point ul;// upper left - - private double[] lower_zone_extents; - private double[] upper_zone_extents; - - private int zone; - - /** - * Construct a CADRG projection. - * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public CADRG(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - minscale = 1000000 / CADRG_SCALE_LIMIT; - } - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - * - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_LIMIT) { - lat = NORTH_LIMIT; - } else if (lat < SOUTH_LIMIT) { - lat = SOUTH_LIMIT; - } - return lat; - } - - // protected void finalize() { - // Debug.message("proj", "CADRG finialized"); - // } - - /** - * Return stringified description of this projection. - *

- * - * @return String - * @see Projection#getProjectionID - * - */ - public String toString() { - return "CADRG[ spps_x=" + spps_x + " spps_y=" + spps_y + " x_pix=" + x_pix_constant - + " y_pix=" + y_pix_constant + - /* " ox=" + ox + */" oy=" + oy + " ul(" + ul.x + "," + ul.y + ")" - + super.toString(); - } - - /** - * Returns the current zone of the projection. Zone number starts at 1, goes - * to 8, per the RPF specification. We don't handle zone 9 (polar). - * - * @return the zone of the projection. - */ - public int getZone() { - return zone; - } - - /** - * Given a letter for a zone, return the CADRG zone equivalent, - */ - public static int getProjZone(char asciiZone) { - int z = (int) asciiZone; - - if (z == 74) - z--; // Fix J to a zone. - if (z > 64) - z -= 64; // Below the equator - else - z -= 48; // Above the equator - - // Now we should have a number, of a zone 1-9 - return z; - } - - /** - * Get the planet pixel circumference. - * - * @return double circumference of planet in pixels - */ - public double getPlanetPixelCircumference() { - // Why this algorithm? Well, the CADRG_ARC_A is a pixel count - // that needs to be multiplied by 1000000 to normalize it - // against the 1:1M factor reflected in the array values. The - // 1.5 factor was tossed in there because it was showing up in - // other calculations as that 100/150 thing. It works in - // tests. - - return (1000000 * (double) CADRG_ARC_A[zone - 1]) / 1.5; - // These are the same things... - // return (float)getXPixConstant() * scale; - - // This is what the default return value is from the super - // class. - // return planetPixelCircumference; // the standard return for - // projections... - } - - /** - * Returns the zone based on the y_pix_constant and a latitude. - *

- * HACK: latitude in decimal degrees DO THE CONSTANTS DEPEND ON THIS?!! - *

- * - * @param lat latitude - * @param y_pix_constant pixel constant - * - */ - protected int getZone(double lat, double y_pix_constant) { - int NOT_SET = -1; - int ret = NOT_SET; - - for (int x = 0; x < CADRG_get_zone_old_extents.length - 1/* 8 */; x++) { - double testLat = Math.abs(lat); - if (testLat <= CADRG_get_zone_old_extents[x]) { - ret = x + 1; - break; - } - } - - if (ret == NOT_SET) - ret = CADRG_get_zone_old_extents.length - 1; - - return ret; - } - - /** - * Returns the x pixel constant of the projection. This was calculated when - * the projection was created. Represents the number of pixels around the - * earth (360 degrees). - */ - public double getXPixConstant() { - return x_pix_constant; - } - - /** - * Returns the y pixel constant of the projection. This was calculated when - * the projection was created. Represents the number of pixels from 0 to 90 - * degrees. - */ - public double getYPixConstant() { - return y_pix_constant; - } - - /** - * Returns the upper zone extent for the given zone at the current scale. - * This only makes sense if the projection is at the same scale as the chart - * data you are interested in. - */ - public double getUpperZoneExtent(int zone) { - if (zone < 1) - zone = 1; - if (zone > 8) - zone = 9; - return upper_zone_extents[zone - 1]; - } - - /** - * Returns the lower zone extent for the given zone at the current scale. - * This only makes sense if the projection is at the same scale as the chart - * data you are interested in. - */ - public double getLowerZoneExtent(int zone) { - if (zone < 1) - zone = 1; - if (zone > 8) - zone = 9; - return lower_zone_extents[zone - 1]; - } - - /** - * Return the number of horizontal frame files that will fit around the - * world in the current zone. This only makes sense if the projection is at - * the same scale as the chart data you are interested in. - * - * @return number of frame columns in the current zone, to go around the - * world. - */ - public int numHorizontalFrames() { - return (int) Math.ceil(x_pix_constant / (1536.0)); - } - - /** - * Return the number of vertical frame files that will fit within the - * current zone, overlaps included. This only makes sense if the projection - * is at the same scale as the chart data you are interested in. - * - * @return number of frame rows in the current zone. - */ - public int numVerticalFrames() { - return (int) Math.round((upper_zone_extents[zone - 1] - lower_zone_extents[zone - 1]) - * (y_pix_constant / 90.0) / (1536.0)); - } - - /** - * Figures out the number of pixels around the earth, for 360 degrees. - *

- * - * @param adrgscale The scale adjusted to 1:1M (1M/real scale) - * @param zone ADRG zone - * @return The number of pixels around the equator (360 degrees) - */ - private double CADRG_x_pix_constant(double adrgscale, int zone) { - // E-W pixel constant - double x_pix = (double) adrgscale * CADRG_ARC_A[zone - 1] / 512.0; - - // Increase, if necessary, to the next highest integer value - x_pix = Math.ceil(x_pix); - x_pix *= 1.33333;// (512*100)/(150*256); - - // Round the final result. - x_pix = Math.round(x_pix); - - return x_pix * 256.0; - } - - /** - * Calculate the maximum allowable scale. - *

- * - * @return float maxscale - * - */ - private float CADRG_calc_maxscale() { - // Why 1.5? It was 150/100? Why? - return (float) Math.floor((1000000 * (float) CADRG_ARC_A[0]) / (width * 1.5f)); - } - - /** - * Returns the number of pixels from the equator to a pole. - *

- * - * @param adrgscale scale adjusted to 1:1M (1M/real scale) - * @return number of pixels from 0 to 90 degrees - * - */ - private double CADRG_y_pix_constant(double adrgscale) { - final int CADRG_ARC_B = 400384; - - double y_pix = (double) adrgscale * CADRG_ARC_B / 512.0; - - // Increase, if necessary, to the next highest integer value - y_pix = Math.ceil(y_pix); - - y_pix *= 0.33333;// (512*100)/(4*150*256); - - // Round the final result. - y_pix = Math.round(y_pix); - - return y_pix * 256.0; - } - - /** - * Checks if a LatLonPoint is plot-able. - *

- * A point is plot-able in the CADRG projection if it is within the North - * and South zone limits. - *

- * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return boolean - */ - public boolean isPlotable(double lat, double lon) { - /** - * I don't think what we are doing here with the latitude is right, - * normalizing the latitude. We're trying to answer a question about - * whether given values are valid, and we're changing those values to be - * valid before answering. Duh. So, no normalizingLatitude before the - * check. - */ - lat = ProjMath.degToRad(lat); - return ((lat < NORTH_LIMIT) && (lat > SOUTH_LIMIT)); - } - - /** - * Forward projects lat,lon into XY space and returns a Point2D. - * - * @param lat float latitude in radians - * @param lon float longitude in radians - * @param ret_val Resulting XY Point2D - * @return Point2D ret_val - */ - public Point2D forward(double lat, double lon, Point2D ret_val, boolean isRadians) { - if (!isRadians) { - lon = Math.toRadians(lon); - lat = Math.toRadians(lat); - } - - double lon_ = wrapLongitude(lon - centerX); - double lat_ = normalizeLatitude(lat); - - int x = (int) ProjMath.roundAdjust(spps_x * lon_) - ul.x; - int y = (int) ProjMath.roundAdjust(-spps_y * lat_) + ul.y + oy; - ret_val.setLocation(x, y); - return ret_val; - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - *

- * - * @param x integer x coordinate - * @param y integer y coordinate - * @param ret_val LatLonPoint - * @return LatLonPoint ret_val - * @see Proj#inverse(Point2D) - * - */ - @SuppressWarnings("unchecked") - public T inverse(double x, double y, T ret_val) { - // Debug.output("CADRG.inverse"); - - if (ret_val == null) { - ret_val = (T) new LatLonPoint.Double(); - } - - /* offset back into pixel space from Drawable space */ - double px = x + ul.x/* - ox */; - double py = -y + ul.y + oy; - - // Check bounds on the call (P Space). Mutate if needed. - if (px > ProjMath.roundAdjust(world.x / 2.0)) { - px = ProjMath.roundAdjust(world.x / 2.0); - } else if (px < ProjMath.roundAdjust(-world.x / 2.0)) { - px = ProjMath.roundAdjust(-world.x / 2.0); - } - if (py > ProjMath.roundAdjust(world.y / 2.0)) { - py = ProjMath.roundAdjust(world.y / 2.0); - } else if (py < ProjMath.roundAdjust(-world.y / 2.0)) { - py = ProjMath.roundAdjust(-world.y / 2.0); - } - - // normalize_latitude on the way out. - double lat_ = normalizeLatitude(py / spps_y); - double lon_ = wrapLongitude((px / spps_x) + centerX); - ret_val.setLocation(Math.toDegrees(lon_), Math.toDegrees(lat_)); - - return ret_val; - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- * - */ - protected synchronized void computeParameters() { - int w, h; - - if (ul == null) - ul = new Point(0, 0); // HACK - - // quick calculate the maxscale - maxscale = CADRG_calc_maxscale(); - if (scale > maxscale) - scale = maxscale; - - // Compute the "ADRG" scale, which gets used below. - double adrgscale = 1000000.0 / scale; // 1 million (from - // ADRG - // spec) - if (adrgscale > CADRG_SCALE_LIMIT) { - Debug.message("proj", "CADRG: adrgscale > CADRG_SCALE_LIMIT"); - adrgscale = CADRG_SCALE_LIMIT; - } - - // Compute the y pixel constant based on scale. - y_pix_constant = CADRG_y_pix_constant(adrgscale); - if (Debug.debugging("proj")) { - Debug.output("Y pix constant = " + y_pix_constant); - } - - // //// - - /** Pixels per degree */ - double ppd = y_pix_constant / 90.0; - if (upper_zone_extents == null || lower_zone_extents == null) { - upper_zone_extents = new double[CADRG_get_zone_old_extents.length]; - lower_zone_extents = new double[CADRG_get_zone_old_extents.length + 1]; - - lower_zone_extents[0] = 0f; - lower_zone_extents[8] = 80f; - upper_zone_extents[8] = 90f; - - // figure out new extents - from CADRG spec - for (int x = 0; x < CADRG_get_zone_old_extents.length - 1/* 8 */; x++) { - double pivot = Math.floor(ppd * CADRG_get_zone_old_extents[x] / 1536.0); - lower_zone_extents[x + 1] = pivot * 1536.0 / ppd; - // Can't go further than the equator. - // if (x == 0) lower_zone_extents[x] = 0; - pivot++; - upper_zone_extents[x] = pivot * 1536.0 / ppd; - Debug.message("proj", "lower_zone_extents[" + x + "] = " + lower_zone_extents[x]); - Debug.message("proj", "upper_zone_extents[" + x + "] = " + upper_zone_extents[x]); - } - } - // //// - - // What zone are we in? To try to reduce pixel spacing jumping when - // zoomed - // out, just set the zone level to one when zoomed out past 1:60M. There - // aren't any charts available at those scales in this projection type. - - if (scale > 60000000) { - zone = 1; - } else { - zone = getZone(ProjMath.radToDeg(centerY), y_pix_constant); - } - if (Debug.debugging("proj")) { - Debug.output("Zone = " + zone); - } - - // Compute the x pixel constant, based on scale and zone. - x_pix_constant = CADRG_x_pix_constant(adrgscale, zone); - - // If the x_pix_constant, or number of pixels around the earth is less - // than or equal to the width of the map window, then the corner - // coordinates become equal or inverted (ul vs lr). - if (width >= x_pix_constant) { - x_pix_constant = width + 1; - } - - if (Debug.debugging("proj")) { - Debug.output("x_pix_constant = " + x_pix_constant); - } - // Now I can compute the world coordinate. - if (world == null) - world = new Point(0, 0); - world.x = (int) ProjMath.roundAdjust(x_pix_constant); - world.y = (int) ProjMath.roundAdjust(y_pix_constant * 4.0 / 2.0); - Debug.message("proj", "world = " + world.x + "," + world.y); - - // Compute scaled pixels per RADIAN, not SCOORD - spps_x = (double) x_pix_constant / MoreMath.TWO_PI/* - * MoreMath.DEG_TO_SC(360 - * ) - */; - spps_y = (double) y_pix_constant / MoreMath.HALF_PI/* - * MoreMath.DEG_TO_SC( - * 90 ) - */; - Debug.message("proj", "spps = " + spps_x + "," + spps_y); - - // Fix the "small world" situation, computing ox, oy. - if (width > world.x) { - Debug.message("proj", "CADRG: fixing small world"); - w = world.x; - // ox = (int) ProjMath.roundAdjust((width - w) / 2.0); - } else { - w = width; - // ox = 0; - } - if (height > world.y) { - h = (int) world.y; - oy = (int) ProjMath.roundAdjust((height - h) / 2.0); - } else { - h = height; - oy = 0; - } - - // compute the "upper left" adjustment. - long temp = (long) ProjMath.roundAdjust(spps_y * centerY); - if (Debug.debugging("proj")) { - Debug.output("CADRG.temp = " + temp); - } - if (ul == null) - ul = new Point(0, 0); - ul.x = (int) ProjMath.roundAdjust(-w / 2.0); - if ((temp != 0) && (oy != 0)) { - ul.y = (int) ProjMath.roundAdjust(h / 2.0); - } else { - ul.y = (int) temp + (int) ProjMath.roundAdjust(h / 2.0); - } - - if (Debug.debugging("proj")) { - Debug.output("CADRG: ul = " + ul.x + "," + ul.y); - Debug.output(/* "ox = " + ox + */" oy = " + oy); - } - - // Finally compute some useful cylindrical projection - // parameters - // maxscale = (CADRG_ARC_A[0] * (1000000/width));// HACK!!! - half_world = world.x / 2; - - if (scale > maxscale) { - scale = maxscale; - } - // scaled_radius = planetPixelRadius/scale; - Debug.message("proj", "CADRG.computeParameters(): maxscale: " + maxscale); - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return CADRGName; - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a Point2D reflecting a pixel spot on the projection that - * matches the ll1 coordinate, the upper left corner of the area of - * interest. - * @param point2 a Point2D reflecting a pixel spot on the projection that - * matches the ll2 coordinate, usually the lower right corner of the - * area of interest. - */ - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2) { - return getScale(ll1, ll2, point1, point2, 0); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a Point2D reflecting a pixel spot on the projection that - * matches the ll1 coordinate, the upper left corner of the area of - * interest. - * @param point2 a Point2D reflecting a pixel spot on the projection that - * matches the ll2 coordinate, usually the lower right corner of the - * area of interest. - * @param recursiveCount a protective count to keep this method from getting - * in a recursive death spiral. - */ - private float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2, - int recursiveCount) { - - try { - - double deltaDegrees; - double pixPerDegree; - int deltaPix; - double ret; - double dx = Math.abs(point2.getX() - point1.getX()); - double dy = Math.abs(point2.getY() - point1.getY()); - - double nCenterLat = Math.min(ll1.getY(), ll2.getY()) - + Math.abs(ll1.getY() - ll2.getY()) / 2; - double nCenterLon = Math.min(ll1.getX(), ll2.getX()) - + Math.abs(ll1.getX() - ll2.getX()) / 2; - - if (dx < dy) { - double dlat = Math.abs(ll1.getX() - ll2.getY()); - deltaDegrees = dlat; - deltaPix = getHeight(); - pixPerDegree = getScale() * getYPixConstant() / 90; - } else { - double dlon; - double lat1, lon1, lon2; - - // point1 is to the right of point2. switch the - // LatLonPoints so that ll1 is west (left) of ll2. - if (point1.getX() > point2.getX()) { - lat1 = ll1.getY(); - lon1 = ll1.getX(); - ll1.setLocation(ll2); - // Remember for setLocation the order of args is reversed - ll2.setLocation(lon1, lat1); - } - - lon1 = ll1.getX(); - lon2 = ll2.getX(); - - // allow for crossing dateline - if (lon1 > lon2) { - dlon = (180 - lon1) + (180 + lon2); - } else { - dlon = lon2 - lon1; - } - - deltaDegrees = dlon; - deltaPix = getWidth(); - pixPerDegree = getPlanetPixelCircumference() / 360; - } - - // The new scale... - ret = pixPerDegree / (deltaPix / deltaDegrees); - - // OK, now given the new scale at the apparent new center - // location, we need to test if the zone changes, because - // if it does, the values don't work out right because the - // pixel spacings are different. If the zones are - // different, we need to recalculate the scale based on - // the - // new zone. - CADRG newcadrg = new CADRG(new LatLonPoint.Double(nCenterLat, nCenterLon), (float) ret, getWidth(), getHeight()); - - // Use the recursiveCount to prevent extended recalls. A - // couple rounds should suffice. - if (newcadrg.getZone() != zone && recursiveCount < 2) { - ret = newcadrg.getScale(ll1, ll2, newcadrg.forward(ll1), newcadrg.forward(ll2), recursiveCount + 1); - } - - return (float) ret; - } catch (NullPointerException npe) { - Debug.error("ProjMath.getScale(): caught null pointer exception."); - return Float.MAX_VALUE; - } - } - - public static CADRG convertProjection(Projection proj) { - if (proj instanceof CADRG) { - return (CADRG) proj; - } - - CADRG cadrg = new CADRG((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), proj.getWidth(), proj.getHeight()); - - Point2D ulp = cadrg.forward(proj.getUpperLeft()); - Point2D lrp = cadrg.forward(proj.getLowerRight()); - - int w = (int) Math.abs(lrp.getX() - ulp.getX()); - int h = (int) Math.abs(lrp.getY() - ulp.getY()); - - return new CADRG((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), w, h); - } - - /* - * public static void main (String argv[]) { CADRG proj= new CADRG(new - * LatLonPoint(42.0f, 0.0f), 18000000.0f, 620,480); - * - * Debug.output("---testing latitude"); proj.testPoint(0.0f, 0.0f); - * proj.testPoint(10.0f, 0.0f); proj.testPoint(-10.0f, 0.0f); - * proj.testPoint(23.1234f, 0.0f); proj.testPoint(-23.1234f, 0.0f); - * proj.testPoint(90.0f, 0.0f); proj.testPoint(-100.0f, 0.0f); - * - * Debug.output("---testing longitude"); proj.testPoint(0.0f, 10.0f); - * proj.testPoint(0.0f, -10.0f); proj.testPoint(0.0f, 86.45f); - * proj.testPoint(0.0f, -86.45f); proj.testPoint(0.0f, 375.0f); - * proj.testPoint(0.0f, -375.0f); } - * - * private void testPoint(float lat, float lon) { LatLonPoint llpoint = new - * LatLonPoint(ProjMath.radToDeg( - * normalize_latitude(ProjMath.degToRad(lat))), lon); Point point = - * forward(llpoint); - * - * Debug.output("(lon="+llpoint.getLongitude()+ - * ",lat="+llpoint.getLatitude()+ ") = (x="+point.x+",y="+point.y+")"); - * - * llpoint = inverse(point); - * - * Debug.output("(x="+point.x+",y="+point.y+") = (lon="+ - * llpoint.getLongitude()+",lat="+ llpoint.getLatitude()+")"); } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/CADRGLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/CADRGLoader.java deleted file mode 100644 index 4f08571f6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/CADRGLoader.java +++ /dev/null @@ -1,77 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/CADRGLoader.java,v $ -// $RCSfile: CADRGLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the CADRG projection to an OpenMap - * application. - * - * @see BasicProjectionLoader - */ -public class CADRGLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public CADRGLoader() { - super(CADRG.class, - CADRG.CADRGName, - "Equal-Arc projection for displaying RPF data (CADRG and CIB)."); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - return new CADRG(llp, scale, width, height); - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("CADRGLoader: problem creating CADRG projection " - + e.getMessage()); - } - } - - throw new ProjectionException("CADRGLoader: problem creating CADRG projection"); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Cartesian.java b/src/core/src/main/java/com/bbn/openmap/proj/Cartesian.java deleted file mode 100755 index 5b12a720b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Cartesian.java +++ /dev/null @@ -1,449 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Cartesian.java,v $ -// $RCSfile: Cartesian.java,v $ -// $Revision: 1.4 $ -// $Date: 2006/04/07 15:21:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; - -/** - * The Cartesian projection is a non-wrapping, straight-forward scaling - * projection drawn in 2D. The simplest projection ever, it can be used for - * regular plotting. - */ -public class Cartesian extends Proj implements Projection, java.io.Serializable { - /** - * The Cartesian name. - */ - public final static transient String CartesianName = "Cartesian"; - - /** - * The coordinate limit of the left side of the projection. If the left side - * of the map projection would show coordinates more left than this value, - * the center of the map will be changed so that this value is on the edge. - */ - protected double leftLimit; - /** - * The coordinate limit of the right side of the projection. If the right - * side of the map projection would show coordinates more right than this - * value, the center of the map will be changed so that this value is on the - * edge. - */ - protected double rightLimit; - /** - * The coordinate limit of the top side of the projection. If the top side - * of the map projection would show coordinates higher than this value, the - * center of the map will be changed so that this value is on the edge. - */ - protected double topLimit; - /** - * The coordinate limit of the bottom side of the projection. If the bottom - * side of the map projection would show coordinates lower than this value, - * the center of the map will be changed so that this value is on the edge. - */ - protected double bottomLimit; - /** - * A point that can be used for force the projection against the limits. Is - * only used if the limits are set to be something other than infinity. - */ - protected Point2D limitAnchorPoint; - - protected double scaleFactor; - - protected transient double hWidth; - protected transient double hHeight; - protected transient double SFScale; - - protected transient AffineTransform transform1; - protected transient AffineTransform transform2; - // protected transient AffineTransform transform3; - protected transient AffineTransform transform4; - - /** - * Create a Cartesian projection that does straight scaling, no wrapping. - * - * @param center the coordinates of the center of the map. - * @param scale the scale to use for the map, referring to the difference of - * the ration between pixels versus coordinate values. - * @param width the pixel width of the map. - * @param height the pixel height of the map. - */ - public Cartesian(Point2D center, float scale, int width, int height) { - super(center, scale, width, height); - } - - public void init() { - scaleFactor = 100000000; - - // Limits are in coordinate space, dictating how much coordinate space - // can be viewable. The center point and scale should be adjusted as - // appropriate (during computeParameters). - leftLimit = Double.NEGATIVE_INFINITY; - rightLimit = Double.POSITIVE_INFINITY; - topLimit = Double.POSITIVE_INFINITY; - bottomLimit = Double.NEGATIVE_INFINITY; - } - - protected void computeParameters() { - hWidth = width / 2.0; - hHeight = height / 2.0; - SFScale = scaleFactor / scale; - - checkLimits(); - - transform1 = AffineTransform.getTranslateInstance(-centerX, -centerY); - transform2 = AffineTransform.getScaleInstance(SFScale, -SFScale); - // transform3 = AffineTransform.getScaleInstance(1 / SFScale, - // -1 / SFScale); - transform4 = AffineTransform.getTranslateInstance(hWidth, hHeight); - } - - /** - * The method you want to call. Checks if there are limits set, and will - * call setLimits(checkScale) properly. - */ - protected void checkLimits() { - if (leftLimit != Double.NEGATIVE_INFINITY - || rightLimit != Double.POSITIVE_INFINITY - || topLimit != Double.POSITIVE_INFINITY - || bottomLimit != Double.NEGATIVE_INFINITY) { - checkLimits(true); - } - } - - /** - * Should only be called if you've checked there are limits set on the - * projection. - * - * @param checkScale true the first time through, if the scale changes this - * method calls itself with false to prevent a loop. - */ - protected void checkLimits(boolean checkScale) { - - if (limitAnchorPoint != null) { - centerX = limitAnchorPoint.getX(); - centerY = limitAnchorPoint.getY(); - } - - // Check limits. - Point2D p2 = checkUpperLimits(); - if (p2 != null) { - centerX = p2.getX(); - centerY = p2.getY(); - } - - Point2D p1 = checkLowerLimits(); - if (p1 != null) { - centerX = p1.getX(); - centerY = p1.getY(); - } - - if (checkScale && p1 != null && p2 != null) { - double newScale = checkScaleAgainstLimits(); - if (newScale != scale) { - scale = newScale; - SFScale = scaleFactor / scale; - checkLimits(false); - } - } - } - - /** - * Checks the lower limits and returns new center coordinates to keep the - * limits at the edge if necessary. - */ - protected Point2D checkLowerLimits() { - Point2D p1 = new Point2D.Double(); - Point2D p2 = null; - double moveX = 0; - double moveY = 0; - inverse(0, height, p1);// LL corner - if (p1.getX() < leftLimit) { - p2 = forward(centerY, leftLimit, p2); - moveX = p2.getX(); - } - - if (p1.getY() < bottomLimit) { - p2 = forward(bottomLimit, centerX, p2); - moveY = height - p2.getY(); - } - - if (p2 != null) { - inverse(hWidth + moveX, hHeight - moveY, p2); - } - - return p2; - } - - /** - * Checks the upper limits and returns new center coordinates to keep the - * limits at the edge if necessary. - */ - protected Point2D checkUpperLimits() { - Point2D p1 = new Point2D.Double(); - Point2D p2 = null; - double moveX = 0; - double moveY = 0; - inverse(width, 0, p1);// UR corner - if (p1.getX() > rightLimit) { - p2 = forward(centerY, rightLimit, p2); - moveX = width - p2.getX(); - } - - if (p1.getY() > topLimit) { - p2 = forward(topLimit, centerX, p2); - moveY = p2.getY(); - } - - if (p2 != null) { - inverse(hWidth - moveX, hHeight + moveY, p2); - } - - return p2; - } - - /** - * Checks the corner values against the limits and returns the right scale - * to keep limits at the edge if necessary. - */ - protected double checkScaleAgainstLimits() { - Point2D p1 = getUpperLeft(); - Point2D p2 = getLowerRight(); - - double x = p1.getX(); - double y = p1.getY(); - if (topLimit != Double.POSITIVE_INFINITY) { - y = topLimit; - } - - if (leftLimit != Double.NEGATIVE_INFINITY) { - x = leftLimit; - } - p1.setLocation(x, y); - - x = p2.getX(); - y = p2.getY(); - if (bottomLimit != Double.NEGATIVE_INFINITY) { - y = bottomLimit; - } - if (rightLimit != Double.POSITIVE_INFINITY) { - x = rightLimit; - } - - p2.setLocation(x, y); - // second p1, p2 meaningless - return getScale(p1, p2, p1, p2); - } - - /** - * Forward project a world coordinate into screen space. - * - * @param wy vertical coordinate component in world units. - * @param wx horizontal coordinate component in world units. - * @param mapPoint screen point to load result into. OK if null, a new one - * will be created and returned. - * @return Point2D provided or new one created containing map coordinate. - */ - public Point2D forward(double wy, double wx, Point2D mapPoint) { - - double x = ((wx - centerX) * SFScale) + hWidth; - double y = hHeight - ((wy - centerY) * SFScale); - - if (mapPoint == null) { - mapPoint = new Point2D.Double(x, y); - } else { - mapPoint.setLocation(x, y); - } - /* - * fPoint1.setLocation(wx, wy); Point2D tmp = - * transform1.transform(fPoint1, fPoint2); tmp = - * transform2.transform(tmp, fPoint1); tmp = transform4.transform(tmp, - * fPoint2); mapPoint.setLocation(tmp.getX(), tmp.getY()); - */ - return mapPoint; - } - - // Used for AffineTransform forward and inverse methods, to save - // allocation expense. - // Point2D fPoint1 = new Point2D.Double(); - // Point2D fPoint2 = new Point2D.Double(); - // Point2D iPoint1 = new Point2D.Double(); - // Point2D iPoint2 = new Point2D.Double(); - - /** - * Inverse projection a map coordinate into world space. - * - * @param x horizontal map coordinate from left side of map. - * @param y vertical map coordinate from top of map. - * @param worldPoint a Point2D object to load result into. OK if null, a new - * one will be created if necessary. - * @return Point2D provided or new one if created, containing the result. - */ - public Point2D inverse(double x, double y, Point2D worldPoint) { - double worldPointX = (x - hWidth) / SFScale + centerX; - double worldPointY = (hHeight - y) / SFScale + centerY; - - if (worldPoint == null) { - worldPoint = new Point2D.Double(worldPointX, worldPointY); - } else { - worldPoint.setLocation(worldPointX, worldPointY); - } - /* - * try { iPoint1.setLocation(x, y); Point2D tmp = - * transform4.inverseTransform(iPoint1, iPoint2); tmp = - * transform3.transform(tmp, iPoint1); transform1.inverseTransform(tmp, - * worldPoint); } catch (NoninvertibleTransformException e) { - * e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } - */ - return worldPoint; - } - - /** - * @param Az direction, 0 is north, positive is clockwise. - * @param c number of world coordinates to pan. - */ - public void pan(double Az, double c) { - double currentX = centerX; - double currentY = centerY; - - currentX -= c * Math.sin(Math.toRadians(Az) + Math.PI); - currentY -= c * Math.cos(Math.toRadians(Az) + Math.PI); - - setCenter(new Point2D.Double(currentX, currentY)); - } - - /** - * Pan half a view. - */ - public void pan(double Az) { - pan(Az, (getUpperLeft().distance(getLowerRight()) / 4.0)); - } - - /** - * Takes a java.awt.Shape object and re-projects it for a the current view. - * Returns a GeneralPath. - */ -// public Shape forwardShape(Shape shape) { -// return super.forwardShape(shape); -// // return -// // transform4.createTransformedShape(transform2.createTransformedShape(transform1.createTransformedShape(shape))); -// -// // Set Proj.java for the iterator way of doing this. -// } - - /** - */ - public String getName() { - return CartesianName; - } - - /** - */ - public float getScale(Point2D ulWorldPoint, Point2D lrWorldPoint, - Point2D point1, Point2D point2) { - try { - - double worldCoords; - double deltaPix; - double dx = Math.abs(lrWorldPoint.getX() - ulWorldPoint.getX()); - double dy = Math.abs(lrWorldPoint.getY() - ulWorldPoint.getY()); - - if (dx <= dy) { - worldCoords = dx; - deltaPix = Math.abs(point2.getX() - point1.getX()); - } else { - worldCoords = dy; - deltaPix = Math.abs(point2.getY() - point1.getY()); - } - - // The new scale... - return (float) (worldCoords / deltaPix * scaleFactor); - } catch (NullPointerException npe) { - com.bbn.openmap.util.Debug.error("CartesianProjection.getScale(): caught null pointer exception."); - return Float.MAX_VALUE; - } - } - - public boolean isPlotable(double lat, double lon) { - return true; - } - - public Point2D getCenter() { - return new Point2D.Double(centerX, centerY); - } - - public double getBottomLimit() { - return bottomLimit; - } - - public void setBottomLimit(double bottomLimit) { - this.bottomLimit = bottomLimit; - computeParameters(); - } - - public double getLeftLimit() { - return leftLimit; - } - - public void setLeftLimit(double leftLimit) { - this.leftLimit = leftLimit; - computeParameters(); - } - - public Point2D getLimitAnchorPoint() { - return limitAnchorPoint; - } - - public void setLimitAnchorPoint(Point2D limitAnchorPoint) { - this.limitAnchorPoint = limitAnchorPoint; - computeParameters(); - } - - public double getRightLimit() { - return rightLimit; - } - - public void setRightLimit(double rightLimit) { - this.rightLimit = rightLimit; - computeParameters(); - } - - public double getTopLimit() { - return topLimit; - } - - public void setTopLimit(double topLimit) { - this.topLimit = topLimit; - computeParameters(); - } - - public void setLimits(double top, double bottom, double left, double right, - Point2D anchor) { - this.topLimit = top; - this.bottomLimit = bottom; - this.leftLimit = left; - this.rightLimit = right; - this.limitAnchorPoint = anchor; - computeParameters(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/CartesianLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/CartesianLoader.java deleted file mode 100644 index 17f0e851c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/CartesianLoader.java +++ /dev/null @@ -1,288 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/CartesianLoader.java,v $ -// $RCSfile: CartesianLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/02/24 20:43:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the Cartesian projection to an OpenMap application. - * There are some properties you can set for the Cartesian projection, namely - * limits on where it can pan. If you don't set the limits, the projection will - * just keep going. You can use the anchorX and anchorY settings to hold the map - * against some of the limits. - * - *

- *  topLimit=top coordinate limit
- *  bottomLimit=bottom coordinate limit
- *  leftLimit=left side coordinate limit
- *  rightLimit=right side coordinate limit
- *  anchorX=horizontal coordinate to set on projection before checking limits
- *  anchorY=vertical coordinate to set on projection before checking limits
- * 
- * - * @see BasicProjectionLoader - */ -public class CartesianLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public final static String TopLimitProperty = "topLimit"; - public final static String BottomLimitProperty = "bottomLimit"; - public final static String RightLimitProperty = "rightLimit"; - public final static String LeftLimitProperty = "leftLimit"; - public final static String AnchorXProperty = "anchorX"; - public final static String AnchorYProperty = "anchorY"; - - /** - * The coordinate limit of the left side of the projection. If the left side - * of the map projection would show coordinates more left than this value, - * the center of the map will be changed so that this value is on the edge. - */ - protected double leftLimit = Double.NEGATIVE_INFINITY; - /** - * The coordinate limit of the right side of the projection. If the right - * side of the map projection would show coordinates more right than this - * value, the center of the map will be changed so that this value is on the - * edge. - */ - protected double rightLimit = Double.POSITIVE_INFINITY; - /** - * The coordinate limit of the top side of the projection. If the top side - * of the map projection would show coordinates higher than this value, the - * center of the map will be changed so that this value is on the edge. - */ - protected double topLimit = Double.POSITIVE_INFINITY; - /** - * The coordinate limit of the bottom side of the projection. If the bottom - * side of the map projection would show coordinates lower than this value, - * the center of the map will be changed so that this value is on the edge. - */ - protected double bottomLimit = Double.NEGATIVE_INFINITY; - /** - * A point that can be used for force the projection against the limits. Is - * only used if the limits are set to be something other than infinity. - */ - protected Point2D limitAnchorPoint; - - public CartesianLoader() { - super(Cartesian.class, - Cartesian.CartesianName, - "Cartesian projection for displaying projected data."); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - Point2D center = (Point2D) props.get(ProjectionFactory.CENTER); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - - Cartesian proj = new Cartesian(center, scale, width, height); - - proj.setLimits(topLimit, - bottomLimit, - leftLimit, - rightLimit, - limitAnchorPoint); - - return proj; - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("CartesianLoader: problem creating Cartesian projection " - + e.getMessage()); - } - } - - throw new ProjectionException("CartesianLoader: problem creating Cartesian projection"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - leftLimit = PropUtils.doubleFromProperties(props, prefix - + LeftLimitProperty, Double.NEGATIVE_INFINITY); - rightLimit = PropUtils.doubleFromProperties(props, prefix - + RightLimitProperty, Double.POSITIVE_INFINITY); - topLimit = PropUtils.doubleFromProperties(props, prefix - + TopLimitProperty, Double.POSITIVE_INFINITY); - bottomLimit = PropUtils.doubleFromProperties(props, prefix - + BottomLimitProperty, Double.NEGATIVE_INFINITY); - - double x = PropUtils.doubleFromProperties(props, prefix - + AnchorXProperty, Double.POSITIVE_INFINITY); - double y = PropUtils.doubleFromProperties(props, prefix - + AnchorYProperty, Double.POSITIVE_INFINITY); - - if (x != Double.POSITIVE_INFINITY && y != Double.POSITIVE_INFINITY) { - limitAnchorPoint = new Point2D.Double(x, y); - } - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - String x = ""; - String y = ""; - String top = ""; - String bottom = ""; - String left = ""; - String right = ""; - if (leftLimit != Double.NEGATIVE_INFINITY) { - left = Double.toString(leftLimit); - } - if (topLimit != Double.POSITIVE_INFINITY) { - top = Double.toString(topLimit); - } - if (rightLimit != Double.POSITIVE_INFINITY) { - right = Double.toString(rightLimit); - } - if (bottomLimit != Double.NEGATIVE_INFINITY) { - bottom = Double.toString(bottomLimit); - } - props.put(prefix + TopLimitProperty, top); - props.put(prefix + BottomLimitProperty, bottom); - props.put(prefix + RightLimitProperty, right); - props.put(prefix + LeftLimitProperty, left); - if (limitAnchorPoint != null) { - x = Double.toString(limitAnchorPoint.getX()); - y = Double.toString(limitAnchorPoint.getY()); - } - props.put(prefix + AnchorXProperty, x); - props.put(prefix + AnchorYProperty, y); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - LeftLimitProperty, - "Left Limit", - "Coordinate limit for the left side of the map.", - null); - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - RightLimitProperty, - "Right Limit", - "Coordinate limit for the right side of the map.", - null); - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - TopLimitProperty, - "Top Limit", - "Coordinate limit for the top of the map.", - null); - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - BottomLimitProperty, - "Bottom Limit", - "Coordinate limit for the bottom of the map.", - null); - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - AnchorXProperty, - "Anchor X", - "Horizontal Coordinate for anchor point, used to hold projection against limits.", - null); - PropUtils.setI18NPropertyInfo(i18n, - props, - CartesianLoader.class, - AnchorYProperty, - "Anchor Y", - "Horizontal Coordinate for anchor point, used to hold projection against limits.", - null); - - props.put(initPropertiesProperty, PrettyNameProperty + " " - + DescriptionProperty + " " + TopLimitProperty + " " - + BottomLimitProperty + " " + RightLimitProperty + " " - + LeftLimitProperty + " " + AnchorXProperty + " " - + AnchorYProperty); - - return props; - } - - public double getBottomLimit() { - return bottomLimit; - } - - public void setBottomLimit(double bottomLimit) { - this.bottomLimit = bottomLimit; - } - - public double getLeftLimit() { - return leftLimit; - } - - public void setLeftLimit(double leftLimit) { - this.leftLimit = leftLimit; - } - - public Point2D getLimitAnchorPoint() { - return limitAnchorPoint; - } - - public void setLimitAnchorPoint(Point2D limitAnchorPoint) { - this.limitAnchorPoint = limitAnchorPoint; - } - - public double getRightLimit() { - return rightLimit; - } - - public void setRightLimit(double rightLimit) { - this.rightLimit = rightLimit; - } - - public double getTopLimit() { - return topLimit; - } - - public void setTopLimit(double topLimit) { - this.topLimit = topLimit; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Clip.java b/src/core/src/main/java/com/bbn/openmap/proj/Clip.java deleted file mode 100644 index e72788700..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Clip.java +++ /dev/null @@ -1,279 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Clip.java,v $ -// $RCSfile: Clip.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:21 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * Clipping functions. - */ -public class Clip { - - // cannot construct - private Clip() {} - - /** - * Calculate the float[] x,y buffer length for nverts. - *

- * - * @param nverts number of verts - * @return int length required - * - */ - public static final int liang_get_buflen(int nverts) { - //*2 for x,y pairs, *2 for potential extra points, +2 for - // closure, - //and +1 for return length - return (nverts << 2) + 3; - } - - /** - * Liang Barsy polygon clipping algorithm. - *

- * Viewport: xleft < xright, ybottom < ytop - *

- * Set up with: - * float[] ret_val = new float[n*2*2]; - * ret_val = liang_clip(,...,ret_val); - * - *

- * Points: xpoints, ypoints, npts HACK: closure on these points? - * - * @param xleft left side of viewport - * @param xright right side of viewport - * @param ytop top of viewport - * @param ybottom bottom of viewport - * @param x float[] x coords - * @param y float[] y coords - * @param n numcoords - * @param ret_val float[] clipped polygon - * @see #liang_get_buflen - * - */ - public static final float[] liang_clip(int xleft, int xright, int ytop, - int ybottom, float[] x, float[] y, int n, - float[] ret_val) { - int i, num = 0; - double dx, dy, xin, xout, yin, yout, tinx, tiny, tin1, tin2, toutx, touty, tout1; - - /* - * If you put in an n-sided polygon, you will never get more - * than a 2n-sided polygon out (actually you get less, but we - * are being conservative) - */ - for (i = 0; i < n; i++) { - dx = x[i + 1] - x[i]; // (assuming closure of polygon) - dy = y[i + 1] - y[i]; - - /* line points right */ - if ((dx > 0) || ((dx == 0) && (x[i] > xright))) { - xin = xleft; - xout = xright; - } - /* line points left */ - else { - xin = xright; - xout = xleft; - } - /* line points up */ - if ((dy > 0) || ((dy == 0) && (y[i] > ytop))) { - yin = ybottom; - yout = ytop; - } - /* line points down */ - else { - yin = ytop; - yout = ybottom; - } - - tinx = (dx != 0) ? (xin - x[i]) / dx : Double.NEGATIVE_INFINITY; - tiny = (dy != 0) ? (yin - y[i]) / dy : Double.NEGATIVE_INFINITY; - - if (tinx < tiny) { /* first entry at x then y */ - tin1 = tinx; - tin2 = tiny; - } else { /* first entry at y then x */ - tin1 = tiny; - tin2 = tinx; - } - - if (tin1 <= 1) { /* case 2, 3, 4, 6 */ - if (tin1 > 0) { /* case 5 - turning vertex */ - ret_val[num++] = (int) ProjMath.qint((double) (xin)); - ret_val[num++] = (int) ProjMath.qint((double) (yin)); - } - if (tin2 <= 1) { /* case 3, 4, 6 */ - if (dx != 0) - toutx = (xout - x[i]) / dx; - else - /* vertical */ - toutx = ((xleft <= x[i]) && (x[i] <= xright)) ? Double.POSITIVE_INFINITY - : Double.NEGATIVE_INFINITY; - - if (dy != 0) - touty = (yout - y[i]) / dy; - else - /* horizontal */ - touty = ((ybottom <= y[i]) && (y[i] <= ytop)) ? Double.POSITIVE_INFINITY - : Double.NEGATIVE_INFINITY; - - tout1 = (toutx < touty) ? toutx : touty; - - if ((tin2 > 0) || (tout1 > 0)) { /* case 4, 6 */ - if (tin2 <= tout1) { /* - * case 4 - visible - * segment - */ - if (tin2 > 0) /* v[i] outside window */ - if (tinx > tiny) { /* - * vertical - * boundary - */ - ret_val[num++] = (int) ProjMath.qint(xin); - ret_val[num++] = (int) ProjMath.qint(y[i] - + (tinx * dy)); - } else { /* horiz boundary */ - ret_val[num++] = (int) ProjMath.qint(x[i] - + (tiny * dx)); - ret_val[num++] = (int) ProjMath.qint(yin); - } - if (tout1 < 1) { /* v[i+1] outside window */ - if (toutx < touty) { /* - * vertical - * boundary - */ - ret_val[num++] = (int) ProjMath.qint(xout); - ret_val[num++] = (int) ProjMath.qint(y[i] - + (toutx * dy)); - } else { /* horiz boundary */ - ret_val[num++] = (int) ProjMath.qint(x[i] - + (touty * dx)); - ret_val[num++] = (int) ProjMath.qint(yout); - } - } else { - ret_val[num++] = (int) (x[i + 1]); - ret_val[num++] = (int) (y[i + 1]); - } - } else { /* case 6 - turning vertex */ - if (tinx > tiny) { /* second entry at x */ - ret_val[num++] = (int) ProjMath.qint(xin); - ret_val[num++] = (int) ProjMath.qint(yout); - } else { /* second entry at y */ - ret_val[num++] = (int) ProjMath.qint(xout); - ret_val[num++] = (int) ProjMath.qint(yin); - } - } - } - } - } - } - if (num != 0) { - // Close the polygon - ret_val[num++] = ret_val[0];/* lat */ - ret_val[num++] = ret_val[1];/* lon */ - // note the total length - ret_val[ret_val.length - 1] = num; - } else - ret_val[ret_val.length - 1] = num; - - return ret_val; - } - - // enum Values - static final class Values { - final static char LEFT = 0x1; - final static char RIGHT = 0x2; - final static char BOTTOM = 0x4; - final static char TOP = 0x8; - } - - private static final int _quick_code(int x, int y, int xleft, int xright, - int ytop, int ybottom) { - - int val = 0x0; - - if (x < xleft) - val = Values.LEFT; - else if (x > xright) - val = Values.RIGHT; - if (y < ytop) - val |= Values.TOP; - else if (y > ybottom) - val |= Values.BOTTOM; - - return val; - } - - /** - * Check if a line is completely inside or completely outside - * viewport. - *

- * - * @param x1 pt1.x - * @param y1 pt1.y - * @param x2 pt2.x - * @param y2 pt2.y - * @param xleft left - * @param xright right - * @param ytop ytop < ybottom - * @param ybottom ybottom < ytop - * @return int -1=outside, 1=inside, 0=undetermined - * - */ - public final static int quickCheckLineClip(int x1, int y1, int x2, int y2, - int xleft, int xright, int ytop, - int ybottom) - // xleft < xright, ytop < ybottom - { - /* - * return values: 1 = line is fully in window 0 = line is NOT - * fully in window. THIS DOES NOT IMPLY THAT LINE IS PARTIALLY - * INSIDE WINDOW. -1 = line is NOT in window at all - */ - int pt1 = _quick_code(x1, y1, xleft, xright, ytop, ybottom); - int pt2 = _quick_code(x2, y2, xleft, xright, ytop, ybottom); - - if ((pt1 & pt2) != 0) - return -1; // completely outside - else if ((pt1 | pt2) == 0) - return 1; // completely inside - else - return 0; // partially inside? - } - - /* - * public static void main(String[] args) { int xleft = 0; int - * xright = 1024; int ytop = 0; int ybottom = 1024; float[] ret_val = - * null; float[] xs = null, ys = null; - * - * int n = 4; xs = new float[n+1]; ys = new float[n+1]; xs[0] = -100; - * ys[0] = 400; xs[1] = 700; ys[1] = -100; xs[2] = 1100; ys[2] = - * 400; xs[3] = 700; ys[3] = 1100; xs[4] = -100; ys[4] = 400; - * ret_val = new float[liang_get_buflen(n)]; - * - * ret_val = liang_clip( xleft, xright, ybottom, ytop, xs, ys, n, - * ret_val); n = ret_val[ret_val.length-1]-2;// unclosed length - * - * Debug.output("num pairs = " + n); Debug.output("total buffer - * len = " + ret_val.length); for (int i = 0; i < n; i+=2) { - * Debug.output( "(" + ret_val[i] + "," + ret_val[i+1] + ")"); } } - */ -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Cylindrical.java b/src/core/src/main/java/com/bbn/openmap/proj/Cylindrical.java deleted file mode 100644 index a1f2f017d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Cylindrical.java +++ /dev/null @@ -1,486 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Cylindrical.java,v $ -// $RCSfile: Cylindrical.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Base of all cylindrical projections. - *

- * - * @see Projection - * @see Proj - * @see Mercator - * @see CADRG - * - */ -public abstract class Cylindrical - extends GeoProj { - - // used for calculating wrapping of ArrayList graphics - protected transient Point world; // world width in pixels. - protected transient int half_world; // world.x / 2 - - /** - * Construct a cylindrical projection. - *

- * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public Cylindrical(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - } - - /** - * Return string-ified description of this projection. - *

- * - * @return String - * @see Projection#getProjectionID - */ - public String toString() { - return " world(" + world.x + "," + world.y + ")" + super.toString(); - } - - protected void init() { - super.init(); - - // minscale is the minimum scale allowable (before integer - // wrapping - // can occur) - minscale = Math.ceil(planetPixelCircumference / (int) Integer.MAX_VALUE); - if (minscale < 1) { - minscale = 1; - } - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- */ - protected void computeParameters() { - - if (scale < minscale) - scale = minscale; - - // maxscale = scale at which world circumference fits in - // window - maxscale = Math.floor(planetPixelCircumference / width); - if (maxscale < minscale) { - maxscale = minscale; - } - if (scale > maxscale) { - scale = maxscale; - } - scaled_radius = planetPixelRadius / scale; - - if (world == null) - world = new Point(0, 0); - - // width of the world in pixels at current scale - world.x = (int) (planetPixelCircumference / scale); - half_world = world.x / 2; - - // calculate cutoff scale for XWindows workaround - XSCALE_THRESHOLD = (int) (planetPixelCircumference / 64000);// fudge - // it a - // little - // bit - - if (Debug.debugging("proj")) { - Debug.output("Cylindrical.computeParameters(): " + "world.x = " + world.x + " half_world = " + half_world - + " XSCALE_THRESHOLD = " + XSCALE_THRESHOLD); - } - } - - /** - * Get the upper left (northwest) point of the projection. - *

- * Returns the upper left point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * - * @return LatLonPoint - * - */ - public LatLonPoint getUpperLeft() { - return inverse(0, 0, new LatLonPoint.Double()); - } - - /** - * Get the lower right (southeast) point of the projection. - *

- * Returns the lower right point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * - * @return LatLonPoint - * - */ - public LatLonPoint getLowerRight() { - return inverse(width - 1, height - 1, new LatLonPoint.Double()); - } - - /** - * Forward project a raw array of radian points. This assumes nothing about - * the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of lat,lon,... in radians - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - Point2D temp = new Point2D.Float(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp, true); - xcoords[i] = (float) temp.getX(); - ycoords[i] = (float) temp.getY(); - visible[i] = true;// should always be visible in - // cylindrical family - } - // everything is visible - return true; - } - - /** - * Forward project a raw array of radian points. This assumes nothing about - * the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of lat,lon,... in radians - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - Point2D temp = new Point2D.Float(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp, true); - xcoords[i] = (float) temp.getX(); - ycoords[i] = (float) temp.getY(); - visible[i] = true;// should always be visible in - // cylindrical family - } - // everything is visible - return true; - } - - /** - * Forward project a raw float[] Poly. - *

- * Implementation:
- * For the cylindrical "boxy" family of projections, we project all the - * points, and check the horizontal (longitudinal) spacing between vertices - * as we go. If the spacing is greater than half the world width - * (circumference) in pixels, we assume that the segment has wrapped off one - * edge of the screen and back onto the other side. (NOTE that our - * restrictions on line segments mentioned in the Projection interface do - * not allow for lines >= 180 degrees of arc or for the difference in - * longitude between two points to be >= 180 degrees of arc). - *

- * For the case where a segment wraps offscreen, we keep track of the - * wrapping adjustment factor, and shift the points as we go. After - * projecting and shifting all the points, we have a single continuous x-y - * polygon. We then need to make shifted copies of this polygon for the - * maxima and minima wrap values calculated during the projection process. - * This allows us to see the discontinuous (wrapped) sections on the screen - * when they are drawn. - *

- * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segments between vertices (or if < 0, generate - * this value internally) - * @param isFilled filled poly? this is currently ignored for cylindrical - * projections. - * @return ArrayList of x[], y[], x[], y[], ... the projected poly - */ - protected ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - int n, k, flag = 0, min = 0, max = 0; - float xp, xadj = 0; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) { - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - } - - // determine when to stop - Point2D temp = new Point2D.Float(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp, true); - xp = (float) temp.getX(); - xs[0] = (float) temp.getX(); - ys[0] = (float) temp.getY(); - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp, true); - xs[n] = (float) temp.getX(); - ys[n] = (float) temp.getY(); - // segment crosses longitude along screen edge - if (Math.abs(xp - xs[n]) >= half_world) { - flag += (xp < xs[n]) ? -1 : 1;// inc/dec the wrap - // count - min = (flag < min) ? flag : min;// left wrap count - max = (flag > max) ? flag : max;// right wrap count - xadj = flag * world.x;// adjustment to x coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = (float) temp.getX();// save previous unshifted x coordinate - if (flag != 0) { - xs[n] += xadj;// adjust x coordinates - } - } - min *= -1;// positive magnitude - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2 + 2 * (max + min)); - ret_val.add(xs); - ret_val.add(ys); - float[] altx = null; - - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, xs, ys); } - */ - - // add the extra left-wrap polys - for (int i = 1; i <= min; i++) { - altx = new float[xs.length]; - xadj = i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - // add the extra right-wrap polys - for (int i = 1; i <= max; i++) { - altx = new float[xs.length]; - xadj = -i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - return ret_val; - }// _forwardPoly() - - /** - * Forward project a raw float[] Poly. - *

- * Implementation:
- * For the cylindrical "boxy" family of projections, we project all the - * points, and check the horizontal (longitudinal) spacing between vertices - * as we go. If the spacing is greater than half the world width - * (circumference) in pixels, we assume that the segment has wrapped off one - * edge of the screen and back onto the other side. (NOTE that our - * restrictions on line segments mentioned in the Projection interface do - * not allow for lines >= 180 degrees of arc or for the difference in - * longitude between two points to be >= 180 degrees of arc). - *

- * For the case where a segment wraps offscreen, we keep track of the - * wrapping adjustment factor, and shift the points as we go. After - * projecting and shifting all the points, we have a single continuous x-y - * polygon. We then need to make shifted copies of this polygon for the - * maxima and minima wrap values calculated during the projection process. - * This allows us to see the discontinuous (wrapped) sections on the screen - * when they are drawn. - *

- * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segments between vertices (or if < 0, generate - * this value internally) - * @param isFilled filled poly? this is currently ignored for cylindrical - * projections. - * @return ArrayList of x[], y[], x[], y[], ... the projected poly - */ - protected ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - int n, k, flag = 0, min = 0, max = 0; - float xp, xadj = 0; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) { - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - } - - // determine when to stop - Point2D temp = new Point2D.Float(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp, true); - xp = (float) temp.getX(); - xs[0] = (float) temp.getX(); - ys[0] = (float) temp.getY(); - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp, true); - xs[n] = (float) temp.getX(); - ys[n] = (float) temp.getY(); - // segment crosses longitude along screen edge - if (Math.abs(xp - xs[n]) >= half_world) { - flag += (xp < xs[n]) ? -1 : 1;// inc/dec the wrap - // count - min = (flag < min) ? flag : min;// left wrap count - max = (flag > max) ? flag : max;// right wrap count - xadj = flag * world.x;// adjustment to x coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = (float) temp.getX();// save previous unshifted x coordinate - if (flag != 0) { - xs[n] += xadj;// adjust x coordinates - } - } - min *= -1;// positive magnitude - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2 + 2 * (max + min)); - ret_val.add(xs); - ret_val.add(ys); - float[] altx = null; - - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, xs, ys); } - */ - - // add the extra left-wrap polys - for (int i = 1; i <= min; i++) { - altx = new float[xs.length]; - xadj = i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - // add the extra right-wrap polys - for (int i = 1; i <= max; i++) { - altx = new float[xs.length]; - xadj = -i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - return ret_val; - }// _forwardPoly() - - // print out polygon - public static final void dumpPoly(float[] rawllpts, float[] xs, float[] ys) { - Debug.output("poly:"); - for (int i = 0, j = 0; j < xs.length; i += 2, j++) { - System.out.print("[" + ProjMath.radToDeg(rawllpts[i]) + "," + ProjMath.radToDeg(rawllpts[i + 1]) + "]="); - Debug.output("(" + xs[j] + "," + ys[j] + ")"); - } - Debug.output(""); - } - - // print out polygon - public static final void dumpPoly(double[] rawllpts, float[] xs, float[] ys) { - Debug.output("poly:"); - for (int i = 0, j = 0; j < xs.length; i += 2, j++) { - System.out.print("[" + ProjMath.radToDeg(rawllpts[i]) + "," + ProjMath.radToDeg(rawllpts[i + 1]) + "]="); - Debug.output("(" + xs[j] + "," + ys[j] + ")"); - } - Debug.output(""); - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return "Cylindrical"; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/DatumShiftProjection.java b/src/core/src/main/java/com/bbn/openmap/proj/DatumShiftProjection.java deleted file mode 100644 index af8674b6e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/DatumShiftProjection.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.coords.DatumShiftGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * This projection wraps another projection and adds datum handling. The - * motivation for this projection is to be able to serve wms clients requesting - * maps in a datum different from wgs84. - *

- * The underlying data is supposed to be wgs4. The given {@link DatumShiftGCT} - * convert this to another datum before using the wrapped projection to - * calculate the screen coordinates. - *

- * {@link LatLonPoint} as input or output of any of the methods in this class is - * in wgs84. Internally, each method will convert datums as needed. - *

- * A user (like wms) of this projection will use a - * {@link com.bbn.openmap.proj.coords.CoordinateReferenceSystem} to convert coordinates to wgs84 before - * using this method. - */ -public class DatumShiftProjection extends GeoProj { - - private GeoProj wrappedProjection; - - private DatumShiftGCT datum; - - public DatumShiftProjection(GeoProj proj, DatumShiftGCT datum) { - super(proj.getCenter(), - proj.getScale(), - proj.getWidth(), - proj.getHeight()); - this.datum = datum; - this.wrappedProjection = proj; - - setCenter(proj.getCenter()); - } - - @Override - public void setCenter(double lat, double lon) { - super.setCenter(lat, lon); - - Point2D centerInDifferentDatum = datum.forward(lat, - lon, - new Point2D.Double()); - wrappedProjection.setCenter((float) centerInDifferentDatum.getY(), - (float) centerInDifferentDatum.getX()); - } - - public ArrayList _forwardPoly(float[] rawllpts, int ltype, - int nsegs, boolean isFilled) { - - float[] rawllptsInDifferentDatum = new float[rawllpts.length]; - - Point2D tmpll = new Point2D.Double(); - - for (int i = 0; i < rawllpts.length; i += 2) { - tmpll = datum.forward(Math.toDegrees(rawllpts[i]), - Math.toDegrees(rawllpts[i + 1]), - tmpll); - rawllptsInDifferentDatum[i] = (float) Math.toRadians(tmpll.getY()); - rawllptsInDifferentDatum[i + 1] = (float) Math.toRadians(tmpll.getX()); - } - - return wrappedProjection._forwardPoly(rawllptsInDifferentDatum, - ltype, - nsegs, - isFilled); - } - - protected ArrayList _forwardPoly(double[] rawllpts, int ltype, - int nsegs, boolean isFilled) { - - double[] rawllptsInDifferentDatum = new double[rawllpts.length]; - - Point2D tmpll = new Point2D.Double(); - - for (int i = 0; i < rawllpts.length; i += 2) { - tmpll = datum.forward(Math.toDegrees(rawllpts[i]), - Math.toDegrees(rawllpts[i + 1]), - tmpll); - rawllptsInDifferentDatum[i] = Math.toRadians(tmpll.getY()); - rawllptsInDifferentDatum[i + 1] = Math.toRadians(tmpll.getX()); - } - - return wrappedProjection._forwardPoly(rawllptsInDifferentDatum, - ltype, - nsegs, - isFilled); - } - - protected void computeParameters() { - if (wrappedProjection != null) { - - wrappedProjection.width = width; - wrappedProjection.height = height; - wrappedProjection.scale = scale; - // wrappedProjection.ctrLat = ctrLat; - // wrappedProjection.ctrLon = ctrLon; - - wrappedProjection.computeParameters(); - } - } - - public void drawBackground(Graphics2D g, Paint p) { - wrappedProjection.drawBackground(g, p); - } - - public void drawBackground(Graphics g) { - wrappedProjection.drawBackground(g); - } - - public double normalizeLatitude(double lat) { - if (lat > NORTH_POLE) { - return NORTH_POLE; - } else if (lat < SOUTH_POLE) { - return SOUTH_POLE; - } - return lat; - } - - public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian) { - Point2D t; - if (isRadian) { - t = datum.forward(Math.toDegrees(lat), Math.toDegrees(lon)); - } else { - t = datum.forward(lat, lon); - } - return wrappedProjection.forward((float) t.getY(), (float) t.getX(), pt); - } - - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, - float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - - float[] rawllptsInDifferentDatum = new float[rawllpts.length]; - - Point2D tmpll = new Point2D.Double(); - - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - tmpll = datum.forward(Math.toDegrees(rawllpts[j]), - Math.toDegrees(rawllpts[j + 1]), - tmpll); - rawllptsInDifferentDatum[j] = (float) Math.toRadians(tmpll.getY()); - rawllptsInDifferentDatum[j + 1] = (float) Math.toRadians(tmpll.getX()); - } - - return wrappedProjection.forwardRaw(rawllptsInDifferentDatum, - rawoff, - xcoords, - ycoords, - visible, - copyoff, - copylen); - } - - public LatLonPoint getLowerRight() { - Point2D llp = wrappedProjection.getLowerRight(); - return datum.inverse(llp.getX(), llp.getY()); - } - - public LatLonPoint getUpperLeft() { - Point2D llp = wrappedProjection.getUpperLeft(); - return datum.inverse(llp.getX(), llp.getY()); - } - - public LatLonPoint inverse(double x, double y, Point2D pt) { - LatLonPoint llpt = assertLatLonPoint(pt); - llpt = (LatLonPoint) wrappedProjection.inverse(x, y, llpt); - return datum.inverse(llpt.getX(), llpt.getY(), llpt); - } - - public boolean isPlotable(double lat, double lon) { - Point2D t = datum.forward(lat, lon); - return wrappedProjection.isPlotable(t.getY(), t.getX()); - } - - @Override - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, - Point2D point2) { - return wrappedProjection.getScale(ll1, ll2, point1, point2); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/DrawUtil.java b/src/core/src/main/java/com/bbn/openmap/proj/DrawUtil.java deleted file mode 100644 index df63f89e5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/DrawUtil.java +++ /dev/null @@ -1,788 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/DrawUtil.java,v $ -// $RCSfile: DrawUtil.java,v $ -// $Revision: 1.6 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.util.MoreMath; - -/** - * Drawing utility functions. - */ -public class DrawUtil { - - // cannot construct - private DrawUtil() {} - - /** - * Generate additional vertices between two points. - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @param n num segments - * @param include_last include the last one? - * @param ret_val the array to put them in - * @return int[] ret_val - */ - public final static int[] lineSegments(int x1, int y1, int x2, int y2, - int n, boolean include_last, - int[] ret_val) { - if (n <= 0) { - ret_val = new int[2]; - ret_val[0] = x1; - ret_val[1] = y1; - return ret_val; - } - float dx = x2 - x1; - float dy = y2 - y1; - int end = include_last ? n + 1 : n; - end <<= 1; - float inc = 1f / (float) n; - float t = inc; - - // add all the vertices in x,y order - ret_val[0] = x1; - ret_val[1] = y1; - for (int i = 2; i < end; i += 2, t += inc) { - ret_val[i] = x1 + (int) (dx * t); - ret_val[i + 1] = y1 + (int) (dy * t); - } - return ret_val; - } - - /** - * Returns n or n+1 points along a line. - *

- * - * @param pt1 point - * @param pt2 point - * @param n count - * @param include_last boolean - * @return Point[] - */ - public final static Point[] lineSegments(Point pt1, Point pt2, int n, - boolean include_last) { - - Point v = new Point(pt2.x - pt1.x, pt2.y - pt1.y); - int end = include_last ? n + 1 : n; - Point[] ret_val = new Point[end]; - float inc = 1f / (float) n; - float t = inc; - - ret_val[0] = pt1; - for (int i = 1; i < end; i++, t += inc) { - ret_val[i] = new Point(pt1.x + (int) ((float) v.x * t), pt1.y - + (int) ((float) v.y * t)); - } - return ret_val; - } - - /** - * Bresenham's line algorithm. - *

- * Returns an array of points to draw. - *

- * - * @param pt1 point - * @param pt2 point - * @return Point[] - * - */ - public final static Point[] bresenham_line(Point pt1, Point pt2) { - return bresenham_line(pt1.x, pt1.y, pt2.x, pt2.y); - } - - /** - * Bresenham's line algorithm. - *

- * - * @param x1 horizontal pixel window location of first point. - * @param y1 vertical pixel window location of first point. - * @param x2 horizontal pixel window location of second point. - * @param y2 vertical pixel window location of second point. - * @return Point[] - * - */ - public final static Point[] bresenham_line(int x1, int y1, int x2, int y2) { - // This is actually NOT bresenhams algorithm. It is faster! - // -rmf - - // Debug.output("DrawUtil.bresenham_line(" + - // x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")"); - int i; - int d, x, y, ax, ay, sx, sy, dx, dy, t; - - dx = x2 - x1; - ax = Math.abs(dx) << 1; - sx = MoreMath.sign(dx); - dy = y2 - y1; - ay = Math.abs(dy) << 1; - sy = MoreMath.sign(dy); - - t = Math.max(Math.abs(dx), Math.abs(dy)) + 1; - Point[] ret_val = new Point[t]; - - x = x1; - y = y1; - if (ax > ay) { /* x dominant */ - d = ay - (ax >> 1); - for (i = 0;;) { - ret_val[i++] = new Point(x, y); - // ret_val[i].x = x; ret_val[i++].y = y; - if (x == x2) - return ret_val; - if (d >= 0) { - y += sy; - d -= ax; - } - x += sx; - d += ay; - } - } else { /* y dominant */ - d = ax - (ay >> 1); - for (i = 0;;) { - ret_val[i++] = new Point(x, y); - // ret_val[i].x = x; ret_val[i++].y = y; - if (y == y2) - return ret_val; - if (d >= 0) { - x += sx; - d -= ay; - } - y += sy; - d += ax; - } - } - } - - /** - * Tests if a point is inside a polygon. - *

- * - * @param xpts horizontal pixel window points of polygon. - * @param ypts vertical pixel window points of polygon. - * @param ptx horizontal pixel window points of location - * @param pty vertical pixel window points of location. - * @return boolean - */ - public final static boolean inside_polygon(float[] xpts, float[] ypts, - double ptx, double pty) { - - int j, inside_flag = 0; - int numverts = xpts.length; - if (numverts <= 2) - return false; - Point2D vtx0 = new Point2D.Float(), vtx1 = new Point2D.Float(); - double dv0; // prevents OVERFLOW!! - int crossings = 0; - boolean xflag0 = false, yflag0 = false, yflag1 = false; - - vtx0.setLocation(xpts[numverts - 1], ypts[numverts - 1]); - // get test bit for above/below Y axis - yflag0 = ((dv0 = vtx0.getY() - pty) >= 0); - - for (j = 0; j < numverts; j++) { - if ((j & 0x1) != 0) { // HACK - slightly changed - vtx0.setLocation(xpts[j], ypts[j]); - yflag0 = ((dv0 = vtx0.getY() - pty) >= 0); - } else { - vtx1.setLocation(xpts[j], ypts[j]); - yflag1 = (vtx1.getY() >= pty); - } - - /* - * check if points not both above/below X axis - can't hit ray - */ - if (yflag0 != yflag1) { - /* check if points on same side of Y axis */ - if ((xflag0 = (vtx0.getX() >= ptx)) == (vtx1.getX() >= ptx)) { - if (xflag0) - crossings++; - } else { - crossings += ((vtx0.getX() - dv0 * (vtx1.getX() - vtx0.getX()) - / (vtx1.getY() - vtx0.getY())) >= ptx) ? 1 : 0; - } - } - inside_flag = crossings & 0x01; - } - return (inside_flag != 0); - } - - /** - * Returns the distance from Point (x,y) to the closest line segment in the - * Poly (int[] xpts, int[] ypts). - *

- * This procedure assumes that xpts.length == ypts.length. - *

- * - * @param xpts X points of the polygon - * @param ypts Y points of the polygon - * @param ptx x location of the point - * @param pty y location of the point - * @param connected polyline or polygon - */ - public final static float closestPolyDistance(float[] xpts, float[] ypts, - double ptx, double pty, - boolean connected) { - if (xpts.length == 0) - return Float.POSITIVE_INFINITY; - if (xpts.length == 1) - return (float) distance(xpts[0], ypts[0], ptx, pty); - - float temp, distance = Float.POSITIVE_INFINITY; - int i, j; - - for (i = 0, j = 1; j < xpts.length; i++, j++) { - temp = (float) distance_to_line(xpts[i], - ypts[i], - xpts[j], - ypts[j], - ptx, - pty); - // Debug.output( - // "\tdistance from line (" + from.x + "," + from.y + - // "<->" + - // to.x + "," + to.y + ") to point (" + ptx + "," + pty + - // ")=" + - // temp); - if (temp < distance) - distance = temp; - } - - // connect - if (connected) { - temp = (float) distance_to_line(xpts[i], - ypts[i], - xpts[0], - ypts[0], - ptx, - pty); - if (temp < distance) - distance = temp; - } - return distance; - } - - /** - * 2D distance formula. - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @return float distance - */ - public final static float distance(float x1, float y1, float x2, float y2) { - double xdiff = x2 - x1; - double ydiff = y2 - y1; - return (float) Math.sqrt((xdiff * xdiff + ydiff * ydiff)); - } - - /** - * 2D distance formula. - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @return float distance - */ - public final static float distance(int x1, int y1, int x2, int y2) { - double xdiff = x2 - x1; - double ydiff = y2 - y1; - return (float) Math.sqrt((xdiff * xdiff + ydiff * ydiff)); - } - - /** - * 2D distance formula. - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @return double distance - */ - public final static double distance(double x1, double y1, double x2, - double y2) { - double xdiff = x2 - x1; - double ydiff = y2 - y1; - return Math.sqrt((xdiff * xdiff + ydiff * ydiff)); - } - - /** - * Calculate the "pixel distance" between two points (squaring not - * involved). - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @return int pixel distance - */ - public final static int pixel_distance(int x1, int y1, int x2, int y2) { - - int dx = Math.abs(x1 - x2); - int dy = Math.abs(y1 - y2); - return (dx > dy) ? dx : dy; - } - - /** - * Distance to closest endpoint. - *

- * - * @param x1 x coord - * @param y1 y coord - * @param x2 x coord - * @param y2 y coord - * @param x x coord of point - * @param y y coord of point - * @return float distance to endpoint - */ - public final static float distance_to_endpoint(int x1, int y1, int x2, - int y2, int x, int y) { - - return (float) Math.min(distance(x1, y1, x, y), distance(x2, y2, x, y)); - } - - /** - * Compute distance from point to line segment. - *

- * Compute the distance from point (x,y) to a line by computing the - * perpendicular line from (x,y) to the line and finding the intersection of - * this perpendicular and the line. If the intersection is on the line - * segment, then the distance is the distance from the mouse to the - * intersection, otherwise it is the distance from (x,y) to the nearest - * endpoint. - *

- * Equations used to compute distance:
- *

    - *
  • m = (y2-y1)/(x2-x1) slope of the line - *
  • y = mx + b equation of the line - *
  • c = -1/m slope of line perpendicular to it - *
  • y = cx + d equation of perpendicular line - *
  • xi = (d-b)/(m-c) x-intersection, from equating the 2 line equations - *
  • y1 = c* xi + d y-intersection - *
  • distance = sqrt(sqr(x-xi) + sqr(y-yi)) distance between two points - *
- * - * @param x1 line x coord1 - * @param y1 line y coord1 - * @param x2 line x coord2 - * @param y2 line y coord2 - * @param x point x coord - * @param y point y coord - * @return float distance to line segment - * @deprecated USE THE NEW FUNCTION - * - */ - public final static float OLD_distance_to_line(int x1, int y1, int x2, - int y2, int x, int y) { - - float m; /* slope of the line */ - float c; /* slope of a line perpendicular to the line */ - float b; /* y intercept of line */ - float d; /* y intercept of a line perpendicular to the line */ - int xi, yi; /* intersection of line and perpendicular */ - - /* vertical line */ - if (x2 == x1) { - if (y1 <= y && y <= y2 || y2 <= y && y <= y1) - return (float) Math.abs(x - x1); // mouse is alongside - // line - return distance_to_endpoint(x1, y1, x2, y2, x, y); - } - - /* horizontal line */ - if (y2 == y1) { - if (x1 <= x && x <= x2 || x2 <= x && x <= x1) - return (float) Math.abs(y - y1); // mouse is alongside - // line - return distance_to_endpoint(x1, y1, x2, y2, x, y); - } - - m = ((float) (y2 - y1)) / ((float) (x2 - x1)); /* - * slope of the line - */ - c = -1.0f / m; /* slope of perpendicular line */ - d = (float) y - c * (float) x;/* - * perpendicular line through mouse - */ - b = (float) y1 - m * (float) x1; /* the line in the drawing */ - - // NOTE: round error - xi = (int) ProjMath.qint((d - b) / (m - c));// x intersection - yi = (int) ProjMath.qint(c * (float) xi + d);// y intersection - - /* - * If intersection is on the line segment distance is distance from - * mouse to it. - */ - if ((x1 <= xi && xi <= x2 || x2 <= xi && xi <= x1) - && (y1 <= yi && yi <= y2 || y2 <= yi && yi <= y1)) - return distance(xi, yi, x, y); - - /* distance is distance from mouse to nearest endpt */ - return distance_to_endpoint(x1, y1, x2, y2, x, y); - } - - /** - * Compute perpendicular distance from point to line. - *

- * - * @param x1 line x coord1 - * @param y1 line y coord1 - * @param x2 line x coord2 - * @param y2 line y coord2 - * @param x3 point x coord - * @param y3 point y coord - * @return float distance to line - * - */ - public final static float perpendicular_distance_to_line(int x1, int y1, - int x2, int y2, - int x3, int y3) { - - int x12 = x2 - x1; - int y12 = y2 - y1; - int x13 = x3 - x1; - int y13 = y3 - y1; - float D12 = distance(x1, y1, x2, y2); - - return Math.abs((/* Math.abs */(x12 * y13) - /* Math.abs */(x13 * y12)) - / D12); - } - - /** - * Computes the distance from a point to a line segment. - *

- * Variable usage as follows: - *

- *

    - *
  • x12 x distance from the first endpoint to the second. - *
  • y12 y distance from the first endpoint to the second. - *
  • x13 x distance from the first endpoint to point being tested. - *
  • y13 y distance from the first endpoint to point being tested. - *
  • x23 x distance from the second endpoint to point being tested. - *
  • y23 y distance from the second endpoint to point being tested. - *
  • D12 Length of the line segment. - *
  • pp distance along the line segment to the intersection of the - * perpendicular from the point to line extended. - *
- * - * Procedure: - *

- * - * Compute D12, the length of the line segment. Compute pp, the distance to - * the perpendicular. If pp is negative, the intersection is before the - * start of the line segment, so return the distance from the start point. - * If pp exceeds the length of the line segment, then the intersection is - * beyond the end point so return the distance of the point from the end - * point. Otherwise, return the absolute value of the length of the - * perpendicular line. The sign of the length of the perpendicular line - * indicates whether the point lies to the right or left of the line as one - * travels from the start point to the end point. - *

- * - * @param x1 line x coord1 - * @param y1 line y coord1 - * @param x2 line x coord2 - * @param y2 line y coord2 - * @param x3 point x coord - * @param y3 point y coord - * @return float distance to line segment - * - */ - public final static double distance_to_line(double x1, double y1, - double x2, double y2, - double x3, double y3) { - - // algorithm courtesy of Ray 1/16/98 - double x12 = x2 - x1; - double y12 = y2 - y1; - double x13 = x3 - x1; - double y13 = y3 - y1; - double D12 = Math.sqrt(x12 * x12 + y12 * y12); - double pp = (x12 * x13 + y12 * y13) / D12; - if (pp < 0.0) { - return (float) Math.sqrt(x13 * x13 + y13 * y13); - } - if (pp > D12) { - double x23 = x3 - x2; - double y23 = y3 - y2; - return Math.sqrt(x23 * x23 + y23 * y23); - } - return Math.abs(((x12 * y13 - y12 * x13) / D12)); - } - - /** - * Generates a line with width lw, returns an ArrayList of 4 x-y coords. - *

- * - * @param lw line width - * @param x1 line x coord1 - * @param y1 line y coord1 - * @param x2 line x coord2 - * @param y2 line y coord2 - * @return List int[] of x[], y[] - */ - public static List generateWideLine(int lw, int x1, int y1, - int x2, int y2) { - - ArrayList ret_val = new ArrayList(2); - int[] x = new int[4]; - int[] y = new int[4]; - - // calculate the offsets - // lw = lw -1; - int off1 = (int) lw / 2; - int off2 = (lw % 2 != 0) ? (int) lw / 2 + 1 : (int) lw / 2; - - // slope <= 1 - if (Math.abs((float) (y2 - y1) / (float) (x2 - x1)) <= 1f) { - x[0] = x[3] = x1; - x[1] = x[2] = x2; - - y[0] = y1 + off1; - y[1] = y2 + off1; - y[2] = y2 - off2; - y[3] = y1 - off2; - - ret_val.add(x); - ret_val.add(y); - } - - // slope > 1 - else { - x[0] = x1 + off1; - x[1] = x2 + off1; - x[2] = x2 - off2; - x[3] = x1 - off2; - - y[0] = y[3] = y1; - y[1] = y[2] = y2; - - ret_val.add(x); - ret_val.add(y); - } - - return ret_val; - } - - /** - * Generates a polygon or polyline with positive width lw. - *

- * Returns ArrayList of x-y array pairs of coordinates of polygon segments. - * the parameter altx must either be null, or an alternate array of points - * to draw. - *

- * - * @param lw line width - * @param xpts int[] x coords - * @param ypts int[] y coords - * @param altx int[] altx coords - * @param connect polygon or polyline? - * @return List int[] of x[], y[] - * - */ - final public static List generateWidePoly(int lw, int[] xpts, - int[] ypts, - int[] altx, - boolean connect) { - - return generateWidePoly(lw, xpts.length, xpts, ypts, altx, connect); - } - - /** - * Generates a polygon or polyline with positive width lw. - *

- * Returns ArrayList of x-y array pairs of coordinates of polygon segments. - * the parameter altx must either be null, or an alternate array of points - * to draw. - *

- * - * @param lw line width - * @param len numcoords - * @param xpts int[] x coords - * @param ypts int[] y coords - * @param altx int[] altx coords - * @param connect polygon or polyline? - * @return List int[] of x[], y[] - * - */ - final public static List generateWidePoly(int lw, int len, - int[] xpts, - int[] ypts, - int[] altx, - boolean connect) { - - // HACK - altx deprecated? - ArrayList ret_val = new ArrayList(len * 4); - int off1 = 0, off2 = 0; - int[] x = null, y = null, a_x = null; - float slope; - - int end = (connect) ? len : len - 1; - if (len <= 1) - return new ArrayList(); - // lw = lw -1; - - // calculate the offsets - HACK: +1 side not consistent... - off1 = (int) lw / 2; - off2 = (int) Math.ceil((float) lw / 2f); - - // System.out.print("DrawUtil.generateWidePoly Points for - // lw="+lw); - // for (int i=0;i 1 - else { - x[0] = xpts[i] + off1; - x[1] = xpts[j] + off1; - x[2] = xpts[j] - off2; - x[3] = xpts[i] - off2; - - y[0] = y[3] = ypts[i]; - y[1] = y[2] = ypts[j]; - - ret_val.add(x); - ret_val.add(y); - - if (altx != null) { - a_x = new int[4]; - a_x[0] = altx[i] + off1; - a_x[1] = altx[j] + off1; - a_x[2] = altx[j] - off2; - a_x[3] = altx[i] - off2; - ret_val.add(a_x); - ret_val.add(y); - } - } - } - return ret_val; - } - - /* - * public static void main(String[] args) { - * - * - * Debug.output("distance_to_line(0,0,4,4, 2,0): " + - * distance_to_line(0,0,4,4, 2,0)); - * Debug.output("OLD_distance_to_line(0,0,4,4, 2,0): " + - * OLD_distance_to_line(0,0,4,4, 2,0)); - * Debug.output("distance_to_line(0,0,4,4, 50,50): " + - * distance_to_line(0,0,4,4, 50,50)); - * Debug.output("OLD_distance_to_line(0,0,4,4, 50,50): " + - * OLD_distance_to_line(0,0,4,4, 50,50)); - * Debug.output("distance_to_line(-34,12,44,104, -44,-50): " + - * distance_to_line(-34,12,44,104, -44,-50)); - * Debug.output("OLD_distance_to_line(-34,12,44,104, -44,-50): " + - * OLD_distance_to_line(-34,12,44,104, -44,-50)); System.exit(0); // 3-4-5 - * triangle Debug.output(distance(0,0,3,4)); - * Debug.output(distance(0,0,-3,4)); Debug.output(distance(0,0,-3,-4)); - * Debug.output(distance(0,0,3,-4)); Debug.output(); - * - * Debug.output(distance_to_line(0,0,2,2, 0,2)); // root 2 - * Debug.output(distance_to_line(0,0,2,0, 0,2)); // 2 - * Debug.output(distance_to_line(0,0,2,0, -1,-1)); // root 2 - * Debug.output(distance_to_line(0,0,2,0, 1,0)); // 0 - * Debug.output(distance_to_line(0,0,2,2, 1,0)); // rounded! Debug.output(); - * - * int[] xpts = new int[3]; int[] ypts = new int[3]; xpts[0] = 0; ypts[0] = - * 0; xpts[1] = 3; ypts[1] = 0; xpts[2] = 3; ypts[2] = 4; - * - * Debug.output(closestPolyDistance(xpts, ypts, 0,4, true)); - * Debug.output(closestPolyDistance(xpts, ypts, 0,4, false));//3 - * - * xpts[0] = 0; ypts[0] = 0; xpts[1] = 2; ypts[1] = 0; xpts[2] = 2; ypts[2] - * = 2; Debug.output(closestPolyDistance(xpts, ypts, 0,1, true));//round - * Debug.output(closestPolyDistance(xpts, ypts, 0,1, false));//1 // - * linewidth testing - * - * Debug.output(""); ArrayList vec = generateWideLine(3, 0, 0, 5, 5); - * - * int[] x = (int[])vec.elementAt(0); int[] y = (int[])vec.elementAt(1); - * System.out.print("wide line: "); for (int i = 0; i -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Ellipsoid.java,v $ -// $RCSfile: Ellipsoid.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/01/15 19:38:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * A class representing a reference Ellipsoid for UTM calculations. - *

- * - * Adapted to Java by Colin Mummery (colin_mummery@agilent.com) from C++ code by - * Chuck Gantz (chuck.gantz@globalstar.com). - *

- * See http://en.wikipedia.org/wiki/Figure_of_the_Earth - */ -public class Ellipsoid { - - // The ellipsoids defined for this implementation - /** "Airy" */ - public final static Ellipsoid AIRY = new Ellipsoid("Airy", 6377563.0d, 0.00667054d); - /** "Australian National" */ - public final static Ellipsoid AUSTRALIAN_NATIONAL = new Ellipsoid("Australian National", 6378160.0d, 0.006694542d); - /** "Bessel 1841" */ - public final static Ellipsoid BESSEL_1841 = new Ellipsoid("Bessel 1841", 6377397.0d, 0.006674372d); - /** "Bessel 1841 (Nambia) " */ - public final static Ellipsoid BESSEL_1841_NAMIBIA = new Ellipsoid("Bessel 1841 Namibia", 6377484.0d, 0.006674372d); - /** "Clarke 1866" */ - public final static Ellipsoid CLARKE_1866 = new Ellipsoid("Clarke 1866", 6378206.0d, 0.006768658d); - /** "Clarke 1880" */ - public final static Ellipsoid CLARKE_1880 = new Ellipsoid("Clarke 1880", 6378249.0d, 0.006803511d); - /** "Everest" */ - public final static Ellipsoid EVEREST = new Ellipsoid("Everest", 6377276.0d, 0.006637847d); - /** "Fischer 1960 (Mercury) " */ - public final static Ellipsoid FISHER_1960_MERCURY = new Ellipsoid("Fisher 1960 Mercury", 6378166.0d, 0.006693422d); - /** "Fischer 1968" */ - public final static Ellipsoid FISHER_1968 = new Ellipsoid("Fisher 1968", 6378150.0d, 0.006693422d); - /** "GRS 1967" */ - public final static Ellipsoid GRS_1967 = new Ellipsoid("GRS 1967", 6378160.0d, 0.006694605d); - /** "GRS 1980" */ - public final static Ellipsoid GRS_1980 = new Ellipsoid("GRS 1980", 6378137.0d, 0.081819191d, 0.00669438d, 6356752.3141d); - /** "Helmert 1906" */ - public final static Ellipsoid HELMERT_1906 = new Ellipsoid("Helmert 1906", 6378200.0d, 0.006693422d); - /** "Hough" */ - public final static Ellipsoid HOUGH = new Ellipsoid("Hough", 6378270.0d, 0.00672267d); - /** "International" */ - public final static Ellipsoid INTERNATIONAL = new Ellipsoid("International", 6378388.0d, 0.08199189, 0.00672267d, 6356911.946d); - /** "Krassovsky" */ - public final static Ellipsoid KRASSOVSKY = new Ellipsoid("Krassovsky", 6378245.0d, 0.006693422d); - /** "Modified Airy" */ - public final static Ellipsoid MODIFIED_AIRY = new Ellipsoid("Modified Airy", 6377340.0d, 0.00667054d); - /** "Modified Everest" */ - public final static Ellipsoid MODIFIED_EVEREST = new Ellipsoid("Modified Everest", 6377304.0d, 0.006637847d); - /** "Modified Fischer 1960" */ - public final static Ellipsoid MODIFIED_FISCHER_1960 = new Ellipsoid("Modified Fischer", 6378155.0d, 0.006693422d); - /** "South American 1969" */ - public final static Ellipsoid SOUTH_AMERICAN_1969 = new Ellipsoid("South American 1969", 6378160.0d, 0.006694542d); - /** "WGS 60" */ - public final static Ellipsoid WGS_60 = new Ellipsoid("WSG 60", 6378165.0d, 0.006693422d); - /** "WGS 66" */ - public final static Ellipsoid WGS_66 = new Ellipsoid("WGS 66", 6378145.0d, 0.006694542d); - /** "WGS-72" */ - public final static Ellipsoid WGS_72 = new Ellipsoid("WGS 72", 6378135.0d, 0.006694318d); - /** "WGS-84" */ - public final static Ellipsoid WGS_84 = new Ellipsoid("WGS 84", 6378137.0d, 0.081819191d, 0.00669438d, 6356752.3142d); - - /** - * The display name for this ellipsoid. - */ - public final String name; - - /** - * The equitorial radius for this ellipsoid. - */ - public final double radius; - - /** - * The polar radius for this ellipsoid. - */ - public final double polarRadius; - - /** - * The ellipsoid's eccentricity. - */ - public final double ecc; - - /** - * The square of this ellipsoid's eccentricity. - */ - public final double eccsq; - - /** - * Constructs a new Ellipsoid instance. - * - * @param radius The earth radius for this ellipsoid. - * @param eccsq The square of the eccentricity for this ellipsoid. - */ - public Ellipsoid(String name, double radius, double eccsq) { - this(name, radius, eccsq, Double.NaN, Double.NaN); - } - - /** - * Constructs a new Ellipsoid instance. - * - * @param name The name of the ellipsoid. - * @param equitorialRadius The earth equitorial radius for this ellipsoid. - * @param ecc The eccentricity for this ellipsoid. - * @param eccsq The square of the eccentricity for this ellipsoid. - * @param polarRadius The earth polar radius for this ellipsoid. - */ - public Ellipsoid(String name, double equitorialRadius, double ecc, double eccsq, double polarRadius) { - this.name = name; - this.radius = equitorialRadius; - this.ecc = ecc; - this.eccsq = eccsq; - this.polarRadius = polarRadius; - } - - /** - * Returns an array of all available ellipsoids in alphabetical order by - * name. - * - * @return An Ellipsoid[] array containing all the available ellipsoids - */ - public static Ellipsoid[] getAllEllipsoids() { - - Ellipsoid[] all = { AIRY, AUSTRALIAN_NATIONAL, BESSEL_1841, - BESSEL_1841_NAMIBIA, CLARKE_1866, CLARKE_1880, EVEREST, - FISHER_1960_MERCURY, FISHER_1968, GRS_1967, GRS_1980, - HELMERT_1906, HOUGH, INTERNATIONAL, KRASSOVSKY, MODIFIED_AIRY, - MODIFIED_EVEREST, MODIFIED_FISCHER_1960, SOUTH_AMERICAN_1969, - WGS_60, WGS_66, WGS_72, WGS_84 }; - - return all; - } - - /** - * Given the name of an Ellipsoid, find the object for it out of the - * possible selections. Returns null if the Ellipsoid isn't found. - * - * @param name - * @return Ellipsoid for given name, null if not found. - */ - public static Ellipsoid getByName(String name) { - Ellipsoid[] all = getAllEllipsoids(); - if (name != null && name.length() > 0) { - name = name.replace('_', ' '); - - for (int i = 0; i < all.length; i++) { - if (name.equalsIgnoreCase(all[i].name)) { - return all[i]; - } - } - } - - return null; - } - - /** - * Returns a string representation of the object. - * - * @return String representation - */ - public String toString() { - return "Ellipsoid[name=" + name + ", radius=" + radius + ", eccsq=" - + eccsq + "]"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/EqualArc.java b/src/core/src/main/java/com/bbn/openmap/proj/EqualArc.java deleted file mode 100644 index 50a6f473d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/EqualArc.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/EqualArc.java,v $ -// $RCSfile: EqualArc.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * A designator interface to let layers know that a Projection is an - * Equal Arc projection, meaning that the variations in latitude and - * longitude are constant. - */ -public interface EqualArc extends Projection { - - /** - * Returns the x pixel constant of the projection. This was - * calculated when the projection was created. Represents the - * number of pixels around the earth (360 degrees). - */ - public double getXPixConstant(); - - /** - * Returns the y pixel constant of the projection. This was - * calculated when the projection was created. Represents the - * number of pixels from 0 to 90 degrees. - */ - public double getYPixConstant(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/GeoProj.java b/src/core/src/main/java/com/bbn/openmap/proj/GeoProj.java deleted file mode 100644 index ef9d9a3f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/GeoProj.java +++ /dev/null @@ -1,1570 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoProj.java,v $ -//$Revision: 1.7 $ -//$Date: 2009/02/25 22:34:04 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Arc2D; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * GeoProj is the base class of all Projections that deal with coordinates on - * the world sphere. - *

- * You probably don't want to use this class unless you are hacking your own - * projections, or need extended functionality. To be safe you will want to use - * the Projection interface. - * - *

Notes:

- * - *
    - * - *
  • We deal in radians internally. The outside world usually deals in decimal - * degrees. If you have data in radians, DON'T bother converting it into DD's - * since we'll convert it right back into radians for the projection step. For - * more optimization tips, see the OMPoly class. - * - *
  • We default to projecting our data using the WGS84 datum. You can change - * the appropriate parameters of the projection after construction if you need - * to use a different datum. And of course you can derive your own projections - * from this class as you see fit. - * - *
  • The forward() and inverse() methods are currently implemented using the - * algorithms given in John Synder's Map Projections --A Working Manual - * for the sphere. This is sufficient for display purposes, but you should use - * ellipsoidal algorithms in the GreatCircle class to calculate distance and - * azimuths on the ellipsoid. See each projection individually for more - * information. - * - *
  • This class is not thread safe. If two or more threads are using the same - * Proj, then they could disrupt each other. Occasionally you may need to call a - * set method of this class. This might interfere with another - * thread that's using the same projection for forwardPoly or - * another Projection interface method. In general, you should not need to call - * any of the set methods directly, but let the MapBean do it for - * you. - * - *
  • All the various forwardOBJ() methods for ArrayList graphics - * ultimately go through forwardPoly(). - * - *
- * - * @see Projection - * @see Cylindrical - * @see Mercator - * @see CADRG - * @see Azimuth - * @see Orthographic - * @see Planet - * @see GreatCircle - * @see com.bbn.openmap.omGraphics.OMPoly - * - */ -public abstract class GeoProj extends Proj { - private static final long serialVersionUID = 1L; - - // Used for generating segments of List objects - protected static transient int NUM_DEFAULT_CIRCLE_VERTS = 64; - - // SOUTH_POLE <= phi <= NORTH_POLE (radians) - // -DATELINE <= lambda <= DATELINE (radians) - - /** - * North pole latitude in radians. - */ - public final static transient float NORTH_POLE = ProjMath.NORTH_POLE_F; - - /** - * South pole latitude in radians. - */ - public final static transient float SOUTH_POLE = ProjMath.SOUTH_POLE_F; - - /** - * Dateline longitude in radians. - */ - public final static transient float DATELINE = ProjMath.DATELINE_F; - - // Used for generating segments of ArrayList objects - protected static transient int NUM_DEFAULT_GREAT_SEGS = 512; - - // pixels per meter (an extra scaling factor). - protected double pixelsPerMeter; // PPM - protected double planetRadius;// EARTH_RADIUS - protected double planetPixelRadius; // EARTH_PIX_RADIUS - protected double planetPixelCircumference; // EARTH_PIX_CIRCUMFERENCE - protected double scaled_radius; - - protected Mercator mercator = null; // for rhumbline calculations - - public GeoProj(LatLonPoint center, float s, int w, int h) { - super(center, s, w, h); - - // for rhumbline projecting - if (!(this instanceof Mercator)) { - mercator = new Mercator(center, getRhumbLineMercatorScale((float) scale), width, height); - } - } - - protected void init() { - - centerX = wrapLongitude(Math.toRadians(centerX)); - centerY = normalizeLatitude(Math.toRadians(centerY)); - - // pixels per meter (an extra scaling factor). - pixelsPerMeter = Planet.defaultPixelsPerMeter; // PPM - planetRadius = Planet.wgs84_earthEquatorialRadiusMeters_D;// EARTH_RADIUS - planetPixelRadius = planetRadius * pixelsPerMeter; // EARTH_PIX_RADIUS - planetPixelCircumference = MoreMath.TWO_PI_D * planetPixelRadius; // EARTH_PIX_CIRCUMFERENCE - // the scaled_radius should also be set in computeParameters with the - // scale that has been checked against min/max scale - scaled_radius = planetPixelRadius / scale; - /* good for cylindrical */ - maxscale = planetPixelCircumference / width; - } - - /** - * Set the pixels per meter constant. - * - * @param ppm int Pixels Per Meter scale-factor constant - */ - public void setPPM(double ppm) { - pixelsPerMeter = ppm; - if (pixelsPerMeter < 1) { - pixelsPerMeter = 1; - } - computeParameters(); - } - - /** - * Get the pixels-per-meter constant. - * - * @return int Pixels Per Meter scale-factor constant - */ - public double getPPM() { - return pixelsPerMeter; - } - - /** - * Set the planet radius. - * - * @param radius float planet radius in meters - */ - public void setPlanetRadius(double radius) { - planetRadius = radius; - if (planetRadius < 1.0f) { - planetRadius = 1.0f; - } - computeParameters(); - } - - /** - * Get the planet radius. - * - * @return float radius of planet in meters - */ - public double getPlanetRadius() { - return planetRadius; - } - - /** - * Get the planet pixel radius. - * - * @return float radius of planet in pixels - */ - public double getPlanetPixelRadius() { - return planetPixelRadius; - } - - /** - * Get the planet pixel circumference. - * - * @return float circumference of planet in pixels - */ - public double getPlanetPixelCircumference() { - return planetPixelCircumference; - } - - /** - * Set center point of projection. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - */ - public void setCenter(float lat, float lon) { - setCenter((double) lat, (double) lon, false); - } - - /** - * Set center point of projection. - * - * @param lat double latitude in decimal degrees - * @param lon double longitude in decimal degrees - */ - public void setCenter(double lat, double lon) { - setCenter(lat, lon, false); - } - - /** - * Set center point of projection. - * - * @param lat double latitude in decimal degrees - * @param lon double longitude in decimal degrees - */ - public void setCenter(double lat, double lon, boolean isRadians) { - if (!isRadians) { - lat = Math.toRadians(lat); - lon = Math.toRadians(lon); - } - - centerX = wrapLongitude(lon); - centerY = normalizeLatitude(lat); - computeParameters(); - projID = null; - } - - /** - * Get center point of projection. - * - * @return LatLonPoint center of projection, created just for you. - */ - public LatLonPoint getCenter() { - return new LatLonPoint.Double(centerY, centerX, true); - } - - /** - * Returns a center LatLonPoint that was provided, with the location filled into - * the LatLonPoint object. Calls Point2D.setLocation(x, y). - */ - public T getCenter(T center) { - center.setLocation(Math.toDegrees(centerX), Math.toDegrees(centerY)); - return center; - } - - public void setScale(float s) { - super.setScale(s); - // for rhumbline projecting - if (mercator != null) { - mercator.setScale(getRhumbLineMercatorScale(s)); - } - } - - /** - * Checks the provided scale and makes sure it's not bigger than what would give - * good coords. - * - * @param base - * @return return limited version of base. - */ - protected float getRhumbLineMercatorScale(float base) { - if (base > 1000000) { - return 1000000; - } - return base; - } - - /** - * Sets radian latitude to something sane. - *

- * Normalizes the latitude according to the particular projection. - * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - * @see ProjMath#normalizeLatitude(float, float) - * @see LatLonPoint#normalizeLatitude(float) - */ - public float normalizeLatitude(float lat) { - return (float) normalizeLatitude((double) lat); - } - - abstract public double normalizeLatitude(double lat); - - /** - * Sets radian longitude to something sane. - * - * @param lon float longitude in radians - * @return float longitude (-PI <= x < PI) - * @see ProjMath#wrapLongitude(float) - * @see LatLonPoint#wrapLongitude(float) - */ - public final static float wrapLongitude(float lon) { - return ProjMath.wrapLongitude(lon); - } - - public final static double wrapLongitude(double lon) { - return ProjMath.wrapLongitude(lon); - } - - public final static double wrapLongitudeDeg(double lon) { - return ProjMath.wrapLongitudeDeg(lon); - } - - /** - * @deprecated use normalizeLatitude() instead. - */ - public final double normalize_latitude(double lat) { - return normalizeLatitude(lat); - } - - /** - * @deprecated use wrapLongitude() instead. - */ - public final static double wrap_longitude(double lon) { - return wrapLongitude(lon); - } - - /** - * Pan the map/projection. - *

- * Example pans: - *

    - *
  • pan(180, c) pan south `c' degrees - *
  • pan(-90, c) pan west `c' degrees - *
  • pan(0, c) pan north `c' degrees - *
  • pan(90, c) pan east `c' degrees - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees - */ - public void pan(double Az, double c) { - setCenter(RhumbCalculator.calculatePointOnRhumbLine(getCenter(), Math.toRadians(Az), Math.toRadians(c))); - } - - /** - * Pan the map/projection. Figures on an ellipse based around the center of the - * map in the direction provided. - * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - public void pan(double Az) { - double angle = Math.toRadians(90 - Az); - int w2 = getWidth() / 2; - int h2 = getHeight() / 2; - LatLonPoint newLoc = inverse(w2 + (w2 * Math.cos(angle)), h2 + (h2 * Math.sin(angle))); - double dist = RhumbCalculator.getDistanceBetweenPoints(getCenter(), newLoc); - pan(Az, Math.toDegrees(dist)); - } - - /** - * Stringify the projection. - * - * @return stringified projection - * @see #getProjectionID - */ - public String toString() { - return (" radius=" + planetRadius + " ppm=" + pixelsPerMeter + " center(" + centerY + ":" + centerX + ") scale=" - + scale + " maxscale=" + maxscale + " minscale=" + minscale + " width=" + width + " height=" + height - + "]"); - } - - /** - * Copies this projection. - * - * @return a copy of this projection. - */ - public Object clone() { - GeoProj proj = (GeoProj) super.clone(); - if (mercator != null) { - proj.mercator = (Mercator) mercator.clone(); - } - return proj; - } - - public boolean isPlotable(Point2D point) { - if (point instanceof LatLonPoint) { - return isPlotable(point.getY(), point.getX()); - } - - // Well, then, what is it? - return false; - } - - /** - * Forward project a rhumbline poly. - *

- * Draws rhumb lines between vertices of poly. Remember to specify vertices in - * radians! Check in-code comments for details about the algorithm. - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardRhumbPoly(float[] rawllpts, int nsegs, boolean isFilled) { - - // IDEA: - // Rhumblines are straight in the Mercator projection. - // So we can use the Mercator projection to calculate - // vertices along the rhumbline between two points. But - // if there's a better way to calculate loxodromes, - // someone please chime in (openmap@bbn.com)... - // - // ALG: - // Project pairs of vertices through the Mercator - // projection into screen XY space, pick intermediate - // segment points along the straight XY line, then - // convert all vertices back into LatLon space. Pass the - // augmented vertices to _forwardPoly() to be drawn as - // straight segments. - // - // WARNING: - // The algorithm fixes the Cylindrical-wrapping - // problem, and thus duplicates some code in - // Cylindrical._forwardPoly() - - if (this instanceof Mercator) {// simple - return _forwardPoly(rawllpts, LineType.Straight, nsegs, isFilled); - } - - int i, n, xp, flag = 0, xadj = 0, totalpts = 0; - Point from = new Point(0, 0); - Point to = new Point(0, 0); - int len = rawllpts.length; - - float[][] augllpts = new float[len >>> 1][0]; - - // lock access to object global, since this is probably not - // cloned and different layers may be accessing this. - // synchronized (mercator) { - - // we now create a clone of the mercator variable in - // makeClone(), so since different objects should be using - // their clone instead of the main projection, the - // synchronization should be unneeded. - - // use mercator projection to calculate rhumblines. - // mercator.setParms( - // new LatLonPoint(ctrLat, ctrLon, true), - // scale, width, height); - - // Unnecessary to set parameters !! ^^^^^ - - // project everything through the Mercator projection, - // building up lat/lon points along the original rhumb - // line between vertices. - mercator.forward(rawllpts[0], rawllpts[1], from, true); - xp = from.x; - for (i = 0, n = 2; n < len; i++, n += 2) { - mercator.forward(rawllpts[n], rawllpts[n + 1], to, true); - // segment crosses longitude along screen edge - if (Math.abs(xp - to.x) >= mercator.half_world) { - flag += (xp < to.x) ? -1 : 1;// inc/dec the wrap - // count - xadj = flag * mercator.world.x;// adjustment to x - // coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = to.x; - if (flag != 0) { - to.x += xadj;// adjust x coordinate - } - - augllpts[i] = mercator.rhumbProject(from, to, false, nsegs); - totalpts += augllpts[i].length; - from.x = to.x; - from.y = to.y; - } - - LatLonPoint llp = new LatLonPoint.Double(); - mercator.inverse(from.x, from.y, llp); - // }// end synchronized around mercator - - augllpts[i] = new float[2]; - augllpts[i][0] = (float) llp.getRadLat(); - augllpts[i][1] = (float) llp.getRadLon(); - totalpts += 2; - - // put together all the points - float[] newllpts = new float[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - // Debug.output("copying " + augllpts[i].length + " - // floats"); - System.arraycopy(/* src */augllpts[i], 0, /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - // Debug.output("done copying " + totalpts + " total floats"); - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a rhumbline poly. - *

- * Draws rhumb lines between vertices of poly. Remember to specify vertices in - * radians! Check in-code comments for details about the algorithm. - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardRhumbPoly(double[] rawllpts, int nsegs, boolean isFilled) { - - // IDEA: - // Rhumblines are straight in the Mercator projection. - // So we can use the Mercator projection to calculate - // vertices along the rhumbline between two points. But - // if there's a better way to calculate loxodromes, - // someone please chime in (openmap@bbn.com)... - // - // ALG: - // Project pairs of vertices through the Mercator - // projection into screen XY space, pick intermediate - // segment points along the straight XY line, then - // convert all vertices back into LatLon space. Pass the - // augmented vertices to _forwardPoly() to be drawn as - // straight segments. - // - // WARNING: - // The algorithm fixes the Cylindrical-wrapping - // problem, and thus duplicates some code in - // Cylindrical._forwardPoly() - - if (this instanceof Mercator) {// simple - return _forwardPoly(rawllpts, LineType.Straight, nsegs, isFilled); - } - - int i, n, xp, flag = 0, xadj = 0, totalpts = 0; - Point from = new Point(0, 0); - Point to = new Point(0, 0); - int len = rawllpts.length; - - double[][] augllpts = new double[len >>> 1][0]; - - // lock access to object global, since this is probably not - // cloned and different layers may be accessing this. - // synchronized (mercator) { - - // we now create a clone of the mercator variable in - // makeClone(), so since different objects should be using - // their clone instead of the main projection, the - // synchronization should be unneeded. - - // use mercator projection to calculate rhumblines. - // mercator.setParms( - // new LatLonPoint(ctrLat, ctrLon, true), - // scale, width, height); - - // Unnecessary to set parameters !! ^^^^^ - - // project everything through the Mercator projection, - // building up lat/lon points along the original rhumb - // line between vertices. - mercator.forward(rawllpts[0], rawllpts[1], from, true); - xp = from.x; - for (i = 0, n = 2; n < len; i++, n += 2) { - mercator.forward(rawllpts[n], rawllpts[n + 1], to, true); - // segment crosses longitude along screen edge - if (Math.abs(xp - to.x) >= mercator.half_world) { - flag += (xp < to.x) ? -1 : 1;// inc/dec the wrap - // count - xadj = flag * mercator.world.x;// adjustment to x - // coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = to.x; - if (flag != 0) { - to.x += xadj;// adjust x coordinate - } - - augllpts[i] = mercator.rhumbProjectDouble(from, to, false, nsegs); - totalpts += augllpts[i].length; - from.x = to.x; - from.y = to.y; - } - - LatLonPoint llp = new LatLonPoint.Double(); - mercator.inverse(from, llp); - // }// end synchronized around mercator - - augllpts[i] = new double[2]; - augllpts[i][0] = llp.getRadLat(); - augllpts[i][1] = llp.getRadLon(); - totalpts += 2; - - // put together all the points - double[] newllpts = new double[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - // Debug.output("copying " + augllpts[i].length + " - // floats"); - System.arraycopy(/* src */augllpts[i], 0, /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - // Debug.output("done copying " + totalpts + " total floats"); - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a greatcircle poly. - *

- * Draws great circle lines between vertices of poly. Remember to specify - * vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardGreatPoly(float[] rawllpts, int nsegs, boolean isFilled) { - int i, j, k, totalpts = 0; - - Point from = new Point(); - Point to = new Point(); - - int end = rawllpts.length >>> 1; - float[][] augllpts = new float[end][0]; - end -= 1;// stop before last segment - - // calculate extra vertices between all the original segments. - forward(rawllpts[0], rawllpts[1], from, true); - for (i = 0, j = 0, k = 2; i < end; i++, j += 2, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], to, true); - augllpts[i] = getGreatVertices(rawllpts[j], rawllpts[j + 1], rawllpts[k], rawllpts[k + 1], from, to, false, - nsegs); - from.x = to.x; - from.y = to.y; - totalpts += augllpts[i].length; - } - augllpts[i] = new float[2]; - augllpts[i][0] = rawllpts[j]; - augllpts[i][1] = rawllpts[j + 1]; - totalpts += 2; - - // put together all the points - float[] newllpts = new float[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - System.arraycopy(/* src */augllpts[i], 0, /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a greatcircle poly. - *

- * Draws great circle lines between vertices of poly. Remember to specify - * vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardGreatPoly(double[] rawllpts, int nsegs, boolean isFilled) { - int i, j, k, totalpts = 0; - - Point from = new Point(); - Point to = new Point(); - - int end = rawllpts.length >>> 1; - double[][] augllpts = new double[end][0]; - end -= 1;// stop before last segment - - // calculate extra vertices between all the original segments. - forward(rawllpts[0], rawllpts[1], from, true); - for (i = 0, j = 0, k = 2; i < end; i++, j += 2, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], to, true); - augllpts[i] = getGreatVertices(rawllpts[j], rawllpts[j + 1], rawllpts[k], rawllpts[k + 1], from, to, false, - nsegs); - from.x = to.x; - from.y = to.y; - totalpts += augllpts[i].length; - } - augllpts[i] = new double[2]; - augllpts[i][0] = rawllpts[j]; - augllpts[i][1] = rawllpts[j + 1]; - totalpts += 2; - - // put together all the points - double[] newllpts = new double[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - System.arraycopy(/* src */augllpts[i], 0, /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Get the vertices along the great circle between two points. - * - * @param latp previous float latitude - * @param lonp previous float longitude - * @param latn next float latitude - * @param lonn next float longitude - * @param from Point - * @param to Point - * @param include_last include n or n+1 points of the n segments? - * @return float[] lat/lon points in RADIANS! - * - */ - private float[] getGreatVertices(float latp, float lonp, float latn, float lonn, Point from, Point to, - boolean include_last, int nsegs) { - if (nsegs < 1) { - // calculate pixel distance - int dist = DrawUtil.pixel_distance(from.x, from.y, to.x, to.y); - - /* - * determine what would be a decent number of segments to draw. HACK: this is - * hardcoded calculated by what might look ok on screen. We also put a cap on - * the number of extra segments we draw. - */ - nsegs = dist >> 3;// dist/8 - if (nsegs == 0) { - nsegs = 1; - } else if (nsegs > NUM_DEFAULT_GREAT_SEGS) { - nsegs = NUM_DEFAULT_GREAT_SEGS; - } - - // Debug.output( - // "("+from.x+","+from.y+")("+to.x+","+to.y+") - // dist="+dist+" nsegs="+nsegs); - } - - // both of these return float[] radian coordinates! - return GreatCircle.greatCircle(latp, lonp, latn, lonn, nsegs, include_last); - } - - /** - * Get the vertices along the great circle between two points. - * - * @param latp previous double latitude - * @param lonp previous double longitude - * @param latn next double latitude - * @param lonn next double longitude - * @param from Point - * @param to Point - * @param include_last include n or n+1 points of the n segments? - * @param nsegs number of segments to create, or -1 to let algorithm - * figure it out - * @return double[] lat/lon points in RADIANS! - * - */ - private double[] getGreatVertices(double latp, double lonp, double latn, double lonn, Point from, Point to, - boolean include_last, int nsegs) { - if (nsegs < 1) { - // calculate pixel distance - int dist = DrawUtil.pixel_distance(from.x, from.y, to.x, to.y); - - /* - * determine what would be a decent number of segments to draw. HACK: this is - * hardcoded calculated by what might look ok on screen. We also put a cap on - * the number of extra segments we draw. - */ - nsegs = dist >> 3;// dist/8 - if (nsegs == 0) { - nsegs = 1; - } else if (nsegs > NUM_DEFAULT_GREAT_SEGS) { - nsegs = NUM_DEFAULT_GREAT_SEGS; - } - - // Debug.output( - // "("+from.x+","+from.y+")("+to.x+","+to.y+") - // dist="+dist+" nsegs="+nsegs); - } - - // both of these return float[] radian coordinates! - return GreatCircle.greatCircle(latp, lonp, latn, lonn, nsegs, include_last); - } - - /** - * Check for complicated linetypes. - *

- * This depends on the line and this projection. - * - * @param ltype int LineType - * @return boolean - */ - public boolean isComplicatedLineType(int ltype) { - switch (ltype) { - case LineType.Straight: - return false; - case LineType.Rhumb: - return (getClass() == Mercator.class) ? false : true; - case LineType.GreatCircle: - return true/* - * (getProjectionType() == Gnomonic.GnomonicType) ? false : true - */; - default: - Debug.error("Proj.isComplicatedLineType: invalid LineType!"); - return false; - } - } - - /** - * Generates a complicated poly. - * - * @param rawllpts LatLonPofloat[] - * @param ltype line type - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList - */ - protected ArrayList doPolyDispatch(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - switch (ltype) { - case LineType.Rhumb: - return forwardRhumbPoly(rawllpts, nsegs, isFilled); - case LineType.GreatCircle: - return forwardGreatPoly(rawllpts, nsegs, isFilled); - case LineType.Straight: - Debug.error("Proj.doPolyDispatch: Bad Dispatch!\n"); - return new ArrayList(0); - default: - Debug.error("Proj.doPolyDispatch: Invalid LType!\n"); - return new ArrayList(0); - } - } - - /** - * Generates a complicated poly. - * - * @param rawllpts LatLonPofloat[] - * @param ltype line type - * @param nsegs number of segments to draw for greatcircle or rhumb lines (if - * < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList int[] - */ - protected ArrayList doPolyDispatch(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - switch (ltype) { - case LineType.Rhumb: - return forwardRhumbPoly(rawllpts, nsegs, isFilled); - case LineType.GreatCircle: - return forwardGreatPoly(rawllpts, nsegs, isFilled); - case LineType.Straight: - Debug.error("Proj.doPolyDispatch: Bad Dispatch!\n"); - return new ArrayList(0); - default: - Debug.error("Proj.doPolyDispatch: Invalid LType!\n"); - return new ArrayList(0); - } - } - - // /** - // * Given a couple of points representing a bounding box, find out what the - // * scale should be in order to make those points appear at the corners of - // * the projection. - // * - // * @param ll1 the upper left coordinates of the bounding box. - // * @param ll2 the lower right coordinates of the bounding box. - // * @param point1 a java.awt.Point reflecting a pixel spot on the - // projection - // * that matches the ll1 coordinate, the upper left corner of the area - // * of interest. - // * @param point2 a java.awt.Point reflecting a pixel spot on the - // projection - // * that matches the ll2 coordinate, usually the lower right corner of - // * the area of interest. - // */ - // public float getScale(Point2D ll1, Point2D ll2, Point2D point1, - // Point2D point2) { - // if (ll1 instanceof LatLonPoint && ll2 instanceof LatLonPoint) { - // return getScale(LatLonPoint.getDouble(ll1), - // LatLonPoint.getDouble(ll2), - // point1, - // point2); - // } - // - // return getScale(); - // } - - /** - * Given a couple of points representing a bounding box, find out what the scale - * should be in order to make those points appear at the corners of the - * projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.Point reflecting a pixel spot on the projection that - * matches the ll1 coordinate, the upper left corner of the area - * of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection that - * matches the ll2 coordinate, usually the lower right corner of - * the area of interest. - */ - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2) { - - try { - - double deltaDegrees; - double pixPerDegree; - // double deltaPix; - // double dx = Math.abs(point2.getX() - point1.getX()); - // double dy = Math.abs(point2.getY() - point1.getY()); - - // TODO: mercator getScale is wrong for screens in portrait mode, - // that is dx point2.getX()) { - lat1 = ll1.getY(); - lon1 = ll1.getX(); - ll1.setLocation(ll2); - ll2.setLocation(lon1, lat1); - } - - lon1 = ll1.getX(); - lon2 = ll2.getX(); - - // allow for crossing dateline - if (lon1 > lon2) { - dlon = (180 - lon1) + (180 + lon2); - } else { - dlon = lon2 - lon1; - } - - deltaDegrees = dlon; - // deltaPix = dx; - - // This might not be correct for all projection types - pixPerDegree = getPlanetPixelCircumference() / 360.0; - // } - - // The new scale, need it to match the current projection width. - return (float) (pixPerDegree / (getWidth() / deltaDegrees)); - } catch (NullPointerException npe) { - com.bbn.openmap.util.Debug.error("ProjMath.getScale(): caught null pointer exception."); - return Float.MAX_VALUE; - } - } - - /** - * Forward project a point. - */ - public Point2D forward(Point2D llp, Point2D pt) { - return forward(llp.getY(), llp.getX(), pt, false); - } - - /** - * Forward project a LatLonPoint. - *

- * Forward projects a LatLon point into XY space. Returns a Point. - * - * @param llp LatLonPoint to be projected - * @return Point (new) - */ - public Point2D forward(Point2D llp) { - return forward(llp.getY(), llp.getX(), new Point2D.Double(), false); - } - - /** - * Project the point into view space. - * - * @param lat latitude in decimal degrees. - * @param lon longitue in decimal degrees. - */ - public Point2D forward(double lat, double lon, Point2D pt) { - return forward(lat, lon, pt, false); - } - - /** - * Project the point into view space. - * - * @param lat latitude - * @param lon longitude - * @param pt return point - * @param isRadian true if lat/lon are radians instead of decimal degrees - * @return Point2D for projected point - */ - public Point2D forward(float lat, float lon, Point2D pt, boolean isRadian) { - return forward((double) lat, (double) lon, pt, isRadian); - } - - /** - * Project the point into view space. - * - * @param lat latitude - * @param lon longitude - * @param pt return point - * @param isRadian true if lat/lon are radians instead of decimal degrees - * @return Point2D for projected point - */ - abstract public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian); - - /** - * Inverse project a Point from x,y space to LatLon space. - * - * @param point x,y Point - * @return LatLonPoint (new) - */ - public LatLonPoint inverse(Point2D point) { - return inverse(point.getX(), point.getY(), new LatLonPoint.Double()); - } - - /** - * Inverse project x,y coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @return LatLonPoint (new) - * @see #inverse(Point2D) - */ - public LatLonPoint inverse(double x, double y) { - return inverse(x, y, new LatLonPoint.Double()); - } - - /** - * Returns the Point2D provided if it is a LatLonPoint, otherwise it creates a - * LatLonPoint.Double and transfers the values from the provided Point2D object. - */ - protected LatLonPoint assertLatLonPoint(Point2D p2d) { - if (p2d instanceof LatLonPoint) { - return (LatLonPoint) p2d; - } else { - return new LatLonPoint.Double(p2d.getY(), p2d.getX()); - } - } - - /** - * Forward project a LatLon Line. - *

- * Returns a ArrayList of (x[], y[]) coordinate pair(s) of the projected - * line(s). - * - * RESTRICTIONS: A line segment must be - * less than 180 degrees of arc (half the circumference of the world). If you - * need to draw a longer line, then draw several several individual segments of - * less than 180 degrees, or draw a single polyline of those segments. - *

- * We make this restriction because from any point on a sphere, you can reach - * any other point with a maximum traversal of 180degrees of arc. - *

- * Furthermore, for the Cylindrical family of projections, a line must be < - * 180 degrees of arc in longitudinal extent. In other words, the difference of - * longitudes between both vertices must be < 180 degrees. Same as above: if - * you need a long line, you must break it into several segments. - * - * @param ll1 LatLonPoint - * @param ll2 LatLonPoint - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline line - * types, and if < 1, this value is generated internally) - * @return ArrayList int[] - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - * - */ - public ArrayList forwardLine(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs) { - double[] rawllpts = { ll1.getRadLat(), ll1.getRadLon(), ll2.getRadLat(), ll2.getRadLon() }; - return forwardPoly(rawllpts, ltype, nsegs, false); - } - - /** - * Forward project a lat/lon Line. - * - * @see #forwardLine(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardLine(LatLonPoint ll1, LatLonPoint ll2, int ltype) { - return forwardLine(ll1, ll2, ltype, -1); - } - - /** - * Forward project a rectangle defined by an upper left point and a lower right - * point. - *

- * Returns a ArrayList of (x[], y[]) coordinate pairs of the projected points. - *

- * Rects have the same restrictions as polys - * and lines . - * - * @param ll1 LatLonPoint of northwest corner - * @param ll2 LatLonPoint of southeast corner - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline line - * types, and if < 1, this value is generated internally) - * @see #forwardPoly - * @return ArrayList int[] - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs, boolean isFilled) { - double[] rawllpts = { ll1.getRadLat(), ll1.getRadLon(), ll1.getRadLat(), ll2.getRadLon(), ll2.getRadLat(), - ll2.getRadLon(), ll2.getRadLat(), ll1.getRadLon(), - // connect: - ll1.getRadLat(), ll1.getRadLon() }; - return forwardPoly(rawllpts, ltype, nsegs, isFilled); - } - - /** - * Forward project a lat/lon Rectangle. - * - * @see #forwardRect(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype) { - return forwardRect(ll1, ll2, ltype, -1, false); - } - - /** - * Forward project a lat/lon Rectangle. * - * - * @param ll1 LatLonPoint of northwest corner - * @param ll2 LatLonPoint of southeast corner - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline line - * types, and if < 1, this value is generated internally) - * @see #forwardRect(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs) { - return forwardRect(ll1, ll2, ltype, nsegs, false); - } - - /** - * Forward project an arc. - * - * @param c LatLonPoint center - * @param radians boolean radius in radians? - * @param radius radius in radians or decimal degrees - * @param start the starting angle of the arc, zero being North up. Units are - * dependent on radians parameter - the start parameter is in - * radians if radians equals true, decimal degrees if not. - * @param extent the angular extent angle of the arc, zero being no length. - * Units are dependent on radians parameter - the extent - * parameter is in radians if radians equals true, decimal - * degrees if not. - */ - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, double start, double extent) { - return forwardArc(c, radians, radius, -1, start, extent, java.awt.geom.Arc2D.OPEN); - } - - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, int nverts, double start, - double extent) { - return forwardArc(c, radians, radius, nverts, start, extent, java.awt.geom.Arc2D.OPEN); - } - - /** - * Forward project a Lat/Lon Arc. - *

- * Arcs have the same restrictions as polys . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - * @param start the starting angle of the arc, zero being North up. Units are - * dependent on radians parameter - the start parameter is in - * radians if radians equals true, decimal degrees if not. - * @param extent the angular extent angle of the arc, zero being no length. - * Units are dependent on radians parameter - the extent - * parameter is in radians if radians equals true, decimal - * degrees if not. - * @param arcType type of arc to create - see java.awt.geom.Arc2D for (OPEN, - * CHORD, PIE). Arc2D.OPEN means that the just the points for the - * curved edge will be provided. Arc2D.PIE means that addition - * lines from the edge of the curve to the center point will be - * added. Arc2D.CHORD means a single line from each end of the - * curve will be drawn. - */ - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, int nverts, double start, - double extent, int arcType) { - // HACK-need better decision for number of vertices. - if (nverts < 3) - nverts = NUM_DEFAULT_CIRCLE_VERTS; - - double[] rawllpts; - - switch (arcType) { - case Arc2D.PIE: - rawllpts = new double[(nverts << 1) + 4];// *2 for pairs +4 - // connect - break; - case Arc2D.CHORD: - rawllpts = new double[(nverts << 1) + 2];// *2 for pairs +2 - // connect - break; - default: - rawllpts = new double[(nverts << 1)];// *2 for pairs, no - // connect - } - - GreatCircle.earthCircle(c.getRadLat(), c.getRadLon(), (radians) ? radius : ProjMath.degToRad(radius), - (radians) ? start : ProjMath.degToRad(start), (radians) ? extent : ProjMath.degToRad(extent), nverts, - rawllpts); - - int linetype = LineType.Straight; - boolean isFilled = false; - - switch (arcType) { - case Arc2D.PIE: - rawllpts[rawllpts.length - 4] = c.getRadLat(); - rawllpts[rawllpts.length - 3] = c.getRadLon(); - // Fall through... - case Arc2D.CHORD: - rawllpts[rawllpts.length - 2] = rawllpts[0]; - rawllpts[rawllpts.length - 1] = rawllpts[1]; - // Need to do this for the sides, not the arc part. - linetype = LineType.GreatCircle; - isFilled = true; - break; - default: - // Don't need to do anything, defaults are already set. - } - - // forward project the arc-poly. - return forwardPoly(rawllpts, linetype, -1, isFilled); - } - - /** - * Forward project a circle. - * - * @param c LatLonPoint center - * @param radians boolean radius in radians? - * @param radius radius in radians or decimal degrees - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius) { - return forwardCircle(c, radians, radius, -1, false); - } - - /** - * Forward project a Lat/Lon Circle. - *

- * Circles have the same restrictions as polys. - * . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius, int nverts) { - return forwardCircle(c, radians, radius, nverts, false); - } - - /** - * Forward project a Lat/Lon Circle. - *

- * Circles have the same restrictions as polys. - * . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - * @param isFilled filled poly? - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius, int nverts, - boolean isFilled) { - // HACK-need better decision for number of vertices. - if (nverts < 3) - nverts = NUM_DEFAULT_CIRCLE_VERTS; - - double[] rawllpts = new double[(nverts << 1) + 2];// *2 for - // pairs +2 - // connect - GreatCircle.earthCircle(c.getRadLat(), c.getRadLon(), (radians) ? radius : ProjMath.degToRad(radius), nverts, - rawllpts); - // connect the vertices. - rawllpts[rawllpts.length - 2] = rawllpts[0]; - rawllpts[rawllpts.length - 1] = rawllpts[1]; - - // forward project the circle-poly - return forwardPoly(rawllpts, LineType.Straight, -1, isFilled); - } - - // HACK - protected transient static int XTHRESHOLD = 16384;// half range - protected transient int XSCALE_THRESHOLD = 1000000;// dynamically - - /** - * Forward project a LatLon Poly. - *

- * Returns a ArrayList of (x[], y[]) coordinate pair(s) of the projected poly. - * RESTRICTIONS: All the following - * restrictions apply to LatLon polygons (either filled or non-filled). Many of - * these restrictions apply to other poly-like ArrayList graphics (Lines, - * Rectangles, Circles, Ellipses, ...). See also - * restrictions on LatLon lines. - *

- * For the cylindrical projections, (e.g. - * Mercator), your polygons should not include or touch the poles. This is - * because a polygon or polyline that includes a pole becomes a non-continuous - * straight line on the map. "So what about Antarctica", you say, "after all - * it's a polygon that is draped over the South Pole". Well, if you want to see - * it in a cylindrical projection, you will need to "augment" the vertices to - * turn it into a valid x-y polygon. You could do this by removing the segment - * which crosses the dateline, and instead add two extra edges down along both - * sides of the dateline to very near the south pole and then connect these ends - * back the other way around the world (not across the dateline) with a few - * extra line segments (remember the line length - * restrictions ). This way you've removed the polar anomaly from the data - * set. On the screen, all you see is a sliver artifact down along the dateline. - * This is the very method that our DCW data server shows Antarctica. - *

- * There is a fundamental ambiguity with filled polygons on a sphere: which side - * do you draw the fill-color? The Cylindrical family will draw the polygon as - * if it were in x-y space. For the Azimuthal projections, (e.g. Orthographic), - * you can have polygons that cover the pole, but it's important to specify the - * vertices in a clockwise order so that we can do the correct clipping along - * the hemisphere edge. We traverse the vertices assuming that the fill will be - * to the right hand side if the polygon straddles the edge of the projection. - * (This default can be changed). - *

- *

To Be (Mostly) Safe:

- *
    - *
  • Polygons should not touch or encompass the poles unless you will be - * viewing them with azimuthal projections, such as Orthographic.
    - *
  • Polygons should not encompass more area than one hemisphere.
    - *
  • Polygon vertices should be specified in "clockwise", fill-on-right order - * to ensure proper filling.
    - *
  • Polygon edges are also restricted by the - * restrictions on LatLon lines . - *
- *

- *

Optimization Notes:

The projection library deals internally in - * radians, and so you're required to pass in an array of radian points. See - * - * ProjMath.arrayDegToRad(float[]) for an efficient in-place conversion. - *

- * For no-frills, no-assumptions, fast and efficient projecting, see - * forwardRaw() . - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated - * internally) - * @param isFilled poly is filled? or not - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - ArrayList stuff = _forwardPoly(rawllpts, ltype, nsegs, isFilled); - // @HACK: workaround XWindows bug. simple clip to a boundary. - // this is ugly. - if (Environment.doingXWindowsWorkaround() && (scale <= XSCALE_THRESHOLD)) { - int i, j, size = stuff.size(); - float[] xpts, ypts; - for (i = 0; i < size; i += 2) { - xpts = (float[]) stuff.get(i); - ypts = (float[]) stuff.get(i + 1); - for (j = 0; j < xpts.length; j++) { - if (xpts[j] <= -XTHRESHOLD) { - xpts[j] = -XTHRESHOLD; - } else if (xpts[j] >= XTHRESHOLD) { - xpts[j] = XTHRESHOLD; - } - if (ypts[j] <= -XTHRESHOLD) { - ypts[j] = -XTHRESHOLD; - } else if (ypts[j] >= XTHRESHOLD) { - ypts[j] = XTHRESHOLD; - } - } - stuff.set(i, xpts); - stuff.set(i + 1, ypts); - } - } - return stuff; - } - - /** - * Forward project a lat/lon Poly. - *

- * Delegates to _forwardPoly(), and may do additional clipping for Java XWindows - * problem. Remember to specify vertices in radians! - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated - * internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - ArrayList stuff = _forwardPoly(rawllpts, ltype, nsegs, isFilled); - // @HACK: workaround XWindows bug. simple clip to a boundary. - // this is ugly. - if (Environment.doingXWindowsWorkaround() && (scale <= XSCALE_THRESHOLD)) { - int i, j, size = stuff.size(); - float[] xpts, ypts; - for (i = 0; i < size; i += 2) { - xpts = stuff.get(i); - ypts = stuff.get(i + 1); - for (j = 0; j < xpts.length; j++) { - if (xpts[j] <= -XTHRESHOLD) { - xpts[j] = -XTHRESHOLD; - } else if (xpts[j] >= XTHRESHOLD) { - xpts[j] = XTHRESHOLD; - } - if (ypts[j] <= -XTHRESHOLD) { - ypts[j] = -XTHRESHOLD; - } else if (ypts[j] >= XTHRESHOLD) { - ypts[j] = XTHRESHOLD; - } - } - stuff.set(i, xpts); - stuff.set(i + 1, ypts); - } - } - return stuff; - } - - /** - * Forward project a lat/lon Poly defined as decimal degree lat/lons. - *

- * Delegates to _forwardPoly(), and may do additional clipping for Java XWindows - * problem. Remember to specify vertices in decimal degrees. If you have - * radians, use them and call forwardPoly, it's faster. This method will convert - * the coords to radians before calling the fowardPoly method. - * - * @param llpts double[] of lat,lon,lat,lon,... in decimal degree lat/lon! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated - * internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardLLPoly(double[] llpts, int ltype, int nsegs, boolean isFilled) { - double[] rawllpts = new double[llpts.length]; - System.arraycopy(llpts, 0, rawllpts, 0, llpts.length); - ProjMath.arrayDegToRad(rawllpts); - return forwardPoly(rawllpts, ltype, nsegs, isFilled); - } - - /** - * Forward project a lat/lon Poly. Remember to specify vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated - * internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - */ - protected abstract ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled); - - /** - * Forward project a lat/lon Poly. Remember to specify vertices in radians! - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated - * internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - */ - protected abstract ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled); - - /** - * Get the unprojected coordinates units of measure. - * - * @return Length.DECIMAL_DEGREE - */ - public Length getUcuom() { - return Length.DECIMAL_DEGREE; - } - - /** - * Can't set the unprojected coordinates units of measure for a GeoProj, it's - * always Length.DECIMAL_DEGREE. - * - * @param ucuom - */ - public void setUcuom(Length ucuom) { - // no-op - } - - /** - * Convenience method to create a GCT for this projection. For projections that - * start with lat/lon coordinates, this will return a LatLonGCT. For projections - * that have world coordinates in meters, the GCT will provide a way to get to - * those meter coordinates. For instance, a UTMProjection will return a UTMGCT. - * - * @return GeoCoordTransformation for this projection - */ - @SuppressWarnings("unchecked") - public T getGCTForProjection() { - return (T) new LatLonGCT(); - } - - /** - * @return the reference longitude of the projection. For most projections, - * it'll just be the center point longitude. For LLC, it'll be the - * reference meridian. - */ - public double getReferenceLon() { - return getCenter().getX(); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Gnomonic.java b/src/core/src/main/java/com/bbn/openmap/proj/Gnomonic.java deleted file mode 100644 index eb8f8db48..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Gnomonic.java +++ /dev/null @@ -1,509 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Gnomonic.java,v $ -// $RCSfile: Gnomonic.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/04/07 15:21:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Implements the Gnomonic projection. - */ -public class Gnomonic extends Azimuth { - - /** - * The Gnomonic name. - */ - public final static transient String GnomonicName = "Gnomonic"; - - protected double hy, wx; - - // almost constant projection parameters - protected double cosCtrLat; - protected double sinCtrLat; - - public final static transient double epsilon = 0.0001; - public final static transient double HEMISPHERE_EDGE = ((Math.PI / 180d) * 80d);// 80degrees - public final static transient double hPrime = 1d / Math.pow(Math.cos(HEMISPHERE_EDGE), - 2d); - - protected final static float NORTH_BOUNDARY = (float) (NORTH_POLE - epsilon); - protected final static float SOUTH_BOUNDARY = -NORTH_BOUNDARY; - - /** - * Construct a Mercator projection. - * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - * - */ - public Gnomonic(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - setMinScale(1000.0f); - } - - /** - * Return stringified description of this projection. - * - * @return String - * @see Projection#getProjectionID - * - */ - public String toString() { - return "Gnomonic[" + super.toString(); - } - - protected void init() { - super.init(); - - // minscale is the minimum scale allowable (before integer - // wrapping can occur) - minscale = (float) Math.ceil((2 * hPrime * planetPixelRadius) - / (int) Integer.MAX_VALUE); - if (minscale < 1) - minscale = 1; - - // calculate cutoff scale for XWindows workaround - XSCALE_THRESHOLD = (int) ((planetPixelRadius * 2 * hPrime) / 64000);// fudge - - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- * - */ - protected void computeParameters() { - Debug.message("proj", "Gnomonic.computeParameters()"); - super.computeParameters(); - - // maxscale = scale at which a world hemisphere fits in the - // window - maxscale = (width < height) ? (float) (planetPixelRadius * 2 * hPrime) - / (float) width : (float) (planetPixelRadius * 2 * hPrime) - / (float) height; - if (maxscale < minscale) { - maxscale = minscale; - } - - if (scale > maxscale) { - scale = maxscale; - } - - scaled_radius = planetPixelRadius / scale; - - // width of the world in pixels at current scale. We see only - // one hemisphere. - world.x = (int) ((planetPixelRadius * 2 * hPrime) / scale); - - // do some precomputation of stuff - cosCtrLat = Math.cos(centerY); - sinCtrLat = Math.sin(centerY); - - // compute the offsets - hy = height / 2; - wx = width / 2; - } - - /** - * Assume that the Graphics has been set with the Paint/Color needed, just - * render the shape of the background. - */ - public void drawBackground(Graphics g) { - g.fillRect(0, 0, getWidth(), getHeight()); - } - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - *

- * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - * - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_BOUNDARY) { - return NORTH_BOUNDARY; - } else if (lat < SOUTH_BOUNDARY) { - return SOUTH_BOUNDARY; - } - return lat; - } - - final public static double hemisphere_distance(double phi1, double lambda0, - double phi, double lambda) { - return GreatCircle.sphericalDistance(phi1, lambda0, phi, lambda)/*-epsilon*/; - } - - /** - * Check if a given lat/lon is within the visible hemisphere. - * - * @param phi1 latitude - * @param lambda0 longitude - * @param phi latitude - * @param lambda longitude - * @return boolean true if within the visible hemisphere, false if not - */ - final public static boolean hemisphere_clip(float phi1, float lambda0, - float phi, float lambda) { - return (GreatCircle.sphericalDistance(phi1, lambda0, phi, lambda)/*-epsilon*/<= HEMISPHERE_EDGE); - } - - final public static boolean hemisphere_clip(double phi1, double lambda0, - double phi, double lambda) { - return (GreatCircle.sphericalDistance(phi1, lambda0, phi, lambda)/*-epsilon*/<= HEMISPHERE_EDGE); - } - - /** - * Calculate point along edge of hemisphere (using center point and current - * azimuth). - *

- * This is invoked for points that aren't visible in the current hemisphere. - * - * @param p Point2D - * @return Point2D p - * - */ - private Point2D edge_point(Point2D p, double current_azimuth) { - double c = HEMISPHERE_EDGE; - LatLonPoint tmpll = GreatCircle.sphericalBetween(centerY, - centerX, - c/*-epsilon*/, - current_azimuth); - double phi = tmpll.getRadLat(); - double lambda = tmpll.getRadLon(); - - double kPrime = 1f / Math.cos(c); - double cosPhi = Math.cos(phi); - double sinPhi = Math.sin(phi); - double lambdaMinusCtrLon = lambda - centerX; - double cosLambdaMinusCtrLon = Math.cos(lambdaMinusCtrLon); - double sinLambdaMinusCtrLon = Math.sin(lambdaMinusCtrLon); - - double x = (scaled_radius * kPrime * cosPhi * sinLambdaMinusCtrLon) - + wx; - double y = hy - - (scaled_radius * kPrime * (cosCtrLat * sinPhi - sinCtrLat - * cosPhi * cosLambdaMinusCtrLon)); - p.setLocation(x, y); - return p; - } - - /** - * Checks if a LatLonPoint is plot-able. - *

- * A point is plot-able if it is within the visible hemisphere. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return boolean - */ - public boolean isPlotable(double lat, double lon) { - lat = normalizeLatitude(ProjMath.degToRad(lat)); - lon = wrapLongitude(ProjMath.degToRad(lon)); - return hemisphere_clip(centerY, centerX, lat, lon); - } - - /** - * Forward project a point. If the point is not within the viewable - * hemisphere, return flags in AzimuthVar variable if specified. - * - * @param phi float latitude in radians - * @param lambda float longitude in radians - * @param p Point2D - * @param azVar AzimuthVar or null - * @return Point2D pt - */ - protected Point2D _forward(float phi, float lambda, Point2D p, - AzimuthVar azVar) { - return _forward((double) phi, (double) lambda, p, azVar); - } - - /** - * Forward project a point. If the point is not within the viewable - * hemisphere, return flags in AzimuthVar variable if specified. - * - * @param phi double latitude in radians - * @param lambda double longitude in radians - * @param p Point2D - * @param azVar AzimuthVar or null - * @return Point2D pt - */ - protected Point2D _forward(double phi, double lambda, Point2D p, - AzimuthVar azVar) { - double c = hemisphere_distance(centerY, centerX, phi, lambda); - // normalize invalid point to the edge of the sphere - if (c > HEMISPHERE_EDGE) { - double az = GreatCircle.sphericalAzimuth(centerY, - centerX, - phi, - lambda); - if (azVar != null) { - azVar.invalid_forward = true; // set the invalid - // flag - azVar.current_azimuth = (float) az; // record azimuth - // of this - // point - } - return edge_point(p, az); - } - - double kPrime = 1 / Math.cos(c); - double cosPhi = Math.cos(phi); - double sinPhi = Math.sin(phi); - double lambdaMinusCtrLon = lambda - centerX; - double cosLambdaMinusCtrLon = Math.cos(lambdaMinusCtrLon); - double sinLambdaMinusCtrLon = Math.sin(lambdaMinusCtrLon); - - double x = (scaled_radius * kPrime * cosPhi * sinLambdaMinusCtrLon) - + wx; - double y = hy - - (scaled_radius * kPrime * (cosCtrLat * sinPhi - sinCtrLat - * cosPhi * cosLambdaMinusCtrLon)); - p.setLocation(x, y); - return p; - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llp LatLonPoint - * @return LatLonPoint llp - * @see Proj#inverse(Point2D) - * - */ - public T inverse(double x, double y, T llp) { - - if (llp == null) { - llp = (T) new LatLonPoint.Double(); - } - - // convert from screen to world coordinates - x -= wx; - y = hy - y; - - // Debug.output("Gnomonic.inverse: x,y=" + x + "," + y); - - double rho = Math.sqrt(x * x + y * y); - if (rho == 0) { - Debug.message("proj", "Gnomonic.inverse: center!"); - llp.setLocation(ProjMath.radToDeg(centerX), - ProjMath.radToDeg(centerY)); - return llp; - } - - double c = Math.atan2(rho, scaled_radius); - double cosC = Math.cos(c); - double sinC = Math.sin(c); - - // calculate latitude - double lat = Math.asin(cosC * sinCtrLat - + (y * sinC * (cosCtrLat / rho))); - - // calculate longitude - double lon = centerX - + Math.atan2((x * sinC), (rho * cosCtrLat * cosC - y - * sinCtrLat * sinC)); - // Debug.output("Gnomonic.inverse: lat,lon=" + - // ProjMath.radToDeg(lat) + "," + - // ProjMath.radToDeg(lon)); - - // check if point in outer space - // if (MoreMath.approximately_equal(lat, ctrLat) && - // MoreMath.approximately_equal(lon, ctrLon) && - // (Math.abs(x-(width/2))<2) && - // (Math.abs(y-(height/2))<2)) - - if (Double.isNaN(lat) || Double.isNaN(lon)) { - Debug.message("proj", "Gnomonic.inverse(): outer space!"); - lat = centerY; - lon = centerX; - } - - llp.setLocation(Math.toDegrees(wrapLongitude(lon)), Math.toDegrees(normalizeLatitude(lat))); - return llp; - } - - /** - * Check if equator is visible on screen. - * - * @return boolean - */ - public boolean overEquator() { - LatLonPoint llN = new LatLonPoint.Float(); - inverse(width / 2, 0, llN); - LatLonPoint llS = new LatLonPoint.Float(); - inverse(width / 2, height, llS); - return MoreMath.sign(llN.getY()) != MoreMath.sign(llS.getY()); - } - - /** - * Get the upper left (northernmost and westernmost) point of the - * projection. - *

- * Returns the upper left point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - * - * @return LatLonPoint - */ - public LatLonPoint getUpperLeft() { - LatLonPoint tmp = new LatLonPoint.Double(); - double lat, lon; - - // over north pole - if (overNorthPole()) { - lat = NORTH_POLE; - lon = -DATELINE; - } - - // over south pole - else if (overSouthPole()) { - lon = -DATELINE; - if (overEquator()) { - // get top center for latitude - inverse(width / 2, 0, tmp); - lat = tmp.getRadLat(); - } else { - // get left top corner for latitude - inverse(0, 0, tmp); - lat = tmp.getRadLat(); - } - } - - // view in northern hemisphere - else if (tmp.getRadLat() >= 0) { - // get left top corner for longitude - inverse(0, 0, tmp); - lon = tmp.getRadLon(); - // get top center for latitude - inverse(width / 2, 0, tmp); - lat = tmp.getRadLat(); - } - - // view in southern hemisphere - else { - // get left bottom corner for longitude - inverse(0, height, tmp); - lon = tmp.getRadLon(); - - if (overEquator()) { - // get top center (for latitude) - inverse(width / 2, 0, tmp); - lat = tmp.getRadLat(); - } else { - // get left top corner (for latitude) - inverse(0, 0, tmp); - lat = tmp.getRadLat(); - } - } - tmp.setLatLon(lat, lon, true); - // Debug.output("ul="+tmp); - return tmp; - } - - /** - * Get the lower right (southeast) point of the projection. - *

- * Returns the lower right point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * This is trivial for most cylindrical projections, but much more - * complicated for azimuthal projections. - * - * @return LatLonPoint - */ - public LatLonPoint getLowerRight() { - LatLonPoint tmp = new LatLonPoint.Double(); - double lat, lon; - - // over north pole - if (overNorthPole()) { - lon = DATELINE; - if (overEquator()) { - // get bottom center for latitude - inverse(width / 2, height, tmp); - lat = tmp.getRadLat(); - } else { - // get bottom right corner for latitude - inverse(width, height, tmp); - lat = tmp.getRadLat(); - } - } - - // over south pole - else if (overSouthPole()) { - lat = SOUTH_POLE; - lon = DATELINE; - } - - // view in northern hemisphere - else if (tmp.getRadLat() >= 0f) { - // get the right top corner for longitude - inverse(width, 0, tmp); - lon = tmp.getRadLon(); - - if (overEquator()) { - // get the bottom center (for latitude) - inverse(width / 2, height, tmp); - lat = tmp.getRadLat(); - } else { - // get the right bottom corner (for latitude) - inverse(width, height, tmp); - lat = tmp.getRadLat(); - } - } - - // view in southern hemisphere - else { - // get the right bottom corner for longitude - inverse(width, height, tmp); - lon = tmp.getRadLon(); - // get bottom center for latitude - inverse(width / 2, height, tmp); - lat = tmp.getRadLat(); - } - tmp.setLatLon(lat, lon, true); - // Debug.output("lr="+tmp); - return tmp; - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return GnomonicName; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/GnomonicLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/GnomonicLoader.java deleted file mode 100644 index 6a51c640d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/GnomonicLoader.java +++ /dev/null @@ -1,76 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/GnomonicLoader.java,v $ -// $RCSfile: GnomonicLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the Gnomonic projection to an OpenMap - * application. - * - * @see BasicProjectionLoader - */ -public class GnomonicLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public GnomonicLoader() { - super(Gnomonic.class, Gnomonic.GnomonicName, "Gnomonic projection."); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - return new Gnomonic(llp, scale, width, height); - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("GnomonicLoader: problem creating Gnomonic projection " - + e.getMessage()); - } - } - - throw new ProjectionException("GnomonicLoader: problem creating Gnomonic projection"); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/GreatCircle.java b/src/core/src/main/java/com/bbn/openmap/proj/GreatCircle.java deleted file mode 100644 index 168a30fd1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/GreatCircle.java +++ /dev/null @@ -1,634 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/GreatCircle.java,v $ -// $RCSfile: GreatCircle.java,v $ -// $Revision: 1.8 $ -// $Date: 2005/12/09 21:09:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; - -/** - * Methods for calculating great circle and other distances on the sphere and - * ellipsoid. Note that as of OpenMap 4.7, all the method calls with a '_' in - * them have been deprecated, replaced by method names that conform to Java - * conventions. - *

- * Spherical equations taken from John Synder's Map Projections --A Working - * Manual , pp29-31.
- * Latitude/longitude arguments must be in valid radians: -PI<=lambda<PI, - * -PI/2<=phi<=PI/2 - */ -public class GreatCircle { - - // cannot construct - private GreatCircle() { - } - - /** - * Calculate spherical arc distance between two points with double - * precision. - *

- * Computes arc distance `c' on the sphere. equation (5-3a). (0 <= c - * <= PI) - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param phi latitude in radians of end point - * @param lambda longitude in radians of end point - * @return float arc distance `c' - */ - final public static double sphericalDistance(double phi1, double lambda0, double phi, - double lambda) { - double pdiff = Math.sin(((phi - phi1) / 2.0)); - double ldiff = Math.sin((lambda - lambda0) / 2.0); - double rval = Math.sqrt((pdiff * pdiff) + Math.cos(phi1) * Math.cos(phi) * (ldiff * ldiff)); - - return 2.0 * Math.asin(rval); - } - - /** - * Calculate spherical azimuth between two points with double precision. - *

- * Computes the azimuth `Az' east of north from phi1, lambda0 bearing toward - * phi and lambda. (5-4b). (-PI <= Az <= PI). - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param phi latitude in radians of end point - * @param lambda longitude in radians of end point - * @return float azimuth east of north `Az' - * - */ - final public static double sphericalAzimuth(double phi1, double lambda0, double phi, - double lambda) { - double ldiff = lambda - lambda0; - double cosphi = Math.cos(phi); - - return Math.atan2(cosphi * Math.sin(ldiff), (Math.cos(phi1) * Math.sin(phi) - Math.sin(phi1) - * cosphi * Math.cos(ldiff))); - } - - /** - * Calculate point at azimuth and distance from another point, with double - * precision. - *

- * Returns a LatLonPoint.Double at arc distance `c' in direction `Az' from - * start point. - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param c arc radius in radians (0 < c <= PI) - * @param Az azimuth (direction) east of north (-PI <= Az < PI) - * @return LatLonPoint - * - */ - final public static LatLonPoint sphericalBetween(double phi1, double lambda0, double c, - double Az) { - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double cosAz = Math.cos(Az); - double sinAz = Math.sin(Az); - double sinc = Math.sin(c); - double cosc = Math.cos(c); - - return new LatLonPoint.Double(Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz), Math.atan2(sinc - * sinAz, cosphi1 * cosc - sinphi1 * sinc * cosAz) - + lambda0, true); - } - - /** - * Calculate point between two points. - *

- * Same as spherical_between() above except it calculates n equal segments - * along the length of c. - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param c arc radius in radians (0 < c <= PI) - * @param Az azimuth (direction) east of north (-PI <= Az < PI) - * @param n number of points along great circle edge to calculate - * @return float[n+1] radian lat, lon pairs - * - */ - final public static float[] sphericalBetween(float phi1, float lambda0, float c, float Az, int n) { - // full constants for the computation - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double cosAz = Math.cos(Az); - double sinAz = Math.sin(Az); - int end = n << 1; - - // new radian points - float[] points = new float[end + 2]; - points[0] = phi1; - points[1] = lambda0; - - float inc = c / n; - c = inc; - for (int i = 2; i <= end; i += 2, c += inc) { - - // partial constants - double sinc = Math.sin(c); - double cosc = Math.cos(c); - - // generate new point - points[i] = (float) Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - - points[i + 1] = (float) Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc - * cosAz) - + lambda0; - } - return points; - } - - /** - * Calculate point between two points with double precision. - *

- * Same as spherical_between() above except it calculates n equal segments - * along the length of c. - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param c arc radius in radians (0 < c <= PI) - * @param Az azimuth (direction) east of north (-PI <= Az < PI) - * @param n number of points along great circle edge to calculate - * @return double[n+1] radian lat,lon pairs - * - */ - final public static double[] sphericalBetween(double phi1, double lambda0, double c, double Az, - int n) { - // full constants for the computation - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double cosAz = Math.cos(Az); - double sinAz = Math.sin(Az); - int end = n << 1; - - // new radian points - double[] points = new double[end + 2]; - points[0] = phi1; - points[1] = lambda0; - - double inc = c / n; - c = inc; - for (int i = 2; i <= end; i += 2, c += inc) { - - // partial constants - double sinc = Math.sin(c); - double cosc = Math.cos(c); - - // generate new point - points[i] = Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - - points[i + 1] = Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc * cosAz) - + lambda0; - } - return points; - } - - /** - * Calculate great circle between two points on the sphere. - *

- * Folds all computation (distance, azimuth, points between) into one - * function for optimization. returns n or n+1 pairs of lat,lon on great - * circle between lat-lon pairs. - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param phi latitude in radians of end point - * @param lambda longitude in radians of end point - * @param n number of segments - * @param include_last return n or n+1 segments - * @return float[n] or float[n+1] radian lat,lon pairs - * - */ - final public static float[] greatCircle(float phi1, float lambda0, float phi, float lambda, - int n, boolean include_last) { - // number of points to generate - int end = include_last ? n + 1 : n; - end <<= 1;// *2 for pairs - - // calculate a bunch of stuff for later use - double cosphi = Math.cos(phi); - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double ldiff = lambda - lambda0; - double p2diff = Math.sin(((phi - phi1) / 2)); - double l2diff = Math.sin((ldiff) / 2); - - // calculate spherical distance - double c = 2.0f * Math.asin(Math.sqrt(p2diff * p2diff + cosphi1 * cosphi * l2diff * l2diff)); - - // calculate spherical azimuth - double Az = Math.atan2(cosphi * Math.sin(ldiff), (cosphi1 * Math.sin(phi) - sinphi1 - * cosphi * Math.cos(ldiff))); - double cosAz = Math.cos(Az); - double sinAz = Math.sin(Az); - - // generate the great circle line - float[] points = new float[end]; - points[0] = phi1; - points[1] = lambda0; - - double inc = c / n; - c = inc; - for (int i = 2; i < end; i += 2, c += inc) { - - // partial constants - double sinc = Math.sin(c); - double cosc = Math.cos(c); - - // generate new point - points[i] = (float) Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - - points[i + 1] = (float) Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc - * cosAz) - + lambda0; - } - - return points; - } - - /** - * Calculate great circle between two points on the sphere with double - * precision. - *

- * Folds all computation (distance, azimuth, points between) into one - * function for optimization. returns n or n+1 pairs of lat,lon on great - * circle between lat-lon pairs. - *

- * - * @param phi1 latitude in radians of start point - * @param lambda0 longitude in radians of start point - * @param phi latitude in radians of end point - * @param lambda longitude in radians of end point - * @param n number of segments, should be at least 1 - * @param include_last return n or n+1 segments - * @return double[n] or double[n+1] radian lat,lon pairs - * - */ - final public static double[] greatCircle(double phi1, double lambda0, double phi, - double lambda, int n, boolean include_last) { - if (n <= 0) { - n = 1; - } - - // number of points to generate - int end = include_last ? n + 1 : n; - end <<= 1;// *2 for pairs - - // calculate a bunch of stuff for later use - double cosphi = Math.cos(phi); - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double ldiff = lambda - lambda0; - double p2diff = Math.sin(((phi - phi1) / 2)); - double l2diff = Math.sin((ldiff) / 2); - - // calculate spherical distance - double c = 2.0f * Math.asin(Math.sqrt(p2diff * p2diff + cosphi1 * cosphi * l2diff * l2diff)); - - // calculate spherical azimuth - double Az = Math.atan2(cosphi * Math.sin(ldiff), (cosphi1 * Math.sin(phi) - sinphi1 - * cosphi * Math.cos(ldiff))); - double cosAz = Math.cos(Az); - double sinAz = Math.sin(Az); - - // generate the great circle line - double[] points = new double[end]; - points[0] = phi1; - points[1] = lambda0; - - double inc = c / n; - c = inc; - for (int i = 2; i < end; i += 2, c += inc) { - - // partial constants - double sinc = Math.sin(c); - double cosc = Math.cos(c); - - // generate new point - points[i] = Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - - points[i + 1] = Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc * cosAz) - + lambda0; - } - - return points; - } - - /** - * Return a point that is approximately a certain distance along the great - * circle line between two points. Returns the nearest coordinate along a - * set of calculated segments (as dictated by n) that fits the desired - * distance. - * - * @param phi1 latitude of point 1 in radians. - * @param lambda0 longitude of point 1 in radians. - * @param phi latitude of point 2 in radians. - * @param lambda longitude of point 2 in radians. - * @param distance in radians. - * @param n number of segments to divide path into. The more segments, the - * more accurate. If n <= 0, the OpenMap default of 512 is used. - * @return LatLonPoint if distance is less than distance between points, - * null if it is greater. - */ - public static LatLonPoint pointAtDistanceBetweenPoints(double phi1, double lambda0, double phi, - double lambda, double distance, int n) { - LatLonPoint ret = null; - - double pntDist = sphericalDistance(phi1, lambda0, phi, lambda); - - if (pntDist > distance) { - if (n <= 0) { - n = GeoProj.NUM_DEFAULT_GREAT_SEGS; - } - - double[] gcpoints = greatCircle(phi1, lambda0, phi, lambda, n, true); - - // Ratio of desired distance to total distance between points - how - // far down the line we need to go. - double distRatio = distance / pntDist; - // all lat, lon points, get number of vertices, find index of the - // one that fits the ratio of the desired distance to the overall - // distance between points, and then multiply by 2 to get the actual - // index of the matching latitude. - int index = (int) ((int) (gcpoints.length / 2) * distRatio) * 2; - ret = new LatLonPoint.Double(gcpoints[index], gcpoints[index + 1], true); - } - - return ret; - } - - /** - * Calculate partial earth circle on the sphere. - *

- * Returns n float lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param s starting angle in radians. North up is zero. - * @param e angular extent in radians, clockwise right from starting angle. - * @param n number of points along circle edge to calculate - * @return float[n] radian lat,lon pairs along earth circle - * - */ - final public static float[] earthCircle(float phi1, float lambda0, float c, float s, float e, - int n) { - return earthCircle(phi1, lambda0, c, s, e, n, new float[n << 1]); - } - - /** - * Calculate earth circle on the sphere. - *

- * Returns n float lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param n number of points along circle edge to calculate - * @return float[n] radian lat,lon pairs along earth circle - * - */ - final public static float[] earthCircle(float phi1, float lambda0, float c, int n) { - return earthCircle(phi1, lambda0, c, 0.0f, MoreMath.TWO_PI, n, new float[n << 1]); - } - - /** - * Calculate earth circle in the sphere. - *

- * Returns n float lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param n number of points along circle edge to calculate - * @param ret_val float[] ret_val array of n*2 number of points along circle - * edge to calculate - * @return float[n] radian lat,lon pairs along earth circle - * - */ - final public static float[] earthCircle(float phi1, float lambda0, float c, int n, - float[] ret_val) { - return earthCircle(phi1, lambda0, c, 0.0f, MoreMath.TWO_PI, n, ret_val); - } - - /** - * Calculate earth circle in the sphere. - *

- * Returns n float lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point. - * @param lambda0 longitude in radians of center point. - * @param c arc radius in radians (0 < c < PI). - * @param s starting angle in radians. North up is zero. - * @param e angular extent in radians, clockwise right from starting angle. - * @param n number of points along circle edge to calculate. - * @param ret_val float[] ret_val array of n*2 number of points along circle - * edge to calculate. - * @return float[n] radian lat,lon pairs along earth circle. - * - */ - final public static float[] earthCircle(float phi1, float lambda0, float c, float s, float e, - int n, float[] ret_val) { - double Az, cosAz, sinAz; - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double sinc = Math.sin(c); - double cosc = Math.cos(c); - if (n < 2) - n = 2; // Safety to avoid / by zero later. - int end = n << 1;// *2 - - // Only want to create a new return float array if there was a - // null one passed in, or if the number of desired coordinates - // is bigger than what ret_val is currently allocated for. - if (ret_val == null || end > ret_val.length) { - ret_val = new float[end]; - } - - double inc = e / (n - 1); - Az = s; - - // generate the points in clockwise order (conforming to - // internal standard!) - for (int i = 0; i < end; i += 2, Az += inc) { - cosAz = Math.cos(Az); - sinAz = Math.sin(Az); - - ret_val[i] = (float) Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - ret_val[i + 1] = (float) Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc - * cosAz) - + lambda0; - } - - return ret_val; - } - - /** - * Calculate partial earth circle on the sphere with double precision. - *

- * Returns n double lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param s starting angle in radians. North up is zero. - * @param e angular extent in radians, clockwise right from starting angle. - * @param n number of points along circle edge to calculate - * @return double[n] radian lat,lon pairs along earth circle - * - */ - final public static double[] earthCircle(double phi1, double lambda0, double c, double s, - double e, int n) { - return earthCircle(phi1, lambda0, c, s, e, n, new double[n << 1]); - } - - /** - * Calculate earth circle on the sphere with double precision. - *

- * Returns n double lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param n number of points along circle edge to calculate - * @return double[n] radian lat,lon pairs along earth circle - * - */ - final public static double[] earthCircle(double phi1, double lambda0, double c, int n) { - return earthCircle(phi1, lambda0, c, 0.0f, MoreMath.TWO_PI_D, n, new double[n << 1]); - } - - /** - * Calculate earth circle in the sphere with double precision. - *

- * Returns n float lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point - * @param lambda0 longitude in radians of center point - * @param c arc radius in radians (0 < c < PI) - * @param n number of points along circle edge to calculate - * @param ret_val double[] ret_val array of n*2 number of points along - * circle edge to calculate - * @return double[n] radian lat,lon pairs along earth circle - * - */ - final public static double[] earthCircle(double phi1, double lambda0, double c, int n, - double[] ret_val) { - return earthCircle(phi1, lambda0, c, 0.0f, MoreMath.TWO_PI_D, n, ret_val); - } - - /** - * Calculate earth circle in the sphere in double precision. - *

- * Returns n double lat,lon pairs at arc distance c from point at - * phi1,lambda0. - *

- * - * @param phi1 latitude in radians of center point. - * @param lambda0 longitude in radians of center point. - * @param c arc radius in radians (0 < c < PI). - * @param s starting angle in radians. North up is zero. - * @param e angular extent in radians, clockwise right from starting angle. - * @param n number of points along circle edge to calculate. - * @param ret_val double[] ret_val array of n*2 number of points along - * circle edge to calculate. - * @return double[n] radian lat,lon pairs along earth circle. - * - */ - final public static double[] earthCircle(double phi1, double lambda0, double c, double s, - double e, int n, double[] ret_val) { - double Az, cosAz, sinAz; - double cosphi1 = Math.cos(phi1); - double sinphi1 = Math.sin(phi1); - double sinc = Math.sin(c); - double cosc = Math.cos(c); - if (n < 2) - n = 2; // Safety to avoid / by zero later. - int end = n << 1;// *2 - - // Only want to create a new return float array if there was a - // null one passed in, or if the number of desired coordinates - // is bigger than what ret_val is currently allocated for. - if (ret_val == null || end > ret_val.length) { - ret_val = new double[end]; - } - - double inc = e / (n - 1); - Az = s; - - // generate the points in clockwise order (conforming to - // internal standard!) - for (int i = 0; i < end; i += 2, Az += inc) { - cosAz = Math.cos(Az); - sinAz = Math.sin(Az); - - ret_val[i] = Math.asin(sinphi1 * cosc + cosphi1 * sinc * cosAz); - ret_val[i + 1] = Math.atan2(sinc * sinAz, cosphi1 * cosc - sinphi1 * sinc * cosAz) - + lambda0; - } - - return ret_val; - } - - /* - * testing public final static void main (String[] args) { double phi1 = - * 34.3; double lambda0 = 130.299; double phi = -24; double lambda = 33.23; - * - * float dist_sphere = spherical_distance ( ProjMath.degToRad((float)phi1), - * ProjMath.degToRad((float)lambda0), ProjMath.degToRad((float)phi), - * ProjMath.degToRad((float)lambda) ); // meters dist_sphere = - * Planet.wgs84_earthEquatorialCircumferenceMeters - * *(dist_sphere/MoreMath.TWO_PI); - * Debug.output("sphere distance="+dist_sphere/1000f+" km"); - * - * AziDist invVar = ellipsoidalAziDist ( - * Planet.wgs84_earthEquatorialRadiusMeters,//major in meters - * Planet.wgs84_earthFlat, // - * Planet.international1974_earthEquatorialRadiusMeters,//major in meters // - * Planet.international1974_earthFlat, ProjMath.degToRad(phi1), - * ProjMath.degToRad(lambda0), ProjMath.degToRad(phi), - * ProjMath.degToRad(lambda), new AziDist() ); Debug.output("ellipsoid - * distance="+invVar.distance/1000d+" km"); } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LLXY.java b/src/core/src/main/java/com/bbn/openmap/proj/LLXY.java deleted file mode 100644 index 215e8c04e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LLXY.java +++ /dev/null @@ -1,252 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/LLXY.java,v $ -// $RCSfile: LLXY.java,v $ -// $Revision: 1.10 $ -// $Date: 2006/04/07 15:21:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * Implements the LLXY projection, which is basically something where the - * lat/lon and pixel ratios are the same. - */ -public class LLXY - extends Cylindrical - implements EqualArc { - - private static final long serialVersionUID = 1L; - /** - * The LLXY name. - */ - public final static transient String LLXYName = "LLXY"; - public final static transient double epsilon = 0.0001; - // world<->screen coordinate offsets - protected double hy, wx; - protected double cLon; - protected double cLonRad; - protected double cLat; - /** Pixel per degree */ - protected double ppd; - - /** - * Construct a LLXY projection. - * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public LLXY(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - } - - // protected void finalize() { - // Debug.message("gc", "LLXY finalized"); - // } - - /** - * Return stringified description of this projection. - * - * @return String - * @see Projection#getProjectionID - */ - public String toString() { - return "LLXY[" + super.toString() + "]"; - } - - /** - * Called when some fundamental parameters change. - * - * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - */ - protected void computeParameters() { - Debug.message("proj", "LLXY.computeParameters()"); - super.computeParameters(); - - // compute the offsets - hy = height / 2; - wx = width / 2; - // Degrees longitude of the center of the projection. - cLon = ProjMath.radToDeg(centerX); - cLat = ProjMath.radToDeg(centerY); - ppd = world.x / 360f; - - double latLimit = 90 - (hy / ppd); - - // Add check for zoom allowing more than 90 degrees viewable - if (latLimit < 0.0f) - latLimit = 0.0f; - - if (cLat > latLimit) { - cLat = latLimit; - centerY = ProjMath.degToRad(cLat); - } else if (cLat < -latLimit) { - cLat = -latLimit; - centerY = ProjMath.degToRad(cLat); - } - - cLonRad = Math.toRadians(cLon); - - if (Debug.debugging("llxy")) { - Debug.output("LLXY.computeParameters: with center lat:" + cLat + ", lon:" + cLon + " | width:" + width + ", height:" - + height + " | scale:" + scale); - } - } - - /** - * Sets radian latitude to something sane. This is an abstract function since - * some projections don't deal well with extreme latitudes. - * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_POLE) { - return NORTH_POLE; - } else if (lat < SOUTH_POLE) { - return SOUTH_POLE; - } - return lat; - } - - public double normalizeLatitudeDeg(double lat) { - if (lat > ProjMath.NORTH_POLE_DEG_D) { - return ProjMath.NORTH_POLE_DEG_D; - } else if (lat < ProjMath.SOUTH_POLE_DEG_D) { - return ProjMath.SOUTH_POLE_DEG_D; - } - return lat; - } - - /** - * Checks if a LatLonPoint is plot-able. - * - * This method is changed for 5.0. Previously, a point is always plot-able in - * the LLXY projection and that's because the llxy projection was kind of the - * cartesian coordinate system for OpenMap. I think we should start assuming - * that the llxy projection is kind of limited to plotable points on the - * Earth. So, we're checking that now. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return boolean if lat is between 90 and -90, lon between 180 and -180; - */ - public boolean isPlotable(double lat, double lon) { - return lat < 90.0 && lat > -90.0 && lon <= 180 && lon >= -180; - } - - /** - * Forward projects lat,lon into XY space and returns a Point2D. - * - * @param lat float latitude in radians - * @param lon float longitude in radians - * @param p Resulting XY Point2D - * @param isRadian bogus argument indicating that lat,lon arguments are in - * radians - * @return Point2D p - */ - public Point2D forward(double lat, double lon, Point2D p, boolean isRadian) { - if (isRadian) { - lat = Math.toDegrees(normalizeLatitude(lat)); - lon = Math.toDegrees(ProjMath.wrapLongitude(lon - cLonRad)); - } else { - lat = normalizeLatitudeDeg(lat); - lon = wrapLongitudeDeg(lon - cLon); - } - - double x = wx + (lon * ppd); - double y = hy - ((lat - cLat) * ppd); - - p.setLocation(x, y); - return p; - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llp LatLonPoint - * @return LatLonPoint llp - * @see Proj#inverse(Point2D) - */ - public T inverse(double x, double y, T llp) { - - if (llp == null) { - llp = (T) new LatLonPoint.Double(); - } - - // convert from screen to world coordinates, and then - // basically undo the math from the forward method. - double lon = ((x - wx) / ppd) + cLon; - double lat = ((hy - y) / ppd) + cLat; - llp.setLocation(lon, lat); - - return llp; - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return LLXYName; - } - - /** - * Returns the x pixel constant of the projection. This was calculated when - * the projection was created. Represents the number of pixels around the - * earth (360 degrees). - */ - public double getXPixConstant() { - return ppd * 360.0; - } - - /** - * Returns the y pixel constant of the projection. This was calculated when - * the projection was created. Represents the number of pixels from 0 to 90 - * degrees. - */ - public double getYPixConstant() { - return ppd * 90.0; - } - - public static LLXY convertProjection(Projection proj) { - if (proj instanceof LLXY) { - return (LLXY) proj; - } - - LLXY llxy = - new LLXY((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), proj.getWidth(), proj.getHeight()); - - Point2D ulp = llxy.forward(proj.getUpperLeft()); - Point2D lrp = llxy.forward(proj.getLowerRight()); - - int w = (int) Math.abs(lrp.getX() - ulp.getX()); - int h = (int) Math.abs(lrp.getY() - ulp.getY()); - - return new LLXY((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), w, h); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LLXYLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/LLXYLoader.java deleted file mode 100644 index c500ecda4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LLXYLoader.java +++ /dev/null @@ -1,86 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/LLXYLoader.java,v $ -// $RCSfile: LLXYLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/09/19 14:20:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.DatumShiftGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the LLXY projection to an OpenMap application. - * - * @see BasicProjectionLoader - */ -public class LLXYLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public LLXYLoader() { - super(LLXY.class, - LLXY.LLXYName, - "Equivalent projection, used for many web data sources."); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - - GeoProj proj = new LLXY(llp, scale, width, height); - - Ellipsoid ellps = (Ellipsoid) props.get(ProjectionFactory.DATUM); - if ((ellps != null) && (ellps != Ellipsoid.WGS_84)) { - proj = new DatumShiftProjection(proj, new DatumShiftGCT(ellps)); - } - - return proj; - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("LLXYLoader: problem creating LLXY projection " - + e.getMessage()); - } - } - - throw new ProjectionException("LLXYLoader: problem creating LLXY projection"); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LambertConformal.java b/src/core/src/main/java/com/bbn/openmap/proj/LambertConformal.java deleted file mode 100644 index b1cdbdea2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LambertConformal.java +++ /dev/null @@ -1,854 +0,0 @@ -// ********************************************************************** -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/LambertConformal.java,v $ -// $RCSfile: LambertConformal.java,v $ -// $Revision: 1.10 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Implements the LambertConformalConic projection.
- *
- * NOTE: This implementation only works for the northern hemisphere.
- *
- * Needs to be modified for use in the southern hemisphere. - *

- * See http://www.epsg.org/guides/docs/G7-2.pdf - * - * @author David J. Ward - * @author Chris van Lith - * - */ -public class LambertConformal - extends GeoProj { - - /** - * The LambertCC name. - */ - public final static transient String LambertConformalName = "Lambert Conformal"; - - private static final int MODE_2SP = 1; - private static final int MODE_BELGIUM = 2; - - private int mode = MODE_2SP; - - private double lambert_sp_one; - private double lambert_sp_two; - private double centralMeridian; - - double locationCenterXPixel = 0; - double locationCenterYPixel = 0; - double locationCenterXLambert = 0.0; - double locationCenterYLambert = 0.0; - double locationPixelsPerLambert = 0.0; - - double locationOriginX = 0.0; - double locationOriginY = 0.0; - double locationOriginXfPixel = 0.0; - double locationOriginYfPixel = 0.0; - - double referenceLatitude = 0.0; - double falseEasting = 0.0; - double falseNorthing = 0.0; - - // EPSG Guidance Note number 7, part 2 - November 2005 - // Lambert Conic Conformal 9802 - double n = 0.0; - double F = 0.0; - double rf = 0.0; - double lamdaf = 0.0; - double alpha = 0.0; - - private transient Ellipsoid ellps = Ellipsoid.WGS_84; - - /** - * A small number 10^(-10) This number can be re-factored into MoreMath - */ - final public static double EPS10 = 1.0e-10; - - /** - * Construct a Lambert projection. - *

- * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - protected LambertConformal(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - } - - /** - * Constructor for the lambert conformal projection. - * - * @param center center location for projections - * @param scale scale of projection - * @param width width of projection - * @param height height of projection - * @param centralMeridian the Central Meridian in degrees. - * @param sp_one Standard Parallel One in degrees. - * @param sp_two Standard Parallel Two in degrees. - */ - protected LambertConformal(LatLonPoint center, float scale, int width, int height, float centralMeridian, float sp_one, - float sp_two, Ellipsoid ellps) { - this(center, scale, width, height, centralMeridian, sp_one, sp_two, 0f, 0, 0, ellps); - } - - /** - * Constructor for the lambert conformal projection. - * - * @param center center location for projections - * @param scale scale of projection - * @param width width of projection - * @param height height of projection - * @param centralMeridian the Central Meridian in degrees. - * @param sp_one Standard Parallel One in degrees. - * @param sp_two Standard Parallel Two in degrees. - * @param reference_latitude the latitude for the origin of the projection - * @param falseEasting number of meters added as buffer to origin E/W. - * @param falseNorthing number of meters added as buffer to origin for N/S. - * @param ellps the {@link Ellipsoid} used for the projection - */ - public LambertConformal(LatLonPoint center, float scale, int width, int height, double centralMeridian, double sp_one, - double sp_two, double reference_latitude, double falseEasting, double falseNorthing, Ellipsoid ellps) { - - super(center, scale, width, height); - - if (Math.abs(sp_one + sp_two) < EPS10) { - // can not form a corn. - throw new RuntimeException("Unable to create Lambert Cornic"); - } - this.centralMeridian = centralMeridian; - this.lambert_sp_one = sp_one; - this.lambert_sp_two = sp_two; - this.referenceLatitude = reference_latitude; - this.falseEasting = falseEasting; - this.falseNorthing = falseNorthing; - this.ellps = ellps; - - computeParameters(); - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- * - */ - public void computeParameters() { - - // work around problem caused by Proj calling this method before - // constructor is done - if (ellps == null) { - ellps = Ellipsoid.WGS_84; - } - - if (mode == MODE_BELGIUM) { - // Belgium EPSG 9803, adjustment 1972 - alpha = 0.00014204d; - } else { - alpha = 0d; - } - - double phi1 = ProjMath.degToRad(lambert_sp_one); - double phi2 = ProjMath.degToRad(lambert_sp_two); - double phif = ProjMath.degToRad(referenceLatitude); - double e = ellps.ecc; - double sinphi; - - sinphi = Math.sin(phi1); - double m1 = lambMsfn(sinphi, Math.cos(phi1), e); - double t1 = lambTsfn(phi1, sinphi, e); - - if (MoreMath.approximately_equal(phi1, phi2, EPS10)) { - n = sinphi; - } else { - sinphi = Math.sin(phi2); - double m2 = lambMsfn(sinphi, Math.cos(phi2), e); - double t2 = lambTsfn(phi2, sinphi, e); - n = Math.log(m1 / m2) / Math.log(t1 / t2); - } - - F = m1 / (n * Math.pow(t1, n)); - - if (MoreMath.approximately_equal(phi1, phi2, EPS10)) { - rf = 0.0d; - } else { - rf = ellps.radius * F * Math.pow(lambTsfn(phif, Math.sin(phif), e), n); - } - - lamdaf = ProjMath.degToRad(centralMeridian); - - locationCenterXPixel = ((double) getWidth() / 2d); - locationCenterYPixel = ((double) getHeight() / 2d); - - locationPixelsPerLambert = (double) getPPM() / getScale(); - - LatLonPoint origin = new LatLonPoint.Double(referenceLatitude, centralMeridian); - Point2D lp = LLToWorld(origin.getY(), origin.getX(), new Point2D.Double()); - locationOriginX = lp.getX(); - locationOriginY = lp.getY(); - - LatLonPoint center = getCenter(); - lp = LLToWorld(center.getY(), center.getX(), lp); - locationCenterXLambert = lp.getX(); - locationCenterYLambert = lp.getY(); - - // calculate un-truncated true origin pixel value, refer to method - // worldToPixel. - locationOriginXfPixel = locationCenterXPixel + (locationOriginX - locationCenterXLambert) * locationPixelsPerLambert; - locationOriginYfPixel = locationCenterYPixel - (locationOriginY - locationCenterYLambert) * locationPixelsPerLambert; - - if (Debug.debugging("Lambert")) { - Debug.output("Creating LambertConformal: center x = " + locationCenterXLambert + ", center y = " - + locationCenterYLambert); - Debug.output("Creating LambertConformal: origin x = " + locationOriginX + ", origin y = " + locationOriginY); - } - - } - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - *

- * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - * - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_POLE) { - return NORTH_POLE; - } else if (lat < SOUTH_POLE) { - return SOUTH_POLE; - } - return lat; - } - - /*---------------------------------------------------------------------------- - * FUNCTION: LLToWorld - * DATE CREATE: 13-4-2006 - * CREATED BY: Chris van Lith - * Modified By: steve C. Tang, 02/20/2010 - * DESCRIPTION: This function converts lat, lon coordinate to lambert - * coordinate. - *--------------------------------------------------------------------------*/ - public Point2D LLToWorld(double lat, double lon, Point2D lp) { - if (lp == null) { - lp = new Point2D.Double(); - } - - LLToWorldReturningLon(lat, lon, lp); - return lp; - } - - /** - * LLToWorld that returns normalized longitude in radians, to be used for - * more calculations in some methods. Do not provide a NULL lp here if you - * want the world coordinates provided back to you. - * - * @param lat latitude in degrees - * @param lon longitude in degrees. - * @param lp world coordinates are provided back in this object, make sure - * it's not null if you care about them. - * @return normalized longitude in radians, radians lon - radians lat. - */ - protected double LLToWorldReturningLon(double lat, double lon, Point2D lp) { - - double phi_deg = lat; - double phi = ProjMath.degToRad(phi_deg); - double lamba_deg = lon; - double lamba = ProjMath.degToRad(lamba_deg); - - // normalized longitude - double dlamda = lamba - lamdaf; - if (dlamda > Math.PI) { - dlamda -= MoreMath.TWO_PI_D; - } else if (dlamda < -Math.PI) { - dlamda += MoreMath.TWO_PI_D; - } - - double e = ellps.ecc; - double r = 0.0d; - if (!MoreMath.approximately_equal(Math.abs(phi), MoreMath.HALF_PI, EPS10)) { - double t = lambTsfn(phi, Math.sin(phi), e); - r = ellps.radius * F * Math.pow(t, n); - } - double theta = n * dlamda; - - double easting = falseEasting + r * Math.sin(theta - alpha); - double northing = falseNorthing + rf - r * Math.cos(theta - alpha); - - lp.setLocation(easting, northing); - - return dlamda; - } /* end of function LLToWorld */ - - /*---------------------------------------------------------------------------- - * FUNCTION: lat_lon_to_pixel - * DATE CREATE: 28 February 1995 - * CREATED BY: David J. Ward - * Modified by: Steve C. Tang, 02/20/2010 - * DESCRIPTION: This function converts lat, lon coordinate to pixel - * coordinate. - *--------------------------------------------------------------------------*/ - - public double LLToPixel(double lat, double lon, Point2D p) { - - double dlamda; - - Point2D lp = new Point2D.Double(); - dlamda = LLToWorldReturningLon(lat, lon, lp); - - double xrel = lp.getX() - locationCenterXLambert; - double yrel = lp.getY() - locationCenterYLambert; - - xrel = (xrel * locationPixelsPerLambert); - yrel = (yrel * locationPixelsPerLambert); - - xrel = locationCenterXPixel + xrel; - yrel = locationCenterYPixel - yrel; - - if (p == null) { - p = new Point2D.Double(); - } - - p.setLocation(xrel, yrel); - - // In Openmap 4.6.5 and before, the float-2-int truncation in - // World-to-Pixel transform can cause - // the displayed position on the other side if the projection side line - // runs across the pixel. - // For example, a true World coordinate of 678.9 is truncated to (int) - // 678.9=678. while 678.9 - // can correspond to dlamda=180.1 that means -179.9 on the other side, - // 678 - // can correspond to - // dlamda=179.9 during later map projection. We approximate this - // situation - // by forcing the swap. - // Increase PixelsPerLambert and projection size can reduce the error. - if ((dlamda > 3.1415 && p.getX() < locationOriginXfPixel) || (-dlamda > 3.1415 && p.getX() > locationOriginXfPixel)) { - dlamda = -dlamda; - } - - return dlamda; - } /* end of function LLToPixel */ - - // - public Point worldToPixel(Point2D lp, Point p) { - double x = locationCenterXPixel + (lp.getX() - locationCenterXLambert) * locationPixelsPerLambert; - double y = locationCenterYPixel - (lp.getY() - locationCenterYLambert) * locationPixelsPerLambert; - if (p == null) - p = new Point(); - p.setLocation((int) x, (int) y); - return p; - } - - // - public Point2D pixelToWorld(Point p, Point2D lp) { - double x = locationCenterXLambert + (p.getX() - locationCenterXPixel) / locationPixelsPerLambert; - double y = locationCenterYLambert - (p.getY() - locationCenterYPixel) / locationPixelsPerLambert; - if (lp == null) - lp = new Point2D.Double(); - lp.setLocation(x, y); - return lp; - } - - /*---------------------------------------------------------------------------- - * FUNCTION: worldToLL - * DATE CREATE: 13-4-2006 - * CREATED BY: Chris van Lith - * Modified By: Steve C. Tang, 02/20/2010 - * DESCRIPTION: This function converts lambert projections to lat, lon - * coordinate. It is given the lambert projections as the - * input, and the lat, lon coordinate as the output. - *--------------------------------------------------------------------------*/ - public Point2D worldToLL(double x, double y, Point2D llp) { - - x -= falseEasting; - y = rf - (y - falseNorthing); - - double rR = Math.sqrt(x * x + y * y); - if (rR < EPS10) { - llp.setLocation(0.0, n > 0.0 ? 90.0 : -90.0); - return llp; - } - - if (n < 0.0) { - rR = -rR; - x = -x; - y = -y; - } - - double tR = Math.pow(rR / (ellps.radius * F), 1 / n); - double halfe = 0.5 * ellps.ecc; - - double phiT1 = 0.0; - double phiT2 = MoreMath.HALF_PI - 2 * Math.atan(tR); - int iIter = 0, nIter = 10; - double halfesinphi; - do { - phiT1 = phiT2; - halfesinphi = halfe * Math.sin(phiT1); - phiT2 = MoreMath.HALF_PI - 2 * Math.atan(tR * Math.pow((0.5 - halfesinphi) / (0.5 + halfesinphi), halfe)); - } while ((Math.abs(phiT2 - phiT1) > EPS10) && (iIter++ < nIter)); - - double lamda = ((Math.atan2(x, y) + alpha) / n) + lamdaf; - - double lamda_deg = ProjMath.radToDeg(lamda); - double phi_deg = ProjMath.radToDeg(phiT2); - - if (llp == null) { - llp = new LatLonPoint.Double(); - } - - // the LatLonPoint.setLocation(double Lon, double Lat) method specifies - // Lat-lon in reversed order compared to other methods such as - // LatLonPoint.setLocation(double Lat, double lon, boolean isRadian). - // This is very confusing. - llp.setLocation(lamda_deg, phi_deg); // Lon, Lat - - return llp; - } /* end of function worldToLL */ - - /*---------------------------------------------------------------------------- - * FUNCTION: pixelToLL - * DATE CREATE: 28 February 1995 - * CREATED BY: David J. Ward - * Modified By: Steve C. Tang 02/20/2010 - * DESCRIPTION: This function converts pixel coordinate into lat, lon - * coordinate. - *--------------------------------------------------------------------------*/ - public Point2D pixelToLL(double xabs, double yabs, Point2D llp) { - - double x = locationCenterXLambert + ((xabs - locationCenterXPixel) / locationPixelsPerLambert); - double y = locationCenterYLambert + ((locationCenterYPixel - yabs) / locationPixelsPerLambert); - - worldToLL(x, y, llp); - - return llp; - } /* end of function pixelToLL */ - - protected Point2D plotablePoint = new Point2D.Double(); - - /** - * Determine if the location is plotable on the screen. The Lambert - * Conformal projection does not lend its self to a simple determination. - * This method invokes forward to obtain the screen coordinates. If the - * screen coordinates are visible returns true otherwise returns false. - * - * @param lat latitude in degrees - * @param lon longitude in degrees - * @return true is plotable, otherwise false - */ - public boolean isPlotable(double lat, double lon) { - // It is almost impossible to determine it the location - // is plotable without calling forward() for the Point - // and checking if the point is in bounds. - // Be lazy and return true. - - if (lat < -70d) - return false; - forward(lat, lon, plotablePoint); - double x = plotablePoint.getX(); - double y = plotablePoint.getY(); - - return (x >= 0 && x < this.width && y >= 0 && y < height); - } - - /** - * Determine if the location is plotable - * - * @param llpoint location to check - * @return returns true is plotable, otherwise false - */ - public boolean isPlotable(LatLonPoint llpoint) { - return isPlotable(llpoint.getY(), llpoint.getX()); - } - - /** - * Forward projects lat,lon into XY space and sets the results in the p - * provided. - *

- * - * @return Point2D p - * @param lat latitude - * @param lon longitude - * @param p Resulting XY Point2D - * @param isRadian indicates that lat,lon arguments are in radians - */ - public Point2D forward(double lat, double lon, Point2D p, boolean isRadian) { - if (p == null) { - p = new Point2D.Double(); - } - _forward(lat, lon, p, isRadian); - return p; - } - - protected double _forward(double lat, double lon, Point2D p, boolean isRadian) { - - // Figure out the point for screen coordinates. Need to take - // into account that the origin point of the projection may be - // off screen, so we need to take the calculated world - // coordinates of the center of the screen and subtract the - // screen offset from that. - if (isRadian) { - return LLToPixel(ProjMath.radToDeg(lat), ProjMath.radToDeg(lon), p); - } else { - return LLToPixel(lat, lon, p); - } - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - *

- * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llp LatLonPoint - * @return LatLonPoint llp - * @see Proj#inverse(Point2D) - */ - public T inverse(double x, double y, T llp) { - if (llp == null) { - llp = (T) new LatLonPoint.Double(); - } - // convert from screen to world coordinates - pixelToLL(x, y, llp); - return llp; - } - - /** - * Get the upper left (northwest) point of the projection. - *

- * Returns the upper left point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * - * @return LatLonPoint - */ - public LatLonPoint getUpperLeft() { - // In a conic projection the upper left is meaningless - // unless at relatively small scales. - // Return 90.0 -180 until someone figures out a better way. - return new LatLonPoint.Double(90.0, -180.0); - } - - /** - * Get the lower right (southeast) point of the projection. - *

- * Returns the lower right point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * - * @return LatLonPoint - */ - public LatLonPoint getLowerRight() { - // In a conic projection the upper left is meaningless - // unless at relatively small scales. - // Return 90.0 -180 until someone figures out a better way. - return new LatLonPoint.Double(-90.0, 180.0); - } - - public double getReferenceLon() { - return centralMeridian; - } - - /** - * Get the name string of the projection. - * - * @return the projection name - */ - public String getName() { - return LambertConformalName; - } - - /** - * Forward project a raw array of radian points. This assumes nothing about - * the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of lat,lon,... in radians - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - - double[] drawllpts = new double[rawllpts.length]; - System.arraycopy(drawllpts, 0, rawllpts, 0, rawllpts.length); - - return forwardRaw(drawllpts, rawoff, xcoords, ycoords, visible, copyoff, copylen); - } - - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, int copyoff, - int copylen) { - boolean visibleTotal = false; - // HACK grabbed from Cylindrical. Might need fixing. - Point temp = new Point(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp, true); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - - visible[i] = (0 <= temp.x && temp.x <= width) && (0 <= temp.y && temp.y <= height); - - if (visible[i] == true && visibleTotal == false) { - visibleTotal = true; - } - - } - // if everything is visible - return visibleTotal; - } - - /** - * Forward project a lat/lon Poly. Remember to specify vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? this is currently ignored for cylindrical - * projections. - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - - double[] drawllpts = new double[rawllpts.length]; - System.arraycopy(drawllpts, 0, rawllpts, 0, rawllpts.length); - - return _forwardPoly(drawllpts, ltype, nsegs, isFilled); - } - - public ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - - int i, j, k; - - // determine length of pairs - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // Not concerned with any polygons that are completely below - // 60S - - double minlat = ProjMath.degToRad(-60f); - boolean allBelowMinLat = true; - for (i = 0, j = 0; i < len; i++, j += 2) { - double l = rawllpts[j + 1]; - while (l < 0f) - l += Math.PI * 2f; - if (rawllpts[j] > minlat) { - allBelowMinLat = false; - } - } - if (allBelowMinLat) { - return new ArrayList(0); - } - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - - Point temp = new Point(); - int[] xa = new int[len]; - float[] xs = new float[len]; - float[] ys = new float[len]; - double dlamda1, dlamda2; - - // forward project the points - k = 0; - xa[k] = 0; - i = 0; - dlamda1 = _forward(rawllpts[i], rawllpts[i + 1], temp, true); - xs[i] = temp.x; - ys[i] = temp.y; - for (i = 1, j = 2; i < len; i++, j += 2) { - dlamda2 = _forward(rawllpts[j], rawllpts[j + 1], temp, true); - if (Math.abs(dlamda2 - dlamda1) >= Math.PI) { - xa[++k] = i; - } - xs[i] = temp.x; - ys[i] = temp.y; - dlamda1 = dlamda2; - } - - if (xa[k] < len) - xa[++k] = len; - - ArrayList ret_val = new ArrayList(2); - - for (i = 0; i < k; i++) { - len = xa[i + 1] - xa[i]; - if (len > 0) { - float[] xf = new float[len]; - float[] yf = new float[len]; - for (j = 0; j < len; j++) { - xf[j] = xs[j + xa[i]]; - yf[j] = ys[j + xa[i]]; - } - if (i > 0 && i == k - 1 && (xs[0] == xs[xs.length - 1] && ys[0] == ys[ys.length - 1])) { - int len0 = ((float[]) ret_val.get(0)).length; - float[] x0 = new float[len0 + len]; - float[] y0 = new float[len0 + len]; - System.arraycopy(xf, 0, x0, 0, len); - System.arraycopy(yf, 0, y0, 0, len); - System.arraycopy(((float[]) ret_val.get(0)), 0, x0, len, len0); - System.arraycopy(((float[]) ret_val.get(1)), 0, y0, len, len0); - ret_val.set(0, x0); - ret_val.set(1, y0); - } else { - ret_val.add(xf); - ret_val.add(yf); - } - } - } - - return ret_val; - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll1 coordinate, the upper left corner of the area - * of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll2 coordinate, usually the lower right corner of - * the area of interest. - */ - @Override - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2) { - - // super does not calculate scale correct for projections that does use - // the same earth radius up north.. - - double widthPX = point2.getX() - point1.getX(); - - Point2D xx1 = LLToWorld(ll1.getY(), ll1.getX(), new Point2D.Double()); - Point2D xx2 = LLToWorld(ll2.getY(), ll2.getX(), new Point2D.Double()); - - double widthMap = (xx2.getX() - xx1.getX()); - double widthScale = (((double) getPPM()) * (widthMap / widthPX)); - - // TODO: use width-, height- or medium scale? - // Until then, this isn't needed: - - // double heightPX = point2.y - point1.y; - // double heightMap = (xx2.getY() - xx1.getY()); - // double heightScale = (((double) getPPM()) * (heightMap / heightPX)); - - return (float) widthScale; - } - - /** - * Draw the background for the projection. - * - * @param g Graphics2D - * @param paint java.awt.Paint to use for the background - */ - public void drawBackground(java.awt.Graphics2D g, java.awt.Paint paint) { - g.setPaint(paint); - drawBackground(g); - } - - /** - * Draw the background for the projection. - * - * @param g Graphics - */ - public void drawBackground(java.awt.Graphics g) { - g.fillRect(0, 0, getWidth(), getHeight()); - } - - /** - * Special function m = cos(phi) / sqrt(1.0 - (e*sin(phi))**2) - * - * @param sinphi double - * @param cosphi double - * @param e double - * @return double - */ - public static double lambMsfn(double sinphi, double cosphi, double e) { - sinphi *= e; - return cosphi / Math.sqrt(1.d - sinphi * sinphi); - } - - /** - * Special function t = tan(PI/4-phi/2) / pow((1-sinphi)/(1+sinphi), .5*e) - * - * @param phi double - * @param sinphi double - * @param e double - * @return double - */ - public static double lambTsfn(double phi, double sinphi, double e) { - sinphi *= e; - return Math.tan((MoreMath.HALF_PI - phi) * 0.5d) * Math.pow((1.d + sinphi) / (1.d - sinphi), 0.5d * e); - } - - /** - * test method - * - * @param argv command line parameters - */ - public static void main(String argv[]) { - Debug.init(); - Debug.put("Lambert"); - LambertConformal proj = null; - - proj = new LambertConformal(new LatLonPoint.Double(50.679572292f, 5.807370150f), 100000.0f, 620, 480, 4.3569395237f, // centralMeridian - -49.833333109f, // lambert_sp_one - -51.166666321f, // lambert_sp_two - 90.0f, // referenceLatitude - 150000.01f, // falseEasting - 5400088.44f, // falseNorthing - Ellipsoid.WGS_84); - - Debug.message("Lambert", "(1)" + proj.inverse(310, 240)); - - LatLonPoint llp = new LatLonPoint.Double(0.0f, 0.0f); - Debug.message("Lambert", "(2)" + proj.worldToLL(251763.20f, 153034.13f, llp)); - - LatLonPoint pt = new LatLonPoint.Double(50.679572292f, 5.807370150f); - Point2D lp = proj.LLToWorld(pt.getY(), pt.getX(), new Point2D.Double()); - Debug.message("Lambert", "(3)" + lp); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LambertConformalLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/LambertConformalLoader.java deleted file mode 100644 index e85e3b5cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LambertConformalLoader.java +++ /dev/null @@ -1,229 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/LambertConformalLoader.java,v $ -// $RCSfile: LambertConformalLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/15 19:38:33 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the LambertConformal projection to an - * OpenMap application. - * - * @see BasicProjectionLoader - */ -public class LambertConformalLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public final static String CentralMeridianProperty = "centralMeridian"; - public final static String StandardParallelOneProperty = "standardParallel1"; - public final static String StandardParallelTwoProperty = "standardParallel2"; - public final static String ReferenceLatitudeProperty = "referenceLatitude"; - public final static String FalseEastingProperty = "falseEasting"; - public final static String FalseNorthingProperty = "faleNorthing"; - - protected double centralMeridian = -71.50f; - protected double standardParallel1 = 41.716667f; - protected double standardParallel2 = 42.683333f; - protected double referenceLatitude = 41.0; - protected double falseEasting = 200000; - protected double falseNorthing = 750000; - - public LambertConformalLoader() { - super(LambertConformal.class, - LambertConformal.LambertConformalName, - "Lambert Conformal Projection"); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - double central_meridian = PropUtils.doubleFromProperties(props, - CentralMeridianProperty, - centralMeridian); - double sp_one = PropUtils.doubleFromProperties(props, - StandardParallelOneProperty, - standardParallel1); - double sp_two = PropUtils.doubleFromProperties(props, - StandardParallelTwoProperty, - standardParallel2); - double rl = PropUtils.doubleFromProperties(props, - ReferenceLatitudeProperty, - referenceLatitude); - double fe = PropUtils.doubleFromProperties(props, - FalseEastingProperty, - falseEasting); - double fn = PropUtils.doubleFromProperties(props, - FalseNorthingProperty, - falseNorthing); - Ellipsoid ellps = (Ellipsoid) props.get(ProjectionFactory.DATUM); - - return new LambertConformal(llp, scale, width, height, central_meridian, sp_one, sp_two, rl, fe, fn, ellps); - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("LambertConformalLoader: problem creating LambertConformal projection " - + e.getMessage()); - } - } - - throw new ProjectionException("LambertConformalLoader: problem creating LambertConformal projection"); - - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - centralMeridian = PropUtils.doubleFromProperties(props, prefix - + CentralMeridianProperty, centralMeridian); - standardParallel1 = PropUtils.doubleFromProperties(props, prefix - + StandardParallelOneProperty, standardParallel1); - standardParallel2 = PropUtils.doubleFromProperties(props, prefix - + StandardParallelTwoProperty, standardParallel2); - referenceLatitude = PropUtils.doubleFromProperties(props, prefix - + ReferenceLatitudeProperty, referenceLatitude); - falseEasting = PropUtils.doubleFromProperties(props, prefix - + FalseEastingProperty, falseEasting); - falseNorthing = PropUtils.doubleFromProperties(props, prefix - + FalseNorthingProperty, falseNorthing); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + CentralMeridianProperty, - Double.toString(centralMeridian)); - props.put(prefix + StandardParallelOneProperty, - Double.toString(standardParallel1)); - props.put(prefix + StandardParallelTwoProperty, - Double.toString(standardParallel2)); - props.put(prefix + ReferenceLatitudeProperty, - Double.toString(referenceLatitude)); - props.put(prefix + FalseEastingProperty, Double.toString(falseEasting)); - props.put(prefix + FalseNorthingProperty, - Double.toString(falseNorthing)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String internString = i18n.get(LambertConformalLoader.class, - CentralMeridianProperty, - "Central Meridian"); - props.put(CentralMeridianProperty + LabelEditorProperty, internString); - - internString = i18n.get(ProjectionLoader.class, - CentralMeridianProperty, - I18n.TOOLTIP, - "Central Meridian Longitude for Projection"); - props.put(CentralMeridianProperty, internString); - - internString = i18n.get(LambertConformalLoader.class, - StandardParallelOneProperty, - "Standard Parallel 1"); - props.put(StandardParallelOneProperty + LabelEditorProperty, - internString); - - internString = i18n.get(ProjectionLoader.class, - StandardParallelOneProperty, - I18n.TOOLTIP, - "First Standard Parallel Latitude for Projection"); - props.put(StandardParallelOneProperty, internString); - - internString = i18n.get(LambertConformalLoader.class, - StandardParallelTwoProperty, - "Standard Parallel 2"); - props.put(StandardParallelTwoProperty + LabelEditorProperty, - internString); - - internString = i18n.get(ProjectionLoader.class, - StandardParallelTwoProperty, - I18n.TOOLTIP, - "Second Standard Parallel Latitude for Projection"); - props.put(StandardParallelTwoProperty, internString); - - internString = i18n.get(LambertConformalLoader.class, - ReferenceLatitudeProperty, - "Reference Latitude"); - props.put(ReferenceLatitudeProperty + LabelEditorProperty, internString); - - internString = i18n.get(ProjectionLoader.class, - ReferenceLatitudeProperty, - I18n.TOOLTIP, - "The Reference Latitude of the Projection Origin"); - props.put(ReferenceLatitudeProperty, internString); - - internString = i18n.get(LambertConformalLoader.class, - FalseEastingProperty, - "False Easting"); - props.put(FalseEastingProperty + LabelEditorProperty, internString); - - internString = i18n.get(ProjectionLoader.class, - FalseEastingProperty, - I18n.TOOLTIP, - "Meters added to projected location of origin E/W"); - props.put(FalseEastingProperty, internString); - - internString = i18n.get(LambertConformalLoader.class, - FalseNorthingProperty, - "False Northing"); - props.put(FalseNorthingProperty + LabelEditorProperty, internString); - - internString = i18n.get(ProjectionLoader.class, - FalseNorthingProperty, - I18n.TOOLTIP, - "Meters added to projected location of origin N/S"); - props.put(FalseNorthingProperty, internString); - - props.put(initPropertiesProperty, PrettyNameProperty + " " - + DescriptionProperty + " " + CentralMeridianProperty + " " - + StandardParallelOneProperty + " " - + StandardParallelTwoProperty + " " + ReferenceLatitudeProperty - + " " + FalseEastingProperty + " " + FalseNorthingProperty); - - return props; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Length.java b/src/core/src/main/java/com/bbn/openmap/proj/Length.java deleted file mode 100644 index 47fcc06f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Length.java +++ /dev/null @@ -1,182 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Length.java,v $ -// $RCSfile: Length.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * Length is a convenience class used for a couple of things. It can be used to - * specify unit type, and can be used for conversion from radians to/from - * whatever units are represented by the implemented class. - */ -public enum Length { - - /** Miles, in WGS 84 spherical earth model units. */ - MILE("mile", "miles", Planet.wgs84_earthEquatorialCircumferenceMiles_D), - /** Feet, in WGS 84 spherical earth model units. */ - FEET("feet", "ft", Planet.wgs84_earthEquatorialCircumferenceMiles_D * 5280.0), - /** Feet, in WGS 84 spherical earth model units. */ - YARD("yards", "yd", Planet.wgs84_earthEquatorialCircumferenceMiles_D * 5280.0 / 3.0), - /** Meters, in WGS 84 Spherical earth model units. */ - METER("meter", "m", Planet.wgs84_earthEquatorialCircumferenceMeters_D), - /** Kilometers, in WGS 84 Spherical earth model units. */ - KM("kilometer", "km", Planet.wgs84_earthEquatorialCircumferenceKM_D), - /** Nautical Miles, in WGS 84 Spherical earth model units. */ - NM("nautical mile", "nm", Planet.wgs84_earthEquatorialCircumferenceNMiles_D), - /** Decimal Degrees, in WGS 84 Spherical earth model units. */ - DECIMAL_DEGREE("decimal degree", "deg", 360.0), - /** Data Mile, in WGS 84 spherical earth model units. */ - DM("datamile", "dm", Planet.wgs84_earthEquatorialCircumferenceMiles_D * 5280.0 / 6000.0), - - /** Radians, in terms of a spherical earth. */ - RADIAN("radian", "rad", com.bbn.openmap.util.MoreMath.TWO_PI_D) { - public float toRadians(float numUnits) { - return numUnits; - } - - public double toRadians(double numUnits) { - return numUnits; - } - - public float fromRadians(float numRadians) { - return numRadians; - } - - public double fromRadians(double numRadians) { - return numRadians; - } - }; - - /** Unit/radians */ - protected final double constant; - protected final String name; - protected final String abbr; - protected double unitEquatorCircumference; - protected transient I18n i18n = Environment.getI18n(); - - /** - * Create a Length, with a name an the number of it's units that go around - * the earth at its equator. The name and abbreviation are converted to - * lower case for consistency. - */ - private Length(String name, String abbr, double unitEquatorCircumference) { - this.name = i18n.get(this, abbr + ".name", name).toLowerCase().intern(); - this.unitEquatorCircumference = unitEquatorCircumference; - this.constant = unitEquatorCircumference / com.bbn.openmap.util.MoreMath.TWO_PI_D; - this.abbr = abbr.toLowerCase().intern(); - } - - /** - * Given a number of units provided by this Length, convert to a number of - * radians. - */ - public float toRadians(float numUnits) { - getLogger().fine("Translating " + name + " from radians"); - return numUnits / (float) constant; - } - - public double toRadians(double numUnits) { - getLogger().fine("Translating " + name + " from radians"); - return numUnits / constant; - } - - /** - * Given a number of radians, convert to the number of units represented by - * this length. - */ - public float fromRadians(float numRadians) { - getLogger().fine("Translating radians from " + name); - return numRadians * (float) constant; - } - - /** - * Given a number of radians, convert to the number of units represented by - * this length. - */ - public double fromRadians(double numRadians) { - getLogger().fine("Translating radians from " + name); - return numRadians * constant; - } - - /** - * Return the name for this length type. - */ - public String toString() { - return name; - } - - /** - * Return the abbreviation for this length type. - */ - public String getAbbr() { - return abbr; - } - - /** - * Get the Length object with the given name or abbreviation. If nothing - * exists with that name, then return null. The lower case version of the - * name or abbreviation is checked against the available options. - */ - public static Length get(String name) { - if (name != null) { - for (Length length : values()) { - if (length.name.equalsIgnoreCase(name) || length.abbr.equalsIgnoreCase(name)) { - return length; - } - } - } - return null; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Length.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LineCoordinateGenerator.java b/src/core/src/main/java/com/bbn/openmap/proj/LineCoordinateGenerator.java deleted file mode 100644 index 0c7da252a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LineCoordinateGenerator.java +++ /dev/null @@ -1,345 +0,0 @@ -package com.bbn.openmap.proj; - -import java.awt.Shape; -import java.awt.geom.FlatteningPathIterator; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * Generator class that connects simple coordinates with complex lines (great - * circle or rhumb). If you provide decimal degrees, the answer will be in - * decimal degrees. If coords are provided in radians, the answer will be in - * radians. - * - *

- * Usage:
- * 
- * double[] coords = new double[] { 30.0, -125.0, 30.0, -90.0, 15.0, -90.0, 15, -125.0, 30.0, -125.0 };
- * double[] complexCoords = LineCoordinateGenerator.fromDegrees(coords).withSegmentsPerDegrees(10).greatCircleLineDoubles();
- * 
- * 
- * - * @author dietrick - */ -public class LineCoordinateGenerator { - - public final static double DEFAULT_SEGS_PER_DEG = 10; - double segsPerDeg = DEFAULT_SEGS_PER_DEG; - final double[] llpts; - private boolean returnDegrees = false; - - /** - * Use static methods to create one, designating radians or degrees. - * - * @param radians - */ - private LineCoordinateGenerator(double[] radians) { - this.llpts = radians; - } - - /** - * Create LCG with radian coordinates. - * - * @param radians array of coordinates in radians, in lat, lon, lat, lon - * order. - * @return LCG - */ - public static LineCoordinateGenerator fromRadians(double[] radians) { - return new LineCoordinateGenerator(radians); - } - - /** - * Create LCG with decimal degree coordinates. - * - * @param degrees array of coordinates in degrees, in lat, lon, lat, lon - * order. - * @return LCG - */ - public static LineCoordinateGenerator fromDegrees(double[] degrees) { - double[] radians = new double[degrees.length]; - System.arraycopy(degrees, 0, radians, 0, degrees.length); - ProjMath.arrayDegToRad(radians); - return new LineCoordinateGenerator(radians).fromDegrees(); - } - - private LineCoordinateGenerator fromDegrees() { - returnDegrees = true; - return this; - } - - /** - * Set how complex the line is by setting how many segments per degree are - * used to approximate the curve. - * - * @param spd the default is 10 segments per degree - * @return this - */ - public LineCoordinateGenerator withSegmentsPerDegrees(double spd) { - this.segsPerDeg = spd; - return this; - } - - /** - * Return the source coordinates connected by great circle lines - * - * @return double[] in lat, lon, lat, lon order. - */ - public double[] greatCircleLineDoubles() { - return toDoubles(greatCircleLineShape()).get(0); - } - - /** - * Create a java.awt.Shape object of coordinates connected by great circle - * lines. - * - * @return java.awt.Shape - */ - public Shape greatCircleLineShape() { - GeneralPath path = null; - if (llpts != null && llpts.length >= 4 && llpts.length % 2 == 0) { - double y1 = llpts[0]; - double x1 = llpts[1]; - - path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, llpts.length / 2); - boolean firstCoords = true; - - for (int i = 2; i < llpts.length; i += 2) { - double y2 = llpts[i]; - double x2 = llpts[i + 1]; - - double radDist = GreatCircle.sphericalDistance(y1, x1, y2, x2); - int nsegs = (int) (ProjMath.radToDeg(radDist) * segsPerDeg); // segs/degree - - if (nsegs == 0) { - nsegs = 1; - } - - double[] coords = GreatCircle.greatCircle(y1, x1, y2, x2, nsegs, false); - - if (returnDegrees) { - ProjMath.arrayRadToDeg(coords); - } - - for (int j = 0; j <= coords.length - 1; j += 2) { - if (firstCoords) { - path.moveTo(coords[j + 1], coords[j]); - firstCoords = false; - } else { - path.lineTo(coords[j + 1], coords[j]); - } - } - - x1 = x2; - y1 = y2; - } - - // End point, since great circle calc doesn't tack on the last - // point. - if (returnDegrees) { - path.lineTo(ProjMath.radToDeg(x1), ProjMath.radToDeg(y1)); - } else { - path.lineTo(x1, y1); - } - } - - return path; - } - - /** - * Return the source coordinates connected by rhumb lines - * - * @return double[] in lat, lon, lat, lon order. - */ - public double[] rhumbLineDoubles() { - return toDoubles(rhumbLineShape()).get(0); - } - - /** - * Create a java.awt.Shape object of coordinates connected by rhumb lines. - * - * @return java.awt.Shape - */ - public Shape rhumbLineShape() { - GeneralPath path = null; - if (llpts != null && llpts.length >= 4 && llpts.length % 2 == 0) { - LatLonPoint ll1 = new LatLonPoint.Double(llpts[0], llpts[1], true); - - path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, llpts.length / 2); - boolean firstCoords = true; - - for (int i = 2; i < llpts.length - 1; i += 2) { - LatLonPoint ll2 = new LatLonPoint.Double(llpts[i], llpts[i + 1], true); - - if (firstCoords) { - moveTo(path, ll1); - firstCoords = false; - } else { - lineTo(path, ll1); - } - - double radDist = RhumbCalculator.getDistanceBetweenPoints(ll1, ll2); - double angle = RhumbCalculator.getAzimuthBetweenPoints(ll1, ll2); - - double segDistIncrease = radDist / ProjMath.degToRad(ProjMath.radToDeg(radDist) * segsPerDeg); // segs/degree - - double segDist = segDistIncrease; - - while (segDist < radDist) { - LatLonPoint llp = RhumbCalculator.calculatePointOnRhumbLine(ll1, angle, segDist); - lineTo(path, llp); - segDist += segDistIncrease; - } - - ll1 = ll2; - } - - // Make sure last coordinate is on return shape - lineTo(path, ll1); - - } - - return path; - } - - private void moveTo(GeneralPath path, LatLonPoint llp) { - if (returnDegrees) { - path.moveTo(llp.getX(), llp.getY()); - } else { - path.moveTo(llp.getRadLon(), llp.getRadLat()); - } - } - - private void lineTo(GeneralPath path, LatLonPoint llp) { - if (returnDegrees) { - path.lineTo(llp.getX(), llp.getY()); - } else { - path.lineTo(llp.getRadLon(), llp.getRadLat()); - } - } - - /** - * Creates a Shape object from provided coordinates. - * - * @return java.awt.Shape - */ - public Shape straightLineShape() { - GeneralPath path = null; - if (llpts != null && llpts.length >= 4 && llpts.length % 2 == 0) { - double y1 = llpts[0]; - double x1 = llpts[1]; - - path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, llpts.length / 2); - if (returnDegrees) { - path.moveTo(ProjMath.radToDeg(x1), ProjMath.radToDeg(y1)); - } else { - path.moveTo(x1, y1); - } - - for (int i = 2; i < llpts.length - 1; i += 2) { - x1 = llpts[i + 1]; - y1 = llpts[i]; - - if (returnDegrees) { - path.lineTo(ProjMath.radToDeg(x1), ProjMath.radToDeg(y1)); - } else { - path.lineTo(x1, y1); - } - } - } - return path; - } - - /** - * Convert a Shape object into a List of double[]. Separate double[] are - * created in case there's a moveTo in the order of coordinates in Shape. - * - * @param s java.awt.Shape - * @return a List of double[] - */ - public static List toDoubles(Shape s) { - List coordLists = new ArrayList(); - - PathIterator pi2 = s.getPathIterator(null); - FlatteningPathIterator pi = new FlatteningPathIterator(pi2, .25); - double[] coords = new double[6]; - - double lastMovedToPntX = Double.NaN; - double lastMovedToPntY = Double.NaN; - - List curCoord = null; - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - if (type == PathIterator.SEG_LINETO) { - - // Moved to the next point - curCoord = assertList(curCoord); - // lat/lon order - curCoord.add(coords[1]); - curCoord.add(coords[0]); - - } else if (type == PathIterator.SEG_MOVETO) { - - if (curCoord != null && !curCoord.isEmpty()) { - coordLists.add(toArray(curCoord)); - curCoord = null; - } - - // Usually the first set of coords - lastMovedToPntX = coords[0]; - lastMovedToPntY = coords[1]; - - curCoord = assertList(curCoord); - curCoord.add(lastMovedToPntY); - curCoord.add(lastMovedToPntX); - - } else if (type == PathIterator.SEG_CLOSE) { - - // The last set of coords, if they should go back to the first - // set of coords. - final double x = coords[0]; - final double y = coords[1]; - - if (x != lastMovedToPntX && y != lastMovedToPntY) { - curCoord = assertList(curCoord); - curCoord.add(y); - curCoord.add(x); - } - - if (curCoord != null && !curCoord.isEmpty()) { - coordLists.add(toArray(curCoord)); - curCoord = null; - } - } - - pi.next(); - } - - if (curCoord != null && !curCoord.isEmpty()) { - coordLists.add(toArray(curCoord)); - } - - return coordLists; - } - - private static List assertList(List list) { - if (list != null) { - return list; - } - return new ArrayList(); - } - - private static double[] toArray(List coords) { - double[] ret = new double[coords.size()]; - int i = 0; - for (double d : coords) { - ret[i++] = d; - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/LineType.java b/src/core/src/main/java/com/bbn/openmap/proj/LineType.java deleted file mode 100644 index fdab21c90..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/LineType.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/LineType.java,v $ -// $RCSfile: LineType.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * LineType constants. - */ -public final class LineType { - - // cannot construct - private LineType() {} - - /** - * Straight lines are the easiest and fastest to draw. Use them if - * you're concerned about speed of projecting. - */ - final public static transient int Straight = 1; - - /** - * Rhumb lines follow a constant bearing. - */ - final public static transient int Rhumb = 2; - - /** - * Great circle lines follow the shortest path between two points - * on a sphere. - */ - final public static transient int GreatCircle = 3; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Mercator.java b/src/core/src/main/java/com/bbn/openmap/proj/Mercator.java deleted file mode 100644 index 5b4b2f9b1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Mercator.java +++ /dev/null @@ -1,386 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Mercator.java,v $ -// $RCSfile: Mercator.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/04/07 15:21:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Implements the Mercator projection. - */ -public class Mercator extends Cylindrical { - - /** - * The Mercator name. - */ - public final static transient String MercatorName = "Mercator"; - - // maximum number of segments to draw for rhumblines. - protected final static int MAX_RHUMB_SEGS = 512; - - /* - * HACK epsilon: skirt the edge of the infinite. If this is too small then - * we get too close to +-INFINITY when we forward project. Tweak this if you - * start getting Infinity or NaN's for forward(). - */ - protected static double epsilon = 0.01f; - - // world<->screen coordinate offsets - protected transient double hy, wx; - - // almost constant projection parameters - protected transient double tanCtrLat; - protected transient double asinh_of_tanCtrLat; - - /** - * Construct a Mercator projection. - * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public Mercator(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - } - - // protected void finalize() { - // Debug.message("mercator", "Mercator finalized"); - // } - - /** - * Return stringified description of this projection. - * - * @return String - * @see Projection#getProjectionID - */ - public String toString() { - return "Mercator[" + super.toString(); - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- * - */ - protected void computeParameters() { - Debug.message("mercator", "Mercator.computeParameters()"); - super.computeParameters(); - - // do some precomputation of stuff - tanCtrLat = Math.tan(centerY); - asinh_of_tanCtrLat = MoreMath.asinh(tanCtrLat); - - // compute the offsets - hy = height / 2; - wx = width / 2; - } - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - *

- * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_POLE - epsilon) { - return NORTH_POLE - epsilon; - } else if (lat < SOUTH_POLE + epsilon) { - return SOUTH_POLE + epsilon; - } - return lat; - } - - // protected float forward_x(float lambda) { - // return scaled_radius * wrap_longitude(lambda - ctrLon) + - // (float)wx; - // } - - // protected float forward_y(float phi) { - // return (float)hy - (scaled_radius * - // (MoreMath.asinh((float)Math.tan(phi)) - - // asinh_of_tanCtrLat)); - // } - - /** - * Checks if a LatLonPoint is plot-able. - *

- * A point is always plot-able in the Mercator projection (even the North - * and South poles since we normalize latitude). - * - * @param lat double latitude in decimal degrees - * @param lon double longitude in decimal degrees - * @return boolean - */ - public boolean isPlotable(double lat, double lon) { - return true; - } - - /** - * Forward projects lat,lon into XY space and returns a Point2D. - *

- * - * @param lat double latitude in radians - * @param lon double longitude in radians - * @param p Resulting XY Point2D - * @param isRadian bogus argument indicating that lat,lon arguments are in - * radians - * @return Point2D p - */ - public Point2D forward(double lat, double lon, Point2D p, boolean isRadian) { - if (!isRadian) { - lat = ProjMath.degToRad(lat); - lon = ProjMath.degToRad(lon); - } - // first normalize - lat = normalizeLatitude(lat); - lon = wrapLongitude(lon); - - // same as forward_x and forward_y, and convert to screen - // coords - double x = (scaled_radius * wrapLongitude(lon - centerX)) + wx; - double y = hy - (scaled_radius * (MoreMath.asinh(Math.tan(lat)) - asinh_of_tanCtrLat)); - p.setLocation(x, y); - return p; - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llp LatLonPoint - * @return LatLonPoint llp - * @see Proj#inverse(Point2D) - */ - public T inverse(double x, double y, T llp) { - - if (llp == null) { - llp = (T) new LatLonPoint.Double(); - } - - // convert from screen to world coordinates - x -= wx; - y = hy - y; - - // inverse project - double wc = asinh_of_tanCtrLat * scaled_radius; - - llp.setLocation(Math.toDegrees(wrapLongitude(x / scaled_radius + centerX)), Math.toDegrees(normalizeLatitude(Math.atan(Math.sinh((y + wc) - / scaled_radius))))); - - return llp; - } - - /** - * Computes the best stepping factor for a rhumbline. - *

- * Computes the best stepping factor between two x,y points in order to - * interpolate points on a rhumb line. (We calculate rhumb lines by forward - * projecting the line in the Mercator projection, and then calculating - * segments along the straight line between them.) - * - * @param pt1 Point2D - * @param pt2 Point2D - * @return int number of points to use - */ - protected final static int rhumbStep(Point2D pt1, Point2D pt2) { - int step = (int) DrawUtil.distance(pt1.getX(), pt1.getY(), pt2.getX(), pt2.getY()); - - if (step > 8192) { - step = 512; - } else { - step >>= 3;// step/8 - } - return (step == 0) ? 1 : step; - } - - /** - * Calculates the points along a rhumbline between two XY points. - *

- * Loxodromes are straight in the Mercator projection. Calculate a bunch of - * extra points between the two points, inverse project back into LatLons - * and return all the vertices. - * - * @param from Point2D - * @param to Point2D - * @param include_last include the very last point? - * @param nsegs number of segments - * @return float[] of lat, lon, lat, lon, ... in RADIANS! - */ - protected float[] rhumbProject(Point2D from, Point2D to, boolean include_last, int nsegs) { - - // calculate pixel distance - if (nsegs < 1) { - // dynamically calculate the number of segments to draw - nsegs = DrawUtil.pixel_distance((int) from.getX(), (int) from.getY(), (int) to.getX(), (int) to.getY()) >> 3;// /8 - if (nsegs == 0) - nsegs = 1; - else if (nsegs > MAX_RHUMB_SEGS) - nsegs = MAX_RHUMB_SEGS; - } - - // Debug.output( - // "from=("+from.x+","+from.y+")to=("+to.x+","+to.y+")"); - LatLonPoint llp = new LatLonPoint.Double(); - // inverse(from.x, from.y, llp); - // LatLonPoint llp2 = inverse(to.x, to.y, new LatLonPoint()); - // Debug.output( - // "invfrom=("+llp.getLatitude()+","+llp.getLongitude()+ - // ")invto=("+llp2.getLatitude()+","+llp2.getLongitude()+")"); - // Debug.output("nsegs="+nsegs); - // calculate nsegs(+1) extra vertices between endpoints - int[] xypts = DrawUtil.lineSegments((int) from.getX(), (int) from.getY(), // coords - (int) to.getX(), (int) to.getY(), nsegs, // number of segs - // between - include_last, // include last point - new int[nsegs << 1] // retval - ); - - float[] llpts = new float[xypts.length]; - for (int i = 0; i < llpts.length; i += 2) { - // System.out.print("("+xypts[i]+","+xypts[i+1]+")"); - inverse(xypts[i], xypts[i + 1], llp); - llpts[i] = (float) llp.getRadLat(); - llpts[i + 1] = (float) llp.getRadLon(); - } - // Debug.output(""); - return llpts; - } - - /** - * Calculates the points along a rhumbline between two XY points. - *

- * Loxodromes are straight in the Mercator projection. Calculate a bunch of - * extra points between the two points, inverse project back into LatLons - * and return all the vertices. - * - * @param from Point2D - * @param to Point2D - * @param include_last include the very last point? - * @param nsegs number of segments - * @return double[] of lat, lon, lat, lon, ... in RADIANS! - */ - protected double[] rhumbProjectDouble(Point2D from, Point2D to, boolean include_last, int nsegs) { - - // calculate pixel distance - if (nsegs < 1) { - // dynamically calculate the number of segments to draw - nsegs = DrawUtil.pixel_distance((int) from.getX(), (int) from.getY(), (int) to.getX(), (int) to.getY()) >> 3;// /8 - if (nsegs == 0) - nsegs = 1; - else if (nsegs > MAX_RHUMB_SEGS) - nsegs = MAX_RHUMB_SEGS; - } - - // Debug.output( - // "from=("+from.x+","+from.y+")to=("+to.x+","+to.y+")"); - LatLonPoint llp = new LatLonPoint.Double(); - // inverse(from.x, from.y, llp); - // LatLonPoint llp2 = inverse(to.x, to.y, new LatLonPoint()); - // Debug.output( - // "invfrom=("+llp.getLatitude()+","+llp.getLongitude()+ - // ")invto=("+llp2.getLatitude()+","+llp2.getLongitude()+")"); - // Debug.output("nsegs="+nsegs); - // calculate nsegs(+1) extra vertices between endpoints - int[] xypts = DrawUtil.lineSegments((int) from.getX(), (int) from.getY(), // coords - (int) to.getX(), (int) to.getY(), nsegs, // number of segs - // between - include_last, // include last point - new int[nsegs << 1] // retval - ); - - double[] llpts = new double[xypts.length]; - for (int i = 0; i < llpts.length; i += 2) { - // System.out.print("("+xypts[i]+","+xypts[i+1]+")"); - inverse(xypts[i], xypts[i + 1], llp); - llpts[i] = llp.getRadLat(); - llpts[i + 1] = llp.getRadLon(); - } - // Debug.output(""); - return llpts; - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return MercatorName; - } - - // ------------------------------------------------------------- - - /* - * public void testPoint(float lat, float lon) { float x, y; lon = - * wrap_longitude(ProjMath.degToRad(lon)); lat = - * normalize_latitude(ProjMath.degToRad(lat)); x = forward_x(lon) - - * (float)wx; y = (float)hy - forward_y(lat); - * - * Debug.output( "(lon="+ProjMath.radToDeg(lon)+",lat="+ - * ProjMath.radToDeg(lat)+ ") = (x="+x+",y="+y+")"); lat = - * inverse_lat((float)hy-y); lon = wrap_longitude(inverse_lon(x+(float)wx)); - * Debug.output( "(x="+x+",y="+y+") = (lon="+ - * ProjMath.radToDeg(lon)+",lat="+ProjMath.radToDeg(lat)+")"); } - * - * public static void main (String argv[]) { Mercator proj=null; // proj = - * new Mercator(new LatLonPoint(0.0f, -180.0f), 1.0f, 620, 480); proj = new - * Mercator(new LatLonPoint(0.0f, 0.0f), 1.0f, 620, 480); // test on unit - * circle proj.setEarthRadius(1.0f); - * Debug.output("setEarthRadius("+proj.getEarthRadius()+")"); - * proj.setPPM(1); Debug.output("setPPM("+proj.getPPM()+")"); - * proj.setScale(1.0f); Debug.output("setScale("+proj.getScale()+")"); - * Debug.output(proj); - * - * Debug.output("---testing latitude"); proj.testPoint(0.0f, 0.0f); - * proj.testPoint(10.0f, 0.0f); proj.testPoint(40.0f, 0.0f); - * proj.testPoint(-85.0f, 0.0f); proj.testPoint(-80.0f, 0.0f); - * proj.testPoint(-90.0f, 0.0f); proj.testPoint(100.0f, 0.0f); - * proj.testPoint(-3272.0f, 0.0f); Debug.output("---testing longitude"); - * proj.testPoint(0.0f, 10.0f); proj.testPoint(0.0f, -10.0f); - * proj.testPoint(0.0f, 90.0f); proj.testPoint(0.0f, -90.0f); - * proj.testPoint(0.0f, 175.0f); proj.testPoint(0.0f, -175.0f); - * proj.testPoint(0.0f, 180.0f); proj.testPoint(0.0f, -180.0f); - * proj.testPoint(0.0f, 190.0f); proj.testPoint(0.0f, -190.0f); - * proj.testPoint(0.0f, 370.0f); proj.testPoint(0.0f, -370.0f); - * proj.testPoint(0.0f, 550.0f); proj.testPoint(0.0f, -550.0f); - * - * float LAT_RANGE = (float)Math.PI; float LON_RANGE = (float)Math.PI*2f; - * float HALF_LAT = (float)Math.PI/2f; float HALF_LON = (float)Math.PI; - * - * System.out.print("timing forward: "); long start = - * System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { - * proj.forward_x((float)Math.random()*LON_RANGE-HALF_LON); - * proj.forward_y((float)Math.random()*LAT_RANGE-HALF_LAT); } long stop = - * System.currentTimeMillis(); Debug.output((stop - start)/1000.0d + " - * seconds."); } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/MercatorLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/MercatorLoader.java deleted file mode 100644 index 71d706dd7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/MercatorLoader.java +++ /dev/null @@ -1,78 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/MercatorLoader.java,v $ -// $RCSfile: MercatorLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the Mercator projection to an OpenMap - * application. - * - * @see BasicProjectionLoader - */ -public class MercatorLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public final static ProjectionLoader defaultMercator = new MercatorLoader(); - - public MercatorLoader() { - super(Mercator.class, Mercator.MercatorName, "Mercator Projection"); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - return new Mercator(llp, scale, width, height); - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("MercatorLoader: problem creating Mercator projection " - + e.getMessage()); - } - } - - throw new ProjectionException("MercatorLoader: problem creating Mercator projection"); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Orthographic.java b/src/core/src/main/java/com/bbn/openmap/proj/Orthographic.java deleted file mode 100644 index c968fd70d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Orthographic.java +++ /dev/null @@ -1,484 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Orthographic.java,v $ -// $RCSfile: Orthographic.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/04/07 15:21:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.MoreMath; - -/** - * Implements the Orthographic projection. - */ -public class Orthographic extends Azimuth { - - /** - * The Orthographic name. - */ - public final static transient String OrthographicName = "Orthographic"; - - protected double hy, wx; - - // almost constant projection parameters - protected double cosCtrLat; - protected double sinCtrLat; - - public final static transient double epsilon = 0.0001f; - protected final static double NORTH_BOUNDARY = NORTH_POLE - epsilon; - protected final static double SOUTH_BOUNDARY = -NORTH_BOUNDARY; - - /** - * Construct an Orthographic projection. - * - * @param center LatLonPoint center of projection - * @param scale float scale of projection - * @param width width of screen - * @param height height of screen - */ - public Orthographic(LatLonPoint center, float scale, int width, int height) { - super(center, scale, width, height); - setMinScale(1000.0f); - } - - // protected void finalize() { - // Debug.message("proj", "Orthographic finalized"); - // } - - /** - * Return stringified description of this projection. - * - * @return String - * @see Projection#getProjectionID - */ - public String toString() { - return "Orthographic[" + super.toString(); - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - *

- */ - protected void computeParameters() { - Debug.message("proj", "Orthographic.computeParameters()"); - super.computeParameters(); - - // do some precomputation of stuff - cosCtrLat = Math.cos(centerY); - sinCtrLat = Math.sin(centerY); - - // compute the offsets - hy = height / 2; - wx = width / 2; - } - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - *

- * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_BOUNDARY) { - return NORTH_BOUNDARY; - } else if (lat < SOUTH_BOUNDARY) { - return SOUTH_BOUNDARY; - } - return lat; - } - - /** - * Check if a given lat/lon is within the visible hemisphere. - * - * @param phi1 latitude - * @param lambda0 longitude - * @param phi latitude - * @param lambda longitude - * @return boolean true if within the visible hemisphere, false if not - */ - final public static boolean hemisphere_clip(float phi1, float lambda0, - float phi, float lambda) { - return (GreatCircle.sphericalDistance(phi1, lambda0, phi, lambda)/*-epsilon*/<= MoreMath.HALF_PI); - } - - final public static boolean hemisphere_clip(double phi1, double lambda0, - double phi, double lambda) { - return (GreatCircle.sphericalDistance(phi1, lambda0, phi, lambda)/*-epsilon*/<= MoreMath.HALF_PI_D); - } - - /** - * Calculate point along edge of hemisphere (using center point and current - * azimuth). - *

- * This is invoked for points that aren't visible in the current hemisphere. - * - * @param p Point2D - * @return Point2D p - */ - private Point2D edge_point(Point2D p, double current_azimuth) { - LatLonPoint tmpll = GreatCircle.sphericalBetween(centerY, - centerX, - MoreMath.HALF_PI_D/*-epsilon*/, - current_azimuth); - - double phi = tmpll.getRadLat(); - double lambda = tmpll.getRadLon(); - double cosPhi = Math.cos(phi); - double lambdaMinusCtrLon = lambda - centerX; - - double x = (scaled_radius * cosPhi * Math.sin(lambdaMinusCtrLon)) + wx; - double y = hy - - (scaled_radius * (cosCtrLat * Math.sin(phi) - sinCtrLat - * cosPhi * Math.cos(lambdaMinusCtrLon))); - p.setLocation(x, y); - return p; - } - - /** - * Checks if a LatLonPoint is plot-able. - *

- * A point is plot-able if it is within the visible hemisphere. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return boolean - */ - public boolean isPlotable(double lat, double lon) { - lat = normalizeLatitude(ProjMath.degToRad(lat)); - lon = wrapLongitude(ProjMath.degToRad(lon)); - return hemisphere_clip(centerY, centerX, lat, lon); - } - - /** - * Forward project a point. If the point is not within the viewable - * hemisphere, return flags in AzimuthVar variable if specified. - * - * @param phi double latitude in radians - * @param lambda double longitude in radians - * @param p Point2D - * @param azVar AzimuthVar or null - * @return Point2D pt - */ - protected Point2D _forward(double phi, double lambda, Point2D p, - AzimuthVar azVar) { - double cosPhi = Math.cos(phi); - double lambdaMinusCtrLon = lambda - centerX; - - // normalize invalid point to the edge of the sphere - if (!hemisphere_clip(centerY, centerX, phi, lambda)) { - double az = GreatCircle.sphericalAzimuth(centerY, - centerX, - phi, - lambda); - if (azVar != null) { - // set the invalid flag - azVar.invalid_forward = true; - // record azimuth of this point - azVar.current_azimuth = az; - } - return edge_point(p, az); - } - - double x = (scaled_radius * cosPhi * Math.sin(lambdaMinusCtrLon)) + wx; - double y = hy - - (scaled_radius * (cosCtrLat * Math.sin(phi) - sinCtrLat - * cosPhi * Math.cos(lambdaMinusCtrLon))); - p.setLocation(x, y); - return p; - } - - /** - * Inverse project x,y coordinates into a LatLonPoint. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llp LatLonPoint - * @return LatLonPoint llp - * @see Proj#inverse(Point2D) - */ - public T inverse(double x, double y, T llp) { - - if (llp == null) { - llp = (T) new LatLonPoint.Double(); - } - - // convert from screen to world coordinates - x -= wx; - y = hy - y; - - // Debug.output("Orthographic.inverse: x,y=" + x + "," + y); - - // sqrt(pt . pt) - double rho = Math.sqrt(x * x + y * y); - if (rho == 0) { - Debug.message("proj", "Orthographic.inverse: center!"); - llp.setLocation(Math.toDegrees(centerX), Math.toDegrees(centerY)); - return llp; - } - - // float c = (float)Math.asin(rho/scaled_radius); - // float cosC = (float)Math.cos(c); - // float sinC = (float)Math.sin(c); - double sinC = rho / scaled_radius; - double cosC = Math.sqrt(1 - sinC * sinC); - - // calculate latitude - double lat = Math.asin(cosC * sinCtrLat - + (y * sinC * (cosCtrLat / rho))); - - // calculate longitude - double lon; - if (centerY == NORTH_POLE) { - lon = centerX + Math.atan2(x, -y); - } else if (centerY == SOUTH_POLE) { - lon = centerX + Math.atan2(x, y); - } else { - lon = centerX - + Math.atan2((x * sinC), (rho * cosCtrLat * cosC - y - * sinCtrLat * sinC)); - } - // Debug.output("Orthographic.inverse: lat,lon=" + - // ProjMath.radToDeg(lat) + "," + - // ProjMath.radToDeg(lon)); - - // check if point in outer space - // if (MoreMath.approximately_equal(lat, ctrLat) && - // MoreMath.approximately_equal(lon, ctrLon) && - // (Math.abs(x-(width/2))<2) && - // (Math.abs(y-(height/2))<2)) - if (Double.isNaN(lat) || Double.isNaN(lon)) { - // Debug.message("proj", "Orthographic.inverse(): outer - // space!"); - lat = centerY; - lon = centerX; - } - - llp.setLocation(Math.toDegrees(wrapLongitude(lon)), Math.toDegrees(normalizeLatitude(lat))); - return llp; - } - - /** - * Get the upper left (northernmost and westernmost) point of the - * projection. - *

- * Returns the upper left point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - * - * @return LatLonPoint - */ - public LatLonPoint getUpperLeft() { - LatLonPoint tmp = new LatLonPoint.Double(); - double lat, lon; - - // over north pole - if (overNorthPole()) { - lat = NORTH_POLE; - lon = -DATELINE; - } - - // over south pole - else if (overSouthPole()) { - lon = -DATELINE; - - // get the left top corner - inverse(0, 0, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - lat = centerY + MoreMath.HALF_PI_D; - } else { - // northernmost coord is left top - lat = tmp.getY(); - } - } - - // view in northern hemisphere - else if (centerY >= 0f) { - // get the left top corner - inverse(0, 0, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - inverse(width / 2, 0, tmp); - lat = tmp.getRadLat(); - lon = -DATELINE; - } else { - // westernmost coord is left top - lon = tmp.getRadLon(); - // northernmost coord is center top - inverse(width / 2, 0, tmp); - lat = tmp.getRadLat(); - } - } - - // view in southern hemisphere - else { - // get the left top corner - inverse(0, 0, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - lat = centerY + MoreMath.HALF_PI_D; - lon = -DATELINE; - } else { - // northernmost coord is left top - lat = tmp.getRadLat(); - // westernmost coord is left bottom - inverse(0, height - 1, tmp); - lon = tmp.getRadLon(); - } - } - tmp.setLatLon(lat, lon, true); - // Debug.output("ul="+tmp); - return tmp; - } - - /** - * Get the lower right (southeast) point of the projection. - *

- * Returns the lower right point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * This is trivial for most cylindrical projections, but much more - * complicated for azimuthal projections. - * - * @return LatLonPoint - */ - public LatLonPoint getLowerRight() { - LatLonPoint tmp = new LatLonPoint.Double(); - double lat, lon; - - // over north pole - if (overNorthPole()) { - lon = DATELINE; - - // get the right bottom corner - inverse(width - 1, height - 1, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - lat = centerY - MoreMath.HALF_PI_D; - } else { - // southernmost coord is right bottom - lat = tmp.getRadLat(); - } - } - - // over south pole - else if (overSouthPole()) { - lat = SOUTH_POLE; - lon = DATELINE; - } - - // view in northern hemisphere - else if (centerY >= 0f) { - // get the right bottom corner - inverse(width - 1, height - 1, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - lat = centerY - MoreMath.HALF_PI_D; - lon = DATELINE; - } else { - // southernmost coord is right bottom - lat = tmp.getRadLat(); - // easternmost coord is right top - inverse(width - 1, 0, tmp); - lon = tmp.getRadLon(); - } - } - - // view in southern hemisphere - else { - // get the right bottom corner - inverse(width - 1, height - 1, tmp); - - // check for invalid - if (MoreMath.approximately_equal(tmp.getRadLon(), centerX, 0.0001f)) { - inverse(width / 2, height - 1, tmp); - lat = tmp.getRadLat(); - lon = DATELINE; - } else { - // easternmost coord is right bottom - lon = tmp.getRadLon(); - // southernmost coord is center bottom - inverse(width / 2, height - 1, tmp); - lat = tmp.getRadLat(); - } - } - tmp.setLatLon(lat, lon, true); - // Debug.output("lr="+tmp); - return tmp; - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return OrthographicName; - } - - /* - * public void testPoint(float lat, float lon) { float x, y; lon = - * wrap_longitude(ProjMath.degToRad(lon)); lat = - * normalize_latitude(ProjMath.degToRad(lat)); x = forward_x(lat, lon); y = - * forward_y(lat, lon); - * - * Debug.output("(lon="+ProjMath.radToDeg(lon)+",lat="+ - * ProjMath.radToDeg(lat)+ ") = (x="+x+",y="+y+")"); lat = inverse_lat(x, - * y); lon = wrap_longitude(inverse_lon(x, y)); - * Debug.output("(x="+x+",y="+y+") = (lon="+ ProjMath.radToDeg(lon)+",lat="+ - * ProjMath.radToDeg(lat)+")"); } - * - * public static void main (String argv[]) { Orthographic proj=null; proj = - * new Orthographic(new LatLonPoint(40.0f, 0.0f), 1.0f, 620, 480); - * - * Debug.output("testing"); proj.setEarthRadius(1.0f); - * Debug.output("setEarthRadius("+proj.getEarthRadius()+")"); - * proj.setPPM(1); Debug.output("setPPM("+proj.getPPM()+")"); - * proj.setMinScale(1.0f); - * Debug.output("setMinScale("+proj.getMinScale()+")"); try { - * proj.setScale(1.0f); } catch (java.beans.PropertyVetoException e) { } - * Debug.output("setScale("+proj.getScale()+")"); Debug.output(proj); - * Debug.output(); - * - * Debug.output("---testing latitude"); proj.testPoint(0.0f, 0.0f); - * proj.testPoint(10.0f, 0.0f); proj.testPoint(40.0f, 0.0f); - * proj.testPoint(-80.0f, 0.0f); proj.testPoint(-90.0f, 0.0f); - * proj.testPoint(100.0f, 0.0f); proj.testPoint(-3272.0f, 0.0f); - * Debug.output("---testing longitude"); proj.testPoint(0.0f, 10.0f); - * proj.testPoint(0.0f, -10.0f); proj.testPoint(0.0f, 90.0f); - * proj.testPoint(0.0f, -90.0f); proj.testPoint(0.0f, 170.0f); - * proj.testPoint(0.0f, -170.0f); proj.testPoint(0.0f, 180.0f); - * proj.testPoint(0.0f, -180.0f); proj.testPoint(0.0f, 190.0f); - * proj.testPoint(0.0f, -190.0f); Debug.output("---testing lat&lon"); - * proj.testPoint(100.0f, 370.0f); proj.testPoint(-30.0f, -370.0f); - * proj.testPoint(-80.0f, 550.0f); proj.testPoint(0.0f, -550.0f); } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/OrthographicLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/OrthographicLoader.java deleted file mode 100644 index c676ddb62..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/OrthographicLoader.java +++ /dev/null @@ -1,78 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/OrthographicLoader.java,v $ -// $RCSfile: OrthographicLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * ProjectionLoader to add the Orthographic projection to an OpenMap - * application. - * - * @see BasicProjectionLoader - */ -public class OrthographicLoader extends BasicProjectionLoader implements - ProjectionLoader { - - public OrthographicLoader() { - super(Orthographic.class, - Orthographic.OrthographicName, - "Orthographic projection."); - } - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException { - - try { - LatLonPoint llp = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - return new Orthographic(llp, scale, width, height); - - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("OrthographicLoader: problem creating Orthographic projection " - + e.getMessage()); - } - } - - throw new ProjectionException("OrthographicLoader: problem creating Orthographic projection"); - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Planet.java b/src/core/src/main/java/com/bbn/openmap/proj/Planet.java deleted file mode 100644 index cf5be3a06..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Planet.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Planet.java,v $ -// $RCSfile: Planet.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import com.bbn.openmap.util.MoreMath; - -/** - * Planet datums and parameters. These values are taken from John - * Snyder's Map Projections --A Working Manual You should add - * datums as needed, consult the ellips.dat file. - */ -public class Planet { - - // Solar system id's. Add new ones as needed. - final public static transient int Earth = 3; - final public static transient int Mars = 4; - - // WGS84 / GRS80 datums - final public static transient float wgs84_earthPolarRadiusMeters = 6356752.3142f; - final public static transient double wgs84_earthPolarRadiusMeters_D = 6356752.3142; - final public static transient float wgs84_earthEquatorialRadiusMeters = 6378137.0f; - final public static transient double wgs84_earthEquatorialRadiusMeters_D = 6378137.0; - /* 1 - (minor/major) = 1/298.257 */ - final public static transient float wgs84_earthFlat = 1 - (wgs84_earthPolarRadiusMeters / wgs84_earthEquatorialRadiusMeters); - /* sqrt(2*f - f^2) = 0.081819221f */ - final public static transient float wgs84_earthEccen = (float) Math.sqrt(2 - * wgs84_earthFlat - (wgs84_earthFlat * wgs84_earthFlat)); - final public static transient float wgs84_earthEquatorialCircumferenceMeters = MoreMath.TWO_PI - * wgs84_earthEquatorialRadiusMeters; - final public static transient float wgs84_earthEquatorialCircumferenceKM = wgs84_earthEquatorialCircumferenceMeters / 1000f; - final public static transient float wgs84_earthEquatorialCircumferenceMiles = wgs84_earthEquatorialCircumferenceKM * 0.62137119f;// HACK - /* 60.0f * 360.0f -- sixty nm per degree units? */ - final public static transient float wgs84_earthEquatorialCircumferenceNMiles = wgs84_earthEquatorialCircumferenceMeters / 1852f; - final public static transient double wgs84_earthEquatorialCircumferenceMeters_D = MoreMath.TWO_PI_D - * wgs84_earthEquatorialRadiusMeters_D; - final public static transient double wgs84_earthEquatorialCircumferenceKM_D = wgs84_earthEquatorialCircumferenceMeters_D / 1000; - final public static transient double wgs84_earthEquatorialCircumferenceMiles_D = wgs84_earthEquatorialCircumferenceKM_D * 0.62137119;// HACK - /* 60.0f * 360.0f; sixty nm per degree */// units? - final public static transient double wgs84_earthEquatorialCircumferenceNMiles_D = wgs84_earthEquatorialCircumferenceMeters_D / 1852; - // wgs84_earthEquatorialCircumferenceKM*0.5389892f; // calculated, - // same as line above. - // wgs84_earthEquatorialCircumferenceKM*0.5399568f;//HACK use UNIX - // units? << This was wrong. - - // Mars - final public static transient float marsEquatorialRadius = 3393400.0f;// meters - final public static transient float marsEccen = 0.101929f;// eccentricity - // e - final public static transient float marsFlat = 0.005208324f;// 1-(1-e^2)^1/2 - - // International 1974 - final public static transient float international1974_earthPolarRadiusMeters = 6356911.946f; - final public static transient float international1974_earthEquatorialRadiusMeters = 6378388f; - /* 1 - (minor/major) = 1/297 */ - final public static transient float international1974_earthFlat = 1 - (international1974_earthPolarRadiusMeters / international1974_earthEquatorialRadiusMeters); - /* - * Extra scale constant for better viewing of maps (do not use - * this to calculate anything but points to be viewed!) 3384: mattserver/Map.C, 3488: dcw - */ - public transient static int defaultPixelsPerMeter = 3272; - - // cannot construct - private Planet() {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Proj.java b/src/core/src/main/java/com/bbn/openmap/proj/Proj.java deleted file mode 100644 index 26319380d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Proj.java +++ /dev/null @@ -1,1020 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Proj.java,v $ -// $RCSfile: Proj.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.util.Debug; - -/** - * Proj is the base class of all Projections. - *

- * You probably don't want to use this class unless you are hacking your own - * projections, or need extended functionality. To be safe you will want to use - * the Projection interface. - * - *

Notes:

- * - *
    - * - *
  • There are no assumption made as to the units of the values provided to - * the projection, each projection type has its own interpretation of what the - * values are. - * - *
  • The order of coordinate parameters changes, depending on the convention - * of the superclass object of the one being referred to. Coordinate tuples - * referring to projected coordinates are generally x, y, those referring to - * unprojected coordinates are y, x (lat/lon). - * - *
  • This class is not thread safe. If two or more threads are using the same - * Proj, then they could disrupt each other. Occasionally you may need to call a - * set method of this class. This might interfere with another - * thread that's using the same projection for forwardPoly or - * another Projection interface method. In general, you should not need to call - * any of the set methods directly, but let the MapBean do it for - * you. - * - *
  • All the various forwardOBJ() methods for ArrayList graphics - * ultimately go through forwardPoly(). - * - *
- * - * @see Cartesian - * @see GeoProj - * - */ -public abstract class Proj implements Projection, Cloneable, Serializable { - - private static final long serialVersionUID = 1L; - - /** - * Minimum width of projection. - */ - public final static transient int MIN_WIDTH = 10; // pixels - - /** - * Minimum height of projection. - */ - public final static transient int MIN_HEIGHT = 10; // pixels - - protected int width = 640, height = 480; - protected double minscale = 1.0; // 1:minscale - protected double maxscale = Double.MAX_VALUE; - protected double scale = maxscale; - protected double centerX; - protected double centerY; - protected String projID = null; // identifies this projection (if needed) - /** - * The rotation angle of the map is stored here so that non-rotating things - * can correct themselves. Is not used for equality checks. - */ - protected double rotationAngle = 0; - - /** - * The unprojected coordinates units of measure. - */ - protected Length ucuom = null; - - /** - * Construct a projection. - * - * @param center LatLonPoint center of projection - * @param s float scale of projection - * @param w width of screen - * @param h height of screen - * @see ProjectionFactory - */ - public Proj(Point2D center, float s, int w, int h) { - if (Debug.debugging("proj")) { - Debug.output("Proj()"); - } - - setParms(center, s, w, h); - projID = null; - - } - - /** - * Set the scale of the projection. - *

- * Sets the projection to the scale 1:s iff minscale < s < maxscale. - *
- * If s < minscale, sets the projection to minscale.
- * If s > maxscale, sets the projection to maxscale.
- * - * @param s float scale - */ - public void setScale(float s) { - scale = s; - if (scale < minscale) { - scale = minscale; - } else if (scale > maxscale) { - scale = maxscale; - } - computeParameters(); - projID = null; - } - - /** - * Set the minscale of the projection. - *

- * Usually you will not need to do this. - * - * @param s float minscale - */ - public void setMinScale(float s) { - if (s > maxscale) - return; - - minscale = s; - if (scale < minscale) { - scale = minscale; - } - computeParameters(); - projID = null; - } - - /** - * Set the maximum scale of the projection. - *

- * Usually you will not need to do this. - * - * @param s float minscale - */ - public void setMaxScale(float s) { - if (s < minscale) - return; - - maxscale = s; - if (scale > maxscale) { - scale = maxscale; - } - computeParameters(); - projID = null; - } - - /** - * Get the scale of the projection. - * - * @return double scale value - */ - public float getScale() { - return (float) scale; - } - - /** - * Get the maximum scale of the projection. - * - * @return double max scale value - */ - public float getMaxScale() { - return (float) maxscale; - } - - /** - * Get minimum scale of the projection. - * - * @return double min scale value - */ - public float getMinScale() { - return (float) minscale; - } - - /** - * Set center point of projection. - * - * @param pt Point2D for center. Point2D values will be copied. - */ - public void setCenter(Point2D pt) { - setCenter(pt.getY(), pt.getX()); - } - - /** - * Set center point of projection. - * - * @param y vertical value of center. - * @param x horizontal value of center. - */ - public void setCenter(double y, double x) { - // Since we need to re-run computeParameters and the projID, - // we better make a clone of the center, so whoever sets the - // center can't change it by simply changing the center's - // parameters without recalculating the parameters. - centerX = x; - centerY = y; - computeParameters(); - projID = null; - } - - /** - * Get center point of projection. - * - * @return Point2D center of projection, created just for you. - */ - @SuppressWarnings("unchecked") - public Point2D getCenter() { - return getCenter(new Point2D.Double()); - } - - /** - * Returns a center Point2D that was provided, with the location filled into - * the Point2D object. Calls Point2D.setLocation(x, y). - */ - public T getCenter(T center) { - center.setLocation(centerX, centerY); - return center; - } - - /** - * Set projection width. - * - * @param width width of projection screen - */ - public void setWidth(int width) { - this.width = width; - - if (this.width < MIN_WIDTH) { - Debug.message("proj", "Proj.setWidth: width too small!"); - this.width = MIN_WIDTH; - } - computeParameters(); - projID = null; - } - - /** - * Set projection height. - * - * @param height height of projection screen - */ - public void setHeight(int height) { - this.height = height; - if (this.height < MIN_HEIGHT) { - Debug.message("proj", "Proj.setHeight: height too small!"); - this.height = MIN_HEIGHT; - } - computeParameters(); - projID = null; - } - - /** - * Get projection width. - * - * @return width of projection screen - */ - public int getWidth() { - return width; - } - - /** - * Get projection height. - * - * @return height of projection screen - */ - public int getHeight() { - return height; - } - - /** - * Sets all the projection variables at once before calling - * computeParameters(). - * - * @param center LatLonPoint center - * @param scale float scale - * @param width width of screen - * @param height height of screen - */ - protected void setParms(Point2D center, float scale, int width, int height) { - centerX = center.getX(); - centerY = center.getY(); - this.scale = scale; - - this.width = width; - if (this.width < MIN_WIDTH) { - Debug.message("proj", "Proj.setParms: width too small!"); - this.width = MIN_WIDTH; - } - this.height = height; - if (this.height < MIN_HEIGHT) { - Debug.message("proj", "Proj.setParms: height too small!"); - this.height = MIN_HEIGHT; - } - - init(); - - if (this.scale < minscale) { - this.scale = minscale; - } else if (this.scale > maxscale) { - this.scale = maxscale; - } - - computeParameters(); - projID = null; - } - - /** - * Called after the center and scale is set in setParams, but before the - * scale is checked for legitimacy. This is an opportunity to set constants - * in subclasses before anything else gets called or checked for validity. - * This is different than computeParameters() which is called after some - * checks. This is a good time to pre-calculate constants and set maxscale - * and minscale. - *

- * Make sure you call super.init() if you override this method. - */ - protected void init() { - } - - /** - * Sets the projection ID used for determining equality. The projection ID - * String is interned for efficient comparison. - */ - protected void setProjectionID() { - projID = (getClass().getName() + ":" + scale + ":" + centerX + ":" + centerY + ":" + width + ":" + height + ":" - + rotationAngle); - } - - /** - * Gets the projection ID used for determining equality. - * - * @return the projection ID, as an intern()ed String - */ - public String getProjectionID() { - if (projID == null) - setProjectionID(); - return projID; - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - */ - protected abstract void computeParameters(); - - /** - * Stringify the projection. - * - * @return stringified projection - * @see #getProjectionID - */ - public String toString() { - return (" center(" + centerX + ":" + centerY + ") scale=" + scale + " maxscale=" + maxscale + " minscale=" - + minscale + " width=" + width + " height=" + height + "]"); - } - - /** - * Test for equality. - * - * @param o Object to compare. - * @return boolean comparison - */ - public boolean equals(Object o) { - if (o == null) - return false; - if (getClass() != o.getClass()) { - return false; - } - return getProjectionID().equals(((Projection) o).getProjectionID()); - } - - /** - * Return hashcode value of projection. - * - * @return int hashcode - */ - public int hashCode() { - return getProjectionID().hashCode(); - } - - /** - * Clone the projection. - * - * @return Projection clone of this one. - */ - public Projection makeClone() { - return (Projection) this.clone(); - } - - /** - * Copies this projection. - * - * @return a copy of this projection. - */ - public Object clone() { - try { - return (Proj) super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - /** - * Forward project a LatLonPoint. - *

- * Forward projects a LatLon point into XY space. Returns a Point2D. - * - * @param llp LatLonPoint to be projected - * @return Point2D (new) - */ - public Point2D forward(Point2D llp) { - return forward(llp.getY(), llp.getX(), new Point2D.Float()); - } - - /** - * Forward projects a LatLonPoint into XY space and return a - * java.awt.geom.Point2D. - * - * @param llp LatLonPoint to be projected - * @param pt Resulting XY Point2D - * @return Point2D pt - */ - public Point2D forward(Point2D llp, Point2D pt) { - return forward(llp.getY(), llp.getX(), pt); - } - - /** - * Forward project lat,lon coordinates. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return Point2D (new) - */ - public Point2D forward(float lat, float lon) { - return forward((double) lat, (double) lon, new Point2D.Float()); - } - - public Point2D forward(float lat, float lon, Point2D pt) { - return forward((double) lat, (double) lon, pt); - } - - public Point2D forward(double lat, double lon) { - return forward(lat, lon, new Point2D.Double()); - } - - public abstract Point2D forward(double lat, double lon, Point2D pt); - - public T inverse(Point2D point, T llpt) { - return inverse(point.getX(), point.getY(), llpt); - } - - /** - * Inverse project a Point2D from x,y space to coordinate space. - * - * @param point x,y Point2D - * @return LatLonPoint (new) - */ - @SuppressWarnings("unchecked") - public Point2D inverse(Point2D point) { - return inverse(point.getX(), point.getY(), new Point2D.Double()); - } - - /** - * Inverse project x,y coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @return LatLonPoint (new) - * @see #inverse(Point2D) - */ - @SuppressWarnings("unchecked") - public Point2D inverse(double x, double y) { - return inverse(x, y, new Point2D.Double()); - } - - public abstract T inverse(double x, double y, T llpt); - - /** - * Simple shape inverse projection, converts the x,y values in the shape to - * the x, y values of the projection. - * - * @param shape projected shape. - * @return Shape containing source coordinates inversely projected. - */ - public Shape inverseShape(Shape shape) { - PathIterator pi = shape.getPathIterator(null); - double[] coords = new double[6]; - Point2D world = new Point2D.Double(); - Point2D world2 = new Point2D.Double(); - Point2D world3 = new Point2D.Double(); - Point2D screen = new Point2D.Double(); - Point2D screen2 = new Point2D.Double(); - Point2D screen3 = new Point2D.Double(); - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - screen.setLocation(coords[0], coords[1]); - inverse(screen, world); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(world.getX(), world.getY()); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(world.getX(), world.getY()); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - screen2.setLocation(coords[2], coords[3]); - inverse(screen2, world2); - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(world.getX(), world.getY(), world2.getX(), world2.getY()); - } else if (type == PathIterator.SEG_CUBICTO) { - screen3.setLocation(coords[4], coords[5]); - inverse(screen3, world3); - path.curveTo(world.getX(), world.getY(), world2.getX(), world2.getY(), world3.getX(), - world3.getY()); - } - } - - pi.next(); - } - - return path; - } - - /** - * Simple shape projection, doesn't take into account what kind of lines - * should be drawn between shape points, assumes they should be 2D lines as - * rendered in 2D space, not interpolated for accuracy as Great Circle/Rhumb - * lines on a globe.. - */ - public Shape forwardShape(Shape shape) { - PathIterator pi = shape.getPathIterator(null); - double[] coords = new double[6]; - Point2D world = new Point2D.Double(); - Point2D world2 = new Point2D.Double(); - Point2D world3 = new Point2D.Double(); - Point screen = new Point(); - Point screen2 = new Point(); - Point screen3 = new Point(); - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - world.setLocation(coords[0], coords[1]); - forward(world, screen); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(screen.x, screen.y); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(screen.x, screen.y); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - world2.setLocation(coords[2], coords[3]); - forward(world2, screen2); - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(screen.x, screen.y, screen2.x, screen2.y); - } else if (type == PathIterator.SEG_CUBICTO) { - world3.setLocation(coords[4], coords[5]); - forward(world3, screen3); - path.curveTo(screen.x, screen.y, screen2.x, screen2.y, screen3.x, screen3.y); - } - } - - pi.next(); - } - - return path; - } - - /** - * Forward project a raw array of points. This assumes nothing about the - * array of coordinates. In no way does it assume the points are connected - * or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of y, x world coordinates. - * @param rawoff offset into rawllpts. - * @param xcoords x projected horizontal map coordinates. - * @param ycoords y projected vertical map coordinates. - * @param visible coordinates visible? - * @param copyoff offset into x,y visible arrays. - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, - int copyoff, int copylen) { - Point temp = new Point(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - visible[i] = true; - } - return true; - } - - /** - * Forward project a raw array of points. This assumes nothing about the - * array of coordinates. In no way does it assume the points are connected - * or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of y, x world coordinates. - * @param rawoff offset into rawllpts. - * @param xcoords x projected horizontal map coordinates. - * @param ycoords y projected vertical map coordinates. - * @param visible coordinates visible? - * @param copyoff offset into x,y visible arrays. - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, boolean[] visible, - int copyoff, int copylen) { - Point temp = new Point(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - visible[i] = true; - } - return true; - } - - public ArrayList forwardLine(Point2D ll1, Point2D ll2) { - double[] rawllpts = { ll1.getY(), ll1.getX(), ll2.getY(), ll2.getX() }; - return forwardPoly(rawllpts, false); - } - - /** - * Forward project a rectangle. - * - * @param ll1 LatLonPoint - * @param ll2 LatLonPoint - * @return ArrayList float[] - */ - public ArrayList forwardRect(Point2D ll1, Point2D ll2) { - double[] rawllpts = { ll1.getY(), ll1.getX(), ll1.getY(), ll2.getX(), ll2.getY(), ll2.getX(), ll2.getY(), - ll1.getX(), - // connect: - ll1.getY(), ll1.getX() }; - return forwardPoly(rawllpts, true); - } - - public ArrayList forwardPoly(float[] rawllpts, boolean isFilled) { - // For regular OMGraphics, some of the rawllpts are in radians and must - // be translated into decimal degrees before they really are able to be - // displayed here, i.e.: - // wx = Math.toDegrees(wx); - // wy = Math.toDegrees(wy); - - int n, k; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp); - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp); - xs[n] = temp.x; - ys[n] = temp.y; - } - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - - return ret_val; - } - - public ArrayList forwardPoly(double[] rawllpts, boolean isFilled) { - int n, k; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp); - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp); - xs[n] = temp.x; - ys[n] = temp.y; - } - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - return ret_val; - } - - /** - * Pan the map/projection. - *

- * Example pans: - *

    - *
  • pan(180, c) pan south `c' degrees - *
  • pan(-90, c) pan west `c' degrees - *
  • pan(0, c) pan north `c' degrees - *
  • pan(90, c) pan east `c' degrees - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees - */ - abstract public void pan(double Az, double c); - - /** - * Pan the map/projection. - *
    - *
  • pan(180, c) pan south - *
  • pan(-90, c) pan west - *
  • pan(0, c) pan north - *
  • pan(90, c) pan east - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - abstract public void pan(double Az); - - /** - * pan the map northwest. - */ - final public void panNW() { - pan(-45f); - } - - final public void panNW(double c) { - pan(-45f); - } - - /** - * pan the map north. - */ - final public void panN() { - pan(0f); - } - - final public void panN(double c) { - pan(0f); - } - - /** - * pan the map northeast. - */ - final public void panNE() { - pan(45f); - } - - final public void panNE(double c) { - pan(45f); - } - - /** - * pan the map east. - */ - final public void panE() { - pan(90f); - } - - final public void panE(double c) { - pan(90f); - } - - /** - * pan the map southeast. - */ - final public void panSE() { - pan(135f); - } - - final public void panSE(double c) { - pan(135f); - } - - /** - * pan the map south. - */ - final public void panS() { - pan(180f); - } - - final public void panS(double c) { - pan(180f); - } - - /** - * pan the map southwest. - */ - final public void panSW() { - pan(-135f); - } - - final public void panSW(double c) { - pan(-135f); - } - - /** - * pan the map west. - */ - final public void panW() { - pan(-90f); - } - - final public void panW(double c) { - pan(-90f); - } - - /** - * @param lat latitude y point - * @param lon latitude x point - * @return true if the lat/lon can be displayed in the current projection window. - */ - public abstract boolean isPlotable(double lat, double lon); - - public boolean isPlotable(Point2D point) { - return isPlotable(point.getY(), point.getX()); - } - - /** - * Draw the background for the projection. - * - * @param g Graphics2D - * @param paint java.awt.Paint to use for the background - */ - public void drawBackground(Graphics2D g, java.awt.Paint paint) { - g.setPaint(paint); - drawBackground(g); - } - - /** - * Draw the background for the projection. Assume that the Graphics has been - * set with the Paint/Color needed, just render the shape of the background. - * - * @param g Graphics - */ - public void drawBackground(Graphics g) { - g.fillRect(0, 0, getWidth(), getHeight()); - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return "Proj"; - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll1 coordinate, the upper left - * corner of the area of interest. Note that this is the location - * where you want ll1 to go in the new projection scale, not - * where it is now. - * @param point2 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll2 coordinate, usually the lower - * right corner of the area of interest. Note that this is the - * location where you want ll2 to go in the new projection, not - * where it is now. - */ - public abstract float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2); - - /** - * Overridden to ensure that setParameters() are called with the read - * values. - * - * @param in - * @throws IOException - * @throws ClassNotFoundException - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - computeParameters(); - projID = null; - } - - /** - * Get the unprojected coordinates units of measure. - * - * @return Length. May be null if unknown. - * @see Length - */ - public Length getUcuom() { - return ucuom; - } - - /** - * Set the unprojected coordinates units of measure. - * - * @param ucuom - */ - public void setUcuom(Length ucuom) { - this.ucuom = ucuom; - } - - /** - * Get the world coordinate of the upper left corner of the map. - */ - @SuppressWarnings("unchecked") - public Point2D getUpperLeft() { - return inverse(0, 0, new Point2D.Double()); - } - - /** - * Get the world coordinate of the lower right corner of the map. - */ - @SuppressWarnings("unchecked") - public Point2D getLowerRight() { - return inverse(width, height, new Point2D.Double()); - } - - /** - * @return the rotationAngle - */ - public double getRotationAngle() { - return rotationAngle; - } - - /** - * This setting is purely for informational purposes, as a way for the - * projection to pass along any rotation activity of the MapBean to - * OMGraphics. Setting this value will not rotate the map. Rotating the map - * should be done directly to the MapBean. - * - * @param rotationAngle the rotationAngle to set, in RADIANS - */ - public void setRotationAngle(double rotationAngle) { - this.rotationAngle = rotationAngle; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjMath.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjMath.java deleted file mode 100644 index 376ee8d4e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjMath.java +++ /dev/null @@ -1,795 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjMath.java,v $ -// $RCSfile: ProjMath.java,v $ -// $Revision: 1.9 $ -// $Date: 2007/06/21 21:39:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.util.MoreMath; - -/** - * Math functions used by projection code. - */ -public final class ProjMath { - - /** - * North pole latitude in radians. - */ - public final static transient float NORTH_POLE_F = MoreMath.HALF_PI; - - /** - * South pole latitude in radians. - */ - public final static transient float SOUTH_POLE_F = -NORTH_POLE_F; - - /** - * North pole latitude in radians. - */ - public final static transient double NORTH_POLE_D = MoreMath.HALF_PI_D; - - /** - * North pole latitude in degrees. - */ - public final static transient double NORTH_POLE_DEG_D = 90d; - - /** - * South pole latitude in radians. - */ - public final static transient double SOUTH_POLE_D = -NORTH_POLE_D; - - /** - * South pole latitude in degrees. - */ - public final static transient double SOUTH_POLE_DEG_D = -NORTH_POLE_DEG_D; - - /** - * Dateline longitude in radians. - */ - public final static transient float DATELINE_F = (float) Math.PI; - - /** - * Dateline longitude in radians. - */ - public final static transient double DATELINE_D = Math.PI; - - /** - * Dateline longitude in degrees. - */ - public final static transient double DATELINE_DEG_D = 180d; - - /** - * Longitude range in radians. - */ - public final static transient float LON_RANGE_F = (float) MoreMath.TWO_PI; - - /** - * Longitude range in radians. - */ - public final static transient double LON_RANGE_D = MoreMath.TWO_PI_D; - - /** - * Longitude range in degrees. - */ - public final static transient double LON_RANGE_DEG_D = 360d; - - // cannot construct - private ProjMath() { - } - - /** - * rounds the quantity away from 0. - * - * @param x in value - * @return double - * @see #qint(double) - */ - public final static double roundAdjust(double x) { - return qint_old(x); - } - - /** - * Rounds the quantity away from 0. - * - * @param x value - * @return double - */ - public final static double qint(double x) { - return qint_new(x); - } - - final private static double qint_old(double x) { - return (((int) x) < 0) ? (x - 0.5) : (x + 0.5); - } - - final private static double qint_new(double x) { - // -1 or +1 away from zero - return (x <= 0.0) ? (x - 1.0) : (x + 1.0); - } - - /** - * Calculate the shortest arc distance between two lons. - * - * @param lon1 radians - * @param lon2 radians - * @return float distance - */ - public final static float lonDistance(float lon1, float lon2) { - return (float) Math.min(Math.abs(lon1 - lon2), - ((lon1 < 0) ? lon1 + Math.PI : Math.PI - lon1) + ((lon2 < 0) ? lon2 + Math.PI : Math.PI - lon2)); - } - - /** - * Convert between decimal degrees and scoords. - * - * @param deg degrees - * @return long scoords - * - */ - public final static long DEG_TO_SC(double deg) { - return (long) (deg * 3600000); - } - - /** - * Convert between decimal degrees and scoords. - * - * @param sc scoords - * @return double decimal degrees - */ - public final static double SC_TO_DEG(int sc) { - return ((double) (sc) / (60.0 * 60.0 * 1000.0)); - } - - /** - * Convert radians to degrees. - * - * @param rad radians - * @return double decimal degrees - */ - public final static double radToDeg(double rad) { - return Math.toDegrees(rad); - } - - /** - * Convert radians to degrees. - * - * @param rad radians - * @return float decimal degrees - */ - public final static float radToDeg(float rad) { - return (float) Math.toDegrees((double) rad); - } - - /** - * Convert degrees to radians. - * - * @param deg degrees - * @return double radians - */ - public final static double degToRad(double deg) { - return Math.toRadians(deg); - } - - /** - * Convert degrees to radians. - * - * @param deg degrees - * @return float radians - */ - public final static float degToRad(float deg) { - return (float) Math.toRadians((double) deg); - } - - /** - * Generate a hashCode value for a lat/lon pair. - * - * @param lat latitude - * @param lon longitude - * @return int hashcode - * - */ - public final static int hashLatLon(float lat, float lon) { - if (lat == -0f) - lat = 0f;// handle negative zero (anything else?) - if (lon == -0f) - lon = 0f; - int tmp = Float.floatToIntBits(lat); - int hash = (tmp << 5) | (tmp >> 27);// rotate the lat bits - return hash ^ Float.floatToIntBits(lon);// XOR with lon - } - - /** - * Converts an array of decimal degrees float lat/lons to float radians in - * place. - * - * @param degs float[] lat/lons in decimal degrees - * @return float[] lat/lons in radians - */ - public final static float[] arrayDegToRad(float[] degs) { - for (int i = 0; i < degs.length; i++) { - degs[i] = degToRad(degs[i]); - } - return degs; - } - - /** - * Converts an array of radian float lat/lons to decimal degrees in place. - * - * @param rads float[] lat/lons in radians - * @return float[] lat/lons in decimal degrees - */ - public final static float[] arrayRadToDeg(float[] rads) { - for (int i = 0; i < rads.length; i++) { - rads[i] = radToDeg(rads[i]); - } - return rads; - } - - /** - * Converts an array of decimal degrees double lat/lons to double radians in - * place. - * - * @param degs double[] lat/lons in decimal degrees - * @return double[] lat/lons in radians - */ - public final static double[] arrayDegToRad(double[] degs) { - for (int i = 0; i < degs.length; i++) { - degs[i] = degToRad(degs[i]); - } - return degs; - } - - /** - * Converts an array of radian double lat/lons to decimal degrees in place. - * - * @param rads double[] lat/lons in radians - * @return double[] lat/lons in decimal degrees - */ - public final static double[] arrayRadToDeg(double[] rads) { - for (int i = 0; i < rads.length; i++) { - rads[i] = radToDeg(rads[i]); - } - return rads; - } - - /** - * @deprecated use normalizeLatitude instead. - */ - public final static float normalize_latitude(float lat, float epsilon) { - return normalizeLatitude(lat, epsilon); - } - - /** - * Normalizes radian latitude. Normalizes latitude if at or exceeds epsilon - * distance from a pole. - * - * @param lat float latitude in radians - * @param epsilon epsilon (>= 0) radians distance from pole - * @return float latitude (-PI/2 <= phi <= PI/2) - * @see com.bbn.openmap.proj.coords.LatLonPoint#normalizeLatitude(double) - */ - public final static float normalizeLatitude(float lat, float epsilon) { - if (lat > NORTH_POLE_F - epsilon) { - return NORTH_POLE_F - epsilon; - } else if (lat < SOUTH_POLE_F + epsilon) { - return SOUTH_POLE_F + epsilon; - } - return lat; - } - - /** - * @deprecated use normalizeLatitude instead. - */ - public final static double normalize_latitude(double lat, double epsilon) { - return normalizeLatitude(lat, epsilon); - } - - /** - * Normalizes radian latitude. Normalizes latitude if at or exceeds epsilon - * distance from a pole. - * - * @param lat double latitude in radians - * @param epsilon epsilon (>= 0) radians distance from pole - * @return double latitude (-PI/2 <= phi <= PI/2) - * @see com.bbn.openmap.proj.coords.LatLonPoint#normalizeLatitude(double) - */ - public final static double normalizeLatitude(double lat, double epsilon) { - if (lat > NORTH_POLE_D - epsilon) { - return NORTH_POLE_D - epsilon; - } else if (lat < SOUTH_POLE_D + epsilon) { - return SOUTH_POLE_D + epsilon; - } - return lat; - } - - /** - * @deprecated use wrapLongitde instead. - */ - public final static float wrap_longitude(float lon) { - return wrapLongitude(lon); - } - - /** - * Sets radian longitude to something sane. - * - * @param lon float longitude in radians - * @return float longitude (-PI <= lambda < PI) - */ - public final static float wrapLongitude(float lon) { - if ((lon < -DATELINE_F) || (lon > DATELINE_F)) { - lon += DATELINE_F; - lon %= LON_RANGE_F; - lon += (lon < 0) ? DATELINE_F : -DATELINE_F; - } - return lon; - } - - /** - * @deprecated use wrapLongitude instead. - */ - public final static double wrap_longitude(double lon) { - return wrapLongitude(lon); - } - - /** - * Sets radian longitude to something sane. - * - * @param lon double longitude in radians - * @return double longitude (-PI <= lambda < PI) - */ - public final static double wrapLongitude(double lon) { - if ((lon < -DATELINE_D) || (lon > DATELINE_D)) { - lon += DATELINE_D; - lon %= LON_RANGE_D; - lon += (lon < 0) ? DATELINE_D : -DATELINE_D; - } - return lon; - } - - /** - * Sets degree longitude to something sane. - * - * @param lon double longitude in degrees - * @return double longitude (-180 <= lambda < 180) - */ - public final static double wrapLongitudeDeg(double lon) { - if ((lon < -DATELINE_DEG_D) || (lon > DATELINE_DEG_D)) { - lon += DATELINE_DEG_D; - lon %= LON_RANGE_DEG_D; - lon += (lon < 0) ? DATELINE_DEG_D : -DATELINE_DEG_D; - } - return lon; - } - - /** - * Converts units (km, nm, miles, etc) to decimal degrees for a spherical - * planet. This does not check for arc distances > 1/2 planet - * circumference, which are better represented as (2pi - calculated arc). - * - * @param u units float value - * @param uCircumference units circumference of planet - * @return float decimal degrees - */ - public final static float sphericalUnitsToDeg(float u, float uCircumference) { - return 360f * (u / uCircumference); - } - - /** - * Converts units (km, nm, miles, etc) to arc radians for a spherical - * planet. This does not check for arc distances > 1/2 planet - * circumference, which are better represented as (2pi - calculated arc). - * - * @param u units float value - * @param uCircumference units circumference of planet - * @return float arc radians - */ - public final static float sphericalUnitsToRad(float u, float uCircumference) { - return MoreMath.TWO_PI * (u / uCircumference); - } - - /** - * @deprecated use geocentricLatitude instead. - */ - public final static float geocentric_latitude(float lat, float lon) { - return geocentricLatitude(lat, lon); - } - - /** - * Calculate the geocentric latitude given a geographic latitude. According - * to John Synder:
- * "The geographic or geodetic latitude is the angle which a line - * perpendicular to the surface of the ellipsoid at the given point makes - * with the plane of the equator. ...The geocentric latitude is the angle - * made by a line to the center of the ellipsoid with the equatorial plane". - * ( Map Projections --A Working Manual , p 13) - *

- * Translated from Ken Anderson's lisp code Freeing the Essence of - * Computation - * - * @param lat float geographic latitude in radians - * @param flat float flatening factor - * @return float geocentric latitude in radians - * @see #geographic_latitude - */ - public final static float geocentricLatitude(float lat, float flat) { - float f = 1.0f - flat; - return (float) Math.atan((f * f) * (float) Math.tan(lat)); - } - - /** - * @deprecated use geographicLoatitude instead. - */ - public final static float geographic_latitude(float lat, float lon) { - return geographicLatitude(lat, lon); - } - - /** - * Calculate the geographic latitude given a geocentric latitude. Translated - * from Ken Anderson's lisp code Freeing the Essence of Computation - * - * @param lat float geocentric latitude in radians - * @param flat float flatening factor - * @return float geographic latitude in radians - * @see #geocentric_latitude - */ - public final static float geographicLatitude(float lat, float flat) { - float f = 1.0f - flat; - return (float) Math.atan((float) Math.tan(lat) / (f * f)); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScale(Point2D ll1, Point2D ll2, Projection projection) { - if (projection == null) { - return Float.MAX_VALUE; - } - - Point2D point1 = projection.forward(ll1); - Point2D point2 = projection.forward(ll2); - - return getScale(ll1, ll2, point1, point2, projection); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. This method is generally called from objects dealing with - * MouseEvents. - * - * @param point1 a java.awt.Point reflecting a pixel spot on the projection, - * usually the upper left corner of the area of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection, - * usually the lower right corner of the area of interest. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScale(Point point1, Point point2, Projection projection) { - - return getScaleFromProjected(point1, point2, projection); - } - - /** - * Given a couple of points representing a bounding box of projected - * coordinates, find out what the scale should be in order to make those - * points appear at the corners of the projection, with the intention that - * the bounding box will then fill the projected space. - * - * @param point1 a java.awt.Point reflecting a pixel spot on the projection, - * usually the upper left corner of the area of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection, - * usually the lower right corner of the area of interest. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScaleFromProjected(Point2D point1, Point2D point2, Projection projection) { - if (projection == null) { - return Float.MAX_VALUE; - } - - /** - * Just to make sure of the order for upper left and lower right, which - * seems to make a difference for the projection calculation. - */ - Point2D upperLeft = new Point2D.Double(Math.min(point1.getX(), point2.getX()), - Math.min(point1.getY(), point2.getY())); - Point2D lowerRight = new Point2D.Double(Math.max(point1.getX(), point2.getX()), - Math.max(point1.getY(), point2.getY())); - - Point2D ll1 = projection.inverse(upperLeft); - Point2D ll2 = projection.inverse(lowerRight); - - return getScale(ll1, ll2, upperLeft, lowerRight, projection); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll1 coordinate in the new space, the upper - * left corner of the area of interest. Where the ll1 is going to - * go in the new projection. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll2 coordinate in the new space, usually the - * lower right corner of the area of interest. Where the ll2 is - * going to go in the new projection. - * @param projection the projection to use to query to get the scale for, - * for projection type and height and width. - */ - protected static float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2, Projection projection) { - - return projection.getScale(ll1, ll2, point1, point2); - } - - /* - * public static void main(String[] args) { float degs = - * sphericalUnitsToRad( Planet.earthEquatorialRadius/2, - * Planet.earthEquatorialRadius); Debug.output("degs = " + degs); float - * LAT_DEC_RANGE = 90.0f; float LON_DEC_RANGE = 360.0f; float lat, lon; for - * (int i = 0; i < 100; i++) { lat = - * com.bbn.openmap.LatLonPoint.normalize_latitude( - * (float)Math.random()*LAT_DEC_RANGE); lon = - * com.bbn.openmap.LatLonPoint.wrap_longitude( - * (float)Math.random()*LON_DEC_RANGE); Debug.output( "(" + lat + "," + lon - * + ") : (" + degToRad(lat) + "," + degToRad(lon) + ") : (" + - * radToDeg(degToRad(lat)) + "," + radToDeg(degToRad(lon)) + ")"); } } - */ - - /** - * Generic test for seeing if an left longitude value and a right longitude - * value seem to constitute crossing the dateline. - * - * @param leftLon the leftmost longitude, in decimal degrees. Expected to - * represent the location of the left side of a map window. - * @param rightLon the rightmost longitude, in decimal degrees. Expected to - * represent the location of the right side of a map window. - * @param projScale the projection scale, considered if the two values are - * very close to each other and leftLon less than rightLon. - * @return true if it seems like these two longitude values represent a - * dateline crossing. - */ - public static boolean isCrossingDateline(double leftLon, double rightLon, float projScale) { - // if the left longitude is greater than the right, we're obviously - // crossing the dateline. If they are approximately equal, we could be - // showing the whole earth, but only if the scale is significantly - // large. If the scale is small, we could be really zoomed in. - return ((leftLon > rightLon) - || (MoreMath.approximately_equal(leftLon, rightLon, .001f) && projScale > 1000000f)); - } - - /** - * Given a projection and the starting point of a box (pt1), look at pt2 to - * see if it represents the ratio of the projection map size. If it doesn't, - * provide a point that does. You need to make sure that the proj, pt1 and - * pt2 is not null. - * - * @param proj the projection to use for the calculations. - * @param pt1 upper left point in pixel space - * @param pt2 second point in pixel space. - * @return new pt that matches projection h/w ratio. - */ - public static Point getRatioPoint(Projection proj, Point pt1, Point pt2) { - float mapRatio = (float) proj.getHeight() / (float) proj.getWidth(); - - float boxHeight = (float) (pt1.y - pt2.y); - float boxWidth = (float) (pt1.x - pt2.x); - float boxRatio = Math.abs(boxHeight / boxWidth); - int isNegative = -1; - if (boxRatio > mapRatio) { - // box is too tall, adjust boxHeight - if (boxHeight < 0) { - isNegative = 1; - } - boxHeight = Math.abs(mapRatio * boxWidth); - pt2.y = pt1.y + (isNegative * (int) boxHeight); - - } else if (boxRatio < mapRatio) { - // box is too wide, adjust boxWidth - if (boxWidth < 0) { - isNegative = 1; - } - boxWidth = Math.abs(boxHeight / mapRatio); - pt2.x = pt1.x + (isNegative * (int) boxWidth); - } - return pt2; - } - - /** - * Given a projection to match against and the starting point of a box - * (pt1), look at pt2 to see if it represents the ratio of the projection - * map size. Return a rectangle for the resulting zoom area. - * - * @param proj the current projection. - * @param pt1 first point, where mouse down happened, for instance. - * @param pt2 latest point, where mouse released happened, for instance. - * @param zoomOnCenter whether the first point represents the center of the - * zoom box, or one of the corners. - * @return Rectangle2D representing the new zoom box. - */ - public static Rectangle2D getRatioBox(Projection proj, Point2D pt1, Point2D pt2, boolean zoomOnCenter) { - double mapRatio = (double) proj.getHeight() / (double) proj.getWidth(); - - double boxHeight = Math.abs(pt1.getY() - pt2.getY()); - double boxWidth = Math.abs(pt1.getX() - pt2.getX()); - double boxRatio = Math.abs(boxHeight / boxWidth); - - if (boxRatio > mapRatio) { - boxHeight = Math.abs(mapRatio * boxWidth); - } else if (boxRatio < mapRatio) { - boxWidth = Math.abs(boxHeight / mapRatio); - } - - if (zoomOnCenter) { - double anchorx = pt1.getX() - boxWidth; - double anchory = pt1.getY() - boxHeight; - - return new Rectangle2D.Double(anchorx, anchory, 2 * boxWidth, 2 * boxHeight); - } else { - - double anchorx = pt1.getX(); - if (pt2.getX() < anchorx) { - anchorx -= boxWidth; - } - double anchory = pt1.getY(); - if (pt2.getY() < anchory) { - anchory -= boxHeight; - } - - return new Rectangle2D.Double(anchorx, anchory, boxWidth, boxHeight); - } - } - - /** - * Walks around the perimeter of the sourceMapProjection and returns the - * lat/lon coords of the outline. - * - * @param sourceMapProjection the source map's projection. - * @return double[] in y, x order, in whatever units the source map - * projection's inverse function returns. - */ - public static double[] getProjectionScreenOutlineCoords(Projection sourceMapProjection) { - - // Sourge projection not yet set - if (sourceMapProjection == null) { - return null; - } - - // Would have used ArrayList here but didn't for - // backward compatibility. - ArrayList l = new ArrayList(); - - // Get the parameters needed for building the coverage polygon - int width = sourceMapProjection.getWidth(); - int height = sourceMapProjection.getHeight(); - double xinc = ((double) width) / 10.0; - double yinc = ((double) height) / 10.0; - - Point2D center = sourceMapProjection.getCenter(new Point2D.Double()); - Point2D tmpllp; - - // Walk the top edge of the source projection's screen bounds - for (int i = 0; i <= 10; i++) { - tmpllp = sourceMapProjection.inverse(xinc * i, 0, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the right edge of the source projection's screen bounds - for (int i = 0; i <= 10; i++) { - tmpllp = sourceMapProjection.inverse(width, yinc * i, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the south edge of the source projection's screen bounds - for (int i = 10; i >= 0; i--) { - tmpllp = sourceMapProjection.inverse(xinc * i, height, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the left edge of the source projection's screen bounds - for (int i = 10; i >= 0; i--) { - tmpllp = sourceMapProjection.inverse(0, yinc * i, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // populate the coordinate array for the polygon - double[] llarr = new double[l.size() * 2]; - int i = 0; - for (Point2D pnt : l) { - llarr[i] = pnt.getY(); - llarr[i + 1] = pnt.getX(); - i += 2; - } - - return llarr; - } - - /** - * Returns true if the Point is visible on the provided projection. - * - * @param sourceMapProjection - * @param llp - * @return true if the Point is visible on the provided projection. - */ - public static boolean isVisible(Projection sourceMapProjection, Point2D llp) { - boolean ret = false; - if (sourceMapProjection != null) { - if (sourceMapProjection.isPlotable(llp)) { - Point2D p = sourceMapProjection.forward(llp); - double x = p.getX(); - double y = p.getY(); - if (x >= 0 && x <= sourceMapProjection.getWidth() && y >= 0 && y <= sourceMapProjection.getWidth()) { - ret = true; - } - } - } - return ret; - } - - /** - * Cumulative distance calculated between coords. - * @param radianCoords lat, lon, lat, lon order - * @return distance in radians - */ - public static double distance(double[] radianCoords) { - if (radianCoords != null && radianCoords.length >= 4) { - double totalDist = 0.0; - int len = radianCoords.length; - double y1 = radianCoords[0]; - double x1 = radianCoords[1]; - for (int i = 2; i < len - 1; i += 2) { - double y2 = radianCoords[i]; - double x2 = radianCoords[i + 1]; - - totalDist += Geo.distance(y1, x1, y2, x2); - - y1 = y2; - x1 = x2; - } - return totalDist; - } - - return 0.0; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/Projection.java b/src/core/src/main/java/com/bbn/openmap/proj/Projection.java deleted file mode 100644 index ac42c7c7f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/Projection.java +++ /dev/null @@ -1,473 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Projection.java,v $ -// $RCSfile: Projection.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Shape; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -/** - * Projection interface to the OpenMap projection library. - *

- * This is a READONLY interface to the projection object. See the - * Proj class for read/write access. - *

- * A projection is an object that is maintained by the map, and represents a - * abstract "view" of the data. The projection has the properties of x-width, * - * y-height, scale (in pixels/meters), and a x/y center point that is in - * different units, depending on the projection implementation. - *

- * - * Projection Notes/Assumptions: - *

- *

- * - * Implementation Notes: - *

    - *
  • This methods in this interface are safe to use among different threads, - * BUT the underlying classes may not be. Use with care. - *
- *

- * - * Bibliography: - *
- * Many of the specific projection equations were taken from Map Projections - * --A Working Manual , by John Synder. - * - * @see Proj - * @see Cylindrical - * @see Mercator - * @see CADRG - * @see Azimuth - * @see Orthographic - * @see Cartesian - * @see GeoProj - * - */ -public interface Projection extends java.io.Serializable { - - /** - * Get the scale. - * - * @return float scale - */ - public float getScale(); - - /** - * Get the maximum scale value. - * - * @return float maxscale - */ - public float getMaxScale(); - - /** - * Get the minimum scale value. - * - * @return float minscale - */ - public float getMinScale(); - - /** - * Get the center coordinate. - * - * @return center point - */ - public T getCenter(); - - /** - * Get the center coordinates set in a Point2D object provided. - * - * @param fillInThis the Point2D to fill in. - * @return center point provided. - */ - public T getCenter(T fillInThis); - - /** - * Get the width of the map in pixels. - * - * @return int width. - */ - public int getWidth(); - - /** - * Get the height of the map in pixels. - * - * @return int height. - */ - public int getHeight(); - - /** - * Get the projection ID string. - * - * @return String projID - */ - public String getProjectionID(); - - /** - * Get the upper left (northwest) point of the projection. - *

- * Returns the upper left point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * This is trivial for most cylindrical projections, but much more - * complicated for azimuthal projections. - * - * @return Point2D - */ - public T getUpperLeft(); - - /** - * Get the lower right (southeast) point of the projection. - *

- * Returns the lower right point (or closest equivalent) of the projection - * based on the center point and height and width of screen. - *

- * This is trivial for most cylindrical projections, but much more - * complicated for azimuthal projections. - * - * @return Point2D - */ - public T getLowerRight(); - - /** - * Checks if a point is plot-able. - *

- * Call this to check and see if a point can be plotted. This is meant to be - * used for checking before projecting and rendering Point2D objects - * (bitmaps or text objects tacked at a specific location, for instance). - * - * @param point Point2D - * @return boolean - */ - public boolean isPlotable(Point2D point); - - /** - * Checks if a location is plot-able. - *

- * Call this to check and see if a location can be plotted. This is meant to - * be used for checking before projecting and rendering Point2D objects - * (bitmaps or text objects tacked at a location, for instance). - * - * @param lat vertical location component (units depend on the projection - * implementation). - * @param lon horizontal location component (units depend on the projection - * implementation). - * @return boolean true of plotable. - */ - public boolean isPlotable(double lat, double lon); - - /** - * Forward project a world coordinate into XY pixel space. - * - * @param coord Point2D - * @return Point2D (new) - */ - public Point2D forward(Point2D coord); - - /** - * Forward projects a world coordinate into XY space and return a Point2D. - * - * @param llp Point2D containing coordinates to be projected - * @param pt A Point2D object to load the result into, a new Point2D object - * will be created if this is null. - * @return Point2D The Point2D object provided (for convenience) or created - * with the result. - */ - public Point2D forward(Point2D llp, Point2D pt); - - /** - * Forward project y, x world coordinates into xy space. - * - * @param lat float vertical location component (units depend on projection - * implementation). - * @param lon float horizontal location component (units depend on - * projection implementation). - * @return Point2D (new) - */ - public Point2D forward(float lat, float lon); - - /** - * Forward project y, x world coordinates into xy space. - * - * @param lat double vertical location component (units depend on projection - * implementation). - * @param lon double horizontal location component (units depend on - * projection implementation). - * @return Point2D (new) - */ - public Point2D forward(double lat, double lon); - - /** - * Forward projects y, x world coordinates into XY space and returns a - * Point2D. - * - * @param lat float vertical location component (units depend on projection - * implementation). - * @param lon float horizontal location component (units depend on - * projection implementation). - * @param pt A Point2D object to load the result into, a new Point2D object - * will be created if this is null. - * @return Point2D The Point2D object provided (for convenience) or created - * with the result. - */ - public Point2D forward(float lat, float lon, Point2D pt); - - /** - * Forward projects y, x world coordinates into XY space and returns a - * Point2D. - * - * @param lat double vertical location component (units depend on projection - * implementation). - * @param lon double horizontal location component (units depend on - * projection implementation). - * @param pt A Point2D object to load the result into, a new Point2D object - * will be created if this is null. - * @return Point2D The Point2D object provided (for convenience) or created - * with the result. - */ - public Point2D forward(double lat, double lon, Point2D pt); - - /** - * Forward project a shape defined with world coordinates into map x, y - * space. - * - * @param shape java.awt.Shape object to project. - * @return java.awt.Shape object defined for projection. - */ - public Shape forwardShape(Shape shape); - - /** - * Inverse project a Point2D from map x/y space into world coordinates. - * - * @param point XY Point2D - * @return Point2D (new) - */ - public T inverse(Point2D point); - - /** - * Inverse project a Point2D from map x/y space into world coordinates. - * - * @param point2D XY Point2D - * @param llpt resulting Point2D object to load the result into, a new - * Point2D object will be created if this is null. - * @return Point2D Object containing result. - */ - public T inverse(Point2D point2D, T llpt); - - /** - * Inverse project x,y coordinates into world coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @return Point2D (new) - */ - public T inverse(double x, double y); - - /** - * Inverse project x,y coordinates into world coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @param llpt Point2D to be loaded with the result. A new Point2D object - * will be created if this is null. - * @return Point2D llpt - * @see Proj#inverse(Point2D) - */ - public T inverse(double x, double y, T llpt); - - /** - * Simple shape inverse projection, converts the x,y values in the shape to - * the x, y values of the projection. - * - * @param shape projected shape. - * @return Shape containing source coordinates inversely projected. - */ - public Shape inverseShape(Shape shape); - - /** - * Pan the map/projection. - *

    - *
  • pan(180, c) pan south `c' amount. - *
  • pan(-90, c) pan west `c' amount. - *
  • pan(0, c) pan north `c' amount. - *
  • pan(90, c) pan east `c' amount. - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c distance in units determined by the projection implementation. - */ - public void pan(double Az, double c); - - /** - * Pan the map/projection. - *
    - *
  • pan(180) pan south - *
  • pan(-90) pan west - *
  • pan(0) pan north - *
  • pan(90) pan east - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - public void pan(double Az); - - /** - * Forward project a line defined by two coordinate end points. - *

- * Returns a ArrayList int[] of (x[], y[]) coordinate pair(s) of the - * projected line(s). - */ - public ArrayList forwardLine(Point2D ll1, Point2D ll2); - - /** - * Forward project a rectangle defined by an upper left point and a lower - * right point. - *

- * Returns a ArrayList int[] of (x[], y[]) coordinate pairs of the - * projected points. - * - * @param ll1 Point2D of northwest corner - * @param ll2 Point2D of southeast corner - * @return ArrayList - */ - public ArrayList forwardRect(Point2D ll1, Point2D ll2); - - /** - * Forward project a polygon defined by the coordinates. The isFilled flag - * is only occasionally important, for certain projections in certain - * situations. - * - * @param rawllpts a set of y, x coordinates. - * @param isFilled true of is important to note the area of the poly, - * instead of just the edge. - * @return ArrayList float[] contains sets of float[]x, float[] y arrays. - */ - public ArrayList forwardPoly(float[] rawllpts, boolean isFilled); - - /** - * Forward project a polygon defined by the coordinates. The isFilled flag - * is only occasionally important, for certain projections in certain - * situations. - * - * @param rawllpts a set of y, x coordinates. - * @param isFilled true of is important to note the area of the poly, - * instead of just the edge. - * @return ArrayList float[] contains sets of float[]x, float[] y arrays. - */ - public ArrayList forwardPoly(double[] rawllpts, boolean isFilled); - - /** - * Forward project a raw array of world coordinates. This assumes nothing - * about the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - * - * @param rawllpts array of y, x - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, - boolean[] visible, int copyoff, int copylen); - - /** - * Forward project a raw array of world coordinates. This assumes nothing - * about the array of coordinates. In no way does it assume the points are - * connected or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - * - * @param rawllpts array of y, x - * @param rawoff offset into rawllpts - * @param xcoords x coordinates - * @param ycoords y coordinates - * @param visible coordinates visible? - * @param copyoff offset into x,y,visible arrays - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, - boolean[] visible, int copyoff, int copylen); - - /** - * Clone the projection. - * - * @return Projection clone of this one. - */ - public Projection makeClone(); - - /** - * Get the String used as a name, usually as a type. - */ - public String getName(); - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll1 coordinate, the upper left corner - * of the area of interest. Note that this is where ll1 is going to - * go in the new projection, not where it is now. - * @param point2 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll2 coordinate, usually the lower - * right corner of the area of interest. Note that this is where ll2 - * is going to go in the new projection, not where it is now. - */ - public float getScale(T ll1, T ll2, Point2D point1, Point2D point2); - - /** - * Get the unprojected coordinates units of measure. - * - * @return Length. May be null if unknown. - */ - public Length getUcuom(); - - /** - * Get the rotation setting of the view for this projection. Provided here - * so that map objects manage their orientation if they want. - * - * @return rotation of the view in RADIANS. - */ - public double getRotationAngle(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionException.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionException.java deleted file mode 100644 index 5bb34e929..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionException.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionException.java,v $ -// $RCSfile: ProjectionException.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:23 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -/** - * A RuntimeException subclass to handle problems creating a - * projection with the ProjectionFactory. - */ -public class ProjectionException extends RuntimeException { - - public ProjectionException(Exception e) { - super(e.toString()); - } - - public ProjectionException(String s) { - super(s); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionFactory.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionFactory.java deleted file mode 100644 index cc5066f02..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionFactory.java +++ /dev/null @@ -1,557 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionFactory.java,v $ -// $RCSfile: ProjectionFactory.java,v $ -// $Revision: 1.15 $ -// $Date: 2007/04/17 20:25:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.SoloMapComponent; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The ProjectionFactory creates Projections. It used to have Projection classes - * hard-coded into it which were accessible through static methods, but this - * paradigm has been changed slightly so the ProjectionFactory is a - * SoloMapComponent added to the MapHandler. It will attach itself to a MapBean - * if it finds one in the MapHandler. - *

- * - * The ProjectionFactory can look for ProjectionLoaders in the MapHandler to - * dynamically add projections to the factory. The ProjectionHandler can also - * create ProjectionLoaders from property settings. Changes to the available - * projections can be discovered through property changes. - *

- */ -public class ProjectionFactory extends OMComponent implements SoloMapComponent { - - /** - * Center lat/lon property parameter for new projections passed to - * ProjectionLoader. - */ - public final static String CENTER = "CENTER"; - /** - * Scale property parameter for new projections passed to ProjectionLoader. - */ - public final static String SCALE = "SCALE"; - /** - * Projection height (pixels) property parameter for new projections passed - * to ProjectionLoader. - */ - public final static String HEIGHT = "HEIGHT"; - /** - * Projection width (pixels) property parameter for new projections passed - * to ProjectionLoader. - */ - public final static String WIDTH = "WIDTH"; - /** - * Datum property parameter for new projections passed to ProjectionLoader. - */ - public final static String DATUM = "DATUM"; - - /** - * The property name that is fired when the list of available projections - * has changed. - */ - public final static String AvailableProjectionProperty = "AvailableProjections"; - - /** - * ProjectionFactory property used to designate new projection loaders that - * should be created from properties. - */ - public final static String ProjectionLoadersProperty = "projectionLoaders"; - - /** - * PropertyChangeSupport for letting listeners know about new projections - * that are available from the factory. - */ - protected PropertyChangeSupport pcs; - - protected Vector projLoaders = new Vector(); - - /** - * - */ - public ProjectionFactory() { - pcs = new PropertyChangeSupport(this); - } - - /** - * Check the properties for those to create ProjectionLoaders. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String loaderPrefixesString = props.getProperty(prefix + ProjectionLoadersProperty); - if (loaderPrefixesString != null) { - List loaderPrefixes = PropUtils.parseSpacedMarkers(loaderPrefixesString); - List loaders = ComponentFactory.create(loaderPrefixes, prefix, props); - - for (Object obj : loaders) { - if (obj instanceof ProjectionLoader) { - projLoaders.add((ProjectionLoader) obj); - } - } - } - } - - /** - * Create the properties to create ProjectionLoaders that this loader - * created. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - if (projLoaders != null) { - StringBuffer markerlist = new StringBuffer(); - int count = 0; - for (Iterator it = projLoaders.iterator(); it.hasNext();) { - - ProjectionLoader pl = it.next(); - String markerName; - if (pl instanceof PropertyConsumer) { - - PropertyConsumer pc = (PropertyConsumer) pl; - markerName = PropUtils.getScopedPropertyPrefix(pc.getPropertyPrefix()); - - // Need to do this here before the marker name - // potentially changes - props.put(markerName + "class", pl.getClass().getName()); - - if (markerName.startsWith(prefix)) { - markerName = markerName.substring(prefix.length()); - } - pc.getProperties(props); - - } else { - - markerName = "projectionLoader" + (count++); - // Need to do this here for any projection loaders - // that aren't property consumers. - props.put(markerName + ".class", pl.getClass().getName()); - - } - - markerlist.append(" ").append(markerName); - } - - props.put(prefix + ProjectionLoadersProperty, markerlist.toString()); - } - - return props; - } - - /** - * Returns an array of Projection names available from this factory. - */ - public String[] getAvailableProjections() { - // duplicate List to handle multiple simultaneous requests - List projLoaders = new ArrayList(getProjectionLoaders()); - int nProjections = projLoaders.size(); - String projNames[] = new String[nProjections]; - int i = 0; - - for (Iterator it = projLoaders.iterator(); it.hasNext();) { - projNames[i++] = it.next().getPrettyName(); - } - - return projNames; - } - - /** - * Return the Projection Class with the given pretty name. - * - * @param name the name of the projection, set in the pretty name of it's - * ProjectionLoader. - * @return Class of Projection, or null if not found. - */ - @SuppressWarnings("unchecked") - public Class getProjClassForName(String name) { - if (name != null) { - for (Iterator it = getProjectionLoaders().iterator(); it.hasNext();) { - ProjectionLoader loader = it.next(); - if (name.equalsIgnoreCase(loader.getPrettyName())) { - return loader.getProjectionClass(); - } - } - - // If there wasn't a class with the pretty name, check to - // make sure it wasn't a class name itself. If it fails, - // return null. We just want to do this in case people - // start using class names for pretty names. - try { - Class clss = Class.forName(name); - if (Projection.class.isAssignableFrom(clss)) { - return (Class) clss; - } - - } catch (ClassNotFoundException cnfe) { - } - - } - return null; - } - - /** - * Makes a new projection based on the given projection class name and - * parameters from the given projection. - */ - public Projection makeProjection(String projClassName, Projection p) { - - Point2D ctr = p.getCenter(); - return makeProjection(projClassName, ctr, p.getScale(), p.getWidth(), p.getHeight()); - } - - /** - * Create a projection. If the Class for the classname can't be found, a - * Mercator projection will be returned. - * - * @param projClassName the classname of the projection. - * @param center Point2D center of the projection. - * @param scale float scale. - * @param width pixel width of projection. - * @param height pixel height of projection. - * @return Projection - */ - public Projection makeProjection(String projClassName, Point2D center, float scale, int width, - int height) { - - if (projClassName == null) { - throw new ProjectionException("No projection class name specified"); - } - - return makeProjection(getProjClassForName(projClassName), center, scale, width, height); - } - - /** - * Create a projection. If the class can't be found, a Mercator projection - * will be returned. - * - * @param projClass the class of the projection. - * @param center Point2D center of the projection. - * @param scale float scale. - * @param width pixel width of projection. - * @param height pixel height of projection. - * @return Projection - */ - public Projection makeProjection(Class projClass, Point2D center, - float scale, int width, int height) { - - ProjectionLoader loader = MercatorLoader.defaultMercator; - - for (Iterator it = iterator(); it.hasNext();) { - ProjectionLoader pl = (ProjectionLoader) it.next(); - if (pl.getProjectionClass() == projClass) { - loader = pl; - } - } - - return makeProjection(loader, center, scale, width, height); - } - - /** - * Looks at the Environment settings for the default projection and returns - * a Projection suited for those settings. If there is a problem creating - * the projection, the default projection of the MapBean will be returned. - * The ProjectionFactory needs to be loaded with the Projection class - * described in the properties before this will return an expected - * projection. - * - * @return Projection from Environment settings. - */ - public Projection getDefaultProjectionFromEnvironment() { - return getDefaultProjectionFromEnvironment(0, 0); - } - - /** - * Looks at the Environment settings for the default projection and returns - * a Projection suited for those settings. If there is a problem creating - * the projection, the default projection of the MapBean will be returned. - * The ProjectionFactory needs to be loaded with the Projection class - * described in the properties before this will return an expected - * projection. - * - * @param width pixel height of projection. If 0 or less, the - * Environment.Width value will be used. - * @param height pixel height of projection. If 0 or less, the - * Environment.Height value will be used. - * @return Projection from Environment settings, fit for the pixel height - * and width provided. - */ - public Projection getDefaultProjectionFromEnvironment(int width, int height) { - // Initialize the map projection, scale, center - // with user prefs or defaults - Projection proj = null; - - int w = (width <= 0) ? Environment.getInteger(Environment.Width, MapBean.DEFAULT_WIDTH) - : width; - int h = (height <= 0) ? Environment.getInteger(Environment.Height, MapBean.DEFAULT_HEIGHT) - : height; - - try { - proj = makeProjection(Environment.get(Environment.Projection), new LatLonPoint.Float(Environment.getFloat(Environment.Latitude, 0f), Environment.getFloat(Environment.Longitude, 0f)), Environment.getFloat(Environment.Scale, Float.POSITIVE_INFINITY), w, h); - - } catch (com.bbn.openmap.proj.ProjectionException pe) { - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine("Can't use (" - + Environment.Projection - + " = " - + Environment.get(Environment.Projection) - + ") property as a projection class, need a class name instead. Using default of com.bbn.openmap.proj.Mercator."); - } - proj = makeProjection(Mercator.class, new LatLonPoint.Float(Environment.getFloat(Environment.Latitude, 0f), Environment.getFloat(Environment.Longitude, 0f)), Environment.getFloat(Environment.Scale, Float.POSITIVE_INFINITY), w, h); - } - - return proj; - } - - /** - * Call the provided ProjectionLoader to create the projection with the - * given parameters. The parameters are converted to Properties before being - * passed to the ProjectionLoader. - * - * @param loader ProjectionLoader for projection type - * @param center center coordinate for projection - * @param scale scale for projection - * @param width pixel width of projection - * @param height pixel height of projection - * @return Projection - */ - public Projection makeProjection(ProjectionLoader loader, Point2D center, float scale, - int width, int height) { - return makeProjection(loader, center, scale, width, height, null); - } - - /** - * Call the provided ProjectionLoader to create the projection with the - * given parameters. The parameters are converted to Properties before being - * passed to the ProjectionLoader. The ProjectionLoader should throw a - * ProjectionException from here if it has a problem creating the projection - * with the provided parameters. - * - * @param loader projection loader to use. - * @param center Point2D center of the projection. - * @param scale float scale. - * @param width pixel width of projection. - * @param height pixel height of projection. - * @param projProps a Properties object to add the parameters to, which can - * include extra parameters that are needed by this particular - * projection loader. If null, a Properties object will be created. - * @return projection, or null if the projection can't be created. - */ - public Projection makeProjection(ProjectionLoader loader, Point2D center, float scale, - int width, int height, Properties projProps) { - - Projection proj = null; - if (loader == null) { - getLogger().warning("not given a ProjectionLoader to use to create a Projection"); - return proj; - } - - if (projProps == null) { - projProps = new Properties(); - } - - projProps.put(CENTER, center); - projProps.put(SCALE, Float.toString(scale)); - projProps.put(WIDTH, Integer.toString(width)); - projProps.put(HEIGHT, Integer.toString(height)); - - proj = loader.create(projProps); - - if (proj == null) { - getLogger().warning("tried to create a Projection from a " + loader.getPrettyName() - + ", " + loader.getProjectionClass().getName() + ", failed."); - } - - return proj; - } - - public void addProjectionLoader(ProjectionLoader loader) { - projLoaders.add(loader); - fireLoadersChanged(); - } - - public boolean removeProjectionLoader(ProjectionLoader loader) { - boolean removed = projLoaders.remove(loader); - if (removed) { - fireLoadersChanged(); - } - return removed; - } - - public void clearProjectionLoaders() { - if (!projLoaders.isEmpty()) { - projLoaders.clear(); - fireLoadersChanged(); - } - } - - public Iterator iterator() { - return projLoaders.iterator(); - } - - public int numProjections() { - return projLoaders.size(); - } - - public Collection getProjectionLoaders() { - return Collections.unmodifiableCollection(projLoaders); - } - - protected void fireLoadersChanged() { - pcs.firePropertyChange(AvailableProjectionProperty, null, projLoaders); - } - - public void addPropertyChangeListener(PropertyChangeListener pcl) { - if (pcl != null) { - pcs.addPropertyChangeListener(pcl); - pcl.propertyChange(new PropertyChangeEvent(this, AvailableProjectionProperty, null, projLoaders)); - } - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener pcl) { - if (pcl != null) { - pcs.addPropertyChangeListener(propertyName, pcl); - pcl.propertyChange(new PropertyChangeEvent(this, AvailableProjectionProperty, null, projLoaders)); - } - } - - public void removePropertyChangeListener(PropertyChangeListener pcl) { - pcs.removePropertyChangeListener(pcl); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener pcl) { - pcs.removePropertyChangeListener(propertyName, pcl); - } - - /** - * Using the MapHandler to find ProjectionLoaders being added from the - * application. - */ - public void findAndInit(Object obj) { - if (obj instanceof ProjectionLoader) { - addProjectionLoader((ProjectionLoader) obj); - } - - if (obj instanceof MapBean) { - ((MapBean) obj).setProjectionFactory(this); - } - } - - /** - * Using the MapHandler to find ProjectionLoaders being removed from the - * application. - */ - public void findAndUndo(Object obj) { - if (obj instanceof ProjectionLoader) { - removeProjectionLoader((ProjectionLoader) obj); - } - } - - /** - * Convenience method to load a ProjectionFactory and default projections - * into the provided MapHandler. - * - * @param mapHandler the MapHandler to receive the default ProjectionFactory - */ - public static void loadDefaultProjections(MapHandler mapHandler) { - mapHandler.add(loadDefaultProjections(new ProjectionFactory())); - } - - /** - * Convenience method to load default projections into a ProjectionFactory - * that will be created. - * - * @return ProjectionFactory - */ - public static ProjectionFactory loadDefaultProjections() { - return loadDefaultProjections(new ProjectionFactory()); - } - - /** - * Convenience method to load default projections into a ProjectionFactory. - * - * @param pf - * @return ProjectionFactory - */ - public static ProjectionFactory loadDefaultProjections(ProjectionFactory pf) { - if (pf != null && pf.numProjections() == 0) { - pf.addProjectionLoader(new com.bbn.openmap.proj.MercatorLoader()); - pf.addProjectionLoader(new com.bbn.openmap.proj.OrthographicLoader()); - pf.addProjectionLoader(new com.bbn.openmap.proj.CADRGLoader()); - pf.addProjectionLoader(new com.bbn.openmap.proj.LLXYLoader()); - pf.addProjectionLoader(new com.bbn.openmap.proj.GnomonicLoader()); - pf.addProjectionLoader(new com.bbn.openmap.proj.CartesianLoader()); - } - return pf; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(ProjectionFactory.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - // -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionLoader.java deleted file mode 100644 index 273986247..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionLoader.java +++ /dev/null @@ -1,64 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionLoader.java,v $ -// $RCSfile: ProjectionLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.util.Properties; - -/** - * A ProjectionLoader is a class that knows how to create projection - * classes for given parameters. The ProjectionFactory used to have - * projection classes hard-coded into it, but it now uses - * ProjectionLoaders to create different projections for it. It can - * provide the Class to use for a certain projection, and can provide - * a name and description to use for GUIs. The ProjectionFactory looks - * for these in the MapHandler. - * - * @see ProjectionFactory - * @see BasicProjectionLoader - */ -public interface ProjectionLoader { - - /** - * Get a class name to use for the projection. This will be used - * as a key in the projection factory. - */ - public Class getProjectionClass(); - - /** - * Get a pretty name for the projection. - */ - public String getPrettyName(); - - /** - * Get a description for the projection. - */ - public String getDescription(); - - /** - * Create the projection with the given parameters. - * - * @throws ProjectionException if a parameter is missing or invalid - */ - public Projection create(Properties props) throws ProjectionException; - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStack.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStack.java deleted file mode 100644 index 38aaae4bb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStack.java +++ /dev/null @@ -1,392 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStack.java,v $ -// $RCSfile: ProjectionStack.java,v $ -// $Revision: 1.8 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Container; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Point2D; -import java.util.Stack; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; - -/** - * Provides Projection Stack, to listen for projection changes and remember them - * as they pass by. As a Tool, it provides a GUI so that past projections can be - * retrieved, and, if a past projection is being displayed, a forward projection - * stack is activated to provide a path to get to the last projection set in the - * MapBean. ProjectionStackTriggers should hook themselves up to the - * ProjectionStack. The ProjectionStack is responsible for finding and - * connecting to the MapBean. - */ -public class ProjectionStack extends OMComponent implements ActionListener, - ProjectionListener { - - private final static Logger logger = Logger - .getLogger("com.bbn.openmap.proj.ProjectionStack"); - - public final static int DEFAULT_MAX_SIZE = 10; - public final static int REMEMBER_ALL = -1; - /** - * The currentProjection should be the top item on the backStack. - */ - protected transient ProjHolder currentProjection; - protected transient String currentProjectionID; - protected transient Container face; - protected transient MapBean mapBean; - protected int stackSize = DEFAULT_MAX_SIZE; - - public final static transient String BackProjCmd = "backProjection"; - public final static transient String ForwardProjCmd = "forwardProjection"; - public final static transient String ClearBackStackCmd = "clearBackStack"; - public final static transient String ClearForwardStackCmd = "clearForwardStack"; - public final static transient String ClearStacksCmd = "clearStacks"; - - protected Stack backStack; - protected Stack forwardStack; - - protected ProjectionStackSupport triggers; - - /** - * Create the projection submenu. - */ - public ProjectionStack() { - } - - public void setMapBean(MapBean map) { - if (mapBean != null) { - mapBean.removeProjectionListener(this); - } - - if (map != null) { - map.addProjectionListener(this); - } - mapBean = map; - } - - public MapBean getMapBean() { - return mapBean; - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand().intern(); - - logger.fine("Received command: " + command); - - boolean changeProjection = false; - - // This is important. We need to set the current projection - // before setting the projection in the MapBean. That way, - // the projectionChanged method actions won't get fired - if (command == BackProjCmd && backStack != null && backStack.size() > 1) { - - pop(); - currentProjection = backStack.peek(); - changeProjection = true; - } else if (command == ForwardProjCmd && forwardStack != null - && !forwardStack.empty()) { - - currentProjection = backPop(); - changeProjection = true; - } else { - clearStacks( - (command == ClearBackStackCmd || command == ClearStacksCmd), - (command == ClearForwardStackCmd || command == ClearStacksCmd)); - // fireStackStatus is called in clearStacks - } - - if (changeProjection && mapBean != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("changing mapbean projection to : " - + currentProjection); - } - - Projection currProj = currentProjection.create(mapBean.getWidth(), - mapBean.getHeight()); - mapBean.setProjection(currProj); - fireStackStatus(); - } - } - - // ------------------------------------------------------------ - // ProjectionListener interface - // ------------------------------------------------------------ - - protected ProjectionFactory getProjectionFactory(ProjectionEvent e) { - Object obj = e.getSource(); - if (obj instanceof MapBean) { - return ((MapBean) obj).getProjectionFactory(); - } else if (mapBean != null) { - return mapBean.getProjectionFactory(); - } - return ProjectionFactory.loadDefaultProjections(); - } - - /** - * The Map projection has changed. - * - * @param e - * ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - logger.fine("ProjectionStack.projectionChanged()"); - Projection newProj = e.getProjection(); - - // If the ProjectionStack doesn't already know about the - // projection change, that means that it didn't instigate it, - // and the new projection needs to get added to the stack, - // with the forwardStack cleared. - if (currentProjection == null || !currentProjection.equals(newProj)) { - logger.fine("pushing projection on backStack"); - // push on the backStack, clear the forwardStack; - currentProjection = push(new ProjHolder(newProj, - getProjectionFactory(e))); - if (forwardStack != null) { - forwardStack.clear(); - } - fireStackStatus(); - } else { - logger - .fine("new projection matches current projection, no action."); - } - } - - /** - * Clear out the chosen projection stacks and fire an event to update the - * triggers on stack status. - * - * @param clearBackStack - * clear out the backward projection stack. - * @param clearForwardStack - * clear out the forward projection stack. - */ - public synchronized void clearStacks(boolean clearBackStack, - boolean clearForwardStack) { - - if (clearBackStack && backStack != null) { - ProjHolder currentProj = pop(); // current projection - backStack.clear(); - push(currentProj); - } - - if (clearForwardStack && forwardStack != null) { - forwardStack.clear(); - } - fireStackStatus(); - } - - /** - * Take a ProjHolder off the backStack, and push it on the forward stack. - * - * @return the ProjHolder pushed onto the forwardStack. - */ - protected synchronized ProjHolder pop() { - ProjHolder proj = backStack.pop(); - - if (forwardStack == null) { - forwardStack = new Stack(); - } - - while (forwardStack.size() >= stackSize) { - forwardStack.removeElementAt(0); - } - forwardStack.push(proj); - return proj; - } - - /** - * Take a ProjHolder off the forwardStack, and push it on the backStack. - * - * @return the ProjHolder pushed on the backStack. - */ - protected synchronized ProjHolder backPop() { - ProjHolder proj = forwardStack.pop(); - - // This has almost no chance of happening... - if (backStack == null) { - backStack = new Stack(); - } - - while (backStack.size() >= stackSize) { - backStack.removeElementAt(0); - } - backStack.push(proj); - return proj; - } - - /** - * Put a new ProjHolder on the backStack, to remember for later in case we - * need to back up. - * - * @param proj - * ProjHolder. - * @return the ProjHolder pushed on the backStack. - */ - protected synchronized ProjHolder push(ProjHolder proj) { - if (backStack == null) { - backStack = new Stack(); - } - - if (backStack.size() >= stackSize) { - backStack.removeElementAt(0); - } - return backStack.push(proj); - } - - public void fireStackStatus() { - fireStackStatus((backStack != null && backStack.size() > 1), - (forwardStack != null && !forwardStack.empty())); - } - - public void fireStackStatus(boolean enableBackButton, - boolean enableForwardButton) { - if (triggers != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("back enabled: " + enableBackButton - + ", forward enabled: " + enableForwardButton); - } - triggers.fireStackStatus(enableBackButton, enableForwardButton); - } - } - - /** - * ProjectionStackTriggers should call this method, and all will be well. - */ - public void addProjectionStackTrigger(ProjectionStackTrigger trigger) { - trigger.addActionListener(this); - if (triggers == null) { - triggers = new ProjectionStackSupport(); - } - triggers.add(trigger); - trigger.updateProjectionStackStatus((backStack != null && backStack - .size() > 1), (forwardStack != null && !forwardStack.empty())); - } - - /** - * ProjectionStackTriggers should call this method, and all will be well. - */ - public void removeProjectionStackTrigger(ProjectionStackTrigger trigger) { - trigger.removeActionListener(this); - if (triggers != null) { - triggers.remove(trigger); - if (triggers.size() == 0) { - triggers = null; - } - } - } - - // ------------------------------------------------------------ - // BeanContextMembershipListener and BeanContextChild interface - // ------------------------------------------------------------ - - /** - * Look at the object received in a MapHandler status message and disconnect - * from it if necessary. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof com.bbn.openmap.MapBean) { - logger.fine("ProjectionStack removing a MapBean."); - MapBean map = getMapBean(); - if (map != null && map == (MapBean) someObj) { - setMapBean(null); - } - } - } - - /** - * Look at the object received in a MapHandler status message and connect to - * it if necessary. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof com.bbn.openmap.MapBean) { - logger.fine("ProjectionStack found a MapBean."); - setMapBean((MapBean) someObj); - } - } - - public class ProjHolder { - - public Class projClass; - public float scale; - public Point2D center; - protected Point tmpPoint1; - protected Point tmpPoint2; - protected ProjectionFactory projFactory; - - public ProjHolder(Projection proj, ProjectionFactory projectionFactory) { - projClass = proj.getClass(); - scale = proj.getScale(); - center = proj.getCenter(); - projFactory = projectionFactory; - } - - public boolean equals(Projection proj) { - // For some reason, the ProjectionFactory can mess up the - // center lat/lons, so that the center isn't EXACTLY what - // they were when the projection was created. It's almost - // like it decides what map it can draw, and then figures - // out what the coordinate of the center pixel of the - // projection it created was. Doing this projection hack - // seems to accurately determine what projections are - // actually identical visually, which is what you want to - // know anyway. - Point2D tmpPoint1 = proj.forward(proj.getCenter()); - Point2D tmpPoint2 = proj.forward(center); - - boolean same = (projClass == proj.getClass() - && scale == proj.getScale() && - - // NOT GOOD ENOUGH! Sometimes, the - // slighest difference causes a false - // false. - - // MoreMath.approximately_equal(center.getLatitude(), - // proj.getCenter().getLatitude(), - // .00001f) && - // MoreMath.approximately_equal(center.getLongitude(), - // proj.getCenter().getLongitude(), - // .00001f) - // This seems to work... - tmpPoint1.getX() == tmpPoint2.getX() && tmpPoint1.getY() == tmpPoint2 - .getY()); - return same; - } - - public Projection create(int width, int height) { - return projFactory.makeProjection(projClass, center, scale, width, - height); - } - - public String toString() { - return ("[ProjHolder: class(" + projClass.getName() + "), scale(" - + scale + "), center(" + center + ")]"); - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackSupport.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackSupport.java deleted file mode 100644 index 397066d47..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackSupport.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStackSupport.java,v $ -// $RCSfile: ProjectionStackSupport.java,v $ -// $Revision: 1.5 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.util.ArrayList; -import java.util.Iterator; - -import com.bbn.openmap.util.Debug; - -/** - * This is a utility class that can be used by beans that need support - * for handling ProjectionListeners and firing ProjectionEvents. You - * can use an instance of this class as a member field of your bean - * and delegate work to it. - */ -public class ProjectionStackSupport implements java.io.Serializable { - - transient private ArrayList triggers; - - /** - * Construct a ProjectionStackSupport. - */ - public ProjectionStackSupport() {} - - /** - * Add a ProjectionStackTrigger. - * - * @param pt ProjectionStackTrigger - */ - public synchronized void add(ProjectionStackTrigger pt) { - if (triggers == null) { - triggers = new ArrayList(); - } - - if (!triggers.contains(pt)) { - triggers.add(pt); - } - } - - /** - * Remove a ProjectionStackTrigger. - * - * @param pt ProjectionStackTrigger - */ - public synchronized void remove(ProjectionStackTrigger pt) { - if (triggers == null) { - return; - } - triggers.remove(pt); - } - - /** - * Return a cloned list of Triggers. - * - * @return Vector of triggers, null if none have been added. - */ - public synchronized ArrayList getTriggers() { - if (triggers == null) { - return null; - } - - return (ArrayList) triggers.clone(); - } - - public int size() { - return triggers.size(); - } - - /** - * Send a status to all registered triggers. - * - * @param enableBackProjections there is at least one past - * projection in the back cache. - * @param enableForwardProjections there is at least one future - * projection in the forward cache. Used when a past - * projection is being used. - */ - public void fireStackStatus(boolean enableBackProjections, - boolean enableForwardProjections) { - - ArrayList targets = getTriggers(); - - if (triggers == null) { - return; - } - - Iterator iterator = targets.iterator(); - - while (iterator.hasNext()) { - ProjectionStackTrigger target = iterator.next(); - if (Debug.debugging("projectionstack")) { - Debug.output("ProjectionStackSupport.fireStackStatus(): target is: " - + target); - } - - target.updateProjectionStackStatus(enableBackProjections, - enableForwardProjections); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackTrigger.java b/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackTrigger.java deleted file mode 100644 index 4fea101d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/ProjectionStackTrigger.java +++ /dev/null @@ -1,61 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjectionStackTrigger.java,v $ -// $RCSfile: ProjectionStackTrigger.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:23 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.event.ActionListener; - -/** - * Provides Projection Stack input by firing BackProkCmd and - * ForwardProjCmd commands, which cause it to set a projection in the - * MapBean. The commands used when firing an action event should be - * the ones listed in the ProjectionStack - */ -public interface ProjectionStackTrigger { - - /** - * Add an ActionListener for events that trigger events to shift - * the Projection stack. - */ - public void addActionListener(ActionListener al); - - /** - * Remove an ActionListener that receives events that trigger - * events to shift the Projection stack. - */ - public void removeActionListener(ActionListener al); - - /** - * To receive a status to let the trigger know if any projections - * in the forward or backward stacks exist, possibly to disable - * any gui widgets. - * - * @param containsBackProjections there is at least one past - * projection in the back cache. - * @param containsForwardProjections there is at least one future - * projection in the forward cache. Used when a past - * projection is being used. - */ - public void updateProjectionStackStatus(boolean containsBackProjections, - boolean containsForwardProjections); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/proj/RhumbCalculator.java b/src/core/src/main/java/com/bbn/openmap/proj/RhumbCalculator.java deleted file mode 100644 index ef057a6e3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/RhumbCalculator.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * $Header: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/RhumbCalculator.java,v 1.5 2005/12/09 21:09:01 dietrick Exp $ - * - * Copyright 2004 OBR Centrum Techniki Morskiej, All rights reserved. - * - */ -package com.bbn.openmap.proj; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; - -/** - * - * @version $Header: - * /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/RhumbCalculator - * .java,v 1.1 2004/05/10 20:53:58 dietrick Exp $ - * @author pawkub - * - * This class contains methods that helps you make calculations - * performed ASSOCIATED The so-called. Rhumbline. This class contains - * several oglnych wzorw and beyond OpenMap is ASSOCIATED with nothing. - * You can drop into OpenMap and contained in it, where will you need - * (and it is places a few). - */ -public class RhumbCalculator { - - /** - * The constructor is private, because (for now) class contains only A few - * static methods. - */ - private RhumbCalculator() { - } - - /** - * This method allows public location point on the Rhumb Line, znajc - * Location reference point, the azimuth and Distance. - * - * @param point LatLonPoint the staring point. - * @param azimuth in radians, clockwise from North (0.0). - * @param dist distance in radians. - * @return LatLonPoint on the rhumb line at the azimuth and distance - * specified. - */ - public static LatLonPoint calculatePointOnRhumbLine(LatLonPoint point, double azimuth, - double dist) { - double az = MoreMath.TWO_PI_D - azimuth; - double lat1 = point.getRadLat(); - double lon1 = point.getRadLon(); - - double lat = lat1 + dist * Math.cos(az); - double dphi = Math.log(Math.abs((1 + Math.sin(lat)) / Math.cos(lat))) - - Math.log(Math.abs((1 + Math.sin(lat1)) / Math.cos(lat1))); - double dlon = 0.0; - - if (Math.abs(Math.cos(az)) > Math.sqrt(0.00000000000001)) { - dlon = dphi * Math.tan(az); - } else { // along parallel - dlon = Math.sin(az) * dist / Math.cos(lat1); - } - - double lon = mod(lon1 - dlon + Math.PI, 2 * Math.PI) - Math.PI; - - return new LatLonPoint.Double(lat, lon, true); - } - - /** - * This method allows znormowa worth to the given - * - * @param y - * @param x - * @return regulated worth - */ - private static double mod(double y, double x) { - double ret; - if (y >= 0) { - ret = y - x * (int) (y / x); - } else { - ret = y + x * ((int) (-y / x) + 1); - } - return ret; - } - - /** - * - * @param p1 LatLonPoint the first point. - * @param p2 LatLonPoint to the second point. - * @return distance in radians - */ - public static double getDistanceBetweenPoints(LatLonPoint p1, LatLonPoint p2) { - double lat1 = p1.getRadLat(); - double lon1 = p1.getRadLon(); - double lat2 = p2.getRadLat(); - double lon2 = p2.getRadLon(); - double d = 0.0; - double tc = 0.0; - double dlon_W = mod(lon2 - lon1, 2 * Math.PI); - double dlon_E = mod(lon1 - lon2, 2 * Math.PI); - - tc = getAzimuthBetweenPoints(p1, p2); - if (Math.abs(lat1 - lat2) < Math.sqrt(0.00000000000001)) { - // distance along parallel - d = Math.min(dlon_W, dlon_E) * Math.cos(lat1); - } else { - d = Math.abs((lat2 - lat1) / Math.cos(tc)); - } - return d; - } - - /** - * This method allows you to calculate the azimuth between the points. - * - * @param p1 LatLonPoint the first point. - * @param p2 LatLonPoint to the second point. - * @return azimuth in radians of the bearing from the first point to the - * second point. - */ - public static double getAzimuthBetweenPoints(LatLonPoint p1, LatLonPoint p2) { - double lat1 = p1.getRadLat(); - double lon1 = p1.getRadLon(); - double lat2 = p2.getRadLat(); - double lon2 = p2.getRadLon(); - - double tc = 0.0; - double dlon_W = mod(lon2 - lon1, 2.0 * Math.PI); - double dlon_E = mod(lon1 - lon2, 2.0 * Math.PI); - double dphi = Math.log(Math.abs((1 + Math.sin(lat2)) / Math.cos(lat2))) - - Math.log(Math.abs((1 + Math.sin(lat1)) / Math.cos(lat1))); - if (dlon_W < dlon_E) {// West is the shortest - tc = mod(Math.atan2(-dlon_W, dphi), 2.0 * Math.PI); - } else { - tc = mod(Math.atan2(dlon_E, dphi), 2.0 * Math.PI); - } - return MoreMath.TWO_PI_D - tc; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/UTMProjection.java b/src/core/src/main/java/com/bbn/openmap/proj/UTMProjection.java deleted file mode 100644 index 842051bbf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/UTMProjection.java +++ /dev/null @@ -1,479 +0,0 @@ -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.UTMGCT; -import com.bbn.openmap.proj.coords.UTMPoint; - -/** - * A OpenMap Projection class that uses the {@link UTMPoint} to do its - * calculation. - */ -public class UTMProjection extends GeoProj { - - /** - * Center of view as xy coordinates relative to the underlying projection - */ - // TODO: find a better name? - protected Point2D.Double xycenter = new Point2D.Double(); - - protected double hy, wx; - - /** - * Pixel per map unit. this is for a projection with a quadratic grid like - * utm - */ - protected double ppu; - - // used for calculating wrapping of ArrayList graphics - // TODO: copied from Cylindrical. may need to change. - protected Point world; // world width in pixels. - - protected int half_world; // world.x / 2 - - protected int zoneNumber; - - protected boolean northern; - - protected Ellipsoid ellps; - - public UTMProjection(LatLonPoint center, float s, int w, int h, int zone_number, - boolean isnorthern, Ellipsoid ellps) { - super(center, s, w, h); - - this.zoneNumber = zone_number; - this.northern = isnorthern; - this.ellps = ellps; - } - - protected void computeParameters() { - // super.computeParameters(); - - hy = height / 2; - wx = width / 2; - - if (xycenter != null) { - UTMPoint c = UTMPoint.LLtoUTM(getCenter(), ellps, new UTMPoint(), zoneNumber, - northern); - xycenter.setLocation(c.easting, c.northing); - } - - // width of the world in pixels at current scale - // TODO: copied from Cylindrical. may need to change - if (world == null) { - world = new Point(); - } - world.x = (int) (planetPixelCircumference / scale); - half_world = world.x / 2; - - ppu = (((float) pixelsPerMeter) / getScale()); - } - - public Point2D forward(LatLonPoint llp, Point2D pt) { - return forward(llp, pt, new UTMPoint()); - } - - @Override - public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian) { - LatLonPoint llp = new LatLonPoint.Double(lat, lon, isRadian); - return forward(llp, pt, new UTMPoint()); - } - - public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian, - UTMPoint utmPoint) { - LatLonPoint llp = new LatLonPoint.Double(lat, lon, isRadian); - return forward(llp, pt, utmPoint); - } - - private Point2D forward(LatLonPoint llp, Point2D pt, UTMPoint utmPoint) { - utmPoint = UTMPoint.LLtoUTM(llp, ellps, utmPoint, zoneNumber, northern); - - pt.setLocation((wx + (ppu * (utmPoint.easting - xycenter.getX()))), - (hy - (ppu * (utmPoint.northing - xycenter.getY())))); - - return pt; - } - - public T inverse(double x, double y, T llpt) { - - double northing = xycenter.getY() + ((hy - y) / ppu); - double easting = xycenter.getX() + ((x - wx) / ppu); - - if (!(llpt instanceof LatLonPoint)) { - llpt = (T) new LatLonPoint.Double(); - } - - llpt = (T) UTMPoint.UTMtoLL(ellps, northing, easting, zoneNumber, northern, - (LatLonPoint) llpt); - - return llpt; - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 - * the upper left coordinates of the bounding box. - * @param ll2 - * the lower right coordinates of the bounding box. - * @param point1 - * a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll1 coordinate, the upper left corner of the - * area of interest. - * @param point2 - * a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll2 coordinate, usually the lower right - * corner of the area of interest. - */ - @Override - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2) { - - // super does not calculate scale correct for projections that does use - // the same earth radius up north.. - - double widthPX = point2.getX() - point1.getX(); - - // float heightPX = point2.y - point1.y; - - // Instead of blindly casting, lets just make sure we have the correct object type. - LatLonPoint llp1 = LatLonPoint.getDouble(ll1); - LatLonPoint llp2 = LatLonPoint.getDouble(ll2); - - UTMPoint xx1 = UTMPoint.LLtoUTM(llp1, ellps, new UTMPoint(), - zoneNumber, northern); - UTMPoint xx2 = UTMPoint.LLtoUTM(llp2, ellps, new UTMPoint(), - zoneNumber, northern); - - double widthMap = (xx2.easting - xx1.easting); - float widthScale = (float) (((double) getPPM()) * (widthMap / widthPX)); - - // float heightMap = (xx2.northing - xx1.northing); - // float heightScale = (float) (((double) getPPM()) * (heightMap / - // heightPX)); - - // TODO: use width-, height- or medium scale? I guess width- and height - // scale should be equal as the grid inside a single UTM zone is - // quadratic. - - return widthScale; - } - - protected ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - // TODO: copied from Cylindrical. may need to change. - int n, k, flag = 0, min = 0, max = 0, xp, xadj = 0; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) { - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - } - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // more temp objects to limit number of new objects that needs to be - // created - UTMPoint tempUtm = new UTMPoint(); - LatLonPoint tempLL = new LatLonPoint.Double(); - - // forward project the first point - tempLL.setLatLon(rawllpts[0], rawllpts[1], true); - forward(tempLL, temp, tempUtm); - // forward(rawllpts[0], rawllpts[1], temp, true, tempUtm); - xp = temp.x; - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - tempLL.setLatLon(rawllpts[k], rawllpts[k + 1], true); - forward(tempLL, temp, tempUtm); - // forward(rawllpts[k], rawllpts[k + 1], temp, true, tempUtm); - xs[n] = temp.x; - ys[n] = temp.y; - // segment crosses longitude along screen edge - if (Math.abs(xp - xs[n]) >= half_world) { - flag += (xp < xs[n]) ? -1 : 1;// inc/dec the wrap - // count - min = (flag < min) ? flag : min;// left wrap count - max = (flag > max) ? flag : max;// right wrap count - xadj = flag * world.x;// adjustment to x coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = temp.x;// save previous unshifted x coordinate - if (flag != 0) { - xs[n] += xadj;// adjust x coordinates - } - } - min *= -1;// positive magnitude - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2 + 2 * (max + min)); - ret_val.add(xs); - ret_val.add(ys); - float[] altx = null; - - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, xs, ys); } - */ - - // add the extra left-wrap polys - for (int i = 1; i <= min; i++) { - altx = new float[xs.length]; - xadj = i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - // add the extra right-wrap polys - for (int i = 1; i <= max; i++) { - altx = new float[xs.length]; - xadj = -i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - return ret_val; - }// _forwardPoly() - - @Override - protected ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - // TODO: copied from Cylindrical. may need to change. - int n, k, flag = 0, min = 0, max = 0, xp, xadj = 0; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // handle complicated line in specific routines - if (isComplicatedLineType(ltype)) { - return doPolyDispatch(rawllpts, ltype, nsegs, isFilled); - } - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // more temp objects to limit number of new objects that needs to be - // created - UTMPoint tempUtm = new UTMPoint(); - LatLonPoint tempLL = new LatLonPoint.Double(); - - // forward project the first point - tempLL.setLatLon(rawllpts[0], rawllpts[1], true); - forward(tempLL, temp, tempUtm); - // forward(rawllpts[0], rawllpts[1], temp, true, tempUtm); - xp = temp.x; - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - tempLL.setLatLon(rawllpts[k], rawllpts[k + 1], true); - forward(tempLL, temp, tempUtm); - // forward(rawllpts[k], rawllpts[k + 1], temp, true, tempUtm); - xs[n] = temp.x; - ys[n] = temp.y; - // segment crosses longitude along screen edge - if (Math.abs(xp - xs[n]) >= half_world) { - flag += (xp < xs[n]) ? -1 : 1;// inc/dec the wrap - // count - min = (flag < min) ? flag : min;// left wrap count - max = (flag > max) ? flag : max;// right wrap count - xadj = flag * world.x;// adjustment to x coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = temp.x;// save previous unshifted x coordinate - if (flag != 0) { - xs[n] += xadj;// adjust x coordinates - } - } - min *= -1;// positive magnitude - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2 + 2 * (max + min)); - ret_val.add(xs); - ret_val.add(ys); - float[] altx = null; - - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, xs, ys); } - */ - - // add the extra left-wrap polys - for (int i = 1; i <= min; i++) { - altx = new float[xs.length]; - xadj = i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - // add the extra right-wrap polys - for (int i = 1; i <= max; i++) { - altx = new float[xs.length]; - xadj = -i * world.x;// shift opposite - for (int j = 0; j < altx.length; j++) { - altx[j] = xs[j] + xadj; - } - ret_val.add(altx); - ret_val.add(ys); - /* - * if (Debug.debugging("proj")) { dumpPoly(rawllpts, altx, ys); } - */ - } - - return ret_val; - } - - /** - * Draw the background for the projection. - * - * @param g - * Graphics2D - * @param paint - * java.awt.Paint to use for the background - */ - public void drawBackground(Graphics2D g, java.awt.Paint paint) { - g.setPaint(paint); - drawBackground(g); - } - - /** - * Assume that the Graphics has been set with the Paint/Color needed, just - * render the shape of the background. - */ - public void drawBackground(Graphics g) { - g.fillRect(0, 0, getWidth(), getHeight()); - } - - public boolean forwardRaw(float[] rawllpts, int rawoff, int[] xcoords, int[] ycoords, - boolean[] visible, int copyoff, int copylen) { - // TODO: copied from Cylindrical. may need a change - Point temp = new Point(); - UTMPoint tempUtm = new UTMPoint(); - LatLonPoint tempLL = new LatLonPoint.Double(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - tempLL.setLatLon(rawllpts[j], rawllpts[j + 1], true); - forward(tempLL, temp, tempUtm); - // forward(rawllpts[j], rawllpts[j + 1], temp, true, tempUtm); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - visible[i] = true; - } - // everything is visible - return true; - } - - public LatLonPoint getLowerRight() { - return inverse(width - 1, height - 1, new LatLonPoint.Double()); - } - - public LatLonPoint getUpperLeft() { - return inverse(0, 0, new LatLonPoint.Double()); - } - - public int getZoneNumber() { - return zoneNumber; - } - - public void setZoneNumber(int zoneNumber) { - this.zoneNumber = zoneNumber; - computeParameters(); - } - - public boolean isNorthern() { - return northern; - } - - public void setNorthern(boolean northern) { - this.northern = northern; - computeParameters(); - } - - public Ellipsoid getEllps() { - return ellps; - } - - public void setEllps(Ellipsoid ellps) { - this.ellps = ellps; - computeParameters(); - } - - /* - * HACK epsilon: skirt the edge of the infinite. If this is too small then - * we get too close to +-INFINITY when we forward project. Tweak this if you - * start getting Infinity or NaN's for forward(). - */ - protected static double epsilon = 0.01f; - - /** - * Sets radian latitude to something sane. This is an abstract function - * since some projections don't deal well with extreme latitudes. - * - * @param lat - * float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - */ - public double normalizeLatitude(double lat) { - if (lat > NORTH_POLE - epsilon) { - return NORTH_POLE - epsilon; - } else if (lat < SOUTH_POLE + epsilon) { - return SOUTH_POLE + epsilon; - } - return lat; - } - - public boolean isPlotable(double lat, double lon) { - // TODO need to figure out how to calculate this - return true; - } - - /** - * Convenience method to create a GCT for this projection. For projections - * that start with lat/lon coordinates, this will return a LatLonGCT. For - * projections that have world coordinates in meters, the GCT will provide a - * way to get to those meter coordinates. For instance, a UTMProjection will - * return a UTMGCT. - * - * @return UTMGCT for current projection - */ - public UTMGCT getGCTForProjection() { - return new UTMGCT(getZoneNumber(), isNorthern() ? 'N' : 'S'); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/UTMProjectionLoader.java b/src/core/src/main/java/com/bbn/openmap/proj/UTMProjectionLoader.java deleted file mode 100644 index f424cdc3b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/UTMProjectionLoader.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.bbn.openmap.proj; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.coords.DatumShiftGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -public class UTMProjectionLoader extends BasicProjectionLoader { - - public static final String ZONE_NUMBER = "zoneNumber"; - - public static final String ZONE_LETTER = "zoneLetter"; - - protected int defaultZoneNumber = 0; - protected char defaultZoneLetter = 'N'; - - public UTMProjectionLoader() { - super(UTMProjection.class, "UTM Projection", "UTM Projection"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - defaultZoneNumber = PropUtils.intFromProperties(props, prefix - + ZONE_NUMBER, defaultZoneNumber); - defaultZoneLetter = PropUtils.charFromProperties(props, prefix - + ZONE_LETTER, defaultZoneLetter); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ZONE_LETTER, "" + defaultZoneLetter); - props.put(prefix + ZONE_NUMBER, Integer.toString(defaultZoneNumber)); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, - props, - UTMProjectionLoader.class, - ZONE_LETTER, - "Zone Letter", - "The UTM Zone Letter (N or S)", - null); - - PropUtils.setI18NPropertyInfo(i18n, - props, - UTMProjectionLoader.class, - ZONE_NUMBER, - "Zone Number", - "The UTM Zone Number", - null); - - return props; - } - - public Projection create(Properties props) throws ProjectionException { - try { - LatLonPoint center = convertToLLP((Point2D) props.get(ProjectionFactory.CENTER)); - float scale = PropUtils.floatFromProperties(props, - ProjectionFactory.SCALE, - 10000000); - int height = PropUtils.intFromProperties(props, - ProjectionFactory.HEIGHT, - 100); - int width = PropUtils.intFromProperties(props, - ProjectionFactory.WIDTH, - 100); - - // TODO I'm thinking that if we have a center lat/lon for the - // projection we can figure out what the zone number and letter are. - // We don't need to pass properties for them. On second thought, - // maybe that should apply only if the defaults aren't set. - - int zone_number = PropUtils.intFromProperties(props, - ZONE_NUMBER, - defaultZoneNumber); - - char zone_letter = PropUtils.charFromProperties(props, - ZONE_LETTER, - defaultZoneLetter); - boolean isnorthern = (zone_letter == 'N'); - String ellipsoidString = props.getProperty(ProjectionFactory.DATUM); - // Assume WGS84 if not specified. - Ellipsoid ellps = Ellipsoid.WGS_84; - if (ellipsoidString != null) { - ellps = Ellipsoid.getByName(ellipsoidString); - } - GeoProj proj = new UTMProjection(center, scale, width, height, zone_number, isnorthern, ellps); - // handle GRS80 as WGS84 as they are almost the same - if ((ellps != null) - && (!(ellps == Ellipsoid.WGS_84) || (ellps == Ellipsoid.GRS_1980))) { - proj = new DatumShiftProjection(proj, new DatumShiftGCT(ellps)); - } - return proj; - } catch (Exception e) { - if (Debug.debugging("proj")) { - Debug.output("UTMProjectionLoader: problem creating UTM projection " - + e.getMessage()); - e.printStackTrace(); - } - } - - throw new ProjectionException("UTMProjectionLoader: problem creating UTM projection"); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/AbstractGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/AbstractGCT.java deleted file mode 100644 index 957632dfd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/AbstractGCT.java +++ /dev/null @@ -1,45 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: AbstractGCT.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/01/29 22:04:13 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.OMComponent; - -public abstract class AbstractGCT extends OMComponent implements GeoCoordTransformation { - - public Point2D forward(double lat, double lon) { - return forward(lat, lon, new Point2D.Double()); - } - - public abstract Point2D forward(double lat, double lon, Point2D ret); - - public LatLonPoint inverse(double x, double y) { - return inverse(x, y, new LatLonPoint.Double()); - } - - public abstract LatLonPoint inverse(double x, double y, LatLonPoint ret); - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/AxisOrder.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/AxisOrder.java deleted file mode 100644 index 1d1aa4d4d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/AxisOrder.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.bbn.openmap.proj.coords; - -public enum AxisOrder { - - eastBeforeNorth, northBeforeEast; - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/BoundingBox.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/BoundingBox.java deleted file mode 100644 index d699f344e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/BoundingBox.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.bbn.openmap.proj.coords; - -/** - * A Bounding Box. - */ -public class BoundingBox { - - private double minx; - - private double miny; - - private double maxx; - - private double maxy; - - public BoundingBox(double minx, double miny, double maxx, double maxy) { - this.minx = minx; - this.miny = miny; - this.maxx = maxx; - this.maxy = maxy; - } - - public double getMinX() { - return minx; - } - - public double getMinY() { - return miny; - } - - public double getMaxX() { - return maxx; - } - - public double getMaxY() { - return maxy; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/CoordinateReferenceSystem.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/CoordinateReferenceSystem.java deleted file mode 100644 index 58f7225dd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/CoordinateReferenceSystem.java +++ /dev/null @@ -1,298 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.LLXYLoader; -import com.bbn.openmap.proj.LambertConformalLoader; -import com.bbn.openmap.proj.MercatorLoader; -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.ProjectionLoader; -import com.bbn.openmap.proj.UTMProjectionLoader; - -public class CoordinateReferenceSystem { - - private String code; - - private GeoCoordTransformation coordTransform; - - private ProjectionLoader projLoader; - - private BoundingBox boundingBox; - - private String projLoaderClassName; - - private Ellipsoid ellipsoid = Ellipsoid.WGS_84; - - private Properties defaultProjectionParameters = new Properties(); - - private AxisOrder axisOrder; - - protected static final Map crss = - Collections.synchronizedMap(new TreeMap()); - - static { - // unprojected wgs84 - addCrs(new CoordinateReferenceSystem("EPSG:4326", LatLonGCT.INSTANCE, LLXYLoader.class, Ellipsoid.WGS_84, null, null, - AxisOrder.northBeforeEast)); - addCrs(new CoordinateReferenceSystem("CRS:84", LatLonGCT.INSTANCE, LLXYLoader.class, Ellipsoid.WGS_84)); - - // unprojected ED50 - addCrs(new CoordinateReferenceSystem("EPSG:4230", new DatumShiftGCT(Ellipsoid.INTERNATIONAL), LLXYLoader.class, - Ellipsoid.INTERNATIONAL)); - - // Spherical Mercator for overlaying with Google Maps - // http://trac.openlayers.org/wiki/SphericalMercator - addCrs(new CoordinateReferenceSystem("EPSG:900913", new MercatorMeterGCT(Planet.wgs84_earthEquatorialRadiusMeters_D, - Planet.wgs84_earthEquatorialRadiusMeters_D), - MercatorLoader.class, Ellipsoid.WGS_84)); - addCrs(new CoordinateReferenceSystem("EPSG:3857", new MercatorMeterGCT(Planet.wgs84_earthEquatorialRadiusMeters_D, - Planet.wgs84_earthEquatorialRadiusMeters_D), - MercatorLoader.class, Ellipsoid.WGS_84)); - - addUtms(); - - // Estonian Coordinate System of 1997 - EPSG:3301 - // http://spatialreference.org/ref/epsg/3301/ - // bounding box values from a national WMS from Estonian - addLcc("EPSG:3301", Ellipsoid.GRS_1980, 59.33333333333334, 58d, 57.51755393055556d, 24d, 500000, 6375000, - new BoundingBox(300000, 6.3e+06, 800000, 6.7e+06), AxisOrder.northBeforeEast); - - // SWEREF 99 TM (EPSG:3006) - // http://spatialreference.org/ref/epsg/3006/ - addUtm("EPSG:3006", 33, 'N', Ellipsoid.GRS_1980, - new BoundingBox(218128.7031d, 6126002.9379d, 1083427.2970d, 7692850.9468d), AxisOrder.northBeforeEast); - - // ETRS89 / ETRS-TM35FIN - // http://spatialreference.org/ref/epsg/3067/ - addUtm("EPSG:3067", 35, 'N', Ellipsoid.GRS_1980, new BoundingBox(50199.4814d, 6582464.0358d, 761274.6247d, 7799839.8902d)); - } - - private static void addLcc(String code, Ellipsoid ellps, double sp1, double sp2, double refLat, double centMeri, - double falseEast, double falseNorth, BoundingBox bbox, AxisOrder axisOrder) { - - Properties props = new Properties(); - props.put(LambertConformalLoader.StandardParallelOneProperty, Double.toString(sp1)); - props.put(LambertConformalLoader.StandardParallelTwoProperty, Double.toString(sp2)); - props.put(LambertConformalLoader.ReferenceLatitudeProperty, Double.toString(refLat)); - props.put(LambertConformalLoader.CentralMeridianProperty, Double.toString(centMeri)); - props.put(LambertConformalLoader.FalseEastingProperty, Double.toString(falseEast)); - props.put(LambertConformalLoader.FalseNorthingProperty, Double.toString(falseNorth)); - props.put(ProjectionFactory.DATUM, ellps); - props.put(ProjectionFactory.CENTER, new LatLonPoint.Double(refLat, centMeri)); - - addCrs(new CoordinateReferenceSystem(code, new LambertConformalGCT(props), LambertConformalLoader.class, ellps, props, - bbox, axisOrder)); - } - - public static void addCrs(CoordinateReferenceSystem crs) { - crss.put(crs.getCode(), crs); - } - - private static void addUtms() { - for (int zone = 1; zone <= 60; zone++) { - - String zoneCode = String.valueOf(zone); - while (zoneCode.length() < 2) { - zoneCode = "0" + zoneCode; - } - - // wgs84 utm - addUtm("EPSG:326" + zoneCode, zone, 'N', Ellipsoid.WGS_84, null); - addUtm("EPSG:327" + zoneCode, zone, 'S', Ellipsoid.WGS_84, null); - - // ed50 utm - if ((zone >= 28) && (zone <= 38)) { - addUtm("EPSG:230" + zoneCode, zone, 'N', Ellipsoid.INTERNATIONAL, null); - } - - // ETRS89 utm - if ((zone >= 28) && (zone <= 38)) { - addUtm("EPSG:258" + zoneCode, zone, 'N', Ellipsoid.GRS_1980, null); - } - - } - } - - private static void addUtm(String epsg, int zone_number, char zone_letter, Ellipsoid ellps, BoundingBox bbox) { - addUtm(epsg, zone_number, zone_letter, ellps, bbox, AxisOrder.eastBeforeNorth); - } - - private static void addUtm(String epsg, int zone_number, char zone_letter, Ellipsoid ellps, BoundingBox bbox, - AxisOrder axisOrder) { - // some properties for the projection loader - Properties projProps = new Properties(); - projProps.put(UTMProjectionLoader.ZONE_NUMBER, Integer.toString(zone_number)); - projProps.put(UTMProjectionLoader.ZONE_LETTER, Character.toString(zone_letter)); - UTMGCT utmgct = new UTMGCT(zone_number, zone_letter); - utmgct.setEllipsoid(ellps); - - GeoCoordTransformation gct = utmgct; - - // add datum shift for non-wgs84/grs80 - if (!((ellps == Ellipsoid.WGS_84) || (ellps == Ellipsoid.GRS_1980))) { - DatumShiftGCT egct = new DatumShiftGCT(ellps); - gct = new MultiGCT(new GeoCoordTransformation[] { - egct, - utmgct - }); - } - - addCrs(new CoordinateReferenceSystem(epsg, gct, UTMProjectionLoader.class, ellps, projProps, bbox, axisOrder)); - } - - public CoordinateReferenceSystem(String code, GeoCoordTransformation coordConverter, Class projLoaderClass, - Ellipsoid ellipsoid) { - this.code = code; - this.coordTransform = coordConverter; - this.projLoaderClassName = projLoaderClass.getName(); - this.ellipsoid = ellipsoid; - this.axisOrder = AxisOrder.eastBeforeNorth; - - defaultProjectionParameters.put(ProjectionFactory.DATUM, ellipsoid); - } - - public CoordinateReferenceSystem(String code, GeoCoordTransformation coordConverter, Class projLoaderClass, - Ellipsoid ellipsoid, Properties projectionParameters, BoundingBox boundingBox, - AxisOrder axisOrder) { - this(code, coordConverter, projLoaderClass, ellipsoid); - - if (projectionParameters != null) { - defaultProjectionParameters.putAll(projectionParameters); - } - this.boundingBox = boundingBox; - this.axisOrder = axisOrder; - } - - public static CoordinateReferenceSystem getForCode(String code) { - CoordinateReferenceSystem crs = crss.get(code); - // TODO: handle extra parameters like - // AUTO2:42003,0.3048006096012192,-100,45. See ISO/DIS 19128 wms v1.3.0 - // chapter 6.7.3.4 - // TODO: clone to simplify transformator by not being thread safe? - return crs; - } - - public static Collection getCodes() { - return crss.keySet(); - } - - protected ProjectionLoader projectionLoader() { - - if (projLoader != null) { - return projLoader; - } - - try { - Class cl = Class.forName(projLoaderClassName); - Object o = cl.newInstance(); - projLoader = (ProjectionLoader) o; - return projLoader; - } catch (ClassNotFoundException e) { - throw new IllegalStateException(e.getMessage()); - } catch (InstantiationException e) { - throw new IllegalStateException(e.getMessage()); - } catch (IllegalAccessException e) { - throw new IllegalStateException(e.getMessage()); - } - - } - - public GeoProj createProjection(Properties overrideProjectionParameters) { - Properties projectionParameters = new Properties(); - projectionParameters.putAll(defaultProjectionParameters); - projectionParameters.putAll(overrideProjectionParameters); - return (GeoProj) projectionLoader().create(projectionParameters); - } - - /** - * Return a EPSG code like "EPSG:4326" - * - * @return EPSG code - */ - public String getCode() { - return code; - } - - /** - * Return the bounding box of this coordinate system or null if the bounding - * box is not defined. - */ - public BoundingBox getBoundingBox() { - return boundingBox; - } - - public AxisOrder getAxisOrder() { - return axisOrder; - } - - public void prepareProjection(GeoProj proj) { - // TODO: do we need this?? - proj.setPlanetRadius(ellipsoid.radius); - } - - /** - * Convert the given (projected) coordinate in the CRS to a LatLonPoint - * without respect for axis order. - * - * @param x - * @param y - * @return LatLonPoint from inverse projected x, y coordinate - */ - public LatLonPoint inverse(double x, double y) { - return coordTransform.inverse(x, y); - } - - /** - * Convert the given (projected) coordinate in the CRS to a LatLonPoint. If - * the useAxisOrder parameter is true, then the - * {@link CoordinateReferenceSystem}s {@link AxisOrder} will be used. - * - * @param x - * @param y - * @return LatLonPoint from inverse projected x, y coordinate - */ - public LatLonPoint inverse(double x, double y, boolean useAxisOrder) { - if (useAxisOrder && (getAxisOrder() == AxisOrder.northBeforeEast)) { - return coordTransform.inverse(y, x); - } - return coordTransform.inverse(x, y); - } - - public Point2D forward(double lat, double lon) { - return coordTransform.forward(lat, lon); - } - - public Point2D forward(double lat, double lon, boolean useAxisOrder) { - Point2D p = coordTransform.forward(lat, lon); - if (useAxisOrder && (getAxisOrder() == AxisOrder.northBeforeEast)) { - double x = p.getX(); - double y = p.getY(); - p.setLocation(y, x); - } - return p; - } - - public int hashCode() { - return getCode().hashCode(); - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - CoordinateReferenceSystem o = (CoordinateReferenceSystem) obj; - return getCode().equals(o.getCode()); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/DMSLatLonPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/DMSLatLonPoint.java deleted file mode 100644 index 588e18afa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/DMSLatLonPoint.java +++ /dev/null @@ -1,399 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/DMSLatLonPoint.java,v $ -// $RCSfile: DMSLatLonPoint.java,v $ -// $Revision: 1.7 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.util.Assert; - -/** - * Encapsulates a latitude and longitude coordinate in degrees, minutes and - * seconds as well as the sign. - *

- * - * Original code contributed by Colin Mummery (colin_mummery@yahoo.com) - */ -public class DMSLatLonPoint implements Cloneable { - - private final static double MINUTE = 1 / 60.0; - private final static double SECOND = 1 / 3600.0; - - /** - * Indicates if the latitude is negative, the actual int values are always - * positive. - */ - public boolean lat_isnegative; - /** - * The number of degrees in the latitude. - */ - public int lat_degrees; - /** - * The number of minutes in the latitude. - */ - public int lat_minutes; - /** - * The number of seconds in the latitude. - */ - public double lat_seconds; - - /** - * Indicates if the longitude is negative, the actual int values are always - * positive. - */ - public boolean lon_isnegative; - /** - * The number of degrees in the longitude. - */ - public int lon_degrees; - /** - * The number of minutes in the longitude. - */ - public int lon_minutes; - /** - * The number of seconds in the longitude. - */ - public double lon_seconds; - - /** - * Construct a default LatLonPoint with zero values. - */ - public DMSLatLonPoint() { - } - - /** - * Create DMSLatLonPoint where lat_degrees and lon_degrees are signed, - * negative for South and West. - * - * @param lat_degrees - * @param lat_minutes - * @param lat_seconds - * @param lon_degrees - * @param lon_minutes - * @param lon_seconds - */ - public DMSLatLonPoint(int lat_degrees, int lat_minutes, double lat_seconds, int lon_degrees, - int lon_minutes, double lon_seconds) { - this(lat_degrees < 0, Math.abs(lat_degrees), lat_minutes, lat_seconds, lon_degrees < 0, Math.abs(lon_degrees), lon_minutes, lon_seconds); - } - - /** - * Construct a DMSLatLonPoint from raw int lat/lon. All parameters are - * checked for their validity. - * - * @param lat_isnegative boolean value indicating the sign of the latitude - * @param lat_degrees integer number of degrees in latitude - * @param lat_minutes integer number of minutes in latitude - * @param lat_seconds float number of seconds in latitude - * @param lon_isnegative boolean value indicating the sign of the longitude - * @param lon_degrees integer number of degrees in longitude - * @param lon_minutes integer number of minutes in longitude - * @param lon_seconds float number of seconds in longitude - */ - public DMSLatLonPoint(boolean lat_isnegative, int lat_degrees, int lat_minutes, - double lat_seconds, boolean lon_isnegative, int lon_degrees, int lon_minutes, - double lon_seconds) { - - this.lat_isnegative = lat_isnegative; - this.lat_degrees = (int) LatLonPoint.normalizeLatitude(lat_degrees); - if (this.lat_degrees < 0) { - // can't have a negative value - this.lat_degrees = -this.lat_degrees; - } - this.lat_minutes = normalize_value(lat_minutes); - this.lat_seconds = normalize_value(lat_seconds); - - this.lon_isnegative = lon_isnegative; - this.lon_degrees = (int) LatLonPoint.wrapLongitude(lon_degrees); - if (this.lon_degrees < 0) { - // can't have a negative value - this.lon_degrees = -this.lon_degrees; - } - this.lon_minutes = normalize_value(lon_minutes); - this.lon_seconds = normalize_value(lon_seconds); - } - - /** - * Create DMSLatLonPoint from different notation - * - * @param lat_degrees integer degrees for lat, signed negative for South - * @param lat_minutesDotSeconds positive decimal minutes.seconds fraction - * @param lon_degrees integer degrees for lon, signed negative for West - * @param lon_minutesDotSeconds positive decimal minutes.seconds fraction - */ - public DMSLatLonPoint(int lat_degrees, double lat_minutesDotSeconds, int lon_degrees, - double lon_minutesDotSeconds) { - this.lat_isnegative = lat_degrees < 0; - this.lat_degrees = (int) LatLonPoint.normalizeLatitude(Math.abs(lat_degrees)); - - double lat_minDSec = Math.abs(lat_minutesDotSeconds); - this.lat_minutes = normalize_value((int) lat_minDSec); - this.lat_seconds = normalize_value((lat_minDSec - this.lat_minutes) * 60.0); - - this.lon_isnegative = lon_degrees < 0; - this.lon_degrees = (int) LatLonPoint.wrapLongitude(Math.abs(lon_degrees)); - - double lon_minDSec = Math.abs(lon_minutesDotSeconds); - this.lon_minutes = normalize_value((int) lon_minDSec); - this.lon_seconds = normalize_value((lon_minDSec - this.lon_minutes) * 60.0); - } - - /** - * Constructs a new DMSLatLonPoint given a LatLonPoint instance - * - * @param llp A LatLonPoint instance - */ - public DMSLatLonPoint(LatLonPoint llp) { - getDMSLatLonPoint(llp, this); - } - - /** - * A static method which takes an instance of a LatLongPoint and sets the - * correct values into an instance of DMSLatLonPoint. - * - * @param llp A LatLonPoint instance. - * @param dllp A DMSLatLonPoint instance. - */ - static void getDMSLatLonPoint(LatLonPoint llp, DMSLatLonPoint dllp) { - - // set everything to zero - dllp.lat_degrees = 0; - dllp.lat_minutes = 0; - dllp.lat_seconds = 0f; - dllp.lat_isnegative = false; - dllp.lon_degrees = 0; - dllp.lon_minutes = 0; - dllp.lon_seconds = 0f; - dllp.lon_isnegative = false; - - // First do the latitude - double val = llp.getY(); - - if (val < 0) { - dllp.lat_isnegative = true; - val = -val; - } // remove the sign but remember it - - dllp.lat_degrees = (int) Math.floor((double) val); - - if (val >= SECOND) { - // If it's less then a second then we assume zero...I - // guess - // we could round up - int deg = (int) val; - // take out the whole degrees - double rem = val - deg; - // Do we have anything left to convert to a minute - if (rem >= MINUTE) { // get the minutes - int min = (int) (rem * 60); - dllp.lat_minutes = min; - rem -= (min * MINUTE); - } - // Any seconds left? - if (rem >= SECOND) { // get the seconds - double sec = (rem * 3600.0); - dllp.lat_seconds = sec; - rem -= (sec * SECOND); - } - } else { - dllp.lat_isnegative = false; // we don't want a negative - // zero - } - - // Next repeat the code for longitude, easiest just to repeat - // it - val = llp.getX(); - if (val < 0) { - dllp.lon_isnegative = true; - val = -val; - } - - dllp.lon_degrees = (int) Math.floor((double) val); - - if (val >= SECOND) { - int deg = (int) val; - double rem = val - deg; - if (rem >= MINUTE) { - int min = (int) (rem * 60.0); - dllp.lon_minutes = min; - rem -= (min * MINUTE); - } - if (rem >= SECOND) { - double sec = rem * 3600.0; - dllp.lon_seconds = sec; - rem -= (sec * SECOND); - } - } else { - dllp.lon_isnegative = false; - } - } - - /** - * Return a LatLonPoint from this DMSLatLonPoint. The LatLonPoint is - * allocated here. - * - * @return LatLonPoint, full of decimal degrees. - */ - public LatLonPoint getLatLonPoint() { - return getLatLonPoint(null); - } - - /** - * Return a LatLonPoint from this DMSLatLonPoint. The LatLonPoint is - * allocated here if the llp is null. If it's not null, then the llp is - * loaded with the proper values. - * - * @param llp the LatLonPoint to load up. - * @return LatLonPoint, full of decimal degrees. - */ - public LatLonPoint getLatLonPoint(LatLonPoint llp) { - double lat = getDecimalLatitude(); - double lon = getDecimalLongitude(); - if (llp == null) { - return new LatLonPoint.Double(lat, lon); - } else { - llp.setLatLon(lat, lon); - return llp; - } - } - - /** - * Returns the latitude as decimal degrees. - * - * @return A float value for the latitude - */ - public double getDecimalLatitude() { - double val = (lat_degrees + (lat_minutes * MINUTE) + (lat_seconds * SECOND)); - return (lat_isnegative) ? -val : val; - } - - /** - * Returns the longitude as decimal degrees. - * - * @return A float value for the longitude - */ - public double getDecimalLongitude() { - double val = (lon_degrees + (lon_minutes * MINUTE) + (lon_seconds * SECOND)); - return (lon_isnegative) ? -val : val; - } - - /** - * Returns a string representation of the object. - * - * @return String representation - */ - public String toString() { - return "DMSLatLonPoint[lat_isnegative = " + lat_isnegative + ", lat_degrees = " - + lat_degrees + ", lat_minutes = " + lat_minutes + ", lat_seconds = " + lat_seconds - + ", lon_isnegative = " + lon_isnegative + ", lon_degrees = " + lon_degrees - + ", lon_minutes = " + lon_minutes + ", lon_seconds = " + lon_seconds + "]"; - } - - /** - * Set DMSLatLonPoint. Sets the current instance values to be the same as - * another DMSLatLonPoint instance. - * - * @param llpt DMSLatLonPoint - */ - public void setDMSLatLon(DMSLatLonPoint llpt) { - lat_isnegative = llpt.lat_isnegative; - lat_degrees = llpt.lat_degrees; - lat_minutes = llpt.lat_minutes; - lat_seconds = llpt.lat_seconds; - lon_isnegative = llpt.lon_isnegative; - lon_degrees = llpt.lon_degrees; - lon_minutes = llpt.lon_minutes; - lon_seconds = llpt.lon_seconds; - } - - /** - * Clone the DMSLatLonPoint. - * - * @return clone - */ - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - Assert.assertExp(false, "DMSLatLonPoint: internal error!"); - return null;// statement not reached - } - } - - /** - * Determines whether two DMSLatLonPoints are exactly equal. - * - * @param obj Object - * @return boolean - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DMSLatLonPoint pt = (DMSLatLonPoint) obj; - return (pt.lat_isnegative == lat_isnegative && pt.lat_degrees == lat_degrees - && pt.lat_minutes == lat_degrees && pt.lat_seconds == lat_seconds - && pt.lon_isnegative == lon_isnegative && pt.lon_degrees == lon_degrees - && pt.lon_minutes == lon_minutes && pt.lon_seconds == lon_seconds); - } - - /** - * Sets the minutes and seconds to something sane. - * - * @param val an int value for the minutes or seconds - * @return int value normalized - */ - final public static int normalize_value(int val) { - val %= 60; - if (val < 0) { - val += 60; - } - return val; - } - - /** - * Sets the minutes and seconds to something sane. - * - * @param val an double value for the minutes or seconds - * @return float value normalized - */ - final public static double normalize_value(double val) { - val %= 60f; - if (val < 0f) { - val += 60f; - } - return val; - } - - /** - * Generate a hash value for the point. Hash by spreading the values across - * a 32 bit int, ignoring the sign allow 8 bits (max 255) for degrees, 7 - * bits (max 127) for (minutes + seconds) so the total is 30 bits. - * - * @return An int hash value representing the point. - */ - public int hashCode() { - return (lat_degrees | lon_degrees << 8 | (lat_minutes + (int) lat_seconds) << 16 - | (lon_minutes + (int) lon_seconds) << 23); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/DatumShiftGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/DatumShiftGCT.java deleted file mode 100644 index bd28c7162..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/DatumShiftGCT.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Ellipsoid; - -/** - * A {@link CoordinateReferenceSystem} to convert a latlon in a given - * {@link Ellipsoid} to/from wgs84. - *

- * The {@link LatLonPoint}-side is in wgs84 and the {@link Point2D}-side in - * the other {@link Ellipsoid} given by the constructor. - *

- * Datum shifting is performed using {@link ECEFPoint} - */ -public class DatumShiftGCT extends AbstractGCT { - - private Ellipsoid ellip; - - private HelmertTransformation eceftransf; - private HelmertTransformation eceftransfInverse; - - private ECEFPoint ecef = new ECEFPoint(); - - public DatumShiftGCT(Ellipsoid ellip) { - this.ellip = ellip; - - eceftransf = HelmertTransformation.find(Ellipsoid.WGS_84, ellip); - eceftransfInverse = HelmertTransformation.find(ellip, Ellipsoid.WGS_84); - } - - /** - * Convert from a latlon in wgs84 to the {@link Ellipsoid} of this instance - */ - public synchronized Point2D forward(double lat, double lon, Point2D ret) { - ecef.setLatLon(lat, lon, Ellipsoid.WGS_84); - eceftransf.apply(ecef); - return ecef.getLatLon(ellip, ret); - } - - /** - * Convert from a latlon in the {@link Ellipsoid} of this instance to wgs84 - */ - public synchronized LatLonPoint inverse(double x, double y, LatLonPoint ret) { - ecef.setLatLon(y, x, ellip); - eceftransfInverse.apply(ecef); - return ecef.getLatLon(ret); - } - - public String toString() { - return getClass().getSimpleName() + "(" + ellip.name + ")"; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/ECEFPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/ECEFPoint.java deleted file mode 100644 index 60f620294..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/ECEFPoint.java +++ /dev/null @@ -1,384 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/ECEFPoint.java,v $ -// $RCSfile: ECEFPoint.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -// ********************************************************************** -// -// Based on coordinate conversion utilities in GeoTools -// -// Note: Height calculations are present, but commented out. -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.util.HashCodeUtil; -import com.bbn.openmap.util.MoreMath; - -/** - * From: http://www.commlinx.com.au/Datum%20Transformation%20Description.html : - *

- * The Cartesian coordinate frame of reference used in GPS/GLONASS is called - * Earth-Centered, Earth-Fixed (ECEF). ECEF uses three-dimensional XYZ - * coordinates (in meters) to describe the location of a GPS user or satellite. - * The term "Earth- Centered" comes from the fact that the origin of the axis - * (0,0,0) is located at the mass center of gravity (determined through years of - * tracking satellite trajectories). The term "Earth-Fixed" implies that the - * axes are fixed with respect to the earth (that is, they rotate with the - * earth). The Z-axis pierces the North Pole, and the XY-axis defines the - * equatorial plane (Figure 1). - *

- * - * ECEF coordinates are expressed in a reference system that is related to - * mapping representations. Because the earth has a complex shape, a simple, yet - * accurate, method to approximate the earth's shape is required. The use of a - * reference ellipsoid allows for the conversion of the ECEF coordinates to the - * more commonly used geodetic-mapping coordinates of Latitude, Longitude, and - * Altitude (LLA). - */ -public class ECEFPoint { - - protected static double EQUIVALENT_TOLERANCE = 0.001; - - protected double x_ = 0.0; - protected double y_ = 0.0; - protected double z_ = 0.0; - - /** - * Construct a default ECEFPoint. - */ - public ECEFPoint() { - } - - /** - * Construct an ECEFPoint - */ - public ECEFPoint(double x, double y, double z) { - setECEF(x, y, z); - } - - /** - * Construct an ECEFPoint - * - * @param pt ECEFPoint - */ - public ECEFPoint(ECEFPoint pt) { - x_ = pt.x_; - y_ = pt.y_; - z_ = pt.z_; - } - - /** - * Construct an ECEFPoint - */ - public ECEFPoint(float x, float y, float z) { - this((double) x, (double) y, (double) z); - } - - public static ECEFPoint LLtoECEF(LatLonPoint llpoint) { - return LLtoECEF(llpoint, new ECEFPoint()); - } - - public static ECEFPoint LLtoECEF(LatLonPoint llpoint, ECEFPoint ecef) { - if (ecef == null) { - ecef = new ECEFPoint(); - } - - ecef.setLatLon(llpoint); - return ecef; - } - - /** - * Returns a string representation of the object. - * - * @return String representation - */ - public String toString() { - return "ECEFPoint[x=" + x_ + ",y=" + y_ + ",z=" + z_ + "]"; - } - - /** - * Set x. - */ - public void setx(double x) { - x_ = x; - } - - /** - * Set y. - */ - public void sety(double y) { - y_ = y; - } - - /** - * Set z. - */ - public void setz(double z) { - z_ = z; - } - - /** - * Set x y z. - */ - public void setECEF(double x, double y, double z) { - x_ = x; - y_ = y; - z_ = z; - } - - /** - * Set ECEFPoint. - */ - public void setECEF(ECEFPoint pt) { - x_ = pt.x_; - y_ = pt.y_; - z_ = pt.z_; - } - - /** - * Get x - */ - public double getx() { - return x_; - } - - /** - * Get y - */ - public double gety() { - return y_; - } - - /** - * Get z - */ - public double getz() { - return z_; - } - - /** - * Determines whether two ECEFPoints are equal. - * - * @param obj Object - * @return Whether the two points are equal - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ECEFPoint pt = (ECEFPoint) obj; - return (MoreMath.approximately_equal(x_, pt.x_, EQUIVALENT_TOLERANCE) - && MoreMath.approximately_equal(y_, pt.y_, EQUIVALENT_TOLERANCE) && MoreMath.approximately_equal(z_, pt.z_, - EQUIVALENT_TOLERANCE)); - } - - /** - * Write object. - * - * @param s DataOutputStream - */ - public void write(DataOutputStream s) - throws IOException { - // Write my information - s.writeDouble(x_); - s.writeDouble(y_); - s.writeDouble(z_); - } - - /** - * Read object. - * - * @param s DataInputStream - */ - public void read(DataInputStream s) - throws IOException { - setECEF(s.readDouble(), s.readDouble(), s.readDouble()); - } - - /** - * Set an ECEFPoint from a LatLonPoint - * - * @param pt LatLonPoint - */ - public void setLatLon(LatLonPoint pt) { - setLatLon(pt.getY(), pt.getX(), Ellipsoid.WGS_84); - } - - /** - * Set an ECEFPoint from a Lat, Lon - */ - public void setLatLon(float lat, float lon) { - setLatLon(lat, lon, Ellipsoid.WGS_84); - } - - /** - * Set an ECEFPoint from a Lat, Lon - */ - public void setLatLon(double lat, double lon, Ellipsoid ellip) { - - final double a = ellip.radius; // semimajor (meters) - final double b = ellip.polarRadius; // semiminor (meters) - final double a2 = a * a; - final double b2 = b * b; - final double e2 = (a2 - b2) / a2; - - final double L = Math.toRadians(lon); // Longitude - final double P = Math.toRadians(lat); // Latitude - final double h = 0; // Height above the ellipsoid (m) - - final double cosLat = Math.cos(P); - final double sinLat = Math.sin(P); - final double rn = a / Math.sqrt(1 - e2 * (sinLat * sinLat)); - - final double x = (rn + h) * cosLat * Math.cos(L); // X: Toward - // prime - // meridian - final double y = (rn + h) * cosLat * Math.sin(L); // Y: Toward - // East - final double z = (rn * (1 - e2) + h) * sinLat; // Z: Toward - // North - - this.setECEF(x, y, z); - } - - /** - * Return a LatLonPoint in WGS 84 - */ - public LatLonPoint getLatLon() { - return getLatLon(new LatLonPoint.Double()); - } - - /** - * Return a LatLonPoint in WGS 84 - */ - public LatLonPoint getLatLon(LatLonPoint instance) { - Point2D p = getLatLon(Ellipsoid.WGS_84, null); - instance.setLatLon(p.getY(), p.getX()); - return instance; - } - - /** - * Return a Point2D in the given {@link Ellipsoid} with longitude as x and - * latitude as y - */ - public Point2D getLatLon(Ellipsoid ellip, Point2D ret) { - - if (ret == null) { - ret = new Point2D.Double(); - } - - final double a = ellip.radius; // semimajor (meters) - final double b = ellip.polarRadius; // semiminor (meters) - final double a2 = a * a; - final double b2 = b * b; - final double e2 = (a2 - b2) / a2; - final double ep2 = (a2 - b2) / b2; - - /** - * Cosine of 67.5 degrees. - */ - // final double COS_67P5 = 0.38268343236508977; - - /** - * Toms region 1 constant. - */ - final double AD_C = 1.0026000; - - final double x = x_; // Toward prime meridian - final double y = y_; // Toward East - final double z = z_; // Toward North - - // Note: The Java version of 'atan2' work correctly for x==0. - // No need for special handling like in the C version. - // No special handling neither for latitude. Formulas - // below are generic enough, considering that 'atan' - // work correctly with infinities (1/0). - - // Note: Variable names follow the notation used in Toms, Feb - // 1996 - final double W2 = x * x + y * y; // square of distance from Z - // axis - final double W = Math.sqrt(W2); // distance from Z axis - final double T0 = z * AD_C; // initial estimate of vertical - // component - final double S0 = Math.sqrt(T0 * T0 + W2); // initial estimate - // of horizontal - // component - final double sin_B0 = T0 / S0; // sin(B0), B0 is estimate of - // Bowring aux variable - final double cos_B0 = W / S0; // cos(B0) - final double sin3_B0 = sin_B0 * sin_B0 * sin_B0; // cube of - // sin(B0) - final double T1 = z + b * ep2 * sin3_B0; // corrected estimate - // of vertical - // component - final double sum = W - a * e2 * (cos_B0 * cos_B0 * cos_B0); // numerator - // of - // cos(phi1) - final double S1 = Math.sqrt(T1 * T1 + sum * sum); // corrected - // estimate - // of - // horizontal - // component - final double sin_p1 = T1 / S1; // sin(phi1), phi1 is estimated - // latitude - final double cos_p1 = sum / S1; // cos(phi1) - - final double longitude = Math.toDegrees(Math.atan2(y, x)); - final double latitude = Math.toDegrees(Math.atan(sin_p1 / cos_p1)); - // final double height; - - // if (computeHeight) { - // final double rn = a/Math.sqrt(1-e2*(sin_p1*sin_p1)); // - // Earth radius at location - // if (cos_p1 >= +COS_67P5) height = W / +cos_p1 - rn; - // else if (cos_p1 <= -COS_67P5) height = W / -cos_p1 - rn; - // else height = z / sin_p1 + rn*(e2 - 1.0); - // } - - ret.setLocation(longitude, latitude); - // LatLonPoint ret = new LatLonPoint((float) latitude, (float) longitude); - return ret; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - int result = HashCodeUtil.SEED; - result = HashCodeUtil.hash(result, x_); - result = HashCodeUtil.hash(result, y_); - result = HashCodeUtil.hash(result, z_); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/EnuFrame.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/EnuFrame.java deleted file mode 100644 index 37673a37c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/EnuFrame.java +++ /dev/null @@ -1,307 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/EnuFrame.java,v $ -//$RCSfile: EnuFrame.java,v $ -//$Revision: 1.7 $ -//$Date: 2009/02/25 22:34:04 $ -//$Author: dietrick $ -// -//*********************************************************** - -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.proj.ProjMath; - -/** - * Encapsulates the ENU (East-North-Up) coordinate system. - *

- * I like the idea of hiding the detail of the transformation from the user. The - * user needs no detailed knowledge of mathematics and if we change the - * algorithm, nobody will be affected. - *

- * Author: Robert Hayes - */ -public class EnuFrame { - - /** - * The x component of the coordinate (EAST). - */ - protected float x; - /** - * The y component of the coordinate (NORTH). - */ - protected float y; - /** - * The z component of the coordinate (UP). - */ - protected float z; - - /** - * Construct a default EnuFrame. x,y,z are all set to zero. - */ - public EnuFrame() { - x = 0.0f; - y = 0.0f; - z = 0.0f; - - } - - /** - * Construct a EnuFrame from a ECEF vector and a LatLonPoint. - * - * @param llpt LatLonPoint. - * @param ecefv representing an ecef vector. - */ - public EnuFrame(double[] ecefv, LatLonPoint llpt) { - double lat_ = llpt.getY(); - double lon_ = llpt.getX(); - - double latitude = ProjMath.degToRad(lat_); - double longitude = ProjMath.degToRad(lon_); - - double ecefVector[] = new double[3]; - double enuVector[] = new double[3]; - - ecefVector[0] = ecefv[0]; - ecefVector[1] = ecefv[1]; - ecefVector[2] = ecefv[2]; - - ecef2enu(ecefVector, latitude, longitude, enuVector); - - this.x = (float) enuVector[0]; - this.y = (float) enuVector[1]; - this.z = (float) enuVector[2]; - - } - - /** - * Convert to geocentric frame using a LatLonPoint. - * - * @param llpt - * @return a double of ecef values - */ - public double[] toGeocentricFrame(LatLonPoint llpt) { - double lat_ = (double) llpt.getY(); - double lon_ = (double) llpt.getX(); - - double latitude = ProjMath.degToRad(lat_); - double longitude = ProjMath.degToRad(lon_); - - double enuVector[] = new double[3]; - double ecefVector[] = new double[3]; - - enuVector[0] = this.x; - enuVector[1] = this.y; - enuVector[2] = this.z; - - enu2ecef(ecefVector, latitude, longitude, enuVector); - - return ecefVector; - } - - /** - * Internal conversion routine. - * - * @param ecefVector vector - * @param latitude in radians. - * @param longitude in radians - * @param enuVector vector - */ - public void ecef2enu(double ecefVector[], double latitude, - double longitude, double enuVector[]) { - - double temp[][] = new double[3][3]; - double slat = Math.sin(latitude); - double clat = Math.cos(latitude); - double slon = Math.sin(longitude); - double clon = Math.cos(longitude); - - temp[0][0] = -slon; - temp[0][1] = clon; - temp[0][2] = 0.0; - - temp[1][0] = -clon * slat; - temp[1][1] = -slon * slat; - temp[1][2] = clat; - - temp[2][0] = clon * clat; - temp[2][1] = slon * clat; - temp[2][2] = slat; - - for (int j = 0; j < 3; ++j) { - enuVector[j] = 0.0; - for (int i = 0; i < 3; i++) { - enuVector[j] += temp[j][i] * ecefVector[i]; - } - } - } - - /** - * Internal conversion routine. - * - * @param ecefVector vector - * @param latitude in radians. - * @param longitude in radians - * @param enuVector vector - */ - protected void enu2ecef(double ecefVector[], double latitude, - double longitude, double enuVector[]) { - - double temp[][] = new double[3][3]; - double clat = Math.cos(latitude); - double slat = Math.sin(latitude); - double clon = Math.cos(longitude); - double slon = Math.sin(longitude); - - temp[0][0] = -slon; - temp[0][1] = -clon * slat; - temp[0][2] = clon * clat; - - temp[1][0] = clon; - temp[1][1] = -slon * slat; - temp[1][2] = slon * clat; - - temp[2][0] = 0.0; - temp[2][1] = clat; - temp[2][2] = slat; - - for (int j = 0; j < 3; ++j) { - ecefVector[j] = 0.0; - for (int i = 0; i < 3; i++) { - ecefVector[j] += temp[j][i] * enuVector[i]; - } - } - - } - - /** - * Set x. - * - * @param pX in meters. - */ - public void setX(float pX) { - x = pX; - } - - /** - * Set y. - * - * @param pY in meters. - */ - public void setY(float pY) { - y = pY; - } - - /** - * Set z. - * - * @param pZ in meters. - */ - public void setZ(float pZ) { - z = pZ; - } - - /** - * Set x,y,z. - * - * @param v1 East. - * @param v2 North. - * @param v3 Up. - */ - public void setXYZ(float v1, float v2, float v3) { - x = v1; - y = v2; - z = v3; - } - - /** - * Get x. - * - * @return float x. - */ - public float getX() { - return x; - } - - /** - * Get Y. - * - * @return float y. - */ - public float getY() { - return y; - } - - /** - * Get Z. - * - * @return float z. - */ - public float getZ() { - return z; - } - - /** - * To get the direction as a vector. - * - * @param degrees is heading 0-360 - * @param latitude in degrees. - * @param longitude in degrees. - * @param ecefVector vector - */ - public void toDirectionVector(double degrees, double latitude, - double longitude, double ecefVector[]) { - - double radians = Math.toRadians(degrees) - 360; - double east = Math.sin(radians); - double north = Math.cos(radians); - double lat_ = Math.toRadians(latitude); - double lon_ = Math.toRadians(longitude); - double up = 0.0; - double enuVector[] = { east, north, up }; - this.enu2ecef(ecefVector, lat_, lon_, enuVector); - } - - /* - * public static void main(String[] args) { - * - * double ecefVector[] = new double[3]; double enuVector[] = new double[3]; - * double longitude = Math.toRadians(40.00); double latitude = - * Math.toRadians(-74.50) - * - * EnuFrame test = new EnuFrame(); - * - * ecefVector[0] = 13; ecefVector[1] = 5; ecefVector[2] = 8; - * - * enuVector[0] = 0.e0; enuVector[0] = 0.e0; enuVector[0] = 0.e0; - * - * System.err.println("lat" + latitude + " lon" + longitude); - * //System.err.println("" + ecefVector[0] + ":" + ecefVector[2]+ - * ecefVector[2] ); //System.err.println("" + enuVector[0] + ":" + - * enuVector[2]+ enuVector[2] ); - * // TEST1 test.ecef2enu(ecefVector, latitude, longitude, enuVector); - * System.err.println("TEST1:"); System.err.println("ECEF:" + ecefVector[0] + " : " + - * ecefVector[1]+ " :" +ecefVector[2] ); System.err.println("ENU:" + - * enuVector[0] + " : " + enuVector[1]+ " : "+enuVector[2] ); - * - * ecefVector[0] = 0.e0; ecefVector[1] = 0.e0; ecefVector[2] = 0.e0; // - * TEST2 test.enu2ecef(ecefVector, latitude, longitude, enuVector); - * System.err.println("TEST2:"); System.err.println("ENU:" + enuVector[0] + " : " + - * enuVector[1]+ " : "+enuVector[2] ); System.err.println("ECEF:" + - * ecefVector[0] + " : " + ecefVector[1]+ " :" +ecefVector[2] ); } - */ - -}// class - diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/GeoCoordTransformation.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/GeoCoordTransformation.java deleted file mode 100644 index 09b3080f2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/GeoCoordTransformation.java +++ /dev/null @@ -1,44 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoCoordTransformation.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/01/29 22:04:13 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -/** - * A GeoCoordTransformation is an object that knows how to translate a set of - * coordinates from one coordinate system definition to/from a set of decimal - * degree coordinates. - * - * @author dietrick - */ -public interface GeoCoordTransformation { - Point2D forward(double lat, double lon); - - Point2D forward(double lat, double lon, Point2D ret); - - LatLonPoint inverse(double x, double y); - - LatLonPoint inverse(double x, double y, LatLonPoint ret); -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/HelmertTransformation.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/HelmertTransformation.java deleted file mode 100644 index c63c79c33..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/HelmertTransformation.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.proj.Ellipsoid; - -/** - * Helmert 7-parameter transformation - * - * http://www.posc.org/Epicentre.2_2/DataModel/ExamplesofUsage/eu_cs35.html - * https://www.og.berr.gov.uk/regulation/guidance/co_systems/co_sys_12.htm - * http://www.ogp.org.uk/pubs/373-10.pdf - */ -public class HelmertTransformation { - - private static final int TYPE_POSITION_VECTOR = 1; - - private static final int TYPE_COORDINATE_FRAME = 2; - - /** - * Parameters to transform from WGS84 to ED50 north of 62deg N. - */ - public static final HelmertTransformation WGS84_TO_ED50_N62N = new HelmertTransformation(116.641d, 56.931d, 110.559d, -0.000004327d, -0.000004464d, 0.000004444d, ppmToM(3.520d), TYPE_POSITION_VECTOR); - - /** - * Parameters to transform from ED50 to WGS84 north of 62deg N. - */ - public static final HelmertTransformation ED50_TO_WGS84_N62N = WGS84_TO_ED50_N62N.createReverse(); - - /** - * Parameters to transform from WGS84 to ED50 south of 62deg N. - */ - public static final HelmertTransformation WGS84_TO_ED50_S62N = new HelmertTransformation(90.365d, 101.130d, 123.384d, -0.000001614d, -0.000000373d, -0.000004334d, ppmToM(-1.994d), TYPE_POSITION_VECTOR); - - /** - * Parameters to transform from ED50 to WGS84 south of 62deg N. - */ - private static final HelmertTransformation ED50_TO_WGS84_S62N = WGS84_TO_ED50_S62N.createReverse(); - - private final double dX; - private final double dY; - private final double dZ; - - private final double rX; - private final double rY; - private final double rZ; - - private final double neg_rX; - private final double neg_rY; - private final double neg_rZ; - - private final double m; - - private final int type; - - public static final HelmertTransformation find(Ellipsoid source, Ellipsoid dest) { - // TODO: include projection center - if ((source == Ellipsoid.WGS_84) && (dest == Ellipsoid.INTERNATIONAL)) { - return WGS84_TO_ED50_S62N; - } - if ((source == Ellipsoid.INTERNATIONAL) && (dest == Ellipsoid.WGS_84)) { - return ED50_TO_WGS84_S62N; - } - throw new IllegalArgumentException("Unknown transformation from " + source + " to " + dest); - } - - /** - * - * @param dX - * @param dY - * @param dZ - * @param rX - * @param rY - * @param rZ - * @param m a scale correction factor near 1. see {@link #ppmToM(double)} - * @param type - */ - private HelmertTransformation(double dX, double dY, double dZ, double rX, double rY, double rZ, - double m, int type) { - this.dX = dX; - this.dY = dY; - this.dZ = dZ; - - this.rX = rX; - this.rY = rY; - this.rZ = rZ; - - this.neg_rX = -1d * rX; - this.neg_rY = -1d * rY; - this.neg_rZ = -1d * rZ; - - this.m = m; - - this.type = type; - } - - private HelmertTransformation createReverse() { - // m should be switched around 1. So 0.9 should be 1.1 and so on. - double newM = 2d - m; - return new HelmertTransformation(-1d * dX, -1d * dY, -1d * dZ, neg_rX, neg_rY, neg_rZ, newM, type); - } - - public void apply(ECEFPoint coord) { - double x = coord.x_; - double y = coord.y_; - double z = coord.z_; - - x *= m; - y *= m; - z *= m; - - switch (type) { - case TYPE_POSITION_VECTOR: - x = x + (neg_rZ * y) + (rX * z); - y = (rZ * x) + y + (neg_rX * z); - z = (neg_rY * x) + (rX * y) + z; - break; - case TYPE_COORDINATE_FRAME: - x = x + (rZ * y) + (neg_rX * z); - y = (neg_rZ * x) + y + (rX * z); - z = (rY * x) + (neg_rX * y) + z; - break; - } - - x += dX; - y += dY; - z += dZ; - - coord.setECEF(x, y, z); - } - - /** - * Convert the scale factor from parts per million. - * - * @param ppm scale factor in parts per million - * @return scale correction factor. - */ - private static final double ppmToM(double ppm) { - return 1d + (ppm / 1000000d); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/LambertConformalGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/LambertConformalGCT.java deleted file mode 100644 index eb817ad92..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/LambertConformalGCT.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.LambertConformal; -import com.bbn.openmap.proj.LambertConformalLoader; - -public class LambertConformalGCT extends AbstractGCT { - - private LambertConformal lcc = null; - - public LambertConformalGCT(LambertConformal lcc) { - this.lcc = lcc; - } - - public LambertConformalGCT(Properties props) { - LambertConformalLoader loader = new LambertConformalLoader(); - lcc = (LambertConformal) loader.create(props); - } - - public synchronized Point2D forward(double lat, double lon, Point2D ret) { - return lcc.LLToWorld(lat, lon, ret); - } - - public synchronized LatLonPoint inverse(double x, double y, LatLonPoint ret) { - return (LatLonPoint) lcc.worldToLL(x, y, ret); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonGCT.java deleted file mode 100644 index 3ca95c222..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonGCT.java +++ /dev/null @@ -1,51 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: LatLonGCT.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/01/29 22:04:13 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -public class LatLonGCT implements GeoCoordTransformation { - - public final static LatLonGCT INSTANCE = new LatLonGCT(); - - public Point2D forward(double lat, double lon) { - return forward(lat, lon, new Point2D.Double()); - } - - public Point2D forward(double lat, double lon, Point2D ret) { - ret.setLocation(lon, lat); - return ret; - } - - public LatLonPoint inverse(double x, double y) { - return inverse(x, y, new LatLonPoint.Double()); - } - - public LatLonPoint inverse(double x, double y, LatLonPoint ret) { - ret.setLatLon((float) y, (float) x); - return ret; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonPoint.java deleted file mode 100644 index 14550d3c4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/LatLonPoint.java +++ /dev/null @@ -1,819 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: LatLonPoint.java,v $ -//$Revision: 1.2 $ -//$Date: 2007/12/03 23:39:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.Serializable; - -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.MoreMath; - -/** - * A Point2D representation of LatLonPoints, used integrate with the - * Projections. These LatLonPoints wrap their internal decimal degree values so - * the latitude are between -90 and 90 and the longitudes are between -180 and - * 180. Radian values are precalculated and held within the object. - *

- * - * The LatLonPoint is an abstract class and can't be instantiated directly. You - * need to create a Float or Double version of a LatLonPoint, much like the - * Point2D object. - *

- * - * @author dietrick - */ -public abstract class LatLonPoint extends Point2D implements Cloneable, Serializable { - - /** - * - */ - private static final long serialVersionUID = 4416029542303298672L; - public final static double NORTH_POLE = 90.0; - public final static double SOUTH_POLE = -NORTH_POLE; - public final static double DATELINE = 180.0; - public final static double LON_RANGE = 360.0; - - protected LatLonPoint() { - } - - /** - * Factory method that will create a LatLonPoint.Float from a Point2D - * object. If pt2D is already a LatLonPoint.Float object, it is simply - * returned. - * - * @param pt2D - * @return a LatLonPoint.Float object. - */ - public static LatLonPoint getFloat(Point2D pt2D) { - if (pt2D instanceof Float) { - return (Float) pt2D; - } else { - return new Float(pt2D); - } - } - - /** - * Factory method that will create a LatLonPoint.Double from a Point2D - * object. If pt2D is already a LatLonPoint.Double object, it is simply - * returned. - * - * @param pt2D - * @return a LatLonPoint.Double object. - */ - public static LatLonPoint getDouble(Point2D pt2D) { - if (pt2D instanceof Double) { - return (Double) pt2D; - } else { - return new Double(pt2D); - } - } - - /** - * Set the latitude, longitude for this point. - * - * @param lat decimal degree latitude - * @param lon decimal degree longitude. - */ - public abstract void setLatLon(double lat, double lon); - - /** - * Set the latitude, longitude for this point, with the option of noting - * whether the values are in degrees or radians. - * - * @param lat latitude - * @param lon longitude. - * @param isRadians true of values are radians. - */ - public abstract void setLatLon(double lat, double lon, boolean isRadians); - - /** - * @return decimal degree longitude as a float. - */ - public abstract float getLongitude(); - - /** - * @return decimal degree latitude as a float. - */ - public abstract float getLatitude(); - - /** - * @return radian longitude value. - */ - public abstract double getRadLon(); - - /** - * @return radian latitude value. - */ - public abstract double getRadLat(); - - /** - * Set decimal degree latitude. - */ - public abstract void setLatitude(double lat); - - /** - * Set decimal degree longitude. - */ - public abstract void setLongitude(double lon); - - /** - * The Float version of a LatLonPoint, where coordinates are held to float - * precision. - */ - public static class Float extends LatLonPoint { - - /** - * - */ - private static final long serialVersionUID = -2447464428275551182L; - protected float lat; - protected float lon; - protected transient float radLat; - protected transient float radLon; - - /** - * Default constructor, values set to 0, 0. - */ - public Float() { - } - - /** - * @param lat decimal degree latitude. - * @param lon decimal degree longitude. - */ - public Float(float lat, float lon) { - setLatLon(lat, lon, false); - } - - /** - * @param lat latitude - * @param lon longitude - * @param isRadian true if values are radians, false if decimal degrees. - */ - public Float(float lat, float lon, boolean isRadian) { - setLatLon(lat, lon, isRadian); - } - - /** - * Create Float version from another LatLonPoint. - * - * @param llp - */ - public Float(LatLonPoint llp) { - setLatLon(llp.getLatitude(), llp.getLongitude(), false); - } - - /** - * Create Float version from Point2D object, where the x, y values are - * expected to be decimal degrees. - * - * @param pt2D - */ - public Float(Point2D pt2D) { - setLatLon(pt2D.getY(), pt2D.getX(), false); - } - - /** - * Point2D method, inheriting signature!! - * - * @param x longitude value in decimal degrees. - * @param y latitude value in decimal degrees. - */ - public void setLocation(float x, float y) { - setLatLon(y, x, false); - } - - /** - * Point2D method, inheriting signature!! - * - * @param x longitude value in decimal degrees. - * @param y latitude value in decimal degrees. - */ - public void setLocation(double x, double y) { - setLatLon((float) y, (float) x, false); - } - - /** - * Set lat/lon values. - * - * @param lat decimal degree latitude. - * @param lon decimal degree longitude. - */ - public void setLatLon(float lat, float lon) { - setLatLon(lat, lon, false); - } - - /** - * Set lat/lon values. - * - * @param lat decimal degree latitude. - * @param lon decimal degree longitude. - */ - public void setLatLon(double lat, double lon) { - setLatLon((float) lat, (float) lon, false); - } - - /** - * Set lat/lon values. - * - * @param lat latitude. - * @param lon longitude. - * @param isRadians true if values are radians. - */ - public void setLatLon(double lat, double lon, boolean isRadians) { - if (isRadians) { - radLat = (float) lat; - radLon = (float) lon; - this.lat = (float) ProjMath.radToDeg(lat); - this.lon = (float) ProjMath.radToDeg(lon); - } else { - this.lat = (float) Double.normalizeLatitude(lat); - this.lon = (float) Double.wrapLongitude(lon); - radLat = (float) ProjMath.degToRad(lat); - radLon = (float) ProjMath.degToRad(lon); - } - } - - /** - * Set lat/lon values. - * - * @param lat latitude. - * @param lon longitude. - * @param isRadians true if values are radians. - */ - public void setLatLon(float lat, float lon, boolean isRadians) { - if (isRadians) { - radLat = lat; - radLon = lon; - this.lat = ProjMath.radToDeg(lat); - this.lon = ProjMath.radToDeg(lon); - } else { - this.lat = normalizeLatitude(lat); - this.lon = wrapLongitude(lon); - radLat = ProjMath.degToRad(lat); - radLon = ProjMath.degToRad(lon); - } - } - - /** - * Point2D method. - * - * @return decimal degree longitude. - * - * @see java.awt.geom.Point2D#getX() - */ - public double getX() { - return (double) lon; - } - - /** - * Point2D method - * - * @return decimal degree latitude. - */ - public double getY() { - return (double) lat; - } - - /** - * @return decimal degree longitude. - */ - public float getLongitude() { - return lon; - } - - /** - * @return decimal degree latitude. - */ - public float getLatitude() { - return lat; - } - - /** - * @return radian longitude. - */ - public double getRadLon() { - return (double) radLon; - } - - /** - * @return radian latitude. - */ - public double getRadLat() { - return (double) radLat; - } - - /** - * Set latitude. - * - * @param lat latitude in decimal degrees - */ - public void setLatitude(float lat) { - this.lat = normalizeLatitude(lat); - radLat = ProjMath.degToRad(lat); - } - - /** - * Set latitude. - * - * @param lat latitude in decimal degrees - */ - public void setLatitude(double lat) { - setLatitude((float) lat); - } - - /** - * Set longitude. - * - * @param lon longitude in decimal degrees - */ - public void setLongitude(float lon) { - this.lon = wrapLongitude(lon); - radLon = ProjMath.degToRad(lon); - } - - /** - * Set longitude. - * - * @param lon longitude in decimal degrees - */ - public void setLongitude(double lon) { - setLongitude((float) lon); - } - - /** - * Find a LatLonPoint a distance and direction away from this point, - * based on the spherical earth model. - * - * @param dist distance, in radians. - * @param az radians of azimuth (direction) east of north (-PI <= Az - * < PI) - * @return LatLonPoint result - */ - public LatLonPoint getPoint(float dist, float az) { - return GreatCircle.sphericalBetween(radLat, radLon, dist, az); - } - - /** - * Write object. - * - * @param s DataOutputStream - */ - public void write(DataOutputStream s) throws IOException { - // Write my information - s.writeFloat(lat); - s.writeFloat(lon); - } - - /** - * Read object. Assumes that the floats read off the stream will be in - * decimal degrees. Latitude read off the stream first, then longitude. - * - * @param s DataInputStream - */ - public void read(DataInputStream s) throws IOException { - setLatLon(s.readFloat(), s.readFloat(), false); - } - - /** - * Read object. Latitude read off the stream first, then longitude. - * - * @param s DataInputStream - * @param inRadians if true, the floats read off stream will be - * considered to be radians. Otherwise, they will be considered - * to be decimal degrees. - */ - public void read(DataInputStream s, boolean inRadians) throws IOException { - setLatLon(s.readFloat(), s.readFloat(), inRadians); - } - - /** - * Calculate the radlat_ and radlon_ instance - * variables upon deserialization. Also, check lat_ and - * lon_ for safety; someone may have tampered with the - * stream. - * - * @param stream Stream to read lat_ and lon_ - * from. - */ - private void readObject(java.io.ObjectInputStream stream) - throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - lat = normalizeLatitude(lat); - lon = wrapLongitude(lon); - radLat = ProjMath.degToRad(lat); - radLon = ProjMath.degToRad(lon); - } - - public String toString() { - return "LatLonPoint.Float[lat=" + lat + ",lon=" + lon + "]"; - } - } - - /** - * Double precision version of LatLonPoint. - * - * @author dietrick - */ - public static class Double extends LatLonPoint { - /** - * - */ - private static final long serialVersionUID = -7463055211717523471L; - - protected double lat; - protected double lon; - protected transient double radLat; - protected transient double radLon; - - /** - * Default constructor, values set to 0, 0. - */ - public Double() { - } - - /** - * Set the latitude, longitude for this point in decimal degrees. - * - * @param lat latitude - * @param lon longitude. - */ - public Double(double lat, double lon) { - setLatLon(lat, lon, false); - } - - /** - * Set the latitude, longitude for this point, with the option of noting - * whether the values are in degrees or radians. - * - * @param lat latitude - * @param lon longitude. - * @param isRadian true of values are radians. - */ - public Double(double lat, double lon, boolean isRadian) { - setLatLon(lat, lon, isRadian); - } - - /** - * Create Double version from another LatLonPoint. - * - * @param llp - */ - public Double(LatLonPoint llp) { - setLatLon(llp.getY(), llp.getX(), false); - } - - /** - * Create Double version from Point2D object, where the x, y values are - * expected to be decimal degrees. - * - * @param pt2D - */ - public Double(Point2D pt2D) { - setLatLon(pt2D.getY(), pt2D.getX(), false); - } - - /** - * Point2D method, inheriting signature!! - * - * @param x longitude value in decimal degrees. - * @param y latitude value in decimal degrees. - */ - public void setLocation(double x, double y) { - setLatLon(y, x, false); - } - - /** - * Set latitude and longitude. - * - * @param lat latitude in decimal degrees. - * @param lon longitude in decimal degrees. - */ - public void setLatLon(double lat, double lon) { - setLatLon(lat, lon, false); - } - - /** - * Set latitude and longitude. - * - * @param lat latitude. - * @param lon longitude. - * @param isRadians true if lat/lon values are radians. - */ - public void setLatLon(double lat, double lon, boolean isRadians) { - if (isRadians) { - radLat = lat; - radLon = lon; - this.lat = ProjMath.radToDeg(lat); - this.lon = ProjMath.radToDeg(lon); - } else { - this.lat = normalizeLatitude(lat); - this.lon = wrapLongitude(lon); - radLat = ProjMath.degToRad(lat); - radLon = ProjMath.degToRad(lon); - } - } - - /** - * @return longitude in decimal degrees. - */ - public double getX() { - return lon; - } - - /** - * @return latitude in decimal degrees. - */ - public double getY() { - return lat; - } - - /** - * @return float latitude in decimal degrees. - */ - public float getLatitude() { - return (float) lat; - } - - /** - * @return float longitude in decimal degrees. - */ - public float getLongitude() { - return (float) lon; - } - - /** - * @return radian longitude. - */ - public double getRadLon() { - return radLon; - } - - /** - * @return radian latitude. - */ - public double getRadLat() { - return radLat; - } - - /** - * Set latitude. - * - * @param lat latitude in decimal degrees - */ - public void setLatitude(double lat) { - this.lat = normalizeLatitude(lat); - radLat = ProjMath.degToRad(lat); - } - - /** - * Set longitude. - * - * @param lon longitude in decimal degrees - */ - public void setLongitude(double lon) { - this.lon = wrapLongitude(lon); - radLon = ProjMath.degToRad(lon); - } - - /** - * Find a LatLonPoint a distance and direction away from this point, - * based on the spherical earth model. - * - * @param dist distance, in radians. - * @param az radians of azimuth (direction) east of north (-PI <= Az - * < PI) - * @return LatLonPoint result - */ - public LatLonPoint getPoint(double dist, double az) { - return GreatCircle.sphericalBetween(radLat, radLon, dist, az); - } - - /** - * Write object. - * - * @param s DataOutputStream - */ - public void write(DataOutputStream s) throws IOException { - // Write my information - s.writeDouble(lat); - s.writeDouble(lon); - } - - /** - * Read object. Assumes that the floats read off the stream will be in - * decimal degrees. Latitude read off the stream first, then longitude. - * - * @param s DataInputStream - */ - public void read(DataInputStream s) throws IOException { - setLatLon(s.readDouble(), s.readDouble(), false); - } - - /** - * Read object. Latitude read off the stream first, then longitude. - * - * @param s DataInputStream - * @param inRadians if true, the floats read off stream will be - * considered to be radians. Otherwise, they will be considered - * to be decimal degrees. - */ - public void read(DataInputStream s, boolean inRadians) throws IOException { - setLatLon(s.readDouble(), s.readDouble(), inRadians); - } - - /** - * Calculate the radLat and radLon instance - * variables upon deserialization. Also, check lat and - * lon for safety; someone may have tampered with the - * stream. - * - * @param stream Stream to read lat and lon - * from. - */ - private void readObject(java.io.ObjectInputStream stream) - throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - lat = normalizeLatitude(lat); - lon = wrapLongitude(lon); - radLat = ProjMath.degToRad(lat); - radLon = ProjMath.degToRad(lon); - } - - public String toString() { - return "LatLonPoint.Double[lat=" + lat + ",lon=" + lon + "]"; - } - - } - - /** - * Set location values from another lat/lon point. - * - * @param llp - */ - public void setLatLon(LatLonPoint llp) { - setLatLon(llp.getY(), llp.getX(), false); - } - - /** - * Ensure latitude is between the poles. - * - * @param lat - * @return latitude greater than or equal to -90 and less than or equal to - * 90. - */ - public final static float normalizeLatitude(float lat) { - return (float) normalizeLatitude((double) lat); - } - - /** - * Sets latitude to something sane. - * - * @param lat latitude in decimal degrees - * @return float normalized latitude in decimal degrees (−90° ≤ - * φ ≤ 90°) - */ - public final static double normalizeLatitude(double lat) { - if (lat > NORTH_POLE) { - lat = NORTH_POLE; - } - if (lat < SOUTH_POLE) { - lat = SOUTH_POLE; - } - return lat; - } - - /** - * Ensure the longitude is between the date line. - * - * @param lon - * @return longitude that is smaller than or equal to 180 and greater than - * or equal to -180 - */ - public final static float wrapLongitude(float lon) { - return (float) wrapLongitude((double) lon); - } - - /** - * Sets longitude to something sane. - * - * @param lon longitude in decimal degrees - * @return float wrapped longitude in decimal degrees (−180° ≤ - * λ ≤ 180°) - */ - public final static double wrapLongitude(double lon) { - if ((lon < -DATELINE) || (lon > DATELINE)) { - // System.out.print("LatLonPoint: wrapping longitude " - // + - // lon); - lon += DATELINE; - lon = lon % LON_RANGE; - lon = (lon < 0) ? DATELINE + lon : -DATELINE + lon; - // Debug.output(" to " + lon); - } - return lon; - } - - /** - * Check if latitude is bogus. Latitude is invalid if lat > 90° or if - * lat < −90°. - * - * @param lat latitude in decimal degrees - * @return boolean true if latitude is invalid - */ - public static boolean isInvalidLatitude(double lat) { - return ((lat > NORTH_POLE) || (lat < SOUTH_POLE)); - } - - /** - * Check if longitude is bogus. Longitude is invalid if lon > 180° or - * if lon < −180°. - * - * @param lon longitude in decimal degrees - * @return boolean true if longitude is invalid - */ - public static boolean isInvalidLongitude(double lon) { - return ((lon < -DATELINE) || (lon > DATELINE)); - } - - /** - * Determines whether two LatLonPoints are equal. - * - * @param obj Object - * @return Whether the two points are equal up to a tolerance of 10 -5 - * degrees in latitude and longitude. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final LatLonPoint pt = (LatLonPoint) obj; - return (MoreMath.approximately_equal(getY(), pt.getY()) && MoreMath.approximately_equal(getX(), pt.getX())); - } - - /** - * Find the distance to another LatLonPoint, based on a earth spherical - * model. - * - * @param toPoint LatLonPoint - * @return distance, in radians. You can use an com.bbn.openmap.proj.Length - * to convert the radians to other units. - */ - public double distance(LatLonPoint toPoint) { - return GreatCircle.sphericalDistance(getRadLat(), getRadLon(), toPoint.getRadLat(), toPoint.getRadLon()); - } - - /** - * Find the azimuth to another point, based on the spherical earth model. - * - * @param toPoint LatLonPoint - * @return the azimuth `Az' east of north from this point bearing toward the - * one provided as an argument.(-PI <= Az <= PI). - * - */ - public double azimuth(LatLonPoint toPoint) { - return GreatCircle.sphericalAzimuth(getRadLat(), getRadLon(), toPoint.getRadLat(), toPoint.getRadLon()); - } - - /** - * Get a new LatLonPoint a distance and azimuth from another point, based on - * the spherical earth model. - * - * @param distance radians - * @param azimuth radians - * @return LatLonPoint that is distance and azimuth away from this one. - */ - public LatLonPoint getPoint(double distance, double azimuth) { - return GreatCircle.sphericalBetween(getRadLat(), getRadLon(), distance, azimuth); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/MGRSPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/MGRSPoint.java deleted file mode 100644 index d7f571d0f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/MGRSPoint.java +++ /dev/null @@ -1,1101 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/MGRSPoint.java,v $ -// $RCSfile: MGRSPoint.java,v $ -// $Revision: 1.20 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.PrintStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * A class representing a MGRS coordinate that has the ability to provide the - * decimal degree lat/lon equivalent, as well as the UTM equivalent. This class - * does not do checks to see if the MGRS coordinates provided actually make - * sense. It assumes that the values are valid. - */ -public class MGRSPoint - extends ZonedUTMPoint { - - /** - * UTM zones are grouped, and assigned to one of a group of 6 sets. - */ - protected final static int NUM_100K_SETS = 6; - /** - * The column letters (for easting) of the lower left value, per set. - */ - public final static int[] SET_ORIGIN_COLUMN_LETTERS = { - 'A', - 'J', - 'S', - 'A', - 'J', - 'S' - }; - /** - * The row letters (for northing) of the lower left value, per set. - */ - public final static int[] SET_ORIGIN_ROW_LETTERS = { - 'A', - 'F', - 'A', - 'F', - 'A', - 'F' - }; - /** - * The column letters (for easting) of the lower left value, per set,, for - * Bessel Ellipsoid. - */ - public final static int[] BESSEL_SET_ORIGIN_COLUMN_LETTERS = { - 'A', - 'J', - 'S', - 'A', - 'J', - 'S' - }; - /** - * The row letters (for northing) of the lower left value, per set, for - * Bessel Ellipsoid. - */ - public final static int[] BESSEL_SET_ORIGIN_ROW_LETTERS = { - 'L', - 'R', - 'L', - 'R', - 'L', - 'R' - }; - - public final static int SET_NORTHING_ROLLOVER = 20000000; - /** - * Use 5 digits for northing and easting values, for 1 meter accuracy of - * coordinate. - */ - public final static int ACCURACY_1_METER = 5; - /** - * Use 4 digits for northing and easting values, for 10 meter accuracy of - * coordinate. - */ - public final static int ACCURACY_10_METER = 4; - /** - * Use 3 digits for northing and easting values, for 100 meter accuracy of - * coordinate. - */ - public final static int ACCURACY_100_METER = 3; - /** - * Use 2 digits for northing and easting values, for 1000 meter accuracy of - * coordinate. - */ - public final static int ACCURACY_1000_METER = 2; - /** - * Use 1 digits for northing and easting values, for 10000 meter accuracy of - * coordinate. - */ - public final static int ACCURACY_10000_METER = 1; - - /** The set origin column letters to use. */ - protected int[] originColumnLetters = SET_ORIGIN_COLUMN_LETTERS; - /** The set origin row letters to use. */ - protected int[] originRowLetters = SET_ORIGIN_ROW_LETTERS; - - public final static int A = 'A'; - public final static int I = 'I'; - public final static int O = 'O'; - public final static int V = 'V'; - public final static int Z = 'Z'; - - protected boolean DEBUG = false; - protected final static Logger logger = Logger.getLogger("com.bbn.openmap.proj.coords.MGRSPoint"); - - /** The String holding the MGRS coordinate value. */ - protected String mgrs; - - /** - * Controls the number of digits that the MGRS coordinate will have, which - * directly affects the accuracy of the coordinate. Default is - * ACCURACY_1_METER, which indicates that MGRS coordinates will have 10 - * digits (5 easting, 5 northing) after the 100k two letter code, indicating - * 1 meter resolution. - */ - protected int accuracy = ACCURACY_1_METER; - - /** - * Point to create if you are going to use the static methods to fill the - * values in. - */ - public MGRSPoint() { - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Constructs a new MGRS instance from a MGRS String, validating the string - * as a MGRS coordinate. - */ - public MGRSPoint(String mgrsString) - throws NumberFormatException { - this(); - setMGRS(mgrsString); - } - - /** - * Constructs a new MGRSPoint instance from values in another MGRSPoint. - */ - public MGRSPoint(MGRSPoint point) { - this(); - mgrs = point.mgrs; - northing = point.northing; - easting = point.easting; - zone_number = point.zone_number; - zone_letter = point.zone_letter; - accuracy = point.accuracy; - } - - /** - * Create a MGRSPoint from standard values. - * - * @param northing northing offset - * @param easting easting offset - * @param zoneNumber the MGRS zone number - * @param zoneLetter the MGRS zone letter. - */ - public MGRSPoint(double northing, double easting, int zoneNumber, char zoneLetter) { - super(northing, easting, zoneNumber, zoneLetter); - } - - /** - * Construct a MGRSPoint from a LatLonPoint, assuming a WGS_84 ellipsoid. - */ - public MGRSPoint(LatLonPoint llpoint) { - this(llpoint, Ellipsoid.WGS_84); - } - - /** - * Construct a MGRSPoint from a LatLonPoint and a particular ellipsoid. - */ - public MGRSPoint(LatLonPoint llpoint, Ellipsoid ellip) { - this(); - LLtoMGRS(llpoint, ellip, this); - } - - /** - * Set the MGRS value for this Point. Will be decoded, and the MGRS values - * figured out. You can call toLatLonPoint() to translate it to lat/lon - * decimal degrees. - */ - public void setMGRS(String mgrsString) - throws NumberFormatException { - try { - mgrs = mgrsString.toUpperCase(); // Just to make sure. - decode(mgrs); - } catch (StringIndexOutOfBoundsException sioobe) { - throw new NumberFormatException("MGRSPoint has bad string: " + mgrsString); - } catch (NullPointerException npe) { - // Blow off - } - } - - /** - * Get the MGRS string value - the honkin' coordinate value. - */ - public String getMGRS() { - if (mgrs == null) { - resolve(); - } - return mgrs; - } - - /** - * Convert this MGRSPoint to a LatLonPoint, and assume a WGS_84 ellipsoid. - */ - public LatLonPoint toLatLonPoint() { - return toLatLonPoint(Ellipsoid.WGS_84, new LatLonPoint.Double()); - } - - /** - * Convert this MGRSPoint to a LatLonPoint, and use the given ellipsoid. - */ - public LatLonPoint toLatLonPoint(Ellipsoid ellip) { - return toLatLonPoint(ellip, new LatLonPoint.Double()); - } - - /** - * Fill in the given LatLonPoint with the converted values of this MGRSPoint, - * and use the given ellipsoid. - */ - public LatLonPoint toLatLonPoint(Ellipsoid ellip, LatLonPoint llpoint) { - return MGRStoLL(this, ellip, llpoint); - } - - /** - * Returns a string representation of the object. - * - * @return String representation - */ - public String toString() { - return "MGRSPoint[" + mgrs + "]"; - } - - /** - * Create a LatLonPoint from a MGRSPoint. - * - * @param mgrsp to convert. - * @param ellip Ellipsoid for earth model. - * @param llp a LatLonPoint to fill in values for. If null, a new LatLonPoint - * will be returned. If not null, the new values will be set in this - * object, and it will be returned. - * @return LatLonPoint with values converted from MGRS coordinate. - */ - public static LatLonPoint MGRStoLL(MGRSPoint mgrsp, Ellipsoid ellip, LatLonPoint llp) { - return UTMtoLL(ellip, mgrsp.northing, mgrsp.easting, mgrsp.zone_number, MGRSPoint.MGRSZoneToUTMZone(mgrsp.zone_letter), llp); - } - - /** - * Create a LatLonPoint from a MGRSPoint. - * - * @param ellip ellipsoid - * @param northing northing in meters - * @param easting easting in meters - * @param zoneNumber zone number for mgrs - * @param zoneLetter zone letter for mgrs - * @param llp LatLonPoint object to use for answer, ok if null. - * @return LatLonPoint from MGRSPoint - */ - public static LatLonPoint MGRStoLL(Ellipsoid ellip, double northing, double easting, int zoneNumber, char zoneLetter, - LatLonPoint llp) { - return UTMtoLL(ellip, northing, easting, zoneNumber, MGRSPoint.MGRSZoneToUTMZone(zoneLetter), llp); - } - - /** - * Converts a LatLonPoint to a MGRS Point, assuming the WGS_84 ellipsoid. - * - * @return MGRSPoint, or null if something bad happened. - */ - public static MGRSPoint LLtoMGRS(LatLonPoint llpoint) { - return LLtoMGRS(llpoint, Ellipsoid.WGS_84, new MGRSPoint()); - } - - /** - * Converts a LatLonPoint to a MGRS Point. - * - * @param llpoint the LatLonPoint to convert. - * @param mgrsp a MGRSPoint to put the results in. If it's null, a MGRSPoint - * will be allocated. - * @return MGRSPoint, or null if something bad happened. If a MGRSPoint was - * passed in, it will also be returned on a successful conversion. - */ - public static MGRSPoint LLtoMGRS(LatLonPoint llpoint, MGRSPoint mgrsp) { - return LLtoMGRS(llpoint, Ellipsoid.WGS_84, mgrsp); - } - - /** - * Create a MGRSPoint from a LatLonPoint. - * - * @param llp LatLonPoint to convert. - * @param ellip Ellipsoid for earth model. - * @param mgrsp a MGRSPoint to fill in values for. If null, a new MGRSPoint - * will be returned. If not null, the new values will be set in this - * object, and it will be returned. - * @return MGRSPoint with values converted from lat/lon. - */ - public static MGRSPoint LLtoMGRS(LatLonPoint llp, Ellipsoid ellip, MGRSPoint mgrsp) { - - if (mgrsp == null || !(mgrsp instanceof MGRSPoint)) { - mgrsp = new MGRSPoint(); - } - - // Calling LLtoUTM here results in N/S zone letters! wrong! - mgrsp = (MGRSPoint) LLtoUTM(llp, ellip, mgrsp); - // Need to add this to set the right letter for the latitude. - mgrsp.zone_letter = mgrsp.getLetterDesignator(llp.getLatitude()); - mgrsp.resolve(); - return mgrsp; - } - - /** - * Convert MGRS zone letter to UTM zone letter, N or S. - * - * @param mgrsZone - * @return N of given zone is equal or larger than N, S otherwise. - */ - public static char MGRSZoneToUTMZone(char mgrsZone) { - if (Character.toUpperCase(mgrsZone) >= 'N') { - return 'N'; - } else { - return 'S'; - } - } - - /** - * Method that provides a check for MGRS zone letters. Returns an uppercase - * version of any valid letter passed in. - */ - protected char checkZone(char zone) { - zone = Character.toUpperCase(zone); - - if (zone <= 'A' || zone == 'B' || zone == 'Y' || zone >= 'Z' || zone == 'I' || zone == 'O') { - throw new NumberFormatException("Invalid MGRSPoint zone letter: " + zone); - } - - return zone; - } - - /** - * Set the number of digits to use for easting and northing numbers in the - * mgrs string, which reflects the accuracy of the coordinate. From 5 (1 - * meter) to 1 (10,000 meter). - */ - public void setAccuracy(int value) { - accuracy = value; - mgrs = null; - } - - public int getAccuracy() { - return accuracy; - } - - /** - * Set the MGRS parameters from a MGRS coordinate string. - * - * @param mgrsString an UPPERCASE coordinate string is expected. - */ - protected void decode(String mgrsString) - throws NumberFormatException { - - if (mgrsString == null || mgrsString.length() == 0) { - throw new NumberFormatException("MGRSPoint coverting from nothing"); - } - - // Ensure an upper-case string - mgrsString = mgrsString.toUpperCase(); - - int length = mgrsString.length(); - - String hunK = null; - StringBuffer sb = new StringBuffer(); - char testChar; - int i = 0; - - // get Zone number - while (!Character.isLetter(testChar = mgrsString.charAt(i))) { - if (i >= 2) { - throw new NumberFormatException("MGRSPoint bad conversion from: " + mgrsString - + ", first two characters need to be a number between 1-60."); - } - sb.append(testChar); - i++; - } - - zone_number = Integer.parseInt(sb.toString()); - - if (zone_number < 1 || zone_number > 60) { - throw new NumberFormatException("MGRSPoint bad conversion from: " + mgrsString - + ", first two characters need to be a number between 1-60."); - } - - if (i == 0 || i + 3 > length) { - // A good MGRS string has to be 4-5 digits long, - // ##AAA/#AAA at least. - throw new NumberFormatException("MGRSPoint bad conversion from: " + mgrsString - + ", MGRS string must be at least 4-5 digits long"); - } - - zone_letter = mgrsString.charAt(i++); - - // Should we check the zone letter here? Why not. - if (zone_letter <= 'A' || zone_letter == 'B' || zone_letter == 'Y' || zone_letter >= 'Z' || zone_letter == 'I' - || zone_letter == 'O') { - throw new NumberFormatException("MGRSPoint zone letter " + (char) zone_letter + " not handled: " + mgrsString); - } - - hunK = mgrsString.substring(i, i += 2); - - // Validate, check the zone, make sure each letter is between A-Z, not I - // or O - char char1 = hunK.charAt(0); - char char2 = hunK.charAt(1); - if (char1 < 'A' || char2 < 'A' || char1 > 'Z' || char2 > 'Z' || char1 == 'I' || char2 == 'I' || char1 == 'O' || char2 == 'O') { - throw new NumberFormatException("MGRSPoint bad conversion from " + mgrsString + ", invalid 100k designator"); - } - - int set = get100kSetForZone(zone_number); - - float east100k = getEastingFromChar(char1, set); - float north100k = getNorthingFromChar(char2, set); - - // We have a bug where the northing may be 2000000 too low. - // How do we know when to roll over? - - while (north100k < getMinNorthing(zone_letter)) { - north100k += 2000000; - } - - // calculate the char index for easting/northing separator - int remainder = length - i; - - if (remainder % 2 != 0) { - throw new NumberFormatException( - "MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" - + mgrsString); - } - - int sep = remainder / 2; - - float sepEasting = 0f; - float sepNorthing = 0f; - - if (sep > 0) { - if (DEBUG) - logger.fine(" calculating e/n from " + mgrs.substring(i)); - float accuracyBonus = 100000f / (float) Math.pow(10, sep); - if (DEBUG) - logger.fine(" calculated accuracy bonus as " + accuracyBonus); - String sepEastingString = mgrsString.substring(i, i + sep); - if (DEBUG) - logger.fine(" parsed easting as " + sepEastingString); - sepEasting = Float.parseFloat(sepEastingString) * accuracyBonus; - String sepNorthingString = mgrsString.substring(i + sep); - if (DEBUG) - logger.fine(" parsed northing as " + sepNorthingString); - sepNorthing = Float.parseFloat(sepNorthingString) * accuracyBonus; - } - - easting = sepEasting + east100k; - northing = sepNorthing + north100k; - - if (DEBUG) { - logger.fine("Decoded " + mgrsString + " as zone number: " + zone_number + ", zone letter: " + zone_letter + ", easting: " - + easting + ", northing: " + northing + ", 100k: " + hunK); - } - } - - /** - * Create the mgrs string based on the internal MGRS parameter settings, - * should be called if the accuracy changes. - * - * @param digitAccuracy The number of digits to use for the northing and - * easting numbers. 5 digits reflect a 1 meter accuracy, 4 - 10 meter, - * 3 - 100 meter, 2 - 1000 meter, 1 - 10,000 meter. - */ - public void resolve(int digitAccuracy) { - setAccuracy(digitAccuracy); - resolve(); - } - - /** - * Create the mgrs string based on the internal MGRS parameter settings, - * using the accuracy set in the MGRSPoint. - */ - public void resolve() { - if (zone_letter == 'Z') { - mgrs = "Latitude limit exceeded"; - } else { - StringBuffer sb = - new StringBuffer(Integer.toString(zone_number)).append(zone_letter) - .append(get100kID(easting, northing, zone_number)); - StringBuffer seasting = new StringBuffer(Integer.toString((int) easting)); - StringBuffer snorthing = new StringBuffer(Integer.toString((int) northing)); - - if (DEBUG) { - logger.fine(" Resolving MGRS from easting: " + seasting + " derived from " + easting + ", and northing: " + snorthing - + " derived from " + northing); - } - - while (accuracy + 1 > seasting.length()) { - seasting.insert(0, '0'); - } - - // We have to be careful here, the 100k values shouldn't - // be - // used for calculating stuff here. - - while (accuracy + 1 > snorthing.length()) { - snorthing.insert(0, '0'); - } - - while (snorthing.length() > 6) { - snorthing.deleteCharAt(0); - } - - if (DEBUG) { - logger.fine(" -- modified easting: " + seasting + " and northing: " + snorthing); - } - - try { - sb.append(seasting.substring(1, accuracy + 1)).append(snorthing.substring(1, accuracy + 1)); - - mgrs = sb.toString(); - } catch (IndexOutOfBoundsException ioobe) { - mgrs = null; - } - } - } - - /** - * Given a MGRS/UTM zone number, figure out the MGRS 100K set it is in. - */ - protected int get100kSetForZone(int i) { - int set = i % NUM_100K_SETS; - if (set == 0) - set = NUM_100K_SETS; - return set; - } - - /** - * Provided so that extensions to this class can provide different origin - * letters, in case of different ellipsoids. The int[] represents all of the - * first letters in the bottom left corner of each set box, as shown in an - * MGRS 100K box layout. - */ - protected int[] getOriginColumnLetters() { - return originColumnLetters; - } - - /** - * Provided so that extensions to this class can provide different origin - * letters, in case of different ellipsoids. The int[] represents all of the - * first letters in the bottom left corner of each set box, as shown in an - * MGRS 100K box layout. - */ - protected void setOriginColumnLetters(int[] letters) { - originColumnLetters = letters; - } - - /** - * Provided so that extensions to this class can provide different origin - * letters, in case of different ellipsoids. The int[] represents all of the - * second letters in the bottom left corner of each set box, as shown in an - * MGRS 100K box layout. - */ - protected int[] getOriginRowLetters() { - return originRowLetters; - } - - /** - * Provided so that extensions to this class can provide different origin - * letters, in case of different ellipsoids. The int[] represents all of the - * second letters in the bottom left corner of each set box, as shown in an - * MGRS 100K box layout. - */ - protected void setOriginRowLetters(int[] letters) { - originRowLetters = letters; - } - - /** - * Get the two letter 100k designator for a given MGRS/UTM easting, northing and - * zone number value. - */ - protected String get100kID(double easting, double northing, int zone_number) { - int set = get100kSetForZone(zone_number); - int setColumn = ((int) easting / 100000); - int setRow = ((int) northing / 100000) % 20; - return get100kID(setColumn, setRow, set); - } - - /** - * Given the first letter from a two-letter MGRS 100k zone, and given the - * MGRS table set for the zone number, figure out the easting value that - * should be added to the other, secondary easting value. - */ - protected float getEastingFromChar(char e, int set) { - int baseCol[] = getOriginColumnLetters(); - // colOrigin is the letter at the origin of the set for the - // column - int curCol = baseCol[set - 1]; - float eastingValue = 100000f; - boolean rewindMarker = false; - - while (curCol != e) { - curCol++; - if (curCol == I) - curCol++; - if (curCol == O) - curCol++; - if (curCol > Z) { - if (rewindMarker) { - throw new NumberFormatException("Bad character: " + e); - } - curCol = A; - rewindMarker = true; - } - eastingValue += 100000f; - } - - if (DEBUG) { - logger.fine("Easting value for " + (char) e + " from set: " + set + ", col: " + curCol + " is " + eastingValue); - } - return eastingValue; - } - - /** - * Given the second letter from a two-letter MGRS 100k zone, and given the - * MGRS table set for the zone number, figure out the northing value that - * should be added to the other, secondary northing value. You have to - * remember that Northings are determined from the equator, and the vertical - * cycle of letters mean a 2000000 additional northing meters. This happens - * approx. every 18 degrees of latitude. This method does *NOT* count any - * additional northings. You have to figure out how many 2000000 meters need - * to be added for the zone letter of the MGRS coordinate. - * - * @param n second letter of the MGRS 100k zone - * @param set the MGRS table set number, which is dependent on the MGRS/UTM zone - * number. - */ - protected float getNorthingFromChar(char n, int set) { - - if (n > 'V') { - throw new NumberFormatException("MGRSPoint given invalid Northing " + n); - } - - int baseRow[] = getOriginRowLetters(); - // rowOrigin is the letter at the origin of the set for the - // column - int curRow = baseRow[set - 1]; - float northingValue = 0f; - boolean rewindMarker = false; - - while (curRow != n) { - curRow++; - if (curRow == I) - curRow++; - if (curRow == O) - curRow++; - // fixing a bug making whole application hang in this loop - // when 'n' is a wrong character - if (curRow > V) { - if (rewindMarker) { // making sure that this loop ends - throw new NumberFormatException("Bad character: " + n); - } - curRow = A; - rewindMarker = true; - } - northingValue += 100000f; - } - - if (DEBUG) { - logger.fine("Northing value for " + (char) n + " from set: " + set + ", row: " + curRow + " is " + northingValue); - } - - return northingValue; - } - - /** - * Get the two-letter MGRS 100k designator given information translated from - * the MGRS/UTM northing, easting and zone number. - * - * @param setColumn the column index as it relates to the MGRS 100k set - * spreadsheet, created from the MGRS/UTM easting. Values are 1-8. - * @param setRow the row index as it relates to the MGRS 100k set - * spreadsheet, created from the MGRS/UTM northing value. Values are from - * 0-19. - * @param set the set block, as it relates to the MGRS 100k set spreadsheet, - * created from the MGRS/UTM zone. Values are from 1-60. - * @return two letter MGRS 100k code. - */ - protected String get100kID(int setColumn, int setRow, int set) { - - if (DEBUG) { - System.out.println("set (" + set + ") column = " + setColumn + ", row = " + setRow); - } - - int baseCol[] = getOriginColumnLetters(); - int baseRow[] = getOriginRowLetters(); - - // colOrigin and rowOrigin are the letters at the origin of - // the set - int colOrigin = baseCol[set - 1]; - int rowOrigin = baseRow[set - 1]; - - if (DEBUG) { - System.out.println("starting at = " + (char) colOrigin + (char) rowOrigin); - } - - // colInt and rowInt are the letters to build to return - int colInt = colOrigin + setColumn - 1; - int rowInt = rowOrigin + setRow; - boolean rollover = false; - - if (colInt > Z) { - colInt = colInt - Z + A - 1; - rollover = true; - if (DEBUG) - System.out.println("rolling over col, new value: " + (char) colInt); - } - - if (colInt == I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) { - colInt++; - if (DEBUG) - System.out.println("skipping I in col, new value: " + (char) colInt); - } - if (colInt == O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) { - colInt++; - if (DEBUG) - System.out.println("skipping O in col, new value: " + (char) colInt); - if (colInt == I) { - colInt++; - if (DEBUG) - System.out.println(" hit I, new value: " + (char) colInt); - } - } - - if (colInt > Z) { - colInt = colInt - Z + A - 1; - if (DEBUG) - System.out.println("rolling(2) col, new value: " + (char) rowInt); - } - - if (rowInt > V) { - rowInt = rowInt - V + A - 1; - rollover = true; - if (DEBUG) - System.out.println("rolling over row, new value: " + (char) rowInt); - } else { - rollover = false; - } - - if (rowInt == I || (rowOrigin < I && rowInt > I) || ((rowInt > I || rowOrigin < I) && rollover)) { - rowInt++; - if (DEBUG) - System.out.println("skipping I in row, new value: " + (char) rowInt); - } - - if (rowInt == O || (rowOrigin < O && rowInt > O) || ((rowInt > O || rowOrigin < O) && rollover)) { - rowInt++; - if (DEBUG) - System.out.println("skipping O in row, new value: " + (char) rowInt); - if (rowInt == I) { - rowInt++; - if (DEBUG) - System.out.println(" hit I, new value: " + (char) rowInt); - } - } - - if (rowInt > V) { - rowInt = rowInt - V + A - 1; - if (DEBUG) - System.out.println("rolling(2) row, new value: " + (char) rowInt); - } - - String twoLetter = (char) colInt + "" + (char) rowInt; - - if (DEBUG) { - System.out.println("ending at = " + twoLetter); - } - - return twoLetter; - } - - /** - * Testing method, used to print out the MGRS 100k two letter set tables. - */ - protected void print100kSets() { - StringBuffer sb = null; - for (int set = 1; set <= 6; set++) { - System.out.println("-------------\nFor 100K Set " + set + ":\n-------------\n"); - for (int i = 19; i >= 0; i -= 1) { - sb = new StringBuffer(Integer.toString(i * 100000)).append("\t| "); - - for (int j = 1; j <= 8; j++) { - sb.append(" ").append(get100kID(j, i, set)); - } - - sb.append(" |"); - System.out.println(sb); - } - } - } - - /** - * The function getMinNorthing returns the minimum northing value of a MGRS - * zone. - * - * portted from Geotrans' c Latitude_Band_Value structure table. zoneLetter : - * MGRS zone (input) - */ - - protected float getMinNorthing(char zoneLetter) - throws NumberFormatException { - float northing; - switch (zoneLetter) { - case 'C': - northing = 1100000.0f; - break; - case 'D': - northing = 2000000.0f; - break; - case 'E': - northing = 2800000.0f; - break; - case 'F': - northing = 3700000.0f; - break; - case 'G': - northing = 4600000.0f; - break; - case 'H': - northing = 5500000.0f; - break; - case 'J': - northing = 6400000.0f; - break; - case 'K': - northing = 7300000.0f; - break; - case 'L': - northing = 8200000.0f; - break; - case 'M': - northing = 9100000.0f; - break; - case 'N': - northing = 0.0f; - break; - case 'P': - northing = 800000.0f; - break; - case 'Q': - northing = 1700000.0f; - break; - case 'R': - northing = 2600000.0f; - break; - case 'S': - northing = 3500000.0f; - break; - case 'T': - northing = 4400000.0f; - break; - case 'U': - northing = 5300000.0f; - break; - case 'V': - northing = 6200000.0f; - break; - case 'W': - northing = 7000000.0f; - break; - case 'X': - northing = 7900000.0f; - break; - default: - northing = -1.0f; - } - if (northing >= 0.0) { - return northing; - } else { - throw new NumberFormatException("Invalid zone letter: " + zone_letter); - } - - } - - private static void runTests(String fName, String inType) { - - LineNumberReader lnr = null; - PrintStream pos = null; - String record = null; - StringBuffer outStr1 = new StringBuffer(); - StringBuffer outStr2 = new StringBuffer(); - - try { - - /* - * File inFile = new File(fName + ".dat"); File outFile = new - * File(fName + ".out"); FileInputStream fis = new - * FileInputStream(inFile); FileOutputStream fos = new - * FileOutputStream(outFile); BufferedInputStream bis = new - * BufferedInputStream(fis); - */ - pos = new PrintStream(new FileOutputStream(new File(fName + ".out"))); - lnr = new LineNumberReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File(fName))))); - - if (inType.equalsIgnoreCase("MGRS")) { - outStr1.append("MGRS to LatLonPoint\n\tMGRS\t\tLatitude Longitude\n"); - outStr2.append("MGRS to UTM\n\tMGRS\t\tZone Easting Northing\n"); - } else if (inType.equalsIgnoreCase("UTM")) { - outStr1.append("UTM to LatLonPoint\n\tUTM\t\tLatitude Longitude\n"); - outStr2.append("UTM to MGRS\n\tUTM\t\tMGRS\n"); - } else if (inType.equalsIgnoreCase("LatLon")) { - outStr1.append("LatLonPoint to UTM\nLatitude Longitude\t\tZone Easting Northing \n"); - outStr2.append("LatLonPoint to MGRS\nLatitude Longitude\t\tMGRS\n"); - } - - while ((record = lnr.readLine()) != null) { - if (inType.equalsIgnoreCase("MGRS")) { - try { - MGRSPoint mgrsp = new MGRSPoint(record); - record = record.trim(); - mgrsp.decode(record); - - outStr1.append(record).append(" is ").append(mgrsp.toLatLonPoint()).append("\n"); - outStr2.append(record).append(" to UTM: ").append(mgrsp.zone_number).append(" ").append(mgrsp.easting) - .append(" ").append(mgrsp.northing).append("\n"); - } catch (NumberFormatException nfe) { - logger.warning(nfe.getMessage()); - } - - } else if (inType.equalsIgnoreCase("UTM")) { - MGRSPoint mgrsp; - UTMPoint utmp; - float e, n; - int z; - char zl; - String tmp; - record = record.trim(); - tmp = record.substring(0, 2); - z = Integer.parseInt(tmp); - tmp = record.substring(5, 11); - e = Float.parseFloat(tmp); - tmp = record.substring(12, 19); - n = Float.parseFloat(tmp); - zl = record.charAt(3); - utmp = new UTMPoint(n, e, z, zl); - LatLonPoint llp = utmp.toLatLonPoint(); - mgrsp = LLtoMGRS(llp); - outStr1.append(record).append(" is ").append(llp).append(" back to ").append(LLtoUTM(llp)).append("\n"); - outStr2.append(record).append(" is ").append(mgrsp).append("\n"); - } else if (inType.equalsIgnoreCase("LatLon")) { - float lat, lon; - int index; - String tmp; - record = record.trim(); - index = record.indexOf("\040"); - if (index < 0) { - index = record.indexOf("\011"); - } - tmp = record.substring(0, index); - lat = Float.parseFloat(tmp); - tmp = record.substring(index); - lon = Float.parseFloat(tmp); - LatLonPoint llp = new LatLonPoint.Double(lat, lon); - // UTMPoint utmp = LLtoUTM(llp); - MGRSPoint mgrsp = LLtoMGRS(llp); - outStr1.append(record).append(" to UTM: ").append(mgrsp.zone_number).append(" ").append(mgrsp.easting).append(" ") - .append(mgrsp.northing).append("\n"); - outStr2.append(record).append(" -> ").append(mgrsp.mgrs).append("\n"); - } - - } - - } catch (IOException e) { - // catch io errors from FileInputStream or readLine() - System.out.println("IO error: " + e.getMessage()); - - } finally { - if (pos != null) { - pos.print(outStr1.toString()); - pos.print("\n"); - pos.print(outStr2.toString()); - pos.close(); - } - // if the file opened okay, make sure we close it - if (lnr != null) { - try { - lnr.close(); - } catch (IOException ioe) { - } - } - - } - - } - - public static void main(String[] argv) { - Debug.init(); - - ArgParser ap = new ArgParser("MGRSPoint"); - ap.add("mgrs", "Print Latitude and Longitude for MGRS value", 1); - ap.add("latlon", "Print MGRS for Latitude and Longitude values", 2, true); - ap.add("sets", "Print the MGRS 100k table"); - ap.add("altsets", "Print the MGRS 100k table for the Bessel ellipsoid"); - ap.add("rtc", "Run test case, with filename and input data type [MGRS | UTM | LatLon]", 2); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String arg[]; - arg = ap.getArgValues("sets"); - if (arg != null) { - new MGRSPoint().print100kSets(); - } - - arg = ap.getArgValues("altsets"); - if (arg != null) { - MGRSPoint mgrsp = new MGRSPoint(); - mgrsp.setOriginColumnLetters(BESSEL_SET_ORIGIN_COLUMN_LETTERS); - mgrsp.setOriginRowLetters(BESSEL_SET_ORIGIN_ROW_LETTERS); - mgrsp.print100kSets(); - } - - arg = ap.getArgValues("mgrs"); - if (arg != null) { - try { - MGRSPoint mgrsp = new MGRSPoint(arg[0]); - Debug.output(arg[0] + " is " + mgrsp.toLatLonPoint()); - } catch (NumberFormatException nfe) { - Debug.error(nfe.getMessage()); - } - } - - arg = ap.getArgValues("latlon"); - if (arg != null) { - try { - - float lat = Float.parseFloat(arg[0]); - float lon = Float.parseFloat(arg[1]); - - LatLonPoint llp = new LatLonPoint.Double(lat, lon); - MGRSPoint mgrsp = LLtoMGRS(llp); - UTMPoint utmp = LLtoUTM(llp); - - if (utmp.zone_letter == 'Z') { - Debug.output(llp + "to UTM: latitude limit exceeded."); - } else { - Debug.output(llp + " is " + utmp); - } - - Debug.output(llp + " is " + mgrsp); - - } catch (NumberFormatException nfe) { - Debug.error("The numbers provided: " + argv[0] + ", " + argv[1] + " aren't valid"); - } - } - - arg = ap.getArgValues("rtc"); - if (arg != null) { - runTests(arg[0], arg[1]); - } - - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorMeterGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorMeterGCT.java deleted file mode 100644 index 7dd5cdf8b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorMeterGCT.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.util.MoreMath; - -/** - * Convert between mercator meters and lat/lon degrees. - * - * http://johndeck.blogspot.com/2005_09_01_johndeck_archive.html - * http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm - */ -public class MercatorMeterGCT extends AbstractGCT implements - GeoCoordTransformation { - - public final static MercatorMeterGCT INSTANCE = new MercatorMeterGCT(); - - // TODO: better names? - private double latfac; - private double lonfac; - - public MercatorMeterGCT() { - latfac = Planet.wgs84_earthPolarRadiusMeters_D; - lonfac = Planet.wgs84_earthPolarRadiusMeters_D; - } - - public MercatorMeterGCT(double latfac, double lonfac) { - this.latfac = latfac; - this.lonfac = lonfac; - } - - public Point2D forward(double lat, double lon, Point2D ret) { - - lat = LatLonPoint.normalizeLatitude(lat); - lon = LatLonPoint.wrapLongitude(lon); - - double latrad = Math.toRadians(lat); - double lonrad = Math.toRadians(lon); - - double lat_m = latfac - * Math.log(Math.tan(((latrad + MoreMath.HALF_PI_D) / 2d))); - double lon_m = lonfac * lonrad; - - ret.setLocation(lon_m, lat_m); - - return ret; - } - - public LatLonPoint inverse(double lon_m, double lat_m, LatLonPoint ret) { - double latrad = (2d * Math.atan(Math.exp(lat_m / latfac))) - - MoreMath.HALF_PI_D; - double lonrad = lon_m / lonfac; - - double lat = Math.toDegrees(latrad); - double lon = Math.toDegrees(lonrad); - - lat = LatLonPoint.normalizeLatitude(lat); - lon = LatLonPoint.wrapLongitude(lon); - - ret.setLatLon(lat, lon); - - return ret; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorUVGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorUVGCT.java deleted file mode 100644 index 094c091d5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/MercatorUVGCT.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -/** - * Convert between mercator uv coordinates that are used for map tiles and - * lat/lon degrees. Setting the zoom level sets the number of expected pixels in - * the Mercator uv projection in both directions. - */ -public abstract class MercatorUVGCT - extends AbstractGCT - implements GeoCoordTransformation { - - int zoomLevel; - - protected MercatorUVGCT(int zoomLevel) { - this.zoomLevel = zoomLevel; - } - - public abstract Point2D forward(double lat, double lon, Point2D ret); - - public abstract LatLonPoint inverse(double uvx, double uvy, LatLonPoint ret); - - public int getZoomLevel() { - return zoomLevel; - } - - public void setZoomLevel(int zoomLevel) { - this.zoomLevel = zoomLevel; - } - - public static class OSM - extends MercatorUVGCT { - - public OSM(int zoomLevel) { - super(zoomLevel); - } - - public Point2D forward(double lat, double lon, Point2D ret) { - if (ret == null) { - ret = new Point2D.Double(); - } - - ret.setLocation(((lon + 180.0) / 360.0 * Math.pow(2.0, zoomLevel)), - ((1.0 - Math.log(Math.tan(lat * Math.PI / 180.0) + (1.0 / Math.cos(lat * Math.PI / 180.0))) / Math.PI) / 2.0 * (Math.pow(2.0, - zoomLevel)))); - return ret; - } - - public LatLonPoint inverse(double uvx, double uvy, LatLonPoint ret) { - if (ret == null) { - ret = new LatLonPoint.Double(); - } - - ret.setLocation(360.0 / Math.pow(2.0, zoomLevel) * uvx - 180.0, - -90.0 + 360.0 / Math.PI * Math.atan(Math.exp((-2.0 * Math.PI * uvy) / Math.pow(2.0, zoomLevel) + Math.PI))); - return ret; - } - - } - - public static class TMS - extends MercatorUVGCT { - - public TMS(int zoomLevel) { - super(zoomLevel); - } - - public Point2D forward(double lat, double lon, Point2D ret) { - if (ret == null) { - ret = new Point2D.Double(); - } - - ret.setLocation(((lon + 180.0) / 360.0 * Math.pow(2, zoomLevel)), - Math.pow(2.0, zoomLevel) - - ((1.0 - Math.log(Math.tan(lat * Math.PI / 180.0) + (1.0 / Math.cos(lat * Math.PI / 180.0))) - / Math.PI) / 2.0 * (Math.pow(2.0, zoomLevel)))); - return ret; - } - - public LatLonPoint inverse(double uvx, double uvy, LatLonPoint ret) { - if (ret == null) { - ret = new LatLonPoint.Double(); - } - - ret.setLocation(360 / Math.pow(2, zoomLevel) * uvx - 180.0, - -90.0 - + 360.0 - / Math.PI - * Math.atan(Math.exp((-2.0 * Math.PI * (-(uvy - Math.pow(2.0, zoomLevel)))) - / Math.pow(2.0, zoomLevel) + Math.PI))); - - return ret; - } - - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/MultiGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/MultiGCT.java deleted file mode 100644 index 3fcf741f6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/MultiGCT.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -/** - * A {@link GeoCoordTransformation} consisting of an ordered list of other - * {@link GeoCoordTransformation}. - *

- * The forward methods perform the {@link GeoCoordTransformation}s in the given - * order. The inverse methods in the opposite order. - */ -public class MultiGCT extends AbstractGCT { - - private GeoCoordTransformation[] gcts; - - public MultiGCT(GeoCoordTransformation[] gcts) { - this.gcts = gcts; - } - - public Point2D forward(double lat, double lon, Point2D ret) { - for (int i = 0; i < gcts.length; i++) { - ret = gcts[i].forward(lat, lon, ret); - lat = ret.getY(); - lon = ret.getX(); - } - return ret; - } - - public LatLonPoint inverse(double x, double y, LatLonPoint ret) { - for (int i = gcts.length - 1; i >= 0; i--) { - ret = gcts[i].inverse(x, y, ret); - x = ret.getX(); - y = ret.getY(); - } - return ret; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/NedFrame.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/NedFrame.java deleted file mode 100644 index ff27955ee..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/NedFrame.java +++ /dev/null @@ -1,338 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/NedFrame.java,v $ -//$RCSfile: NedFrame.java,v $ -//$Revision: 1.6 $ -//$Date: 2009/02/25 22:34:04 $ -//$Author: dietrick $ -// -//*********************************************************** - -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.proj.ProjMath; - -/** - * Encapsulates the NED (North-East-Down) coordinate system. This is also know - * as local tangent plane (LTP). - *

- * Author: Robert Hayes - *

- */ -public class NedFrame { - - /** - * The x component of the coordinate (NORTH). - */ - protected float x; - /** - * The y component of the coordinate (EAST). - */ - protected float y; - /** - * The z component of the coordinate (DOWN). - */ - protected float z; - - /** - * Construct a default NedFrame. x,y,z are all set to zero. - */ - public NedFrame() { - x = 0.0f; - y = 0.0f; - z = 0.0f; - } - - /** - * Construct a NedFrame from ECEF vector and latitude and longitude. - * - * @param x ecef x. - * @param y ecef y. - * @param z ecef z. - * @param lat = latitude in degrees. - * @param lon = longitude in degrees. - */ - public NedFrame(float x, float y, float z, double lat, double lon) { - // All calculations are done using radians! - - double ecef[] = new double[3]; - double ned[] = new double[3]; - - double latitude = ProjMath.degToRad(lat); - double longitude = ProjMath.degToRad(lon); - - ecef[0] = x; - ecef[1] = y; - ecef[2] = z; - - ecef2ned(ned, latitude, longitude, ecef); - - this.x = (float) ned[0]; - this.y = (float) ned[1]; - this.z = (float) ned[2]; - } - - /** - * Construct a NedFrame from a ECEF vector and a LatLonPoint. - * - * @param ecefVector - */ - public NedFrame(double[] ecefVector, LatLonPoint llpt) { - // All calculations are done using radians! - - double ecef[] = new double[3]; - double ned[] = new double[3]; - double lat_ = llpt.getY(); - double lon_ = llpt.getX(); - double latitude = ProjMath.degToRad(lat_); - double longitude = ProjMath.degToRad(lon_); - - ecef[0] = ecefVector[0]; - ecef[1] = ecefVector[1]; - ecef[2] = ecefVector[2]; - - ecef2ned(ned, latitude, longitude, ecef); - - this.x = (float) ned[0]; - this.y = (float) ned[1]; - this.z = (float) ned[2]; - - } - - /** - * Convert to a geocentric frame using a LatLonPoint. - * - * @param llpt - * @return a vector of ecef values - */ - public double[] toGeocentricFrame(LatLonPoint llpt) { - // All calculations are done using radians! - double ecef[] = new double[3]; - double ned[] = new double[3]; - double lat_ = llpt.getY(); - double lon_ = llpt.getX(); - double latitude = ProjMath.degToRad(lat_); - double longitude = ProjMath.degToRad(lon_); - - ned2ecef(ned, latitude, longitude, ecef); - - return ecef; - } - - /** - * Internal conversion routine. - * - * @param ned vector - * @param latitude in radians. - * @param longitude in radians - * @param ecef vector - */ - public void ecef2ned(double ned[], double latitude, double longitude, - double ecef[]) { - - double temp[][] = new double[3][3]; - - double clat = Math.cos(latitude); - double clon = Math.cos(longitude); - double slat = Math.sin(latitude); - double slon = Math.sin(longitude); - - temp[0][0] = -slat * clon; - temp[0][1] = -slat * slon; - temp[0][2] = clat; - - temp[1][0] = -slon; - temp[1][1] = clon; - temp[1][2] = 0.0; - - temp[2][0] = -clat * clon; - temp[2][1] = -clat * slon; - temp[2][2] = -slat; - - for (int j = 0; j < 3; ++j) { - ned[j] = 0.0; - for (int i = 0; i < 3; i++) - ned[j] += temp[j][i] * ecef[i]; - } - - } - - /** - * Internal conversion routine. - * - * @param ned vector - * @param latitude in radians. - * @param longitude in radians - * @param ecef vector - */ - public void ned2ecef(double ned[], double latitude, double longitude, - double ecef[]) { - - double temp[][] = new double[3][3]; - - double clat = Math.cos(latitude); - double clon = Math.cos(longitude); - double slat = Math.sin(latitude); - double slon = Math.sin(longitude); - - ned[0] = this.x; - ned[1] = this.y; - ned[2] = this.z; - - temp[0][0] = -slat * clon; - temp[1][0] = -slat * slon; - temp[2][0] = clat; - - temp[0][1] = -slon; - temp[1][1] = clon; - temp[2][1] = 0.0; - - temp[0][2] = -clat * clon; - temp[1][2] = -clat * slon; - temp[2][2] = -slat; - - for (int j = 0; j < 3; ++j) { - ecef[j] = 0.0; - for (int i = 0; i < 3; i++) - ecef[j] += temp[j][i] * ned[i]; - } - } - - /** - * Copy construct a NedFrame. - * - * @param nedpt NedFrame - */ - public NedFrame(NedFrame nedpt) { - x = nedpt.x; - y = nedpt.y; - z = nedpt.z; - } - - /** - * - * @return String representation of NED vector. - */ - public String toString() { - return "NedFrame[N=" + x + ",E=" + y + ",D=" + z + "]"; - } - - /** - * Set x. - * - * @param pX in meters. - */ - public void setX(float pX) { - x = pX; - } - - /** - * Set y. - * - * @param pY in meters. - */ - public void setY(float pY) { - y = pY; - } - - /** - * Set z. - * - * @param pZ in meters. - */ - public void setZ(float pZ) { - z = pZ; - } - - /** - * Set x,y,z. - * - * @param v1 North. - * @param v2 East. - * @param v3 Down. - */ - public void setXYZ(float v1, float v2, float v3) { - x = v1; - y = v2; - z = v3; - } - - /** - * Get x. - * - * @return float x. - */ - public float getX() { - return x; - } - - /** - * Get Y. - * - * @return float y. - */ - public float getY() { - return y; - } - - /** - * Get Z. - * - * @return float z. - */ - public float getZ() { - return z; - } - - /** - * Get speed. - * - * @return double speed. - */ - public double toSpeed() { - return Math.sqrt(x * x + y * y); - } - - /** - * Get heading. - * - * @return double heading in degrees. - */ - public double toHeading() { - double radians = Math.atan2(y, x); - double degrees = Math.toDegrees(radians); - if (degrees < 0) { - degrees += degrees + 360; - } - return degrees; - } - - /* - * public final static void main (String[] args) { // TEST1 double temp[] = - * new double[3]; temp[0] = 13; temp[1] = 5; temp[2] = 8; - * - * LatLonPoint llpt = new LatLonPoint(40.00,-74.500); - * System.out.println("llpt" + llpt); System.out.println("ecef:" + temp[0] + " : " + - * temp[1] + " : " + temp[2]); - * - * NedFrame nedv = new NedFrame(temp,llpt); System.out.println("ned" + - * nedv); - * - * temp = nedv.toGeocentricFrame(llpt); System.out.println("ecef:" + temp[0] + " : " + - * temp[1] + " : " + temp[2]); } - */ - -}// class - diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/UPSPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/UPSPoint.java deleted file mode 100644 index ffadff1f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/UPSPoint.java +++ /dev/null @@ -1,305 +0,0 @@ -//********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/UPSPoint.java,v $ -// $RCSfile: UPSPoint.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -/** - * Class UPSPoint. - *

- * This class encapsulates a UPS point. - *

- * UPS is known as (Universal Polar Stereographic). - *

- * UPS is a coordinate system of Earth's polar regions north of - *

- * 84 degrees north, and south of 80 degrees south. - *

- * This class defaults to WGS-1984. - *

- * - * @author Bob Hayes - */ -public class UPSPoint { - - /** Easting */ - protected double easting; - /** Northing */ - protected double northing; - /** Hemisphere */ - // protected boolean southernHemisphere; - private double Degree = Math.PI / 180.0; - - // WGS-1984: 6378137.0, 298.257223563 0.00669438d - - /** Constructor for the UPSPoint object */ - public UPSPoint() { - this.easting = 0; - this.northing = 0; - // southernHemisphere = false; - } - - /** - * Constructor for the UPSPoint object - * - * @param easting easting - * @param northing northing - */ - public UPSPoint(double easting, double northing) { - this.easting = easting; - this.northing = northing; - // southernHemisphere = southern; - } - - /** - * Static method to create a UPSPoint object from lat/lon coordinates. - * Method avoids conflict with (double, double) constructor. - * - * @param lat latitude in decimal degrees - * @param lon longitude in decimal degrees - */ - public static UPSPoint createUPSPoint(double lat, double lon) { - UPSPoint ups = new UPSPoint(); - ups.toUPS(lat, lon); - return ups; - } - - /** - * Constructor for the UPSPoint object - * - * @param llpt LatLonPoint - */ - public UPSPoint(LatLonPoint llpt) { - this.toUPS(llpt.getY(), llpt.getX()); - } - - /** - * Converts a lat-lon pair to UPS point - * - * @param lat latitude in decimal degrees - * @param lon longitude in decimal degrees - */ - public void toUPS(double lat, double lon) { - double a = 0; - double t = 0; - double e = 0; - double es = 0; - double rho = 0; - double x; - double y; - final double k0 = 0.994; - - double lambda = lon * Degree; - double phi = Math.abs(lat * Degree); - // double phi = (lat * Degree); - - a = 6378137.0; - es = 0.00669438d; - - e = Math.sqrt(es); - t = Math.tan(Math.PI / 4.0 - phi / 2.0) - / Math.pow((1.0 - e * Math.sin(phi)) - / (1.0 + e * Math.sin(phi)), (e / 2.0)); - rho = 2.0 - * a - * k0 - * t - / Math.sqrt(Math.pow(1.0 + e, 1.0 + e) - * Math.pow(1.0 - e, 1.0 - e)); - x = rho * Math.sin(lambda); - y = rho * Math.cos(lambda); - - if (lat > 0.0) { - // Northern hemisphere - y = -(y); - // southernHemisphere = false; - } - x += 2.0e6; - // Add in false easting and northing - y += 2.0e6; - - easting = x; - northing = y; - } - - /* - * --------------------------------------------------------------------------------- - */ - - /** - * Convert a UPSPoint to a LatLonPoint - * - * @return returns a LatLonPoint - */ - public LatLonPoint toLatLonPoint(boolean southernHemisphere) { - LatLonPoint llp = new LatLonPoint.Double(); - double lon = 0; - double lat = 0; - double a = 0; - double es = 0; - double e = 0; - double t = 0; - double rho = 0; - double x = easting; - double y = northing; - final double k0 = 0.994; - - a = 6378137.0; - es = 0.00669438d; - - e = Math.sqrt(es); - - x -= 2.0e6; - // Remove false easting and northing - y -= 2.0e6; - - rho = Math.sqrt(x * x + y * y); - t = rho - * Math.sqrt(Math.pow(1.0 + e, 1.0 + e) - * Math.pow(1.0 - e, 1.0 - e)) / (2.0 * a * k0); - - lat = calcPhi(e, t); - lat /= Degree; - - if (y != 0.0) { - t = Math.atan(Math.abs(x / y)); - } else { - t = Math.PI / 2.0; - if (x < 0.0) { - t = -t; - } - } - - if (southernHemisphere == false) { - y = -y; - } else { - lat = -lat; - } - - if (y < 0.0) { - t = Math.PI - t; - } - - if (x < 0.0) { - t = -t; - } - - lon = t / Degree; - llp.setLatitude((float) lat); - llp.setLongitude((float) lon); - return llp; - } - - /* - * --------------------------------------------------------------------------------- - */ - - /** - * Sets the northing attribute - * - * @param northing The new northing value - */ - public void setNorthing(double northing) { - this.northing = northing; - } - - /** - * Sets the easting attribute - * - * @param easting The new easting value - */ - public void setEasting(double easting) { - this.easting = easting; - } - - /** - * Gets the easting attribute - * - * @return The easting value - */ - public double getNorthing() { - return northing; - } - - /** - * Gets the easting attribute - * - * @return The easting value - */ - public double getEasting() { - return easting; - } - - /** - * Description of the Method - * - * @return returns a string representation of the object - */ - public String toString() { - return "Easting:" + easting + " Northing:" + northing; - } - - /** - * Calculate phi (latitude) - * - * @param e - * @param t - * @return phi - */ - static double calcPhi(double e, double t) { - double phi = 0; - double old = Math.PI / 2.0 - 2.0 * Math.atan(t); - short maxIterations = 20; - - while ((Math.abs((phi - old) / phi) > 1.0e-8) && (maxIterations != 0)) { - old = phi; - phi = Math.PI - / 2.0 - - 2.0 - * Math.atan(t - * Math.pow((1.0 - e * Math.sin(phi)) - / ((1.0 + e * Math.sin(phi))), (e / 2.0))); - maxIterations--; - } - return phi; - } - - /** - * Tested against the NIMA calculator - */ - public static void main(String[] args) { - // TEST1 - NORTH & WEST - LatLonPoint llpt1 = new LatLonPoint.Double(87.00, -74.50); - System.out.println(llpt1.toString()); - UPSPoint ups = new UPSPoint(llpt1); - System.out.println(ups.toString()); - LatLonPoint llpt2 = ups.toLatLonPoint(false); - System.out.println(llpt2.toString()); - // TEST2 - SOUTH & EAST - System.out.println("--------------------------------------------"); - llpt1 = new LatLonPoint.Double(-89.00, 110.50); - System.out.println(llpt1.toString()); - ups = new UPSPoint(llpt1); - System.out.println(ups.toString()); - llpt2 = ups.toLatLonPoint(true); - System.out.println(llpt2.toString()); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMGCT.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMGCT.java deleted file mode 100644 index 21b51a5cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMGCT.java +++ /dev/null @@ -1,123 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: UTMGCT.java,v $ -//$Revision: 1.3 $ -//$Date: 2008/09/19 14:20:14 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; -import java.util.Properties; - -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.util.PropUtils; - -public class UTMGCT extends AbstractGCT implements GeoCoordTransformation { - - public final static String ZoneProperty = "zone"; - public final static String HemiProperty = "hemi"; - public final static String ElliposoidProperty = "ellipsoid"; - - protected Ellipsoid ellipsoid = Ellipsoid.WGS_84; - - protected LatLonPoint tmpLL = new LatLonPoint.Double(); - protected UTMPoint tmpUTM = new UTMPoint(); - - protected int zone_number; - protected char zone_letter; - - /** - * Make sure you call setProperties() or set the UTM before trying to use - * this object. - * - */ - public UTMGCT() {} - - public UTMGCT(int zone_number, char zone_letter) { - this.zone_number = zone_number; - this.zone_letter = zone_letter; - } - - public UTMGCT(UTMPoint utmPoint) { - setUtm(utmPoint); - } - - public UTMPoint getUtm() { - return tmpUTM; - } - - public void setUtm(UTMPoint utm) { - this.tmpUTM = utm; - this.zone_number = utm.zone_number; - this.zone_letter = utm.zone_letter; - } - - public synchronized Point2D forward(double lat, double lon, Point2D ret) { - tmpLL.setLatLon(lat, lon); - UTMPoint.LLtoUTM(tmpLL, ellipsoid, tmpUTM, zone_number, zone_letter == 'N'); - ret.setLocation(tmpUTM.easting, tmpUTM.northing); - return ret; - } - - public LatLonPoint inverse(double x, double y, LatLonPoint ret) { - UTMPoint.UTMtoLL(ellipsoid, y, x, zone_number, zone_letter, ret); - return ret; - } - - public void setProperties(String propertyPrefix, Properties props) { - super.setProperties(propertyPrefix, props); - - propertyPrefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - zone_number = PropUtils.intFromProperties(props, propertyPrefix - + ZoneProperty, 0); - - String hString = props.getProperty(propertyPrefix + HemiProperty, "N"); - zone_letter = hString.charAt(0); - - String eName = props.getProperty(propertyPrefix + ElliposoidProperty, - "WGS_84"); - ellipsoid = Ellipsoid.getByName(eName); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ZoneProperty, Integer.toString(zone_number)); - props.put(prefix + HemiProperty, Character.toString(zone_letter)); - props.put(prefix + ElliposoidProperty, ellipsoid.name.toUpperCase() - .replace(' ', '_')); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - return props; - } - - public Ellipsoid getEllipsoid() { - return ellipsoid; - } - - public void setEllipsoid(Ellipsoid ellipsoid) { - this.ellipsoid = ellipsoid; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMPoint.java deleted file mode 100644 index ad76a1b22..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/UTMPoint.java +++ /dev/null @@ -1,529 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/coords/UTMPoint.java,v $ -// $RCSfile: UTMPoint.java,v $ -// $Revision: 1.17 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.proj.Ellipsoid; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.util.HashCodeUtil; - -/** - * A class representing a UTM co-ordinate. - *

- * - * Adapted to Java by Colin Mummery (colin_mummery@yahoo.com) from C++ code by - * Chuck Gantz (chuck.gantz@globalstar.com) - */ -public class UTMPoint { - - /** - * The northing component of the coordinate. - */ - public double northing; - /** - * The easting component of the coordinate. - */ - public double easting; - /** - * The zone number of the coordinate, must be between 1 and 60. - */ - public int zone_number; - /** - * For UTM, 'N' or 'S', to designate the northern or southern hemisphere. - */ - public char zone_letter; - - /** - * Point to create if you are going to use the static methods to fill the - * values in. - */ - public UTMPoint() { - } - - /** - * Constructs a new UTM instance. - * - * @param northing The northing component. - * @param easting The easting component. - * @param zone_number The zone of the coordinate. - * @param zone_letter For UTM, 'N' or 'S', to designate the northern or - * southern hemisphere. - * @throws NumberFormatException if N or S isn't used - */ - public UTMPoint(double northing, double easting, int zone_number, char zone_letter) { - this.northing = northing; - this.easting = easting; - this.zone_number = zone_number; - this.zone_letter = checkZone(zone_letter); - } - - /** - * Constructs a new UTMPoint instance from values in another UTMPoint. - */ - public UTMPoint(UTMPoint point) { - this(point.northing, point.easting, point.zone_number, point.zone_letter); - } - - /** - * Construct a UTMPoint from a LatLonPoint, assuming a WGS_84 ellipsoid. - */ - public UTMPoint(LatLonPoint llpoint) { - this(llpoint, Ellipsoid.WGS_84); - } - - /** - * Construct a UTMPoint from a LatLonPoint and a particular ellipsoid. - */ - public UTMPoint(LatLonPoint llpoint, Ellipsoid ellip) { - this(); - LLtoUTM(llpoint, ellip, this); - } - - public boolean equals(Object obj) { - if (obj instanceof UTMPoint) { - UTMPoint pnt = (UTMPoint) obj; - return northing == pnt.northing && easting == pnt.easting && zone_number == pnt.zone_number - && zone_letter == pnt.zone_letter; - } - return false; - } - - /** - * Method that provides a check for UTM zone letters. Returns an uppercase - * version of any valid letter passed in, 'N' or 'S'. - * - * @throws NumberFormatException if zone letter is invalid - */ - protected char checkZone(char zone) { - zone = Character.toUpperCase(zone); - - if (zone != 'N' && zone != 'S') { - throw new NumberFormatException("Invalid UTMPoint zone letter: " + zone); - } - - return zone; - } - - /** - * Convert this UTMPoint to a LatLonPoint, and assume a WGS_84 ellipsoid. - */ - public LatLonPoint toLatLonPoint() { - return UTMtoLL(this, Ellipsoid.WGS_84, new LatLonPoint.Double()); - } - - /** - * Convert this UTMPoint to a LatLonPoint, and use the given ellipsoid. - */ - public LatLonPoint toLatLonPoint(Ellipsoid ellip) { - return UTMtoLL(this, ellip, new LatLonPoint.Double()); - } - - /** - * Fill in the given LatLonPoint with the converted values of this UTMPoint, - * and use the given ellipsoid. - */ - public LatLonPoint toLatLonPoint(Ellipsoid ellip, LatLonPoint llpoint) { - return UTMtoLL(this, ellip, llpoint); - } - - /** - * Returns a string representation of the object. - * - * @return String representation - */ - public String toString() { - return "UTMPoint[zone_number=" + zone_number + ", easting=" + easting + ", northing=" + northing + ", hemisphere=" - + zone_letter + "]"; - } - - /** - * Converts a LatLonPoint to a UTM Point, assuming the WGS_84 ellipsoid. - * - * @return UTMPoint, or null if something bad happened. - */ - public static UTMPoint LLtoUTM(LatLonPoint llpoint) { - return LLtoUTM(llpoint, Ellipsoid.WGS_84, new UTMPoint()); - } - - /** - * Converts a LatLonPoint to a UTM Point. - * - * @param llpoint the LatLonPoint to convert. - * @param utmpoint a UTMPoint to put the results in. If it's null, a - * UTMPoint will be allocated. - * @return UTMPoint, or null if something bad happened. If a UTMPoint was - * passed in, it will also be returned on a successful conversion. - */ - public static UTMPoint LLtoUTM(LatLonPoint llpoint, UTMPoint utmpoint) { - return LLtoUTM(llpoint, Ellipsoid.WGS_84, utmpoint); - } - - /** - * Converts a set of Longitude and Latitude co-ordinates to UTM given an - * ellipsoid - * - * @param ellip an ellipsoid definition. - * @param llpoint the coordinate to be converted - * @param utmpoint A UTMPoint instance to put the results in. If null, a new - * UTMPoint will be allocated. - * @return A UTM class instance containing the value of null if - * conversion failed. If you pass in a UTMPoint, it will be returned - * as well if successful. - */ - public static UTMPoint LLtoUTM(LatLonPoint llpoint, Ellipsoid ellip, UTMPoint utmpoint) { - - // find the native zone for the given llpoint - int zoneNumber = getZoneNumber(llpoint.getY(), llpoint.getX()); - boolean isnorthern = (llpoint.getLatitude() >= 0f); - - return LLtoUTM(llpoint, ellip, utmpoint, zoneNumber, isnorthern); - } - - /** - * Converts a set of Longitude and Latitude co-ordinates to UTM given an - * ellipsoid and the UTM zone to use. - * - * @param ellip an ellipsoid definition. - * @param llpoint the coordinate to be converted - * @param utmPoint A UTMPoint instance to put the results in. If null, a new - * UTMPoint will be allocated. - * @param zoneNumber the number of the zone - * @param isNorthern true if zone is in northern hemisphere - * @return A UTM class instance containing the value of null if - * conversion failed. If you pass in a UTMPoint, it will be returned - * as well if successful. - */ - public static UTMPoint LLtoUTM(LatLonPoint llpoint, Ellipsoid ellip, UTMPoint utmPoint, int zoneNumber, boolean isNorthern) { - - double a = ellip.radius; - double k0 = 0.9996; - - double eccSquared = ellip.eccsq; - double eccPrimeSquared = (eccSquared) / (1 - eccSquared); - double eccSquared2 = eccSquared * eccSquared; - double eccSquared3 = eccSquared2 * eccSquared; - - double N, T, C, A, M; - - double LatRad = llpoint.getRadLat(); - double LongRad = llpoint.getRadLon(); - - // in middle of zone - double LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin - double LongOriginRad = Math.toRadians(LongOrigin); - - double tanLatRad = Math.tan(LatRad); - double sinLatRad = Math.sin(LatRad); - double cosLatRad = Math.cos(LatRad); - - N = a / Math.sqrt(1 - eccSquared * sinLatRad * sinLatRad); - T = tanLatRad * tanLatRad; - C = eccPrimeSquared * cosLatRad * cosLatRad; - A = cosLatRad * (LongRad - LongOriginRad); - - M = - a - * ((1 - eccSquared / 4 - 3 * eccSquared2 / 64 - 5 * eccSquared3 / 256) * LatRad - - (3 * eccSquared / 8 + 3 * eccSquared2 / 32 + 45 * eccSquared3 / 1024) * Math.sin(2 * LatRad) - + (15 * eccSquared2 / 256 + 45 * eccSquared3 / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared3 / 3072) - * Math.sin(6 * LatRad)); - - double UTMEasting = - (k0 - * N - * (A + (1 - T + C) * A * A * A / 6.0d + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A - * A * A / 120.0d) + 500000.0d); - - double UTMNorthing = - (k0 * (M + N - * Math.tan(LatRad) - * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0d + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) - * A * A * A * A * A * A / 720.0d))); - if (!isNorthern) { - UTMNorthing += 10000000.0f; // 10000000 meter offset for - // southern hemisphere - } - - if (utmPoint == null) { - utmPoint = new UTMPoint(); - } - - utmPoint.northing = UTMNorthing; - utmPoint.easting = UTMEasting; - utmPoint.zone_number = zoneNumber; - utmPoint.zone_letter = isNorthern ? 'N' : 'S'; - - return utmPoint; - } - - /** - * Returns 'N' if the latitude is equal to or above the equator, 'S' if it's - * below. - * - * @param lat The float value of the latitude. - * - * @return A char value - */ - protected char getLetterDesignator(double lat) { - char letterDesignator = 'N'; - - if (lat < 0) { - letterDesignator = 'S'; - } - - return letterDesignator; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - result = HashCodeUtil.hash(result, northing); - result = HashCodeUtil.hash(result, easting); - result = HashCodeUtil.hash(result, zone_number); - result = HashCodeUtil.hash(result, zone_letter); - return result; - } - - /** - * Converts UTM coords to lat/long given an ellipsoid given an instance of - * UTMPoint. - * - * @param utm_point A UTMPoint instance. - * @param ellip a ellipsoid definition. - * @param llpoint a LatLonPoint, if you want it to be filled in with the - * results. If null, a new LatLonPoint will be allocated. - * @return A LatLonPoint class instance containing the lat/long value, or - * null if conversion failed. If you pass in a - * LatLonPoint, it will be returned as well, if successful. - */ - public static LatLonPoint UTMtoLL(UTMPoint utm_point, Ellipsoid ellip, LatLonPoint llpoint) { - return UTMtoLL(ellip, utm_point.northing, utm_point.easting, utm_point.zone_number, utm_point.zone_letter, llpoint); - } - - /** - * Converts UTM coords to lat/long given an ellipsoid. This is a convenience - * class where the Zone can be specified as a single string eg."60N" which - * is then broken down into the ZoneNumber and ZoneLetter. - * - * @param ellip an ellipsoid definition. - * @param UTMNorthing A float value for the northing to be converted. - * @param UTMEasting A float value for the easting to be converted. - * @param UTMZone A String value for the UTM zone eg."60N". - * @param llpoint a LatLonPoint, if you want it to be filled in with the - * results. If null, a new LatLonPoint will be allocated. - * @return A LatLonPoint class instance containing the lat/long value, or - * null if conversion failed. If you pass in a - * LatLonPoint, it will be returned as well, if successful. - */ - public static LatLonPoint UTMtoLL(Ellipsoid ellip, double UTMNorthing, double UTMEasting, String UTMZone, LatLonPoint llpoint) { - - // without the zone we can't calculate the Lat and Long - if (UTMZone == null || UTMZone.length() == 0) { - return null; - } - - int ZoneNumber = 1; - char ZoneLetter = 'N'; // northern hemisphere by default if no - // character is found - - // Break out the Zone number and zone letter from the UTMZone - // string We assume the string is a valid zone with a number - // followed by a zone letter If there is no Letter we assume - // that it's the Northern hemisphere - int ln = UTMZone.length() - 1; - if (ln > 0) { - // If it's Zero then there is only one character and it - // must be the Zone number - ZoneLetter = UTMZone.charAt(ln); - if (!Character.isLetter(ZoneLetter)) { - // No letter so assume it's missing & default to 'N' - ZoneLetter = 'N'; - ln++; - } - } - - // convert the number but catch the exception if it's not - // valid - try { - ZoneNumber = Integer.parseInt(UTMZone.substring(0, ln)); - } catch (NumberFormatException nfe) { - return null; - } - - return UTMtoLL(ellip, UTMNorthing, UTMEasting, ZoneNumber, ZoneLetter, llpoint); - } - - /** - * Converts UTM coords to lat/long given an ellipsoid. This is a convenience - * class where the exact Zone letter is not known. Instead only the - * hemisphere needs to be indicated. - * - * @param ellip an ellipsoid definition. - * @param UTMNorthing A float value for the northing to be converted. - * @param UTMEasting A float value for the easting to be converted. - * @param ZoneNumber An int value indicating the float number. - * @param isNorthern A boolean which is true for the northern hemisphere - * otherwise false for the southern. - * @param llpoint a LatLonPoint, if you want it to be filled in with the - * results. If null, a new LatLonPoint will be allocated. - * @return A LatLonPoint class instance containing the lat/long value, or - * null if conversion failed. If you pass in a - * LatLonPoint, it will be returned as well, if successful. - */ - public static LatLonPoint UTMtoLL(Ellipsoid ellip, double UTMNorthing, double UTMEasting, int ZoneNumber, boolean isNorthern, - LatLonPoint llpoint) { - - return UTMtoLL(ellip, UTMNorthing, UTMEasting, ZoneNumber, (isNorthern) ? 'N' : 'S', llpoint); - } - - /** - * Converts UTM coords to lat/long given an ellipsoid. - *

- * Equations from USGS Bulletin 1532
- * East Longitudes are positive, West longitudes are negative.
- * North latitudes are positive, South latitudes are negative.
- * - * @param ellip an ellipsoid definition. - * @param UTMNorthing A float value for the northing to be converted. - * @param UTMEasting A float value for the easting to be converted. - * @param zoneNumber An int value specifiying the UTM zone number. - * @param zoneLetter A char value specifying the ZoneLetter within the - * ZoneNumber. - * @param llpoint a LatLonPoint, if you want it to be filled in with the - * results. If null, a new LatLonPoint will be allocated. - * @return A LatLonPoint class instance containing the lat/long value, or - * null if conversion failed. If you pass in a - * LatLonPoint, it will be returned as well, if successful. - */ - public static LatLonPoint UTMtoLL(Ellipsoid ellip, double UTMNorthing, double UTMEasting, int zoneNumber, char zoneLetter, - LatLonPoint llpoint) { - - // check the ZoneNummber is valid - if (zoneNumber < 0 || zoneNumber > 60) { - return null; - } - - double k0 = 0.9996; - double a = ellip.radius; - double eccSquared = ellip.eccsq; - double eccPrimeSquared; - double e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared)); - double N1, T1, C1, R1, D, M; - double LongOrigin; - double mu, phi1Rad; - - // remove 500,000 meter offset for longitude - double x = UTMEasting - 500000.0d; - double y = UTMNorthing; - - // We must know somehow if we are in the Northern or Southern - // hemisphere, this is the only time we use the letter So even - // if the Zone letter isn't exactly correct it should indicate - // the hemisphere correctly - if (zoneLetter == 'S') { - y -= 10000000.0d;// remove 10,000,000 meter offset used - // for southern hemisphere - } - - // There are 60 zones with zone 1 being at West -180 to -174 - LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin - // in middle of - // zone - - eccPrimeSquared = (eccSquared) / (1 - eccSquared); - - M = y / k0; - mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256)); - - phi1Rad = - mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) - * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu); - // double phi1 = ProjMath.radToDeg(phi1Rad); - - N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad)); - T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad); - C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad); - R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5); - D = x / (N1 * k0); - - double lat = - phi1Rad - - (N1 * Math.tan(phi1Rad) / R1) - * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 - * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) - * D * D * D * D * D * D / 720); - lat = ProjMath.radToDeg(lat); - - double lon = - (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) - * D * D * D * D * D / 120) - / Math.cos(phi1Rad); - lon = LongOrigin + ProjMath.radToDeg(lon); - if (llpoint != null) { - llpoint.setLatLon(lat, lon); - return llpoint; - } else { - return new LatLonPoint.Double(lat, lon); - } - } - - /** - * Find zone number based on the given latitude and longitude in *degrees*. - * - * @param lat in decimal degrees - * @param lon in decimal degrees - * @return zone number for UTM zone for lat, lon - */ - public static int getZoneNumber(double lat, double lon) { - int zoneNumber = (int) ((lon + 180) / 6) + 1; - - // Make sure the longitude 180.00 is in Zone 60 - if (lon == 180) { - zoneNumber = 60; - } - - // Special zone for Norway - if (lat >= 56.0f && lat < 64.0f && lon >= 3.0f && lon < 12.0f) { - zoneNumber = 32; - } - - // Special zones for Svalbard - if (lat >= 72.0f && lat < 84.0f) { - if (lon >= 0.0f && lon < 9.0f) - zoneNumber = 31; - else if (lon >= 9.0f && lon < 21.0f) - zoneNumber = 33; - else if (lon >= 21.0f && lon < 33.0f) - zoneNumber = 35; - else if (lon >= 33.0f && lon < 42.0f) - zoneNumber = 37; - } - - return zoneNumber; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/VHTransform.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/VHTransform.java deleted file mode 100644 index 70a7444cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/VHTransform.java +++ /dev/null @@ -1,457 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/VHTransform.java,v $ -// $RCSfile: VHTransform.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj.coords; - -import java.awt.geom.Point2D; - -/* Cathleen Lancaster - 6 Hutcheson */ - -/** - * The VH coordinate system is used by ATT to compute distance used in - * determining phone call costs. - *

- * - * VH coordinates can be used to compute distance simply, see distance(). - *

- * - * This code is based on C code provided by the authors mentioned below, as well - * as Lisp code by Larry Denenberg of BBN. - *

- * - * I have ported this code to Java, unified the forward and inverse - * transformations and added some comments. I've left basic code and comments - * mostly intact. - *

- * - * The url's to the original emails are: - *

- * - * http://x11.dejanews.com/getdoc.xp?AN=177302113&CONTEXT=895858362.931528704&hitnum=1
- * http://x11.dejanews.com/getdoc.xp?AN=223540739&CONTEXT=895858362.931528704&hitnum=5 - */ -public class VHTransform implements GeoCoordTransformation { - /* Polynomial constants */ - public static final double K1 = .99435487; - public static final double K2 = .00336523; - public static final double K3 = -.00065596; - public static final double K4 = .00005606; - public static final double K5 = -.00000188; - - /* PI in various forms */ - public static final double M_PI_2 = Math.PI / 2.0; - - /* - * spherical coordinates of eastern reference point EX^2 + EY^2 + EZ^2 = 1 - */ - public static final double EX = .40426992; - public static final double EY = .68210848; - public static final double EZ = .60933887; - - /* - * spherical coordinates of western reference point WX^2 + WY^2 + WZ^2 = 1 - */ - public static final double WX = .65517646; - public static final double WY = .37733790; - public static final double WZ = .65449210; - - /* spherical coordinates of V-H coordinate system */ - /* PX^2 + PY^2 + PZ^2 = 1 */ - public static final double PX = -0.555977821730048699; - public static final double PY = -0.345728488161089920; - public static final double PZ = 0.755883902605524030; - - /* Rotation by 76 degrees */ - public final static double rot = Math.toRadians(76.597497064); - public final static double ROTC = Math.cos(rot); - public final static double ROTS = Math.sin(rot); - - /* orthogonal translation values */ - public static final double TRANSV = 6363.235; - public static final double TRANSH = 2250.700; - - /** radius of earth in sqrt(0.1)-mile units, minus 0.3 percent */ - public static final double RADIUS = 12481.103; - - public static final double K9 = RADIUS * ROTC; - public static final double K10 = RADIUS * ROTS; - - public VHTransform() { - } - - /** Return the V corresponding to the most recent toVH(). * */ - public double getV() { - return this.resultV; - } - - /** Return the H corresponding to the most recent toVH(). * */ - public double getH() { - return this.resultH; - } - - /** - * Return the latitude corresponding to the most recent toLatLon(). * - */ - public double getLat() { - return this.resultLat; - } - - /** - * Return the longitude corresponding to the most recent toLatLon(). * - */ - public double getLon() { - return this.resultLon; - } - - /** Return the distance in miles between 2 VH pairs. * */ - public static double distance(double v1, double h1, double v2, double h2) { - double dv = v2 - v1; - double dh = h2 - h1; - // Was - // return Math.sqrt(dv*dv + dh*dh)/10.0; - // Now, thanks to Andrew Canfield - return Math.sqrt((dv * dv + dh * dh) / 10.0); - } - - private double resultV = 0.0; - private double resultH = 0.0; - private double resultLat = 0.0; - private double resultLon = 0.0; - - /* - * - * Subject: Re: AT&T V-H Coordinates From: shoppa@alph02.triumf.ca (Tim - * Shoppa) Date: 1996/08/28 Message-ID: - * Newsgroups: comp.dcom.telecom [More Headers] [Subscribe to - * comp.dcom.telecom] - * - * In article , Drew Larsen - * wrote: > Ok folks, scratch your heads and see if - * you can remember how to > translate a point on the earth measured in - * latitude/longitude to the > commonly used V&H system used in the telecom - * industry. - * - * Below is a past post by Stu Jeffery containing a program which does the - * conversion the other way. If anybody is willing to buy me a nice lunch - * (my standard fee for two dimensional function inversion), I'll modify it - * to go both ways :-) - * - * Tim Shoppa, TRIUMF theory group | Internet: shoppa@triumf.ca TRIUMF, - * Canada's National Meson Facility | Voice: 604-222-1047 loc 6446 4004 - * WESBROOK MALL, UBC CAMPUS | FAX: 604-222-1074 University of British - * Columbia, Vancouver, B.C., CANADA V6T 2A3 - * - * Article: 54928 of comp.dcom.telecom Date: Tue, 29 Aug 1995 00:16:38 -0800 - * From: stu@shell.portal.com (Stu Jeffery) Subject: Re: V&H Questions - * Message-ID: X-Telecom-Digest: Volume 15, - * Issue 362, Message 11 of 11 - * - * Attached is a C program that will do what you want. I don't know anything - * more than what is here. I think it was posted in a news group, so use at - * your own legal risk. I have compiled it and it works fine. - * - * Going the other way is a bit more complicated. Probably the simplest way - * is by successive approximation. - * - * Good Luck. - * - * ----------------------------------------- - */ - - /** - * Computes Bellcore/AT&T V & H (vertical and horizontal) coordinates from - * latitude and longitude. Used primarily by local exchange carriers (LEC's) - * to compute the V & H coordinates for wire centers. - *

- * - * This is an implementation of the Donald Elliptical Projection, a - * Two-Point Equidistant projection developed by Jay K. Donald of AT&T in - * 1956 to establish long-distance telephone rates. (ref: - * "V-H Coordinate Rediscovered", Eric K. Grimmelmann, Bell Labs Tech. Memo, - * 9/80. (References Jay Donald notes of Jan 17, 1957.)) Ashok Ingle of - * Bellcore also wrote an internal memo on the subject. - *

- * - * The projection is specially modified for the ellipsoid and is confined to - * the United States and southern Canada. - *

- * - * Derived from a program obtained from an anonymous author within Bellcore - * by way of the National Exchange Carrier Association. Cleaned up and - * improved a bit by Tom Libert (tom@comsol.com, libert@citi.umich.edu). - *

- * - * CASH REWARD for copies of the reference papers, or for an efficient - * (non-iterative) inverse for this program! (i.e. a program to compute lat - * & long from V & H). - */ - - /** lat and lon are in degrees, positive north and east. */ - public void toVH(double lat, double lon) { - - lat = Math.toRadians(lat); - lon = Math.toRadians(lon); - - /* Translate east by 52 degrees */ - double lon1 = lon + Math.toRadians(52.0); - /* Convert latitude to geocentric latitude using Horner's rule */ - double latsq = lat * lat; - double lat1 = lat - * (K1 + (K2 + (K3 + (K4 + K5 * latsq) * latsq) * latsq) * latsq); - - /* - * x, y, and z are the spherical coordinates corresponding to lat, lon. - */ - double cos_lat1 = Math.cos(lat1); - double x = cos_lat1 * Math.sin(-lon1); - double y = cos_lat1 * Math.cos(-lon1); - double z = Math.sin(lat1); - /* - * e and w are the cosine of the angular distance (radians) between our - * point and the east and west centers. - */ - double e = EX * x + EY * y + EZ * z; - double w = WX * x + WY * y + WZ * z; - e = e > 1.0 ? 1.0 : e; - w = w > 1.0 ? 1.0 : w; - e = M_PI_2 - Math.atan(e / Math.sqrt(1 - e * e)); - w = M_PI_2 - Math.atan(w / Math.sqrt(1 - w * w)); - /* e and w are now in radians. */ - double ht = (e * e - w * w + .16) / .8; - double vt = Math.sqrt(Math.abs(e * e - ht * ht)); - vt = (PX * x + PY * y + PZ * z) < 0 ? -vt : vt; - /* rotate and translate to get final v and h. */ - double v = TRANSV + K9 * ht - K10 * vt; - double h = TRANSH + K10 * ht + K9 * vt; - this.resultV = v; - this.resultH = h; - } - - /* - * Stu Jeffery Internet: stu@shell.portal.com 1072 Seena Ave. voice: - * 415-966-8199 Los Altos, CA. 94024 fax: 415-966-8456 ////// Subject: V & H - * to Latitude and Longitude From: sicherman@lucent.com (Col. G.L. - * Sicherman) Date: 1997/03/05 Message-ID: - * Newsgroups: comp.dcom.telecom [More - * Headers] [Subscribe to comp.dcom.telecom] - * - * - * Recently I wanted to convert some Bell Labs "V&H" coordinates to latitude - * and longitude. A careful search through the Telecomm- unications Archives - * turned up a C program for converting in the other direction, and many - * pleas for what I was looking for. One poster even offered money! - * - * Since I work for Bell Labs, I had no trouble getting a copy of Erik - * Grimmelmann's legendary memorandum. (Don't get your hopes up - Bell Labs - * has no intention of releasing it to the public!) Thus armed, I hacked up - * the following C program, which ought to compile on any C platform. Its - * input and output agree with the output and input of ll_to_vh (as hacked - * by Tom Libert), and the comments summarize the math as explained by - * Grimmelmann. Enjoy! - */ - /** - * V&H is a system of coordinates (V and H) for describing locations of rate - * centers in the United States. The projection, devised by J. K. Donald, is - * an "elliptical," or "doubly equidistant" projection, scaled down by a - * factor of 0.003 to balance errors. - *

- * - * The foci of the projection, from which distances are measured accurately - * (except for the scale correction), are at 37d 42m 14.69s N, 82d 39m - * 15.27s W (in Floyd Co., Ky.) and 41d 02m 55.53s N, 112d 03m 39.35 W (in - * Webster Co., Utah). They are just 0.4 radians apart. - *

- * - * Here is the transformation from latitude and longitude to V&H: First - * project the earth from its ellipsoidal surface to a sphere. This alters - * the latitude; the coefficients bi in the program are the coefficients of - * the polynomial approximation for the inverse transformation. (The - * function is odd, so the coefficients are for the linear term, the cubic - * term, and so on.) Also subtract 52 degrees from the longitude. - *

- * - * For the rest, compute the arc distances of the given point to the - * reference points, and transform them to the coordinate system in which - * the line through the reference points is the X-axis and the origin is the - * eastern reference point. The solution is - *

- * h = (square of distance to E - square of distance to W + square of - * distance between E and W) / twice distance between E and W;
- * v = square root of absolute value of (square of distance to E - square of - * h). - *

- * Reduce by three-tenths of a percent, rotate by 76.597497 degrees, and add - * 6363.235 to V and 2250.7 to H. - *

- * - * To go the other way, as this program does, undo the final translation, - * rotation, and scaling. The z-value Pz of the point on the x-y-z sphere - * satisfies the quadratic Azz+Bz+c=0, where - *

- * A = (ExWz-EzWx)^2 + (EyWzx-EzWy)^2 + (ExWy-EyWx)^2;
- * B = -2[(Ex cos(arc to W) - Wx cos(arc to E))(ExWz-EzWx) - (Ey cos(arc to - * W) -Wy cos(arc to E))(EyWz-EzWy)];
- * C = (Ex cos(arc to W) - Wx cos(arc to E))^2 + (Ey cos(arc to W) - Wy - * cos(arc to E))^2 - (ExWy - EyWx)^2. - *

- * Solve with the quadratic formula. The latitude is simply the arc sine of - * Pz. Px and Py satisfy - *

- * ExPx + EyPy + EzPz = cos(arc to E);
- * WxPx + WyPy + WzPz = cos(arc to W). - *

- * Substitute Pz's value, and solve linearly to get Px and Py. The longitude - * is the arc tangent of Px/Py. Finally, this latitude and longitude are - * spherical; use the inverse polynomial approximation on the latitude to - * get the ellipsoidal earth latitude, and add 52 degrees to the longitude. - */ - public void toLatLon(double v0, double h0) { - /* GX = ExWz - EzWx; GY = EyWz - EzWy */ - final double GX = 0.216507961908834992; - final double GY = -0.134633014879368199; - /* A = (ExWz-EzWx)^2 + (EyWz-EzWy)^2 + (ExWy-EyWx)^2 */ - final double A = 0.151646645621077297; - /* Q = ExWy-EyWx; Q2 = Q*Q */ - final double Q = -0.294355056616412800; - final double Q2 = 0.0866448993556515751; - final double EPSILON = .0000001; - - double v = (double) v0; - double h = (double) h0; - - double t1 = (v - TRANSV) / RADIUS; - double t2 = (h - TRANSH) / RADIUS; - double vhat = ROTC * t2 - ROTS * t1; - double hhat = ROTS * t2 + ROTC * t1; - double e = Math.cos(Math.sqrt(vhat * vhat + hhat * hhat)); - double w = Math.cos(Math.sqrt(vhat * vhat + (hhat - 0.4) * (hhat - 0.4))); - double fx = EY * w - WY * e; - double fy = EX * w - WX * e; - double b = fx * GX + fy * GY; - double c = fx * fx + fy * fy - Q2; - double disc = b * b - A * c; /* discriminant */ - double x, y, z, delta; - if (Math.abs(disc) < EPSILON) { - // if (disc==0.0) { /* It's right on the E-W axis */ - z = b / A; - x = (GX * z - fx) / Q; - y = (fy - GY * z) / Q; - } else { - delta = Math.sqrt(disc); - z = (b + delta) / A; - x = (GX * z - fx) / Q; - y = (fy - GY * z) / Q; - if (vhat * (PX * x + PY * y + PZ * z) < 0) { /* - * wrong direction - */ - z = (b - delta) / A; - x = (GX * z - fx) / Q; - y = (fy - GY * z) / Q; - } - } - double lat = Math.asin(z); - - /* - * Use polynomial approximation for inverse mapping (sphere to - * spheroid): - */ - final double[] bi = { 1.00567724920722457, -0.00344230425560210245, - 0.000713971534527667990, -0.0000777240053499279217, - 0.00000673180367053244284, -0.000000742595338885741395, - 0.0000000905058919926194134 }; - double lat2 = lat * lat; - /* - * KRA: Didn't seem to work at first, so i unrolled it. double earthlat - * = 0.0; for (int i=6; i>=0; i--) { earthlat = (earthlat + bi[i]) * (i - * > 0? lat2 : lat); } - */ - - double earthlat = lat - * (bi[0] + lat2 - * (bi[1] + lat2 - * (bi[2] + lat2 - * (bi[3] + lat2 - * (bi[4] + lat2 - * (bi[5] + lat2 * (bi[6]))))))); - earthlat = Math.toDegrees(earthlat); - - /* - * Adjust longitude by 52 degrees: - */ - double lon = Math.toDegrees(Math.atan2(x, y)); - double earthlon = lon + 52.0; - - this.resultLat = earthlat; - this.resultLon = -earthlon; - // Col. G. L. Sicherman. - } - - public void toLatLon(int v0, int h0) { - toLatLon((double) v0, (double) h0); - } - - public Point2D forward(double lat, double lon) { - return forward(lat, lon, null); - } - - public Point2D forward(double lat, double lon, Point2D ret) { - if (ret == null) { - ret = new Point2D.Double(); - } - - toVH(lat, lon); - ret.setLocation(getV(), getH()); - return ret; - } - - public LatLonPoint inverse(double v, double h) { - return inverse(v, h, null); - } - - public LatLonPoint inverse(double v, double h, LatLonPoint ret) { - if (ret == null) { - ret = new LatLonPoint.Double(); - } - toLatLon(v, h); - ret.setLocation(getLat(), getLon()); - return ret; - } - - public static void main(String[] args) { - if (args.length < 2) { - System.out.println("Usage: VHTransform lat lon"); - System.exit(0); - } - - try { - double lat = Double.parseDouble(args[0]); - double lon = Double.parseDouble(args[1]); - - VHTransform vh = new VHTransform(); - Point2D vhpnts = vh.forward(lat, lon); - - System.out.println(vhpnts); - } catch (NumberFormatException nfe) { - System.out.println("can't parse numbers, should be lat, lon"); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/coords/ZonedUTMPoint.java b/src/core/src/main/java/com/bbn/openmap/proj/coords/ZonedUTMPoint.java deleted file mode 100644 index 4306d3e6f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/coords/ZonedUTMPoint.java +++ /dev/null @@ -1,169 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: ZonedUTMPoint.java,v $ -//$Revision: 1.6 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj.coords; - -import com.bbn.openmap.proj.Ellipsoid; - -/** - * A ZonedUTMPoint is a UTMPoint that handles a MGRS zone letter instead of N or - * S. - * - * @author dietrick - */ -public class ZonedUTMPoint extends UTMPoint { - - /** - * Constructor pass-through. - */ - public ZonedUTMPoint() { - super(); - } - - /** - * @param northing The northing component. - * @param easting The easting component. - * @param zone_number The zone of the coordinate. - * @param zone_letter MGRS zone letter - */ - public ZonedUTMPoint(double northing, double easting, int zone_number, - char zone_letter) { - super(northing, - easting, - zone_number, - MGRSPoint.MGRSZoneToUTMZone(zone_letter)); - // Need to remember the zone_letter passed in, that's the point of this - // class. - this.zone_letter = zone_letter; - } - - /** - * Constructor pass-through. - */ - public ZonedUTMPoint(UTMPoint point) { - super(point); - } - - /** - * Constructor pass-through. - */ - public ZonedUTMPoint(LatLonPoint llpoint) { - super(llpoint); - } - - /** - * Constructor pass-through. - */ - public ZonedUTMPoint(LatLonPoint llpoint, Ellipsoid ellip) { - super(llpoint, ellip); - } - - /** - * Converts UTM coords to lat/long given an ellipsoid. - *

- * Equations from USGS Bulletin 1532
- * East Longitudes are positive, West longitudes are negative.
- * North latitudes are positive, South latitudes are negative.
- * - * @param ellip an ellipsoid definition. - * @param UTMNorthing A float value for the northing to be converted. - * @param UTMEasting A float value for the easting to be converted. - * @param ZoneNumber An int value specifiying the UTM zone number. - * @param ZoneLetter A char value specifying the ZoneLetter within the - * ZoneNumber, letter being MGRS zone. - * @param llpoint a LatLonPoint, if you want it to be filled in with the - * results. If null, a new LatLonPoint will be allocated. - * @return A LatLonPoint class instance containing the lat/long value, or - * null if conversion failed. If you pass in a - * LatLonPoint, it will be returned as well, if successful. - */ - public static LatLonPoint ZonedUTMtoLL(Ellipsoid ellip, double UTMNorthing, - double UTMEasting, int ZoneNumber, - char ZoneLetter, LatLonPoint llpoint) { - return UTMPoint.UTMtoLL(ellip, - UTMNorthing, - UTMEasting, - ZoneNumber, - MGRSPoint.MGRSZoneToUTMZone(ZoneLetter), - llpoint); - } - - /** - * Determines the correct MGRS letter designator for the given latitude - * returns 'Z' if latitude is outside the MGRS limits of 84N to 80S. - * - * @param lat The float value of the latitude. - * - * @return A char value which is the MGRS zone letter. - */ - protected char getLetterDesignator(double lat) { - - // This is here as an error flag to show that the Latitude is - // outside MGRS limits - char LetterDesignator = 'Z'; - - if ((84 >= lat) && (lat >= 72)) - LetterDesignator = 'X'; - else if ((72 > lat) && (lat >= 64)) - LetterDesignator = 'W'; - else if ((64 > lat) && (lat >= 56)) - LetterDesignator = 'V'; - else if ((56 > lat) && (lat >= 48)) - LetterDesignator = 'U'; - else if ((48 > lat) && (lat >= 40)) - LetterDesignator = 'T'; - else if ((40 > lat) && (lat >= 32)) - LetterDesignator = 'S'; - else if ((32 > lat) && (lat >= 24)) - LetterDesignator = 'R'; - else if ((24 > lat) && (lat >= 16)) - LetterDesignator = 'Q'; - else if ((16 > lat) && (lat >= 8)) - LetterDesignator = 'P'; - else if ((8 > lat) && (lat >= 0)) - LetterDesignator = 'N'; - else if ((0 > lat) && (lat >= -8)) - LetterDesignator = 'M'; - else if ((-8 > lat) && (lat >= -16)) - LetterDesignator = 'L'; - else if ((-16 > lat) && (lat >= -24)) - LetterDesignator = 'K'; - else if ((-24 > lat) && (lat >= -32)) - LetterDesignator = 'J'; - else if ((-32 > lat) && (lat >= -40)) - LetterDesignator = 'H'; - else if ((-40 > lat) && (lat >= -48)) - LetterDesignator = 'G'; - else if ((-48 > lat) && (lat >= -56)) - LetterDesignator = 'F'; - else if ((-56 > lat) && (lat >= -64)) - LetterDesignator = 'E'; - else if ((-64 > lat) && (lat >= -72)) - LetterDesignator = 'D'; - else if ((-72 > lat) && (lat >= -80)) - LetterDesignator = 'C'; - return LetterDesignator; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/proj/package.html b/src/core/src/main/java/com/bbn/openmap/proj/package.html deleted file mode 100644 index a7d40fd81..000000000 --- a/src/core/src/main/java/com/bbn/openmap/proj/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides projection classes. - - diff --git a/src/core/src/main/java/com/bbn/openmap/time/Clock.java b/src/core/src/main/java/com/bbn/openmap/time/Clock.java deleted file mode 100644 index 89ebfbe1f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/Clock.java +++ /dev/null @@ -1,797 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/time/Clock.java,v $ -// $RCSfile: Clock.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.beancontext.BeanContextChildSupport; -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.Timer; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The Clock is a controller that manages a Timer in order to support the notion - * of a time range and a list of objects that can contribute to that time range. - * The clock can count forward and backward, can wrap around the time limits, - * and can be set to any time between the time range limits. The clock sends out - * time notifications as PropertyChangeEvents. - */ -public class Clock extends OMComponent implements RealTimeHandler, - ActionListener, PropertyChangeListener, TimeBoundsHandler, Serializable { - - public final static int DEFAULT_TIME_INTERVAL = 1000; - - /** - * timeFormat, used for the times listed in properties for rates/pace. - */ - public final static String TimeFormatProperty = "timeFormat"; - - /** - * TimeFormat default is similar to IETF standard date syntax: "13:30:00" - * represented by (HH:mm:ss). - */ - protected SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); - - protected Timer timer; - - protected long startTime = Long.MAX_VALUE; - - protected long endTime = Long.MIN_VALUE; - - protected long time = 0; - - /** - * The timeIncrement is the amount of time that passes for each clock tick. - * This sets up the ratio for slow and fast motion changes for a set clock - * update rate. Can be modified with the pace accessors. - */ - protected int timeIncrement = DEFAULT_TIME_INTERVAL; - - protected boolean timeWrap = false; - - protected int clockDirection = 1; - - protected List timerRates; - - protected transient List timeBoundsProviders; - protected transient List timeBoundsListeners; - protected transient List timeEventListeners; - - /** - * The delay between timer pulses, in milliseconds. - */ - protected int updateInterval = DEFAULT_TIME_INTERVAL; - - public Clock() { - // Created again with the peer not set, this allows the Clock to be - // added to multiple MapHandlers. - beanContextChildSupport = new BeanContextChildSupport(); - createTimer(); - timerRates = new LinkedList(); - timeBoundsProviders = new Vector(); - timeBoundsListeners = new Vector(); - timeEventListeners = new Vector(); - } - - // ////////////////////////// - // RealTimeHandler methods. - // ////////////////////////// - - /** - * Set the real time clock interval between clock ticks, in milliseconds. - */ - public void setUpdateInterval(int delay) { - updateInterval = delay; - if (timer != null) { - timer.setDelay(updateInterval); - if (timer.isRunning()) { - timer.restart(); - } - } - } - - /** - * Return the real time interval between clock ticks, in milliseconds. - */ - public int getUpdateInterval() { - return updateInterval; - } - - /** - * Set the amount of simulation time that passes with each clock tick, in - * milliseconds. - */ - public void setPace(int pace) { - timeIncrement = pace; - } - - /** - * Get the amount of simulation time that passes with each clock tick, in - * milliseconds. - */ - public int getPace() { - return timeIncrement; - } - - /** - * Called to set the clock to a specific time, usually for jumps. - * - * @param t the time in unix epoch terms - */ - public void setTime(long t) { - setTime(t, TimerStatus.UPDATE); - } - - /** - * The call to set the clock for all reasons. - * - * @param t the time in unix epoch terms - * @param timeStatus TimerStatus indicating how the clock is changing. - */ - protected void setTime(long t, TimerStatus timeStatus) { - - // Catch interactive cycles and other duplications that may be - // triggered from other gui components. - if (t == time) - return; - - if (Debug.debugging("clock")) { - Debug.output("Clock.setTime: " + t + " for " + timeStatus); - } - - time = t; - fireClockUpdate(timeStatus); - } - - /** - * The method that delivers the current time status to the - * TimeEventListeners. - */ - protected void fireClockUpdate(TimerStatus timerStatus) { - fireUpdateTime(TimeEvent.create(this, - // time, time - systemTime, simTime + time - systemTime, - time, - systemTime, - simTime, - timerStatus)); - } - - /** - * Get the current time. - */ - public long getTime() { - return time; - } - - /** - * Method to call to start the timer. - */ - public void startClock() { - if (!timer.isRunning()) { - firePropertyChange(TIMER_STATUS, - TimerStatus.STOPPED, - (getClockDirection() > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD)); - fireClockUpdate(getClockDirection() > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD); - } - if (Debug.debugging("clock")) { - Debug.output("Clock: Starting clock"); - } - timer.restart(); - } - - /** - * Method to call to stop the timer. - */ - public void stopClock() { - if (timer.isRunning()) { - firePropertyChange(TIMER_STATUS, - (getClockDirection() > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD), - TimerStatus.STOPPED); - fireClockUpdate(TimerStatus.STOPPED); - timer.stop(); - } - } - - /** - * Set whether time increases or decreases when the clock is run. If - * direction is zero or greater, clock runs forward. If direction is - * negative, clock runs backward. - */ - public void setClockDirection(int direction) { - TimerStatus oldDirection = clockDirection > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD; - - if (direction >= 0) { - clockDirection = 1; - } else { - clockDirection = -1; - } - - TimerStatus newDirection = clockDirection > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD; - - if (timer.isRunning()) { - if (oldDirection != newDirection) { - firePropertyChange(TIMER_STATUS, oldDirection, newDirection); - fireClockUpdate(newDirection); - } - } - } - - /** - * Get whether time increases or decreases when the clock is run. If - * direction is zero or greater, clock runs forward. If direction is - * negative, clock runs backward. - */ - public int getClockDirection() { - return clockDirection; - } - - /** - * Move the clock forward one time increment. - */ - public void stepForward() { - changeTimeBy(timeIncrement, timeWrap, TimerStatus.STEP_FORWARD); - } - - /** - * Move the clock back one time increment. - */ - public void stepBackward() { - changeTimeBy(-timeIncrement, timeWrap, TimerStatus.STEP_BACKWARD); - } - - // ///// Convenience methods for ReadTimeHandler - - /** - * Call setTime with the amount given added to the current time. The amount - * should be negative if you are going backward through time. You need to - * make sure manageGraphics is called for the map to update. - *

- * - * @param amount to change the current time by, in milliseconds. - */ - protected void changeTimeBy(long amount) { - changeTimeBy(amount, timeWrap, (amount >= 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD)); - } - - /** - * Call setTime with the amount given added to the current time. The amount - * should be negative if you are going backward through time. You need to - * make sure manageGraphics is called for the map to update. - * - * @param amount to change the current time by, in milliseconds. - * @param wrapAroundTimeLimits if true, the time will be set as if the start - * and end times of the scenario are connected, so that moving the - * time past the time scale in either direction will put the time at - * the other end of the scale. - */ - protected void changeTimeBy(long amount, boolean wrapAroundTimeLimits) { - changeTimeBy(amount, - wrapAroundTimeLimits, - (amount >= 0 ? TimerStatus.FORWARD : TimerStatus.BACKWARD)); - } - - /** - * Call setTime with the amount given added to the current time. The amount - * should be negative if you are going backward through time. You need to - * make sure manageGraphics is called for the map to update. - * - * @param amount to change the current time by, in milliseconds. - * @param wrapAroundTimeLimits if true, the time will be set as if the start - * and end times of the scenario are connected, so that moving the - * time past the time scale in either direction will put the time at - * the other end of the scale. - * @param timeStatus the string given to the TimeEvent to let everyone know - * why the time is changing. Usually TIMER_TIME_STATUS if the timer - * went off normally, or TIME_SET_STATUS if the time is being - * specifically set to something. - */ - protected void changeTimeBy(long amount, boolean wrapAroundTimeLimits, - TimerStatus timeStatus) { - - long oldTime = getTime(); - long newTime; - boolean stopClock = false; - - newTime = oldTime + amount; - - if (newTime > endTime || newTime < startTime) { - if (wrapAroundTimeLimits) { - newTime = (amount >= 0 ? startTime : endTime); - } else { - newTime = (amount >= 0 ? endTime : startTime); - stopClock = true; - } - } - - if (Debug.debugging("clock")) { - Debug.output("Clock " - + (stopClock ? ("stopping clock at (" + newTime) - : ("changing time by [" + amount + "] to (" + newTime)) - + ") : " + timeStatus); - } - - // Should set the new time before telling everyone the clock is stopped. - setTime(newTime, timeStatus); - - if (stopClock) { - stopClock(); - } - } - - // /////////////////////// - // ActionListener method - // /////////////////////// - - /** - * ActionListener interface, gets called when the timer goes ping if there - * isn't a command with the ActionEvent. Otherwise, the command should be - * filled in. - */ - public void actionPerformed(ActionEvent ae) { - if (ae.getSource() == getTimer()) { - - // Normal time change call. - // changeTimeBy(timeIncrement * clockDirection); - - // Hacked version, so that the video can get events that - // they will listen to if the clock is running backwards. - changeTimeBy(timeIncrement * clockDirection, - timeWrap, - clockDirection < 0 ? TimerStatus.UPDATE - : TimerStatus.FORWARD); - } - } - - // ////////////////////////////// - // PropertyChangeListener method - // ////////////////////////////// - - /** - * PropertyChangeListener method called when the bounds on a - * TimeBoundsProvider changes, so so that the range of times can be - * adjusted. - */ - public void propertyChange(PropertyChangeEvent pce) { - resetTimeBounds(); - } - - // ////////////////////////////// - // TimeBoundsProvider methods - // ////////////////////////////// - - /** - * Add a TimeBoundsProvider to the clock, so it knows the bounds of it's - * time range. - */ - public void addTimeBoundsProvider(TimeBoundsProvider tbp) { - if (!timeBoundsProviders.contains(tbp)) { - timeBoundsProviders.add(tbp); - resetTimeBounds(); - } - } - - public void removeTimeBoundsProvider(TimeBoundsProvider tbp) { - timeBoundsProviders.remove(tbp); - resetTimeBounds(); - } - - public void clearTimeBoundsProviders() { - timeBoundsProviders.clear(); - resetTimeBounds(); - } - - // ////////////////////////////// - // TimeBoundsListener methods - // ////////////////////////////// - - /** - * Add a TimeBoundsListener to the clock, so it knows who to tell when the - * time bounds change. - */ - public void addTimeBoundsListener(TimeBoundsListener tbl) { - if (!timeBoundsListeners.contains(tbl)) { - timeBoundsListeners.add(tbl); - } - } - - public void removeTimeBoundsListener(TimeBoundsListener tbl) { - timeBoundsListeners.remove(tbl); - } - - public void clearTimeBoundsListeners() { - timeBoundsListeners.clear(); - } - - public void fireUpdateTimeBounds(TimeBoundsEvent tbe) { - if (timeBoundsListeners != null) { - List copy; - synchronized(timeBoundsListeners) { - copy = new ArrayList(timeBoundsListeners); - } - for (Iterator it = copy.iterator(); it.hasNext();) { - it.next().updateTimeBounds(tbe); - } - } - } - - // ////////////////////////////// - // TimeEventListener methods - // ////////////////////////////// - - /** - * Add a TimeEventListener to the clock, so it knows who to update when the - * time changes. - */ - public void addTimeEventListener(TimeEventListener tel) { - if (!timeEventListeners.contains(tel)) { - timeEventListeners.add(tel); - } - } - - public void removeTimeEventListener(TimeEventListener tel) { - timeEventListeners.remove(tel); - } - - public void clearTimeEventListeners() { - timeEventListeners.clear(); - } - - public void fireUpdateTime(TimeEvent te) { - if (timeEventListeners != null) { - List copy; - synchronized(timeEventListeners) { - copy = new ArrayList(timeEventListeners); - } - for (Iterator it = copy.iterator(); it.hasNext();) { - it.next().updateTime(te); - } - } - } - - // ////////////////////////////// - // Generic Clock Methods - // ////////////////////////////// - - /** - * Method to call when TimeBoundsProviders change, in order to query them - * and figure out what the new time range is. - */ - public void resetTimeBounds() { - TimeBounds oldtb = new TimeBounds(startTime, endTime); - - startTime = Long.MAX_VALUE; - endTime = Long.MIN_VALUE; - int activeTimeBoundsProviderCount = 0; - - List copy; - synchronized(timeBoundsProviders) { - copy = new ArrayList(timeBoundsProviders); - } - for (Iterator it = copy.iterator(); it.hasNext();) { - TimeBoundsProvider tbp = it.next(); - if (tbp.isActive()) { - activeTimeBoundsProviderCount++; - TimeBounds bounds = tbp.getTimeBounds(); - if (bounds != null && !bounds.isUnset()) { - addTime(bounds.getStartTime()); - addTime(bounds.getEndTime()); - - if (Debug.debugging("clock")) { - Debug.output("Clock.resetTimeBounds(" - + tbp.getClass().getName() + ") adding " - + bounds); - } - } - } else { - if (Debug.debugging("clock")) { - Debug.output("Clock.resetTimeBounds(" - + tbp.getClass().getName() + ") not active"); - } - } - } - - // system time is startTime, let other components track their - // relative system time if it is important to them. - systemTime = startTime; - - /* - * First thing, let all the TimeBoundsProviders know what the overall - * TimeBounds is, in case they need to update their GUI or something. - */ - TimeBounds tb = new TimeBounds(startTime, endTime); - for (Iterator it = copy.iterator(); it.hasNext();) { - it.next().handleTimeBounds(tb); - } - - long currentTime = time; - // If the number of activeTimeBoundsProviders is zero, reset the clock - // to the startTime, which should be Long.MAX_TIME, and this should - // reset it when some TimeBoundsProvider is made active.x - if (activeTimeBoundsProviderCount == 0) { - setTime(startTime); - } else if (currentTime < startTime || currentTime == Long.MAX_VALUE) { - setTime(startTime); - } else if (currentTime > endTime) { - setTime(endTime); - } - - /* - * Now, update the TimeBoundsListeners, so they can update their GUIs. - */ - fireUpdateTimeBounds(new TimeBoundsEvent(this, tb, oldtb)); - - if (tb.isUnset()) { - fireUpdateTime(TimeEvent.NO_TIME); - } - - } - - /** - * Add a time to the time range, fire a TimeBoundsEvent if the time range - * changes. - * - * @param timeStamp in milliseconds - */ - public void addTimeToBounds(long timeStamp) { - long oldStartTime = startTime; - long oldEndTime = endTime; - - addTime(timeStamp); - - if (oldStartTime != startTime || oldEndTime != endTime) { - fireUpdateTimeBounds(new TimeBoundsEvent(this, new TimeBounds(oldStartTime, oldEndTime), new TimeBounds(startTime, endTime))); - } - } - - /** - * Add a time to the time range. - * - * @param timeStamp in milliseconds - */ - protected void addTime(long timeStamp) { - - if (timeStamp < startTime) { - if (Debug.debugging("clock")) { - Debug.output("Clock: setting startTime: " + timeStamp); - } - - startTime = timeStamp; - } - - if (timeStamp > endTime) { - if (Debug.debugging("clock")) { - Debug.output("Clock: setting endTime: " + timeStamp); - } - - endTime = timeStamp; - } - - // This is actually resetting the time even if it doesn't need to be - // reset, since startTime and endTime really can be in the middle of - // being redefined. The time check should happen after all times have - // been added, the old and new system times have been checked, and then - // we'll have a better idea of where time should be. - // if (time < startTime) { - // time = (long) startTime; - // } else if (time > endTime) { - // time = (long) endTime; - // } // else, leave it alone... - - } - - public long getStartTime() { - return startTime; - } - - public long getEndTime() { - return endTime; - } - - protected long systemTime = 0; - - protected long simTime = 0; - - /** - * Set the system time and simulation time. These times are used in relation - * to any offsets. System time usually gets reset when the time bounds are - * reset. - * - * @param sysTime the system (computer) time used in TimeEvents. - * @param simulationTime the scenario time used in TimeEvents. - */ - public void setBaseTimesForTimeEvent(long sysTime, long simulationTime) { - systemTime = sysTime; - simTime = simulationTime; - } - - public long getSimTime() { - return simTime; - } - - public long getSystemTime() { - return systemTime; - } - - // ////////////////////////// - // Timer management methods - // ////////////////////////// - - /** - * Get the timer being used for automatic updates. May be null if a timer is - * not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, you can set - * the timer to do that. Set it to null to disable it. If the current timer - * is not null, the graphic loader is removed as an ActionListener. If the - * new one is not null, the graphic loader is added as an ActionListener. - */ - public void setTimer(Timer t) { - if (timer != null) { - timer.stop(); - timer.removeActionListener(this); - } - - timer = t; - if (timer != null) { - timer.removeActionListener(this); - timer.addActionListener(this); - } - } - - /** - * Creates a timer with the current updateInterval and calls setTimer(). - */ - public void createTimer() { - Timer t = new Timer(updateInterval, this); - t.setInitialDelay(0); - setTimer(t); - } - - /** - * Get a list of TimerRateHolders. - */ - public List getTimerRates() { - return timerRates; - } - - /** - * Make sure the List contains TimerRateHolders. - */ - public void setTimerRates(List rates) { - timerRates = rates; - } - - // //////////////////// - // OMComponent methods - // //////////////////// - - /** - * @param prefix string prefix used in the properties file for this - * component. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String timeFormatString = properties.getProperty(prefix - + TimeFormatProperty, - ((SimpleDateFormat) timeFormat).toPattern()); - - timeFormat = new SimpleDateFormat(timeFormatString); - timerRates = TimerRateHolder.getTimerRateHolders(prefix, properties); - } - - /** - * OMComponent method, called when new components are added to the - * MapHandler. Lets the Clock find TimeBoundsProviders that have been added - * to the application, so that the Clock can register itself as a - * PropertyChangeListener. - */ - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof TimeBoundsProvider) { - if (Debug.debugging("clock")) { - Debug.output("Clock.findAndInit(TimeBoundsProvider): " - + someObj.getClass().getName()); - } - addTimeBoundsProvider((TimeBoundsProvider) someObj); - } - } - - /** - * OMComponent method, called when new components are removed from the - * MapHandler. Lets the Clock unregister itself as PropertyChangeListener to - * TimeBoundsProviders. - */ - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof TimeBoundsProvider) { - removeTimeBoundsProvider((TimeBoundsProvider) someObj); - } - } - - /** - * Adds a PropertyChangeListener to this Clock, so that object can receive - * time PropertyChangeEvents. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl) { - if (Debug.debugging("clock")) { - Debug.output("Clock: adding property change listener"); - } - - super.addPropertyChangeListener(TIMER_STATUS, pcl); - initializePropertyChangeListener(pcl); - } - - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener pcl) { - super.addPropertyChangeListener(propertyName, pcl); - initializePropertyChangeListener(pcl); - } - - /** - * Fires Propertyevents to new PropertyChangeListeners so they get the - * latest info. - */ - protected void initializePropertyChangeListener(PropertyChangeListener pcl) { - TimerStatus runningStatus = timer.isRunning() ? (getClockDirection() > 0 ? TimerStatus.FORWARD - : TimerStatus.BACKWARD) - : TimerStatus.STOPPED; - firePropertyChange(TIMER_STATUS, null, runningStatus); - fireClockUpdate(runningStatus); - } - - /** - * @return true if timer is running. - */ - public boolean isRunning() { - return timer.isRunning(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/RealTimeHandler.java b/src/core/src/main/java/com/bbn/openmap/time/RealTimeHandler.java deleted file mode 100644 index 6b54ccc6b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/RealTimeHandler.java +++ /dev/null @@ -1,133 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/RealTimeHandler.java,v $ -// $RCSfile: RealTimeHandler.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:50 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -/** - * The RealTimeHandler interface describes an object that has to deal - * with a timer that controls time on a different scale. For instance, - * the timer may be controlling objects on a map that move over days, - * where days in the scenario time are represented by several seconds - * on the timer. - */ -public interface RealTimeHandler { - - /** - * Property name fired for time PropertyChangeEvents dealing with general - * TimeEvents, when a clock is being started, stopped or jumped to a new - * location. - */ - public final static String TIMER_STATUS = "TIMER_STATUS_PROPERTY"; - - /** - * Set the timer interval, or how often the timer updates. - * - * @param interval number of milliseconds between updates. - */ - public void setUpdateInterval(int interval); - - /** - * Get the timer interval, or how often the timer updates. - * - * @return interval number of milliseconds between updates. - */ - public int getUpdateInterval(); - - /** - * Set the number of scenario units that pass when the timer - * updates within its interval. - * - * @param pace a number that means something to the - * RealTimeHandler. - */ - public void setPace(int pace); - - /** - * Get the number of scenario units that pass when the timer - * updates within its interval. - * - * @return a number that means something to the RealTimeHandler. - */ - public int getPace(); - - /** - * Set the current time value for the timer. The meaning of the - * time value depends on the RealTimeHandler. - * - * @param time - */ - public void setTime(long time); - - /** - * Get the current time value for the timer. The meaning of the - * time value depends on the RealTimeHandler. - * - * @return time - */ - public long getTime(); - - /** - * Start the timer. - */ - public void startClock(); - - /** - * Stop the timer. - */ - public void stopClock(); - - /** - * Set whether time increases or decreases when the clock is run. - * If direction is zero or greater, clock runs forward. If - * direction is negative, clock runs backward. - */ - public void setClockDirection(int direction); - - /** - * Get whether time increases or decreases when the clock is run. - * If direction is zero or greater, clock runs forward. If - * direction is negative, clock runs backward. - */ - public int getClockDirection(); - - /** - * Move the clock forward one clock interval. - */ - public void stepForward(); - - /** - * Move the clock back one clock interval. - */ - public void stepBackward(); - - /** - * Add a listener for TimeEvents describing what the handler is up to. - * @param listener - */ - public void addTimeEventListener(TimeEventListener listener); - - /** - * Remove a listener so it stops receiving TimeEvents. - * @param listener - */ - public void removeTimeEventListener(TimeEventListener listener); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeBounds.java b/src/core/src/main/java/com/bbn/openmap/time/TimeBounds.java deleted file mode 100644 index 366c4ef17..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeBounds.java +++ /dev/null @@ -1,128 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/time/TimeBounds.java,v $ -// $RCSfile: TimeBounds.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.io.Serializable; - -import com.bbn.openmap.util.HashCodeUtil; - -/** - * A class for holding a range of times. - */ -public class TimeBounds - implements Serializable { - - protected long startTime; - protected long endTime; - - /** - * Creates a TimeBounds object ready for times to be added to it. The - * starting time is set to Long.MAX_VALUE, the end time is set to - * Long.MIN_VALUE, so any time addition will cause start and end times to be - * replaced. - */ - public TimeBounds() { - setTimes(Long.MAX_VALUE, Long.MIN_VALUE); - } - - public TimeBounds(long start, long end) { - setTimes(start, end); - } - - public void setTimes(long start, long end) { - startTime = start; - endTime = end; - } - - public long getStartTime() { - return startTime; - } - - public long getEndTime() { - return endTime; - } - - public void reset() { - startTime = Long.MAX_VALUE; - endTime = Long.MIN_VALUE; - } - - /** - * Add a time to the bounds, resetting the start and end time as necessary. - * - * @param timeStamp in milliseconds - */ - public void addTimeToBounds(long timeStamp) { - - if (timeStamp < startTime) { - startTime = timeStamp; - } - - if (timeStamp > endTime) { - endTime = timeStamp; - } - } - - public String toString() { - return "TimeBounds[start=" + startTime + ", end=" + endTime + "]"; - } - - /** - * Add the start and end times of provided TimeBounds to this TimeBounds. - * - * @param timeBounds - */ - public void addTimeToBounds(TimeBounds timeBounds) { - addTimeToBounds(timeBounds.getStartTime()); - addTimeToBounds(timeBounds.getEndTime()); - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TimeBounds timeBounds = (TimeBounds) obj; - return (startTime == timeBounds.getStartTime() && endTime == timeBounds.getEndTime()); - } - - public boolean isUnset() { - return startTime == Long.MAX_VALUE && endTime == Long.MIN_VALUE; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, startTime); - result = HashCodeUtil.hash(result, endTime); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsEvent.java b/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsEvent.java deleted file mode 100644 index c68a65df8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsEvent.java +++ /dev/null @@ -1,96 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.time; - -/** - * Contains the message from a TimeBoundsHandler to a TimeBoundsListener. If the - * new TimeBounds is null, then the TimeBoundsHandler has gone inactive (nothing - * providing time bounds). If it isn't and the old TimeBounds is null, the - * TimeBoundsHandler has gone active (something is now providing time bounds). - * - * @author dietrick - */ -public class TimeBoundsEvent { - - protected TimeBoundsHandler source; - protected TimeBounds newTimeBounds; - protected TimeBounds oldTimeBounds; - protected boolean induceGraphicalUpdate; - - public TimeBoundsEvent(TimeBoundsHandler source, TimeBounds ntb, TimeBounds otb) { - this.source = source; - this.newTimeBounds = ntb; - this.oldTimeBounds = otb; - this.induceGraphicalUpdate = true; - } - - /** - * The TimeBoundsHandler that is sending the message. - * - * @return source of time bounds message - */ - public TimeBoundsHandler getSource() { - return source; - } - - /** - * @return if null, the TimeBoundsHandler is now inactive. Otherwise, - * returns the updated TimeBounds. - */ - public TimeBounds getNewTimeBounds() { - return newTimeBounds; - } - - /** - * Only really used to indicate when a TimeBoundsHandler has gone active, if - * this is null and the new TimeBounds isn't. - * - * @return old time bounds - */ - public TimeBounds getOldTimeBounds() { - return oldTimeBounds; - } - - /** - * @return whether this event should cause any graphical changes. (Set to - * false if you're firing multiple events and you want only one of - * them - generally the last one, naturally - to begin the work of - * updating the display.) - */ - public boolean isInduceGraphicalUpdate() { - return induceGraphicalUpdate; - } - - /** - * @param induceGraphicalUpdate Whether this event should cause any - * graphical changes. (Set to false if you're firing multiple events - * and you want only one of them - generally the last one, naturally - * - to begin the work of updating the display.) - */ - public void setInduceGraphicalUpdate(boolean induceGraphicalUpdate) { - this.induceGraphicalUpdate = induceGraphicalUpdate; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsHandler.java b/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsHandler.java deleted file mode 100644 index 65c004c83..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.time; - -/** - * Describes a component that listens to TimeBoundsProviders, for the purpose - * of figuring out the overall time bounds when contributions to the bounds will - * be made from several other objects, some of which may or may not be active. A - * TimeBoundsHandler is the go-between object between TimeBoundsProviders and - * TimeBoundsListeners. The TimeBoundsHandler will look for TimeBoundsListeners - * in the MapHandler and will notify them when the overall time bounds change. - * - * @author dietrick - */ -public interface TimeBoundsHandler { - - public void addTimeBoundsProvider(TimeBoundsProvider tbp); - - public void removeTimeBoundsProvider(TimeBoundsProvider tbp); - - public void clearTimeBoundsProviders(); - - public void resetTimeBounds(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsListener.java b/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsListener.java deleted file mode 100644 index 9537cd4fa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsListener.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/time/TimeBoundsListener.java,v $ -// $RCSfile: TimeBoundsListener.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.beans.PropertyChangeListener; - -/** - * A component that is interested in knowing about time bounds, i.e. a window of - * time. A TimeBoundsHandler will notify the listener when the time bounds - * changes. - */ -public interface TimeBoundsListener extends PropertyChangeListener { - - /** - * This method will be called on the TimeBoundsListener to let it know that - * the time bounds have changed. - * - * @param tbe TimeBoundsEvent with the source of the change along with the - * old and new values. - */ - void updateTimeBounds(TimeBoundsEvent tbe); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsProvider.java b/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsProvider.java deleted file mode 100644 index c4eb7f3ef..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeBoundsProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/time/TimeBoundsProvider.java,v $ -// $RCSfile: TimeBoundsProvider.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -/** - * A component that can provide information about a time range it cares about. - * Looks for TimeBoundsHandlers and adds them to itself. The TimeBoundsHandler - * will also look for TimeBoundsProviders and add them to itself, two-way - * connection, because they both have to initial communication at different - * times. - */ -public interface TimeBoundsProvider { - - /** - * A method called on the TimeBoundsProvider to retrieve the provider's time - * bounds. - */ - public TimeBounds getTimeBounds(); - - /** - * A method called on the TimeBoundsProvider to inform it of the overall - * time bounds, in case some external time bounds values are being set by - * another component and this provider wants to react to those bounds in - * some way. - */ - public void handleTimeBounds(TimeBounds tb); - - /** - * A query that can be made to the TimeBoundsProvider asking it if it is - * active, and if it's time bounds should be considered. - */ - public boolean isActive(); - - /** - * An accessor that switches the TimeBoundsProvider on/off. - */ - public void setActive(boolean active); - - /** - * The TimeBoundsProvider keep track of the handlers it needs to notify when - * the bounds or activeness changes. Called when a new handler needs to - * know. - */ - public void addTimeBoundsHandler(TimeBoundsHandler tbh); - - /** - * The TimeBoundsProvider keep track of the handlers it needs to notify when - * the bounds or activeness changes. Called when a handler doesn't need to - * know. - */ - public void removeTimeBoundsHandler(TimeBoundsHandler tbh); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeEvent.java b/src/core/src/main/java/com/bbn/openmap/time/TimeEvent.java deleted file mode 100644 index d9593a8cc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeEvent.java +++ /dev/null @@ -1,141 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/darwars/ambush/aar/src/com/bbn/ambush/time/TimeEvent.java,v $ -// $RCSfile: TimeEvent.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.io.Serializable; - -/** - * The heartbeat of the application that indicates what the current display time - * is, for all other components to react to. It might reflect the current system - * time, or the time that should be reflected in some recording playback. - * - * @author dietrick - */ -public class TimeEvent implements Serializable { - - /** - * The source of the TimeEvent. - */ - protected Object source; - /** - * The current system time, millis from unix epoch. - */ - protected long systemTime; - /** - * The current offset time, in millis from the start of the time frame of - * interest. - */ - protected long offsetTime; - /** - * The current simulation time, if the current system time does not - * correspond to the time frame of the data. - */ - protected long simTime; - /** - * Description of how/why time changed. - */ - protected TimerStatus timerStatus; - - public final static TimeEvent NO_TIME = new TimeEvent(null, Long.MIN_VALUE, Long.MAX_VALUE, Long.MAX_VALUE, TimerStatus.INACTIVE); - - /** - * Create a time event. - * - * @param src the object creating the time event. - * @param systemTime the current system time, millis from the epoch. - * @param offsetTime the current offset time, in millis from the start of - * the mission or media. - * @param simTime the current simulation time, in millis from the start of - * the simulation clock. - * @param timerStatus - */ - public TimeEvent(Object src, long systemTime, long offsetTime, - long simTime, TimerStatus timerStatus) { - this.source = src; - this.systemTime = systemTime; - this.offsetTime = offsetTime; - this.simTime = simTime; - this.timerStatus = timerStatus; - } - - /** - * Create a time event, with the option of receiving the NO_TIME event if - * the time is Long.MIN_VALUE and the system time and simulation time are - * Long.MAX_VALUE. - * - * @param src the object creating the time event. - * @param time the current time of the clock, millis from the epoch. - * @param systemTime the time of the start of the media, in millis from - * epoch. Subtracted from the time, it should give the offset time - * from the start of the mission or media. - * @param simTime the starting time within the simulation of the currently - * active mission or media, in millis. When the offset time (time - - * system time) is added to this time, you should have the current - * game time. - * @param timerStatus to describe what kind of TimeEvent should be - * created. - * @return a TimeEvent, or TimeEvent.NO_TIME object if the time values - * indicate that no time has been set on the clock. - */ - public static TimeEvent create(Object src, long time, long systemTime, - long simTime, TimerStatus timerStatus) { - if (time == Long.MIN_VALUE || time == Long.MAX_VALUE) { - return NO_TIME; - } - - return new TimeEvent(src, time, time - systemTime, simTime + time - - systemTime, timerStatus); - } - - public Object getSource() { - return source; - } - - public long getSystemTime() { - return systemTime; - } - - public long getOffsetTime() { - return offsetTime; - } - - public long getSimTime() { - return simTime; - } - - /** - * Returns the String identifying the timer action (TIMER_FORWARD, - * TIMER_STOPPED, TIMER_TIME_STATUS, ...). - * - * @return String identifying what's going on with the timer. - */ - public TimerStatus getTimerStatus() { - return timerStatus; - } - - public String toString() { - return "TimeEvent: " + timerStatus + " [" + offsetTime + ", " - + systemTime + ", " + simTime + "]"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimeEventListener.java b/src/core/src/main/java/com/bbn/openmap/time/TimeEventListener.java deleted file mode 100644 index 07db10f3f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimeEventListener.java +++ /dev/null @@ -1,36 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.time; - -/** - * A TimeEventListener is interested in the current time setting, and why the - * time has changed to that particular value. The Clock sends out TimeEvents, so - * anything that should be listening to the Clock should be a TimeEventListener. - * - * @author dietrick - */ -public interface TimeEventListener { - void updateTime(TimeEvent te); -} diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimerRateHolder.java b/src/core/src/main/java/com/bbn/openmap/time/TimerRateHolder.java deleted file mode 100644 index d0e9668b9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimerRateHolder.java +++ /dev/null @@ -1,239 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/time/TimerRateHolder.java,v $ -// $RCSfile: TimerRateHolder.java,v $ -// $Revision: 1.1 $ -// $Date: 2007/09/25 17:30:35 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.io.Serializable; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A convenience class that keeps track of a relationship between real-time - * changes and scenario-time changes. - */ -public class TimerRateHolder implements PropertyConsumer, Serializable { - - private static final long serialVersionUID = 1L; - /** - * The string used for the default pace baseline ("00:00:00"). Needs to match - * the pace format. - */ - public final static String DEFAULT_PACE_BASELINE_VALUE = "00:00:00"; - /** - * The string used for the default pace format ("HH:mm:ss"). - */ - public final static String DEFAULT_PACE_FORMAT = "HH:mm:ss"; - - /** - * Property used to describe a list of properties for TimerRateHolders - * (timerRates) - */ - public final static String TimerRatesProperty = "timerRates"; - - /** - * PaceFormatProperty represents the property used for describing the pace - * format (paceFormat). - */ - public final static String PaceFormatProperty = "paceFormat"; - /** - * PaceBaselineProperty represents the property used for baselining the pace - * value (paceBaseline). - */ - public final static String PaceBaselineProperty = "paceBaseline"; - /** - * Clock that describes how often the pace value is applied to the time value - * (clockIntervalMillis). - */ - public final static String ClockIntervalProperty = "clockIntervalMillis"; - /** The property used for the pace setting (pace). */ - public final static String PaceProperty = "pace"; - - /** - * Display label for this Timer rate. - */ - protected String label; - /** - * The number of milliseconds that the timer should wait between updates. - */ - protected long clockInterval; - /** - * The pace is the amount of time that should pass, in simulation time, when the - * timer gets updated. If the clock is updating every second, and you have the - * pace set for 1 hour, then the situation controlled by the application's clock - * will be updated 1 hour every second. - */ - protected long pace; - /** - * The format used in the properties to note the pace. Kept in order to write - * out the format if that's needed. - */ - protected SimpleDateFormat paceFormat; - /** - * The baseline used to normalize the pace setting. Defaults to "OO:OO:OO". - */ - protected String paceZero; - /** - * Flag that denotes whether the TimerRateHolder has be successfully set. - */ - protected boolean valid = false; - /** - * The prefix used to set the properties, saved in case the properties are - * retrieved. - */ - protected String propPrefix; - - /** - * Create a TimerRateHolder with the default pace format and value (00:00:00). - */ - public TimerRateHolder() { - paceFormat = new SimpleDateFormat(DEFAULT_PACE_FORMAT); - paceZero = DEFAULT_PACE_BASELINE_VALUE; - } - - /** - * Create a TimerRateHolder with a date format, and a baseline time. The default - * baseline time is "00:00:00", so if you need to change that, use this - * constructor. The pace for this TimerRateHolder should be a relative amount of - * time, and that relativity, taking into account the locale offset to GMT, is - * given by the baseline time. The baseline time should match the format given. - */ - public TimerRateHolder(SimpleDateFormat simpleDateFormat, String dpz) { - paceFormat = simpleDateFormat; - paceZero = dpz; - } - - public void setLabel(String lab) { - label = lab; - } - - public String getLabel() { - return label; - } - - public void setPace(long pace) { - this.pace = pace; - } - - public long getPace() { - return pace; - } - - public void setClockInterval(long cli) { - clockInterval = cli; - } - - public long getClockInterval() { - return clockInterval; - } - - public String toString() { - return "TimePanel.TimerRateHolder [" + label + ", clock:" + clockInterval + ", pace:" + pace + "] (" + valid - + ")"; - } - - public void setProperties(Properties props) { - setProperties(null, props); - } - - public void setProperties(String prefix, Properties props) { - - propPrefix = prefix; - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - try { - label = props.getProperty(prefix + Layer.PrettyNameProperty); - clockInterval = PropUtils.longFromProperties(props, prefix + ClockIntervalProperty, -1L); - String paceString = props.getProperty(prefix + PaceProperty); - pace = paceFormat.parse(paceString).getTime() - paceFormat.parse(paceZero).getTime(); - valid = true; - - } catch (NullPointerException npe) { - Debug.error("TimerRateHolder caught NPE: " + npe.getMessage()); - } catch (ParseException pe) { - Debug.error("TimerRateHolder parse exception: " + pe.getMessage()); - } - } - - public Properties getProperties(Properties props) { - return props; - } - - public Properties getPropertyInfo(Properties props) { - return props; - } - - public String getPropertyPrefix() { - return propPrefix; - } - - public void setPropertyPrefix(String p) { - propPrefix = p; - } - - public static List getTimerRateHolders(String prefix, Properties properties) { - - List timerRateHolders = new LinkedList(); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String paceFormatString = properties.getProperty(prefix + PaceFormatProperty, DEFAULT_PACE_FORMAT); - String paceBaselineString = properties.getProperty(prefix + PaceBaselineProperty, DEFAULT_PACE_BASELINE_VALUE); - SimpleDateFormat paceFormat = new SimpleDateFormat(paceFormatString); - - if (Debug.debugging("timerrateholder")) { - Debug.output("TimerRateHolder timer rate pace pattern: " + paceFormatString); - } - - String timerRatesString = properties.getProperty(prefix + TimerRatesProperty); - - if (timerRatesString != null) { - if (Debug.debugging("timerrateholder")) { - Debug.output("TimerRateHolder reading timer rates: " + timerRatesString); - } - - for (String ratePrefix : PropUtils.parseSpacedMarkers(timerRatesString)) { - TimerRateHolder trh = new TimerRateHolder(paceFormat, paceBaselineString); - trh.setProperties(prefix + ratePrefix, properties); - - if (trh.valid) { - timerRateHolders.add(trh); - if (Debug.debugging("timerrateholder")) { - Debug.output("TimerRateHolder adding " + trh); - } - } else { - if (Debug.debugging("timerrateholder")) { - Debug.output("TimerRateHolder NOT adding " + ratePrefix); - } - } - } - } - - return timerRateHolders; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/time/TimerStatus.java b/src/core/src/main/java/com/bbn/openmap/time/TimerStatus.java deleted file mode 100644 index 706d7caf7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/time/TimerStatus.java +++ /dev/null @@ -1,141 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/time/TimeConstants.java,v $ -// $RCSfile: TimeConstants.java,v $ -// $Revision: 1.5 $ -// $Date: 2007/09/25 17:31:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.time; - -import java.io.Serializable; - -import com.bbn.openmap.util.HashCodeUtil; - -/** - * TimerStatus objects accompany TimeEvents to describe what's going on with the - * application clock, or the reason the current time has changed. - */ -public class TimerStatus implements Serializable { - - /** - * Command string for clock controllers. - */ - public final static String TIMER_STEP_FORWARD = "Timer step forward"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_STEP_BACKWARD = "Timer step backward"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_FORWARD = "Timer run forward"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_BACKWARD = "Timer run backward"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_STOPPED = "Timer stopped"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_UPDATED = "Timer updated"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_ACTIVE = "Timer active"; - /** - * Command string for clock controllers. - */ - public final static String TIMER_INACTIVE = "Timer inactive"; - - /** - * Indicates that the clock has been moved incrementally forward, stepping - * by a set value controlled by some other mechanism. Not set when the clock - * is changed due to normal running. - */ - public final static TimerStatus STEP_FORWARD = new TimerStatus(TIMER_STEP_FORWARD); - /** - * Indicates that the clock has been moved incrementally backward, stepping - * by a set value controlled by some other mechanism. Not set when the clock - * is changed due to normal running. - */ - public final static TimerStatus STEP_BACKWARD = new TimerStatus(TIMER_STEP_BACKWARD); - /** - * Indicates the clock is running, and time has been incremented by the - * clock. - */ - public final static TimerStatus FORWARD = new TimerStatus(TIMER_FORWARD); - /** - * Indicates the clock is running, and time has been decremented by the - * clock. - */ - public final static TimerStatus BACKWARD = new TimerStatus(TIMER_BACKWARD); - /** - * Indicates that the clock is no longer running. - */ - public final static TimerStatus STOPPED = new TimerStatus(TIMER_STOPPED); - /** - * Used when the timer is moved to a specific value, not when the clock is - * running incrementally. Indicates a jump in time. - */ - public final static TimerStatus UPDATE = new TimerStatus(TIMER_UPDATED); - /** - * Indicates that the clock is active and may be sending events. - */ - public final static TimerStatus ACTIVE = new TimerStatus(TIMER_ACTIVE); - /** - * Indicates that the clock is inactive and will not be sending events. - */ - public final static TimerStatus INACTIVE = new TimerStatus(TIMER_INACTIVE); - - protected String description; - - public TimerStatus(String description) { - this.description = description; - } - - public String toString() { - return description; - } - - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TimerStatus ts = (TimerStatus) obj; - return ts == this; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - result = HashCodeUtil.hash(result, description); - return result; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBox.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBox.java deleted file mode 100644 index 195d0bc9e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBox.java +++ /dev/null @@ -1,323 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Dimension; -import java.awt.Image; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.image.BufferedImage; -import java.beans.BeanInfo; -import java.util.HashMap; -import java.util.Vector; - -import com.bbn.openmap.image.ImageScaler; -import com.bbn.openmap.util.Debug; - -/** - * The BeanBox class manages a set of java beans that are delivered to - * it from the {@link com.bbn.openmap.tools.beanbox.BeanPanel}via the - * {@link com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher}. An - * implementation of this abstract class is expected to be associated - * with an openmap layer. The abstract BeanBox class performs - * functions such as adding and removing beans from the associated - * openmap layer and provides support for moving beans on the layer - * and cut/copy/paste functionality. - *

- * Layer developers wishing to make use of the BeanBox's bean - * management capabilities should: - *

- *

    - *
  • Implement a layer specific version of this abstract class. - *
  • - *
  • Implement the - * {@link com.bbn.openmap.tools.beanbox.BeanBoxHandler}interface in - * the layer associated with the BeanBox implementation.
  • - *
- *

- * - * An implementation of this class should provide layer specific - * versions of at least the following abstract base class methods: - *

- *

    - *
  • addBean
  • - *
  • removeBean
  • - *
  • containsBean
  • - *
  • setBeanProperties
  • - *
  • getBeanAtLocation
  • - *
  • findEnclosingContainer (should always return null if - * implementation does not support - * {@link com.bbn.openmap.tools.beanbox.BeanContainer}s)
  • - *
  • relocateBean
  • - *
  • beanChanged
  • - *
- *

- * Additionally, an implementation of this class can optionally - * provide layer specific versions of the following base class - * methods: - *

- *

    - *
  • showSelected
  • - *
  • showCut
  • - *
  • showUnCut
  • - *
- *

- */ - -public abstract class BeanBox { - - private HashMap beanInfoMap; - - /** - * Default constructor initializes the BeanBox. - */ - public BeanBox() { - beanInfoMap = new HashMap(); - } - - /** - * Utility method to obtain the BeanInfo object associated with a - * bean class that the BeanBox knows about. Returns a null if none - * found. - */ - public BeanInfo getBeanInfoForBean(String beanClassName) { - BeanInfo beanInfo = (BeanInfo) beanInfoMap.get(beanClassName); - if (beanInfo == null) { - beanInfo = BeanPanel.findBeanInfo(beanClassName); - if (beanInfo != null) - beanInfoMap.put(beanClassName, beanInfo); - } - - return beanInfo; - } - - /** - * This method is called by the BeanBoxDnDCatcher to give the - * BeanBox the bean has has just been dropped on the map. - * - * @param object a Vector containing in the following order: the dropped - * bean object, its BeanInfo and a Point object containing - * the drop location. - */ - void addBean(Vector object) { - - if (object == null || object.size() != 3 - || !(object.get(1) instanceof BeanInfo) - || !(object.get(2) instanceof Point)) { - throw new IllegalArgumentException("bad drop object " + object); - } - - Object bean = object.get(0); - BeanInfo beanInfo = (BeanInfo) object.get(1); - Point point = (Point) object.get(2); - - beanInfoMap.put(bean.getClass().getName(), beanInfo); - - prepareForAddition(bean, beanInfo, point); - - } - - /** - * This method is called by a - * {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet}when - * the user closes the propertysheet window. - */ - void editComplete(Object bean) { - if (!containsBean(bean)) { - addBean(bean); - doSpecialHandling(bean); - } - } - - /** - * This method is called to prepare the bean for addition to the - * beanbox. In the base class implementation, this method calls - * the abstract setBeanProperties method. It then displays the - * property sheet for the bean, thereby giving the user a chance - * to edit the bean's properties before the bean is added to the - * beanbox. - */ - protected void prepareForAddition(Object bean, BeanInfo beanInfo, - Point location) { - - try { - setBeanProperties(bean, beanInfo, location); - createPropertySheet(bean); - } catch (Exception e) { - //System.out.println(e); - e.printStackTrace(); - } - - } - - /** - * Utility method to create and display a property sheet to show - * the specified bean's properties. - */ - protected void createPropertySheet(Object bean) throws Exception { - // Create a new Property Sheet. - GenericPropertySheet propertySheet = new GenericPropertySheet(bean, 575, 20, null, this); - propertySheet.setVisible(true); - } - - /** - * Checks if the specified bean should be added to a - * {@link com.bbn.openmap.tools.beanbox.BeanContainer}. - */ - protected void doSpecialHandling(Object bean) { - - // if bean is a container, add its id to our list of - // containers - // adding containers to other containers is not handled for - // now because of unresolved issues about treating - // over-lapping - // containers. - - if (!(bean instanceof BeanContainer)) { - - // check if the bean was dropped into a container, - // if so add it to the container - BeanContainer container = findEnclosingContainer(bean); - - if (container != null) - container.add(bean); - } - } - - /** - * Returns the image that the cursor will be set to when the - * specified bean is dragged over the map. Default implementation - * returns the image contained in the BeanInfo for the bean, or - * the default BeanPanel image if no image is found in the - * BeanInfo. - */ - protected Image getDragImage(Object bean) { - BeanInfo beanInfo = this.getBeanInfoForBean(bean.getClass().getName()); - - if (beanInfo == null) { - if (Debug.debugging("beanbox")) - Debug.output("No beanInfo found for bean: " + bean); - return BeanPanel.defaultBeanIcon.getImage(); - } - - Image img = beanInfo.getIcon(BeanInfo.ICON_COLOR_32x32); - - if (img == null) { - if (Debug.debugging("beanbox")) - Debug.output("No image found in beanInfo for bean: " + bean); - return BeanPanel.defaultBeanIcon.getImage(); - } - - Dimension d = Toolkit.getDefaultToolkit().getBestCursorSize(16, 16); - if (Debug.debugging("beanbox")) - Debug.output("" + d); - img = ImageScaler.getOptimalScalingImage(img,(int) d.getWidth(), - (int) d.getHeight(), BufferedImage.TYPE_INT_ARGB); - - return img; - } - - /** - * This method is called when the user selects a bean, usually as - * a a result of the clicking on it in a layer. An implementation - * of this class can override this method to highlight the - * selected bean using a mechanism specific to the openmap layer - * associated with that BeanBox. Base class method does nothing. - */ - public void showSelected(Object bean) {} - - /** - * This method is called when the user 'cuts' a bean, usually as a - * a result of the clicking on it in a layer and then pressing - * Ctrl-X. An implementation of this class can override this - * method to highlight the selected bean using a mechanism - * specific to the openmap layer associated with that BeanBox. - * Base class method does nothing. - */ - public void showCut(Object bean) {} - - /** - * This method is called when the user cancels a 'cut' operation, - * usually as a a result of pressing the ESC key. An - * implementation of this class can override this method to remove - * any highlights on the bean marked for cutting. Base class - * method does nothing. - */ - public void showUnCut(Object bean) {} - - /** - * This method is called when a bean is dropped on the layer - * associated with this BeanBox. - */ - public abstract void addBean(Object bean); - - /** - * This method is called when a bean is moved from the layer - * associated with this BeanBox to another layer. - */ - public abstract void removeBean(Object bean); - - /** - * This method is intended to check whether this BeanBox knows - * about the specified bean. - */ - public abstract boolean containsBean(Object bean); - - /** - * This method is called when a bean is dropped on the layer - * associated with this BeanBox. This method gives a chance to set - * the dropped bean's properties based on the information in its - * BeanInfo and the drop location. The called to addBean follows - * this call in the drop sequence. - */ - public abstract void setBeanProperties(Object bean, BeanInfo beanInfo, - Point location); - - /** - * Returns a bean contained in the layer at the specified map - * location. - * - * @return a bean Object or null if no bean is found at the - * location. - */ - public abstract Object getBeanAtLocation(Point pointOnMap); - - /** - * Returns a bean contained in the layer that implements the - * BeanContainer interface and which contains the specified bean. - * - * @return a BeanContainer object or null if no such container - * bean is found. - */ - public abstract BeanContainer findEnclosingContainer(Object bean); - - /** - * This method is called when a bean is moved from its present - * location to the newlocation within the layer associated with - * this BeanBox. - */ - public abstract void relocateBean(Object bean, BeanInfo beanInfo, - Point newLocation); - - /** - * This method is called by a propertysheet whenever a bean - * property changes. It is intended to provide a place for the - * layer developer to update the layer if required. - */ - public abstract void beanChanged(Object bean, String changedPropertyName); -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxDnDCatcher.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxDnDCatcher.java deleted file mode 100644 index 9f502931f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxDnDCatcher.java +++ /dev/null @@ -1,692 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Image; -import java.awt.Point; -import java.awt.datatransfer.Transferable; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSource; -import java.awt.dnd.DragSourceListener; -import java.awt.dnd.DropTarget; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.InputEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.beans.BeanInfo; -import java.beans.PropertyChangeListener; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.net.URL; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.ImageIcon; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.SwingConstants; -import javax.swing.border.Border; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.SoloMapComponent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.tools.dnd.ComponentDragGestureListener; -import com.bbn.openmap.tools.dnd.DefaultDnDCatcher; -import com.bbn.openmap.tools.dnd.DefaultTransferableObject; -import com.bbn.openmap.util.Debug; - -/** - * The BeanBoxDnDCatcher class manages all Java Drag-and-Drop events associated - * with openmap layers that implement the - * {@link com.bbn.openmap.tools.beanbox.BeanBoxHandler}interface. - */ -public class BeanBoxDnDCatcher extends DefaultDnDCatcher implements - SoloMapComponent, BeanContextChild, BeanContextMembershipListener, - PropertyChangeListener, Serializable, ProjectionListener, - LayerListener, ActionListener { - - static { - - setDefaultIcon(); - - } - - private Vector transferData; - private Point dropLocation; - - /** holds the currently selected bean */ - protected Object selectedBean = null; - - /** holds the serialized version of currently selected bean */ - protected ByteArrayOutputStream serBean = null; - - /** holds the map location of the currently selected bean */ - protected Point selectedBeanLocation = null; - - /** - * holds the {@link com.bbn.openmap.tools.beanbox.BeanBox}that manages the - * currently selected bean - */ - protected BeanBox selectedBeanBox = null; - - /** - * holds the openmap layer that contains the currently selected bean - */ - protected Layer selectedBeanLayer = null; - - /** holds the currently cut bean, if any */ - Object cutBean = null; - - /** - * contains BeanInfo objects hashed by the class names of the associated - * bean classes - */ - protected HashMap beanInfoMap = null; - - /** - * Constructs a new {@link com.bbn.openmap.tools.dnd.DnDListener} object. - */ - public BeanBoxDnDCatcher() { - this(new DragSource()); - } - - /** - * Constructs a new MouseDragGestureRecognizer given the DragSource for the - * Component. - * - * @param ds the DragSource for the Component - */ - public BeanBoxDnDCatcher(DragSource ds) { - this(ds, null); - } - - /** - * Construct a new MouseDragGestureRecognizer given the DragSource for the - * Component c, and the Component to observe. - * - * @param ds the DragSource for the Component c - * @param c the Component to observe - */ - public BeanBoxDnDCatcher(DragSource ds, Component c) { - this(ds, c, DnDConstants.ACTION_MOVE); - } - - /** - * Construct a new MouseDragGestureRecognizer given the DragSource for the - * Component c, and the Component to observe and the drag-and-drop action. - * - * @param ds the DragSource for the Component c - * @param c the Component to observe - * @param act the drag-and-drop action - */ - public BeanBoxDnDCatcher(DragSource ds, Component c, int act) { - this(ds, c, act, null); - } - - /** - * Construct a new MouseDragGestureRecognizer given the DragSource for the - * Component c, and the Component to observe. the drag-and-drop action and a - * DragGestureListener - * - * @param ds the DragSource for the Component c - * @param c the Component to observe - * @param act the drag-and-drop action - * @param dgl the DragGestureListener - */ - public BeanBoxDnDCatcher(DragSource ds, Component c, int act, - DragGestureListener dgl) { - super(ds, c, act, dgl); - dragSource = getDragSource(); - dragGestureListener = new ComponentDragGestureListener(this, this); - setSourceActions(DnDConstants.ACTION_MOVE); - - beanInfoMap = new HashMap(); - } - - /** - * Calls superclass method and then adds the KeyListener to someObj if - * someObj is of type OpenMapFrame. - */ - public void findAndInit(Object someObj) { - super.findAndInit(someObj); - if (someObj instanceof MapBean) { - - ((MapBean) someObj).addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent evt) { - if (evt.getModifiers() == InputEvent.CTRL_MASK - && evt.getKeyCode() == KeyEvent.VK_C) - copySelectedBean(); - else if (evt.getModifiers() == InputEvent.CTRL_MASK - && evt.getKeyCode() == KeyEvent.VK_V) - pasteSelectedBean(); - else if (evt.getModifiers() == InputEvent.CTRL_MASK - && evt.getKeyCode() == KeyEvent.VK_X) - cutSelectedBean(); - else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) - unCutSelectedBean(); - else if (evt.getKeyCode() == KeyEvent.VK_DELETE) - deleteSelectedBean(); - } - }); - } - } - - /** - * This method is called when the user chooses to copy a bean by some means - * such by by pressing Ctrl-C. This method tries to serialize the selected - * bean. If no bean is selected or the bean is not serializable, this method - * is a no-op. - */ - protected void copySelectedBean() { - if (Debug.debugging("beanbox")) - Debug.output("Enter> copySelectedBean"); - if (selectedBean == null || selectedBeanLocation == null) { - clearSelection(); - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - if (Debug.debugging("beanbox")) - Debug.output("selectedBeanLocation=" + selectedBeanLocation); - return; - } - - try { - serBean = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(serBean); - oos.writeObject(selectedBean); - } catch (Exception e) { - e.printStackTrace(); - clearSelection(); - if (Debug.debugging("beanbox")) - Debug.output("Exit> copySelectedBean"); - return; - } - - cutBean = null; - - if (Debug.debugging("beanbox")) - Debug.output("Exit> copySelectedBean"); - } - - /** - * This method is called when the user chooses to paste by some means (such - * by pressing Ctrl-V) a previously copied or cut bean. This method tries to - * deserialize the previously serialized bean. If the bean in question was - * cut, this method also removes it from from the source beanbox. The paste - * operation is treated the same as a drop operation. If no bean was - * previously copied or cut or if an error occurs during deserialization, - * this method is a no-op. - */ - protected void pasteSelectedBean() { - if (Debug.debugging("beanbox")) - Debug.output("Enter> pasteSelectedBean"); - - if (serBean == null) { - clearSelection(); - if (Debug.debugging("beanbox")) - Debug.output("Exit> pasteSelectedBean"); - return; - } - - BeanInfo beanInfo = (BeanInfo) beanInfoMap.get(selectedBean.getClass() - .getName()); - if (beanInfo == null) { - System.out.println("ERROR> BBDnDC::pasteSelectedBean: " - + "no cached BeanInfo found for bean " + selectedBean); - clearSelection(); - return; - } - - // if bean was cut, remove it from its present location - if (cutBean != null) { - selectedBeanBox.removeBean(selectedBean); - } - - Object deserBean = null; - - try { - ByteArrayInputStream bais = new ByteArrayInputStream(serBean.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(bais); - deserBean = ois.readObject(); - } catch (Exception e) { - e.printStackTrace(); - clearSelection(); - if (Debug.debugging("beanbox")) - Debug.output("Exit> pasteSelectedBean"); - return; - } - - // construct a transferData object - transferData = new Vector(); - transferData.add(deserBean); - transferData.add(beanInfo); - transferData.add(new Boolean(false)); // bean not being moved - - // let dropLocation be selectedBeanLocation - dropLocation = selectedBeanLocation; - - showPopUp(selectedBeanLayer); - - cutBean = null; - if (Debug.debugging("beanbox")) - Debug.output("Exit> pasteSelectedBean"); - } - - /** - * This method is called when the user chooses to cut a bean by some means - * such by by pressing Ctrl-X. This method tries to serialize the selected - * bean. If no bean is selected or the bean is not serializable, this method - * is a no-op. - */ - protected void cutSelectedBean() { - if (Debug.debugging("beanbox")) - Debug.output("Enter> cutSelectedBean"); - - if (selectedBean == null || selectedBeanLocation == null) { - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - if (Debug.debugging("beanbox")) - Debug.output("selectedBeanLocation=" + selectedBeanLocation); - clearSelection(); - return; - } - - try { - serBean = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(serBean); - oos.writeObject(selectedBean); - } catch (Exception e) { - e.printStackTrace(); - clearSelection(); - if (Debug.debugging("beanbox")) - Debug.output("Exit> copySelectedBean"); - return; - } - - cutBean = selectedBean; - - selectedBeanBox.showCut(selectedBean); - - if (Debug.debugging("beanbox")) - Debug.output("Exit> cutSelectedBean"); - } - - /** - * This method is called when the user chooses to cancel a cut operation on - * a bean by some means such by by pressing ESC. If no bean was marked for - * cutting this method is a no-op. - */ - protected void unCutSelectedBean() { - if (Debug.debugging("beanbox")) - Debug.output("Enter> unCutSelectedBean"); - - if (selectedBean == null || selectedBeanLocation == null) { - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - if (Debug.debugging("beanbox")) - Debug.output("selectedBeanLocation=" + selectedBeanLocation); - clearSelection(); - return; - } - - selectedBeanBox.showUnCut(selectedBean); - - clearSelection(); - - if (Debug.debugging("beanbox")) - Debug.output("Exit> unCutSelectedBean"); - } - - private void clearSelection() { - cutBean = null; - selectedBean = null; - selectedBeanLocation = null; - selectedBeanBox = null; - selectedBeanLayer = null; - serBean = null; - } - - /** - * This method is called when the user chooses to delete a bean by some - * means such by by pressing DEL. This method removes the selected bean from - * its beanbox. If no bean is selected this method is a no-op. - */ - protected void deleteSelectedBean() { - if (Debug.debugging("beanbox")) - Debug.output("Enter> deleteSelectedBean"); - - if (selectedBean == null || selectedBeanLocation == null) { - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - if (Debug.debugging("beanbox")) - Debug.output("selectedBeanLocation=" + selectedBeanLocation); - return; - } - - selectedBeanBox.removeBean(selectedBean); - cutBean = null; - - if (Debug.debugging("beanbox")) - Debug.output("Exit> deleteSelectedBean"); - } - - /** - * The drag operation has terminated with a drop on this - * DropTarget. This method is responsible for undertaking the - * transfer of the data associated with the gesture. The - * DropTargetDropEvent provides a means to obtain a - * Transferable object that represents the data object(s) to be - * transfered. - *

- *

- * - * @param dtde the DropTargetDropEvent - */ - public void drop(DropTargetDropEvent dtde) { - if (Debug.debugging("beanbox")) - Debug.output("Enter> drop"); - - dtde.acceptDrop(DnDConstants.ACTION_MOVE); - extractTransferData(dtde); - extractDropLocation(dtde); - - if (transferData == null || dropLocation == null) - return; - - Component parent = ((DropTarget) dtde.getSource()).getComponent(); - - dtde.dropComplete(true); - - showPopUp(parent); - if (Debug.debugging("beanbox")) - Debug.output("Exit> drop"); - } - - private void showPopUp(Component parent) { - if (Debug.debugging("beanbox")) - Debug.output("Enter> showPopUp"); - JPopupMenu popup = new JPopupMenu(); - TitledBorder titledBorder = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), - "Available Drop Targets:"); - - titledBorder.setTitleColor(Color.gray); - popup.setBorder(titledBorder); - - Border compoundborder = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), - BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - Enumeration keys = layers.keys(); - while (keys.hasMoreElements()) { - String layerName = keys.nextElement().toString(); - Layer omlayer = (Layer) layers.get(layerName); - - if (omlayer.isVisible()) { - JMenuItem menuItem = new JMenuItem(layerName); - menuItem.setHorizontalTextPosition(SwingConstants.CENTER); - menuItem.setBorder(compoundborder); - menuItem.addActionListener(this); - popup.add(menuItem); - } - } - - popup.addSeparator(); - - JMenuItem menuItem = new JMenuItem("CANCEL"); - menuItem.setForeground(Color.red); - menuItem.setHorizontalTextPosition(SwingConstants.CENTER); - menuItem.setBorder(compoundborder); - - popup.add(menuItem); - - if (Debug.debugging("beanbox")) - Debug.output("showing popup"); - - popup.show(parent, dropLocation.x, dropLocation.y); - if (Debug.debugging("beanbox")) - Debug.output("Exit> showPopUp"); - } - - /** - * Displays a {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet}if - * mouse click is on a bean in some layer. In case of overlapping beans, - * chooses the first bean found to be under the mouse, which is usually a - * bean in the top most visible layer. - */ - public void mouseClicked(MouseEvent evt) { - if (Debug.debugging("beanbox")) - Debug.output("Enter> mouseClicked"); - - Point srcLocation = evt.getPoint(); - - Enumeration keys = layers.keys(); - while (keys.hasMoreElements()) { - String layerName = keys.nextElement().toString(); - selectedBeanLayer = (Layer) layers.get(layerName); - if (!selectedBeanLayer.isVisible()) - continue; - selectedBeanBox = ((BeanBoxHandler) selectedBeanLayer).getBeanBox(); - if (selectedBeanBox == null) - continue; - selectedBean = selectedBeanBox.getBeanAtLocation(srcLocation); - if (selectedBean != null) { - break; - } - } - - if (selectedBean == null) { - clearSelection(); - return; - } - - selectedBeanLocation = srcLocation; - - selectedBeanBox.showSelected(selectedBean); - - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - - if (evt.getModifiers() != InputEvent.BUTTON1_MASK) { - GenericPropertySheet propertySheet = new GenericPropertySheet(selectedBean, 575, 20, null, selectedBeanBox); - propertySheet.setVisible(true); - } - - if (Debug.debugging("beanbox")) - Debug.output("Exit> mouseClicked"); - } - - /** - * This method is called whenever the user choose a layer to drop or move a - * bean to. This method adds the bean to the layer or moves the beans to or - * within the selected layer. - */ - public void actionPerformed(ActionEvent evt) { - - if (Debug.debugging("beanbox")) - Debug.output("Enter> actionPerformed"); - Object source = evt.getSource(); - if (!(source instanceof JMenuItem)) - return; - - JMenuItem mi = (JMenuItem) source; - String name = mi.getText(); - Layer targetLayer = (Layer) layers.get(name); - - if (targetLayer == null) { - System.out.println("ERROR> BBDnDC::actionPerformed: " - + "no layer found with name " + name); - return; - } - - BeanBox targetBeanBox = ((BeanBoxHandler) targetLayer).getBeanBox(); - - Object bean = transferData.get(0); - BeanInfo beanInfo = (BeanInfo) transferData.get(1); - Boolean wasBeanMoved = (Boolean) transferData.get(2); - - if (wasBeanMoved.booleanValue()) { - - String sourceLayerName = (String) transferData.get(3); - if (sourceLayerName.equals(targetLayer.getName())) { - targetBeanBox.relocateBean(bean, beanInfo, dropLocation); - } else { - Layer sourceLayer = (Layer) layers.get(sourceLayerName); - BeanBox sourceBeanBox = ((BeanBoxHandler) sourceLayer).getBeanBox(); - sourceBeanBox.removeBean(bean); - Vector object = new Vector(); - object.add(bean); - object.add(beanInfo); - object.add(dropLocation); - targetBeanBox.addBean(object); - } - } else { - Vector object = new Vector(); - object.add(bean); - object.add(beanInfo); - object.add(dropLocation); - targetBeanBox.addBean(object); - } - } - - /** - * Asscoiates a DropTarget with each layer. Also caches all layers that - * implement the BeanBoxHandler interface. - */ - public void setLayers(Layer[] allLayers) { - layers.clear(); - if (allLayers != null) { - for (int i = 0; i < allLayers.length; i++) { - new DropTarget(allLayers[i], DnDConstants.ACTION_MOVE, this); - if (allLayers[i] instanceof BeanBoxHandler) { - Debug.message("DnDCatcher", "Layers changed"); - layers.put(allLayers[i].getName(), allLayers[i]); - } - } - } - } - - /** - * Invoked on dragGestureRecognized - */ - public void startDragAction(DragGestureEvent dge, DragSourceListener dsl) { - if (Debug.debugging("beanbox")) - Debug.output("Enter> startDragAction"); - - Object selectedBean = null; - BeanBox selectedBeanBox = null; - Layer selectedLayer = null; - - Point srcLocation = dge.getDragOrigin(); - - Enumeration keys = layers.keys(); - while (keys.hasMoreElements()) { - String layerName = keys.nextElement().toString(); - Layer omLayer = (Layer) layers.get(layerName); - BeanBox beanBox = ((BeanBoxHandler) omLayer).getBeanBox(); - selectedBean = beanBox.getBeanAtLocation(srcLocation); - if (selectedBean != null) { - selectedBeanBox = beanBox; - selectedLayer = omLayer; - break; - } - } - - if (Debug.debugging("beanbox")) - Debug.output("selectedBean=" + selectedBean); - - if (selectedBean == null || selectedBeanBox == null - || selectedLayer == null) { - if (Debug.debugging("beanbox")) - Debug.output("Exit> startDragAction, selected bean/beanbox/layer is null"); - return; - } - - Image dragImage = selectedBeanBox.getDragImage(selectedBean); - - super.setCursor(dragImage, DragSource.DefaultMoveDrop); - - BeanInfo beanInfo = selectedBeanBox.getBeanInfoForBean(selectedBean.getClass() - .getName()); - - Vector beanTransferData = new Vector(); - beanTransferData.add(selectedBean); - beanTransferData.add(beanInfo); - beanTransferData.add(new Boolean(true)); - beanTransferData.add(selectedLayer.getName()); - - dragSource.startDrag(dge, - super.getCursor(DragSource.DefaultMoveDrop), - new DefaultTransferableObject(beanTransferData), - dsl); - - if (Debug.debugging("beanbox")) - Debug.output("Exit> startDragAction"); - } - - private void extractTransferData(DropTargetDropEvent dtde) { - if (dtde == null) { - System.out.println("ERROR> BDnDC::getTransferData(): dropEvent is null"); - return; - } - - Transferable tr = dtde.getTransferable(); - try { - transferData = (Vector) tr.getTransferData(DefaultTransferableObject.OBJECT_FLAVOR); - - // cache beanInfos - if (transferData.size() >= 2) { - Object bean = transferData.get(0); - BeanInfo beanInfo = (BeanInfo) transferData.get(1); - beanInfoMap.put(bean.getClass().getName(), beanInfo); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void extractDropLocation(DropTargetDropEvent dtde) { - if (dtde == null) { - System.out.println("ERROR> BDnDC::getTransferData(): dropEvent is null"); - return; - } - - dropLocation = dtde.getLocation(); - } - - private static void setDefaultIcon() { - if (BeanPanel.defaultBeanIcon == null) { - URL url = BeanPanel.class.getResource("bluebean.gif"); - if (url != null) - BeanPanel.defaultBeanIcon = new ImageIcon(url); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxHandler.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxHandler.java deleted file mode 100644 index bdf5ac2ac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanBoxHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -/** - * The BeanBoxHandler interface should be implemented by an openmap - * layer that needs to interact with the - * {@link com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher}via the - * {@link com.bbn.openmap.tools.beanbox.BeanBox}instance associated - * with the layer. The BeanBoxDnDCatcher class uses the getBeanBox() - * method declared on this interface to obtain access to the - * {@link com.bbn.openmap.tools.beanbox.BeanBox}object associated - * with the layer. - */ -public interface BeanBoxHandler { - - /** - * returns a layer specific implementation of the - * {@link com.bbn.openmap.tools.beanbox.BeanBox}class instance. - */ - public BeanBox getBeanBox(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanContainer.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanContainer.java deleted file mode 100644 index 70b979440..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanContainer.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.util.Vector; - -/** - * The {@link com.bbn.openmap.tools.beanbox.BeanBox}treats all bean - * objects that implement this interface as container beans. - */ -public interface BeanContainer { - - /** - * gets the contents of this container as a vector of bean - * objects. - */ - public Vector getContents(); - - /** - * sets the contents of this container as a vector of bean - * objects. - */ - public void setContents(Vector contents); - - /** - * adds the specified bean object to this container. - */ - public void add(Object bean); - - /** - * removes the specified bean object from this container. - */ - public void remove(Object bean); - - /** - * removes all beans from this container. - */ - public void removeAll(); - - /** - * checks if the specified bean lies in this container. - */ - public boolean contains(Object bean); - - /** - * gets the layout manager bean assocciated with this container. - */ - public BeanLayoutManager getLayout(); - - /** - * sets the layout manager bean assocciated with this container. - * The layout manager bean is responsible for laying out the - * contents of this container. - */ - public void setLayout(BeanLayoutManager layout); - - /** - * gets the class name of the layout manager bean assocciated with - * this container. - */ - public String getLayoutClass(); - - /** - * sets the class name of the layout manager bean assocciated with - * this container. - */ - public void setLayoutClass(String lc); - - /** - * calling this method is meant to generate a call to the layout - * manager's layoutContainer method. - */ - public void validate(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutEditor.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutEditor.java deleted file mode 100644 index 6763b6b5c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutEditor.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Component; - -/** - * Custom property editor for the - * {@link com.bbn.openmap.tools.beanbox.BeanLayoutManager}property. - */ -public class BeanLayoutEditor - extends PropertyBeanEditor { - private GenericPropertySheet propSheet; - - /** - * returns an instance of the - * {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet} which serves as - * the custom editor component for the BeanLayoutManager property. - */ - public Component getCustomEditor() { - Object value = getValue(); - if (propSheet == null) - propSheet = new GenericPropertySheet(value, 575, 20, this, null); - else - propSheet.setTarget(value); - return propSheet; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManager.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManager.java deleted file mode 100644 index 8af9f66bf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManager.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -/** - * A BeanLayoutManager is a bean that manages the layout of a - * BeanContainer. - */ -public abstract class BeanLayoutManager implements java.io.Serializable { - /** - * BeanContainer whose contents are laid out using this layout - * manager. - */ - protected BeanContainer _container; - - /** default constructor needed for beanification. */ - public BeanLayoutManager() {} - - /** - * Called by the container to layout its contents. Default method - * does nothing. - */ - public abstract void layoutContainer(); - - /** sets the container. */ - public void setContainer(BeanContainer c) { - _container = c; - } - - /** Gets the container associated with this layout manager. */ - public BeanContainer getContainer() { - return _container; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManagerBeanInfo.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManagerBeanInfo.java deleted file mode 100644 index 63804f841..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanLayoutManagerBeanInfo.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.beans.BeanInfo; -import java.beans.PropertyDescriptor; -import java.beans.SimpleBeanInfo; -import java.util.ArrayList; -import java.util.List; - -/** - * BeanInfo for a - * {@link com.bbn.openmap.tools.beanbox.BeanLayoutManager}. - */ -public class BeanLayoutManagerBeanInfo extends SimpleBeanInfo { - - /** - * returns the location of the 16 x 16 bit image icon. - */ - public String getImage16Location() { - return "BeanLayoutManagerIcon16.gif"; - } - - /** - * returns the location of the 32 x 32 bit image icon. - */ - public String getImage32Location() { - return "BeanLayoutManagerIcon32.gif"; - } - - /** - * subclasses should NOT over-ride this method. Instead, they - * should over-ride localProperties to create their own - * properties. - */ - public PropertyDescriptor[] getPropertyDescriptors() { - ArrayList list = new ArrayList(10); - localProperties(list); - return list.toArray(new PropertyDescriptor[list.size()]); - } - - /** - * direct and indirect subclasses of this bean info class should - * override this method to add their property descripters to the - * list generated by the super-class method. A localProperties - * method written in the subclass should include in a call to - * super.localProperties in order to get the list of superclass - * property descripters. It should then add its own property - * descriptors to this list. A subclass does not need to over-ride - * this method if it has no property descripters of its own to add - * to the list of super-class descriptors. - * - * @param ps a List containing property descripters of all super - * classes. - */ - protected void localProperties(List ps) {} - - /** - * returns the image associated with the bean. This method calls - * getImage16Location() and getImage32Location() to locate the - * image file. - * - * @return An image object containing a 16 x 16 bit image is - * returned if found otherwise a 32 x 32 bit image is - * returned if found. Else a null is returned. - */ - public java.awt.Image getIcon(int iconKind) { - if (iconKind == BeanInfo.ICON_COLOR_16x16 - || iconKind == BeanInfo.ICON_MONO_16x16) { - java.awt.Image img = loadImage(getImage16Location()); - return img; - } else if (iconKind == BeanInfo.ICON_COLOR_32x32 - || iconKind == BeanInfo.ICON_MONO_32x32) { - java.awt.Image img = loadImage(getImage32Location()); - return img; - } - return null; - } - - /** - * A convenience method to create and add a property descriptor to - * a list. A subclass of this bean info class can use this method - * to add its own property descriptors to the list of super class - * property descriptors made available in the localProperties - * method. - * - * @param ps list of property descriptors - * @param name the name of the property - * @param beanClass the Bean class defining the property - */ - protected static void property(List ps, String name, Class beanClass) { - property(ps, name, beanClass, null); - } - - /** - * A convenience method to create and add a property descriptor to - * a list and associate an editor class with the property. A - * subclass of this bean info class can use this method to add its - * own property descriptors to the list of super class property - * descriptors made available in the localProperties method. - * - * @param ps list of property descriptors - * @param name the name of the property - * @param beanClass the Bean class defining the property - * @param editorClass a class to be registered as the editor for - * the specified property. - */ - protected static void property(List ps, String name, Class beanClass, - Class editorClass) { - try { - PropertyDescriptor pd = new PropertyDescriptor(name, beanClass); - if (editorClass != null) - pd.setPropertyEditorClass(editorClass); - ps.add(pd); - } catch (Exception e) { - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanPanel.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanPanel.java deleted file mode 100644 index 109680bf9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/BeanPanel.java +++ /dev/null @@ -1,860 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Container; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Image; -import java.awt.Insets; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSource; -import java.awt.dnd.DragSourceDragEvent; -import java.awt.dnd.DragSourceDropEvent; -import java.awt.dnd.DragSourceEvent; -import java.awt.dnd.DragSourceListener; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.beans.BeanDescriptor; -import java.beans.BeanInfo; -import java.beans.Beans; -import java.beans.Introspector; -import java.io.File; -import java.io.Serializable; -import java.net.URL; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; - -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.ListCellRenderer; -import javax.swing.SwingUtilities; -import javax.swing.event.MouseInputAdapter; - -import com.bbn.openmap.gui.OMToolComponent; -import com.bbn.openmap.tools.dnd.DefaultTransferableObject; -import com.bbn.openmap.util.Debug; - -/** - * The BeanPanel class is an openmap component that loads a set of - * java bean classes upon startup and organizes them into one or more - * tabbed panes. The organization of the tabs is specified in the - * openmap properties file (see below). A bean loaded by the BeanPanel - * is represented using information available in the BeanInfo. The - * BeanPanel tries to represent the bean as an icon followed by the - * bean's pretty name. It gets the (32 x 32 pixels size) color icon - * from the BeanInfo and it gets the bean's pretty name from the - * BeanDescriptor defined in the BeanInfo. If no icon is available, - * the default bluebean.gif icon included in this package is used. If - * no pretty name is available, the last portion of the bean's fully - * qualified class name is used to represent the bean's name. - *

- * The BeanPanel uses Java Drag-And-Drop and is registered as the - * DragSource for Drag-And-Drop events. A user can drag and drop a - * bean from one of the tabs in the BeanPanel onto the map where the - * {@link com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher}catches the - * bean. - *

- * The following are the properties that the BeanPanel reads from the - * openmap properties file: - *

- * 
- *  #------------------------------
- *  # Properties for BeanPanel
- *  #------------------------------
- *  # This property should reflect the paths to the directories 
- *  # containing the bean jars, separated by a space.
- *  beanpanel.beans.path=g:/path-one/jars h:/path-two/lib
- *  
- *  # This property should reflect the logical names of tabs in the BeanPanel,
- *  # separated by a space. The order in which the tabs are specified in this
- *  property is the order in which they appear in the BeanPanel
- *  beanpanel.tabs=tab1 tab2
- * 
- *  # for each tab specified in the beanpabel.tabs property, the following
- *  # two properties should respectively reflect the pretty name of the tab and
- *  # the class names of the beans that should appear in the tab. Class names should
- *  # be separated by spaces.
- *  beanpanel.tab1.name=tab1-pretty-name
- *  beanpanel.tab1.beans=fully-qualified-bean-class-name fully-qualified-bean-class-name ...
- *  beanpanel.tab2.name=tab2-pretty-name
- *  beanpanel.tab2.beans=fully-qualified-bean-class-name fully-qualified-bean-class-name ...
- *  
- *  #-------------------------------------
- *  # End of properties for BeanPanel
- *  #-------------------------------------
- *  
- *  The BeanPanel looks for beanInfos in the same package as the associated
- *  bean as well as in the Introspector's search path. The Introspector's
- *  search path can be augmented by specifying a comma separated list of
- *  package names in the bean.infos.path system (-D) property.
- *  
- *  A BeanPanel can also be created and used as a standalone class, i.e. independent 
- *  of the openmap components architecture by using the BeanPanel constructor that
- *  takes a Properties object as an argument. This constructor creates and initializes 
- *  a BeanPanel object from properties in the Properties object. The format of the 
- *  properties is the same as the one specified in the openmap properties file.
- *  
- * 
- */ -public class BeanPanel extends OMToolComponent implements Serializable { - - /** Default icon for representing a bean */ - public static ImageIcon defaultBeanIcon; - - static { - augmentBeanInfoSearchPath(); - setDefaultIcon(); - } - - /** Default key for the BeanPanel Tool. */ - public static final String defaultKey = "beanpanel"; - - private BeanHelper helper = new BeanHelper(); - private Vector beanLabels = new Vector(); - private Vector beanNames = new Vector(); - private Vector beanIcons = new Vector(); - private Vector beanJars = new Vector(); - private Vector beanInfos = new Vector(); - - private Vector beanPaths; - private HashMap toolbarTabInfo; - private Vector toolbarTabOrder; - - /** DnD source */ - private DragSource dragSource; - - private JTabbedPane tabbedPane; - - private Cursor customCursor; - - private JFrame beanFrame = null; - - /** - * Constructs the BeanPanel component, creates a DragSource and - * DragSourceListener objects and registers itself as the source - * of Java drag events. Note that this constructor does not - * initialize the BeanPanel GUI. Instead the GUI is initialized - * lazily when the user clicks on the 'Face' of this object on the - * openmap components bar. Thus, this constructor should not be - * used to create a stand-alone BeanPanel. Use the parameterized - * constructor to create a stand-alone BeanPanel. - */ - public BeanPanel() { - super(); - setKey(defaultKey); - - beanPaths = new Vector(); - toolbarTabInfo = new HashMap(); - toolbarTabOrder = new Vector(); - - tabbedPane = new JTabbedPane(); - - dragSource = new DragSource(); - ComponentDragSourceListener tdsl = new ComponentDragSourceListener(); - dragSource.createDefaultDragGestureRecognizer(tabbedPane, - DnDConstants.ACTION_MOVE, - new ComponentDragGestureListener(tdsl)); - - if (Debug.debugging("beanpanel")) - Debug.output("Created Bean Panel"); - } - - /** - * This constructor does everything that the default constructor - * does and in addition initializes the BeanPanel's properties - * from the Properties object and initializes the BeanPanel GUI. - * Use this constructor to create a stand-alone BeanPanel. - */ - public BeanPanel(Properties props) { - - this(); - - if (props == null) - throw new IllegalArgumentException("null props"); - - this.setProperties(props); - - this.initGui(); - - } - - /** - * Tool interface method. The retrieval tool's interface. This - * method creates a button that will bring up the BeanPanel. - * - * @return A container that will contain the 'face' of this panel - * on the OpenMap ToolPanel. - */ - public Container getFace() { - if (Debug.debugging("beanpanel")) - Debug.output("Enter> BP::getFace"); - - JButton button = null; - - if (defaultBeanIcon == null) { - if (Debug.debugging("beanpanel")) - Debug.output("Enter> null defaultBeanIcon!"); - button = new JButton("Bean Box"); - } else - button = new JButton(defaultBeanIcon); - - button.setBorderPainted(false); - button.setToolTipText("Bean Box"); - button.setMargin(new Insets(0, 0, 0, 0)); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent evt) { - showBeanPanel(true); - } - }); - - if (Debug.debugging("beanpanel")) - Debug.output("Exit> BP::getFace"); - - button.setVisible(getUseAsTool()); - return button; - } - - /** - * Utility method for finding the BeanInfo associated with a bean - * class name. This method first attaches the String "BeanInfo" to - * the end of the class name and then searches the package of the - * specified class for the BeanInfo class. If the BeanInfo is not - * found in the bean class's package, then the method searches for - * the BeanInfo in the Introspector search path. - * - * @param beanClassName the fully qualified name of the bean class - * @return an instance of the BeanInfo class for the specified - * class, if one is found, otherwise null. - */ - public static synchronized BeanInfo findBeanInfo(String beanClassName) { - //System.out.println("Finding beanInfo for " + - // beanClassName); - String[] beanInfoPaths = Introspector.getBeanInfoSearchPath(); - String infoClassName = beanClassName + "BeanInfo"; - Class infoClass = null; - - try { - infoClass = Class.forName(infoClassName); - //System.out.println("returning " + infoClass); - return (BeanInfo) infoClass.newInstance(); - } catch (Exception ex) { - //System.out.println ("Unable to find BeanInfo class for - // " + infoClassName); - } - - for (int i = 0; i < beanInfoPaths.length; i++) { - //System.out.println ("Looking in " + beanInfoPaths[i]); - int index = beanClassName.lastIndexOf("."); - String classNameWithDot = beanClassName.substring(index); - infoClassName = beanInfoPaths[i] + classNameWithDot + "BeanInfo"; - try { - infoClass = Class.forName(infoClassName); - break; - } catch (ClassNotFoundException ex) { - //System.out.println ("Unable to find BeanInfo class - // for " + infoClassName); - } - } - - Object retval = null; - - if (infoClass != null) { - try { - retval = infoClass.newInstance(); - } catch (Exception ex) { - //System.out.println("Unable to instantiate " + - // infoClassName); - } - } - - //System.out.println("returning " + infoClass); - - return (BeanInfo) retval; - } - - /** - * Loads java beans from jar files. This method first gets the - * locations of the jar files from the openmap properties file and - * then loads the bean classes from them. - */ - private void loadBeans() { - - Vector jarNames = getJarNames(); - for (int i = 0; i < jarNames.size(); i++) { - String jarFileName = (String) jarNames.elementAt(i); - try { - JarLoader.loadJarDoOnBean(jarFileName, helper); - } catch (Throwable th) { - System.out.println("BP::loadBeans: jar load failed: " - + jarFileName); - th.printStackTrace(); - } - } - } - - private Vector getJarNames() { - Vector result = new Vector(); - - if (beanPaths == null || beanPaths.isEmpty()) - return result; - - for (int i = 0; i < beanPaths.size(); i++) { - String path = (String) beanPaths.get(i); - File dir = new File(path); - - if (!dir.isDirectory()) { - System.out.println("BP::getJarNames: " + dir - + " is not a directory!"); - continue; - } - - String names[] = dir.list(new FileExtension(".jar")); - - for (int j = 0; j < names.length; j++) - result.add(dir.getPath() + File.separatorChar + names[j]); - } - - return result; - } - - private JList createTab(Vector beanClassNames) { - final JList list = new JList(); - - if (beanClassNames == null || beanClassNames.isEmpty()) - return list; - - Vector labels = new Vector(); - - for (int i = 0; i < beanClassNames.size(); i++) { - String beanClassName = (String) beanClassNames.get(i); - int index = beanNames.indexOf(beanClassName); - - if (index < 0) { - System.out.println("BP::createTab: could not locate beanClass=" - + beanClassName); - continue; - } - - String label = (String) beanLabels.get(index); - labels.add(label); - } - - list.setListData(labels); - list.setCellRenderer(new MyCellRenderer()); - - MouseEventForwarder forwarder = new MouseEventForwarder(); - list.addMouseListener(forwarder); - list.addMouseMotionListener(forwarder); - - return list; - } - - private synchronized void showBeanPanel(boolean isVisible) { - - if (beanFrame != null) { - beanFrame.setVisible(isVisible); - if (isVisible) - beanFrame.toFront(); - return; - } - - if (!isVisible) - return; - - initGui(); - beanFrame = new JFrame("Bean Box"); - beanFrame.getContentPane() - .setLayout(new BoxLayout(beanFrame.getContentPane(), BoxLayout.Y_AXIS)); - beanFrame.getContentPane().add(this); - - beanFrame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent evt) { - beanFrame.setVisible(false); - } - }); - - beanFrame.pack(); - beanFrame.setVisible(true); - } - - private synchronized void initGui() { - - loadBeans(); - - this.setLayout(new BorderLayout()); - - if (toolbarTabOrder != null && !toolbarTabOrder.isEmpty()) { - MouseEventForwarder forwarder = new MouseEventForwarder(); - tabbedPane.addMouseListener(forwarder); - tabbedPane.addMouseMotionListener(forwarder); - - for (int i = 0; i < toolbarTabOrder.size(); i++) { - String tabName = (String) toolbarTabOrder.get(i); - Vector beanClassNames = (Vector) toolbarTabInfo.get(tabName); - JList listTab = createTab(beanClassNames); - tabbedPane.addTab(tabName, listTab); - } - - JScrollPane sPane = new JScrollPane(tabbedPane); - - add(sPane, BorderLayout.CENTER); - } - - setPreferredSize(new Dimension(400, 250)); - setMinimumSize(new Dimension(400, 250)); - - } - - public synchronized void setProperties(String prefix, Properties props) { - - loadBeanPaths(props); - - loadToolBarTabInfo(props); - } - - private void loadBeanPaths(Properties props) { - if (Debug.debugging("beanpanel")) - Debug.output("Enter> BP::loadBeanPaths"); - String beanPathsStr = props.getProperty("beanpanel.beans.path"); - - if ((beanPathsStr != null) - && !((beanPathsStr = beanPathsStr.trim()).length() == 0)) { - StringTokenizer st = new StringTokenizer(beanPathsStr, " "); - - while (st.hasMoreTokens()) - beanPaths.add(st.nextToken()); - } - - if (Debug.debugging("beanpanel")) - Debug.output("beanPaths=" + beanPaths); - if (Debug.debugging("beanpanel")) - Debug.output("Exit> BP::loadBeanPaths"); - } - - private void loadToolBarTabInfo(Properties props) { - if (Debug.debugging("beanpanel")) - Debug.output("Enter> BP::loadToolBarTabInfo"); - - String tabsStr = props.getProperty("beanpanel.tabs"); - - if ((tabsStr != null) && !((tabsStr = tabsStr.trim()).length() == 0)) { - StringTokenizer st = new StringTokenizer(tabsStr, " "); - - while (st.hasMoreTokens()) { - String tab = st.nextToken(); - String tabName = props.getProperty("beanpanel." + tab + ".name"); - String beanClassesStr = props.getProperty("beanpanel." + tab - + ".beans"); - - if ((beanClassesStr != null) - && !((beanClassesStr = beanClassesStr.trim()).length() == 0)) { - StringTokenizer st2 = new StringTokenizer(beanClassesStr, " "); - Vector beanClassNames = new Vector(); - - while (st2.hasMoreTokens()) - beanClassNames.add(st2.nextToken()); - - toolbarTabInfo.put(tabName, beanClassNames); - toolbarTabOrder.add(tabName); - } - } - } - - if (Debug.debugging("beanpanel")) - Debug.output("toolbarTabInfo=" + toolbarTabInfo); - if (Debug.debugging("beanpanel")) - Debug.output("toolbarTabOrder=" + toolbarTabOrder); - if (Debug.debugging("beanpanel")) - Debug.output("Exit> BP::loadToolBarTabInfo"); - } - - private void setDragCursor(int index) { - ImageIcon icon = (ImageIcon) beanIcons.get(index); - Point offset = new Point(0, 0); - Image img = icon.getImage(); - - customCursor = Toolkit.getDefaultToolkit().createCustomCursor(img, - offset, - ""); - } - - private class BeanHelper implements DoOnBean { - - public void action(JarInfo ji, BeanInfo bi, Class beanClass, - String beanName) { - - if (Debug.debugging("beanpanel")) - Debug.output("Enter> ACTION: " + beanName); - - if (Debug.debugging("beanpanel")) - Debug.output("ACTION: " + beanName); - if (Debug.debugging("beanpanel")) - Debug.output("bi: " + bi); - if (Debug.debugging("beanpanel")) - Debug.output("bi.getClass(): " + bi.getClass()); - - String label; - ImageIcon icon = null; - - if (beanName.equals(beanClass.getName())) { - if (Debug.debugging("beanpanel")) - Debug.output("beanName=" + beanName); - BeanDescriptor bd = bi.getBeanDescriptor(); - if (bd != null) - label = bd.getDisplayName(); - else { - int index = beanName.lastIndexOf("."); - if (index >= 0 && index < beanName.length() - 1) - label = beanName.substring(index + 1, beanName.length()); - else - label = beanName; - } - if (Debug.debugging("beanpanel")) - Debug.output("label=" + label); - Image img = bi.getIcon(BeanInfo.ICON_COLOR_32x32); - if (Debug.debugging("beanpanel")) - Debug.output("img=" + img); - - if (img == null) { - URL url = this.getClass().getResource("bluebean.gif"); - icon = new ImageIcon(url); - } else - icon = new ImageIcon(img); - } else { - label = beanName; - int ix = beanName.lastIndexOf('.'); - - if (ix >= 0) - label = beanName.substring(ix + 1); - } - - beanLabels.addElement(label); - beanNames.addElement(beanClass.getName()); - beanIcons.addElement(icon); - beanJars.addElement(ji); - beanInfos.addElement(bi); - - if (Debug.debugging("beanpanel")) - Debug.output("Exit> ACTION: " + beanName); - } - - public void error(String message, Exception e) { - if (Debug.debugging("beanpanel")) - Debug.output("BP::BeanHelper:error " + message); - e.printStackTrace(); - } - - public void error(String message) { - if (Debug.debugging("beanpanel")) - Debug.output("BP::BeanHelper:error " + message); - } - } - - private class MyCellRenderer implements ListCellRenderer { - - public Component getListCellRendererComponent(JList list, Object value, // value - // to - // display - int index, // cell - // index - boolean isSelected, // is - // the - // cell - // selected - boolean cellHasFocus) // the - // list - // and - // the - // cell - // have - // the - // focus - { - String s = value.toString(); - - JLabel label = new JLabel(s); - label.setHorizontalAlignment(JLabel.LEFT); - int i = beanLabels.indexOf(s); - ImageIcon icon = (ImageIcon) beanIcons.get(i); - label.setIcon(icon); - - if (isSelected) { - label.setBackground(list.getSelectionBackground()); - label.setForeground(list.getSelectionForeground()); - } else { - label.setBackground(list.getBackground()); - label.setForeground(list.getForeground()); - } - - label.setEnabled(list.isEnabled()); - label.setFont(list.getFont()); - label.setOpaque(true); - return label; - } - } - - /* DnD Listeners */ - - private class ComponentDragSourceListener implements DragSourceListener { - public void dragDropEnd(DragSourceDropEvent dsde) { - if (Debug.debugging("beanpanel")) - Debug.output("dragDropEnd (drag)"); - } - - public void dragEnter(DragSourceDragEvent dsde) { - if (Debug.debugging("beanpanel")) - Debug.output("dragEnter (drag)"); - int action = dsde.getDropAction(); - if (action == DnDConstants.ACTION_MOVE) { - dsde.getDragSourceContext().setCursor(customCursor); - } else { - dsde.getDragSourceContext() - .setCursor(DragSource.DefaultCopyNoDrop); - } - } - - public void dragOver(DragSourceDragEvent dsde) { - if (Debug.debugging("beanpanel")) - Debug.output("dragOver (drag)"); - int action = dsde.getDropAction(); - if (action == DnDConstants.ACTION_MOVE) { - dsde.getDragSourceContext().setCursor(customCursor); - } else { - dsde.getDragSourceContext() - .setCursor(DragSource.DefaultCopyNoDrop); - } - } - - public void dropActionChanged(DragSourceDragEvent dsde) { - if (Debug.debugging("beanpanel")) - Debug.output("dropActionChanged (drag)"); - int action = dsde.getDropAction(); - if (action == DnDConstants.ACTION_MOVE) { - dsde.getDragSourceContext().setCursor(customCursor); - } else { - dsde.getDragSourceContext() - .setCursor(DragSource.DefaultCopyNoDrop); - } - } - - public void dragExit(DragSourceEvent dse) { - if (Debug.debugging("beanpanel")) - Debug.output("dragExit (drag)"); - dse.getDragSourceContext().setCursor(DragSource.DefaultCopyNoDrop); - } - } - - private class ComponentDragGestureListener implements DragGestureListener { - ComponentDragSourceListener tdsl; - - public ComponentDragGestureListener(ComponentDragSourceListener tdsl) { - this.tdsl = tdsl; - } - - public void dragGestureRecognized(DragGestureEvent dge) { - if (Debug.debugging("beanpanel")) - Debug.output("dragGestureRecognized"); - JList list = (JList) tabbedPane.getComponentAt(tabbedPane.getSelectedIndex()); - String label = null; - label = (String) list.getSelectedValue(); - if (label != null) { - int index = beanLabels.indexOf(label); - if (index == -1) { - System.out.println("ERROR> BP::dragGestureRecognized: " - + "no beanlabel found for label=" + label); - return; - } - -// JarInfo ji = (JarInfo) beanJars.get(index); - String beanName = (String) beanNames.get(index); - - Object bean = null; - try { - bean = Beans.instantiate(null, beanName); - if (Debug.debugging("beanpanel")) - Debug.output("Instantiated bean: " + bean); - setDragCursor(index); - - } catch (Exception ex) { - System.out.println("ERROR> BP::dragGestureRecognized: " - + " error instantiating bean"); - ex.printStackTrace(); - return; - } - - BeanInfo bi = (BeanInfo) beanInfos.get(index); - - Vector beanTransferData = new Vector(); - beanTransferData.add(bean); - beanTransferData.add(bi); - beanTransferData.add(new Boolean(false)); - dragSource.startDrag(dge, - customCursor, - new DefaultTransferableObject(beanTransferData), - tdsl); - - revalidate(); - repaint(); - } - } - } - - private class MouseEventForwarder extends MouseInputAdapter { - - public void mousePressed(MouseEvent e) { - Component comp = (Component) e.getSource(); - Container parent = comp.getParent(); - if (parent != null) { - Point newPoint = SwingUtilities.convertPoint(comp, - e.getPoint(), - parent); - e.translatePoint(newPoint.x - e.getX(), newPoint.y - e.getY()); - MouseEvent me = new MouseEvent(parent, e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger()); - parent.dispatchEvent(me); - } - } - - public void mouseReleased(MouseEvent e) { - Component comp = (Component) e.getSource(); - Container parent = comp.getParent(); - if (parent != null) { - Point newPoint = SwingUtilities.convertPoint(comp, - e.getPoint(), - parent); - e.translatePoint(newPoint.x - e.getX(), newPoint.y - e.getY()); - MouseEvent me = new MouseEvent(parent, e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger()); - parent.dispatchEvent(me); - } - } - - public void mouseDragged(MouseEvent e) { - Component comp = (Component) e.getSource(); - Container parent = comp.getParent(); - if (parent != null) { - Point newPoint = SwingUtilities.convertPoint(comp, - e.getPoint(), - parent); - e.translatePoint(newPoint.x - e.getX(), newPoint.y - e.getY()); - MouseEvent me = new MouseEvent(parent, e.getID(), e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger()); - parent.dispatchEvent(me); - } - } - } - - private static void setDefaultIcon() { - if (BeanPanel.defaultBeanIcon == null) { - URL url = BeanPanel.class.getResource("bluebean.gif"); - if (url != null) - BeanPanel.defaultBeanIcon = new ImageIcon(url); - } - } - - private static void augmentBeanInfoSearchPath() { - - if (Debug.debugging("beanpanel")) - Debug.output("Enter> augmentBeanInfoSearchPath"); - - String beanInfoPath = System.getProperty("bean.infos.path"); - - if (Debug.debugging("beanpanel")) - Debug.output("beanInfoPath=" + beanInfoPath); - - if (beanInfoPath == null - || (beanInfoPath = beanInfoPath.trim()).length() == 0) - return; - - String[] oldPath = java.beans.Introspector.getBeanInfoSearchPath(); - - Vector newPath = new Vector(); - - if (oldPath != null && oldPath.length > 0) - newPath.addAll(Arrays.asList(oldPath)); - - if (Debug.debugging("beanpanel")) - Debug.output("oldPath=" + newPath); - - StringTokenizer st = new StringTokenizer(beanInfoPath, ", "); - - while (st.hasMoreTokens()) { - String path = st.nextToken(); - - if (newPath.contains(path)) - continue; - - newPath.add(path); - } - - java.beans.Introspector.setBeanInfoSearchPath((String[]) newPath.toArray(new String[newPath.size()])); - - if (Debug.debugging("beanpanel")) - Debug.output("UPDATED> beanInfo search path to: " + newPath); - - if (Debug.debugging("beanpanel")) - Debug.output("Exit> augmentBeanInfoSearchPath"); - } - - public static void main(String[] args) { - - Properties props = new Properties(); - props.setProperty("beanpanel.beans.path", ""); - props.setProperty("beanpanel.tabs", "tab1 tab2 tab3"); - props.setProperty("beanpanel.tab1.name", "Generic"); - props.setProperty("beanpanel.tab1.beans", - "com.bbn.openmap.examples.beanbox.SimpleBeanObject"); - props.setProperty("beanpanel.tab2.name", "Container"); - props.setProperty("beanpanel.tab2.beans", - "com.bbn.openmap.examples.beanbox.SimpleBeanContainer"); - props.setProperty("beanpanel.tab3.name", "Military"); - props.setProperty("beanpanel.tab3.beans", - "com.bbn.openmap.examples.beanbox.Fighter"); - - BeanPanel bp = new BeanPanel(props); - JFrame beanFrame = new JFrame("Bean Box"); - beanFrame.getContentPane().add(bp); - beanFrame.pack(); - beanFrame.setVisible(true); - - try { - Thread.sleep(2000); - beanFrame.setVisible(false); - Thread.sleep(2000); - beanFrame.setVisible(true); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/CustomizerDialog.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/CustomizerDialog.java deleted file mode 100644 index 47b536dd7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/CustomizerDialog.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Button; -import java.awt.Component; -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.Customizer; - -/** - * Utility class that takes a generic component editor and wraps it in - * a Dialog box. This includes adding the Frame and the "ok" and - * "cancel" buttons. This class is used by the - * {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet}to show - * a bean customizer. - */ -public class CustomizerDialog extends Dialog implements ActionListener { - - private Component body; - private Button doneButton; - private static int vPad = 5; - private static int hPad = 4; - - /** - * Constructor taking the parent frame, the customizer component - * and the target bean as arguments. - */ - public CustomizerDialog(Frame frame, Customizer customizer, Object target) { - super(frame, customizer.getClass().getName(), true); - setLayout(null); - - body = (Component) customizer; - add(body); - - doneButton = new Button("Done"); - doneButton.addActionListener(this); - add(doneButton); - - int x = frame.getLocation().x + 30; - int y = frame.getLocation().y + 100; - setLocation(x, y); - - setVisible(true); - } - - public void doLayout() { - Insets ins = getInsets(); - Dimension bodySize = body.getPreferredSize(); - Dimension buttonSize = doneButton.getPreferredSize(); - - int width = ins.left + 2 * hPad + ins.right + bodySize.width; - int height = ins.top + 3 * vPad + ins.bottom + bodySize.height - + buttonSize.height; - - body.setBounds(ins.left + hPad, - ins.top + vPad, - bodySize.width, - bodySize.height); - - doneButton.setBounds((width - buttonSize.width) / 2, - ins.top + (2 * hPad) + bodySize.height, - buttonSize.width, - buttonSize.height); - - setSize(width, height); - } - - /** - * Disposes this dialog. - */ - public void actionPerformed(ActionEvent evt) { - // Our "done" button got pushed. - dispose(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/DoOnBean.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/DoOnBean.java deleted file mode 100644 index 1ea7bc071..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/DoOnBean.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.beans.BeanInfo; - -/** - * An action to perform on instantiated beans. Used by the BeanPanel. - */ - -public interface DoOnBean { - void action(JarInfo ji, BeanInfo bi, Class beanClass, String beanName); - - void error(String msg); // display an error message - - void error(String msg, Exception ex); // ditto, with an exception -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/FileExtension.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/FileExtension.java deleted file mode 100644 index 620d567da..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/FileExtension.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.io.File; -import java.io.FilenameFilter; - -/** - * File filter utility class. Used by the BeanPanel. - */ -public class FileExtension implements FilenameFilter { - private String extension; - - /** - * Constructor taking a file extension as argument. - */ - public FileExtension(String ext) { - this.extension = ext; - } - - /** - * Accept file name if it has the stored extension. - */ - public boolean accept(File dir, String name) { - return name.endsWith(extension); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertyEditorInterface.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertyEditorInterface.java deleted file mode 100644 index 3ff9304d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertyEditorInterface.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -/** - * An interface implemented by property editors requiring access to - * the bean whose properties they are editing. - */ -public interface GenericPropertyEditorInterface { - - /** - * This method is called by the - * {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet}on - * property editors that implement this interface to set the - * target bean in them. An editor implementing this method can use - * it to cache the target bean. - */ - public void setTargetBean(Object bean); - - /** - * gets the target bean associated with a property editor. - */ - public Object getTargetBean(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertySheet.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertySheet.java deleted file mode 100644 index 289c028e8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/GenericPropertySheet.java +++ /dev/null @@ -1,591 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.Rectangle; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.beans.BeanInfo; -import java.beans.Beans; -import java.beans.Customizer; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.beans.PropertyEditor; -import java.beans.PropertyEditorManager; -import java.beans.PropertyVetoException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import javax.swing.BorderFactory; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; - -/** - * Displays the properties associated with a bean for editing. An instance of - * this class is created by the {@link com.bbn.openmap.tools.beanbox.BeanBox}to - * display the properties of a bean that the user has clicked on the map. An - * instance of GenericPropertySheet can also be used as a custom editor - * component for a bean property that is itself a bean. - */ -public class GenericPropertySheet extends JDialog implements PropertyChangeListener { - - /** - * contains a reference to an internal panel that displays the bean's - * properties. - */ - protected PropertySheetPanel panel; - - /** - * If an instance of this class is used as a custom editor component of a - * bean's property that is itself a bean, this member contains a reference - * to the custom editor. - */ - protected PropertyEditor editor; - - /** the bean that this property sheet is associated with. */ - protected Object targetBean; - - /** - * A GenericPropertySheet can be optionally associated with a BeanBox. - */ - protected BeanBox beanBox; - - /** - * contains the rectangular bounds of this GenericPropertySheet. - */ - protected Rectangle bounds; - - /** - * contains the number of editors displayed in this GenericPropertySheet. - */ - protected int numEditorsToDisplay; - - /** - * Constructs a property sheet dialog. - * - * @param isModal whether the propertysheet should be displayed in a modal - * dialog. - * @param title the title of this propertysheet. - */ - public GenericPropertySheet(boolean isModal, String title) { - super((JFrame) null, title, isModal); - } - - /** - * Constructs a property sheet dialog. - * - * @param target the bean associated with this property sheet. - * @param x the top-left x position of this property sheet. - * @param y the top-left y position of this property sheet. - * @param beanBox the beanBox that this propertysheet is associated with. - * This param is usually non-null only if this is a top-level - * property-sheet. When this param is non-null, this propertysheet - * will inform the BeanBox whenever a property on the bean changes by - * calling the beanChanged method on BeanBox. Additionally the - * propertysheet will call the editComplete method on the BeanBox - * when the user closes the window. - */ - public GenericPropertySheet(Object target, int x, int y, PropertyEditor pe, BeanBox beanBox) { - this(false, target, new Rectangle(x, y, 100, 100), pe, beanBox); - } - - /** - * Constructs a property sheet dialog. - * - * @param isModal whether to display the propertysheet as a modal dialog. - * @param target the bean property that this class handles. - * @param bounds the boundaries to use - * @param pe the parent PropertyEditor of this sheet. An instance of - * GenericPropertySheet is invoked from the getCustomEditor method of - * pe. The parent editor can be null, in which case this class - * behaves exactly as a regular property sheet class. - * @param beanBox the beanBox that this propertysheet is associated with. - * This param is usually non-null only if this is a top-level - * property-sheet. When this param is non-null, this propertysheet - * will inform the BeanBox whenever a property on the bean changes by - * calling the beanChanged method on BeanBox. - */ - - public GenericPropertySheet(boolean isModal, Object target, Rectangle bounds, - PropertyEditor pe, BeanBox beanBox) { - super((JFrame) null, "Properties - ", isModal); - - this.targetBean = target; - - /* - * if (bounds == null) this.bounds = new Rectangle(0, 0, 100, 100); else - * { this.bounds = new Rectangle(); this.bounds.x = bounds.x; - * this.bounds.y = bounds.y; this.bounds.width = (bounds.width > 0) ? - * bounds.width : 100; this.bounds.height = (bounds.height > 0) ? - * bounds.height : 100; } - */ - - this.editor = pe; - this.beanBox = beanBox; - - init(); - this.getContentPane().add(panel); - } - - /** - * Initializes the background, bounds, title, panel and adds a window - * listener. - */ - protected void init() { - setBackground(Color.lightGray); - // setBounds(bounds.x, bounds.y, bounds.width, bounds.height); - initTitle(); - initPanel(); - addWindowListener(); - } - - /** - * Initializes the property sheet panel. - */ - protected void initPanel() { - panel = new PropertySheetPanel(this); - - if (targetBean != null) - panel.setTarget(targetBean); - } - - /** - * Initializes the property sheet's title. - */ - protected void initTitle() { - if (targetBean != null) { - Class beanClass = targetBean.getClass(); - try { - BeanInfo bi = Introspector.getBeanInfo(beanClass); - String label = bi.getBeanDescriptor().getDisplayName(); - setTitle(label + " Properties"); - } catch (Exception ex) { - System.err.println("GenericPropertySheet: couldn't find BeanInfo for " + beanClass); - ex.printStackTrace(); - } - } - } - - /** - * adds a window listener to this property sheet. The windowClosing method - * calls the editComplete method on the BeanBox associated with this - * property sheet if there is one. - */ - protected void addWindowListener() { - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent evt) { - if (beanBox != null) - beanBox.editComplete(targetBean); - setVisible(false); - } - }); - } - - /** - * Returns the JPanel object used to display all the editors in this - * property sheet. - */ - protected PropertySheetPanel getPropertySheetPanel() { - return panel; - } - - /** - * Sets the frame size in order to accommodate all property editors. - */ - protected void setFrameSize() { - int approxControlBarWidth = 60; - int approxTitleBarHeight = 20; - int approxIconWidth = 20; - int approxFontWidth = 8; - int approxFontHeight = 25; - int approxTitleWidth = (getTitle() == null) ? approxControlBarWidth * 2 : (approxIconWidth - + (getTitle().length() * approxFontWidth) + approxControlBarWidth); - int width = (approxTitleWidth > 220) ? approxTitleWidth : 220; - //setSize(width, approxTitleBarHeight + numEditorsToDisplay * approxFontHeight * 2); - setSize(width, approxTitleBarHeight + numEditorsToDisplay * approxFontHeight); - } - - /** - * Sets the number of editors to be displayed on this property sheet. - */ - protected void setNumEditorsToDisplay(int numEditorsToDisplay) { - this.numEditorsToDisplay = numEditorsToDisplay; - } - - /** - * Sets the bean associated with this property sheet. The property sheet - * will re-initialize to display the bean's properties when this method is - * called. - */ - public void setTarget(Object bean) { - // System.out.println("Enter> - // GenericPropertySheet.setTarget()"); - - panel.setTarget(bean); - Class beanClass = bean.getClass(); - - try { - BeanInfo bi = Introspector.getBeanInfo(beanClass); - String label = bi.getBeanDescriptor().getDisplayName(); - setTitle("Properties for " + label); - } catch (Exception ex) { - System.err.println("GenericPropertySheet: couldn't find BeanInfo for " + beanClass); - ex.printStackTrace(); - } - - setVisible(true); - targetBean = bean; - - // System.out.println("Exit> - // GenericPropertySheet.setTarget()"); - } - - // private void setCustomizer(Customizer c) { - // panel.setCustomizer(c); - // } - - /** - * Required by interface PropertyChangeListener. This method is called - * whenever one of the properties of the associated bean changes. If there - * is a PropertyEditor associated with this property sheet, this method will - * generate a call to the editor's setValue method. If there is a BeanBox - * associated with this property sheet, this method will generate a call to - * beanChanged method on the BeanBox. - */ - public void propertyChange(PropertyChangeEvent evt) { - panel.wasModified(evt); - - if (editor != null) - editor.setValue(targetBean); - - if (beanBox != null) - beanBox.beanChanged(targetBean, evt.getPropertyName()); - } -} - -// ***************************************************************************** - -/** - * A utilty class used to display a bean's properties on a GenericPropertySheet. - */ - -class PropertySheetPanel extends JPanel { - - private GenericPropertySheet _frame; - - // We need to cache the targets' wrapper so we can annotate it with - // information about what target properties have changed during - // design - // time. - private Object targetBean; - private PropertyDescriptor[] properties; - private PropertyEditor[] editors; - private Object[] values; - private Component[] views; - private JLabel[] labels; - - private boolean processEvents; - - PropertySheetPanel(GenericPropertySheet frame) { - _frame = frame; - this.setLayout(null); - this.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5)); - } - - synchronized void setTarget(Object targ) { - // System.out.println("Enter> - // PropertySheetPanel.setTarget()"); - - // We make the panel invisible during the reconfiguration - // to try to reduce screen flicker. - setVisible(false); - - removeAll(); - targetBean = targ; - - try { - BeanInfo bi = Introspector.getBeanInfo(targetBean.getClass()); - properties = bi.getPropertyDescriptors(); - } catch (IntrospectionException ex) { - error("GenericPropertySheet: Couldn't introspect", ex); - return; - } - - editors = new PropertyEditor[properties.length]; - values = new Object[properties.length]; - views = new Component[properties.length]; - labels = new JLabel[properties.length]; - int numEditorsToDisplay = 0; - - for (int i = 0; i < properties.length; i++) { - String name = properties[i].getDisplayName(); - - // Don't display hidden or expert properties. - if (properties[i].isHidden() || properties[i].isExpert()) { - System.out.println("Ignoring hidden or expert property " + name); - continue; - } - - Class type = properties[i].getPropertyType(); - Method getter = properties[i].getReadMethod(); - Method setter = properties[i].getWriteMethod(); - - // Only display read/write properties. - if ((getter == null) || (setter == null)) { - System.out.println("Ignoring read-only/write-only property " + name); - continue; - } - - Component view = null; - - try { - Object args[] = {}; - Object value = getter.invoke(targetBean, args); - values[i] = value; - PropertyEditor editor = null; - Class pec = properties[i].getPropertyEditorClass(); - - if (pec != null) { - try { - editor = (PropertyEditor) pec.newInstance(); - } catch (Exception ex) { - // Drop through. - System.out.println("Cannot instantiate editor class: " + pec); - System.out.println("Will try to find editor using " - + "PropertyEditorManager"); - } - } - - if (editor == null) - editor = PropertyEditorManager.findEditor(type); - - editors[i] = editor; - - // If we can't edit this component, skip it. - if (editor == null) { - // If it's a user-defined property we give a - // warning. - String getterClass = properties[i].getReadMethod().getDeclaringClass().getName(); - - if (getterClass.indexOf("java.") != 0) - System.err.println("Warning: Can't find public property editor for property \"" - + name + "\". Skipping."); - - continue; - } - - // System.out.println("About to set value " + value); - editor.setValue(value); - editor.addPropertyChangeListener(_frame); - - // Now figure out how to display it... - if (editor.isPaintable() && editor.supportsCustomEditor()) - view = new PropertyCanvas(_frame, editor); - else if (editor.getTags() != null) - view = new PropertySelector(editor); - else if (editor.getAsText() != null) { - view = new PropertyText(editor); - } else { - System.err.println("Warning: Property \"" + name - + "\" has non-displayabale editor. Skipping."); - continue; - } - - if (editor instanceof GenericPropertyEditorInterface) - ((GenericPropertyEditorInterface) editor).setTargetBean(targetBean); - } catch (InvocationTargetException ex) { - System.err.println("Skipping property " + name + " ; exception on target: " - + ex.getTargetException()); - ex.getTargetException().printStackTrace(); - continue; - } catch (Exception ex) { - System.err.println("Skipping property " + name + "; exception: " + ex); - ex.printStackTrace(); - continue; - } - - labels[i] = new JLabel(name, JLabel.LEFT); - views[i] = view; - - numEditorsToDisplay++; - } // end for - - this.setLayout(new GridLayout(numEditorsToDisplay, 2)); - - for (int i = 0; i < properties.length; i++) - if (views[i] != null) { - add(labels[i]); - add(views[i]); - } - - _frame.setNumEditorsToDisplay(numEditorsToDisplay); - _frame.setFrameSize(); - processEvents = true; - setVisible(true); - - // System.out.println("Exit> PropertySheetPanel.setTarget()"); - } // end setTarget - - synchronized void setCustomizer(Customizer c) { - if (c != null) - c.addPropertyChangeListener(_frame); - } - - synchronized void wasModified(PropertyChangeEvent evt) { - // System.out.println("Enter> - // PropertySheetPanel.wasModified"); - // System.out.println("evt = " + evt); - - if (!processEvents) { - // System.out.println("Exit>GPS::wasModified"); - return; - } - - if (evt.getSource() instanceof PropertyEditor) { - PropertyEditor editor = (PropertyEditor) evt.getSource(); - // System.out.println("editor="+editor); - - for (int i = 0; i < editors.length; i++) { - if (editors[i] == editor) { - PropertyDescriptor property = properties[i]; - Object value = editor.getValue(); - - // if value is the string "null", reset it to null - if ((value != null) && (value instanceof String) - && ((String) value).trim().equalsIgnoreCase("null")) - value = null; - - values[i] = value; - Method setter = property.getWriteMethod(); - - try { - Object args[] = { value }; - args[0] = value; - setter.invoke(targetBean, args); - } catch (InvocationTargetException ex) { - if (ex.getTargetException() instanceof PropertyVetoException) { - // warning("Vetoed; reason is: " - // + - // ex.getTargetException().getMessage()); - // temp deadlock fix...I need to remove the - // deadlock. - System.err.println("WARNING: Vetoed; reason is: " - + ex.getTargetException().getMessage()); - } else - error("InvocationTargetException while updating " + property.getName(), ex.getTargetException()); - } catch (Exception ex) { - error("Unexpected exception while updating " + property.getName(), ex); - } - - if ((views[i] != null) && (views[i] instanceof PropertyCanvas)) { - // System.out.println("repainting view"); - views[i].repaint(); - } - - break; - } - } - } - - // System.out.println("updating other values..."); - - // we want to update in the target - // Now re-read all the properties and update the editors - // for any other properties that have changed. - for (int i = 0; i < properties.length; i++) { - Object o; - - try { - Method getter = properties[i].getReadMethod(); - Object args[] = {}; - o = getter.invoke(targetBean, args); - } catch (Exception ex) { - // System.out.println(" setting o to null"); - o = null; - } - - // System.out.println(" values[" + i + "]=" + values[i]); - - // check if 'o' is of type Object[] - if ((o instanceof Object[]) && (values[i] instanceof Object[])) { - Object[] oldVal = (Object[]) values[i]; - Object[] newVal = (Object[]) o; - - if (newVal.length == oldVal.length) { - for (int j = 0; j < newVal.length; j++) - if (!newVal[j].equals(oldVal[j])) - break; - - continue; - } - } else if ((o == values[i]) || ((o != null) && o.equals(values[i]))) - // The property is equal to its old value. - continue; - - values[i] = o; - - // System.out.println(" editors[" + i + "]=" + - // editors[i]); - - // Make sure we have an editor for this property... - if (editors[i] == null) - continue; - - // System.out.println(" calling setValue on - // editors["+i+"]="+editors[i]); - - // The property has changed! Update the editor. - editors[i].setValue(o); - - if (views[i] != null) - views[i].repaint(); - } - - // Make sure the target bean gets repainted. - if (Beans.isInstanceOf(targetBean, Component.class)) - ((Component) (Beans.getInstanceOf(targetBean, Component.class))).repaint(); - - // System.out.println("Exit-> - // PropertySheetPanel.wasModified"); - } - - // ---------------------------------------------------------------------- - - // private void warning(String s) { - // System.out.println("Warning: " + s); - // } - - // ---------------------------------------------------------------------- - // Log an error. - - private void error(String message, Throwable th) { - String mess = message + ":\n" + th; - System.err.println(message); - th.printStackTrace(); - System.out.println(mess); - } - - // ---------------------------------------------------------------------- -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarInfo.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarInfo.java deleted file mode 100644 index 4823cda10..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarInfo.java +++ /dev/null @@ -1,206 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.beans.BeanInfo; -import java.beans.Beans; -import java.beans.Introspector; -import java.util.Hashtable; - -/** - * Utility class for representing a loaded Jar file. - */ -public class JarInfo { - - private String[] beanNames; - private BeanInfo[] beanInfos; - private Class[] beanClasses; - private boolean[] fromPrototype; - private MessageHeader[] manifestData; - private String jarName; - private static Hashtable beanToJar = new Hashtable(); - - public JarInfo(String jarName, String[] beanNames, boolean[] fromPrototype, - MessageHeader[] manifestData) { - if (beanNames.length != fromPrototype.length) { - throw new Error("beanNames and fromPrototype need to have the same length"); - } - //System.out.println("Created JarInfo"); - this.jarName = jarName; - this.beanNames = beanNames; - this.fromPrototype = fromPrototype; - this.manifestData = manifestData; - this.beanInfos = new BeanInfo[beanNames.length]; - this.beanClasses = new Class[beanNames.length]; - for (int i = 0; i < beanNames.length; i++) { - beanToJar.put(beanNames[i], jarName); // record where this - // beanName came - // from - if (fromPrototype[i]) { - // delay instantiating it - continue; - } - // get the BeanInfo data - Class c; - //System.out.println("Loading bean: " + beanNames[i]); - try { - c = Class.forName(beanNames[i]); - beanClasses[i] = c; - //System.out.println(" succeeded."); - } catch (Exception ex) { - // We don't print an error at this point. Instead we - // print - // an error later, in JarInfo.getInstance. - System.err.println("Could not load " + beanNames[i] + " from " - + jarName); - continue; - } catch (Error er) { - System.out.println(er); - //er.printStackTrace(); - System.err.println("Could not load " + beanNames[i] + " in " - + jarName); - continue; - } - - BeanInfo bi; - try { - //System.out.println("Getting beanInfo for: " + c); - bi = (BeanInfo) BeanPanel.findBeanInfo(beanNames[i]); - } catch (Exception ex) { - System.err.println("JarInfo: couldn't find BeanInfo for " + c - + "; caught " + ex); - continue; - } catch (Error er) { - System.out.println(er.getMessage()); - er.printStackTrace(); - System.err.println("Could not load beanInfo for " - + beanNames[i] + " in " + jarName); - continue; - } - - if (bi != null) { - beanInfos[i] = bi; - //System.out.println(" succeeded."); - } //else - //System.out.println(" failed."); - } - //System.out.println("Exit JarInfo"); - } - - /** - * Gets the name of the jar file that the bean came from. - */ - public static String getJarName(String beanName) { - return (String) beanToJar.get(beanName); - } - - /** - * Get the name of the file containing this jar file - */ - public String getJarName() { - return jarName; - } - - /** - * Get the number of beans in this Jar file - */ - public int getCount() { - return beanNames.length; - } - - /** - * Get the bean class for the ith bean in this file - */ - Class getBeanClass(int i) { - return beanClasses[i]; - } - - /** - * Get the BeanInfo for the ith bean in this jar file - */ - BeanInfo getBeanInfo(int i) { - if (beanInfos[i] != null) { - return beanInfos[i]; - } else { - Object b = getInstance(beanNames[i]); - if (b != null) { - Class c = b.getClass(); - BeanInfo bi; - try { - bi = Introspector.getBeanInfo(c); - } catch (Exception ex) { - System.err.println("JarInfo: couldn't find BeanInfo for " - + c + "; caught " + ex); - return null; - } - - beanInfos[i] = bi; - return bi; - } - return null; - } - } - - /** - * The bean name of the ith stored bean. - */ - String getName(int i) { - return beanNames[i]; - } - - /** - * True if the bean from a serialized prototype. - */ - public boolean isFromPrototype(String name) { - return fromPrototype[indexForName(name)]; - } - - /** - * Get Manifest Headers for the specified bean name - */ - public MessageHeader getManifestData(String name) { - return manifestData[indexForName(name)]; - } - - /** - * Get a new Bean instance given its name - */ - public Object getInstance(String name) { - try { - return Beans.instantiate(null, name); - } catch (Throwable th) { - if (com.bbn.openmap.util.Debug.debugging("beanbox")) { - System.err.println(th); - th.printStackTrace(); - if (name.indexOf('\\') >= 0) { - System.err.println(" Note that file names in manifests must use forward " - + "slashes \"/\" \n rather than back-slashes \"\\\""); - } - } - return null; - } - } - - private int indexForName(String name) { - for (int i = 0; i < beanNames.length; i++) { - if (beanNames[i].equals(name)) { - return i; - } - } - return -1; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarLoader.java deleted file mode 100644 index 9a45f3344..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/JarLoader.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -/** - * Utility class for reading the contents of a JAR file. - * - */ - -import java.beans.BeanInfo; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -public class JarLoader { - - private InputStream jarStream; // Jar input stream - private String jarName; // name of the jar file - private static boolean warnedAboutNoBeans; - - /** - * Create a JarLoader to read a JAR and to process its contents. - * Classes and resources are loaded against a single common class - * loader instance so that things like "adaptor class - * instantiaton" can work. - * - * Loading is started with loadIt() - */ - public JarLoader(String jarName) throws FileNotFoundException { - // wil check that this file exists, and that is about it. - //System.out.println("Created JarLoader for file: " + - // jarName); - this.jarName = jarName; - InputStream is = new FileInputStream(jarName); - jarStream = new BufferedInputStream(is); - } - - /* - * In here for compatibility with older versions of JDK1.1 - */ -// private String guessContentTypeFromStream(InputStream is) -// throws IOException { -// String type; -// type = URLConnection.guessContentTypeFromStream(is); -// // that should be taught about serialized objects. -// -// if (type == null) { -// is.mark(10); -// int c1 = is.read(); -// int c2 = is.read(); -// int c3 = is.read(); -// int c4 = is.read(); -// int c5 = is.read(); -// int c6 = is.read(); -// is.reset(); -// if (c1 == 0xAC && c2 == 0xED) { -// type = "application/java-serialized-object"; -// } -// } -// return type; -// } - - /** - * Load the classes, resources, etc. - */ - public JarInfo loadJar() throws IOException { - //System.out.println("Enter> JarLoader.loadJar()"); - ZipInputStream zis = null; - Manifest mf = null; - - boolean empty = true; - - try { - zis = new ZipInputStream(jarStream); - ZipEntry ent = null; - - while ((ent = zis.getNextEntry()) != null) { - empty = false; - - String name = ent.getName(); - - if (Manifest.isManifestName(name)) { - /* the object we're loading */ - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buffer[] = new byte[1024]; - - for (;;) { - int len = zis.read(buffer); - if (len < 0) { - break; - } - baos.write(buffer, 0, len); - } - - byte[] buf = baos.toByteArray(); - mf = new Manifest(buf); - } - - } - - } catch (IOException ex) { - throw ex; - } catch (Throwable th) { - th.printStackTrace(); - throw new IOException("loadJar caught: " + th); - } finally { - if (zis != null) { - try { - zis.close(); - } catch (Exception ex) { - // ignore - } - } - } - - // Unfortunately ZipInputStream doesn't throw an exception if - // you hand - // it a non-Zip file. Our only way of spotting an invalid Jar - // file - // is if there no ZIP entries. - if (empty) { - throw new IOException("JAR file is corrupt or empty"); - } - - JarInfo ji = createJarInfo(mf); - //System.out.println("Exit> JarLoader.loadJar()"); - return ji; - } - - /** - * Load the JAR file, then apply an action to each bean found - */ - public static void loadJarDoOnBean(String jarFile, DoOnBean action) - throws java.io.IOException { - JarLoader jl = new JarLoader(jarFile); - JarInfo ji = jl.loadJar(); - if (ji == null) { - System.err.println("JAR file " + jarFile - + " did not load properly!"); - System.err.println("Check for error messages possibly regarding"); - System.err.println("problems defining classes"); - return; - } - if (ji.getCount() == 0) { - System.err.println("Jar file " + jarFile - + " didn't have any beans!"); - if (!warnedAboutNoBeans) { - // We only print this explanatory message once. - warnedAboutNoBeans = true; - System.err.println(); - System.err.println("Each jar file needs to contain a manifest file describing which entries are"); - System.err.println("beans. You can should provide a suitable manifest when you create the jar."); - System.err.println(); - } - } - - for (int i = 0; i < ji.getCount(); i++) { - String beanName = ji.getName(i); - BeanInfo bi = ji.getBeanInfo(i); - Class bc = ji.getBeanClass(i); - if (bi == null || bc == null) { - // We couldn't load the bean. - continue; - } - - action.action(ji, bi, bc, beanName); - } - } - - /** - * Create a JarInfo from a manifest and a class list - */ - - private JarInfo createJarInfo(Manifest mf) { - //System.out.println("Enter> JarLoader.createJarInfo()"); - Hashtable beans; - Hashtable headersTable = new Hashtable(); - if (mf == null) { - // Beans are only identified through a manifest entry. - // If we don't have a manifest, the beans hashtable - // should remain empty. - beans = new Hashtable(); - } else { - beans = new Hashtable(); - for (Enumeration entries = mf.entries(); entries.hasMoreElements();) { - MessageHeader mh = (MessageHeader) entries.nextElement(); - String name = mh.findValue("Name"); - String isBean = mh.findValue("Java-Bean"); - if (isBean != null && isBean.equalsIgnoreCase("True")) { - String beanName; - boolean fromPrototype = true; - if (name.endsWith(".class")) { - fromPrototype = false; - beanName = name.substring(0, name.length() - 6); - } else if (name.endsWith(".ser")) { - beanName = name.substring(0, name.length() - 4); - } else { - beanName = name; - } - beanName = beanName.replace('/', '.'); - beans.put(beanName, new Boolean(fromPrototype)); - headersTable.put(beanName, mh); - } - } - } - - String beanNames[] = new String[beans.size()]; - boolean fromPrototype[] = new boolean[beans.size()]; - MessageHeader headers[] = new MessageHeader[beans.size()]; - Enumeration keys; - int i; - for (keys = beans.keys(), i = 0; keys.hasMoreElements(); i++) { - String key = (String) keys.nextElement(); - beanNames[i] = key; - fromPrototype[i] = ((Boolean) beans.get(key)).booleanValue(); - headers[i] = (MessageHeader) headersTable.get(key); - } - - //System.out.println("Exiting> JarLoader.createJarInfo()"); - return new JarInfo(jarName, beanNames, fromPrototype, headers); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/Manifest.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/Manifest.java deleted file mode 100644 index f96407c0e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/Manifest.java +++ /dev/null @@ -1,157 +0,0 @@ -/********************************************************************* - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC A Part of Verizon 10 Moulton Street Cambridge, - * MA 02138 (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC All Rights Reserved. - * ********************************************************************** - */ - -package com.bbn.openmap.tools.beanbox; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.Vector; - -/* - * Stores a list of headers that all pertain to a particular file in - * the archive - */ -public class Manifest { - - private Vector entries = new Vector(); - - static final boolean debug = false; - - static final void debug(String s) { - if (debug) - System.out.println("man> " + s); - } - - public Manifest() {} - - public Manifest(byte[] bytes) throws IOException { - this(new ByteArrayInputStream(bytes)); - } - - /** - * Parse a manifest from a stream - */ - public Manifest(InputStream is) throws IOException { - while (is.available() != 0) { - MessageHeader m = new MessageHeader(is); - entries.addElement(m); - } - } - - /* recursively generate manifests from directory tree */ - public Manifest(String[] files) throws IOException { - MessageHeader globals = new MessageHeader(); - globals.add("Manifest-Version", "1.0"); - addEntry(globals); - addFiles(null, files); - } - - public void addEntry(MessageHeader entry) { - entries.addElement(entry); - } - - public MessageHeader getEntry(String name) { - Enumeration enumeration = entries(); - while (enumeration.hasMoreElements()) { - MessageHeader mh = (MessageHeader) enumeration.nextElement(); - String nameVal = mh.findValue("Name"); - if (nameVal != null && nameVal.equals(name)) { - return mh; - } - } - return null; - } - - public MessageHeader entryAt(int i) { - return (MessageHeader) entries.elementAt(i); - } - - public Enumeration entries() { - return entries.elements(); - } - - public void addFiles(File dir, String[] files) throws IOException { - if (files == null) - return; - for (int i = 0; i < files.length; i++) { - File file; - if (dir == null) { - file = new File(files[i]); - } else { - file = new File(dir, files[i]); - } - if (file.isDirectory()) { - addFiles(file, file.list()); - } else { - addFile(file); - } - } - } - - public void addFile(File f) throws IOException { - MessageHeader mh = new MessageHeader(); - mh.add("Name", f.getPath()); - addEntry(mh); - } - - /* - * Add a manifest file at current position in a stream - */ - public void stream(OutputStream os, Vector extraFiles) throws IOException { - - /* - * the first header in the file should be the global one. It - * should say "Manifest-Version: x.x"; barf if not - */ - MessageHeader globals = (MessageHeader) entries.elementAt(0); - if (globals.findValue("Manifest-Version") == null) { - throw new IOException("Manifest file requires " - + "Manifest-Version: 1.0 in 1st header"); - } - - PrintWriter ps = new PrintWriter(os); - globals.print(ps); - - for (int i = 1; i < entries.size(); ++i) { - MessageHeader mh = (MessageHeader) entries.elementAt(i); - - mh.print(ps); - - /* REMIND: could be adding files twice!!! */ - String name = mh.findValue("name"); - if (extraFiles != null && name != null) { - extraFiles.addElement(name); - } - } - } - - public static boolean isManifestName(String name) { - - // remove leading / - if (name.charAt(0) == '/') { - name = name.substring(1, name.length()); - } - // case insensitive - name = name.toUpperCase(); - - if (name.equals("META-INF/MANIFEST.MF")) { - return true; - } - return false; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/MessageHeader.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/MessageHeader.java deleted file mode 100644 index dd4a69bc1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/MessageHeader.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.io.InputStream; -import java.io.PrintWriter; - -/** - * An RFC 844 or MIME message header. Includes methods for parsing - * headers from incoming streams, fetching values, setting values, and - * printing headers. Key values of null are legal: they indicate lines - * in the header that don't have a valid key, but do have a value - * (this isn't legal according to the standard, but lines like this - * are everywhere). - */ -public class MessageHeader { - private String keys[]; - private String values[]; - private int nkeys; - - public MessageHeader() { - grow(); - } - - public MessageHeader(InputStream is) throws java.io.IOException { - parseHeader(is); - } - - /** - * Find the value that corresponds to this key. It finds only the - * first occurrence of the key. - * - * @param k the key to find. - * @return null if not found. - */ - public String findValue(String k) { - if (k == null) { - for (int i = nkeys; --i >= 0;) - if (keys[i] == null) - return values[i]; - } else - for (int i = nkeys; --i >= 0;) { - if (k.equalsIgnoreCase(keys[i])) - return values[i]; - } - return null; - } - - public String getKey(int n) { - if (n < 0 || n >= nkeys) - return null; - return keys[n]; - } - - public String getValue(int n) { - if (n < 0 || n >= nkeys) - return null; - return values[n]; - } - - /** - * Find the next value that corresponds to this key. It finds the - * first value that follows v. To iterate over all the values of a - * key use: - * - *
-     * 
-     *           for(String v=h.findValue(k); v!=null; v=h.findNextValue(k, v)) {
-     *               ...
-     *           }
-     *   
-     * 
- */ - public String findNextValue(String k, String v) { - boolean foundV = false; - if (k == null) { - for (int i = nkeys; --i >= 0;) - if (keys[i] == null) - if (foundV) - return values[i]; - else if (values[i].equalsIgnoreCase(v)) - foundV = true; - } else - for (int i = nkeys; --i >= 0;) - if (k.equalsIgnoreCase(keys[i])) - if (foundV) - return values[i]; - else if (values[i].equalsIgnoreCase(v)) - foundV = true; - return null; - } - - /** - * Prints the key-value pairs represented by this header. Also - * prints the RFC required blank line at the end. Omits pairs with - * a null key. - */ - public void print(PrintWriter p) { - for (int i = 0; i < nkeys; i++) - if (keys[i] != null) - p.println(keys[i] + (values[i] != null ? ": " + values[i] : "") - + "\r"); - p.println("\r"); - p.flush(); - } - - /** - * Adds a key value pair to the end of the header. Duplicates are - * allowed. - */ - public void add(String k, String v) { - grow(); - keys[nkeys] = k; - values[nkeys] = v; - nkeys++; - } - - /** - * Prepends a key value pair to the beginning of the header. - * Duplicates are allowed. - */ - public void prepend(String k, String v) { - grow(); - for (int i = nkeys; i > 0; i--) { - keys[i] = keys[i - 1]; - values[i] = values[i - 1]; - } - keys[0] = k; - values[0] = v; - nkeys++; - } - - /** - * Overwrite the previous key/val pair at location 'i' with the - * new k/v. If the index didn't exist before the key/val is simply - * tacked onto the end. - */ - public void set(int i, String k, String v) { - grow(); - if (i < 0) { - return; - } else if (i > nkeys) { - add(k, v); - } else { - keys[i] = k; - values[i] = v; - } - } - - /** - * Grow the key/value arrays as needed - */ - private void grow() { - if (keys == null || nkeys >= keys.length) { - String[] nk = new String[nkeys + 4]; - String[] nv = new String[nkeys + 4]; - if (keys != null) - System.arraycopy(keys, 0, nk, 0, nkeys); - if (values != null) - System.arraycopy(values, 0, nv, 0, nkeys); - keys = nk; - values = nv; - } - } - - /** - * Sets the value of a key. If the key already exists in the - * header, it's value will be changed. Otherwise a new key/value - * pair will be added to the end of the header. - */ - public void set(String k, String v) { - for (int i = nkeys; --i >= 0;) - if (k.equalsIgnoreCase(keys[i])) { - values[i] = v; - return; - } - add(k, v); - } - - /** - * Convert a message-id string to canonical form (strips off - * leading and trailing <>s) - */ - public static String canonicalID(String id) { - if (id == null) - return ""; - int st = 0; - int len = id.length(); - boolean substr = false; - int c; - while (st < len && ((c = id.charAt(st)) == '<' || c <= ' ')) { - st++; - substr = true; - } - while (st < len && ((c = id.charAt(len - 1)) == '>' || c <= ' ')) { - len--; - substr = true; - } - return substr ? id.substring(st, len) : id; - } - - /** Parse a MIME header from an input stream. */ - public void parseHeader(InputStream is) throws java.io.IOException { - nkeys = 0; - if (is == null) - return; - char s[] = new char[10]; - int firstc = is.read(); - while (firstc != '\n' && firstc != '\r' && firstc >= 0) { - int len = 0; - int keyend = -1; - int c; - boolean inKey = firstc > ' '; - s[len++] = (char) firstc; - parseloop: { - parseloop2: while ((c = is.read()) >= 0) { - switch (c) { - case ':': - if (inKey && len > 0) - keyend = len; - inKey = false; - break; - case '\t': - c = ' '; - case ' ': - inKey = false; - break; - case '\r': - case '\n': - firstc = is.read(); - if (c == '\r' && firstc == '\n') { - firstc = is.read(); - if (firstc == '\r') - firstc = is.read(); - } - if (firstc == '\n' || firstc == '\r' || firstc > ' ') - break parseloop; - /* continuation */ - continue parseloop2; - } - if (len >= s.length) { - char ns[] = new char[s.length * 2]; - System.arraycopy(s, 0, ns, 0, len); - s = ns; - } - s[len++] = (char) c; - } - firstc = -1; - } - while (len > 0 && s[len - 1] <= ' ') - len--; - String k; - if (keyend <= 0) { - k = null; - keyend = 0; - } else { - k = String.copyValueOf(s, 0, keyend); - if (keyend < len && s[keyend] == ':') - keyend++; - while (keyend < len && s[keyend] <= ' ') - keyend++; - } - String v; - if (keyend >= len) - v = new String(); - else - v = String.copyValueOf(s, keyend, len - keyend); - add(k, v); - } - } - - public String toString() { - StringBuffer result = new StringBuffer(super.toString()); - for (int i = 0; i < keys.length; i++) { - result.append("{").append(keys[i]).append(": ").append(values[i]).append("}"); - } - return result.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyBeanEditor.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyBeanEditor.java deleted file mode 100644 index 8f1b538f5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyBeanEditor.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.beans.PropertyEditorSupport; - -/** Custom property editor for a bean property that is itself a bean. */ - -public class PropertyBeanEditor - extends PropertyEditorSupport { - private GenericPropertySheet propSheet; - - /** - * returns true; - */ - public boolean isPaintable() { - return true; - } - - /** - * represents the face of the custom property editor as a rectangular box - * containing the text "Click to Edit". - */ - public void paintValue(Graphics g, Rectangle box) { - Color oldColor = g.getColor(); - Font oldFont = g.getFont(); - g.setColor(Color.blue); - g.setFont(new Font(oldFont.getFontName(), Font.BOLD, oldFont.getSize())); - g.drawRect(box.x - 1, box.y + 1, box.width - 2, box.height - 2); - g.setColor(Color.white); - g.drawString("Click to Edit", box.x + 10, box.y + box.height / 2 + 4); - g.setFont(oldFont); - g.setColor(oldColor); - } - - /** - * returns true. - */ - public boolean supportsCustomEditor() { - return true; - } - - /** - * returns an instance of the - * {@link com.bbn.openmap.tools.beanbox.GenericPropertySheet} which serves as - * the custom editor component for the bean property associated with this - * editor. - */ - public Component getCustomEditor() { - if (propSheet == null) - propSheet = new GenericPropertySheet(getValue(), 575, 20, this, null); - return propSheet; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyCanvas.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyCanvas.java deleted file mode 100644 index 3770cb149..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyCanvas.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Canvas; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.beans.PropertyEditor; - -import javax.swing.JDialog; - -/** - * Provides support to the GenericPropertySheet for displaying a - * custom PropertyEditor. - */ -public class PropertyCanvas extends Canvas implements MouseListener { - - public PropertyCanvas(JDialog frame, PropertyEditor pe) { - this.frame = frame; - editor = pe; - addMouseListener(this); - } - - public void paint(Graphics g) { - Rectangle box = new Rectangle(2, 2, getSize().width - 4, getSize().height - 4); - editor.paintValue(g, box); - } - - private boolean ignoreClick = false; - - public void mouseClicked(MouseEvent evt) { - if (!ignoreClick) { - try { - ignoreClick = true; - int x = frame.getLocation().x - 30; - int y = frame.getLocation().y + 50; - new PropertyDialog(frame, editor, x, y); - } finally { - ignoreClick = false; - } - } - } - - public void mousePressed(MouseEvent evt) {} - - public void mouseReleased(MouseEvent evt) {} - - public void mouseEntered(MouseEvent evt) {} - - public void mouseExited(MouseEvent evt) {} - - private JDialog frame; - private PropertyEditor editor; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyDialog.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyDialog.java deleted file mode 100644 index 081e01461..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyDialog.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.BorderLayout; -import java.awt.Button; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyEditor; - -import javax.swing.JDialog; - -/** - * Provides support to the GenericPropertySheet for displaying a - * custom PropertyEditor. - */ -class PropertyDialog extends Dialog implements ActionListener { - - private Button doneButton; - private Component body; - private final static int vPad = 5; - private final static int hPad = 4; - - PropertyDialog(JDialog frame, PropertyEditor pe, int x, int y) { - super(frame, pe.getClass().getName(), true); - setLayout(null); - body = pe.getCustomEditor(); - - if (body instanceof Window) { - if (!((Container) body).isVisible()) - ((Container) body).setVisible(true); - } else { - setLayout(new BorderLayout()); - add(body, BorderLayout.CENTER); - doneButton = new Button("Done"); - doneButton.addActionListener(this); - add(doneButton, BorderLayout.SOUTH); - setLocation(x, y); - setVisible(true); - } - } - - public void actionPerformed(ActionEvent evt) { - // Button down. - dispose(); - } - - public void doLayout() { - Insets ins = getInsets(); - Dimension bodySize = body.getPreferredSize(); - Dimension buttonSize = doneButton.getPreferredSize(); - - int width = ins.left + 2 * hPad + ins.right + bodySize.width; - int height = ins.top + 3 * vPad + ins.bottom + bodySize.height - + buttonSize.height; - - body.setBounds(ins.left + hPad, - ins.top + vPad, - bodySize.width, - bodySize.height); - - doneButton.setBounds((width - buttonSize.width) / 2, - ins.top + (2 * hPad) + bodySize.height, - buttonSize.width, - buttonSize.height); - - setSize(width, height); - - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertySelector.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertySelector.java deleted file mode 100644 index b29a56bf4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertySelector.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.Choice; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.beans.PropertyEditor; - -/** - * A class that provides support for a PropertyEditor that uses tags. - */ - -public class PropertySelector extends Choice implements ItemListener { - - public PropertySelector(PropertyEditor pe) { - editor = pe; - String tags[] = editor.getTags(); - for (int i = 0; i < tags.length; i++) { - addItem(tags[i]); - } - select(0); - // This is a noop if the getAsText is not a tag. - select(editor.getAsText()); - addItemListener(this); - } - - public void itemStateChanged(ItemEvent evt) { - String s = getSelectedItem(); - editor.setAsText(s); - } - - public void repaint() { - select(editor.getAsText()); - } - - PropertyEditor editor; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyText.java b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyText.java deleted file mode 100644 index f42c98ae3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/PropertyText.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBNT Solutions LLC - * A Part of - * Verizon - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright (C) 2002 by BBNT Solutions, LLC - * All Rights Reserved. - * ********************************************************************** */ - -package com.bbn.openmap.tools.beanbox; - -import java.awt.TextField; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.beans.PropertyEditor; - -/** - * A class that provides support for a PropertyEditor that displays a - * text property. - */ -public class PropertyText extends TextField implements KeyListener, - FocusListener { - - public PropertyText(PropertyEditor pe) { - super(pe.getAsText()); - editor = pe; - addKeyListener(this); - addFocusListener(this); - } - - public void repaint() { - setText(editor.getAsText()); - } - - protected void updateEditor() { - try { - editor.setAsText(getText()); - } catch (IllegalArgumentException ex) { - // Quietly ignore. - } - } - - //---------------------------------------------------------------------- - // Focus listener methods. - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) { - updateEditor(); - } - - //---------------------------------------------------------------------- - // Keyboard listener methods. - - public void keyReleased(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - updateEditor(); - } - } - - public void keyPressed(KeyEvent e) {} - - public void keyTyped(KeyEvent e) {} - - //---------------------------------------------------------------------- - private PropertyEditor editor; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/package.html b/src/core/src/main/java/com/bbn/openmap/tools/beanbox/package.html deleted file mode 100644 index 8f2850a0d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/beanbox/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - -The beanbox package contains classes that implement a BeanPanel component. -A BeanPanel is an openmap component that loads a set of java beans upon -startup and organizes them into one or more tabbed panes. The structure of the tabs is specified in the openmap properties file. For details see {@link com.bbn.openmap.tools.beanbox.BeanPanel}. The BeanPanel component uses Java Drag-And-Drop and is registered as a DragSource for Drag-And-Drop events. A user can drag and drop a bean from one of the tabs in the BeanPanel onto the map where the {@link com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher} catches the bean. -

-This package also contains classes to catch the bean dragged from the BeanPanel and dropped on the layer. The {@link com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher} class defined in this package catches drag-n-drop events generated from the BeanPanel and delivers them to a target beanbox. A beanbox is a user-defined class that implements the abstract {@link com.bbn.openmap.tools.beanbox.BeanBox} class -contained in this package. Each BeanBox implementation is expected to be associated with an openmap layer. The BeanBox class manages a set of java beans that are delivered to it from the BeanPanel via the BeanBoxDnDCatcher. The abstract BeanBox base class performs functions such as adding and removing beans from its associated layer and provides support for moving beans on the layer and cut/copy/paste functionality. -

-The classes in this package have dependencies on the classes in the com.bbn.openmap.tools.dnd package. - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/ComponentDragGestureListener.java b/src/core/src/main/java/com/bbn/openmap/tools/dnd/ComponentDragGestureListener.java deleted file mode 100644 index 17217f9b4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/ComponentDragGestureListener.java +++ /dev/null @@ -1,75 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/dnd/ComponentDragGestureListener.java,v $ -//$RCSfile: ComponentDragGestureListener.java,v $ -//$Revision: 1.3 $ -//$Date: 2004/10/14 18:06:25 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.dnd; - -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSourceListener; -import java.awt.dnd.InvalidDnDOperationException; - -import com.bbn.openmap.util.Debug; - -/** - * A custom DragGestureListener class that accepts DefaultDnDCatcher - * as one of the parameters and invokes its startDragAction() method - * on dragGestureRecognized event. - */ - -public class ComponentDragGestureListener implements DragGestureListener { - private DragSourceListener dsl; - private DefaultDnDCatcher dndCatcher; - - /** - * Note that DefaultDnDCatcher is a DragSourceListener itself, so - * dndCatcher and dsl can be the same object. - */ - - public ComponentDragGestureListener(DefaultDnDCatcher dndCatcher, - DragSourceListener dsl) { - this.dndCatcher = dndCatcher; - this.dsl = dsl; - Debug.message("draggesturelistener", - "Created> ComponentDragGestureListener"); - Debug.message("draggesturelistener", "dndCatcher=" + dndCatcher); - } - - /** - * A DragGestureRecognizer has detected a - * platform-dependent drag initiating gesture and is notifying - * this listener in order for it to initiate the action for the - * user. - *

- * - * @param dge the DragGestureEvent describing the - * gesture that has just occurred - */ - - public void dragGestureRecognized(DragGestureEvent dge) { - Debug.message("draggesturelistener", - "ComponentDragGestureListener.dragGestureRecognized"); - try { - dndCatcher.startDragAction(dge, dsl); - } catch (InvalidDnDOperationException idoe) { - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultDnDCatcher.java b/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultDnDCatcher.java deleted file mode 100644 index 173de0488..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultDnDCatcher.java +++ /dev/null @@ -1,642 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/dnd/DefaultDnDCatcher.java,v $ -//$RCSfile: DefaultDnDCatcher.java,v $ -//$Revision: 1.6 $ -//$Date: 2005/08/09 20:45:09 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.dnd; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.datatransfer.Transferable; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSource; -import java.awt.dnd.DragSourceListener; -import java.awt.dnd.DropTarget; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.Serializable; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; - -import javax.swing.BorderFactory; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.SwingConstants; -import javax.swing.border.Border; -import javax.swing.border.TitledBorder; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.location.Location; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * DefaultDnDCatcher manages Drag and Drop events on the map. - * - * Drag: When a mouseDragged event occurs, DropListenerSupport forwards it to - * the DefaultDnDCatcher (consume() method). If it's the first mouseDragged - * event, dragGestureRecognized is fired and drag starts. - * - * Drop: Each layer in the LayerHandler listens to the drop events. When a drop - * occurs, a list of potential targets (layers) is shown in the popup menu. - * - * DefaultDnDCatcher recognizes Location as the droppable object. - * - * DefaultDnDCatcher recognizes OMGraphicHandlerLayer layers as potential drop - * targets. - */ - -public class DefaultDnDCatcher extends DnDListener implements BeanContextChild, - BeanContextMembershipListener, PropertyChangeListener, Serializable, - ProjectionListener, LayerListener, ActionListener { - - /** - * PropertyChangeSupport for handling listeners. - */ - protected PropertyChangeSupport pcSupport = new PropertyChangeSupport(this); - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Hashtable for keeping references to potential drop targets - */ - protected Hashtable layers = new Hashtable(); - - // a reference to the MouseDelegator object in the MapHandler - protected transient MouseDelegator md; - - // a copy of current projection - protected transient Projection proj; - - // object that is being passed in transferable - protected Object transferData; - - protected Point dropLocation; - - /** - * Constructs a new DefaultDnDCatcher. - */ - public DefaultDnDCatcher() { - this(new DragSource()); - } - - /** - * Constructs a new DefaultDnDCatcher given the DragSource for the - * Component. - * - * @param ds the DragSource for the Component - */ - public DefaultDnDCatcher(DragSource ds) { - this(ds, null); - } - - /** - * Construct a new DefaultDnDCatcher given the DragSource for the Component - * c, and the Component to observe. - * - * @param ds the DragSource for the Component c - * @param c the Component to observe - */ - public DefaultDnDCatcher(DragSource ds, Component c) { - this(ds, c, DnDConstants.ACTION_NONE); - } - - public DefaultDnDCatcher(DragSource ds, Component c, int act) { - this(ds, c, act, null); - } - - public DefaultDnDCatcher(DragSource ds, Component c, int act, - DragGestureListener dgl) { - super(ds, c, act, dgl); - dragSource = getDragSource(); - dragGestureListener = new ComponentDragGestureListener(this, this); - setSourceActions(DnDConstants.ACTION_MOVE); - } - - /** - * Invoked when an action from the popup menu occurs. - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - Object source = e.getSource(); - if (!(source instanceof JMenuItem)) - return; - - JMenuItem mi = (JMenuItem) source; - String name = mi.getText(); - OMGraphicHandlerLayer targetLayer = (OMGraphicHandlerLayer) layers.get(name); - - if (targetLayer == null) { - Debug.message("defaultdndcatcher", - "ERROR> DefaultDnDCatcher::actionPerformed: " - + "no layer found with name " + name); - return; - } - - targetLayer.doAction((OMGraphic) transferData, - new OMAction(OMAction.UPDATE_GRAPHIC_MASK)); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcSupport.addPropertyChangeListener(listener); - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - pcSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * BeanContextMembershipListener method. Called when new objects are added - * to the parent BeanContext. - * - * @param bcme event that contains an iterator that can be used to go - * through the new objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when objects have been - * removed from the parent BeanContext. The DefaultDnDCatcher looks for the - * MapBean it is managing DnD and MouseEvents for, and any layers that may - * be removed. - * - * @param bcme event that contains an iterator that can be used to go - * through the removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * The method is invoked on mousePressed, mouseReleased, and mouseDragged - * events that come from the MapBean through DropListenerSupport. - * - * @return boolean - * @param e java.awt.event.MouseEvent - */ - public boolean consume(MouseEvent e) { - if (e.getID() == MouseEvent.MOUSE_PRESSED) { - mousePressed(e); - } else if (e.getID() == MouseEvent.MOUSE_RELEASED) { - mouseReleased(e); - } else if (e.getID() == MouseEvent.MOUSE_DRAGGED) { - mouseDragged(e); - } - - return false; - } - - /** - * The drag operation has terminated with a drop on this - * DropTarget. This method is responsible for undertaking the - * transfer of the data associated with the gesture. The - * DropTargetDropEvent provides a means to obtain a - * Transferable object that represents the data object(s) to be - * transfered. - *

- * From this method, the DropTargetListener shall accept or - * reject the drop via the acceptDrop(int dropAction) or rejectDrop() - * methods of the DropTargetDropEvent parameter. - *

- * Subsequent to acceptDrop(), but not before, - * DropTargetDropEvent's getTransferable() method may be - * invoked, and data transfer may be performed via the returned - * Transferable's getTransferData() method. - *

- * At the completion of a drop, an implementation of this method is required - * to signal the success/failure of the drop by passing an appropriate - * boolean to the DropTargetDropEvent's - * dropComplete(boolean success) method. - *

- * Note: The actual processing of the data transfer is not required to - * finish before this method returns. It may be deferred until later. - *

- * - * @param dtde the DropTargetDropEvent - */ - public void drop(java.awt.dnd.DropTargetDropEvent dtde) { - - // - // Accept the drop and get transferable object. - // - dtde.acceptDrop(DnDConstants.ACTION_MOVE); - transferData = extractTransferData(dtde); - dropLocation = extractDropLocation(dtde); - dtde.dropComplete(true); - - if (transferData == null || dropLocation == null) - return; - - JPopupMenu popup = new JPopupMenu(); - TitledBorder titledBorder = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), - "Available Drop Targets:"); - - titledBorder.setTitleColor(Color.gray); - popup.setBorder(titledBorder); - - Border compoundborder = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), - BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - // - // Check whether the dropped object is of type Location - // (has exact x and y coordinates). - // - if (transferData instanceof Location) { - ((Location) transferData).setLocation(dropLocation.x, - dropLocation.y, - proj); - - OMGraphicHandlerLayer omlayer = null; - String layer_name; - Enumeration keys = layers.keys(); - - while (keys.hasMoreElements()) { - layer_name = keys.nextElement().toString(); - omlayer = (OMGraphicHandlerLayer) layers.get(layer_name); - - if (omlayer.isVisible()) { - JMenuItem menuItem = new JMenuItem(layer_name); - menuItem.setHorizontalTextPosition(SwingConstants.CENTER); - menuItem.setBorder(compoundborder); - menuItem.addActionListener(this); - popup.add(menuItem); - } - } - - popup.addSeparator(); - } - - JMenuItem menuItem = new JMenuItem("CANCEL"); - menuItem.setForeground(Color.red); - menuItem.setHorizontalTextPosition(SwingConstants.CENTER); - menuItem.setBorder(compoundborder); - - popup.add(menuItem); - - popup.setPreferredSize(new Dimension(150, (popup.getComponentCount() + 1) * 25)); - - // - // Show a popup menu of available drop targets. - // - popup.show(((DropTarget) dtde.getSource()).getComponent(), - dropLocation.x, - dropLocation.y); - - } - - /** - * Gets the location where the drop action occurred. - */ - private Point extractDropLocation(DropTargetDropEvent dtde) { - if (dtde == null) { - Debug.message("defaultdndcatcher", - "ERROR> BDnDC::getTransferData(): dropEvent is null"); - return null; - } - return dtde.getLocation(); - } - - /** - * Gets the object that is passed in transferable in DropTargetDropEvent. - */ - - private Object extractTransferData(DropTargetDropEvent dtde) { - if (dtde == null) { - Debug.message("defaultdndcatcher", - "ERROR> DefaultDnDCatcher::getTransferData(): dropEvent is null"); - return null; - } - - Transferable tr = dtde.getTransferable(); - try { - return tr.getTransferData(DefaultTransferableObject.OBJECT_FLAVOR); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * Called when an object should be evaluated by the DefaultDnDCatcher to see - * if it is needed. - */ - public void findAndInit(Object someObj) { - - if (someObj instanceof MouseDelegator) - md = (MouseDelegator) someObj; - - if (someObj instanceof MapBean) { - ((MapBean) someObj).addProjectionListener(this); - setProjection(((MapBean) someObj).getProjection().makeClone()); - } - - if (someObj instanceof LayerHandler) { - LayerHandler lh = (LayerHandler) someObj; - lh.addLayerListener(this); - setLayers(lh.getLayers()); - } - } - - /** - * Eventually gets called when the DefaultDnDCatcher is added to the - * BeanContext, and when other objects are added to the BeanContext anytime - * after that. The DefaultDnDCatcher looks for LayerHandler to get - * OMGraphicHandlerLayer layers to manage Drag and Drop events for. If a - * MapBean is added to the BeanContext while another already is in use, the - * second MapBean will take the place of the first. - * - * @param it iterator to use to go through the new objects in the - * BeanContext. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Called by childrenRemoved. - */ - public void findAndUndo(Object someObj) { - - if (someObj == md) { - md = null; - } - - if (someObj instanceof MapBean) { - ((MapBean) someObj).removeProjectionListener(this); - setProjection((Projection) null); - } - - if (someObj instanceof LayerHandler) { - LayerHandler lh = (LayerHandler) someObj; - lh.removeLayerListener(this); - setLayers((Layer[]) null); - } - } - - public void firePropertyChange(String property, Object oldObj, Object newObj) { - - pcSupport.firePropertyChange(property, oldObj, newObj); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - /** - * @return the current BeanContext associated with the JavaBean - */ - public java.beans.beancontext.BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Gets current projection. - */ - - public Projection getProjection() { - return proj; - } - - /** - * The mouseDragged event gets interpreted as DragGestureRecognized when - * startDrag boolean is true. After the first mouseDragged event, set - * startDrag to false. - * - */ - public void mouseDragged(MouseEvent e) { - Debug.message("defaultdndcatcher", "mouseDragged, startDrag=" - + startDrag); - if (startDrag) { - startDrag = false; - if (md.getActiveMouseMode() instanceof SelectMouseMode) { - appendEvent(e); - setComponent((Component) e.getSource()); - fireDragGestureRecognized(DnDConstants.ACTION_MOVE, - ((MouseEvent) getTriggerEvent()).getPoint()); - } - } - } - - /** - * On mouseReleased, set startDrag to true in order to enable dragging. - */ - - public void mouseReleased(MouseEvent e) { - startDrag = true; - } - - /** - * Invoked when there has been a fundamental change to the Map. - *

- * Layers are expected to recompute their graphics (if this makes sense), - * and then repaint() themselves. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - setProjection(e); - } - - /** - * This method gets called when a bound property is changed. - * - * @param evt A PropertyChangeEvent object describing the event source and - * the property that has changed. - */ - public void propertyChange(java.beans.PropertyChangeEvent evt) {} - - /** - * remove a property change listener to this bean child - */ - public void removePropertyChangeListener( - String name, - java.beans.PropertyChangeListener pcl) {} - - /** - * remove a vetoable change listener to this child - */ - public void removeVetoableChangeListener( - String name, - java.beans.VetoableChangeListener vcl) {} - - /** - * A change in the value of the nesting BeanContext property of this - * BeanContextChild may be vetoed by throwing the appropriate exception. - * - * @param in_bc the new BeanContext for this object - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** - * DefaultDnDCatcher adds itself to each layer as the DropTargetListener. - * This is needed in order to capture drop events from any layer on the map, - * and then apply the events to the applicable layers. - */ - public void setLayers(Layer[] allLayers) { - // remove old layers list - layers.clear(); - if (allLayers != null) { - for (int i = 0; i < allLayers.length; i++) { - // create a new drop target - /* dropTarget = */new DropTarget(allLayers[i], DnDConstants.ACTION_MOVE, this); - if (allLayers[i] instanceof OMGraphicHandlerLayer) { - Debug.message("DnDCatcher", "Layers changed"); - // keep a reference to potential drop target - layers.put(allLayers[i].getName(), allLayers[i]); - } - } - } - } - - /** - * The method is invoked when there is a change in layers property in the - * LayerHandler. - */ - - public void setLayers(LayerEvent evt) { - if (evt.getType() == LayerEvent.ALL) { - setLayers(evt.getLayers()); - } - } - - /** - * This method lets you take the ProjectionEvent received from the MapBean, - * and lets you know if you should do something with it. MUST to be called - * in the projectionChanged() method of your layer, if you want to refer to - * the projection later. If this methods returns null, you probably just - * want to call repaint() if your layer.paint() method is ready to paint - * what it should. - * - * @param projEvent the ProjectionEvent from the ProjectionListener method. - * @return The new Projection if it is different from the one we already - * have, null if is the same as the current one. - */ - public Projection setProjection(ProjectionEvent projEvent) { - Projection newProjection = projEvent.getProjection(); - - if (!newProjection.equals(getProjection())) { - Projection clone = newProjection.makeClone(); - setProjection(clone); - return clone; - } else { - return null; - } - } - - /** - * Sets the current projection. - */ - - public void setProjection(Projection projection) { - proj = projection; - } - - /** - * Invoked on dragGestureRecognized in the ComponentDragGestureListener - * class. - * - */ - public void startDragAction(DragGestureEvent dge, DragSourceListener dsl) { - - // create a Transferable object here. - - // Create a location object that can be dropped on a layer. - - // dragSource.startDrag(dge, - // getCursor(DragSource.DefaultMoveDrop), new - // DefaultTransferableObject(new BasicLocation()), dsl); - - // SinkGraphic is a singleton object used as sample. No action - // on a layer will be done at drop. - dragSource.startDrag(dge, - getCursor(DragSource.DefaultMoveDrop), - new DefaultTransferableObject(SinkGraphic.getSharedInstance()), - dsl); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultTransferableObject.java b/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultTransferableObject.java deleted file mode 100644 index 4b070fbc2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DefaultTransferableObject.java +++ /dev/null @@ -1,97 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/dnd/DefaultTransferableObject.java,v $ -//$RCSfile: DefaultTransferableObject.java,v $ -//$Revision: 1.2 $ -//$Date: 2004/10/14 18:06:25 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.dnd; - -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.util.Arrays; - -/** - * Transferable object class with the default data flavor of - * DataFlavor.javaJVMLocalObjectMimeType. - */ - -public class DefaultTransferableObject implements Transferable { - - public static final DataFlavor OBJECT_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, - "Object/JavaBean"); - - private Object obj; - - private DataFlavor[] flavors = { OBJECT_FLAVOR }; - - public DefaultTransferableObject(Object data) { - obj = data; - } - - /** - * Adds another supported data flavor to the array. - */ - public void addTransferDataFlavor(DataFlavor flavor) { - Arrays.asList(flavors).add(flavor); - } - - /** - * Returns an object which represents the data to be transferred. The class - * of the object returned is defined by the representation class of the - * flavor. - * - * @param flavor the requested flavor for the data - * @see DataFlavor#getRepresentationClass - * @exception UnsupportedFlavorException if the requested data flavor is not - * supported. - */ - public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { - - for (int i = 0; i < flavors.length; i++) - if (flavor == flavors[i]) { - return obj; - } - - throw new UnsupportedFlavorException(flavor); - } - - /** - * Returns an array of DataFlavor objects indicating the flavors the data - * can be provided in. The array should be ordered according to preference - * for providing the data (from most richly descriptive to least - * descriptive). - * - * @return an array of data flavors in which this data can be transferred - */ - public DataFlavor[] getTransferDataFlavors() { - return flavors; - } - - /** - * Returns whether or not the specified data flavor is supported for this - * object. - * - * @param flavor the requested flavor for the data - * @return boolean indicating whether or not the data flavor is supported - */ - public boolean isDataFlavorSupported(DataFlavor flavor) { - return Arrays.asList(flavors).contains(flavor); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DnDListener.java b/src/core/src/main/java/com/bbn/openmap/tools/dnd/DnDListener.java deleted file mode 100644 index 252b7c3cf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DnDListener.java +++ /dev/null @@ -1,357 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/dnd/DnDListener.java,v $ -//$RCSfile: DnDListener.java,v $ -//$Revision: 1.2 $ -//$Date: 2004/10/14 18:06:25 $ -//$Author: dietrick $ -// -//********************************************************************** -package com.bbn.openmap.tools.dnd; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Image; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureListener; -import java.awt.dnd.DragSource; -import java.awt.dnd.DragSourceDragEvent; -import java.awt.dnd.DragSourceDropEvent; -import java.awt.dnd.DragSourceEvent; -import java.awt.dnd.DragSourceListener; -import java.awt.dnd.DropTargetDragEvent; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.dnd.DropTargetEvent; -import java.awt.dnd.DropTargetListener; -import java.awt.dnd.MouseDragGestureRecognizer; -import java.util.Hashtable; - -import com.bbn.openmap.util.Debug; - -/** - * DnDListener acts as the base DnD and MouseListener class. Some of - * its methods should be overriden by extending classes. - * - * @see DefaultDnDCatcher - */ -public class DnDListener extends MouseDragGestureRecognizer implements - DragSourceListener, DropTargetListener { - - // startDrag is a boolean flag. When set to true it enables - // dragging. - protected boolean startDrag = true; - - // Specifies the default DnD action. - protected int default_action = DnDConstants.ACTION_MOVE; - - // A hashtable of custom cursors. - private Hashtable cursors = new Hashtable(); - - /** - * Constructs a new DnDListener given the DragSource for the - * Component. - * - * @param ds the DragSource for the Component - */ - protected DnDListener(DragSource ds) { - this(ds, null); - } - - /** - * Construct a new DnDListener given the DragSource for the - * Component c, and the Component to observe. - * - * @param ds the DragSource for the Component c - * @param c the Component to observe - */ - protected DnDListener(DragSource ds, Component c) { - this(ds, c, DnDConstants.ACTION_NONE); - } - - protected DnDListener(DragSource ds, Component c, int act) { - this(ds, c, act, null); - } - - protected DnDListener(DragSource ds, Component c, int act, - DragGestureListener dgl) { - super(ds, c, act, dgl); - } - - /** - * This method is invoked to signify that the Drag and Drop - * operation is complete. The getDropSuccess() method of the - * DragSourceDropEvent can be used to determine the - * termination state. The getDropAction() method returns the - * operation that the DropTarget selected (via the - * DropTargetDropEvent acceptDrop() parameter) to apply to the - * Drop operation. Once this method is complete, the current - * DragSourceContext and associated resources - * become invalid. - *

- * - * @param dsde the DragSourceDropEvent - */ - public void dragDropEnd(DragSourceDropEvent dsde) { - Debug.message("dndlistener", "dragDropEnd(source)"); - // set the startDrag flag to true to enable dragging. - startDrag = true; - } - - /** - * Called as the hotspot enters a platform dependent drop site. - * This method is invoked when the following conditions are true: - *

    - *
  • The logical cursor's hotspot initially intersects a GUI - * Component's visible geometry. - *
  • That Component has an active - * DropTarget associated with it. - *
  • The DropTarget's registered - * DropTargetListener dragEnter() method is invoked - * and returns successfully. - *
  • The registered DropTargetListener invokes - * the DropTargetDragEvent's acceptDrag() method - * to accept the drag based upon interrogation of the source's - * potential drop action(s) and available data types ( - * DataFlavor s). - *
- *

- * - * @param dsde the DragSourceDragEvent - */ - public void dragEnter(DragSourceDragEvent dsde) { - int action = dsde.getDropAction(); - Debug.message("dndlistener", "dragEnter (source)"); - Debug.message("dndlistener", "action=" + action); - if (action == default_action) { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveDrop)); - } else { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveNoDrop)); - } - - } - - /** - * Called when a drag operation has encountered the - * DropTarget. - *

- * - * @param dtde the DropTargetDragEvent - */ - public void dragEnter(DropTargetDragEvent dtde) { - Debug.message("dndlistener", "dragEnter (target)"); - int action = dtde.getDropAction(); - Debug.message("dndlistener", "action=" + action); - dtde.acceptDrag(action); - } - - /** - * Called as the hotspot exits a platform dependent drop site. - * This method is invoked when the following conditions are true: - *

    - *
  • The cursor's logical hotspot no longer intersects the - * visible geometry of the Component associated - * with the previous dragEnter() invocation. - *
- * OR - *
    - *
  • The Component that the logical cursor's - * hotspot intersected that resulted in the previous dragEnter() - * invocation no longer has an active DropTarget or - * DropTargetListener associated with it. - *
- * OR - *
    - *
  • The current DropTarget's - * DropTargetListener has invoked rejectDrag() - * since the last dragEnter() or dragOver() invocation. - *
- *

- * - * @param dse the DragSourceEvent - */ - public void dragExit(DragSourceEvent dse) { - Debug.message("dndlistener", "dragExit (source)"); - dse.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); - } - - /** - * The drag operation has departed the DropTarget - * without dropping. - *

- * - * @param dte the DropTargetEvent - */ - public void dragExit(DropTargetEvent dte) { - Debug.message("dndlistener", "dragExit (target)"); - } - - /** - * Called as the hotspot moves over a platform dependent drop - * site. This method is invoked when the following conditions are - * true: - *

    - *
  • The cursor's logical hotspot has moved but still - * intersects the visible geometry of the Component - * associated with the previous dragEnter() invocation. - *
  • That Component still has a - * DropTarget associated with it. - *
  • That DropTarget is still active. - *
  • The DropTarget's registered - * DropTargetListener dragOver() method is invoked - * and returns successfully. - *
  • The DropTarget does not reject the drag via - * rejectDrag() - *
- *

- * - * @param dsde the DragSourceDragEvent - */ - public void dragOver(DragSourceDragEvent dsde) { - Debug.message("dndlistener", "dragOver(source)"); - int action = dsde.getDropAction(); - if (action == default_action) { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveDrop)); - } else { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveNoDrop)); - } - } - - /** - * Called when a drag operation is ongoing on the - * DropTarget. - *

- * - * @param dtde the DropTargetDragEvent - */ - public void dragOver(DropTargetDragEvent dtde) { - Debug.message("dndlistener", "dragOver(target)"); - dtde.acceptDrag(dtde.getDropAction()); - } - - /** - * The drag operation has terminated with a drop on this - * DropTarget. This method is responsible for - * undertaking the transfer of the data associated with the - * gesture. The DropTargetDropEvent provides a - * means to obtain a Transferable object that - * represents the data object(s) to be transfered. - *

- * From this method, the DropTargetListener shall - * accept or reject the drop via the acceptDrop(int dropAction) or - * rejectDrop() methods of the DropTargetDropEvent - * parameter. - *

- * Subsequent to acceptDrop(), but not before, - * DropTargetDropEvent's getTransferable() method - * may be invoked, and data transfer may be performed via the - * returned Transferable's getTransferData() - * method. - *

- * At the completion of a drop, an implementation of this method - * is required to signal the success/failure of the drop by - * passing an appropriate boolean to the - * DropTargetDropEvent's dropComplete(boolean - * success) method. - *

- * Note: The actual processing of the data transfer is not - * required to finish before this method returns. It may be - * deferred until later. - *

- * - * @param dtde the DropTargetDropEvent - */ - public void drop(DropTargetDropEvent dtde) {} - - /** - * Called when the user has modified the drop gesture. This method - * is invoked when the state of the input device(s) that the user - * is interacting with changes. Such devices are typically the - * mouse buttons or keyboard modifiers that the user is - * interacting with. - *

- * - * @param dsde the DragSourceDragEvent - */ - public void dropActionChanged(DragSourceDragEvent dsde) { - Debug.message("dndlistener", "dropActionChanged(source)"); - int action = dsde.getDropAction(); - Debug.message("dndlistener", "action=" + action); - if (action == default_action) { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveDrop)); - } else { - dsde.getDragSourceContext() - .setCursor(getCursor(DragSource.DefaultMoveNoDrop)); - } - } - - /** - * Called if the user has modified the current drop gesture. - *

- * - * @param dtde the DropTargetDragEvent - */ - public void dropActionChanged(DropTargetDragEvent dtde) { - Debug.message("dndlistener", "dropActionChanged(target)"); - int action = dtde.getDropAction(); - Debug.message("dndlistener", "action=" + action); - dtde.acceptDrag(action); - } - - /** - * Get the Cursor object associated with the default_cursor. If - * not found, return the passed cursor. - */ - - public Cursor getCursor(Cursor default_cursor) { - Cursor cursor = (Cursor) cursors.get(default_cursor); - return (cursor != null) ? cursor : default_cursor; - } - - /** - * Returns the default DnD action. - * - * @return int - */ - public int getDefaultAction() { - return default_action; - } - - /** - * Sets a custom Cursor object associated with the default_cursor. - */ - - public void setCursor(Image img, Cursor default_cursor) { - Point offset = new Point(0, 0); - Cursor customCursor = Toolkit.getDefaultToolkit() - .createCustomCursor(img, offset, ""); - cursors.put(default_cursor, customCursor); - } - - /** - * Sets the default DnD action. - * - * @param newAction int - */ - public void setDefaultAction(int newAction) { - default_action = newAction; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DropListenerSupport.java b/src/core/src/main/java/com/bbn/openmap/tools/dnd/DropListenerSupport.java deleted file mode 100644 index 3f7452cf9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/DropListenerSupport.java +++ /dev/null @@ -1,345 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/dnd/DropListenerSupport.java,v $ -//$RCSfile: DropListenerSupport.java,v $ -//$Revision: 1.3 $ -//$Date: 2005/08/09 20:45:09 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.dnd; - -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.util.Iterator; -import java.util.Vector; - -import com.bbn.openmap.MapBean; -import com.bbn.openmap.SoloMapComponent; -import com.bbn.openmap.util.Debug; - -/** - * The DropListenerSupport manages the DefaultDnDCatchers that handle - * Drag and Drop events on the map. There should only be one - * DropListenerSupport within a MapHandler. - * - * DropListenerSupport keeps a list of all DefaultDnDCatcher objects - * from a MapHandler. It adds itself to the MapBean as MouseListener - * and MouseMotionListener. On MousePressed, MouseDragged, and - * MouseReleased events it loops through the DnDCatchers and invokes a - * consume() method in each of them. - * - * @see DefaultDnDCatcher - */ -public class DropListenerSupport implements PropertyChangeListener, - java.io.Serializable, BeanContextChild, BeanContextMembershipListener, - SoloMapComponent, MouseListener, MouseMotionListener { - - /** - * Holds a list of DefaultDndCatchers - */ - protected transient Vector dndCatchers = new Vector(2); - - /** - * The MapBean. - */ - protected transient MapBean map; - - /** - * PropertyChangeSupport for handling listeners. - */ - protected PropertyChangeSupport pcSupport = new PropertyChangeSupport(this); - - /** - * BeanContextChildSupport object provides helper functions for - * BeanContextChild interface. - */ - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Construct a DropListenerSupport without an associated MapBean. - * You will need to set the MapBean via setMap(). - * - * @see #setMap - */ - public DropListenerSupport() { - this(null); - } - - /** - * Construct a DropListenerSupport with an associated MapBean. - * - * @param map MapBean - */ - public DropListenerSupport(MapBean map) { - setMap(map); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcSupport.addPropertyChangeListener(listener); - } - - /** Method for BeanContextChild interface. */ - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - pcSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void addVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * BeanContextMembershipListener method. Called when new objects - * are added to the parent BeanContext. - * - * @param bcme event that contains an iterator that can be used to - * go through the new objects. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when objects have - * been removed from the parent BeanContext. The - * DropListenerSupport looks for the MapBean it is managing - * MouseEvents for, and any DefaultDndCatchers that may be - * removed. - * - * @param bcme event that contains an iterator that can be used to - * go through the removed objects. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * Called when an object should be evaluated by the - * DropListenerSupport to see if it is needed. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof MapBean) { - Debug.message("droplistenersupport", - "DropListenerSupport found a map."); - setMap((MapBean) someObj); - } - - if (someObj instanceof DefaultDnDCatcher) { - getBeanContext().addBeanContextMembershipListener((DefaultDnDCatcher) someObj); - Debug.message("DropListener", - "DropListener found a DefaultDnDCatcher."); - dndCatchers.addElement(someObj); - } - } - - /** - * Eventually gets called when the DropListenerSupport is added to - * the BeanContext, and when other objects are added to the - * BeanContext anytime after that. The DropListenerSupport looks - * for a MapBean to manage MouseEvents for, and DefaultDndCatchers - * to use to manage those events. If a MapBean is added to the - * BeanContext while another already is in use, the second MapBean - * will take the place of the first. - * - * @param it iterator to use to go through the new objects in the - * BeanContext. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * Called by childrenRemoved. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - if (getMap() == (MapBean) someObj) { - Debug.message("droplistenersupport", - "DropListenerSupport: removing the map."); - setMap(null); - } - } - } - - public void firePropertyChange(String property, Object oldObj, Object newObj) { - - pcSupport.firePropertyChange(property, oldObj, newObj); - } - - /** - * Report a vetoable property update to any registered listeners. - * If anyone vetos the change, then fire a new event reverting - * everyone to the old value and then rethrow the - * PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about - * to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the - * property change to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Get the associated MapBean. - * - * @return MapBean - */ - public MapBean getMap() { - return map; - } - - /** - * Invoked when the mouse has been clicked on a component. - */ - public void mouseClicked(java.awt.event.MouseEvent e) {} - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. Mouse drag events will continue to be delivered to the - * component where the first originated until the mouse button is - * released (regardless of whether the mouse position is within - * the bounds of the component). - */ - public void mouseDragged(java.awt.event.MouseEvent e) { - for (int i = 0; i < dndCatchers.size(); i++) { - if (((DefaultDnDCatcher) dndCatchers.get(i)).consume(e)) - break; - } - } - - /** - * Invoked when the mouse enters a component. - */ - public void mouseEntered(java.awt.event.MouseEvent e) {} - - /** - * Invoked when the mouse exits a component. - */ - public void mouseExited(java.awt.event.MouseEvent e) {} - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons no down). - */ - public void mouseMoved(java.awt.event.MouseEvent e) {} - - /** - * Invoked when a mouse button has been pressed on a component. - */ - public void mousePressed(java.awt.event.MouseEvent e) { - for (int i = 0; i < dndCatchers.size(); i++) { - if (((DefaultDnDCatcher) dndCatchers.get(i)).consume(e)) - break; - } - } - - /** - * Invoked when a mouse button has been released on a component. - */ - public void mouseReleased(java.awt.event.MouseEvent e) { - for (int i = 0; i < dndCatchers.size(); i++) { - if (((DefaultDnDCatcher) dndCatchers.get(i)).consume(e)) - break; - } - } - - /** - * PropertyChangeListenter Interface method. - * - * @param evt PropertyChangeEvent - */ - public void propertyChange(PropertyChangeEvent evt) {} - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcSupport.removePropertyChangeListener(listener); - } - - /** Method for BeanContextChild interface. */ - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - pcSupport.removePropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface. */ - public void removeVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, - in_vcl); - } - - /** Method for BeanContextChild interface. */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** - * Set the associated MapBean. - * - * @param mapbean MapBean - */ - public void setMap(MapBean mapbean) { - if (map != null) { - map.removePropertyChangeListener(this); - map.removeMouseListener(this); - map.removeMouseMotionListener(this); - } - - map = mapbean; - if (map != null) { - map.addPropertyChangeListener(this); - map.addMouseListener(this); - map.addMouseMotionListener(this); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/dnd/package.html b/src/core/src/main/java/com/bbn/openmap/tools/dnd/package.html deleted file mode 100644 index f1f123b14..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/dnd/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains classes to support Java Drag and Drop -functionality on the map. - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/AbstractToolLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/AbstractToolLoader.java deleted file mode 100644 index 7c79d4008..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/AbstractToolLoader.java +++ /dev/null @@ -1,173 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/AbstractToolLoader.java,v $ -// $RCSfile: AbstractToolLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.util.HashMap; -import java.util.Map; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * The AbstractToolLoader groups together some of the code that was - * being duplicated in the different EditToolLoaders. It uses a - * EditClassWrapper to describe how to edit/create/represent graphics, - * and keeps track of multiple EditClassWrappers in case the - * EditToolLoader can handle multiple graphic types. - */ -public abstract class AbstractToolLoader implements EditToolLoader { - - protected Map graphicInfo; - protected I18n i18n = Environment.getI18n(); - - /** - * Each subclass should initialize the graphicInfo HashMap by - * calling addEditClassWrapper(EditClassWrapper). - */ - public abstract void init(); - - public void addEditClassWrapper(EditClassWrapper ecw) { - if (graphicInfo == null) { - graphicInfo = new HashMap<>(); - } - - if (ecw != null) { - graphicInfo.put(ecw.getClassName().intern(), ecw); - } - } - - public void removeEditClassWrapper(EditClassWrapper ecw) { - if (graphicInfo != null && ecw != null) { - graphicInfo.remove(ecw.getClassName().intern()); - } - } - - /** - * Get the Class names that the loader is able to create - * EditableOMGraphics for. - */ - public String[] getEditableClasses() { - String[] strings = null; - if (graphicInfo != null) { - strings = graphicInfo.keySet().toArray(new String[graphicInfo.size()]); - } - return strings; - } - - /** - * Give the Class name of a graphic to create, returning an - * EditableOMGraphic for that graphic. - */ - public EditableOMGraphic getEditableGraphic(String classname) { - EditableOMGraphic eomg = null; - - if (graphicInfo != null) { - EditClassWrapper ecw = graphicInfo.get(classname.intern()); - if (ecw != null) { - String ecn = ecw.getEditableClassName(); - try { - Object obj = Class.forName(ecn).newInstance(); - if (obj instanceof EditableOMGraphic) { - eomg = (EditableOMGraphic) obj; - } - } catch (ClassNotFoundException cnfe) { - Debug.error("AbstractToolLoader can't get editable graphic for " - + classname - + "\n ClassNotFoundException caught."); - } catch (InstantiationException ie) { - Debug.error("AbstractToolLoader can't get editable graphic for " - + classname - + "\n InstantiationException caught."); - } catch (IllegalAccessException iae) { - Debug.error("AbstractToolLoader can't get editable graphic for " - + classname - + "\n IllegalAccessException caught."); - } - } - } - - return eomg; - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the - * point, like point type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - EditableOMGraphic eomg = getEditableGraphic(classname); - if (eomg != null && ga != null) { - // This is a little redundant - the graphic is created - // with the call to getEditableGraphic(classname), but is - // then destroyed and created again with the - // GraphicAttributes settings. I'm not sure how to get - // around this at this point in a generic fashion. Before - // the AbstractToolLoader was created, each EditToolLoader - // called the EditableOMGraphic constructor with the - // GraphicAttributes as an argument. Hard to do when you - // only have a editableClassName. - eomg.createGraphic(ga); - } - return eomg; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public abstract EditableOMGraphic getEditableGraphic(OMGraphic graphic); - - /** - * Get an Icon for a classname. - */ - public ImageIcon getIcon(String classname) { - if (graphicInfo != null) { - EditClassWrapper ecw = (EditClassWrapper) graphicInfo.get(classname.intern()); - if (ecw != null) { - return ecw.getIcon(); - } - } - return null; - } - - /** - * Get the pretty name, suitable for a GUI, for a classname. - */ - public String getPrettyName(String classname) { - if (graphicInfo != null) { - EditClassWrapper ecw = (EditClassWrapper) graphicInfo.get(classname.intern()); - if (ecw != null) { - return ecw.getPrettyName(); - } - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingTool.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingTool.java deleted file mode 100644 index 29e7488d4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingTool.java +++ /dev/null @@ -1,218 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/DrawingTool.java,v $ -// $RCSfile: DrawingTool.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.awt.event.MouseEvent; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * A DrawingTool is an object that can take a request for editing an - * OMGraphic, or for creating an OMGraphic from a classname, and find - * a EditTool to do the job. The DrawingTool is responsible for - * providing any user interface that is needed to adjust the - * OMGraphic. - */ -public interface DrawingTool { - - /** - * A integer that is looked at internally, bitwise, to determine - * different behaviors. If you care about specific behavior of the - * DrawingTool, you should set this to what you want to make sure - * the tool acts the way you want. - */ - public void setBehaviorMask(int mask); - - /** - * A integer that is looked at internally, bitwise, to determine - * different behaviors. - */ - public int getBehaviorMask(); - - /** - * Given a classname, provide an OMGraphic for that classname. - * It's assumed that the DrawingTool will be holding on to an - * EditableOMGraphic encasing the returned OMGraphic, and that the - * parameters of the OMGraphic may still change depending on user - * input. - * - * @param classname the classname of the OMGraphic to create. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic create(String classname, DrawingToolRequestor requestor); - - /** - * Given a classname, provide an OMGraphic for that classname. - * It's assumed that the DrawingTool will be holding on to an - * EditableOMGraphic encasing the returned OMGraphic, and that the - * parameters of the OMGraphic may still change depending on user - * input. - * - * @param classname the classname of the OMGraphic to create. - * @param ga GraphicAttributes object that contains more - * information about the type of line to be created. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic create(String classname, GraphicAttributes ga, - DrawingToolRequestor requestor); - - /** - * Same as create(String, GraphicAttributes, - * DrawingToolRequestor), except that you have to option of - * suppressing the GUI that could be available from the - * EditableOMGraphic. - * - * @param classname the classname of the OMGraphic to create. - * @param ga GraphicAttributes object that contains more - * information about the type of line to be created. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @param showGUI set to true (default) if a GUI showing attribute - * controls should be displayed. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic create(String classname, GraphicAttributes ga, - DrawingToolRequestor requestor, boolean showGUI); - - /** - * Given an OMGraphic, set things up so that the OMGraphic will be - * edited. Returns the OMGraphic being edited. Shouldn't assume - * that the two objects are the same. It's assumed that the - * DrawingTool will be holding on to an EditableOMGraphic encasing - * the returned OMGraphic, and that the parameters of the - * OMGraphic may still change depending on user input. - * - * @param g the OMGraphic to wrap in an EditableOMGraphic, and - * therefore to edit. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor); - - /** - * Same as edit(omGraphic, DrawingToolRequestor), except that you - * have to option of suppressing the GUI that could be available - * from the EditableOMGraphic. - * - * @param g the OMGraphic to wrap in an EditableOMGraphic, and - * therefore to edit. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @param showGUI set to true (default) if a GUI showing attribute - * controls should be displayed. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor, - boolean showGUI); - - /** - * Given an EditableOMGraphic, direct events to the - * EditableOMGraphic so that it can modify its OMGraphic. With - * this method, the loaders are not needed. - * - * @param eomg and EditableOMGraphic to manipulate. - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @return OMGraphic if everything's OK, null if the request can't - * be fulfilled. - */ - public OMGraphic edit(EditableOMGraphic eomg, DrawingToolRequestor requestor); - - /** - * A slightly different edit method, where the EditableOMGraphic - * is put directly into edit mode, and the mouse events - * immediately start making modifications to the OMGraphic. - * - * @param g OMGraphic to modify - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @param e MouseEvent to use to start editing with. - * @return OMGraphic being modified. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor, - MouseEvent e); - - /** - * A slightly different edit method, where the EditableOMGraphic - * is put directly into edit mode, and the mouse events - * immediately start making modifications to the OMGraphic. - * - * @param eomg EditableOMGraphic to modify - * @param requestor the Component that is requesting the - * OMGraphic. The requestor gets notified when the user is - * finished with the DrawingTool and the graphic is ready. - * @param e MouseEvent to use to start editing with. - * @return OMGraphic being modified contained within the - * EditableOMGraphic. - */ - public OMGraphic edit(EditableOMGraphic eomg, - DrawingToolRequestor requestor, MouseEvent e); - - /** - * Check to see if the class type can be created/edited by the - * DrawingTool. - */ - public boolean canEdit(Class clas); - - /** - * Add an EditToolLoader to the DrawingTool, expanding the - * DrawingTool's capability to handle more graphic types. - */ - public void addLoader(EditToolLoader loader); - - /** - * Remove an EditToolLoader from the DrawingTool. - */ - public void removeLoader(EditToolLoader loader); - - /** - * Get an array of EditToolLoaders that the DrawingTool knows - * about. - */ - public EditToolLoader[] getLoaders(); - - /** - * Set the loaders within the DrawingTool. - */ - public void setLoaders(EditToolLoader[] loaders); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestor.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestor.java deleted file mode 100755 index ccbfc8308..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestor.java +++ /dev/null @@ -1,50 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/DrawingToolRequestor.java,v $ -// $RCSfile: DrawingToolRequestor.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * A DrawingToolRequestor is an object that asks a DrawingTool to do - * something for it. The drawingComplete method is called when the - * DrawingTool is complete, letting the requestor know when it should - * get the map repainted, or to send the EditableOMGraphic to another - * object. - */ -public interface DrawingToolRequestor { - /** - * The method where a graphic, and an action to take on the - * graphic, arrives. - */ - public void drawingComplete(OMGraphic omg, OMAction action); - - /** - * Needed to fill in a GUI with a receiver's name, to enable the - * user to send a graphic to a specific object. Should be a pretty - * name, suitable to let a user know what it is. It's important - * that the requestor have a name, because that could be the key - * that is used in some GUI components. - */ - public String getName(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestorList.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestorList.java deleted file mode 100644 index 71bc06c81..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/DrawingToolRequestorList.java +++ /dev/null @@ -1,107 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/DrawingToolRequestorList.java,v -// $ -// $RCSfile: DrawingToolRequestorList.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.util.HashMap; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; - -public class DrawingToolRequestorList implements DrawingToolRequestor { - - protected String name; - protected Map table; - - public DrawingToolRequestorList() { - table = new HashMap<>(); - } - - public void add(OMGraphic omg, DrawingToolRequestor dtr) { - if (Debug.debugging("drawingtool")) { - Debug.output("DTRL.add(" + omg.getClass().getName() + ")"); - } - table.put(omg, dtr); - } - - public void remove(OMGraphic omg) { - table.remove(omg); - } - - public void clear() { - table.clear(); - } - - /** - * The method where a graphic, and an action to take on the graphic, arrives. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - - if (omg instanceof OMGraphicList) { - if (Debug.debugging("drawingtool")) { - Debug.output("DTRL.drawingComplete(list)"); - } - - for (OMGraphic omgi : (OMGraphicList) omg) { - DrawingToolRequestor dtr = (DrawingToolRequestor) table.get(omgi); - if (dtr != null) { - if (Debug.debugging("drawingtool")) { - Debug.output(" notifying requestor for list member " + omgi.getClass().getName()); - } - dtr.drawingComplete(omgi, action); - } - } - } else { - DrawingToolRequestor dtr = table.get(omg); - if (dtr != null) { - if (Debug.debugging("drawingtool")) { - Debug.output(" notifying requestor for " + omg.getClass().getName()); - } - dtr.drawingComplete(omg, action); - } - } - - if (Debug.debugging("drawingtool")) { - Debug.output("DTRL.drawingComplete complete"); - } - } - - void setName(String name) { - this.name = name; - } - - /** - * Needed to fill in a GUI with a receiver's name, to enable the user to send a - * graphic to a specific object. Should be a pretty name, suitable to let a user - * know what it is. It's important that the requestor have a name, because that - * could be the key that is used in some GUI components. - */ - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditClassWrapper.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditClassWrapper.java deleted file mode 100644 index 605bfdce3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditClassWrapper.java +++ /dev/null @@ -1,83 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/EditClassWrapper.java,v $ -// $RCSfile: EditClassWrapper.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.net.URL; - -import javax.swing.ImageIcon; - -/** - * The EditClassWrapper is used by the EditToolLoaders to keep graphic - * classes associated with their class names, the editable class name, - * a valid icon and pretty name to be used in a GUI. - */ -public class EditClassWrapper { - - protected String className = null; - protected String editableClassName = null; - protected ImageIcon icon = null; - protected String prettyName; - - public EditClassWrapper(String classname, String editableclassname, - String iconname, String prettyname) { - className = classname; - editableClassName = editableclassname; - prettyName = prettyname; - URL url = this.getClass().getResource(iconname); - if (url != null) { - icon = new ImageIcon(url); - } - } - - public void setClassName(String classname) { - className = classname; - } - - public String getClassName() { - return className; - } - - public void setEditableClassName(String editableclassname) { - editableClassName = editableclassname; - } - - public String getEditableClassName() { - return editableClassName; - } - - public void setPrettyName(String prettyname) { - prettyName = prettyname; - } - - public String getPrettyName() { - return prettyName; - } - - public void setIcon(ImageIcon image) { - icon = image; - } - - public ImageIcon getIcon() { - return icon; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditToolLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditToolLoader.java deleted file mode 100644 index 07594f37e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/EditToolLoader.java +++ /dev/null @@ -1,88 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/EditToolLoader.java,v $ -// $RCSfile: EditToolLoader.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * An EditToolLoader is interface that describes an object that - * creates something that can create or edit an OMGraphic. The - * EditToolLoader should be able to be tossed at a DrawingTool, and - * the DrawingTool should be able find out what kind of objects it can - * adjust or create, and then use it if any requests come in that fit. - */ -public interface EditToolLoader { - - /** - * Get the classnames that the loader is able to create - * EditableOMGraphics for. - */ - public String[] getEditableClasses(); - - /** - * Give the classname of a graphic to create, returning a default - * EditableOMGraphic for that graphic. If you don't want a graphic - * type to be part of the GUI, then just return an - * EditableOMGraphic for that classname here, and don't return it - * for other queries (getEditableClasses, etc.). - */ - public EditableOMGraphic getEditableGraphic(String classname); - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set various other parameters for the graphic. - * If you don't want a graphic type to be part of the GUI, then - * just return an EditableOMGraphic for that classname here, and - * don't return it for other queries (getEditableClasses, etc.). - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga); - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic); - - /** - * Get an Icon that is suitable for representing the class given - * by the classname. OpenMap is going with a 20 x 20 icon. - * - * @param classname the classname to get the icon for. - * @return Image classname icon. - */ - public ImageIcon getIcon(String classname); - - /** - * Provide a pretty name to use for a particular class. Intended - * to be part of a GUI, either on a list, or as a tool tip. - * - * @param classname the classname to get the icon for. - */ - public String getPrettyName(String classname); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMCircleLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMCircleLoader.java deleted file mode 100755 index 77aec9c58..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMCircleLoader.java +++ /dev/null @@ -1,91 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMCircleLoader.java,v $ -// $RCSfile: OMCircleLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMCircle; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMRangeRings; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRangeRings; - -/** - * Loader that knows how to create/edit OMCircle and OMRangeRings - * objects. - */ -public class OMCircleLoader extends AbstractToolLoader implements - EditToolLoader { - - protected String circleClassName = "com.bbn.openmap.omGraphics.OMCircle"; - protected String rangeRingsClassName = "com.bbn.openmap.omGraphics.OMRangeRings"; - - public OMCircleLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(circleClassName, "com.bbn.openmap.omGraphics.EditableOMCircle", "editablecircle.gif", i18n.get(OMCircleLoader.class, - "omcircle.circle", - "Circle")); - addEditClassWrapper(ecw); - - ecw = new EditClassWrapper(rangeRingsClassName, "com.bbn.openmap.omGraphics.EditableOMRangeRings", "editablerangering.gif", i18n.get(OMCircleLoader.class, - "omcircle.rings", - "Range Rings")); - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the - * circle, like circle type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - String name = classname.intern(); - if (name == circleClassName) { - return new EditableOMCircle(ga); - } - if (name == rangeRingsClassName) { - return new EditableOMRangeRings(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - // Range rings have to go first, they subclass Circles. - if (graphic instanceof OMRangeRings) { - return new EditableOMRangeRings((OMRangeRings) graphic); - } - if (graphic instanceof OMCircle) { - return new EditableOMCircle((OMCircle) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDecoratedSplineLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDecoratedSplineLoader.java deleted file mode 100644 index c90a98250..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDecoratedSplineLoader.java +++ /dev/null @@ -1,82 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMDecoratedSplineLoader.java,v $ -// $RCSfile: OMDecoratedSplineLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMDecoratedSpline; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMDecoratedSpline; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMSpline; - -/** - * OMDecoratedSplineLoader - * - * @author Eric LEPICIER - * @version 22 juil. 2002 - */ -public class OMDecoratedSplineLoader extends AbstractToolLoader implements - EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMDecoratedSpline"; - - public OMDecoratedSplineLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMDecoratedSpline", "editablespline.gif", i18n.get(OMDecoratedSplineLoader.class, - "omdecoratedspline", - "Decorated Splines")); - - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the - * spline, like spline type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMDecoratedSpline(ga); - } - - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMDecoratedSpline) { - return new EditableOMDecoratedSpline((OMSpline) graphic); - } - return null; - } - -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDistanceLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDistanceLoader.java deleted file mode 100644 index 157284c5c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDistanceLoader.java +++ /dev/null @@ -1,85 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMDistanceLoader.java,v $ -// $RCSfile: OMDistanceLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMDistance; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMDistance; -import com.bbn.openmap.omGraphics.OMGraphic; - -/** - * Loader that knows how to create/edit OMDistance objects. - * - * @author Ben Lubin - * @version $Revision: 1.4 $ on $Date: 2004/10/14 18:06:26 $ - * @since 1/3/03 - */ -public class OMDistanceLoader extends AbstractToolLoader implements - EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMDistance"; - - protected String editableClassName = "com.bbn.openmap.omGraphics.EditableOMDistance"; - - public OMDistanceLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, editableClassName, "distance.png", i18n.get(OMDistanceLoader.class, - "omdistance", - "Distance")); - - addEditClassWrapper(ecw); - - // A class wrapper isn't added here for the LabeledOMPoly - // because currently they are only created programmatically. - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the poly, - * like poly type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMDistance(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMDistance) { - return new EditableOMDistance((OMDistance) graphic); - } - return null; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingTool.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingTool.java deleted file mode 100644 index 7e231a9ed..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingTool.java +++ /dev/null @@ -1,1968 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMDrawingTool.java,v $ -// $RCSfile: OMDrawingTool.java,v $ -// $Revision: 1.33 $ -// $Date: 2007/12/03 23:47:37 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.tools.drawing; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JSeparator; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.PaintListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.UndoStack; -import com.bbn.openmap.gui.OMToolComponent; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.gui.menu.UndoMenuItemStackTrigger; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMGraphicList; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.SinkGraphic; -import com.bbn.openmap.omGraphics.editable.GraphicSelectedState; -import com.bbn.openmap.omGraphics.event.EOMGEvent; -import com.bbn.openmap.omGraphics.event.EOMGListener; -import com.bbn.openmap.omGraphics.event.SelectionListener; -import com.bbn.openmap.omGraphics.event.SelectionProvider; -import com.bbn.openmap.omGraphics.event.SelectionSupport; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMDrawingTool implements the DrawingTool interface, and can be used to - * adjust the drawing parameters of OMGraphics. It is basically a manager for - * directing MouseEvents and MouseMotionEvents from a Component to a - * EditableOMGraphic. The EditableOMGraphic is responsible for interpreting the - * events and making the adjustments to the OMGraphic it has wrapped within. The - * OMDrawingTool also tries to keep the presentation of the OMGraphic up to - * date, by managing the repaints of the Component to include the graphic being - * modified. - *

- * - * The OMDrawingTool is also a com.bbn.openmap.gui.Tool, which allows it to - * appear in the OpenMap toolbar. The OMDrawingTool keeps track of whether it is - * a tool, and appears accordingly: - *

- * - * If the OMDrawingTool is being used as a tool (getUseAsTool() == true), then - * it will set itself to be visible. If you are putting an OMDrawingTool in the - * OpenMap application and you want the color/line/graphic options to be visible - * in the toolbar, use the itTool property for the OMDrawingTool in the - * properties file. If you are using your own OMDrawingTool, in your - * EditorLayerTool for instance, you should set useAsTool(true) programmatically - * to get the visibility of the tool to appear. There is a property to tell the - * OMDrawingTool to be visible when it is inactive, and that flag is true by - * default. You can set that property (visibleWhenInactive) to change this - * behavior. - * - * If the OMDrawingTool is not being used as a tool, it can be brought up in a - * window. This window can be brought up with a right click or control-click on - * the object being edited. - *

- * - * If the OMGraphic being edited doesn't want to have the OMDrawingTool visible, - * it won't be. Neither the tool nor the option to bring the window up won't be - * displayed with a right/control click. - *

- * - * The OMDrawingTool uses a behavior mask to give control over how it behaves. - * You can control if the attribute palette appears, if a popup gui appears by - * default when the editing is complete, or appear when the alt+mouse key or - * right mouse key is pressed. You should set this mask if you are not sure - * about the values that other components may have set on the OMDrawingTool. - *

- * - * The OMDrawingTool uses EditToolLoaders to determine what EditableOMGraphic - * can be used for a particular class name or OMGraphic type. If a loader for an - * OMGraphic type is not found, then that OMGraphic type won't be handled, and - * the tool will react to a create() or edit() call with a null object pointer. - * If a loader is found, and the OMgraphic can be edited or modified, then the - * create() or edit() methods will return a pointer to the OMGraphic being - * modified. - *

- * - * The GUI for the OMDrawingTool is multi-layered. The OMDrawingTool contains a - * GraphicsAttributes object, which is an extension of the GraphicAttributes - * object. The GraphicAttributes GUI within the tool lets you change the colors, - * line width and line dash pattern of the current OMGraphic. The - * GraphicAttributes contribution to the GUI is not yet implemented, but will - * let you change the render type and line type of the OMGraphic. Finally, the - * EditableOMGraphic is given an opportunity to change and set parameters of the - * OMGraphic that is knows about - for instance, the EditableOMLine object will - * soon provide an interface to set arrowheads on the lines, as well as set the - * amount of arc a line has (it's currently not implemented). - *

- */ -public class OMDrawingTool extends OMToolComponent implements DrawingTool, Serializable, - PropertyChangeListener, ProjectionListener, EOMGListener, PaintListener, SelectionProvider { - - private static final long serialVersionUID = 1L; - /** - * A GraphicAttributes object that describes the current coloring parameters - * for the current graphic. - */ - protected GraphicAttributes graphicAttributes = GraphicAttributes.getGADefaultClone(); - /** - * The current graphic being modified. - */ - protected EditableOMGraphic currentEditable; - /** - * The MouseDelegator to use to get mouse events directed to the - * DrawingTool. - */ - protected MouseDelegator mouseDelegator; - /** - * A placeholder for the last mouse mode active before the drawing tool took - * over. - */ - protected MapMouseMode formerMouseMode = null; - /** - * The JComponent the drawing tool is servicing, usually the MapBean. - */ - protected JComponent canvas; - /** - * The objects that know how to create a EditableOMGraphic for a particular - * class name or OMGraphic. - */ - protected Map loaders = new HashMap<>(); - /** - * The ordered list of EditToolLoaders, for notification. Preservers order, - * no duplicates. - */ - protected List rawLoaders = new ArrayList<>(); - /** - * The MouseMode used for the drawing tool. - */ - protected OMDrawingToolMouseMode dtmm; - /** - * Flag to allow drawing tool to sense when an OMGraphic is clicked off and - * deactivate. True by default. - */ - protected boolean allowDrawingToolToDeactivateItself = true; - /** - * The component to notify when the drawing tool is finished. - */ - protected DrawingToolRequestor requestor = null; - /** - * The current projection. - */ - protected Projection projection = null; - /** - * A support object to handle telling listeners that the drawing tool is in - * the process of editing an object, hence making it selected. - */ - protected SelectionSupport selectionSupport = null; - /** - * The stack for keeping track of edits and allowing them to be reverted. - */ - protected UndoStack undoStack = null; - protected UndoMenuItemStackTrigger undoTrigger = null; - /** - * A behavior mask to show the GUI for the OMDrawingTool. Since the - * OMDrawingTool is a com.bbn.openmap.gui.Tool object, it will only appear - * on the tool panel if it has been added to it, and if it is being used as - * a tool. - */ - public final static int SHOW_GUI_BEHAVIOR_MASK = 1 << 0; // + 1 - /** - * A behavior mask to add a menu item to the popup that will allow the GUI - * to appear. If the OMDrawingTool is not being used as a tool and this is - * set along with USE_POPUP_BEHAVIOR_MASK or ALT_POPUP_BEHAVIOR_MASK, then - * the OMDrawingTool will appear in a window when the Change Appearance - * option is selected in the popup menu. - */ - public final static int GUI_VIA_POPUP_BEHAVIOR_MASK = 1 << 1; // + 2 - /** - * Flag to tell the OMDrawingTool to display a popup when - * gesturing/modifications appear to be over. Was the default action of the - * tool, but was moved to only happening when the ctrl key or right mouse - * button is pressed. You can force the old behavior by setting this. - */ - public final static int USE_POPUP_BEHAVIOR_MASK = 1 << 2; // + 4 - /** - * Allow a GUI popup to appear over the map when the gesturing/modifications - * appear to be over, and when the ctrl key or right mouse button is - * pressed. - */ - public final static int ALT_POPUP_BEHAVIOR_MASK = 1 << 3; // + 8 - /** - * Set the flag for the behavior that will tell the OMDrawingTool to *NOT* - * add the OMDrawingToolMouseMode to the MouseDelegator as the active mouse - * mode when activated. Should be called before create/edit is called, and - * then you have to make sure that you provide MouseEvents to the - * OMDrawingToolMouseMode or EditableOMGraphic in order to modify the - * OMGraphic. Don't call this if you have already started using the tool, - * the tool won't do anything if anything else is currently being modified. - */ - public final static int PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK = 1 << 4; // + 16 - /** - * This behavior is used internally, when the OMDrawingTool should be told - * to clean up as soon as it is safe. - */ - public final static int DEACTIVATE_ASAP_BEHAVIOR_MASK = 1 << 5; // + 32 - /** - * A convenience value that tells the OMDrawingTool to show the GUI if it is - * a tool, or to only display the popup with the ctrl key or right mouse - * button if it isn't. A combination of SHOW_GUI, GUI_VIA_POPUP and - * ALT_POPUP. - */ - public final static int DEFAULT_BEHAVIOR_MASK = 11; - /** - * A convenience value that tells the OMDrawingTool to not show the GUI, but - * show the popup with the alt key, and the popup has the ability to delete - * the OMGraphic. A combination of GUI_VIA_POPUP and ALT_POPUP. - */ - public final static int QUICK_CHANGE_BEHAVIOR_MASK = 10; - /** - * A integer that is looked at, bitwise, to determine different behaviors. - */ - protected int behaviorMask = DEFAULT_BEHAVIOR_MASK; - /** - * Used for property change notifications. - */ - public final static String LoadersProperty = "OMDrawingTool.loaders"; - /** - * Debug flag turned on when drawingtool debug flag enabled. - */ - protected boolean DEBUG = false; - /** - * A handle to the InformationDelegator to use for status messages. - */ - protected InformationDelegator informationDelegator = null; - /** - * A Vector of Classes that can be handled by the OMDrawingTool. Constructed - * the first time canEdit() is called after an EditToolLoader is added or - * removed. - */ - protected List> possibleEditableClasses = null; - /** - * Just a helper flag to reduce work caused by unnecessary deactivate calls. - * Set internally in activate() and deactivate(). - */ - protected boolean activated = false; - /** - * Tell the drawing tool to be invisible when it is inactive. True by - * default. - */ - protected boolean visibleWhenInactive = true; - /** - * The property, visibleWhenIactive, to set to false if you want that - * behavior. - */ - public final static String VisibleWhenInactiveProperty = "visibleWhenInactive"; - /** - * The property list defining behavior mask values that should be set. - */ - public final static String BehaviorProperty = "behavior"; - /** - * Flag to tell tool to reset the GUI when it is deactivated. The only time - * you would want this to be false (true is default) is when you are - * creating many objects of the same type, and don't want the gui to keep - * going back and forth between the default and special settings. Usually - * set to in the drawingComplete method of an EditorTool. Reset to true when - * showPalette is called. - */ - protected boolean resetGUIWhenDeactivated = true; - - /** - * Create a OpenMap Drawing Tool. - */ - public OMDrawingTool() { - super(); - setBorder(BorderFactory.createEmptyBorder()); - DEBUG = Debug.debugging("drawingtool"); - selectionSupport = new SelectionSupport(this); - setAttributes(new GraphicAttributes()); - setMouseMode(createMouseMode()); - undoStack = new UndoStack(); - undoTrigger = new UndoMenuItemStackTrigger(); - undoStack.addUndoStackTrigger(undoTrigger); - - // Shouldn't assume that the drawing tool is a tool. This can - // be set in the properties if it should be. Otherwise, the - // default action is to appear on a right click called from - // the GUI. - setUseAsTool(false); - } - - /** - * Create the mouse mode used with the drawing tool. Called in the default - * empty constructor, returns a OMDrawingToolMouseMode by default. - */ - protected OMDrawingToolMouseMode createMouseMode() { - return new OMDrawingToolMouseMode(this); - } - - /** - * Create a new OMGraphic, encased in a new EditableOMGraphic that can - * modify it. If a loader cannot be found that can handle a graphic with the - * given classname, this method will return a null object. If you aren't - * sure of the behavior mask set in the tool, and you want a particular - * behavior, set it before calling this method. - * - * @param classname the classname of the graphic to create. - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @return OMGraphic of the classname given, null if the DrawingTool can't - * create it. - */ - public OMGraphic create(String classname, DrawingToolRequestor requestor) { - return create(classname, null, requestor); - } - - /** - * Create a new OMGraphic, encased in a new EditableOMGraphic that can - * modify it. If a loader cannot be found that can handle a graphic with the - * given classname, this method will return a null object. If you aren't - * sure of the behavior mask set in the tool, and you want a particular - * behavior, set it before calling this method. - * - * @param classname the classname of the graphic to create. - * @param ga GraphicAttributes object that contains more information about - * the type of line to be created. - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @return OMGraphic of the classname given, null if the DrawingTool can't - * create it. - */ - public OMGraphic create(String classname, GraphicAttributes ga, DrawingToolRequestor requestor) { - return create(classname, ga, requestor, isMask(SHOW_GUI_BEHAVIOR_MASK)); - } - - /** - * Create a new OMGraphic, encased in a new EditableOMGraphic that can - * modify it. If a loader cannot be found that can handle a graphic with the - * given classname, this method will return a null object. This method gives - * you the option of suppressing the GUI for the EditableOMGraphic. If you - * aren't sure of the behavior mask set in the tool, and you want a - * particular behavior, set it before calling this method. - * - * @param classname the classname of the graphic to create. - * @param ga GraphicAttributes object that contains more information about - * the type of line to be created. - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @param showGUI set to true (default) if a GUI showing attribute controls - * should be displayed. The behaviorMask will be adjusted - * accordingly. - * @return OMGraphic of the classname given, null if the DrawingTool can't - * create it. - */ - public OMGraphic create(String classname, GraphicAttributes ga, DrawingToolRequestor requestor, - boolean showGUI) { - - if (getCurrentEditable() != null) { - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): can't create " + classname - + ", drawing tool busy with another graphic."); - } - return null; - } - - if (DEBUG) { - Debug.output("OMDrawingTool.create(" + classname + ")"); - } - - if (showGUI) { - if (DEBUG) { - Debug.output("OMDrawingTool.create(): showing GUI per request"); - } - setMask(SHOW_GUI_BEHAVIOR_MASK); - } else { - if (DEBUG) { - Debug.output("OMDrawingTool.create(): NOT showing GUI per request"); - } - unsetMask(SHOW_GUI_BEHAVIOR_MASK); - } - - EditableOMGraphic eomg = getEditableGraphic(classname, ga); - - if (eomg == null || eomg.getGraphic() == null) { - return null; - } - - setAttributes(ga); - eomg.setShowGUI(isMask(SHOW_GUI_BEHAVIOR_MASK)); - eomg.setActionMask(OMGraphic.ADD_GRAPHIC_MASK); - - return edit(eomg, requestor); - } - - /** - * Given an OMGraphic, wrap it in the applicable EditableOMGraphic, allow - * the user to make modifications, and then call - * requestor.drawingComplete(). If you aren't sure of the behavior mask set - * in the tool, and you want a particular behavior, set it before calling - * this method. - * - * @param g OMGraphic to modify - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @return OMGraphic being modified, null if the OMDrawingTool can't figure - * out what to use for the modifications. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor) { - return edit(g, requestor, g.getShowEditablePalette()); - } - - /** - * Given an OMGraphic, wrap it in the applicable EditableOMGraphic, allow - * the user to make modifications, and then call - * requestor.drawingComplete(). This methods gives you the option to - * suppress the GUI from the EditableOMGraphic. If you aren't sure of the - * behavior mask set in the tool, and you want a particular behavior, set it - * before calling this method. - * - * @param g OMGraphic to modify - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @param showGUI set to true (default) if a GUI showing attribute controls - * should be displayed. The behaviorMask will be adjusted - * accordingly. - * @return OMGraphic being modified, null if the OMDrawingTool can't figure - * out what to use for the modifications. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor, boolean showGUI) { - - if (g == null) { - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): can't edit null OMGraphic."); - } - return null; - } - - if (getCurrentEditable() != null) { - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): can't edit " + g.getClass().getName() - + ", drawing tool busy with another graphic."); - } - return null; - } - - this.requestor = requestor; - - if (showGUI) { - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): showing GUI per request"); - } - setMask(SHOW_GUI_BEHAVIOR_MASK); - } else { - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): NOT showing GUI per request"); - } - unsetMask(SHOW_GUI_BEHAVIOR_MASK); - } - - EditableOMGraphic eomg = getEditableGraphic(g); - - if (eomg != null) { - eomg.setShowGUI(isMask(SHOW_GUI_BEHAVIOR_MASK)); - eomg.setActionMask(OMGraphic.UPDATE_GRAPHIC_MASK); - return edit(eomg, requestor); - } - - return null; - } - - /** - * Given an EditableOMGraphic, use it to make modifications, and then call - * requestor.drawingComplete(). The requestor is responsible for setting up - * the correct initial state of the EditableOMGraphic. The requestor will be - * given the action mask that is set in the EditableOMGraphic at this point, - * if no other external modifications to it are made. If you aren't sure of - * the behavior mask set in the tool, and you want a particular behavior, - * set it before calling this method. - * - * This method is called by other edit methods. - * - * @param eomg OMGraphic to modify - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @return OMGraphic being modified contained within the EditableOMGraphic. - */ - public OMGraphic edit(EditableOMGraphic eomg, DrawingToolRequestor requestor) { - - if (setCurrentEditable(eomg)) { - - // resetGUI() for current EOMG doesn't need to be called - // here, it's called later from activate - - if (DEBUG) { - Debug.output("OMDrawingTool.edit success"); - } - - this.requestor = requestor; - - if (currentEditable != null) { - graphicAttributes.setFrom(currentEditable.getGraphic()); - activate(); - - // Check currentEditable in case activating caused - // something strange to happen, most likely with - // activating the MouseModes. - if (currentEditable != null) { - return currentEditable.getGraphic(); - } - } - } - - if (DEBUG) { - Debug.output("OMDrawingTool.edit(): can't edit " + eomg.getClass().getName() - + ", drawing tool busy with another graphic."); - } - - return null; - } - - /** - * A slightly different edit method, where the EditableOMGraphic is put - * directly into edit mode, and the mouse events immediately start making - * modifications to the OMGraphic. The palette is not shown, but if you set - * the GUI_VIA_POPUP_BEHAVIOR_MASK on the OMDrawingTool, the option to bring - * up the drawing tool palette will be presented to the user. If you aren't - * sure of the behavior mask set in the tool, and you want a particular - * behavior, set it before calling this method. - * - * @param g OMGraphic to modify - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @param e MouseEvent to use to start editing with. - * @return OMGraphic being modified. - */ - public OMGraphic edit(OMGraphic g, DrawingToolRequestor requestor, MouseEvent e) { - - OMGraphic ret = null; - - if (getCurrentEditable() == null) { - EditableOMGraphic eomg = getEditableGraphic(g); - if (eomg != null) { - ret = edit(eomg, requestor, e); - } - } - - return ret; - } - - /** - * A slightly different edit method, where the EditableOMGraphic is put - * directly into edit mode, and the mouse events immediately start making - * modifications to the OMGraphic. If you aren't sure of the behavior mask - * set in the tool, and you want a particular behavior, set it before - * calling this method. - * - * @param eomg EditableOMGraphic to modify - * @param requestor the Component that is requesting the OMGraphic. The - * requestor gets notified when the user is finished with the - * DrawingTool and the graphic is ready. - * @param e MouseEvent to use to start editing with. - * @return OMGraphic being modified contained within the EditableOMGraphic. - */ - public OMGraphic edit(EditableOMGraphic eomg, DrawingToolRequestor requestor, MouseEvent e) { - - OMGraphic ret = null; - if (eomg != null) { - eomg.setActionMask(OMGraphic.UPDATE_GRAPHIC_MASK); - - ret = edit(eomg, requestor); - - if (ret != null) { - currentEditable.handleInitialMouseEvent(e); - } - } - - return ret; - } - - /** - * Returns true of the OMGraphic is being edited, or is on an - * EditableOMGraphicList being manipulated. - */ - public boolean isEditing(OMGraphic omg) { - boolean ret = false; - EditableOMGraphic eomg = getCurrentEditable(); - if (eomg != null - && eomg.getGraphic() == omg - || (eomg instanceof EditableOMGraphicList && ((OMGraphicList) ((EditableOMGraphicList) eomg).getGraphic()).contains(omg))) { - ret = true; - } - return ret; - } - - public void deselect(OMGraphic omg) { - if (DEBUG) { - Debug.output("OMDrawingTool.deselect()"); - } - - if (getCurrentEditable() != null) { - if (currentEditable.getGraphic() == omg) { - deactivate(); - } else { - if (currentEditable instanceof EditableOMGraphicList) { - ((EditableOMGraphicList) currentEditable).remove(omg); - canvas.repaint(); - } - } - } - } - - /** - * @return true if the OMDrawingTool is editing where it wasn't before. - */ - public boolean select(OMGraphic omg, DrawingToolRequestor req, MouseEvent e) { - - if (DEBUG) { - Debug.output("OMDrawingTool.select()"); - } - - OMGraphic ret = null; - boolean currentlyEditing = (getCurrentEditable() != null); - if (currentlyEditing) { - boolean repaintCanvas = true; - if (!(currentEditable instanceof EditableOMGraphicList)) { - if (DEBUG) { - Debug.output("OMDrawingTool.select: already working on OMGraphic, creating an EditableOMGraphicList for selection mode"); - } - - EditableOMGraphicList eomgl = new EditableOMGraphicList(new OMGraphicList()); - eomgl.setProjection(getProjection()); - DrawingToolRequestorList rl = new DrawingToolRequestorList(); - // Add what's current to the requestor list - rl.add(currentEditable.getGraphic(), requestor); - // then add the current editable to the eomgl - eomgl.add(currentEditable); - currentEditable.removeEOMGListener(this); - - // tell selectionlisteners to disregard the current - // thing. - setCurrentEditable(null); - // reset the requestor to the requestor list - requestor = rl; - // now reactivate with the eomgl - setCurrentEditable(eomgl); - - if (DEBUG) { - EditableOMGraphic ce = getCurrentEditable(); - Debug.output("OMDrawingTool: current editable is: " - + (ce == null ? "null" : ce.getClass().getName())); - } - // Activate the list to make sure the listeners are - // set up - // so the map gets repainted with the new EOMG in - // selected mode - activate(false); - - // Don't need to repaint if we call activate() - repaintCanvas = false; - } else { - // We already have an EditableOMGraphicList, just add - // the new stuff to it. - - if (DEBUG) { - Debug.output("OMDrawingTool.select: already working on EditableOMGraphicList"); - } - } - - // OK, even if we've just created the new EOMGL and added - // a previous OMG to it, we still need to deal with the - // OMG that has just been added into the method. - ((EditableOMGraphicList) currentEditable).add(omg, this); - - if (requestor instanceof DrawingToolRequestorList) { - ((DrawingToolRequestorList) requestor).add(omg, req); - } else { - Debug.error("OHHHH, THE HORRORS!"); - Thread.dumpStack(); - } - - // OK, make the EditableOMGraphic list react to the new - // mouse event, which will also set the state machine, - // which will flow to the new EditableOMGraphic. - ((EditableOMGraphicList) currentEditable).handleInitialMouseEvent(e); - - // Make sure the list is returned. - ret = currentEditable.getGraphic(); - - // Only need to call canvas.repaint() if activate isn't - // called, and this is where that will happen. This makes - // the grab points show up on the new OMGraphic. - if (repaintCanvas && canvas != null) { - canvas.repaint(); - } - } else { - if (DEBUG) { - Debug.output("OMDrawingTool.select: activating for: " + omg.getClass().getName()); - } - - // Since this is the first OMG in the tool at this point, - // it's standard editing behavior.... - ret = edit(omg, req, e); - } - - return ret != null; - } - - /** - * Given a classname, check the EditToolLoaders and create the OMGraphic it - * represents wrapped in an EditableOMGraphic. - * - * @param classname the classname of an OMGraphic to create. - * @param ga GraphicAttributes needed to initialize the OMGraphic. - * @return EdtiableOMGraphic, or null if none of the loaders can figure out - * what to make. - */ - public EditableOMGraphic getEditableGraphic(String classname, GraphicAttributes ga) { - - EditableOMGraphic eomg = null; - EditToolLoader loader = (EditToolLoader) loaders.get(classname); - if (loader == null) { - - if (DEBUG) { - Debug.output("OMDrawingTool.getEditableGraphic(" + classname - + ") - rechecking loaders"); - } - - // The loaders may be able to instantiate objects they - // don't want in the GUI - check to see if they can.. - for (EditToolLoader ldr : loaders.values()) { - eomg = ldr.getEditableGraphic(classname, ga); - if (eomg != null) { - break; - } - } - - } else { - eomg = loader.getEditableGraphic(classname, ga); - } - - if (eomg instanceof EditableOMGraphicList) { - ((EditableOMGraphicList) eomg).init(this); - } - - return eomg; - } - - /** - * Given an OMGraphic, check the EditToolLoaders and wrap it in an - * EditableOMGraphic. - * - * @param g the OMGraphic being wrapped. - * @return EdtiableOMGraphic, or null if none of the loaders can figure out - * what to make. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic g) { - - // This is what we need to do to handle an OMGraphicList - // handled for editing, but we still need to come up with a - // way to handle DrawingToolRequestors. - - // if (g instanceof OMGraphicList) { - // EditableOMGraphicList eomgl = - // new EditableOMGraphicList((OMGraphicList)g); - // eomgl.init(this); - // return eomgl; - // } - - for (String key : loaders.keySet()) { - - if (DEBUG) { - Debug.output("OMDrawingTool.getEditableGraphic(" + g.getClass().getName() - + "): looking at (" + key + ") loader."); - } - - try { - Class kc = Class.forName(key); - Class gc = g.getClass(); - if (kc == gc || kc.isAssignableFrom(gc)) { - EditToolLoader loader = (EditToolLoader) loaders.get(key); - - if (loader == null) { - return null; - } - - // There is a reason why the generation of the - // graphic is done here. I think it has to do - // with something with the creation of the - // EditableOMGraphic and its display with the - // GrabPoints. - generateOMGraphic(g); - - EditableOMGraphic eomg = loader.getEditableGraphic(g); - - if (DEBUG) { - Debug.output("OMDrawingTool.getEditableGraphic(" + g.getClass().getName() - + "): found one."); - } - - return eomg; - } - } catch (ClassNotFoundException cnfe) { - if (DEBUG) { - Debug.output("OMDrawingTool.getEditableGraphic(" + g.getClass().getName() - + ") comparision couldn't find class for " + key); - } - } - } - return null; - } - - /** - * Return true if the OMDrawingTool can edit the OMGraphic. Meant to be a - * low-cost check, with a minimal allocation of memory. - */ - public boolean canEdit(Class omgc) { - if (possibleEditableClasses == null) { - Set keys = loaders.keySet(); - possibleEditableClasses = new ArrayList<>(keys.size()); - - for (String key : keys) { - try { - possibleEditableClasses.add(Class.forName(key)); - } catch (ClassNotFoundException cnfe) { - // Don't worry about this now... - } - } - } - - for (Class kc : possibleEditableClasses) { - if (kc == omgc || kc.isAssignableFrom(omgc)) { - return true; - } - } - return false; - } - - /** - * Set the EditableOMGraphic being used, if it hasn't already been set. You - * can set it to null all the time. This method triggers the selection - * listeners. - */ - public synchronized boolean setCurrentEditable(EditableOMGraphic eomg) { - - if (currentEditable == null || eomg == null) { - // Moved here so that currentEditable is set when the - // events are fired, in case someone want's to know when - // an OMGraphic has been selected. - currentEditable = eomg; - - if (selectionSupport != null) { - if (eomg == null && currentEditable != null) { - // No longer being edited. - selectionSupport.fireSelection(currentEditable.getGraphic(), requestor, false); - } else if (eomg != null) { - // Starting to be edited. - selectionSupport.fireSelection(eomg.getGraphic(), requestor, true); - } // else all is null, ignore... - } - - if (currentEditable != null) { - currentEditable.setUndoStack(undoStack); - return true; - } - } - - return false; - } - - /** - * Get the current EditableOMGraphic being used by the drawing tool. Could - * be null if nothing valid is happening, i.e. if the OMDrawingTool isn't - * actively editing something. - */ - public synchronized EditableOMGraphic getCurrentEditable() { - return currentEditable; - } - - /** - * If you need your OMDrawingToolMouseMode to do something a little - * different, you can substitute your subclass here. Don't set this to null. - */ - public void setMouseMode(OMDrawingToolMouseMode adtmm) { - dtmm = adtmm; - } - - /** - * If you want to run the drawing tool in passive mode, you'll need a handle - * on the mouseMode to feed events to. - */ - public OMDrawingToolMouseMode getMouseMode() { - return dtmm; - } - - /** - * Add an EditToolLoader to the Hashtable of loaders that the OMDrawingTool - * can use to create/modify OMGraphics. - */ - public void addLoader(EditToolLoader loader) { - String[] classnames = loader.getEditableClasses(); - rawLoaders.add(loader); - // Add the loader to the hashtable, with the classnames as - // keys. Then, when we get a request for a classname, we do - // a lookup and get the proper loader for the key. - if (classnames != null) { - for (int i = 0; i < classnames.length; i++) { - loaders.put(classnames[i].intern(), loader); - } - possibleEditableClasses = null; - } - firePropertyChange(LoadersProperty, null, rawLoaders); - } - - /** - * Make sure that new property change listeners receive a current list of - * edit tool loaders. - */ - public void addPropertyChangeListener(PropertyChangeListener listener) { - if (listener != null) { - super.addPropertyChangeListener(listener); - listener.propertyChange(new PropertyChangeEvent(this, LoadersProperty, null, rawLoaders)); - } - } - - /** - * Remove an EditToolLoader from the Hashtable of loaders that the - * OMDrawingTool can use to create/modify OMGraphics. - */ - public void removeLoader(EditToolLoader loader) { - String[] classnames = loader.getEditableClasses(); - - // Remove the loader to the hashtable, with the classnames as - // keys. - if (classnames != null) { - for (int i = 0; i < classnames.length; i++) { - EditToolLoader etl = (EditToolLoader) loaders.get(classnames[i].intern()); - if (etl == loader) { - loaders.remove(classnames[i]); - } else { - if (DEBUG) { - Debug.output("DrawingTool.removeLoader: loader to be removed isn't the current loader for " - + classnames[i] + ", ignored."); - } - } - } - rawLoaders.remove(loader); - firePropertyChange(LoadersProperty, null, rawLoaders); - possibleEditableClasses = null; - } - } - - /** - * Get an array of all the loaders the OMDrawingTool has access to. - */ - public EditToolLoader[] getLoaders() { - return loaders.values().toArray(new EditToolLoader[loaders.size()]); - } - - /** - * Set the loaders that the OMDrawingTool has access to. - */ - public void setLoaders(EditToolLoader[] etls) { - loaders.clear(); - rawLoaders.clear(); - if (etls != null) { - for (int i = 0; i < etls.length; i++) { - addLoader(etls[i]); - } - } - } - - public void resetGUIWhenDeactivated(boolean value) { - resetGUIWhenDeactivated = value; - } - - /** - * Get the GUI that dictates what the OMDrawingTool has control over. This - * should include a section on controlling the GraphicAttributes, a section - * for controls provided by the current EditableOMGraphic for parameters - * unique to the EOMG, and any other controls that the tool may need. This - * method now returns this OMDrawingTool, but also serves as a reset method - * for the GUI to configure itself for the current EditableOMGraphic. - *

- * - * To create different types of graphics, the OMDrawingToolMouseMode can be - * used, to attach to a layer to make it a drawing layer. The Loaders can be - * queried to get their trigger graphics so you can load the drawing tool - * with a particular loader to create a particular graphic. But here, we - * just deal with the actual controls over the particular graphic loaded and - * being modified. - *

- * - * @return this. - */ - public Component getGUI() { - if (!resetGUIWhenDeactivated) { - return this; - } - - removeAll(); - Component eomgc = null; - - graphicAttributes.setLineMenuAdditions(null); - graphicAttributes.setOrientation(getOrientation()); - - // We're adding these separately now, not as part of the interface for - // the - // EditableOMGraphic. - if (graphicAttributes != null) { - - add(graphicAttributes.getGUI()); - } - - if (currentEditable != null) { - // GUI specific to a particular EditableOMGraphic type. - eomgc = currentEditable.getGUI(graphicAttributes); - if (eomgc != null) { - add(eomgc); - } - } - - revalidate(); - return this; - } - - public void setInformationDelegator(InformationDelegator id) { - informationDelegator = id; - } - - public InformationDelegator getInformationDelegator() { - return informationDelegator; - } - - /** - * Put the message in a display line that the OMDrawingTool is using. - */ - public void setRemarks(String message) { - if (informationDelegator != null) { - informationDelegator.displayInfoLine(message, InformationDelegator.MAP_OBJECT_INFO_LINE); - } - } - - /** - * Convenience function to tell if the OMDrawingTool is currently working on - * an OMGraphic. - */ - public boolean isActivated() { - return activated; - } - - /** - * Turn the OMDrawingTool on, attaching it to the MouseDelegator or the - * canvas component it is assigned to. Also brings up the drawing palette. - * Called automatically from the create/edit methods. - */ - protected synchronized void activate() { - activate(true); - } - - /** - * Turn the OMDrawingTool on with the caveat that the OMDrawingTool may be - * active already, and that a complete hookup may not be needed. If a - * complete hookup is needed, this methid will attach the OMDrawingTool to - * the MouseDelegator or the canvas component it is assigned to and display - * the drawing palette. Called automatically from the create/edit methods - * for complete hookup. Partial hookup is called from select() methods. - */ - protected synchronized void activate(boolean completeHookup) { - activated = true; - - if (DEBUG) { - Debug.output("OMDrawingTool: activate()"); - } - if (currentEditable != null && graphicAttributes != null) { - // For partial hookups, for select() we don't need this. - if (completeHookup) { - graphicAttributes.setTo(currentEditable.getGraphic()); - currentEditable.getGraphic().setVisible(false); - } - currentEditable.addEOMGListener(this); - - // If we're editing a existing OMGraphic, we need to save current - // state. We can check that because existing OMGraphics should be - // selected at this point. - if (currentEditable.getStateMachine().getState() instanceof GraphicSelectedState) { - currentEditable.updateCurrentState(null); - } - } - - if (!isMask(PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK) && completeHookup) { - if (mouseDelegator != null) { - if (Debug.debugging("drawingtooldetail")) { - Debug.output("OMDrawingTool.activate() mousemode connecting to MouseDelegator"); - } - formerMouseMode = mouseDelegator.getActiveMouseMode(); - mouseDelegator.setActiveMouseMode(dtmm); - - } else if (canvas != null) { - // If a MouseDelegator is not being used, go directly - // to - // the MapBean. - if (Debug.debugging("drawingtooldetail")) { - Debug.output("OMDrawingTool.activate() mousemode connecting directly to canvas"); - } - canvas.addMouseListener(dtmm); - canvas.addMouseMotionListener(dtmm); - } else { - Debug.error("Drawing Tool can't find a map to work with"); - } - } - - // The Drawing tool is added as a projection listener so that - // it can properly update the current graphic if the map - // projection changes during graphic creation/edit. - - if (canvas != null) { - if (canvas instanceof MapBean && completeHookup) { - ((MapBean) canvas).addPaintListener(this); - ((MapBean) canvas).addProjectionListener(this); - } - // Gets the graphic highlighted on the map, if needed. - canvas.repaint(); - } - - if (completeHookup) { - // Show the gui. - showPalette(); - } - } - - /** - * Turn the drawing tool off, disconnecting it from the MouseDelegator or - * canvas component, and removing the palette. Called automatically from the - * mouse mode an GUI when appropriate, although you can force a cleanup if - * needed by calling this method. Calling this version of deactivate() just - * uses the action mask stored in the EditableOMGraphic, which knows if the - * graphic is being updated or created. - */ - public void deactivate() { - int actionMask = 0; - if (currentEditable != null) { - actionMask = currentEditable.getActionMask(); - } - deactivate(actionMask); - } - - /** - * Turn the drawing tool off, disconnecting it from the MouseDelegator or - * canvas component, and removing the palette. This version can called when - * you want to control what action is taken by the receiver. - * - * @param actionToDoWithOMGraphic a masked int from OMGraphicConstants that - * describes an OMAction to take on the current editable. - * @see com.bbn.openmap.omGraphics.OMGraphicConstants - */ - public synchronized void deactivate(int actionToDoWithOMGraphic) { - if (DEBUG) { - Debug.output("OMDrawingTool: deactivate(" - + (activated ? "while active" : "while inactive") + ")"); - } - - // Don't waste effort; - if (!activated) { - return; - } - - if (!isMask(PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK)) { - if (mouseDelegator != null) { - mouseDelegator.setActiveMouseMode(formerMouseMode); - mouseDelegator.removeMouseMode(dtmm); - } else if (canvas != null) { - // If a MouseDelegator is not being used, go directly - // to - // the canvas. - canvas.removeMouseListener(dtmm); - canvas.removeMouseMotionListener(dtmm); - } - } - - if (canvas != null) { - if (canvas instanceof MapBean) { - ((MapBean) canvas).removeProjectionListener(this); - ((MapBean) canvas).removePaintListener(this); - } - } - - OMGraphic g = null; - - if (currentEditable != null) { - if (!(currentEditable.getStateMachine().getState() instanceof com.bbn.openmap.omGraphics.editable.GraphicUndefinedState)) { - g = currentEditable.getGraphic(); - } - currentEditable.removeEOMGListener(this); - } - - // //////////////////////////////// - // Clean up, then notify listener - - setCurrentEditable(null); - // hide the gui while currentEditable is null, so it resets to - // the default. - hidePalette(); - unsetMask(DEACTIVATE_ASAP_BEHAVIOR_MASK); - popup = null; - activated = false; - undoStack.clearStacks(true, true); - - // End cleanup - // //////////////////////////////// - - /** - * Just need something to allow editors to clean up with the mouse - * modes. Only does this if the action to take is to delete the - * non-existent graphic. - */ - if (g == null && (actionToDoWithOMGraphic & OMAction.DELETE_GRAPHIC_MASK) > 0) { - g = SinkGraphic.getSharedInstance(); - } - - if (g != null && requestor != null) { - g.setVisible(true); - OMAction action = new OMAction(); - action.setMask(actionToDoWithOMGraphic); - generateOMGraphic(g); - notifyListener(g, action); - } - - // By putting this here, it gives the listener the slight - // opportunity to not have the gui reset right away. This - // opportunity gives an editor tool a smoother runtime when - // duplicate objects are being created one after another, and - // you don't want all the GUI reconfiguring to happen when it - // will just go back to the same thing in a second. - getGUI(); - - } - - /** - * If the projection is not null, generate the OMGraphic. - */ - protected void generateOMGraphic(OMGraphic g) { - if (g != null && g.getNeedToRegenerate()) { - Projection proj = getProjection(); - if (proj != null) { - g.generate(proj); - } else if (DEBUG) { - Debug.output("OMDrawingTool: graphic needs generation: " + g.getNeedToRegenerate()); - } - } - } - - /** - * Notify the listener of an action to a graphic. - * - * @param graphic the graphic being created/modified - * @param action the OMAction telling the listener what to do with the - * graphic. - */ - public void notifyListener(OMGraphic graphic, OMAction action) { - if (requestor != null) { - if (DEBUG) { - Debug.output("OMDrawingTool: notifying requestor, graphic with action"); - } - requestor.drawingComplete(graphic, action); - } - - // in case the requestor is a layer that is not visible - if (canvas != null) { - canvas.repaint(); - } - } - - /** - * ProjectionListener method. Helps if the currentEditable is set. - */ - public void projectionChanged(ProjectionEvent e) { - setProjection((Projection) e.getProjection().makeClone()); - } - - /** - * Set the current projection. Tells the currentEditable what it is too. - */ - public void setProjection(Projection proj) { - projection = proj; - if (currentEditable != null) { - currentEditable.setProjection(projection); - } - } - - /** - * Get the current projection, if one has been provided. If one has not been - * provided, then the canvas is checked to see if it is a MapBean. If it is, - * then that projection is returned. If that doesn't work, it will finally - * return null. - */ - public Projection getProjection() { - if (projection == null && canvas instanceof MapBean) { - projection = ((MapBean) canvas).getProjection(); - } - return projection; - } - - /** - * Set the GraphicAttributes object used to fill the OMGraphic - * java.awt.Graphics parameters. - */ - public void setAttributes(GraphicAttributes da) { - if (graphicAttributes != null) { - graphicAttributes.getPropertyChangeSupport().removePropertyChangeListener(this); - } - - if (da == null) { - graphicAttributes = GraphicAttributes.DEFAULT; - } else { - graphicAttributes = da; - } - - graphicAttributes.getPropertyChangeSupport().addPropertyChangeListener(this); - - if (currentEditable != null) { - graphicAttributes.setTo(currentEditable.getGraphic()); - } - } - - /** - * Get the DrawingAttributes driving the parameters of the current graphic. - */ - public GraphicAttributes getAttributes() { - return graphicAttributes; - } - - /** - * PaintListener interface. We want to know when the canvas is repainted. - * - * @param source object being painted. - * @param g the Graphics to draw into. - */ - public void listenerPaint(Object source, Graphics g) { - // Call repaintRender here because if the graphic is in the - // middle of being moved, we'll draw it in the mouse event - // thread. Otherwise, it gets set in the image for the - // background, which looks bad. - if (currentEditable != null) { - // do g.create() to prevent Stroke remnants from affecting - // the Border of the canvas. - currentEditable.repaintRender(g.create()); - } - } - - /** - * Set the MouseDelegator used to receive mouse events. - */ - public void setMouseDelegator(MouseDelegator md) { - if (mouseDelegator != null) { - mouseDelegator.removePropertyChangeListener(this); - } - - mouseDelegator = md; - - if (mouseDelegator != null) { - mouseDelegator.addPropertyChangeListener(this); - } - } - - /** - * Get the MouseDelegator used to receive mouse events. - */ - public MouseDelegator getMouseDelegator() { - return mouseDelegator; - } - - public void setCursor(java.awt.Cursor cursor) { - if (canvas != null) { - canvas.setCursor(cursor); - } - } - - public java.awt.Cursor getCursor() { - if (canvas != null) { - return canvas.getCursor(); - } else { - return null; - } - } - - /** - * Set the JComponent this thing is directing events for. If the - * MouseDelegator is not set, the Canvas is contacted to get MouseEvents - * from. Within the BeanContext, the OMDrawingTool looks for MapBeans to use - * as canvases. - */ - public void setCanvas(JComponent can) { - canvas = can; - } - - /** - * Get the JComponent this thing is directing events for. - */ - public JComponent getCanvas() { - return canvas; - } - - /** - * Set whether the Tool's face should be used. The subclasses to this class - * should either remove all components from its face, or make its face - * invisible if this is set to false. - */ - // public void setUseAsTool(boolean value) { - // super.setUseAsTool(value); - // } - /** - * Called from the findAndInit(Iterator) method, when objects are added to - * the MapHandler. so the OMDrawingTool can hook up with what it needs. An - * InformationDelegator is used to provide map coordinates of the mouse - * movements. The MouseDelegator is used to intercept MouseEvents when the - * OMDrawingTool is activated. The MapBean is used to get mouse events if - * the MouseDelegator isn't loaded, and is also used to help out with smooth - * repaints() in general. EditToolLoaders are looked for to load into the - * OMDrawingTool to handler different graphic requests. - */ - public void findAndInit(Object someObj) { - - if (someObj instanceof InformationDelegator) { - if (DEBUG) { - Debug.output("DrawingTool: found InformationDelegator"); - } - if (dtmm != null) { - dtmm.setInfoDelegator((InformationDelegator) someObj); - } - setInformationDelegator((InformationDelegator) someObj); - } - if (someObj instanceof MouseDelegator) { - if (DEBUG) { - Debug.output("DrawingTool: found MouseDelegator."); - } - setMouseDelegator((MouseDelegator) someObj); - } - if (someObj instanceof MapBean) { - if (DEBUG) { - Debug.output("DrawingTool: found MapBean."); - } - setCanvas((JComponent) someObj); - } - if (someObj instanceof EditToolLoader) { - if (DEBUG) { - Debug.output("DrawingTool: found EditToolLoader: " + someObj.getClass().getName()); - } - addLoader((EditToolLoader) someObj); - } - } - - /** - * Called by childrenRemoved, it provides a good method for handling any - * object you may want to take away from the OMDrawingTool. The - * OMDrawingTool figures out if it should disconnect itseld from the object. - */ - public void findAndUndo(Object someObj) { - if (someObj == getInformationDelegator()) { - if (dtmm != null && dtmm.getInfoDelegator() == (InformationDelegator) someObj) { - dtmm.setInfoDelegator(null); - } - setInformationDelegator(null); - } - if (someObj == getMouseDelegator()) { - setMouseDelegator(null); - } - if (someObj == getCanvas()) { - setCanvas(null); - } - if (someObj instanceof EditToolLoader) { - removeLoader((EditToolLoader) someObj); - } - } - - // ////////////// end BeanContext stuff - /** - * Display the palette. - */ - public void showPalette() { - Debug.message("drawingtool", "OMDrawingTool.showPalette()"); - resetGUIWhenDeactivated = true; - getGUI(); // resets the gui. - - /* - * This repaint needs to be here because sometimes the GUI doesn't - * update on the revalidate being called in the GUI. - */ - repaint(); - - // Should only be visible if the tool isn't being used as a - // tool, which means that it's being held by something else, - // or if it is a tool and the SHOW_GUI flag is set. - boolean shouldBeVisible = !getUseAsTool() - || (isMask(SHOW_GUI_BEHAVIOR_MASK) && getUseAsTool()); - - setVisible(shouldBeVisible); - } - - /** - * Hide the OMDrawingTool palette. - */ - public void hidePalette() { - Debug.message("drawingtool", "OMDrawingTool.hidePalette()"); - - setVisible(visibleWhenInactive); - - WindowSupport ws = getWindowSupport(); - if (ws != null) { - ws.killWindow(); - } - } - - public void showInWindow() { - if (!getUseAsTool() && getWindowSupport() == null) { - setWindowSupport(new WindowSupport(getGUI(), i18n.get(OMDrawingTool.class, "drawingtool", "Drawing Tool"))); - } - - WindowSupport ws = getWindowSupport(); - - if (ws != null && !getUseAsTool()) { - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - int xoffset = 0; - int yoffset = 0; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - if (frame != null) { - xoffset = frame.getX(); - yoffset = frame.getY(); - } - } - - ws.displayInWindow(frame, WindowSupport.Dlg.class, windowx + xoffset, windowy + yoffset, -1, -1); - } else { - Debug.output("OMDrawingTool.showPalette(): NOT showing palette, ws == null:" - + (ws == null) + ", used as tool:" + getUseAsTool()); - } - } - - /** - * A integer that is looked at internally, bitwise, to determine different - * behaviors. If you care about specific behavior of the DrawingTool, you - * should set this to what you want to make sure the tool acts the way you - * want. - */ - public void setBehaviorMask(int mask) { - behaviorMask = mask; - } - - /** - * A integer that is looked at internally, bitwise, to determine different - * behaviors. - */ - public int getBehaviorMask() { - return behaviorMask; - } - - /** - * Set the behavior mask to the default. - */ - public void resetBehaviorMask() { - behaviorMask = DEFAULT_BEHAVIOR_MASK; - } - - /** - * Set a particular mask bit in the internal value. - * - * @param mask an OMDrawingTool behavior mask. - * @return the changed integer value. - */ - public int setMask(int mask) { - behaviorMask = OMAction.setMask(behaviorMask, mask); - return behaviorMask; - } - - /** - * Unset a particular mask bit in the internal value. - * - * @param mask an OMDrawingTool behavior mask. - * @return the changed integer value. - */ - public int unsetMask(int mask) { - behaviorMask = OMAction.unsetMask(behaviorMask, mask); - return behaviorMask; - } - - /** - * Return whether a mask value is set in the internal value. - * - * @param mask an OMDrawingTool behavior mask. - * @return whether the value bit is set on the internal value. - */ - public boolean isMask(int mask) { - return OMAction.isMask(behaviorMask, mask); - } - - /** - * PropertyChangeListener method. If DrawingAttribute parameters change, - * this method is called, and we update the OMGraphic parameters. - */ - public void propertyChange(PropertyChangeEvent pce) { - Object source = pce.getSource(); - if (source instanceof DrawingAttributes && currentEditable != null) { - graphicAttributes.setTo(currentEditable.getGraphic()); - - if (projection != null) { - currentEditable.regenerate(projection); - } - - if (canvas != null) { - canvas.repaint(); - } - } else if (source.equals(mouseDelegator)) { - Object oldValue = pce.getOldValue(); - if (this.equals(oldValue)) { - deactivate(); - } - } - } - - /** - * Used to hold the last thing displayed to the remarks window. - */ - String lastRemarks = ""; - JPopupMenu popup = null; - int windowx, windowy; - - /** - * This is a EOMGListener method, and gets called by the EditableOMGraphic - * when something changes. - */ - public void eomgChanged(EOMGEvent event) { - if (Debug.debugging("drawingtooldetail")) { - Debug.output("OMDrawingTool.eomgChanged()"); - } - - Cursor cursor = event.getCursor(); - if (cursor != null) { - setCursor(cursor); - } - - // We might have used the InformationDelgator to put the - // comments - // in the info line, but that can't work, because we are - // already putting the lat/lon info on the info line. - - // Updated, 4.6 - now that the InformationDelegator has new - // places for coordinate information and map object - // information, we can sent the info there, and it looks OK. - - String message = event.getMessage(); - if (message != null && !message.equals(lastRemarks)) { - lastRemarks = message; - setRemarks(message); - } - - if (event.shouldShowGUI() && isMask(ALT_POPUP_BEHAVIOR_MASK)) { - if (DEBUG) { - Debug.output("OMDrawingTool.eomgChanged(): try for menu."); - } - MouseEvent me = event.getMouseEvent(); - - // While we're here, get a good place for the window in - // case we need to put it up later. - if (currentEditable != null) { - - currentEditable.getStateMachine().setSelected(); - currentEditable.redraw(me, true); - - Shape ces = currentEditable.getGraphic().getShape(); - if (ces != null) { - Rectangle rect = ces.getBounds(); - windowx = (int) rect.getX(); - windowy = (int) rect.getY() - 50; - } - } - - /** - * Let's see if we should bring up pop-up menu with all sorts of - * lovely options - if the right mouse key was pressed, or if the - * ctrl key was pressed with the mouse button being released, - * display the option menu. Otherwise, just get ready to end. - */ - boolean popupIsUp = doPopup(me.getX(), me.getY(), null); - - currentEditable.setPopupIsUp(popupIsUp); - } else if (event.shouldDeactivate() && isAllowDrawingToolToDeactivateItself()) { - if (DEBUG) { - Debug.output("OMDrawingTool.eomgChanged(): omdt being told to deactivate"); - } - - if (isMask(USE_POPUP_BEHAVIOR_MASK) && !getUseAsTool()) { - EditableOMGraphic eomg = getCurrentEditable(); - if (eomg != null) { - java.awt.Shape shape = eomg.getGraphic().getShape(); - Rectangle rect = shape.getBounds(); - - List vec = new ArrayList<>(); - vec.add(new JSeparator()); - - JMenuItem done = new JMenuItem("Done"); - done.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent ae) { - deactivate(); - } - }); - vec.add(done); - - if (!doPopup((int) (rect.getX() + rect.getWidth()), (int) (rect.getY() + rect.getHeight()), vec)) { - deactivate(); - } - } - } else { - deactivate(); - } - } - } - - public boolean isAllowDrawingToolToDeactivateItself() { - return allowDrawingToolToDeactivateItself; - } - - public void setAllowDrawingToolToDeactivateItself(boolean allow) { - allowDrawingToolToDeactivateItself = allow; - } - - protected boolean doPopup(int x, int y, List additionalOptions) { - // TODO This prevents piggybacking and updating of menu. Eliminate the - // test, always create a new popup. Also, popup should be protected, not - // visible from subclasses. - - // Also, DrawingToolRequestor should be modified to allow the - // OMDrawingTool to ask it for additionalOptions for a given - // EditableOMGraphic - - // Also also, the OMGraphic should store the class name of the - // editableomgraphic it wants to have used on it in it's attributes. - - if (additionalOptions != null && !additionalOptions.isEmpty()) { - popup = null; - } - - boolean showPopup = (popup != null); - - if (popup == null && !getUseAsTool()) { - popup = createPopupMenu(); - - if (additionalOptions != null && !additionalOptions.isEmpty() && popup != null) { - for (Component comp : additionalOptions) { - popup.add(comp); - } - } - - showPopup = (popup != null); - } - - if (showPopup) { - - JComponent map = null; - if (mouseDelegator != null) { - map = mouseDelegator.getMap(); - } else if (canvas != null) { - // If a MouseDelegator is not being used, go - // directly to the MapBean. - map = canvas; - } - - if (map != null && x >= 0 && y >= 0) { - popup.show(map, x, y); - } else { - Debug.error("OMDrawingTool: no " + (map == null ? "/component" : "/") - + ((x < 0 || y < 0) ? "location/" : "/") + " to show popup on!"); - } - return true; - } - - return false; - } - - public JPopupMenu createPopupMenu() { - - OMGraphic g = getCurrentEditable().getGraphic(); - JPopupMenu pum = new JPopupMenu(); - - if ((g.getAttribute(OMGraphicConstants.CHANGE_APPEARANCE)) == null - || ((Boolean) g.getAttribute(OMGraphicConstants.CHANGE_APPEARANCE)).booleanValue()) { - - JMenuItem gui = new JMenuItem(i18n.get(OMDrawingTool.class, "popupMenuChangeAppearance", "Attributes...")); - gui.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent ae) { - EditableOMGraphic eomg = getCurrentEditable(); - if (eomg != null) { - boolean previous = eomg.getShowGUI(); - eomg.setShowGUI(true); - setVisible(true); - if (!getUseAsTool()) { - showInWindow(); - } - eomg.setShowGUI(previous); - eomg.getStateMachine().setSelected(); - } - } - }); - - // This is where we are going to add the DrawingAttributes menu. We - // need to take it off the - // EOMG gui palettes, though - pum.add(graphicAttributes.getColorAndLineMenu()); - - if (isMask(SHOW_GUI_BEHAVIOR_MASK | GUI_VIA_POPUP_BEHAVIOR_MASK) && !getUseAsTool()) { - pum.add(gui); - } else { - Debug.output("Not adding Change Appearance to popup: guiViaPopup(" - + isMask(SHOW_GUI_BEHAVIOR_MASK) + ") isTool(" + getUseAsTool() + ")"); - } - } - - if ((g.getAttribute(OMGraphicConstants.REMOVABLE)) == null - || ((Boolean) g.getAttribute(OMGraphicConstants.REMOVABLE)).booleanValue()) { - - JMenuItem delete = new JMenuItem(i18n.get(OMDrawingTool.class, "popupMenuDelete", "Delete")); - delete.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent ae) { - OMAction action = new OMAction(); - action.setMask(OMGraphic.DELETE_GRAPHIC_MASK); - EditableOMGraphic eomg = getCurrentEditable(); - if (eomg != null) { - OMGraphic g = eomg.getGraphic(); - if (g != null) { - notifyListener(g, action); - } - } - setCurrentEditable(null); - deactivate(); - } - }); - pum.add(delete); - } - - pum.addSeparator(); - pum.add(undoTrigger.getUndoMenuItem()); - pum.add(undoTrigger.getRedoMenuItem()); - - // JMenuItem reset = new JMenuItem("Undo Changes"); - // reset.setEnabled(false); - // reset.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent ae) { - // if (currentEditable != null) { - // currentEditable.reset(); - // } - // } - // }); - - // pum.add(reset); - - return pum.getComponentCount() > 0 ? pum : null; - } - - // ////////// SelectionListener support - public void addSelectionListener(SelectionListener list) { - if (selectionSupport != null) { - selectionSupport.addSelectionListener(list); - } - } - - public void removeSelectionListener(SelectionListener list) { - if (selectionSupport != null) { - selectionSupport.removeSelectionListener(list); - } - } - - public void clearSelectionListeners() { - if (selectionSupport != null) { - selectionSupport.clearSelectionListeners(); - } - } - - // ////////// SelectionListener support ends - public static void main(String[] args) { - OMDrawingTool omdt = new OMDrawingTool(); - omdt.showPalette(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - visibleWhenInactive = PropUtils.booleanFromProperties(props, prefix - + VisibleWhenInactiveProperty, visibleWhenInactive); - getGUI(); - setVisible(visibleWhenInactive); - - String behaviorList = props.getProperty(prefix + BehaviorProperty); - - if (behaviorList != null) { - List behaviorStrings = PropUtils.parseSpacedMarkers(behaviorList); - int behavior = 0; - for (String behaviorString : behaviorStrings) { - try { - int val = OMDrawingTool.class.getField(behaviorString).getInt(null); - behavior |= val; - } catch (NoSuchFieldException nsfe) { - } catch (IllegalAccessException iae) { - } - - } - - setMask(behavior); - } - - } - // TODO need to override getProperties to include Behavior mask settings. -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolLauncher.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolLauncher.java deleted file mode 100644 index e0cda2136..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolLauncher.java +++ /dev/null @@ -1,827 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMDrawingToolLauncher.java,v $ -// $RCSfile: OMDrawingToolLauncher.java,v $ -// $Revision: 1.21 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; - -import com.bbn.openmap.InformationDelegator; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.OMToolComponent; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * This tool is a widget that calls the OMDrawingTool to create a specific - * graphic. The launcher is completely configured by EditToolLaunchers it gets - * told about from the DrawingTool, and OMGraphicHandlers that it finds in a - * MapHandler. There are no methods to manually add stuff to this GUI. - *

- * - * There are two properties that can be set for the launcher: - * - *

- * 
- * 
- * 
- * 
- *       # Number of launcher buttons to place in a row in that part of the
- *       # GUI. -1 (the default) is to keep them all on one line.
- *       omdtl.horizNumLoaderButtons=-1
- * 
- *       # If set to true, a text popup will be used for the OMGraphic
- *       # loaders instead of buttons (false is default).
- *       omdtl.useTextLabels=false
- * 
- * 
- * 
- * 
- */ -public class OMDrawingToolLauncher extends OMToolComponent implements ActionListener, PropertyChangeListener { - - private static final long serialVersionUID = 1L; - protected DrawingTool drawingTool; - protected boolean useTextEditToolTitles = false; - protected GraphicAttributes defaultGraphicAttributes = new GraphicAttributes(); - public int maxHorNumLoaderButtons = -1; - - // Places buttons in alphabetical order - // protected TreeMap loaders = new TreeMap(); - protected Vector loaders = new Vector(); - - protected Vector drawingToolRequestors = new Vector(); - - protected DrawingToolRequestor currentRequestor; - protected String currentCreation; - protected JComboBox requestors; - protected JButton createButton; - protected JPanel panel3; - - /** - * Property for setting the maximum number of loader buttons to allow in the - * horizontal direction in the GUI (horizNumLoaderButtons). -1 means to just lay - * them out in one row. - */ - public final static String HorizontalNumberOfLoaderButtonsProperty = "horizNumLoaderButtons"; - public final static String UseLoaderTextProperty = "useTextLabels"; - - String[] rtc = { i18n.get(OMDrawingToolLauncher.class, "renderingType.LatLon", "Lat/Lon"), - i18n.get(OMDrawingToolLauncher.class, "renderingType.XY", "X/Y"), - i18n.get(OMDrawingToolLauncher.class, "renderingType.XYOffset", "X/Y Offset") }; - - public final static String CreateCmd = "CREATE"; - - /** Default key for the DrawingToolLauncher Tool. */ - public static final String defaultKey = "omdrawingtoollauncher"; - - public OMDrawingToolLauncher() { - super(); - - setWindowSupport(new WindowSupport(this, - i18n.get(OMDrawingToolLauncher.class, "omdrawingtoollauncher", "Drawing Tool Launcher"))); - setKey(defaultKey); - defaultGraphicAttributes.setRenderType(OMGraphic.RENDERTYPE_LATLON); - defaultGraphicAttributes.setLineType(OMGraphic.LINETYPE_GREATCIRCLE); - resetGUI(); - } - - /** - * Set the DrawingTool for this launcher. - */ - public void setDrawingTool(DrawingTool dt) { - if (drawingTool instanceof OMDrawingTool) { - ((OMDrawingTool) drawingTool).removePropertyChangeListener(this); - } - - drawingTool = dt; - - if (drawingTool instanceof OMDrawingTool) { - ((OMDrawingTool) drawingTool).addPropertyChangeListener(this); - } - } - - public DrawingTool getDrawingTool() { - return drawingTool; - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand().intern(); - - Debug.message("drawingtool", "DrawingToolLauncher.actionPerformed(): " + command); - - // This is important. We need to set the current projection - // before setting the projection in the MapBean. That way, - // the projectionChanged method actions won't get fired - if (command == CreateCmd) { - // Get the active EditToolLoader - DrawingTool dt = getDrawingTool(); - - if (dt instanceof OMDrawingTool) { - OMDrawingTool omdt = (OMDrawingTool) dt; - - if (omdt.isActivated()) { - omdt.deactivate(); - } - } - - if (dt != null && currentCreation != null && currentRequestor != null) { - // Copy the default GraphicAttributes into another - // copy... - GraphicAttributes ga = (GraphicAttributes) defaultGraphicAttributes.clone(); - - // fire it up! - dt.setBehaviorMask(OMDrawingTool.DEFAULT_BEHAVIOR_MASK); - dt.create(currentCreation, ga, currentRequestor); - } else { - - StringBuffer sb = new StringBuffer(); - StringBuffer em = new StringBuffer(); - - if (dt == null) { - sb.append(" No drawing tool is available!\n"); - em.append(i18n.get(OMDrawingToolLauncher.class, "noDrowingTool", - " No drawing tool is available!\n")); - } else { - sb.append(" Drawing tool OK.\n"); - } - - if (currentCreation == null) { - sb.append(" No valid choice of graphic to create.\n"); - em.append(i18n.get(OMDrawingToolLauncher.class, "noValidChoice", - " No valid choice of graphic to create.\n")); - } else { - sb.append(" Graphic choice OK.\n"); - } - - if (currentRequestor == null) { - sb.append(" No valid receiver for the created graphic.\n"); - em.append(i18n.get(OMDrawingToolLauncher.class, "noValidReceiver", - " No valid receiver for the created graphic.\n")); - } else { - sb.append(" Graphic receiver OK.\n"); - } - - Debug.output("OMDrawingToolLauncher: Something is not set:\n" + sb.toString()); - - MapHandler mapHandler = (MapHandler) getBeanContext(); - if (mapHandler != null) { - InformationDelegator id = (InformationDelegator) mapHandler - .get("com.bbn.openmap.InformationDelegator"); - if (id != null) { - - id.displayMessage(i18n.get(OMDrawingToolLauncher.class, "problem", "Problem"), - i18n.get(OMDrawingToolLauncher.class, "problemCreatingGraphic", - "Problem creating new graphic:\n") + em.toString()); - } - } - } - } - } - - /** - * Set the current requestor to receive a requested OMGraphic. Changes are - * reflected in the GUI, and setCurrentRequestor() will eventually be called. - */ - public void setRequestor(String aName) { - if (requestors != null) { - if (aName != null) { - requestors.setSelectedItem(aName); - } else { - if (!drawingToolRequestors.isEmpty()) { - setRequestor(((DrawingToolRequestor) drawingToolRequestors.elementAt(0)).getName()); - } - } - } - } - - /** - * Fills combobox with recent values. - */ - private void resetCombo() { - Object oldChoice = null; - if (requestors != null) { - oldChoice = requestors.getSelectedItem(); - - ActionListener[] actions = requestors.getActionListeners(); - for (int loop = 0; loop < actions.length; loop++) { - requestors.removeActionListener(actions[loop]); - } - requestors.removeAllItems(); - for (DrawingToolRequestor requestor : drawingToolRequestors) { - requestors.addItem(requestor.getName()); - } - if (oldChoice != null) { - requestors.setSelectedItem(oldChoice); - } - for (int loop = 0; loop < actions.length; loop++) { - requestors.addActionListener(actions[loop]); - } - setCurrentRequestor((String) requestors.getSelectedItem()); - } - createButton.setEnabled(drawingToolRequestors != null && !drawingToolRequestors.isEmpty()); - } - - /** - * Build the stuff that goes in the launcher. - */ - public void resetGUI() { - removeAll(); - - JPanel palette = new JPanel(); - palette.setLayout(new BoxLayout(palette, BoxLayout.Y_AXIS)); - palette.setAlignmentX(Component.CENTER_ALIGNMENT); // LEFT - palette.setAlignmentY(Component.CENTER_ALIGNMENT); // BOTTOM - - String[] requestorNames = new String[drawingToolRequestors.size()]; - - if (Debug.debugging("omdtl")) { - Debug.output("Have " + requestorNames.length + " REQUESTORS"); - } - - for (int i = 0; i < requestorNames.length; i++) { - requestorNames[i] = ((DrawingToolRequestor) drawingToolRequestors.elementAt(i)).getName(); - if (requestorNames[i] == null) { - Debug.output( - "OMDrawingToolLauncher has a requestor that is unnamed. Please assign a name to the requestor"); - requestorNames[i] = "-- Unnamed --"; - } - if (Debug.debugging("omdtl")) { - Debug.output("Adding REQUESTOR " + requestorNames[i] + " to menu"); - } - } - - Object oldChoice = null; - if (requestors != null) { - oldChoice = requestors.getSelectedItem(); - } - - requestors = new JComboBox(requestorNames); - requestors.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) e.getSource(); - String currentChoice = (String) jcb.getSelectedItem(); - setCurrentRequestor(currentChoice); - } - }); - - if (requestorNames.length > 0) { - if (oldChoice == null) { - requestors.setSelectedIndex(0); - } else { - requestors.setSelectedItem(oldChoice); - } - } - - JPanel panel = PaletteHelper - .createPaletteJPanel(i18n.get(OMDrawingToolLauncher.class, "panelSendTo", "Send To:")); - panel.add(requestors); - palette.add(panel); - - if (Debug.debugging("omdtl")) { - Debug.output("Figuring out tools, using names"); - } - - panel = PaletteHelper - .createPaletteJPanel(i18n.get(OMDrawingToolLauncher.class, "panelGraphicType", "Graphic Type:")); - panel.add(getToolWidgets(useTextEditToolTitles)); - palette.add(panel); - - String[] renderTypes = new String[3]; - - renderTypes[OMGraphic.RENDERTYPE_LATLON - 1] = rtc[0]; - renderTypes[OMGraphic.RENDERTYPE_XY - 1] = rtc[1]; - renderTypes[OMGraphic.RENDERTYPE_OFFSET - 1] = rtc[2]; - - JComboBox renderTypeList = new JComboBox<>(renderTypes); - renderTypeList.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) e.getSource(); - String currentChoice = (String) jcb.getSelectedItem(); - if (currentChoice.equals(rtc[2])) { - defaultGraphicAttributes.setRenderType(OMGraphic.RENDERTYPE_OFFSET); - } else if (currentChoice.equals(rtc[1])) { - defaultGraphicAttributes.setRenderType(OMGraphic.RENDERTYPE_XY); - } else { - defaultGraphicAttributes.setRenderType(OMGraphic.RENDERTYPE_LATLON); - } - } - }); - - renderTypeList.setSelectedIndex(defaultGraphicAttributes.getRenderType() - 1); - - panel = PaletteHelper.createHorizontalPanel( - i18n.get(OMDrawingToolLauncher.class, "panelGraphicAttributes", "Graphic Attributes:")); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.CENTER; - panel.setLayout(gridbag); - - String interString = i18n.get(OMDrawingToolLauncher.class, "panelRenderingType", "Rendering Type:"); - JPanel panel2 = new JPanel(); - JLabel renderTypeLabel = new JLabel(interString); - panel2.add(renderTypeLabel); - panel2.add(renderTypeList); - - panel3 = new JPanel(); - updateDrawingAttributesGUI(); - - gridbag.setConstraints(panel2, c); - panel.add(panel2); - gridbag.setConstraints(panel3, c); - panel.add(panel3); - palette.add(panel); - - createButton = new JButton(i18n.get(OMDrawingToolLauncher.class, "createButton", "Create Graphic")); - createButton.setActionCommand(CreateCmd); - createButton.addActionListener(this); - - JPanel dismissBox = new JPanel(); - JButton dismiss = new JButton(i18n.get(OMDrawingToolLauncher.class, "dismiss", "Close")); - dismissBox.setLayout(new BoxLayout(dismissBox, BoxLayout.X_AXIS)); - dismissBox.setAlignmentX(Component.CENTER_ALIGNMENT); - dismissBox.setAlignmentY(Component.BOTTOM_ALIGNMENT); - dismissBox.add(createButton); - dismissBox.add(dismiss); - - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - setAlignmentX(Component.CENTER_ALIGNMENT); - setAlignmentY(Component.BOTTOM_ALIGNMENT); - add(palette); - add(dismissBox); - - dismiss.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - getWindowSupport().killWindow(); - } - }); - } - - protected void updateDrawingAttributesGUI() { - panel3.removeAll(); - String interString = i18n.get(OMDrawingToolLauncher.class, "panelLineColorTypes", "Line/Colors:"); - JLabel lcLabel = new JLabel(interString); - panel3.add(lcLabel); - panel3.add(defaultGraphicAttributes.getGUI()); - } - - protected JComponent getToolWidgets() { - JPanel iconBar = new JPanel(); - // this parameters should be read from properties! - iconBar.setLayout(new GridLayout(2, 4)); - ButtonGroup bg = new ButtonGroup(); - JToggleButton btn = null; - boolean setFirstButtonSelected = true; - - for (LoaderHolder lh : loaders) { - String pName = lh.prettyName; - EditToolLoader etl = lh.loader; - ImageIcon icon = etl.getIcon(getEditableClassName(pName)); - btn = new JToggleButton(icon); - btn.setMargin(new Insets(0, 0, 0, 0)); - btn.setToolTipText(pName); - btn.setActionCommand(pName); - btn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setCurrentCreation(ae.getActionCommand()); - } - }); - if (setFirstButtonSelected) { - btn.setSelected(true); - setCurrentCreation(pName); - setFirstButtonSelected = false; - } - bg.add(btn); - iconBar.add(btn); - } - return iconBar; - } - - protected JComponent getToolWidgets(boolean useText) { - - if (useText) { - // Set editables with all the pretty names. - List editables = new ArrayList(); - - for (LoaderHolder lh : loaders) { - editables.add(lh.prettyName); - } - - return createToolOptionMenu(editables); - } else { - return createToolButtonPanel(); - } - } - - private JComboBox createToolOptionMenu(List editables) { - String[] toolNames = new String[editables.size()]; - toolNames = editables.toArray(toolNames); - - JComboBox tools = new JComboBox<>(toolNames); - tools.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) e.getSource(); - String currentChoice = (String) jcb.getSelectedItem(); - setCurrentCreation(currentChoice); - } - }); - - if (toolNames.length > 0) { - tools.setSelectedIndex(0); - } - - return tools; - } - - private JPanel createToolButtonPanel() { - // Otherwise, create a set of buttons. - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.gridwidth = GridBagConstraints.REMAINDER; - - panel.setLayout(gridbag); - - ButtonGroup bg = new ButtonGroup(); - - int toolbarCount = 0; - boolean limitWidth = false; - if (maxHorNumLoaderButtons >= 0) { - limitWidth = true; - } - - JToggleButton btn; - JToolBar iconBar = null; - boolean activeSet = false; - for (LoaderHolder lh : loaders) { - - if (toolbarCount == 0) { - iconBar = new JToolBar(); - iconBar.setFloatable(false); - gridbag.setConstraints(iconBar, c); - panel.add(iconBar); - } - - String pName = lh.prettyName; - EditToolLoader etl = lh.loader; - ImageIcon icon = etl.getIcon(getEditableClassName(pName)); - - btn = new JToggleButton(icon, !activeSet); - btn.setToolTipText(pName); - btn.setActionCommand(pName); - btn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setCurrentCreation(ae.getActionCommand()); - } - }); - bg.add(btn); - - if (iconBar != null) { - iconBar.add(btn); - } - - toolbarCount++; - - // Just set one as active, the first one. - if (!activeSet) { - setCurrentCreation(pName); - activeSet = true; - } - - if (limitWidth && toolbarCount >= maxHorNumLoaderButtons) { - toolbarCount = 0; - } - } - - return panel; - } - - /** - * Set the component that will receive the new/edited OMGraphic from the - * DrawingTool. Does not change the GUI. Called when the combo box changes. - * - * @param name GUI pretty name of requestor. - */ - public void setCurrentRequestor(String name) { - if (name == null) { - return; - } - - for (DrawingToolRequestor dtr : drawingToolRequestors) { - if (name.equals(dtr.getName())) { - currentRequestor = dtr; - return; - } - } - currentRequestor = null; - } - - /** - * Set the next thing to be created to be whatever the pretty name represents. - * Sets currentCreation. - * - * @param name GUI pretty name of thing to be created, from one of the - * EditToolLoaders. - */ - public void setCurrentCreation(String name) { - currentCreation = getEditableClassName(name); - } - - /** - * Given a pretty name, look through the EditToolLoaders and find out the - * classname that goes with editing it. - * - * @param prettyName GUI pretty name of tool, or thing to be created, from one - * of the EditToolLoaders. - */ - public String getEditableClassName(String prettyName) { - for (LoaderHolder lh : loaders) { - EditToolLoader etl = lh.loader; - String[] ec = etl.getEditableClasses(); - - for (int i = 0; i < ec.length; i++) { - if (prettyName.equals(etl.getPrettyName(ec[i]))) { - defaultGraphicAttributes.setEnableFillPaintChoice(!(etl instanceof NonRegional)); - updateDrawingAttributesGUI(); - panel3.revalidate(); - return ec[i]; - } - } - } - return null; - } - - /** - * This is the method that your object can use to find other objects within the - * MapHandler (BeanContext). This method gets called when the object gets added - * to the MapHandler, or when another object gets added to the MapHandler after - * the object is a member. - * - * @param someObj the object that was added to the BeanContext (MapHandler) that - * is being searched for. Find the ones you need, and hook - * yourself up. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof OMDrawingTool) { - Debug.message("omdtl", "OMDrawingToolLauncher found a DrawingTool."); - setDrawingTool((DrawingTool) someObj); - } - if (someObj instanceof DrawingToolRequestor) { - if (Debug.debugging("omdtl")) { - Debug.output("OMDrawingToolLauncher found a DrawingToolRequestor - " - + ((DrawingToolRequestor) someObj).getName()); - } - drawingToolRequestors.add((DrawingToolRequestor) someObj); - // resetGUI(); - resetCombo(); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't do - * anything. If your layer does something with the childrenAdded method, or - * findAndInit, you should take steps in this method to unhook the layer from - * the object used in those methods. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof OMDrawingTool) { - Debug.message("omdtl", "OMDrawingToolLauncher found a DrawingTool."); - OMDrawingTool dt = (OMDrawingTool) someObj; - if (dt == getDrawingTool()) { - setDrawingTool(null); - dt.removePropertyChangeListener(this); - } - } - - if (someObj instanceof DrawingToolRequestor) { - if (Debug.debugging("omdtl")) { - Debug.output("OMDrawingToolLauncher removing a DrawingToolRequestor - " - + ((DrawingToolRequestor) someObj).getName()); - } - drawingToolRequestors.remove((DrawingToolRequestor) someObj); - if (drawingToolRequestors.isEmpty()) {// there is no - // Requestor, so - // lets remove the - // window. - getWindowSupport().killWindow(); - currentRequestor = null; - } - // resetGUI(); - resetCombo(); - setRequestor(null); - } - } - - /** - * Tool interface method. The retrieval tool's interface. This method creates a - * button that will bring up the LauncherPanel. - * - * @return String The key for this tool. - */ - public Container getFace() { - JToolBar jtb = null; - if (getUseAsTool()) { - jtb = new com.bbn.openmap.gui.GridBagToolBar(); - // "Drawing Tool Launcher"; - JButton drawingToolButton = new JButton(new ImageIcon( - OMDrawingToolLauncher.class.getResource("Drawing.gif"), - i18n.get(OMDrawingToolLauncher.class, "drawingToolButton", I18n.TOOLTIP, "Drawing Tool Launcher"))); - drawingToolButton.setToolTipText( - i18n.get(OMDrawingToolLauncher.class, "drawingToolButton", I18n.TOOLTIP, "Drawing Tool Launcher")); - drawingToolButton.addActionListener(getActionListener()); - jtb.add(drawingToolButton); - } - return jtb; - } - - /** - * Get the ActionListener that triggers the LauncherPanel. Useful to have to - * provide an alternative way to bring up the LauncherPanel. - * - * @return ActionListener - */ - public ActionListener getActionListener() { - return new ActionListener() { - public void actionPerformed(ActionEvent evt) { - - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - // -1 will get size from pack(), and get location (initially) to - // the middle of the screen if the WindowSupport doesn't have - // memory of where it's been. - getWindowSupport().displayInWindow(frame, -1, -1, -1, -1); - } - }; - } - - /** - * Get the attributes that initialize the graphic. - */ - public GraphicAttributes getDefaultGraphicAttributes() { - return defaultGraphicAttributes; - } - - /** - * Set the attributes that initialize the graphic. - */ - public void setDefaultGraphicAttributes(GraphicAttributes ga) { - defaultGraphicAttributes = ga; - } - - /** - * Set the loaders with an Iterator containing EditToolLoaders. - */ - public void setLoaders(Iterator iterator) { - loaders.clear(); - while (iterator.hasNext()) { - addLoader((EditToolLoader) iterator.next()); - } - } - - /** - * Returns an iterator of LoaderHolders. - */ - public Iterator getLoaders() { - return loaders.iterator(); - } - - public void addLoader(EditToolLoader etl) { - if (etl != null) { - String[] classNames = etl.getEditableClasses(); - for (int i = 0; i < classNames.length; i++) { - loaders.add(new LoaderHolder(etl.getPrettyName(classNames[i]), etl)); - } - } - } - - public void removeLoader(EditToolLoader etl) { - if (etl != null) { - for (LoaderHolder lh : loaders) { - if (lh.loader == etl) { - loaders.remove(lh); - } - } - } - } - - /** - * PropertyChangeListener method, to listen for the OMDrawingTool's list of - * loaders that may or may not change. - */ - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName() == OMDrawingTool.LoadersProperty) { - Object obj = pce.getNewValue(); - if (obj instanceof List) { - @SuppressWarnings("unchecked") - List loaders = (List) obj; - setLoaders(loaders.iterator()); - resetGUI(); - } - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - maxHorNumLoaderButtons = PropUtils.intFromProperties(props, prefix + HorizontalNumberOfLoaderButtonsProperty, - maxHorNumLoaderButtons); - useTextEditToolTitles = PropUtils.booleanFromProperties(props, prefix + UseLoaderTextProperty, - useTextEditToolTitles); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + HorizontalNumberOfLoaderButtonsProperty, Integer.toString(maxHorNumLoaderButtons)); - props.put(prefix + UseLoaderTextProperty, new Boolean(useTextEditToolTitles).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String internString = i18n.get(OMDrawingToolLauncher.class, HorizontalNumberOfLoaderButtonsProperty, - I18n.TOOLTIP, "Number of loader buttons to place horizontally"); - props.put(HorizontalNumberOfLoaderButtonsProperty, internString); - - internString = i18n.get(OMDrawingToolLauncher.class, HorizontalNumberOfLoaderButtonsProperty, - "# Horizontal Buttons"); - props.put(HorizontalNumberOfLoaderButtonsProperty + LabelEditorProperty, internString); - - internString = i18n.get(OMDrawingToolLauncher.class, UseLoaderTextProperty, I18n.TOOLTIP, - "Use text popup for loader selection."); - props.put(UseLoaderTextProperty, internString); - - internString = i18n.get(OMDrawingToolLauncher.class, UseLoaderTextProperty, "Use Text For Selection"); - props.put(UseLoaderTextProperty + LabelEditorProperty, internString); - - return props; - } - - public static class LoaderHolder { - public String prettyName; - public EditToolLoader loader; - - public LoaderHolder(String pn, EditToolLoader etl) { - prettyName = pn; - loader = etl; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolMouseMode.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolMouseMode.java deleted file mode 100644 index 3c2a77c56..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMDrawingToolMouseMode.java +++ /dev/null @@ -1,179 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMDrawingToolMouseMode.java,v $ -// $Revision: 1.4 $ $Date: 2004/10/14 18:06:26 $ $Author: dietrick $ -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import java.awt.Cursor; -import java.awt.event.MouseEvent; - -import com.bbn.openmap.event.CoordMouseMode; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.util.Debug; - -/** - * The OMDrawingToolMouseMode is the MapMouseMode that handles the events for - * the OMDrawingTool. - */ -public class OMDrawingToolMouseMode - extends CoordMouseMode { - - private static final long serialVersionUID = 1L; - - /** - * Mouse Mode identifier, which is "Drawing Tool". - */ - public final static transient String modeID = "Drawing"; - - protected OMDrawingTool drawingTool = null; - - /** - * Construct an OMDrawingToolMouseMode. Sets the ID of the mode to the - * modeID, the consume mode to true. - */ - public OMDrawingToolMouseMode() { - super(modeID, true); - } - - /** - * Construct a OMDrawingToolMouseMode. Lets you set the consume mode. If the - * events are consumed, then a MouseEvent is sent only to the first - * MapMouseListener that successfully processes the event. If they are not - * consumed, then all of the listeners get a chance to act on the event. - * - * @param omdt the drawing tool for this mousemode - */ - public OMDrawingToolMouseMode(OMDrawingTool omdt) { - this(); - drawingTool = omdt; - setModeCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - - /** - * Set the DrawingTool for the mouse mode. Expected to be self-called by the - * mouse mode using the BeanContext. - */ - protected void setDrawingTool(OMDrawingTool omdt) { - drawingTool = omdt; - } - - /** - * Get the drawing tool for the mouse mode. - */ - protected OMDrawingTool getDrawingTool() { - return drawingTool; - } - - /** - * Get the EditableOMGraphic from the OMDrawingTool. Returns null if anything - * isn't set up correctly. - */ - protected EditableOMGraphic getCurrentGraphic() { - if (drawingTool == null) { - return null; - } - return drawingTool.getCurrentEditable(); - } - - // MouseListener and MouseMotionListener interface methods - - /** - * - */ - public void mousePressed(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mousePressed"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mousePressed(e); - } - fireMouseLocation(e); - } - - /** - * - */ - public void mouseReleased(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mousePressed"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseReleased(e); - } - fireMouseLocation(e); - if (drawingTool != null) { - if (drawingTool.isMask(OMDrawingTool.DEACTIVATE_ASAP_BEHAVIOR_MASK)) { - drawingTool.deactivate(); - } - } - } - - /** - * - */ - public void mouseClicked(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mouseClicked"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseClicked(e); - } - } - - /** - * - */ - public void mouseEntered(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mouseEntered"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseEntered(e); - } - } - - /** - * - */ - public void mouseExited(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mouseExited"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseExited(e); - } - } - - /** - * - */ - public void mouseDragged(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mouseDragged"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseDragged(e); - } - fireMouseLocation(e); - } - - /** - * - */ - public void mouseMoved(MouseEvent e) { - Debug.message("drawingtooldetail", "DrawingTool.mouseMoved"); - EditableOMGraphic graphic = getCurrentGraphic(); - if (graphic != null) { - graphic.mouseMoved(e); - } - fireMouseLocation(e); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMLineLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMLineLoader.java deleted file mode 100644 index f520b04cb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMLineLoader.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMLineLoader.java,v $ -// $RCSfile: OMLineLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMLine; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.geom.NonRegional; - -/** - * Loader that knows how to create/edit OMLine objects. - */ -public class OMLineLoader extends AbstractToolLoader implements EditToolLoader, NonRegional { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMLine"; - - public OMLineLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMLine", "editableline.gif", i18n.get(OMLineLoader.class, - "omline", - "Line")); - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the line, - * like line type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMLine(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMLine) { - return new EditableOMLine((OMLine) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPointLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPointLoader.java deleted file mode 100644 index 23c92c62f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPointLoader.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMPointLoader.java,v $ -// $RCSfile: OMPointLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMPoint; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoint; - -/** - * Loader that knows how to create/edit OMPoint objects. - */ -public class OMPointLoader extends AbstractToolLoader implements EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMPoint"; - - public OMPointLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMPoint", "editablepoint.gif", i18n.get(OMPointLoader.class, - "ompoint", - "Point")); - - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the - * point, like point type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMPoint(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMPoint) { - return new EditableOMPoint((OMPoint) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPolyLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPolyLoader.java deleted file mode 100644 index bfa3fc7e0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMPolyLoader.java +++ /dev/null @@ -1,82 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMPolyLoader.java,v $ -// $RCSfile: OMPolyLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMPoly; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.labeled.EditableLabeledOMPoly; - -/** - * Loader that knows how to create/edit OMPoly objects. - */ -public class OMPolyLoader extends AbstractToolLoader implements EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMPoly"; - protected String labeledClassName = "com.bbn.openmap.omGraphics.labeled.LabeledOMPoly"; - - public OMPolyLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMPoly", "editablepoly.gif", i18n.get(OMPolyLoader.class, - "ompoly", - "Polygons/Polylines")); - - addEditClassWrapper(ecw); - - // A class wrapper isn't added here for the LabeledOMPoly - // because currently they are only created programmatically. - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the poly, - * like poly type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMPoly(ga); - } - if (classname.intern() == labeledClassName) { - return new EditableLabeledOMPoly(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMPoly) { - return new EditableOMPoly((OMPoly) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMRectLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMRectLoader.java deleted file mode 100644 index b10dab4c4..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMRectLoader.java +++ /dev/null @@ -1,73 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMRectLoader.java,v $ -// $RCSfile: OMRectLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMRect; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRect; - -/** - * Loader that knows how to create/edit OMRect objects. - */ -public class OMRectLoader extends AbstractToolLoader implements EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMRect"; - - public OMRectLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMRect", "editablerect.gif", i18n.get(OMRectLoader.class, - "omrect", - "Rectangle")); - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the rect, - * like rect type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMRect(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMRect) { - return new EditableOMRect((OMRect) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMScalingRasterLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMScalingRasterLoader.java deleted file mode 100644 index dc6327649..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMScalingRasterLoader.java +++ /dev/null @@ -1,74 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMScalingRasterLoader.java,v $ -// $RCSfile: OMScalingRasterLoader.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMScalingRaster; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMScalingRaster; - -/** - * Loader that knows how to create/edit OMRect objects. - */ -public class OMScalingRasterLoader extends AbstractToolLoader implements - EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMScalingRaster"; - - public OMScalingRasterLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMScalingRaster", "editablescalingraster.gif", i18n.get(OMScalingRasterLoader.class, - "omscalingraster", - "Raster")); - addEditClassWrapper(ecw); - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the rect, - * like rect type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMScalingRaster(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMScalingRaster) { - return new EditableOMScalingRaster((OMScalingRaster) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMSplineLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMSplineLoader.java deleted file mode 100644 index 910b22c7f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMSplineLoader.java +++ /dev/null @@ -1,85 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMSplineLoader.java,v $ -// $RCSfile: OMSplineLoader.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMSpline; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMSpline; -import com.bbn.openmap.omGraphics.labeled.EditableLabeledOMSpline; - -/** - * OMSplineLoader - * - * @author Eric LEPICIER - * @version 22 juil. 2002 - */ -public class OMSplineLoader extends AbstractToolLoader implements - EditToolLoader { - - protected String graphicClassName = "com.bbn.openmap.omGraphics.OMSpline"; - protected String labeledClassName = "com.bbn.openmap.omGraphics.labeled.LabeledOMSpline"; - - public OMSplineLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(graphicClassName, "com.bbn.openmap.omGraphics.EditableOMSpline", "editablespline.gif", i18n.get(OMSplineLoader.class, - "omspline", - "Splines")); - addEditClassWrapper(ecw); - - // A class wrapper isn't added here for the LabeledOMSpline - // because currently they are only created programmatically. - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the - * spline, like spline type and rendertype. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == graphicClassName) { - return new EditableOMSpline(ga); - } - if (classname.intern() == labeledClassName) { - return new EditableLabeledOMSpline(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMSpline) { - return new EditableOMSpline((OMSpline) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMTextLoader.java b/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMTextLoader.java deleted file mode 100644 index 2eadf414f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/OMTextLoader.java +++ /dev/null @@ -1,75 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/drawing/OMTextLoader.java,v $ -// $RCSfile: OMTextLoader.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.drawing; - -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.EditableOMText; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMText; - -/** - * Loader that knows how to create/edit OMText objects. - */ -public class OMTextLoader extends AbstractToolLoader implements EditToolLoader { - - protected String textClassName = "com.bbn.openmap.omGraphics.OMText"; - - public OMTextLoader() { - init(); - } - - public void init() { - EditClassWrapper ecw = new EditClassWrapper(textClassName, "com.bbn.openmap.omGraphics.EditableOMText", "editabletext.gif", i18n.get(OMTextLoader.class, - "omtext", - "Text")); - - addEditClassWrapper(ecw); - - } - - /** - * Give the classname of a graphic to create, returning an - * EditableOMGraphic for that graphic. The GraphicAttributes - * object lets you set some of the initial parameters of the text, - * like font and size. - */ - public EditableOMGraphic getEditableGraphic(String classname, - GraphicAttributes ga) { - if (classname.intern() == textClassName) { - return new EditableOMText(ga); - } - return null; - } - - /** - * Give an OMGraphic to the EditToolLoader, which will create an - * EditableOMGraphic for it. - */ - public EditableOMGraphic getEditableGraphic(OMGraphic graphic) { - if (graphic instanceof OMText) { - return new EditableOMText((OMText) graphic); - } - return null; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/drawing/package.html b/src/core/src/main/java/com/bbn/openmap/tools/drawing/package.html deleted file mode 100644 index 2001e13dc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/drawing/package.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - -Provides classes to implement a drawing tool. The OMDrawingTool is -really a managing class that uses -com.bbn.openmap.omGraphics.EditableOMGraphics to make adjustments to -OMGraphics. It uses a DrawingToolMouseMode to direct events to the -current EditableOMGraphic, which in turn, figures out what changes to -implement on the OMGraphic based on its state. - -The OMDrawingTool uses EditToolLoaders, provided at runtime, to figure -out what EditableOMGraphic to use for what OMGraphic type (and by -extension, any combination or object to be modified). - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicAppIconPart.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicAppIconPart.java deleted file mode 100644 index ed1d4b554..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicAppIconPart.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/BasicAppIconPart.java,v $ -// $RCSfile: BasicAppIconPart.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Shape; -import java.awt.geom.AffineTransform; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * A BasicAppIconPart is a BasicIconPart that can be interested in a - * set of DrawingAttributes on the fly. Good for an icon part that may - * change under certain system conditions, like something reflecting a - * current color, or an application icon reflecting a color theme in - * the application. The BasicAppIconPart may have a default - * DrawingAttributes that describe how it should be drawn if other - * DrawingAttributes aren't provided at rendertime. - */ -public class BasicAppIconPart extends BasicIconPart implements IconPart, Cloneable { - - public BasicAppIconPart(Shape shape) { - super(shape); - } - - public BasicAppIconPart(Shape shape, AffineTransform transform) { - super(shape, transform); - } - - /** - * Get the DrawingAttributes that should be used for rendering. - * - * @param da DrawingAttributes passed in that may affect rendering - * choices. For the BasicAppIconPart, if this is not null, - * it is returned. Otherwise, the internal version is - * returned. - * @return DrawingAttribute for this part. - */ - protected DrawingAttributes getAttributesForRendering(DrawingAttributes da) { - if (da == null) { - return getRenderingAttributes(); - } else { - return da; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicIconPart.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicIconPart.java deleted file mode 100644 index 819a1c633..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/BasicIconPart.java +++ /dev/null @@ -1,252 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/BasicIconPart.java,v $ -// $RCSfile: BasicIconPart.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/08/29 23:07:54 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * The BasicIconPart is an implementation of the IconPart. In addition to the - * geometry and DrawingAttributes adjustments that can be done on an IconPart, - * the BasicIconPart also lets you use an AffineTransform to rotate, translate - * or scale the geometries and will create GradientPaints for the Colors from - * the DrawingAttribtues if desired. - */ -public class BasicIconPart implements IconPart, Cloneable { - - /** - * AffineTransform to adjust geometry if needed. - */ - protected AffineTransform baseTransform; - /** - * Shape geometry for this IconPart. - */ - protected Shape geometry; - /** - * Shape clipping area for this IconPart. - */ - protected Shape clip; - /** - * DrawingAttributes for this IconPart. - */ - protected DrawingAttributes renderingAttributes = null; - /** - * Flag to modifying DrawingAttributes Colors into GradientPaints, for that 3D - * lighting look. - */ - protected boolean gradient = false; - - /** - * Create a BasicIconPart with a java.awt.Shape object for a geometry. - */ - public BasicIconPart(Shape shape) { - this(shape, null, DrawingAttributes.DEFAULT); - } - - /** - * Create a BasicIconPart with a java.awt.Shape object for a geometry, along - * with an AffineTransform that may be applied to the geometry at rendertime. - */ - public BasicIconPart(Shape shape, AffineTransform transform) { - this(shape, transform, DrawingAttributes.DEFAULT); - } - - /** - * Create a BasicIconPart with a java.awt.Shape object for a geometry. - */ - public BasicIconPart(Shape shape, DrawingAttributes da) { - this(shape, (AffineTransform) null, da); - } - - /** - * Create a BasicIconPart with a java.awt.Shape object for a geometry, along - * with an AffineTransform that may be applied to the geometry at rendertime. - */ - public BasicIconPart(Shape shape, AffineTransform transform, DrawingAttributes da) { - geometry = shape; - - if (transform == null) { - transform = new AffineTransform(); - } - - baseTransform = transform; - setRenderingAttributes(da); - } - - /** - * Get the DrawingAttributes that should be used for rendering. - * - * @param da DrawingAttributes passed in that may affect rendering choices. Can - * be null, and the IconPart may decide to ignore it. - * @return DrawingAttribute for this part. - */ - protected DrawingAttributes getAttributesForRendering(DrawingAttributes da) { - return getRenderingAttributes(); - } - - /** - * @param g a java.awt.Graphics object to render into. - * @param width pixel width of icon, used to scale geometry. - * @param height pixel height of icon, used to scale geometry. - */ - public void render(Graphics g, int width, int height) { - render(g, width, height, null); - } - - /** - * @param g a java.awt.Graphics object to render into. - * @param width pixel width of icon, used to scale geometry. - * @param height pixel height of icon, used to scale geometry. - * @param appDA drawing attributes to use under certain conditions. Certain - * IconParts on this list may use these drawing attributes if they - * want/should. May be null. - */ - public void render(Graphics g, int width, int height, DrawingAttributes appDA) { - - AffineTransform transform = AffineTransform.getScaleInstance((double) width / 100.0, (double) height / 100.0); - transform.concatenate(baseTransform); - - // Handle clip area in Graphics, first - Shape clip = getClip(); - if (clip != null) { - g.setClip(new GeneralPath(clip).createTransformedShape(transform)); - } - - if (geometry != null) { - Shape shape = new GeneralPath(geometry).createTransformedShape(transform); - getAttributesForRendering(appDA).render((Graphics2D) g, shape, gradient); - } - } - - /** - * Set whether colors should be replaced by GradientPaints. - */ - public void setGradient(boolean value) { - gradient = value; - } - - /** - * Get whether colors should be replaced by GradientPaints. - */ - public boolean isGradient() { - return gradient; - } - - public void setClip(Shape clipArea) { - clip = clipArea; - } - - public Shape getClip() { - return clip; - } - - public void setGeometry(Shape shape) { - geometry = shape; - } - - public Shape getGeometry() { - return geometry; - } - - public void setTransform(AffineTransform af) { - baseTransform = af; - } - - public AffineTransform getTransform() { - return baseTransform; - } - - public void setRenderingAttributes(DrawingAttributes da) { - renderingAttributes = da; - } - - public DrawingAttributes getRenderingAttributes() { - if (renderingAttributes == null) { - return DrawingAttributes.DEFAULT; - } else { - return renderingAttributes; - } - } - - private BasicIconPart with(Shape s, AffineTransform af, DrawingAttributes da, Shape clipArea, boolean gradient) { - BasicIconPart bip = new BasicIconPart(s, af, da); - bip.setGradient(gradient); - bip.setClip(clipArea); - return bip; - } - - /** - * @param da new DrawingAttributes - * @return new BasicIconPart with adjusted setting. - */ - public BasicIconPart with(DrawingAttributes da) { - return with(geometry, baseTransform, da, clip, gradient); - } - - /** - * @param new affine transform to be applied to the geometry - * @return new BasicIconPart with adjusted setting. - */ - public BasicIconPart with(AffineTransform af) { - return with(geometry, af, renderingAttributes, clip, gradient); - } - - /** - * @param s new geometry - * @return new BasicIconPart with adjusted setting. - */ - public BasicIconPart with(Shape s) { - return with(s, baseTransform, renderingAttributes, clip, gradient); - } - - /** - * @param c new clip area - * @return new BasicIconPart with adjusted setting. - */ - public BasicIconPart withClip(Shape c) { - return with(geometry, baseTransform, renderingAttributes, c, gradient); - } - - /** - * @param gradient true to use gradient colors - * @return new BasicIconPart with adjusted setting. - */ - public BasicIconPart with(boolean gradient) { - return with(geometry, baseTransform, renderingAttributes, clip, gradient); - } - - public Object clone() { - BasicIconPart clone = null; - try { - clone = (BasicIconPart) super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return clone; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconFactoryTestingTool.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/IconFactoryTestingTool.java deleted file mode 100644 index d618bb2aa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconFactoryTestingTool.java +++ /dev/null @@ -1,162 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/IconFactoryTestingTool.java,v $ -// $RCSfile: IconFactoryTestingTool.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/03/06 16:01:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Container; -import java.awt.Polygon; -import java.awt.Shape; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.Ellipse2D; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JToolBar; -import javax.swing.SwingConstants; - -import com.bbn.openmap.gui.Tool; -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * An example class and example for how to use the OMIconFactory and IconParts - * to create Icons. Can be run as a class, or can be used as an OpenMap Tool to - * show up on the OpenMap ToolPanel. - */ -public class IconFactoryTestingTool - implements Tool { - - public IconFactoryTestingTool() { - } - - /** - * The retrieval tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - JToolBar jtb = new JToolBar(); - jtb.setFloatable(false); - - DrawingAttributes da = new DrawingAttributes(); - da.setLinePaint(Color.blue); - da.setFillPaint(Color.blue); - da.setStroke(new BasicStroke(2)); - DrawingAttributes da2 = new DrawingAttributes(); - da2.setFillPaint(Color.lightGray); - da2.setLinePaint(Color.lightGray); - da2.setStroke(new BasicStroke(2)); - - int[] xpoints = new int[] { - 15, - 15, - 50, - 50, - 90, - 50, - 50, - 15 - }; - int[] ypoints = new int[] { - 30, - 70, - 70, - 90, - 50, - 10, - 30, - 30 - }; - Shape shape = new Polygon(xpoints, ypoints, xpoints.length); - - BasicIconPart testPart = new BasicIconPart(shape); - testPart.setRenderingAttributes(da); - testPart.setGradient(true); - - Shape shape2 = new Ellipse2D.Double(5, 5, 90, 90); - BasicIconPart testPart2 = new BasicIconPart(shape2); - testPart2.setRenderingAttributes(da2); - testPart2.setGradient(true); - - IconPartList parts = new IconPartList(); - parts.add(testPart2); - parts.add(testPart); - - BasicIconPart testPart3 = new BasicIconPart(shape, AffineTransform.getRotateInstance(Math.PI / 4, 50, 50)); - testPart3.setRenderingAttributes(da); - testPart3.setGradient(true); - - IconPartList parts2 = new IconPartList(); - parts2.add(testPart2); - parts2.add(testPart3); - - jtb.add(new JButton(OMIconFactory.getIcon(10, 10, parts))); - jtb.add(new JButton(OMIconFactory.getIcon(20, 20, parts))); - jtb.add(new JButton(OMIconFactory.getIcon(50, 50, parts))); - jtb.add(new JButton(OMIconFactory.getIcon(50, 50, parts2))); - jtb.add(new JButton(OMIconFactory.getIcon(10, 20, parts2))); - - return jtb; - } - - /** - * The retrieval key for this tool - * - * @return String The key for this tool. - */ - public String getKey() { - return "IconFactoryTestingTool"; - } - - /** - * Set the retrieval key for this tool - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - } - - public static void main(String[] argv) { - JFrame frame = new JFrame("IconFactoryTestingTool"); - frame.getContentPane().add(new IconFactoryTestingTool().getFace()); - frame.pack(); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - // need a shutdown event to notify other gui beans and - // then exit. - System.exit(0); - } - }); - - frame.setVisible(true); - } - - public void setOrientation(int orientation) { - } - - public int getOrientation() { - return SwingConstants.HORIZONTAL; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPart.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPart.java deleted file mode 100644 index a23828871..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPart.java +++ /dev/null @@ -1,102 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/IconPart.java,v $ -// $RCSfile: IconPart.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Graphics; -import java.awt.Shape; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * An IconPart is an object that makes up a piece of what's rendered - * on an Icon. It has a java.awt.Shape object that specifies what gets - * rendered, and it has a clipping shape that specifies how much of - * the shape gets rendered. The rendering attributes specify how the - * shape is colored, drawn, etc. - * - * The coordinates of the Shape objects used for the clip area and - * geometry are in relative coordinates, and should be thought of as - * percentage coordinates, on a scale from 1 to 100. The size of the - * Graphics object provided in the render method will dictate how - * large the part will actually be on the screen. If coordinates of - * the IconPart are greater than 100 or less than zero, that part will - * not appear on the icon. That may help with defining certain shapes - * to appear on the icon, however. - */ -public interface IconPart { - - /** - * Have the IconPart render itself into the Graphic object for a - * given height and width. - */ - public void render(Graphics g, int width, int height); - - /** - * Have the IconPart render itself into the Graphic object for a - * given height and width. The DrawingAttributes will dictate how - * the geometries can be drawn, of the IconPart may react to a - * System setting or last-minute attributes. The IconPart may - * decide to ignore this provided DrawingAttributes and just use - * what it has. appDA may be null, in which case the internal - * DrawingAttributes will be used. - */ - public void render(Graphics g, int width, int height, - DrawingAttributes appDA); - - /** - * Set a clip area for the IconPart to draw only certain parts of - * the geometry. - */ - public void setClip(Shape clipArea); - - /** - * Get a clip area for the IconPart. - */ - public Shape getClip(); - - /** - * Set the geometry for this IconPart. - */ - public void setGeometry(Shape shape); - - /** - * Get the geometry for this IconPart. - */ - public Shape getGeometry(); - - /** - * Set the rendering attributes for this IconPart. - */ - public void setRenderingAttributes(DrawingAttributes da); - - /** - * Get the rendering attributes for this IconPart. - */ - public DrawingAttributes getRenderingAttributes(); - - /** - * @return copy of itself, IconParts need to be Cloneable - */ - public Object clone(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollection.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollection.java deleted file mode 100644 index d671d52a2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollection.java +++ /dev/null @@ -1,236 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/IconPartCollection.java,v $ -// $RCSfile: IconPartCollection.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * A collection of IconParts, available by name. - */ -public class IconPartCollection extends IconPartCollectionEntry { - - protected Map entryMap; - protected List collections; - - protected IconPartCollection() { - } - - /** - * Create a collection with a name and description. - */ - public IconPartCollection(String name, String description) { - setName(name); - setDescription(description); - } - - /** - * Add an entry to the collection. - */ - public void add(IconPartCollectionEntry entry) { - if (entry != null) { - String entryName = entry.getName(); - if (entryName != null) { - getEntryMap().put(entryName.intern(), entry); - } - - if (entry instanceof IconPartCollection) { - getCollections().add((IconPartCollection) entry); - } - } - } - - /** - * Remove an entry from the collection. - */ - public Object remove(IconPartCollectionEntry entry) { - return getEntryMap().remove(entry.getName()); - } - - /** - * Clear the entries in the collection. - */ - public void clear() { - getEntryMap().clear(); - } - - /** - * Get the set of names for the entries of this collection. - */ - public Set keySet() { - return getEntryMap().keySet(); - } - - /** - * Get an icon part for the given name set with the given rendering attributes. - * Calls get(name); - */ - public IconPart get(String name, DrawingAttributes da) { - IconPart ip = get(name); - if (ip != null) { - ip.setRenderingAttributes(da); - } - return ip; - } - - /** - * Get an icon part for the given name. The top level IconPartCollectionEntries - * are checked for the name. Will return null if no IconPart exists for the - * name. If the name is a collection name, null will be returned. However, - * before returning null, any IconPartCollection added to this collection will - * be checked, too, and any hits will be returned. - */ - public IconPart get(String name) { - IconPartCollectionEntry entry = getEntryMap().get(name.intern()); - IconPart part = null; - - if (entry != null) { - part = (IconPart) entry.getIconPart().clone(); - } - - if (part == null) { - List cllctns = getCollections(); - for (IconPartCollection ipc : cllctns) { - part = ipc.get(name); - if (part != null) { - break; - } - } - } - - return part; - } - - /** - * Get a description for the given name. The top level IconPartCollectionEntries - * are checked for the name. Will return null if no entry exists for the name. - * If the name is a collection name, the description of the collection will be - * returned. Before returning null, any IconPartCollection added to this - * collection will be checked, too, and any hits will be returned. - */ - public String getDescription(String name) { - IconPartCollectionEntry entry = getEntryMap().get(name.intern()); - String desc = null; - - if (entry != null) { - desc = entry.getDescription(); - } - - if (desc == null) { - for (IconPartCollection ipc : getCollections()) { - desc = ipc.getDescription(name); - if (desc != null) { - break; - } - } - } - - return desc; - } - - /** - * Create an IconPart from the list of entry names. - * - * @param list a List of Strings, with the strings being names of entries into - * this collection. - */ - public IconPart compose(List list) { - IconPartList ipl = new IconPartList(); - - for (String partName : list) { - IconPart part = get(partName); - if (part != null) { - ipl.add(part); - } - } - - return ipl; - } - - /** - * Get a list of description Strings from a list of entry names. - * - * @param list a List of Strings, with the strings being names of entries into - * this collection. - * @return a List of description Strings for the given list of names. - */ - public List composeDescription(List list) { - LinkedList ll = new LinkedList(); - - for (String entry : list) { - String des = getDescription(entry); - if (des != null) { - ll.add(des); - } - } - return ll; - } - - /** - * Set the entry Map. - */ - protected void setEntryMap(Map map) { - entryMap = map; - } - - /** - * Get the entry Map. - */ - protected Map getEntryMap() { - if (entryMap == null) { - entryMap = new HashMap(); - } - return entryMap; - } - - /** - * Set the List to be used for holding IconPartCollections added to this - * collection. - */ - protected void setCollections(List list) { - collections = list; - } - - /** - * Get the List of IconPartCollections that have been added. - */ - protected List getCollections() { - if (collections == null) { - collections = new LinkedList(); - } - return collections; - } - - public void setIconPart(IconPart part) { - this.part = part; - } - - public IconPart getIconPart() { - return part; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollectionEntry.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollectionEntry.java deleted file mode 100644 index 6d3a7b5fd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartCollectionEntry.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/IconPartCollectionEntry.java,v $ -// $RCSfile: IconPartCollectionEntry.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -/** - * An entry into an IconPartCollection, providing an IconPart with a - * name and description. - */ -public class IconPartCollectionEntry { - - protected IconPart part; - protected String name; - protected String description; - - protected IconPartCollectionEntry() {} - - public IconPartCollectionEntry(String name, String description, - IconPart part) { - this.name = name; - this.description = description; - this.part = part; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setIconPart(IconPart part) { - this.part = part; - } - - public IconPart getIconPart() { - return part; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartList.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartList.java deleted file mode 100644 index 4115d171e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/IconPartList.java +++ /dev/null @@ -1,175 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/IconPartList.java,v $ -// $RCSfile: IconPartList.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * An IconPartList is a group of IconParts that can be rendered - * together. If you ask an IconPartList for it's geometry, it will - * combine all its parts into one geometry, and use its - * DrawingAttributes to render that combined shape. The IconPartList - * is itself an IconPart, so the recursive possibilities are endless. - */ -public class IconPartList implements IconPart, Iterable, Cloneable { - - protected List parts; - protected DrawingAttributes renderingAttributes = null; - protected Shape clip = null; - - public IconPartList() {} - - protected List getList() { - if (parts == null) { - parts = new LinkedList(); - } - return parts; - } - - public Iterator iterator() { - return parts.iterator(); - } - - /** - * First in drawn on bottom. Last in on top. - */ - public void add(IconPart part) { - getList().add(part); - } - - public boolean remove(IconPart part) { - return getList().remove(part); - } - - public void clear() { - getList().clear(); - } - - public void render(Graphics g, int width, int height) { - render(g, width, height, null); - } - - /** - * @param appDA drawing attributes to use under certain - * conditions. Certain IconParts on this list may use these - * drawing attributes if they want/should. May be null. - */ - public void render(Graphics g, int width, int height, - DrawingAttributes appDA) { - - // Handle clip area in Graphics, first - Shape clip = getClip(); - if (clip != null) { - g.setClip(clip); - } - - DrawingAttributes da = getRenderingAttributes(); - DrawingAttributes tmpDA = null; - - for (IconPart part : this) { - - if (da != null) { - tmpDA = part.getRenderingAttributes(); - part.setRenderingAttributes(da); - } - - Graphics2D g2 = (Graphics2D) g.create(); - part.render(g2, width, height); - g2.dispose(); - - if (da != null) { - part.setRenderingAttributes(tmpDA); - tmpDA = null; - } - } - } - - public void setClip(Shape clipArea) { - clip = clipArea; - } - - public Shape getClip() { - return clip; - } - - public void setGeometry(Shape shape) { - // dump the list, create a generic IconPart to hold the shape. - List list = getList(); - list.clear(); - list.add(new BasicIconPart(shape)); - } - - /** - * If you ask a IconPartList for its geometry, it will combine all - * its parts to make one Shape object. All the rendering - * attributes from the individual parts will be ignored. The - * contributions will be kept geometrically separate - * (disconnected) and their clipping areas will be ignored. - */ - public Shape getGeometry() { - GeneralPath geometry = null; - for (IconPart part : this) { - - Shape shp = part.getGeometry(); - - if (shp == null) { - continue; - } - - if (geometry == null) { - geometry = new GeneralPath(shp); - } else { - geometry.append(shp, false); - } - } - return geometry; - } - - public void setRenderingAttributes(DrawingAttributes da) { - renderingAttributes = da; - } - - public DrawingAttributes getRenderingAttributes() { - return renderingAttributes; - } - - public Object clone() { - IconPartList clone = new IconPartList(); - for (IconPart part : this) { - clone.add((IconPart)part.clone()); - } - - clone.setRenderingAttributes(getRenderingAttributes()); - clone.setClip(getClip()); - return clone; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconFactory.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconFactory.java deleted file mode 100644 index 6ff8a2bf7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconFactory.java +++ /dev/null @@ -1,119 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/OMIconFactory.java,v $ -// $RCSfile: OMIconFactory.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:27 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.omGraphics.DrawingAttributes; - -/** - * The OMIconFactory is a factory to build ImageIcons, with content described by - * IconParts for a certain size. - */ -public class OMIconFactory { - - /** - * Create an ImageIcon that is a certain pixel height and width. This will - * return an empty ImageIcon, and you'd have to do the rendering into its - * image. - */ - public static ImageIcon createImageIcon(int width, int height) { - return createImageIcon(width, height, BufferedImage.TYPE_INT_ARGB); - } - - /** - * Create an ImageIcon that is a certain pixel height and width, with a - * specified image type (ARGB, RGB, etc). This will return an empty - * ImageIcon, and you'd have to do the rendering into its image. - */ - public static ImageIcon createImageIcon(int width, int height, int imageType) { - return new ImageIcon(new BufferedImage(width, height, imageType)); - } - - /** - * Create an ImageIcon that is a certain pixel height and width created with - * a certain IconPart geometry. The geometry will be drawing with default - * DrawingAttributes. - */ - public static ImageIcon getIcon(int width, int height, IconPart geometry) { - return getIcon(width, height, geometry, null); - } - - /** - * Create an ImageIcon that is a certain pixel height and width created with - * a certain IconPart geometry. Also, the DrawingAttributes can be used to - * add color/texture to the IconPart geometries. - */ - public static ImageIcon getIcon(int width, int height, IconPart geometry, - DrawingAttributes appDA) { - return getIcon(width, height, geometry, appDA, null); - } - - /** - * Create an ImageIcon that is a certain pixel height and width created with - * a certain IconPart geometry. Also, the DrawingAttributes can be used to - * add color/texture to the IconPart geometries, and an AffineTransform can - * be used to further modify the geometry. How the DrawingAttributes are - * used depends on the IconPart, how it handles its - * getAttributesForRendering(...) method. Some IconParts allow for accents - * to be painted that might be part of a theme. This appDA argument lets you - * specify how those accents might be rendered. General DrawingAttributes - * should be set on the IconPart, however. - */ - public static ImageIcon getIcon(int width, int height, IconPart geometry, - DrawingAttributes appDA, AffineTransform af) { - ImageIcon icon = createImageIcon(width, height); - Graphics2D g = (Graphics2D) icon.getImage().getGraphics(); - if (af != null) { - g.setTransform(af); - } - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - geometry.render(g, width, height, appDA); - return icon; - } - - /** - * Create an ImageIcon that is a certain pixel height and width created with - * a certain IconPart geometry. Also, the DrawingAttributes can be used to - * add color/texture to the IconPart geometries, and an angle can be - * provided to rotate the geometry (zero is north up, positive clockwise, - * angle in RADIANS). - */ - public static ImageIcon getIcon(int width, int height, IconPart geometry, - DrawingAttributes appDA, double rot) { - return getIcon(width, - height, - geometry, - appDA, - AffineTransform.getRotateInstance(rot, - width / 2.0, - height / 2.0)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconPart.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconPart.java deleted file mode 100644 index b0b7b1aaf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/OMIconPart.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.bbn.openmap.tools.icon; - -import java.awt.Polygon; -import java.awt.Shape; -import java.awt.geom.Arc2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; - -/** - * Pre-defined shapes used for images on gui controls. All of these shapes are - * defined within a region between 0,0 and 100,100 for scaling. - * - * @author dietrick - */ -public enum OMIconPart { - - BIG_BOX(getPolygon(new int[] { 10, 10, 90, 90, 10 }, new int[] { 10, 90, 90, 10, 10 })), - SMALL_BOX(getPolygon(new int[] { 30, 30, 70, 70, 30 }, new int[] { 30, 70, 70, 30, 30 })), - FILL_BOX(getPolygon(new int[] { 10, 10, 50, 50, 30, 30, 70, 70, 50, 50, 90, 90, 10 }, - new int[] { 10, 90, 90, 70, 70, 30, 30, 70, 70, 90, 90, 10, 10 })), - UL_TRI(getPolygon(new int[] { 10, 10, 75, 10 }, new int[] { 10, 75, 10, 10 })), - LR_TRI(getPolygon(new int[] { 25, 90, 90, 25 }, new int[] { 90, 90, 25, 90 })), - LL_UR_LINE(getPolygon(new int[] { 10, 90 }, new int[] { 90, 10 })), - UL_LR_LINE(getPolygon(new int[] { 10, 90 }, new int[] { 10, 90 })), - BIG_ARROW(getPolygon(new int[] { 50, 90, 80, 80, 20, 20, 10, 50 }, new int[] { 10, 40, 40, 90, 90, 40, 40, 10 })), - MED_ARROW(getPolygon(new int[] { 50, 90, 70, 70, 30, 30, 10, 50 }, new int[] { 10, 50, 50, 90, 90, 50, 50, 10 })), - SMALL_ARROW(getPolygon(new int[] { 50, 80, 60, 60, 40, 40, 20, 50 }, new int[] { 10, 50, 50, 90, 90, 50, 50, 10 })), - CORNER_TRI(getPolygon(new int[] { 10, 50, 10 }, new int[] { 10, 10, 50 })), - OPP_CORNER_TRI(getPolygon(new int[] { 50, 90, 50 }, new int[] { 50, 50, 90 })), CIRCLE(getCircle(50, 50, 46)), - DOT(getCircle(50, 50, 6)), - PLUS(getPolygon(new int[] { 25, 50, 50, 50, 50, 75, 75, 50, 50, 50, 50, 25, 25 }, - new int[] { 50, 50, 25, 25, 50, 50, 50, 50, 75, 75, 50, 50, 50 })), - ADD_PLUS(getPolygon(new int[] { 70, 80, 80, 80, 80, 90 }, new int[] { 20, 20, 10, 30, 20, 20 })), - MINUS(getPolygon(new int[] { 25, 75 }, new int[] { 50, 50 })), MAP_PIN_HEAD(getCircle(50, 33, 30)), - MAP_PIN_BOTTOM(getPolygon(new int[] { 50, 30, 70, 50 }, new int[] { 90, 50, 50, 90 })), - TRIANGLE(getPolygon(new int[] { 10, 50, 90, 10 }, new int[] { 90, 10, 90, 90 })), - SQUAT_TRIANGLE(getPath(new int[] { 10, 50, 90 }, new int[] { 60, 40, 60 })); - - private final BasicIconPart iconPart; - - private OMIconPart(Shape s) { - iconPart = new BasicIconPart(s); - } - - /** - * - * @return the IconPart for the enum part. - */ - public IconPart getIconPart() { - return iconPart; - } - - /** - * Create a pixel-based general path Shape. No limitations for general use, - * OMIconParts will have coordinates between 0-100. - * - * @param xp x coordinates, between 0-100 - * @param yp y coordinates, between 0-100 - * @return Shape created from GeneralPath - */ - public static Shape getPath(int[] xp, int[] yp) { - if (xp.length < 2) { - return null; - } - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, xp.length); - path.moveTo((float) xp[0], (float) yp[0]); - for (int index = 1; index < xp.length; index++) { - path.lineTo((float) xp[index], (float) yp[index]); - } - return path; - } - - /** - * Create a pixel-based shape. - * - * @param xp x coordinates of polygon - * @param yp y coordinates of polygon - * @return Polygon shape - */ - public static Shape getPolygon(int[] xp, int[] yp) { - return new Polygon(xp, yp, xp.length); - } - - /** - * Create a pixel-based shape. - * - * @param x center x coordinate - * @param y center y coordinate - * @param radius radius of circle - * @return Shape from Ellipse - */ - public static Shape getCircle(double x, double y, double radius) { - return new Ellipse2D.Double(x - radius, y - radius, radius * 2, radius * 2); - } - - /** - * Create a pixel-based shape. - * - * @param x center x coordinate - * @param y center y coordinate - * @param radius radius of circle - * @param start starting angle of arc in degrees - * @param end ending angle of arc in degrees - * @return Shape from Arc2D - */ - public static Shape getArc(double x, double y, double radius, double start, double end, int type) { - Arc2D arc = new Arc2D.Double(type); - arc.setArcByCenter(x, y, radius, start, end, type); - return arc; - } - - /** - * Create the reload symbol used by layer palettes. - * - * @return IconPart - */ - public static IconPart getReloadSymbol() { - IconPartList ipList = new IconPartList(); - ipList.add(new BasicIconPart(getArc(50, 50, 30, 90, 270, Arc2D.OPEN))); - ipList.add(new BasicIconPart(getPolygon(new int[] { 43, 65, 49 }, new int[] { 15, 20, 37 }))); - return ipList; - } - - /** - * Create a settings symbol created from parts, used by layer palettes. - * - * @return IconPart - */ - public static IconPart getSettingsSymbol() { - IconPartList ipList = new IconPartList(); - ipList.add(new BasicIconPart(getCircle(50, 50, 30))); - - for (int i = 0; i < 360; i += 45) { - double angle = Math.toRadians(i); - double cos = Math.cos(angle); - double sin = Math.sin(angle); - double x1 = 30.0 * cos + 50; - double y1 = 30.0 * sin + 50; - double x2 = 40.0 * cos + 50; - double y2 = 40.0 * sin + 50; - - Line2D.Double line = new Line2D.Double(x1, y1, x2, y2); - ipList.add(new BasicIconPart(line)); - } - - return ipList; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java b/src/core/src/main/java/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java deleted file mode 100644 index aa30fd09a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java +++ /dev/null @@ -1,104 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java,v -// $ -// $RCSfile: OpenMapAppPartCollection.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/08/29 23:07:53 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.tools.icon; - -public class OpenMapAppPartCollection extends IconPartCollection { - - static OpenMapAppPartCollection omparts; - - protected OpenMapAppPartCollection() { - super("OpenMap", "Common parts used in OpenMap Application Icons"); - init(); - } - - public static OpenMapAppPartCollection getInstance() { - if (omparts == null) { - omparts = new OpenMapAppPartCollection(); - } - return omparts; - } - - protected void init() { - add(BIG_BOX); - add(SMALL_BOX); - add(FILL_BOX); - add(UL_TRI); - add(LR_TRI); - add(LL_UR_LINE); - add(UL_LR_LINE); - add(BIG_ARROW); - add(MED_ARROW); - add(SMALL_ARROW); - add(CORNER_TRI); - add(OPP_CORNER_TRI); - add(CIRCLE); - add(DOT); - add(PLUS); - add(ADD_PLUS); - add(MINUS); - add(CIRCLE); - add(MAP_PIN_HEAD); - add(MAP_PIN_BOTTOM); - add(TRIANGLE); - add(SQUAT_TRIANGLE); - } - - public final static OpenMapAppPart BIG_BOX = new OpenMapAppPart("BIG_BOX", "BIG_BOX", OMIconPart.BIG_BOX); - public final static OpenMapAppPart SMALL_BOX = new OpenMapAppPart("SMALL_BOX", "SMALL_BOX", OMIconPart.SMALL_BOX); - public final static OpenMapAppPart FILL_BOX = new OpenMapAppPart("FILL_BOX", "FILL_BOX", OMIconPart.FILL_BOX); - public final static OpenMapAppPart UL_TRI = new OpenMapAppPart("UL_TRI", "UL_TRI", OMIconPart.UL_TRI); - public final static OpenMapAppPart LR_TRI = new OpenMapAppPart("LR_TRI", "LR_TRI", OMIconPart.LR_TRI); - public final static OpenMapAppPart LL_UR_LINE = new OpenMapAppPart("LL_UR_LINE", "LL_UR_LINE", - OMIconPart.LL_UR_LINE); - public final static OpenMapAppPart UL_LR_LINE = new OpenMapAppPart("UL_LR_LINE", "UL_LR_LINE", - OMIconPart.UL_LR_LINE); - public final static OpenMapAppPart BIG_ARROW = new OpenMapAppPart("BIG_ARROW", "BIG_ARROW", OMIconPart.BIG_ARROW); - public final static OpenMapAppPart MED_ARROW = new OpenMapAppPart("MED_ARROW", "MED_ARROW", OMIconPart.MED_ARROW); - public final static OpenMapAppPart SMALL_ARROW = new OpenMapAppPart("SMALL_ARROW", "SMALL_ARROW", - OMIconPart.SMALL_ARROW); - public final static OpenMapAppPart CORNER_TRI = new OpenMapAppPart("CORNER_TRI", "CORNER_TRI", - OMIconPart.CORNER_TRI); - public final static OpenMapAppPart OPP_CORNER_TRI = new OpenMapAppPart("OPP_CORNER_TRI", "OPP_CORNER_TRI", - OMIconPart.OPP_CORNER_TRI); - public final static OpenMapAppPart CIRCLE = new OpenMapAppPart("CIRCLE", "CIRCLE", OMIconPart.CIRCLE); - public final static OpenMapAppPart DOT = new OpenMapAppPart("DOT", "DOT", OMIconPart.DOT); - public final static OpenMapAppPart PLUS = new OpenMapAppPart("PLUS", "PLUS", OMIconPart.PLUS); - public final static OpenMapAppPart ADD_PLUS = new OpenMapAppPart("ADD_PLUS", "ADD_PLUS", OMIconPart.ADD_PLUS); - public final static OpenMapAppPart MINUS = new OpenMapAppPart("MINUS", "MINUS", OMIconPart.MINUS); - public final static OpenMapAppPart MAP_PIN_HEAD = new OpenMapAppPart("MAP_PIN_HEAD", "MAP_PIN_HEAD", - OMIconPart.MAP_PIN_HEAD); - public final static OpenMapAppPart MAP_PIN_BOTTOM = new OpenMapAppPart("MAP_PIN_BOTTOM", "MAP_PIN_BOTTOM", - OMIconPart.MAP_PIN_BOTTOM); - public final static OpenMapAppPart TRIANGLE = new OpenMapAppPart("TRIANGLE", "TRIANGLE", OMIconPart.TRIANGLE); - public final static OpenMapAppPart SQUAT_TRIANGLE = new OpenMapAppPart("SQUAT_TRIANGLE", "SQUAT_TRIANGLE", - OMIconPart.SQUAT_TRIANGLE); - - public static class OpenMapAppPart extends IconPartCollectionEntry { - - public OpenMapAppPart(String n, String d, OMIconPart iconPart) { - super(n, d, iconPart.getIconPart()); - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/icon/package.html b/src/core/src/main/java/com/bbn/openmap/tools/icon/package.html deleted file mode 100644 index e87138ede..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/icon/package.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The icon package is intended to provide the capability to create or -fetch icons. - -The OMIconFactory can create ImageIcons from IconParts and -IconPartLists (a sequence of IconParts). The OMIconFactory can -create icons of any size. - -The IconPart is the base interface for the package, defining an -object that contains geometry and information on how to render that -geometry. The IconPart geometry coordinates are defined on a -coordinate system to 100, like a percentage. When the IconPart is -told how big the icon it is a part of, it scales itself to fit the -icon. Any part of the IconPart geometry defined less than zero or -greater than 100 is clipped. - -IconPartCollections are mechanisms for IconParts to be organized and -retrievable by name. - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/package.html b/src/core/src/main/java/com/bbn/openmap/tools/package.html deleted file mode 100644 index b0b938da6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The tools package is intended to provide a place where components that -provide general services can be kept. - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Intersection.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Intersection.java deleted file mode 100644 index 09ba3bb0d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Intersection.java +++ /dev/null @@ -1,249 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Intersection.java,v -// $ -// $RCSfile: Intersection.java,v $ -// $Revision: 1.3 $ -// $Date: 2009/02/25 22:34:04 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class Intersection extends Waypoint implements RoadObject { - - private static final long serialVersionUID = 1L; - public final static Intersection INTEGRITY_CHECK_BOTH_INTERSECTIONS = new Intersection("BOTH_INTERSECTIONS"); - public final static Intersection INTEGRITY_CHECK_INROADS = new Intersection("INROADS"); - - /** - * The list of roads at this intersection. - */ - List roads = new ArrayList<>(4); - - /** - * The "name" of this intersection. Intersections are named after their - * coordinates. Coordinates (in degrees) are multiplied by 10000000 and - * truncated to integers. - */ - private String name; - - private boolean displayAsTerminal = false; - - public static int GRID = 100000;// was 100000 - - private Intersection(String name) { - // NOOP, used for integrity checks - super(null, null); - this.name = name; - } - - /** - * Create an Intersection at a given location. - * - * @param loc the location of the intersection. - */ - public Intersection(LatLonPoint loc, RoadLayer layer) { - this(loc, getLatLonPointName(loc), layer); - } - - public Intersection(LatLonPoint loc, String name, RoadLayer layer) { - super(loc, layer); - this.name = name; - } - - public static Class getGraphicClass() { - return Graphic.class; - } - - public static String getLatLonPointName(LatLonPoint loc) { - StringBuffer buf = new StringBuffer(24); - buf.append((int) (loc.getY() * GRID)); - buf.append(","); - buf.append((int) (loc.getX() * GRID)); - return new String(buf.toString()); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Add a road to this intersection. - * - * @param road The road to be added. - */ - public void addRoad(Road road) { - roads.add(road); - } - - public void removeRoad(Road road) { - roads.remove(road); - } - - public int getRoadCount() { - return roads.size(); - } - - /** - * Merge another intersection with this one. All the roads of the other - * intersection are removed and added onto this. - */ - public void merge(Intersection other) { - for (Road road : other.getRoads()) { - road.changeIntersection(other, this); - addRoad(road); - } - other.clear(); - setModified(true); - } - - public void clear() { - roads.clear(); - } - - /** - * Get the List of Roads - * @return roads - */ - public List getRoads() { - return roads; - } - - public Road getRoad(int ix) { - return roads.get(ix); - } - - public void setTerminalStatus(boolean yes) { - displayAsTerminal = yes; - update(); - } - - public boolean getTerminalStatus() { - return displayAsTerminal; - } - - /** - * Render the graphics for this intersection. - */ - public void render(OMGraphicList gl, boolean forceNew) { - RoadGraphic visual = getVisual(); - if (visual == null || forceNew) { - visual = new Graphic(displayAsTerminal); - setVisual(visual); - } - gl.add((Graphic) visual); - } - - /** - * Render the graphics for the roads leaving this intersection. - */ - public void renderRoads(OMGraphicList gl, boolean forceNew) { - for (Road road : roads) { - if (road.getFirstIntersection() == this) { - road.render(gl, forceNew); - } - } - } - - /** - * Override equals so that two Intersections at the same location are the same - * Intersection. - */ - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Intersection other = (Intersection) obj; - return other.getLocation().equals(getLocation()); - } - - /** - * Override hashCode so that two Intersections at the same location have the - * same hashcode. - */ - public int hashCode() { - LatLonPoint llp = getLocation(); - int hc1 = Float.floatToIntBits(llp.getLatitude()); - int hc2 = Float.floatToIntBits(llp.getLongitude()); - return hc1 ^ (hc2 << 5) ^ (hc2 >>> 27); - } - - public Intersection startMove(boolean shifted) { - if (shifted) { - RoadLayer layer = getRoadLayer(); - Road road = layer.createRoad(this); - return road.getOtherIntersection(this); - } else { - return this; - } - } - - public void update() { - super.update(); - for (Road road : roads) { - road.updateLines(); - } - } - - public String toString() { - return super.toString() + "[" + getName() + "," + getLocation().toString() + "] " + getRoadCount() + " roads"; - } - - /** - * Inner class for the visual representation of an Intersection. The visual - * representation of the the Waypoint base class is extended so that the move - * method can also update the roads connected to the intersection. - */ - - public class Graphic extends Waypoint.Graphic implements RoadGraphic { - - private static final long serialVersionUID = 1L; - - Graphic(boolean displayAsTerminal) { - super(displayAsTerminal ? 5 : 3); - if (displayAsTerminal) - setLinePaint(Color.red); - } - - public RoadObject getRoadObject() { - return Intersection.this; - } - - public Intersection getIntersection() { - return Intersection.this; - } - - public String toString() { - return super.toString() + "[" + Intersection.this.toString() + "]"; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/LayerView.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/LayerView.java deleted file mode 100644 index 89d7a7491..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/LayerView.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/LayerView.java,v $ -// $RCSfile: LayerView.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * Services the layer provides to the road layer helper. - */ -public interface LayerView { - - /** - * Needed to find the height and width of the displayed routes, - * etc. - */ - Projection getProjection(); - - /** - * Should return a flattened list of road OMGraphics. No embedded - * OMGraphicLists. - */ - OMGraphicList getOMGraphicsFromSource(); - - /** - * Draw extra OMGraphics (intersections, to debug the road layer), - * a callback method to the LayerView to let it know what the - * RoadFinder is doing. - */ - void setExtraGraphics(OMGraphicList toDraw); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Road.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Road.java deleted file mode 100644 index d491c8f13..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Road.java +++ /dev/null @@ -1,448 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Road.java,v -// $ -// $RCSfile: Road.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Point; -import java.io.Serializable; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class Road implements RoadObject, Serializable { - - private static final long serialVersionUID = 1L; - - transient Logger logger = Logger.getLogger(this.getClass().getName()); - - /** - * The points along the road. The first and last points are always - * Intersections. - */ - private Waypoint[] points; - - /** - * The lines between the points. - */ - private RoadLine[] lines; - - /** - * The class of this road. A Road's class implies what kind of road it is. For - * now this governs its visual appearance of color and width. - */ - private RoadClass roadClass; - - private boolean isRoute = false; - - private boolean blocked = false; - - /** - * The id of this road. - */ - private int id; - - /** - * The name of this road. - */ - private String name; - - /** - * True if this road has been modified (points added or removed). - */ - private boolean modified = false; - - /** - * The RoadLayer we belong to so we can invoke its services. - */ - private transient RoadLayer roadLayer; - - /** - * Selection flag for this road. - */ - private boolean selected = false; - - /** - * Blink flag for this road. - */ - private boolean blinkState = false; - - /** - * Create a road between two Intersections. The detailed segments between the - * intersections may be filled in later. - * - * @param id a unique, integer identifier of this road. - * @param name a name for this road. - * @param from the intersection from which this road leaves. - * @param to the intersection to which this road goes. - * @param roadClass the class of this road. - * @param roadLayer the RoadLayer we belong to. - */ - public Road(int id, String name, Intersection from, Intersection to, RoadClass roadClass, RoadLayer roadLayer) { - this.id = id; - this.name = name; - this.roadLayer = roadLayer; - points = new Waypoint[2]; - setIntersections(from, to); - this.roadClass = roadClass; - createLines(); - modified = false; - } - - public double getLengthInKilometers() { - double kilometers = 0.0; - LatLonPoint prevPoint = points[0].getLocation(); - // logger.warning ("" + this + " pt 0 " + points[0] + " pt 1 " - // + points[1] + " getSecondInter " + getSecondIntersection - // ()); - for (int i = 1; i < points.length; i++) { - LatLonPoint thisPoint = points[i].getLocation(); - kilometers += GreatCircle.sphericalDistance(prevPoint.getY(), prevPoint.getX(), thisPoint.getY(), - thisPoint.getX()); - prevPoint = thisPoint; - } - return kilometers; - } - - public double getTraverseHours() { - if (isBlocked()) - return Float.MAX_VALUE; - return getLengthInKilometers() / getRoadClass().getConvoySpeed(); - } - - public LatLonPoint getLocationAtKilometer(double kilometers) { - LatLonPoint prevPoint = points[0].getLocation(); - double prevLat = prevPoint.getY(); - double prevLon = prevPoint.getX(); - for (int i = 1; i < points.length; i++) { - LatLonPoint thisPoint = points[i].getLocation(); - double thisLat = thisPoint.getY(); - double thisLon = thisPoint.getX(); - double thisLength = GreatCircle.sphericalDistance(prevLat, prevLon, thisLat, thisLon); - if (thisLength >= kilometers) { - double fraction = kilometers / thisLength; - double deltaLat = thisLat - prevLat; - double deltaLon = thisLon - prevLon; - if (deltaLon < -180f) - deltaLon += 360f; - else if (deltaLon > 180f) - deltaLon -= 360f; - return new LatLonPoint.Double(prevLat + fraction * deltaLat, prevLon + fraction * deltaLon); - } - kilometers -= thisLength; - prevPoint = thisPoint; - prevLat = thisLat; - prevLon = thisLon; - } - return prevPoint; - } - - private void createLines() { - lines = new RoadLine[points.length - 1]; - for (int i = 0; i < lines.length; i++) { - lines[i] = new RoadLine(this, i); - } - blinkLines(); - } - - private void blinkLines() { - for (int i = 0; i < lines.length; i++) - lines[i].blink(blinkState); - } - - /** - * Set the state of the modified flag. Setting the modified flag to false also - * sets the modified flag of all the points to false as well. - * - * @param newValue the new setting. - */ - public void setModified(boolean newValue) { - modified = newValue; - if (newValue == false) { - for (int i = 0; i < points.length; i++) - points[i].setModified(false); - } - } - - /** - * Get the state of the modified flag. - * - * @return true if the road or its points have been modified. - */ - public boolean getModified() { - if (modified) - return true; - for (int i = 0; i < points.length; i++) - if (points[i].getModified()) - return true; - return false; - } - - public void block() { - blocked = true; - updateLines(); - } - - public void unblock() { - blocked = false; - updateLines(); - } - - public boolean isBlocked() { - return blocked; - } - - public void blink(boolean newState) { - blinkState = newState; - if (lines != null) - blinkLines(); - blinkPoints(); - } - - /** - * Accessor for the ID property. - * - * @return the road ID. - */ - public int getID() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String newName) { - name = newName; - } - - public RoadClass getRoadClass() { - return roadClass; - } - - public void setRoadClass(RoadClass newClass) { - roadClass = newClass; - setModified(true); - updateLines(); - } - - public String getRoadClassName() { - return roadClass.getName().toString(); - } - - public void isRoute(boolean yes) { - isRoute = yes; - updateLines(); - } - - public boolean isRoute() { - return isRoute; - } - - public RoadLayer getRoadLayer() { - return roadLayer; - } - - public void setIntersections(Intersection from, Intersection to) { - if (from == null) { - logger.warning("from is null."); - Thread.dumpStack(); - } - if (to == null) { - logger.warning("to is null."); - Thread.dumpStack(); - } - - points[0] = from; - points[points.length - 1] = to; - checkPoints(); - createLines(); - setModified(true); - } - - public void setRoadPoints(RoadPoint[] innerPoints) { - Waypoint[] oldPoints = points; - points = new Waypoint[2 + innerPoints.length]; - points[0] = oldPoints[0]; - System.arraycopy(innerPoints, 0, points, 1, innerPoints.length); - points[points.length - 1] = oldPoints[oldPoints.length - 1]; - - if (points[points.length - 1] == null) { - logger.warning("to is null."); - Thread.dumpStack(); - } - - checkPoints(); - - createLines(); - // blinkPoints(); - setModified(true); - } - - public void checkPoints() { - for (int i = 0; i < points.length; i++) { - if (points[i] == null) { - logger.warning("found null point at " + i); - Thread.dumpStack(); - } - } - } - - public RoadPoint[] getRoadPoints() { - RoadPoint[] innerPoints = new RoadPoint[points.length - 2]; - System.arraycopy(points, 1, innerPoints, 0, innerPoints.length); - return innerPoints; - } - - public void insertRoadPointAt(RoadPoint wp, int ix) { - Waypoint[] oldPoints = points; - points = new Waypoint[1 + oldPoints.length]; - System.arraycopy(oldPoints, 0, points, 0, ix); - points[ix] = wp; - if (wp == null) { - logger.warning("wp is null."); - Thread.dumpStack(); - } - checkPoints(); - System.arraycopy(oldPoints, ix, points, ix + 1, oldPoints.length - ix); - createLines(); - // blinkPoints(); - setModified(true); - } - - public void deleteRoadPoint(RoadPoint rp) { - for (int ix = 1; ix < points.length - 1; ix++) { - if (points[ix] == rp) { - Waypoint[] oldPoints = points; - points = new Waypoint[oldPoints.length - 1]; - System.arraycopy(oldPoints, 0, points, 0, ix); - System.arraycopy(oldPoints, ix + 1, points, ix, oldPoints.length - ix - 1); - createLines(); - setModified(true); - return; - } - } - checkPoints(); - - } - - public Intersection getFirstIntersection() { - return (Intersection) points[0]; - } - - public Intersection getSecondIntersection() { - return (Intersection) points[points.length - 1]; - } - - public Intersection getOtherIntersection(Intersection intersection) { - if (intersection == points[0]) - return (Intersection) points[points.length - 1]; - return (Intersection) points[0]; - } - - public void changeIntersection(Intersection oldIntersection, Intersection newIntersection) { - if (oldIntersection == points[0]) { - setIntersections(newIntersection, getSecondIntersection()); - } else if (oldIntersection == points[points.length - 1]) { - setIntersections(getFirstIntersection(), newIntersection); - } - checkPoints(); - - } - - public Waypoint getWaypoint(int ix) { - return points[ix]; - } - - public Waypoint[] getPoints() { - return points; - } - - public RoadPoint[] getPointsBefore(RoadPoint wp) { - for (int i = 1; i < points.length - 1; i++) { - if (points[i] == wp) { - RoadPoint[] answer = new RoadPoint[i - 1]; - System.arraycopy(points, 1, answer, 0, answer.length); - return answer; - } - } - return new RoadPoint[0]; - } - - public RoadPoint[] getPointsAfter(RoadPoint wp) { - for (int i = 1; i < points.length - 1; i++) { - if (points[i] == wp) { - RoadPoint[] answer = new RoadPoint[points.length - i - 2]; - System.arraycopy(points, i + 1, answer, 0, answer.length); - return answer; - } - } - RoadPoint[] answer = new RoadPoint[points.length - 2]; - System.arraycopy(points, 1, answer, 0, answer.length); - return answer; - } - - private void blinkPoints() { - for (int i = 1; i < points.length - 1; i++) { - points[i].blink(blinkState); - } - } - - /** - * Mark this Road as needing a new visual representation. - */ - public synchronized void updateLines() { - for (int i = 0; i < lines.length; i++) { - lines[i].update(); - } - } - - public void moveTo(Point loc) { - } - - public synchronized void render(OMGraphicList gl, boolean projectionIsNew) { - if (roadLayer.isEditing()) { - for (int i = 1; i < points.length - 1; i++) { - points[i].render(gl, projectionIsNew); - } - } - for (int i = 0; i < lines.length; i++) { - lines[i].render(gl, projectionIsNew); - } - } - - public String toString() { - return name + " from " + getFirstIntersection() + " to " + getSecondIntersection() + " " + points.length - + " points."; - } - - public boolean isSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadClass.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadClass.java deleted file mode 100644 index 8ffd66486..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadClass.java +++ /dev/null @@ -1,60 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadClass.java,v -// $ -// $RCSfile: RoadClass.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/12 21:47:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Color; -import java.io.Serializable; - -public class RoadClass implements Serializable { - - private static final long serialVersionUID = 1L; - private String name; - private Color color; - private int width; - private float convoySpeed; - - public RoadClass(String name, Color color, int width, float convoySpeed) { - this.name = name; - this.color = color; - this.width = width; - this.convoySpeed = convoySpeed; - } - - public String getName() { - return name; - } - - public Color getColor() { - return color; - } - - public int getWidth() { - return width; - } - - public float getConvoySpeed() { - return convoySpeed; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadFinder.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadFinder.java deleted file mode 100644 index 62089267f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadFinder.java +++ /dev/null @@ -1,1241 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBN Technologies - * A Division of - * BBN Corporation - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright 1998 by BBN Technologies, A Division of - * BBN Corporation, all rights reserved. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadFinder.java,v $ - * $RCSfile: RoadFinder.java,v $ - * $Revision: 1.7 $ - * $Date: 2006/02/16 16:22:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.tools.roads; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.PathIterator; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * Gives road access to a shape or vpf layer. - */ -public class RoadFinder implements RoadServices, ProjectionListener, RoadLayer { - - protected RoadClasses roadClasses = new RoadClasses(); - - protected RoadClass defaultRoadClass; - - protected LayerView layer; - - protected Intersections intersections = new Intersections(); - - protected RoadList roads = new RoadList(); - - protected List removedRoads = new ArrayList<>(); - - /** - * how far (in lat-lon space) from lat,lon point to look in quad tree for - * nearest road * - */ - protected float halo; - - Logger logger = Logger.getLogger(this.getClass().getName()); - boolean drawIntersections = false; - boolean drawResults = false; - boolean doLoopCheck = false; - protected QuadTree interQuadTree; - boolean doInterp = true; - - /** list of extra graphics to display */ - OMGraphicList toDraw = new OMGraphicList(); - boolean showLines = true; - int roadsMade = 0; - - public RoadFinder(LayerView layer, boolean drawIntersections, boolean drawResults) { - initRoadClasses(); - - this.drawIntersections = drawIntersections; - this.drawResults = drawResults; - logger.info("drawIntersections is " + drawIntersections); - logger.info("drawResults is " + drawResults); - this.layer = layer; - } - - protected void initRoadClasses() { - roadClasses.put(new RoadClass("1", Color.magenta, 2, 25.0f)); - defaultRoadClass = findRoadClass("1"); - } - - /** - * Implemented for ProtectionListener - */ - public void projectionChanged(ProjectionEvent e) { - try { - getData(); - } catch (Exception ee) { - logger.warning("Got exception " + ee); - ee.printStackTrace(); - } - } - - /** - * Take the shape data on the layer and use it to populate our roads and - * intersections. - * - * Clears lists of roads and intersections first, and after calculating the - * roads, tells the RoadLayer what extra graphics to display, if any. - */ - protected synchronized void getData() throws Exception { - logger.info("get Data called."); - intersections.clear(); - removedRoads.clear(); - roads.clear(); - toDraw.clear(); - getRoads(); - checkIntegrity(); - logger.info("showing " + toDraw.size() + " extra graphics."); - layer.setExtraGraphics(toDraw); - halo = 0.05f * (getProjection().getScale() / 20000f); - } - - /** - * Take the shape data on the layer and use it to populate our roads and - * intersections. - * - */ - protected void getRoads() throws Exception { - roadsMade = 0; - OMGraphicList rectangle = layer.getOMGraphicsFromSource(); - int[] xPoints = new int[1024]; - int[] yPoints = new int[1024]; - interQuadTree = new QuadTree<>(); - - int height = getProjection().getHeight(); - int width = getProjection().getWidth(); - int skipped = 0; - - synchronized (rectangle) { - double[] points = new double[6]; - if (logger.isLoggable(Level.INFO)) - logger.info("iterating over rectangle contents."); - - int num = 0; - int made = 0; - for (OMGraphic graphic : rectangle) { - double lastXOff = 0; - double lastYOff = 0; - - num++; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("examining " + graphic); - } - - Shape shape = graphic.getShape(); - if (shape == null) { - continue; - } - - PathIterator path = shape.getPathIterator(new AffineTransform()); - int segment = 0; - int itemsInPath = 0; - boolean pathValid = true; - - while (!path.isDone() && pathValid) { - int type = path.currentSegment(points); - itemsInPath++; - boolean offScreen = false; - if (points[0] < 0 || points[0] >= width) { - // logger.warning("skipping x point " + - // points[0] + " b/c it's off the map."); - offScreen = true; - } - if (points[1] < 0 || points[1] >= height) { - // logger.warning("skipping y point " + - // points[1] + " b/c it's off the map."); - offScreen = true; - } - - switch (type) { - case PathIterator.SEG_CLOSE: - logger.warning("got close"); - break; - case PathIterator.SEG_CUBICTO: - logger.warning("got cubic to"); - break; - case PathIterator.SEG_LINETO: - if (offScreen) { - if (segment > 0) { - // BOZO - // should reexamine whether this is - // legal - there should be - // a one-to-one mapping between - // graphic and road object, - // but this will throw away the - // original entry - - if (doInterp) { - Point interpPt = interp(xPoints[segment - 1], yPoints[segment - 1], points[0], - points[1], width, height); - xPoints[segment] = interpPt.x; - yPoints[segment++] = interpPt.y; - - makeRoad(shape, graphic, made++, xPoints, yPoints, segment); - lastXOff = 0; - lastYOff = 0; - segment = 0; - } - } else { - lastXOff = points[0]; - lastYOff = points[1]; - } - } else { // onscreen - if (lastXOff != 0 || lastYOff != 0) { - Point interpPt = interp(points[0], points[1], lastXOff, lastYOff, width, height); - xPoints[segment] = interpPt.x; - yPoints[segment++] = interpPt.y; - } - - xPoints[segment] = (int) points[0]; - yPoints[segment++] = (int) points[1]; - lastXOff = 0; - lastYOff = 0; - } - - if (logger.isLoggable(Level.FINE)) - logger.fine(" line to " + points[0] + ", " + points[1]); - - break; - case PathIterator.SEG_MOVETO: - if (offScreen) { - lastXOff = points[0]; - lastYOff = points[1]; - } else { - if (segment == 0) { - xPoints[segment] = (int) points[0]; - yPoints[segment++] = (int) points[1]; - } else { - // we got a second move to in the list - // - this is not valid - pathValid = false; - logger.info("got invalid path."); - } - - lastXOff = 0; - lastYOff = 0; - } - - if (logger.isLoggable(Level.FINE)) - logger.fine(" moving to " + points[0] + ", " + points[1]); - - break; - case PathIterator.SEG_QUADTO: - logger.warning("got quad to"); - break; - default: - logger.warning("got another type : " + type); - break; - } - } - - if (segment < 2) { - skipped++; - logger.fine("Skipping line that doesn't have an end point"); - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("items in path " + itemsInPath); - - makeRoad(shape, graphic, made++, xPoints, yPoints, segment); - } - segment = 0; - - path.next(); - } - - if (logger.isLoggable(Level.INFO)) { - logger.info("num items " + num + " skipped " + skipped); - } - - } - } - - /** - * find a point between x1,y1 and x2, y2 that is within the visible map - * - * @param width of visible map - * @param height of visible map - * @return Point between x1,y1 and x2, y2 - */ - protected Point interp(double x1, double y1, double x2, double y2, int width, int height) { - double deltaY = y2 - y1; - double deltaX = x2 - x1; - double slope = deltaY / deltaX; - double newX = x2; - double newY = y2; - - if (newX < 0) { - newX = 0; - newY = Math.round(slope * (newX - x1) + y1); - } else if (newX >= width) { - newX = width - 1; - newY = Math.round(slope * (newX - x1) + y1); - } - - if (newY < 0) { - newY = 0; - newX = Math.round(x1 + (newY - y1) / slope); - } else if (newY >= height) { - newY = height - 1; - newX = Math.round(x1 + (newY - y1) / slope); - } - - int intX = (int) newX; - int intY = (int) newY; - - if (intX < 0) { - logger.warning("new x is " + intX); - intX = 0; - } - if (intX >= width) { - logger.warning("new x is " + intX); - intX = width - 1; - } - if (intY < 0) { - logger.warning("new y is " + intY); - intY = 0; - } - if (intY >= height) { - logger.warning("new y is " + intY); - intY = height - 1; - } - - if (logger.isLoggable(Level.INFO)) { - logger.info("from " + x1 + "," + y1 + " to " + x2 + "," + y2 + "w " + width + " h " + height + " interp " - + intX + "," + intY); - } - - return new Point(intX, intY); - } - - /** - * Makes a road object given the points on the shape that are within the visible - * box - * - * Stores it in a quadTree - */ - protected void makeRoad(Shape shape, OMGeometry graphic, int num, int[] xPoints, int[] yPoints, int segment) { - createRoadFromPoints(num, xPoints, yPoints, segment); - } - - /** - * Makes a road object given the points on the shape that are within the visible - * box - * - * @param nPoints in the xpoints and ypoints arrays - */ - protected RoadObject createRoadFromPoints(int id, int[] xpoints, int[] ypoints, int nPoints) { - RoadPoint[] roadPoints = new RoadPoint[nPoints - 2]; - Intersection from = findIntersection(xpoints[0], ypoints[0]); - Intersection to = findIntersection(xpoints[nPoints - 1], ypoints[nPoints - 1]); - - if (from == null) { - logger.warning("no from intersection for " + xpoints[0] + ", " + ypoints[0]); - } - if (to == null) { - logger.warning("no to intersection for " + xpoints[nPoints - 1] + ", " + ypoints[nPoints - 1]); - } - - int fromBefore = from.getRoadCount(); - int toBefore = to.getRoadCount(); - - String name = "road"; - Road road = createRoad(id, name + "-" + id, from, to, defaultRoadClass); - if (fromBefore + 1 != from.getRoadCount()) - logger.severe("huh? " + from + " had " + fromBefore + " roads before and now " + from.getRoadCount()); - if (toBefore + 1 != to.getRoadCount()) - logger.severe("huh? " + to + " had " + toBefore + " roads before and now " + to.getRoadCount()); - int width = roadsMade % 5; - roadsMade++; - - if (logger.isLoggable(Level.INFO)) { - logger.info("road # " + roadsMade + " " + road + " has " + nPoints + " points"); - } - - if (!showLines && drawIntersections) { - OMPoint point = new YellowPoint(xpoints[0], ypoints[0], 10); - toDraw.add(point); - } - - for (int i = 1; i < nPoints - 1; i++) { - roadPoints[i - 1] = new RoadPoint(road, createLatLonPoint(xpoints[i], ypoints[i]), this); - if (drawIntersections) { - if (showLines) { - OMLine line = new YellowLine(xpoints[i - 1], ypoints[i - 1], xpoints[i], ypoints[i], width); - toDraw.add(line); - toDraw.add(new OMText((xpoints[i - 1] - xpoints[i]) / 2 + xpoints[i - 1], - (ypoints[i - 1] - ypoints[i]) / 2 + ypoints[i - 1] - 5, "" + roadsMade, 0)); - } else { - OMPoint point = new YellowPoint(xpoints[i], ypoints[i], 10); - toDraw.add(point); - } - } - } - - if (drawIntersections) { - if (showLines) { - OMLine line = new YellowLine(xpoints[nPoints - 2], ypoints[nPoints - 2], xpoints[nPoints - 1], - ypoints[nPoints - 1], width); - toDraw.add(line); - toDraw.add(new OMText((xpoints[nPoints - 2] - xpoints[nPoints - 1]) / 2 + xpoints[nPoints - 2], - (ypoints[nPoints - 2] - ypoints[nPoints - 1]) / 2 + ypoints[nPoints - 2] - 5, "" + roadsMade, - 0)); - line.addArrowHead(true); - } else { - OMPoint point = new YellowPoint(xpoints[nPoints - 1], ypoints[nPoints - 1], 10); - toDraw.add(point); - } - } - - if (to == from && nPoints == 2) { - deleteRoad(road); - return null; - } - - road.setRoadPoints(roadPoints); - - if (!road.getFirstIntersection().equals(from)) - logger.severe("huh? " + road + " first inter " + road.getFirstIntersection() + " not " + from); - - if (!road.getSecondIntersection().equals(to)) - logger.severe("huh? " + road + " second inter " + road.getSecondIntersection() + " not " + to); - - if (road.getPoints().length < 2) - logger.warning("Error : somehow made a road " + road + " with too few points."); - else if (logger.isLoggable(Level.INFO)) { - // logger.info("made " + road); - } - - return road; - } - - /** a yellow point for displaying intersections */ - protected class YellowPoint extends OMPoint { - private static final long serialVersionUID = 1L; - - public YellowPoint(int x, int y, int radius) { - super(x, y, radius); - } - - public void render(Graphics g) { - setGraphicsColor(g, Color.YELLOW); - draw(g, getShape()); - } - } - - /** a yellow line for display routes between intersections */ - protected class YellowLine extends OMLine { - private static final long serialVersionUID = 1L; - int width; - - public YellowLine(int x, int y, int x2, int y2, int width) { - super(x, y, x2, y2); - this.width = width; - } - - public void render(Graphics g) { - float[] dash1 = new float[width + 1]; - dash1[0] = 10.f; - - for (int i = 1; i < width; i++) { - dash1[i] = 2.0f; - } - - BasicStroke dashed = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, - 0.0f); - ((Graphics2D) g).setStroke(dashed); - setGraphicsColor(g, Color.YELLOW); - draw(g, getShape()); - } - } - - protected LatLonPoint createLatLonPoint(int x, int y) { - return getProjection().inverse(x, y, new LatLonPoint.Double()); - } - - protected Intersection findIntersection(LatLonPoint loc, String name) { - if (name == null) - return findIntersection(loc); - Intersection intersection = intersections.get(name); - if (intersection != null) { - LatLonPoint foundLoc = intersection.getLocation(); - float distance = (Math.abs(foundLoc.getLatitude() - loc.getLatitude()) - + Math.abs(foundLoc.getLongitude() - loc.getLongitude())); - if (distance * Intersection.GRID > 0.1f) { - intersection = findIntersection(loc); // Ignore the - // name, it's - // too far away. - System.out - .println("Using " + intersection.getName() + " instead of " + name + " distance = " + distance); - return intersection; - } - } else { - intersection = new Intersection(loc, name, this); - intersections.put(intersection); - interQuadTree.put(intersection.getLatitude(), intersection.getLongitude(), intersection); - } - return intersection; - } - - protected Intersection findIntersection(int x, int y) { - LatLonPoint fromLoc = createLatLonPoint(x, y); - Intersection from = findIntersection(fromLoc); - return from; - } - - protected Intersection findIntersection(LatLonPoint loc) { - String name = Intersection.getLatLonPointName(loc); - Intersection intersection = intersections.get(name); - if (intersection == null) { - if (logger.isLoggable(Level.FINE)) - logger.fine("making new intersection for " + loc); - intersection = new Intersection(loc, name, this); - interQuadTree.put(intersection.getLatitude(), intersection.getLongitude(), intersection); - intersections.put(intersection); - } else { - if (logger.isLoggable(Level.FINE)) - logger.fine("found existing intersection for " + loc + " with " + intersection.getRoadCount() - + " roads coming out of it."); - } - return intersection; - } - - protected void deleteIntersection(Intersection intersection) { - if (intersection.getRoadCount() > 0) - throw new IllegalArgumentException("Attempt to delete connected intersection"); - intersections.remove(intersection); - } - - /** - * called from Intersection Implemented for RoadLayer interface - */ - public Road createRoad(Intersection from) { - return createRoad(-1, null, from, null, null); - } - - protected Road createRoad(int id, String name, Intersection from, Intersection to, RoadClass cl_ss) { - if (id < 0) { - id = findUnusedRoadID(); - } - if (name == null) { - name = "Road_" + id; - } - if (from == null) { - from = findIntersection(to.getLocation(), to.getName() + ".drag"); - } - if (to == null) { - to = findIntersection(from.getLocation(), from.getName() + ".drag"); - } - if (cl_ss == null) { - cl_ss = defaultRoadClass; - } - - Road road = new Road(id, name, from, to, cl_ss, this); - road.setModified(true); - from.addRoad(road); - to.addRoad(road); - roads.add(road); - return road; - } - - public void deleteRoad(Road road) { - Intersection intersection1 = road.getFirstIntersection(); - Intersection intersection2 = road.getSecondIntersection(); - intersection1.removeRoad(road); - intersection2.removeRoad(road); - if (intersection1.getRoadCount() == 0) { - deleteIntersection(intersection1); - } - if (intersection2.getRoadCount() == 0) { - deleteIntersection(intersection2); - } - if (intersection1.getRoadCount() == 2 - && intersection1.getRoad(0).getRoadClass() == intersection1.getRoad(1).getRoadClass()) { - joinRoads(intersection1); - } - if (intersection2.getRoadCount() == 2 - && intersection2.getRoad(0).getRoadClass() == intersection2.getRoad(1).getRoadClass()) { - joinRoads(intersection2); - } - removedRoads.add(road); - roads.remove(road); - } - - /** - * Split a road into two roads at one of its corners. An intersection is created - * where the corner was and the segments before the corner become the segments - * of the original road. The segments after the corner become the segments of a - * new road between the new intersection and the - */ - public Intersection splitRoad(Road road, RoadPoint rp) { - RoadPoint[] pointsBefore = road.getPointsBefore(rp); - RoadPoint[] pointsAfter = road.getPointsAfter(rp); - Intersection newIntersection = findIntersection(rp.getLocation(), null); - Intersection firstIntersection = road.getFirstIntersection(); - Intersection secondIntersection = road.getSecondIntersection(); - road.setIntersections(firstIntersection, newIntersection); - road.setRoadPoints(pointsBefore); - secondIntersection.removeRoad(road); - newIntersection.addRoad(road); - Road newRoad = createRoad(-1, null, newIntersection, secondIntersection, road.getRoadClass()); - newRoad.setRoadPoints(pointsAfter); - return newIntersection; - } - - /** - * Join two roads into one. The roads must be the only two roads at the - * intersection and must be of the same class. If the roads are not distinct, - * then we quietly delete the road and remove the intersection. The roads might - * not be distinct if they form an isolated loop (such as a racetrack). Thus - * situation is particularly problematic if the road has no inner points. The - * RoadPoints of both roads are concatenated with a new RoadPoint where the - * intersection was between them. This code is a little complicated because the - * RoadPoints must be assembled in a valid order. The order used is to start - * from the other intersection of the first road to the given intersection and - * from the given intersection of the second road to the other intersection of - * the second road. - */ - public void joinRoads(Intersection intersection) { - if (intersection.getRoadCount() != 2) - throw new IllegalArgumentException("Illegal intersection conversion"); - Road road0 = intersection.getRoad(0); - Road road1 = intersection.getRoad(1); - if (road0 == road1) { - roads.remove(road1); - intersections.remove(intersection); - return; - } - if (road0.getRoadClass() != road1.getRoadClass()) - throw new IllegalArgumentException("Illegal intersection conversion"); - intersections.remove(intersection); - roads.remove(road1); - RoadPoint[] road0Points = road0.getRoadPoints(); - RoadPoint[] road1Points = road1.getRoadPoints(); - RoadPoint[] innerPoints = new RoadPoint[road0Points.length + road1Points.length + 1]; - int j = 0; - Intersection firstIntersection; - if (intersection == road0.getFirstIntersection()) { - firstIntersection = road0.getSecondIntersection(); - for (int i = road0Points.length; --i >= 0;) - innerPoints[j++] = road0Points[i]; - } else { - firstIntersection = road0.getFirstIntersection(); - System.arraycopy(road0Points, 0, innerPoints, j, road0Points.length); - j += road0Points.length; - } - Intersection otherIntersection = road1.getOtherIntersection(intersection); - otherIntersection.removeRoad(road1); - road0.setIntersections(firstIntersection, otherIntersection); - otherIntersection.addRoad(road0); - innerPoints[j++] = new RoadPoint(road0, intersection.getLocation(), this); - if (intersection == road1.getFirstIntersection()) { - System.arraycopy(road1Points, 0, innerPoints, j, road1Points.length); - j += road1Points.length; - } else { - for (int i = road1Points.length; --i >= 0;) - innerPoints[j++] = road1Points[i]; - } - road0.setRoadPoints(innerPoints); - road0.setName(mergeRoadNames(road0.getName(), road1.getName())); - } - - protected String mergeRoadNames(String name0, String name1) { - return name0 + "+" + name1; - } - - public RoadClass findRoadClass(Object className) { - RoadClass cl_ss = (RoadClass) roadClasses.get(className); - if (cl_ss == null) { - return defaultRoadClass; - } - return cl_ss; - } - - public int findUnusedRoadID() { - return roads.findUnusedID(); - } - - /** - * Displays a Route between two points on the map. - *

- * - * @param start start from start point on map - * @param end to end point on map - * @param route the Route to travel from start to end - * @param segments as side effect, populated with PathSegments between returned - * WayPoints - * @return List of WayPoints - */ - public List displayPathOnRoad(Point start, Point end, Route route, List segments) { - List newPoints; - try { - if (route == null) { - OMPoint point = new RedPoint(start.x, start.y, 5); - toDraw.add(point); - point = new RedPoint(end.x, end.y, 5); - toDraw.add(point); - - return null; - } - - if (drawResults) { - OMPoint point = new YellowPoint(start.x, start.y, 10); - toDraw.add(point); - point = new YellowPoint(end.x, end.y, 10); - toDraw.add(point); - } - - newPoints = new ArrayList<>(); - populatePointsAndSegments(route, newPoints, segments); - - if (drawResults) { - Point last = null; - Point first = null; - for (Point pt : newPoints) { - - if (last != null) { - OMLine line = new BlueLine(last.x, last.y, pt.x, pt.y); - toDraw.add(line); - } - if (first == null) { - first = pt; - } - last = pt; - } - - if (first != null && last != null) { - // draw line from start to beginning intersection - OMLine line = new YellowLine(start.x, start.y, first.x, first.y, 10); - toDraw.add(line); - line = new YellowLine(last.x, last.y, end.x, end.y, 10); - toDraw.add(line); - } - } - } catch (Exception e) { - logger.warning("Got exception " + e); - e.printStackTrace(); - return null; - } - - return newPoints; - - } - - /** - * Finds closest intersection to start and end find path from start intersection - * to end intersection - *

- * - * This method works on screen coordinates. - * - * @param start from start point on map - * @param end to end point on map - * @param segments as side effect, populated with PathSegments between returned - * WayPoints - * @return List of WayPoints - */ - public List getPathOnRoad(Point start, Point end, List segments) { - List newPoints; - try { - Route bestRoute = getRouteBetweenPoints(start, end); - newPoints = displayPathOnRoad(start, end, bestRoute, segments); - } catch (Exception e) { - logger.warning("Got exception " + e); - e.printStackTrace(); - return null; - } - - return newPoints; - } - - /** - * a red point for displaying when we can't find a route between two points - */ - protected class RedPoint extends OMPoint { - private static final long serialVersionUID = 1L; - public RedPoint(int x, int y, int radius) { - super(x, y, radius); - } - - public void render(Graphics g) { - setGraphicsColor(g, Color.RED); - draw(g, getShape()); - } - } - - /** a blue line to indicate the found route */ - protected class BlueLine extends OMLine { - private static final long serialVersionUID = 1L; - int width; - - public BlueLine(int x, int y, int x2, int y2) { - super(x, y, x2, y2); - this.width = 5; - } - - public void render(Graphics g) { - float[] dash1 = new float[width + 1]; - dash1[0] = 10.f; - - for (int i = 1; i < width; i++) { - dash1[i] = 2.0f; - } - - BasicStroke dashed = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, - 0.0f); - ((Graphics2D) g).setStroke(dashed); - setGraphicsColor(g, Color.BLUE); - draw(g, getShape()); - } - } - - /** - * Returns best Route between two points specified by latitude and longitude. - *

- * - * This method works on latitude/longitude coordinates. - * - * @return Route between two points - */ - public Route getPathOnRoad(LatLonPoint start, LatLonPoint end) { - Intersection startTemp = findClosestIntersection(start); - Intersection endTemp = findClosestIntersection(end); - - Route bestRoute = null; - - if (startTemp != null && endTemp != null) { - if (roadClasses == null) { - logger.warning("huh? road classes is null???"); - return bestRoute; - } - - bestRoute = Route.getBestRoute(startTemp, endTemp, roadClasses.getBestConvoySpeed(), - roadClasses.getWorstConvoySpeed()); - } - - if (bestRoute == null) { - if (logger.isLoggable(Level.INFO)) - logger.info("no route from " + startTemp + " to " + endTemp); - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("route from " + startTemp + " to " + endTemp + " is " + bestRoute); - } - - // post condition check - if (logger.isLoggable(Level.INFO) && bestRoute != null) { - float length = 0; - for (int i = 0; i < bestRoute.getRoads().length; i++) { - Road road = bestRoute.getRoads()[i]; - length += road.getLengthInKilometers(); - } - - logger.info("best route from " + bestRoute.getOriginIntersection() + " - start " + start + " to " - + bestRoute.getDestinationIntersection() + " - end " + end + " was " + length + " kilometers."); - } - - return bestRoute; - } - - /** - * Returns best Route between two points - * - * This method works on latitude/longitude coordinates. - * - * @return Route between two points - */ - public Route getRouteBetweenPoints(Point start, Point end) { - return getPathOnRoad(createLatLonPoint(start.x, start.y), createLatLonPoint(end.x, end.y)); - } - - /** - * Look in intersection Quad Tree for closest intersection to point x,y - * - * @return Intersection closest - */ - protected Intersection findClosestIntersection(int x, int y) { - return findClosestIntersection(createLatLonPoint(x, y)); - } - - /** - * Look in intersection Quad Tree for closest intersection to point at specified - * latitude and longitude. - *

- * - * @return Intersection closest - */ - protected Intersection findClosestIntersection(LatLonPoint latLon) { - Intersection inter = (Intersection) interQuadTree.get(latLon.getY(), latLon.getX()); - if (inter == null) - logger.warning("no intersection at " + latLon); - - return inter; - } - - /** - * Iterates over route, populating points and segments lists. Worries about - * sequence order of from and to points, i.e. end of one road should be the - * start of the next. This is not guaranteed by the route, so we have to check. - * - * @param bestRoute route to iterate over. - * @param newPoints populated with Points on the route. - * @param segments populated with Segments. - */ - protected void populatePointsAndSegments(Route bestRoute, List newPoints, List segments) { - Projection proj = getProjection(); - - Intersection origin = bestRoute.getOriginIntersection(); - // Intersection dest = bestRoute.getDestinationIntersection(); - - if (logger.isLoggable(Level.INFO)) - logger.info("adding " + bestRoute.roads.length + " new roads."); - - Road road = null; - - Intersection from = origin, to = null; - - Set loopSet = new HashSet<>(); - if (doLoopCheck) { - loopSet.add(origin); - } - - Set ptSet = new HashSet<>(); - for (int i = 0; i < bestRoute.roads.length; i++) { - road = bestRoute.roads[i]; - - if (!from.equals(road.getFirstIntersection()) && !from.equals(road.getSecondIntersection())) { - logger.severe("huh? " + from + " is not an intersection on road " + road); - } - - Point pt = createPoint((Point) proj.forward(from.getLocation(), new Point())); - - if (doLoopCheck) { - if (ptSet.contains(pt)) { - logger.warning("pt set has duplicate at " + pt); - } - ptSet.add(pt); - } - - newPoints.add(pt); - to = road.getOtherIntersection(from); - if (doLoopCheck) { - if (loopSet.contains(to)) { - logger.warning("road has a cycle at " + to); - } - loopSet.add(to); - } - - // check to see if we need to reverse the order of the - // road points, - // which may not be ordered the same as the previous road - - boolean reverse = from.equals(road.getSecondIntersection()); - Segment path = getPathSegment(proj, road, reverse); - - if (logger.isLoggable(Level.INFO)) - logger.info("created path " + path); - - segments.add(path); - - from = to; - } - - if (to != null) { - Point pt = createPoint((Point) proj.forward(to.getLocation(), new Point())); - if (ptSet.contains(pt)) { - logger.warning("pt set has duplicate at " + pt); - } - - newPoints.add(pt); - - if (logger.isLoggable(Level.INFO)) - logger.info(" now " + newPoints.size() + " points and " + segments.size() + " segments."); - } - } - - /** - * Converts a road into a path segment - reverse parameter guarantees the - * ordering of the points is consistent across multiple path segments in the - * whole route. - * - * @return PathSegment converted from a road - */ - protected Segment getPathSegment(Projection proj, Road road, boolean reverse) { - RoadPoint[] roadPoints = road.getRoadPoints(); - - List newPoints = new ArrayList<>(); - if (reverse) { - for (int i = roadPoints.length - 1; i > 0; i--) { - newPoints.add(createPoint((Point) proj.forward(roadPoints[i].getLocation(), new Point()))); - } - } else { - for (int i = 0; i < roadPoints.length; i++) { - newPoints.add(createPoint((Point) proj.forward(roadPoints[i].getLocation(), new Point()))); - } - } - - return createSegment(newPoints); - } - - /** - * Allows subclasses to redefine segments - */ - protected Segment createSegment(List newPoints) { - return new Segment(newPoints); - } - - /** - * Allows subclasses to redefine points returned - */ - protected Point createPoint(Point pt) { - return new Point(pt); - } - - public Projection getProjection() { - return layer.getProjection(); - } - - /** - * Check the integrity of our data structures. - * - * Scan the known intersections. Note intersections with no roads. Scan the - * roads of the intersection: Each road has two intersections. If the road has - * already been encountered, then we recorded its "other" intersection and that - * must match this intersection. If it doesn't match, record an error. If it - * does match reset its recorded other intersection to be a special marker - * indicating that both ends of the road have been accounted for. If the road - * has not already been encountered, then record its "other" intersection. Scan - * the known roads. Every road should accounted for in the "other" intersection - * table and should be marked as having both intersections accounted for. Note - * the roads which were not found in the first scan and the roads which were - * found, but for which both intersections were not found. Remark every road. - * Finally scan the other intersection table for entries which were not marked - * as being in the roads vector. - */ - protected void checkIntegrity() { - // CharArrayWriter errorWriter = new CharArrayWriter(); - // PrintWriter errors = new PrintWriter(errorWriter); - PrintStream errors = System.err; - Map otherIntersections = new HashMap<>(); - - for (Intersection intersection : intersections.getIntersections()) { - - int nRoads = intersection.getRoadCount(); - if (nRoads == 0) { - errors.println("Dangling intersection"); - errors.println(" Intersection = " + intersection); - continue; - } - - for (Road road : intersection.getRoads()) { - - Object other = otherIntersections.get(road); - if (other == null) { - otherIntersections.put(road, road.getOtherIntersection(intersection)); - } else if (other == intersection) { - otherIntersections.put(road, Intersection.INTEGRITY_CHECK_BOTH_INTERSECTIONS); - } else { - errors.println("Misconnected"); - errors.println(" Road = " + road); - errors.println(" Road.Other = " + other); - errors.println(" Intersection = " + intersection); - } - } - } - - for (Road road : roads.getRoads()) { - - Intersection other = otherIntersections.get(road); - if (other == null) { - errors.println("Road not found in intersections"); - errors.println(" Road = " + road); - } else if (other != Intersection.INTEGRITY_CHECK_BOTH_INTERSECTIONS) { - errors.println("Road incompletely connected"); - errors.println(" Road = " + road); - errors.println(" Road.Other = " + other); - } else if (other == Intersection.INTEGRITY_CHECK_INROADS) { - errors.println("Road doubly listed"); - errors.println(" Road = " + road); - } - - otherIntersections.put(road, Intersection.INTEGRITY_CHECK_INROADS); - } - - for (Road road : otherIntersections.keySet()) { - Object other = otherIntersections.get(road); - if (other != Intersection.INTEGRITY_CHECK_INROADS) { - errors.println("Road not listed"); - errors.println(" Road = " + road); - } - } - // String errString = errorWriter.toString(); - // if (errString.isEmpty()) - // return; - // JTextArea text = new JTextArea(errString); - // JScrollPane scrollPane = new JScrollPane(text); - // final JFrame dialog = new JFrame("Errors"); - // JButton ok = new JButton("OK"); - // ok.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent e) { - // dialog.dispose(); - // } - // }); - // dialog.getContentPane().add(scrollPane, - // BorderLayout.CENTER); - // dialog.getContentPane().add(ok, BorderLayout.SOUTH); - // dialog.setSize(new java.awt.Dimension(640, 480)); - // dialog.setVisible(true); - } - - static class RoadList { - int nextRoadId = -1; - Map roads = new HashMap<>(); - - public void clear() { - roads.clear(); - } - - public void add(Road r) { - roads.put(r.getID(), r); - } - - public void remove(Road r) { - roads.remove(r.getID()); - } - - public int findUnusedID() { - ++nextRoadId; - return nextRoadId; - } - - public Road elementAt(int n) { - return roads.get(n); - } - - public List getRoads() { - return new ArrayList<> (roads.values()); - } - - public int size() { - return roads.size(); - } - } - - public static class Intersections { - private Map intersections = new HashMap<>(); - - public void put(Intersection intersection) { - int suffix = 0; - String name = intersection.getName(); - while (intersections.containsKey(name)) { - suffix++; - name = intersection.getName() + "," + suffix; - } - intersection.setName(name); - intersections.put(name, intersection); - } - - public void remove(Intersection intersection) { - intersections.remove(intersection.getName()); - } - - public Intersection get(String name) { - return (Intersection) intersections.get(name); - } - - public Collection getIntersections() { - return intersections.values(); - } - - public boolean contains(Intersection intersection) { - return intersections.get(intersection.getName()) == intersection; - } - - public void clear() { - intersections.clear(); - } - - public int size() { - return intersections.size(); - } - } - - public static class RoadClasses extends HashMap { - private static final long serialVersionUID = 1L; - - float bestConvoySpeed = 0.0f; - float worstConvoySpeed = Float.MAX_VALUE; - - public void put(RoadClass roadClass) { - put(roadClass.getName(), roadClass); - if (roadClass.getConvoySpeed() > bestConvoySpeed) { - bestConvoySpeed = roadClass.getConvoySpeed(); - } - if (roadClass.getConvoySpeed() < worstConvoySpeed) { - worstConvoySpeed = roadClass.getConvoySpeed(); - } - } - - public float getBestConvoySpeed() { - return bestConvoySpeed; - } - - public float getWorstConvoySpeed() { - return worstConvoySpeed; - } - } - - /** BOZO remove me */ - public boolean isEditing() { - return false; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadGraphic.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadGraphic.java deleted file mode 100644 index e4b51acbf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadGraphic.java +++ /dev/null @@ -1,31 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadGraphic.java,v -// $ -// $RCSfile: RoadGraphic.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -public interface RoadGraphic { - public RoadObject getRoadObject(); - - public void blink(boolean on); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLayer.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLayer.java deleted file mode 100644 index fd67f4876..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLayer.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadLayer.java,v $ -// $RCSfile: RoadLayer.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import com.bbn.openmap.proj.Projection; - -/** - * Services provided by RoadFinder for helper classes like - * Intersection - */ -public interface RoadLayer { - - Projection getProjection(); - - Road createRoad(Intersection inter); - - boolean isEditing(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLine.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLine.java deleted file mode 100644 index f1ccfe3ac..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadLine.java +++ /dev/null @@ -1,122 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadLine.java,v -// $ -// $RCSfile: RoadLine.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/12/09 21:09:12 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Point; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class RoadLine extends Visual implements RoadObject { - - private static final long serialVersionUID = 1L; - - private Road road; - - private int index; - - public RoadLine(Road road, int index) { - this.road = road; - this.index = index; - } - - public void moveTo(Point loc) {} - - public RoadPoint addRoadPoint(int x, int y) { - RoadLayer layer = road.getRoadLayer(); - Projection p = layer.getProjection(); - RoadPoint rp = new RoadPoint(road, p.inverse(x, y, new LatLonPoint.Double()), layer); - road.insertRoadPointAt(rp, index + 1); - return rp; - } - - public Road getRoad() { - return road; - } - - public synchronized void render(OMGraphicList gl, boolean forceNew) { - RoadGraphic visual = getVisual(); - if (visual == null || forceNew) { - LatLonPoint p1 = road.getWaypoint(index).getLocation(); - LatLonPoint p2 = road.getWaypoint(index + 1).getLocation(); - visual = new Graphic(p1, p2); - setVisual(visual); - } - gl.add((Graphic) visual); - } - - public class Graphic extends OMLine implements RoadGraphic { - private static final long serialVersionUID = 1L; - - Graphic(LatLonPoint p1, LatLonPoint p2) { - super(p1.getY(), p1.getX(), p2.getY(), p2.getX(), - OMLine.LINETYPE_STRAIGHT); - if (road.isBlocked()) { - setLinePaint(Color.white); - //setLineWidth(road.getRoadClass().getWidth() * 2 + - // 2); - } else { - setLinePaint(road.getRoadClass().getColor()); - /* - * if (road.isRoute()) { - * setLineWidth(road.getRoadClass().getWidth() * 2 + - * 2); } else { - * setLineWidth(road.getRoadClass().getWidth()); } - */ - } - } - - public void blink(boolean newState) { - blinkState = newState; - } - - public void render(Graphics g) { - if (blinkState) - return; - super.render(g); - /* - * if (false && lineWidth > 1) { g.setColor(Color.black); - * int[] x = null, y = null; - * - * int size = fatLines.size(); for (int i = 0; i < size; - * i+=2) { x = (int[])(fatLines.elementAt(i)); y = - * (int[])(fatLines.elementAt(i+1)); g.drawPolygon(x, y, - * x.length); } } - */ - } - - public RoadObject getRoadObject() { - return RoadLine.this; - } - - public RoadLine getRoadLine() { - return RoadLine.this; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadObject.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadObject.java deleted file mode 100644 index c3db6ce5e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadObject.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadObject.java,v -// $ -// $RCSfile: RoadObject.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import com.bbn.openmap.omGraphics.OMGraphicList; - -public interface RoadObject { - - public void render(OMGraphicList gl, boolean forceNew); - - public void moveTo(java.awt.Point loc); - - public void blink(boolean newState); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadPoint.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadPoint.java deleted file mode 100644 index 91e26346a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadPoint.java +++ /dev/null @@ -1,87 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadPoint.java,v -// $ -// $RCSfile: RoadPoint.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class RoadPoint extends Waypoint implements RoadObject { - - private static final long serialVersionUID = 1L; - private Road road; - - public RoadPoint(Road road, LatLonPoint loc, RoadLayer layer) { - super(loc, layer); - this.road = road; - } - - public RoadPoint(Road road, Intersection intersection) { - super(intersection.location, intersection.layer); - this.road = road; - } - - public Road getRoad() { - return road; - } - - public void delete() { - road.deleteRoadPoint(this); - } - - public void update() { - super.update(); - road.updateLines(); - } - - public void render(OMGraphicList gl, boolean forceNew) { - RoadGraphic visual = getVisual(); - if (visual == null || forceNew) { - visual = new Graphic(); - setVisual(visual); - } - gl.add((Graphic) visual); - } - - public class Graphic extends Waypoint.Graphic { - private static final long serialVersionUID = 1L; - - public Graphic() { - super(2); - } - - public RoadObject getRoadObject() { - return getRoadPoint(); - } - - public RoadPoint getRoadPoint() { - return RoadPoint.this; - } - } - - public String toString() { - return "RoadPoint on road " + road + ", " + super.toString(); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadServices.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadServices.java deleted file mode 100644 index 9a2c57bdf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/RoadServices.java +++ /dev/null @@ -1,78 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadServices.java,v $ -// $RCSfile: RoadServices.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/12 21:47:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Point; -import java.util.List; - -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * getPathOnRoad interface - any layer that implements this interface - * can return a route between two points - */ -public interface RoadServices { - - /** - * Returns the best Route between a start point and end point. - *

- * - * This method works by finding the closest intersection to start and end - * points, and then finding a path from start intersection to end intersection. - * The method works on screen coordinates. - * - * @param start - Start point on the map in screen coordinates. - * @param end - End point on the map in screen coordinates. - * @param segments is populated by road segments, each segment is - * a list of points in screen coordinates. - * @return a list of points between start and end points in screen coordinates. - */ - List getPathOnRoad(Point start, Point end, List segments); - - /** - * Returns the best Route between a start point and end point. - *

- * - * This method works by finding the closest intersection to start and end - * points, and then finding a path from start intersection to end intersection. - * The method works in latitude/longitude coordinates. - * - * @param start - Start point in latitude/longitude coordinates. - * @param end - End point in latitude/longitude coordinates. - * @return the best route to travel by Road from start to end - */ - Route getPathOnRoad(LatLonPoint start, LatLonPoint end); - - /** - * Displays a Route between two points on the map. - *

- * - * @param start start from start point on map - * @param end to end point on map - * @param route the Route to travel from start to end - * @param segments as side effect, populated with PathSegments - * between returned WayPoints - * @return List of WayPoints - */ - List displayPathOnRoad(Point start, Point end, Route route, List segments); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Route.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Route.java deleted file mode 100644 index bf2585564..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Route.java +++ /dev/null @@ -1,272 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Route.java,v -// $ -// $RCSfile: Route.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class Route implements Cloneable, Serializable { - - private static final long serialVersionUID = 1L; - - private static float MSEC_PER_HOUR = 3600000.0f; - - private String name = null; - - Road[] roads; - - private boolean startWithFirstIntersection; - // private boolean endWithFirstIntersection; - - transient Logger logger = Logger.getLogger(this.getClass().getName()); - - static class NodeInfo { - Intersection intersection; - Road bestRoad = null; - double time; - double crowsPathHours; - - NodeInfo(Intersection intersection, Road road, double time, double crowsPathHours) { - this.intersection = intersection; - this.bestRoad = road; - this.time = time; - this.crowsPathHours = crowsPathHours; - } - } - - public synchronized static Route getBestRoute(Intersection from, Intersection to, double bestConvoySpeed, - double worstConvoySpeed) { - Map marks = new HashMap<>(); - boolean haveRoute = false; - LatLonPoint toLoc = to.getLocation(); - double toLat = toLoc.getY(); - double toLon = toLoc.getX(); - LatLonPoint fromLoc = from.getLocation(); - double fromLat = fromLoc.getY(); - double fromLon = fromLoc.getX(); - double timeLimitBase = GreatCircle.sphericalDistance(toLat, toLon, fromLat, fromLon) / worstConvoySpeed; - double bestTime = Double.MAX_VALUE; - for (float snakeFactor = 1.0f; snakeFactor < 40f; snakeFactor *= 2f) { - // if (logger.isLoggable(Level.INFO)) - // logger.info ("Snake factor " + snakeFactor); - - double timeLimit = timeLimitBase * snakeFactor; - List toDo = new ArrayList<>(); - toDo.add(from); - marks.clear(); - marks.put(from, new NodeInfo(from, null, 0.0f, 0.0f)); - while (!toDo.isEmpty()) { - List newToDo = new ArrayList<>(); - for (Intersection thisIntersection : toDo) { - - NodeInfo thisInfo = (NodeInfo) marks.get(thisIntersection); - // System.out.println ("examining " + - // thisIntersection); - for (Road road : thisIntersection.getRoads()) { - - // System.out.println (" - road " + road); - double roadTime = road.getTraverseHours(); - double newTime = thisInfo.time + roadTime; - - if (newTime > timeLimit) { - continue; - } - Intersection nextIntersection = road.getOtherIntersection(thisIntersection); - // System.out.println (" - next inter " + nextIntersection); - - NodeInfo nextInfo = marks.get(nextIntersection); - if (nextInfo == null) { - LatLonPoint nextLoc = nextIntersection.getLocation(); - double crowsPathDistance = GreatCircle.sphericalDistance(toLat, toLon, nextLoc.getY(), - nextLoc.getX()); - double crowsPathHours = crowsPathDistance / bestConvoySpeed; - nextInfo = new NodeInfo(nextIntersection, road, newTime, crowsPathHours); - marks.put(nextIntersection, nextInfo); - if (newTime + nextInfo.crowsPathHours > bestTime) - continue; - newToDo.add(nextIntersection); - - // System.out.println (" - best road for " + nextIntersection + " is " + road); - - } else if (nextInfo.time > newTime) { - if (!nextInfo.intersection.equals(nextIntersection)) { - System.err.println("huh? lookup of " + nextIntersection + " gets node info with inter " - + nextInfo.intersection); - } - nextInfo.time = newTime; - nextInfo.bestRoad = road; - // System.out.println (" - (redo) best - // road for " + nextIntersection + " is " - // + road); - if (newTime + nextInfo.crowsPathHours > bestTime) - continue; - newToDo.add(nextIntersection); - } else { - continue; - } - if (nextIntersection == to) { - // System.err.println ("found end " + to); - bestTime = nextInfo.time; - haveRoute = true; - } - } - } - toDo = newToDo; - } - - if (haveRoute) { - break; - } - } - - List roadVector = new ArrayList<>(); - Route result = null; - if (haveRoute) { - for (NodeInfo info = (NodeInfo) marks.get(to); result == null;) { - roadVector.add(info.bestRoad); - // System.err.println ("adding Road #" + (i++) + " - " - // + info.bestRoad); - Intersection prevIntersection = info.bestRoad.getOtherIntersection(info.intersection); - if (prevIntersection == from) - result = new Route(roadVector, info.bestRoad.getFirstIntersection() == prevIntersection); - else - info = (NodeInfo) marks.get(prevIntersection); - } - } - marks = null; - return result; - } - - public Route(String name, Road[] roads, boolean startWithFirstIntersection) { - this.name = name; - this.roads = roads; - this.startWithFirstIntersection = startWithFirstIntersection; - } - - private Route(List roadVector, boolean startWithFirstIntersection) { - int nRoads = roadVector.size(); - roads = new Road[nRoads]; - for (int i = 0; i < nRoads; i++) { - roads[i] = roadVector.get(nRoads - 1 - i); - } - this.startWithFirstIntersection = startWithFirstIntersection; - } - - public Object clone() { - return new Route(null, roads, startWithFirstIntersection); - } - - public String getName() { - return name; - } - - public void setName(String newName) { - name = newName; - } - - public Road[] getRoads() { - return roads; - } - - public int getBlockedRoadCount() { - int blockedRoadCount = 0; - for (int i = 0; i < roads.length; i++) { - if (roads[i].isBlocked()) { - blockedRoadCount++; - } - } - return blockedRoadCount; - } - - public void unblockBlockedRoads() { - for (int i = 0; i < roads.length; i++) { - if (roads[i].isBlocked()) { - roads[i].unblock(); - } - } - } - - public Intersection getOriginIntersection() { - if (startWithFirstIntersection) - return roads[0].getFirstIntersection(); - else - return roads[0].getSecondIntersection(); - } - - public Intersection getDestinationIntersection() { - Intersection x = getOriginIntersection(); - for (int i = 0; i < roads.length; i++) { - x = roads[i].getOtherIntersection(x); - } - return x; - } - - public long getTravelTime() { - double hours = 0.0f; - for (int i = 0; i < roads.length; i++) { - Road road = roads[i]; - double roadLength = road.getLengthInKilometers(); - double convoySpeed = road.getRoadClass().getConvoySpeed(); - double timeToTraverse = roadLength / convoySpeed; - hours += timeToTraverse; - } - return (long) (hours * MSEC_PER_HOUR); - } - - public LatLonPoint location(long time) { - double hours = time / MSEC_PER_HOUR; - Intersection from = (startWithFirstIntersection ? roads[0].getFirstIntersection() - : roads[0].getSecondIntersection()); - - for (int i = 0; i < roads.length; i++) { - Road road = roads[i]; - boolean forward = road.getFirstIntersection() == from; - double roadLength = road.getLengthInKilometers(); - double convoySpeed = road.getRoadClass().getConvoySpeed(); - double timeToTraverse = roadLength / convoySpeed; - if (timeToTraverse > hours) { - float fraction = (float) hours / (float) timeToTraverse; - if (!forward) { - fraction = 1.0f - fraction; - } - return road.getLocationAtKilometer(roadLength * fraction); - } - hours -= timeToTraverse; - if (forward) { - from = road.getSecondIntersection(); - } else { - from = road.getFirstIntersection(); - } - } - return from.getLocation(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Segment.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Segment.java deleted file mode 100644 index ccbc18ea0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Segment.java +++ /dev/null @@ -1,51 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Segment.java,v $ -// $RCSfile: Segment.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Point; -import java.util.List; - -/** - * Represents one road segment. - */ -public class Segment { - - protected List allTravelPoints; - - public Segment(List points) { - this.allTravelPoints = points; - } - - public String toString() { - StringBuffer str = new StringBuffer(); - for (int i = 0; i < allTravelPoints.size(); i++) { - str.append("=>"); - - Point pt = (Point) allTravelPoints.get(i); - str.append("{").append(pt.x).append(",").append(pt.y).append("}"); - } - str.append("=>"); - - return str.toString(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Visual.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Visual.java deleted file mode 100644 index 9a1075bdb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Visual.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Visual.java,v -// $ -// $RCSfile: Visual.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/12 21:47:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.io.Serializable; - -public class Visual implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * The visual representation of this Waypoint. - */ - private transient RoadGraphic visual; - - protected boolean blinkState = false; - - /** - * The RoadLayer of which we are a part. - */ - protected transient RoadLayer layer; - - /** - * Mark this Visual as needing to have its visual representation - * updated. It has moved or otherwise changed its appearance. - */ - public void update() { - visual = null; - } - - public void setVisual(RoadGraphic newVisual) { - visual = newVisual; - visual.blink(blinkState); - } - - public RoadGraphic getVisual() { - return visual; - } - - public void blink(boolean newState) { - blinkState = newState; - if (visual != null) { - visual.blink(newState); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/Waypoint.java b/src/core/src/main/java/com/bbn/openmap/tools/roads/Waypoint.java deleted file mode 100644 index bf0a68bae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/Waypoint.java +++ /dev/null @@ -1,184 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Waypoint.java,v -// $ -// $RCSfile: Waypoint.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/02/16 16:22:49 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Color; -import java.awt.Point; -import java.io.Serializable; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public abstract class Waypoint extends Visual implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * The location of this waypoint. - */ - protected LatLonPoint location; - - protected Point screenLocation = null; - - /** - * True if this waypoint has modified since it was created or written. - */ - private boolean modified = false; - - /** - * create a Waypoint at a given location. - * - * @param loc the location of the Waypoint - */ - public Waypoint(LatLonPoint loc, RoadLayer layer) { - location = loc; - this.layer = layer; - } - - /** - * Set the modified flag - */ - public void setModified(boolean newValue) { - modified = newValue; - } - - /** - * Get the state of the modified flag. - */ - public boolean getModified() { - return modified; - } - - /** - * Get the location of this Waypoint. - * - * @return the location of this Waypoint. - */ - public LatLonPoint getLocation() { - return location; - } - - /** - * Set the location of this Waypoint. - * - * @param loc the new location. - */ - public void setLocation(LatLonPoint loc) { - location = loc; - update(); - } - - public Point getScreenLocation() { - if (screenLocation == null) - screenLocation = (Point) getRoadLayer().getProjection() - .forward(location, new Point()); - return screenLocation; - } - - public void setScreenLocation(Point loc) { - setLocation(getRoadLayer().getProjection().inverse(loc.x, - loc.y, - new LatLonPoint.Double())); - } - - public void update() { - super.update(); - screenLocation = null; - } - - // /** - // * Get the OMGraphic for this Waypoint. - // * @return the visual OMGraphic. Create it if necessary - // */ - // public OMGraphic getOMGraphic(Projection p) { - // if (visual == null) { - // OMGraphicList gl = new OMGraphicList(1); - // render(gl, p, true); - // } - // return visual; - // } - - /** - * Get the RoadLayer of which this is a part. - * - * @return the RoadLayer. - */ - public RoadLayer getRoadLayer() { - return layer; - } - - /** - * Move this Intersection a distance on the screen. - */ - public void moveTo(Point loc) { - setScreenLocation(loc); - } - - public double getLatitude() { - return getLocation().getY(); - } - - public double getLongitude() { - return getLocation().getX(); - } - - /** - * Add the visual representation of this Waypoint to the graphics list. Our - * visual representation is just a rectangle with radius 2. - */ - public abstract void render(OMGraphicList gl, boolean projectionIsNew); - - public abstract class Graphic extends OMRect implements RoadGraphic { - private static final long serialVersionUID = 1L; - Logger logger = Logger.getLogger(this.getClass().getName()); - private boolean blinkState = false; - - protected Graphic(int radius) { - super(Waypoint.this.getLocation().getY(), Waypoint.this.getLocation().getX(), - -radius, - -radius, - radius, - radius); - setLinePaint(Color.black); - } - - public void blink(boolean newState) { - blinkState = newState; - } - - public void render(java.awt.Graphics g) { - if (!blinkState) - super.render(g); - } - - public abstract RoadObject getRoadObject(); - } - - public String toString() { - return "Waypoint : location " + location; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/roads/package.html b/src/core/src/main/java/com/bbn/openmap/tools/roads/package.html deleted file mode 100644 index f9f11b95e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/roads/package.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides classes to determine routes given a set of roads and -intersections. The com.bbn.openmap.layer.shape.MultiRoadLayer uses -these classes to determine routes using Shape file data. The -com.bbn.openmap.layer.vpf.VPFRoadLayer uses these classes to -determine routes using VPF road data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/BasicSymbolImageMaker.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/BasicSymbolImageMaker.java deleted file mode 100644 index 5db37a55e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/BasicSymbolImageMaker.java +++ /dev/null @@ -1,183 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: BasicSymbolImageMaker.java,v $ -//$Revision: 1.5 $ -//$Date: 2008/01/29 22:04:13 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.Dimension; -import java.awt.Paint; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.image.ImageScaler; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -public class BasicSymbolImageMaker extends OMComponent implements - SymbolImageMaker { - - protected String dataPath; - protected Paint background; - - public BasicSymbolImageMaker() { - this(null); - } - - public BasicSymbolImageMaker(String dataPath) { - this.dataPath = (dataPath != null ? dataPath : ""); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - setBackground(PropUtils.parseColorFromProperties(props, prefix - + BackgroundPaintProperty, "0x00000000")); - String dataPathString = props.getProperty(prefix + DataPathProperty); - if (dataPathString != null) { - setDataPath(dataPathString); - } else { - if (Debug.debugging("symbology")) { - Debug.output(getClass().getName() - + " data path (" - + prefix - + DataPathProperty - + ") not set in properties, might be OK if symbol data stored in jar in classpath."); - } - } - } - - /** - * @param code - * @return URL for a file containing the symbol for the given code, null if - * it's not available. - * @throws MalformedURLException - */ - protected URL getFileURL(String code) throws MalformedURLException { - code = massageCode(code); - code = dataPath + ((dataPath != null && dataPath.length() > 0) ? "/" : "") - + code + getFileExtension(); - if (Debug.debugging("symbology")) { - Debug.output("AbstractSymbolImageMaker: code massaged to " + code); - } - URL ret = PropUtils.getResourceOrFileOrURL(code); - return ret; - } - - /** - * Return the file extension of this particular SymbolImageMaker, added to - * the symbol name after the code has been massaged into a file name. The - * BasicSymbolImageLaker doesn't add an extension. If you override, include - * the dot at the beginning of the return string. - */ - public String getFileExtension() { - return ""; - } - - /** - * @param code - * @return code that has any wildcard characters changed for the sake of the - * symbol database. - */ - protected String massageCode(String code) { - code = code.replace('*', '-').toLowerCase(); - - return code; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.tools.symbology.milStd2525.SymbolImageMaker#getIcon(java.lang.String, - * java.awt.Dimension) - */ - public ImageIcon getIcon(String code, Dimension di) { - - if (code == null) { - return null; - } - - try { - URL fileURL = getFileURL(code); - if (Debug.debugging("symbology")) { - Debug.output("BasicSymbolImageMaker: Trying to create " - + fileURL); - } - - BufferedImage bi = BufferedImageHelper.getBufferedImage(fileURL); - return new ImageIcon(ImageScaler.getOptimalScalingImage(bi, (int) di.getWidth(), - (int) di.getHeight(), bi.getType())); - } catch (IOException e) { - e.printStackTrace(); - } catch (NullPointerException npe) { - if (Debug.debugging("symbology")) { - Debug.output("BasicSymbolImageMaker: didn't find data for image: " + code); - if (Debug.debugging("symbologydetail")) { - npe.printStackTrace(); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.tools.symbology.milStd2525.SymbolImageMaker#setDataPath(java.lang.String) - */ - public void setDataPath(String dataPath) { - this.dataPath = dataPath; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.tools.symbology.milStd2525.SymbolImageMaker#setBackground(java.awt.Paint) - */ - public void setBackground(Paint p) { - this.background = p; - } - - /** - * @return Returns the background. - */ - public Paint getBackground() { - return background; - } - - /** - * @return Returns the dataPath. - */ - public String getDataPath() { - return dataPath; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeAffiliation.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeAffiliation.java deleted file mode 100644 index 33c19a935..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeAffiliation.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeAffiliation.java,v $ -// $RCSfile: CodeAffiliation.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The CodeAffiliation CodePosition presents options for symbols, - * noting that the symbol represents a friend, foe or unknown. This - * notation is made in the second character of some symbol code - * strings (those that allow affiliations). - */ -public class CodeAffiliation extends CodePosition { - - public CodeAffiliation() { - super("Affiliation", 2, 2); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeBattleDimension.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeBattleDimension.java deleted file mode 100644 index 3339e8450..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeBattleDimension.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeBattleDimension.java,v $ -// $RCSfile: CodeBattleDimension.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The CodeBattleDimension CodePositions notes whether the symbol - * represents an object in space, in the air, on the ground, surface - * of the water or underneath the water. The battle dimension usually - * changes the background shape of the symbol, and is noted on the - * third character of the symbol codes of those symbols that have - * battle dimensions. - */ -public class CodeBattleDimension extends CodePosition { - - public CodeBattleDimension() { - super("Battle Dimension", 3, 3); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeCategory.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeCategory.java deleted file mode 100644 index 3acccc1a9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeCategory.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeCategory.java,v $ -// $RCSfile: CodeCategory.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The CodeCategory CodePosition is used by Tactical Graphics to note - * the types of activities that a symbol represents - tasks, general - * maneuvers, support. The CodeCategory is represented by the third - * position of the symbol code of tactical graphic symbols. - */ -public class CodeCategory extends CodePosition { - - public CodeCategory() { - super("Category", 3, 3); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeFunctionID.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeFunctionID.java deleted file mode 100644 index a65d2543d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeFunctionID.java +++ /dev/null @@ -1,115 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeFunctionID.java,v $ -// $RCSfile: CodeFunctionID.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; - -/** - * The CodeFunctionID CodePosition represents a single level of the - * part of the tree that starts to really scope in on a symbol's - * purpose. CodeFunctionIDs are used to represent the 5-10 characters - * of a symbol code. The CodePositions are linked together in a tree - * format when the hierarchy tree is read and interpreted, with like - * features grouped together under a common SymbolPart by a - * CodeFunctionID. - */ -public class CodeFunctionID extends CodePosition { - - public CodeFunctionID() { - // Code function IDs are not kept around, they are just used - // to create the SymbolPart Structure. The first three - // arguments in the super call are meaningless. - this(5); - } - - public CodeFunctionID(int pos) { - // Code function IDs are not kept around, they are just used - // to create the SymbolPart Structure. The first three - // arguments in the super call are meaningless. - super("Function ID", pos, 10); - } - - public void parseHierarchy(String hCode, Properties props, SymbolPart parent) { - - List parentList = null; - int subLevelNumber = 1; - - int pos = getStartIndex() + parent.positionShift; - if (pos < 4) - pos = 4; - - if (pos == 10) { - return; - } - - // startIndex is one less that originally specified, need to - // add an extra 1 to the new position of counteract that. - CodeFunctionID cp = new CodeFunctionID(pos + 2); - - while (subLevelNumber > 0) { - String hCode2 = hCode + "." + subLevelNumber; - String entry = props.getProperty(hCode2); - if (entry != null) { - - if (DEBUG) { - Debug.output("CodeFunctionID.parse: reading " + hCode2 - + " as " + entry); - } - - SymbolPart sp = new SymbolPart(cp, entry, props, parent); - - if (parentList == null) { - parentList = parent.getSubs(); - if (parentList == null) { - parentList = new ArrayList<>(); - parent.setSubs(parentList); - } - } - - if (DEBUG) { - Debug.output("CodeFunctionID.parse: adding " - + sp.getPrettyName() + " to " - + parent.getPrettyName()); - } - - parentList.add(sp); - - if (DEBUG) { - Debug.output("CodePosition.parse: looking for children of " - + sp.getPrettyName()); - } - - cp.parseHierarchy(hCode2, props, sp); - subLevelNumber++; - - } else { - subLevelNumber = -1; - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMETOCCategory.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMETOCCategory.java deleted file mode 100644 index 6d526615e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMETOCCategory.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeMETOCCategory.java,v $ -// $RCSfile: CodeMETOCCategory.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * A CodeMETOCCategory is similar to the Tactical Graphics - * CodeCategory, but it applies to the METOC symbol set instead. This - * CodePosition notes the second character in METOC symbol codes, and - * represents whether a METOC event is in space, the atmosphere or - * ocean. - */ -public class CodeMETOCCategory extends CodePosition { - - public CodeMETOCCategory() { - super("METOC Catetory", 2, 2); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWCategory.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWCategory.java deleted file mode 100644 index 2513fd8d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWCategory.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWCategory.java,v $ -// $RCSfile: CodeMOOTWCategory.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * A CodeMOOTWCategory is similar to the Tactical Graphics - * CodeCategory, but it applies to the MOOTW symbol set instead. This - * CodePosition notes the third character in MOOTW symbol codes, and - * represents whether a MOOTW event concerns violent activities, - * locations, operations, or items. - */ -public class CodeMOOTWCategory extends CodePosition { - - public CodeMOOTWCategory() { - super("MOOTW Categories", 3, 3); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWModifier.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWModifier.java deleted file mode 100644 index b936df973..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWModifier.java +++ /dev/null @@ -1,58 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeMOOTWModifier.java,v $ -// $RCSfile: CodeMOOTWModifier.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.Properties; - -import com.bbn.openmap.util.PropUtils; - -/** - * A CodeMOOTWCategory is similar to the CodeModifier CodeCategory, - * but it applies to the MOOTW symbol set instead. This CodePosition - * notes the 11 and 12 characters in MOOTW symbol codes. - */ -public class CodeMOOTWModifier extends CodePosition { - - public CodeMOOTWModifier() { - super("MOOTW Modifiers", 11, 12); - } - - /** - * Starts looking for property 1, creates SymbolParts until the - * numbers run out. If there are limits to what properties should - * be read, this method should be overriden. - */ - public void parsePositions(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - for (int index = 1; index > 0 && index < 126; index++) { - String entry = props.getProperty(prefix + Integer.toString(index)); - - if (entry != null) { - addPositionChoice(index, entry, prefix, props); - } else { - index = -1; - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOptions.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOptions.java deleted file mode 100644 index e85f42743..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOptions.java +++ /dev/null @@ -1,53 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeOptions.java,v $ -// $RCSfile: CodeOptions.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.List; - -/** - * CodeOptions represent a set of CodePositions that can be chosen for a - * particular SymbolPart. This class is a holder for affiliations, order of - * battle, modifier settings, etc. - */ -public class CodeOptions { - protected List options; - - public CodeOptions(List opts) { - options = opts; - } - - public String toString() { - StringBuffer sb = new StringBuffer("CodeOptions:\n"); - if (options != null) { - for (CodePosition cp : options) { - sb.append(cp.toString()).append("\n"); - } - } - return sb.toString(); - } - - public List getOptions() { - return options; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOrderOfBattle.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOrderOfBattle.java deleted file mode 100644 index 4c7295a1b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeOrderOfBattle.java +++ /dev/null @@ -1,35 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeOrderOfBattle.java,v $ -// $RCSfile: CodeOrderOfBattle.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The CodeOrderOfBattle CodePosition handles the 15th character in - * most symbol codes. It provides additional information about the - * role of a symbol in the battlespace. - */ -public class CodeOrderOfBattle extends CodePosition { - - public CodeOrderOfBattle() { - super("Order of Battle", 15, 15); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePosition.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePosition.java deleted file mode 100644 index fbd136810..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePosition.java +++ /dev/null @@ -1,348 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodePosition.java,v $ -// $RCSfile: CodePosition.java,v $ -// $Revision: 1.12 $ -// $Date: 2005/08/11 20:39:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The CodePosition class is a base class used to interpret and organize role - * settings for a symbol. The SymbolCode describes a symbol and its role, with - * different characters having defined meanings and optional values, depending - * on the symbol. The CodePosition object defines a character and meaning for a - * character in a certain place. A SymbolPart refers to a particlar CodePosition - * that uniquely defines it, giving it some organizational meaning. SymbolParts - * that share a parent can get to the parent's CodePositin to see that meaning - * as well. - *

- * - * CodePositions have some intelligence for parsing position properties and - * hierarchy properties, which allow the whole symbol tree to be defined. - *

- * - * CodePositions server a couple of different roles. Some CodePosition objects - * organize the kinds of set values that may be applicable for a certain - * character position, and can offer those choices. These organizational - * CodePositions won't have a SymbolPart to represent itself. Other - * CodePositions, including the choices and those tied directly to SymbolParts - * in the SymbolPart tree, don't offer choices but can provide SymbolParts to - * represent themselves in the symbol. - */ -public class CodePosition { - - public final static char NO_CHAR = ' '; - public final static int NO_NUMBER = -1; - - protected int hierarchyNumber; - protected String id; - protected String prettyName; - protected int startIndex; - protected int endIndex; - protected CodePosition nextPosition = null; - protected SymbolPart symbolPart = null; - - public boolean DEBUG = false; - - /** Property file property for pretty name 'name' */ - public final static String NameProperty = "name"; - - /** - * Property file property for a classname representing the next position in the - * position tree 'next'. - */ - public final static String NextProperty = "next"; - - /** - * A list of CodePosition choices for this position. This is only used for a - * single instance of the CodePosition that in turn holds this list of possible - * versions. - */ - protected List choices; - - public CodePosition() { - DEBUG = Debug.debugging("codeposition"); - } - - public CodePosition(String name, int start, int end) { - this(); - startIndex = start - 1; - endIndex = end; - prettyName = name; - } - - /** - * A query method that answers of the given 15 digit code applies to this symbol - * part. - * - * @param queryCode - * @return true if the code applies to this position. - */ - public boolean codeMatches(String queryCode) { - int length = id.length(); - - if (Debug.debugging("symbology.detail")) { - Debug.output( - "Checking " + queryCode + " against |" + id + "| starting at " + startIndex + " for " + length); - } - return queryCode.regionMatches(true, startIndex, id, 0, length); - } - - /** - * Get the current list of CodePosition possibilities. Only returns a list for - * the CodePositions used to parse the position properties. - */ - public List getPositionChoices() { - return choices; - } - - /** - * Get a CodePosition from this list of available possibilities given the - * hierarchy number for the position. Not all positions have a hierarchy number, - * but the number given in the positions properties will probably suffice. - */ - public CodePosition getFromChoices(int hierarchyNumber) { - List aList = getPositionChoices(); - if (aList != null) { - for (CodePosition cp : aList) { - if (hierarchyNumber == cp.getHierarchyNumber()) { - return cp; - } - } - } - return null; - } - - /** - * Method to add a position to the choices for this particular code position. - * - * @param index the hierarchical index for this position choice. This really - * only becomes important for those CodePositions which are used - * for interpreting the hierarchy properties. Other positions can - * use them for convenience, and this value will probably be just - * an ordering number for this choice out of all the other choices - * for the position. - * @param entry this should be character or characters used in the symbol code - * for this particular position choice. - * @param prefix the scoping property prefix used for all the properties. The - * entry is discovered by looking in the properties for this - * 'prefix.index'. Then other properties are discovered by looking - * for 'prefix.entry.propertyKey' properties. - * @param props the position properties. - */ - protected CodePosition addPositionChoice(int index, String entry, String prefix, Properties props) { - String className = this.getClass().getName(); - CodePosition cp = (CodePosition) ComponentFactory.create(className); - if (cp != null) { - if (DEBUG) { - Debug.output("CodePosition: created position (" + className + ")"); - } - - // Before prefix is modified - cp.symbolPart = getSymbolPart(prefix + entry, prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix) + entry + "."; - - // Might not mean anything for option-type positions - cp.hierarchyNumber = index; - // cp.id = entry.charAt(0); // ASSUMED, but breaks - // multi-character codes - cp.id = entry; - cp.prettyName = props.getProperty(prefix + NameProperty); - addPositionChoice(cp); - } else { - if (DEBUG) { - Debug.output("CodePosition: couldn't create position (" + className + ")"); - } - } - return cp; - } - - /** - * Add the CodePosition to the choices, creating the choices List if needed. - */ - public void addPositionChoice(CodePosition cp) { - if (choices == null) { - choices = new LinkedList<>(); - } - choices.add(cp); - } - - /** - * This method reads Properties to add choices to this class as options for what - * values are valid in this position. - */ - protected void parsePositions(String prefix, Properties props) { - int index = 1; - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String entry = props.getProperty(prefix + Integer.toString(index)); - - while (entry != null) { - addPositionChoice(index, entry, prefix, props); - entry = props.getProperty(prefix + Integer.toString(++index)); - } - } - - /** - * A method called when parsing position properties. - * - * @param entry should be prefix of the overall position class along with the - * symbol representation for that position. - * @param prefix should just be the prefix for the overall position class, - * including the period before the symbol representation for that - * position. - * @param props the position properties. - */ - protected SymbolPart getSymbolPart(String entry, String prefix, Properties props) { - int offset = prefix.length(); - return new SymbolPart(this, entry, props, null, offset, offset + endIndex - startIndex, false); - } - - protected void parseHierarchy(String hCode, Properties props, SymbolPart parent) { - - List parentList = null; - int levelCounter = 1; - - while (levelCounter > 0) { - - String hierarchyCode = hCode + "." + levelCounter; - - if (DEBUG) { - Debug.output("CodePosition.parse: " + hierarchyCode + " with " + getPrettyName()); - } - - String entry = props.getProperty(hierarchyCode); - - if (entry != null) { - CodeFunctionID cp = new CodeFunctionID(); - SymbolPart sp = new SymbolPart(cp, entry, props, parent); - - if (parentList == null) { - parentList = parent.getSubs(); - if (parentList == null) { - parentList = new LinkedList<>(); - parent.setSubs(parentList); - } - } - - if (DEBUG) { - Debug.output("CodePosition.parse: adding " + sp.getPrettyName() + " to " + parent.getPrettyName()); - } - - parentList.add(sp); - - if (DEBUG) { - Debug.output("CodePosition.parse: looking for children of " + sp.getPrettyName()); - } - - cp.parseHierarchy(hierarchyCode, props, sp); - - levelCounter++; - - } else { - levelCounter = -1; // Flag to punch out of loop - } - } - } - - /** - * The SymbolPart tree can be represented by a hierarchy number system, and this - * system is what is used in the hierarchy properties file to build the symbol - * tree. - */ - public int getHierarchyNumber() { - return hierarchyNumber; - } - - /** - * Return a string version of the hierarchy number. - */ - public String getHierarchyNumberString() { - return Integer.toString(hierarchyNumber); - } - - /** - * Get the character, in the symbol code, that this position represents. - */ - public String getID() { - return id; - } - - /** - * Get the pretty name that states what this position and character represents. - */ - public String getPrettyName() { - return prettyName; - } - - /** - * Get the starting index of the span that this position represents. This value - * is a java index value starting at 0. - */ - public int getStartIndex() { - return startIndex; - } - - /** - * Get the ending index of the span that this position represents. This value is - * a java index value starting at 0. - */ - public int getEndIndex() { - return endIndex; - } - - /** - * Return the next CodePosition. An organizational tool to help build the - * SymbolPart tree when parsing the hierarchy properties. - */ - public CodePosition getNextPosition() { - return nextPosition; - } - - public String toString() { - // return getPrettyName() + " [" + getID() + "] at " + - // getStartIndex() + ", " + getEndIndex(); - return getPrettyName(); - } - - protected CodePosition getNULLCodePosition() { - String className = this.getClass().getName(); - CodePosition cp = (CodePosition) ComponentFactory.create(className); - StringBuffer idbuf = new StringBuffer(); - for (int i = startIndex; i < endIndex; i++) { - idbuf.append("*"); - } - cp.id = idbuf.toString(); - cp.prettyName = "- Unspecified -"; - if (Debug.debugging("symbology")) { - Debug.output("CodePosition: creating *unspecified* version of (" + className + ") with " + cp.id + ", " - + cp.prettyName); - } - return cp; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePositionTree.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePositionTree.java deleted file mode 100644 index 2339ac016..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodePositionTree.java +++ /dev/null @@ -1,153 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodePositionTree.java,v $ -// $RCSfile: CodePositionTree.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/12/08 01:08:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; - -/** - * The CodePositionTree is a CodeScheme CodePosition object that has some - * intelligence on how to starting building the SymbolPart tree for the - * SymbolReferenceLibrary. It knows how to set up CodeOptions for the different - * types of CodeSchemes, and starts the parsing of the hierarchy properties. - */ -public class CodePositionTree extends CodeScheme { - - public CodePositionTree(Properties positionProperties) { - // Read CodeSchemes, build position tree. Then, this - // CodePosition can be used to build the hierarchical symbol - // tree from the head SymbolPart - - CodeScheme cs = new CodeScheme(); - cs.parsePositions("scheme", positionProperties); - // This is needed to parse hierarchy... - choices = cs.getPositionChoices(); - - // parsePositions("scheme", positionProperties); - // // This is needed to parse hierarchy... - // choices = cs.getPositionChoices(); - - // Read Optional Flag Positions - CodeAffiliation ca = new CodeAffiliation(); - ca.parsePositions("affiliation", positionProperties); - ca.choices.add(0, ca.getNULLCodePosition()); - - CodeWarfightingModifier cwm = new CodeWarfightingModifier(); - CodeSizeModifier csm = new CodeSizeModifier(); - CodeMOOTWModifier cmm = new CodeMOOTWModifier(); - cwm.parsePositions("modifiers", positionProperties); - cwm.choices.add(0, cwm.getNULLCodePosition()); - csm.parsePositions("modifiers", positionProperties); - csm.choices.add(0, csm.getNULLCodePosition()); - cmm.parsePositions("modifiers", positionProperties); - cmm.choices.add(0, cmm.getNULLCodePosition()); - - CodeStatus cstatus = new CodeStatus(); - cstatus.parsePositions("status", positionProperties); - cstatus.choices.add(0, cstatus.getNULLCodePosition()); - - CodeOrderOfBattle coob = new CodeOrderOfBattle(); - coob.parsePositions("oob", positionProperties); - coob.choices.add(0, coob.getNULLCodePosition()); - - List basicOptions = new LinkedList<>(); - basicOptions.add(ca); - basicOptions.add(cstatus); - basicOptions.add(cwm); - basicOptions.add(csm); - basicOptions.add(cmm); - // basicOptions.add(cc); - basicOptions.add(coob); - setCodeOptions(new CodeOptions(basicOptions)); - - List warfightingOptions = new LinkedList<>(); - warfightingOptions.add(ca); - warfightingOptions.add(cstatus); - warfightingOptions.add(cwm); - // warfightingOptions.add(cc); // CodeCountry - warfightingOptions.add(coob); - // Kind of a hack, I know the number is the hierarchy number - // of the particular scheme, and that the position.properties - // file is setting up the options to reflect that for all of - // these code option settings. - ((CodeScheme) cs.getFromChoices(1)).setCodeOptions(new CodeOptions(warfightingOptions)); - // ((CodeScheme)getFromChoices(1)).setCodeOptions(new - // CodeOptions(warfightingOptions)); - - List tacOptions = new LinkedList<>(); - tacOptions.add(ca); - tacOptions.add(cstatus); - tacOptions.add(csm); - // tacOptions.add(cc); // CodeCountry - ((CodeScheme) cs.getFromChoices(2)).setCodeOptions(new CodeOptions(tacOptions)); - // ((CodeScheme)getFromChoices(2)).setCodeOptions(new - // CodeOptions(tacOptions)); - - List intelOptions = new LinkedList<>(); - intelOptions.add(ca); - intelOptions.add(cstatus); - // intelOptions.add(cc); // CodeCountry - intelOptions.add(coob); - ((CodeScheme) cs.getFromChoices(4)).setCodeOptions(new CodeOptions(intelOptions)); - // ((CodeScheme)getFromChoices(4)).setCodeOptions(new - // CodeOptions(intelOptions)); - - List mootwOptions = new LinkedList<>(); - mootwOptions.add(ca); - mootwOptions.add(cstatus); - mootwOptions.add(cmm); - // mootwOptions.add(cc); // CodeCountry - mootwOptions.add(coob); - ((CodeScheme) cs.getFromChoices(5)).setCodeOptions(new CodeOptions(mootwOptions)); - // ((CodeScheme)getFromChoices(5)).setCodeOptions(new - // CodeOptions(mootwOptions)); - } - - public SymbolPart parseHierarchy(String name, Properties hierarchyProperties) { - List positions = getPositionChoices(); - - SymbolPartTree head = new SymbolPartTree(name); - List subs = new LinkedList<>(); - head.setSubs(subs); - - for (CodePosition cp : positions) { - if (cp instanceof CodeScheme) { - CodeScheme cs = (CodeScheme) cp; - - if (Debug.debugging("symbolpart")) { - Debug.output("CodePositionTree: loading " + cs.getPrettyName()); - } - - SymbolPart sp = cs.parseHierarchy(hierarchyProperties, head); - if (sp != null) { - subs.add(sp); - } - } - } - - return head; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeScheme.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeScheme.java deleted file mode 100644 index fca97fba2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeScheme.java +++ /dev/null @@ -1,271 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeScheme.java,v $ -// $RCSfile: CodeScheme.java,v $ -// $Revision: 1.9 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The CodeScheme represents the options presented in the first - * character of the 15 character symbol code. This character - * represents the scheme, or symbology set, of the top-most branches - * of the MIL-STD-2525B symbol tree. The layout and meaning of the 15 - * characters depend on the scheme, and the CodeScheme can figure out - * some of them when it parses the position properties to see what - * other CodePositions are fundamental for a particular instance of a - * CodeScheme. There are other CodePositions that present choices for - * a particular scheme type, and the CodeScheme needs to be told what - * those options are. The CodePositionTree handles setting up the - * CodeScheme with its optional CodePositions. - */ -public class CodeScheme extends CodePosition { - - /** - * The base 15 character code for a symbol under a scheme. This - * code has wild-cards and unused charaters in them where - * appropriate for the scheme. - */ - protected String defaultSymbolCode = SymbolPart.DEFAULT_SYMBOL_CODE; - /** - * For parsing the hierarchy, most schemes have some characters - * added to their hierarchy index number. This can be specified in - * the position properties. - */ - protected String hierarchyAddition; - - /** - * Property keyword for the default symbol code - * 'defaultSymbolCode'. - */ - public final static String DefaultSymbolCodeProperty = "defaultSymbolCode"; - - /** - * Property keyword for the hierarchy addition string - * 'hierarchyCodeAddition'. - */ - public final static String HierarchyCodeAdditionProperty = "hierarchyCodeAddition"; - - public CodeScheme() { - super("Scheme", 1, 1); - } - - /** - * The method needs more information from the properties than the - * CodePosition version of this method provides, like getting the - * base symbol code for the scheme and the hierarchy addition. - */ - public CodePosition addPositionChoice(int index, String entry, - String prefix, Properties props) { - - CodeScheme cs = (CodeScheme) super.addPositionChoice(index, - entry, - prefix, - props); - prefix = PropUtils.getScopedPropertyPrefix(prefix) + entry + "."; - - String next = props.getProperty(prefix + NextProperty); - - if (next != null) { - String nextClassName = props.getProperty(next + ".class"); - if (nextClassName != null) { - CodePosition cp = (CodePosition) ComponentFactory.create(nextClassName); - if (DEBUG) { - Debug.output("CodeScheme created next class(" + next - + "), " + nextClassName); - } - if (cp != null) { - cs.nextPosition = cp; - cp.parsePositions(next, props); - } - } else { - if (DEBUG) { - Debug.output("CodeScheme couldn't create next class(" - + next + "), " + nextClassName); - } - } - } - - cs.defaultSymbolCode = props.getProperty(prefix - + DefaultSymbolCodeProperty); - cs.hierarchyAddition = props.getProperty(prefix - + HierarchyCodeAdditionProperty, ""); - // Don't need to add to choices, already done in super class - // method. - return cs; - } - - /** - * Parse the hierarchy properties to create SymbolParts for those - * parts under a particular scheme represented by this instance of - * CodeScheme. - * - * @param props the hierarchy properties. - * @param parent the SymbolPart parent that the new SymbolPart - * tree falls under. - */ - public SymbolPart parseHierarchy(Properties props, SymbolPart parent) { - String hCode = getHierarchyNumber() + hierarchyAddition; - String entry = props.getProperty(hCode); - SymbolPart sp = null; - - if (entry != null) { - sp = new SymbolPart(this, entry, props, parent); - parseHierarchy(hCode, props, sp); - } - - return sp; - } - - /** - * Parse the hierarchy properties to create SymbolParts for those - * parts under a particular scheme represented by this instance of - * CodeScheme. - * - * @param hCode the hierarchy code of this scheme, used to grow - * the tree for subsequent generations. - * @param props the hierarchy properties. - * @param parent the SymbolPart parent that the new SymbolPart - * tree falls under. - */ - public void parseHierarchy(String hCode, Properties props, SymbolPart parent) { - - List codePositionList = null; - - if (nextPosition != null) { - codePositionList = nextPosition.getPositionChoices(); - } - - if (codePositionList == null || codePositionList.isEmpty()) { - Debug.output(prettyName - + ".parseHierarchy(): codePositionList.size = 0"); - return; - } - - List parentList = null; - - for (CodePosition cp : codePositionList) { - - String newHCode = hCode + "." + cp.getHierarchyNumber(); - if (DEBUG) { - Debug.output("CodeScheme.parse: " + newHCode + " with " - + cp.getPrettyName()); - } - - String entry = props.getProperty(newHCode); - if (entry != null) { - SymbolPart sp = new SymbolPart(cp, entry, props, parent); - - if (parentList == null) { - parentList = parent.getSubs(); - if (parentList == null) { - parentList = new ArrayList<>(); - parent.setSubs(parentList); - } - } - - if (DEBUG) { - Debug.output("CodeScheme.parse: adding " - + sp.getPrettyName() + " to " - + parent.getPrettyName()); - } - - parentList.add(sp); - - if (DEBUG) { - Debug.output("CodeScheme.parse: handling " - + cp.getPrettyName() + " children for " - + sp.getPrettyName()); - } - - cp.parseHierarchy(newHCode, props, sp); - - } else { - if (DEBUG) { - Debug.output("CodeScheme.parse: no entry found for " - + newHCode); - } - } - } - } - - /** - * Return the default 15 character symbol code for this instance - * of a scheme. Pretty much all of the symbols below this node in - * the SymbolPart tree will have the same base code, with their - * parameters written on top of it. - */ - public StringBuffer getDefaultSymbolCode() { - return new StringBuffer(defaultSymbolCode); - } - - /** - * A set of CodePostitions that can be set with on this scheme. - * It's different from the choices, which is a list of - * instantiated CodePositions for a particular CodePosition. The - * options are a set of CodePositions, containing choices. For - * instance, for a warfighing code scheme, there would be code - * positions for affiliation, status, order of battle and - * modifiers. The metoc code scheme wouldn't have options. Each - * CodePosition returned in the options can represent a setting - * for the position (its choices will be null), or can represent a - * suite of choices if there is a list of other CodePositions in - * its choices parameter. - */ - protected CodeOptions options; - - /** - * Set the code options for this scheme. - */ - public void setCodeOptions(CodeOptions co) { - options = co; - } - - /** - * Get the code options set for this scheme. - */ - public CodeOptions getCodeOptions() { - return options; - } - - /** - * Get the code options for the scheme as it relates to the symbol - * part. The symbol part may have some restrictions set on it by - * having one of the option CodePositions set within it. If that's - * the case, then the CodeOptions returned will have the - * CodePosition object for that aspect of the symbol represented - * by a CodePosition object without choices. - */ - public CodeOptions getCodeOptions(SymbolPart sp) { - // Check with the symbol part first to see of there are any - // options for the particular positions established and - // limiting for the particular symbol, and then substitute - // defaults for any other positions. - - return options; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeSizeModifier.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeSizeModifier.java deleted file mode 100644 index b8ff94d61..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeSizeModifier.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeSizeModifier.java,v $ -// $RCSfile: CodeSizeModifier.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.Properties; - -import com.bbn.openmap.util.PropUtils; - -/** - * The CodeSizeModifier is a CodeModifier for the tactical graphics - * scheme set, for code symbol positions 11 and 12. - */ -public class CodeSizeModifier extends CodePosition { - - public CodeSizeModifier() { - super("Echelon/Size", 11, 12); - } - - /** - * The CodeSizeModifier is more particular. It wants the first 14 - * code in modifers.properties, and then the last one. - */ - protected void parsePositions(String prefix, Properties props) { - String entry = null; - prefix = PropUtils.getScopedPropertyPrefix(prefix); - for (int index = 1; index > 0 && index < 15; index++) { - entry = props.getProperty(prefix + Integer.toString(index)); - if (entry != null) { - addPositionChoice(index, entry, prefix, props); - } else { - index = -1; - } - } - - // HACK I know that 'K-' is at 128 in the modifiers.properties - // file. - entry = props.getProperty(prefix + "128"); - if (entry != null) { - addPositionChoice(128, entry, prefix, props); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeStatus.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeStatus.java deleted file mode 100644 index 98a72d82b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeStatus.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeStatus.java,v $ -// $RCSfile: CodeStatus.java,v $ -// $Revision: 1.7 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The CodeStatus CodePosition is used to mark and anticipated or - * planned object, or one that is currently present. It is used on - * position 4 in the symbol code. - */ -public class CodeStatus extends CodePosition { - - public CodeStatus() { - super("Status", 4, 4); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeWarfightingModifier.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeWarfightingModifier.java deleted file mode 100644 index 0a2fa0ad2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/CodeWarfightingModifier.java +++ /dev/null @@ -1,59 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/CodeWarfightingModifier.java,v $ -// $RCSfile: CodeWarfightingModifier.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.util.Properties; - -import com.bbn.openmap.util.PropUtils; - -/** - * The CodeWarfightingModifier CodePosition defines different - * modifiers used for symbols in the warfighting scheme. It is used in - * position 11 and 12 of the symbol code. - */ -public class CodeWarfightingModifier extends CodePosition { - - public CodeWarfightingModifier() { - super("Modifier", 11, 12); - } - - /** - * Starts looking for property 1, creates SymbolParts until the - * numbers run out. If there are limits to what properties should - * be read, this method should be overriden. - */ - public void parsePositions(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - for (int index = 1; index > 0 && index < 128; index++) { - String entry = props.getProperty(prefix + Integer.toString(index)); - - if (entry != null) { - addPositionChoice(index, entry, prefix, props); - } else { - index = -1; - } - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/GIFSymbolImageMaker.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/GIFSymbolImageMaker.java deleted file mode 100644 index e5c721665..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/GIFSymbolImageMaker.java +++ /dev/null @@ -1,43 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GIFSymbolImageMaker.java,v $ -//$Revision: 1.4 $ -//$Date: 2005/02/11 22:39:43 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - - -public class GIFSymbolImageMaker extends BasicSymbolImageMaker { - - /** - * - */ - public GIFSymbolImageMaker() {} - - public GIFSymbolImageMaker(String dataPath) { - super(dataPath); - } - - public String getFileExtension() { - return ".gif"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/PNGSymbolImageMaker.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/PNGSymbolImageMaker.java deleted file mode 100644 index 77c2caf6d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/PNGSymbolImageMaker.java +++ /dev/null @@ -1,43 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: PNGSymbolImageMaker.java,v $ -//$Revision: 1.1 $ -//$Date: 2005/02/11 22:39:43 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - - -public class PNGSymbolImageMaker extends BasicSymbolImageMaker { - - /** - * - */ - public PNGSymbolImageMaker() {} - - public PNGSymbolImageMaker(String dataPath) { - super(dataPath); - } - - public String getFileExtension() { - return ".png"; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSourceFileReorganizer.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSourceFileReorganizer.java deleted file mode 100644 index 692f1d3ee..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSourceFileReorganizer.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/ChangeCase.java,v $ -// $RCSfile: ChangeCase.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.io.File; -import java.io.IOException; - -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.wanderer.Wanderer; -import com.bbn.openmap.util.wanderer.WandererCallback; - -/** - * SVGSourceFileReorganizer is a simple utility that takes the source SVG files - * from the DISA package and reorganizes them into a simplier file structure - * that OpenMap classes can use. DISA has extraneous characters at the front of - * the svg file names (a number for which symbol in a particular directory and a - * period) and they are organized in a named directory structure. This wanderer - * finds all of the svg files, chops off the first two characters and places - * them in a target directory. - * - * If you want to convert the files to raster formats (gif, png) use the batik rasterizer: - * - *

- * 
- * java -jar batik-rasterizer.jar FILES
- * 
- * 
- * - * Otherwise, to use this class: - * - *
- * 
- *  Usage: java com.bbn.openmap.tools.symbology.milStd2525.SVGSourceFileReorganizer -target targetDir -source (dir path 1)(dir path 2) ...
- * 
- * 
- */ -public class SVGSourceFileReorganizer - extends Wanderer - implements WandererCallback { - - File rootDir; - boolean verbose = false; - - public SVGSourceFileReorganizer(File rootDir) { - super(); - this.rootDir = rootDir; - this.rootDir.mkdirs(); - setExhaustiveSearch(true); - setTopToBottom(false); - setCallback(this); - } - - public void setVerbose(boolean val) { - verbose = val; - } - - public boolean getVerbose() { - return verbose; - } - - public boolean handleFile(File file) { - - String fileName = file.getName(); - if (!fileName.endsWith(".svg")) { - return true; - } - - String newFileName = fileName.substring(2); - - File target = new File(rootDir, newFileName); - try { - if (verbose) { - System.out.println("copying " + file + " to " + target); - - if (target.exists()) { - System.out.println("++++ overwriting " + target); - } - } - - FileUtils.copy(file, target, 2500); - } catch (IOException ioe) { - if (verbose) { - System.out.println("Problem copying " + file + " to " + target); - } - } - - return true; - } - - /** - * Given a set of files or directories, organize SVG files. - * - * @param argv paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - Debug.init(); - - ArgParser ap = new ArgParser("SVGSourceFileReorganizer"); - ap.add("source", "The directory to search for source svg files.", ArgParser.TO_END); - ap.add("target", "The target directory to place gathered and modified files.", 1); - ap.add("verbose", "Talk alot."); - - if (argv.length == 0) { - ap.bail("", true); - } - - ap.parse(argv); - - String[] sourceDirs; - sourceDirs = ap.getArgValues("source"); - if (sourceDirs == null) { - ap.bail("Need source directories", true); - } - - String[] targetDirs; - targetDirs = ap.getArgValues("target"); - if (targetDirs == null || targetDirs.length > 1) { - ap.bail("Need target directory", true); - } - - boolean verbose = false; - String[] verboseTest = ap.getArgValues("verbose"); - if (verboseTest != null) { - verbose = true; - } - - if (targetDirs != null && sourceDirs != null) { - SVGSourceFileReorganizer cc = new SVGSourceFileReorganizer(new File(targetDirs[0])); - cc.setVerbose(verbose); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < sourceDirs.length; i++) { - cc.handleEntry(new File(sourceDirs[i])); - } - } - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.util.wanderer.WandererCallback#handleDirectory(java.io - * .File) - */ - public boolean handleDirectory(File directory) { - return true; // Continue wandering - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSymbolImageMaker.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSymbolImageMaker.java deleted file mode 100644 index 4e2609fd2..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SVGSymbolImageMaker.java +++ /dev/null @@ -1,87 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: SVGSymbolImageMaker.java,v $ -//$Revision: 1.5 $ -//$Date: 2005/02/11 22:17:38 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.Dimension; -import java.io.IOException; -import java.net.URL; - -import javax.swing.ImageIcon; - -import org.apache.batik.transcoder.TranscoderException; - -import com.bbn.openmap.image.SVGRasterizer; -import com.bbn.openmap.util.Debug; - -public class SVGSymbolImageMaker extends BasicSymbolImageMaker { - - protected SVGRasterizer rasterizer; - - /** - * - */ - public SVGSymbolImageMaker() { - this(""); - } - - public SVGSymbolImageMaker(String dataPath) { - rasterizer = new SVGRasterizer(); - this.dataPath = (dataPath != null ? dataPath : ""); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.tools.symbology.milStd2525.SymbolImageMaker#getIcon(java.lang.String, - * java.awt.Dimension) - */ - public ImageIcon getIcon(String code, Dimension di) { - - try { - URL fileURL = getFileURL(code); - if (Debug.debugging("symbology")) { - Debug.output("SVGSymbolImageMaker: Trying to create " + fileURL); - } - rasterizer = new SVGRasterizer(fileURL); - return new ImageIcon(rasterizer.createBufferedImage(di)); - } catch (TranscoderException e) { - Debug.output("FYI (exception handled):"); - e.printStackTrace(); - } catch (IOException e) { - Debug.output("FYI (exception handled):"); - e.printStackTrace(); - } catch (NullPointerException npe) { - if (Debug.debugging("symbology")) { - Debug.output("SVGSymbolImageMaker: didn't find data for image"); - npe.printStackTrace(); - } - } - return null; - } - - public String getFileExtension() { - return ".svg"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolChooser.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolChooser.java deleted file mode 100644 index 510aba1a5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolChooser.java +++ /dev/null @@ -1,959 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/SymbolChooser.java,v $ -// $RCSfile: SymbolChooser.java,v $ -// $Revision: 1.16 $ -// $Date: 2006/11/14 22:44:08 $ -// $Author: kratkiew $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.HeadlessException; -import java.awt.Insets; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.Serializable; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.UIManager; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import com.bbn.openmap.gui.DimensionQueryPanel; -import com.bbn.openmap.image.AcmeGifFormatter; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.image.ImageFormatter; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PaletteHelper; - -/** - * The SymbolChooser is a GUI symbol builder. It can be used in stand-alone mode - * to create image files, or be integrated into a java application to create - * ImageIcons. - *

- * To bring up this chooser, run this class as a stand-alone application, or call - * showDialog(..) - */ -public class SymbolChooser extends JPanel implements ActionListener { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public final static String CREATE_IMAGE_CMD = "CREATE_IMAGE_CMD"; - public final static String NAMEFIELD_CMD = "NAMEFIELD_CMD"; - public final static String EMPTY_FEATURE_LIST = null; - public final static int DEFAULT_ICON_DIMENSION = 100; - public final static String EMPTY_CODE = "---------------"; - - protected static ImageIcon DEFAULT_SYMBOL_IMAGE; - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - protected ImageIcon symbolImage; - protected DefaultMutableTreeNode currentSymbol = null; - protected SymbolTreeHolder currentSymbolTreeHolder; - protected SymbolReferenceLibrary library; - protected List trees; - protected DimensionQueryPanel dqp; - - protected JButton clearFeaturesButton; - protected JButton createImageFileButton; - protected JTextField nameField; - protected JLabel symbolImageLabel; - protected JScrollPane treeView; - protected JPanel optionPanel; - protected Dimension iconDimension; - protected boolean allowCreateImage = true; - - public SymbolChooser(SymbolReferenceLibrary srl) { - - library = srl; - - try { - trees = createNodes(srl); - } catch (FormatException fe) { - Debug.output("SymbolChooser(): Caught FormatException reading data: " - + fe.getMessage()); - } - - init(srl, trees); - } - - /** - * Update the GUI with the contents of the provided SymbolTreeHolder, - * reflecting a new set of symbols. - * - * @param sth - */ - public void setSelectedTreeHolder(SymbolTreeHolder sth) { - treeView.setViewportView(sth.getTree()); - optionPanel.removeAll(); - optionPanel.add(sth.getOptionPanel()); - sth.handleNodeSelection((DefaultMutableTreeNode) sth.tree.getLastSelectedPathComponent()); - - revalidate(); - } - - /** - * Convenience function to get a standard blank image for those SymbolParts - * that are not found by the SymbolImageMaker. - * - * @return DEFAULT_SYMBOL_IMAGE - */ - public static ImageIcon getNotFoundImageIcon() { - if (DEFAULT_SYMBOL_IMAGE == null) { - BufferedImage bi = new BufferedImage(DEFAULT_ICON_DIMENSION, DEFAULT_ICON_DIMENSION, BufferedImage.TYPE_INT_RGB); - Graphics g = bi.getGraphics(); - g.setColor(Color.LIGHT_GRAY); - g.fillRect(0, 0, DEFAULT_ICON_DIMENSION, DEFAULT_ICON_DIMENSION); - DEFAULT_SYMBOL_IMAGE = new ImageIcon(bi); - } - return DEFAULT_SYMBOL_IMAGE; - } - - /** - * Create the GUI based on the contents of the SymbolReferenceLibrary and - * the SymbolPartTrees created from the options. - * - * @param srl - * @param trees - */ - protected void init(SymbolReferenceLibrary srl, List trees) { - - // /////////////////// - // Create the tree window by creating the scroll pane and add - // the tree to it. - GridBagLayout outergridbag = new GridBagLayout(); - GridBagConstraints outerc = new GridBagConstraints(); - - JPanel setChoicePanel = new JPanel(); - JLabel setChoiceLabel = new JLabel("Symbol Set:"); - JComboBox setChoices = new JComboBox<>(trees.toArray(new SymbolTreeHolder[trees.size()])); - setChoices.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - @SuppressWarnings("unchecked") - JComboBox jcb = (JComboBox) e.getSource(); - setSelectedTreeHolder((SymbolTreeHolder) jcb.getSelectedItem()); - } - }); - - currentSymbolTreeHolder = (SymbolTreeHolder) setChoices.getSelectedItem(); - - setChoicePanel.add(setChoiceLabel); - setChoicePanel.add(setChoices); - - treeView = new JScrollPane(currentSymbolTreeHolder.getTree()); - setLayout(outergridbag); - - outerc.fill = GridBagConstraints.BOTH; - outerc.gridwidth = GridBagConstraints.REMAINDER; - outerc.weighty = 0.0; - outerc.insets = new Insets(5, 10, 5, 10); - outergridbag.setConstraints(setChoicePanel, outerc); - add(setChoicePanel); - - outerc.weightx = 1.0; - outerc.weighty = 1.0; - outerc.gridwidth = GridBagConstraints.RELATIVE; - outergridbag.setConstraints(treeView, outerc); - add(treeView); - - // Add the symbol preview area to the right of the tree - JPanel symbolPanel = PaletteHelper.createVerticalPanel(" Current Symbol "); - setImageIcon(getNotFoundImageIcon()); - symbolPanel.add(symbolImageLabel); - - outerc.weightx = 0.0; - outerc.gridwidth = GridBagConstraints.REMAINDER; - outergridbag.setConstraints(symbolPanel, outerc); - - dqp = new DimensionQueryPanel(getDesiredIconDimension()); - outergridbag.setConstraints(dqp, outerc); - symbolPanel.add(dqp); - - add(symbolPanel); - - // /////////////////// - - optionPanel = PaletteHelper.createVerticalPanel(" Symbol Attributes "); - optionPanel.add(((SymbolTreeHolder) setChoices.getSelectedItem()).getOptionPanel()); - outergridbag.setConstraints(optionPanel, outerc); - add(optionPanel); - - // /////////////////// - // gridbag2 is for the name panel and the recent symbols. - GridBagLayout gridbag2 = new GridBagLayout(); - GridBagConstraints c2 = new GridBagConstraints(); - JPanel namePanel = new JPanel(); - namePanel.setLayout(gridbag2); - - c2.weightx = 0; - c2.anchor = GridBagConstraints.WEST; - JLabel nameLabel = new JLabel("Symbol Code: "); - gridbag2.setConstraints(nameLabel, c2); - namePanel.add(nameLabel); - - c2.fill = GridBagConstraints.HORIZONTAL; - c2.weightx = 1.0; - if (nameField == null) { - nameField = new JTextField(EMPTY_CODE); - } - nameField.addActionListener(this); - nameField.setActionCommand(NAMEFIELD_CMD); - gridbag2.setConstraints(nameField, c2); - namePanel.add(nameField); - - createImageFileButton = new JButton("Create Image File"); - createImageFileButton.addActionListener(this); - createImageFileButton.setActionCommand(CREATE_IMAGE_CMD); - createImageFileButton.setEnabled(false); - createImageFileButton.setVisible(allowCreateImage); - - c2.weightx = 0.0; - gridbag2.setConstraints(createImageFileButton, c2); - namePanel.add(createImageFileButton); - - outerc.weighty = 0.0; - outerc.gridwidth = GridBagConstraints.REMAINDER; - outergridbag.setConstraints(namePanel, outerc); - add(namePanel); - // /////////////////// - // Just call this to make sure that the stuff in the name - // field matches the selected JTree - setSelectedTreeHolder(currentSymbolTreeHolder); - } - - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - - if (command == CREATE_IMAGE_CMD && library != null && nameField != null) { - try { - setDesiredIconDimension(dqp.getDimension()); - } catch (NumberFormatException e) { - JOptionPane.showMessageDialog(this, - "Width and height must be integers.", - "Warning", - JOptionPane.WARNING_MESSAGE); - return; - } - Dimension d = getDesiredIconDimension(); - ImageIcon ii = library.getIcon(getCode(), d); - - if (ii == null) { - createImageFileButton.setEnabled(false); - return; - } - - try { - BufferedImage bi = BufferedImageHelper.getBufferedImage(ii.getImage(), - 0, - 0, - (int) d.getWidth(), - (int) d.getHeight(), - BufferedImage.TYPE_INT_ARGB); - ImageFormatter formatter = new AcmeGifFormatter(); - byte[] imageBytes = formatter.formatImage(bi); - String newFileName = FileUtils.getFilePathToSaveFromUser("Create File To Save"); - if (newFileName != null) { - FileOutputStream fos = new FileOutputStream(newFileName); - fos.write(imageBytes); - fos.flush(); - fos.close(); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - if (command == NAMEFIELD_CMD) { - handleManualNameFieldUpdate(getCode()); - } - - } - - /** - * Update the GUI to react to code typed into the string window. - * - * @param text - */ - protected void handleManualNameFieldUpdate(String text) { - if (text == null) - return; - if (text.length() > 15) { - text = text.substring(0, 15); - } - text = text.toUpperCase().replace('*', '-'); - - for (SymbolTreeHolder sth : trees) { - - if (sth != null) { - DefaultMutableTreeNode node = sth.getNodeForCode(text); - if (node != null) { - if (Debug.debugging("symbology")) { - Debug.output("SymbolChooser: Found node for " + text); - } - sth.getTree() - .setSelectionPath(new TreePath(node.getPath())); - sth.updateOptionsForCode(text); - setSelectedTreeHolder(sth); - } - } - } - } - - /** - * Initialization method to create the SymbolTreeHolders from the - * SymbolReferenceLibrary. - * - * @param srl - * @return List of nodes of the symbol part tree. - * @throws FormatException - */ - protected List createNodes(SymbolReferenceLibrary srl) - throws FormatException { - - List treeList = new LinkedList<>(); - List subs = srl.getHead().getSubs(); - int count = 1; - if (subs != null) { - for (SymbolPart schemeSymbolPart : subs) { - CodeOptions options = ((CodeScheme) srl.positionTree.getFromChoices(count++)).getCodeOptions(null); - treeList.add(new SymbolTreeHolder(schemeSymbolPart, options)); - } - } - - return treeList; - } - - /** - * Get the current symbol code listed in the GUI. - * - * @return code for current symbol. - */ - public String getCode() { - if (nameField != null) - return nameField.getText(); - return EMPTY_CODE; - } - - /** - * Set the symbol code in the GUI. - */ - public void setCode(String code) { - if (nameField == null) { - // If we do this here, the default jtree presented - // will be able to put it's default symbol code in the - // text field widget. Has to be done before that - // default JTree is made. - nameField = new JTextField(code); - } else { - nameField.setText(code); - } - } - - /** - * Get the icon displayed in the GUI. - * - * @return ImageIcon being displayed. - */ - public ImageIcon getImageIcon() { - return symbolImage; - } - - /** - * Set the current icon in the display. - * - * @param ii - */ - public void setImageIcon(ImageIcon ii) { - symbolImage = ii; - - if (symbolImageLabel == null) { - symbolImageLabel = new JLabel(symbolImage); - } else { - symbolImageLabel.setIcon(symbolImage); - } - } - - /** - * Set the dimension o the icon to be created. - * - * @param d - */ - public void setDesiredIconDimension(Dimension d) { - iconDimension = d; - - dqp.setDimension(getDesiredIconDimension()); - } - - /** - * @return the dimension of the icon to be created. - */ - public Dimension getDesiredIconDimension() { - if (iconDimension == null) { - iconDimension = new Dimension(DEFAULT_ICON_DIMENSION, DEFAULT_ICON_DIMENSION); - } - return iconDimension; - } - - /** - * @return Returns the allowCreateImage. - */ - public boolean isAllowCreateImage() { - return allowCreateImage; - } - - /** - * @param allowCreateImage The allowCreateImage to set. - */ - public void setAllowCreateImage(boolean allowCreateImage) { - this.allowCreateImage = allowCreateImage; - if (createImageFileButton != null) { - createImageFileButton.setVisible(allowCreateImage); - } - } - - public static ImageIcon showDialog(Component component, String title, - SymbolReferenceLibrary srl, - String defaultSymbolCode) - throws HeadlessException { - - final SymbolChooser pane = new SymbolChooser(srl); - - SymbolTracker ok = new SymbolTracker(pane); - JDialog dialog = createDialog(component, title, true, pane, ok, null); - dialog.addWindowListener(new SymbolChooserDialog.Closer()); - dialog.addComponentListener(new SymbolChooserDialog.DisposeOnClose()); - pane.setCode(defaultSymbolCode); - pane.handleManualNameFieldUpdate(defaultSymbolCode); - dialog.setVisible(true); // blocks until user brings dialog down... - - return ok.getImageIcon(); - } - - /** - * Creates JDialog window displaying a SymbolChooser. - */ - public static JDialog createDialog(Component c, String title, - boolean modal, - SymbolChooser chooserPane, - ActionListener okListener, - ActionListener cancelListener) - throws HeadlessException { - - return new SymbolChooserDialog(c, title, modal, chooserPane, okListener, cancelListener); - } - - public static void main(String[] args) { - Debug.init(); - - ArgParser ap = new ArgParser("SymbolChooser"); - ap.add("type", - "Type of symbol image set being used (PNG, GIF or SVG, PNG is default)", - 1); - ap.add("path", - "Path to root directory of symbol image set if not in classpath", - 1); - ap.add("default", "15 character code for default icon", 1); - ap.add("verbose", "Print messages"); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String arg[]; - arg = ap.getArgValues("type"); - String symbolImageMakerClass = "com.bbn.openmap.tools.symbology.milStd2525.PNGSymbolImageMaker"; - if (arg != null) { - if (arg[0].equalsIgnoreCase("SVG")) { - symbolImageMakerClass = "com.bbn.openmap.tools.symbology.milStd2525.SVGSymbolImageMaker"; - } else if (arg[0].equalsIgnoreCase("GIF")) { - symbolImageMakerClass = "com.bbn.openmap.tools.symbology.milStd2525.GIFSymbolImageMaker"; - } - } - - String defaultSymbolCode = "SFPPV-----*****"; - arg = ap.getArgValues("default"); - if (arg != null) { - defaultSymbolCode = arg[0]; - } - - arg = ap.getArgValues("verbose"); - if (arg != null) { - Debug.put("symbology"); - } - - SymbolReferenceLibrary srl = new SymbolReferenceLibrary(); - if (srl.setSymbolImageMaker(symbolImageMakerClass) != null) { - - arg = ap.getArgValues("path"); - if (arg != null) { - srl.getSymbolImageMaker().setDataPath(arg[0]); - } - - SymbolChooser.showDialog(null, - "MIL-STD-2525B Symbol Chooser", - srl, - defaultSymbolCode); - } else { - Debug.output("Couldn't create SymbolImageMaker"); - } - - System.exit(0); - } - - public class SymbolTreeHolder /*extends ListenerSupport*/ implements - TreeSelectionListener { - - // Optionally play with line styles. Possible values are - // "Angled", "Horizontal", and "None" (the default). - protected boolean playWithTreeLineStyle = false; - protected String treeLineStyle = "Angled"; - - protected JTree tree; - protected JPanel optionPanel; - protected CodeOptions options; - protected Character[] optionChars = new Character[15]; - protected Hashtable> optionMenuHashtable; - protected SymbolPart symbolPart; - - public SymbolTreeHolder(SymbolPart schemeSymbolPart, CodeOptions opts) { - this.symbolPart = schemeSymbolPart; - DefaultMutableTreeNode top = new DefaultMutableTreeNode(schemeSymbolPart); - addNodes(top, schemeSymbolPart); - - tree = new JTree(top); - tree.getSelectionModel() - .setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setVisibleRowCount(10); - tree.addTreeSelectionListener(this); - tree.setSelectionPath(new TreePath(top)); - - if (playWithTreeLineStyle) { - tree.putClientProperty("JTree.lineStyle", treeLineStyle); - } - - options = opts; - optionPanel = getOptionPanel(); - } - - public JTree getTree() { - return tree; - } - - protected void addNodes(DefaultMutableTreeNode node, SymbolPart sp) { - - DefaultMutableTreeNode newNode = null; - List subs = sp.getSubs(); - if (subs != null) { - for (SymbolPart symPart : subs) { - newNode = new DefaultMutableTreeNode(symPart); - node.add(newNode); - addNodes(newNode, symPart); - } - } - } - - public DefaultMutableTreeNode getNodeForCode(String code) { - - DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel() - .getRoot(); - - SymbolPart sp = (SymbolPart) root.getUserObject(); - - if (Debug.debugging("symbology.detail")) { - Debug.output("Tree root object has " + sp.getClass().getName() - + " user object with code |" + sp.getCode() - + "| at code position " - + sp.getCodePosition().startIndex); - } - - if (sp.codeMatches(code)) { - return getNodeForCodeStartingAt(root, code); - } else { - return null; - } - } - - protected DefaultMutableTreeNode getNodeForCodeStartingAt( - DefaultMutableTreeNode node, - String code) { - @SuppressWarnings("rawtypes") - Enumeration enumeration = node.children(); - while (enumeration.hasMoreElements()) { - DefaultMutableTreeNode kid = (DefaultMutableTreeNode) enumeration.nextElement(); - SymbolPart ssp = (SymbolPart) kid.getUserObject(); - - try { - if (code.charAt(ssp.getCodePosition().startIndex) == '-') - return node; - - if (ssp.codeMatches(code)) { - return getNodeForCodeStartingAt(kid, code); - } - } catch (StringIndexOutOfBoundsException sioobe) { - } catch (NullPointerException npe) { - } - } - - return node; - } - - /** - * Given an text string, have the options available to the current - * SymbolTreeHolder reflect those updates. - * - * @param text - */ - protected void updateOptionsForCode(String text) { - for (CodePosition cp : options.getOptions()) { - JComboBox jcb = optionMenuHashtable.get(cp); - if (jcb != null) { - int numComps = jcb.getItemCount(); - for (int i = 0; i < numComps; i++) { - if (jcb.getItemAt(i).codeMatches(text)) { - jcb.setSelectedIndex(i); - break; - } - } - } - } - } - - public void valueChanged(TreeSelectionEvent e) { - handleNodeSelection((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); - } - - public void updateInterfaceToLastSelectedNode() { - handleNodeSelection((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); - } - - public void handleNodeSelection(DefaultMutableTreeNode node) { - - if (node == null) { - setCode(""); - return; - } - - Object nodeInfo = node.getUserObject(); - if (nodeInfo instanceof SymbolPart) { - SymbolPart symbolPart = (SymbolPart) nodeInfo; - currentSymbol = node; - setCode(updateStringWithCurrentOptionChars(symbolPart.getSymbolCode())); - ImageIcon ii = library.getIcon(getCode(), - new Dimension(DEFAULT_ICON_DIMENSION, DEFAULT_ICON_DIMENSION)); - if (createImageFileButton != null) { - createImageFileButton.setEnabled(ii != null); - } - - if (ii == null) { - ii = getNotFoundImageIcon(); - } - setImageIcon(ii); - } else { - setCode(""); - setImageIcon(getNotFoundImageIcon()); - createImageFileButton.setEnabled(false); - } - } - - public JPanel getOptionPanel() { - if (optionPanel == null) { - optionMenuHashtable = new Hashtable> (); - optionPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - optionPanel.setLayout(gridbag); - - if (options != null) { - int i = 0; - for (CodePosition cp : options.getOptions()) { - - List lt = cp.getPositionChoices(); - - if (lt != null) { - JLabel label = new JLabel(cp.getPrettyName() + ": "); - - c.gridx = 0; - c.gridy = i++; - c.weightx = 0; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.EAST; - - gridbag.setConstraints(label, c); - optionPanel.add(label); - - JComboBox jcb = new JComboBox<>(lt.toArray(new CodePosition[lt.size()])); - jcb.addActionListener(new ActionListener() { - @SuppressWarnings("rawtypes") - public void actionPerformed(ActionEvent ae) { - setPositionSetting((CodePosition) ((JComboBox) ae.getSource()).getSelectedItem()); - updateInterfaceToLastSelectedNode(); - } - }); - - c.gridx = 1; - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - - gridbag.setConstraints(jcb, c); - optionPanel.add(jcb); - optionMenuHashtable.put(cp, jcb); - } - } - } else { - optionPanel.add(new JLabel("No options available for these symbols.")); - } - - } - return optionPanel; - } - - public void setPositionSetting(CodePosition cp) { - if (Debug.debugging("codeposition")) { - Debug.output("Setting " + cp.getPrettyName() + " [" - + cp.getID() + "] at " + cp.getStartIndex() + ", " - + cp.getEndIndex()); - } - updateOptionChars(cp); - setCode(updateStringWithCurrentOptionChars(getCode())); - } - - public void updateOptionChars(CodePosition cp) { - String cpString = cp.getID(); - for (int i = 0; i < cpString.length(); i++) { - char curChar = cpString.charAt(i); - optionChars[cp.getStartIndex() + i] = new Character(curChar); - } - } - - public String updateStringWithCurrentOptionChars( - String currentSymbolCode) { - try { - StringBuffer buf = new StringBuffer(currentSymbolCode); - for (int i = 0; i < optionChars.length; i++) { - Character c = optionChars[i]; - if (c != null) { - buf.setCharAt(i, c.charValue()); - } - - } - currentSymbolCode = buf.toString(); - } catch (StringIndexOutOfBoundsException siobe) { - } catch (NullPointerException npe) { - } - return currentSymbolCode; - } - - public String toString() { - return symbolPart.getCodePosition().getPrettyName(); - } - - } - -} - -/* - * Class which builds a symbol chooser dialog consisting of a SymbolChooser with - * "Ok", "Cancel", and "Reset" buttons. This class is based on the contents of - * the JColorChooser components. - */ - -class SymbolChooserDialog extends JDialog { - /** - * - */ - private static final long serialVersionUID = 1L; - private String initialCode; - private SymbolChooser chooserPane; - - public SymbolChooserDialog(Component c, String title, boolean modal, - SymbolChooser chooserPane, ActionListener okListener, - ActionListener cancelListener) throws HeadlessException { - - super(JOptionPane.getFrameForComponent(c), title, modal); - this.chooserPane = chooserPane; - - String okString = UIManager.getString("ColorChooser.okText"); - String cancelString = UIManager.getString("ColorChooser.cancelText"); - String resetString = UIManager.getString("ColorChooser.resetText"); - - Container contentPane = getContentPane(); - contentPane.setLayout(new BorderLayout()); - contentPane.add(chooserPane, BorderLayout.CENTER); - - /* - * Create Lower button panel - */ - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); - JButton okButton = new JButton(okString); - getRootPane().setDefaultButton(okButton); - okButton.setActionCommand("OK"); - if (okListener != null) { - okButton.addActionListener(okListener); - } - okButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - setVisible(false); - } - }); - buttonPane.add(okButton); - - JButton cancelButton = new JButton(cancelString); - - cancelButton.setActionCommand("cancel"); - if (cancelListener != null) { - cancelButton.addActionListener(cancelListener); - } - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - setVisible(false); - } - }); - buttonPane.add(cancelButton); - - JButton resetButton = new JButton(resetString); - resetButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - reset(); - } - }); - - buttonPane.add(resetButton); - contentPane.add(buttonPane, BorderLayout.SOUTH); - - applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation()); - - pack(); - setLocationRelativeTo(c); - } - - public void setVisible(boolean val) { - if (val) { - initialCode = chooserPane.getCode(); - } - super.setVisible(val); - } - - public void reset() { - chooserPane.setCode(initialCode); - chooserPane.handleManualNameFieldUpdate(initialCode); - } - - static class Closer extends WindowAdapter implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - public void windowClosing(WindowEvent e) { - Window w = e.getWindow(); - w.setVisible(false); - } - } - - static class DisposeOnClose extends ComponentAdapter implements - Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - public void componentHidden(ComponentEvent e) { - Window w = (Window) e.getComponent(); - w.dispose(); - } - } - -} - -class SymbolTracker implements ActionListener, Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - SymbolChooser chooser; - ImageIcon icon; - - public SymbolTracker(SymbolChooser c) { - chooser = c; - } - - public void actionPerformed(ActionEvent e) { - // This is subject to too many timing problems, it's easier if we just get the icon - // when asked in getImageIcon. - - // icon = chooser.library.getIcon(chooser.getCode(), - // chooser.getDesiredIconDimension()); - } - - public ImageIcon getImageIcon() { - try { - return chooser.library.getIcon(chooser.getCode(), - chooser.getDesiredIconDimension()); - } catch (NullPointerException npe) { - Debug.error("SymbolChooser.SymbolTracker: something messed up with chooser:"); - npe.printStackTrace(); - } - return null; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolImageMaker.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolImageMaker.java deleted file mode 100644 index 0e7688199..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolImageMaker.java +++ /dev/null @@ -1,43 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: SymbolImageMaker.java,v $ -//$Revision: 1.2 $ -//$Date: 2004/12/10 14:17:11 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.Dimension; -import java.awt.Paint; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.PropertyConsumer; - -public interface SymbolImageMaker extends PropertyConsumer { - public final static String BackgroundPaintProperty = "background"; - public final static String DataPathProperty = "path"; - - public ImageIcon getIcon(String code, Dimension di); - - public void setDataPath(String dataPath); - - public void setBackground(Paint p); -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPart.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPart.java deleted file mode 100644 index eff816618..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPart.java +++ /dev/null @@ -1,413 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/SymbolPart.java,v $ -// $RCSfile: SymbolPart.java,v $ -// $Revision: 1.12 $ -// $Date: 2005/08/11 20:39:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.dataAccess.cgm.CGM; -import com.bbn.openmap.util.Debug; - -/** - * The SymbolPart class represents one part in a hierarchy of pieces - * needed to represent an actual symbol. A symbol may require - * geometries from its parents, as each piece further down the - * hierarchy makes each symbol's meaning more specific, or scoped for - * a particular task. The top-level SymbolPart represents the entire - * symbology tree. Descending down through the tree, a SymbolPart - * representing one of the 5 Scheme sections is next, with the lower - * levels dependent on the Scheme definitions. - *

- * - * The SymbolPart is smart enough to use the hierarchy.properties file - * that defines the symbol set and create the symbol tree using the - * appropriate Code classes. Not all Code classes help define the - * tree, because some aspects of a symbol are flexible, like the - * Affiliation (enemy, friend, etc). The SymbolPart tree only defines - * some aspects of the symbol. Other parts of the symbol are dependent - * on these flexible variations that are provided to the SymbolPart at - * the time icons are created. - */ -public class SymbolPart { - - public final static String DEFAULT_SYMBOL_CODE = " "; - - /** Property file property for pretty name 'name' */ - public final static String NameProperty = "name"; - /** Property file property for cgm file too represent the symbol. */ - public final static String CGMProperty = "cgm"; - - /** - * The Object that describes the location of this symbol part in - * the symbol hierarchy as defined by the 15 digit symbol code. - */ - protected CodePosition codePosition; - /** - * The part of the symbol code unique to this symbol part. Parents - * and children will make up the other parts of the code. - */ - protected String code; - /** - * The pretty name for a symbol represented by this SymbolPart at - * this point in the hierarchy. - */ - protected String prettyName; - /** - * The file containing the symbol geometry for this SymbolPart. - */ - protected String cgmName; - /** - * The symbol geometry object for this SymbolPart. - */ - protected CGM cgm; - /** - * A list of children SymbolParts relative to this one. - */ - protected List subs; - /** - * The parent SymbolPart to this one. - */ - protected SymbolPart parent; - /** - * Some positions need to shift for entries that don't follow the - * conventions on the specification. - */ - protected int positionShift = 0; - - protected static boolean DEBUG = false; - - public final static char UNUSED = '-'; - public final static char WILD = '*'; - - protected SymbolPart() { - DEBUG = Debug.debugging("symbolpart"); - } - - /** - * The most-used constructor, used by CodePosition objects to - * create the different levels of the SymbolPart tree. The - * SymbolPart uses the parameters and the Properties to define its - * name and get the cgm file holding the geometry for the symbol. - * This constructor focuses on the Scheme, Dimension and - * FunctionID symbol parts. - * - * @param codePosition CodePosition object that corresponds to the - * SymbolPart. CodePosition object with lower position - * numbers tend to define more general symbols. - * @param symbolCode the 15 character symbol string that defines - * this SymbolPart. This string is associated with a - * hierarchy number in the Properties. - * @param props the Properties object contains all the information - * about the symbol tree. - * @param parent the SymbolPart that is above this one in the - * SymbolPart tree. - */ - public SymbolPart(CodePosition codePosition, String symbolCode, - Properties props, SymbolPart parent) { - this(codePosition, - symbolCode, - props, - parent, - codePosition.getStartIndex(), - codePosition.getEndIndex(), - true); - } - - /** - * A different constructor used by OptionPositions. The SymbolPart - * uses the parameters and the Properties to define its name and - * get the cgm file holding the geometry for the symbol. This - * constructor focuses on the Scheme, Dimension and FunctionID - * symbol parts. - * - * @param codePosition CodePosition object that corresponds to the - * SymbolPart. CodePosition object with lower position - * numbers tend to define more general symbols. - * @param symbolCode the 15 character symbol string that defines - * this SymbolPart. This string is associated with a - * hierarchy number in the Properties. - * @param props the Properties object contains all the information - * about the symbol tree. - * @param parent the SymbolPart that is above this one in the - * SymbolPart tree. - */ - public SymbolPart(CodePosition codePosition, String symbolCode, - Properties props, SymbolPart parent, int start, int end, - boolean shiftIfNecessary) { - - this.code = symbolCode.substring(start, end); - this.codePosition = codePosition; - - // For OptionPositions, we need to have a version where the - // start and end aren't used for parsing, because the - // properties are especially designed for them. We just need - // the indexes for placement into the symbol code later. The - // new code just needs to read symbolCode from the beginning - // for the length between the indexes. - - boolean debug = DEBUG; - - // This corrects the situation where the symbol code is - // shorter in the specification than it would seem - // appropriate for its place in the hierarchy. - while (code.charAt(0) == UNUSED && start > 1 && shiftIfNecessary) { - code = symbolCode.substring(--start, end); - this.positionShift--; - } - - this.prettyName = props.getProperty(symbolCode + "." + NameProperty); - this.cgmName = props.getProperty(symbolCode + "." + CGMProperty); - this.parent = parent; - - String sc = getSymbolCode(); - - if (Debug.debugging("errors") && !symbolCode.equals(sc)) { - debug = true; - } - - if (debug) { - Debug.output("SymbolPart(" + codePosition.getPrettyName() - + "): read " + start + " of [" + symbolCode + "] as [" + sc - + "] : " + this.prettyName + " (" + code + ")"); - } - } - - /** - * Sets the part of the SymbolCode that is unique to this - * SymbolPart. - */ - public void setCode(String c) { - code = c; - } - - /** - * Gets the part of the SymbolCode that is unique to this - * SymbolPart. - */ - public String getCode() { - return code; - } - - /** - * Sets the descriptive name if this SymbolPart. - */ - public void setPrettyName(String pn) { - prettyName = pn; - } - - /** - * Sets the descriptive name if this SymbolPart. - */ - public String getPrettyName() { - return prettyName; - } - - /** - * Sets the SymbolPart's parent in the SymbolPart tree. - */ - public void setParent(SymbolPart par) { - parent = par; - } - - /** - * Retrieves the SymbolPart's parent in the SymbolPart tree. - */ - public SymbolPart getParent() { - return parent; - } - - /** - * Sets a list of SymbolPart tree for more specific - * representations of what this SymbolPart represents. - */ - public void setSubs(List set) { - subs = set; - } - - /** - * Gets a list of SymbolPart tree for more specific - * representations of what this SymbolPart represents. - */ - public List getSubs() { - return subs; - } - - /** - * Get a simple string representation of this SymbolPart, - * including the 15 digit code and the pretty name. - */ - public String toString() { - // return " [" + getSymbolCode() + "] " + prettyName; - return prettyName; - } - - /** - * A method used by the tree to provide a string representation of - * how all the SymbolParts are connected. - */ - public String getDescription(int level) { - StringBuffer sb = new StringBuffer(); - String indicator = "|--> "; - if (level > 0) { - sb.append(indicator); - } - - List subs = getSubs(); - int subSize = 0; - if (subs != null) { - subSize = subs.size(); - } - - sb.append(toString()); - if (subSize > 0) { - sb.append(" with ").append(subSize).append(" subcategor" - ).append((subSize == 1 ? "y\n" : "ies\n")); - } else { - sb.append("\n"); - } - - if (subs != null) { - synchronized (this) { - StringBuffer sb1 = new StringBuffer(); - - for (int i = 0; i < level; i++) { - sb1.append(" "); - } - - String spacer = sb1.toString(); - - for (SymbolPart sp : subs) { - sb.append(spacer).append(sp.getDescription(level + 1)); - } - } - } - - return sb.toString(); - } - - /** - * The starting command for retrieving the description with this - * SymbolPart being the top of the tree. - */ - public String getDescription() { - return getDescription(0); - } - - /** - * Retrieves the 15 character symbol code for this SymbolPart. - * Calling this method will cause the SymbolPart to ask all of - * it's parents to contribute their part of the code as well. - */ - public String getSymbolCode() { - return getSymbolCode(null).toString(); - } - - /** - * A 15 character string of spaces, where spaces won't overwrite - * the current character when this symbol writes to a - * getSymbolCode() string. - */ - public StringBuffer getSymbolCodeMask() { - return new StringBuffer(DEFAULT_SYMBOL_CODE); - } - - /** - * A SymbolPart tree method that gets the SymbolPart's parents - * contribution for the symbol code. - */ - protected StringBuffer getSymbolCode(StringBuffer symbolCode) { - - if (codePosition instanceof CodeScheme) { - symbolCode = ((CodeScheme) codePosition).getDefaultSymbolCode(); - } else if (parent != null) { - symbolCode = parent.getSymbolCode(symbolCode); - } else { - symbolCode = getSymbolCodeMask(); - } - - if (codePosition != null) { - int key = codePosition.getStartIndex() + positionShift; - symbolCode = symbolCode.replace(key, - codePosition.getEndIndex(), - code); - } - - return symbolCode; - } - - public CodePosition getCodePosition() { - return codePosition; - } - - public CodeOptions getCodeOptions() { - CodeScheme cs = getCodeScheme(); - if (cs != null) { - return cs.getCodeOptions(this); - } else { - return null; - } - } - - public CodeScheme getCodeScheme() { - CodeScheme cs = null; - if (codePosition instanceof CodeScheme) { - cs = (CodeScheme) codePosition; - } else if (parent != null) { - cs = parent.getCodeScheme(); - } - return cs; - } - - /** - * A query method that answers if the given 15 digit code applies - * to this symbol part. - * - * @param queryCode - * @return true if the code applies to this position. - */ - public boolean codeMatches(String queryCode) { - if (codePosition != null && code != null) { - int startIndex = codePosition.startIndex; - int length = code.indexOf('-'); - if (length == -1) { - length = code.length(); - } - - if (Debug.debugging("symbology.detail")) { - Debug.output("Checking " + queryCode + " against |" + code - + "| starting at " + startIndex + " for " + length); - } - return queryCode.regionMatches(true, startIndex, code, 0, length); - } - - // Nothing set, must be the head and we want a match. - return true; - } - - public void paintIcon(Graphics2D g, CodeOptions co, Dimension di) { - - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPartTree.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPartTree.java deleted file mode 100644 index 4e2fc771a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolPartTree.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/SymbolPartTree.java,v $ -// $RCSfile: SymbolPartTree.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -/** - * The SymbolPartTree is a SymbolPart that serves as the top node of - * the SymbolPart tree. - */ -public class SymbolPartTree extends SymbolPart { - - public SymbolPartTree(String name) { - prettyName = name; - } - - /** - * Get a simple string representation of this SymbolPart, - * including the 15 digit code and the pretty name. - */ - public String toString() { - return "[" + prettyName + "] Symbol Set"; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolReferenceLibrary.java b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolReferenceLibrary.java deleted file mode 100644 index bbe1bf65f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/SymbolReferenceLibrary.java +++ /dev/null @@ -1,310 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/symbology/milStd2525/SymbolReferenceLibrary.java,v $ -// $RCSfile: SymbolReferenceLibrary.java,v $ -// $Revision: 1.12 $ -// $Date: 2005/08/11 20:39:17 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.symbology.milStd2525; - -import java.awt.Dimension; -import java.net.URL; -import java.util.List; -import java.util.Properties; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The SymbolReferenceLibrary is a organizational class for creating - * and managing a SymbolPart tree. It can handle requests for decoding - * a Symbol code and providing a SymbolPart for that code, and can - * fetch ImageIcons for codes and SymbolParts. This is the class you - * can put in the MapHandler for other components to use in order to - * create symbols. The DemoLayer, for instance, uses the - * MapHandler.findAndInit() method to find it and create a space - * shuttle icon. - *

- * - * This SymbolReferenceLibrary has one property that lets you specify - * the SymbolImageMaker it should use to create image icons. - * - *

- *  
- *   
- *   symbolreferencelibrary.class=com.bbn.openmap.tools.symbology.milStd2525.SymbolReferenceLibrary
- *   
- *   # properties to use for GIF image data files
- *   symbolreferencelibrary.imageMakerClass=com.bbn.openmap.tools.symbology.milStd2525.GIFSymbolImageMaker
- *   # optional property used as a path to the parent of the data files if it's not in the classpath.
- *   symbolreferencelibrary.path=<path to image data file directory>
- *   # optional background color for icons if you want something other than clear.
- *   symbolreferencelibrary.background=AAGGRRBB
- *   
- *   # properties to use for SVG image data files obtained from DISA.  You need to have Batik jars in 
- *   # your classpath to use the SVG files, as well as the omsvg.jar file
- *   symbolreferencelibrary.imageMakerClass=com.bbn.openmap.tools.symbology.milStd2525.SVGSymbolImageMaker
- *   # optional property used as a path to the parent of the data files if it's not in the classpath.
- *   symbolreferencelibrary.path=<path to image data file directory>
- *   # optional background color for icons if you want something other than clear.
- *   symbolreferencelibrary.background=AAGGRRBB
- *  
- * 
- */ -public class SymbolReferenceLibrary extends OMComponent { - - public final static String SymbolImageMakerClassProperty = "imageMakerClass"; - - protected SymbolPart head; - protected CodePositionTree positionTree; - protected static SymbolReferenceLibrary library = null; - protected CodeOptions symbolAttributes; - protected SymbolImageMaker symbolImageMaker; - - /** - * A constructor used when the SymbolImageMaker will be set later, - * either via the setProperties method or programmatically. - */ - public SymbolReferenceLibrary() { - this(null); - } - - /** - * Create a SymbolReferenceLibrary with a SymbolImageMaker to use - * to create images from a data source. It's expected that the - * SymbolImageMaker is ready to go, configured to create images - * given a code. The SRL will use the hierarchy.properties file - * found as a resource as the reference for the symbol hierarchy. - * - * @param sim - */ - public SymbolReferenceLibrary(SymbolImageMaker sim) { - Properties props = findAndLoadProperties("hierarchy.properties"); - if (props != null) { - initialize(props, sim); - } - } - - public Properties findAndLoadProperties(String propertiesResource) { - try { - URL url = PropUtils.getResourceOrFileOrURL(SymbolReferenceLibrary.class, - propertiesResource); - Properties props = new Properties(); - props.load(url.openStream()); - return props; - } catch (java.net.MalformedURLException murle) { - Debug.output("SymbolReferenceLibrary has malformed path to " - + propertiesResource); - } catch (java.io.IOException ioe) { - Debug.output("SymbolReferenceLibrary I/O exception reading " - + propertiesResource); - } - return null; - } - - protected void initialize(Properties props, SymbolImageMaker sim) { - symbolImageMaker = sim; - - if (Debug.debugging("symbology")) { - Debug.output("SRL: loading"); - } - - Properties positionProperties = findAndLoadProperties("positions.properties"); - if (positionProperties != null) { - positionTree = new CodePositionTree(positionProperties); - head = positionTree.parseHierarchy("MIL-STD-2525B Symbology", props); - } - - if (Debug.debugging("symbology")) { - Debug.output("SRL: initialized"); - } - - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - String symbolImageMakerClassString = props.getProperty(realPrefix - + SymbolImageMakerClassProperty); - if (symbolImageMakerClassString != null) { - symbolImageMaker = setSymbolImageMaker(symbolImageMakerClassString); - if (symbolImageMaker != null) { - symbolImageMaker.setProperties(prefix, props); - } - } - } - - public SymbolImageMaker setSymbolImageMaker(String classname) { - try { - setSymbolImageMaker((SymbolImageMaker) Class.forName(classname) - .newInstance()); - return getSymbolImageMaker(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - public CodeOptions getCodeOptions() { - if (positionTree != null) { - return positionTree.getCodeOptions(null); - } - return null; - } - - /** - * Given a SymbolPart, return what options are available for it. - * This depends on what scheme the SymbolPart inherits from. Not - * implemented. - * - * @param sp The SymbolPart in question. - * @param co Current settings that may be in use. - */ - public CodeOptions getCodeOptions(SymbolPart sp, CodeOptions co) { - return null; - } - - /** - * Return an image given a SymbolCode and dimension. - */ - public ImageIcon getIcon(String symbolCode, Dimension di) { - if (Debug.debugging("symbology")) { - Debug.output("SymbolReferenceLibrary asked to create: " - + symbolCode + " at " + di); - } - if (symbolImageMaker != null) { - return symbolImageMaker.getIcon(symbolCode, di); - } - return null; - } - - /** - * Return an image for a particular SymbolPart, its options and - * dimensions. Not implemented. - */ - public ImageIcon getIcon(SymbolPart sp, CodeOptions co, Dimension di) { - return null; - } - - /** - * Return the 15 character character string representing a - * SymbolPart with CodeOptions. Not implemented. - */ - public String getSymbolCode(SymbolPart sp, CodeOptions co) { - return null; - } - - /** - * The SymbolParts in the library are stored in a tree hierarchy, - * and this method gets the top level one representing the - * MIL-STD-2525 tree. - */ - public SymbolPart getHead() { - return head; - } - - /** - * Returns a huge, multi-line string listing all of the symbols, - * their names and their relation to each other. - */ - public String getDescription() { - String description = null; - if (head != null) { - description = head.getDescription(); - } - return description; - } - - /** - * Check to see if code exists, if it's valid. If you get a - * SymbolPart back from this query, then you can call getIcon. - * - * @param code - * @return SymbolPart for the 15 character code of a symbol. - */ - public SymbolPart getSymbolPartForCode(String code) { - - if (Debug.debugging("symbology.detail")) { - Debug.output("SymbolReferenceLibrary checking for " + code - + " in SymbolPart tree."); - } - - if (head.codeMatches(code)) { - return getSymbolPartForCodeStartingAt(head, code); - } else { - return null; - } - } - - protected SymbolPart getSymbolPartForCodeStartingAt(SymbolPart node, - String code) { - List sublist = node.getSubs(); - - if (sublist == null || sublist.isEmpty()) { - // Last on the line of the tree, this is the closest match... - return node; - } - - for (SymbolPart ssp : sublist) { - - try { - char ch = code.charAt(ssp.getCodePosition().startIndex); - if (ch == '-' || ch == '*') - return node; - - if (ssp.codeMatches(code)) { - return getSymbolPartForCodeStartingAt(ssp, code); - } - } catch (StringIndexOutOfBoundsException sioobe) { - } catch (NullPointerException npe) { - } - } - - return node; - } - - public static void main(String[] argv) { - Debug.init(); - Debug.put("codeposition"); - SymbolReferenceLibrary srl = new SymbolReferenceLibrary(); - Debug.output(srl.getDescription()); - } - - /** - * @return Returns the symbolImageMaker. - */ - public SymbolImageMaker getSymbolImageMaker() { - return symbolImageMaker; - } - - /** - * @param symbolImageMaker The symbolImageMaker to set. - */ - public void setSymbolImageMaker(SymbolImageMaker symbolImageMaker) { - this.symbolImageMaker = symbolImageMaker; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/package.html b/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/package.html deleted file mode 100644 index a4852efa9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/symbology/milStd2525/package.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -This package provides a way to create MIL-STD-2525B compliant symbols. -The SymbolChooser class provides a GUI to selecting icons, and can be -run in standalone mode to figure out a symbol code to use for the -SymbolReferenceLibrary.

- -The SymbolReferenceLibrary is the main class to use to create images, -though. It parses the hierarchy.properties file to create the -symbology tree, and parses the positions.properties file to create a -different tree for understanding the significance of different -positions in the symbol code. The SymbolReferenceLibrary use -SymbolImageMakers to create the icon based on a symbol code.

- -Not all symbols have been implemented, we hope to add to them over -time. The SymbolChooser lets you wander through the tree to find the -icon that suites your need. We're including a set of 100x100 pixel -GIF icons that can be used with the GIFSymbolImageMaker. DISA makes a set of SVG -files that can also be used by people who meet their distribution -criteria. You'll need the Batik package -(http://xml.apache.org/batik) jar files in your classpath to be able -to use these files, in addition to the omsvg.jar file from the -OpenMap package. In addition, the DISA symbol files come in a large -directory tree, and for use with the OpenMap code, they need to be -reorganized so that all of the .svg files are in one directory or in -the top level of a jar file. The SVGSymbolImageMaker can be used -with those .svg files. - - diff --git a/src/core/src/main/java/com/bbn/openmap/tools/terrain/LOSGenerator.java b/src/core/src/main/java/com/bbn/openmap/tools/terrain/LOSGenerator.java deleted file mode 100644 index c7d289f61..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/terrain/LOSGenerator.java +++ /dev/null @@ -1,246 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/terrain/LOSGenerator.java,v $ -// $RCSfile: LOSGenerator.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:10 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.terrain; - -import java.awt.Color; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.dted.DTEDFrameCache; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Planet; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.MoreMath; - -/** - * A Class that can do Line-Of-Sight calculations between two points. Uses the - * DTEDFrameCache to get elevations. - */ -public class LOSGenerator { - - // These are used to control the algorithm type. Right now, the - // first two are eliminated, since the azimuth algorithm is - // faster - // and more precise. - final static int PRECISE = 0; - final static int GOODENOUGH = 1; - final static int AZIMUTH = 2; - - // The colors of pixels - final static int DEFAULT_INVISIBLE = new Color(0, 0, 0, 0).getRGB(); - final static int DEFAULT_VISIBLE = new Color(0, 255, 0, 255).getRGB(); - final static int DEFAULT_MAYBEVISIBLE = new Color(255, 255, 0, 255).getRGB(); - - protected int INVISIBLE = DEFAULT_INVISIBLE; - protected int VISIBLE = DEFAULT_VISIBLE; - protected int MAYBEVISIBLE = DEFAULT_MAYBEVISIBLE; - - DTEDFrameCache dtedCache = null; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.tools.terrain.LOSGenerator"); - - /** - * Not the preferred way to create one of these. It's full of defaults. - */ - public LOSGenerator() { - } - - public LOSGenerator(DTEDFrameCache cache) { - setDtedCache(cache); - } - - public void setDtedCache(DTEDFrameCache cache) { - dtedCache = cache; - } - - public DTEDFrameCache getDtedCache() { - return dtedCache; - } - - /** - * Check to see if two points are within line of sight of each other, taking - * into account their elevations above Mean Sea Level as retrieved by a DTED - * database, and any other addition height of each object. - * - * @param startLLP location of point 1. - * @param startObjHeight the elevation of point 1 above the surface, in - * meters. The surface elevation of the point will be looked up and - * added to this value. - * @param addStartElevation true if startObjHeight also needs DTED lookup - * added to it. - * @param endLLP location of point 2. - * @param endObjHeight the elevation of point 2 above the surface, in - * meters. The surface elevation of the point will be looked up and - * added to this value. - * @param numPoints number of sample points to check between the two end - * points. Can be dependent on the Projection of the current map, and - * based on the number of pixels between the projected points. Could - * also be based on the number of elevation posts between the two - * points in the DTED database. - * @return true of their is a line-of-sight path between the two points. - */ - public boolean isLOS(LatLonPoint startLLP, int startObjHeight, boolean addStartElevation, - LatLonPoint endLLP, int endObjHeight, int numPoints) { - - boolean ret = false; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LOSGenerator.isLOS: " + startLLP + " at height:" + startObjHeight + ", " - + endLLP + " at height:" + endObjHeight + ", numPoints = " + numPoints); - } - - if (dtedCache == null) { - return ret; - } - - int startTotalHeight = startObjHeight - + (addStartElevation ? dtedCache.getElevation((float) startLLP.getLatitude(), (float) startLLP.getLongitude()) - : 0); - - double[] llpoints = GreatCircle.greatCircle(startLLP.getRadLat(), startLLP.getRadLon(), endLLP.getRadLat(), endLLP.getRadLon(), numPoints, true); - LatLonPoint llp = new LatLonPoint.Double(); - int gcPointListSize = llpoints.length; - double smallestSlopeValue = -Math.PI; - // Start at a couple of points away from origin - for (int i = 4; i < gcPointListSize; i += 2) { - llp.setLatLon(llpoints[i], llpoints[i + 1], true); - int heightAboveGround = 0; - // Only add height to end point - if (i >= gcPointListSize - 2) { - heightAboveGround = endObjHeight; - } - double slopeOfCurrentPoint = calculateLOSSlope(startLLP, startTotalHeight, llp, heightAboveGround); - - // if the slope is smaller than the max slope yet seen, it is - // visible. - if (slopeOfCurrentPoint > smallestSlopeValue) { - smallestSlopeValue = slopeOfCurrentPoint; - ret = true; - - // If the last point has the largest slope, then the - // point is LOS. - } else { - ret = false; - } - - if (logger.isLoggable(Level.FINER)) { - logger.finer(" LOS:" + (i / 2) + " - slope = " - + Length.DECIMAL_DEGREE.fromRadians(slopeOfCurrentPoint) - + " at height of point: " + heightAboveGround + (ret ? " *" : " -")); - } - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LOSGenerator - points " + (ret ? "" : " NOT ") + " in LOS"); - } - - return ret; - } - - /** - * CalculateLOSslope figures out the slope from one point to another. The - * arc_dist is in radians, and is the radian arc distance of the point from - * the center point of the image, on the earth. This slope calculation does - * take the earth's curvature into account, based on the spherical model. - * The slope returned is the angle from the end point to the beginning - * point, relative to the vertical of the end point to the center of the - * earth - i.e. starting at the axis pointing straight down into the earth, - * how many radians do you have to angle up until you hit the starting - * point. The DTED elevation of the end point is gathered from the dted - * cache. - * - * @param startLLP the coordinates of point 1. - * @param startTotalHeight the total height of point 1, from the Mean Sea - * Level - so it's the elevation of the point plus altitude above the - * surface, in meters. - * @param endLLP the coordinates of point 2. - * @param endObjHeight the elevation of point 2 above the surface, in - * meters. The surface elevation of the point will be looked up and - * added to this value. - * @return slope of line between the two points, with zero pointing straight - * down, in radians. - */ - public double calculateLOSSlope(LatLonPoint startLLP, int startTotalHeight, LatLonPoint endLLP, - int endObjHeight) { - - if (dtedCache == null) { - return 0; - } - - double arc_dist = startLLP.distance(endLLP); - - int endTotalHeight = endObjHeight - + dtedCache.getElevation(endLLP.getLatitude(), endLLP.getLongitude()); - return calculateLOSSlope(startTotalHeight, endTotalHeight, arc_dist); - } - - /** - * Calculate the slope of a line between two points across a spherical model - * of the earth. A slope of zero is pointing to the sky from the starting - * point. 90 degrees is perpendicular from that start point vector, which - * would be the slope of two points next to each other of the same height. - * Any angle greater than than and you're rolling downhill. - * - * @param startTotalHeight total height of one point, in meters. Should - * represent elevation of point which is the surface elevation above - * MSL, and the height above the surface. - * @param endTotalHeight total height of one the other point, in meters. - * Should represent elevation of point which is the surface elevation - * above MSL, and the height above the surface. - * @param arc_dist the surface angle, in radians, across the spherical model - * of the earth that separates the two points. - */ - public static double calculateLOSSlope(int startTotalHeight, int endTotalHeight, double arc_dist) { - double ret = 0; - double P = Math.sin(arc_dist) * (endTotalHeight + Planet.wgs84_earthEquatorialRadiusMeters); - - double xPrime = Math.cos(arc_dist) - * (endTotalHeight + Planet.wgs84_earthEquatorialRadiusMeters); - - double cutoff = startTotalHeight + Planet.wgs84_earthEquatorialRadiusMeters; - - // Suggested changes, submitted by Mark Wigmore. Introduces - // use of doubles, and avoidance of PI/2 tan() calculations. - - double bottom = cutoff - xPrime; - ret = MoreMath.HALF_PI_D - Math.atan(bottom / P); - return ret; - } - - // public static void main(String[] args) { - // - // float dist = Length.FEET.toRadians(1000); - // - // System.out.println("slope = " - // + Length.DECIMAL_DEGREE.fromRadians(LOSGenerator.calculateLOSSlope(10, - // 10, dist))); - // System.out.println("slope = " - // + Length.DECIMAL_DEGREE.fromRadians(LOSGenerator.calculateLOSSlope(5, 10, - // dist))); - // System.out.println("slope = " - // + Length.DECIMAL_DEGREE.fromRadians(LOSGenerator.calculateLOSSlope(15, - // 10, dist))); - // - // } -} diff --git a/src/core/src/main/java/com/bbn/openmap/tools/terrain/package.html b/src/core/src/main/java/com/bbn/openmap/tools/terrain/package.html deleted file mode 100644 index 28db91d1e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/tools/terrain/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -The tools/terrain package is for components that provide services -dealing with terrain (elevation) data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/AbstractXmlParser.java b/src/core/src/main/java/com/bbn/openmap/util/AbstractXmlParser.java deleted file mode 100644 index ac8413d7c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/AbstractXmlParser.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Base class for xml parsing - * - * @author rshapiro - */ -abstract public class AbstractXmlParser - extends DefaultHandler { - private final Logger logger = Logger.getLogger("com.bbn.openmap.util.AbstractXmlParser"); - - private final StringBuilder charactersCollector = new StringBuilder(); - private String collectCharactersForElement; - - /** - * Parse an XML resource by url. Exceptions are logged rather than thrown. If - * an exception occurs the return value will be false to indicate that fact. - * - * @param file The file to parse. - * @return Whether or not the parse succeeded. - */ - public boolean parseXmlResource(File file) { - Reader reader = null; - try { - reader = new BufferedReader(new FileReader(file)); - return parseXmlResource(file.getPath(), new InputSource(reader)); - } catch (FileNotFoundException e) { - logger.warning("Failed to open " + file + ":" + e.getMessage()); - return false; - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // best-effort - } - } - } - } - - /** - * Parse from the given source. The source will not be closed after the - * parse: the caller should do this. - * - * Exceptions are logged rather than thrown. If an exception occurs the - * return value will be false to indicate that fact. - * - * @param resourceName The resource name to use in warning messages. - * @param source The source of the xml input. - * @return Whether or not the parse succeeded. - */ - public boolean parseXmlResource(Object resourceName, InputSource source) { - XMLReader reader; - source.setEncoding("UTF8"); - try { - reader = XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - if (logger.isLoggable(Level.SEVERE)) { - logger.warning("Failed to create reader for " + resourceName + ": " + e.getMessage()); - } - return false; - } - boolean status = false; - reader.setContentHandler(this); - reader.setErrorHandler(this); - try { - reader.parse(source); - status = true; - } catch (SAXParseException e) { - if (logger.isLoggable(Level.WARNING)) { - logger.warning("Failed to parse " + resourceName + " Line: " + e.getLineNumber() + " Col: " + e.getColumnNumber() - + ": " + e); - } - } catch (SAXException e) { - if (logger.isLoggable(Level.WARNING)) { - logger.warning("Failed to parse " + resourceName + e.getMessage()); - } - } catch (IOException e) { - if (logger.isLoggable(Level.WARNING)) { - logger.warning("Failed to parse " + resourceName + ":" + e.getMessage()); - } - } - return status; - } - - /** - * Inform the parser that we want to start gathering up the character data - * for the current element. This would typically be invoked in - * {@link #startElement} with the localName as the parameter. - * - * Use {@link #getCollectedCharacters}, typically in the corresponding - * {@link #endElement}, to retrieve the result. - * - * @param expectedElement The element whose character data we're gathering. - * Caller must pass the same element to - * {@link #getCollectedCharacters} to ensure consistency. - */ - public void collectCharacters(String expectedElement) { - collectCharactersForElement = expectedElement; - } - - /** - * Get the final string accumulated from all invocations of - * {@link #characters} since the last call to {@link #collectCharacters}. - * - * @param expectedElement The element whose character data we're gathering. - * Caller must pass the same element to {@link #collectCharacters} to - * ensure consistency. - * @return The String accumulated from all intervening calls to - * {@link #characters}. - * @throws RuntimeException if the expectedElement doesn't match. - */ - public String getCollectedCharacters(String expectedElement) { - if (expectedElement.equals(collectCharactersForElement)) { - String result = charactersCollector.toString(); - charactersCollector.delete(0, result.length()); - collectCharactersForElement = null; - return result; - } else { - throw new RuntimeException("Expected \"" + expectedElement + "\", found \"" + collectCharactersForElement + "\""); - } - } - - /** - * Handle multiple callbacks per element, which will happen when the data - * includes xml escape sequences. Each escape sequence comes in its own - * callback. - */ - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - if (collectCharactersForElement != null) { - charactersCollector.append(ch, start, length); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/ArgParser.java b/src/core/src/main/java/com/bbn/openmap/util/ArgParser.java deleted file mode 100644 index 85848a286..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/ArgParser.java +++ /dev/null @@ -1,462 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/ArgParser.java,v $ -// $RCSfile: ArgParser.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/08/24 20:17:48 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.util.Vector; - -/** - * A simple class to manage the line arguments of a program. Takes the String[] - * argv that is provided to the main method of a class, and separates them out, - * depending on the options given to the ArgParser. After you create the parser, - * add your options that you want. - */ -public class ArgParser { - /** - * The length to submit if you want a variable length list at the end of the - * command line, like all the arguments left over. - */ - public final static int TO_END = -1; - /** The program name that's using the parser. */ - protected String programName; - /** The Args that the parser is looking for. */ - protected Vector args; - /** The String array that holds all of the leftover argvs. */ - protected String[] rest = new String[0]; - /** The character flag for an option. */ - protected char option = '-'; - /** - * Tells the Args to accept the first letter of their name for argv options - * specified with one letter. - */ - protected boolean allowAbbr = true; - - /** - * Create a parser for the named program. Automatically adds the -help - * option. - * - * @param pName the program name. - */ - public ArgParser(String pName) { - programName = pName; - args = new Vector(); - args.add(new HelpArg()); - } - - /** - * Add a argument to the parser. Don't include the '-' in the argName, - * that's added automatically. Assumes that the option expects no arguments. - * - * @param argName the command line option - * @param desc a help line description. - */ - public void add(String argName, String desc) { - add(argName, desc, 0); - } - - /** - * Add a argument to the parser. Don't include the '-' in the argName, - * that's added automatically. - * - * @param argName the command line option - * @param desc a help line description. - * @param expectedNumberOfArguments the number of option parameters expected - * for this option. - */ - public void add(String argName, String desc, int expectedNumberOfArguments) { - add(argName, desc, expectedNumberOfArguments, false); - } - - /** - * Add a argument to the parser. Don't include the '-' in the argName, - * that's added automatically. - * - * @param argName the command line option - * @param desc a help line description. - * @param expectedNumberOfArguments the number of option parameters expected - * for this option. - * @param expectDashedArguments tell the parser that this option may have - * arguments that may start with dashes, for instance, a negative - * number. False by default. - */ - public void add(String argName, String desc, int expectedNumberOfArguments, boolean expectDashedArguments) { - Arg newArg = new Arg(argName, desc, expectedNumberOfArguments, expectDashedArguments); - args.add(newArg); - if (Debug.debugging("parse")) { - Debug.output("ArgParser: adding " + argName); - } - } - - /** - * Parse and organize the array of Strings. If something goes wrong, bail() - * may be called. - * - * @param argv arguments to be parsed - * @return true if everything goes well, false if not - */ - public boolean parse(String[] argv) { - try { - if (argv == null || argv.length == 0) { - return false; - } - for (int i = 0; i < argv.length; i++) { - boolean hit = false; - if (argv[i].charAt(0) == option) { - String eval = argv[i].substring(1); - for (int j = 0; j < args.size(); j++) { - Arg curArg = (Arg) args.elementAt(j); - if (curArg.is(eval, allowAbbr)) { - if (Debug.debugging("parse")) { - Debug.output("ArgParser: arg " + curArg.name + " reading values."); - } - if (!curArg.readArgs(argv, ++i)) { - // Something's wrong with the - // arguments. - bail("ArgParser: Unexpected arguments with option " + curArg.name + ".", true); - } - hit = true; - if (curArg.numExpectedValues != TO_END) { - i += (curArg.numExpectedValues - 1); - } else { - i = argv.length; - } - } - } - if (hit == false) { - // option flagged, but option unknown. - bail(programName + ": unknown option " + argv[i], false); - } - } - - if (hit == false) { - if (i == 0) { - rest = argv; - } else { - int diff = argv.length - i; - rest = new String[diff]; - for (int k = 0; k < diff; k++) { - rest[k] = argv[i + k]; - if (rest[k].charAt(0) == option) { - bail("ArgParser: Not expecting option in list of arguments.", true); - } - } - } - if (Debug.debugging("parse")) { - Debug.output("ArgParser: adding " + rest.length + " strings to the leftover list."); - } - - return true; - } - } - } catch (ArrayIndexOutOfBoundsException aioobe) { - bail("Expecting more arguments for option", true); - } catch (NegativeArraySizeException nase) { - return false; - } - return true; - } - - /** - * Called if something is messed up. Prints a message, and the usage - * statement, if desired. - * - * @param message a message to display. - * @param printUsageStatement true to display a list of available options - */ - public void bail(String message, boolean printUsageStatement) { - Debug.output(message); - if (printUsageStatement) - printUsage(); - System.exit(0); - } - - /** - * Tell the parser to accept first-letter representations of the options. - * - * @param set true to accept - */ - public void setAllowAbbr(boolean set) { - allowAbbr = set; - } - - /** - * @return true the parser accepts first-letter representations of the - * options - */ - public boolean getAllowAbbr() { - return allowAbbr; - } - - /** - * @return a Vector of Arg objects - */ - public Vector getArgs() { - return args; - } - - /** - * Return a Arg object with a particular name. This method shouldn't be used - * to figure out if values have been passed in to an application. It's to - * find out if an option is available to be chosen, not if it has. - * - * @param name of Arg - * @return Arg with name - */ - public Arg getArg(String name) { - for (int i = 0; i < args.size(); i++) { - ArgParser.Arg arg = (ArgParser.Arg) args.elementAt(i); - if (name.equalsIgnoreCase(arg.name)) { - return arg; - } - } - return null; - } - - /** - * Given an Arg name, return the values. Returns a zero length array - * (non-null) value for options that don't require arguments. Returns null - * if the option name wasn't found in the list, or if the option wasn't - * chosen in the parsed array of Strings. - * - * @param name key string for values - * @return values for name - */ - public String[] getArgValues(String name) { - for (int i = 0; i < args.size(); i++) { - ArgParser.Arg arg = (ArgParser.Arg) args.elementAt(i); - if (name.equalsIgnoreCase(arg.name)) { - if (arg.flagged) { - return arg.values; - } - } - } - return null; - } - - /** - * @return the String[] that makes up the trailing Strings after the options - * were parsed - */ - public String[] getRest() { - return rest; - } - - /** - * Print a list of options added to the parser. - */ - public void printUsage() { - Debug.output(programName + " Arguments:"); - for (int i = 0; i < args.size(); i++) { - ArgParser.Arg arg = (ArgParser.Arg) args.elementAt(i); - StringBuffer sb = new StringBuffer(); - String filler = arg.name.length() < 6 ? "\t\t" : "\t"; - - sb.append(" -").append(arg.name).append(filler).append(arg.description); - if (arg.numExpectedValues == TO_END) { - sb.append(" (Variable number of arguments expected)"); - } else if (arg.numExpectedValues == 1) { - sb.append(" (1 argument expected)"); - } else { - sb.append(" (").append(arg.numExpectedValues).append(" arguments expected)"); - } - Debug.output(sb.toString()); - } - } - - public static void main(String[] argv) { - Debug.init(); - ArgParser ap = new ArgParser("ArgParser"); - ap.add("first", "First test argument, no parameters expected"); - ap.add("second", "Second test argument, two parameters expected", 2); - ap.add("third", "Third test argument, no parameters expected"); - ap.add("fourth", "Fourth test argument, one parameter expected", 1); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - int i; - Vector args = ap.getArgs(); - for (i = 0; i < args.size(); i++) { - ArgParser.Arg a = (ArgParser.Arg) args.elementAt(i); - Debug.output(a.toString()); - } - - String[] rest = ap.getRest(); - Debug.output("Rest:"); - for (i = 0; i < rest.length; i++) { - Debug.output(rest[i]); - } - } - - /** - * A default version of the Arg class used to represent options for the - * ArgParser to use. - */ - public class Arg { - public String name; - public String description; - public int numExpectedValues; - public String[] values = null; - public char c; - public boolean flagged = false; - public boolean dashedArguments = false; - - /** - * Create an Arg with a name and help line description. - * - * @param aName name of arg - * @param desc description of arg, used in usage statement - */ - public Arg(String aName, String desc) { - this(aName, desc, 0); - } - - /** - * Create an Arg with a name and help line description, along with a - * number of expected arguments to follow this option. - * - * @param aName name of arg - * @param desc description of arg, used in usage statement - * @param expectedNumberOfArguments number of values expected for - * argument - */ - public Arg(String aName, String desc, int expectedNumberOfArguments) { - this(aName, desc, expectedNumberOfArguments, false); - } - - /** - * Create an Arg with a name and help line description, along with a - * number of expected arguments to follow this option. Has an argument - * to not check for arguments that may start with dashes, in case one of - * the arguments may be a negative number. - * - * @param aName name of arg - * @param desc description of arg, used in usage statement - * @param expectedNumberOfArguments number of values expected for - * argument - * @param expectDashedArguments if they could be dashed (like a negative - * number) - */ - public Arg(String aName, String desc, int expectedNumberOfArguments, boolean expectDashedArguments) { - name = aName; - description = desc; - numExpectedValues = expectedNumberOfArguments; - c = name.charAt(0); - dashedArguments = expectDashedArguments; - } - - /** - * Returns true if the atg string matches the name of the Arg, or, if - * allowAbbr is true, returns true if the arg length is one and it - * matches the first letter of the arg name. - * - * @param arg string to test - * @param allowAbbr ok to check first letter - * @return true if a match - */ - public boolean is(String arg, boolean allowAbbr) { - if (name.equalsIgnoreCase(arg)) { - return true; - } - - if (allowAbbr && arg.length() == 1) { - if (arg.charAt(0) == c) { - return true; - } - } - return false; - } - - /** - * Runs through the array of Strings, starting at the argIndex, and - * creates the values array from it. Uses the expected number of - * arguments to tell when it's done. Returns true if everything happens - * as expected. - * - * @param argv the entire array passed to the parser. - * @param argIndex the index of the first option argument value. - * @return true if what was read was what was expected. - */ - public boolean readArgs(String[] argv, int argIndex) - throws ArrayIndexOutOfBoundsException, NegativeArraySizeException { - - if (numExpectedValues != TO_END) { - values = new String[numExpectedValues]; - } else { - values = new String[argv.length - argIndex]; - } - - for (int i = 0; i < values.length; i++) { - values[i] = argv[argIndex + i]; - if (values[i].charAt(0) == option && !dashedArguments) { - if (numExpectedValues != TO_END) { - Debug.output("ArgParser: Option " + name + " expects " + numExpectedValues - + (numExpectedValues == 1 ? " argument." : " arguments.")); - - } else { - Debug.output("ArgParser: Option " + name + " not expecting options after its values."); - } - return false; // Unexpected argument. - } - } - flagged = true; - return true; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("Arg: ").append(name).append(" expects ").append(numExpectedValues) - .append((numExpectedValues == 1 ? " value.\n" : " values.\n")); - if (values != null) { - sb.append("Values: "); - for (int i = 0; i < values.length; i++) { - sb.append("[").append(values[i]).append("]"); - } - sb.append("\n"); - } - return sb.toString(); - } - } - - /** - * A Arg class to spur off help messages. Gets added automatically to the - * parser. - */ - public class HelpArg - extends ArgParser.Arg { - - public HelpArg() { - super("help", "Print usage statement, with arguments.", 0); - } - - public boolean is(String arg, boolean allowAbbr) { - boolean askingForHelp = super.is(arg, allowAbbr); - if (askingForHelp) { - ArgParser.this.bail("", true); - } - return false; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/Assert.java b/src/core/src/main/java/com/bbn/openmap/util/Assert.java deleted file mode 100644 index 267bd305f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Assert.java +++ /dev/null @@ -1,105 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/Assert.java,v $ -// $RCSfile: Assert.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * Assert provides an assertion facility in Java comparable to the - * assert macros in C/C++. This class was taken from the Java FAQ - * maintained by Perter Van Der Linden at http://www.afu.com/intro.html - * , section 17, question 6. Here is the original entry in the - * FAQ: - *

- *
- * 
- *  11.6 How can I write C/C++ style assertions in Java?
- * 
- *  A.  The two classes shown below provide an assertion facility in Java.
- *      Set Assert.enabled to true to enable the assertions, and to false to
- *      disable assertions in production code. The AssertionException is not
- *      meant to be caught--instead, let it print a trace.
- * 
- *      With a good optimizing compiler there will be no run time overhead
- *      for many uses of these assertions when Assert.enabled is set to false.
- *      However, if the condition in the assertion may have side effects, the
- *      condition code cannot be optimized away. For example, in the assertion
- *       
- * 
- * Assert.assertExp(size() <= maxSize, "Maximum size exceeded");
- * 
- * 
- *      the call to size() cannot be optimized away unless the compiler can
- *      see that the call has no side effects. C and C++ use the preprocessor
- *      to guarantee that assertions will never cause overhead in production
- *      code. Without a preprocessor, it seems the best we can do in Java is
- *      to write
- *       
- * 
- * Assert.assertExp(Assert.enabled && size() <= maxSize, "Too big");
- * 
- * 
- *      In this case, when Assert.enabled is false, the method call can always
- *      be optimized away, even if it has side effects.
- *  
- * 
- * - * @author Peter Van Der Linden - * @author Maintained by: Tom Mitchell (tmitchell@bbn.com) - * @version $Revision: 1.4 $, $Date: 2004/10/14 18:06:29 $ - */ -public final class Assert { - - /** - * Don't allow construction, all methods are static. - */ - private Assert() {} - - /** - * Globally enable or disable assertions. - */ - public static final boolean enabled = true; - - /** - * Assert a condition to be true. If it is not true, an exception - * is thrown. - * - * @param b An expression expected to be true - * @param s Exception string if expression is false - * @exception AssertionException if expression is false - */ - public static final void assertExp(boolean b, String s) { - if (enabled && !b) - throw new AssertionException(s); - } - - /** - * Assert a condition to be true. If it is not true, an exception - * is thrown. - * - * @param b An expression expected to be true - * @exception AssertionException if expression is false - */ - public static final void assertExp(boolean b) { - assertExp(b, ""); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/AssertionException.java b/src/core/src/main/java/com/bbn/openmap/util/AssertionException.java deleted file mode 100644 index 6760486a0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/AssertionException.java +++ /dev/null @@ -1,50 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/AssertionException.java,v $ -// $RCSfile: AssertionException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:29 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * Signals that an assertion has failed. - * - * @author unascribed - * @version $Revision: 1.3 $, $Date: 2004/10/14 18:06:29 $ - * @see Assert - */ -public class AssertionException extends RuntimeException { - - /** - * Constructs a default AssertionException. - */ - public AssertionException() { - this(""); - } - - /** - * Constructs an AssertionException with the - * specified detail message. - * - * @param s the detail message - */ - public AssertionException(String s) { - super(s); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/Attributable.java b/src/core/src/main/java/com/bbn/openmap/util/Attributable.java deleted file mode 100644 index 102fd9db0..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Attributable.java +++ /dev/null @@ -1,73 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: Attributable.java,v $ -//$Revision: 1.1 $ -//$Date: 2007/08/16 22:15:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.util; - -import java.util.Map; - -/** - * An object that has attributes. - * - * @author dietrick - */ -public interface Attributable { - - /** - * Put an attribute in the object, the value can be retrieved later via the - * key. - * - * @param key attribute key - * @param value attribute value - */ - public void putAttribute(K key, V value); - - /** - * Get the attribute stored under a key. - * - * @param key attribute key - * @return value if found, null if not. - */ - public Object getAttribute(K key); - - /** - * Tells the object to clear all of its attributes. - */ - public void clearAttributes(); - - /** - * Convenience method to allow super class methods access to an attribute - * table if they are acting as a wrapper. - * - * @return Map of all attributes - */ - public Map getAttributes(); - - /** - * Convenience method to allow super class methods access to an attribute - * table if they are acting as a wrapper. - * - * @param map Map of all attributes - */ - public void setAttributes(Map map); -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/BasicI18n.java b/src/core/src/main/java/com/bbn/openmap/util/BasicI18n.java deleted file mode 100644 index 7a342ef12..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/BasicI18n.java +++ /dev/null @@ -1,567 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/BasicI18n.java,v $ -// $RCSfile: BasicI18n.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/07/29 14:36:22 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.text.MessageFormat; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.ResourceBundle; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.border.Border; -import javax.swing.border.TitledBorder; - -/** - * Basic implementation of internationalization support. - *

- * This class backs the I18n interface by I18n.property files that it expects to - * find in each package. - *

- * This class provides a mechanism for creating the I18n.property files that it - * expects to use in the application. If the 'i18n.create' flag is set in the - * Debug class, then this class will track what resource bundle property files - * were searched for, and what values were returned for requested keys. The - * dumpCreatedResourceBundles() method will cause the resource bundles to be - * written out, where they can be modified to change the strings displayed in - * the GUI. If the 'i18n.default' flag is set, then 'I18N.properties' files will - * be created. If that flag is not set, then the name of the files will be - * modified for the locale currently set for the application (i.e. - * I18N_en_US.properties for the US locale). You can add the - * I18nFileCreateMenuItem to an application to trigger the - * dumpCreatedResourceBundles() method. - */ -public class BasicI18n - implements I18n, Serializable { - - /** - * Debug string, 'i18n' - */ - public static final String DEBUG = "i18n"; - - /** - * Debug string that causes the BasicI18n class to keep track of resource - * property files and strings it looks for, as well as their defaults. These - * files can be created by calling dumpCreatedResourceBundles(). - */ - public static final String DEBUG_CREATE = "i18n.create"; - - /** - * If set, created ResourceBundle files will not have the local suffixes - * added to them. Otherwise, the locale set in I18n will be used and - * appended. - */ - public static final String DEBUG_CREATE_DEFAULT = "i18n.default"; - - /** - * All properties files containing string should be contained in a file - * called I18N.properties. This string defines the I18N. - */ - public static final String ResourceFileNamePrefix = "I18N"; - - private Locale loc; - - protected transient Hashtable createHash = null; - - // Constructors: - // ///////////// - - /** - * Create a BasicI18n object from the default locale. - */ - public BasicI18n() { - this(Locale.getDefault()); - } - - /** - * Create a BasicI18n object with given locale. - */ - public BasicI18n(Locale loc) { - this.loc = loc; - } - - public String get(Object requestor, String field, String defaultString) { - return get(requestor, field, TEXT, defaultString); - } - - public String get(Object requestor, String field, int type, String defaultString) { - return get(requestor.getClass(), field, type, defaultString); - } - - public String get(Class requestor, String field, String defaultString) { - return get(requestor, field, TEXT, defaultString); - } - - public String get(Class requestor, String field, int type, String defaultString) { - String ret = getInternal(requestor, field, type); - - if (Debug.debugging(DEBUG_CREATE)) { - setForBundleCreation(requestor, field, type, defaultString); - } - - if (ret == null) { - return defaultString; - } - return ret; - } - - protected Hashtable getCreateHash() { - if (createHash == null) { - createHash = new Hashtable(); - } - return createHash; - } - - // Methods making it easier to use MessageFormat: - // ////////////////////////////////////////////// - - public String get(Object requestor, String field, String defaultString, Object param1) { - return get(requestor.getClass(), field, TEXT, defaultString, new Object[] { - param1 - }); - } - - public String get(Object requestor, String field, int type, String defaultString, Object param1) { - return get(requestor.getClass(), field, type, defaultString, new Object[] { - param1 - }); - } - - public String get(Class requestor, String field, String defaultString, Object param1) { - return get(requestor, field, TEXT, defaultString, new Object[] { - param1 - }); - } - - public String get(Class requestor, String field, int type, String defaultString, Object param1) { - return get(requestor, field, type, defaultString, new Object[] { - param1 - }); - } - - public String get(Object requestor, String field, String defaultString, Object param1, Object param2) { - return get(requestor.getClass(), field, TEXT, defaultString, new Object[] { - param1, - param2 - }); - } - - public String get(Object requestor, String field, int type, String defaultString, Object param1, Object param2) { - return get(requestor.getClass(), field, type, defaultString, new Object[] { - param1, - param2 - }); - } - - public String get(Class requestor, String field, String defaultString, Object param1, Object param2) { - return get(requestor, field, TEXT, defaultString, new Object[] { - param1, - param2 - }); - } - - public String get(Class requestor, String field, int type, String defaultString, Object param1, Object param2) { - return get(requestor, field, type, defaultString, new Object[] { - param1, - param2 - }); - } - - public String get(Object requestor, String field, String defaultString, Object[] params) { - return get(requestor.getClass(), field, TEXT, defaultString, params); - } - - public String get(Object requestor, String field, int type, String defaultString, Object[] params) { - return get(requestor.getClass(), field, type, defaultString, params); - } - - public String get(Class requestor, String field, String defaultString, Object[] params) { - return get(requestor, field, TEXT, defaultString, params); - } - - public String get(Class requestor, String field, int type, String defaultString, Object[] params) { - return MessageFormat.format(get(requestor, field, type, defaultString), params); - } - - // Methods fill setting the textual properties of common Swing - // components: - // /////////////////////////////////////////////////////////////////////// - - public void set(Object requestor, String field, JLabel comp) { - set(requestor, field, (JComponent) comp); - comp.setText(getTEXT(requestor, field, comp.getText())); - comp.setDisplayedMnemonic(getMNEMONIC(requestor, field, comp.getDisplayedMnemonic(), false)); - } - - public void set(Object requestor, String field, JButton comp) { - set(requestor, field, (JComponent) comp); - comp.setText(getTEXT(requestor, field, comp.getText())); - comp.setMnemonic(getMNEMONIC(requestor, field, comp.getMnemonic(), false)); - } - - public void set(Object requestor, String field, JMenu comp) { - set(requestor, field, (JComponent) comp); - comp.setText(getTEXT(requestor, field, comp.getText())); - comp.setMnemonic(getMNEMONIC(requestor, field, comp.getMnemonic(), true)); - } - - public void set(Object requestor, String field, JMenuItem comp) { - set(requestor, field, (JComponent) comp); - comp.setText(getTEXT(requestor, field, comp.getText())); - comp.setMnemonic(getMNEMONIC(requestor, field, comp.getMnemonic(), true)); - } - - public void set(Object requestor, String field, JDialog comp) { - comp.setTitle(getTITLE(requestor, field, comp.getTitle())); - } - - public void set(Object requestor, String field, JFrame comp) { - comp.setTitle(getTITLE(requestor, field, comp.getTitle())); - } - - public void set(Object requestor, String field, JComponent comp) { - setTOOLTIP(requestor, field, comp); - Border b = comp.getBorder(); - if (b instanceof TitledBorder) { - TitledBorder t = (TitledBorder) b; - t.setTitle(getTITLE(requestor, field, t.getTitle())); - } - } - - // Methods for filling in strings using reflection: - // //////////////////////////////////////////////// - - public void set(Object requestor, String field) { - Class c = requestor.getClass(); - Field f = null; - try { - f = c.getField(field); - } catch (NoSuchFieldException e) { - // We'll try again below. - } catch (SecurityException e) { - RuntimeException r = - new MissingResourceException("SecurityException trying to reflect on field field", c.getName(), field); - r.initCause(e); - throw r; - } - if (f == null) { - try { - f = c.getDeclaredField(field); - } catch (NoSuchFieldException e) { - RuntimeException r = new MissingResourceException("Can't find field via reflection", c.getName(), field); - r.initCause(e); - throw r; - } catch (SecurityException e) { - RuntimeException r = - new MissingResourceException("SecurityException trying to reflect on field field", c.getName(), field); - r.initCause(e); - throw r; - } - } - // Try to set it accessible: - try { - f.setAccessible(true); - } catch (SecurityException e) { - Debug.message(DEBUG, "Couldn't set field " + field + " accessible"); - } - // Ok, now try to get the data: - Class type = f.getType(); - Object fd = null; - try { - fd = f.get(requestor); - } catch (IllegalArgumentException e) { - RuntimeException r = new MissingResourceException("Couldn't get field", c.getName(), field); - r.initCause(e); - throw r; - } catch (IllegalAccessException e) { - RuntimeException r = new MissingResourceException("Couldn't access field", c.getName(), field); - r.initCause(e); - throw r; - } - // Now do the calls: - if (JLabel.class.isInstance(type)) { - set(requestor, field, (JLabel) fd); - } else if (JButton.class.isInstance(type)) { - set(requestor, field, (JButton) fd); - } else if (JMenu.class.isInstance(type)) { - set(requestor, field, (JMenu) fd); - } else if (JMenuItem.class.isInstance(type)) { - set(requestor, field, (JMenuItem) fd); - } else if (JDialog.class.isInstance(type)) { - set(requestor, field, (JDialog) fd); - } else if (JFrame.class.isInstance(type)) { - set(requestor, field, (JFrame) fd); - } else if (JComponent.class.isInstance(type)) { - set(requestor, field, (JComponent) fd); - } else { - Debug.message(DEBUG, "Couldn't assign data for unknown type: " + type); - } - } - - public void fill(Object requestor) { - - } - - // // - // // Implementation Methods: - // ///////////////////////// - // ///////////////////////// - - /** - * Set a tooltip on the given component if it has one. - */ - protected void setTOOLTIP(Object requestor, String field, JComponent comp) { - String tooltip = get(requestor, field, TOOLTIP, comp.getToolTipText()); - if (tooltip != null) { - comp.setToolTipText(tooltip); - } else { - Debug.message(DEBUG, "No tooltip for: " + getKeyRef(requestor, field)); - } - } - - /** - * Get text for the given component. - */ - protected String getTEXT(Object requestor, String field, String defaultString) { - String text = get(requestor, field, TEXT, defaultString); - if (text == null) { - throw new MissingResourceException("No TEXT resource", requestor.getClass().getName(), field); - } - return text; - } - - /** - * Get title for the given component. - */ - protected String getTITLE(Object requestor, String field, String defaultString) { - String title = get(requestor, field, TITLE, defaultString); - if (title == null) { - throw new MissingResourceException("No TITLE resource", requestor.getClass().getName(), field); - } - return title; - } - - /** - * Get text for the given component. - */ - protected int getMNEMONIC(Object requestor, String field, int defaultInt, boolean verbose) { - String mn = get(requestor, field, MNEMONIC, Character.toString((char) defaultInt)); - if (mn == null) { - if (verbose) { - Debug.message(DEBUG, "No MNEMONIC resource for " + getKeyRef(requestor, field)); - } - return defaultInt; - } - // Now parse this string into something useful: - // For now, don't deal with virtual keys, though that is an - // obvious - // extension: - return Character.getNumericValue(mn.charAt(0)); - } - - /** - * Obtain a String from the underlying data for the given class/field/type. - * - * @return null if the data can't be found -- defaulting happens above here. - */ - protected String getInternal(Class requestor, String field, int type) { - ResourceBundle bundle = null; - Package pckg = requestor.getPackage(); - - String bString = (pckg == null ? "" : (requestor.getPackage().getName() + ".")) + ResourceFileNamePrefix; - - try { - bundle = ResourceBundle.getBundle(bString, loc); - } catch (MissingResourceException e) { - Debug.message(DEBUG, "Could not locate resource: " + bString.replace('.', '/') + ".properties"); - return null; - } - - String key = shortClassName(requestor) + "." + field; - switch (type) { - case TEXT: - // Do nothing. - break; - case TITLE: - key += ".title"; - break; - case TOOLTIP: - key += ".tooltip"; - break; - case MNEMONIC: - key += ".mnemonic"; - break; - } - - try { - - return bundle.getString(key); - - } catch (MissingResourceException e) { - - Debug.message(DEBUG, "Could not locate string in resource: " - + (pckg == null ? "" : (requestor.getPackage().getName().replace('.', '/') + ".")) + "properties for key: " - + key); - - return null; - } - } - - /** - * Obtain a String from the underlying data for the given class/field/type. - * The default is set in the propertyFileProperties. This method is called - * when the debugging flag is set, indicating that a new resource directory - * should be created for all classes that use 18n resources. - */ - protected void setForBundleCreation(Class requestor, String field, int type, String defaultString) { - ResourceBundle bundle = null; - - Package pckg = requestor.getPackage(); - - String bString = (pckg == null ? "" : (requestor.getPackage().getName() + ".")) + ResourceFileNamePrefix; - - String propertyFileNameKey = null; - Properties propertyFileProperties = null; - - // OK, first see what the property file should be. - StringBuffer sbuf = new StringBuffer(bString.replace('.', '/')); - // Scope the desired resource bundle property file if the - // default isn't wanted. - if (!Debug.debugging(DEBUG_CREATE_DEFAULT)) { - sbuf.append("_").append(loc.toString()); - } - sbuf.append(".properties"); - propertyFileNameKey = sbuf.toString().intern(); - - // See if we already have a properties file with the key-value - // pairs for this particular resource bundle. - propertyFileProperties = (Properties) getCreateHash().get(propertyFileNameKey); - - // If not, create it. - if (propertyFileProperties == null) { - propertyFileProperties = new Properties(); - getCreateHash().put(propertyFileNameKey, propertyFileProperties); - } - - try { - bundle = ResourceBundle.getBundle(bString, loc); - } catch (MissingResourceException e) { - } - - String resourceKey = shortClassName(requestor) + "." + field; - switch (type) { - case TEXT: - // Do nothing. - break; - case TITLE: - resourceKey += ".title"; - break; - case TOOLTIP: - resourceKey += ".tooltip"; - break; - case MNEMONIC: - resourceKey += ".mnemonic"; - break; - } - - try { - if (bundle != null) { - String resourceValue = bundle.getString(resourceKey); - propertyFileProperties.put(resourceKey, resourceValue); - } else { - propertyFileProperties.put(resourceKey, defaultString); - } - } catch (MissingResourceException e) { - propertyFileProperties.put(resourceKey, defaultString); - } - } - - /** - * If called, will bring up a JFileChooser so you can pick a location to - * dump the resource files that were searched for, with values that were - * found or the defaults provided in the code. This will only do something - * if the BasicI18n class was accessed with the 'i18n.create' flag set in - * the Debug class. - */ - public void dumpCreatedResourceBundles() { - String location = FileUtils.getFilePathToSaveFromUser("Choose Location"); - if (location != null) { - dumpCreatedResourceBundles(location); - } - } - - /** - * Will dump the resource bundle property files searched for by this class, - * along with the contents that were returned or with the defaults provided - * by the application. - * - * @param location directory location to use as the root for resource bundle - * file hierarchy. - */ - public void dumpCreatedResourceBundles(String location) { - Hashtable bundleHash = getCreateHash(); - for (Enumeration enumeration = bundleHash.keys(); enumeration.hasMoreElements();) { - String key = (String) enumeration.nextElement(); - Properties props = (Properties) bundleHash.get(key); - - try { - File propFile = new File(location + "/" + key); - - File parentDir = new File(propFile.getParent()); - parentDir.mkdirs(); - - propFile.createNewFile(); - FileOutputStream fos = new FileOutputStream(propFile); - props.store(fos, "I18N Resource File"); - fos.close(); - } catch (FileNotFoundException fnfe) { - fnfe.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public static String shortClassName(Class c) { - String name = c.getName(); - return name.substring(name.lastIndexOf(".") + 1); - } - - private static String getKeyRef(Object requestor, String field) { - return requestor.getClass().getName() + "." + field; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/BrowserLauncher2WebBrowser.java b/src/core/src/main/java/com/bbn/openmap/util/BrowserLauncher2WebBrowser.java deleted file mode 100644 index dcf633983..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/BrowserLauncher2WebBrowser.java +++ /dev/null @@ -1,67 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/WebBrowser.java,v $ -// $RCSfile: WebBrowser.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 18:37:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import edu.stanford.ejalbert.BrowserLauncher; -import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException; -import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException; - -/** - * A WebBrowser implementation that uses BrowserLauncher2. Requires the - * BrowserLauncher2 jar to be in the classpath and the - * InformationDelegator.webBrowserClass property set to this classname. - * - * @author dietrick - */ -public class BrowserLauncher2WebBrowser extends WebBrowser { - - BrowserLauncher browserLauncher; - - /** - * Create a web browser that delegates launching to BrowserLauncher2. - * - */ - public BrowserLauncher2WebBrowser() { - try { - browserLauncher = new BrowserLauncher(); - } catch (BrowserLaunchingInitializingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (UnsupportedOperatingSystemException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * Creates a new web browser process, or points the current one to the url - * argument. - * - * @param urlString URL - * - */ - public void launch(String urlString) { - browserLauncher.openURLinBrowser(urlString); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/CSVTokenizer.java b/src/core/src/main/java/com/bbn/openmap/util/CSVTokenizer.java deleted file mode 100644 index 63e1df3b8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/CSVTokenizer.java +++ /dev/null @@ -1,224 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/CSVTokenizer.java,v $ -// $RCSfile: CSVTokenizer.java,v $ -// $Revision: 1.6 $ -// $Date: 2008/03/03 16:44:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * Tokenizer for comma separated values files, at least as generated by excel. - *

- * token() returns the next token, which can be either: - *

    - *
  • null, indicating an empty field. - *
  • a Double, indicating a numeric field. - *
  • a String, indicating an alphanumeric field. - *
  • the NEWLINE object, indicating the end of a record. - *
  • the EOF object, test with isEOF(), indicating the end of file. - *
- */ -public class CSVTokenizer extends Tokenizer { - /** A flag the makes the tokenizer read numbers as strings. */ - boolean numberReadAsString = false; - - public CSVTokenizer(java.io.Reader in) { - super(in); - } - - /** - * If you set numberReadAsString is true, then any number will be maintained - * as a String. - * - * @param in input Reader - * @param numberReadAsString true if numbers should be interpreted to - * Strings - */ - public CSVTokenizer(java.io.Reader in, boolean numberReadAsString) { - super(in); - this.numberReadAsString = numberReadAsString; - } - - protected Object lastTokened = NEWLINE; - - /** - * @return the next object read from the stream. - */ - public Object token() { - int c = next(); - Object ret = null; - if (c == ',') { - if (lastTokened == NEWLINE) { - // Catch the first empty field on a new line. - putback(c); - ret = EMPTY; - } else { - ret = tokenAfterComma(); - } - } else if (c == '\n') - ret = NEWLINE; - else if (c == '"') - ret = tokenString(next()); - else if (c == '\\') - ret = tokenString(c); - else if ((c == '-' || c == '.' || isDigit(c)) && !numberReadAsString) - ret = tokenNumber(c); - else if (c == -1) - ret = EOF; - else - ret = tokenAny(c); - - lastTokened = ret; - - return ret; - } - - /** - * Return the next object read from the stream, called if a comma is found - * first in order to catch empty fields accurately. - */ - protected Object tokenAfterComma() { - int c = next(); - if (c == ',' || c == '\n') { - putback(c); - return EMPTY; - } else if (c == '"') - return tokenString(next()); - else if (c == '\\') - return tokenString(c); - else if ((c == '-' || c == '.' || isDigit(c)) && !numberReadAsString) - return tokenNumber(c); - else if (c == -1) - return EOF; - else - return tokenAny(c); - } - - /** - * seq(is('"'), many(alt(seq(isNot('"')), bpush)
- * seq(is('"')),alt(seq(is('"'), bpush))), - */ - - Object tokenString(int c) { - while (true) { - // Enable escapes to force characters into string. - if (c == '\\') { - bpush(next()); - c = next(); - } else if (c == '"') { - // Changed from the commented-out code below, - // in order to ignore quotes in any order until - // delimiter is reached. Quotes preceded by the - // escape character live on in the string, via the - // code above. - c = next(); - if (isDelimiter(c)) - return bclear(); - else - continue; - - // int c1 = next(); - // if (c1 == '"') { - // bpush(c1); - // c = next(); - // } else { - // if (isDelimiter(c1)) { - // return bclear(); - // } else { - // return error("Expected Delimiter after string!"); - // } - // } - - } else if (isAny(c)) { - bpush(c); - c = next(); - } else { - return bclear(); - } - } - } - - /** - * This checks for the delimiter at the end of a token. We assume it can - * either be a ',' separating the next field, or '\n' indicating the end of - * a field and the end of a record, so we putback(c). - *

- * isDelimiter.set(alt(is(','), is(-1), seq(is('\n'), putback))); - */ - boolean isDelimiter(int c) { - // All delimiters are handled equally now. We used to not put back - // commas and EOF because it was more efficient to just return, but now - // we putback and catch them in the token() call, in order to better - // field empty fields, especially the ellusive common newline combo. - if (c == ',' || c == -1 || c == '\n') { - putback(c); // Wait for next token(). - return true; - } else { - return false; - } - } - - /** - * Return a number or a string. - */ - Object tokenNumber(int c) { - Object result = tokenAny(c); - try { - Double d = new Double((String) result); - return d; - } catch (NumberFormatException e) { - return result; - } - } - - /** - * Return anything up to the next delimiter as a string. - * tokenAny.set(alt(seq(isDelimiter, bclear), seq(bpush,tokenAny))) - */ - Object tokenAny(int c) { - while (true) { - if (isDelimiter(c)) { - return bclear(); - } else { - bpush(c); - c = next(); - } - } - } - - public static void main(String[] args) { - try { - CSVTokenizer csv = new - // CSVTokenizer(new java.io.FileReader(args[0])); - CSVTokenizer(new java.io.BufferedReader(new java.io.FileReader(args[0]))); - // new java.io.InputStreamReader - // (new java.io.FileInputStream(args[0])))); - while (true) { - Object token = csv.token(); - if (csv.isEOF(token)) { - csv.close(); - return; - } - System.out.println(token); - } - } catch (Exception e) { - System.out.println(e); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/ClasspathHacker.java b/src/core/src/main/java/com/bbn/openmap/util/ClasspathHacker.java deleted file mode 100644 index d506793a8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/ClasspathHacker.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.util; - -/************************************************************************************************** - * Copyright (c) 2004, Federal University of So Carlos * - * * - * All rights reserved. * - * * - * Redistribution and use in source and binary forms, with or without modification, are permitted * - * provided that the following conditions are met: * - * * - * * Redistributions of source code must retain the above copyright notice, this list of * - * conditions and the following disclaimer. * - * * Redistributions in binary form must reproduce the above copyright notice, this list of * - * * conditions and the following disclaimer in the documentation and/or other materials * - * * provided with the distribution. * - * * Neither the name of the Federal University of So Carlos nor the names of its * - * * contributors may be used to endorse or promote products derived from this software * - * * without specific prior written permission. * - * * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - **************************************************************************************************/ - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.logging.Logger; - -/** - * Useful class for dynamically changing the classpath, adding classes during - * runtime. - * - * @author unknown - */ -public class ClasspathHacker { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.util.ClasspathHacker"); - - /** - * Parameters of the method to add an URL to the System classes. - */ - private static final Class[] parameters = new Class[] { URL.class }; - - /** - * Adds a file to the classpath. - * - * @param s a String pointing to the file - * @throws IOException if there was a problem - */ - public static void addFile(String s) throws IOException { - File f = new File(s); - addFile(f); - }// end method - - /** - * Adds a file to the classpath - * - * @param f the file to be added - * @throws IOException if there was a problem - */ - public static void addFile(File f) throws IOException { - addURL(f.toURI().toURL()); - }// end method - - /** - * Adds the content pointed by the URL to the classpath. - * - * @param u the URL pointing to the content to be added - * @throws IOException if there was a problem with URL - */ - public static void addURL(URL u) throws IOException { - URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); - - Class sysclass = URLClassLoader.class; - try { - boolean loadIt = true; - URL[] currentPaths = sysloader.getURLs(); - - for (URL cPath : currentPaths) { - if (cPath.getFile().equals(u.getFile())) { - loadIt = false; - } - } - - if (loadIt) { - Method method = sysclass.getDeclaredMethod("addURL", parameters); - method.setAccessible(true); - method.invoke(sysloader, new Object[] { u }); - logger.fine("loaded jar file"); - } else { - logger.fine("jar file already loaded, skipping"); - } - } catch (Throwable t) { - t.printStackTrace(); - throw new IOException("Error, could not add URL to system classloader"); - } // end try catch - }// end method -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/ColorFactory.java b/src/core/src/main/java/com/bbn/openmap/util/ColorFactory.java deleted file mode 100644 index 28ae534e7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/ColorFactory.java +++ /dev/null @@ -1,336 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/ColorFactory.java,v $ -// $RCSfile: ColorFactory.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/11 20:39:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.awt.Color; -import java.awt.Paint; -import java.lang.reflect.Field; -import java.util.Properties; - -/** - * ColorFactory creates instances of colors. This class has methods which create - * java.awt.Color or - * com.bbn.openmap.omGraphics.OMColor objects. This class handles - * creation of Color objects in a Java version-neutral way by using reflection - * to create the java.awt.Color object. This way we support the extended Java 2 - * platform without sacrificing support for JDK 1.1.X. - *

- * NOTE: For general RGB-colored graphics, you should directly use the - * java.awt.Color 1.1.X constructors. If you are interested in using - * alpha-valued colors, or using colors in a (JDK) version-neutral way, then - * read on... - *

- * You may want to use this class because: - *

    - *
  • You want to use alpha-valued colors in your images under both JDK 1.1 and - * JDK 1.2. (JDK1.1 has limited support for alpha-valued images). You can use - * the appropriate createColor() methods in this class with the - * forceAlpha set to true and you are guaranteed - * (almost!) to get back an alpha-valued color. - *

    - *

  • You want to use alpha-valued colors for generic graphics, but only in a - * version-neutral way and if the support is available (e.g., you're running - * under the Java 2 platform). In this case you can call the appropriate - * createColor() methods without the forceAlpha - * argument, or with forceAlpha set to false. - *
- * - * @see com.bbn.openmap.omGraphics.OMColor - */ -public class ColorFactory { - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color to use if the property value doesn't work - * @return java.awt.Color - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault) - throws NumberFormatException { - String colorString = p.getProperty(propName, dfault); - return parseColor(colorString, true); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color to use if the property value doesn't work - * @param forceAlpha - * force using alpha value - * @return java.awt.Color - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault, boolean forceAlpha) - throws NumberFormatException { - String colorString = p.getProperty(propName, dfault); - return parseColor(colorString, forceAlpha); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color or paint to use if the property value doesn't work - * @return something of T - * @see #parseColor(String, boolean) - */ - @SuppressWarnings("unchecked") - public static T parseColorFromProperties(Properties p, String propName, T dfault) { - try { - String colorString = p.getProperty(propName); - if (colorString != null) { - return (T) parseColor(colorString, true); - } - } catch (NumberFormatException nfe) { - } - return dfault; - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. - * - * @param colorString - * the 24/32bit hex string value (ARGB) - * @return java.awt.Color 24bit RGB, 24/32bit ARGB - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColor(String colorString) throws NumberFormatException { - return parseColor(colorString, true); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString - * the 24/32bit hex string value (ARGB) - * @param forceAlpha - * force using alpha value - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #createColor(int, boolean) - */ - public static Color parseColor(String colorString, boolean forceAlpha) throws NumberFormatException { - - int value; - - // If we come across people who do one letter per color. - if (colorString.length() == 3) { - colorString = new StringBuilder().append(colorString.charAt(0)).append(colorString.charAt(0)) - .append(colorString.charAt(1)).append(colorString.charAt(1)).append(colorString.charAt(2)) - .append(colorString.charAt(2)).toString(); - } - - try { - value = (int) Long.parseLong(colorString, 16); - } catch (NumberFormatException nfe) { - value = Long.decode(colorString).intValue(); - // If decode can't catch it, throw an Exception... - } - - // We want to test for this - if the length of the colorString - // is less than 7, then the caller probably doesn't care about - // transparency and wants the color to be opaque. However, - // "0" is a common number for clear, and should be - // transparent. - if (colorString.length() < 7 && !colorString.equals("0")) { - // Just a RGB value, use regular JDK1.1 constructor - return new Color(value); - } - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param red - * red component (0.0-1.0) - * @param green - * green component (0.0-1.0) - * @param blue - * blue component (0.0-1.0) - * @param alpha - * alpha component (0.0-1.0) - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(float red, float green, float blue, float alpha) { - return createColor(red, green, blue, alpha, true); - } - - /** - * Create a Color. - * - * @param red - * red component (0.0-1.0) - * @param green - * green component (0.0-1.0) - * @param blue - * blue component (0.0-1.0) - * @param alpha - * alpha component (0.0-1.0) - * @param forceAlpha - * force using alpha value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(float red, float green, float blue, float alpha, boolean forceAlpha) { - int value = (((int) (alpha * 255) & 0xff) << 24) | (((int) (red * 255) & 0xff) << 16) - | (((int) (green * 255) & 0xff) << 8) | (int) (blue * 255) & 0xff; - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param red - * red component (0-255) - * @param green - * green component (0-255) - * @param blue - * blue component (0-255) - * @param alpha - * alpha component (0-255) - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int red, int green, int blue, int alpha) { - return createColor(red, green, blue, alpha, true); - } - - /** - * Create a Color. - * - * @param red - * red component (0-255) - * @param green - * green component (0-255) - * @param blue - * blue component (0-255) - * @param alpha - * alpha component (0-255) - * @param forceAlpha - * force using alpha value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int red, int green, int blue, int alpha, boolean forceAlpha) { - int value = ((alpha & 0xff) << 24) | ((red & 0xff) << 16) | ((green & 0xff) << 8) | blue & 0xff; - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param value - * 32bit ARGB color value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int value) { - return createColor(value, true); - } - - /** - * Create a Color. - * - * @param value - * 32bit ARGB color value - * @param forceAlpha - * force using alpha value the underlying java.awt.Color supports - * it - * @return Color or OMColor that has an ARGB value - */ - public static Color createColor(int value, boolean forceAlpha) { - return new Color(value, forceAlpha); - } - - public static String getHexColorString(Color color) { - return Integer.toHexString((color.getRGB() & 0x00FFFFFF) | (color.getAlpha() << 24)); - } - - /** - * Method that returns a java.awt.Color object given the name of the color. - * Depends on the static instances of color provided by the java.awt.Color - * class. - * - * @param name - * @param defaultColor - * @return Color that reflects the name, or the default color. - */ - public static Color getNamedColor(String name, Color defaultColor) { - if (name != null) { - Field[] colorFields = Color.class.getDeclaredFields(); - for (int i = 0; i < colorFields.length; i++) { - Field f = colorFields[i]; - try { - if (name.equalsIgnoreCase(f.getName())) { - return (Color) f.get((Object) null); - } - } catch (IllegalAccessException iae) { - // Whoa, shouldn't happen, but hey - } catch (ClassCastException cce) { - // Shouldn't ask for anything other than colors, - // either. - } - } - } - - return defaultColor; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/ComponentFactory.java b/src/core/src/main/java/com/bbn/openmap/util/ComponentFactory.java deleted file mode 100644 index b1b0eb516..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/ComponentFactory.java +++ /dev/null @@ -1,674 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/ComponentFactory.java,v $ -// $RCSfile: ComponentFactory.java,v $ -// $Revision: 1.15 $ -// $Date: 2006/05/19 15:26:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressSupport; - -/** - * The OpenMap ComponentFactory is a class that can construct objects from class - * names, with the added capability of passing the new object a Properties - * object to initialize itself. The new object may also receive a property - * prefix to use to scope its properties from the Properties object. It is - * sensitive to the OpenMap paradigm of marker names in a list: That a list of - * objects can be defined as a space separated names (marker names) within a - * String. Those marker names can serve as a prefix for other properties within - * a Properties object, as well as the prefix for a '.class' property to define - * the class name for the new object. - */ -public class ComponentFactory { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.util.ComponentFactory"); - - /** - * The property to use for the class name of new objects - ".class". Expects - * that a prefix will be prepended to it. - */ - public static final String DotClassNameProperty = ".class"; - /** - * A property to use for the class name of new objects - "class". Can be used - * with the PropUtils.objectsFromProperties method as the defining property. - */ - public static final String ClassNameProperty = "class"; - - /** - * The singleton instance of the ComponentFactory. - */ - private static ComponentFactory singleton; - - protected ComponentFactory() { - } - - /** - * Method call to retrieve the singleton instance of the ComponentFactory. - * - * @return ComponentFactory. - */ - protected static ComponentFactory getInstance() { - if (singleton == null) { - singleton = new ComponentFactory(); - } - return singleton; - } - - /** - * Set the singleton instance of the ComponentFactory. - * - * @param cf - */ - protected static void setInstance(ComponentFactory cf) { - singleton = cf; - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @return Vector containing the new Objects. - */ - public static List create(List markerNames, Properties properties) { - return getInstance()._create(markerNames, null, properties, null, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker names. - * @param properties Properties object containing the details. - * @return Vector containing the new Objects. - */ - public static List create(List markerNames, String prefix, Properties properties) { - return getInstance()._create(markerNames, prefix, properties, null, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker - * names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates to. - * It's OK if this is null to not have progress events - * sent. - * @return Vector containing the new Objects. - */ - public static List create(List markerNames, String prefix, Properties properties, - ProgressSupport progressSupport) { - return getInstance()._create(markerNames, prefix, properties, progressSupport, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates to. - * It's OK if this is null to not have progress events - * sent. - * @return Vector containing the new Objects. - */ - public static List create(List markerNames, Properties properties, ProgressSupport progressSupport) { - return getInstance()._create(markerNames, null, properties, progressSupport, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress - * updates to. It's OK if this is null to not have - * progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble creating an - * object, it's marker name will be placed in the - * returned vector instead of a component. If false, - * only valid objects will be returned in the - * vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can figure - * out which one couldn't be created. In any case, the size of the - * returned vector is the same size as the markerNames vector, so you - * can figure out which markerNames go with which objects. - */ - public static List create(List markerNames, Properties properties, ProgressSupport progressSupport, - boolean matchInOutVectorSize) { - return getInstance()._create(markerNames, null, properties, progressSupport, matchInOutVectorSize); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker - * names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress - * updates to. It's OK if this is null to not have - * progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble creating an - * object, it's marker name will be placed in the - * returned vector instead of a component. If false, - * only valid objects will be returned in the - * vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can figure - * out which one couldn't be created. In any case, the size of the - * returned vector is the same size as the markerNames vector, so you - * can figure out which markerNames go with which objects. - */ - public static List create(List markerNames, String prefix, Properties properties, - ProgressSupport progressSupport, boolean matchInOutVectorSize) { - - return getInstance()._create(markerNames, prefix, properties, progressSupport, matchInOutVectorSize); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in the - * Properties object for the markerName.class property to get a class name to - * create each object. Then, if the new objects are PropertyConsumers, use the - * marker name as a property prefix to get properties for that object out of the - * Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker - * names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress - * updates to. It's OK if this is null to not have - * progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble creating an - * object, it's marker name will be placed in the - * returned vector instead of a component. If false, - * only valid objects will be returned in the - * vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can figure - * out which one couldn't be created. In any case, the size of the - * returned vector is the same size as the markerNames vector, so you - * can figure out which markerNames go with which objects. - */ - protected List _create(List markerNames, String prefix, Properties properties, - ProgressSupport progressSupport, boolean matchInOutVectorSize) { - - int size = markerNames.size(); - List vector = new ArrayList<>(size); - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Creating Components", 100, 0); - } - - String propertyPrefix = PropUtils.getScopedPropertyPrefix(prefix); - int i = 0; - for (String markerName : markerNames) { - String componentName = propertyPrefix + markerName; - - String classProperty = componentName + DotClassNameProperty; - String className = properties.getProperty(classProperty); - - if (className == null) { - logger.warning("Failed to locate property \"" + componentName + "\" with class \"" + classProperty - + "\"\n Skipping component \"" + componentName + "\""); - if (matchInOutVectorSize) { - vector.add(componentName); - } - continue; - } - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Creating Components", size, i); - } - - Object component = create(className, componentName, properties); - - if (component != null) { - vector.add(component); - if (logger.isLoggable(Level.FINE)) { - logger.fine("ComponentFactory: [" + className + "(" + i + ")] created"); - } - } else { - if (matchInOutVectorSize) { - vector.add(componentName); - } - logger.info("[" + componentName + " : " + className + "(" + i - + ")] NOT created. -- Set logging flag to FINE/FINER for details."); - } - i++; - } - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Configuring...", size, size); - } - return vector; - } - - /** - * Create a single object. - * - * @param className Class name to instantiate, empty constructor. - * @return object if all goes well, null if not. - */ - public static Object create(String className) { - return create(className, (Object[]) null, null, null); - } - - /** - * Create a single object. - * - * @param className Class name to instantiate. - * @param properties Properties to use to initialize the object, if the object - * is a PropertyConsumer. - * @return object if all goes well, null if not. - */ - public static Object create(String className, Properties properties) { - return create(className, (Object[]) null, null, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the object - * is a PropertyConsumer. - * @return Object or null if it couldn't be created - */ - public static Object create(String className, String prefix, Properties properties) { - - return create(className, (Object[]) null, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the constructor - * of the component. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs) { - return create(className, constructorArgs, null, null, null); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the constructor - * of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, Class[] argClasses) { - return create(className, constructorArgs, argClasses, null, null); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the constructor - * of the component. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, String prefix, Properties properties) { - return create(className, constructorArgs, null, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the constructor - * of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, Class[] argClasses, String prefix, - Properties properties) { - return getInstance()._create(className, constructorArgs, argClasses, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the constructor - * of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - protected Object _create(String className, Object[] constructorArgs, Class[] argClasses, String prefix, - Properties properties) { - String errorMessage = null; - Throwable exceptionCaught = null; - boolean DEBUG = false; - try { - - if (logger.isLoggable(Level.FINER)) { - DEBUG = true; - logger.finer("creating: " + className); - } - - // Apparently, this fails in certain cases where OpenMap is being - // used as a plugin in a NetBeans or Eclipse architecture and the - // application classloader isn't aware of the plugins classes. It - // limits the creation of the object to classes in the caller's - // classloader. - // Class newObjClass = Class.forName(className.trim()); - // replaced with: - - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if (cl == null) { - cl = this.getClass().getClassLoader(); - } - Class newObjClass = Class.forName(className.trim(), true, cl); - - if (DEBUG) - logger.finer(" - got class for " + className); - - if (argClasses == null) { - if (constructorArgs != null && constructorArgs.length > 0) { - - argClasses = new Class[constructorArgs.length]; - for (int i = 0; i < argClasses.length; i++) { - argClasses[i] = constructorArgs[i].getClass(); - } - } else { - // If empty, make null - constructorArgs = null; - } - } - - if (DEBUG) { - StringBuffer sb = new StringBuffer(); - if (constructorArgs == null) { - sb.append("null"); - } else { - for (int i = 0; i < constructorArgs.length; i++) { - sb.append(constructorArgs[i].getClass().getName()); - if (i < constructorArgs.length - 1) - sb.append(", "); - } - } - logger.finer(" - created class arguments [" + sb.toString() + "]"); - } - - Constructor constructor = null; - Object obj = null; - - try { - constructor = newObjClass.getConstructor(argClasses); - - if (DEBUG) - logger.finer(" - got constructor"); - - // Create component - obj = constructor.newInstance(constructorArgs); - if (DEBUG) - logger.finer(" - got object"); - - } catch (NoSuchMethodException nsmei) { - /* - * The argClasses may have subclasses of what the desired constructor needs, so - * we need to check explicitly. - */ - obj = createWithSubclassConstructorArgs(newObjClass, argClasses, constructorArgs); - if (DEBUG && obj != null) - logger.finer(" - got object on try #2"); - } - - if (obj instanceof PropertyConsumer && properties != null) { - if (DEBUG) { - logger.finer(" setting properties with prefix \"" + prefix + "\""); - } - ((PropertyConsumer) obj).setProperties(prefix, properties); - - if (Debug.debugging(BasicI18n.DEBUG_CREATE)) { - /* - * If we're interested in creating resource bundle files, we should cause these - * PropertyConsumers to ask for their property info, since this is where most of - * the elective GUI strings are queried and found. - */ - ((PropertyConsumer) obj).getPropertyInfo(null); - } - - if (DEBUG) - logger.finer(" - set properties"); - } - return obj; - - } catch (NoSuchMethodException nsme) { - exceptionCaught = nsme; - errorMessage = "NoSuchMethodException: " + nsme.getMessage(); - } catch (InstantiationException ie) { - exceptionCaught = ie; - errorMessage = "InstantiationException: " + ie.getMessage() - + " - Might be trying to create an abstract class"; - } catch (IllegalAccessException iae) { - if (DEBUG) - iae.printStackTrace(); - exceptionCaught = iae; - errorMessage = "IllegalAccessException: " + iae.getMessage(); - } catch (IllegalArgumentException iae2) { - if (DEBUG) - iae2.printStackTrace(); - exceptionCaught = iae2; - errorMessage = "IllegalArgumentException: " + iae2.getMessage(); - } catch (InvocationTargetException ite) { - if (DEBUG) - ite.printStackTrace(); - exceptionCaught = ite; - errorMessage = "InvocationTargetException: " + ite.getMessage(); - } catch (ClassNotFoundException cnfe) { - exceptionCaught = cnfe; - errorMessage = "ClassNotFoundException: " + cnfe.getMessage(); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Failed to create \"" + className - + (prefix != null ? "\" using component marker name \"" + prefix + "\"" : "") + " - error message: " - + errorMessage); - - if (exceptionCaught != null) { - logger.log(Level.WARNING, "Exception reported is as follows:", exceptionCaught); - } - } - - return null; - } - - /** - * Method to create Object with arguments. - * - * @param newObjClass the Class to be created. - * @param argClasses an array of Classes describing the arguments. - * @param constructorArgs an array of Objects for arguments. - * @return Object created from the Class and arguments. - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - protected Object createWithSubclassConstructorArgs(Class newObjClass, Class[] argClasses, - Object[] constructorArgs) throws NoSuchMethodException, InstantiationException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException { - - boolean DEBUG = logger.isLoggable(Level.FINER); - - int numArgClasses = 0; - - if (argClasses != null) { - numArgClasses = argClasses.length; - } - - Constructor[] constructors = newObjClass.getConstructors(); - int numConstructors = constructors.length; - - if (DEBUG) { - logger.finer( - " - searching " + numConstructors + " possible constructor" + (numConstructors == 1 ? "" : "s")); - } - - for (int i = 0; i < numConstructors; i++) { - Constructor constructor = constructors[i]; - - Class[] arguments = constructor.getParameterTypes(); - int numArgs = arguments.length; - - // First, check the number of arguments for a match - if (numArgs != numArgClasses) { - if (DEBUG) { - logger.finer(" - constructor " + i + " with " + numArgs + " arguments not a match"); - } - - continue; // Nope, not it. - } - - // OK, empty constructor desired, punch... - // If argClasses == null, then numArgs will equal zero. Makes the - // compiler happy. - if (numArgs == 0 || argClasses == null) { - if (DEBUG) { - logger.finer(" - constructor " + i + " with no arguments is a match"); - } - return constructor; - } - - // Check to see if the argument classes of the Constructor - // are assignable to the desired argClasses being sought. - boolean good = false; - for (int j = 0; j < numArgs; j++) { - if (arguments[j] == argClasses[j]) { - if (DEBUG) { - logger.finer(" - direct arg class match, arg " + j); - } - good = true; // Maintain true... - } else if (arguments[j].isAssignableFrom(argClasses[j])) { - - // Doesn't work quite yet. May have to check for - // super-super class,etc, and we still get an - // IllegalArgumentException due to argument type - // mismatch. - - // Is this even necessary? Don't think so... - argClasses[j] = argClasses[j].getSuperclass(); - if (DEBUG) { - logger.finer(" - superclass arg class match, arg " + j + " reassigning to " - + argClasses[j].toString()); - } - good = true; // Maintain true... - // } else if (constructorArgs[j] instanceof - // Number) { - // if (DEBUG) { - // Debug.output(" - Number type match, arg " + j); - // } - // good = true; // Maintain true... - - } else { - if (DEBUG) { - logger.finer(" - arg class mismatch on arg " + j + ", bailing (" + arguments[j].getName() - + " vs. " + argClasses[j].getName() + ")"); - } - good = false; // Punch with false - break; - } - } - - if (good) { - if (DEBUG) { - logger.finer(" - creating object"); - } - Object obj = constructor.newInstance(constructorArgs); - if (DEBUG) { - logger.finer(" - created object"); - } - return obj; - } - } - - return null; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/DataBounds.java b/src/core/src/main/java/com/bbn/openmap/util/DataBounds.java deleted file mode 100644 index 404534993..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/DataBounds.java +++ /dev/null @@ -1,244 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/DataBounds.java,v $ -// $RCSfile: DataBounds.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.awt.geom.Point2D; - -/** - * A simple utility class that holds a min, max for a group of points. - */ -public class DataBounds { - - protected Point2D min; - protected Point2D max; - - protected DataBounds hardLimits; - - /** - * True if the direction of the y coordinates increase in the up direction. - * Should be set to false if larger y values are actually lower pixel values - * on the map. - */ - boolean yDirUp = true; - - public DataBounds() { - } - - public DataBounds(double minx, double miny, double maxx, double maxy) { - add(minx, miny); - add(maxx, maxy); - } - - public DataBounds(Point2D minP, Point2D maxP) { - add(minP); - add(maxP); - } - - /** - * @return a point set to the average of the min and max values. May return - * null if no points have been added - */ - public Point2D getCenter() { - if (min != null) { - double minx = min.getX(); - double miny = min.getY(); - double maxx = max.getX(); - double maxy = max.getY(); - return new Point2D.Double((minx + maxx) / 2, (miny + maxy) / 2); - } else - return null; - } - - public String toString() { - return "DataBounds| min:" + min + " max:" + max; - } - - /** - * @return upper right point - */ - public Point2D getMax() { - return max; - } - - /** - * @return lower left point - */ - public Point2D getMin() { - return min; - } - - public void add(double x, double y) { - if (min == null) { - min = new Point2D.Double(x, y); - max = new Point2D.Double(x, y); - } else { - double minx = min.getX(); - double miny = min.getY(); - double maxx = max.getX(); - double maxy = max.getY(); - - if (minx > x) - minx = x; - if (miny > y) - miny = y; - if (maxx < x) - maxx = x; - if (maxy < y) - maxy = y; - - if (hardLimits != null) { - double hlminx = hardLimits.min.getX(); - double hlminy = hardLimits.min.getY(); - double hlmaxx = hardLimits.max.getX(); - double hlmaxy = hardLimits.max.getY(); - - minx = setInRange(hlmaxx, hlminx, minx); - maxx = setInRange(hlmaxx, hlminx, maxx); - miny = setInRange(hlmaxy, hlminy, miny); - maxy = setInRange(hlmaxy, hlminy, maxy); - - } - - min.setLocation(minx, miny); - max.setLocation(maxx, maxy); - } - } - - /** - * Add min and max from a TimeBounds object to this one. - * - * @param dataBounds another TimeBounds object. - */ - public void add(DataBounds dataBounds) { - if (dataBounds != null) { - add(dataBounds.getMin()); - add(dataBounds.getMax()); - } - } - - /** - * Make sure the value is within the range. - * - * @param hi high range value - * @param lo low range value - * @param val testing value - * @return the value, adjusted if necessary. - */ - protected double setInRange(double hi, double lo, double val) { - if (val > hi) { - val = hi; - } - - if (val < lo) { - val = lo; - } - - return val; - } - - /** - * Add Point2D values to TimeBounds. - * - * @param point Point2D - */ - public void add(Point2D point) { - if (point != null) { - add(point.getX(), point.getY()); - } - } - - public boolean contains(Point2D query) { - double x = query.getX(); - double y = query.getY(); - return x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY(); - } - - public double getWidth() { - return max.getX() - min.getX(); - } - - public double getHeight() { - return max.getY() - min.getY(); - } - - public DataBounds getHardLimits() { - return hardLimits; - } - - public void setHardLimits(DataBounds hardLimits) { - this.hardLimits = hardLimits; - } - - public boolean isyDirUp() { - return yDirUp; - } - - public void setyDirUp(boolean yDirUp) { - this.yDirUp = yDirUp; - } - - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof DataBounds) { - DataBounds dobj = (DataBounds) obj; - boolean match = (min == null && dobj.getMin() == null && max == null && dobj.getMax() == null); - boolean match2 = false; - try { - match2 = getMin().equals(dobj.getMin()) && getMax().equals(dobj.getMax()); - } catch (NullPointerException npe) { - - } - - return this.yDirUp == dobj.yDirUp && (match || match2); - } - - return false; - } - - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - if (max != null) { - result = HashCodeUtil.hash(result, max.getY()); - result = HashCodeUtil.hash(result, max.getX()); - } - if (min != null) { - result = HashCodeUtil.hash(result, min.getY()); - result = HashCodeUtil.hash(result, min.getX()); - } - result = HashCodeUtil.hash(result, yDirUp); - return result; - } - - public boolean intersects(DataBounds db2) { - if (db2 == null) { - return false; - } - Point2D min2 = db2.getMin(); - Point2D max2 = db2.getMax(); - return !(min2 == null || (min2.getY() > max.getY() || max2.getY() < min.getY()) - || (min2.getX() > max.getX() || max2.getX() < min.getX())); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/DataBoundsProvider.java b/src/core/src/main/java/com/bbn/openmap/util/DataBoundsProvider.java deleted file mode 100644 index bbb228ecf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/DataBoundsProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/DataBoundsProvider.java,v $ -// $RCSfile: DataBoundsProvider.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * An interface describing a Component that can provide basic information about - * the area its data covers. - */ -public interface DataBoundsProvider { - - /** - * @return a DataBounds object describing the area of coverage, may be null - * if the data hasn't been evaluated yet. - */ - public DataBounds getDataBounds(); - - /** - * @return A pretty name for the boundary, suitable for a GUI - */ - public String getName(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/DataOrganizer.java b/src/core/src/main/java/com/bbn/openmap/util/DataOrganizer.java deleted file mode 100644 index e5ac22a6e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/DataOrganizer.java +++ /dev/null @@ -1,89 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/DataOrganizer.java,v $ -// $RCSfile: DataOrganizer.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.util.Collection; - -/** - * The DataOrganizer lets you organize objects in a way that will let you - * retrieve them based on a geographic query. It's an interface that lets you - * decide, with an implementation, the best way to manage and retrieve your - * data. - */ -public interface DataOrganizer { - - /** - * Add a object into the organizer at a location. - * - * @param lat up-down location (latitude, y) - * @param lon left-right location (longitude, x) - * @param obj object to add - * @return true if the insertion worked. - */ - public boolean put(double lat, double lon, T obj); - - /** - * Remove a object out of the organizer at a location. - * - * @param lat up-down location (latitude, y) - * @param lon left-right location (longitude, x) - * @param obj object to remove - * @return the object removed, null if the object not found. - */ - public T remove(double lat, double lon, T obj); - - /** Clear the organizer. */ - public void clear(); - - /** - * Find an object closest to a lat/lon. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @return the object that is closest to the lat/lon. - */ - public T get(double lat, double lon); - - /** - * Find an object closest to a lat/lon, within a given maximum. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param withinDistance maximum distance to have a hit. - * @return the object that is closest to the lat/lon, within the given - * distance. - */ - public T get(double lat, double lon, double withinDistance); - - /** - * Find all the objects within a bounding box. - * - * @param north top location in QuadTree Grid (latitude, y) - * @param west left location in QuadTree Grid (longitude, x) - * @param south lower location in QuadTree Grid (latitude, y) - * @param east right location in QuadTree Grid (longitude, x) - * @return Vector of objects. - */ - public Collection get(double north, double west, double south, double east); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/Debug.java b/src/core/src/main/java/com/bbn/openmap/util/Debug.java deleted file mode 100644 index 80e4c45be..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Debug.java +++ /dev/null @@ -1,627 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/Debug.java,v $ -// $RCSfile: Debug.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/12/08 01:10:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.applet.Applet; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; - -/** - * An abstract class that presents a static interface for debugging - * output. It also provides a way to direct output into a log. There - * are two types of output - the regular output information, and the - * error information, and they can be handled separately. There are - * two differences between the two - the error file only gets created - * if there is an error, and the error messages have a header and a - * tail surrounding the messages, making them easier to spot. If the - * output and error file are set to be the same (setLogFile()), then - * that file is created automatically, regardless of anything being - * put into it. - *

- * Debugging output is turned on or off by system properties for - * applications, or parameters for applets. - *

- * A programmer can use code like the following: - *

- *


- * 
- * if (Debug.debugging("foo")) {
- *     System.out.println("Got " + nbytes + " bytes of data.");
- * }
- * 
- * 
- *

- * The message gets printed when the application is run with - * -Ddebug.foo or when the applet gets run with: - *

- * 
- * <param name=debug.foo value=>
- * 
- * 
- * The special token debug.all turns on all debugging - * for both applets and applications. - * - * @author Tom Mitchell (tmitchell@bbn.com) - * @author $Author: dietrick $ - * @version $Revision: 1.6 $, $Date: 2004/12/08 01:10:45 $ - */ -public abstract class Debug { - - public static String ERROR_HEADER = "\n*** ERROR ***"; - public static String ERROR_TAIL = "*************"; - - /** - * Don't allow construction, all methods are static. - */ - private Debug() { - } - - /** - * Globally enable or disable debugging. - */ - public static final boolean On = true; - /** - * The stream where debugging output should go. Default is System.out. - */ - public static PrintStream out = System.out; - /** - * The stream where debugging error messages should go. Default is - * System.err. Use the function Debug.error to write to it, in case you also - * want to direct output to a file. - */ - protected static PrintStream err = System.err; - /** - * The File for logging errors. - */ - protected static File errorFile = null; - /** - * The flag for whether the output stream should still be notified if - * logging output. - */ - protected static boolean notifyOut = true; - /** - * The flag for whether the err stream should still be notified if logging - * errors. - */ - protected static boolean notifyErr = true; - /** - * The DataOutputStream for logging output. - */ - protected static DataOutputStream outputLog = null; - /** - * The DataOutputStream for logging errors. - */ - protected static DataOutputStream errorLog = null; - /** - * Flag to have the errors appended to the error log. - */ - protected static boolean errorAppend = false; - /** - * Flag to indicate whether all debug messages should get printed. This is - * shorthand for defining all the debug symbols. - */ - public static boolean debugAll = false; - /** - * The user specified flag to indicate all debugging is on. Default is - * "all". - */ - public static String debugAllToken = "all"; - - private static Hashtable dbgTable = new Hashtable(); - private static String debugTokenHeader = "debug."; - - /** - * Initialize debugging for the given applet. Applets must pass an array of - * parameters because the applet Parameters list cannot be accessed in - * whole, only queried. The parameters list looks something like this: - * - *
-     * 
-     * String[] debugTokens = { "debug.debug", // com.bbn.openmap.Debug
-     *         "debug.openmap", // com.bbn.openmap.client.OpenMap
-     *         "debug.mappanel", // com.bbn.openmap.awt.MapPanel
-     *         "debug.awt", // com.bbn.openmap.awt.*
-     *         "debug.map", // com.bbn.openmap.Map
-     *         "debug.layer", // com.bbn.openmap.Layer
-     *         "debug.proj", // com.bbn.openmap.proj.*
-     *         "debug.spec", // com.bbn.openmap.spec.*
-     *         "debug.env" // com.bbn.openmap.Environment
-     * };
-     * 
-     * 
- * - * @param applet The applet - * @param parameters The debugging flags to look for in the applet's - * parameters list - */ - public static void init(Applet applet, String[] parameters) { - if (applet == null) { - // handle a SecurityException in case we are an applet - // but no applet was passed as an argument. - try { - init(System.getProperties()); - } catch (SecurityException e) { - } - } else if (parameters != null) { - try { - for (int i = 0; i < parameters.length; i++) { - String pname = parameters[i]; - if (pname.startsWith(debugTokenHeader) - && (applet.getParameter(parameters[i]) != null)) { - String token = pname.substring(debugTokenHeader.length()); - dbgTable.put(token, Boolean.TRUE); - } - } - // look for special debug.all token! - if (applet.getParameter(debugTokenHeader + debugAllToken) != null) { - dbgTable.put(debugAllToken, Boolean.TRUE); - } - } catch (NullPointerException npe) { - } - } - - Debug.postInit(); - } - - /** - * Initialize debugging for an application. Debugging symbols are detected - * in the given properties list, and must have the form "debug.X", where X - * is a debug token used in the application. - * - * @param p A properties list, usually System.getProperties() - */ - public static void init(Properties p) { - Enumeration e = p.propertyNames(); - while (e.hasMoreElements()) { - String name = e.nextElement().toString(); - if (name.startsWith(debugTokenHeader)) { - String token = name.substring(debugTokenHeader.length()); - dbgTable.put(token, Boolean.TRUE); - } - } - Debug.postInit(); - } - - /** - * Initialize debugging from the system properties. - */ - public static void init() { - Properties p; - try { - p = System.getProperties(); - } catch (java.security.AccessControlException ace) { - p = new Properties(); - } - - init(p); - } - - /** - * Common inits, regardless of applet or application. - */ - private static void postInit() { - debugAll = dbgTable.containsKey(debugAllToken); - } - - /** - * Indicates if the debugging for the named token is on or off. - * - * @param token a candidate token - * @return true if debugging is on, false otherwise. - */ - public static boolean debugging(String token) { - return Debug.On && (debugAll || dbgTable.containsKey(token)); - } - - /** - * Installs a new debug token - * - * @param dbgToken token name - */ - public static void put(String dbgToken) { - dbgTable.put(dbgToken, Boolean.TRUE); - } - - /** - * Rremoves a debug token - * - * @param dbgToken token name - */ - public static void remove(String dbgToken) { - dbgTable.remove(dbgToken); - } - - /** - * Prints message if dbgToken - * debugging is on. NOTE, WARNING!: this is a potentially - * expensive method if you pass a message String composed of many - * concatenated pairs. For example, like:
- * `onceStr+" "+uponStr+" a "+timeStr+", "+ ... +"\nThe end."' - *
- * Instead you should do:
-     * 
-     * 
-     *   if (Debug.debugging(dbgToken)) {
-     *       Debug.output(onceStr+" "+uponStr+" a "+timeStr+", "+ ... +"\nThe end.");
-     *   }
-     * 
-     * 
-     * 
- * - * @param dbgToken a token to be tested by debugging() - * @param message a message to be printed - */ - public static void message(String dbgToken, String message) { - if (Debug.On && Debug.debugging(dbgToken)) { - Debug.output(message); - } - } - - /** - * Sets the debugging output stream to the named stream. - * - * @param out the desired debugging output stream - */ - public static void setPrintStream(PrintStream out) { - Debug.out = out; - } - - /** - * Accessor for the current debugging output stream. - * - * @return the current debugging output stream. - */ - public static PrintStream getPrintStream() { - return out; - } - - /** - * Provide a file to log output. This can be in conjunction with the output - * stream, or instead of it. Will overwrite the file, if it exists. - * - * @param file the file to use for the error log. - * @param alsoToOutStream true if the out stream should still - * provide output, in addition to logging the output - */ - public static void directOutput(File file, boolean alsoToOutStream) { - try { - directOutput(new FileOutputStream(file), alsoToOutStream); - } catch (IOException ioe) { - // If something goes wrong, set the output to the - // System.out only, and hope someone sees it. - notifyOut = true; - out = System.out; - error("Debug: can't set up <" + file + "> for log file! \n" + ioe); - return; - } - } - - /** - * Provide a file to log output. This can be in conjunction with the output - * stream, or instead of it. - * - * @param filename the file to use for the error log. - * @param append if true, log the output at the end of the file, instead of - * the beginning. - * @param alsoToOutStream true if the out stream should still provide - * output, in addition to logging the output. - */ - public static void directOutput(String filename, boolean append, boolean alsoToOutStream) { - try { - directOutput(new FileOutputStream(filename, append), alsoToOutStream); - } catch (IOException ioe) { - // If something goes wrong, set the output to the - // System.out only, and hope someone sees it. - notifyOut = true; - out = System.out; - error("Debug: can't set up <" + filename + "> for log file! \n" + ioe); - return; - } - } - - /** - * Provide a DataOutputStream to log output. This can be in conjunction with - * the output stream, or instead of it. - * - * @param os the OutputStream that's handling outputlogging. - * @param alsoToOutStream true if the out stream should still provide - * output, in addition to logging the output. - */ - public static void directOutput(OutputStream os, boolean alsoToOutStream) { - outputLog = new DataOutputStream(os); - notifyOut = alsoToOutStream; - } - - /** - * Sets the error output stream to the named stream. - * - * @param err the desired error output stream - */ - public static void setErrorStream(PrintStream err) { - Debug.err = err; - } - - /** - * Accessor for the current error output stream. - * - * @return the current error output stream. - */ - public static PrintStream getErrorStream() { - return err; - } - - /** - * Provide a file to log errors. This can be in conjunction with the - * errorstream, or instead of it. - * - * @param file the file to use for the error log. - * @param alsoToErrStream true if the err stream should still provide - * output, in addition to logging the errors. - */ - public static void directErrors(File file, boolean alsoToErrStream) { - errorFile = file; - notifyErr = alsoToErrStream; - } - - /** - * Provide a file to log errors. This can be in conjunction with the - * errorstream, or instead of it. - * - * @param filename the file to use for the error log. - * @param append if true, log the output at the end of the file, instead of - * the beginning. - * @param alsoToErrStream true if the err stream should still provide - * output, in addition to logging the errors. - */ - public static void directErrors(String filename, boolean append, boolean alsoToErrStream) { - errorAppend = append; - errorFile = new File(filename); - notifyErr = alsoToErrStream; - } - - /** - * Provide a DataOutputStream to log errors. This can be in conjunction with - * the errorstream, or instead of it. - * - * @param os the DataOutputStream handling error logging. - * @param alsoToErrStream true if the err stream should still provide - * output, in addition to logging the errors. - */ - public static void directErrors(OutputStream os, boolean alsoToErrStream) { - errorLog = new DataOutputStream(os); - notifyErr = alsoToErrStream; - } - - /** - * Handle error messages, buy writing them to an error log, if that has been - * set up, and/or to the error stream, if requested. The special thing about - * error output is that the error is framed with a header and a tail, - * hopefully to make it easier for someone to spot in the log. - * - * @param errorString the string to write as an error. - */ - public static void error(String errorString) { - - try { - if (errorLog == null) { - // If no errors have happened yet, this will get run. - if (errorFile != null) { - FileOutputStream log = new FileOutputStream(errorFile.getPath(), errorAppend); - errorLog = new DataOutputStream(log); - - // Lets make introductions into the error file, - // shall we? - errorLog.writeBytes("\n"); - errorLog.writeBytes(getMapBeanMessage()); - errorLog.writeBytes("\n"); - errorLog.writeBytes("ERROR log file - " - + java.util.Calendar.getInstance().getTime()); - errorLog.writeBytes("\n"); - errorLog.writeBytes(ERROR_TAIL); - errorLog.writeBytes(ERROR_TAIL); - errorLog.writeBytes(ERROR_TAIL); - errorLog.writeBytes("\n"); - ///////////////////// - - errorLog.writeBytes(ERROR_HEADER); - errorLog.writeBytes(errorString); - errorLog.writeBytes("\n"); - errorLog.writeBytes(ERROR_TAIL); - errorLog.writeBytes("\n"); - } - } else { - // With the log already set up, this should get run. - errorLog.writeBytes(ERROR_HEADER); - errorLog.writeBytes("\n"); - errorLog.writeBytes(errorString); - errorLog.writeBytes("\n"); - errorLog.writeBytes(ERROR_TAIL); - errorLog.writeBytes("\n"); - } - } catch (IOException ioe) { - // If something goes wrong, set the output to the - // System.err only, and hope someone sees it. - errorFile = null; - notifyErr = true; - err = System.err; - err.println(ERROR_HEADER); - err.println("Debug: error writing <" + errorString + "> to log! \n" + ioe); - err.println(ERROR_TAIL); - return; - } - - // Write to the error stream if required. - if (notifyErr) { - err.println(ERROR_HEADER); - err.println(errorString); - err.println(ERROR_TAIL); - } - } - - /** - * A reflective method to get the copyright message from the MapBean without - * having to actually compile the MapBean when Debug is compiled.\ - * - * @return MapBean message. - */ - public static String getMapBeanMessage() { - String message = ""; - try { - Class mbClass = Class.forName("com.bbn.openmap.MapBean"); - java.lang.reflect.Method crMessage = mbClass.getDeclaredMethod("getCopyrightMessage", (Class[]) null); - message = (String) crMessage.invoke(mbClass, (Object[]) null); - } catch (java.lang.reflect.InvocationTargetException ite) { - System.out.println(ite.getMessage()); - } catch (IllegalArgumentException iae) { - System.out.println(iae.getMessage()); - } catch (IllegalAccessException iae2) { - System.out.println(iae2.getMessage()); - } catch (NoSuchMethodException nme) { - System.out.println(nme.getMessage()); - } catch (NullPointerException npe) { - System.out.println(npe.getMessage()); - } catch (SecurityException se) { - System.out.println(se.getMessage()); - } catch (ClassNotFoundException cnfe) { - System.out.println(cnfe.getMessage()); - } - return message; - } - - /** println to output. */ - public static void output() { - Debug.output(""); - } - - /** - * Handle output messages, buy writing them to an output log, if that has - * been set up, and/or to the output stream, if requested. - * - * @param outputString the string to write as output. - */ - public static void output(String outputString) { - - try { - if (outputLog != null) { - outputLog.writeBytes(outputString); - outputLog.writeBytes("\n"); - } - } catch (IOException ioe) { - // If something goes wrong, set the output to the - // System.out only, and hope someone sees it. - notifyOut = true; - out = System.out; - error("Debug: output writing <" + outputString + "> to log! \n" + ioe); - return; - } - - // Write to the output stream if required. - if (notifyOut) { - out.println(outputString); - } - } - - /** - * Provide a file to log output. This can be in conjunction with the - * streams, or instead of them. This basically sets the output log and the - * error log to be the same thing. - * - * @param file the file to use for the error log. - * @param alsoToStreams true if the streams should still provide output, in - * addition to logging the output. - */ - public static void setLog(File file, boolean alsoToStreams) { - - try { - FileOutputStream logStream = new FileOutputStream(file); - setLog(logStream, alsoToStreams); - } catch (IOException ioe) { - // If something goes wrong, set the output to the - // System streams only, and hope someone sees it. - resetOutput(); - error("IOException trying to create a log file.\n" + ioe); - } - } - - /** - * Provide an output stream to log output. This can be in conjunction with - * the streams, or instead of them. This basically sets the output log and - * the error log to be the same thing. - * - * @param logStream the output stream for output. - * @param alsoToStreams true if the streams should still provide output, in - * addition to logging the output. - */ - public static void setLog(OutputStream logStream, boolean alsoToStreams) { - DataOutputStream dos = new DataOutputStream(logStream); - outputLog = dos; - errorLog = dos; - // Wrap up loose ends - if something happens to the - // logStream, we'll just shut down logging, and force - // everything to the output streams. - errorFile = null; - notifyErr = alsoToStreams; - notifyOut = alsoToStreams; - } - - /** - * Reset the logging to the output. - */ - public static void resetOutput() { - // If something goes wrong, set the output to the - // System streams only, and hope someone sees it. - notifyOut = true; - errorFile = null; - notifyErr = true; - err = System.err; - out = System.out; - } - - /** - * Dummy function to illustrate usage of the debugging class. - */ - public static void sampleUsage() { - if (Debug.On && Debug.debugging("debug")) { - Debug.output("debug message"); - } else { - Debug.output("try again"); - } - } - - /** - * main routine used in unit testing. - * - * @param args none expected - */ - public static void main(String args[]) { - Debug.init(System.getProperties()); - Debug.sampleUsage(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/DeepCopyUtil.java b/src/core/src/main/java/com/bbn/openmap/util/DeepCopyUtil.java deleted file mode 100644 index 54c9d6976..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/DeepCopyUtil.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * - * Copyright 2011 BBN Technologies - * - */ -package com.bbn.openmap.util; - -import com.bbn.openmap.omGraphics.OMGeometry; - -/** - * A set of convenience functions for deep copying data structures. - * - * @author ddietrick - */ -public class DeepCopyUtil { - - public static double[] deepCopy(double[] source) { - if (source == null) { - return null; - } - double[] ds = new double[source.length]; - System.arraycopy(source, 0, ds, 0, source.length); - return ds; - } - - public static int[] deepCopy(int[] source) { - if (source == null) { - return null; - } - int[] ints = new int[source.length]; - System.arraycopy(source, 0, ints, 0, source.length); - return ints; - } - - public static boolean[] deepCopy(boolean[] source) { - if (source == null) { - return null; - } - boolean[] bools = new boolean[source.length]; - System.arraycopy(source, 0, bools, 0, source.length); - return bools; - } - - public static float[] deepCopy(float[] source) { - if (source == null) { - return null; - } - float[] floats = new float[source.length]; - System.arraycopy(source, 0, floats, 0, source.length); - return floats; - } - - public static char[] deepCopy(char[] source) { - if (source == null) { - return null; - } - char[] chars = new char[source.length]; - System.arraycopy(source, 0, chars, 0, source.length); - return chars; - } - - public static short[] deepCopy(short[] source) { - if (source == null) { - return null; - } - short[] shorts = new short[source.length]; - System.arraycopy(source, 0, shorts, 0, source.length); - return shorts; - } - - public static long[] deepCopy(long[] source) { - if (source == null) { - return null; - } - long[] longs = new long[source.length]; - System.arraycopy(source, 0, longs, 0, source.length); - return longs; - } - - public static byte[] deepCopy(byte[] source) { - if (source == null) { - return null; - } - byte[] bytes = new byte[source.length]; - System.arraycopy(source, 0, bytes, 0, source.length); - return bytes; - } - - public static T deepCopy(T source) { - T list = (T) ComponentFactory.create(source.getClass().getName()); - list.restore(source); - return list; - } - - public static T[] deepCopy(T[] source) { - if (source == null) { - return null; - } - - // This is a shallow copy, clone objects are same as source objects - T[] clone = source.clone(); - - // JDK 1.6 required - //T[] clone = Arrays.copyOfRange(source, 0, source.length); - - for (int i = 0; i < source.length; i++) { - T subclone = null; - subclone = (T) ComponentFactory.create(source[i].getClass().getName()); - if (subclone != null) { - subclone.restore(source[i]); - } - clone[i] = subclone; - } - - return clone; - } - - public static double[][] deepCopy(double[][] source) { - if (source == null) { - return null; - } - - double[][] ret = new double[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new double[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static boolean[][] deepCopy(boolean[][] source) { - if (source == null) { - return null; - } - - boolean[][] ret = new boolean[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new boolean[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static byte[][] deepCopy(byte[][] source) { - if (source == null) { - return null; - } - - byte[][] ret = new byte[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new byte[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static char[][] deepCopy(char[][] source) { - if (source == null) { - return null; - } - - char[][] ret = new char[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new char[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static int[][] deepCopy(int[][] source) { - if (source == null) { - return null; - } - - int[][] ret = new int[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new int[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static float[][] deepCopy(float[][] source) { - if (source == null) { - return null; - } - - float[][] ret = new float[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new float[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static long[][] deepCopy(long[][] source) { - if (source == null) { - return null; - } - - long[][] ret = new long[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new long[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } - - public static short[][] deepCopy(short[][] source) { - if (source == null) { - return null; - } - - short[][] ret = new short[source.length][]; - for (int i = 0; i < source.length; i++) { - if (source[i] != null) { - ret[i] = new short[source[i].length]; - System.arraycopy(source[0], 0, ret[i], 0, source[i].length); - } - } - return ret; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/FanCompress.java b/src/core/src/main/java/com/bbn/openmap/util/FanCompress.java deleted file mode 100644 index f7fc39702..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/FanCompress.java +++ /dev/null @@ -1,292 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/FanCompress.java,v $ -// $RCSfile: FanCompress.java,v $ -// $Revision: 1.4 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - - -/** - * Class to perform fan compression on points. - *

FAN COMPRESSION

- *
    - *
  • R.A. Fowell, and D.D. McNeil, Faster Plots by Fan - * Data-Compression, IEEE Computer Graphics & Applications, 1989, - * 58-66. - *
  • See also, J.G. Dunham, Optimum uniformr piecewise linear - * approximation of planar curves, IEEE Trans. Pat. Anal and Mach. - * Intel, Vol, PAMI-8, No 1, 1986, p. 67-75. - *
- */ -public abstract class FanCompress { - - public static class FanPoint { - public double x; - public double y; - } - - /** - * FanCompress class for float values. - */ - public static class FloatCompress extends FanCompress { - - private int read = 0; - private int write = 0; - protected double[] array; - protected double zero_eps = 0.0001; - - /** - * Construct a FanCompress object which deals in floats. - * - * @param array float[] array of coordinate pairs. - */ - public FloatCompress(double[] array) { - this.array = array; - } - - /** - * Get the next point. - * - * @param p FanPoint - * @return boolean false if no more points. - */ - public boolean next_point(FanPoint p) { - if (read + 1 < array.length) { - p.x = (double) array[read++]; - p.y = (double) array[read++]; - return true; - } else { - return false; - } - } - - /** - * Save coordinates. This routine coalesces adjacent points - * which have the same coordinates. - * - * @param x coordinate - * @param y coordinate - */ - public void save_point(double x, double y) { - if (write + 1 < read) { - // coalesce points - if ((write > 1) - && MoreMath.approximately_equal((float) x, - array[write - 2], - zero_eps) - && MoreMath.approximately_equal((float) y, - array[write - 1], - zero_eps)) { - return; - } - array[write++] = (float) x; - array[write++] = (float) y; - } else { - System.err.println("FanCompress.FloatCompress.save_point(): " - + "ignoring extra..."); - } - } - - /** - * Save only unique coordinates. If several points are the - * same, then coalesce them into one point. - * - * @param epsilon threshold used to determine uniqueness of - * coordinates. - */ - public void set_coalesce_points(double epsilon) { - zero_eps = (float) epsilon; - } - - /** - * Return a copy of the internal array. Invoke this method - * after running fan_compress() on this object. - * - * @return float[] - */ - public double[] getArray() { - double[] ret_val = new double[write]; - System.arraycopy(array, 0, ret_val, 0, write); - return ret_val; - } - } - - /** - * Get the next point. - * - * @param p FanPoint - * @return boolean false if no more points. - */ - public abstract boolean next_point(FanPoint p); - - /** - * Save coordinates. - * - * @param x coordinate - * @param y coordinate - */ - public abstract void save_point(double x, double y); - - /** - * Save only unique coordinates. If several points are the same, - * then coalesce them into one point. - * - * @param epsilon threshold used to determine uniqueness of - * coordinates. - */ - public abstract void set_coalesce_points(double epsilon); - - /** - * Perform fan compression. IF there is only 1 point, save-point - * will be run on it twice, sorry. - * - * @param fan FanCompress object - * @param epsilon double - */ - public static final void fan_compress(FanCompress fan, double epsilon) { - double epsilon_squared; /* epsilon * epsilon */ - double p0x, p0y; /* Start of segment. */ - FanPoint p = new FanPoint(); - // double px, py; /* Current point x,y */ - - epsilon_squared = epsilon * epsilon; - - if (!fan.next_point(p)) /* Get first point */ - return; - - fan.save_point(p.x, p.y); /* Save it. */ - p0x = p.x; /* p0 <- p. */ - p0y = p.y; - - while (true) { - double distance; - double pu; - double ux, uy; - double vx, vy; - double f1, f2, f3; - double xok, yok; - - /* Find first point > epsilon from p0. */ - while (true) { - double dx; - double dy; - - dx = p.x - p0x; - dy = p.y - p0y; - - distance = dx * dx + dy * dy; - - if (distance > epsilon_squared) - break; - - if (!fan.next_point(p)) { - // goto finish; - fan.save_point(p.x, p.y); /* Save last point. */ - return; - } - - } - - distance = Math.sqrt(distance); - - pu = distance; /* U component of p. */ - - ux = (p.x - p0x) / pu; /* U unit vector. */ - uy = (p.y - p0y) / pu; - - vx = -uy; /* V unit vector. */ - vy = ux; - - f1 = pu; /* Region. */ - f2 = epsilon / pu; - - f3 = -f2; - - xok = p.x; /* Last point we know is OK. */ - yok = p.y; - - while (true) { - double dx, dy; - double /* pu, */pv; - boolean keep; - - if (!fan.next_point(p)) { - // goto finish; - fan.save_point(p.x, p.y); /* Save last point. */ - return; - } - - keep = true; - dx = p.x - p0x; - dy = p.y - p0y; - pu = ux * dx + uy * dy; - pv = vx * dx + vy * dy; - - if (pu >= f1) { - /* Still moving away from p0? */ - double slope; - - slope = pv / pu; - - if (slope <= f2 && slope >= f3) { - double temp; - - /* Still in region? */ - double dslope; - - dslope = epsilon / pu; - - keep = false; - - f1 = pu; - /* Adjust region. */ - temp = slope + dslope; - - if (temp < f2) - f2 = temp; /* Min. */ - temp = slope - dslope; - - if (temp > f3) - f3 = temp; /* Max. */ - } - } - - if (keep) { - fan.save_point(xok, yok); - - p0x = xok; /* p0 <- pOK. */ - p0y = yok; - - break; - } else { - xok = p.x; - yok = p.y; - } - } - } - - // System.out.println("should not reach here"); - - // finish: - // - // save_point(p.x, p.y); /* Save last point. */ - // return; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/FileUtils.java b/src/core/src/main/java/com/bbn/openmap/util/FileUtils.java deleted file mode 100644 index cf9591e30..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/FileUtils.java +++ /dev/null @@ -1,455 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/FileUtils.java,v -// $ -// $RCSfile: FileUtils.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/07/10 23:22:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.Adler32; -import java.util.zip.CheckedOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import javax.swing.filechooser.FileFilter; - -import com.bbn.openmap.Environment; - -public class FileUtils { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.util.FileUtils"); - - public static String getFilePathToSaveFromUser(String title) { - OpenFileRunnable runnable = new OpenFileRunnable(title, null) { - public void run() { - JFileChooser chooser = getChooser(title); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showSaveDialog(null); - result = handleResponse(chooser, state); - } - }; - runnable.invoke(); - return runnable.getResult(); - } - - public static String getFilePathToOpenFromUser(String title) { - return getFilePathToOpenFromUser(title, null); - } - - public static String getFilePathToOpenFromUser(String title, FileFilter ff) { - OpenFileRunnable runnable = new OpenFileRunnable(title, ff); - runnable.invoke(); - return runnable.getResult(); - } - - public static String getPathToOpenFromUser(String title, FileFilter ff, int fileSelectionMode, - String acceptButtonText) { - OpenPathRunnable runnable = new OpenPathRunnable(title, ff, fileSelectionMode, acceptButtonText); - runnable.invoke(); - return runnable.getResult(); - } - - static class OpenFileRunnable implements Runnable { - - String title; - FileFilter fileFilter; - String result; - - OpenFileRunnable(String title, FileFilter ff) { - this.title = title; - this.fileFilter = ff; - } - - public void run() { - JFileChooser chooser = getChooser(title); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showOpenDialog(null); - this.result = handleResponse(chooser, state); - } - - String getResult() { - return result; - } - - void invoke() { - try { - if (!SwingUtilities.isEventDispatchThread()) { - SwingUtilities.invokeAndWait(OpenFileRunnable.this); - } else { - run(); - } - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - } - } - } - - static class OpenPathRunnable extends OpenFileRunnable { - - int fileSelectionMode; - String acceptButtonText; - - OpenPathRunnable(String title, FileFilter ff, int fileSelectionMode, String acceptButtonText) { - super(title, ff); - this.fileSelectionMode = fileSelectionMode; - this.acceptButtonText = acceptButtonText; - } - - public void run() { - JFileChooser chooser = getChooser(title); - chooser.setFileSelectionMode(fileSelectionMode); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showDialog(null, acceptButtonText); - this.result = handleResponse(chooser, state); - } - } - - public static JFileChooser getChooser(String title) { - // setup the file chooser - File startingPoint = new File(Environment.get("lastchosendirectory", System.getProperty("user.home"))); - JFileChooser chooser = new JFileChooser(startingPoint); - chooser.setDialogTitle(title); - return chooser; - } - - public static String handleResponse(JFileChooser chooser, int state) { - String ret = null; - try { - // only bother trying to read the file if there is one - // for some reason, the APPROVE_OPTION said it was a - // boolean during compile and didn't work in this next - // statement - if ((state != JFileChooser.CANCEL_OPTION) && (state != JFileChooser.ERROR_OPTION)) { - - ret = chooser.getSelectedFile().getCanonicalPath(); - - int dirIndex = ret.lastIndexOf(File.separator); - if (dirIndex >= 0) { - // store the selected file for later - Environment.set("lastchosendirectory", ret.substring(0, dirIndex)); - } - } - } catch (IOException ioe) { - JOptionPane.showMessageDialog(null, ioe.getMessage(), "Error picking file", JOptionPane.ERROR_MESSAGE); - ioe.printStackTrace(); - } - return ret; - } - - /** - * Copy a file to another location, byte-wise. - * - * @param fromFile - * the File to copy from. - * @param toFile - * the File to copy to. - * @param bufSize - * the byte size of the transfer buffer. - * @throws IOException - * Thrown if anything goes wrong. - */ - public static void copy(File fromFile, File toFile, int bufSize) throws IOException { - - FileInputStream fis = new FileInputStream(fromFile); - FileOutputStream fos = new FileOutputStream(toFile); - - if (bufSize <= 0) { - bufSize = 1024; - } - - byte[] bytes = new byte[bufSize]; - - int numRead; - - while ((numRead = fis.read(bytes)) > 0) { - fos.write(bytes, 0, numRead); - } - - fis.close(); - fos.close(); - } - - /** - * Delete a file or a directory, including its content. - * - * @param file file to delete - * @throws IOException if there's a problem - */ - public static void deleteFile(File file) throws IOException { - - if (file.isDirectory()) { - - // directory is empty, then delete it - if (file.list().length == 0) { - - file.delete(); - System.out.println("Directory is deleted : " + file.getAbsolutePath()); - - } else { - - // list all the directory contents - String files[] = file.list(); - - for (String temp : files) { - // construct the file structure - File fileDelete = new File(file, temp); - - // recursive delete - deleteFile(fileDelete); - } - - // check the directory again, if empty then delete it - if (file.list().length == 0) { - file.delete(); - - } - } - - } else { - // if file, then delete it - file.delete(); - - } - } - - /** - * Create a zip file containing the given File. - * - * @param zipFileName The path to the zip file. If it doesn't end in .zip, - * .zip will be added to it. - * @param toBeZipped The Path of the file/directory to be zipped. - * @throws IOException if there's a problem - * @throws FileNotFoundException if there's a problem - */ - public static void saveZipFile(String zipFileName, File toBeZipped) throws IOException, FileNotFoundException { - - try { - - if (!zipFileName.endsWith(".zip")) { - zipFileName += ".zip"; - } - - File zipFile = new File(zipFileName); - if (!zipFile.getParentFile().exists()) { - zipFile.getParentFile().mkdirs(); - } - FileOutputStream fos = new FileOutputStream(zipFile); - ZipOutputStream zoStream = new ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.STORED); - writeZipEntry(toBeZipped, zoStream, toBeZipped.getParent().length() + 1); - zoStream.close(); - } catch (SecurityException se) { - logger.warning("Security Exception caught while creating " + zipFileName); - } - } - - /** - * Create a zip file containing the files in the list. The entries will not - * have their parent's file names in their path, they are stored with the - * given file at the root of the zip/jar. - * - * @param zipFileName The path to the zip/jar file. - * @param toBeZipped The List of files to be placed in the zip/jar. - * @throws IOException if there's a problem - * @throws FileNotFoundException if there's a problem - */ - public static void saveZipFile(String zipFileName, List toBeZipped) - throws IOException, FileNotFoundException { - - try { - - File zipFile = new File(zipFileName); - if (!zipFile.getParentFile().exists()) { - zipFile.getParentFile().mkdirs(); - } - FileOutputStream fos = new FileOutputStream(zipFile); - CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32()); - ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(checksum)); - // ZipOutputStream zoStream = new ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.STORED); - for (File file : toBeZipped) { - writeZipEntry(file, zoStream, file.getParent().length() + 1); - } - zoStream.close(); - } catch (SecurityException se) { - logger.warning("Security Exception caught while creating " + zipFileName); - } - } - - /** - * Writes a file to the jar stream. - * - * @param toBeZipped the file to be written - * @param zoStream the stream to write it to, prepared for the - * ZipFile/JarFile - * @param prefixTrimLength The number of characters to trim off the absolute - * path of the file to be zipped. Can be useful to adjust this to - * adjust the directory depth of the entry for when it is unpacked. - * If less than 0, only the file name will be used. - * @throws IOException if there's a problem - */ - public static void writeZipEntry(File toBeZipped, ZipOutputStream zoStream, int prefixTrimLength) - throws IOException { - - if (toBeZipped.isDirectory()) { - File[] files = toBeZipped.listFiles(); - for (int i = 0; i < files.length; i++) { - writeZipEntry(files[i], zoStream, prefixTrimLength); - } - } else { - - if (logger.isLoggable(Level.FINE)) { - logger.fine(toBeZipped + ", " + toBeZipped.getAbsolutePath().substring(prefixTrimLength) + ")"); - } - - writeZipEntry(toBeZipped, zoStream, prefixTrimLength < 0 ? toBeZipped.getName() - : toBeZipped.getAbsolutePath().substring(prefixTrimLength)); - } - } - - protected static void writeZipEntry(File fromFile, ZipOutputStream zoStream, String entryName) throws IOException { - - entryName = entryName.replace('\\', '/'); - - // long size = fromFile.length(); - ZipEntry zEntry = new ZipEntry(entryName); - // zEntry.setSize(size); - // zEntry.setCrc(0);// Don't know what it these values are - // right now, but zero works... - zoStream.putNextEntry(zEntry); - - FileInputStream fis = new FileInputStream(fromFile); - - byte[] bytes = new byte[1024]; - - int numRead; - // CRC32 checksum = new CRC32(); - while ((numRead = fis.read(bytes)) > 0) { - zoStream.write(bytes, 0, numRead); - // checksum.update(bytes, 0, numRead); - } - // zEntry.setCrc(checksum.getValue()); - zoStream.closeEntry(); - fis.close(); - } - - /** - * Unpack a zip file. - * - * @param zipFileName - * The path name of the zip file to unpack. - * @param toDir - * the directory to put the unpacked files in. - * @param deleteAfter - * flag to delete the zip file when complete. - */ - public static void openZipFile(String zipFileName, File toDir, boolean deleteAfter) { - if (zipFileName != null) { - try { - InputStream in; - - if (!toDir.exists()) { - toDir.mkdirs(); - } - - URL zipurl = PropUtils.getResourceOrFileOrURL(zipFileName); - if (zipurl != null) { - - in = new BufferedInputStream(zipurl.openStream()); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(" unzipping " + zipFileName); - } - ZipInputStream zin = new ZipInputStream(in); - ZipEntry e; - - while ((e = zin.getNextEntry()) != null) { - - if (e.isDirectory()) { - new File(toDir, e.getName()).mkdirs(); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine(" unzipping " + e.getName()); - } - unzip(zin, new File(toDir, e.getName())); - } - } - zin.close(); - if (deleteAfter) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("unzipping complete, deleting zip file"); - } - - File file = new File(zipurl.getFile()); - if (file.exists()) { - file.delete(); - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("unzipping complete, leaving zip file"); - } - return; - } - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - protected static void unzip(ZipInputStream zin, File f) throws IOException { - final int BUFFER = 2048; - FileOutputStream out = new FileOutputStream(f); - byte[] b = new byte[BUFFER]; - int len = 0; - BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER); - while ((len = zin.read(b, 0, BUFFER)) != -1) { - dest.write(b, 0, len); - } - dest.flush(); - dest.close(); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/HandleError.java b/src/core/src/main/java/com/bbn/openmap/util/HandleError.java deleted file mode 100644 index e09cedbec..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/HandleError.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/HandleError.java,v $ -// $RCSfile: HandleError.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * Use this class to catch a checked exception and throw it as an - * uncheck one. This way, people will find out about it, but don't - * have to explicitly handle it. - */ -public class HandleError extends RuntimeException { - public HandleError(Exception e) { - super(e.toString()); - } - - public HandleError(String s) { - super(s); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/HashCodeUtil.java b/src/core/src/main/java/com/bbn/openmap/util/HashCodeUtil.java deleted file mode 100644 index 18bbb2a40..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/HashCodeUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.bbn.openmap.util; - -import java.lang.reflect.Array; - -/** - * Collected methods which allow easy implementation of hashCode. - * Algorithm from Effective Java by Joshua Bloch. Implementation found at - * http://www.javapractices.com. - * - * Example use case: - * - *
- * public int hashCode() {
- *     int result = HashCodeUtil.SEED;
- *     // collect the contributions of various fields
- *     result = HashCodeUtil.hash(result, fPrimitive);
- *     result = HashCodeUtil.hash(result, fObject);
- *     result = HashCodeUtil.hash(result, fArray);
- *     return result;
- * }
- * 
- */ -public final class HashCodeUtil { - - /** - * An initial value for a hashCode, to which is added - * contributions from fields. Using a non-zero value decreases collisons of - * hashCode values. - */ - public static final int SEED = 17; - - /** - * hash booleans. - * - * @param aSeed seeding int to start with - * @param aBoolean object to hash - * @return hash for boolean - */ - public static int hash(int aSeed, boolean aBoolean) { - return firstTerm(aSeed) + (aBoolean ? 1 : 0); - } - - /** - * hash chars. - * - * @param aSeed seeding int to start with - * @param aChar object to hash - * @return hash for char - */ - public static int hash(int aSeed, char aChar) { - return firstTerm(aSeed) + (int) aChar; - } - - /** - * hash ints. - * - * @param aSeed seeding int to start with - * @param aInt object to hash - * @return hash for int - */ - public static int hash(int aSeed, int aInt) { - /* - * Implementation Note Note that byte and short are handled by this - * method, through implicit conversion. - */ - return firstTerm(aSeed) + aInt; - } - - /** - * hash longs. - * - * @param aSeed seeding int to start with - * @param aLong object to hash - * @return hash for long - */ - public static int hash(int aSeed, long aLong) { - return firstTerm(aSeed) + (int) (aLong ^ (aLong >>> 32)); - } - - /** - * hash floats. - * - * @param aSeed seeding int to start with - * @param aFloat object to hash - * @return hash for float - */ - public static int hash(int aSeed, float aFloat) { - return hash(aSeed, Float.floatToIntBits(aFloat)); - } - - /** - * hash for doubles - * - * @param aSeed seeding int to start with - * @param aDouble to hash - * @return hash for double - */ - public static int hash(int aSeed, double aDouble) { - return hash(aSeed, Double.doubleToLongBits(aDouble)); - } - - /** - * aObject is a possibly-null object field, and possibly an - * array. - * - * If aObject is an array, then each element may be a primitive - * or a possibly-null object. - * - * @param aSeed seeding int to start with - * @param aObject object to hash - * @return hash for aObject - */ - public static int hash(int aSeed, Object aObject) { - int result = aSeed; - if (aObject == null) { - result = hash(result, 0); - } else if (!isArray(aObject)) { - result = hash(result, aObject.hashCode()); - } else { - int length = Array.getLength(aObject); - for (int idx = 0; idx < length; ++idx) { - Object item = Array.get(aObject, idx); - // recursive call! - result = hash(result, item); - } - } - return result; - } - - // / PRIVATE /// - private static final int fODD_PRIME_NUMBER = 31; - - private static int firstTerm(int aSeed) { - return fODD_PRIME_NUMBER * aSeed; - } - - private static boolean isArray(Object aObject) { - return aObject.getClass().isArray(); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/I18n.java b/src/core/src/main/java/com/bbn/openmap/util/I18n.java deleted file mode 100644 index cf0a850f6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/I18n.java +++ /dev/null @@ -1,436 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/I18n.java,v $ -// $RCSfile: I18n.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuItem; - -/** - * Interface for Internationalization support in Openamp. The I18n - * implementation will define where the resources for the given class - * are stored. - *

- * Intended Usage: - *

- * There are several possible uses of this interface, outlined below: - * - *

    - *
  • Simple Usage:
    - * The simplest case is where you just want to get the possibly - * internationalized version of a given string. This would look like - * the following: - *

    - * - * I18n i18n = Environment.getI18n();
    - * String message = i18n.get(this, "message", "Please enter a number: ");
    - *
    - *

    - * There is also similar version of get(...) that takes - * a Class instead, and thefore can be used in static - * contexts. If the Strings you are looking for pertain to specific - * types (i.e. uses) you can you the form of get(...) - * that specifies this, as the following example illustrates: - *

    - * - * I18n i18n = Environment.getI18n();
    - * JButton okButton = new JButton(i18n.get(this, "okButton", i18n.TEXT, "Ok")); - *
    - * okButton.setTooltipText(i18n.get(this, "okButton", i18n.TOOLTOP, "Ok"));
    - *
    - *

    - * Again there is a similar version of this method that takes a - * Class instead of an object so it can be used in - * static contexts. - *

    - * Note that in both examples given, the field - * parameter to the get(...) methods are the name of - * the variable that holds the string returned. For the these methods, - * this is a convention rather than a requirement. However, it - * suggested that you maintain this convention because doing so makes - * it clearer what is going on and because it is most similar to how - * the calls are made in the reflective case below. - *

    - * Note also that there are several additional get(...) - * methods that can be used to make getting paramaterized (as if by - * MessageFormat) Strings easier. - * - *

  • Swing Usage:
    - * If you are setting the text fields on Swing objects, the - * set(...) methods of this class can help you. Here is - * an example: - *

    - * - * I18n i18n = Environment.getI18n();
    - * JButton myButton = new JButton();
    - * I18n.set(this, "myButton", myButton);
    - *
    - *

    - * This will get the string information (both tool tip and text) from - * the appropriate ResourceBundle and set the button's slots with it. - *

    - * Note that in this example the field parameter to the - * set(...) method is the name of the field that holds - * the object being setup. For these methods this is a convention - * rather than a requirement. However, it suggested that you maintain - * this convention because doing so makes it clearer what is going on - * and because it is most similar to how the calls are made in the - * reflective case below. - *

  • Reflective Calls:
    - * For the typical uses of this class, there are two calls that can - * make things very easy, by doing a bunch of the work for you. In - * most implementations if this interface, they will accomplish this - * via reflection under-the-hood. Here are some examples: - *

    - * - * public class MyClass {
    - *   JButton myButton = new JButton();
    - *   public MyClass() {
    - *     Environment.getI18n().set(this, "myButton");
    - *   }
    - * }
    - *
    - *

    - * This code will setup the properties of the object held by the - * myButton variable, without the programmer having to - * do much at all. Here is an example of the other reflective method: - *

    - * - * public class MyClass {
    - *   JButton myButton = new JButton();
    - *   JLabel myLabel = new JLabel(); - *   public MyClass() {
    - *     Environment.getI18n().fill(this);
    - *   }
    - * }
    - *
    - *

    - * Here we can see that a single call is filling in all of the text - * for all of the relevant objects, in this case both - * myButton and myLabel. - *

- *

- * In case you were wondering, the oft used I18n abbreviation - * comes from the 18 characters between the 'I' and the 'n' in the - * word Internationalization. - * - * @see com.bbn.openmap.Environment - * @see BasicI18n - */ -public interface I18n { - - //Types: - //////// - - /** - * Primary type for a given field (default if types aren't - * applicable). - */ - public final int TEXT = 1; - /** Title for components where that is appropriate. */ - public final int TITLE = 2; - /** Tooltip for a given field. */ - public final int TOOLTIP = 3; - /** Mnemonic for a given field. */ - public final int MNEMONIC = 4; - - /** - * Get the string associated with the given object/field (Defaults - * to TEXT for the type). - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the String or the Swing object that - * uses the String (like a button or a label). - * @param defaultString what to use if the resource can't be found. - */ - public String get(Object requestor, String field, String defaultString); - - /** - * Get the string associated with the given object/field/type. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the Swing object that uses the String - * (like a button or a label). - * @param type which specific slot in the Swing object the string - * pertains to. One of TEXT, TOOLTIP or MNEMONIC. - * @param defaultString what to use if the resource can't be found. - */ - public String get(Object requestor, String field, int type, - String defaultString); - - /** - * Get the string associated with the given class/field (Defaults - * to TEXT for the type). - * - * @param requestor the class of the object containing the code - * requesting the String (typically Foo.class). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the String or the Swing object that - * uses the String (like a button or a label). - * @param defaultString what to use if the resource can't be found. - */ - public String get(Class requestor, String field, String defaultString); - - /** - * Get the string associated with the given class/field/type. - * - * @param requestor the classof the object containing the code - * requesting the String (typically Foo.class). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the Swing object that uses the String - * (like a button or a label). - * @param type which specific slot in the Swing object the string - * pertains to. One of TEXT, TOOLTIP or MNEMONIC. - * @param defaultString what to use if the resource can't be found. - */ - public String get(Class requestor, String field, int type, - String defaultString); - - //Methods making it easier to use MessageFormat: - //////////////////////////////////////////////// - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, String defaultString, - Object param1); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, int type, - String defaultString, Object param1); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, String defaultString, - Object param1); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, int type, - String defaultString, Object param1); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, String defaultString, - Object param1, Object param2); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, int type, - String defaultString, Object param1, Object param2); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, String defaultString, - Object param1, Object param2); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, int type, - String defaultString, Object param1, Object param2); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, String defaultString, - Object[] params); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Object requestor, String field, int type, - String defaultString, Object[] params); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, String defaultString, - Object[] params); - - /** - * Method to get a parameterized String, as if by MessageFormat. - * - * @see java.text.MessageFormat - */ - public String get(Class requestor, String field, int type, - String defaultString, Object[] params); - - //Methods fill setting the textual properties of common Swing - // components: - ///////////////////////////////////////////////////////////////////////// - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JLabel comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JButton comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JMenu comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JMenuItem comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JDialog comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JFrame comp); - - /** - * Set the textual properties from values in the appropriate - * ResourceBundle. - *

- * Note: This method just looks for a TitledBorder on the - * component. - * - * @param requestor object containing the code requesting the - * String (typically this). - * @param field the field the String belongs to. Typically this will - * be the variable name referring to the comp parameter. - * @param comp the component whose properties are being set. - */ - public void set(Object requestor, String field, JComponent comp); - - //Methods for filling in strings using reflection: - ////////////////////////////////////////////////// - - /** - * Set the textual properties on a Swing component that is a - * member of a given class, from values in the ResourceBundle - * associated with that class. Note that the field must contain an - * object of a known type (see the other set(...) methods of this - * class). - *

- * The setting of the values of this field will be accomplished by - * calling the appropriate set(...) method on this class. - * - * @param requestor object containing the code requesting the - * Component setup (typically this). - * @param field the variable name of the component being setup. - */ - public void set(Object requestor, String field); - - /** - * Fill in all of the fields of the given object that are of known - * types (see the set(...) methods of this class) with values - * obtained from the appropriate ResourceBundle. - *

- * The setting of the values of this field will be accomplished by - * calling the appropriate set(...) method on this class. - */ - public void fill(Object requestor); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/ISwingWorker.java b/src/core/src/main/java/com/bbn/openmap/util/ISwingWorker.java deleted file mode 100644 index da2287180..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/ISwingWorker.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.util; - -/** - * Interface that describes kinds of SwingWorkers that layers might want to use. - * - * @author rshapiro - */ -public interface ISwingWorker { - - /** - * Compute the value to be returned by the get method. - * - * @return the get method return - */ - public T construct(); - - /** - * Called on the event dispatching thread (not on the worker thread) after - * the construct method has returned. - */ - public void finished(); - - /** - * A new method that interrupts the worker thread. Call this method to force - * the worker to stop what it's doing. - */ - public void interrupt(); - - public boolean isInterrupted(); - - /** - * Return the value created by the construct method. Returns - * null if either the constructing thread or the current thread was - * interrupted before a value was produced. - * - * @return the value created by the construct method - */ - public T get(); - - /** - * Start the worker thread. - */ - public void start(); - - /** - * For compatibility with old versions of SwingWorker, calls start(). - */ - public void execute(); - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/MoreMath.java b/src/core/src/main/java/com/bbn/openmap/util/MoreMath.java deleted file mode 100644 index 1c311f69c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/MoreMath.java +++ /dev/null @@ -1,563 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MoreMath.java,v $ -// $RCSfile: MoreMath.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * MoreMath provides functions that are not part of the standard Math - * class. - *

- * - *

- * 
- *  Functions:
- *       asinh(float x) - hyperbolic arcsine
- *       sinh(float x) - hyperbolic sine
- * 
- *  Need to Implement:
- *  Function                Definition                              
- *  Hyperbolic cosine       (eˆx+eˆ-x)/2                            
- *  Hyperbolic tangent      (eˆx-eˆ-x)/(eˆx+eˆ-x)                   
- *  Hyperbolic arc cosine   2 log  (sqrt((x+1)/2) + sqrt((x-1)/2))  
- *  Hyperbolic arc tangent  (log  (1+x) - log (1-x))/2
- *  
- * 
- */ -public class MoreMath { - - /** - * 2*Math.PI - */ - final public static transient float TWO_PI = (float) Math.PI * 2.0f; - - /** - * 2*Math.PI - */ - final public static transient double TWO_PI_D = Math.PI * 2.0d; - - /** - * Math.PI/2 - */ - final public static transient float HALF_PI = (float) Math.PI / 2.0f; - - /** - * Math.PI/2 - */ - final public static transient double HALF_PI_D = Math.PI / 2.0d; - - final public static double EQUIVALENT_TOLERANCE = 0.0000001; - - // cannot construct - private MoreMath() {} - - /** - * Checks if a ~= b. Use this to test equality of floating point - * numbers. - *

- * - * @param a double - * @param b double - * @param epsilon the allowable error - * @return boolean - */ - final public static boolean approximately_equal(double a, double b, - double epsilon) { - return (Math.abs(a - b) <= epsilon); - } - - /** - * Checks if a ~= b. Use this to test equality of floating point - * numbers against EQUIVALENT_TOLERANCE. - *

- * - * @param a double - * @param b double - * @return boolean - */ - final public static boolean approximately_equal(double a, double b) { - return (Math.abs(a - b) <= EQUIVALENT_TOLERANCE); - } - - /** - * Checks if a ~= b. Use this to test equality of floating point - * numbers. - *

- * - * @param a float - * @param b float - * @param epsilon the allowable error - * @return boolean - */ - final public static boolean approximately_equal(float a, float b, - float epsilon) { - return (Math.abs(a - b) <= epsilon); - } - - /** - * Hyperbolic arcsin. - *

- * Hyperbolic arc sine: log (x+sqrt(1+x^2)) - * - * @param x float - * @return float asinh(x) - */ - public static final float asinh(float x) { - return (float) Math.log(x + Math.sqrt(x * x + 1)); - } - - /** - * Hyperbolic arcsin. - *

- * Hyperbolic arc sine: log (x+sqrt(1+x^2)) - * - * @param x double - * @return double asinh(x) - */ - public static final double asinh(double x) { - return (double) Math.log(x + Math.sqrt(x * x + 1)); - } - - // HACK - are there functions that already exist? - /** - * Return sign of number. - * - * @param x short - * @return int sign -1, 1 - */ - public static final int sign(short x) { - return (x < 0) ? -1 : 1; - } - - /** - * Return sign of number. - * - * @param x int - * @return int sign -1, 1 - */ - public static final int sign(int x) { - return (x < 0) ? -1 : 1; - } - - /** - * Return sign of number. - * - * @param x long - * @return int sign -1, 1 - */ - public static final int sign(long x) { - return (x < 0) ? -1 : 1; - } - - /** - * Return sign of number. - * - * @param x float - * @return int sign -1, 1 - */ - public static final int sign(float x) { - return (x < 0f) ? -1 : 1; - } - - /** - * Return sign of number. - * - * @param x double - * @return int sign -1, 1 - */ - public static final int sign(double x) { - return (x < 0d) ? -1 : 1; - } - - /** - * Check if number is odd. - * - * @param x short - * @return boolean - */ - public static final boolean odd(short x) { - return !even(x); - } - - /** - * Check if number is odd. - * - * @param x int - * @return boolean - */ - public static final boolean odd(int x) { - return !even(x); - } - - /** - * Check if number is odd. - * - * @param x long - * @return boolean - */ - public static final boolean odd(long x) { - return !even(x); - } - - /** - * Check if number is even. - * - * @param x short - * @return boolean - */ - public static final boolean even(short x) { - return ((x & 0x1) == 0); - } - - /** - * Check if number is even. - * - * @param x int - * @return boolean - */ - public static final boolean even(int x) { - return ((x & 0x1) == 0); - } - - /** - * Check if number is even. - * - * @param x long - * @return boolean - */ - public static final boolean even(long x) { - return ((x & 0x1) == 0); - } - - /** - * Converts a byte in the range of -128 to 127 to an int in the - * range 0 - 255. - * - * @param b (-128 <= b <= 127) - * @return int (0 <= b <= 255) - */ - public static final int signedToInt(byte b) { - return ((int) b & 0xff); - } - - /** - * Converts a short in the range of -32768 to 32767 to an int in - * the range 0 - 65535. - * - * @param w (-32768 <= b <= 32767) - * @return int (0 <= b <= 65535) - */ - public static final int signedToInt(short w) { - return ((int) w & 0xffff); - } - - /** - * Convert an int in the range of -2147483648 to 2147483647 to a - * long in the range 0 to 4294967295. - * - * @param x (-2147483648 <= x <= 2147483647) - * @return long (0 <= x <= 4294967295) - */ - public static final long signedToLong(int x) { - return ((long) x & 0xFFFFFFFFL); - } - - /** - * Converts an int in the range of 0 - 65535 to an int in the - * range of 0 - 255. - * - * @param w int (0 <= w <= 65535) - * @return int (0 <= w <= 255) - */ - public static final int wordToByte(int w) { - return w >> 8; - } - - /** - * Build short out of bytes (in big endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return short - */ - public static final short BuildShortBE(byte bytevec[], int offset) { - return (short) (((int) (bytevec[0 + offset]) << 8) | (signedToInt(bytevec[1 + offset]))); - } - - /** - * Build short out of bytes (in little endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return short - */ - public static final short BuildShortLE(byte bytevec[], int offset) { - return (short) (((int) (bytevec[1 + offset]) << 8) | (signedToInt(bytevec[0 + offset]))); - } - - /** - * Build short out of bytes. - * - * @param bytevec bytes - * @param offset byte offset - * @param MSBFirst BE or LE? - * @return short - */ - public static final short BuildShort(byte bytevec[], int offset, - boolean MSBFirst) { - if (MSBFirst) { - return (BuildShortBE(bytevec, offset)); - } else { - return (BuildShortLE(bytevec, offset)); - } - } - - /** - * Build short out of bytes (in big endian order). - * - * @param bytevec bytes - * @param MSBFirst BE or LE? - * @return short - */ - - public static final short BuildShortBE(byte bytevec[], boolean MSBFirst) { - return BuildShortBE(bytevec, 0); - } - - /** - * Build short out of bytes (in little endian order). - * - * @param bytevec bytes - * @param MSBFirst BE or LE? - * @return short - */ - public static final short BuildShortLE(byte bytevec[], boolean MSBFirst) { - return BuildShortLE(bytevec, 0); - } - - /** - * Build short out of bytes. - * - * @param bytevec bytes - * @param MSBFirst BE or LE? - * @return short - */ - public static final short BuildShort(byte bytevec[], boolean MSBFirst) { - return BuildShort(bytevec, 0, MSBFirst); - } - - /** - * Build int out of bytes (in big endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return int - */ - public static final int BuildIntegerBE(byte bytevec[], int offset) { - return (((int) (bytevec[0 + offset]) << 24) - | (signedToInt(bytevec[1 + offset]) << 16) - | (signedToInt(bytevec[2 + offset]) << 8) | (signedToInt(bytevec[3 + offset]))); - } - - /** - * Build int out of bytes (in little endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return int - */ - public static final int BuildIntegerLE(byte bytevec[], int offset) { - return (((int) (bytevec[3 + offset]) << 24) - | (signedToInt(bytevec[2 + offset]) << 16) - | (signedToInt(bytevec[1 + offset]) << 8) | (signedToInt(bytevec[0 + offset]))); - } - - /** - * Build int out of bytes. - * - * @param bytevec bytes - * @param offset byte offset - * @param MSBFirst BE or LE? - * @return int - */ - public static final int BuildInteger(byte bytevec[], int offset, - boolean MSBFirst) { - if (MSBFirst) - return BuildIntegerBE(bytevec, offset); - else - return BuildIntegerLE(bytevec, offset); - } - - /** - * Build int out of bytes (in big endian order). - * - * @param bytevec bytes - * @return int - */ - public static final int BuildIntegerBE(byte bytevec[]) { - return BuildIntegerBE(bytevec, 0); - } - - /** - * Build int out of bytes (in little endian order). - * - * @param bytevec bytes - * @return int - */ - public static final int BuildIntegerLE(byte bytevec[]) { - return BuildIntegerLE(bytevec, 0); - } - - /** - * Build int out of bytes. - * - * @param bytevec bytes - * @param MSBFirst BE or LE? - * @return int - */ - public static final int BuildInteger(byte bytevec[], boolean MSBFirst) { - if (MSBFirst) - return BuildIntegerBE(bytevec, 0); - else - return BuildIntegerLE(bytevec, 0); - } - - /** - * Build long out of bytes (in big endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return long - */ - public static final long BuildLongBE(byte bytevec[], int offset) { - return (((long) signedToInt(bytevec[0 + offset]) << 56) - | ((long) signedToInt(bytevec[1 + offset]) << 48) - | ((long) signedToInt(bytevec[2 + offset]) << 40) - | ((long) signedToInt(bytevec[3 + offset]) << 32) - | ((long) signedToInt(bytevec[4 + offset]) << 24) - | ((long) signedToInt(bytevec[5 + offset]) << 16) - | ((long) signedToInt(bytevec[6 + offset]) << 8) | ((long) signedToInt(bytevec[7 + offset]))); - } - - /** - * Build long out of bytes (in little endian order). - * - * @param bytevec bytes - * @param offset byte offset - * @return long - */ - public static final long BuildLongLE(byte bytevec[], int offset) { - return (((long) signedToInt(bytevec[7 + offset]) << 56) - | ((long) signedToInt(bytevec[6 + offset]) << 48) - | ((long) signedToInt(bytevec[5 + offset]) << 40) - | ((long) signedToInt(bytevec[4 + offset]) << 32) - | ((long) signedToInt(bytevec[3 + offset]) << 24) - | ((long) signedToInt(bytevec[2 + offset]) << 16) - | ((long) signedToInt(bytevec[1 + offset]) << 8) | ((long) signedToInt(bytevec[0 + offset]))); - } - - /** - * Build long out of bytes. - * - * @param bytevec bytes - * @param offset byte offset - * @param MSBFirst BE or LE? - * @return long - */ - public static final long BuildLong(byte bytevec[], int offset, - boolean MSBFirst) { - if (MSBFirst) - return BuildLongBE(bytevec, offset); - else - return BuildLongLE(bytevec, offset); - } - - /** - * Build long out of bytes (in big endian order). - * - * @param bytevec bytes - * @return long - */ - public static final long BuildLongBE(byte bytevec[]) { - return BuildLongBE(bytevec, 0); - } - - /** - * Build long out of bytes (in little endian order). - * - * @param bytevec bytes - * @return long - */ - public static final long BuildLongLE(byte bytevec[]) { - return BuildLongLE(bytevec, 0); - } - - /** - * Build long out of bytes. - * - * @param bytevec bytes - * @param MSBFirst BE or LE? - * @return long - */ - public static final long BuildLong(byte bytevec[], boolean MSBFirst) { - if (MSBFirst) - return BuildLongBE(bytevec, 0); - else - return BuildLongLE(bytevec, 0); - } - - /** - * lat just less than 90 degrees. - * @param val lat value to test - * @return value just less than... - */ - public static double latJLT90(double val) { - return justLessThan(val, 90, .00001); - } - - /** - * Return value just less than provided value, in positive and negative terms. - * @param val value to test - * @param lessThan abs value to test against - * @param howMuchLess how much to move val to zero based on comparison to less than - * @return val, or adjusted val - */ - public static double justLessThan(double val, double lessThan, double howMuchLess) { - if (val >= lessThan) { - val = lessThan = howMuchLess; - } else if (val <= -lessThan) { - val = -lessThan + howMuchLess; - } - return val; - } - - /* - * public static final void main(String[] args) { byte[] b = new - * byte[4]; b[0] = (byte)0xff; b[1] = (byte)0x7f; - * com.bbn.openmap.util.Debug.output("32767="+BuildShortLE(b, 0)); - * b[0] = (byte)0x7f; b[1] = (byte)0xff; - * com.bbn.openmap.util.Debug.output("32767="+BuildShortBE(b, 0)); - * b[1] = (byte)0xff; b[2] = (byte)0xff; b[3] = (byte)0xff; - * com.bbn.openmap.util.Debug.output("2147483647="+BuildIntegerBE(b, - * 0)); - * com.bbn.openmap.util.Debug.output("maxuint="+signedToLong(0xffffffff)); } - */ -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/OMLoggingFormatter.java b/src/core/src/main/java/com/bbn/openmap/util/OMLoggingFormatter.java deleted file mode 100644 index 378028cae..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/OMLoggingFormatter.java +++ /dev/null @@ -1,69 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: OMLoggingFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2006/12/15 18:39:55 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.util; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.logging.Formatter; -import java.util.logging.LogRecord; - -public class OMLoggingFormatter extends Formatter { - - /** - * Format the given LogRecord. - * - * @param record the log record to be formatted. - * @return a formatted log record - */ - public synchronized String format(LogRecord record) { - StringBuffer sb = new StringBuffer(); - if (record.getSourceClassName() != null) { - sb.append(record.getSourceClassName()); - } else { - sb.append(record.getLoggerName()); - } - if (record.getSourceMethodName() != null) { - sb.append("."); - sb.append(record.getSourceMethodName()).append("() "); - } - String message = formatMessage(record); - sb.append(record.getLevel().getLocalizedName()); - sb.append(": "); - sb.append(message); - sb.append("\n"); - if (record.getThrown() != null) { - try { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - record.getThrown().printStackTrace(pw); - pw.close(); - sb.append(sw.toString()); - } catch (Exception ex) { - } - } - return sb.toString(); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/Palette.java b/src/core/src/main/java/com/bbn/openmap/util/Palette.java deleted file mode 100644 index 0cb926896..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Palette.java +++ /dev/null @@ -1,29 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/Palette.java,v $ -// $RCSfile: Palette.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * - */ -public interface Palette { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/PaletteHelper.java b/src/core/src/main/java/com/bbn/openmap/util/PaletteHelper.java deleted file mode 100644 index 3bb9f17c6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/PaletteHelper.java +++ /dev/null @@ -1,408 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/PaletteHelper.java,v $ -// $RCSfile: PaletteHelper.java,v $ -// $Revision: 1.6 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/* AWT & Schwing */ - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentListener; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingConstants; -import javax.swing.event.InternalFrameListener; - -import com.bbn.openmap.Layer; - -/** - * Helps create palette GUI widgets. - */ -public class PaletteHelper { - - /** - * This class has only static methods, so there isn't any need to - * instantiate an object. - */ - private PaletteHelper() {} - - /** - * Create a panel containing a checkbox. - * - * @param boxlabel the string to use for the box title - * @param buttons the list of button names - * @param checked the initial state of each checkbox item - * @param al the actionlistener to invoke for a button. the - * actioncommand is set to a string containing the integer - * index of the button. - * @return the JPanel the the buttons are placed in - * @see javax.swing.AbstractButton#setActionCommand(String) - * @see javax.swing.JCheckBox - */ - public static JPanel createCheckbox(String boxlabel, String[] buttons, - boolean[] checked, ActionListener al) { - - JPanel jp = createPaletteJPanel(boxlabel); - for (int j = 0; j < buttons.length; j++) { - JCheckBox jcb = new JCheckBox(buttons[j]); - jcb.setActionCommand(Integer.toString(j));//index of - // checked - if (al != null) - jcb.addActionListener(al); - jcb.setSelected(checked[j]); - jp.add(jcb); - } - return jp; - } - - /** - * Create a panel containing a radiobox. - * - * @param boxlabel the string to use for the box title - * @param buttons the list of button names - * @param initiallySelected the index of the initially selected - * button. -1 for no button initially selected. - * @param al the actionlistener to invoke for a button. the - * actioncommand is set to a string containing the integer - * index of the button. - * @return the JPanel the the buttons are placed in - * @see javax.swing.AbstractButton#setActionCommand(String) - * @see javax.swing.ButtonGroup - */ - public static JPanel createRadiobox(String boxlabel, String[] buttons, - int initiallySelected, ActionListener al) { - - JPanel jp = createPaletteJPanel(boxlabel); - - ButtonGroup buttongroup = new ButtonGroup(); - - for (int j = 0; j < buttons.length; j++) { - JRadioButton jrb = new JRadioButton(buttons[j]); - jrb.setActionCommand("" + j);//index in list - jp.add(jrb); - buttongroup.add(jrb); - if (al != null) { - jrb.addActionListener(al); - } - if (j == initiallySelected) { - jrb.setSelected(true); - } else { - jrb.setSelected(false); - } - } - return jp; - } - - /** - * Create a panel that does horizontal layout - * - * @param title the title of the panel (null allowed) - * @return the panel that got created - */ - public static JPanel createHorizontalPanel(String title) { - JPanel panel = new JPanel(); - // panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); - panel.setLayout(new GridLayout(1, 0)); - if (title != null) { - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - title)); - } else { - panel.setBorder(BorderFactory.createEtchedBorder()); - } - return panel; - } - - /** - * Create a panel that does vertical layout - * - * @param title the title of the panel (null allowed) - * @return the panel that got created - */ - public static JPanel createVerticalPanel(String title) { - JPanel panel = new JPanel(); - // panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - panel.setLayout(new GridLayout(0, 1)); - if (title != null) { - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - title)); - } else { - panel.setBorder(BorderFactory.createEtchedBorder()); - } - return panel; - } - - /** - * Create a panel with a border and title - * - * @param title the title of the panel (null allowed) - * @return the panel that got created - */ - public static JPanel createPaletteJPanel(String title) { - JPanel panel = new JPanel(); - - if (title != null) { - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), - title)); - } else { - panel.setBorder(BorderFactory.createEtchedBorder()); - } - - panel.setLayout(new GridLayout(0, 1)); - return panel; - } - - /** - * Create and add a text entry field to a JComponent. - * - * @param title the title of the frame - * @param entry the name of the entry field - * @param parent the component to add ourselves to - * @return the text field - */ - public static JTextField createTextEntry(String title, String entry, - JComponent parent) { - - JPanel pal = PaletteHelper.createHorizontalPanel(null); - JLabel label = new JLabel(title); - label.setHorizontalTextPosition(JLabel.RIGHT); - JTextField tf = new JTextField(entry); - label.setLabelFor(tf); - pal.add(label); - pal.add(tf); - parent.add(pal); - return tf; - } - - /** - * Create and add a text area to a JComponent. - * - * @param title the title of the frame - * @param entry the name of the entry field - * @param parent the component to add ourselves to - * @param rows the number of rows - * @param cols the number of columns - * @return the text area - */ - public static JTextArea createTextArea(String title, String entry, - JComponent parent, int rows, int cols) { - JPanel pal = PaletteHelper.createHorizontalPanel(null); - JLabel label = new JLabel(title); - label.setHorizontalTextPosition(JLabel.RIGHT); - JTextArea ta = new JTextArea(entry, rows, cols); - JScrollPane jsp = new JScrollPane(ta); - label.setLabelFor(jsp); - pal.add(label); - pal.add(jsp); - parent.add(pal); - return ta; - } - - /** - * Get a layer's associated palette as an internal window - * - * @param layer the layer to get the palette for - * @param ifl the listener to associate with the palette - * @return the frame that the palette is in - */ - public static JInternalFrame getPaletteInternalWindow( - Layer layer, - InternalFrameListener ifl) { - return getPaletteInternalWindow(layer.getGUI(), layer.getName() - + " Palette", ifl); - } - - /** - * Get a layer's associated palette as a top-level window - * - * @param layer the layer to get the palette for - * @param cl the listener to associate with the palette - * @return the frame that the palette is in - */ - public static JFrame getPaletteWindow(Layer layer, ComponentListener cl) { - Component layerGUI = getLayerGUIComponent(layer); - - JPanel dismissBox = new JPanel(); - dismissBox.setLayout(new BoxLayout(dismissBox, BoxLayout.X_AXIS)); - dismissBox.setAlignmentX(Component.LEFT_ALIGNMENT); - dismissBox.setAlignmentY(Component.BOTTOM_ALIGNMENT); - dismissBox.add(Box.createHorizontalGlue()); - JButton dismiss = new JButton("Close"); - dismissBox.add(dismiss); - dismissBox.add(Box.createHorizontalGlue()); - - JPanel pane = new JPanel(); - pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); - pane.setAlignmentX(Component.CENTER_ALIGNMENT); - pane.setAlignmentY(Component.BOTTOM_ALIGNMENT); - pane.add(layerGUI); - pane.add(dismissBox); - - final JFrame frame = getPaletteWindow(pane, layer.getName() - + " Palette", cl); - - dismiss.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - frame.setVisible(false); - } - }); - return frame; - } - - /** - * Get a Component that represents a layer's GUI. - * - * @param layer the layer to get the palette for - * @return the Component that represents the GUI for the layer. - */ - public static Component getLayerGUIComponent(Layer layer) { - - Component pal = layer.getGUI(); - if (pal == null) { - pal = new JLabel("No Palette"); - } - - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - p.setAlignmentX(Component.LEFT_ALIGNMENT); - p.setAlignmentY(Component.BOTTOM_ALIGNMENT); - p.add(pal); - - return p; - } - - /** - * Get a layer's associated palette as an internal window - * - * @param gui the Component to place in the window - * @param windowName the title of the palette - * @param ifl the listener to associate with the palette - * @return the frame that the palette is in - */ - public static JInternalFrame getPaletteInternalWindow( - Component gui, - String windowName, - InternalFrameListener ifl) { - - JInternalFrame paletteWindow; - - // create the palette's scroll pane - JScrollPane scrollPane = new JScrollPane(gui, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - - // create the palette internal window - paletteWindow = new JInternalFrame(windowName, true, //resizable - true, //closable - false, //maximizable - true //iconifiable - ); - - // add a window listener that destroys the palette when - // the window is closed - paletteWindow.addInternalFrameListener(ifl); - paletteWindow.getContentPane().add(scrollPane); - paletteWindow.setOpaque(true); - - //layout all the components - paletteWindow.pack(); - - return paletteWindow; - } - - /** - * Get a layer's associated palette as a top-level window - * - * @param gui the Component to place in the window - * @param windowName the title of the window - * @param cl the listener to associate with the palette - * @return the frame that the palette is in - */ - public static JFrame getPaletteWindow(Component gui, String windowName, - ComponentListener cl) { - - JScrollPane scrollPane = new JScrollPane(gui, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - - // create the palette internal window - JFrame paletteWindow = new JFrame(windowName); - - paletteWindow.addComponentListener(cl); - paletteWindow.getContentPane().add(scrollPane); - //layout all the components - paletteWindow.pack(); - return paletteWindow; - } - - /** - * Get a layer's associated palette as a top-level window - * - * @param gui the Component to place in the window - * @param windowName the title of the frame - * @param cl the listener to associate with the palette - * @return the frame that the palette is in - */ - public static JFrame getNoScrollPaletteWindow(Component gui, - String windowName, - ComponentListener cl) { - - JPanel pane = new JPanel(); - pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); - pane.setAlignmentX(Component.CENTER_ALIGNMENT); - pane.setAlignmentY(Component.BOTTOM_ALIGNMENT); - pane.add(gui); - JFrame paletteWindow = new JFrame(windowName); - paletteWindow.addComponentListener(cl); - paletteWindow.getContentPane().add(pane); - paletteWindow.pack(); - - return paletteWindow; - } - - public static JComponent getToolBarFill(int orientation) { - Dimension dim = null; - if (orientation == SwingConstants.HORIZONTAL) { - dim = new Dimension(2, 1); - } else { - dim = new Dimension(1, 2); - } - return new Box.Filler(dim, dim, dim); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/PooledSwingWorker.java b/src/core/src/main/java/com/bbn/openmap/util/PooledSwingWorker.java deleted file mode 100644 index 0c2f30f2d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/PooledSwingWorker.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.bbn.openmap.util; - - -/** - * @param The type of value computed by the task. - * - * Use thread pool to run tasks that compute a value. - * - * Thanks to Carsten for cleaning this up. - */ -public abstract class PooledSwingWorker extends SwingWorker { - - /** - * Start a thread that will call the construct method and then - * exit. - */ - public PooledSwingWorker() { - super(); - } - - /** - * Start the worker thread. - */ - public void start() { - TaskService.singleton().spawn(getFuture()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/PropUtils.java b/src/core/src/main/java/com/bbn/openmap/util/PropUtils.java deleted file mode 100644 index a467f4b3d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/PropUtils.java +++ /dev/null @@ -1,1052 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/PropUtils.java,v -// $ -// $RCSfile: PropUtils.java,v $ -// $Revision: 1.16 $ -// $Date: 2008/09/26 12:07:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/* Java Core */ -import java.awt.Color; -import java.awt.Paint; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JFileChooser; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; - -public class PropUtils { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.util.PropUtils"); - - /** - * Parse a list of marker names from a space separated list within a String. - *

- * - * @param markerList a string containing a space delimited list of marker - * names. - * @return Vector of marker names. - */ - public static List parseSpacedMarkers(String markerList) { - return parseMarkers(markerList, " "); - } - - /** - * Parse a list of marker names from a space separated list within a String. - *

- * - * @param markerList a string containing a list of things to be parsed. - * @param delim the list of tokens to look for which separate the list - * elements. - * @return Vector of marker names. - */ - public static List parseMarkers(String markerList, String delim) { - List markers = null; - - if (markerList == null) { - logger.fine("marker list null!"); - return new ArrayList<>(0); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("parsing marker list |" + markerList + "|"); - } - - // First, get rid of the quotation marks; - markerList = markerList.replace('\"', '\0'); - // Next, tokenize the space delimited string - StringTokenizer tokens = new StringTokenizer(markerList, delim); - markers = new ArrayList<>(tokens.countTokens()); - while (tokens.hasMoreTokens()) { - String name = tokens.nextToken().trim(); - markers.add(name); - } - return markers; - } - - /** - * A string used in marker names for property editors, when a custom editor - * used by an Inspector can set several top-level properties. - */ - public final static String DUMMY_MARKER_NAME = "DUMMY_MARKER_NAME"; - /** Borrowed from Properties.java */ - public static final String keyValueSeparators = "=: \t\r\n\f"; - /** Borrowed from Properties.java */ - public static final String strictKeyValueSeparators = "=:"; - /** Borrowed from Properties.java */ - public static final String whiteSpaceChars = " \t\r\n\f"; - /** As defined in the OGC Web Mapping Test bed. */ - public static final String propertySeparators = "&"; - - /** - * Take a property list, defined in a single string, and return a Properties - * object. The properties, as key-value pairs, are separated by another type - * of symbol. In this method, the key-values are assumed to be separated - * from other key-value pairs by PropUtils.propertySeparators String - * characters, and each key is separated from its value by any character in - * the PropUtils.keyValueSeparators list. - * - * @param list the properties list string. - * @return Properties object containing keys and values. - * @throws PropertyStringFormatException if a key doesn't have a value. - */ - public static Properties parsePropertyList(String list) throws PropertyStringFormatException { - return parsePropertyList(list, propertySeparators, keyValueSeparators); - } - - /** - * Take a property list, defined in a single string, and return a Properties - * object. The properties, as key-value pairs, are separated by another type - * of symbol. - * - * @param list the properties list string. - * @return Properties object containing keys and values. - * @param propertySeparators the key-values are assumed to be separated from - * other key-value pairs by any character in this String. - * @param keyValueSeparators each key is separated from its value by any - * character in this String. - * @throws PropertyStringFormatException if a key doesn't have a value. - */ - public static Properties parsePropertyList(String list, String propertySeparators, - String keyValueSeparators) - throws PropertyStringFormatException { - - Properties props = new Properties(); - - List keyValuePairs = parseMarkers(list, propertySeparators); - for (int i = 0; i < keyValuePairs.size(); i++) { - // Next, tokenize the space delimited string - StringTokenizer tokens = new StringTokenizer(keyValuePairs.get(i), keyValueSeparators); - - try { - String key = tokens.nextToken().trim(); - String value = tokens.nextToken().trim(); - props.put(key, value); - } catch (NoSuchElementException nsee) { - throw new PropertyStringFormatException(list); - } - } - return props; - } - - /** - * Copy the contents from one properties object to another. - * - * @param from the source Properties object. - * @param to the destination Properties object. - */ - public static void copyProperties(Properties from, Properties to) { - Enumeration keys = from.keys(); - - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - to.put(key, from.getProperty(key)); - } - } - - /** - * Load the named file from the named directory into the given - * Properties instance. If the file is not found a warning is - * issued. If an IOException occurs, a fatal error is printed. - * - * @param props the instance to receive the loaded properties - * @param dir the directory where the properties file resides - * @param file the name of the file - * @return true if the properties file exists and was loaded. - */ - public static boolean loadProperties(Properties props, String dir, String file) { - File propsFile = new File(dir, file); - - try { - InputStream propsStream = new FileInputStream(propsFile); - props.load(propsStream); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + propsFile); - } - return true; - - } catch (java.io.FileNotFoundException e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("File not found - \"" + propsFile + "\""); - } - } catch (java.io.IOException e) { - logger.warning("Caught IO Exception reading \"" + propsFile + "\""); - e.printStackTrace(); - } catch (java.security.AccessControlException ace) { - } - return false; - } - - /** - * Loads properties from a java resource. This will load the named resource - * identifier into the given properties instance. - * - * @param properties the Properties instance to receive the properties. - * @param propsIn an InputStream to read properties from - * @return true if the properties file exists and was loaded. - */ - public static boolean loadProperties(Properties properties, InputStream propsIn) { - try { - properties.load(propsIn); - return true; - } catch (java.io.IOException e) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("Caught IOException loading properties from InputStream."); - } - return false; - } - } - - /** - * A function that brings up a file chooser window in order to have the user - * look for a valid Java properties file. - * - * @return properties object with selected file contents. - */ - public static Properties promptUserForProperties() { - JFileChooser fileChooser = new JFileChooser(); - int retvalue = fileChooser.showOpenDialog(null); - Properties props = new Properties(); - if (retvalue != JFileChooser.APPROVE_OPTION) { - return props; - } - try { - FileInputStream inputStream = new FileInputStream(fileChooser.getSelectedFile()); - props.load(inputStream); - return props; - } catch (Exception ioe) { - System.err.println("PropUtils.promptUserForProperties: Exception reading properties file."); - System.err.println(ioe.getMessage()); - ioe.printStackTrace(); - return props; - } - } - - /** - * It seems like every PropertyConsumer wrestles with having a prefix or - * not. This method lets you just get the prefix with a period on the end - * (for scoping purposes), or just returns an empty String. Either way, you - * get a String you can slap on the beginning of your defined property names - * to get a valid property based on what the prefix is. - * - * @param pc the PropertyConsumer to fetch from - * @return an empty string if no prefix, or the prefix with a period at the - * end - */ - public static String getScopedPropertyPrefix(PropertyConsumer pc) { - return getScopedPropertyPrefix(pc.getPropertyPrefix()); - } - - /** - * Given the string, check if it's null. If it isn't, check to see if it - * ends with a period, and do nothing if it does. If it doesn't end in a - * period, add one, and then return that. The returned string should be good - * for prepending to other properties. - * - * @param pre the string to check - * @return an empty string or one that ends with a period - */ - public static String getScopedPropertyPrefix(String pre) { - if (pre == null || pre.length() == 0) { - return ""; - } else if (pre.endsWith(".")) { - return pre; - } else { - return pre + "."; - } - } - - /** - * Should be called by a PropertyConsumer in the - * getPropertiesInfo(Properties) method to create a property marker name for - * a custom PropertyEditor that will modify several top-level properties, - * i.e. the com.bbn.openmap.omGraphics.DrawingAttributesPropertyEditor. - * - * @param realComponentPropertyPrefix the top-level prefix that the - * PropertyConsumer being set with the properties has. Can be null. - * @param anyDesiredScoper an additional scoping mechanism if there are more - * than one custom editors being used for a given getPropertyInfo - * call. - * @return The string that is used for a marker for a custom editor. - */ - public static String getDummyMarkerForPropertyInfo(String realComponentPropertyPrefix, - String anyDesiredScoper) { - return DUMMY_MARKER_NAME + (anyDesiredScoper != null ? anyDesiredScoper : "") + "." - + (realComponentPropertyPrefix != null ? realComponentPropertyPrefix : ""); - } - - /** - * Should be used inside a - * PropertyConsumerPropertyEditor.setProperties(String, Properties) method - * to set the real property prefix. The PropertyConsumer that the Inspector - * is looking at should use the getDummyMarker() call to create the marker - * for the getPropertyInfor(Properties) call. - * - * @param possibleDummyMarker string to check for DUMMY_MARKER_NAME, - * indicating that's a dummy - * @return the encoded 'real' property prefix for the PropertyConsumer - * embedded in the dummy marker, or the possibleDummyMarker if it's - * not a dummy marker. - */ - public static String decodeDummyMarkerFromPropertyInfo(String possibleDummyMarker) { - if (possibleDummyMarker != null && possibleDummyMarker.startsWith(DUMMY_MARKER_NAME)) { - int lastDot = possibleDummyMarker.lastIndexOf("."); - if (lastDot != -1) { - possibleDummyMarker = possibleDummyMarker.substring(lastDot + 1); - } - } - return possibleDummyMarker; - } - - /** - * It kills Properties to have null values set. You can wrap a property - * value in this in PropertyConsumer.getProperties() to not worry about it. - * - * @param prop property value to be set in properties after this call - * @return empty string if prop equals null, else returns what was passed in - */ - public static String unnull(Object prop) { - if (prop == null) { - return ""; - } - return prop.toString(); - } - - /** - * Takes a string of `;' separated paths and returns an array of parsed - * strings. NOTE: this method currently doesn't support appropriate quoting - * of the `;' character, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @return Array of strings representing paths. - */ - public static String[] initPathsFromProperties(Properties p, String propName) { - return initPathsFromProperties(p, propName, null); - } - - /** - * Takes a string of `;' separated paths and returns an array of parsed - * strings. NOTE: this method currently doesn't support appropriate quoting - * of the `;' character, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @param defaultPaths the value of the paths to set if the property doesn't - * exist, or if is doesn't contain anything. - * @return Array of strings representing paths. - */ - public static String[] initPathsFromProperties(Properties p, String propName, - String[] defaultPaths) { - String[] ret = stringArrayFromProperties(p, propName, ";"); - - if (ret == null) { - ret = defaultPaths; - } - - return ret; - } - - /** - * Return the first letter of the property specified by propName. If that - * value is null or has length of zero, the default char is returned. - * - * @param p properties to load from - * @param propName property name - * @param defaultValue default to use if property isn't found - * @return first char from property, or default. - */ - public static char charFromProperties(Properties p, String propName, char defaultValue) { - char ret = defaultValue; - String charString = p.getProperty(propName); - if (charString != null && charString.length() > 0) { - return charString.charAt(0); - } - return ret; - } - - /** - * Gets an integer out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return integer value associated with the property. - */ - public static int intFromProperties(Properties p, String propName, int defaultValue) { - int ret = defaultValue; - String intString = p.getProperty(propName); - - if (intString != null) { - try { - ret = Integer.parseInt(intString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets an float out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return float value associated with the property. - */ - public static float floatFromProperties(Properties p, String propName, float defaultValue) { - float ret = defaultValue; - String floatString = p.getProperty(propName); - - if (floatString != null) { - try { - ret = Float.parseFloat(floatString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets an boolean out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return boolean value associated with the property. - */ - public static boolean booleanFromProperties(Properties p, String propName, boolean defaultValue) { - boolean ret = defaultValue; - String booleanString = p.getProperty(propName); - if (booleanString != null) { - ret = booleanString.trim().equalsIgnoreCase("true"); - } - - return ret; - } - - /** - * Creates an object out of a property name. If anything fails, return null. - * - * @param p properties - * @param propName name of class to instantiate. - * @return null on failure, otherwise, a default constructed instance of the - * class named in the property. - */ - public static Object objectFromProperties(Properties p, String propName) { - - Object ret = null; - String objectName = p.getProperty(propName); - if (objectName != null) { - ret = ComponentFactory.create(objectName); - } - return ret; - } - - /** - * Takes a string of representing token separated properties and returns an - * array of parsed strings. NOTE: this method currently doesn't support - * appropriate quoting of the token, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @param tok the characters separating the strings. - * @return Array of strings between the tokens. - */ - public static String[] stringArrayFromProperties(Properties p, String propName, String tok) { - - String[] ret = null; - String raw = p.getProperty(propName); - - if (raw != null && raw.length() > 0) { - - try { - StringTokenizer token = new StringTokenizer(raw, tok); - int numPaths = token.countTokens(); - - ret = new String[numPaths]; - for (int i = 0; i < numPaths; i++) { - ret[i] = token.nextToken(); - } - return ret; - } catch (java.util.NoSuchElementException e) { - e.printStackTrace(); - } - } - return ret; - } - - /** - * Gets a double out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return double value associated with the property. - */ - public static double doubleFromProperties(Properties p, String propName, double defaultValue) { - double ret = defaultValue; - String doubleString = p.getProperty(propName); - - if (doubleString != null) { - try { - ret = Double.parseDouble(doubleString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets a long out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return long value associated with the property. - */ - public static long longFromProperties(Properties p, String propName, long defaultValue) { - long ret = defaultValue; - String longString = p.getProperty(propName); - - if (longString != null) { - try { - ret = Long.parseLong(longString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color to use if the property value doesn't work - * @return java.awt.Color - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault) - throws NumberFormatException { - return ColorFactory.parseColorFromProperties(p, propName, dfault, false); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color to use if the property value doesn't work - * @param forceAlpha force using alpha value - * @return java.awt.Color - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault, - boolean forceAlpha) throws NumberFormatException { - return ColorFactory.parseColorFromProperties(p, propName, dfault, forceAlpha); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color or paint to use if the property value doesn't work - * @return object of type of the default - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static T parseColorFromProperties(Properties p, String propName, T dfault) { - return ColorFactory.parseColorFromProperties(p, propName, dfault); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString the 24/32bit hex string value (ARGB) - * @param forceAlpha force using alpha value - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColor(String, boolean) - */ - public static Color parseColor(String colorString, boolean forceAlpha) - throws NumberFormatException { - return ColorFactory.parseColor(colorString, forceAlpha); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString the 24/32bit hex string value (ARGB) - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColor(String, boolean) - */ - public static Color parseColor(String colorString) throws NumberFormatException { - return ColorFactory.parseColor(colorString, false); - } - - /** - * Returns a string representing a color, properly buffered for zeros for - * different alpha values. - * - * @param color the source Color - * @return string for color with alpha values. - */ - public static String getProperty(Color color) { - StringBuffer hexstring = new StringBuffer(Integer.toHexString(color.getRGB())); - while (hexstring.length() < 8) { - hexstring.insert(0, '0'); - } - return hexstring.toString(); - } - - /** - * Converts a properties object to an array of Strings. The resulting array - * will consist of alternating key-value strings. - * - * @param props the properties object to convert. - * @return an array of Strings representing key-value pairs. - */ - public static String[] getPropertiesAsStringArray(Properties props) { - - int size = props.size(); - String[] ret = new String[size * 2]; // key and value - int count = 0; - Enumeration things = props.propertyNames(); - while (things.hasMoreElements()) { - ret[count] = (String) things.nextElement(); - ret[count + 1] = (String) props.getProperty(ret[count]); - count += 2; - } - return ret; - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. Resources are checked for in the general classpath. - * - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(String name) throws java.net.MalformedURLException { - return getResourceOrFileOrURL(null, name); - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. - * - * @param askingClass the object asking for the URL. - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(Object askingClass, String name) - throws java.net.MalformedURLException { - - return getResourceOrFileOrURL(askingClass.getClass(), name); - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. - * - * @param askingClass the class asking for the URL. Can be null. - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(Class askingClass, String name) - throws java.net.MalformedURLException { - - boolean DEBUG = logger.isLoggable(Level.FINE); - - if (name == null) { - if (DEBUG) - logger.fine("null file name"); - return null; - } - - URL retval = null; - if (DEBUG) - logger.fine("looking for " + name); - - if (askingClass != null) { - // First see if we have a resource by that name - if (DEBUG) - logger.fine("checking as resource"); - - retval = askingClass.getResource(name); - } - if (retval == null) { - // Check the general classpath... - if (DEBUG) - logger.fine("checking in general classpath"); - retval = Thread.currentThread().getContextClassLoader().getResource(name); - } - - // if (retval == null && !Environment.isApplet()) { - // // Check the classpath plus the share directory, which may - // // be in the openmap.jar file or in the development - // // environment. - // if (DEBUG) - // logger.fine("checking with ClassLoader"); - // retval = ClassLoader.getSystemResource("share/" + name); - // } - - if (retval == null && Environment.isApplet()) { - if (DEBUG) - logger.fine("checking with URLClassLoader"); - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - URLClassLoader ucl = URLClassLoader.newInstance(cba); - retval = ucl.getResource(name); - } - - // If there was no resource by that name available - if (retval == null) { - if (DEBUG) - logger.fine("not found as resource"); - - try { - java.io.File file = new java.io.File(name); - if (file.exists()) { - retval = file.toURI().toURL(); - if (DEBUG) - logger.fine("found as file :)"); - } else { - // Otherwise treat it as a raw URL. - if (DEBUG) - logger.fine("Not a file, checking as URL"); - retval = new URL(name); - java.io.InputStream is = retval.openStream(); - is.close(); - if (DEBUG) - logger.fine("OK as URL :)"); - } - } catch (java.io.IOException ioe) { - retval = null; - } catch (java.security.AccessControlException ace) { - logger.warning("AccessControlException trying to access " + name); - retval = null; - } catch (Exception e) { - logger.warning("caught exception " + e.getMessage()); - retval = null; - } - } - - if (DEBUG) { - if (retval != null) { - logger.fine("Resource " + name + "=" + retval.toString()); - } else { - logger.fine("Resource " + name + " can't be found..."); - } - } - - return retval; - } - - /** - * Simple space saving implementation of common I18n Property Info setting. - * - * @param i18n i18n object to use to search for internationalized strings. - * @param info the properties class being used to set information into. - * @param classToSetFor class to use for i18n search. - * @param propertyName property to set for. - * @param label label to use for GUI (can be null if N/A). - * @param tooltip tooltip to use for GUI (can be null if N/A). - * @param editor editor class string to use for GUI (can be null if N/A). - * @return Properties object passed in, or new one if null Properties passed - * in. - */ - public static Properties setI18NPropertyInfo(I18n i18n, Properties info, - Class classToSetFor, - String propertyName, String label, String tooltip, - String editor) { - if (info == null) { - info = new Properties(); - } - if (i18n != null) { - if (tooltip != null) { - String internString = i18n.get(classToSetFor, propertyName, I18n.TOOLTIP, tooltip); - info.put(propertyName, internString); - } - if (label != null) { - String internString = i18n.get(classToSetFor, propertyName, label); - info.put(propertyName + PropertyConsumer.LabelEditorProperty, internString); - } - if (editor != null) { - info.put(propertyName + PropertyConsumer.ScopedEditorProperty, editor); - } - } - return info; - } - - /** - * If the layer has a dataPathPrefix attribute set, that attribute value can - * be used as a common path to prepend to any layer's data path. This allows - * you to set a relative path to files in the layer's properties, and then - * prepend the absolute path later at runtime. - *

- * - * The dataPathPrefix can be set in the properties for a layer, where it is - * pushed to the layer's attributes in Layer.setProperties(). This method is - * intended for layers that have sub-layers, so the parent layer can set - * that dataPathPrefix property on it's children automatically. - * - * @param layer the parent layer to retrieve the attribute from - * @param props the properties that define the children, and also passed to - * them for configuration - * @param layerListProperty the property for the parent that lists the - * marker names for the children - */ - public static void putDataPrefixToLayerList(Layer layer, Properties props, - String layerListProperty) { - String dataPrefix = (String) layer.getAttribute(Layer.DataPathPrefixProperty); - if (dataPrefix != null && dataPrefix.length() > 0) { - putDataPrefixToLayerList(dataPrefix, props, layerListProperty); - } - } - - /** - * If the layer has a dataPathPrefix attribute set, that attribute value can - * be used as a common path to prepend to any layer's data path. This allows - * you to set a relative path to files in the layer's properties, and then - * prepend the absolute path later at runtime. - *

- * - * The dataPathPrefix can be set in the properties for a layer, where it is - * pushed to the layer's attributes in Layer.setProperties(). This method is - * intended for layers that have sub-layers, so the parent layer can set - * that dataPathPrefix property on it's children automatically. - * - * @param dataPrefix the dataPathPrefix retrieved from the parent attributes - * @param props the properties that define the children, and also passed to - * them for configuration - * @param layerListProperty the property for the parent that lists the - * marker names for the children - */ - public static void putDataPrefixToLayerList(String dataPrefix, Properties props, - String layerListProperty) { - List layersValue = parseSpacedMarkers(props.getProperty(layerListProperty)); - - for (String markerName : layersValue) { - props.setProperty(getScopedPropertyPrefix(markerName) + Layer.DataPathPrefixProperty, dataPrefix); - } - } - - /** - * Get a List of Objects defined by marker names listed in a property. If - * the objects are PropertyConsumers, they will be given the properties and - * their scoped property prefix so they can configure themselves. - * - *

-     * 
-     * listProperty=markername1 markername2 markername3
-     * markername1.definingProperty=classname1
-     * markername2.definingProperty=classname2
-     * markername3.definingProperty=classname3
-     * 
-     * 
- * - * @param p Properties object containing all properties - * @param markerListProperty listProperty in example above - * @param definingProperty definingProperty in example above, scoped - * property when combined with marker name to define the class that - * should be created for an object. - * @return List of objects created from properties - */ - public static List objectsFromProperties(Properties p, String markerListProperty, - String definingProperty) { - return objectsFromScopedProperties(p, markerListProperty, definingProperty, null); - // - // String markerList = p.getProperty(markerListProperty); - // List ret = new LinkedList(); - // - // if (markerList != null) { - // Vector markerNames = parseSpacedMarkers(markerList); - // for (String markerName : markerNames) { - // String classname = p.getProperty(markerName + "." - // + definingProperty); - // if (classname != null) { - // Object obj = ComponentFactory.create(classname, markerName, - // p); - // - // if (obj != null) { - // ret.add(obj); - // } - // } - // } - // - // } - // - // return ret; - } - - /** - * Get a List of Objects defined by marker names listed in a property, when - * this list property has been scoped by a parent object definition. If the - * objects are PropertyConsumers, they will be given the properties and - * their scoped property prefix so they can configure themselves. - * - *
-     * 
-     * parentMarker.listProperty=markername1 markername2 markername3
-     * parentMarker.markername1.definingProperty=classname1
-     * parentMarker.markername2.definingProperty=classname2
-     * parentMarker.markername3.definingProperty=classname3
-     * 
-     * 
- * - * @param p Properties object containing all properties - * @param markerListProperty listProperty in example above - * @param definingProperty definingProperty in example above, scoped - * property when combined with marker name to define the class that - * should be created for an object. - * @param parentMarker the string that should be used as the prefix for the - * defining property - * @return List of objects created from properties, where properties are - * scoped for each object. - */ - public static List objectsFromScopedProperties(Properties p, String markerListProperty, - String definingProperty, - String parentMarker) { - String markerList = p.getProperty(markerListProperty); - List ret = new LinkedList(); - parentMarker = PropUtils.getScopedPropertyPrefix(parentMarker); - - if (markerList != null) { - List markerNames = parseSpacedMarkers(markerList); - for (String markerName : markerNames) { - String classname = p.getProperty(parentMarker + markerName + "." - + definingProperty); - if (classname != null) { - Object obj = ComponentFactory.create(classname, markerName, p); - - if (obj != null) { - ret.add(obj); - } - } - } - } - - return ret; - } - - /** - * Add the object property value to properties if it's not null or empty, - * which assumes it should be set to the default value. - * - * @param props Properties to write to - * @param propertyName the scoped property to enter value under - * @param value the object to get property from - toString() will be called - * if not null. - * @param class for property - */ - public static void putIfNotDefault(Properties props, String propertyName, - T value) { - putIfNotDefault(props, propertyName, value, null); - } - - /** - * Add the object property value to properties if it's not null or default - * value. - * - * @param props Properties to write to - * @param propertyName the scoped property to enter value under - * @param value the object to get property from - toString() will be called - * if not null. - * @param def the default value of the property. If not null and value not - * null, toString().equals() will be used to determine equality. If - * not equal, then value will be set in props. - * @param matching class types for the property - */ - public static void putIfNotDefault(Properties props, String propertyName, - T value, T def) { - if (value != null) { - String valString = value.toString().trim(); - if (def == null || (def != null && !def.toString().trim().equals(valString))) { - // empty property strings are a pain... - if (valString.length() != 0) { - props.put(propertyName, valString); - } - } - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/PropertyStringFormatException.java b/src/core/src/main/java/com/bbn/openmap/util/PropertyStringFormatException.java deleted file mode 100644 index e4adfecdc..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/PropertyStringFormatException.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/PropertyStringFormatException.java,v $ -// $RCSfile: PropertyStringFormatException.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - */ -public class PropertyStringFormatException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a MapRequestFormatException with - * null as its error message string. - */ - public PropertyStringFormatException() { - super(); - } - - /** - * Constructs a MapRequestFormatException, saving - * a reference to the error message string s for later - * retrieval by the getMessage method. - * - * @param s the detail message. - */ - public PropertyStringFormatException(String s) { - super(s); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/util/SwingWorker.java b/src/core/src/main/java/com/bbn/openmap/util/SwingWorker.java deleted file mode 100644 index 3a6586767..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/SwingWorker.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.bbn.openmap.util; - -import java.util.concurrent.Callable; -import java.util.concurrent.FutureTask; - -/** - * This class used to be based on the 3rd version of SwingWorker. But Carsten - * provided a more modern version that's a lot cleaner. - * - * @param The type of value computed by the task. - */ -public abstract class SwingWorker implements ISwingWorker { - - private Exception executionException; - - private FutureTask future = null; - - /** - * Start a thread that will call the construct method and then - * exit. - */ - public SwingWorker() { - final Callable doWork = new Callable() { - public T call() { - return construct(); - } - }; - future = new FutureTask(doWork) { - @Override - protected void done() { - finished(); - } - }; - } - - /** - * Compute the value to be returned by the get method. - */ - public abstract T construct(); - - /** - * For compatibility with old versions of SwingWorker, calls start(). - */ - public void execute() { - start(); - } - - /** - * Start the worker thread. - */ - public void start() { - new Thread(future).start(); - } - - /** - * Return the value created by the construct method. Returns - * null if either the constructing thread or the current thread was - * interrupted before a value was produced. - * - * @return the value created by the construct method - */ - public T get() { - try { - return future.get(); - } catch (Exception e) { - executionException = e; - } - return null; - } - - /** - * A new method that interrupts the worker thread. Call this method to force - * the worker to stop what it's doing. - */ - public void interrupt() { - future.cancel(true); - } - - public boolean isInterrupted() { - return future.isCancelled(); - } - - /** - * Called on the event dispatching thread (not on the worker thread) after - * the construct method has returned. - */ - public void finished() { - } - - /** - * @return the executionException - */ - public Exception getExecutionException() { - return executionException; - } - - /** - * @param executionException the executionException to set - */ - public void setExecutionException(Exception executionException) { - this.executionException = executionException; - } - - /** - * @return the future - */ - public FutureTask getFuture() { - return future; - } - - /** - * @param future the future to set - */ - public void setFuture(FutureTask future) { - this.future = future; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/TaskService.java b/src/core/src/main/java/com/bbn/openmap/util/TaskService.java deleted file mode 100644 index 9dabd0d49..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/TaskService.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Copyright 2010 BBN Technologies - * - */ -package com.bbn.openmap.util; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Reuse threads instead of making new ones over and over. - */ -public final class TaskService { - public static TaskService singleton() { - return SingletonHolder.instance; - } - - private static class SingletonHolder { - private static final TaskService instance = new TaskService(); - } - - private ExecutorService executor; - - private TaskService() { - executor = Executors.newCachedThreadPool(); - } - - /** - * Run a task in a thread. - * - * @param task the runnable - */ - public void spawn(Runnable task) { - executor.execute(task); - } - - public Future spawn(Callable task) { - return executor.submit(task); - } - - /** - * Allows more control over how threads can be allocated. - * - * @param eService ExecutorService that allocates and schedules thread - * spawning for layers. - */ - public void setExecutorService(ExecutorService eService) { - if (eService != null) { - executor = eService; - } - } - - /** - * If called, will replace the default unbounded executor using a cached - * thread pool with a fixed thread pool executor, so the maxNumThreads are - * allocated. If they are all busy, the Runnables will queue. - * - * @param maxNumThreads number of threads to allocate for the thread pool - */ - public void setMaxNumThreads(int maxNumThreads) { - executor = new ThreadPoolExecutor(0, maxNumThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue()); - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/Taskable.java b/src/core/src/main/java/com/bbn/openmap/util/Taskable.java deleted file mode 100644 index 7f79e26ce..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Taskable.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/Taskable.java,v $ -// $RCSfile: Taskable.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.awt.event.ActionListener; - -/** - * Taskables are ActionListeners that respond to events from Timers. - * If a Taskable has been added to a Timer's queue, it will receive - * actionPerformed() notifications each time the timer - * expires. - *

- * Some OpenMap Layers are Taskables. These layers expect to refresh - * their graphics at a certain rate. - * - * @see javax.swing.Timer - */ -public interface Taskable extends ActionListener { - - /** - * Get the sleep hint in milliseconds. The Taskable implementation - * should determine the sleep (delay) interval between invocations - * of its actionPerformed(). - *

- * NOTE: this is only a hint for the timer. It's the Taskable's - * responsibility to determine if too little or too much time has - * elapsed between invocations of actionPerformed(). - * - * @return int milliseconds of sleep interval - */ - public int getSleepHint(); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/Tokenizer.java b/src/core/src/main/java/com/bbn/openmap/util/Tokenizer.java deleted file mode 100644 index fbb8da220..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/Tokenizer.java +++ /dev/null @@ -1,139 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/Tokenizer.java,v $ -// $RCSfile: Tokenizer.java,v $ -// $Revision: 1.4 $ -// $Date: 2008/02/27 01:05:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/** - * Tokenizer provides some tools useful for defining tokenizers. You - * get 1 character pushback. - */ -public class Tokenizer extends java.io.PushbackReader { - StringBuffer b; - int lineCount = 0; - - public Tokenizer(java.io.Reader in) { - super(in, 2); - this.b = new StringBuffer(80); - } - - // KRA 25Oct98: class Match requires access to NEWLINE and EOF, - // YOW! - public final static Object NEWLINE = new Object() { - public String toString() { - return ""; - } - }; - - public final static Object EOF = new Object() { - public String toString() { - return ""; - } - }; - - public final static Object EMPTY = new Object() { - public String toString() { - return ""; - } - }; - - public boolean isNewline(Object o) { - return o == NEWLINE; - } - - public boolean isEOF(Object o) { - return o == EOF; - } - - public boolean isAny(int c) { - return c != -1; - } - - public boolean isAlpha(int c) { - return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; - } - - public boolean isDigit(int c) { - return c >= '0' && c <= '9'; - } - - public boolean isAlphanumeric(int c) { - return isAlpha(c) || isDigit(c); - } - - public void bpush(int c) { - this.b.append((char) c); - } // Yow! - - public String bclear() { - // YOW! Carefully copy string so it won't have 80 charaters - // under it. - String result = this.b.toString(); - this.b.setLength(0); - int L = result.length(); - char[] chars = new char[L]; - result.getChars(0, L, chars, 0); - return new String(chars); - } - - /** - * Read the next character. Convert alternative line breaks to '\n'. Thank - * you Bill Gates! - * - * @return next character - */ - public int next() { - int c; - try { - c = this.read(); - if (c == '\r') { - int c1 = this.read(); - if (c1 == '\n') { - c = '\n'; - } else { - this.unread(c1); - c = '\n'; - } - } - if (c == '\n') - this.lineCount++; - //_ System.out.print((char) c + "_"); - return c; - } catch (java.io.IOException e) { - throw new HandleError(e); - } - } - - public void putback(int c) { - // System.out.println("putback: '" + (char) c + "'"); - try { - if (c != -1) - this.unread(c); - } catch (java.io.IOException e) { - throw new HandleError(e); - } - } - - public Object error(String s) { - throw new HandleError("at line " + this.lineCount + ": " + s); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/WebBrowser.java b/src/core/src/main/java/com/bbn/openmap/util/WebBrowser.java deleted file mode 100644 index bf5df31d3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/WebBrowser.java +++ /dev/null @@ -1,109 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/WebBrowser.java,v $ -// $RCSfile: WebBrowser.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/09 18:37:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; - -/** - * WebBrower - handles the WebBrowser process on behalf of OM. This class should - * be extended and implemented fully to handle browser requests as you like. You - * can use BrowserLauncher2 if you like. - */ -public abstract class WebBrowser { - - InfoDisplayListener info = null; - - /** - * Write temporary file to temporary directory, and generate URL. - * - * @param text text String - * @return String file URL - */ - protected String writeFileAndGenerateURL(String text) { - - File tmpFile = null; - - try { - tmpFile = File.createTempFile(Environment.OpenMapPrefix, ".html", new File(Environment.get(Environment.TmpDir))); - - tmpFile.deleteOnExit(); // get rid of it when the user - // quits. - - FileOutputStream fs = new FileOutputStream(tmpFile); - PrintWriter out = new PrintWriter((OutputStream) fs); - out.println(text); - fs.close(); // close the streams - - String urlString = tmpFile.toURI().toURL().toString(); - Debug.output("WebBrowser: created " + urlString); - return urlString; - - } catch (SecurityException se) { - Debug.error("WebBrowser.writeAndGenerateURL: " + se); - } catch (IOException ioe) { - Debug.error("WebBrowser.writeAndGenerateURL: " + ioe); - } - - postErrorMessage("Cannot write to temp file:" - + (tmpFile != null ? tmpFile.getAbsolutePath() : "unknown")); - - return null; - } - - public void setInfoDelegator(InfoDisplayListener info) { - this.info = info; - } - - /** - * Creates a new web browser process, or points the current one to the url - * argument. - * - * @param urlString URL - * - */ - public abstract void launch(String urlString); - - /** - * Writes out temporary text file, and creates a new web browser process or - * points the current one at the file. - * - * @param text String - * - */ - public void writeAndLaunch(String text) { - launch(writeFileAndGenerateURL(text)); - } - - private void postErrorMessage(String message) { - info.requestMessage(new InfoDisplayEvent(this, message)); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheHandler.java b/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheHandler.java deleted file mode 100644 index 4a4e8361d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheHandler.java +++ /dev/null @@ -1,214 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/cacheHandler/CacheHandler.java,v -// $ -// $RCSfile: CacheHandler.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/12/15 18:39:53 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.cacheHandler; - -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A base cache support object. Based on the - * com.bbn.openmap.layer.util.cacheHandler package components, this CacheHandler - * uses Objects instead of Strings and will be replacing the earlier version. - * - * @author dietrick - */ -public abstract class CacheHandler { - protected CacheObject[] objs; - protected int logicalClock; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.util.cacheHandler.CacheHandler"); - - public static int DEFAULT_MAX_CACHE_SIZE = 25; - - /** - * Standard default constructor - */ - public CacheHandler() { - initCache(DEFAULT_MAX_CACHE_SIZE); - } - - /** - * Constructor used when you know the limits - */ - public CacheHandler(int max_size) { - initCache(max_size); - } - - /** - * Set the size, reset the logical clock - */ - private void initCache(int max_size) { - if (objs != null && objs.length == max_size) { - clear(); - } else { - objs = new CacheObject[max_size]; - } - logicalClock = 0; - } - - /** - * Remove all the objects from the cache. - */ - public void clear() { - if (objs != null) { - for (int i = 0; i < objs.length; i++) { - objs[i] = null; - } - } - } - - /** - * Need to clear memory, get gc moving, and ready for new objects - */ - public void resetCache() { - initCache(objs.length); - } - - /** - * Need to clear memory, get gc moving, and ready for new objects. Delete - * the current Hashtable and create a new one with the new capacity. - * - * @param max_size the capacity of the Hashtable. - */ - public void resetCache(int max_size) { - initCache(max_size); - } - - /** - * Get the current size of the cache. - */ - public int getCacheSize() { - return objs.length; - } - - /** - * The main call to retrieve something from the cache - */ - public Object get(Object key) { - CacheObject ret = searchCache(key); - if (ret != null) - return ret.obj; - - ret = load(key); - if (ret == null) - return null; - - replaceLeastUsed(ret); - return ret.obj; - } - - /** - * Called from get if the key doesn't exist, to "load" the new object into - * the cache before returning it. This function should define how a - * CacheObject is created, or loaded from the file system, or whatever. - */ - public abstract CacheObject load(Object key); - - /** - * Search the cache for a match -return null if not found. The key search is - * case insensitive. - */ - public CacheObject searchCache(Object key) { - for (int i = 0; i < objs.length; i++) { - CacheObject co = objs[i]; - if (co == null) { - // Since we load 0 -> length - 1, if we get a null - // one, the rest are null, too. - break; - } else if (co.id.equals(key)) { - return co; - } - } - return null; - } - - /** - * If there is space in the cache, put the object in. If there isn't space, - * find the least used object, and replace it. - */ - protected void replaceLeastUsed(CacheObject newObj) { - - // If the cache has room... - int i; - for (i = objs.length - 1; i >= 0; i--) { - if (objs[i] == null) { - // Somewhere in a partially filled cache, keep looking - // for the last taken place... - if (i == 0) { - // there is nothing in the cache. - objs[0] = newObj; - if (logger.isLoggable(Level.FINE)) { - logger.fine("was empty - added " + newObj.id); - } - - return; - } else { - continue; - } - } else if (i == objs.length - 1) { - // We're at the end, and there is no empty space - - // we'll need to look at the LRU clock. - break; - } else { - // We are at the index of the last taken spot, and the - // next place is available. - objs[i + 1] = newObj; - if (logger.isLoggable(Level.FINE)) { - logger.fine("had room - added " + newObj.id + " to the " - + i + " spot."); - } - return; - } - } - - // If we get here, we need to replace something in the cache. - - int minClock = logicalClock + 1; - int LUIndex = -1; - - for (i = objs.length - 1; i >= 0; i--) { - if (objs[i].older(minClock)) { - LUIndex = i; - minClock = objs[i].cachedTime; - } - } - - if (LUIndex != -1) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Tossing " + objs[LUIndex].id - + " from cache[" + LUIndex + "] to add " + newObj.id); - } - objs[LUIndex] = newObj; - newObj.cachedTime = logicalClock++; - } - } - - /** - * Return a ListIterator of the cache objects. - */ - public java.util.ListIterator listIterator() { - return java.util.Arrays.asList(objs).listIterator(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheObject.java b/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheObject.java deleted file mode 100644 index df7add5c1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/CacheObject.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/cacheHandler/CacheObject.java,v -// $ -// $RCSfile: CacheObject.java,v $ -// $Revision: 1.2 $ -// $Date: 2006/12/15 18:39:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.cacheHandler; - -public class CacheObject { - - public Object obj = null; - public int cachedTime = 0; - public Object id = null; - - /** - * New object, set the local clock to zero - */ - public CacheObject(Object identifier, Object cachedObject) { - id = identifier; - obj = cachedObject; - } - - public boolean match(Object queryID) { - return (queryID.equals(id)); - } - - public boolean older(int time) { - return (cachedTime < time); - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/package.html b/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/package.html deleted file mode 100644 index ad79df63c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/cacheHandler/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides utility code for a data cache. This cache is based on the com.bbn.openmap.layer.util.cacheHandler package, but this cache is based on using Objects for keys instead of Strings. This package will be replacing the other one. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/BasicCoordInfoFormatter.java b/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/BasicCoordInfoFormatter.java deleted file mode 100644 index ad20031a6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/BasicCoordInfoFormatter.java +++ /dev/null @@ -1,98 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: BasicCoordInfoFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/10/10 00:57:21 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.util.coordFormatter; - -import java.awt.geom.Point2D; -import java.text.DecimalFormat; -import java.util.Properties; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.PropUtils; - -/** - * A CoordInfoFormatter that creates the default OpenMap string:

- * 
- * Lat, Lon (latitude, longitude) - x, y (x pixel loc, y pixel loc)
- * 
- * 
- * - * @author dietrick - */ -public class BasicCoordInfoFormatter extends OMComponent implements - CoordInfoFormatter { - - protected String prettyName = "Default"; - public static final String DEGREE_SIGN = "\u00b0"; - protected DecimalFormat df = new DecimalFormat("0.###"); - - public BasicCoordInfoFormatter() { - - } - - public String createCoordinateInformationLine(int x, int y, - Point2D llp, Object source) { - if (llp != null) { - return "Lat, Lon (" + df.format(llp.getY()) + ", " - + df.format(llp.getX()) + ") - x, y (" + x + "," - + y + ")"; - } else { - return "x, y (" + x + "," + y + ")"; - } - } - - public String getPrettyName() { - return prettyName; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - prettyName = props.getProperty(prefix + Layer.PrettyNameProperty, - prettyName); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + Layer.PrettyNameProperty, prettyName); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, - props, - this.getClass(), - Layer.PrettyNameProperty, - "Name", - "Name for formatter", - null); - - return props; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatter.java b/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatter.java deleted file mode 100644 index dd8d97c71..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatter.java +++ /dev/null @@ -1,54 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: CoordInfoFormatter.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/10/10 00:57:21 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.util.coordFormatter; - -import java.awt.geom.Point2D; - -import com.bbn.openmap.PropertyConsumer; - -/** - * A CoordInfoFormatter is an object that can create a String for display from coordinate information. - * - * @author dietrick - */ -public interface CoordInfoFormatter extends PropertyConsumer { - - /** - * The main function of this class - * @param x the x pixel coordinate of the map, 0 is left side. - * @param y the y pixel coordinate of the map, 0 is top. - * @param llp the LatLonPoint represented by the pixel location. - * @param source the object calling this method. - * @return String with coordinate info on it. - */ - public String createCoordinateInformationLine(int x, int y, - Point2D llp, Object source); - - /** - * A name, suitable for GUI display, of this formatter. - * @return String for pretty name for formatter - */ - public String getPrettyName(); -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatterHandler.java b/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatterHandler.java deleted file mode 100644 index 11ee1d711..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/CoordInfoFormatterHandler.java +++ /dev/null @@ -1,130 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: CoordInfoFormatterHandler.java,v $ -//$Revision: 1.2 $ -//$Date: 2008/10/10 00:57:21 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.util.coordFormatter; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The CoordInfoFormatterHandler manages CoordInfoFormatters for all of the - * CoordMouseModes, in order to provide a consistent coordinate display across - * mouse modes that display coordinate info. If you want different coordinate - * information for each CoordMouseMode, set the CoordInfoFormatter on each mouse - * mode and don't use this class in the openmap.components property or - * MapHandler. Only use this if you want to provide a choice to your users and - * you want that choice used over all of your mouse modes. - *

- * This class should be placed in the MapHandler, which you can do via the - * properties by adding it's marker name to the openmap.components property - * list. The properties look like this (for a marker name - * coordFormatterHandler): - * - *

- * 
- * coordFormatterHandler.class=com.bbn.openmap.util.coordFormatter.CoordInfoFormatterHandler
- * coordFormatterHandler.formatters=dmsFormatter basicFormatter
- * coordFormatterHandler.dmsFormatter.class=com.bbn.openmap.util.coordFormatter.DMSCoordInfoFormatter
- * coordFormatterHandler.basicFormatter.class=com.bbn.openmap.util.coordFormatter.BasicCoordInfoFormatter
- * 
- * 
- * - * @author dietrick - */ -public class CoordInfoFormatterHandler extends OMComponent { - - protected List formatters = new ArrayList(); - protected CoordInfoFormatter activeFormatter = null; - public final static String FORMATTER_PROPERTY = "formatters"; - - public CoordInfoFormatterHandler() { - - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - // Create the formatters from the property settings. - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - String markerList = props.getProperty(realPrefix + FORMATTER_PROPERTY); - if (markerList != null) { - List formatterV = PropUtils.parseSpacedMarkers(markerList); - List formatters = ComponentFactory.create(formatterV, prefix, props); - - for (Object obj : formatters) { - if (obj instanceof CoordInfoFormatter) { - CoordInfoFormatter cif = (CoordInfoFormatter) obj; - if (activeFormatter == null) { - activeFormatter = cif; - } - this.formatters.add(cif); - } - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - StringBuffer markerList = new StringBuffer(); - for (Iterator it = formatters.iterator(); it.hasNext();) { - CoordInfoFormatter cif = it.next(); - cif.getProperties(props); - markerList.append(cif.getPropertyPrefix()).append(" "); - props.put(PropUtils.getScopedPropertyPrefix(cif), cif.getClass().getName()); - } - - props.put(prefix + FORMATTER_PROPERTY, markerList.toString().trim()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - return props; - } - - public void setActiveFormatter(CoordInfoFormatter formatter) { - CoordInfoFormatter oldFormatter = activeFormatter; - if (oldFormatter == formatter) { - return; - } - - activeFormatter = formatter; - firePropertyChange(FORMATTER_PROPERTY, oldFormatter, activeFormatter); - } - - public void addPropertyChangeListener(String property, PropertyChangeListener pcl) { - super.addPropertyChangeListener(property, pcl); - pcl.propertyChange(new PropertyChangeEvent(this, FORMATTER_PROPERTY, null, activeFormatter)); - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/DMSCoordInfoFormatter.java b/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/DMSCoordInfoFormatter.java deleted file mode 100644 index d07ac22ce..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/DMSCoordInfoFormatter.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.bbn.openmap.util.coordFormatter; - -/** - * Copyright NAVICON A/S - * com@navicon.dk - * - * Formats a string to represent DMS for lat/lon information. - */ -import java.awt.geom.Point2D; -import java.text.NumberFormat; - -public class DMSCoordInfoFormatter extends BasicCoordInfoFormatter { - - public DMSCoordInfoFormatter() {} - - public String createCoordinateInformationLine(int x, int y, - Point2D llp, Object source) { - if (llp != null) { - return "Cursor Position (" + formatLatitude(llp.getY()) - + ", " + formatLongitude(llp.getX()) + ")"; - } else { - return "Lat, Lon (" + "?" + ", " + "?" + ")"; - } - } - - public static String formatLatitude(double latitude) { - return formatDegreesMinutes(latitude, 2, latitude < 0 ? "S" : "N"); - } - - public static String formatLongitude(double longitude) { - return formatDegreesMinutes(longitude, 3, longitude < 0 ? "W" : "E"); - } - - public static String formatDegreesMinutes(double value, int integerDigits, - String semisphere) { - double valueAbs = Math.abs(value); - int degrees = (int) valueAbs; - double minutes = (valueAbs - degrees) * 60.0; - - NumberFormat nf = NumberFormat.getInstance(); - nf.setGroupingUsed(false); - nf.setMinimumIntegerDigits(integerDigits); - nf.setMaximumIntegerDigits(integerDigits); - String strDegrees = nf.format(degrees); - nf.setMinimumIntegerDigits(2); - nf.setMaximumIntegerDigits(2); - nf.setMinimumFractionDigits(3); - nf.setMaximumFractionDigits(3); - String strMinutes = nf.format(minutes); - return strDegrees + DEGREE_SIGN + strMinutes + "'" + semisphere; - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/MGRSCoordInfoFormatter.java b/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/MGRSCoordInfoFormatter.java deleted file mode 100644 index 1db24f7c8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/coordFormatter/MGRSCoordInfoFormatter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.bbn.openmap.util.coordFormatter; - -/** - * Copyright NAVICON A/S - * com@navicon.dk - * - * Formats a string to represent DMS for lat/lon information. - */ -import java.awt.geom.Point2D; - -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.proj.coords.MGRSPoint; - -public class MGRSCoordInfoFormatter extends BasicCoordInfoFormatter { - - public MGRSCoordInfoFormatter() { - } - - public String createCoordinateInformationLine(int x, int y, - Point2D llp, Object source) { - if (llp != null) { - double lat = llp.getY(); - double lon = llp.getX(); - return "MGRS (" + MGRSPoint.LLtoMGRS(new LatLonPoint.Double(lat, lon)).getMGRS() + ")"; - } else { - return "MGRS (" + "?" + ", " + "?" + ")"; - } - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/ContainerElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/ContainerElement.java deleted file mode 100644 index f167560df..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/ContainerElement.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/ContainerElement.java,v $ -// $RCSfile: ContainerElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** - * This interface is used to describe object which maintain some type - * of (ordered) list of contained objects. - * - * @see Document - * @see ListElement - */ -public interface ContainerElement extends Element { - /** - * add an additional element to the Container - * - * @param e the element to add - */ - public void addElement(Element e); - - /** - * add an additional element to the Container - * - * @param s the String to add - */ - public void addElement(String s); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/Document.java b/src/core/src/main/java/com/bbn/openmap/util/html/Document.java deleted file mode 100644 index 3b48a493a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/Document.java +++ /dev/null @@ -1,122 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/Document.java,v $ -// $RCSfile: Document.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -import java.io.Writer; - -/** This class wraps an entire html document (page) */ -public class Document implements ContainerElement { - /** this title of the document */ - protected String title; - /** the base URL for this document */ - protected String base; - /** the body of the document */ - protected ListElement body; - - /** Construct a document with no title and an empty body */ - public Document() { - body = new ListElement(); - } - - /** - * Construct a document with a title but an empty body - * - * @param title the title of the document - */ - public Document(String title) { - body = new ListElement(); - this.title = title; - } - - /** - * Writer for title - * - * @param title the new document title - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Writer for the base url - * - * @param base the new base URL - */ - public void setBase(String base) { - this.base = base; - } - - /** - * Add another element to the body of the document - * - * @param e the element to add - */ - public void addElement(Element e) { - body.addElement(e); - } - - /** - * Add another string to the body of the document - * - * @param s the string to add - */ - public void addElement(String s) { - addElement(new StringElement(s)); - } - - /** - * Write the header to the output - * - * @param out the Writer to dump output to - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generateHeader(Writer out) throws java.io.IOException { - out.write(""); - if (title != null) { - out.write(""); - out.write(title); - out.write(""); - } - if (base != null) { - out.write(""); - } - out.write(""); - } - - /** - * convert representation to html and write it out - * - * @param out the output Writer - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generate(Writer out) throws java.io.IOException { - out.write(""); - generateHeader(out); - out.write(""); - body.generate(out); - out.write(""); - out.write(""); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/Element.java b/src/core/src/main/java/com/bbn/openmap/util/html/Element.java deleted file mode 100644 index e180c68fd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/Element.java +++ /dev/null @@ -1,38 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/Element.java,v $ -// $RCSfile: Element.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** - * This interface describes any html element that knows how to dump - * itself to an java.io.Writer - */ -public interface Element { - /** - * convert representation to html and write it out - * - * @param out the output Writer - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generate(java.io.Writer out) throws java.io.IOException; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/HeaderElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/HeaderElement.java deleted file mode 100644 index 06abc4faa..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/HeaderElement.java +++ /dev/null @@ -1,54 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/HeaderElement.java,v $ -// $RCSfile: HeaderElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** This class provides easy access to the html header tags */ -public class HeaderElement extends WrapElement { - - /** - * Construct a header - * - * @param headLevel the level of the header (should be a small - * integer) - * @param e the element in the header - * @exception IllegalArgumentException headLevel was invalid - */ - public HeaderElement(int headLevel, Element e) { - super("h" + headLevel, e); - if (headLevel < 1) - throw new IllegalArgumentException("HeaderElement: headLevel = " - + headLevel); - } - - /** - * Construct a header - * - * @param headLevel the level of the header (should be a small - * integer) - * @param s the string in the header - * @exception IllegalArgumentException headLevel was invalid - */ - public HeaderElement(int headLevel, String s) { - this(headLevel, new StringElement(s)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/HtmlListElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/HtmlListElement.java deleted file mode 100644 index 876485722..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/HtmlListElement.java +++ /dev/null @@ -1,75 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/HtmlListElement.java,v $ -// $RCSfile: HtmlListElement.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** A container for a list body */ -public class HtmlListElement implements ContainerElement { - private Element header; - private ListBodyElement items = new ListBodyElement(); - - /** Construct a new ListElement */ - public HtmlListElement() { - this((Element) null); - } - - public HtmlListElement(String s) { - this(new StringElement(s)); - } - - public HtmlListElement(Element header) { - this.header = header; - } - - public void setTitleElement(Element e) { - header = e; - } - - public void setTitleElement(String s) { - setTitleElement(new StringElement(s)); - } - - public void generate(java.io.Writer out) throws java.io.IOException { - if (header != null) { - header.generate(out); - } - new WrapElement("ul", items).generate(out); - } - - /** - * Add an element to the end of the list - * - * @param e the element to add - */ - public void addElement(Element e) { - items.addElement(e); - } - - /** - * Add an element to the end of the list - * - * @param s the string to add - */ - public void addElement(String s) { - addElement(new StringElement(s)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/ListBodyElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/ListBodyElement.java deleted file mode 100644 index 3ef484f70..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/ListBodyElement.java +++ /dev/null @@ -1,39 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/ListBodyElement.java,v $ -// $RCSfile: ListBodyElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** A container for a list body */ -public class ListBodyElement extends ListElement { - - /** Construct a new ListElement */ - public ListBodyElement() {} - - /** - * Add an element to the end of the list - * - * @param e the element to add - */ - public void addElement(Element e) { - super.addElement(new WrapElement("li", e)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/ListElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/ListElement.java deleted file mode 100644 index 1f1d000cd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/ListElement.java +++ /dev/null @@ -1,66 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/ListElement.java,v $ -// $RCSfile: ListElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -import java.util.Enumeration; -import java.util.Vector; - -/** A basic html container type */ -public class ListElement implements ContainerElement { - - /** An ordered vector of elements */ - protected Vector v = new Vector(); - - /** Construct a new ListElement */ - public ListElement() {} - - /** - * Add an element to the end of the list - * - * @param e the element to add - */ - public void addElement(Element e) { - v.addElement(e); - } - - /** - * Add an element to the end of the list - * - * @param s the string to add - */ - public void addElement(String s) { - addElement(new StringElement(s)); - } - - /** - * convert representation to html and write it out - * - * @param out the output Writer - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generate(java.io.Writer out) throws java.io.IOException { - for (Enumeration e = v.elements(); e.hasMoreElements();) - ((Element) e.nextElement()).generate(out); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/StringElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/StringElement.java deleted file mode 100644 index 7bde28874..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/StringElement.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/StringElement.java,v -// $ -// $RCSfile: StringElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -public class StringElement implements Element { - - /** the string value that we are */ - protected String s; - - /** - * Construct a new StringElement with a string literal - * - * @param s the string to use - */ - public StringElement(String s) { - this.s = s; - } - - /** - * convert representation to html and write it out - * - * @param out the output Writer - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generate(java.io.Writer out) throws java.io.IOException { - out.write(s); - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/TableCellElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/TableCellElement.java deleted file mode 100644 index 1c5919c3b..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/TableCellElement.java +++ /dev/null @@ -1,30 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/TableCellElement.java,v $ -// $RCSfile: TableCellElement.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** - * All classes that can be an cell in an html table implement this - * type - */ -public interface TableCellElement extends Element { -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/TableDataElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/TableDataElement.java deleted file mode 100644 index 8b181769a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/TableDataElement.java +++ /dev/null @@ -1,63 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/TableDataElement.java,v $ -// $RCSfile: TableDataElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:06 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** This class is used for a basic cell in a html table */ -public class TableDataElement extends WrapElement implements TableCellElement { - - /** - * Construct a data cell with an element - * - * @param e the element to put in the cell - */ - public TableDataElement(Element e) { - super("td", e); - } - - /** - * Construct a data cell with a string - * - * @param s the string to put in the cell - */ - public TableDataElement(String s) { - super("td", new StringElement(s)); - } - - /** - * Construct a data cell with an element - * - * @param e the element to put in the cell - */ - public TableDataElement(String paramString, Element e) { - super("td", paramString, e); - } - - /** - * Construct a data cell with a string - * - * @param s the string to put in the cell - */ - public TableDataElement(String paramString, String s) { - super("td", paramString, new StringElement(s)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/TableHeaderElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/TableHeaderElement.java deleted file mode 100644 index 3601ba02d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/TableHeaderElement.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/TableHeaderElement.java,v $ -// $RCSfile: TableHeaderElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** This class is used for Column/Row head elements in html tables */ -public class TableHeaderElement extends WrapElement implements TableCellElement { - /** - * Construct a column header with an element - * - * @param e the element to put in the cell - */ - public TableHeaderElement(Element e) { - super("th", e); - } - - /** - * Construct a column header with a string - * - * @param s the string to put in the cell - */ - public TableHeaderElement(String s) { - super("th", new StringElement(s)); - } - - /** - * Construct a column header with an element - * - * @param e the element to put in the cell - */ - public TableHeaderElement(String paramString, Element e) { - super("th", paramString, e); - } - - /** - * Construct a column header with a string - * - * @param s the string to put in the cell - */ - public TableHeaderElement(String paramString, String s) { - super("th", paramString, new StringElement(s)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/TableRowElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/TableRowElement.java deleted file mode 100644 index ab4e03f63..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/TableRowElement.java +++ /dev/null @@ -1,61 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/TableRowElement.java,v $ -// $RCSfile: TableRowElement.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** This class implements an entire row of an html table */ -public class TableRowElement extends WrapElement implements ContainerElement { - - /** Construct an empty row */ - public TableRowElement() { - super("tr", new ListElement()); - } - - /** - * Add a column to the row - * - * @param ne add the element wrapped inside a TableDataElement - * @see TableDataElement - */ - public void addElement(Element ne) { - ((ListElement) e).addElement(new TableDataElement(ne)); - } - - /** - * Add a column to the row - * - * @param s add the element wrapped inside a TableDataElement - * @see TableDataElement - */ - public void addElement(String s) { - ((ListElement) e).addElement(new TableDataElement(s)); - } - - /** - * Add a column to the row - * - * @param c adds the cell to the row (doesn't wrap it) - */ - public void addElement(TableCellElement c) { - ((ListElement) e).addElement(c); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/WrapElement.java b/src/core/src/main/java/com/bbn/openmap/util/html/WrapElement.java deleted file mode 100644 index 5fedde408..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/WrapElement.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/html/WrapElement.java,v $ -// $RCSfile: WrapElement.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.html; - -/** - * This class is used for html tags that are begin/end paired. For - * example, the html - * <code>wrapped element</code> would have - * a wrapString of code, and an element of "wrapped element" - */ -public class WrapElement implements Element { - - /** the html tag to "wrap" around the contained element */ - protected String wrapString; - /** params for the tag open */ - protected String paramString; - /** the element that gets wrapped */ - protected Element e; - - /** - * Construct a WrapElement with just a wrapping string - * - * @param wrapString the html tag that gets wrapped around the - * element - */ - public WrapElement(String wrapString) { - this(wrapString, null, null); - } - - /** - * Construct a WrapElement with a wrapping string and element - * - * @param wrapString the html tag that gets wrapped around the - * element - * @param e the element that gets contained - */ - public WrapElement(String wrapString, Element e) { - this(wrapString, null, e); - } - - /** - * Construct a WrapElement with a wrapping string and params - * - * @param wrapString the html tag that gets wrapped around the - * element - * @param paramString the string that gets contained - */ - public WrapElement(String wrapString, String paramString) { - this(wrapString, paramString, null); - } - - /** - * Construct a WrapElement with a wrapping string, params and - * element - * - * @param wrapString the html tag that gets wrapped around the - * element - * @param e the element that gets contained - */ - public WrapElement(String wrapString, String paramString, Element e) { - this.wrapString = wrapString; - this.paramString = paramString; - this.e = e; - } - - /** - * Writer for the Element attribute - * - * @param e the new element value - */ - public void setElement(Element e) { - this.e = e; - } - - /** - * Accessor for the element attribute - * - * @return the contained element - */ - public Element getElement() { - return e; - } - - /** - * convert representation to html and write it out - * - * @param out the output Writer - * @exception java.io.IOException an IO error occurred accessing - * out - */ - public void generate(java.io.Writer out) throws java.io.IOException { - out.write("<" + wrapString); - if (paramString != null) { - out.write(" " + paramString); - } - out.write(">"); - e.generate(out); - out.write("\r\n"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/html/package.html b/src/core/src/main/java/com/bbn/openmap/util/html/package.html deleted file mode 100644 index ca0aa0e35..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/html/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide utility code for generating simple HTML documents. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/FileListener.java b/src/core/src/main/java/com/bbn/openmap/util/http/FileListener.java deleted file mode 100644 index 61e58cf3c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/FileListener.java +++ /dev/null @@ -1,69 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/FileListener.java,v $ -// $RCSfile: FileListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.FileInputStream; -import java.io.IOException; - -import com.bbn.openmap.util.Debug; - -/** - * An HttpRequestListener that sends a file back. - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public class FileListener implements HttpRequestListener { - - public FileListener() {} - - /** - * Reverse the input and send it back to the client. - */ - public void httpRequest(HttpRequestEvent e) throws IOException { - String filename = e.getRequest().substring(1); - if (Debug.debugging("http")) { - Debug.output("FileListener: Looking for file " + filename); - } - - FileInputStream requestedfile; - try { - requestedfile = new FileInputStream(filename); - } catch (java.io.FileNotFoundException exception) { - Debug.error("FileListener: Unable to find file " + filename); - return; - // Need a return value here - } - - // Read in the file's bytes. This doesn't seem super efficient - int bytes = requestedfile.available(); - byte[] b = new byte[bytes]; - int bytes_read = requestedfile.read(b); - if (bytes_read != bytes) { - Debug.error("FileListener: Did not read the correct number of bytes for " - + filename); - } - // and write out the raw bytes - e.getWriter().write(new String(b)); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/HttpConnection.java b/src/core/src/main/java/com/bbn/openmap/util/http/HttpConnection.java deleted file mode 100644 index fd837721d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/HttpConnection.java +++ /dev/null @@ -1,370 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/HttpConnection.java,v $ -// $RCSfile: HttpConnection.java,v $ -// $Revision: 1.8 $ -// $Date: 2007/01/25 22:11:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.Socket; -import java.util.StringTokenizer; - -import com.bbn.openmap.util.Debug; - -/** - * HttpConnection handles the communication with an HTTP client in its - * own thread. An instance of this class is created by the - * HttpServer each time a connection is made. The - * instance exists only long enough to fulfill the request, then dies. - * - * @author Tom Mitchell - * @version 1.1, 06/17/97 - * @see HttpServer - */ -public class HttpConnection extends Thread { - - protected HttpServer server; - protected Socket client; - protected BufferedReader in; - protected OutputStream out; - protected boolean isConnectionOpen = true; - - public final static String CONTENT_JPEG = "image/jpeg"; - public final static String CONTENT_GIF = "image/gif"; - public final static String CONTENT_PPM = "image/ppm"; - public final static String CONTENT_PNG = "image/png"; - public final static String CONTENT_TIFF = "image/tiff"; - public final static String CONTENT_GEOTIFF = "image/geotiff"; - public final static String CONTENT_WBMP = "image/wbmp"; - public final static String CONTENT_SVG = "image/svg"; - public final static String CONTENT_HTML = "text/html"; - public final static String CONTENT_MOV = "video/quicktime"; - public final static String CONTENT_PLAIN = "text/plain"; - public final static String CONTENT_XML = "text/xml"; - public final static String CONTENT_JSON = "application/json"; - - /** - * Initialize the input Reader and output - * Writer and start the connection thread. - * - * @param client_socket the client's socket - * @param server the server object - */ - public HttpConnection(Socket client_socket, HttpServer server) { - client = client_socket; - this.server = server; - InputStreamReader isr; -// OutputStreamWriter osr; - - try { - isr = new InputStreamReader(client.getInputStream()); - in = new BufferedReader(isr); - out = client.getOutputStream(); -// osr = new OutputStreamWriter(client.getOutputStream()); -// out = new BufferedWriter(osr); - } catch (IOException e) { - try { - close(); - } catch (IOException e2) { - } - System.err.println("Exception while getting socket streams: " + e); - return; - } - } - - public static String[] getAllContentTypes() { - return new String[] { CONTENT_JPEG, CONTENT_GIF, CONTENT_HTML, - CONTENT_MOV, CONTENT_PLAIN, CONTENT_XML, CONTENT_PPM, - CONTENT_PNG, CONTENT_SVG, CONTENT_GEOTIFF, CONTENT_TIFF, - CONTENT_WBMP}; - } - - /** - * The running thread simply reads all the lines of input and - * hands each line off to be parsed. - */ - public void run() { - String line; - - try { - while (isConnectionOpen) { - // read in a line - line = in.readLine(); - if (line == null) - break; - processLine(line); - } - } catch (IOException e) { - } finally { - try { - close(); - } catch (IOException e2) { - } - } - Debug.message("httpconnection", "Connection closed. Exiting thread"); - } - - /** - * Processes a line of an HTTP request. The only interesting line - * we really look at is a GET command, which starts with "GET". - * - * @param line one line of an HTTP request - */ - protected void processLine(String line) throws IOException { - if (Debug.debugging("httpconnection")) { - Debug.output("HttpConnection | processLine -- Processing command " - + line); - } - - if (line.startsWith("GET")) { - processGetCommand(line); - } else if (line.startsWith("POST")) { - Debug.message("httpconnection", "handling POST"); - handlePost(); - } - } - - protected void handlePost() throws IOException { - Debug.message("httpconnection", "HttpConnection | handlePost"); - String line; - int contentLength = 0; - try { - while (isConnectionOpen) { - // read in a line - line = in.readLine(); - Debug.message("httpconnection", line); - - if (line == null) - break; - - String lineupp = line.toUpperCase(); - if (lineupp.startsWith("CONTENT-LENGTH")) { - contentLength = readContentLength(line); - Debug.message("httpconnection", - "HttpConnection -- Contentlength = " - + contentLength); - } - - if (line.length() == 0) { - readContent(contentLength); - } - } - } catch (IOException e) { - } finally { - try { - close(); - } catch (IOException e2) { - } - } - } - - protected int readContentLength(String line) { - // Find the content length and read it - StringTokenizer tokenizer = new StringTokenizer(line, ":"); - // this is first token "Content-length" - tokenizer.nextToken(); - // Actual length after ':' "Content-length: xxx" - String strLength = tokenizer.nextToken(); - int length = Integer.parseInt(strLength.trim()); - return length; - } - - // check if it is an environment key - value pair - // ASSUME actual content won't have ':' - protected boolean isEnvarLine(String line) { - if (line.indexOf(":") != -1) { - return true; - } - return false; - } - - protected void readContent(int length) throws IOException { - - char[] c_content = new char[length]; - int nread = 0; - int remaining = length; - try { - while (nread < length) { - //nread += in.read(c_content, nread, length); - int tmp = in.read(c_content, nread, remaining); - nread += tmp; - remaining -= tmp; - Debug.message("httpconnection", "Length of content read " - + nread + " length=" + length + " remaining=" - + remaining); - } - - } catch (java.io.IOException ioe) { - Debug.error("HttpConnection | readContent -- Exception while reading content(key-values from POST) " - + ioe.getMessage()); - } - - String content = new String(c_content); - content = content.trim(); - - if (Debug.debugging("httpconnection")) { - Debug.output("HttpConection showing Content :-- " + content); - } - - //processGetCommand(content); - - HttpRequestEvent event = server.fireHttpRequestEvent(content, out); - - // Check to see if the Writer in the Event was used. If it - // was, then the listeners contributed concatenated text, and - // the result needs to be retrieved and sent back. - if (event.isWriterUsed()) { - Writer writer = event.getWriter(); - String result = writer.toString(); - writeHttpResponse(out, null, result); - } - - // else - assume that the binary response listeners took care - // of writing things back on their own, - - out.flush(); - close(); - } - - /** - * Process a "GET" HTTP command. The leading "GET " and the - * trailing HTTP version information are stripped off and a - * HttpRequestEvent is fired via the HttpServer. - * - * @param cmd a "GET" HTTP command - */ - protected void processGetCommand(String cmd) throws IOException { - // Command looks like: "GET /thisURL HTTP/1.0" - String location = cmd.substring(4); // remove the "GET " - int locationEnd = location.indexOf(" "); // end at first space - location = location.substring(0, locationEnd); - - // Figure out what type of file to figure Content-type - // string contents - String contentType; - if (location.endsWith(".gif") || location.endsWith(".GIF")) { - - contentType = CONTENT_GIF; - - } else if (location.endsWith(".htm") || location.endsWith(".html") - || location.endsWith(".HTM") || location.endsWith(".HTML")) { - - contentType = CONTENT_HTML; - - } else if (location.endsWith(".jpg") || location.endsWith(".JPG") - || location.endsWith(".jpeg") || location.endsWith(".JPEG")) { - - contentType = CONTENT_JPEG; - - } else if (location.endsWith(".mov") || location.endsWith(".MOV")) { - - contentType = CONTENT_MOV; - - } else if (location.indexOf('?') != -1) { - - contentType = null; - - } else { - contentType = CONTENT_PLAIN; - } - - HttpRequestEvent event = server.fireHttpRequestEvent(location, out); - - // Check to see if the Writer in the Event was used. If it - // was, then the listeners contributed concatenated text, and - // the result needs to be retrieved and sent back. - if (event.isWriterUsed()) { - Writer writer = event.getWriter(); - String result = writer.toString(); - writeHttpResponse(out, contentType, result); - } - - // else - assume that the binary response listeners took care - // of writing things back on their own, - - out.flush(); - close(); - } - - /** - * Can be used to write the header to an HttpResponse. You need to - * create a Writer tied to the OutputStream in order to write this - * text. - * - * @param out Writer to place text on the OutputStream. - * @param contentType the mime type for your response. - * @param contentLength the byte length of your response. - */ - public static void writeHttpResponseHeader(Writer out, String contentType, - int contentLength) - throws IOException { - - out.write("HTTP/1.0 200 \n"); // return status - out.write("Content-type: " + contentType + "\n"); // important! - out.write("Content-Length: " + contentLength + "\n"); // important! - out.write("\n"); - } - - /** - * Write a String response to the OutputStream. - * - * @param out the OutputStream of the response. - * @param contentType the content type of the response. - * @param response the string containing the response. - */ - public static void writeHttpResponse(OutputStream out, String contentType, - String response) throws IOException { - - OutputStreamWriter osw = new OutputStreamWriter(out); - writeHttpResponseHeader(osw, contentType, response.length()); - osw.write(response); - osw.flush(); - } - - /** - * Write a byte[] response to the OutputStream. - * - * @param out the OutputStream of the response. - * @param contentType the content type of the response. - * @param response the byte array containing the response. - */ - public static void writeHttpResponse(OutputStream out, String contentType, - byte[] response) throws IOException { - OutputStreamWriter osw = new OutputStreamWriter(out); - writeHttpResponseHeader(osw, contentType, response.length); - osw.flush(); - out.write(response, 0, response.length); - osw.flush(); - } - - /** - * Close the socket connection that we have opened - */ - public void close() throws IOException { - client.close(); - isConnectionOpen = false; - } -} - diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestEvent.java b/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestEvent.java deleted file mode 100644 index 1c126bf86..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestEvent.java +++ /dev/null @@ -1,104 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/HttpRequestEvent.java,v $ -// $RCSfile: HttpRequestEvent.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.OutputStream; -import java.io.StringWriter; -import java.io.Writer; - -/** - * An event corresponding to a single HTTP request ("GET" command). - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public class HttpRequestEvent extends java.util.EventObject { - - protected String request; - protected OutputStream output; - protected Writer writer; - - /** - * Creates an http request event. - * - * @param source the source object - * @param request the parsed target of the "GET" command - * @param out the http client output stream - */ - public HttpRequestEvent(Object source, String request, OutputStream out) { - super(source); - this.request = request; - this.output = out; - } - - /** - * Gets the http request, which is the target of the "GET" - * command. - *

- * For the URL - * http://www.bbn.com/openmap/docs/index.html - *

- * the request string is /openmap/docs/index.html - * - * @return the request string - */ - public String getRequest() { - return request; - } - - /** - * Gets the output stream connected to the http client. - * - * @return the OutputStream associated with the http client. - */ - public OutputStream getOutputStream() { - return output; - } - - /** - * Get a Writer associated with the output stream connected to the - * http client. If a writer hasn't been created, then one will be. - * - * @return the Writer associated with the http client. - * @see java.io.Writer - */ - public Writer getWriter() { - if (writer == null) { - writer = new StringWriter(); - } - return writer; - } - - /** - * Find out if anyone used the writer. If it has been used, then, - * as a HttpServer, you can assume that the listeners were all - * contributing text into the writer, and you now need to take the - * Writer buffer, create a string, and write the contents as - * output. - * - * @return true if the writer has been created. - */ - public boolean isWriterUsed() { - return (writer != null); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestListener.java b/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestListener.java deleted file mode 100644 index 7752e466a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/HttpRequestListener.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/HttpRequestListener.java,v $ -// $RCSfile: HttpRequestListener.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -/** - * The listener interface for receiving http requests. - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public interface HttpRequestListener extends java.util.EventListener { - - /** - * Invoked when an http request is received. - */ - public void httpRequest(HttpRequestEvent e) throws java.io.IOException; -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/HttpServer.java b/src/core/src/main/java/com/bbn/openmap/util/http/HttpServer.java deleted file mode 100644 index 203aba17c..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/HttpServer.java +++ /dev/null @@ -1,236 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/HttpServer.java,v $ -// $RCSfile: HttpServer.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:57:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Enumeration; -import java.util.Vector; - -import com.bbn.openmap.util.Debug; - -/** - * A simple HTTP Server implementing HTTP/0.9 protocols. - * - * Cobbled together from a server originally written by David Flanagan - * for the book Java in a Nutshell , Copyright(c) 1996 - * O'Reilly & Associates. - * - * Modified to use JDK 1.1 Readers, and Writers. Further modified to - * use the JDK 1.1 Event model. - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public class HttpServer extends Thread { - - /** - * The default port. A port of 0 (zero) causes the system to - * allocate any unused port. With any other number the system will - * attempt to open that port, and throw an exception if it is in - * use. - */ - public final static int DEFAULT_PORT = 0; - - protected int port; - protected ServerSocket listen_socket; - protected Vector listeners; - - /** - * Creates an Http Server on the indicated port, and then starts a - * thread that listens to that port. The thread will not be a - * daemon thread. - * - * @param port the port to open - * @see java.net.ServerSocket - */ - public HttpServer(int port) throws IOException { - this(port, false); - } - - /** - * Creates an Http Server on the indicated port, and then starts a - * thread that listens to that port. The thread will be a daemon - * thread of asDaemon is true. - * - * @param port the port to open - * @param asDaemon whether to make thread a daemon - * @see java.net.ServerSocket - */ - public HttpServer(int port, boolean asDaemon) throws IOException { - this.port = port; - listeners = new Vector(); - listen_socket = new ServerSocket(port); - this.setDaemon(asDaemon); - } - - /** - * Creates an Http Server on any free port, and then starts a - * thread that listens to that port. - * - * @see java.net.ServerSocket - */ - public HttpServer() throws IOException { - this(DEFAULT_PORT); - } - - /** - * The body of the server thread. Loop forever, listening for and - * accepting connections from clients. For each connection, create - * a HttpConnection object to handle communication through the new - * Socket. - * - * @see HttpConnection - * @see java.net.Socket - */ - public void run() { - try { - while (true) { - Socket client_socket = listen_socket.accept(); - HttpConnection httpConnection = new HttpConnection(client_socket, this); - httpConnection.start(); - } - } catch (IOException e) { - System.err.println("Exception while listening for connections"); - e.printStackTrace(); - } - } - - /** - * Gets the port associate with this server. - * - * @return the server's port - */ - public int getPort() { - return listen_socket.getLocalPort(); - } - - /** - * Creates a HttpRequestEvent and sends it to all registered - * listeners. - * - * @param request the parsed http request - * @param output OutputStream associated with the request's client - * connection. - * @see java.io.DataOutputStream - * @see HttpRequestListener - * @see HttpRequestEvent - */ - public HttpRequestEvent fireHttpRequestEvent(String request, - OutputStream output) - throws IOException { - - HttpRequestEvent event = new HttpRequestEvent(this, request, output); - - HttpRequestListener listener; - // Make a copy of the list and fire the events using that - // copy. - // This means that listeners can be added or removed from the - // original list in response to this event. - Vector list = (Vector) listeners.clone(); - Enumeration e = list.elements(); - while (e.hasMoreElements()) { - listener = (HttpRequestListener) e.nextElement(); - listener.httpRequest(event); - } - - return event; - } - - /** - * Adds a new http request listener. Don't add multiple listeners - * when binary content responses are required! One Listener should - * handle binary responses, because the result length needs to be - * calculated. You can add multiple Listeners that use the Writer - * inside the HttpRequestEvent to concatenate a complete text - * response. - * - * @param l the listener - * @see HttpRequestListener - */ - public void addHttpRequestListener(HttpRequestListener l) { - listeners.addElement(l); - } - - /** - * Removes an http request listener. - * - * @param l a listener - * @see HttpRequestListener - */ - public void removeHttpRequestListener(HttpRequestListener l) { - listeners.removeElement(l); - } - - /** - * A main routine for unit testing. Starts a HttpServer, adds - * several HttpRequestListeners, and waits for connections. - *

- * Usage: java com.bbn.openmap.layer.util.http.HttpServer [port] - *

- * If no port is specified, the default port is used. - *

- * If port zero is specified, the system chooses the port. - *

- * If a port other than zero is specified, the http server will - * attempt to open that port, or fail if it is in use. - *

- * Examples: - *

- * java com.bbn.openmap.layer.util.http.HttpServer - *

- * java com.bbn.openmap.layer.util.http.HttpServer 8000 - *

- * java com.bbn.openmap.layer.util.http.HttpServer 0 - *

- * - * @param args command line args - */ - public static void main(String[] args) { - Debug.init(); - int port = 0; - if (args.length == 1) { - try { - port = Integer.parseInt(args[0]); - } catch (NumberFormatException e) { - port = 0; - } - } - - try { - HttpServer server = new HttpServer(port); - server.addHttpRequestListener(new SeparatorListener()); - server.addHttpRequestListener(new SieveListener()); - server.addHttpRequestListener(new SeparatorListener()); - server.addHttpRequestListener(new ReverseListener()); - server.addHttpRequestListener(new SeparatorListener()); - server.start(); - System.out.println("Server listening on port " + server.getPort()); - } catch (IOException e) { - System.err.println("Unable to start http server:"); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/IHttpResponse.java b/src/core/src/main/java/com/bbn/openmap/util/http/IHttpResponse.java deleted file mode 100644 index ee286077d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/IHttpResponse.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.bbn.openmap.util.http; - -import java.io.IOException; - -/** - */ -public interface IHttpResponse { - - /** - * Write a String response to the OutputStream. - * - * @param contentType the content type of the response. - * @param response the string containing the response. - */ - public void writeHttpResponse(String contentType, String response) - throws IOException; - - /** - * Write a byte[] response to the OutputStream. - * - * @param contentType the content type of the response. - * @param response the byte array containing the response. - */ - public void writeHttpResponse(String contentType, byte[] response) - throws IOException; -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/ReverseListener.java b/src/core/src/main/java/com/bbn/openmap/util/http/ReverseListener.java deleted file mode 100644 index c3ea05cfe..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/ReverseListener.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/ReverseListener.java,v $ -// $RCSfile: ReverseListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.IOException; - -/** - * An HttpRequestListener that reverses its input. - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public class ReverseListener implements HttpRequestListener { - public ReverseListener() {} - - /** - * Reverse the input and send it back to the client. - */ - public void httpRequest(HttpRequestEvent e) throws IOException { - // reverse the input - int len = e.getRequest().length(); - StringBuffer revline = new StringBuffer(len); - for (int i = len - 1; i >= 0; i--) - revline.insert(len - 1 - i, e.getRequest().charAt(i)); - - // and write out the reversed request - e.getWriter().write(revline.toString()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/SeparatorListener.java b/src/core/src/main/java/com/bbn/openmap/util/http/SeparatorListener.java deleted file mode 100644 index 8865827bf..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/SeparatorListener.java +++ /dev/null @@ -1,37 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/SeparatorListener.java,v $ -// $Revision: 1.5 $ $Date: 2004/10/14 18:06:07 $ $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.IOException; - -/** - * An HttpRequestListener that writes an HTML Separator ("<HR>") - * to the client. - */ -public class SeparatorListener implements HttpRequestListener { - public SeparatorListener() {} - - /** - * Ignore the request, just write the separator. - */ - public void httpRequest(HttpRequestEvent e) throws IOException { - e.getWriter().write("


"); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/SieveListener.java b/src/core/src/main/java/com/bbn/openmap/util/http/SieveListener.java deleted file mode 100644 index 10aa3a9f1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/SieveListener.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/http/SieveListener.java,v $ -// $RCSfile: SieveListener.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.http; - -import java.io.IOException; - -/** - * An HttpRequestListener that returns the request to the client. - * - * @author Tom Mitchell - * @version 1.0, 06/13/97 - */ -public class SieveListener implements HttpRequestListener { - public SieveListener() {} - - /** - * Just write the request out to the client. - */ - public void httpRequest(HttpRequestEvent e) throws IOException { - e.getWriter().write(e.getRequest()); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/http/package.html b/src/core/src/main/java/com/bbn/openmap/util/http/package.html deleted file mode 100644 index 7a6600e21..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/http/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides some utility classes for serving data via the HTTP protocol. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/package.html b/src/core/src/main/java/com/bbn/openmap/util/package.html deleted file mode 100644 index 2153ad113..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide miscellaneous utility classes for OpenMap. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ColorPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ColorPropertyEditor.java deleted file mode 100644 index 5ef4b039f..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ColorPropertyEditor.java +++ /dev/null @@ -1,208 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/ColorPropertyEditor.java,v $ -// $RCSfile: ColorPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2006-10-25 12:21:51 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyEditorSupport; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMColorChooser; -import com.bbn.openmap.tools.icon.IconPartList; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.tools.icon.OpenMapAppPartCollection; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that brings up a JFileChooser panel to select a - * file. - */ -public class ColorPropertyEditor extends PropertyEditorSupport { - - /** The Component returned by getCustomEditor(). */ - JButton button; - - static I18n i18n = Environment.getI18n(); - - public final static String title = i18n.get(ColorPropertyEditor.class, "Select_color","Select color..."); - - protected int icon_width = 20; - protected int icon_height = 20; - - /** Create FilePropertyEditor. */ - public ColorPropertyEditor() { - button = new JButton(title); - } - - // - // PropertyEditor interface - // - - /** - * PropertyEditor interface. - * - * @return true - */ - @Override - public boolean supportsCustomEditor() { - return true; - } - - /** - * Returns a JButton that will bring up a JFileChooser dialog. - * - * @return JButton button - */ - @Override - public Component getCustomEditor() { - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - - Color startingColor; - try { - startingColor = ColorFactory.parseColor(getAsText(), true); - } catch (NumberFormatException nfe) { - startingColor = OMColor.clear; - } - - Color color = OMColorChooser.showDialog(button, - title, - startingColor); - - if (color == null) { - // Canceled. - color = startingColor; - } - - ColorPropertyEditor.this.setValue(color); - } - }); - - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - c.weightx = 1; - panel.setLayout(gridbag); - gridbag.setConstraints(button, c); - panel.add(button); - - return panel; - } - - public ImageIcon getIconForPaint(Paint paint, boolean fill) { - - if (paint == null) { - paint = Color.black; - } - - DrawingAttributes da = new DrawingAttributes(); - da.setLinePaint(paint); - da.setStroke(new BasicStroke(2)); - if (fill) { - da.setFillPaint(paint); - } - - OpenMapAppPartCollection collection = OpenMapAppPartCollection.getInstance(); - IconPartList parts = new IconPartList(); - - if (paint instanceof Color || paint == OMColor.clear) { - Color color = (Color) paint; - Color opaqueColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); - DrawingAttributes opaqueDA = new DrawingAttributes(); - opaqueDA.setLinePaint(opaqueColor); - opaqueDA.setStroke(new BasicStroke(2)); - - if (fill) { - opaqueDA.setFillPaint(opaqueColor); - } - - parts.add(collection.get("LR_TRI", opaqueDA)); - parts.add(collection.get("UL_TRI", da)); - } else { - parts.add(collection.get("BIG_BOX", da)); - } - - return OMIconFactory.getIcon(icon_width, icon_height, parts); - } - - /** Implement PropertyEditor interface. */ - @Override - public void setValue(Object someObj) { - - if (someObj == null) { - setButtonForColor(Color.black); - } else if (someObj instanceof Color) { - setButtonForColor((Color) someObj); - } else if (someObj instanceof String) { - Color color = OMColor.clear; - try { - color = ColorFactory.parseColor((String) someObj, true); - } catch (NumberFormatException nfe) { - Debug.output("ColorPropertyEditor.setValue problem with color: " + someObj + "\n" - + nfe.getMessage()); - } - - setButtonForColor(color); - } - } - - protected void setButtonForColor(Color color) { - button.setIcon(getIconForPaint(color, true)); - String val = Integer.toHexString(color.getRGB()); - if (val.equals("0")) { - val = "00000000"; - } - - button.setText(val); - } - - /** Implement PropertyEditor interface. */ - @Override - public String getAsText() { - return button.getText(); - } - - // - // ActionListener interface - // - - /** Implement ActionListener interface. */ - public void actionPerformed(ActionEvent e) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ComboBoxPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ComboBoxPropertyEditor.java deleted file mode 100644 index c305d2117..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/ComboBoxPropertyEditor.java +++ /dev/null @@ -1,65 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/ComboBoxPropertyEditor.java,v $ -// $RCSfile: ComboBoxPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JComboBox; - -import com.bbn.openmap.util.Debug; - -/** - * The ComboBoxPropertyEditor provides a set of options within a - * JComboBox. - * - * @see OptionPropertyEditor - */ -public class ComboBoxPropertyEditor extends OptionPropertyEditor { - - protected JComboBox combo; - - public ComboBoxPropertyEditor() {} - - public void setOptions(String[] options) { - combo = new JComboBox<>(options); - setCustomEditor(combo); - } - - /** Sets option based on string. */ - public void setValue(Object string) { - if (combo != null) { - combo.setSelectedItem(string); - } else { - Debug.output("Setting " + string - + " before ComboBoxPropertyEditor is ready"); - } - } - - /** Returns String from option choices. */ - public String getAsText() { - if (combo != null) { - return (String) combo.getSelectedItem(); - } else { - return ""; - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/DirectoryPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/DirectoryPropertyEditor.java deleted file mode 100644 index 291e8638d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/DirectoryPropertyEditor.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/DirectoryPropertyEditor.java,v $ -// $RCSfile: DirectoryPropertyEditor.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/05/24 17:55:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JFileChooser; - -/** - * A PropertyEditor that brings up a JFileChooser panel to select a - * directory. A single directory choice can be made, and only choices - * that reside on the local file system. - */ -public class DirectoryPropertyEditor extends FilePropertyEditor { - - /** - * - */ - public DirectoryPropertyEditor() {} - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return JFileChooser.DIRECTORIES_ONLY for - * DirectoryPropertyEditor. - */ - public int getFileSelectionMode() { - return JFileChooser.DIRECTORIES_ONLY; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FDUPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FDUPropertyEditor.java deleted file mode 100644 index 1d9209447..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FDUPropertyEditor.java +++ /dev/null @@ -1,57 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/FDUPropertyEditor.java,v $ -// $RCSfile: FDUPropertyEditor.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/05/24 17:55:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JFileChooser; - -/** - * FDUPropertyEditor - File, Directory and URL PropertyEditor. This is - * a PropertyEditor that provides a text field where a URL, file path - * or directory path can be entered. There is also a button that - * brings up a file chooser, and anything chosen *replaces* the - * contents in the text field. - */ -public class FDUPropertyEditor extends FilePropertyEditor { - - /** Create FDUDirectoryPropertyEditor. */ - public FDUPropertyEditor() {} - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return true for FDUPropertyEditor. - */ - public boolean isTextFieldEditable() { - return true; - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return JFileChooser.FILES_AND_DIRECTORIES for FDUPropertyEditor. - */ - public int getFileSelectionMode() { - return JFileChooser.FILES_AND_DIRECTORIES; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FUPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FUPropertyEditor.java deleted file mode 100644 index 5f1e4d4d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FUPropertyEditor.java +++ /dev/null @@ -1,47 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/FUPropertyEditor.java,v $ -// $RCSfile: FUPropertyEditor.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/05/24 17:55:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - - -/** - * FUPropertyEditor - File and URL PropertyEditor. This is a - * PropertyEditor that provides a text field where a URL or file path - * can be entered. There is also a button that brings up a file - * chooser, and anything chosen *replaces* the contents in the text - * field. - */ -public class FUPropertyEditor extends FilePropertyEditor { - - /** Create FUPropertyEditor. */ - public FUPropertyEditor() {} - - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return true for FUPropertyEditor. - */ - public boolean isTextFieldEditable() { - return true; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FilePropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FilePropertyEditor.java deleted file mode 100644 index 612875f60..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/FilePropertyEditor.java +++ /dev/null @@ -1,197 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/FilePropertyEditor.java,v $ -// $RCSfile: FilePropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2006-10-25 12:21:51 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyEditorSupport; - -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JPanel; -import javax.swing.JTextField; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that brings up a JFileChooser panel to select a - * file. A single file choice can be made, and only choices that - * reside on the local file system. - */ -public class FilePropertyEditor extends PropertyEditorSupport implements - ActionListener { - - /** The Component returned by getCustomEditor(). */ - protected JButton button; - protected JTextField textField = new JTextField(15); - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - /** Create FilePropertyEditor. */ - public FilePropertyEditor() { - button = new JButton(getButtonTitle()); - textField.setEditable(isTextFieldEditable()); - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return "Set" for FilePropertyEditor. - */ - public String getButtonTitle() { - return i18n.get(FilePropertyEditor.class, "Set", "Set"); - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return false for FilePropertyEditor. - */ - public boolean isTextFieldEditable() { - return false; - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return JFileChooser.FILES_ONLY for FilePropertyEditor. - */ - public int getFileSelectionMode() { - return JFileChooser.FILES_ONLY; - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return false for FilePropertyEditor. - */ - public boolean isMultiSelectEnabled() { - return false; - } - - // - // PropertyEditor interface - // - - /** - * PropertyEditor interface. - * - * @return true - */ - @Override - public boolean supportsCustomEditor() { - return true; - } - - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = getFileChooser(); - int returnVal = chooser.showOpenDialog((Component) null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String newFilename = chooser.getSelectedFile().getAbsolutePath(); - newFilename = cleanUpName(newFilename); - textField.setText(newFilename); - firePropertyChange(); - } - } - - /** - * Change double backslashes to forward slash, OK for java world. - */ - protected String cleanUpName(String name) { - // replace all back slashes with forward slashes to permit - // safe writing and reading from PrintStreams - return name.replace('\\', '/').trim(); - } - - /** - * Returns an uneditable text area with a JButton that will bring - * up a JFileChooser dialog. - * - * @return JButton button - */ - @Override - public Component getCustomEditor() { - button.addActionListener(this); - - JPanel jp = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - jp.setLayout(gridbag); - - c.weightx = 1f; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(textField, c); - jp.add(textField); - - c.weightx = 0; - c.anchor = GridBagConstraints.EAST; - c.fill = GridBagConstraints.NONE; - gridbag.setConstraints(button, c); - jp.add(button); - return jp; - } - - public JFileChooser getFileChooser() { - JFileChooser chooser = new JFileChooser(getLastLocation()); - chooser.setFileSelectionMode(getFileSelectionMode()); - chooser.setMultiSelectionEnabled(isMultiSelectEnabled()); - return chooser; - } - - /** Implement PropertyEditor interface. */ - @Override - public void setValue(Object someObj) { - if (someObj instanceof String) { - textField.setText((String) someObj); - } - } - - /** Implement PropertyEditor interface. */ - @Override - public String getAsText() { - return textField.getText(); - } - - public String getLastLocation() { - String currentLocation = getAsText(); - char sepChar = '/'; // Java path separator - int lastSepIndex = currentLocation.lastIndexOf(sepChar); - // System.out.println(currentLocation + ", index of " + - // sepChar + " is at " + lastSepIndex); - if (currentLocation.length() == 0 || lastSepIndex == -1) { - currentLocation = null; - } else { - String substring = currentLocation.substring(0, lastSepIndex); - // System.out.println(substring); - currentLocation = substring; - } - return currentLocation; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/Inspector.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/Inspector.java deleted file mode 100644 index 801613ebb..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/Inspector.java +++ /dev/null @@ -1,531 +0,0 @@ -// Bart 20060831 -> i18n - -/* - * File: Inspector.java - * Date: Jul 2001 - * Author: Kai Lessmann - * Copyright 2001 Intevation GmbH, Germany - * - * This file is Free Software to be included into OpenMap - * under its Free Software license. - * Permission is granted to use, modify and redistribute. - * - * Intevation hereby grants BBN a royalty free, worldwide right and license - * to use, copy, distribute and make Derivative Works - * of this Free Software created by Kai Lessmann - * and sublicensing rights of any of the foregoing. - * - */ - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyEditor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.I18n; -import com.bbn.openmap.util.PropUtils; - -/** - * Class to inspect a PropertyConsumer. Used by the LayerAddPanel class to - * interactively configure a Layer object before it gets added to the map. This - * class should suffice to "inspect" any PropertyConsumer on a very basic level, - * handling is more convenient if property editor classes are available. The - * behavior of the Inspector is configured through properties; the - * propertiesInfo object of a PropertyConsumer may contain a - * initPropertiesProperty which determines which properties are to be shown and - * in which order, in a space separated list, i.e. - * - * - * initPropertiesProperty=class prettyName shapeFile - * - * If this property is not defined, then all the properties will be - * displayed, in alphabetical order. - * - * For each property there may be a editorProperty entry giving a PropertyEditor - * class to instantiate as an editor for the property, i.e. - * shapeFile.editor=com.bbn.openmap.util.propertyEditor.FilePropertyEditor - * . - */ -public class Inspector implements ActionListener { - - /** A simple TextField as a String editor. */ - protected final String defaultEditorClass = "com.bbn.openmap.util.propertyEditor.TextPropertyEditor"; - - /** - * The PropertyConsumer being inspected. Set in inspectPropertyConsumer. - */ - protected PropertyConsumer propertyConsumer = null; - - /** Handle to the GUI. Used for setVisible(true/false). */ - protected WindowSupport windowSupport = null; - - /** Action command for the cancelButton. */ - // public so it can be referenced from the actionListener - public final static String cancelCommand = "cancelCommand"; - - /** The action command for the doneButton. */ - // public so it can be referenced from the actionListener - public final static String doneCommand = "doneCommand"; - - /** - * Hashtable containing property names, and their editors. Used to fetch - * user inputs for configuring a property consumer. - */ - protected Hashtable editors = null; - - /** - * Handle to call back the object that invokes this Inspector. - */ - protected ActionListener actionListener = null; - - /** - * Flag to print out the properties. Used when the Inspector is in - * stand-alone mode, so that the properties are directed to stdout. - */ - protected boolean print = false; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - /** - * Set an ActionListener for callbacks. Once a Layer object is configured, - * i.e. the "Add" button has been clicked, an ActionListener that invoked - * this Inspector can register here to be notified. - */ - public void addActionListener(ActionListener al) { - actionListener = al; - } - - /** Does nothing. */ - public Inspector() {} - - /** Sets the actionListener. */ - public Inspector(ActionListener al) { - actionListener = al; - } - - /** - * Inspect and configure a PropertyConsumer object. Main method of this - * class. The argument PropertyConsumer is inspected through the - * ProperyConsumer interface, the properties are displayed to be edited. - */ - public void inspectPropertyConsumer(PropertyConsumer propertyConsumer) { - String prefix = propertyConsumer.getPropertyPrefix(); - - // construct GUI - if (windowSupport != null) { - windowSupport.killWindow(); - windowSupport = null; - } - - JComponent comp = createPropertyGUI(propertyConsumer); - windowSupport = new WindowSupport(comp, i18n.get(Inspector.class, - "Inspector", - "Inspector") - + " - " + prefix); - - windowSupport.setMaxSize(-1, 500); - windowSupport.displayInWindow(); - } - - public List sortKeys(Collection keySet) { - List ret = new ArrayList<>(keySet); - Collections.sort(ret); - return ret; - } - - /** - * Creates a JComponent with the properties to be changed. This component is - * suitable for inclusion into a GUI. - * - * @param pc The property consumer to create a gui for. - * @return JComponent, a panel holding the interface to set the properties. - */ - public JComponent createEmbeddedPropertyGUI(PropertyConsumer pc) { - // fill variables - this.propertyConsumer = pc; - Properties props = new Properties(); - props = pc.getProperties(props); - Properties info = new Properties(); - info = pc.getPropertyInfo(info); - String prefix = pc.getPropertyPrefix(); - - return createEmbeddedPropertyGUI(prefix, props, info); - } - - /** - * Creates a JComponent with the properties to be changed. This component is - * suitable for inclusion into a GUI. Don't use this method directly! Use - * the createPropertyGUI(PropertyConsumer) instead. You will get a - * NullPointerException if you use this method without setting the - * PropertyConsumer in the Inspector. - * - * @param prefix the property prefix for the property consumer. Received - * from the PropertyConsumer.getPropertyPrefix() method. Properties - * that start with this prefix will have the prefix removed from the - * display, so the GUI will only show the actual property name. - * @param props the properties received from the - * PropertyConsumer.getProperties() method. - * @param info the properties received from the - * PropertyConsumer.getPropertyInfo() method, containing descriptions - * and any specific PropertyEditors that should be used for a - * particular property named in the PropertyConsumer.getProperties() - * properties. - * @return JComponent, a panel holding the interface to set the properties. - */ - public JComponent createEmbeddedPropertyGUI(String prefix, - Properties props, - Properties info) { - - if (Debug.debugging("inspectordetail")) { - Debug.output("Inspector creating GUI for " + prefix - + "\nPROPERTIES " + props + "\nPROP INFO " + info); - } - - // collect the properties that are going to be displayed... - - // First, check the initPropertiesProperty for the PropertyConsumer - // stating which properties it wants included. - String propertyList = info.getProperty(PropertyConsumer.initPropertiesProperty); - List sortedKeys; - - if (propertyList != null) { - List propertiesToShow = PropUtils.parseSpacedMarkers(propertyList); - for (int i = 0; i < propertiesToShow.size(); i++) { - propertiesToShow.set(i, prefix + "." + propertiesToShow.get(i)); - } - sortedKeys = propertiesToShow; - } else { - // otherwise, show them all, in alphabetical order - sortedKeys = new ArrayList<>(props.stringPropertyNames()); - Collections.sort(sortedKeys); - } - - editors = new Hashtable(sortedKeys.size()); - - JPanel component = new JPanel(); - component.setLayout(new BorderLayout()); - - JPanel propertyPanel = new JPanel(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.insets = new Insets(2, 10, 2, 10); - propertyPanel.setLayout(gridbag); - - int i = 0; - for (String prop : sortedKeys) { - - // Marker is going to be the scoped version of prop, if needed. - String marker = prop; - if (prefix != null && prop.startsWith(prefix)) { - marker = prop.substring(prefix.length() + 1); - } - - if (marker.startsWith(".")) { - marker = marker.substring(1); - } - - String editorMarker = marker - + PropertyConsumer.ScopedEditorProperty; - String editorClass = info.getProperty(editorMarker); - if (editorClass == null) { - editorClass = defaultEditorClass; - } - - // instantiate PropertyEditor - Class propertyEditorClass = null; - PropertyEditor editor = null; - try { - propertyEditorClass = Class.forName(editorClass); - editor = (PropertyEditor) propertyEditorClass.newInstance(); - if (editor instanceof PropertyConsumer) { - ((PropertyConsumer) editor).setProperties(marker, info); - } - editors.put(prop, editor); - } catch (Exception e) { - e.printStackTrace(); - editorClass = null; - } - - Component editorFace = null; - if (editor != null && editor.supportsCustomEditor()) { - editorFace = editor.getCustomEditor(); - } else { - editorFace = new JLabel(i18n.get(Inspector.class, - "Does_not_support_custom_editor", - "Does not support custom editor")); - - } - - if (editor != null) { - Object propVal = props.get(prop); - if (Debug.debugging("inspector")) { - Debug.output("Inspector loading " + prop + "(" + propVal - + ")"); - } - editor.setValue(propVal); - } - - // Customized labels for each property, instead of the - // abbreviated nature of the true property names. - String labelMarker = marker + PropertyConsumer.LabelEditorProperty; - String labelText = info.getProperty(labelMarker); - if (labelText == null) { - labelText = marker; - } - - JLabel label = new JLabel(labelText + ":"); - label.setHorizontalAlignment(SwingConstants.RIGHT); - - c.gridx = 0; - c.gridy = i++; - c.weightx = 0; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.EAST; - - gridbag.setConstraints(label, c); - propertyPanel.add(label); - - c.gridx = 1; - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - - gridbag.setConstraints(editorFace, c); - propertyPanel.add(editorFace); - - String toolTip = (String) info.get(marker); - label.setToolTipText(toolTip == null ? i18n.get(Inspector.class, - "No_further_information_available", - "No further information available.") : toolTip); - - } - - // create the palette's scroll pane - JScrollPane scrollPane = new JScrollPane(propertyPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - scrollPane.setBorder(null); - // scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - component.add(scrollPane, BorderLayout.CENTER); - return component; - } - - /** - * Creates a JComponent with the properties to be changed. This component is - * suitable for inclusion into a GUI. - * - * @param pc The property consumer to create a gui for. - * @return JComponent, a panel holding the interface to set the properties. - */ - public JComponent createPropertyGUI(PropertyConsumer pc) { - // fill variables - this.propertyConsumer = pc; - Properties props = new Properties(); - props = pc.getProperties(props); - Properties info = new Properties(); - info = pc.getPropertyInfo(info); - String prefix = pc.getPropertyPrefix(); - - return createPropertyGUI(prefix, props, info); - } - - /** - * Creates a JComponent with the properties to be changed. This component is - * suitable for inclusion into a GUI. Don't use this method directly! Use - * the createPropertyGUI(PropertyConsumer) instead. You will get a - * NullPointerException if you use this method without setting the - * PropertyConsumer in the Inspector. - * - * @param prefix the property prefix for the property consumer. Received - * from the PropertyConsumer.getPropertyPrefix() method. Properties - * that start with this prefix will have the prefix removed from the - * display, so the GUI will only show the actual property name. - * @param props the properties received from the - * PropertyConsumer.getProperties() method. - * @param info the properties received from the - * PropertyConsumer.getPropertyInfo() method, containing descriptions - * and any specific PropertyEditors that should be used for a - * particular property named in the PropertyConsumer.getProperties() - * properties. - * @return JComponent, a panel holding the interface to set the properties. - */ - public JComponent createPropertyGUI(String prefix, Properties props, - Properties info) { - - JComponent component = createEmbeddedPropertyGUI(prefix, props, info); - - JButton doneButton = null, cancelButton = null; - - JPanel buttons = new JPanel(); - if (print) { - doneButton = new JButton(i18n.get(Inspector.class, "Print", "Print")); - cancelButton = new JButton(i18n.get(Inspector.class, "Quit", "Quit")); - } else { - doneButton = new JButton(i18n.get(Inspector.class, "Ok", "Ok")); - cancelButton = new JButton(i18n.get(Inspector.class, - "Cancel", - "Cancel")); - } - doneButton.addActionListener(this); - doneButton.setActionCommand(doneCommand); - cancelButton.addActionListener(this); - cancelButton.setActionCommand(cancelCommand); - buttons.add(doneButton); - buttons.add(cancelButton); - - component.add(buttons, BorderLayout.SOUTH); - - component.validate(); - return component; - } - - /** - * Implement the ActionListener interface. The actions registering here - * should be generated by the two buttons in the Inspector GUI. - */ - public void actionPerformed(ActionEvent e) { - final String actionCommand = e.getActionCommand(); - String prefix = propertyConsumer.getPropertyPrefix(); - - if (actionCommand == doneCommand) {// confirmed - Properties props = collectProperties(); - - if (!print) { - if (windowSupport != null) { - windowSupport.killWindow(); - } - propertyConsumer.setProperties(prefix, props); - if (actionListener != null) { - actionListener.actionPerformed(e); - } - } else { - Set> entrySet = props.entrySet(); - Iterator> it = entrySet.iterator(); - while (it.hasNext()) { - Entry next = it.next(); - String val = (String) next.getValue(); - System.out.println(next.getKey() + "=" + val); - } - } - - } else if (actionCommand == cancelCommand) {// canceled - if (actionListener != null && actionListener != this) { - actionListener.actionPerformed(e); - } - propertyConsumer = null; // to be garb. coll'd - if (windowSupport != null) { - windowSupport.killWindow(); - } - - if (print) { - System.exit(0); - } - } - } - - /** - * Tells the Inspector to collect the properties from the editors and set - * them on its PropertyConsumer. - */ - public void collectAndSetProperties() { - if (propertyConsumer != null) { - String prefix = propertyConsumer.getPropertyPrefix(); - Properties props = collectProperties(); - propertyConsumer.setProperties(prefix, props); - } - } - - /** Extracts properties from textfield[]. */ - public Properties collectProperties() { - Properties props = new Properties(); - - for (String key : editors.keySet()) { - PropertyEditor editor = editors.get(key); - if (editor != null) { - String stuff = editor.getAsText(); - // If it's not defined with text, don't put it in the - // properties. The layer should handle this and use - // its default settings. - if (stuff != null && stuff.length() > 0) { - props.put(key, stuff); - } - - if (editor instanceof PropertyConsumer) { - ((PropertyConsumer) editor).getProperties(props); - } - } - } - return props; - } - - public void setPrint(boolean p) { - print = p; - } - - public boolean getPrint() { - return print; - } - - public WindowSupport getWindowSupport() { - return windowSupport; - } - - /** test cases. */ - public static void main(String[] args) { - Debug.init(); - String name = (args.length < 1) ? "com.bbn.openmap.layer.shape.ShapeLayer" - : args[0]; - PropertyConsumer propertyconsumer = null; - try { - Class c = Class.forName(name); - propertyconsumer = (PropertyConsumer) c.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - System.exit(1); - } - - if (propertyconsumer != null) { - Properties props = new Properties(), info = new Properties(); - System.out.println("Inspecting " + name); - - String pp = name.substring(name.lastIndexOf(".") + 1); - propertyconsumer.setPropertyPrefix(pp.toLowerCase()); - - props = propertyconsumer.getProperties(props); - info = propertyconsumer.getPropertyInfo(info); - - Inspector inspector = new Inspector(); - inspector.setPrint(true); - inspector.addActionListener(inspector); - inspector.inspectPropertyConsumer(propertyconsumer); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirFilePropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirFilePropertyEditor.java deleted file mode 100644 index f0f043fa9..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirFilePropertyEditor.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/MultiDirFilePropertyEditor.java,v $ -// $RCSfile: MultiDirFilePropertyEditor.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/05/24 17:55:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JFileChooser; - -/** - * A PropertyEditor that brings up a JFileChooser panel to several - * files and directories. You can enter information in the text field, - * and pressing the add button will bring up a file chooser. Anything - * chosen in the file chooser will be appended to what is currently in - * the text field. - */ -public class MultiDirFilePropertyEditor extends MultiDirectoryPropertyEditor { - - /** Create MultiDirFilePropertyEditor. */ - public MultiDirFilePropertyEditor() {} - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return JFileChooser.DIRECTORIES_ONLY for - * MultiDirFilePropertyEditor. - */ - public int getFileSelectionMode() { - return JFileChooser.FILES_AND_DIRECTORIES; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirectoryPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirectoryPropertyEditor.java deleted file mode 100644 index 02cc62ae5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/MultiDirectoryPropertyEditor.java +++ /dev/null @@ -1,128 +0,0 @@ -// Bart 20060831 -> i18n -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/MultiDirectoryPropertyEditor.java,v $ -// $RCSfile: MultiDirectoryPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2006-10-25 12:21:51 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.io.File; - -import javax.swing.JFileChooser; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that brings up a JFileChooser panel that allows - * the user to choose one or more directories. The user can also enter - * information in the text field, and pressing the add button will - * bring up a file chooser. Anything chosen in the file chooser will - * be appended to what is currently in the text field. - */ -public class MultiDirectoryPropertyEditor extends FilePropertyEditor { - - protected char pathSeparator; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - /** Create MultiDirectoryPropertyEditor. */ - public MultiDirectoryPropertyEditor() { - setPathSeparator(';'); - } - - @Override - public String getButtonTitle() { - return i18n.get(MultiDirectoryPropertyEditor.class, "Add", "Add"); - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return true for MultiDirectoryPropertyEditor. - */ - @Override - public boolean isTextFieldEditable() { - return true; - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return JFileChooser.DIRECTORIES_ONLY for MultiDirectoryPropertyEditor. - */ - @Override - public int getFileSelectionMode() { - return JFileChooser.DIRECTORIES_ONLY; - } - - /** - * Internal callback method that can be overridden by subclasses. - * - * @return true for MultiDirectoryPropertyEditor. - */ - @Override - public boolean isMultiSelectEnabled() { - return true; - } - - /** - * Set the character to use when appending paths. - */ - public void setPathSeparator(char c) { - pathSeparator = c; - } - - public char getPathSeparator() { - return pathSeparator; - } - - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = getFileChooser(); - int returnVal = chooser.showOpenDialog((Component) null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - - File[] choices = chooser.getSelectedFiles(); - for (File element : choices) { - String newFilename = element.getAbsolutePath(); - newFilename = cleanUpName(newFilename); - append(newFilename); - } - firePropertyChange(); - } - } - - /** - * Add a path to the end of the current path. Uses the - * pathSeparator between paths. - */ - public void append(String addPath) { - String currentPath = textField.getText(); - if (currentPath.length() == 0) { - setValue(addPath); - } else { - setValue(currentPath.concat(";" + addPath)); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/NonEditablePropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/NonEditablePropertyEditor.java deleted file mode 100644 index 6ac65a910..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/NonEditablePropertyEditor.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/NonEditablePropertyEditor.java,v $ -// $RCSfile: NonEditablePropertyEditor.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.beans.PropertyEditorSupport; - -import javax.swing.JLabel; - -/** - * A PropertyEditor that doesn't let you edit the property. - */ -public class NonEditablePropertyEditor extends PropertyEditorSupport { - - /** The Component returned by getCustomEditor(). */ - JLabel label; - - /** Create NonEditablePropertyEditor. */ - public NonEditablePropertyEditor() {} - - // - // PropertyEditor interface - // - - /** - * PropertyEditor interface. - * - * @return true - */ - public boolean supportsCustomEditor() { - return true; - } - - /** - * Returns a blank JLabel. - * - * @return JButton button - */ - public Component getCustomEditor() { - if (label == null) { - label = new JLabel(); - } - return label; - } - - /** Implement PropertyEditor interface. */ - public void setValue(Object someObj) { - if (someObj instanceof String) { - label.setText((String) someObj); - } - } - - /** Implement PropertyEditor interface. */ - public String getAsText() { - return label.getText(); - } - - // - // ActionListener interface - // - - public void actionPerformed(ActionEvent e) {} -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OnOffPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OnOffPropertyEditor.java deleted file mode 100644 index 781d61ea3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OnOffPropertyEditor.java +++ /dev/null @@ -1,45 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/OnOffPropertyEditor.java,v $ -// $RCSfile: OnOffPropertyEditor.java,v $ -// $Revision: 1.1 $ -// $Date: 2006-08-31 15:56:07 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JRadioButton; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that displays a On/Off option. The widget returns - * true or false as a string when queried. - */ -public class OnOffPropertyEditor extends TrueFalsePropertyEditor { - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - public OnOffPropertyEditor() { - trueButton = new JRadioButton(i18n.get(OnOffPropertyEditor.class, "On", "On")); - falseButton = new JRadioButton(i18n.get(OnOffPropertyEditor.class, "Off", "Off")); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OptionPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OptionPropertyEditor.java deleted file mode 100644 index fbaae0ac5..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OptionPropertyEditor.java +++ /dev/null @@ -1,116 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/OptionPropertyEditor.java,v $ -// $RCSfile: OptionPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.event.FocusEvent; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The base class for property editors that support a list of options being - * presented in the GUI. When defining the properties that the property editor - * will use for a PropertyConsumer in the getPropertyInfo method, just use the - * name of the property that the options are being used for: - * - *
- * 
- * 
- *  BigNameOptionProperty.options=option1 option2 option3
- *  BigNameOptionProperty.option1=Big Name 1
- *  BigNameOptionProperty.option2=Big Name 2
- *  BigNameOptionProperty.option3=Big Name 3
- * 
- * 
- * 
- * - * Don't use the property prefix for the PropertyConsumer being defined, only - * the property. - */ -public abstract class OptionPropertyEditor extends PropertyConsumerPropertyEditor { - - public final static String OptionsProperty = "options"; - public final static String ScopedOptionsProperty = ".options"; - - protected Component customEditor = null; - - public OptionPropertyEditor() { - } - - public boolean supportsCustomEditor() { - return true; - } - - public void setCustomEditor(Component comp) { - customEditor = comp; - } - - /** Returns the editor GUI. */ - public Component getCustomEditor() { - return customEditor; - } - - public abstract void setOptions(String[] options); - - /** Sets option based on string. */ - public abstract void setValue(Object string); - - /** Returns String from option choices. */ - public abstract String getAsText(); - - public void focusGained(FocusEvent e) { - } - - public void focusLost(FocusEvent e) { - firePropertyChange(); - } - - /** - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - // get the options, first from the space separated option - // property list, then from the properties using the marker - // names from that list. - String[] options = null; - prefix = PropUtils.getScopedPropertyPrefix(prefix); - String optionListProperty = props.getProperty(prefix + OptionsProperty); - if (optionListProperty != null) { - List optionVector = PropUtils.parseSpacedMarkers(optionListProperty); - options = new String[optionVector.size()]; - for (int i = 0; i < options.length; i++) { - options[i] = props.getProperty(prefix + optionVector.get(i)); - } - - setOptions(options); - - } else { - Debug.error("OptionPropertyEditor for " + prefix + " not given options"); - } - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OrientationPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OrientationPropertyEditor.java deleted file mode 100644 index 74c987a3e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/OrientationPropertyEditor.java +++ /dev/null @@ -1,49 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/OrientationPropertyEditor.java,v -// $ -// $RCSfile: OrientationPropertyEditor.java,v $ -// $Revision: 1.1 $ -// $Date: 2006-08-31 15:56:07 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JRadioButton; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -public class OrientationPropertyEditor extends TrueFalsePropertyEditor { - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - public final static String VERTICAL = "vertical"; - public final static String HORIZONTAL = "horizontal"; - - public OrientationPropertyEditor() { - setUseAltCommandStrings(true); - trueButton = new JRadioButton(i18n.get(OrientationPropertyEditor.class, "Vertical", "Vertical")); - trueButton.setActionCommand(VERTICAL); - falseButton = new JRadioButton(i18n.get(OrientationPropertyEditor.class, "Horizontal", "Horizontal")); - falseButton.setActionCommand(HORIZONTAL); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/PropertyConsumerPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/PropertyConsumerPropertyEditor.java deleted file mode 100644 index 04e3d3b48..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/PropertyConsumerPropertyEditor.java +++ /dev/null @@ -1,129 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/PropertyConsumerPropertyEditor.java,v $ -// $RCSfile: PropertyConsumerPropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.beans.PropertyEditorSupport; -import java.util.Properties; - -import com.bbn.openmap.PropertyConsumer; - -/** - * The base class for property editors that can use properties to - * provide a more complex interface, and need more flexibility to - * contribute different parameters. The PropertyEditor's - * PropertyConsumer methods are called by the Inspector at particular - * times. The setProperties method is called to configure the - * PropertyConsumerPropertyEdtior. The prefix used in the - * setProperties method is the limited scope of just the property name - * being defined and/or adjusted. Any other properties defined need to - * also be defined at this level, with the property prefix used as a - * base. The getProperties() method will be called by the Inspector as - * a way for this property editor to provide more properties as a - * result of configuration. - */ -public abstract class PropertyConsumerPropertyEditor extends - PropertyEditorSupport implements PropertyConsumer { - - protected String propertyPrefix = null; - - public PropertyConsumerPropertyEditor() {} - - /** - * @param props the Properties object. - */ - public void setProperties(Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) {} - - /** - * PropertyConsumer method. - * - * @param props a Properties object to load the PropertyConsumer - * properties into. If props equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting - * the properties able to be set on this PropertyConsumer. The key - * for each property should be the raw property name (without a - * prefix) with a value that is a String that describes what the - * property key represents, along with any other information about - * the property that would be helpful (range, default value, - * etc.). It's not really defined what this method call should be - * returning. - * - * @param list a Properties object to load the PropertyConsumer - * properties into. If getList equals null, then a new - * Properties object should be created. - * @return Properties object containing PropertyConsumer property - * values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object - * created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - return list; - } - - /** - * Set the property key prefix that should be used by the - * PropertyConsumer. The prefix, along with a '.', should be - * prepended to the property keys known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to - * the property keys for Properties lookups. - * - * @return the property prefix. - */ - public String getPropertyPrefix() { - return propertyPrefix; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TextPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TextPropertyEditor.java deleted file mode 100644 index 408caf662..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TextPropertyEditor.java +++ /dev/null @@ -1,90 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/TextPropertyEditor.java,v $ -// $RCSfile: TextPropertyEditor.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.beans.PropertyEditorSupport; - -import javax.swing.JPanel; -import javax.swing.JTextField; - -/** - * A PropertyEditor that displays a TextField to edit a String. - */ -public class TextPropertyEditor extends PropertyEditorSupport implements - ActionListener, FocusListener { - - /** The GUI component of this editor. */ - JTextField textField = new JTextField(10); - - public boolean supportsCustomEditor() { - return true; - } - - /** Returns the editor GUI, ie a JTextField. */ - public Component getCustomEditor() { - JPanel jp = new JPanel(); - textField.addActionListener(this); - textField.addFocusListener(this); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - jp.setLayout(gridbag); - - c.weightx = 1f; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(textField, c); - jp.add(textField); - - return jp; - } - - public void actionPerformed(ActionEvent e) { - //System.out.println("value changed"); - firePropertyChange(); - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) { - firePropertyChange(); - } - - /** Sets String in JTextField. */ - public void setValue(Object string) { - if (!(string instanceof String)) - return; - textField.setText((String) string); - } - - /** Returns String from JTextfield. */ - public String getAsText() { - return textField.getText(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TrueFalsePropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TrueFalsePropertyEditor.java deleted file mode 100644 index ce11bf7cd..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/TrueFalsePropertyEditor.java +++ /dev/null @@ -1,156 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/TrueFalsePropertyEditor.java,v $ -// $RCSfile: TrueFalsePropertyEditor.java,v $ -// $Revision: 1.2 $ -// $Date: 2006-10-25 12:21:52 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.beans.PropertyEditorSupport; - -import javax.swing.ButtonGroup; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that displays an either/or option. The widget - * returns true or false as a string when queried, or the button's - * action commands if set differently in subclasses. If you extend - * this class and override the constructor, you can change the two - * choices presented, like "enabled/disabled, on/off", etc. The - * responses will be true and false, unless the action commands for - * the trueButton and falseButton are set to something else and - * useAltCommandStrings is set to true. - */ -public class TrueFalsePropertyEditor extends PropertyEditorSupport implements - ActionListener, FocusListener { - - protected ButtonGroup buttonGroup = new ButtonGroup(); - protected boolean option = true; - protected JRadioButton trueButton; - protected JRadioButton falseButton; - protected boolean useAltCommandStrings = false; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - public final static String TrueString = "true"; - public final static String FalseString = "false"; - - public TrueFalsePropertyEditor() { - trueButton = new JRadioButton(i18n.get(TrueFalsePropertyEditor.class, "True", "True")); - falseButton = new JRadioButton(i18n.get(TrueFalsePropertyEditor.class, "False", "False")); - } - - @Override - public boolean supportsCustomEditor() { - return true; - } - - public void setUseAltCommandStrings(boolean value) { - useAltCommandStrings = value; - } - - public boolean getUseAltCommandStrings() { - return useAltCommandStrings; - } - - /** Returns the editor GUI, ie a JTextField. */ - @Override - public Component getCustomEditor() { - JPanel panel = new JPanel(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.anchor = GridBagConstraints.WEST; - panel.setLayout(gridbag); - - if (!getUseAltCommandStrings()) { - trueButton.setActionCommand(TrueString); - falseButton.setActionCommand(FalseString); - } - trueButton.addActionListener(this); - falseButton.addActionListener(this); - - buttonGroup.add(trueButton); - buttonGroup.add(falseButton); - - setSelected(option); - - gridbag.setConstraints(trueButton, c); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1; - gridbag.setConstraints(falseButton, c); - panel.add(trueButton); - panel.add(falseButton); - - return panel; - } - - public void actionPerformed(ActionEvent e) { - String ac = e.getActionCommand(); - setSelected(ac.equalsIgnoreCase(trueButton.getActionCommand())); - - //System.out.println("value changed"); - firePropertyChange(); - } - - public void setSelected(boolean set) { - option = set; - trueButton.setSelected(option); - falseButton.setSelected(!option); - } - - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) { - firePropertyChange(); - } - - /** Sets String in JTextField. */ - @Override - public void setValue(Object string) { - if (!(string instanceof String)) { - return; - } - - setSelected(((String) string).equalsIgnoreCase(trueButton.getActionCommand())); - } - - /** Returns String from ButtonGroup. */ - @Override - public String getAsText() { - if (option) { - return trueButton.getActionCommand(); - } - return falseButton.getActionCommand(); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/YesNoPropertyEditor.java b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/YesNoPropertyEditor.java deleted file mode 100644 index c41ed2c23..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/YesNoPropertyEditor.java +++ /dev/null @@ -1,45 +0,0 @@ -// Bart 20060831 -> i18n - -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /home/cvs/nodus/src/com/bbn/openmap/util/propertyEditor/YesNoPropertyEditor.java,v $ -// $RCSfile: YesNoPropertyEditor.java,v $ -// $Revision: 1.1 $ -// $Date: 2006-08-31 15:56:07 $ -// $Author: jourquin $ -// -// ********************************************************************** - -package com.bbn.openmap.util.propertyEditor; - -import javax.swing.JRadioButton; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.util.I18n; - -/** - * A PropertyEditor that displays a Yes/No option. The widget returns - * true or false as a string when queried. - */ -public class YesNoPropertyEditor extends TrueFalsePropertyEditor { - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - public YesNoPropertyEditor() { - trueButton = new JRadioButton(i18n.get(YesNoPropertyEditor.class, "Yes", "Yes")); - falseButton = new JRadioButton(i18n.get(YesNoPropertyEditor.class, "No", "No")); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/package.html b/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/package.html deleted file mode 100644 index 3e68d4a84..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/propertyEditor/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide PropertyEditors for different property types of OpenMap components. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/MutableDistance.java b/src/core/src/main/java/com/bbn/openmap/util/quadtree/MutableDistance.java deleted file mode 100644 index e362ee5d6..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/MutableDistance.java +++ /dev/null @@ -1,34 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/MutableDistance.java,v $ -// $RCSfile: MutableDistance.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.quadtree; - -/** - * A *really* simple class used as a changable double. - */ -public class MutableDistance { - public double value = 0; - - public MutableDistance(double distance) { - value = distance; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTree.java b/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTree.java deleted file mode 100644 index 281219bf7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTree.java +++ /dev/null @@ -1,153 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/QuadTree.java,v $ -// $RCSfile: QuadTree.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:31 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.quadtree; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; - -import com.bbn.openmap.util.DataOrganizer; -import com.bbn.openmap.util.MoreMath; - -/** - * The QuadTree lets you organize objects in a grid, that redefines itself and - * refines the gridding over locations where more objects are gathered. - */ -public class QuadTree implements DataOrganizer, Serializable { - - static final long serialVersionUID = -7707825592455579873L; - - protected QuadTreeNode top; - - public QuadTree() { - this(90.0, -180.0, -90.0, 180.0, 20, QuadTreeNode.NO_MIN_SIZE); - } - - public QuadTree(double north, double west, double south, double east, int maxItems) { - this(north, west, south, east, maxItems, QuadTreeNode.NO_MIN_SIZE); - } - - public QuadTree(int up, int left, int down, int right, int maxItems) { - this(up, left, down, right, maxItems, QuadTreeNode.DEFAULT_MIN_SIZE); - } - - public QuadTree(double north, double west, double south, double east, int maxItems, - double minSize) { - top = new QuadTreeNode(north, west, south, east, maxItems, minSize); - } - - /** - * Add a object into the tree at a location. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param obj the object to insert into the tree - * @return true if the insertion worked. - */ - public boolean put(double lat, double lon, T obj) { - return top.put(lat, lon, obj); - } - - /** - * Remove a object out of the tree at a location. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param obj the object to remove - * @return the object removed, null if the object not found. - */ - public T remove(double lat, double lon, T obj) { - return top.remove(lat, lon, obj); - } - - /** Clear the tree. */ - public void clear() { - top.clear(); - } - - /** - * Get an object closest to a lat/lon. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @return the object that was found. - */ - public T get(double lat, double lon) { - return top.get(lat, lon); - } - - /** - * Get an object closest to a lat/lon, within a maximum distance. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param withinDistance the maximum distance to get a hit, in decimal - * degrees. - * @return the object that was found, null if nothing is within the maximum - * distance. - */ - public T get(double lat, double lon, double withinDistance) { - return top.get(lat, lon, withinDistance); - } - - /** - * Get all the objects within a bounding box. - * - * @param north top location in QuadTree Grid (latitude, y) - * @param west left location in QuadTree Grid (longitude, x) - * @param south lower location in QuadTree Grid (latitude, y) - * @param east right location in QuadTree Grid (longitude, x) - * @return Vector of objects. - */ - public Collection get(double north, double west, double south, double east) { - return get(north, west, south, east, null); - } - - /** - * Get all the objects within a bounding box, and return the objects in the - * provided Collection. - * - * @param north top location in QuadTree Grid (latitude, y) - * @param west left location in QuadTree Grid (longitude, x) - * @param south lower location in QuadTree Grid (latitude, y) - * @param east right location in QuadTree Grid (longitude, x) - * @param collection a Collection to add objects to. - * @return Collection of objects. - */ - public Collection get(double north, double west, double south, double east, - Collection collection) { - - if (collection == null) { - collection = new ArrayList(); - } - // crossing the dateline, right?? Or at least containing the - // entire earth. Might be trouble for VERY LARGE scales. The - // last check is for micro-errors that happen to lon points - // where there might be a smudge overlap for very small - // scales. - if (west > east || MoreMath.approximately_equal(west, east, .001)) { - return top.get(north, west, south, 180, top.get(north, -180, south, east, collection)); - } else - return top.get(north, west, south, east, collection); - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeLeaf.java b/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeLeaf.java deleted file mode 100644 index 9752b3a5a..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeLeaf.java +++ /dev/null @@ -1,42 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/QuadTreeLeaf.java,v -// $ -// $RCSfile: QuadTreeLeaf.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.quadtree; - -import java.io.Serializable; - -public class QuadTreeLeaf implements Serializable { - - static final long serialVersionUID = 7885745536157252519L; - - public double latitude; - public double longitude; - public T object; - - public QuadTreeLeaf(double lat, double lon, T obj) { - latitude = lat; - longitude = lon; - object = obj; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeNode.java b/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeNode.java deleted file mode 100644 index 0cdbd6b23..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeNode.java +++ /dev/null @@ -1,370 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/QuadTreeNode.java,v $ -// $RCSfile: QuadTreeNode.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.quadtree; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Vector; - -import com.bbn.openmap.util.MoreMath; - -/** - * The QuadTreeNode is the part of the QuadTree that either holds children - * nodes, or objects as leaves. Currently, the nodes that have children do not - * hold items that span across children boundaries, since this was designed to - * handle point data. - */ - -public class QuadTreeNode implements Serializable { - - static final long serialVersionUID = -6111633198469889444L; - - public final static float NO_MIN_SIZE = -1; - public final static float DEFAULT_MIN_SIZE = 5; - - protected Collection> items; - protected Collection> children; - protected int maxItems; - protected double minSize; - public QuadTreeRect bounds; - /** - * Added to avoid problems when a node is completely filled with a single - * point value. - */ - protected boolean allTheSamePoint; - protected double firstLat; - protected double firstLon; - - /** - * Constructor to use if you are going to store the objects in lat/lon - * space, and there is really no smallest node size. - * - * @param north northern border of node coverage. - * @param west western border of node coverage. - * @param south southern border of node coverage. - * @param east eastern border of node coverage. - * @param maximumItems number of items to hold in a node before splitting - * itself into four children and redispensing the items into them. - */ - public QuadTreeNode(double north, double west, double south, double east, int maximumItems) { - this(north, west, south, east, maximumItems, NO_MIN_SIZE); - } - - /** - * Constructor to use if you are going to store the objects in x/y space, - * and there is a smallest node size because you don't want the nodes to be - * smaller than a group of pixels. - * - * @param north northern border of node coverage. - * @param west western border of node coverage. - * @param south southern border of node coverage. - * @param east eastern border of node coverage. - * @param maximumItems number of items to hold in a node before splitting - * itself into four children and redispensing the items into them. - * @param minimumSize the minimum difference between the boundaries of the - * node. - */ - public QuadTreeNode(double north, double west, double south, double east, int maximumItems, - double minimumSize) { - bounds = new QuadTreeRect(north, west, south, east); - maxItems = maximumItems; - minSize = minimumSize; - items = new ArrayList>(); - } - - /** Return true if the node has children. */ - public boolean hasChildren() { - return (children != null); - } - - /** - * This method splits the node into four children, and disperses the items - * into the children. The split only happens if the boundary size of the - * node is larger than the minimum size (if we care). The items in this node - * are cleared after they are put into the children. - */ - protected void split() { - // Make sure we're bigger than the minimum, if we care, - if (minSize != NO_MIN_SIZE) { - if (MoreMath.approximately_equal(bounds.north, bounds.south, minSize) - && MoreMath.approximately_equal(bounds.east, bounds.west, minSize)) - return; - } - - double nsHalf = (bounds.north - (bounds.north - bounds.south) / 2.0); - double ewHalf = (bounds.east - (bounds.east - bounds.west) / 2.0); - children = new ArrayList>(4); - - children.add(new QuadTreeNode(bounds.north, bounds.west, nsHalf, ewHalf, maxItems)); - children.add(new QuadTreeNode(bounds.north, ewHalf, nsHalf, bounds.east, maxItems)); - children.add(new QuadTreeNode(nsHalf, ewHalf, bounds.south, bounds.east, maxItems)); - children.add(new QuadTreeNode(nsHalf, bounds.west, bounds.south, ewHalf, maxItems)); - Collection temp = new ArrayList(items); - items.clear(); - - for (QuadTreeLeaf leaf : temp) { - put(leaf); - } - } - - /** - * Get the node that covers a certain lat/lon pair. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @return node if child covers the point, null if the point is out of - * range. - */ - protected QuadTreeNode getChild(double lat, double lon) { - if (bounds.pointWithinBounds(lat, lon)) { - if (children != null) { - for (QuadTreeNode child : children) { - if (child.bounds.pointWithinBounds(lat, lon)) - return child.getChild(lat, lon); - } - } else { - return this; // no children, lat, lon here... - } - } - return null; - } - - /** - * Add a object into the tree at a location. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param obj object to add to the tree. - * @return true if the put worked. - */ - public boolean put(double lat, double lon, T obj) { - return put(new QuadTreeLeaf(lat, lon, obj)); - } - - /** - * Add a QuadTreeLeaf into the tree at a location. - * - * @param leaf object-location composite - * @return true if the pution worked. - */ - public boolean put(QuadTreeLeaf leaf) { - if (children == null) { - this.items.add(leaf); - if (this.items.size() == 1) { - this.allTheSamePoint = true; - this.firstLat = leaf.latitude; - this.firstLon = leaf.longitude; - } else { - if (this.firstLat != leaf.latitude || this.firstLon != leaf.longitude) { - this.allTheSamePoint = false; - } - } - - if (this.items.size() > maxItems && !this.allTheSamePoint) { - split(); - } - return true; - } else { - QuadTreeNode node = getChild(leaf.latitude, leaf.longitude); - if (node != null) { - return node.put(leaf); - } - } - return false; - } - - /** - * Remove a object out of the tree at a location. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param obj the object to be removed. - * @return the object removed, null if the object not found. - */ - public T remove(double lat, double lon, T obj) { - return remove(new QuadTreeLeaf(lat, lon, obj)); - } - - /** - * Remove a QuadTreeLeaf out of the tree at a location. - * - * @param leaf object-location composite - * @return the object removed, null if the object not found. - */ - public T remove(QuadTreeLeaf leaf) { - if (children == null) { - // This must be the node that has it... - for (QuadTreeLeaf qtl : new ArrayList>(items)) { - if (leaf.object == qtl.object) { - items.remove(qtl); - return qtl.object; - } - } - } else { - QuadTreeNode node = getChild(leaf.latitude, leaf.longitude); - if (node != null) { - return node.remove(leaf); - } - } - return null; - } - - /** Clear the tree below this node. */ - public void clear() { - this.items.clear(); - if (children != null) { - for (QuadTreeNode child : children) { - child.clear(); - } - children = null; - } - } - - /** - * Get an object closest to a lat/lon. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @return the object that matches the best distance, null if no object was - * found. - */ - public T get(double lat, double lon) { - return get(lat, lon, Double.POSITIVE_INFINITY); - } - - /** - * Get an object closest to a lat/lon. If there are children at this node, - * then the children are searched. The children are checked first, to see if - * they are closer than the best distance already found. If a closer object - * is found, bestDistance will be updated with a new Double object that has - * the new distance. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param withinDistance maximum get distance. - * @return the object that matches the best distance, null if no closer - * object was found. - */ - public T get(double lat, double lon, double withinDistance) { - return get(lat, lon, new MutableDistance(withinDistance)); - } - - /** - * Get an object closest to a lat/lon. If there are children at this node, - * then the children are searched. The children are checked first, to see if - * they are closer than the best distance already found. If a closer object - * is found, bestDistance will be updated with a new Double object that has - * the new distance. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @param bestDistance the closest distance of the object found so far. - * @return the object that matches the best distance, null if no closer - * object was found. - */ - public T get(double lat, double lon, MutableDistance bestDistance) { - T closest = null; - // This must be the node that has it... - if (children == null) { - for (QuadTreeLeaf qtl : items) { - double dx = lon - qtl.longitude; - double dy = lat - qtl.latitude; - double distanceSqr = dx * dx + dy * dy; - - if (distanceSqr < bestDistance.value) { - bestDistance.value = distanceSqr; - closest = qtl.object; - } - } - return closest; - } else { - // Check the distance of the bounds of the children, - // versus the bestDistance. If there is a boundary that - // is closer, then it is possible that another node has an - // object that is closer. - for (QuadTreeNode child : children) { - double childDistance = child.bounds.borderDistanceSqr(lat, lon); - if (childDistance < bestDistance.value) { - T test = child.get(lat, lon, bestDistance); - if (test != null) - closest = test; - } - } - } - return closest; - } - - /** - * Get all the objects within a bounding box. - * - * @param north top location in QuadTree Grid (latitude, y) - * @param west left location in QuadTree Grid (longitude, x) - * @param south lower location in QuadTree Grid (latitude, y) - * @param east right location in QuadTree Grid (longitude, x) - * @return Collection of objects. - */ - public Collection get(double north, double west, double south, double east) { - return get(new QuadTreeRect(north, west, south, east), new ArrayList()); - } - - /** - * Get all the objects within a bounding box. - * - * @param north top location in QuadTree Grid (latitude, y) - * @param west left location in QuadTree Grid (longitude, x) - * @param south lower location in QuadTree Grid (latitude, y) - * @param east right location in QuadTree Grid (longitude, x) - * @param collection current Collection of objects. - * @return collection of objects. - */ - public Collection get(double north, double west, double south, double east, - Collection collection) { - return get(new QuadTreeRect(north, west, south, east), collection); - } - - /** - * Get all the objects within a bounding box. - * - * @param rect boundary of area to fill. - * @param collection current Collection of objects. - * @return updated Collection of objects. - */ - public Collection get(QuadTreeRect rect, Collection collection) { - if (children == null) { - for (QuadTreeLeaf qtl : this.items) { - if (rect.pointWithinBounds(qtl.latitude, qtl.longitude)) { - collection.add(qtl.object); - } - } - } else { - for (QuadTreeNode child : children) { - if (child.bounds.within(rect)) { - child.get(rect, collection); - } - } - } - return collection; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeRect.java b/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeRect.java deleted file mode 100644 index a29092174..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/QuadTreeRect.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/QuadTreeRect.java,v -// $ -// $RCSfile: QuadTreeRect.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.quadtree; - -import java.io.Serializable; - -public class QuadTreeRect implements Serializable { - - static final long serialVersionUID = -5585535433679092922L; - - public double north; - public double south; - public double west; - public double east; - - public QuadTreeRect(double n, double w, double s, double e) { - north = n; - west = w; - south = s; - east = e; - } - - public boolean within(QuadTreeRect rect) { - return within(rect.north, rect.west, rect.south, rect.east); - } - - public boolean within(double n, double w, double s, double e) { - - // We check for equality for the northern and western border - // because the rectangles, out of convention for this package, - // will contain points that exactly match those borders. - - // Thanks to Paul Tomblin for pointing out that the old code - // wasn't entirely correct, and supplied the better algorithm. - - if (s >= north) { - return false; - } - if (n < south) { - return false; - } - if (w > east) { - return false; - } - if (e <= west) { - return false; - } - return true; - } - - public boolean pointWithinBounds(double lat, double lon) { - return (lon >= west && lon < east && lat <= north && lat > south); - } - - /** - * A utility method to figure out the closest distance of a border to a - * point. If the point is inside the rectangle, return 0. - * - * @param lat up-down location in QuadTree Grid (latitude, y) - * @param lon left-right location in QuadTree Grid (longitude, x) - * @return closest distance to the point. - */ - public double borderDistance(double lat, double lon) { - - double nsdistance; - double ewdistance; - - if (south <= lat && lat <= north) { - nsdistance = 0; - } else { - nsdistance = Math.min((Math.abs(lat - north)), (Math.abs(lat - south))); - } - - if (west <= lon && lon <= east) { - ewdistance = 0; - } else { - ewdistance = Math.min((Math.abs(lon - east)), (Math.abs(lon - west))); - } - - return Math.sqrt(Math.pow(nsdistance, 2.0) + Math.pow(ewdistance, 2.0)); - } - - /** - * Notice the change from borderDistance() to borderDistanceSqr() since - * distance squared must be used throughout, which is now given by: - * - * @param lat - * @param lon - * @return border distance squared - */ - public double borderDistanceSqr(double lat, double lon) { - double nsdistance; - double ewdistance; - - if (south <= lat && lat <= north) { - nsdistance = 0.0; - } else { - nsdistance = Math.min((Math.abs(lat - north)), (Math.abs(lat - south))); - } - - if (west <= lon && lon <= east) { - ewdistance = 0.0; - } else { - ewdistance = Math.min((Math.abs(lon - east)), (Math.abs(lon - west))); - } - - if (nsdistance == 0.0 && ewdistance == 0.0) // save computing 0 distance - return 0.0; - - double dx = ewdistance * ewdistance; - double dy = nsdistance * nsdistance; - return dx * dx + dy * dy; - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/quadtree/package.html b/src/core/src/main/java/com/bbn/openmap/util/quadtree/package.html deleted file mode 100644 index 4c1a1e32e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/quadtree/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provide a quad-tree for latitude/longitude based data. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/State.java b/src/core/src/main/java/com/bbn/openmap/util/stateMachine/State.java deleted file mode 100644 index 349b05ef8..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/State.java +++ /dev/null @@ -1,179 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/stateMachine/State.java,v $ -// $RCSfile: State.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/10 22:19:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.stateMachine; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.AdjustmentEvent; -import java.awt.event.AdjustmentListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.ContainerEvent; -import java.awt.event.ContainerListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.TextEvent; -import java.awt.event.TextListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.util.I18n; - -/** - * The state is intended to be a abstract juncture in a pattern of - * events. The idea is that for a given state, an event will call a - * unique response. This class lets you define this juncture, and can - * be used as a Java adapter to define only the listener responses you - * care about. The state, as defined in your implementation, can reset - * the StateMachine to it's new state after it responds to an event. - *

- * - * Since this state machine can be used in OpenMap, the - * Mouse/MouseMotion Listeners are MapMouseListeners. This is to let - * OpenMap know not to send the result on to other layers that like to - * hear about events. This State class has a setting on how you want - * the unused MapMouseListener functions to respond to events. The - * default is false, and this means that other layers will have a - * chance to respond to events. If you want other layer's event - * reception to pause a little, set the mapMouseListenerResponse to - * true. - */ -public abstract class State implements ActionListener, AdjustmentListener, - ComponentListener, ContainerListener, FocusListener, ItemListener, - KeyListener, MapMouseListener, TextListener, WindowListener { - - /** The default response for the MapMouseListener methods. */ - boolean mapMouseListenerResponse = false; - - /** To read local settings */ - protected I18n i18n = Environment.getI18n(); - - /** - * Set the MapMouseListener method default response value. If - * value is true, other layers on the map will not receive mouse - * events. - */ - public void setMapMouseListenerResponse(boolean value) { - mapMouseListenerResponse = value; - } - - /** - * Get the value of the default response to MapMouseListener - * methods. - */ - public boolean getMapMouseListenerResponse() { - return mapMouseListenerResponse; - } - - // / ActionListener interface - public void actionPerformed(ActionEvent e) {} - - // / AdjustmentListener interface - public void adjustmentValueChanged(AdjustmentEvent e) {} - - // / ComponentListener interface - public void componentResized(ComponentEvent e) {} - - public void componentMoved(ComponentEvent e) {} - - public void componentShown(ComponentEvent e) {} - - public void componentHidden(ComponentEvent e) {} - - // / ContainerListener interface - public void componentAdded(ContainerEvent e) {} - - public void componentRemoved(ContainerEvent e) {} - - // / FocusListener interface - public void focusGained(FocusEvent e) {} - - public void focusLost(FocusEvent e) {} - - // / ItemListener interface - public void itemStateChanged(ItemEvent e) {} - - // / KeyListener interface - public void keyTyped(KeyEvent e) {} - - public void keyPressed(KeyEvent e) {} - - public void keyReleased(KeyEvent e) {} - - // / MapMouseListener - public String[] getMouseModeServiceList() { - return null; - } - - public boolean mousePressed(MouseEvent e) { - return mapMouseListenerResponse; - } - - public boolean mouseReleased(MouseEvent e) { - return mapMouseListenerResponse; - } - - public boolean mouseClicked(MouseEvent e) { - return mapMouseListenerResponse; - } - - public void mouseEntered(MouseEvent e) {} - - public void mouseExited(MouseEvent e) {} - - public boolean mouseDragged(MouseEvent e) { - return mapMouseListenerResponse; - } - - public boolean mouseMoved(MouseEvent e) { - return mapMouseListenerResponse; - } - - public void mouseMoved() {} - - // / TextListener interface - public void textValueChanged(TextEvent e) {} - - // / WindowListener interface - public void windowOpened(WindowEvent e) {} - - public void windowClosing(WindowEvent e) {} - - public void windowClosed(WindowEvent e) {} - - public void windowIconified(WindowEvent e) {} - - public void windowDeiconified(WindowEvent e) {} - - public void windowActivated(WindowEvent e) {} - - public void windowDeactivated(WindowEvent e) {} - -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/StateMachine.java b/src/core/src/main/java/com/bbn/openmap/util/stateMachine/StateMachine.java deleted file mode 100644 index 5cf0571f7..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/StateMachine.java +++ /dev/null @@ -1,200 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/util/stateMachine/StateMachine.java,v $ -// $RCSfile: StateMachine.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/10 22:19:45 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.stateMachine; - -import java.util.Enumeration; -import java.util.Vector; - -/** - * The StateMachine lets you organize event handling, if the order of - * the events are important to you. You can use the setState commands - * with the state you want, if you are holding on a copy of it. - * Otherwise, the state machine assumes you know the index of the - * state you want. - */ -public class StateMachine { - /** The states to track. */ - protected Vector states = new Vector(); - /** The current state that will receive the next event. */ - protected State currentState; - /** The state to go to whan all is bad. */ - protected State resetState; - - public StateMachine() {} - - /** - * Define the state machine using the array of states. Order is - * maintained. - * - * @param s array of states. - */ - public StateMachine(State[] s) { - for (int i = 0; i < s.length; i++) - states.addElement(s[i]); - } - - /** Sets the current state to the reset state. */ - public void reset() { - currentState = resetState; - } - - /** - * Set the states to the new array. - * - * @param s array of states. - */ - public void setStates(State[] s) { - states.clear(); - addStates(s); - } - - /** - * Set the states to the vector of States. - * - * @param s - */ - public void setStates(Vector s) { - states = s; - } - - /** - * Get the Vector of States. - * - * @return Vector - */ - public Vector getStates() { - return states; - } - - /** - * Append States to the state Vector. - * - * @param s an Array of States. - */ - public void addStates(State[] s) { - for (int i = 0; i < s.length; i++) - states.addElement(s[i]); - } - - /** - * Set the current state to the given state. If the state is not - * in the state machine, then the state is added to the end to the - * state vector. - * - * @param state the state to set to the current one. - */ - public void setState(State state) { - if (!states.contains(state)) - states.addElement(state); - currentState = state; - } - - /** - * Set the current state to the state residing in the vector at - * the given index. If the index is larger than the number of - * states in the machine, the statemachine is reset. - * - * @param stateIndex the index of the current state. - */ - public void setState(int stateIndex) { - try { - currentState = (State) states.elementAt(stateIndex); - } catch (ArrayIndexOutOfBoundsException e) { - reset(); - System.err.println("StateMachine: out of bounds exception caught!"); - } - } - - /** - * Set the state at an index to new State Object. If the index - * isn't currently being used, the StateMachine is reset. - * - * @param stateIndex - * @param state - */ - public void setStateAt(int stateIndex, State state) { - try { - states.setElementAt(state, stateIndex); - } catch (ArrayIndexOutOfBoundsException e) { - System.err.println("StateMachine: out of bounds exception caught when trying to replace State that didn't exist."); - } - } - - /** Return the current State. */ - public State getState() { - return currentState; - } - - /** - * Return the state at the given index. If the index is larger - * that the number of states, null is returned. - */ - public State getState(int stateIndex) { - try { - return (State) states.elementAt(stateIndex); - } catch (ArrayIndexOutOfBoundsException e) { - System.err.println("StateMachine: out of bounds exception caught!"); - return null; - } - } - - /** - * Set the state to be gone to if the state machine is reset. If - * the state does not exist in the state machine already, it will - * be added to the end of the state vector. - */ - public void setResetState(State state) { - if (!states.contains(state)) - states.addElement(state); - resetState = state; - } - - /** - * Set the reset state to be used by the state machine. If a bad - * integer value is given, the first state in the state vector is - * made the reset state. - */ - public void setResetState(int stateIndex) { - try { - resetState = (State) states.elementAt(stateIndex); - } catch (ArrayIndexOutOfBoundsException e) { - System.err.println("StateMachine: out of bounds exception caught!"); - if (states.size() > 1) - resetState = (State) states.elementAt(0); - } - } - - /** Return the reset state. */ - public State getResetState() { - return resetState; - } - - /** Set the MapMouseListenerResponse for all the states. */ - public void setMapMouseListenerResponses(boolean value) { - Enumeration sItems = states.elements(); - while (sItems.hasMoreElements()) { - State state = (State) sItems.nextElement(); - state.setMapMouseListenerResponse(value); - } - } -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/package.html b/src/core/src/main/java/com/bbn/openmap/util/stateMachine/package.html deleted file mode 100644 index d180ba250..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/stateMachine/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - -Provides a basic finite-state-machine implementation. - - diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/ChangeCase.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/ChangeCase.java deleted file mode 100644 index 1cf3a3675..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/ChangeCase.java +++ /dev/null @@ -1,152 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/ChangeCase.java,v $ -// $RCSfile: ChangeCase.java,v $ -// $Revision: 1.5 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; - -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.Debug; - -/** - * ChangeCase is a simple class that traverses a file system tree and converts - * the contents to upper ot lower case letters, depending on the options - * provided. - * - *

- * 
- * 
- *    Usage: java com.bbn.openmap.util.wanderer.ChangeCase [-u|-l] (dir path 1)(dir path 2) ...
- * 
- * 
- * 
- */ -public class ChangeCase - extends Wanderer - implements WandererCallback { - - boolean toUpper = false; - boolean verbose = false; - - public ChangeCase(boolean toUpperCase) { - super(); - toUpper = toUpperCase; - setExhaustiveSearch(true); - setTopToBottom(false); - setCallback(this); - } - - public void setVerbose(boolean val) { - verbose = val; - } - - public boolean getVerbose() { - return verbose; - } - - public boolean handleDirectory(File directory) { - return handleFile(directory); - } - - public boolean handleFile(File file) { - File newFile; - String parent = file.getParent(); - - if (parent != null) { - if (toUpper) { - newFile = new File(parent, file.getName().toUpperCase()); - } else { - newFile = new File(parent, file.getName().toLowerCase()); - } - } else { - if (toUpper) { - newFile = new File(file.getName().toUpperCase()); - } else { - newFile = new File(file.getName().toLowerCase()); - } - } - - if (file.renameTo(newFile)) { - if (verbose) { - System.out.println("Renamed " + (file.getParent() == null ? "." : file.getParent()) + File.separator + file.getName() - + " to " + (newFile.getParent() == null ? "." : newFile.getParent()) + File.separator + newFile.getName()); - } - } else { - System.out.println("Renaming " + (file.getParent() == null ? "." : file.getParent()) + File.separator + file.getName() - + " to " + (newFile.getParent() == null ? "." : newFile.getParent()) + File.separator + newFile.getName() - + " FAILED"); - } - return true; - } - - /** - * Given a set of files or directories, parade through them to change their - * case. - * - * @param argv paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - Debug.init(); - boolean toUpper = true; - - ArgParser ap = new ArgParser("ChangeCase"); - ap.add("upper", "Change file and directory names to UPPER CASE (default). ...", ArgParser.TO_END); - ap.add("lower", "Change file and directory names to lower case. ...", ArgParser.TO_END); - ap.add("verbose", "Announce all changes, failures will still be reported."); - - if (argv.length == 0) { - ap.bail("", true); - } - - ap.parse(argv); - - String[] dirs; - dirs = ap.getArgValues("lower"); - if (dirs != null) { - Debug.output("Converting to lower case names..."); - toUpper = false; - } else { - dirs = ap.getArgValues("upper"); - // No arguments given, going to default. - if (dirs == null) { - dirs = argv; - } - Debug.output("Converting to UPPER CASE names..."); - } - - boolean verbose = false; - String[] verboseTest = ap.getArgValues("verbose"); - if (verboseTest != null) { - verbose = true; - } - - ChangeCase cc = new ChangeCase(toUpper); - cc.setVerbose(verbose); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - cc.handleEntry(new File(dirs[i])); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/DataPathWanderer.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/DataPathWanderer.java deleted file mode 100644 index a4802f3d1..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/DataPathWanderer.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.bbn.openmap.util.wanderer; - -import java.util.ArrayList; -import java.util.List; - -/** - * A DataPathWanderer provides a list of valid data paths found from a parent - * directory. This class is intended to be provided by a layer to report which - * data files or directories can be used for that layer, given some parent - * directory or file. - * - * @author dfdietrick - */ -public abstract class DataPathWanderer extends Wanderer implements WandererCallback { - - protected List dataPaths; - - /** - * Which component class, like a specific layer type, will be using the data - * path. - * - * @return Class of using component. - */ - public abstract Class getDataUserClass(); - - /** - * @return pretty name of the using component.x - */ - public abstract String getPrettyName(); - - public DataPathWanderer() { - - } - - /** - * Returns a list of file/directory paths. - * - * @return a list of file/directory paths. If null, no required data paths - * were found and the layer is indicating that it needs paths. If a - * list is returned and its empty, then the layer doesn't require a - * data file. - */ - public List getDataPaths() { - return dataPaths; - } - - /** - * Adds a data path to the path repository. Creates the repository list if - * it doesn't yet exist. A call with a null path will get the repository - * list created. - * - * @param path - */ - protected void addDataPath(String path) { - if (dataPaths == null) { - dataPaths = new ArrayList(); - } - - if (path != null) { - dataPaths.add(path); - } - } - - /** - * True if layer being described can handle more than one data path, i.e. - * all the data paths found can be added to a single layer. - * - * @return false by default - */ - public boolean isMultiPathLayer() { - return false; - } - -} diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/OneWaySync.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/OneWaySync.java deleted file mode 100644 index b1058394e..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/OneWaySync.java +++ /dev/null @@ -1,498 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/OneWaySync.java,v $ -// $RCSfile: OneWaySync.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/09 18:41:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.ArgParser; - -/** - * The OneWaySync is a class that copies files from one directory to another, - * skipping specified extensions or only copying files and directories with - * specified extensions. It's used by the OpenMap team to keep the internal CVS - * tree in sync with the external one. The main() function has the avoid/limit - * suffixes hard-coded, you can extend or change the settings in a different - * class. - */ -public class OneWaySync extends Wanderer implements WandererCallback { - - /** The source directory. */ - protected File src; - /** The target directory. */ - protected File tgt; - /** The suffixes to skip over for directories. */ - public String[] dirSuffixAvoids = null; - /** The suffixes to skip over for files. */ - public String[] fileSuffixAvoids = null; - /** The suffixes to limit copying to for directories. */ - public String[] dirSuffixLimits = null; - /** The suffixes to limit copying to for files. */ - public String[] fileSuffixLimits = null; - /** The list of stuff skipped over. */ - protected LinkedList notCopiedList = new LinkedList(); - /** Flag for printing out activities. */ - protected boolean verbose = false; - /** Flag for not doing the changes, just saying what would happen. */ - protected boolean fakeit = false; - /** Flag to not have files that exist overwritten. */ - protected boolean overwrite = true; - - public OneWaySync(String srcDirName, String targetDirName) { - super(); - setCallback(this); - - src = new File(srcDirName); - tgt = new File(targetDirName); - } - - /** - * Check to see if a source directory name should be skipped, based on the - * avoid and limit list. - */ - protected boolean checkToSkipDirectory(String name) { - if (dirSuffixAvoids != null) { - for (int i = 0; i < dirSuffixAvoids.length; i++) { - if (name.endsWith(dirSuffixAvoids[i])) { - // Was on avoid list, skip it. - return true; - } - } - } - - if (dirSuffixLimits != null) { - for (int i = 0; i < dirSuffixLimits.length; i++) { - if (name.endsWith(dirSuffixLimits[i])) { - return false; - } - } - // Wasn't on limit list, skip it. - return true; - } - - return false; - } - - /** - * Check to see if a source file name should be skipped, based on the avoid - * and limit list. - */ - protected boolean checkToSkipFile(String name) { - if (fileSuffixAvoids != null) { - for (int i = 0; i < fileSuffixAvoids.length; i++) { - if (name.endsWith(fileSuffixAvoids[i])) { - // Was on avoid list, skip it. - return true; - } - } - } - - if (fileSuffixLimits != null) { - for (int i = 0; i < fileSuffixLimits.length; i++) { - if (name.endsWith(fileSuffixLimits[i])) { - return false; - } - } - // Wasn't on limit list, skip it. - return true; - } - - return false; - } - - /** - * Wanderer method handing directories. - */ - public boolean handleDirectory(File directory, String[] contentNames) { - String newDirName = getRelativePathFromSource(directory); - - if (newDirName == null) { - if (directory != src) { - notCopiedList.add(directory); - } - super.handleDirectory(directory, contentNames); - return true; - } - - if (!checkToSkipDirectory(newDirName)) { - File newDir = getTargetFile(newDirName); - if (!newDir.exists()) { - if (verbose) { - getLogger().info("Creating " + newDir); - } - if (!fakeit && overwrite) - newDir.mkdir(); - } - super.handleDirectory(directory, contentNames); - } else { - notCopiedList.add(directory); - } - - return true; - } - - /** - * WandererCallback method handing directories, not used. - */ - public boolean handleDirectory(File file) { - return true; - } - - /** - * WandererCallback method handing files, check and copy those that fit the - * avoid and limit parameters. - */ - public boolean handleFile(File file) { - String newFileName = getRelativePathFromSource(file); - - if (!checkToSkipFile(newFileName)) { - File newFile = getTargetFile(newFileName); - if (verbose) { - getLogger().info("Copying " + file + " to " + newFile); - } - if (!fakeit && overwrite) - copy(file, newFile); - } else { - notCopiedList.add(file); - } - return true; - } - - /** - * Copy files. - */ - public void copy(File fromFile, File toFile) { - try { - FileInputStream fis = new FileInputStream(fromFile); - FileOutputStream fos = new FileOutputStream(toFile); - - int num = 0; - byte[] stuff = new byte[4096]; - while ((num = fis.read(stuff)) > 0) { - fos.write(stuff, 0, num); - } - fis.close(); - fos.close(); - - } catch (IOException ioe) { - getLogger().warning("Exception reading from " + fromFile + " and writing to " + toFile); - } - } - - /** - * Strip the source directory part of the path from the file, return what - * remains. - */ - public String getRelativePathFromSource(File file) { - return subtractPathFromDirectory(src, file); - } - - /** - * Strip the target directory part of the path from the file, return what - * remains. - */ - public String getRelativePathFromTarget(File file) { - return subtractPathFromDirectory(tgt, file); - } - - /** - * Tack the file path onto the source directory. - */ - public File getSourceFile(String relativePath) { - return new File(src, relativePath); - } - - /** - * Tack the file path onto the target directory. - */ - public File getTargetFile(String relativePath) { - return new File(tgt, relativePath); - } - - /** - * Print out the files/directories not copied. - */ - public void writeUnsynched() { - for (Iterator it = notCopiedList.iterator(); it.hasNext();) { - getLogger().info(" " + it.next()); - } - } - - /** - * Create a BackCheck object that looks to see what files are in the target - * but not in the source. - */ - public void checkTargetSolos() { - new BackCheck(tgt.getPath(), src.getPath()); - } - - /** - * Take the source directory out of the path to the directory. - */ - protected String subtractPathFromDirectory(File dir, File file) { - String name = file.getPath(); - String dirName = dir.getPath(); - - if (name.equals(dirName)) { - if (verbose) { - getLogger().info("OneWaySync avoiding subtraction operation on top-level directory"); - } - return null; - } - - int index = name.indexOf(dirName); - if (index != -1) { - try { - String relative = name.substring(index + dirName.length() + 1); - if (verbose) { - getLogger().info("From " + file + ", returning " + relative); - } - return relative; - } catch (StringIndexOutOfBoundsException sioobe) { - getLogger().warning("Problem clipping first " + (dirName.length() + 1) + " characters off " + file); - return null; - } - } else { - getLogger().warning("File " + file + " is not in directory " + dir); - return null; - } - } - - /** - * Start copying files from the source directory to the target directory. - */ - public void start() { - String errorMessage = null; - if (src == null) { - errorMessage = "OneWaySync: Source directory unspecified"; - } else if (!src.exists()) { - errorMessage = "OneWaySync: Source directory (" + src + ") doesn't exist!"; - } - - if (tgt != null) { - if (!tgt.exists()) { - if (verbose) { - getLogger().info("OneWaySync: target directory (" + tgt + ") doesn't exist, creating..."); - } - - try { - if (!fakeit && !tgt.mkdir()) { - errorMessage = "OneWaySync: target directory (" + tgt + ") can't be created."; - } - } catch (SecurityException se) { - errorMessage = "OneWaySync: creating target directory (" + tgt - + ") isn't allowed, Security Exception: " + se.getMessage(); - se.printStackTrace(); - } - } - } else { - errorMessage = "OneWaySync: target directory unspecified"; - } - - if (errorMessage != null) { - getLogger().warning(errorMessage); - System.exit(0); - } - - handleEntry(src); - } - - public void setVerbose(boolean val) { - verbose = val; - } - - public boolean getVerbose() { - return verbose; - } - - public void setFakeit(boolean val) { - fakeit = val; - } - - public boolean getFakeit() { - return fakeit; - } - - public void setDirSuffixAvoids(String[] avoids) { - dirSuffixAvoids = avoids; - } - - public void setFileSuffixAvoids(String[] avoids) { - fileSuffixAvoids = avoids; - } - - public void setDirSuffixLimits(String[] limits) { - dirSuffixLimits = limits; - } - - public void setFileSuffixLimits(String[] limits) { - fileSuffixLimits = limits; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(OneWaySync.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - /** - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("OneWaySync"); - ap.add("source", "The source directory to copy files and directories from.", 1); - ap.add("target", "The target directory to receive the updated files and directories.", 1); - ap.add("verbose", "Announce all changes, failures will still be reported."); - ap.add("fakeit", "Just print what would happen, don't really do anything."); - ap.add("report", "Print out what didn't get copied, and what files exist only on the target side."); - - if (argv.length < 4) { - ap.bail("", true); - } - - ap.parse(argv); - - boolean verbose = false; - String[] verb = ap.getArgValues("verbose"); - if (verb != null) { - verbose = true; - } - - boolean fakeit = false; - verb = ap.getArgValues("fakeit"); - if (verb != null) { - verbose = true; - fakeit = true; - } - - boolean report = false; - verb = ap.getArgValues("report"); - if (verb != null) { - report = true; - } - - String[] sourceDir; - sourceDir = ap.getArgValues("source"); - if (sourceDir != null && sourceDir.length >= 1) { - if (verbose) { - getLogger().info("Source directory is " + sourceDir[0]); - } - } else { - ap.bail("OneWaySync needs path to source directory", false); - } - - String[] targetDir; - targetDir = ap.getArgValues("target"); - if (targetDir != null && targetDir.length >= 1) { - if (verbose) { - getLogger().info("Target directory is " + targetDir[0]); - } - } else { - ap.bail("OneWaySync needs path to source directory", false); - } - - // Should be 'since' instead of 'if' - if (sourceDir != null && targetDir != null) { - - OneWaySync cc = new OneWaySync(sourceDir[0], targetDir[0]); - cc.setVerbose(verbose); - cc.setFakeit(fakeit); - cc.setDirSuffixAvoids(new String[] { "CVS" }); - cc.setFileSuffixLimits(new String[] { ".java", "Makefile", ".cvsignore", ".html", ".properties", ".txt", - ".c", ".h", ".png" }); - cc.start(); - if (report) { - getLogger().info("-------- Not Copied --------"); - cc.writeUnsynched(); - getLogger().info("----------------------------"); - cc.checkTargetSolos(); - } - } - } - - public static class BackCheck extends OneWaySync { - - public BackCheck(String targetDirName, String srcDirName) { - super(targetDirName, srcDirName); - fakeit = true; - overwrite = false; - if (getLogger().isLoggable(Level.FINE)) { - verbose = true; - } - start(); - - getLogger().info("-------- Only In Target Directory--------"); - writeUnsynched(); - getLogger().info("-----------------------------------------"); - } - - public boolean handleDirectory(File directory, String[] contentNames) { - String newDirName = getRelativePathFromSource(directory); - if (newDirName == null) { - return super.handleDirectory(directory, contentNames); - } - - File newDir = getTargetFile(newDirName); - if (!newDir.exists()) { - notCopiedList.add(directory); - } - return super.handleDirectory(directory, contentNames); - } - - public boolean handleFile(File file) { - if (!getTargetFile(getRelativePathFromSource(file)).exists()) { - notCopiedList.add(file); - } - return true; - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/Purge.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/Purge.java deleted file mode 100644 index f1854fcc3..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/Purge.java +++ /dev/null @@ -1,173 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/Purge.java,v $ -// $RCSfile: Purge.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:41:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.ArgParser; - -/** - * PURGE deletes files that start with, or end with, certain strings. Good for - * cleaning up backup leftover from various editors. - * - *
- * 
- *  Usage: java com.bbn.openmap.util.wanderer.Purge (dir path) ...
- * 
- * 
- */ -public class Purge extends Wanderer implements WandererCallback { - - boolean DETAIL = false; - String[][] purgeables = new String[2][]; - - public Purge(String[] startsWith, String[] endsWith) { - super(); - purgeables[0] = startsWith; - purgeables[1] = endsWith; - - if (purgeables[0] == null) { - purgeables[0] = new String[0]; - } - - if (purgeables[1] == null) { - purgeables[1] = new String[0]; - } - - DETAIL = getLogger().isLoggable(Level.FINE); - setCallback(this); - - if (DETAIL) { - StringBuffer sb = new StringBuffer("Deleting files that "); - boolean sw = false; - if (startsWith != null && startsWith.length > 0) { - sb.append("start with "); - for (int i = 0; i < startsWith.length; i++) { - sb.append(startsWith[i]).append(" "); - } - sw = true; - } - - if (endsWith != null && endsWith.length > 0) { - if (sw) { - sb.append("and "); - } - sb.append("end with "); - for (int i = 0; i < endsWith.length; i++) { - sb.append(endsWith[i]).append(" "); - } - } - getLogger().info(sb.toString()); - } - - } - - public boolean handleDirectory(File directory) { - // Do nothing to directories - return true; - } - - public boolean handleFile(File file) { - String fileName = file.getName(); - int i; - - for (i = 0; i < purgeables[0].length; i++) { - if (fileName.startsWith(purgeables[0][i])) { - if (DETAIL) { - getLogger().info("Deleting " + fileName); - } - file.delete(); - return true; - } - } - - for (i = 0; i < purgeables[1].length; i++) { - if (fileName.endsWith(purgeables[1][i])) { - if (DETAIL) { - getLogger().info("Deleting " + fileName); - } - file.delete(); - return true; - } - } - - return true; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Purge.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - /** - * Given a set of files or directories, parade through them to find files - * that end with '`', or files that start with '.#', and delete them. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("Purge"); - - if (argv.length == 0) { - ap.bail("Wanders through directory tree pruning '~' files.\nUsage: java com.bbn.openmap.util.wanderer.Purge ", - false); - } - - Purge purge = new Purge(new String[] { ".#" }, new String[] { "~" }); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < argv.length; i++) { - purge.handleEntry(new File(argv[i])); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/SLOC.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/SLOC.java deleted file mode 100644 index f0de27302..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/SLOC.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/SLOC.java,v $ -// $RCSfile: SLOC.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.ArgParser; - -/** - * Count the source lines of code but going through the directory and counting ; - * and }. - */ -public class SLOC implements WandererCallback { - - int sloc = 0; - boolean DETAIL = false; - - public void setSLOC(int num) { - sloc = num; - DETAIL = getLogger().isLoggable(Level.FINE); - } - - public int getSLOC() { - return sloc; - } - - // do nothing on directories - public boolean handleDirectory(File directory) { - return true; - } - - // count the ; and } in each file. - public boolean handleFile(File file) { - if (!file.getName().endsWith(".java")) { - return true; - } - - if (DETAIL) { - getLogger().info("Counting code in " + file.getName()); - } - - int count = 0; - - try { - BinaryBufferedFile bbf = new BinaryBufferedFile(file); - - try { - while (true) { - char c = bbf.readChar(); - if (c == ';' || c == '}') { - count++; - } - } - } catch (EOFException eofe) { - } catch (FormatException fe) { - } - bbf.close(); - - if (DETAIL) { - getLogger().info(file.getName() + " has " + count + " LOC"); - } - - sloc += count; - - } catch (IOException ioe) { - } - return true; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(SLOC.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - - /** - * Given a set of files or directories, parade through them to change their - * case. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("SLOC"); - - if (argv.length == 0) { - ap.bail("Counts ';' and '}' to sum up Source Lines Of Code\nUsage: java com.bbn.openmap.util.wanderer.SLOC ", - false); - } - - ap.parse(argv); - - String[] dirs = argv; - - SLOC sloc = new SLOC(); - Wanderer wanderer = new Wanderer(sloc); - - int runningTotal = 0; - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - sloc.setSLOC(0); - wanderer.handleEntry(new File(dirs[i])); - getLogger().info("Source Lines of Code in " + dirs[i] + " = " + sloc.getSLOC()); - runningTotal += sloc.getSLOC(); - } - - if (dirs.length > 1) { - getLogger().info("Total Source Lines of Code in all directories = " + runningTotal); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/TestWandererCallback.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/TestWandererCallback.java deleted file mode 100644 index ae8e65470..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/TestWandererCallback.java +++ /dev/null @@ -1,45 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/TestWandererCallback.java,v $ -// $RCSfile: TestWandererCallback.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; - -/** - * The Wanderer walks through a directory tree, and makes calls to the - * WandererCallback with what it finds. You add your WandererCallback - * to the Wanderer, and then just take your action on the files. - */ -public class TestWandererCallback implements WandererCallback { - - public boolean handleDirectory(File directory) { - System.out.println("Directory - " + directory.getName() + " has " - + directory.list().length + " item(s)"); - return true; - } - - public boolean handleFile(File file) { - System.out.println("File - " + file.getName()); - return true; - } - -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/Wanderer.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/Wanderer.java deleted file mode 100644 index 557556b3d..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/Wanderer.java +++ /dev/null @@ -1,203 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/Wanderer.java,v $ -// $RCSfile: Wanderer.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/07/17 17:31:46 $ -// $Author: mthome $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; - -import com.bbn.openmap.util.ArgParser; - -/** - * A Wanderer is a class that traverses a directory tree and finds files and - * directories. It then makes a method call on the WandererCallback class to - * have something done on those directories or files. Subclasses can set whether - * the search is exhaustive (ignoring returns from handleDirectory that the - * search was successful) and/or runs top to bottom of the directory structure, - * or bottom to top. - */ -public class Wanderer { - - WandererCallback callback = null; - protected boolean exhaustiveSearch = false; - protected boolean topToBottom = true; - - public Wanderer() { - - } - - public Wanderer(WandererCallback callback) { - this(); - this.callback = callback; - } - - public void setCallback(WandererCallback cb) { - callback = cb; - } - - public WandererCallback getCallback() { - return callback; - } - - /** - * Given a file representing a top-level directory, start wandering the tree - * and call handleDirectory or handleFile on the WandererCallback. - * - * @param file - * File (directory) to start at. - * @return true if the wandering should continue. - */ - public boolean handleEntry(File file) { - boolean continueWandering = true; - try { - String[] filenames = file.list(); - boolean dirTest = false; - boolean not14 = false; - - try { - java.lang.reflect.Method method = file.getClass().getDeclaredMethod("isDirectory", (Class[]) null); - Object obj = method.invoke(file, (Object[]) null); - if (obj instanceof Boolean) { - dirTest = ((Boolean) obj).booleanValue(); - } - } catch (NoSuchMethodException nsme) { - not14 = true; - } catch (SecurityException se) { - not14 = true; - } catch (IllegalAccessException iae) { - not14 = true; - } catch (IllegalArgumentException iae2) { - not14 = true; - } catch (java.lang.reflect.InvocationTargetException ite) { - not14 = true; - } - - if (not14) { - dirTest = (filenames != null); - } - - if (dirTest) { - - if (isTopToBottom()) { - // It's a directory... - continueWandering = callback.handleDirectory(file); - - if (continueWandering) { - continueWandering = handleDirectory(file, filenames); - } - } else { - handleDirectory(file, filenames); - callback.handleDirectory(file); - } - - } else { - continueWandering = callback.handleFile(file); - } - } catch (NullPointerException npe) { - System.out.println("null pointer exception"); - } catch (SecurityException se) { - } - - return continueWandering; - } - - /** - * Management method for the wanderer, that steps through the children of - * the directory and calls handleEntry for them. - * - * @param directory - * the directory to handle - * @param contentNames - * an array of Strings representing children of the directory - * @return true if the wandering should continue. - * @throws SecurityException - */ - protected boolean handleDirectory(File directory, String[] contentNames) throws SecurityException { - - boolean continueWandering = true; - - for (String child : contentNames) { - boolean keepGoing = handleEntry(new File(directory.getAbsolutePath() + File.separator, child)); - if (!keepGoing) { - continueWandering = exhaustiveSearch; - - if (!continueWandering) { - break; - } - } - } - - return continueWandering; - } - - public boolean isExhaustiveSearch() { - return exhaustiveSearch; - } - - /** - * @param exhaustiveSearch - * set to true if you want to ignore the handleDirectory and - * handleFile return values. - */ - public void setExhaustiveSearch(boolean exhaustiveSearch) { - this.exhaustiveSearch = exhaustiveSearch; - } - - public boolean isTopToBottom() { - return topToBottom; - } - - /** - * Set to true if handleDirectory is called before moving to - * handleFile/handleDirectory for child files. - * - * @param topToBottom - */ - public void setTopToBottom(boolean topToBottom) { - this.topToBottom = topToBottom; - } - - /** - * Given a set of files or directories, parade through them to change their - * case. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - ArgParser ap = new ArgParser("Wanderer"); - - if (argv.length == 0) { - ap.bail("", true); - } - - String[] dirs = argv; - - Wanderer wanderer = new Wanderer(new TestWandererCallback()); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - wanderer.handleEntry(new File(dirs[i])); - } - } -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/WandererCallback.java b/src/core/src/main/java/com/bbn/openmap/util/wanderer/WandererCallback.java deleted file mode 100644 index a9dc29087..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/WandererCallback.java +++ /dev/null @@ -1,50 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/WandererCallback.java,v $ -// $RCSfile: WandererCallback.java,v $ -// $Revision: 1.2 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; - -/** - * The Wanderer walks through a directory tree, and makes calls to the - * WandererCallback with what it finds. You add your WandererCallback to the - * Wanderer, and then just take your action on the files. - */ -public interface WandererCallback { - - /** - * Do what you need to do to the directory. - * - * @param directory that represents a directory to deal with. - * @return true to continue wandering through to children. - */ - public boolean handleDirectory(File directory); - - /** - * Do what you need to do to the file. - * - * @param file to handle. - * @return true to continue evaluating siblings and parent directory - * siblings. - */ - public boolean handleFile(File file); -} \ No newline at end of file diff --git a/src/core/src/main/java/com/bbn/openmap/util/wanderer/package.html b/src/core/src/main/java/com/bbn/openmap/util/wanderer/package.html deleted file mode 100644 index 07d32a449..000000000 --- a/src/core/src/main/java/com/bbn/openmap/util/wanderer/package.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -This package contains support to create classes that can traverse -file system trees and perform actions on the files and directories. - diff --git a/src/core/src/main/java/doppelt/Quantize.java b/src/core/src/main/java/doppelt/Quantize.java deleted file mode 100644 index dbc1db709..000000000 --- a/src/core/src/main/java/doppelt/Quantize.java +++ /dev/null @@ -1,724 +0,0 @@ -/* - * @(#)Quantize.java 0.90 9/19/00 Adam Doppelt - */ - -/** - * An efficient color quantization algorithm, adapted from the C++ - * implementation quantize.c in ImageMagick. The pixels for - * an image are placed into an oct tree. The oct tree is reduced in - * size, and the pixels from the original image are reassigned to the - * nodes in the reduced tree.

- * - * Here is the copyright notice from ImageMagick: - * - *

-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% Permission is hereby granted, free of charge, to any person obtaining a %
-% copy of this software and associated documentation files
-("ImageMagick"), %
-% to deal in ImageMagick without restriction, including without
-limitation %
-% the rights to use, copy, modify, merge, publish, distribute,
-sublicense, %
-% and/or sell copies of ImageMagick, and to permit persons to whom the %
-% ImageMagick 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 ImageMagick. %
-% %
-% 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 %
-% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or
-other %
-% dealings in ImageMagick. %
-% %
-% Except as contained in this notice, the name of the E. I. du Pont de %
-% Nemours and Company shall not be used in advertising or otherwise to %
-% promote the sale, use or other dealings in ImageMagick without prior %
-% written authorization from the E. I. du Pont de Nemours and Company. %
-% %
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-
- * - * - * @version 0.90 19 Sep 2000 - * @author Adam Doppelt - */ -package doppelt; - -public class Quantize { - -/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% % -% % -% % -% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % -% Q Q U U A A NN N T I ZZ E % -% Q Q U U AAAAA N N N T I ZZZ EEEEE % -% Q QQ U U A A N NN T I ZZ E % -% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % -% % -% % -% Reduce the Number of Unique Colors in an Image % -% % -% % -% Software Design % -% John Cristy % -% July 1992 % -% % -% % -% Copyright 1998 E. I. du Pont de Nemours and Company % -% % -% Permission is hereby granted, free of charge, to any person obtaining a % -% copy of this software and associated documentation files -("ImageMagick"), % -% to deal in ImageMagick without restriction, including without -limitation % -% the rights to use, copy, modify, merge, publish, distribute, -sublicense, % -% and/or sell copies of ImageMagick, and to permit persons to whom the % -% ImageMagick 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 ImageMagick. % -% % -% 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 % -% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or -other % -% dealings in ImageMagick. % -% % -% Except as contained in this notice, the name of the E. I. du Pont de % -% Nemours and Company shall not be used in advertising or otherwise to % -% promote the sale, use or other dealings in ImageMagick without prior % -% written authorization from the E. I. du Pont de Nemours and Company. % -% % -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% -% Realism in computer graphics typically requires using 24 bits/pixel to -% generate an image. Yet many graphic display devices do not contain -% the amount of memory necessary to match the spatial and color -% resolution of the human eye. The QUANTIZE program takes a 24 bit -% image and reduces the number of colors so it can be displayed on -% raster device with less bits per pixel. In most instances, the -% quantized image closely resembles the original reference image. -% -% A reduction of colors in an image is also desirable for image -% transmission and real-time animation. -% -% Function Quantize takes a standard RGB or monochrome images and quantizes -% them down to some fixed number of colors. -% -% For purposes of color allocation, an image is a set of n pixels, where -% each pixel is a point in RGB space. RGB space is a 3-dimensional -% vector space, and each pixel, pi, is defined by an ordered triple of -% red, green, and blue coordinates, (ri, gi, bi). -% -% Each primary color component (red, green, or blue) represents an -% intensity which varies linearly from 0 to a maximum value, cmax, which -% corresponds to full saturation of that color. Color allocation is -% defined over a domain consisting of the cube in RGB space with -% opposite vertices at (0,0,0) and (cmax,cmax,cmax). QUANTIZE requires -% cmax = 255. -% -% The algorithm maps this domain onto a tree in which each node -% represents a cube within that domain. In the following discussion -% these cubes are defined by the coordinate of two opposite vertices: -% The vertex nearest the origin in RGB space and the vertex farthest -% from the origin. -% -% The tree's root node represents the the entire domain, (0,0,0) through -% (cmax,cmax,cmax). Each lower level in the tree is generated by -% subdividing one node's cube into eight smaller cubes of equal size. -% This corresponds to bisecting the parent cube with planes passing -% through the midpoints of each edge. -% -% The basic algorithm operates in three phases: Classification, -% Reduction, and Assignment. Classification builds a color -% description tree for the image. Reduction collapses the tree until -% the number it represents, at most, the number of colors desired in the -% output image. Assignment defines the output image's color map and -% sets each pixel's color by reclassification in the reduced tree. -% Our goal is to minimize the numerical discrepancies between the original -% colors and quantized colors (quantization error). -% -% Classification begins by initializing a color description tree of -% sufficient depth to represent each possible input color in a leaf. -% However, it is impractical to generate a fully-formed color -% description tree in the classification phase for realistic values of -% cmax. If colors components in the input image are quantized to k-bit -% precision, so that cmax= 2k-1, the tree would need k levels below the -% root node to allow representing each possible input color in a leaf. -% This becomes prohibitive because the tree's total number of nodes is -% 1 + sum(i=1,k,8k). -% -% A complete tree would require 19,173,961 nodes for k = 8, cmax = 255. -% Therefore, to avoid building a fully populated tree, QUANTIZE: (1) -% Initializes data structures for nodes only as they are needed; (2) -% Chooses a maximum depth for the tree as a function of the desired -% number of colors in the output image (currently log2(colormap size)). -% -% For each pixel in the input image, classification scans downward from -% the root of the color description tree. At each level of the tree it -% identifies the single node which represents a cube in RGB space -% containing the pixel's color. It updates the following data for each -% such node: -% -% n1: Number of pixels whose color is contained in the RGB cube -% which this node represents; -% -% n2: Number of pixels whose color is not represented in a node at -% lower depth in the tree; initially, n2 = 0 for all nodes except -% leaves of the tree. -% -% Sr, Sg, Sb: Sums of the red, green, and blue component values for -% all pixels not classified at a lower depth. The combination of -% these sums and n2 will ultimately characterize the mean color of a -% set of pixels represented by this node. -% -% E: The distance squared in RGB space between each pixel contained -% within a node and the nodes' center. This represents the quantization -% error for a node. -% -% Reduction repeatedly prunes the tree until the number of nodes with -% n2 > 0 is less than or equal to the maximum number of colors allowed -% in the output image. On any given iteration over the tree, it selects -% those nodes whose E count is minimal for pruning and merges their -% color statistics upward. It uses a pruning threshold, Ep, to govern -% node selection as follows: -% -% Ep = 0 -% while number of nodes with (n2 > 0) > required maximum number of colors -% prune all nodes such that E <= Ep -% Set Ep to minimum E in remaining nodes -% -% This has the effect of minimizing any quantization error when merging -% two nodes together. -% -% When a node to be pruned has offspring, the pruning procedure invokes -% itself recursively in order to prune the tree from the leaves upward. -% n2, Sr, Sg, and Sb in a node being pruned are always added to the -% corresponding data in that node's parent. This retains the pruned -% node's color characteristics for later averaging. -% -% For each node, n2 pixels exist for which that node represents the -% smallest volume in RGB space containing those pixel's colors. When n2 -% > 0 the node will uniquely define a color in the output image. At the -% beginning of reduction, n2 = 0 for all nodes except a the leaves of -% the tree which represent colors present in the input image. -% -% The other pixel count, n1, indicates the total number of colors -% within the cubic volume which the node represents. This includes n1 - -% n2 pixels whose colors should be defined by nodes at a lower level in -% the tree. -% -% Assignment generates the output image from the pruned tree. The -% output image consists of two parts: (1) A color map, which is an -% array of color descriptions (RGB triples) for each color present in -% the output image; (2) A pixel array, which represents each pixel as -% an index into the color map array. -% -% First, the assignment phase makes one pass over the pruned color -% description tree to establish the image's color map. For each node -% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the -% mean color of all pixels that classify no lower than this node. Each -% of these colors becomes an entry in the color map. -% -% Finally, the assignment phase reclassifies each pixel in the pruned -% tree to identify the deepest node containing the pixel's color. The -% pixel's value in the pixel array becomes the index of this node's mean -% color in the color map. -% -% With the permission of USC Information Sciences Institute, 4676 Admiralty -% Way, Marina del Rey, California 90292, this code was adapted from module -% ALCOLS written by Paul Raveling. -% -% The names of ISI and USC are not used in advertising or publicity -% pertaining to distribution of the software without prior specific -% written permission from ISI. -% -*/ - - final static boolean QUICK = true; - - final static int MAX_RGB = 255; - final static int MAX_NODES = 266817; - final static int MAX_TREE_DEPTH = 8; - - // these are precomputed in advance - static int SQUARES[]; - static int SHIFT[]; - - static { - SQUARES = new int[MAX_RGB + MAX_RGB + 1]; - for (int i= -MAX_RGB; i <= MAX_RGB; i++) { - SQUARES[i + MAX_RGB] = i * i; - } - - SHIFT = new int[MAX_TREE_DEPTH + 1]; - for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) { - SHIFT[i] = 1 << (15 - i); - } - } - - /** - * Reduce the image to the given number of colors. The pixels are - * reduced in place. - * @return The new color palette. - */ - public static int[] quantizeImage(int pixels[][], int max_colors) { - Cube cube = new Cube(pixels, max_colors); - cube.classification(); - cube.reduction(); - cube.assignment(); - return cube.colormap; - } - - static class Cube { - int pixels[][]; - int max_colors; - int colormap[]; - - Node root; - int depth; - - // counter for the number of colors in the cube. this gets - // recalculated often. - int colors; - - // counter for the number of nodes in the tree - int nodes; - - Cube(int pixels[][], int max_colors) { - this.pixels = pixels; - this.max_colors = max_colors; - - int i = max_colors; - // tree_depth = log max_colors - // 4 - for (depth = 1; i != 0; depth++) { - i /= 4; - } - if (depth > 1) { - --depth; - } - if (depth > MAX_TREE_DEPTH) { - depth = MAX_TREE_DEPTH; - } else if (depth < 2) { - depth = 2; - } - - root = new Node(this); - } - - /* - * Procedure Classification begins by initializing a color - * description tree of sufficient depth to represent each - * possible input color in a leaf. However, it is impractical - * to generate a fully-formed color description tree in the - * classification phase for realistic values of cmax. If - * colors components in the input image are quantized to k-bit - * precision, so that cmax= 2k-1, the tree would need k levels - * below the root node to allow representing each possible - * input color in a leaf. This becomes prohibitive because the - * tree's total number of nodes is 1 + sum(i=1,k,8k). - * - * A complete tree would require 19,173,961 nodes for k = 8, - * cmax = 255. Therefore, to avoid building a fully populated - * tree, QUANTIZE: (1) Initializes data structures for nodes - * only as they are needed; (2) Chooses a maximum depth for - * the tree as a function of the desired number of colors in - * the output image (currently log2(colormap size)). - * - * For each pixel in the input image, classification scans - * downward from the root of the color description tree. At - * each level of the tree it identifies the single node which - * represents a cube in RGB space containing It updates the - * following data for each such node: - * - * number_pixels : Number of pixels whose color is contained - * in the RGB cube which this node represents; - * - * unique : Number of pixels whose color is not represented - * in a node at lower depth in the tree; initially, n2 = 0 - * for all nodes except leaves of the tree. - * - * total_red/green/blue : Sums of the red, green, and blue - * component values for all pixels not classified at a lower - * depth. The combination of these sums and n2 will - * ultimately characterize the mean color of a set of pixels - * represented by this node. - */ - void classification() { - int pixels[][] = this.pixels; - - int width = pixels.length; - int height = pixels[0].length; - - // convert to indexed color - for (int x = width; x-- > 0; ) { - for (int y = height; y-- > 0; ) { - int pixel = pixels[x][y]; - int red = (pixel >> 16) & 0xFF; - int green = (pixel >> 8) & 0xFF; - int blue = (pixel >> 0) & 0xFF; - - // a hard limit on the number of nodes in the tree - if (nodes > MAX_NODES) { - System.out.println("pruning"); - root.pruneLevel(); - --depth; - } - - // walk the tree to depth, increasing the - // number_pixels count for each node - Node node = root; - for (int level = 1; level <= depth; ++level) { - int id = (((red > node.mid_red ? 1 : 0) << 0) | - ((green > node.mid_green ? 1 : 0) << 1) | - ((blue > node.mid_blue ? 1 : 0) << 2)); - if (node.child[id] == null) { - new Node(node, id, level); - } - node = node.child[id]; - node.number_pixels += SHIFT[level]; - } - - ++node.unique; - node.total_red += red; - node.total_green += green; - node.total_blue += blue; - } - } - } - - /* - * reduction repeatedly prunes the tree until the number of - * nodes with unique > 0 is less than or equal to the maximum - * number of colors allowed in the output image. - * - * When a node to be pruned has offspring, the pruning - * procedure invokes itself recursively in order to prune the - * tree from the leaves upward. The statistics of the node - * being pruned are always added to the corresponding data in - * that node's parent. This retains the pruned node's color - * characteristics for later averaging. - */ - void reduction() { - long threshold = 1; - while (colors > max_colors) { - colors = 0; - threshold = root.reduce(threshold, Long.MAX_VALUE); - } - } - - /** - * The result of a closest color search. - */ - static class Search { - int distance; - int color_number; - } - - /* - * Procedure assignment generates the output image from the - * pruned tree. The output image consists of two parts: (1) A - * color map, which is an array of color descriptions (RGB - * triples) for each color present in the output image; (2) A - * pixel array, which represents each pixel as an index into - * the color map array. - * - * First, the assignment phase makes one pass over the pruned - * color description tree to establish the image's color map. - * For each node with n2 > 0, it divides Sr, Sg, and Sb by n2. - * This produces the mean color of all pixels that classify no - * lower than this node. Each of these colors becomes an entry - * in the color map. - * - * Finally, the assignment phase reclassifies each pixel in - * the pruned tree to identify the deepest node containing the - * pixel's color. The pixel's value in the pixel array becomes - * the index of this node's mean color in the color map. - */ - void assignment() { - colormap = new int[colors]; - - colors = 0; - root.colormap(); - - int pixels[][] = this.pixels; - - int width = pixels.length; - int height = pixels[0].length; - - Search search = new Search(); - - // convert to indexed color - for (int x = width; x-- > 0; ) { - for (int y = height; y-- > 0; ) { - int pixel = pixels[x][y]; - int red = (pixel >> 16) & 0xFF; - int green = (pixel >> 8) & 0xFF; - int blue = (pixel >> 0) & 0xFF; - - // walk the tree to find the cube containing that color - Node node = root; - for ( ; ; ) { - int id = (((red > node.mid_red ? 1 : 0) << 0) | - ((green > node.mid_green ? 1 : 0) << 1) | - ((blue > node.mid_blue ? 1 : 0) << 2) ); - if (node.child[id] == null) { - break; - } - node = node.child[id]; - } - - if (QUICK) { - // if QUICK is set, just use that - // node. Strictly speaking, this isn't - // necessarily best match. - pixels[x][y] = node.color_number; - } else { - // Find the closest color. - search.distance = Integer.MAX_VALUE; - node.parent.closestColor(red, green, blue, search); - pixels[x][y] = search.color_number; - } - } - } - } - - /** - * A single Node in the tree. - */ - static class Node { - Cube cube; - - // parent node - Node parent; - - // child nodes - Node child[]; - int nchild; - - // our index within our parent - int id; - // our level within the tree - int level; - // our color midpoint - int mid_red; - int mid_green; - int mid_blue; - - // the pixel count for this node and all children - long number_pixels; - - // the pixel count for this node - int unique; - // the sum of all pixels contained in this node - int total_red; - int total_green; - int total_blue; - - // used to build the colormap - int color_number; - - Node(Cube cube) { - this.cube = cube; - this.parent = this; - this.child = new Node[8]; - this.id = 0; - this.level = 0; - - this.number_pixels = Long.MAX_VALUE; - - this.mid_red = (MAX_RGB + 1) >> 1; - this.mid_green = (MAX_RGB + 1) >> 1; - this.mid_blue = (MAX_RGB + 1) >> 1; - } - - Node(Node parent, int id, int level) { - this.cube = parent.cube; - this.parent = parent; - this.child = new Node[8]; - this.id = id; - this.level = level; - - // add to the cube - ++cube.nodes; - if (level == cube.depth) { - ++cube.colors; - } - - // add to the parent - ++parent.nchild; - parent.child[id] = this; - - // figure out our midpoint - int bi = (1 << (MAX_TREE_DEPTH - level)) >> 1; - mid_red = parent.mid_red + ((id & 1) > 0 ? bi : -bi); - mid_green = parent.mid_green + ((id & 2) > 0 ? bi : -bi); - mid_blue = parent.mid_blue + ((id & 4) > 0 ? bi : -bi); - } - - /** - * Remove this child node, and make sure our parent - * absorbs our pixel statistics. - */ - void pruneChild() { - --parent.nchild; - parent.unique += unique; - parent.total_red += total_red; - parent.total_green += total_green; - parent.total_blue += total_blue; - parent.child[id] = null; - --cube.nodes; - cube = null; - parent = null; - } - - /** - * Prune the lowest layer of the tree. - */ - void pruneLevel() { - if (nchild != 0) { - for (int id = 0; id < 8; id++) { - if (child[id] != null) { - child[id].pruneLevel(); - } - } - } - if (level == cube.depth) { - pruneChild(); - } - } - - /** - * Remove any nodes that have fewer than threshold - * pixels. Also, as long as we're walking the tree: - * - * - figure out the color with the fewest pixels - * - recalculate the total number of colors in the tree - */ - long reduce(long threshold, long next_threshold) { - if (nchild != 0) { - for (int id = 0; id < 8; id++) { - if (child[id] != null) { - next_threshold = child[id].reduce(threshold, -next_threshold); - } - } - } - if (number_pixels <= threshold) { - pruneChild(); - } else { - if (unique != 0) { - cube.colors++; - } - if (number_pixels < next_threshold) { - next_threshold = number_pixels; - } - } - return next_threshold; - } - - /* - * colormap traverses the color cube tree and notes each - * colormap entry. A colormap entry is any node in the - * color cube tree where the number of unique colors is - * not zero. - */ - void colormap() { - if (nchild != 0) { - for (int id = 0; id < 8; id++) { - if (child[id] != null) { - child[id].colormap(); - } - } - } - if (unique != 0) { - int r = ((total_red + (unique >> 1)) / unique); - int g = ((total_green + (unique >> 1)) / unique); - int b = ((total_blue + (unique >> 1)) / unique); - cube.colormap[cube.colors] = ((( 0xFF) << 24) | - ((r & 0xFF) << 16) | - ((g & 0xFF) << 8) | - ((b & 0xFF) << 0)); - color_number = cube.colors++; - } - } - - /* ClosestColor traverses the color cube tree at a - * particular node and determines which colormap entry - * best represents the input color. - */ - void closestColor(int red, int green, int blue, Search -search) { - if (nchild != 0) { - for (int id = 0; id < 8; id++) { - if (child[id] != null) { - child[id].closestColor(red, green, blue, -search); - } - } - } - - if (unique != 0) { - int color = cube.colormap[color_number]; - int distance = distance(color, red, green, blue); - if (distance < search.distance) { - search.distance = distance; - search.color_number = color_number; - } - } - } - - /** - * Figure out the distance between this node and som color. - */ - final static int distance(int color, int r, int g, int b) { - return (SQUARES[((color >> 16) & 0xFF) - r + MAX_RGB] + - SQUARES[((color >> 8) & 0xFF) - g + MAX_RGB] + - SQUARES[((color >> 0) & 0xFF) - b + MAX_RGB]); - } - - public String toString() { - StringBuffer buf = new StringBuffer(); - if (parent == this) { - buf.append("root"); - } else { - buf.append("node"); - } - buf.append(' '); - buf.append(level); - buf.append(" ["); - buf.append(mid_red); - buf.append(','); - buf.append(mid_green); - buf.append(','); - buf.append(mid_blue); - buf.append(']'); - return new String(buf); - } - } - } -} diff --git a/src/core/src/main/java/doppelt/Quantize32.java b/src/core/src/main/java/doppelt/Quantize32.java deleted file mode 100644 index 901f0a576..000000000 --- a/src/core/src/main/java/doppelt/Quantize32.java +++ /dev/null @@ -1,744 +0,0 @@ -package doppelt; - -/** - * A modified version of Quantize.java that handles alpha. - */ - -/* - * @(#)Quantize.java 0.90 9/19/00 Adam Doppelt - */ - -/** - * An efficient color quantization algorithm, adapted from the C++ - * implementation quantize.c in ImageMagick. The pixels for - * an image are placed into an oct tree. The oct tree is reduced in - * size, and the pixels from the original image are reassigned to the - * nodes in the reduced tree.

- * - * Here is the copyright notice from ImageMagick: - * - *

-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% Permission is hereby granted, free of charge, to any person obtaining a %
-% copy of this software and associated documentation files
-("ImageMagick"), %
-% to deal in ImageMagick without restriction, including without
-limitation %
-% the rights to use, copy, modify, merge, publish, distribute,
-sublicense, %
-% and/or sell copies of ImageMagick, and to permit persons to whom the %
-% ImageMagick 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 ImageMagick. %
-% %
-% 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 %
-% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or
-other %
-% dealings in ImageMagick. %
-% %
-% Except as contained in this notice, the name of the E. I. du Pont de %
-% Nemours and Company shall not be used in advertising or otherwise to %
-% promote the sale, use or other dealings in ImageMagick without prior %
-% written authorization from the E. I. du Pont de Nemours and Company. %
-% %
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-
- * - * - * @version 0.90 19 Sep 2000 - * @author Adam Doppelt - */ -//package doppelt; - -public class Quantize32 { - -/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% % -% % -% % -% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % -% Q Q U U A A NN N T I ZZ E % -% Q Q U U AAAAA N N N T I ZZZ EEEEE % -% Q QQ U U A A N NN T I ZZ E % -% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % -% % -% % -% Reduce the Number of Unique Colors in an Image % -% % -% % -% Software Design % -% John Cristy % -% July 1992 % -% % -% % -% Copyright 1998 E. I. du Pont de Nemours and Company % -% % -% Permission is hereby granted, free of charge, to any person obtaining a % -% copy of this software and associated documentation files -("ImageMagick"), % -% to deal in ImageMagick without restriction, including without -limitation % -% the rights to use, copy, modify, merge, publish, distribute, -sublicense, % -% and/or sell copies of ImageMagick, and to permit persons to whom the % -% ImageMagick 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 ImageMagick. % -% % -% 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 % -% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or -other % -% dealings in ImageMagick. % -% % -% Except as contained in this notice, the name of the E. I. du Pont de % -% Nemours and Company shall not be used in advertising or otherwise to % -% promote the sale, use or other dealings in ImageMagick without prior % -% written authorization from the E. I. du Pont de Nemours and Company. % -% % -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% -% Realism in computer graphics typically requires using 24 bits/pixel to -% generate an image. Yet many graphic display devices do not contain -% the amount of memory necessary to match the spatial and color -% resolution of the human eye. The QUANTIZE program takes a 24 bit -% image and reduces the number of colors so it can be displayed on -% raster device with less bits per pixel. In most instances, the -% quantized image closely resembles the original reference image. -% -% A reduction of colors in an image is also desirable for image -% transmission and real-time animation. -% -% Function Quantize takes a standard RGB or monochrome images and quantizes -% them down to some fixed number of colors. -% -% For purposes of color allocation, an image is a set of n pixels, where -% each pixel is a point in RGB space. RGB space is a 3-dimensional -% vector space, and each pixel, pi, is defined by an ordered triple of -% red, green, and blue coordinates, (ri, gi, bi). -% -% Each primary color component (red, green, or blue) represents an -% intensity which varies linearly from 0 to a maximum value, cmax, which -% corresponds to full saturation of that color. Color allocation is -% defined over a domain consisting of the cube in RGB space with -% opposite vertices at (0,0,0) and (cmax,cmax,cmax). QUANTIZE requires -% cmax = 255. -% -% The algorithm maps this domain onto a tree in which each node -% represents a cube within that domain. In the following discussion -% these cubes are defined by the coordinate of two opposite vertices: -% The vertex nearest the origin in RGB space and the vertex farthest -% from the origin. -% -% The tree's root node represents the the entire domain, (0,0,0) through -% (cmax,cmax,cmax). Each lower level in the tree is generated by -% subdividing one node's cube into eight smaller cubes of equal size. -% This corresponds to bisecting the parent cube with planes passing -% through the midpoints of each edge. -% -% The basic algorithm operates in three phases: Classification, -% Reduction, and Assignment. Classification builds a color -% description tree for the image. Reduction collapses the tree until -% the number it represents, at most, the number of colors desired in the -% output image. Assignment defines the output image's color map and -% sets each pixel's color by reclassification in the reduced tree. -% Our goal is to minimize the numerical discrepancies between the original -% colors and quantized colors (quantization error). -% -% Classification begins by initializing a color description tree of -% sufficient depth to represent each possible input color in a leaf. -% However, it is impractical to generate a fully-formed color -% description tree in the classification phase for realistic values of -% cmax. If colors components in the input image are quantized to k-bit -% precision, so that cmax= 2k-1, the tree would need k levels below the -% root node to allow representing each possible input color in a leaf. -% This becomes prohibitive because the tree's total number of nodes is -% 1 + sum(i=1,k,8k). -% -% A complete tree would require 19,173,961 nodes for k = 8, cmax = 255. -% Therefore, to avoid building a fully populated tree, QUANTIZE: (1) -% Initializes data structures for nodes only as they are needed; (2) -% Chooses a maximum depth for the tree as a function of the desired -% number of colors in the output image (currently log2(colormap size)). -% -% For each pixel in the input image, classification scans downward from -% the root of the color description tree. At each level of the tree it -% identifies the single node which represents a cube in RGB space -% containing the pixel's color. It updates the following data for each -% such node: -% -% n1: Number of pixels whose color is contained in the RGB cube -% which this node represents; -% -% n2: Number of pixels whose color is not represented in a node at -% lower depth in the tree; initially, n2 = 0 for all nodes except -% leaves of the tree. -% -% Sr, Sg, Sb: Sums of the red, green, and blue component values for -% all pixels not classified at a lower depth. The combination of -% these sums and n2 will ultimately characterize the mean color of a -% set of pixels represented by this node. -% -% E: The distance squared in RGB space between each pixel contained -% within a node and the nodes' center. This represents the quantization -% error for a node. -% -% Reduction repeatedly prunes the tree until the number of nodes with -% n2 > 0 is less than or equal to the maximum number of colors allowed -% in the output image. On any given iteration over the tree, it selects -% those nodes whose E count is minimal for pruning and merges their -% color statistics upward. It uses a pruning threshold, Ep, to govern -% node selection as follows: -% -% Ep = 0 -% while number of nodes with (n2 > 0) > required maximum number of colors -% prune all nodes such that E <= Ep -% Set Ep to minimum E in remaining nodes -% -% This has the effect of minimizing any quantization error when merging -% two nodes together. -% -% When a node to be pruned has offspring, the pruning procedure invokes -% itself recursively in order to prune the tree from the leaves upward. -% n2, Sr, Sg, and Sb in a node being pruned are always added to the -% corresponding data in that node's parent. This retains the pruned -% node's color characteristics for later averaging. -% -% For each node, n2 pixels exist for which that node represents the -% smallest volume in RGB space containing those pixel's colors. When n2 -% > 0 the node will uniquely define a color in the output image. At the -% beginning of reduction, n2 = 0 for all nodes except a the leaves of -% the tree which represent colors present in the input image. -% -% The other pixel count, n1, indicates the total number of colors -% within the cubic volume which the node represents. This includes n1 - -% n2 pixels whose colors should be defined by nodes at a lower level in -% the tree. -% -% Assignment generates the output image from the pruned tree. The -% output image consists of two parts: (1) A color map, which is an -% array of color descriptions (RGB triples) for each color present in -% the output image; (2) A pixel array, which represents each pixel as -% an index into the color map array. -% -% First, the assignment phase makes one pass over the pruned color -% description tree to establish the image's color map. For each node -% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the -% mean color of all pixels that classify no lower than this node. Each -% of these colors becomes an entry in the color map. -% -% Finally, the assignment phase reclassifies each pixel in the pruned -% tree to identify the deepest node containing the pixel's color. The -% pixel's value in the pixel array becomes the index of this node's mean -% color in the color map. -% -% With the permission of USC Information Sciences Institute, 4676 Admiralty -% Way, Marina del Rey, California 90292, this code was adapted from module -% ALCOLS written by Paul Raveling. -% -% The names of ISI and USC are not used in advertising or publicity -% pertaining to distribution of the software without prior specific -% written permission from ISI. -% -*/ - - final static boolean QUICK = true; - - final static int MAX_RGB = 255; - final static int MAX_NODES = 266817; - final static int MAX_TREE_DEPTH = 8; - - // these are precomputed in advance - static int SQUARES[]; - static int SHIFT[]; - - static { - SQUARES = new int[MAX_RGB + MAX_RGB + 1]; - for (int i= -MAX_RGB; i <= MAX_RGB; i++) { - SQUARES[i + MAX_RGB] = i * i; - } - - SHIFT = new int[MAX_TREE_DEPTH + 1]; - for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) { - SHIFT[i] = 1 << (15 - i); - } - } - - /** - * Reduce the image to the given number of colors. The pixels are - * reduced in place. - * @return The new color palette. - */ - public static int[] quantizeImage(int pixels[][], int max_colors) { - Cube cube = new Cube(pixels, max_colors); - cube.classification(); - cube.reduction(); - cube.assignment(); - return cube.colormap; - } - - static class Cube { - int pixels[][]; - int max_colors; - int colormap[]; - - Node root; - int depth; - - // counter for the number of colors in the cube. this gets - // recalculated often. - int colors; - - // counter for the number of nodes in the tree - int nodes; - - Cube(int pixels[][], int max_colors) { - this.pixels = pixels; - this.max_colors = max_colors; - - int i = max_colors; - // tree_depth = log max_colors - // 4 - for (depth = 1; i != 0; depth++) { - i /= 4; - } - if (depth > 1) { - --depth; - } - if (depth > MAX_TREE_DEPTH) { - depth = MAX_TREE_DEPTH; - } else if (depth < 2) { - depth = 2; - } - - root = new Node(this); - } - - /* - * Procedure Classification begins by initializing a color - * description tree of sufficient depth to represent each - * possible input color in a leaf. However, it is impractical - * to generate a fully-formed color description tree in the - * classification phase for realistic values of cmax. If - * colors components in the input image are quantized to k-bit - * precision, so that cmax= 2k-1, the tree would need k levels - * below the root node to allow representing each possible - * input color in a leaf. This becomes prohibitive because the - * tree's total number of nodes is 1 + sum(i=1,k,8k). - * - * A complete tree would require 19,173,961 nodes for k = 8, - * cmax = 255. Therefore, to avoid building a fully populated - * tree, QUANTIZE: (1) Initializes data structures for nodes - * only as they are needed; (2) Chooses a maximum depth for - * the tree as a function of the desired number of colors in - * the output image (currently log2(colormap size)). - * - * For each pixel in the input image, classification scans - * downward from the root of the color description tree. At - * each level of the tree it identifies the single node which - * represents a cube in RGB space containing It updates the - * following data for each such node: - * - * number_pixels : Number of pixels whose color is contained - * in the RGB cube which this node represents; - * - * unique : Number of pixels whose color is not represented - * in a node at lower depth in the tree; initially, n2 = 0 - * for all nodes except leaves of the tree. - * - * total_red/green/blue : Sums of the red, green, and blue - * component values for all pixels not classified at a lower - * depth. The combination of these sums and n2 will - * ultimately characterize the mean color of a set of pixels - * represented by this node. - */ - void classification() { - int pixels[][] = this.pixels; - - int width = pixels.length; - int height = pixels[0].length; - - // convert to indexed color - for (int x = width; x-- > 0; ) { - for (int y = height; y-- > 0; ) { - int pixel = pixels[x][y]; - int alpha = (pixel >> 24) & 0xFF; - int red = (pixel >> 16) & 0xFF; - int green = (pixel >> 8) & 0xFF; - int blue = (pixel >> 0) & 0xFF; - - // a hard limit on the number of nodes in the tree - if (nodes > MAX_NODES) { - System.out.println("pruning"); - root.pruneLevel(); - --depth; - } - - // walk the tree to depth, increasing the - // number_pixels count for each node - Node node = root; - for (int level = 1; level <= depth; ++level) { - int id = (((red > node.mid_red ? 1 : 0) << 0) | - ((green > node.mid_green ? 1 : 0) << 1) | - ((blue > node.mid_blue ? 1 : 0) << 2) | - ((alpha > node.mid_alpha ? 1 : 0) << 3)); - if (node.child[id] == null) { - new Node(node, id, level); - } - node = node.child[id]; - node.number_pixels += SHIFT[level]; - } - - ++node.unique; - node.total_alpha += alpha; - node.total_red += red; - node.total_green += green; - node.total_blue += blue; - } - } - } - - /* - * reduction repeatedly prunes the tree until the number of - * nodes with unique > 0 is less than or equal to the maximum - * number of colors allowed in the output image. - * - * When a node to be pruned has offspring, the pruning - * procedure invokes itself recursively in order to prune the - * tree from the leaves upward. The statistics of the node - * being pruned are always added to the corresponding data in - * that node's parent. This retains the pruned node's color - * characteristics for later averaging. - */ - void reduction() { - long threshold = 1; - while (colors > max_colors) { - colors = 0; - threshold = root.reduce(threshold, Long.MAX_VALUE); - } - } - - /** - * The result of a closest color search. - */ - static class Search { - int distance; - int color_number; - } - - /* - * Procedure assignment generates the output image from the - * pruned tree. The output image consists of two parts: (1) A - * color map, which is an array of color descriptions (RGB - * triples) for each color present in the output image; (2) A - * pixel array, which represents each pixel as an index into - * the color map array. - * - * First, the assignment phase makes one pass over the pruned - * color description tree to establish the image's color map. - * For each node with n2 > 0, it divides Sr, Sg, and Sb by n2. - * This produces the mean color of all pixels that classify no - * lower than this node. Each of these colors becomes an entry - * in the color map. - * - * Finally, the assignment phase reclassifies each pixel in - * the pruned tree to identify the deepest node containing the - * pixel's color. The pixel's value in the pixel array becomes - * the index of this node's mean color in the color map. - */ - void assignment() { - colormap = new int[colors]; - - colors = 0; - root.colormap(); - - int pixels[][] = this.pixels; - - int width = pixels.length; - int height = pixels[0].length; - - Search search = new Search(); - - // convert to indexed color - for (int x = width; x-- > 0; ) { - for (int y = height; y-- > 0; ) { - int pixel = pixels[x][y]; - int alpha = (pixel >> 24) & 0xFF; - int red = (pixel >> 16) & 0xFF; - int green = (pixel >> 8) & 0xFF; - int blue = (pixel >> 0) & 0xFF; - - // walk the tree to find the cube containing that color - Node node = root; - for ( ; ; ) { - int id = (((red > node.mid_red ? 1 : 0) << 0) | - ((green > node.mid_green ? 1 : 0) << 1) | - ((blue > node.mid_blue ? 1 : 0) << 2) | - ((alpha > node.mid_alpha ? 1 : 0) << 3)); - if (node.child[id] == null) { - break; - } - node = node.child[id]; - } - - if (QUICK) { - // if QUICK is set, just use that - // node. Strictly speaking, this isn't - // necessarily best match. - pixels[x][y] = node.color_number; - } else { - // Find the closest color. - search.distance = Integer.MAX_VALUE; - node.parent.closestColor(alpha, red, green, blue, search); - pixels[x][y] = search.color_number; - } - } - } - } - - /** - * A single Node in the tree. - */ - static class Node { - Cube cube; - - // parent node - Node parent; - - // child nodes - Node child[]; - int nchild; - - // our index within our parent - int id; - // our level within the tree - int level; - // our color midpoint - int mid_alpha; - int mid_red; - int mid_green; - int mid_blue; - - // the pixel count for this node and all children - long number_pixels; - - // the pixel count for this node - int unique; - // the sum of all pixels contained in this node - int total_alpha; - int total_red; - int total_green; - int total_blue; - - // used to build the colormap - int color_number; - - Node(Cube cube) { - this.cube = cube; - this.parent = this; - this.child = new Node[16]; - this.id = 0; - this.level = 0; - - this.number_pixels = Long.MAX_VALUE; - - this.mid_red = (MAX_RGB + 1) >> 1; - this.mid_green = (MAX_RGB + 1) >> 1; - this.mid_blue = (MAX_RGB + 1) >> 1; - this.mid_alpha = (MAX_RGB + 1) >> 1; - } - - Node(Node parent, int id, int level) { - this.cube = parent.cube; - this.parent = parent; - this.child = new Node[16]; - this.id = id; - this.level = level; - - // add to the cube - ++cube.nodes; - if (level == cube.depth) { - ++cube.colors; - } - - // add to the parent - ++parent.nchild; - parent.child[id] = this; - - // figure out our midpoint - int bi = (1 << (MAX_TREE_DEPTH - level)) >> 1; - mid_red = parent.mid_red + ((id & 1) > 0 ? bi : -bi); - mid_green = parent.mid_green + ((id & 2) > 0 ? bi : -bi); - mid_blue = parent.mid_blue + ((id & 4) > 0 ? bi : -bi); - mid_alpha = parent.mid_alpha + ((id & 8) > 0 ? bi : -bi); - } - - /** - * Remove this child node, and make sure our parent - * absorbs our pixel statistics. - */ - void pruneChild() { - --parent.nchild; - parent.unique += unique; - parent.total_alpha += total_alpha; - parent.total_red += total_red; - parent.total_green += total_green; - parent.total_blue += total_blue; - parent.child[id] = null; - --cube.nodes; - cube = null; - parent = null; - } - - /** - * Prune the lowest layer of the tree. - */ - void pruneLevel() { - if (nchild != 0) { - for (int id = 0; id < child.length; id++) { - if (child[id] != null) { - child[id].pruneLevel(); - } - } - } - if (level == cube.depth) { - pruneChild(); - } - } - - /** - * Remove any nodes that have fewer than threshold - * pixels. Also, as long as we're walking the tree: - * - * - figure out the color with the fewest pixels - * - recalculate the total number of colors in the tree - */ - long reduce(long threshold, long next_threshold) { - if (nchild != 0) { - for (int id = 0; id < child.length; id++) { - if (child[id] != null) { - next_threshold = child[id].reduce(threshold, -next_threshold); - } - } - } - if (number_pixels <= threshold) { - pruneChild(); - } else { - if (unique != 0) { - cube.colors++; - } - if (number_pixels < next_threshold) { - next_threshold = number_pixels; - } - } - return next_threshold; - } - - /* - * colormap traverses the color cube tree and notes each - * colormap entry. A colormap entry is any node in the - * color cube tree where the number of unique colors is - * not zero. - */ - void colormap() { - if (nchild != 0) { - for (int id = 0; id < child.length; id++) { - if (child[id] != null) { - child[id].colormap(); - } - } - } - if (unique != 0) { - int a = ((total_alpha + (unique >> 1)) / unique); - int r = ((total_red + (unique >> 1)) / unique); - int g = ((total_green + (unique >> 1)) / unique); - int b = ((total_blue + (unique >> 1)) / unique); - cube.colormap[cube.colors] = (((a & 0xFF) << 24) | - ((r & 0xFF) << 16) | - ((g & 0xFF) << 8) | - ((b & 0xFF) << 0)); - color_number = cube.colors++; - } - } - - /* ClosestColor traverses the color cube tree at a - * particular node and determines which colormap entry - * best represents the input color. - */ - void closestColor(int alpha, int red, int green, int blue, Search -search) { - if (nchild != 0) { - for (int id = 0; id < child.length; id++) { - if (child[id] != null) { - child[id].closestColor(alpha, red, green, blue, -search); - } - } - } - - if (unique != 0) { - int color = cube.colormap[color_number]; - int distance = distance(color, alpha, red, green, blue); - if (distance < search.distance) { - search.distance = distance; - search.color_number = color_number; - } - } - } - - /** - * Figure out the distance between this node and som color. - */ - final static int distance(int color, int a, int r, int g, int b) { - return (SQUARES[((color >> 24) & 0xFF) - a + MAX_RGB] + - SQUARES[((color >> 16) & 0xFF) - r + MAX_RGB] + - SQUARES[((color >> 8) & 0xFF) - g + MAX_RGB] + - SQUARES[((color >> 0) & 0xFF) - b + MAX_RGB]); - } - - public String toString() { - StringBuffer buf = new StringBuffer(); - if (parent == this) { - buf.append("root"); - } else { - buf.append("node"); - } - buf.append(' '); - buf.append(level); - buf.append(" ["); - buf.append(mid_alpha); - buf.append(','); - buf.append(mid_red); - buf.append(','); - buf.append(mid_green); - buf.append(','); - buf.append(mid_blue); - buf.append(']'); - return new String(buf); - } - } - } -} diff --git a/src/core/src/main/java/org/geotiff/epsg/GeographicCS.java b/src/core/src/main/java/org/geotiff/epsg/GeographicCS.java deleted file mode 100644 index 050440fd1..000000000 --- a/src/core/src/main/java/org/geotiff/epsg/GeographicCS.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.geotiff.epsg; - -/** - * Represents the Geographic (Datum) coordinate system. - * - * @author: Niles D. Ritter - */ - -public class GeographicCS extends HorizontalCS { - - /** - * Protected Constructor; use the factory method in HorizontalCS to make - * this. - */ - protected GeographicCS(int code) { - super(code); - } - - /** - * Standard accessor. - */ - public HorizontalCS getGeographicCS() { - return this; - } - -} diff --git a/src/core/src/main/java/org/geotiff/epsg/HorizontalCS.java b/src/core/src/main/java/org/geotiff/epsg/HorizontalCS.java deleted file mode 100644 index 9882e7e31..000000000 --- a/src/core/src/main/java/org/geotiff/epsg/HorizontalCS.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.geotiff.epsg; - -/** - * Represents the base class of the EPSG horizontal coordinate systems. It is - * also contains the factory method for constructing these things. - * - * @author: Niles D. Ritter - */ - -public abstract class HorizontalCS { - - // registered EPGS codes - public static int WGS84 = 4326; - - private int code; - - protected HorizontalCS(int code) { - setCode(code); - } - - protected void setCode(int aCode) { - code = aCode; - } - - public int getCode() { - return code; - } - - /** - * This method must be implemented by the extendend class to return the - * undelying geographic coordinate system. - */ - public abstract HorizontalCS getGeographicCS(); - - /** - * Factory method for coordinate systems. - */ - public static HorizontalCS create(int code) throws InvalidCodeException { - if (code < 0) - throw new InvalidCodeException("whatever"); - - if (code < 5000) - return new GeographicCS(code); - else - return new ProjectedCS(code); - } -} diff --git a/src/core/src/main/java/org/geotiff/epsg/InvalidCodeException.java b/src/core/src/main/java/org/geotiff/epsg/InvalidCodeException.java deleted file mode 100644 index 748f7bc37..000000000 --- a/src/core/src/main/java/org/geotiff/epsg/InvalidCodeException.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.geotiff.epsg; - -/** - * Represents the Exception when an invalid coordinate system code is entered. - * - * @author: Niles D. Ritter - */ - -public class InvalidCodeException extends Exception { - - public InvalidCodeException() {} - - public InvalidCodeException(String msg) { - super(msg); - } -} diff --git a/src/core/src/main/java/org/geotiff/epsg/ProjectedCS.java b/src/core/src/main/java/org/geotiff/epsg/ProjectedCS.java deleted file mode 100644 index ea266c0ff..000000000 --- a/src/core/src/main/java/org/geotiff/epsg/ProjectedCS.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.geotiff.epsg; - -/** - * Represents the Projected coordinate system. - * - * @author: Niles D. Ritter - */ - -public class ProjectedCS extends HorizontalCS { - - GeographicCS geographicCS; - - /** - * Protected Constructor; use the factory method in HorizontalCS to make - * this. - */ - protected ProjectedCS(int code) { - super(code); - - // NB: Must construct the GeographicCS - // associated with this PCS!! - } - - /** - * Standard accessor. - */ - public HorizontalCS getGeographicCS() { - return geographicCS; - } - -} diff --git a/src/core/src/main/java/org/geotiff/image/KeyMap.java b/src/core/src/main/java/org/geotiff/image/KeyMap.java deleted file mode 100644 index 3c1c29633..000000000 --- a/src/core/src/main/java/org/geotiff/image/KeyMap.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.geotiff.image; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; - -/** - * The KeyMap represents the two-way mapping between a single set - * of GeoTIFF codes and their symbolic string names. The - * KeyRegistry keeps track of all of these. - * - * @see KeyRegistry - */ -public class KeyMap extends Properties { - -// private String name; - - private HashMap inverse = new HashMap(); - - /** Empty Constructor for serialization */ - public KeyMap() { - super(); - } - - /** Constructor for named resource file */ - public KeyMap(String resourceName) throws IOException { - super(); - InputStream propfile = getClass().getClassLoader().getResourceAsStream(resourceName); - if (propfile == null) { - throw new IOException("Resource not found"); - } - load(propfile); - - // Construct the inverse of the table - Iterator iter = entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - try { - inverse.put(entry.getValue(), entry.getKey()); - } catch (Exception e) { - // okay to fail for repeated. - } - } - } - - /** - * Gets property from key; if value starts with a $ it is an alias to - * another property. The method is non-recursive, and only follows one level - * of indirection. - * - * @param key the symbolic key to resolve - */ - public String getProperty2(String key) { - String val = getProperty(key); - if (val == null) - return val; - if (val.startsWith("$")) { - val = getProperty(val.substring(1)); - } - return val; - } - - /** - * Gets integer code from named key - * - * @param key the symbolic key to resolve - */ - int getCode(String key) { - if (key == null) - return -1; - String sval = getProperty2(key); - if (sval == null) - return -1; - else - return Integer.parseInt(sval.trim()); - } - - /** - * Gets primary string key from code value. - * - * @param code the numeric code to lookup. - */ - String getKey(int code) { - return (String) inverse.get((new Integer(code)).toString()); - } - -} diff --git a/src/core/src/main/java/org/geotiff/image/KeyRegistry.java b/src/core/src/main/java/org/geotiff/image/KeyRegistry.java deleted file mode 100644 index 652133326..000000000 --- a/src/core/src/main/java/org/geotiff/image/KeyRegistry.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.geotiff.image; - -import java.io.IOException; -import java.util.HashMap; - -/** - * The KeyRegistry provides the global registry for all sets of KeyMaps. All - * methods are static. - */ -public class KeyRegistry { - - private static HashMap keyMaps = new HashMap(); - public static String GEOKEY = "geokey"; - public static String GEO_CTRANS = "ProjCoordTransGeoKey"; - public static String EPSG_PCS = "ProjectedCSTypeGeoKey"; - public static String EPSG_DATUM = "GeogGeodeticDatumGeoKey"; - public static String EPSG_ELLIPSE = "GeogEllipsoidGeoKey"; - public static String EPSG_GCS = "GeogGeographicTypeGeoKey"; - public static String EPSG_PM = "GeogPrimeMeridianGeoKey"; - public static String EPSG_PROJ = "ProjectionGeoKey"; - public static String EPSG_VERTCS = "VerticalCSTypeGeoKey"; - - public static String UNIT_GEOG = "GeogLinearUnitsGeoKey"; - public static String UNIT_PROJ = "ProjLinearUnitsGeoKey"; - public static String UNIT_VERTCS = "VerticalUnitsGeoKey"; - - public static KeyRegistry instance = new KeyRegistry(); - - private KeyRegistry() { - try { - addKeyMap(EPSG_DATUM, "org/geotiff/epsg/epsg_datum.properties"); - addKeyMap(EPSG_ELLIPSE, "org/geotiff/epsg/epsg_ellipse.properties"); - addKeyMap(EPSG_GCS, "org/geotiff/epsg/epsg_gcs.properties"); - addKeyMap(EPSG_PCS, "org/geotiff/epsg/epsg_pcs.properties"); - addKeyMap(EPSG_PM, "org/geotiff/epsg/epsg_pm.properties"); - addKeyMap(EPSG_PROJ, "org/geotiff/epsg/epsg_proj.properties"); - addKeyMap(EPSG_VERTCS, "org/geotiff/epsg/epsg_vertcs.properties"); - addKeyMap(GEO_CTRANS, "org/geotiff/image/geo_ctrans.properties"); - addKeyMap(GEOKEY, "org/geotiff/image/geokey.properties"); - - // A number of Keys use epsg units, so we share them -// addKeyMap(UNIT_GEOG, "/org/geotiff/epsg/epsg_unit.properties"); - KeyMap units = getKeyMap(UNIT_GEOG); - addKeyMap(UNIT_PROJ, units); - addKeyMap(UNIT_VERTCS, units); - } catch (IOException e) { - // do nothing - } - } - - public static KeyRegistry getKeyRegistry() { - return instance; - } - - public static void addKeyMap(String name, KeyMap map) throws IOException { - keyMaps.put(name, map); - } - - public static void addKeyMap(String name, String resource) - throws IOException { - addKeyMap(name, new KeyMap(resource)); - } - - public static KeyMap getKeyMap(String name) { - Object map = keyMaps.get(name); - return (KeyMap) map; - } - - public static int getCode(String map, String key) { - KeyMap keyMap = getKeyMap(map); - if (keyMap == null) - return -1; - return keyMap.getCode(key); - } - - public static String getKey(String map, int code) { - KeyMap keyMap = getKeyMap(map); - if (keyMap == null) - return null; - return keyMap.getKey(code); - } -} diff --git a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDescriptor.java b/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDescriptor.java deleted file mode 100644 index bc600a2c6..000000000 --- a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDescriptor.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.geotiff.image.jai; - -/* - * JAI GeoTIFF extensions. - * Copyright (c) 2000 Niles Ritter. - */ -import org.libtiff.jai.codec.XTIFFDirectory; -import org.libtiff.jai.operator.XTIFFDescriptor; - -/** - * The GeoTIFFDescriptor is a single class that is both an OperationDescriptor - * and a RenderedImageFactory for the overridden "tiff" operation. - * - * @author Niles Ritter - */ - -public class GeoTIFFDescriptor extends XTIFFDescriptor { - - /** - * The public Constructor. - */ - public GeoTIFFDescriptor() { - super(); - } - - private static boolean alreadyCalled = false; - - /** - * A convenience method for registering the "geotiff" methods into JAI. This - * needs only be called once before using GeoTIFF methods. - */ - public synchronized static void register() { - if (!alreadyCalled) { - // Create the objects - GeoTIFFDescriptor odesc = new GeoTIFFDescriptor(); - XTIFFDescriptor.register(odesc); - - // Tell XTIFF to create a GeoTIFF directory instead of XTIFF. - XTIFFDirectory.setFactory(new GeoTIFFFactory()); - alreadyCalled = true; - } - } -} diff --git a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDirectory.java b/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDirectory.java deleted file mode 100644 index 3faa68e10..000000000 --- a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFDirectory.java +++ /dev/null @@ -1,342 +0,0 @@ -package org.geotiff.image.jai; - -import java.util.Iterator; -import java.util.TreeMap; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFDirectory; -import org.libtiff.jai.codec.XTIFFField; - -import com.sun.media.jai.codec.SeekableStream; - -/** - * An extension of the XTIFFDirectory that understands the structure of the - * GeoTIFF key set - * - * @author Niles D. Ritter - */ - -public class GeoTIFFDirectory extends XTIFFDirectory implements java.io.Serializable { - - private TreeMap geoKeyIndex = new TreeMap(); - private int keyDirectoryVersion; - private int majorRevision; - private int minorRevision; - private int numberOfKeys; - private double[] tiepoints = null; - private double[] scales = null; - private double[] matrix = null; - private boolean hasGeoKeys = false; - - /** - * public constructor (for serializability) - */ - public GeoTIFFDirectory() { - } - - /** - * Constructs a GeoTIFFDirectory by reading a SeekableStream. The ifd_offset - * parameter specifies the stream offset from which to begin reading; this - * mechanism is sometimes used to store private IFDs within a TIFF file that - * are not part of the normal sequence of IFDs. - */ - - public GeoTIFFDirectory(SeekableStream stream, long ifd_offset) throws java.io.IOException { - super(stream, ifd_offset); - readGeoKeys(); - log("GeoTIFFDirectory constructor success."); - } - - /** - * Constructs a GeoTIFFDirectory from a SeekableStream. The directory - * parameter specifies which directory to read from the linked list present - * in the stream; directory 0 is normally read but it is possible to store - * multiple images in a single TIFF file by maintaing multiple directories. - */ - - public GeoTIFFDirectory(SeekableStream stream, int directory) throws java.io.IOException { - super(stream, directory); - readGeoKeys(); - log("GeoTIFFDirectory constructor success."); - } - - private void log(String msg) { - } - - /** - * Generates the TIFF fields from the GeoKey list - */ - private void createGeoTags() { - - if (!hasGeoKeys) - return; - - char numberOfKeys = (char) geoKeyIndex.size(); - char[] keys = new char[(numberOfKeys + 1) * 4]; - - // Write the 4-entry header - keys[0] = 1; // key version - keys[1] = 1; // majorRevision - keys[2] = 0; // minorRevision - keys[3] = numberOfKeys; - - // Write the key directory out - Iterator it = geoKeyIndex.values().iterator(); - double[] doubles = new double[numberOfKeys]; - String strings = ""; - int indx = 4; - char numDoubles = 0; - char tag = 0; - char valueOrOffset = 0; - while (it.hasNext()) { - XTIFFField geoKey = (XTIFFField) it.next(); - switch (geoKey.getType()) { - case XTIFFField.TIFF_SHORT: - // short values are stored in the valueOrOffset - tag = 0; - valueOrOffset = (char) geoKey.getAsInt(0); - break; - case XTIFFField.TIFF_DOUBLE: - tag = (char) XTIFF.TIFFTAG_GEO_DOUBLE_PARAMS; - doubles[numDoubles] = geoKey.getAsDouble(0); - valueOrOffset = numDoubles++; - break; - case XTIFFField.TIFF_ASCII: - // strings are '|' pipe delimited - tag = (char) XTIFF.TIFFTAG_GEO_ASCII_PARAMS; - valueOrOffset = (char) strings.length(); - strings = strings + geoKey.getAsString(0) + "|"; - break; - } // switch - keys[indx++] = (char) geoKey.getTag(); - keys[indx++] = tag; - keys[indx++] = (char) geoKey.getCount(); - keys[indx++] = valueOrOffset; - } // while - - // Add the Directory tag - addField(XTIFF.TIFFTAG_GEO_KEY_DIRECTORY, XTIFFField.TIFF_SHORT, keys.length, keys); - - // Add the Ascii tag if needed - if (strings.length() > 0) { - char zero = 0; - strings = strings + zero; - addField(XTIFF.TIFFTAG_GEO_ASCII_PARAMS, XTIFFField.TIFF_ASCII, strings.length(), new String[] { strings }); - } - - // Add the double tag if needed - if (numDoubles > 0) { - double[] doubleVals = new double[numDoubles]; - for (int i = 0; i < numDoubles; i++) - doubleVals = doubles; - addField(XTIFF.TIFFTAG_GEO_DOUBLE_PARAMS, XTIFFField.TIFF_DOUBLE, numDoubles, doubleVals); - } - - // set up the other values stored in tags - if (matrix != null) - addField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX, XTIFFField.TIFF_DOUBLE, matrix.length, matrix); - if (tiepoints != null) - addField(XTIFF.TIFFTAG_GEO_TIEPOINTS, XTIFFField.TIFF_DOUBLE, tiepoints.length, tiepoints); - if (scales != null) - addField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE, XTIFFField.TIFF_DOUBLE, scales.length, scales); - } - - /** - * stores a single geoKey in the index table, from the existing field - * information - */ - private void storeGeoKey(int keyID, int tiffTag, int valueCount, int valueOrOffset) - throws java.io.IOException { - int type = XTIFFField.TIFF_SHORT; - Object value = null; - if (tiffTag > 0) { - // Values are in another tag: - XTIFFField values = getField(tiffTag); - if (values != null) { - type = values.getType(); - if (type == XTIFFField.TIFF_ASCII) { - String svalue = values.getAsString(0).substring(valueOrOffset, valueOrOffset - + valueCount - 1); - value = new String[] { svalue }; - } else if (type == XTIFFField.TIFF_DOUBLE) { - // we shouldn't have valueCount != 1 here - double dvalue = values.getAsDouble(valueOrOffset); - value = new double[] { dvalue }; - } - } else { - throw new java.io.IOException("GeoTIFF tag not found"); - } // values tag found - } else { - // value is SHORT, stored in valueOrOffset - type = XTIFFField.TIFF_SHORT; - value = new char[] { (char) valueOrOffset }; - } // tiffTag - addGeoKey(keyID, type, valueCount, value); - } - - /** - * Returns an array of XTIFFFields containing all the fields in this - * directory. Prior to returning array, determine if there are any GeoKeys, - * and if so, set up the corresponding GeoTIFF fields. - */ - public XTIFFField[] getFields() { - if (hasGeoKeys) - createGeoTags(); - return super.getFields(); - } - - /** - * populates the geoKeyIndex table from the values stored in the current - * TIFF fields. - */ - private void readGeoKeys() throws java.io.IOException { - - // read in the keys - XTIFFField geoKeyTag = getField(XTIFF.TIFFTAG_GEO_KEY_DIRECTORY); - if (geoKeyTag != null) { - char[] keys = geoKeyTag.getAsChars(); - - // Set up header info - keyDirectoryVersion = keys[0]; // should be 1 forever. - majorRevision = keys[1]; // currently 1 - minorRevision = keys[2]; // 0,1, or 2... - numberOfKeys = keys[3]; - - // Parse out keys and values - for (int i = 4; i < keys.length; i += 4) { - int keyID = keys[i]; - int tiffTag = keys[i + 1]; - int valueCount = keys[i + 2]; - int valueOrOffset = keys[i + 3]; - storeGeoKey(keyID, tiffTag, valueCount, valueOrOffset); - } - - } - - // set up the values stored in tags - // read in the data stored as real tags - XTIFFField matrixTag = getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); - XTIFFField tiepointTag = getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); - XTIFFField scaleTag = getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); - if (tiepointTag != null) { - tiepoints = tiepointTag.getAsDoubles(); - } - if (scaleTag != null) { - scales = scaleTag.getAsDoubles(); - } - if (matrixTag != null) { - matrix = matrixTag.getAsDoubles(); - } - } // readGeoKeys - - /** - * Add a geoKey to the directory - */ - public void addGeoKey(int key, int type, int count, Object data) { - XTIFFField geoKey = createField(key, type, count, data); - addGeoKey(geoKey); - } - - /** - * Add an existing geoKey to the directory. - */ - public void addGeoKey(XTIFFField geoKey) { - geoKeyIndex.put(new Integer(geoKey.getTag()), geoKey); - hasGeoKeys = true; - } - - /** - * Returns an array of XTIFFFields containing all the fields corresponding - * to the GeoKeys. - */ - public XTIFFField[] getGeoKeys() { - XTIFFField[] keys = new XTIFFField[geoKeyIndex.size()]; - Iterator it = geoKeyIndex.values().iterator(); - int i = 0; - while (it.hasNext()) { - keys[i++] = (XTIFFField) it.next(); - } - return keys; - } - - /** - * Indexed Accessor to the Geokeys,indexed by the key values. - */ - public XTIFFField getGeoKey(int key) { - return (XTIFFField) geoKeyIndex.get(new Integer(key)); - } - - /** - * return the tiepoint tag values - */ - public double[] getTiepoints() { - return tiepoints; - } - - /** - * return the pixel scale tag values - */ - public double[] getPixelScale() { - return scales; - } - - /** - * return the transformation matrix tag values - */ - public double[] getTransformationMatrix() { - return matrix; - } - - /** - * set the tiepoint tag values - */ - public void setTiepoints(double[] tiepoints) { - this.tiepoints = tiepoints; - } - - /** - * return the pixel scale tag values - */ - public void setPixelScale(double[] scales) { - this.scales = scales; - } - - /** - * return the pixel scale tag values - */ - public void setTransformationMatrix(double[] matrix) { - this.matrix = matrix; - } - - public int getKeyDirectoryVersion() { - return keyDirectoryVersion; - } - - public void setKeyDirectoryVersion(int keyDirectoryVersion) { - this.keyDirectoryVersion = keyDirectoryVersion; - } - - public int getMajorRevision() { - return majorRevision; - } - - public void setMajorRevision(int majorRevision) { - this.majorRevision = majorRevision; - } - - public int getMinorRevision() { - return minorRevision; - } - - public void setMinorRevision(int minorRevision) { - this.minorRevision = minorRevision; - } - - public int getNumberOfKeys() { - return numberOfKeys; - } - - public void setNumberOfKeys(int numberOfKeys) { - this.numberOfKeys = numberOfKeys; - } -} diff --git a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFFactory.java b/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFFactory.java deleted file mode 100644 index 5adf8c841..000000000 --- a/src/core/src/main/java/org/geotiff/image/jai/GeoTIFFFactory.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * GeoTIFF extension to JAI. - * - * Software distributed distributed on an "AS IS" - * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. - * Permission granted to use and modify this code, - * so long as this copyright notice appears in the derived code. - * - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -package org.geotiff.image.jai; - -import java.io.IOException; - -import org.libtiff.jai.codec.XTIFFDirectory; -import org.libtiff.jai.codec.XTIFFFactory; - -import com.sun.media.jai.codec.SeekableStream; - -/** - * A factory object for a GeoTIFFDirectory and its corresponding XTIFFField - * class. - * - * @see XTIFFDirectory - * @see XTIFFField - */ -public class GeoTIFFFactory extends XTIFFFactory implements - java.io.Serializable { - /** - * Default constructor - */ - public GeoTIFFFactory() {} - - /** - * Constructs a TIFFDirectoryFactory from a SeekableStream. The directory - * parameter specifies which directory to read from the linked list present - * in the stream; directory 0 is normally read but it is possible to store - * multiple images in a single TIFF file by maintaing multiple directories. - * - * @param stream a SeekableStream to read from. - * @param directory the index of the directory to read. - */ - public XTIFFDirectory createDirectory(SeekableStream stream, int directory) - throws IOException { - return new GeoTIFFDirectory(stream, directory); - } - - /** - * Constructs a TIFFDirectory by reading a SeekableStream. The ifd_offset - * parameter specifies the stream offset from which to begin reading; this - * mechanism is sometimes used to store private IFDs within a TIFF file that - * are not part of the normal sequence of IFDs. - * - * @param stream a SeekableStream to read from. - * @param ifd_offset the long byte offset of the directory. - */ - public XTIFFDirectory createDirectory(SeekableStream stream, long ifd_offset) - throws IOException { - return new GeoTIFFDirectory(stream, ifd_offset); - } - - /** - * Constructs an empty TIFFDirectory for writing - */ - public XTIFFDirectory createDirectory() { - return new GeoTIFFDirectory(); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFF.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFF.java deleted file mode 100644 index ceee60129..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFF.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -/** - * XTIFF. eXtensible TIFF Library. - * - * A class containing common image type-codes and public tags. - * - */ - -public abstract class XTIFF { - public static final int TIFFTAG_NEWSUBFILETYPE = 254; - public static final int FILETYPE_REDUCEDIMAGE = 1; - public static final int FILETYPE_PAGE = 2; - public static final int FILETYPE_MASK = 4; - public static final int TIFFTAG_OSUBFILETYPE = 255; - public static final int OFILETYPE_IMAGE = 1; - public static final int OFILETYPE_REDUCEDIMAGE = 2; - public static final int OFILETYPE_PAGE = 3; - public static final int TIFFTAG_IMAGE_WIDTH = 256; - public static final int TIFFTAG_IMAGE_LENGTH = 257; - public static final int TIFFTAG_BITS_PER_SAMPLE = 258; - public static final int TIFFTAG_COMPRESSION = 259; - public static final int COMPRESSION_NONE = 1; - public static final int COMPRESSION_FAX_G3_1D = 2; - public static final int COMPRESSION_FAX_G3_2D = 3; - public static final int COMPRESSION_FAX_G4_2D = 4; - public static final int COMPRESSION_LZW = 5; - public static final int COMPRESSION_OJPEG = 6; - public static final int COMPRESSION_JPEG = 7; - public static final int COMPRESSION_NEXT = 32766; - public static final int COMPRESSION_CCITTRLEW = 32771; - public static final int COMPRESSION_PACKBITS = 32773; - public static final int COMPRESSION_THUNDERSCAN = 32809; - public static final int COMPRESSION_DEFLATE = 32946; - public static final int COMPRESSION_IT8CTPAD = 32895; - public static final int COMPRESSION_IT8LW = 32896; - public static final int COMPRESSION_IT8MP = 32897; - public static final int COMPRESSION_IT8BL = 32898; - public static final int COMPRESSION_PIXARFILM = 32908; - public static final int COMPRESSION_PIXARLOG = 32909; - public static final int COMPRESSION_DCS = 32947; - public static final int COMPRESSION_JBIG = 34661; - public static final int COMPRESSION_SGILOG = 34676; - public static final int COMPRESSION_SGILOG24 = 34677; - public static final int TIFFTAG_PHOTOMETRIC_INTERPRETATION = 262; - public static final int PHOTOMETRIC_WHITE_IS_ZERO = 0; - public static final int PHOTOMETRIC_BLACK_IS_ZERO = 1; - public static final int PHOTOMETRIC_RGB = 2; - public static final int PHOTOMETRIC_PALETTE = 3; - public static final int PHOTOMETRIC_TRANSPARENCY = 4; - public static final int PHOTOMETRIC_CMYK = 5; - public static final int PHOTOMETRIC_YCBCR = 6; - public static final int PHOTOMETRIC_CIELAB = 8; - public static final int PHOTOMETRIC_LOGL = 32844; - public static final int PHOTOMETRIC_LOGLUV = 32845; - public static final int TIFFTAG_THRESHHOLDING = 263; - public static final int THRESHHOLD_BILEVEL = 1; - public static final int THRESHHOLD_HALFTONE = 2; - public static final int THRESHHOLD_ERRORDIFFUSE = 3; - public static final int TIFFTAG_CELLWIDTH = 264; - public static final int TIFFTAG_CELLLENGTH = 265; - public static final int TIFFTAG_FILL_ORDER = 266; - public static final int FILL_ORDER_MSB2LSB = 1; - public static final int FILL_ORDER_LSB2MSB = 2; - public static final int TIFFTAG_DOCUMENTNAME = 269; - public static final int TIFFTAG_IMAGEDESCRIPTION = 270; - public static final int TIFFTAG_MAKE = 271; - public static final int TIFFTAG_MODEL = 272; - public static final int TIFFTAG_STRIPOFFSETS = 273; - public static final int TIFFTAG_ORIENTATION = 274; - public static final int ORIENTATION_TOPLEFT = 1; - public static final int ORIENTATION_TOPRIGHT = 2; - public static final int ORIENTATION_BOTRIGHT = 3; - public static final int ORIENTATION_BOTLEFT = 4; - public static final int ORIENTATION_LEFTTOP = 5; - public static final int ORIENTATION_RIGHTTOP = 6; - public static final int ORIENTATION_RIGHTBOT = 7; - public static final int ORIENTATION_LEFTBOT = 8; - public static final int TIFFTAG_STRIP_OFFSETS = 273; - public static final int TIFFTAG_SAMPLES_PER_PIXEL = 277; - public static final int TIFFTAG_ROWS_PER_STRIP = 278; - public static final int TIFFTAG_STRIP_BYTE_COUNTS = 279; - public static final int TIFFTAG_MINSAMPLEVALUE = 280; - public static final int TIFFTAG_MAXSAMPLEVALUE = 281; - public static final int TIFFTAG_X_RESOLUTION = 282; - public static final int TIFFTAG_Y_RESOLUTION = 283; - public static final int TIFFTAG_PLANARCONFIG = 284; - public static final int PLANARCONFIG_CONTIG = 1; - public static final int PLANARCONFIG_SEPARATE = 2; - public static final int TIFFTAG_PAGENAME = 285; - public static final int TIFFTAG_XPOSITION = 286; - public static final int TIFFTAG_YPOSITION = 287; - public static final int TIFFTAG_FREEOFFSETS = 288; - public static final int TIFFTAG_FREEBYTECOUNTS = 289; - public static final int TIFFTAG_GRAYRESPONSEUNIT = 290; - public static final int GRAYRESPONSEUNIT_10S = 1; - public static final int GRAYRESPONSEUNIT_100S = 2; - public static final int GRAYRESPONSEUNIT_1000S = 3; - public static final int GRAYRESPONSEUNIT_10000S = 4; - public static final int GRAYRESPONSEUNIT_100000S = 5; - public static final int TIFFTAG_GRAYRESPONSECURVE = 291; - public static final int TIFFTAG_T4_OPTIONS = 292; - public static final int T4_2DENCODING = 1; - public static final int T4_UNCOMPRESSED = 2; - public static final int T4_FILLBITS = 4; - public static final int TIFFTAG_T6_OPTIONS = 293; - public static final int T6_UNCOMPRESSED = 2; - public static final int TIFFTAG_RESOLUTION_UNIT = 296; - public static final int RESUNIT_NONE = 1; - public static final int RESUNIT_INCH = 2; - public static final int RESUNIT_CENTIMETER = 3; - public static final int TIFFTAG_PAGENUMBER = 297; - public static final int TIFFTAG_COLORRESPONSEUNIT = 300; - public static final int COLORRESPONSEUNIT_10S = 1; - public static final int COLORRESPONSEUNIT_100S = 2; - public static final int COLORRESPONSEUNIT_1000S = 3; - public static final int COLORRESPONSEUNIT_10000S = 4; - public static final int COLORRESPONSEUNIT_100000S = 5; - public static final int TIFFTAG_TRANSFERFUNCTION = 301; - public static final int TIFFTAG_SOFTWARE = 305; - public static final int TIFFTAG_DATETIME = 306; - public static final int TIFFTAG_ARTIST = 315; - public static final int TIFFTAG_HOSTCOMPUTER = 316; - public static final int TIFFTAG_PREDICTOR = 317; - public static final int TIFFTAG_WHITEPOINT = 318; - public static final int TIFFTAG_PRIMARYCHROMATICITIES = 319; - public static final int TIFFTAG_COLORMAP = 320; - public static final int TIFFTAG_HALFTONEHINTS = 321; - public static final int TIFFTAG_TILE_WIDTH = 322; - public static final int TIFFTAG_TILE_LENGTH = 323; - public static final int TIFFTAG_TILE_OFFSETS = 324; - public static final int TIFFTAG_TILE_BYTE_COUNTS = 325; - public static final int TIFFTAG_BADFAXLINES = 326; - public static final int TIFFTAG_CLEANFAXDATA = 327; - public static final int CLEANFAXDATA_CLEAN = 0; - public static final int CLEANFAXDATA_REGENERATED = 1; - public static final int CLEANFAXDATA_UNCLEAN = 2; - public static final int TIFFTAG_CONSECUTIVEBADFAXLINES = 328; - public static final int TIFFTAG_SUBIFD = 330; - public static final int TIFFTAG_INKSET = 332; - public static final int INKSET_CMYK = 1; - public static final int TIFFTAG_INKNAMES = 333; - public static final int TIFFTAG_NUMBEROFINKS = 334; - public static final int TIFFTAG_DOTRANGE = 336; - public static final int TIFFTAG_TARGETPRINTER = 337; - public static final int TIFFTAG_EXTRASAMPLES = 338; - public static final int TIFFTAG_EXTRA_SAMPLES = 338; - public static final int EXTRA_SAMPLE_UNSPECIFIED = 0; - public static final int EXTRA_SAMPLE_ASSOCALPHA = 1; - public static final int EXTRA_SAMPLE_UNASSALPHA = 2; - public static final int TIFFTAG_SAMPLE_FORMAT = 339; - public static final int SAMPLE_FORMAT_UINT = 1; - public static final int SAMPLE_FORMAT_INT = 2; - public static final int SAMPLE_FORMAT_IEEEFP = 3; - public static final int SAMPLE_FORMAT_VOID = 4; - public static final int TIFFTAG_S_MIN_SAMPLE_VALUE = 340; - public static final int TIFFTAG_S_MAX_SAMPLE_VALUE = 341; - public static final int TIFFTAG_COPYRIGHT = 33432; - public static final int TIFFTAG_GEO_TIEPOINTS = 33922; - public static final int TIFFTAG_GEO_PIXEL_SCALE = 33550; - public static final int TIFFTAG_GEO_TRANS_MATRIX = 34264; - public static final int TIFFTAG_GEO_KEY_DIRECTORY = 34735; - public static final int TIFFTAG_GEO_DOUBLE_PARAMS = 34736; - public static final int TIFFTAG_GEO_ASCII_PARAMS = 34737; - - // JAI (not TIFF) Image types - public static final int TYPE_BILEVEL_WHITE_IS_ZERO = 0; - public static final int TYPE_BILEVEL_BLACK_IS_ZERO = 1; - public static final int TYPE_GREYSCALE_WHITE_IS_ZERO = 2; - public static final int TYPE_GREYSCALE_BLACK_IS_ZERO = 3; - public static final int TYPE_RGB = 4; - public static final int TYPE_ARGB_PRE = 5; - public static final int TYPE_ARGB = 6; - public static final int TYPE_ORGB = 7; - public static final int TYPE_RGB_EXTRA = 8; - public static final int TYPE_PALETTE = 9; - public static final int TYPE_TRANS = 10; -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDecodeParam.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDecodeParam.java deleted file mode 100644 index 8a41c55c6..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDecodeParam.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import com.sun.media.jai.codec.TIFFDecodeParam; - -/** - * An extension of TIFFDecodeParam for decoding images in the - * TIFF format. In addition to the inherited properties, this object also - * retains a reference to the parsed XTIFFDirectory that is constructed from the - * file. For encoding, an empty XTIFFDirectory is constructed, into which the - * user may provide any additional tags for controlling the contents of the - * data. For example, if the image is to be compressed, some additional tags may - * be needed to specify parameters for the particular compression scheme. - * - * @see XTIFFDirectory - * @see XTIFFDecodeParam - */ - -public class XTIFFDecodeParam extends TIFFDecodeParam { - - protected XTIFFDirectory directory = null; - - /** - * Promotes an XTIFFEncodeParam object from simpler one - */ - public XTIFFDecodeParam(TIFFDecodeParam param) { - if (param == null) - return; - setDecodePaletteAsShorts(param.getDecodePaletteAsShorts()); - } - - /** Constructs a default instance of XTIFFDecodeParam. */ - public XTIFFDecodeParam() {} - - /** returns the current XTIFFDirectory */ - public XTIFFDirectory getDirectory() { - return directory; - } - - /** sets the current XTIFFDirectory */ - public void setDirectory(XTIFFDirectory dir) { - directory = dir; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDirectory.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDirectory.java deleted file mode 100644 index 6cbf6c651..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFDirectory.java +++ /dev/null @@ -1,856 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.io.IOException; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.TreeMap; -import java.util.Vector; - -import org.libtiff.jai.util.JaiI18N; - -import com.sun.media.jai.codec.SeekableStream; - -/** - * XTIFFDirectory is an extensible TIFF directory object. This class may be - * extended without changing the XTIFF codec by overriding the XTIFFFactory - * instance registered in this class. In addition, this class is the repository - * of all XTIFFTileCodec's which may be augmented with new codecs, again without - * overriding the ImageCodec. If the jai "tiff" codec has been overridden - * through the XTIFFDescriptor.register() method, each XTIFF image - * will possess a property called "tiff.directory" which will be an object of - * the type created by the factory. The class is declared as serializable to - * permit its transmission to remote images as a set of parameters to the codec, - * and to be able to survive as an instantiated property of the RenderedImage. - * - * - * @serializable - * @author Niles Ritter - * @see XTIFFDescriptor - * @see XTIFFField - * @see XTIFFTileCodec - * @see XTIFFFactory - */ -public class XTIFFDirectory - extends Object - implements java.io.Serializable { - private int imageType; - - /** default directory factory */ - protected static XTIFFFactory factory = new XTIFFFactory(); - - protected static Hashtable tileCodecs = new Hashtable(); - - /** The stream being read. Not persisted */ - transient protected SeekableStream stream; - - /** A boolean storing the endianness of the stream. */ - boolean isBigEndian; - - /** A boolean indicating tiled tagset */ - boolean _isTiled = false; - - /** for dynamically adding fields in sorted order */ - TreeMap fieldIndex = new TreeMap(); - - /** The default constructor. Publicized for Serializability */ - public XTIFFDirectory() { - } - - private static boolean isValidEndianTag(int endian) { - return ((endian == 0x4949) || (endian == 0x4d4d)); - } - - /** - * If true this image uses TIFF 6.0 tiling - */ - public boolean isTiled() { - return _isTiled; - } - - /** - * reads the TIFF header. Not likely to be overridden. - */ - protected void readHeader() - throws IOException { - - // Read the TIFF header - stream.seek(0L); - int endian = stream.readUnsignedShort(); - if (!isValidEndianTag(endian)) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFDirectory1")); - } - isBigEndian = (endian == 0x4d4d); - - // Verify that Douglas Addams still has influence in software: - int magic = readUnsignedShort(stream); - if (magic != 42) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFDirectory2")); - } - - } - - /** - * Constructs a XTIFFDirectory from a SeekableStream. The directory parameter - * specifies which directory to read from the linked list present in the - * stream; directory 0 is normally read but it is possible to store multiple - * images in a single TIFF file by maintaing multiple directories. - * - * @param stream a SeekableStream to read from. - * @param directory the index of the directory to read. - */ - protected XTIFFDirectory(SeekableStream stream, int directory) - throws IOException { - - this.stream = stream; - long global_save_offset = stream.getFilePointer(); - long ifd_offset; - - readHeader(); - - // Get the initial ifd offset as an unsigned int (using a long) - ifd_offset = readUnsignedInt(stream); - - for (int i = 0; i < directory; i++) { - if (ifd_offset == 0L) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFDirectory3")); - } - - stream.seek(ifd_offset); - int entries = readUnsignedShort(stream); - stream.skip(12 * entries); - - ifd_offset = readUnsignedInt(stream); - } - - stream.seek(ifd_offset); - initialize(); - stream.seek(global_save_offset); - } - - /** - * Constructs a XTIFFDirectory by reading a SeekableStream. The ifd_offset - * parameter specifies the stream offset from which to begin reading; this - * mechanism is sometimes used to store private IFDs within a TIFF file that - * are not part of the normal sequence of IFDs. - * - * @param stream a SeekableStream to read from. - * @param ifd_offset the long byte offset of the directory. - */ - protected XTIFFDirectory(SeekableStream stream, long ifd_offset) - throws IOException { - this.stream = stream; - long global_save_offset = stream.getFilePointer(); - - readHeader(); - - stream.seek(ifd_offset); - initialize(); - stream.seek(global_save_offset); - } - - private static final int[] _sizeOfType = { - 0, // 0 = n/a - 1, // 1 = byte - 1, // 2 = ascii - 2, // 3 = short - 4, // 4 = long - 8, // 5 = rational - 1, // 6 = sbyte - 1, // 7 = undefined - 2, // 8 = sshort - 4, // 9 = slong - 8, // 10 = srational - 4, // 11 = float - 8 - // 12 = double - }; - - /** - * Return the size of a data type. Extend if you need to define new TIFF - * field types. Also override the createField() method of the XTIFFFactory, - * the XTIFFField class, and the readFieldValue() method here. - * - * @param type the XTIFFField type code - * @see XTIFFField - * @see XTIFFFactory - */ - public int sizeOfType(int type) - throws ArrayIndexOutOfBoundsException { - return _sizeOfType[type]; - } - - /** - * Create and add a TIFF field to this directory. - * - * @param tag the TIFF tag listed in XTIFF - * @param type the TIFF field type listed in XTIFFField - * @param count the number of values in array obj - * @param obj the array of values - * @see XTIFFField - * @see XTIFF - */ - public void addField(int tag, int type, int count, Object obj) { - addField(factory.createField(tag, type, count, obj)); - } - - /** - * Create a TIFF field - * - * @param tag the TIFF tag listed in XTIFF - * @param type the TIFF field type listed in XTIFFField - * @param count the number of values in array obj - * @param obj the array of values - * @see XTIFFField - * @see XTIFF - */ - public static XTIFFField createField(int tag, int type, int count, Object obj) { - return factory.createField(tag, type, count, obj); - } - - /** - * Add an existing TIFF field to this directory. - * - * @param type the XTIFFField type code - * @see XTIFFField - */ - public void addField(XTIFFField field) { - fieldIndex.put(new Integer(field.tag), field); - } - - /** - * Initialize the directory from a stream - */ - protected void initialize() - throws IOException { - XTIFFField field; - // long nextTagOffset; - - int numEntries = readUnsignedShort(stream); - - for (int i = 0; i < numEntries; i++) { - - try { - field = readField(); - } catch (ArrayIndexOutOfBoundsException ae) { - // if the data type is unknown we should skip this TIFF Field - continue; - } - addField(field); - } - } - - /** Returns the number of directory entries. */ - public int getNumEntries() { - return fieldIndex.size(); - } - - /** - * Returns the value of a given tag as a XTIFFField, or null if the tag is - * not present. - */ - public XTIFFField getField(int tag) { - return (XTIFFField) fieldIndex.get(new Integer(tag)); - } - - /** - * Returns true if a tag appears in the directory. - */ - public boolean isTagPresent(int tag) { - return fieldIndex.containsKey(new Integer(tag)); - } - - /** - * Returns an ordered array of ints indicating the tag values. - */ - public int[] getTags() { - int[] tags = new int[fieldIndex.size()]; - Iterator it = fieldIndex.keySet().iterator(); - int i = 0; - while (it.hasNext()) { - tags[i++] = ((Integer) it.next()).intValue(); - } - return tags; - } - - /** - * Returns an array of XTIFFFields containing all the fields in this - * directory. - */ - public XTIFFField[] getFields() { - XTIFFField[] fields = new XTIFFField[fieldIndex.size()]; - Iterator it = fieldIndex.values().iterator(); - int i = 0; - while (it.hasNext()) { - fields[i++] = (XTIFFField) it.next(); - } - return fields; - } - - /** - * Returns the value of a particular index of a given tag as a byte. The - * caller is responsible for ensuring that the tag is present and has type - * XTIFFField.TIFF_SBYTE, TIFF_BYTE, or TIFF_UNDEFINED. - */ - public byte getFieldAsByte(int tag, int index) { - return (getField(tag).getAsBytes())[index]; - } - - /** - * Returns the value of index 0 of a given tag as a byte. The caller is - * responsible for ensuring that the tag is present and has type - * XTIFFField.TIFF_SBYTE, TIFF_BYTE, or TIFF_UNDEFINED. - */ - public byte getFieldAsByte(int tag) { - return getFieldAsByte(tag, 0); - } - - /** - * Returns the value of a particular index of a given tag as a long. The - * caller is responsible for ensuring that the tag is present and has type - * TIFF_BYTE, TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, TIFF_SSHORT, TIFF_SLONG - * or TIFF_LONG. - */ - public long getFieldAsLong(int tag, int index) { - return getField(tag).getAsLong(index); - } - - /** - * Returns the value of index 0 of a given tag as a long. The caller is - * responsible for ensuring that the tag is present and has type TIFF_BYTE, - * TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, TIFF_SSHORT, TIFF_SLONG or - * TIFF_LONG. - */ - public long getFieldAsLong(int tag) { - return getFieldAsLong(tag, 0); - } - - /** - * Returns the value of a particular index of a given tag as a float. The - * caller is responsible for ensuring that the tag is present and has numeric - * type (all but TIFF_UNDEFINED and TIFF_ASCII). - */ - public float getFieldAsFloat(int tag, int index) { - return getField(tag).getAsFloat(index); - } - - /** - * Returns the value of index 0 of a given tag as a float. The caller is - * responsible for ensuring that the tag is present and has numeric type (all - * but TIFF_UNDEFINED and TIFF_ASCII). - */ - public float getFieldAsFloat(int tag) { - return getFieldAsFloat(tag, 0); - } - - /** - * Returns the value of a particular index of a given tag as a double. The - * caller is responsible for ensuring that the tag is present and has numeric - * type (all but TIFF_UNDEFINED and TIFF_ASCII). - */ - public double getFieldAsDouble(int tag, int index) { - return getField(tag).getAsDouble(index); - } - - /** - * Returns the value of index 0 of a given tag as a double. The caller is - * responsible for ensuring that the tag is present and has numeric type (all - * but TIFF_UNDEFINED and TIFF_ASCII). - */ - public double getFieldAsDouble(int tag) { - return getFieldAsDouble(tag, 0); - } - - /** - * TIFF field-value reader. Override if there are new field types. Also - * override sizeOfType() and, possibly the createField method of the factory, - * if the field needs new accessors. - */ - public Object readFieldValue(int tag, int type, int count) - throws IOException, ArrayIndexOutOfBoundsException { - int j; - Object obj = null; - - switch (type) { - case XTIFFField.TIFF_BYTE: - case XTIFFField.TIFF_SBYTE: - case XTIFFField.TIFF_UNDEFINED: - case XTIFFField.TIFF_ASCII: - byte[] bvalues = new byte[count]; - stream.readFully(bvalues, 0, count); - - if (type == XTIFFField.TIFF_ASCII) { - - // Can be multiple strings - int index = 0, prevIndex = 0; - Vector v = new Vector(); - - while (index < count) { - while ((index < count) && (bvalues[index++] != 0)) { - ; - } - // When we encountered zero, means one string has ended - v.add(new String(bvalues, prevIndex, (index - prevIndex))); - prevIndex = index; - } - - count = v.size(); - String strings[] = new String[count]; - for (int c = 0; c < count; c++) { - strings[c] = (String) v.elementAt(c); - } - - obj = strings; - } else { - obj = bvalues; - } - - break; - - case XTIFFField.TIFF_SHORT: - char[] cvalues = new char[count]; - for (j = 0; j < count; j++) { - cvalues[j] = (char) (readUnsignedShort(stream)); - } - obj = cvalues; - break; - - case XTIFFField.TIFF_LONG: - long[] lvalues = new long[count]; - for (j = 0; j < count; j++) { - lvalues[j] = readUnsignedInt(stream); - } - obj = lvalues; - break; - - case XTIFFField.TIFF_RATIONAL: - long[][] llvalues = new long[count][2]; - for (j = 0; j < count; j++) { - llvalues[j][0] = readUnsignedInt(stream); - llvalues[j][1] = readUnsignedInt(stream); - } - obj = llvalues; - break; - - case XTIFFField.TIFF_SSHORT: - short[] svalues = new short[count]; - for (j = 0; j < count; j++) { - svalues[j] = readShort(stream); - } - obj = svalues; - break; - - case XTIFFField.TIFF_SLONG: - int[] ivalues = new int[count]; - for (j = 0; j < count; j++) { - ivalues[j] = readInt(stream); - } - obj = ivalues; - break; - - case XTIFFField.TIFF_SRATIONAL: - int[][] iivalues = new int[count][2]; - for (j = 0; j < count; j++) { - iivalues[j][0] = readInt(stream); - iivalues[j][1] = readInt(stream); - } - obj = iivalues; - break; - - case XTIFFField.TIFF_FLOAT: - float[] fvalues = new float[count]; - for (j = 0; j < count; j++) { - fvalues[j] = readFloat(stream); - } - obj = fvalues; - break; - - case XTIFFField.TIFF_DOUBLE: - double[] dvalues = new double[count]; - for (j = 0; j < count; j++) { - dvalues[j] = readDouble(stream); - } - obj = dvalues; - break; - - default: - System.err.println(JaiI18N.getString("XTIFFDirectory0")); - break; - } - return obj; - } - - /** - * Method for reading a field from stream. Positions stream at the next field - * location. - */ - private XTIFFField readField() - throws IOException, ArrayIndexOutOfBoundsException { - // int j; - int tag = readUnsignedShort(stream); - int type = readUnsignedShort(stream); - int count = (int) readUnsignedInt(stream); - int value = 0; - - // The place to return to to read the next tag - long nextTagOffset = stream.getFilePointer() + 4; - - try { - // If the tag data can't fit in 4 bytes, the next 4 bytes - // contain the starting offset of the data - if (count * sizeOfType(type) > 4) { - value = (int) (readUnsignedInt(stream)); - stream.seek(value); - } - } catch (ArrayIndexOutOfBoundsException ae) { - System.err.println(tag + " " + JaiI18N.getString("XTIFFDirectory4")); - // if the data type is unknown we should skip this TIFF Field - stream.seek(nextTagOffset); - throw ae; - } - - Object obj = readFieldValue(tag, type, count); - - // Position stream at next field and return this one - stream.seek(nextTagOffset); - - return createField(tag, type, count, obj); - } - - // Methods to read primitive data types from the stream - - protected short readShort(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readShort(); - } else { - return stream.readShortLE(); - } - } - - protected int readUnsignedShort(SeekableStream stream) - throws IOException { - if (isBigEndian) { - int val = stream.readUnsignedShort(); - return val; - } else { - int val = stream.readUnsignedShortLE(); - return val; - } - } - - protected int readInt(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readInt(); - } else { - return stream.readIntLE(); - } - } - - protected long readUnsignedInt(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readUnsignedInt(); - } else { - return stream.readUnsignedIntLE(); - } - } - - protected long readLong(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readLong(); - } else { - return stream.readLongLE(); - } - } - - protected float readFloat(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readFloat(); - } else { - return stream.readFloatLE(); - } - } - - protected double readDouble(SeekableStream stream) - throws IOException { - if (isBigEndian) { - return stream.readDouble(); - } else { - return stream.readDoubleLE(); - } - } - - // Static methods used by the public static method below - - private static int readUnsignedShort(SeekableStream stream, boolean isBigEndian) - throws IOException { - if (isBigEndian) { - return stream.readUnsignedShort(); - } else { - return stream.readUnsignedShortLE(); - } - } - - private static long readUnsignedInt(SeekableStream stream, boolean isBigEndian) - throws IOException { - if (isBigEndian) { - return stream.readUnsignedInt(); - } else { - return stream.readUnsignedIntLE(); - } - } - - // Utilities - - /** - * Returns the number of image directories (subimages) stored in a given TIFF - * file, represented by a SeekableStream. - */ - public static int getNumDirectories(SeekableStream stream) - throws IOException { - long pointer = stream.getFilePointer(); // Save stream pointer - - stream.seek(0L); - int endian = stream.readUnsignedShort(); - if (!isValidEndianTag(endian)) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFDirectory1")); - } - boolean isBigEndian = (endian == 0x4d4d); - int magic = readUnsignedShort(stream, isBigEndian); - if (magic != 42) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFDirectory2")); - } - - stream.seek(4L); - long offset = readUnsignedInt(stream, isBigEndian); - - int numDirectories = 0; - while (offset != 0L) { - ++numDirectories; - - stream.seek(offset); - int entries = readUnsignedShort(stream, isBigEndian); - stream.skip(12 * entries); - offset = readUnsignedInt(stream, isBigEndian); - } - - stream.seek(pointer); // Reset stream pointer - return numDirectories; - } - - /** - * Returns a boolean indicating whether the byte order used in the the TIFF - * file is big-endian (i.e. whether the byte order is from the most - * significant to the least significant) - */ - public boolean isBigEndian() { - return isBigEndian; - } - - /** - * Specifies the type of compression to be used. The compression type - * specified will be honored only if it is compatible with the image being - * written out. - * - * @param compression The compression type. - */ - public void setCompression(int compression) { - // this.compression = compression; - // Check to see if compression supported - // Add Field - addField(XTIFF.TIFFTAG_COMPRESSION, XTIFFField.TIFF_SHORT, 1, new char[] { - (char) compression - }); - } - - /** - * Return the type of compression indicated in the TIFF fields, or - * XTIFF.COMPRESSION_NON if not specified. - */ - public int getCompression() { - if (getField(XTIFF.TIFFTAG_COMPRESSION) == null) - return XTIFF.COMPRESSION_NONE; - return (int) getFieldAsLong(XTIFF.TIFFTAG_COMPRESSION); - } - - /** - * If set, the data will be written out in tiled format, instead of in - * strips. - * - * @param isTiled Specifies whether the image data should be wriiten out in - * tiled format. - */ - public void setIsTiled(boolean isTiled) { - this._isTiled = isTiled; - } - - /** - * Constructs a tile codec for decoding data, using the compression defined - * in the current directory. - * - * @param param the encoding param - * @see XTIFFTileCodec - */ - public XTIFFTileCodec createTileCodec(XTIFFDecodeParam param) - throws IOException { - int compression = getCompression(); - XTIFFTileCodec codec = getTileCodec(compression); - if (codec == null) - throw new IOException("Compression type (" + compression + ") not supported"); - return codec.create(param); - } - - /** - * Constructs a tile codec for encoding data, using the compression defined - * in the current directory. - * - * @param param the encoding param - * @see XTIFFTileCodec - */ - public XTIFFTileCodec createTileCodec(XTIFFEncodeParam param) - throws IOException { - int compression = getCompression(); - XTIFFTileCodec codec = getTileCodec(compression); - if (codec == null) - throw new IOException("Compression type (" + compression + ") not supported"); - return codec.create(param); - } - - /** - * Set the XTIFFFactory, which is used to construct the XTIFFDirectory object - * assigned as a "tiff.directory" property in the resulting jai image. - * - * @param fact the factory to register. The factory is guaranteed to always - * be non-null; if a null is passed in then the default XTIFFFactory - * is used. a null object is passed in - * @see XTIFFFactory - */ - public static void setFactory(XTIFFFactory fact) { - if (fact == null) - factory = new XTIFFFactory(); - else - factory = fact; - } - - /** - * Constructs a XTIFFDirectory from a SeekableStream. The directory parameter - * specifies which directory to read from the linked list present in the - * stream; directory 0 is normally read but it is possible to store multiple - * images in a single TIFF file by maintaing multiple directories. - * - * @param stream a SeekableStream to read from. - * @param directory the index of the directory to read. - * @see XTIFFFactory - */ - public static XTIFFDirectory create(SeekableStream stream, int directory) - throws IOException { - return factory.createDirectory(stream, directory); - } - - /** - * Constructs a TIFFDirectory by reading a SeekableStream. The ifd_offset - * parameter specifies the stream offset from which to begin reading; this - * mechanism is sometimes used to store private IFDs within a TIFF file that - * are not part of the normal sequence of IFDs. Uses the XTIFFFactory to do - * this, so to extend the directory class, the factory method should be - * extended and registered instead of this one. - * - * @param stream a SeekableStream to read from. - * @param ifd_offset the long byte offset of the directory. - * @see XTIFFFactory - */ - public static XTIFFDirectory create(SeekableStream stream, long ifd_offset) - throws IOException { - return factory.createDirectory(stream, ifd_offset); - } - - /** - * Constructs an XTIFFDirectory from the currently. registered XTIFFDirectory - * factory. - * - * @see XTIFFFactory - */ - public static XTIFFDirectory create() { - return factory.createDirectory(); - } - - /** - * Return the currently registered XTIFFTileCodec for this compression type. - * Used by the XTIFFImage to decode the compression data. - * - * @see XTIFFTileCodec - */ - public static XTIFFTileCodec getTileCodec(int comp) { - return (XTIFFTileCodec) tileCodecs.get(new Integer(comp)); - } - - /** - * UnRegister the XTIFFTileCodec corresponding to the TIFF compression type. - * - * @param comp The TIFF compression code indicated - */ - public static void unRegisterTileCodec(int comp) { - XTIFFTileCodec cod = getTileCodec(comp); - tileCodecs.remove(cod); - } - - /** - * Register a new XTIFFTileCodec for encoding and decoding compressed TIFF - * image data. This overrides any existing codec previously registered. - * - * @param comp The TIFF compression code indicated by the - * @param codec The codec to register. XTIFF.TIFFTAG_COMPRESSION field. - * @see XTIFFTileCodec - */ - public static void registerTileCodec(int comp, XTIFFTileCodec codec) { - tileCodecs.put(new Integer(comp), codec); - } - - /** - * Get the JAI Image decoded type. This method is called by the - * XTIFFTileCodeImpl object during the decode() method to determine what type - * of colorspace and sample model to use. - */ - public int getImageType() { - return imageType; - } - - /** - * Set the JAI Image decoded type. This method is called by the XTIFFImage - * constructor to indicate to the XTIFFTileCodec what type of colorspace and - * sample model to use. The types are enumerated in the XTIFF class. - * - * @see XTIFF - * @see XTIFFImage - * @see XTIFFTileCodec - */ - public void setImageType(int image_type) { - imageType = image_type; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFEncodeParam.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFEncodeParam.java deleted file mode 100644 index 913d5339e..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFEncodeParam.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -/** - * An extension of TIFFEncodeParam for encoding images in - * the TIFF format using the XTIFF machinery. The encode object creates - * an empty XTIFFDirectory, which the user may may access and add - * whatever XTIFFFields they need for annotation, compression, etc. - * It shouldn't be necessary to extend this class further, as all - * parameters will be passed through the XTIFFDirectory. - */ - -import com.sun.media.jai.codec.TIFFEncodeParam; - -public class XTIFFEncodeParam extends TIFFEncodeParam { - - /* inherited: compression, tiled */ - private int _compression; - private boolean _isTiled; - - /** For XTIFF everything is stored in the directory */ - private XTIFFDirectory directory; - - /** - * Promotes an XTIFFEncodeParam object from simpler one - */ - public XTIFFEncodeParam(TIFFEncodeParam param) { - initialize(); - if (param == null) - return; - setCompression(param.getCompression()); - setWriteTiled(param.getWriteTiled()); - } - - /** - * Constructs an XTIFFEncodeParam object with default values for parameters. - */ - public XTIFFEncodeParam() { - initialize(); - } - - /** - * Initializes an XTIFFEncodeParam with default values for parameters. - */ - public void initialize() { - directory = XTIFFDirectory.create(); - setCompression(COMPRESSION_NONE); - setWriteTiled(false); - } - - public XTIFFDirectory getDirectory() { - return directory; - } - - /** - * Specifies the type of compression to be used. The compression type - * specified will be honored only if it is compatible with the image being - * written out. - * - * @param compression The compression type. - */ - public void setCompression(int compression) { - directory.setCompression(compression); - _compression = compression; - } - - /** - * Specifies the type of compression to be used. The compression type - * specified will be honored only if it is compatible with the image being - * written out. - * - */ - public int getCompression() { - return _compression; - } - - /** - * If set, the data is in tiled format, instead of in strips. - */ - public boolean getWriteTiled() { - return _isTiled; - } - - /** - * If set, the data will be written out in tiled format, instead of in - * strips. - * - * @param writeTiled Specifies whether the image data should be wriiten out - * in tiled format. - */ - public void setWriteTiled(boolean writeTiled) { - directory.setIsTiled(writeTiled); - _isTiled = writeTiled; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFFactory.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFFactory.java deleted file mode 100644 index fd31c30f6..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFFactory.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.io.IOException; - -import com.sun.media.jai.codec.SeekableStream; - -/** - * A class representing the factory for constructing a XTIFFDirectory, and the - * corresponding XTIFFFields. If you are creating extensions to those classes, - * extend this class as well. See the GeoTIFF package for an example of how to - * do this. - * - * @see org.libtiff.jai.TIFFDescriptor - * @see XTIFFField - * @see XTIFFDirectory - */ -public class XTIFFFactory extends Object implements java.io.Serializable { - /** - * Default constructor - */ - public XTIFFFactory() {} - - /** - * Constructs an XTIFFDirectoryFactory from a SeekableStream. The directory - * parameter specifies which directory to read from the linked list present - * in the stream; directory 0 is normally read but it is possible to store - * multiple images in a single TIFF file by maintaing multiple directories. - * - * @param stream a SeekableStream to read from. - * @param directory the index of the directory to read. - */ - public XTIFFDirectory createDirectory(SeekableStream stream, int directory) - throws IOException { - return new XTIFFDirectory(stream, directory); - } - - /** - * Constructs a XTIFFDirectory by reading a SeekableStream. The ifd_offset - * parameter specifies the stream offset from which to begin reading; this - * mechanism is sometimes used to store private IFDs within a TIFF file that - * are not part of the normal sequence of IFDs. - * - * @param stream a SeekableStream to read from. - * @param ifd_offset the long byte offset of the directory. - */ - public XTIFFDirectory createDirectory(SeekableStream stream, long ifd_offset) - throws IOException { - return new XTIFFDirectory(stream, ifd_offset); - } - - /** - * Constructs an empty XTIFFDirectory for encoding - */ - public XTIFFDirectory createDirectory() { - return new XTIFFDirectory(); - } - - /** - * Constructs an XTIFFField from values - * - * @param tag the TIFF tag listed in XTIFF - * @param type the TIFF field type listed in XTIFFField - * @param count the number of values in array obj - * @param obj the array of values - * @see XTIFFField - */ - public XTIFFField createField(int tag, int type, int count, Object obj) { - return new XTIFFField(tag, type, count, obj); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFField.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFField.java deleted file mode 100644 index ef3a032ce..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFField.java +++ /dev/null @@ -1,484 +0,0 @@ -package org.libtiff.jai.codec; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -/** - * XTIFFField is class representing a field in a TIFF 6.0 Image File Directory. - * Unlike the JAI TIFFField class, this one is serializable, - * assuming the underlying data object is. Revision: Fix getAsLongs to support - * arrays of Short. - * - * @see javax.media.jai.operator.TIFFDescriptor - * @see TIFFDirectory - */ - -public class XTIFFField extends Object implements java.io.Serializable, - Comparable { - - /** Flag for 8 bit unsigned integers. */ - public static final int TIFF_BYTE = 1; - - /** Flag for null-terminated ASCII strings. */ - public static final int TIFF_ASCII = 2; - - /** Flag for 16 bit unsigned integers. */ - public static final int TIFF_SHORT = 3; - - /** Flag for 32 bit unsigned integers. */ - public static final int TIFF_LONG = 4; - - /** Flag for pairs of 32 bit unsigned integers. */ - public static final int TIFF_RATIONAL = 5; - - /** Flag for 8 bit signed integers. */ - public static final int TIFF_SBYTE = 6; - - /** Flag for 8 bit uninterpreted bytes. */ - public static final int TIFF_UNDEFINED = 7; - - /** Flag for 16 bit signed integers. */ - public static final int TIFF_SSHORT = 8; - - /** Flag for 32 bit signed integers. */ - public static final int TIFF_SLONG = 9; - - /** Flag for pairs of 32 bit signed integers. */ - public static final int TIFF_SRATIONAL = 10; - - /** Flag for 32 bit IEEE floats. */ - public static final int TIFF_FLOAT = 11; - - /** Flag for 64 bit IEEE doubles. */ - public static final int TIFF_DOUBLE = 12; - - /** The tag number. */ - int tag = 0; - - /** The tag type. */ - int type; - - /** The number of data items present in the field. */ - int count; - - /** The field data. (NB must be serializble!) */ - Object data; - - /** The default constructor. Made public for Serialization */ - public XTIFFField() {} - - /** - * Constructs a XTIFFField with arbitrary data. The data parameter must be - * an array of a Java type appropriate for the type of the TIFF field. Since - * there is no available 32-bit unsigned datatype, long is used. The mapping - * between types is as follows: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TIFF type Java type
TIFF_BYTEbyte
TIFF_ASCIIString
TIFF_SHORTchar
TIFF_LONGlong
TIFF_RATIONALlong[2]
TIFF_SBYTEbyte
TIFF_UNDEFINEDbyte
TIFF_SSHORTshort
TIFF_SLONGint
TIFF_SRATIONALint[2]
TIFF_FLOATfloat
TIFF_DOUBLEdouble
- */ - public XTIFFField(int tag, int type, int count, Object data) { - this.tag = tag; - this.type = type; - this.count = count; - this.data = data; - } - - /** - * Returns the tag number, between 0 and 65535. - */ - public int getTag() { - return tag; - } - - /** - * Returns the type of the data stored in the IFD. For a TIFF6.0 file, the - * value will equal one of the TIFF_ constants defined in this class. For - * future revisions of TIFF, higher values are possible. - * - */ - public int getType() { - return type; - } - - /** - * Returns the number of elements in the IFD. (Image File Directory) - * - * @see XTIFFDirectory - */ - public int getCount() { - return count; - } - - /** - * Returns the data as an uninterpreted array of bytes. The type of the - * field must be one of TIFF_BYTE, TIFF_SBYTE, or TIFF_UNDEFINED; - * - *

- * For data in TIFF_BYTE format, the application must take care when - * promoting the data to longer integral types to avoid sign extension. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_BYTE, TIFF_SBYTE, or TIFF_UNDEFINED. - */ - public byte[] getAsBytes() { - return (byte[]) data; - } - - /** - * Returns the data as an array of Strings. The type of the field must be - * TIFF_ASCII. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_ASCII - */ - public String[] getAsStrings() { - return (String[]) data; - } - - /** - * Returns TIFF_SHORT data as an array of chars (unsigned 16-bit integers). - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_SHORT. - */ - public char[] getAsChars() { - return (char[]) data; - } - - /** - * Returns TIFF_SSHORT data as an array of shorts (signed 16-bit integers). - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_SSHORT. - */ - public short[] getAsShorts() { - return (short[]) data; - } - - /** - * Returns TIFF_SLONG data as an array of ints (signed 32-bit integers). - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_SLONG. - */ - public int[] getAsInts() { - return (int[]) data; - } - - /** - * Returns TIFF_LONG data as an array of longs (signed 64-bit integers). - * - *

- * A ClassCastException will be thrown if the field is not an array of type - * TIFF_LONG or TIFF_SHORT. - */ - public long[] getAsLongs() { - if (type == TIFF_SHORT) { - char[] vals = (char[]) data; - long[] newvals = new long[vals.length]; - for (int i = 0; i < vals.length; i++) - newvals[i] = vals[i] & 0xffff; - return newvals; - } else { - return (long[]) data; - } - } - - /** - * Returns TIFF_FLOAT data as an array of floats. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_FLOAT. - */ - public float[] getAsFloats() { - return (float[]) data; - } - - /** - * Returns TIFF_DOUBLE data as an array of doubles. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_DOUBLE. - */ - public double[] getAsDoubles() { - return (double[]) data; - } - - /** - * Returns TIFF_SRATIONAL data as an array of 2-element arrays of ints. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_SRATIONAL. - */ - public int[][] getAsSRationals() { - return (int[][]) data; - } - - /** - * Returns TIFF_RATIONAL data as an array of 2-element arrays of longs. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_RATTIONAL. - */ - public long[][] getAsRationals() { - return (long[][]) data; - } - - /** - * Returns data in TIFF_BYTE, TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, - * TIFF_SSHORT, or TIFF_SLONG format as an int. - * - *

- * TIFF_BYTE and TIFF_UNDEFINED data are treated as unsigned; that is, no - * sign extension will take place and the returned value will be in the - * range [0, 255]. TIFF_SBYTE data will be returned in the range [-128, - * 127]. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_BYTE, TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, TIFF_SSHORT, or - * TIFF_SLONG. - */ - public int getAsInt(int index) { - switch (type) { - case TIFF_BYTE: - case TIFF_UNDEFINED: - return ((byte[]) data)[index] & 0xff; - case TIFF_SBYTE: - return ((byte[]) data)[index]; - case TIFF_SHORT: - return ((char[]) data)[index] & 0xffff; - case TIFF_SSHORT: - return ((short[]) data)[index]; - case TIFF_SLONG: - return ((int[]) data)[index]; - default: - throw new ClassCastException(); - } - } - - /** - * Returns data in TIFF_BYTE, TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, - * TIFF_SSHORT, TIFF_SLONG, or TIFF_LONG format as a long. - * - *

- * TIFF_BYTE and TIFF_UNDEFINED data are treated as unsigned; that is, no - * sign extension will take place and the returned value will be in the - * range [0, 255]. TIFF_SBYTE data will be returned in the range [-128, - * 127]. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_BYTE, TIFF_SBYTE, TIFF_UNDEFINED, TIFF_SHORT, TIFF_SSHORT, - * TIFF_SLONG, or TIFF_LONG. - */ - public long getAsLong(int index) { - switch (type) { - case TIFF_BYTE: - case TIFF_UNDEFINED: - return ((byte[]) data)[index] & 0xff; - case TIFF_SBYTE: - return ((byte[]) data)[index]; - case TIFF_SHORT: - return ((char[]) data)[index] & 0xffff; - case TIFF_SSHORT: - return ((short[]) data)[index]; - case TIFF_SLONG: - return ((int[]) data)[index]; - case TIFF_LONG: - return ((long[]) data)[index]; - default: - throw new ClassCastException(); - } - } - - /** - * Returns data in any numerical format as a float. Data in TIFF_SRATIONAL - * or TIFF_RATIONAL format are evaluated by dividing the numerator into the - * denominator using double-precision arithmetic and then truncating to - * single precision. Data in TIFF_SLONG, TIFF_LONG, or TIFF_DOUBLE format - * may suffer from truncation. - * - *

- * A ClassCastException will be thrown if the field is of type - * TIFF_UNDEFINED or TIFF_ASCII. - */ - public float getAsFloat(int index) { - switch (type) { - case TIFF_BYTE: - return ((byte[]) data)[index] & 0xff; - case TIFF_SBYTE: - return ((byte[]) data)[index]; - case TIFF_SHORT: - return ((char[]) data)[index] & 0xffff; - case TIFF_SSHORT: - return ((short[]) data)[index]; - case TIFF_SLONG: - return ((int[]) data)[index]; - case TIFF_LONG: - return ((long[]) data)[index]; - case TIFF_FLOAT: - return ((float[]) data)[index]; - case TIFF_DOUBLE: - return (float) ((double[]) data)[index]; - case TIFF_SRATIONAL: - int[] ivalue = getAsSRational(index); - return (float) ((double) ivalue[0] / ivalue[1]); - case TIFF_RATIONAL: - long[] lvalue = getAsRational(index); - return (float) ((double) lvalue[0] / lvalue[1]); - default: - throw new ClassCastException(); - } - } - - /** - * Returns data in any numerical format as a float. Data in TIFF_SRATIONAL - * or TIFF_RATIONAL format are evaluated by dividing the numerator into the - * denominator using double-precision arithmetic. - * - *

- * A ClassCastException will be thrown if the field is of type - * TIFF_UNDEFINED or TIFF_ASCII. - */ - public double getAsDouble(int index) { - switch (type) { - case TIFF_BYTE: - return ((byte[]) data)[index] & 0xff; - case TIFF_SBYTE: - return ((byte[]) data)[index]; - case TIFF_SHORT: - return ((char[]) data)[index] & 0xffff; - case TIFF_SSHORT: - return ((short[]) data)[index]; - case TIFF_SLONG: - return ((int[]) data)[index]; - case TIFF_LONG: - return ((long[]) data)[index]; - case TIFF_FLOAT: - return ((float[]) data)[index]; - case TIFF_DOUBLE: - return ((double[]) data)[index]; - case TIFF_SRATIONAL: - int[] ivalue = getAsSRational(index); - return (double) ivalue[0] / ivalue[1]; - case TIFF_RATIONAL: - long[] lvalue = getAsRational(index); - return (double) lvalue[0] / lvalue[1]; - default: - throw new ClassCastException(); - } - } - - /** - * Returns a TIFF_ASCII data item as a String. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_ASCII. - */ - public String getAsString(int index) { - return ((String[]) data)[index]; - } - - /** - * Returns a TIFF_SRATIONAL data item as a two-element array of ints. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_SRATIONAL. - */ - public int[] getAsSRational(int index) { - return ((int[][]) data)[index]; - } - - /** - * Returns a TIFF_RATIONAL data item as a two-element array of ints. - * - *

- * A ClassCastException will be thrown if the field is not of type - * TIFF_RATIONAL. - */ - public long[] getAsRational(int index) { - return ((long[][]) data)[index]; - } - - /** - * For sorting, implement Comparable - */ - public int compareTo(Object o) throws ClassCastException { - if (!(o instanceof XTIFFField)) - throw new ClassCastException("comparator is not an XTIFFField"); - if (o == null) - throw new NullPointerException("comparator"); - return tag - ((XTIFFField) o).tag; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodec.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodec.java deleted file mode 100644 index 964e3ffae..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodec.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.libtiff.jai.codec; - -import java.awt.Rectangle; -import java.awt.image.RenderedImage; -import java.awt.image.WritableRaster; -import java.io.IOException; - -/** - * The XTIFFTileCodec is the common interface used by all registered - * implementations of TIFF data compression. Unlike other file formats, TIFF has - * no fixed set of data compressions schemes, but allows for new and - * user-defined compression types. - *

- * To use a new codec with the XTIFFDirectory you must do the following things: - *

    - *
  • register XTIFF methods with JAI through the XTIFFDescriptor - *
  • implement the methods below; it is recommended to use the - * XTIFFTileCodecImpl class for this purpose, as it reduces the problem to one - * of defining the actual data compression and decompression algorithms. If you - * do not support encoding (e.g LZW), be sure the canEncode() methods returns - * false. - *
  • register the implemented code with the XTIFFDirectory, indicating in the - * register method all TIFF compression codes that this codec can handle. - *
- * - * @see XTIFFTileCodecImpl - */ -public interface XTIFFTileCodec { - - /** - * Create a codec for encoding data. - * - * @param param the encoding parameter. It is the responsibility of the - * codec to initialize itself from this parameter. - */ - public XTIFFTileCodec create(XTIFFEncodeParam param) throws IOException; - - /** - * Create a codec for decoding - * - * @param param the decoding parameter. It is the responsibility of the - * codec to initialize itself from this parameter. - */ - public XTIFFTileCodec create(XTIFFDecodeParam param) throws IOException; - - /** - * Encode some data from RenderedImage, and return the actual number of - * bytes stored in output buffer. - */ - public int encode(RenderedImage im, Rectangle rect, byte[] output); - - /** - * Decode input byte data into a new WritableRaster, using information from - * underlying RenderedImage - */ - public WritableRaster decode(RenderedImage im, Rectangle rect, byte[] input); - - /** - * Return the associated TIFF compression code - */ - public int getCompression(); - - /** - * Return the largest possible compressed buffer size for this image in - * bytes. This is used by the XTIFFImage constructor to allocate a decoding - * buffer. - */ - public int getCompressedTileSize(RenderedImage im); - - /** - * Register this codec with the XTIFFDirectory. The method may register - * itself with multiple TIFF compression codes, if it supports more than - * one. - * - * @see XTIFFDirectory - */ - public void register(); -} diff --git a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodecImpl.java b/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodecImpl.java deleted file mode 100644 index 00d675a19..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codec/XTIFFTileCodecImpl.java +++ /dev/null @@ -1,761 +0,0 @@ -package org.libtiff.jai.codec; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.DataBufferShort; -import java.awt.image.DataBufferUShort; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; -import java.awt.image.renderable.ParameterBlock; -import java.io.IOException; - -import javax.media.jai.JAI; -import javax.media.jai.RasterFactory; - -import org.libtiff.jai.util.JaiI18N; - -/** - * Provides a base class for writing TIFF tile codecs, to be registered with the - * XTIFFDirectory. This codec allows for both decoding and (optionally) encoding - * of tiles, and also handles the colorspace conversion in decoding. - *

- * At the minimum you will need to implement the two methods decodeTilePixels() - * for byte and short data, as well as the methods register() and create(). If - * your decoder requires additional parameters from the tags, set them up in - * initializeDecoding(), and initializeEncoding() for encoding. - *

- * To implement encoding, you must override the canEncode() method to return - * true, and implement encodeTilePixels(). - * - * @author Niles Ritter - * @see XTIFFTileCodec - */ -public abstract class XTIFFTileCodecImpl implements XTIFFTileCodec { - - // //////////////////////////////////////////////////// - // // Implementation Section - // // Override or implement methods here - // //////////////////////////////////////////////////// - - /** - * Registration method. Must be implemented by the extended class to - * register itself with the XTIFFDirectory for all compression codes it - * supports (e.g Fax codec supports 3 codes). - * - * @see XTIFFDirectory - */ - public abstract void register(); - - /** - * Implement this to return the corresponding empty codec object. - */ - public abstract XTIFFTileCodec create(); - - /** - * Indicate whether this codec can encode data. Override to return true only - * if your codec implments encoding. - */ - public boolean canEncode() { - return false; - } - - /** - * The initialization method particular to decoding. Extend for whatever - * compression-specific information or parameters is needed. The decoding - * parameter has already been assigned at this point, as well as the - * XTIFFDirectory parsed from the input stream, and so all XTIFFFields are - * available. - */ - public void initializeDecoding() {} - - /** - * The initialization method particular to encoding. Extend for whatever - * compression-specific information or parameters is needed. The decoding - * parameter has already been assigned at this point, as well as the - * XTIFFDirectory parsed from the input stream, and so all XTIFFFields are - * available. - */ - public void initializeEncoding() {} - - /** - * decode bpixel byte array of data into pixels, packed for 1,2,4 8 bit - * pixels. Must implment this. - * - * @param bpixels the byte array of compressed input data - * @param rect the rectangular shape of the target pixels - * @param pixels the target decompressed pixels. - */ - public abstract void decodeTilePixels(byte[] bpixels, Rectangle rect, - byte[] pixels); - - /** - * decode bpixel byte array of data into pixels, packed for 16 bit pixels. - * Must implment this. - * - * @param bpixels the byte array of compressed input data - * @param rect the rectangular shape of the target pixels - * @param pixels the target decompressed pixels. - */ - public abstract void decodeTilePixels(byte[] bpixels, Rectangle rect, - short[] pixels); - - /** - * encode the tile in pixels into bpixels and return the byte size of the - * compressed data. Override this method if canEncode() = true; - * - * @param pixels input pixels - * @param rect the array dimensions of samples - * @param bpixels the target array of compressed byte data - */ - - public int encodeTilePixels(int[] pixels, Rectangle rect, byte[] bpixels) { - return 0; - } - - // //////////////////////////////////////////////////// - // // Common Section - // //////////////////////////////////////////////////// - - protected XTIFFDirectory directory = null; - protected RenderedImage image = null; - protected int minY; - protected int minX; - protected int width; - protected int length; - protected int numBands; - protected int tileLength; - protected int tileWidth; - protected int compression; - protected SampleModel sampleModel; - protected int[] sampleSize; - protected char[] bitsPerSample; - protected char[] colormap = null; - - /** - * The empty constructor. - */ - public XTIFFTileCodecImpl() {} - - /** - * The method for initializing information common to both encoder and - * decoder. - */ - public void initialize() { - width = (int) getLongField(XTIFF.TIFFTAG_IMAGE_WIDTH); - length = (int) getLongField(XTIFF.TIFFTAG_IMAGE_LENGTH); - isTiled = directory.isTiled(); - if (isTiled) { - tileWidth = (int) getLongField(XTIFF.TIFFTAG_TILE_WIDTH); - tileLength = (int) getLongField(XTIFF.TIFFTAG_TILE_LENGTH); - } else { - tileWidth = width; - tileLength = (int) getLongField(XTIFF.TIFFTAG_ROWS_PER_STRIP); - } - // Figure out what compression if any, is being used. - XTIFFField compField = directory.getField(XTIFF.TIFFTAG_COMPRESSION); - if (compField != null) { - compression = compField.getAsInt(0); - } else { - compression = XTIFF.COMPRESSION_NONE; - } - XTIFFField cfield = directory.getField(XTIFF.TIFFTAG_COLORMAP); - if (cfield != null) - colormap = cfield.getAsChars(); - - // Read the TIFFTAG_BITS_PER_SAMPLE field - XTIFFField bitsField = directory.getField(XTIFF.TIFFTAG_BITS_PER_SAMPLE); - - if (bitsField == null) { - // Default - bitsPerSample = new char[1]; - bitsPerSample[0] = 1; - } else { - bitsPerSample = bitsField.getAsChars(); - } - image_type = directory.getImageType(); - } - - /** - * A common utility method for accessing the XTIFFFields in the current - * image directory. - */ - protected long getLongField(int fld) { - XTIFFField field = directory.getField(fld); - if (field == null) - return 0; - else - return field.getAsLong(0); - } - - /** - * This method may be used by the implementations register() method to - * register itself with the XTIFFDirectory. - * - * @see XTIFFDirectory - */ - public void register(int comp) { - XTIFFDirectory.registerTileCodec(comp, this); - } - - /** - * One-time common image parameter setup - * - * @param img the source image that will be encoded into a TIFF formatted - * stream, or the TIFF image from which Raster tiles will be decoded. - */ - protected void setupSourceImage(RenderedImage img) { - image = img; - - // Get raster parameters - minY = image.getMinY(); - minX = image.getMinX(); - sampleModel = image.getSampleModel(); - numBands = sampleModel.getNumBands(); - sampleSize = sampleModel.getSampleSize(); - - } - - /** - * Returns the TIFF compression type - */ - public int getCompression() { - return compression; - } - - // //////////////////////////////////////////////////// - // // Encoding Section - // //////////////////////////////////////////////////// - - protected XTIFFEncodeParam encodeParam = null; - private int _pixels[]; - protected boolean isTiled; - - /** - * The method for creating an encoder from the XTIFFEncodeParam information. - */ - public XTIFFTileCodec create(XTIFFEncodeParam param) throws IOException { - XTIFFTileCodecImpl codec = (XTIFFTileCodecImpl) create(); - codec.initialize(param); - return codec; - } - - protected void initialize(XTIFFEncodeParam param) throws IOException { - if (!canEncode()) - throw new IOException("encoding not supported"); - encodeParam = param; - directory = param.getDirectory(); - initialize(); - initializeEncoding(); - } - - /** - * Encode the data into buffer and return byte count Normally you will not - * need to override this method, but instead implement the - * encodeTilePixels() method. - */ - public int encode(RenderedImage img, Rectangle rect, byte[] bpixels) { - if (image == null) { - setupSourceImage(img); - setupBufferForEncoding(); - } - - // Fill tile buffer, padding right with zeroes. - getTilePixels(rect); - - // encode and return number of bytes compressed - return encodeTilePixels(_pixels, rect, bpixels); - } - - /** - * One-time setup for encoding - */ - protected void setupBufferForEncoding() { - // Set up input tile/strip buffer - _pixels = new int[tileWidth * tileLength * numBands]; - - // if padding necessary do it now. - int padRight = (tileWidth - (width % tileWidth)) % tileWidth; - int padBottom = (tileLength - (length % tileLength)) % tileLength; - if (!isTiled) - padBottom = 0; - if (padRight > 0 || padBottom > 0) { - ParameterBlock pb = new ParameterBlock(); - pb.addSource(image); - pb.add(null) - .add(padRight) - .add(null) - .add(padBottom) - .add(null) - .add(null); - image = JAI.create("border", pb); - } - } - - /** - * Get the portion of tile fitting into buffer. You probably won't need to - * override this. - * - * @param rect the region to extract from image. - */ - - protected void getTilePixels(Rectangle rect) { - // Grab the pixels - Raster src = image.getData(rect); - int col = (int) rect.getX(); - int row = (int) rect.getY(); - int rows = (int) rect.getHeight(); - int cols = (int) rect.getWidth(); - src.getPixels(col, row, cols, rows, _pixels); - } - - /** - * If derived classes can make a better estimate for the maximum size of a - * compressed tile, they should override this, which assumes conservatively - * that it won't be worse than twice the original size. - * - * @param im the rendered image containing the image data - */ - public int getCompressedTileSize(RenderedImage im) { - sampleModel = im.getSampleModel(); - numBands = sampleModel.getNumBands(); - sampleSize = sampleModel.getSampleSize(); - return (int) Math.ceil(2 * tileWidth * tileLength * numBands - * (sampleSize[0] / 8.0)); - } - - // //////////////////////////////////////////////////// - // // Decoding Section - // //////////////////////////////////////////////////// - - protected XTIFFDecodeParam decodeParam = null; - protected boolean decodePaletteAsShorts = false; - protected int unitsInThisTile; - protected byte _bdata[] = null; - protected short _sdata[] = null; - protected byte[] bpixvals = null; - protected short[] spixvals = null; - protected DataBuffer buffer = null; - protected int dataType; - protected int image_type; - - /** - * The standard decoder creation method - */ - public XTIFFTileCodec create(XTIFFDecodeParam param) throws IOException { - XTIFFTileCodecImpl codec = (XTIFFTileCodecImpl) create(); - codec.initialize(param); - return codec; - } - - protected void initialize(XTIFFDecodeParam param) throws IOException { - decodeParam = param; - decodePaletteAsShorts = param.getDecodePaletteAsShorts(); - directory = param.getDirectory(); - initialize(); - initializeDecoding(); - } - - /** - * One-time setup for encoding. Some configurations require a temp array for - * unpacking 16-bit palette data. - */ - protected void setupBufferForDecoding() { - - // int length; - buffer = sampleModel.createDataBuffer(); - dataType = sampleModel.getDataType(); - - if (dataType == DataBuffer.TYPE_BYTE) { - _bdata = ((DataBufferByte) buffer).getData(); - bpixvals = _bdata; - } else if (dataType == DataBuffer.TYPE_USHORT) { - _sdata = ((DataBufferUShort) buffer).getData(); - if (!decodePaletteAsShorts) - spixvals = _sdata; - } else if (dataType == DataBuffer.TYPE_SHORT) { - _sdata = ((DataBufferShort) buffer).getData(); - if (!decodePaletteAsShorts) - spixvals = _sdata; - } - if (decodePaletteAsShorts) { - int len = _sdata.length; - if (bitsPerSample[0] == 16) - spixvals = new short[len]; - else - bpixvals = new byte[len]; - } - } - - /** - * Decode a rectangle of data stored in bpixels into a raster tile. Usually - * you will not need to override this, but instead implement the - * decodeTilePixels methods. - */ - public WritableRaster decode(RenderedImage img, Rectangle newRect, - byte[] bpixels) { - if (image == null) { - setupSourceImage(img); - } - - setupBufferForDecoding(); // set up every time - - unitsInThisTile = newRect.width * newRect.height * numBands; - - // uncompress data - decodeTilePixels(bpixels, newRect); - - // post-processing of color data - decodeColor(newRect); - - // put buffer into a tile - return setTilePixels(newRect); - } - - /** - * Postprocess the uncompressed color data into the appropriate display - * color model. This implementation Does a number of things: - *

    - *
  • For RGB color, reverse to BGR which apparently is faster for Java 2D - * display - *
  • For one-bit WHITE_IS_ZERO data, flip the values so that they will - * look correct - *
  • If the decodePaletteAsShorts flag is true then unpack the bits and - * apply the lookup table, as 16-bit lookup is not supported in JAI. - *
- * Override this if you have other color types. - * - * @see XTIFFDecodeParam - */ - protected void decodeColor(Rectangle newRect) { - switch (dataType) { - case DataBuffer.TYPE_BYTE: - decodeColor(bpixvals, _bdata, newRect); - break; - case DataBuffer.TYPE_SHORT: - case DataBuffer.TYPE_USHORT: - if (bpixvals != null) - decodeColor(bpixvals, _sdata, newRect); - else - decodeColor(spixvals, _sdata, newRect); - } - } - - /** - * Decode a tile of data into either byte or short pixel buffers. Override - * this if you have other buffer types (e.g. int) - */ - protected void decodeTilePixels(byte[] bpixels, Rectangle newRect) { - - // decodeTilePixels into the appropriate buffer - if (bpixvals != null) - decodeTilePixels(bpixels, newRect, bpixvals); - else - decodeTilePixels(bpixels, newRect, spixvals); - } - - /** - * Take the values from the buffer and store them in a WritableRaster - * object. - */ - protected WritableRaster setTilePixels(Rectangle rect) { - return (WritableRaster) RasterFactory.createWritableRaster(sampleModel, - buffer, - new Point((int) rect.getX(), (int) rect.getY())); - } - - /** - * A useful Method to interpret a byte array as shorts. Method depends on - * whether the bytes are stored in a big endian or little endian format. - */ - - protected void unpackShorts(byte byteArray[], short output[], int shortCount) { - - int j; - int firstByte, secondByte; - - if (directory.isBigEndian()) { - - for (int i = 0; i < shortCount; i++) { - j = 2 * i; - firstByte = byteArray[j] & 0xff; - secondByte = byteArray[j + 1] & 0xff; - output[i] = (short) ((firstByte << 8) + secondByte); - } - - } else { - - for (int i = 0; i < shortCount; i++) { - j = 2 * i; - firstByte = byteArray[j] & 0xff; - secondByte = byteArray[j + 1] & 0xff; - output[i] = (short) ((secondByte << 8) + firstByte); - } - } - } - - // //////////////////////////////////////////////////////////////////////// - // /// Color decoding section - // //////////////////////////////////////////////////////////////////////// - - /** - * Decode short pixel data, or interpret palette data as short from byte. - */ - protected void decodeColor(byte[] bpix, short[] sdata, Rectangle newRect) { - // short sswap; - - switch (image_type) { - case XTIFF.TYPE_PALETTE: - if (bitsPerSample[0] == 8) { - - // At this point the data is 1 banded and will - // become 3 banded only after we've done the palette - // lookup, since unitsInThisTile was calculated with - // 3 bands, we need to divide this by 3. - int unitsBeforeLookup = unitsInThisTile / 3; - - // Expand the palette image into an rgb image with ushort - // data type. - int cmapValue; - int count = 0, lookup, len = colormap.length / 3; - int len2 = len * 2; - for (int i = 0; i < unitsBeforeLookup; i++) { - // Get the index into the colormap - lookup = bpix[i] & 0xff; - // Get the blue value - cmapValue = colormap[lookup + len2]; - sdata[count++] = (short) (cmapValue & 0xffff); - // Get the green value - cmapValue = colormap[lookup + len]; - sdata[count++] = (short) (cmapValue & 0xffff); - // Get the red value - cmapValue = colormap[lookup]; - sdata[count++] = (short) (cmapValue & 0xffff); - } - - } else if (bitsPerSample[0] == 4) { - - int padding = newRect.width % 2; -// int bytesPostDecoding = ((newRect.width + 1) / 2) -// * newRect.height; - - int bytes = unitsInThisTile / 3; - - // Unpack the 2 pixels packed into each byte. - byte[] data = new byte[bytes]; - - int srcCount = 0, dstCount = 0; - for (int j = 0; j < newRect.height; j++) { - for (int i = 0; i < newRect.width / 2; i++) { - data[dstCount++] = (byte) ((bpix[srcCount] & 0xf0) >> 4); - data[dstCount++] = (byte) (bpix[srcCount++] & 0x0f); - } - - if (padding == 1) { - data[dstCount++] = (byte) ((bpix[srcCount++] & 0xf0) >> 4); - } - } - - int len = colormap.length / 3; - int len2 = len * 2; - int cmapValue, lookup; - int count = 0; - for (int i = 0; i < bytes; i++) { - lookup = data[i] & 0xff; - cmapValue = colormap[lookup + len2]; - sdata[count++] = (short) (cmapValue & 0xffff); - cmapValue = colormap[lookup + len]; - sdata[count++] = (short) (cmapValue & 0xffff); - cmapValue = colormap[lookup]; - sdata[count++] = (short) (cmapValue & 0xffff); - } - } else { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder7")); - } - break; - } - } - - /** - * Decode short color data, or interpret palette data as short. - */ - protected void decodeColor(short[] spix, short[] sdata, Rectangle newRect) { - short sswap; - - switch (image_type) { - case XTIFF.TYPE_GREYSCALE_WHITE_IS_ZERO: - case XTIFF.TYPE_GREYSCALE_BLACK_IS_ZERO: - // Since we are using a ComponentColorModel with this image, - // we need to change the WhiteIsZero data to BlackIsZero data - // so it will display properly. - if (image_type == XTIFF.TYPE_GREYSCALE_WHITE_IS_ZERO) { - - if (dataType == DataBuffer.TYPE_USHORT) { - - for (int l = 0; l < sdata.length; l++) { - sdata[l] = (short) (65535 - spix[l]); - } - - } else if (dataType == DataBuffer.TYPE_SHORT) { - - for (int l = 0; l < sdata.length; l++) { - sdata[l] = (short) (~spix[l]); - } - } - } - - break; - - case XTIFF.TYPE_RGB: - // Change to BGR order, as Java2D displays that faster - for (int i = 0; i < unitsInThisTile; i += 3) { - sswap = spix[i]; - sdata[i] = spix[i + 2]; - sdata[i + 2] = sswap; - } - break; - - case XTIFF.TYPE_ORGB: - case XTIFF.TYPE_ARGB_PRE: - case XTIFF.TYPE_ARGB: - // Change from RGBA to ABGR for Java2D's faster special cases - for (int i = 0; i < unitsInThisTile; i += 4) { - // Swap R and A - sswap = spix[i]; - sdata[i] = spix[i + 3]; - sdata[i + 3] = sswap; - - // Swap G and B - sswap = spix[i + 1]; - sdata[i + 1] = spix[i + 2]; - sdata[i + 2] = sswap; - } - break; - - case XTIFF.TYPE_RGB_EXTRA: - break; - - case XTIFF.TYPE_PALETTE: - if (decodePaletteAsShorts) { - - // At this point the data is 1 banded and will - // become 3 banded only after we've done the palette - // lookup, since unitsInThisTile was calculated with - // 3 bands, we need to divide this by 3. - int unitsBeforeLookup = unitsInThisTile / 3; - - // Since unitsBeforeLookup is the number of shorts, - // but we do our decompression in terms of bytes, we - // need to multiply it by 2 in order to figure out - // how many bytes we'll get after decompression. -// int entries = unitsBeforeLookup * 2; - - if (dataType == DataBuffer.TYPE_USHORT) { - - // Expand the palette image into an rgb image with ushort - // data type. - int cmapValue; - int count = 0, lookup, len = colormap.length / 3; - int len2 = len * 2; - for (int i = 0; i < unitsBeforeLookup; i++) { - // Get the index into the colormap - lookup = spix[i] & 0xffff; - // Get the blue value - cmapValue = colormap[lookup + len2]; - sdata[count++] = (short) (cmapValue & 0xffff); - // Get the green value - cmapValue = colormap[lookup + len]; - sdata[count++] = (short) (cmapValue & 0xffff); - // Get the red value - cmapValue = colormap[lookup]; - sdata[count++] = (short) (cmapValue & 0xffff); - } - - } else if (dataType == DataBuffer.TYPE_SHORT) { - - // Expand the palette image into an rgb image with - // short data type. - int cmapValue; - int count = 0, lookup, len = colormap.length / 3; - int len2 = len * 2; - for (int i = 0; i < unitsBeforeLookup; i++) { - // Get the index into the colormap - lookup = spix[i] & 0xffff; - // Get the blue value - cmapValue = colormap[lookup + len2]; - sdata[count++] = (short) cmapValue; - // Get the green value - cmapValue = colormap[lookup + len]; - sdata[count++] = (short) cmapValue; - // Get the red value - cmapValue = colormap[lookup]; - sdata[count++] = (short) cmapValue; - } - }// dataType - }// decodePaletteAsShorts - break; - - case XTIFF.TYPE_TRANS: - break; - } - } - - /** - * Decode byte color data - */ - protected void decodeColor(byte[] bpix, byte[] bdata, Rectangle newRect) { - byte bswap; - - switch (image_type) { - case XTIFF.TYPE_BILEVEL_WHITE_IS_ZERO: - case XTIFF.TYPE_BILEVEL_BLACK_IS_ZERO: - case XTIFF.TYPE_GREYSCALE_WHITE_IS_ZERO: - case XTIFF.TYPE_GREYSCALE_BLACK_IS_ZERO: - case XTIFF.TYPE_RGB_EXTRA: - case XTIFF.TYPE_TRANS: - // nothing - break; - - case XTIFF.TYPE_RGB: - if (bitsPerSample[0] == 8) { - - // Change to BGR order, as Java2D displays that faster - for (int i = 0; i < unitsInThisTile; i += 3) { - bswap = bpix[i]; - bdata[i] = bpix[i + 2]; - bdata[i + 2] = bswap; - } - - } - break; - - case XTIFF.TYPE_ORGB: - case XTIFF.TYPE_ARGB_PRE: - case XTIFF.TYPE_ARGB: - if (bitsPerSample[0] == 8) { - // Convert from RGBA to ABGR for Java2D - for (int i = 0; i < unitsInThisTile; i += 4) { - // Swap R and A - bswap = bpix[i]; - bdata[i] = bpix[i + 3]; - bdata[i + 3] = bswap; - - // Swap G and B - bswap = bpix[i + 1]; - bdata[i + 1] = bpix[i + 2]; - bdata[i + 2] = bswap; - } - } - break; - - case XTIFF.TYPE_PALETTE: - // - break; - - }// switch - }// decodeColor - -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFCodec.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFCodec.java deleted file mode 100644 index 0ecb553a3..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFCodec.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.libtiff.jai.codecimpl; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.awt.image.RenderedImage; -import java.io.OutputStream; - -import com.sun.media.jai.codec.ImageCodec; -import com.sun.media.jai.codec.ImageDecodeParam; -import com.sun.media.jai.codec.ImageDecoder; -import com.sun.media.jai.codec.ImageEncodeParam; -import com.sun.media.jai.codec.ImageEncoder; -import com.sun.media.jai.codec.SeekableStream; -import com.sun.media.jai.codec.TIFFDecodeParam; -import com.sun.media.jai.codec.TIFFEncodeParam; - -/** - * TIFFCodec is declared final so we can't extend it - */ -public class XTIFFCodec extends ImageCodec { - - public XTIFFCodec() {} - - static { - // All built-in codec support should be here - (new XTIFFUncompTileCodec()).register(); - (new XTIFFLZWTileCodec()).register(); - (new XTIFFPackTileCodec()).register(); - (new XTIFFFaxTileCodec()).register(); - } - - public String getFormatName() { - return "tiff"; - } - - public Class getEncodeParamClass() { - return TIFFEncodeParam.class; - } - - public Class getDecodeParamClass() { - return TIFFDecodeParam.class; - } - - public boolean canEncodeImage(RenderedImage im, ImageEncodeParam param) { - return true; - } - - protected ImageEncoder createImageEncoder(OutputStream dst, - ImageEncodeParam param) { - return new XTIFFImageEncoder(dst, param); - } - - protected ImageDecoder createImageDecoder(SeekableStream src, - ImageDecodeParam param) { - return new XTIFFImageDecoder(src, param); - } - - public int getNumHeaderBytes() { - return 4; - } - - public boolean isFormatRecognized(byte[] header) { - if ((header[0] == 0x49) && (header[1] == 0x49) && (header[2] == 0x2a) - && (header[3] == 0x00)) { - return true; - } - - if ((header[0] == 0x4d) && (header[1] == 0x4d) && (header[2] == 0x00) - && (header[3] == 0x2a)) { - return true; - } - - return false; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxDecoder.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxDecoder.java deleted file mode 100644 index db30da94b..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxDecoder.java +++ /dev/null @@ -1,1425 +0,0 @@ -package org.libtiff.jai.codecimpl; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import org.libtiff.jai.util.JaiI18N; - -// Expose the class (mistake in JAI?) - -public class XTIFFFaxDecoder { - - private int bitPointer, bytePointer; - private byte[] data; - private int w, h; - private int fillOrder; - - // Data structures needed to store changing elements for the previous - // and the current scanline - private int changingElemSize = 0; - private int prevChangingElems[]; - private int currChangingElems[]; - - // Element at which to start search in getNextChangingElement - private int lastChangingElement = 0; - - private int compression = 2; - - // Variables set by T4Options - private int uncompressedMode = 0; - private int fillBits = 0; - private int oneD; - - static int table1[] = { 0x00, // 0 bits are left in first byte - SHOULD - // NOT HAPPEN - 0x01, // 1 bits are left in first byte - 0x03, // 2 bits are left in first byte - 0x07, // 3 bits are left in first byte - 0x0f, // 4 bits are left in first byte - 0x1f, // 5 bits are left in first byte - 0x3f, // 6 bits are left in first byte - 0x7f, // 7 bits are left in first byte - 0xff // 8 bits are left in first byte - }; - - static int table2[] = { 0x00, // 0 - 0x80, // 1 - 0xc0, // 2 - 0xe0, // 3 - 0xf0, // 4 - 0xf8, // 5 - 0xfc, // 6 - 0xfe, // 7 - 0xff // 8 - }; - - // Table to be used when fillOrder = 2, for flipping bytes. - static byte flipTable[] = { 0, -128, 64, -64, 32, -96, 96, -32, 16, -112, - 80, -48, 48, -80, 112, -16, 8, -120, 72, -56, 40, -88, 104, -24, - 24, -104, 88, -40, 56, -72, 120, -8, 4, -124, 68, -60, 36, -92, - 100, -28, 20, -108, 84, -44, 52, -76, 116, -12, 12, -116, 76, -52, - 44, -84, 108, -20, 28, -100, 92, -36, 60, -68, 124, -4, 2, -126, - 66, -62, 34, -94, 98, -30, 18, -110, 82, -46, 50, -78, 114, -14, - 10, -118, 74, -54, 42, -86, 106, -22, 26, -102, 90, -38, 58, -70, - 122, -6, 6, -122, 70, -58, 38, -90, 102, -26, 22, -106, 86, -42, - 54, -74, 118, -10, 14, -114, 78, -50, 46, -82, 110, -18, 30, -98, - 94, -34, 62, -66, 126, -2, 1, -127, 65, -63, 33, -95, 97, -31, 17, - -111, 81, -47, 49, -79, 113, -15, 9, -119, 73, -55, 41, -87, 105, - -23, 25, -103, 89, -39, 57, -71, 121, -7, 5, -123, 69, -59, 37, - -91, 101, -27, 21, -107, 85, -43, 53, -75, 117, -11, 13, -115, 77, - -51, 45, -83, 109, -19, 29, -99, 93, -35, 61, -67, 125, -3, 3, - -125, 67, -61, 35, -93, 99, -29, 19, -109, 83, -45, 51, -77, 115, - -13, 11, -117, 75, -53, 43, -85, 107, -21, 27, -101, 91, -37, 59, - -69, 123, -5, 7, -121, 71, -57, 39, -89, 103, -25, 23, -105, 87, - -41, 55, -73, 119, -9, 15, -113, 79, -49, 47, -81, 111, -17, 31, - -97, 95, -33, 63, -65, 127, -1, }; - - // The main 10 bit white runs lookup table - static short white[] = { - // 0 - 7 - 6430, 6400, 6400, 6400, 3225, 3225, 3225, 3225, - // 8 - 15 - 944, 944, 944, 944, 976, 976, 976, 976, - // 16 - 23 - 1456, 1456, 1456, 1456, 1488, 1488, 1488, 1488, - // 24 - 31 - 718, 718, 718, 718, 718, 718, 718, 718, - // 32 - 39 - 750, 750, 750, 750, 750, 750, 750, 750, - // 40 - 47 - 1520, 1520, 1520, 1520, 1552, 1552, 1552, 1552, - // 48 - 55 - 428, 428, 428, 428, 428, 428, 428, 428, - // 56 - 63 - 428, 428, 428, 428, 428, 428, 428, 428, - // 64 - 71 - 654, 654, 654, 654, 654, 654, 654, 654, - // 72 - 79 - 1072, 1072, 1072, 1072, 1104, 1104, 1104, 1104, - // 80 - 87 - 1136, 1136, 1136, 1136, 1168, 1168, 1168, 1168, - // 88 - 95 - 1200, 1200, 1200, 1200, 1232, 1232, 1232, 1232, - // 96 - 103 - 622, 622, 622, 622, 622, 622, 622, 622, - // 104 - 111 - 1008, 1008, 1008, 1008, 1040, 1040, 1040, 1040, - // 112 - 119 - 44, 44, 44, 44, 44, 44, 44, 44, - // 120 - 127 - 44, 44, 44, 44, 44, 44, 44, 44, - // 128 - 135 - 396, 396, 396, 396, 396, 396, 396, 396, - // 136 - 143 - 396, 396, 396, 396, 396, 396, 396, 396, - // 144 - 151 - 1712, 1712, 1712, 1712, 1744, 1744, 1744, 1744, - // 152 - 159 - 846, 846, 846, 846, 846, 846, 846, 846, - // 160 - 167 - 1264, 1264, 1264, 1264, 1296, 1296, 1296, 1296, - // 168 - 175 - 1328, 1328, 1328, 1328, 1360, 1360, 1360, 1360, - // 176 - 183 - 1392, 1392, 1392, 1392, 1424, 1424, 1424, 1424, - // 184 - 191 - 686, 686, 686, 686, 686, 686, 686, 686, - // 192 - 199 - 910, 910, 910, 910, 910, 910, 910, 910, - // 200 - 207 - 1968, 1968, 1968, 1968, 2000, 2000, 2000, 2000, - // 208 - 215 - 2032, 2032, 2032, 2032, 16, 16, 16, 16, - // 216 - 223 - 10257, 10257, 10257, 10257, 12305, 12305, 12305, 12305, - // 224 - 231 - 330, 330, 330, 330, 330, 330, 330, 330, - // 232 - 239 - 330, 330, 330, 330, 330, 330, 330, 330, - // 240 - 247 - 330, 330, 330, 330, 330, 330, 330, 330, - // 248 - 255 - 330, 330, 330, 330, 330, 330, 330, 330, - // 256 - 263 - 362, 362, 362, 362, 362, 362, 362, 362, - // 264 - 271 - 362, 362, 362, 362, 362, 362, 362, 362, - // 272 - 279 - 362, 362, 362, 362, 362, 362, 362, 362, - // 280 - 287 - 362, 362, 362, 362, 362, 362, 362, 362, - // 288 - 295 - 878, 878, 878, 878, 878, 878, 878, 878, - // 296 - 303 - 1904, 1904, 1904, 1904, 1936, 1936, 1936, 1936, - // 304 - 311 - -18413, -18413, -16365, -16365, -14317, -14317, -10221, -10221, - // 312 - 319 - 590, 590, 590, 590, 590, 590, 590, 590, - // 320 - 327 - 782, 782, 782, 782, 782, 782, 782, 782, - // 328 - 335 - 1584, 1584, 1584, 1584, 1616, 1616, 1616, 1616, - // 336 - 343 - 1648, 1648, 1648, 1648, 1680, 1680, 1680, 1680, - // 344 - 351 - 814, 814, 814, 814, 814, 814, 814, 814, - // 352 - 359 - 1776, 1776, 1776, 1776, 1808, 1808, 1808, 1808, - // 360 - 367 - 1840, 1840, 1840, 1840, 1872, 1872, 1872, 1872, - // 368 - 375 - 6157, 6157, 6157, 6157, 6157, 6157, 6157, 6157, - // 376 - 383 - 6157, 6157, 6157, 6157, 6157, 6157, 6157, 6157, - // 384 - 391 - -12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275, - // 392 - 399 - -12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275, - // 400 - 407 - 14353, 14353, 14353, 14353, 16401, 16401, 16401, 16401, - // 408 - 415 - 22547, 22547, 24595, 24595, 20497, 20497, 20497, 20497, - // 416 - 423 - 18449, 18449, 18449, 18449, 26643, 26643, 28691, 28691, - // 424 - 431 - 30739, 30739, -32749, -32749, -30701, -30701, -28653, -28653, - // 432 - 439 - -26605, -26605, -24557, -24557, -22509, -22509, -20461, -20461, - // 440 - 447 - 8207, 8207, 8207, 8207, 8207, 8207, 8207, 8207, - // 448 - 455 - 72, 72, 72, 72, 72, 72, 72, 72, - // 456 - 463 - 72, 72, 72, 72, 72, 72, 72, 72, - // 464 - 471 - 72, 72, 72, 72, 72, 72, 72, 72, - // 472 - 479 - 72, 72, 72, 72, 72, 72, 72, 72, - // 480 - 487 - 72, 72, 72, 72, 72, 72, 72, 72, - // 488 - 495 - 72, 72, 72, 72, 72, 72, 72, 72, - // 496 - 503 - 72, 72, 72, 72, 72, 72, 72, 72, - // 504 - 511 - 72, 72, 72, 72, 72, 72, 72, 72, - // 512 - 519 - 104, 104, 104, 104, 104, 104, 104, 104, - // 520 - 527 - 104, 104, 104, 104, 104, 104, 104, 104, - // 528 - 535 - 104, 104, 104, 104, 104, 104, 104, 104, - // 536 - 543 - 104, 104, 104, 104, 104, 104, 104, 104, - // 544 - 551 - 104, 104, 104, 104, 104, 104, 104, 104, - // 552 - 559 - 104, 104, 104, 104, 104, 104, 104, 104, - // 560 - 567 - 104, 104, 104, 104, 104, 104, 104, 104, - // 568 - 575 - 104, 104, 104, 104, 104, 104, 104, 104, - // 576 - 583 - 4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107, - // 584 - 591 - 4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107, - // 592 - 599 - 4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107, - // 600 - 607 - 4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107, - // 608 - 615 - 266, 266, 266, 266, 266, 266, 266, 266, - // 616 - 623 - 266, 266, 266, 266, 266, 266, 266, 266, - // 624 - 631 - 266, 266, 266, 266, 266, 266, 266, 266, - // 632 - 639 - 266, 266, 266, 266, 266, 266, 266, 266, - // 640 - 647 - 298, 298, 298, 298, 298, 298, 298, 298, - // 648 - 655 - 298, 298, 298, 298, 298, 298, 298, 298, - // 656 - 663 - 298, 298, 298, 298, 298, 298, 298, 298, - // 664 - 671 - 298, 298, 298, 298, 298, 298, 298, 298, - // 672 - 679 - 524, 524, 524, 524, 524, 524, 524, 524, - // 680 - 687 - 524, 524, 524, 524, 524, 524, 524, 524, - // 688 - 695 - 556, 556, 556, 556, 556, 556, 556, 556, - // 696 - 703 - 556, 556, 556, 556, 556, 556, 556, 556, - // 704 - 711 - 136, 136, 136, 136, 136, 136, 136, 136, - // 712 - 719 - 136, 136, 136, 136, 136, 136, 136, 136, - // 720 - 727 - 136, 136, 136, 136, 136, 136, 136, 136, - // 728 - 735 - 136, 136, 136, 136, 136, 136, 136, 136, - // 736 - 743 - 136, 136, 136, 136, 136, 136, 136, 136, - // 744 - 751 - 136, 136, 136, 136, 136, 136, 136, 136, - // 752 - 759 - 136, 136, 136, 136, 136, 136, 136, 136, - // 760 - 767 - 136, 136, 136, 136, 136, 136, 136, 136, - // 768 - 775 - 168, 168, 168, 168, 168, 168, 168, 168, - // 776 - 783 - 168, 168, 168, 168, 168, 168, 168, 168, - // 784 - 791 - 168, 168, 168, 168, 168, 168, 168, 168, - // 792 - 799 - 168, 168, 168, 168, 168, 168, 168, 168, - // 800 - 807 - 168, 168, 168, 168, 168, 168, 168, 168, - // 808 - 815 - 168, 168, 168, 168, 168, 168, 168, 168, - // 816 - 823 - 168, 168, 168, 168, 168, 168, 168, 168, - // 824 - 831 - 168, 168, 168, 168, 168, 168, 168, 168, - // 832 - 839 - 460, 460, 460, 460, 460, 460, 460, 460, - // 840 - 847 - 460, 460, 460, 460, 460, 460, 460, 460, - // 848 - 855 - 492, 492, 492, 492, 492, 492, 492, 492, - // 856 - 863 - 492, 492, 492, 492, 492, 492, 492, 492, - // 864 - 871 - 2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059, - // 872 - 879 - 2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059, - // 880 - 887 - 2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059, - // 888 - 895 - 2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059, - // 896 - 903 - 200, 200, 200, 200, 200, 200, 200, 200, - // 904 - 911 - 200, 200, 200, 200, 200, 200, 200, 200, - // 912 - 919 - 200, 200, 200, 200, 200, 200, 200, 200, - // 920 - 927 - 200, 200, 200, 200, 200, 200, 200, 200, - // 928 - 935 - 200, 200, 200, 200, 200, 200, 200, 200, - // 936 - 943 - 200, 200, 200, 200, 200, 200, 200, 200, - // 944 - 951 - 200, 200, 200, 200, 200, 200, 200, 200, - // 952 - 959 - 200, 200, 200, 200, 200, 200, 200, 200, - // 960 - 967 - 232, 232, 232, 232, 232, 232, 232, 232, - // 968 - 975 - 232, 232, 232, 232, 232, 232, 232, 232, - // 976 - 983 - 232, 232, 232, 232, 232, 232, 232, 232, - // 984 - 991 - 232, 232, 232, 232, 232, 232, 232, 232, - // 992 - 999 - 232, 232, 232, 232, 232, 232, 232, 232, - // 1000 - 1007 - 232, 232, 232, 232, 232, 232, 232, 232, - // 1008 - 1015 - 232, 232, 232, 232, 232, 232, 232, 232, - // 1016 - 1023 - 232, 232, 232, 232, 232, 232, 232, 232, }; - - // Additional make up codes for both White and Black runs - static short additionalMakeup[] = { 28679, 28679, 31752, (short) 32777, - (short) 33801, (short) 34825, (short) 35849, (short) 36873, - (short) 29703, (short) 29703, (short) 30727, (short) 30727, - (short) 37897, (short) 38921, (short) 39945, (short) 40969 }; - - // Initial black run look up table, uses the first 4 bits of a code - static short initBlack[] = { - // 0 - 7 - 3226, 6412, 200, 168, 38, 38, 134, 134, - // 8 - 15 - 100, 100, 100, 100, 68, 68, 68, 68 }; - - // - static short twoBitBlack[] = { 292, 260, 226, 226 }; // 0 - 3 - - // Main black run table, using the last 9 bits of possible 13 bit code - static short black[] = { - // 0 - 7 - 62, 62, 30, 30, 0, 0, 0, 0, - // 8 - 15 - 0, 0, 0, 0, 0, 0, 0, 0, - // 16 - 23 - 0, 0, 0, 0, 0, 0, 0, 0, - // 24 - 31 - 0, 0, 0, 0, 0, 0, 0, 0, - // 32 - 39 - 3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225, - // 40 - 47 - 3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225, - // 48 - 55 - 3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225, - // 56 - 63 - 3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225, - // 64 - 71 - 588, 588, 588, 588, 588, 588, 588, 588, - // 72 - 79 - 1680, 1680, 20499, 22547, 24595, 26643, 1776, 1776, - // 80 - 87 - 1808, 1808, -24557, -22509, -20461, -18413, 1904, 1904, - // 88 - 95 - 1936, 1936, -16365, -14317, 782, 782, 782, 782, - // 96 - 103 - 814, 814, 814, 814, -12269, -10221, 10257, 10257, - // 104 - 111 - 12305, 12305, 14353, 14353, 16403, 18451, 1712, 1712, - // 112 - 119 - 1744, 1744, 28691, 30739, -32749, -30701, -28653, -26605, - // 120 - 127 - 2061, 2061, 2061, 2061, 2061, 2061, 2061, 2061, - // 128 - 135 - 424, 424, 424, 424, 424, 424, 424, 424, - // 136 - 143 - 424, 424, 424, 424, 424, 424, 424, 424, - // 144 - 151 - 424, 424, 424, 424, 424, 424, 424, 424, - // 152 - 159 - 424, 424, 424, 424, 424, 424, 424, 424, - // 160 - 167 - 750, 750, 750, 750, 1616, 1616, 1648, 1648, - // 168 - 175 - 1424, 1424, 1456, 1456, 1488, 1488, 1520, 1520, - // 176 - 183 - 1840, 1840, 1872, 1872, 1968, 1968, 8209, 8209, - // 184 - 191 - 524, 524, 524, 524, 524, 524, 524, 524, - // 192 - 199 - 556, 556, 556, 556, 556, 556, 556, 556, - // 200 - 207 - 1552, 1552, 1584, 1584, 2000, 2000, 2032, 2032, - // 208 - 215 - 976, 976, 1008, 1008, 1040, 1040, 1072, 1072, - // 216 - 223 - 1296, 1296, 1328, 1328, 718, 718, 718, 718, - // 224 - 231 - 456, 456, 456, 456, 456, 456, 456, 456, - // 232 - 239 - 456, 456, 456, 456, 456, 456, 456, 456, - // 240 - 247 - 456, 456, 456, 456, 456, 456, 456, 456, - // 248 - 255 - 456, 456, 456, 456, 456, 456, 456, 456, - // 256 - 263 - 326, 326, 326, 326, 326, 326, 326, 326, - // 264 - 271 - 326, 326, 326, 326, 326, 326, 326, 326, - // 272 - 279 - 326, 326, 326, 326, 326, 326, 326, 326, - // 280 - 287 - 326, 326, 326, 326, 326, 326, 326, 326, - // 288 - 295 - 326, 326, 326, 326, 326, 326, 326, 326, - // 296 - 303 - 326, 326, 326, 326, 326, 326, 326, 326, - // 304 - 311 - 326, 326, 326, 326, 326, 326, 326, 326, - // 312 - 319 - 326, 326, 326, 326, 326, 326, 326, 326, - // 320 - 327 - 358, 358, 358, 358, 358, 358, 358, 358, - // 328 - 335 - 358, 358, 358, 358, 358, 358, 358, 358, - // 336 - 343 - 358, 358, 358, 358, 358, 358, 358, 358, - // 344 - 351 - 358, 358, 358, 358, 358, 358, 358, 358, - // 352 - 359 - 358, 358, 358, 358, 358, 358, 358, 358, - // 360 - 367 - 358, 358, 358, 358, 358, 358, 358, 358, - // 368 - 375 - 358, 358, 358, 358, 358, 358, 358, 358, - // 376 - 383 - 358, 358, 358, 358, 358, 358, 358, 358, - // 384 - 391 - 490, 490, 490, 490, 490, 490, 490, 490, - // 392 - 399 - 490, 490, 490, 490, 490, 490, 490, 490, - // 400 - 407 - 4113, 4113, 6161, 6161, 848, 848, 880, 880, - // 408 - 415 - 912, 912, 944, 944, 622, 622, 622, 622, - // 416 - 423 - 654, 654, 654, 654, 1104, 1104, 1136, 1136, - // 424 - 431 - 1168, 1168, 1200, 1200, 1232, 1232, 1264, 1264, - // 432 - 439 - 686, 686, 686, 686, 1360, 1360, 1392, 1392, - // 440 - 447 - 12, 12, 12, 12, 12, 12, 12, 12, - // 448 - 455 - 390, 390, 390, 390, 390, 390, 390, 390, - // 456 - 463 - 390, 390, 390, 390, 390, 390, 390, 390, - // 464 - 471 - 390, 390, 390, 390, 390, 390, 390, 390, - // 472 - 479 - 390, 390, 390, 390, 390, 390, 390, 390, - // 480 - 487 - 390, 390, 390, 390, 390, 390, 390, 390, - // 488 - 495 - 390, 390, 390, 390, 390, 390, 390, 390, - // 496 - 503 - 390, 390, 390, 390, 390, 390, 390, 390, - // 504 - 511 - 390, 390, 390, 390, 390, 390, 390, 390, }; - - static byte twoDCodes[] = { - // 0 - 7 - 80, 88, 23, 71, 30, 30, 62, 62, - // 8 - 15 - 4, 4, 4, 4, 4, 4, 4, 4, - // 16 - 23 - 11, 11, 11, 11, 11, 11, 11, 11, - // 24 - 31 - 11, 11, 11, 11, 11, 11, 11, 11, - // 32 - 39 - 35, 35, 35, 35, 35, 35, 35, 35, - // 40 - 47 - 35, 35, 35, 35, 35, 35, 35, 35, - // 48 - 55 - 51, 51, 51, 51, 51, 51, 51, 51, - // 56 - 63 - 51, 51, 51, 51, 51, 51, 51, 51, - // 64 - 71 - 41, 41, 41, 41, 41, 41, 41, 41, - // 72 - 79 - 41, 41, 41, 41, 41, 41, 41, 41, - // 80 - 87 - 41, 41, 41, 41, 41, 41, 41, 41, - // 88 - 95 - 41, 41, 41, 41, 41, 41, 41, 41, - // 96 - 103 - 41, 41, 41, 41, 41, 41, 41, 41, - // 104 - 111 - 41, 41, 41, 41, 41, 41, 41, 41, - // 112 - 119 - 41, 41, 41, 41, 41, 41, 41, 41, - // 120 - 127 - 41, 41, 41, 41, 41, 41, 41, 41, }; - - /** - * @param fillOrder The fill order of the compressed data bytes. - * @param compData Array containing compressed data. - * @param w - * @param h - */ - public XTIFFFaxDecoder(int fillOrder, int w, int h) { - this.fillOrder = fillOrder; - this.w = w; - this.h = h; - - this.bitPointer = 0; - this.bytePointer = 0; - this.prevChangingElems = new int[w]; - this.currChangingElems = new int[w]; - } - - // One-dimensional decoding methods - - public void decode1D(byte[] buffer, byte[] compData, int startX, int height) { - this.data = compData; - - int lineOffset = 0; - int scanlineStride = (w + 7) / 8; - - bitPointer = 0; - bytePointer = 0; - - for (int i = 0; i < height; i++) { - decodeNextScanline(buffer, lineOffset, startX); - lineOffset += scanlineStride; - } - } - - public void decodeNextScanline(byte[] buffer, int lineOffset, int bitOffset) { - int bits = 0, code = 0, isT = 0; - int current, entry, twoBits; - boolean isWhite = true; - int dstEnd = 0; - - // Initialize starting of the changing elements array - changingElemSize = 0; - - // While scanline not complete - while (bitOffset < w) { - while (isWhite) { - // White run - current = nextNBits(10); - entry = white[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x0f; - - if (bits == 12) { // Additional Make up code - // Get the next 2 bits - twoBits = nextLesserThan8Bits(2); - // Consolidate the 2 new bits and last 2 bits into 4 bits - current = ((current << 2) & 0x000c) | twoBits; - entry = additionalMakeup[current]; - bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 - code = (entry >>> 4) & 0x0fff; // 12 bits - bitOffset += code; // Skip white run - - updatePointer(4 - bits); - } else if (bits == 0) { // ERROR - throw new Error(JaiI18N.getString("XTIFFFaxDecoder0")); - } else if (bits == 15) { // EOL - throw new Error(JaiI18N.getString("XTIFFFaxDecoder1")); - } else { - // 11 bits - 0000 0111 1111 1111 = 0x07ff - code = (entry >>> 5) & 0x07ff; - bitOffset += code; - - updatePointer(10 - bits); - if (isT == 0) { - isWhite = false; - currChangingElems[changingElemSize++] = bitOffset; - } - } - } - - // Check whether this run completed one width, if so - // advance to next byte boundary for compression = 2. - if (bitOffset == w) { - if (compression == 2) { - advancePointer(); - } - break; - } - - while (isWhite == false) { - // Black run - current = nextLesserThan8Bits(4); - entry = initBlack[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x000f; - code = (entry >>> 5) & 0x07ff; - - if (code == 100) { - current = nextNBits(9); - entry = black[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x000f; - code = (entry >>> 5) & 0x07ff; - - if (bits == 12) { - // Additional makeup codes - updatePointer(5); - current = nextLesserThan8Bits(4); - entry = additionalMakeup[current]; - bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 - code = (entry >>> 4) & 0x0fff; // 12 bits - - setToBlack(buffer, lineOffset, bitOffset, code); - bitOffset += code; - - updatePointer(4 - bits); - } else if (bits == 15) { - // EOL code - throw new Error(JaiI18N.getString("XTIFFFaxDecoder2")); - } else { - setToBlack(buffer, lineOffset, bitOffset, code); - bitOffset += code; - - updatePointer(9 - bits); - if (isT == 0) { - isWhite = true; - currChangingElems[changingElemSize++] = bitOffset; - } - } - } else if (code == 200) { - // Is a Terminating code - current = nextLesserThan8Bits(2); - entry = twoBitBlack[current]; - code = (entry >>> 5) & 0x07ff; - bits = (entry >>> 1) & 0x0f; - - setToBlack(buffer, lineOffset, bitOffset, code); - bitOffset += code; - - updatePointer(2 - bits); - isWhite = true; - currChangingElems[changingElemSize++] = bitOffset; - } else { - // Is a Terminating code - setToBlack(buffer, lineOffset, bitOffset, code); - bitOffset += code; - - updatePointer(4 - bits); - isWhite = true; - currChangingElems[changingElemSize++] = bitOffset; - } - } - - // Check whether this run completed one width - if (bitOffset == w) { - if (compression == 2) { - advancePointer(); - } - break; - } - } - - currChangingElems[changingElemSize++] = bitOffset; - } - - // Two-dimensional decoding methods - - public void decode2D(byte[] buffer, byte compData[], int startX, - int height, long tiffT4Options) { - this.data = compData; - compression = 3; - - bitPointer = 0; - bytePointer = 0; - - int scanlineStride = (w + 7) / 8; - - int a0, a1, b1, b2; - int[] b = new int[2]; - int entry, code, bits, color; - boolean isWhite; - int currIndex = 0; - int temp[]; - - // fillBits - dealt with this in readEOL - // 1D/2D encoding - dealt with this in readEOL - - // uncompressedMode - haven't dealt with this yet. - // TODO: Deal with uncompressedMode, aastha 03/03/1999 - - oneD = (int) (tiffT4Options & 0x01); - uncompressedMode = (int) ((tiffT4Options & 0x02) >> 1); - fillBits = (int) ((tiffT4Options & 0x04) >> 2); - - // The data must start with an EOL code - if (readEOL() != 1) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder3")); - } - - int lineOffset = 0; - int bitOffset; - - // Then the 1D encoded scanline data will occur, changing elements - // array gets set. - decodeNextScanline(buffer, lineOffset, startX); - lineOffset += scanlineStride; - - for (int lines = 1; lines < height; lines++) { - - // Every line must begin with an EOL followed by a bit which - // indicates whether the following scanline is 1D or 2D encoded. - if (readEOL() == 0) { - // 2D encoded scanline follows - - // Initialize previous scanlines changing elements, and - // initialize current scanline's changing elements array - temp = prevChangingElems; - prevChangingElems = currChangingElems; - currChangingElems = temp; - currIndex = 0; - - // a0 has to be set just before the start of this scanline. - a0 = -1; - isWhite = true; - bitOffset = startX; - - lastChangingElement = 0; - - while (bitOffset < w) { - // Get the next changing element - getNextChangingElement(a0, isWhite, b); - - b1 = b[0]; - b2 = b[1]; - - // Get the next seven bits - entry = nextLesserThan8Bits(7); - - // Run these through the 2DCodes table - entry = (int) (twoDCodes[entry] & 0xff); - - // Get the code and the number of bits used up - code = (entry & 0x78) >>> 3; - bits = entry & 0x07; - - if (code == 0) { - if (!isWhite) { - setToBlack(buffer, lineOffset, bitOffset, b2 - - bitOffset); - } - bitOffset = a0 = b2; - - // Set pointer to consume the correct number of bits. - updatePointer(7 - bits); - } else if (code == 1) { - // Horizontal - updatePointer(7 - bits); - - // identify the next 2 codes. - int number; - if (isWhite) { - number = decodeWhiteCodeWord(); - bitOffset += number; - currChangingElems[currIndex++] = bitOffset; - - number = decodeBlackCodeWord(); - setToBlack(buffer, lineOffset, bitOffset, number); - bitOffset += number; - currChangingElems[currIndex++] = bitOffset; - } else { - number = decodeBlackCodeWord(); - setToBlack(buffer, lineOffset, bitOffset, number); - bitOffset += number; - currChangingElems[currIndex++] = bitOffset; - - number = decodeWhiteCodeWord(); - bitOffset += number; - currChangingElems[currIndex++] = bitOffset; - } - - a0 = bitOffset; - } else if (code <= 8) { - // Vertical - a1 = b1 + (code - 5); - - currChangingElems[currIndex++] = a1; - - // We write the current color till a1 - 1 pos, - // since a1 is where the next color starts - if (!isWhite) { - setToBlack(buffer, lineOffset, bitOffset, a1 - - bitOffset); - } - bitOffset = a0 = a1; - isWhite = !isWhite; - - updatePointer(7 - bits); - } else { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder4")); - } - } - - // Add the changing element beyond the current scanline for the - // other color too - currChangingElems[currIndex++] = bitOffset; - changingElemSize = currIndex; - } else { - // 1D encoded scanline follows - decodeNextScanline(buffer, lineOffset, startX); - } - - lineOffset += scanlineStride; - } - } - - public synchronized void decodeT6(byte[] buffer, byte[] compData, - int startX, int height, long tiffT6Options) { - this.data = compData; - compression = 4; - - bitPointer = 0; - bytePointer = 0; - - int scanlineStride = (w + 7) / 8; - int bufferOffset = 0; - - int a0, a1, b1, b2; - int entry, code, bits; - byte color; - boolean isWhite; - int currIndex; - int temp[]; - - // Return values from getNextChangingElement - int[] b = new int[2]; - - // uncompressedMode - have written some code for this, but this - // has not been tested due to lack of test images using this optional - // extension. This code is when code == 11. aastha 03/03/1999 - uncompressedMode = (int) ((tiffT6Options & 0x02) >> 1); - - // Local cached reference - int[] cce = currChangingElems; - - // Assume invisible preceding row of all white pixels and insert - // both black and white changing elements beyond the end of this - // imaginary scanline. - changingElemSize = 0; - cce[changingElemSize++] = w; - cce[changingElemSize++] = w; - - int lineOffset = 0; - int bitOffset; - - for (int lines = 0; lines < height; lines++) { - // a0 has to be set just before the start of the scanline. - a0 = -1; - isWhite = true; - - // Assign the changing elements of the previous scanline to - // prevChangingElems and start putting this new scanline's - // changing elements into the currChangingElems. - temp = prevChangingElems; - prevChangingElems = currChangingElems; - cce = currChangingElems = temp; - currIndex = 0; - - // Start decoding the scanline at startX in the raster - bitOffset = startX; - - // Reset search start position for getNextChangingElement - lastChangingElement = 0; - - // Till one whole scanline is decoded - while (bitOffset < w) { - // Get the next changing element - getNextChangingElement(a0, isWhite, b); - b1 = b[0]; - b2 = b[1]; - - // Get the next seven bits - entry = nextLesserThan8Bits(7); - // Run these through the 2DCodes table - entry = (int) (twoDCodes[entry] & 0xff); - - // Get the code and the number of bits used up - code = (entry & 0x78) >>> 3; - bits = entry & 0x07; - - if (code == 0) { // Pass - // We always assume WhiteIsZero format for fax. - if (!isWhite) { - setToBlack(buffer, lineOffset, bitOffset, b2 - - bitOffset); - } - bitOffset = a0 = b2; - - // Set pointer to only consume the correct number of bits. - updatePointer(7 - bits); - } else if (code == 1) { // Horizontal - // Set pointer to only consume the correct number of bits. - updatePointer(7 - bits); - - // identify the next 2 alternating color codes. - int number; - if (isWhite) { - // Following are white and black runs - number = decodeWhiteCodeWord(); - bitOffset += number; - cce[currIndex++] = bitOffset; - - number = decodeBlackCodeWord(); - setToBlack(buffer, lineOffset, bitOffset, number); - bitOffset += number; - cce[currIndex++] = bitOffset; - } else { - // First a black run and then a white run follows - number = decodeBlackCodeWord(); - setToBlack(buffer, lineOffset, bitOffset, number); - bitOffset += number; - cce[currIndex++] = bitOffset; - - number = decodeWhiteCodeWord(); - bitOffset += number; - cce[currIndex++] = bitOffset; - } - - a0 = bitOffset; - } else if (code <= 8) { // Vertical - a1 = b1 + (code - 5); - cce[currIndex++] = a1; - - // We write the current color till a1 - 1 pos, - // since a1 is where the next color starts - if (!isWhite) { - setToBlack(buffer, lineOffset, bitOffset, a1 - - bitOffset); - } - bitOffset = a0 = a1; - isWhite = !isWhite; - - updatePointer(7 - bits); - } else if (code == 11) { - if (nextLesserThan8Bits(3) != 7) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder5")); - } - - int zeros = 0; - boolean exit = false; - - while (!exit) { - while (nextLesserThan8Bits(1) != 1) { - zeros++; - } - - if (zeros > 5) { - // Exit code - - // Zeros before exit code - zeros = zeros - 6; - - if (!isWhite && (zeros > 0)) { - cce[currIndex++] = bitOffset; - } - - // Zeros before the exit code - bitOffset += zeros; - if (zeros > 0) { - // Some zeros have been written - isWhite = true; - } - - // Read in the bit which specifies the color of - // the following run - if (nextLesserThan8Bits(1) == 0) { - if (!isWhite) { - cce[currIndex++] = bitOffset; - } - isWhite = true; - } else { - if (isWhite) { - cce[currIndex++] = bitOffset; - } - isWhite = false; - } - - exit = true; - } - - if (zeros == 5) { - if (!isWhite) { - cce[currIndex++] = bitOffset; - } - bitOffset += zeros; - - // Last thing written was white - isWhite = true; - } else { - bitOffset += zeros; - - cce[currIndex++] = bitOffset; - setToBlack(buffer, lineOffset, bitOffset, 1); - ++bitOffset; - - // Last thing written was black - isWhite = false; - } - - } - } else { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder5")); - } - } - - // Add the changing element beyond the current scanline for the - // other color too - cce[currIndex++] = bitOffset; - - // Number of changing elements in this scanline. - changingElemSize = currIndex; - - lineOffset += scanlineStride; - } - } - - private void setToBlack(byte[] buffer, int lineOffset, int bitOffset, - int numBits) { - int bitNum = 8 * lineOffset + bitOffset; - int lastBit = bitNum + numBits; - - int byteNum = bitNum >> 3; - - // Handle bits in first byte - int shift = bitNum & 0x7; - if (shift > 0) { - int maskVal = 1 << (7 - shift); - byte val = buffer[byteNum]; - while (maskVal > 0 && bitNum < lastBit) { - val |= maskVal; - maskVal >>= 1; - ++bitNum; - } - buffer[byteNum] = val; - } - - // Fill in 8 bits at a time - byteNum = bitNum >> 3; - while (bitNum < lastBit - 7) { - buffer[byteNum++] = (byte) 255; - bitNum += 8; - } - - // Fill in remaining bits - while (bitNum < lastBit) { - byteNum = bitNum >> 3; - buffer[byteNum] |= 1 << (7 - (bitNum & 0x7)); - ++bitNum; - } - } - - // Returns run length - private int decodeWhiteCodeWord() { - int current, entry, bits, isT, twoBits, code = -1; - int runLength = 0; - boolean isWhite = true; - - while (isWhite) { - current = nextNBits(10); - entry = white[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x0f; - - if (bits == 12) { // Additional Make up code - // Get the next 2 bits - twoBits = nextLesserThan8Bits(2); - // Consolidate the 2 new bits and last 2 bits into 4 bits - current = ((current << 2) & 0x000c) | twoBits; - entry = additionalMakeup[current]; - bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 - code = (entry >>> 4) & 0x0fff; // 12 bits - runLength += code; - updatePointer(4 - bits); - } else if (bits == 0) { // ERROR - throw new Error(JaiI18N.getString("XTIFFFaxDecoder0")); - } else if (bits == 15) { // EOL - throw new Error(JaiI18N.getString("XTIFFFaxDecoder1")); - } else { - // 11 bits - 0000 0111 1111 1111 = 0x07ff - code = (entry >>> 5) & 0x07ff; - runLength += code; - updatePointer(10 - bits); - if (isT == 0) { - isWhite = false; - } - } - } - - return runLength; - } - - // Returns run length - private int decodeBlackCodeWord() { - int current, entry, bits, isT, twoBits, code = -1; - int runLength = 0; - boolean isWhite = false; - - while (!isWhite) { - current = nextLesserThan8Bits(4); - entry = initBlack[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x000f; - code = (entry >>> 5) & 0x07ff; - - if (code == 100) { - current = nextNBits(9); - entry = black[current]; - - // Get the 3 fields from the entry - isT = entry & 0x0001; - bits = (entry >>> 1) & 0x000f; - code = (entry >>> 5) & 0x07ff; - - if (bits == 12) { - // Additional makeup codes - updatePointer(5); - current = nextLesserThan8Bits(4); - entry = additionalMakeup[current]; - bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 - code = (entry >>> 4) & 0x0fff; // 12 bits - runLength += code; - - updatePointer(4 - bits); - } else if (bits == 15) { - // EOL code - throw new Error(JaiI18N.getString("XTIFFFaxDecoder2")); - } else { - runLength += code; - updatePointer(9 - bits); - if (isT == 0) { - isWhite = true; - } - } - } else if (code == 200) { - // Is a Terminating code - current = nextLesserThan8Bits(2); - entry = twoBitBlack[current]; - code = (entry >>> 5) & 0x07ff; - runLength += code; - bits = (entry >>> 1) & 0x0f; - updatePointer(2 - bits); - isWhite = true; - } else { - // Is a Terminating code - runLength += code; - updatePointer(4 - bits); - isWhite = true; - } - } - - return runLength; - } - - private int readEOL() { - if (fillBits == 0) { - if (nextNBits(12) != 1) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder6")); - } - } else if (fillBits == 1) { - - // First EOL code word xxxx 0000 0000 0001 will occur - // As many fill bits will be present as required to make - // the EOL code of 12 bits end on a byte boundary. - - int bitsLeft = 8 - bitPointer; - - if (nextNBits(bitsLeft) != 0) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder8")); - } - - // If the number of bitsLeft is less than 8, then to have a 12 - // bit EOL sequence, two more bytes are certainly going to be - // required. The first of them has to be all zeros, so ensure - // that. - if (bitsLeft < 4) { - if (nextNBits(8) != 0) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder8")); - } - } - - // There might be a random number of fill bytes with 0s, so - // loop till the EOL of 0000 0001 is found, as long as all - // the bytes preceding it are 0's. - int n; - while ((n = nextNBits(8)) != 1) { - - // If not all zeros - if (n != 0) { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder8")); - } - } - } - - // If one dimensional encoding mode, then always return 1 - if (oneD == 0) { - return 1; - } else { - // Otherwise for 2D encoding mode, - // The next one bit signifies 1D/2D encoding of next line. - return nextLesserThan8Bits(1); - } - } - - private void getNextChangingElement(int a0, boolean isWhite, int[] ret) { - // Local copies of instance variables - int[] pce = this.prevChangingElems; - int ces = this.changingElemSize; - - // If the previous match was at an odd element, we still - // have to search the preceeding element. - // int start = lastChangingElement & ~0x1; - int start = lastChangingElement > 0 ? lastChangingElement - 1 : 0; - if (isWhite) { - start &= ~0x1; // Search even numbered elements - } else { - start |= 0x1; // Search odd numbered elements - } - - int i = start; - for (; i < ces; i += 2) { - int temp = pce[i]; - if (temp > a0) { - lastChangingElement = i; - ret[0] = temp; - break; - } - } - - if (i + 1 < ces) { - ret[1] = pce[i + 1]; - } - } - - private int nextNBits(int bitsToGet) { - byte b, next, next2next; - int l = data.length - 1; - int bp = this.bytePointer; - - if (fillOrder == 1) { - b = data[bp]; - - if (bp == l) { - next = 0x00; - next2next = 0x00; - } else if ((bp + 1) == l) { - next = data[bp + 1]; - next2next = 0x00; - } else { - next = data[bp + 1]; - next2next = data[bp + 2]; - } - } else if (fillOrder == 2) { - b = flipTable[data[bp] & 0xff]; - - if (bp == l) { - next = 0x00; - next2next = 0x00; - } else if ((bp + 1) == l) { - next = flipTable[data[bp + 1] & 0xff]; - next2next = 0x00; - } else { - next = flipTable[data[bp + 1] & 0xff]; - next2next = flipTable[data[bp + 2] & 0xff]; - } - } else { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder7")); - } - - int bitsLeft = 8 - bitPointer; - int bitsFromNextByte = bitsToGet - bitsLeft; - int bitsFromNext2NextByte = 0; - if (bitsFromNextByte > 8) { - bitsFromNext2NextByte = bitsFromNextByte - 8; - bitsFromNextByte = 8; - } - - bytePointer++; - - int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft); - int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); - - int i3 = 0; - if (bitsFromNext2NextByte != 0) { - i2 <<= bitsFromNext2NextByte; - i3 = (next2next & table2[bitsFromNext2NextByte]) >>> (8 - bitsFromNext2NextByte); - i2 |= i3; - bytePointer++; - bitPointer = bitsFromNext2NextByte; - } else { - if (bitsFromNextByte == 8) { - bitPointer = 0; - bytePointer++; - } else { - bitPointer = bitsFromNextByte; - } - } - - int i = i1 | i2; - return i; - } - - private int nextLesserThan8Bits(int bitsToGet) { - byte b, next; - int l = data.length - 1; - int bp = this.bytePointer; - - if (fillOrder == 1) { - b = data[bp]; - if (bp == l) { - next = 0x00; - } else { - next = data[bp + 1]; - } - } else if (fillOrder == 2) { - b = flipTable[data[bp] & 0xff]; - if (bp == l) { - next = 0x00; - } else { - next = flipTable[data[bp + 1] & 0xff]; - } - } else { - throw new Error(JaiI18N.getString("XTIFFFaxDecoder7")); - } - - int bitsLeft = 8 - bitPointer; - int bitsFromNextByte = bitsToGet - bitsLeft; - - int shift = bitsLeft - bitsToGet; - int i1, i2; - if (shift >= 0) { - i1 = (b & table1[bitsLeft]) >>> shift; - bitPointer += bitsToGet; - if (bitPointer == 8) { - bitPointer = 0; - bytePointer++; - } - } else { - i1 = (b & table1[bitsLeft]) << (-shift); - i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); - - i1 |= i2; - bytePointer++; - bitPointer = bitsFromNextByte; - } - - return i1; - } - - // Move pointer backwards by given amount of bits - private void updatePointer(int bitsToMoveBack) { - int i = bitPointer - bitsToMoveBack; - - if (i < 0) { - bytePointer--; - bitPointer = 8 + i; - } else { - bitPointer = i; - } - } - - // Move to the next byte boundary - private boolean advancePointer() { - if (bitPointer != 0) { - bytePointer++; - bitPointer = 0; - } - - return true; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxTileCodec.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxTileCodec.java deleted file mode 100644 index b0bf89783..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFFaxTileCodec.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.libtiff.jai.codecimpl; - -import java.awt.Rectangle; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFField; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.codec.XTIFFTileCodecImpl; - -/** - * This codec encapsulates all the logic for the TIFF "lzw" decoding codec - * algorithm. - */ -public class XTIFFFaxTileCodec extends XTIFFTileCodecImpl { - - private XTIFFFaxDecoder decoder = null; - - // Fax compression related variables - long tiffT4Options; - long tiffT6Options; - int fillOrder; - - /** - * Public constructor - */ - public XTIFFFaxTileCodec() {} - - /** - * Creation method - */ - public XTIFFTileCodec create() { - return new XTIFFFaxTileCodec(); - } - - public boolean canEncode() { - return false; - } - - /** - * Registration method - */ - public void register() { - register(XTIFF.COMPRESSION_FAX_G3_1D); - register(XTIFF.COMPRESSION_FAX_G3_2D); - register(XTIFF.COMPRESSION_FAX_G4_2D); - } - - /** - * The initialization method particular to Fax decoding. - */ - public void initializeDecoding() { - - XTIFFField fillOrderField = directory.getField(XTIFF.TIFFTAG_FILL_ORDER); - if (fillOrderField != null) { - fillOrder = fillOrderField.getAsInt(0); - } else { - // Default Fill Order - fillOrder = 1; - } - // Fax T.4 compression options - if (compression == 3) { - XTIFFField t4OptionsField = directory.getField(XTIFF.TIFFTAG_T4_OPTIONS); - if (t4OptionsField != null) { - tiffT4Options = t4OptionsField.getAsLong(0); - } else { - // Use default value - tiffT4Options = 0; - } - } - - // Fax T.6 compression options - if (compression == 4) { - XTIFFField t6OptionsField = directory.getField(XTIFF.TIFFTAG_T6_OPTIONS); - if (t6OptionsField != null) { - tiffT6Options = t6OptionsField.getAsLong(0); - } else { - // Use default value - tiffT6Options = 0; - } - } - - decoder = new XTIFFFaxDecoder(fillOrder, tileWidth, tileLength); - - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, byte[] bdata) { - if (compression == XTIFF.COMPRESSION_FAX_G3_1D) { - decoder.decode1D(bdata, input, newRect.x, newRect.height); - } else if (compression == XTIFF.COMPRESSION_FAX_G3_2D) { - decoder.decode2D(bdata, - input, - newRect.x, - newRect.height, - tiffT4Options); - } else if (compression == XTIFF.COMPRESSION_FAX_G4_2D) { - decoder.decodeT6(bdata, - input, - newRect.x, - newRect.height, - tiffT6Options); - } - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, short[] sdata) { - // not used for fax. - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImage.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImage.java deleted file mode 100644 index 4c4d88864..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImage.java +++ /dev/null @@ -1,661 +0,0 @@ -package org.libtiff.jai.codecimpl; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.awt.Rectangle; -import java.awt.Transparency; -import java.awt.color.ColorSpace; -import java.awt.image.ComponentColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.IndexColorModel; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.PixelInterleavedSampleModel; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.io.IOException; - -import javax.media.jai.RasterFactory; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFDecodeParam; -import org.libtiff.jai.codec.XTIFFDirectory; -import org.libtiff.jai.codec.XTIFFField; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.util.JaiI18N; - -import com.sun.media.jai.codec.ImageCodec; -import com.sun.media.jai.codec.SeekableStream; -import com.sun.media.jai.codec.TIFFDecodeParam; -import com.sun.media.jai.codecimpl.SimpleRenderedImage; - -public class XTIFFImage extends SimpleRenderedImage { - - XTIFFTileCodec codec; - XTIFFDirectory dir; - TIFFDecodeParam param; - int photometric_interp; - SeekableStream stream; - int tileSize; - int tilesX, tilesY; - long[] tileOffsets; - long tileByteCounts[]; - char colormap[]; - char bitsPerSample[]; - int samplesPerPixel; - int extraSamples; - byte palette[]; - int bands; - char sampleFormat[]; - - boolean decodePaletteAsShorts; - - boolean isBigEndian; - - // Image types - int image_type; - int dataType; - - /** - * Constructs a XTIFFImage that acquires its data from a given - * SeekableStream and reads from a particular IFD of the stream. The index - * of the first IFD is 0. - * - * @param stream the SeekableStream to read from. - * @param param an instance of TIFFDecodeParam, or null. - * @param directory the index of the IFD to read from. - */ - public XTIFFImage(SeekableStream stream, TIFFDecodeParam param, - int directory) throws IOException { - - this.stream = stream; - if (param == null || !(param instanceof XTIFFDecodeParam)) { - param = new XTIFFDecodeParam(param); - } - this.param = param; - - decodePaletteAsShorts = param.getDecodePaletteAsShorts(); - - // Read the specified directory. - dir = XTIFFDirectory.create(stream, directory); - properties.put("tiff.directory", dir); - ((XTIFFDecodeParam) param).setDirectory(dir); - - // Check whether big endian or little endian format is used. - isBigEndian = dir.isBigEndian(); - - setupImageParameters(); - - setupSamplesAndColor(); - - dir.setImageType(image_type); - - // Calculate number of tiles and the tileSize in bytes - tilesX = (width + tileWidth - 1) / tileWidth; - tilesY = (height + tileHeight - 1) / tileHeight; - tileSize = tileWidth * tileHeight * bands; - - try { - codec = dir.createTileCodec((XTIFFDecodeParam) param); - } catch (Exception e) { - } - } - - /** - * This method gets the image parameters from fields - */ - protected void setupImageParameters() { - - // Set basic image layout - minX = minY = 0; - width = (int) dir.getFieldAsLong(XTIFF.TIFFTAG_IMAGE_WIDTH); - height = (int) dir.getFieldAsLong(XTIFF.TIFFTAG_IMAGE_LENGTH); - - photometric_interp = (int) dir.getFieldAsLong(XTIFF.TIFFTAG_PHOTOMETRIC_INTERPRETATION); - - // Read the TIFFTAG_BITS_PER_SAMPLE field - XTIFFField bitsField = dir.getField(XTIFF.TIFFTAG_BITS_PER_SAMPLE); - - if (bitsField == null) { - // Default - bitsPerSample = new char[1]; - bitsPerSample[0] = 1; - } else { - bitsPerSample = bitsField.getAsChars(); - } - - for (int i = 1; i < bitsPerSample.length; i++) { - if (bitsPerSample[i] != bitsPerSample[1]) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder19")); - } - } - - // Get the number of samples per pixel - XTIFFField sfield = dir.getField(XTIFF.TIFFTAG_SAMPLES_PER_PIXEL); - if (sfield == null) { - samplesPerPixel = 1; - } else { - samplesPerPixel = (int) sfield.getAsLong(0); - } - - // Figure out if any extra samples are present. - XTIFFField efield = dir.getField(XTIFF.TIFFTAG_EXTRA_SAMPLES); - if (efield == null) { - extraSamples = 0; - } else { - extraSamples = (int) efield.getAsLong(0); - } - - // Read the TIFFTAG_SAMPLE_FORMAT tag to see whether the data might be - // signed or floating point - XTIFFField sampleFormatField = dir.getField(XTIFF.TIFFTAG_SAMPLE_FORMAT); - - if (sampleFormatField != null) { - sampleFormat = sampleFormatField.getAsChars(); - - // Check that all the samples have the same format - for (int l = 1; l < sampleFormat.length; l++) { - if (sampleFormat[l] != sampleFormat[0]) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder20")); - } - } - - } else { - sampleFormat = new char[] { 1 }; - } - - if (sampleFormat[0] == 1 || sampleFormat[0] == 4) { - - // Unsigned or unknown - if (bitsPerSample[0] == 8) { - dataType = DataBuffer.TYPE_BYTE; - } else if (bitsPerSample[0] == 16) { - dataType = DataBuffer.TYPE_USHORT; - } else if (bitsPerSample[0] == 32) { - dataType = DataBuffer.TYPE_INT; - } - - } else if (sampleFormat[0] == 2) { - // Signed - - if (bitsPerSample[0] == 1 || bitsPerSample[0] == 4 - || bitsPerSample[0] == 8) { - - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder21")); - - } else if (bitsPerSample[0] == 16) { - dataType = DataBuffer.TYPE_SHORT; - } else if (bitsPerSample[0] == 32) { - dataType = DataBuffer.TYPE_INT; - } - - } else if (sampleFormat[0] == 3) { - // Floating point - // dataType = DataBuffer.TYPE_FLOAT; - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder22")); - } - - if (dir.getField(XTIFF.TIFFTAG_TILE_WIDTH) != null) { - // Image is in tiled format - tileWidth = (int) dir.getFieldAsLong(XTIFF.TIFFTAG_TILE_WIDTH); - tileHeight = (int) dir.getFieldAsLong(XTIFF.TIFFTAG_TILE_LENGTH); - tileOffsets = (dir.getField(XTIFF.TIFFTAG_TILE_OFFSETS)).getAsLongs(); - tileByteCounts = dir.getField(XTIFF.TIFFTAG_TILE_BYTE_COUNTS) - .getAsLongs(); - - } else { - - // Image is in stripped format, looks like tiles to us - tileWidth = width; - XTIFFField field = dir.getField(XTIFF.TIFFTAG_ROWS_PER_STRIP); - if (field == null) { - // Default is infinity (2^32 -1), basically the entire image - // TODO: Can do a better job of tiling here - tileHeight = height; - } else { - long l = field.getAsLong(0); - long infinity = 1; - infinity = (infinity << 32) - 1; - if (l == infinity) { - // 2^32 - 1 (effectively infinity, entire image is 1 strip) - tileHeight = height; - } else { - tileHeight = (int) l; - } - } - - XTIFFField tileOffsetsField = dir.getField(XTIFF.TIFFTAG_STRIP_OFFSETS); - if (tileOffsetsField == null) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder11")); - } else { - tileOffsets = tileOffsetsField.getAsLongs(); - } - - XTIFFField tileByteCountsField = dir.getField(XTIFF.TIFFTAG_STRIP_BYTE_COUNTS); - if (tileByteCountsField == null) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder12")); - } else { - tileByteCounts = tileByteCountsField.getAsLongs(); - } - } - } - - /** - * This method constructs the sampleModel, colorModel, determines the - * image_type and the bands parameter. - */ - protected void setupSamplesAndColor() { - - // Figure out which kind of image we are dealing with. - switch (photometric_interp) { - - case XTIFF.PHOTOMETRIC_WHITE_IS_ZERO: - - bands = 1; - - // Bilevel or Grayscale - WhiteIsZero - if (bitsPerSample[0] == 1) { - - image_type = XTIFF.TYPE_BILEVEL_WHITE_IS_ZERO; - - // Keep pixels packed, use IndexColorModel - sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, 1); - - // Set up the palette - byte r[] = new byte[] { (byte) 255, (byte) 0 }; - byte g[] = new byte[] { (byte) 255, (byte) 0 }; - byte b[] = new byte[] { (byte) 255, (byte) 0 }; - - colorModel = new IndexColorModel(1, 2, r, g, b); - - } else { - - image_type = XTIFF.TYPE_GREYSCALE_WHITE_IS_ZERO; - - if (bitsPerSample[0] == 4) { - sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, 4); - - colorModel = ImageCodec.createGrayIndexColorModel(sampleModel, - false); - - } else if (bitsPerSample[0] == 8) { - sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - bands); - - colorModel = ImageCodec.createGrayIndexColorModel(sampleModel, - false); - - } else if (bitsPerSample[0] == 16) { - - sampleModel = RasterFactory.createPixelInterleavedSampleModel(dataType, - tileWidth, - tileHeight, - bands); - - colorModel = ImageCodec.createComponentColorModel(sampleModel); - - } else { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFImageDecoder14")); - } - } - - break; - - case XTIFF.PHOTOMETRIC_BLACK_IS_ZERO: - - bands = 1; - - // Bilevel or Grayscale - BlackIsZero - if (bitsPerSample[0] == 1) { - - image_type = XTIFF.TYPE_BILEVEL_BLACK_IS_ZERO; - - // Keep pixels packed, use IndexColorModel - sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, 1); - - // Set up the palette - byte r[] = new byte[] { (byte) 0, (byte) 255 }; - byte g[] = new byte[] { (byte) 0, (byte) 255 }; - byte b[] = new byte[] { (byte) 0, (byte) 255 }; - - // 1 Bit pixels packed into a byte, use IndexColorModel - colorModel = new IndexColorModel(1, 2, r, g, b); - - } else { - - image_type = XTIFF.TYPE_GREYSCALE_BLACK_IS_ZERO; - - if (bitsPerSample[0] == 4) { - sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, 4); - colorModel = ImageCodec.createGrayIndexColorModel(sampleModel, - true); - } else if (bitsPerSample[0] == 8) { - sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - bands); - colorModel = ImageCodec.createComponentColorModel(sampleModel); - - } else if (bitsPerSample[0] == 16) { - - sampleModel = RasterFactory.createPixelInterleavedSampleModel(dataType, - tileWidth, - tileHeight, - bands); - colorModel = ImageCodec.createComponentColorModel(sampleModel); - - } else { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFImageDecoder14")); - } - } - - break; - - case XTIFF.PHOTOMETRIC_RGB: - - bands = samplesPerPixel; - - // RGB full color image - if (bitsPerSample[0] == 8) { - - sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - bands); - } else if (bitsPerSample[0] == 16) { - - sampleModel = RasterFactory.createPixelInterleavedSampleModel(dataType, - tileWidth, - tileHeight, - bands); - } else { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder15")); - } - - if (samplesPerPixel < 3) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder1")); - - } else if (samplesPerPixel == 3) { - - image_type = XTIFF.TYPE_RGB; - // No alpha - colorModel = ImageCodec.createComponentColorModel(sampleModel); - - } else if (samplesPerPixel == 4) { - - if (extraSamples == 0) { - - image_type = XTIFF.TYPE_ORGB; - // Transparency.OPAQUE signifies image data that is - // completely opaque, meaning that all pixels have an alpha - // value of 1.0. So the extra band gets ignored, which is - // what we want. - colorModel = createAlphaComponentColorModel(dataType, - true, - false, - Transparency.OPAQUE); - - } else if (extraSamples == 1) { - - image_type = XTIFF.TYPE_ARGB_PRE; - // Pre multiplied alpha. - colorModel = createAlphaComponentColorModel(dataType, - true, - true, - Transparency.TRANSLUCENT); - - } else if (extraSamples == 2) { - - image_type = XTIFF.TYPE_ARGB; - // The extra sample here is unassociated alpha, usually a - // transparency mask, also called soft matte. - colorModel = createAlphaComponentColorModel(dataType, - true, - false, - Transparency.BITMASK); - } - - } else { - image_type = XTIFF.TYPE_RGB_EXTRA; - - // For this case we can't display the image, so there is no - // point in trying to reformat the data to be BGR followed by - // the ExtraSamples, the way Java2D would like it, because - // Java2D can't display it anyway. Therefore create a sample - // model with increasing bandOffsets, and keep the colorModel - // as null, as there is no appropriate ColorModel. - - int bandOffsets[] = new int[bands]; - for (int i = 0; i < bands; i++) { - bandOffsets[i] = i; - } - - if (bitsPerSample[0] == 8) { - - sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, bands, bands - * tileWidth, bandOffsets); - colorModel = null; - - } else if (bitsPerSample[0] == 16) { - - sampleModel = new PixelInterleavedSampleModel(dataType, tileWidth, tileHeight, bands, bands - * tileWidth, bandOffsets); - colorModel = null; - } - } - - break; - - case XTIFF.PHOTOMETRIC_PALETTE: - - image_type = XTIFF.TYPE_PALETTE; - - // Get the colormap - XTIFFField cfield = dir.getField(XTIFF.TIFFTAG_COLORMAP); - if (cfield == null) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder2")); - } else { - colormap = cfield.getAsChars(); - } - - // Could be either 1 or 3 bands depending on whether we use - // IndexColorModel or not. - if (decodePaletteAsShorts) { - bands = 3; - - if (bitsPerSample[0] != 4 && bitsPerSample[0] != 8 - && bitsPerSample[0] != 16) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder13")); - } - - // If no SampleFormat tag was specified and if the - // bitsPerSample are less than or equal to 8, then the - // dataType was initially set to byte, but now we want to - // expand the palette as shorts, so the dataType should - // be ushort. - if (dataType == DataBuffer.TYPE_BYTE) { - dataType = DataBuffer.TYPE_USHORT; - } - - // Data will have to be unpacked into a 3 band short image - // as we do not have a IndexColorModel that can deal with - // a colormodel whose entries are of short data type. - sampleModel = RasterFactory.createPixelInterleavedSampleModel(dataType, - tileWidth, - tileHeight, - bands); - colorModel = ImageCodec.createComponentColorModel(sampleModel); - - } else { - - bands = 1; - - if (bitsPerSample[0] == 4) { - // Pixel data will not be unpacked, will use MPPSM to store - // packed data and IndexColorModel to do the unpacking. - sampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, tileWidth, tileHeight, bitsPerSample[0]); - } else if (bitsPerSample[0] == 8) { - sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - bands); - } else if (bitsPerSample[0] == 16) { - - // Here datatype has to be unsigned since we are storing - // indices into the IndexColorModel palette. Ofcourse - // the actual palette entries are allowed to be negative. - sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, - tileWidth, - tileHeight, - bands); - } else { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder13")); - } - - int bandLength = colormap.length / 3; - byte r[] = new byte[bandLength]; - byte g[] = new byte[bandLength]; - byte b[] = new byte[bandLength]; - - int gIndex = bandLength; - int bIndex = bandLength * 2; - - if (dataType == DataBuffer.TYPE_SHORT) { - - for (int i = 0; i < bandLength; i++) { - r[i] = param.decodeSigned16BitsTo8Bits((short) colormap[i]); - g[i] = param.decodeSigned16BitsTo8Bits((short) colormap[gIndex - + i]); - b[i] = param.decodeSigned16BitsTo8Bits((short) colormap[bIndex - + i]); - } - - } else { - - for (int i = 0; i < bandLength; i++) { - r[i] = param.decode16BitsTo8Bits(colormap[i] & 0xffff); - g[i] = param.decode16BitsTo8Bits(colormap[gIndex + i] & 0xffff); - b[i] = param.decode16BitsTo8Bits(colormap[bIndex + i] & 0xffff); - } - - } - - colorModel = new IndexColorModel(bitsPerSample[0], bandLength, r, g, b); - } - - break; - - case XTIFF.PHOTOMETRIC_TRANSPARENCY: - - image_type = XTIFF.TYPE_TRANS; - - // Transparency Mask - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder3")); - // break; - - default: - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder4")); - } - - } - - /** - * Reads a private IFD from a given offset in the stream. This method may be - * used to obtain IFDs that are referenced only by private tag values. - */ - public XTIFFDirectory getPrivateIFD(long offset) throws IOException { - return XTIFFDirectory.create(stream, offset); - } - - private WritableRaster tile00 = null; - - /** - * Returns tile (tileX, tileY) as a Raster. - */ - public synchronized Raster getTile(int tileX, int tileY) { - if (tileX == 0 && tileY == 0 && tile00 != null) { - return tile00; - } - - if ((tileX < 0) || (tileX >= tilesX) || (tileY < 0) - || (tileY >= tilesY)) { - throw new IllegalArgumentException(JaiI18N.getString("XTIFFImageDecoder5")); - } - - // file setup1 - - // Save original file pointer position and seek to tile data location. - long save_offset = 0; - try { - save_offset = stream.getFilePointer(); - stream.seek(tileOffsets[tileY * tilesX + tileX]); - } catch (IOException ioe) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder8")); - } - - // Number of bytes in this tile (strip) after compression. - int byteCount = (int) tileByteCounts[tileY * tilesX + tileX]; - - // Find out the number of bytes in the current tile - Rectangle tileRect = new Rectangle(tileXToX(tileX), tileYToY(tileY), tileWidth, tileHeight); - Rectangle newRect = tileRect.intersection(getBounds()); - - // file setup2 - - byte data[] = new byte[byteCount]; - WritableRaster tile = null; - try { - stream.readFully(data, 0, byteCount); - tile = codec.decode(this, newRect, data); - stream.seek(save_offset); - } catch (IOException e) { - throw new RuntimeException("Failed to read raw tile data:" + e); - } - - if (tileX == 0 && tileY == 0) { - tile00 = tile; - } - return tile; - } - - // Create ComponentColorModel for TYPE_RGB images - private ComponentColorModel createAlphaComponentColorModel( - int dataType, - boolean hasAlpha, - boolean isAlphaPremultiplied, - int transparency) { - - ComponentColorModel ccm = null; - int RGBBits[][] = new int[3][]; - - RGBBits[0] = new int[] { 8, 8, 8, 8 }; // Byte - RGBBits[1] = new int[] { 16, 16, 16, 16 }; // Short - RGBBits[2] = new int[] { 16, 16, 16, 16 }; // UShort - RGBBits[2] = new int[] { 32, 32, 32, 32 }; // Int - - ccm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), RGBBits[dataType], hasAlpha, isAlphaPremultiplied, transparency, dataType); - return ccm; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageDecoder.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageDecoder.java deleted file mode 100644 index 66ab6ee44..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageDecoder.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.libtiff.jai.codecimpl; - -/* - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: _______________________________________ - * are Copyright (C): _______________________________________ - * All Rights Reserved. - * Contributor(s): _______________________________________ - */ - -import java.awt.image.RenderedImage; -import java.io.IOException; - -import org.libtiff.jai.util.JaiI18N; - -import com.sun.media.jai.codec.ImageDecodeParam; -import com.sun.media.jai.codec.SeekableStream; -import com.sun.media.jai.codec.TIFFDecodeParam; -import com.sun.media.jai.codecimpl.TIFFImageDecoder; - -/** - */ -public class XTIFFImageDecoder extends TIFFImageDecoder { - - public XTIFFImageDecoder(SeekableStream input, ImageDecodeParam param) { - super(input, param); - } - - public RenderedImage decodeAsRenderedImage(int page) throws IOException { - if ((page < 0) || (page >= getNumPages())) { - throw new IOException(JaiI18N.getString("XTIFFImageDecoder9")); - } - return new XTIFFImage(input, (TIFFDecodeParam) param, page); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageEncoder.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageEncoder.java deleted file mode 100644 index 8ea12e0d6..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFImageEncoder.java +++ /dev/null @@ -1,815 +0,0 @@ -package org.libtiff.jai.codecimpl; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.awt.Rectangle; -import java.awt.color.ColorSpace; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.IndexColorModel; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Vector; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFDirectory; -import org.libtiff.jai.codec.XTIFFEncodeParam; -import org.libtiff.jai.codec.XTIFFField; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.util.JaiI18N; - -import com.sun.media.jai.codec.ImageEncodeParam; -import com.sun.media.jai.codec.TIFFEncodeParam; -import com.sun.media.jai.codec.TIFFField; -import com.sun.media.jai.codecimpl.TIFFImageDecoder; -import com.sun.media.jai.codecimpl.TIFFImageEncoder; - -/** - * A baseline TIFF writer. The writer outputs TIFF images in either Bilevel, - * Greyscale, Palette color or Full Color modes. - * - */ -public class XTIFFImageEncoder extends TIFFImageEncoder { - - long firstIFDOffset = 0; - XTIFFDirectory directory; - XTIFFEncodeParam tparam; - int width; - int length; - SampleModel sampleModel; - int numBands; - int sampleSize[]; - int dataType; - boolean dataTypeIsShort; - ColorModel colorModel; - int numTiles; - int compression; - boolean isTiled; - long tileLength; - long tileWidth; - byte[] bpixels = null; - long stripTileByteCounts[]; - long stripTileOffsets[]; - long currentOffset = 0; - - // Image Types - public static final int XTIFF_BILEVEL_WHITE_IS_ZERO = 0; - public static final int XTIFF_BILEVEL_BLACK_IS_ZERO = 1; - public static final int XTIFF_PALETTE = 2; - public static final int XTIFF_FULLCOLOR = 3; - public static final int XTIFF_GREYSCALE = 4; - - /** - * Standard constructor - */ - public XTIFFImageEncoder(OutputStream output, ImageEncodeParam param) { - super(output, param); - if (this.param == null || !(param instanceof XTIFFEncodeParam)) { - this.param = new XTIFFEncodeParam((TIFFEncodeParam) param); - } - tparam = (XTIFFEncodeParam) this.param; - directory = tparam.getDirectory(); - } - - private File createTemp() throws IOException { - String tmpdir = System.getProperty("tiff.io.tmpdir"); - File file = null; - if (tmpdir != null) - file = File.createTempFile("libtiff.jai.", ".dat", new File(tmpdir)); - else - file = File.createTempFile("libtiff.jai.", ".dat"); - file.deleteOnExit(); - return file; - } - - private void copyImageData(File tmp, OutputStream out, int total) - throws IOException { - int bufsize = 1024; - int bytes = 0; - byte[] buf = new byte[bufsize]; - FileInputStream in = new FileInputStream(tmp); - do { - bytes = in.read(buf); - out.write(buf, 0, bytes); - total -= bytes; - } while (total > 0); - in.close(); - } - - /** - * Encodes a RenderedImage and writes the output to the OutputStream - * associated with this ImageEncoder. - */ - public void encode(RenderedImage im) throws IOException { - - // Set comp into directory - compression = tparam.getCompression(); - - // see if tiled - isTiled = ((TIFFEncodeParam) param).getWriteTiled(); - - // Setup Directory fields. - getImageFields(im); - - if (compression == XTIFF.COMPRESSION_NONE) { - computeIFDOffset(); - writeFileHeader(firstIFDOffset); - currentOffset = 8; - writeImageData(im, output); - writeDirectory(directory.getFields(), 0); - } else { - // We have to write compressed data out to - // a temp file to compute the IFD offset. - // The only alternative is to compress the - // data twice, which is just about as bad. - currentOffset = 8; - File tmp = null; - try { - tmp = createTemp(); - OutputStream tmpOut = new FileOutputStream(tmp); - int total = writeImageData(im, tmpOut); - tmpOut.close(); - writeFileHeader(currentOffset + currentOffset % 2); - copyImageData(tmp, output, total); - writeDirectory(directory.getFields(), 0); - } finally { - if (tmp != null) - tmp.delete(); - } - } - } - - /** - * Precomputes the IFD Offset for uncompressed data. - */ - private void computeIFDOffset() { - - long bytesPerRow = (long) Math.ceil((sampleSize[0] / 8.0) * tileWidth - * numBands); - long bytesPerTile = bytesPerRow * tileLength; - long lastTile = bytesPerTile; - - if (!isTiled) { - // Last strip may have lesser rows - long lastStripRows = length - (tileLength * (numTiles - 1)); - lastTile = lastStripRows * bytesPerRow; - } - - long totalBytesOfData = bytesPerTile * (numTiles - 1) + lastTile; - - // File header always occupies 8 bytes and we write the image data - // after that. - firstIFDOffset = 8 + totalBytesOfData; - // Must begin on a word boundary - if ((firstIFDOffset % 2) != 0) { - firstIFDOffset++; - } - } - - private void writeFileHeader(long firstIFDOffset) throws IOException { - // 8 byte image file header - - // Byte order used within the file - Big Endian - output.write('M'); - output.write('M'); - - // Magic value - output.write(0); - output.write(42); - - // Offset in bytes of the first IFD, must begin on a word boundary - writeLong(firstIFDOffset); - - } - - // method for adding tags that haven't been set by user - private void addIfAbsent(int tag, int type, int count, Object obj) { - if (directory.getField(tag) == null) - directory.addField(tag, type, count, obj); - } - - private void getImageFields(RenderedImage im) - /* throws IOException */{ - - width = im.getWidth(); - length = im.getHeight(); // TIFF calls it length - - sampleModel = im.getSampleModel(); - numBands = sampleModel.getNumBands(); - sampleSize = sampleModel.getSampleSize(); - - dataType = sampleModel.getDataType(); - if (dataType != DataBuffer.TYPE_BYTE - && dataType != DataBuffer.TYPE_SHORT - && dataType != DataBuffer.TYPE_USHORT) { - // Support only byte and (unsigned) short. - throw new Error(JaiI18N.getString("TIFFImageEncoder0")); - } - - dataTypeIsShort = dataType == DataBuffer.TYPE_SHORT - || dataType == DataBuffer.TYPE_USHORT; - - colorModel = im.getColorModel(); - if (colorModel != null && colorModel instanceof IndexColorModel - && dataTypeIsShort) { - // Don't support (unsigned) short palette-color images. - throw new Error(JaiI18N.getString("TIFFImageEncoder2")); - } - IndexColorModel icm = null; - int sizeOfColormap = 0; - char colormap[] = null; - - // Basic fields - have to be in increasing numerical order BILEVEL - // ImageWidth 256 - // ImageLength 257 - // BitsPerSample 258 - // Compression 259 - // PhotoMetricInterpretation 262 - // StripOffsets 273 - // RowsPerStrip 278 - // StripByteCounts 279 - // XResolution 282 - // YResolution 283 - // ResolutionUnit 296 - - int photometricInterpretation = XTIFF.PHOTOMETRIC_RGB; - int imageType = XTIFF_FULLCOLOR; - - // IMAGE TYPES POSSIBLE - - // Bilevel - // BitsPerSample = 1 - // Compression = 1, 2, or 32773 - // PhotometricInterpretation either 0 or 1 - - // Greyscale - // BitsPerSample = 4 or 8 - // Compression = 1, 32773 - // PhotometricInterpretation either 0 or 1 - - // Palette - // ColorMap 320 - // BitsPerSample = 4 or 8 - // PhotometrciInterpretation = 3 - - // Full color - // BitsPerSample = 8, 8, 8 - // SamplesPerPixel = 3 or more 277 - // Compression = 1, 32773 - // PhotometricInterpretation = 2 - - if (colorModel instanceof IndexColorModel) { - - icm = (IndexColorModel) colorModel; - int mapSize = icm.getMapSize(); - - if (sampleSize[0] == 1) { - // Bilevel image - - if (mapSize != 2) { - throw new IllegalArgumentException(JaiI18N.getString("TIFFImageEncoder1")); - } - - byte r[] = new byte[mapSize]; - icm.getReds(r); - byte g[] = new byte[mapSize]; - icm.getGreens(g); - byte b[] = new byte[mapSize]; - icm.getBlues(b); - - if ((r[0] & 0xff) == 0 && (r[1] & 0xff) == 255 - && (g[0] & 0xff) == 0 && (g[1] & 0xff) == 255 - && (b[0] & 0xff) == 0 && (b[1] & 0xff) == 255) { - - imageType = XTIFF_BILEVEL_BLACK_IS_ZERO; - - } else if ((r[0] & 0xff) == 255 && (r[1] & 0xff) == 0 - && (g[0] & 0xff) == 255 && (g[1] & 0xff) == 0 - && (b[0] & 0xff) == 255 && (b[1] & 0xff) == 0) { - - imageType = XTIFF_BILEVEL_WHITE_IS_ZERO; - - } else { - imageType = XTIFF_PALETTE; - } - - } else { - // Palette color image. - imageType = XTIFF_PALETTE; - } - } else { - - // If it is not an IndexColorModel, it can either be a greyscale - // image or a full color image - - if ((colorModel == null || colorModel.getColorSpace().getType() == ColorSpace.TYPE_GRAY) - && numBands == 1) { - // Greyscale image - imageType = XTIFF_GREYSCALE; - } else { - // Full color image - imageType = XTIFF_FULLCOLOR; - } - } - - switch (imageType) { - - case XTIFF_BILEVEL_WHITE_IS_ZERO: - photometricInterpretation = XTIFF.PHOTOMETRIC_WHITE_IS_ZERO; - break; - - case XTIFF_BILEVEL_BLACK_IS_ZERO: - photometricInterpretation = XTIFF.PHOTOMETRIC_BLACK_IS_ZERO; - break; - - case XTIFF_GREYSCALE: - // Since the CS_GRAY colorspace is always of type black_is_zero - photometricInterpretation = XTIFF.PHOTOMETRIC_BLACK_IS_ZERO; - break; - - case XTIFF_PALETTE: - photometricInterpretation = XTIFF.PHOTOMETRIC_PALETTE; - - icm = (IndexColorModel) colorModel; - sizeOfColormap = icm.getMapSize(); - - byte r[] = new byte[sizeOfColormap]; - icm.getReds(r); - byte g[] = new byte[sizeOfColormap]; - icm.getGreens(g); - byte b[] = new byte[sizeOfColormap]; - icm.getBlues(b); - - int redIndex = 0, - greenIndex = sizeOfColormap; - int blueIndex = 2 * sizeOfColormap; - colormap = new char[sizeOfColormap * 3]; - for (int i = 0; i < sizeOfColormap; i++) { - colormap[redIndex++] = (char) (r[i] << 8); - colormap[greenIndex++] = (char) (g[i] << 8); - colormap[blueIndex++] = (char) (b[i] << 8); - } - - sizeOfColormap *= 3; - - // Since we will be writing the colormap field. - break; - - case XTIFF_FULLCOLOR: - photometricInterpretation = XTIFF.PHOTOMETRIC_RGB; - break; - - } - - if (isTiled) { - tileWidth = 16L; - tileLength = 16L; - XTIFFField fld = directory.getField(XTIFF.TIFFTAG_TILE_WIDTH); - if (fld != null) - tileWidth = (int) fld.getAsLong(0); - fld = directory.getField(XTIFF.TIFFTAG_TILE_LENGTH); - if (fld != null) - tileLength = (int) fld.getAsLong(0); - } else { - // Default strip is 8 rows. - tileLength = 8L; - // tileWidth of strip is width - - tileWidth = width; - XTIFFField fld = directory.getField(TIFFImageDecoder.TIFF_ROWS_PER_STRIP); - if (fld != null) - tileLength = fld.getAsLong(0); - } - - numTiles = (int) Math.ceil((double) length / (double) tileLength) - * (int) Math.ceil((double) width / (double) tileWidth); - - stripTileByteCounts = new long[numTiles]; - stripTileOffsets = new long[numTiles]; - - // Image Width - directory.addField(XTIFF.TIFFTAG_IMAGE_WIDTH, - TIFFField.TIFF_LONG, - 1, - (Object) (new long[] { width })); - - // Image Length - directory.addField(XTIFF.TIFFTAG_IMAGE_LENGTH, - TIFFField.TIFF_LONG, - 1, - new long[] { length }); - - directory.addField(XTIFF.TIFFTAG_BITS_PER_SAMPLE, - TIFFField.TIFF_SHORT, - numBands, - convertToChars(sampleSize)); - - directory.addField(XTIFF.TIFFTAG_COMPRESSION, - TIFFField.TIFF_SHORT, - 1, - new char[] { (char) compression }); - - directory.addField(XTIFF.TIFFTAG_PHOTOMETRIC_INTERPRETATION, - TIFFField.TIFF_SHORT, - 1, - new char[] { (char) photometricInterpretation }); - - directory.addField(XTIFF.TIFFTAG_SAMPLES_PER_PIXEL, - TIFFField.TIFF_SHORT, - 1, - new char[] { (char) numBands }); - - if (isTiled) { - directory.addField(XTIFF.TIFFTAG_TILE_WIDTH, - TIFFField.TIFF_LONG, - 1, - new long[] { tileWidth }); - - directory.addField(XTIFF.TIFFTAG_TILE_LENGTH, - TIFFField.TIFF_LONG, - 1, - new long[] { tileLength }); - - directory.addField(XTIFF.TIFFTAG_TILE_OFFSETS, - TIFFField.TIFF_LONG, - numTiles, - stripTileOffsets); - - directory.addField(XTIFF.TIFFTAG_TILE_BYTE_COUNTS, - TIFFField.TIFF_LONG, - numTiles, - stripTileByteCounts); - } else { - directory.addField(XTIFF.TIFFTAG_STRIP_OFFSETS, - TIFFField.TIFF_LONG, - numTiles, - stripTileOffsets); - - directory.addField(XTIFF.TIFFTAG_ROWS_PER_STRIP, - TIFFField.TIFF_LONG, - 1, - new long[] { tileLength }); - - directory.addField(XTIFF.TIFFTAG_STRIP_BYTE_COUNTS, - TIFFField.TIFF_LONG, - numTiles, - stripTileByteCounts); - } - - addIfAbsent(XTIFF.TIFFTAG_X_RESOLUTION, - TIFFField.TIFF_RATIONAL, - 1, - new long[][] { { 72, 1 } }); - - addIfAbsent(XTIFF.TIFFTAG_Y_RESOLUTION, - TIFFField.TIFF_RATIONAL, - 1, - new long[][] { { 72, 1 } }); - - addIfAbsent(XTIFF.TIFFTAG_RESOLUTION_UNIT, - TIFFField.TIFF_SHORT, - 1, - new char[] { (char) 2 }); - - if (colormap != null) { - directory.addField(XTIFF.TIFFTAG_COLORMAP, - TIFFField.TIFF_SHORT, - sizeOfColormap, - colormap); - } - - // Data Sample Format Extension fields. - if (dataTypeIsShort) { - // SampleFormat - int[] sampleFormat = new int[numBands]; - sampleFormat[0] = dataType == DataBuffer.TYPE_USHORT ? 1 : 2; - for (int b = 1; b < numBands; b++) { - sampleFormat[b] = sampleFormat[0]; - } - directory.addField(XTIFF.TIFFTAG_SAMPLE_FORMAT, - TIFFField.TIFF_SHORT, - numBands, - convertToChars(sampleFormat)); - - // SMinSampleValue: set to data type minimum. - int[] minValue = new int[numBands]; - minValue[0] = dataType == DataBuffer.TYPE_USHORT ? 0 - : Short.MIN_VALUE; - for (int b = 1; b < numBands; b++) { - minValue[b] = minValue[0]; - } - directory.addField(XTIFF.TIFFTAG_S_MIN_SAMPLE_VALUE, - TIFFField.TIFF_SHORT, - numBands, - convertToChars(minValue)); - - // SMaxSampleValue: set to data type maximum. - int[] maxValue = new int[numBands]; - maxValue[0] = dataType == DataBuffer.TYPE_USHORT ? 65535 - : Short.MAX_VALUE; - for (int b = 1; b < numBands; b++) { - maxValue[b] = maxValue[0]; - } - directory.addField(XTIFF.TIFFTAG_S_MAX_SAMPLE_VALUE, - TIFFField.TIFF_SHORT, - numBands, - convertToChars(maxValue)); - } - - } - - private char[] convertToChars(int[] shorts) { - char[] out = new char[shorts.length]; - for (int i = 0; i < shorts.length; i++) - out[i] = (char) shorts[i]; - return out; - } - - protected int getSampleSize() { - if (dataType == DataBuffer.TYPE_BYTE) - return 1; - else if (dataTypeIsShort) - return 2; - return 1; // what should go here? - } - - protected int getTileSize() { - return (int) (tileLength * tileWidth * numBands); - } - - private int writeImageData(RenderedImage im, OutputStream out) - throws IOException { - int total = 0; - - // Get the encoder - XTIFFTileCodec codec = directory.createTileCodec(tparam); - - // Create a buffer to hold the data - // to be written to the file, so we can use array writes. - int tsize = codec.getCompressedTileSize(im); - bpixels = new byte[tsize]; - - // Encode one tile at a time - Rectangle rect = new Rectangle(); - float minX = (float) im.getMinX(); - float minY = (float) im.getMinY(); - float rows = (float) tileLength; - float cols = (float) tileWidth; - int i = 0; - for (int row = 0; row < length; row += tileLength) { - for (int col = 0; col < width; col += tileWidth) { - if (!isTiled) - rows = Math.min(tileLength, length - row); - rect.setRect(minX + col, minY + row, cols, rows); - int tileSize = codec.encode(im, rect, bpixels); - out.write(bpixels, 0, tileSize); - stripTileOffsets[i] = currentOffset; - stripTileByteCounts[i++] = tileSize; - currentOffset += tileSize; - total += tileSize; - } - } - return total; - } - - private void writeDirectory(XTIFFField fields[], int nextIFDOffset) - throws IOException { - - if (currentOffset % 2 == 1) { - output.write(0); - currentOffset++; - } - - // 2 byte count of number of directory entries (fields) - int numEntries = fields.length; - - long offsetBeyondIFD = currentOffset + 12 * numEntries + 4 + 2; - Vector tooBig = new Vector(); - - XTIFFField field; - int tag; - int type; - int count; - - // Write number of fields in the IFD - writeUnsignedShort(numEntries); - - for (int i = 0; i < numEntries; i++) { - - field = fields[i]; - - // 12 byte field entry TIFFField - - // byte 0-1 Tag that identifies a field - tag = field.getTag(); - writeUnsignedShort(tag); - - // byte 2-3 The field type - type = field.getType(); - writeUnsignedShort(type); - - // bytes 4-7 the number of values of the indicated type - count = field.getCount(); - writeLong(count); - - // bytes 8 - 11 the value offset - if (count * sizeOfType[type] > 4) { - - // We need an offset as data won't fit into 4 bytes - writeLong(offsetBeyondIFD); - offsetBeyondIFD += (count * sizeOfType[type]); - tooBig.add(new Integer(i)); - - } else { - - writeValuesAsFourBytes(field); - } - - } - - // Address of next IFD - writeLong(nextIFDOffset); - - int index; - // Write the tag values that did not fit into 4 bytes - - for (int i = 0; i < tooBig.size(); i++) { - index = ((Integer) tooBig.elementAt(i)).intValue(); - writeValues(fields[index]); - } - } - - private static final int[] sizeOfType = { 0, // 0 = n/a - 1, // 1 = byte - 1, // 2 = ascii - 2, // 3 = short - 4, // 4 = long - 8, // 5 = rational - 1, // 6 = sbyte - 1, // 7 = undefined - 2, // 8 = sshort - 4, // 9 = slong - 8, // 10 = srational - 4, // 11 = float - 8 // 12 = double - }; - - private void writeValuesAsFourBytes(XTIFFField field) throws IOException { - - int dataType = field.getType(); - int count = field.getCount(); - - switch (dataType) { - - // unsigned 8 bits - case TIFFField.TIFF_BYTE: - byte bytes[] = field.getAsBytes(); - - for (int i = 0; i < count; i++) { - output.write(bytes[i]); - } - - for (int i = 0; i < (4 - count); i++) { - output.write(0); - } - - break; - - // unsigned 16 bits - case TIFFField.TIFF_SHORT: - char shorts[] = field.getAsChars(); - - for (int i = 0; i < count; i++) { - writeUnsignedShort((int) shorts[i]); - } - - for (int i = 0; i < (2 - count); i++) { - writeUnsignedShort(0); - } - - break; - - // unsigned 32 bits - case TIFFField.TIFF_LONG: - long longs[] = field.getAsLongs(); - - for (int i = 0; i < count; i++) { - writeLong(longs[i]); - } - break; - } - - } - - private void writeValues(XTIFFField field) throws IOException { - - int dataType = field.getType(); - int count = field.getCount(); - - switch (dataType) { - - // character data with NULL termination - case TIFFField.TIFF_ASCII: - String strings[] = field.getAsStrings(); - for (int i = 0; i < strings.length; i++) { - byte bytes[] = strings[i].getBytes(); - for (int j = 0; j < bytes.length; j++) { - output.write(bytes[j]); - } - if ((i + 1) < count) - output.write(0); - } - break; - - // unsigned 8 bits - case TIFFField.TIFF_BYTE: - byte bytes[] = field.getAsBytes(); - for (int i = 0; i < count; i++) { - output.write(bytes[i]); - } - break; - - // unsigned 16 bits - case TIFFField.TIFF_SHORT: - char shorts[] = field.getAsChars(); - for (int i = 0; i < count; i++) { - writeUnsignedShort((int) shorts[i]); - } - break; - - // unsigned 32 bits - case TIFFField.TIFF_LONG: - long longs[] = field.getAsLongs(); - for (int i = 0; i < count; i++) { - writeLong(longs[i]); - } - break; - - // IEEE 8-byte double - case TIFFField.TIFF_DOUBLE: - double doubles[] = field.getAsDoubles(); - for (int i = 0; i < count; i++) { - writeDouble(doubles[i]); - } - break; - - case TIFFField.TIFF_RATIONAL: - long rationals[][] = field.getAsRationals(); - for (int i = 0; i < count; i++) { - writeLong(rationals[i][0]); - writeLong(rationals[i][1]); - } - break; - - } - - } - - // Here s is never expected to have value greater than what can be - // stored in 2 bytes. - private void writeUnsignedShort(int s) throws IOException { - output.write((s & 0xff00) >>> 8); - output.write(s & 0x00ff); - } - - private void writeLong(long l) throws IOException { - output.write((int) ((l & 0xff000000) >>> 24)); - output.write((int) ((l & 0x00ff0000) >>> 16)); - output.write((int) ((l & 0x0000ff00) >>> 8)); - output.write(((int) l & 0x000000ff)); - } - - // write 8-byte IEEE double - private void writeDouble(double d) throws IOException { - long lval = Double.doubleToLongBits(d); - writeLong(lval >>> 32); - writeLong((lval & 0xffffffff)); - } - -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFLZWTileCodec.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFLZWTileCodec.java deleted file mode 100644 index 18d1814ed..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFLZWTileCodec.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.libtiff.jai.codecimpl; - -import java.awt.Rectangle; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFField; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.codec.XTIFFTileCodecImpl; -import org.libtiff.jai.util.JaiI18N; - -import com.sun.media.jai.codecimpl.TIFFLZWDecoder; - -/** - * This codec encapsulates all the logic for the TIFF "lzw" decoding codec - * algorithm. - */ -public class XTIFFLZWTileCodec extends XTIFFTileCodecImpl { - - private TIFFLZWDecoder lzwDecoder = null; - - // LZW compression related variable - int predictor; - int samplesPerPixel; - - /** - * Public constructor - */ - public XTIFFLZWTileCodec() {} - - /** - * Creation method - */ - public XTIFFTileCodec create() { - return new XTIFFLZWTileCodec(); - } - - // public boolean canEncode() {return true;} - - /** - * Registration method - */ - public void register() { - register(XTIFF.COMPRESSION_LZW); - } - - /** - * The initialization method particular to LZW decoding. - */ - public void initializeDecoding() { - // Get the number of samples per pixel - XTIFFField sfield = directory.getField(XTIFF.TIFFTAG_SAMPLES_PER_PIXEL); - if (sfield == null) { - samplesPerPixel = 1; - } else { - samplesPerPixel = (int) sfield.getAsLong(0); - } - XTIFFField predictorField = directory.getField(XTIFF.TIFFTAG_PREDICTOR); - - if (predictorField == null) { - predictor = 1; - } else { - predictor = predictorField.getAsInt(0); - if (predictor != 1 && predictor != 2) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder16")); - } - if (predictor == 2 && bitsPerSample[0] != 8) { - throw new RuntimeException(bitsPerSample[0] - + JaiI18N.getString("XTIFFImageDecoder17")); - } - } - lzwDecoder = new TIFFLZWDecoder(tileWidth, predictor, samplesPerPixel); - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, byte[] bdata) { - lzwDecoder.decode(input, bdata, newRect.height); - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, short[] sdata) { - - // Since unitsInThisTile is the number of shorts, - // but we do our decompression in terms of bytes, we - // need to multiply unitsInThisTile by 2 in order to - // figure out how many bytes we'll get after - // decompression. - byte byteArray[] = new byte[unitsInThisTile * 2]; - lzwDecoder.decode(input, byteArray, newRect.height); - unpackShorts(byteArray, sdata, unitsInThisTile); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFPackTileCodec.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFPackTileCodec.java deleted file mode 100644 index bfd5115cf..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFPackTileCodec.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.libtiff.jai.codecimpl; - -import java.awt.Rectangle; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.codec.XTIFFTileCodecImpl; -import org.libtiff.jai.util.JaiI18N; - -/** - * This codec encapsulates all the logic for the default TIFF "packbits" - * bit-packing codec algorithm. - */ -public class XTIFFPackTileCodec extends XTIFFTileCodecImpl { - - public XTIFFPackTileCodec() {} - - public XTIFFTileCodec create() { - return new XTIFFPackTileCodec(); - } - - public boolean canEncode() { - return false; - } - - public void register() { - register(XTIFF.COMPRESSION_PACKBITS); - } - - /** - * encode the tile into bpixels and return the byte size (uncompressed - * packing algorithm). The padding has already been done, so we may safely - * assume that pixels is exactly rows by cols by numBands ints. - */ - - public int encodeTilePixels(int[] pixels, Rectangle newRect, byte[] bpixels) { - return 0; - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, byte[] bdata) { - - if (bitsPerSample[0] == 8) { - decodePackbits(input, unitsInThisTile, bdata); - } else if (bitsPerSample[0] == 4) { - // Since the decompressed data will still be packed - // 2 pixels into 1 byte, calculate bytesInThisTile - int bytesInThisTile; - if ((newRect.width % 8) == 0) { - bytesInThisTile = (newRect.width / 2) * newRect.height; - } else { - bytesInThisTile = (newRect.width / 2 + 1) * newRect.height; - } - - decodePackbits(input, bytesInThisTile, bdata); - } - } - - /** - * Decode a rectangle of pixels - */ - public void decodeTilePixels(byte[] input, Rectangle newRect, short[] sdata) { - int bytesInThisTile = unitsInThisTile * 2; - byte byteArray[] = new byte[bytesInThisTile]; - decodePackbits(input, bytesInThisTile, byteArray); - unpackShorts(byteArray, sdata, unitsInThisTile); - } - - // Uncompress packbits compressed image data. - private byte[] decodePackbits(byte data[], int arraySize, byte[] dst) { - - if (dst == null) { - dst = new byte[arraySize]; - } - - int srcCount = 0, dstCount = 0; - byte repeat, b; - - try { - - while (dstCount < arraySize) { - - b = data[srcCount++]; - - if (b >= 0 && b <= 127) { - - // literal run packet - for (int i = 0; i < (b + 1); i++) { - dst[dstCount++] = data[srcCount++]; - } - - } else if (b <= -1 && b >= -127) { - - // 2 byte encoded run packet - repeat = data[srcCount++]; - for (int i = 0; i < (-b + 1); i++) { - dst[dstCount++] = repeat; - } - - } else { - // no-op packet. Do nothing - srcCount++; - } - } - } catch (java.lang.ArrayIndexOutOfBoundsException ae) { - throw new RuntimeException(JaiI18N.getString("XTIFFImageDecoder10")); - } - - return dst; - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFUncompTileCodec.java b/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFUncompTileCodec.java deleted file mode 100644 index 2030c81e5..000000000 --- a/src/core/src/main/java/org/libtiff/jai/codecimpl/XTIFFUncompTileCodec.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.libtiff.jai.codecimpl; - -import java.awt.Rectangle; - -import org.libtiff.jai.codec.XTIFF; -import org.libtiff.jai.codec.XTIFFTileCodec; -import org.libtiff.jai.codec.XTIFFTileCodecImpl; - -/** - * This codec encapsulates all the logic for the default TIFF "uncompressed" - * bit-packing codec algorithm. - */ -public class XTIFFUncompTileCodec extends XTIFFTileCodecImpl { - - public XTIFFUncompTileCodec() {} - - public XTIFFTileCodec create() { - return new XTIFFUncompTileCodec(); - } - - public boolean canEncode() { - return true; - } - - public void register() { - register(XTIFF.COMPRESSION_NONE); - } - - /** - * encode the tile into bpixels and return the byte size (uncompressed - * packing algorithm). The padding has already been done, so we may safely - * assume that pixels is exactly rows by cols by numBands ints. - */ - - public int encodeTilePixels(int[] pixels, Rectangle rect, byte[] bpixels) { - - int rows = (int) rect.getHeight(); - int cols = (int) rect.getWidth(); - int index/*, remainder*/; - int pixel = 0; - int k = 0; - int rowBytes = 0; - - switch (sampleSize[0]) { - - case 1: - - index = 0; - rowBytes = (cols + 7) / 8; - - // For each of the rows in a tile - for (int i = 0; i < rows; i++) { - - // Write out the number of pixels exactly - // divisible by 8 (bits per byte) - for (int j = 0; j < cols / 8; j++) { - - pixel = (pixels[index++] << 7) | (pixels[index++] << 6) - | (pixels[index++] << 5) | (pixels[index++] << 4) - | (pixels[index++] << 3) | (pixels[index++] << 2) - | (pixels[index++] << 1) | pixels[index++]; - bpixels[k++] = (byte) pixel; - } - - // Write out the pixels remaining after division by 8 - if (cols % 8 > 0) { - pixel = 0; - for (int j = 0; j < cols % 8; j++) { - pixel |= (pixels[index++] << (7 - j)); - } - bpixels[k++] = (byte) pixel; - } - } // row loop - break; - - case 4: - - index = 0; - rowBytes = (cols + 3) / 4; - - // For each of the rows in a strip - for (int i = 0; i < rows; i++) { - - // Write out the number of pixels that will fit into an - // even number of nibbles. - for (int j = 0; j < cols / 2; j++) { - pixel = (pixels[index++] << 4) | pixels[index++]; - bpixels[k++] = (byte) pixel; - } - - // Last pixel for odd-length lines - if ((cols % 2) != 0) { - pixel = pixels[index++] << 4; - bpixels[k++] = (byte) pixel; - } - } - break; - - case 8: - - index = 0; - rowBytes = cols * numBands; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols * numBands; j++) { - bpixels[k++] = (byte) pixels[index++]; - } - } - break; - - case 16: - - index = 0; - rowBytes = cols * 2; - int l = 0; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - short value = (short) pixels[index++]; - bpixels[l++] = (byte) ((value & 0xff00) >> 8); - bpixels[l++] = (byte) (value & 0x00ff); - } - } - break; - - } - return rows * rowBytes; - } - - /** - * Decompress data packed bytes into packed bytes - */ - public void decodeTilePixels(byte[] input, Rectangle rect, byte[] bpixels) { - for (int i = 0; i < unitsInThisTile; i++) { - bpixels[i] = input[i]; - } - } - - /** - * Decompress data packed bytes into short - */ - public void decodeTilePixels(byte[] input, Rectangle rect, short[] spixels) { - unpackShorts(input, spixels, unitsInThisTile); - } - -} diff --git a/src/core/src/main/java/org/libtiff/jai/operator/XTIFFDescriptor.java b/src/core/src/main/java/org/libtiff/jai/operator/XTIFFDescriptor.java deleted file mode 100644 index 3a212ed65..000000000 --- a/src/core/src/main/java/org/libtiff/jai/operator/XTIFFDescriptor.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.libtiff.jai.operator; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -// Sun does not expose this in the API, but -// its interface is described in the jai examples. -import java.awt.RenderingHints; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.ParameterBlock; -import java.awt.image.renderable.RenderedImageFactory; - -import javax.media.jai.JAI; -import javax.media.jai.OperationDescriptorImpl; -import javax.media.jai.OperationRegistry; - -import org.libtiff.jai.codecimpl.XTIFFCodec; -import org.libtiff.jai.codecimpl.XTIFFImage; - -import com.sun.media.jai.codec.ImageCodec; -import com.sun.media.jai.codec.SeekableStream; -import com.sun.media.jai.codec.TIFFDecodeParam; - -/** - * XTIFFDescriptor: A single class that is both an OperationDescriptor and a - * RenderedImageFactory for overriding the JAI "tiff" operation. - * - * @see XTIFFDirectory - * @see XTIFFTileCodecImpl - */ - -public class XTIFFDescriptor extends OperationDescriptorImpl implements - RenderedImageFactory { - - // The resource strings that provide the general documentation - // and specify the parameter list for the GeoTIFF operation. - private static final String[][] resources = { - { "GlobalName", "xtiff" }, - { "LocalName", "xtiff" }, - { "Vendor", "libtiff.org" }, - { "Description", "A TIFF parser, extending the TIFF operation." }, - { "DocURL", "http://www.geotiff.org/javadocs/XTIFFDescriptor.html" }, - { "Version", "1.0" }, { "arg0Desc", "param1" }, - { "arg1Desc", "param2" } }; - - // The parameter names for the GeoTIFF operation. Extenders may - // want to rename them to something more meaningful. - private static final String[] paramNames = { "stream", "param" }; - - // The class types for the parameters of the GeoTIFF operation. - // User defined classes can be used here as long as the fully - // qualified name is used and the classes can be loaded. - private static final Class[] paramClasses = { - com.sun.media.jai.codec.SeekableStream.class, - com.sun.media.jai.codec.TIFFDecodeParam.class }; - - // The default parameter values for the GeoTIFF operation - // when using a ParameterBlockJAI. - private static final Object[] paramDefaults = { null, null }; - - /** - * Standard public constructor - */ - public XTIFFDescriptor() { - super(resources, 0, paramClasses, paramNames, paramDefaults); - } - - /** - * Create an XTIFFImage with the given ParameterBlock if the XTIFFImage can - * handle the particular ParameterBlock. Otherwise, null image is returned. - */ - public RenderedImage create(ParameterBlock paramBlock, - RenderingHints renderHints) { - StringBuffer msg = new StringBuffer(); - if (!validateParameters(paramBlock, msg)) { - return null; - } - try { - SeekableStream in = (SeekableStream) paramBlock.getObjectParameter(0); - XTIFFImage image = new XTIFFImage(in, (TIFFDecodeParam) paramBlock.getObjectParameter(1), 0); - return image; - } catch (Exception e) { - return null; - } - } - - /** - * A convenience method for registering XTIFF methods into JAI, for extended - * classes of XTIFFDescriptor. - */ - public static void register(XTIFFDescriptor odesc) { - - OperationRegistry reg = JAI.getDefaultInstance().getOperationRegistry(); - - // override tiff operation - // reg.unregisterOperationDescriptor("tiff"); - - // ...and register tiff with the new desc - // reg.registerOperationDescriptor(odesc, "tiff"); - reg.registerDescriptor(odesc); - - // reg.registerRIF("tiff", "org.libtiff.jai", odesc); - - // re-register the tiff codec - // ImageCodec.unregisterCodec("tiff"); - ImageCodec.registerCodec(new XTIFFCodec()); - } - - /** - * A convenience method for registering the default XTIFF methods into JAI. - */ - public static void register() { - - // Create the objects - XTIFFDescriptor odesc = new XTIFFDescriptor(); - register(odesc); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/util/JaiI18N.java b/src/core/src/main/java/org/libtiff/jai/util/JaiI18N.java deleted file mode 100644 index a0fa5a622..000000000 --- a/src/core/src/main/java/org/libtiff/jai/util/JaiI18N.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.libtiff.jai.util; -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -public class JaiI18N { - - public static String getString(String key) { - return PropertyUtil.getString(key); - } -} diff --git a/src/core/src/main/java/org/libtiff/jai/util/PropertyUtil.java b/src/core/src/main/java/org/libtiff/jai/util/PropertyUtil.java deleted file mode 100644 index 6db69fe80..000000000 --- a/src/core/src/main/java/org/libtiff/jai/util/PropertyUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.libtiff.jai.util; - -/* - * XTIFF: eXtensible TIFF libraries for JAI. - * - * The contents of this file are subject to the JAVA ADVANCED IMAGING - * SAMPLE INPUT-OUTPUT CODECS AND WIDGET HANDLING SOURCE CODE License - * Version 1.0 (the "License"); You may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.sun.com/software/imaging/JAI/index.html - * - * 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 JAVA ADVANCED IMAGING SAMPLE INPUT-OUTPUT CODECS - * AND WIDGET HANDLING SOURCE CODE. - * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. - * Portions created by: Niles Ritter - * are Copyright (C): Niles Ritter, GeoTIFF.org, 1999,2000. - * All Rights Reserved. - * Contributor(s): Niles Ritter - */ - -import java.util.Locale; -import java.util.ResourceBundle; - -public class PropertyUtil { - - private static ResourceBundle b; - - /** Get bundle from .properties files in the package path */ - private static ResourceBundle getBundle() { - ResourceBundle bundle = null; - - try { - bundle = ResourceBundle.getBundle("org.libtiff.jai.codec.xtiff", Locale.US); - return bundle; - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - public static String getString(String key) { - if (b == null) { - b = getBundle(); - } - return b.getString(key); - } -} diff --git a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/add_16x16.png b/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/add_16x16.png deleted file mode 100644 index 414f91251..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/add_16x16.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/edit_16x16.png b/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/edit_16x16.png deleted file mode 100644 index 48ddf94f5..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/edit_16x16.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/push_16x16.png b/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/push_16x16.png deleted file mode 100644 index b8b046c6a..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/push_16x16.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/remov_16x16.png b/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/remov_16x16.png deleted file mode 100644 index 7b238038d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/dataAccess/mapTile/remov_16x16.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/event/Distance.gif b/src/core/src/main/resources/com/bbn/openmap/event/Distance.gif deleted file mode 100644 index 2411064b7..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/event/Distance.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/event/Gestures.gif b/src/core/src/main/resources/com/bbn/openmap/event/Gestures.gif deleted file mode 100644 index 0642f676c..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/event/Gestures.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/event/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/event/I18N.properties deleted file mode 100644 index 0bc57d515..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/event/I18N.properties +++ /dev/null @@ -1,11 +0,0 @@ -NavMouseMode.prettyName=Navigation - -NavMouseMode2.prettyName=Navigation - -DefaultOverviewMouseMode.prettyName=Navigation - -NullMouseMode.prettyName=None - -SelectMouseMode.prettyName=Gestures - -DistanceMouseMode.prettyName=Distance \ No newline at end of file diff --git a/src/core/src/main/resources/com/bbn/openmap/event/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/event/I18N_pl_PL.properties deleted file mode 100644 index 5de3de311..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/event/I18N_pl_PL.properties +++ /dev/null @@ -1,21 +0,0 @@ -NavMouseMode.prettyName=Nawigowanie po mapie - - - -NavMouseMode2.prettyName=Nawigowanie po mapie - - - -DefaultOverviewMouseMode.prettyName=Nawigowanie po mapie - - - -NullMouseMode.prettyName=None - - - -SelectMouseMode.prettyName=Wskazywanie obiekt\u00F3w - - - -DistanceMouseMode.prettyName=Namiar i odleg\u0142o\u015B\u0107 diff --git a/src/core/src/main/resources/com/bbn/openmap/event/Navigation.gif b/src/core/src/main/resources/com/bbn/openmap/event/Navigation.gif deleted file mode 100644 index 8ea26fdf0..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/event/Navigation.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/event/None.gif b/src/core/src/main/resources/com/bbn/openmap/event/None.gif deleted file mode 100644 index bab04673a..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/event/None.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/event/Pan.gif b/src/core/src/main/resources/com/bbn/openmap/event/Pan.gif deleted file mode 100644 index e5f0665eb..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/event/Pan.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/AddLayer.gif b/src/core/src/main/resources/com/bbn/openmap/gui/AddLayer.gif deleted file mode 100644 index feb829e04..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/AddLayer.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/BulbDone.gif b/src/core/src/main/resources/com/bbn/openmap/gui/BulbDone.gif deleted file mode 100644 index bb277759b..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/BulbDone.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/BulbOff.gif b/src/core/src/main/resources/com/bbn/openmap/gui/BulbOff.gif deleted file mode 100644 index 1f56839bf..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/BulbOff.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/BulbOn.gif b/src/core/src/main/resources/com/bbn/openmap/gui/BulbOn.gif deleted file mode 100644 index d97223449..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/BulbOn.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/BulbWorking.gif b/src/core/src/main/resources/com/bbn/openmap/gui/BulbWorking.gif deleted file mode 100644 index 44d482a30..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/BulbWorking.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/DeleteLayer.gif b/src/core/src/main/resources/com/bbn/openmap/gui/DeleteLayer.gif deleted file mode 100644 index 52b283e38..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/DeleteLayer.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/DoubleDown.gif b/src/core/src/main/resources/com/bbn/openmap/gui/DoubleDown.gif deleted file mode 100644 index 95dd45bd7..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/DoubleDown.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/DoubleUp.gif b/src/core/src/main/resources/com/bbn/openmap/gui/DoubleUp.gif deleted file mode 100644 index 28cf4e156..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/DoubleUp.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/Down.gif b/src/core/src/main/resources/com/bbn/openmap/gui/Down.gif deleted file mode 100644 index 627c0bb82..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/Down.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/gui/I18N.properties deleted file mode 100644 index b0156f35b..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/gui/I18N.properties +++ /dev/null @@ -1,64 +0,0 @@ -# Sample ResourceBundle properties file - -CoordPanel.border=Decimal Degrees -CoordPanel.lonlabel=Longitude:\ -CoordPanel.latlabel=Latitude:\ - -CombinedCoordPanel.closebutton=Close -CombinedCoordPanel.applybutton=Apply -CombinedCoordPanel.tabPane.mgrs=MRGS -CombinedCoordPanel.tabPane.decdeg=Dec Deg -CombinedCoordPanel.tabPane.dms=DMS -CombinedCoordPanel.tabPane.utm=UTM - -MGRSCoordPanel.border=MGRS Coordinate -MGRSCoordPanel.mgrsLabel=MGRS:\ - -DMSCoordPanel.border=Degrees|Minutes|Seconds -DMSCoordPanel.latlabel=Latitude DMS:\ -DMSCoordPanel.lonlabel=Longitude DMS:\ - -UTMCoordPanel.border=Zone Number|Hemisphere|Easting|Northing -UTMCoordPanel.zone.tooltip=Zone Number: 1-60 -UTMCoordPanel.hemi.tooltip=Hemisphere: N or S -UTMCoordPanel.utmLabel=UTM:\ - -CoordDialog.defaultTitle=Go To Coordinates - -CombinedCoordPanel.defaultComment=Set Center of Map to Coordinates: - -NavigatePanel.panNW.tooltip=Pan Northwest -NavigatePanel.panN.tooltip=Pan North -NavigatePanel.panNE.tooltip=Pan Northeast -NavigatePanel.panE.tooltip=Pan East -NavigatePanel.panSE.tooltip=Pan Southeast -NavigatePanel.panS.tooltip=Pan South -NavigatePanel.panSW.tooltip=Pan Southwest -NavigatePanel.panW.tooltip=Pan West -NavigatePanel.center.tooltip=Center Map at Starting Coords - -ZoomPanel.zoomin.tooltip=Zoom In -ZoomPanel.zoominfactor.tooltip=Zoom in X{0,number,#.##} -ZoomPanel.zoomout.tooltip=Zoom Out -ZoomPanel.zoomoutfactor.tooltip=Zoom out X{0,number,#.##} - -ScaleTextPanel.Scale.tooltip=Scale - -ProjectionStackTool.backTip=Go back to previous projection -ProjectionStackTool.forwardTip=Go forward to next projection -ProjectionStackTool.disabled=disabled - -LayerControlButtonPanel.moveLayerToTop=Move selected layer to top -LayerControlButtonPanel.moveLayerUpOne=Move selected layer up one -LayerControlButtonPanel.moveLayerToBottom=Move selected layer to bottom -LayerControlButtonPanel.moveLayerDownOne=Move selected layer down one -LayerControlButtonPanel.removeLayer=Remove selected layer -LayerControlButtonPanel.addLayer=Add a layer - -LayerPane.layerName.tooltip=Click to select layer - -LayerPane.onoffButton.tooltip=Turn "{0}" layer on/off - -LayerPane.paletteButton.paletteAvailable.tooltip=Display tools for "{0}" layer - -LayerPane.paletteButton.noPaletteAvailable.tooltip=No tools available for "{0}" layer diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/I18N_da_DK.properties b/src/core/src/main/resources/com/bbn/openmap/gui/I18N_da_DK.properties deleted file mode 100644 index d347770d4..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/gui/I18N_da_DK.properties +++ /dev/null @@ -1,91 +0,0 @@ -# Danish translation - -CoordPanel.border=Decimal Grader -CoordPanel.lonlabel=Længdegrad:\ -CoordPanel.latlabel=Bredegrad:\ - -CombinedCoordPanel.closebutton=Luk -CombinedCoordPanel.applybutton=Anvend -CombinedCoordPanel.tabPane.mgrs=MRGS -CombinedCoordPanel.tabPane.decdeg=Dec Deg -CombinedCoordPanel.tabPane.dms=DMS -CombinedCoordPanel.tabPane.utm=UTM - -MGRSCoordPanel.border=MGRS Koordinater -MGRSCoordPanel.mgrsLabel=MGRS:\ - -DMSCoordPanel.border=Grader|Minutter|Sekunder -DMSCoordPanel.latlabel=Breddegrad DMS:\ -DMSCoordPanel.lonlabel=Længdegrad DMS:\ - -UTMCoordPanel.border=Zone nummer|Hemisphere|Easting|Northing -UTMCoordPanel.zone.tooltip=Zone Nummer: 1-60 -UTMCoordPanel.hemi.tooltip=Hemisphere: N or S -UTMCoordPanel.utmLabel=UTM:\ - -CoordDialog.defaultTitle=Gå Til Koordinater - -CombinedCoordPanel.defaultComment=Set Kort Centrum Til Koordinater: - -NavigatePanel.panNW.tooltip=Pan Nord-vest -NavigatePanel.panN.tooltip=Pan Nord -NavigatePanel.panNE.tooltip=Pan Nord-øst -NavigatePanel.panE.tooltip=Pan Øst -NavigatePanel.panSE.tooltip=Pan Syd-øst -NavigatePanel.panS.tooltip=Pan Syd -NavigatePanel.panSW.tooltip=Pan Syd-vest -NavigatePanel.panW.tooltip=Pan Vest -NavigatePanel.center.tooltip=Centerer Kort på Start Koords - -ZoomPanel.zoomin.tooltip=Zoom ind -ZoomPanel.zoominfactor.tooltip=Zoom ind X{0,number,#.##} -ZoomPanel.zoomout.tooltip=Zoom ud -ZoomPanel.zoomoutfactor.tooltip=Zoom ud X{0,number,#.##} - -ScaleTextPanel.Scale.tooltip=Skala - - -NavigateMenu.navigate=Naviger -NavigateMenu.navigate.mnemonic=N - -NavigateMenu.zoomIn=Zoom ind - -NavigateMenu.zoomOut=Zoom ud - -LayerPane.clickToSelectLayer=Klik for at vælge lag -LayerPane.turnLayerOnOFF=Lag vis/gem -LayerPane.noPaletteAvailable=Ingen editor tilgængelig -LayerPane.paletteAvailable=Vis editor - - -LayersPanel.title=Lag - -LayerControlButtonPanel.moveLayerToTop=Flyt det valgte lag til toppen -LayerControlButtonPanel.moveLayerUpOne=Flyt det valgte lag en position op -LayerControlButtonPanel.moveLayerDownOne=Flyt det valgte lag en position ned -LayerControlButtonPanel.moveLayerToBottom=Flyt det valgte lag til bunden -LayerControlButtonPanel.removeLayer=Slet det valgte lag -LayerControlButtonPanel.addLayer=Tilf\u00F8j et lag - -LayersMenu.editLayersButtonTitle=Ret lag... -LayersMenu.addLayersButtonTitle=Tilf\u00F8j lag... - - -#GoToMenu.goto=G\u00E5 til -#GoToMenu.goto.mnemonic=G -GoToMenu.goto=Bogm\u00E6rker -GoToMenu.goto.mnemonic=B -GoToMenu.goOverData=G\u00E5 til data -GoToMenu.addSavedView=Tilføj bogm\u00E6rke... -GoToMenu.world=Verden -GoToMenu.nameOfView=Bogm\u00E6rke navn -GoToMenu.close=Luk -GoToMenu.addView=Tilf\u00F8j bogm\u00E6rke -GoToMenu.addViewTitle=Tilf\u00F8j bogm\u00E6rke - - -ScaleTextPanel.setScale.tooltip=Skala - -OMGraphicDeleteTool.deleteButton.tooltip=Slet det valgte objekt - -LayersPanel.layerButton.tooltip=Vis lag editor diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/gui/I18N_pl_PL.properties deleted file mode 100644 index 374c8f252..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/gui/I18N_pl_PL.properties +++ /dev/null @@ -1,80 +0,0 @@ -# Sample ResourceBundle properties file - -CoordPanel.border=Stopnie dziesi\u0119tne - -CoordPanel.lonlabel=D\u0142ugo\u015B\u0107:\ - -CoordPanel.latlabel=Szeroko\u015B\u0107:\ - -CombinedCoordPanel.closebutton=Rezygnuj - -CombinedCoordPanel.applybutton=Akceptuj - -CombinedCoordPanel.tabPane.mgrs=MRGS - -CombinedCoordPanel.tabPane.decdeg=\ \ \u00B0\ \ - -CombinedCoordPanel.tabPane.dms=\ \u00B0 ' "\ - -CombinedCoordPanel.tabPane.utm=UTM - -MGRSCoordPanel.border=MGRS wsp\u00F3\u0142rz\u0119dne - -MGRSCoordPanel.mgrsLabel=MGRS:\ - -DMSCoordPanel.border=Stopnie|Minuty|Sekundy - -DMSCoordPanel.latlabel=Szeroko\u015B\u0107 SMS:\ - -DMSCoordPanel.lonlabel=D\u0142ugo\u015B\u0107 SMS:\ - -UTMCoordPanel.border=Numer strefy|P\u00F3\u0142kula|Easting|Northing - -UTMCoordPanel.utmLabel=UTM:\ - -UTMCoordPanel.zone.tooltip=Numer strefy\: 1-60 - -UTMCoordPanel.hemi.tooltip=P\u00F3\u0142kula\: N lub S - -CoordDialog.defaultTitle=Skocz do lokalizacji - -CombinedCoordPanel.defaultComment=Ustaw wsp\u00F3\u0142rz\u0119dne \u015Brodka mapy: - -NavigatePanel.panNW.tooltip=Przesu\u0144 na p\u00F3\u0142nocny zach\u00F3d -NavigatePanel.panN.tooltip=Przesu\u0144 na p\u00F3\u0142noc -NavigatePanel.panNE.tooltip=Przesu\u0144 na p\u00F3\u0142nocny wsch\u00F3d -NavigatePanel.panW.tooltip=Przesu\u0144 na zach\u00F3d -NavigatePanel.panE.tooltip=Przesu\u0144 na wsch\u00F3d -NavigatePanel.panSW.tooltip=Przesu\u0144 na po\u0142udniowy zach\u00F3d -NavigatePanel.panS.tooltip=Przesu\u0144 na po\u0142udnie -NavigatePanel.panSE.tooltip=Przesu\u0144 na po\u0142udniowy wsch\u00F3d -NavigatePanel.center.tooltip=Wr\u00F3\u0107 na pocz\u0105tkow\u0105 pozycj\u0119 - -ProjectionStackTool.backTip=Przejd\u017A do poprzedniej pozycji -ProjectionStackTool.forwardTip=Przejd\u017A do nast\u0119pnej pozycji -ProjectionStackTool.disabled=niedost\u0119pne - -LayerControlButtonPanel.moveLayerToTop=Przesu\u0144 zaznaczon\u0105 warstw\u0119 na pocz\u0105tek -LayerControlButtonPanel.moveLayerUpOne=Przesu\u0144 zaznaczon\u0105 warstw\u0119 o 1 w g\u00F3r\u0119 -LayerControlButtonPanel.moveLayerToBottom=Przesu\u0144 zaznaczon\u0105 warstw\u0119 na koniec -LayerControlButtonPanel.moveLayerDownOne=Przesu\u0144 zaznaczon\u0105 warstw\u0119 o 1 w d\u00F3\u0142 -LayerControlButtonPanel.removeLayer=Usu\u0144 zaznaczon\u0105 warstw\u0119 -LayerControlButtonPanel.addLayer=Dodaj warstw\u0119 - -ZoomPanel.zoomin.tooltip=Powi\u0119ksz - -ZoomPanel.zoominfactor.tooltip=Powi\u0119ksz X{0,number,\#.\#\#} - -ZoomPanel.zoomoutfactor.tooltip=Pomniejsz X{0,number,\#.\#\#} - -ScaleTextPanel.Scale.tooltip=Skala - -ZoomPanel.zoomout.tooltip=Pomniejsz - -LayerPane.layerName.tooltip=Kliknij aby zaznaczy\u0107 warstw\u0119 - -LayerPane.onoffButton.tooltip=W\u0142\u0105cz/wy\u0142\u0105cz warstw\u0119\: "{0}" - -LayerPane.paletteButton.paletteAvailable.tooltip=Poka\u017C/schowaj okno ustawie\u0144 warstwy\: "{0}" - -LayerPane.paletteButton.noPaletteAvailable.tooltip=Okna ustawie\u0144 dla warstwy "{0}" nie istnieje diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOff.gif b/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOff.gif deleted file mode 100644 index 91f3d3b65..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOff.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOn.gif b/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOn.gif deleted file mode 100644 index 97cabe61f..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/PaletteOn.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/Up.gif b/src/core/src/main/resources/com/bbn/openmap/gui/Up.gif deleted file mode 100644 index 1099627aa..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/Up.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/backproj.gif b/src/core/src/main/resources/com/bbn/openmap/gui/backproj.gif deleted file mode 100644 index bf5439eaf..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/backproj.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/center.gif b/src/core/src/main/resources/com/bbn/openmap/gui/center.gif deleted file mode 100644 index 059ec079c..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/center.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/delete.gif b/src/core/src/main/resources/com/bbn/openmap/gui/delete.gif deleted file mode 100644 index 5d7bc2505..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/delete.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/dimbackproj.gif b/src/core/src/main/resources/com/bbn/openmap/gui/dimbackproj.gif deleted file mode 100644 index 1a38e65a9..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/dimbackproj.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/dimforwardproj.gif b/src/core/src/main/resources/com/bbn/openmap/gui/dimforwardproj.gif deleted file mode 100644 index e5f4e16bb..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/dimforwardproj.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/e.gif b/src/core/src/main/resources/com/bbn/openmap/gui/e.gif deleted file mode 100644 index 8afd45ea3..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/e.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/forwardproj.gif b/src/core/src/main/resources/com/bbn/openmap/gui/forwardproj.gif deleted file mode 100644 index 60cfe666c..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/forwardproj.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/green.gif b/src/core/src/main/resources/com/bbn/openmap/gui/green.gif deleted file mode 100644 index 2ceb6b196..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/green.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/grey.gif b/src/core/src/main/resources/com/bbn/openmap/gui/grey.gif deleted file mode 100644 index 08b4cb722..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/grey.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/layers.gif b/src/core/src/main/resources/com/bbn/openmap/gui/layers.gif deleted file mode 100644 index 666403963..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/layers.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N.properties deleted file mode 100644 index 4c24bad2d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N.properties +++ /dev/null @@ -1,8 +0,0 @@ -# Sample ResourceBundle properties file - -CoordsMenuItem.name=Coordinates... -CoordsMenuItem.combinedCoordDialog.title=Go To Coordinates... - -MouseModeMenu.mouseModeMenu=Mouse Mode - -ProjectionMenu.projectionMenu=Projection diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N_pl_PL.properties deleted file mode 100644 index 0e4b4e61b..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/gui/menu/I18N_pl_PL.properties +++ /dev/null @@ -1,11 +0,0 @@ -# Sample ResourceBundle properties file - - - -CoordsMenuItem.name=Wsp\u00F3\u0142rz\u0119dne ... - -CoordsMenuItem.combinedCoordDialog.title=Id\u017A do wsp\u00F3\u0142rz\u0119dnych ... - -MouseModeMenu.mouseModeMenu=Tryb pracy myszy - -ProjectionMenu.projectionMenu=Odwzorowanie diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/n.gif b/src/core/src/main/resources/com/bbn/openmap/gui/n.gif deleted file mode 100644 index b230b665d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/n.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/ne.gif b/src/core/src/main/resources/com/bbn/openmap/gui/ne.gif deleted file mode 100644 index 872134892..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/ne.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/nw.gif b/src/core/src/main/resources/com/bbn/openmap/gui/nw.gif deleted file mode 100644 index 39b235448..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/nw.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/overview.gif b/src/core/src/main/resources/com/bbn/openmap/gui/overview.gif deleted file mode 100644 index 8b47cee0e..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/overview.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/overviewHide.png b/src/core/src/main/resources/com/bbn/openmap/gui/overviewHide.png deleted file mode 100644 index eb2a98028..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/overviewHide.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/overviewHidePressed.png b/src/core/src/main/resources/com/bbn/openmap/gui/overviewHidePressed.png deleted file mode 100644 index f6cb63786..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/overviewHidePressed.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/overviewShow.png b/src/core/src/main/resources/com/bbn/openmap/gui/overviewShow.png deleted file mode 100644 index bbe6f6300..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/overviewShow.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/overviewShowPressed.png b/src/core/src/main/resources/com/bbn/openmap/gui/overviewShowPressed.png deleted file mode 100644 index 4be8387f6..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/overviewShowPressed.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/plus.gif b/src/core/src/main/resources/com/bbn/openmap/gui/plus.gif deleted file mode 100644 index 941407583..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/plus.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/red.gif b/src/core/src/main/resources/com/bbn/openmap/gui/red.gif deleted file mode 100644 index f9b55ad0d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/red.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/s.gif b/src/core/src/main/resources/com/bbn/openmap/gui/s.gif deleted file mode 100644 index 7f4842dc3..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/s.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/se.gif b/src/core/src/main/resources/com/bbn/openmap/gui/se.gif deleted file mode 100644 index 7bd0c8682..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/se.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/sw.gif b/src/core/src/main/resources/com/bbn/openmap/gui/sw.gif deleted file mode 100644 index 755f8bde0..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/sw.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/pause.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/pause.png deleted file mode 100644 index 3e06a5d15..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/pause.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/playbackward.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/playbackward.png deleted file mode 100644 index 0cd07d9b6..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/playbackward.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/playforward.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/playforward.png deleted file mode 100644 index 3f8232918..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/playforward.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/stepbackward.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/stepbackward.png deleted file mode 100644 index f80abe064..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/stepbackward.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/stepforward.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/stepforward.png deleted file mode 100644 index 7a516f15d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/stepforward.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/timergreen.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/timergreen.png deleted file mode 100644 index fde4e0f34..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/timergreen.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/timeroff.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/timeroff.png deleted file mode 100644 index d24aef049..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/timeroff.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/time/timerred.png b/src/core/src/main/resources/com/bbn/openmap/gui/time/timerred.png deleted file mode 100644 index 69a6f720d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/time/timerred.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/w.gif b/src/core/src/main/resources/com/bbn/openmap/gui/w.gif deleted file mode 100644 index ff40b06e5..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/w.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/zoomIn.gif b/src/core/src/main/resources/com/bbn/openmap/gui/zoomIn.gif deleted file mode 100644 index ce99d5c8d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/zoomIn.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/gui/zoomOut.gif b/src/core/src/main/resources/com/bbn/openmap/gui/zoomOut.gif deleted file mode 100644 index 5ea29dedd..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/gui/zoomOut.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/layer/I18N.properties deleted file mode 100644 index 6d3a9db3d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/I18N.properties +++ /dev/null @@ -1,89 +0,0 @@ -GraticuleLayer.10DegreeColor.tooltip = Color of the ten degree graticule lines. - -GraticuleLayer.10DegreeColor = 10 degree color - -GraticuleLayer.5DegreeColor.tooltip = Color of the five degree graticule lines. - -GraticuleLayer.5DegreeColor = 5 degree color - -GraticuleLayer.1DegreeColor.tooltip = Color of the one degree graticule lines. - -GraticuleLayer.1DegreeColor = 1 degree color - -GraticuleLayer.equatorColor.tooltip = Color of the Equator. - -GraticuleLayer.equatorColor = Equator color - -GraticuleLayer.datelineColor.tooltip = Color of the Date line. - -GraticuleLayer.datelineColor = Dateline color - -GraticuleLayer.specialLineColor.tooltip = Color of Tropic of Cancer, Capricorn lines. - -GraticuleLayer.specialLineColor = Special line color - -GraticuleLayer.textColor.tooltip = Color of the line label text. - -GraticuleLayer.textColor = Text color - -GraticuleLayer.threshold.tooltip = The number of lines showing before finer grain lines appear. - -GraticuleLayer.threshold = Threshold - -GraticuleLayer.showRuler.tooltip = Show the one and five degree lines. - -GraticuleLayer.showRuler = Ruler - -GraticuleLayer.show1And5Lines.tooltip = Show the line label text. - -GraticuleLayer.show1And5Lines = Show 1, 5 degree lines - -GraticuleLayer.fontSize.tooltip = The size of the font, in points, of the line labels. - -GraticuleLayer.fontSize = Font size - - - -GraticuleLayer.layerPanel=Graticule Layer Options - -GraticuleLayer.showRulerButton=Show Lat/Lon Labels - -GraticuleLayer.show15Button=Show 1, 5 Degree Lines - -GraticuleLayer.setProperties=Preferences - -GraticuleLayer.redraw=Redraw Graticule Layer - -DrawingToolLayer.Save_As_Shape_File=Save As Shape File - -DrawingToolLayer.Save_Layer_Graphics=Save Layer Graphics - -DrawingToolLayer.CLICK_TO_EDIT=Click to Edit - -DrawingToolLayer.QUERY_HEADER=What would you like to do? - -DrawingToolLayer.SAVE_MAP=Save map - -DrawingToolLayer.SHAPE_SAVE_MAP=Save map as Shape file(s) - -DrawingToolLayer.SHAPE_ERROR_MESSAGE=There's nothing on the map for this layer to save. - -DrawingToolLayer.RELOAD=Re-load map from file - -DrawingToolLayer.PREFERENCES=Change preferences - -DrawingToolLayer.CHOOSE_SAVE=Choose file to use to save layer\: - -DrawingToolLayer.LOAD_ERROR=The file doesn't appear to be a valid map file - -DrawingToolLayer.OK.tooltip=Do action and dismiss window. - -DrawingToolLayer.Cancel.tooltip=Do nothing and dismiss window. - -DrawingToolLayer.Apply.tooltip=Do action and leave window up. - -DrawingToolLayer.OK=OK - -DrawingToolLayer.Cancel=Cancel - -DrawingToolLayer.Apply=Apply diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/I18N_da_DK.properties b/src/core/src/main/resources/com/bbn/openmap/layer/I18N_da_DK.properties deleted file mode 100644 index 7b0d2ef39..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/I18N_da_DK.properties +++ /dev/null @@ -1,2 +0,0 @@ -DrawingToolLayer.infoText.tooltip=Klik for at rette. - diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/layer/I18N_pl_PL.properties deleted file mode 100644 index 1d5c05cec..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/I18N_pl_PL.properties +++ /dev/null @@ -1,89 +0,0 @@ - -GraticuleLayer.equatorColor.tooltip=Pozwala zmieni\u0107 kolor linii r\u00F3wnika - -GraticuleLayer.specialLineColor.tooltip=Kolor zwrotnik\u00F3w Raka i Kozioro\u017Cca - -GraticuleLayer.10DegreeColor.tooltip=Pozwala zmieni\u0107 kolor linii siatki (10 stopni) - -GraticuleLayer.5DegreeColor.tooltip=Pozwala zmieni\u0107 kolor linii siatki (5 stopni) - -GraticuleLayer.1DegreeColor.tooltip=Pozwala zmieni\u0107 kolor linii siatki (1 stopie\u0144) - -GraticuleLayer.datelineColor=Po\u0142udnik zerowy - -GraticuleLayer.datelineColor.tooltip=Kolor po\u0142udnika zerowego - -GraticuleLayer.specialLineColor=Linie specjalne - -GraticuleLayer.textColor.tooltip=Pozwala zmieni\u0107 kolor tekstu na etykietach - -GraticuleLayer.textColor=Kolor tekstu - -GraticuleLayer.fontSize=Rozmiar czcionki - -GraticuleLayer.show1And5Lines=Etykiety 1 i 5 stopni - -GraticuleLayer.show1And5Lines.tooltip=Pozwala na ukrycie etykiet reprezentuj\u0105cych 1 i 5 stopni - -GraticuleLayer.showRuler.tooltip=Pozwala na ukrycie linii reprezentuj\u0105cych 1 i 5 stopni - -GraticuleLayer.showRuler=Linie 1 i 5 stopni - -GraticuleLayer.fontSize.tooltip=Ustawia rozmiar czcionki na etyietach - -GraticuleLayer.equatorColor=R\u00F3wnik - -GraticuleLayer.1DegreeColor=Linie siatki (1 stopie\u0144) - -GraticuleLayer.5DegreeColor=Linie siatki (5 stopni) - -GraticuleLayer.10DegreeColor=Linie siatki (10 stopni) - -GraticuleLayer.threshold.tooltip=Pokazywana liczba linii, zanim mniejsze zaczn\u0105 si\u0119 pojawia\u0107 - -GraticuleLayer.threshold=Linie - -GraticuleLayer.layerPanel=Opcje warstwy siatki - -GraticuleLayer.showRulerButton=Etykiety szeroko\u015B\u0107/dlugo\u015B\u0107 - -GraticuleLayer.show15Button=Linie 1 i 5 stopni - -GraticuleLayer.setProperties=Ustawienia - -GraticuleLayer.redraw=Od\u015Bwie\u017C warstw\u0119 siatki - -DrawingToolLayer.Save_As_Shape_File=Zapisz jako plik kszta\u0142tu - -DrawingToolLayer.Save_Layer_Graphics=Zapisz warstw\u0119 graficzn\u0105 - -DrawingToolLayer.CLICK_TO_EDIT=Kliknij aby edytowa\u0107 - -DrawingToolLayer.QUERY_HEADER=Wybierz operacj\u0119 - -DrawingToolLayer.SAVE_MAP=Zapisz map\u0119 - -DrawingToolLayer.SHAPE_SAVE_MAP=Zapisz map\u0119 w formacie Shape - -DrawingToolLayer.SHAPE_ERROR_MESSAGE=W warstwie nie ma \u017Cadnych obiekt\u00F3w do zapisu. - -DrawingToolLayer.RELOAD=Odczytaj ponownie z pliku - -DrawingToolLayer.PREFERENCES=Zmie\u0144 ustawienia - -DrawingToolLayer.CHOOSE_SAVE=Wybierz plik do zapisu warstwy\: - -DrawingToolLayer.LOAD_ERROR=Wybrano plik w niew\u0142a\u015Bciwym formacie - -DrawingToolLayer.OK.tooltip=Wykonaj operacj\u0119 i zamknij okno - -DrawingToolLayer.Cancel.tooltip=Zamknij okno - -DrawingToolLayer.Apply.tooltip=Wykonaj operacj\u0119 i pozostaw okno otwarte - -#OK -DrawingToolLayer.OK=OK - -DrawingToolLayer.Cancel=Rezygnuj - -DrawingToolLayer.Apply=Zastosuj diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/fighter.gif b/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/fighter.gif deleted file mode 100644 index fe309b4a4..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/fighter.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/openmap.properties b/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/openmap.properties deleted file mode 100644 index 673207806..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/openmap.properties +++ /dev/null @@ -1,443 +0,0 @@ -# ********************************************************************** -# -# -# -# BBN Technologies, a Verizon Company -# 10 Moulton Street -# Cambridge, MA 02138 -# (617) 873-8000 -# -# Copyright (C) BBNT Solutions LLC. All rights reserved. -# -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/examples/beanbox/openmap.properties,v $ -# $RCSfile: openmap.properties,v $ -# $Revision: 1.1.1.1 $ -# $Date: 2003/02/14 21:35:48 $ -# $Author: dietrick $ -# -# ********************************************************************** -# -# WHAT IS THIS FILE? -# -# This is a generic OpenMap properties file, which controls how -# components are loaded into the OpenMap application. It specifies -# the initial projection the map should have when OpenMap is started, -# the layers that should be available, which ones should be turned on, -# and lets you adjust all the layers' attributes for their startup -# configuration. Most importantly, this file also lets you add and -# remove different components from the application itself. You can -# modify it with any text editor you like. -# -# WHAT ARE PROPERTIES? -# -# Java properties are a set of key=value pairs. The key is the name -# of the thing you are setting, and the value is what you are setting -# it to. There are a couple of things to look for that we do with key -# values in this properties file. -# -# First, all the properties that can be set for a component are -# *hopefully* listed in the Javadocs (Java API documentation). If a -# component is specified as a com.bbn.openmap.PropertyConsumer, it -# will be given a change to configure itself based on the settings -# within the properties file. Components can be layers or any other -# part of the OpenMap application. -# -# Secondly, the keys are scoped to focus the value to a specific -# instance of a components. If there are more that one layer of a -# specific type (say, two ShapeLayers, one for roads and one for -# rivers), the names of they keys will have a different prefix for the -# key. For instance, ShapeLayers have a lineColor attribute you can -# set in this file, and the value used is a hexidecimal value for an -# ARGB color (transparency (A), red (R), green (G), blue (B)): -# -# For a red, non-transparent color for the line. -# lineColor=FFFF0000 -# -# But there are two layers - to scope the property for different -# layers, a prefix must be added to the property, separated by a '.': -# -# roads.lineColor=FFFF0000 -# rivers.lineColor=FF0000FF -# -# In this case, the roads layer has a red line color and the rivers -# layer has a blue line color. The prefix 'roads' and 'rivers' is -# something picked to your liking and used only within this property -# file, and is referred to in OpenMap documentation as a marker name. -# Marker names are first used in a list - the openmap.layers property -# is a perfect example: -# -# openmap.layers=first second third -# -# In this example, I've chosen first, second and third to be marker -# names of three different layers. Later in the properties file, I -# would use these marker names to define the layers and each layer's -# attributes. For the 'first' layer, I'll define a ShapeLayer: -# -# # All layers require a class name that defines which one to use -# first.class=com.bbn.openmap.layer.shape.ShapeLayer -# -# # And a pretty name to use in the GUI -# first.prettyName=Roads -# -# # Now come properties that are particular to ShapeLayers: -# -# # These first two are mandatory for the ShapeLayer: -# first.shapeFile= -# first.spatialIndex= -# -# # These are optional, and override the defaults set in the ShapeLayer: -# first.lineColor=FFFF0000 -# first.lineWidth=2 -# -# You do this for each layer listed. To add a layer to the -# application, you make up a marker name, add it to the list, and then -# define a set of properties for it using the marker name as a prefix. -# - -# This marker name list paradigm is used throughout the properties -# file. It's an important concept to understand before modifying this -# file. -# -# HOW MANY PROPERTIES FILES ARE THERE? -# -# OpenMap looks for this file in several different places. When it -# finds one, it loads all the properties, and moves on. If two -# properties have the same key, the last version read wins. The most -# important place to keep a version of the openmap.properties file is -# a personalized one in your home directory or profile directory. -# This is the last one read. It also lets you personalize your -# application setup and not affect anyone else using the OpenMap -# installation. -# -# OK, lets define the map! -# -########################################################### -# These properties define the formatters the Simple Http -# Image Server uses. The default formatter is the first one -# in the list. -# The layers property can be used to override the -# openmap.startUpLayers property as the default layers. -########################################################### - -formatters=gif jpeg -gif.class =com.bbn.openmap.image.AcmeGifFormatter -jpeg.class=com.bbn.openmap.image.SunJPEGFormatter -#layers=date drawing daynight graticule shapePolitical tz - - -# ################################################### -# These properties define the starting projection of the map. -# These properties are listed in com.bbn.openmap.Environment.java, -# and affect the initialization of the application. -# ################################################### - -# Latitude and longitude in decimal degrees -openmap.Latitude=41.5f -openmap.Longitude=-71f -# Scale: zoom level (1:scale) -openmap.Scale=10000000f - -# Projection type to start the map with. Try "cadrg", "orthographic", -# which are projection IDs. Check a particular projection class for -# it's ID string. -openmap.Projection=mercator - -# Width and Height of map, in pixels -openmap.Width=800 -openmap.Height=600 - -# Change this for a different title in the main window. -openmap.Title=OpenMap(tm) - -# pixel X/Y window position (if values < 0, then center window on screen) -openmap.x=-1 -openmap.y=-1 - -# The background color of the map, in hex AARRGGBB values (AA is -# transparancy, RR, GG and BB are red, green and blue in hex values -# between 00-FF (0-255)). -openmap.BackgroundColor=FF89C5F9 - -# Here is a property that lets you add debug statements to the -# application, to get more informative printouts detailing what is -# going on in the application. Each source file may Debug statements -# throughout it (Debug.debugging("keyword") or -# Debug.message("keyword", "statement")), and you can turn those -# statements on by adding those keywords to this list. Follows the -# marker name paradigm, with space-separated names. -#openmap.Debug=basic - -# Ironically, the "properties" property, which details where the -# PropertyHandler is looking for its properties, won't work here. - -# ################################################### -# These are miscellaneous variables for the OpenMap application. -# ################################################### -# How to lauch a browser to display additional information. -# Windows example: openmap.WebBrowser=C:\\program files\\internet explorer\\iexplore.exe -openmap.WebBrowser=/usr/bin/netscape -install -# Used for creating web pages for the browser -openmap.TempDirectory=/tmp -# Help web pages -openmap.HelpURL=http://openmap.bbn.com/doc/user-guide.html -# Use internal frames as an application - used to be gui.UseInternalFrames -openmap.UseInternalFrames=false - -# OpenMap has a Debug messaging mechanism that lets you set certain -# keywords as environment variables (-Ddebug.keyword) to enable -# printouts from different objects. The code contains these keywords, -# and by looking at a classes' code, you can figure out what the -# keywords are (look for Debug.message("keyword", "message") and 'if -# (Debug.debugging("keyword")' statements). You can enable these -# messages by putting those keywords in a space-separated list in this -# property. If you don't want extra messages, you can ignore this -# property and leave it empty. - -#openmap.Debug= - -# You may be trying to run OpenMap as an applet, with the data files -# in their own jar file. It's difficult to get the applet to look in -# a data jar file if there are no classes in it (I couldn't find a -# solution to this). So, OpenMap now has a workaround. You can use -# the com.bbn.openmap.io.AppletDataNugget class to create a -# package-less, empty class to put at the root of your data jar file -# (JavaDocs contains instructions, and there is a usage statement -# printout if you run the class). It might be good practice to name -# this class the same name as the jar file itself. Put the name of -# the class (or classes) that is in the data jar file in this list, -# and the BinaryFile will be able to find it. If you aren't running -# as an applet, or your data is not in a jar file by itself, you don't -# need to use this property. - -#openmap.appletDataNuggets= - -# ################################################### -# These properties define the general components to use in the -# application, OTHER than layers. Notice the marker name list. You -# can add and removed parts of the application here, simply by -# adjusting this marker name list and adding properties for that -# marker name. Note the order in which menu objects are important, -# except helpMenu which is always adjusted to be the last menu item. -# -# If you want to remove components from the application, simply remove -# the marker name from the openmap.components list. You don't have to -# delete the class definition property, too. If you want to add a -# component to the list, add the marker name to the openmap.components -# list when you want it to be created and added relative to the other -# components, and then add a 'marker name'.class property for that -# component to this file. -# ################################################### - -openmap.components=frame menuBar informationDelegator fileMenu helpMenu controlMenu navigateMenu layersMenu helpUserMenuItem toolBar omToolSet omdrawingtool layersPanel omdtl overviewMapHandler layerHandler dropSupport mouseModePanel mouseDelegator navMouseMode selectMouseMode distanceMouseMode nullMouseMode omlineloader projectionstack projectionstacktool omcircleloader omrectloader ompointloader ompolyloader goto addlayer dndCatcher beanpanel - -frame.class=com.bbn.openmap.gui.OpenMapFrame -layerHandler.class=com.bbn.openmap.LayerHandler -toolBar.class=com.bbn.openmap.gui.ToolPanel -omToolSet.class=com.bbn.openmap.gui.OMToolSet -layersPanel.class=com.bbn.openmap.gui.LayersPanel -overviewMapHandler.class=com.bbn.openmap.gui.OverviewMapHandler -layersMenu.class=com.bbn.openmap.gui.LayersMenu -menuPanel.class=com.bbn.openmap.gui.MenuPanel -mouseModePanel.class=com.bbn.openmap.gui.MouseModePanel -informationDelegator.class=com.bbn.openmap.InformationDelegator -mouseDelegator.class=com.bbn.openmap.MouseDelegator -navMouseMode.class=com.bbn.openmap.event.NavMouseMode2 -selectMouseMode.class=com.bbn.openmap.event.SelectMouseMode -distanceMouseMode.class=com.bbn.openmap.event.DistanceMouseMode -nullMouseMode.class=com.bbn.openmap.event.NullMouseMode -menuBar.class=com.bbn.openmap.gui.MenuBar -fileMenu.class=com.bbn.openmap.gui.FileMenu -helpMenu.class=com.bbn.openmap.gui.DefaultHelpMenu -controlMenu.class=com.bbn.openmap.gui.ControlMenu -navigateMenu.class=com.bbn.openmap.gui.NavigateMenu -helpUserMenuItem.class=com.bbn.openmap.gui.UserGuideMenuItems -omdrawingtool.class=com.bbn.openmap.tools.drawing.OMDrawingTool -omlineloader.class=com.bbn.openmap.tools.drawing.OMLineLoader -omcircleloader.class=com.bbn.openmap.tools.drawing.OMCircleLoader -omrectloader.class=com.bbn.openmap.tools.drawing.OMRectLoader -ompointloader.class=com.bbn.openmap.tools.drawing.OMPointLoader -ompolyloader.class=com.bbn.openmap.tools.drawing.OMPolyLoader -projectionstack.class=com.bbn.openmap.proj.ProjectionStack -projectionstacktool.class=com.bbn.openmap.gui.ProjectionStackTool -omdtl.class=com.bbn.openmap.tools.drawing.OMDrawingToolLauncher -addlayer.class=com.bbn.openmap.gui.LayerAddPanel -goto.class=com.bbn.openmap.gui.GoToMenu -goto.addDefaults=true -dropSupport.class=com.bbn.openmap.tools.dnd.DropListenerSupport -dndCatcher.class=com.bbn.openmap.tools.beanbox.BeanBoxDnDCatcher -beanpanel.class=com.bbn.openmap.tools.beanbox.BeanPanel - -# ################################################### -# Properties defined for the BeanPanel component -# ################################################### - -beanpanel.beans.path=lib -beanpanel.tabs=tab1 tab2 tab3 -beanpanel.tab1.name=Generic -beanpanel.tab1.beans=com.bbn.openmap.layer.beanbox.SimpleBeanObject -beanpanel.tab2.name=Container -beanpanel.tab2.beans=com.bbn.openmap.layer.beanbox.SimpleBeanContainer -beanpanel.tab3.name=Military -beanpanel.tab3.beans=com.bbn.openmap.layer.beanbox.Fighter - -# ################################################### -# Properties defined for the overview map handler. -# ################################################### - -# marker name list, layer defined later -overviewLayers=overviewLayer -# how zoomed out to keep the overview map versus the main map -overviewScaleFactor=10f -# when to stop zooming in -overviewMinScale=10000000f -# the layer to use to render on top, showing where the main map covers. -overviewStatusLayer=com.bbn.openmap.layer.OverviewMapAreaLayer - -# ################################################### -# You can refer to other properties files and have their properties -# loaded as well. This is good for defining a set of layers that work -# with a particular type of data, for instance, and then override some -# of those properties defined in those files to localize them for your -# setup. This works with a marker name list. By default, nothing defined. -# ################################################### - -#openmap.include=include1 include2 -#include1.URL= -#include2.URL= - -# ################################################### -# Here is the list of layers to add to the map. The properties for -# each marker name are defined later. -# -# If you want to remove a layer from the application, remove its -# marker name from the openmap.layers property list. You do not have -# to delete all of its properties as well. -# -# If you want to add a layer to the application, add it's marker name -# to the openmap.layers property list, and then add its properties to -# this file. As a minimum, Layers all need a 'marker name'.class -# property, and a 'marker name'.prettyName property (for the GUI -# components). Consult the JavaDocs for a layer to see what other -# properties can be set for that layer. -# ################################################### - -# Layers listed here appear on the Map in the order of their names. -openmap.layers=simpleBeanLayer date daynight graticule shapePolitical - -# These layers are turned on when the map is first started. Order -# does not matter here... -openmap.startUpLayers=simpleBeanLayer graticule shapePolitical - - -# ################################################### -# These are the properties for individual layers. Consult the -# javadocs (Java API pages) for the individual layers for options. -# ################################################### - -### Layer used by the overview handler -overviewLayer.class=com.bbn.openmap.layer.shape.ShapeLayer -overviewLayer.prettyName=Overview -overviewLayer.shapeFile=data/shape/dcwpo-browse.shp -overviewLayer.spatialIndex=data/shape/dcwpo-browse.ssx -overviewLayer.lineColor=ff000000 -overviewLayer.fillColor=ffbdde83 - -### ShapeFile layers -shapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -shapePolitical.prettyName=Political Boundaries -# Specify shapefile and spatial-index file as a filename or pathname. -# If the former, you must reference the directory where this file -# lives in your CLASSPATH -shapePolitical.shapeFile=data/shape/dcwpo-browse.shp -shapePolitical.spatialIndex=data/shape/dcwpo-browse.ssx -# Colors (32bit ARGB) -shapePolitical.lineColor=ff000000 -shapePolitical.fillColor=ffbdde83 - -### Graticule layer -graticule.class=com.bbn.openmap.layer.GraticuleLayer -graticule.prettyName=Graticule -# Show lat / lon spacing labels -graticule.showRuler=true -graticule.show1And5Lines=true -# Controls when the five degree lines and one degree lines kick in -#- when there is less than the threshold of ten degree lat or lon -#lines, five degree lines are drawn. The same relationship is there -#for one to five degree lines. -graticule.threshold=2 -# the color of 10 degree spaing lines (ARGB) -graticule.10DegreeColor=99000000 -# the color of 5 degree spaing lines (ARGB) -graticule.5DegreeColor=99009900 -# the color of 1 degree spaing lines (ARGB) -graticule.1DegreeColor=99003300 -# the color of the equator (ARGB) -graticule.equatorColor=99FF0000 -# the color of the international dateline (ARGB) -graticule.dateLineColor=99000000 -# the color of the special lines (ARGB) -graticule.specialLineColor=99000000 -# the color of the labels (ARGB) -graticule.textColor=99000000 - - -### Date & Time layer -date.class=com.bbn.openmap.layer.DateLayer -date.prettyName=Date & Time -# display font as a Java font string -date.font=SansSerif-Bold -# like XWindows geometry: [+-]X[+-]Y, `+' indicates relative to -# left edge or top edges, `-' indicates relative to right or bottom -# edges, XX is x coordinate, YY is y coordinate -date.geometry=+20+30 -# background rectangle color ARGB -date.color.bg=ff808080 -# foreground text color ARGB -date.color.fg=ff000000 -# date format (using java.text.SimpleDateFormat patterns) -date.date.format=EEE, d MMM yyyy HH:mm:ss z - - -### Day/Night shading layer properties -daynight.class=com.bbn.openmap.layer.daynight.DayNightLayer -daynight.prettyName=Day/Night Shading -# draw terminator as poly (faster calculation than image, defaults to -# true). -daynight.doPolyTerminator=true -# number of vertices for polygon terminator line. this is only valid -# if doPolyTerminator is true... -daynight.terminatorVerts=512 -# termFade - the distance of the transition of fade, as a percentage of PI. -daynight.termFade=.1 -# currentTime - true to display the shading at the computer's current time. -daynight.currentTime=true -# updateInterval - time in milliseconds between updates. currentTime has to be -# true for this to be used. 1000*60*5 = 300000 = 5min updates -daynight.updateInterval=300000 -# Shading Colors (32bit ARGB) -daynight.nighttimeColor=64000000 -daynight.daytimeColor=00FFFFFF - - -### VMAP Political layer -vmapPolitical.class=com.bbn.openmap.layer.vpf.VPFLayer -vmapPolitical.prettyName=VMAP Political -vmapPolitical.vpfPath=data/vmap/vmaplv0 -vmapPolitical.coverageType=bnd -vmapPolitical.featureTypes=edge area text -# just display coastlines and political boundaries -#vmapPolitical.edge= polbndl coastl depthl -vmapPolitical.edge= polbndl coastl -# just display political areas and not oceans -#vmapPolitical.area= oceansea polbnda -vmapPolitical.area= polbnda - -# Use this property for a better focus on feature types, especially -# for more fine-grained databases -#vmapPolitical.searchByFeature=true - -simpleBeanLayer.class=com.bbn.openmap.layer.beanbox.SimpleBeanLayer -simpleBeanLayer.prettyName=Simple Bean Layer diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebean.gif b/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebean.gif deleted file mode 100644 index 7263b47c1..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebean.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebeancontainer.gif b/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebeancontainer.gif deleted file mode 100644 index 2e651359d..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/layer/beanbox/simplebeancontainer.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/daynight/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/layer/daynight/I18N.properties deleted file mode 100644 index c4e54f981..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/daynight/I18N.properties +++ /dev/null @@ -1,27 +0,0 @@ -# Sample ResourceBundle properties file - -DayNightLayer.daytimeColor=Daytime Color -DayNightLayer.daytimeColor.tooltip=Color for the daytime area, if polygon terminator isn't used. - -DayNightLayer.nighttimeColor=Nighttime Color -DayNightLayer.nighttimeColor.tooltip=Color for the nighttime area. - -DayNightLayer.termFade=Fade -DayNightLayer.termFade.tooltip=Percentage of the distance from the horizon to the brightest point to start fading to darkness, 0.0 to 0.5. - -DayNightLayer.useCurrentTime=Use Current Time -DayNightLayer.useCurrentTime.tooltip=If true, the layer will set the darkness according to the current time. - -DayNightLayer.overlayTime=Overlay Time -DayNightLayer.overlayTime.tooltip=The time used to create the layer, in milliseconds from java/unix epoch (leave empty for current time). - -DayNightLayer.updateInterval=Update Interval -DayNightLayer.updateInterval.tooltip=Update interval to automatically update the layer, in milli-seconds. - -DayNightLayer.doPolyTerminator=Use Polygon -DayNightLayer.doPolyTerminator.tooltip=Render with polygon instead of image (it's faster). - -DayNightLayer.terminatorVerts=Number of Polygon Vertices -DayNightLayer.terminatorVerts.tooltip=Number of vertices of the polygon terminator (more is smoother). - - diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/etopo/ETOPOLayer.properties b/src/core/src/main/resources/com/bbn/openmap/layer/etopo/ETOPOLayer.properties deleted file mode 100644 index b860d55bd..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/etopo/ETOPOLayer.properties +++ /dev/null @@ -1,15 +0,0 @@ -### ETOPO properties -etopo.class=com.bbn.openmap.layer.etopo.ETOPOLayer -etopo.prettyName=World Terrain Elevation / Ocean Depth -# This property should reflect the path to the ETOPO data -etopo.path=/usr/local/openmap/share -# Number between 0-255: 0 is transparent, 255 is opaque -etopo.opaque=200 -# Type of display for the data on startup -# 0 = greyscale slope shading -# 1 = coloredg slope shading -etopo.view.type=1 -# spacing in minutes for ETOPO data (must be 5,10, or 15) -etopo.minute.spacing=10 -# Contrast setting on startup, 1-5 -etopo.contrast=3 diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/location/I18N_da_DK.properties b/src/core/src/main/resources/com/bbn/openmap/layer/location/I18N_da_DK.properties deleted file mode 100644 index 8c10f23b0..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/location/I18N_da_DK.properties +++ /dev/null @@ -1,2 +0,0 @@ -LocationLayer.declutterNames=Declutter Navne -LocationLayer.declutterNames.tooltip=Flytter rundt p\u00E5 labels s\u00E5 de ikke overlapper.
Hvis du er zommet ud og der er mange labels kan det være tidskrævende. diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/plotLayer/AT.gst_small.txt b/src/core/src/main/resources/com/bbn/openmap/layer/plotLayer/AT.gst_small.txt deleted file mode 100644 index fdfb3b309..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/plotLayer/AT.gst_small.txt +++ /dev/null @@ -1,2000 +0,0 @@ -AT 2 1 19980921 1998092101 1998.72066 -33.8333 152.0000 0.0 19.0 20.0 9.0 -AT 2 1 19980921 1998092101 1998.72066 -33.2417 150.5844 310.0 19.0 20.0 9.0 -AT 2 2 19980921 1998092103 1998.72089 -23.4200 133.5200 580.0 31.0 32.0 12.5 -AT 2 2 19980921 1998092102 1998.72078 -42.9183 147.3553 30.0 17.0 -99.0 -99.0 -AT 2 1 19980921 1998092104 1998.72100 -32.3333 115.9500 20.0 9.0 -99.0 -99.0 -AT 2 1 19980921 1998092111 1998.72180 50.8103 4.9368 55.0 17.0 21.0 10.5 -AT 2 1 19980921 1998092111 1998.72180 47.6535 9.1260 420.0 17.0 19.0 8.0 -AT 2 1 19980921 1998092112 1998.72192 47.6410 9.1867 443.0 16.5 16.5 6.5 -AT 2 1 19980921 1998092111 1998.72180 46.7403 7.6083 565.0 13.0 18.5 4.5 -AT 1 3 19980921 1998092110 1998.72169 48.9413 8.3978 129.0 14.0 20.0 10.0 -AT 2 1 19980921 1998092111 1998.72180 50.7863 7.7175 190.0 18.0 20.0 7.0 -AT 2 1 19980921 1998092110 1998.72169 53.5833 11.4167 30.0 17.0 20.5 11.9 -AT 2 1 19980921 1998092109 1998.72158 51.6333 12.2667 55.0 17.0 20.0 11.0 -AT 2 1 19980921 1998092111 1998.72180 51.5550 6.9450 38.0 20.0 22.0 9.0 -AT 1 1 19980921 1998092110 1998.72169 47.7500 9.1667 200.0 13.0 21.0 9.0 -AT 2 2 19980921 1998092109 1998.72158 50.6080 12.1675 314.0 14.7 20.9 7.7 -AT 2 1 19980921 1998092111 1998.72180 53.5853 9.9472 23.0 15.0 18.0 11.0 -AT 2 1 19980921 1998092111 1998.72180 53.8728 8.7428 0.0 13.0 16.0 11.0 -AT 2 1 19980921 1998092111 1998.72180 50.0907 10.8023 285.0 17.6 17.6 4.0 -AT 2 1 19980921 1998092111 1998.72180 59.4340 24.7493 60.0 16.4 16.4 7.0 -AT 2 1 19980921 1998092109 1998.72158 61.6937 27.2650 123.0 12.0 14.0 -4.0 -AT 2 1 19980921 1998092110 1998.72169 63.2377 29.2537 110.0 12.0 12.9 8.6 -AT 2 1 19980921 1998092109 1998.72158 64.2312 27.7283 143.0 12.0 -99.0 -99.0 -AT 2 1 19980921 1998092108 1998.72146 62.2658 26.2078 93.0 12.5 17.0 9.0 -AT 2 1 19980921 1998092110 1998.72169 60.8042 23.4944 110.0 15.0 15.0 6.0 -AT 2 1 19980921 1998092111 1998.72180 37.6717 26.8292 200.0 20.0 22.0 15.0 -AT 2 1 19980921 1998092110 1998.72169 37.0677 22.4247 207.0 27.1 28.5 15.4 -AT 2 1 19980921 1998092108 1998.72146 37.9365 23.6960 12.0 25.0 27.0 18.0 -AT 2 2 19980921 1998092111 1998.72180 45.4933 15.5622 119.0 17.0 19.0 5.0 -AT 2 1 19980921 1998092110 1998.72169 43.5167 16.4333 25.0 16.0 16.0 12.0 -AT 2 1 19980921 1998092111 1998.72180 45.8295 17.3845 124.0 18.0 18.0 11.0 -AT 2 2 19980921 1998092104 1998.72100 35.3500 136.9000 49.0 30.0 33.0 21.5 -AT 2 1 19980921 1998092104 1998.72100 32.1850 130.1675 100.0 31.0 31.0 24.0 -AT 2 2 19980921 1998092104 1998.72100 36.5333 136.6667 60.0 26.0 33.5 20.5 -AT 2 1 19980921 1998092102 1998.72078 35.4100 139.4000 10.0 27.7 32.1 25.1 -AT 2 2 19980921 1998092103 1998.72089 36.2000 139.2833 35.0 24.0 28.0 22.0 -AT 2 1 19980921 1998092103 1998.72089 35.1667 126.8833 70.0 20.6 35.2 20.2 -AT 2 1 19980921 1998092111 1998.72180 51.6667 5.6167 16.0 18.0 22.0 11.0 -AT 2 1 19980921 1998092112 1998.72192 52.3833 4.9333 -1.0 20.0 23.0 7.0 -AT 2 1 19980921 1998092111 1998.72180 52.0852 4.3103 0.0 17.0 19.0 10.0 -AT 2 2 19980921 1998092111 1998.72180 52.7780 6.9092 20.0 18.0 19.0 9.0 -AT 2 1 19980921 1998092109 1998.72158 63.4333 10.6167 20.0 17.0 22.0 4.0 -AT 2 3 19980921 1998092111 1998.72180 68.1458 13.6250 20.0 11.0 13.5 10.0 -AT 2 1 19980921 1998092110 1998.72169 59.1333 10.2333 0.0 18.0 24.0 6.0 -AT 2 1 19980921 1998092110 1998.72169 59.0180 10.0342 35.0 17.0 17.0 10.0 -AT 2 1 19980921 1998092109 1998.72158 59.5667 9.2667 114.0 13.0 23.0 0.0 -AT 2 2 19980921 1998092111 1998.72180 61.3538 5.3987 333.0 15.0 17.0 6.0 -AT 2 1 19980921 1998092112 1998.72192 60.1468 11.1639 146.0 19.0 23.0 7.0 -AT 2 1 19980921 1998092112 1998.72192 32.8167 -16.9833 30.0 24.0 24.0 17.0 -AT 2 1 19980921 1998092110 1998.72169 59.3428 17.9147 29.0 13.0 15.0 6.0 -AT 2 1 19980921 1998092111 1998.72180 63.8110 16.4080 212.0 14.0 -99.0 -99.0 -AT 2 3 19980921 1998092111 1998.72180 56.0413 13.6785 100.0 14.3 18.6 7.1 -AT 2 1 19980921 1998092109 1998.72158 36.7993 34.5690 51.0 28.0 32.0 19.5 -AT 2 2 19980921 1998092120 1998.72283 57.7883 -152.4030 35.0 12.0 14.0 1.0 -AT 2 1 19980921 1998092118 1998.72260 31.2445 -85.4483 71.0 25.0 33.0 25.0 -AT 2 1 19980921 1998092118 1998.72260 34.6545 -86.5740 143.0 26.0 37.0 22.0 -AT 2 2 19980921 1998092117 1998.72249 34.8630 -87.5290 178.0 28.0 28.0 23.0 -AT 2 1 19980921 1998092118 1998.72260 35.2969 -94.0361 198.0 32.0 34.0 24.5 -AT 2 1 19980921 1998092118 1998.72260 33.6669 -93.5914 110.0 29.0 47.0 23.0 -AT 2 2 19980921 1998092117 1998.72249 36.2012 -94.1738 1389.0 19.0 33.0 18.0 -AT 2 1 19980921 1998092119 1998.72272 32.2405 -110.8765 762.0 34.0 35.5 20.0 -AT 2 2 19980921 1998092118 1998.72260 31.5702 -110.2403 1312.0 28.0 32.0 16.0 -AT 2 2 19980921 1998092119 1998.72272 37.3583 -118.4007 1243.0 24.0 -99.0 -99.0 -AT 2 2 19980921 1998092118 1998.72260 40.0643 -105.1122 1546.0 8.0 -99.0 -99.0 -AT 2 1 19980921 1998092118 1998.72260 37.4083 -102.6139 1308.0 18.0 33.0 12.0 -AT 2 1 19980921 1998092118 1998.72260 39.7944 -105.2925 1958.0 7.0 24.0 7.0 -AT 2 1 19980921 1998092116 1998.72237 41.4022 -72.4833 20.0 26.0 27.0 11.0 -AT 2 1 19980921 1998092117 1998.72249 26.1425 -80.1395 0.0 37.0 39.0 24.0 -AT 2 1 19980921 1998092117 1998.72249 27.7118 -82.6614 6.0 33.0 34.0 22.0 -AT 2 1 19980921 1998092116 1998.72237 29.4641 -81.2446 6.0 31.0 32.0 25.0 -AT 2 1 19980921 1998092117 1998.72249 33.6675 -84.0178 224.0 24.0 29.0 22.0 -AT 2 1 19980921 1998092118 1998.72260 41.4222 -94.7800 484.0 12.0 25.0 10.0 -AT 2 1 19980921 1998092118 1998.72260 42.5172 -90.7222 268.0 17.0 31.0 12.0 -AT 2 1 19980921 1998092118 1998.72260 41.7181 -94.9322 399.0 10.0 32.0 9.0 -AT 2 1 19980921 1998092116 1998.72237 42.0347 -93.6197 277.0 15.0 25.0 11.0 -AT 2 1 19980921 1998092119 1998.72272 43.0532 -114.1536 1299.0 19.0 23.0 3.0 -AT 2 1 19980921 1998092119 1998.72272 43.6279 -111.7409 1856.0 17.0 29.0 3.0 -AT 2 1 19980921 1998092120 1998.72283 42.9321 -114.7119 1111.0 15.0 23.0 4.0 -AT 2 2 19980921 1998092117 1998.72249 41.7600 -87.6765 229.0 21.0 33.0 18.0 -AT 2 2 19980921 1998092117 1998.72249 42.3333 -89.0333 252.0 17.0 30.0 13.0 -AT 2 1 19980921 1998092118 1998.72260 41.4392 -90.7175 223.0 18.0 -99.0 -99.0 -AT 2 4 19980921 1998092117 1998.72249 41.9363 -88.3625 223.0 18.0 18.0 12.0 -AT 2 1 19980921 1998092117 1998.72249 41.7676 -88.2930 203.0 26.0 33.0 15.0 -AT 2 1 19980921 1998092118 1998.72260 41.8089 -88.0111 203.0 20.0 29.0 20.0 -AT 2 1 19980921 1998092117 1998.72249 41.9013 -88.3190 215.0 20.0 32.0 14.0 -AT 2 1 19980921 1998092117 1998.72249 41.3975 -90.8994 222.0 15.0 -99.0 -99.0 -AT 2 1 19980921 1998092117 1998.72249 39.7683 -86.1581 259.0 28.0 31.0 22.0 -AT 2 1 19980921 1998092117 1998.72249 37.3366 -87.5054 134.0 29.0 36.0 8.0 -AT 2 1 19980921 1998092117 1998.72249 38.2542 -85.7594 145.0 27.0 33.0 22.0 -AT 2 1 19980921 1998092116 1998.72237 41.7072 -70.7630 0.0 23.5 27.5 18.0 -AT 2 1 19980921 1998092116 1998.72237 42.5962 -72.3115 287.0 24.0 27.0 8.0 -AT 2 2 19980921 1998092116 1998.72237 38.6215 -76.8627 92.0 30.0 30.0 20.0 -AT 2 2 19980921 1998092116 1998.72237 42.6733 -83.3885 322.0 23.5 29.5 22.0 -AT 2 2 19980921 1998092116 1998.72237 42.6847 -84.4545 266.0 28.0 32.0 11.0 -AT 2 1 19980921 1998092117 1998.72249 42.1018 -83.2729 174.0 25.0 27.0 19.0 -AT 2 1 19980921 1998092118 1998.72260 41.9442 -84.8839 327.0 22.0 31.0 12.0 -AT 1 1 19980921 1998092117 1998.72249 47.5233 -92.5364 430.0 11.7 11.7 3.9 -AT 2 1 19980921 1998092117 1998.72249 38.2088 -92.6753 226.0 28.0 -99.0 -99.0 -AT 2 3 19980921 1998092117 1998.72249 40.4177 -91.7128 217.0 15.0 31.0 14.0 -AT 2 2 19980921 1998092117 1998.72249 30.4503 -88.8285 0.0 26.0 -99.0 -99.0 -AT 2 2 19980921 1998092117 1998.72249 30.8427 -89.1102 200.0 30.0 -99.0 -99.0 -AT 1 2 19980921 1998092116 1998.72237 35.5950 -82.5062 719.0 20.0 32.2 15.6 -AT 2 1 19980921 1998092117 1998.72249 48.1268 -98.8688 486.0 10.0 24.0 0.0 -AT 2 1 19980921 1998092119 1998.72272 41.1544 -96.0419 318.0 15.1 35.0 10.2 -AT 2 2 19980921 1998092116 1998.72237 43.1778 -71.8247 169.0 26.0 31.5 17.5 -AT 2 1 19980921 1998092115 1998.72226 42.8650 -71.4939 80.0 24.0 30.0 12.0 -AT 2 2 19980921 1998092117 1998.72249 43.0217 -74.3722 289.0 25.0 27.0 9.0 -AT 2 1 19980921 1998092116 1998.72237 42.8526 -78.8252 125.0 23.0 24.0 16.0 -AT 2 2 19980921 1998092116 1998.72237 43.2072 -78.4593 446.0 25.0 -99.0 -99.0 -AT 2 1 19980921 1998092116 1998.72237 41.4739 -81.5372 314.0 22.0 32.0 17.0 -AT 2 1 19980921 1998092116 1998.72237 38.9928 -83.4644 265.0 25.0 26.0 25.0 -AT 2 1 19980921 1998092116 1998.72237 40.7473 -81.0400 314.0 25.0 31.0 14.0 -AT 2 1 19980921 1998092116 1998.72237 39.9611 -82.9989 224.0 28.0 -99.0 -99.0 -AT 2 1 19980921 1998092115 1998.72226 40.5343 -80.1801 316.0 22.0 29.0 18.0 -AT 2 1 19980921 1998092118 1998.72260 40.4847 -78.0106 358.0 27.0 30.0 18.0 -AT 2 1 19980921 1998092115 1998.72226 39.9470 -75.9753 160.0 26.1 27.7 15.5 -AT 2 2 19980921 1998092116 1998.72237 39.9345 -77.2450 215.0 22.0 25.0 16.0 -AT 2 1 19980921 1998092116 1998.72237 41.4488 -75.6018 465.0 29.0 29.0 18.0 -AT 2 1 19980921 1998092117 1998.72249 41.6311 -78.0917 490.0 26.0 28.0 16.0 -AT 2 1 19980921 1998092115 1998.72226 32.4258 -80.7292 6.0 29.0 32.0 22.0 -AT 2 2 19980921 1998092117 1998.72249 43.5428 -96.7927 419.0 11.0 -99.0 -99.0 -AT 2 1 19980921 1998092116 1998.72237 35.1635 -87.7185 216.0 28.0 45.0 8.0 -AT 2 2 19980921 1998092118 1998.72260 32.8598 -96.8002 161.0 36.0 37.0 22.0 -AT 2 2 19980921 1998092118 1998.72260 29.5052 -98.6833 183.0 45.0 45.0 34.0 -AT 2 2 19980921 1998092117 1998.72249 29.7977 -95.5793 7.0 32.0 36.0 26.0 -AT 2 2 19980921 1998092118 1998.72260 29.7500 -95.5058 -20.0 34.0 36.0 24.0 -AT 2 1 19980921 1998092118 1998.72260 29.7533 -95.7152 24.0 34.0 35.0 25.0 -AT 2 1 19980921 1998092117 1998.72249 32.8139 -96.9486 184.0 35.0 35.0 21.0 -AT 2 1 19980921 1998092118 1998.72260 40.5697 -111.8540 1594.0 32.0 32.0 2.0 -AT 2 1 19980921 1998092116 1998.72237 37.1000 -79.9000 304.0 29.0 -99.0 -99.0 -AT 2 2 19980921 1998092116 1998.72237 38.0410 -78.4877 133.0 31.0 32.0 20.0 -AT 2 1 19980921 1998092119 1998.72272 48.6969 -122.9042 140.0 16.0 18.0 10.0 -AT 2 1 19980921 1998092119 1998.72272 48.1832 -122.1198 157.0 19.0 19.0 8.0 -AT 2 1 19980921 1998092117 1998.72249 45.1672 -91.1492 340.0 14.0 27.0 6.0 -AT 2 2 19980921 1998092117 1998.72249 43.3852 -87.9413 209.0 21.0 32.0 11.0 -AT 2 2 19980921 1998092117 1998.72249 46.7133 -92.0920 213.0 12.0 22.0 7.0 -AT 2 1 19980921 1998092116 1998.72237 43.3347 -90.3867 250.0 17.0 -99.0 -99.0 -AT 2 1 19980921 1998092117 1998.72249 43.4005 -90.6196 272.0 13.0 -99.0 -99.0 -AT 2 1 19980920 1998092011 1998.71906 47.6535 9.1260 420.0 18.0 18.0 5.0 -AT 2 1 19980921 1998092011 1998.71906 46.7403 7.6083 565.0 13.0 19.0 6.5 -AT 2 1 19980921 1998092011 1998.71906 50.7863 7.7175 190.0 18.0 24.0 13.0 -AT 2 1 19980921 1998092012 1998.71918 53.5833 11.4167 30.0 16.4 17.0 13.8 -AT 1 1 19980921 1998092009 1998.71884 47.7500 9.1667 200.0 11.0 20.0 7.0 -AT 2 2 19980921 1998092009 1998.71884 50.6080 12.1675 314.0 15.7 21.9 9.5 -AT 2 1 19980921 1998092011 1998.71906 53.5853 9.9472 23.0 16.5 18.5 13.0 -AT 2 1 19980921 1998092011 1998.71906 53.8728 8.7428 0.0 14.0 17.0 10.0 -AT 2 1 19980920 1998092010 1998.71895 59.4340 24.7493 60.0 15.5 16.0 10.0 -AT 2 1 19980920 1998092010 1998.71895 63.2377 29.2537 110.0 11.6 14.1 7.5 -AT 2 2 19980921 1998092010 1998.71895 60.8042 23.4932 105.0 11.0 16.0 5.0 -AT 2 1 19980921 1998092010 1998.71895 64.8781 28.9342 211.0 7.5 7.5 5.0 -AT 2 1 19980921 1998092008 1998.71872 61.4805 23.8000 80.0 10.0 15.0 8.0 -AT 2 1 19980920 1998092010 1998.71895 59.8268 22.9755 0.0 17.0 18.0 9.0 -AT 2 2 19980921 1998092009 1998.71884 60.4543 26.2247 30.0 12.0 14.0 9.5 -AT 2 2 19980920 1998092009 1998.71884 64.7622 26.4150 80.0 10.4 10.4 1.6 -AT 2 1 19980921 1998092008 1998.71872 62.2658 26.2078 93.0 11.0 14.0 8.0 -AT 2 2 19980921 1998092010 1998.71895 62.2888 25.7350 100.0 11.0 15.0 9.0 -AT 2 1 19980920 1998092011 1998.71906 37.6717 26.8292 200.0 23.0 25.0 15.0 -AT 2 1 19980921 1998092010 1998.71895 37.0677 22.4247 207.0 26.1 30.7 14.9 -AT 2 1 19980921 1998092008 1998.71872 37.9365 23.6960 12.0 21.0 28.0 16.5 -AT 2 1 19980921 1998092011 1998.71906 45.8295 17.3845 124.0 12.0 19.0 11.0 -AT 2 2 19980921 1998092012 1998.71918 63.9982 -22.5603 15.0 7.0 10.0 4.0 -AT 2 1 19980921 1998092011 1998.71906 32.0212 35.7178 894.0 29.0 30.0 17.0 -AT 2 2 19980921 1998092001 1998.71792 36.5333 136.6667 60.0 30.5 33.0 20.0 -AT 2 1 19980920 1998092002 1998.71804 35.4100 139.4000 10.0 31.0 31.5 20.5 -AT 2 2 19980921 1998092003 1998.71815 35.8215 139.6715 5.0 26.0 32.5 22.5 -AT 2 1 19980921 1998092012 1998.71918 51.2508 5.9389 30.0 18.0 19.0 12.0 -AT 2 1 19980921 1998092011 1998.71906 52.0852 4.3103 0.0 18.0 19.0 14.0 -AT 2 3 19980921 1998092011 1998.71906 68.1458 13.6250 20.0 12.5 13.0 8.5 -AT 2 1 19980921 1998092011 1998.71906 59.0180 10.0342 35.0 17.0 19.0 10.0 -AT 2 1 19980921 1998092012 1998.71918 32.8167 -16.9833 30.0 22.0 28.0 21.0 -AT 2 3 19980920 1998092011 1998.71906 56.0413 13.6785 100.0 16.0 16.1 9.6 -AT 2 2 19980920 1998092021 1998.72021 57.6138 -152.2355 14.0 11.0 12.0 9.0 -AT 2 2 19980920 1998092021 1998.72021 57.7883 -152.4030 35.0 14.0 14.0 9.0 -AT 2 1 19980921 1998092018 1998.71986 35.2969 -94.0361 198.0 34.0 34.0 22.0 -AT 2 1 19980921 1998092018 1998.71986 32.2217 -110.9258 836.0 35.5 37.2 25.0 -AT 2 2 19980921 1998092018 1998.71986 31.5702 -110.2403 1312.0 31.0 36.0 18.0 -AT 2 1 19980921 1998092019 1998.71998 32.2217 -110.9258 836.0 35.0 37.0 21.0 -AT 2 1 19980920 1998092019 1998.71998 42.3565 -114.5887 1392.0 26.0 -99.0 2.0 -AT 2 2 19980921 1998092017 1998.71975 41.7600 -87.6765 229.0 32.0 33.0 21.0 -AT 2 1 19980920 1998092016 1998.71963 41.7072 -70.7630 0.0 24.0 25.5 12.5 -AT 2 2 19980920 1998092015 1998.71952 42.3697 -71.7850 160.0 29.0 30.0 12.0 -AT 2 2 19980921 1998092016 1998.71963 38.6215 -76.8627 92.0 24.0 35.0 16.0 -AT 2 2 19980920 1998092016 1998.71963 44.3853 -68.2080 22.0 19.0 19.0 14.0 -AT 2 2 19980920 1998092016 1998.71963 44.8817 -69.4458 88.0 22.5 27.0 13.0 -AT 2 2 19980921 1998092017 1998.71975 42.3363 -85.3522 282.0 30.0 32.0 15.0 -AT 2 2 19980921 1998092017 1998.71975 43.1778 -71.8247 169.0 28.5 29.0 5.0 -AT 2 1 19980920 1998092017 1998.71975 43.2992 -73.6356 84.0 26.5 26.5 17.0 -AT 2 1 19980920 1998092018 1998.71986 36.0906 -94.9200 280.0 24.0 32.0 21.0 -AT 2 1 19980920 1998092017 1998.71975 40.5343 -80.1801 316.0 27.0 31.0 20.0 -AT 2 1 19980921 1998092018 1998.71986 40.4847 -78.0106 358.0 28.0 28.0 15.0 -AT 2 1 19980921 1998092017 1998.71975 41.4488 -75.6018 465.0 22.0 28.0 12.0 -AT 2 1 19980920 1998092017 1998.71975 39.9606 -75.6058 111.0 28.0 28.0 17.0 -AT 2 1 19980921 1998092018 1998.71986 29.8073 -95.5373 7.0 32.0 33.0 22.0 -AT 2 1 19980921 1998092018 1998.71986 29.7533 -95.7152 24.0 36.0 47.0 10.0 -AT 2 1 19980921 1998092019 1998.71998 41.8067 -111.3050 1802.0 11.0 13.0 5.0 -AT 2 2 19980921 1998092016 1998.71963 38.0410 -78.4877 133.0 29.0 29.0 19.0 -AT 2 1 19980920 1998092019 1998.71998 48.6969 -122.9042 140.0 16.0 17.0 9.0 -AT 2 1 19980921 1998092019 1998.71998 48.1832 -122.1198 157.0 17.0 18.0 9.5 -AT 2 1 19980920 1998092018 1998.71986 47.6589 -117.4250 675.0 16.0 19.0 11.0 -AT 2 2 19980921 1998092017 1998.71975 46.7133 -92.0920 213.0 24.0 24.0 17.0 -AT 2 1 19980920 1998091911 1998.71632 47.6535 9.1260 420.0 16.0 17.0 5.0 -AT 2 1 19980921 1998091911 1998.71632 46.7403 7.6083 565.0 12.5 19.0 4.5 -AT 1 3 19980919 1998091909 1998.71610 48.9413 8.3978 129.0 16.0 17.0 7.0 -AT 2 1 19980921 1998091911 1998.71632 50.7863 7.7175 190.0 18.0 24.0 13.0 -AT 2 1 19980921 1998091912 1998.71644 53.5833 11.4167 30.0 15.1 20.4 10.9 -AT 1 1 19980921 1998091909 1998.71610 47.7500 9.1667 200.0 9.0 17.0 8.0 -AT 2 2 19980921 1998091909 1998.71610 50.6080 12.1675 314.0 15.8 16.1 8.4 -AT 2 1 19980919 1998091911 1998.71632 53.5853 9.9472 23.0 14.5 15.0 11.5 -AT 2 1 19980921 1998091911 1998.71632 53.8728 8.7428 0.0 15.0 16.0 11.0 -AT 2 1 19980920 1998091910 1998.71621 59.4340 24.7493 60.0 16.0 16.0 10.5 -AT 2 1 19980919 1998091910 1998.71621 63.2377 29.2537 110.0 12.3 13.4 7.5 -AT 2 2 19980921 1998091910 1998.71621 60.8042 23.4932 105.0 14.0 17.4 9.0 -AT 2 1 19980921 1998091910 1998.71621 64.8781 28.9342 211.0 6.0 6.5 4.5 -AT 2 1 19980920 1998091910 1998.71621 59.8268 22.9755 0.0 14.0 17.0 12.0 -AT 2 2 19980919 1998091910 1998.71621 64.7622 26.4150 80.0 8.1 8.1 5.9 -AT 2 1 19980921 1998091908 1998.71598 62.2658 26.2078 93.0 12.0 17.0 8.0 -AT 2 1 19980919 1998091911 1998.71632 37.6717 26.8292 200.0 23.0 27.0 17.0 -AT 2 1 19980921 1998091910 1998.71621 37.0677 22.4247 207.0 29.2 30.9 18.0 -AT 2 1 19980921 1998091911 1998.71632 37.9365 23.6960 12.0 26.5 28.5 21.5 -AT 2 2 19980919 1998091912 1998.71644 46.0532 16.1832 172.0 11.0 20.0 6.0 -AT 2 1 19980921 1998091911 1998.71632 45.8295 17.3845 124.0 19.0 23.0 10.0 -AT 2 2 19980921 1998091913 1998.71655 63.9982 -22.5603 15.0 11.0 12.3 5.0 -AT 2 1 19980921 1998091911 1998.71632 32.0212 35.7178 894.0 30.0 32.0 17.0 -AT 2 2 19980919 1998091904 1998.71553 32.7833 129.8667 20.0 33.7 34.9 21.6 -AT 2 2 19980919 1998091904 1998.71553 35.3500 136.9000 49.0 31.5 32.0 22.0 -AT 2 1 19980919 1998091903 1998.71541 35.0000 136.0000 92.0 27.0 27.0 19.5 -AT 2 2 19980919 1998091904 1998.71553 38.6527 141.2933 60.0 28.0 28.0 20.0 -AT 2 2 19980919 1998091903 1998.71541 36.5333 136.6667 60.0 32.2 32.2 20.8 -AT 2 1 19980919 1998091903 1998.71541 35.7417 139.5908 48.0 30.1 31.9 19.5 -AT 2 1 19980919 1998091903 1998.71541 35.1825 136.8028 2.0 30.0 30.0 29.0 -AT 2 1 19980919 1998091903 1998.71541 35.3408 132.9011 35.0 24.5 27.2 20.0 -AT 2 2 19980921 1998091903 1998.71541 35.8215 139.6715 5.0 26.5 27.5 21.0 -AT 2 2 19980919 1998091904 1998.71553 36.2000 139.2833 35.0 22.0 33.0 21.0 -AT 2 2 19980919 1998091904 1998.71553 33.7333 130.6500 34.0 29.0 29.0 24.0 -AT 2 1 19980921 1998091911 1998.71632 52.0852 4.3103 0.0 19.0 19.0 16.0 -AT 2 3 19980921 1998091912 1998.71644 68.1458 13.6250 20.0 9.5 11.5 8.0 -AT 2 1 19980921 1998091911 1998.71632 59.0180 10.0342 35.0 17.0 17.0 10.0 -AT 2 1 19980921 1998091912 1998.71644 32.8167 -16.9833 30.0 25.0 26.0 22.0 -AT 2 1 19980921 1998091910 1998.71621 59.3428 17.9147 29.0 13.0 14.0 11.0 -AT 2 3 19980919 1998091911 1998.71632 56.0413 13.6785 100.0 14.0 17.1 9.6 -AT 2 2 19980919 1998091921 1998.71747 57.6138 -152.2355 14.0 11.5 12.0 6.5 -AT 2 2 19980920 1998091921 1998.71747 57.7883 -152.4030 35.0 12.0 13.0 8.0 -AT 2 1 19980920 1998091921 1998.71747 62.6067 -159.5184 135.0 7.0 9.0 4.0 -AT 2 1 19980921 1998091918 1998.71712 35.2969 -94.0361 198.0 31.0 32.0 20.0 -AT 2 1 19980921 1998091918 1998.71712 32.2217 -110.9258 836.0 38.8 39.4 21.6 -AT 2 2 19980921 1998091918 1998.71712 31.5702 -110.2403 1312.0 32.0 36.0 18.0 -AT 2 1 19980921 1998091919 1998.71724 32.2217 -110.9258 836.0 34.0 38.0 21.0 -AT 2 2 19980921 1998091917 1998.71701 41.7600 -87.6765 229.0 32.0 32.0 19.0 -AT 2 2 19980921 1998091917 1998.71701 42.3333 -89.0333 252.0 32.0 34.0 25.0 -AT 2 4 19980921 1998091917 1998.71701 41.9363 -88.3625 223.0 27.0 29.0 20.0 -AT 2 1 19980919 1998091916 1998.71689 41.7072 -70.7630 0.0 24.0 24.0 9.5 -AT 2 2 19980920 1998091915 1998.71678 42.3697 -71.7850 160.0 25.0 25.0 13.0 -AT 2 2 19980921 1998091916 1998.71689 38.6215 -76.8627 92.0 25.0 -99.0 -99.0 -AT 2 2 19980920 1998091916 1998.71689 44.3853 -68.2080 22.0 18.0 19.0 12.0 -AT 2 2 19980920 1998091916 1998.71689 44.8817 -69.4458 88.0 22.5 22.5 10.0 -AT 2 2 19980921 1998091918 1998.71712 42.3363 -85.3522 282.0 29.0 31.0 10.0 -AT 2 2 19980921 1998091918 1998.71712 43.1778 -71.8247 169.0 26.0 26.0 9.5 -AT 2 1 19980920 1998091916 1998.71689 43.2992 -73.6356 84.0 21.0 24.0 13.0 -AT 2 1 19980920 1998091918 1998.71712 36.0906 -94.9200 280.0 26.0 30.0 20.0 -AT 2 1 19980920 1998091917 1998.71701 40.5343 -80.1801 316.0 30.0 31.0 19.0 -AT 2 1 19980919 1998091918 1998.71712 40.4847 -78.0106 358.0 25.0 29.0 15.0 -AT 2 1 19980920 1998091916 1998.71689 41.4488 -75.6018 465.0 26.0 29.0 16.0 -AT 2 1 19980919 1998091917 1998.71701 39.9606 -75.6058 111.0 24.0 29.0 15.0 -AT 2 1 19980921 1998091918 1998.71712 29.8073 -95.5373 7.0 30.0 33.0 28.0 -AT 2 1 19980921 1998091918 1998.71712 29.7533 -95.7152 24.0 35.0 46.0 10.0 -AT 2 1 19980921 1998091919 1998.71724 41.8067 -111.3050 1802.0 17.0 18.0 4.0 -AT 2 1 19980919 1998091919 1998.71724 40.7608 -111.8903 1711.0 18.0 34.0 8.0 -AT 2 2 19980921 1998091916 1998.71689 38.0410 -78.4877 133.0 25.0 28.0 18.0 -AT 2 1 19980920 1998091919 1998.71724 48.6969 -122.9042 140.0 15.0 19.0 14.0 -AT 2 1 19980921 1998091919 1998.71724 48.1832 -122.1198 157.0 16.0 21.0 13.5 -AT 2 1 19980919 1998091919 1998.71724 47.6589 -117.4250 675.0 12.0 20.0 10.0 -AT 2 2 19980921 1998091917 1998.71701 46.7133 -92.0920 213.0 18.0 36.0 15.0 -AT 2 1 19980918 1998091801 1998.71244 -33.8333 152.0000 0.0 23.0 25.0 9.0 -AT 2 2 19980918 1998091803 1998.71267 -23.4200 133.5200 580.0 32.0 32.5 12.0 -AT 2 1 19980918 1998091803 1998.71267 -37.8167 144.9667 12.0 20.0 20.0 10.0 -AT 2 1 19980918 1998091811 1998.71358 50.8103 4.9368 55.0 15.0 16.0 3.5 -AT 2 1 19980918 1998091811 1998.71358 47.6535 9.1260 420.0 15.0 15.0 10.0 -AT 2 1 19980918 1998091812 1998.71370 47.5017 9.4242 400.0 15.0 15.0 10.0 -AT 2 1 19980918 1998091811 1998.71358 46.7403 7.6083 565.0 16.0 17.0 4.0 -AT 2 1 19980921 1998091804 1998.71279 37.5319 121.3792 30.0 26.5 29.0 18.0 -AT 2 2 19980918 1998091809 1998.71336 53.3817 12.6002 72.0 13.0 15.0 6.0 -AT 1 3 19980918 1998091810 1998.71347 48.9413 8.3978 129.0 13.0 14.0 13.0 -AT 2 1 19980921 1998091811 1998.71358 50.7863 7.7175 190.0 13.0 14.0 10.0 -AT 2 1 19980918 1998091810 1998.71347 53.5833 11.4167 30.0 14.1 14.1 9.6 -AT 2 1 19980918 1998091809 1998.71336 51.6333 12.2667 55.0 14.0 14.0 12.0 -AT 2 1 19980918 1998091810 1998.71347 52.4252 12.5523 50.0 14.9 15.3 9.2 -AT 2 1 19980918 1998091810 1998.71347 51.5550 6.9450 38.0 17.0 21.0 9.0 -AT 1 1 19980921 1998091809 1998.71336 47.7500 9.1667 200.0 11.0 13.0 11.0 -AT 2 2 19980921 1998091809 1998.71336 50.6080 12.1675 314.0 13.8 15.4 10.4 -AT 2 1 19980919 1998091811 1998.71358 53.5853 9.9472 23.0 14.5 16.5 11.0 -AT 2 1 19980921 1998091811 1998.71358 53.8728 8.7428 0.0 14.0 16.0 10.0 -AT 2 1 19980921 1998091812 1998.71370 52.0833 15.0833 180.0 14.0 15.0 10.0 -AT 2 1 19980921 1998091811 1998.71358 51.0500 13.6833 111.0 16.0 16.5 -99.0 -AT 2 1 19980918 1998091811 1998.71358 50.0907 10.8023 285.0 13.8 13.8 9.5 -AT 2 1 19980918 1998091810 1998.71347 48.5895 8.8750 462.0 13.5 14.5 10.0 -AT 2 1 19980918 1998091810 1998.71347 59.4340 24.7493 60.0 16.5 16.5 10.0 -AT 1 1 19980918 1998091810 1998.71347 59.3922 27.7987 30.0 15.0 -99.0 -99.0 -AT 2 1 19980921 1998091809 1998.71336 60.4714 25.1058 53.0 16.0 17.0 8.0 -AT 2 1 19980921 1998091811 1998.71358 60.6297 24.8403 125.0 13.5 26.0 2.0 -AT 2 1 19980918 1998091810 1998.71347 63.2377 29.2537 110.0 12.0 12.1 7.8 -AT 2 2 19980921 1998091810 1998.71347 60.8042 23.4932 105.0 17.4 17.4 8.7 -AT 2 1 19980921 1998091810 1998.71347 64.8781 28.9342 211.0 6.0 6.0 4.0 -AT 2 1 19980920 1998091810 1998.71347 59.8268 22.9755 0.0 18.0 18.0 13.0 -AT 2 2 19980921 1998091809 1998.71336 60.4543 26.2247 30.0 15.0 15.0 10.0 -AT 2 1 19980919 1998091810 1998.71347 60.4069 22.3400 18.0 15.0 16.0 6.0 -AT 2 2 19980918 1998091810 1998.71347 64.7622 26.4150 80.0 6.8 7.8 5.1 -AT 2 1 19980918 1998091810 1998.71347 62.2981 27.1472 124.0 14.0 14.0 7.0 -AT 2 1 19980920 1998091810 1998.71347 60.2662 24.8543 32.0 15.0 15.0 10.0 -AT 2 1 19980921 1998091808 1998.71324 62.2658 26.2078 93.0 11.0 16.0 8.0 -AT 2 2 19980918 1998091811 1998.71358 62.3018 27.1365 122.0 15.0 21.0 8.0 -AT 2 2 19980921 1998091810 1998.71347 62.2888 25.7350 100.0 12.0 17.0 12.0 -AT 2 1 19980918 1998091811 1998.71358 37.6717 26.8292 200.0 26.0 28.0 14.0 -AT 2 1 19980921 1998091810 1998.71347 37.9915 23.6752 40.0 27.0 28.0 19.0 -AT 2 1 19980921 1998091810 1998.71347 37.0677 22.4247 207.0 28.7 29.6 16.1 -AT 2 1 19980918 1998091810 1998.71347 38.9533 20.7520 15.0 18.0 27.0 17.0 -AT 2 1 19980918 1998091810 1998.71347 37.9365 23.6960 12.0 27.0 28.0 19.5 -AT 2 1 19980918 1998091812 1998.71370 45.3388 14.3083 10.0 23.0 24.0 10.0 -AT 2 2 19980918 1998091810 1998.71347 45.4933 15.5622 119.0 14.0 14.0 5.0 -AT 2 2 19980918 1998091812 1998.71370 46.0532 16.1832 172.0 17.0 21.0 7.0 -AT 2 1 19980918 1998091811 1998.71358 45.8295 17.3845 124.0 19.0 19.0 8.0 -AT 2 2 19980921 1998091815 1998.71404 63.9982 -22.5603 15.0 9.0 10.0 3.0 -AT 2 1 19980921 1998091811 1998.71358 32.0212 35.7178 894.0 30.0 30.0 17.0 -AT 2 2 19980919 1998091804 1998.71279 32.7833 129.8667 20.0 27.3 27.9 21.0 -AT 2 2 19980918 1998091804 1998.71279 35.3500 136.9000 49.0 26.0 30.0 20.5 -AT 2 1 19980919 1998091803 1998.71267 35.0000 136.0000 92.0 23.0 25.5 22.0 -AT 2 2 19980918 1998091804 1998.71279 38.6527 141.2933 60.0 23.0 23.0 18.0 -AT 2 2 19980918 1998091803 1998.71267 34.1352 131.4557 17.0 27.5 27.5 12.0 -AT 2 2 19980919 1998091804 1998.71279 36.5333 136.6667 60.0 26.1 27.5 18.0 -AT 2 1 19980918 1998091802 1998.71256 35.4100 139.4000 10.0 21.2 28.3 19.3 -AT 2 1 19980919 1998091803 1998.71267 35.3408 132.9011 35.0 21.2 23.0 17.4 -AT 2 2 19980921 1998091803 1998.71267 35.8215 139.6715 5.0 26.0 27.0 20.5 -AT 2 2 19980918 1998091804 1998.71279 33.7333 130.6500 34.0 26.0 28.0 17.0 -AT 2 3 19980918 1998091803 1998.71267 35.1528 129.0303 80.0 25.5 27.0 17.0 -AT 2 1 19980918 1998091803 1998.71267 35.1667 126.8833 70.0 26.0 28.5 14.2 -AT 2 1 19980918 1998091811 1998.71358 51.6667 5.6167 16.0 16.0 17.0 5.0 -AT 2 1 19980918 1998091811 1998.71358 51.2508 5.9389 30.0 17.0 17.0 7.0 -AT 2 1 19980918 1998091812 1998.71370 52.3833 4.9333 -1.0 19.0 20.0 7.0 -AT 2 1 19980918 1998091811 1998.71358 52.0852 4.3103 0.0 17.0 17.0 11.0 -AT 2 2 19980921 1998091811 1998.71358 52.7780 6.9092 20.0 16.0 16.0 11.0 -AT 2 1 19980921 1998091812 1998.71370 52.0000 5.9167 0.0 14.9 15.7 8.5 -AT 2 1 19980918 1998091810 1998.71347 63.4333 10.6167 20.0 11.0 15.0 6.0 -AT 2 3 19980921 1998091811 1998.71358 68.1458 13.6250 20.0 11.0 11.5 7.5 -AT 2 1 19980918 1998091811 1998.71358 59.2067 10.4033 20.0 15.0 18.0 9.0 -AT 2 2 19980918 1998091811 1998.71358 63.4503 10.4463 30.0 15.0 15.0 2.0 -AT 2 1 19980918 1998091811 1998.71358 59.0180 10.0342 35.0 18.0 19.0 10.0 -AT 2 1 19980918 1998091811 1998.71358 59.4850 6.4883 70.0 11.5 16.5 9.0 -AT 2 2 19980918 1998091811 1998.71358 61.3538 5.3987 333.0 10.0 14.5 1.5 -AT 2 1 19980921 1998091812 1998.71370 60.1468 11.1639 146.0 15.0 15.0 8.0 -AT 2 1 19980918 1998091811 1998.71358 58.2833 7.9833 49.0 -99.0 -99.0 4.0 -AT 2 1 19980921 1998091812 1998.71370 63.7333 10.6333 15.0 21.0 21.0 11.0 -AT 2 1 19980920 1998091812 1998.71370 54.3167 18.6333 5.0 21.5 -99.0 12.0 -AT 2 1 19980918 1998091812 1998.71370 32.8167 -16.9833 30.0 22.0 28.5 18.5 -AT 2 1 19980918 1998091810 1998.71347 57.9275 12.0843 15.0 17.0 17.0 9.0 -AT 2 1 19980918 1998091811 1998.71358 63.8110 16.4080 212.0 8.0 13.1 3.6 -AT 2 3 19980918 1998091811 1998.71358 56.0413 13.6785 100.0 15.2 17.3 7.7 -AT 2 1 19980918 1998091809 1998.71336 36.7993 34.5690 51.0 30.0 32.0 20.5 -AT 2 2 19980918 1998091821 1998.71473 57.6138 -152.2355 14.0 11.0 12.5 6.0 -AT 2 2 19980918 1998091820 1998.71461 57.7883 -152.4030 35.0 13.0 13.0 5.0 -AT 2 1 19980918 1998091822 1998.71484 62.6067 -159.5184 135.0 5.0 8.0 3.0 -AT 2 1 19980918 1998091819 1998.71450 34.6545 -86.5740 143.0 35.0 36.0 20.0 -AT 2 1 19980918 1998091816 1998.71416 34.7792 -86.6124 275.0 33.0 35.0 21.0 -AT 2 2 19980921 1998091817 1998.71427 34.8630 -87.5290 178.0 33.0 35.0 20.0 -AT 2 1 19980918 1998091818 1998.71438 35.2969 -94.0361 198.0 29.5 32.5 20.0 -AT 2 1 19980918 1998091818 1998.71438 33.6669 -93.5914 110.0 32.0 41.0 30.0 -AT 2 1 19980918 1998091817 1998.71427 33.6140 -92.0778 43.0 31.0 34.0 21.0 -AT 2 2 19980918 1998091817 1998.71427 36.2012 -94.1738 1389.0 29.0 29.0 19.0 -AT 2 1 19980921 1998091820 1998.71461 32.3593 -111.0118 743.0 36.0 36.0 23.0 -AT 2 1 19980921 1998091818 1998.71438 32.2217 -110.9258 836.0 39.4 40.5 21.6 -AT 2 2 19980918 1998091818 1998.71438 31.5702 -110.2403 1312.0 33.0 34.0 16.0 -AT 2 1 19980921 1998091819 1998.71450 32.2217 -110.9258 836.0 36.0 37.0 22.0 -AT 2 2 19980921 1998091820 1998.71461 36.5963 -119.4493 99.0 25.0 33.0 15.0 -AT 2 1 19980918 1998091819 1998.71450 37.8244 -122.2306 70.0 20.0 20.0 14.0 -AT 2 1 19980918 1998091819 1998.71450 33.7769 -118.0386 7.0 25.0 26.0 12.0 -AT 2 2 19980918 1998091819 1998.71450 37.3583 -118.4007 1243.0 28.0 30.0 7.0 -AT 2 2 19980918 1998091818 1998.71438 40.0643 -105.1122 1546.0 27.0 30.0 9.0 -AT 2 1 19980918 1998091818 1998.71438 37.4083 -102.6139 1308.0 32.0 32.0 13.0 -AT 2 2 19980918 1998091820 1998.71461 40.5000 -107.5333 1900.0 -99.0 25.0 2.0 -AT 2 2 19980918 1998091815 1998.71404 41.0533 -73.5388 24.0 20.0 25.0 15.0 -AT 2 1 19980921 1998091817 1998.71427 26.1425 -80.1395 0.0 33.0 34.0 24.0 -AT 2 1 19980918 1998091818 1998.71438 28.1984 -81.4870 13.0 31.0 32.0 26.0 -AT 2 1 19980918 1998091817 1998.71427 27.7118 -82.6614 6.0 30.0 32.0 22.0 -AT 2 1 19980918 1998091817 1998.71427 28.5381 -81.3794 23.0 30.0 30.0 27.0 -AT 2 1 19980918 1998091816 1998.71416 29.4641 -81.2446 6.0 30.0 30.0 29.0 -AT 2 2 19980919 1998091817 1998.71427 28.1013 -80.6243 12.0 32.0 32.0 24.0 -AT 2 2 19980918 1998091817 1998.71427 27.6270 -81.5242 36.0 27.0 28.0 24.0 -AT 2 1 19980918 1998091818 1998.71438 41.4222 -94.7800 484.0 28.0 30.0 17.0 -AT 2 1 19980918 1998091818 1998.71438 42.0678 -90.1741 178.0 30.0 31.0 17.0 -AT 2 1 19980921 1998091817 1998.71427 42.8008 -92.2618 288.0 26.0 27.0 15.0 -AT 2 1 19980918 1998091818 1998.71438 41.7181 -94.9322 399.0 28.0 30.0 14.0 -AT 2 1 19980918 1998091819 1998.71450 42.7242 -114.5178 1100.0 22.0 31.0 15.0 -AT 2 1 19980921 1998091819 1998.71450 43.0532 -114.1536 1299.0 22.0 29.0 13.0 -AT 2 2 19980919 1998091820 1998.71461 46.7298 -116.9968 836.0 18.0 29.0 14.0 -AT 2 1 19980918 1998091820 1998.71461 42.9321 -114.7119 1111.0 22.0 34.0 16.0 -AT 2 2 19980918 1998091817 1998.71427 41.7600 -87.6765 229.0 30.0 30.0 17.0 -AT 2 1 19980918 1998091817 1998.71427 41.4392 -90.7175 223.0 27.0 27.0 17.0 -AT 2 4 19980918 1998091817 1998.71427 41.9363 -88.3625 223.0 25.0 25.0 17.0 -AT 2 1 19980921 1998091817 1998.71427 41.7676 -88.2930 203.0 31.0 34.0 16.0 -AT 2 1 19980918 1998091817 1998.71427 41.9013 -88.3190 215.0 27.0 27.0 15.0 -AT 2 1 19980918 1998091817 1998.71427 41.3975 -90.8994 222.0 25.0 25.0 16.0 -AT 2 1 19980918 1998091817 1998.71427 39.7683 -86.1581 259.0 29.0 29.0 19.0 -AT 2 1 19980918 1998091817 1998.71427 39.5392 -86.3692 218.0 32.0 37.0 17.0 -AT 2 1 19980920 1998091816 1998.71416 41.1306 -85.1289 238.0 28.5 32.0 12.5 -AT 2 2 19980918 1998091818 1998.71438 39.0382 -95.3958 313.0 31.0 31.0 18.0 -AT 2 1 19980921 1998091817 1998.71427 38.2542 -85.7594 145.0 32.0 36.0 27.0 -AT 2 1 19980918 1998091815 1998.71404 41.7072 -70.7630 0.0 18.0 26.0 13.0 -AT 2 2 19980920 1998091815 1998.71404 42.3697 -71.7850 160.0 22.0 28.0 12.0 -AT 2 1 19980921 1998091816 1998.71416 42.5962 -72.3115 287.0 21.0 27.0 8.0 -AT 2 1 19980918 1998091816 1998.71416 44.3670 -69.7340 81.0 15.0 28.0 9.0 -AT 2 2 19980918 1998091816 1998.71416 44.3853 -68.2080 22.0 14.0 14.0 9.0 -AT 2 2 19980920 1998091816 1998.71416 44.8817 -69.4458 88.0 21.5 25.0 2.5 -AT 2 2 19980918 1998091816 1998.71416 42.6733 -83.3885 322.0 26.0 27.5 10.0 -AT 2 2 19980918 1998091817 1998.71427 42.6847 -84.4545 266.0 28.0 28.0 8.0 -AT 2 1 19980921 1998091816 1998.71416 41.9442 -84.8839 327.0 23.0 36.0 12.0 -AT 2 2 19980918 1998091816 1998.71416 43.9393 -82.9968 217.0 25.0 26.0 11.0 -AT 2 2 19980921 1998091816 1998.71416 42.3363 -85.3522 282.0 25.0 30.0 9.0 -AT 1 1 19980918 1998091818 1998.71438 47.5233 -92.5364 430.0 26.7 26.7 15.0 -AT 2 3 19980918 1998091818 1998.71438 40.4177 -91.7128 217.0 27.0 28.0 -99.0 -AT 2 1 19980918 1998091818 1998.71438 34.8390 -88.5610 99.0 33.0 37.0 20.0 -AT 2 2 19980918 1998091817 1998.71427 30.8427 -89.1102 200.0 25.0 -99.0 -99.0 -AT 2 2 19980918 1998091819 1998.71450 45.4500 -112.1897 1559.0 20.0 27.0 16.0 -AT 2 1 19980918 1998091817 1998.71427 35.5978 -82.4000 832.0 30.0 30.0 30.0 -AT 2 1 19980918 1998091815 1998.71404 34.6914 -76.8937 0.0 26.0 27.0 22.0 -AT 2 2 19980918 1998091816 1998.71416 36.2417 -80.2908 953.0 28.0 34.0 20.0 -AT 1 2 19980918 1998091817 1998.71427 35.5950 -82.5062 719.0 29.4 33.3 14.4 -AT 2 1 19980918 1998091817 1998.71427 48.1268 -98.8688 486.0 19.0 21.0 10.0 -AT 2 1 19980918 1998091816 1998.71416 42.4739 -96.4133 329.0 27.0 32.0 16.0 -AT 2 2 19980918 1998091816 1998.71416 43.1778 -71.8247 169.0 18.5 24.5 8.0 -AT 2 1 19980918 1998091815 1998.71404 42.8650 -71.4939 80.0 20.5 26.0 10.0 -AT 2 1 19980918 1998091816 1998.71416 43.2081 -71.5381 105.0 22.0 27.0 4.0 -AT 2 1 19980918 1998091817 1998.71427 40.8989 -74.0931 25.0 23.0 29.0 12.0 -AT 2 1 19980918 1998091815 1998.71404 39.9008 -74.8239 17.0 24.0 24.0 17.0 -AT 2 2 19980918 1998091817 1998.71427 43.0217 -74.3722 289.0 20.0 24.0 6.0 -AT 2 1 19980920 1998091817 1998.71427 43.2992 -73.6356 84.0 21.0 26.5 8.0 -AT 2 1 19980918 1998091816 1998.71416 43.1008 -74.7733 234.0 20.0 26.0 6.0 -AT 2 1 19980918 1998091816 1998.71416 42.8526 -78.8252 125.0 19.0 28.0 11.0 -AT 2 1 19980918 1998091816 1998.71416 41.9269 -73.9978 122.0 23.0 28.0 11.0 -AT 2 1 19980918 1998091816 1998.71416 41.4739 -81.5372 314.0 27.0 28.0 10.5 -AT 2 1 19980918 1998091816 1998.71416 40.7473 -81.0400 314.0 27.0 27.0 8.0 -AT 2 1 19980918 1998091816 1998.71416 39.9611 -82.9989 224.0 28.0 29.0 15.0 -AT 2 1 19980920 1998091818 1998.71438 36.0906 -94.9200 280.0 24.0 28.0 19.0 -AT 2 1 19980918 1998091818 1998.71438 45.1753 -121.0803 666.0 19.0 26.0 9.0 -AT 2 1 19980918 1998091815 1998.71404 40.5343 -80.1801 316.0 24.0 27.0 14.0 -AT 2 1 19980918 1998091818 1998.71438 40.4847 -78.0106 358.0 28.0 28.0 15.0 -AT 2 1 19980918 1998091815 1998.71404 39.9470 -75.9753 160.0 21.1 24.4 14.4 -AT 2 1 19980918 1998091816 1998.71416 41.4488 -75.6018 465.0 25.0 29.0 13.0 -AT 2 3 19980918 1998091817 1998.71427 40.0435 -75.0243 -11.0 26.0 26.0 19.0 -AT 2 2 19980918 1998091817 1998.71427 39.7487 -77.5712 204.0 28.0 31.0 16.0 -AT 2 1 19980918 1998091817 1998.71427 41.6311 -78.0917 490.0 27.0 27.0 6.0 -AT 2 1 19980919 1998091817 1998.71427 39.9606 -75.6058 111.0 33.0 34.0 28.0 -AT 2 1 19980918 1998091816 1998.71416 18.4987 -67.1398 56.0 29.0 32.0 25.0 -AT 2 1 19980918 1998091815 1998.71404 32.4258 -80.7292 6.0 24.0 32.0 22.0 -AT 2 1 19980918 1998091818 1998.71438 43.8878 -100.7407 698.0 33.0 36.0 17.0 -AT 2 2 19980918 1998091817 1998.71427 43.5428 -96.7927 419.0 30.0 31.0 16.0 -AT 2 1 19980918 1998091817 1998.71427 29.7631 -95.3631 7.0 31.0 34.0 26.0 -AT 2 2 19980918 1998091818 1998.71438 32.8598 -96.8002 161.0 33.0 34.0 22.0 -AT 2 1 19980921 1998091818 1998.71438 29.8073 -95.5373 7.0 33.0 36.0 26.0 -AT 2 2 19980918 1998091817 1998.71427 29.7977 -95.5793 7.0 30.3 30.4 20.0 -AT 2 1 19980918 1998091818 1998.71438 29.7533 -95.7152 24.0 32.0 44.0 12.0 -AT 2 1 19980918 1998091817 1998.71427 32.8139 -96.9486 184.0 30.0 31.0 21.0 -AT 2 2 19980918 1998091819 1998.71450 31.1020 -97.7372 289.0 30.0 30.0 22.0 -AT 2 1 19980921 1998091819 1998.71450 41.8067 -111.3050 1802.0 23.0 27.0 7.0 -AT 2 1 19980918 1998091819 1998.71450 40.5697 -111.8540 1594.0 32.0 32.0 19.0 -AT 2 2 19980921 1998091817 1998.71427 37.9943 -77.9623 107.0 23.0 32.0 19.0 -AT 2 2 19980920 1998091817 1998.71427 37.0510 -76.3222 3.0 25.0 32.0 21.0 -AT 2 1 19980918 1998091816 1998.71416 38.0391 -78.4868 117.0 26.0 33.0 20.0 -AT 2 1 19980918 1998091820 1998.71461 48.6969 -122.9042 140.0 -99.0 -99.0 12.0 -AT 2 1 19980918 1998091819 1998.71450 48.1832 -122.1198 157.0 17.5 23.0 12.5 -AT 2 1 19980918 1998091819 1998.71450 47.6589 -117.4250 675.0 17.0 25.0 11.0 -AT 2 2 19980918 1998091820 1998.71461 48.5070 -122.6208 83.0 21.0 21.0 12.0 -AT 2 1 19980918 1998091817 1998.71427 45.1672 -91.1492 340.0 25.0 27.0 6.0 -AT 2 2 19980918 1998091817 1998.71427 43.3852 -87.9413 209.0 28.0 29.0 10.0 -AT 2 1 19980918 1998091816 1998.71416 44.2705 -88.4242 249.0 25.0 25.0 15.0 -AT 2 2 19980918 1998091818 1998.71438 46.7133 -92.0920 213.0 32.0 32.0 13.0 -AT 2 1 19980918 1998091816 1998.71416 43.3347 -90.3867 250.0 24.0 33.0 11.0 -AT 2 1 19980918 1998091817 1998.71427 43.4005 -90.6196 272.0 26.0 28.0 15.0 -AT 2 1 19980921 1998091818 1998.71438 42.0544 -104.9520 1506.0 32.0 33.0 16.0 -AT 1 1 19980921 1998091715 1998.71130 -63.4000 -56.9833 10.0 -5.1 -1.4 -12.5 -AT 2 1 19980920 1998091715 1998.71130 -34.5292 -58.5162 22.0 14.0 22.0 12.0 -AT 2 2 19980917 1998091702 1998.70982 -35.2400 149.0712 576.0 15.5 15.5 0.5 -AT 2 2 19980917 1998091703 1998.70993 -23.4200 133.5200 580.0 22.0 22.0 3.0 -AT 2 1 19980917 1998091703 1998.70993 -37.8167 144.9667 12.0 19.0 19.0 10.0 -AT 2 1 19980917 1998091704 1998.71005 -32.3333 115.9500 20.0 15.0 24.0 12.0 -AT 2 1 19980918 1998091711 1998.71084 50.8103 4.9368 55.0 13.5 17.5 6.0 -AT 2 1 19980918 1998091711 1998.71084 47.6535 9.1260 420.0 13.0 17.0 10.0 -AT 2 1 19980921 1998091711 1998.71084 47.5678 7.6362 260.0 13.0 19.0 11.0 -AT 2 1 19980918 1998091712 1998.71096 47.5017 9.4242 400.0 12.0 17.0 10.0 -AT 2 1 19980917 1998091711 1998.71084 46.7403 7.6083 565.0 15.0 20.0 9.5 -AT 2 1 19980921 1998091704 1998.71005 37.5319 121.3792 30.0 27.5 28.0 16.5 -AT 2 1 19980917 1998091711 1998.71084 49.5420 15.3537 518.0 12.0 13.0 7.0 -AT 2 2 19980917 1998091709 1998.71062 53.3817 12.6002 72.0 12.0 15.0 10.0 -AT 2 3 19980918 1998091711 1998.71084 50.5412 8.5220 260.0 13.0 15.0 7.0 -AT 1 3 19980917 1998091710 1998.71073 48.9413 8.3978 129.0 12.0 16.0 10.5 -AT 2 1 19980921 1998091711 1998.71084 50.7863 7.7175 190.0 11.0 16.0 9.0 -AT 2 1 19980917 1998091711 1998.71084 53.5833 11.4167 30.0 13.6 15.7 10.5 -AT 2 1 19980918 1998091709 1998.71062 51.6333 12.2667 55.0 11.0 16.0 11.0 -AT 2 1 19980917 1998091710 1998.71073 52.4252 12.5523 50.0 14.3 18.1 10.5 -AT 2 1 19980917 1998091711 1998.71084 51.5550 6.9450 38.0 14.0 16.0 9.0 -AT 1 1 19980921 1998091709 1998.71062 47.7500 9.1667 200.0 10.0 17.0 10.0 -AT 2 2 19980921 1998091709 1998.71062 50.6080 12.1675 314.0 12.7 18.6 10.5 -AT 2 1 19980917 1998091711 1998.71084 53.5853 9.9472 23.0 13.0 13.5 11.0 -AT 2 1 19980921 1998091711 1998.71084 53.8728 8.7428 0.0 13.0 16.0 9.0 -AT 2 1 19980921 1998091712 1998.71096 52.0833 15.0833 180.0 12.0 13.0 10.0 -AT 2 1 19980921 1998091711 1998.71084 51.0500 13.6833 111.0 12.0 17.5 10.0 -AT 2 1 19980918 1998091710 1998.71073 48.5895 8.8750 462.0 11.0 18.0 8.5 -AT 2 1 19980918 1998091711 1998.71084 53.6437 9.9630 15.0 14.0 14.0 11.0 -AT 2 1 19980917 1998091709 1998.71062 59.4340 24.7493 60.0 15.0 16.0 9.0 -AT 1 1 19980918 1998091710 1998.71073 59.3922 27.7987 30.0 15.0 -99.0 -99.0 -AT 2 2 19980917 1998091711 1998.71084 58.7150 26.7513 80.0 16.0 17.0 9.0 -AT 2 1 19980917 1998091710 1998.71073 60.4714 25.1058 53.0 15.0 16.0 8.0 -AT 2 1 19980917 1998091711 1998.71084 60.6297 24.8403 125.0 11.0 12.0 10.0 -AT 2 1 19980918 1998091710 1998.71073 63.2377 29.2537 110.0 11.4 12.4 8.6 -AT 2 1 19980917 1998091708 1998.71050 60.1833 24.0167 56.0 14.8 15.8 9.2 -AT 2 2 19980921 1998091710 1998.71073 60.8042 23.4932 105.0 12.4 17.0 6.1 -AT 2 1 19980921 1998091710 1998.71073 64.8781 28.9342 211.0 5.5 11.0 5.5 -AT 2 1 19980920 1998091710 1998.71073 59.8268 22.9755 0.0 15.5 15.5 13.0 -AT 2 2 19980917 1998091710 1998.71073 64.7622 26.4150 80.0 7.7 11.9 7.2 -AT 2 1 19980917 1998091710 1998.71073 62.2981 27.1472 124.0 13.0 15.0 13.0 -AT 2 1 19980920 1998091709 1998.71062 60.2662 24.8543 32.0 9.0 14.0 1.0 -AT 2 1 19980921 1998091708 1998.71050 62.2658 26.2078 93.0 13.0 16.0 4.0 -AT 2 2 19980918 1998091710 1998.71073 62.3018 27.1365 122.0 13.0 16.0 9.0 -AT 2 1 19980917 1998091710 1998.71073 60.8042 23.4944 110.0 12.0 16.0 10.0 -AT 2 1 19980918 1998091711 1998.71084 40.5478 23.0013 25.0 27.8 31.0 14.0 -AT 2 1 19980917 1998091710 1998.71073 37.6717 26.8292 200.0 27.0 27.0 17.0 -AT 2 1 19980921 1998091710 1998.71073 37.9915 23.6752 40.0 27.0 29.0 19.0 -AT 2 1 19980921 1998091710 1998.71073 37.0677 22.4247 207.0 25.9 30.2 13.9 -AT 2 1 19980918 1998091710 1998.71073 38.9533 20.7520 15.0 24.0 27.0 17.0 -AT 2 1 19980918 1998091710 1998.71073 37.9365 23.6960 12.0 27.5 30.0 18.5 -AT 2 1 19980918 1998091711 1998.71084 46.0023 16.1195 162.0 12.0 22.0 12.0 -AT 2 1 19980917 1998091712 1998.71096 45.3388 14.3083 10.0 16.0 23.0 15.0 -AT 2 2 19980917 1998091710 1998.71073 45.4933 15.5622 119.0 12.0 24.0 11.0 -AT 2 1 19980917 1998091710 1998.71073 45.5139 17.1278 170.0 10.0 24.0 10.0 -AT 2 2 19980918 1998091712 1998.71096 46.0532 16.1832 172.0 11.0 21.0 11.0 -AT 2 1 19980918 1998091711 1998.71084 45.8295 17.3845 124.0 11.0 22.0 10.0 -AT 2 2 19980921 1998091713 1998.71107 63.9982 -22.5603 15.0 7.4 12.0 -2.0 -AT 2 1 19980921 1998091711 1998.71084 32.0212 35.7178 894.0 30.0 32.0 19.0 -AT 2 2 19980918 1998091704 1998.71005 35.3500 136.9000 49.0 29.0 29.5 12.4 -AT 2 1 19980917 1998091703 1998.70993 32.1850 130.1675 100.0 26.0 27.0 24.0 -AT 2 1 19980917 1998091703 1998.70993 35.0000 136.0000 92.0 25.5 25.5 19.0 -AT 2 2 19980917 1998091703 1998.70993 34.1352 131.4557 17.0 24.5 31.0 19.0 -AT 2 2 19980917 1998091704 1998.71005 36.5333 136.6667 60.0 21.0 22.1 18.3 -AT 2 1 19980917 1998091704 1998.71005 34.7033 135.8400 100.0 24.0 28.3 18.8 -AT 2 1 19980917 1998091703 1998.70993 35.7417 139.5908 48.0 27.3 31.9 21.6 -AT 2 1 19980918 1998091702 1998.70982 35.4100 139.4000 10.0 26.4 32.0 21.4 -AT 2 1 19980921 1998091704 1998.71005 33.1917 131.6250 50.0 25.5 27.5 20.0 -AT 2 1 19980918 1998091704 1998.71005 34.5006 133.5764 16.0 25.0 25.5 18.0 -AT 2 1 19980917 1998091703 1998.70993 35.3408 132.9011 35.0 22.5 24.9 11.8 -AT 2 2 19980918 1998091702 1998.70982 35.8215 139.6715 5.0 27.0 32.5 21.5 -AT 2 2 19980917 1998091703 1998.70993 36.2000 139.2833 35.0 26.0 30.0 24.0 -AT 2 3 19980918 1998091703 1998.70993 35.1528 129.0303 80.0 26.0 28.0 18.0 -AT 2 1 19980917 1998091703 1998.70993 35.1667 126.8833 70.0 27.2 29.4 19.6 -AT 2 1 19980917 1998091701 1998.70970 7.1000 171.2200 3.0 32.0 32.0 27.0 -AT 2 1 19980917 1998091711 1998.71084 51.6667 5.6167 16.0 14.5 15.0 11.0 -AT 2 1 19980917 1998091712 1998.71096 51.2508 5.9389 30.0 15.0 17.0 10.0 -AT 2 1 19980917 1998091712 1998.71096 52.3833 4.9333 -1.0 15.0 15.0 11.0 -AT 2 2 19980917 1998091711 1998.71084 52.7780 6.9092 20.0 15.0 15.0 11.0 -AT 2 1 19980917 1998091710 1998.71073 63.4333 10.6167 20.0 15.0 17.0 11.0 -AT 2 3 19980917 1998091711 1998.71084 68.1458 13.6250 20.0 11.0 13.5 10.0 -AT 2 1 19980918 1998091711 1998.71084 59.2067 10.4033 20.0 18.0 21.0 6.0 -AT 2 2 19980917 1998091711 1998.71084 63.4503 10.4463 30.0 13.0 16.0 2.0 -AT 2 1 19980917 1998091711 1998.71084 59.0180 10.0342 35.0 17.0 17.0 8.0 -AT 2 1 19980917 1998091711 1998.71084 59.4850 6.4883 70.0 10.0 12.0 8.0 -AT 2 1 19980917 1998091710 1998.71073 59.5667 9.2667 114.0 16.0 16.5 8.0 -AT 2 2 19980917 1998091712 1998.71096 61.3538 5.3987 333.0 14.0 16.0 10.0 -AT 2 1 19980921 1998091712 1998.71096 60.1468 11.1639 146.0 15.0 21.0 9.0 -AT 2 1 19980918 1998091711 1998.71084 58.2833 7.9833 49.0 -99.0 28.0 1.0 -AT 2 1 19980921 1998091712 1998.71096 63.7333 10.6333 15.0 14.0 21.5 5.5 -AT 2 1 19980920 1998091712 1998.71096 54.3167 18.6333 5.0 13.8 -99.0 9.0 -AT 2 1 19980917 1998091712 1998.71096 32.8167 -16.9833 30.0 24.0 28.0 22.0 -AT 2 1 19980921 1998091710 1998.71073 59.3428 17.9147 29.0 14.0 14.0 11.0 -AT 2 1 19980918 1998091711 1998.71084 57.9275 12.0843 15.0 15.0 16.5 3.0 -AT 2 1 19980917 1998091711 1998.71084 63.8110 16.4080 212.0 12.5 21.7 12.0 -AT 2 3 19980917 1998091711 1998.71084 56.0413 13.6785 100.0 14.8 15.0 5.4 -AT 2 1 19980917 1998091709 1998.71062 36.7993 34.5690 51.0 31.5 31.5 22.5 -AT 2 2 19980917 1998091721 1998.71199 57.6138 -152.2355 14.0 12.0 15.5 7.5 -AT 2 2 19980917 1998091720 1998.71187 57.7883 -152.4030 35.0 11.0 15.0 8.0 -AT 2 1 19980918 1998091722 1998.71210 62.6067 -159.5184 135.0 9.0 12.0 8.0 -AT 2 1 19980917 1998091717 1998.71153 34.6545 -86.5740 143.0 34.0 37.0 19.0 -AT 2 1 19980917 1998091716 1998.71142 34.7792 -86.6124 275.0 35.0 35.0 22.0 -AT 2 2 19980917 1998091717 1998.71153 34.8630 -87.5290 178.0 33.0 37.0 20.0 -AT 2 1 19980917 1998091718 1998.71164 35.2969 -94.0361 198.0 28.5 32.0 20.5 -AT 2 1 19980918 1998091718 1998.71164 33.6669 -93.5914 110.0 33.0 42.0 10.0 -AT 2 1 19980917 1998091717 1998.71153 33.6140 -92.0778 43.0 30.0 34.0 22.0 -AT 2 2 19980917 1998091717 1998.71153 36.2012 -94.1738 1389.0 27.0 27.0 20.0 -AT 2 1 19980918 1998091718 1998.71164 32.2217 -110.9258 836.0 37.2 38.9 21.6 -AT 2 1 19980917 1998091718 1998.71164 33.4483 -112.0730 372.0 39.0 42.0 24.0 -AT 2 2 19980917 1998091718 1998.71164 31.5702 -110.2403 1312.0 31.0 34.0 16.0 -AT 2 1 19980918 1998091719 1998.71176 32.2217 -110.9258 836.0 35.0 38.0 22.0 -AT 2 1 19980917 1998091719 1998.71176 36.7503 -119.8210 89.0 31.0 37.0 16.0 -AT 2 2 19980917 1998091721 1998.71199 34.4233 -119.7030 0.0 23.0 23.0 16.0 -AT 2 2 19980921 1998091720 1998.71187 36.5963 -119.4493 99.0 30.0 35.0 19.0 -AT 2 1 19980917 1998091719 1998.71176 37.8244 -122.2306 70.0 16.0 21.0 13.0 -AT 2 2 19980918 1998091720 1998.71187 39.8007 -120.4660 1500.0 25.0 30.0 2.0 -AT 2 1 19980918 1998091720 1998.71187 33.7769 -118.0386 7.0 23.0 25.0 16.0 -AT 2 1 19980918 1998091720 1998.71187 34.2417 -118.4811 213.0 35.0 -99.0 -99.0 -AT 2 2 19980917 1998091719 1998.71176 37.3583 -118.4007 1243.0 28.0 30.0 12.0 -AT 2 2 19980917 1998091718 1998.71164 40.0643 -105.1122 1546.0 25.0 30.0 8.0 -AT 2 1 19980917 1998091718 1998.71164 39.7944 -105.2925 1958.0 25.0 27.0 7.0 -AT 2 1 19980917 1998091717 1998.71153 41.8758 -72.8017 28.0 30.0 -99.0 -99.0 -AT 2 1 19980917 1998091715 1998.71130 41.0533 -73.5388 18.0 20.0 25.0 15.0 -AT 2 1 19980918 1998091717 1998.71153 41.8097 -72.8311 31.0 26.0 26.0 12.0 -AT 2 1 19980917 1998091717 1998.71153 28.0433 -81.9567 35.0 20.0 24.0 15.0 -AT 2 1 19980917 1998091717 1998.71153 27.7118 -82.6614 6.0 30.0 32.0 22.0 -AT 2 3 19980920 1998091717 1998.71153 26.7072 -80.0382 2.0 30.0 31.0 23.0 -AT 2 1 19980917 1998091716 1998.71142 29.4641 -81.2446 6.0 29.0 29.0 25.0 -AT 2 2 19980919 1998091717 1998.71153 28.1013 -80.6243 12.0 30.0 30.0 25.0 -AT 2 2 19980918 1998091717 1998.71153 27.6270 -81.5242 36.0 31.0 33.0 25.0 -AT 2 1 19980921 1998091717 1998.71153 28.0183 -82.1131 31.0 25.0 31.0 24.0 -AT 2 1 19980917 1998091717 1998.71153 33.6675 -84.0178 224.0 30.0 33.0 19.0 -AT 2 1 19980917 1998091717 1998.71153 42.5172 -90.7222 268.0 27.0 28.0 25.0 -AT 2 1 19980918 1998091718 1998.71164 42.0678 -90.1741 178.0 27.0 30.0 17.0 -AT 2 1 19980917 1998091718 1998.71164 42.7013 -92.0744 310.0 25.0 27.0 15.0 -AT 2 1 19980921 1998091717 1998.71153 42.8008 -92.2618 288.0 25.0 26.0 14.0 -AT 2 1 19980917 1998091718 1998.71164 41.7181 -94.9322 399.0 27.0 29.0 13.0 -AT 2 1 19980917 1998091718 1998.71164 41.5568 -90.6042 188.0 27.0 -99.0 -99.0 -AT 2 1 19980917 1998091720 1998.71187 42.7242 -114.5178 1100.0 28.0 31.0 14.0 -AT 2 1 19980917 1998091719 1998.71176 43.4777 -115.3098 1307.0 22.0 33.0 6.0 -AT 2 2 19980919 1998091719 1998.71176 46.7298 -116.9968 836.0 28.0 32.0 18.0 -AT 2 1 19980917 1998091719 1998.71176 43.6279 -111.7409 1856.0 29.0 31.0 12.0 -AT 2 1 19980917 1998091719 1998.71176 42.9321 -114.7119 1111.0 28.0 34.0 15.0 -AT 2 2 19980917 1998091717 1998.71153 41.7600 -87.6765 229.0 25.0 26.0 20.0 -AT 2 1 19980917 1998091718 1998.71164 41.4392 -90.7175 223.0 24.0 28.0 18.0 -AT 2 4 19980918 1998091717 1998.71153 41.9363 -88.3625 223.0 23.0 23.0 17.0 -AT 2 1 19980921 1998091717 1998.71153 41.7676 -88.2930 203.0 28.0 30.0 20.0 -AT 2 1 19980918 1998091718 1998.71164 42.0333 -87.7333 178.0 28.0 28.0 8.0 -AT 2 1 19980917 1998091718 1998.71164 41.8089 -88.0111 203.0 24.0 33.0 19.0 -AT 2 1 19980917 1998091717 1998.71153 41.7412 -87.8932 204.0 30.0 -99.0 -99.0 -AT 2 1 19980917 1998091717 1998.71153 41.9013 -88.3190 215.0 25.0 25.0 16.0 -AT 2 1 19980918 1998091717 1998.71153 41.3975 -90.8994 222.0 22.0 26.0 15.0 -AT 2 1 19980917 1998091717 1998.71153 39.7683 -86.1581 259.0 25.0 27.0 20.0 -AT 2 1 19980917 1998091717 1998.71153 39.5392 -86.3692 218.0 25.0 33.0 17.0 -AT 2 1 19980920 1998091716 1998.71142 41.1306 -85.1289 238.0 28.5 28.5 16.0 -AT 2 2 19980918 1998091718 1998.71164 39.0382 -95.3958 313.0 25.0 30.0 18.0 -AT 2 1 19980917 1998091716 1998.71142 36.8302 -84.8523 364.0 31.0 32.0 22.0 -AT 2 1 19980917 1998091717 1998.71153 38.2542 -85.7594 145.0 32.0 35.0 25.0 -AT 2 1 19980917 1998091716 1998.71142 41.7072 -70.7630 0.0 23.0 24.5 12.0 -AT 2 2 19980917 1998091715 1998.71130 42.3697 -71.7850 160.0 24.0 30.0 7.0 -AT 2 1 19980918 1998091716 1998.71142 42.5962 -72.3115 287.0 23.0 27.0 6.0 -AT 2 2 19980921 1998091716 1998.71142 38.6215 -76.8627 92.0 29.0 35.0 21.0 -AT 2 1 19980917 1998091716 1998.71142 44.5883 -69.5992 68.0 21.5 27.2 1.1 -AT 2 1 19980917 1998091716 1998.71142 44.3670 -69.7340 81.0 26.0 31.0 14.0 -AT 2 2 19980917 1998091716 1998.71142 44.3853 -68.2080 22.0 18.0 18.0 11.0 -AT 2 2 19980920 1998091717 1998.71153 44.8817 -69.4458 88.0 23.5 23.5 4.5 -AT 2 2 19980918 1998091717 1998.71153 42.6847 -84.4545 266.0 25.0 27.0 12.0 -AT 2 1 19980917 1998091716 1998.71142 41.9442 -84.8839 327.0 20.0 23.0 13.0 -AT 2 2 19980917 1998091716 1998.71142 43.9393 -82.9968 217.0 21.0 24.0 10.0 -AT 2 2 19980921 1998091716 1998.71142 42.3363 -85.3522 282.0 28.0 28.0 11.0 -AT 1 1 19980918 1998091718 1998.71164 47.5233 -92.5364 430.0 27.2 27.8 12.8 -AT 2 1 19980917 1998091717 1998.71153 36.9289 -93.9275 422.0 25.0 26.0 15.0 -AT 2 3 19980917 1998091718 1998.71164 40.4177 -91.7128 217.0 27.0 28.0 22.0 -AT 2 1 19980917 1998091717 1998.71153 33.4503 -88.8183 88.0 55.0 55.0 55.0 -AT 2 1 19980917 1998091718 1998.71164 34.8390 -88.5610 99.0 34.0 35.0 21.0 -AT 2 2 19980917 1998091717 1998.71153 30.4503 -88.8285 0.0 29.0 33.0 22.0 -AT 2 2 19980917 1998091717 1998.71153 30.8427 -89.1102 200.0 34.0 -99.0 -99.0 -AT 2 2 19980918 1998091719 1998.71176 45.4500 -112.1897 1559.0 26.0 31.0 10.0 -AT 2 1 19980918 1998091716 1998.71142 34.6914 -76.8937 0.0 26.0 29.0 22.0 -AT 2 2 19980918 1998091716 1998.71142 36.2417 -80.2908 953.0 30.0 34.0 19.0 -AT 2 2 19980918 1998091716 1998.71142 43.1778 -71.8247 169.0 22.5 25.0 6.0 -AT 2 1 19980917 1998091715 1998.71130 42.8650 -71.4939 80.0 23.0 25.0 8.0 -AT 2 1 19980918 1998091717 1998.71153 40.8989 -74.0931 25.0 28.0 33.0 18.0 -AT 2 1 19980917 1998091718 1998.71164 39.9008 -74.8239 17.0 26.0 30.0 26.0 -AT 2 2 19980917 1998091717 1998.71153 43.0217 -74.3722 289.0 20.0 22.0 4.0 -AT 2 1 19980920 1998091717 1998.71153 43.2992 -73.6356 84.0 21.5 21.5 6.0 -AT 2 1 19980918 1998091716 1998.71142 43.1008 -74.7733 234.0 22.0 23.0 5.0 -AT 2 1 19980917 1998091716 1998.71142 42.8526 -78.8252 125.0 17.0 22.0 11.0 -AT 2 2 19980917 1998091716 1998.71142 43.2072 -78.4593 446.0 21.0 21.0 1.0 -AT 2 2 19980918 1998091717 1998.71153 42.9048 -78.8602 162.0 23.0 23.0 11.0 -AT 2 1 19980917 1998091716 1998.71142 41.4739 -81.5372 314.0 21.0 -99.0 14.0 -AT 2 1 19980917 1998091716 1998.71142 38.9928 -83.4644 265.0 25.0 25.0 16.0 -AT 2 1 19980917 1998091716 1998.71142 40.7473 -81.0400 314.0 23.0 25.0 16.0 -AT 2 1 19980917 1998091716 1998.71142 39.9611 -82.9989 224.0 27.0 30.0 19.0 -AT 2 1 19980917 1998091718 1998.71164 34.6452 -97.9518 360.0 27.0 29.0 22.0 -AT 2 1 19980920 1998091718 1998.71164 36.0906 -94.9200 280.0 21.0 24.0 19.0 -AT 2 1 19980917 1998091718 1998.71164 35.5485 -97.4150 364.0 32.0 36.0 20.0 -AT 2 1 19980917 1998091718 1998.71164 45.1753 -121.0803 666.0 20.0 33.0 9.0 -AT 2 1 19980917 1998091717 1998.71153 40.5343 -80.1801 316.0 26.0 30.0 18.0 -AT 2 1 19980917 1998091717 1998.71153 40.4847 -78.0106 358.0 23.0 33.0 20.0 -AT 2 2 19980917 1998091716 1998.71142 39.9345 -77.2450 215.0 23.0 32.0 21.0 -AT 2 1 19980918 1998091716 1998.71142 41.4488 -75.6018 465.0 24.0 27.0 16.0 -AT 2 3 19980918 1998091717 1998.71153 40.0435 -75.0243 -11.0 21.5 32.0 18.5 -AT 2 2 19980918 1998091717 1998.71153 39.7487 -77.5712 204.0 26.0 32.0 21.0 -AT 2 1 19980917 1998091717 1998.71153 41.6311 -78.0917 490.0 26.0 26.0 -99.0 -AT 2 1 19980919 1998091717 1998.71153 39.9606 -75.6058 111.0 24.0 33.0 18.0 -AT 2 1 19980918 1998091716 1998.71142 18.4987 -67.1398 56.0 31.0 33.0 25.0 -AT 2 1 19980917 1998091716 1998.71142 18.3994 -66.0503 234.0 32.0 33.0 15.0 -AT 2 1 19980917 1998091715 1998.71130 32.4258 -80.7292 6.0 29.0 34.0 21.0 -AT 2 1 19980918 1998091718 1998.71164 43.8878 -100.7407 698.0 29.0 31.0 16.0 -AT 2 2 19980917 1998091718 1998.71164 43.5428 -96.7927 419.0 27.0 30.0 15.0 -AT 2 1 19980917 1998091718 1998.71164 35.0531 -85.0503 266.0 33.0 -99.0 -99.0 -AT 2 1 19980917 1998091716 1998.71142 35.1635 -87.7185 216.0 34.0 45.0 9.0 -AT 2 1 19980921 1998091718 1998.71164 29.8073 -95.5373 7.0 34.0 39.0 32.0 -AT 2 2 19980917 1998091717 1998.71153 29.7977 -95.5793 7.0 29.0 31.0 29.0 -AT 2 1 19980917 1998091718 1998.71164 29.7533 -95.7152 24.0 31.0 31.0 23.0 -AT 2 1 19980917 1998091717 1998.71153 32.8139 -96.9486 184.0 27.0 32.0 -99.0 -AT 2 2 19980917 1998091719 1998.71176 31.1020 -97.7372 289.0 24.0 27.0 23.0 -AT 2 1 19980921 1998091719 1998.71176 41.8067 -111.3050 1802.0 25.0 28.0 7.0 -AT 2 1 19980919 1998091719 1998.71176 40.7608 -111.8903 1711.0 26.0 34.0 14.0 -AT 2 1 19980917 1998091717 1998.71153 37.1000 -79.9000 304.0 30.0 36.0 19.0 -AT 2 1 19980917 1998091717 1998.71153 37.5372 -79.3990 289.0 28.0 34.0 19.0 -AT 2 1 19980917 1998091716 1998.71142 38.0391 -78.4868 117.0 30.0 35.0 20.0 -AT 2 1 19980918 1998091719 1998.71176 48.6969 -122.9042 140.0 17.0 17.0 -99.0 -AT 2 1 19980917 1998091719 1998.71176 48.1832 -122.1198 157.0 19.0 27.0 10.0 -AT 2 1 19980917 1998091719 1998.71176 47.6589 -117.4250 675.0 24.0 32.0 12.0 -AT 2 2 19980917 1998091720 1998.71187 48.5070 -122.6208 83.0 16.0 24.0 11.0 -AT 2 1 19980917 1998091717 1998.71153 45.1672 -91.1492 340.0 25.0 27.0 12.0 -AT 2 2 19980917 1998091717 1998.71153 43.3852 -87.9413 209.0 28.0 29.0 9.0 -AT 2 1 19980918 1998091717 1998.71153 44.2705 -88.4242 249.0 23.0 26.0 18.0 -AT 2 2 19980917 1998091716 1998.71142 46.7133 -92.0920 213.0 18.0 31.0 13.0 -AT 2 1 19980917 1998091716 1998.71142 43.3347 -90.3867 250.0 23.0 -99.0 -99.0 -AT 2 1 19980917 1998091717 1998.71153 43.4005 -90.6196 272.0 24.0 27.0 14.0 -AT 2 1 19980918 1998091718 1998.71164 44.7361 -87.6208 208.0 19.0 21.0 -18.0 -AT 2 1 19980921 1998091718 1998.71164 42.0544 -104.9520 1506.0 32.0 34.0 17.0 -AT 1 1 19980921 1998091615 1998.70856 -63.4000 -56.9833 10.0 -5.4 -4.1 -14.0 -AT 2 1 19980920 1998091615 1998.70856 -34.5292 -58.5162 22.0 19.0 19.0 11.0 -AT 2 2 19980916 1998091603 1998.70719 -23.4200 133.5200 580.0 21.0 22.5 9.0 -AT 2 2 19980916 1998091603 1998.70719 -27.2170 153.0546 2.0 23.5 24.0 6.5 -AT 2 1 19980916 1998091603 1998.70719 -36.5500 145.9833 174.0 14.0 18.0 2.0 -AT 2 1 19980917 1998091603 1998.70719 -37.8167 144.9667 12.0 14.0 18.0 3.0 -AT 2 1 19980916 1998091604 1998.70731 -32.3333 115.9500 20.0 24.0 24.0 11.0 -AT 2 1 19980918 1998091611 1998.70811 50.8103 4.9368 55.0 12.0 15.5 5.5 -AT 2 1 19980920 1998091611 1998.70811 47.6535 9.1260 420.0 15.0 15.0 11.0 -AT 2 1 19980916 1998091612 1998.70822 47.5017 9.4242 400.0 16.0 18.0 10.0 -AT 2 1 19980916 1998091611 1998.70811 46.7403 7.6083 565.0 15.0 17.0 10.0 -AT 2 1 19980921 1998091604 1998.70731 37.5319 121.3792 30.0 28.0 28.5 20.5 -AT 2 1 19980916 1998091611 1998.70811 49.5420 15.3537 518.0 12.0 12.0 6.0 -AT 2 2 19980916 1998091609 1998.70788 53.3817 12.6002 72.0 12.0 14.0 10.0 -AT 2 3 19980918 1998091611 1998.70811 50.5412 8.5220 260.0 14.0 17.0 8.0 -AT 1 3 19980916 1998091610 1998.70799 48.9413 8.3978 129.0 14.0 16.0 14.0 -AT 2 1 19980916 1998091611 1998.70811 50.7863 7.7175 190.0 12.0 16.0 11.0 -AT 2 1 19980916 1998091610 1998.70799 53.5833 11.4167 30.0 12.2 18.6 6.0 -AT 2 1 19980916 1998091609 1998.70788 51.6333 12.2667 55.0 11.0 14.0 10.0 -AT 2 1 19980916 1998091610 1998.70799 52.4252 12.5523 50.0 15.6 16.9 11.3 -AT 2 1 19980916 1998091612 1998.70822 51.5550 6.9450 38.0 11.0 15.0 11.0 -AT 1 1 19980921 1998091609 1998.70788 47.7500 9.1667 200.0 13.0 13.0 9.0 -AT 2 2 19980921 1998091609 1998.70788 50.6080 12.1675 314.0 17.1 17.4 11.8 -AT 2 1 19980916 1998091611 1998.70811 53.5853 9.9472 23.0 13.5 13.5 10.5 -AT 2 1 19980921 1998091611 1998.70811 53.8728 8.7428 0.0 15.0 15.0 10.0 -AT 2 1 19980921 1998091612 1998.70822 52.0833 15.0833 180.0 12.0 15.0 10.0 -AT 2 1 19980916 1998091610 1998.70799 51.3187 13.2825 97.0 14.0 17.0 13.0 -AT 2 1 19980921 1998091611 1998.70811 51.0500 13.6833 111.0 11.0 11.2 -99.0 -AT 2 1 19980918 1998091610 1998.70799 48.5895 8.8750 462.0 15.0 16.0 10.5 -AT 2 1 19980918 1998091611 1998.70811 53.6437 9.9630 15.0 13.0 13.0 10.0 -AT 2 1 19980916 1998091611 1998.70811 59.4340 24.7493 60.0 16.0 16.0 9.0 -AT 1 1 19980917 1998091610 1998.70799 59.3922 27.7987 30.0 14.0 14.0 10.0 -AT 2 2 19980917 1998091611 1998.70811 58.7150 26.7513 80.0 14.0 17.0 7.0 -AT 2 1 19980917 1998091611 1998.70811 58.3767 26.7089 200.0 15.0 16.0 10.0 -AT 2 1 19980916 1998091608 1998.70776 60.4714 25.1058 53.0 14.0 15.0 9.0 -AT 2 1 19980917 1998091611 1998.70811 60.6297 24.8403 125.0 14.0 25.0 2.0 -AT 2 1 19980921 1998091609 1998.70788 61.6937 27.2650 123.0 15.0 15.0 1.0 -AT 2 1 19980918 1998091610 1998.70799 63.2377 29.2537 110.0 12.0 14.4 11.6 -AT 2 1 19980916 1998091611 1998.70811 60.1833 24.0167 56.0 15.7 16.0 9.2 -AT 2 2 19980921 1998091610 1998.70799 60.8042 23.4932 105.0 17.0 17.0 6.8 -AT 2 1 19980921 1998091610 1998.70799 64.8781 28.9342 211.0 12.0 13.5 12.0 -AT 2 1 19980916 1998091610 1998.70799 61.6781 27.2033 110.0 14.0 15.0 11.0 -AT 2 1 19980917 1998091611 1998.70811 61.4805 23.8000 80.0 15.0 15.0 10.0 -AT 2 1 19980920 1998091610 1998.70799 59.8268 22.9755 0.0 15.0 16.5 14.0 -AT 2 1 19980916 1998091611 1998.70811 61.7403 27.3347 97.0 13.0 15.0 10.0 -AT 2 2 19980916 1998091610 1998.70799 64.7622 26.4150 80.0 11.2 19.6 10.7 -AT 2 1 19980916 1998091610 1998.70799 62.2981 27.1472 124.0 14.0 16.0 12.0 -AT 2 1 19980920 1998091611 1998.70811 60.2662 24.8543 32.0 13.0 22.0 11.0 -AT 2 1 19980916 1998091608 1998.70776 62.2658 26.2078 93.0 17.0 19.0 14.0 -AT 2 2 19980918 1998091609 1998.70788 62.3018 27.1365 122.0 14.0 16.0 11.0 -AT 2 2 19980921 1998091610 1998.70799 62.2888 25.7350 100.0 14.0 15.0 10.0 -AT 2 1 19980916 1998091610 1998.70799 60.8042 23.4944 110.0 15.0 18.0 8.0 -AT 2 1 19980916 1998091611 1998.70811 37.9522 23.6133 35.0 29.0 32.0 23.0 -AT 2 1 19980916 1998091611 1998.70811 37.6717 26.8292 200.0 27.0 28.0 19.0 -AT 2 1 19980921 1998091610 1998.70799 37.9915 23.6752 40.0 29.0 31.0 21.0 -AT 2 1 19980921 1998091610 1998.70799 37.0677 22.4247 207.0 27.9 29.2 15.3 -AT 2 1 19980918 1998091610 1998.70799 38.9533 20.7520 15.0 24.0 27.0 16.0 -AT 2 1 19980916 1998091610 1998.70799 37.9365 23.6960 12.0 27.5 31.5 20.0 -AT 2 1 19980918 1998091611 1998.70811 46.0023 16.1195 162.0 22.0 24.0 7.0 -AT 2 1 19980917 1998091612 1998.70822 45.3388 14.3083 10.0 23.0 24.0 12.0 -AT 2 2 19980917 1998091610 1998.70799 45.4933 15.5622 119.0 21.0 22.0 7.0 -AT 2 1 19980917 1998091610 1998.70799 45.5139 17.1278 170.0 22.0 24.0 8.0 -AT 2 2 19980918 1998091612 1998.70822 46.0532 16.1832 172.0 21.0 21.0 6.0 -AT 2 1 19980917 1998091611 1998.70811 45.8295 17.3845 124.0 21.0 23.0 12.0 -AT 2 2 19980916 1998091612 1998.70822 63.9982 -22.5603 15.0 7.0 9.0 -2.0 -AT 2 1 19980921 1998091611 1998.70811 32.0212 35.7178 894.0 33.0 34.0 20.0 -AT 2 2 19980916 1998091604 1998.70731 35.3500 136.9000 49.0 28.5 29.5 20.4 -AT 2 1 19980916 1998091604 1998.70731 32.1850 130.1675 100.0 28.0 30.0 26.0 -AT 2 1 19980916 1998091603 1998.70719 35.0000 136.0000 92.0 27.0 28.0 22.0 -AT 2 2 19980916 1998091604 1998.70731 38.6527 141.2933 60.0 23.0 26.0 22.0 -AT 2 2 19980916 1998091603 1998.70719 34.1352 131.4557 17.0 25.0 31.0 21.0 -AT 2 2 19980917 1998091604 1998.70731 36.5333 136.6667 60.0 25.2 25.3 19.0 -AT 2 2 19980916 1998091603 1998.70719 35.3500 139.5167 60.0 30.5 30.5 21.5 -AT 2 1 19980916 1998091603 1998.70719 35.1825 136.8028 2.0 29.0 29.0 23.0 -AT 2 1 19980918 1998091602 1998.70708 35.4100 139.4000 10.0 26.5 28.2 21.2 -AT 2 1 19980921 1998091604 1998.70731 33.1917 131.6250 50.0 26.2 27.8 20.0 -AT 2 1 19980916 1998091603 1998.70719 35.3408 132.9011 35.0 22.2 23.2 19.8 -AT 2 2 19980918 1998091603 1998.70719 35.8215 139.6715 5.0 33.5 33.5 20.5 -AT 2 2 19980917 1998091603 1998.70719 36.2000 139.2833 35.0 22.0 32.0 21.0 -AT 2 2 19980916 1998091604 1998.70731 33.7333 130.6500 34.0 23.0 34.0 20.0 -AT 2 3 19980918 1998091603 1998.70719 35.1528 129.0303 80.0 28.0 30.0 20.0 -AT 2 1 19980917 1998091601 1998.70696 7.1000 171.2200 3.0 29.0 31.0 26.0 -AT 2 1 19980916 1998091611 1998.70811 51.6667 5.6167 16.0 13.5 17.0 12.0 -AT 2 1 19980916 1998091612 1998.70822 52.3833 4.9333 -1.0 20.0 23.0 10.0 -AT 2 1 19980916 1998091610 1998.70799 52.0852 4.3103 0.0 15.0 18.0 12.0 -AT 2 2 19980916 1998091611 1998.70811 52.7780 6.9092 20.0 14.0 16.0 12.0 -AT 2 1 19980916 1998091609 1998.70788 63.4333 10.6167 20.0 17.0 23.0 11.0 -AT 2 3 19980917 1998091611 1998.70811 68.1458 13.6250 20.0 13.5 19.0 4.5 -AT 2 1 19980918 1998091611 1998.70811 59.2067 10.4033 20.0 13.0 21.0 10.0 -AT 2 1 19980916 1998091611 1998.70811 59.0180 10.0342 35.0 14.0 14.0 10.0 -AT 2 1 19980917 1998091611 1998.70811 59.4850 6.4883 70.0 10.0 11.0 7.0 -AT 2 1 19980917 1998091610 1998.70799 59.5667 9.2667 114.0 17.0 18.0 9.0 -AT 2 1 19980921 1998091612 1998.70822 58.1000 6.6500 15.0 13.5 14.0 10.0 -AT 2 2 19980916 1998091611 1998.70811 61.3538 5.3987 333.0 10.0 11.5 8.0 -AT 2 1 19980921 1998091612 1998.70822 60.1468 11.1639 146.0 15.0 21.0 11.0 -AT 2 1 19980918 1998091611 1998.70811 58.2833 7.9833 49.0 -99.0 24.5 4.0 -AT 2 1 19980921 1998091612 1998.70822 63.7333 10.6333 15.0 9.0 17.0 5.0 -AT 2 1 19980920 1998091612 1998.70822 54.3167 18.6333 5.0 14.5 -99.0 7.5 -AT 2 1 19980916 1998091612 1998.70822 32.8167 -16.9833 30.0 25.5 26.5 21.0 -AT 2 1 19980916 1998091611 1998.70811 59.3428 17.9147 29.0 13.0 13.0 11.0 -AT 2 1 19980916 1998091612 1998.70822 60.6056 16.7468 63.0 18.7 29.2 10.5 -AT 2 1 19980916 1998091611 1998.70811 57.9275 12.0843 15.0 15.5 16.0 11.0 -AT 2 1 19980917 1998091611 1998.70811 63.8110 16.4080 212.0 12.0 24.4 10.7 -AT 2 3 19980916 1998091611 1998.70811 56.0413 13.6785 100.0 13.3 13.3 9.9 -AT 2 1 19980916 1998091609 1998.70788 36.7993 34.5690 51.0 30.5 31.5 22.5 -AT 2 2 19980916 1998091621 1998.70925 57.6138 -152.2355 14.0 15.0 17.0 7.0 -AT 2 2 19980916 1998091620 1998.70913 57.7883 -152.4030 35.0 12.0 16.0 4.0 -AT 2 1 19980918 1998091622 1998.70936 62.6067 -159.5184 135.0 8.0 10.0 4.0 -AT 2 1 19980917 1998091617 1998.70879 32.9439 -85.9539 161.0 28.9 34.0 19.0 -AT 2 1 19980916 1998091616 1998.70868 34.7792 -86.6124 275.0 34.0 35.0 23.0 -AT 2 2 19980916 1998091617 1998.70879 34.8630 -87.5290 178.0 33.0 35.0 24.0 -AT 2 1 19980918 1998091618 1998.70890 33.6669 -93.5914 110.0 23.0 30.0 19.0 -AT 2 1 19980916 1998091617 1998.70879 36.1867 -94.1286 379.0 21.0 28.0 19.0 -AT 2 1 19980917 1998091617 1998.70879 33.6140 -92.0778 43.0 30.0 30.0 22.0 -AT 2 2 19980916 1998091617 1998.70879 36.2012 -94.1738 1389.0 20.0 26.0 20.0 -AT 2 1 19980917 1998091620 1998.70913 32.3593 -111.0118 743.0 37.0 38.0 20.0 -AT 2 1 19980917 1998091618 1998.70890 32.2217 -110.9258 836.0 37.2 38.8 25.0 -AT 2 1 19980916 1998091619 1998.70902 32.2405 -110.8765 762.0 37.0 38.5 25.5 -AT 2 1 19980916 1998091618 1998.70890 33.4483 -112.0730 372.0 36.0 40.0 30.0 -AT 2 2 19980916 1998091618 1998.70890 31.5702 -110.2403 1312.0 31.0 31.0 12.0 -AT 2 1 19980918 1998091619 1998.70902 32.2217 -110.9258 836.0 36.0 37.0 22.0 -AT 2 1 19980916 1998091619 1998.70902 36.7503 -119.8210 89.0 31.0 39.0 15.0 -AT 2 2 19980921 1998091620 1998.70913 36.5963 -119.4493 99.0 33.0 38.0 20.0 -AT 2 2 19980918 1998091621 1998.70925 39.8007 -120.4660 1500.0 30.0 30.0 5.0 -AT 2 1 19980916 1998091620 1998.70913 36.7870 -119.7830 80.0 32.0 34.0 -99.0 -AT 2 1 19980918 1998091619 1998.70902 33.7769 -118.0386 7.0 23.0 26.0 14.0 -AT 2 1 19980921 1998091620 1998.70913 37.2908 -120.3175 87.0 -99.0 36.6 17.4 -AT 2 1 19980918 1998091620 1998.70913 34.2417 -118.4811 213.0 30.0 -99.0 -99.0 -AT 2 2 19980917 1998091619 1998.70902 37.3583 -118.4007 1243.0 30.0 30.0 12.0 -AT 2 2 19980916 1998091618 1998.70890 40.0643 -105.1122 1546.0 22.0 27.0 15.0 -AT 2 1 19980916 1998091618 1998.70890 37.4083 -102.6139 1308.0 32.0 32.0 19.0 -AT 2 1 19980916 1998091618 1998.70890 39.7944 -105.2925 1958.0 24.0 24.0 6.0 -AT 2 2 19980916 1998091616 1998.70868 41.0533 -73.5388 24.0 25.0 40.0 20.0 -AT 2 1 19980918 1998091617 1998.70879 41.8097 -72.8311 31.0 24.0 27.0 19.0 -AT 2 1 19980916 1998091616 1998.70868 26.1425 -80.1395 0.0 30.0 38.0 25.0 -AT 2 3 19980920 1998091618 1998.70890 26.7072 -80.0382 2.0 27.0 28.0 22.0 -AT 2 1 19980916 1998091616 1998.70868 29.4641 -81.2446 6.0 27.0 31.0 27.0 -AT 2 2 19980919 1998091617 1998.70879 28.1013 -80.6243 12.0 26.0 29.0 24.0 -AT 2 2 19980918 1998091617 1998.70879 27.6270 -81.5242 36.0 27.0 33.0 24.0 -AT 2 1 19980921 1998091617 1998.70879 28.0183 -82.1131 31.0 29.0 31.0 23.0 -AT 2 1 19980917 1998091617 1998.70879 33.6675 -84.0178 224.0 30.0 31.0 19.0 -AT 2 1 19980916 1998091618 1998.70890 42.5172 -90.7222 268.0 23.0 26.0 17.0 -AT 2 1 19980921 1998091617 1998.70879 42.8008 -92.2618 288.0 25.0 26.0 16.0 -AT 2 1 19980916 1998091618 1998.70890 41.7181 -94.9322 399.0 17.8 27.8 6.1 -AT 2 1 19980917 1998091616 1998.70868 42.0347 -93.6197 277.0 25.0 25.0 16.0 -AT 2 1 19980916 1998091620 1998.70913 42.7242 -114.5178 1100.0 28.0 32.0 14.0 -AT 2 1 19980917 1998091619 1998.70902 43.4777 -115.3098 1307.0 25.0 37.0 12.0 -AT 2 2 19980916 1998091620 1998.70913 46.7298 -116.9968 836.0 29.0 34.0 18.0 -AT 2 1 19980916 1998091619 1998.70902 43.6279 -111.7409 1856.0 29.0 31.0 11.0 -AT 2 1 19980916 1998091620 1998.70913 42.9321 -114.7119 1111.0 30.0 33.0 14.0 -AT 2 2 19980916 1998091617 1998.70879 41.7600 -87.6765 229.0 26.0 26.0 21.0 -AT 2 4 19980916 1998091617 1998.70879 41.9363 -88.3625 223.0 23.0 23.0 17.0 -AT 2 1 19980916 1998091618 1998.70890 41.8089 -88.0111 203.0 25.0 31.0 20.0 -AT 2 1 19980916 1998091617 1998.70879 41.7412 -87.8932 204.0 26.0 -99.0 -99.0 -AT 2 1 19980916 1998091617 1998.70879 41.9013 -88.3190 215.0 26.0 26.0 18.0 -AT 2 1 19980916 1998091617 1998.70879 41.3975 -90.8994 222.0 22.0 24.0 17.0 -AT 2 1 19980916 1998091617 1998.70879 39.7683 -86.1581 259.0 26.0 27.0 24.0 -AT 2 1 19980916 1998091617 1998.70879 39.5392 -86.3692 218.0 27.0 38.0 18.0 -AT 2 1 19980920 1998091616 1998.70868 41.1306 -85.1289 238.0 21.0 28.0 19.0 -AT 2 2 19980918 1998091618 1998.70890 39.0382 -95.3958 313.0 27.0 30.0 20.0 -AT 2 1 19980916 1998091617 1998.70879 37.3366 -87.5054 134.0 22.0 36.0 8.0 -AT 2 1 19980917 1998091616 1998.70868 38.2542 -85.7594 145.0 32.0 42.0 24.0 -AT 2 1 19980916 1998091616 1998.70868 41.7072 -70.7630 0.0 23.5 27.5 20.0 -AT 2 1 19980918 1998091616 1998.70868 42.5962 -72.3115 287.0 22.0 28.0 20.0 -AT 2 2 19980916 1998091616 1998.70868 38.6215 -76.8627 92.0 33.0 -99.0 -99.0 -AT 2 2 19980916 1998091616 1998.70868 44.3853 -68.2080 22.0 20.0 20.0 13.0 -AT 2 2 19980920 1998091616 1998.70868 44.8817 -69.4458 88.0 21.0 21.0 16.5 -AT 2 1 19980916 1998091617 1998.70879 45.7459 -85.5245 198.0 20.0 -99.0 -99.0 -AT 2 2 19980918 1998091616 1998.70868 42.6733 -83.3885 322.0 25.0 27.0 22.0 -AT 2 2 19980916 1998091617 1998.70879 42.6847 -84.4545 266.0 23.0 26.0 19.0 -AT 2 1 19980916 1998091616 1998.70868 41.9442 -84.8839 327.0 23.0 32.0 21.0 -AT 2 2 19980917 1998091616 1998.70868 42.3363 -85.3522 282.0 25.0 25.0 18.0 -AT 1 1 19980917 1998091618 1998.70890 47.5233 -92.5364 430.0 23.3 23.9 10.6 -AT 2 2 19980916 1998091618 1998.70890 45.2418 -93.4128 201.0 24.0 26.0 24.0 -AT 2 3 19980916 1998091618 1998.70890 40.4177 -91.7128 217.0 24.0 33.0 23.0 -AT 2 1 19980916 1998091618 1998.70890 34.8390 -88.5610 99.0 34.0 35.0 20.0 -AT 2 2 19980916 1998091617 1998.70879 30.4503 -88.8285 0.0 31.0 33.0 23.0 -AT 2 2 19980917 1998091617 1998.70879 30.8427 -89.1102 200.0 29.0 -99.0 -99.0 -AT 2 1 19980918 1998091617 1998.70879 35.5978 -82.4000 832.0 29.0 29.0 28.0 -AT 2 2 19980918 1998091616 1998.70868 36.2417 -80.2908 953.0 30.0 35.0 18.0 -AT 2 1 19980917 1998091617 1998.70879 35.3915 -83.1969 830.0 36.0 38.5 28.0 -AT 2 1 19980916 1998091617 1998.70879 48.1268 -98.8688 486.0 22.0 23.0 12.0 -AT 2 1 19980917 1998091616 1998.70868 42.4739 -96.4133 329.0 25.0 33.0 15.0 -AT 2 2 19980916 1998091616 1998.70868 43.1778 -71.8247 169.0 23.0 29.0 21.0 -AT 2 1 19980916 1998091616 1998.70868 43.2081 -71.5381 105.0 26.0 26.0 15.0 -AT 2 1 19980916 1998091617 1998.70879 40.8989 -74.0931 25.0 33.0 33.0 22.0 -AT 2 1 19980916 1998091618 1998.70890 39.9008 -74.8239 17.0 20.5 20.5 19.5 -AT 2 2 19980916 1998091617 1998.70879 43.0217 -74.3722 289.0 21.0 25.0 17.0 -AT 2 1 19980920 1998091617 1998.70879 43.2992 -73.6356 84.0 19.0 23.5 17.0 -AT 2 1 19980918 1998091616 1998.70868 43.1008 -74.7733 234.0 21.0 26.0 19.0 -AT 2 1 19980916 1998091616 1998.70868 42.8526 -78.8252 125.0 19.0 26.0 13.0 -AT 2 2 19980916 1998091616 1998.70868 43.2072 -78.4593 446.0 18.0 27.0 17.0 -AT 2 2 19980916 1998091617 1998.70879 42.9048 -78.8602 162.0 18.0 26.0 16.0 -AT 2 1 19980916 1998091616 1998.70868 38.9928 -83.4644 265.0 24.0 31.0 20.0 -AT 2 1 19980916 1998091616 1998.70868 40.7473 -81.0400 314.0 26.0 29.0 18.0 -AT 2 1 19980916 1998091616 1998.70868 39.9611 -82.9989 224.0 28.0 32.0 20.0 -AT 2 1 19980916 1998091619 1998.70902 34.6452 -97.9518 360.0 27.0 32.0 22.0 -AT 2 1 19980917 1998091618 1998.70890 36.0906 -94.9200 280.0 23.0 28.0 20.0 -AT 2 1 19980917 1998091618 1998.70890 35.5485 -97.4150 364.0 32.0 35.0 20.0 -AT 2 1 19980916 1998091618 1998.70890 45.1753 -121.0803 666.0 24.0 34.0 13.0 -AT 2 2 19980920 1998091617 1998.70879 41.3393 -80.3955 350.0 20.0 26.0 17.0 -AT 2 2 19980917 1998091617 1998.70879 40.7867 -77.0345 162.0 29.0 31.0 19.0 -AT 2 1 19980916 1998091615 1998.70856 40.5343 -80.1801 316.0 22.0 31.0 20.0 -AT 2 1 19980916 1998091615 1998.70856 39.9470 -75.9753 160.0 29.4 30.0 17.8 -AT 2 2 19980916 1998091616 1998.70868 39.9345 -77.2450 215.0 32.0 33.0 20.0 -AT 2 1 19980916 1998091616 1998.70868 41.4488 -75.6018 465.0 26.0 30.0 15.0 -AT 2 3 19980916 1998091617 1998.70879 40.0435 -75.0243 -11.0 32.0 32.0 22.0 -AT 2 2 19980918 1998091617 1998.70879 39.7487 -77.5712 204.0 28.0 33.0 20.0 -AT 2 1 19980916 1998091617 1998.70879 41.6311 -78.0917 490.0 24.0 25.0 -99.0 -AT 2 1 19980919 1998091617 1998.70879 39.9606 -75.6058 111.0 32.0 33.0 22.0 -AT 2 1 19980916 1998091616 1998.70868 18.4987 -67.1398 56.0 32.0 33.0 25.0 -AT 2 1 19980917 1998091616 1998.70868 18.3994 -66.0503 234.0 34.0 35.0 16.0 -AT 2 1 19980916 1998091615 1998.70856 32.4258 -80.7292 6.0 30.0 32.0 20.0 -AT 2 1 19980916 1998091618 1998.70890 45.8817 -98.1550 390.0 25.0 28.0 12.0 -AT 2 1 19980916 1998091618 1998.70890 29.7631 -95.3631 7.0 24.0 28.0 22.0 -AT 2 2 19980916 1998091618 1998.70890 32.8598 -96.8002 161.0 26.0 31.0 21.0 -AT 2 2 19980916 1998091618 1998.70890 29.5052 -98.6833 183.0 23.0 44.0 22.0 -AT 2 1 19980921 1998091618 1998.70890 29.8073 -95.5373 7.0 26.0 27.0 24.0 -AT 2 2 19980916 1998091617 1998.70879 29.7977 -95.5793 7.0 27.0 29.5 25.0 -AT 2 1 19980917 1998091618 1998.70890 29.5611 -104.3640 837.0 28.0 40.0 22.0 -AT 2 2 19980916 1998091618 1998.70890 31.1020 -97.7372 289.0 23.5 31.0 22.0 -AT 2 1 19980921 1998091619 1998.70902 41.8067 -111.3050 1802.0 25.0 26.0 8.0 -AT 2 1 19980919 1998091619 1998.70902 40.7608 -111.8903 1711.0 26.0 34.0 17.0 -AT 2 1 19980916 1998091616 1998.70868 37.1000 -79.9000 304.0 35.0 36.0 18.0 -AT 2 2 19980920 1998091617 1998.70879 37.0510 -76.3222 3.0 25.0 35.0 15.0 -AT 2 1 19980917 1998091616 1998.70868 38.0391 -78.4868 117.0 31.0 36.0 20.0 -AT 2 1 19980917 1998091616 1998.70868 44.4053 -72.9933 664.0 22.0 -99.0 -99.0 -AT 2 1 19980916 1998091619 1998.70902 48.1832 -122.1198 157.0 22.0 27.0 9.0 -AT 2 1 19980916 1998091619 1998.70902 47.6589 -117.4250 675.0 27.0 34.0 26.0 -AT 2 1 19980916 1998091619 1998.70902 48.5467 -117.9044 774.0 26.0 33.0 12.0 -AT 2 2 19980916 1998091620 1998.70913 48.5070 -122.6208 83.0 20.0 21.0 10.0 -AT 2 2 19980916 1998091617 1998.70879 43.3852 -87.9413 209.0 24.0 32.0 9.0 -AT 2 2 19980916 1998091616 1998.70868 46.7133 -92.0920 213.0 23.0 23.0 18.0 -AT 2 1 19980916 1998091618 1998.70890 44.7361 -87.6208 208.0 16.0 18.0 -15.0 -AT 2 1 19980921 1998091618 1998.70890 42.0544 -104.9520 1506.0 26.0 26.0 10.0 -AT 1 1 19980921 1998091515 1998.70582 -63.4000 -56.9833 10.0 -11.4 -9.5 -21.8 -AT 2 1 19980920 1998091515 1998.70582 -34.5292 -58.5162 22.0 19.0 19.0 6.0 -AT 2 1 19980915 1998091501 1998.70422 -33.6427 150.0425 1220.0 8.0 8.0 1.0 -AT 2 1 19980915 1998091501 1998.70422 -33.8333 152.0000 0.0 20.0 22.0 9.0 -AT 2 2 19980915 1998091503 1998.70445 -27.2170 153.0546 2.0 22.0 29.0 -99.0 -AT 2 1 19980917 1998091501 1998.70422 -27.6000 153.1000 62.0 21.0 29.0 21.0 -AT 2 1 19980915 1998091503 1998.70445 -16.9167 145.7667 12.0 27.0 30.0 20.0 -AT 2 1 19980915 1998091502 1998.70434 -34.7833 138.7167 165.0 13.4 16.1 9.1 -AT 2 1 19980915 1998091503 1998.70445 -37.8167 144.9667 12.0 8.0 22.0 7.0 -AT 2 1 19980915 1998091504 1998.70457 -32.3333 115.9500 20.0 20.0 20.0 8.0 -AT 2 1 19980918 1998091511 1998.70537 50.8103 4.9368 55.0 16.5 18.0 5.5 -AT 2 1 19980915 1998091511 1998.70537 47.6535 9.1260 420.0 13.0 13.0 9.0 -AT 2 1 19980921 1998091511 1998.70537 47.5678 7.6362 260.0 14.0 14.0 11.0 -AT 2 1 19980916 1998091512 1998.70548 47.5017 9.4242 400.0 20.0 21.0 9.0 -AT 2 1 19980915 1998091511 1998.70537 46.7403 7.6083 565.0 15.0 15.0 9.5 -AT 2 1 19980921 1998091504 1998.70457 37.5319 121.3792 30.0 27.5 29.0 21.0 -AT 2 1 19980916 1998091511 1998.70537 48.9908 17.7203 250.0 11.5 13.0 8.0 -AT 2 1 19980916 1998091511 1998.70537 49.5420 15.3537 518.0 9.0 12.0 5.0 -AT 2 2 19980915 1998091509 1998.70514 53.3817 12.6002 72.0 11.0 14.0 6.0 -AT 2 3 19980918 1998091511 1998.70537 50.5412 8.5220 260.0 12.0 14.0 6.0 -AT 2 1 19980916 1998091511 1998.70537 51.0167 13.8333 112.0 14.6 15.0 9.0 -AT 1 3 19980915 1998091509 1998.70514 48.9413 8.3978 129.0 11.0 11.0 10.0 -AT 2 1 19980915 1998091511 1998.70537 50.7863 7.7175 190.0 12.0 12.0 8.0 -AT 2 1 19980915 1998091512 1998.70548 53.5833 11.4167 30.0 12.0 12.0 4.0 -AT 2 1 19980915 1998091509 1998.70514 51.6333 12.2667 55.0 13.0 13.0 7.0 -AT 2 1 19980915 1998091510 1998.70525 52.4252 12.5523 50.0 13.1 14.7 5.7 -AT 2 1 19980915 1998091511 1998.70537 53.6000 10.1667 33.0 13.0 14.0 4.0 -AT 2 1 19980915 1998091510 1998.70525 51.5550 6.9450 38.0 14.5 16.0 9.5 -AT 2 2 19980921 1998091511 1998.70537 50.6080 12.1675 314.0 14.1 14.8 9.6 -AT 2 1 19980915 1998091511 1998.70537 53.5853 9.9472 23.0 11.0 14.5 6.5 -AT 2 1 19980921 1998091511 1998.70537 53.8728 8.7428 0.0 14.0 15.0 11.0 -AT 2 1 19980921 1998091512 1998.70548 52.0833 15.0833 180.0 12.0 14.0 9.0 -AT 2 1 19980916 1998091510 1998.70525 51.3187 13.2825 97.0 13.0 17.0 12.0 -AT 2 1 19980921 1998091511 1998.70537 51.0500 13.6833 111.0 15.0 16.0 8.5 -AT 2 1 19980918 1998091510 1998.70525 48.5895 8.8750 462.0 10.5 12.0 9.0 -AT 2 1 19980918 1998091511 1998.70537 53.6437 9.9630 15.0 10.0 10.0 3.0 -AT 2 1 19980915 1998091511 1998.70537 59.4340 24.7493 60.0 16.0 20.5 12.0 -AT 2 1 19980916 1998091510 1998.70525 59.3922 27.7987 30.0 14.0 -99.0 9.0 -AT 2 2 19980917 1998091511 1998.70537 58.7150 26.7513 80.0 11.0 12.0 10.0 -AT 2 1 19980917 1998091511 1998.70537 58.3767 26.7089 200.0 14.0 22.0 13.0 -AT 2 1 19980915 1998091509 1998.70514 60.4714 25.1058 53.0 16.0 18.0 13.0 -AT 2 1 19980917 1998091511 1998.70537 60.6297 24.8403 125.0 15.0 21.0 -1.0 -AT 2 1 19980921 1998091509 1998.70514 61.6937 27.2650 123.0 15.0 22.0 -1.0 -AT 2 1 19980916 1998091510 1998.70525 63.2377 29.2537 110.0 14.4 19.4 -99.0 -AT 2 2 19980921 1998091510 1998.70525 60.8042 23.4932 105.0 15.2 19.5 13.1 -AT 2 1 19980921 1998091510 1998.70525 64.8781 28.9342 211.0 12.5 13.5 9.0 -AT 2 1 19980916 1998091510 1998.70525 61.6781 27.2033 110.0 14.0 19.0 11.0 -AT 2 1 19980920 1998091510 1998.70525 59.8268 22.9755 0.0 15.0 20.0 14.0 -AT 2 1 19980916 1998091511 1998.70537 61.7403 27.3347 97.0 15.0 21.0 9.0 -AT 2 2 19980915 1998091508 1998.70502 64.7622 26.4150 80.0 13.6 19.6 10.7 -AT 2 1 19980915 1998091510 1998.70525 62.2981 27.1472 124.0 15.0 18.0 13.0 -AT 2 1 19980920 1998091510 1998.70525 60.2662 24.8543 32.0 16.0 20.0 16.0 -AT 2 2 19980918 1998091510 1998.70525 62.3018 27.1365 122.0 16.0 19.0 12.0 -AT 2 2 19980916 1998091510 1998.70525 62.2888 25.7350 100.0 15.3 22.0 12.0 -AT 2 1 19980915 1998091510 1998.70525 37.6717 26.8292 200.0 30.0 33.0 19.0 -AT 2 1 19980921 1998091510 1998.70525 37.9915 23.6752 40.0 31.0 31.0 22.0 -AT 2 1 19980921 1998091510 1998.70525 37.0677 22.4247 207.0 25.5 28.5 20.4 -AT 2 1 19980916 1998091510 1998.70525 37.9365 23.6960 12.0 29.5 31.0 22.0 -AT 2 1 19980918 1998091511 1998.70537 46.0023 16.1195 162.0 17.0 17.0 5.0 -AT 2 1 19980917 1998091512 1998.70548 45.3388 14.3083 10.0 20.0 21.0 10.0 -AT 2 2 19980915 1998091510 1998.70525 45.4933 15.5622 119.0 18.0 18.0 4.0 -AT 2 1 19980917 1998091510 1998.70525 45.5139 17.1278 170.0 20.0 22.0 6.0 -AT 2 2 19980918 1998091512 1998.70548 46.0532 16.1832 172.0 18.0 18.0 4.0 -AT 2 1 19980917 1998091512 1998.70548 45.3278 14.4458 20.0 21.0 21.0 11.0 -AT 2 1 19980917 1998091511 1998.70537 45.8295 17.3845 124.0 20.0 20.0 6.0 -AT 2 2 19980916 1998091512 1998.70548 63.9982 -22.5603 15.0 8.0 9.0 5.0 -AT 2 1 19980921 1998091511 1998.70537 32.0212 35.7178 894.0 30.0 32.0 19.0 -AT 2 2 19980916 1998091504 1998.70457 35.3500 136.9000 49.0 26.0 31.0 22.0 -AT 2 1 19980917 1998091502 1998.70434 39.8283 140.0571 64.0 23.0 30.0 21.8 -AT 2 2 19980915 1998091502 1998.70434 38.6527 141.2933 60.0 27.0 27.0 18.0 -AT 2 2 19980917 1998091504 1998.70457 36.5333 136.6667 60.0 26.9 26.9 21.6 -AT 2 1 19980916 1998091503 1998.70445 35.1825 136.8028 2.0 30.0 32.0 24.0 -AT 2 1 19980918 1998091502 1998.70434 35.4100 139.4000 10.0 25.5 29.2 20.6 -AT 2 1 19980921 1998091504 1998.70457 33.1917 131.6250 50.0 24.8 25.0 22.2 -AT 2 3 19980918 1998091503 1998.70445 35.1528 129.0303 80.0 32.5 34.0 20.0 -AT 2 1 19980917 1998091503 1998.70445 37.3095 127.0053 93.0 23.7 27.5 23.0 -AT 2 1 19980915 1998091503 1998.70445 35.1667 126.8833 70.0 27.1 31.2 12.3 -AT 2 1 19980917 1998091501 1998.70422 7.1000 171.2200 3.0 30.2 33.0 30.0 -AT 2 1 19980916 1998091511 1998.70537 51.6667 5.6167 16.0 15.0 15.0 8.0 -AT 2 1 19980917 1998091512 1998.70548 51.2508 5.9389 30.0 15.0 23.0 5.0 -AT 2 1 19980915 1998091512 1998.70548 52.3833 4.9333 -1.0 16.0 16.5 12.0 -AT 2 1 19980918 1998091510 1998.70525 52.0852 4.3103 0.0 15.0 15.0 12.0 -AT 2 2 19980915 1998091511 1998.70537 52.7780 6.9092 20.0 13.0 14.0 9.0 -AT 2 1 19980915 1998091511 1998.70537 63.4333 10.6167 20.0 20.0 25.0 9.0 -AT 2 3 19980915 1998091511 1998.70537 68.1458 13.6250 20.0 17.0 17.5 7.5 -AT 2 1 19980918 1998091511 1998.70537 59.2067 10.4033 20.0 17.0 17.0 13.0 -AT 2 1 19980916 1998091511 1998.70537 59.0180 10.0342 35.0 16.0 17.0 13.0 -AT 2 2 19980921 1998091510 1998.70525 58.9428 5.6570 37.0 12.5 16.5 8.0 -AT 2 1 19980916 1998091510 1998.70525 59.5667 9.2667 114.0 16.0 18.0 11.0 -AT 2 1 19980921 1998091512 1998.70548 58.1000 6.6500 15.0 12.0 13.5 12.0 -AT 2 2 19980915 1998091510 1998.70525 61.3538 5.3987 333.0 13.0 18.0 9.0 -AT 2 1 19980921 1998091511 1998.70537 60.1468 11.1639 146.0 16.5 17.0 9.0 -AT 2 1 19980918 1998091511 1998.70537 58.2833 7.9833 49.0 13.7 20.0 10.0 -AT 2 1 19980921 1998091512 1998.70548 63.7333 10.6333 15.0 10.0 17.0 5.5 -AT 2 1 19980920 1998091512 1998.70548 54.3167 18.6333 5.0 21.4 -99.0 8.0 -AT 2 1 19980915 1998091512 1998.70548 32.8167 -16.9833 30.0 24.0 28.0 21.0 -AT 2 1 19980916 1998091510 1998.70525 59.3428 17.9147 29.0 12.0 19.0 11.0 -AT 2 1 19980915 1998091511 1998.70537 57.9275 12.0843 15.0 14.5 16.0 11.5 -AT 2 1 19980916 1998091512 1998.70548 63.8110 16.4080 212.0 13.0 -99.0 -99.0 -AT 2 3 19980915 1998091511 1998.70537 56.0413 13.6785 100.0 11.7 14.9 8.5 -AT 2 1 19980915 1998091509 1998.70514 36.7993 34.5690 51.0 30.0 31.5 23.5 -AT 2 2 19980915 1998091521 1998.70651 57.6138 -152.2355 14.0 12.0 15.0 3.0 -AT 2 2 19980915 1998091520 1998.70639 57.7883 -152.4030 35.0 11.0 19.0 1.0 -AT 2 2 19980916 1998091522 1998.70662 64.8380 -147.7277 150.0 18.0 27.0 5.0 -AT 2 1 19980918 1998091522 1998.70662 62.6067 -159.5184 135.0 8.0 10.0 4.0 -AT 2 1 19980915 1998091518 1998.70616 31.2445 -85.4483 71.0 33.0 34.0 23.0 -AT 2 1 19980917 1998091517 1998.70605 32.9439 -85.9539 161.0 29.0 35.6 20.0 -AT 2 1 19980915 1998091517 1998.70605 34.6545 -86.5740 143.0 32.0 38.0 14.0 -AT 2 1 19980915 1998091516 1998.70594 34.7792 -86.6124 275.0 32.0 33.0 22.0 -AT 2 2 19980915 1998091517 1998.70605 34.8630 -87.5290 178.0 30.0 35.0 19.0 -AT 2 1 19980916 1998091518 1998.70616 35.2969 -94.0361 198.0 22.5 22.5 20.0 -AT 2 1 19980918 1998091518 1998.70616 33.6669 -93.5914 110.0 31.0 39.0 20.0 -AT 2 1 19980915 1998091517 1998.70605 36.1867 -94.1286 379.0 26.0 27.0 19.0 -AT 2 1 19980915 1998091517 1998.70605 33.6140 -92.0778 43.0 25.5 33.0 21.0 -AT 2 2 19980915 1998091517 1998.70605 36.2012 -94.1738 1389.0 25.0 25.0 22.0 -AT 2 1 19980915 1998091520 1998.70639 32.3593 -111.0118 743.0 37.0 38.0 21.0 -AT 2 1 19980916 1998091518 1998.70616 32.2217 -110.9258 836.0 37.2 39.4 21.1 -AT 2 1 19980915 1998091519 1998.70628 32.2405 -110.8765 762.0 36.5 39.0 22.0 -AT 2 2 19980915 1998091518 1998.70616 31.5702 -110.2403 1312.0 27.0 36.0 18.0 -AT 2 1 19980918 1998091519 1998.70628 32.2217 -110.9258 836.0 37.0 37.0 21.0 -AT 2 2 19980921 1998091520 1998.70639 36.5963 -119.4493 99.0 33.0 38.0 21.0 -AT 2 2 19980918 1998091520 1998.70639 39.8007 -120.4660 1500.0 30.0 31.0 6.0 -AT 2 1 19980916 1998091520 1998.70639 36.7870 -119.7830 80.0 31.0 36.0 20.0 -AT 2 1 19980917 1998091519 1998.70628 33.7769 -118.0386 7.0 24.0 26.0 14.0 -AT 2 1 19980921 1998091520 1998.70639 37.2908 -120.3175 87.0 -99.0 37.3 18.3 -AT 2 1 19980918 1998091520 1998.70639 34.2417 -118.4811 213.0 30.0 -99.0 -99.0 -AT 2 2 19980915 1998091519 1998.70628 37.3583 -118.4007 1243.0 30.0 31.0 11.0 -AT 2 2 19980915 1998091518 1998.70616 40.0643 -105.1122 1546.0 32.0 35.0 10.0 -AT 2 1 19980916 1998091518 1998.70616 37.4083 -102.6139 1308.0 24.0 28.0 19.0 -AT 2 2 19980915 1998091516 1998.70594 41.0533 -73.5388 24.0 25.0 25.0 19.0 -AT 2 1 19980918 1998091517 1998.70605 41.8097 -72.8311 31.0 26.0 26.0 17.0 -AT 2 2 19980915 1998091517 1998.70605 25.6753 -80.2850 20.0 26.0 34.0 25.0 -AT 2 1 19980915 1998091516 1998.70594 26.1425 -80.1395 0.0 32.0 39.0 30.0 -AT 2 3 19980920 1998091518 1998.70616 26.7072 -80.0382 2.0 28.0 33.0 25.0 -AT 2 1 19980915 1998091517 1998.70605 28.5381 -81.3794 23.0 28.0 30.0 25.0 -AT 2 1 19980916 1998091516 1998.70594 29.4641 -81.2446 6.0 31.0 31.0 25.0 -AT 2 2 19980919 1998091517 1998.70605 28.1013 -80.6243 12.0 30.0 31.0 26.0 -AT 2 2 19980918 1998091517 1998.70605 27.6270 -81.5242 36.0 31.0 32.0 24.0 -AT 2 1 19980921 1998091517 1998.70605 28.0183 -82.1131 31.0 31.0 33.0 22.0 -AT 2 1 19980915 1998091517 1998.70605 33.6675 -84.0178 224.0 29.0 31.0 19.0 -AT 2 1 19980915 1998091517 1998.70605 42.5172 -90.7222 268.0 20.0 24.0 18.0 -AT 2 1 19980916 1998091518 1998.70616 42.0678 -90.1741 178.0 24.0 36.0 14.0 -AT 2 1 19980915 1998091518 1998.70616 42.7013 -92.0744 310.0 24.0 25.0 20.0 -AT 2 1 19980921 1998091517 1998.70605 42.8008 -92.2618 288.0 25.0 25.0 18.0 -AT 2 1 19980915 1998091518 1998.70616 41.7181 -94.9322 399.0 26.0 27.0 17.0 -AT 2 1 19980915 1998091516 1998.70594 42.0347 -93.6197 277.0 26.0 26.0 19.0 -AT 2 1 19980917 1998091518 1998.70616 41.5568 -90.6042 188.0 22.0 23.0 19.0 -AT 2 1 19980915 1998091520 1998.70639 42.7242 -114.5178 1100.0 28.0 -99.0 -99.0 -AT 2 1 19980915 1998091519 1998.70628 43.4777 -115.3098 1307.0 30.0 32.0 10.0 -AT 2 2 19980915 1998091519 1998.70628 46.7298 -116.9968 836.0 30.0 32.0 18.0 -AT 2 1 19980915 1998091519 1998.70628 43.6279 -111.7409 1856.0 29.0 29.0 11.0 -AT 2 1 19980916 1998091519 1998.70628 42.6185 -112.0176 2184.0 28.0 31.0 20.0 -AT 2 2 19980916 1998091517 1998.70605 41.7600 -87.6765 229.0 22.0 28.0 22.0 -AT 2 2 19980915 1998091517 1998.70605 42.3333 -89.0333 252.0 21.0 21.0 20.0 -AT 2 1 19980915 1998091518 1998.70616 41.4392 -90.7175 223.0 23.0 23.0 22.0 -AT 2 4 19980916 1998091517 1998.70605 41.9363 -88.3625 223.0 21.0 21.0 20.0 -AT 2 1 19980921 1998091517 1998.70605 41.7676 -88.2930 203.0 23.0 24.0 19.0 -AT 2 1 19980915 1998091518 1998.70616 41.8089 -88.0111 203.0 22.0 33.0 21.0 -AT 2 1 19980917 1998091517 1998.70605 41.9119 -88.2908 215.0 23.0 24.0 17.0 -AT 2 1 19980915 1998091517 1998.70605 41.9013 -88.3190 215.0 22.0 24.0 20.0 -AT 2 1 19980915 1998091517 1998.70605 41.3975 -90.8994 222.0 22.0 36.0 13.0 -AT 2 1 19980916 1998091517 1998.70605 39.7683 -86.1581 259.0 25.0 33.0 25.0 -AT 2 1 19980915 1998091517 1998.70605 39.5392 -86.3692 218.0 26.0 39.0 19.0 -AT 2 1 19980920 1998091516 1998.70594 41.1306 -85.1289 238.0 26.0 32.5 20.5 -AT 2 2 19980918 1998091518 1998.70616 39.0382 -95.3958 313.0 27.0 30.0 20.0 -AT 2 1 19980915 1998091517 1998.70605 37.3366 -87.5054 134.0 30.0 31.0 8.0 -AT 2 2 19980915 1998091517 1998.70605 36.9320 -84.0933 307.0 30.0 36.0 22.0 -AT 2 1 19980915 1998091517 1998.70605 37.5528 -87.9893 113.0 27.0 32.0 20.0 -AT 2 1 19980916 1998091517 1998.70605 37.5728 -82.7528 355.0 28.0 32.0 17.0 -AT 2 1 19980916 1998091517 1998.70605 36.8302 -84.8523 364.0 31.0 32.0 21.0 -AT 2 1 19980915 1998091516 1998.70594 38.2542 -85.7594 145.0 27.0 28.0 20.0 -AT 2 1 19980915 1998091516 1998.70594 41.7072 -70.7630 0.0 25.5 26.5 18.0 -AT 2 2 19980917 1998091515 1998.70582 42.3697 -71.7850 160.0 28.0 29.0 20.0 -AT 2 1 19980916 1998091516 1998.70594 42.5962 -72.3115 287.0 23.5 23.5 20.0 -AT 2 1 19980915 1998091516 1998.70594 44.3670 -69.7340 81.0 25.0 28.0 15.0 -AT 2 2 19980915 1998091516 1998.70594 44.3853 -68.2080 22.0 17.0 20.0 13.0 -AT 2 2 19980920 1998091516 1998.70594 44.8817 -69.4458 88.0 18.5 26.0 10.5 -AT 2 1 19980915 1998091518 1998.70616 43.0128 -83.6914 248.0 24.0 28.0 20.0 -AT 2 1 19980916 1998091517 1998.70605 45.7459 -85.5245 198.0 19.0 -99.0 -99.0 -AT 2 2 19980918 1998091516 1998.70594 42.6733 -83.3885 322.0 25.5 28.5 18.0 -AT 2 1 19980915 1998091516 1998.70594 41.9442 -84.8839 327.0 36.0 41.0 11.0 -AT 2 2 19980916 1998091516 1998.70594 43.9393 -82.9968 217.0 27.0 27.0 26.0 -AT 2 2 19980916 1998091516 1998.70594 42.3363 -85.3522 282.0 21.0 28.0 19.0 -AT 2 1 19980915 1998091516 1998.70594 42.4427 -85.6413 259.0 22.0 26.5 20.0 -AT 2 1 19980916 1998091518 1998.70616 45.5897 -94.1483 372.0 24.0 25.0 10.0 -AT 1 1 19980916 1998091518 1998.70616 47.5233 -92.5364 430.0 22.2 22.2 11.1 -AT 2 3 19980915 1998091518 1998.70616 40.4177 -91.7128 217.0 24.0 32.0 22.0 -AT 2 1 19980915 1998091518 1998.70616 34.8390 -88.5610 99.0 32.0 34.0 20.0 -AT 2 2 19980915 1998091517 1998.70605 30.8427 -89.1102 200.0 31.0 -99.0 -99.0 -AT 2 2 19980918 1998091519 1998.70628 45.4500 -112.1897 1559.0 27.0 29.0 10.0 -AT 2 1 19980918 1998091516 1998.70594 34.6914 -76.8937 0.0 30.0 31.5 12.0 -AT 2 2 19980918 1998091517 1998.70605 36.2417 -80.2908 953.0 29.0 36.0 16.0 -AT 1 2 19980918 1998091517 1998.70605 35.5950 -82.5062 719.0 32.2 32.8 11.1 -AT 2 1 19980915 1998091517 1998.70605 48.1268 -98.8688 486.0 18.0 37.0 5.0 -AT 2 2 19980916 1998091516 1998.70594 43.1778 -71.8247 169.0 23.0 28.0 19.0 -AT 2 1 19980915 1998091515 1998.70582 42.8650 -71.4939 80.0 28.0 28.0 20.0 -AT 2 1 19980915 1998091516 1998.70594 43.2081 -71.5381 105.0 25.0 27.5 19.0 -AT 2 1 19980915 1998091516 1998.70594 40.8989 -74.0931 25.0 27.0 31.0 21.0 -AT 2 2 19980915 1998091517 1998.70605 43.0217 -74.3722 289.0 23.0 26.0 18.0 -AT 2 1 19980920 1998091517 1998.70605 43.2992 -73.6356 84.0 22.0 25.0 18.5 -AT 2 1 19980915 1998091516 1998.70594 41.1456 -73.8242 73.0 29.0 29.0 23.0 -AT 2 1 19980915 1998091516 1998.70594 43.1008 -74.7733 234.0 24.0 29.0 8.0 -AT 2 1 19980915 1998091516 1998.70594 42.8526 -78.8252 125.0 27.0 28.0 19.0 -AT 2 2 19980916 1998091516 1998.70594 43.2072 -78.4593 446.0 26.0 29.0 21.0 -AT 2 1 19980915 1998091516 1998.70594 41.4739 -81.5372 314.0 27.5 35.0 23.0 -AT 2 1 19980915 1998091516 1998.70594 38.9928 -83.4644 265.0 31.0 32.0 22.0 -AT 2 1 19980915 1998091516 1998.70594 40.7473 -81.0400 314.0 30.0 32.0 19.0 -AT 2 1 19980915 1998091516 1998.70594 39.9611 -82.9989 224.0 30.0 38.0 21.0 -AT 2 1 19980915 1998091518 1998.70616 34.6452 -97.9518 360.0 29.0 32.0 22.0 -AT 2 1 19980917 1998091518 1998.70616 36.0906 -94.9200 280.0 24.0 27.0 21.0 -AT 2 1 19980917 1998091518 1998.70616 35.5485 -97.4150 364.0 32.0 36.0 20.0 -AT 2 1 19980915 1998091518 1998.70616 45.1753 -121.0803 666.0 22.0 33.0 10.0 -AT 2 2 19980920 1998091517 1998.70605 41.3393 -80.3955 350.0 25.5 30.0 18.0 -AT 2 2 19980917 1998091517 1998.70605 40.7867 -77.0345 162.0 27.0 33.0 21.0 -AT 2 1 19980915 1998091515 1998.70582 40.5343 -80.1801 316.0 25.0 32.0 20.0 -AT 2 1 19980915 1998091518 1998.70616 40.4847 -78.0106 358.0 32.0 35.0 17.0 -AT 2 1 19980916 1998091515 1998.70582 39.9470 -75.9753 160.0 26.7 30.0 18.9 -AT 2 2 19980916 1998091516 1998.70594 39.9345 -77.2450 215.0 29.0 37.0 14.0 -AT 2 1 19980915 1998091516 1998.70594 41.4488 -75.6018 465.0 26.0 32.0 20.0 -AT 2 3 19980915 1998091517 1998.70605 40.0435 -75.0243 -11.0 35.0 35.0 17.5 -AT 2 2 19980915 1998091517 1998.70605 39.7487 -77.5712 204.0 28.0 32.0 20.0 -AT 2 1 19980919 1998091517 1998.70605 39.9606 -75.6058 111.0 29.0 31.0 20.0 -AT 2 2 19980921 1998091516 1998.70594 18.0340 -66.8733 57.0 32.0 34.0 27.0 -AT 2 1 19980915 1998091516 1998.70594 18.4987 -67.1398 56.0 31.0 34.5 24.0 -AT 2 1 19980915 1998091516 1998.70594 18.3994 -66.0503 234.0 29.0 35.0 18.0 -AT 2 1 19980915 1998091515 1998.70582 32.4258 -80.7292 6.0 30.0 33.0 20.0 -AT 2 1 19980915 1998091519 1998.70628 45.8817 -98.1550 390.0 23.0 28.0 8.0 -AT 2 1 19980915 1998091517 1998.70605 35.0531 -85.0503 266.0 29.0 36.0 26.0 -AT 2 2 19980915 1998091518 1998.70616 32.8598 -96.8002 161.0 23.0 31.0 23.0 -AT 2 1 19980921 1998091518 1998.70616 29.8073 -95.5373 7.0 29.0 32.0 28.0 -AT 2 2 19980915 1998091517 1998.70605 29.7977 -95.5793 7.0 29.0 34.0 25.0 -AT 2 1 19980915 1998091518 1998.70616 29.7533 -95.7152 24.0 27.0 44.0 25.0 -AT 2 1 19980915 1998091517 1998.70605 32.8139 -96.9486 184.0 22.0 35.0 -99.0 -AT 2 2 19980915 1998091519 1998.70628 31.1020 -97.7372 289.0 30.0 31.0 24.0 -AT 2 1 19980921 1998091519 1998.70628 41.8067 -111.3050 1802.0 25.0 26.0 6.0 -AT 2 1 19980915 1998091518 1998.70616 40.5697 -111.8540 1594.0 -99.0 42.0 15.0 -AT 2 1 19980917 1998091519 1998.70628 40.7608 -111.8903 1711.0 23.0 31.0 15.0 -AT 2 1 19980915 1998091516 1998.70594 37.1000 -79.9000 304.0 33.0 37.0 18.0 -AT 2 1 19980917 1998091517 1998.70605 37.5372 -79.3990 289.0 29.0 38.0 17.0 -AT 2 1 19980917 1998091516 1998.70594 38.0391 -78.4868 117.0 32.0 36.0 20.0 -AT 2 1 19980916 1998091516 1998.70594 44.4053 -72.9933 664.0 20.0 20.0 17.0 -AT 2 1 19980916 1998091520 1998.70639 48.6969 -122.9042 140.0 18.0 19.0 -99.0 -AT 2 1 19980915 1998091519 1998.70628 48.1832 -122.1198 157.0 17.0 25.5 8.0 -AT 2 1 19980915 1998091519 1998.70628 47.6589 -117.4250 675.0 30.0 31.0 12.0 -AT 2 1 19980916 1998091519 1998.70628 48.5467 -117.9044 774.0 25.0 30.0 5.5 -AT 2 2 19980915 1998091520 1998.70639 48.5070 -122.6208 83.0 18.0 19.0 10.0 -AT 2 2 19980915 1998091517 1998.70605 43.3852 -87.9413 209.0 21.0 33.0 21.0 -AT 2 2 19980915 1998091516 1998.70594 46.7133 -92.0920 213.0 20.0 25.0 16.0 -AT 2 1 19980915 1998091516 1998.70594 43.3347 -90.3867 250.0 22.0 27.0 5.0 -AT 2 1 19980915 1998091516 1998.70594 43.4005 -90.6196 272.0 20.0 20.0 18.0 -AT 2 1 19980916 1998091518 1998.70616 44.7361 -87.6208 208.0 16.0 20.0 -17.0 -AT 2 1 19980921 1998091518 1998.70616 42.0544 -104.9520 1506.0 25.0 25.0 10.0 -AT 1 1 19980921 1998091415 1998.70308 -63.4000 -56.9833 10.0 -17.9 -14.0 -20.8 -AT 2 1 19980920 1998091415 1998.70308 -34.5292 -58.5162 22.0 16.0 22.0 3.0 -AT 2 1 19980914 1998091401 1998.70148 -33.6427 150.0425 1220.0 10.0 10.0 1.0 -AT 2 1 19980914 1998091401 1998.70148 -33.8333 152.0000 0.0 19.0 24.0 9.0 -AT 2 1 19980914 1998091401 1998.70148 -33.2417 150.5844 310.0 18.5 19.0 6.5 -AT 2 1 19980915 1998091402 1998.70160 -34.7833 138.7167 165.0 15.9 15.9 5.7 -AT 2 1 19980914 1998091403 1998.70171 -37.8167 144.9667 12.0 14.0 22.0 9.0 -AT 2 1 19980914 1998091404 1998.70183 -32.3333 115.9500 20.0 19.0 -99.0 -99.0 -AT 2 1 19980915 1998091411 1998.70263 47.6535 9.1260 420.0 12.0 13.0 7.0 -AT 2 1 19980915 1998091411 1998.70263 47.5678 7.6362 260.0 12.0 16.0 8.0 -AT 2 1 19980916 1998091412 1998.70274 47.5017 9.4242 400.0 10.0 13.0 7.0 -AT 2 1 19980914 1998091411 1998.70263 46.7403 7.6083 565.0 10.5 13.0 6.0 -AT 2 1 19980921 1998091404 1998.70183 37.5319 121.3792 30.0 28.5 32.0 23.5 -AT 1 1 19980916 1998091404 1998.70183 38.6667 114.6000 70.0 24.3 29.1 11.2 -AT 2 1 19980916 1998091411 1998.70263 48.9908 17.7203 250.0 13.0 13.5 7.5 -AT 2 1 19980914 1998091411 1998.70263 49.5420 15.3537 518.0 12.0 12.0 6.0 -AT 2 2 19980914 1998091409 1998.70240 53.3817 12.6002 72.0 12.0 20.3 12.0 -AT 2 3 19980918 1998091411 1998.70263 50.5412 8.5220 260.0 12.0 15.0 7.0 -AT 2 1 19980915 1998091411 1998.70263 51.0167 13.8333 112.0 13.4 14.0 6.0 -AT 1 3 19980914 1998091409 1998.70240 48.9413 8.3978 129.0 11.0 16.0 10.0 -AT 2 1 19980914 1998091411 1998.70263 50.7863 7.7175 190.0 10.0 13.0 7.0 -AT 2 1 19980915 1998091412 1998.70274 53.5833 11.4167 30.0 11.0 12.0 9.0 -AT 2 1 19980914 1998091409 1998.70240 51.6333 12.2667 55.0 12.0 20.0 9.0 -AT 2 1 19980914 1998091409 1998.70240 52.4252 12.5523 50.0 10.9 11.9 7.0 -AT 2 1 19980914 1998091411 1998.70263 51.5550 6.9450 38.0 10.5 20.0 6.0 -AT 2 1 19980916 1998091410 1998.70251 53.6632 13.5572 35.0 15.0 19.0 9.0 -AT 2 2 19980914 1998091410 1998.70251 50.6080 12.1675 314.0 11.1 16.0 7.3 -AT 2 1 19980914 1998091411 1998.70263 53.5853 9.9472 23.0 12.5 15.5 9.0 -AT 2 1 19980914 1998091411 1998.70263 53.8728 8.7428 0.0 13.0 17.0 12.0 -AT 2 1 19980921 1998091411 1998.70263 52.0833 15.0833 180.0 14.0 18.0 6.0 -AT 2 1 19980916 1998091410 1998.70251 51.3187 13.2825 97.0 14.0 28.0 7.0 -AT 2 1 19980921 1998091411 1998.70263 51.0500 13.6833 111.0 14.0 25.0 4.5 -AT 2 1 19980918 1998091410 1998.70251 48.5895 8.8750 462.0 11.0 13.0 6.0 -AT 2 1 19980914 1998091412 1998.70274 53.6437 9.9630 15.0 16.0 -99.0 -99.0 -AT 2 1 19980914 1998091411 1998.70263 59.4425 24.7057 30.0 21.0 24.0 12.0 -AT 2 1 19980915 1998091411 1998.70263 59.4340 24.7493 60.0 20.5 22.6 13.0 -AT 2 1 19980914 1998091410 1998.70251 59.3922 27.7987 30.0 18.0 -99.0 10.0 -AT 2 2 19980917 1998091411 1998.70263 58.7150 26.7513 80.0 22.0 24.0 9.0 -AT 2 1 19980917 1998091411 1998.70263 58.3767 26.7089 200.0 18.0 22.0 13.0 -AT 2 1 19980915 1998091409 1998.70240 60.4714 25.1058 53.0 18.0 19.0 12.0 -AT 2 1 19980914 1998091410 1998.70251 61.6937 27.2650 123.0 19.0 23.0 -4.0 -AT 2 1 19980914 1998091410 1998.70251 63.2377 29.2537 110.0 18.2 18.9 5.1 -AT 2 1 19980914 1998091410 1998.70251 60.1833 24.0167 56.0 19.0 20.0 9.8 -AT 2 2 19980921 1998091410 1998.70251 60.8042 23.4932 105.0 18.0 21.0 11.0 -AT 2 1 19980921 1998091410 1998.70251 64.8781 28.9342 211.0 12.0 12.0 7.0 -AT 2 1 19980914 1998091409 1998.70240 66.5078 25.7033 123.0 10.0 13.0 5.0 -AT 2 1 19980915 1998091409 1998.70240 61.4805 23.8000 80.0 15.0 20.0 12.0 -AT 2 1 19980920 1998091410 1998.70251 59.8268 22.9755 0.0 17.0 21.0 14.0 -AT 2 1 19980915 1998091410 1998.70251 64.9028 25.4694 15.0 16.0 16.0 7.0 -AT 2 2 19980915 1998091410 1998.70251 60.4543 26.2247 30.0 19.0 19.0 13.0 -AT 2 2 19980914 1998091410 1998.70251 64.7622 26.4150 80.0 15.7 15.7 10.7 -AT 2 1 19980914 1998091410 1998.70251 62.2981 27.1472 124.0 19.0 19.0 12.0 -AT 2 2 19980914 1998091409 1998.70240 60.9902 25.5207 155.0 18.0 19.0 7.0 -AT 2 1 19980920 1998091411 1998.70263 60.2662 24.8543 32.0 19.0 20.0 16.0 -AT 2 1 19980914 1998091408 1998.70228 62.2658 26.2078 93.0 16.0 20.0 8.0 -AT 2 2 19980918 1998091410 1998.70251 62.3018 27.1365 122.0 18.0 20.0 9.0 -AT 2 2 19980916 1998091410 1998.70251 62.2888 25.7350 100.0 16.4 22.0 7.0 -AT 2 1 19980916 1998091410 1998.70251 60.8042 23.4944 110.0 17.0 17.0 14.0 -AT 2 1 19980916 1998091411 1998.70263 37.9522 23.6133 35.0 31.0 32.0 23.0 -AT 2 1 19980915 1998091410 1998.70251 37.9915 23.6752 40.0 29.0 31.0 21.0 -AT 2 1 19980921 1998091410 1998.70251 37.0677 22.4247 207.0 26.8 28.9 16.0 -AT 2 1 19980916 1998091410 1998.70251 37.9365 23.6960 12.0 28.0 32.0 22.0 -AT 2 1 19980918 1998091411 1998.70263 46.0023 16.1195 162.0 11.0 15.0 9.0 -AT 2 1 19980917 1998091412 1998.70274 45.3388 14.3083 10.0 13.0 28.0 10.0 -AT 2 2 19980915 1998091410 1998.70251 45.4933 15.5622 119.0 9.0 15.0 7.0 -AT 2 1 19980917 1998091410 1998.70251 45.5139 17.1278 170.0 15.0 15.0 11.0 -AT 2 2 19980918 1998091412 1998.70274 46.0532 16.1832 172.0 8.0 15.0 7.0 -AT 2 1 19980914 1998091412 1998.70274 45.3278 14.4458 20.0 19.0 28.0 18.0 -AT 2 1 19980914 1998091411 1998.70263 45.8295 17.3845 124.0 10.0 15.0 10.0 -AT 2 2 19980915 1998091412 1998.70274 63.9982 -22.5603 15.0 7.6 8.5 3.4 -AT 2 1 19980921 1998091411 1998.70263 32.0212 35.7178 894.0 28.0 30.0 17.0 -AT 2 2 19980914 1998091404 1998.70183 35.3500 136.9000 49.0 31.0 34.5 22.5 -AT 2 1 19980914 1998091404 1998.70183 32.1850 130.1675 100.0 32.0 32.0 26.0 -AT 2 1 19980917 1998091402 1998.70160 39.8283 140.0571 64.0 28.5 28.5 14.5 -AT 2 2 19980914 1998091404 1998.70183 38.6527 141.2933 60.0 24.0 25.0 19.0 -AT 2 2 19980914 1998091404 1998.70183 36.5333 136.6667 60.0 29.5 30.0 20.1 -AT 2 1 19980914 1998091404 1998.70183 34.7033 135.8400 100.0 30.7 33.1 21.0 -AT 2 1 19980916 1998091403 1998.70171 35.1825 136.8028 2.0 30.0 33.0 22.0 -AT 2 1 19980914 1998091402 1998.70160 35.4100 139.4000 10.0 26.9 30.5 21.9 -AT 2 1 19980921 1998091404 1998.70183 33.1917 131.6250 50.0 30.0 31.0 21.6 -AT 2 1 19980916 1998091403 1998.70171 35.3408 132.9011 35.0 29.5 29.5 11.0 -AT 2 2 19980916 1998091403 1998.70171 35.8215 139.6715 5.0 30.0 32.0 22.0 -AT 2 3 19980918 1998091403 1998.70171 35.1528 129.0303 80.0 33.0 34.0 20.0 -AT 2 1 19980917 1998091403 1998.70171 37.3095 127.0053 93.0 25.2 -99.0 -99.0 -AT 2 1 19980914 1998091403 1998.70171 37.3300 126.5800 95.0 29.0 34.0 22.5 -AT 2 1 19980914 1998091403 1998.70171 35.1667 126.8833 70.0 23.5 28.8 18.4 -AT 2 1 19980917 1998091401 1998.70148 7.1000 171.2200 3.0 30.0 30.4 30.0 -AT 2 1 19980914 1998091411 1998.70263 51.6667 5.6167 16.0 13.0 13.0 8.0 -AT 2 1 19980914 1998091412 1998.70274 52.3833 4.9333 -1.0 12.5 17.5 4.5 -AT 2 1 19980914 1998091411 1998.70263 52.0852 4.3103 0.0 12.0 12.0 7.0 -AT 2 2 19980915 1998091411 1998.70263 52.7780 6.9092 20.0 9.0 21.0 6.0 -AT 2 1 19980914 1998091410 1998.70251 63.4333 10.6167 20.0 24.0 24.0 11.0 -AT 2 3 19980914 1998091411 1998.70263 68.1458 13.6250 20.0 15.5 16.0 11.0 -AT 2 1 19980918 1998091411 1998.70263 59.2067 10.4033 20.0 14.0 -99.0 -99.0 -AT 2 1 19980914 1998091411 1998.70263 59.0180 10.0342 35.0 15.0 15.0 12.0 -AT 2 1 19980915 1998091411 1998.70263 59.4850 6.4883 70.0 13.0 17.0 11.0 -AT 2 2 19980921 1998091410 1998.70251 58.9428 5.6570 37.0 14.5 17.5 7.0 -AT 2 1 19980916 1998091410 1998.70251 59.5667 9.2667 114.0 15.0 17.0 9.0 -AT 2 1 19980921 1998091412 1998.70274 58.1000 6.6500 15.0 12.5 -99.0 -99.0 -AT 2 2 19980914 1998091410 1998.70251 61.3538 5.3987 333.0 12.5 17.5 7.5 -AT 2 1 19980914 1998091411 1998.70263 58.2833 7.9833 49.0 14.0 14.0 8.5 -AT 2 1 19980921 1998091412 1998.70274 63.7333 10.6333 15.0 20.0 20.5 9.5 -AT 2 1 19980920 1998091412 1998.70274 54.3167 18.6333 5.0 22.3 -99.0 12.0 -AT 2 1 19980914 1998091412 1998.70274 32.8167 -16.9833 30.0 24.5 25.0 20.0 -AT 2 1 19980914 1998091410 1998.70251 59.3428 17.9147 29.0 18.0 20.0 11.0 -AT 2 1 19980914 1998091410 1998.70251 57.9275 12.0843 15.0 16.5 17.5 12.0 -AT 2 1 19980916 1998091412 1998.70274 63.8110 16.4080 212.0 14.0 -99.0 -99.0 -AT 2 3 19980914 1998091411 1998.70263 56.0413 13.6785 100.0 13.0 16.4 10.5 -AT 2 2 19980915 1998091421 1998.70377 57.6138 -152.2355 14.0 11.0 14.0 4.0 -AT 2 2 19980915 1998091420 1998.70365 57.7883 -152.4030 35.0 14.0 16.0 5.0 -AT 2 2 19980916 1998091422 1998.70388 64.8380 -147.7277 150.0 20.0 29.0 4.0 -AT 2 1 19980914 1998091422 1998.70388 62.6067 -159.5184 135.0 5.0 8.0 1.0 -AT 2 1 19980915 1998091418 1998.70342 31.2445 -85.4483 71.0 34.0 34.0 18.5 -AT 2 1 19980915 1998091417 1998.70331 32.9439 -85.9539 161.0 28.0 34.0 19.0 -AT 2 1 19980914 1998091416 1998.70320 34.7792 -86.6124 275.0 32.0 37.0 14.0 -AT 2 2 19980914 1998091417 1998.70331 34.8630 -87.5290 178.0 30.0 37.0 14.0 -AT 2 1 19980914 1998091417 1998.70331 35.2969 -94.0361 198.0 24.0 24.0 22.0 -AT 2 1 19980917 1998091418 1998.70342 33.6669 -93.5914 110.0 27.0 40.0 20.0 -AT 2 1 19980914 1998091417 1998.70331 36.1867 -94.1286 379.0 24.0 32.0 20.0 -AT 2 1 19980915 1998091417 1998.70331 33.6140 -92.0778 43.0 25.0 -99.0 -99.0 -AT 2 2 19980914 1998091417 1998.70331 36.2012 -94.1738 1389.0 23.0 33.0 20.0 -AT 2 1 19980915 1998091420 1998.70365 32.3593 -111.0118 743.0 37.0 38.0 21.0 -AT 2 1 19980915 1998091418 1998.70342 32.2217 -110.9258 836.0 38.8 39.4 21.6 -AT 2 1 19980914 1998091419 1998.70354 32.2405 -110.8765 762.0 37.0 40.0 21.0 -AT 2 1 19980915 1998091418 1998.70342 33.4483 -112.0730 372.0 36.0 40.0 23.0 -AT 2 2 19980914 1998091418 1998.70342 31.5702 -110.2403 1312.0 33.0 -99.0 -99.0 -AT 2 1 19980918 1998091419 1998.70354 32.2217 -110.9258 836.0 35.0 36.0 21.0 -AT 2 2 19980921 1998091420 1998.70365 36.5963 -119.4493 99.0 35.0 39.0 16.0 -AT 2 1 19980915 1998091419 1998.70354 37.8244 -122.2306 70.0 15.0 26.0 13.5 -AT 2 2 19980918 1998091420 1998.70365 39.8007 -120.4660 1500.0 29.0 30.0 2.0 -AT 2 1 19980916 1998091420 1998.70365 36.7870 -119.7830 80.0 34.0 -99.0 -99.0 -AT 2 1 19980918 1998091419 1998.70354 33.7769 -118.0386 7.0 25.0 26.0 14.0 -AT 2 1 19980921 1998091420 1998.70365 37.2908 -120.3175 87.0 -99.0 39.2 18.3 -AT 2 2 19980914 1998091419 1998.70354 37.3583 -118.4007 1243.0 28.0 -99.0 -99.0 -AT 2 2 19980915 1998091418 1998.70342 40.0643 -105.1122 1546.0 20.0 -99.0 -99.0 -AT 2 1 19980916 1998091418 1998.70342 37.4083 -102.6139 1308.0 32.0 34.0 15.0 -AT 2 1 19980914 1998091417 1998.70331 39.7944 -105.2925 1958.0 18.0 25.0 6.0 -AT 2 2 19980914 1998091416 1998.70320 41.0533 -73.5388 24.0 24.0 24.0 19.0 -AT 2 1 19980918 1998091417 1998.70331 41.8097 -72.8311 31.0 20.0 -99.0 -99.0 -AT 2 2 19980914 1998091417 1998.70331 25.6753 -80.2850 20.0 32.0 -99.0 -99.0 -AT 2 1 19980914 1998091417 1998.70331 26.1425 -80.1395 0.0 36.0 40.0 35.0 -AT 2 3 19980915 1998091418 1998.70342 26.7072 -80.0382 2.0 31.0 31.0 24.0 -AT 2 1 19980914 1998091416 1998.70320 28.5381 -81.3794 23.0 31.0 33.0 25.0 -AT 2 1 19980914 1998091417 1998.70331 29.4641 -81.2446 6.0 30.0 30.0 22.0 -AT 2 2 19980919 1998091417 1998.70331 28.1013 -80.6243 12.0 29.0 31.0 24.0 -AT 2 2 19980918 1998091417 1998.70331 27.6270 -81.5242 36.0 30.0 31.0 21.0 -AT 2 1 19980921 1998091417 1998.70331 28.0183 -82.1131 31.0 32.0 32.0 20.0 -AT 2 1 19980914 1998091417 1998.70331 33.6675 -84.0178 224.0 29.0 32.0 17.0 -AT 2 1 19980914 1998091417 1998.70331 42.5172 -90.7222 268.0 21.0 35.0 15.0 -AT 2 1 19980916 1998091418 1998.70342 42.0678 -90.1741 178.0 21.0 40.0 15.0 -AT 2 1 19980915 1998091418 1998.70342 42.7013 -92.0744 310.0 21.0 35.0 15.0 -AT 2 1 19980921 1998091417 1998.70331 42.8008 -92.2618 288.0 20.0 -99.0 -99.0 -AT 2 1 19980914 1998091418 1998.70342 41.7181 -94.9322 399.0 21.0 33.0 12.0 -AT 2 1 19980914 1998091416 1998.70320 42.0347 -93.6197 277.0 20.0 31.0 19.0 -AT 2 1 19980917 1998091418 1998.70342 41.5568 -90.6042 188.0 21.0 -99.0 -99.0 -AT 2 1 19980914 1998091419 1998.70354 43.4777 -115.3098 1307.0 25.0 32.0 9.0 -AT 2 2 19980915 1998091420 1998.70365 46.7298 -116.9968 836.0 30.0 30.0 24.0 -AT 2 1 19980914 1998091419 1998.70354 43.6279 -111.7409 1856.0 26.0 27.0 9.0 -AT 2 2 19980914 1998091417 1998.70331 41.7600 -87.6765 229.0 25.0 36.0 23.0 -AT 2 2 19980914 1998091417 1998.70331 42.3333 -89.0333 252.0 20.0 31.0 13.0 -AT 2 1 19980914 1998091418 1998.70342 41.4392 -90.7175 223.0 22.0 33.0 21.0 -AT 2 4 19980914 1998091417 1998.70331 41.9363 -88.3625 223.0 20.0 20.0 10.0 -AT 2 1 19980914 1998091417 1998.70331 41.7676 -88.2930 203.0 23.0 35.0 14.0 -AT 2 1 19980914 1998091418 1998.70342 41.8089 -88.0111 203.0 24.0 33.0 22.0 -AT 2 1 19980916 1998091417 1998.70331 41.9142 -88.3086 215.0 22.0 34.0 20.0 -AT 2 1 19980916 1998091417 1998.70331 41.9119 -88.2908 215.0 20.0 33.0 19.0 -AT 2 1 19980915 1998091417 1998.70331 41.9013 -88.3190 215.0 14.0 32.0 -99.0 -AT 2 1 19980915 1998091418 1998.70342 41.3495 -88.5271 174.0 21.0 33.0 11.0 -AT 2 1 19980916 1998091417 1998.70331 39.7683 -86.1581 259.0 32.0 34.0 15.0 -AT 2 1 19980914 1998091417 1998.70331 39.5392 -86.3692 218.0 33.0 34.0 9.0 -AT 2 1 19980920 1998091416 1998.70320 41.1306 -85.1289 238.0 28.0 -99.0 -99.0 -AT 2 2 19980914 1998091418 1998.70342 39.0382 -95.3958 313.0 23.0 36.0 19.0 -AT 2 1 19980914 1998091417 1998.70331 37.3366 -87.5054 134.0 33.0 36.0 8.0 -AT 2 2 19980914 1998091417 1998.70331 36.9320 -84.0933 307.0 32.0 38.0 12.0 -AT 2 1 19980915 1998091417 1998.70331 37.5528 -87.9893 113.0 32.0 35.0 13.0 -AT 2 1 19980916 1998091417 1998.70331 37.5728 -82.7528 355.0 32.0 38.0 15.0 -AT 2 1 19980916 1998091417 1998.70331 36.8302 -84.8523 364.0 33.0 34.0 20.0 -AT 2 1 19980914 1998091416 1998.70320 38.2542 -85.7594 145.0 34.0 36.0 24.0 -AT 2 1 19980914 1998091416 1998.70320 41.7072 -70.7630 0.0 21.5 23.0 11.5 -AT 2 2 19980914 1998091415 1998.70308 42.3697 -71.7850 160.0 17.0 26.0 15.0 -AT 2 2 19980916 1998091416 1998.70320 38.6215 -76.8627 92.0 30.0 35.0 21.0 -AT 2 1 19980914 1998091416 1998.70320 44.3670 -69.7340 81.0 24.0 -99.0 -99.0 -AT 2 2 19980920 1998091416 1998.70320 44.8817 -69.4458 88.0 22.5 23.0 3.0 -AT 2 1 19980916 1998091417 1998.70331 45.7459 -85.5245 198.0 16.0 -99.0 -99.0 -AT 2 2 19980914 1998091416 1998.70320 42.6733 -83.3885 322.0 27.0 33.0 20.5 -AT 2 2 19980916 1998091417 1998.70331 42.6847 -84.4545 266.0 30.0 34.0 14.0 -AT 2 1 19980914 1998091417 1998.70331 41.9442 -84.8839 327.0 24.0 32.0 12.0 -AT 2 2 19980914 1998091416 1998.70320 43.9393 -82.9968 217.0 25.0 30.0 17.0 -AT 2 2 19980915 1998091416 1998.70320 42.3363 -85.3522 282.0 24.0 34.0 17.0 -AT 2 1 19980915 1998091416 1998.70320 42.4427 -85.6413 259.0 22.0 33.0 14.0 -AT 2 1 19980916 1998091418 1998.70342 45.5897 -94.1483 372.0 21.0 35.0 17.0 -AT 1 1 19980914 1998091418 1998.70342 47.5233 -92.5364 430.0 22.2 23.3 15.6 -AT 2 2 19980914 1998091418 1998.70342 45.2418 -93.4128 201.0 25.0 26.0 24.0 -AT 2 3 19980914 1998091417 1998.70331 40.4177 -91.7128 217.0 21.0 -99.0 -99.0 -AT 2 2 19980914 1998091417 1998.70331 30.4503 -88.8285 0.0 30.0 -99.0 -99.0 -AT 2 2 19980914 1998091417 1998.70331 30.8427 -89.1102 200.0 29.0 -99.0 -99.0 -AT 2 2 19980915 1998091419 1998.70354 45.4500 -112.1897 1559.0 22.0 26.0 9.0 -AT 2 1 19980918 1998091417 1998.70331 35.5978 -82.4000 832.0 33.0 33.0 -99.0 -AT 2 1 19980914 1998091417 1998.70331 35.7719 -78.6389 78.0 33.0 -99.0 -99.0 -AT 2 1 19980918 1998091416 1998.70320 34.6914 -76.8937 0.0 28.0 31.0 13.0 -AT 2 2 19980918 1998091417 1998.70331 36.2417 -80.2908 953.0 31.0 38.0 14.0 -AT 2 1 19980917 1998091417 1998.70331 35.3915 -83.1969 830.0 35.0 41.0 27.0 -AT 2 1 19980914 1998091417 1998.70331 48.1268 -98.8688 486.0 20.0 38.0 6.0 -AT 2 2 19980915 1998091416 1998.70320 43.1778 -71.8247 169.0 23.5 25.0 12.5 -AT 2 1 19980914 1998091416 1998.70320 42.8650 -71.4939 80.0 24.0 30.0 12.0 -AT 2 1 19980914 1998091416 1998.70320 43.2081 -71.5381 105.0 26.0 -99.0 -99.0 -AT 2 2 19980914 1998091417 1998.70331 43.0217 -74.3722 289.0 23.0 25.0 10.0 -AT 2 1 19980920 1998091416 1998.70320 43.2992 -73.6356 84.0 23.5 24.0 13.5 -AT 2 1 19980915 1998091416 1998.70320 43.1008 -74.7733 234.0 24.0 26.0 4.0 -AT 2 1 19980914 1998091415 1998.70308 42.8526 -78.8252 125.0 26.0 27.0 10.0 -AT 2 1 19980915 1998091416 1998.70320 41.4739 -81.5372 314.0 31.0 31.5 16.0 -AT 2 1 19980914 1998091416 1998.70320 38.9928 -83.4644 265.0 28.0 32.0 14.0 -AT 2 1 19980914 1998091416 1998.70320 40.7473 -81.0400 314.0 29.0 32.0 9.0 -AT 2 1 19980914 1998091416 1998.70320 39.9611 -82.9989 224.0 33.0 -99.0 -99.0 -AT 2 1 19980914 1998091418 1998.70342 34.6452 -97.9518 360.0 28.0 28.0 22.0 -AT 2 1 19980917 1998091418 1998.70342 36.0906 -94.9200 280.0 21.0 23.0 20.0 -AT 2 1 19980917 1998091418 1998.70342 35.5485 -97.4150 364.0 30.0 36.0 19.0 -AT 2 1 19980914 1998091418 1998.70342 45.1753 -121.0803 666.0 22.0 33.0 5.0 -AT 2 2 19980920 1998091417 1998.70331 41.3393 -80.3955 350.0 28.0 29.0 18.0 -AT 2 2 19980917 1998091417 1998.70331 40.7867 -77.0345 162.0 28.0 33.0 13.0 -AT 2 1 19980914 1998091415 1998.70308 40.5343 -80.1801 316.0 26.0 31.0 20.0 -AT 2 1 19980914 1998091418 1998.70342 40.4847 -78.0106 358.0 31.0 32.0 16.0 -AT 2 1 19980916 1998091415 1998.70308 39.9470 -75.9753 160.0 31.6 31.6 20.0 -AT 2 2 19980914 1998091416 1998.70320 39.9345 -77.2450 215.0 28.0 33.0 12.0 -AT 2 1 19980914 1998091416 1998.70320 41.4488 -75.6018 465.0 27.0 29.0 17.0 -AT 2 2 19980914 1998091417 1998.70331 40.0068 -75.1347 9.0 29.0 -99.0 -99.0 -AT 2 3 19980914 1998091417 1998.70331 40.0435 -75.0243 -11.0 28.0 28.0 20.0 -AT 2 2 19980915 1998091417 1998.70331 39.7487 -77.5712 204.0 28.0 33.0 18.0 -AT 2 1 19980919 1998091417 1998.70331 39.9606 -75.6058 111.0 31.0 32.0 21.0 -AT 2 2 19980921 1998091416 1998.70320 18.0340 -66.8733 57.0 33.0 34.0 27.0 -AT 2 1 19980915 1998091416 1998.70320 18.3994 -66.0503 234.0 33.0 34.0 15.0 -AT 2 1 19980914 1998091415 1998.70308 32.4258 -80.7292 6.0 30.0 32.0 15.0 -AT 2 1 19980914 1998091418 1998.70342 45.8817 -98.1550 390.0 25.0 25.0 16.0 -AT 2 1 19980914 1998091418 1998.70342 35.0531 -85.0503 266.0 33.0 -99.0 -99.0 -AT 2 1 19980917 1998091416 1998.70320 35.1635 -87.7185 216.0 31.0 45.0 5.0 -AT 2 1 19980914 1998091418 1998.70342 29.7631 -95.3631 7.0 -99.0 -99.0 -99.0 -AT 2 2 19980914 1998091418 1998.70342 32.8598 -96.8002 161.0 26.0 26.0 23.0 -AT 2 2 19980915 1998091418 1998.70342 29.5052 -98.6833 183.0 31.0 42.0 20.0 -AT 2 1 19980921 1998091418 1998.70342 29.8073 -95.5373 7.0 30.0 31.0 24.0 -AT 2 2 19980914 1998091417 1998.70331 29.7977 -95.5793 7.0 31.0 -99.0 -99.0 -AT 2 1 19980914 1998091418 1998.70342 29.7533 -95.7152 24.0 34.0 48.0 34.0 -AT 2 1 19980914 1998091417 1998.70331 32.8139 -96.9486 184.0 33.0 -99.0 -99.0 -AT 2 2 19980914 1998091419 1998.70354 31.1020 -97.7372 289.0 27.0 28.0 22.0 -AT 2 1 19980921 1998091419 1998.70354 41.8067 -111.3050 1802.0 23.0 25.0 6.0 -AT 2 1 19980917 1998091419 1998.70354 40.7608 -111.8903 1711.0 23.0 28.0 12.0 -AT 2 1 19980914 1998091416 1998.70320 37.1000 -79.9000 304.0 34.0 -99.0 -99.0 -AT 2 1 19980917 1998091417 1998.70331 37.5372 -79.3990 289.0 30.0 35.0 15.0 -AT 2 1 19980917 1998091416 1998.70320 38.0391 -78.4868 117.0 30.0 37.0 16.0 -AT 2 1 19980917 1998091416 1998.70320 44.4053 -72.9933 664.0 19.0 -99.0 -99.0 -AT 2 1 19980914 1998091419 1998.70354 48.1832 -122.1198 157.0 18.0 21.0 10.0 -AT 2 1 19980914 1998091419 1998.70354 47.6589 -117.4250 675.0 27.0 -99.0 -99.0 -AT 2 1 19980917 1998091419 1998.70354 48.5467 -117.9044 774.0 26.0 29.0 6.0 -AT 2 2 19980914 1998091420 1998.70365 48.5070 -122.6208 83.0 16.0 24.0 8.0 -AT 2 2 19980914 1998091417 1998.70331 43.3852 -87.9413 209.0 21.0 32.0 21.0 -AT 2 2 19980914 1998091416 1998.70320 46.7133 -92.0920 213.0 20.0 20.0 16.0 -AT 2 1 19980914 1998091416 1998.70320 43.3347 -90.3867 250.0 20.0 -99.0 -99.0 -AT 2 1 19980916 1998091418 1998.70342 44.8756 -91.9192 276.0 25.0 26.0 17.0 -AT 1 1 19980921 1998091315 1998.70034 -63.4000 -56.9833 10.0 -20.3 -12.8 -21.6 -AT 2 1 19980914 1998091301 1998.69874 -33.2417 150.5844 310.0 19.0 20.0 12.0 -AT 2 1 19980917 1998091301 1998.69874 -27.6000 153.1000 62.0 28.0 28.0 15.0 -AT 2 1 19980915 1998091302 1998.69886 -34.7833 138.7167 165.0 14.7 15.2 6.8 -AT 2 1 19980914 1998091311 1998.69989 50.6292 6.0261 290.0 9.2 12.8 5.3 -AT 2 1 19980913 1998091311 1998.69989 47.6535 9.1260 420.0 11.0 14.0 8.0 -AT 2 1 19980916 1998091312 1998.70000 47.5017 9.4242 400.0 15.0 17.0 8.0 -AT 2 1 19980914 1998091311 1998.69989 46.7403 7.6083 565.0 10.0 14.5 6.0 -AT 2 1 19980921 1998091304 1998.69909 37.5319 121.3792 30.0 30.5 31.0 23.0 -AT 1 1 19980916 1998091304 1998.69909 38.6667 114.6000 70.0 25.6 31.5 15.4 -AT 2 1 19980916 1998091311 1998.69989 48.9908 17.7203 250.0 10.0 21.0 9.5 -AT 1 1 19980916 1998091312 1998.70000 50.7823 15.0568 418.0 9.5 15.5 7.5 -AT 2 1 19980914 1998091311 1998.69989 49.5420 15.3537 518.0 12.0 14.0 8.0 -AT 2 3 19980918 1998091311 1998.69989 50.5412 8.5220 260.0 11.0 12.0 6.0 -AT 2 1 19980915 1998091311 1998.69989 51.0167 13.8333 112.0 14.0 20.0 5.0 -AT 1 3 19980913 1998091310 1998.69977 48.9413 8.3978 129.0 12.5 13.0 10.0 -AT 2 1 19980914 1998091311 1998.69989 50.7863 7.7175 190.0 10.0 11.0 6.0 -AT 2 1 19980915 1998091312 1998.70000 53.5833 11.4167 30.0 11.0 14.0 10.0 -AT 2 2 19980914 1998091311 1998.69989 50.6080 12.1675 314.0 15.8 17.9 10.3 -AT 2 1 19980914 1998091311 1998.69989 53.8728 8.7428 0.0 14.0 16.0 13.0 -AT 2 1 19980916 1998091312 1998.70000 53.6437 9.9630 15.0 14.0 15.3 9.3 -AT 2 1 19980921 1998091310 1998.69977 58.8258 22.7762 8.0 19.0 19.0 15.0 -AT 2 1 19980914 1998091311 1998.69989 59.4340 24.7493 60.0 22.6 22.6 13.0 -AT 2 1 19980914 1998091310 1998.69977 59.3922 27.7987 30.0 22.0 22.5 15.0 -AT 2 2 19980917 1998091311 1998.69989 58.7150 26.7513 80.0 20.0 24.0 10.0 -AT 2 1 19980917 1998091311 1998.69989 58.3767 26.7089 200.0 18.0 18.0 13.0 -AT 2 2 19980914 1998091310 1998.69977 60.8042 23.4932 105.0 21.0 21.0 13.0 -AT 2 1 19980914 1998091309 1998.69966 64.8781 28.9342 211.0 9.5 11.5 7.0 -AT 2 1 19980920 1998091310 1998.69977 59.8268 22.9755 0.0 18.0 18.0 15.0 -AT 2 1 19980918 1998091310 1998.69977 65.8767 28.9375 210.0 9.0 15.0 9.0 -AT 2 2 19980915 1998091309 1998.69966 60.4543 26.2247 30.0 16.0 18.0 13.0 -AT 2 2 19980913 1998091309 1998.69966 64.7622 26.4150 80.0 13.0 15.2 7.3 -AT 2 2 19980914 1998091309 1998.69966 60.9902 25.5207 155.0 17.0 18.5 7.0 -AT 2 1 19980915 1998091310 1998.69977 37.9915 23.6752 40.0 28.0 33.0 24.0 -AT 2 1 19980921 1998091310 1998.69977 37.0677 22.4247 207.0 27.8 33.7 18.3 -AT 2 1 19980913 1998091308 1998.69954 37.9365 23.6960 12.0 28.0 32.0 22.5 -AT 2 1 19980918 1998091311 1998.69989 46.0023 16.1195 162.0 15.0 23.0 11.0 -AT 2 1 19980917 1998091310 1998.69977 45.5139 17.1278 170.0 12.0 16.0 10.0 -AT 2 2 19980914 1998091311 1998.69989 46.0532 16.1832 172.0 12.0 22.0 10.0 -AT 2 1 19980914 1998091312 1998.70000 45.3278 14.4458 20.0 20.0 20.0 14.0 -AT 2 1 19980915 1998091310 1998.69977 43.7333 15.9056 70.0 18.0 25.0 16.0 -AT 2 1 19980914 1998091311 1998.69989 45.8295 17.3845 124.0 14.0 23.0 11.0 -AT 2 2 19980913 1998091312 1998.70000 63.9982 -22.5603 15.0 6.0 7.0 5.0 -AT 2 1 19980921 1998091311 1998.69989 32.0212 35.7178 894.0 29.0 31.0 19.0 -AT 2 2 19980914 1998091304 1998.69909 35.3500 136.9000 49.0 31.0 31.0 24.0 -AT 2 1 19980917 1998091302 1998.69886 39.8283 140.0571 64.0 26.5 28.0 20.0 -AT 2 2 19980914 1998091304 1998.69909 38.6527 141.2933 60.0 30.0 30.0 19.0 -AT 2 2 19980914 1998091304 1998.69909 36.5333 136.6667 60.0 30.0 30.0 19.2 -AT 2 1 19980914 1998091304 1998.69909 34.7033 135.8400 100.0 31.6 33.0 20.0 -AT 2 1 19980916 1998091303 1998.69897 35.1825 136.8028 2.0 29.0 32.0 22.0 -AT 2 1 19980921 1998091302 1998.69886 35.4100 139.4000 10.0 29.0 34.0 21.5 -AT 2 1 19980921 1998091304 1998.69909 33.1917 131.6250 50.0 31.0 32.4 21.5 -AT 2 1 19980917 1998091301 1998.69874 7.1000 171.2200 3.0 30.0 31.0 29.0 -AT 2 1 19980914 1998091311 1998.69989 -17.5000 24.2667 1073.0 33.0 34.0 15.0 -AT 2 1 19980914 1998091311 1998.69989 52.0852 4.3103 0.0 9.0 15.0 8.0 -AT 2 3 19980914 1998091312 1998.70000 68.1458 13.6250 20.0 15.5 16.0 10.0 -AT 2 1 19980914 1998091312 1998.70000 32.8167 -16.9833 30.0 25.0 27.0 20.0 -AT 2 1 19980913 1998091309 1998.69966 56.2723 14.5257 56.0 15.0 18.0 14.0 -AT 2 3 19980913 1998091311 1998.69989 56.0413 13.6785 100.0 15.8 17.1 13.2 -AT 2 2 19980913 1998091321 1998.70103 57.6138 -152.2355 14.0 11.5 13.5 4.5 -AT 2 2 19980914 1998091322 1998.70114 57.7883 -152.4030 35.0 12.0 14.0 7.0 -AT 2 1 19980914 1998091322 1998.70114 62.6067 -159.5184 135.0 6.0 14.0 4.0 -AT 2 1 19980915 1998091316 1998.70046 31.2445 -85.4483 71.0 29.0 29.0 17.0 -AT 2 1 19980914 1998091318 1998.70068 35.2969 -94.0361 198.0 23.0 23.5 21.0 -AT 2 1 19980914 1998091318 1998.70068 32.2217 -110.9258 836.0 38.8 39.4 21.6 -AT 2 1 19980918 1998091319 1998.70080 32.2217 -110.9258 836.0 34.0 37.0 22.0 -AT 2 1 19980918 1998091319 1998.70080 33.7769 -118.0386 7.0 23.0 26.0 14.0 -AT 2 1 19980921 1998091320 1998.70091 37.2908 -120.3175 87.0 -99.0 38.3 17.8 -AT 2 2 19980914 1998091315 1998.70034 41.0533 -73.5388 24.0 28.0 35.0 21.0 -AT 2 1 19980918 1998091318 1998.70068 28.1984 -81.4870 13.0 31.0 32.0 26.0 -AT 2 3 19980915 1998091318 1998.70068 26.7072 -80.0382 2.0 30.0 31.0 25.0 -AT 2 1 19980913 1998091317 1998.70057 29.4641 -81.2446 6.0 29.0 30.0 19.0 -AT 2 2 19980916 1998091317 1998.70057 30.9900 -83.3818 60.0 33.5 33.5 15.5 -AT 2 1 19980914 1998091316 1998.70046 33.6675 -84.0178 224.0 28.0 30.0 17.0 -AT 2 1 19980914 1998091318 1998.70068 42.0347 -93.6197 277.0 30.0 34.0 16.0 -AT 2 2 19980914 1998091317 1998.70057 41.7600 -87.6765 229.0 33.0 35.0 18.0 -AT 2 2 19980914 1998091317 1998.70057 42.3333 -89.0333 252.0 30.0 32.0 14.0 -AT 2 4 19980914 1998091317 1998.70057 41.9363 -88.3625 223.0 29.0 33.0 17.0 -AT 2 1 19980914 1998091317 1998.70057 41.9119 -88.2908 215.0 28.0 29.0 15.0 -AT 2 1 19980916 1998091317 1998.70057 40.6167 -87.3208 217.0 33.2 35.5 19.7 -AT 2 1 19980913 1998091316 1998.70046 41.7072 -70.7630 0.0 19.0 26.5 17.0 -AT 2 2 19980914 1998091315 1998.70034 42.3697 -71.7850 160.0 20.0 31.0 15.0 -AT 2 2 19980916 1998091316 1998.70046 38.6215 -76.8627 92.0 35.0 36.0 16.0 -AT 2 2 19980914 1998091316 1998.70046 44.3853 -68.2080 22.0 21.0 21.0 11.0 -AT 2 2 19980913 1998091316 1998.70046 44.8817 -69.4458 88.0 18.5 18.5 10.0 -AT 2 2 19980915 1998091316 1998.70046 42.6733 -83.3885 322.0 27.0 33.0 20.5 -AT 2 2 19980914 1998091317 1998.70057 42.3363 -85.3522 282.0 31.0 33.0 11.0 -AT 2 1 19980916 1998091318 1998.70068 45.5897 -94.1483 372.0 23.0 33.0 13.0 -AT 2 2 19980918 1998091317 1998.70057 36.2417 -80.2908 953.0 30.0 35.0 11.0 -AT 2 1 19980914 1998091317 1998.70057 35.3915 -83.1969 830.0 34.0 40.0 26.5 -AT 2 2 19980914 1998091317 1998.70057 43.1778 -71.8247 169.0 22.0 27.0 11.0 -AT 2 1 19980920 1998091316 1998.70046 43.2992 -73.6356 84.0 19.5 23.5 8.5 -AT 2 1 19980913 1998091318 1998.70068 36.0906 -94.9200 280.0 23.0 29.0 21.0 -AT 2 2 19980920 1998091317 1998.70057 41.3393 -80.3955 350.0 28.0 28.0 12.0 -AT 2 1 19980913 1998091316 1998.70046 40.5343 -80.1801 316.0 26.0 29.0 19.0 -AT 2 1 19980914 1998091317 1998.70057 40.4847 -78.0106 358.0 28.0 33.0 15.0 -AT 2 1 19980914 1998091316 1998.70046 41.4488 -75.6018 465.0 27.0 30.0 15.0 -AT 2 2 19980914 1998091317 1998.70057 39.7487 -77.5712 204.0 28.0 33.0 18.0 -AT 2 1 19980913 1998091317 1998.70057 39.9606 -75.6058 111.0 29.0 31.0 19.0 -AT 2 2 19980921 1998091316 1998.70046 18.0340 -66.8733 57.0 33.0 34.0 25.0 -AT 2 1 19980914 1998091318 1998.70068 45.8817 -98.1550 390.0 22.0 27.0 19.0 -AT 2 1 19980914 1998091318 1998.70068 29.7533 -95.7152 24.0 30.0 30.0 22.0 -AT 2 2 19980914 1998091319 1998.70080 31.1020 -97.7372 289.0 25.0 25.0 21.0 -AT 2 1 19980917 1998091319 1998.70080 41.8067 -111.3050 1802.0 17.0 19.0 8.0 -AT 2 1 19980913 1998091319 1998.70080 40.7608 -111.8903 1711.0 20.0 23.0 11.0 -AT 2 1 19980917 1998091317 1998.70057 38.0391 -78.4868 117.0 35.0 36.0 13.0 -AT 2 1 19980913 1998091319 1998.70080 48.6969 -122.9042 140.0 18.0 23.0 13.0 -AT 2 1 19980914 1998091319 1998.70080 48.1832 -122.1198 157.0 19.0 21.0 11.0 -AT 2 1 19980916 1998091319 1998.70080 48.5467 -117.9044 774.0 25.0 29.0 6.5 -AT 2 2 19980914 1998091318 1998.70068 46.7133 -92.0920 213.0 17.0 20.0 15.0 -AT 2 1 19980916 1998091318 1998.70068 44.8756 -91.9192 276.0 24.0 35.0 21.0 -AT 1 1 19980921 1998091215 1998.69760 -63.4000 -56.9833 10.0 -12.0 -7.4 -21.5 -AT 2 1 19980914 1998091201 1998.69600 -33.2417 150.5844 310.0 19.0 20.0 14.0 -AT 2 1 19980917 1998091201 1998.69600 -27.6000 153.1000 62.0 26.0 26.0 13.0 -AT 2 1 19980915 1998091202 1998.69612 -34.7833 138.7167 165.0 15.6 15.8 8.3 -AT 2 1 19980914 1998091211 1998.69715 50.6292 6.0261 290.0 10.0 19.1 9.2 -AT 2 1 19980912 1998091211 1998.69715 47.6535 9.1260 420.0 12.0 15.0 11.0 -AT 2 1 19980916 1998091212 1998.69726 47.5017 9.4242 400.0 11.0 16.0 10.0 -AT 2 1 19980914 1998091211 1998.69715 46.7403 7.6083 565.0 12.5 16.5 10.0 -AT 2 1 19980921 1998091204 1998.69635 37.5319 121.3792 30.0 27.0 30.5 23.5 -AT 1 1 19980916 1998091204 1998.69635 38.6667 114.6000 70.0 26.8 33.4 17.7 -AT 2 1 19980916 1998091211 1998.69715 48.9908 17.7203 250.0 19.5 20.0 19.0 -AT 1 1 19980916 1998091212 1998.69726 50.7823 15.0568 418.0 15.0 16.0 12.5 -AT 2 1 19980914 1998091211 1998.69715 49.5420 15.3537 518.0 14.0 19.0 12.0 -AT 2 3 19980918 1998091211 1998.69715 50.5412 8.5220 260.0 13.0 14.0 11.0 -AT 2 1 19980915 1998091211 1998.69715 51.0167 13.8333 112.0 14.0 14.0 10.0 -AT 1 3 19980912 1998091210 1998.69703 48.9413 8.3978 129.0 13.0 28.0 13.0 -AT 2 1 19980912 1998091211 1998.69715 50.7863 7.7175 190.0 11.0 19.0 11.0 -AT 2 1 19980915 1998091212 1998.69726 53.5833 11.4167 30.0 16.0 20.0 14.0 -AT 2 2 19980914 1998091209 1998.69692 50.6080 12.1675 314.0 15.9 19.9 13.4 -AT 2 1 19980912 1998091211 1998.69715 53.5853 9.9472 23.0 14.0 19.0 13.0 -AT 2 1 19980914 1998091211 1998.69715 53.8728 8.7428 0.0 14.0 17.0 13.0 -AT 2 1 19980916 1998091212 1998.69726 53.6437 9.9630 15.0 17.5 19.4 8.2 -AT 2 1 19980921 1998091210 1998.69703 58.8258 22.7762 8.0 17.0 20.0 15.0 -AT 2 1 19980912 1998091210 1998.69703 59.4340 24.7493 60.0 16.8 21.1 13.0 -AT 2 1 19980914 1998091210 1998.69703 59.3922 27.7987 30.0 16.0 17.0 5.0 -AT 2 2 19980917 1998091211 1998.69715 58.7150 26.7513 80.0 16.0 17.0 14.0 -AT 2 1 19980917 1998091211 1998.69715 58.3767 26.7089 200.0 18.0 18.0 16.0 -AT 2 1 19980912 1998091210 1998.69703 63.2377 29.2537 110.0 16.7 18.0 13.3 -AT 2 2 19980914 1998091210 1998.69703 60.8042 23.4932 105.0 17.7 19.1 13.2 -AT 2 1 19980914 1998091209 1998.69692 64.8781 28.9342 211.0 14.5 15.0 10.0 -AT 2 1 19980920 1998091210 1998.69703 59.8268 22.9755 0.0 16.0 20.0 14.0 -AT 2 1 19980916 1998091211 1998.69715 61.7403 27.3347 97.0 12.0 21.0 10.0 -AT 2 1 19980918 1998091210 1998.69703 65.8767 28.9375 210.0 15.0 15.0 14.0 -AT 2 2 19980915 1998091210 1998.69703 60.4543 26.2247 30.0 17.0 19.0 14.0 -AT 2 2 19980914 1998091209 1998.69692 60.9902 25.5207 155.0 17.0 19.0 7.0 -AT 2 2 19980914 1998091210 1998.69703 62.3018 27.1365 122.0 20.0 20.0 15.0 -AT 2 1 19980916 1998091211 1998.69715 37.9522 23.6133 35.0 30.0 31.0 23.0 -AT 2 1 19980915 1998091210 1998.69703 37.9915 23.6752 40.0 33.0 33.0 22.0 -AT 2 1 19980921 1998091210 1998.69703 37.0677 22.4247 207.0 33.1 33.1 18.7 -AT 2 1 19980913 1998091208 1998.69680 37.9365 23.6960 12.0 29.0 32.0 22.5 -AT 2 1 19980918 1998091211 1998.69715 46.0023 16.1195 162.0 21.0 26.0 18.0 -AT 2 1 19980912 1998091210 1998.69703 45.4933 15.5622 118.0 23.0 27.0 17.0 -AT 2 2 19980912 1998091210 1998.69703 45.4933 15.5622 119.0 23.0 27.0 17.0 -AT 2 1 19980917 1998091210 1998.69703 45.5139 17.1278 170.0 12.0 15.0 11.0 -AT 2 2 19980914 1998091211 1998.69715 46.0532 16.1832 172.0 21.0 24.0 18.0 -AT 2 1 19980914 1998091212 1998.69726 45.3278 14.4458 20.0 13.0 20.0 10.0 -AT 2 1 19980915 1998091210 1998.69703 43.7333 15.9056 70.0 24.0 29.0 21.0 -AT 2 1 19980914 1998091211 1998.69715 45.8295 17.3845 124.0 23.0 26.0 13.0 -AT 2 2 19980912 1998091213 1998.69737 63.9982 -22.5603 15.0 6.0 7.0 4.0 -AT 2 1 19980921 1998091211 1998.69715 32.0212 35.7178 894.0 33.0 34.0 20.0 -AT 2 2 19980914 1998091204 1998.69635 35.3500 136.9000 49.0 31.0 32.0 22.5 -AT 2 1 19980917 1998091202 1998.69612 39.8283 140.0571 64.0 28.5 28.5 19.5 -AT 2 2 19980914 1998091202 1998.69612 38.6527 141.2933 60.0 25.0 28.0 17.0 -AT 2 2 19980914 1998091204 1998.69635 36.5333 136.6667 60.0 28.5 30.0 20.9 -AT 2 1 19980914 1998091204 1998.69635 34.7033 135.8400 100.0 31.7 32.9 22.1 -AT 2 1 19980916 1998091203 1998.69623 35.1825 136.8028 2.0 29.0 33.0 22.0 -AT 2 1 19980921 1998091204 1998.69635 33.1917 131.6250 50.0 31.5 32.2 22.0 -AT 2 3 19980918 1998091203 1998.69623 35.1528 129.0303 80.0 31.0 32.5 20.8 -AT 2 1 19980914 1998091203 1998.69623 37.3300 126.5800 95.0 33.0 33.0 22.0 -AT 2 1 19980914 1998091211 1998.69715 52.0852 4.3103 0.0 15.0 17.0 11.0 -AT 2 3 19980914 1998091212 1998.69726 68.1458 13.6250 20.0 12.0 16.5 10.5 -AT 2 1 19980914 1998091212 1998.69726 32.8167 -16.9833 30.0 26.0 27.0 20.0 -AT 2 1 19980913 1998091212 1998.69726 56.2723 14.5257 56.0 17.0 19.0 11.0 -AT 2 1 19980914 1998091211 1998.69715 57.9275 12.0843 15.0 17.0 17.5 12.0 -AT 2 3 19980912 1998091211 1998.69715 56.0413 13.6785 100.0 17.1 19.0 10.8 -AT 2 2 19980912 1998091221 1998.69829 57.6138 -152.2355 14.0 12.0 13.0 5.0 -AT 2 2 19980914 1998091222 1998.69840 57.7883 -152.4030 35.0 11.0 13.0 8.0 -AT 2 1 19980914 1998091222 1998.69840 62.6067 -159.5184 135.0 10.0 14.0 3.0 -AT 2 1 19980914 1998091218 1998.69795 35.2969 -94.0361 198.0 23.0 32.5 22.0 -AT 2 1 19980914 1998091218 1998.69795 32.2217 -110.9258 836.0 35.5 39.4 22.7 -AT 2 1 19980918 1998091219 1998.69806 32.2217 -110.9258 836.0 36.0 36.0 21.0 -AT 2 1 19980918 1998091219 1998.69806 33.7769 -118.0386 7.0 25.0 26.0 15.0 -AT 2 1 19980921 1998091220 1998.69817 37.2908 -120.3175 87.0 -99.0 35.3 15.4 -AT 2 2 19980914 1998091215 1998.69760 41.0533 -73.5388 24.0 25.0 25.0 10.0 -AT 2 3 19980913 1998091218 1998.69795 26.7072 -80.0382 2.0 30.0 30.0 26.0 -AT 2 1 19980913 1998091217 1998.69783 29.4641 -81.2446 6.0 26.0 27.0 23.0 -AT 2 2 19980916 1998091217 1998.69783 30.9900 -83.3818 60.0 28.5 34.0 18.0 -AT 2 1 19980914 1998091217 1998.69783 33.6675 -84.0178 224.0 26.0 28.0 17.0 -AT 2 1 19980914 1998091216 1998.69772 42.0347 -93.6197 277.0 31.0 45.0 10.0 -AT 2 2 19980914 1998091217 1998.69783 41.7600 -87.6765 229.0 32.0 32.0 18.0 -AT 2 4 19980914 1998091217 1998.69783 41.9363 -88.3625 223.0 20.0 20.0 10.0 -AT 2 1 19980916 1998091217 1998.69783 40.6167 -87.3208 217.0 30.5 34.4 17.2 -AT 2 1 19980912 1998091216 1998.69772 41.7072 -70.7630 0.0 26.0 27.5 13.5 -AT 2 2 19980912 1998091216 1998.69772 42.3697 -71.7850 160.0 29.0 29.0 13.0 -AT 2 2 19980916 1998091217 1998.69783 38.6215 -76.8627 92.0 34.0 34.0 11.0 -AT 2 2 19980912 1998091216 1998.69772 44.3853 -68.2080 22.0 17.0 21.0 10.0 -AT 2 2 19980913 1998091216 1998.69772 44.8817 -69.4458 88.0 14.5 22.5 4.5 -AT 2 2 19980915 1998091216 1998.69772 42.6733 -83.3885 322.0 26.0 28.0 17.0 -AT 2 2 19980914 1998091217 1998.69783 42.3363 -85.3522 282.0 29.0 29.0 10.0 -AT 2 1 19980916 1998091218 1998.69795 45.5897 -94.1483 372.0 24.0 36.0 17.0 -AT 2 2 19980918 1998091217 1998.69783 36.2417 -80.2908 953.0 28.0 31.0 9.0 -AT 2 2 19980912 1998091216 1998.69772 43.1778 -71.8247 169.0 27.5 28.0 11.5 -AT 2 1 19980920 1998091217 1998.69783 43.2992 -73.6356 84.0 22.0 26.0 14.5 -AT 2 1 19980913 1998091218 1998.69795 36.0906 -94.9200 280.0 26.0 32.0 19.0 -AT 2 2 19980920 1998091217 1998.69783 41.3393 -80.3955 350.0 26.0 26.0 13.0 -AT 2 1 19980912 1998091218 1998.69795 40.5343 -80.1801 316.0 29.0 29.0 17.0 -AT 2 1 19980912 1998091217 1998.69783 40.4847 -78.0106 358.0 29.0 30.0 12.0 -AT 2 1 19980913 1998091216 1998.69772 41.4488 -75.6018 465.0 27.0 28.0 12.0 -AT 2 2 19980913 1998091217 1998.69783 39.7487 -77.5712 204.0 26.0 28.0 15.0 -AT 2 1 19980912 1998091217 1998.69783 39.9606 -75.6058 111.0 30.0 30.0 16.0 -AT 2 2 19980921 1998091216 1998.69772 18.0340 -66.8733 57.0 33.0 35.0 27.0 -AT 2 1 19980914 1998091218 1998.69795 45.8817 -98.1550 390.0 28.0 31.0 17.0 -AT 2 2 19980914 1998091217 1998.69783 29.7977 -95.5793 7.0 26.5 -99.0 -99.0 -AT 2 1 19980914 1998091218 1998.69795 29.7533 -95.7152 24.0 26.0 30.0 24.0 -AT 2 2 19980914 1998091219 1998.69806 31.1020 -97.7372 289.0 22.0 22.0 21.0 -AT 2 1 19980916 1998091219 1998.69806 41.8067 -111.3050 1802.0 16.0 16.0 8.0 -AT 2 1 19980912 1998091219 1998.69806 40.7608 -111.8903 1711.0 20.0 21.0 12.0 -AT 2 2 19980915 1998091215 1998.69760 18.3247 -64.9093 0.0 30.0 32.0 27.0 -AT 2 1 19980912 1998091219 1998.69806 48.6969 -122.9042 140.0 18.0 24.0 13.0 -AT 2 1 19980914 1998091219 1998.69806 48.1832 -122.1198 157.0 18.0 23.0 10.0 -AT 2 1 19980912 1998091218 1998.69795 47.6589 -117.4250 675.0 22.0 27.0 8.0 -AT 2 1 19980916 1998091219 1998.69806 48.5467 -117.9044 774.0 -99.0 27.0 4.0 -AT 2 2 19980914 1998091218 1998.69795 46.7133 -92.0920 213.0 23.0 35.0 18.0 -AT 1 1 19980921 1998091115 1998.69486 -63.4000 -56.9833 10.0 -16.0 -12.4 -21.0 -AT 2 1 19980914 1998091116 1998.69498 -34.5671 -58.4482 0.0 0.0 0.0 0.0 -AT 2 1 19980911 1998091102 1998.69338 -33.6427 150.0425 1220.0 12.0 12.0 6.0 -AT 2 1 19980911 1998091104 1998.69361 -31.9500 115.8500 18.0 22.0 26.0 4.0 -AT 2 1 19980914 1998091101 1998.69326 -28.3333 152.3000 587.0 19.0 26.0 5.0 -AT 2 1 19980911 1998091101 1998.69326 -33.8333 152.0000 0.0 18.0 21.0 15.0 -AT 2 2 19980911 1998091103 1998.69349 -23.4200 133.5200 580.0 32.0 32.0 6.0 -AT 2 2 19980911 1998091103 1998.69349 -27.2170 153.0546 2.0 21.0 21.5 14.0 -AT 2 1 19980911 1998091103 1998.69349 -16.9167 145.7667 12.0 30.0 30.0 20.0 -AT 2 1 19980915 1998091103 1998.69349 -34.7833 138.7167 165.0 22.7 22.8 11.9 -AT 2 1 19980911 1998091103 1998.69349 -37.8167 144.9667 12.0 22.0 22.0 10.0 -AT 2 1 19980914 1998091104 1998.69361 -32.3333 115.9500 20.0 17.0 18.0 8.0 -AT 2 1 19980911 1998091111 1998.69441 50.8103 4.9368 55.0 18.8 22.4 13.4 -AT 2 1 19980914 1998091111 1998.69441 50.6292 6.0261 290.0 16.9 21.0 12.4 -AT 2 1 19980911 1998091111 1998.69441 47.6535 9.1260 420.0 15.0 24.0 14.0 -AT 2 1 19980915 1998091111 1998.69441 47.5678 7.6362 260.0 16.0 22.0 11.0 -AT 2 1 19980916 1998091112 1998.69452 47.5017 9.4242 400.0 15.0 25.0 13.0 -AT 2 1 19980911 1998091111 1998.69441 46.7403 7.6083 565.0 14.5 27.0 13.0 -AT 2 1 19980921 1998091104 1998.69361 37.5319 121.3792 30.0 29.8 33.8 23.0 -AT 1 1 19980916 1998091104 1998.69361 38.6667 114.6000 70.0 26.6 33.3 19.6 -AT 2 1 19980916 1998091111 1998.69441 48.9908 17.7203 250.0 22.0 22.0 19.0 -AT 1 1 19980916 1998091112 1998.69452 50.7823 15.0568 418.0 16.0 23.0 5.0 -AT 2 1 19980911 1998091111 1998.69441 49.5420 15.3537 518.0 19.0 20.0 14.0 -AT 2 3 19980918 1998091111 1998.69441 50.5412 8.5220 260.0 19.0 23.0 13.0 -AT 2 1 19980915 1998091111 1998.69441 51.0167 13.8333 112.0 19.0 26.0 4.0 -AT 1 3 19980911 1998091110 1998.69429 48.9413 8.3978 129.0 17.0 28.0 14.0 -AT 2 1 19980912 1998091111 1998.69441 50.7863 7.7175 190.0 15.0 21.0 14.0 -AT 2 1 19980911 1998091112 1998.69452 53.5833 11.4167 30.0 16.0 20.0 15.0 -AT 2 1 19980911 1998091109 1998.69418 51.6333 12.2667 55.0 20.0 20.0 18.0 -AT 2 1 19980911 1998091110 1998.69429 52.4252 12.5523 50.0 21.4 24.5 16.3 -AT 2 1 19980921 1998091110 1998.69429 51.5000 7.0000 28.0 21.0 22.0 16.0 -AT 2 1 19980911 1998091110 1998.69429 51.5550 6.9450 38.0 20.0 23.0 13.0 -AT 2 1 19980916 1998091110 1998.69429 53.6632 13.5572 35.0 17.0 22.0 12.0 -AT 2 1 19980916 1998091112 1998.69452 52.3333 10.5333 73.0 18.5 21.0 15.0 -AT 2 2 19980911 1998091111 1998.69441 50.6080 12.1675 314.0 18.8 25.9 16.5 -AT 2 1 19980911 1998091111 1998.69441 53.5853 9.9472 23.0 17.0 20.0 15.0 -AT 2 1 19980914 1998091111 1998.69441 53.8728 8.7428 0.0 14.0 18.0 13.0 -AT 2 1 19980914 1998091110 1998.69429 52.0833 15.0833 180.0 18.5 24.0 17.0 -AT 2 1 19980918 1998091110 1998.69429 51.3187 13.2825 97.0 22.0 29.0 13.0 -AT 2 1 19980916 1998091112 1998.69452 53.6437 9.9630 15.0 17.5 20.0 14.2 -AT 2 1 19980914 1998091111 1998.69441 59.4425 24.7057 30.0 19.0 20.0 15.0 -AT 2 1 19980921 1998091110 1998.69429 58.8258 22.7762 8.0 19.0 19.0 14.0 -AT 2 1 19980912 1998091111 1998.69441 59.4340 24.7493 60.0 21.1 21.1 15.0 -AT 1 1 19980911 1998091110 1998.69429 59.3922 27.7987 30.0 17.5 17.5 13.0 -AT 2 2 19980917 1998091111 1998.69441 58.7150 26.7513 80.0 16.0 17.0 15.0 -AT 2 1 19980917 1998091111 1998.69441 58.3767 26.7089 200.0 18.0 18.0 15.0 -AT 2 1 19980911 1998091109 1998.69418 60.4714 25.1058 53.0 19.0 20.0 8.0 -AT 2 1 19980911 1998091111 1998.69441 60.6297 24.8403 125.0 15.0 15.0 12.0 -AT 2 1 19980916 1998091110 1998.69429 63.2377 29.2537 110.0 17.0 18.3 13.0 -AT 2 1 19980911 1998091109 1998.69418 62.8036 30.1181 109.0 15.0 18.0 13.0 -AT 2 2 19980914 1998091110 1998.69429 60.8042 23.4932 105.0 19.1 19.1 15.0 -AT 2 1 19980911 1998091109 1998.69418 64.8781 28.9342 211.0 14.0 14.5 13.0 -AT 2 1 19980920 1998091110 1998.69429 59.8268 22.9755 0.0 18.0 19.0 15.0 -AT 2 1 19980916 1998091111 1998.69441 61.7403 27.3347 97.0 16.0 21.0 7.0 -AT 2 1 19980915 1998091110 1998.69429 64.9028 25.4694 15.0 15.0 16.0 12.0 -AT 2 1 19980918 1998091109 1998.69418 65.8767 28.9375 210.0 14.0 14.0 13.0 -AT 2 2 19980911 1998091110 1998.69429 60.4543 26.2247 30.0 16.0 16.0 10.0 -AT 2 1 19980915 1998091109 1998.69418 60.9857 24.4333 142.0 15.0 15.0 14.0 -AT 2 2 19980911 1998091109 1998.69418 64.7622 26.4150 80.0 15.2 15.3 14.1 -AT 2 2 19980914 1998091108 1998.69406 60.9902 25.5207 155.0 16.0 21.0 13.0 -AT 2 1 19980912 1998091110 1998.69429 60.2662 24.8543 32.0 18.0 18.0 -99.0 -AT 2 1 19980911 1998091108 1998.69406 62.2658 26.2078 93.0 19.0 19.0 14.0 -AT 2 2 19980911 1998091110 1998.69429 62.3018 27.1365 122.0 17.0 18.0 15.0 -AT 2 2 19980916 1998091110 1998.69429 62.2888 25.7350 100.0 16.0 17.0 14.0 -AT 2 1 19980911 1998091110 1998.69429 60.8042 23.4944 110.0 17.0 17.0 14.0 -AT 2 1 19980916 1998091111 1998.69441 37.9522 23.6133 35.0 30.0 32.0 25.0 -AT 2 1 19980915 1998091110 1998.69429 37.9915 23.6752 40.0 30.0 31.0 24.5 -AT 2 1 19980911 1998091110 1998.69429 37.0677 22.4247 207.0 33.0 33.0 21.7 -AT 2 1 19980913 1998091108 1998.69406 37.9365 23.6960 12.0 27.5 29.0 22.5 -AT 2 1 19980917 1998091112 1998.69452 45.3388 14.3083 10.0 25.0 29.0 17.0 -AT 2 2 19980912 1998091110 1998.69429 45.4933 15.5622 119.0 18.0 23.0 13.0 -AT 2 1 19980917 1998091110 1998.69429 45.5139 17.1278 170.0 26.0 26.0 11.0 -AT 2 2 19980914 1998091111 1998.69441 46.0532 16.1832 172.0 19.0 22.0 11.0 -AT 2 1 19980911 1998091112 1998.69452 45.3278 14.4458 20.0 28.0 30.0 18.0 -AT 2 1 19980915 1998091110 1998.69429 43.7333 15.9056 70.0 29.0 29.0 18.0 -AT 2 1 19980914 1998091111 1998.69441 45.8295 17.3845 124.0 21.0 23.0 13.0 -AT 2 2 19980915 1998091112 1998.69452 63.9982 -22.5603 15.0 6.0 8.0 4.0 -AT 2 1 19980921 1998091111 1998.69441 32.0212 35.7178 894.0 34.0 36.0 20.0 -AT 2 2 19980919 1998091104 1998.69361 32.7833 129.8667 20.0 29.9 33.1 19.8 -AT 2 2 19980914 1998091104 1998.69361 35.3500 136.9000 49.0 30.5 33.5 21.5 -AT 2 1 19980917 1998091102 1998.69338 39.8283 140.0571 64.0 28.0 29.0 18.0 -AT 2 2 19980914 1998091103 1998.69349 34.1352 131.4557 17.0 29.0 31.0 24.0 -AT 2 2 19980914 1998091104 1998.69361 36.5333 136.6667 60.0 30.0 30.0 17.9 -AT 2 1 19980914 1998091104 1998.69361 34.7033 135.8400 100.0 31.3 32.8 20.0 -AT 2 1 19980914 1998091102 1998.69338 35.4100 139.4000 10.0 27.0 31.0 21.2 -AT 2 1 19980921 1998091104 1998.69361 33.1917 131.6250 50.0 31.6 31.8 21.2 -AT 2 1 19980914 1998091104 1998.69361 34.5006 133.5764 16.0 34.0 35.0 22.0 -AT 2 1 19980914 1998091103 1998.69349 35.3408 132.9011 35.0 28.7 30.4 17.8 -AT 2 1 19980911 1998091105 1998.69372 36.3756 127.3564 40.0 30.5 32.6 18.7 -AT 2 3 19980911 1998091104 1998.69361 35.1528 129.0303 80.0 32.0 33.5 22.1 -AT 2 1 19980917 1998091101 1998.69326 7.1000 171.2200 3.0 32.0 38.0 30.2 -AT 2 1 19980914 1998091111 1998.69441 -17.5000 24.2667 1073.0 33.0 34.0 14.0 -AT 2 1 19980914 1998091111 1998.69441 51.6667 5.6167 16.0 13.0 14.0 10.0 -AT 2 1 19980911 1998091112 1998.69452 51.2508 5.9389 30.0 18.0 24.0 11.0 -AT 2 1 19980911 1998091112 1998.69452 52.3833 4.9333 -1.0 15.0 21.0 13.5 -AT 2 2 19980911 1998091111 1998.69441 52.7780 6.9092 20.0 18.0 22.0 14.0 -AT 2 1 19980911 1998091110 1998.69429 63.4333 10.6167 20.0 19.0 20.0 13.0 -AT 2 3 19980911 1998091111 1998.69441 68.1458 13.6250 20.0 16.0 17.5 9.0 -AT 2 1 19980918 1998091111 1998.69441 59.2067 10.4033 20.0 14.0 17.0 13.0 -AT 2 1 19980911 1998091111 1998.69441 59.0180 10.0342 35.0 15.0 16.0 14.0 -AT 2 1 19980915 1998091111 1998.69441 59.4850 6.4883 70.0 13.5 15.0 11.0 -AT 2 2 19980921 1998091110 1998.69429 58.9428 5.6570 37.0 14.0 16.0 13.0 -AT 2 1 19980914 1998091109 1998.69418 59.5667 9.2667 114.0 14.8 15.0 12.0 -AT 2 2 19980911 1998091111 1998.69441 61.3538 5.3987 333.0 14.0 16.0 12.0 -AT 2 1 19980911 1998091111 1998.69441 58.2833 7.9833 49.0 15.0 15.0 12.0 -AT 2 1 19980916 1998091111 1998.69441 59.3833 10.2833 29.0 17.5 18.0 9.0 -AT 2 1 19980914 1998091112 1998.69452 63.7333 10.6333 15.0 18.0 20.0 1.0 -AT 2 1 19980911 1998091112 1998.69452 32.8167 -16.9833 30.0 22.5 27.0 18.0 -AT 2 1 19980914 1998091110 1998.69429 59.3428 17.9147 29.0 18.0 20.0 12.0 -AT 2 1 19980911 1998091110 1998.69429 60.6056 16.7468 63.0 17.0 20.6 12.1 -AT 2 1 19980913 1998091112 1998.69452 56.2723 14.5257 56.0 18.0 19.5 13.5 -AT 2 1 19980911 1998091110 1998.69429 57.9275 12.0843 15.0 16.5 18.5 14.0 -AT 2 3 19980911 1998091111 1998.69441 56.0413 13.6785 100.0 17.2 18.9 12.8 -AT 2 2 19980911 1998091121 1998.69555 57.6138 -152.2355 14.0 13.0 13.0 11.5 -AT 2 2 19980911 1998091120 1998.69543 57.7883 -152.4030 35.0 10.0 10.0 8.0 -AT 2 2 19980912 1998091122 1998.69566 64.8380 -147.7277 150.0 14.0 21.0 1.0 -AT 2 1 19980911 1998091122 1998.69566 62.6067 -159.5184 135.0 10.0 16.0 2.0 -AT 2 1 19980915 1998091118 1998.69521 31.2445 -85.4483 71.0 29.0 29.0 21.0 -AT 2 1 19980911 1998091116 1998.69498 34.7792 -86.6124 275.0 31.0 47.0 16.0 -AT 2 2 19980911 1998091117 1998.69509 34.8630 -87.5290 178.0 29.0 32.0 15.0 -AT 2 1 19980914 1998091117 1998.69509 35.2969 -94.0361 198.0 31.5 34.0 21.0 -AT 2 1 19980917 1998091118 1998.69521 33.6669 -93.5914 110.0 40.0 51.0 31.0 -AT 2 2 19980911 1998091118 1998.69521 35.4763 -94.2173 131.0 32.0 34.0 21.0 -AT 2 1 19980911 1998091116 1998.69498 36.1867 -94.1286 379.0 29.0 33.0 20.0 -AT 2 1 19980915 1998091117 1998.69509 33.6140 -92.0778 43.0 23.0 33.0 22.0 -AT 2 2 19980911 1998091117 1998.69509 36.2012 -94.1738 1389.0 30.0 37.0 20.0 -AT 2 1 19980911 1998091119 1998.69532 32.3593 -111.0118 743.0 34.0 38.0 20.0 -AT 2 1 19980914 1998091118 1998.69521 32.2217 -110.9258 836.0 32.7 37.7 22.7 -AT 2 1 19980911 1998091118 1998.69521 33.4483 -112.0730 372.0 33.0 45.0 10.0 -AT 2 2 19980911 1998091118 1998.69521 31.5702 -110.2403 1312.0 33.0 36.0 18.0 -AT 2 1 19980918 1998091119 1998.69532 32.2217 -110.9258 836.0 32.0 36.0 21.0 -AT 2 2 19980918 1998091119 1998.69532 39.8007 -120.4660 1500.0 20.0 21.0 2.0 -AT 2 1 19980911 1998091118 1998.69521 33.7769 -118.0386 7.0 25.0 26.0 16.0 -AT 2 1 19980921 1998091120 1998.69543 37.2908 -120.3175 87.0 -99.0 32.7 12.4 -AT 2 2 19980911 1998091118 1998.69521 40.0643 -105.1122 1546.0 26.0 34.0 13.0 -AT 2 1 19980916 1998091118 1998.69521 37.4083 -102.6139 1308.0 32.0 33.0 24.0 -AT 2 1 19980911 1998091118 1998.69521 39.2410 -107.8189 3152.0 23.0 30.0 12.0 -AT 2 1 19980912 1998091116 1998.69498 41.8758 -72.8017 28.0 25.0 -99.0 -99.0 -AT 2 2 19980911 1998091115 1998.69486 41.0533 -73.5388 24.0 18.0 18.0 11.0 -AT 2 1 19980911 1998091117 1998.69509 28.3644 -82.1961 25.0 27.0 30.0 20.0 -AT 2 1 19980911 1998091117 1998.69509 28.0433 -81.9567 35.0 23.0 24.0 16.0 -AT 2 1 19980911 1998091117 1998.69509 26.1425 -80.1395 0.0 39.0 40.0 34.0 -AT 2 1 19980911 1998091116 1998.69498 29.4641 -81.2446 6.0 27.0 27.0 24.0 -AT 2 2 19980919 1998091117 1998.69509 28.1013 -80.6243 12.0 29.0 29.0 24.0 -AT 2 2 19980911 1998091117 1998.69509 27.6270 -81.5242 36.0 29.0 32.0 28.0 -AT 2 1 19980921 1998091117 1998.69509 28.0183 -82.1131 31.0 28.0 30.0 22.0 -AT 2 2 19980916 1998091116 1998.69498 30.9900 -83.3818 60.0 -99.0 -99.0 -99.0 -AT 2 1 19980914 1998091117 1998.69509 33.6675 -84.0178 224.0 25.0 28.0 12.0 -AT 2 2 19980916 1998091117 1998.69509 34.0697 -84.2133 359.0 29.0 29.0 9.0 -AT 2 1 19980911 1998091117 1998.69509 42.5172 -90.7222 268.0 22.0 26.0 11.0 -AT 2 1 19980915 1998091118 1998.69521 42.7013 -92.0744 310.0 26.0 28.0 12.0 -AT 2 1 19980911 1998091116 1998.69498 42.0347 -93.6197 277.0 27.0 29.0 10.0 -AT 2 1 19980911 1998091119 1998.69532 43.4777 -115.3098 1307.0 24.0 25.0 11.0 -AT 2 1 19980911 1998091119 1998.69532 43.6279 -111.7409 1856.0 29.0 29.0 9.0 -AT 2 2 19980911 1998091117 1998.69509 41.7600 -87.6765 229.0 28.0 28.0 16.0 -AT 2 2 19980911 1998091118 1998.69521 42.3333 -89.0333 252.0 28.0 28.0 16.0 -AT 2 1 19980911 1998091118 1998.69521 41.4392 -90.7175 223.0 29.0 29.0 10.0 -AT 2 1 19980914 1998091117 1998.69509 41.7676 -88.2930 203.0 35.0 38.0 14.0 -AT 2 1 19980911 1998091118 1998.69521 41.8089 -88.0111 203.0 25.0 30.0 13.0 -AT 2 1 19980916 1998091117 1998.69509 41.9119 -88.2908 215.0 25.0 26.0 14.0 -AT 2 1 19980915 1998091119 1998.69532 41.3495 -88.5271 174.0 28.0 28.0 9.0 -AT 2 1 19980911 1998091117 1998.69509 39.5392 -86.3692 218.0 30.0 39.0 7.0 -AT 2 1 19980916 1998091117 1998.69509 40.6167 -87.3208 217.0 28.8 32.1 14.9 -AT 2 1 19980912 1998091116 1998.69498 41.1306 -85.1289 238.0 27.0 29.0 12.0 -AT 2 1 19980911 1998091118 1998.69521 38.8814 -94.8189 317.0 31.1 31.1 13.3 -AT 2 1 19980911 1998091119 1998.69532 37.3366 -87.5054 134.0 33.0 36.0 8.0 -AT 2 2 19980914 1998091117 1998.69509 36.9320 -84.0933 307.0 27.0 29.0 10.0 -AT 2 1 19980915 1998091117 1998.69509 37.5528 -87.9893 113.0 28.0 30.0 8.0 -AT 2 1 19980911 1998091117 1998.69509 36.8302 -84.8523 364.0 29.0 30.0 14.0 -AT 2 1 19980911 1998091116 1998.69498 38.2542 -85.7594 145.0 30.0 39.0 30.0 -AT 2 1 19980911 1998091116 1998.69498 41.7072 -70.7630 0.0 21.5 23.0 11.0 -AT 2 2 19980911 1998091115 1998.69486 42.3697 -71.7850 160.0 24.0 24.0 11.0 -AT 2 1 19980914 1998091116 1998.69498 42.5962 -72.3115 287.0 24.0 24.0 5.0 -AT 2 2 19980911 1998091116 1998.69498 38.6215 -76.8627 92.0 25.0 25.0 10.0 -AT 2 1 19980916 1998091118 1998.69521 39.0594 -76.6483 13.0 29.0 29.0 12.0 -AT 2 2 19980911 1998091116 1998.69498 44.3853 -68.2080 22.0 17.0 17.0 11.0 -AT 2 2 19980913 1998091116 1998.69498 44.8817 -69.4458 88.0 18.5 18.5 4.5 -AT 2 2 19980915 1998091117 1998.69509 42.6733 -83.3885 322.0 26.0 26.0 15.0 -AT 2 2 19980911 1998091117 1998.69509 42.6847 -84.4545 266.0 29.0 30.0 12.0 -AT 2 1 19980911 1998091116 1998.69498 41.9442 -84.8839 327.0 22.0 25.0 11.0 -AT 2 2 19980911 1998091116 1998.69498 43.9393 -82.9968 217.0 23.0 24.0 17.0 -AT 2 2 19980914 1998091116 1998.69498 42.3363 -85.3522 282.0 26.0 27.0 11.0 -AT 2 1 19980916 1998091118 1998.69521 45.5897 -94.1483 372.0 29.0 34.0 16.0 -AT 2 2 19980915 1998091118 1998.69521 45.2418 -93.4128 201.0 32.0 32.0 19.0 -AT 2 3 19980911 1998091118 1998.69521 40.4177 -91.7128 217.0 30.0 40.0 -3.0 -AT 2 1 19980911 1998091118 1998.69521 34.8390 -88.5610 99.0 28.0 31.0 17.0 -AT 2 2 19980911 1998091117 1998.69509 30.4503 -88.8285 0.0 24.5 25.0 21.0 -AT 2 2 19980911 1998091117 1998.69509 30.8427 -89.1102 200.0 21.0 -99.0 -99.0 -AT 2 2 19980911 1998091119 1998.69532 45.4500 -112.1897 1559.0 18.0 22.0 7.0 -AT 2 1 19980918 1998091117 1998.69509 35.5978 -82.4000 832.0 34.0 36.0 33.0 -AT 2 2 19980918 1998091117 1998.69509 36.2417 -80.2908 953.0 26.0 30.0 9.0 -AT 2 1 19980914 1998091117 1998.69509 35.3915 -83.1969 830.0 31.0 32.0 28.0 -AT 1 2 19980911 1998091117 1998.69509 35.5950 -82.5062 719.0 26.7 26.7 5.6 -AT 2 1 19980911 1998091117 1998.69509 48.1268 -98.8688 486.0 20.0 38.0 6.0 -AT 2 1 19980911 1998091116 1998.69498 42.4739 -96.4133 329.0 26.0 36.0 18.0 -AT 2 2 19980912 1998091117 1998.69509 43.1778 -71.8247 169.0 21.5 21.5 8.0 -AT 2 1 19980911 1998091116 1998.69498 42.8650 -71.4939 80.0 22.0 24.0 8.0 -AT 2 1 19980911 1998091116 1998.69498 43.2081 -71.5381 105.0 24.0 24.0 9.0 -AT 2 2 19980911 1998091117 1998.69509 43.0217 -74.3722 289.0 20.0 20.0 5.0 -AT 2 1 19980920 1998091116 1998.69498 43.2992 -73.6356 84.0 20.5 21.0 6.5 -AT 2 1 19980911 1998091116 1998.69498 43.1008 -74.7733 234.0 20.0 20.0 3.0 -AT 2 1 19980911 1998091116 1998.69498 42.8526 -78.8252 125.0 21.0 22.0 11.0 -AT 2 2 19980917 1998091117 1998.69509 40.8995 -73.9005 76.0 26.0 26.0 12.0 -AT 2 1 19980911 1998091116 1998.69498 41.4739 -81.5372 314.0 24.0 24.0 11.5 -AT 2 1 19980911 1998091116 1998.69498 40.7473 -81.0400 314.0 24.0 24.0 4.0 -AT 2 1 19980911 1998091116 1998.69498 39.9611 -82.9989 224.0 28.0 28.0 9.0 -AT 2 1 19980911 1998091118 1998.69521 34.6452 -97.9518 360.0 30.0 33.0 24.0 -AT 2 1 19980913 1998091118 1998.69521 36.0906 -94.9200 280.0 27.0 32.0 19.0 -AT 2 1 19980911 1998091118 1998.69521 35.5485 -97.4150 364.0 33.0 45.0 25.0 -AT 2 2 19980920 1998091117 1998.69509 41.3393 -80.3955 350.0 23.0 23.0 9.0 -AT 2 2 19980917 1998091117 1998.69509 40.7867 -77.0345 162.0 21.0 33.0 11.0 -AT 2 1 19980911 1998091115 1998.69486 40.5343 -80.1801 316.0 20.0 21.0 10.0 -AT 2 1 19980916 1998091115 1998.69486 39.9470 -75.9753 160.0 23.3 23.3 4.9 -AT 2 2 19980911 1998091116 1998.69498 39.9345 -77.2450 215.0 25.0 25.0 10.0 -AT 2 1 19980912 1998091116 1998.69498 41.4488 -75.6018 465.0 22.0 22.0 6.0 -AT 2 2 19980911 1998091117 1998.69509 40.0068 -75.1347 9.0 26.0 26.0 15.0 -AT 2 3 19980911 1998091117 1998.69509 40.0435 -75.0243 -11.0 26.0 27.5 9.0 -AT 2 1 19980914 1998091116 1998.69498 40.0183 -75.9142 124.0 21.0 -99.0 -99.0 -AT 2 2 19980913 1998091117 1998.69509 39.7487 -77.5712 204.0 23.0 23.0 8.0 -AT 2 1 19980912 1998091117 1998.69509 39.9606 -75.6058 111.0 23.0 23.0 11.0 -AT 2 2 19980912 1998091116 1998.69498 18.0340 -66.8733 57.0 34.0 34.0 26.0 -AT 2 1 19980911 1998091116 1998.69498 18.4987 -67.1398 56.0 32.0 33.0 24.0 -AT 2 1 19980915 1998091116 1998.69498 18.3994 -66.0503 234.0 34.0 36.0 15.0 -AT 2 1 19980914 1998091115 1998.69486 32.4258 -80.7292 6.0 25.0 29.0 15.0 -AT 2 1 19980911 1998091118 1998.69521 35.1635 -87.7185 216.0 27.0 41.0 5.0 -AT 2 1 19980914 1998091118 1998.69521 29.7631 -95.3631 7.0 26.0 26.0 23.0 -AT 2 2 19980911 1998091118 1998.69521 32.8598 -96.8002 161.0 24.0 46.0 21.0 -AT 2 1 19980911 1998091118 1998.69521 29.7533 -95.7152 24.0 27.0 27.0 24.0 -AT 2 1 19980911 1998091117 1998.69509 32.8139 -96.9486 184.0 24.0 36.0 22.0 -AT 2 2 19980911 1998091119 1998.69532 31.1020 -97.7372 289.0 23.0 29.0 22.0 -AT 2 1 19980916 1998091119 1998.69532 41.8067 -111.3050 1802.0 25.0 26.0 8.0 -AT 2 1 19980913 1998091119 1998.69532 40.7608 -111.8903 1711.0 21.0 27.0 14.0 -AT 2 1 19980911 1998091116 1998.69498 37.1000 -79.9000 304.0 29.0 30.0 12.0 -AT 2 1 19980917 1998091117 1998.69509 37.5372 -79.3990 289.0 25.0 30.0 15.0 -AT 2 2 19980920 1998091117 1998.69509 37.0510 -76.3222 3.0 28.0 28.0 12.0 -AT 2 2 19980915 1998091115 1998.69486 18.3247 -64.9093 0.0 32.0 34.0 30.0 -AT 2 1 19980911 1998091119 1998.69532 48.1832 -122.1198 157.0 22.0 26.0 11.5 -AT 2 1 19980913 1998091119 1998.69532 47.6589 -117.4250 675.0 25.0 25.0 11.0 -AT 2 1 19980914 1998091119 1998.69532 48.5467 -117.9044 774.0 -99.0 25.5 4.0 -AT 2 2 19980911 1998091120 1998.69543 48.5070 -122.6208 83.0 20.0 22.0 13.0 -AT 2 2 19980911 1998091117 1998.69509 43.3852 -87.9413 209.0 30.0 30.0 23.0 -AT 2 2 19980911 1998091116 1998.69498 46.7133 -92.0920 213.0 26.0 34.0 20.0 -AT 2 2 19980918 1998091118 1998.69521 43.0287 -88.0370 205.0 26.0 26.0 17.0 -AT 2 1 19980914 1998091118 1998.69521 44.7361 -87.6208 208.0 22.0 25.0 -15.0 -AT 1 1 19980914 1998091015 1998.69212 -63.4000 -56.9833 10.0 -21.5 -20.0 -22.3 -AT 2 1 19980914 1998091016 1998.69224 -34.5671 -58.4482 0.0 0.0 0.0 0.0 -AT 2 1 19980920 1998091015 1998.69212 -34.5292 -58.5162 22.0 18.0 18.0 11.0 -AT 2 1 19980910 1998091001 1998.69053 -33.6427 150.0425 1220.0 14.0 16.0 2.0 -AT 2 1 19980910 1998091001 1998.69053 -33.8333 152.0000 0.0 22.0 22.0 9.0 -AT 2 1 19980910 1998091001 1998.69053 -33.2417 150.5844 310.0 19.0 20.0 9.0 -AT 2 2 19980910 1998091003 1998.69075 -23.4200 133.5200 580.0 24.0 24.0 3.5 -AT 2 2 19980910 1998091003 1998.69075 -27.2170 153.0546 2.0 19.0 22.0 11.0 -AT 2 1 19980910 1998091003 1998.69075 -16.9167 145.7667 12.0 28.0 30.0 20.0 -AT 2 1 19980915 1998091003 1998.69075 -34.7833 138.7167 165.0 18.6 20.1 12.1 -AT 2 1 19980910 1998091003 1998.69075 -37.8167 144.9667 12.0 17.0 20.0 9.0 -AT 2 1 19980910 1998091004 1998.69087 -32.3333 115.9500 20.0 19.0 -99.0 9.0 -AT 2 1 19980911 1998091011 1998.69167 50.8103 4.9368 55.0 19.2 21.8 16.2 -AT 2 1 19980914 1998091011 1998.69167 50.6292 6.0261 290.0 19.1 20.1 15.6 -AT 2 1 19980911 1998091011 1998.69167 47.6535 9.1260 420.0 21.0 25.0 15.0 -AT 2 1 19980911 1998091011 1998.69167 47.5678 7.6362 260.0 22.0 27.0 16.0 -AT 2 1 19980916 1998091012 1998.69178 47.5017 9.4242 400.0 19.0 21.0 11.0 -AT 2 1 19980910 1998091011 1998.69167 46.7403 7.6083 565.0 20.5 27.5 13.5 -AT 2 1 19980921 1998091004 1998.69087 37.5319 121.3792 30.0 32.2 34.1 23.3 -AT 1 1 19980916 1998091004 1998.69087 38.6667 114.6000 70.0 27.6 32.9 18.4 -AT 2 1 19980916 1998091011 1998.69167 48.9908 17.7203 250.0 22.0 22.5 18.5 -AT 1 1 19980916 1998091012 1998.69178 50.7823 15.0568 418.0 22.1 22.2 15.5 -AT 2 1 19980910 1998091011 1998.69167 49.5420 15.3537 518.0 19.0 20.0 12.0 -AT 2 3 19980918 1998091011 1998.69167 50.5412 8.5220 260.0 20.0 23.0 16.0 -AT 2 1 19980915 1998091011 1998.69167 51.0167 13.8333 112.0 21.5 22.0 11.0 -AT 2 1 19980912 1998091011 1998.69167 50.7863 7.7175 190.0 18.5 22.0 16.0 -AT 2 1 19980911 1998091012 1998.69178 53.5833 11.4167 30.0 18.0 21.0 17.0 -AT 2 1 19980911 1998091009 1998.69144 51.6333 12.2667 55.0 20.0 25.0 19.0 -AT 2 1 19980921 1998091010 1998.69155 51.5000 7.0000 28.0 13.0 23.0 13.0 -AT 2 1 19980910 1998091012 1998.69178 51.5550 6.9450 38.0 19.0 20.0 13.0 -AT 2 1 19980916 1998091010 1998.69155 53.6632 13.5572 35.0 17.0 22.0 10.0 -AT 2 1 19980916 1998091012 1998.69178 52.3333 10.5333 73.0 21.5 22.0 6.0 -AT 2 2 19980910 1998091010 1998.69155 50.6080 12.1675 314.0 20.9 26.9 18.3 -AT 2 1 19980910 1998091011 1998.69167 53.5853 9.9472 23.0 18.5 20.5 16.0 -AT 2 1 19980914 1998091011 1998.69167 53.8728 8.7428 0.0 14.0 16.0 13.0 -AT 2 1 19980914 1998091010 1998.69155 52.0833 15.0833 180.0 20.0 24.0 18.0 -AT 2 1 19980918 1998091010 1998.69155 51.3187 13.2825 97.0 21.0 29.0 12.0 -AT 1 1 19980910 1998091010 1998.69155 53.4667 9.9667 20.0 26.0 26.0 15.5 -AT 2 1 19980916 1998091012 1998.69178 53.6437 9.9630 15.0 18.1 19.8 14.0 -AT 2 2 19980918 1998091017 1998.69235 -2.1428 -79.9065 2.0 24.0 32.0 21.0 -AT 2 1 19980914 1998091011 1998.69167 59.4425 24.7057 30.0 15.0 22.0 15.0 -AT 2 1 19980921 1998091010 1998.69155 58.8258 22.7762 8.0 15.0 20.0 14.0 -AT 2 1 19980912 1998091009 1998.69144 59.4340 24.7493 60.0 15.5 20.0 12.0 -AT 1 1 19980910 1998091010 1998.69155 59.3922 27.7987 30.0 17.0 17.0 12.0 -AT 2 2 19980917 1998091011 1998.69167 58.7150 26.7513 80.0 12.0 16.0 10.0 -AT 2 1 19980911 1998091011 1998.69167 58.3767 26.7089 200.0 16.0 21.0 14.0 -AT 2 1 19980910 1998091009 1998.69144 60.4714 25.1058 53.0 15.0 20.0 8.0 -AT 2 2 19980911 1998091010 1998.69155 62.7908 30.1637 128.0 15.0 19.5 10.0 -AT 2 1 19980911 1998091011 1998.69167 60.6297 24.8403 125.0 13.0 19.0 13.0 -AT 2 1 19980916 1998091010 1998.69155 63.2377 29.2537 110.0 17.2 19.2 12.1 -AT 2 1 19980911 1998091009 1998.69144 62.8036 30.1181 109.0 14.0 19.0 13.0 -AT 2 2 19980914 1998091010 1998.69155 60.8042 23.4932 105.0 16.0 21.0 14.0 -AT 2 1 19980911 1998091009 1998.69144 62.2508 25.7381 100.0 18.0 20.0 14.0 -AT 2 1 19980910 1998091009 1998.69144 64.8781 28.9342 211.0 13.0 17.5 12.5 -AT 2 1 19980910 1998091009 1998.69144 66.5078 25.7033 123.0 13.0 14.0 8.0 -AT 2 1 19980920 1998091010 1998.69155 59.8268 22.9755 0.0 15.0 18.0 15.0 -AT 2 1 19980916 1998091011 1998.69167 61.7403 27.3347 97.0 16.0 19.0 7.0 -AT 2 1 19980915 1998091010 1998.69155 64.9028 25.4694 15.0 16.0 17.0 12.0 -AT 2 1 19980918 1998091009 1998.69144 65.8767 28.9375 210.0 13.0 13.0 11.0 -AT 2 2 19980910 1998091010 1998.69155 60.4543 26.2247 30.0 17.0 17.0 11.0 -AT 2 1 19980915 1998091009 1998.69144 60.9857 24.4333 142.0 13.0 18.0 13.0 -AT 2 2 19980910 1998091010 1998.69155 64.7622 26.4150 80.0 16.0 20.0 11.0 -AT 2 1 19980911 1998091010 1998.69155 62.2981 27.1472 124.0 16.0 19.0 12.0 -AT 2 2 19980910 1998091009 1998.69144 60.9902 25.5207 155.0 14.0 21.0 12.0 -AT 2 1 19980912 1998091010 1998.69155 60.2662 24.8543 32.0 14.0 20.0 -99.0 -AT 2 1 19980910 1998091008 1998.69132 62.2658 26.2078 93.0 18.0 20.0 11.0 -AT 2 2 19980911 1998091010 1998.69155 62.3018 27.1365 122.0 16.0 22.0 12.0 -AT 2 2 19980916 1998091010 1998.69155 62.2888 25.7350 100.0 15.0 21.0 2.0 -AT 2 1 19980910 1998091010 1998.69155 60.8042 23.4944 110.0 15.0 18.0 14.0 -AT 2 1 19980916 1998091011 1998.69167 37.9522 23.6133 35.0 30.0 33.0 24.0 -AT 2 1 19980910 1998091010 1998.69155 37.9915 23.6752 40.0 28.0 33.5 22.0 -AT 2 1 19980921 1998091010 1998.69155 37.0677 22.4247 207.0 33.5 33.5 21.0 -AT 2 1 19980913 1998091010 1998.69155 37.9365 23.6960 12.0 28.5 33.0 23.5 -AT 2 1 19980918 1998091011 1998.69167 46.0023 16.1195 162.0 22.0 22.0 17.0 -AT 2 1 19980917 1998091012 1998.69178 45.3388 14.3083 10.0 25.0 26.0 18.0 -AT 2 2 19980912 1998091010 1998.69155 45.4933 15.5622 119.0 23.0 27.0 17.0 -AT 2 1 19980917 1998091010 1998.69155 45.5139 17.1278 170.0 21.0 21.0 12.0 diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N.properties deleted file mode 100644 index 3844452f6..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N.properties +++ /dev/null @@ -1,35 +0,0 @@ -# Sample ResourceBundle properties file - -ShapeLayer.shapeFile=Name of the shape file - -ShapeLayer.spatialIndex=Name of the spatial index file - -ShapeLayer.spatialIndex.tooltip=Location of Spatial Index file - .ssx (File, URL or relative file path). - -ShapeLayer.shapeFile.tooltip=Location of Shape file - .shp (File, URL or relative file path). - -ShapeLayer.pointImageURL=Point image URL - -ShapeLayer.pointImageURL.tooltip=Image file to use for map location of point data (optional). - -ShapeLayer.redrawLayerButton=Redraw Layer - -SpatialIndexHandler.enableButton=Show - -SpatialIndexHandler.bufferButton=Buffer - -SpatialIndexHandler.buffered.tooltip=Read and hold entire file contents (may be faster) - -SpatialIndexHandler.buffered=Buffered - -SpatialIndexHandler.enabled=Enabled - -SpatialIndexHandler.enabled.tooltip=Show file contents - -ShapeLayer.shadowX=Shadow X - -ShapeLayer.shadowX.tooltip=Horizontal pixel offset for shadow image for shapes. - -ShapeLayer.shadowY=Shadow Y - -ShapeLayer.shadowY.tooltip=Vertical pixel offset for shadow image for shapes. diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N_pl_PL.properties deleted file mode 100644 index a86835927..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/shape/I18N_pl_PL.properties +++ /dev/null @@ -1,35 +0,0 @@ -# Sample ResourceBundle properties file - -ShapeLayer.shapeFile=Plik 'shape' - -ShapeLayer.spatialIndex=Plik 'spatial index' - -ShapeLayer.spatialIndex.tooltip=Po\u0142o\u017Cenie pliku spatial index -.ssx (Plik,URL albo \u015Bcie\u017Cka do pliku) - -ShapeLayer.shapeFile.tooltip=Po\u0142o\u017Cenie pliku shape - .shp (Plik,URL albo \u015Bcie\u017Cka do pliku) - -ShapeLayer.pointImageURL=Plik 'point image' - -ShapeLayer.pointImageURL.tooltip=Plik z obrazem u\u017Cwanym na mapie dla danych punktowych (opcjonalne) - -SpatialIndexHandler.enableButton=Poka\u017C - -SpatialIndexHandler.bufferButton=Bufor - -SpatialIndexHandler.buffered.tooltip=Czytaj i utrzymuj zawarto\u015B\u0107 pliku (mo\u017Ce przyspieszy\u0107 dzia\u0142anie) - -SpatialIndexHandler.buffered=Buforowane - -SpatialIndexHandler.enabled=W\u0142\u0105czone - -SpatialIndexHandler.enabled.tooltip=Poka\u017C zawarto\u015Bc pliku - -ShapeLayer.shadowX=Cieniowanie X - -ShapeLayer.shadowX.tooltip=Poziome przesuni\u0119cie pikseli dla cieniowanego rysunku - -ShapeLayer.shadowY=Cieniowanie Y - -ShapeLayer.shadowY.tooltip=Pionowe przesuni\u0119cie pikseli dla cieniowanego rysunku - -ShapeLayer.redrawLayerButton=Od\u015Bwie\u017C warstw\u0119 diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/terrain/TerrainLayer.properties b/src/core/src/main/resources/com/bbn/openmap/layer/terrain/TerrainLayer.properties deleted file mode 100644 index 3cbfb9c9d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/terrain/TerrainLayer.properties +++ /dev/null @@ -1,36 +0,0 @@ -# ********************************************************************** -# -# BBN Corporation -# 10 Moulton St. -# Cambridge, MA 02138 -# (617) 873-2000 -# -# Copyright (C) 1998 -# This software is subject to copyright protection under the laws of -# the United States and other countries. -# -# ********************************************************************** -# -# $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/TerrainLayer.properties,v $ -# $RCSfile: TerrainLayer.properties,v $ -# $Revision: 1.1.1.1 $ -# $Date: 2003/02/14 21:35:48 $ -# $Author: dietrick $ -# -# ********************************************************************** - - -#---------------------------------------------------------------------- -# Properties file for TerrainLayer -#---------------------------------------------------------------------- -# This property should reflect the paths to the DTED directories -terrain.dted.paths=/usr/local/matt/data/dted -# The default tool to use for the terrain layer. -terrain.default.mode=PROFILE - -#---------------------------------------------------------------------- -# End of properties file for TerrainLayer -#---------------------------------------------------------------------- - - - diff --git a/src/core/src/main/resources/com/bbn/openmap/layer/vpf/defaultVPFlayers.properties b/src/core/src/main/resources/com/bbn/openmap/layer/vpf/defaultVPFlayers.properties deleted file mode 100644 index 0a9c2ab79..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/layer/vpf/defaultVPFlayers.properties +++ /dev/null @@ -1,34 +0,0 @@ -## -## Support a simple alias mechanism for common vpf layers -## - -# Just continents -vmapCoastline.coverageType=bnd -vmapCoastline.featureTypes=edge area -vmapCoastline.edge=coastl -vmapCoastline.area=polbnda - -# Basic political boundaries with VMAP -vmapPolitical.coverageType=bnd -vmapPolitical.featureTypes=edge area text -#skip the depth contours -#vmapPolitical.edge= polbndl coastl depthl -vmapPolitical.edge= polbndl coastl -#skip filling the ocean areas -#vmapPolitical.area= oceansea polbnda -vmapPolitical.area= polbnda -#vmapPolitical.text= pol - -# Basic political boundaries with DCW -dcwPolitical.coverageType=po -dcwPolitical.featureTypes=edge area - -# VMAP Road network data -vmapRoad.coverageType=trans -vmapRoad.featureTypes=edge -vmapRoad.edge=roadl - -# VMAP Railroad network data -vmapRRoad.coverageType=trans -vmapRRoad.featureTypes=edge -vmapRRoad.edge=railrdl diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N.properties deleted file mode 100644 index f89de26aa..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N.properties +++ /dev/null @@ -1,113 +0,0 @@ -# Sample ResourceBundle properties file - -DrawingAttributes.lineColor=Line color - -DrawingAttributes.lineColor.tooltip=Edge color for graphics. - -DrawingAttributes.fillColor=Fill color - -DrawingAttributes.fillColor.tooltip=Fill color for graphics. - -DrawingAttributes.selectColor=Selected color - -DrawingAttributes.selectColor.tooltip=Selected edge color for graphics. - -DrawingAttributes.mattingColor=Matting color - -DrawingAttributes.mattingColor.tooltip=Matting edge color for graphics. - -DrawingAttributes.fillPattern=Image fill pattern - -DrawingAttributes.fillPattern.tooltip=Image file to use for fill pattern for graphics (optional). - -DrawingAttributes.lineWidth=Line width - -DrawingAttributes.lineWidth.tooltip=Line width for edges of graphics - -DrawingAttributes.dashPattern=Dash pattern - -DrawingAttributes.dashPattern.tooltip=Line dash pattern, represented by space separated numbers (on off on ...) - -DrawingAttributes.dashPhase=Dash phase - -DrawingAttributes.dashPhase.tooltip=Phase for dash pattern (Default is 0) - -DrawingAttributes.baseScale=Base scale - -DrawingAttributes.baseScale.tooltip=Scale which should be used as the base scale for the
patterns and line width. If set, size of pattern and
widths will be adjusted to the map scale - -DrawingAttributes.matted=Matted - -DrawingAttributes.matted.tooltip=Flag to enable a thin black matting to be drawn around graphics.. - -DrawingAttributes.chooseLineColor=Choose Line Color - -DrawingAttributes.chooseMattingColor=Choose Matting Color - -DrawingAttributes.chooseFillColor=Choose Fill Color - -DrawingAttributes.chooseSelectColor=Choose Select Color - -DrawingAttributes.lineButton.tooltip=Modify Line Parameters - -DrawingAttributes.mattedCheckBox.tooltip=Enable/Disable Matting on Edge - -DrawingAttributes.mattingColorButton.tooltip=Change Matted Edge Color (true/opaque) - -DrawingAttributes.selectColorButton.tooltip=Change Highlight Edge Color (true/opaque) - -DrawingAttributes.fillColorButton.tooltip=Change Fill Color (true/opaque) - -DrawingAttributes.lineColorButton.tooltip=Change Edge Color (true/opaque) - -BasicStrokeEditorMenu.Modify_Line_Parameters=Modify Line Parameters - -BasicStrokeEditorMenu.Joint_Decoration=Joint Decoration - -BasicStrokeEditorMenu.Round=Round - -BasicStrokeEditorMenu.Butt=Butt - -BasicStrokeEditorMenu.Dash_Pattern=Dash Pattern - -BasicStrokeEditorMenu.Cap_Decoration=Cap Decoration - -BasicStrokeEditorMenu.Square=Square - -BasicStrokeEditorMenu.Bevel=Bevel - -BasicStrokeEditorMenu.Line_Width=Line Width - -BasicStrokeEditorMenu.Miter=Miter - -GraphicAttributes.Line_Type=Line Type - -GraphicAttributes.Great_Circle=Great Circle - -GraphicAttributes.Rhumb=Rhumb - -GraphicAttributes.Straight=Straight - -ColorTracker.opaque=opaque - -ColorTracker.clear=clear - -EditableOMText.textField.tooltip=Text rotation in degrees - -EditableOMText.sizesFont.tooltip=Font Size - -EditableOMText.boldFont.tooltip=Bold Font - -EditableOMText.italicFont.tooltip=Italic Font - -EditableOMAbstractLine.Arrows=Arrows - -EditableOMRangeRings.intervalField.tooltip=Value for interval between rings. - -EditableOMRangeRings.unitStrings.concentric=concentric - -EditableOMPoly.polygonButton.tooltip=Automatically link first and last nodes - -EditableOMPoly.addButton.tooltip=Add a node to the polygon - -EditableOMPoly.deleteButton.tooltip=Delete a node from the polygon diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_da_DK.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_da_DK.properties deleted file mode 100644 index e3391bcac..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_da_DK.properties +++ /dev/null @@ -1,71 +0,0 @@ -# Sample ResourceBundle properties file - -DrawingAttributes.lineColor=Linie farve - -DrawingAttributes.lineColor.tooltip=kant farve for grafik. - -DrawingAttributes.fillColor=Udfyldnings farve - -DrawingAttributes.fillColor.tooltip=Udfyldnings farve for grafik. - -DrawingAttributes.selectColor=Valgte kant farve - -DrawingAttributes.selectColor.tooltip=Valgte kant farve for grafik. - -DrawingAttributes.mattingColor=Sammenfiltnigs farve - -DrawingAttributes.mattingColor.tooltip=Sammenfiltnings kant farve for grafik. - -DrawingAttributes.fillPattern=Billede udfyldnings mønster - -DrawingAttributes.fillPattern.tooltip=Billede file som anvendes til udfyldnings mønster (valgfri). - -DrawingAttributes.lineWidth=Linie bredde - -DrawingAttributes.lineWidth.tooltip=Linie bredde fro kanterne i grafikken. - -DrawingAttributes.dashPattern=Stiplet mønster - -DrawingAttributes.dashPattern.tooltip=Stiplet mønstre -#, represented by space separated numbers (on off on ...) - -DrawingAttributes.dashPhase=Stiple fase - -DrawingAttributes.dashPhase.tooltip=Fase stipel mønster (Default er 0) - -DrawingAttributes.baseScale=Basis målestok - -DrawingAttributes.baseScale.tooltip=#Målestok som anvendes til skalering af
mønstere og linie bredde. Når basis målestok er aktive bliver størrlesen af mønstre og linie bredder tilpasset kort målstokken. - -DrawingAttributes.matted=Sammenfilted - -DrawingAttributes.matted.tooltip=Flag som aktivere tegning af en tynd sort skygge omnkring omkring grafik. - -DrawingAttributes.chooseLineColor=Vælg linie farve - -DrawingAttributes.chooseMattingColor=Vælg sammenfiltnings farve - -DrawingAttributes.chooseFillColor=Vælg udfyldnings farve - -DrawingAttributes.chooseSelectColor=Choose Select Color - -DrawingAttributes.lineButton.tooltip=Opsætning af linie parametere - -DrawingAttributes.mattedCheckBox.tooltip=Aktiver/Deaktiver kant skygger - -DrawingAttributes.mattingColorButton.tooltip=Vælg kant skygge farve. - -DrawingAttributes.selectColorButton.tooltip=Vælg Highlight kant farve - -DrawingAttributes.fillColorButton.tooltip=Vælg udfyldnings farve - -DrawingAttributes.lineColorButton.tooltip=Vælg kant farve - - -EditableOMPoly.polygonButton.tooltip=Luk polygon automatisk - -EditableOMPoly.addButton.tooltip=Tilføj punkt -#til polygon - -EditableOMPoly.deleteButton.tooltip=Fjern punkt -#fra polygon diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_pl_PL.properties deleted file mode 100644 index e12dac038..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/I18N_pl_PL.properties +++ /dev/null @@ -1,113 +0,0 @@ -# Sample ResourceBundle properties file - -DrawingAttributes.lineColor=Kolor linii - -DrawingAttributes.lineColor.tooltip=Kolor krawedzi dla grafiki - -DrawingAttributes.fillColor=Kolor wype\u0142nienia - -DrawingAttributes.fillColor.tooltip=Kolor wype\u0142nienia dla grafiki - -DrawingAttributes.selectColor=Kolor wybranej linii - -DrawingAttributes.selectColor.tooltip=Kolor wybranje linii na obiekcie graficznym - -DrawingAttributes.mattingColor=Kolor cieniowania - -DrawingAttributes.mattingColor.tooltip=Kolor cieniowania linii - -DrawingAttributes.fillPattern=Wzorzec wype\u0142nienia (obrazek) - -DrawingAttributes.fillPattern.tooltip=Obrazek u\u017Cywany jako wype\u0142nienie t\u0142a (opcjonalnie) - -DrawingAttributes.lineWidth=Szeroko\u015B\u0107 linii - -DrawingAttributes.lineWidth.tooltip=Szeroko\u015B\u0107 lini dla kraw\u0119dzi rysunku - -DrawingAttributes.dashPattern=Wzorzec linii przerywanej - -DrawingAttributes.dashPattern.tooltip=Wzorzec linii przerywanej, reprezentowany jako spacja odzielana liczbami (linia przerwa lnia...) - -DrawingAttributes.dashPhase=Przesuni\u0119cie linii - -DrawingAttributes.dashPhase.tooltip=Przesuni\u0119cie lini przerywanej (domy\u015Blnie 0) - -DrawingAttributes.baseScale=Skala podstawowa - -DrawingAttributes.baseScale.tooltip=Skala, kt\u00F3ra b\u0119dzie u\u017Cywana jak skala dla
wzor\u00F3w i grubo\u015Bci linii. Je\u015Bli ustawiona, rozmairy wzor\u00F3w oraz
grubo\u015Bci linii zostana dostosowane do skali mapy. - -DrawingAttributes.matted=Cieniowanie - -DrawingAttributes.matted.tooltip=Znacznik, okre\u015Blaj\u0105cy czy ma by\u0107 rysowana cieniutka siatka dooko\u0142a grafiki - -DrawingAttributes.chooseLineColor=Wybierz kolor linii - -DrawingAttributes.chooseMattingColor=Wybierz kolor cieniowania - -DrawingAttributes.chooseFillColor=Wybierz kolor wype\u0142nienia - -DrawingAttributes.chooseSelectColor=Wybierz kolor selekcji - -DrawingAttributes.lineButton.tooltip=Modyfikacja parametr\u00F3w linii - -DrawingAttributes.mattedCheckBox.tooltip=W\u0142\u0105cz/wy\u0142\u0105cz cieniowanie na kraw\u0119dziach - -DrawingAttributes.mattingColorButton.tooltip=Zmiana koloru cieniowania lini (zdefiniowany / podstawowy) - -DrawingAttributes.selectColorButton.tooltip=Zmiana koloru linii pod\u015Bwietlenia (zdefiniowany / podstawowy) - -DrawingAttributes.fillColorButton.tooltip=Zmiana koloru wype\u0142nienia (zdefiniowany / podstawowy) - -DrawingAttributes.lineColorButton.tooltip=Zmiana koloru kraw\u0119dzi (zdefiniowany / podstawowy) - -BasicStrokeEditorMenu.Line_Width=Szeroko\u015B\u0107 linii - -BasicStrokeEditorMenu.Joint_Decoration=Styl \u0142\u0105czenia - -BasicStrokeEditorMenu.Cap_Decoration=Styl zako\u0144czenia - -BasicStrokeEditorMenu.Modify_Line_Parameters=Modyfikacja parametr\u00F3w linii - -BasicStrokeEditorMenu.Round=Zaokr\u0105glone - -BasicStrokeEditorMenu.Square=Kwadratowe - -BasicStrokeEditorMenu.Butt=Przylegaj\u0105ce - -BasicStrokeEditorMenu.Miter=K\u0105towe - -BasicStrokeEditorMenu.Bevel=Uko\u015Bne - -BasicStrokeEditorMenu.Dash_Pattern=Wz\u00F3r linii - -GraphicAttributes.Line_Type=Rodzaj linii - -GraphicAttributes.Straight=Prosta - -GraphicAttributes.Rhumb=Loksodroma - -GraphicAttributes.Great_Circle=Ortodroma - -ColorTracker.clear= Przezroczysto\u015B\u0107 - -ColorTracker.opaque= - -EditableOMText.textField.tooltip=K\u0105t obrotu tekstu w stopniach - -EditableOMText.sizesFont.tooltip=Rozmiar czcionki - -EditableOMText.boldFont.tooltip=Pogrubienie - -EditableOMText.italicFont.tooltip=Kursywa - -EditableOMAbstractLine.Arrows=Strza\u0142ki - -EditableOMRangeRings.intervalField.tooltip=Odleg\u0142o\u015B\u0107 mi\u0119dzy okr\u0119gami lub ilo\u015B\u0107 okr\u0119g\u00F3w. - -EditableOMRangeRings.unitStrings.concentric=okr\u0119gi - -EditableOMPoly.polygonButton.tooltip=Automatycznie \u0142\u0105cz pierwszy i ostatni punkt - -EditableOMPoly.addButton.tooltip=Dodaj punkt - -EditableOMPoly.deleteButton.tooltip=Usu\u0144 punkt diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/addnode.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/addnode.gif deleted file mode 100644 index 3fb5c5789..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/addnode.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/addpoint.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/addpoint.gif deleted file mode 100644 index 9f923c35f..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/addpoint.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/deletepoint.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/deletepoint.gif deleted file mode 100644 index 045574129..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/deletepoint.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N.properties deleted file mode 100644 index a92a2698d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N.properties +++ /dev/null @@ -1,47 +0,0 @@ -# Sample ResourceBundle properties file - -TextUndefinedState.Click_to_define_the_text_location.=Click to define the text location. - -PolySetOffsetState.Click_to_place_offset_point_for_poly.=Click to place offset point for poly. - -PolyDeleteNodeState.Release_over_a_node_to_delete_it.=Release over a node to delete it. - -PolyDeleteNodeState.Click_a_node_to_delete_it.=Click a node to delete it. - -PolyAddNodeState.Click_on_a_node_to_add_a_point.=Click on a node to add a point. - -PolyAddNodeState.Release_on_an_node_to_add_a_node.=Release on an node to add a node. - -PointUndefinedState.Click_to_define_the_point_location.=Click to define the point location. - -TextSetOffsetState.Click_to_place_offset_point.=Click to place offset point. - -ScalingRasterSetOffsetState.Click_to_place_offset_point.=Click to place offset point. - -PointSetOffsetState.Click_to_place_offset_point.=Click to place offset point. - -RectSetOffsetState.Click_to_place_offset_point.=Click to place offset point. - -LineSetOffsetState.Click_to_place_offset_point_for_line.=Click to place offset point for line. - -ListUnselectedState.Click_to_select_the_graphic.=Click to select the graphic. - -GraphicUnselectedState.Click_to_select_the_graphic.=Click to select the graphic. - -GraphicUndefinedState.Click_and_Drag_to_define_graphic.=Click and Drag to define graphic. - -GraphicSelectedState.Click_and_Drag_to_move_the_graphic.=Click and Drag to move the graphic. - -CircleSetOffsetState.Click_to_place_offset_point_for_circle.=Click to place offset point for circle. - -ScalingRasterSelectedState.Click_and_Drag_to_change_the_graphic.=Click and Drag to change the graphic. - -RectSelectedState.Click_and_Drag_to_change_the_graphic.=Click and Drag to change the graphic. - -ListSelectedState.Click_and_Drag_to_change_the_graphic.=Click and Drag to change the graphic. - -GraphicSelectedState.Click_and_Drag_to_change_the_graphic.=Click and Drag to change the graphic. - -CircleSelectedState.Click_and_Drag_to_change_the_graphic.=Click and Drag to change the graphic. - -CircleSelectedState.Click_and_Drag_edge_to_resize.=Click and Drag edge to resize. diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_da_DK.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_da_DK.properties deleted file mode 100644 index deafc2d68..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_da_DK.properties +++ /dev/null @@ -1,4 +0,0 @@ -GraphicSelectedState.dragText=Klik og tr\u00E6k for at flytte objektet - -GraphicSelectedState.modifyText=Klik og tr\u00E6k for at \u00E6ndre objektet - diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_pl_PL.properties deleted file mode 100644 index 743c4d90d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/I18N_pl_PL.properties +++ /dev/null @@ -1,45 +0,0 @@ -# Sample ResourceBundle properties file - -TextUndefinedState.Click_to_define_the_text_location.=Kliknij aby zdefiniowa\u0107 lokalizacj\u0119 tekstu. - -PolyDeleteNodeState.Release_over_a_node_to_delete_it.=Zwolnij klawisz nad w\u0119z\u0142em aby go usun\u0105\u0107. - -PolyDeleteNodeState.Click_a_node_to_delete_it.=Kliknij w\u0119ze\u0142 aby go usun\u0105\u0107. - -PolyAddNodeState.Click_on_a_node_to_add_a_point.=Kliknij na w\u0119\u017Ale aby doda\u0107 punkt. - -PointUndefinedState.Click_to_define_the_point_location.=Kliknij aby usun\u0105\u0107 lokalizacj\u0119 punktu. - -TextSetOffsetState.Click_to_place_offset_point.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia. - -ScalingRasterSetOffsetState.Click_to_place_offset_point.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia. - -PointSetOffsetState.Click_to_place_offset_point.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia. - -RectSetOffsetState.Click_to_place_offset_point.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia. - -LineSetOffsetState.Click_to_place_offset_point_for_line.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia dla linii. - -ListUnselectedState.Click_to_select_the_graphic.=Kliknij aby zaznaczy\u0107 grafik\u0119. - -GraphicUnselectedState.Click_to_select_the_graphic.=Kliknij aby zaznaczy\u0107 grafik\u0119. - -GraphicUndefinedState.Click_and_Drag_to_define_graphic.=Kliknij i przeci\u0105gnij aby zdefiniowa\u0107 grafik\u0119. - -GraphicSelectedState.Click_and_Drag_to_move_the_graphic.=Kliknij i przeci\u0105gnij aby przesun\u0105\u0107 grafik\u0119. - -CircleSetOffsetState.Click_to_place_offset_point_for_circle.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia dla ko\u0142a. - -ScalingRasterSelectedState.Click_and_Drag_to_change_the_graphic.=Kliknij i przeci\u0105gnij aby zmieni\u0107 grafik\u0119. - -RectSelectedState.Click_and_Drag_to_change_the_graphic.=Kliknij i przeci\u0105gnij aby zmieni\u0107 grafik\u0119. - -ListSelectedState.Click_and_Drag_to_change_the_graphic.=Kliknij i przeci\u0105gnij aby zmieni\u0107 grafik\u0119. - -GraphicSelectedState.Click_and_Drag_to_change_the_graphic.=Kliknij i przeci\u0105gnij aby zmieni\u0107 grafik\u0119. - -CircleSelectedState.Click_and_Drag_to_change_the_graphic.=Kliknij i przeci\u0105gnij aby zmieni\u0107 grafik\u0119. - -CircleSelectedState.Click_and_Drag_edge_to_resize.=Kliknij i przeci\u0105gnij kraw\u0119d\u017A aby zmieni\u0107 jej rozmiar. - -PolySetOffsetState.Click_to_place_offset_point_for_poly.=Kliknij aby ustawi\u0107 punkt przesuni\u0119cia dla \u0142amanej. diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/edit.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/edit.gif deleted file mode 100644 index 99f601efa..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/edit.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/move.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/move.gif deleted file mode 100644 index 08b33ca52..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/move.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/putnode.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/putnode.gif deleted file mode 100644 index 231fda3ac..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/editable/putnode.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/omGraphics/enclosepoly.gif b/src/core/src/main/resources/com/bbn/openmap/omGraphics/enclosepoly.gif deleted file mode 100644 index 1d35263ce..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/omGraphics/enclosepoly.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/plugin/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/plugin/I18N.properties deleted file mode 100644 index ba1c9cf49..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/plugin/I18N.properties +++ /dev/null @@ -1,53 +0,0 @@ -# Sample ResourceBundle properties file - -UTMGridPlugIn.showLabels=Show labels - -UTMGridPlugIn.showZones=Show zones - -UTMGridPlugIn.showLabels.tooltip=Show Labels for Grid Lines - -UTMGridPlugIn.showZones.tooltip=Show UTM Zone Grid Lines. - -UTMGridPlugIn.show100KmGrid=Show 100Km grid lines - -UTMGridPlugIn.utmGridColor=Grid color - -UTMGridPlugIn.distanceGridColor=Distance grid color - -UTMGridPlugIn.distanceGridResolution=Resolution for grid lines - -UTMGridPlugIn.show100KmGrid.tooltip=Show 100Km Distance Grid Lines - -UTMGridPlugIn.utmGridColor.tooltip=Color for UTM Zone Grid lines. - -UTMGridPlugIn.distanceGridColor.tooltip=Color for Equal-Distance Grid Lines. - -UTMGridPlugIn.distanceGridResolution.tooltip=Meter Resolution for Distance Grid Lines (0-5) - -UTMGridPlugIn.setLabelsButton=Show Zone Labels - -UTMGridPlugIn.utmGridColorButton=Set UTM Grid Color - -UTMGridPlugIn.setZonesButton=Show UTM Zone Grid - -UTMGridPlugIn.set100kGridButton=Show 100Km Distance Grid - -UTMGridPlugIn.resPanel=Distance Grid Units - -UTMGridPlugIn.distGridColorButton=Set Distance Grid Color - -UTMGridPlugIn.utmGridColorChooser=Choose UTM Grid Color - -UTMGridPlugIn.distanceGridColorChooser=Choose Distance Grid Color - -UTMGridPlugIn.resStrings.1m=\ 1 meter\ - -UTMGridPlugIn.resStrings.10m=\ 10 meter\ - -UTMGridPlugIn.resStrings.100m=\ 100 meter\ - -UTMGridPlugIn.resStrings.1000m=\ 1000 meter\ - -UTMGridPlugIn.resStrings.10000m=\ 10,000 meter\ \ \ - -UTMGridPlugIn.resStrings.noGrid=\ No Grid\ diff --git a/src/core/src/main/resources/com/bbn/openmap/plugin/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/plugin/I18N_pl_PL.properties deleted file mode 100644 index 9d42cc779..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/plugin/I18N_pl_PL.properties +++ /dev/null @@ -1,53 +0,0 @@ -# Sample ResourceBundle properties file - -UTMGridPlugIn.showLabels=Poka\u017C etykiety - -UTMGridPlugIn.showZones=Poka\u017C strefy - -UTMGridPlugIn.showLabels.tooltip=Poka\u017C etykiety dla lini siatki - -UTMGridPlugIn.showZones.tooltip=Poka\u017C linie stref czasowych UTM - -UTMGridPlugIn.show100KmGrid=Poka\u017C linie 100km - -UTMGridPlugIn.utmGridColor=Kolor linii - -UTMGridPlugIn.distanceGridColor=Kolor linii 100km - -UTMGridPlugIn.distanceGridResolution=Gesto\u015B\u0107 siatki - -UTMGridPlugIn.show100KmGrid.tooltip=Poka\u017C linie co 100km - -UTMGridPlugIn.utmGridColor.tooltip=Kolor linii dla stref czasowych UTM - -UTMGridPlugIn.distanceGridColor.tooltip=Kolor linii dla nak\u0142adaj\u0105cych sie element\u00F3w siatki. - -UTMGridPlugIn.distanceGridResolution.tooltip=Gesto\u015B\u0107 linii siatki dla 100km linii (0-5) - -UTMGridPlugIn.setLabelsButton=Poka\u017C etykiety stref - -UTMGridPlugIn.utmGridColorButton=Kolor linii - -UTMGridPlugIn.setZonesButton=Poka\u017C strefy - -UTMGridPlugIn.set100kGridButton=Poka\u017C linie 100km - -UTMGridPlugIn.resPanel=Odleg\u0142o\u015Bci linii - -UTMGridPlugIn.distGridColorButton=Kolor linii 100km - -UTMGridPlugIn.utmGridColorChooser=Wybierz kolor linii UTM - -UTMGridPlugIn.distanceGridColorChooser=Wybierz kolor - -UTMGridPlugIn.resStrings.1m=1 metr - -UTMGridPlugIn.resStrings.10m=10 metr\u00F3w - -UTMGridPlugIn.resStrings.100m=100 metr\u00F3w - -UTMGridPlugIn.resStrings.1000m=1000 metr\u00F3w - -UTMGridPlugIn.resStrings.10000m=10,000 mert\u00F3w - -UTMGridPlugIn.resStrings.noGrid=Brak siatki diff --git a/src/core/src/main/resources/com/bbn/openmap/proj/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/proj/I18N.properties deleted file mode 100644 index 32fa2b0de..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/proj/I18N.properties +++ /dev/null @@ -1,16 +0,0 @@ - -Length.miles.name=mile - -Length.feet.name=feet - -Length.m.name=meter - -Length.km.name=kilometer - -Length.nm.name=nautical mile - -Length.deg.name=decimal degree - -Length.rad.name=radian - -Length.dm.name=datamile diff --git a/src/core/src/main/resources/com/bbn/openmap/proj/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/proj/I18N_pl_PL.properties deleted file mode 100644 index 59cb7fa27..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/proj/I18N_pl_PL.properties +++ /dev/null @@ -1,15 +0,0 @@ -Length.miles.name=mile - -Length.feet.name=stopy - -Length.m.name=metry - -Length.km.name=kilometry - -Length.nm.name=mile morskie - -Length.deg.name=stopnie - -Length.rad.name=radiany - -Length.dm.name=mile zwyk\u0142e (datamile) diff --git a/src/core/src/main/resources/com/bbn/openmap/proj/ellips.dat b/src/core/src/main/resources/com/bbn/openmap/proj/ellips.dat deleted file mode 100644 index 190c26ac2..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/proj/ellips.dat +++ /dev/null @@ -1,27 +0,0 @@ -# Common Ellipsoids -# Datum derived from file from US Army Corps of Engineers Topographic -# Engineering Center (TEC). www.tec.army.mil - -Airy AA 10 6377563.396 6356256.9090 299.3249646 -Modified Airy AM 11 6377340.189 6356034.4480 299.3249646 -Australian National AN 08 6378160 6356774.7190 298.25 -Bessel 1841 BR 05 6377397.155 6356078.9630 299.1528128 -Bessel 1841(Namibia) BN 16 6377483.865 6356165.383 299.1528128 -Clarke 1866 CC 01 6378206.4 6356583.800 294.9786982 -Clarke 1880 CD 03 6378249.145 6356514.870 293.465 -Everest EA 04 6377276.345 6356075.413 300.8017 -Everest (E. Malasia, Brunei) EB 27 6377298.556 6356097.55 300.8017 -Everest 1956 (India) EC 29 6377301.243 6356100.228 300.8017 -Everest 1969 (West Malasia) ED 12 6377295.664 6356094.668 300.8017 -Everest 1948(W.Mals. & Sing.) EE 30 6377304.063 6356103.039 300.8017 -Everest (Pakistan) EF 28 6377309.613 6356109.571 300.8017 -Mod. Fischer 1960(South Asia) FA 18 6378155 6356773.320 298.3 -GRS 80 RF 21 6378137 6356752.3141 298.257222101 -Helmert 1906 HE 22 6378200 6356818.170 298.3 -Hough HO 14 6378270 6356794.343 297 -Indonesian 1974 ID 31 6378160 6356774.504 298.247 -International IN 02 6378388 6356911.946 297 -Krassovsky KA 23 6378245 6356863.019 298.3 -South American 1969 SA 24 6378160 6356774.719 298.25 -WGS 72 WD 13 6378135 6356750.520 298.26 -WGS 84 WE 09 6378137 6356752.3142 298.257223563 diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/beanbox/bluebean.gif b/src/core/src/main/resources/com/bbn/openmap/tools/beanbox/bluebean.gif deleted file mode 100644 index 7263b47c1..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/beanbox/bluebean.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/Drawing.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/Drawing.gif deleted file mode 100644 index cf4fd1969..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/Drawing.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N.properties b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N.properties deleted file mode 100644 index e70d6c087..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N.properties +++ /dev/null @@ -1,60 +0,0 @@ - -OMDrawingToolLauncher.drawingToolButton.tooltip=Drawing Tool Launcher - -OMDrawingToolLauncher.panelSendTo=Send To: - -OMDrawingToolLauncher.panelGraphicType=Graphic Type: - -OMDrawingToolLauncher.panelGraphicAttributes=Graphic Attributes: - -OMDrawingToolLauncher.panelRenderingType=Rendering Type: - -OMDrawingToolLauncher.dismiss=Close - -OMDrawingToolLauncher.createButton=Create Graphic - -OMDrawingToolLauncher.renderingType.LatLon=Lat/Lon - -OMDrawingToolLauncher.renderingType.XY=XY - -OMDrawingToolLauncher.renderingType.XYOffset=XY Offset - -OMDrawingToolLauncher.omdrawingtoollauncher=Drawing Tool Launcher - -OMDrawingToolLauncher.noValidChoice=\ \ \ No valid choice of graphic to create.\n - -OMDrawingToolLauncher.noDrowingTool=\ \ \ No drawing tool is available!\n - -OMDrawingToolLauncher.noValidReceiver=\ \ \ No valid receiver for the created graphic.\n - -OMDrawingToolLauncher.problem=Problem - -OMDrawingToolLauncher.problemCreatingGraphic=Problem creating new graphic:\n - -OMDrawingToolLauncher.panelLineColorTypes=Line/Colors: - -OMCircleLoader.omcircle.rings=Range Rings - -OMCircleLoader.omcircle.circle=Circle - -OMDecoratedSplineLoader.omdecortedspline=Decorated Splines - -OMDrawingTool.drawingtool=Drawing Tool - -OMLineLoader.omline=Line - -OMPointLoader.ompoint=Point - -OMPolyLoader.ompoly=Polygons/Polylines - -OMRectLoader.omrect=Rectangle - -OMSplineLoader.omspline=Splines - -OMTextLoader.omtext=Text - -OMDistanceLoader.omdistance=Distance - -OMDrawingTool.popupMenuDelete=Delete - -OMDrawingTool.popupMenuChangeAppearance=Change Appearance diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N_pl_PL.properties b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N_pl_PL.properties deleted file mode 100644 index 1305048c7..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/I18N_pl_PL.properties +++ /dev/null @@ -1,60 +0,0 @@ - -OMDrawingToolLauncher.drawingToolButton.tooltip=Edytor warstwy - -OMDrawingToolLauncher.panelSendTo=Zapisz w: - -OMDrawingToolLauncher.panelGraphicType=Rodzaj obiektu: - -OMDrawingToolLauncher.panelGraphicAttributes=Atrybuty: - -OMDrawingToolLauncher.panelRenderingType=Rodzaj pozycjonowania: - -OMDrawingToolLauncher.dismiss=Schowaj - -OMDrawingToolLauncher.createButton=Utw\u00F3rz obiekt - -OMDrawingToolLauncher.renderingType.LatLon=Szeroko\u015B\u0107/D\u0142ugo\u015B\u0107 - -OMDrawingToolLauncher.renderingType.XY=XY - -OMDrawingToolLauncher.renderingType.XYOffset=XY przesuni\u0119cie - -OMDrawingToolLauncher.omdrawingtoollauncher=Edytor warstwy - -OMDrawingToolLauncher.noValidChoice=\ \ \ Niepoprawny wyb\u00F3r grfiki do stworzenia.\n - -OMDrawingToolLauncher.noDrowingTool=\ \ \ Brak dost\u0119pnych narz\u0119dzi do rysowania!\n - -OMDrawingToolLauncher.noValidReceiver=\ \ \ Brak odpowiedniego odbiorcy dla stworzonego rysunku.\n - -OMDrawingToolLauncher.problem=Problem - -OMDrawingToolLauncher.problemCreatingGraphic=Wyst\u0105pi\u0142 problem przy tworzeniau rysunku:\n - -OMDrawingToolLauncher.panelLineColorTypes=Typ linii oraz kolor: - -OMCircleLoader.omcircle.rings=Pier\u015Bcienie - -OMCircleLoader.omcircle.circle=Ko\u0142o - -OMDecoratedSplineLoader.omdecortedspline=Decorated splines - -OMDrawingTool.drawingtool=Rysowanie - -OMLineLoader.omline=Linia - -OMPointLoader.ompoint=Punkt - -OMPolyLoader.ompoly=Wielok\u0105ty / linie \u0142amane - -OMRectLoader.omrect=Prostok\u0105t - -OMSplineLoader.omspline=Linia krzywa - -OMTextLoader.omtext=Tekst - -OMDistanceLoader.omdistance=Odleg\u0142o\u015B\u0107 - -OMDrawingTool.popupMenuDelete=Usu\u0144 - -OMDrawingTool.popupMenuChangeAppearance=Zmie\u0144 wygl\u0105d ... diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/distance.png b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/distance.png deleted file mode 100644 index 21649df24..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/distance.png and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablecircle.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablecircle.gif deleted file mode 100644 index 08441083a..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablecircle.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editableline.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editableline.gif deleted file mode 100644 index 76fe60976..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editableline.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoint.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoint.gif deleted file mode 100644 index 066fe2668..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoint.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoly.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoly.gif deleted file mode 100644 index b51f12dad..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablepoly.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerangering.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerangering.gif deleted file mode 100644 index 2c164c515..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerangering.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerect.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerect.gif deleted file mode 100644 index 53dd2e25f..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablerect.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablescalingraster.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablescalingraster.gif deleted file mode 100644 index 2e1dcdff2..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablescalingraster.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablespline.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablespline.gif deleted file mode 100644 index 2b5c0aa25..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editablespline.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editabletext.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editabletext.gif deleted file mode 100644 index cad360303..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/editabletext.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/launcher.gif b/src/core/src/main/resources/com/bbn/openmap/tools/drawing/launcher.gif deleted file mode 100644 index fe0de9d20..000000000 Binary files a/src/core/src/main/resources/com/bbn/openmap/tools/drawing/launcher.gif and /dev/null differ diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/hierarchy.properties b/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/hierarchy.properties deleted file mode 100644 index e92823a58..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/hierarchy.properties +++ /dev/null @@ -1,2692 +0,0 @@ -########################################### -#HEIRARCHY NUMBER=2525_CODE -#2525_CODE.name=PRETTYNAME -#2525_CODE.iconFile=CGM file location -########################################### - -1.X=S*X*------***** -S*X*------*****.name=UNKNOWN/UNKNOWN -1.X.1=S*P*------***** -S*P*------*****.name=SPACE TRACK -1.X.1.1=S*P*S-----***** -S*P*S-----*****.name=SATELLITE -1.X.1.2=S*P*V-----***** -S*P*V-----*****.name=CREWED SPACE VEHICLE -1.X.1.3=S*P*T-----***** -S*P*T-----*****.name=SPACE STATION -1.X.2=S*A*------***** -S*A*------*****.name=AIR TRACK -1.X.2.1=S*A*M-----***** -S*A*M-----*****.name=MILITARY -1.X.2.1.1=S*A*MF----***** -S*A*MF----*****.name=FIXED WING -1.X.2.1.1.1=S*A*MFB---***** -S*A*MFB---*****.name=BOMBER -1.X.2.1.1.2=S*A*MFF---***** -S*A*MFF---*****.name=FIGHTER -1.X.2.1.1.2.1=S*A*MFFI--***** -S*A*MFFI--*****.name=INTERCEPTOR -1.X.2.1.1.3=S*A*MFT---***** -S*A*MFT---*****.name=TRAINER -1.X.2.1.1.4=S*A*MFA---***** -S*A*MFA---*****.name=ATTACK/STRIKE -1.X.2.1.1.5=S*A*MFL---***** -S*A*MFL---*****.name=VSTOL -1.X.2.1.1.6=S*A*MFK---***** -S*A*MFK---*****.name=TANKER -1.X.2.1.1.7=S*A*MFC---***** -S*A*MFC---*****.name=CARGO AIRLIFT (TRANSPORT) -1.X.2.1.1.7.1=S*A*MFCL--***** -S*A*MFCL--*****.name=CARGO AIRLIFT (LIGHT) -1.X.2.1.1.7.2=S*A*MFCM--***** -S*A*MFCM--*****.name=CARGO AIRLIFT (MEDIUM) -1.X.2.1.1.7.3=S*A*MFCH--***** -S*A*MFCH--*****.name=CARGO AIRLIFT (HEAVY) -1.X.2.1.1.8=S*A*MFJ---***** -S*A*MFJ---*****.name=ELECTRONIC COUNTERMEASURES (ECM/JAMMER) -1.X.2.1.1.9=S*A*MFO---***** -S*A*MFO---*****.name=MEDEVAC -1.X.2.1.1.10=S*A*MFR---***** -S*A*MFR---*****.name=RECONNAISSANCE -1.X.2.1.1.10.1=S*A*MFRW--***** -S*A*MFRW--*****.name=AIRBORNE EARLY WARNING (AEW) -1.X.2.1.1.10.2=S*A*MFRZ--***** -S*A*MFRZ--*****.name=ELECTRONIC SURVEILLANCE MEASURES -1.X.2.1.1.10.3=S*A*MFRX--***** -S*A*MFRX--*****.name=PHOTOGRAPHIC -1.X.2.1.1.11=S*A*MFP---***** -S*A*MFP---*****.name=PATROL -1.X.2.1.1.11.1=S*A*MFPN--***** -S*A*MFPN--*****.name=ANTISURFACE WARFARE/ASUW -1.X.2.1.1.11.2=S*A*MFPM--***** -S*A*MFPM--*****.name=MINE COUNTERMEASURES -1.X.2.1.1.12=S*A*MFU---***** -S*A*MFU---*****.name=UTILITY -1.X.2.1.1.12.1=S*A*MFUL--***** -S*A*MFUL--*****.name=UTILITY (LIGHT) -1.X.2.1.1.12.2=S*A*MFUM--***** -S*A*MFUM--*****.name=UTILITY (MEDIUM) -1.X.2.1.1.12.3=S*A*MFUH--***** -S*A*MFUH--*****.name=UTILITY (HEAVY) -1.X.2.1.1.13=S*A*MFY---***** -S*A*MFY---*****.name=COMMUNICATIONS (C3I) -1.X.2.1.1.14=S*A*MFH---***** -S*A*MFH---*****.name=COMBAT SEARCH AND RESCUE (CSAR) -1.X.2.1.1.15=S*A*MFD---***** -S*A*MFD---*****.name=AIRBORNE COMMAND POST (C2) -1.X.2.1.1.16=S*A*MFQ---***** -S*A*MFQ---*****.name=DRONE (RPV/UAV) -1.X.2.1.1.17=S*A*MFS---***** -S*A*MFS---*****.name=ANTISUBMARINE WARFARE (ASW) CARRIER BASED -1.X.2.1.1.18=S*A*MFM---***** -S*A*MFM---*****.name=SPECIAL OPERATIONS FORCES (SOF) -1.X.2.1.2=S*A*MH----***** -S*A*MH----*****.name=ROTARY WING -1.X.2.1.2.1=S*A*MHA---***** -S*A*MHA---*****.name=ATTACK -1.X.2.1.2.2=S*A*MHS---***** -S*A*MHS---*****.name=ANTISUBMARINE WARFARE/MPA -1.X.2.1.2.3=S*A*MHU---***** -S*A*MHU---*****.name=UTILITY -1.X.2.1.2.3.1=S*A*MHUL--***** -S*A*MHUL--*****.name=UTILITY (LIGHT) -1.X.2.1.2.3.2=S*A*MHUM--***** -S*A*MHUM--*****.name=UTILITY (MEDIUM) -1.X.2.1.2.3.3=S*A*MHUH--***** -S*A*MHUH--*****.name=UTILITY (HEAVY) -1.X.2.1.2.4=S*A*MHI---***** -S*A*MHI---*****.name=MINE COUNTERMEASURES -1.X.2.1.2.5=S*A*MHH---***** -S*A*MHH---*****.name=COMBAT SEARCH AND RESCUE (CSAR) -1.X.2.1.2.6=S*A*MHR---***** -S*A*MHR---*****.name=RECONNAISSANCE -1.X.2.1.2.7=S*A*MHQ---***** -S*A*MHQ---*****.name=DRONE (RPV/UAV) -1.X.2.1.2.8=S*A*MHC---***** -S*A*MHC---*****.name=CARGO AIRLIFT (TRANSPORT) -1.X.2.1.2.8.1=S*A*MHCL--***** -S*A*MHCL--*****.name=CARGO AIRLIFT (LIGHT) -1.X.2.1.2.8.2=S*A*MHCM--***** -S*A*MHCM--*****.name=CARGO AIRLIFT (MEDIUM) -1.X.2.1.2.8.3=S*A*MHCH--***** -S*A*MHCH--*****.name=CARGO AIRLIFT (HEAVY) -1.X.2.1.2.9=S*A*MHT---***** -S*A*MHT---*****.name=TRAINER -1.X.2.1.2.10=S*A*MHO---***** -S*A*MHO---*****.name=MEDEVAC -1.X.2.1.2.11=S*A*MHM---***** -S*A*MHM---*****.name=SPECIAL OPERATIONS FORCES (SOF) -1.X.2.1.2.12=S*A*MHD---***** -S*A*MHD---*****.name=AIRBORNE COMMAND POST (C2) -1.X.2.1.2.13=S*A*MHK---***** -S*A*MHK---*****.name=TANKER -1.X.2.1.2.14=S*A*MHJ---***** -S*A*MHJ---*****.name=ELECTRONIC COUNTERMEASURES (ECM/JAMMER) -1.X.2.1.3=S*A*ML----***** -S*A*ML----*****.name=LIGHTER THAN AIR -1.X.2.2=S*A*W-----***** -S*A*W-----*****.name=WEAPON -1.X.2.2.1=S*A*WM----***** -S*A*WM----*****.name=MISSILE IN FLIGHT -1.X.2.2.1.1=S*A*WMS---***** -S*A*WMS---*****.name=SURFACE/LAND LAUNCHED MISSILE -1.X.2.2.1.1.1=S*A*WMSS--***** -S*A*WMSS--*****.name=SURFACE TO SURFACE MISSILE (SSM) -1.X.2.2.1.1.2=S*A*WMSA--***** -S*A*WMSA--*****.name=SURFACE TO AIR MISSILE (SAM) -1.X.2.2.1.2=S*A*WMA---***** -S*A*WMA---*****.name=AIR LAUNCHED MISSILE -1.X.2.2.1.2.1=S*A*WMAS--***** -S*A*WMAS--*****.name=AIR TO SURFACE MISSILE (ASM) -1.X.2.2.1.2.2=S*A*WMAA--***** -S*A*WMAA--*****.name=AIR TO AIR MISSILE (AAM) -1.X.2.2.1.3=S*A*WMU---***** -S*A*WMU---*****.name=SUBSURFACE TO SURFACE MISSILE (S/SSM) -1.X.2.2.1.4=S*A*WML---***** -S*A*WML---*****.name=LAND ATTACK MISSILE -1.X.2.2.2=S*A*WD----***** -S*A*WD----*****.name=DECOY -1.X.2.3=S*A*C-----***** -S*A*C-----*****.name=CIVIL AIRCRAFT -1.X.2.3.1=S*A*CF----***** -S*A*CF----*****.name=FIXED WING -1.X.2.3.2=S*A*CH----***** -S*A*CH----*****.name=ROTARY WING -1.X.2.3.3=S*A*CL----***** -S*A*CL----*****.name=LIGHTER THAN AIR -1.X.3=S*G*------***** -S*G*------*****.name=GROUND TRACK -1.X.3.1=S*G*U-----***** -S*G*U-----*****.name=UNIT -1.X.3.1.1=S*G*UC----***** -S*G*UC----*****.name=COMBAT -1.X.3.1.1.1=S*G*UCD---***** -S*G*UCD---*****.name=AIR DEFENSE -1.X.3.1.1.1.1=S*G*UCDS--***** -S*G*UCDS--*****.name=SHORT RANGE -1.X.3.1.1.1.1.1=S*G*UCDSC-***** -S*G*UCDSC-*****.name=CHAPARRAL -1.X.3.1.1.1.1.2=S*G*UCDSS-***** -S*G*UCDSS-*****.name=STINGER -1.X.3.1.1.1.1.3=S*G*UCDSV-***** -S*G*UCDSV-*****.name=VULCAN -1.X.3.1.1.1.2=S*G*UCDM--***** -S*G*UCDM--*****.name=AIR DEFENSE MISSILE -1.X.3.1.1.1.2.1=S*G*UCDML-***** -S*G*UCDML-*****.name=AIR DEFENSE MISSILE LIGHT -1.X.3.1.1.1.2.1.1=S*G*UCDMLA***** -S*G*UCDMLA*****.name=AIR DEFENSE MISSILE MOTORIZED (AVENGER) -1.X.3.1.1.1.2.2=S*G*UCDMM-***** -S*G*UCDMM-*****.name=AIR DEFENSE MISSILE MEDIUM -1.X.3.1.1.1.2.3=S*G*UCDMH-***** -S*G*UCDMH-*****.name=AIR DEFENSE MISSILE HEAVY -1.X.3.1.1.1.2.4=S*G*UCDH--***** -S*G*UCDH--*****.name=H/MAD -1.X.3.1.1.1.2.4.1=S*G*UCDHH-***** -S*G*UCDHH-*****.name=HAWK -1.X.3.1.1.1.2.4.2=S*G*UCDHP-***** -S*G*UCDHP-*****.name=PATRIOT -1.X.3.1.1.1.3=S*G*UCDG--***** -S*G*UCDG--*****.name=GUN UNIT -1.X.3.1.1.1.4=S*G*UCDC--***** -S*G*UCDC--*****.name=COMPOSITE -1.X.3.1.1.1.5=S*G*UCDT--***** -S*G*UCDT--*****.name=TARGETING UNIT -1.X.3.1.1.1.6=S*G*UCDO--***** -S*G*UCDO--*****.name=THEATER MISSILE DEFENSE UNIT -1.X.3.1.1.2=S*G*UCA---***** -S*G*UCA---*****.name=ARMOR -1.X.3.1.1.2.1=S*G*UCAT--***** -S*G*UCAT--*****.name=ARMOR TRACK -1.X.3.1.1.2.1.1=S*G*UCATA-***** -S*G*UCATA-*****.name=ARMOR TRACK AIRBORNE -1.X.3.1.1.2.1.2=S*G*UCATW-***** -S*G*UCATW-*****.name=ARMOR TRACK AMPHIBIOUS -1.X.3.1.1.2.1.2.1=S*G*UCATWR***** -S*G*UCATWR*****.name=ARMOR TRACK AMPHIBIOUS RECOVERY -1.X.3.1.1.2.1.3=S*G*UCATL-***** -S*G*UCATL-*****.name=ARMOR TRACK, LIGHT -1.X.3.1.1.2.1.4=S*G*UCATM-***** -S*G*UCATM-*****.name=ARMOR TRACK, MEDIUM -1.X.3.1.1.2.1.5=S*G*UCATH-***** -S*G*UCATH-*****.name=ARMOR TRACK, HEAVY -1.X.3.1.1.2.1.6=S*G*UCATR-***** -S*G*UCATR-*****.name=ARMOR TRACK, RECOVERY -1.X.3.1.1.2.2=S*G*UCAW--***** -S*G*UCAW--*****.name=ARMOR, WHEELED -1.X.3.1.1.2.2.1=S*G*UCAWS-***** -S*G*UCAWS-*****.name=ARMOR, WHEELED AIR ASSAULT -1.X.3.1.1.2.2.2=S*G*UCAWA-***** -S*G*UCAWA-*****.name=ARMOR, WHEELED AIRBORNE -1.X.3.1.1.2.2.3=S*G*UCAWW-***** -S*G*UCAWW-*****.name=ARMOR, WHEELED AMPHIBIOUS -1.X.3.1.1.2.2.3.1=S*G*UCAWWR***** -S*G*UCAWWR*****.name=ARMOR, WHEELED AMPHIBIOUS RECOVERY -1.X.3.1.1.2.2.4=S*G*UCAWL-***** -S*G*UCAWL-*****.name=ARMOR, WHEELED LIGHT -1.X.3.1.1.2.2.5=S*G*UCAWM-***** -S*G*UCAWM-*****.name=ARMOR, WHEELED MEDIUM -1.X.3.1.1.2.2.6=S*G*UCAWH-***** -S*G*UCAWH-*****.name=ARMOR, WHEELED HEAVY -1.X.3.1.1.2.2.7=S*G*UCAWR-***** -S*G*UCAWR-*****.name=ARMOR, WHEELED RECOVERY -1.X.3.1.1.3=S*G*UCAA--***** -S*G*UCAA--*****.name=ANTI ARMOR -1.X.3.1.1.3.1=S*G*UCAAD-***** -S*G*UCAAD-*****.name=ANTI ARMOR DISMOUNTED -1.X.3.1.1.3.2=S*G*UCAAL-***** -S*G*UCAAL-*****.name=ANTI ARMOR LIGHT -1.X.3.1.1.3.3=S*G*UCAAM-***** -S*G*UCAAM-*****.name=ANTI ARMOR AIRBORNE -1.X.3.1.1.3.4=S*G*UCAAS-***** -S*G*UCAAS-*****.name=ANTI ARMOR AIR ASSAULT -1.X.3.1.1.3.5=S*G*UCAAU-***** -S*G*UCAAU-*****.name=ANTI ARMOR MOUNTAIN -1.X.3.1.1.3.6=S*G*UCAAC-***** -S*G*UCAAC-*****.name=ANTI ARMOR ARCTIC -1.X.3.1.1.3.7=S*G*UCAAA-***** -S*G*UCAAA-*****.name=ANTI ARMOR ARMORED -1.X.3.1.1.3.7.1=S*G*UCAAAT***** -S*G*UCAAAT*****.name=ANTI ARMOR ARMORED TRACKED -1.X.3.1.1.3.7.2=S*G*UCAAAW***** -S*G*UCAAAW*****.name=ANTI ARMOR ARMORED WHEELED -1.X.3.1.1.3.7.3=S*G*UCAAAS***** -S*G*UCAAAS*****.name=ANTI ARMOR ARMORED AIR ASSAULT -1.X.3.1.1.3.8=S*G*UCAAO-***** -S*G*UCAAO-*****.name=ANTI ARMOR MOTORIZED -1.X.3.1.1.3.8.1=S*G*UCAAOS***** -S*G*UCAAOS*****.name=ANTI ARMOR MOTORIZED AIR ASSAULT -1.X.3.1.1.4=S*G*UCV---***** -S*G*UCV---*****.name=AVIATION -1.X.3.1.1.4.1=S*G*UCVF--***** -S*G*UCVF--*****.name=FIXED WING -1.X.3.1.1.4.1.1=S*G*UCVFU-***** -S*G*UCVFU-*****.name=UTILITY FIXED WING -1.X.3.1.1.4.1.2=S*G*UCVFA-***** -S*G*UCVFA-*****.name=ATTACK FIXED WING -1.X.3.1.1.4.1.3=S*G*UCVFR-***** -S*G*UCVFR-*****.name=RECON FIXED WING -1.X.3.1.1.4.2=S*G*UCVR--***** -S*G*UCVR--*****.name=ROTARY WING -1.X.3.1.1.4.2.1=S*G*UCVRA-***** -S*G*UCVRA-*****.name=ATTACK ROTARY WING -1.X.3.1.1.4.2.2=S*G*UCVRS-***** -S*G*UCVRS-*****.name=SCOUT ROTARY WING -1.X.3.1.1.4.2.3=S*G*UCVRW-***** -S*G*UCVRW-*****.name=ANTISUBMARINE WARFARE ROTARY WIN -1.X.3.1.1.4.2.4=S*G*UCVRU-***** -S*G*UCVRU-*****.name=UTILITY ROTARY WING -1.X.3.1.1.4.2.4.1=S*G*UCVRUL***** -S*G*UCVRUL*****.name=LIGHT UTILITY ROTARY WING -1.X.3.1.1.4.2.4.2=S*G*UCVRUM***** -S*G*UCVRUM*****.name=MEDIUM UTILITY ROTARY WING -1.X.3.1.1.4.2.4.3=S*G*UCVRUH***** -S*G*UCVRUH*****.name=HEAVY UTILITY ROTARY WING -1.X.3.1.1.4.2.5=S*G*UCVRUC***** -S*G*UCVRUC*****.name=C2 ROTARY WING -1.X.3.1.1.4.2.6=S*G*UCVRUE***** -S*G*UCVRUE*****.name=MEDEVAC ROTARY WING -1.X.3.1.1.4.2.7=S*G*UCVRM-***** -S*G*UCVRM-*****.name=MINE COUNTERMEASURE ROTARY WING -1.X.3.1.1.4.3=S*G*UCVS--***** -S*G*UCVS--*****.name=SEARCH AND RESCUE -1.X.3.1.1.4.4=S*G*UCVC--***** -S*G*UCVC--*****.name=COMPOSITE -1.X.3.1.1.4.5=S*G*UCVV--***** -S*G*UCVV--*****.name=VERTICAL/SHORT TAKEOFF AND LANDING (V/STOL) -1.X.3.1.1.4.6=S*G*UCVU--***** -S*G*UCVU--*****.name=UNMANNED AERIAL VEHICLE -1.X.3.1.1.4.6.1=S*G*UCVUF-***** -S*G*UCVUF-*****.name=UNMANNED AERIAL VEHICLE FIXED WING -1.X.3.1.1.4.6.2=S*G*UCVUR-***** -S*G*UCVUR-*****.name=UNMANNED AERIAL VEHICLE ROTARY WING -1.X.3.1.1.5=S*G*UCI---***** -S*G*UCI---*****.name=INFANTRY -1.X.3.1.1.5.1=S*G*UCIL--***** -S*G*UCIL--*****.name=INFANTRY LIGHT -1.X.3.1.1.5.2=S*G*UCIM--***** -S*G*UCIM--*****.name=INFANTRY MOTORIZED -1.X.3.1.1.5.3=S*G*UCIO--***** -S*G*UCIO--*****.name=INFANTRY MOUNTAIN -1.X.3.1.1.5.4=S*G*UCIA--***** -S*G*UCIA--*****.name=INFANTRY AIRBORNE -1.X.3.1.1.5.5=S*G*UCIS--***** -S*G*UCIS--*****.name=INFANTRY AIR ASSAULT -1.X.3.1.1.5.6=S*G*UCIZ--***** -S*G*UCIZ--*****.name=INFANTRY MECHANIZED -1.X.3.1.1.5.7=S*G*UCIN--***** -S*G*UCIN--*****.name=INFANTRY NAVAL -1.X.3.1.1.5.8=S*G*UCII--***** -S*G*UCII--*****.name=INFANTRY FIGHTING VEHICLE -1.X.3.1.1.5.9=S*G*UCIC--***** -S*G*UCIC--*****.name=INFANTRY ARCTIC -1.X.3.1.1.6=S*G*UCE---***** -S*G*UCE---*****.name=ENGINEER -1.X.3.1.1.6.1=S*G*UCEC--***** -S*G*UCEC--*****.name=ENGINEER COMBAT -1.X.3.1.1.6.1.1=S*G*UCECS-***** -S*G*UCECS-*****.name=ENGINEER COMBAT AIR ASSAULT -1.X.3.1.1.6.1.2=S*G*UCECA-***** -S*G*UCECA-*****.name=ENGINEER COMBAT AIRBORNE -1.X.3.1.1.6.1.3=S*G*UCECC-***** -S*G*UCECC-*****.name=ENGINEER COMBAT ARCTIC -1.X.3.1.1.6.1.4=S*G*UCECL-***** -S*G*UCECL-*****.name=ENGINEER COMBAT LIGHT (SAPPER) -1.X.3.1.1.6.1.5=S*G*UCECM-***** -S*G*UCECM-*****.name=ENGINEER COMBAT MEDIUM -1.X.3.1.1.6.1.6=S*G*UCECH-***** -S*G*UCECH-*****.name=ENGINEER COMBAT HEAVY -1.X.3.1.1.6.1.7=S*G*UCECT-***** -S*G*UCECT-*****.name=ENGINEER COMBAT MECHANIZED (TRACK) -1.X.3.1.1.6.1.8=S*G*UCECW-***** -S*G*UCECW-*****.name=ENGINEER COMBAT MOTORIZED -1.X.3.1.1.6.1.9=S*G*UCECO-***** -S*G*UCECO-*****.name=ENGINEER COMBAT MOUNTAIN -1.X.3.1.1.6.1.10=S*G*UCECR-***** -S*G*UCECR-*****.name=ENGINEER COMBAT RECON -1.X.3.1.1.6.2=S*G*UCEN--***** -S*G*UCEN--*****.name=ENGINEER CONSTRUCTION -1.X.3.1.1.6.2.1=S*G*UCENN-***** -S*G*UCENN-*****.name=ENGINEER NAVAL CONSTRUCTION -1.X.3.1.1.7=S*G*UCF---***** -S*G*UCF---*****.name=FIELD ARTILLERY -1.X.3.1.1.7.1=S*G*UCFH--***** -S*G*UCFH--*****.name=HOWITZER/GUN -1.X.3.1.1.7.1.1=S*G*UCFHE-***** -S*G*UCFHE-*****.name=SELF-PROPELLED -1.X.3.1.1.7.1.2=S*G*UCFHS-***** -S*G*UCFHS-*****.name=AIR ASSAULT -1.X.3.1.1.7.1.3=S*G*UCFHA-***** -S*G*UCFHA-*****.name=AIRBORNE -1.X.3.1.1.7.1.4=S*G*UCFHC-***** -S*G*UCFHC-*****.name=ARCTIC -1.X.3.1.1.7.1.5=S*G*UCFHO-***** -S*G*UCFHO-*****.name=MOUNTAIN -1.X.3.1.1.7.1.6=S*G*UCFHL-***** -S*G*UCFHL-*****.name=LIGHT -1.X.3.1.1.7.1.7=S*G*UCFHM-***** -S*G*UCFHM-*****.name=MEDIUM -1.X.3.1.1.7.1.8=S*G*UCFHH-***** -S*G*UCFHH-*****.name=HEAVY -1.X.3.1.1.7.1.9=S*G*UCFHX-***** -S*G*UCFHX-*****.name=AMPHIBIOUS -1.X.3.1.1.7.2=S*G*UCFR--***** -S*G*UCFR--*****.name=ROCKET -1.X.3.1.1.7.2.1=S*G*UCFRS-***** -S*G*UCFRS-*****.name=SINGLE ROCKET LAUNCHER -1.X.3.1.1.7.2.1.1=S*G*UCFRSS***** -S*G*UCFRSS*****.name=SINGLE ROCKET SELF-PROPELLED -1.X.3.1.1.7.2.1.2=S*G*UCFRSR***** -S*G*UCFRSR*****.name=SINGLE ROCKET TRUCK -1.X.3.1.1.7.2.1.3=S*G*UCFRST***** -S*G*UCFRST*****.name=SINGLE ROCKET TOWED -1.X.3.1.1.7.2.2=S*G*UCFRM-***** -S*G*UCFRM-*****.name=MULTI ROCKET LAUNCHER -1.X.3.1.1.7.2.2.1=S*G*UCFRMS***** -S*G*UCFRMS*****.name=MULTI ROCKET SELF-PROPELLED -1.X.3.1.1.7.2.2.2=S*G*UCFRMR***** -S*G*UCFRMR*****.name=MULTI ROCKET TRUCK -1.X.3.1.1.7.2.2.3=S*G*UCFRMT***** -S*G*UCFRMT*****.name=MULTI ROCKET TOWED -1.X.3.1.1.7.3=S*G*UCFT--***** -S*G*UCFT--*****.name=TARGET ACQUISITION -1.X.3.1.1.7.3.1=S*G*UCFTR-***** -S*G*UCFTR-*****.name=RADAR -1.X.3.1.1.7.3.2=S*G*UCFTS-***** -S*G*UCFTS-*****.name=SOUND -1.X.3.1.1.7.3.3=S*G*UCFTF-***** -S*G*UCFTF-*****.name=FLASH (OPTICAL) -1.X.3.1.1.7.3.4=S*G*UCFTC-***** -S*G*UCFTC-*****.name=COLT/FIST -1.X.3.1.1.7.3.4.1=S*G*UCFTCD***** -S*G*UCFTCD*****.name=DISMOUNTED COLT/FIST -1.X.3.1.1.7.3.4.2=S*G*UCFTCM***** -S*G*UCFTCM*****.name=TRACKED COLT/FIST -1.X.3.1.1.7.3.5=S*G*UCFTA-***** -S*G*UCFTA-*****.name=ANGLICO -1.X.3.1.1.7.4=S*G*UCFM--***** -S*G*UCFM--*****.name=MORTAR -1.X.3.1.1.7.4.1=S*G*UCFMS-***** -S*G*UCFMS-*****.name=SELF-PROPELLED (SP) TRACKED MORTAR -1.X.3.1.1.7.4.2=S*G*UCFMW-***** -S*G*UCFMW-*****.name=SP WHEELED MORTAR -1.X.3.1.1.7.4.3=S*G*UCFMT-***** -S*G*UCFMT-*****.name=TOWED MORTAR -1.X.3.1.1.7.4.3.1=S*G*UCFMTA***** -S*G*UCFMTA*****.name=TOWED AIRBORNE MORTAR -1.X.3.1.1.7.4.3.2=S*G*UCFMTS***** -S*G*UCFMTS*****.name=TOWED AIR ASSAULT MORTAR -1.X.3.1.1.7.4.3.3=S*G*UCFMTC***** -S*G*UCFMTC*****.name=TOWED ARCTIC MORTAR -1.X.3.1.1.7.4.3.4=S*G*UCFMTO***** -S*G*UCFMTO*****.name=TOWED MOUNTAIN MORTAR -1.X.3.1.1.7.4.4=S*G*UCFML-***** -S*G*UCFML-*****.name=AMPHIBIOUS MORTAR -1.X.3.1.1.7.5=S*G*UCFS--***** -S*G*UCFS--*****.name=ARTILLERY SURVEY -1.X.3.1.1.7.5.1=S*G*UCFSS-***** -S*G*UCFSS-*****.name=AIR ASSAULT -1.X.3.1.1.7.5.2=S*G*UCFSA-***** -S*G*UCFSA-*****.name=AIRBORNE -1.X.3.1.1.7.5.3=S*G*UCFSL-***** -S*G*UCFSL-*****.name=LIGHT -1.X.3.1.1.7.5.4=S*G*UCFSO-***** -S*G*UCFSO-*****.name=MOUNTAIN -1.X.3.1.1.7.6=S*G*UCFO--***** -S*G*UCFO--*****.name=METEOROLOGICAL -1.X.3.1.1.7.6.1=S*G*UCFOS-***** -S*G*UCFOS-*****.name=AIR ASSAULT METEOROLOGICAL -1.X.3.1.1.7.6.2=S*G*UCFOA-***** -S*G*UCFOA-*****.name=AIRBORNE METEOROLOGICAL -1.X.3.1.1.7.6.3=S*G*UCFOL-***** -S*G*UCFOL-*****.name=LIGHT METEOROLOGICAL -1.X.3.1.1.7.6.4=S*G*UCFOO-***** -S*G*UCFOO-*****.name=MOUNTAIN METEOROLOGICAL -1.X.3.1.1.8=S*G*UCR---***** -S*G*UCR---*****.name=RECONNAISSANCE -1.X.3.1.1.8.1=S*G*UCRH--***** -S*G*UCRH--*****.name=RECONNAISSANCE HORSE -1.X.3.1.1.8.2=S*G*UCRV--***** -S*G*UCRV--*****.name=RECONNAISSANCE CAVALRY -1.X.3.1.1.8.2.1=S*G*UCRVA-***** -S*G*UCRVA-*****.name=RECONNAISSANCE CAVALRY ARMORED -1.X.3.1.1.8.2.2=S*G*UCRVM-***** -S*G*UCRVM-*****.name=RECONNAISSANCE CAVALRY MOTORIZED -1.X.3.1.1.8.2.3=S*G*UCRVG-***** -S*G*UCRVG-*****.name=RECONNAISSANCE CAVALRY GROUND -1.X.3.1.1.8.2.4=S*G*UCRVO-***** -S*G*UCRVO-*****.name=RECONNAISSANCE CAVALRY AIR -1.X.3.1.1.8.3=S*G*UCRC--***** -S*G*UCRC--*****.name=RECONNAISSANCE ARCTIC -1.X.3.1.1.8.4=S*G*UCRS--***** -S*G*UCRS--*****.name=RECONNAISSANCE AIR ASSAULT -1.X.3.1.1.8.5=S*G*UCRA--***** -S*G*UCRA--*****.name=RECONNAISSANCE AIRBORNE -1.X.3.1.1.8.6=S*G*UCRO--***** -S*G*UCRO--*****.name=RECONNAISSANCE MOUNTAIN -1.X.3.1.1.8.7=S*G*UCRL--***** -S*G*UCRL--*****.name=RECONNAISSANCE LIGHT -1.X.3.1.1.8.8=S*G*UCRR--***** -S*G*UCRR--*****.name=RECONNAISSANCE MARINE -1.X.3.1.1.8.8.1=S*G*UCRRD-***** -S*G*UCRRD-*****.name=RECONNAISSANCE MARINE DIVISION -1.X.3.1.1.8.8.2=S*G*UCRRF-***** -S*G*UCRRF-*****.name=RECONNAISSANCE MARINE FORCE -1.X.3.1.1.8.8.3=S*G*UCRRL-***** -S*G*UCRRL-*****.name=RECONNAISSANCE MARINE LIGHT ARMORED RECONNAISSNACE (LAR) -1.X.3.1.1.8.9=S*G*UCRX--***** -S*G*UCRX--*****.name=RECONNAISSANCE LONG RANGE SURVEILLANCE (LRS) -1.X.3.1.1.9=S*G*UCM---***** -S*G*UCM---*****.name=MISSILE (SURF-SURF) -1.X.3.1.1.9.1=S*G*UCMT--***** -S*G*UCMT--*****.name=MISSILE (SURF-SURF) TACTICAL -1.X.3.1.1.9.2=S*G*UCMS--***** -S*G*UCMS--*****.name=MISSILE (SURF-SURF) STRATEGIC -1.X.3.1.1.10=S*G*UCS---***** -S*G*UCS---*****.name=INTERNAL SECURITY FORCES -1.X.3.1.1.10.1=S*G*UCSW--***** -S*G*UCSW--*****.name=RIVERINE -1.X.3.1.1.10.2=S*G*UCSG--***** -S*G*UCSG--*****.name=GROUND -1.X.3.1.1.10.2.1=S*G*UCSGD-***** -S*G*UCSGD-*****.name=DISMOUNTED GROUND -1.X.3.1.1.10.2.2=S*G*UCSGM-***** -S*G*UCSGM-*****.name=MOTORIZED GROUND -1.X.3.1.1.10.2.3=S*G*UCSGA-***** -S*G*UCSGA-*****.name=MECHANIZED GROUND -1.X.3.1.1.10.3=S*G*UCSM--***** -S*G*UCSM--*****.name=WHEELED MECHANIZED -1.X.3.1.1.10.4=S*G*UCSR--***** -S*G*UCSR--*****.name=RAILROAD -1.X.3.1.1.10.5=S*G*UCSA--***** -S*G*UCSA--*****.name=AVIATION -1.X.3.1.2=S*G*UU----***** -S*G*UU----*****.name=COMBAT SUPPORT -1.X.3.1.2.1=S*G*UUA---***** -S*G*UUA---*****.name=COMBAT SUPPORT NBC -1.X.3.1.2.1.1=S*G*UUAC--***** -S*G*UUAC--*****.name=CHEMICAL -1.X.3.1.2.1.1.1=S*G*UUACC-***** -S*G*UUACC-*****.name=SMOKE/DECON -1.X.3.1.2.1.1.1.1=S*G*UUACCK***** -S*G*UUACCK*****.name=MECHANIZED SMOKE/DECON -1.X.3.1.2.1.1.1.2=S*G*UUACCM***** -S*G*UUACCM*****.name=MOTORIZED SMOKE/DECON -1.X.3.1.2.1.1.2=S*G*UUACS-***** -S*G*UUACS-*****.name=SMOKE -1.X.3.1.2.1.1.2.1=S*G*UUACSM***** -S*G*UUACSM*****.name=MOTORIZED SMOKE -1.X.3.1.2.1.1.2.2=S*G*UUACSA***** -S*G*UUACSA*****.name=ARMOR SMOKE -1.X.3.1.2.1.1.3=S*G*UUACR-***** -S*G*UUACR-*****.name=CHEMICAL RECON -1.X.3.1.2.1.1.3.1=S*G*UUACRW***** -S*G*UUACRW*****.name=CHEMICAL WHEELED ARMORED VEHICLE -1.X.3.1.2.1.1.3.2=S*G*UUACRS***** -S*G*UUACRS*****.name=CHEMICAL WHEELED ARMORED VEHICLE RECONNAISSANCE SURVEILLANCE -1.X.3.1.2.1.2=S*G*UUAN--***** -S*G*UUAN--*****.name=NUCLEAR -1.X.3.1.2.1.3=S*G*UUAB--***** -S*G*UUAB--*****.name=BIOLOGICAL -1.X.3.1.2.1.3.1=S*G*UUABR-***** -S*G*UUABR-*****.name=RECON EQUIPPED -1.X.3.1.2.1.4=S*G*UUAD--***** -S*G*UUAD--*****.name=DECONTAMINATION -1.X.3.1.2.2=S*G*UUM---***** -S*G*UUM---*****.name=MILITARY INTELLIGENCE -1.X.3.1.2.2.1=S*G*UUMA--***** -S*G*UUMA--*****.name=AERIAL EXPLOITATION -1.X.3.1.2.2.2=S*G*UUMS--***** -S*G*UUMS--*****.name=SIGNAL INTELLIGENCE (SIGINT) -1.X.3.1.2.2.2.1=S*G*UUMSE-***** -S*G*UUMSE-*****.name=ELECTRONIC WARFARE -1.X.3.1.2.2.2.1.1=S*G*UUMSEA***** -S*G*UUMSEA*****.name=ARMORED WHEELED VEHICLE -1.X.3.1.2.2.2.1.2=S*G*UUMSED***** -S*G*UUMSED*****.name=DIRECTION FINDING -1.X.3.1.2.2.2.1.3=S*G*UUMSEI***** -S*G*UUMSEI*****.name=INTERCEPT -1.X.3.1.2.2.2.1.4=S*G*UUMSEJ***** -S*G*UUMSEJ*****.name=JAMMING -1.X.3.1.2.2.2.1.5=S*G*UUMSET***** -S*G*UUMSET*****.name=THEATER -1.X.3.1.2.2.2.1.6=S*G*UUMSEC***** -S*G*UUMSEC*****.name=CORPS -1.X.3.1.2.2.3=S*G*UUMC--***** -S*G*UUMC--*****.name=COUNTER INTELLIGENCE -1.X.3.1.2.2.4=S*G*UUMR--***** -S*G*UUMR--*****.name=SURVEILLANCE -1.X.3.1.2.2.4.1=S*G*UUMRG-***** -S*G*UUMRG-*****.name=GROUND SURVEILLANCE RADAR -1.X.3.1.2.2.4.2=S*G*UUMRS-***** -S*G*UUMRS-*****.name=SENSOR -1.X.3.1.2.2.4.2.1=S*G*UUMRSS***** -S*G*UUMRSS*****.name=SENSOR SCM -1.X.3.1.2.2.4.3=S*G*UUMRX-***** -S*G*UUMRX-*****.name=GROUND STATION MODULE -1.X.3.1.2.2.4.4=S*G*UUMMO-***** -S*G*UUMMO-*****.name=METEOROLOGICAL -1.X.3.1.2.2.5=S*G*UUMO--***** -S*G*UUMO--*****.name=OPERATIONS -1.X.3.1.2.2.6=S*G*UUMT--***** -S*G*UUMT--*****.name=TACTICAL EXPLOIT -1.X.3.1.2.2.7=S*G*UUMQ--***** -S*G*UUMQ--*****.name=INTERROGATION -1.X.3.1.2.2.8=S*G*UUMJ--***** -S*G*UUMJ--*****.name=JOINT INTELLIGENCE CENTER -1.X.3.1.2.3=S*G*UUL---***** -S*G*UUL---*****.name=LAW ENFORCEMENT UNIT -1.X.3.1.2.3.1=S*G*UULS--***** -S*G*UULS--*****.name=SHORE PATROL -1.X.3.1.2.3.2=S*G*UULM--***** -S*G*UULM--*****.name=MILITARY POLICE -1.X.3.1.2.3.3=S*G*UULC--***** -S*G*UULC--*****.name=CIVILIAN LAW ENFORCEMENT -1.X.3.1.2.3.4=S*G*UULF--***** -S*G*UULF--*****.name=SECURITY POLICE (AIR) -1.X.3.1.2.3.5=S*G*UULD--***** -S*G*UULD--*****.name=CENTRAL INTELLIGENCE DIVISION (CID) -1.X.3.1.2.4=S*G*UUS---***** -S*G*UUS---*****.name=SIGNAL UNIT -1.X.3.1.2.4.1=S*G*UUSA--***** -S*G*UUSA--*****.name=AREA -1.X.3.1.2.4.2=S*G*UUSC--***** -S*G*UUSC--*****.name=COMMUNICATION CONFIGURED PACKAGE -1.X.3.1.2.4.2.1=S*G*UUSCL-***** -S*G*UUSCL-*****.name=LARGE COMMUNICATION CONFIGURED PACKAGE (LCCP) -1.X.3.1.2.4.3=S*G*UUSO--***** -S*G*UUSO--*****.name=COMMAND OPERATIONS -1.X.3.1.2.4.4=S*G*UUSF--***** -S*G*UUSF--*****.name=FORWARD COMMUNICATIONS -1.X.3.1.2.4.5=S*G*UUSM--***** -S*G*UUSM--*****.name=MULTIPLE SUBSCRIBER ELEMENT -1.X.3.1.2.4.5.1=S*G*UUSMS-***** -S*G*UUSMS-*****.name=SMALL EXTENSION NODE -1.X.3.1.2.4.5.2=S*G*UUSML-***** -S*G*UUSML-*****.name=LARGE EXTENSION NODE -1.X.3.1.2.4.5.3=S*G*UUSMN-***** -S*G*UUSMN-*****.name=NODE CENTER -1.X.3.1.2.4.6=S*G*UUSR--***** -S*G*UUSR--*****.name=RADIO UNIT -1.X.3.1.2.4.6.1=S*G*UUSRS-***** -S*G*UUSRS-*****.name=TACTICAL SATELLITE -1.X.3.1.2.4.6.2=S*G*UUSRT-***** -S*G*UUSRT-*****.name=TELETYPE CENTER -1.X.3.1.2.4.6.3=S*G*UUSRW-***** -S*G*UUSRW-*****.name=RELAY -1.X.3.1.2.4.7=S*G*UUSS--***** -S*G*UUSS--*****.name=SIGNAL SUPPORT -1.X.3.1.2.4.8=S*G*UUSW--***** -S*G*UUSW--*****.name=TELEPHONE SWITCH -1.X.3.1.2.4.9=S*G*UUSX--***** -S*G*UUSX--*****.name=ELECTRONIC RANGING -1.X.3.1.2.5=S*G*UUI---***** -S*G*UUI---*****.name=INFORMATION WARFARE UNIT -1.X.3.1.2.6=S*G*UUP---***** -S*G*UUP---*****.name=LANDING SUPPORT -1.X.3.1.2.7=S*G*UUE---***** -S*G*UUE---*****.name=EXPLOSIVE ORDINANCE DISPOSAL -1.X.3.1.3=S*G*US----***** -S*G*US----*****.name=COMBAT SERVICE SUPPORT -1.X.3.1.3.1=S*G*USA---***** -S*G*USA---*****.name=ADMINISTRATIVE (ADMIN) -1.X.3.1.3.1.1=S*G*USAT--***** -S*G*USAT--*****.name=ADMIN THEATER -1.X.3.1.3.1.2=S*G*USAC--***** -S*G*USAC--*****.name=ADMIN CORPS -1.X.3.1.3.1.3=S*G*USAJ--***** -S*G*USAJ--*****.name=JUDGE ADVOCATE GENERAL (JAG) -1.X.3.1.3.1.3.1=S*G*USAJT-***** -S*G*USAJT-*****.name=JAG THEATER -1.X.3.1.3.1.3.2=S*G*USAJC-***** -S*G*USAJC-*****.name=JAG CORPS -1.X.3.1.3.1.4=S*G*USAO--***** -S*G*USAO--*****.name=POSTAL -1.X.3.1.3.1.4.1=S*G*USAOT-***** -S*G*USAOT-*****.name=POSTAL THEATER -1.X.3.1.3.1.4.2=S*G*USAOC-***** -S*G*USAOC-*****.name=POSTAL CORPS -1.X.3.1.3.1.5=S*G*USAF--***** -S*G*USAF--*****.name=FINANCE -1.X.3.1.3.1.5.1=S*G*USAFT-***** -S*G*USAFT-*****.name=FINANCE THEATER -1.X.3.1.3.1.5.2=S*G*USAFC-***** -S*G*USAFC-*****.name=FINANCE CORPS -1.X.3.1.3.1.6=S*G*USAS--***** -S*G*USAS--*****.name=PERSONNEL SERVICES -1.X.3.1.3.1.6.1=S*G*USAST-***** -S*G*USAST-*****.name=PERSONNEL THEATER -1.X.3.1.3.1.6.2=S*G*USASC-***** -S*G*USASC-*****.name=PERSONNEL CORPS -1.X.3.1.3.1.7=S*G*USAM--***** -S*G*USAM--*****.name=MORTUARY/GRAVES REGISTRY -1.X.3.1.3.1.7.1=S*G*USAMT-***** -S*G*USAMT-*****.name=MORTUARY/GRAVES REGISTRY THEATER -1.X.3.1.3.1.7.2=S*G*USAMC-***** -S*G*USAMC-*****.name=MORTUARY/GRAVES REGISTRY CORPS -1.X.3.1.3.1.8=S*G*USAR--***** -S*G*USAR--*****.name=RELIGIOUS/CHAPLAIN -1.X.3.1.3.1.8.1=S*G*USART-***** -S*G*USART-*****.name=RELIGIOUS/CHAPLAIN THEATER -1.X.3.1.3.1.8.2=S*G*USARC-***** -S*G*USARC-*****.name=RELIGIOUS/CHAPLAIN CORPS -1.X.3.1.3.1.9=S*G*USAP--***** -S*G*USAP--*****.name=PUBLIC AFFAIRS -1.X.3.1.3.1.9.1=S*G*USAPT-***** -S*G*USAPT-*****.name=PUBLIC AFFAIRS THEATER -1.X.3.1.3.1.9.2=S*G*USAPC-***** -S*G*USAPC-*****.name=PUBLIC AFFAIRS CORPS -1.X.3.1.3.1.9.3=S*G*USAPB-***** -S*G*USAPB-*****.name=PUBLIC AFFAIRS BROADCAST -1.X.3.1.3.1.9.3.1=S*G*USAPBT***** -S*G*USAPBT*****.name=PUBLIC AFFAIRS BROADCAST THEATER -1.X.3.1.3.1.9.3.2=S*G*USAPBC***** -S*G*USAPBC*****.name=PUBLIC AFFAIRS BROADCAST CORPS -1.X.3.1.3.1.9.4=S*G*USAPM-***** -S*G*USAPM-*****.name=PUBLIC AFFAIRS JOINT INFORMATION BUREAU (JIB) -1.X.3.1.3.1.9.4.1=S*G*USAPMT***** -S*G*USAPMT*****.name=PUBLIC AFFAIRS JIB THEATER -1.X.3.1.3.1.9.4.2=S*G*USAPMC***** -S*G*USAPMC*****.name=PUBLIC AFFAIRS JIB CORPS -1.X.3.1.3.1.10=S*G*USAX--***** -S*G*USAX--*****.name=REPLACEMENT HOLDING UNIT (RHU) -1.X.3.1.3.1.10.1=S*G*USAXT-***** -S*G*USAXT-*****.name=RHU THEATER -1.X.3.1.3.1.10.2=S*G*USAXC-***** -S*G*USAXC-*****.name=RHU CORPS -1.X.3.1.3.1.11=S*G*USAL--***** -S*G*USAL--*****.name=LABOR -1.X.3.1.3.1.11.1=S*G*USALT-***** -S*G*USALT-*****.name=LABOR THEATER -1.X.3.1.3.1.11.2=S*G*USALC-***** -S*G*USALC-*****.name=LABOR CORPS -1.X.3.1.3.1.12=S*G*USAW--***** -S*G*USAW--*****.name=MORALE, WELFARE, RECREATION (MWR) -1.X.3.1.3.1.12.1=S*G*USAWT-***** -S*G*USAWT-*****.name=MWR THEATER -1.X.3.1.3.1.12.2=S*G*USAWC-***** -S*G*USAWC-*****.name=MWR CORPS -1.X.3.1.3.1.13=S*G*USAQ--***** -S*G*USAQ--*****.name=QUARTERMASTER (SUPPLY) -1.X.3.1.3.1.13.1=S*G*USAQT-***** -S*G*USAQT-*****.name=QUARTERMASTER (SUPPLY) THEATER -1.X.3.1.3.1.13.2=S*G*USAQC-***** -S*G*USAQC-*****.name=QUARTERMASTER (SUPPLY) CORPS -1.X.3.1.3.2=S*G*USM---***** -S*G*USM---*****.name=MEDICAL -1.X.3.1.3.2.1=S*G*USMT--***** -S*G*USMT--*****.name=MEDICAL THEATER -1.X.3.1.3.2.2=S*G*USMC--***** -S*G*USMC--*****.name=MEDICAL CORPS -1.X.3.1.3.2.3=S*G*USMM--***** -S*G*USMM--*****.name=MEDICAL TREATMENT FACILITY -1.X.3.1.3.2.3.1=S*G*USMMT-***** -S*G*USMMT-*****.name=MEDICAL TREATMENT FACILITY THEATER -1.X.3.1.3.2.3.2=S*G*USMMC-***** -S*G*USMMC-*****.name=MEDICAL TREATMENT FACILITY CORPS -1.X.3.1.3.2.4=S*G*USMV--***** -S*G*USMV--*****.name=MEDICAL VETERINARY -1.X.3.1.3.2.4.1=S*G*USMVT-***** -S*G*USMVT-*****.name=MEDICAL VETERINARY THEATER -1.X.3.1.3.2.4.2=S*G*USMVC-***** -S*G*USMVC-*****.name=MEDICAL VETERINARY CORPS -1.X.3.1.3.2.5=S*G*USMD--***** -S*G*USMD--*****.name=MEDICAL DENTAL -1.X.3.1.3.2.5.1=S*G*USMDT-***** -S*G*USMDT-*****.name=MEDICAL DENTAL THEATER -1.X.3.1.3.2.5.2=S*G*USMDC-***** -S*G*USMDC-*****.name=MEDICAL DENTAL CORPS -1.X.3.1.3.2.6=S*G*USMP--***** -S*G*USMP--*****.name=MEDICAL PSYCHOLOGICAL -1.X.3.1.3.2.6.1=S*G*USMPT-***** -S*G*USMPT-*****.name=MEDICAL PSYCHOLOGICAL THEATER -1.X.3.1.3.2.6.2=S*G*USMPC-***** -S*G*USMPC-*****.name=MEDICAL PSYCHOLOGICAL CORPS -1.X.3.1.3.3=S*G*USS---***** -S*G*USS---*****.name=SUPPLY -1.X.3.1.3.3.1=S*G*USST--***** -S*G*USST--*****.name=SUPPLY THEATER -1.X.3.1.3.3.2=S*G*USSC--***** -S*G*USSC--*****.name=SUPPLY CORPS -1.X.3.1.3.3.3=S*G*USS1--***** -S*G*USS1--*****.name=SUPPLY CLASS I -1.X.3.1.3.3.3.1=S*G*USS1T-***** -S*G*USS1T-*****.name=SUPPLY CLASS I THEATER -1.X.3.1.3.3.3.2=S*G*USS1C-***** -S*G*USS1C-*****.name=SUPPLY CLASS I CORPS -1.X.3.1.3.3.4=S*G*USS2--***** -S*G*USS2--*****.name=SUPPLY CLASS II -1.X.3.1.3.3.4.1=S*G*USS2T-***** -S*G*USS2T-*****.name=SUPPLY CLASS II THEATER -1.X.3.1.3.3.4.2=S*G*USS2C-***** -S*G*USS2C-*****.name=SUPPLY CLASS II CORPS -1.X.3.1.3.3.5=S*G*USS3--***** -S*G*USS3--*****.name=SUPPLY CLASS III -1.X.3.1.3.3.5.1=S*G*USS3T-***** -S*G*USS3T-*****.name=SUPPLY CLASS III THEATER -1.X.3.1.3.3.5.2=S*G*USS3C-***** -S*G*USS3C-*****.name=SUPPLY CLASS III CORPS -1.X.3.1.3.3.5.3=S*G*USS3A-***** -S*G*USS3A-*****.name=SUPPLY CLASS III AVIATION -1.X.3.1.3.3.5.3.1=S*G*USS3AT***** -S*G*USS3AT*****.name=SUPPLY CLASS III AVIATION THEATER -1.X.3.1.3.3.5.3.2=S*G*USS3AC***** -S*G*USS3AC*****.name=SUPPLY CLASS III AVIATION CORPS -1.X.3.1.3.3.6=S*G*USS4--***** -S*G*USS4--*****.name=SUPPLY CLASS IV -1.X.3.1.3.3.6.1=S*G*USS4T-***** -S*G*USS4T-*****.name=SUPPLY CLASS IV THEATER -1.X.3.1.3.3.6.2=S*G*USS4C-***** -S*G*USS4C-*****.name=SUPPLY CLASS IV CORPS -1.X.3.1.3.3.7=S*G*USS5--***** -S*G*USS5--*****.name=SUPPLY CLASS V -1.X.3.1.3.3.7.1=S*G*USS5T-***** -S*G*USS5T-*****.name=SUPPLY CLASS V THEATER -1.X.3.1.3.3.7.2=S*G*USS5C-***** -S*G*USS5C-*****.name=SUPPLY CLASS V CORPS -1.X.3.1.3.3.8=S*G*USS6--***** -S*G*USS6--*****.name=SUPPLY CLASS VI -1.X.3.1.3.3.8.1=S*G*USS6T-***** -S*G*USS6T-*****.name=SUPPLY CLASS VI THEATER -1.X.3.1.3.3.8.2=S*G*USS6C-***** -S*G*USS6C-*****.name=SUPPLY CLASS VI CORPS -1.X.3.1.3.3.9=S*G*USS7--***** -S*G*USS7--*****.name=SUPPLY CLASS VII -1.X.3.1.3.3.9.1=S*G*USS7T-***** -S*G*USS7T-*****.name=SUPPLY CLASS VII THEATER -1.X.3.1.3.3.9.2=S*G*USS7C-***** -S*G*USS7C-*****.name=SUPPLY CLASS VII CORPS -1.X.3.1.3.3.10=S*G*USS8--***** -S*G*USS8--*****.name=SUPPLY CLASS VIII -1.X.3.1.3.3.10.1=S*G*USS8T-***** -S*G*USS8T-*****.name=SUPPLY CLASS VIII THEATER -1.X.3.1.3.3.10.2=S*G*USS8C-***** -S*G*USS8C-*****.name=SUPPLY CLASS VIII CORPS -1.X.3.1.3.3.11=S*G*USS9--***** -S*G*USS9--*****.name=SUPPLY CLASS IX -1.X.3.1.3.3.11.1=S*G*USS9T-***** -S*G*USS9T-*****.name=SUPPLY CLASS IX THEATER -1.X.3.1.3.3.11.2=S*G*USS9C-***** -S*G*USS9C-*****.name=SUPPLY CLASS IX CORPS -1.X.3.1.3.3.12=S*G*USSX--***** -S*G*USSX--*****.name=SUPPLY CLASS X -1.X.3.1.3.3.12.1=S*G*USSXT-***** -S*G*USSXT-*****.name=SUPPLY CLASS X THEATER -1.X.3.1.3.3.12.2=S*G*USSXC-***** -S*G*USSXC-*****.name=SUPPLY CLASS X CORPS -1.X.3.1.3.3.13=S*G*USSL--***** -S*G*USSL--*****.name=SUPPLY LAUNDRY/BATH -1.X.3.1.3.3.13.1=S*G*USSLT-***** -S*G*USSLT-*****.name=SUPPLY LAUNDRY/BATH THEATER -1.X.3.1.3.3.13.2=S*G*USSLC-***** -S*G*USSLC-*****.name=SUPPLY LAUNDRY/BATH CORPS -1.X.3.1.3.3.14=S*G*USSW--***** -S*G*USSW--*****.name=SUPPLY WATER -1.X.3.1.3.3.14.1=S*G*USSWT-***** -S*G*USSWT-*****.name=SUPPLY WATER THEATER -1.X.3.1.3.3.14.2=S*G*USSWC-***** -S*G*USSWC-*****.name=SUPPLY WATER CORPS -1.X.3.1.3.3.14.3=S*G*USSWP-***** -S*G*USSWP-*****.name=SUPPLY WATER PURIFICATION -1.X.3.1.3.3.14.3.1=S*G*USSWPT***** -S*G*USSWPT*****.name=SUPPLY WATER PURIFICATION THEATER -1.X.3.1.3.3.14.3.2=S*G*USSWPC***** -S*G*USSWPC*****.name=SUPPLY WATER PURIFICATION CORPS -1.X.3.1.3.4=S*G*UST---***** -S*G*UST---*****.name=TRANSPORTATION -1.X.3.1.3.4.1=S*G*USTT--***** -S*G*USTT--*****.name=TRANSPORTATION THEATER -1.X.3.1.3.4.2=S*G*USTC--***** -S*G*USTC--*****.name=TRANSPORTATION CORPS -1.X.3.1.3.4.3=S*G*USTM--***** -S*G*USTM--*****.name=MOVEMENT CONTROL CENTER(MCC) -1.X.3.1.3.4.3.1=S*G*USTMT-***** -S*G*USTMT-*****.name=MCC THEATER -1.X.3.1.3.4.3.2=S*G*USTMC-***** -S*G*USTMC-*****.name=MCC CORPS -1.X.3.1.3.4.4=S*G*USTR--***** -S*G*USTR--*****.name=RAILHEAD -1.X.3.1.3.4.4.1=S*G*USTRT-***** -S*G*USTRT-*****.name=RAILHEAD THEATER -1.X.3.1.3.4.4.2=S*G*USTRC-***** -S*G*USTRC-*****.name=RAILHEAD CORPS -1.X.3.1.3.4.5=S*G*USTS--***** -S*G*USTS--*****.name=SPOD/SPOE -1.X.3.1.3.4.5.1=S*G*USTST-***** -S*G*USTST-*****.name=SPOD/SPOE TEATER -1.X.3.1.3.4.5.2=S*G*USTSC-***** -S*G*USTSC-*****.name=SPOD/SPOE CORPS -1.X.3.1.3.4.6=S*G*USTA--***** -S*G*USTA--*****.name=APOD/APOE -1.X.3.1.3.4.6.1=S*G*USTAT-***** -S*G*USTAT-*****.name=APOD/APOE THEATER -1.X.3.1.3.4.6.2=S*G*USTAC-***** -S*G*USTAC-*****.name=APOD/APOE CORPS -1.X.3.1.3.4.7=S*G*USTI--***** -S*G*USTI--*****.name=MISSILE -1.X.3.1.3.4.7.1=S*G*USTIT-***** -S*G*USTIT-*****.name=MISSILE THEATER -1.X.3.1.3.4.7.2=S*G*USTIC-***** -S*G*USTIC-*****.name=MISSILE CORPS -1.X.3.1.3.5=S*G*USX---***** -S*G*USX---*****.name=MAINTENANCE -1.X.3.1.3.5.1=S*G*USXT--***** -S*G*USXT--*****.name=MAINTENANCE THEATER -1.X.3.1.3.5.2=S*G*USXC--***** -S*G*USXC--*****.name=MAINTENANCE CORPS -1.X.3.1.3.5.3=S*G*USXH--***** -S*G*USXH--*****.name=MAINTENANCE HEAVY -1.X.3.1.3.5.3.1=S*G*USXHT-***** -S*G*USXHT-*****.name=MAINTENANCE HEAVY THEATER -1.X.3.1.3.5.3.2=S*G*USXHC-***** -S*G*USXHC-*****.name=MAINTENANCE HEAVY CORPS -1.X.3.1.3.5.4=S*G*USXR--***** -S*G*USXR--*****.name=MAINTENANCE RECOVERY -1.X.3.1.3.5.4.1=S*G*USXRT-***** -S*G*USXRT-*****.name=MAINTENANCE RECOVERY THEATER -1.X.3.1.3.5.4.2=S*G*USXRC-***** -S*G*USXRC-*****.name=MAINTENANCE RECOVERY CORPS -1.X.3.1.3.5.5=S*G*USXO--***** -S*G*USXO--*****.name=ORDNANCE -1.X.3.1.3.5.5.1=S*G*USXOT-***** -S*G*USXOT-*****.name=ORDNANCE THEATER -1.X.3.1.3.5.5.2=S*G*USXOC-***** -S*G*USXOC-*****.name=ORDNANCE CORPS -1.X.3.1.3.5.5.3=S*G*USXOM-***** -S*G*USXOM-*****.name=ORDNANCE MISSILE -1.X.3.1.3.5.5.3.1=S*G*USXOMT***** -S*G*USXOMT*****.name=ORDNANCE MISSILE THEATER -1.X.3.1.3.5.5.3.2=S*G*USXOMC***** -S*G*USXOMC*****.name=ORDNANCE MISSILE CORPS -1.X.3.1.3.5.6=S*G*USXE--***** -S*G*USXE--*****.name=ELECTRO-OPTICAL -1.X.3.1.3.5.6.1=S*G*USXET-***** -S*G*USXET-*****.name=ELECTRO-OPTICAL THEATER -1.X.3.1.3.5.6.2=S*G*USXEC-***** -S*G*USXEC-*****.name=ELECTRO-OPTICAL CORPS -1.X.3.1.4=S*G*UH----***** -S*G*UH----*****.name=SPECIAL C2 HEADQUARTERS COMPONENT -1.X.3.2=S*G*E-----***** -S*G*E-----*****.name=GROUND TRACK EQUIPMENT -1.X.3.2.1=S*G*EW----***** -S*G*EW----*****.name=WEAPON -1.X.3.2.1.1=S*G*EWM---***** -S*G*EWM---*****.name=MISSILE LAUNCHER -1.X.3.2.1.1.1=S*G*EWMA--***** -S*G*EWMA--*****.name=AIR DEFENSE (AD) MISSILE LAUNCHER -1.X.3.2.1.1.1.1=S*G*EWMAS-***** -S*G*EWMAS-*****.name=SHORT RANGE AD MISSILE LAUNCHER -1.X.3.2.1.1.1.2=S*G*EWMAI-***** -S*G*EWMAI-*****.name=INTERMEDIATE RANGE AD MISSILE LAUNCHER -1.X.3.2.1.1.1.3=S*G*EWMAL-***** -S*G*EWMAL-*****.name=LONG RANGE AD MISSILE LAUNCHER -1.X.3.2.1.1.1.4=S*G*EWMAT-***** -S*G*EWMAT-*****.name=AD MISSILE LAUNCHER THEATER -1.X.3.2.1.1.2=S*G*EWMS--***** -S*G*EWMS--*****.name=SURF-SURF (SS) MISSILE LAUNCHER -1.X.3.2.1.1.2.1=S*G*EWMSS-***** -S*G*EWMSS-*****.name=SHORT RANGE SS MISSILE LAUNCHER -1.X.3.2.1.1.2.2=S*G*EWMSI-***** -S*G*EWMSI-*****.name=INTERMEDIATE RANGE SS MISSILE LAUNCHER -1.X.3.2.1.1.2.3=S*G*EWMSL-***** -S*G*EWMSL-*****.name=LONG RANGE SS MISSILE LAUNCHER -1.X.3.2.1.1.3=S*G*EWMT--***** -S*G*EWMT--*****.name=MISSILE LAUNCHER ANTITANK (AT) -1.X.3.2.1.1.3.1=S*G*EWMTL-***** -S*G*EWMTL-*****.name=MISSILE LAUNCHER AT LIGHT -1.X.3.2.1.1.3.2=S*G*EWMTM-***** -S*G*EWMTM-*****.name=MISSILE LAUNCHER AT MEDIUM -1.X.3.2.1.1.3.3=S*G*EWMTH-***** -S*G*EWMTH-*****.name=MISSILE LAUNCHER AT HEAVY -1.X.3.2.1.2=S*G*EWS---***** -S*G*EWS---*****.name=SINGLE ROCKET LAUNCHER -1.X.3.2.1.2.1=S*G*EWSL--***** -S*G*EWSL--*****.name=SINGLE ROCKET LAUNCHER LIGHT -1.X.3.2.1.2.2=S*G*EWSM--***** -S*G*EWSM--*****.name=SINGLE ROCKET LAUNCHER MEDIUM -1.X.3.2.1.2.3=S*G*EWSH--***** -S*G*EWSH--*****.name=SINGLE ROCKET LAUNCHER HEAVY -1.X.3.2.1.3=S*G*EWX---***** -S*G*EWX---*****.name=MULTIPLE ROCKET LAUNCHER -1.X.3.2.1.3.1=S*G*EWXL--***** -S*G*EWXL--*****.name=MULTIPLE ROCKET LAUNCHER LIGHT -1.X.3.2.1.3.2=S*G*EWXM--***** -S*G*EWXM--*****.name=MULTIPLE ROCKET LAUNCHER MEDIUM -1.X.3.2.1.3.3=S*G*EWXH--***** -S*G*EWXH--*****.name=MULTIPLE ROCKET LAUNCHER HEAVY -1.X.3.2.1.4=S*G*EWT---***** -S*G*EWT---*****.name=ANTI-TANK ROCKET LAUNCHER -1.X.3.2.1.4.1=S*G*EWTL--***** -S*G*EWTL--*****.name=ANTI-TANK ROCKET LAUNCHER LIGHT -1.X.3.2.1.4.2=S*G*EWTM--***** -S*G*EWTM--*****.name=ANTI-TANK ROCKET LAUNCHER MEDIUM -1.X.3.2.1.4.3=S*G*EWTH--***** -S*G*EWTH--*****.name=ANTI-TAK ROCKET LAUNCHER HEAVY -1.X.3.2.1.5=S*G*EWR---***** -S*G*EWR---*****.name=RIFLE/AUTOMATIC WEAPON -1.X.3.2.1.5.1=S*G*EWRR--***** -S*G*EWRR--*****.name=RIFLE -1.X.3.2.1.5.2=S*G*EWRL--***** -S*G*EWRL--*****.name=LIGHT MACHINE GUN -1.X.3.2.1.5.3=S*G*EWRH--***** -S*G*EWRH--*****.name=HEAVY MACHINE GUN -1.X.3.2.1.6=S*G*EWZ---***** -S*G*EWZ---*****.name=GRENADE LAUNCHER -1.X.3.2.1.6.1=S*G*EWZL--***** -S*G*EWZL--*****.name=GRENADE LAUNCHER LIGHT -1.X.3.2.1.6.2=S*G*EWZM--***** -S*G*EWZM--*****.name=GRENADE LAUNCHER MEDIUM -1.X.3.2.1.6.3=S*G*EWZH--***** -S*G*EWZH--*****.name=GRENADE LAUNCHER HEAVY -1.X.3.2.1.7=S*G*EWO---***** -S*G*EWO---*****.name=MORTAR -1.X.3.2.1.7.1=S*G*EWOL--***** -S*G*EWOL--*****.name=MORTAR LIGHT -1.X.3.2.1.7.2=S*G*EWOM--***** -S*G*EWOM--*****.name=MORTAR MEDIUM -1.X.3.2.1.7.3=S*G*EWOH--***** -S*G*EWOH--*****.name=MORTAR HEAVY -1.X.3.2.1.8=S*G*EWH---***** -S*G*EWH---*****.name=HOWITZER -1.X.3.2.1.8.1=S*G*EWHL--***** -S*G*EWHL--*****.name=HOWITZER LIGHT -1.X.3.2.1.8.1.1=S*G*EWHLS-***** -S*G*EWHLS-*****.name=HOWITZER LIGHT SELF-PROPELLED -1.X.3.2.1.8.2=S*G*EWHM--***** -S*G*EWHM--*****.name=HOWITZER MEDIUM -1.X.3.2.1.8.2.1=S*G*EWHMS-***** -S*G*EWHMS-*****.name=HOWITZER MEDIUM SELF-PROPELLED -1.X.3.2.1.8.3=S*G*EWHH--***** -S*G*EWHH--*****.name=HOWITZER HEAVY -1.X.3.2.1.8.3.1=S*G*EWHHS-***** -S*G*EWHHS-*****.name=HOWITZER HEAVY SELF-PROPELLED -1.X.3.2.1.9=S*G*EWG---***** -S*G*EWG---*****.name=ANTI-TANK GUN -1.X.3.2.1.9.1=S*G*EWGL--***** -S*G*EWGL--*****.name=ANTI-TANK GUN LIGHT -1.X.3.2.1.9.2=S*G*EWGM--***** -S*G*EWGM--*****.name=ANTI-TANK GUN MEDIUM -1.X.3.2.1.9.3=S*G*EWGH--***** -S*G*EWGH--*****.name=ANTI-TANK GUN HEAVY -1.X.3.2.1.9.4=S*G*EWGR--***** -S*G*EWGR--*****.name=ANTI-TANK GUN RECOILLESS -1.X.3.2.1.10=S*G*EWD---***** -S*G*EWD---*****.name=DIRECT FIRE GUN -1.X.3.2.1.10.1=S*G*EWDL--***** -S*G*EWDL--*****.name=DIRECT FIRE GUN LIGHT -1.X.3.2.1.10.1.1=S*G*EWDLS-***** -S*G*EWDLS-*****.name=DIRECT FIRE GUN LIGHT SELF-PROPELLED -1.X.3.2.1.10.2=S*G*EWDM--***** -S*G*EWDM--*****.name=DIRECT FIRE GUN MEDIUM -1.X.3.2.1.10.2.1=S*G*EWDMS-***** -S*G*EWDMS-*****.name=DIRECT FIRE GUN MEDIUM SELF-PROPELLED -1.X.3.2.1.10.3=S*G*EWDH--***** -S*G*EWDH--*****.name=DIRECT FIRE GUN HEAVY -1.X.3.2.1.10.3.1=S*G*EWDHS-***** -S*G*EWDHS-*****.name=DIRECT FIRE GUN HEAVY SELF-PROPELLED -1.X.3.2.1.11=S*G*EWA---***** -S*G*EWA---*****.name=AIR DEFENSE GUN -1.X.3.2.1.11.1=S*G*EWAL--***** -S*G*EWAL--*****.name=AIR DEFENSE GUN LIGHT -1.X.3.2.1.11.2=S*G*EWAM--***** -S*G*EWAM--*****.name=AIR DEFENSE GUN MEDIUM -1.X.3.2.1.11.3=S*G*EWAH--***** -S*G*EWAH--*****.name=AIR DEFENSE GUN HEAVY -1.X.3.2.2=S*G*EV----***** -S*G*EV----*****.name=GROUND VEHICLE -1.X.3.2.2.1=S*G*EVA---***** -S*G*EVA---*****.name=ARMORED VEHICLE -1.X.3.2.2.1.1=S*G*EVAT--***** -S*G*EVAT--*****.name=TANK -1.X.3.2.2.1.1.1=S*G*EVATL-***** -S*G*EVATL-*****.name=TANK LIGHT -1.X.3.2.2.1.1.1.1=S*G*EVATLR***** -S*G*EVATLR*****.name=TANK LIGHT RECOVERY -1.X.3.2.2.1.1.2=S*G*EVATM-***** -S*G*EVATM-*****.name=TANK MEDIUM -1.X.3.2.2.1.1.2.1=S*G*EVATMR***** -S*G*EVATMR*****.name=TANK MEDIUM RECOVERY -1.X.3.2.2.1.1.3=S*G*EVATH-***** -S*G*EVATH-*****.name=TANK HEAVY -1.X.3.2.2.1.1.3.1=S*G*EVATHR***** -S*G*EVATHR*****.name=TANK HEAVY RECOVERY -1.X.3.2.2.1.2=S*G*EVAA--***** -S*G*EVAA--*****.name=ARMORED PERSONNEL CARRIER -1.X.3.2.2.1.2.1=S*G*EVAAR-***** -S*G*EVAAR-*****.name=ARMORED PERSONNEL CARRIER RECOVERY -1.X.3.2.2.1.3=S*G*EVAI--***** -S*G*EVAI--*****.name=ARMORED INFANTRY -1.X.3.2.2.1.4=S*G*EVAC--***** -S*G*EVAC--*****.name=C2V/ACV -1.X.3.2.2.1.5=S*G*EVAS--***** -S*G*EVAS--*****.name=COMBAT SERVICE SUPPORT VEHICLE -1.X.3.2.2.1.6=S*G*EVAL--***** -S*G*EVAL--*****.name=LIGHT ARMORED VEHICLE -1.X.3.2.2.2=S*G*EVU---***** -S*G*EVU---*****.name=UTILITY VEHICLE -1.X.3.2.2.2.1=S*G*EVUB--***** -S*G*EVUB--*****.name=BUS -1.X.3.2.2.2.2=S*G*EVUS--***** -S*G*EVUS--*****.name=SEMI -1.X.3.2.2.2.3=S*G*EVUL--***** -S*G*EVUL--*****.name=LIMITED CROSS-COUNTRY TRUCK -1.X.3.2.2.2.4=S*G*EVUX--***** -S*G*EVUX--*****.name=CROSS-COUNTRY TRUCK -1.X.3.2.2.2.5=S*G*EVUR--***** -S*G*EVUR--*****.name=WATER CRAFT -1.X.3.2.2.3=S*G*EVE---***** -S*G*EVE---*****.name=ENGINEER VEHICLE -1.X.3.2.2.3.1=S*G*EVEB--***** -S*G*EVEB--*****.name=BRIDGE -1.X.3.2.2.3.2=S*G*EVEE--***** -S*G*EVEE--*****.name=EARTHMOVER -1.X.3.2.2.3.3=S*G*EVEC--***** -S*G*EVEC--*****.name=CONSTRUCTION VEHICLE -1.X.3.2.2.3.4=S*G*EVEM--***** -S*G*EVEM--*****.name=MINE LAYING VEHICLE -1.X.3.2.2.3.4.1=S*G*EVEMV-***** -S*G*EVEMV-*****.name=ARMORED CARRIER WITH VOLCANO -1.X.3.2.2.3.4.2=S*G*EVEML-***** -S*G*EVEML-*****.name=TRUCK MOUNTED WITH VOLCANO -1.X.3.2.2.3.5=S*G*EVEA--***** -S*G*EVEA--*****.name=MINE CLEARING VEHICLE -1.X.3.2.2.3.5.1=S*G*EVEAA-***** -S*G*EVEAA-*****.name=ARMORED MOUNTED MINE CLEARING VEHICLE -1.X.3.2.2.3.5.2=S*G*EVEAT-***** -S*G*EVEAT-*****.name=TRAILER MOUNTED MINE CLEARING VEHICLE -1.X.3.2.2.3.6=S*G*EVED--***** -S*G*EVED--*****.name=DOZER -1.X.3.2.2.4=S*G*EVT---***** -S*G*EVT---*****.name=TRAIN LOCOMOTIVE -1.X.3.2.2.5=S*G*EVC---***** -S*G*EVC---*****.name=CIVILIAN VEHICLE -1.X.3.2.3=S*G*ES----***** -S*G*ES----*****.name=SENSOR -1.X.3.2.3.1=S*G*ESR---***** -S*G*ESR---*****.name=RADAR -1.X.3.2.3.2=S*G*ESE---***** -S*G*ESE---*****.name=EMPLACED SENSOR -1.X.3.2.4=S*G*EX----***** -S*G*EX----*****.name=SPECIAL EQUIPMENT -1.X.3.2.4.1=S*G*EXL---***** -S*G*EXL---*****.name=LASER -1.X.3.2.4.2=S*G*EXN---***** -S*G*EXN---*****.name=NBC EQUIPMENT -1.X.3.2.4.3=S*G*EXF---***** -S*G*EXF---*****.name=FLAME THROWER -1.X.3.2.4.4=S*G*EXM---***** -S*G*EXM---*****.name=LAND MINES -1.X.3.2.4.4.1=S*G*EXMC--***** -S*G*EXMC--*****.name=CLAYMORE -1.X.3.2.4.4.2=S*G*EXML--***** -S*G*EXML--*****.name=LESS THAN LETHAL -1.X.3.3=S*G*I-----H**** -S*G*I-----H****.name=INSTALLATION -1.X.3.3.1=S*G*IR----H**** -S*G*IR----H****.name=RAW MATERIAL PRODUCTION/STORAGE -1.X.3.3.1.1=S*G*IRM---H**** -S*G*IRM---H****.name=MINE -1.X.3.3.1.2=S*G*IRP---H**** -S*G*IRP---H****.name=PETROLEUM/GAS/OIL -1.X.3.3.1.3=S*G*IRN---H**** -S*G*IRN---H****.name=NBC -1.X.3.3.1.3.1=S*G*IRNB--H**** -S*G*IRNB--H****.name=BIOLOGICAL -1.X.3.3.1.3.2=S*G*IRNC--H**** -S*G*IRNC--H****.name=CHEMICAL -1.X.3.3.1.3.3=S*G*IRNN--H**** -S*G*IRNN--H****.name=NUCLEAR -1.X.3.3.2=S*G*IP----H**** -S*G*IP----H****.name=PROCESSING FACILITY -1.X.3.3.2.1=S*G*IPD---H**** -S*G*IPD---H****.name=DECON -1.X.3.3.3=S*G*IE----H**** -S*G*IE----H****.name=EQUIPMENT MANUFACTURE -1.X.3.3.4=S*G*IU----H**** -S*G*IU----H****.name=SERVICE, RESEARCH, UTILITY FACILITY -1.X.3.3.4.1=S*G*IUR---H**** -S*G*IUR---H****.name=TECHNOLOGICAL RESEARCH FACILITY -1.X.3.3.4.2=S*G*IUT---H**** -S*G*IUT---H****.name=TELECOMMUNICATIONS FACILITY -1.X.3.3.4.3=S*G*IUE---H**** -S*G*IUE---H****.name=ELECTRIC POWER FACILITY -1.X.3.3.4.3.1=S*G*IUEN--H**** -S*G*IUEN--H****.name=NUCLEAR PLANT -1.X.3.3.4.3.2=S*G*IUED--H**** -S*G*IUED--H****.name=DAM -1.X.3.3.4.3.3=S*G*IUEF--H**** -S*G*IUEF--H****.name=FOSSIL FUEL -1.X.3.3.4.4=S*G*IUP---H**** -S*G*IUP---H****.name=PUBLIC WATER SERVICES -1.X.3.3.5=S*G*IM----H**** -S*G*IM----H****.name=MILITARY MATERIEL FACILITY -1.X.3.3.5.1=S*G*IMF---H**** -S*G*IMF---H****.name=NUCLEAR ENERGY -1.X.3.3.5.1.1=S*G*IMFA--H**** -S*G*IMFA--H****.name=ATOMIC ENERGY REACTOR -1.X.3.3.5.1.2=S*G*IMFP--H**** -S*G*IMFP--H****.name=NUCLEAR MATERIAL PRODUCTION -1.X.3.3.5.1.2.1=S*G*IMFPW-H**** -S*G*IMFPW-H****.name=WEAPONS GRADE -1.X.3.3.5.1.3=S*G*IMFS--H**** -S*G*IMFS--H****.name=NUCLEAR MATERIAL STORAGE -1.X.3.3.5.2=S*G*IMA---H**** -S*G*IMA---H****.name=AIRCRAFT PRODUCTION & ASSEMBLY -1.X.3.3.5.3=S*G*IME---H**** -S*G*IME---H****.name=AMMUNITION AND EXPLOSIVES PRODUCTION -1.X.3.3.5.4=S*G*IMG---H**** -S*G*IMG---H****.name=ARMAMENT PRODUCTION -1.X.3.3.5.5=S*G*IMV---H**** -S*G*IMV---H****.name=MILITARY VEHICLE PRODUCTION -1.X.3.3.5.6=S*G*IMN---H**** -S*G*IMN---H****.name=ENGINEERING EQUIPMENT PRODUCTION -1.X.3.3.5.6.1=S*G*IMNB--H**** -S*G*IMNB--H****.name=BRIDGE -1.X.3.3.5.7=S*G*IMC---H**** -S*G*IMC---H****.name=CHEMICAL & BIOLOGICAL WARFARE PRODUCTION -1.X.3.3.5.8=S*G*IMS---H**** -S*G*IMS---H****.name=SHIP CONSTRUCTION -1.X.3.3.5.9=S*G*IMM---H**** -S*G*IMM---H****.name=MISSILE & SPACE SYSTEM PRODUCTION -1.X.3.3.6=S*G*IG----H**** -S*G*IG----H****.name=GOVERNMENT LEADERSHIP -1.X.3.3.7=S*G*IB----H**** -S*G*IB----H****.name=MILITARY BASE/FACILITY -1.X.3.3.7.1=S*G*IBA---H**** -S*G*IBA---H****.name=AIRPORT/AIRBASE -1.X.3.3.7.2=S*G*IBN---H**** -S*G*IBN---H****.name=SEAPORT/NAVAL BASE -1.X.3.3.8=S*G*IT----H**** -S*G*IT----H****.name=TRANSPORT FACILITY -1.X.3.3.9=S*G*IX----H**** -S*G*IX----H****.name=MEDICAL FACILITY -1.X.3.3.9.1=S*G*IXH---H**** -S*G*IXH---H****.name=HOSPITAL -1.X.4=S*S*------***** -S*S*------*****.name=SEA SURFACE TRACK -1.X.4.1=S*S*C-----***** -S*S*C-----*****.name=COMBATANT -1.X.4.1.1=S*S*CL----***** -S*S*CL----*****.name=LINE -1.X.4.1.1.1=S*S*CLCV--***** -S*S*CLCV--*****.name=CARRIER -1.X.4.1.1.2=S*S*CLBB--***** -S*S*CLBB--*****.name=BATTLESHIP -1.X.4.1.1.3=S*S*CLCC--***** -S*S*CLCC--*****.name=CRUISER -1.X.4.1.1.4=S*S*CLDD--***** -S*S*CLDD--*****.name=DESTROYER -1.X.4.1.1.5=S*S*CLFF--***** -S*S*CLFF--*****.name=FRIGATE/CORVETTE -1.X.4.1.2=S*S*CA----***** -S*S*CA----*****.name=AMPHIBIOUS WARFARE SHIP -1.X.4.1.2.1=S*S*CALA--***** -S*S*CALA--*****.name=ASSAULT VESSEL -1.X.4.1.2.2=S*S*CALS--***** -S*S*CALS--*****.name=LANDING SHIP -1.X.4.1.2.3=S*S*CALC--***** -S*S*CALC--*****.name=LANDING CRAFT -1.X.4.1.3=S*S*CM----***** -S*S*CM----*****.name=MINE WARFARE VESSEL -1.X.4.1.3.1=S*S*CMML--***** -S*S*CMML--*****.name=MINELAYER -1.X.4.1.3.2=S*S*CMMS--***** -S*S*CMMS--*****.name=MINESWEEPER -1.X.4.1.3.3=S*S*CMMH--***** -S*S*CMMH--*****.name=MINEHUNTER -1.X.4.1.3.4=S*S*CMMA--***** -S*S*CMMA--*****.name=MCM SUPPORT -1.X.4.1.3.5=S*S*CMMD--***** -S*S*CMMD--*****.name=MCM DRONE -1.X.4.1.4=S*S*CP----***** -S*S*CP----*****.name=PATROL -1.X.4.1.4.1=S*S*CPSB--***** -S*S*CPSB--*****.name=ANTISUBMARINE WARFARE -1.X.4.1.4.2=S*S*CPSU--***** -S*S*CPSU--*****.name=ANTISURFACE WARFARE -1.X.4.1.5=S*S*CH----***** -S*S*CH----*****.name=HOVERCRAFT -1.X.4.1.6=S*S*S-----***** -S*S*S-----*****.name=STATION -1.X.4.1.6.1=S*S*SP----***** -S*S*SP----*****.name=PICKET -1.X.4.1.6.2=S*S*SA----***** -S*S*SA----*****.name=ASW SHIP -1.X.4.1.7=S*S*G-----***** -S*S*G-----*****.name=NAVY GROUP -1.X.4.1.7.1=S*S*GT----***** -S*S*GT----*****.name=NAVY TASK FORCE -1.X.4.1.7.2=S*S*GG----***** -S*S*GG----*****.name=NAVY TASK GROUP -1.X.4.1.7.3=S*S*GU----***** -S*S*GU----*****.name=NAVY TASK UNIT -1.X.4.1.7.4=S*S*GC----***** -S*S*GC----*****.name=CONVOY -1.X.4.2=S*S*N-----***** -S*S*N-----*****.name=NONCOMBATANT -1.X.4.2.1=S*S*NR----***** -S*S*NR----*****.name=UNDERWAY REPLENISHMENT -1.X.4.2.2=S*S*NF----***** -S*S*NF----*****.name=FLEET SUPPORT -1.X.4.2.3=S*S*NI----***** -S*S*NI----*****.name=INTELLIGENCE -1.X.4.2.4=S*S*NS----***** -S*S*NS----*****.name=SERVICE & SUPPORT HARBOR -1.X.4.2.5=S*S*NM----***** -S*S*NM----*****.name=HOSPITAL SHIP -1.X.4.2.6=S*S*NH----***** -S*S*NH----*****.name=HOVERCRAFT -1.X.4.2.7=S*S*NN----***** -S*S*NN----*****.name=STATION -1.X.4.2.7.1=S*S*NNR---***** -S*S*NNR---*****.name=RESCUE -1.X.4.3=S*S*X-----***** -S*S*X-----*****.name=NON-MILITARY -1.X.4.3.1=S*S*XM----***** -S*S*XM----*****.name=MERCHANT -1.X.4.3.1.1=S*S*XMC---***** -S*S*XMC---*****.name=CARGO -1.X.4.3.1.2=S*S*XMR---***** -S*S*XMR---*****.name=ROLL ON/ROLL OFF -1.X.4.3.1.3=S*S*XMO---***** -S*S*XMO---*****.name=OILER/TANKER -1.X.4.3.1.4=S*S*XMTU--***** -S*S*XMTU--*****.name=TUG -1.X.4.3.1.5=S*S*XMF---***** -S*S*XMF---*****.name=FERRY -1.X.4.3.1.6=S*S*XMP---***** -S*S*XMP---*****.name=PASSENGER -1.X.4.3.1.7=S*S*XMH---***** -S*S*XMH---*****.name=HAZARDOUS MATERIALS (HAZMAT) -1.X.4.3.1.8=S*S*XMTO--***** -S*S*XMTO--*****.name=TOWING VESSEL -1.X.4.3.2=S*S*XF----***** -S*S*XF----*****.name=FISHING -1.X.4.3.2.1=S*S*XFDF--***** -S*S*XFDF--*****.name=DRIFTER -1.X.4.3.2.2=S*S*XFDR--***** -S*S*XFDR--*****.name=DREDGE -1.X.4.3.2.3=S*S*XFTR--***** -S*S*XFTR--*****.name=TRAWLER -1.X.4.3.3=S*S*XR----***** -S*S*XR----*****.name=LEISURE CRAFT -1.X.4.3.4=S*S*XL----***** -S*S*XL----*****.name=LAW ENFORCEMENT VESSEL -1.X.4.3.5=S*S*XH----***** -S*S*XH----*****.name=HOVERCRAFT -1.X.4.4=S*S*O-----***** -S*S*O-----*****.name=OWN TRACK -1.X.5=S*U*------***** -S*U*------*****.name=SUBSURFACE TRACK -1.X.5.1=S*U*S-----***** -S*U*S-----*****.name=SUBMARINE -1.X.5.1.1=S*U*SN----***** -S*U*SN----*****.name=NUCLEAR PROPULSION -1.X.5.1.2=S*U*SC----***** -S*U*SC----*****.name=CONVENTIONAL PROPULSION -1.X.5.1.3=S*U*SO----***** -S*U*SO----*****.name=OTHER SUBMERSIBLE -1.X.5.1.3.1=S*U*SU----***** -S*U*SU----*****.name=UNMANNED UNDERWATER VEHICLE (UUV) -1.X.5.1.4=S*U*SS----***** -S*U*SS----*****.name=STATION -1.X.5.1.4.1=S*U*SSA---***** -S*U*SSA---*****.name=ASW SUBMARINE -1.X.5.2=S*U*W-----***** -S*U*W-----*****.name=UNDERWATER WEAPON -1.X.5.2.1=S*U*WT----***** -S*U*WT----*****.name=TORPEDO -1.X.5.2.2=S*U*WM----***** -S*U*WM----*****.name=SEA MINE -1.X.5.2.2.1=S*U*WMD---***** -S*U*WMD---*****.name=SEA MINE DEALT -1.X.5.2.2.2=S*U*WMG---***** -S*U*WMG---*****.name=SEA MINE (GROUND) -1.X.5.2.2.2.1=S*U*WMGD--***** -S*U*WMGD--*****.name=SEA MINE (GROUND) DEALT -1.X.5.2.2.3=S*U*WMM---***** -S*U*WMM---*****.name=SEA MINE (MOORED) -1.X.5.2.2.3.1=S*U*WMMD--***** -S*U*WMMD--*****.name=SEA MINE (MOORED) DEALT -1.X.5.2.2.4=S*U*WMF---***** -S*U*WMF---*****.name=SEA MINE (FLOATING) -1.X.5.2.2.4.1=S*U*WMFD--***** -S*U*WMFD--*****.name=SEA MINE (FLOATING) DEALT -1.X.5.2.2.5=S*U*WMO---***** -S*U*WMO---*****.name=SEA MINE (IN OTHER POSITION) -1.X.5.2.2.5.1=S*U*WMOD--***** -S*U*WMOD--*****.name=SEA MINE (IN OTHER POSITION) DEALT -1.X.5.3=S*U*WD----***** -S*U*WD----*****.name=UNDERWATER DECOY -1.X.5.3.1=S*U*WDM---***** -S*U*WDM---*****.name=SEA MINE DECOY -1.X.5.4=S*U*N-----***** -S*U*N-----*****.name=NON-SUBMARINE -1.X.5.4.1=S*U*ND----***** -S*U*ND----*****.name=DIVER -1.X.6=S*F*------***** -S*F*------*****.name=SPECIAL OPERATIONS FORCES (SOF) UNIT -1.X.6.1=S*F*A-----***** -S*F*A-----*****.name=SOF UNIT AVIATION -1.X.6.1.1=S*F*AF----***** -S*F*AF----*****.name=SOF UNIT FIXED WING -1.X.6.1.1.1=S*F*AFA---***** -S*F*AFA---*****.name=SOF UNIT ATTACK -1.X.6.1.1.2=S*F*AFK---***** -S*F*AFK---*****.name=SOF UNIT REFUEL -1.X.6.1.1.3=S*F*AFU---***** -S*F*AFU---*****.name=SOF UNIT UTILITY -1.X.6.1.1.3.1=S*F*AFUL--***** -S*F*AFUL--*****.name=SOF UNIT UTILITY (LIGHT) -1.X.6.1.1.3.2=S*F*AFUM--***** -S*F*AFUM--*****.name=SOF UNIT UTILITY (MEDIUM) -1.X.6.1.1.3.3=S*F*AFUH--***** -S*F*AFUH--*****.name=SOF UNIT UTILITY (HEAVY) -1.X.6.1.2=S*F*AV----***** -S*F*AV----*****.name=SOF UNIT VSTOL -1.X.6.1.3=S*F*AH----***** -S*F*AH----*****.name=SOF UNIT ROTARY WING -1.X.6.1.3.1=S*F*AHH---***** -S*F*AHH---*****.name=SOF UNIT COMBAT SEARCH AND RESCUE -1.X.6.1.3.2=S*F*AHA---***** -S*F*AHA---*****.name=SOF UNIT ATTACK -1.X.6.1.3.3=S*F*AHU---***** -S*F*AHU---*****.name=SOF UNIT UTILITY -1.X.6.1.3.3.1=S*F*AHUL--***** -S*F*AHUL--*****.name=SOF UNIT UTILITY (LIGHT) -1.X.6.1.3.3.2=S*F*AHUM--***** -S*F*AHUM--*****.name=SOF UNIT UTILITY (MEDIUM) -1.X.6.1.3.3.3=S*F*AHUH--***** -S*F*AHUH--*****.name=SOF UNIT UTILITY (HEAVY) -1.X.6.2=S*F*N-----***** -S*F*N-----*****.name=SOF UNIT SOF UNIT NAVAL -1.X.6.2.1=S*F*NS----***** -S*F*NS----*****.name=SOF UNIT SEAL -1.X.6.2.2=S*F*NU----***** -S*F*NU----*****.name=SOF UNIT UNDERWATER DEMOLITION TEAM -1.X.6.2.3=S*F*NB----***** -S*F*NB----*****.name=SOF UNIT SPECIAL BOAT -1.X.6.2.4=S*F*NN----***** -S*F*NN----*****.name=SOF UNIT SPECIAL SSNR -1.X.6.3=S*F*G-----***** -S*F*G-----*****.name=SOF UNIT GROUND -1.X.6.3.1=S*F*GS----***** -S*F*GS----*****.name=SOF UNIT SPECIAL FORCES -1.X.6.3.2=S*F*GR----***** -S*F*GR----*****.name=SOF UNIT RANGER -1.X.6.3.3=S*F*GP----***** -S*F*GP----*****.name=SOF UNIT PSYCHOLOGICAL OPERATIONS (PSYOP) -1.X.6.3.3.1=S*F*GPA---***** -S*F*GPA---*****.name=SOF UNIT FIXED AVIATION -1.X.6.3.4=S*F*GC----***** -S*F*GC----*****.name=SOF UNIT CIVIL AFFAIRS -1.X.6.4=S*F*B-----***** -S*F*B-----*****.name=SOF UNIT SUPPORT -2.X=G*------------X -G*------------X.name=TACTICAL GRAPHICS -2.X.1=G*T*------****X -G*T*------****X.name=TASKS -2.X.1.1=G*T*B-----****X -G*T*B-----****X.name=BLOCK -2.X.1.2=G*T*H-----****X -G*T*H-----****X.name=BREACH -2.X.1.3=G*T*Y-----****X -G*T*Y-----****X.name=BYPASS -2.X.1.4=G*T*C-----****X -G*T*C-----****X.name=CANALIZE -2.X.1.5=G*T*X-----****X -G*T*X-----****X.name=CLEAR -2.X.1.6=G*T*J-----****X -G*T*J-----****X.name=CONTAIN -2.X.1.7=G*T*K-----****X -G*T*K-----****X.name=COUNTERATTACK (CATK) -2.X.1.7.1=G*T*KF----****X -G*T*KF----****X.name=COUNTERATTACK BY FIRE -2.X.1.8=G*T*L-----****X -G*T*L-----****X.name=DELAY -2.X.1.9=G*T*D-----****X -G*T*D-----****X.name=DESTROY -2.X.1.10=G*T*T-----****X -G*T*T-----****X.name=DISRUPT -2.X.1.11=G*T*F-----****X -G*T*F-----****X.name=FIX -2.X.1.12=G*T*A-----****X -G*T*A-----****X.name=FOLLOW AND ASSUME -2.X.1.12.1=G*T*AS----****X -G*T*AS----****X.name=FOLLOW AND SUPPORT -2.X.1.13=G*T*I-----****X -G*T*I-----****X.name=INTERDICT -2.X.1.14=G*T*E-----****X -G*T*E-----****X.name=ISOLATE -2.X.1.15=G*T*N-----****X -G*T*N-----****X.name=NEUTRALIZE -2.X.1.16=G*T*O-----****X -G*T*O-----****X.name=OCCUPY -2.X.1.17=G*T*P-----****X -G*T*P-----****X.name=PENETRATE -2.X.1.18=G*T*R-----****X -G*T*R-----****X.name=RELIEF IN PLACE (RIP) -2.X.1.19=G*T*Q-----****X -G*T*Q-----****X.name=RETAIN -2.X.1.20=G*T*M-----****X -G*T*M-----****X.name=RETIREMENT -2.X.1.21=G*T*S-----****X -G*T*S-----****X.name=SECURE -2.X.1.22=G-T*U---------X -G-T*U---------X.name=SECURITY -2.X.1.22.1=G*T*US----****X -G*T*US----****X.name=SCREEN -2.X.1.22.2=G*T*UG----****X -G*T*UG----****X.name=GUARD -2.X.1.22.3=G*T*UC----****X -G*T*UC----****X.name=COVER -2.X.1.23=G*T*Z-----****X -G*T*Z-----****X.name=SEIZE -2.X.1.24=G*T*W-----****X -G*T*W-----****X.name=WITHDRAW -2.X.1.24.1=G*T*WP----****X -G*T*WP----****X.name=WITHDRAW UNDER PRESSURE -2.X.2=G*G*------****X -G*G*------****X.name=COMMAND AND CONTROL AND GENERAL MANEUVER -2.X.2.1=G*G*G-----****X -G*G*G-----****X.name=GENERAL -2.X.2.1.1=G*G*GP----****X -G*G*GP----****X.name=POINTS -2.X.2.1.1.1=G*G*GPU---****X -G*G*GPU---****X.name=UNDER SEA WARFARE -2.X.2.1.1.1.1=G*G*GPUU--****X -G*G*GPUU--****X.name=UNDERWATER -2.X.2.1.1.1.1.1=G*G*GPUUD-****X -G*G*GPUUD-****X.name=DATUM -2.X.2.1.1.1.1.2=G*G*GPUUB-****X -G*G*GPUUB-****X.name=BRIEF CONTACT -2.X.2.1.1.1.1.3=G*G*GPUUL-****X -G*G*GPUUL-****X.name=LOST CONTACT -2.X.2.1.1.1.1.4=G*G*GPUUS-****X -G*G*GPUUS-****X.name=SINKER -2.X.2.1.1.1.2=G*G*GPUY--****X -G*G*GPUY--****X.name=SONOBUOY -2.X.2.1.1.1.2.1=G*G*GPUYP-****X -G*G*GPUYP-****X.name=PATTERN CENTER -2.X.2.1.1.1.2.2=G*G*GPUYD-****X -G*G*GPUYD-****X.name=DIRECTIONAL FREQUENCY ANALYZING AND RECORDING (DIFAR) -2.X.2.1.1.1.2.3=G*G*GPUYL-****X -G*G*GPUYL-****X.name=LOW FREQUENCY ANALYZING AND RECORDING (LOFAR) -2.X.2.1.1.1.2.4=G*G*GPUYC-****X -G*G*GPUYC-****X.name=COMMAND ACTIVE SONOBUOY SYSTEM (CASS) -2.X.2.1.1.1.2.5=G*G*GPUYS-****X -G*G*GPUYS-****X.name=DIRECTIONAL COMMAND ACTIVE SONOBUOY SYSTEM (DICASS) -2.X.2.1.1.1.2.6=G*G*GPUYB-****X -G*G*GPUYB-****X.name=BATHYTHERMOGRAPH TRANSMITTING (BT) -2.X.2.1.1.1.2.7=G*G*GPUYA-****X -G*G*GPUYA-****X.name=ANM -2.X.2.1.1.1.2.8=G*G*GPUYV-****X -G*G*GPUYV-****X.name=VERTICAL LINE ARRAY DIFAR (VLAD) -2.X.2.1.1.1.2.9=G*G*GPUYT-****X -G*G*GPUYT-****X.name=ATAC -2.X.2.1.1.1.2.10=G*G*GPUYR-****X -G*G*GPUYR-****X.name=RANGE ONLY (RO) -2.X.2.1.1.1.2.11=G*G*GPUYK-****X -G*G*GPUYK-****X.name=KINGPIN -2.X.2.1.1.1.3=G*G*GPUS--****X -G*G*GPUS--****X.name=SEARCH -2.X.2.1.1.1.3.1=G*G*GPUSA-****X -G*G*GPUSA-****X.name=SEARCH AREA -2.X.2.1.1.1.3.2=G*G*GPUSD-****X -G*G*GPUSD-****X.name=DIP POSITION -2.X.2.1.1.1.3.3=G*G*GPUSC-****X -G*G*GPUSC-****X.name=SEARCH CENTER -2.X.2.1.1.2=G*G*GPR---****X -G*G*GPR---****X.name=REFERENCE POINT -2.X.2.1.1.2.1=G*G*GPRS--****X -G*G*GPRS--****X.name=SPECIAL POINT -2.X.2.1.1.2.2=G*G*GPRN--****X -G*G*GPRN--****X.name=NAV REFERENCE -2.X.2.1.1.2.3=G*G*GPRD--****X -G*G*GPRD--****X.name=DLRP -2.X.2.1.1.2.4=G*G*GPRI--****X -G*G*GPRI--****X.name=POINT OF INTEREST -2.X.2.1.1.3=G*G*GPW---****X -G*G*GPW---****X.name=WEAPON -2.X.2.1.1.3.1=G*G*GPWA--****X -G*G*GPWA--****X.name=AIM POINT -2.X.2.1.1.3.2=G*G*GPWD--****X -G*G*GPWD--****X.name=DROP POINT -2.X.2.1.1.3.3=G*G*GPWE--****X -G*G*GPWE--****X.name=ENTRY POINT -2.X.2.1.1.3.4=G*G*GPWG--****X -G*G*GPWG--****X.name=GROUND ZERO -2.X.2.1.1.3.5=G*G*GPWM--****X -G*G*GPWM--****X.name=MSL DETECT POINT -2.X.2.1.1.3.6=G*G*GPWI--****X -G*G*GPWI--****X.name=IMPACT POINT -2.X.2.1.1.3.7=G*G*GPWP--****X -G*G*GPWP--****X.name=PREDICTED IMPACT POINT -2.X.2.1.1.4=G*G*GPF---****X -G*G*GPF---****X.name=FORMATION -2.X.2.1.1.5=G*G*GPH---****X -G*G*GPH---****X.name=HARBOR (GENERAL) -2.X.2.1.1.5.1=G*G*GPHQ--****X -G*G*GPHQ--****X.name=POINT Q -2.X.2.1.1.5.2=G*G*GPHA--****X -G*G*GPHA--****X.name=POINT A -2.X.2.1.1.5.3=G*G*GPHY--****X -G*G*GPHY--****X.name=POINT Y -2.X.2.1.1.5.4=G*G*GPHX--****X -G*G*GPHX--****X.name=POINT X -2.X.2.1.1.6=G*G*GPO---****X -G*G*GPO---****X.name=ROUTE -2.X.2.1.1.6.1=G*G*GPOZ--****X -G*G*GPOZ--****X.name=RENDEZVOUS -2.X.2.1.1.6.2=G*G*GPOD--****X -G*G*GPOD--****X.name=DIVERSIONS -2.X.2.1.1.6.3=G*G*GPOW--****X -G*G*GPOW--****X.name=WAYPOINT -2.X.2.1.1.6.4=G*G*GPOP--****X -G*G*GPOP--****X.name=PIM -2.X.2.1.1.6.5=G*G*GPOR--****X -G*G*GPOR--****X.name=POINT R -2.X.2.1.1.7=G*G*GPA---****X -G*G*GPA---****X.name=AIR CONTROL -2.X.2.1.1.7.1=G*G*GPAP--****X -G*G*GPAP--****X.name=COMBAT AIR PATROL (CAP) -2.X.2.1.1.7.2=G*G*GPAW--****X -G*G*GPAW--****X.name=AIRBORNE EARLY WARNING (AEW) -2.X.2.1.1.7.3=G*G*GPAT--****X -G*G*GPAT--****X.name=TACAN -2.X.2.1.1.7.4=G*G*GPAK--****X -G*G*GPAK--****X.name=TANKING -2.X.2.1.1.7.5=G*G*GPAA--****X -G*G*GPAA--****X.name=ANTISUBMARINE WARFARE , FIXED WING -2.X.2.1.1.7.6=G*G*GPAH--****X -G*G*GPAH--****X.name=ANTISUBMARINE WARFARE, ROTARY WING -2.X.2.1.1.7.7=G*G*GPAO--****X -G*G*GPAO--****X.name=TOMCAT -2.X.2.1.1.7.8=G*G*GPAR--****X -G*G*GPAR--****X.name=RESCUE -2.X.2.1.1.7.9=G*G*GPAL--****X -G*G*GPAL--****X.name=REPLENISH -2.X.2.1.1.7.10=G*G*GPAM--****X -G*G*GPAM--****X.name=MARSHALL -2.X.2.1.1.7.11=G*G*GPAS--****X -G*G*GPAS--****X.name=STRIKE IP -2.X.2.1.1.7.12=G*G*GPAC--****X -G*G*GPAC--****X.name=CORRIDOR TAB -2.X.2.1.1.8=G*G*GPP---****X -G*G*GPP---****X.name=ACTION POINTS (GENERAL) -2.X.2.1.1.8.1=G*G*GPPK--****X -G*G*GPPK--****X.name=CHECK POINT -2.X.2.1.1.8.2=G*G*GPPC--****X -G*G*GPPC--****X.name=CONTACT POINT -2.X.2.1.1.8.3=G*G*GPPO--****X -G*G*GPPO--****X.name=COORDINATION POINT -2.X.2.1.1.8.4=G*G*GPPD--****X -G*G*GPPD--****X.name=DECISION POINT -2.X.2.1.1.8.5=G*G*GPPL--****X -G*G*GPPL--****X.name=LINKUP POINT -2.X.2.1.1.8.6=G*G*GPPP--****X -G*G*GPPP--****X.name=PASSAGE POINT -2.X.2.1.1.8.7=G*G*GPPR--****X -G*G*GPPR--****X.name=RALLY POINT -2.X.2.1.1.8.8=G*G*GPPE--****X -G*G*GPPE--****X.name=RELEASE POINT -2.X.2.1.1.8.9=G*G*GPPS--****X -G*G*GPPS--****X.name=START POINT -2.X.2.1.1.8.10=G*G*GPPW--****X -G*G*GPPW--****X.name=WAYPOINT -2.X.2.1.2=G*G*GL----****X -G*G*GL----****X.name=LINES -2.X.2.1.2.1=G*G*GLB---****X -G*G*GLB---****X.name=BOUNDARIES -2.X.2.1.2.2=G*G*GLF---****X -G*G*GLF---****X.name=FORWARD LINE OF OWN TROOPS (FLOT) -2.X.2.1.2.3=G*G*GLC---****X -G*G*GLC---****X.name=LINE OF CONTACT -2.X.2.1.2.4=G*G*GLP---****X -G*G*GLP---****X.name=PHASE LINE -2.X.2.1.2.5=G*G*GLL---****X -G*G*GLL---****X.name=LIGHT LINE -2.X.2.1.3=G*G*GA----****X -G*G*GA----****X.name=AREAS -2.X.2.1.3.1=G*G*GAG---****X -G*G*GAG---****X.name=GENERAL AREA -2.X.2.1.3.2=G*G*GAA---****X -G*G*GAA---****X.name=ASSEMBLY AREA -2.X.2.1.3.3=G*G*GAE---****X -G*G*GAE---****X.name=ENGAGEMENT AREA -2.X.2.1.3.4=G*G*GAF---****X -G*G*GAF---****X.name=FORTIFIED AREA -2.X.2.1.3.5=G*G*GAD---****X -G*G*GAD---****X.name=DROP ZONE -2.X.2.1.3.6=G*G*GAX---****X -G*G*GAX---****X.name=EXTRACTION ZONE (EZ) -2.X.2.1.3.7=G*G*GAL---****X -G*G*GAL---****X.name=LANDING ZONE (LZ) -2.X.2.1.3.8=G*G*GAP---****X -G*G*GAP---****X.name=PICKUP ZONE (PZ) -2.X.2.1.3.9=G*G*GAS---****X -G*G*GAS---****X.name=SEARCH AREA/RECONNAISSANCE AREA -2.X.2.1.3.10=G*G*GAY---****X -G*G*GAY---****X.name=LIMITED ACCESS AREA -2.X.2.1.3.11=G*G*GAZ---****X -G*G*GAZ---****X.name=AIRFIELD ZONE -2.X.2.2=G*G*A-----****X -G*G*A-----****X.name=AVIATION -2.X.2.2.1=G*G*AP----****X -G*G*AP----****X.name=POINTS -2.X.2.2.1.1=G*G*APP---****X -G*G*APP---****X.name=AIR CONTROL POINT (ACP) -2.X.2.2.1.2=G*G*APC---****X -G*G*APC---****X.name=COMMUNICATIONS CHECKPOINT (CCP) -2.X.2.2.1.3=G*G*APU---****X -G*G*APU---****X.name=POP-UP POINT (PUP) -2.X.2.2.1.4=G*G*APD---****X -G*G*APD---****X.name=DOWNED AIRCREW PICKUP POINT -2.X.2.2.2=G*G*AL----****X -G*G*AL----****X.name=LINES -2.X.2.2.2.1=G*G*ALC---****X -G*G*ALC---****X.name=AIR CORRIDOR -2.X.2.2.2.2=G*G*ALM---****X -G*G*ALM---****X.name=MINIMUM RISK ROUTE (MRR) -2.X.2.2.2.3=G*G*ALS---****X -G*G*ALS---****X.name=STANDARD-USE ARMY AIRCRAFT FLIGHT ROUTE (SAAFR) -2.X.2.2.2.4=G*G*ALU---****X -G*G*ALU---****X.name=UNMANNED AERIAL VEHICLE (UAV) ROUTE -2.X.2.2.2.5=G*G*ALL---****X -G*G*ALL---****X.name=LOW LEVEL TRANSIT ROUTE (LLTR) -2.X.2.2.3=G*G*AA----****X -G*G*AA----****X.name=AREAS -2.X.2.2.3.1=G*G*AAR---****X -G*G*AAR---****X.name=RESTRICTED OPERATIONS ZONE (ROZ) -2.X.2.2.3.2=G*G*AAF---****X -G*G*AAF---****X.name=FORWARD AREA AIR DEFENSE ZONE (FAADEZ) -2.X.2.2.3.3=G*G*AAH---****X -G*G*AAH---****X.name=HIGH DENSITY AIRSPACE CONTROL ZONE (HIDACZ) -2.X.2.2.3.4=G*G*AAM---****X -G*G*AAM---****X.name=MISSILE ENGAGEMENT ZONE (MEZ) -2.X.2.2.3.4.1=G*G*AAML--****X -G*G*AAML--****X.name=LOW ALTITUDE MEZ -2.X.2.2.3.4.2=G*G*AAMH--****X -G*G*AAMH--****X.name=HIGH ALTITUDE MEZ -2.X.2.2.3.5=G*G*AAW---****X -G*G*AAW---****X.name=WEAPONS FREE ZONE -2.X.2.3=G*G*P-----****X -G*G*P-----****X.name=DECEPTION -2.X.2.3.1=G*G*PD----****X -G*G*PD----****X.name=DUMMY (DECEPTION/DECOY) -2.X.2.3.2=G*G*PA----****X -G*G*PA----****X.name=AXIS OF ADVANCE FOR FEINT -2.X.2.3.3=G*G*PF----****X -G*G*PF----****X.name=DIRECTION OF ATTACK FOR FEINT -2.X.2.3.4=G*G*PM----****X -G*G*PM----****X.name=DECOY MINED AREA -2.X.2.3.5=G*G*PY----****X -G*G*PY----****X.name=DECOY MINED AREA, FENCED -2.X.2.3.6=G*G*PN----****X -G*G*PN----****X.name=DUMMY MINEFIELD (STATIC) -2.X.2.3.7=G*G*PC----****X -G*G*PC----****X.name=DUMMY MINEFIELD (DYNAMIC) -2.X.2.4=G*G*D-----****X -G*G*D-----****X.name=DEFENSE -2.X.2.4.1=G*G*DP----****X -G*G*DP----****X.name=POINTS -2.X.2.4.1.1=G*G*DPT---****X -G*G*DPT---****X.name=TARGET REFERENCE POINT (TRP) -2.X.2.4.1.2=G*G*DPO---****X -G*G*DPO---****X.name=OBSERVATION POST/OUTPOST -2.X.2.4.1.2.1=G*G*DPOC--****X -G*G*DPOC--****X.name=COMBAT OUTPOST -2.X.2.4.1.2.2=G*G*DPOR--****X -G*G*DPOR--****X.name=OBSERVATION POST OCCUPIED BY DISMOUNTED SCOUTS OR RECONNAISSANCE -2.X.2.4.1.2.3=G*G*DPOF--****X -G*G*DPOF--****X.name=FORWARD OBSERVER POSITION -2.X.2.4.1.2.4=G*G*DPOS--****X -G*G*DPOS--****X.name=SENSOR OUTPOST/LISTENING POST (OP/LP) -2.X.2.4.1.2.5=G*G*DPON--****X -G*G*DPON--****X.name=NBC OBSERVATION POST (DISMOUNTED) -2.X.2.4.2=G*G*DL----****X -G*G*DL----****X.name=LINES -2.X.2.4.2.1=G*G*DLF---****X -G*G*DLF---****X.name=FORWARD EDGE OF BATTLE AREA (FEBA) -2.X.2.4.2.2=G*G*DLP---****X -G*G*DLP---****X.name=PRINCIPAL DIRECTION OF FIRE (PDF) -2.X.2.4.3=G*G*DA----****X -G*G*DA----****X.name=AREAS -2.X.2.4.3.1=GFG*DAB---****X -GFG*DAB---****X.name=BATTLE POSITION -2.X.2.4.3.1.1=G*G*DABP--****X -G*G*DABP--****X.name=PREPARED BUT NOT OCCUPIED -2.X.2.4.3.2=G*G*DAE---****X -G*G*DAE---****X.name=ENGAGEMENT AREA -2.X.2.5=G*G*O-----****X -G*G*O-----****X.name=OFFENSE -2.X.2.5.1=G*G*OP----****X -G*G*OP----****X.name=POINTS -2.X.2.5.1.1=G*G*OPP---****X -G*G*OPP---****X.name=POINT OF DEPARTURE -2.X.2.5.2=G*G*OL----****X -G*G*OL----****X.name=LINES -2.X.2.5.2.1=G*G*OLA---****X -G*G*OLA---****X.name=AXIS OF ADVANCE -2.X.2.5.2.1.1=G*G*OLAV--****X -G*G*OLAV--****X.name=FRIENDLY AVIATION -2.X.2.5.2.1.2=G*G*OLAA--****X -G*G*OLAA--****X.name=FRIENDLY AIRBORNE -2.X.2.5.2.1.3=G*G*OLAR--****X -G*G*OLAR--****X.name=FRIENDLY ATTACK, ROTARY WING -2.X.2.5.2.1.4=G*G*OLAG--****X -G*G*OLAG--****X.name=GROUND -2.X.2.5.2.1.4.1=G*G*OLAGM-****X -G*G*OLAGM-****X.name=MAIN ATTACK -2.X.2.5.2.1.4.2=G*G*OLAGS-****X -G*G*OLAGS-****X.name=SUPPORTING ATTACK -2.X.2.5.2.2=G*G*OLK---****X -G*G*OLK---****X.name=DIRECTION OF ATTACK -2.X.2.5.2.2.1=G*G*OLKA--****X -G*G*OLKA--****X.name=AVIATION -2.X.2.5.2.2.2=G*G*OLKG--****X -G*G*OLKG--****X.name=GROUND -2.X.2.5.2.2.2.1=G*G*OLKGM-****X -G*G*OLKGM-****X.name=MAIN ATTACK -2.X.2.5.2.2.2.2=G*G*OLKGS-****X -G*G*OLKGS-****X.name=SUPPORTING ATTACK -2.X.2.5.2.3=G*G*OLF---****X -G*G*OLF---****X.name=FINAL COORDINATION LINE -2.X.2.5.2.4=G*G*OLI---****X -G*G*OLI---****X.name=INFILTRATION LINE -2.X.2.5.2.5=G*G*OLL---****X -G*G*OLL---****X.name=LIMIT OF ADVANCE -2.X.2.5.2.6=G*G*OLT---****X -G*G*OLT---****X.name=LINE OF DEPARTURE -2.X.2.5.2.7=G*G*OLC---****X -G*G*OLC---****X.name=LINE OF DEPARTURE/LINE OF CONTACT (LD/LC) -2.X.2.5.2.8=G*G*OLP---****X -G*G*OLP---****X.name=PROBABLE LINE OF DEPLOYMENT (PLD) -2.X.2.5.3=G*G*OA----****X -G*G*OA----****X.name=AREAS -2.X.2.5.3.1=G*G*OAA---****X -G*G*OAA---****X.name=ASSAULT POSITION -2.X.2.5.3.2=G*G*OAK---****X -G*G*OAK---****X.name=ATTACK POSITION -2.X.2.5.3.3=G*G*OAF---****X -G*G*OAF---****X.name=ATTACK BY FIRE POSITION -2.X.2.5.3.4=G*G*OAS---****X -G*G*OAS---****X.name=SUPPORT BY FIRE POSITION -2.X.2.5.3.5=G*G*OAO---****X -G*G*OAO---****X.name=OBJECTIVE -2.X.2.5.3.6=G*G*OAP---****X -G*G*OAP---****X.name=PENETRATION BOX -2.X.2.6=G*G*S-----****X -G*G*S-----****X.name=SPECIAL -2.X.2.6.1=G*G*SL----****X -G*G*SL----****X.name=LINE -2.X.2.6.1.1=G*G*SLA---****X -G*G*SLA---****X.name=AMBUSH -2.X.2.6.1.2=G*G*SLH---****X -G*G*SLH---****X.name=HOLDING LINE -2.X.2.6.1.3=G*G*SLR---****X -G*G*SLR---****X.name=RELEASE LINE -2.X.2.6.2=G*G*SA----****X -G*G*SA----****X.name=AREA -2.X.2.6.2.1=G*G*SAO---****X -G*G*SAO---****X.name=AREA OF OPERATIONS (AO) -2.X.2.6.2.2=G*G*SAA---****X -G*G*SAA---****X.name=AIRHEAD -2.X.2.6.2.3=G*G*SAB---****X -G*G*SAB---****X.name=BRIDGEHEAD -2.X.2.6.2.4=G*G*SAE---****X -G*G*SAE---****X.name=ENCIRCLEMENT -2.X.2.6.2.5=G*G*SAN---****X -G*G*SAN---****X.name=NAMED AREA OF INTEREST (NAI) -2.X.2.6.2.6=G*G*SAT---****X -G*G*SAT---****X.name=TARGETED AREA OF INTEREST (TAI) -2.X.3=G*M*------****X -G*M*------****X.name=MOBILITY/SURVIVABILITY -2.X.3.1=G*M*O-----****X -G*M*O-----****X.name=OBSTACLES -2.X.3.1.1=G*M*OG----****X -G*M*OG----****X.name=GENERAL -2.X.3.1.1.1=G*M*OGB---****X -G*M*OGB---****X.name=BELT -2.X.3.1.1.2=G*M*OGL---****X -G*M*OGL---****X.name=LINE -2.X.3.1.1.3=G*M*OGZ---****X -G*M*OGZ---****X.name=ZONE -2.X.3.1.1.4=G*M*OGF---****X -G*M*OGF---****X.name=OBSTACLE FREE AREA -2.X.3.1.1.5=G*M*OGR---****X -G*M*OGR---****X.name=OBSTACLE RESTRICTED AREA -2.X.3.1.2=G*M*OS----****X -G*M*OS----****X.name=ABATIS -2.X.3.1.3=G*M*OA----****X -G*M*OA----****X.name=ANTITANK OBSTACLES -2.X.3.1.3.1=G*M*OAD---****X -G*M*OAD---****X.name=ANTITANK DITCH -2.X.3.1.3.1.1=G*M*OADU--****X -G*M*OADU--****X.name=UNDER CONSTRUCTION -2.X.3.1.3.1.2=G*M*OADC--****X -G*M*OADC--****X.name=COMPLETE -2.X.3.1.3.2=G*M*OAR---****X -G*M*OAR---****X.name=ANTITANK DITCH REINFORCED WITH ANTITANK MINES -2.X.3.1.3.3=G*M*OAO---****X -G*M*OAO---****X.name=ANTITANK OBSTACLES: TETRAHEDRONS, DRAGONS TEETH, AND OTHER SIMILAR OBSTACLES -2.X.3.1.3.3.1=G*M*OAOF--****X -G*M*OAOF--****X.name=FIXED AND PREFABRICATED -2.X.3.1.3.3.2=G*M*OAOM--****X -G*M*OAOM--****X.name=MOVEABLE -2.X.3.1.3.3.3=G*M*OAOP--****X -G*M*OAOP--****X.name=MOVEABLE AND PREFABRICATED -2.X.3.1.3.4=G*M*OAW---****X -G*M*OAW---****X.name=ANTITANK WALL -2.X.3.1.4=G*M*OB----****X -G*M*OB----****X.name=BOOBY TRAP -2.X.3.1.5=G*M*OM----****X -G*M*OM----****X.name=MINES -2.X.3.1.5.1=G*M*OMU---****X -G*M*OMU---****X.name=UNSPECIFIED MINE -2.X.3.1.5.2=G*M*OMT---****X -G*M*OMT---****X.name=ANTITANK MINE (AT) -2.X.3.1.5.3=G*M*OMD---****X -G*M*OMD---****X.name=ANTITANK MINE WITH ANTIHANDLING DEVICE -2.X.3.1.5.4=G*M*OME---****X -G*M*OME---****X.name=ANTITANK MINE (DIRECTIONAL) -2.X.3.1.5.5=G*M*OMP---****X -G*M*OMP---****X.name=ANTIPERSONNEL (AP) MINES -2.X.3.1.5.6=G*M*OMW---****X -G*M*OMW---****X.name=WIDE AREA MINES -2.X.3.1.5.7=G*M*OMC---****X -G*M*OMC---****X.name=MINE CLUSTER -2.X.3.1.6=G*M*OF----****X -G*M*OF----****X.name=MINEFIELDS -2.X.3.1.6.1=G*M*OFS---****X -G*M*OFS---****X.name=STATIC DEPICTION -2.X.3.1.6.2=G*M*OFD---****X -G*M*OFD---****X.name=DYNAMIC DEPICTION -2.X.3.1.6.3=G*M*OFG---****X -G*M*OFG---****X.name=GAP -2.X.3.1.6.4=G*M*OFA---****X -G*M*OFA---****X.name=MINED AREA -2.X.3.1.7=G*M*OE----****X -G*M*OE----****X.name=OBSTACLE EFFECT -2.X.3.1.7.1=G*M*OEB---****X -G*M*OEB---****X.name=BLOCK -2.X.3.1.7.2=G*M*OEF---****X -G*M*OEF---****X.name=FIX -2.X.3.1.7.3=G*M*OET---****X -G*M*OET---****X.name=TURN -2.X.3.1.7.4=G*M*OED---****X -G*M*OED---****X.name=DISRUPT -2.X.3.1.8=G*M*OU----****X -G*M*OU----****X.name=UNEXPLODED ORDINANCE AREA (UXO) -2.X.3.1.9=G*M*OR----****X -G*M*OR----****X.name=ROADBLOCKS, CRATERS, AND BLOWN BRIDGES -2.X.3.1.9.1=G*M*ORP---****X -G*M*ORP---****X.name=PLANNED -2.X.3.1.9.2=G*M*ORS---****X -G*M*ORS---****X.name=EXPLOSIVES, STATE OF READINESS 1 (SAFE) -2.X.3.1.9.3=G*M*ORA---****X -G*M*ORA---****X.name=EXPLOSIVES, STATE OF READINESS 2 (ARMED-BUT PASSABLE) -2.X.3.1.9.4=G*M*ORC---****X -G*M*ORC---****X.name=ROADBLOCK COMPLETE (EXECUTED) -2.X.3.1.10=G*M*OT----****X -G*M*OT----****X.name=TRIP WIRE -2.X.3.1.11=G*M*OW----****X -G*M*OW----****X.name=WIRE OBSTACLE -2.X.3.1.11.1=GHM*OWU---****X -GHM*OWU---****X.name=UNSPECIFIED -2.X.3.1.11.2=GHM*OWS---****X -GHM*OWS---****X.name=SINGLE FENCE -2.X.3.1.11.3=GFM*OWD---****X -GFM*OWD---****X.name=DOUBLE FENCE -2.X.3.1.11.4=G*M*OWA---****X -G*M*OWA---****X.name=DOUBLE APRON FENCE -2.X.3.1.11.5=G*M*OWL---****X -G*M*OWL---****X.name=LOW WIRE FENCE -2.X.3.1.11.6=G*M*OWH---****X -G*M*OWH---****X.name=HIGH WIRE FENCE -2.X.3.1.11.7=G*M*OWC---****X -G*M*OWC---****X.name=CONCERTINA -2.X.3.1.11.7.1=G*M*OWCS--****X -G*M*OWCS--****X.name=SINGLE CONCERTINA -2.X.3.1.11.7.2=G*M*OWCD--****X -G*M*OWCD--****X.name=DOUBLE STRAND CONCERTINA -2.X.3.1.11.7.3=G*M*OWCT--****X -G*M*OWCT--****X.name=TRIPLE STRAND CONCERTINA -2.X.3.2=G*M*B-----****X -G*M*B-----****X.name=OBSTACLE BYPASS -2.X.3.2.1=G*M*BD----****X -G*M*BD----****X.name=OBSTACLE BYPASS DIFFICULTY -2.X.3.2.1.1=G*M*BDE---****X -G*M*BDE---****X.name=BYPASS EASY -2.X.3.2.1.2=G*M*BDD---****X -G*M*BDD---****X.name=BYPASS DIFFICULT -2.X.3.2.1.3=G*M*BDI---****X -G*M*BDI---****X.name=BYPASS IMPOSSIBLE -2.X.3.2.2=G*M*BC----****X -G*M*BC----****X.name=CROSSING SITE/WATER CROSSING -2.X.3.2.2.1=G*M*BCA---****X -G*M*BCA---****X.name=ASSAULT CROSSING AREA -2.X.3.2.2.2=G*M*BCB---****X -G*M*BCB---****X.name=BRIDGE OR GAP -2.X.3.2.2.3=G*M*BCF---****X -G*M*BCF---****X.name=FERRY -2.X.3.2.2.4=G*M*BCE---****X -G*M*BCE---****X.name=FORD EASY -2.X.3.2.2.5=G*M*BCD---****X -G*M*BCD---****X.name=FORD DIFFICULT -2.X.3.2.2.6=G*M*BCL---****X -G*M*BCL---****X.name=LANE -2.X.3.2.2.7=G*M*BCR---****X -G*M*BCR---****X.name=RAFT SITE -2.X.3.2.2.8=G*M*BCP---****X -G*M*BCP---****X.name=ENGINEER REGULATING POINT -2.X.3.3=G*M*S-----****X -G*M*S-----****X.name=SURVIVABILITY -2.X.3.3.1=G*M*SE----****X -G*M*SE----****X.name=EARTHWORK, SMALL TRENCH OR FORTIFICATION -2.X.3.3.2=G*M*SF----****X -G*M*SF----****X.name=FORT -2.X.3.3.3=G*M*SL----****X -G*M*SL----****X.name=FORTIFIED LINE -2.X.3.3.4=G*M*SW----****X -G*M*SW----****X.name=FOXHOLE, EMPLACEMENT OR WEAPON SITE -2.X.3.3.5=G*M*SP----****X -G*M*SP----****X.name=STRONG POINT -2.X.3.3.6=G*M*SS----****X -G*M*SS----****X.name=SURFACE SHELTER -2.X.3.3.7=G*M*SU----****X -G*M*SU----****X.name=UNDERGROUND SHELTER -2.X.3.4=G*M*N-----****X -G*M*N-----****X.name=NUCLEAR, BIOLOGICAL AND CHEMICAL -2.X.3.4.1=G*M*NM----****X -G*M*NM----****X.name=MINIMUM SAFE DISTANCE ZONES -2.X.3.4.2=G*M*NZ----****X -G*M*NZ----****X.name=NUCLEAR DETINATIONS GROUND ZERO -2.X.3.4.3=G*M*NF----****X -G*M*NF----****X.name=FALLOUT PRODUCING -2.X.3.4.4=G*M*NR----****X -G*M*NR----****X.name=RADIOACTIVE AREA -2.X.3.4.5=G*M*NB----****X -G*M*NB----****X.name=BIOLOGICALLY CONTAMINATED AREA -2.X.3.4.6=G*M*NC----****X -G*M*NC----****X.name=CHEMICALLY CONTAMINATED AREA -2.X.3.4.7=G*M*NE----****X -G*M*NE----****X.name=RELEASE EVENTS -2.X.3.4.7.1=G*M*NEB---****X -G*M*NEB---****X.name=BIOLOGICAL -2.X.3.4.7.2=G*M*NEC---****X -G*M*NEC---****X.name=CHEMICAL -2.X.3.4.8=G*M*ND----****X -G*M*ND----****X.name=DECONTAMINATION (DECON) POINTS -2.X.3.4.8.1=G*M*NDP---****X -G*M*NDP---****X.name=DECON SITE/POINT (UNSPECIFIED) -2.X.3.4.8.2=G*M*NDA---****X -G*M*NDA---****X.name=ALTERNATE DECON SITE/POINT (UNSPECIFIED) -2.X.3.4.8.3=G*M*NDT---****X -G*M*NDT---****X.name=DECON SITE/POINT (TROOPS) -2.X.3.4.8.4=G*M*NDE---****X -G*M*NDE---****X.name=DECON SITE/POINT (EQUIPMENT) -2.X.3.4.8.5=G*M*NDB---****X -G*M*NDB---****X.name=DECON SITE/POINT (EQUIPMENT AND TROOPS) -2.X.3.4.8.6=G*M*NDO---****X -G*M*NDO---****X.name=DECON SITE/POINT (OPERATIONAL DECONTAMINATION) -2.X.3.4.8.7=G*M*NDD---****X -G*M*NDD---****X.name=DECON SITE/POINT (THOROUGH DECONTAMINATION) -2.X.3.4.9=G*M*NL----****X -G*M*NL----****X.name=DOSE RATE CONTOUR LINES -2.X.4=G*F*------****X -G*F*------****X.name=FIRE SUPPORT -2.X.4.1=G*F*P-----****X -G*F*P-----****X.name=POINT -2.X.4.1.1=G*F*PT----****X -G*F*PT----****X.name=TARGET -2.X.4.1.1.1=G*F*PTS---****X -G*F*PTS---****X.name=POINT/SINGLE TARGET -2.X.4.1.1.2=G*F*PTN---****X -G*F*PTN---****X.name=NUCLEAR TARGET -2.X.4.1.1.3=G*F*PTC---****X -G*F*PTC---****X.name=CIRCULAR TARGET -2.X.4.1.1.4=G*F*PTR---****X -G*F*PTR---****X.name=RECTANGULAR TARGET -2.X.4.1.2=G*F*PS----****X -G*F*PS----****X.name=FIRE SUPPORT STATION -2.X.4.2=G*F*L-----****X -G*F*L-----****X.name=LINES -2.X.4.2.1=G*F*LF----****X -G*F*LF----****X.name=FIRE SUPPORT COORDINATION LINE (FSCL) -2.X.4.2.2=G*F*LC----****X -G*F*LC----****X.name=COORDINATED FIRE LINE (CFL) -2.X.4.2.3=G*F*LN----****X -G*F*LN----****X.name=NO-FIRE LINE (NFL) -2.X.4.2.4=G*F*LR----****X -G*F*LR----****X.name=RESTRICTIVE FIRE LINE (RFL) -2.X.4.2.5=G*F*LL----****X -G*F*LL----****X.name=LINEAR TARGET -2.X.4.2.6=G*F*LP----****X -G*F*LP----****X.name=FINAL PROTECTIVE FIRE (FPF) -2.X.4.2.7=G*F*LS----****X -G*F*LS----****X.name=LINEAR SMOKE TARGET -2.X.4.3=G*F*A-----****X -G*F*A-----****X.name=AREAS -2.X.4.3.1=G*F*AA----****X -G*F*AA----****X.name=FIRE SUPPORT AREA (FSA) -2.X.4.3.2=G*F*AC----****X -G*F*AC----****X.name=AIRSPACE COORDINATION AREA (ACA) -2.X.4.3.3=G*F*AT----****X -G*F*AT----****X.name=AREA TARGET -2.X.4.3.4=G*F*AK----****X -G*F*AK----****X.name=SMOKE -2.X.4.3.5=G*F*AS----****X -G*F*AS----****X.name=SERIES OR GROUP OF TARGETS -2.X.4.3.6=G*F*AB----****X -G*F*AB----****X.name=BOMB AREA -2.X.4.3.7=G*F*AF----****X -G*F*AF----****X.name=FREE FIRE AREA (FFA) -2.X.4.3.8=G*F*AN----****X -G*F*AN----****X.name=NO-FIRE AREA (NFA) -2.X.4.3.9=G*F*AR----****X -G*F*AR----****X.name=RESTRICTIVE FIRE AREA (RFA) -2.X.4.3.10=G*F*AP----****X -G*F*AP----****X.name=POSITION AREA FOR ARTILLERY (PAA) -2.X.5=G*S*------****X -G*S*------****X.name=COMBAT SERVICE SUPPORT -2.X.5.1=G*S*P-----****X -G*S*P-----****X.name=POINTS -2.X.5.1.1=G*S*PX----****X -G*S*PX----****X.name=AMBULANCE EXCHANGE POINT -2.X.5.1.2=G*S*PC----****X -G*S*PC----****X.name=CANNIBALIZATION POINT -2.X.5.1.3=G*S*PY----****X -G*S*PY----****X.name=CASUALTY COLLECTION POINT -2.X.5.1.4=G*S*PT----****X -G*S*PT----****X.name=CIVILIAN COLLECTION POINT -2.X.5.1.5=G*S*PD----****X -G*S*PD----****X.name=DETAINEE COLLECTION POINT -2.X.5.1.6=G*S*PE----****X -G*S*PE----****X.name=ENEMY PRISONER OF WAR (EPW) COLLECTION POINT -2.X.5.1.7=G*S*PL----****X -G*S*PL----****X.name=LOGISTICS RELEASE POINT (LRP) -2.X.5.1.8=G*S*PM----****X -G*S*PM----****X.name=MAINTENANCE COLLECTION POINT -2.X.5.1.9=G*S*PR----****X -G*S*PR----****X.name=REARM, REFUEL AND RESUPPLY POINT -2.X.5.1.10=G*S*PU----****X -G*S*PU----****X.name=REFUEL ON THE MOVE (ROM) POINT -2.X.5.1.11=G*S*PO----****X -G*S*PO----****X.name=TRAFFIC CONTROL POST (TCP) -2.X.5.1.12=G*S*PI----****X -G*S*PI----****X.name=TRAILER TRANSFER POINT -2.X.5.1.13=G*S*PN----****X -G*S*PN----****X.name=UNIT MAINTENANCE COLLECTION POINT -2.X.5.1.14=G*S*PS----****X -G*S*PS----****X.name=SUPPLY POINTS -2.X.5.1.14.1=G*S*PSZ---****X -G*S*PSZ---****X.name=GENERAL -2.X.5.1.14.2=G*S*PSA---****X -G*S*PSA---****X.name=CLASS 1 -2.X.5.1.14.3=G*S*PSB---****X -G*S*PSB---****X.name=CLASS II -2.X.5.1.14.4=G*S*PSC---****X -G*S*PSC---****X.name=CLASS III -2.X.5.1.14.5=G*S*PSD---****X -G*S*PSD---****X.name=CLASS IV -2.X.5.1.14.6=G*S*PSE---****X -G*S*PSE---****X.name=CLASS V -2.X.5.1.14.7=G*S*PSF---****X -G*S*PSF---****X.name=CLASS VI -2.X.5.1.14.8=G*S*PSG---****X -G*S*PSG---****X.name=CLASS VII -2.X.5.1.14.9=G*S*PSH---****X -G*S*PSH---****X.name=CLASS VIII -2.X.5.1.14.10=G*S*PSI---****X -G*S*PSI---****X.name=CLASS IX -2.X.5.1.14.11=G*S*PSJ---****X -G*S*PSJ---****X.name=CLASS X -2.X.5.1.15=G*S*PA----****X -G*S*PA----****X.name=AMMUNITION POINTS -2.X.5.1.15.1=G*S*PAS---****X -G*S*PAS---****X.name=AMMUNITION SUPPLY POINT (ASP) -2.X.5.1.15.2=G*S*PAT---****X -G*S*PAT---****X.name=AMMUNITION TRANSFER POINT (ATP) -2.X.5.2=G*S*L-----****X -G*S*L-----****X.name=LINES -2.X.5.2.1=G*S*LC----****X -G*S*LC----****X.name=CONVOYS -2.X.5.2.1.1=G*S*LCM---****X -G*S*LCM---****X.name=MOVING CONVOY -2.X.5.2.1.2=G*S*LCH---****X -G*S*LCH---****X.name=HALTED CONVOY -2.X.5.2.2=G*S*LR----****X -G*S*LR----****X.name=SUPPLY ROUTES -2.X.5.2.2.1=G*S*LRM---****X -G*S*LRM---****X.name=MAIN SUPPLY ROUTE -2.X.5.2.2.2=G*S*LRA---****X -G*S*LRA---****X.name=ALTERNATE SUPPLY ROUTE -2.X.5.2.2.3=G*S*LRO---****X -G*S*LRO---****X.name=ONE-WAY TRAFFIC -2.X.5.2.2.4=G*S*LRT---****X -G*S*LRT---****X.name=ALTERNATING TRAFFIC -2.X.5.2.2.5=G*S*LRW---****X -G*S*LRW---****X.name=TWO-WAY TRAFFIC -2.X.5.3=G*S*A-----****X -G*S*A-----****X.name=AREA -2.X.5.3.1=G*S*AD----****X -G*S*AD----****X.name=DETAINEE HOLDING AREA -2.X.5.3.2=G*S*AE----****X -G*S*AE----****X.name=ENEMY PRISONER OF WAR (EPW) HOLDING AREA -2.X.5.3.3=G*S*AR----****X -G*S*AR----****X.name=FORWARD ARMING AND REFUELING AREA (FARP) -2.X.5.3.4=G*S*AH----****X -G*S*AH----****X.name=REFUGEE HOLDING AREA -2.X.5.3.5=G*S*AS----****X -G*S*AS----****X.name=SUPPORT AREAS -2.X.5.3.5.1=G*S*ASB---****X -G*S*ASB---****X.name=BRIGADE (BSA) -2.X.5.3.5.2=G*S*ASD---****X -G*S*ASD---****X.name=DIVISION (DSA) -2.X.5.3.5.3=G*S*ASR---****X -G*S*ASR---****X.name=REGIMENTAL (RSA) -2.X.6=G*O*------****X -G*O*------****X.name=OTHER -2.X.6.1=G*O*E-----****X -G*O*E-----****X.name=EMERGENCY -2.X.6.1.1=G*O*ED----****X -G*O*ED----****X.name=DITCHED AIRCRAFT -2.X.6.1.2=G*O*EP----****X -G*O*EP----****X.name=PERSON IN WATER -2.X.6.1.3=G*O*EV----****X -G*O*EV----****X.name=DISTRESSED VESSEL -2.X.6.2=G*O*H-----****X -G*O*H-----****X.name=HAZARD -2.X.6.2.1=G*O*HM----****X -G*O*HM----****X.name=SEA MINE-LIKE -2.X.6.2.2=G*O*HN----****X -G*O*HN----****X.name=NAVIGATIONAL -2.X.6.2.3=G*O*HI----****X -G*O*HI----****X.name=ICEBERG -2.X.6.2.4=G*O*HO----****X -G*O*HO----****X.name=OIL RIG -2.X.6.3=G*O*S-----****X -G*O*S-----****X.name=SEA SUBSURFACE RETURNS -2.X.6.3.1=G*O*SB----****X -G*O*SB----****X.name=BOTTOM RETURN/NOMBO -2.X.6.3.1.1=G*O*SBM---****X -G*O*SBM---****X.name=INSTALLATION/MANMADE -2.X.6.3.1.2=G*O*SBN---****X -G*O*SBN---****X.name=SEABED ROCK/STONE, OBSTACLE, OTHER -2.X.6.3.1.3=G*O*SBW---****X -G*O*SBW---****X.name=WRECK -2.X.6.3.2=G*O*SM----****X -G*O*SM----****X.name=MARINE LIFE -2.X.6.3.3=G*O*SS----****X -G*O*SS----****X.name=SEA ANOMALY (WAKE, CURRENT, KNUCKLE) -2.X.6.4=G*O*B-----****X -G*O*B-----****X.name=BEARING LINE -2.X.6.4.1=G*O*BE----****X -G*O*BE----****X.name=ELECTRONIC -2.X.6.4.2=G*O*BA----****X -G*O*BA----****X.name=ACOUSTIC -2.X.6.4.3=G*O*BT----****X -G*O*BT----****X.name=TORPEDO -2.X.6.4.4=G*O*BO----****X -G*O*BO----****X.name=ELECTRO-OPTICAL INTERCEPT -2.X.6.5=G*O*F-----****X -G*O*F-----****X.name=FIX -2.X.6.5.1=G*O*FA----****X -G*O*FA----****X.name=ACOUSTIC -2.X.6.5.2=G*O*FE----****X -G*O*FE----****X.name=ELECTRO-MAGNETIC -2.X.6.5.3=G*O*FO----****X -G*O*FO----****X.name=ELECTRO-OPTICAL -3=W-------------- -W--------------.name=METOC -3.1=WA------------- -WA-------------.name=ATMOSPHERIC -3.1.1=WA--P---------- -WA--P----------.name=PRESSURE SYSTEMS -3.1.1.1=WA--PL--------- -WA--PL---------.name=LOW PRESSURE CENTER -3.1.1.2=WA--PH--------- -WA--PH---------.name=HIGH PRESSURE CENTER -3.1.1.3=WA--PF--------- -WA--PF---------.name=FRONTAL SYSTEMS -3.1.1.3.1=WA--PFC-------- -WA--PFC--------.name=COLD FRONT -3.1.1.3.1.1=WA--PFCU------- -WA--PFCU-------.name=UPPER COLD FRONT -3.1.1.3.2=WA--PFW-------- -WA--PFW--------.name=WARM FRONT -3.1.1.3.2.1=WA--PFWU------- -WA--PFWU-------.name=UPPER WARM FRONT -3.1.1.3.3=WA--PFO-------- -WA--PFO--------.name=OCCLUDED FRONT -3.1.1.3.4=WA--PFS-------- -WA--PFS--------.name=STATIONARY FRONT -3.1.1.4=WA--PX--------- -WA--PX---------.name=LINES -3.1.1.4.1=WA--PXT-------- -WA--PXT--------.name=TROUGH LINE -3.1.1.4.2=WA--PXR-------- -WA--PXR--------.name=RIDGE LINE -3.1.1.4.3=WA--PXS-------- -WA--PXS--------.name=SQUALL LINE -3.1.2=WA--T---------- -WA--T----------.name=TURBULENCE -3.1.2.1=WA--TL--------- -WA--TL---------.name=LIGHT TURBULENCE -3.1.2.2=WA--TM--------- -WA--TM---------.name=MODERATE TURBULENCE -3.1.2.3=WA--TS--------- -WA--TS---------.name=SEVERE TURBULENCE -3.1.2.4=WA--TE--------- -WA--TE---------.name=EXTREME TURBULENCE -3.1.3=WA--I---------- -WA--I----------.name=ICING -3.1.3.1=WA--IC--------- -WA--IC---------.name=CLEAR ICING -3.1.3.1.1=WA--ICL-------- -WA--ICL--------.name=LIGHT CLEAR ICING -3.1.3.1.2=WA--ICM-------- -WA--ICM--------.name=MODERATE CLEAR ICING -3.1.3.1.3=WA--ICS-------- -WA--ICS--------.name=SEVERE CLEAR ICING -3.1.3.2=WA--IR--------- -WA--IR---------.name=RIME ICING -3.1.3.2.1=WA--IRL-------- -WA--IRL--------.name=LIGHT RIME ICING -3.1.3.2.2=WA--IRM-------- -WA--IRM--------.name=MODERATE RIME ICING -3.1.3.2.3=WA--IRS-------- -WA--IRS--------.name=SEVERE RIME ICING -3.1.3.3=WA--IM--------- -WA--IM---------.name=MIXED ICING -3.1.3.3.1=WA--IML-------- -WA--IML--------.name=LIGHT MIXED ICING -3.1.3.3.2=WA--IMM-------- -WA--IMM--------.name=MODERATE MIXED ICING -3.1.3.3.3=WA--IMS-------- -WA--IMS--------.name=SEVERE MIXED ICING -3.1.4=WA--W---------- -WA--W----------.name=WIND BARB -3.1.4.1=WA--WJ--------- -WA--WJ---------.name=JET STREAM -3.1.5=WA--F---------- -WA--F----------.name=FLIGHT RULES -3.1.5.1=WA--FI--------- -WA--FI---------.name=INSTRUMENT CEILING -3.1.5.2=WA--FV--------- -WA--FV---------.name=VISUAL CEILING -3.1.6=WA--C---------- -WA--C----------.name=COVERAGE SYMBOLS -3.1.6.1=WA--CC--------- -WA--CC---------.name=CLEAR SKY (SKC) -3.1.6.2=WA--CS--------- -WA--CS---------.name=SCATTERED SKY (SCT) -3.1.6.3=WA--CB--------- -WA--CB---------.name=BROKEN SKY (BKN) -3.1.6.4=WA--CW--------- -WA--CW---------.name=OVERCAST WITH BREAKS -3.1.6.5=WA--CO--------- -WA--CO---------.name=OVERCAST (OVC) -3.1.6.6=WA--CP--------- -WA--CP---------.name=SKY OBSCURED OR PARTIALLY OBSCURED -3.1.7=WA--R---------- -WA--R----------.name=PRECIPITATION -3.1.7.1=WA--RR--------- -WA--RR---------.name=RAIN (RA) -3.1.7.1.1=WA--RRS-------- -WA--RRS--------.name=RAIN SHOWER -3.1.7.1.2=WA--RRF-------- -WA--RRF--------.name=FREEZING RAIN (FZRA) -3.1.7.1.3=WA--RRD-------- -WA--RRD--------.name=DRIZZLE (DZ) -3.1.7.1.3.1=WA--RRDF------- -WA--RRDF-------.name=FREEZING DRIZZLE (FZDZ) -3.1.7.2=WA--RS--------- -WA--RS---------.name=SNOW(SN) -3.1.7.2.1=WA--RSS-------- -WA--RSS--------.name=SNOW SHOWERS -3.1.7.2.2=WA--RSG-------- -WA--RSG--------.name=SNOW GRAINS (SG) -3.1.7.3=WA--RH--------- -WA--RH---------.name=HAIL -3.1.7.4=WA--RI--------- -WA--RI---------.name=ICE PELLETS (PE) -3.1.7.5=WA--RC--------- -WA--RC---------.name=ICE CRYSTALS (IC) -3.1.8=WA--S---------- -WA--S----------.name=STORMS -3.1.8.1=WA--ST--------- -WA--ST---------.name=THUNDERSTORMS (TS) -3.1.8.1.1=WA--STR-------- -WA--STR--------.name=THUNDERSTORM (TS) WITH RAIN (RA) -3.1.8.1.2=WA--STF-------- -WA--STF--------.name=FUNNEL CLOUD (FC)/TORNADO/WATERSPOUT -3.1.8.1.3=WA--STL-------- -WA--STL--------.name=LIGHTNING (LTG) -3.1.8.2=WA--SS--------- -WA--SS---------.name=STORM SYSTEMS -3.1.8.2.1=WA--SST-------- -WA--SST--------.name=TROPICAL STORM -3.1.8.2.2=WA--SSH-------- -WA--SSH--------.name=HURRICANE -3.1.9=WA--O---------- -WA--O----------.name=OBSTRUCTIONS TO VISIBILITY -3.1.9.1=WA--OS--------- -WA--OS---------.name=BLOWING SNOW (BLSN) -3.1.9.2=WA--OF--------- -WA--OF---------.name=FOG (FG) -3.1.9.2.1=WA--OFF-------- -WA--OFF--------.name=FREEZING FOG (FZFG) -3.1.9.3=WA--OT--------- -WA--OT---------.name=DUST/SAND STORM -3.1.9.4=WA--OD--------- -WA--OD---------.name=DUST DEVIL -3.1.9.5=WA--OK--------- -WA--OK---------.name=SMOKE (FU) -3.1.9.6=WA--OH--------- -WA--OH---------.name=HAZE (HZ) -3.1.9.7=WA--OB--------- -WA--OB---------.name=BLOWING DUST OR SAND -3.2=WO------------- -WO-------------.name=OCEANIC -3.3=WS------------- -WS-------------.name=SPACE -4.X=I-------------- -I--------------.name=SIGNALS INTELLIGENCE -4.X.1=I*P*--------*** -I*P*--------***.name=SPACE TRACK -4.X.1.1=I*P*S-------*** -I*P*S-------***.name=SIGNAL INTERCEPT -4.X.1.1.1=I*P*SC------*** -I*P*SC------***.name=COMMUNICATIONS -4.X.1.1.1.1=I*P*SCD-----*** -I*P*SCD-----***.name=SATELLITE DOWN-LINK -4.X.1.1.2=I*P*SR------*** -I*P*SR------***.name=RADAR -4.X.1.1.2.1=I*P*SRD-----*** -I*P*SRD-----***.name=DATA TRANSMISSION -4.X.1.1.2.2=I*P*SRE-----*** -I*P*SRE-----***.name=EARTH SURVEILLANCE -4.X.1.1.2.3=I*P*SRI-----*** -I*P*SRI-----***.name=IFF (TRANSPONDER) -4.X.1.1.2.4=I*P*SRM-----*** -I*P*SRM-----***.name=MULTI-FUNCTION -4.X.1.1.2.5=I*P*SRT-----*** -I*P*SRT-----***.name=TARGET ACQUISITION -4.X.1.1.2.6=I*P*SRS-----*** -I*P*SRS-----***.name=SPACE -4.X.1.1.2.7=I*P*SRU-----*** -I*P*SRU-----***.name=UNKNOWN -4.X.2=I*A*--------*** -I*A*--------***.name=AIR TRACK -4.X.2.1=I*A*S-------*** -I*A*S-------***.name=SIGNAL INTERCEPT -4.X.2.1.1=I*A*SC------*** -I*A*SC------***.name=COMMUNICATIONS -4.X.2.1.1.1=I*A*SCC-----*** -I*A*SCC-----***.name=CELLULAR/MOBILE -4.X.2.1.1.2=I*A*SCO-----*** -I*A*SCO-----***.name=OMNI-LINE-OF-SIGHT (LOS) -4.X.2.1.1.3=I*A*SCP-----*** -I*A*SCP-----***.name=POINT-TO-POINT LINE-OF-SIGHT (LOS) -4.X.2.1.1.4=I*A*SCS-----*** -I*A*SCS-----***.name=SATELLITE UP-LINK -4.X.2.1.2=I*A*SR------*** -I*A*SR------***.name=RADAR -4.X.2.1.2.1=I*A*SRAI----*** -I*A*SRAI----***.name=AIRBORNE INTERCEPT -4.X.2.1.2.2=I*A*SRAS----*** -I*A*SRAS----***.name=AIRBORNE SEARCH & BOMBING -4.X.2.1.2.3=I*A*SRC-----*** -I*A*SRC-----***.name=CONTROLLED INTERCEPT -4.X.2.1.2.4=I*A*SRD-----*** -I*A*SRD-----***.name=DATA TRANSMISSION -4.X.2.1.2.5=I*A*SRE-----*** -I*A*SRE-----***.name=EARLY WARNING -4.X.2.1.2.6=I*A*SRF-----*** -I*A*SRF-----***.name=FIRE CONTROL -4.X.2.1.2.7=I*A*SRI-----*** -I*A*SRI-----***.name=IFF (TRANSPONDER) -4.X.2.1.2.8=I*A*SRMA----*** -I*A*SRMA----***.name=MISSILE ACQUISITION -4.X.2.1.2.9=I*A*SRMD----*** -I*A*SRMD----***.name=MISSILE DOWNLINK -4.X.2.1.2.10=I*A*SRMG----*** -I*A*SRMG----***.name=MISSILE GUIDANCE -4.X.2.1.2.11=I*A*SRMT----*** -I*A*SRMT----***.name=MISSILE TRACKING -4.X.2.1.2.12=I*A*SRMF----*** -I*A*SRMF----***.name=MULTI-FUNCTION -4.X.2.1.2.13=I*A*SRTI----*** -I*A*SRTI----***.name=TARGET ILLUMINATOR -4.X.2.1.2.14=I*A*SRTA----*** -I*A*SRTA----***.name=TARGET ACQUISITION -4.X.2.1.2.15=I*A*SRTT----*** -I*A*SRTT----***.name=TARGET TRACKING -4.X.2.1.2.16=I*A*SRU-----*** -I*A*SRU-----***.name=UNKNOWN -4.X.3=I*G*--------*** -I*G*--------***.name=GROUND TRACK -4.X.3.1=I*G*S-------*** -I*G*S-------***.name=SIGNAL INTERCEPT -4.X.3.1.1=I*G*SC------*** -I*G*SC------***.name=COMMUNICATIONS -4.X.3.1.1.1=I*G*SCC-----*** -I*G*SCC-----***.name=CELLULAR/MOBILE -4.X.3.1.1.2=I*G*SCO-----*** -I*G*SCO-----***.name=OMNI-LINE-OF-SIGHT (LOS) -4.X.3.1.1.3=I*G*SCP-----*** -I*G*SCP-----***.name=POINT-TO-POINT LINE-OF-SIGHT (LOS) -4.X.3.1.1.4=I*G*SCS-----*** -I*G*SCS-----***.name=SATELLITE UP-LINK -4.X.3.1.1.5=I*G*SCT-----*** -I*G*SCT-----***.name=TROPOSPHERIC SCATTER -4.X.3.1.2=I*G*SR------*** -I*G*SR------***.name=RADAR -4.X.3.1.2.1=I*G*SRAT----*** -I*G*SRAT----***.name=AIR TRAFFIC CONTROL -4.X.3.1.2.2=I*G*SRAA----*** -I*G*SRAA----***.name=ANTI-AIRCRAFT -4.X.3.1.2.3=I*G*SRB-----*** -I*G*SRB-----***.name=BATTLEFIELD SURVEILLANCE -4.X.3.1.2.4=I*G*SRCS----*** -I*G*SRCS----***.name=COASTAL SURVEILLANCE -4.X.3.1.2.5=I*G*SRCA----*** -I*G*SRCA----***.name=CONTROLLED APPROACH -4.X.3.1.2.6=I*G*SRD-----*** -I*G*SRD-----***.name=DATA TRANSMISSION -4.X.3.1.2.7=I*G*SRE-----*** -I*G*SRE-----***.name=EARLY WARNING -4.X.3.1.2.8=I*G*SRF-----*** -I*G*SRF-----***.name=FIRE CONTROL -4.X.3.1.2.9=I*G*SRH-----*** -I*G*SRH-----***.name=HEIGHT FINDING -4.X.3.1.2.10=I*G*SRI-----*** -I*G*SRI-----***.name=IDENTIFICATION FRIEND/FOE (INTERROGATOR) -4.X.3.1.2.11=I*G*SRMM----*** -I*G*SRMM----***.name=METEOROLOGICAL (MILITARY) -4.X.3.1.2.12=I*G*SRMA----*** -I*G*SRMA----***.name=MISSILE ACQUISITION -4.X.3.1.2.13=I*G*SRMG----*** -I*G*SRMG----***.name=MISSILE GUIDANCE -4.X.3.1.2.14=I*G*SRMT----*** -I*G*SRMT----***.name=MISSILE TRACKING -4.X.3.1.2.15=I*G*SRMF----*** -I*G*SRMF----***.name=MULTI-FUNCTION -4.X.3.1.2.16=I*G*SRS-----*** -I*G*SRS-----***.name=SHELL TRACKING -4.X.3.1.2.17=I*G*SRTA----*** -I*G*SRTA----***.name=TARGET ACQUISITION -4.X.3.1.2.18=I*G*SRTI----*** -I*G*SRTI----***.name=TARGET ILLUMINATOR -4.X.3.1.2.19=I*G*SRTT----*** -I*G*SRTT----***.name=TARGET TRACKING -4.X.3.1.2.20=I*G*SRU-----*** -I*G*SRU-----***.name=UNKNOWN -4.X.4=I*S*--------*** -I*S*--------***.name=SEA SURFACE TRACK -4.X.4.1=I*S*S-------*** -I*S*S-------***.name=SIGNAL INTERCEPT -4.X.4.1.1=I*S*SC------*** -I*S*SC------***.name=COMMUNICATIONS -4.X.4.1.1.1=I*S*SCC-----*** -I*S*SCC-----***.name=CELLULAR/MOBILE -4.X.4.1.1.2=I*S*SCO-----*** -I*S*SCO-----***.name=OMNI-LINE-OF-SIGHT (LOS) -4.X.4.1.1.3=I*S*SCP-----*** -I*S*SCP-----***.name=POINT-TO-POINT LINE-OF-SIGHT (LOS) -4.X.4.1.1.4=I*S*SCS-----*** -I*S*SCS-----***.name=SATELLITE UP-LINK -4.X.4.1.2=I*S*SR------*** -I*S*SR------***.name=RADAR -4.X.4.1.2.1=I*S*SRAT----*** -I*S*SRAT----***.name=AIR TRAFFIC CONTROL -4.X.4.1.2.2=I*S*SRAA----*** -I*S*SRAA----***.name=ANTI-AIRCRAFT -4.X.4.1.2.3=I*S*SRCA----*** -I*S*SRCA----***.name=CONTROLLED APPROACH -4.X.4.1.2.4=I*S*SRCI----*** -I*S*SRCI----***.name=CONTROLLED INTERCEPT -4.X.4.1.2.5=I*S*SRD-----*** -I*S*SRD-----***.name=DATA TRANSMISSION -4.X.4.1.2.6=I*S*SRE-----*** -I*S*SRE-----***.name=EARLY WARNING -4.X.4.1.2.7=I*S*SRF-----*** -I*S*SRF-----***.name=FIRE CONTROL -4.X.4.1.2.8=I*S*SRH-----*** -I*S*SRH-----***.name=HEIGHT FINDING -4.X.4.1.2.9=I*S*SRI-----*** -I*S*SRI-----***.name=IDENTIFICATION FRIEND/FOE (INTERROGATOR) -4.X.4.1.2.10=I*S*SRMM----*** -I*S*SRMM----***.name=METEOROLOGICAL (MILITARY) -4.X.4.1.2.11=I*S*SRMA----*** -I*S*SRMA----***.name=MISSILE ACQUISITION -4.X.4.1.2.12=I*S*SRMG----*** -I*S*SRMG----***.name=MISSILE GUIDANCE -4.X.4.1.2.13=I*S*SRMT----*** -I*S*SRMT----***.name=MISSILE TRACKING -4.X.4.1.2.14=I*S*SRMF----*** -I*S*SRMF----***.name=MULTI-FUNCTION -4.X.4.1.2.15=I*S*SRS-----*** -I*S*SRS-----***.name=SURFACE SEARCH -4.X.4.1.2.16=I*S*SRTA----*** -I*S*SRTA----***.name=TARGET ACQUISITION -4.X.4.1.2.17=I*S*SRTI----*** -I*S*SRTI----***.name=TARGET ILLUMINATOR -4.X.4.1.2.18=I*S*SRTT----*** -I*S*SRTT----***.name=TARGET TRACKING -4.X.4.1.2.19=I*S*SRU-----*** -I*S*SRU-----***.name=UNKNOWN -4.X.5=I*U*--------*** -I*U*--------***.name=SUBSURFACE TRACK -4.X.5.1=I*U*S-------*** -I*U*S-------***.name=SIGNAL INTERCEPT -4.X.5.1.1=I*U*SC------*** -I*U*SC------***.name=COMMUNICATIONS -4.X.5.1.1.1=I*U*SCO-----*** -I*U*SCO-----***.name=OMNI-LINE-OF-SIGHT (LOS) -4.X.5.1.1.2=I*U*SCP-----*** -I*U*SCP-----***.name=POINT-TO-POINT LINE-OF-SIGHT (LOS) -4.X.5.1.1.3=I*U*SCS-----*** -I*U*SCS-----***.name=SATELLITE UP-LINK -4.X.5.1.2=I*U*SR------*** -I*U*SR------***.name=RADAR -4.X.5.1.2.1=I*U*SRD-----*** -I*U*SRD-----***.name=DATA TRANSMISSION -4.X.5.1.2.2=I*U*SRE-----*** -I*U*SRE-----***.name=EARLY WARNING -4.X.5.1.2.3=I*U*SRM-----*** -I*U*SRM-----***.name=MULTI-FUNCTION -4.X.5.1.2.4=I*U*SRS-----*** -I*U*SRS-----***.name=SURFACE SEARCH -4.X.5.1.2.5=I*U*SRT-----*** -I*U*SRT-----***.name=TARGET ACQUISITION -4.X.5.1.2.6=I*U*SRU-----*** -I*U*SRU-----***.name=UNKNOWN -5.X=O*--------***** -O*--------*****.name=MILITARY OPERATIONS OTHER THAN WAR (MOOTW) -5.X.1=O*V*------***** -O*V*------*****.name=VIOLENT ACTIVITIES (DEATH CAUSING) -5.X.1.1=O*V*A-----***** -O*V*A-----*****.name=ARSON/FIRE -5.X.1.2=O*V*M-----***** -O*V*M-----*****.name=ASSASSINATION/MURDER/EXECUTION -5.X.1.3=O*V*B-----***** -O*V*B-----*****.name=BOMB/BOMBING -5.X.1.4=O*V*Y-----***** -O*V*Y-----*****.name=BOOBY TRAP -5.X.1.5=O*V*D-----***** -O*V*D-----*****.name=DRIVE-BY SHOOTING -5.X.1.6=O*V*S-----***** -O*V*S-----*****.name=SNIPING -5.X.1.7=O*V*P-----***** -O*V*P-----*****.name=POISONING -5.X.2=O*L*------***** -O*L*------*****.name=LOCATIONS -5.X.2.1=O*L*B-----***** -O*L*B-----*****.name=BLACK LIST LOCATION -5.X.2.2=O*L*G-----***** -O*L*G-----*****.name=GRAY LIST LOCATION -5.X.2.3=O*L*W-----***** -O*L*W-----*****.name=WHITE LIST LOCATION -5.X.3=O*O*------***** -O*O*------*****.name=OPERATIONS -5.X.3.1=O*O*P-----***** -O*O*P-----*****.name=PATROLLING -5.X.3.2=O*O*R-----***** -O*O*R-----*****.name=RECRUITMENT -5.X.3.2.1=O*O*RW----***** -O*O*RW----*****.name=RECRUITMENT (WILLING) -5.X.3.2.2=O*O*RC----***** -O*O*RC----*****.name=RECRUITMENT (COERCED/IMPRESSED) -5.X.3.3=O*O*D-----***** -O*O*D-----*****.name=DEMONSTRATION -5.X.3.4=O*O*M-----***** -O*O*M-----*****.name=MINE LAYING -5.X.3.5=O*O*Y-----***** -O*O*Y-----*****.name=PSYCHOLOGICAL OPERATIONS (PSYOP) -5.X.3.5.1=O*O*YT----***** -O*O*YT----*****.name=PSYOP (TV AND RADIO PROPAGANDA) -5.X.3.5.2=O*O*YW----***** -O*O*YW----*****.name=PSYOP (WRITTEN PROPAGANA) -5.X.3.5.3=O*O*YH----***** -O*O*YH----*****.name=HOUSE-TO-HOUSE PROPAGANDA -5.X.3.6=O*O*F-----***** -O*O*F-----*****.name=FORAGING/SEARCHING -5.X.3.7=O*O*S-----***** -O*O*S-----*****.name=SPY -5.X.3.8=O*O*O-----***** -O*O*O-----*****.name=FOOD DISTRIBUTION -5.X.3.9=O*O*E-----***** -O*O*E-----*****.name=EXTORTION -5.X.3.10=O*O*H-----***** -O*O*H-----*****.name=HIJACKING -5.X.3.10.1=O*O*HT----***** -O*O*HT----*****.name=HIJACKING (VEHICLE) -5.X.3.10.2=O*O*HA----***** -O*O*HA----*****.name=HIJACKING (AIRPLANE) -5.X.3.10.3=O*O*HV----***** -O*O*HV----*****.name=HIJACKING (BOAT) -5.X.3.11=O*O*K-----***** -O*O*K-----*****.name=KIDNAPPING -5.X.3.12=O*O*A-----***** -O*O*A-----*****.name=ARREST -5.X.3.13=O*O*U-----***** -O*O*U-----*****.name=DRUG OPERATION -5.X.4=O*I*------***** -O*I*------*****.name=ITEMS -5.X.4.1=O*I*R-----***** -O*I*R-----*****.name=REFUGEES -5.X.4.2=O*I*S-----***** -O*I*S-----*****.name=SAFE HOUSE -5.X.4.3=O*I*G-----***** -O*I*G-----*****.name=GRAFITTI -5.X.4.4=O*I*V-----***** -O*I*V-----*****.name=VANDALISM/RAPE/LOOT/RANSACK/PLUNDER/SACK -5.X.4.5=O*I*I-----***** -O*I*I-----*****.name=KNOWN INSURGENT VEHICLE -5.X.4.6=O*I*D-----***** -O*I*D-----*****.name=DRUG VEHICLE -5.X.4.7=O*I*F-----***** -O*I*F-----*****.name=INTERNAL SECURITY FORCE diff --git a/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/positions.properties b/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/positions.properties deleted file mode 100644 index 35337189d..000000000 --- a/src/core/src/main/resources/com/bbn/openmap/tools/symbology/milStd2525/positions.properties +++ /dev/null @@ -1,395 +0,0 @@ - -# Schemes (Top level categories for symbols) -scheme.class=com.bbn.openmap.tools.symbology.milStd2525.CodeScheme -scheme.1=S -scheme.S.name=WARFIGHTING -scheme.S.name=C2 Symbology: Units, Equipment and Installations -scheme.S.next=battleDimension -scheme.S.defaultSymbolCode=****------***** -scheme.S.hierarchyCodeAddition=.X -scheme.2=G -scheme.G.name=TACTICAL GRAPHICS -scheme.G.name=C2 Symbology: Military Operations -scheme.G.next=category -scheme.G.defaultSymbolCode=****------****X -scheme.G.hierarchyCodeAddition=.X -scheme.3=W -scheme.W.name=METOC -scheme.W.name=METOC Symbology -scheme.W.next=metoc -scheme.W.defaultSymbolCode=--------------- -scheme.W.hierarchyCodeAddition= -scheme.4=I -scheme.I.name=INTELLIGENCE -scheme.I.name=Signals Intelligence Symbology -scheme.I.next=battleDimension -scheme.I.defaultSymbolCode=****--------*** -scheme.I.hierarchyCodeAddition=.X -scheme.5=O -scheme.O.name=Military Operations Other Than War (MOOTW) -scheme.O.name=Military Operations Other Than War (MOOTW) Symbology -scheme.O.next=mootw -scheme.O.defaultSymbolCode=****------***** -scheme.O.hierarchyCodeAddition=.X -#scheme.6=M -#scheme.M.name=Mapping (reserved - under development) -#scheme.M.next= -#scheme.M.defaultSymbolCode= - -# Affiliation, 2nd position codes -affiliation.class=com.bbn.openmap.tools.symbology.milStd2525.CodeAffiliation -affiliation.1=P -affiliation.P.name=PENDING -affiliation.2=U -affiliation.U.name=UNKNOWN -affiliation.3=A -affiliation.A.name=ASSUMED FRIEND -affiliation.4=F -affiliation.F.name=FRIEND -affiliation.5=N -affiliation.N.name=NEUTRAL -affiliation.6=S -affiliation.S.name=SUSPECT -affiliation.7=H -affiliation.H.name=HOSTILE -affiliation.8=J -affiliation.J.name=JOKER -affiliation.9=K -affiliation.K.name=FAKER -affiliation.10=O -affiliation.O.name=NONE SPECIFIED - -# METOC Category, 2nd position -metoc.class=com.bbn.openmap.tools.symbology.milStd2525.CodeMETOCCategory -metoc.1=A -metoc.A.name=ATMOSPHERIC -metoc.2=O -metoc.O.name=OCEANIC -metoc.3=S -metoc.S.name=SPACE - -# Battle Dimension, 3rd position codes -battleDimension.class=com.bbn.openmap.tools.symbology.milStd2525.CodeBattleDimension -battleDimension.1=P -battleDimension.P.name=SPACE -battleDimension.2=A -battleDimension.A.name=AIR -battleDimension.3=G -battleDimension.G.name=GROUND -battleDimension.4=S -battleDimension.S.name=SEA SURFACE -battleDimension.5=U -battleDimension.U.name=SEA SUBSURFACE -battleDimension.6=F -battleDimension.F.name=SOF -battleDimension.7=X -battleDimension.X.name=OTHER (No frame) - -# MOOTW Categories, 3rd position -mootw.class=com.bbn.openmap.tools.symbology.milStd2525.CodeMOOTWCategory -mootw.1=V -mootw.V.name=VIOLENT ACTIVITIES -mootw.2=L -mootw.L.name=LOCATIONS -mootw.3=O -mootw.O.name=OPERATIONS -mootw.4=I -mootw.I.name=ITEMS - -# General Code Categories, 3rd position for Tactical Graphics -category.class=com.bbn.openmap.tools.symbology.milStd2525.CodeCategory -category.1=T -category.T.name=TASKS -category.2=G -category.G.name=C2 & GENERAL MANEUVER -category.3=M -category.M.name=MOBILITY/SURVIVABILITY -category.4=F -category.F.name=FIRE SUPPORT -category.5=S -category.S.name=COMBAT SERVICE SUPPORT -category.6=O -category.O.name=OTHER - -# Status, 4th position codes -status.class=com.bbn.openmap.tools.symbology.milStd2525.CodeStatus -status.1=A -status.A.name=ANTICIPATED/PLANNED -status.2=P -status.P.name=PRESENT - -# Order of Battle, 15th position codes. -oob.class=com.bbn.openmap.tools.symbology.milStd2525.CodeOrderOfBattle -oob.1=A -oob.A.name=AIR OB -oob.2=E -oob.E.name=ELECTRONIC OB -oob.3=C -oob.C.name=CIVILIAN OB -oob.4=G -oob.G.name=GROUND OB -oob.5=N -oob.N.name=MARITIME OB -oob.6=S -oob.S.name=STRATEGIC FORCE RELATED -# Don't know if we need this one. -#oob.7=X -#oob.X.name=CONTROL MARKINGS - -# Modifiers, 11 & 12 position -modifiers.1=-- -modifiers.--.name=NULL -modifiers.2=-A -modifiers.-A.name=TEAM/CREW -modifiers.3=-B -modifiers.-B.name=SQUAD -modifiers.4=-C -modifiers.-C.name=SECTION -modifiers.5=-D -modifiers.-D.name=PLATOON/DETACHMENT -modifiers.6=-E -modifiers.-E.name=COMPANY/BATTERY/TROOP -modifiers.7=-F -modifiers.-F.name=BATTALION/SQUADRON -modifiers.8=-G -modifiers.-G.name=REGIMENT/GROUP -modifiers.9=-H -modifiers.-H.name=BRIGADE -modifiers.10=-I -modifiers.-I.name=DIVISION -modifiers.11=-J -modifiers.-J.name=CORPS/MEF -modifiers.12=-K -modifiers.-K.name=ARMY -modifiers.13=-L -modifiers.-L.name=ARMY GROUP/FRONT -modifiers.14=-M -modifiers.-M.name=REGION -modifiers.15=A- -modifiers.A-.name=HEADQUARTERS (HQ) -modifiers.16=AA -modifiers.AA.name=HQ TEAM/CREW -modifiers.17=AB -modifiers.AB.name=HQ SQUAD -modifiers.18=AC -modifiers.AC.name=HQ SECTION -modifiers.19=AD -modifiers.AD.name=HQ PLATOON/DETACHMENT -modifiers.20=AE -modifiers.AE.name=HQ COMPANY/BATTERY/TROOP -modifiers.21=AF -modifiers.AF.name=HQ BATTALION/SQUADRON -modifiers.22=AG -modifiers.AG.name=HQ REGIMENT/GROUP -modifiers.23=AH -modifiers.AH.name=HQ BRIGADE AI HQ DIVISION -modifiers.24=AJ -modifiers.AJ.name=HQ CORPS/MEF -modifiers.25=AK -modifiers.AK.name=HQ ARMY -modifiers.26=AL -modifiers.AL.name=HQ ARMY GROUP/FRONT -modifiers.27=AM -modifiers.AM.name=HQ REGION -modifiers.28=B- -modifiers.B-.name=TASK FORCE (TF) HQ -modifiers.29=BA -modifiers.BA.name=TF HQ TEAM/CREW -modifiers.30=BB -modifiers.BB.name=TF HQ SQUAD -modifiers.31=BC -modifiers.BC.name=TF HQ SECTION -modifiers.32=BD -modifiers.BD.name=TF HQ PLATOON/DETACHMENT -modifiers.33=BE -modifiers.BE.name=TF HQ COMPANY/BATTERY/TROOP -modifiers.34=BF -modifiers.BF.name=TF HQ BATTALION/SQUADRON -modifiers.35=BG -modifiers.BG.name=TF HQ REGIMENT/GROUP -modifiers.36=BH -modifiers.BH.name=TF HQ BRIGADE -modifiers.37=BI -modifiers.BI.name=TF HQ DIVISION -modifiers.38=BJ -modifiers.BJ.name=TF HQ CORPS/MEF -modifiers.39=BK -modifiers.BK.name=TF HQ ARMY -modifiers.40=BL -modifiers.BL.name=TF HQ ARMY GROUP/FRONT -modifiers.41=BM -modifiers.BM.name=TF HQ REGION -modifiers.42=C- -modifiers.C-.name=FEINT DUMMY (FD) HQ -modifiers.43=CA -modifiers.CA.name=FD HQ TEAM/CREW -modifiers.44=CB -modifiers.CB.name=FD HQ SQUAD -modifiers.45=CC -modifiers.CC.name=FD HQ SECTION -modifiers.46=CD -modifiers.CD.name=FD HQ PLATOON/DETACHMENT -modifiers.47=CE -modifiers.CE.name=FD HQ COMPANY/BATTERY/TROOP -modifiers.48=CF -modifiers.CF.name=FD HQ BATTALION/SQUADRO -modifiers.49=CG -modifiers.CG.name=FD HQ REGIMENT/GROUP -modifiers.50=CH -modifiers.CH.name=FD HQ BRIGADE -modifiers.51=CI -modifiers.CI.name=FD HQ DIVISION -modifiers.52=CJ -modifiers.CJ.name=FD HQ CORPS/MEF -modifiers.53=CK -modifiers.CK.name=FD HQ ARMY -modifiers.54=CL -modifiers.CL.name=FD HQ ARMY GROUP/FRONT -modifiers.55=CM -modifiers.CM.name=FD HQ REGION -modifiers.56=D- -modifiers.D-.name=FEINT DUMMY/TASK FORCE (FD/TF) HQ -modifiers.57=DA -modifiers.DA.name=FD/TF HQ TEAM/CRE -modifiers.58=DB -modifiers.DB.name=FD/TF HQ SQUAD -modifiers.59=DC -modifiers.DC.name=FD/TF HQ SECTION -modifiers.60=DD -modifiers.DD.name=FD/TF HQ PLATOON/DETACHMENT -modifiers.61=DE -modifiers.DE.name=FD/TF HQ COMPANY/BATTERY/TROOP -modifiers.62=DF -modifiers.DF.name=FD/TF HQ BATTALION/SQUADRON -modifiers.63=DG -modifiers.DG.name=FD/TF HQ REGIMENT/GROUP -modifiers.64=DH -modifiers.DH.name=FD/TF HQ BRIGADE -modifiers.65=DI -modifiers.DI.name=FD/TF HQ DIVISION -modifiers.66=DJ -modifiers.DJ.name=FD/TF HQ CORPS/MEF -modifiers.67=DK -modifiers.DK.name=FD/TF HQ ARMY -modifiers.68=DL -modifiers.DL.name=FD/TF HQ ARMY GROUP/FRONT -modifiers.69=DM -modifiers.DM.name=FD/TF HQ REGION -modifiers.70=E- -modifiers.E-.name=TASK FORCE (TF) -modifiers.71=EA -modifiers.EA.name=TF TEAM/CREW -modifiers.72=EB -modifiers.EB.name=TF SQUAD -modifiers.73=EC -modifiers.EC.name=TF SECTION -modifiers.74=ED -modifiers.ED.name=TF PLATOON/DETACHMENT -modifiers.75=EE -modifiers.EE.name=TF COMPANY/BATTERY/TROOP -modifiers.76=EF -modifiers.EF.name=TF BATTALION/SQUADRON -modifiers.77=EG -modifiers.EG.name=TF REGIMENT/GROUP -modifiers.78=EH -modifiers.EH.name=TF BRIGADE -modifiers.79=EI -modifiers.EI.name=TF DIVISION -modifiers.80=EJ -modifiers.EJ.name=TF CORPS/MEF -modifiers.81=EK -modifiers.EK.name=TF ARMY -modifiers.82=EL -modifiers.EL.name=TF ARMY GROUP/FRONT -modifiers.83=EM -modifiers.EM.name=TF REGION -modifiers.84=F- -modifiers.F-.name=FEINT DUMMY (FD) -modifiers.85=FA -modifiers.FA.name=FD TEAM/CREW -modifiers.86=FB -modifiers.FB.name=FD SQUAD -modifiers.87=FC -modifiers.FC.name=FD SECTION -modifiers.88=FD -modifiers.FD.name=FD PLATOON/DETACHMENT -modifiers.89=FE -modifiers.FE.name=FD COMPANY/BATTERY/TROOP -modifiers.90=FF -modifiers.FF.name=FD BATTALION/SQUADRON -modifiers.91=FG -modifiers.FG.name=FD REGIMENT/GROUP -modifiers.92=FH -modifiers.FH.name=FD BRIGADE -modifiers.93=FI -modifiers.FI.name=FD DIVISION -modifiers.94=FJ -modifiers.FJ.name=FD CORPS/MEF -modifiers.95=FK -modifiers.FK.name=FD ARMY -modifiers.96=FL -modifiers.FL.name=FD ARMY GROUP/FRONT -modifiers.97=FM -modifiers.FM.name=FD REGION -modifiers.98=G- -modifiers.G-.name=FEINT DUMMY/TASK FORCE (FD/TF) -modifiers.99=GA -modifiers.GA.name=FD/TF TEAM/CREW -modifiers.100=GB -modifiers.GB.name=FD/TF SQUAD -modifiers.101=GC -modifiers.GC.name=FD/TF SECTION -modifiers.102=GD -modifiers.GD.name=FD/TF PLATOON/DETACHMENT -modifiers.103=GE -modifiers.GE.name=FD/TF COMPANY/BATTERY/TROOP -modifiers.104=GF -modifiers.GF.name=FD/TF BATTALION/SQUADRON -modifiers.105=GG -modifiers.GG.name=FD/TF REGIMENT/GROUP -modifiers.106=GH -modifiers.GH.name=FD/TF BRIGADE -modifiers.107=GI -modifiers.GI.name=FD/TF DIVISION -modifiers.108=GJ -modifiers.GJ.name=FD/TF CORPS/MEF -modifiers.109=GK -modifiers.GK.name=FD/TF ARMY -modifiers.110=GL -modifiers.GL.name=FD/TF ARMY GROUP/FRONT -modifiers.111=GM -modifiers.GM.name=FD/TF REGION -modifiers.112=H- -modifiers.H-.name=INSTALLATION -modifiers.113=HB -modifiers.HB.name=FEINT DUMMY INSTALLATION -modifiers.114=M- -modifiers.M-.name=MOBILITY EQUIPMENT -modifiers.115=MO -modifiers.MO.name=MOBILITY WHEELED/LIMITED CROSS COUNTR -modifiers.116=MP -modifiers.MP.name=MOBILITY CROSS COUNTRY -modifiers.117=MQ -modifiers.MQ.name=MOBILITY TRACKED -modifiers.118=MR -modifiers.MR.name=MOBILITY WHEELED AND TRACKED COMBINATION -modifiers.119=MS -modifiers.MS.name=MOBILITY TOWED -modifiers.120=MT -modifiers.MT.name=MOBILITY RAIL -modifiers.121=MU -modifiers.MU.name=MOBILITY OVER THE SNOW -modifiers.122=MV -modifiers.MV.name=MOBILITY SLED -modifiers.123=MW -modifiers.MW.name=MOBILITY PACK ANIMALS -modifiers.124=MX -modifiers.MX.name=MOBILITY BARGE -modifiers.125=MY -modifiers.MY.name=MOBILITY AMPHIBIOUS -modifiers.126=NS -modifiers.NS.name=TOWED ARRAY (SHORT) -modifiers.127=NL -modifiers.NL.name=TOWED ARRAY (LONG) -modifiers.128=K- -modifiers.K-.name=NUCLEAR YIELD IN KILOTONS diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_datum.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_datum.properties deleted file mode 100644 index d011d0145..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_datum.properties +++ /dev/null @@ -1,168 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - DatumE_Airy1830 = 6001 - DatumE_AiryModified1849 = 6002 - DatumE_AustralianNationalSpheroid = 6003 - DatumE_Bessel1841 = 6004 - DatumE_BesselModified = 6005 - DatumE_BesselNamibia = 6006 - DatumE_Clarke1858 = 6007 - DatumE_Clarke1866 = 6008 - DatumE_Clarke1866Michigan = 6009 - DatumE_Clarke1880_Benoit = 6010 - DatumE_Clarke1880_IGN = 6011 - DatumE_Clarke1880_RGS = 6012 - DatumE_Clarke1880_Arc = 6013 - DatumE_Clarke1880_SGA1922 = 6014 - DatumE_Everest1830_1937Adjustment = 6015 - DatumE_Everest1830_1967Definition = 6016 - DatumE_Everest1830_1975Definition = 6017 - DatumE_Everest1830Modified = 6018 - DatumE_GRS1980 = 6019 - DatumE_Helmert1906 = 6020 - DatumE_IndonesianNationalSpheroid = 6021 - DatumE_International1924 = 6022 - DatumE_International1967 = 6023 - DatumE_Krassowsky1960 = 6024 - DatumE_NWL9D = 6025 - DatumE_NWL10D = 6026 - DatumE_Plessis1817 = 6027 - DatumE_Struve1860 = 6028 - DatumE_WarOffice = 6029 - DatumE_WGS84 = 6030 - DatumE_GEM10C = 6031 - DatumE_OSU86F = 6032 - DatumE_OSU91A = 6033 - DatumE_Clarke1880 = 6034 - DatumE_Sphere = 6035 - Datum_Adindan = 6201 - Datum_Australian_Geodetic_Datum_1966 = 6202 - Datum_Australian_Geodetic_Datum_1984 = 6203 - Datum_Ain_el_Abd_1970 = 6204 - Datum_Afgooye = 6205 - Datum_Agadez = 6206 - Datum_Lisbon = 6207 - Datum_Aratu = 6208 - Datum_Arc_1950 = 6209 - Datum_Arc_1960 = 6210 - Datum_Batavia = 6211 - Datum_Barbados = 6212 - Datum_Beduaram = 6213 - Datum_Beijing_1954 = 6214 - Datum_Reseau_National_Belge_1950 = 6215 - Datum_Bermuda_1957 = 6216 - Datum_Bern_1898 = 6217 - Datum_Bogota = 6218 - Datum_Bukit_Rimpah = 6219 - Datum_Camacupa = 6220 - Datum_Campo_Inchauspe = 6221 - Datum_Cape = 6222 - Datum_Carthage = 6223 - Datum_Chua = 6224 - Datum_Corrego_Alegre = 6225 - Datum_Cote_d_Ivoire = 6226 - Datum_Deir_ez_Zor = 6227 - Datum_Douala = 6228 - Datum_Egypt_1907 = 6229 - Datum_European_Datum_1950 = 6230 - Datum_European_Datum_1987 = 6231 - Datum_Fahud = 6232 - Datum_Gandajika_1970 = 6233 - Datum_Garoua = 6234 - Datum_Guyane_Francaise = 6235 - Datum_Hu_Tzu_Shan = 6236 - Datum_Hungarian_Datum_1972 = 6237 - Datum_Indonesian_Datum_1974 = 6238 - Datum_Indian_1954 = 6239 - Datum_Indian_1975 = 6240 - Datum_Jamaica_1875 = 6241 - Datum_Jamaica_1969 = 6242 - Datum_Kalianpur = 6243 - Datum_Kandawala = 6244 - Datum_Kertau = 6245 - Datum_Kuwait_Oil_Company = 6246 - Datum_La_Canoa = 6247 - Datum_Provisional_S_American_Datum_1956 = 6248 - Datum_Lake = 6249 - Datum_Leigon = 6250 - Datum_Liberia_1964 = 6251 - Datum_Lome = 6252 - Datum_Luzon_1911 = 6253 - Datum_Hito_XVIII_1963 = 6254 - Datum_Herat_North = 6255 - Datum_Mahe_1971 = 6256 - Datum_Makassar = 6257 - Datum_European_Reference_System_1989 = 6258 - Datum_Malongo_1987 = 6259 - Datum_Manoca = 6260 - Datum_Merchich = 6261 - Datum_Massawa = 6262 - Datum_Minna = 6263 - Datum_Mhast = 6264 - Datum_Monte_Mario = 6265 - Datum_M_poraloko = 6266 - Datum_North_American_Datum_1927 = 6267 - Datum_NAD_Michigan = 6268 - Datum_North_American_Datum_1983 = 6269 - Datum_Nahrwan_1967 = 6270 - Datum_Naparima_1972 = 6271 - Datum_New_Zealand_Geodetic_Datum_1949 = 6272 - Datum_NGO_1948 = 6273 - Datum_Datum_73 = 6274 - Datum_Nouvelle_Triangulation_Francaise = 6275 - Datum_NSWC_9Z_2 = 6276 - Datum_OSGB_1936 = 6277 - Datum_OSGB_1970_SN = 6278 - Datum_OS_SN_1980 = 6279 - Datum_Padang_1884 = 6280 - Datum_Palestine_1923 = 6281 - Datum_Pointe_Noire = 6282 - Datum_Geocentric_Datum_of_Australia_1994 = 6283 - Datum_Pulkovo_1942 = 6284 - Datum_Qatar = 6285 - Datum_Qatar_1948 = 6286 - Datum_Qornoq = 6287 - Datum_Loma_Quintana = 6288 - Datum_Amersfoort = 6289 - Datum_RT38 = 6290 - Datum_South_American_Datum_1969 = 6291 - Datum_Sapper_Hill_1943 = 6292 - Datum_Schwarzeck = 6293 - Datum_Segora = 6294 - Datum_Serindung = 6295 - Datum_Sudan = 6296 - Datum_Tananarive_1925 = 6297 - Datum_Timbalai_1948 = 6298 - Datum_TM65 = 6299 - Datum_TM75 = 6300 - Datum_Tokyo = 6301 - Datum_Trinidad_1903 = 6302 - Datum_Trucial_Coast_1948 = 6303 - Datum_Voirol_1875 = 6304 - Datum_Voirol_Unifie_1960 = 6305 - Datum_Bern_1938 = 6306 - Datum_Nord_Sahara_1959 = 6307 - Datum_Stockholm_1938 = 6308 - Datum_Yacare = 6309 - Datum_Yoff = 6310 - Datum_Zanderij = 6311 - Datum_Militar_Geographische_Institut = 6312 - Datum_Reseau_National_Belge_1972 = 6313 - Datum_Deutsche_Hauptdreiecksnetz = 6314 - Datum_Conakry_1905 = 6315 - Datum_WGS72 = 6322 - Datum_WGS72_Transit_Broadcast_Ephemeris = 6324 - Datum_WGS84 = 6326 - Datum_Ancienne_Triangulation_Francaise = 6901 - Datum_Nord_de_Guerre = 6902 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_ellipse.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_ellipse.properties deleted file mode 100644 index 44dd2ed13..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_ellipse.properties +++ /dev/null @@ -1,48 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - Ellipse_Airy_1830 = 7001 - Ellipse_Airy_Modified_1849 = 7002 - Ellipse_Australian_National_Spheroid = 7003 - Ellipse_Bessel_1841 = 7004 - Ellipse_Bessel_Modified = 7005 - Ellipse_Bessel_Namibia = 7006 - Ellipse_Clarke_1858 = 7007 - Ellipse_Clarke_1866 = 7008 - Ellipse_Clarke_1866_Michigan = 7009 - Ellipse_Clarke_1880_Benoit = 7010 - Ellipse_Clarke_1880_IGN = 7011 - Ellipse_Clarke_1880_RGS = 7012 - Ellipse_Clarke_1880_Arc = 7013 - Ellipse_Clarke_1880_SGA_1922 = 7014 - Ellipse_Everest_1830_1937_Adjustment = 7015 - Ellipse_Everest_1830_1967_Definition = 7016 - Ellipse_Everest_1830_1975_Definition = 7017 - Ellipse_Everest_1830_Modified = 7018 - Ellipse_GRS_1980 = 7019 - Ellipse_Helmert_1906 = 7020 - Ellipse_Indonesian_National_Spheroid = 7021 - Ellipse_International_1924 = 7022 - Ellipse_International_1967 = 7023 - Ellipse_Krassowsky_1940 = 7024 - Ellipse_NWL_9D = 7025 - Ellipse_NWL_10D = 7026 - Ellipse_Plessis_1817 = 7027 - Ellipse_Struve_1860 = 7028 - Ellipse_War_Office = 7029 - Ellipse_WGS_84 = 7030 - Ellipse_GEM_10C = 7031 - Ellipse_OSU86F = 7032 - Ellipse_OSU91A = 7033 - Ellipse_Clarke_1880 = 7034 - Ellipse_Sphere = 7035 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_gcs.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_gcs.properties deleted file mode 100644 index 98c4f6405..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_gcs.properties +++ /dev/null @@ -1,181 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - GCSE_Airy1830 = 4001 - GCSE_AiryModified1849 = 4002 - GCSE_AustralianNationalSpheroid = 4003 - GCSE_Bessel1841 = 4004 - GCSE_BesselModified = 4005 - GCSE_BesselNamibia = 4006 - GCSE_Clarke1858 = 4007 - GCSE_Clarke1866 = 4008 - GCSE_Clarke1866Michigan = 4009 - GCSE_Clarke1880_Benoit = 4010 - GCSE_Clarke1880_IGN = 4011 - GCSE_Clarke1880_RGS = 4012 - GCSE_Clarke1880_Arc = 4013 - GCSE_Clarke1880_SGA1922 = 4014 - GCSE_Everest1830_1937Adjustment = 4015 - GCSE_Everest1830_1967Definition = 4016 - GCSE_Everest1830_1975Definition = 4017 - GCSE_Everest1830Modified = 4018 - GCSE_GRS1980 = 4019 - GCSE_Helmert1906 = 4020 - GCSE_IndonesianNationalSpheroid = 4021 - GCSE_International1924 = 4022 - GCSE_International1967 = 4023 - GCSE_Krassowsky1940 = 4024 - GCSE_NWL9D = 4025 - GCSE_NWL10D = 4026 - GCSE_Plessis1817 = 4027 - GCSE_Struve1860 = 4028 - GCSE_WarOffice = 4029 - GCSE_WGS84 = 4030 - GCSE_GEM10C = 4031 - GCSE_OSU86F = 4032 - GCSE_OSU91A = 4033 - GCSE_Clarke1880 = 4034 - GCSE_Sphere = 4035 - GCS_Adindan = 4201 - GCS_AGD66 = 4202 - GCS_AGD84 = 4203 - GCS_Ain_el_Abd = 4204 - GCS_Afgooye = 4205 - GCS_Agadez = 4206 - GCS_Lisbon = 4207 - GCS_Aratu = 4208 - GCS_Arc_1950 = 4209 - GCS_Arc_1960 = 4210 - GCS_Batavia = 4211 - GCS_Barbados = 4212 - GCS_Beduaram = 4213 - GCS_Beijing_1954 = 4214 - GCS_Belge_1950 = 4215 - GCS_Bermuda_1957 = 4216 - GCS_Bern_1898 = 4217 - GCS_Bogota = 4218 - GCS_Bukit_Rimpah = 4219 - GCS_Camacupa = 4220 - GCS_Campo_Inchauspe = 4221 - GCS_Cape = 4222 - GCS_Carthage = 4223 - GCS_Chua = 4224 - GCS_Corrego_Alegre = 4225 - GCS_Cote_d_Ivoire = 4226 - GCS_Deir_ez_Zor = 4227 - GCS_Douala = 4228 - GCS_Egypt_1907 = 4229 - GCS_ED50 = 4230 - GCS_ED87 = 4231 - GCS_Fahud = 4232 - GCS_Gandajika_1970 = 4233 - GCS_Garoua = 4234 - GCS_Guyane_Francaise = 4235 - GCS_Hu_Tzu_Shan = 4236 - GCS_HD72 = 4237 - GCS_ID74 = 4238 - GCS_Indian_1954 = 4239 - GCS_Indian_1975 = 4240 - GCS_Jamaica_1875 = 4241 - GCS_JAD69 = 4242 - GCS_Kalianpur = 4243 - GCS_Kandawala = 4244 - GCS_Kertau = 4245 - GCS_KOC = 4246 - GCS_La_Canoa = 4247 - GCS_PSAD56 = 4248 - GCS_Lake = 4249 - GCS_Leigon = 4250 - GCS_Liberia_1964 = 4251 - GCS_Lome = 4252 - GCS_Luzon_1911 = 4253 - GCS_Hito_XVIII_1963 = 4254 - GCS_Herat_North = 4255 - GCS_Mahe_1971 = 4256 - GCS_Makassar = 4257 - GCS_EUREF89 = 4258 - GCS_Malongo_1987 = 4259 - GCS_Manoca = 4260 - GCS_Merchich = 4261 - GCS_Massawa = 4262 - GCS_Minna = 4263 - GCS_Mhast = 4264 - GCS_Monte_Mario = 4265 - GCS_M_poraloko = 4266 - GCS_NAD27 = 4267 - GCS_NAD_Michigan = 4268 - GCS_NAD83 = 4269 - GCS_Nahrwan_1967 = 4270 - GCS_Naparima_1972 = 4271 - GCS_GD49 = 4272 - GCS_NGO_1948 = 4273 - GCS_Datum_73 = 4274 - GCS_NTF = 4275 - GCS_NSWC_9Z_2 = 4276 - GCS_OSGB_1936 = 4277 - GCS_OSGB70 = 4278 - GCS_OS_SN80 = 4279 - GCS_Padang = 4280 - GCS_Palestine_1923 = 4281 - GCS_Pointe_Noire = 4282 - GCS_GDA94 = 4283 - GCS_Pulkovo_1942 = 4284 - GCS_Qatar = 4285 - GCS_Qatar_1948 = 4286 - GCS_Qornoq = 4287 - GCS_Loma_Quintana = 4288 - GCS_Amersfoort = 4289 - GCS_RT38 = 4290 - GCS_SAD69 = 4291 - GCS_Sapper_Hill_1943 = 4292 - GCS_Schwarzeck = 4293 - GCS_Segora = 4294 - GCS_Serindung = 4295 - GCS_Sudan = 4296 - GCS_Tananarive = 4297 - GCS_Timbalai_1948 = 4298 - GCS_TM65 = 4299 - GCS_TM75 = 4300 - GCS_Tokyo = 4301 - GCS_Trinidad_1903 = 4302 - GCS_TC_1948 = 4303 - GCS_Voirol_1875 = 4304 - GCS_Voirol_Unifie = 4305 - GCS_Bern_1938 = 4306 - GCS_Nord_Sahara_1959 = 4307 - GCS_Stockholm_1938 = 4308 - GCS_Yacare = 4309 - GCS_Yoff = 4310 - GCS_Zanderij = 4311 - GCS_MGI = 4312 - GCS_Belge_1972 = 4313 - GCS_DHDN = 4314 - GCS_Conakry_1905 = 4315 - GCS_WGS_72 = 4322 - GCS_WGS_72BE = 4324 - GCS_WGS_84 = 4326 - GCS_Bern_1898_Bern = 4801 - GCS_Bogota_Bogota = 4802 - GCS_Lisbon_Lisbon = 4803 - GCS_Makassar_Jakarta = 4804 - GCS_MGI_Ferro = 4805 - GCS_Monte_Mario_Rome = 4806 - GCS_NTF_Paris = 4807 - GCS_Padang_Jakarta = 4808 - GCS_Belge_1950_Brussels = 4809 - GCS_Tananarive_Paris = 4810 - GCS_Voirol_1875_Paris = 4811 - GCS_Voirol_Unifie_Paris = 4812 - GCS_Batavia_Jakarta = 4813 - GCS_ATF_Paris = 4901 - GCS_NDG_Paris = 4902 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_pcs.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_pcs.properties deleted file mode 100644 index 1a3735679..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_pcs.properties +++ /dev/null @@ -1,991 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - PCS_Adindan_UTM_zone_37N = 20137 - PCS_Adindan_UTM_zone_38N = 20138 - PCS_AGD66_AMG_zone_48 = 20248 - PCS_AGD66_AMG_zone_49 = 20249 - PCS_AGD66_AMG_zone_50 = 20250 - PCS_AGD66_AMG_zone_51 = 20251 - PCS_AGD66_AMG_zone_52 = 20252 - PCS_AGD66_AMG_zone_53 = 20253 - PCS_AGD66_AMG_zone_54 = 20254 - PCS_AGD66_AMG_zone_55 = 20255 - PCS_AGD66_AMG_zone_56 = 20256 - PCS_AGD66_AMG_zone_57 = 20257 - PCS_AGD66_AMG_zone_58 = 20258 - PCS_AGD84_AMG_zone_48 = 20348 - PCS_AGD84_AMG_zone_49 = 20349 - PCS_AGD84_AMG_zone_50 = 20350 - PCS_AGD84_AMG_zone_51 = 20351 - PCS_AGD84_AMG_zone_52 = 20352 - PCS_AGD84_AMG_zone_53 = 20353 - PCS_AGD84_AMG_zone_54 = 20354 - PCS_AGD84_AMG_zone_55 = 20355 - PCS_AGD84_AMG_zone_56 = 20356 - PCS_AGD84_AMG_zone_57 = 20357 - PCS_AGD84_AMG_zone_58 = 20358 - PCS_Ain_el_Abd_UTM_zone_37N = 20437 - PCS_Ain_el_Abd_UTM_zone_38N = 20438 - PCS_Ain_el_Abd_UTM_zone_39N = 20439 - PCS_Ain_el_Abd_Bahrain_Grid = 20499 - PCS_Afgooye_UTM_zone_38N = 20538 - PCS_Afgooye_UTM_zone_39N = 20539 - PCS_Lisbon_Portugese_Grid = 20700 - PCS_Aratu_UTM_zone_22S = 20822 - PCS_Aratu_UTM_zone_23S = 20823 - PCS_Aratu_UTM_zone_24S = 20824 - PCS_Arc_1950_Lo13 = 20973 - PCS_Arc_1950_Lo15 = 20975 - PCS_Arc_1950_Lo17 = 20977 - PCS_Arc_1950_Lo19 = 20979 - PCS_Arc_1950_Lo21 = 20981 - PCS_Arc_1950_Lo23 = 20983 - PCS_Arc_1950_Lo25 = 20985 - PCS_Arc_1950_Lo27 = 20987 - PCS_Arc_1950_Lo29 = 20989 - PCS_Arc_1950_Lo31 = 20991 - PCS_Arc_1950_Lo33 = 20993 - PCS_Arc_1950_Lo35 = 20995 - PCS_Batavia_NEIEZ = 21100 - PCS_Batavia_UTM_zone_48S = 21148 - PCS_Batavia_UTM_zone_49S = 21149 - PCS_Batavia_UTM_zone_50S = 21150 - PCS_Beijing_Gauss_zone_13 = 21413 - PCS_Beijing_Gauss_zone_14 = 21414 - PCS_Beijing_Gauss_zone_15 = 21415 - PCS_Beijing_Gauss_zone_16 = 21416 - PCS_Beijing_Gauss_zone_17 = 21417 - PCS_Beijing_Gauss_zone_18 = 21418 - PCS_Beijing_Gauss_zone_19 = 21419 - PCS_Beijing_Gauss_zone_20 = 21420 - PCS_Beijing_Gauss_zone_21 = 21421 - PCS_Beijing_Gauss_zone_22 = 21422 - PCS_Beijing_Gauss_zone_23 = 21423 - PCS_Beijing_Gauss_13N = 21473 - PCS_Beijing_Gauss_14N = 21474 - PCS_Beijing_Gauss_15N = 21475 - PCS_Beijing_Gauss_16N = 21476 - PCS_Beijing_Gauss_17N = 21477 - PCS_Beijing_Gauss_18N = 21478 - PCS_Beijing_Gauss_19N = 21479 - PCS_Beijing_Gauss_20N = 21480 - PCS_Beijing_Gauss_21N = 21481 - PCS_Beijing_Gauss_22N = 21482 - PCS_Beijing_Gauss_23N = 21483 - PCS_Belge_Lambert_50 = 21500 - PCS_Bern_1898_Swiss_Old = 21790 - PCS_Bogota_UTM_zone_17N = 21817 - PCS_Bogota_UTM_zone_18N = 21818 - PCS_Bogota_Colombia_3W = 21891 - PCS_Bogota_Colombia_Bogota = 21892 - PCS_Bogota_Colombia_3E = 21893 - PCS_Bogota_Colombia_6E = 21894 - PCS_Camacupa_UTM_32S = 22032 - PCS_Camacupa_UTM_33S = 22033 - PCS_C_Inchauspe_Argentina_1 = 22191 - PCS_C_Inchauspe_Argentina_2 = 22192 - PCS_C_Inchauspe_Argentina_3 = 22193 - PCS_C_Inchauspe_Argentina_4 = 22194 - PCS_C_Inchauspe_Argentina_5 = 22195 - PCS_C_Inchauspe_Argentina_6 = 22196 - PCS_C_Inchauspe_Argentina_7 = 22197 - PCS_Carthage_UTM_zone_32N = 22332 - PCS_Carthage_Nord_Tunisie = 22391 - PCS_Carthage_Sud_Tunisie = 22392 - PCS_Corrego_Alegre_UTM_23S = 22523 - PCS_Corrego_Alegre_UTM_24S = 22524 - PCS_Douala_UTM_zone_32N = 22832 - PCS_Egypt_1907_Red_Belt = 22992 - PCS_Egypt_1907_Purple_Belt = 22993 - PCS_Egypt_1907_Ext_Purple = 22994 - PCS_ED50_UTM_zone_28N = 23028 - PCS_ED50_UTM_zone_29N = 23029 - PCS_ED50_UTM_zone_30N = 23030 - PCS_ED50_UTM_zone_31N = 23031 - PCS_ED50_UTM_zone_32N = 23032 - PCS_ED50_UTM_zone_33N = 23033 - PCS_ED50_UTM_zone_34N = 23034 - PCS_ED50_UTM_zone_35N = 23035 - PCS_ED50_UTM_zone_36N = 23036 - PCS_ED50_UTM_zone_37N = 23037 - PCS_ED50_UTM_zone_38N = 23038 - PCS_Fahud_UTM_zone_39N = 23239 - PCS_Fahud_UTM_zone_40N = 23240 - PCS_Garoua_UTM_zone_33N = 23433 - PCS_ID74_UTM_zone_46N = 23846 - PCS_ID74_UTM_zone_47N = 23847 - PCS_ID74_UTM_zone_48N = 23848 - PCS_ID74_UTM_zone_49N = 23849 - PCS_ID74_UTM_zone_50N = 23850 - PCS_ID74_UTM_zone_51N = 23851 - PCS_ID74_UTM_zone_52N = 23852 - PCS_ID74_UTM_zone_53N = 23853 - PCS_ID74_UTM_zone_46S = 23886 - PCS_ID74_UTM_zone_47S = 23887 - PCS_ID74_UTM_zone_48S = 23888 - PCS_ID74_UTM_zone_49S = 23889 - PCS_ID74_UTM_zone_50S = 23890 - PCS_ID74_UTM_zone_51S = 23891 - PCS_ID74_UTM_zone_52S = 23892 - PCS_ID74_UTM_zone_53S = 23893 - PCS_ID74_UTM_zone_54S = 23894 - PCS_Indian_1954_UTM_47N = 23947 - PCS_Indian_1954_UTM_48N = 23948 - PCS_Indian_1975_UTM_47N = 24047 - PCS_Indian_1975_UTM_48N = 24048 - PCS_Jamaica_1875_Old_Grid = 24100 - PCS_JAD69_Jamaica_Grid = 24200 - PCS_Kalianpur_India_0 = 24370 - PCS_Kalianpur_India_I = 24371 - PCS_Kalianpur_India_IIa = 24372 - PCS_Kalianpur_India_IIIa = 24373 - PCS_Kalianpur_India_IVa = 24374 - PCS_Kalianpur_India_IIb = 24382 - PCS_Kalianpur_India_IIIb = 24383 - PCS_Kalianpur_India_IVb = 24384 - PCS_Kertau_Singapore_Grid = 24500 - PCS_Kertau_UTM_zone_47N = 24547 - PCS_Kertau_UTM_zone_48N = 24548 - PCS_La_Canoa_UTM_zone_20N = 24720 - PCS_La_Canoa_UTM_zone_21N = 24721 - PCS_PSAD56_UTM_zone_18N = 24818 - PCS_PSAD56_UTM_zone_19N = 24819 - PCS_PSAD56_UTM_zone_20N = 24820 - PCS_PSAD56_UTM_zone_21N = 24821 - PCS_PSAD56_UTM_zone_17S = 24877 - PCS_PSAD56_UTM_zone_18S = 24878 - PCS_PSAD56_UTM_zone_19S = 24879 - PCS_PSAD56_UTM_zone_20S = 24880 - PCS_PSAD56_Peru_west_zone = 24891 - PCS_PSAD56_Peru_central = 24892 - PCS_PSAD56_Peru_east_zone = 24893 - PCS_Leigon_Ghana_Grid = 25000 - PCS_Lome_UTM_zone_31N = 25231 - PCS_Luzon_Philippines_I = 25391 - PCS_Luzon_Philippines_II = 25392 - PCS_Luzon_Philippines_III = 25393 - PCS_Luzon_Philippines_IV = 25394 - PCS_Luzon_Philippines_V = 25395 - PCS_Makassar_NEIEZ = 25700 - PCS_Malongo_1987_UTM_32S = 25932 - PCS_Merchich_Nord_Maroc = 26191 - PCS_Merchich_Sud_Maroc = 26192 - PCS_Merchich_Sahara = 26193 - PCS_Massawa_UTM_zone_37N = 26237 - PCS_Minna_UTM_zone_31N = 26331 - PCS_Minna_UTM_zone_32N = 26332 - PCS_Minna_Nigeria_West = 26391 - PCS_Minna_Nigeria_Mid_Belt = 26392 - PCS_Minna_Nigeria_East = 26393 - PCS_Mhast_UTM_zone_32S = 26432 - PCS_Monte_Mario_Italy_1 = 26591 - PCS_Monte_Mario_Italy_2 = 26592 - PCS_M_poraloko_UTM_32N = 26632 - PCS_M_poraloko_UTM_32S = 26692 - PCS_NAD27_UTM_zone_3N = 26703 - PCS_NAD27_UTM_zone_4N = 26704 - PCS_NAD27_UTM_zone_5N = 26705 - PCS_NAD27_UTM_zone_6N = 26706 - PCS_NAD27_UTM_zone_7N = 26707 - PCS_NAD27_UTM_zone_8N = 26708 - PCS_NAD27_UTM_zone_9N = 26709 - PCS_NAD27_UTM_zone_10N = 26710 - PCS_NAD27_UTM_zone_11N = 26711 - PCS_NAD27_UTM_zone_12N = 26712 - PCS_NAD27_UTM_zone_13N = 26713 - PCS_NAD27_UTM_zone_14N = 26714 - PCS_NAD27_UTM_zone_15N = 26715 - PCS_NAD27_UTM_zone_16N = 26716 - PCS_NAD27_UTM_zone_17N = 26717 - PCS_NAD27_UTM_zone_18N = 26718 - PCS_NAD27_UTM_zone_19N = 26719 - PCS_NAD27_UTM_zone_20N = 26720 - PCS_NAD27_UTM_zone_21N = 26721 - PCS_NAD27_UTM_zone_22N = 26722 - PCS_NAD27_Alabama_East = 26729 - PCS_NAD27_Alabama_West = 26730 - PCS_NAD27_Alaska_zone_1 = 26731 - PCS_NAD27_Alaska_zone_2 = 26732 - PCS_NAD27_Alaska_zone_3 = 26733 - PCS_NAD27_Alaska_zone_4 = 26734 - PCS_NAD27_Alaska_zone_5 = 26735 - PCS_NAD27_Alaska_zone_6 = 26736 - PCS_NAD27_Alaska_zone_7 = 26737 - PCS_NAD27_Alaska_zone_8 = 26738 - PCS_NAD27_Alaska_zone_9 = 26739 - PCS_NAD27_Alaska_zone_10 = 26740 - PCS_NAD27_California_I = 26741 - PCS_NAD27_California_II = 26742 - PCS_NAD27_California_III = 26743 - PCS_NAD27_California_IV = 26744 - PCS_NAD27_California_V = 26745 - PCS_NAD27_California_VI = 26746 - PCS_NAD27_California_VII = 26747 - PCS_NAD27_Arizona_East = 26748 - PCS_NAD27_Arizona_Central = 26749 - PCS_NAD27_Arizona_West = 26750 - PCS_NAD27_Arkansas_North = 26751 - PCS_NAD27_Arkansas_South = 26752 - PCS_NAD27_Colorado_North = 26753 - PCS_NAD27_Colorado_Central = 26754 - PCS_NAD27_Colorado_South = 26755 - PCS_NAD27_Connecticut = 26756 - PCS_NAD27_Delaware = 26757 - PCS_NAD27_Florida_East = 26758 - PCS_NAD27_Florida_West = 26759 - PCS_NAD27_Florida_North = 26760 - PCS_NAD27_Hawaii_zone_1 = 26761 - PCS_NAD27_Hawaii_zone_2 = 26762 - PCS_NAD27_Hawaii_zone_3 = 26763 - PCS_NAD27_Hawaii_zone_4 = 26764 - PCS_NAD27_Hawaii_zone_5 = 26765 - PCS_NAD27_Georgia_East = 26766 - PCS_NAD27_Georgia_West = 26767 - PCS_NAD27_Idaho_East = 26768 - PCS_NAD27_Idaho_Central = 26769 - PCS_NAD27_Idaho_West = 26770 - PCS_NAD27_Illinois_East = 26771 - PCS_NAD27_Illinois_West = 26772 - PCS_NAD27_Indiana_East = 26773 - PCS_NAD27_BLM_14N_feet = 26774 - PCS_NAD27_Indiana_West = 26774 - PCS_NAD27_BLM_15N_feet = 26775 - PCS_NAD27_Iowa_North = 26775 - PCS_NAD27_BLM_16N_feet = 26776 - PCS_NAD27_Iowa_South = 26776 - PCS_NAD27_BLM_17N_feet = 26777 - PCS_NAD27_Kansas_North = 26777 - PCS_NAD27_Kansas_South = 26778 - PCS_NAD27_Kentucky_North = 26779 - PCS_NAD27_Kentucky_South = 26780 - PCS_NAD27_Louisiana_North = 26781 - PCS_NAD27_Louisiana_South = 26782 - PCS_NAD27_Maine_East = 26783 - PCS_NAD27_Maine_West = 26784 - PCS_NAD27_Maryland = 26785 - PCS_NAD27_Massachusetts = 26786 - PCS_NAD27_Massachusetts_Is = 26787 - PCS_NAD27_Michigan_North = 26788 - PCS_NAD27_Michigan_Central = 26789 - PCS_NAD27_Michigan_South = 26790 - PCS_NAD27_Minnesota_North = 26791 - PCS_NAD27_Minnesota_Cent = 26792 - PCS_NAD27_Minnesota_South = 26793 - PCS_NAD27_Mississippi_East = 26794 - PCS_NAD27_Mississippi_West = 26795 - PCS_NAD27_Missouri_East = 26796 - PCS_NAD27_Missouri_Central = 26797 - PCS_NAD27_Missouri_West = 26798 - PCS_NAD_Michigan_Michigan_East = 26801 - PCS_NAD_Michigan_Michigan_Old_Central = 26802 - PCS_NAD_Michigan_Michigan_West = 26803 - PCS_NAD83_UTM_zone_3N = 26903 - PCS_NAD83_UTM_zone_4N = 26904 - PCS_NAD83_UTM_zone_5N = 26905 - PCS_NAD83_UTM_zone_6N = 26906 - PCS_NAD83_UTM_zone_7N = 26907 - PCS_NAD83_UTM_zone_8N = 26908 - PCS_NAD83_UTM_zone_9N = 26909 - PCS_NAD83_UTM_zone_10N = 26910 - PCS_NAD83_UTM_zone_11N = 26911 - PCS_NAD83_UTM_zone_12N = 26912 - PCS_NAD83_UTM_zone_13N = 26913 - PCS_NAD83_UTM_zone_14N = 26914 - PCS_NAD83_UTM_zone_15N = 26915 - PCS_NAD83_UTM_zone_16N = 26916 - PCS_NAD83_UTM_zone_17N = 26917 - PCS_NAD83_UTM_zone_18N = 26918 - PCS_NAD83_UTM_zone_19N = 26919 - PCS_NAD83_UTM_zone_20N = 26920 - PCS_NAD83_UTM_zone_21N = 26921 - PCS_NAD83_UTM_zone_22N = 26922 - PCS_NAD83_UTM_zone_23N = 26923 - PCS_NAD83_Alabama_East = 26929 - PCS_NAD83_Alabama_West = 26930 - PCS_NAD83_Alaska_zone_1 = 26931 - PCS_NAD83_Alaska_zone_2 = 26932 - PCS_NAD83_Alaska_zone_3 = 26933 - PCS_NAD83_Alaska_zone_4 = 26934 - PCS_NAD83_Alaska_zone_5 = 26935 - PCS_NAD83_Alaska_zone_6 = 26936 - PCS_NAD83_Alaska_zone_7 = 26937 - PCS_NAD83_Alaska_zone_8 = 26938 - PCS_NAD83_Alaska_zone_9 = 26939 - PCS_NAD83_Alaska_zone_10 = 26940 - PCS_NAD83_California_1 = 26941 - PCS_NAD83_California_2 = 26942 - PCS_NAD83_California_3 = 26943 - PCS_NAD83_California_4 = 26944 - PCS_NAD83_California_5 = 26945 - PCS_NAD83_California_6 = 26946 - PCS_NAD83_Arizona_East = 26948 - PCS_NAD83_Arizona_Central = 26949 - PCS_NAD83_Arizona_West = 26950 - PCS_NAD83_Arkansas_North = 26951 - PCS_NAD83_Arkansas_South = 26952 - PCS_NAD83_Colorado_North = 26953 - PCS_NAD83_Colorado_Central = 26954 - PCS_NAD83_Colorado_South = 26955 - PCS_NAD83_Connecticut = 26956 - PCS_NAD83_Delaware = 26957 - PCS_NAD83_Florida_East = 26958 - PCS_NAD83_Florida_West = 26959 - PCS_NAD83_Florida_North = 26960 - PCS_NAD83_Hawaii_zone_1 = 26961 - PCS_NAD83_Hawaii_zone_2 = 26962 - PCS_NAD83_Hawaii_zone_3 = 26963 - PCS_NAD83_Hawaii_zone_4 = 26964 - PCS_NAD83_Hawaii_zone_5 = 26965 - PCS_NAD83_Georgia_East = 26966 - PCS_NAD83_Georgia_West = 26967 - PCS_NAD83_Idaho_East = 26968 - PCS_NAD83_Idaho_Central = 26969 - PCS_NAD83_Idaho_West = 26970 - PCS_NAD83_Illinois_East = 26971 - PCS_NAD83_Illinois_West = 26972 - PCS_NAD83_Indiana_East = 26973 - PCS_NAD83_Indiana_West = 26974 - PCS_NAD83_Iowa_North = 26975 - PCS_NAD83_Iowa_South = 26976 - PCS_NAD83_Kansas_North = 26977 - PCS_NAD83_Kansas_South = 26978 - PCS_NAD83_Kentucky_North = 26979 - PCS_NAD83_Kentucky_South = 26980 - PCS_NAD83_Louisiana_North = 26981 - PCS_NAD83_Louisiana_South = 26982 - PCS_NAD83_Maine_East = 26983 - PCS_NAD83_Maine_West = 26984 - PCS_NAD83_Maryland = 26985 - PCS_NAD83_Massachusetts = 26986 - PCS_NAD83_Massachusetts_Is = 26987 - PCS_NAD83_Michigan_North = 26988 - PCS_NAD83_Michigan_Central = 26989 - PCS_NAD83_Michigan_South = 26990 - PCS_NAD83_Minnesota_North = 26991 - PCS_NAD83_Minnesota_Cent = 26992 - PCS_NAD83_Minnesota_South = 26993 - PCS_NAD83_Mississippi_East = 26994 - PCS_NAD83_Mississippi_West = 26995 - PCS_NAD83_Missouri_East = 26996 - PCS_NAD83_Missouri_Central = 26997 - PCS_NAD83_Missouri_West = 26998 - PCS_Nahrwan_1967_UTM_38N = 27038 - PCS_Nahrwan_1967_UTM_39N = 27039 - PCS_Nahrwan_1967_UTM_40N = 27040 - PCS_Naparima_UTM_20N = 27120 - PCS_GD49_NZ_Map_Grid = 27200 - PCS_GD49_North_Island_Grid = 27291 - PCS_GD49_South_Island_Grid = 27292 - PCS_Datum_73_UTM_zone_29N = 27429 - PCS_ATF_Nord_de_Guerre = 27500 - PCS_NTF_France_I = 27581 - PCS_NTF_France_II = 27582 - PCS_NTF_France_III = 27583 - PCS_NTF_Nord_France = 27591 - PCS_NTF_Centre_France = 27592 - PCS_NTF_Sud_France = 27593 - PCS_British_National_Grid = 27700 - PCS_Point_Noire_UTM_32S = 28232 - PCS_GDA94_MGA_zone_48 = 28348 - PCS_GDA94_MGA_zone_49 = 28349 - PCS_GDA94_MGA_zone_50 = 28350 - PCS_GDA94_MGA_zone_51 = 28351 - PCS_GDA94_MGA_zone_52 = 28352 - PCS_GDA94_MGA_zone_53 = 28353 - PCS_GDA94_MGA_zone_54 = 28354 - PCS_GDA94_MGA_zone_55 = 28355 - PCS_GDA94_MGA_zone_56 = 28356 - PCS_GDA94_MGA_zone_57 = 28357 - PCS_GDA94_MGA_zone_58 = 28358 - PCS_Pulkovo_Gauss_zone_4 = 28404 - PCS_Pulkovo_Gauss_zone_5 = 28405 - PCS_Pulkovo_Gauss_zone_6 = 28406 - PCS_Pulkovo_Gauss_zone_7 = 28407 - PCS_Pulkovo_Gauss_zone_8 = 28408 - PCS_Pulkovo_Gauss_zone_9 = 28409 - PCS_Pulkovo_Gauss_zone_10 = 28410 - PCS_Pulkovo_Gauss_zone_11 = 28411 - PCS_Pulkovo_Gauss_zone_12 = 28412 - PCS_Pulkovo_Gauss_zone_13 = 28413 - PCS_Pulkovo_Gauss_zone_14 = 28414 - PCS_Pulkovo_Gauss_zone_15 = 28415 - PCS_Pulkovo_Gauss_zone_16 = 28416 - PCS_Pulkovo_Gauss_zone_17 = 28417 - PCS_Pulkovo_Gauss_zone_18 = 28418 - PCS_Pulkovo_Gauss_zone_19 = 28419 - PCS_Pulkovo_Gauss_zone_20 = 28420 - PCS_Pulkovo_Gauss_zone_21 = 28421 - PCS_Pulkovo_Gauss_zone_22 = 28422 - PCS_Pulkovo_Gauss_zone_23 = 28423 - PCS_Pulkovo_Gauss_zone_24 = 28424 - PCS_Pulkovo_Gauss_zone_25 = 28425 - PCS_Pulkovo_Gauss_zone_26 = 28426 - PCS_Pulkovo_Gauss_zone_27 = 28427 - PCS_Pulkovo_Gauss_zone_28 = 28428 - PCS_Pulkovo_Gauss_zone_29 = 28429 - PCS_Pulkovo_Gauss_zone_30 = 28430 - PCS_Pulkovo_Gauss_zone_31 = 28431 - PCS_Pulkovo_Gauss_zone_32 = 28432 - PCS_Pulkovo_Gauss_4N = 28464 - PCS_Pulkovo_Gauss_5N = 28465 - PCS_Pulkovo_Gauss_6N = 28466 - PCS_Pulkovo_Gauss_7N = 28467 - PCS_Pulkovo_Gauss_8N = 28468 - PCS_Pulkovo_Gauss_9N = 28469 - PCS_Pulkovo_Gauss_10N = 28470 - PCS_Pulkovo_Gauss_11N = 28471 - PCS_Pulkovo_Gauss_12N = 28472 - PCS_Pulkovo_Gauss_13N = 28473 - PCS_Pulkovo_Gauss_14N = 28474 - PCS_Pulkovo_Gauss_15N = 28475 - PCS_Pulkovo_Gauss_16N = 28476 - PCS_Pulkovo_Gauss_17N = 28477 - PCS_Pulkovo_Gauss_18N = 28478 - PCS_Pulkovo_Gauss_19N = 28479 - PCS_Pulkovo_Gauss_20N = 28480 - PCS_Pulkovo_Gauss_21N = 28481 - PCS_Pulkovo_Gauss_22N = 28482 - PCS_Pulkovo_Gauss_23N = 28483 - PCS_Pulkovo_Gauss_24N = 28484 - PCS_Pulkovo_Gauss_25N = 28485 - PCS_Pulkovo_Gauss_26N = 28486 - PCS_Pulkovo_Gauss_27N = 28487 - PCS_Pulkovo_Gauss_28N = 28488 - PCS_Pulkovo_Gauss_29N = 28489 - PCS_Pulkovo_Gauss_30N = 28490 - PCS_Pulkovo_Gauss_31N = 28491 - PCS_Pulkovo_Gauss_32N = 28492 - PCS_Qatar_National_Grid = 28600 - PCS_RD_Netherlands_Old = 28991 - PCS_RD_Netherlands_New = 28992 - PCS_SAD69_UTM_zone_18N = 29118 - PCS_SAD69_UTM_zone_19N = 29119 - PCS_SAD69_UTM_zone_20N = 29120 - PCS_SAD69_UTM_zone_21N = 29121 - PCS_SAD69_UTM_zone_22N = 29122 - PCS_SAD69_UTM_zone_17S = 29177 - PCS_SAD69_UTM_zone_18S = 29178 - PCS_SAD69_UTM_zone_19S = 29179 - PCS_SAD69_UTM_zone_20S = 29180 - PCS_SAD69_UTM_zone_21S = 29181 - PCS_SAD69_UTM_zone_22S = 29182 - PCS_SAD69_UTM_zone_23S = 29183 - PCS_SAD69_UTM_zone_24S = 29184 - PCS_SAD69_UTM_zone_25S = 29185 - PCS_Sapper_Hill_UTM_20S = 29220 - PCS_Sapper_Hill_UTM_21S = 29221 - PCS_Schwarzeck_UTM_33S = 29333 - PCS_Sudan_UTM_zone_35N = 29635 - PCS_Sudan_UTM_zone_36N = 29636 - PCS_Tananarive_Laborde = 29700 - PCS_Tananarive_UTM_38S = 29738 - PCS_Tananarive_UTM_39S = 29739 - PCS_Timbalai_1948_Borneo = 29800 - PCS_Timbalai_1948_UTM_49N = 29849 - PCS_Timbalai_1948_UTM_50N = 29850 - PCS_TM65_Irish_Nat_Grid = 29900 - PCS_Trinidad_1903_Trinidad = 30200 - PCS_TC_1948_UTM_zone_39N = 30339 - PCS_TC_1948_UTM_zone_40N = 30340 - PCS_Voirol_N_Algerie_ancien = 30491 - PCS_Voirol_S_Algerie_ancien = 30492 - PCS_Voirol_Unifie_N_Algerie = 30591 - PCS_Voirol_Unifie_S_Algerie = 30592 - PCS_Bern_1938_Swiss_New = 30600 - PCS_Nord_Sahara_UTM_29N = 30729 - PCS_Nord_Sahara_UTM_30N = 30730 - PCS_Nord_Sahara_UTM_31N = 30731 - PCS_Nord_Sahara_UTM_32N = 30732 - PCS_Yoff_UTM_zone_28N = 31028 - PCS_Zanderij_UTM_zone_21N = 31121 - PCS_MGI_Austria_West = 31291 - PCS_MGI_Austria_Central = 31292 - PCS_MGI_Austria_East = 31293 - PCS_Belge_Lambert_72 = 31300 - PCS_DHDN_Germany_zone_1 = 31491 - PCS_DHDN_Germany_zone_2 = 31492 - PCS_DHDN_Germany_zone_3 = 31493 - PCS_DHDN_Germany_zone_4 = 31494 - PCS_DHDN_Germany_zone_5 = 31495 - PCS_NAD27_Montana_North = 32001 - PCS_NAD27_Montana_Central = 32002 - PCS_NAD27_Montana_South = 32003 - PCS_NAD27_Nebraska_North = 32005 - PCS_NAD27_Nebraska_South = 32006 - PCS_NAD27_Nevada_East = 32007 - PCS_NAD27_Nevada_Central = 32008 - PCS_NAD27_Nevada_West = 32009 - PCS_NAD27_New_Hampshire = 32010 - PCS_NAD27_New_Jersey = 32011 - PCS_NAD27_New_Mexico_East = 32012 - PCS_NAD27_New_Mexico_Cent = 32013 - PCS_NAD27_New_Mexico_West = 32014 - PCS_NAD27_New_York_East = 32015 - PCS_NAD27_New_York_Central = 32016 - PCS_NAD27_New_York_West = 32017 - PCS_NAD27_New_York_Long_Is = 32018 - PCS_NAD27_North_Carolina = 32019 - PCS_NAD27_North_Dakota_N = 32020 - PCS_NAD27_North_Dakota_S = 32021 - PCS_NAD27_Ohio_North = 32022 - PCS_NAD27_Ohio_South = 32023 - PCS_NAD27_Oklahoma_North = 32024 - PCS_NAD27_Oklahoma_South = 32025 - PCS_NAD27_Oregon_North = 32026 - PCS_NAD27_Oregon_South = 32027 - PCS_NAD27_Pennsylvania_N = 32028 - PCS_NAD27_Pennsylvania_S = 32029 - PCS_NAD27_Rhode_Island = 32030 - PCS_NAD27_South_Carolina_N = 32031 - PCS_NAD27_South_Carolina_S = 32033 - PCS_NAD27_South_Dakota_N = 32034 - PCS_NAD27_South_Dakota_S = 32035 - PCS_NAD27_Tennessee = 32036 - PCS_NAD27_Texas_North = 32037 - PCS_NAD27_Texas_North_Cen = 32038 - PCS_NAD27_Texas_Central = 32039 - PCS_NAD27_Texas_South_Cen = 32040 - PCS_NAD27_Texas_South = 32041 - PCS_NAD27_Utah_North = 32042 - PCS_NAD27_Utah_Central = 32043 - PCS_NAD27_Utah_South = 32044 - PCS_NAD27_Vermont = 32045 - PCS_NAD27_Virginia_North = 32046 - PCS_NAD27_Virginia_South = 32047 - PCS_NAD27_Washington_North = 32048 - PCS_NAD27_Washington_South = 32049 - PCS_NAD27_West_Virginia_N = 32050 - PCS_NAD27_West_Virginia_S = 32051 - PCS_NAD27_Wisconsin_North = 32052 - PCS_NAD27_Wisconsin_Cen = 32053 - PCS_NAD27_Wisconsin_South = 32054 - PCS_NAD27_Wyoming_East = 32055 - PCS_NAD27_Wyoming_E_Cen = 32056 - PCS_NAD27_Wyoming_W_Cen = 32057 - PCS_NAD27_Wyoming_West = 32058 - PCS_NAD27_Puerto_Rico = 32059 - PCS_NAD27_St_Croix = 32060 - PCS_NAD83_Montana = 32100 - PCS_NAD83_Nebraska = 32104 - PCS_NAD83_Nevada_East = 32107 - PCS_NAD83_Nevada_Central = 32108 - PCS_NAD83_Nevada_West = 32109 - PCS_NAD83_New_Hampshire = 32110 - PCS_NAD83_New_Jersey = 32111 - PCS_NAD83_New_Mexico_East = 32112 - PCS_NAD83_New_Mexico_Cent = 32113 - PCS_NAD83_New_Mexico_West = 32114 - PCS_NAD83_New_York_East = 32115 - PCS_NAD83_New_York_Central = 32116 - PCS_NAD83_New_York_West = 32117 - PCS_NAD83_New_York_Long_Is = 32118 - PCS_NAD83_North_Carolina = 32119 - PCS_NAD83_North_Dakota_N = 32120 - PCS_NAD83_North_Dakota_S = 32121 - PCS_NAD83_Ohio_North = 32122 - PCS_NAD83_Ohio_South = 32123 - PCS_NAD83_Oklahoma_North = 32124 - PCS_NAD83_Oklahoma_South = 32125 - PCS_NAD83_Oregon_North = 32126 - PCS_NAD83_Oregon_South = 32127 - PCS_NAD83_Pennsylvania_N = 32128 - PCS_NAD83_Pennsylvania_S = 32129 - PCS_NAD83_Rhode_Island = 32130 - PCS_NAD83_South_Carolina = 32133 - PCS_NAD83_South_Dakota_N = 32134 - PCS_NAD83_South_Dakota_S = 32135 - PCS_NAD83_Tennessee = 32136 - PCS_NAD83_Texas_North = 32137 - PCS_NAD83_Texas_North_Cen = 32138 - PCS_NAD83_Texas_Central = 32139 - PCS_NAD83_Texas_South_Cen = 32140 - PCS_NAD83_Texas_South = 32141 - PCS_NAD83_Utah_North = 32142 - PCS_NAD83_Utah_Central = 32143 - PCS_NAD83_Utah_South = 32144 - PCS_NAD83_Vermont = 32145 - PCS_NAD83_Virginia_North = 32146 - PCS_NAD83_Virginia_South = 32147 - PCS_NAD83_Washington_North = 32148 - PCS_NAD83_Washington_South = 32149 - PCS_NAD83_West_Virginia_N = 32150 - PCS_NAD83_West_Virginia_S = 32151 - PCS_NAD83_Wisconsin_North = 32152 - PCS_NAD83_Wisconsin_Cen = 32153 - PCS_NAD83_Wisconsin_South = 32154 - PCS_NAD83_Wyoming_East = 32155 - PCS_NAD83_Wyoming_E_Cen = 32156 - PCS_NAD83_Wyoming_W_Cen = 32157 - PCS_NAD83_Wyoming_West = 32158 - PCS_NAD83_Puerto_Rico_Virgin_Is = 32161 - PCS_WGS72_UTM_zone_1N = 32201 - PCS_WGS72_UTM_zone_2N = 32202 - PCS_WGS72_UTM_zone_3N = 32203 - PCS_WGS72_UTM_zone_4N = 32204 - PCS_WGS72_UTM_zone_5N = 32205 - PCS_WGS72_UTM_zone_6N = 32206 - PCS_WGS72_UTM_zone_7N = 32207 - PCS_WGS72_UTM_zone_8N = 32208 - PCS_WGS72_UTM_zone_9N = 32209 - PCS_WGS72_UTM_zone_10N = 32210 - PCS_WGS72_UTM_zone_11N = 32211 - PCS_WGS72_UTM_zone_12N = 32212 - PCS_WGS72_UTM_zone_13N = 32213 - PCS_WGS72_UTM_zone_14N = 32214 - PCS_WGS72_UTM_zone_15N = 32215 - PCS_WGS72_UTM_zone_16N = 32216 - PCS_WGS72_UTM_zone_17N = 32217 - PCS_WGS72_UTM_zone_18N = 32218 - PCS_WGS72_UTM_zone_19N = 32219 - PCS_WGS72_UTM_zone_20N = 32220 - PCS_WGS72_UTM_zone_21N = 32221 - PCS_WGS72_UTM_zone_22N = 32222 - PCS_WGS72_UTM_zone_23N = 32223 - PCS_WGS72_UTM_zone_24N = 32224 - PCS_WGS72_UTM_zone_25N = 32225 - PCS_WGS72_UTM_zone_26N = 32226 - PCS_WGS72_UTM_zone_27N = 32227 - PCS_WGS72_UTM_zone_28N = 32228 - PCS_WGS72_UTM_zone_29N = 32229 - PCS_WGS72_UTM_zone_30N = 32230 - PCS_WGS72_UTM_zone_31N = 32231 - PCS_WGS72_UTM_zone_32N = 32232 - PCS_WGS72_UTM_zone_33N = 32233 - PCS_WGS72_UTM_zone_34N = 32234 - PCS_WGS72_UTM_zone_35N = 32235 - PCS_WGS72_UTM_zone_36N = 32236 - PCS_WGS72_UTM_zone_37N = 32237 - PCS_WGS72_UTM_zone_38N = 32238 - PCS_WGS72_UTM_zone_39N = 32239 - PCS_WGS72_UTM_zone_40N = 32240 - PCS_WGS72_UTM_zone_41N = 32241 - PCS_WGS72_UTM_zone_42N = 32242 - PCS_WGS72_UTM_zone_43N = 32243 - PCS_WGS72_UTM_zone_44N = 32244 - PCS_WGS72_UTM_zone_45N = 32245 - PCS_WGS72_UTM_zone_46N = 32246 - PCS_WGS72_UTM_zone_47N = 32247 - PCS_WGS72_UTM_zone_48N = 32248 - PCS_WGS72_UTM_zone_49N = 32249 - PCS_WGS72_UTM_zone_50N = 32250 - PCS_WGS72_UTM_zone_51N = 32251 - PCS_WGS72_UTM_zone_52N = 32252 - PCS_WGS72_UTM_zone_53N = 32253 - PCS_WGS72_UTM_zone_54N = 32254 - PCS_WGS72_UTM_zone_55N = 32255 - PCS_WGS72_UTM_zone_56N = 32256 - PCS_WGS72_UTM_zone_57N = 32257 - PCS_WGS72_UTM_zone_58N = 32258 - PCS_WGS72_UTM_zone_59N = 32259 - PCS_WGS72_UTM_zone_60N = 32260 - PCS_WGS72_UTM_zone_1S = 32301 - PCS_WGS72_UTM_zone_2S = 32302 - PCS_WGS72_UTM_zone_3S = 32303 - PCS_WGS72_UTM_zone_4S = 32304 - PCS_WGS72_UTM_zone_5S = 32305 - PCS_WGS72_UTM_zone_6S = 32306 - PCS_WGS72_UTM_zone_7S = 32307 - PCS_WGS72_UTM_zone_8S = 32308 - PCS_WGS72_UTM_zone_9S = 32309 - PCS_WGS72_UTM_zone_10S = 32310 - PCS_WGS72_UTM_zone_11S = 32311 - PCS_WGS72_UTM_zone_12S = 32312 - PCS_WGS72_UTM_zone_13S = 32313 - PCS_WGS72_UTM_zone_14S = 32314 - PCS_WGS72_UTM_zone_15S = 32315 - PCS_WGS72_UTM_zone_16S = 32316 - PCS_WGS72_UTM_zone_17S = 32317 - PCS_WGS72_UTM_zone_18S = 32318 - PCS_WGS72_UTM_zone_19S = 32319 - PCS_WGS72_UTM_zone_20S = 32320 - PCS_WGS72_UTM_zone_21S = 32321 - PCS_WGS72_UTM_zone_22S = 32322 - PCS_WGS72_UTM_zone_23S = 32323 - PCS_WGS72_UTM_zone_24S = 32324 - PCS_WGS72_UTM_zone_25S = 32325 - PCS_WGS72_UTM_zone_26S = 32326 - PCS_WGS72_UTM_zone_27S = 32327 - PCS_WGS72_UTM_zone_28S = 32328 - PCS_WGS72_UTM_zone_29S = 32329 - PCS_WGS72_UTM_zone_30S = 32330 - PCS_WGS72_UTM_zone_31S = 32331 - PCS_WGS72_UTM_zone_32S = 32332 - PCS_WGS72_UTM_zone_33S = 32333 - PCS_WGS72_UTM_zone_34S = 32334 - PCS_WGS72_UTM_zone_35S = 32335 - PCS_WGS72_UTM_zone_36S = 32336 - PCS_WGS72_UTM_zone_37S = 32337 - PCS_WGS72_UTM_zone_38S = 32338 - PCS_WGS72_UTM_zone_39S = 32339 - PCS_WGS72_UTM_zone_40S = 32340 - PCS_WGS72_UTM_zone_41S = 32341 - PCS_WGS72_UTM_zone_42S = 32342 - PCS_WGS72_UTM_zone_43S = 32343 - PCS_WGS72_UTM_zone_44S = 32344 - PCS_WGS72_UTM_zone_45S = 32345 - PCS_WGS72_UTM_zone_46S = 32346 - PCS_WGS72_UTM_zone_47S = 32347 - PCS_WGS72_UTM_zone_48S = 32348 - PCS_WGS72_UTM_zone_49S = 32349 - PCS_WGS72_UTM_zone_50S = 32350 - PCS_WGS72_UTM_zone_51S = 32351 - PCS_WGS72_UTM_zone_52S = 32352 - PCS_WGS72_UTM_zone_53S = 32353 - PCS_WGS72_UTM_zone_54S = 32354 - PCS_WGS72_UTM_zone_55S = 32355 - PCS_WGS72_UTM_zone_56S = 32356 - PCS_WGS72_UTM_zone_57S = 32357 - PCS_WGS72_UTM_zone_58S = 32358 - PCS_WGS72_UTM_zone_59S = 32359 - PCS_WGS72_UTM_zone_60S = 32360 - PCS_WGS72BE_UTM_zone_1N = 32401 - PCS_WGS72BE_UTM_zone_2N = 32402 - PCS_WGS72BE_UTM_zone_3N = 32403 - PCS_WGS72BE_UTM_zone_4N = 32404 - PCS_WGS72BE_UTM_zone_5N = 32405 - PCS_WGS72BE_UTM_zone_6N = 32406 - PCS_WGS72BE_UTM_zone_7N = 32407 - PCS_WGS72BE_UTM_zone_8N = 32408 - PCS_WGS72BE_UTM_zone_9N = 32409 - PCS_WGS72BE_UTM_zone_10N = 32410 - PCS_WGS72BE_UTM_zone_11N = 32411 - PCS_WGS72BE_UTM_zone_12N = 32412 - PCS_WGS72BE_UTM_zone_13N = 32413 - PCS_WGS72BE_UTM_zone_14N = 32414 - PCS_WGS72BE_UTM_zone_15N = 32415 - PCS_WGS72BE_UTM_zone_16N = 32416 - PCS_WGS72BE_UTM_zone_17N = 32417 - PCS_WGS72BE_UTM_zone_18N = 32418 - PCS_WGS72BE_UTM_zone_19N = 32419 - PCS_WGS72BE_UTM_zone_20N = 32420 - PCS_WGS72BE_UTM_zone_21N = 32421 - PCS_WGS72BE_UTM_zone_22N = 32422 - PCS_WGS72BE_UTM_zone_23N = 32423 - PCS_WGS72BE_UTM_zone_24N = 32424 - PCS_WGS72BE_UTM_zone_25N = 32425 - PCS_WGS72BE_UTM_zone_26N = 32426 - PCS_WGS72BE_UTM_zone_27N = 32427 - PCS_WGS72BE_UTM_zone_28N = 32428 - PCS_WGS72BE_UTM_zone_29N = 32429 - PCS_WGS72BE_UTM_zone_30N = 32430 - PCS_WGS72BE_UTM_zone_31N = 32431 - PCS_WGS72BE_UTM_zone_32N = 32432 - PCS_WGS72BE_UTM_zone_33N = 32433 - PCS_WGS72BE_UTM_zone_34N = 32434 - PCS_WGS72BE_UTM_zone_35N = 32435 - PCS_WGS72BE_UTM_zone_36N = 32436 - PCS_WGS72BE_UTM_zone_37N = 32437 - PCS_WGS72BE_UTM_zone_38N = 32438 - PCS_WGS72BE_UTM_zone_39N = 32439 - PCS_WGS72BE_UTM_zone_40N = 32440 - PCS_WGS72BE_UTM_zone_41N = 32441 - PCS_WGS72BE_UTM_zone_42N = 32442 - PCS_WGS72BE_UTM_zone_43N = 32443 - PCS_WGS72BE_UTM_zone_44N = 32444 - PCS_WGS72BE_UTM_zone_45N = 32445 - PCS_WGS72BE_UTM_zone_46N = 32446 - PCS_WGS72BE_UTM_zone_47N = 32447 - PCS_WGS72BE_UTM_zone_48N = 32448 - PCS_WGS72BE_UTM_zone_49N = 32449 - PCS_WGS72BE_UTM_zone_50N = 32450 - PCS_WGS72BE_UTM_zone_51N = 32451 - PCS_WGS72BE_UTM_zone_52N = 32452 - PCS_WGS72BE_UTM_zone_53N = 32453 - PCS_WGS72BE_UTM_zone_54N = 32454 - PCS_WGS72BE_UTM_zone_55N = 32455 - PCS_WGS72BE_UTM_zone_56N = 32456 - PCS_WGS72BE_UTM_zone_57N = 32457 - PCS_WGS72BE_UTM_zone_58N = 32458 - PCS_WGS72BE_UTM_zone_59N = 32459 - PCS_WGS72BE_UTM_zone_60N = 32460 - PCS_WGS72BE_UTM_zone_1S = 32501 - PCS_WGS72BE_UTM_zone_2S = 32502 - PCS_WGS72BE_UTM_zone_3S = 32503 - PCS_WGS72BE_UTM_zone_4S = 32504 - PCS_WGS72BE_UTM_zone_5S = 32505 - PCS_WGS72BE_UTM_zone_6S = 32506 - PCS_WGS72BE_UTM_zone_7S = 32507 - PCS_WGS72BE_UTM_zone_8S = 32508 - PCS_WGS72BE_UTM_zone_9S = 32509 - PCS_WGS72BE_UTM_zone_10S = 32510 - PCS_WGS72BE_UTM_zone_11S = 32511 - PCS_WGS72BE_UTM_zone_12S = 32512 - PCS_WGS72BE_UTM_zone_13S = 32513 - PCS_WGS72BE_UTM_zone_14S = 32514 - PCS_WGS72BE_UTM_zone_15S = 32515 - PCS_WGS72BE_UTM_zone_16S = 32516 - PCS_WGS72BE_UTM_zone_17S = 32517 - PCS_WGS72BE_UTM_zone_18S = 32518 - PCS_WGS72BE_UTM_zone_19S = 32519 - PCS_WGS72BE_UTM_zone_20S = 32520 - PCS_WGS72BE_UTM_zone_21S = 32521 - PCS_WGS72BE_UTM_zone_22S = 32522 - PCS_WGS72BE_UTM_zone_23S = 32523 - PCS_WGS72BE_UTM_zone_24S = 32524 - PCS_WGS72BE_UTM_zone_25S = 32525 - PCS_WGS72BE_UTM_zone_26S = 32526 - PCS_WGS72BE_UTM_zone_27S = 32527 - PCS_WGS72BE_UTM_zone_28S = 32528 - PCS_WGS72BE_UTM_zone_29S = 32529 - PCS_WGS72BE_UTM_zone_30S = 32530 - PCS_WGS72BE_UTM_zone_31S = 32531 - PCS_WGS72BE_UTM_zone_32S = 32532 - PCS_WGS72BE_UTM_zone_33S = 32533 - PCS_WGS72BE_UTM_zone_34S = 32534 - PCS_WGS72BE_UTM_zone_35S = 32535 - PCS_WGS72BE_UTM_zone_36S = 32536 - PCS_WGS72BE_UTM_zone_37S = 32537 - PCS_WGS72BE_UTM_zone_38S = 32538 - PCS_WGS72BE_UTM_zone_39S = 32539 - PCS_WGS72BE_UTM_zone_40S = 32540 - PCS_WGS72BE_UTM_zone_41S = 32541 - PCS_WGS72BE_UTM_zone_42S = 32542 - PCS_WGS72BE_UTM_zone_43S = 32543 - PCS_WGS72BE_UTM_zone_44S = 32544 - PCS_WGS72BE_UTM_zone_45S = 32545 - PCS_WGS72BE_UTM_zone_46S = 32546 - PCS_WGS72BE_UTM_zone_47S = 32547 - PCS_WGS72BE_UTM_zone_48S = 32548 - PCS_WGS72BE_UTM_zone_49S = 32549 - PCS_WGS72BE_UTM_zone_50S = 32550 - PCS_WGS72BE_UTM_zone_51S = 32551 - PCS_WGS72BE_UTM_zone_52S = 32552 - PCS_WGS72BE_UTM_zone_53S = 32553 - PCS_WGS72BE_UTM_zone_54S = 32554 - PCS_WGS72BE_UTM_zone_55S = 32555 - PCS_WGS72BE_UTM_zone_56S = 32556 - PCS_WGS72BE_UTM_zone_57S = 32557 - PCS_WGS72BE_UTM_zone_58S = 32558 - PCS_WGS72BE_UTM_zone_59S = 32559 - PCS_WGS72BE_UTM_zone_60S = 32560 - PCS_WGS84_UTM_zone_1N = 32601 - PCS_WGS84_UTM_zone_2N = 32602 - PCS_WGS84_UTM_zone_3N = 32603 - PCS_WGS84_UTM_zone_4N = 32604 - PCS_WGS84_UTM_zone_5N = 32605 - PCS_WGS84_UTM_zone_6N = 32606 - PCS_WGS84_UTM_zone_7N = 32607 - PCS_WGS84_UTM_zone_8N = 32608 - PCS_WGS84_UTM_zone_9N = 32609 - PCS_WGS84_UTM_zone_10N = 32610 - PCS_WGS84_UTM_zone_11N = 32611 - PCS_WGS84_UTM_zone_12N = 32612 - PCS_WGS84_UTM_zone_13N = 32613 - PCS_WGS84_UTM_zone_14N = 32614 - PCS_WGS84_UTM_zone_15N = 32615 - PCS_WGS84_UTM_zone_16N = 32616 - PCS_WGS84_UTM_zone_17N = 32617 - PCS_WGS84_UTM_zone_18N = 32618 - PCS_WGS84_UTM_zone_19N = 32619 - PCS_WGS84_UTM_zone_20N = 32620 - PCS_WGS84_UTM_zone_21N = 32621 - PCS_WGS84_UTM_zone_22N = 32622 - PCS_WGS84_UTM_zone_23N = 32623 - PCS_WGS84_UTM_zone_24N = 32624 - PCS_WGS84_UTM_zone_25N = 32625 - PCS_WGS84_UTM_zone_26N = 32626 - PCS_WGS84_UTM_zone_27N = 32627 - PCS_WGS84_UTM_zone_28N = 32628 - PCS_WGS84_UTM_zone_29N = 32629 - PCS_WGS84_UTM_zone_30N = 32630 - PCS_WGS84_UTM_zone_31N = 32631 - PCS_WGS84_UTM_zone_32N = 32632 - PCS_WGS84_UTM_zone_33N = 32633 - PCS_WGS84_UTM_zone_34N = 32634 - PCS_WGS84_UTM_zone_35N = 32635 - PCS_WGS84_UTM_zone_36N = 32636 - PCS_WGS84_UTM_zone_37N = 32637 - PCS_WGS84_UTM_zone_38N = 32638 - PCS_WGS84_UTM_zone_39N = 32639 - PCS_WGS84_UTM_zone_40N = 32640 - PCS_WGS84_UTM_zone_41N = 32641 - PCS_WGS84_UTM_zone_42N = 32642 - PCS_WGS84_UTM_zone_43N = 32643 - PCS_WGS84_UTM_zone_44N = 32644 - PCS_WGS84_UTM_zone_45N = 32645 - PCS_WGS84_UTM_zone_46N = 32646 - PCS_WGS84_UTM_zone_47N = 32647 - PCS_WGS84_UTM_zone_48N = 32648 - PCS_WGS84_UTM_zone_49N = 32649 - PCS_WGS84_UTM_zone_50N = 32650 - PCS_WGS84_UTM_zone_51N = 32651 - PCS_WGS84_UTM_zone_52N = 32652 - PCS_WGS84_UTM_zone_53N = 32653 - PCS_WGS84_UTM_zone_54N = 32654 - PCS_WGS84_UTM_zone_55N = 32655 - PCS_WGS84_UTM_zone_56N = 32656 - PCS_WGS84_UTM_zone_57N = 32657 - PCS_WGS84_UTM_zone_58N = 32658 - PCS_WGS84_UTM_zone_59N = 32659 - PCS_WGS84_UTM_zone_60N = 32660 - PCS_WGS84_UTM_zone_1S = 32701 - PCS_WGS84_UTM_zone_2S = 32702 - PCS_WGS84_UTM_zone_3S = 32703 - PCS_WGS84_UTM_zone_4S = 32704 - PCS_WGS84_UTM_zone_5S = 32705 - PCS_WGS84_UTM_zone_6S = 32706 - PCS_WGS84_UTM_zone_7S = 32707 - PCS_WGS84_UTM_zone_8S = 32708 - PCS_WGS84_UTM_zone_9S = 32709 - PCS_WGS84_UTM_zone_10S = 32710 - PCS_WGS84_UTM_zone_11S = 32711 - PCS_WGS84_UTM_zone_12S = 32712 - PCS_WGS84_UTM_zone_13S = 32713 - PCS_WGS84_UTM_zone_14S = 32714 - PCS_WGS84_UTM_zone_15S = 32715 - PCS_WGS84_UTM_zone_16S = 32716 - PCS_WGS84_UTM_zone_17S = 32717 - PCS_WGS84_UTM_zone_18S = 32718 - PCS_WGS84_UTM_zone_19S = 32719 - PCS_WGS84_UTM_zone_20S = 32720 - PCS_WGS84_UTM_zone_21S = 32721 - PCS_WGS84_UTM_zone_22S = 32722 - PCS_WGS84_UTM_zone_23S = 32723 - PCS_WGS84_UTM_zone_24S = 32724 - PCS_WGS84_UTM_zone_25S = 32725 - PCS_WGS84_UTM_zone_26S = 32726 - PCS_WGS84_UTM_zone_27S = 32727 - PCS_WGS84_UTM_zone_28S = 32728 - PCS_WGS84_UTM_zone_29S = 32729 - PCS_WGS84_UTM_zone_30S = 32730 - PCS_WGS84_UTM_zone_31S = 32731 - PCS_WGS84_UTM_zone_32S = 32732 - PCS_WGS84_UTM_zone_33S = 32733 - PCS_WGS84_UTM_zone_34S = 32734 - PCS_WGS84_UTM_zone_35S = 32735 - PCS_WGS84_UTM_zone_36S = 32736 - PCS_WGS84_UTM_zone_37S = 32737 - PCS_WGS84_UTM_zone_38S = 32738 - PCS_WGS84_UTM_zone_39S = 32739 - PCS_WGS84_UTM_zone_40S = 32740 - PCS_WGS84_UTM_zone_41S = 32741 - PCS_WGS84_UTM_zone_42S = 32742 - PCS_WGS84_UTM_zone_43S = 32743 - PCS_WGS84_UTM_zone_44S = 32744 - PCS_WGS84_UTM_zone_45S = 32745 - PCS_WGS84_UTM_zone_46S = 32746 - PCS_WGS84_UTM_zone_47S = 32747 - PCS_WGS84_UTM_zone_48S = 32748 - PCS_WGS84_UTM_zone_49S = 32749 - PCS_WGS84_UTM_zone_50S = 32750 - PCS_WGS84_UTM_zone_51S = 32751 - PCS_WGS84_UTM_zone_52S = 32752 - PCS_WGS84_UTM_zone_53S = 32753 - PCS_WGS84_UTM_zone_54S = 32754 - PCS_WGS84_UTM_zone_55S = 32755 - PCS_WGS84_UTM_zone_56S = 32756 - PCS_WGS84_UTM_zone_57S = 32757 - PCS_WGS84_UTM_zone_58S = 32758 - PCS_WGS84_UTM_zone_59S = 32759 - PCS_WGS84_UTM_zone_60S = 32760 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_pm.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_pm.properties deleted file mode 100644 index c402be15e..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_pm.properties +++ /dev/null @@ -1,24 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - PM_Greenwich = 8901 - PM_Lisbon = 8902 - PM_Paris = 8903 - PM_Bogota = 8904 - PM_Madrid = 8905 - PM_Rome = 8906 - PM_Bern = 8907 - PM_Jakarta = 8908 - PM_Ferro = 8909 - PM_Brussels = 8910 - PM_Stockholm = 8911 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_proj.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_proj.properties deleted file mode 100644 index b859cb083..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_proj.properties +++ /dev/null @@ -1,311 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - Proj_Alabama_CS27_East = 10101 - Proj_Alabama_CS27_West = 10102 - Proj_Alabama_CS83_East = 10131 - Proj_Alabama_CS83_West = 10132 - Proj_Arizona_Coordinate_System_east = 10201 - Proj_Arizona_Coordinate_System_Central = 10202 - Proj_Arizona_Coordinate_System_west = 10203 - Proj_Arizona_CS83_east = 10231 - Proj_Arizona_CS83_Central = 10232 - Proj_Arizona_CS83_west = 10233 - Proj_Arkansas_CS27_North = 10301 - Proj_Arkansas_CS27_South = 10302 - Proj_Arkansas_CS83_North = 10331 - Proj_Arkansas_CS83_South = 10332 - Proj_California_CS27_I = 10401 - Proj_California_CS27_II = 10402 - Proj_California_CS27_III = 10403 - Proj_California_CS27_IV = 10404 - Proj_California_CS27_V = 10405 - Proj_California_CS27_VI = 10406 - Proj_California_CS27_VII = 10407 - Proj_California_CS83_1 = 10431 - Proj_California_CS83_2 = 10432 - Proj_California_CS83_3 = 10433 - Proj_California_CS83_4 = 10434 - Proj_California_CS83_5 = 10435 - Proj_California_CS83_6 = 10436 - Proj_Colorado_CS27_North = 10501 - Proj_Colorado_CS27_Central = 10502 - Proj_Colorado_CS27_South = 10503 - Proj_Colorado_CS83_North = 10531 - Proj_Colorado_CS83_Central = 10532 - Proj_Colorado_CS83_South = 10533 - Proj_Connecticut_CS27 = 10600 - Proj_Connecticut_CS83 = 10630 - Proj_Delaware_CS27 = 10700 - Proj_Delaware_CS83 = 10730 - Proj_Florida_CS27_East = 10901 - Proj_Florida_CS27_West = 10902 - Proj_Florida_CS27_North = 10903 - Proj_Florida_CS83_East = 10931 - Proj_Florida_CS83_West = 10932 - Proj_Florida_CS83_North = 10933 - Proj_Georgia_CS27_East = 11001 - Proj_Georgia_CS27_West = 11002 - Proj_Georgia_CS83_East = 11031 - Proj_Georgia_CS83_West = 11032 - Proj_Idaho_CS27_East = 11101 - Proj_Idaho_CS27_Central = 11102 - Proj_Idaho_CS27_West = 11103 - Proj_Idaho_CS83_East = 11131 - Proj_Idaho_CS83_Central = 11132 - Proj_Idaho_CS83_West = 11133 - Proj_Illinois_CS27_East = 11201 - Proj_Illinois_CS27_West = 11202 - Proj_Illinois_CS83_East = 11231 - Proj_Illinois_CS83_West = 11232 - Proj_Indiana_CS27_East = 11301 - Proj_Indiana_CS27_West = 11302 - Proj_Indiana_CS83_East = 11331 - Proj_Indiana_CS83_West = 11332 - Proj_Iowa_CS27_North = 11401 - Proj_Iowa_CS27_South = 11402 - Proj_Iowa_CS83_North = 11431 - Proj_Iowa_CS83_South = 11432 - Proj_Kansas_CS27_North = 11501 - Proj_Kansas_CS27_South = 11502 - Proj_Kansas_CS83_North = 11531 - Proj_Kansas_CS83_South = 11532 - Proj_Kentucky_CS27_North = 11601 - Proj_Kentucky_CS27_South = 11602 - Proj_Kentucky_CS83_North = 11631 - Proj_Kentucky_CS83_South = 11632 - Proj_Louisiana_CS27_North = 11701 - Proj_Louisiana_CS27_South = 11702 - Proj_Louisiana_CS83_North = 11731 - Proj_Louisiana_CS83_South = 11732 - Proj_Maine_CS27_East = 11801 - Proj_Maine_CS27_West = 11802 - Proj_Maine_CS83_East = 11831 - Proj_Maine_CS83_West = 11832 - Proj_Maryland_CS27 = 11900 - Proj_Maryland_CS83 = 11930 - Proj_Massachusetts_CS27_Mainland = 12001 - Proj_Massachusetts_CS27_Island = 12002 - Proj_Massachusetts_CS83_Mainland = 12031 - Proj_Massachusetts_CS83_Island = 12032 - Proj_Michigan_State_Plane_East = 12101 - Proj_Michigan_State_Plane_Old_Central = 12102 - Proj_Michigan_State_Plane_West = 12103 - Proj_Michigan_CS27_North = 12111 - Proj_Michigan_CS27_Central = 12112 - Proj_Michigan_CS27_South = 12113 - Proj_Michigan_CS83_North = 12141 - Proj_Michigan_CS83_Central = 12142 - Proj_Michigan_CS83_South = 12143 - Proj_Minnesota_CS27_North = 12201 - Proj_Minnesota_CS27_Central = 12202 - Proj_Minnesota_CS27_South = 12203 - Proj_Minnesota_CS83_North = 12231 - Proj_Minnesota_CS83_Central = 12232 - Proj_Minnesota_CS83_South = 12233 - Proj_Mississippi_CS27_East = 12301 - Proj_Mississippi_CS27_West = 12302 - Proj_Mississippi_CS83_East = 12331 - Proj_Mississippi_CS83_West = 12332 - Proj_Missouri_CS27_East = 12401 - Proj_Missouri_CS27_Central = 12402 - Proj_Missouri_CS27_West = 12403 - Proj_Missouri_CS83_East = 12431 - Proj_Missouri_CS83_Central = 12432 - Proj_Missouri_CS83_West = 12433 - Proj_Montana_CS27_North = 12501 - Proj_Montana_CS27_Central = 12502 - Proj_Montana_CS27_South = 12503 - Proj_Montana_CS83 = 12530 - Proj_Nebraska_CS27_North = 12601 - Proj_Nebraska_CS27_South = 12602 - Proj_Nebraska_CS83 = 12630 - Proj_Nevada_CS27_East = 12701 - Proj_Nevada_CS27_Central = 12702 - Proj_Nevada_CS27_West = 12703 - Proj_Nevada_CS83_East = 12731 - Proj_Nevada_CS83_Central = 12732 - Proj_Nevada_CS83_West = 12733 - Proj_New_Hampshire_CS27 = 12800 - Proj_New_Hampshire_CS83 = 12830 - Proj_New_Jersey_CS27 = 12900 - Proj_New_Jersey_CS83 = 12930 - Proj_New_Mexico_CS27_East = 13001 - Proj_New_Mexico_CS27_Central = 13002 - Proj_New_Mexico_CS27_West = 13003 - Proj_New_Mexico_CS83_East = 13031 - Proj_New_Mexico_CS83_Central = 13032 - Proj_New_Mexico_CS83_West = 13033 - Proj_New_York_CS27_East = 13101 - Proj_New_York_CS27_Central = 13102 - Proj_New_York_CS27_West = 13103 - Proj_New_York_CS27_Long_Island = 13104 - Proj_New_York_CS83_East = 13131 - Proj_New_York_CS83_Central = 13132 - Proj_New_York_CS83_West = 13133 - Proj_New_York_CS83_Long_Island = 13134 - Proj_North_Carolina_CS27 = 13200 - Proj_North_Carolina_CS83 = 13230 - Proj_North_Dakota_CS27_North = 13301 - Proj_North_Dakota_CS27_South = 13302 - Proj_North_Dakota_CS83_North = 13331 - Proj_North_Dakota_CS83_South = 13332 - Proj_Ohio_CS27_North = 13401 - Proj_Ohio_CS27_South = 13402 - Proj_Ohio_CS83_North = 13431 - Proj_Ohio_CS83_South = 13432 - Proj_Oklahoma_CS27_North = 13501 - Proj_Oklahoma_CS27_South = 13502 - Proj_Oklahoma_CS83_North = 13531 - Proj_Oklahoma_CS83_South = 13532 - Proj_Oregon_CS27_North = 13601 - Proj_Oregon_CS27_South = 13602 - Proj_Oregon_CS83_North = 13631 - Proj_Oregon_CS83_South = 13632 - Proj_Pennsylvania_CS27_North = 13701 - Proj_Pennsylvania_CS27_South = 13702 - Proj_Pennsylvania_CS83_North = 13731 - Proj_Pennsylvania_CS83_South = 13732 - Proj_Rhode_Island_CS27 = 13800 - Proj_Rhode_Island_CS83 = 13830 - Proj_South_Carolina_CS27_North = 13901 - Proj_South_Carolina_CS27_South = 13902 - Proj_South_Carolina_CS83 = 13930 - Proj_South_Dakota_CS27_North = 14001 - Proj_South_Dakota_CS27_South = 14002 - Proj_South_Dakota_CS83_North = 14031 - Proj_South_Dakota_CS83_South = 14032 - Proj_Tennessee_CS27 = 14100 - Proj_Tennessee_CS83 = 14130 - Proj_Texas_CS27_North = 14201 - Proj_Texas_CS27_North_Central = 14202 - Proj_Texas_CS27_Central = 14203 - Proj_Texas_CS27_South_Central = 14204 - Proj_Texas_CS27_South = 14205 - Proj_Texas_CS83_North = 14231 - Proj_Texas_CS83_North_Central = 14232 - Proj_Texas_CS83_Central = 14233 - Proj_Texas_CS83_South_Central = 14234 - Proj_Texas_CS83_South = 14235 - Proj_Utah_CS27_North = 14301 - Proj_Utah_CS27_Central = 14302 - Proj_Utah_CS27_South = 14303 - Proj_Utah_CS83_North = 14331 - Proj_Utah_CS83_Central = 14332 - Proj_Utah_CS83_South = 14333 - Proj_Vermont_CS27 = 14400 - Proj_Vermont_CS83 = 14430 - Proj_Virginia_CS27_North = 14501 - Proj_Virginia_CS27_South = 14502 - Proj_Virginia_CS83_North = 14531 - Proj_Virginia_CS83_South = 14532 - Proj_Washington_CS27_North = 14601 - Proj_Washington_CS27_South = 14602 - Proj_Washington_CS83_North = 14631 - Proj_Washington_CS83_South = 14632 - Proj_West_Virginia_CS27_North = 14701 - Proj_West_Virginia_CS27_South = 14702 - Proj_West_Virginia_CS83_North = 14731 - Proj_West_Virginia_CS83_South = 14732 - Proj_Wisconsin_CS27_North = 14801 - Proj_Wisconsin_CS27_Central = 14802 - Proj_Wisconsin_CS27_South = 14803 - Proj_Wisconsin_CS83_North = 14831 - Proj_Wisconsin_CS83_Central = 14832 - Proj_Wisconsin_CS83_South = 14833 - Proj_Wyoming_CS27_East = 14901 - Proj_Wyoming_CS27_East_Central = 14902 - Proj_Wyoming_CS27_West_Central = 14903 - Proj_Wyoming_CS27_West = 14904 - Proj_Wyoming_CS83_East = 14931 - Proj_Wyoming_CS83_East_Central = 14932 - Proj_Wyoming_CS83_West_Central = 14933 - Proj_Wyoming_CS83_West = 14934 - Proj_Alaska_CS27_1 = 15001 - Proj_Alaska_CS27_2 = 15002 - Proj_Alaska_CS27_3 = 15003 - Proj_Alaska_CS27_4 = 15004 - Proj_Alaska_CS27_5 = 15005 - Proj_Alaska_CS27_6 = 15006 - Proj_Alaska_CS27_7 = 15007 - Proj_Alaska_CS27_8 = 15008 - Proj_Alaska_CS27_9 = 15009 - Proj_Alaska_CS27_10 = 15010 - Proj_Alaska_CS83_1 = 15031 - Proj_Alaska_CS83_2 = 15032 - Proj_Alaska_CS83_3 = 15033 - Proj_Alaska_CS83_4 = 15034 - Proj_Alaska_CS83_5 = 15035 - Proj_Alaska_CS83_6 = 15036 - Proj_Alaska_CS83_7 = 15037 - Proj_Alaska_CS83_8 = 15038 - Proj_Alaska_CS83_9 = 15039 - Proj_Alaska_CS83_10 = 15040 - Proj_Hawaii_CS27_1 = 15101 - Proj_Hawaii_CS27_2 = 15102 - Proj_Hawaii_CS27_3 = 15103 - Proj_Hawaii_CS27_4 = 15104 - Proj_Hawaii_CS27_5 = 15105 - Proj_Hawaii_CS83_1 = 15131 - Proj_Hawaii_CS83_2 = 15132 - Proj_Hawaii_CS83_3 = 15133 - Proj_Hawaii_CS83_4 = 15134 - Proj_Hawaii_CS83_5 = 15135 - Proj_Puerto_Rico_CS27 = 15201 - Proj_St_Croix = 15202 - Proj_Puerto_Rico_Virgin_Is = 15230 - Proj_BLM_14N_feet = 15914 - Proj_BLM_15N_feet = 15915 - Proj_BLM_16N_feet = 15916 - Proj_BLM_17N_feet = 15917 - Proj_Map_Grid_of_Australia_48 = 17348 - Proj_Map_Grid_of_Australia_49 = 17349 - Proj_Map_Grid_of_Australia_50 = 17350 - Proj_Map_Grid_of_Australia_51 = 17351 - Proj_Map_Grid_of_Australia_52 = 17352 - Proj_Map_Grid_of_Australia_53 = 17353 - Proj_Map_Grid_of_Australia_54 = 17354 - Proj_Map_Grid_of_Australia_55 = 17355 - Proj_Map_Grid_of_Australia_56 = 17356 - Proj_Map_Grid_of_Australia_57 = 17357 - Proj_Map_Grid_of_Australia_58 = 17358 - Proj_Australian_Map_Grid_48 = 17448 - Proj_Australian_Map_Grid_49 = 17449 - Proj_Australian_Map_Grid_50 = 17450 - Proj_Australian_Map_Grid_51 = 17451 - Proj_Australian_Map_Grid_52 = 17452 - Proj_Australian_Map_Grid_53 = 17453 - Proj_Australian_Map_Grid_54 = 17454 - Proj_Australian_Map_Grid_55 = 17455 - Proj_Australian_Map_Grid_56 = 17456 - Proj_Australian_Map_Grid_57 = 17457 - Proj_Australian_Map_Grid_58 = 17458 - Proj_Argentina_1 = 18031 - Proj_Argentina_2 = 18032 - Proj_Argentina_3 = 18033 - Proj_Argentina_4 = 18034 - Proj_Argentina_5 = 18035 - Proj_Argentina_6 = 18036 - Proj_Argentina_7 = 18037 - Proj_Colombia_3W = 18051 - Proj_Colombia_Bogota = 18052 - Proj_Colombia_3E = 18053 - Proj_Colombia_6E = 18054 - Proj_Egypt_Red_Belt = 18072 - Proj_Egypt_Purple_Belt = 18073 - Proj_Extended_Purple_Belt = 18074 - Proj_New_Zealand_North_Island_Nat_Grid = 18141 - Proj_New_Zealand_South_Island_Nat_Grid = 18142 - Proj_Bahrain_Grid = 19900 - Proj_Netherlands_E_Indies_Equatorial = 19905 - Proj_RSO_Borneo = 19912 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_unit.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_unit.properties deleted file mode 100644 index 7684d3830..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_unit.properties +++ /dev/null @@ -1,36 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - Linear_Meter = 9001 - Linear_Foot = 9002 - Linear_Foot_US_Survey = 9003 - Linear_Foot_Modified_American = 9004 - Linear_Foot_Clarke = 9005 - Linear_Foot_Indian = 9006 - Linear_Link = 9007 - Linear_Link_Benoit = 9008 - Linear_Link_Sears = 9009 - Linear_Chain_Benoit = 9010 - Linear_Chain_Sears = 9011 - Linear_Yard_Sears = 9012 - Linear_Yard_Indian = 9013 - Linear_Fathom = 9014 - Linear_Mile_International_Nautical = 9015 - Angular_Radian = 9101 - Angular_Degree = 9102 - Angular_Arc_Minute = 9103 - Angular_Arc_Second = 9104 - Angular_Grad = 9105 - Angular_Gon = 9106 - Angular_DMS = 9107 - Angular_DMS_Hemisphere = 9108 diff --git a/src/core/src/main/resources/org/geotiff/epsg/epsg_vertcs.properties b/src/core/src/main/resources/org/geotiff/epsg/epsg_vertcs.properties deleted file mode 100644 index f6ef0324a..000000000 --- a/src/core/src/main/resources/org/geotiff/epsg/epsg_vertcs.properties +++ /dev/null @@ -1,51 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - VertCS_Airy_1830_ellipsoid = 5001 - VertCS_Airy_Modified_1849_ellipsoid = 5002 - VertCS_ANS_ellipsoid = 5003 - VertCS_Bessel_1841_ellipsoid = 5004 - VertCS_Bessel_Modified_ellipsoid = 5005 - VertCS_Bessel_Namibia_ellipsoid = 5006 - VertCS_Clarke_1858_ellipsoid = 5007 - VertCS_Clarke_1866_ellipsoid = 5008 - VertCS_Clarke_1880_Benoit_ellipsoid = 5010 - VertCS_Clarke_1880_IGN_ellipsoid = 5011 - VertCS_Clarke_1880_RGS_ellipsoid = 5012 - VertCS_Clarke_1880_Arc_ellipsoid = 5013 - VertCS_Clarke_1880_SGA_1922_ellipsoid = 5014 - VertCS_Everest_1830_1937_Adjustment_ellipsoid = 5015 - VertCS_Everest_1830_1967_Definition_ellipsoid = 5016 - VertCS_Everest_1830_1975_Definition_ellipsoid = 5017 - VertCS_Everest_1830_Modified_ellipsoid = 5018 - VertCS_GRS_1980_ellipsoid = 5019 - VertCS_Helmert_1906_ellipsoid = 5020 - VertCS_INS_ellipsoid = 5021 - VertCS_International_1924_ellipsoid = 5022 - VertCS_International_1967_ellipsoid = 5023 - VertCS_Krassowsky_1940_ellipsoid = 5024 - VertCS_NWL_9D_ellipsoid = 5025 - VertCS_NWL_10D_ellipsoid = 5026 - VertCS_Plessis_1817_ellipsoid = 5027 - VertCS_Struve_1860_ellipsoid = 5028 - VertCS_War_Office_ellipsoid = 5029 - VertCS_WGS_84_ellipsoid = 5030 - VertCS_GEM_10C_ellipsoid = 5031 - VertCS_OSU86F_ellipsoid = 5032 - VertCS_OSU91A_ellipsoid = 5033 - VertCS_Newlyn = 5101 - VertCS_North_American_Vertical_Datum_1929 = 5102 - VertCS_North_American_Vertical_Datum_1988 = 5103 - VertCS_Yellow_Sea_1956 = 5104 - VertCS_Baltic_Sea = 5105 - VertCS_Caspian_Sea = 5106 diff --git a/src/core/src/main/resources/org/geotiff/image/geo_ctrans.properties b/src/core/src/main/resources/org/geotiff/image/geo_ctrans.properties deleted file mode 100644 index 35ef26ca1..000000000 --- a/src/core/src/main/resources/org/geotiff/image/geo_ctrans.properties +++ /dev/null @@ -1,49 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - CT_TransverseMercator = 1 - CT_TransvMercator_Modified_Alaska = 2 - CT_ObliqueMercator = 3 - CT_ObliqueMercator_Laborde = 4 - CT_ObliqueMercator_Rosenmund = 5 - CT_ObliqueMercator_Spherical = 6 - CT_Mercator = 7 - CT_LambertConfConic_2SP = 8 - CT_LambertConfConic =$CT_LambertConfConic_2SP - CT_LambertConfConic_1SP = 9 - CT_LambertConfConic_Helmert =$CT_LambertConfConic_1SP - CT_LambertAzimEqualArea = 10 - CT_AlbersEqualArea = 11 - CT_AzimuthalEquidistant = 12 - CT_EquidistantConic = 13 - CT_Stereographic = 14 - CT_PolarStereographic = 15 - CT_ObliqueStereographic = 16 - CT_Equirectangular = 17 - CT_CassiniSoldner = 18 - CT_Gnomonic = 19 - CT_MillerCylindrical = 20 - CT_Orthographic = 21 - CT_Polyconic = 22 - CT_Robinson = 23 - CT_Sinusoidal = 24 - CT_VanDerGrinten = 25 - CT_NewZealandMapGrid = 26 - CT_TransvMercator_SouthOriented = 27 - CT_SouthOrientedGaussConformal =$CT_TransvMercator_SouthOriented - CT_AlaskaConformal =$CT_TransvMercator_Modified_Alaska - CT_TransvEquidistCylindrical =$CT_CassiniSoldner - CT_ObliqueMercator_Hotine =$CT_ObliqueMercator - CT_SwissObliqueCylindrical =$CT_ObliqueMercator_Rosenmund - CT_GaussBoaga =$CT_TransverseMercator - CT_GaussKruger =$CT_TransverseMercator diff --git a/src/core/src/main/resources/org/geotiff/image/geo_models.properties b/src/core/src/main/resources/org/geotiff/image/geo_models.properties deleted file mode 100755 index bc5ea97df..000000000 --- a/src/core/src/main/resources/org/geotiff/image/geo_models.properties +++ /dev/null @@ -1,19 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ -ModelTypeProjected = 1 -ModelTypeGeographic = 2 -ModelTypeGeocentric = 3 -ModelProjected = 1 -ModelGeographic = 2 -ModelGeocentric = 3 diff --git a/src/core/src/main/resources/org/geotiff/image/geo_rasters.properties b/src/core/src/main/resources/org/geotiff/image/geo_rasters.properties deleted file mode 100755 index 5549adab7..000000000 --- a/src/core/src/main/resources/org/geotiff/image/geo_rasters.properties +++ /dev/null @@ -1,15 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ -RasterPixelIsArea = 1 -RasterPixelIsPoint = 2 diff --git a/src/core/src/main/resources/org/geotiff/image/geokey.properties b/src/core/src/main/resources/org/geotiff/image/geokey.properties deleted file mode 100644 index bdc4aa8d8..000000000 --- a/src/core/src/main/resources/org/geotiff/image/geokey.properties +++ /dev/null @@ -1,62 +0,0 @@ -# **********************************************************************/ -# * geokeys.h - Public registry for valid GEOTIFF GeoKeys. -# * -# * Written By: Niles D. Ritter -# * -# * Revision History: -# * -# * Rev.# Author M/D/Y Date Key Changes/Additions -# * ----- ------ ---------- ------------------------------------- -# * 0 ndr 06/10/95 Inital Beta Release -# * 1 ndr 09/18/95 Final 1.0 Release -# * -# **********************************************************************/ - GTModelTypeGeoKey = 1024 - GTRasterTypeGeoKey = 1025 - GTCitationGeoKey = 1026 - GeographicTypeGeoKey = 2048 - GeogCitationGeoKey = 2049 - GeogGeodeticDatumGeoKey = 2050 - GeogPrimeMeridianGeoKey = 2051 - GeogLinearUnitsGeoKey = 2052 - GeogLinearUnitSizeGeoKey = 2053 - GeogAngularUnitsGeoKey = 2054 - GeogAngularUnitSizeGeoKey = 2055 - GeogEllipsoidGeoKey = 2056 - GeogSemiMajorAxisGeoKey = 2057 - GeogSemiMinorAxisGeoKey = 2058 - GeogInvFlatteningGeoKey = 2059 - GeogAzimuthUnitsGeoKey = 2060 - GeogPrimeMeridianLongGeoKey = 2061 - ProjectedCSTypeGeoKey = 3072 - PCSCitationGeoKey = 3073 - ProjectionGeoKey = 3074 - ProjCoordTransGeoKey = 3075 - ProjLinearUnitsGeoKey = 3076 - ProjLinearUnitSizeGeoKey = 3077 - ProjStdParallel1GeoKey = 3078 - ProjStdParallelGeoKey =$ProjStdParallel1GeoKey - ProjStdParallel2GeoKey = 3079 - ProjNatOriginLongGeoKey = 3080 - ProjOriginLongGeoKey =$ProjNatOriginLongGeoKey - ProjNatOriginLatGeoKey = 3081 - ProjOriginLatGeoKey =$ProjNatOriginLatGeoKey - ProjFalseEastingGeoKey = 3082 - ProjFalseNorthingGeoKey = 3083 - ProjFalseOriginLongGeoKey = 3084 - ProjFalseOriginLatGeoKey = 3085 - ProjFalseOriginEastingGeoKey = 3086 - ProjFalseOriginNorthingGeoKey = 3087 - ProjCenterLongGeoKey = 3088 - ProjCenterLatGeoKey = 3089 - ProjCenterEastingGeoKey = 3090 - ProjCenterNorthingGeoKey = 3091 - ProjScaleAtNatOriginGeoKey = 3092 - ProjScaleAtOriginGeoKey =$ProjScaleAtNatOriginGeoKey - ProjScaleAtCenterGeoKey = 3093 - ProjAzimuthAngleGeoKey = 3094 - ProjStraightVertPoleLongGeoKey = 3095 - VerticalCSTypeGeoKey = 4096 - VerticalCitationGeoKey = 4097 - VerticalDatumGeoKey = 4098 - VerticalUnitsGeoKey = 4099 diff --git a/src/core/src/main/resources/org/libtiff/jai/codec/xtiff_en_US.properties b/src/core/src/main/resources/org/libtiff/jai/codec/xtiff_en_US.properties deleted file mode 100644 index f17aaa321..000000000 --- a/src/core/src/main/resources/org/libtiff/jai/codec/xtiff_en_US.properties +++ /dev/null @@ -1,44 +0,0 @@ -XTIFFDirectory0=Unsupported TIFFField tag. -XTIFFDirectory1=Bad endianness tag (not 0x4949 or 0x4d4d). -XTIFFDirectory2=Bad magic number, should be 42. -XTIFFDirectory3=Directory number too large. -XTIFFDirectory4=- Ignoring this tag due to invalid data type. -XTIFFEncodeParam0=This compression scheme is not implemented yet. -XTIFFEncodeParam1=Unsupported compression scheme specified. -XTIFFEncodeParam2=Writing out Tiled TIFF images is not implemented yet. -XTIFFFaxDecoder0=Invalid code encountered. -XTIFFFaxDecoder1=EOL code word encountered in White run. -XTIFFFaxDecoder2=EOL code word encountered in Black run. -XTIFFFaxDecoder3=First scanline must be 1D encoded. -XTIFFFaxDecoder4=Invalid code encountered while decoding 2D group 3 compressed data. -XTIFFFaxDecoder5=Invalid code encountered while decoding 2D group 4 compressed data. -XTIFFFaxDecoder6=Scanline must begin with EOL code word. -XTIFFFaxDecoder7=TIFF_FILL_ORDER tag must be either 1 or 2. -XTIFFFaxDecoder8=All fill bits preceding EOL code must be 0. -XTIFFImageDecoder0=Reading in compressed TIFF images is not implemented yet. -XTIFFImageDecoder10=Unable to decode Packbits compressed data - not enough data. -XTIFFImageDecoder11=TIFF_STRIP_OFFSETS is a required field. -XTIFFImageDecoder12=TIFF_STRIP_BYTE_COUNTS is a required field. -XTIFFImageDecoder13=Only 4, 8 or 16 bits per sample are supported for TIFF Palette color images. -XTIFFImageDecoder14=Only 4, 8 and 16 bit samples are supported for Greyscale TIFFs. -XTIFFImageDecoder15=Only 8 and 16 bit samples are supported for Full color images. -XTIFFImageDecoder16=Illegal value for Predictor in TIFF file. -XTIFFImageDecoder17=-bit samples are not supported for Horizontal differencing Predictor. -XTIFFImageDecoder18=Unsupported compression. -XTIFFImageDecoder19=All samples must have the same bit depth. -XTIFFImageDecoder1=Bad TIFF Image File: SamplesPerPixel tag must have a value >=3 for RGB full color images -XTIFFImageDecoder20=All samples must have the same data format. -XTIFFImageDecoder21=Only 16bit samples can be signed. -XTIFFImageDecoder22=Only integral image data is supported. -XTIFFImageDecoder2=Colormap must be present for a Palette Color image. -XTIFFImageDecoder3=Reading of TIFF files with a value of 4 for the PhotometricInterpretation tag is not implemented yet. -XTIFFImageDecoder4=Non-baseline TIFF not implemented yet - unexpected value for PhotometricInterpretation tag. -XTIFFImageDecoder5=Illegal tile requested from a TIFFImage. -XTIFFImageDecoder6=Non-baseline TIFF not implemented yet - unexpected value for BitsPerSample tag. -XTIFFImageDecoder7=Support for TIFF Palette images with a value of BitsPerSample tag other than 4 or 8 not implemeneted yet. -XTIFFImageDecoder8=IOException occured while reading TIFF image data. -XTIFFImageDecoder9=Illegal page requested from a TIFF file. -XTIFFImageEncoder0=TIFF encoder supports byte and (unsigned) short data only. -XTIFFImageEncoder1=Invalid image - An image with sampleSize of 1 bit must have IndexColorModel with mapsize of 2. -XTIFFImageEncoder2=TIFF encoder does not support (unsigned) short palette images. -greater than 8. diff --git a/src/core/src/test/java/com/bbn/openmap/geo/GeoTest.java b/src/core/src/test/java/com/bbn/openmap/geo/GeoTest.java deleted file mode 100644 index 8c94d7d22..000000000 --- a/src/core/src/test/java/com/bbn/openmap/geo/GeoTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.bbn.openmap.geo; - -import org.junit.Assert; -import org.junit.Test; - -public class GeoTest { - @Test - public void testLatLonConversion2() { - System.out.println("@Test - testLatLonConversion"); - - double bosLat = 42.366978; - double bosLon = -71.022362; - double sfoLat = 37.615223; - double sfoLon = -122.389977; - - double distNM = Geo.distanceNM(bosLat, bosLon, sfoLat, sfoLon); - System.out.println("distNM: " + distNM); - double distKM1 = distNM * Geo.METERS_PER_NM / 1000; - System.out.println("distKM1: " + distKM1); - - double distKM2 = Geo.distanceKM(bosLat, bosLon, sfoLat, sfoLon); - System.out.println("distKM2: " + distKM2); - - // from Planet.java - double wgs84_earthEquatorialRadiusMeters_D = 6378137.0; - double circumferenceMeters = wgs84_earthEquatorialRadiusMeters_D * 2.0 * Math.PI; - double wgs84_earthEquatorialCircumferenceNMiles_D = 21600.0; - - double circumf_meters_per_nm = circumferenceMeters / wgs84_earthEquatorialCircumferenceNMiles_D; - - System.out.println("circumf_meters_per_nm: " + circumf_meters_per_nm); - System.out.println("Geo.METERS_PER_NM: " + Geo.METERS_PER_NM); - - Assert.assertEquals(distKM1, distKM2, 1); - } -} diff --git a/src/core/src/test/java/com/bbn/openmap/geo/IntersectionTest.java b/src/core/src/test/java/com/bbn/openmap/geo/IntersectionTest.java deleted file mode 100644 index 1eee25d54..000000000 --- a/src/core/src/test/java/com/bbn/openmap/geo/IntersectionTest.java +++ /dev/null @@ -1,752 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.geo; - -import junit.framework.TestCase; - -public class IntersectionTest extends TestCase { - - public double[] swap(double[] input) { - double[] poly = new double[_Polygon.length]; - for (int i = 0; i < _Polygon.length - 1; i += 2) { - poly[i + 1] = _Polygon[i]; - poly[i] = _Polygon[i + 1]; - } - return poly; - } - - // @Test - public void testIsSelfIntersectingPoly() { - double[] poly = swap(_Polygon); - - // assertTrue(Intersection.isSelfIntersectingPoly(toFloatArray(_BadPolygon))); - assertFalse(Intersection.isSelfIntersectingPoly(poly)); - } - - // @Test - public void testIsPointInPolygonGeoGeoArrayBoolean() { - double[] poly = swap(_Polygon); - - GeoArray ga = GeoArray.Double.createFromLatLonDegrees(poly); - GeoRegion reg = new GeoRegion.Impl(poly); - BoundingCircle bound = reg.getBoundingCircle(); - Geo centroid = bound.getCenter(); - Geo internal = Geo.makeGeoDegrees(41.671, -70.492); - assertTrue(Intersection.isPointInPolygon(internal, ga)); - assertTrue(Intersection.isPointInPolygon(centroid, ga, internal)); - assertFalse(Intersection.isPointInPolygon(centroid.antipode(), ga)); - - assertTrue(Intersection.isPointInPolygon(new Geo(42.296, -72.552, true), ga, internal)); - // assertFalse(Intersection.isPointInPolygon(new Geo(39.0, -20, true), ga, - // internal)); - - assertTrue(Intersection.isPointInPolygon(internal, ga)); - // assertTrue(Intersection.isPointInPolygon(centroid, ga)); - assertFalse(Intersection.isPointInPolygon(centroid.antipode(), ga)); - - assertFalse(Intersection.isPointInPolygon(new Geo(38.75, -27.6, true), ga)); - assertFalse(Intersection.isPointInPolygon(new Geo(39.0, -90, true), ga)); - - } - - private static double[] _Polygon = { -73.267463684082031, 42.745159149169922, -73.214195251464844, - 42.743900299072266, -73.076728820800781, 42.740665435791016, -73.023033142089844, 42.739715576171875, - -72.930160522460938, 42.738025665283203, -72.907691955566406, 42.737617492675781, -72.843818664550781, - 42.736457824707031, -72.6099853515625, 42.730937957763672, -72.456634521484375, 42.727611541748047, - -72.348747253417969, 42.724704742431641, -72.283203125, 42.722934722900391, -72.109703063964844, - 42.718254089355469, -71.928733825683594, 42.712970733642578, -71.899391174316406, 42.712112426757812, - -71.865089416503906, 42.710990905761719, -71.629257202148438, 42.704227447509766, -71.385360717773438, - 42.69879150390625, -71.296798706054688, 42.697776794433594, -71.28240966796875, 42.710025787353516, - -71.274276733398438, 42.719100952148438, -71.267379760742188, 42.727725982666016, -71.259872436523438, - 42.73492431640625, -71.256103515625, 42.737686157226562, -71.252357482910156, 42.740428924560547, - -71.24688720703125, 42.743202209472656, -71.246109008789062, 42.743595123291016, -71.237983703613281, - 42.745853424072266, -71.230491638183594, 42.746292114257812, -71.223625183105469, 42.746280670166016, - -71.214897155761719, 42.744895935058594, -71.20367431640625, 42.742145538330078, -71.191200256347656, - 42.739387512207031, -71.184349060058594, 42.737552642822266, -71.189102172851562, 42.790748596191406, - -71.168403625488281, 42.808429718017578, -71.133354187011719, 42.821517944335938, -71.065963745117188, - 42.806312561035156, -71.048210144042969, 42.846710205078125, -71.042549133300781, 42.851692199707031, - -71.036270141601562, 42.855762481689453, -71.031883239746094, 42.858020782470703, -71.025619506835938, - 42.859817504882812, -71.008720397949219, 42.862026214599609, -70.998077392578125, 42.8642578125, - -70.9818115234375, 42.866016387939453, -70.971794128417969, 42.8677978515625, -70.96551513671875, - 42.869590759277344, -70.961128234863281, 42.871391296386719, -70.948577880859375, 42.876338958740234, - -70.933525085449219, 42.882640838623047, -70.925369262695312, 42.885334014892578, -70.916603088378906, - 42.886661529541016, -70.908470153808594, 42.886623382568359, -70.899726867675781, 42.885219573974609, - -70.892242431640625, 42.882911682128906, -70.886009216308594, 42.880611419677734, -70.880401611328125, - 42.877853393554688, -70.871086120605469, 42.871444702148438, -70.860504150390625, 42.865482330322266, - -70.851165771484375, 42.861343383789062, -70.848045349121094, 42.860874176025391, -70.844284057617188, - 42.862220764160156, -70.836128234863281, 42.865364074707031, -70.827964782714844, 42.86895751953125, - -70.818557739257812, 42.871635437011719, -70.816680908203125, 42.871562957763672, -70.814918518066406, - 42.860252380371094, -70.814979553222656, 42.853885650634766, -70.814453125, 42.843879699707031, - -70.813339233398438, 42.830234527587891, -70.812164306640625, 42.822498321533203, -70.816543579101562, - 42.822525024414062, -70.821556091308594, 42.820728302001953, -70.826545715332031, 42.822120666503906, - -70.830917358398438, 42.8221435546875, -70.83966064453125, 42.822643280029297, -70.846565246582031, - 42.819496154785156, -70.857208251953125, 42.816818237304688, -70.865951538085938, 42.816864013671875, - -70.867195129394531, 42.817775726318359, -70.87713623046875, 42.824188232421875, -70.884620666503906, - 42.826042175292969, -70.890243530273438, 42.825614929199219, -70.892143249511719, 42.823352813720703, - -70.889678955078125, 42.819248199462891, -70.886581420898438, 42.816051483154297, -70.879112243652344, - 42.813289642333984, -70.863533020019531, 42.808666229248047, -70.858558654785156, 42.805915832519531, - -70.852981567382812, 42.801342010498047, -70.845512390136719, 42.798576354980469, -70.836784362792969, - 42.796710968017578, -70.831153869628906, 42.797595977783203, -70.828651428222656, 42.79803466796875, - -70.823036193847656, 42.797096252441406, -70.819297790527344, 42.796623229980469, -70.819892883300781, - 42.799354553222656, -70.81787109375, 42.814346313476562, -70.810371398925781, 42.814762115478516, - -70.809181213378906, 42.808387756347656, -70.809242248535156, 42.802478790283203, -70.808692932128906, - 42.795204162597656, -70.807487487792969, 42.790195465087891, -70.806282043457031, 42.786098480224609, - -70.805091857910156, 42.780635833740234, -70.800834655761719, 42.769248962402344, -70.795356750488281, - 42.755126953125, -70.78863525390625, 42.740997314453125, -70.784370422363281, 42.730972290039062, - -70.778846740722656, 42.721851348876953, -70.771469116210938, 42.711357116699219, -70.770896911621094, - 42.706356048583984, -70.770294189453125, 42.704536437988281, -70.770309448242188, 42.703170776367188, - -70.771583557128906, 42.700904846191406, -70.774093627929688, 42.699554443359375, -70.778457641601562, - 42.699581146240234, -70.781562805175781, 42.700958251953125, -70.784042358398438, 42.701881408691406, - -70.785255432128906, 42.705524444580078, -70.790199279785156, 42.710094451904297, -70.790817260742188, - 42.710552215576172, -70.796966552734375, 42.719223022460938, -70.799385070800781, 42.7274169921875, - -70.801193237304688, 42.733791351318359, -70.807342529296875, 42.742462158203125, -70.812309265136719, - 42.745670318603516, -70.816062927246094, 42.744781494140625, -70.817306518554688, 42.744789123535156, - -70.816696166992188, 42.743419647216797, -70.81549072265625, 42.738868713378906, -70.814308166503906, - 42.732498168945312, -70.814979553222656, 42.727954864501953, -70.819374084472656, 42.724796295166016, - -70.818801879882812, 42.719795227050781, -70.818817138671875, 42.718429565429688, -70.818824768066406, - 42.717067718505859, -70.816993713378906, 42.713420867919922, -70.817024230957031, 42.710239410400391, - -70.817680358886719, 42.70660400390625, -70.820823669433594, 42.704803466796875, -70.823951721191406, - 42.703456878662109, -70.824607849121094, 42.699821472167969, -70.822128295898438, 42.698448181152344, - -70.818389892578125, 42.697971343994141, -70.813392639160156, 42.699310302734375, -70.808998107910156, - 42.701557159423828, -70.808372497558594, 42.702011108398438, -70.802757263183594, 42.701980590820312, - -70.796531677246094, 42.701038360595703, -70.790336608886719, 42.696914672851562, -70.7928466796875, - 42.695110321044922, -70.793479919433594, 42.694206237792969, -70.795997619628906, 42.691947937011719, - -70.797271728515625, 42.689228057861328, -70.796035766601562, 42.688312530517578, -70.794166564941406, - 42.687847137451172, -70.789169311523438, 42.688728332519531, -70.783538818359375, 42.690517425537109, - -70.776687622070312, 42.690025329589844, -70.7723388671875, 42.688182830810547, -70.767364501953125, - 42.686790466308594, -70.76300048828125, 42.685855865478516, -70.756156921386719, 42.684452056884766, - -70.748062133789062, 42.68304443359375, -70.741241455078125, 42.679821014404297, -70.737541198730469, - 42.676162719726562, -70.735069274902344, 42.673877716064453, -70.733222961425781, 42.671592712402344, - -70.727066040039062, 42.664737701416016, -70.728958129882812, 42.662933349609375, -70.73516845703125, - 42.664787292480469, -70.738883972167969, 42.667079925537109, -70.743232727050781, 42.668472290039062, - -70.746963500976562, 42.669853210449219, -70.751937866210938, 42.670791625976562, -70.757514953613281, - 42.674461364746094, -70.763717651367188, 42.676769256591797, -70.771865844726562, 42.673175811767578, - -70.773780822753906, 42.669097900390625, -70.775054931640625, 42.666378021240234, -70.774452209472656, - 42.664554595947266, -70.7713623046875, 42.661357879638672, -70.769538879394531, 42.657257080078125, - -70.768951416015625, 42.653617858886719, -70.770225524902344, 42.651351928710938, -70.770240783691406, - 42.649986267089844, -70.766517639160156, 42.648147583007812, -70.765296936035156, 42.645870208740234, - -70.764694213867188, 42.644046783447266, -70.764717102050781, 42.641319274902344, -70.762260437011719, - 42.638580322265625, -70.759765625, 42.638565063476562, -70.752830505371094, 42.645797729492188, - -70.750335693359375, 42.646240234375, -70.747222900390625, 42.645767211914062, -70.745361328125, - 42.645301818847656, -70.7447509765625, 42.643478393554688, -70.745399475097656, 42.641208648681641, - -70.744819641113281, 42.637569427490234, -70.739860534667969, 42.635269165039062, -70.737358093261719, - 42.636161804199219, -70.736709594726562, 42.637977600097656, -70.736686706542969, 42.640251159667969, - -70.735389709472656, 42.644786834716797, -70.732276916503906, 42.644771575927734, -70.7279052734375, - 42.645198822021484, -70.722908020019531, 42.646533966064453, -70.721641540527344, 42.648342132568359, - -70.720977783203125, 42.651519775390625, -70.720924377441406, 42.656520843505859, -70.719635009765625, - 42.660148620605469, -70.716522216796875, 42.660129547119141, -70.712799072265625, 42.658290863037109, - -70.709686279296875, 42.657817840576172, -70.706596374511719, 42.655525207519531, -70.702247619628906, - 42.654136657714844, -70.694778442382812, 42.653179168701172, -70.689811706542969, 42.651786804199219, - -70.684242248535156, 42.648571014404297, -70.685554504394531, 42.642669677734375, -70.686813354492188, - 42.641765594482422, -70.68994140625, 42.640876770019531, -70.698692321777344, 42.638656616210938, - -70.700592041015625, 42.635490417480469, -70.70001220703125, 42.632305145263672, -70.698143005371094, - 42.631839752197266, -70.695648193359375, 42.632278442382812, -70.690673828125, 42.631336212158203, - -70.68695068359375, 42.629951477050781, -70.685081481933594, 42.629940032958984, -70.682579040527344, - 42.630832672119141, -70.680709838867188, 42.630821228027344, -70.679473876953125, 42.629901885986328, - -70.678237915039062, 42.628986358642578, -70.675750732421875, 42.628517150878906, -70.674484252929688, - 42.630325317382812, -70.672569274902344, 42.634407043457031, -70.66937255859375, 42.6407470703125, - -70.670578002929688, 42.643939971923828, -70.673057556152344, 42.645771026611328, -70.672386169433594, - 42.649402618408203, -70.674850463867188, 42.652145385742188, -70.677345275878906, 42.651706695556641, - -70.679214477539062, 42.651718139648438, -70.681068420410156, 42.653095245361328, -70.681632995605469, - 42.658096313476562, -70.679718017578125, 42.662178039550781, -70.674697875976562, 42.664871215820312, - -70.66400146484375, 42.672985076904297, -70.660179138183594, 42.679779052734375, -70.65264892578125, - 42.683368682861328, -70.645736694335938, 42.6878662109375, -70.643882751464844, 42.686038970947266, - -70.640151977539062, 42.685558319091797, -70.631973266601562, 42.690959930419922, -70.628852844238281, - 42.691394805908203, -70.626998901367188, 42.690017700195312, -70.623916625976562, 42.686813354492188, - -70.620811462402344, 42.685882568359375, -70.618980407714844, 42.683143615722656, -70.621612548828125, - 42.672252655029297, -70.62164306640625, 42.669525146484375, -70.621673583984375, 42.667255401611328, - -70.619209289550781, 42.664966583251953, -70.616752624511719, 42.662220001220703, -70.613029479980469, - 42.660377502441406, -70.604324340820312, 42.658954620361328, -70.597488403320312, 42.657543182373047, - -70.595657348632812, 42.654346466064453, -70.596305847167969, 42.652534484863281, -70.593223571777344, - 42.649787902832031, -70.592002868652344, 42.647506713867188, -70.592666625976562, 42.644783020019531, - -70.592704772949219, 42.6416015625, -70.590858459472656, 42.6397705078125, -70.590873718261719, - 42.638408660888672, -70.592185974121094, 42.633869171142578, -70.595314025878906, 42.632984161376953, - -70.598434448242188, 42.632549285888672, -70.600929260253906, 42.632568359375, -70.606536865234375, - 42.632152557373047, -70.610916137695312, 42.631271362304688, -70.615303039550781, 42.6290283203125, - -70.616584777832031, 42.626308441162109, -70.617874145507812, 42.622684478759766, -70.622886657714844, - 42.620445251464844, -70.626655578613281, 42.618198394775391, -70.629791259765625, 42.616401672363281, - -70.628623962402344, 42.610485076904297, -70.629295349121094, 42.606399536132812, -70.6324462890625, - 42.603237152099609, -70.635612487792969, 42.599166870117188, -70.638137817382812, 42.596458435058594, - -70.641288757324219, 42.59375, -70.643165588378906, 42.592857360839844, -70.648796081542969, - 42.591072082519531, -70.650070190429688, 42.588809967041016, -70.650115966796875, 42.585174560546875, - -70.6551513671875, 42.580207824707031, -70.660774230957031, 42.578880310058594, -70.663864135742188, - 42.580718994140625, -70.664459228515625, 42.583450317382812, -70.663185119628906, 42.585258483886719, - -70.661903381347656, 42.588432312011719, -70.659378051757812, 42.591594696044922, -70.65625, - 42.592483520507812, -70.654991149902344, 42.593841552734375, -70.65496826171875, 42.595203399658203, - -70.656196594238281, 42.596576690673828, -70.658050537109375, 42.597953796386719, -70.656784057617188, - 42.599761962890625, -70.656143188476562, 42.601119995117188, -70.65673828125, 42.603397369384766, - -70.656089782714844, 42.605663299560547, -70.662918090820312, 42.607524871826172, -70.671638488769531, - 42.607582092285156, -70.674774169921875, 42.605785369873047, -70.681060791015625, 42.601280212402344, - -70.684959411621094, 42.587215423583984, -70.689353942871094, 42.584060668945312, -70.691871643066406, - 42.582256317138672, -70.695014953613281, 42.579551696777344, -70.699417114257812, 42.575939178466797, - -70.703781127929688, 42.575057983398438, -70.708786010742188, 42.572818756103516, -70.715011596679688, - 42.573307037353516, -70.718772888183594, 42.570606231689453, -70.72503662109375, 42.567462921142578, - -70.726890563964844, 42.568382263183594, -70.731208801269531, 42.572044372558594, -70.736785888671875, - 42.574348449707031, -70.746772766113281, 42.572586059570312, -70.753646850585938, 42.570354461669922, - -70.758033752441406, 42.567653656005859, -70.763679504394531, 42.563594818115234, -70.76806640625, - 42.560440063476562, -70.773078918457031, 42.5577392578125, -70.775558471679688, 42.558208465576172, - -70.780487060546875, 42.563232421875, -70.787361145019531, 42.561000823974609, -70.80169677734375, - 42.558803558349609, -70.820442199707031, 42.551631927490234, -70.832283020019531, 42.549877166748047, - -70.849723815917969, 42.549057006835938, -70.855987548828125, 42.544998168945312, -70.8609619140625, - 42.545475006103516, -70.869674682617188, 42.545970916748047, -70.879051208496094, 42.541019439697266, - -70.887123107910156, 42.542873382568359, -70.890815734863281, 42.548347473144531, -70.8995361328125, - 42.547023773193359, -70.916313171386719, 42.550281524658203, -70.920074462890625, 42.547569274902344, - -70.921348571777344, 42.543483734130859, -70.911407470703125, 42.542076110839844, -70.901481628417969, - 42.538398742675781, -70.8946533203125, 42.536544799804688, -70.89031982421875, 42.533798217773438, - -70.885986328125, 42.531505584716797, -70.883522033691406, 42.527862548828125, -70.872268676757812, - 42.534626007080078, -70.867919921875, 42.533241271972656, -70.86859130859375, 42.528244018554688, - -70.882980346679688, 42.519222259521484, -70.887351989746094, 42.516971588134766, -70.883682250976562, - 42.510139465332031, -70.8843994140625, 42.498779296875, -70.876304626464844, 42.499649047851562, - -70.873794555664062, 42.502365112304688, -70.869384765625, 42.508251190185547, -70.864990234375, - 42.512321472167969, -70.8612060546875, 42.518211364746094, -70.85064697265625, 42.516792297363281, - -70.84381103515625, 42.515850067138672, -70.848289489746094, 42.502693176269531, -70.852104187011719, - 42.493625640869141, -70.8489990234375, 42.493610382080078, -70.837074279785156, 42.50445556640625, - -70.830863952636719, 42.50396728515625, -70.833465576171875, 42.491714477539062, -70.839103698730469, - 42.487651824951172, -70.850288391113281, 42.488616943359375, -70.857139587402344, 42.486835479736328, - -70.86090087890625, 42.484127044677734, -70.867149353027344, 42.480522155761719, -70.872772216796875, - 42.477821350097656, -70.879005432128906, 42.475578308105469, -70.885940551757812, 42.464706420898438, - -70.889068603515625, 42.462902069091797, -70.890953063964844, 42.460639953613281, -70.894699096679688, - 42.458385467529297, -70.90277099609375, 42.460693359375, -70.913307189941406, 42.463924407958984, - -70.922637939453125, 42.463054656982422, -70.928909301757812, 42.456722259521484, -70.93145751953125, - 42.449462890625, -70.932731628417969, 42.445381164550781, -70.93280029296875, 42.437202453613281, - -70.929100036621094, 42.433547973632812, -70.926643371582031, 42.429901123046875, -70.922920227050781, - 42.429431915283203, -70.9185791015625, 42.428050994873047, -70.908645629882812, 42.426189422607422, - -70.905563354492188, 42.423446655273438, -70.901878356933594, 42.418888092041016, -70.905014038085938, - 42.415721893310547, -70.9130859375, 42.415756225585938, -70.924873352050781, 42.418991088867188, - -70.931724548339844, 42.416294097900391, -70.93731689453125, 42.416770935058594, -70.941558837890625, - 42.429058074951172, -70.942115783691406, 42.437240600585938, -70.944557189941406, 42.443611145019531, - -70.950752258300781, 42.445457458496094, -70.953857421875, 42.444095611572266, -70.957611083984375, - 42.442306518554688, -70.965744018554688, 42.435523986816406, -70.975135803222656, 42.426471710205078, - -70.982017517089844, 42.420139312744141, -70.988906860351562, 42.4119873046875, -70.988960266113281, - 42.404716491699219, -70.985885620117188, 42.400615692138672, -70.985923767089844, 42.395164489746094, - -70.98345947265625, 42.393341064453125, -70.976020812988281, 42.391040802001953, -70.972312927246094, - 42.388751983642578, -70.967987060546875, 42.386463165283203, -70.972358703613281, 42.382846832275391, - -70.971771240234375, 42.378299713134766, -70.962547302246094, 42.366905212402344, -70.958900451660156, - 42.356891632080078, -70.952140808105469, 42.346870422363281, -70.954643249511719, 42.344608306884766, - -70.969467163085938, 42.355117797851562, -70.972549438476562, 42.357402801513672, -70.974395751953125, - 42.359226226806641, -70.974380493164062, 42.361953735351562, -70.971855163574219, 42.366943359375, - -70.974319458007812, 42.369678497314453, -70.977424621582031, 42.36968994140625, -70.984886169433594, - 42.368354797363281, -70.989845275878906, 42.369285583496094, -70.994171142578125, 42.371574401855469, - -70.99664306640625, 42.373401641845703, -70.9959716796875, 42.380214691162109, -71.000923156738281, - 42.382503509521484, -71.005889892578125, 42.382522583007812, -71.007781982421875, 42.377986907958984, - -71.00408935546875, 42.373428344726562, -71.001014709472656, 42.369327545166016, -70.997955322265625, - 42.362953186035156, -70.994873046875, 42.360671997070312, -70.990524291992188, 42.36065673828125, - -70.988067626953125, 42.357917785644531, -70.989334106445312, 42.354290008544922, -70.994316101074219, - 42.351581573486328, -70.998039245605469, 42.35205078125, -71.00115966796875, 42.34979248046875, - -71.003646850585938, 42.348892211914062, -71.005508422851562, 42.348445892333984, -71.009223937988281, - 42.349822998046875, -71.024055480957031, 42.359416961669922, -71.045730590820312, 42.366767883300781, - -71.048225402832031, 42.364501953125, -71.047660827636719, 42.355869293212891, -71.052024841308594, - 42.352703094482422, -71.055168151855469, 42.346351623535156, -71.050209045410156, 42.345424652099609, - -71.037757873535156, 42.351291656494141, -71.033439636230469, 42.347640991210938, -71.01983642578125, - 42.340774536132812, -71.0155029296875, 42.338943481445312, -71.014930725097656, 42.332122802734375, - -71.02301025390625, 42.330337524414062, -71.028610229492188, 42.327632904052734, -71.031112670898438, - 42.324916839599609, -71.037315368652344, 42.324939727783203, -71.045394897460938, 42.322238922119141, - -71.045417785644531, 42.319515228271484, -71.044815063476562, 42.316787719726562, -71.035530090332031, - 42.31402587890625, -71.046142578125, 42.303615570068359, -71.046173095703125, 42.299072265625, - -71.044380187988281, 42.288616180419922, -71.037582397460938, 42.284957885742188, -71.033775329589844, - 42.298122406005859, -71.031272888183594, 42.300384521484375, -71.027565002441406, 42.299007415771484, - -71.021995544433594, 42.297622680664062, -71.017013549804688, 42.300331115722656, -71.005203247070312, - 42.304828643798828, -70.995277404785156, 42.304336547851562, -70.99530029296875, 42.301155090332031, - -71.000907897949219, 42.298000335693359, -71.004653930664062, 42.294376373291016, -71.009017944335938, - 42.291213989257812, -71.018325805664062, 42.289432525634766, -71.019599914550781, 42.285346984863281, - -71.017753601074219, 42.282615661621094, -71.010971069335938, 42.278045654296875, -71.0023193359375, - 42.273471832275391, -70.998016357421875, 42.268913269042969, -70.9906005859375, 42.264793395996094, - -70.976966857910156, 42.264286041259766, -70.972007751464844, 42.264720916748047, -70.965774536132812, - 42.269237518310547, -70.954582214355469, 42.273281097412109, -70.949012756347656, 42.271892547607422, - -70.950302124023438, 42.2659912109375, -70.9503173828125, 42.263267517089844, -70.955314636230469, - 42.259201049804688, -70.957199096679688, 42.256027221679688, -70.961570739746094, 42.251502990722656, - -70.965301513671875, 42.249248504638672, -70.970268249511719, 42.248813629150391, -70.970909118652344, - 42.246089935302734, -70.973403930664062, 42.243827819824219, -70.973434448242188, 42.239738464355469, - -70.972831726074219, 42.237010955810547, -70.967269897460938, 42.235626220703125, -70.966041564941406, - 42.234260559082031, -70.963584899902344, 42.230613708496094, -70.960502624511719, 42.228782653808594, - -70.956146240234375, 42.231491088867188, -70.957977294921875, 42.23468017578125, -70.960411071777344, - 42.240596771240234, -70.958526611328125, 42.244678497314453, -70.954177856445312, 42.246021270751953, - -70.94732666015625, 42.249626159667969, -70.938621520996094, 42.253677368164062, -70.935546875, - 42.250484466552734, -70.940559387207031, 42.244144439697266, -70.939353942871094, 42.239597320556641, - -70.936286926269531, 42.235496520996094, -70.931983947753906, 42.231842041015625, -70.930130004882812, - 42.231380462646484, -70.925155639648438, 42.233631134033203, -70.922042846679688, 42.234977722167969, - -70.9207763671875, 42.238609313964844, -70.922622680664062, 42.239524841308594, -70.925064086914062, - 42.244529724121094, -70.921295166015625, 42.250873565673828, -70.907569885253906, 42.260807037353516, - -70.897651672363281, 42.261215209960938, -70.894561767578125, 42.260292053222656, -70.897750854492188, - 42.250312805175781, -70.894058227539062, 42.247116088867188, -70.88909912109375, 42.247093200683594, - -70.884132385253906, 42.247978210449219, -70.880401611328125, 42.249324798583984, -70.882827758789062, - 42.255241394042969, -70.880340576171875, 42.256591796875, -70.876625061035156, 42.256118774414062, - -70.873550415039062, 42.253379821777344, -70.870445251464844, 42.253818511962891, -70.866714477539062, - 42.255615234375, -70.862991333007812, 42.256053924560547, -70.861717224121094, 42.259681701660156, - -70.862899780273438, 42.266048431396484, -70.868446350097656, 42.269710540771484, -70.873367309570312, - 42.273822784423828, -70.876457214355469, 42.274745941162109, -70.883270263671875, 42.275230407714844, - -70.881996154785156, 42.279312133789062, -70.882575988769531, 42.284313201904297, -70.886222839355469, - 42.292510986328125, -70.889892578125, 42.298431396484375, -70.899177551269531, 42.299839019775391, - -70.908500671386719, 42.297611236572266, -70.9140625, 42.299453735351562, -70.919639587402344, - 42.30084228515625, -70.919609069824219, 42.304019927978516, -70.907180786132812, 42.307144165039062, - -70.889793395996094, 42.309337615966797, -70.8804931640625, 42.309291839599609, -70.881156921386719, - 42.304298400878906, -70.876274108886719, 42.295188903808594, -70.868316650390625, 42.283790588378906, - -70.856010437011719, 42.273281097412109, -70.853546142578125, 42.272361755371094, -70.842430114746094, - 42.26776123046875, -70.826927185058594, 42.265426635742188, -70.823860168457031, 42.264942169189453, - -70.80841064453125, 42.260318756103516, -70.796676635742188, 42.255710601806641, -70.793083190917969, - 42.243427276611328, -70.791328430175781, 42.232967376708984, -70.786170959472656, 42.233951568603516, - -70.783828735351562, 42.239288330078125, -70.779472351074219, 42.241077423095703, -70.775749206542969, - 42.241966247558594, -70.771385192871094, 42.244213104248047, -70.770698547363281, 42.251026153564453, - -70.766342163085938, 42.252361297607422, -70.761451721191406, 42.246429443359375, -70.758476257324219, - 42.234603881835938, -70.747444152832031, 42.223640441894531, -70.730842590332031, 42.212184906005859, - -70.720359802246094, 42.208034515380859, -70.724128723144531, 42.203060150146484, -70.724800109863281, - 42.198520660400391, -70.721076965332031, 42.198497772216797, -70.716094970703125, 42.200740814208984, - -70.714866638183594, 42.199821472167969, -70.713661193847656, 42.197090148925781, -70.714927673339844, - 42.194828033447266, -70.715568542480469, 42.192562103271484, -70.71685791015625, 42.188022613525391, - -70.71630859375, 42.182117462158203, -70.713981628417969, 42.168472290039062, -70.715873718261719, - 42.165760040283203, -70.723915100097656, 42.166263580322266, -70.728858947753906, 42.166748046875, - -70.735099792480469, 42.161788940429688, -70.730789184570312, 42.160400390625, -70.724578857421875, - 42.162178039550781, -70.717788696289062, 42.160320281982422, -70.715965270996094, 42.157585144042969, - -70.714790344238281, 42.15167236328125, -70.712379455566406, 42.145755767822266, -70.704353332519531, - 42.144794464111328, -70.70428466796875, 42.150245666503906, -70.709121704101562, 42.160724639892578, - -70.706634521484375, 42.161617279052734, -70.704154968261719, 42.161602020263672, -70.702323913574219, - 42.159317016601562, -70.701118469238281, 42.156585693359375, -70.69256591796875, 42.147445678710938, - -70.681015014648438, 42.129661560058594, -70.670059204101562, 42.114601135253906, -70.64495849609375, - 42.093544006347656, -70.639457702636719, 42.088058471679688, -70.639595031738281, 42.077159881591797, - -70.641456604003906, 42.076263427734375, -70.645797729492188, 42.074928283691406, -70.647689819335938, - 42.071762084960938, -70.647735595703125, 42.068126678466797, -70.646553039550781, 42.064033508300781, - -70.6435546875, 42.056743621826172, -70.638710021972656, 42.048538208007812, -70.62347412109375, - 42.031177520751953, -70.611274719238281, 42.018833160400391, -70.607009887695312, 42.014259338378906, - -70.597244262695312, 42.005561828613281, -70.597892761230469, 42.002841949462891, -70.60284423828125, - 42.001968383789062, -70.610206604003906, 42.006107330322266, -70.617652893066406, 42.003433227539062, - -70.623863220214844, 42.000297546386719, -70.627021789550781, 41.994869232177734, -70.633224487304688, - 41.992183685302734, -70.636924743652344, 41.992664337158203, -70.63812255859375, 41.995849609375, - -70.637474060058594, 41.998119354248047, -70.636215209960938, 41.999923706054688, -70.634353637695312, - 42.000823974609375, -70.629989624023438, 42.003971099853516, -70.623153686523438, 42.007556915283203, - -70.620033264160156, 42.010261535644531, -70.621788024902344, 42.017993927001953, -70.63031005859375, - 42.028045654296875, -70.640068054199219, 42.038555145263672, -70.644309997558594, 42.045394897460938, - -70.649803161621094, 42.050884246826172, -70.651618957519531, 42.054073333740234, -70.6546630859375, - 42.057727813720703, -70.657066345214844, 42.063190460205078, -70.668838500976562, 42.061000823974609, - -70.671958923339844, 42.058292388916016, -70.673233032226562, 42.055576324462891, -70.671409606933594, - 42.052841186523438, -70.668937683105469, 42.0523681640625, -70.665855407714844, 42.051895141601562, - -70.659713745117188, 42.048675537109375, -70.655403137207031, 42.047740936279297, -70.654212951660156, - 42.044097900390625, -70.662872314453125, 42.043247222900391, -70.6666259765625, 42.0391845703125, - -70.66790771484375, 42.035106658935547, -70.669189453125, 42.031478881835938, -70.670455932617188, - 42.029216766357422, -70.672966003417969, 42.025600433349609, -70.676727294921875, 42.020626068115234, - -70.668128967285156, 42.016937255859375, -70.666946411132812, 42.01239013671875, -70.668220520019531, - 42.009220123291016, -70.674446105957031, 42.005168914794922, -70.676300048828125, 42.004730224609375, - -70.678764343261719, 42.005199432373047, -70.682441711425781, 42.007492065429688, -70.686698913574219, - 42.013423919677734, -70.68975830078125, 42.015712738037109, -70.697212219238281, 42.012126922607422, - -70.710243225097656, 42.006755828857422, -70.709686279296875, 42.001758575439453, -70.704154968261719, - 41.99945068359375, -70.698654174804688, 41.993968963623047, -70.696884155273438, 41.987144470214844, - -70.683990478515625, 41.980705261230469, -70.6766357421875, 41.976119995117188, -70.671150207519531, - 41.970634460449219, -70.666915893554688, 41.963340759277344, -70.660797119140625, 41.958305358886719, - -70.652847290039062, 41.952804565429688, -70.647293090820312, 41.952316284179688, -70.645416259765625, - 41.954570770263672, -70.644149780273438, 41.957290649414062, -70.642875671386719, 41.960910797119141, - -70.645896911621094, 41.965930938720703, -70.650146484375, 41.971858978271484, -70.653785705566406, - 41.976879119873047, -70.651283264160156, 41.979587554931641, -70.648834228515625, 41.97821044921875, - -70.645179748535156, 41.974098205566406, -70.64093017578125, 41.968166351318359, -70.637306213378906, - 41.961784362792969, -70.631256103515625, 41.95220947265625, -70.628227233886719, 41.947647094726562, - -70.624580383300781, 41.943080902099609, -70.62274169921875, 41.942157745361328, -70.619674682617188, - 41.940776824951172, -70.610420227050781, 41.940711975097656, -70.60546875, 41.942039489746094, - -70.600471496582031, 41.946548461914062, -70.594902038574219, 41.947872161865234, -70.5911865234375, - 41.948299407958984, -70.586257934570312, 41.947811126708984, -70.576431274414062, 41.944107055664062, - -70.567230224609375, 41.939952850341797, -70.562355041503906, 41.935379028320312, -70.553779602050781, - 41.930774688720703, -70.545806884765625, 41.927536010742188, -70.538406372070312, 41.927482604980469, - -70.539138793945312, 41.918857574462891, -70.547187805175781, 41.916648864746094, -70.547264099121094, - 41.911197662353516, -70.544281005859375, 41.903911590576172, -70.541252136230469, 41.899799346923828, - -70.5345458984375, 41.893848419189453, -70.530296325683594, 41.889274597167969, -70.531074523925781, - 41.877479553222656, -70.531852722167969, 41.866130828857422, -70.52642822265625, 41.857009887695312, - -70.53021240234375, 41.850681304931641, -70.534034729003906, 41.841625213623047, -70.54345703125, - 41.828529357910156, -70.544822692871094, 41.818550109863281, -70.540657043457031, 41.808074951171875, - -70.526046752929688, 41.795707702636719, -70.508941650390625, 41.786495208740234, -70.49432373046875, - 41.775482177734375, -70.488227844238281, 41.771350860595703, -70.476028442382812, 41.763534545898438, - -70.427642822265625, 41.748157501220703, -70.38104248046875, 41.737773895263672, -70.349082946777344, - 41.735675811767578, -70.31341552734375, 41.734897613525391, -70.295600891113281, 41.733375549316406, - -70.287033081054688, 41.730567932128906, -70.278495788574219, 41.726402282714844, -70.276710510253906, - 41.722755432128906, -70.282264709472656, 41.721900939941406, -70.288383483886719, 41.723770141601562, - -70.292091369628906, 41.722900390625, -70.295814514160156, 41.720664978027344, -70.300102233886719, - 41.722064971923828, -70.3062744140625, 41.720760345458984, -70.311126708984375, 41.724437713623047, - -70.319709777832031, 41.726329803466797, -70.327728271484375, 41.725040435791016, -70.335136413574219, - 41.723293304443359, -70.343757629394531, 41.722915649414062, -70.350502014160156, 41.723884582519531, - -70.354835510253906, 41.722560882568359, -70.351852416992188, 41.716632843017578, -70.345756530761719, - 41.713401794433594, -70.333488464355469, 41.711475372314453, -70.313209533691406, 41.710384368896484, - -70.301536560058594, 41.709819793701172, -70.292922973632812, 41.710193634033203, -70.284934997558594, - 41.709663391113281, -70.274436950683594, 41.712291717529297, -70.268882751464844, 41.713146209716797, - -70.265815734863281, 41.712661743164062, -70.2640380859375, 41.709011077880859, -70.259735107421875, - 41.708972930908203, -70.258415222167969, 41.713951110839844, -70.252182006835938, 41.718433380126953, - -70.249053955078125, 41.721580505371094, -70.242263793945312, 41.722873687744141, -70.2379150390625, - 41.725559234619141, -70.240310668945312, 41.728759765625, -70.23529052734375, 41.734611511230469, - -70.219779968261719, 41.741725921630859, -70.190071105957031, 41.750961303710938, -70.182708740234375, - 41.749977111816406, -70.159820556640625, 41.756095886230469, -70.153709411621094, 41.753765106201172, - -70.151313781738281, 41.750560760498047, -70.142539978027344, 41.758644104003906, -70.133293151855469, - 41.759452819824219, -70.128395080566406, 41.758037567138672, -70.124122619628906, 41.756175994873047, - -70.119735717773438, 41.760215759277344, -70.115409851074219, 41.761077880859375, -70.1092529296875, - 41.761466979980469, -70.096855163574219, 41.765872955322266, -70.083251953125, 41.768901824951172, - -70.050460815429688, 41.777164459228516, -70.039276123046875, 41.782032012939453, -70.024391174316406, - 41.787311553955078, -70.018096923828125, 41.793598175048828, -70.009330749511719, 41.800758361816406, - -70.004302978515625, 41.805240631103516, -70.004043579101562, 41.817497253417969, -70.005668640136719, - 41.827960968017578, -70.004135131835938, 41.842021942138672, -70.007568359375, 41.854320526123047, - -70.009262084960938, 41.861606597900391, -70.010986328125, 41.867530822753906, -70.010910034179688, - 41.871162414550781, -70.010208129882812, 41.875240325927734, -70.010757446289062, 41.878425598144531, - -70.008857727050781, 41.88067626953125, -70.002571105957031, 41.886505126953125, -70.004989624023438, - 41.888805389404297, -70.008644104003906, 41.890663146972656, -70.012351989746094, 41.890251159667969, - -70.016677856445312, 41.889846801757812, -70.020347595214844, 41.891254425048828, -70.023391723632812, - 41.893104553222656, -70.024559020996094, 41.896293640136719, -70.023292541503906, 41.89764404296875, - -70.021430969238281, 41.898532867431641, -70.017723083496094, 41.898941040039062, -70.013397216796875, - 41.899345397949219, -70.009757995605469, 41.896125793457031, -70.003578186035156, 41.896965026855469, - -70.004119873046875, 41.900604248046875, -70.004638671875, 41.9051513671875, -69.997787475585938, - 41.908248901367188, -70.003883361816406, 41.9114990234375, -70.009498596191406, 41.90838623046875, - -70.017539978027344, 41.907569885253906, -70.022468566894531, 41.907627105712891, -70.024299621582031, - 41.908554077148438, -70.027931213378906, 41.911773681640625, -70.030342102050781, 41.914527893066406, - -70.032112121582031, 41.918182373046875, -70.034553527832031, 41.919570922851562, -70.03509521484375, - 41.923210144042969, -70.036293029785156, 41.925041198730469, -70.038719177246094, 41.926883697509766, - -70.042396545410156, 41.927837371826172, -70.047935485839844, 41.928806304931641, -70.054779052734375, - 41.926155090332031, -70.06353759765625, 41.919895172119141, -70.064788818359375, 41.919002532958984, - -70.063117980957031, 41.910354614257812, -70.063232421875, 41.9049072265625, -70.063369750976562, - 41.898097991943359, -70.067741394042969, 41.895420074462891, -70.066070556640625, 41.886772155761719, - -70.063072204589844, 41.882652282714844, -70.0618896484375, 41.879913330078125, -70.063201904296875, - 41.876296997070312, -70.068756103515625, 41.875904083251953, -70.072402954101562, 41.878669738769531, - -70.074790954589844, 41.882328033447266, -70.075912475585938, 41.887790679931641, -70.075767517089844, - 41.895053863525391, -70.075592041015625, 41.903682708740234, -70.07666015625, 41.911869049072266, - -70.077178955078125, 41.916416168212891, -70.077674865722656, 41.922325134277344, -70.078170776367188, - 41.928234100341797, -70.078689575195312, 41.933235168457031, -70.07916259765625, 41.940505981445312, - -70.078964233398438, 41.950035095214844, -70.078125, 41.960929870605469, -70.077964782714844, - 41.969104766845703, -70.078422546386719, 41.976829528808594, -70.079483032226562, 41.985469818115234, - -70.081130981445312, 41.995479583740234, -70.082794189453125, 42.004581451416016, -70.087570190429688, - 42.012805938720703, -70.092292785644531, 42.023761749267578, -70.099555969238281, 42.031108856201172, - -70.107460021972656, 42.037551879882812, -70.116020202636719, 42.042182922363281, -70.124610900878906, - 42.045455932617188, -70.1331787109375, 42.050086975097656, -70.138694763183594, 42.052417755126953, - -70.147918701171875, 42.054786682128906, -70.155303955078125, 42.056224822998047, -70.163948059082031, - 42.056770324707031, -70.171401977539062, 42.055030822753906, -70.18011474609375, 42.051486968994141, - -70.185752868652344, 42.047454833984375, -70.1895751953125, 42.041587829589844, -70.195228576660156, - 42.036647796630859, -70.198341369628906, 42.035320281982422, -70.199600219726562, 42.033969879150391, - -70.200874328613281, 42.03216552734375, -70.197242736816406, 42.028041839599609, -70.194816589355469, - 42.025745391845703, -70.188629150390625, 42.026134490966797, -70.181808471679688, 42.027427673339844, - -70.172447204589844, 42.032329559326172, -70.166877746582031, 42.032726287841797, -70.168212890625, - 42.027744293212891, -70.179458618164062, 42.021045684814453, -70.190597534179688, 42.019798278808594, - -70.198616027832031, 42.020332336425781, -70.208343505859375, 42.029060363769531, -70.214378356933594, - 42.036842346191406, -70.217964172363281, 42.043235778808594, -70.22161865234375, 42.046451568603516, - -70.225250244140625, 42.050575256347656, -70.228912353515625, 42.052883148193359, -70.232574462890625, - 42.055644989013672, -70.234382629394531, 42.057933807373047, -70.23187255859375, 42.0601806640625, - -70.232452392578125, 42.062454223632812, -70.235527038574219, 42.062938690185547, -70.241775512695312, - 42.059368133544922, -70.244842529296875, 42.060760498046875, -70.244155883789062, 42.064388275146484, - -70.242843627929688, 42.068462371826172, -70.239067077636719, 42.072513580322266, -70.229721069335938, - 42.076507568359375, -70.221023559570312, 42.078693389892578, -70.205543518066406, 42.079902648925781, - -70.195030212402344, 42.080249786376953, -70.18267822265625, 42.079673767089844, -70.167839050292969, - 42.079521179199219, -70.135215759277344, 42.072368621826172, -70.108772277832031, 42.065273284912109, - -70.088523864746094, 42.057331085205078, -70.070785522460938, 42.048507690429688, -70.056770324707031, - 42.038810729980469, -70.045242309570312, 42.028690338134766, -70.03314208984375, 42.016292572021484, - -70.019927978515625, 41.998878479003906, -70.005531311035156, 41.978729248046875, -69.9906005859375, - 41.955394744873047, -69.979301452636719, 41.935733795166016, -69.974624633789062, 41.923873901367188, - -69.963951110839844, 41.904216766357422, -69.9564208984375, 41.882328033447266, -69.950706481933594, - 41.861824035644531, -69.943092346191406, 41.844024658203125, -69.939010620117188, 41.833076477050781, - -69.936225891113281, 41.819873809814453, -69.934562683105469, 41.811679840087891, -69.936500549316406, - 41.8076171875, -69.940818786621094, 41.807216644287109, -69.941993713378906, 41.809955596923828, - -69.944168090820312, 41.82269287109375, -69.946441650390625, 41.831802368164062, -69.947608947753906, - 41.834541320800781, -69.951904296875, 41.835498809814453, -69.954933166503906, 41.837806701660156, - -69.958656311035156, 41.836490631103516, -69.962387084960938, 41.835170745849609, -69.966819763183594, - 41.82977294921875, -69.964508056640625, 41.822483062744141, -69.962799072265625, 41.816104888916016, - -69.965362548828125, 41.811595916748047, -69.969718933105469, 41.809375762939453, -69.970970153808594, - 41.808483123779297, -69.97662353515625, 41.803558349609375, -69.9842529296875, 41.792293548583984, - -69.983757019042969, 41.786838531494141, -69.978790283203125, 41.788597106933594, -69.970649719238281, - 41.79486083984375, -69.965019226074219, 41.798877716064453, -69.957511901855469, 41.804237365722656, - -69.955741882324219, 41.800582885742188, -69.952812194824219, 41.794193267822266, -69.949119567871094, - 41.794147491455078, -69.944061279296875, 41.799991607666016, -69.933601379394531, 41.799407958984375, - -69.934310913085938, 41.795330047607422, -69.931907653808594, 41.792575836181641, -69.931007385253906, - 41.778034210205078, -69.930145263671875, 41.761222839355469, -69.92822265625, 41.737133026123047, - -69.925621032714844, 41.716217041015625, -69.925399780273438, 41.698505401611328, -69.927635192871094, - 41.681278228759766, -69.933509826660156, 41.665912628173828, -69.939216613769531, 41.657814025878906, - -69.949302673339844, 41.646583557128906, -69.952888488769531, 41.651168823242188, -69.944549560546875, - 41.666957855224609, -69.937629699707031, 41.674137115478516, -69.936820983886719, 41.682750701904297, - -69.936012268066406, 41.691368103027344, -69.9346923828125, 41.695438385009766, -69.934623718261719, - 41.698619842529297, -69.932113647460938, 41.700859069824219, -69.931983947753906, 41.706760406494141, - -69.934158325195312, 41.719497680664062, -69.935676574707031, 41.734046936035156, -69.937171936035156, - 41.749958038330078, -69.938362121582031, 41.751789093017578, -69.940116882324219, 41.755897521972656, - -69.942405700683594, 41.763641357421875, -69.945907592773438, 41.772312164306641, -69.950859069824219, - 41.771011352539062, -69.95465087890625, 41.766513824462891, -69.957778930664062, 41.7642822265625, - -69.963203430175781, 41.769340515136719, -69.969322204589844, 41.771228790283203, -69.972434997558594, - 41.769451141357422, -69.970657348632812, 41.766250610351562, -69.964019775390625, 41.760269165039062, - -69.962890625, 41.755714416503906, -69.970352172851562, 41.752170562744141, -69.968574523925781, - 41.748973846435547, -69.970474243164062, 41.746723175048828, -69.969413757324219, 41.738536834716797, - -69.971305847167969, 41.736743927001953, -69.981758117675781, 41.736869812011719, -69.98919677734375, - 41.734233856201172, -69.993064880371094, 41.726104736328125, -69.99627685546875, 41.719783782958984, - -69.995162963867188, 41.714324951171875, -69.993377685546875, 41.711578369140625, -69.985305786132812, - 41.715118408203125, -69.982192993164062, 41.716896057128906, -69.976646423339844, 41.71728515625, - -69.975456237792969, 41.7154541015625, -69.980484008789062, 41.710517883300781, -69.980560302734375, - 41.706886291503906, -69.975692749023438, 41.704559326171875, -69.9732666015625, 41.703166961669922, - -69.967735290527344, 41.703102111816406, -69.962753295898438, 41.705768585205078, -69.958404541015625, - 41.707530975341797, -69.951705932617188, 41.704727172851562, -69.951194763183594, 41.700180053710938, - -69.951400756835938, 41.690647125244141, -69.946746826171875, 41.678787231445312, -69.950637817382812, - 41.669754028320312, -69.961395263671875, 41.655357360839844, -69.968093872070312, 41.658157348632812, - -69.960517883300781, 41.6676025390625, -69.962287902832031, 41.670799255371094, -69.972213745117188, - 41.666831970214844, -69.979011535644531, 41.665096282958984, -69.985122680664062, 41.666534423828125, - -69.980903625488281, 41.662849426269531, -69.98406982421875, 41.658348083496094, -69.987716674804688, - 41.660205841064453, -69.991378784179688, 41.661609649658203, -69.998023986816406, 41.666683197021484, - -70.008377075195312, 41.671344757080078, -70.020095825195312, 41.669662475585938, -70.036125183105469, - 41.667121887207031, -70.053367614746094, 41.665500640869141, -70.064498901367188, 41.662448883056641, - -70.073074340820312, 41.6634521484375, -70.087852478027344, 41.662254333496094, -70.104522705078125, - 41.658802032470703, -70.124885559082031, 41.65447998046875, -70.142822265625, 41.648769378662109, - -70.162437438964844, 41.6512451171875, -70.178459167480469, 41.648685455322266, -70.18768310546875, - 41.648326873779297, -70.1932373046875, 41.647018432617188, -70.196907043457031, 41.647964477539062, - -70.202537536621094, 41.642574310302734, -70.2105712890625, 41.639930725097656, -70.235305786132812, - 41.631095886230469, -70.25390625, 41.621292114257812, -70.255256652832031, 41.614494323730469, - -70.262710571289062, 41.610027313232422, -70.265785217285156, 41.609603881835938, -70.268814086914062, - 41.611900329589844, -70.269905090332031, 41.61962890625, -70.267929077148438, 41.627330780029297, - -70.263648986816406, 41.626377105712891, -70.259346008300781, 41.626338958740234, -70.257461547851562, - 41.629043579101562, -70.250053405761719, 41.630786895751953, -70.243263244628906, 41.632991790771484, - -70.2437744140625, 41.638442993164062, -70.258415222167969, 41.644489288330078, -70.269462585449219, - 41.645050048828125, -70.275703430175781, 41.639659881591797, -70.272705078125, 41.635543823242188, - -70.27398681640625, 41.632381439208984, -70.277671813964844, 41.632415771484375, -70.282546997070312, - 41.634731292724609, -70.295463562011719, 41.633945465087891, -70.307868957519531, 41.626796722412109, - -70.316482543945312, 41.625968933105469, -70.318336486816406, 41.625080108642578, -70.331100463867188, - 41.633365631103516, -70.343978881835938, 41.634845733642578, -70.356918334960938, 41.632236480712891, - -70.362571716308594, 41.624568939208984, -70.371330261230469, 41.614658355712891, -70.384925842285156, - 41.609329223632812, -70.396003723144531, 41.608062744140625, -70.396575927734375, 41.610336303710938, - -70.3922119140625, 41.614837646484375, -70.390953063964844, 41.616645812988281, -70.3927001953125, - 41.62255859375, -70.394523620605469, 41.623935699462891, -70.394462585449219, 41.627567291259766, - -70.395034790039062, 41.630298614501953, -70.395584106445312, 41.634387969970703, -70.399215698242188, - 41.638053894042969, -70.405967712402344, 41.638565063476562, -70.410316467285156, 41.635425567626953, - -70.4134521484375, 41.631362915039062, -70.423988342285156, 41.62554931640625, -70.43267822265625, - 41.619720458984375, -70.432807922363281, 41.611095428466797, -70.435317993164062, 41.607486724853516, - -70.439697265625, 41.602073669433594, -70.451576232910156, 41.588096618652344, -70.4620361328125, - 41.586368560791016, -70.457260131835938, 41.577247619628906, -70.465377807617188, 41.567783355712891, - -70.474685668945312, 41.561046600341797, -70.480880737304688, 41.557010650634766, -70.489517211914062, - 41.553447723388672, -70.492607116699219, 41.552108764648438, -70.498771667480469, 41.549888610839844, - -70.508590698242188, 41.549964904785156, -70.51104736328125, 41.549530029296875, -70.514122009277344, - 41.549552917480469, -70.520881652832031, 41.548698425292969, -70.522689819335938, 41.550979614257812, - -70.515869140625, 41.555923461914062, -70.51641845703125, 41.560466766357422, -70.520492553710938, - 41.576385498046875, -70.524757385253906, 41.578689575195312, -70.529106140136719, 41.575088500976562, - -70.53363037109375, 41.558326721191406, -70.533737182617188, 41.550609588623047, -70.533760070800781, - 41.549251556396484, -70.544784545898438, 41.550239562988281, -70.555252075195312, 41.547592163085938, - -70.572456359863281, 41.545902252197266, -70.576751708984375, 41.545932769775391, -70.577949523925781, - 41.547760009765625, -70.579093933105469, 41.554122924804688, -70.577774047851562, 41.561374664306641, - -70.581405639648438, 41.565486907958984, -70.583251953125, 41.565044403076172, -70.586380004882812, - 41.560073852539062, -70.587074279785156, 41.554176330566406, -70.587821960449219, 41.543743133544922, - -70.595207214355469, 41.541980743408203, -70.603797912597656, 41.541587829589844, -70.612358093261719, - 41.543914794921875, -70.630851745605469, 41.5372314453125, -70.646316528320312, 41.526443481445312, - -70.653770446777344, 41.518321990966797, -70.657493591308594, 41.514713287353516, -70.662979125976562, - 41.517929077148438, -70.669082641601562, 41.520236968994141, -70.673332214355469, 41.523895263671875, - -70.680084228515625, 41.523483276367188, -70.684432983398438, 41.518520355224609, -70.687484741210938, - 41.5198974609375, -70.689872741699219, 41.525810241699219, -70.684295654296875, 41.530769348144531, - -70.667030334472656, 41.537921905517578, -70.661476135253906, 41.541065216064453, -70.6583251953125, - 41.5478515625, -70.655136108398438, 41.557819366455078, -70.652580261230469, 41.566425323486328, - -70.642051696777344, 41.574527740478516, -70.643218994140625, 41.579074859619141, -70.6456298828125, - 41.582721710205078, -70.64801025390625, 41.589092254638672, -70.647956848144531, 41.593631744384766, - -70.64599609375, 41.603153228759766, -70.650230407714844, 41.608627319335938, -70.648971557617188, - 41.611343383789062, -70.647102355957031, 41.613597869873047, -70.643302917480469, 41.622653961181641, - -70.64202880859375, 41.626277923583984, -70.646827697753906, 41.635841369628906, -70.64984130859375, - 41.640403747558594, -70.649162292480469, 41.645847320556641, -70.628189086914062, 41.652969360351562, - -70.626304626464844, 41.656135559082031, -70.631187438964844, 41.658889770507812, -70.637313842773438, - 41.660293579101562, -70.644706726074219, 41.658981323242188, -70.650810241699219, 41.662200927734375, - -70.654457092285156, 41.665855407714844, -70.651344299316406, 41.668560028076172, -70.643959045410156, - 41.669872283935547, -70.629837036132812, 41.668415069580078, -70.623054504394531, 41.670185089111328, - -70.618705749511719, 41.673786163330078, -70.622955322265625, 41.678356170654297, -70.625923156738281, - 41.686550140380859, -70.632041931152344, 41.689315795898438, -70.638206481933594, 41.687538146972656, - -70.641334533691406, 41.683475494384766, -70.645675659179688, 41.680324554443359, -70.656761169433594, - 41.678581237792969, -70.658584594726562, 41.679954528808594, -70.657905578613281, 41.685401916503906, - -70.645500183105469, 41.694400787353516, -70.62823486328125, 41.698822021484375, -70.620208740234375, - 41.701038360595703, -70.623115539550781, 41.714675903320312, -70.6224365234375, 41.719669342041016, - -70.629875183105469, 41.715179443359375, -70.634170532226562, 41.715660095214844, -70.638450622558594, - 41.717960357666016, -70.634696960449219, 41.722927093505859, -70.627883911132812, 41.726966857910156, - -70.625991821289062, 41.730587005615234, -70.619140625, 41.737354278564453, -70.619735717773438, - 41.739173889160156, -70.620948791503906, 41.74053955078125, -70.624031066894531, 41.740108489990234, - -70.62835693359375, 41.738323211669922, -70.63397216796875, 41.736602783203125, -70.634536743164062, - 41.736095428466797, -70.641937255859375, 41.734325408935547, -70.648689270019531, 41.735733032226562, - -70.654869079589844, 41.733505249023438, -70.654914855957031, 41.729873657226562, -70.651313781738281, - 41.722129821777344, -70.648910522460938, 41.717575073242188, -70.649581909179688, 41.713039398193359, - -70.652091979980469, 41.708515167236328, -70.660797119140625, 41.700855255126953, -70.667015075683594, - 41.694992065429688, -70.672599792480469, 41.69049072265625, -70.677490234375, 41.692790985107422, - -70.674385070800781, 41.69549560546875, -70.669395446777344, 41.701820373535156, -70.663162231445312, - 41.708587646484375, -70.657577514648438, 41.712638854980469, -70.658157348632812, 41.7158203125, - -70.665519714355469, 41.717227935791016, -70.667961120605469, 41.719062805175781, -70.670394897460938, - 41.721347808837891, -70.672821044921875, 41.724536895751953, -70.674644470214844, 41.726818084716797, - -70.677703857421875, 41.727745056152344, -70.683876037597656, 41.725967407226562, -70.691276550292969, - 41.724655151367188, -70.699844360351562, 41.728340148925781, -70.706581115722656, 41.73065185546875, - -70.707786560058594, 41.732929229736328, -70.70587158203125, 41.739273071289062, -70.7039794921875, - 41.74334716796875, -70.706428527832031, 41.744724273681641, -70.708900451660156, 41.743377685546875, - -70.710769653320312, 41.741573333740234, -70.715095520019531, 41.739784240722656, -70.722511291503906, - 41.736648559570312, -70.726211547851562, 41.735767364501953, -70.721969604492188, 41.729835510253906, - -70.71954345703125, 41.727096557617188, -70.721412658691406, 41.724838256835938, -70.725692749023438, - 41.726680755615234, -70.735481262207031, 41.732189178466797, -70.736732482910156, 41.729923248291016, - -70.731880187988281, 41.723995208740234, -70.726997375488281, 41.720333099365234, -70.722145080566406, - 41.714401245117188, -70.717864990234375, 41.712108612060547, -70.714210510253906, 41.708454132080078, - -70.713630676269531, 41.705722808837891, -70.719184875488281, 41.703487396240234, -70.7265625, - 41.703987121582031, -70.724800109863281, 41.696712493896484, -70.717453002929688, 41.693492889404297, - -70.716255187988281, 41.690761566162109, -70.718124389648438, 41.688503265380859, -70.715736389160156, - 41.682132720947266, -70.717018127441406, 41.677600860595703, -70.720695495605469, 41.678531646728516, - -70.725570678710938, 41.682643890380859, -70.731056213378906, 41.686305999755859, -70.736572265625, - 41.688156127929688, -70.741439819335938, 41.693180084228516, -70.740798950195312, 41.694992065429688, - -70.733436584472656, 41.694038391113281, -70.734642028808594, 41.69586181640625, -70.741950988769531, - 41.702262878417969, -70.747467041015625, 41.703655242919922, -70.759063720703125, 41.712348937988281, - -70.762168884277344, 41.709644317626953, -70.756134033203125, 41.698261260986328, -70.753791809082031, - 41.687347412109375, -70.750762939453125, 41.683246612548828, -70.74896240234375, 41.679149627685547, - -70.744720458984375, 41.673679351806641, -70.748428344726562, 41.671886444091797, -70.756973266601562, - 41.677379608154297, -70.762519836425781, 41.676052093505859, -70.758934020996094, 41.666046142578125, - -70.758468627929688, 41.652423858642578, -70.764671325683594, 41.647010803222656, -70.764717102050781, - 41.642017364501953, -70.770263671875, 41.640235900878906, -70.772712707519531, 41.641609191894531, - -70.775741577148438, 41.645709991455078, -70.779991149902344, 41.650730133056641, -70.787353515625, - 41.651679992675781, -70.797805786132812, 41.650825500488281, -70.805747985839844, 41.655406951904297, - -70.818023681640625, 41.657291412353516, -70.822349548339844, 41.654132843017578, -70.828536987304688, - 41.650081634521484, -70.815711975097656, 41.642299652099609, -70.807121276855469, 41.640892028808594, - -70.799209594726562, 41.633583068847656, -70.799247741699219, 41.629497528076172, -70.802352905273438, - 41.626338958740234, -70.809738159179688, 41.624561309814453, -70.815231323242188, 41.628223419189453, - -70.817039489746094, 41.631866455078125, -70.823188781738281, 41.630989074707031, -70.824447631835938, - 41.627819061279297, -70.828155517578125, 41.626022338867188, -70.833084106445312, 41.624233245849609, - -70.837989807128906, 41.624710083007812, -70.844734191894531, 41.626560211181641, -70.847793579101562, - 41.627487182617188, -70.853912353515625, 41.629779815673828, -70.86004638671875, 41.631175994873047, - -70.867446899414062, 41.628032684326172, -70.866264343261719, 41.622577667236328, -70.854019165039062, - 41.617984771728516, -70.852249145507812, 41.610710144042969, -70.850471496582031, 41.603893280029297, - -70.849922180175781, 41.596626281738281, -70.850593566894531, 41.590728759765625, -70.8543701171875, - 41.579853057861328, -70.856208801269531, 41.580318450927734, -70.85986328125, 41.583965301513672, - -70.862861633300781, 41.591243743896484, -70.866470336914062, 41.599433898925781, -70.868255615234375, - 41.605796813964844, -70.87249755859375, 41.612628936767578, -70.873039245605469, 41.620796203613281, - -70.879127502441406, 41.626274108886719, -70.888954162597656, 41.626319885253906, -70.899406433105469, - 41.625007629394531, -70.905471801757812, 41.634571075439453, -70.905418395996094, 41.640468597412109, - -70.909049987792969, 41.647296905517578, -70.911468505859375, 41.651847839355469, -70.912025451660156, - 41.658660888671875, -70.913162231445312, 41.669559478759766, -70.921852111816406, 41.659610748291016, - -70.923774719238281, 41.65008544921875, -70.925071716308594, 41.641468048095703, -70.923294067382812, - 41.633289337158203, -70.916023254394531, 41.620998382568359, -70.903244018554688, 41.607322692871094, - -70.900901794433594, 41.593696594238281, -70.910736083984375, 41.592830657958984, -70.913734436035156, - 41.601016998291016, -70.920402526855469, 41.611942291259766, -70.926528930664062, 41.613780975341797, - -70.930877685546875, 41.606990814208984, -70.92913818359375, 41.594730377197266, -70.933486938476562, - 41.587940216064453, -70.934776306152344, 41.580226898193359, -70.937858581542969, 41.578880310058594, - -70.943962097167969, 41.583446502685547, -70.950035095214844, 41.592094421386719, -70.956733703613281, - 41.598934173583984, -70.961044311523438, 41.596683502197266, -70.962921142578125, 41.592151641845703, - -70.965385437011719, 41.591709136962891, -70.964210510253906, 41.584442138671875, -70.961158752441406, - 41.582157135009766, -70.956855773925781, 41.583045959472656, -70.952568054199219, 41.5816650390625, - -70.950149536132812, 41.577117919921875, -70.93798828125, 41.562992095947266, -70.939247131347656, - 41.558917999267578, -70.93743896484375, 41.554824829101562, -70.933792114257812, 41.550270080566406, - -70.931381225585938, 41.544811248779297, -70.928977966308594, 41.538898468017578, -70.930824279785156, - 41.538002014160156, -70.933883666992188, 41.538921356201172, -70.940628051757812, 41.539859771728516, - -70.945549011230469, 41.538063049316406, -70.948661804199219, 41.531723022460938, -70.949295043945312, - 41.529457092285156, -70.952377319335938, 41.527652740478516, -70.951179504394531, 41.523563385009766, - -70.951805114746094, 41.521751403808594, -70.951820373535156, 41.519935607910156, -70.95062255859375, - 41.516750335693359, -70.954330444335938, 41.512683868408203, -70.956779479980469, 41.513599395751953, - -70.957351684570312, 41.519050598144531, -70.957916259765625, 41.524497985839844, -70.959747314453125, - 41.526321411132812, -70.961570739746094, 41.528598785400391, -70.966461181640625, 41.530891418457031, - -70.968879699707031, 41.534980773925781, -70.968238830566406, 41.538608551025391, -70.971900939941406, - 41.5408935546875, -70.976837158203125, 41.537734985351562, -70.986000061035156, 41.543220520019531, - -70.987899780273438, 41.53460693359375, -70.983619689941406, 41.532772064208984, -70.981803894042969, - 41.529132843017578, -70.979995727539062, 41.525039672851562, -70.981857299804688, 41.522327423095703, - -70.983108520507812, 41.518245697021484, -70.984359741210938, 41.515071868896484, -70.983772277832031, - 41.511436462402344, -70.984405517578125, 41.509170532226562, -70.988090515136719, 41.508277893066406, - -71.002792358398438, 41.510604858398438, -71.015678405761719, 41.509292602539062, -71.020622253417969, - 41.503410339355469, -71.033531188964844, 41.498916625976562, -71.0347900390625, 41.493930816650391, - -71.035415649414062, 41.4912109375, -71.034820556640625, 41.488483428955078, -71.036087036132812, - 41.483043670654297, -71.039779663085938, 41.480785369873047, -71.042221069335938, 41.482154846191406, - -71.044647216796875, 41.486248016357422, -71.045814514160156, 41.495330810546875, -71.053138732910156, - 41.501712799072266, -71.06109619140625, 41.503101348876953, -71.076416015625, 41.505424499511719, - -71.083152770996094, 41.506351470947266, -71.078224182128906, 41.509967803955078, -71.07208251953125, - 41.512218475341797, -71.064720153808594, 41.512645721435547, -71.05859375, 41.511260986328125, - -71.055511474609375, 41.513973236083984, -71.053672790527344, 41.513969421386719, -71.04754638671875, - 41.513042449951172, -71.045082092285156, 41.513938903808594, -71.045059204101562, 41.51666259765625, - -71.047470092773438, 41.524387359619141, -71.050430297851562, 41.541194915771484, -71.051033020019531, - 41.543010711669922, -71.054664611816406, 41.551193237304688, -71.058944702148438, 41.553478240966797, - -71.065673828125, 41.557132720947266, -71.069931030273438, 41.563045501708984, -71.070518493652344, - 41.566680908203125, -71.069877624511719, 41.572124481201172, -71.068008422851562, 41.576206207275391, - -71.065498352050781, 41.584819793701172, -71.064231872558594, 41.591625213623047, -71.0660400390625, - 41.597080230712891, -71.069091796875, 41.599357604980469, -71.071563720703125, 41.596645355224609, - -71.072822570800781, 41.592563629150391, -71.075340270996094, 41.581676483154297, -71.0784912109375, - 41.568523406982422, -71.077293395996094, 41.563072204589844, -71.074867248535156, 41.558071136474609, - -71.068778991699219, 41.550788879394531, -71.066360473632812, 41.545333862304688, -71.066390991210938, - 41.540340423583984, -71.067657470703125, 41.5330810546875, -71.065849304199219, 41.527629852294922, - -71.070182800292969, 41.521739959716797, -71.080604553222656, 41.522232055664062, -71.08734130859375, - 41.524066925048828, -71.091575622558594, 41.534069061279297, -71.096488952636719, 41.533176422119141, - -71.101371765136719, 41.537277221679688, -71.109306335449219, 41.545017242431641, -71.116050720214844, - 41.545490264892578, -71.117912292480469, 41.540958404541016, -71.112442016601562, 41.532318115234375, - -71.102073669433594, 41.522300720214844, -71.098419189453125, 41.517749786376953, -71.098426818847656, - 41.515933990478516, -71.098442077636719, 41.513210296630859, -71.096626281738281, 41.508663177490234, - -71.094207763671875, 41.503211975097656, -71.0966796875, 41.499588012695312, -71.101585388183594, - 41.499149322509766, -71.105255126953125, 41.5009765625, -71.10955810546875, 41.500080108642578, - -71.116317749023438, 41.496471405029297, -71.120613098144531, 41.495574951171875, -71.121200561523438, - 41.500568389892578, -71.122947692871094, 41.518276214599609, -71.132362365722656, 41.594562530517578, - -71.137855529785156, 41.599571228027344, -71.140907287597656, 41.603664398193359, -71.142120361328125, - 41.606845855712891, -71.142715454101562, 41.610931396484375, -71.142074584960938, 41.615016937255859, - -71.141448974609375, 41.618194580078125, -71.140815734863281, 41.621368408203125, -71.139579772949219, - 41.623634338378906, -71.137725830078125, 41.625900268554688, -71.135871887207031, 41.627708435058594, - -71.134017944335938, 41.630428314208984, -71.134002685546875, 41.632698059082031, -71.133987426757812, - 41.634967803955078, -71.135208129882812, 41.637241363525391, -71.13580322265625, 41.640422821044922, - -71.132057189941406, 41.652214050292969, -71.133247375488281, 41.659481048583984, -71.176834106445312, - 41.668220520019531, -71.17620849609375, 41.670944213867188, -71.19586181640625, 41.674625396728516, - -71.198921203613281, 41.678264617919922, -71.19830322265625, 41.679622650146484, -71.190284729003906, - 41.685958862304688, -71.1810302734375, 41.693202972412109, -71.169929504394531, 41.699985504150391, - -71.152023315429688, 41.715373992919922, -71.1396484375, 41.729412078857422, -71.136550903320312, - 41.733943939208984, -71.135284423828125, 41.740749359130859, -71.135261535644531, 41.744834899902344, - -71.13275146484375, 41.754364013671875, -71.121017456054688, 41.762500762939453, -71.106163024902344, - 41.777439117431641, -71.104896545410156, 41.783790588378906, -71.10546875, 41.791965484619141, - -71.105453491210938, 41.794689178466797, -71.108543395996094, 41.791973114013672, -71.111625671386719, - 41.79107666015625, -71.114669799804688, 41.797443389892578, -71.11773681640625, 41.799266815185547, - -71.116455078125, 41.809707641601562, -71.117630004882812, 41.818790435791016, -71.121978759765625, - 41.811992645263672, -71.123252868652344, 41.805187225341797, -71.126968383789062, 41.801113128662109, - -71.129447937011719, 41.797031402587891, -71.128852844238281, 41.794303894042969, -71.125190734863281, - 41.787487030029297, -71.124626159667969, 41.778854370117188, -71.127120971679688, 41.771598815917969, - -71.132072448730469, 41.766166687011719, -71.137641906738281, 41.761184692382812, -71.140754699707031, - 41.75347900390625, -71.142654418945312, 41.743495941162109, -71.144523620605469, 41.738506317138672, - -71.154396057128906, 41.733085632324219, -71.163032531738281, 41.728115081787109, -71.166130065917969, - 41.723129272460938, -71.171707153320312, 41.713607788085938, -71.184646606445312, 41.709098815917969, - -71.193885803222656, 41.704582214355469, -71.19696044921875, 41.70458984375, -71.199394226074219, - 41.710494995117188, -71.200599670410156, 41.715950012207031, -71.202445983886719, 41.715499877929688, - -71.206153869628906, 41.712326049804688, -71.207405090332031, 41.707790374755859, -71.212944030761719, - 41.705989837646484, -71.216011047363281, 41.707355499267578, -71.217842102050781, 41.711448669433594, - -71.222732543945312, 41.71917724609375, -71.227035522460938, 41.718276977539062, -71.227668762207031, - 41.715099334716797, -71.261375427246094, 41.751487731933594, -71.2841796875, 41.761306762695312, - -71.3179931640625, 41.775871276855469, -71.325912475585938, 41.779281616210938, -71.327140808105469, - 41.781097412109375, -71.3289794921875, 41.783824920654297, -71.330207824707031, 41.786552429199219, - -71.331428527832031, 41.789730072021484, -71.334495544433594, 41.792457580566406, -71.337570190429688, - 41.795188903808594, -71.33941650390625, 41.797004699707031, -71.34063720703125, 41.799732208251953, - -71.340629577636719, 41.802909851074219, -71.340621948242188, 41.805633544921875, -71.340614318847656, - 41.80926513671875, -71.342460632324219, 41.812900543212891, -71.344291687011719, 41.81744384765625, - -71.343673706054688, 41.821075439453125, -71.343666076660156, 41.824253082275391, -71.340576171875, - 41.827880859375, -71.338722229003906, 41.830150604248047, -71.336868286132812, 41.832870483398438, - -71.336860656738281, 41.835140228271484, -71.338088989257812, 41.837413787841797, -71.338699340820312, - 41.839229583740234, -71.339309692382812, 41.841045379638672, -71.338691711425781, 41.842864990234375, - -71.335594177246094, 41.84967041015625, -71.333740234375, 41.853755950927734, -71.333114624023438, - 41.857387542724609, -71.333717346191406, 41.861019134521484, -71.335556030273438, 41.867832183837891, - -71.336776733398438, 41.873283386230469, -71.339218139648438, 41.882366180419922, -71.339820861816406, - 41.887363433837891, -71.338584899902344, 41.890995025634766, -71.33734130859375, 41.893718719482422, - -71.338569641113281, 41.898258209228516, -71.382362365722656, 41.891494750976562, -71.381660461425781, - 41.942752838134766, -71.380561828613281, 41.985042572021484, -71.379676818847656, 42.019100189208984, - -71.426620483398438, 42.018680572509766, -71.498268127441406, 42.016880035400391, -71.53656005859375, - 42.015914916992188, -71.558792114257812, 42.015293121337891, -71.668113708496094, 42.012233734130859, - -71.797943115234375, 42.008888244628906, -71.799095153808594, 42.0238037109375, -71.885589599609375, - 42.025386810302734, -71.943565368652344, 42.026397705078125, -71.969612121582031, 42.027378082275391, - -71.976272583007812, 42.027717590332031, -72.002983093261719, 42.029071807861328, -72.081436157226562, - 42.028739929199219, -72.102310180664062, 42.029506683349609, -72.135818481445312, 42.030735015869141, - -72.136436462402344, 42.030754089355469, -72.232192993164062, 42.031154632568359, -72.293373107910156, - 42.031700134277344, -72.308197021484375, 42.031608581542969, -72.348983764648438, 42.032501220703125, - -72.4476318359375, 42.034282684326172, -72.452178955078125, 42.034355163574219, -72.458755493164062, - 42.0343017578125, -72.47442626953125, 42.034404754638672, -72.509414672851562, 42.034889221191406, - -72.526336669921875, 42.035053253173828, -72.573219299316406, 42.030132293701172, -72.58477783203125, - 42.024837493896484, -72.604034423828125, 42.025241851806641, -72.607124328613281, 42.025306701660156, - -72.6094970703125, 42.030723571777344, -72.639938354492188, 42.031620025634766, -72.680183410644531, - 42.035106658935547, -72.707733154296875, 42.037094116210938, -72.757431030273438, 42.036148071289062, - -72.756538391113281, 42.031421661376953, -72.757240295410156, 42.028720855712891, -72.759605407714844, - 42.025966644287109, -72.763389587402344, 42.023418426513672, -72.768600463867188, 42.004287719726562, - -72.818145751953125, 41.997913360595703, -72.816795349121094, 42.016387939453125, -72.815544128417969, - 42.037651062011719, -72.898963928222656, 42.037918090820312, -72.93975830078125, 42.037929534912109, - -72.96881103515625, 42.038505554199219, -73.008659362792969, 42.039516448974609, -73.04052734375, - 42.040325164794922, -73.048202514648438, 42.040462493896484, -73.051658630371094, 42.040489196777344, - -73.052894592285156, 42.040485382080078, -73.05438232421875, 42.040534973144531, -73.134117126464844, - 42.043285369873047, -73.281089782714844, 42.04730224609375, -73.287399291992188, 42.047473907470703, - -73.313255310058594, 42.048206329345703, -73.333137512207031, 42.048538208007812, -73.33428955078125, - 42.048557281494141, -73.365837097167969, 42.049732208251953, -73.490058898925781, 42.049697875976562, - -73.498092651367188, 42.049571990966797, -73.502120971679688, 42.063705444335938, -73.508407592773438, - 42.08575439453125, -73.482246398925781, 42.164787292480469, -73.439590454101562, 42.279891967773438, - -73.416412353515625, 42.341842651367188, -73.395660400390625, 42.397323608398438, -73.379165649414062, - 42.441974639892578, -73.354629516601562, 42.509468078613281, -73.351921081542969, 42.516696929931641, - -73.322761535644531, 42.596240997314453, -73.30902099609375, 42.633716583251953, -73.291336059570312, - 42.681137084960938, -73.267463684082031, 42.745159149169922 }; -} diff --git a/src/mac/OpenMap.app/Contents/Info.plist b/src/mac/OpenMap.app/Contents/Info.plist deleted file mode 100644 index 63474e251..000000000 --- a/src/mac/OpenMap.app/Contents/Info.plist +++ /dev/null @@ -1,54 +0,0 @@ - - - - - CFBundleName - OpenMap - CFBundleVersion - @version@ - CFBundleAllowMixedLocalizations - false - CFBundleExecutable - JavaApplicationStub - CFBundleDevelopmentRegion - English - CFBundlePackageType - APPL - CFBundleSignature - ???? - CFBundleGetInfoString - OpenMap @version@, Copyright (C) BBN Technologies LLC - CFBundleInfoDictionaryVersion - 6.0 - CFBundleIconFile - OpenMap.icns - Java - - WorkingDirectory - $APP_PACKAGE/Contents/Resources/Java - VMOptions - -Xmx768m - MainClass - com.bbn.openmap.app.Main - JVMVersion - 1.5+ - ClassPath - - $APP_PACKAGE/Contents/Resources - $JAVAROOT/openmap.jar - $JAVAROOT/omcorba.jar - $JAVAROOT/omsvg.jar - $JAVAROOT/omj3d.jar - $JAVAROOT/milStd2525_png.jar - $APP_PACKAGE/Contents/Resources/share - - Properties - - apple.laf.useScreenMenuBar - true - com.apple.macos.useScreenMenuBar - true - - - - diff --git a/src/mac/OpenMap.app/Contents/MacOS/JavaApplicationStub b/src/mac/OpenMap.app/Contents/MacOS/JavaApplicationStub deleted file mode 100755 index c55eb5ff3..000000000 Binary files a/src/mac/OpenMap.app/Contents/MacOS/JavaApplicationStub and /dev/null differ diff --git a/src/mac/OpenMap.app/Contents/PkgInfo b/src/mac/OpenMap.app/Contents/PkgInfo deleted file mode 100644 index bd04210fb..000000000 --- a/src/mac/OpenMap.app/Contents/PkgInfo +++ /dev/null @@ -1 +0,0 @@ -APPL???? \ No newline at end of file diff --git a/src/mac/OpenMap.app/Contents/Resources/OpenMap.icns b/src/mac/OpenMap.app/Contents/Resources/OpenMap.icns deleted file mode 100644 index 1235efaa8..000000000 Binary files a/src/mac/OpenMap.app/Contents/Resources/OpenMap.icns and /dev/null differ diff --git a/src/mac/README b/src/mac/README deleted file mode 100644 index 7efe36751..000000000 --- a/src/mac/README +++ /dev/null @@ -1,31 +0,0 @@ -This package contains: - -The OpenMap application, configured with basic layers and default components. - -An openmap.properties file to place in your home directory -(/Users/). You can modify this file to change the layers -in the application and reconfigure the application components. There -are instructions for modifying the openmap.properties inside that -file. - -The openmap-4.6 development directory, containing the source code and -documentation for the OpenMap package. To compile OpenMap source -code, set the OPENMAP_HOME environment variable to the location of -the openmap-4.6 directory: - -For the bash shell: -> export OPENMAP_HOME - -for tcsh: -> setenv OPENMAP_HOME - -Then, type: - -> make mac - -For other compilation options, type: - -> make help - -Please see http://openmap.bbn.com for more information, and contact us at -openmap@bbn.com with any questions and/or comments. diff --git a/src/maptileservlet/.gitignore b/src/maptileservlet/.gitignore deleted file mode 100644 index dc5353ef0..000000000 --- a/src/maptileservlet/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/.classpath -/.settings/ diff --git a/src/maptileservlet/.project b/src/maptileservlet/.project deleted file mode 100644 index c4a4f7cca..000000000 --- a/src/maptileservlet/.project +++ /dev/null @@ -1,42 +0,0 @@ - - - openmap-maptileservlet - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/src/maptileservlet/README b/src/maptileservlet/README deleted file mode 100644 index ccfae7432..000000000 --- a/src/maptileservlet/README +++ /dev/null @@ -1,128 +0,0 @@ -A basic set of JSP/Servlet code to serve up map tiles, such as the type -the MapTileLayer uses (or Leaflet). - -The packages uses J2EE capabilities, and has only been tested under -the Apache Software Foundation's Jakarta Tomcat J2EE engine and Glassfish. - -The OpenMap Maptile Servlet can serve up different tile sets. - -To build the code, the build.xml file needs to be modified so the -servlet-api.jar is found. This file is in the tomcat and glassfish -installations. - -Next, you need to modify the WEB-INF/web.xml file so it points to your -map tile data. Each tile set is defined by a properties file, four -have been provided in this package as an example. The servlet will -look for the TileSetDefinitions property which should point to a -directory containing all of the map set properties files. If you -add/remove/change a properties file in this directory, simply restart -the servlet to pick up the changes. - - - TileSetDefinitions - ./tileSetProperties - - Tile sets available for request. - - - -The default properties file directory will be copied into the classes directory when -the war file gets created, so the servlet can find them and configure -itself to serve up tiles. The relative path in that param-value path starts -at the classes directory. You can change the param-value path to be an absolute -file path if you want to put the properties files out on your system. Don't -modify the versions in the classes directory, they will be overwritten if you -run ant on the build.xml file. - -Each property file should contain the same basic properties for a MapTileLayer: - -The 'name' property is important - it's the name your request will -have in it to specify a particular tile set. - -name=my_tile_set -rootDir=/Volumes/data/my_tile_set - -You can specify a MapTileSet class to use for a map tile sets. The StandardMapTileSet -is the default, but the TileMillMapTile can be used to read mbtiles files, and the -RelayMapTileSet can be used to fetch tiles from a remote server while maintaining -a local cache copy of the tiles for subsequent distribution. You can specify the -MapTileSet class using the 'class' property. - -class=com.bbn.openmap.maptileservlet.MBRasterMapTileSet - -or - -class=com.bbn.openmap.maptileservlet.RelayMapTileSet - -The other properties that can be used are standard for the MapTileLayer, -too. The rootDir property tells the MapTileSet where to look for more information, -and it will look for a tiles.omp file for more properties that pertain to that -particular map tile set. You can specify properties in the properties file specified -in the TileSetDefinitions (tileset1.properties, for example), or you can just have -other properties in the tiles.omp file stored in the rootDir directory. For example, these -properties can be set to handle what the MapTileSet does when a tile is not found: - -emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.ShpFileEmptyTileHandler -shpFile=/data/shape/cntry02/cntry02.shp -background.fillColor=EAFFF4 -background.lineColor=EAFFF4 -mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform -land.lineColor=DECD8B -land.fillColor=DECD8B - -The properties from the emptyTileHandler on down are just properties -for the EmptyTileHandler defined for the dataset. That's just a -component that can create tiles on the fly for any missing tiles. The -one defined here will use a shape file to create missing tiles. If -you don't supply these parameters, that's OK - nothing will be served -for empty tiles. - -The tiles can be requested by accessing: - -http://localhost:tomcat_port/ommaptile/my_tile_set/z/x/y.png - -where z is zoom level (0-20), x and y are tile coordinates (which depend on zoom level). - -You can use the MapTileLayer to connect to this server, if you -configure it with these properties: - -tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer -tiles.prettyName=Map Tiles -tiles.rootDir=http://localhost:8080:/maptile/my_tile_set - -Another good way to play with this is by using Leaflet, at -http://leaflet.cloudmade.com/. It's a javascript mapping toolkit. -You can use use a html page like this to connect to this server, with -the leaflet package stored next to it on the web server. - - - - - - - - - - - - - -
- - - - - - diff --git a/src/maptileservlet/build.xml b/src/maptileservlet/build.xml deleted file mode 100644 index 53c9a54a5..000000000 --- a/src/maptileservlet/build.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/maptileservlet/pom.xml b/src/maptileservlet/pom.xml deleted file mode 100644 index eaeba7341..000000000 --- a/src/maptileservlet/pom.xml +++ /dev/null @@ -1,106 +0,0 @@ - - 4.0.0 - openmap-maptileservlet - org.openmap-java - 6.0 - war - openmap-maptileservlet - OpenMap is a Java Beans based toolkit for building applications and applets needing geographic information. This project encapsulates map tile servlet components that can be used with Tomcat/Glassfish to create a tile server. - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - - package - - jar - - - ommaptile - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.2.1 - - - attach-sources - install - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - install - - jar - - - - - - org.apache.maven.plugins - maven-install-plugin - 2.5.2 - - - package - - ommaptile - org.openmap-java - 6.0 - jar - ${project.build.directory}/${project.build.finalName}-ommaptile.jar - - - install-file - - - - - - - - - UTF-8 - 7 - 1.7 - - - - javax.servlet - servlet-api - 2.5 - - - org.xerial - sqlite-jdbc - 3.8.11.2 - - - org.openmap-java - openmap - 6.0 - jar - - - - diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MBRasterMapTileSet.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MBRasterMapTileSet.java deleted file mode 100644 index 44ac412a7..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MBRasterMapTileSet.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - */ -package com.bbn.openmap.maptileservlet; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.dataAccess.mapTile.mb.RasterMapTileFactory; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.image.PNGImageIOFormatter; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.PropUtils; - -/** - * MapTileSet that reads MapBox raster mbtiles files. - * - *
- * name=the-name-of-dataset
- * class=com.bbn.openmap.maptileservlet.MBRasterMapTileSet
- * rootDir=the path to the mbtiles file.
- *  * 
- * - * As an example, a url for accessing a tile from this server would be: - * - *
- * http://your.machine/ommaptile/the-name-of-dataset/z/x/y.png
- * 
- * - * where ommaptile is the name of the servlet. You can change that in the - * web.xml and in glassfish/tomcat. - * - * @author dietrick - */ -public class MBRasterMapTileSet extends StandardMapTileSet { - - public MBRasterMapTileSet() { - } - - public MBRasterMapTileSet(Properties props) { - setProperties(props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + CLASS_ATTRIBUTE, this.getClass().getName()); - - return props; - } - - public byte[] getImageData(String pathInfo) throws IOException, FormatException { - - byte[] imageData = null; - - try { - Class.forName(RasterMapTileFactory.DEFAULT_TEST_CLASS); - } catch (Exception e) { - getLogger().warning("can't locate sqlite JDBC components"); - return null; - } - - try { - - TileInfo ti = new TileInfo(pathInfo); - - Connection conn = DriverManager.getConnection(rootDir); - Statement stat = conn.createStatement(); - - // "select zoom_level, tile_column, tile_row, tile_data from map, images where map.tile_id = images.tile_id"; - StringBuilder statement = new StringBuilder("select tile_data from map, images where"); - statement.append(" zoom_level = ").append(ti.zoomLevel); - statement.append(" and tile_column = ").append(ti.x); - statement.append(" and tile_row = ").append((int) (Math.pow(2, ti.zoomLevel)) - ti.y - - 1); - statement.append(" and map.tile_id = images.tile_id;"); - - ResultSet rs = stat.executeQuery(statement.toString()); - while (rs.next()) { - byte[] imageBytes = rs.getBytes("tile_data"); - ImageIcon ii = new ImageIcon(imageBytes); - BufferedImage bi = BufferedImageHelper.getBufferedImage(ii.getImage(), 0, 0, -1, -1); - - // TODO: Still have to incorporate properties or something to - // all - // specification of map image format. - imageData = new PNGImageIOFormatter().formatImage(bi); - } - rs.close(); - conn.close(); - } catch (Exception e) { - getLogger().warning("something went wrong fetching image from database: " - + e.getMessage()); - e.printStackTrace(); - } - - return imageData; - } - - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(MapTileSet.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - -} diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileServlet.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileServlet.java deleted file mode 100644 index 52bb0a8d1..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileServlet.java +++ /dev/null @@ -1,387 +0,0 @@ -package com.bbn.openmap.maptileservlet; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.http.HttpConnection; -import com.bbn.openmap.util.wanderer.Wanderer; -import com.bbn.openmap.util.wanderer.WandererCallback; - -/** - * MapTileServlet is a servlet class that fields requests for map tiles. It can - * handle multiple MapTileSets, each one defined by a properties file. The - * web.xml file for this servlet lets you specify the directory where these - * properties files are, under the TileSetDefinitions attribute. The properties - * files in that directory are automatically read and used to create - * MapTileSets. The default deployed name and location of this directory is the - * WEB-INF/classes/tileSetDefinitions directory, but any location can be - * specified. - * - * Each maptileset properties file should specify a name of the tile set, which - * is used in the path to reach those tiles. The MapTileSet object is used by - * the MapTileServlet to handle the specific configuration of the tile set, and - * the MapTileSet object classname to use can be specified in the maptileset - * properties under the 'class' property. The StandardMapTileSet is used by - * default, it assumes the tile set is stored in a z/x/y file structure. The - * TileMillMapTileSet knows how to use mbtiles files created using TileMill. The - * RelayMapTileSet uses a local z/x/y directory structure as a cache for tiles - * to disperse, but goes to another server location to fetch new tiles it - * doesn't have. Each MapTileSet has configuration information in its javadoc. - * See the web.xml file for more information about configuring this - * MapTileServlet. - * - * @author dietrick - */ -public class MapTileServlet extends HttpServlet { - public final static String TILE_SET_DESCRIPTION_ATTRIBUTE = "TileSetDefinitions"; - public final static String LEAFLET_CSS_LOCATION_ATTRIBUTE = "leaflet_css"; - public final static String LEAFLET_JS_LOCATION_ATTRIBUTE = "leaflet_js"; - protected Map mapTileSets; - - String leafletCssLocation = "http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"; - String leafletJsLocation = "http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"; - - /** - * A do-nothing constructor - init does all the work. - */ - public MapTileServlet() { - super(); - - mapTileSets = Collections.synchronizedMap(new HashMap()); - } - - /** - * Called when the servlet is loaded. - */ - public void init(ServletConfig config) throws ServletException { - super.init(config); - ServletContext context = config.getServletContext(); - - Logger logger = getLogger(); - String leafletCss = context.getInitParameter(LEAFLET_CSS_LOCATION_ATTRIBUTE); - if (leafletCss != null) { - leafletCssLocation = leafletCss; - } - logger.info("leaflet.css located at :" + leafletCssLocation); - - String leafletJs = context.getInitParameter(LEAFLET_JS_LOCATION_ATTRIBUTE); - if (leafletJs != null) { - leafletJsLocation = leafletJs; - } - logger.info("leaflet.js located at :" + leafletJsLocation); - - String descriptions = context.getInitParameter(TILE_SET_DESCRIPTION_ATTRIBUTE); - logger.info("Looking for Tile Set Descriptions at: " + descriptions); - if (descriptions != null) { - - // Changing descriptions to a folder containing properties files - // defining tile sets. - try { - - URL descriptionFolder = PropUtils.getResourceOrFileOrURL(descriptions); - new PropertiesWanderer(new File(descriptionFolder.getFile())); - - } catch (MalformedURLException e) { - logger.warning("unable to open for Tile Set properties file given " + descriptions); - } catch (NullPointerException npe) { - logger.warning("Can't find directory holding Tile Set properties files: " - + descriptions); - } - } - - } - - /** - * Given a URL to a properties file describing a MapTileSet, create it and - * add it to the list. - * - * @param tileSetProperties - * @throws IOException - * @throws MalformedURLException - */ - protected void parseAndAddMapTileSet(URL tileSetProperties) - throws IOException, MalformedURLException { - Properties descProps = new Properties(); - Logger logger = getLogger(); - - logger.info("going to read props"); - InputStream descURLStream = tileSetProperties.openStream(); - descProps.load(descURLStream); - - logger.info("loaded " + tileSetProperties.toString() + " " + descProps.toString()); - - MapTileSet mts = createMapTileSetFromProperties(descProps); - - if (mts != null && mts.allGood()) { - String mtsName = mts.getName(); - mapTileSets.put(mts.getName(), mts); - logger.info("Adding " + mtsName + " dataset"); - } - - descURLStream.close(); - } - - protected MapTileSet createMapTileSetFromProperties(Properties props) { - String className = props.getProperty(MapTileSet.CLASS_ATTRIBUTE); - Logger logger = getLogger(); - if (className == null) { - MapTileSet mts = new StandardMapTileSet(); - mts.setProperties(props); - return mts; - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating special map tile set: " + className); - } - try { - Object obj = ComponentFactory.create(className, null, props); - - if (obj instanceof MapTileSet) { - return (MapTileSet) obj; - } else { - logger.fine("Had trouble creating " - + (obj == null ? className : obj.getClass().getName()) - + ", not a MapTileSet"); - } - - } catch (Exception e) { - getLogger().severe("Problem creating " + className + ", " + e.getMessage()); - } - } - - return null; - } - - /** - * Handles - */ - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - OutputStream out = resp.getOutputStream(); - - String pathInfo = req.getPathInfo(); - Logger logger = getLogger(); - if (logger.isLoggable(Level.FINE)) { - logger.fine("received: " + pathInfo); - } - - // Empty path request, let's return summary catalog, might be of some - // help. - if (pathInfo.length() <= 1) { - String tilePathHeader = req.getServerName() + ":" + req.getServerPort() - + req.getContextPath(); - StringBuilder builder = new StringBuilder("Map Tile Sets:

"); - for (MapTileSet mts : mapTileSets.values()) { - String description = mts.getDescription(); - builder.append("Tile set name: "); - builder.append(mts.getName()).append(", description: "); - builder.append(description == null ? "n/a" : description).append("
"); - } - builder.append(""); - - resp.setContentType(HttpConnection.CONTENT_HTML); - OutputStreamWriter osw = new OutputStreamWriter(out); - out.write(builder.toString().getBytes()); - osw.flush(); - return; - } - - MapTileSet mts = getMapTileSetForRequest(pathInfo); - - if (mts != null) { - - if (pathInfo.endsWith("map")) { - String tilePathHeader = req.getServerName() + ":" + req.getServerPort() - + req.getContextPath(); - String map = getMap(tilePathHeader, mts); - resp.setContentType(HttpConnection.CONTENT_HTML); - OutputStreamWriter osw = new OutputStreamWriter(out); - out.write(map.getBytes()); - osw.flush(); - return; - } - - try { - resp.setContentType(HttpConnection.CONTENT_PNG); - byte[] imageData = mts.getImageData(pathInfo); - OutputStreamWriter osw = new OutputStreamWriter(out); - out.write(imageData, 0, imageData.length); - osw.flush(); - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - getLogger().fine("Tile not found: " + pathInfo); - } - HttpConnection.writeHttpResponse(out, HttpConnection.CONTENT_PLAIN, "Problem loading " - + pathInfo + " from map tile set:" + mts.getName()); - } - } else { - HttpConnection.writeHttpResponse(out, HttpConnection.CONTENT_PLAIN, "Map Tile Set not found for request: " - + pathInfo); - } - } - - protected MapTileSet getMapTileSetForRequest(String pathInfo) { - if (pathInfo.startsWith("/")) { - pathInfo = pathInfo.substring(1); - } - - String key = pathInfo; - - // That first part of the path is the MapTileSet name. - int slash = pathInfo.indexOf('/'); - if (slash > 0) { - key = pathInfo.substring(0, slash); - } - - return mapTileSets.get(key); - } - - /** - * Given a starting directory, look for properties files that describe - * MapTileSets. - * - * @author dietrick - */ - private class PropertiesWanderer extends Wanderer implements WandererCallback { - - public PropertiesWanderer(File startingDirectory) { - setCallback(this); - handleEntry(startingDirectory); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.util.wanderer.WandererCallback#handleDirectory(java - * .io.File) - */ - public boolean handleDirectory(File directory) { - // Do nothing to directories - return true; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.util.wanderer.WandererCallback#handleFile(java.io - * .File) - */ - public boolean handleFile(File file) { - getLogger().fine("Checking " + file); - try { - String name = file.getName(); - if (name.endsWith("properties")) { - parseAndAddMapTileSet(file.toURI().toURL()); - } - } catch (MalformedURLException murle) { - getLogger().warning("Unable to read/load " + file + ", murle"); - } catch (IOException e) { - getLogger().warning("Unable to read/load " + file + ", ioe"); - } - return true; - } - - } - - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(MapTileServlet.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - /** - * Creates a HTML string that will display a Leaflet map with the map tiles - * for the MapTileSet. - * - * @param tileReqHeader the server:port/context string of this servlet. - * @param mts the MapTileSet to display. - * @return html text. - */ - protected String getMap(String tileReqHeader, MapTileSet mts) { - String name = mts.getName(); - - List nameList = new ArrayList(); - nameList.add(name); - for (MapTileSet set : mapTileSets.values()) { - if (!name.equals(set.getName())) { - nameList.add(set.getName()); - } - } - - StringBuilder ret = new StringBuilder(); - - ret.append(""); - ret.append(""); - ret.append("

"); - ret.append(""); - - return ret.toString(); - } -} diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileSet.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileSet.java deleted file mode 100644 index 4e0a9affa..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/MapTileSet.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.bbn.openmap.maptileservlet; - -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.io.FormatException; -import java.io.IOException; - -/** - * The MapTileSet contains all the information for handling a specific set of tiles. It contains a description, key to - * use in the request, the location of the data directory, and how to handle empty tiles. - * - * @author dietrick - */ -public interface MapTileSet - extends PropertyConsumer { - - /** - * Property used for MapTileSet class. - */ - public final static String CLASS_ATTRIBUTE = "class"; - - /** - * Check for MapTileServlet to see if the MapTileSet is configured properly. - * - * @return true if configured. - */ - boolean allGood(); - - /** - * byte array image data for path. - * - * @param pathInfo path for file, in z/x/y format. - * @return byte[] for image data, null if not found. - * @throws IOException - * @throws FormatException - */ - byte[] getImageData(String pathInfo) - throws IOException, FormatException; - - /** - * Return name to use in URL to tell MapTileServlet to get frames from this MapTileSet. - * - * @return name of this map tile set. - */ - public String getName(); - - /** - * Set the name of this map tile set. - * - * @param name - */ - public void setName(String name); - - /** - * Get a description of this tile set. - * - * @return string description. - */ - public String getDescription(); - - /** - * Set the description of this tile set. - * - * @param description - */ - public void setDescription(String description); -} diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/RelayMapTileSet.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/RelayMapTileSet.java deleted file mode 100644 index de116bb33..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/RelayMapTileSet.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.bbn.openmap.maptileservlet; - -import com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.PropUtils; -import java.io.IOException; -import java.util.Properties; - -/** - * The RelayMapTileSet contains all the information for handling a specific set of tiles. It contains a description, key - * to use in the request, the location of the data directory or jar. This MapTileSet is able to contact a remote server - * for tiles if the tile file isn't found locally. - *

- * These properties should be in the properties file referenced in the web.xml file for this tile set: - * - *

- * name=the-name-of-dataset
- * class=com.bbn.openmap.maptileservlet.RelayMapTileSet
- * rootDir=the formatted URL for remote tiles, i.e. http://server.com/{z}/{x}/{y}.png
- * localCacheRootDir=the local path of the cached tiles, i.e. /data/tiles/{z}/{x}/{y}.png
- * 
- * - * As an example, a url for accessing a tile from this server would be: - *
- * http://your.machine/ommaptile/the-name-of-dataset/z/x/y.png
- * 
where ommaptile is the name of the servlet. You can change that in the web.xml and in glassfish/tomcat. - * - * @author dietrick - */ -public class RelayMapTileSet - extends ServerMapTileFactory - implements MapTileSet { - - protected String name; - protected String description = null; - - // To allow the component factory to create it. - public RelayMapTileSet() { - } - - public boolean allGood() { - return name != null && rootDir != null; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - name = props.getProperty(prefix + StandardMapTileSet.NAME_ATTRIBUTE, name); - description = props.getProperty(prefix + StandardMapTileSet.DESCRIPTION_ATTRIBUTE, description); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + StandardMapTileSet.NAME_ATTRIBUTE, PropUtils.unnull(name)); - props.put(prefix + StandardMapTileSet.DESCRIPTION_ATTRIBUTE, PropUtils.unnull(name)); - return props; - } - - public byte[] getImageData(String pathInfo) - throws IOException, FormatException { - byte[] imageData = null; - - // We're assuming that all queries are coming in with the name in front, - // along with a slash - if (name != null) { - int index = pathInfo.indexOf(name, 1); - pathInfo = pathInfo.substring(index + name.length()); - } - - // We need to build and check for local file. If not found, then call - // getImageBytes to fetch from other server and cache locally - String localFilePath = null; - TileInfo tInfo = new TileInfo(pathInfo); - - if (!tInfo.valid) { - return imageData; - } - - if (localCacheDir != null) { - localFilePath = buildLocalFilePath(tInfo.x, tInfo.y, tInfo.zoomLevel, getFileExt()); - - try { - - BinaryBufferedFile file = new BinaryBufferedFile(localFilePath); - imageData = file.readBytes(100000, true); - file.close(); - return imageData; - - } catch (IOException ioe) { - // Didn't find local version of file, that's OK. Continue on... - } - } - - // The file wasn't found. - String remoteFilePath = buildFilePath(tInfo.x, tInfo.y, tInfo.zoomLevel, getFileExt()); - imageData = getImageBytes(remoteFilePath, localFilePath); - - return imageData; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/StandardMapTileSet.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/StandardMapTileSet.java deleted file mode 100644 index 17f1ceea9..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/StandardMapTileSet.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.bbn.openmap.maptileservlet; - -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory; -import com.bbn.openmap.image.PNGImageIOFormatter; -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.PropUtils; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.logging.Level; - -/** - * The StandardMapTileSet contains all the information for handling a specific set of tiles. It contains a description, - * key to use in the request, the location of the data directory or jar, and how to handle empty tiles. The - * StandardMapTileSet properties file would look like this: - * - *
- * name=the-name-of-dataset
- * # default, don't really need to specify the class property
- * #class=com.bbn.openmap.maptileservlet.StandardMapTileSet
- * rootDir=the path to the root of the tile directory, the parent of the z-level directory.
- * 
- * - * As an example, a url for accessing a tile from this server would be: - * - *
- * http://your.machine/ommaptile/the-name-of-dataset/z/x/y.png
- * 
- * - * where ommaptile is the name of the servlet. You can change that in the web.xml and in glassfish/tomcat. - * - * @author dietrick - */ -public class StandardMapTileSet - extends StandardMapTileFactory - implements MapTileSet { - - public final static String NAME_ATTRIBUTE = "name"; - public final static String DESCRIPTION_ATTRIBUTE = "description"; - - protected String name; - protected String description = null; - - // To allow the component factory to create it. - public StandardMapTileSet() { - } - - public boolean allGood() { - return name != null && rootDir != null; - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - name = props.getProperty(prefix + NAME_ATTRIBUTE, name); - description = props.getProperty(prefix + DESCRIPTION_ATTRIBUTE, description); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + NAME_ATTRIBUTE, PropUtils.unnull(name)); - props.put(prefix + DESCRIPTION_ATTRIBUTE, PropUtils.unnull(description)); - return props; - } - - public byte[] getImageData(String pathInfo) - throws IOException, FormatException { - byte[] imageData = null; - - // We're assuming that all queries are coming in with the name in front, - // along with a slash - if (name != null) { - int index = pathInfo.indexOf(name, 1); - pathInfo = pathInfo.substring(index + name.length()); - } - - String filePath = rootDir + pathInfo; - if (logger.isLoggable(Level.FINE)) { - logger.fine("looking for " + filePath); - } - - try { - - BinaryBufferedFile file = new BinaryBufferedFile(filePath); - imageData = file.readBytes(100000, true); - file.close(); - - } catch (IOException ioe) { - logger.fine("Problem fetching the file"); - // The file wasn't found. - if (emptyTileHandler != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating " + filePath + " since it wasn't found from the server."); - } - - TileInfo ti = new TileInfo(filePath);// FPBT: used to be - // pathInfo - ti.setMtcTransform(getMtcTransform()); - BufferedImage bufferedImage = ti.getBufferedImage(emptyTileHandler); - - if (bufferedImage != null) { - imageData = new PNGImageIOFormatter().formatImage(bufferedImage); - logger.fine("buffered image created, writing file to disk too"); - File newFile = new File(filePath); - newFile.getParentFile().mkdirs(); - // Write the image data to the local cache location - FileOutputStream fos = new FileOutputStream(newFile); - fos.write(imageData); - fos.flush(); - fos.close(); - } else { - logger.fine("null buffered image back from EmptyTileHandler"); - } - } else { - logger.fine("no empty file handler"); - } - } - - return imageData; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/TileInfo.java b/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/TileInfo.java deleted file mode 100644 index 944814e48..000000000 --- a/src/maptileservlet/src/main/java/com/bbn/openmap/maptileservlet/TileInfo.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Copyright 2012 BBN Technologies - * - */ -package com.bbn.openmap.maptileservlet; - -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.mapTile.EmptyTileHandler; -import com.bbn.openmap.dataAccess.mapTile.MapTileCoordinateTransform; -import com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform; -import com.bbn.openmap.dataAccess.mapTile.SimpleEmptyTileHandler; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.coords.LatLonPoint; - -/** - * TileInfo can look at a path string and figure out zoom level, x, y for tiles. - * - * @author dietrick - */ -public class TileInfo { - int x; - int y; - int zoomLevel; - String format; - String pathInfo; - MapTileCoordinateTransform mtcTransform; - - boolean valid = false; - - Logger logger = Logger.getLogger("com.bbn.openmap.maptileservlet"); - - public TileInfo(String pathInfo) { - this.pathInfo = pathInfo; - - if (pathInfo == null) { - return; - } - - int dotIndex = pathInfo.lastIndexOf('.'); - if (dotIndex > 0) { - format = pathInfo.substring(dotIndex + 1); - - int ySlashIndex = pathInfo.lastIndexOf('/'); - if (ySlashIndex > 0) { - String yString = pathInfo.substring(ySlashIndex + 1, dotIndex); - - int xSlashIndex = pathInfo.lastIndexOf('/', ySlashIndex - 1); - if (xSlashIndex > 0) { - String xString = pathInfo.substring(xSlashIndex + 1, ySlashIndex); - - int zSlashIndex = pathInfo.lastIndexOf('/', xSlashIndex - 1); - if (zSlashIndex >= 0) { - String zString = pathInfo.substring(zSlashIndex + 1, xSlashIndex); - - // OK, we're here! - x = Integer.parseInt(xString); - y = Integer.parseInt(yString); - zoomLevel = Integer.parseInt(zString); - valid = true; - return; - } - } - } - } - - logger.info("can't decode " + pathInfo); - } - - public BufferedImage getBufferedImage(EmptyTileHandler eth) { - if (eth != null) { - - LatLonPoint center = mtcTransform.tileUVToLatLon(new Point2D.Double(x + .5, y + .5), zoomLevel, new LatLonPoint.Double()); - Mercator merc = new Mercator(center, mtcTransform.getScaleForZoom(zoomLevel), SimpleEmptyTileHandler.TILE_SIZE, SimpleEmptyTileHandler.TILE_SIZE); - logger.fine("going to create empty tile: " + pathInfo + " from " - + eth.getClass().getName()); - - return eth.getImageForEmptyTile(pathInfo, x, y, zoomLevel, getMtcTransform(), merc); - } - return null; - } - - public MapTileCoordinateTransform getMtcTransform() { - if (mtcTransform == null) { - mtcTransform = new OSMMapTileCoordinateTransform(); - } - return mtcTransform; - } - - public void setMtcTransform(MapTileCoordinateTransform mtcTransform) { - this.mtcTransform = mtcTransform; - } -} \ No newline at end of file diff --git a/src/maptileservlet/src/main/resources/tileSetProperties/tileset1.properties b/src/maptileservlet/src/main/resources/tileSetProperties/tileset1.properties deleted file mode 100644 index d1ff660f1..000000000 --- a/src/maptileservlet/src/main/resources/tileSetProperties/tileset1.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Note that this tileset is contained in the ommaptile tile set -# properties directory referenced in the web.xml file under the -# TileSetDefinitions property. That's what gets this file read. The -# ant jar target will package this properties file properly for -# deployment in the war. You can add more properties files to the -# directoryfor different tile sets. - -# The name is the scoping name in the path after the servlet argument: -# http://localhost:8080/ommaptile/tileset1/z/x/y.png gets you tiles. -name=OSM -description=Standard map tile set example -# The rootDir is where the tile set is on your local system. -#rootDir= -rootDir=/Volumes/data/st_osm_tiles -#rootDir=/f:/data/tiles - -# This example uses the default MapTileSet class, which just looks on disk for files. No class property needed. - diff --git a/src/maptileservlet/src/main/resources/tileSetProperties/tileset2.properties b/src/maptileservlet/src/main/resources/tileSetProperties/tileset2.properties deleted file mode 100644 index 54aef3416..000000000 --- a/src/maptileservlet/src/main/resources/tileSetProperties/tileset2.properties +++ /dev/null @@ -1,25 +0,0 @@ -# Note that this tileset is contained in the ommaptile tile set -# properties directory referenced in the web.xml file under the -# TileSetDefinitions property. That's what gets this file read. The -# ant jar target will package this properties file properly for -# deployment in the war. You can add more properties files to the -# directoryfor different tile sets. - -name=Control Room - -#The rootDir for a TileMill file, using the sql jar file in the classpath, too. -rootDir=jdbc:sqlite:/Volumes/data/tiles/control-room.mbtiles -# Windows version: -#rootDir=jdbc:sqlite:/f:/data/tiles/control-room.mbtiles - -# Identifies to the servlet that this tile set needs a different MapTileSet class -# because it will be looking at a mbtiles file -class=com.bbn.openmap.maptileservlet.MBRasterMapTileSet - -# Or, if you like, you can set up a RelayMapTileSet, which will pull -#tiles from one source and cache them on this server for local -#distribution. - -#class=com.bbn.openmap.maptileservlet.RelayMapTileSet -#rootDir=http://someserver.com/tileset/{z}/{y}/{x}.png -#localCacheRootDir=/data/tiles/tileset/{z}/{x}/{y}.png diff --git a/src/maptileservlet/src/main/resources/tileSetProperties/tileset3.properties b/src/maptileservlet/src/main/resources/tileSetProperties/tileset3.properties deleted file mode 100644 index f507d8ed1..000000000 --- a/src/maptileservlet/src/main/resources/tileSetProperties/tileset3.properties +++ /dev/null @@ -1,35 +0,0 @@ -# Note that this tileset is contained in the ommaptile tile set -# properties directory referenced in the web.xml file under the -# TileSetDefinitions property. That's what gets this file read. The -# ant jar target will package this properties file properly for -# deployment in the war. You can add more properties files to the -# directoryfor different tile sets. - -# This tile set uses the MapTileMaker EmptyTileHandler, which will -# generate tiles as needed when they aren't found in the rootDir. - -name=landmass -description=Land mass using shape file -rootDir=/Volumes/data/tiles/cntry02 -emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.MapTileMaker - -# This file should also contain the properties needed to define layers -# and zoom level rules for tile creation. Standard MapTileMaker -# properties apply, see javadoc for details. - - -antialiasing=true -#background=FFDECD8B - -# This layers property is used if no zoom levels are defined. If zoom -# levels are defined, each one will have it's own layers property. If -# some zoom levels are defined, then tiles will only be created for -# those zoom levels, and the servlet will be unresponsive for -# undefined zoom levels. -layers=shapePolitical - -# Standard openmap layer property definition -shapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -shapePolitical.fillColor=ffdecd8b -shapePolitical.lineColor=ffdecd8b -shapePolitical.shapeFile=/Volumes/data/shape/world/cntry02/cntry02.shp diff --git a/src/maptileservlet/src/main/resources/tileSetProperties/tileset4.properties b/src/maptileservlet/src/main/resources/tileSetProperties/tileset4.properties deleted file mode 100644 index a1669bf46..000000000 --- a/src/maptileservlet/src/main/resources/tileSetProperties/tileset4.properties +++ /dev/null @@ -1,155 +0,0 @@ -# Note that this tileset is contained in the ommaptile tile set -# properties directory referenced in the web.xml file under the -# TileSetDefinitions property. That's what gets this file read. The -# ant jar target will package this properties file properly for -# deployment in the war. You can add more properties files to the -# directoryfor different tile sets. - -name=fldnc -description=DNC coverage over Florida - -#The rootDir for a TileMill file, using the sql jar file in the classpath, too. -#rootDir=/Volumes/data/tiles/postgres/{z}/{x}/{y}.png - -emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.MapTileMaker - -antialiasing=true -background=00000000 -formatters=png -layers=dnch dnca dncc dncg -png.class=com.bbn.openmap.image.PNGImageIOFormatter -rootDir=/Volumes/data/tiles/florida_tiles - -zoomLevels=defaultZoom 15 16 -#zoomLevels=0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - -dnca.addToBeanContext=true -dnca.autoPalette=false -dnca.background=false -dnca.cgmDirectory=/Volumes/data/geosym/graphics/cgm -dnca.class=com.bbn.openmap.layer.vpf.VPFFeatureLayer -dnca.consumeEvents=false -dnca.cutoffScale=31000000 -dnca.faccLookupFile=/Volumes/data/vpf/symbology/dnc-symbol-lookup.csv -dnca.featureInfoHandler=com.bbn.openmap.layer.vpf.TTFeatureInfoHandler -dnca.iconSize=20 -dnca.idsm=0.0 -dnca.interruptable=true -dnca.isdm=0.0 -dnca.libraryName=a -dnca.mouseModes=Gestures -dnca.msdc=30.0 -dnca.mssc=1.0 -dnca.pcp.class=com.bbn.openmap.layer.policy.ListResetPCPolicy -dnca.prettyName=DNC Approach -dnca.priorityFile=/Volumes/data/vpf/symbology/dnc-priority-background.csv -dnca.projectionChangePolicy=pcp -dnca.removable=true -dnca.renderPolicy=rp -dnca.rp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy -dnca.ssdc=5.0 -dnca.transparency=1.0 -dnca.vpfPath=/Volumes/data/vpf/dnc/dnc15 -dncc.addToBeanContext=true -dncc.autoPalette=false -dncc.background=false -dncc.cgmDirectory=/Volumes/data/geosym/graphics/cgm -dncc.class=com.bbn.openmap.layer.vpf.VPFFeatureLayer -dncc.consumeEvents=false -dncc.cutoffScale=31000000 -dncc.faccLookupFile=/Volumes/data/vpf/symbology/dnc-symbol-lookup.csv -dncc.iconSize=20 -dncc.idsm=0.0 -dncc.interruptable=true -dncc.isdm=0.0 -dncc.libraryName=c -dncc.mouseModes=Gestures -dncc.msdc=30.0 -dncc.mssc=1.0 -dncc.pcp.class=com.bbn.openmap.layer.policy.ListResetPCPolicy -dncc.prettyName=DNC Coastal -dncc.priorityFile=/Volumes/data/vpf/symbology/dnc-priority-background.csv -dncc.projectionChangePolicy=pcp -dncc.removable=true -dncc.renderPolicy=rp -dncc.rp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy -dncc.ssdc=5.0 -dncc.transparency=1.0 -dncc.vpfPath=/Volumes/data/vpf/dnc/dnc15 -dncg.addToBeanContext=true -dncg.autoPalette=false -dncg.background=false -dncg.cgmDirectory=/Volumes/data/geosym/graphics/cgm -dncg.class=com.bbn.openmap.layer.vpf.VPFFeatureLayer -dncg.consumeEvents=false -dncg.cutoffScale=31000000 -dncg.faccLookupFile=/Volumes/data/vpf/symbology/dnc-symbol-lookup.csv -dncg.iconSize=20 -dncg.idsm=0.0 -dncg.interruptable=true -dncg.isdm=0.0 -dncg.libraryName=g -dncg.mouseModes=Gestures -dncg.msdc=30.0 -dncg.mssc=1.0 -dncg.pcp.class=com.bbn.openmap.layer.policy.ListResetPCPolicy -dncg.prettyName=DNC General -dncg.priorityFile=/Volumes/data/vpf/symbology/dnc-priority-background.csv -dncg.projectionChangePolicy=pcp -dncg.removable=true -dncg.renderPolicy=rp -dncg.rp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy -dncg.ssdc=5.0 -dncg.transparency=1.0 -dncg.vpfPath=/Volumes/data/vpf/dnc/dnc15 -dnch.addToBeanContext=true -dnch.autoPalette=false -dnch.background=false -dnch.cgmDirectory=/Volumes/data/geosym/graphics/cgm -dnch.class=com.bbn.openmap.layer.vpf.VPFFeatureLayer -dnch.consumeEvents=false -dnch.cutoffScale=31000000 -dnch.faccLookupFile=/Volumes/data/vpf/symbology/dnc-symbol-lookup.csv -dnch.iconSize=20 -dnch.idsm=0.0 -dnch.interruptable=true -dnch.isdm=0.0 -dnch.libraryName=h a -dnch.mouseModes=Gestures -dnch.msdc=30.0 -dnch.mssc=1.0 -dnch.pcp.class=com.bbn.openmap.layer.policy.ListResetPCPolicy -dnch.prettyName=DNC Harbor -dnch.priorityFile=/Volumes/data/vpf/symbology/dnc-priority-background.csv -dnch.projectionChangePolicy=pcp -dnch.removable=true -dnch.renderPolicy=rp -dnch.rp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy -dnch.ssdc=5.0 -dnch.transparency=1.0 -dnch.vpfPath=/Volumes/data/vpf/dnc/dnc15 - -#defaultZoom.range=13 -#defaultZoom.zoomLevel=13 -defaultZoom.name=Zoom Level 13 -defaultZoom.description=Configuration for Zoom Level 13 -defaultZoom.bounds=27.27 -80.749 28.382 -80.596 -defaultZoom.class=com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker -defaultZoom.layers=dncc dncg - -15=15 -15.zoomLevel=16 -15.name=Zoom Level 16 -15.description=Configuration for Zoom Level 15 -15.bounds=27.0 -81.5 29.5 -70.8 -15.class=com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker -15.layers=dnch dnca dncc dncg - -16=16 -16.zoomLevel=16 -16.name=Zoom Level 16 -16.description=Configuration for Zoom Level 16 -16.bounds=27.0 -81.5 29.5 -70.8 -16.class=com.bbn.openmap.dataAccess.mapTile.ZoomLevelMaker -16.layers=dnch dnca dncc dncg - diff --git a/src/maptileservlet/src/main/webapp/WEB-INF/.gitignore b/src/maptileservlet/src/main/webapp/WEB-INF/.gitignore deleted file mode 100644 index 165caec40..000000000 --- a/src/maptileservlet/src/main/webapp/WEB-INF/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/classes -/lib diff --git a/src/maptileservlet/src/main/webapp/WEB-INF/web.xml b/src/maptileservlet/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index c08e7cf90..000000000 --- a/src/maptileservlet/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - MapTile Utility Web Services - - A web service intented to provide Tile Map Server (TMS) image tiles, and also control production of those tiles. - - - - - - TileSetDefinitions - ./tileSetProperties - - Standard tile set properties - - - - - - leaflet_css - http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css - - CSS for leaflet map. - - - - - leaflet_js - http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js - - Leaflet map source and definitions. - - - - - - ommaptile - - Provide map tiles as asked for, based on z/x/y.png requests. - - com.bbn.openmap.maptileservlet.MapTileServlet - - - - - - - ommaptile - * - - - - - - 30 - - - diff --git a/src/openmap/com/bbn/openmap/BufferedMapBean.java b/src/openmap/com/bbn/openmap/BufferedMapBean.java deleted file mode 100644 index ab5492ad1..000000000 --- a/src/openmap/com/bbn/openmap/BufferedMapBean.java +++ /dev/null @@ -1,282 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/BufferedMapBean.java,v $ -// $RCSfile: BufferedMapBean.java,v $ -// $Revision: 1.6 $ -// $Date: 2004/10/14 18:05:39 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.AlphaComposite; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.event.ComponentEvent; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.Projection; - -/** - * The BufferedMapBean extends the MapBean by adding (you guessed it) buffering. - *

- * Specifically, the layers are stored in a java.awt.Image so that the frequent - * painting done by Swing on lightweight components will not cause the layers to - * do unnecessary work re-rendering themselves each time. - *

- * Changing the default clipping area may cause some Layers to not be drawn - * completely, depending on what the clipping area is set to and when the layer - * is trying to get itself painted. When manually adjusting clipping area, make - * sure that when restricted clipping is over that a full repaint occurs if - * there is a chance that another layer may be trying to paint itself. - */ -public class BufferedMapBean extends MapBean { - - private static Logger logger = Logger.getLogger(BufferedMapBean.class.getName()); - protected boolean bufferDirty = true; - protected BufferedImage drawingBuffer = null; - - protected PanHelper panningTransform = null; - - public BufferedMapBean() { - super(); - } - - public BufferedMapBean(boolean useThreadedNotification) { - super(useThreadedNotification); - } - - /** - * Invoked when component has been resized. Layer buffer is nullified. and - * super.componentResized(e) is called. - * - * @param e ComponentEvent - */ - public void componentResized(ComponentEvent e) { - setBufferDirty(true); - - super.componentResized(e); - } - - /** - * Provide a drawing buffer for the layers based on the projection - * parameters. If the currentImageBuffer is the right size, the pixels will - * be cleared. - * - * @param currentImageBuffer the buffer to reuse and return, if the size is - * appropriate. Flushed if another BufferedImage is returned. - * @param proj the current projection of the map - * @return BufferedImage to be used for image buffer. - */ - protected BufferedImage resetDrawingBuffer(BufferedImage currentImageBuffer, Projection proj) { - try { - - int w = proj.getWidth(); - int h = proj.getHeight(); - - if (currentImageBuffer != null) { - int cibWidth = currentImageBuffer.getWidth(); - int cibHeight = currentImageBuffer.getHeight(); - - if (cibWidth == w && cibHeight == h) { - Graphics2D graphics = (Graphics2D) currentImageBuffer.getGraphics(); - graphics.setComposite(AlphaComposite.Clear); - graphics.fillRect(0, 0, w, h); - graphics.setComposite(AlphaComposite.SrcOver); - return currentImageBuffer; - } else { - currentImageBuffer.flush(); - } - } - - return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - - } catch (java.lang.NegativeArraySizeException nae) { - } catch (java.lang.IllegalArgumentException iae) { - } - - return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); - } - - /** - * Same as paintChildren, but allows you to set a clipping area to paint. Be - * careful with this, because if the clipping area is set while some layer - * decides to paint itself, that layer may not have all it's objects - * painted. Same warnings apply. - */ - public void paintChildren(Graphics g, Rectangle clip) { - - // if a layer has requested a render, then we render all of - // them into a drawing buffer - BufferedImage localDrawingBuffer = drawingBuffer; - - if (panningTransform == null && bufferDirty) { - bufferDirty = false; - - localDrawingBuffer = resetDrawingBuffer(localDrawingBuffer, getProjection()); - // In case it's been resized - drawingBuffer = localDrawingBuffer; - - // draw the old image - Graphics gr = getMapBeanRepaintPolicy().modifyGraphicsForPainting(localDrawingBuffer.getGraphics()); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("BufferedMapBean rendering layers to buffer."); - } - - super.paintChildren(gr, null); - gr.dispose(); - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("BufferedMapBean rendering buffer."); - } - - if (panningTransform != null) { - - panningTransform.render((Graphics2D) g); - return; - - } else if (localDrawingBuffer != null) { - - RotationHelper rotHelper = getRotHelper(); - - if (rotHelper != null) { - rotHelper.paintChildren(g, clip); - rotHelper.paintPainters(g); - } else { - drawProjectionBackground(g); - // draw the buffer to the screen, daImage will be drawingBuffer - // without rotation - g.drawImage(localDrawingBuffer, 0, 0, null); - - painters.paint(g); - } - } - } - - /** - * Interface-like method to query if the MapBean is buffered, so you can - * control behavior better. Allows the removal of specific instance-like - * queries for, say, BufferedMapBean, when all you really want to know is if - * you have the data is buffered, and if so, should be buffer be cleared. - * For the BufferedMapBean, always true. - */ - public boolean isBuffered() { - return true; - } - - /** - * Marks the image buffer as dirty if value is true. On the next - * paintChildren(), we will call paint() on all - * Layer components. - * - * @param value boolean - */ - public void setBufferDirty(boolean value) { - bufferDirty = value; - } - - /** - * Checks whether the image buffer should be repainted. - * - * @return boolean whether the layer buffer is dirty - */ - public boolean isBufferDirty() { - return bufferDirty; - } - - /** - * Clear out resources for the current drawing buffer. - */ - protected void disposeDrawingBuffer() { - Image localDrawingBuffer = drawingBuffer; - drawingBuffer = null; - if (localDrawingBuffer != null) { - localDrawingBuffer.flush(); - } - } - - public void dispose() { - disposeDrawingBuffer(); - super.dispose(); - } - - public AffineTransform getPanningTransform() { - return panningTransform; - } - - /** - * Set a panning transform on the buffer for rendering in a different place, - * quickly. Sets the buffer to be dirty, so when the panning transform is - * removed, it will be recreated. - * - * @param transform - */ - public void setPanningTransform(AffineTransform transform) { - if (transform != null) { - if (panningTransform == null) { - panningTransform = new PanHelper(transform); - setBufferDirty(true); - } else { - panningTransform.update(transform); - } - } else { - if (panningTransform != null) { - panningTransform.dispose(); - } - panningTransform = null; - } - } - - protected class PanHelper extends AffineTransform { - protected Image buffer; - - protected PanHelper(AffineTransform aft) { - super(aft); - this.buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); - paintChildren(this.buffer.getGraphics(), null); - } - - protected void update(AffineTransform aft) { - super.setTransform(aft); - } - - protected void render(Graphics2D g) { - drawProjectionBackground(g); - ((Graphics2D) g).setTransform(this); - if (buffer != null) { - g.drawImage(buffer, 0, 0, null); - } - - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper == null) { - painters.paint(g); - } - } - - protected void dispose() { - if (buffer != null) { - buffer.flush(); - buffer = null; - } - } - - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/Layer.java b/src/openmap/com/bbn/openmap/Layer.java deleted file mode 100644 index a95f99bf3..000000000 --- a/src/openmap/com/bbn/openmap/Layer.java +++ /dev/null @@ -1,1638 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/Layer.java,v $ -// $RCSfile: Layer.java,v $ -// $Revision: 1.34 $ -// $Date: 2008/09/28 19:06:07 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.MouseListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.lang.reflect.Method; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.swing.Icon; -import javax.swing.JComponent; - -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.gui.ScrollPaneWindowSupport; -import com.bbn.openmap.gui.WindowSupport; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * Layer objects are components which can be added to the MapBean to make a map. - *

- * - * Layers implement the ProjectionListener interface to listen for - * ProjectionEvents. When the projection changes, they may need to refetch, - * regenerate their graphics, and then repaint themselves into the new view. - *

- * - * When the Layer is added to the MapBean, it will start receiving - * ProjectionEvents via the ProjectionListener.projectionChanged() method it has - * to implement. There is a setProjection(ProjectionEvent) methods that should - * be called from there if you want to save the projection for later use - * (handling MouseEvents, etc). If you call getProjection() before calling - * setProjection(), getProjection() will return null, and your OMGraphics will - * complain and probably freak out at some point. - * - *

- * // // SAMPLE handling of the ProjectionListener interface.
- * 
- * public void projectionChanged(com.bbn.openmap.event.ProjectionEvent pe) {
- *     Projection proj = setProjection(pe);
- *     if (proj != null) {
- *         // Use the projection to gather OMGraphics in the layer,
- *         // and prepare the layer so that in the paint() method,
- *         // the OMGraphics get rendered.
- * 
- *         // Call any methods that kick off work to build graphics
- *         // here...
- * 
- *         // You get the paint() methods called by calling
- *         // repaint():
- *         repaint();
- *     }
- * 
- *     fireStatusUpdate(LayerStatusEvent.FINISH_WORKING);
- * }
- * 
- * - * @see com.bbn.openmap.event.ProjectionListener - * @see com.bbn.openmap.event.ProjectionEvent - * @see com.bbn.openmap.PropertyConsumer - */ -public abstract class Layer extends JComponent implements ProjectionListener, ProjectionPainter, - BeanContextChild, BeanContextMembershipListener, PropertyConsumer, ActionListener { - - private static final long serialVersionUID = 1L; - - /** - * Pre-caches the swing package. Computed based on the package of - * JComponent. - */ - protected static final String SWING_PACKAGE = getPackage(JComponent.class); - - /** - * The String to use for a key lookup in a Properties object to find the - * name to use in a GUI relating to this layer. - */ - public static final String PrettyNameProperty = "prettyName"; - - /** - * The property to set to add the layer to the BeanContext - * "addToBeanContext". This probably needs be set by the layer itself, - * because it knows whether it needs other components or not. However, this - * property is defined in case an option can be given to the user. If a - * Layer doesn't want this option given, it should reset the - * addToBeanContext variable after setProperties() is called. The - * Layer.setProperties() methods maintain the current state of the variable - * if undefined, which is true by default. - */ - public static final String AddToBeanContextProperty = "addToBeanContext"; - - /** - * Property 'background' to designate this layer as a background layer, - * which will cause extra buffering to occur if the application can handle - * it. False by default. - */ - public static final String AddAsBackgroundProperty = "background"; - - /** - * Property 'removable' to designate this layer as removable from the - * application, or able to be deleted. True by default. - */ - public static final String RemovableProperty = "removable"; - - /** - * The property for designating the minimum projection scale value that the - * layer will respond to. This Layer class doesn't limit how subclasses will - * react to projections with scale values smaller than the specified value. - */ - public static final String MinScaleProperty = "minScale"; - /** - * The property for designating the maximum projection scale value that the - * layer will respond to. This Layer class doesn't limit how subclasses will - * react to projections with scale values greater than the specified value. - */ - public static final String MaxScaleProperty = "maxScale"; - - /** - * The property to show the palette when the layer is created - or, more - * accurately, when the properties are set. - */ - public static final String AutoPaletteProperty = "autoPalette"; - /** Layer-defined action event command to display the palette. */ - public static final String DisplayPaletteCmd = "displayPaletteCmd"; - /** Layer-defined action event command to hide the palette. */ - public static final String HidePaletteCmd = "hidePaletteCmd"; - /** - * Layer-defined action event command to display the properties using an - * Inspector. - */ - public static final String DisplayPropertiesCmd = "displayPropertiesCmd"; - /** - * Layer-defined action event command to force a redraw on the layer. The - * Layer class does not respond to this command, it's provided as a - * convenience. - */ - public static final String RedrawCmd = "redrawCmd"; - /** - * Generic property that may be set for a layer to let it know at runtime - * that a path prefix needs to be added to a relative data path. This - * property should be set in the attributes of a layer after being read from - * properties. - */ - public static final String DataPathPrefixProperty = "dataPathPrefix"; - - /** - * The property used to name a class providing translation services - * (optional, depends on input data). - */ - public final static String TransformProperty = "transform"; - - /** - * The listeners to the Layer that respond to requests for information - * displays, like messages, requests for URL displays, etc. - */ - private final ListenerSupport IDListeners = new ListenerSupport(this); - - /** - * List of LayerStatusListeners. - */ - private final ListenerSupport lsListeners = new ListenerSupport(this); - - /** - * Token uniquely identifying this layer in the application properties. - */ - protected String propertyPrefix = null; - - /** - * Used by the LayerHandler to check if the layer should be added to the - * MapHandler BeanContext. See the comments under the - * AddToBeanContextProperty. True by default. - */ - protected boolean addToBeanContext = true; - - /** - * Flag used by the layer to indicate that it should be treated as a - * background layer, indicating that any cache mechanism available can - * enable extra buffering. This may prevent mouse events from being received - * by the layer. - */ - protected boolean addAsBackground = false; - - /** - * Flag to designate the layer as removable or not. - */ - protected boolean removable = true; - - /** - * A flag to have the layer display it's palette when the properties are - * set. If you are creating a layer manually, just call showPalette() - * instead. - */ - protected boolean autoPalette = false; - - /** - * A minimum projection scale value that the layer will respond to. Using - * this value for reacting to the projection depends on the Layer - * implementation, the Layer class doesn't limit subclasses from doing their - * own thing in response to the scale setting on a projection. - */ - protected float minScale = Float.MIN_VALUE; - - /** - * A maximum projection scale value that the layer will respond to. Using - * this value for reacting to the projection depends on the Layer - * implementation, the Layer class doesn't limit subclasses from doing their - * own thing in response to the scale setting on a projection. - */ - protected float maxScale = Float.MAX_VALUE; - - /** - * This is a convenience copy of the latest projection received from the - * MapBean, when the Layer is added to the map. If you need it, use the - * accessor!. - */ - private Projection projection = null; - - /** - * Support class that now handles palette windows. - */ - protected transient WindowSupport windowSupport; - - /** - * A helper component listener that is paying attention to the visibility of - * the palette. - */ - protected transient ComponentListener paletteListener; - - /** - * A pointer to the JDialog or JInternalFrame. May be used by the layer's - * ComponentListeners to figure out if a component event is for the layer or - * for the palette. - */ - protected transient Container palette; - - /** - * The BeanContext allows Layers to find other components, and other - * components to find the layer, if the layer is added to it. - */ - protected transient BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * All layers have access to an I18n object, which is provided by the - * Environment. - */ - protected transient I18n i18n = Environment.getI18n(); - - /** - * Icon associated with layer. - */ - private Icon icon = null; - - /** - * Hashtable containing attribute information for the layer. For serialized - * layers, we're not really going out of our way to make sure that keys and - * values are serializable. - */ - protected Hashtable attributes; - - /** - * A translator that can be set to convert pre-projected coordinates from - * the file into decimal degree lat/lon, and for saving data to a file in - * pre-projected coordinates. - */ - protected GeoCoordTransformation coordTransform; - - /** - * New variable to describe when a layer has responded to a projection - * change and is ready to be painted. Used by the BufferedLayerMapBean, - * which limits repaint calls to only be passed on when all background - * layers are ready to be painted. This eliminates the flashing effect - * caused when some layers call for a repaint before background layers do, - * causing the map background to be displayed for a second. - */ - protected AtomicBoolean readyToPaint = new AtomicBoolean(true); - - /** - * Returns the package of the given class as a string. - * - * @param c a class - */ - protected static String getPackage(Class c) { - String className = c.getName(); - int lastDot = className.lastIndexOf('.'); - return className.substring(0, lastDot); - } - - /** - * Override to only allow swing package listeners. If Listeners get added to - * the Layers, the mouse events don't make it to the map. Ever. - *

- * Swing popup menus, like JPopupMenu grab the JComponent by - * adding themselves as MouseListener s. So this method allows - * instances of classes in the xxx.swing package to be added as - * MouseListeners, and no one else. - * - * @param l a mouse listener. - */ - public final void addMouseListener(MouseListener l) { - String pkg = getPackage(l.getClass()); - if (java.beans.Beans.isDesignTime() || pkg.equals(SWING_PACKAGE) - || pkg.startsWith(SWING_PACKAGE) - || pkg.startsWith("com.sun.java.accessibility.util")) { - - // Used to do nothing for the equals and startsWith - // comparison, but that breaks the menus from being - // recinded when something else is clicked on. Thanks to - // Tom Peel for pointing this out, 11/29/00. - super.addMouseListener(l); - } else { - throw new IllegalArgumentException("This operation is disallowed because the package \"" - + getPackage(l.getClass()) + "\" is not in the swing package (\"" - + SWING_PACKAGE + "\")."); - } - } - - /** - * Sets the properties for the Layer. This particular method - * assumes that the marker name is not needed, because all of the contents - * of this Properties object are to be used for this layer, and scoping the - * properties with a prefix is unnecessary. - * - * @param props the Properties object. - */ - public void setProperties(Properties props) { - setProperties(getPropertyPrefix(), props); - } - - /** - * Sets the properties for the Layer. Part of the - * PropertyConsumer interface. Layers which override this method should do - * something like: - * - *

-     * public void setProperties(String prefix, Properties props) {
-     *     super.setProperties(prefix, props);
-     *     // do local stuff
-     * }
-     * 
- * - * If the addToBeanContext property is not defined, it maintains the same - * state. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - setLayerProperties(prefix, props); - } - - /** - * Called by setProperties. Allows subclasses to avoid super.setProperties() - * while still having basic Layer settings taken care of. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - protected void setLayerProperties(String prefix, Properties props) { - String prettyName = PrettyNameProperty; - setPropertyPrefix(prefix); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - prettyName = realPrefix + PrettyNameProperty; - - String defaultName = getName(); - if (defaultName == null) { - defaultName = "Anonymous"; - } - - setName(props.getProperty(prettyName, defaultName)); - - setAddToBeanContext(PropUtils.booleanFromProperties(props, realPrefix - + AddToBeanContextProperty, addToBeanContext)); - - setAddAsBackground(PropUtils.booleanFromProperties(props, realPrefix - + AddAsBackgroundProperty, addAsBackground)); - - setRemovable(PropUtils.booleanFromProperties(props, realPrefix - + RemovableProperty, removable)); - - autoPalette = PropUtils.booleanFromProperties(props, realPrefix - + AutoPaletteProperty, autoPalette); - - setMinScale(PropUtils.floatFromProperties(props, realPrefix - + MinScaleProperty, getMinScale())); - setMaxScale(PropUtils.floatFromProperties(props, realPrefix - + MaxScaleProperty, getMaxScale())); - - String dataPathPrefix = props.getProperty(realPrefix + DataPathPrefixProperty, ""); - if (dataPathPrefix.length() > 0) { - putAttribute(DataPathPrefixProperty, dataPathPrefix); - } - - String transClassName = props.getProperty(realPrefix + TransformProperty); - if (transClassName != null) { - try { - coordTransform = (GeoCoordTransformation) ComponentFactory.create(transClassName, realPrefix - + TransformProperty, props); - } catch (ClassCastException cce) { - - } - } - } - - public void setName(String name) { - super.setName(name); - - BeanContext bc = getBeanContext(); - if (bc instanceof MapHandler) { - LayerHandler lh = (LayerHandler) ((MapHandler) bc).get("com.bbn.openmap.LayerHandler"); - - if (lh != null) { - lh.setLayers(); - } - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - props.put(prefix + "class", this.getClass().getName()); - - String prettyName = getName(); - if (prettyName != null) { - props.put(prefix + PrettyNameProperty, prettyName); - } - - props.put(prefix + AutoPaletteProperty, new Boolean(autoPalette).toString()); - props.put(prefix + AddAsBackgroundProperty, new Boolean(addAsBackground).toString()); - props.put(prefix + RemovableProperty, new Boolean(removable).toString()); - props.put(prefix + AddToBeanContextProperty, new Boolean(addToBeanContext).toString()); - - if (getMinScale() != Float.MIN_VALUE) { - props.put(prefix + MinScaleProperty, Float.toString(getMinScale())); - } - if (getMaxScale() != Float.MAX_VALUE) { - props.put(prefix + MaxScaleProperty, Float.toString(getMaxScale())); - } - - String dataPathPrefix = (String) getAttribute(DataPathPrefixProperty); - if (dataPathPrefix != null) { - props.put(prefix + DataPathPrefixProperty, dataPathPrefix); - } - - if (coordTransform instanceof PropertyConsumer) { - ((PropertyConsumer) coordTransform).getProperties(props); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put("class", "Class Name used for Layer."); - list.put("class.editor", "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - - String internString = i18n.get(Layer.class, PrettyNameProperty, I18n.TOOLTIP, "Presentable name for Layer"); - list.put(PrettyNameProperty, internString); - internString = i18n.get(Layer.class, PrettyNameProperty, "Layer Name"); - list.put(PrettyNameProperty + LabelEditorProperty, internString); - list.put(PrettyNameProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.NonEditablePropertyEditor"); - - internString = i18n.get(Layer.class, AutoPaletteProperty, I18n.TOOLTIP, "Flag to automatically display palette when properties are set"); - list.put(AutoPaletteProperty, internString); - internString = i18n.get(Layer.class, AutoPaletteProperty, "Open Palette At Start"); - list.put(AutoPaletteProperty + LabelEditorProperty, internString); - list.put(AutoPaletteProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, AddAsBackgroundProperty, I18n.TOOLTIP, "Flag to use the layer as a background layer"); - list.put(AddAsBackgroundProperty, internString); - internString = i18n.get(Layer.class, AddAsBackgroundProperty, "Background"); - list.put(AddAsBackgroundProperty + LabelEditorProperty, internString); - list.put(AddAsBackgroundProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, RemovableProperty, I18n.TOOLTIP, "Flag to allow layer to be deleted."); - list.put(RemovableProperty, internString); - internString = i18n.get(Layer.class, RemovableProperty, "Removable"); - list.put(RemovableProperty + LabelEditorProperty, internString); - list.put(RemovableProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, AddToBeanContextProperty, I18n.TOOLTIP, "Flag to give the layer access to all of the other application components."); - list.put(AddToBeanContextProperty, internString); - internString = i18n.get(Layer.class, AddToBeanContextProperty, "Add to MapHandler"); - list.put(AddToBeanContextProperty + LabelEditorProperty, internString); - list.put(AddToBeanContextProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - internString = i18n.get(Layer.class, MinScaleProperty, I18n.TOOLTIP, "Minimum projection scale value that the layer will respond to."); - list.put(MinScaleProperty, internString); - internString = i18n.get(Layer.class, MinScaleProperty, "Minimum Scale Value"); - list.put(MinScaleProperty + LabelEditorProperty, internString); - - internString = i18n.get(Layer.class, MaxScaleProperty, I18n.TOOLTIP, "Maximum projection scale value that the layer will respond to."); - list.put(MaxScaleProperty, internString); - internString = i18n.get(Layer.class, MaxScaleProperty, "Maximum Scale Value"); - list.put(MaxScaleProperty + LabelEditorProperty, internString); - - return list; - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix for the layer - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * Set the projection the layer should use for calculations. You probably - * don't need this if you are wondering if you do. Call - * setProjection(projEvent) instead. - */ - public void setProjection(Projection proj) { - projection = proj; - } - - /** - * This method lets you take the ProjectionEvent received from the MapBean, - * and lets you know if you should do something with it. MUST to be called - * in the projectionChanged() method of your layer, if you want to refer to - * the projection later. If this methods returns null, you probably just - * want to call repaint() if your layer.paint() method is ready to paint - * what it should. - * - * @param projEvent the ProjectionEvent from the ProjectionListener method. - * @return The new Projection if it is different from the one we already - * have, null if is the same as the current one. - */ - public Projection setProjection(ProjectionEvent projEvent) { - Projection newProjection = projEvent.getProjection(); - - if (!newProjection.equals(getProjection())) { - Projection clone = newProjection.makeClone(); - setProjection(clone); - return clone; - } else { - return null; - } - } - - /** - * Get the latest projection. - */ - public Projection getProjection() { - return projection; - } - - /** - * Returns the MapMouseListener object that handles the mouse events. This - * method is IGNORED in this class: it returns null. Derived Layers should - * return the appropriate object if they desire to receive MouseEvents. The - * easiest thing for a Layer to do in order to receive MouseEvents is to - * implement the MapMouseListener interface and return itself. A code - * snippet: - *

- *

-     * public MapMouseListener getMapMouseListener() {
-     *     return this;
-     * }
-     * 
-     * public String[] getMouseModeServiceList() {
-     *     return new String[] { SelectMouseMode.modeID };
-     * }
-     * 
- * - * @return null for the default, method can be overridden to return - * something interested in mouse events. - */ - public MapMouseListener getMapMouseListener() { - return null; - } - - /** - * A GUI query method for other components to use to display whether gui - * controls are available for this layer. If your layer provides gui - * controls and the LayersPanel is being used in your application, you - * should override this method in your layer to return true. This will allow - * the other gui components to know that your layer has controls, while - * still not actually building those controls until they are needed by the - * user. - * - * @return true if there is a GUI for controlling the layer settings, false - * if not or if the getGUI() method hasn't been overridden. - */ - public boolean hasGUI() { - boolean hasGUI = false; - - try { - Method guiMethod = getClass().getMethod("getGUI", (Class[]) null); - hasGUI = (guiMethod.getDeclaringClass() != Layer.class); - } catch (Exception ex) { - hasGUI = getGUI() != null; - } - - return hasGUI; - } - - /** - * Gets the gui controls associated with the layer. This default - * implementation returns null indicating that the layer has no gui - * controls. - * - * @return java.awt.Component or null, null by default. - */ - public Component getGUI() { - return null; - } - - // ///////////////////////////////////////////////// - // InfoDisplay Handling Setup and Firing - - /** - * Adds a listener for InfoDisplayEvents. - * - * @param aInfoDisplayListener the listener to add - */ - public void addInfoDisplayListener(InfoDisplayListener aInfoDisplayListener) { - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.add(aInfoDisplayListener); - // } - } - - /** - * Removes an InfoDisplayListener from this Layer. - * - * @param aInfoDisplayListener the listener to remove - */ - public void removeInfoDisplayListener(InfoDisplayListener aInfoDisplayListener) { - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.remove(aInfoDisplayListener); - // } - } - - /** - * Sends a request to the InfoDisplayListener to show the information in the - * InfoDisplay event on an single line display facility. - * - * @param evt the InfoDisplay event carrying the string. - */ - public void fireRequestInfoLine(InfoDisplayEvent evt) { - // synchronized (IDListeners) { // //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestInfoLine(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplay listener to display the information on - * an single line display facility. The InfoDisplayEvent is created inside - * this function. - * - * @param infoLine the string to put in the InfoDisplayEvent. - */ - public void fireRequestInfoLine(String infoLine) { - fireRequestInfoLine(new InfoDisplayEvent(this, infoLine)); - } - - /** - * Sends a request to the InfoDisplay listener to display the information on - * an single line display facility at preferred location. The - * InfoDisplayEvent is created inside this function. - * - * @param infoLine the string to put in the InfoDisplayEvent. - * @param loc the index of a preferred location, starting at 0. - */ - public void fireRequestInfoLine(String infoLine, int loc) { - fireRequestInfoLine(new InfoDisplayEvent(this, infoLine, loc)); - } - - /** - * Sends a request to the InfoDisplay listener to display the information in - * the InfoDisplay event in a Browser. - * - * @param evt the InfoDisplayEvent holding the contents to put in the - * Browser. - */ - public void fireRequestBrowserContent(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestBrowserContent(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display the information in - * a Browser. The InfoDisplayEvent is created here holding the - * browserContent - * - * @param browserContent the contents to put in the Browser. - */ - public void fireRequestBrowserContent(String browserContent) { - fireRequestBrowserContent(new InfoDisplayEvent(this, browserContent)); - } - - /** - * Sends a request to the InfoDisplayListener to display a URL given in the - * InfoDisplay event in a Browser. - * - * @param evt the InfoDisplayEvent holding the url location to give to the - * Browser. - */ - public void fireRequestURL(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestURL(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display a URL in a browser. - * The InfoDisplayEvent is created here, and the URL location is put inside - * it. - * - * @param url the url location to give to the Browser. - */ - public void fireRequestURL(String url) { - fireRequestURL(new InfoDisplayEvent(this, url)); - } - - /** - * Sends a request to the InfoDisplayListener to show a specific cursor over - * its component area. - * - * @param cursor the cursor to use. - */ - public void fireRequestCursor(java.awt.Cursor cursor) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestCursor(cursor); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to put the information in the - * InfoDisplay event in a dialog window. - * - * @param evt the InfoDisplayEvent holding the message to put into the - * dialog window. - */ - public void fireRequestMessage(InfoDisplayEvent evt) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - listener.requestMessage(evt); - } - // } - } - - /** - * Sends a request to the InfoDisplayListener to display the information in - * a dialog window. The InfoDisplayEvent is created here, and the URL - * location is put inside it. - * - * @param message the message to put in the dialog window. - */ - public void fireRequestMessage(String message) { - fireRequestMessage(new InfoDisplayEvent(this, message)); - } - - /** - * Request to show the tool tips on the map. - * - * @param tip string to display. - */ - public void fireRequestToolTip(String tip) { - fireRequestToolTip(new InfoDisplayEvent(this, tip)); - } - - /** - * Request to hide the tool tips on the map. - */ - public void fireHideToolTip() { - fireRequestToolTip((InfoDisplayEvent) null); - } - - /** - * Fire off a Tool Tip request to the InfoDisplayListeners. If the - * InfoDisplayEvent is null, then a requestHideToolTip will be fired. - */ - public void fireRequestToolTip(InfoDisplayEvent event) { - // synchronized (IDListeners) { //2012.06.15 TAW - for (InfoDisplayListener listener : IDListeners) { - if (event != null) { - listener.requestShowToolTip(event); - } else { - listener.requestHideToolTip(); - } - } - // } - } - - // ///////////////////////////////////////////////// - // LayerStatus Handling Setup and Firing - - /** - * Adds a listener for LayerStatusEvents. - * - * @param aLayerStatusListener LayerStatusListener - */ - public void addLayerStatusListener(LayerStatusListener aLayerStatusListener) { - // synchronized (lsListeners) { //2012.06.15 TAW - lsListeners.add(aLayerStatusListener); - // } - } - - /** - * Removes a LayerStatusListene from this Layer. - * - * @param aLayerStatusListener the listener to remove - */ - public void removeLayerStatusListener(LayerStatusListener aLayerStatusListener) { - // synchronized (lsListeners) { //2012.06.15 TAW - lsListeners.remove(aLayerStatusListener); - // } - } - - /** - * Sends a status update to the LayerStatusListener. - * - * @param evt LayerStatusEvent - */ - public void fireStatusUpdate(LayerStatusEvent evt) { - // synchronized (lsListeners) { //2012.06.15 TAW - // AWTAvailable conditional removed, not used, not useful. - for (LayerStatusListener listener : lsListeners) { - listener.updateLayerStatus(evt); - } - // } - } - - /** - * Sends a status update to the LayerStatusListener. - * - * @param status the new status - */ - public void fireStatusUpdate(int status) { - fireStatusUpdate(new LayerStatusEvent(this, status)); - } - - /** - * Repaint the layer. If you are using BufferedMapBean for your application, - * WE STRONGLY RECOMMEND THAT YOU DO NOT OVERRIDE THIS METHOD. This method - * marks the layer buffer so that it will be refreshed. If you override this - * method, and don't call super.repaint(), the layers will not be repainted. - */ - public void repaint(long tm, int x, int y, int width, int height) { - readyToPaint.set(true); - Component p = getParent(); - if (p instanceof MapBean) { - ((MapBean) p).setBufferDirty(true); - if (Debug.debugging("basic")) { - Debug.output(getName() + "|Layer: repaint(tm=" + tm + ", x=" + x + ", y=" + y - + ", width=" + width + ", height=" + height + ")"); - } - - // How dangerous is this? Let the MapBean manage the - // repaint call? Seems to work OK, and lets the buffered - // MapBeans work better when they are embedded in other - // components. It's this call here that makes the - // BufferedLayer work right. - - // This repaint request has been changed to call a - // specific - // method on the MapBean, which includes the layer making - // the request. This is a hook for a policy object in the - // MapBean to make a decision on whether to honor the - // request, or to handle it in a different way if the - // environment dictates that should happen. - - // ((MapBean)p).repaint(); to -> - ((MapBean) p).repaint(this); - } else if (p != null) { - p.repaint(tm, x, y, width, height); - } else { - super.repaint(tm, x, y, width, height); - } - } - - /** - * This method is here to provide a default action for Layers as they act as - * a ProjectionPainter. Normally, ProjectionPainters are expected to receive - * the projection, gather/create OMGraphics that apply to the projection, - * and render them into the Graphics provided. This is supposed to be done - * in the same thread that calls this function, so the caller knows that - * when this method returns, everything that the ProjectionPainter needed to - * do is complete. - *

- * If the layer doesn't override this method, then the paint(Graphics) - * method will be called. - * - * @param proj Projection of the map. - * @param g java.awt.Graphics to draw into. - */ - public void renderDataForProjection(Projection proj, Graphics g) { - if (isProjectionOK(proj)) { - paint(g); - } - } - - /** - * Method that responds whether the Layer should render on the map, given a - * particular projection. The method currently just tests the projection's - * scale against the min and max values set on the layer. - * - * @param proj The projection to test against. - * @return true if OK. - */ - public boolean isProjectionOK(Projection proj) { - return (proj != null && proj.getScale() >= minScale && proj.getScale() <= maxScale); - } - - /** - * This method is called when the layer is added to the MapBean - * - * @param cont Container - */ - public void added(Container cont) { - } - - /** - * This method is called after the layer is removed from the MapBean and - * when the projection changes. We recommend that Layers override this - * method and nullify memory-intensive variables. - * - * @param cont Container - */ - public void removed(Container cont) { - } - - /** - * Method called when layer detects that it has been removed from - * MapHandler, assumes it's being thrown away. Use this method to let go of - * everything and to make any calls necessary to remove from listener lists - * that might not get picked up via MapHandler calls. - */ - public void dispose() { - clearListeners(); - if (attributes != null) { - attributes.clear(); - } - removed(null); - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - protected ListenerSupport localHackList; - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. Set to false to test. - */ - protected boolean doHack = true; - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void setVisible(boolean show) { - super.setVisible(show); - if (doHack && !show) { - notifyHideHack(); - } - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void addComponentListener(ComponentListener cl) { - super.addComponentListener(cl); - if (localHackList == null) { - localHackList = new ListenerSupport(this); - } - localHackList.add(cl); - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void removeComponentListener(ComponentListener cl) { - super.removeComponentListener(cl); - if (localHackList != null) { - localHackList.remove(cl); - } - } - - /** - * Part of a layer hack to notify the component listener when the component - * is hidden. These components don't receive the ComponentHidden - * notification. Remove when it works. - */ - public void notifyHideHack() { - if (localHackList == null) { - return; - } - - ComponentEvent ce = new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN); - - for (ComponentListener listener : localHackList) { - listener.componentHidden(ce); - } - } - - /** - * Set whether the Layer should be added to the BeanContext. - */ - public void setAddToBeanContext(boolean set) { - addToBeanContext = set; - } - - /** - * Set whether the Layer should be added to the BeanContext. - */ - public boolean getAddToBeanContext() { - return addToBeanContext; - } - - /** - * Mark the layer as one that should be considered a background layer. What - * that means is up to the MapBean or application. - */ - public void setAddAsBackground(boolean set) { - addAsBackground = set; - } - - /** - * Check to see if the layer is marked as one that should be considered a - * background layer. What that means is up to the MapBean or application. - * - * @return true if layer is a background layer, meaning that it should be - * dropped to the bottom of the map and incorporated into a - * background layer image buffer if one is available. - */ - public boolean getAddAsBackground() { - return addAsBackground; - } - - /** - * @return the readyToPaint - */ - public boolean isReadyToPaint() { - return readyToPaint.get(); - } - - /** - * @param readyToPaint the readyToPaint to set - */ - public void setReadyToPaint(boolean readyToPaint) { - this.readyToPaint.set(readyToPaint); - } - - /** - * Mark the layer as removable, or one that can be deleted from the - * application. What that means is up to the LayerHandler or other - * application components. - */ - public void setRemovable(boolean set) { - removable = set; - } - - /** - * Check to see if the layer is marked as one that can be removed from an - * application. - * - * @return true if layer should be allowed to be deleted. - */ - public boolean isRemovable() { - return removable; - } - - /** - * Check to see if the removable layer can be removed now. - * - * @return true if layer should be allowed to be deleted. - */ - public boolean removeConfirmed() { - return true; - } - - /** - * This is the method that your layer can use to find other objects within - * the MapHandler (BeanContext). This method gets called when the Layer gets - * added to the MapHandler, or when another object gets added to the - * MapHandler after the Layer is a member. If the LayerHandler creates the - * Layer from properties, the LayerHandler will add the Layer to the - * BeanContext if Layer.addToBeanContext is true. It is false by default. - * - * For Layers, this method doesn't do anything by default. If you need your - * layer to get ahold of another object, then you can use the Iterator to go - * through the objects to look for the one you need. - */ - public void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - /** - * This method is called by the findAndInit(Iterator) method, once for every - * object inside the iterator. It's here to allow subclasses a way to - * receive objects and still let the super classes have a shot at the - * object. So, you can override this method can call super.findAndInit(obj), - * or override the findAndInit(Iterator) method and call - * super.findAndInit(obj). Whatever. - */ - public void findAndInit(Object obj) { - } - - /** - * BeanContextMembershipListener method. Called when a new object is added - * to the BeanContext of this object. - */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - findAndInit(bcme.iterator()); - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. For the Layer, this method doesn't - * do anything. If your layer does something with the childrenAdded method, - * or findAndInit, you should take steps in this method to unhook the layer - * from the object used in those methods. - */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - /** - * This is the method that does the opposite as the findAndInit(Object). - * Lets you call super classes with objects that need to be removed. At this - * level, if the layer detects that it is being removed from the MapHandler, - * it calls dispose on itself. - */ - public void findAndUndo(Object obj) { - if (obj == this) { - this.dispose(); - } - } - - /** Method for BeanContextChild interface. */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** - * Method for BeanContextChild interface. Gets an iterator from the - * BeanContext to call findAndInit() over. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - connectToBeanContext(in_bc); - findAndInit(in_bc.iterator()); - } - } - - /** - * Layer method to just connect to the BeanContext, without grabbing the - * iterator as in setBeanContext(). Good for protected sub-layers where you - * want to optimize the calling of the findAndInit() method over them. - */ - public void connectToBeanContext(BeanContext in_bc) throws PropertyVetoException { - - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - } - } - - /** - * Layer method to just disconnect from the BeanContext, without grabbing - * the iterator as in setBeanContext(). Good for protected sub-layers where - * you want to optimize the calling of the findAndUndo() method over them. - */ - public void disconnectFromBeanContext() throws PropertyVetoException { - - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.removeBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(null); - } - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to add a listener to this object's property. This listener wants to have - * the right to veto a property change. - */ - public void addVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Method for BeanContextChild interface. Uses the BeanContextChildSupport - * to remove a listener to this object's property. The listener has the - * power to veto property changes. - */ - public void removeVetoableChangeListener(String propertyName, VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, in_vcl); - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - super.fireVetoableChange(name, oldValue, newValue); - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - public void clearListeners() { - if (localHackList != null) { - localHackList.clear(); - } - // synchronized (IDListeners) { //2012.06.15 TAW - IDListeners.clear(); - // } - // synchronized (lsListeners) { - lsListeners.clear(); - // } - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.removeBeanContextMembershipListener(this); - } - } - - protected void finalize() { - if (Debug.debugging("gc")) { - Debug.output("Layer |" + getName() + " |: getting GC'd"); - } - } - - /** - * Fire a component event to the Layer component listeners, with the palette - * as the component, letting them know if it's visible or not. - */ - public void firePaletteEvent(ComponentEvent event) { - if (localHackList == null) { - return; - } - - palette = (Container) event.getSource(); - int eventType = event.getID(); - for (ComponentListener listener : localHackList) { - if (eventType == ComponentEvent.COMPONENT_HIDDEN) { - listener.componentHidden(event); - } else if (eventType == ComponentEvent.COMPONENT_SHOWN) { - listener.componentShown(event); - } - } - - if (eventType == ComponentEvent.COMPONENT_HIDDEN) { - palette = null; - } - } - - /** - * Return the JDialog, or JInternalFrame, that serves as the palette for the - * layer. May be null. - */ - public Container getPalette() { - return palette; - } - - /** - * Called when something about the layer has changed that would require the - * palette to be reconfigured. Will cause getGUI() to be called again. You - * should take steps before calling this method to make sure that the - * getGUI() method is ready to recreate the palette components from scratch - * if needed. - */ - protected void resetPalette() { - java.awt.Container pal = getPalette(); - boolean putUp = false; - if (pal != null && pal.isVisible()) { - putUp = true; - setPaletteVisible(false); - } - - if (putUp) { - setPaletteVisible(true); - } - } - - /** - * Make the palette visible or not, destroy if invisible. - */ - public void setPaletteVisible(boolean visible) { - if (visible) { - showPalette(); - } else { - hidePalette(); - } - } - - /** - * Set the WindowSupport object handling the palette. - */ - public void setWindowSupport(WindowSupport ws) { - windowSupport = ws; - } - - /** - * Get the WindowSupport object handling the palette. - */ - public WindowSupport getWindowSupport() { - return windowSupport; - } - - /** - * Callback method to override how window support is created. - * - * @return WindowSupport object for layer palette. - */ - protected WindowSupport createWindowSupport() { - return new ScrollPaneWindowSupport(getGUI(), getName()); - } - - /** - * Make the palette visible. Will automatically determine if we're running - * in an applet environment and will use a JInternalFrame over a JFrame if - * necessary. - */ - public void showPalette() { - - WindowSupport ws = getWindowSupport(); - if (ws == null) { - ws = createWindowSupport(); - paletteListener = new ComponentAdapter() { - public void componentShown(ComponentEvent e) { - firePaletteEvent(e); - } - - public void componentHidden(ComponentEvent e) { - firePaletteEvent(e); - } - }; - setWindowSupport(ws); - } else { - ws.setTitle(getName()); - ws.setContent(getGUI()); - } - - if (ws != null) { - MapHandler mh = (MapHandler) getBeanContext(); - // Window frame = null; // java 5 incompatibility - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - - if (frame == null) { - MapBean mapBean = (MapBean) mh.get("com.bbn.openmap.MapBean"); - if (mapBean == null) { - Debug.message("layer", "Layer.showPalette: Warning...mapBean = null"); - } else { - try { - java.awt.Component parent = mapBean.getParent(); - while (parent.getParent() != null - && !(parent instanceof java.awt.Window)) { - parent = parent.getParent(); - } - - /* java 5 incompatibility */ - /* - * if (parent instanceof java.awt.Window) { frame = - * (java.awt.Window) parent; } - */ - - if (parent instanceof java.awt.Frame) { - frame = (java.awt.Frame) parent; - } - - } catch (Exception e) { - e.printStackTrace(); - } // ignore any problems here - } - } - } - - if (paletteListener != null) { - ws.addComponentListener(paletteListener); - } - ws.displayInWindow(frame); - } - } - - /** - * Hide the layer's palette. - */ - public void hidePalette() { - WindowSupport ws = getWindowSupport(); - if (ws != null) { - ws.killWindow(); - } - } - - /** - * The default actionPerformed method for Layer. Make sure you call - * super.actionPerformed if you care about receiving palette show/hide - * commands. This method is also set up to receive the DisplayPropertiesCmd, - * and will bring up the Inspector for the layer. - */ - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - if (command == DisplayPaletteCmd) { - if (Debug.debugging("layer")) { - Debug.output(getName() + " displaying palette"); - } - showPalette(); - } else if (command == HidePaletteCmd) { - if (Debug.debugging("layer")) { - Debug.output(getName() + " hiding palette"); - } - hidePalette(); - } else if (command == DisplayPropertiesCmd) { - Inspector inspector = new Inspector(); - inspector.inspectPropertyConsumer(this); - } - } - - /** - * Handle Serialization a little bit better, replacing the I18n and - * BeanContextChildSupport. - * - * @param in - * @throws IOException - * @throws ClassNotFoundException - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - i18n = Environment.getI18n(); - beanContextChildSupport = new BeanContextChildSupport(this); - } - - public Icon getIcon() { - return icon; - } - - public void setIcon(Icon icon) { - this.icon = icon; - } - - public boolean isAutoPalette() { - return autoPalette; - } - - public void setAutoPalette(boolean autoPalette) { - this.autoPalette = autoPalette; - } - - public float getMaxScale() { - return maxScale; - } - - public void setMaxScale(float maxScale) { - this.maxScale = maxScale; - } - - public float getMinScale() { - return minScale; - } - - public void setMinScale(float minScale) { - this.minScale = minScale; - } - - public void putAttribute(Object key, Object value) { - if (attributes == null) { - attributes = new Hashtable(); - } - attributes.put(key, value); - } - - public Object getAttribute(Object key) { - Object ret = null; - if (key != null && attributes != null) { - ret = attributes.get(key); - } - return ret; - } - - public GeoCoordTransformation getCoordTransform() { - return coordTransform; - } - - public void setCoordTransform(GeoCoordTransformation coordTranslator) { - this.coordTransform = coordTranslator; - } - - /** - * The dataPathPrefix layer attribute lets you append a path to a relative - * path at runtime. This method tells the layer to check for that layer - * attribute for such a prefix path, and prepends it to the given string - * separating them with a '/'. - * - * @param fileName to prepend the attribute to - */ - protected String prependDataPathPrefix(String fileName) { - String dataPathPrefix = (String) getAttribute(Layer.DataPathPrefixProperty); - if (dataPathPrefix != null && dataPathPrefix.length() > 0) { - fileName = dataPathPrefix + "/" + fileName; - } - return fileName; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/LayerHandler.java b/src/openmap/com/bbn/openmap/LayerHandler.java deleted file mode 100644 index 0cf64c220..000000000 --- a/src/openmap/com/bbn/openmap/LayerHandler.java +++ /dev/null @@ -1,1144 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/LayerHandler.java,v $ -// $RCSfile: LayerHandler.java,v $ -// $Revision: 1.16 $ -// $Date: 2006/08/09 21:08:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Component; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.LayerConfigurationListener; -import com.bbn.openmap.event.LayerConfigurationListenerSupport; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.LayerSupport; -import com.bbn.openmap.plugin.PlugIn; -import com.bbn.openmap.plugin.PlugInLayer; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The LayerHandler is a component that keeps track of all Layers for the - * MapBean, whether or not they are currently part of the map or not. It is able - * to dynamically add and remove layers from the list of available layers. - * Whether a layer is added to the MapBean depends on the visibility setting of - * the layer. If Layer.isVisible() is true, the layer will be added to the - * MapBean. There are methods within the LayerHandler that let you change the - * visibility setting of a layer. - *

- * The LayerHandler is able to take a Properties object, and create layers that - * are defined within it. The key property is "layers", which may or may not - * have a prefix for it. If that property does have a prefix (prefix.layers, - * i.e. openmap.layers), then that prefix has to be known and passed in to the - * constructor or init method. This layers property should fit the general - * openmap marker list paradigm, where the marker names are listed in a space - * separated list, and then each marker name is used as a prefix for the - * properties for a particular layer. As a minimum, each layer needs to have the - * class and prettyName properties defined. The class property should define the - * class name to use for the layer, and the prettyName property needs to be a - * name for the layer to be used in the GUI. Any other property that the - * particular layer can use should be listed in the Properties, with the - * applicable marker name as a prefix. Each layer should have its available - * properties defined in its documentation. For example: - *

- *

- * - *

- *           <p/>
- *             openmap.layers=marker1 marker2 (etc)
- *             marker1.class=com.bbn.openmap.layer.GraticuleLayer
- *             marker1.prettyName=Graticule Layer
- *             # false is default
- *             marker1.addToBeanContext=false
- *           <p/>
- *             marker2.class=com.bbn.openmap.layer.shape.ShapeLayer
- *             marker2.prettyName=Political Boundaries
- *             marker2.shapeFile=pathToShapeFile
- *             marker2.spatialIndex=pathToSpatialIndexFile
- *             marker2.lineColor=FFFFFFFF
- *             marker2.fillColor=FFFF0000
- *           <p/>
- * 
- * - *

- * The LayerHandler is a SoloMapComponent, which means that for a particular - * map, there should only be one of them. When a LayerHandler is added to a - * BeanContext, it will look for a MapBean to connect to itself as a - * LayerListener so that the MapBean will receive LayerEvents - this is the - * mechanism that adds and removes layers on the map. If more than one MapBean - * is added to the BeanContext, then the last MapBean added will be added as a - * LayerListener, with any prior MapBeans added as a LayerListener removed from - * the LayerHandler. The MapHandler controls the behavior of multiple - * SoloMapComponent addition to the BeanContext. - */ -public class LayerHandler extends OMComponent implements SoloMapComponent, Serializable { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.LayerHandler"); - - /** - * Property for space separated layers. If a prefix is needed, just use the - * methods that let you use the prefix - don't worry about the period, it - * will be added automatically. - */ - public static final String layersProperty = "layers"; - /** - * Property for space separated layers to be displayed at startup. If a - * prefix is needed, just use the methods that let you use the prefix - - * don't worry about the period, it will be added automatically. - */ - public static final String startUpLayersProperty = "startUpLayers"; - /** - * Flag to set synchronous threading on the LayerHandler, telling it to - * react to layer order changes and layer visibility requests within the - * calling thread. By default, this action is true. Setting it to false may - * eliminate pauses in GUI reactions by off-loading work done by layers - * being added to the MapBean, but there have been reports that the - * asynchronous nature of the threading queue may be causing an unexpected - * state in layer order and/or availability under certain intense layer - * management conditions (created by automated processes, for example). - */ - public static final String SynchronousThreadingProperty = "synchronousThreading"; - /** - * The object holding on to all LayerListeners interested in the layer - * arrangement and availability. Not expected to be null. - */ - protected transient LayerSupport listeners = new LayerSupport(this); - /** - * LayerConfigurationListenerSupport for LayerConfigurationListeners. - */ - protected transient LayerConfigurationListenerSupport layerConfigListeners = new LayerConfigurationListenerSupport(this); - /** - * The list of all layers, even the ones that are not part of the map. - */ - protected List allLayers = new ArrayList(); - /** - * This handle is only here to keep it appraised of layer prefix names. - */ - protected PropertyHandler propertyHandler; - - /** - * If you use this constructor, the LayerHandler expects that the layers - * will be created and added later, either by addLayer() or init(). - */ - public LayerHandler() { - } - - /** - * Start the LayerHandler, and have it create all the layers as defined in a - * properties file. - * - * @param props properties as defined in an openmap.properties file. - */ - public LayerHandler(Properties props) { - init(null, props); - } - - /** - * Start the LayerHandler, and have it create all the layers as defined in a - * properties file. - * - * @param prefix the prefix for the layers and startUpLayers properties, as - * if they are listed as prefix.layers, and prefix.startUpLayers. - * @param props properties as defined in an openmap.properties file. - */ - public LayerHandler(String prefix, Properties props) { - init(prefix, props); - } - - /** - * Start the LayerHandler with configured layers. - */ - public LayerHandler(Layer[] layers) { - init(layers); - } - - /** - * Extension of the OMComponent. If the LayerHandler is created by the - * ComponentFactory (via the PropertyHandler), this method will be called - * automatically. For the OpenMap applications, this method is rigged to - * handle the openmap.layers property by calling init("openmap", props). If - * you are using the LayerHandler in a different setting, then you might - * want to just call init() directly, or extend this class and have - * setProperties do what you want. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - // Whoa! We used to replace the prefix provided to this method with - // 'openmap', - // AKA Environment.OpenMapPrefix, but that seems rude and hackish. We're - // going to have the getLayers(prefix, props) method use the prefix - // passed in, and if the layerHandler prefix.layers can't be found, - // we'll revert to looking for the openmap.layers property, just to be - // backward compatible. - // init(Environment.OpenMapPrefix, props); - init(prefix, props); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a - * properties object. The properties should be created from an - * openmap.properties file. - * - * @param prefix the prefix to use for the layers and startUpLayers - * properties. - * @param props properties as defined in an openmap.properties file. - */ - public void init(String prefix, Properties props) { - prefix = PropUtils.getScopedPropertyPrefix(prefix); - init(getLayers(prefix, props)); - - getListeners().setSynchronous(PropUtils.booleanFromProperties(props, prefix - + SynchronousThreadingProperty, getListeners().isSynchronous())); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a URL - * containing an openmap.properties file. - * - * @param url a url for a properties file. - */ - public void init(java.net.URL url) { - init(null, url); - } - - /** - * Initialize the LayerHandler by having it construct it's layers from a URL - * containing an openmap.properties file. - * - * @param prefix the prefix to use for the layers and startUpLayers - * properties. - * @param url a url for a properties file. - */ - public void init(String prefix, java.net.URL url) { - try { - java.io.InputStream in = url.openStream(); - Properties props = new Properties(); - props.load(in); - init(getLayers(prefix, props)); - } catch (java.net.MalformedURLException murle) { - logger.warning("LayerHandler.init(URL): " + url + " is not a valid URL"); - } catch (java.io.IOException e) { - logger.warning("LayerHandler.init(URL): Caught an IOException"); - } - } - - /** - * Initialize from an array of layers. This will cause the LayerListeners, - * if they exist, to update themselves with the current list of layers. This - * will check to add layers to the MapHandler. - * - * @param layers the initial array of layers. - */ - public void init(Layer[] layers) { - init(Arrays.asList(layers)); - } - - public void init(List layers) { - // Should get rid of the old layers properly, holding onto - // non-removeable layers. - removeAll(); - - // OK, we need to check the allLayers array, because at this point it - // could still be holding non-removable layers. If we just replace them, - // we've broken the contract of non-removal. Move the non-removable - // layers to the bottom and put the new layers on top. We also need to - // check to make sure that any duplicate layers on either list are - // parsed down to one layer. We use the Vector.contains() method for - // that check. - List currentLayers = getLayerList(); - - if (layers == null) { - layers = new ArrayList(); - } - - // Go through the list of old-non-removable layers, if they are not on - // the new layer list, add them to the end. - for (Layer layer : currentLayers) { - if (!layers.contains(layer) || !layer.isRemovable()) { - layers.add(layer); - } - } - - setLayerList(layers); - - // This should work for layers being reloaded from the PropertyHandler, - // it's better than doing it in the getLayers(...) method below - // (getLayers() is called before init()). For the - // initial LayerHandler construction and Layer creation in an - // application, the BeanContext should be null at this point, so this - // method call will do nothing. But for resetting the layers with new - // ones, they will get dumped into the BeanContext/MapHandler. - addLayersToBeanContext(layers); - } - - public void setPropertyHandler(PropertyHandler ph) { - propertyHandler = ph; - } - - public PropertyHandler getPropertyHandler() { - return propertyHandler; - } - - /** - * This is the method that gets used to parse the layer properties from an - * openmap.properties file, where the layer marker names are listed under a - * layers property, and each layer is then represented by a marker.class - * property, and a maker.prettyName property. - * - * @param p properties containing layers property, the startupLayers - * property listing the layers to make visible immediately, and the - * layer properties as well. - * @return Layer[] of layers created from the properties. - */ - protected Layer[] getLayers(Properties p) { - return getLayers(null, p); - } - - /** - * This is the method that gets used to parse the layer properties from an - * openmap.properties file, where the layer marker names are listed under a - * prefix.layers property, and each layer is then represented by a - * marker.class property, and a maker.prettyName property. - * - * @param prefix the prefix to use to use for the layer list (layers) - * property and the startUpLayers property. If it is not null, this - * will cause the method to look for prefix.layers and - * prefix.startUpLayers. - * @param p the properties to build the layers from. - * @return Layer[] - */ - protected Layer[] getLayers(String prefix, Properties p) { - logger.fine("Getting new layers from properties..."); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String layersValueString = p.getProperty(prefix + layersProperty); - - String startupLayersValueString = p.getProperty(prefix + startUpLayersProperty); - - if (layersValueString == null) { - layersValueString = p.getProperty(PropUtils.getScopedPropertyPrefix(Environment.OpenMapPrefix) - + layersProperty); - } - - if (startupLayersValueString == null) { - startupLayersValueString = p.getProperty(PropUtils.getScopedPropertyPrefix(Environment.OpenMapPrefix) - + startUpLayersProperty); - } - - Vector startuplayers = PropUtils.parseSpacedMarkers(startupLayersValueString); - Vector layersValue = PropUtils.parseSpacedMarkers(layersValueString); - - if (startuplayers.isEmpty()) { - logger.info("No layers on startup list"); - } - - if (layersValue.isEmpty()) { - logger.info("No property \"" + layersProperty + "\" found in properties."); - return new Layer[0]; - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer markers found = " + layersValue); - } - } - - Layer[] layers = getLayers(layersValue, startuplayers, p); - - // You don't want to call addLayersToBeanContext here, it sets up a - // cycle. The layers are not yet set in the LayerHandler, so the - // LayerHandle won't know to ignore them when they show up in - // findAndInit(). The one thing this call did, however, is get the - // BeanContext to the layers before the startup layers were added to the - // MapBean. It's possible that without this call, layers that build - // their OMGraphicLists once may not have the BeanContext resources they - // need in order to build that list. - - // addLayersToBeanContext(layers); - - return layers; - } - - /** - * A static method that lets you pass in a Properties object, along with two - * Vectors of strings, each Vector representing marker names for layers - * contained in the Properties. - *

- * If a PlugIn is listed in the properties, the LayerHandler will create a - * PlugInLayer for it and set the PlugIn in that layer. - * - * @param layerList Vector of marker names to use to inspect the properties - * with. - * @param visibleLayerList Vector of marker names representing the layers - * that should initially be set to visible when created, so that - * those layers are initially added to the map. - * @param p Properties object containing the layers properties. - * @return Layer[] - */ - public static Layer[] getLayers(Vector layerList, Vector visibleLayerList, - Properties p) { - - int nLayerNames = layerList.size(); - Vector layers = new Vector(nLayerNames); - - for (String layerName : layerList) { - String classProperty = layerName + ".class"; - String className = p.getProperty(classProperty); - if (className == null) { - logger.info("Failed to locate property \"" + classProperty - + "\"\n Skipping layer \"" + layerName + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, layerName, p); - Layer l; - - if (obj instanceof Layer) { - l = (Layer) obj; - } else if (obj instanceof PlugIn) { - - PlugInLayer pl = new PlugInLayer(); - pl.setProperties(layerName, p); - pl.setPlugIn((PlugIn) obj); - l = pl; - } else { - logger.info("Skipped \"" - + layerName - + "\" " - + (obj == null ? " - unable to create " : ", type " - + obj.getClass().getName() + " is not a layer or plugin")); - continue; - } - - // Figure out of the layer is on the startup list, - // and make it visible if it is... - l.setVisible(visibleLayerList.contains(layerName)); - // The ComponentFactory does this now - // l.setProperties(layerName, p); - - layers.addElement(l); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + l.getName() - + (l.isVisible() ? " is visible" : " is not visible")); - } - } - - int nLayers = layers.size(); - if (nLayers == 0) { - return new Layer[0]; - } else { - Layer[] value = new Layer[nLayers]; - layers.copyInto(value); - return value; - } - } - - /** - * Add a LayerListener to the LayerHandler, in order to be told about layers - * that need to be added to the map. The new LayerListener will receive two - * events, one telling it all the layers available, and one telling it which - * layers are active (visible). - * - * @param ll LayerListener, usually the MapBean or other GUI components - * interested in providing layer controls. - */ - public void addLayerListener(LayerListener ll) { - logger.fine("adding layer listener"); - listeners.add(ll); - // Usually, the listeners are interested in one type of event - // or the other. So fire both, and let the listener hash it - // out. - ll.setLayers(new LayerEvent(this, LayerEvent.ALL, getLayers())); - ll.setLayers(new LayerEvent(this, LayerEvent.ADD, getMapLayers())); - } - - /** - * Add a LayerConfigurationListener, so a component can make adjustments to - * new layer configurations before they get sent to the map. - * - * @param lcl LayerConfigurationListener - */ - public void addLayerConfigurationListener(LayerConfigurationListener lcl) { - layerConfigListeners.add(lcl); - } - - /** - * Add a LayerListener to the LayerHandler, in order to be told about layers - * that need to be added to the map. - * - * @param ll LayerListener, usually the MapBean or other GUI components - * interested in providing layer controls. - */ - public void removeLayerListener(LayerListener ll) { - if (listeners != null) { - listeners.remove(ll); - } - } - - /** - * Remove a LayerConfigurationListener. - * - * @param lcl LayerConfigurationListener - */ - public void removeLayerConfigurationListener(LayerConfigurationListener lcl) { - layerConfigListeners.remove(lcl); - } - - /** - * Set all the layers held by the LayerHandler. The visible layers will be - * sent to listeners interested in visible layers (LayerEvent.REPLACE), and - * the list of all layers will be sent to listeners interested in - * LayerEvent.ALL events. Calling this method from other GUI components - * could break the non-removable contract that previous layers had. The - * previous layers aren't checked against this list to insure that - * non-removable layers are still on this list and visible. GUI components - * that may call this need to set up their GUI controls to not allow - * non-removable layers to be eliminated from the application. - *

- *

- * This method will not add the layers to the MapHandler, so you can call - * this if you know the layers are already in the MapHandler or don't need - * to be. If you want layers to be added to the MapHandler (if the - * LayerHandler knows about it), call init(Layer[]) instead. - *

- *

- * Also, this method will disregard layer non-removable status for any - * layers currently held, and will simply replace all layers with the ones - * provided. If you want the non-removable flag to be adhered to, call - * init(Layers[]). - * - * @param layers Layer array of all the layers to be held by the - * LayerHandler. - */ - public synchronized void setLayers(Layer[] layers) { - setLayerList(Arrays.asList(layers)); - } - - public synchronized void setLayerList(List layers) { - List localAllLayers = organizeBackgroundLayers(layers); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("setting layers: " + getLayerNamesFromArray(layers)); - } - - // I think this is where we need to make the call to - // LayerConfigurationListeners to check the status of the layer cake, so - // they can make appropriate changes before the LayerListeners get da - // layers. - - List checkedList = layerConfigListeners.checkLayerConfiguration(new ArrayList(localAllLayers)); - if (checkedList != null) { - localAllLayers = organizeBackgroundLayers(checkedList); - } - - allLayers = localAllLayers; - - getListeners().pushLayerEvent(LayerEvent.ALL, getLayers()); - getListeners().pushLayerEvent(LayerEvent.REPLACE, getMapLayers()); - } - - protected String getLayerNamesFromArray(List lArray) { - StringBuilder buf = new StringBuilder(); - if (lArray != null) { - for (Layer l : lArray) { - if (buf.length() > 0) { - buf.append(" "); - } - buf.append(l.getName()); - } - } - return buf.toString(); - } - - /** - * Checks to see if there are background layers on top of foreground layers. - * - * @param layers - * @return true if background layers need to be pushed down - */ - protected boolean isForegroundUnderBackgroundLayer(List layers) { - boolean foundBackgroundLayer = false; - if (layers != null) { - for (Layer layer : layers) { - if (layer != null) { - if (layer.getAddAsBackground()) { - foundBackgroundLayer = true; - } else if (foundBackgroundLayer) { - return true; - } - } - } - } - - return false; - } - - /** - * Does the check to see of foreground layers are below background layers, - * and then iterates through the Layer[] switching layers around until they - * are in the appropriate order. - * - * @param layers - * @return Layer[] of layers with background layers moved to back. - */ - protected List organizeBackgroundLayers(List layers) { - if (isForegroundUnderBackgroundLayer(layers)) { - - List fLayers = new ArrayList(layers.size()); - List bLayers = new ArrayList(layers.size()); - - for (Layer layer : layers) { - if (layer != null) { - if (layer.getAddAsBackground()) { - bLayers.add(layer); - } else { - fLayers.add(layer); - } - } - } - - // Append all background layers behind foreground layers. - fLayers.addAll(bLayers); - return fLayers; - - } else { - return layers; - } - } - - /** - * Returns the object responsible for holding on to objects listening to - * layer changes. - * - * @return LayerSupport containing pointers to all objects interested in the - * status (order, visibility) of the available layers. - */ - protected LayerSupport getListeners() { - return listeners; - } - - /** - * If you are futzing with the layer visibility outside the purview of the - * LayerHandler (not using the turnLayerOn() methods) then you can call this - * to get all the listeners using the current set of visible layers. - */ - public void setLayers() { - setLayerList(getLayerList()); - } - - /** - * Get a layer array, of potential layers that CAN be added to the map, not - * the ones that are active on the map. A new array is returned, containing - * the current layers. - * - * @return new Layer[] containing new layers. - */ - public synchronized Layer[] getLayers() { - List layers = getLayerList(); - return layers.toArray(new Layer[layers.size()]); - } - - /** - * Returns a copy of the List of all the available layers. - * - * @return List of Layers - */ - public synchronized List getLayerList() { - if (allLayers == null) { - return new ArrayList(); - } else { - return new ArrayList(allLayers); - } - } - - /** - * Get the layers that are currently part of the Map - the ones that are - * visible. - * - * @return an Layer[] of visible Layers. - */ - public Layer[] getMapLayers() { - - List activeLayers = new ArrayList(); - - for (Layer layer : getLayers()) { - if (layer != null && layer.isVisible()) { - activeLayers.add(layer); - } - } - - Layer[] cake = activeLayers.toArray(new Layer[activeLayers.size()]); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("providing map layers: " + getLayerNamesFromArray(activeLayers)); - } - - return cake; - } - - /** - * Move a layer to a certain position. Returns true if the layer exists in - * the LayerHandler, false if is doesn't. No action is taken if the layer - * isn't already added to the LayerHandler stack. If the position is 0 or - * less the layer is moved on top. If the position is greater or equal to - * the number of layers, the layer is moved to the bottom of the pile. - * - * @param layer the layer to move. - * @param toPosition the array index to place it, shifting the other layers - * up or down, depending on where the layer is originally. - * @return true if the layer is already contained in the LayerHandler, false - * if not. - */ - public boolean moveLayer(Layer layer, int toPosition) { - boolean found = getLayerList().contains(layer); - addLayer(layer, toPosition); - - return found; - } - - /** - * Add a layer to the bottom of the layer stack. If the layer is already - * part of the layer stack, nothing is done. - * - * @param layer the layer to add. - */ - public void addLayer(Layer layer) { - if (allLayers == null) { - addLayer(layer, 0); - return; - } - - if (!allLayers.contains(layer)) { - allLayers.add(layer); - } - } - - /** - * Add a layer to a certain position in the layer array. If the position is - * 0 or less, the layer is put up front (on top). If the position is greater - * than the length of the current array, the layer is put at the end, (on - * the bottom). A Layer can only be added once. If you add a layer that is - * already added to the LayerHandler, it will be moved to the requested - * position. - * - * @param layer the layer to add. - * @param position the array index to place it. - */ - public void addLayer(Layer layer, int position) { - // Working copy - List currentLayers = getLayerList(); - - // If it is already part of the list, we're going to move it to the new - // position. Remove it from the current position. If it's not on the - // list this call is a NO-OP. - currentLayers.remove(layer); - - if (position > allLayers.size()) { - currentLayers.add(layer); - } else { - if (position < 0) { - position = 0; - } - currentLayers.add(position, layer); - } - - if (propertyHandler != null) { - String pre = layer.getPropertyPrefix(); - if (pre != null && pre.length() > 0) { - propertyHandler.addUsedPrefix(pre); - } - } - - // Need to make this call before thinking about adding the Layer to the - // BeanContext, so when the Layer shows up in the findAndInit() method, - // it's already a part of the Layer list. One potential problem that may - // occur is that the Layer might not be ready to be added to the map and - // to other application components that get LayerEvents from the - // LayerHandler, and they will all know about the layer being in the - // stack after the setLayers() call. - setLayerList(currentLayers); - - // Add the layer to the BeanContext, if it wants to be and it's not - // already in a BeanContext. Thought about making the BC check look for - // the same BC as the LayerHandler is a part of, but it's probably - // better just to do a null check in case the Layer is a member of a - // more restricted BeanContext with limited access. - BeanContext bc = getBeanContext(); - if (bc != null && layer.getAddToBeanContext() && layer.getBeanContext() == null) { - bc.add(layer); - } - } - - /** - * Remove a layer from the list of potentials. - * - * @param layer to remove. - */ - public void removeLayer(Layer layer) { - if (layer != null && layer.isRemovable()) { - List currentLayers = getLayerList(); - currentLayers.remove(layer); - setLayerList(currentLayers); - } else { - if (layer != null) { - logger.warning("received command to remove " + layer.getName() - + ", which has been designated as *NOT* removeable"); - throw new com.bbn.openmap.util.HandleError("LayerHandler commanded to delete a layer (" - + layer.getName() + ") that is not removeable"); - } - } - } - - /** - * Remove a layer from the list of potentials. - * - * @param index of layer in the layer array. Top-most is first. - */ - public void removeLayer(int index) { - List currentLayers = getLayerList(); - try { - currentLayers.remove(index); - setLayerList(currentLayers); - } catch (IndexOutOfBoundsException ioobe) { - // ignore it. - } - } - - public boolean hasLayer(Layer l) { - return getLayerList().contains(l); - } - - /** - * Remove all the layers (that are marked as removable). - */ - public void removeAll() { - List oldLayers = getLayerList(); - if (allLayers == null || allLayers.isEmpty()) { - return; - } - - BeanContext bc = getBeanContext(); - List nonRemoveableLayers = new ArrayList(); - - for (Layer layer : oldLayers) { - if (layer != null) { - if (layer.isRemovable()) { - turnLayerOn(false, layer); - layer.clearListeners(); - if (bc != null) { - // Remove the layer from the BeanContext - bc.remove(layer); - } - } else { - nonRemoveableLayers.add(layer); - } - } - } - - setLayerList(nonRemoveableLayers); - - // I know this is bad but it seems to work, forcing the - // memory from old, deleted layers to be freed. With such a - // drastic method call as removeAll, this should be OK. - System.gc(); - } - - /** - * The version that does the work. The other two functions do sanity checks. - * Calls setLayers(), and removes the layer from the BeanContext. - * - * @param currentLayers the current layers handled in the LayersMenu. - * @param index the validated index of the layer to remove. - */ - protected void removeLayer(Layer[] currentLayers, int index) { - Layer rLayer = currentLayers[index]; - - if (!rLayer.isRemovable()) { - logger.warning("received command to remove " + rLayer.getName() - + ", which has been designated as *NOT* removeable"); - return; - } - - rLayer.setVisible(false); - - Layer[] newLayers = new Layer[currentLayers.length - 1]; - System.arraycopy(currentLayers, 0, newLayers, 0, index); - System.arraycopy(currentLayers, index + 1, newLayers, index, currentLayers.length - index - - 1); - - // Remove the layer to the BeanContext, if it wants to be. - BeanContext bc = getBeanContext(); - if (bc != null) { - bc.remove(rLayer); - } - turnLayerOn(false, rLayer); - rLayer.clearListeners(); - rLayer = null; - - // Shouldn't call this, but it's the only thing that seems to - // make it work... - // if (Debug.debugging("helpgc")) { - // System.gc(); - // } - - setLayers(newLayers); - } - - /** - * Take a layer that the LayersMenu knows about, that may or may not be a - * part of the map, and change its visibility by adding/removing it from the - * MapBean. - * - * @param setting true to add layer to the map. - * @param index the index of the layer to turn on/off. - * @return true of index represented a layer, false if not or if something - * went wrong. - */ - public boolean turnLayerOn(boolean setting, int index) { - try { - return turnLayerOn(setting, getLayerList().get(index)); - } catch (ArrayIndexOutOfBoundsException aoobe) { - // Do nothing... - } catch (NullPointerException npe) { - // Do nothing... - } - return false; - } - - /** - * Take a layer that the LayersMenu knows about, that may or may not be a - * part of the map, and change its visibility by adding/removing it from the - * MapBean. If the layer is not found, it's added and the visibility depends - * on the setting parameter. - * - * @param setting true to add layer to the map. - * @param layer the layer to turn on. - * @return true if the layer was found, false if not or if something went - * wrong. - */ - public boolean turnLayerOn(boolean setting, Layer layer) { - - if ((setting && !layer.isVisible()) || (!setting && layer.isVisible())) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("turning " + layer.getName() + (setting ? " on" : " off")); - } - - layer.setVisible(setting); - - List newList = layerConfigListeners.checkLayerConfiguration(getLayerList()); - if (newList != null) { - allLayers = organizeBackgroundLayers(newList); - } - - getListeners().pushLayerEvent(LayerEvent.REPLACE, getMapLayers()); - return true; - } - return false; - } - - /** - * Called from childrenAdded(), when a new component is added to the - * BeanContext, and from setBeanContext() when the LayerHandler is initially - * added to the BeanContext. This method takes the iterator provided when - * those methods are called, and looks for the objects that the LayerHandler - * is interested in, namely, the MapBean, the PropertyHandler, or any other - * LayerListeners. The LayerHandler handles multiple LayerListeners, and if - * one is found, it is added to the LayerListener list. If a PropertyHandler - * is found, then init() is called, effectively resetting the layers held by - * the LayerHandler. - * - * @param someObj an Object being added to the MapHandler/BeanContext. - */ - public void findAndInit(Object someObj) { - - if (someObj instanceof LayerListener) { - logger.fine("LayerHandler found a LayerListener."); - addLayerListener((LayerListener) someObj); - } - - if (someObj instanceof LayerConfigurationListener) { - logger.fine("LayerHandler found a LayerConfigurationListener."); - addLayerConfigurationListener((LayerConfigurationListener) someObj); - } - - if (someObj instanceof Layer) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerHandler found a Layer |" + ((Layer) someObj).getName() + "|" - + someObj.getClass().getName()); - } - if (!hasLayer((Layer) someObj)) { - addLayer((Layer) someObj, 0); - } - } - - if (someObj instanceof PlugIn) { - PlugIn pi = (PlugIn) someObj; - if (pi.getComponent() == null) { - PlugInLayer pil = new PlugInLayer(); - pil.setPlugIn(pi); - addLayer(pil, 0); - } - } - - if (someObj instanceof PropertyHandler) { - // Used to notify the PropertyHandler of used property - // prefix names. - setPropertyHandler((PropertyHandler) someObj); - } - } - - /** - * A BeanContextMembershipListener interface method, which is called when - * new objects are removed from the BeanContext. If a LayerListener or Layer - * is found on this list, it is removed from the list of LayerListeners. - * - * @param someObj an Object being removed from the MapHandler/BeanContext. - */ - public void findAndUndo(Object someObj) { - - if (someObj instanceof LayerListener) { - logger.fine("LayerListener object is being removed"); - removeLayerListener((LayerListener) someObj); - } - - if (someObj instanceof LayerConfigurationListener) { - logger.fine("LayerConfigurationListener is being removed."); - removeLayerConfigurationListener((LayerConfigurationListener) someObj); - } - - if (someObj instanceof Layer) { - removeLayer((Layer) someObj); - } - - if (someObj instanceof PlugIn) { - PlugIn pi = (PlugIn) someObj; - Component comp = pi.getComponent(); - if (comp instanceof Layer && hasLayer((Layer) comp)) { - removeLayer((Layer) comp); - } - } - - if (someObj instanceof PropertyHandler && someObj == getPropertyHandler()) { - setPropertyHandler(null); - } - } - - /** - * Add layers to the BeanContext, if they want to be. Since the BeanContext - * is a Collection, it doesn't matter if a layer is already there because - * duplicates aren't allowed. - * - * @param layers layers to add, if they want to be. - */ - public void addLayersToBeanContext(List layers) { - BeanContext bc = getBeanContext(); - if (bc == null || layers == null) { - return; - } - - for (Layer layer : layers) { - if (layer.getAddToBeanContext() && layer.getBeanContext() == null) { - bc.add(layer); - } - } - } - - /** - * Add layers to the BeanContext, if they want to be. Since the BeanContext - * is a Collection, it doesn't matter if a layer is already there because - * duplicates aren't allowed. - * - * @param layers layers to add, if they want to be. - */ - public void removeLayersFromBeanContext(List layers) { - BeanContext bc = getBeanContext(); - if (bc == null || layers == null) { - return; - } - - for (Layer layer : layers) { - bc.remove(layer); - } - } - - /** - * Called when the LayerHandler is added to a BeanContext. This method calls - * findAndInit() to hook up with any objects that may already be added to - * the BeanContext. A BeanContextChild method. - * - * @param in_bc BeanContext. - */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - if (in_bc != null) { - logger.fine("setting bean context"); - in_bc.addBeanContextMembershipListener(this); - beanContextChildSupport.setBeanContext(in_bc); - - // This will cause findAndInit to be called on the layers and - // plugins after they are added to the MapHandler, so they can find - // the components they need before they get added to the - // map (if they are to be added at startup). - addLayersToBeanContext(getLayerList()); - - // Calling this here may (will) cause the MapBean to get - // loaded with its initial layers, since it is a - // LayerListener. - findAndInit(in_bc.iterator()); - } - } - - public void setSynchronousThreading(boolean s) { - getListeners().setSynchronous(s); - } - - public boolean isSynchronousThreading() { - return getListeners().isSynchronous(); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - props.put(PropUtils.getScopedPropertyPrefix(this) + SynchronousThreadingProperty, Boolean.toString(getListeners().isSynchronous())); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String internString = i18n.get(LayerHandler.class, SynchronousThreadingProperty, I18n.TOOLTIP, "Launch new threads to do work."); - props.put(SynchronousThreadingProperty, internString); - internString = i18n.get(LayerHandler.class, SynchronousThreadingProperty, "Synchronous Threading"); - props.put(SynchronousThreadingProperty + LabelEditorProperty, internString); - props.put(SynchronousThreadingProperty + EditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/MapBean.java b/src/openmap/com/bbn/openmap/MapBean.java deleted file mode 100644 index c7c494bb1..000000000 --- a/src/openmap/com/bbn/openmap/MapBean.java +++ /dev/null @@ -1,1780 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/MapBean.java,v $ -// $RCSfile: MapBean.java,v $ -// $Revision: 1.23 $ -// $Date: 2009/02/05 18:46:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.ContainerEvent; -import java.awt.event.ContainerListener; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JComponent; -import javax.swing.OverlayLayout; - -import com.bbn.openmap.event.CenterEvent; -import com.bbn.openmap.event.CenterListener; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.event.PaintListener; -import com.bbn.openmap.event.PaintListenerSupport; -import com.bbn.openmap.event.PanEvent; -import com.bbn.openmap.event.PanListener; -import com.bbn.openmap.event.ProjectionChangeVetoException; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.event.ProjectionSupport; -import com.bbn.openmap.event.ZoomEvent; -import com.bbn.openmap.event.ZoomListener; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * The MapBean is the main component of the OpenMap Development Kit. It is a - * Java Bean that manages and displays a map. A map is comprised of a projection - * and a list of layers, and this class has methods that allow you to control - * the projection parameters and to add and remove layers. Layers that are part - * of the map receive dynamic notifications of changes to the underlying view - * and projection. - *

- * Most of the methods in the MapBean are called from the Java AWT and Swing - * code. These methods make the MapBean a good "Swing citizen" to its parent - * components, and you should not need to invoke them. In general there are only - * two reasons to call MapBean methods: controlling the projection, and adding - * or removing layers. - *

- * When controlling the MapBean projection, simply call the method that applies - * - setCenter, pan, zoom, etc. NOTE: If you are setting more than one parameter - * of the projection, it's more efficient to getProjection(), directly set the - * parameters of the projection object, and then call setProjection() with the - * modified projection. That way, each ProjectionListener of the MapBean (each - * layer) will only receive one projectionChanged() method call, as opposed to - * receiving one for each projection adjustment. - *

- * To add or remove layers, use the add() and remove() methods that the MapBean - * inherits from java.awt.Container. The add() method can be called with an - * integer that indicates its desired position in the layer list. - *

- * Changing the default clipping area may cause some Layers to not be drawn - * completely, depending on what the clipping area is set to and when the layer - * is trying to get itself painted. When manually adjusting clipping area, make - * sure that when restricted clipping is over that a full repaint occurs if - * there is a chance that another layer may be trying to paint itself. - *

- * PropertyChangeListeners and ProjectionListeners both receive notifications of - * the projection changes, but the PropertyChangeListeners receive them first. - * If you want to have a component that limits the MapBean's projection - * parameters, it should be a PropertyChangeListener on the MapBean, and throw a - * ProjectionChangeVetoException whenever a Projection setting falls outside of - * the limits. The ProjectionChangeVetoException should hold the alternate - * settings allowed by the listener. When a ProjectionChangeVetoException is - * thrown, all of the PropertyChangeListeners will receive another - * PropertyChangeEvent notification, under the MapBean.projectionVetoed property - * name. The old value for that property will be the rejected Projection object, - * and the new value will be the ProjectionChangeVetoException containing the - * new suggestions. The MapBean will then apply the suggestions and launch - * another round of projection change notifications. The ProjectionListeners - * only receive notification of Projections that have passed through the - * PropertyChangeListeners. - * - * @see Layer - */ -public class MapBean extends JComponent - implements ComponentListener, ContainerListener, ProjectionListener, PanListener, - ZoomListener, LayerListener, CenterListener, SoloMapComponent { - - private static Logger logger = Logger.getLogger(MapBean.class.getName()); - - public static final String LayersProperty = "MapBean.layers"; - - public static final String CursorProperty = "MapBean.cursor"; - - public static final String BackgroundProperty = "MapBean.background"; - - public static final String ProjectionProperty = "MapBean.projection"; - - public static final String ProjectionVetoedProperty = "MapBean.projectionVetoed"; - - /** - * OpenMap title. - */ - public static final String title = "OpenMap(tm)"; - - /** - * OpenMap version. - */ - public static final String version = "5.1.15"; - - /** - * Suppress the copyright message on initialization. - */ - public static boolean suppressCopyright = false; - - private static boolean DEBUG_TIMESTAMP = false; - - private static boolean DEBUG_THREAD = true; - - private static final String copyrightNotice = "OpenMap(tm) Version " + version + "\r\n" - + " Copyright (C) BBNT Solutions LLC. All rights reserved.\r\n" - + " See http://openmap-java.org/ for details.\r\n"; - - public final static float DEFAULT_CENTER_LAT = 0.0f; - - public final static float DEFAULT_CENTER_LON = 0.0f; - - // zoomed all the way out - public final static float DEFAULT_SCALE = Float.MAX_VALUE; - - public final static int DEFAULT_WIDTH = 640; - - public final static int DEFAULT_HEIGHT = 480; - - protected int minHeight = 100; - - protected int minWidth = 100; - - protected Proj projection = new Mercator(new LatLonPoint.Double(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON), DEFAULT_SCALE, DEFAULT_WIDTH, DEFAULT_HEIGHT); - - protected final ProjectionSupport projectionSupport; - - /** - * Layers that are removed from the MapBean are held until the next - * projection change. When the projection changes, they are notified that - * they have been removed from the map. This list is kept so that toggling a - * layer on and off won't cause them to get rid of their resources, in case - * the user is just creating different views of the map. - */ - protected final Vector removedLayers = new Vector(0); - - /** - * Some users may want the layers deleted immediately when they are removed - * from the map. This flag controls that. The default behavior is to hold a - * reference to a layer and actually release it when the projection changes - * (default = true). Set to false if you want the MapBean to tell a Layer it - * has been removed immediately when it happens. - */ - protected boolean layerRemovalDelayed = true; - - /** - * This vector is to let the layers know when they have been added to the - * map. - */ - protected final Vector addedLayers = new Vector(0); - - /** - * The PaintListeners want to know when the map has been repainted. - */ - protected final PaintListenerSupport painters; - - /** - * The background color for this particular MapBean. If null, the setting - * for the projection, which in turn is set in the Environment class, will - * be used. - */ - protected Paint background = null; - - /** - * The MapBeanRepaintPolicy to use to handler/filter/pace layer repaint() - * requests. If not set, a StandardMapBeanRepaintPolicy will be used, which - * forwards repaint requests to Swing normally. - */ - protected MapBeanRepaintPolicy repaintPolicy = null; - /** - * The angle, in radians, to rotate the map. 0.0 is north-up, clockwise is - * positive. - */ - protected double rotationAngle = 0; - - public final static Color DEFAULT_BACKGROUND_COLOR = new Color(191, 239, 255); - - /** - * Return the OpenMap Copyright message. - * - * @return String Copyright - */ - public static String getCopyrightMessage() { - return copyrightNotice; - } - - /** - * Construct a MapBean. - */ - public MapBean() { - this(true); - } - - public MapBean(boolean useThreadedNotification) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean()"); - } - if (!suppressCopyright) { - Debug.output(copyrightNotice); - } - - background = DEFAULT_BACKGROUND_COLOR; - - // Don't need one for every MapBean, just the first one. - suppressCopyright = true; - - super.setLayout(new OverlayLayout(this)); - projectionSupport = new ProjectionSupport(this, useThreadedNotification); - addComponentListener(this); - addContainerListener(this); - - painters = new PaintListenerSupport(this); - - // ---------------------------------------- - // In a builder tool it seems that the OverlayLayout - // makes the MapBean fail to resize. And since it has - // no children by default, it has no size. So I add - // a null Layer here to give it a default size. - // ---------------------------------------- - if (java.beans.Beans.isDesignTime()) { - add(new Layer() { - public void projectionChanged(ProjectionEvent e) { - } - - public Dimension getPreferredSize() { - return new Dimension(100, 100); - } - }); - } - - setPreferredSize(new Dimension(projection.getWidth(), projection.getHeight())); - - DEBUG_TIMESTAMP = logger.isLoggable(Level.FINER); - DEBUG_THREAD = logger.isLoggable(Level.FINER); - } - - /** - * Return a string-ified representation of the MapBean. - * - * @return String representing mapbean. - */ - public String toString() { - return getClass().getName() + "@" + Integer.toHexString(hashCode()); - } - - /** - * Call when getting rid of the MapBean, it releases pointers to all - * listeners and kills the ProjectionSupport thread. - */ - public void dispose() { - setLayerRemovalDelayed(false); - - projectionSupport.dispose(); - painters.clear(); - addedLayers.removeAllElements(); - - currentLayers = null; - projectionFactory = null; - - removeComponentListener(this); - removeContainerListener(this); - removeAll(); - purgeAndNotifyRemovedLayers(); - } - - /*---------------------------------------------------------------------- - * Window System overrides - *----------------------------------------------------------------------*/ - - /** - * Adds additional constraints on possible children components. The new - * component must be a Layer. This method included as a good container - * citizen, and should not be called directly. Use the add() methods - * inherited from java.awt.Container instead. - * - * @param comp Component - * @param constraints Object - * @param index int location - */ - protected final void addImpl(Component comp, Object constraints, int index) { - if (comp instanceof Layer) { - super.addImpl(comp, constraints, index); - } else { - throw new IllegalArgumentException("only Layers can be added to a MapBean"); - } - } - - /** - * Prevents changing the LayoutManager. Don't let anyone change the - * LayoutManager! This is called by the parent component and should not be - * called directly. - */ - public final void setLayout(LayoutManager mgr) { - throw new IllegalArgumentException("cannot change layout of Map"); - } - - /** - * Return the minimum size of the MapBean window. Included here to be a good - * citizen. - */ - public Dimension getMinimumSize() { - return new Dimension(minWidth, minHeight); - } - - /** - * Set the minimum size of the MapBean window. Included here to be a good - * citizen. - */ - public void setMinimumSize(Dimension dim) { - minWidth = (int) dim.getWidth(); - minHeight = (int) dim.getHeight(); - } - - /** - * Get the Insets of the MapBean. This returns 0-length Insets. - *

- * This makes sure that there will be no +x,+y offset when drawing graphics. - * This is ok since any borders around the MapBean will get drawn afterwards - * on top. - * - * @return Insets 0-length Insets - */ - public final Insets getInsets() { - return insets; - } - - private final transient static Insets insets = new Insets(0, 0, 0, 0); - - /*---------------------------------------------------------------------- - * ComponentListener implementation - *----------------------------------------------------------------------*/ - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been resized, and kicks off a projection - * change. - * - * @param e ComponentEvent - */ - public void componentResized(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Size changed: " + getWidth() + " x " + getHeight()); - } - - projection.setWidth(getWidth()); - projection.setHeight(getHeight()); - fireProjectionChanged(); - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been moved. - * - * @param e ComponentEvent - */ - public void componentMoved(ComponentEvent e) { - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been shown. - * - * @param e ComponentEvent - */ - public void componentShown(ComponentEvent e) { - } - - /** - * ComponentListener interface method. Should not be called directly. - * Invoked when component has been hidden. - * - * @param e ComponentEvent - */ - public void componentHidden(ComponentEvent e) { - } - - /*---------------------------------------------------------------------- - * - *----------------------------------------------------------------------*/ - - /** - * Add a ProjectionListener to the MapBean. You do not need to call this - * method to add layers as ProjectionListeners. This method is called for - * the layer when it is added to the MapBean. Use this method for other - * objects that you want to know about the MapBean's projection. - * - * @param l ProjectionListener - */ - public synchronized void addProjectionListener(ProjectionListener l) { - projectionSupport.add(l); - // Assume that it wants the current projection - try { - l.projectionChanged(new ProjectionEvent(this, getRotatedProjection())); - } catch (Exception e) { - if (logger.isLoggable(Level.FINER)) { - logger.fine("ProjectionListener not handling projection well: " - + l.getClass().getName() + " : " + e.getClass().getName() + " : " - + e.getMessage()); - e.printStackTrace(); - } - } - } - - /** - * Remove a ProjectionListener from the MapBean. You do not need to call - * this method to remove layers that are ProjectionListeners. This method is - * called for the layer when it is removed from the MapBean. Use this method - * for other objects that you want to remove from receiving projection - * events. - * - * @param l ProjectionListener - */ - public synchronized void removeProjectionListener(ProjectionListener l) { - projectionSupport.remove(l); - } - - /** - * Called from within the MapBean when its projection listeners need to know - * about a projection change. - */ - protected void fireProjectionChanged() { - - // This handles setting up the RotationHelper if it's needed. - Projection proj = getRotatedProjection(); - - // Fire the property change, so the messages get cleared out. - // Then, if any of the layers have a problem with their new - // projection, their messages will be displayed. - if (logger.isLoggable(Level.FINE)) { - logger.fine("MapBean firing projection: " + proj); - } - try { - firePropertyChange(ProjectionProperty, null, proj); - } catch (ProjectionChangeVetoException pcve) { - firePropertyChange(ProjectionVetoedProperty, proj, pcve); - pcve.updateWithParameters(this); - return; - } - - // Mark the layers as dirty, as a group, before notifying them of a - // projection change. They will mark themselves clean when they call - // repaint. - for (Component c : getComponents()) { - Layer l = (Layer) c; - if (l != null) { - // Weird, I know, but I've seen c be null and throw an - // exception here. - l.setReadyToPaint(false); - } - } - - projectionSupport.fireProjectionChanged(proj); - purgeAndNotifyRemovedLayers(); - } - - /** - * Clear the vector containing all of the removed layers, and let those - * layers know they have been removed from the map. - */ - public void purgeAndNotifyRemovedLayers() { - // Tell any layers that have been removed that they have - // been removed - - ArrayList rLayers = new ArrayList(removedLayers); - removedLayers.clear(); - - if (rLayers.isEmpty()) { - return; - } - for (Layer layer : rLayers) { - layer.removed(this); - } - - // Shouldn't call this, but it's the only thing - // that seems to make it work... - // Seems to help gc'ing layers in a timely manner. - if (Debug.debugging("helpgc")) { - System.gc(); - } - } - - /*---------------------------------------------------------------------- - * Properties - *----------------------------------------------------------------------*/ - - /** - * Gets the scale of the map. - * - * @return float the current scale of the map - * @see Projection#getScale - */ - public float getScale() { - return projection.getScale(); - } - - /** - * Sets the scale of the map. The Projection may silently disregard this - * setting, setting it to a maxscale or minscale - * value. - * - * @param newScale the new scale - * @see Proj#setScale - */ - public void setScale(float newScale) { - projection.setScale(newScale); - fireProjectionChanged(); - } - - /** - * Gets the center of the map in the form of a LatLonPoint. - * - * @return the center point of the map - * @see Projection#getCenter - */ - public Point2D getCenter() { - return projection.getCenter(); - } - - /** - * Sets the center of the map. - * - * @param newCenter the center point of the map - * @see Proj#setCenter(Point2D) - */ - public void setCenter(Point2D newCenter) { - projection.setCenter(newCenter); - fireProjectionChanged(); - } - - /** - * Sets the center of the map. - * - * @param lat the latitude of center point of the map in decimal degrees - * @param lon the longitude of center point of the map in decimal degrees - * @see Proj#setCenter(double, double) - */ - public void setCenter(double lat, double lon) { - projection.setCenter(new Point2D.Double(lon, lat)); - fireProjectionChanged(); - } - - /** - * Sets the center of the map. - * - * @param lat the latitude of center point of the map in decimal degrees - * @param lon the longitude of center point of the map in decimal degrees - * @see Proj#setCenter(double, double) - */ - public void setCenter(float lat, float lon) { - setCenter((double) lat, (double) lon); - } - - /** - * Set the background color of the map. If the background for this MapBean - * is not null, the background of the projection will be used. - * - * @param color java.awt.Color. - */ - public void setBackgroundColor(Color color) { - setBackground(color); - } - - public void setBackground(Color color) { - super.setBackground(color); - setBckgrnd((Paint) color); - } - - /** - * We override this to set the paint mode on the Graphics before the border - * is painted, otherwise we get an XOR effect in the border. - */ - public void paintBorder(Graphics g) { - g.setPaintMode(); - super.paintBorder(g); - } - - /** - * Set the background of the map. If the background for this MapBean is not - * null, the background of the projection will be used. - * - * @param paint java.awt.Paint. - */ - public void setBckgrnd(Paint paint) { - setBufferDirty(true); - - // Instead, do this. - Paint oldBackground = background; - background = paint; - firePropertyChange(BackgroundProperty, oldBackground, background); - - repaint(); - } - - /** - * Get the background color of the map. If the background color for this - * MapBean has been explicitly set, that value will be returned. Otherwise, - * the background color of the projection will be returned. If the - * background is not a color (as opposed to Paint) this method will return - * null. - * - * @return color java.awt.Color. - */ - public Color getBackground() { - Paint ret = getBckgrnd(); - if (ret instanceof Color) { - return (Color) ret; - } - - return super.getBackground(); - } - - /** - * Get the background of the map. If the background for this MapBean has - * been explicitly set, that value will be returned. Otherwise, the - * background of the projection will be returned. - * - * @return color java.awt.Color. - */ - public Paint getBckgrnd() { - Paint ret = background; - if (ret == null) { - ret = super.getBackground(); - } - return ret; - } - - /** - * Get the projection property, reflects the projection with no rotation. - * - * @return current Projection of map. - */ - public Projection getProjection() { - return projection; - } - - /** - * @return the expanded rotated projection if map rotated, normal projection - * if not rotated. The rotated projection is larger than the MapBean - * and has extra offsets. - */ - public Projection getRotatedProjection() { - RotationHelper rotation = getUpdatedRotHelper(); - Projection proj = rotation != null ? rotation.getProjection() : projection; - // Double check - ((Proj) proj).setRotationAngle(getRotationAngle()); - return proj; - } - - /** - * Set the projection. Shouldn't be null, and won't do anything if it is. - * - * @param aProjection Projection - */ - public void setProjection(Projection aProjection) { - if (aProjection != null && !aProjection.getProjectionID().contains("NaN")) { - setBufferDirty(true); - projection = (Proj) aProjection; - setPreferredSize(new Dimension(projection.getWidth(), projection.getHeight())); - fireProjectionChanged(); - } - } - - // ------------------------------------------------------------ - // CenterListener interface - // ------------------------------------------------------------ - - /** - * Handles incoming CenterEvents. - * - * @param evt the incoming center event - */ - public void center(CenterEvent evt) { - setCenter(evt.getLatitude(), evt.getLongitude()); - } - - // ------------------------------------------------------------ - // PanListener interface - // ------------------------------------------------------------ - - /** - * Handles incoming PanEvents. - * - * @param evt the incoming pan event - */ - public void pan(PanEvent evt) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("PanEvent: " + evt); - } - float az = evt.getAzimuth() - (float) Math.toDegrees(rotationAngle); - float c = evt.getArcDistance(); - if (Float.isNaN(c)) { - projection.pan(az); - } else { - projection.pan(az, c); - } - - fireProjectionChanged(); - } - - // ------------------------------------------------------------ - // ZoomListener interface - // ------------------------------------------------------------ - - /** - * Zoom the Map. Part of the ZoomListener interface. Sets the scale of the - * MapBean projection, based on a relative or absolute amount. - * - * @param evt the ZoomEvent describing the new scale. - */ - public void zoom(ZoomEvent evt) { - float newScale; - if (evt.isAbsolute()) { - newScale = evt.getAmount(); - } else if (evt.isRelative()) { - newScale = getScale() * evt.getAmount(); - } else { - return; - } - setScale(newScale); - } - - // ------------------------------------------------------------ - // ContainerListener interface - // ------------------------------------------------------------ - - protected transient Layer[] currentLayers = new Layer[0]; - - protected transient boolean doContainerChange = true; - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param value boolean - */ - public void setDoContainerChange(boolean value) { - // if changing from false to true, call changeLayers() - if (!doContainerChange && value) { - doContainerChange = value; - changeLayers(null); - } else { - doContainerChange = value; - } - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @return boolean - */ - public boolean getDoContainerChange() { - return doContainerChange; - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param e ContainerEvent - */ - public void componentAdded(ContainerEvent e) { - // Blindly cast. addImpl has already checked to be - // sure the child is a Layer. - Layer childLayer = (Layer) e.getChild(); - addProjectionListener(childLayer); - - // If the new layer is in the queue to have removed() called - // on it take it off the queue, and don't add it to the - // added() queue (it doesn't know that it was removed, yet). - // Otherwise, add it to the queue to have added() called on - // it. - if (!removedLayers.removeElement(childLayer)) { - addedLayers.addElement(childLayer); - } - changeLayers(e); - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. Layers that are removed are added to a list, - * which is cleared when the projection changes. If they are added to the - * MapBean again before the projection changes, they are taken off the list, - * added back to the MapBean, and are simply repainted. This prevents layers - * from doing unnecessary work if they are toggled on and off without - * projection changes. - * - * @param e ContainerEvent - * @see com.bbn.openmap.MapBean#purgeAndNotifyRemovedLayers - */ - public void componentRemoved(ContainerEvent e) { - // Blindly cast. addImpl has already checked to be - // sure the child is a Layer. - Layer childLayer = (Layer) e.getChild(); - removeProjectionListener(childLayer); - removedLayers.addElement(childLayer); - changeLayers(e); - } - - /** - * ContainerListener Interface method. Should not be called directly. Part - * of the ContainerListener interface, and it's here to make the MapBean a - * good Container citizen. - * - * @param e ContainerEvent - */ - protected void changeLayers(ContainerEvent e) { - // Container Changes can be disabled to speed adding/removing - // multiple layers - if (!doContainerChange) { - return; - } - Component[] comps = this.getComponents(); - int ncomponents = comps.length; - Layer[] newLayers = new Layer[ncomponents]; - System.arraycopy(comps, 0, newLayers, 0, ncomponents); - if (logger.isLoggable(Level.FINE)) { - debugmsg("changeLayers() - firing change"); - } - firePropertyChange(LayersProperty, currentLayers, newLayers); - - // Tell the new layers that they have been added - for (Layer layer : addedLayers) { - layer.added(this); - } - addedLayers.removeAllElements(); - - currentLayers = newLayers; - - } - - // ------------------------------------------------------------ - // ProjectionListener interface - // ------------------------------------------------------------ - - /** - * ProjectionListener interface method. Should not be called directly. - * - * @param e ProjectionEvent - */ - public void projectionChanged(ProjectionEvent e) { - Projection newProj = e.getProjection(); - if (!projection.equals(newProj)) { - setProjection(newProj); - } - } - - /** - * Set the Mouse cursor over the MapBean component. - * - * @param newCursor Cursor - */ - public void setCursor(Cursor newCursor) { - firePropertyChange(CursorProperty, this.getCursor(), newCursor); - super.setCursor(newCursor); - } - - /** - * In addition to adding the PropertyChangeListener as the JComponent method - * does, this method also provides the listener with the initial version of - * the Layer and Cursor properties. - */ - public void addPropertyChangeListener(PropertyChangeListener pcl) { - super.addPropertyChangeListener(pcl); - pcl.propertyChange(new PropertyChangeEvent(this, LayersProperty, currentLayers, currentLayers)); - pcl.propertyChange(new PropertyChangeEvent(this, CursorProperty, this.getCursor(), this.getCursor())); - pcl.propertyChange(new PropertyChangeEvent(this, BackgroundProperty, this.getBckgrnd(), this.getBckgrnd())); - } - - protected final void debugmsg(String msg) { - logger.fine(this.toString() - + (DEBUG_TIMESTAMP ? (" [" + System.currentTimeMillis() + "]") : "") - + (DEBUG_THREAD ? (" [" + Thread.currentThread() + "]") : "") + ": " + msg); - } - - /** - * Same as JComponent.paint(), except if there are no children (Layers), the - * projection still paints the background and the border is painted. - */ - public void paint(Graphics g) { - if (projection != null) { - drawProjectionBackground(g); - } - - if (this.getComponentCount() > 0) { - paintChildren(g, null); - } - - paintPainters(g); - - // Border gets painted over by printChildren with special layer - // handling. - paintBorder(g); - } - - /** - * Convenience method to test if Graphics is Graphics2D object, and to try - * to do the right thing. - */ - protected void drawProjectionBackground(Graphics g) { - if (g instanceof Graphics2D) { - projection.drawBackground((Graphics2D) g, getBckgrnd()); - } else { - g.setColor(getBackground()); - projection.drawBackground(g); - } - } - - /** - * Same as JComponent.paintChildren() except any PaintListeners are notified - * and the border is painted over the children. - */ - public void paintChildren(Graphics g) { - paintChildren(g, null); - paintPainters(g); - } - - public void paintPainters(Graphics g) { - // Just want a quick, non-changing handle on the helper. Don't need to - // configure it. - RotationHelper rotationHelper = getRotHelper(); - - if (rotationHelper != null) { - rotationHelper.paintPainters(g); - } else { - painters.paint(g); - } - } - - /** - * Same as paintChildren, but allows you to set a clipping area to paint. Be - * careful with this, because if the clipping area is set while some layer - * decides to paint itself, that layer may not have all it's objects - * painted. - */ - public void paintChildren(Graphics g, Rectangle clip) { - - g = getMapBeanRepaintPolicy().modifyGraphicsForPainting(g); - - drawProjectionBackground(g); - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - rotationHelper.paintChildren(g, clip); - } else { - // Normal painting - super.paintChildren(g); - } - } - - /** - * A method that grabs the component list of the MapBean, and renders just - * the layers from back to front. No clipping is set, other than what is set - * on the Graphics object. - * - * @param g Graphics - */ - protected void paintLayers(Graphics g) { - synchronized (getTreeLock()) { - int i = getComponentCount() - 1; - if (i < 0) { - return; - } - - for (; i >= 0; i--) { - Component comp = getComponent(i); - - final boolean isLayer = comp instanceof Layer; - - if (isLayer && comp.isVisible()) { - comp.paint(g); - } - } - } - } - - public Graphics getGraphics(boolean rotateIfSet) { - RotationHelper rotationHelper = getRotHelper(); - if (rotateIfSet && rotationHelper != null) { - return rotationHelper.getGraphics(); - } - - return super.getGraphics(); - } - - /** - * Method that provides an option of whether or not to draw the border when - * painting. Usually called from another object trying to control the Map - * appearance when events are flying around. - */ - public void paintChildrenWithBorder(Graphics g, boolean drawBorder) { - paintChildren(g); - if (drawBorder) { - paintBorder(g); - } - } - - /** - * Add a PaintListener. - * - * @param l PaintListener - */ - public synchronized void addPaintListener(PaintListener l) { - painters.add(l); - } - - /** - * Remove a PaintListener. - * - * @param l PaintListener - */ - public synchronized void removePaintListener(PaintListener l) { - painters.remove(l); - } - - // ------------------------------------------------------------ - // LayerListener interface - // ------------------------------------------------------------ - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. - * - * @param evt a LayerEvent - */ - public void setLayers(LayerEvent evt) { - setBufferDirty(true); - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - // Don't care about these at all... - return; - } - - // @HACK is this cool?: - if (layers == null) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean.setLayers(): layers is null!"); - } - return; - } - - boolean oldChange = getDoContainerChange(); - setDoContainerChange(false); - - // use LayerEvent.REPLACE when you want to remove all current - // layers add a new set - if (type == LayerEvent.REPLACE) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Replacing all layers"); - } - removeAll(); - - for (Layer layer : layers) { - - if (layer == null) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("MapBean.setLayers(): skipping null layer from being added to MapBean"); - } - continue; - } - - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - add(layer); - layer.setVisible(true); - } - - } - - // use LayerEvent.ADD when adding and/or reshuffling layers - else if (type == LayerEvent.ADD) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding new layers"); - } - for (Layer layer : layers) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Adding layer[" + layer.getName() + "]"); - } - add(layer); - layer.setVisible(true); - } - } - - // use LayerEvent.REMOVE when you want to delete layers from - // the map - else if (type == LayerEvent.REMOVE) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Removing layers"); - } - for (Layer layer : layers) { - if (logger.isLoggable(Level.FINE)) { - debugmsg("Removing layer[" + layer.getName() + "]"); - } - remove(layer); - } - } - - if (!layerRemovalDelayed) { - purgeAndNotifyRemovedLayers(); - } - - setDoContainerChange(oldChange); - revalidate(); - repaint(); - } - - /** - * A call to try and get the MapBean to reduce flashing by controlling when - * repaints happen, waiting for lower layers to call for a repaint(), too. - * Calls shouldForwardRepaint(Layer), which acts as a policy for whether to - * forward the repaint up the Swing tree. - */ - public void repaint(Layer layer) { - setBufferDirty(true); - if (logger.isLoggable(Level.FINER)) { - String name = layer.getName(); - logger.finer((name == null ? layer.getClass().getName() : name) - + " - wants a repaint()"); - } - getMapBeanRepaintPolicy().repaint(layer); - } - - /** - * Set the MapBeanRepaintPolicy used by the MapBean. This policy can be used - * to pace/filter layer repaint() requests. - */ - public void setMapBeanRepaintPolicy(MapBeanRepaintPolicy mbrp) { - repaintPolicy = mbrp; - } - - /** - * Get the MapBeanRepaintPolicy used by the MapBean. This policy can be used - * to pace/filter layer repaint() requests. If no policy has been set, a - * StandardMapBeanRepaintPolicy will be created, which simply forwards all - * requests. - */ - public MapBeanRepaintPolicy getMapBeanRepaintPolicy() { - if (repaintPolicy == null) { - repaintPolicy = new StandardMapBeanRepaintPolicy(this); - } - return repaintPolicy; - } - - /** - * Convenience function to get the LatLonPoint representing a screen - * location from a MouseEvent. Returns null if the event is null, or if the - * projection is not set in the MapBean. Allocates new LatLonPoint with - * coordinates. Takes rotation set on MapBean into account. - */ - public Point2D getCoordinates(MouseEvent event) { - return getCoordinates(event, null); - } - - /** - * Convenience function to get the LatLonPoint representing a screen - * location from a MouseEvent. Returns null if the event is null, or if the - * projection is not set in the MapBean. Save on memory allocation by - * sending in the LatLonPoint to fill. Takes rotation set on MapBean into - * account. - */ - public T getCoordinates(MouseEvent event, T llp) { - Projection proj = getProjection(); - if (proj == null || event == null) { - return null; - } - - return inverse(event.getX(), event.getY(), llp); - } - - /** - * Convenience function to get the pixel Point2D representing a screen - * location from a MouseEvent in the projection space (as if there is no - * rotation set). Returns null if the event is null. This is used to talk to - * the OMGraphics, since they don't know about the map rotation. - */ - public Point2D getNonRotatedLocation(MouseEvent event) { - return getNonRotatedLocation(event, null); - } - - /** - * Convenience function to get the pixel Point2D representing a screen - * location from a MouseEvent in the projection space (as if there is no - * rotation set). Returns null if the event is null. This is used to talk to - * the OMGraphics, since they don't know about the map rotation. - */ - public Point2D getNonRotatedLocation(MouseEvent event, Point2D pnt) { - if (event == null) { - return null; - } - - if (pnt == null) { - pnt = new Point2D.Double(event.getX(), event.getY()); - } else { - pnt.setLocation(event.getX(), event.getY()); - } - - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - pnt = rotationHelper.inverseTransform(pnt, pnt); - } - - return pnt; - } - - /** - * If the map has been rotated, get a shape that has been transformed into - * the pixel space of the unrotated maps (the space the projected OMGraphics - * know about). - * - * @param shape input shape - * @return GeneralPath for transform shape if map is rotated, the input - * shape if the map is not rotated. - */ - public Shape getNonRotatedShape(Shape shape) { - RotationHelper rotationHelper = getRotHelper(); - if (rotationHelper != null) { - return rotationHelper.inverseTransform(shape); - } - return shape; - } - - /** - * Checks the rotation set on the MapBean and accounts for it before calling - * inverse on the projection. - * - * @param x horizontal window pixel from left side - * @param y vertical window pixel from top - * @param ret Point2D object returned with coordinates suitable for - * projection where mouse event is. - * @return the provided T ret object, or new Point2D object from projection - * if ret is null. - */ - public T inverse(double x, double y, T ret) { - RotationHelper rotationHelper = getRotHelper(); - return (rotationHelper == null) ? getProjection().inverse(x, y, ret) - : rotationHelper.inverse(x, y, ret); - } - - /** - * Interface-like method to query if the MapBean is buffered, so you can - * control behavior better. Allows the removal of specific instance-like - * queries for, say, BufferedMapBean, when all you really want to know is if - * you have the data is buffered, and if so, should be buffer be cleared. - * For the MapBean, always false. - */ - public boolean isBuffered() { - return false; - } - - /** - * Interface-like method to set a buffer dirty, if there is one. In MapBean, - * there isn't. - * - * @param value boolean - */ - public void setBufferDirty(boolean value) { - } - - /** - * Checks whether the image buffer should be repainted. - * - * @return boolean whether the layer buffer is dirty. Always true for - * MapBean, because a paint is always gonna need to happen. - */ - public boolean isBufferDirty() { - return true; - } - - /** - * If true (default) layers are held when they are removed, and then - * released and notified of removal when the projection changes. This saves - * the layers from releasing resources if the layer is simply being toggled - * on/off for different map views. - * - * @param set the setting - */ - public void setLayerRemovalDelayed(boolean set) { - layerRemovalDelayed = set; - } - - /** - * @return the flag for delayed layer removal. - */ - public boolean isLayerRemovalDelayed() { - return layerRemovalDelayed; - } - - /** - * Go through the layers, and for all of them that have the autoPalette - * variable turned on, show their palettes. - */ - public void showLayerPalettes() { - for (Component comp : getComponents()) { - // they have to be layers - Layer l = (Layer) comp; - if (l.autoPalette) { - l.showPalette(); - } - } - } - - /** - * Turn off all layer palettes. - */ - public void hideLayerPalettes() { - for (Component comp : getComponents()) { - // they have to be layers - ((Layer) comp).hidePalette(); - } - } - - protected ProjectionFactory projectionFactory; - - public ProjectionFactory getProjectionFactory() { - if (projectionFactory == null) { - projectionFactory = ProjectionFactory.loadDefaultProjections(); - } - - return projectionFactory; - } - - public void setProjectionFactory(ProjectionFactory projFactory) { - projectionFactory = projFactory; - } - - protected RotationHelper rotHelper; - - /** - * Handles all of the updating of the RotationHelper if needed, based on the - * current rotation settings on the MapBean. - * - * @return the locRotHelper, null if not needed. - */ - protected RotationHelper getUpdatedRotHelper() { - double rotAngle = getRotationAngle(); - Projection proj = getProjection(); - RotationHelper rotationHelper = getRotHelper(); - - if (rotAngle != 0.0) { - if (rotationHelper == null) { - rotationHelper = new RotationHelper(rotAngle, proj); - setRotHelper(rotationHelper); - } else { - rotationHelper.updateForBufferDimensions(proj); - rotationHelper.updateAngle(rotAngle); - } - } else if (rotationHelper != null) { - /* - * Just because the angle is zero, let's check with the - * rotationHelper. If the map is just passing through zero rotation, - * keep it around. If we get a couple of projection changes with the - * az set to zero, then get rid of the rotation helper. - */ - if (rotationHelper.isStillNeeded(rotAngle)) { - rotationHelper.updateForBufferDimensions(proj); - rotationHelper.updateAngle(rotAngle); - } else { - setRotHelper(null); - rotationHelper = null; - } - } // else return null rotationHelper - - return rotationHelper; - } - - /** - * Get the RotationHelper that assists with rotated maps. - * - * @return RotationHelper, may be null if map isn't rotated. - */ - protected RotationHelper getRotHelper() { - return rotHelper; - } - - /** - * @param nRotHelper the locRotHelper to set as the current one. Disposes of - * the old one. - */ - protected void setRotHelper(RotationHelper nRotHelper) { - RotationHelper rotationHelper = this.rotHelper; - if (rotationHelper != null) { - rotationHelper.dispose(); - } - - this.rotHelper = nRotHelper; - } - - /** - * Set the rotation of the map in RADIANS. - * - * @param angle radians of rotation, increasing clockwise. - */ - public void setRotationAngle(double angle) { - setRotationAngle(angle, false); - } - - /** - * Set the rotation of the map in RADIANS. - * - * @param angle radians of rotation, increasing clockwise. - * @param fastRotation if true, fireProjectionChange will not be called, and - * the RotationHelper will be used to spin image buffer. - */ - public void setRotationAngle(double angle, boolean fastRotation) { - if (this.rotationAngle != angle) { - this.rotationAngle = angle; - - /* - * moving into this block makes rotation work faster, and smooth. - * However, it doesn't give the non-rotating OMGraphics a chance to - * counteract the rotation. - */ - if (fastRotation && angle != 0) { - /* - * If only the angle changes, we can just update the - * locRotHelper angle, and reuse all of the other settings. If - * the angle changes and zero is involved,either way, get the - * rotation helper set up in fireProjectionChanged. The - * RotationHelper needs to be redefined for any other projection - * changes anyway. - */ - RotationHelper locRotHelper = getRotHelper(); - if (locRotHelper != null) { - locRotHelper.updateAngle(angle); - repaint(); - return; - } - } - - fireProjectionChanged(); - } - } - - /** - * Get the rotation of the map in RADIANS. - * - * @return the angle the map has been rotated, in RADIANS, clockwise is - * positive. - */ - public double getRotationAngle() { - return rotationAngle; - } - - protected class RotationHelper { - - Image rotImage; - - double angle; - Point2D rotCenter; - int rotBufferHeight; - int rotBufferWidth; - int rotXOffset; - int rotYOffset; - Projection rotProjection; - AffineTransform rotTransform; - - private RotationHelper(double angle, Projection currentProjection) { - updateForBufferDimensions(currentProjection); - updateAngle(angle); - } - - /** - * We're going to try to do buffering with a image that will cover all - * of the corners when the map is rotated. We'll measure the ground - * distance from the center of the projection/map to each corner, and - * take the longest to create a bounding circle. The NSEW of that - * bounding circle (as a bounding box) Makes up the buffered image pixel - * bounds, and the inverse projected coordinates of that box should be - * returned as upper left and lower right coordinates when those methods - * are called. The projection of that box should be the same as the - * current projection, except for the new width and height. - * - * Because the height and width are different for the buffered image, - * we're going to have to translate it before it is rotated. We can - * probably just tack on an additional translate to the rot. That - * difference will be 1/2 the difference of the height and width between - * the rot image and the original projection (mapbean dimensions). - * - * @param proj the projection to use to create the current image buffer - * @return boolean true if the rotBufferHeight and/or rotBufferWidth - * have changed, indicating that the image buffer was recreated - * for new dimensions. - */ - protected boolean updateForBufferDimensions(Projection proj) { - - int currentRotBufferWidth = rotBufferWidth; - int currentRotBufferHeight = rotBufferHeight; - - Point2D center = proj.getCenter(); - Point2D ul = proj.getUpperLeft(); - Point2D lr = proj.getLowerRight(); - - /* - * Woooooow, we're really going to have to work it, aren't we? We - * need to handle GeoProj differently than Cartesian coords. That - * seems to lend itself to moving this kind of calculations to the - * super classes of the projection classes. *sigh* - * - * For now, let's try assuming that GeoProj - */ - Geo centerGeo = new Geo(center.getY(), center.getX()); - Geo ulGeo = new Geo(ul.getY(), ul.getX()); - Geo lrGeo = new Geo(lr.getY(), lr.getX()); - - // Comparing the UL and LR corners for distance, get the greatest. - double dist = Math.max(centerGeo.distance(ulGeo), centerGeo.distance(lrGeo)); - - // Now calculate the bounds of that distance in 4 directions - Geo N = Geo.offset(centerGeo, dist, 0); - Geo S = Geo.offset(centerGeo, dist, Math.PI); - Geo E = Geo.offset(centerGeo, dist, Math.PI / 2.0); - Geo W = Geo.offset(centerGeo, dist, -Math.PI / 2); - - // Calculate the coordinates of new bounds for that distance from - // center. - Point2D newUL = new Point2D.Double(W.getLongitude(), N.getLatitude()); - Point2D newLR = new Point2D.Double(E.getLongitude(), S.getLatitude()); - - // Calculate the pixel bounds of the new bounding box to get new - // projection h, w - Point2D newULPix = proj.forward(newUL); - Point2D newLRPix = proj.forward(newLR); - - int reqRotBufferHeight = (int) Math.abs(newLRPix.getY() - newULPix.getY()); - int reqRotBufferWidth = (int) Math.abs(newLRPix.getX() - newULPix.getX()); - - // If the image is a little bigger than we need, we can reuse. Only - // replace it if it is significantly bigger, or at all smaller. - boolean needNewHeightImage = reqRotBufferHeight > currentRotBufferHeight - || reqRotBufferHeight < .9 * currentRotBufferHeight; - boolean needNewWidthImage = reqRotBufferWidth > currentRotBufferWidth - || currentRotBufferWidth < .9 * currentRotBufferWidth; - - boolean bufferImageResized = false; - - if (needNewHeightImage || needNewWidthImage) { - this.rotImage = new BufferedImage(reqRotBufferWidth, reqRotBufferHeight, BufferedImage.TYPE_INT_ARGB); - rotBufferWidth = reqRotBufferWidth; - rotBufferHeight = reqRotBufferHeight; - bufferImageResized = true; - } - - rotProjection = projectionFactory.makeProjection(proj.getClass(), center, proj.getScale(), rotBufferWidth, rotBufferHeight); - this.rotCenter = rotProjection.forward(center); - - /* - * Now calculate the different in size between the current - * projection and the buffered image projection, and the offset - * needed for translation for proper painting. - */ - this.rotXOffset = (rotProjection.getWidth() - proj.getWidth()) / 2; - this.rotYOffset = (rotProjection.getHeight() - proj.getHeight()) / 2; - - return bufferImageResized; - } - - public void updateAngle(double angle) { - this.angle = angle; - this.rotTransform = AffineTransform.getRotateInstance(angle, rotCenter.getX(), rotCenter.getY()); - } - - /** - * @param az angle to test against - * @return true if current angle or new angle is not zero. Two zero - * angles in a row is an indication that the RotationHelper is - * no longer needed. - */ - public boolean isStillNeeded(double az) { - return !(az == 0.0 && angle == 0.0); - } - - /** - * @return the projection of the image buffer that is big enough for - * rotated areas. - */ - public Projection getProjection() { - return rotProjection; - } - - public void paintChildren(Graphics g, Rectangle clip) { - - if (rotProjection == null) { - // We're not properly prepared for rotation, return; - return; - } - - Graphics2D g2 = (Graphics2D) rotImage.getGraphics(); - ((Proj) rotProjection).drawBackground(g2, getBckgrnd()); - g2.setTransform(rotTransform); - paintLayers(g2); - g.drawImage(rotImage, -rotXOffset, -rotYOffset, null); - g2.dispose(); - } - - public void paintPainters(Graphics g) { - if (!painters.isEmpty()) { - Graphics2D g2 = (Graphics2D) g.create(); - AffineTransform transform = AffineTransform.getTranslateInstance(-rotXOffset - + getX(), -rotYOffset + getY()); - transform.concatenate(rotTransform); - g2.setTransform(transform); - - painters.paint(g2); - g2.dispose(); - } - } - - /** - * @return a Graphics object from the MapBean with the rotation - * transform applied. - */ - public Graphics getGraphics() { - Graphics2D g = (Graphics2D) MapBean.super.getGraphics().create(); - g.setTransform(rotTransform); - return g; - } - - /** - * Performs a projection.inverse operation that also takes into account - * rotation. - * - * @param x pixel x - * @param y pixel y - * @param ret T in the coordinate space of projection. - * @return T, either ret or a new object. - */ - public T inverse(double x, double y, T ret) { - - Point2D pnt = new Point2D.Double(x + rotXOffset, y + rotYOffset); - - try { - pnt = rotTransform.inverseTransform(pnt, pnt); - return getProjection().inverse(pnt, ret); - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, e.getMessage(), e); - } - - return ret; - } - - /** - * Returns dst, the unrotated pixel location of the map. - * - * @param src the pixel point - * @param dst - * @return see above. - */ - public Point2D inverseTransform(Point2D src, Point2D dst) { - try { - src.setLocation(src.getX() + rotXOffset, src.getY() + rotYOffset); - dst = rotTransform.inverseTransform(src, dst); - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, e.getMessage(), e); - } - return dst; - } - - /** - * Returns a transformed version of the Shape, unrotated into the - * projected pixel space of the layer OMGraphics. - * - * @param shape to transform - * @return the transformed shape. - */ - public Shape inverseTransform(Shape shape) { - - float[] coords = new float[6]; - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - PathIterator pi = shape.getPathIterator(getInverseRotationTransform()); - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(coords[0], coords[1]); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(coords[0], coords[1]); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(coords[0], coords[1], coords[2], coords[3]); - } else if (type == PathIterator.SEG_CUBICTO) { - path.curveTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); - } - } - - pi.next(); - } - - return path; - } - - public AffineTransform getInverseRotationTransform() { - try { - AffineTransform translateOffset = AffineTransform.getTranslateInstance(rotXOffset, rotYOffset); - AffineTransform transform = rotTransform.createInverse(); - translateOffset.preConcatenate(transform); - return translateOffset; - } catch (NoninvertibleTransformException e) { - logger.log(Level.FINE, "AffineTransform problem", e); - } - - return new AffineTransform(); - } - - public void dispose() { - if (rotImage != null) { - rotImage.flush(); - } - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/app/example/SimpleMap.java b/src/openmap/com/bbn/openmap/app/example/SimpleMap.java deleted file mode 100644 index 748ff1f6e..000000000 --- a/src/openmap/com/bbn/openmap/app/example/SimpleMap.java +++ /dev/null @@ -1,84 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/examples/simple/SimpleMap.java,v $ -// $RCSfile: SimpleMap.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:05:46 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.app.example; - -import com.bbn.openmap.gui.BasicMapPanel; -import com.bbn.openmap.layer.shape.ShapeLayer; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Properties; -import javax.swing.JFrame; - -/** - * This is a simple application that uses the OpenMap MapBean to show a map. - * This sample application is just provided to show the simplest way to put a - * map in a java application. If you want a the best example to use for a simple - * application to play with OpenMap components, use SimpleMap2! Use a MapPanel! - *

- * This example shows: - *

    - *
  • MapBean - *
  • ShapeLayer with political data - *
- */ -public class SimpleMap { - - public static void main(String args[]) { - - BasicMapPanel mapPanel = new BasicMapPanel(); - - // Create a ShapeLayer to show world political boundaries. - // Set the properties of the layer. This assumes that the - // "data" directory containing the files "dcwpo-browse.shp" - // and "dcwpo-browse.ssx" are in a path specified in the - // CLASSPATH variable. These files are distributed with - // OpenMap and reside in the toplevel "share" subdirectory. - ShapeLayer shapeLayer = new ShapeLayer(); - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "data/shape/dcwpo-browse.shp"); - shapeLayerProps.put("spatialIndex", "data/shape/dcwpo-browse.ssx"); - shapeLayer.setProperties(shapeLayerProps); - - // Add the political layer to the map - mapPanel.getMapBean().add(shapeLayer); - - // Create a Swing frame - JFrame frame = new JFrame("Simple Map"); - // Size the frame appropriately - frame.setSize(640, 480); - // Add the map to the frame - frame.getContentPane().add(mapPanel); - - // If you close the frame, exit the app. - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - // Display the frame - frame.setVisible(true); - } -} diff --git a/src/openmap/com/bbn/openmap/app/example/SimpleMap2.java b/src/openmap/com/bbn/openmap/app/example/SimpleMap2.java deleted file mode 100644 index 4bad1997f..000000000 --- a/src/openmap/com/bbn/openmap/app/example/SimpleMap2.java +++ /dev/null @@ -1,173 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/examples/simple/SimpleMap2.java,v $ -// $RCSfile: SimpleMap2.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/05/23 19:46:57 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.app.example; - -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.MultipleSoloMapComponentException; -import com.bbn.openmap.event.OMMouseMode; -import com.bbn.openmap.gui.LayersPanel; -import com.bbn.openmap.gui.MapPanel; -import com.bbn.openmap.gui.OpenMapFrame; -import com.bbn.openmap.gui.OverlayMapPanel; -import com.bbn.openmap.gui.ToolPanel; -import com.bbn.openmap.layer.GraticuleLayer; -import com.bbn.openmap.layer.learn.BasicLayer; -import com.bbn.openmap.layer.shape.BufferedShapeLayer; -import com.bbn.openmap.layer.shape.ShapeLayer; -import com.bbn.openmap.proj.coords.LatLonPoint; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Properties; - -/** - * This is a simple application that uses the OpenMap MapBean to show a map. - * This is the model you should follow if you are starting to use OpenMap and - * want to create your own application. Use a MapPanel! Use the MapHandler - * inside it! - *

- * This example shows: - *

    - *
  • MapBean - *
  • MapHandler - *
  • LayerHandler - *
  • LayersPanel - *
  • ShapeLayer with political data - *
  • GraticuleLayer - *
  • BasicLayer with some random data - *
  • Tools to navigate around on the map - *
- */ -public class SimpleMap2 { - - public SimpleMap2() { - - try { - - /* - * The BasicMapPanel automatically creates many default components, - * including the MapBean and the MapHandler. You can extend the - * BasicMapPanel class if you like to add different functionality or - * different types of objects. - */ - MapPanel mapPanel = new OverlayMapPanel(); - - /* - * The MapHandler is central to this application, although you never - * really see it. It's in the MapPanel. Calling addMapComponent(obj) - * is the same as calling mapPanel.getMapHandler().add(obj). - */ - - /* - * Create and add a LayerHandler to the MapHandler. The LayerHandler - * manages Layers, whether they are part of the map or not. - * layer.setVisible(true) will add it to the map. The LayerHandler - * has methods to do this, too. The LayerHandler will find the - * MapBean in the MapHandler. - */ - mapPanel.addMapComponent(new LayerHandler()); - // Add MouseDelegator, which handles mouse modes (managing mouse - // events via MouseModes) - mapPanel.addMapComponent(new MouseDelegator()); - // Add OMMouseMode, which handles how the map reacts to mouse - // movements - mapPanel.addMapComponent(new OMMouseMode()); - // Add a ToolPanel for widgets on the north side of the map. - mapPanel.addMapComponent(new ToolPanel()); - // Add a LayersPanel, which lets you control layers - mapPanel.addMapComponent(new LayersPanel()); - - /* - * Create a ShapeLayer to show world political boundaries. Set the - * properties of the layer. This assumes that the datafile - * "cntry02.shp" is in a path specified in the CLASSPATH variable. - * These files are distributed with OpenMap and reside in the top - * level "share" sub-directory. - */ - ShapeLayer shapeLayer = new BufferedShapeLayer(); - - // Since this Properties object is being used just for - // this layer, the properties do not have to be scoped - // with marker name. - Properties shapeLayerProps = new Properties(); - shapeLayerProps.put("prettyName", "Political Solid"); - shapeLayerProps.put("lineColor", "000000"); - shapeLayerProps.put("fillColor", "BDDE83"); - shapeLayerProps.put("shapeFile", "data/shape/cntry02/cntry02.shp"); - shapeLayer.setProperties(shapeLayerProps); - shapeLayer.setVisible(true); - - // Last on top. - mapPanel.addMapComponent(shapeLayer); - mapPanel.addMapComponent(new GraticuleLayer()); - mapPanel.addMapComponent(new BasicLayer()); - - // Create a Swing frame. The OpenMapFrame knows how to use - // the MapHandler to locate and place certain objects. - OpenMapFrame frame = new OpenMapFrame("Simple Map 2"); - // Size the frame appropriately - frame.setSize(640, 480); - - mapPanel.addMapComponent(frame); - - // If you close the frame, exit the app - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - // Display the frame - frame.setVisible(true); - - // Get the default MapBean that the BasicMapPanel created. - MapBean mapBean = mapPanel.getMapBean(); - // Set the map's center - mapBean.setCenter(new LatLonPoint.Double(43.0, -95.0)); - // Set the map's scale 1:120 million - mapBean.setScale(120000000f); - - } catch (MultipleSoloMapComponentException msmce) { - // The MapHandler is only allowed to have one of certain - // items. These items implement the SoloMapComponent - // interface. The MapHandler can have a policy that - // determines what to do when duplicate instances of the - // same type of object are added - replace or ignore. - - // In this example, this will never happen, since we are - // controlling that one MapBean, LayerHandler, - // MouseDelegator, etc is being added to the MapHandler. - } - } - - public static void main(String[] args) { - // Schedule a job for the event-dispatching thread: - // creating and showing this application's GUI. - javax.swing.SwingUtilities.invokeLater(new Runnable() { - public void run() { - new SimpleMap2(); - } - }); - } -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java b/src/openmap/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java deleted file mode 100644 index b8a1bb8eb..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/mapTile/MapTileFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.Projection; - -/** - * An object that fetches tiles for a given projection. It could cache the - * tiles, it can get them from anywhere it might want to. - * - * @author dietrick - */ -public interface MapTileFactory { - /** - * Create an OMGraphicList with a set of tiles on it. - * - * @param proj - * @return OMGraphicList that was created. - */ - OMGraphicList getTiles(Projection proj); - - /** - * Create an OMGraphicList that covers the projection with tiles that suit - * the specified zoom level. - */ - OMGraphicList getTiles(Projection proj, int zoomLevel); - - /** - * Add tiles to OMGraphicList provided that suit the given projection. - * - * @param proj - * @param list - * @return the OMGraphicList provided. - */ - OMGraphicList getTiles(Projection proj, int zoomLevel, OMGraphicList list); - - /** - * Set a MapTileRequestor in the tile factory that should be told to repaint - * when new tiles become available, and to check with during the tile fetch - * whether to keep going or not. listUpdate will be called when a new tile - * has been added to the OMGraphicList passed in the getTiles method, and - * shouldContinue will be called during stable times during the getTiles - * fetch. - * - * @param requestor - * callback MapTileRequestor to ask status questions. - */ - void setMapTileRequester(MapTileRequester requestor); - - /** - * Tell the factory to clean up resources. - */ - void reset(); - - /** - * Get object that handles empty tiles. - * - * @return EmptyTileHandler used by the factory. - */ - EmptyTileHandler getEmptyTileHandler(); -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java b/src/openmap/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java deleted file mode 100644 index a24473db5..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/mapTile/ServerMapTileFactory.java +++ /dev/null @@ -1,346 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; - -import javax.swing.ImageIcon; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The ServerMapTileFactory is an extension to the StandardMapTileFactory that - * can go to a http server to retrieve image tiles. You provide it with a root - * URL that points to the parent directory of the tiles, and then this component - * will add on the zoom/x/y.extension to that directory path to make the call - * for a specific tile. Please make sure you have the permission of the server's - * owner before hammering away at retrieving tiles from it. - * - * This component can be configured using properties: - *

- * - *

- * # Inherited from StandardMapTileFactory
- * rootDir=the URL to the parent directory of the tiles on a server. The factory will construct specific file paths that are appended to this value. 
- * fileExt=the file extension to append to the tile names, should have a period.
- * cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * 
- * # Additional properties
- * localCacheRootDir=if specified, the factory will store tiles locally at this root directory.  This directory is checked before going to the server, too.
- * 
- * - * @author dietrick - */ -public class ServerMapTileFactory extends StandardMapTileFactory implements MapTileFactory, - PropertyConsumer { - - public final static String LOCAL_CACHE_ROOT_DIR_PROPERTY = "localCacheRootDir"; - - protected String localCacheDir = null; - - public ServerMapTileFactory() { - this(null); - } - - public ServerMapTileFactory(String rootDir) { - this.rootDir = rootDir; - this.fileExt = ".png"; - verbose = logger.isLoggable(Level.FINE); - } - - /** - * An auxiliary call to retrieve something from the cache, modified to allow - * load method to do some projection calculations to initialize tile - * parameters. If the object is not found in the cache, null is returned. - */ - public Object getFromCache(Object key, int x, int y, int zoomLevel) { - String localLoc = null; - - if (localCacheDir != null && zoomLevelInfo != null) { - localLoc = buildLocalFilePath(x, y, zoomLevel, fileExt); - /** - * If a local cache is defined, then the cache will always use the - * string for the local file as the key. - */ - CacheObject ret = searchCache(localLoc); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - /** - * Return null if the localized version isn't found in cache when - * local version is defined. - */ - return null; - } - - // Assuming that the localCacheDir is not defined, so the cache objects - // will be using the server location as key - - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - return null; - } - - /** - * Checks the local directory first for a locally cached version of the tile - * before going off to the server. If a local directory is listed as a - * cache, any retrieved files will be stored there for future use. We are - * using the local name of the file as the cache key for all tiles for - * consistency - all tiles are looked up with local cache locations. - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - - if (verbose) { - logger.fine("fetching file for cache: " + key); - } - - byte[] imageBytes = null; - - CacheObject localVersion = super.load(key, x, y, zoomLevel, proj); - - if (localVersion != null) { - logger.fine("found version of tile in local cache: " + key); - return localVersion; - } - - // build file path here uses rootDir, which is the URL. - String imagePath = buildFilePath(x, y, zoomLevel, fileExt); - - imageBytes = getImageBytes(imagePath, (String) key); - - if (imageBytes != null && imageBytes.length > 0) { - // image found - ImageIcon ii = new ImageIcon(imageBytes); - - try { - BufferedImage rasterImage = preprocessImage(ii.getImage(), ii.getIconWidth(), ii.getIconHeight()); - OMGraphic raster = createOMGraphicFromBufferedImage(rasterImage, x, y, zoomLevel, proj); - - /* - * Again, create a CacheObject based on the local name if - * the local dir is defined. - */ - if (raster != null) { - return new CacheObject(key, raster); - } - - } catch (InterruptedException ie) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("factory interrupted fetching " + imagePath); - } - } - - } - - /* - * At this point, nothing was found for this location, so it's an - * empty tile. - */ - return getEmptyTile(key, x, y, zoomLevel, proj); - } - - return null; - } - - /** - * Tries to get the image bytes from imagePath URL. If image found, will - * write it locally to localFilePath for caching. - * - * @param imagePath the source URL image path. - * @param localFilePath the caching local file path - * @return byte[] of image - */ - public byte[] getImageBytes(String imagePath, String localFilePath) { - byte[] imageBytes = null; - - try { - java.net.URL url = new java.net.URL(imagePath); - java.net.URLConnection urlc = url.openConnection(); - - if (logger.isLoggable(Level.FINER)) { - logger.finer("url content type: " + urlc.getContentType()); - } - - if (urlc == null || urlc.getContentType() == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("unable to connect to (tile might be unavailable): " + imagePath); - } - - // text - } else if (urlc.getContentType().startsWith("text")) { - java.io.BufferedReader bin = new java.io.BufferedReader(new java.io.InputStreamReader(urlc.getInputStream())); - String st; - StringBuffer message = new StringBuffer(); - while ((st = bin.readLine()) != null) { - message.append(st); - } - - // Debug.error(message.toString()); - // How about we toss the message out to the user - // instead? - logger.fine(message.toString()); - - // image - } else if (urlc.getContentType().startsWith("image")) { - - InputStream in = urlc.getInputStream(); - // ------- Testing without this - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int buflen = 2048; // 2k blocks - byte buf[] = new byte[buflen]; - int len = -1; - while ((len = in.read(buf, 0, buflen)) != -1) { - out.write(buf, 0, len); - } - out.flush(); - out.close(); - - imageBytes = out.toByteArray(); - - if (localFilePath != null) { - File localFile = new File(localFilePath); - - File parentDir = localFile.getParentFile(); - parentDir.mkdirs(); - - FileOutputStream fos = new FileOutputStream(localFile); - fos.write(imageBytes); - fos.flush(); - fos.close(); - } - - } // end if image - } catch (java.net.MalformedURLException murle) { - logger.warning("ServerMapTileFactory: URL \"" + imagePath + "\" is malformed."); - } catch (java.io.IOException ioe) { - logger.fine("Couldn't connect to " + imagePath + ", connection problem"); - } - - return imageBytes; - - } - - /** - * Acts the same as the buildFilePath method, but works for a local - * directory specified in the properties. - * - * @param x tile coordinate - * @param y tile coordinate - * @param z zoom level - * @param fileExt file extension for image tiles. - * @return new path for tile file - */ - public String buildLocalFilePath(int x, int y, int z, String fileExt) { - if (localTilePathBuilder == null) { - localTilePathBuilder = new TilePathBuilder(localCacheDir); - } - - return localTilePathBuilder.buildTilePath(x, y, z, fileExt); - } - - private TilePathBuilder localTilePathBuilder = null; - - /** - * Creates a unique cache key for this tile based on zoom, x, y. This method - * was created so the ServerMapTileFactory could override it and use local - * cache names for keys if a local cache was being used. - * - * @param x tile coord. - * @param y tile coord. - * @param z zoomLevel. - * @param fileExt file extension. - * @return String used in cache. - */ - protected String buildCacheKey(int x, int y, int z, String fileExt) { - if (localCacheDir != null) { - return buildLocalFilePath(x, y, z, fileExt); - } - return super.buildCacheKey(x, y, z, fileExt); - } - - public Properties getProperties(Properties getList) { - getList = super.getProperties(getList); - getList.put(prefix + LOCAL_CACHE_ROOT_DIR_PROPERTY, PropUtils.unnull(localCacheDir)); - return getList; - } - - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, LOCAL_CACHE_ROOT_DIR_PROPERTY, "Local Cache Tile Directory", "Root directory containing image tiles retrieved from image server.", "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - return list; - } - - public void setProperties(String prefix, Properties setList) { - super.setProperties(prefix, setList); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - localCacheDir = setList.getProperty(prefix + LOCAL_CACHE_ROOT_DIR_PROPERTY, localCacheDir); - } - - /** - * Tell the factory to dump the cache. For the ServerMapTileFactory, this - * also includes the local file cache dir. - */ - public void reset() { - super.reset(); - if (localCacheDir != null) { - File localCacheDirFile = new File(localCacheDir); - if (localCacheDirFile.exists()) { - try { - FileUtils.deleteFile(localCacheDirFile); - } catch (IOException e) { - logger.fine("There's a problem deleting local cache directory: " - + e.getMessage()); - } - } - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java b/src/openmap/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java deleted file mode 100644 index 43aae3e95..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/mapTile/StandardMapTileFactory.java +++ /dev/null @@ -1,1269 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMScalingRaster; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.omGraphics.OMWarpingImage; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ClasspathHacker; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; -import com.bbn.openmap.util.cacheHandler.CacheObject; - -/** - * The StandardImageTileFactory is a TileFactory implementation that retrieves - * image tiles from local storage. These tiles are assumed to be stored in the - * local file system, at some root directory, and then in some hierarchy like - * zoom-level/x coord/y coord.file-extension. This class can be extended to - * allow different tile naming/storing conventions to be used. - *

- * - * This component can be configured using properties: - *

- * - *

- * rootDir=the path to the parent directory of the tiles. The factory will construct specific file paths that are appended to this value.
- * fileExt=the file extension to append to the tile names
- * cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TSMMapTileCoordinateTransform
- * # what to do about missing tiles?
- * emptyTileHandler=com.bbn.openmap.dataAccess.mapTile.SimpleEmptyTileHandler
- * # Set a tile image preparer, if you want to change how images are rendered (greyscale, for instance)
- * tileImagePreparer=com.bbn.openmap.dataAccess.mapTile.StandardImagePreparer
- * # or
- * tileImagePreparer=com.bbn.openmap.dataAccess.mapTile.GreyscaleImagePreparer
- * 
- * - * @author dietrick - */ -public class StandardMapTileFactory extends CacheHandler implements MapTileFactory, - PropertyConsumer { - protected String prefix = null; - protected final static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory"); - protected final static Logger mapTileLogger = Logger.getLogger("MAPTILE_DEBUGGING"); - public final static String ROOT_DIR_PROPERTY = "rootDir"; - public final static String FILE_EXT_PROPERTY = "fileExt"; - public final static String CACHE_SIZE_PROPERTY = "cacheSize"; - public final static String MTCTRANSFORM_PROPERTY = "mapTileTransform"; - public final static String EMPTY_TILE_HANDLER_PROPERTY = "emptyTileHandler"; - public final static String ZOOM_LEVEL_INFO_PROPERTY = "zoomLevelInfo"; - public final static String ZOOM_LEVEL_TILE_SIZE_PROPERTY = "zoomLevelTileSize"; - public final static String TILE_IMAGE_PREPARER_PROPERTY = "tileImagePreparer"; - /** - * Inserted into properties loaded via tiles.omp, so that the - * EmptyTileHandler can know where the tile set is located, in case it needs - * to know the absolute path. Will contain the root directory path specified - * in the factory properties, as opposed to any rootDir property set in the - * tiles.omp file that would specify a relative root directory path. - */ - public final static String ROOT_DIR_PATH_PROPERTY = "rootDirPath"; - /** - * The name of the properties file that the factory looks for in the root - * directory of the data (tiles.omp). - */ - public final static String TILE_PROPERTIES = "tiles.omp"; - protected ZoomLevelInfo zoomLevelInfo = new ZoomLevelInfo(); - protected String rootDir; - protected String fileExt = ".png"; - protected String rootDirProperty; // For writing out later, if necessary - protected EmptyTileHandler emptyTileHandler = null; - protected boolean verbose = false; - /** - * The zoom level tile size is used by the factory to determine when it - * needs to get tiles for a different zoom level. The default value is 350. - * That is, when the factory is figuring out what zoom level to use, if the - * pixel size of a tile is greater than or equal to 350 x 350, it decides to - * check the next zoom level for retrieving tiles. This is used instead of - * just comparing projection scales. - */ - protected int zoomLevelTileSize = 350; - protected TileImagePreparer tileImagePreparer; - - /** - * If set, the MapTileRequester will be notified when the list provided in - * getTiles() has been updated, and asked if it should continue with the - * getTiles() request at opportune times, when tile fetching is stable. - */ - protected MapTileRequester mapTileRequester; - /** - * Flag to tell the factory to create the extra tiles off-map. Tends to - * cause the layer to do more work than necessary, so it's not used. - */ - private boolean doExtraTiles = false; - /** - * Coordinate transform for the uv coordinates of the tiles. Different - * sources have different origins for tile coordinates. - */ - protected MapTileCoordinateTransform mtcTransform = new OSMMapTileCoordinateTransform(); - - public StandardMapTileFactory() { - super(100); - verbose = logger.isLoggable(Level.FINE); - } - - public StandardMapTileFactory(MapTileRequester layer, String rootDir, String tileFileExt) { - super(100); - setRootDir(rootDir); - setFileExt(tileFileExt); - verbose = logger.isLoggable(Level.FINE); - this.mapTileRequester = layer; - } - - @Override - public CacheObject load(Object key) { - return null; - } - - /** - * Tell the factory to dump the cache. - */ - public void reset() { - clear(); - } - - /** - * Called to load cache object from data source, when not found in cache. - * - * @param key cache key - * @param x uv x coordinate - * @param y uv y coordinate - * @param zoomLevel zoom level for tile to load - * @param proj passed solely to enable checking if the projection of the - * tiles matches the rendered projection. - * @return CacheObject returned from cache, null if not found - */ - public CacheObject load(Object key, int x, int y, int zoomLevel, Projection proj) { - if (key instanceof String) { - String imagePath = (String) key; - if (verbose) { - logger.fine("fetching file for cache: " + imagePath); - } - - try { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - if (imageURL != null) { - - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - OMGraphic raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - - if (raster != null) { - return new CacheObject(imagePath, raster); - } - - } else { - logger.fine("Can't find resource located at " + imagePath); - } - } catch (MalformedURLException e) { - logger.fine("Can't find resource located at " + imagePath); - } catch (InterruptedException e) { - logger.fine("Reading the image file was interrupted: " + imagePath); - } catch (Exception fnfe) { - logger.fine("file not found: " + imagePath); - } - } - return null; - } - - /** - * Creates an OMRaster appropriate for projection and other parameters from - * a buffered image. - * - * @param bi BufferedImage to use for tile. - * @param x x uv coordinate for tile. - * @param y y uv coordinate for tile. - * @param zoomLevel zoom level for tile. - * @param proj the current map projection - * @return OMGraphic (OMScalingRaster or OMWarpingImage, most likely) - * @throws InterruptedException - */ - protected OMGraphic createOMGraphicFromBufferedImage(BufferedImage bi, int x, int y, - int zoomLevel, Projection proj) - throws InterruptedException { - - OMGraphic raster = null; - - if (bi != null) { - BufferedImage rasterImage = preprocessImage(bi, bi.getWidth(), bi.getHeight()); - - if (proj instanceof Mercator) { - raster = getTileMatchingProjectionType(rasterImage, x, y, zoomLevel); - } else { - raster = getTileNotMatchingProjectionType(rasterImage, x, y, zoomLevel); - } - - if (mapTileLogger.isLoggable(Level.FINE)) { - raster.putAttribute(OMGraphic.LABEL, new OMTextLabeler("Tile: " + zoomLevel + "|" - + x + "|" + y, OMText.JUSTIFY_CENTER)); - raster.setSelected(true); - } - } - - return raster; - } - - /** - * Create an OMScalingRaster that matches the basic projection of the - * current map. Only scales evenly for the opposite corner points. - * - * @param image BufferedImage created from tile file - * @param x uv x coordinate - * @param y uv y coordinate - * @param zoomLevel zoom level for tile retrieval - * @return OMGraphic, but really an OMScalingRaster. - */ - protected OMGraphic getTileMatchingProjectionType(BufferedImage image, int x, int y, - int zoomLevel) { - - Point2D pnt = new Point2D.Double(); - pnt.setLocation(x, y); - Point2D tileUL = mtcTransform.tileUVToLatLon(pnt, zoomLevel); - pnt.setLocation(x + 1, y + 1); - Point2D tileLR = mtcTransform.tileUVToLatLon(pnt, zoomLevel); - if (verbose) { - logger.fine("tile coords: " + tileUL + ", " + tileLR); - } - - double x1 = Math.min(tileUL.getX(), tileLR.getX()); - double x2 = Math.max(tileUL.getX(), tileLR.getX()); - double y1 = Math.min(tileUL.getY(), tileLR.getY()); - double y2 = Math.max(tileUL.getY(), tileLR.getY()); - - return new OMScalingRaster(y2, x1, y1, x2, image); - } - - /** - * Create an OMWarpingImage that knows how to re-project itself for - * different projections. The base projection is going to be defined for the - * mtc transform set on the factory. Warping images are slower to generate - * for a map projection than scaling rasters. - * - * @param image - * @param x - * @param y - * @param zoomLevel - * @return OMGraphic, but really an OMWarpingImage - */ - protected OMGraphic getTileNotMatchingProjectionType(BufferedImage image, int x, int y, - int zoomLevel) { - - DataBounds dataBounds = new DataBounds(new Point(x, y), new Point(x + 1, y + 1)); - dataBounds.setyDirUp(mtcTransform.isYDirectionUp()); - - return new OMWarpingImage(image, mtcTransform.getTransform(zoomLevel), dataBounds); - } - - /** - * Method that allows subclasses to modify the image as necessary before it - * is passed into an OMGraphic. - * - * @param origImage Any java Image - * @param imageWidth pixel width - * @param imageHeight pixel height - * @return BufferedImage with any changes necessary. - * @throws InterruptedException - */ - protected BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException { - - return getTileImagePreparer().preprocessImage(origImage, imageWidth, imageHeight); - } - - /** - * The main call to retrieve something from the cache, modified to allow - * load method to do some projection calculations to initialize tile - * parameters. If the object is not found in the cache, then load is called - * to get it from the data source. - * - * @param key cache key, usually string of location of a tile - * @param x uv x location of tile - * @param y uv y location of tile - * @param zoomLevel zoom level of tile - * @param proj passed solely to enable checking if the projection of the - * tiles matches the rendered projection. - * @return object from cache. - */ - public Object get(Object key, int x, int y, int zoomLevel, Projection proj) { - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - ret = load(key, x, y, zoomLevel, proj); - if (ret == null) { - return null; - } - - replaceLeastUsed(ret); - return ret.obj; - } - - /** - * An auxiliary call to retrieve something from the cache, modified to allow - * load method to do some projection calculations to initialize tile - * parameters. If the object is not found in the cache, null is returned. - * - * @param key cache key, usually string of location of a tile - * @param x uv x location of tile - * @param y uv y location of tile - * @param zoomLevel zoom level of tile - * @return cache object if found, null if not. - */ - public Object getFromCache(Object key, int x, int y, int zoomLevel) { - CacheObject ret = searchCache(key); - if (ret != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("found tile (" + x + ", " + y + ") in cache"); - } - return ret.obj; - } - - return null; - } - - /** - * Call to make when you want the tile factory to create some empty tile - * representation for the given location. You can return any type of - * OMGraphic embedded in a CacheObject. - * - * @param key the cache key for this object - * @param x the uv x coordinate of the tile - * @param y the uv y coordinate of the tile - * @param zoomLevel the zoom level for the tile - * @param proj the projection being used for the map. - * @return CacheObject, or null if the empty tile should be blank. - */ - public CacheObject getEmptyTile(Object key, int x, int y, int zoomLevel, Projection proj) { - - getTileImagePreparer().prepareForEmptyTile(this); - - EmptyTileHandler empTileHandler = getEmptyTileHandler(); - if (empTileHandler != null) { - - BufferedImage bi = empTileHandler.getImageForEmptyTile((String) key, x, y, zoomLevel, mtcTransform, proj); - - OMGraphic raster; - try { - raster = createOMGraphicFromBufferedImage(bi, x, y, zoomLevel, proj); - if (raster != null) { - - if (mapTileLogger.isLoggable(Level.FINE)) { - Object labelObj = raster.getAttribute(OMGraphic.LABEL); - if (labelObj instanceof OMTextLabeler) { - OMTextLabeler label = (OMTextLabeler) labelObj; - label.setData("EMPTY " + label.getData()); - } - } - - return new CacheObject(key, raster); - } - - } catch (InterruptedException e) { - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - } - } - return null; - } - - /** - * Returns projected tiles for the given projection. - * - * @param proj the projection to fetch tiles for. - * @return OMGraphicList containing projected OMGraphics. - */ - public OMGraphicList getTiles(Projection proj) { - return getTiles(proj, -1, new OMGraphicList()); - } - - /** - * Returns projected tiles for given projection at specified zoom level. - * - * @param proj projection for query - * @param zoomLevel zoom level 1-20 for tiles to be returned, -1 for code to - * figure out appropriate zoom level. - * @return OMGraphicList with tiles. - */ - public OMGraphicList getTiles(Projection proj, int zoomLevel) { - return getTiles(proj, zoomLevel, new OMGraphicList()); - } - - protected Projection lastProj; - - /** - * Returns projected tiles for given projection at specified zoom level. Use - * this call if you are providing a repaint callback component to the - * factory, so you will have a handle on the OMGraphicList to render to. - * - * @param proj projection for query - * @param zoomLevel zoom level 1-20 for tiles to be returned, -1 for code to - * figure out appropriate zoom level. - * @param list OMGraphicList that is returned, that will also have tiles - * added to it. - * @return OMGraphicList with tiles. - */ - public OMGraphicList getTiles(Projection proj, int zoomLevel, OMGraphicList list) { - String fExt = getFileExt(); - if (fExt == null || rootDir == null) { - logger.warning("No path to tile files provided (" + rootDir + "), or file extension (" - + fExt + ") not specified"); - return list; - } - - if (lastProj == null || !proj.getClass().isAssignableFrom(lastProj.getClass())) { - logger.fine("Clearing out cache for new projection type"); - clear(); // empty the cache to rebuild OMGraphics for different type - // projection. - } - - lastProj = proj; - - /** - * Given a projection, a couple of things have to happen. - * - * - First, we need to figure out what zoom level fits us best if it is - * not specified. - * - * - Second, we need to figure out the uv bounds that fit the - * projection. - * - * - Third, we need to grab the images for uv grid, by cycling through - * the limits in both directions. - * - * The TileMaker static methods let us convert uv to lat/lon and back, a - * ZoomLevelInfo object can be used to figure out what the file path - * looks like. - */ - if (zoomLevel < 0) { - zoomLevel = mtcTransform.getZoomLevelForProj(proj, zoomLevelTileSize); - if (verbose) { - logger.fine("Best zoom level calculated at: " + zoomLevel); - } - } - - if (zoomLevel >= 0) { - - if (zoomLevel == 0) { - zoomLevel++; - } - - zoomLevelInfo.setZoomLevel(zoomLevel); - - Point2D upperLeft = proj.getUpperLeft(); - Point2D lowerRight = proj.getLowerRight(); - - int[] uvBounds = mtcTransform.getTileBoundsForProjection(upperLeft, lowerRight, zoomLevel); - int uvup = uvBounds[0]; - int uvleft = uvBounds[1]; - int uvbottom = uvBounds[2]; - int uvright = uvBounds[3]; - - if (verbose) { - logger.fine("for " + proj + ", fetching tiles between x(" + uvleft + ", " + uvright - + ") y(" + uvup + ", " + uvbottom + ")"); - } - - // dateline test - Point2D datelinePnt = proj.forward(new LatLonPoint.Double(upperLeft.getY(), 180d)); - double dlx = datelinePnt.getX(); - boolean dateline = dlx > 0 & dlx < proj.getWidth(); - logger.fine("Long(180) located at " + dlx); - - if (!dateline) { - getTiles(uvleft, uvright, uvup, uvbottom, zoomLevelInfo, proj, list); - } else { - logger.fine("handling DATELINE"); - getTiles(uvleft, (int) Math.pow(2, zoomLevel), uvup, uvbottom, zoomLevelInfo, proj, list); - getTiles(0, uvright, uvup, uvbottom, zoomLevelInfo, proj, list); - } - - } - return list; - } - - /** - * A temporary object used to store information about map tiles that are not - * found in the cache. The caching mechanism has been modified to search for - * cached tiles first, and using this object to hold information about map - * tiles that need to be loaded. The cached tiles will be immediately - * displayed, and then these tiles will be displayed after that as they are - * loaded. - * - * @author dietrick - */ - class LoadObj { - String imagePath; - int x; - int y; - int zoomLevel; - - LoadObj(String p, int x, int y, int z) { - this.imagePath = p; - this.x = x; - this.y = y; - this.zoomLevel = z; - } - } - - protected void getTiles(int uvleft, int uvright, int uvup, int uvbottom, - ZoomLevelInfo zoomLevelInfo, Projection proj, OMGraphicList list) { - if (verbose) { - logger.fine("for zoom level: " + zoomLevelInfo.getZoomLevel() - + ", screen covers uv coords [t:" + uvup + ", l:" + uvleft + ", b:" + uvbottom - + ", r:" + uvright + "]"); - } - - if (zoomLevelInfo.getZoomLevel() == 0) { - logger.fine("got one tile, OM can't draw a single tile covering the earth. Sorry."); - } - - List reloads = new ArrayList(); - int zoomLevel = zoomLevelInfo.getZoomLevel(); - - int uvleftM = (int) Math.min(uvleft, uvright); - int uvrightM = (int) Math.max(uvleft, uvright); - int uvupM = (int) Math.min(uvbottom, uvup); - int uvbottomM = (int) Math.max(uvbottom, uvup); - - for (int x = uvleftM; x < uvrightM; x++) { - for (int y = uvupM; y < uvbottomM; y++) { - - if (mapTileRequester != null && !mapTileRequester.shouldContinue()) { - return; - } - - String imagePath = buildCacheKey(x, y, zoomLevel, getFileExt()); - - /** - * Need to modify the action of the cache a little to make the - * map appear more responsive. So, we cycle through the desired - * tiles, gathering all of the tiles that are immediately - * available. Generate them, add them to list, and call repaint - * when they are set. - * - * Keep track of the ones that are not there, and load those - * one-by-one after, calling repaint as they are added to the - * list. - */ - OMGraphic tileGraphic = (OMGraphic) getFromCache(imagePath, x, y, zoomLevel); - - if (tileGraphic != null) { - - if (mapTileLogger.isLoggable(Level.FINE)) { - tileGraphic.putAttribute(OMGraphic.LABEL, new OMTextLabeler("Tile: " - + zoomLevel + "|" + x + "|" + y, OMText.JUSTIFY_CENTER)); - tileGraphic.setSelected(true); - } - - tileGraphic.generate(proj); - list.add(tileGraphic); - } else { - reloads.add(new LoadObj(imagePath, x, y, zoomLevel)); - } - } - } - - if (verbose) { - logger.fine("found " + list.size() + " frames in cache, loading " + reloads.size() - + " others now..."); - } - - if (mapTileRequester != null) { - mapTileRequester.listUpdated(); - } - - /* - * Load the tiles that are not already in the cache, that need to be - * fetched from the source. - */ - for (LoadObj reload : reloads) { - // Check and see of we should bother fetching the new tile. - if (mapTileRequester != null && !mapTileRequester.shouldContinue()) { - return; - } - - loadTile(reload.imagePath, reload.x, reload.y, reload.zoomLevel, proj, list); - - // OK, got it, notify requester the list has been updated. - if (mapTileRequester != null) { - mapTileRequester.listUpdated(); - } - } - - if (verbose) { - logger.fine("finished loading " + reloads.size() + " frames from source for screen" - + (doExtraTiles ? ", moving to off-screen frames..." : "")); - } - - if (!doExtraTiles) { - return; - } - - // Just for giggles, lets go ahead and walk around the edge of the area - // and prefetch tiles to load them into memory... - - // int uvleft, int uvright, int uvup, int uvbottom - int x1 = uvleft; - int y1 = uvup; - int x2 = uvright; - int y2 = uvbottom; - boolean top = false; - boolean left = false; - boolean right = false; - boolean bottom = false; - if (x1 > 0) { - x1--; - left = true; - } - if (y1 > 0) { - y1--; - top = true; - } - int edgeTileCount = zoomLevelInfo.getEdgeTileCount(); - if (x2 < edgeTileCount - 1) { - x2++; - right = true; - } - if (y2 < edgeTileCount - 1) { - y2++; - bottom = true; - } - - // Get the corners - if (top && left) { - loadTile(x1, y1, zoomLevel, proj, list); - } - if (bottom && left) { - loadTile(x1, y2, zoomLevel, proj, list); - } - if (bottom && right) { - loadTile(x2, y2, zoomLevel, proj, list); - } - if (top && right) { - loadTile(x2, y1, zoomLevel, proj, list); - } - // Now go along the sides - if (top) { - for (int x = uvleft; x < uvright; x++) { - loadTile(x, y1, zoomLevel, proj, list); - } - } - - if (bottom) { - for (int x = uvleft; x < uvright; x++) { - loadTile(x, y2, zoomLevel, proj, list); - } - } - - if (right) { - for (int y = uvup; y < uvbottom; y++) { - loadTile(x2, y, zoomLevel, proj, list); - } - } - - if (left) { - for (int y = uvup; y < uvbottom; y++) { - loadTile(x1, y, zoomLevel, proj, list); - } - } - - if (verbose) { - logger.fine("finished loading all tiles (" + list.size() + ")"); - } - } - - /** - * Handles going to the cache, getting the cache to load the tile, and then - * manage the resulting OMRaster tile. Adds the tile to the list after - * generating it with the projection, and calls the repaintCallback if there - * is one. - * - * @param imagePath the image path for the tile - * @param x the x uv coordinate of the tile - * @param y the y uv coordinate of the tile - * @param zoomLevel the zoomLevel of the tile - * @param proj the current projection. - * @param list the OMGraphicList to add the tile to. - * @throws InterruptedException - */ - private void loadTile(String imagePath, int x, int y, int zoomLevel, Projection proj, - OMGraphicList list) { - - CacheObject ret = load(imagePath, x, y, zoomLevel, proj); - if (ret == null) { - - // Check if the factory wants to do anything for empty tiles. - ret = getEmptyTile(imagePath, x, y, zoomLevel, proj); - } - - if (ret != null) { - replaceLeastUsed(ret); - OMGraphic raster = (OMGraphic) ret.obj; - - if (raster != null) { - - raster.generate(proj); - list.add(raster); - - if (logger.isLoggable(Level.FINE)) { - raster.putAttribute(OMGraphic.TOOLTIP, imagePath); - } - } - } - } - - /** - * Handles going to the cache, getting the cache to load the tile, and then - * manage the resulting OMRaster tile. Adds the tile to the list after - * generating it with the projection, and calls the repaintCallback if there - * is one. Handles creating the image file path given the other info. - * - * @param x the x uv coordinate of the tile - * @param y the y uv coordinate of the tile - * @param zoomLevel the zoomLevel of the tile - * @param proj the current projection. - * @param list the OMGraphicList to add the tile to. - * @throws InterruptedException - */ - private void loadTile(int x, int y, int zoomLevel, Projection proj, OMGraphicList list) { - // String imagePath = zoomLevelInfo.formatImageFilePath(rootDir, x, y) + - // fileExt; - String imagePath = buildFilePath(x, y, zoomLevel, getFileExt()); - loadTile(imagePath, x, y, zoomLevel, proj, list); - } - - /** - * Build an image path to load, based on specified tile coordinates, zoom - * level and file extension settings. - * - * Look at the root directory definition and determine if the x,y,z values - * of the path are specified as the holder values {z}, {x} and {y}. - * - * If they aren't specified, the provided values will be appended to the - * rootDir as z/x/y.fileExt. - * - * If {z}, {x} or {y} are found in the root dir path, then it's assumed that - * the rootDir contains all the information needed to specify the path and - * regular expressions will be used to replace those value holders with the - * values specified. The file extension in this case will not be appended to - * the rootDir. - * - * @param x the x tile coordinate - * @param y the y tile coordinate - * @param z the zoom level - * @param fileExt the file extension to use for the path. - */ - public String buildFilePath(int x, int y, int z, String fileExt) { - TilePathBuilder pathBuilder = getTilePathBuilder(); - if (pathBuilder == null) { - pathBuilder = new TilePathBuilder(rootDir); - setTilePathBuilder(pathBuilder); - } - - return pathBuilder.buildTilePath(x, y, z, fileExt); - } - - private TilePathBuilder tilePathBuilder = null; - - protected void setTilePathBuilder(TilePathBuilder tpb) { - tilePathBuilder = tpb; - } - - protected TilePathBuilder getTilePathBuilder() { - return tilePathBuilder; - } - - /** - * Creates a unique cache key for this tile based on zoom, x, y. This method - * was created so the ServerMapTileFactory could override it and use local - * cache names for keys if a local cache was being used. - * - * @param x tile coord. - * @param y tile coord. - * @param z zoomLevel. - * @param fileExt file extension. - * @return String used in cache. - */ - protected String buildCacheKey(int x, int y, int z, String fileExt) { - return buildFilePath(x, y, z, fileExt); - } - - public static class TilePathBuilder { - String rez = "(\\{z\\})"; // Curly Braces 1 - String rex = "(\\{x\\})"; // Curly Braces 2 - String rey = "(\\{y\\})"; // Curly Braces 3 - - Pattern pz = Pattern.compile(rez, Pattern.CASE_INSENSITIVE); - Pattern px = Pattern.compile(rex, Pattern.CASE_INSENSITIVE); - Pattern py = Pattern.compile(rey, Pattern.CASE_INSENSITIVE); - - String startingPath; - boolean patternsUsed = false; - boolean patternUseChecked = false; - - public TilePathBuilder(String rootDir) { - startingPath = rootDir; - } - - public boolean isPatternsUsed() { - return patternsUsed; - } - - public String buildTilePath(int x, int y, int z, String fileExt) { - String ret = startingPath; - if (((!patternUseChecked) || (patternUseChecked && patternsUsed)) - && startingPath != null && startingPath.length() != 0) { - ret = updatePath(ret, pz, Integer.toString(z)); - ret = updatePath(ret, px, Integer.toString(x)); - ret = updatePath(ret, py, Integer.toString(y)); - patternUseChecked = true; - } - - if (!patternsUsed) { - // No pattern matching, need to build from scratch, with fileExt - return buildDefaultTilePath(x, y, z, fileExt); - } - - return ret; - } - - private String buildDefaultTilePath(int x, int y, int z, String fileExt) { - return startingPath + "/" + z + "/" + x + "/" + y + fileExt; - } - - private String updatePath(String currentPath, Pattern p, String replaceWith) { - Matcher m = p.matcher(currentPath); - if (m.find()) { - patternsUsed = true; - return m.replaceAll(replaceWith); - } - return currentPath; - } - } - - public MapTileRequester getMapTileRequester() { - return mapTileRequester; - } - - public void setMapTileRequester(MapTileRequester mtRequestor) { - this.mapTileRequester = mtRequestor; - } - - public Properties getProperties(Properties getList) { - String prefix = PropUtils.getScopedPropertyPrefix(this); - getList.put(prefix + ROOT_DIR_PROPERTY, PropUtils.unnull(rootDirProperty)); - getList.put(prefix + FILE_EXT_PROPERTY, PropUtils.unnull(getFileExt())); - getList.put(prefix + CACHE_SIZE_PROPERTY, Integer.toString(getCacheSize())); - getList.put(prefix + MTCTRANSFORM_PROPERTY, mtcTransform.getClass().toString()); - if (emptyTileHandler != null) { - getList.put(prefix + EMPTY_TILE_HANDLER_PROPERTY, emptyTileHandler.getClass().toString()); - if (emptyTileHandler instanceof PropertyConsumer) { - ((PropertyConsumer) emptyTileHandler).getProperties(getList); - } - } - - // Only save the zoomLevelInfo property if it's not the default. - if (zoomLevelInfo != null && !zoomLevelInfo.getClass().equals(ZoomLevelInfo.class)) { - getList.put(prefix + ZOOM_LEVEL_INFO_PROPERTY, zoomLevelInfo.getClass().getName()); - } - - getList.put(prefix + ZOOM_LEVEL_TILE_SIZE_PROPERTY, Integer.toString(zoomLevelTileSize)); - TileImagePreparer tip = getTileImagePreparer(); - if (!(tip instanceof StandardImagePreparer)) { - getList.put(prefix + TILE_IMAGE_PREPARER_PROPERTY, tip.getClass().getName()); - if (tip instanceof PropertyConsumer) { - ((PropertyConsumer) tip).getProperties(getList); - } - } - - return getList; - } - - public Properties getPropertyInfo(Properties list) { - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, ROOT_DIR_PROPERTY, "Tile URL or Path", "Root directory containing image tiles, or URL (http://tileserver/{z}/{x}/{y}.png)", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, FILE_EXT_PROPERTY, "Image File Extension", "Extension of image files (.jpg, .png, etc)", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, CACHE_SIZE_PROPERTY, "Cache Size", "Number of tile images held in memory", null); - PropUtils.setI18NPropertyInfo(i18n, list, com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory.class, ZOOM_LEVEL_TILE_SIZE_PROPERTY, "Zoom Level Tile Size", "The maximum pixel size of a tile before switching to a higher zoom level (350 is default)", null); - return list; - } - - public String getInitPropertiesOrder() { - return ROOT_DIR_PROPERTY + " " + FILE_EXT_PROPERTY; - } - - public String getPropertyPrefix() { - return prefix; - } - - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String rootDirectory = setList.getProperty(prefix + ROOT_DIR_PROPERTY); - if (rootDirectory != null) { - setRootDir(rootDirectory); - } - - String tmpFileExt = setList.getProperty(prefix + FILE_EXT_PROPERTY, getFileExt()); - - // Add a period if it doesn't exist. - if (tmpFileExt != null) { - setFileExt(tmpFileExt); - } - - String mapTileCoordinateTransform = setList.getProperty(prefix + MTCTRANSFORM_PROPERTY); - if (mapTileCoordinateTransform != null) { - Object obj = ComponentFactory.create(mapTileCoordinateTransform); - - if (obj instanceof MapTileCoordinateTransform) { - setMtcTransform((MapTileCoordinateTransform) obj); - } - } - - String emptyTileHandlerString = setList.getProperty(prefix + EMPTY_TILE_HANDLER_PROPERTY); - if (emptyTileHandlerString != null) { - Object obj = ComponentFactory.create(emptyTileHandlerString, prefix, setList); - - if (obj instanceof EmptyTileHandler) { - setEmptyTileHandler((EmptyTileHandler) obj); - } - } - - String zoomLevelInfoString = setList.getProperty(prefix + ZOOM_LEVEL_INFO_PROPERTY); - if (zoomLevelInfoString != null) { - Object obj = ComponentFactory.create(zoomLevelInfoString, prefix, setList); - - if (obj instanceof ZoomLevelInfo) { - setZoomLevelInfo((ZoomLevelInfo) obj); - } - } - - String tileImagePreparerString = setList.getProperty(prefix + TILE_IMAGE_PREPARER_PROPERTY); - if (tileImagePreparerString != null) { - Object obj = ComponentFactory.create(tileImagePreparerString, prefix, setList); - if (obj instanceof TileImagePreparer) { - setTileImagePreparer((TileImagePreparer) obj); - } - } - - super.resetCache(PropUtils.intFromProperties(setList, prefix + CACHE_SIZE_PROPERTY, getCacheSize())); - - zoomLevelTileSize = PropUtils.intFromProperties(setList, prefix - + ZOOM_LEVEL_TILE_SIZE_PROPERTY, zoomLevelTileSize); - } - - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - public String getRootDir() { - return rootDir; - } - - public void setRootDir(String rootDirectory) { - - if (rootDirectory != null) { - if (rootDirectory.endsWith("jar")) { - - rootDirProperty = rootDirectory; - String jarFileNames = rootDirectory; - // Only use the tiles.omp file in the first file found. - boolean tilesFileFound = false; - - Vector jarNames = PropUtils.parseMarkers(jarFileNames, ";"); - for (String jarName : jarNames) { - - boolean jarFileFound = false; - - try { - - if (!tilesFileFound) { - URL jarURL = PropUtils.getResourceOrFileOrURL(jarName); - - if (jarURL != null) { - jarFileFound = true; - JarInputStream jarStream = new JarInputStream(jarURL.openStream()); - JarEntry jarEntry = null; - - while ((jarEntry = jarStream.getNextJarEntry()) != null) { - String entryName = jarEntry.getName(); - if (entryName.equals(TILE_PROPERTIES)) { - byte[] readBytes = new byte[100]; - byte[] contentBytes = new byte[0]; - - int numRead = 0; - while ((numRead = jarStream.read(readBytes, 0, readBytes.length)) > 0) { - byte[] tmpBytes = new byte[numRead - + contentBytes.length]; - System.arraycopy(contentBytes, 0, tmpBytes, 0, contentBytes.length); - System.arraycopy(readBytes, 0, tmpBytes, contentBytes.length, numRead); - - contentBytes = tmpBytes; - } - - ByteArrayInputStream bais = new ByteArrayInputStream(contentBytes); - configureFromProperties(bais, rootDirectory); - bais.close(); - - jarStream.closeEntry(); - tilesFileFound = true; - break; - } - } - - jarStream.close(); - } - } - - if (jarFileFound) { - logger.fine("adding " + jarName + " to classpath"); - ClasspathHacker.addFile(jarName); - } else { - logger.fine("can't find " + jarName + ", not adding to classpath"); - } - - // JarFile jarFile = new JarFile(jarName); - // JarEntry jarPropertyFile = (JarEntry) - // jarFile.getEntry(TILE_PROPERTIES); - // - // if (jarPropertyFile != null) { - // InputStream is = - // jarFile.getInputStream(jarPropertyFile); - // configureFromProperties(is, rootDirectory); - // } - - } catch (IOException ioe) { - logger.warning("couldn't add map data jar file: " + jarName); - } - - } - - // You might notice that we didn't set the rootDir here if a jar - // file is being used. That's because we just want to use - // whatever - // the tile file says, and this method will be called again if - // needed when the properties get written. - - } else { - // check for tile.omp file that may describe how to read tiles. - File tileProps = new File(rootDirectory, TILE_PROPERTIES); - - // Keep track of what the root directory was before we read - // tiles.omp - String currentRootDirectory = this.rootDir; - String currentRootDirProperty = rootDirProperty; - if (tileProps.exists()) { - try { - // Do this in case other properties are set for the tile - // set, file ext, transform. - configureFromProperties(tileProps.toURI().toURL().openStream(), rootDirectory); - } catch (MalformedURLException murle) { - logger.warning("tile file for " + rootDirectory + " couldn't be read: " - + tileProps.getAbsolutePath()); - } catch (IOException ioe) { - logger.warning("tile file for " + rootDirectory + " couldn't be read"); - } - } - - /* - * OK, things look a little crazy here, because there is a bit - * of recursion going on. The configure call above may cause a - * setRootDir call with a relative path stored in a jar file. - * These rules below make sure the relative root dir from the - * inner loop sets the rootDir, while preserving the - * rootDirProperty from the outer loop. - */ - - if (currentRootDirectory == null && this.rootDir == null) { - // the tiles.omp file didn't change the root directory, so - // lets go with the directory given. - this.rootDir = rootDirectory; - } - - if (currentRootDirProperty == null) { - // Assuming a file path being set, not as a result of a jar - // file - rootDirProperty = rootDirectory; - } - } - - } else { - // nulled out - this.rootDir = rootDirectory; - rootDirProperty = rootDirectory; - } - - // Reset for new path - tilePathBuilder = null; - - } - - public TileImagePreparer getTileImagePreparer() { - if (tileImagePreparer == null) { - tileImagePreparer = new StandardImagePreparer(); - } - return tileImagePreparer; - } - - public void setTileImagePreparer(TileImagePreparer tileImagePreparer) { - this.tileImagePreparer = tileImagePreparer; - } - - /** - * Called with an input stream for a properties file, used for reading - * tiles.omp files. - * - * @param is input stream for tiles.omp file. - * @param rootDirectory original path to what was specified as root - * directory - * @throws IOException - */ - protected void configureFromProperties(InputStream is, String rootDirectory) throws IOException { - - Properties props = new Properties(); - props.load(is); - - props.put(ROOT_DIR_PATH_PROPERTY, rootDirectory); - - String oldPrefix = getPropertyPrefix(); - setProperties(null, props); - setPropertyPrefix(oldPrefix); - } - - public String getFileExt() { - return fileExt; - } - - public void setFileExt(String fileExt) { - this.fileExt = (fileExt != null && fileExt.startsWith(".")) ? fileExt : "." + fileExt; - } - - /** - * Get the ZoomLevelInfo set on the factory. The ZoomLevelInfo has basic - * layout information about tiles for a particular zoom level, including how - * tiles are named and how the factory should go about loading them. The - * default ZoomLevelInfo is based on the OpenStreetMap tile layout, zoom - * levels 0-20 (where level 0 is all the way zoomed out), and the tiles are - * stored zoomLevel/x/y.(fileExt). - * - * @return the zoomLevelInfo - */ - public ZoomLevelInfo getZoomLevelInfo() { - return zoomLevelInfo; - } - - /** - * Get the ZoomLevelInfo set on the factory. The ZoomLevelInfo has basic - * layout information about tiles for a particular zoom level, including how - * tiles are named and how the factory should go about loading them. The - * default ZoomLevelInfo is based on the OpenStreetMap tile layout, zoom - * levels 0-20 (where level 0 is all the way zoomed out), and the tiles are - * stored zoomLevel/x/y.(fileExt). You can set a different zoom level info - * if you want to work with a tile set that is stored/defined differently - * than OSM. - *

- * Won't allow itself to be set to null. - * - * @param zoomLevelInfo the zoomLevelInfo to set - */ - public void setZoomLevelInfo(ZoomLevelInfo zoomLevelInfo) { - if (zoomLevelInfo != null) { - this.zoomLevelInfo = zoomLevelInfo; - } - } - - public MapTileCoordinateTransform getMtcTransform() { - return mtcTransform; - } - - /** - * Set the map tile coordinate transformed used to figure out lat/lon to - * tile coordinates. Can't be null, if you set it to null an - * OSMMapTileCoordTransform will be created instead. - * - * @param mtcTransform - */ - public void setMtcTransform(MapTileCoordinateTransform mtcTransform) { - if (mtcTransform == null) { - mtcTransform = new OSMMapTileCoordinateTransform(); - } - this.mtcTransform = mtcTransform; - } - - /** - * @return the emptyTileHandler - */ - public EmptyTileHandler getEmptyTileHandler() { - return emptyTileHandler; - } - - /** - * @param emptyTileHandler the emptyTileHandler to set - */ - public void setEmptyTileHandler(EmptyTileHandler emptyTileHandler) { - this.emptyTileHandler = emptyTileHandler; - } -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java b/src/openmap/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java deleted file mode 100644 index b0c51db4c..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/mapTile/TileImagePreparer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * TileImagePreparer.java Jan 10, 2012 9:37:01 PM - */ - -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.Image; -import java.awt.image.BufferedImage; - -/** - * TODO: Describe the TileImagePreparer interface class here. - * - * @author dietrick - */ -public interface TileImagePreparer { - - /** - * Sometimes, based on the color handling of the preparer, empty tiles need to be handled differently. - * - * @param factory used to make calls on the factory to prepare for empty tile fetch. - */ - void prepareForEmptyTile(MapTileFactory factory); - - /** - * Method called to manipulate provided image in some way, returning modified image. - * - * @param origImage Any java Image - * @param imageWidth pixel width - * @param imageHeight pixel height - * @return BufferedImage with any changes necessary. - * @throws InterruptedException - */ - BufferedImage preprocessImage(Image origImage, int imageWidth, int imageHeight) - throws InterruptedException; -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java b/src/openmap/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java deleted file mode 100644 index ed0ae0a87..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/mapTile/ZoomLevelMakerFace.java +++ /dev/null @@ -1,660 +0,0 @@ -package com.bbn.openmap.dataAccess.mapTile; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.net.URL; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - -import javax.swing.AbstractListModel; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.ListSelectionModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.bbn.openmap.I18n; -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.gui.OMComponentPanel; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; - -/** - * A class that visually manages the settings for a ZoomLevelInfo object. Works - * inside the MapTileMakerComponent. - * - * @author dietrick - */ -public class ZoomLevelMakerFace extends OMComponentPanel { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.mapTile.ZoomLevelMakerFace"); - - private static final long serialVersionUID = 1L; - protected ZoomLevelMaker zfi; - boolean active = false; - boolean include = false; - - protected JList boundsList; - protected List boundsObjectList; - protected BoundsListModel boundsModel; - protected OMGraphicList boundaries = new OMGraphicList(); - - protected List layerList = new ArrayList(); - protected MapTileMakerComponent organizer; - - protected JPanel layerPanel; - protected JButton createBoundaryButton; - protected JButton editBoundaryButton; - protected JButton deleteBoundaryButton; - protected JLabel intro; - protected JLabel tileDimensions; - protected JButton scaleButton; - JSpinner rangeLevelChoice; - - @SuppressWarnings("serial") - public ZoomLevelMakerFace(ZoomLevelMaker zfi, MapTileMakerComponent mtmc) { - - this.zfi = zfi; - this.organizer = mtmc; - setLayout(new GridBagLayout()); - - JPanel introPanel = new JPanel(new GridBagLayout()); - - JLabel intro = new JLabel(i18n.get(ZoomLevelMakerFace.class, "zoom_level", "Make tiles for zoom levels")); - JLabel tileDimLabel = new JLabel(i18n.get(ZoomLevelMakerFace.class, "tile_dim", "Tile Dimensions")); - JLabel baseScaleLabel = new JLabel(i18n.get(ZoomLevelMakerFace.class, "base_scale", "Base Scale for Zoom Level")); - - JSpinner zoomLevelChoice = new JSpinner(new SpinnerNumberModel(0, 0, 20, 1.0)) { - public void setValue(Object value) { - if (value instanceof Number) { - value = new Double(((Number) value).intValue()); - } - super.setValue(value); - - updateZoomLevel(((Double) getValue()).intValue()); - } - }; - String upperZoomLevelTT = i18n.get(ZoomLevelMakerFace.class, "upper_zoom_level", I18n.TOOLTIP, "Upper zoom level"); - String lowerZoomLevelTT = i18n.get(ZoomLevelMakerFace.class, "lower_zoom_level", I18n.TOOLTIP, "Lower zoom level"); - zoomLevelChoice.setToolTipText(upperZoomLevelTT); - - tileDimensions = new JLabel(); - scaleButton = new JButton(); - scaleButton.setBorder(BorderFactory.createLineBorder(Color.GRAY)); - scaleButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - MapHandler mHandler = (MapHandler) organizer.getBeanContext(); - MapBean map = mHandler.get(MapBean.class); - map.setScale(getZoomLevelMaker().getScale()); - } - }); - - rangeLevelChoice = new JSpinner(new SpinnerNumberModel(0, 0, 20, 1.0)) { - public void setValue(Object value) { - if (value instanceof Number) { - int newVal = ((Number) value).intValue(); - int limit = getZoomLevelMaker().getZoomLevel(); - if (newVal > limit) { - newVal = limit; - } - value = new Double(newVal); - - getZoomLevelMaker().setRange(newVal); - } - super.setValue(value); - } - }; - rangeLevelChoice.setToolTipText(lowerZoomLevelTT); - - GridBagConstraints c = new GridBagConstraints(); - c.gridx = GridBagConstraints.REMAINDER; - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(0, 0, 0, 0); - - JPanel zoomHolder = new JPanel(); - zoomHolder.add(zoomLevelChoice, c); - zoomHolder.add(new JLabel(" to "), c); - zoomHolder.add(rangeLevelChoice, c); - - addIntroEntry(introPanel, intro, zoomHolder, 0, new Insets(0, 0, 0, 0)); - addIntroEntry(introPanel, tileDimLabel, tileDimensions, 1, new Insets(0, 0, 5, 0)); - addIntroEntry(introPanel, baseScaleLabel, scaleButton, 2, new Insets(0, 0, 5, 0)); - - updateZoomLevel(0); - add(introPanel, c); - - c.gridx = GridBagConstraints.REMAINDER; - c.anchor = GridBagConstraints.WEST; - - include = true; - - c.fill = GridBagConstraints.BOTH; - c.weightx = 1.0f; - - layerPanel = new JPanel(new GridBagLayout()); - setLayers(layerList); - - JPanel outerLayerPanel = new JPanel(new GridBagLayout()); - String layers_for_title = i18n.get(ZoomLevelMakerFace.class, "layers_for_title", "Layers"); - outerLayerPanel.setBorder(BorderFactory.createTitledBorder(layers_for_title)); - JScrollPane jsp = new JScrollPane(layerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - c.weighty = 1.0f; - c.insets = new Insets(0, 0, 0, 0); - outerLayerPanel.add(jsp, c); - c.weighty = .8f; - c.insets = new Insets(3, 0, 3, 0); - add(outerLayerPanel, c); - - JPanel boundsPanel = new JPanel(new BorderLayout()); - String boundaries_for_title = i18n.get(ZoomLevelMakerFace.class, "boundaries_for_title", "Boundaries"); - boundsPanel.setBorder(BorderFactory.createTitledBorder(boundaries_for_title)); - boundsObjectList = new ArrayList(); - boundsModel = new BoundsListModel(); - boundsList = new JList(boundsModel); - boundsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - boundsList.setLayoutOrientation(JList.VERTICAL); - boundsList.setVisibleRowCount(4); - boundsList.addListSelectionListener(new SelectionListener()); - boundsList.addMouseListener(new ListMouseListener()); - - JScrollPane scrollableBoundsList = new JScrollPane(boundsList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - boundsPanel.add(scrollableBoundsList, BorderLayout.CENTER); - - JPanel boundsButtonPanel = new JPanel(); - - ImageIcon ii = createImageIcon("add_16x16.png"); - createBoundaryButton = new JButton(ii); - String create_a_boundary_rectangle = i18n.get(ZoomLevelMakerFace.class, "create_a_boundary_rectangle", "Create a boundary rectangle"); - createBoundaryButton.setToolTipText(create_a_boundary_rectangle); - createBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - organizer.createRectangle(); - } - }); - boundsButtonPanel.add(createBoundaryButton); - - ii = createImageIcon("edit_16x16.png"); - editBoundaryButton = new JButton(ii); - String edit_a_selected_boundary_rectangle = i18n.get(ZoomLevelMakerFace.class, "edit_a_selected_boundary_rectangle", "Edit a selected boundary rectangle"); - editBoundaryButton.setToolTipText(edit_a_selected_boundary_rectangle); - editBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (boundsList.getSelectedIndex() != -1) { - BoundsObject selected = (BoundsObject) boundsList.getSelectedValue(); - organizer.edit(selected.bounds, null); - } - } - }); - boundsButtonPanel.add(editBoundaryButton); - - ii = createImageIcon("remov_16x16.png"); - deleteBoundaryButton = new JButton(ii); - String delete_a_selected_boundary_rectangle = i18n.get(ZoomLevelMakerFace.class, "delete_a_selected_boundary_rectangle", "Delete a selected boundary rectangle"); - deleteBoundaryButton.setToolTipText(delete_a_selected_boundary_rectangle); - deleteBoundaryButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (boundsList.getSelectedIndex() != -1) { - BoundsObject selected = (BoundsObject) boundsList.getSelectedValue(); - boundaries.remove(selected.bounds); - boundsObjectList.remove(selected); - boundsList.repaint(); - - if (organizer.drawingTool.isActivated()) { - organizer.drawingTool.deactivate(OMAction.DELETE_GRAPHIC_MASK); - } - - ((MapHandler) organizer.getBeanContext()).get(MapBean.class).repaint(); - } - } - }); - boundsButtonPanel.add(deleteBoundaryButton); - boundsPanel.add(boundsButtonPanel, BorderLayout.SOUTH); - c.weighty = .8f; - add(boundsPanel, c); - } - - protected void addIntroEntry(JPanel panel, JComponent left, JComponent right, int y, Insets i) { - GridBagConstraints c = new GridBagConstraints(); - - c.gridx = 0; - c.gridy = y; - c.weightx = 0; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.WEST; - c.insets = i; - - panel.add(left, c); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1f; - panel.add(Box.createHorizontalGlue(), c); - - c.gridx = 1; - c.fill = GridBagConstraints.NONE; - c.weightx = 0f; - c.anchor = GridBagConstraints.EAST; - panel.add(right, c); - } - - public void updateZoomLevel(int zoomLevel) { - DecimalFormat df = new DecimalFormat("000,000"); - zfi.setZoomLevel(zoomLevel); - - zfi.setScale(new OSMMapTileCoordinateTransform().getScaleForZoom(zoomLevel)); - - int etc = zfi.getEdgeTileCount(); - - tileDimensions.setText(etc + " x " + etc); - - String scale = "1:" + df.format(zfi.getScale()); - - scaleButton.setText(scale); - String tooltip = i18n.get(ZoomLevelMakerFace.class, "set_map_scale_to", I18n.TOOLTIP, "Set map scale to"); - scaleButton.setToolTipText(tooltip + " " + scale); - - Object obj = rangeLevelChoice.getValue(); - if (obj instanceof Number) { - int rangeVal = ((Number) obj).intValue(); - if (rangeVal > zoomLevel) { - rangeVal = zoomLevel; - rangeLevelChoice.setValue(new Integer(zoomLevel)); - zfi.setRange(rangeVal); - } - } - - } - - protected void enableBoundaryButtons(boolean setting) { - createBoundaryButton.setEnabled(setting); - - boolean somethingSelected = boundsList.getSelectedIndex() != -1; - - editBoundaryButton.setEnabled(setting && somethingSelected); - deleteBoundaryButton.setEnabled(setting && somethingSelected); - } - - /** - * Given a set of Layers, look at the internal list and make sure there are - * layer objects that match. Purges LayerObjects that don't represent - * layers, and adds LayerObjects as needed. Calls setLayers with - * LayerObjects. - * - * @param layers - */ - protected void setLayers(Layer[] layers) { - - List layerObjects = new ArrayList(); - - for (Layer layer : layers) { - boolean foundOne = false; - for (LayerObject lo : layerList) { - if (lo.getLayer().equals(layer)) { - foundOne = true; - layerObjects.add(lo); - break; - } - } - - if (!foundOne) { - layerObjects.add(new LayerObject(layer)); - } - } - - setLayers(layerObjects); - } - - /** - * Update the layer panel to have buttons for the layer objects. Doesn't do - * any checking, just adds them to the layerPanel, and adds the button that - * pushes this ZLIF's layer settings to all other layers. - * - * @param layerObjects - */ - protected void setLayers(List layerObjects) { - this.layerList = layerObjects; - - if (layerPanel == null) { - return; - } - - layerPanel.removeAll(); - GridBagConstraints c = new GridBagConstraints(); - c.gridx = GridBagConstraints.REMAINDER; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0f; - c.anchor = GridBagConstraints.WEST; - - for (LayerObject lo : layerObjects) { - - String layerMarker = lo.getLayer().getPropertyPrefix(); - if (layerMarker != null) { - lo.setSelected(zfi.getLayers().contains(layerMarker)); - } - - layerPanel.add(lo, c); - } - - c.fill = GridBagConstraints.BOTH; - c.weighty = 1.0f; - layerPanel.add(Box.createGlue(), c); - } - - /** - * Given a list of LayerObjects, make the visibility of the internal layers - * match the list. - * - * @param layerObjects - */ - protected void matchObjects(List layerObjects) { - - for (LayerObject lo : layerList) { - for (LayerObject toMatch : layerObjects) { - Layer matchedLayer = toMatch.getLayer(); - if (lo.getLayer().equals(matchedLayer)) { - - boolean turnOn = toMatch.isSelected(); - String layerMarker = matchedLayer.getPropertyPrefix(); - - lo.setSelected(turnOn); - - if (turnOn) { - if (!zfi.getLayers().contains(layerMarker)) { - zfi.getLayers().add(layerMarker); - } - } else { - zfi.getLayers().remove(layerMarker); - } - } - } - - setInclude(!zfi.getLayers().isEmpty()); - } - } - - public void matchBounds(List bounds) { - boundsModel.clear(); - boundaries.clear(); - - for (BoundsObject bo : bounds) { - BoundsObject copy = bo.clone(); - boundsModel.addElement(copy); - boundaries.add(bo.bounds); - } - } - - /** - * Whether this ZLIF is the active tab in the MapTileMakerComponent. - * - * @return true if face is active - */ - protected boolean isActive() { - return active; - } - - /** - * Set this as the active ZLIF in MapTileMakerComponent. - * - * @param active - */ - protected void setActive(boolean active) { - this.active = active; - } - - /** - * Whether this ZoomLevel should be used in the tile creation or skipped. - * - * @return if zoom level should be included in tile creation. - */ - public boolean isInclude() { - return include; - } - - /** - * Set whether this ZoomLevel should be used in the tile creation. - * - * @param include - */ - public void setInclude(boolean include) { - this.include = include; - // includeButton.setSelected(include); - } - - ZoomLevelMaker getZoomLevelMaker() { - return zfi; - } - - void setZoomLevelMaker(ZoomLevelMaker zfi) { - this.zfi = zfi; - } - - /** - * Called from MapTileMakerComponent if this is the active ZLIF when the - * drawing tool completes, assigning the boundary to this ZLIF (or whatever - * action is provided). - * - * @param omg - * @param action - */ - public void handleBoundary(OMGraphic omg, OMAction action) { - boundaries.doAction(omg, action); - - boundsModel.clear(); - int count = 1; - for (OMGraphic omr : boundaries) { - if (omr instanceof OMRect) { - String bounding_rectangle = i18n.get(ZoomLevelMakerFace.class, "bounding_rectangle", "Bounding Rectangle"); - boundsModel.addElement(new BoundsObject((OMRect) omr, bounding_rectangle + " " - + (count++))); - } - } - - } - - /** - * Called from the MapTileMakerComponent, so this ZLIF is ready to paint its - * boundaries if it is activated. - * - * @param proj Projection to use to render boundaries. - * @return true if boundaries can be generated for given projection - */ - protected boolean generate(Projection proj) { - if (boundaries != null) { - return boundaries.generate(proj); - } - return false; - } - - /** - * Called from the MapTileMakerComponent, when this is the active ZLIF so - * the current boundaries are painted on top of the map. - * - * @param graphics - */ - protected void paintBoundaries(Graphics graphics) { - if (boundaries != null) { - boundaries.render(graphics); - } - } - - /** - * Bounds list model for boundary JList. - * - * @author dietrick - */ - private final class BoundsListModel extends AbstractListModel { - private static final long serialVersionUID = 1L; - - public int getSize() { - return boundsObjectList.size(); - } - - public BoundsObject getElementAt(int index) { - return boundsObjectList.get(index); - } - - public void editElement(int index) { - fireContentsChanged(this, index, index); - } - - public void insertElement(BoundsObject obj, int index) { - boundsObjectList.add(index, obj); - fireIntervalAdded(this, index, index); - } - - public void addElement(BoundsObject obj) { - int index = getSize(); - boundsObjectList.add(obj); - fireIntervalAdded(this, index, index); - } - - public BoundsObject removeElementAt(int index) { - BoundsObject obj = boundsObjectList.remove(index); - fireIntervalRemoved(this, index, index); - return obj; - } - - public void clear() { - int size = boundsObjectList.size(); - boundsObjectList.clear(); - fireIntervalRemoved(this, 0, size); - } - } - - /** - * The list object used to represent a boundary. - * - * @author dietrick - */ - public class BoundsObject implements Cloneable { - protected OMRect bounds; - protected String name; - - public BoundsObject(OMRect rect, String displayName) { - bounds = rect; - name = displayName; - } - - public String toString() { - return name; - } - - public BoundsObject clone() { - OMRect copy = new OMRect(bounds.getNorthLat(), bounds.getWestLon(), bounds.getSouthLat(), bounds.getEastLon(), OMGraphic.LINETYPE_RHUMB); - DrawingAttributes atts = DrawingAttributes.getDefaultClone(); - atts.setFrom(bounds); - atts.setTo(copy); - return new BoundsObject(bounds, name); - } - } - - /** - * A component used to represent a layer/layer setting in the face. - * - * @author dietrick - */ - public class LayerObject extends JCheckBox { - private static final long serialVersionUID = 1L; - protected Layer layer; - - public LayerObject(Layer layer) { - super(layer.getName(), layer.isVisible()); - this.layer = layer; - addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String pp = getLayer().getPropertyPrefix(); - if (((JCheckBox) ae.getSource()).isSelected()) { - if (!zfi.getLayers().contains(pp)) { - zfi.getLayers().add(pp); - } - } else { - zfi.getLayers().remove(pp); - } - - if (active /* duh */&& organizer != null) { - organizer.shuffleLayers(ZoomLevelMakerFace.this); - setInclude(zfi.getLayers() != null && !zfi.getLayers().isEmpty()); - } - } - }); - } - - Layer getLayer() { - return layer; - } - - public String toString() { - return layer.getName(); - } - } - - /** - * A class that listens for selections on the boundary list. - * - * @author dietrick - */ - private final class SelectionListener implements ListSelectionListener { - - public void valueChanged(ListSelectionEvent e) { - if (!e.getValueIsAdjusting()) { - boolean somethingSelected = boundsList.getSelectedIndex() != -1; - editBoundaryButton.setEnabled(somethingSelected); - deleteBoundaryButton.setEnabled(somethingSelected); - } - } - } - - /** - * A class that listens for double-clicks on the boundary list, launching an - * editor for that rectangle. - * - * @author dietrick - */ - private class ListMouseListener extends MouseAdapter { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - int index = boundsList.locationToIndex(e.getPoint()); - if (index != -1) { - BoundsObject selected = (BoundsObject) boundsList.getSelectedValue(); - organizer.edit(selected.bounds, null); - } - } - } - } - - public ImageIcon createImageIcon(String path) { - URL imgURL = ZoomLevelMakerFace.class.getClassLoader().getResource("com/bbn/openmap/dataAccess/mapTile/" - + path); - if (imgURL != null) { - return new ImageIcon(imgURL); - } else { - System.err.println("Couldn't find file: " + path); - return null; - } - } -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/shape/DbfHandler.java b/src/openmap/com/bbn/openmap/dataAccess/shape/DbfHandler.java deleted file mode 100644 index bf71c88a0..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/shape/DbfHandler.java +++ /dev/null @@ -1,219 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: DbfHandler.java,v $ -//$Revision: 1.7 $ -//$Date: 2008/11/11 00:35:52 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.rule.IndexRule; -import com.bbn.openmap.omGraphics.rule.Rule; -import com.bbn.openmap.omGraphics.rule.RuleHandler; -import com.bbn.openmap.util.PropUtils; - -/** - * The DbfHandler manages OMGraphics based on DBF file settings. It uses Rules - * to evaluate DBF record information for each OMGraphic that is given to it, - * and can set rendering settings, labels, visibility and information text based - * on those rules. If rules aren't defined, then the dbf file won't be read for - * each entry and any evaluation attempt will just return the OMGraphic as it - * was provided. - * - *

- * Properties as an example used within the ShapeLayer: - * - *

- * 
- * neroads.class=com.bbn.openmap.layer.shape.ShapeLayer
- * neroads.prettyName=Roads
- * neroads.shapeFile=roads.shp
- * neroads.mouseModes=Gestures
- * # Rule marker names specified in space-separated list
- * neroads.rules=rule0 rule1
- * # global scale settings can be used so work is only performed within scale range of minScale/maxScale
- * neroads.maxScale=1000000f
- * 
- * # rule0 definition:
- * # CLASS_RTE is a DBF column name
- * neroads.rule0.key=CLASS_RTE
- * # operation, if key value is less than 2
- * neroads.rule0.op=lt
- * neroads.rule0.val=2
- * # If rule is met, then actions can be performed:
- * # Column names can be added together in a label by specifying them in a space-separated list
- * neroads.rule0.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * # Labels can have scale limits imposed, so they don't appear if map scale is 
- * # greater than maxScale or less than minScale
- * neroads.rule0.label.maxScale=1000000
- * # Visibility can be controlled with respect to scale as well
- * neroads.rule0.render=true
- * neroads.rule0.render.maxScale=1000000
- * # Rendering attributes can be specified.
- * neroads.rule0.lineColor=FFFA73
- * neroads.rule0.lineWidth=4
- * neroads.rule0.mattingColor=55AAAAAA
- * 
- * # rule1 definition:
- * neroads.rule1.key=CLASS_RTE
- * neroads.rule1.op=all
- * neroads.rule1.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * neroads.rule1.label.maxScale=200000
- * neroads.rule1.render=true
- * neroads.rule1.render.maxScale=500000
- * neroads.rule1.lineColor=FFFFFF
- * neroads.rule1.lineWidth=3
- * neroads.rule1.mattingColor=55AAAAAA
- * 
- * 
- * - * @author dietrick - */ -public class DbfHandler extends RuleHandler { - - protected DbfFile dbf; - protected List rules; - protected DrawingAttributes defaultDA; - - protected DbfHandler() { - defaultDA = new DrawingAttributes(); - } - - public DbfHandler(String dbfFilePath) throws IOException, FormatException { - this(new BinaryFile(dbfFilePath)); - } - - public DbfHandler(BinaryFile bf) throws IOException, FormatException { - this(); - dbf = new DbfFile(bf); - dbf.close(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - defaultDA.setProperties(prefix, props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - defaultDA.getProperties(props); - - return props; - } - - public DbfFile getDbf() { - return dbf; - } - - public void setDbf(DbfFile dbf) { - this.dbf = dbf; - } - - public DrawingAttributes getDefaultDA() { - return defaultDA; - } - - public void setDefaultDA(DrawingAttributes defaultDA) { - this.defaultDA = defaultDA; - } - - /** - * Tells the DbfFile to close the file pointer to the data. Will reopen if - * needed. - */ - public void close() { - if (dbf != null) { - dbf.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.omGraphics.RuleHandler#createRule() - */ - @Override - public Rule createRule() { - return new DbfRule(dbf); - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.omGraphics.RuleHandler#getRecordDataForOMGraphic(com. - * bbn.openmap.omGraphics.OMGraphic) - */ - @Override - public List getRecordDataForOMGraphic(OMGraphic omg) { - try { - return (List) dbf.getRecordData((Integer) omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE)); - } catch (IOException ioe) { - - } catch (FormatException fe) { - - } - return null; - } - - public class DbfRule extends IndexRule { - DbfFile dbf; - - public DbfRule(DbfFile dbf) { - this.dbf = dbf; - } - - /** - * A record List for the attributes of an OMGraphic might have a name - * for each entry. Given a name, provide the index into the List to get - * that attribute value. - * - * @param columnName name of a attribute in a List, like a column name - * of a list of lists. - * @return the int index of the entry in the record List. - */ - public int getRecordColumnIndexForName(String columnName) { - return dbf.getColumnIndexForName(columnName); - } - - /** - * Provide the title of the attribute at a specific entry. - * - * @param index into the record List. - * @return the record List name for that index. - */ - public String getRecordColumnName(int index) { - return dbf.getColumnName(index); - } - } - -} diff --git a/src/openmap/com/bbn/openmap/dataAccess/shape/DbfTableModel.java b/src/openmap/com/bbn/openmap/dataAccess/shape/DbfTableModel.java deleted file mode 100644 index dd4fe62c4..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/shape/DbfTableModel.java +++ /dev/null @@ -1,1225 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/openmap/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/DbfTableModel.java,v $ -// $RCSfile: DbfTableModel.java,v $ -// $Revision: 1.18 $ -// $Date: 2009/02/05 18:47:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListSelectionModel; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableCellRenderer; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.dataAccess.shape.input.DbfInputStream; -import com.bbn.openmap.dataAccess.shape.output.DbfOutputStream; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PropUtils; - -/** - * An implementation of TableModel that manages tabular data read from a dbf - * file and enables the user to stored data store herein to be saved to a file - * conforming to the DBF III file format specification. - * - * To create a three one column model: - * - *
- * DbfTableModel model = new DbfTableModel(1);
- * 
- * model.setDecimalCount(0, (byte) 0);
- * model.setLength(0, (byte) 10);
- * model.setColumnName(0, "Column1");
- * model.setType(0, (byte) DbfTableModel.TYPE_CHARACTER);
- * 
- * model.setDecimalCount(1, (byte) 0);
- * model.setLength(1, (byte) 10);
- * model.setColumnName(1, "Column1");
- * model.setType(1, (byte) DbfTableModel.TYPE_NUMERIC);
- * 
- * model.setDecimalCount(2, (byte) 0);
- * model.setLength(2, (byte) 10);
- * model.setColumnName(2, "Column1");
- * model.setType(2, (byte) DbfTableModel.TYPE_CHARACTER);
- * 
- * esriLayer.setModel(model);
- * 
- * - * @author Doug Van Auken - */ -public class DbfTableModel extends AbstractTableModel - implements ShapeConstants, TableModelListener, Iterable> { - - /* - * Binary, Memo, OLE Fields and .DBT Files - * - * Binary, memo, and OLE fields store data in .DBT files consisting of - * blocks numbered sequentially (0, 1, 2, etc.). SET BLOCKSIZE determines - * the size of each block. The first block in the .DBT file, block 0, is the - * .DBT file header. Each binary, memo, or OLE field of each record in the - * .DBF file contains the number of the block (in OEM code page values) - * where the field's data actually begins. If a field contains no data, the - * .DBF file contains blanks (0x20) rather than a number. - * - * When data is changed in a field, the block numbers may also change and - * the number in the .DBF may be changed to reflect the new location. - */ - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.DbfTableModel"); - - private static final long serialVersionUID = 1L; - /** - * 10 digits representing a .DBT block number. The number is stored as a - * string, right justified and padded with blanks. - */ - public static final byte TYPE_BINARY = 'B'; - /** - * All OEM code page characters - padded with blanks to the width of the - * field. - */ - public static final byte TYPE_CHARACTER = 'C'; - /** 8 bytes - date stored as a string in the format YYYYMMDD. */ - public static final byte TYPE_DATE = 'D'; - /** - * Number stored as a string, right justified, and padded with blanks to the - * width of the field. - */ - public static final byte TYPE_NUMERIC = 'N'; - /** 1 byte - initialized to 0x20 (space) otherwise T or F. */ - public static final byte TYPE_LOGICAL = 'L'; - /** - * 10 digits (bytes) representing a .DBT block number. The number is stored - * as a string, right justified and padded with blanks. - */ - public static final byte TYPE_MEMO = 'M'; - /** - * 8 bytes - two longs, first for date, second for time. The date is the - * number of days since 01/01/4713 BC. Time is hours * 3600000L + minutes * - * 60000L + Seconds * 1000L - */ - public static final byte TYPE_TIMESTAMP = '@'; - /** 4 bytes. Leftmost bit used to indicate sign, 0 negative. */ - public static final byte TYPE_LONG = 'I'; - /** Same as a Long */ - public static final byte TYPE_AUTOINCREMENT = '+'; - /** - * Number stored as a string, right justified, and padded with blanks to the - * width of the field. - */ - public static final byte TYPE_FLOAT = 'F'; - /** 8 bytes - no conversions, stored as a double. */ - public static final byte TYPE_DOUBLE = 'O'; - /** - * 10 digits (bytes) representing a .DBT block number. The number is stored - * as a string, right justified and padded with blanks. - */ - public static final byte TYPE_OLE = 'G'; - - /** - * Edit button mask, to allow adding/removing rows. Be very careful with - * this option if you plan on using this file with a shape file - the number - * of records has to match the number of graphics in a shape file, so if you - * add or delete, you should add/delete the graphic in the shape file, too. - */ - public static final int MODIFY_ROW_MASK = 1 << 0; - /** - * Edit button mask, to allow adding/removing columns in the attribute - * table. - */ - public static final int MODIFY_COLUMN_MASK = 1 << 1; - /** - * Button mask to drop the frame quietly, with the modifications to the - * table complete. - */ - public static final int DONE_MASK = 1 << 3; - - /** - * Button mask to show a save button to write out any changes. - */ - public static final int SAVE_MASK = 1 << 4; - - /** - * Old Object value held for every NUMERIC cell that had a problem - * importing. Now, those cells are filled with whitespace. - */ - public final static Double ZERO = new Double(0); - - /** - * An array of bytes that contain the character lengths for each column - */ - protected int[] _lengths = null; - - /** - * An array of bytes that contain the number of decimal places for each - * column - */ - protected byte[] _decimalCounts = null; - - /** An array of bytes that contain the column types for each column */ - protected byte[] _types = null; - - /** An array of bytes that contain the names for each column */ - protected String[] _names = null; - - /** Class scope reference to a list of data formatted by row */ - protected List> _records = null; - - /** - * Class scope variable for the number of columns that exist in the model - */ - protected int _columnCount = -1; - - protected boolean writable = false; - - protected JTable table; - protected final DbfTableModel parent; - - protected boolean dirty = false; - protected boolean exitOnClose = false; - - protected boolean DEBUG = false; - - // I18N mechanism - static I18n i18n = Environment.getI18n(); - - protected DbfTableModel() { - parent = this; - DEBUG = logger.isLoggable(Level.FINE); - } - - /** - * Creates a blank DbfTableModel - * - * @param columnCount The number of columns this model will manage - */ - public DbfTableModel(int columnCount) { - this(); - _columnCount = columnCount; - _records = new ArrayList>(); - _lengths = new int[columnCount]; - _decimalCounts = new byte[columnCount]; - _types = new byte[columnCount]; - _names = new String[columnCount]; - } - - /** - * Creates a DbfTableModel based on an InputStream - * - * @param is The dbf file - */ - public DbfTableModel(DbfInputStream is) { - this(); - _lengths = is.getLengths(); - _decimalCounts = is.getDecimalCounts(); - _names = is.getColumnNames(); - _types = is.getTypes(); - _records = is.getRecords(); - _columnCount = is.getColumnCount(); - } - - /** - * Adds a row of data to the the model - * - * @param columns A collection of columns that comprise the row of data - * @exception An exception is thrown if the number of elements in the passed - * in collection does not match the number of columns in the - * model - */ - public void addRecord(List columns) { - if (columns.size() != _columnCount) { - throw new RuntimeException("DbfTableModel: Mismatched Column Count"); - } - _records.add(columns); - } - - /** - * Remove the record at the index. - */ - public List remove(int index) { - return _records.remove(index); - } - - public void addBlankRecord() { - addRecord(getBlankRecord()); - } - - public List getBlankRecord() { - ArrayList record = new ArrayList(); - - for (int i = 0; i < _columnCount; i++) { - record.add(getEmptyDefaultForType(getType(i))); - } - return record; - } - - public Object getEmptyDefaultForType(byte type) { - // May need to be updated to provide real values. - if (isNumericalType(type)) { - return new Double(0); - } else if (type == DBF_TYPE_LOGICAL.byteValue()) { - return new Boolean(false); - } else { - return ""; - } - } - - public static boolean isNumericalType(byte type) { - return type == DbfTableModel.TYPE_NUMERIC || type == DbfTableModel.TYPE_LONG || type == DbfTableModel.TYPE_FLOAT - || type == DbfTableModel.TYPE_DOUBLE || type == DbfTableModel.TYPE_AUTOINCREMENT; - } - - public static boolean isValidType(byte type) { - return type == DbfTableModel.TYPE_NUMERIC || type == DbfTableModel.TYPE_LONG || type == DbfTableModel.TYPE_FLOAT - || type == DbfTableModel.TYPE_DOUBLE || type == DbfTableModel.TYPE_BINARY || type == DbfTableModel.TYPE_CHARACTER - || type == DbfTableModel.TYPE_DATE || type == DbfTableModel.TYPE_LOGICAL || type == DbfTableModel.TYPE_MEMO - || type == DbfTableModel.TYPE_TIMESTAMP || type == DbfTableModel.TYPE_AUTOINCREMENT - || type == DbfTableModel.TYPE_OLE; - } - - /** - * Retrieves the record array list for the passed record number. In OpenMap, - * Shape file records start their indexes at 0. This is the number attribute - * stored in the EsriGraphic. Note: The Shape Specification and Shape files - * contain indexes starting at 0. Make sure you don't get bit by an - * off-by-one situation. - * - * @param recordnumber The record number - * @return An ArrayList for the given record number - */ - public List getRecord(int recordnumber) { - try { - return _records.get(recordnumber); - } catch (ArrayIndexOutOfBoundsException aioobe) { - return null; - } - } - - /** - * Get an iterator over the records. - */ - public Iterator> getRecords() { - return _records.iterator(); - } - - /** - * Iterable method for the records. - */ - public Iterator> iterator() { - return _records.iterator(); - } - - /** - * Retrieves the column class for the passed in column index - * - * @param c The column index - * @return The column class for the given column index - */ - public Class getColumnClass(int c) { - return getValueAt(0, c).getClass(); - } - - /** - * Retrieves the number of columns that exist in the model - * - * @return The number of columns that exist in the model - */ - public int getColumnCount() { - return _columnCount; - } - - /** - * Retrieves the number of decimal places for the passed in column index - * - * @param column The column index - * @return The number of decimal places for the given column index - */ - public byte getDecimalCount(int column) { - return _decimalCounts[column]; - } - - /** - * Retrieves the column name for the passed in column index - * - * @param column The column index - * @return The column name for the given column index - */ - public String getColumnName(int column) { - return _names[column]; - } - - /** - * Find the column index of the column with the given name. - * - * @param columnName - * @return If the columnName is valid, some number between 0-column count. - * Otherwise, -1 for non-valid names. - */ - public int getColumnIndexForName(String columnName) { - if (_names != null) { - for (int i = 0; i < _names.length; i++) { - if (_names[i].equalsIgnoreCase(columnName)) { - return i; - } - } - } - return -1; - } - - /** - * Retrieves the character length for the passed in column index - * - * @param column The column index - * @return The character length for the given column index - */ - public int getLength(int column) { - return _lengths[column]; - } - - /** - * Retrieves the number of columns that exist in the model - * - * @return The number column that exist in the model - */ - public int getRowCount() { - if (_records == null) { - return 0; - } else { - return _records.size(); - } - } - - /** - * Retrieves the column type for the passed in column index - * - * @param column The column index - * @return The column type for the given column index - */ - public byte getType(int column) { - return _types[column]; - } - - /** - * Retrieves a value for a specific column and row index - * - * @return Object A value for a specific column and row index - */ - public Object getValueAt(int row, int column) { - List cells = _records.get(row); - Object cell = cells.get(column); - return cell; - } - - /** - * Sets the column name for the passed-in field index - * - * @param column The column index - * @param name The name to assign for the passed-in column index - */ - public void setColumnName(int column, String name) { - _names[column] = name; - } - - /** - * Sets the decimal count for the passed in field index - * - * @param column The index to the column - * @param decimalCount The number of decimals places to assign to the passed - * in column - */ - public void setDecimalCount(int column, byte decimalCount) { - _decimalCounts[column] = decimalCount; - } - - /** - * Set the character length for the passed-in field index - * - * @param column The column index - * @param length The character length to assign for the passed-in column - * index - */ - public void setLength(int column, int length) { - _lengths[column] = length; - } - - /** - * Sets the column type for the passed-in field index - * - * @param column The column index - * @param type The type of column to assign for the passed-in column index - */ - public void setType(int column, byte type) { - _types[column] = type; - } - - public void setValueAt(Object object, int row, int column) { - List columns = _records.get(row); - columns.set(column, object); - } - - public boolean isCellEditable(int rowIndex, int columnIndex) { - return writable; - } - - public void setWritable(boolean set) { - writable = set; - } - - public boolean getWritable() { - return writable; - } - - /** - * Needs to be called before displaying the DbfTableModel. - */ - public JTable getTable(ListSelectionModel lsm) { - JTable t = getTable(); - t.setModel(this); - t.setSelectionModel(lsm); - t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); - return t; - } - - protected JTable getTable() { - if (table == null) { - table = new DbfJTable(this); - } - return table; - } - - // In case you want to add options to modify the table. - JPanel controlPanel = null; - - public Component getGUI(String filename, int actionMask) { - - JPanel panel = new JPanel(); - - if (filename != null) { - panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), filename)); - } else { - panel.setBorder(BorderFactory.createEtchedBorder()); - } - - panel.setLayout(new BorderLayout()); - - JScrollPane pane = new JScrollPane(getTable(new DefaultListSelectionModel())); - panel.add(pane, BorderLayout.CENTER); - - controlPanel = new JPanel(); - panel.add(controlPanel, BorderLayout.SOUTH); - - if ((actionMask & MODIFY_ROW_MASK) != 0) { - JButton addButton = new JButton(i18n.get(DbfTableModel.class, "Add", "Add")); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - addBlankRecord(); - fireTableDataChanged(); - } - }); - - JButton deleteButton = new JButton(i18n.get(DbfTableModel.class, "Delete", "Delete")); - deleteButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - int[] index = getTable().getSelectedRows(); - - if (index.length > 0) { - - // Ask to make sure... - - int check = - JOptionPane.showConfirmDialog(null, - (i18n.get(DbfTableModel.class, "Are_you_sure_you_want_to_delete", - "Are you sure you want to delete") + " " + (index.length > 1 - ? i18n.get(DbfTableModel.class, "these_rows", "these rows?") - : i18n.get(DbfTableModel.class, "this_row", "this row?"))), - i18n.get(DbfTableModel.class, "Confirm_Delete", "Confirm Delete"), - JOptionPane.OK_CANCEL_OPTION); - - if (check == JOptionPane.YES_OPTION) { - - for (int i = index.length - 1; i >= 0; i--) { - if (DEBUG) - logger.fine("Deleting record " + index[i]); - List removed = remove(index[i]); - if (DEBUG) - logger.fine("Deleted records: " + removed); - } - fireTableDataChanged(); - } - } - } - }); - - controlPanel.add(addButton); - controlPanel.add(deleteButton); - } - - if ((actionMask & MODIFY_COLUMN_MASK) != 0) { - JButton editTableButton = new JButton(i18n.get(DbfTableModel.class, "Edit_Table_Format", "Edit Table Format")); - editTableButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - MetaDbfTableModel mdtm = new MetaDbfTableModel(parent); - mdtm.addTableModelListener(parent); - mdtm.showGUI(filePath.toString()); - } - }); - - controlPanel.add(editTableButton); - } - - if ((actionMask & SAVE_MASK) != 0) { - JButton saveButton = new JButton(i18n.get(DbfTableModel.class, "Save", "Save")); - saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - try { - write(parent, null); - } catch (FileNotFoundException fnfe) { - } catch (IOException ioe) { - } - } - }); - controlPanel.add(saveButton); - } - - if ((actionMask & DONE_MASK) != 0) { - JButton doneButton = new JButton(i18n.get(DbfTableModel.class, "Done", "Done")); - doneButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - frame.dispose(); - } - }); - controlPanel.add(doneButton); - } - - return panel; - } - - protected final StringBuffer filePath = new StringBuffer(); - protected JFrame frame = null; - - public void hideGUI() { - if (frame != null) { - frame.setVisible(false); - } - } - - public void showGUI(String filename, int actionMask) { - - if (frame == null) { - frame = new JFrame(filename); - - filePath.replace(0, filePath.capacity(), filename); - - frame.getContentPane().add(getGUI(null, actionMask), BorderLayout.CENTER); - - frame.setSize(400, 300); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - // need a shutdown event to notify other gui beans - // and - // then exit. - exitWindowClosed(); - } - }); - } - - frame.setVisible(true); - } - - public void exitWindowClosed() { - if (exitOnClose) { - System.exit(0); - } - } - - public void tableChanged(TableModelEvent e) { - dirty = true; - if (DEBUG) - logger.fine("DbfTableModel sensing change"); - - int row = e.getFirstRow(); - // Of course, the only thing we're listening to here is the - // MetaDbfTableModel changes, and if we get a HEADER_ROW - // change it's telling us to modify *OUR* headers, to commit - // all the changes that were made to it. Otherwise, we should - // just track the events and make them happen when we get - // this. - if (row == TableModelEvent.HEADER_ROW) { - commitEvents((DbfTableModel) e.getSource()); - } - } - - protected void commitEvents(DbfTableModel model) { - - if (DEBUG) - logger.fine("Committing changes"); - - Iterator> modelRecords = model.getRecords(); - int index = -1; - - while (modelRecords.hasNext()) { - List modelRecord = modelRecords.next(); - - String modelColumnName = (String) modelRecord.get(0); - Byte modelType = (Byte) modelRecord.get(1); - Integer modelLengthOfField = (Integer) modelRecord.get(2); - Integer modelNumDecPlaces = (Integer) modelRecord.get(3); - - index++; - if (index < _columnCount) { - String columnName = _names[index]; - if (DEBUG) - logger.fine(columnName + ", " + modelColumnName); - while (!columnName.equalsIgnoreCase(modelColumnName)) { - deleteColumn(index); - if (index >= _columnCount) { - addColumn(modelRecord); - break; - } - columnName = _names[index]; - } - - if (columnName.equalsIgnoreCase(modelColumnName)) { - _types[index] = modelType.byteValue(); - _lengths[index] = modelLengthOfField.intValue(); - _decimalCounts[index] = modelNumDecPlaces.byteValue(); - } - - } else { - // Add Column - if (DEBUG) - logger.fine("Add column " + modelColumnName); - addColumn(modelRecord); - } - } - - while (++index < _columnCount) { - if (DEBUG) - logger.fine("Deleting extra column"); - deleteColumn(index); - } - - if (DEBUG) { - logger.fine("New Table:"); - for (int j = 0; j < _names.length; j++) { - logger.fine(" " + _names[j]); - } - } - fireTableStructureChanged(); - dirty = false; - } - - /** - * Delete a column, iterating through all the records and deleting that part - * of each record. - */ - protected void deleteColumn(int columnIndex) { - Iterator> rows = getRecords(); - while (rows.hasNext()) { - rows.next().remove(columnIndex); - } - - _columnCount -= 1; - - _lengths = remove(_lengths, columnIndex); - _decimalCounts = remove(_decimalCounts, columnIndex); - _types = remove(_types, columnIndex); - _names = remove(_names, columnIndex); - } - - /** - */ - protected int[] remove(int[] current, int index) { - - int[] newBytes = new int[current.length - 1]; - System.arraycopy(current, 0, newBytes, 0, index); - System.arraycopy(current, index + 1, newBytes, index, current.length - index - 1); - return newBytes; - } - - /** - */ - protected byte[] remove(byte[] current, int index) { - - byte[] newBytes = new byte[current.length - 1]; - System.arraycopy(current, 0, newBytes, 0, index); - System.arraycopy(current, index + 1, newBytes, index, current.length - index - 1); - return newBytes; - } - - /** - */ - protected String[] remove(String[] current, int index) { - - String[] newStrings = new String[current.length - 1]; - System.arraycopy(current, 0, newStrings, 0, index); - System.arraycopy(current, index + 1, newStrings, index, current.length - index - 1); - return newStrings; - } - - /** - * The types in the ArrayList are set - String, Byte, Integer, Integer - to - * match the format of the header. - */ - protected void addColumn(List recordColumn) { - - Iterator> rows = getRecords(); - while (rows.hasNext()) { - rows.next().add(""); - } - - _columnCount++; - - _names = add(_names, ((String) recordColumn.get(0))); - _types = add(_types, ((Byte) recordColumn.get(1)).byteValue()); - _lengths = add(_lengths, ((Integer) recordColumn.get(2)).byteValue()); - _decimalCounts = add(_decimalCounts, ((Integer) recordColumn.get(3)).byteValue()); - } - - /** - */ - protected int[] add(int[] current, byte nb) { - int[] newBytes = new int[current.length + 1]; - System.arraycopy(current, 0, newBytes, 0, current.length); - newBytes[current.length] = nb; - return newBytes; - } - - /** - */ - protected byte[] add(byte[] current, byte nb) { - byte[] newBytes = new byte[current.length + 1]; - System.arraycopy(current, 0, newBytes, 0, current.length); - newBytes[current.length] = nb; - return newBytes; - } - - protected String[] add(String[] current, String string) { - String[] newStrings = new String[current.length + 1]; - System.arraycopy(current, 0, newStrings, 0, current.length); - newStrings[current.length] = string; - return newStrings; - } - - public void cleanupChanges() { - if (DEBUG) - Debug.output("DbfTableModel cleaning up changes."); - dirty = false; - } - - /** - * Create another DbfTableModel with the same structure as this one (number - * of columns, column names, lengths and decimal counts). - */ - public DbfTableModel headerClone() { - int size = getColumnCount(); - DbfTableModel dtm = new DbfTableModel(size); - for (int i = 0; i < size; i++) { - dtm.setColumnName(i, this.getColumnName(i)); - dtm.setDecimalCount(i, this.getDecimalCount(i)); - dtm.setLength(i, this.getLength(i)); - dtm.setType(i, this.getType(i)); - } - return dtm; - } - - /** - * Creates a DbfTableModel for a given .dbf file - * - * @param dbf The url of the file to retrieve. - * @return The DbfTableModel, null if there is a problem. - */ - public static DbfTableModel getDbfTableModel(URL dbf) { - try { - return read(dbf); - } catch (Exception exception) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("problem loading DBF file" + exception.getMessage()); - } - return null; - } - } - - public static DbfTableModel read(URL dbf) - throws Exception { - InputStream is = dbf.openStream(); - DbfTableModel model = new DbfTableModel(new DbfInputStream(is)); - is.close(); - return model; - } - - public static String write(DbfTableModel model, String location) - throws FileNotFoundException, IOException { - if (location == null) { - - location = - FileUtils.getFilePathToSaveFromUser(i18n.get(DbfTableModel.class, "Select_DBF_Name", "Select DBF file name...")); - if (location != null && !location.endsWith(".dbf")) { - location = location + ".dbf"; - } - } - if (location != null) { - DbfOutputStream dos = new DbfOutputStream(new FileOutputStream(new File(location))); - dos.writeModel(model); - } - - return location; - } - - /** - * Takes the object and converts it to a String for output. - * - * @param obj - * @param type - * @param df - * @param columnLength the length of the column entries, so whitespace can - * be added if needed. - * @return a string value representing the object. If the object is null, a - * whitespace string will be returned. - */ - public static String getStringForType(Object obj, byte type, DecimalFormat df, int columnLength) { - String ret = ""; - - if (obj != null) { - - if (isNumericalType(type)) { - try { - ret = df.format(((Double) obj).doubleValue()); - } catch (Exception e) { - ret = ""; - } - - } else if (obj instanceof String) { - ret = (String) obj; - } - } - - if (ret.length() != columnLength) { - ret = appendWhitespaceOrTrim(ret, columnLength); - } - - return ret; - } - - /** - * A method that looks at the length of String s and returns a copy of it - * with whitespace appended to the end to allow it to have the provided - * length. - * - * @param s - * @param length - * @return String with whitespace added if needed. - */ - public static String appendWhitespaceOrTrim(String s, int length) { - if (s == null) { - s = new String(""); - } - - int retLength = s.length(); - if (retLength < length) { - StringBuffer sb = new StringBuffer(s); - int numWhites = length - retLength; - for (int i = 0; i < numWhites; i++) { - sb.append(" "); - } - s = sb.toString(); - } else if (retLength > length) { - s = s.substring(0, length); - } - - return s; - } - - public static Object getObjectForType(String cellContents, int type, DecimalFormat df, int columnLength) - throws java.text.ParseException { - Object ret = cellContents; - if (isNumericalType((byte) type)) { - if (cellContents.length() > 0) { - try { - ret = new Double(cellContents); - } catch (NumberFormatException nfe) { - // Shouldn't get here, but thought it might help. DFD - ret = new Double(df.parse(cellContents).doubleValue()); - } - } else { - // If we come across a numerical cell that doesn't contain data, - // we should create an empty whitespace string in that cell - // instead of setting it to ZERO. ZERO has a very different - // meaning. - - ret = appendWhitespaceOrTrim(null, columnLength); - } - } else if (type == DbfTableModel.TYPE_BINARY || type == DbfTableModel.TYPE_MEMO || type == DbfTableModel.TYPE_OLE) { - if (cellContents.length() < 10) { - cellContents = cellContents.trim(); - // prepending whitespace. - StringBuffer bu = new StringBuffer(); - int numSpaces = 10 - cellContents.length(); - for (int i = 0; i < numSpaces; i++) { - bu.append(" "); - } - bu.append(cellContents); - ret = bu.toString(); - } - } else if (type == DbfTableModel.TYPE_TIMESTAMP) { - // uhhhhhh.... - } - - return ret; - } - - public boolean isExitOnClose() { - return exitOnClose; - } - - public void setExitOnClose(boolean exitOnClose) { - this.exitOnClose = exitOnClose; - } - - public static void main(String[] args) { - Debug.init(); - if (args.length < 1) { - test(); - } else { - - try { - - URL dbf = PropUtils.getResourceOrFileOrURL(args[0]); - InputStream is = dbf.openStream(); - DbfInputStream dis = new DbfInputStream(is); - DbfTableModel dtm = new DbfTableModel(dis); - dtm.setWritable(true); - dtm.exitOnClose = true; - dtm.showGUI(args[0], MODIFY_ROW_MASK | MODIFY_COLUMN_MASK | SAVE_MASK); - is.close(); - } catch (Exception e) { - Debug.error(e.getMessage()); - e.printStackTrace(); - } - } - } - - public static void test() { - DbfTableModel dtm = new DbfTableModel(2); - dtm.setColumnName(0, "NAME"); - dtm.setColumnName(1, "VALUE"); - - dtm.setDecimalCount(0, (byte) 0); - dtm.setDecimalCount(1, (byte) 3); - - dtm.setLength(0, 20); - dtm.setLength(1, 10); - - dtm.setType(0, TYPE_CHARACTER); - dtm.setType(1, TYPE_DOUBLE); - - ArrayList record = new ArrayList(); - record.add("ok"); - record.add(new Double(345.3)); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("null"); - record.add(null); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("blank"); - record.add(""); - dtm.addRecord(record); - - record = new ArrayList(); - record.add("zero"); - record.add(new Double(0)); - dtm.addRecord(record); - - try { - write(dtm, "./test.dbf"); - - dtm = read(new File("./test.dbf").toURI().toURL()); - - dtm.showGUI("test.dbf", MODIFY_ROW_MASK | MODIFY_COLUMN_MASK | SAVE_MASK); - - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - class DbfJTable - extends JTable { - private static final long serialVersionUID = 1L; - DbfTableModel dbfTableModel; - DoubleRenderer dRenderer = new DoubleRenderer(); - - public DbfJTable(DbfTableModel model) { - super(model); - dbfTableModel = model; - } - - public TableCellRenderer getCellRenderer(int row, int column) { - if (isNumericalType(_types[column])) { - dRenderer.formatter.setMaximumFractionDigits(_decimalCounts[column]); - return dRenderer; - } - return super.getCellRenderer(row, column); - } - } - - static class DoubleRenderer - extends DefaultTableCellRenderer { - private static final long serialVersionUID = 1L; - NumberFormat formatter = NumberFormat.getInstance(); - - public DoubleRenderer() { - super(); - setHorizontalAlignment(JLabel.RIGHT); - } - - public void setValue(Object value) { - try { - setText(formatter.format(value)); - return; - } catch (Exception e) { - - } - setText(""); - } - } - - public boolean matches(DbfTableModel dbf) { - boolean columnsMatch = false; - - if (dbf != null) { - int columnCount = getColumnCount(); - columnsMatch = dbf.getColumnCount() == columnCount; - - int i = 0; - while (columnsMatch && i < columnCount) { - columnsMatch = columnsMatch && dbf.getColumnName(i).equals(getColumnName(i)); - i++; - } - } - return columnsMatch; - } - - public void append(DbfTableModel dbf) { - if (matches(dbf)) { - Iterator> it = dbf.getRecords(); - while (it.hasNext()) { - addRecord(it.next()); - } - } - } - - /** - * - */ - @SuppressWarnings("unchecked") - public void doAction(OMGraphicList list, OMGraphic graphic, OMAction action, DbfTableModelFactory dbfFactory) { - - if (list == null || graphic == null) { - return; - } - - if (list.size() != getRowCount()) { - logger.warning("DBF rows don't match list contents"); - return; - } - - // Take the contents (rows) of the DbfTableModel, store them in the - // OMGraphics, do the action on the list, then reset the DbfTableModel. - // Reset the indexes in the OMGraphics. - int indexCount = 0; - for (OMGraphic omg : list) { - Integer index = (Integer) omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - if (index != null) { - if (index != indexCount) { - // ooh jeez. - logger.warning("the indexes in the list are off, (counted) " + indexCount + " vs (record) " + index); - } - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getRecord(index)); - } else { - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getRecord(indexCount)); - } - indexCount++; - } - - if (graphic.getAttribute(SHAPE_DBF_INFO_ATTRIBUTE) == null) { - - if (dbfFactory != null) { - graphic.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, dbfFactory.getNewDefaultRow()); - } else { - graphic.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, getBlankRecord()); - } - } - - list.doAction(graphic, action); - - _records.clear(); - - indexCount = 0; - for (OMGraphic omg : list) { - _records.add((List) omg.getAttribute(SHAPE_DBF_INFO_ATTRIBUTE)); - omg.putAttribute(SHAPE_DBF_INFO_ATTRIBUTE, null); - omg.putAttribute(SHAPE_INDEX_ATTRIBUTE, new Integer(indexCount++)); - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java b/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java deleted file mode 100644 index 1f38fa249..000000000 --- a/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java +++ /dev/null @@ -1,416 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/dataAccess/shape/EsriGraphicList.java,v $ -// $RCSfile: EsriGraphicList.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.dataAccess.shape; - -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.dataAccess.shape.input.ShpInputStream; -import com.bbn.openmap.dataAccess.shape.input.ShxInputStream; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.util.ArgParser; -import com.bbn.openmap.util.PropUtils; - -/** - * EsriGraphicList ensures that only supported geometry types are added to its - * list. Each subclass of this EsriGraphicList list will hold polyline, polygon, - * or point geometry -- other types of geometry are not supported. As shapes are - * added to the list, EsriGraphicList will ensure that the type of geometry - * being added is the same type of geometry as specified by the subclass list - * type. - * - * @author Doug Van Auken - * @author Don Dietrick - */ -public abstract class EsriGraphicList - extends OMGraphicList - implements ShapeConstants, EsriGraphic { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.dataAccess.shape.EsriGraphicList"); - protected double[] extents; - protected int type; - - /** - * Over-ride the add( ) method to trap for inconsistent shape geometry. If - * you are adding a OMGraphic that is not a list, make sure this list is a - * sub-list containing multiple geometry parts. Only add another list to a - * top level EsriGraphicList. - * - * @param shape the non-null OMGraphic to add - */ - public boolean add(OMGraphic shape) { - return super.add(shape); - } - - /** - * Add an OMGraphic to the GraphicList. The OMGraphic must not be null. - * - * @param g the non-null OMGraphic to add - * @return true if addition is successful. - * @exception IllegalArgumentException if OMGraphic is null - */ - public boolean addOMGraphic(OMGraphic g) { - return add(g); - } - - public void setType(int type) { - this.type = type; - } - - /** - * Get the list type in ESRI type number form - */ - public int getType() { - return type; - } - - /** - * Construct an EsriGraphicList. - */ - public EsriGraphicList() { - super(); - } - - /** - * Construct an EsriGraphicList with an initial capacity. - * - * @param initialCapacity the initial capacity of the list - */ - public EsriGraphicList(int initialCapacity) { - super(initialCapacity); - } - - /** - * Construct an EsriGraphicList with an initial capacity and a standard - * increment value. - * - * @param initialCapacity the initial capacity of the list - * @param capacityIncrement the capacityIncrement for resizing - * @deprecated capacityIncrement doesn't do anything. - */ - public EsriGraphicList(int initialCapacity, int capacityIncrement) { - super(initialCapacity); - } - - /** - * The lat/lon extent of the EsriGraphicList contents, assumed to contain - * miny, minx, maxy maxx in order of the array. - */ - public void setExtents(double[] extents) { - this.extents = extents; - } - - /** - * The lat/lon extent of the EsriGraphicList contents, returned as miny, - * minx, maxy maxx in order of the array. - */ - public double[] getExtents() { - if (extents == null) { - // These are set to their opposites to guarantee some - // movement. - extents = new double[] { - 90f, - 180f, - -90f, - -180f - }; - } - - return extents; - } - - public void addExtents(double[] graphicExtents) { - double[] ex = getExtents(); - - // Check both graphic extents in case they are inadvertently - // switched. - for (int i = 0; i < graphicExtents.length; i += 2) { - if (ex[0] > graphicExtents[i]) - ex[0] = graphicExtents[i]; - if (ex[1] > graphicExtents[i + 1]) - ex[1] = graphicExtents[i + 1]; - if (ex[2] < graphicExtents[i]) - ex[2] = graphicExtents[i]; - if (ex[3] < graphicExtents[i + 1]) - ex[3] = graphicExtents[i + 1]; - } - - // System.out.println("extents of list: " + - // ex[1] + ", " + - // ex[0] + ", " + - // ex[3] + ", " + - // ex[2]); - - } - - /** - * Set the DbfTableModel in the AppObject of this list that holds the - * attribute information about this list's objects. - */ - public void setTable(DbfTableModel dtm) { - if (dtm != null) { - putAttribute(DBF_ATTRIBUTE, dtm); - } else { - removeAttribute(DBF_ATTRIBUTE); - } - } - - /** - * Get the DbfTableModel object from the AppObject of this list. - */ - public DbfTableModel getTable() { - Object obj = getAttribute(DBF_ATTRIBUTE); - if (obj instanceof DbfTableModel) { - return (DbfTableModel) obj; - } else { - return null; - } - } - - /** - * Create a generic DbfTableModel for the contents of this list, where the - * attributes hold rendering properties for the list contents. The table is - * stored in the AppObject member variable of the list. - */ - public void createTable() { - // lineWidth, lineColor, fillColor, selectColor We could do - // stroke info. Toss space in there for name, or general - // attribute for later. - // this.setAppObject(EsriShapeExport.createDefaultModel(this)); - putAttribute(DBF_ATTRIBUTE, EsriShapeExport.createDefaultModel(this)); - } - - /** - * Reads the contents of the SHX and SHP files. The SHX file will be read - * first by utilizing the ShapeIndex.open method. This method will return a - * list of offsets, which the AbstractSupport.open method will use to - * iterate through the contents of the SHP file. - * - * @param shp The url of the SHP file - * @param shx The url of the SHX file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if this is - * null. - * @param dbf a DbfTableModel, if you want each row of objects from the - * table (an array), inserted into their associated OMGraphic's - * appObject. The dbf will be added to the list appObject, so you can - * ask it questions later. If null, no problem. If the number of - * records doesn't match the OMGraphic list length, nothing will be - * done. - * @return A new EsriGraphicList, null if there is a problem. - * - * @deprecated use getGraphicList(URL, DrawingAttributes, DbfTableModel) - */ - public static EsriGraphicList getEsriGraphicList(URL shp, URL shx, DrawingAttributes drawingAttributes, DbfTableModel dbf) { - return getEsriGraphicList(shp, drawingAttributes, dbf, null); - } - - /** - * Reads the contents of the SHP files. - * - * @param shp The url of the SHP file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if this is - * null. - * @param dbf a DbfTableModel. The dbf will be added to the list appObject, - * so you can ask it questions later. If null, no problem. If the - * number of records doesn't match the OMGraphic list length, nothing - * will be done. - * @param coordTranslator a GeoCoordTransformation to use to convert - * coordinates to decimal degree lat/lon data. - * @return A new EsriGraphicList, null if there is a problem. - */ - public static EsriGraphicList getEsriGraphicList(URL shp, DrawingAttributes drawingAttributes, DbfTableModel dbf, - GeoCoordTransformation coordTranslator) { - EsriGraphicList list = null; - - // Open and stream shp file - try { - InputStream is = shp.openStream(); - ShpInputStream pis = new ShpInputStream(is); - if (drawingAttributes != null) { - pis.setDrawingAttributes(drawingAttributes); - } - EsriGraphicFactory egf = new EsriGraphicFactory(OMGraphic.LINETYPE_GREATCIRCLE, coordTranslator); - list = pis.getGeometry(egf); - is.close(); - } catch (Exception e) { - logger.warning("Not able to stream SHP file"); - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - return null; - } - - if (list != null && dbf != null && dbf.getRowCount() == list.size()) { - list.setTable(dbf); - } - - return list; - } - - /** - * Reads the contents of the SHP files, including the DBF file, based on the - * location of the shape file. The dbf will be added to the list appObject, - * so you can ask it questions later. If null, no problem. If the number of - * records doesn't match the OMGraphic list length, the dbf information - * won't be added to the list. - * - * @param shp The url of the SHP file - * @param drawingAttributes a DrawingAttributes object containing the - * rendering parameters you might want on the OMGraphics. The - * OMGraphic default (black edge, clear fill) will be used if this is - * null. - * @param coordTranslator used to transform coordinates to lat/lon decimal - * degrees for OpenMap. - * @return A new EsriGraphicList, null if there is a problem. - */ - public static EsriGraphicList getEsriGraphicList(URL shp, DrawingAttributes drawingAttributes, - GeoCoordTransformation coordTranslator) { - DbfTableModel dbf = null; - - if (shp != null) { - String shpPath = shp.getFile(); - String protocol = shp.getProtocol(); - String host = shp.getHost(); - - if (shpPath != null && shpPath.endsWith(".shp")) { - String dbfPath = shpPath.replace(".shp", ".dbf"); - URL dbfURL; - try { - dbfURL = new URL(protocol, host, dbfPath); - dbf = DbfTableModel.getDbfTableModel(dbfURL); - dbfURL = null; - } catch (MalformedURLException e) { - e.printStackTrace(); - } - } - } - - return getEsriGraphicList(shp, drawingAttributes, dbf, coordTranslator); - } - - /** - * Find EsriGraphics with a certain attribute - * - * @param value the value of the desired attribute. - * @param columnName the columnName in the dbf - * @return new List of EsriGraphic shapes with value in column - * @throws FormatException thrown if columnName isn't found. - */ - public List getGraphicsWithValueInColumn(Object value, String columnName) throws FormatException { - List ret = new ArrayList(); - DbfTableModel dbf = getTable(); - int colIndex = dbf.findColumn(columnName); - if (colIndex != -1) { - for (OMGraphic eg : this) { - Integer index = (Integer) eg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE); - List atts = dbf.getRecord(index); - - if (atts.get(colIndex).equals(value)) { - ret.add((EsriGraphic) eg); - } - } - } else { - throw new FormatException("Column " + columnName + " not found"); - } - - return ret; - } - - public static void main(String[] args) { - - ArgParser ap = new ArgParser("EsriGraphicList"); - ap.add("fixcl", "Check and fix content length of Shape file", 1); - ap.add("print", "Display text structure of shapes in Shape file", 1); - - if (!ap.parse(args)) { - ap.printUsage(); - System.exit(0); - } - - String[] fixit = ap.getArgValues("fixcl"); - if (fixit != null) { - String shape = fixit[0]; - if (shape.endsWith(".shp")) { - shape = shape.substring(0, shape.length() - 4); - - try { - URL shx = PropUtils.getResourceOrFileOrURL(shape + ".shx"); - InputStream is = shx.openStream(); - ShxInputStream pis = new ShxInputStream(is); - int[][] index = pis.getIndex(); - is.close(); - - RandomAccessFile raf = new RandomAccessFile(shape + ".shp", "rw"); - raf.seek(24); - int contentLength = raf.readInt(); - - int indexedContentLength = index[0][index[0].length - 1] + index[1][index[1].length - 1]; - - if (contentLength != indexedContentLength) { - System.out.println(shape + " content length - shp: " + contentLength + ", shx: " + indexedContentLength); - raf.seek(24); - raf.writeInt(indexedContentLength); - } - raf.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - - } else { - System.out.println("Shape " + shape + " doesn't look like a shape file"); - } - } - - String[] printit = ap.getArgValues("print"); - if (printit != null) { - try { - EsriGraphicList.logger.setLevel(Level.FINER); - EsriGraphicFactory.logger.setLevel(Level.FINER); - URL eglURL = PropUtils.getResourceOrFileOrURL(printit[0]); - EsriGraphicList egl = EsriGraphicList.getEsriGraphicList(eglURL, null, null); - if (egl != null) { - System.out.println(egl.getDescription()); - } - - } catch (Exception e) { - logger.warning(e.getMessage()); - e.printStackTrace(); - } - } - } -} diff --git a/src/openmap/com/bbn/openmap/gui/LayerAddPanel.java b/src/openmap/com/bbn/openmap/gui/LayerAddPanel.java deleted file mode 100644 index 5e9d6f6cd..000000000 --- a/src/openmap/com/bbn/openmap/gui/LayerAddPanel.java +++ /dev/null @@ -1,491 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerAddPanel.java,v $ -// $RCSfile: LayerAddPanel.java,v $ -// $Revision: 1.9 $ -// $Date: 2006/02/14 20:55:52 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.Hashtable; -import java.util.Properties; -import java.util.Set; -import java.util.Vector; - -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTextField; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.plugin.PlugIn; -import com.bbn.openmap.plugin.PlugInLayer; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * Class to interactively add a Layer to the map. A LayerAddPanel utilizes the - * bean context mechanisms to keep up to date about the applications - * LayerHandler and PropertyHandler (see findAndInit method). A property is used - * to determine objects of which Layer subclasses can be instantiated (see - * static String layerTypes), for configuration of a layer-to-be an Inspector is - * invoked to inspect and configure a Layer object through the PropertyConsumer - * interface. - */ -public class LayerAddPanel extends OMComponentPanel implements Serializable, ActionListener { - /** - * Constant field containing markers used in properties file for layers that - * can be created using the LayerAddPanel. - */ - public final static String layerTypes = "addableLayers"; - - /** - * Holds the PropertyHandler. - */ - protected PropertyHandler propertyHandler = null; - /** - * Holds the LayerHandler. - */ - protected LayerHandler layerHandler = null; - /** - * The list of available Layer classes. Is initiated with pretty names. - */ - protected JComboBox list = null; - /** - * Text field used to define new Layer class to create. - */ - protected JTextField classTextField = null; - /** The String to use as a prefix for the new Layer's properties. */ - protected JTextField prefixTextField = null; - /** Action command String for JButton. */ - protected final String configureActionCommand = "configureActionCommand"; - /** Contains Layer classes to be instantiated. */ - protected Hashtable layerClasses = null; - /** The Inspector to handle the configuration of the new Layer. */ - protected Inspector inspector = null; - /** The layer to configure and add. */ - protected Object layer; - /** - * JButton to use to create new Layer. - */ - protected JButton configureButton; - - /** - * Creates the LayerPanel. - */ - public LayerAddPanel() { - super(); - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel()"); - } - inspector = new Inspector(); - inspector.addActionListener((ActionListener) this); - } - - /** - * Creates the LayerPanel. - * - * @param l the LayerHandler controlling the layers. - */ - public LayerAddPanel(PropertyHandler p, LayerHandler l) { - this(); - propertyHandler = p; - layerHandler = l; - } - - public void createLayerClasses(Layer[] layers) { - getLayerClasses().clear(); - - for (Layer l : layers) { - String name = l.getName(); - if (name == null) { - name = l.getClass().getName(); - int lastDotIndex = name.lastIndexOf('.'); - if (lastDotIndex >= 0) { - name = name.substring(lastDotIndex); - } - } - - addLayer(name, l.getClass().getName()); - } - } - - /** - * Produces a dialog panel to add a Layer, with the layers given. - */ - public void createPanel(Layer[] layers) { - createLayerClasses(layers); - createPanel(); - } - - public final static String DefaultLayerName = "Layer Name"; - - /** - * Produces a dialog panel to add a layer. If the layers haven't been - * manually added through createPanel(layers), then the PropertyHandler is - * consulted and the layer list is built from the layerTypes property. - */ - public void createPanel() { - removeAll(); - - configureButton = new JButton(i18n.get(LayerAddPanel.class, "configureButton", "Configure")); - configureButton.addActionListener(this); - configureButton.setActionCommand(configureActionCommand); - - String defaultLayerName = i18n.get(LayerAddPanel.class, "defaultLayerName", DefaultLayerName); - prefixTextField = new JTextField(defaultLayerName, 12); - - Set keys = getLayerClasses().keySet(); - String[] layerTypes = keys.toArray(new String[keys.size()]); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1.0; - c.gridwidth = GridBagConstraints.REMAINDER; - c.insets = new Insets(10, 10, 5, 10); - - if (layerTypes.length == 0) { - configureButton.setEnabled(false); - classTextField = new JTextField(30); - classTextField.setToolTipText(i18n.get(LayerAddPanel.class, "classFieldToolTip", "Class name of layer to add")); - /* - * // Since there's no list provided, give a text box to let the - * user // specify which layer to create. String message = - * i18n.get(LayerAddPanel.class, "noLayersAvailableMessage", - * "No Layers available for creation."); JLabel label = new - * JLabel(message); - */ - - classTextField.setInputVerifier(new InputVerifier() { - - @Override - public boolean verify(JComponent input) { - JTextField tf = (JTextField) input; - String className = tf.getText(); - try { - ClassLoader.getSystemClassLoader().loadClass(className); - } catch (ClassNotFoundException cnfe) { - configureButton.setEnabled(false); - return false; - } - - configureButton.setEnabled(true); - return true; - } - - }); - - gridbag.setConstraints(classTextField, c); - add(classTextField); - - configureButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - String newClassName = (String) classTextField.getText(); - String prefix = prefixTextField.getText().trim(); - createLayer(newClassName, prefix); - } - }); - - } else { - list = new JComboBox(layerTypes); - gridbag.setConstraints(list, c); - add(list); - - configureButton.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - String prettyName = (String) list.getSelectedItem(); - String prefix = prefixTextField.getText().trim(); - - if (prettyName == null) { - return; - } - - String newClassName = layerClasses.get(prettyName); - - createLayer(newClassName, prefix); - } - }); - - } - - // Prefix/Name field - c.insets = new Insets(5, 10, 10, 10); - c.gridwidth = GridBagConstraints.RELATIVE; - gridbag.setConstraints(prefixTextField, c); - add(prefixTextField); - - // Add configure button - c.weightx = 0; - gridbag.setConstraints(configureButton, c); - add(configureButton); - - invalidate(); - } - - public Hashtable getLayerClasses() { - if (layerClasses == null) { - layerClasses = new Hashtable(); - } - return layerClasses; - } - - public void addLayer(String prettyName, String className) { - getLayerClasses().put(prettyName, className); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel.setProperties()"); - } - getLayerTypes(props); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - int layerNumber = 1; - if (layerClasses != null) { - StringBuffer layerList = new StringBuffer(); - - for (String prettyName : layerClasses.keySet()) { - String className = (String) layerClasses.get(prettyName); - - String markerName = "l" + (layerNumber++); - layerList.append(markerName).append(" "); - props.put(markerName + ".prettyName", prettyName); - props.put(markerName + ".class", className); - } - props.put(Environment.OpenMapPrefix + "." + layerTypes, layerList.toString()); - } - - return props; - } - - /** - * Gets Layer information from PropertyHandler. These layers are defined in - * the application properties under the openmap.layerTypes property. - * - * @return Hashtable of prettyName String keys with classname values. Empty - * Hashtable if no layers are available. - */ - protected Hashtable getLayerTypes() { - return getLayerTypes(null); - } - - /** - * Gets Layer information from the given properties. These layers are - * defined in the application properties under the openmap.layerTypes - * property. If the given properties are null, then the property handler, if - * found, will be consulted directly. - * - * @return Hashtable of prettyName String keys with classname values. Empty - * Hashtable if no layers are available. - */ - protected Hashtable getLayerTypes(Properties props) { - Hashtable layerHash = getLayerClasses(); - layerHash.clear(); - - if (props == null) { - if (propertyHandler != null) { - props = propertyHandler.getProperties(); - } else { - return layerHash; - } - } - - String prefix = Environment.OpenMapPrefix; - String addableList = props.getProperty(prefix + "." + layerTypes); - - if (Debug.debugging("addable")) { - Debug.output("LayerAddPanel: " + addableList); - } - - Vector layerClassList = PropUtils.parseSpacedMarkers(addableList); - - if (layerClassList == null) { - return layerHash; - } - - // debug info: available layers - int unNamedCount = 1; - for (String layerClassString : layerClassList) { - String className = props.getProperty(layerClassString + ".class"); - String prettyName = props.getProperty(layerClassString + ".prettyName"); - - if (prettyName == null) { - prettyName = "Layer " + (unNamedCount++); - } - - if (className != null) { - if (Debug.debugging("addable")) { - Debug.output(" adding " + className + ", " + className); - } - layerHash.put(prettyName, className); - } - } - return layerHash; - } - - /** - * Create a layer given a class name and property prefix to be used as a - * name. - * - * @param className class of layer to create. - * @param prefix pretty name and property prefix. - */ - protected void createLayer(String className, String prefix) { - Object obj = ComponentFactory.create(className); - - if (obj instanceof Layer || obj instanceof PlugIn) { - - if (obj instanceof PlugIn) { - PlugInLayer pil = new PlugInLayer(); - pil.setPlugIn((PlugIn) obj); - layer = pil; - } else { - layer = (Layer) obj; - } - - // Set the pretty name to what the user chose. - ((Layer) layer).setName(prefix); - - prefixTextField.setText(""); - if (classTextField != null) { - classTextField.setText(""); - } - - WindowSupport ws = getWindowSupport(); - if (ws != null) { - ws.cleanUp(); - } - } - - if (obj instanceof PropertyConsumer) { - // Set the prefix to a modified version of the pretty name. - prefix = propertyHandler.getUniquePrefix(prefix); - ((PropertyConsumer) obj).setPropertyPrefix(prefix); - inspector.inspectPropertyConsumer((PropertyConsumer) obj); - } - } - - /** - * Method associated with the ActionListener interface. - */ - public void actionPerformed(ActionEvent e) { - - if (e.getActionCommand() == Inspector.doneCommand) { - // the confirmation button of the Inspector panel was - // pressed - // find the beancontext and add the layer at hand (var. - // layer) - if (layer != null && layerHandler != null) { - if (layer instanceof Layer) { - // Let's add it on top, so the user can find it - // easier, instead of adding it to the bottom and - // having it lost behind some other layers. - layerHandler.addLayer((Layer) layer, 0); - } - prefixTextField.setText(DefaultLayerName); - } else if (layerHandler != null) { - String message = i18n.get(LayerAddPanel.class, "noLayerHandlerMessage", "Layer Handler not found.\nCan't find anything to add the layer to."); - JOptionPane.showMessageDialog(this, message); - } else { - String message = i18n.get(LayerAddPanel.class, "noLayerCreatedMessage", "No Layer instantiated."); - JOptionPane.showMessageDialog(this, message); - } - } else if (e.getActionCommand() == Inspector.cancelCommand) { - if (layer != null && propertyHandler != null) { - propertyHandler.removeUsedPrefix(((PropertyConsumer) layer).getPropertyPrefix()); - } - } - } - - /** - * Show the panel in a JFrame. - */ - public void showPanel() { - createPanel(); - prefixTextField.setText(DefaultLayerName); - - WindowSupport ws = getWindowSupport(); - - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - if (ws == null) { - ws = new WindowSupport(this, i18n.get(LayerAddPanel.class, "title", "Add Layer")); - setWindowSupport(ws); - } - - ws.displayInWindow(frame, -1, -1, -1, -1); - } - - /** - * Looks for PropertyHandler and LayerHandler. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof PropertyHandler) { - // do the initializing that need to be done here - Debug.message("layerspanel", "LayerAddPanel found a LayerHandler"); - propertyHandler = (PropertyHandler) someObj; - } - if (someObj instanceof LayerHandler) { - layerHandler = (LayerHandler) someObj; - } - } - - /** - * Disconnect from any objects that are removed from MapHandler. - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof PropertyHandler && propertyHandler == someObj) { - // do the initializing that need to be done here - Debug.message("addable", "LayerAddPanel removing PropertyHandler"); - propertyHandler = null; - } - if (someObj instanceof LayerHandler && someObj == layerHandler) { - Debug.message("addable", "LayerAddPanel removing LayerHandler"); - layerHandler = null; - } - } - -} diff --git a/src/openmap/com/bbn/openmap/gui/LayerPane.java b/src/openmap/com/bbn/openmap/gui/LayerPane.java deleted file mode 100644 index b654b9d77..000000000 --- a/src/openmap/com/bbn/openmap/gui/LayerPane.java +++ /dev/null @@ -1,477 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies, a Verizon Company -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayerPane.java,v $ -// $RCSfile: LayerPane.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/06/13 21:33:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.io.Serializable; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.AbstractButton; -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; - -/** - * A LayerPane is a single instance of how a layer represented in the - * LayersPanel. It contains three widgets: an on/off button; a palette button; - * and a toggle button with the layer name. - *

- */ -public class LayerPane extends JPanel implements Serializable, ActionListener, - ComponentListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.LayerPane"); - - protected transient AbstractButton onoffButton; - protected transient AbstractButton paletteButton; - protected transient JToggleButton layerName; - protected transient boolean selected; - protected transient Layer layer; - - protected transient LayerHandler layerHandler; - - // the icons - protected static transient URL url1; - protected static transient ImageIcon paletteIcon; - protected static transient URL url2; - protected static transient ImageIcon paletteOnIcon; - protected static transient URL url3; - protected static transient ImageIcon layerOnIcon; - protected static transient URL url4; - protected static transient ImageIcon layerOffIcon; - - public transient final static String showPaletteCmd = "showPalette"; - public transient final static String toggleLayerCmd = "toggleLayerCmd"; - - protected Color offColor; - protected Color onColor = new Color(0xFF0066CC); - - protected I18n i18n = Environment.getI18n(); - - // default initializations - static { - url1 = LayerPane.class.getResource("PaletteOff.gif"); - paletteIcon = new ImageIcon(url1, "Palette"); - url2 = LayerPane.class.getResource("PaletteOn.gif"); - paletteOnIcon = new ImageIcon(url2, "Palette on"); - - url3 = LayerPane.class.getResource("BulbOn.gif"); - layerOnIcon = new ImageIcon(url3, "Layer selected"); - url4 = LayerPane.class.getResource("BulbOff.gif"); - layerOffIcon = new ImageIcon(url4, "Layer not selected"); - } - - /** - * @param layer the layer to be represented by the pane. - * @param bg the buttongroup for the layer - * @param layerHandler the LayerHandler that contains information about the - * Layers. - */ - public LayerPane(Layer layer, LayerHandler layerHandler, ButtonGroup bg) { - super(); - this.layer = layer; - setLayerHandler(layerHandler); - createGUI(bg); - layer.addComponentListener(this); - } - - protected void createGUI(ButtonGroup bg) { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - layerName = new JToggleButton(layer.getName()); - layerName.setBorderPainted(false); - layerName.addActionListener(this); - - offColor = layerName.getBackground(); - layerName.setToolTipText(i18n.get(LayerPane.class, - "layerName.tooltip", - "Click to select layer")); - layerName.setHorizontalAlignment(SwingConstants.LEFT); - bg.add(layerName); - - c.gridy = 0; - c.gridx = GridBagConstraints.RELATIVE; - c.anchor = GridBagConstraints.WEST; - c.insets = new Insets(0, 0, 0, 0); - - onoffButton = getOnOffButton(); - gridbag.setConstraints(onoffButton, c); - add(onoffButton); - - paletteButton = getPaletteButton(); - gridbag.setConstraints(paletteButton, c); - add(paletteButton); - - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(layerName, c); - add(layerName); - } - - /** - * Simply creates the AbstractButton object that turns the layer on/off. - * Override this if you want to change the kind of button used. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton createOnOffButton() { - return new JCheckBox(layerOffIcon); - } - - /** - * Calls createOnOFfButton to create the button, and then adds all the - * behavior settings to the button. Override this if you want to change - * everything about the button. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton getOnOffButton() { - AbstractButton onoffButton = createOnOffButton(); - onoffButton.setSelectedIcon(layerOnIcon); - onoffButton.setActionCommand(toggleLayerCmd); - onoffButton.addActionListener(this); - - String interString = i18n.get(LayerPane.class, - "onoffButton.tooltip", - "Turn \"{0}\" layer on/off", - layer.getName()); - onoffButton.setToolTipText(interString); - // Determine if this layer has already been activated - onoffButton.setSelected(layer.isVisible()); - onoffButton.setEnabled(layer.isRemovable()); - return onoffButton; - } - - /** - * Simply creates the AbstractButton object that turns the layer palette - * on/off. Override this if you want to change the kind of button used. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton createPaletteButton() { - return new JCheckBox(paletteIcon); - } - - /** - * Calls createPaletteButton to create the button, and then adds all the - * behavior settings to the button. Override this if you want to change - * everything about the button. - * - * @return AbstractButton in an off state. - */ - protected AbstractButton getPaletteButton() { - AbstractButton paletteButton = createPaletteButton(); - paletteButton.setSelectedIcon(paletteOnIcon); - paletteButton.setBorderPainted(false); - - String interString; - if (!layer.hasGUI()) { - interString = i18n.get(LayerPane.class, - "paletteButton.noPaletteAvailable.tooltip", - "No tools available for \"{0}\" layer", - layer.getName()); - paletteButton.setEnabled(false); - } else { - interString = i18n.get(LayerPane.class, - "paletteButton.paletteAvailable.tooltip", - "Display tools for \"{0}\" layer", - layer.getName()); - } - paletteButton.setToolTipText(interString); - - paletteButton.setActionCommand(showPaletteCmd); - paletteButton.addActionListener(this); - return paletteButton; - } - - /** - * Used for the background LayerPanel marker. - */ - protected LayerPane(String title) { - super(); - // prevent null pointers somewhere... - this.layer = com.bbn.openmap.layer.SinkLayer.getSharedInstance(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - setLayout(gridbag); - - JSeparator sep = new JSeparator(); - sep.setToolTipText(title); - - c.anchor = GridBagConstraints.WEST; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - gridbag.setConstraints(sep, c); - add(sep); - } - - public void setLayerHandler(LayerHandler in_layerHandler) { - layerHandler = in_layerHandler; - } - - /** - * @return LayerHandler if it has been found in the MapHandler or set. - */ - protected LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Same as cleanup, except the layer name toggle button gets removed from - * the given button group. - */ - public void cleanup(ButtonGroup bg) { - if (bg != null) { - bg.remove(layerName); - } - cleanup(); - } - - /** - * LayerPane disconnects from listeners, nulls out components, shuts down - * layer palette. - */ - public void cleanup() { - layerName.setSelected(false); - - if (layer != null) { - this.layer.setPaletteVisible(false); - this.layer.removeComponentListener(this); - } - if (onoffButton != null) { - onoffButton.removeActionListener(this); - } - if (paletteButton != null) { - paletteButton.removeActionListener(this); - } - layerName = null; - this.layer = null; - this.layerHandler = null; - this.removeAll(); - } - - public Dimension getPreferredSize() { - return new Dimension(200, 32); - } - - public Dimension getMinimumSize() { - return new Dimension(100, 20); - } - - /** - * @return whether the layer is on - */ - public boolean isLayerOn() { - return onoffButton.isSelected(); - } - - /** - * Turns the button on or off - */ - public void setLayerOn(boolean value) { - onoffButton.setSelected(value); - } - - /** - * @return whether the palette for this layer is on - */ - public boolean isPaletteOn() { - return paletteButton.isSelected(); - } - - /** - * Turns the palette button on or off - */ - public void setPaletteOn(boolean value) { - paletteButton.setSelected(value); - } - - /** - * @return the status of the layerName toggle button - */ - public boolean isSelected() { - return layerName.isSelected(); - } - - /** - * Highlights/de-highlights the panel border. - */ - public void setSelected(boolean select) { - String command = select ? LayersPanel.LayerSelectedCmd - : LayersPanel.LayerDeselectedCmd; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerPane for " + getLayer().getName() + " " + command - + ", firing event"); - } - - if (select) { - setBorder(BorderFactory.createLoweredBevelBorder()); - } else { - setBorder(null); - } - - firePropertyChange(command, null, getLayer()); - } - - /** - * @return the layer represented by this LayerPane - */ - public Layer getLayer() { - return layer; - } - - /** - * Tell the pane to check with the layer to get the current layer name for - * it's label. - */ - public void updateLayerLabel() { - layerName.setText(getLayer().getName()); - } - - protected void showPalette() { - layer.showPalette(); - // This is needed in case the palette button is pressed, and the palette - // is already visible. Without this, the button toggles off even though - // the palette remains up. - setPaletteOn(true); - } - - protected void hidePalette() { - layer.hidePalette(); - } - - /** - * ActionListener interface. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - - if (e.getSource().equals(paletteButton)) { - layerName.doClick(); - showPalette(); - } else if (e.getSource().equals(onoffButton)) { - layerName.doClick(); - // layer is selected, add it to or remove it from map - if (layerHandler != null) { - logger.fine("LayerPane|actionPerformed calling layerHandler.turnLayerOn()"); - layerHandler.turnLayerOn(onoffButton.isSelected(), layer); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " - + layer.getName() - + (layer.isVisible() ? " is visible." - : " is NOT visible")); - } - } else if (e.getSource().equals(layerName)) { - setSelected(layerName.isSelected()); - } - } - - /** - * Invoked when component has been resized. - */ - public void componentResized(ComponentEvent e) {} - - /** - * Invoked when component has been moved. - */ - public void componentMoved(ComponentEvent e) {} - - /** - * Invoked when component has been shown. - */ - public void componentShown(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer pane for " + layer.getName() - + " receiving componentShown event"); - } - - Component comp = e.getComponent(); - if (comp == null) { - } else if (comp == layer) { - if (isLayerOn() != true) { - setLayerOn(true); - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now visible."); - } - } - } else if (comp == layer.getPalette()) { - setPaletteOn(true); - } - } - - /** - * Invoked when component has been hidden. - */ - public void componentHidden(ComponentEvent e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer pane for " + layer.getName() - + " receiving componentHidden event"); - } - Component comp = e.getComponent(); - - if (comp == layer) { - if (isLayerOn() != false) { - setLayerOn(false); - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now hidden."); - } - } - } else if (comp == layer.getPalette()) { - setPaletteOn(false); - } else if (comp == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer " + layer.getName() + " is now hidden."); - } - } - } - - public static LayerPane getBackgroundLayerSeparator(String title) { - return new LayerPane(title); - } -} diff --git a/src/openmap/com/bbn/openmap/gui/LayersMenu.java b/src/openmap/com/bbn/openmap/gui/LayersMenu.java deleted file mode 100644 index e496eb62e..000000000 --- a/src/openmap/com/bbn/openmap/gui/LayersMenu.java +++ /dev/null @@ -1,606 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayersMenu.java,v $ -// $RCSfile: LayersMenu.java,v $ -// $Revision: 1.11 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.beans.PropertyVetoException; -import java.io.Serializable; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenuItem; -import javax.swing.JSeparator; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.util.Debug; - -/** - * The LayersMenu is a JMenu which is a list of the layers of the map. This - * LayersMenu expects to work with a LayerHandler containing all the possible - * layers that may be added to the map. This list defaults to being checkbuttons - * which add and remove the named layer to/from the Map. You can also use an - * instance of this object to show/hide layer palettes. - *

- * - * This object is interested in contacting a LayerHandler to find out all the - * layers available, and optionally, a LayersPanel in order to provide a menu - * item that will call up the GUI for the LayersPanel. If this LayersMenu is a - * member of a BeanContext, it expects that only one of each of these objects - * will be added, but if more than one per type is added, the last one added to - * be BeanContext will be the one hooked up to this LayersMenu. - */ -public class LayersMenu extends AbstractOpenMapMenu implements Serializable, LayerListener { - - /** - * Static value to set this menu to control layer visibility. - */ - public static final transient int LAYERS_ON_OFF = 1; - /** - * Static value to set this menu to control layer palette visibility. - */ - public static final transient int PALETTES_ON_OFF = 2; - /** - * The flag setting the behavior of the menu, whether it controls the layers - * or the layers palettes. - */ - protected int menuType = -1; - /** - * The LayerHandler to listen to for layers available for the map. - */ - protected transient LayerHandler layerHandler; - /** - * Used by the BeanContext methods to insure that the component we - * disconnect the edit button from is the same one being removed from the - * BeanContext. - */ - protected transient LayersPanel layersPanel; - /** A button on the bottom of the menu to bring up the layersPanel. */ - protected transient JMenuItem edit = null; - /** The default edit button title. */ - public final static String defaultEditLayersButtonTitle = "Edit Layers..."; - /** The actual edit button title. */ - protected transient String editLayersButtonTitle = defaultEditLayersButtonTitle; - /** The menu item to add a layer to the map. */ - protected transient JMenuItem add = null; - /** The default add button title. */ - protected transient String addLayersButtonTitle = "Add Layers..."; - - /** - * Construct LayersMenu. - */ - public LayersMenu() { - this(null); - } - - /** - * Construct LayersMenu. - * - * @param lHandler the handler for the layer - */ - public LayersMenu(LayerHandler lHandler) { - this(lHandler, "Layers", LAYERS_ON_OFF); - } - - /** - * Construct LayersMenu. - * - * @param lHandler the handler for the layer - * @param menuName the name of the menu - * @param menuType either LAYERS_ON_OFF, or PALETTES_ON_OFF - */ - public LayersMenu(LayerHandler lHandler, String menuName, int menuType) { - super(); - this.menuType = menuType; - setText(menuName); - // setMnemonic('L');// HMMMM - - layerHandler = lHandler; - - // Layers will be turned on by something else initially. - if (layerHandler != null) { - setLayers(layerHandler.getLayers()); - } - } - - /** - * Set the LayerHandler that the LayersPanel listens to. If the LayerHandler - * is not null, the LayersMenu will be added to the LayerHandler - * LayerListener list, and the LayersMenu will receive a LayerEvent with the - * current layers. - *

- * - * If there is a LayerHandler that is already being listened to, then the - * LayersPanel will remove itself from current LayerHandler as a - * LayerListener, before adding itself to the new LayerHandler. - *

- * - * Lastly, if the LayerHandler passed in is null, the LayersPanel will - * disconnect itself from any LayerHandler currently held, and reset itself - * with no layers. - * - * @param lh the LayerHandler containing the layers. - */ - public void setLayerHandler(LayerHandler lh) { - if (layerHandler != null) { - layerHandler.removeLayerListener(this); - } - - layerHandler = lh; - if (layerHandler != null) { - layerHandler.addLayerListener(this); - } else { - setLayers(new Layer[0]); - } - } - - /** - * Get the LayerHandler that the LayersPanel listens to. - */ - public LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Set the LayersPanel privately to keep track of what object is being used - * from the BeanContext. - */ - protected void setLayersPanel(LayersPanel lp) { - layersPanel = lp; - } - - /** - * Get the LayersPanel, privately held to keep track of what object is being - * used from the BeanContext. - */ - protected LayersPanel getLayersPanel() { - return layersPanel; - } - - /** - * Return the title of the menu option to call up LayersPanel. - */ - public void setEditLayersButtonTitle(String buttonTitle) { - editLayersButtonTitle = buttonTitle; - } - - /** - * Return the title of the menu option to call up LayersPanel. - */ - public String getEditLayersButtonTitle() { - return editLayersButtonTitle; - } - - /** - * Set the edit menu item that triggers the LayersPanel action listener. - * Assumes that it's already wired up. - */ - public void setEdit(JMenuItem e) { - edit = e; - - // This actually adds the edit button to the bottom of the - // LayerMenu when the menu is reconstructed. - if (getLayerHandler() != null) { - setLayers(getLayerHandler().getLayers()); - } - } - - /** - * Set the add menu item. - */ - public void setAdd(JMenuItem a) { - add = a; - if (getLayerHandler() != null) { - setLayers(getLayerHandler().getLayers()); - } - } - - /** - * Get the edit menu item that triggers the LayersPanel action listener. - */ - public JMenuItem getEdit() { - return edit; - } - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. - * - * @param evt a LayerEvent - */ - public void setLayers(LayerEvent evt) { - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - setLayers(layers); - } - } - - /** - * Set the layers that are on the menu. Calls for AWT thread to update - * layers - * - * @param inLayers the array of layers. - */ - public void setLayers(Layer[] inLayers) { - if (SwingUtilities.isEventDispatchThread()) { - setLayersFromEDT(inLayers); - } else { - SwingUtilities.invokeLater(new MyWorker(inLayers)); - } - } - - protected void setLayersFromEDT(Layer[] inLayers) { - removeAll(); - - // Set everything up for the new layers - if (inLayers == null) { - if (Debug.debugging("layersmenu")) { - Debug.error("LayersMenu.setLayers(): Layers are null."); - } - } else { - for (Layer layer : inLayers) { - LayerCheckBoxMenuItem cbs = new LayerCheckBoxMenuItem(layer); - cbs.setEnabled(layer.isRemovable()); - add(cbs); - } - } - - if (edit != null) { - add(new JSeparator()); - add(edit); - } - if (add != null) { - add(add); - } - } - - /** - * Remove all the components from the menu. Also calls cleanup() on all the - * LayerCheckBoxMenuItems, so they can remove themselves from their layers. - */ - public void removeAll() { - Component[] components = getMenuComponents(); - - if (components.length > 0) { - Debug.message("layersmenu", "LayersMenu.removeAll(): purging menu"); - } - - for (int i = 0; i < components.length; i++) { - if (components[i] instanceof LayerCheckBoxMenuItem) { - ((LayerCheckBoxMenuItem) components[i]).cleanup(); - } - } - super.removeAll(); - } - - /** - * Update the layer names. - */ - public synchronized void updateLayerLabels() { - if (layerHandler != null) { - setLayers(layerHandler.getLayers()); - } - } - - /** - * CheckBoxMenuItem that encapsulates a Layer. - */ - class LayerCheckBoxMenuItem extends JCheckBoxMenuItem implements ActionListener, ComponentListener { - /** The layer that the button triggers. */ - Layer layer; - /** - * Let's be safe - */ - Object LAYER_LOCK = new Object(); - - /** - * Construct the menu item, connected to the given layer. - */ - LayerCheckBoxMenuItem(Layer aLayer) { - if (aLayer == null) { - throw new IllegalArgumentException("null Layer"); - } - synchronized (LAYER_LOCK) { - layer = aLayer; - } - this.setText(layer.getName()); - setState(layer.isVisible()); - - this.addActionListener(this); - layer.addComponentListener(this); - } - - /** Get the layer for this checkbox. */ - public Layer getLayer() { - synchronized (LAYER_LOCK) { - return layer; - } - } - - /** - * Disconnect all the listeners from the layer, clean up other - * references. - */ - public void cleanup() { - this.removeActionListener(this); - if (layer != null) { - layer.removeComponentListener(this); - } - - synchronized (LAYER_LOCK) { - layer = null; - } - } - - /** - * If this widget is being used for bringing up palettes, bring up the - * layer's palette. - */ - protected void showPalette() { - Layer layer = getLayer(); - if (layer != null) { - layer.showPalette(); - } - } - - /** - * If this widget is being used for bringing up palettes, hide the - * layer's palette. - */ - protected void hidePalette() { - Layer layer = getLayer(); - if (layer != null) { - layer.hidePalette(); - } - } - - /** This menu item listens to the status of its layer. */ - public void componentResized(ComponentEvent e) { - } - - /** This menu item listens to the status of its layer. */ - public void componentMoved(ComponentEvent e) { - } - - /** - * This menu item listens to the status of its layer. If the layer - * becomes visible, it makes the check box enabled. - */ - public void componentShown(ComponentEvent e) { - Layer layer = getLayer(); - if (layer != null) { - if (e.getComponent() == layer) { - if (getState() != true && menuType == LAYERS_ON_OFF) { - setState(true); - if (Debug.debugging("layersmenu")) { - Debug.output("layersmenu.LCBMI: layer " + layer.getName() - + " is now visible."); - } - } - } else if (e.getComponent() == layer.getPalette() && menuType == PALETTES_ON_OFF) { - setState(true); - } - } - } - - /** - * This menu item listens to the status of its layer. If the layer - * becomes invisible, it disables the check box. - */ - public void componentHidden(ComponentEvent e) { - Layer layer = getLayer(); - if (layer != null) { - if (e.getComponent() == layer) { - if (getState() != false && menuType == LAYERS_ON_OFF) { - setState(false); - if (Debug.debugging("layersmenu")) { - Debug.output("layersmenu.LCBMI: layer " + layer.getName() - + " is now hidden."); - } - } - } else if (e.getComponent() == layer.getPalette() && menuType == PALETTES_ON_OFF) { - setState(false); - } - } - } - - /** - * Triggered by the menu item check button. - * - * @param e ActionEvent fired by the button. - */ - public void actionPerformed(ActionEvent e) { - - if (!this.equals(e.getSource())) { - Debug.error("Wiring is hopelessly wrong in LayersMenu"); - } - switch (menuType) { - case LAYERS_ON_OFF: - layerHandler.turnLayerOn(getState(), getLayer()); - break; - case PALETTES_ON_OFF: - if (getState()) - showPalette(); - else - hidePalette(); - break; - default: - System.err.println("LayersMenu: unknown menuType!"); - } - } - } - - /** - * Given a LayersPanel, set up a JButton to add to the end of the LayersMenu - * that will trigger the action listener of the LayersPanel. - * - * @param lp the LayersPanel to ask for an ActionListener from. - */ - public void setupEditLayersButton(LayersPanel lp) { - // initialize the Edit Layers... button. - JMenuItem button = new JMenuItem(i18n.get(LayersMenu.class, "editLayersButtonTitle", editLayersButtonTitle)); - button.setActionCommand("edit"); - button.addActionListener(lp.getActionListener()); - setEdit(button); - setLayersPanel(lp); - } - - /** - * Constructs the menu item that will bring up the LayerAddPanel. - */ - public void setupLayerAddButton(final LayerAddPanel menu) { - final LayerAddPanel lap = menu; - - if (menu != null) { - JMenuItem button = new JMenuItem(i18n.get(LayersMenu.class, "addLayersButtonTitle", addLayersButtonTitle)); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - lap.showPanel(); - } - }); - - setAdd(button); - add(button); - } - } - - /** - * Called when the BeanContext membership changes with object from the - * BeanContext. This lets this object hook up with what it needs. It expects - * to find only one LayerHandler and LayersPanel in the BeanContext. If - * another LayerHandler/LayersPanel is somehow added to the BeanContext, - * however, it will drop the connection to the component it is set up to - * listen to, and rewire itself to reflect the status of the last version of - * the LayerHandler/LayersPanel found. - * - * @param someObj Object received in the BeanContext or - * BeanContextMembershipEvent. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu found a LayerHandler"); - setLayerHandler((LayerHandler) someObj); - } else if (someObj instanceof LayersPanel) { - setupEditLayersButton((LayersPanel) someObj); - } else if (someObj instanceof LayerAddPanel) { - // if a LayerAddPanel is present, do the necessary things - setupLayerAddButton((LayerAddPanel) someObj); - } - } - - /** - * Called when objects are removed from the BeanContext. Should be used to - * check for relevant objects that need to be disconnected from this object. - * This method does check to see if a LayerHandler or LayersPanel is being - * removed, that it is the same object currently being used by this - * LayersMenu. - * - * @param someObj the object being removed from the BeanContext - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerHandler) { - - LayerHandler lh = (LayerHandler) someObj; - // Need to check to see if this layerhandler is the - // same as the one we have !!!! - if (lh != getLayerHandler()) { - Debug.message("bc", "LayersMenu asked to remove LayerHandler that is not the same as what is currently held - ignoring request."); - return; - } - - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu.childrenRemoved: removing LayerHandler"); - setLayerHandler(null); - setEdit(null); - } - if (someObj instanceof LayersPanel) { - LayersPanel lp = (LayersPanel) someObj; - // There's a problem here. We can't tell if the - // LayersPanel being removed is the owner of the - // action listener used by the edit button. If two - // LayersPanels have been added to the BeanContext, - // and we're now listening to the second one, then if - // the first one is removed, we are forced here to - // disconnect from the second and valid one. Looks - // like we need to maintain a handle on the - // LayersPanel being triggered. - if (lp != getLayersPanel()) { - Debug.message("bc", "LayersMenu asked to remove LayersPanel that is not the same as what is currently held - ignoring request."); - return; - } - // do the initializing that need to be done here - Debug.message("bc", "LayersMenu.childrenRemoved: removing LayersPanel"); - setLayersPanel(null); - setEdit(null); - } - } - - /** - * Report a vetoable property update to any registered listeners. If anyone - * vetos the change, then fire a new event reverting everyone to the old - * value and then rethrow the PropertyVetoException. - *

- * - * No event is fired if old and new are equal and non-null. - *

- * - * @param name The programmatic name of the property that is about to change - * - * @param oldValue The old value of the property - * @param newValue - The new value of the property - * - * @throws PropertyVetoException if the recipient wishes the property change - * to be rolled back. - */ - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - super.fireVetoableChange(name, oldValue, newValue); - beanContextChildSupport.fireVetoableChange(name, oldValue, newValue); - } - - class MyWorker implements Runnable { - - private Layer[] layers; - - public MyWorker(Layer[] inLayers) { - layers = inLayers.clone(); - } - - public void run() { - try { - setLayersFromEDT(layers); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/openmap/com/bbn/openmap/gui/LayersPanel.java b/src/openmap/com/bbn/openmap/gui/LayersPanel.java deleted file mode 100644 index 778a40a79..000000000 --- a/src/openmap/com/bbn/openmap/gui/LayersPanel.java +++ /dev/null @@ -1,1106 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/LayersPanel.java,v $ -// $RCSfile: LayersPanel.java,v $ -// $Revision: 1.17 $ -// $Date: 2009/02/26 21:16:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.ButtonModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JScrollBar; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; - -import com.bbn.openmap.BufferedLayerMapBean; -import com.bbn.openmap.I18n; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.LayerListener; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The LayersPanel displays the list of layers that OpenMap can display. The - * layer name is displayed accompanied by an on/off button and a tool palette - * button. Pressing the on/off button will cause the the map to display/remove - * the layer. Pressing the tool palette button will cause a window to be - * displayed containing widgets specific to that layer. - *

- * - * The order of the layers in the list reflects the order that the layers are - * displayed on the map, with the bottom-most layer listed on the panel - * underneath all the the other layers displayed on the map. The order of the - * layers is determined by their order in the Layer[] passed in the setLayers - * method. - *

- * - * The order of the layers can be changed by sending the LayersPanel an - * ActionEvent with one of the string commands in the class, or by sending a - * PropertyChangeEvent with a command and a Layer as the new value. - *

- * - * In the standard GUI, the order can be changed by selecting a layer by - * clicking on the layer's name (or on either of buttons), then clicking on one - * of the four buttons on the left side of the panel. The four buttons signify, - * from top to bottom: Move the selected layer to the top; Move the selected - * layer up one position; Move the selected layer down one position; Move the - * selected layer to the bottom. - *

- * - * The LayersPanel can be used within a BeanContext. If it is added to a - * BeanConext, it will look for a LayerHandler to add itself to as a - * LayerListener. The LayersPanel can only listen to one LayerHandler, so if - * more than one is found, only the last one found will be used. If another - * LayerHandler is added to the BeanContext later, the new LayerHandler will be - * used. The LayersPanel is also considered to be a Tool, which will cause a - * button that will bring up the LayersPanel to be automatically added to the - * ToolPanel if a ToolPanel is part of the BeanContext. - *

- * - * When the LayersPanel discovers a BufferedLayerMapBean is being used, it adds - * a special LayerPane to its LayerPane list that shows which layers are being - * buffered in the MapBean. This special LayerPane shows up as a line in the - * list, and all layers below that line are being specially buffered by the - * BufferedLayerMapBean. - *

- * - * The properties that can be set for the LayersPanel: - * - *

- * 
- * 
- * 
- *          # Use LayerStatusPanes for the layers if true, otherwise
- *          # LayerPanes.  LayerStatusPanes turn the on/off bulbs to green/red
- *          # bulbs when the layer is resting/working.  LayerPanes just show
- *          # yellow bulbs when the layer is part of the map.
- *          showStatus=true
- *          # When the BufferedLayerMapBean is used, a divider will be
- *          # displayed in the list of layers showing which layers are in the
- *          # MapBean buffer (below the line).  Commands to move layers, by
- *          # default, respect this divider, requiring more commands to have
- *          # layers cross it.
- *          boundary=true
- *          # Add control buttons - use "none" for no button.  If undefined,
- *          # the LayerControlButtonPanel will be created automatically.
- *          controls=com.bbn.openmap.gui.LayerControlButtonPanel
- *          # Any control properties added here, prepended by "controls"...
- *          controls.configuration=WEST
- * 
- * 
- * 
- * 
- */ -public class LayersPanel extends OMToolComponent - implements Serializable, ActionListener, LayerListener, PropertyChangeListener { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.LayersPanel"); - - /** Action command for the layer order buttons. */ - public final static String LayerTopCmd = "LayerTopCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerBottomCmd = "LayerBottomCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerUpCmd = "LayerUpCmd"; - /** Action command for the layer order buttons. */ - public final static String LayerDownCmd = "LayerDownCmd"; - /** Action command removing a layer. */ - public final static String LayerRemoveCmd = "LayerRemoveCmd"; - /** Action command adding a layer. */ - public final static String LayerAddCmd = "LayerAddCmd"; - /** Action command for notification that a layer has been selected. */ - public final static String LayerSelectedCmd = "LayerSelected"; - /** - * Action command for notification that a layer has been deselected. Not so - * reliable. Usually a selection notification means that others are - * deselected. - */ - public final static String LayerDeselectedCmd = "LayerDeselected"; - - /** - * A property to set the class to create for layer order controls. If - * undefined, a LayerControlButtonPanel in its default configuration will be - * created. For no controls added, use (none) for this property. - */ - public final static String ControlButtonsProperty = "controls"; - /** - * A property that can be used for controlling how the to top and to bottom - * commands will be interpreted when a BufferedLayerMapBean is used. See the - * definition of bufferedBoundary. - */ - public final static String BufferedBoundaryProperty = "boundary"; - /** - * A property that can be used for controlling what type of LayerPanes are - * used. If true (default) a LayerStatusPane will be created for each layer. - * Otherwise, a LayerPane will be used. - */ - public final static String ShowStatusProperty = "showStatus"; - - /** - * A value for the (controls) property to not include control buttons in the - * interface. - */ - public final static String NO_CONTROLS = "none"; - - /** Default key for the LayersPanel Tool. */ - public final static String defaultKey = "layerspanel"; - - /** - * The LayerHandler to listen to for LayerEvents, and also to notify if the - * layer order should change. - */ - protected transient LayerHandler layerHandler = null; - /** - * Panel that lets you dynamically add and configure layers. - */ - protected transient LayerAddPanel layerAddPanel = null; - /** - * The components holding the layer name label, the on/off indicator and on - * button, and the palette on/off indicator and palette on button. - */ - protected transient List panes; - /** The internal component that holds the panes. */ - protected transient JPanel panesPanel; - /** The scroll pane to use for panes. */ - protected transient JScrollPane scrollPane; - /** The Layer order adjustment button group. */ - protected transient ButtonGroup bg; - /** The ActionListener that will bring up the LayersPanel. */ - protected ActionListener actionListener; - /** The set of buttons that control the layers. */ - protected LayerControlButtonPanel controls = null; - /** - * Hashtable that tracks LayerPanes for layers, with the layer as the key - * and LayerPane as the value. - */ - protected Hashtable paneLookUp = new Hashtable(); - /** - * A special LayerPane used when the LayersPanel senses that a - * BufferedLayerMapBean is being used. This LayersPanel is a separating line - * showing which layers are part of the MapBean's buffer, and which are not. - */ - protected LayerPane backgroundLayerSeparator = null; - /** - * Behavior flag so that if there is a background buffered layer on the - * MapBean, and a buffered layer divider in the LayersPanel, whether - * commands instructing a layer to the top or bottom of the list should - * honor the virtual boundary between buffered and unbuffered layers. That - * is, if a layer is on the bottom of the buffered list and is instructed to - * go to the top of the overall list, it will only first travel to the top - * of the buffered layers. On a subsequent top command, it will go to the - * top of the list. The same behavior applies for going down. True is - * default. If set to false, these commands will just send the selected - * layer to the top and bottom of the entire list. - */ - protected boolean bufferedBoundary = true; - - /** - * Behavior flag that determines what kind of LayerPane is used for the - * layers. If true (default) the LayerStatusPane will be used. Otherwise, - * the LayerPane will be used instead. - */ - protected boolean showStatus = true; - - /** - * Construct the LayersPanel. - */ - public LayersPanel() { - super(); - setKey(defaultKey); - setLayout(new BorderLayout()); - } - - /** - * Construct the LayersPanel. - * - * @param lHandler the LayerHandler controlling the layers. - */ - public LayersPanel(LayerHandler lHandler) { - this(); - setLayerHandler(lHandler); - } - - /** - * Construct the LayersPanel. - * - * @param lHandler the LayerHandler controlling the layers. - * @param addLayerControls if true, buttons that modify layer positions will - * be added. - */ - public LayersPanel(LayerHandler lHandler, boolean addLayerControls) { - this(lHandler); - if (addLayerControls) { - addLayerControls(); - } - } - - /** - * Set the LayerHandler that the LayersPanel listens to. If the LayerHandler - * passed in is not null, the LayersMenu will be added to the LayerHandler - * LayerListener list, and the LayersMenu will receive a LayerEvent with the - * current layers. - *

- * - * If there is a LayerHandler that is already being listened to, then the - * LayersPanel will remove itself from current LayerHandler as a - * LayerListener, before adding itself to the new LayerHandler. - *

- * - * Lastly, if the LayerHandler passed in is null, the LayersPanel will - * disconnect itself from any LayerHandler currently held, and reset itself - * with no layers. - * - * @param lh LayerHandler to listen to, and to use to reorder the layers. - */ - public void setLayerHandler(LayerHandler lh) { - if (layerHandler != null) { - layerHandler.removeLayerListener(this); - } - layerHandler = lh; - if (layerHandler != null) { - layerHandler.addLayerListener(this); - } else { - setLayers(new Layer[0]); - } - updateLayerPanes(layerHandler); - } - - /** - * Get the LayerHandler that the LayersPanel listens to and uses to reorder - * layers. - * - * @return LayerHandler. - */ - public LayerHandler getLayerHandler() { - return layerHandler; - } - - /** - * Set the LayerPanes with the given LayerHandler. - * - * @param layerHandler The LayerHandler controlling the layers - */ - protected void updateLayerPanes(LayerHandler layerHandler) { - for (LayerPane pane : getPanes()) { - pane.setLayerHandler(layerHandler); - } - } - - /** - * LayerListener interface method. A list of layers will be added, removed, - * or replaced based on on the type of LayerEvent. The LayersPanel only - * reacts to LayerEvent.ALL events, to reset the components in the - * LayersPanel. - * - * @param evt a LayerEvent. - */ - public void setLayers(LayerEvent evt) { - Layer[] layers = evt.getLayers(); - int type = evt.getType(); - - if (type == LayerEvent.ALL) { - logger.fine("LayersPanel received layers update"); - setLayers(layers); - } - } - - /** - * Tool interface method. The retrieval tool's interface. This method - * creates a button that will bring up the LayersPanel. - * - * @return String The key for this tool. - */ - public Container getFace() { - JButton layerButton = null; - - if (getUseAsTool()) { - layerButton = new JButton(new ImageIcon(OMToolSet.class.getResource("layers.gif"), "Layer Controls")); - layerButton.setBorderPainted(false); - // layerButton.setToolTipText("Layer Controls"); - layerButton.setToolTipText(i18n.get(LayersPanel.class, "layerButton", I18n.TOOLTIP, "Layer Controls")); - layerButton.setMargin(new Insets(0, 0, 0, 0)); - layerButton.addActionListener(getActionListener()); - } - - return layerButton; - } - - /** - * Get the ActionListener that triggers the LayersPanel. Useful to have to - * provide an alternative way to bring up the LayersPanel. - * - * @return ActionListener - */ - public ActionListener getActionListener() { - return new ActionListener() { - public void actionPerformed(ActionEvent evt) { - WindowSupport ws = getWindowSupport(); - - if (ws == null) { - ws = new WindowSupport(LayersPanel.this, i18n.get(LayersPanel.class, "title", "Layers")); - setWindowSupport(ws); - } - - // Initial settings. - int w = 328; - int h = 300; - - Dimension dim = ws.getComponentSize(); - if (dim != null) { - w = (int) dim.getWidth(); - h = (int) dim.getHeight(); - } - - int x = -1; - int y = -1; - - Point loc = ws.getComponentLocation(); - if (loc != null) { - x = (int) loc.getX(); - y = (int) loc.getY(); - } - - MapHandler mh = (MapHandler) getBeanContext(); - // Window frame = null; // java 5 incompatibility - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - /* java 5 incompatibility */ - /* - * if (frame == null && evt.getSource() instanceof Component) { - * frame = SwingUtilities.getWindowAncestor((Component) - * evt.getSource()); } - */ - ws.displayInWindow(frame, x, y, w, h); - } - }; - } - - /** - * Set the layers that are on the menu. Calls for AWT thread to update - * layers - * - * @param inLayers the array of layers. - */ - public void setLayers(Layer[] inLayers) { - if (SwingUtilities.isEventDispatchThread()) { - setLayersFromEDT(inLayers); - } else { - SwingUtilities.invokeLater(new MyWorker(inLayers)); - } - } - - /** - * Set the layers that are in the LayersPanel. Make sure that the layer[] is - * the same as that passed to any other OpenMap component, like the - * LayersMenu. This method checks to see if the layer[] has actually - * changed, in order or in size. If it has, then createPanel() is called to - * rebuild the LayersPanel. Should be called within the Event Dispatch - * Thread. - * - * @param inLayers the array of layers. - */ - protected void setLayersFromEDT(Layer[] inLayers) { - Layer[] layers = inLayers; - - if (inLayers == null) { - layers = new Layer[0]; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayersPanel.setLayers() with " + layers.length + " layers."); - } - - List panes = getPanes(); - int separatorOffset = 0; - if (backgroundLayerSeparator != null && panes.contains(backgroundLayerSeparator)) { - separatorOffset = 1; - } - - if (panes.size() - separatorOffset != layers.length) { - // if the panel hasn't been created yet, or if someone has - // changed the layers on us, rebuild the panel. - createPanel(layers); - return; - } - - int i = 0; - Iterator it = panes.iterator(); - while (it.hasNext() && i < layers.length) { - LayerPane pane = (LayerPane) it.next(); - - if (pane == backgroundLayerSeparator) { - continue; - } - - if (pane.getLayer() != layers[i]) { - // If the layer order sways at all, then we start over - // and rebuild the panel - createPanel(layers); - return; - } else { - pane.updateLayerLabel(); - } - - // Do this just in case someone has changed something - // somewhere else... - pane.setLayerOn(layers[i].isVisible()); - i++; - } - - // One last check for a mismatch... - if (it.hasNext() || i < layers.length) { - createPanel(layers); - } - // If we get here, it means that what we had is what we - // wanted. - } - - protected List getPanes() { - if (panes == null) { - panes = new LinkedList(); - } - return panes; - } - - protected void setPanes(List lpa) { - panes = lpa; - } - - GridBagLayout panelGridbag; - GridBagConstraints pgbc; - - /** - * Create the panel that shows the LayerPanes. This method creates the - * on/off buttons, palette buttons, and layer labels, and adds them to the - * scrollPane used to display all the layers. - * - * @param inLayers the Layer[] that reflects all possible layers that can be - * added to the map. - */ - public void createPanel(Layer[] inLayers) { - logger.fine("creating panel"); - - Layer[] layers = inLayers; - if (layers == null) { - layers = new Layer[0]; - } - - if (panesPanel == null) { - panesPanel = new JPanel(); - panelGridbag = new GridBagLayout(); - pgbc = new GridBagConstraints(); - - panesPanel.setLayout(panelGridbag); - - pgbc.gridwidth = GridBagConstraints.REMAINDER; - pgbc.anchor = GridBagConstraints.NORTHWEST; - pgbc.fill = GridBagConstraints.HORIZONTAL; - pgbc.weightx = 1.0f; - - } else { - ((GridBagLayout) panesPanel.getLayout()).invalidateLayout(panesPanel); - panesPanel.removeAll(); - } - - if (bg == null) { - bg = new ButtonGroup() { - public void setSelected(ButtonModel m, boolean b) { - if (!b) { - for (LayerPane pane : getPanes()) { - pane.setSelected(false); - } - } - super.setSelected(m, b); - } - }; - } - - List panes = new LinkedList(); - List backgroundPanes = new LinkedList(); - - // populate the arrays of CheckBoxes and strings used to fill - // the JPanel for the panes - for (int i = 0; i < layers.length; i++) { - Layer layer = layers[i]; - if (layer == null) { - logger.fine("caught null layer, " + i + " out of " + layers.length); - continue; - } - - LayerPane lpane = (LayerPane) paneLookUp.get(layer); - - if (lpane == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Creating LayerPane for " + layer.getName()); - } - lpane = createLayerPaneForLayer(layer, layerHandler, bg); - lpane.addPropertyChangeListener(LayerSelectedCmd, this); - lpane.addPropertyChangeListener(LayerDeselectedCmd, this); - paneLookUp.put(layer, lpane); - } else { - // In case this has been modified elsewhere... - lpane.setLayerOn(layer.isVisible()); - } - - if (layer.getAddAsBackground() && backgroundLayerSeparator != null) { - backgroundPanes.add(lpane); - } else { - panes.add(lpane); - - panelGridbag.setConstraints(lpane, pgbc); - panesPanel.add(lpane); - } - } - - if (!backgroundPanes.isEmpty()) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Adding BackgroundLayerSeparator"); - } - panes.add(backgroundLayerSeparator); - panelGridbag.setConstraints(backgroundLayerSeparator, pgbc); - panesPanel.add(backgroundLayerSeparator); - panes.addAll(backgroundPanes); - - for (LayerPane lp : backgroundPanes) { - panelGridbag.setConstraints(lp, pgbc); - panesPanel.add(lp); - } - - } else if (backgroundLayerSeparator != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("No layers are background layers, adding separator"); - } - panes.add(backgroundLayerSeparator); - panelGridbag.setConstraints(backgroundLayerSeparator, pgbc); - panesPanel.add(backgroundLayerSeparator); - } - - addFillerToPanesPanel(); - - setPanes(panes); - - if (scrollPane == null) { - scrollPane = new JScrollPane(panesPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - add(scrollPane, BorderLayout.CENTER); - } - - revalidate(); - } - - protected void addFillerToPanesPanel() { - JPanel filler = new JPanel(); - pgbc.fill = GridBagConstraints.BOTH; - pgbc.weighty = 1.0f; - panelGridbag.setConstraints(filler, pgbc); - panesPanel.add(filler); - pgbc.fill = GridBagConstraints.HORIZONTAL; - pgbc.weighty = 0.0f; - } - - /** - * Called when a new LayerPane needs to be created for a layer. You can use - * this to extend LayerPane and return something else that fits your GUI. - */ - protected LayerPane createLayerPaneForLayer(Layer layer, LayerHandler layerHandler, - ButtonGroup bg) { - if (showStatus) { - return new LayerStatusPane(layer, layerHandler, bg); - } else { - return new LayerPane(layer, layerHandler, bg); - } - } - - public void deletePanes(List dpanes) { - logger.fine("deleting panes"); - if (dpanes != null) { - paneLookUp.clear(); - - for (LayerPane pane : dpanes) { - if (pane != null && pane != backgroundLayerSeparator) { - pane.removePropertyChangeListener(this); - pane.cleanup(bg); - } - } - } - } - - /** - * Tell the LayersPanel to add layer control buttons. Does nothing if the - * controls are already set. - */ - public void addLayerControls() { - if (getControls() == null) { - setControls(createControlButtons()); - } - } - - /** - * Set up the buttons used to move layers up and down, or add/remove layers. - * The button component should hook itself up to the LayersPanel, and assume - * that the LayersPanel has a BorderLayout with the list in the center spot. - */ - public LayerControlButtonPanel createControlButtons() { - return new LayerControlButtonPanel(this); - } - - /** - * Should be called internally, when the LayersPanel creates the - * LayerControlButtonPanel. If called from the LCBP, a loop will ensue. - * - * @param lcbp - */ - protected void setControlsAndNotify(LayerControlButtonPanel lcbp) { - setControls(lcbp); - if (lcbp != null) { - lcbp.setLayersPanel(this); - } - } - - /** - * Simply sets the controls. - * - * @param lcbp - */ - public void setControls(LayerControlButtonPanel lcbp) { - controls = lcbp; - } - - public LayerControlButtonPanel getControls() { - return controls; - } - - /** - * Method associated with the ActionListener interface. This method listens - * for action events meant to change the order of the layers, as fired by - * the layer order buttons. - * - * @param e ActionEvent - */ - public void actionPerformed(java.awt.event.ActionEvent e) { - String command = e.getActionCommand(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(command); - } - - try { - LayerPane pane = findSelectedPane(); - if (pane != null) { - moveLayer(pane, command); - } - } catch (NullPointerException npe) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - } - - /** - * Change a layer's position. - */ - public void moveLayer(Layer layer, String command) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(command + " for " + layer.getName()); - } - - moveLayer((LayerPane) paneLookUp.get(layer), command); - } - - /** - * Change a layer's position, with the layer represented by a LayerPane. - */ - protected void moveLayer(LayerPane lp, String command) { - - if (lp == null) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("LayerPane not represented on list"); - } - - if (command == LayerRemoveCmd) { - // OK, here's a hidden trick. If no layers are - // selected and the minus sign is clicked, then this is called. - System.gc(); - } - return; - } - - List panes = getPanes(); - int row = panes.indexOf(lp); - - boolean boundary = false; - int bls_row = -1; - if (backgroundLayerSeparator != null) { - bls_row = panes.indexOf(backgroundLayerSeparator); - boundary = bufferedBoundary; - } - - if (command.equals(LayerTopCmd)) { - // Move layer selected layer to top - panes.remove(lp); - if (boundary && bls_row > 0 && row > bls_row + 1) { - // If the backgroundLayerSeparator is more than one - // above it, move to just below it on the first top - // command. - panes.add(bls_row + 1, lp); - } else { - panes.add(0, lp); - } - - rejiggerMapLayers(); - } else if (command.equals(LayerBottomCmd)) { - // Move layer selected layer to bottom - panes.remove(lp); - - if (boundary && bls_row > 0 && row < bls_row - 1) { - // If the backgroundLayerSeparator is more than one - // below it, move to just above it on the first top - // command. - panes.add(bls_row - 1, lp); - } else { - panes.add(panes.size(), lp); - } - - rejiggerMapLayers(); - } else if (command.equals(LayerUpCmd)) { - // Move layer selected layer up one - if (row <= 0) - return; - panes.remove(row); - panes.add(row - 1, lp); - rejiggerMapLayers(); - } else if (command.equals(LayerDownCmd)) { - // Move layer selected layer up one - if (row < 0 || row == panes.size() - 1) - return; - panes.remove(row); - panes.add(row + 1, lp); - rejiggerMapLayers(); - } else if (command.equals(LayerRemoveCmd)) { - - if (layerHandler == null || !lp.getLayer().removeConfirmed()) { - return; - } - - // This order is somewhat important. lp.getLayer() will - // be null after lp.cleanup. lp.setSelected() will cause - // a series of property change notifications. - - layerHandler.removeLayer(lp.getLayer()); - lp.cleanup(bg); - - return; - - } else if (command.equals(LayerAddCmd)) { - if (layerAddPanel != null) { - layerAddPanel.showPanel(); - } - } - } - - /** - * Find the selected LayerPane in the current LayerPane list. Will return - * null if there isn't a selected pane. - */ - protected LayerPane findSelectedPane() { - for (LayerPane pane : getPanes()) { - if (pane.isSelected()) { - return pane; - } - } - return null; - } - - /** - * Makes a new layer cake of active layers to send to - * LayerHandler.setLayers(). - */ - protected void rejiggerMapLayers() { - logger.fine("jiggering......."); - - if (layerHandler == null) { - // Why bother doing anything?? - return; - } - - int selectedRow = -1; - - panesPanel.removeAll(); - panelGridbag.invalidateLayout(panesPanel); - - List panes = getPanes(); - List layerList = new LinkedList(); - - int bufferIndex = Integer.MAX_VALUE; - - int i = 0; // track layer index - - for (LayerPane pane : panes) { - - if (pane == backgroundLayerSeparator) { - panelGridbag.setConstraints(pane, pgbc); - panesPanel.add(backgroundLayerSeparator); - bufferIndex = i++; - continue; - } - - Layer layer = pane.getLayer(); - layer.setAddAsBackground(i > bufferIndex); - panelGridbag.setConstraints(pane, pgbc); - panesPanel.add(pane); - layerList.add(layer); - - if (pane.isSelected()) { - selectedRow = i; - } - i++; - } - - addFillerToPanesPanel(); - - scrollPane.revalidate(); - - // Scroll up or down as necessary to keep selected row - // viewable - if (selectedRow >= 0) { - int spheight = scrollPane.getHeight(); - JScrollBar sb = scrollPane.getVerticalScrollBar(); - int sv = sb.getValue(); - int paneheight = ((LayerPane) panes.get(selectedRow)).getHeight(); - int rowvalue = selectedRow * paneheight; - // Don't reset scrollBar unless the selected row - // is not in the viewable range - if (!((rowvalue > sv) && (rowvalue < spheight + sv))) { - sb.setValue(rowvalue); - } - } - - layerHandler.setLayerList(new LinkedList(layerList)); - } - - /** - * Update the layer names - if a layer name has changed, tell the LayerPanes - * to check with their layers to update their labels. - */ - public synchronized void updateLayerLabels() { - for (LayerPane pane : getPanes()) { - pane.updateLayerLabel(); - } - } - - public void propertyChange(PropertyChangeEvent pce) { - String command = pce.getPropertyName(); - Object obj = pce.getNewValue(); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("receiving PropertyChangeEvent " + command + ", " + pce.toString()); - } - - if ((command == LayerSelectedCmd || command == LayerDeselectedCmd) - && obj instanceof Layer) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer panel notification that layer is selected: " - + ((Layer) obj).getName()); - } - firePropertyChange(command, null, ((Layer) obj)); - - } else if ((command == LayersPanel.LayerTopCmd || command == LayersPanel.LayerBottomCmd - || command == LayersPanel.LayerUpCmd || command == LayersPanel.LayerDownCmd - || command == LayersPanel.LayerRemoveCmd) && obj instanceof Layer) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("layer panel notification that layer should be raised: " - + ((Layer) obj).getName()); - } - moveLayer((Layer) obj, command); - } - } - - /** - * Called when the LayersPanel is added the BeanContext, or when another - * object is added to the BeanContext after the LayerHandler has been added. - * This allows the LayersPanel to keep up-to-date with any objects that it - * may be interested in, namely, the LayerHandler. If a LayerHandler has - * already been added, the new LayerHandler will replace it. - * - * @param someObj the object being added to the BeanContext - */ - public void findAndInit(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - logger.fine("LayersPanel found a LayerHandler"); - setLayerHandler((LayerHandler) someObj); - } - - if (someObj instanceof BufferedLayerMapBean) { - logger.fine("LayersPanel found BufferedLayerMapBean, creating separator panel"); - backgroundLayerSeparator = LayerPane.getBackgroundLayerSeparator(" --- Background Layers --- "); - } - - // Don't want to forward ourselves on to controls, supposedly - // they already know. - if (controls != null && someObj != this) { - controls.findAndInit(someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when an object has been - * removed from the parent BeanContext. If a LayerHandler is removed, and - * it's the current one being listened to, then the layers in the panel will - * be wiped clean. - * - * @param someObj the object being removed from the BeanContext - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof LayerHandler) { - // do the initializing that need to be done here - logger.fine("LayersPanel removing LayerHandler"); - if (getLayerHandler() == (LayerHandler) someObj) { - setLayerHandler(null); - } - } - - // Don't want to forward ourselves on to controls, supposedly - // they already know. - if (controls != null && someObj != this) { - controls.findAndUndo(someObj); - } - - if (someObj instanceof Layer) { - paneLookUp.remove((Layer) someObj); - } - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String controlString = props.getProperty(prefix + ControlButtonsProperty); - - if (controlString == null) { - setControls(createControlButtons()); - } else { - controlString = controlString.trim(); - - if (!NO_CONTROLS.equalsIgnoreCase(controlString)) { - Object obj = ComponentFactory.create(controlString, prefix - + ControlButtonsProperty, props); - - if (obj instanceof LayerControlButtonPanel) { - setControlsAndNotify((LayerControlButtonPanel) obj); - } - } - } - - bufferedBoundary = PropUtils.booleanFromProperties(props, prefix - + BufferedBoundaryProperty, bufferedBoundary); - showStatus = PropUtils.booleanFromProperties(props, prefix - + ShowStatusProperty, showStatus); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - LayerControlButtonPanel controls = getControls(); - if (controls != null) { - props.put(prefix + ControlButtonsProperty, controls.getClass().getName()); - controls.getProperties(props); - } - props.put(prefix + BufferedBoundaryProperty, new Boolean(bufferedBoundary).toString()); - props.put(prefix + ShowStatusProperty, new Boolean(showStatus).toString()); - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - String interString = i18n.get(LayersPanel.class, ControlButtonsProperty, I18n.TOOLTIP, "Class to use for layer control buttons (Optional)"); - props.put(ControlButtonsProperty, interString); - interString = i18n.get(LayersPanel.class, ControlButtonsProperty, "Button Panel Control"); - props.put(ControlButtonsProperty + LabelEditorProperty, interString); - - LayerControlButtonPanel controls = getControls(); - if (controls != null) { - controls.getPropertyInfo(props); - } - - interString = i18n.get(LayersPanel.class, BufferedBoundaryProperty, I18n.TOOLTIP, "Force layer movement to respect background layer boundary."); - props.put(BufferedBoundaryProperty, interString); - interString = i18n.get(LayersPanel.class, BufferedBoundaryProperty, "Use Background Layers"); - props.put(BufferedBoundaryProperty + LabelEditorProperty, interString); - props.put(BufferedBoundaryProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(LayersPanel.class, ShowStatusProperty, I18n.TOOLTIP, "Use Layer Panes that show layer status."); - props.put(ShowStatusProperty, interString); - interString = i18n.get(LayersPanel.class, ShowStatusProperty, "Show Layer Status"); - props.put(ShowStatusProperty + LabelEditorProperty, interString); - props.put(ShowStatusProperty - + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return props; - } - - class MyWorker implements Runnable { - - private Layer[] layers; - - public MyWorker(Layer[] inLayers) { - layers = inLayers.clone(); - } - - public void run() { - try { - setLayersFromEDT(layers); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/openmap/com/bbn/openmap/gui/MenuBar.java b/src/openmap/com/bbn/openmap/gui/MenuBar.java deleted file mode 100755 index 5aa37f5c1..000000000 --- a/src/openmap/com/bbn/openmap/gui/MenuBar.java +++ /dev/null @@ -1,198 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/MenuBar.java,v $ -// $RCSfile: MenuBar.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 17:49:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.Component; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.beancontext.BeanContext; -import java.beans.beancontext.BeanContextChild; -import java.beans.beancontext.BeanContextChildSupport; -import java.beans.beancontext.BeanContextMembershipEvent; -import java.beans.beancontext.BeanContextMembershipListener; -import java.io.Serializable; -import java.util.Iterator; - -import javax.swing.JMenu; -import javax.swing.JMenuBar; - -import com.bbn.openmap.util.Debug; - -/** - * The MenuList should create and load this with the menus it it has found. - * - * If added to the MapHandler, this Menubar looks for a JMenus and adds them to - * itself. if an object implements HelpMenu, it is then added as the last - * element. - */ -public class MenuBar extends JMenuBar implements Serializable, - BeanContextMembershipListener, BeanContextChild { - protected BeanContextChildSupport beanContextChildSupport = new BeanContextChildSupport(); - - /** - * Default Constructor is required to create instances at runtime - */ - public MenuBar() {} - - /** - * Called when the MenuBar is a part of a BeanContext, and it is - * added to the BeanContext, or while other objects are added to - * the BeanContext after that. - * - * @param it Iterator - */ - protected void findAndInit(Iterator it) { - while (it.hasNext()) { - findAndInit(it.next()); - } - } - - public void findAndInit(Object someObj) { - if (someObj instanceof JMenu) { - add((JMenu) someObj); - } - } - - public JMenu add(JMenu someMenu) { - int menuCount = getMenuCount(); - - JMenu lastMenu = getLastMenu(); - - // Check for HelpMenu first. - if (someMenu instanceof HelpMenu) { - - // We will use it when its implementation is available. - // get the last menu and see if it is helpmenu - if (lastMenu instanceof HelpMenu) { - if (Debug.debugging("menubar")) { - Debug.output("HelpMenu already exists in MenuBar..overriding it"); - } - remove(lastMenu); - } - // make the help menu as the last menu - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: Adding help menu at " + menuCount); - } - - super.add(someMenu); - - } else if (someMenu instanceof MenuBarMenu) { - - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: Adding Menu " + someMenu + "to index " + menuCount); - } - - if (lastMenu instanceof HelpMenu) { - remove(lastMenu); - - super.add(someMenu); - super.add(lastMenu); - - if (Debug.debugging("menubar")) { - Debug.output("MenuBar: last menu is HelpMenu\n moving helpMenu to " + menuCount); - } - } else { - super.add(someMenu); - } - } - - return someMenu; - } - - /** - * Get the last menu item on the menu bar. If there are no menu - * items, it returns null. - */ - public JMenu getLastMenu() { - int menuCount = getMenuCount(); - if (menuCount > 0) { - return getMenu(menuCount - 1); - } else { - return null; - } - } - - /** Method for BeanContextChild interface */ - public void setBeanContext(BeanContext in_bc) throws PropertyVetoException { - beanContextChildSupport.setBeanContext(in_bc); - if (in_bc != null) { - in_bc.addBeanContextMembershipListener(this); - findAndInit(in_bc.iterator()); - } - } - - /** Method for BeanContextChild interface */ - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - beanContextChildSupport.addPropertyChangeListener(propertyName, in_pcl); - } - - /** Method for BeanContextChild interface */ - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener in_pcl) { - beanContextChildSupport.removePropertyChangeListener(propertyName, - in_pcl); - } - - /** Method for BeanContextChild interface */ - public void addVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.addVetoableChangeListener(propertyName, in_vcl); - } - - /** Method for BeanContextChild interface */ - public void removeVetoableChangeListener(String propertyName, - VetoableChangeListener in_vcl) { - beanContextChildSupport.removeVetoableChangeListener(propertyName, - in_vcl); - } - - /** Method for BeanContextChild interface */ - public BeanContext getBeanContext() { - return beanContextChildSupport.getBeanContext(); - } - - /** Method for BeanContextMembership interface */ - public void childrenAdded(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - findAndInit(it); - } - - /** Method for BeanContextMembership interface */ - public void childrenRemoved(BeanContextMembershipEvent bcme) { - Iterator it = bcme.iterator(); - while (it.hasNext()) { - findAndUndo(it.next()); - } - } - - public void findAndUndo(Object someObj) { - // Check for HelpMenu first. - if (someObj instanceof HelpMenu) { - setHelpMenu(null); - } else if (someObj instanceof MenuBarMenu) { - remove((Component) someObj); - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/gui/OverviewMapHandler.java b/src/openmap/com/bbn/openmap/gui/OverviewMapHandler.java deleted file mode 100644 index 8110a3c54..000000000 --- a/src/openmap/com/bbn/openmap/gui/OverviewMapHandler.java +++ /dev/null @@ -1,1029 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/OverviewMapHandler.java,v $ -// $RCSfile: OverviewMapHandler.java,v $ -// $Revision: 1.15 $ -// $Date: 2006/08/09 21:08:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Insets; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.net.URL; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -import com.bbn.openmap.BufferedMapBean; -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.LayerHandler; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.DefaultOverviewMouseMode; -import com.bbn.openmap.event.LayerEvent; -import com.bbn.openmap.event.ListenerSupport; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.OverviewMapStatusListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.layer.OverviewMapAreaLayer; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The OverviewMapHandler contains a MapBean that contains a projection that - * reflects another MapBean's projection. It manages the two MapBeans and the - * differences in the projections betwen them. The OverviewMapHandler can have a - * projection type independent of that of the source MapBean (the MapBean that - * the OverviewMapHandler's MapBean is paying attention to). It also contains a - * scale factor, which is a multiplier to use against the scale of the source - * MapBean's scale. - *

- * - * The OverviewMapHandler MapBean can also be used to control the source - * MapBean's projection center and scale. The source MapBean just needs to be - * added to the OverviewMapHandler by - * OverviewMapHandler.addControlledMap(MapBean). - *

- * - * The OverviewMapHandler needs to be added to the source MapBean as a - * ProjectionListener. Then, the overview MapBean can be added to the - * ContentPane of a Component by calling - * Component.setContentPane(OverviewMapHandler.getMap()); The OverviewMapHandler - * Should also be added as a ComponentListener to the Component. - *

- * - * After the first projectionChanged() call is received, the OverviewMapHandler - * knows about the source MapBean. Since the OverviewMapHandler is a - * ComponentListener and will therefore find out when it's parent is hidden, it - * will disengage and engage itself from the source MapBean as it's visibility - * changes. - *

- * - * To get the overview map to appear in the OpenMap application, add the - * following properties to your openmap.properties file: - * - *

- * 
- * 
- *       # First, add overviewMapHandler to the openmap.components marker name list.  Then, add:
- *     
- *       overviewMapHandler.class=com.bbn.opemap.gui.OverviewMapHandler
- *       overviewMapHandler.overviewLayers=overviewLayer
- *       overviewMapHandler.overviewScaleFactor=10f
- *       overviewMapHandler.overviewMinScale=100f
- *       # Set the Unit of Measure for the overviewMinScale property
- *       # Omission of  overviewMinScaleUom indicates that overviewMinScale
- *       # is an projection map scale instead of a distance.
- *       overviewMapHandler.overviewMinScaleUom=km
- *     
- *       # 'overviewStatusLayer' is a marker name for any attributes you may
- *       # want to pass to the overviewStatusLayer instance, in addition to
- *       # being used to define the class to use for that special layer.
- *       overviewMapHandler.overviewStatusLayer.class=com.bbn.openmap.layer.OverviewMapAreaLayer
- *       # Properties can be passed to the overview status layer by listing
- *       # them with the OverviewMapHandler prefix.
- *     
- *       # Set the line color for the coverage box outline...
- *       # overviewMapHandler.lineColor=FFFF0000
- *     
- *       # A sample overview map layer
- *       overviewLayer.class=com.bbn.openmap.layer.shape.ShapeLayer
- *       overviewLayer.prettyName=Overview
- *       overviewLayer.shapeFile=/home/dietrick/dev/openmap/share/dcwpo-browse.shp
- *       overviewLayer.spatialIndex=/home/dietrick/dev/openmap/share/dcwpo-browse.ssx
- *       overviewLayer.lineColor=ff000000
- *       overviewLayer.fillColor=ffbdde83
- * 
- * 
- * 
- * - *

- * - * If layers are not added to the overview map, then it won't show up in the - * application. - */ -public class OverviewMapHandler extends OMToolComponent implements ProjectionListener, - Serializable, PropertyConsumer, PropertyChangeListener, ComponentListener { - - public final static String OverviewMapHandlerLayerProperty = "overviewLayers"; - public final static String ScaleFactorProperty = "overviewScaleFactor"; - public final static String ProjectionTypeProperty = "overviewProjectionType"; - public final static String MinScaleProperty = "overviewMinScale"; - public final static String MinScaleUomProperty = "overviewMinScaleUom"; - public final static String StatusLayerProperty = "overviewStatusLayer"; - public final static String ControlSourceMapProperty = "overviewControlSourceMap"; - public final static String BackgroundSlaveProperty = "backgroundSlave"; - public final static float defaultScaleFactor = 20f; - public final static float defaultMinScale = 500000f; - public final static Length defaultMinScaleUom = null; - - /** The multiplier to apply to the scale of the project received. */ - protected float scaleFactor; - /** - * The minimum scale to use for the window. If it gets too small with a - * general type layer, it won't be any use. - */ - protected float minScale; - - /** - * The minimum scale unit of measure to use for the window. Use during - * initialization to compute a projection scale from a distance. - */ - protected Length minScaleUom; - - /** The map of the overview panel. */ - protected transient MapBean map; - /** - * The source MapBean to show the overview of. Gets set when the first - * projectionChanged() gets called. Also used to disconnect from the MapBean - * when the component that this OverviewMapHandler is listening to is - * hidden, and to connect to the MapBean when the component is shown. - */ - protected transient MapBean sourceMap; - /** The projection of the overview map bean. */ - protected transient Proj projection; - /** - * A layer that can be set to constantly be on the top of the map. If the - * status layer is also a OverviewMapStatusListener, it also receives the - * source map projection when that changes, which gives it the capability to - * draw stuff based on that. - */ - protected Layer statusLayer; - /** - * The support to send the source MapBean setCenter and setScale commands if - * a controlled map is added - usually the source map bean. - */ - protected transient ControlledMapSupport controlledMaps; - /** The mouse mode to use for the overview map. */ - protected MapMouseMode mmm; - /** - * The thing listening for a request to bring up a JFrame or JInternalFrame. - */ - protected ActionListener overviewFrameActionListener = null; - /** Indicates if OverviewMap should be controlling sourceMap. */ - protected boolean controlSourceMap = true; - /** Default Frame title for OverviewMapHandler */ - public static final String defaultFrameTitle = "Overview Map"; - /** String The Frame Title */ - protected String frameTitle = defaultFrameTitle; - /** Default key for Tool */ - public static final String defaultKey = "overviewmaphandler"; - - /** - * Flag to change the background color to whatever the source map's is - * changed to. True by default. - */ - protected boolean backgroundSlave = true; - - public final static int INITIAL_WIDTH = 200; - public final static int INITIAL_HEIGHT = 100; - - /** - * Default constructor. make sure init(someProperties) is called before you - * attempt to use this object - */ - public OverviewMapHandler() { - super(); - setKey(defaultKey); - setLayout(new BorderLayout()); - createOverviewMap(); - - // Set up a default... - projection = createStartingProjection(null); - addComponentListener(this); - // Create this when we need it. - // setWindowSupport(new WindowSupport(this, new WindowSupport.Dlg(null, - // "Overview Map"))); - } - - /** - * Create an OverviewMapHandler with properties that do not contain a - * prefix. - * - * @param props properties object. - */ - public OverviewMapHandler(Properties props) throws Exception { - this(null, props); - } - - /** - * Create an OverviewMapHandler with properties that do contain a prefix. - * - * @param prefix the prefix for all the properties that apply to the - * OverviewMapHandler. - * @param props properties object. - */ - public OverviewMapHandler(String prefix, Properties props) throws Exception { - - this(); - setProperties(prefix, props); - } - - /** - * Create an OverviewMapHandler for given MapBean. - * - * @param srcMap srcMapBean - * @param prefix the prefix to place in front of each property - i.e., so - * that each property will be under prefix.propertyName. The period - * between the two will be added. - * @param props properties object. - */ - public OverviewMapHandler(MapBean srcMap, String prefix, Properties props) throws Exception { - this(prefix, props); - setSourceMap(srcMap); - } - - /** - * Create the MapBean used for the overview map, and suppress the copyright - * message at the same time. - */ - protected void createOverviewMap() { - // We don't need another copyright message, right? - MapBean.suppressCopyright = true; - map = new BufferedMapBean(); - this.add(map, BorderLayout.CENTER); - } - - /** - * Initialize based on properties, which will not have a prefix. - * - * @deprecated use setProperties(props). - */ - public void init(Properties props) throws Exception { - setProperties(null, props); - } - - /** - * Initialize an OverviewMapHandler with properties that do contain a - * prefix. - * - * @param prefix the prefix to place in front of each property - i.e., so - * that each property will be under prefix.propertyName. The period - * between the two will be added. - * @param props properties object. - * @deprecated use setProperties(prefix, props). - */ - public void init(String prefix, Properties props) throws Exception { - setProperties(prefix, props); - } - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than the - * setArgs method. Part of the PropertyConsumer interface. - * Layers which override this method should do something like: - *

- *

-     * public void setProperties(String prefix, Properties props) {
-     *     super.setProperties(prefix, props);
-     *     // do local stuff
-     * }
-     * 
- *

If the addToBeanContext property is not defined, it is set - * to false here. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, java.util.Properties props) { - propertyPrefix = prefix; - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - Vector overviewLayers = PropUtils.parseSpacedMarkers(props.getProperty(prefix - + OverviewMapHandlerLayerProperty)); - - if (overviewLayers.isEmpty()) { - Debug.message("overview", "OverviewMapHandler: created without layers!"); - } - - scaleFactor = PropUtils.floatFromProperties(props, prefix + ScaleFactorProperty, defaultScaleFactor); - - minScale = PropUtils.floatFromProperties(props, prefix + MinScaleProperty, defaultMinScale); - - String uom = props.getProperty(prefix + MinScaleUomProperty); - if (uom != null) { - minScaleUom = Length.get(uom); - setMinScale(minScale, minScaleUom); - } - - backgroundSlave = PropUtils.booleanFromProperties(props, prefix + BackgroundSlaveProperty, backgroundSlave); - - setControlSourceMap(PropUtils.booleanFromProperties(props, prefix - + ControlSourceMapProperty, controlSourceMap)); - - String statusLayerName = props.getProperty(prefix + StatusLayerProperty + ".class"); - if (statusLayerName != null) { - statusLayer = (Layer) ComponentFactory.create(statusLayerName, prefix - + StatusLayerProperty, props); - if (statusLayer == null) { - Debug.error("OverviewMapHandler.setProperties: status layer not set."); - } - } else { - statusLayer = new OverviewMapAreaLayer(); - } - - statusLayer.setProperties(prefix, props); - - projection = createStartingProjection(props.getProperty(prefix + ProjectionTypeProperty)); - - setLayers(LayerHandler.getLayers(overviewLayers, overviewLayers, props)); - } - - protected ProjectionFactory getProjectionFactory() { - if (sourceMap != null) { - return sourceMap.getProjectionFactory(); - } - return ProjectionFactory.loadDefaultProjections(); - } - - private Proj createStartingProjection(String projName) { - - ProjectionFactory projectionFactory = getProjectionFactory(); - Class projClass = projectionFactory.getProjClassForName(projName); - - if (projClass == null) { - projClass = Mercator.class; - } - - // The scale, lat/lon and size shouldn't matter, because the - // size will get reset when it is added to a component, and - // the projection will change when it is added to a MapBean - // as a projection listener.p - return (Proj) projectionFactory.makeProjection(projClass, new Point2D.Float(Environment.getFloat(Environment.Latitude, 0f), Environment.getFloat(Environment.Longitude, 0f)), Environment.getFloat(Environment.Scale, Float.POSITIVE_INFINITY) - * scaleFactor, INITIAL_WIDTH, INITIAL_HEIGHT); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object should be - * created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - // Build marker list - StringBuffer layerList = new StringBuffer(); - Component[] comps = map.getComponents(); - int ncomponents = comps.length; - for (int i = 0; i < ncomponents; i++) { - Layer layer = (Layer) comps[i]; - if (layer != statusLayer) { // Take care of the - // statusLayer later. - layerList.append(" ").append(layer.getPropertyPrefix()); - layer.getProperties(props); - } - } - props.put(prefix + OverviewMapHandlerLayerProperty, layerList.toString()); - - props.put(prefix + ScaleFactorProperty, Float.toString(scaleFactor)); - props.put(prefix + ProjectionTypeProperty, map.getProjection().getName()); - props.put(prefix + MinScaleProperty, Float.toString(minScale)); - props.put(prefix + BackgroundSlaveProperty, new Boolean(backgroundSlave).toString()); - - if (statusLayer != null) { - props.put(prefix + StatusLayerProperty, statusLayer.getClass().getName()); - statusLayer.getProperties(props); - } - - props.put(prefix + ControlSourceMapProperty, new Boolean(controlSourceMap).toString()); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(OverviewMapHandlerLayerProperty, "Space separated list of marker names of layers to use as background on the overview map."); - list.put(ScaleFactorProperty, "Multiplier reflecting the difference between the scale of the overview map and the source map (default is 20.0)."); - list.put(ProjectionTypeProperty, "Projection name to use for overview map (Default is mercator)."); - list.put(MinScaleProperty, "Minimum scale of overview map (Default is 500,000.0)."); - list.put(StatusLayerProperty, "Class name of layer to use as the active layer on the overview map, receiving mouse events (Default is com.bbn.openmap.layer.OverviewMapAreaLayer)."); - list.put(ControlSourceMapProperty, "Flag to have the source map controlled by gestures on the overview map (true/false, default is true)."); - list.put(ControlSourceMapProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - list.put(BackgroundSlaveProperty, "Flag to have the map mimic any changes made to the source map's background (true/false, default is true)."); - list.put(BackgroundSlaveProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.TrueFalsePropertyEditor"); - - statusLayer.getPropertyInfo(list); - - return list; - } - - /** - * Sets the sourceMap associated with this OverviewMap. if controlSourceMap - * property is set, srcMap will also be controlled by this OverviewHandler - * Passing a null value will remove the current sourceMap from the list of - * Maps that this handler is controlling and set sourceMap to null. - * - * @param srcMap the master map. - */ - public void setSourceMap(MapBean srcMap) { - if (sourceMap != null) { - removeControlledMap(sourceMap); - sourceMap.removeProjectionListener(this); - sourceMap.removePropertyChangeListener(this); - } - - // Add the sourceMap to a set of listeners that wish to be - // controlled by this OverviewMapHandler - if (srcMap != null) { - if (controlSourceMap == true) { - addControlledMap(srcMap); - } - - // Check and see if the overview map window is up. If it - // is, we should add the overview map as a projection - // listener to it. Note: overview map windows went away - // due to window support, but not sure how it affected - // this statement. Keeping commented code here for - // reference in case behavior is weird. Seems to be - // working as expected, though. DFD - // if ((overviewWindowFrame != null && - // overviewWindowFrame.isShowing()) || - // (overviewWindow != null && overviewWindow.isShowing()) - // || - - // Turns out non-tool overview maps weren't becoming - // projection change listeners... - if (!getUseAsTool() && isVisible()) { - srcMap.addProjectionListener(this); - } - - srcMap.addPropertyChangeListener(this); - } - - sourceMap = srcMap; - } - - /** - * Get the map that the overview map is listening to. - */ - public MapBean getSourceMap() { - return sourceMap; - } - - /** - * Set the string used for the frame title of the overview map. - */ - public void setFrameTitle(String in_frameTitle) { - frameTitle = in_frameTitle; - } - - public String getFrameTitle() { - return frameTitle; - } - - /** - * Set whether the map's background mimics changes to the source map's - * background. - * - * @param set true to enable mimicking. - */ - public void setBackgroundSlave(boolean set) { - backgroundSlave = set; - } - - /** - * Get whether the map's background mimics changes to the source map's - * background. - */ - public boolean getBackgroundSlave() { - return backgroundSlave; - } - - /** - * Default value of this property is true. if you want your sourceMap to be - * controlled by this OverviewMapHandler, set the value of this property for - * this OverviewHandler. This will allow, for instance, clicking on the - * overview map to recenter the source map. That depends on the overview map - * mouse mode, however. - * - * @param value - */ - public void setControlSourceMap(boolean value) { - if (sourceMap != null) { - if (value == true && controlSourceMap == false) { - addControlledMap(sourceMap); - } - if (value == false && controlSourceMap == true) { - removeControlledMap(sourceMap); - } - } - controlSourceMap = value; - } - - public boolean getControlSourceMap() { - return controlSourceMap; - } - - /** - * Set the layers in the Overview MapBean. An AreaLayer is automatically - * added on top. - */ - public void setLayers(Layer[] layers) { - map.setLayers(new LayerEvent(this, LayerEvent.REPLACE, new Layer[0])); - if (statusLayer != null) { - map.add(statusLayer); - } - map.setLayers(new LayerEvent(this, LayerEvent.ADD, layers)); - } - - /** - * Part of the ProjectionListener interface. The new projections from the - * source MapBean arrive here. - * - * @param projEvent the projection event from the source MapBean. - */ - public void projectionChanged(ProjectionEvent projEvent) { - if (sourceMap == null) { - sourceMap = (MapBean) projEvent.getSource(); - map.setBckgrnd(sourceMap.getBckgrnd()); - } - - Projection proj = projEvent.getProjection(); - if (proj == null) { - return; - } - - if (statusLayer instanceof OverviewMapStatusListener) { - ((OverviewMapStatusListener) statusLayer).setSourceMapProjection(proj); - } - - float newScale = proj.getScale() * scaleFactor; - - // Adjust the newScale based on the ratio of the - // source projection width and the overview - // map projection width. - Projection sourceProj = sourceMap.getProjection(); - newScale *= (float) sourceProj.getWidth() / (float) projection.getWidth(); - - if (newScale < minScale) { - newScale = minScale; - } - - projection.setScale(newScale); - projection.setCenter(proj.getCenter()); - map.setProjection(projection); - } - - /** - * Set the MapMouseMode for the overview map. If you want the status layer - * to listen to the mouse mode, you have to get the layer and wire it up - * yourself. - */ - public void setMouseMode(MapMouseMode ammm) { - // If we're removing a mouse mode, disconnect it from the map. - if (ammm == null) { - deactivateMouseMode(); - } - mmm = ammm; - activateMouseMode(); - } - - /** - * Get the MapMouseMode used for the overview map. - */ - public MapMouseMode getMouseMode() { - return mmm; - } - - /** - * Adds the mouse mode as a listener to the overview map. If the mouse mode - * is null, the default is created. - */ - public void activateMouseMode() { - if (mmm == null) { - mmm = new DefaultOverviewMouseMode(this); - } - if (map != null) { - map.addMouseListener(mmm); - map.addMouseMotionListener(mmm); - } - } - - /** - * Disconnects the mouse mode from the overview map. - */ - public void deactivateMouseMode() { - if (mmm != null) { - map.removeMouseListener(mmm); - map.removeMouseMotionListener(mmm); - } - } - - /** - * Add a controlled MapBean to the OverviewMapHandler. Use this method to - * add another MapBean to the overview map in order to have its projection - * controlled by the overview panel. If the overview panel is clicked on, - * the listening MapBean will be recentered. If a box is drawn with a mouse - * drag, the scale of the controlled map will be modified. - * - * @param l MapBean. - */ - public void addControlledMap(MapBean l) { - if (l != null) { - if (controlledMaps == null) { - controlledMaps = new ControlledMapSupport(map); - // If nobody has been listening don't draw anything. - // Since someone is now being controlled, we'll do the - // drawing. - activateMouseMode(); - } - controlledMaps.add(l); - } - } - - /** - * Remove a controlled MapBean from the OverviewMapHandler. - * - * @param l a MapBean. - */ - public void removeControlledMap(MapBean l) { - if (controlledMaps != null) { - controlledMaps.remove(l); - - if (controlledMaps.isEmpty()) { - deactivateMouseMode(); - } - } - } - - /** - * Get the overview MapBean. - * - * @return overview MapBean. - */ - public MapBean getMap() { - return map; - } - - /** - * Set the overview MapBean. - */ - public void setMap(MapBean map) { - if (map != null) { - // get rid of any other MapBean that may have been added - // to the JPanel. - this.remove(map); - } - this.map = map; - this.add(map, BorderLayout.CENTER); - } - - /** - * Get the ControlledMapSupport, which usually contains the source map. - */ - public ControlledMapSupport getControlledMapListeners() { - return controlledMaps; - } - - /** - * Set the ControlledMapSupport, which usually contains the source map. - */ - public void setControlledMapListeners(ControlledMapSupport list) { - controlledMaps = list; - } - - /** - * Get the status layer, which is always drawn on top of the other layers, - * and maintained separately from other layers. - */ - public Layer getStatusLayer() { - return statusLayer; - } - - /** - * Get the status layer, which is always drawn on top of the other layers, - * and maintained separately from other layers. If the layer is also an - * OverviewMapStatusListener, it will receive source map projection changes, - * so it can draw stuff on itself representing what's going on the source - * map. - */ - public void setStatusLayer(Layer layer) { - statusLayer = layer; - } - - /** - * Set the scale factor to use between the source MapBean and the overview - * MapBean. It's a direct multiplier, so the overview MapBean can actually - * be a magnified map, too. The overview map scale = source MapBean scale * - * scaleFactor. - * - * @param setting scale factor - */ - public void setScaleFactor(float setting) { - scaleFactor = setting; - } - - /** - * Get the scale factor used for the overview MapBean. - */ - public float getScaleFactor() { - return scaleFactor; - } - - /** - * Set the projection of the overview MapBean. Lets you set the type, - * really. The scale and center will be reset when a projection event is - * received. - */ - public void setProjection(Proj proj) { - projection = proj; - } - - /** - * Get the current projection of the overview MapBean. - */ - public Proj getProjection() { - return projection; - } - - /** - * Set the minimum scale to use for the overview map. If this is set too - * small with a very general map layer, it won't be of any use, really, if - * it gets really zoomed in. - * - * @param setting the scale setting - 1:setting - */ - public void setMinScale(float setting) { - if (setting > 0) { - minScale = setting; - } - } - - /** - * Set the minimum scale to use for the overview map. If this is set too - * small with a very general map layer, it won't be of any use, really, if - * it gets really zoomed in. - * - * @param width setting the scale setting - 1:setting - * @param uom unit of measure for width - */ - public void setMinScale(float width, Length uom) { - if (width > 0) { - Projection p = map.getProjection(); - - Length projUom = p.getUcuom(); - - if (projUom == null) { - // We're going to assume meters, since this really only applies - // to pre-projected projections like Cartesian, and we might as - // well make it something. Not sure if it matters, as long as - // we're consistent. - projUom = Length.METER; - } - - // This is really not the radius but the half width in radians. - float radius = uom.toRadians(width) / 2; - - Point2D center = p.getCenter(); - Point2D left = new Point2D.Double(center.getX(), center.getY()); - Point2D right = new Point2D.Double(center.getX(), center.getY()); - - double newLeftX = projUom.fromRadians(projUom.toRadians(left.getX()) - radius); - double newRightX = projUom.fromRadians(projUom.toRadians(right.getX()) + radius); - - left.setLocation(newLeftX, left.getY()); - right.setLocation(newRightX, right.getY()); - - minScale = ProjMath.getScale(left, right, p); - } - } - - public float getMinScale() { - return minScale; - } - - /** - * Invoked when component has been shown. This component should be the - * component that contains the OverviewMapHandler. - */ - public void componentShown(ComponentEvent e) { - if (sourceMap != null) { - sourceMap.addProjectionListener(this); - } - } - - /** - * Invoked when component has been hidden. This component should be the - * component that contains the OverviewMapHandler. - */ - public void componentHidden(ComponentEvent e) { - if (sourceMap != null) { - sourceMap.removeProjectionListener(this); - } - } - - public void componentResized(ComponentEvent e) { - } - - public void componentMoved(ComponentEvent e) { - } - - /** - * Return an ActionListener that will bring up an independent window with an - * Overview Map. - * - * @return ActionListener that brings up a Window when an actionPerformed is - * called. - */ - public ActionListener getOverviewFrameActionListener() { - return new ActionListener() { - public void actionPerformed(ActionEvent evt) { - WindowSupport ws = getWindowSupport(); - - MapHandler mh = (MapHandler) getBeanContext(); - Frame frame = null; - if (mh != null) { - frame = (Frame) mh.get(java.awt.Frame.class); - } - - if (ws == null) { - ws = new WindowSupport(OverviewMapHandler.this, new WindowSupport.Dlg(frame, "Overview Map")); - setWindowSupport(ws); - } - - int w = INITIAL_WIDTH; - int h = INITIAL_HEIGHT; - Dimension dim = ws.getComponentSize(); - if (map != null && dim != null) { - w = (int) dim.getWidth(); - h = (int) dim.getHeight(); - } - - ws.displayInWindow(frame, -1, -1, w, h); - } - }; - } - - /** Tool interface method. */ - public Container getFace() { - JButton b = null; - if (getUseAsTool()) { - URL url = getClass().getResource("overview.gif"); - b = new JButton(new ImageIcon(url, frameTitle)); - b.setToolTipText(frameTitle); - b.setMargin(new Insets(0, 0, 0, 0)); - b.addActionListener(getOverviewFrameActionListener()); - b.setBorderPainted(false); - } - return b; - } - - /** - * Called when the OverviewMapHandler is added to the BeanContext, and - * whenever an object is added to the BeanContext after that. The - * OverviewMapHandler looks for a MapBean to use as a source map, and for a - * PropertiesHandler object to use to load itself with layers and other - * properties. If a source MapBean is already set and another MapBean is - * found, the last MapBean will be used as the source MapBean. Every time a - * PropertyHandler is found, the OverviewMapHandler will reinitialize - * itself. - * - * @param someObj the object being added to the BeanContext - */ - public void findAndInit(Object someObj) { - if (someObj instanceof com.bbn.openmap.MapBean) { - Debug.message("overview", "OverviewMapHandler found a MapBean object"); - setSourceMap((MapBean) someObj); - } - } - - /** - */ - public void findAndUndo(Object someObj) { - if (someObj instanceof MapBean) { - if (getSourceMap() == (MapBean) someObj) { - Debug.message("overview", "OverviewMapHandler: removing source MapBean"); - setSourceMap(null); - } - } - - if (someObj.equals(this)) { - dispose(); - } - } - - /** - * Support for directing the setCenter and setScale calls to any MapBeans - * that care to be listening. - */ - public class ControlledMapSupport extends ListenerSupport { - - /** - * Construct a ControlledMapSupport. - * - * @param aSource source Object - */ - public ControlledMapSupport(Object aSource) { - super(aSource); - } - - /** - * Set the center coordinates on all registered listeners. - * - * @param llp the new center point - */ - public void setCenter(Point2D llp) { - for (MapBean mapBean : this) { - mapBean.setCenter(llp); - } - } - - /** - * Set the scale on all registered listeners. - * - * @param scale the new scale - */ - public void setScale(float scale) { - for (MapBean mapBean : this) { - mapBean.setScale(scale); - } - } - } - - /** - * PropertyChangeListener method, to listen for the source map's background - * changes. Act on if necessary. - */ - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName() == MapBean.BackgroundProperty && backgroundSlave) { - map.setBckgrnd((Paint) pce.getNewValue()); - } - } - - public void dispose() { - controlledMaps.clear(); - map.dispose(); - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/gui/menu/MenuList.java b/src/openmap/com/bbn/openmap/gui/menu/MenuList.java deleted file mode 100644 index 4a1bd3e28..000000000 --- a/src/openmap/com/bbn/openmap/gui/menu/MenuList.java +++ /dev/null @@ -1,230 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/menu/MenuList.java,v $ -// $RCSfile: MenuList.java,v $ -// $Revision: 1.6 $ -// $Date: 2007/03/08 17:35:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.gui.menu; - -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.JMenu; -import javax.swing.JMenuBar; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.gui.MenuBar; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The MenuList is a component that creates a set of JMenus from Properties, and - * can provide a JMenuBar or JMenu with those JMenus. Used by the MapPanel. - *

- * - * The MenuList can be used in lieu of defining the OpenMap MenuBar and each - * Menu in the openmap.components property. The MenuList can be defined instead, - * with the menus it should create. It has one property: - * - *

- *   
- *   
- *    menulist.menus=menu1 menu2 menu3
- *    menu1.class=classname of menu1
- *    menu2.class=classname of menu2
- *    menu3.class=classname of menu3
- * 
- * 
- * 
- * - * When the MenuList.setBeanContext() method gets called, the MenuList will add - * its menus to that MapHandler/BeanContext. - * - * By default, the MenuList will provide an OpenMap MenuBar when asked for a - * JMenuBar, which will figure out if one of the child menus is a HelpMenu and - * place it at the end of the MenuBar menus. - */ -public class MenuList extends OMComponent { - - public final static String MenusProperty = "menus"; - public final static String MenuNameProperty = "name"; - - protected List menuList; - - protected String name = "Map"; - - /** - * Create an empty MenuList. - */ - public MenuList() { - menuList = new ArrayList(); - } - - /** - * Get a MenuBar with JMenus on it. If the MenuList has been given a - * MapHandler, the Menus will have been added to it, and therefore will be - * connected to OpenMap components. The MenuBar is not added to the - * MapHandler and probably shouldn't be, since it will find and re-add the - * Menus it finds there in some random order. - */ - public JMenuBar getMenuBar() { - MenuBar menuBar = new MenuBar(); - - for (JMenu menuu : menuList) { - menuBar.add(menuu); - } - return menuBar; - } - - /** - * Get a JMenu with JMenus on it as sub-menus. If the MenuList has been - * given a MapHandler, the Menus will have been added to it, and therefore - * will be connected to OpenMap components. This menu will be named "Map", - * but you can rename it if you want. - */ - public JMenu getMenu() { - JMenu menu = new JMenu(name); - - for (JMenu menuu : menuList) { - menu.add(menuu); - } - return menu; - } - - /** - * The MenuList will look for the "menus" property and build its menus. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - name = props.getProperty(prefix + MenuNameProperty, name); - - Vector menuItems = PropUtils.parseSpacedMarkers(props.getProperty(realPrefix - + MenusProperty)); - if (!menuItems.isEmpty()) { - - for (String itemPrefix : menuItems) { - String classProperty = itemPrefix + ".class"; - String className = props.getProperty(classProperty); - if (className == null) { - Debug.error("MenuList.setProperties(): Failed to locate property \"" - + classProperty + "\"\n Skipping menu \"" + itemPrefix + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, itemPrefix, props); - if (obj instanceof JMenu) { - menuList.add((JMenu) obj); - } - } - } else { - if (Debug.debugging("menu")) { - Debug.output("MenuList created without menus in properties"); - } - } - } - - /** - * PropertyConsumer interface method. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - StringBuffer itemList = new StringBuffer(); - - for (JMenu menu : menuList) { - if (menu instanceof PropertyConsumer) { - PropertyConsumer ps = (PropertyConsumer) menu; - String prefix = ps.getPropertyPrefix(); - if (prefix == null) { - prefix = menu.getText().toLowerCase(); - ps.setPropertyPrefix(prefix); - } - - itemList.append(prefix).append(" "); - ps.getProperties(props); - } - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + MenusProperty, itemList.toString().trim()); - props.put(prefix + MenuNameProperty, PropUtils.unnull(name)); - - return props; - } - - /** - * PropertyConsumer interface method. - */ - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - PropUtils.setI18NPropertyInfo(i18n, props, MenuList.class, MenusProperty, "List of Menus", "List of marker names for menu component properties.", null); - PropUtils.setI18NPropertyInfo(i18n, props, MenuList.class, MenuNameProperty, "Name", "Name of the Menu provided by the MenuList.", null); - return props; - } - - /** - * Called when the MenuList is added to the MapHandler/BeanContext. The - * MenuList will add its menus to the BeanContext. - */ - public void setBeanContext(BeanContext bc) throws PropertyVetoException { - - super.setBeanContext(bc); - if (bc != null) { - for (JMenu menu : menuList) { - bc.add(menu); - } - } - } - - public void findAndInit(Object obj) { - if (obj instanceof JMenu) { - menuList.add((JMenu) obj); - } - } - - public void findAndUndo(Object obj) { - if (obj instanceof JMenu) { - menuList.remove((JMenu) obj); - } - } - - public void add(JMenu menu) { - menuList.add(menu); - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } -} diff --git a/src/openmap/com/bbn/openmap/image/ImageServer.java b/src/openmap/com/bbn/openmap/image/ImageServer.java deleted file mode 100644 index a82f44f39..000000000 --- a/src/openmap/com/bbn/openmap/image/ImageServer.java +++ /dev/null @@ -1,1267 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServer.java,v $ -// $RCSfile: ImageServer.java,v $ -// $Revision: 1.14 $ -// $Date: 2007/04/17 20:23:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.image; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.RenderingHints; -import java.awt.geom.Point2D; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapBean; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.plugin.PlugIn; -import com.bbn.openmap.plugin.PlugInLayer; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Mercator; -import com.bbn.openmap.proj.Proj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.ProjectionFactory; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * The image server is the class you want to deal with when creating images. It - * takes a properties file and creates images based on those properties. It also - * has this queuing thing going so that requests can stack up while the image - * generator is working on requests, and it will notify the requestor when the - * image is ready. - *

- * - * The ImageServer generally has the layers on the map predefined at - * construction, although you can change the layers that it has. When setting - * the layer array, do not use the same layer in two different slots of the - * array - it may not give you the expected map, and may mess around with the - * timing issues that the ImageGenerator takes care of. If you want to reorder - * the layers, do so before adding your request to the ImageServer. - * Additionally, each request has the option of not using certain layers in the - * ImageServer layer array, by turning off the appropriate bits in the layer - * mask. Understand that the image for a request will be created based on the - * layer array contents and the request layer mask at the time the request - * processing is started, not when it is submitted. - *

- * Right now, the ImageServer is single threaded - processing requests one after - * another. The request setup was written to support multi-threaded processing, - * though, where each image could be generated in it's own thread. That code is - * not written - maybe someday. - *

- *

- *                   
- * # If the ImageServer is created and given a prefix (in this example,
- * # 'imageServer') the properties file should contain the properties:
- * imageServer.layers=<layer1 layer2 ...>
- * layer1.className=<classname>
- * layer1.prettyName=<pretty name of layer>
- * # Add other attributes as required by layer1...
- * layer2.className=<classname>
- * layer2.prettyName=<pretty name of layer>
- * # Add other attributes as required by layer2...
- * # First formatter listed is default.
- * imageServer.formatters=<formatter1 formatter2 ...>
- * formatter1.class=<classname of formatter 1>
- * # Add other formatter1 properties
- * formatter2.class=<classname of formatter 2>
- *
- * 
- *

- * NOTE: If you simply hand the ImageServer a standard openmap.properties file, - * it works with the addition of the first two attributes except WITHOUT the - * 'imageServer.' prefix. - * - * New for 4.5: If the layers property is not defined, then the openmap.layers - * property is used to define which layers are available for the ImageServer. - */ -public class ImageServer - implements - /* ImageReadyListener, ImageReceiver, */PropertyConsumer { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.image.ImageServer"); - - /** The Image formatter for the output image. */ - protected ImageFormatter formatter; - - /** - * Hashtable of ImageFormatters available to be used. - */ - protected Map imageFormatters; - - /** The array of layers on the map. First is on top. */ - protected Layer[] layers; - - /** Property for space separated layers. */ - public static final String ImageServerLayersProperty = "layers"; - - /** OpenMap prefix */ - public static final String OpenMapPrefix = "openmap."; - - /** - * Property for the image formatter list of available formats. This property - * should contain a space separated list of marker names. - */ - public static final String ImageFormattersProperty = "formatters"; - - /** Property to turn on anti-aliasing. */ - public static final String AntiAliasingProperty = "antialiasing"; - - /** - * Property to set the background color. - */ - public static final String BackgroundProperty = "background"; - - /** Flag to do graphics and text anti-aliasing on the map image. */ - protected boolean doAntiAliasing = false; - - /** - * A place to hold on to a property prefix in case one is used. Useful for - * ImageServer properties files where more than one image server is defined. - */ - protected String propertiesPrefix = null; - - /** - * The ProjectionFactory to be used for image projections. If null, the - * default projection set will be used. - */ - protected ProjectionFactory projectionFactory; - - private boolean transparent = true; - - /** - * Empty constructor that expects to be configured later. - */ - protected ImageServer() { - } - - /** - * To create the image server, you hand it a set of properties that let it - * create an array of layers, and also to set the properties for those - * layers. The properties file for the ImageServer looks strikingly similar - * to the openmap.properties file. So, all the layers get set up here... - */ - public ImageServer(Properties props) { - setProperties(props); - } - - /** - * Same as the other constructor, except that the properties can have a - * prefix in front of them. The format of the prefix has to match how the - * property is specified the the properties file, which may include the - * period - i.e server1.imageServer.layers, the server1. is the prefix that - * should get passed in. The ImageMaster does this. - */ - public ImageServer(String prefix, Properties props) { - this(prefix, props, null); - } - - /** - * Create an ImageServer that should be configured with a Properties file. - * The prefix given is to scope the ImageServer properties to this instance. - * The Hashtable is for reusing any layers that may already be instantiated. - */ - public ImageServer(String prefix, Properties props, Map instantiatedLayers) { - setProperties(prefix, props, instantiatedLayers); - } - - /** - * Create an ImageServer from an array of Layers and an ImageFormatter. It's - * assumed that the layers are already configured. - * - * @param layers the array of layers. - * @param formatter the ImageFormatter to use for the output image format. - */ - public ImageServer(Layer[] layers, ImageFormatter formatter) { - this.layers = layers; - this.formatter = formatter; - } - - /** - * Set whether anti-aliasing is used when creating the image. - */ - public void setDoAntiAliasing(boolean set) { - doAntiAliasing = set; - } - - /** - * Find out whether anti-aliasing is used when creating the image. - */ - public boolean getDoAntiAliasing() { - return doAntiAliasing; - } - - /** - * Set the layers used on the NEXT request that is processed. Will not - * affect any image currently being created. - * - * @param newLayers an array of com.bbn.openmap.Layer objects, already - * configured and ready to respond to a projectionChanged method - * call. - */ - public synchronized void setLayers(Layer[] newLayers) { - if (newLayers == null) { - layers = new Layer[0]; - } else { - layers = newLayers; - } - } - - /** - * Retrieve the current set of layers used for requests. - * - * @return Layer[] - */ - public synchronized Layer[] getLayers() { - return layers; - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj) { - return createImage(proj, -1, -1, 0xFFFFFFFF); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight) { - return createImage(proj, scaledWidth, scaledHeight, 0xFFFFFFFF); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layer marker names reflecting the layers that should be - * part of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, List showLayers) { - return createImage(proj, scaledWidth, scaledHeight, showLayers, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layersthat should be part of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImageFromLayers(Projection proj, int scaledWidth, int scaledHeight, List showLayers) { - return createImageFromLayers(proj, scaledWidth, scaledHeight, showLayers, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. The background used for the - * image is the one set in this ImageServer object. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param showLayers Layer marker names reflecting the layers that should be - * part of this image. - * @param background the Paint to be used for the background of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, List showLayers, Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer string array."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - java.awt.Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (showLayers != null) { - int size = showLayers.size(); - for (int j = size - 1; j >= 0; j--) { - for (int i = layers.length - 1; i >= 0; i--) { - String layerName = (String) showLayers.get(j); - Layer layer = layers[i]; - String prefix = layer.getPropertyPrefix(); - if (prefix == null) { - // Just in case the PlugInLayer prefix didn't get set to - // the - // same as the plugins' - if (layer instanceof PlugInLayer) { - prefix = ((PlugInLayer) layer).getPlugIn().getPropertyPrefix(); - } - } - - if (layerName.equals(prefix)) { - layer.renderDataForProjection(proj, graphics); - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layer.getName()); - } - } - } - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available for image"); - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * Create an image from a set of layers. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param layers A set of layers to paint into the image. - * @param background the Paint to be used for the background of this image. - * @return a byte[] representing the formatted image. - */ - public byte[] createImageFromLayers(Projection proj, int scaledWidth, int scaledHeight, List layers, Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer list."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - java.awt.Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (layers != null && !layers.isEmpty()) { - for (int i = layers.size() - 1; i >= 0; i--) { - Layer layer = layers.get(i); - - if (layer != null) { - layer.renderDataForProjection(proj, graphics); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layer.getName()); - } - } - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available for image"); - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * This method returns a integer representing a mask created from the - * visibility settings of the layers. - */ - public int calculateVisibleLayerMask() { - int ret = 0; // Initialize all the layer bits to zero. - for (int i = layers.length - 1; i >= 0; i--) { - if (layers[i].isVisible()) { - ret |= (0x00000001 << i); - } - } - return ret; - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. Uses the default background - * set in the ImageServer. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param includedLayerMask a mask signifying which of the ImageServer - * layers to use in the image. It's assumed that the called knows - * which layers are desired. Bit 1 of the mask refers to layer[0], - * etc. A bit turned on means the layer will be included. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, int includedLayerMask) { - return createImage(proj, scaledWidth, scaledHeight, includedLayerMask, getBackground()); - } - - /** - * Use the ProjectionPainter interface of the layers to create an image. - * This approach avoids some of the timing issues that the thread model of - * the MapBean and Layers that seem to pop up from time to time. They are - * Swing components, you know. They were designed to be part of a GUI. So, - * this is a serialized, safe way to do things. - * - * @param proj projection of map. - * @param scaledWidth scaled pixel width of final image. If you don't want - * it scaled, use -1. - * @param scaledHeight scaled pixel height of final image. If you don't want - * it scaled, use -1. - * @param includedLayerMask a mask signifying which of the ImageServer - * layers to use in the image. It's assumed that the called knows - * which layers are desired. Bit 1 of the mask refers to layer[0], - * etc. A bit turned on means the layer will be included. - * @param background the background Paint to use for the image, behind the - * layers. - * @return a byte[] representing the formatted image. - */ - public byte[] createImage(Projection proj, int scaledWidth, int scaledHeight, int includedLayerMask, Paint background) { - - logger.fine("using the new ProjectionPainter interface! createImage with layer mask."); - - if (formatter == null) { - logger.warning("no formatter set! Can't create image."); - return new byte[0]; - } - - ImageFormatter imageFormatter = formatter.makeClone(); - - Graphics graphics = createGraphics(imageFormatter, proj.getWidth(), proj.getHeight()); - - if (graphics == null) { - return new byte[0]; - } - - ((Proj) proj).drawBackground((Graphics2D) graphics, background); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("considering " + layers.length + " for image..."); - } - - if (layers != null) { - for (int i = layers.length - 1; i >= 0; i--) { - if ((includedLayerMask & (0x00000001 << i)) != 0) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer graphics from : " + layers[i].getName()); - } - - layers[i].renderDataForProjection(proj, graphics); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("skipping layer graphics from : " + layers[i].getName()); - } - } - } - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("no layers available"); - } - } - - byte[] formattedImage = getFormattedImage(imageFormatter, scaledWidth, scaledHeight); - graphics.dispose(); - return formattedImage; - } - - /** - * Create a java.awt.Graphics to use for an image. The Graphics will affect - * the image contained within the ImageFormatter. - * - * @param formatter the ImageFormatter containing the image. - * @param width the pixel width of the image. - * @param height the pixel height of the image. - */ - protected Graphics createGraphics(ImageFormatter formatter, int width, int height) { - - java.awt.Graphics graphics = null; - - if (formatter == null) { - logger.warning("ImageServer.createGraphics: Formatter is null, returning null graphics."); - return null; - } - - graphics = formatter.getGraphics(width, height, getTransparent()); - - if (graphics == null) { - logger.warning("ImageServer.createGraphics: NOT able to create Graphics!"); - return null; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("graphics is cool"); - } - - if (doAntiAliasing && graphics instanceof java.awt.Graphics2D) { - java.awt.Graphics2D g2d = (java.awt.Graphics2D) graphics; - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - } - - return graphics; - } - - /** - * Format the image that is contained in the ImageFormatter, scaling to a - * particular size if the scaledWidth and scaledHeight are greater than 0. - */ - protected byte[] getFormattedImage(ImageFormatter formatter, int scaledWidth, int scaledHeight) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("ready to create formatted image."); - } - byte[] formattedImage = null; - - // Now, scale the image, if needed... - if (scaledWidth > 0 && scaledHeight > 0) { - - formattedImage = formatter.getScaledImageBytes(scaledWidth, scaledHeight); - - } else { - logger.fine("ImageServer: using full scale image (unscaled)."); - formattedImage = formatter.getImageBytes(); - } - return formattedImage; - } - - /** - * Set the layers and image type in the properties. - */ - public void setProperties(Properties props) { - setProperties((String) null, props); - } - - /** - * Set the layers and image type in the properties. The properties might - * have a prefix in the file. - */ - public void setProperties(String prefix, Properties props) { - setProperties(prefix, props, (Map) null); - } - - /** - * Set the layers and image type in the properties. The properties might - * have a prefix in the file. - */ - public void setProperties(String prefix, Properties props, Map instantiatedLayers) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - layers = getLayers(props, instantiatedLayers); - formatter = getFormatters(props); - doAntiAliasing = PropUtils.booleanFromProperties(props, prefix + AntiAliasingProperty, false); - - background = getBackground(props, prefix + BackgroundProperty); - } - - /** - * Determine the background color based on property settings. If the - * property key isn't found, the openmap.BackgroundColor property will be - * used. If that isn't found, then Color.white will be returned as default. - * - * @param props properties to check - * @param propertyKey first key to check for. - * @return Paint used for background, as stated in properties - */ - public Paint getBackground(Properties props, String propertyKey) { - String paintString = props.getProperty(propertyKey); - if (paintString == null) { - paintString = props.getProperty(Environment.BackgroundColor); - } - - Paint ret = null; - if (paintString != null) { - try { - ret = PropUtils.parseColor(paintString, transparent); - } catch (NumberFormatException nfe) { - // Color set to white below... - } - } - - if (ret == null) { - ret = Color.white; - } - - return ret; - } - - /** - * Part of the PropertyConsumer interface. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer buf = new StringBuffer(); - for (Layer layer : getLayers()) { - buf.append(layer.getPropertyPrefix()).append(" "); - layer.getProperties(props); - } - - props.put(prefix + ImageServerLayersProperty, buf.toString().trim()); - - buf = new StringBuffer(); - if (imageFormatters != null) { - int index = 1; - for (ImageFormatter formatter : imageFormatters.values()) { - - String className = formatter.getClass().getName(); - String prfx = className.substring(className.lastIndexOf('.') + 1) + index; - - if (formatter instanceof PropertyConsumer) { - PropertyConsumer pc = (PropertyConsumer) formatter; - String opp = pc.getPropertyPrefix(); - - if (opp != null) { - prfx = opp; - pc.getProperties(props); - } else { - pc.setPropertyPrefix(prfx); - pc.getProperties(props); - // Reset it to whatever it was before we grabbed - // properties. - pc.setPropertyPrefix(null); - } - } - - buf.append(prfx).append(" "); - props.put(prfx + ComponentFactory.DotClassNameProperty, formatter.getClass().getName()); - - index++; - } - } - - props.put(prefix + ImageFormattersProperty, buf.toString().trim()); - - props.put(prefix + AntiAliasingProperty, Boolean.toString(doAntiAliasing)); - - if (background instanceof Color) { - String colorString = Integer.toHexString(((Color) background).getRGB()); - props.put(Environment.BackgroundColor, colorString); - } - - return props; - } - - /** - * Part of the PropertyConsumer interface. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - list.put(ImageServerLayersProperty, "A list of marker names (space-separated) for layer definitions"); - list.put(ImageFormattersProperty, "A list of marker names (space-separated) for ImageFormatter definitions"); - list.put(AntiAliasingProperty, "Whether to use anti-aliasing for the image"); - return list; - } - - /** - * Part of the PropertyConsumer interface. Set the Properties prefix to use - * to scope the relevant properties passed into the setProperties method. - */ - public void setPropertyPrefix(String prefix) { - propertiesPrefix = prefix; - } - - /** - * Part of the PropertyConsumer interface. Get the Properties prefix used to - * scope the relevant properties passed into the setProperties method. - */ - public String getPropertyPrefix() { - return propertiesPrefix; - } - - /** - * Given a integer that represents, bitwise, the layers that you want out of - * the current list held by the ImageServer layer array, return an array of - * those layers. - * - * @param layerMask bit mask for desired layers, bit 0 is layer 0. - * @return layer[] - */ - protected synchronized Layer[] getMaskedLayers(int layerMask) { - if (layerMask == 0xFFFFFFFF || layers == null) { - // They all want to be there - if (logger.isLoggable(Level.FINE)) { - logger.fine((layers != null ? "ImageServer: image request adding all layers." - : "ImageServer.getMaskedLayers() null layers")); - } - return layers; - } else { - // Use the vector as a growable array, and add the layers - // to it that the mask says should be there. - Vector layerVector = new Vector(layers.length); - for (int i = 0; i < layers.length; i++) { - if ((layerMask & (0x00000001 << i)) != 0) { - layerVector.add(layers[i]); - if (logger.isLoggable(Level.FINE)) { - logger.fine("image request adding layer: " + layers[i].getName()); - } - } - } - Layer[] imageLayers = new Layer[layerVector.size()]; - return (Layer[]) layerVector.toArray(imageLayers); - } - } - - /** - * Get the ImageFormatter currently used for the image creation. - * - * @return ImageFormatter. - */ - public synchronized ImageFormatter getFormatter() { - return formatter; - } - - /** - * Set the ImageFormatter to be used for ImageCreation. - */ - public synchronized void setFormatter(ImageFormatter f) { - formatter = f; - - if (imageFormatters == null) { - imageFormatters = new Hashtable(); - } - - if (!imageFormatters.containsKey(formatter.getFormatLabel())) { - imageFormatters.put(formatter.getFormatLabel(), formatter); - } - } - - /** - * Set the default formatter to the one with the given label. The label can - * be retrieved from the ImageFormatter. - * - * @param formatterLabel String for a particular formatter. - * @return true if label matches up with a known formatter, false if no - * formatter found. - */ - public synchronized boolean setFormatter(String formatterLabel) { - ImageFormatter tmpFormatter = (ImageFormatter) imageFormatters.get(formatterLabel.intern()); - - if (tmpFormatter != null) { - setFormatter(tmpFormatter); - return true; - } else { - return false; - } - } - - /** - * Get the Hashtable used to hold the ImageFormatters. The label for each - * one is the lookup for it in the Hashtable. - * - * @return Hashtable of ImageFormatters. - */ - public synchronized Map getFormatters() { - return imageFormatters; - } - - /** - * Set the ImageFormatter Hashtable to set up the possible choices for image - * formats. - * - * @param iFormatters Hashtable of ImageFormatters - * @param defaultFormatterKey the key label of the formatter to use for a - * default. - */ - public synchronized void setFormatters(Map iFormatters, String defaultFormatterKey) { - imageFormatters = iFormatters; - formatter = (ImageFormatter) imageFormatters.get(defaultFormatterKey.intern()); - } - - /** - * Create an ImageFormatter from the contents of a properties object. - * - * @param p Properties used to initialize the Properties. - * @return default formatter. - */ - protected synchronized ImageFormatter getFormatters(Properties p) { - String formattersString; - ImageFormatter iFormatter = null; - - String prefix = PropUtils.getScopedPropertyPrefix(this); - formattersString = p.getProperty(prefix + ImageFormattersProperty); - - // First, look at the formatters string to get a marker list - // of available formatters. - if (formattersString != null) { - Vector markerNames = PropUtils.parseSpacedMarkers(formattersString); - Vector formatters = ComponentFactory.create(markerNames, p); - - int size = formatters.size(); - - if (imageFormatters == null) { - imageFormatters = new Hashtable(size); - } - - for (int i = 0; i < size; i++) { - ImageFormatter formatter = (ImageFormatter) formatters.get(i); - imageFormatters.put(formatter.getFormatLabel(), formatter); - - if (i == 0) { - iFormatter = formatter; - } - } - - } else { - logger.fine("no formatters specified"); - } - - return iFormatter; - } - - /** - * Create an array of Layers from a properties object. - */ - protected Layer[] getLayers(Properties p) { - return getLayers(p, (Map) null); - } - - /** - * Create an array of Layers from a properties object. Reuse the layer from - * the hashtable if it's there under the same property name. The Hashtable - * is kept for an ImageServer that is used buy an ImageMaster or another - * object that is using different layers for it's image. It will reuse the - * layers it's already created if the marker names are the same. - * - * @param p properties - * @param instantiatedLayers a hashtable containing layers, with the prefix - * layer name used as the key. - */ - protected Layer[] getLayers(Properties p, Map instantiatedLayers) { - - String layersValue; - String prefix = PropUtils.getScopedPropertyPrefix(this); - layersValue = p.getProperty(prefix + ImageServerLayersProperty); - - if (layersValue == null) { - // get openmap.layers value - layersValue = p.getProperty(OpenMapPrefix + ImageServerLayersProperty); - - if (layersValue == null) { - logger.warning("No property \"" + ImageServerLayersProperty + "\" found in ImageServer properties."); - return new Layer[0]; - } - } - - Vector layerNames = PropUtils.parseSpacedMarkers(layersValue); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("OpenMap.getLayers(): " + layerNames); - } - - int nLayerNames = layerNames.size(); - List layers = new ArrayList(nLayerNames); - - for (String layerName : layerNames) { - - // Check to see if some other ImageServer has used this - // layer, and reuse it. - if (instantiatedLayers != null) { - Layer iLayer = instantiatedLayers.get(layerName); - if (iLayer != null) { - - // We might want to consider adding this: - // iLayer.setProperties(layerName, p); - - layers.add(iLayer); - if (logger.isLoggable(Level.FINE)) { - logger.fine("adding instantiated layer /" + layerName + "/"); - } - continue; - } - } - - // Brand new layer, so instantiate it. - String classProperty = layerName + ".class"; - String className = p.getProperty(classProperty); - if (className == null) { - logger.warning("Failed to locate property \"" + classProperty + "\""); - logger.warning("Skipping layer \"" + layerName + "\""); - continue; - } - - Object obj = ComponentFactory.create(className, layerName, p); - if (obj instanceof Layer || obj instanceof PlugIn) { - Layer l = null; - - if (obj instanceof PlugIn) { - PlugIn pi = (PlugIn) obj; - PlugInLayer pil = new PlugInLayer(); - pil.setPlugIn(pi); - pil.setName(p.getProperty(PropUtils.getScopedPropertyPrefix(pi) + Layer.PrettyNameProperty)); - l = pil; - } else { - l = (Layer) obj; - } - - layers.add(l); - - if (instantiatedLayers != null) { - instantiatedLayers.put(layerName, l); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Saving /" + layerName + "/ to instantiated layers hashtable."); - } - } - } - } - - int nLayers = layers.size(); - if (nLayers == 0) { - return new Layer[0]; - } else { - Layer[] layerArray = new Layer[nLayers]; - layers.toArray(layerArray); - return layerArray; - } - } - - public ProjectionFactory getProjectionFactory() { - if (projectionFactory == null) { - projectionFactory = ProjectionFactory.loadDefaultProjections(); - } - return projectionFactory; - } - - public void setProjectionFactory(ProjectionFactory projFactory) { - projectionFactory = projFactory; - } - - /** - * Takes a byte array and writes it out to a file path. - * - * @param imageBytes the formatted bytes of the image. - * @param outputPath the path of the image file. - * @param checkFormatterForExtension if true, will check the current active - * formatter for extension that will be added to the path if it - * doesn't end with the image type. - * @return the final file path used, with any extensions added. - * @throws IOException - */ - public String writeImageFile(byte[] imageBytes, String outputPath, boolean checkFormatterForExtension) - throws IOException { - String appendix = ""; - - if (checkFormatterForExtension) { - ImageFormatter formatter = getFormatter(); - if (formatter == null) { - appendix = ".jpg"; - } else { - String fileType = formatter.getFormatLabel(); - if (fileType.equals(WMTConstants.IMAGEFORMAT_JPEG)) { - appendix = ".jpg"; - } else { - appendix = "." + fileType.toLowerCase(); - } - } - - // If the file output path already ends properly, don't bother - // changing - // it. - if (outputPath.endsWith(appendix)) { - appendix = ""; - } - } - - String finalOutputPath = outputPath + appendix; - - FileOutputStream fos = new FileOutputStream(finalOutputPath); - - fos.write(imageBytes); - fos.flush(); - fos.close(); - - return finalOutputPath; - } - - /** - * For convenience, to create an image file based on the contents of a - * properties file (like an openmap.properties file). - * - * @param prefix The prefix for the ImageServer properties (layers and - * formatters) to use in the properties file. If defined, then this - * method will look for 'prefix.layers' and prefix.formatters' - * properties. If null, then this method will look 'layers' and - * 'formatters' properties. - * - * @param props The properties to use for defining the layers and plugins to - * use on the map image. Standard openmap.properties formats for - * layer definitions. See the standard openmap.properties file for - * more details on how to define layers and plugins. - * - * @param proj The projection to use for the map. If null, then the - * Environment projection properties will be looked for in the - * Properties. - * - * @param outputPath The output path for the image file. The image file - * should not have an appendix defined. This method will check which - * formatter is being used, and will assign one based on the image - * format (leave off the ., too). - * - * @return the final path of the written image file, with the chosen - * appendix attached. - */ - public static String createImageFile(String prefix, Properties props, Projection proj, String outputPath) - - throws MalformedURLException, IOException { - - String appendix = ""; - - ImageServer is = new ImageServer(props); - - ImageFormatter formatter = is.getFormatter(); - if (formatter == null) { - is.setFormatter(new SunJPEGFormatter()); - appendix = ".jpg"; - } else { - String fileType = formatter.getFormatLabel(); - if (fileType.equals(WMTConstants.IMAGEFORMAT_JPEG)) { - appendix = ".jpg"; - } else { - appendix = "." + fileType.toLowerCase(); - } - } - - Color background = MapBean.DEFAULT_BACKGROUND_COLOR; - background = (Color) PropUtils.parseColorFromProperties(props, Environment.BackgroundColor, background); - - is.setBackground(background); - - // Initialize the map projection, scale, center with - // user prefs or defaults - if (proj == null) { - ProjectionFactory projFactory = is.getProjectionFactory(); - String projName = props.getProperty(Environment.Projection); - Class projClass = projFactory.getProjClassForName(projName); - - if (projClass == null) { - projClass = Mercator.class; - } - - Point2D center = null; - - if (GeoProj.class.isAssignableFrom(projClass)) { - center = - new LatLonPoint.Float(PropUtils.floatFromProperties(props, Environment.Latitude, 0f), - PropUtils.floatFromProperties(props, Environment.Longitude, 0f)); - } else { - center = - new Point2D.Float(PropUtils.floatFromProperties(props, Environment.Latitude, 0f), - PropUtils.floatFromProperties(props, Environment.Longitude, 0f)); - } - - proj = - projFactory.makeProjection(projClass, center, - PropUtils.floatFromProperties(props, Environment.Scale, MapBean.DEFAULT_SCALE), - PropUtils.intFromProperties(props, Environment.Width, MapBean.DEFAULT_WIDTH), - PropUtils.intFromProperties(props, Environment.Height, MapBean.DEFAULT_HEIGHT)); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("creating image with projection " + proj); - } - - byte[] imageBytes = is.createImage(proj); - String finalOutputPath = outputPath + appendix; - FileOutputStream fos = new FileOutputStream(finalOutputPath); - - fos.write(imageBytes); - fos.flush(); - fos.close(); - - return finalOutputPath; - } - - /** - * Paint object used for map backgrounds. - */ - protected Paint background; - - /** - * Set the Paint to use for image backgrounds. - */ - public void setBackground(Paint bg) { - background = bg; - } - - /** - * Get the Paint to use for image backgrounds. - */ - public Paint getBackground() { - return background; - } - - /** - * Set the transparent flag. Even if this flag is true, the image still may - * not end up transparent if the {@link ImageFormatter} does not support - * transparency or the image is completely filled. - * - * @param transparent - */ - public void setTransparent(boolean transparent) { - this.transparent = transparent; - } - - /** - * Get the transparent flag. Even if this flag is true, the image still may - * not end up transparent if the {@link ImageFormatter} does not support - * transparency or the image is completely filled. - * - * @return true if set for transparency - */ - public boolean getTransparent() { - return transparent; - } - - /** - * The ImageServer class main function will create a map image from a - * modified openmap.properties file. - * - *

-     * java com.bbn.openmap.image.ImageServer -properties (path to properties file) -file (path to output image)
-     * 
- * - *

- * The path to the output image should not have an appendix on it, that will - * get assigned depending on what image format is used. - */ - public static void main(String[] argv) { - - com.bbn.openmap.util.ArgParser ap = new com.bbn.openmap.util.ArgParser("ImageServer"); - - ap.add("properties", "The properties file to use for the image.", 1); - ap.add("file", "The output image file, without appendix (default is 'image').", 1); - - if (!ap.parse(argv)) { - ap.printUsage(); - System.exit(0); - } - - String imagefile = "image"; - String arg[]; - - arg = ap.getArgValues("file"); - if (arg != null) { - imagefile = arg[0]; - } - - Properties props = null; - arg = ap.getArgValues("properties"); - if (arg != null) { - String ps = arg[0]; - try { - - URL url = PropUtils.getResourceOrFileOrURL(null, ps); - InputStream inputStream = url.openStream(); - - props = new Properties(); - props.load(inputStream); - - Projection proj = null; - - String finalOutputPath = ImageServer.createImageFile(null, props, proj, imagefile); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Writing image file to: " + finalOutputPath); - } - - } catch (MalformedURLException murle) { - logger.warning("ImageServer can't find properties file: " + arg[0]); - } catch (IOException ioe) { - logger.warning("ImageServer can't write output image: IOException"); - } - } - - System.exit(0); - } -} diff --git a/src/openmap/com/bbn/openmap/io/BinaryFile.java b/src/openmap/com/bbn/openmap/io/BinaryFile.java deleted file mode 100644 index 4b3a805ce..000000000 --- a/src/openmap/com/bbn/openmap/io/BinaryFile.java +++ /dev/null @@ -1,857 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/io/BinaryFile.java,v $ -// $RCSfile: BinaryFile.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/01/21 01:24:42 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.io; - -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MoreMath; -import com.bbn.openmap.util.Debug; - -/** - * The BinaryFile is the standard object used to access data files. It acts like - * a RandomAccessFile, but will work on jar file contents and URLs, too. The - * source of the data is isolated through the InputReader interface. - */ -public class BinaryFile { - private static int openCount = 0; - private static int classCount = 0; - - private InputReader inputReader = null; - - /** - * The byte order of the underlying file. (true== MSB-First == - * big-endian) - */ - protected boolean MSBFirst = false; - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * default byte-order is LSB first. Reads start at the first byte of the - * file. - * - * @param f the file to be opened for reading - * @exception IOException pass-through errors from opening a - * RandomAccessFile with f - * @see java.io.RandomAccessFile - */ - public BinaryFile(File f) throws IOException { - inputReader = new FileInputReader(f); - classCount++; - openCount++; - } - - /** - * Constructs a new BinaryFile with the specified inputReader as the input. - * - * @param inputReader the input reader to be opened for reading - */ - private BinaryFile(InputReader inputReader) { - this.inputReader = inputReader; - classCount++; - openCount++; - } - - /** - * Constructs a new BinaryFile with the specified file as the input. The - * byte-order is undefined. Reads start at the first byte of the file. This - * constructor looks for the file with the string given, and will call the - * correct constructor as appropriate. If the string represents a file - * available locally, then the BinaryFile will be accessed with a - * FileInputReader using a RandomAccessFile. If it's only available as a - * resource, then a StreamInputReader will be used. The name should be a - * path to a file, or the name of a resource that can be found in the - * classpath, or a URL. - * - * @param name the name of the file to be opened for reading - * @exception IOException pass-through errors from opening the file. - */ - public BinaryFile(String name) throws IOException { - boolean showDebug = false; - if (Debug.debugging("binaryfile")) { - showDebug = true; - } - - if (showDebug) { - Debug.output("BinaryFile: trying to figure out how to handle " + name); - } - - try { - File file = null; - URL url = null; - - if (!Environment.isApplet()) { - file = new File(name); - } - - if (file != null && file.exists()) { - // If the string represents a file, then we want to - // use the RandomAccessFile aspect of the BinaryFile. - setInputReader(new FileInputReader(file)); - } else { - // see JNLP deploy tip here - // http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#ClassLoader_and_Resources - final InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - if (resourceStream != null) { - if (showDebug) { - Debug.output("BinaryFile: loading " + name + " via getResourceAsStream"); - } - final String urlName = name; - setInputReader(new StreamInputReader() { - { - this.name = urlName; - this.inputStream = resourceStream; - } - - @Override - protected void reopen() throws IOException { - super.reopen(); - inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - } - }); - } else { - // If the getResourceAsStream didn't work, go back to the - // old way of doing things... - // url = ClassLoader.getSystemResource(name); - url = Thread.currentThread().getContextClassLoader().getResource(name); - - // OK, now we want to look around for the file, in the - // classpaths, and as a resource. It may be a file in - // a classpath, available for direct access. - if (url != null) { - - String newname = url.getFile(); - if (showDebug) { - Debug.output("BinaryFile: looking for " + newname); - } - - if (!Environment.isApplet()) { - file = new File(newname); - } - - if (file != null && file.exists()) { - // It's still a file, available directly. - // Access it with the RandomAccessFile - setInputReader(new FileInputReader(file)); - } else { - // Need to get it as a resource. Needs - // special handling if it's coming in a jar - // file. Jar file references have a "!" in - // them - if (!setJarInputReader(newname)) { - if (showDebug) { - Debug.output(" trying as url: " + url); - } - setInputReader(new URLInputReader(url)); - } - - } - - } else if (Environment.isApplet()) { - if (showDebug) { - Debug.output(" As applet, checking codebase..."); - } - // Look in the codebase for applets... - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - - URLClassLoader ucl = URLClassLoader.newInstance(cba); - url = ucl.getResource(name); - - if (url != null) { - setInputReader(new URLInputReader(url)); - } - } - } - - // It's not in the classpath, so try it as a URL. - if (inputReader == null) { - - if (showDebug) { - Debug.output(" lastly, trying as URL: " + name); - } - try { - setInputReader(new URLInputReader(new URL(name))); - } catch (java.security.AccessControlException ace) { - Debug.output("BinaryFile: " + name + " couldn't be accessed."); - throw new IOException("AccessControlException trying to fetch " + name - + " as a URL"); - } - } - - } - - if (inputReader == null) { - throw new FileNotFoundException("BinaryFile can't find: " + name); - } - - classCount++; - openCount++; - - } catch (IOException ioe) { - throw ioe; - } - } - - /** - * Takes a name of a file, and checks to see if it reflects an entry in a - * jar file. (Check the filename and see if it looks like - * "jarfile!jarfileentry".) If it is, it separates the path, and set the - * inputReader to a JarInputReader and returns true. If not, it returns - * false. - */ - protected boolean setJarInputReader(String name) throws IOException { - - try { - int index = name.indexOf("!"); - if (index != -1) { - - // Used to be this, modified by Erik Sanders to work - // with jdk 1.4 plugin - // String jarFileName = - // name.substring(name.indexOf(":") + 1, index); - - // changed to this... - String jarFileName; - - if (name.startsWith("file:")) { - // java-plugin 1.3 returns local file: strip file: - // from string - jarFileName = name.substring(name.indexOf(":") + 1, index); - } else { - // java-plugin 1.4 returns reference to server, so - // leave http:// part - - // Used to start the substring from 1, but changed - // to 0 thanks to DGK - jarFileName = name.substring(0, index); - } - - // skip !/ " - String jarEntryName = name.substring(index + 2); - if (Debug.debugging("binaryfile")) { - Debug.output(" got: \n" + jarFileName + "\n" + jarEntryName); - } - - // If the jar doesn't exist, should return something - // that indicates this. Should check the performance - // implications of this call, though, at some point. - - // DGK added - File f = new File(jarFileName); - if (f.exists() == false) { - return false; - } - - setInputReader(new JarInputReader(jarFileName, jarEntryName)); - return true; - } - } catch (java.security.AccessControlException ace) { - if (Debug.debugging("binaryfile")) { - Debug.output("BinaryFile.setJarInputFile: AccessControlException for " + name); - } - } - - return false; - } - - /** - * A simple test method to determine if a file or directory, represented by - * a string, can be found by the current Java environment. Uses the same - * tests as BinaryFile constructor for tracking down a file. - * - * @param name A path to a file, a URL, or a path to a jar file entry. - * @return true if the file can be found - */ - public static boolean exists(String name) { - boolean exists = false; - try { - File file = null; - URL url = null; - - if (!Environment.isApplet()) { - file = new File(name); - } - - if (file != null && file.exists()) { - exists = true; - } else { - - // Could be a binary file stored in a jar file - try { - url = new URL(name); - return true; - } catch (MalformedURLException e) { - // Do nothing, try other url types - url = null; - } - - // url = ClassLoader.getSystemResource(name); - url = Thread.currentThread().getContextClassLoader().getResource(name); - - // OK, now we want to look around for the file, in the - // classpaths, and as a resource. It may be a file in - // a classpath, available for direct access. - if (url != null) { - exists = true; - } else if (Environment.isApplet()) { - if (Debug.debugging("binaryfile")) { - Debug.output(" As applet, checking codebase..."); - } - // Look in the codebase for applets... - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - - URLClassLoader ucl = URLClassLoader.newInstance(cba); - if (ucl.getResource(name) != null) { - exists = true; - - // This has been commented out because the - // AppletDataNugget has been deprecated, and - // is not needed. - - // } else { - // url = AppletDataNugget.findResource(name); - - // if (url != null) { - // exists = true; - // } - } - } - - // It's not in the classpath, so try it as a URL to a - // webserver. - if (!exists && name.indexOf("http:") != -1) { - - try { - InputStream stream = new URL(name).openStream(); - stream.close(); - exists = true; - } catch (java.security.AccessControlException ace) { - exists = false; - } - } - } - - } catch (IOException ioe) { - Debug.message("binaryfile", "BinaryFile.exists() caught IOException"); - exists = false; - } - - if (Debug.debugging("binaryfile")) { - Debug.output("BinaryFile.exists(" + name + ") = " + exists); - } - - return exists; - } - - /** - * Get the source name from the input reader. - */ - public String getName() { - if (inputReader != null) { - return inputReader.getName(); - } - return null; - } - - /** - * Get the inputReader used for accessing the file, for querying purposes. - * Don't use it to get data, or the file pointers may get messed up. - */ - public InputReader getInputReader() { - return inputReader; - } - - /** - * Set the input reader used by the BinaryFile. Make sure it's initialized - * properly. - */ - public void setInputReader(InputReader reader) { - if (Debug.debugging("binaryfile")) { - Debug.output("Setting inputReader"); - } - inputReader = reader; - } - - /** - * Set the byte-ordering used to read shorts, int, etc. - * - * @param msbfirst true= MSB first, false= LSB - * first - */ - public void byteOrder(boolean msbfirst) { - MSBFirst = msbfirst; - } - - /** - * Accessor for the byte ordering used to read multibyte types. - * - * @return byte ordering, true means MSB first. - */ - public boolean byteOrder() { - return MSBFirst; - } - - /** - * Skip over n bytes in the input file - * - * @param n the number of bytes to skip - * @return the actual number of bytes skipped. annoying, isn't it? - * @exception IOException Any IO errors that occur in skipping bytes in the - * underlying file - */ - public long skipBytes(long n) throws IOException { - return inputReader.skipBytes(n); - } - - /** - * Get the index of the next character to be read - * - * @return the index - * @exception IOException Any IO errors that occur in accessing the - * underlying file - */ - public long getFilePointer() throws IOException { - return inputReader.getFilePointer(); - } - - /** - * Set the index of the next character to be read. - * - * @param pos the position to seek to. - * @exception IOException Any IO Errors that occur in seeking the underlying - * file. - */ - public void seek(long pos) throws IOException { - inputReader.seek(pos); - } - - /** - * The length of the InputReader source. - */ - public long length() throws IOException { - return inputReader.length(); - } - - /** - * Return how many bytes left to be read in the file. - * - * @return the number of bytes remaining to be read (counted in bytes) - * @exception IOException Any IO errors encountered in accessing the file - */ - public long available() throws IOException { - return inputReader.available(); - } - - /** - * Closes the underlying file, but with a chance for re-opening if accessed - * again. - * - * @exception IOException Any IO errors encountered in accessing the file - */ - public void close() throws IOException { - if (inputReader != null) { - inputReader.close(); - openCount--; - } - } - - /** - * Closes underlying file, get rid of resources and knowledge of file. To be - * called when you don't need the file any more. - * - * @throws IOException - */ - public void dispose() throws IOException { - close(); - inputReader = null; - } - - /** - * Read from the file. - * - * @return one byte from the file. -1 for EOF - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read() throws IOException { - return inputReader.read(); - } - - /** - * Read from the file - * - * @param b The byte array to read into - * @param off the first array position to read into - * @param len the number of bytes to read - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - */ - public int read(byte b[], int off, int len) throws IOException { - return inputReader.read(b, off, len); - } - - /** - * Read from the file. - * - * @param b the byte array to read into. Equivalent to - * read(b, 0, b.length) - * @return the number of bytes read - * @exception IOException Any IO errors encountered in reading from the file - * @see java.io.RandomAccessFile#read(byte[]) - */ - public int read(byte b[]) throws IOException { - return inputReader.read(b); - } - - /** - * Read from the file. - * - * @param howmany the number of bytes to read - * @param allowless if we can return fewer bytes than requested - * @return the array of bytes read. - * @exception FormatException Any IO Exceptions, plus an end-of-file - * encountered after reading some, but now enough, bytes when - * allowless was false - * @exception EOFException Encountered an end-of-file while allowless was - * false, but NO bytes had been read. - */ - public byte[] readBytes(int howmany, boolean allowless) throws EOFException, FormatException { - - return inputReader.readBytes(howmany, allowless); - } - - /** - * Reads and returns a single byte, cast to a char - * - * @return the byte read from the file, cast to a char - * @exception EOFException the end-of-file has been reached, so no chars - * where available - * @exception FormatException a rethrown IOException - */ - public char readChar() throws EOFException, FormatException { - try { - int retv = inputReader.read(); - - if (retv == -1) { - throw new EOFException("Error in ReadChar, EOF reached"); - } - return (char) retv; - } catch (IOException i) { - throw new FormatException("readChar IOException: " + i.getMessage()); - } - } - - /** - * Read a byte from the file, return an unsigned integer. - * - * @return one byte from the file. -1 for EOF causes EOFException - * @exception IOException Any IO errors encountered in reading from the file - */ - public int readUnsigned() throws IOException, EOFException { - byte b = (byte) read(); - if (b == -1) { - throw new EOFException(); - } - return MoreMath.signedToInt(b); - } - - /** - * Reads and returns a short. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public short readShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.BuildShort(readBytes(2, false), MSBFirst); - } - - /** - * Code for reading shorts that are two-byte integers, high order first, and - * negatives are signed magnitude. Users may have to switch the bytes and - * convert negatives to the complement they use. This can be done by putting - * the low order byte first, then turning off bit 15 (the high order bit), - * and then multiplying by -1." Basically they are encoded as positive - * numbers, but bit 15 is set to 1. - * - * @return 2 bytes merged into a short - * @throws EOFException - * @throws FormatException - */ - public short readShortData() throws EOFException, FormatException { - // read in the two bytes - byte[] bytevec = readBytes(2, false); - - // check for negative values - bit 7 of byte 0 - if (bytevec[0] < 0) { - // mask bit 7 - bytevec[0] &= 0x7f; - // create the short and multiply the result by -1 - return ((short) (MoreMath.BuildShort(bytevec, true) * -1)); - } - return MoreMath.BuildShort(bytevec, true); - } - - /** - * Reads and returns a integer from 2 bytes. - * - * @return the 2 bytes merged into a short, according to the current byte - * ordering, and then unsigned to int. - * @exception EOFException there were less than 2 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public int readUnsignedShort() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.signedToInt(readShort()); - } - - /** - * Reads and returns a long - * - * @return the 4 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 4 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the integer - * @see #read(byte[]) - */ - public int readInteger() throws EOFException, FormatException { - // MSBFirst must be set when we are called - return MoreMath.BuildInteger(readBytes(4, false), MSBFirst); - } - - public void readIntegerArray(int vec[], int offset, int len) - throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readInteger(); - } - } - - /** - * Reads and returns a long - * - * @return the 8 bytes merged into a long, according to the current byte - * ordering - * @exception EOFException there were less than 8 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the long - * @see #read(byte[]) - */ - public long readLong() throws EOFException, FormatException { - return MoreMath.BuildLong(readBytes(8, false), MSBFirst); - } - - /** - * Reads and returns a float - * - * @return the 4 bytes merged into a float, according to the current byte - * ordering - * @exception EOFException there were less than 4 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the float - * @see #read(byte[]) - */ - public float readFloat() throws EOFException, FormatException { - return Float.intBitsToFloat(readInteger()); - } - - public void readFloatArray(float vec[], int offset, int len) - throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readFloat(); - } - } - - public void readFloatArray(double vec[], int offset, int len) - throws EOFException, FormatException { - for (int i = 0; i < len; i++) { - vec[offset++] = readFloat(); - } - } - - /** - * Reads and returns a double - * - * @return the 8 bytes merged into a double, according to the current byte - * ordering - * @exception EOFException there were less than 8 bytes left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - * @see #read(byte[]) - */ - public double readDouble() throws EOFException, FormatException { - return Double.longBitsToDouble(readLong()); - } - - /** - * Reads length bytes and returns a string composed of the - * bytes cast to chars - * - * @param length the number of bytes to read into the string - * @return the composed string - * @exception EOFException there were less than length bytes - * left in the file - * @exception FormatException rethrow of IOExceptions encountered while - * reading the bytes for the short - */ - public String readFixedLengthString(int length) throws EOFException, FormatException { - - byte foo[] = readBytes(length, false); - return new String(foo, 0, length); - } - - /** - * Read a bytes and throw an InvalidCharException if it doesn't match - * expected - * - * @param expected what the next char is claimed to be - * @exception EOFException there wasn't a byte, so we can't check for a - * match - * @exception InvalidCharException throws when the character read doesn't - * match expected The .c member of the thrown - * exception is the actual char read - * @exception FormatException some other error from reading the file - */ - public void assertChar(char expected) throws EOFException, FormatException { - char c = readChar(); - if (c != expected) { - throw new InvalidCharException("AssertChar: expected " + expected + " got " + c, c); - } - } - - /** - * Reads a string until the specified delimiter or EOF is encountered - * - * @param delim the end-of-string delimiter - * @return the string that was read - * @exception FormatException rethrow of IOExceptions from the read methods - */ - public String readToDelimiter(char delim) throws FormatException { - StringBuffer buildretval = new StringBuffer(); - char tmp; - try { - while ((tmp = readChar()) != delim) - buildretval.append(tmp); - } catch (EOFException e) { - // allowable - } catch (FormatException fe) { - if (buildretval.length() == 0) { - throw fe; - } - } - return buildretval.toString(); - } - - /** - * Makes sure that the file has been closed. - * - * @exception Throwable what it throws. - */ - protected void finalize() throws Throwable { - close(); - classCount--; - } - - /** - * Maintains a list of objects that can be closed so that other files can be - * opened. - */ - private static Vector> closableList = new Vector>(); - - /** - * Add an object that can be closed if needed. Duplicates are allowed. Only - * holds a WeakReference, so that the object can still be garbage-collected. - * - * @param it the object that can be closed - */ - public static synchronized void addClosable(Closable it) { - closableList.addElement(new WeakReference(it)); - } - - /** - * Remove an object from the closable list. - * - * @param it the object to remove - */ - public static synchronized void removeClosable(Closable it) { - for (int i = 0; i < closableList.size(); i++) { - Object o = closableList.elementAt(i).get(); - if ((o == it) || (o == null)) { - closableList.removeElementAt(i); - i--; // in case its in the list more than once - } - } - } - - public static synchronized void closeClosable() { - System.out.println("closeClosable " + closableList.size()); - for (int i = 0; i < closableList.size(); i++) { - Closable c = (Closable) ((WeakReference) closableList.elementAt(i)).get(); - if ((c == null) || !c.close(false)) { - closableList.removeElementAt(i); - i--; - } - } - } - - /** - * Read the {@link BinaryFile} into memory and return a new - * {@link BinaryFile} instance working on that in-memory version of the - * file. - * - * @return BinaryFile object pointing to memory version. - * @throws IOException - */ - public BinaryFile readFully() throws IOException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - - seek(0); - int len; - while (available() > 0) { - len = read(buf); - baos.write(buf, 0, len); - } - - return new BinaryFile(new ByteArrayInputReader(baos.toByteArray())); - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/DrawingToolLayer.java b/src/openmap/com/bbn/openmap/layer/DrawingToolLayer.java deleted file mode 100644 index d67608d80..000000000 --- a/src/openmap/com/bbn/openmap/layer/DrawingToolLayer.java +++ /dev/null @@ -1,840 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/DrawingToolLayer.java,v $ -// $RCSfile: DrawingToolLayer.java,v $ -// $Revision: 1.35 $ -// $Date: 2008/02/28 23:36:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.StreamCorruptedException; -import java.net.URL; -import java.util.Properties; -import java.util.Vector; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import com.bbn.openmap.I18n; -import com.bbn.openmap.dataAccess.shape.DbfTableModel; -import com.bbn.openmap.dataAccess.shape.DbfTableModelFactory; -import com.bbn.openmap.dataAccess.shape.EsriShapeExport; -import com.bbn.openmap.dataAccess.shape.ShapeConstants; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.MapMouseSupport; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.DrawingTool; -import com.bbn.openmap.tools.drawing.DrawingToolRequestor; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.FileUtils; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.propertyEditor.Inspector; - -/** - * This layer can receive graphics from the OMDrawingToolLauncher, and also sent - * it's graphics to the OMDrawingTool for editing. - *

- * - * The projectionChanged() method is taken care of in the OMGraphicHandlerLayer - * superclass. - *

- * - * This class responds to all the properties that the OMGraphicHandlerLayer - * responds to, including the mouseModes property. If the mouseModes property - * isn't set, the SelectMouseMode.modeID mode ID is set. When the - * MapMouseInterpreter calls select(OMGraphic), the OMGraphic is passed to the - * DrawingTool. This class also responds to the showHints property (true by - * default), which dictates if tooltips and information delegator text is - * displayed when the layer's contents are moused over. - * - *

- * 
- *                                # Properties for DrawingToolLayer:
- *                                drawingToolLayer.class=com.bbn.openmap.layer.DrawingToolLayer
- *                               
- *                                drawingToolLayer.prettyName=General Layer
- *                               
- *                                # optional flag to tell layer to display tooltip queues over it's OMGraphics
- *                                drawingToolLayer.showHints=true
- *                               
- *                                # optional flag to specify file to store and read OMGraphics.  A Save button 
- *                                # is available on the palette.  If it's not specified and the Save button is 
- *                                # chosen, the user will queried for this location.
- *                                drawingToolLayer.file=file to read OMGraphics from
- * 
- * 
- */ -public class DrawingToolLayer extends OMGraphicHandlerLayer implements DrawingToolRequestor { - - /** Get a handle on the DrawingTool. */ - protected OMDrawingTool drawingTool; - - /** - * A flag to provide a tooltip over OMGraphics to click to edit. - */ - protected boolean showHints = true; - - /** - * A property that can control whether mouse events generate hints over map - * objects (showHints). - */ - public final static String ShowHintsProperty = "showHints"; - - /** - * A property to specify the file to use to read and save map objects in - * (file). - */ - public final static String SerializedURLNameProperty = "file"; - - /** - * The name of the file to read/save OMGraphics in. - */ - protected String fileName; - - protected boolean DTL_DEBUG = false; - - protected DbfTableModelFactory dbfFactory = null; - - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - protected OMGraphicList omGraphics; - - public DrawingToolLayer() { - setAddToBeanContext(true); - - DTL_DEBUG = Debug.debugging("dtl"); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - drawingAttributes.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - showHints = PropUtils.booleanFromProperties(props, realPrefix + ShowHintsProperty, showHints); - - if (getMouseModeIDsForEvents() == null) { - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - } - - String fileName = props.getProperty(realPrefix + SerializedURLNameProperty); - - String dataPathPrefix = (String) getAttribute(DataPathPrefixProperty); - if (dataPathPrefix != null) { - fileName = dataPathPrefix + "/" + fileName; - } - - if (fileName != null && fileName.trim().length() > 0) { - this.fileName = fileName; - setOMGraphics(load()); - } - - if (dbfFactory != null) { - dbfFactory.setProperties(prefix, props); - - OMGraphicList list = getOMGraphics(); - if (list != null && list.getAttribute(ShapeConstants.DBF_ATTRIBUTE) == null) { - dbfFactory.createDbf(list); - } - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - drawingAttributes.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + ShowHintsProperty, new Boolean(showHints).toString()); - props.put(prefix + SerializedURLNameProperty, PropUtils.unnull(fileName)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - drawingAttributes.getPropertyInfo(props); - - String interString; - - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, I18n.TOOLTIP, - "Display tooltips over layer's map objects."); - props.put(ShowHintsProperty, interString); - props.put(ShowHintsProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, "Show Hints"); - props.put(ShowHintsProperty + LabelEditorProperty, interString); - - interString = i18n.get(DrawingToolLayer.class, SerializedURLNameProperty, I18n.TOOLTIP, - "File to use for reading and saving map objects."); - props.put(SerializedURLNameProperty, interString); - props.put(SerializedURLNameProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - interString = i18n.get(DrawingToolLayer.class, ShowHintsProperty, "File Name for Saving"); - props.put(SerializedURLNameProperty + LabelEditorProperty, interString); - - props.put(initPropertiesProperty, SerializedURLNameProperty + " " + ShowHintsProperty); - return props; - } - - public synchronized OMGraphicList prepare() { - - Projection proj = getProjection(); - - OMGraphicList currentGraphics = getOMGraphics(); - if (currentGraphics == null) { - currentGraphics = load(); - setOMGraphics(currentGraphics); - } - - if (currentGraphics != null && proj != null) { - currentGraphics.generate(proj); - currentGraphics.setVisible(true); - return new OMGraphicList(currentGraphics); - } - - return null; - } - - public OMDrawingTool getDrawingTool() { - return drawingTool; - } - - public void setDrawingTool(OMDrawingTool dt) { - drawingTool = dt; - } - - /** - * This is the managed list of OMGraphics, the internal list used for - * rendering. - * - * @param omgList - */ - public void setOMGraphics(OMGraphicList omgList) { - omGraphics = omgList; - } - - public OMGraphicList getOMGraphics() { - return omGraphics; - } - - /** - * DrawingToolRequestor method. - */ - public void drawingComplete(OMGraphic omg, OMAction action) { - - if (DTL_DEBUG) { - String cname = omg.getClass().getName(); - int lastPeriod = cname.lastIndexOf('.'); - if (lastPeriod != -1) { - cname = cname.substring(lastPeriod + 1); - } - Debug.output("DrawingToolLayer: DrawingTool complete for " + cname + " > " + action); - } - // First thing, release the proxy MapMouseMode, if there is - // one. - releaseProxyMouseMode(); - - // GRP, assuming that selection is off. - OMGraphicList omgl = new OMGraphicList(); - omg.putAttribute(OMGraphicConstants.UPDATED, Boolean.TRUE); - omgl.add(omg); - deselect(omgl); - - OMGraphicList list = getOMGraphics(); - - if (list == null) { - list = new OMGraphicList(); - setOMGraphics(list); - } - - DbfTableModel dbf = (DbfTableModel) list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - // Adding an OMGraphic without dbf being set, if we can create one - // from a factory, do it. - if (dbf == null && dbfFactory != null) { - dbf = dbfFactory.createDbf(list); - } - - if (dbf != null) { - dbf.doAction(list, omg, action, dbfFactory); - } else { - list.doAction(omg, action); - } - doPrepare(); - } - - /** - * If the DrawingToolLayer is using a hidden OMDrawingTool, release the - * proxy lock on the active MapMouseMode. - */ - public void releaseProxyMouseMode() { - MapMouseMode pmmm = getProxyMouseMode(); - OMDrawingTool dt = getDrawingTool(); - if (pmmm != null && dt != null) { - if (pmmm.isProxyFor(dt.getMouseMode())) { - if (DTL_DEBUG) { - Debug.output("DTL: releasing proxy on " + pmmm.getID()); - } - - pmmm.releaseProxy(); - setProxyMouseMode(null); - fireRequestInfoLine(""); // hidden drawing tool put up - // coordinates, clean up. - } - - if (dt.isActivated()) { - dt.deactivate(); - } - } - } - - /** - * Called by findAndInit(Iterator) so subclasses can find objects, too. - */ - public void findAndInit(Object someObj) { - if (someObj instanceof OMDrawingTool) { - Debug.message("dtl", "DrawingToolLayer: found a drawing tool"); - setDrawingTool((OMDrawingTool) someObj); - } - } - - /** - * BeanContextMembershipListener method. Called when a new object is removed - * from the BeanContext of this object. - */ - public void findAndUndo(Object someObj) { - super.findAndUndo(someObj); - if (someObj instanceof DrawingTool && getDrawingTool() == someObj) { - setDrawingTool(null); - } - } - - protected MapMouseMode proxyMMM = null; - - /** - * Set the ProxyMouseMode for the internal drawing tool, if there is one. - * Can be null. Used to reset the mouse mode when drawing's complete. - */ - protected synchronized void setProxyMouseMode(MapMouseMode mmm) { - proxyMMM = mmm; - } - - /** - * Get the ProxyMouseMode for the internal drawing tool, if there is one. - * May be null. Used to reset the mouse mode when drawing's complete. - */ - protected synchronized MapMouseMode getProxyMouseMode() { - return proxyMMM; - } - - /** - * A method called from within different MapMouseListener methods to check - * whether an OMGraphic *should* be edited if the OMDrawingTool is able to - * edit it. Can be used by subclasses to delineate between OMGraphics that - * are non-relocatable versus those that can be moved. This method should - * work together with the getToolTipForOMGraphic() method so that OMGraphics - * that shouldn't be edited don't provide tooltips that suggest that they - * can be. - *

- * - * By default, this method always returns true because the DrawingToolLayer - * always thinks the OMGraphic should be edited. - */ - public boolean shouldEdit(OMGraphic omgr) { - return true; - } - - protected JPanel box; - protected JComboBox jcb; - - public Component getGUI() { - if (box == null) { - - String interString = i18n.get(DrawingToolLayer.class, "QUERY_HEADER", "What would you like to do?"); - - box = PaletteHelper.createVerticalPanel(interString); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - box.setLayout(gridbag); - - jcb = new JComboBox(getActions()); - c.gridx = GridBagConstraints.REMAINDER; - gridbag.setConstraints(jcb, c); - box.add(jcb); - - JPanel goPanel = new JPanel(); - gridbag.setConstraints(goPanel, c); - box.add(goPanel); - - interString = i18n.get(DrawingToolLayer.class, "OK", "OK"); - JButton button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "OK", I18n.TOOLTIP, "Do action and dismiss window."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - doIt(); - hidePalette(); - } - }); - goPanel.add(button); - - interString = i18n.get(DrawingToolLayer.class, "Apply", "Apply"); - button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "Apply", I18n.TOOLTIP, "Do action and leave window up."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - doIt(); - } - }); - goPanel.add(button); - - interString = i18n.get(DrawingToolLayer.class, "Cancel", "Cancel"); - button = new JButton(interString); - interString = i18n.get(DrawingToolLayer.class, "Cancel", I18n.TOOLTIP, "Do nothing and dismiss window."); - button.setToolTipText(interString); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - hidePalette(); - } - }); - goPanel.add(button); - - } - - return box; - } - - protected void doIt() { - if (jcb != null) { - ((javax.swing.Action) jcb.getSelectedItem()).actionPerformed(null); - } - } - - protected Vector actions; - - /** - * You can override this class if you want to provide more, fewer or - * different actions to the user. - * - * @return Vector of Actions - */ - protected Vector getActions() { - if (actions == null) { - actions = new Vector(); - - actions.add(new AbstractAction() { - public void actionPerformed(ActionEvent e) { - OMGraphicList list = getOMGraphics(); - Object obj = list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - DbfTableModel dbf = null; - - if (obj instanceof DbfTableModel) { - dbf = (DbfTableModel) obj; - } else if (dbfFactory != null) { - dbf = dbfFactory.createDbf(list); - } - - if (dbf == null) { - dbf = new DbfTableModel(0); - int numGraphics = list.size(); - for (int i = 0; i < numGraphics; i++) { - dbf.addBlankRecord(); - } - list.putAttribute(ShapeConstants.DBF_ATTRIBUTE, dbf); - } - dbf.setExitOnClose(false); - dbf.setWritable(true); - dbf.showGUI(getName() + " Attributes", DbfTableModel.MODIFY_COLUMN_MASK - | DbfTableModel.MODIFY_ROW_MASK | DbfTableModel.SAVE_MASK | DbfTableModel.DONE_MASK); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "UPDATE_ATTRIBUTES", "Update feature attributes"); - } - }); - - actions.add(new AbstractAction() { - public void actionPerformed(ActionEvent e) { - saveOMGraphics(getProjection()); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "SAVE_MAP", "Save map"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - OMGraphicList list = new OMGraphicList(getOMGraphics()); - if (list != null && !list.isEmpty()) { - Object obj = list.getAttribute(ShapeConstants.DBF_ATTRIBUTE); - - if (!(obj instanceof DbfTableModel) && dbfFactory != null) { - // If there isn't a dbf table model, create one if - // the DbfTableModelFactory has been configured. - dbfFactory.createDbf(list); - } - - String title = i18n.get(DrawingToolLayer.class, "SHAPE_SAVE_MAP_TITLE", "Save Shape File"); - String saveFilePath = FileUtils.getFilePathToSaveFromUser(title); - - if (saveFilePath != null) { - setFileName(saveFilePath); - } - - EsriShapeExport ese = new EsriShapeExport(list, getProjection(), saveFilePath); - ese.setTransform(coordTransform); - ese.export(); - - } else { - String message = i18n.get(DrawingToolLayer.class, "SHAPE_ERROR_MESSAGE", - "There's nothing on the map for this layer to save."); - fireRequestMessage(message); - } - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "SHAPE_SAVE_MAP", "Save map as Shape file(s)"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - setOMGraphics(load()); - doPrepare(); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "RELOAD", "Re-load map from file"); - } - }); - - actions.add(new AbstractAction() { - - public void actionPerformed(ActionEvent e) { - Inspector inspector = new Inspector(); - inspector.inspectPropertyConsumer(DrawingToolLayer.this); - } - - public String toString() { - return i18n.get(DrawingToolLayer.class, "PREFERENCES", "Change preferences"); - } - }); - } - return actions; - } - - /** - * Get the current OMGraphicList and save it out to the file named in this - * class. If that's null, the user will be asked for one. - * - */ - public void saveOMGraphics(Projection proj) { - if (fileName == null) { - fileName = FileUtils.getFilePathToSaveFromUser( - i18n.get(DrawingToolLayer.class, "CHOOSE_SAVE", "Choose file to use to save layer:")); - } - - if (fileName != null) { - OMGraphicList list = getOMGraphics(); - - if (fileName.toLowerCase().endsWith(".shp")) { - EsriShapeExport ese = new EsriShapeExport(list, proj, fileName); - ese.setTransform(getCoordTransform()); - ese.export(); - } else { - - if (list != null) { - try { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(list); - oos.close(); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } - - /** - * Load the data from the file set in this layer. - * - * @return OMGraphicList loaded from fileName. - */ - public OMGraphicList load() { - OMGraphicList graphicList = new OMGraphicList(); - boolean err = false; - - if (fileName != null) { - try { - OMGraphicList list = null; - URL url = PropUtils.getResourceOrFileOrURL(fileName); - if (url != null) { - if (fileName.endsWith(".shp")) { - list = EsriShapeExport.read(url, drawingAttributes, getCoordTransform()); - // Now that we've established that we are working (or - // want to work with) with a - // shape file, create a dbfFactory for the layer to help - // out with editing. - dbfFactory = new DbfTableModelFactory(); - } else { - ObjectInputStream ois = new ObjectInputStream(url.openStream()); - list = (OMGraphicList) ois.readObject(); - ois.close(); - } - } - - if (list != null) { - graphicList.addAll(list); - graphicList.setAttributes(list.getAttributes()); - } - } catch (FileNotFoundException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (StreamCorruptedException sce) { - sce.printStackTrace(); - fireRequestMessage(i18n.get(DrawingToolLayer.class, "LOAD_ERROR", - "The file doesn't appear to be a valid map file")); - err = true; - } catch (IOException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (ClassNotFoundException e) { - if (DTL_DEBUG) { - e.printStackTrace(); - } - err = true; - } catch (ClassCastException cce) { - if (DTL_DEBUG) { - cce.printStackTrace(); - } - err = true; - } - } - // Something went wrong, we don't want to overwrite something - // that might potentially be something else if a save is - // called for later. - if (err) { - fileName = null; - } - return graphicList; - } - - /** - * A flag to provide a tooltip over OMGraphics to click to edit. - */ - public void setShowHints(boolean show) { - showHints = show; - } - - public boolean getShowHints() { - return showHints; - } - - /** - * Query that an OMGraphic can be highlighted when the mouse moves over it. - * If the answer is true, then highlight with this OMGraphics will be - * called, in addition to getInfoText() and getToolTipTextFor() - */ - public boolean isHighlightable(OMGraphic omg) { - return showHints; - } - - /** - * Query that an OMGraphic is selectable. - */ - public boolean isSelectable(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - return (shouldEdit(omg) && dt != null && dt.canEdit(omg.getClass())); - } - - String editInstruction = i18n.get(DrawingToolLayer.class, "CLICK_TO_EDIT", "Click to edit."); - - /** - * Query for what text should be placed over the information bar when the - * mouse is over a particular OMGraphic. - */ - public String getInfoText(OMGraphic omg) { - DrawingTool dt = getDrawingTool(); - if (dt != null && dt.canEdit(omg.getClass())) { - return editInstruction; - } else { - return null; - } - } - - /** - * Query for what tooltip to display for an OMGraphic when the mouse is over - * it. - */ - public String getToolTipTextFor(OMGraphic omgr) { - OMDrawingTool dt = getDrawingTool(); - if (shouldEdit(omgr) && dt.canEdit(omgr.getClass()) && !dt.isActivated()) { - return editInstruction; - } else { - return null; - } - } - - /** - * GestureResponsePolicy method. - */ - public void select(OMGraphicList omgl) { - super.select(omgl); - if (omgl != null && !omgl.isEmpty()) { - if (omgl.size() == 1) { - edit(omgl.getOMGraphicAt(0)); - } else { - edit(omgl); - } - } - } - - public void edit(OMGraphic omg) { - - OMDrawingTool dt = getDrawingTool(); - - if (dt != null && dt.canEdit(omg.getClass())) { - - // if (dt.isEditing(omg)) { - // dt.deselect(omg); - // return; - // } - - dt.resetBehaviorMask(); - - MapMouseMode omdtmm = dt.getMouseMode(); - if (!omdtmm.isVisible()) { - dt.setMask(OMDrawingTool.PASSIVE_MOUSE_EVENT_BEHAVIOR_MASK); - } - - MapMouseInterpreter mmi = (MapMouseInterpreter) getMapMouseListener(); - - MouseEvent mevent = null; - if (mmi != null) { - mevent = mmi.getCurrentMouseEvent(); - } - - if (omg.isSelected()) { - omg.deselect(); - } - - if (dt.select(omg, this, mevent)) { - // OK, means we're editing - let's lock up the - // MouseMode - if (DTL_DEBUG) { - Debug.output("DTL: starting edit of OMGraphic..."); - } - - // Check to see if the DrawingToolMouseMode wants to - // be invisible. If it does, ask the current - // active MouseMode to be the proxy for it... - if (!omdtmm.isVisible() && mevent instanceof MapMouseEvent) { - MapMouseMode mmm = ((MapMouseEvent) mevent).getMapMouseMode(); - if (mmm.actAsProxyFor(omdtmm, - MapMouseSupport.PROXY_DISTRIB_MOUSE_MOVED & MapMouseSupport.PROXY_DISTRIB_MOUSE_DRAGGED)) { - if (DTL_DEBUG) { - Debug.output("DTL: Setting " + mmm.getID() + " as proxy for drawing tool"); - } - setProxyMouseMode(mmm); - } else { - // WHOA, couldn't get proxy lock - bail - if (DTL_DEBUG) { - Debug.output("DTL: couldn't get proxy lock on " + mmm.getID() - + " deactivating internal drawing tool"); - } - dt.deactivate(); - } - } else { - if (DTL_DEBUG) { - Debug.output("DTL: MouseMode wants to be visible(" + (omdtmm.isVisible()) - + "), or MouseEvent is not a MapMouseEvent(" + !(mevent instanceof MapMouseEvent) - + ")"); - } - } - } else { - if (DTL_DEBUG) { - Debug.output("DTL.edit: dt.select returns false, avoiding modification over " - + omg.getClass().getName()); - } - } - } - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String serializedFile) { - this.fileName = serializedFile; - } - - public DbfTableModelFactory getDbfFactory() { - return dbfFactory; - } - - public void setDbfFactory(DbfTableModelFactory dbfFactory) { - this.dbfFactory = dbfFactory; - } - - public DrawingAttributes getDrawingAttributes() { - return drawingAttributes; - } - - public void setDrawingAttributes(DrawingAttributes drawingAttributes) { - this.drawingAttributes = drawingAttributes; - } -} diff --git a/src/openmap/com/bbn/openmap/layer/EarthquakeLayer.java b/src/openmap/com/bbn/openmap/layer/EarthquakeLayer.java deleted file mode 100644 index 9e798aee9..000000000 --- a/src/openmap/com/bbn/openmap/layer/EarthquakeLayer.java +++ /dev/null @@ -1,643 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/EarthquakeLayer.java,v $ -// $RCSfile: EarthquakeLayer.java,v $ -// $Revision: 1.8 $ -// $Date: 2007/04/24 19:53:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.Socket; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; - -import javax.swing.JButton; -import javax.swing.JPanel; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; -import com.bbn.openmap.util.PropUtils; - -/** - * Get data about recent earthquakes from the USGS finger sites and display it. - *

- * Debugging information is printed when the OpenMap Viewer is launch with - * -Ddebug.earthquake flag. - *

- * - *

- * 
- * 
- *   # Properties for the Earthquake Layer
- *   earthquake.sites=<finger site> <finger site> ...
- *   # in seconds
- *   earthquake.queryinterval=300
- * 
- * 
- * 
- * - * NOTE: I'm not sure this layer works anymore, probably hasn't for some time - * since the finger sites no longer provide data AFAIK. Leaving this layer in - * the package as another example. - */ -public class EarthquakeLayer - extends OMGraphicHandlerLayer - implements MapMouseListener { - - public final static transient String fingerSitesProperty = "sites"; - public final static transient String queryIntervalProperty = "queryInterval"; - - /** - * Sites to finger user the user `quake'. - */ - protected String fingerSites[] = { - "scec.gps.caltech.edu", - "geophys.washington.edu", - "giseis.alaska.edu", - "mbmgsun.mtech.edu", - "quake.eas.slu.edu" - }; - - // Old sites - // "gldfs.cr.usgs.gov", - // "andreas.wr.usgs.gov", - // "seismo.unr.edu", - // "eqinfo.seis.utah.edu", - // "sisyphus.idbsu.edu", - // "info.seismo.usbr.gov", - // "vtso.geol.vt.edu", - // "tako.wr.usgs.gov", - // "ldeo.columbia.edu" - - /** - * Sites that are actively being queried. - */ - protected boolean activeSites[] = new boolean[fingerSites.length]; - - /** Default to 5 minutes. */ - private long fetchIntervalMillis = 300 * 1000; - - // lat-lon data of the earthquakes - protected float llData[] = new float[0]; - - // floating information about the earthquakes - protected String infoData[] = new String[0]; - // floating information about the earthquakes - protected String drillData[] = new String[0]; - - private long lastDataFetchTime = 0; - protected Color lineColor = Color.red; - protected boolean showingInfoLine = false; - - /** The layer GUI. */ - protected JPanel gui = null; - - /** - * Construct an EarthquakeLayer. - */ - public EarthquakeLayer() { - activeSites[0] = true; - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - } - - /** - * Fetch data from finger sites, if needed, generate the OMGraphics with the - * current projection regardless. - */ - public synchronized OMGraphicList prepare() { - if (needToRefetchData()) { - parseData(getEarthquakeData()); - } - return generateGraphics(); - } - - /** - * Fetches data if it hasn't been fetched in a while. - */ - protected boolean needToRefetchData() { - long now = System.currentTimeMillis(); - long last = lastDataFetchTime; - - if ((last + fetchIntervalMillis) < now) { - lastDataFetchTime = now; - return true; - } - return false; - } - - /** - * Create the graphics. - */ - protected OMGraphicList generateGraphics() { - OMGraphicList omgraphics = new OMGraphicList(); - OMPoint circ; - OMText text; - - int circle_r = 2; - int circle_h = 5; - - for (int i = 0, j = 0; i < llData.length; i += 2, j++) { - - // grouping - OMGraphicList group = new OMGraphicList(2); - - // XY-Circle at LatLonPoint - circ = new OMPoint(llData[i], llData[i + 1], circle_r); - circ.setOval(true); - circ.setFillPaint(lineColor); - group.add(circ); - - // Info - text = - new OMText(llData[i], llData[i + 1], 0, circle_h + 10, infoData[j], java.awt.Font.decode("SansSerif"), - OMText.JUSTIFY_CENTER); - text.setLinePaint(lineColor); - group.add(text); - - group.putAttribute(OMGraphic.APP_OBJECT, new Integer(j));// remember - // index - omgraphics.add(group); - } - - omgraphics.generate(getProjection(), false); - return omgraphics; - } - - /** - * Parse the finger site data. - * - * @param data Vector - */ - protected void parseData(Vector data) { - int nLines = data.size(); - llData = new float[2 * nLines]; - infoData = new String[nLines]; - drillData = new String[nLines]; - - for (int i = 0, j = 0, k = 0; i < nLines; i++) { - String line = (String) data.elementAt(i); - - // Read a line of input and break it down - StringTokenizer tokens = new StringTokenizer(line); - String sdate = tokens.nextToken(); - String stime = tokens.nextToken(); - String slat = tokens.nextToken(); - String slon = tokens.nextToken(); - if (slon.startsWith("NWSE"))// handle ` ' in LatLon data - slon = tokens.nextToken(); - String sdep = tokens.nextToken(); - if (sdep.startsWith("NWSE"))// handle ` ' in LatLon data - sdep = tokens.nextToken(); - String smag = tokens.nextToken(); - String q = tokens.nextToken(); - String scomment = tokens.nextToken("\r\n"); - if (q.length() > 1) { - scomment = q + " " + scomment; - } - - infoData[j] = smag; - drillData[j++] = sdate + " " + stime + " (UTC) " + slat + " " + slon + " " + smag + " " + scomment; - - // Remove NESW from lat and lon before converting to float - int west = slon.indexOf("W"); - int south = slat.indexOf("S"); - - if (west >= 0) - slon = slon.replace('W', '\0'); - else - slon = slon.replace('E', '\0'); - if (south >= 0) - slat = slat.replace('S', '\0'); - else - slat = slat.replace('N', '\0'); - slon = slon.trim(); - slat = slat.trim(); - - float flat = 0, flon = 0; - try { - flat = new Float(slat).floatValue(); - flon = new Float(slon).floatValue(); - } catch (NumberFormatException e) { - Debug.error("EarthquakeLayer.parseData(): " + e + " line: " + line); - } - - // replace West and South demarcations with minus sign - if (south >= 0) - flat = -flat; - if (west >= 0) - flon = -flon; - - llData[k++] = flat; - llData[k++] = flon; - } - } - - /** - * Get the earthquake data from the USGS. Should be called in a SwingWorker - * thread, or you will freeze the application. - * - * @return Vector containing information from the websites. - */ - protected Vector getEarthquakeData() { - Vector linesOfData = new Vector(); - Socket quakefinger = null; - PrintWriter output = null; - BufferedReader input = null; - String line; - - for (int i = 0; i < activeSites.length; i++) { - // skip sites which aren't on the active list - if (!activeSites[i]) - continue; - - try { - if (Debug.debugging("earthquake")) { - Debug.output("Opening socket connection to " + fingerSites[i]); - } - quakefinger = new Socket(fingerSites[i], 79);// open - // connection - // to - // finger - // port - quakefinger.setSoTimeout(120 * 1000);// 2 minute - // timeout - output = new PrintWriter(new OutputStreamWriter(quakefinger.getOutputStream()), true); - input = new BufferedReader(new InputStreamReader(quakefinger.getInputStream()), 1); - output.println("/W quake");// use `/W' flag for long - // output - } catch (IOException e) { - Debug.error("EarthquakeLayer.getEarthquakeData(): " + "can't open or write to socket: " + e); - continue; - } - - try { - // add data lines to list - while ((line = input.readLine()) != null) { - if (Debug.debugging("earthquake")) { - Debug.output("EarthquakeLayer.getEarthQuakeData(): " + line); - } - if (line.length() == 0) - continue; - if (!Character.isDigit(line.charAt(0))) - continue; - - line = hackY2K(line); - if (line == null) - continue; - linesOfData.addElement(line); - } - } catch (IOException e) { - Debug.error("EarthquakeLayer.getEarthquakeData(): " + "can't read from the socket: " + e); - } - - try { - if (quakefinger != null) { - quakefinger.close(); - } - } catch (IOException e) { - Debug.error("EarthquakeLayer.getEarthquakeData(): " + "error closing socket: " + e); - } - } - - // int nQuakes = linesOfData.size(); - // for (int i=0; i 70) { - date = "19"; - } else { - date = "20"; - } - } else if (year.length() != 4) { - Debug.error("EarthquakeLayer: unparsable year: " + year); - return null; - } - - date = date + year + "/" + month + "/" + day; - return date; - } - - /** - * Gets the gui controls associated with the layer. - * - * @return Component - */ - public Component getGUI() { - JPanel p; - if (gui == null) { - gui = PaletteHelper.createVerticalPanel("Earthquakes"); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints constraints = new GridBagConstraints(); - gui.setLayout(gridbag); - constraints.fill = GridBagConstraints.HORIZONTAL; // fill - // horizontally - constraints.gridwidth = GridBagConstraints.REMAINDER; // another - // row - constraints.anchor = GridBagConstraints.EAST; // tack to - // the left - // edge - - ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - int index = Integer.parseInt(e.getActionCommand(), 10); - activeSites[index] = !activeSites[index]; - } - }; - p = PaletteHelper.createCheckbox("Sites", fingerSites, activeSites, al); - gridbag.setConstraints(p, constraints); - gui.add(p); - - JButton b = new JButton("Query Now"); - b.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - // force refetch of data - lastDataFetchTime = 0; - doPrepare(); - } - }); - gridbag.setConstraints(p, constraints); - gui.add(b); - - } - return gui; - } - - /** - * Returns the MapMouseListener object that handles the mouse events. - * - * @return the MapMouseListener for the layer, or null if none - */ - public MapMouseListener getMapMouseListener() { - return this; - } - - // ---------------------------------------------------------------- - // MapMouseListener interface methods - // ---------------------------------------------------------------- - - /** - * Return a list of the modes that are interesting to the MapMouseListener. - * The source MouseEvents will only get sent to the MapMouseListener if the - * mode is set to one that the listener is interested in. Layers interested - * in receiving events should register for receiving events in "select" - * mode: - *
-     * return new String[] { SelectMouseMode.modeID };
-     * 
- * - * - * @return String[] of modeID's - * @see com.bbn.openmap.event.NavMouseMode#modeID - * @see com.bbn.openmap.event.SelectMouseMode#modeID - * @see com.bbn.openmap.event.NullMouseMode#modeID - */ - public String[] getMouseModeServiceList() { - return new String[] { - com.bbn.openmap.event.SelectMouseMode.modeID - }; - } - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e) { - return false; - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e) { - OMGraphicList omgraphics = getList(); - if (omgraphics != null && drillData != null) { - OMGraphic obj = omgraphics.findClosest(e.getX(), e.getY(), 4); - if (obj != null) { - int id = ((Integer) obj.getAttribute(OMGraphic.APP_OBJECT)).intValue(); - fireRequestInfoLine(drillData[id]); - showingInfoLine = true; - return true; - } - } - return false; - } - - /** - * Invoked when the mouse has been clicked on a component. The listener will - * receive this event if it successfully processed - * mousePressed(), or if no other listener processes the event. - * If the listener successfully processes mouseClicked(), then it will - * receive the next mouseClicked() notifications that have a click count - * greater than one. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - } - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * The listener will receive these events if it successfully processes - * mousePressed(), or if no other listener processes the event. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e) { - // clean up display - if (showingInfoLine) { - showingInfoLine = false; - fireRequestInfoLine(""); - } - return false; - } - - /** - * Handle a mouse cursor moving without the button being pressed. This event - * is intended to tell the listener that there was a mouse movement, but - * that the event was consumed by another layer. This will allow a mouse - * listener to clean up actions that might have happened because of another - * motion event response. - */ - public void mouseMoved() { - } - - // ---------------------------------------------------------------- - // PropertyConsumer Interface - // ---------------------------------------------------------------- - - /** - * Set the properties of the EarthquakeLayer. - * - * @param prefix String - * @param props Properties - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - // list of sites - String sites = props.getProperty(prefix + fingerSitesProperty); - if (sites != null) { - Vector v = new Vector(); - String str; - StringTokenizer tok = new StringTokenizer(sites); - while (tok.hasMoreTokens()) { - str = tok.nextToken(); - v.addElement(str); - } - int len = v.size(); - fingerSites = new String[len]; - activeSites = new boolean[len]; - activeSites[0] = true; - for (int i = 0; i < len; i++) { - fingerSites[i] = (String) v.elementAt(i); - } - } - - fetchIntervalMillis = PropUtils.intFromProperties(props, prefix + queryIntervalProperty, 300) * 1000; - } - - /** - * Get the associated properties object. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - return getProperties(propertyPrefix, props); - } - - /** - * Get the associated properties object. This method creates a Properties - * object if necessary and fills it with the relevant data for this layer. - * Relevant properties for EarthquakeLayers are the sites to retrieve earth - * quake data from, and the interval in milliseconds (see class - * description.) - */ - public Properties getProperties(String prefix, Properties props) { - props = super.getProperties(props); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - StringBuffer sitesToFinger = new StringBuffer(""); - for (int i = 0; i < fingerSites.length; ++i) { - sitesToFinger.append(fingerSites[i]); - sitesToFinger.append(" "); - } - - sitesToFinger.deleteCharAt(sitesToFinger.length() - 1); - - props.put(prefix + fingerSitesProperty, sitesToFinger.toString()); - props.put(prefix + queryIntervalProperty, Long.toString(fetchIntervalMillis)); - return props; - } - - /** - * Supplies the propertiesInfo object associated with this EarthquakeLayer - * object. Contains the human readable descriptions of the properties and - * the initPropertiesProperty (see Inspector class.) - */ - public Properties getPropertyInfo(Properties info) { - info = super.getPropertyInfo(info); - - info.put(fingerSitesProperty, "WWW sites to finger"); - info.put(queryIntervalProperty, "Query interval in seconds"); - return info; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/LabelLayer.java b/src/openmap/com/bbn/openmap/layer/LabelLayer.java deleted file mode 100644 index 162015088..000000000 --- a/src/openmap/com/bbn/openmap/layer/LabelLayer.java +++ /dev/null @@ -1,391 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/LabelLayer.java,v $ -// $RCSfile: LabelLayer.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:08 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.util.Properties; - -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.Taskable; - -/** - * Layer that displays a label. This Layer is a Taskable - * (ActionListener) object so that it can be prompted by a - * javax.swing.Timer object. This layer understands the following - * properties: - *

- * 
- *   # display font as a Java font string
- *   label.font=SansSerif-Bold
- *   # like XWindows geometry: [+-]X[+-]Y, `+' indicates relative to
- *   # left edge or top edges, `-' indicates relative to right or bottom
- *   # edges, XX is x coordinate, YY is y coordinate
- *   label.geometry=+20-30
- *   # background rectangle color (ARGB)
- *   label.color.bg=ffb3b3b3
- *   # foreground text color (ARGB)
- *   label.color.fg=ff000000
- *   # date format (using java.text.SimpleDateFormat patterns)
- *   label.text=The Graph
- *   
- * 
- *

- * In addition to the previous properties, you can get this layer to - * work with the OpenMap viewer by adding/editing the additional - * properties in your openmap.properties file: - *

- * 
- *   # layers
- *   openmap.layers=label ...
- *   # class
- *   label.class=com.bbn.openmap.layer.LabelLayer
- *   # name
- *   label.prettyName=Label Layer
- * 
- * 
- *

NOTE: the color properties do not support alpha value if - * running on JDK 1.1... - */ -public class LabelLayer extends OMGraphicHandlerLayer implements Taskable, - MapMouseListener { - - // property keys - public final static transient String fontProperty = "font"; - public final static transient String fgColorProperty = "color.fg"; - public final static transient String bgColorProperty = "color.bg"; - public final static transient String geometryProperty = "geometry"; - public final static transient String labelProperty = "text"; - - // properties - protected String fontString = "SansSerif"; - protected Font font = Font.decode(fontString); - protected int fgColorValue = 0x000000;//black - protected Color fgColor = new Color(fgColorValue); - protected int bgColorValue = 0xffffff;//white - protected Color bgColor = new Color(bgColorValue); - protected String geometryString = "+20+20"; - protected String labelText = ""; - - protected OMText text; - - protected int xpos = 10; - protected int ypos = 10; - protected String xgrav = geometryString.substring(0, 1); - protected String ygrav = geometryString.substring(3, 4); - - private int dragX; - private int dragY; - private boolean dragging = false; - - /** - * Construct the LabelLayer. - */ - public LabelLayer() { - text = new OMText(0, 0, "uninitialized", font, OMText.JUSTIFY_RIGHT); - text.setLinePaint(fgColor); - text.setFillPaint(bgColor); - } - - /** - * Sets the properties for the Layer. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - prefix = com.bbn.openmap.util.PropUtils.getScopedPropertyPrefix(prefix); - - fontString = props.getProperty(prefix + fontProperty, fontString); - - fgColor = ColorFactory.parseColorFromProperties(props, prefix - + fgColorProperty, Integer.toString(fgColorValue)); - - bgColor = ColorFactory.parseColorFromProperties(props, prefix - + bgColorProperty, Integer.toString(bgColorValue)); - - geometryString = props.getProperty(prefix + geometryProperty, - geometryString); - parseGeometryString(); - - labelText = props.getProperty(prefix + labelProperty, labelText); - - // reset the property values - font = Font.decode(fontString); - text.setFont(font); - text.setLinePaint(fgColor); - text.setFillPaint(bgColor); - } - - /** Parse X-like geometry string. */ - protected void parseGeometryString() { - int i = 0; - byte[] bytes = geometryString.getBytes(); - xgrav = new String(bytes, 0, 1); - for (i = 2; i < bytes.length; i++) { - if ((bytes[i] == '-') || (bytes[i] == '+')) - break; - } - if (i == bytes.length) - return; - ygrav = (bytes[i] == '-') ? "-" : "+"; - xpos = Integer.parseInt(new String(bytes, 1, i - 1)); - ++i; - ypos = Integer.parseInt(new String(bytes, i, bytes.length - i)); - } - - /** Position the text graphic */ - protected void positionText(int w, int h) { - int xoff, yoff, justify; - if (xgrav.equals("+")) { - xoff = xpos; - justify = OMText.JUSTIFY_LEFT; - } else { - xoff = w - xpos; - justify = OMText.JUSTIFY_RIGHT; - } - if (ygrav.equals("+")) { - yoff = ypos; - } else { - yoff = h - ypos; - } - text.setX(xoff); - text.setY(yoff); - text.setJustify(justify); - } - - /** - * Set the text to display - * - * @param s String - */ - public void setLabelText(String s) { - labelText = s; - } - - /** - * Get the String to display - * - * @return String - */ - public String getLabelText() { - return labelText; - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(Graphics g) { - Projection p = getProjection(); - - if (p == null) - return; - - if (Debug.debugging("labellayer")) { - System.out.println("labelLayer.paint(): " + labelText); - } - - positionText(p.getWidth(), p.getHeight()); - text.setData(labelText); - text.generate(p);//to get bounds - - // render graphics - text.render(g); - } - - //---------------------------------------------------------------------- - // Taskable Interface - //---------------------------------------------------------------------- - - /** - * Invoked by a javax.swing.Timer. - * - * @param e ActionEvent - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - if (Debug.debugging("labellayer")) { - System.out.println("LabelLayer.actionPerformed()"); - } - - repaint(); - } - - //---------------------------------------------------------------------- - // MapMouseListener Interface - //---------------------------------------------------------------------- - - /** - * Returns the MapMouseListener object that handles the mouse - * events. - * - * @return MapMouseListener this - */ - public MapMouseListener getMapMouseListener() { - return this; - } - - /** - * Return a list of the modes that are interesting to the - * MapMouseListener. - * - * @return String[] { SelectMouseMode.modeID } - */ - public String[] getMouseModeServiceList() { - return new String[] { SelectMouseMode.modeID }; - } - - // Mouse Listener events - //////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mousePressed(MouseEvent e) { - int x = e.getX(); - int y = e.getY(); - if (text.distance(x, y) <= 0f) { - dragging = true; - dragX = x; - dragY = y; - return true; - } - return false; // did not handle the event - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - dragging = false; - return false; - } - - /** - * Invoked when the mouse has been clicked on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseClicked(MouseEvent e) { - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) {} - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) {} - - // Mouse Motion Listener events - /////////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then - * dragged. The listener will receive these events if it - * - * @param e MouseEvent - * @return false - */ - public boolean mouseDragged(MouseEvent e) { - Projection proj = getProjection(); - int w = proj.getWidth(); - int h = proj.getHeight(); - int x = e.getX(); - int y = e.getY(); - - // limit coordinates - if (x < 0) - x = 0; - if (y < 0) - y = 0; - if (x > w) - x = w; - if (y > h) - y = h; - - // calculate deltas - int dx = x - dragX; - int dy = y - dragY; - - if (dragging) { - // reset dragging parms - dragX = x; - dragY = y; - // reset graphics positions - text.setX(text.getX() + dx); - text.setY(text.getY() + dy); - repaint(); - return true; - } - return false; - } - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons down). - * - * @param e MouseEvent - * @return false - */ - public boolean mouseMoved(MouseEvent e) { - return false; - } - - /** - * Handle a mouse cursor moving without the button being pressed. - * Another layer has consumed the event. - */ - public void mouseMoved() {} - - public int getSleepHint() { - return 1000000;//update every 1000 seconds - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/OMGraphicHandlerLayer.java b/src/openmap/com/bbn/openmap/layer/OMGraphicHandlerLayer.java deleted file mode 100644 index fcc0b8019..000000000 --- a/src/openmap/com/bbn/openmap/layer/OMGraphicHandlerLayer.java +++ /dev/null @@ -1,1533 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/OMGraphicHandlerLayer.java,v $ -// $RCSfile: OMGraphicHandlerLayer.java,v $ -// $Revision: 1.33 $ -// $Date: 2007/04/24 19:53:44 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Component; -import java.awt.Composite; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Shape; -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.layer.policy.ProjectionChangePolicy; -import com.bbn.openmap.layer.policy.RenderPolicy; -import com.bbn.openmap.layer.policy.StandardPCPolicy; -import com.bbn.openmap.layer.policy.StandardRenderPolicy; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.FilterSupport; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicHandler; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.event.GestureResponsePolicy; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.omGraphics.event.StandardMapMouseInterpreter; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.icon.IconPart; -import com.bbn.openmap.tools.icon.OMIconFactory; -import com.bbn.openmap.tools.icon.OpenMapAppPartCollection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.ISwingWorker; -import com.bbn.openmap.util.PooledSwingWorker; -import com.bbn.openmap.util.PropUtils; - -/** - * The OMGraphicHandlerLayer is a layer that provides OMGraphicHandler support. - * With this support, the OMGraphicHandlerLayer can accept OMAction instructions - * for managing OMGraphics, and can perform display filtering as supported by - * the FilterSupport object. - *

- * - * When extending this class for a simple layer, they only method you need to - * override is the prepare() method. This is a good class to use to start - * writing your own layers. Start with overriding the prepare() method, having - * it return an OMGraphicList containing OMGraphics on the map that are - * appropriate for the current projection. - *

- * - * The OMGraphicHandlerLayer already has an OMGraphicList variable, so if you - * extend this class you don't have to manage another one. You can add your - * OMGraphics to the list provided with getList(). If you create a list of - * OMGraphics that is reused and simply re-projected when the projection - * changes, do nothing - that's what happens anyway based on the default - * ProjectionChangePolicy set for the layer (StandardPCPolicy). You can either - * create an OMGraphicList in the constructor and set it by calling - * setList(OMGraphicList), or you can test for a null OMGraphicList returned - * from getList() in prepare() and create one if it needs to be. If the list - * isn't null, make sure you still call generate on it. The advantage of waiting - * to create the list in prepare is that the processing time to create the - * OMGraphics is delayed until the layer is added to the map. If you create - * OMGraphics in the constructor, you delay the entire program (maybe startup of - * the map!) while the OMGraphics are created. - *

- * - * If you let prepare() create a new OMGraphicList based on the new projection, - * then make sure the ProjectionChangePolicy for the layer is set to a - * com.bbn.openmap.layer.policy.ResetListPCPolicy, or at least clear out the old - * graphics at some point before adding new OMGraphics to the list in that - * method. You just have to do one, not both, of those things. If you are - * managing a lot of OMGraphics and do not null out the list, you may see your - * layer appear to lag behind the projection changes. That's because another - * layer with less work to do finishes and calls repaint, and since your list is - * still set with OMGraphics ready for the old projection, it will just draw - * what it had, and then draw again when it has finished working. Nulling out - * the list will prevent your layer from drawing anything on the new projection - * until it is ready. - *

- * - * The OMGraphicHandlerLayer has support built in for launching a SwingWorker to - * do work for you in a separate thread. This behavior is controlled by the - * ProjectionChangePolicy that is set for the layer. Both the StandardPCPolicy - * and ListResetPCPolicy launch threads by calling doPrepare() on this layer. - * The StandardPCPolicy only calls this if the number of OMGraphics on its list - * is greater than some cutoff value. - *

- * - * useLayerWorker variable is true (default), then doPrepare() will be called - * when a new ProjectionEvent is received in the projectionChanged method. This - * will cause prepare() to be called in a separate thread. You can use prepare() - * to create OMGraphics, the projection will have been set in the layer and is - * available via getProjection(). You should generate() the OMGraphics in - * prepare. NOTE: You can override the projectionChanged() method to - * create/manage OMGraphics any way you want. The SwingWorker only gets launched - * if doPrepare() gets called. - *

- * - * MouseEvents are not handled by a MapMouseInterpreter, with the layer being - * the GestureResponsePolicy object dictating how events are responded to. The - * interpreter does the work of fielding MapMouseEvents, figuring out if they - * concern an OMGraphic, and asking the policy what it should do in certain - * situations, including providing tooltips, information, or opportunities to - * edit OMGraphics. The mouseModes property can be set to the MapMouseMode IDs - * that the interpreter should respond to. - *

- * - * For OMGraphicHandlerLayers, there are several properties that can be set that - * dictate important behavior: - * - *

- *
- *
- *
- *     layer.projectionChangePolicy=pcp
- *     layer.pcp.class=com.bbn.openmap.layer.policy.StandardPCPolicy
- * 
- *     layer.renderPolicy=srp
- *     layer.srp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy
- *     # or
- *     layer.renderPolicy=ta
- *     layer.ta.class=com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy
- *     layer.ta.renderingHints=KEY_TEXT_ANTIALIASING
- *     layer.ta.KEY_TEXT_ANTIALIASING=VALUE_TEXT_ANTIALIAS_ON
- * 
- *     layer.mouseModes=Gestures
- *     layer.consumeEvents=true
- *
- *
- * 
- */ -public class OMGraphicHandlerLayer extends Layer implements GestureResponsePolicy, OMGraphicHandler { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.OMGraphicHandlerLayer"); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * The property that can be set for the ProjectionChangePolicy. This - * property should be set with a scoping marker name used to define a policy - * class and any other properties that the policy should use. - * "projectionChangePolicy" - * - * @see com.bbn.openmap.layer.policy.ProjectionChangePolicy - * @see com.bbn.openmap.layer.policy.StandardPCPolicy - * @see com.bbn.openmap.layer.policy.ListResetPCPolicy - */ - public final static String ProjectionChangePolicyProperty = "projectionChangePolicy"; - /** - * The property that can be set for the RenderPolicy. This property should - * be set with a marker name used to define a policy class and any other - * properties that the policy should use. "renderPolicy" - * - * @see com.bbn.openmap.layer.policy.StandardRenderPolicy - * @see com.bbn.openmap.layer.policy.BufferedImageRenderPolicy - * @see com.bbn.openmap.layer.policy.RenderingHintsRenderPolicy - */ - public final static String RenderPolicyProperty = "renderPolicy"; - - /** - * The property that can be set to tell the layer which mouse modes to - * listen to. The property should be a space-separated list of mouse mode - * IDs, which can be specified for a MapMouseMode in the properties file or, - * if none is specified, the default ID hard-coded into the MapMouseMode. - * "mouseModes" - */ - public final static String MouseModesProperty = "mouseModes"; - - /** - * The property that can be set to tell the layer to consume mouse events. - * The maim reason not to do this is in case you have OMGraphics that you - * are moving, and you need other layers to respond to let you know when you - * are over the place you think you need to be. - */ - public final static String ConsumeEventsProperty = "consumeEvents"; - - /** - * The property to tell the layer how transparent it is. 0 is totally clear, - * 1f is opaque. - */ - public final static String TransparencyProperty = "transparency"; - /** - * The property to tell the layer if the thread launched for prepare() - * method calls can be interrupted. If false, the thread will be allowed to - * complete it's work. This (false) is generally a good setting for layers - * contacting servers. The default setting is, however, true. - */ - public final static String InterruptableProperty = "interruptable"; - - /** - * Filter support that can be used to manage OMGraphics. - */ - protected FilterSupport filter = new FilterSupport(); - - /** - * The ProjectionChangePolicy object that determines how a layer reacts and - * sets up the OMGraphicList to be rendered for the layer when the - * projection changes. - */ - protected ProjectionChangePolicy projectionChangePolicy = null; - - /** - * The RenderPolicy object that determines how a layer's OMGraphicList is - * rendered in the layer.paint() method. - */ - protected RenderPolicy renderPolicy = null; - - /** - * A SwingWorker that can be used for gathering OMGraphics or doing other - * work in a different thread. - */ - protected ISwingWorker layerWorker; - /** - * A SwingWorker created if the projection changes when the primary - * layerworker is off doing work. If a bunch of project changes occur before - * the primary layerworker returns from being interrupted, setting the one - * in the queue will take care of all of them. - */ - protected boolean layerWorkerQueue = false; - - protected String[] mouseModeIDs = null; - - /** - * A flag to tell the layer to be selfish about consuming MouseEvents it - * receives. If set to true, it will consume events so that other layers - * will not receive the events. If false, lower layers will also receive - * events, which will let them react too. Intended to let other layers - * provide information about what the mouse is over when editing. - */ - protected boolean consumeEvents = false; - - /** - * Flag used to avoid the SwingWorker to be interrupted. Useful for layers - * that load an image from a server such as the WMSPlugin to avoid an ugly - * java output "Interrupted while loading image". - */ - protected boolean interruptable = true; - - /** - * Sets the interruptible flag, allowing the current swing worker thread to - * have interrupt called on it. - */ - public void setInterruptable(boolean b) { - interruptable = b; - } - - /** - * Queries for the interruptible flag. - * - * @return true if interruptible flag is set, allowing interrupt to be - * called on swing worker threads. - */ - public boolean isInterruptable() { - return interruptable; - } - - // OMGraphicHandler methods, deferred to FilterSupport... - - /** - * Sets all the OMGraphics outside of this shape to be invisible. Also - * returns another OMGraphicList containing OMGraphics that are contained - * within the Shape provided. - */ - public OMGraphicList filter(Shape withinThisShape) { - return filter.filter(withinThisShape); - } - - /** - * @see com.bbn.openmap.omGraphics.OMGraphicHandler#filter(Shape, boolean). - */ - public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary) { - return filter.filter(shapeBoundary, getInsideBoundary); - } - - /** - * To find out whether SQL queries are handled. - * - * @see com.bbn.openmap.omGraphics.OMGraphicHandler#supportsSQL(). - */ - public boolean supportsSQL() { - return filter.supportsSQL(); - } - - /** - * Depending on the filter's SQL support, returns an OMGraphicList that fit - * the query. - */ - public OMGraphicList filter(String SQLQuery) { - return filter.filter(SQLQuery); - } - - /** - * Perform the OMAction on the OMGraphic, within the OMGraphicList contained - * in the layer. - */ - public boolean doAction(OMGraphic graphic, OMAction action) { - return filter.doAction(graphic, action); - } - - /** - * Get the OMGraphicList held by the layer. May be null. - */ - public OMGraphicList getList() { - return filter.getList(); - } - - /** - * Indicates if the OMGraphicHandler can have its OMGraphicList set. - */ - public boolean canSetList() { - return filter.canSetList(); - } - - /** - * Set the OMGraphicList within this OMGraphicHandler. Works if - * canSetGraphicList == true. - */ - public void setList(OMGraphicList omgl) { - filter.setList(omgl); - } - - /** - * Remove all filters, and reset all graphics to be visible. - */ - public void resetFiltering() { - filter.resetFiltering(); - } - - /** - * Don't set to null. This is here to let subclasses put a more/less capable - * FilterSupport in place. - */ - public void setFilter(FilterSupport fs) { - filter = fs; - } - - /** - * Get the FilterSupport object that is handling the OMGraphicHandler - * methods. - */ - public FilterSupport getFilter() { - return filter; - } - - /** - * From the ProjectionListener interface. The method gets called when the - * layer is part of the map, and whenever the map projection changes. Will - * trigger a repaint(). - *

- * - * The ProjectionEvent is passed to the current ProjectionChangePolicy - * object, which determines what will happen on the layer and how. By - * default, a StandardPCPolicy is notified with the projection change, and - * it will test the projection for changes and make sure prepare() is - * called. It will make the decision whether doPrepare() is called, based on - * the number of OMGraphics on the list, which may launch a swing worker - * thread to call prepare(). The StandardPCPolicy does not do anything to - * the OMGraphicList when the projection changes. - *

- * - * If you need the OMGraphicList cleared out with a new projection, you can - * substitute a ListRestPCPolicy for the StandardPCPolicy. You would want to - * do this if your OMGraphicList changes for different projections - The - * reason the OMGraphicList is nulled out is so if another layer finishes - * before yours does and gets repainted, your old OMGraphics don't get - * painted along side their new ones - it's a mismatched situation. You can - * set the ProjectionChangePolicy directly with the - * setProjectionChangePolicy, or by overriding the getProjectionChangePolicy - * method and returning the type you want by default if it is null. - * - * @see com.bbn.openmap.layer.policy.ProjectionChangePolicy - * @see com.bbn.openmap.layer.policy.StandardPCPolicy - * @see com.bbn.openmap.layer.policy.ListResetPCPolicy - */ - public void projectionChanged(ProjectionEvent pe) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("OMGraphicHandlerLayer " + getName() + " projection changed, calling " - + getProjectionChangePolicy().getClass().getName()); - } - - getRenderPolicy().prePrepare(pe.getProjection()); - getProjectionChangePolicy().projectionChanged(pe); - } - - /** - * Get the ProjectionChangePolicy that determines how a layer reacts and - * gathers OMGraphics for a projection change. - */ - public ProjectionChangePolicy getProjectionChangePolicy() { - if (projectionChangePolicy == null) { - projectionChangePolicy = new StandardPCPolicy(this); - } - return projectionChangePolicy; - } - - /** - * Set the ProjectionChangePolicy that determines how a layer reacts and - * gathers OMGraphics for a projection change. - */ - public void setProjectionChangePolicy(ProjectionChangePolicy pcp) { - projectionChangePolicy = pcp; - // Just to make sure, - pcp.setLayer(this); - } - - /** - * Get the RenderPolicy that determines how an OMGraphicList is rendered. - */ - public RenderPolicy getRenderPolicy() { - if (renderPolicy == null) { - renderPolicy = new StandardRenderPolicy(this); - } - return renderPolicy; - } - - /** - * Set the RenderPolicy that determines how the OMGraphicList is rendered. - */ - public void setRenderPolicy(RenderPolicy rp) { - renderPolicy = rp; - // Just to make sure, - rp.setLayer(this); - } - - /** - * Sets the SwingWorker off to call prepare(). If the SwingWorker passed in - * is not null, start() is called on it. - * - * @param worker null to reset the layerWorker variable, or a SwingWorker to - * start up. - */ - protected void setLayerWorker(ISwingWorker worker) { - synchronized (LAYERWORKER_LOCK) { - layerWorker = worker; - layerWorkerQueue = false; - } - - if (worker != null) { - worker.start(); - } - } - - protected ISwingWorker getLayerWorker() { - return layerWorker; - } - - /** - * Called from within the layer to create a LayerWorker to use for the - * prepare() method. By default, a new LayerWorker is returned. This method - * may be overridden to make the layer use an extended - * LayerWorker/SwingWorker class. - * - * @return SwingWorker/LayerWorker - */ - protected ISwingWorker createLayerWorker() { - return new LayerWorker(); - } - - /** - * Overrides Layer.dispose(), makes sure the OMGraphicList is cleared. - */ - public void dispose() { - super.dispose(); - setList(null); - } - - /** - * This method is here to provide a default action for Layers as they act as - * a ProjectionPainter. Normally, ProjectionPainters are expected to receive - * the projection, gather/create OMGraphics that apply to the projection, - * and render them into the Graphics provided. This is supposed to be done - * in the same thread that calls this function, so the caller knows that - * when this method returns, everything that the ProjectionPainter needed to - * do is complete. - *

- * If the layer doesn't override this method, then the paint(Graphics) - * method will be called. - * - * @param proj Projection of the map. - * @param g java.awt.Graphics to draw into. - */ - public synchronized void renderDataForProjection(Projection proj, Graphics g) { - if (proj == null) { - logger.warning("Layer(" + getName() + ").renderDataForProjection: null projection!"); - return; - } else if (!proj.equals(getProjection())) { - setProjection(proj.makeClone()); - setList(getRenderPolicy().prepare()); - } - paint(g); - } - - /** - * The default action is to get the OMGraphicList and render it. - * - * @param g java.awt.Graphics object to render OMGraphics into. - */ - public void paint(Graphics g) { - getRenderPolicy().paint(g); - } - - /** - * A method that will launch a LayerWorker thread to call the prepare - * method. This method will set in motion all the steps needed to create and - * render the current OMGraphicList with the current projection. Nothing - * more needs to be called, because the LayerWorker will be started, it will - * call prepare(). Inside the prepare() method, the OMGraphicList should be - * created and the OMGraphics generated for the current projection that can - * be picked up in the getProjection() method, and the LayerWorker will call - * workerComplete() which will call repaint() on this layer. - */ - public void doPrepare() { - synchronized (LAYERWORKER_LOCK) { - - if (layerWorkerQueue) { - return; - } - - ISwingWorker currentLayerWorker = layerWorker; - - if (currentLayerWorker != null) { - layerWorkerQueue = true; - if (interruptable) { - currentLayerWorker.interrupt(); - } - return; - } - - setLayerWorker(createLayerWorker()); - } - } - - /** - * A check to see if the LayerWorker (SwingWorker) exists (is doing - * something). - */ - public boolean isWorking() { - // We don't care if it hasn't been interrupted - since the - // LayerWorker will launch a new thread when things settle out, we - // just want to know if there is a LayerWorker in place. If multiple - // doPrepare() calls come in, we need to ignore all of the requests - // that have come it after the first one that canceled the - // LayerWorker in the first place. - synchronized (LAYERWORKER_LOCK) { - return (layerWorker != null); - } - } - - /** - * This is the main method you should be concerned with when overriding this - * class. You have to make sure that this method returns an OMGraphicList - * that is ready to be rendered. That means they need to be generated with - * the current projection, which can be retrieved by calling - * getProjection(). - *

- * - * This method will be called in a separate thread if doPrepare() is called - * on the layer. This will automatically cause repaint() to be called, which - * lets java know to call paint() on this class. - *

- * - * Note that the default action of this method is to get the OMGraphicList - * as it is currently set in the layer, re-projects the list with the - * current projection (calls generate() on them), and then returns the - * current list. - *

- * - * If your layer needs to change what is on the list based on what the - * current projection is, you can either clear() the list yourself and add - * new OMGraphics to it (remember to call generate(Projection) on them), and - * return the list. You also have the option of setting a ListResetPCPolicy, - * which will automatically set the list to null when the projection changes - * before calling this method. The OMGraphicHandlerList will ignore a null - * OMGraphicList. - *

- * - * NOTE: If you call prepare directly, you may need to call repaint(), too. - * With all invocations of this method that are cause by a projection - * change, repaint() will be called for you. - * - * The method is synchronized in case renderDataForProjection() gets called - * while in the middle of this method. For a different projection, that - * would be bad. - */ - public synchronized OMGraphicList prepare() { - OMGraphicList currentList = getList(); - Projection proj = getProjection(); - - // if the layer hasn't been added to the MapBean - // the projection could be null. - if (currentList != null && proj != null) { - currentList.generate(proj); - } - - return currentList; - } - - /** - * Lock object used for managing LayerWorker and queue synchronization. - */ - protected final Object LAYERWORKER_LOCK = new Object(); - - /** - * Check to see if it's likely the current thread will be replaced with - * another one. - * - * @return true if another layer worker is queued up. - */ - public boolean isCancelled() { - synchronized (LAYERWORKER_LOCK) { - return layerWorkerQueue; - } - } - - /** - * The LayerWorker calls this method on the layer when it is done working. - * If the calling worker is not the same as the "current" worker, then a new - * worker is created. - * - * @param worker the worker that has the graphics, must not be null. - */ - protected void workerComplete(ISwingWorker worker) { - - boolean finishUpWithWorker = false; - - synchronized (LAYERWORKER_LOCK) { - finishUpWithWorker = !layerWorkerQueue; - setLayerWorker(layerWorkerQueue ? createLayerWorker() : null); - layerWorkerQueue = false; - } - - if (finishUpWithWorker) { - // CAUTION! layer.repaint() is called in workerComplete!! - getProjectionChangePolicy().workerComplete(worker.get()); - } - } - - /** - * Since we can't have the main thread taking up the time to do the work to - * create OMGraphics, we use this worker thread to do it. - */ - class LayerWorker extends PooledSwingWorker { - /** Constructor used to create a worker thread. */ - public LayerWorker() { - super(); - } - - /** - * Compute the value to be returned by the get method. - */ - public OMGraphicList construct() { - logger.fine(getName() + "|LayerWorker.construct()"); - fireStatusUpdate(LayerStatusEvent.START_WORKING); - String errorMsg = null; - - try { - long start = System.currentTimeMillis(); - OMGraphicList list = getRenderPolicy().prepare(); - long stop = System.currentTimeMillis(); - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + "|LayerWorker.construct(): fetched " - + (list == null ? "null list " : (list.size() + " graphics ")) + "in " - + (double) ((stop - start) / 1000d) + " seconds"); - } - return list; - - } catch (OutOfMemoryError e) { - errorMsg = getName() + "|LayerWorker.construct(): " + e.getMessage(); - if (logger.isLoggable(Level.FINER)) { - logger.fine(errorMsg); - e.printStackTrace(); - } else { - logger.info(getName() + " layer ran out of memory, attempting to recover..."); - } - } catch (Throwable e) { - errorMsg = getName() + "|LayerWorker.construct(): " + e.getClass().getName() + ", " - + e.getMessage(); - logger.info(errorMsg); - e.printStackTrace(); - } - - // This is only called if there is an error. - if (errorMsg != null && logger.isLoggable(Level.FINE)) { - fireRequestMessage(new InfoDisplayEvent(this, errorMsg)); - } - - return null; - } - - /** - * Called on the event dispatching thread (not on the worker thread) - * after the construct method has returned. - */ - public void finished() { - workerComplete(this); - if (!isInterrupted()) { - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - } - - public String toString() { - return getName() + " LayerWorker"; - } - - } - - /** - * Overrides the Layer setProperties method. Also calls Layer's version. If - * the ProjectionChangePolicy and RenderPolicy objects are set - * programmatically, are PropertyConsumers and the .class property is not - * set, they will still have access to properties if this method is called. - * Their property prefix will be scoped as if the OMGraphicHandlerLayer had - * them created, with their prefix being prefix + . + - * PropertyChangePolicyProperty and prefix + . + RenderPolicyProperty. If - * the .class property is set, then a new policy object will be created and - * replace the one set before this method is called. - * - * @param prefix the token to prefix the property names - * @param props the Properties object - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - - String realPrefix = PropUtils.getScopedPropertyPrefix(prefix); - - // Check to see if the layer wants to set its own projection - // change policy. - String pcpString = props.getProperty(realPrefix + ProjectionChangePolicyProperty); - String policyPrefix; - if (pcpString != null) { - policyPrefix = realPrefix + pcpString; - - // If the projection change policy is null, try to create - // it. - String pcpClass = props.getProperty(policyPrefix + ".class"); - if (pcpClass != null) { - - Object obj = ComponentFactory.create(pcpClass, policyPrefix, props); - if (obj != null) { - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " setting ProjectionChangePolicy [" - + obj.getClass().getName() + "]"); - } - - try { - setProjectionChangePolicy((ProjectionChangePolicy) obj); - } catch (ClassCastException cce) { - logger.warning("Layer " - + getName() - + " has " - + policyPrefix - + " property defined in properties for ProjectionChangePolicy, but " - + policyPrefix + ".class property (" + pcpClass - + ") does not define a valid ProjectionChangePolicy. A " - + obj.getClass().getName() + " was created instead."); - } - - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for PropertyChangePolicy, but " - + policyPrefix - + ".class property does not define a valid PropertyChangePolicy."); - } - - } else if (projectionChangePolicy != null) { // ProjectionChangePolicy - // is not null... - // If the projection change policy is not null and the - // policy is a PropertyConsumer, pass the properties - // to the policy. Note that the property prefix for - // the policy is prefix + - // ProjectionChangePolicyProperty - - if (projectionChangePolicy instanceof PropertyConsumer) { - ((PropertyConsumer) projectionChangePolicy).setProperties(policyPrefix, props); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for PropertyChangePolicy, but " - + policyPrefix + ".class property is undefined."); - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " using default ProjectionChangePolicy [" - + getProjectionChangePolicy().getClass().getName() + "]"); - } - - // Check to see if the layer want to set its own rendering - // policy. - String rpString = props.getProperty(realPrefix + RenderPolicyProperty); - if (rpString != null) { - policyPrefix = realPrefix + rpString; - String rpClass = props.getProperty(policyPrefix + ".class"); - - if (rpClass != null) { - - Object rpObj = ComponentFactory.create(rpClass, policyPrefix, props); - - if (rpObj != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " setting RenderPolicy [" - + rpObj.getClass().getName() + "]"); - } - - try { - setRenderPolicy((RenderPolicy) rpObj); - } catch (ClassCastException cce) { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " - + policyPrefix + ".class property (" + rpClass - + ") does not define a valid RenderPolicy. A " - + rpObj.getClass().getName() + " was created instead."); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " - + policyPrefix + ".class property (" + rpClass - + ") isn't being created."); - } - - } else if (renderPolicy != null) { // RenderPolicy is not null... - // Same thing with renderPolicy as with projection - // change policy. - if (renderPolicy instanceof PropertyConsumer) { - ((PropertyConsumer) renderPolicy).setProperties(policyPrefix, props); - } - } else { - logger.warning("Layer " + getName() + " has " + policyPrefix - + " property defined in properties for RenderPolicy, but " + policyPrefix - + ".class property is undefined."); - } - - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("Layer " + getName() + " using default RenderPolicy [" - + getRenderPolicy().getClass().getName() + "]"); - } - - String mmString = props.getProperty(realPrefix + MouseModesProperty); - if (mmString != null) { - Vector mmv = PropUtils.parseSpacedMarkers(mmString); - if (!mmv.isEmpty()) { - String[] mm = new String[mmv.size()]; - int i = 0; - for (String it : mmv) { - mm[i++] = it; - } - setMouseModeIDsForEvents(mm); - } - } - - consumeEvents = PropUtils.booleanFromProperties(props, realPrefix + ConsumeEventsProperty, consumeEvents); - - setTransparency(PropUtils.floatFromProperties(props, realPrefix + TransparencyProperty, getTransparency())); - - setInterruptable(PropUtils.booleanFromProperties(props, realPrefix + InterruptableProperty, isInterruptable())); - } - - /** - * Overrides Layer getProperties method., also calls that method on Layer. - * Sets the properties from the policy objects used by this OMGraphicHandler - * layer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - String policyPrefix = null; - - // //// ProjectionChangePolicy - - ProjectionChangePolicy pcp = getProjectionChangePolicy(); - if (pcp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) pcp).getPropertyPrefix(); - ((PropertyConsumer) pcp).getProperties(props); - } - - if (policyPrefix == null) { - policyPrefix = prefix + "pcp"; - } - - // Whoops, need to make sure pcp is valid but removing the - // OMGHL prefix from the front of the policy prefix (if - // applicable). Same for RenderPolicy - - props.put(prefix + ProjectionChangePolicyProperty, policyPrefix.substring(prefix.length())); - // This has to come after the above line, or the above - // property will have a trailing period. - policyPrefix = PropUtils.getScopedPropertyPrefix(policyPrefix); - props.put(policyPrefix + "class", pcp.getClass().getName()); - - RenderPolicy rp = getRenderPolicy(); - if (rp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) rp).getPropertyPrefix(); - ((PropertyConsumer) rp).getProperties(props); - } - - // /// RenderPolicy - - if (policyPrefix == null) { - policyPrefix = prefix + "rp"; - } - - props.put(prefix + RenderPolicyProperty, policyPrefix.substring(prefix.length())); - // This has to come after the above line, or the above - // property will have a trailing period. - policyPrefix = PropUtils.getScopedPropertyPrefix(policyPrefix); - props.put(policyPrefix + "class", rp.getClass().getName()); - - props.put(prefix + ConsumeEventsProperty, new Boolean(consumeEvents).toString()); - - String[] mm = getMouseModeIDsForEvents(); - if (mm != null && mm.length > 0) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mm.length; i++) { - // Don't need any MouseModes that have been scoped to - // the pretty name, those are automatically generated. - if (mm[i].equals(getName())) { - continue; - } - sb.append(mm[i]).append(" "); - } - props.put(prefix + MouseModesProperty, sb.toString()); - } - - props.put(prefix + TransparencyProperty, Float.toString(getTransparency())); - - props.put(prefix + InterruptableProperty, Boolean.toString(isInterruptable())); - - return props; - } - - /** - * Overrides Layer getProperties method., also calls that method on Layer. - * Sets the properties from the policy objects used by this OMGraphicHandler - * layer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - String policyPrefix = null; - - ProjectionChangePolicy pcp = getProjectionChangePolicy(); - if (pcp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) pcp).getPropertyPrefix(); - if (policyPrefix != null) { - int index = policyPrefix.indexOf("."); - if (index != -1) { - policyPrefix = policyPrefix.substring(index + 1); - } - - ((PropertyConsumer) pcp).getPropertyInfo(list); - } - } - - if (policyPrefix == null) { - policyPrefix = "pcp"; - } - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, policyPrefix - + ".class", "Projection Change Policy", "Class name of ProjectionChangePolicy (optional)", null); - - RenderPolicy rp = getRenderPolicy(); - if (rp instanceof PropertyConsumer) { - policyPrefix = ((PropertyConsumer) rp).getPropertyPrefix(); - - if (policyPrefix != null) { - int index = policyPrefix.indexOf("."); - if (index != -1) { - policyPrefix = policyPrefix.substring(index + 1); - } - } - - ((PropertyConsumer) rp).getPropertyInfo(list); - } else { - } - - if (policyPrefix == null) { - policyPrefix = "rp"; - } - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, policyPrefix - + ".class", "Rendering Policy", "Class name of RenderPolicy (optional)", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, ConsumeEventsProperty, "Consume mouse events", "Flag that tells the layer to consume mouse events, or let other layers use them as well.", "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, MouseModesProperty, "Mouse modes", "Space-separated list of MouseMode IDs to receive events from.", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, TransparencyProperty, "Transparency", "Transparency setting for layer, between 0 (clear) and 1", null); - - PropUtils.setI18NPropertyInfo(i18n, list, OMGraphicHandlerLayer.class, InterruptableProperty, "Interruptable", "Flat to set whether the layer should immediately stop performing current work when the projection changes.", "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - return list; - } - - /** - * The MapMouseInterpreter used to catch the MapMouseEvents and direct them - * to layer as referencing certain OMGraphics. Manages how the layer - * responds to mouse events. - */ - protected MapMouseInterpreter mouseEventInterpreter = null; - - /** - * Set the interpreter used to field and interpret MouseEvents, thereby - * calling GestureResponsePolicy methods on this layer. - */ - public synchronized void setMouseEventInterpreter(MapMouseInterpreter mmi) { - - if (mmi instanceof StandardMapMouseInterpreter) { - String[] modeList = getMouseModeIDsForEvents(); - ((StandardMapMouseInterpreter) mmi).setMouseModeServiceList(modeList); - ((StandardMapMouseInterpreter) mmi).setConsumeEvents(getConsumeEvents()); - } - - if (mouseEventInterpreter != null) { - // Remove handle - mouseEventInterpreter.setGRP(null); - } - - mmi.setGRP(this); - mouseEventInterpreter = mmi; - } - - /** - * Get the interpreter used to field and interpret MouseEvents, thereby - * calling GestureResponsePolicy methods on this layer. This method checks - * to see if any mouse modes ids have been set via the - * getMouseModeIDsForEvents() method, and if there were and the interpreter - * hasn't been set, it will create a StandardMapMouseInterpreter. Otherwise, - * it returns whatever has been set as the interpreter, which could be null. - */ - public synchronized MapMouseInterpreter getMouseEventInterpreter() { - if (getMouseModeIDsForEvents() != null && mouseEventInterpreter == null) { - setMouseEventInterpreter(new StandardMapMouseInterpreter(this)); - } - - return mouseEventInterpreter; - } - - /** - * Query asked from the MouseDelegator for interest in receiving - * MapMouseEvents. This returns a MapMouseInterpreter that has been told to - * listen for events from the MapMouseModes in setMouseModeIDsForEvents(). - */ - public MapMouseListener getMapMouseListener() { - MapMouseListener mml = getMouseEventInterpreter(); - - if (mml != null) { - if (logger.isLoggable(Level.FINE)) { - - String[] modes = mml.getMouseModeServiceList(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < modes.length; i++) { - sb.append(modes[i]).append(", "); - } - - logger.fine("Layer " + getName() + " returning " + mml.getClass().getName() - + " as map mouse listener that listens to: " + sb.toString()); - } - } - - return mml; - } - - /** - * A flag to tell the layer to be selfish about consuming MouseEvents it - * receives. If set to true, it will consume events so that other layers - * will not receive the events. If false, lower layers will also receive - * events, which will let them react too. Intended to let other layers - * provide information about what the mouse is over when editing. - */ - public void setConsumeEvents(boolean consume) { - consumeEvents = consume; - - if (mouseEventInterpreter instanceof StandardMapMouseInterpreter) { - ((StandardMapMouseInterpreter) mouseEventInterpreter).setConsumeEvents(getConsumeEvents()); - } - } - - public boolean getConsumeEvents() { - return consumeEvents; - } - - /** - * This is the important method call that determines what MapMouseModes the - * interpreter for this layer responds to. The MapMouseInterpreter calls - * this so it can respond to MouseDelegator queries. You can - * programmatically call setMouseModeIDsForEvents with the mode IDs to set - * these values, or set the mouseModes property for this layer set to a - * space-separated list of mode IDs. - */ - public String[] getMouseModeIDsForEvents() { - return mouseModeIDs; - } - - /** - * Use this method to set which mouse modes this layer responds to. The - * array should contain the mouse mode IDs. - */ - public void setMouseModeIDsForEvents(String[] mm) { - - if (logger.isLoggable(Level.FINE)) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mm.length; i++) { - sb.append(mm[i]).append(" "); - } - - logger.fine("For layer " + getName() + ", setting mouse modes to " + sb.toString()); - } - - mouseModeIDs = mm; - - if (mouseEventInterpreter instanceof StandardMapMouseInterpreter) { - ((StandardMapMouseInterpreter) mouseEventInterpreter).setMouseModeServiceList(mm); - } - } - - /** - * Query asking if OMGraphic is highlight-able, which means that something - * in the GUI should change when the mouse is moved or dragged over the - * given OMGraphic. Highlighting shows that something could happen, or - * provides cursory information about the OMGraphic. Responding true to this - * method may cause getInfoText() and getToolTipTextFor() methods to be - * called (depends on the MapMouseInterpetor). - */ - public boolean isHighlightable(OMGraphic omg) { - return true; - } - - /** - * Query asking if an OMGraphic is select-able, or able to be moved, deleted - * or otherwise modified. Responding true to this method may cause select() - * to be called (depends on the MapMouseInterpertor) so the meaning depends - * on what the layer does in select. - */ - public boolean isSelectable(OMGraphic omg) { - return false; - } - - /** - * A current list of select OMGraphics. - */ - protected OMGraphicList selectedList; - - /** - * Retrieve the list of currently selected OMGraphics. - */ - public OMGraphicList getSelected() { - return selectedList; - } - - // //// Reactions - - /** - * Fleeting change of appearance for mouse movements over an OMGraphic. - */ - public void highlight(OMGraphic omg) { - omg.select(); - omg.generate(getProjection()); - repaint(); - } - - /** - * Notification to set OMGraphic to normal appearance. - */ - public void unhighlight(OMGraphic omg) { - omg.deselect(); - omg.generate(getProjection()); - repaint(); - } - - /** - * Designate a list of OMGraphics as selected. - */ - public void select(OMGraphicList list) { - if (list != null) { - for (OMGraphic omg : list) { - - if (selectedList == null) { - selectedList = new OMGraphicList(); - } - - if (omg instanceof OMGraphicList && !((OMGraphicList) omg).isVague()) { - select((OMGraphicList) omg); - } else { - selectedList.add(omg); - } - - } - } - } - - /** - * Designate a list of OMGraphics as de-selected. - */ - public void deselect(OMGraphicList list) { - if (list != null) { - for (OMGraphic omg : list) { - if (omg instanceof OMGraphicList && !((OMGraphicList) omg).isVague()) { - deselect((OMGraphicList) omg); - } else if (selectedList != null) { - selectedList.remove(omg); - } - } - } - } - - /** - * Remove OMGraphics from the layer. - */ - public OMGraphicList cut(OMGraphicList omgl) { - OMGraphicList list = getList(); - if (list != null && omgl != null) { - list.removeAll(omgl); - } - return omgl; - } - - /** - * Return a copy of OMGraphics. - */ - public OMGraphicList copy(OMGraphicList omgl) { - return (OMGraphicList) omgl.clone(); - } - - /** - * Add OMGraphics to the Layer. - */ - public void paste(OMGraphicList omgl) { - OMGraphicList list = getList(); - list.addAll(omgl); - } - - /** - * If applicable, should return a short, informational string about the - * OMGraphic to be displayed in the InformationDelegator. Return null if - * nothing should be displayed. - */ - public String getInfoText(OMGraphic omg) { - return null; - } - - /** - * If applicable, should return a tool tip for the OMGraphic. Return null if - * nothing should be shown. - */ - public String getToolTipTextFor(OMGraphic omg) { - return null; - } - - /** - * Return a JMenu with contents applicable to a pop-up menu for a location - * over the map. The pop-up doesn't concern any OMGraphics, and should be - * presented for a click on the map background. - * - * @param mme a MapMouseEvent describing the location over where the menu - * items should apply, in case different options are appropriate for - * different places. - * @return a JMenu for the map. Return null or empty List if no input - * required. - */ - public List getItemsForMapMenu(MapMouseEvent mme) { - return null; - } - - /** - * Return a java.util.List containing input for a JMenu with contents - * applicable to a pop-up menu for a location over an OMGraphic. - * - * @return a List containing options for the given OMGraphic. Return null or - * empty list if there are no options. - */ - public List getItemsForOMGraphicMenu(OMGraphic omg) { - return null; - } - - /** - * A query from the MapMouseInterpreter wondering if the - * GestureResponsePolicy wants events pertaining to mouse movements over the - * map that are not over an OMGraphic. If the GestureResponsePolicy responds - * true, then the mouseOver and leftClick methods will be called on the - * GestureResponsePolicy by the interpreter. There is no rightClick method - * that is called, because a right click will always cause a - * getItemsForMapMenu() method to be called. - */ - public boolean receivesMapEvents() { - return false; - } - - /** - * A notification that the mouse cursor has been moved over the map, not - * over any of the OMGraphics on the GestureResponsePolicy. This only gets - * called if the response to receiveMapEvents is true. - * - * @param mme MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed and should - * not be passed to anybody else. - */ - public boolean mouseOver(MapMouseEvent mme) { - return false; - } - - /** - * A notification that the mouse has been clicked with the left mouse button - * on the map, and not on any of the OMGraphics. This only gets called if - * the response to receiveMapEvents is true. Right clicks on the map are - * always reported to the getItemsForMapMenu method. - * - * @param mme MapMouseEvent describing the location of the mouse. - * @return true of this information is to be considered consumed and should - * not be passed to anybody else. - */ - public boolean leftClick(MapMouseEvent mme) { - return false; - } - - /** - * Create a JPanel that has a slider to control the layer transparency. An - * action listener that calls layer repaint() when the value changes will be - * added to the slider. - * - * @param label - * the label for the panel around the slider. - * @param orientation - * JSlider.HORIZONTAL/JSlider.VERTICAL - * @param initialValue - * an initial transparency value between 0-1, 0 being clear. - * @return JPanel with controls for transparency setting. - */ - public JPanel getTransparencyAdjustmentPanel(String label, int orientation, float initialValue) { - JPanel opaquePanel = new JPanel(); - // opaquePanel.setBorder(BorderFactory.createEtchedBorder()); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - opaquePanel.setLayout(gridbag); - - c.anchor = GridBagConstraints.NORTHWEST; - JLabel jb = new JLabel(i18n.get(OMGraphicHandlerLayer.class, "layerTransparency", "Layer Transparency")); - gridbag.setConstraints(jb, c); - opaquePanel.add(jb); - - JSlider opaqueSlide = new JSlider(orientation, 0/* min */, 255/* max */, - (int) (255f * initialValue)/* inital */); - java.util.Hashtable dict = new java.util.Hashtable(); - dict.put(new Integer(0), new JLabel(i18n.get(OMGraphicHandlerLayer.class, "clearSliderLabel", "clear"))); - dict.put(new Integer(255), new JLabel(i18n.get(OMGraphicHandlerLayer.class, "opqueSliderLabel", "opaque"))); - opaqueSlide.setLabelTable(dict); - opaqueSlide.setPaintLabels(true); - opaqueSlide.setMajorTickSpacing(50); - opaqueSlide.setPaintTicks(true); - opaqueSlide.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent ce) { - JSlider slider = (JSlider) ce.getSource(); - if (slider.getValueIsAdjusting()) { - OMGraphicHandlerLayer.this.setTransparency((float) slider.getValue() / 255f); - repaint(); - } - } - }); - - c.gridy = 1; - gridbag.setConstraints(opaqueSlide, c); - opaquePanel.add(opaqueSlide); - - return opaquePanel; - } - - public JButton getRedrawButton(String tooltip) { - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setStroke(new BasicStroke(3)); - - IconPart reloadSymbol = OpenMapAppPartCollection.getReloadSymbol(); - reloadSymbol.setRenderingAttributes(da); - - ImageIcon ii = OMIconFactory.getIcon(25, 25, reloadSymbol); - JButton redraw = new JButton(ii); - redraw.setActionCommand(RedrawCmd); - redraw.setToolTipText("Redraw Layer"); - redraw.addActionListener(this); - return redraw; - } - - public JButton getSettingsButton(String tooltip) { - DrawingAttributes da = DrawingAttributes.getDefaultClone(); - da.setStroke(new BasicStroke(3)); - - IconPart settingsSymbol = OpenMapAppPartCollection.getSettingsSymbol(); - settingsSymbol.setRenderingAttributes(da); - - ImageIcon ii = OMIconFactory.getIcon(25, 25, settingsSymbol); - JButton redraw = new JButton(ii); - redraw.setActionCommand(DisplayPropertiesCmd); - redraw.setToolTipText(tooltip); - redraw.addActionListener(this); - return redraw; - } - - /** - * Get a default settings panel that contains the layer transparency - * setting, the settings button and a layer refresh button. - * - * @param clss - * The class for i18n translations - * @param opaquenessSetting - * The current opaqueness setting, as some fraction of 255. 1 is - * opaque. - * @return JPanel with the components all laid out. - */ - public JPanel getDefaultSettingsPanel(Class clss, float opaquenessSetting) { - JPanel panel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - panel.setLayout(gridbag); - - c.gridx = 0; - c.gridy = 0; - c.gridheight = 2; - c.insets = new Insets(5, 5, 5, 0); - - JPanel transPanel = getTransparencyAdjustmentPanel( - i18n.get(clss, "layerTransparencyGUILabel", "Layer Transparency"), JSlider.HORIZONTAL, - opaquenessSetting); - gridbag.setConstraints(transPanel, c); - panel.add(transPanel); - - c.gridx = 1; - c.gridheight = 1; - c.insets = new Insets(5, 0, 0, 5); - JButton jb = getSettingsButton(i18n.get(clss, "layerSettingsButtonTooltip", "Change Layer Settings")); - gridbag.setConstraints(jb, c); - panel.add(jb); - - c.gridy = 1; - c.insets = new Insets(0, 0, 5, 5); - jb = getRedrawButton(i18n.get(clss, "layerRedrawButtonTooltip", "Refresh Layer")); - gridbag.setConstraints(jb, c); - panel.add(jb); - - return panel; - } - - /** - * Set the transparency of the layer. This transparency is applied during - * rendering. - * - * @param value - * 0f for clear, 1f for opaque. - */ - public void setTransparency(float value) { - AlphaComposite ac = null; - if (value != 1f) { - ac = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, value); - } - getRenderPolicy().setComposite(ac); - } - - /** - * Get the transparency value for this layer. - * - * @return 1 if opaque, 0 for clear. - */ - public float getTransparency() { - float ret = 1f; - RenderPolicy rp = getRenderPolicy(); - - if (rp != null) { - Composite comp = rp.getComposite(); - if (comp instanceof AlphaComposite) { - ret = ((AlphaComposite) comp).getAlpha(); - } - } - - return ret; - } - - /** - * Override of Layer's actionPerformed method, adds the capability that - * calls doPrepare() if the layer is visible and it receives a RedrawCmd - * command. Also calls Layer.actionPerformed(ActionEvent). - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String cmd = e.getActionCommand(); - if (cmd == RedrawCmd) { - if (isVisible()) { - doPrepare(); - } - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/ScaleDisplayLayer.java b/src/openmap/com/bbn/openmap/layer/ScaleDisplayLayer.java deleted file mode 100644 index 2412137ff..000000000 --- a/src/openmap/com/bbn/openmap/layer/ScaleDisplayLayer.java +++ /dev/null @@ -1,332 +0,0 @@ -/* ********************************************************************** - * - * ROLANDS & ASSOCIATES Corporation - * 500 Sloat Avenue - * Monterey, CA 93940 - * (831) 373-2025 - * - * Copyright (C) 2002, 2003 ROLANDS & ASSOCIATES Corporation. All rights reserved. - * Openmap is a trademark of BBN Technologies, A Verizon Company - * - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/ScaleDisplayLayer.java,v $ - * $Revision: 1.9 $ - * $Date: 2005/12/09 21:09:08 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.layer; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Logger; - -import javax.swing.ButtonGroup; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.PropUtils; - -/** - * Layer objects are components which can be added to the MapBean to make a map. - *

- * Layers implement the ProjectionListener interface to listen for - * ProjectionEvents. When the projection changes, they may need to re-fetch, - * regenerate their graphics, and then repaint themselves into the new view. - *

- *

- * 
- * ### Layer used by the overview handler
- * scaleLayer.class=com.rolands.jtlsweb.map.layer.ScaleDisplayLayer
- * scaleLayer.prettyName=Scale
- * scaleLayer.lineColor=ff777777
- * scaleLayer.textColor=ff000000
- * scaleLayer.unitOfMeasure=nm
- * scaleLayer.locationXoffset=-10
- * scaleLayer.locationYoffset=-20
- * scaleLayer.width=150
- * scaleLayer.height=10
- * 
- * # unitOfMeasure - any com.bbn.openmap.proj.Length instance returned by Length.get(string).
- * # locationXoffset - offset in pixels from left/right, positive from left edge, negative from right edge
- * # locationYoffset - offset in pixels from top/bottom, positive from top edge, negative from bottom edge
- * # width - width of scale indicator bar in pixels
- * # height - height of scale indicator bar in pixels
- *
- * 
- */ -public class ScaleDisplayLayer extends OMGraphicHandlerLayer { - - public ScaleDisplayLayer() { - super(); - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setUnitOfMeasure(Length.KM.toString()); - } - - protected Logger logger = Logger.getLogger("com.bbn.openmap.layer.ScaleDisplayLayer"); - - // Color variables for different line types - protected java.awt.Color lineColor = null; - protected java.awt.Color textColor = null; - - // Default colors to use, if not specified in the properties. - protected String defaultLineColorString = "FFFFFF"; - protected String defaultTextColorString = "FFFFFF"; - protected String defaultUnitOfMeasureString = "km"; - protected int defaultLocationXoffset = -10; - protected int defaultLocationYoffset = -10; - protected int defaultWidth = 150; - protected int defaultHeight = 10; - - // property text values - public static final String UnitOfMeasureProperty = "unitOfMeasure"; - public static final String LocationXOffsetProperty = "locationXoffset"; - public static final String LocationYOffsetProperty = "locationYoffset"; - public static final String WidthProperty = "width"; - public static final String HeightProperty = "height"; - - protected String unitOfMeasure = null; - protected Length uom = Length.get(defaultUnitOfMeasureString); - protected String uomAbbr = uom.getAbbr(); - protected int locationXoffset = defaultLocationXoffset; - protected int locationYoffset = defaultLocationYoffset; - protected int width = defaultWidth; - protected int height = defaultHeight; - - protected DrawingAttributes dAttributes = DrawingAttributes.getDefaultClone(); - - /** - * Sets the properties for the Layer. This allows - * Layer s to get a richer set of parameters than the - * setArgs method. - * - * @param prefix the token to prefix the property names - * @param properties the Properties object - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - dAttributes.setProperties(prefix, properties); - - String unitOfMeasureString = properties.getProperty(prefix + UnitOfMeasureProperty); - if (unitOfMeasureString != null) { - setUnitOfMeasure(unitOfMeasureString); - } - - locationXoffset = PropUtils.intFromProperties(properties, prefix + LocationXOffsetProperty, defaultLocationXoffset); - - locationYoffset = PropUtils.intFromProperties(properties, prefix + LocationYOffsetProperty, defaultLocationYoffset); - - width = PropUtils.intFromProperties(properties, prefix + WidthProperty, defaultWidth); - - height = PropUtils.intFromProperties(properties, prefix + HeightProperty, defaultHeight); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - dAttributes.setProperties(props); - - props.put(prefix + LocationXOffsetProperty, Integer.toString(locationXoffset)); - props.put(prefix + LocationYOffsetProperty, Integer.toString(locationYoffset)); - props.put(prefix + WidthProperty, Integer.toString(width)); - props.put(prefix + HeightProperty, Integer.toString(height)); - - props.put(prefix + UnitOfMeasureProperty, unitOfMeasure); - - return props; - } - - public synchronized OMGraphicList prepare() { - int w, h, left_x = 0, right_x = 0, lower_y = 0, upper_y = 0; - Projection projection = getProjection(); - OMGraphicList graphics = new OMGraphicList(); - - w = projection.getWidth(); - h = projection.getHeight(); - if (locationXoffset < 0) { - left_x = w + locationXoffset - width; - right_x = w + locationXoffset; - } else if (locationXoffset >= 0) { - left_x = locationXoffset; - right_x = locationXoffset + width; - } - if (locationYoffset < 0) { - upper_y = h + locationYoffset - height; - lower_y = h + locationYoffset; - } else if (locationYoffset >= 0) { - upper_y = locationYoffset; - lower_y = locationYoffset + height; - } - - graphics.clear(); - - OMLine line = new OMLine(left_x, lower_y, right_x, lower_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(left_x, lower_y, left_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - line = new OMLine(right_x, lower_y, right_x, upper_y); - dAttributes.setTo(line); - graphics.add(line); - - /* - * We need to use better coordinates to measure distance, like the same - * pixel distance at the center of the map. There's a problem using the - * lower right location, in that those distances decrease as you zoom out. - */ - - int y = h / 2; - int x = w / 2; - int xSide = (right_x - left_x) / 2; - - LatLonPoint loc1 = projection.inverse(x - xSide, y, new LatLonPoint.Double()); - LatLonPoint loc2 = projection.inverse(x + xSide, y, new LatLonPoint.Double()); - - double dist = uom.fromRadians(loc1.distance(loc2)); - - String outtext; - if (dist < 1.0f) { - outtext = String.format("%.3f %s", dist, uomAbbr); - } else if (dist < 10.0f) { - outtext = String.format("%.2f %s", dist, uomAbbr); - } else if (dist < 100.0f) { - outtext = String.format("%.1f %s", dist, uomAbbr); - } else { - outtext = String.format("%.0f %s", dist, uomAbbr); - } - - OMText text = new OMText((left_x + right_x) / 2, lower_y - 3, "" + outtext, OMText.JUSTIFY_CENTER); - - Font font = text.getFont(); - text.setFont(font.deriveFont(font.getStyle(), font.getSize() + 4)); - - dAttributes.setTo(text); - text.setTextMatteColor((Color) dAttributes.getMattingPaint()); - text.setTextMatteStroke(new BasicStroke(5)); - text.setMattingPaint(OMColor.clear); - graphics.add(text); - graphics.generate(projection); - - return graphics; - } - - /** - * Getter for property unitOfMeasure. - * - * @return Value of property unitOfMeasure. - */ - public String getUnitOfMeasure() { - return this.unitOfMeasure; - } - - /** - * Setter for property unitOfMeasure. - * - * @param unitOfMeasure New value of property unitOfMeasure. - * - * @throws PropertyVetoException - */ - public void setUnitOfMeasure(String unitOfMeasure) { - if (unitOfMeasure == null) - unitOfMeasure = Length.KM.toString(); - this.unitOfMeasure = unitOfMeasure; - - // There is a bug in the Length.get() method that will not - // return - // the correct (or any value) for a requested uom. - // This does not work: - // uom = com.bbn.openmap.proj.Length.get(unitOfMeasure); - - // Therefore, The following code correctly obtains the proper - // Length object. - - Length[] choices = Length.values(); - uom = null; - for (int i = 0; i < choices.length; i++) { - if (unitOfMeasure.equalsIgnoreCase(choices[i].toString()) - || unitOfMeasure.equalsIgnoreCase(choices[i].getAbbr())) { - uom = choices[i]; - break; - } - } - - // of no uom is found assign Kilometers as the default. - if (uom == null) - uom = Length.KM; - - uomAbbr = uom.getAbbr(); - - } - - JPanel palettePanel; - ButtonGroup uomButtonGroup; - Vector buttons = new Vector(); - - /** Creates the interface palette. */ - public java.awt.Component getGUI() { - - if (palettePanel == null) { - - logger.fine("creating palette."); - - palettePanel = new JPanel(); - uomButtonGroup = new ButtonGroup(); - - palettePanel.setLayout(new javax.swing.BoxLayout(palettePanel, javax.swing.BoxLayout.Y_AXIS)); - palettePanel.setBorder(new javax.swing.border.TitledBorder("Unit Of Measure")); - - java.awt.event.ActionListener al = new ActionListener() { - // We don't have to check for action commands or anything like that. - // We know this listener is going to be added to JRadioButtons that - // are labeled with abbreviations for length. - public void actionPerformed(ActionEvent e) { - JRadioButton jrb = (JRadioButton) e.getSource(); - setUnitOfMeasure(jrb.getText()); - } - }; - - for (Length lengthType : Length.values()) { - JRadioButton jrb = new JRadioButton(); - jrb.setText(lengthType.getAbbr()); - jrb.setToolTipText(lengthType.toString()); - uomButtonGroup.add(jrb); - palettePanel.add(jrb); - - jrb.addActionListener(al); - - jrb.setSelected(unitOfMeasure.equalsIgnoreCase(lengthType.getAbbr())); - buttons.add(jrb); - } - - } else { - for (JRadioButton button : buttons) { - button.setSelected(uom.getAbbr().equalsIgnoreCase(button.getText())); - } - } - - return palettePanel; - } -} diff --git a/src/openmap/com/bbn/openmap/layer/ScaleFilterLayer.java b/src/openmap/com/bbn/openmap/layer/ScaleFilterLayer.java deleted file mode 100644 index ca8418f22..000000000 --- a/src/openmap/com/bbn/openmap/layer/ScaleFilterLayer.java +++ /dev/null @@ -1,888 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/ScaleFilterLayer.java,v $ -// $RCSfile: ScaleFilterLayer.java,v $ -// $Revision: 1.14 $ -// $Date: 2008/09/26 12:07:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer; - -import java.awt.Component; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.beancontext.BeanContext; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; - -import com.bbn.openmap.Layer; -import com.bbn.openmap.MapHandler; -import com.bbn.openmap.MouseDelegator; -import com.bbn.openmap.event.InfoDisplayEvent; -import com.bbn.openmap.event.InfoDisplayListener; -import com.bbn.openmap.event.LayerStatusEvent; -import com.bbn.openmap.event.LayerStatusListener; -import com.bbn.openmap.event.MapMouseListener; -import com.bbn.openmap.event.MapMouseMode; -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * An OpenMap Layer that encapsulates other layers and acts as a scale filter. - * It will delegate responsibility to one of several layers depending on the - * scale. - *

- * To use this layer, list it as a layer in the openmap.properties file in the - * openmap.layers properties, as you would add any other layer. Then, add these - * properties to the openmap.properties file. The layers added to the - * ScaleFilterLayer do not get added to the openmap.layers property, but instead - * get added to the scaledFilterLayer.layers property listed here. Then, the - * properties for these layers are added to the openmap.properties file like any - * other layer. - *

- *

- * The properties for this layer look like this:
- * 
- * scaledFilterLayer.class=com.bbn.openmap.layer.ScaleFilterLayer
- * scaledFilterLayer.prettyName=<Pretty name used on menu>
- * # List 2 or more layer prefixes, larger scale layers first
- * scaledFilterLayer.layers=layer_1 layer_2 layer_3 ...
- * # List the transition scales to switch between layers
- * scaledFilterLayer.transitionScales= (transition scale from layer 1 to 2) (transition scale from layer 2 to 3) (...)
- *        
- * 
- */ -public class ScaleFilterLayer - extends Layer - implements InfoDisplayListener, LayerStatusListener, PropertyChangeListener, MapMouseListener { - - /** - * The layers property. - */ - public final static transient String layersProperty = "layers"; - - /** - * The transition scales property. - */ - public final static transient String transitionScalesProperty = "transitionScales"; - - /** - * The layers. - */ - protected Vector layers; - - /** - * The transition scales. - */ - protected float[] transitionScales; - - /** - * The default transition scale. - */ - protected float defaultTransitionScale = 40000000f; - - /** - * The index of the currently selected layer. - */ - protected int targetIndex = -1; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.ScaleFilterLayer"); - - /** - * Initializes an empty layer. - */ - public ScaleFilterLayer() { - // Setting the overlay layout seemed like a good idea at the time, but - // it introduces a strange bug where the bounds of the layer get set - // between the center of the map and the lower left corner. This only - // happens for the BufferedLayerMapBean, when there are buffered layers - // active. Very strange, but not setting an overlay seems to work OK, - // too. - // setLayout(new OverlayLayout(this)); - - // To get MouseDelegator, to make decisions on receiving mouse - // modes for child layers. - setAddToBeanContext(true); - } - - /** - * Get the Vector holding the Layers. If it hasn't been asked for yet, a - * new, empty Vector will be returned, one that will be used internally. - */ - public Vector getLayers() { - if (layers == null) { - layers = new Vector(); - } - return layers; - } - - /** - * Get the transition scales used to set the active layer. - */ - public float[] getTransitionScales() { - return transitionScales; - } - - /** - * Programmatic way to set layers and scales. There should be one more layer - * on the list than there is scale in the float array. Layers that should be - * displayed for larger scale numbers (smaller scale) should be at the front - * of the Vector list, and larger numbers should be at the front of the - * scale array. For scale numbers larger than the first number in the array, - * the first layer will be displayed. As the scale number decreases, other - * layers will be displayed. - * - * @param list Vector of layers - * @param scales Array of transition scales. - */ - public void setLayersAndScales(Vector list, float[] scales) { - layers = list; - transitionScales = scales; - } - - /** - * Initializes this layer from the given properties. - * - * @param props the Properties holding settings for this layer - */ - public void setProperties(String prefix, Properties props) { - // Clear out layer and scale state - setLayersAndScales(null, null); - - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - parseLayers(prefix, props); - parseScales(prefix, props); - - // Update our target layer. If there is a current projection and this - // layer is active, we need to pass it along. - if (getProjection() != null) { - Layer currentLayer = configureAppropriateLayer(getProjection().getScale()); - fireStatusUpdate(LayerStatusEvent.START_WORKING); - currentLayer.projectionChanged(new ProjectionEvent((Object) null, getProjection())); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - float[] ts = getTransitionScales(); - StringBuffer tsBuffer = new StringBuffer(); - if (ts != null) { - for (int i = 0; i < ts.length; i++) { - tsBuffer.append(Float.toString(ts[i])).append(" "); - } - } - props.put(prefix + transitionScalesProperty, tsBuffer.toString()); - - StringBuffer layerBuffer = new StringBuffer(); - for (Layer layer : getLayers()) { - layerBuffer.append(layer.getPropertyPrefix()).append(" "); - layer.getProperties(props); - } - props.put(prefix + layersProperty, layerBuffer.toString()); - - return props; - } - - /** - * Get the layer that's appropriate at the current scale. The targetedIndex - * needs to be set before this is called. The targetedIndex is the index to - * the layers array representing the current layer. - * - * @return Layer - */ - public Layer getAppropriateLayer() { - try { - return getLayers().elementAt(targetIndex); - } catch (NullPointerException npe) { - } catch (ArrayIndexOutOfBoundsException aioobe) { - } - - return SinkLayer.getSharedInstance(); - } - - /** - * Create the Layers from a property value string. - * - * @param prefix String - * @param props Properties - */ - protected void parseLayers(String prefix, Properties props) { - PropUtils.putDataPrefixToLayerList(this, props, prefix + layersProperty); - - String layersString = props.getProperty(prefix + layersProperty); - Vector layers = getLayers(); - if (layersString == null || layersString.length() == 0) { - logger.info("ScaleFilterLayer(): null layersString!"); - return; - } - StringTokenizer tok = new StringTokenizer(layersString); - while (tok.hasMoreTokens()) { - Object obj; - String layerName = tok.nextToken(); - String classProperty = layerName + ".class"; - String className = props.getProperty(classProperty); - if (className == null) { - logger.info("ScaleFilterLayer.parseLayers(): Failed to locate property \"" + classProperty + "\""); - logger.info("ScaleFilterLayer.parseLayers(): Skipping layer \"" + layerName + "\""); - className = SinkLayer.class.getName(); - } - - try { - if (className.equals(SinkLayer.class.getName())) { - obj = SinkLayer.getSharedInstance(); - } else { - obj = Class.forName(className).newInstance(); - } - if (logger.isLoggable(Level.FINE)) { - logger.fine("Instantiated " + className); - } - } catch (Exception e) { - logger.info("Failed to instantiate \"" + className + "\": " + e); - obj = SinkLayer.getSharedInstance(); - } - - // create the layer and set its properties - if (obj instanceof Layer) { - Layer l = (Layer) obj; - l.setProperties(layerName, props); - l.addLayerStatusListener(this); - l.addInfoDisplayListener(this); - layers.addElement(l); - } - } - } - - /** - * Create the transition scales from a property value string. If there are N - * layers, there should be N-1 transition scales. - * - * @param prefix String - * @param props Properties - */ - protected void parseScales(String prefix, Properties props) { - StringTokenizer tok = null; - Vector layers = getLayers(); - int size = layers.size(); - if (size > 0) { - --size; - } - transitionScales = new float[size]; - - String scales = props.getProperty(prefix + transitionScalesProperty); - if (scales == null) { - logger.info("Failed to locate property \"" + transitionScalesProperty + "\""); - if (transitionScales.length > 0) { - transitionScales[0] = defaultTransitionScale; - } - for (int i = 1; i < transitionScales.length; i++) { - transitionScales[i] = transitionScales[i - 1] / 3; - } - return; - } - - try { - tok = new StringTokenizer(scales); - transitionScales[0] = (tok.hasMoreTokens()) ? new Float(tok.nextToken()).floatValue() : defaultTransitionScale; - } catch (NumberFormatException e) { - logger.info("ScaleFilterLayer.parseScales()1: " + e); - transitionScales[0] = defaultTransitionScale; - } - - if (tok != null) { - for (int i = 1; i < transitionScales.length; i++) { - try { - transitionScales[i] = - (tok.hasMoreTokens()) ? new Float(tok.nextToken()).floatValue() : transitionScales[i - 1] / 3; - } catch (NumberFormatException e) { - logger.info("ScaleFilterLayer.parseScales()2: " + e); - transitionScales[i] = transitionScales[i - 1] / 3; - } - } - } - } - - /** - * Implementing the ProjectionPainter interface. - */ - public synchronized void renderDataForProjection(Projection proj, java.awt.Graphics g) { - // This is a special case for a layer - It doesn't get told when sub-layers are done working. - // This may be the only time it finds out they are done (if part of SFL in background). - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - if (proj == null) { - logger.info("null projection!"); - return; - } else { - setTargetIndex(proj.getScale()); - Layer layer = getAppropriateLayer(); - layer.renderDataForProjection(proj, g); - } - } - - /** - * Calculate the index of the target layer. If there are N layers, there are - * N-1 transitionScales. The ith layer is chosen if the scale is greater - * than the ith transitionScale. - * - * @param scale the current map scale - * @return true if the targetIndex has changed as a result of the new scale. - */ - public boolean setTargetIndex(float scale) { - boolean changed = false; - float[] target = transitionScales; - - int i = 0; - if (target != null) { - for (i = 0; i < target.length; i++) { - if (scale > target[i]) { - break; - } - } - } - - if (targetIndex != i) { - changed = true; - } - targetIndex = i; - - if (logger.isLoggable(Level.FINE)) { - logger.fine("ScaleFilterLayer(" + getName() + ") targetIndex: " + targetIndex + ", changed: " + changed); - } - - return changed; - } - - /** - * Handles projection change notification events. Throws out old graphics, - * and requests new graphics from the spatial index based on the bounding - * rectangle of the new Projection. - * - * @param ev the new projection event - */ - public void projectionChanged(ProjectionEvent ev) { - // Lets the ScaleFilterLayer remember the projection, just in case. - setProjection(ev); - - Projection proj = ev.getProjection(); - // get the appropriate layer and invoke projectionChanged - Layer layer = configureAppropriateLayer(proj.getScale()); - - fireStatusUpdate(LayerStatusEvent.START_WORKING); - layer.projectionChanged(ev); - } - - protected Layer configureAppropriateLayer(float scale) { - Layer currentLayer = getAppropriateLayer(); - boolean changed = setTargetIndex(scale); - - // get the appropriate layer and invoke projectionChanged - Layer layer = getAppropriateLayer(); - if (changed) { - currentLayer.removeNotify(); - setPaletteTab(targetIndex); - remove(currentLayer); - - // This will handle the repaint() requests from the - // layer... - add(layer); - layer.addNotify(); - checkMouseMode(); - } - - return layer; - } - - /** - * Renders the scale-appropriate layer on the map. - * - * @param g a graphics context - */ - public void paint(Graphics g) { - getAppropriateLayer().paint(g); - fireStatusUpdate(LayerStatusEvent.FINISH_WORKING); - } - - /** - * Try to handle receiving LayerStatusEvents from child layers. May not - * always work, depending on what thread sends/receives this event - usually - * in the Swing thread, and the GUI can't always be updated as expected. - * - * @param evt LayerStatusEvent - */ - public void updateLayerStatus(LayerStatusEvent evt) { - fireStatusUpdate(evt); - } - - protected JPanel panel = null; - protected JTabbedPane tabs = null; - - /** - * Get the GUI (palettes) for the layers. The BufferedLayer actually creates - * a JTabbedPane holding the palettes for all of its layers, and also has a - * pane for itself that provides visibility control for the group layers. - */ - public Component getGUI() { - if (panel == null) { - - Iterator it = getLayers().iterator(); - panel = new JPanel(); - tabs = new JTabbedPane(); - - // bfPanel still needs controls for controlling scales, - // etc, showing which one is showing, etc., as well as - // some indication as which layer is currently active. - - JPanel bfPanel = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - bfPanel.setLayout(gridbag); - - tabs.addTab("Scale Filter Controls", bfPanel); - - JButton gotoButton = new JButton("Go to Active Layer Tab"); - gotoButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setPaletteTab(targetIndex); - } - }); - - c.gridy = 0; - gridbag.setConstraints(gotoButton, c); - bfPanel.add(gotoButton); - - while (it.hasNext()) { - Layer layer = it.next(); - Component layerGUI = layer.getGUI(); - if (layerGUI != null) { - tabs.addTab(layer.getName(), layerGUI); - } else { - tabs.addTab(layer.getName(), getEmptyGUIFiller(layer)); - } - } - panel.add(tabs); - } - setPaletteTab(targetIndex); - return panel; - } - - public Component getEmptyGUIFiller(Layer layer) { - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - - JPanel panel = new JPanel(); - panel.setLayout(gridbag); - - JLabel label = new JLabel("No properties available for"); - JLabel label2 = new JLabel("the " + layer.getName() + "."); - - c.gridwidth = GridBagConstraints.REMAINDER; - gridbag.setConstraints(label, c); - gridbag.setConstraints(label2, c); - panel.add(label); - panel.add(label2); - return panel; - } - - protected void setPaletteTab(int layerIndex) { - Vector layers = getLayers(); - if (layers.size() > layerIndex && tabs != null && layerIndex < tabs.getTabCount()) { - // +1 because the first tab is the ScaleFilterLayer tab - tabs.setSelectedIndex(layerIndex + 1); - } - } - - // ////////////////////////////// - // InfoDisplayListener Methods - // ////////////////////////////// - - /** - * Request to have a URL displayed in a Browser. - * - * @param event InfoDisplayEvent - */ - public void requestURL(InfoDisplayEvent event) { - fireRequestURL(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request to have a message displayed in a dialog window. - * - * @param event InfoDisplayEvent - */ - public void requestMessage(InfoDisplayEvent event) { - fireRequestMessage(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request to have an information line displayed in an application status - * window. - * - * @param event InfoDisplayEvent - */ - public void requestInfoLine(InfoDisplayEvent event) { - fireRequestInfoLine(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request that plain text or html text be displayed in a browser. - * - * @param event InfoDisplayEvent - */ - public void requestBrowserContent(InfoDisplayEvent event) { - fireRequestBrowserContent(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request that the MapBean cursor be set to a certain type. - * - * @param cursor java.awt.Cursor to set over the MapBean. - */ - public void requestCursor(java.awt.Cursor cursor) { - fireRequestCursor(cursor); - } - - /** - * Request a tool tip be shown. - * - * @param event The InfoDisplayEvent containing the text and requestor. - */ - public void requestShowToolTip(InfoDisplayEvent event) { - fireRequestToolTip(new InfoDisplayEvent(this, event.getInformation())); - } - - /** - * Request a tool tip be hidden. - */ - public void requestHideToolTip() { - fireHideToolTip(); - } - - /** - * Try to handle mouse events for the current layer. - */ - public synchronized MapMouseListener getMapMouseListener() { - return this; - } - - /** The current active mouse mode ID. */ - protected String mmID = null; - /** - * Flag to specify that the current layer wants events from the current - * active mouse mode. - */ - protected boolean coolMM = false; - /** - * The current MapMouseListener from the currently appropriate layer. - */ - protected MapMouseListener clmml = null; // current layer map mouse listener - - /** - * Set the coolMM flag, whenever the scale-appropriate layer changes, or if - * the active mouse mode changes. - */ - public synchronized boolean checkMouseMode() { - // check the current MouseMode with the current layer - coolMM = false; - Layer layer = getAppropriateLayer(); - MapMouseListener mml = layer.getMapMouseListener(); - setCurrentLayerMapMouseListener(mml); - if (mml != null) { - String[] mmsl = mml.getMouseModeServiceList(); - for (int i = 0; i < mmsl.length; i++) { - if (mmsl[i].intern() == mmID) { - coolMM = true; - break; - } - } - } - return coolMM; - } - - /** - * Pre-set the MapMouseListener to received events if the current layer - * wants them. - */ - public void setCurrentLayerMapMouseListener(MapMouseListener mml) { - clmml = mml; - } - - /** - * Get the MapMouseListener to received events if the current layer wants - * them. May be null, but coolMM should be false in that case. - */ - public MapMouseListener getCurrentLayerMapMouseListener() { - return clmml; - } - - /** - * Listen for changes to the active mouse mode and for any changes to the - * list of available mouse modes - */ - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName() == MouseDelegator.ActiveModeProperty) { - mmID = ((MapMouseMode) evt.getNewValue()).getID().intern(); - checkMouseMode(); - } - } - - /** - * Return a list of the modes that are interesting to the MapMouseListener. - * The source MouseEvents will only get sent to the MapMouseListener if the - * mode is set to one that the listener is interested in. Layers interested - * in receiving events should register for receiving events in "select" - * mode: - *
-     * 
-     * return new String[] { SelectMouseMode.modeID };
-     * 
-     * 
- * - * - * @return String[] of modeID's - * @see com.bbn.openmap.event.NavMouseMode#modeID - * @see com.bbn.openmap.event.SelectMouseMode#modeID - * @see com.bbn.openmap.event.NullMouseMode#modeID - */ - public String[] getMouseModeServiceList() { - HashSet mmsl = new HashSet(); - Iterator it = getLayers().iterator(); - while (it.hasNext()) { - Layer l = (Layer) it.next(); - MapMouseListener mml = l.getMapMouseListener(); - if (mml != null) { - String[] llist = mml.getMouseModeServiceList(); - for (int i = 0; i < llist.length; i++) { - mmsl.add(llist[i].intern()); - } - } - } - String[] rets = new String[mmsl.size()]; - return mmsl.toArray(rets); - } - - // Mouse Listener events - // ////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mousePressed(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mousePressed(e); - } else { - return false; - } - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseReleased(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseReleased(e); - } else { - return false; - } - } - - /** - * Invoked when the mouse has been clicked on a component. The listener will - * receive this event if it successfully processed - * mousePressed(), or if no other listener processes the event. - * If the listener successfully processes mouseClicked(), then - * it will receive the next mouseClicked() notifications that - * have a click count greater than one. - *

- * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseClicked(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseClicked(e); - } else { - return false; - } - - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseEntered(e); - } - - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseExited(e); - } - } - - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Invoked when a mouse button is pressed on a component and then dragged. - * The listener will receive these events if it successfully processes - * mousePressed(), or if no other listener processes the event. - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseDragged(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseDragged(e); - } else { - return false; - } - } - - /** - * Invoked when the mouse button has been moved on a component (with no - * buttons down). - * - * @param e MouseEvent - * @return true if the listener was able to process the event. - */ - public boolean mouseMoved(MouseEvent e) { - if (coolMM) { - return getCurrentLayerMapMouseListener().mouseMoved(e); - } else { - return false; - } - - } - - /** - * Handle a mouse cursor moving without the button being pressed. This event - * is intended to tell the listener that there was a mouse movement, but - * that the event was consumed by another layer. This will allow a mouse - * listener to clean up actions that might have happened because of another - * motion event response. - */ - public void mouseMoved() { - if (coolMM) { - getCurrentLayerMapMouseListener().mouseMoved(); - } - } - - /** - * Method for BeanContextChild interface. - */ - public void setBeanContext(BeanContext in_bc) - throws PropertyVetoException { - - for (Layer layer : getLayers()) { - // You don't actually want to add the layer to the - // BeanContext, because then the LayerHandler will pick it - // up and add it to the main list of layers. - - layer.connectToBeanContext(in_bc); - } - - super.setBeanContext(in_bc); - } - - public void dispose() { - try { - for (Layer layer : getLayers()) { - layer.disconnectFromBeanContext(); - } - } catch (PropertyVetoException pve) { - - } - - BeanContext bc = getBeanContext(); - if (bc instanceof MapHandler) { - MapHandler mh = (MapHandler) bc; - findAndUndo(mh.get(MouseDelegator.class)); - } - super.dispose(); - } - - /** - * MapHandler child methods, passing found objects to child layers. - */ - public void findAndInit(Object obj) { - super.findAndInit(obj); - - if (obj instanceof MouseDelegator) { - ((MouseDelegator) obj).addPropertyChangeListener(this); - } - - for (Layer layer : getLayers()) { - layer.findAndInit(obj); - } - } - - /** - * MapHandler child methods, passing removed objects to child layers. - */ - public void findAndUndo(Object obj) { - super.findAndUndo(obj); - - if (obj == null) { - return; - } - - if (obj instanceof MouseDelegator) { - ((MouseDelegator) obj).removePropertyChangeListener(this); - } - - for (Layer layer : getLayers()) { - layer.findAndUndo(obj); - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/daynight/DayNightLayer.java b/src/openmap/com/bbn/openmap/layer/daynight/DayNightLayer.java deleted file mode 100644 index 723fd6ab8..000000000 --- a/src/openmap/com/bbn/openmap/layer/daynight/DayNightLayer.java +++ /dev/null @@ -1,533 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/daynight/DayNightLayer.java,v $ -// $RCSfile: DayNightLayer.java,v $ -// $Revision: 1.12 $ -// $Date: 2006/04/07 17:36:01 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.daynight; - -/* Java Core */ -import java.awt.Color; -import java.awt.event.ActionListener; -import java.util.Properties; - -import javax.swing.Timer; - -import com.bbn.openmap.I18n; -import com.bbn.openmap.MoreMath; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.proj.Cylindrical; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * The DayNightLayer is a layer that draws the day/Night terminator on - * the map. When the layer is re-projected, it figures out the - * brightest point on the earth (closest to the sun), and creates an - * image that has daytime pixels clear and the nighttime pixels - * shaded. There are a couple of options available for the layer. The - * terminator can be faded from light to dark, and the width of the - * fading can be adjusted. The color of the shading can be changed. - * The shading can reflect the current time, or be set to display the - * shading of a specified time. A time interval can be set to have the - * layer automatically update at regular intervals. - * - *

- * The openmap.properties file can control the layer with the - * following settings:

- * 
- *  # These are all optional, and can be omitted if you want to use the defaults.
- *  # draw terminator as poly (faster calculation than image,
- *  # defaults to true).
- *  daynight.doPolyTerminator=true
- *  # number of vertices for polygon terminator line.  this is only valid
- *  # if doPolyTerminator is true...
- *  daynight.terminatorVerts=360
- *  # termFade - the distance of the transition of fade, as a percentage of PI.
- *  daynight.termFade=.1
- *  # currentTime - true to display the shading at the computer's current time.
- *  daynight.currentTime=true
- *  # overlayTime - time, in milliseconds from java/unix epoch, to set the layer
- *  # time being displayed.  currentTime has to be false for this to be used.
- *  daynight.overlayTime=919453689000
- *  # updateInterval - time in milliseconds between updates.  currentTime has to be
- *  # true for this to be used.
- *  daynight.updateInterval=300000
- *  # Color of the shading (32bit Hex ARGB)
- *  daynight.nighttimeColor=64000000
- *  
- * 

In addition, you can get this layer to work with the - * OpenMap viewer by editing your openmap.properties file:

- * 
- *  # layers
- *  openmap.layers=daynight ...
- *  # class
- *  daynight.class=com.bbn.openmap.layer.daynight.DayNightLayer
- *  # name
- *  daynight.prettyName=Day/Night Shading
- *  
- * 
- * - */ -public class DayNightLayer extends OMGraphicHandlerLayer implements - ProjectionListener, ActionListener { - /** - * Default value of fade to the terminator line, set to .10f. This - * means that the last 10% of the horizon will be faded out. - */ - public static final float DEFAULT_TERM_FADE = .10f; - /** - * Default update interval, which is never - updates occur on - * re-projections. - */ - public static final int DO_NOT_UPDATE = -1; - - /** The color of daytime - default is white and clear. */ - protected Color daytimeColor = new Color(0x00FFFFFF, true); - /** the color of darkness - default is black. */ - protected Color nighttimeColor = new Color(0x7F000000, true); - - /** - * Percentage of the distance from the horizon to the brightest - * point to start fading to darkness. Expected to be between 0.0 - * and 0.5. - */ - protected float termFade = DEFAULT_TERM_FADE; - /** - * If true, the layer will set the darkness according to the - * current time. - */ - protected boolean currentTime = true; - /** - * The time used to create the layer, in milliseconds from - * java/unix epoch. - */ - protected long overlayTime = 0; - /** - * Update interval to automatically update the layer, in - * milli-seconds - */ - protected int updateInterval = 300000; - /** Update timer. */ - protected Timer timer; - - /** - * Create the terminator line as a polygon. - */ - protected boolean doPolyTerminator = true; - - /** - * The number of vertices of the polygon terminator line. - */ - protected int terminatorVerts = 360; - - /////// Properties - public static final String DaytimeColorProperty = "daytimeColor"; - public static final String NighttimeColorProperty = "nighttimeColor"; - public static final String TermFadeProperty = "termFade"; - public static final String CurrentTimeProperty = "useCurrentTime"; - public static final String OverlayTimeProperty = "overlayTime"; - public static final String UpdateIntervalProperty = "updateInterval"; - public static final String DoPolyTerminatorProperty = "doPolyTerminator"; - public static final String TerminatorVertsProperty = "terminatorVerts"; - - /** - * The default constructor for the Layer. All of the attributes - * are set to their default values. - */ - public DayNightLayer() { - setName("Day-Night"); - } - - /** - * The properties and prefix are managed and decoded here, for the - * standard uses of the DayNightLayer. - * - * @param prefix string prefix used in the properties file for - * this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - overlayTime = PropUtils.longFromProperties(properties, prefix - + OverlayTimeProperty, overlayTime); - if (overlayTime <= 0) { - currentTime = true; - } - - currentTime = PropUtils.booleanFromProperties(properties, prefix - + CurrentTimeProperty, currentTime); - - updateInterval = PropUtils.intFromProperties(properties, prefix - + UpdateIntervalProperty, updateInterval); - - if (updateInterval > 0) { - timer = new Timer(updateInterval, this); - } - - termFade = PropUtils.floatFromProperties(properties, prefix - + TermFadeProperty, termFade); - - if (termFade < 0 || termFade >= .5) { - Debug.output("DayNightLayer: termFade funky value ignored."); - termFade = DEFAULT_TERM_FADE; - } - - daytimeColor = (Color) PropUtils.parseColorFromProperties(properties, - prefix + DaytimeColorProperty, - daytimeColor); - nighttimeColor = (Color) PropUtils.parseColorFromProperties(properties, - prefix + NighttimeColorProperty, - nighttimeColor); - - doPolyTerminator = PropUtils.booleanFromProperties(properties, prefix - + DoPolyTerminatorProperty, doPolyTerminator); - terminatorVerts = PropUtils.intFromProperties(properties, prefix - + TerminatorVertsProperty, terminatorVerts); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + OverlayTimeProperty, Long.toString(overlayTime)); - props.put(prefix + CurrentTimeProperty, - new Boolean(currentTime).toString()); - props.put(prefix + UpdateIntervalProperty, - Integer.toString(updateInterval)); - props.put(prefix + TermFadeProperty, Float.toString(termFade)); - props.put(prefix + DaytimeColorProperty, - Integer.toHexString(daytimeColor.getRGB())); - props.put(prefix + NighttimeColorProperty, - Integer.toHexString(nighttimeColor.getRGB())); - props.put(prefix + DoPolyTerminatorProperty, - new Boolean(doPolyTerminator).toString()); - props.put(prefix + TerminatorVertsProperty, - Integer.toString(terminatorVerts)); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - String interString; - - interString = i18n.get(DayNightLayer.class, - OverlayTimeProperty, - I18n.TOOLTIP, - "The time used to create the layer, in milliseconds from java/unix epoch (leave empty for current time)."); - props.put(OverlayTimeProperty, interString); - interString = i18n.get(DayNightLayer.class, - OverlayTimeProperty, - OverlayTimeProperty); - props.put(OverlayTimeProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, - CurrentTimeProperty, - I18n.TOOLTIP, - "If true, the layer will set the darkness according to the current time."); - props.put(CurrentTimeProperty, interString); - interString = i18n.get(DayNightLayer.class, - CurrentTimeProperty, - CurrentTimeProperty); - props.put(CurrentTimeProperty + LabelEditorProperty, interString); - props.put(CurrentTimeProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, - UpdateIntervalProperty, - I18n.TOOLTIP, - "Update interval to automatically update the layer, in milli-seconds."); - props.put(UpdateIntervalProperty, interString); - interString = i18n.get(DayNightLayer.class, - UpdateIntervalProperty, - UpdateIntervalProperty); - props.put(UpdateIntervalProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, - TermFadeProperty, - I18n.TOOLTIP, - "Percentage of the distance from the horizon to the brightest point to start fading to darkness, 0.0 to 0.5."); - props.put(TermFadeProperty, interString); - interString = i18n.get(DayNightLayer.class, - TermFadeProperty, - TermFadeProperty); - props.put(TermFadeProperty + LabelEditorProperty, interString); - - interString = i18n.get(DayNightLayer.class, - DaytimeColorProperty, - I18n.TOOLTIP, - "Color for the daytime area, if polygon terminator isn't used."); - props.put(DaytimeColorProperty, interString); - interString = i18n.get(DayNightLayer.class, - DaytimeColorProperty, - DaytimeColorProperty); - props.put(DaytimeColorProperty + LabelEditorProperty, interString); - props.put(DaytimeColorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, - NighttimeColorProperty, - I18n.TOOLTIP, - "Color for the nighttime area."); - props.put(NighttimeColorProperty, interString); - interString = i18n.get(DayNightLayer.class, - NighttimeColorProperty, - NighttimeColorProperty); - props.put(NighttimeColorProperty + LabelEditorProperty, interString); - props.put(NighttimeColorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, - DoPolyTerminatorProperty, - I18n.TOOLTIP, - "Render with polygon instead of image (it's faster)."); - props.put(DoPolyTerminatorProperty, interString); - interString = i18n.get(DayNightLayer.class, - DoPolyTerminatorProperty, - DoPolyTerminatorProperty); - props.put(DoPolyTerminatorProperty + LabelEditorProperty, interString); - props.put(DoPolyTerminatorProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - - interString = i18n.get(DayNightLayer.class, - TerminatorVertsProperty, - I18n.TOOLTIP, - "Number of vertices of the polygon terminator (more is smoother)."); - props.put(TerminatorVertsProperty, interString); - interString = i18n.get(DayNightLayer.class, - TerminatorVertsProperty, - TerminatorVertsProperty); - props.put(TerminatorVertsProperty + LabelEditorProperty, interString); - - props.put(initPropertiesProperty, CurrentTimeProperty + " " - + OverlayTimeProperty + " " + UpdateIntervalProperty + " " - + NighttimeColorProperty + " " + DoPolyTerminatorProperty + " " - + TerminatorVertsProperty + " " + DaytimeColorProperty + " " - + TermFadeProperty + " " + RemovableProperty + " " - + AddAsBackgroundProperty); - - return props; - } - - /** - * Handle an ActionEvent from the Timer. - * - * @param ae action event from the timer. - */ - public void actionPerformed(java.awt.event.ActionEvent ae) { - super.actionPerformed(ae); - if (Debug.debugging("daynight")) { - Debug.output(getName() + "| updating image via timer..."); - } - doPrepare(); - } - - /** - * Create the OMGraphic that acts as an overlay showing the - * day/night terminator. The brightest spot on the earth is - * calculated, and then each pixel is inverse projected to find - * out its coordinates. Then the great circle distance is - * calculated. The terminator is assumed to be the great circle - * where all the points are PI/2 away from the bright point. If - * the termFade variable is set, then the difference in color over - * the terminator is feathered, on equal amount of the terminator. - * - * @param projection the projection of the screen, - * @return OMGraphic containing image to use for the layer. The - * image has been projected. - */ - protected OMGraphic createImage(Projection projection) { - - if (currentTime) - overlayTime = System.currentTimeMillis(); - - if (Debug.debugging("daynight")) { - Debug.output("DayNightLayer: Calculating sun position at time " - + Long.toString(overlayTime)); - } - - LatLonPoint brightPoint = SunPosition.sunPosition(overlayTime); - - Debug.message("daynight", "DayNightLayer: Calculated sun position"); - - // Do a fast and relatively inexpensive calculation of the - // terminator. NOTE: for non-cylindrical projections we don't - // create a full-hemisphere circle so that we don't get - // flip-rendering problem... - if (doPolyTerminator) { - Debug.message("daynight", - "DayNightLayer: Creating polygon terminator"); - LatLonPoint darkPoint = brightPoint.getPoint(Math.PI, Math.PI / 4); - OMCircle circle = new OMCircle((float)darkPoint.getY(), (float)darkPoint.getX(), (projection instanceof Cylindrical) ? 90f - : 89.0f,//HACK - Length.DECIMAL_DEGREE, terminatorVerts); - circle.setPolarCorrection(true); - circle.setFillPaint(nighttimeColor); - circle.setLinePaint(nighttimeColor); - circle.generate(projection); - Debug.message("daynight", - "DayNightLayer: Done creating polygon terminator"); - return circle; - } - - int width = projection.getWidth(); - int height = projection.getHeight(); - int[] pixels = new int[width * height]; - - OMRaster ret = new OMRaster((int) 0, (int) 0, width, height, pixels); - - Debug.message("daynight", getName() - + "|createImage: Center of bright spot lat= " - + brightPoint.getLatitude() + ", lon= " - + brightPoint.getLongitude()); - - // Light is clear and/or white - int light = daytimeColor.getRGB(); - - // Allocate the memory here for the testPoint - LatLonPoint testPoint = new LatLonPoint.Float(0f, 0f); - // great circle distance between the bright point and each - // pixel. - double distance; - - // Set the darkeness value - int dark = nighttimeColor.getRGB();// ARGB - int darkness = dark >>> 24;// darkness alpha - int value; - - // Calculate the fae limits around the terminator - float upperFadeLimit = (float) (MoreMath.HALF_PI * (1.0 + termFade)); - float lowerFadeLimit = (float) (MoreMath.HALF_PI * (1.0 - termFade)); - int fadeColorValue = 0x00FFFFFF & (dark); // RGB - - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - - projection.inverse(i, j, testPoint); - distance = brightPoint.distance(testPoint); - - if (distance > upperFadeLimit) { - pixels[j * width + i] = dark; - } else if (distance > lowerFadeLimit) { - value = (int) (darkness * (1 - ((upperFadeLimit - distance) / (upperFadeLimit - lowerFadeLimit)))); - value <<= 24; - pixels[j * width + i] = fadeColorValue | value; - } else { - pixels[j * width + i] = light; - } - } - } - - ret.generate(projection); - return ret; - } - - /** - * Prepares the graphics for the layer. This is where the - * getRectangle() method call is made on the location. - *

- * Occasionally it is necessary to abort a prepare call. When this - * happens, the map will set the cancel bit in the LayerThread, - * (the thread that is running the prepare). If this Layer needs - * to do any cleanups during the abort, it should do so, but - * return out of the prepare asap. - * - */ - public synchronized OMGraphicList prepare() { - - OMGraphicList list = getList(); - if (list == null) { - list = new OMGraphicList(); - } else { - list.clear(); - } - - Debug.message("basic", getName() + "|DayNightLayer.prepare(): doing it"); - - OMGraphic ras = createImage(getProjection()); - if (timer != null) - timer.restart(); - list.add(ras); - - return list; - } - - /** - * Get the time of the overlay. - */ - public long getOverlayTime() { - return overlayTime; - } - - /** - * Set the time for the overlay. - */ - public void setOverlayTime(long ot) { - overlayTime = ot; - currentTime = false; - doPrepare(); - } - - /** - * Returns whether the layer will set the overlayTime to the time - * the image is created. - */ - public boolean getCurrentTime() { - return currentTime; - } - - /** - * Set whether the layer should set the overlayTime to the time - * the image is created. If the time is being set to reflect a - * time other than the current time, this needs to be set to - * false. It actually is, if you manually set the overlay time. - */ - public void setCurrentTime(boolean ct) { - currentTime = ct; - } - - /** - * Get the timer being used for automatic updates. May be null if - * a timer is not set. - */ - public Timer getTimer() { - return timer; - } - - /** - * If you want the layer to update itself at certain intervals, - * you can set the timer to do that. Set it to null to disable it. - */ - public void setTimer(Timer t) { - timer = t; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageManager.java b/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageManager.java deleted file mode 100644 index e64276244..000000000 --- a/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageManager.java +++ /dev/null @@ -1,545 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/dted/DTEDCoverageManager.java,v $ -// $RCSfile: DTEDCoverageManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2005/12/09 21:09:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.dted; - -/* Java Core */ -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.wanderer.Wanderer; -import com.bbn.openmap.util.wanderer.WandererCallback; - -/** - * A DTEDCoverageManager knows how to look at DTED data and figure out what - * coverage is available. - */ -public class DTEDCoverageManager extends OMGraphicList implements PropertyConsumer { - - protected I18n i18n = Environment.getI18n(); - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.dted.DTEDCoverageManager"); - - protected String[] paths; - - /** The default line color for level 0. */ - public final static String DEFAULT_LEVEL0_COLOR_STRING = "CE4F3F"; // redish - /** The default line color for level 1. */ - public final static String DEFAULT_LEVEL1_COLOR_STRING = "339159"; // greenish - /** The default line color for level 2. */ - public final static String DEFAULT_LEVEL2_COLOR_STRING = "0C75D3"; // bluish - - public final static String COVERAGE_FILE_PROPERTY = "coverageFile"; - - /** Coverage for level 0, 1, 2 frames */ - protected boolean[][][] coverage = null; - /** - * CoverageDataFile object handling pre-cached coverage - */ - protected CoverageDataFile coverageFile = null; - - protected DrawingAttributes[] attributes = null; - protected OMGraphicList[] levelRects = null; - - public DTEDCoverageManager(String[] paths) { - this.paths = paths; - - attributes = new DrawingAttributes[3]; - attributes[0] = DrawingAttributes.getDefaultClone(); - attributes[0].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL0_COLOR_STRING)); - attributes[1] = DrawingAttributes.getDefaultClone(); - attributes[1].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL1_COLOR_STRING)); - attributes[2] = DrawingAttributes.getDefaultClone(); - attributes[2].setLinePaint(PropUtils.parseColor(DEFAULT_LEVEL2_COLOR_STRING)); - - levelRects = new OMGraphicList[3]; - levelRects[0] = new OMGraphicList(); - levelRects[1] = new OMGraphicList(); - levelRects[2] = new OMGraphicList(); - } - - public void reset() { - coverage = null; - clear(); - } - - /** - * The method that cycles through all the paths, looking for the frames. - * This takes time, so it's only done when a coverage file can't be found. - * - * @param paths paths to the level 0, 1 and 2 dted root directory. - */ - public boolean[][][] checkOutCoverage(String[] paths) { - - if (paths == null || paths.length == 0) { - logger.warning("No paths for DTED data given."); - return null; - } - - logger.fine("checking out DTED at paths:"); - for (int d1 = 0; d1 < paths.length; d1++) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(" " + paths[d1]); - } - if (!BinaryFile.exists(paths[d1])) { - paths[d1] = null; - logger.fine(" - path invalid, ignoring."); - } - } - - CoverageWandererCallback callback = new CoverageWandererCallback(); - Wanderer wanderer = new Wanderer(callback); - - for (int pathNum = 0; pathNum < paths.length; pathNum++) { - wanderer.handleEntry(new File(paths[pathNum])); - } - - return callback.getCoverage(); - } - - /** - * Method organizes the query based on the projection, and returns the - * applicable rectangles representing the frame coverage. If the coverage - * spans over the date line, then two queries are performed, one for each - * side of the date line. - * - * @param proj the projection of the screen - * @return an array of lists, one for each level of dted data. - */ - public OMGraphicList getCoverageRects(Projection proj) { - - if (coverage == null) { - - if (coverageFile != null) { - coverage = coverageFile.readCoverage(); - } - - if (coverage == null) { - logger.fine("Scanning for frames - This could take several minutes!"); - coverage = checkOutCoverage(paths); - - if (coverageFile != null) { - coverageFile.writeFile(coverage); - } - } - } - - if (isEmpty()) { - getCoverageRects(-180, -90, 179, 89, OMGraphic.LINETYPE_RHUMB, proj); - } else { - generate(proj); - } - return this; - } - - /** - * Get a percentage value of how much of the map is covered for a - * projection. - * - * @param proj - * @return float[] with percentages, float[0] is level 0 coverage, 1 is - * level 1, 2 is level 2. - */ - public float[] getCoverage(Projection proj) { - float[] ret = new float[3]; - if (coverage != null) { - Point pnt1 = new Point(); - Point pnt2 = new Point(); - int height = proj.getHeight(); - int width = proj.getWidth(); - // Number frames possible on map - int total = 0; - for (int x = -180; x < 180; x++) { - for (int y = -90; y < 89; y++) { - proj.forward((float) y, (float) x, pnt1); - proj.forward((float) (y + 1), (float) (x + 1), pnt2); - - double x1 = pnt1.getX(); - double y1 = pnt1.getY(); - double x2 = pnt2.getX(); - double y2 = pnt2.getY(); - - boolean someX = (x1 >= 0 && x1 <= width) || (x2 >= 0 && x2 <= width); - boolean someY = (y1 >= 0 && y1 <= height) || (y2 >= 0 && y2 <= height); - - boolean onMap = someX && someY; - - if (onMap) { - int xIndex = x + 180; - int yIndex = y + 90; - total++; - if (coverage[0][yIndex][xIndex]) - ret[0] += 1f; - if (coverage[1][yIndex][xIndex]) - ret[1] += 1f; - if (coverage[2][yIndex][xIndex]) - ret[2] += 1f; - } - } - } - - logger.info("Total frames: " + total + " " + ret[0] + ", " + ret[1] + ", " + ret[2]); - - ret[0] = ret[0] / total * 100f; - ret[1] = ret[1] / total * 100f; - ret[2] = ret[2] / total * 100f; - } - return ret; - } - - /** - * Method looks at the coverage arrays, and returns the applicable - * rectangles representing the frame coverages. - * - * @param startx the western-most longitude. - * @param starty the southern-most latitude. - * @param endx the eastern-most longitude. - * @param endy the northern-most latitude. - * @param lineType the type of line to use on the rectangles - Cylindrical - * projections can use straight lines, but other projections should - * use Rhumb lines. - * @return an array of lists, one for each level of dted data. - */ - public OMGraphicList getCoverageRects(int startx, int starty, int endx, int endy, int lineType, - Projection proj) { - clear(); - OMRect rect; - - for (int level = 0; level < 3; level++) { - - OMGraphicList rectangles = levelRects[level]; - rectangles.clear(); - rectangles.setVague(true); - - for (int lat = starty; lat <= endy && lat < 90; lat++) { - for (int lon = startx; lon <= endx && lon < 180; lon++) { - if (coverage[level][lat + 90][lon + 180]) { - - double offset = level * .1; - double up = lat + offset; - double left = lon + offset; - double down = lat + 1.0 - offset; - double right = lon + 1.0 - offset; - - rect = new OMRect(up, left, down, right, lineType); - attributes[level].setTo(rect); - rect.generate(proj); - rectangles.add(rect); - } - } - } - add(rectangles); - } - - return this; - } - - ////// PropertyConsumer methods - - protected String prefix; - - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - for (DrawingAttributes atts : attributes) { - atts.getProperties(getList); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - if (coverageFile != null) { - getList.put(prefix + COVERAGE_FILE_PROPERTY, coverageFile.getAbsolutePath()); - } - - if (paths != null) { - StringBuilder sBuilder = new StringBuilder(); - for (String path : paths) { - if (sBuilder.length() != 0) { - sBuilder.append(";"); - } - sBuilder.append(path); - } - getList.put(prefix + DTEDLayer.DTEDPathsProperty, sBuilder.toString()); - } - - return getList; - } - - public Properties getPropertyInfo(Properties list) { - return list; - } - - public String getPropertyPrefix() { - return prefix; - } - - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - public void setProperties(String prefix, Properties setList) { - setPropertyPrefix(prefix); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - attributes[0].setProperties(prefix + "0", setList); - attributes[1].setProperties(prefix + "1", setList); - attributes[2].setProperties(prefix + "2", setList); - - String coverageFileString = setList.getProperty(prefix + COVERAGE_FILE_PROPERTY); - if (coverageFileString != null) { - coverageFile = new CoverageDataFile(coverageFileString); - } - } - - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - ////// end of PropertyConsumer methods - - /** - * @return the coverageFile - */ - public CoverageDataFile getCoverageFile() { - return coverageFile; - } - - /** - * @param coverageFile the coverageFile to set - */ - public void setCoverageFile(CoverageDataFile coverageFile) { - this.coverageFile = coverageFile; - } - - protected JPanel panel; - - public Component getGUI(final OMGraphicHandlerLayer layer) { - if (panel == null) { - panel = new JPanel(); - - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - c.gridx = 0; - panel.setLayout(gridbag); - - ActionListener aListener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - int level = Integer.parseInt(ae.getActionCommand()); - levelRects[level].setVisible(((JCheckBox) ae.getSource()).isSelected()); - layer.doPrepare(); - } - }; - - for (int level = 0; level < 3; level++) { - - JPanel pane = new JPanel(); - String interString = i18n.get(DTEDCoverageManager.class, "level" + level - + "title", "Level " + level + ": "); - pane.add(new JLabel(interString)); - String showString = i18n.get(DTEDCoverageManager.class, "show", "Show"); - JCheckBox jcb = new JCheckBox(showString, levelRects[level].isVisible()); - jcb.addActionListener(aListener); - jcb.setActionCommand(Integer.toString(level)); - pane.add(jcb); - pane.add(attributes[level].getGUI()); - c.gridy = level; - gridbag.setConstraints(pane, c); - panel.add(pane); - } - } - - return panel; - } - - /** - * WandererCallback class that provides coverage array based on existance of - * DTED frames. - * - * @author dietrick - */ - static class CoverageWandererCallback implements WandererCallback { - - boolean[][][] cov; - protected int curLon = Integer.MAX_VALUE; - - CoverageWandererCallback() { - cov = new boolean[3][180][360]; - } - - public boolean handleDirectory(File directory) { - String name = directory.getName().toLowerCase(); - char hemi = name.charAt(0); - if (name.length() == 4 && (hemi == 'e' || hemi == 'w')) { - try { - // Get the longitude index right, use hemi to set the +/-, - // and - // then add 180 to get indexy. - curLon = (hemi == 'w' ? -1 : 1) * Integer.parseInt(name.substring(1)) + 180; - - } catch (NumberFormatException nfe) { - curLon = Integer.MAX_VALUE; - logger.warning("Can't process " + name); - } - } - return true; - } - - public boolean handleFile(File file) { - if (curLon != Integer.MAX_VALUE) { - String name = file.getName().toLowerCase(); - char hemi = name.charAt(0); - char level = name.charAt(name.length() - 1); - if (name.length() == 7 && name.charAt(name.length() - 4) == '.' - && (hemi == 'n' || hemi == 's')) { - - try { - int curLat = (hemi == 's' ? -1 : 1) - * Integer.parseInt(name.substring(1, name.length() - 4)) + 90; - - if (level == '0') { - cov[0][curLat][curLon] = true; - } else if (level == '1') { - cov[1][curLat][curLon] = true; - } else if (level == '2') { - cov[2][curLat][curLon] = true; - } - - } catch (NumberFormatException nfe) { - logger.warning("Can't process " + name); - } - - } - - } - - return true; - } - - boolean[][][] getCoverage() { - return cov; - } - - } - - /** - * Inner class that handles reading and writing coverage cache file. - * - * @author dietrick - */ - public static class CoverageDataFile { - - File coverageFile = null; - - public CoverageDataFile(String path) { - coverageFile = new File(path); - } - - public boolean exists() { - return coverageFile != null && coverageFile.exists(); - } - - public String getAbsolutePath() { - if (coverageFile != null) { - return coverageFile.getAbsolutePath(); - } - - return ""; - } - - public boolean[][][] readCoverage() { - if (exists()) { - - try { - RandomAccessFile raf = new RandomAccessFile(coverageFile, "rw"); - - boolean[][][] coverage = new boolean[3][180][360]; - for (int level = 0; level < 3; level++) { - for (int y = 0; y < 180; y++) { - for (int x = 0; x < 360; x++) { - coverage[level][y][x] = raf.readBoolean(); - } - } - } - raf.close(); - return coverage; - } catch (FileNotFoundException e) { - - } catch (IOException ioe) { - - } - } - return null; - } - - public void writeFile(boolean[][][] coverage) { - try { - RandomAccessFile raf = new RandomAccessFile(coverageFile, "rw"); - - for (int level = 0; level < 3; level++) { - for (int y = 0; y < 180; y++) { - for (int x = 0; x < 360; x++) { - raf.writeBoolean(coverage[level][y][x]); - } - } - } - raf.close(); - } catch (FileNotFoundException e) { - - } catch (IOException ioe) { - - } catch (ArrayIndexOutOfBoundsException aioobe) { - - } - } - - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/event/CSVEventImporter.java b/src/openmap/com/bbn/openmap/layer/event/CSVEventImporter.java deleted file mode 100644 index 4ea265cc5..000000000 --- a/src/openmap/com/bbn/openmap/layer/event/CSVEventImporter.java +++ /dev/null @@ -1,532 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.event; - -import java.net.MalformedURLException; -import java.net.URL; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.ImageIcon; -import javax.swing.SwingConstants; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.event.OMEvent; -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.layer.location.LocationHandler; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.time.TemporalOMGraphic; -import com.bbn.openmap.omGraphics.time.TemporalOMGraphicList; -import com.bbn.openmap.omGraphics.time.TemporalOMPoint; -import com.bbn.openmap.omGraphics.time.TemporalOMScalingIcon; -import com.bbn.openmap.omGraphics.time.TemporalPoint; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.time.TimeBounds; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * A data importer for the EventLayer. The location file should contain information about objects that will be moving on - * the map. The activity file will contain information about where and when the objects moved. Sample properties: - * - *

- *    eventLayer.class=com.bbn.openmap.layer.time.EventLayer
- *    eventLayer.importer=com.bbn.openmap.layer.time.CSVEventImporter
- *    eventLayer.prettyName=Test Event
- *    eventLayer.locationFile=org-list.csv
- *    eventLayer.locationFileHasHeader=true
- *    eventLayer.nameIndex=0
- *    eventLayer.iconIndex=5
- *    eventLayer.activityFile=org-activities.csv
- *    eventLayer.activityFileHasHeader=true
- *    eventLayer.activityNameIndex=1
- *    eventLayer.latIndex=9
- *    eventLayer.lonIndex=10
- *    eventLayer.timeFormat=d-MMM-yyyy HH:mm
- *    eventLayer.timeIndex=7
- *    # If no icon defined, used for location markers edge.
- *    eventLayer.lineColor=aaaaaa33
- *    # If no icon defined, used for location markers fill.
- *    eventLayer.fillColor=aaaaaa33
- * 
- * - * @author dietrick - */ -public class CSVEventImporter extends OMComponent implements EventImporter { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.event.CSVEventImporter"); - - /** locationFile */ - public final static String LocationFileProperty = "locationFile"; - /** locationFileHasHeader */ - public final static String LocationHeaderProperty = "locationFileHasHeader"; - /** iconIndex */ - public final static String IconIndexProperty = "iconIndex"; - /** nameIndex */ - public final static String NameIndexProperty = "nameIndex"; - - /** activityFile */ - public final static String ActivityFileProperty = "activityFile"; - /** activityNameIndex */ - public final static String ActivityNameIndexProperty = "activityNameIndex"; - /** activityFileHasHeader */ - public final static String ActivityHeaderProperty = "activityFileHasHeader"; - /** latIndex */ - public final static String LatIndexProperty = "latIndex"; - /** lonIndex */ - public final static String LonIndexProperty = "lonIndex"; - /** timeIndex */ - public final static String TimeIndexProperty = "timeIndex"; - /** eastIsNeg */ - public final static String EastIsNegProperty = "eastIsNeg"; - /** showNames */ - public final static String ShowNamesProperty = LocationHandler.ShowNamesProperty; - /** defaultURL */ - public final static String DefaultIconURLProperty = "defaultURL"; - /** timeFormat */ - public final static String TimeFormatProperty = "timeFormat"; - /** - * TimeFormat default is similar to IETF standard date syntax: - * "Sat, 12 Aug 1995 13:30:00 GMT" represented by (EEE, d MMM yyyy HH:mm:ss - * z), except for the local timezone. - */ - protected SimpleDateFormat timeFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); - - protected String locationFile; - protected boolean locationHeader = true; - protected int nameIndex; - protected int iconIndex; - protected String activityFile; - protected boolean activityHeader = true; - protected int activityNameIndex; - protected int latIndex; - protected int lonIndex; - protected int timeIndex; - protected boolean eastIsNeg = false; - protected int orientation = SwingConstants.HORIZONTAL; - - /** Icon URL for points to use as default. May be null. */ - protected String defaultIconURL; - protected boolean showNames = false; - protected DrawingAttributes drawingAttributes = DrawingAttributes.getDefaultClone(); - - public CSVEventImporter() { - - } - - /** - * Read the data files and construct the TemporalOMGraphics. You also need - * to create TimeBounds, keep track of the time stamps from the data source, - * and set the new TimeBounds on the EventLayer before returning from this - * method. If you want to set the DataBounds on the layer, in order for the - * view menu to have a selection for the area of interest, fetch the - * DataBounds object and set it accordingly while you are in this method. - *

- * Read the data files and construct the TemporalOMGraphics. There are four - * things you need to do in this method. - *

    - *
  • Create an TemporalOMGraphicList, add TemporalOMGraphics, return it. - *
  • Set a new TimeBounds object on the callback EventLayer when all the - * timestamp range is known. - *
  • Add OMEvents to the callback.events list, one for each TemporalPoint - * created. - *
  • Add locations to callback's DataBounds (callback.getDataBounds()). - *
- */ - public synchronized TemporalOMGraphicList createData(EventLayer callback) { - TemporalOMGraphicList list = new TemporalOMGraphicList(); - Hashtable library = new Hashtable(); - Hashtable iconLibrary = new Hashtable(); - - // BOTH IMPORTANT - DataBounds dataBounds = callback.getDataBounds(); - TimeBounds timeBounds = new TimeBounds(); - - // Create TemporalOMGraphics, to associate events to - if (locationFile != null && nameIndex != -1) { - logger.fine("Reading location file..."); - try { - CSVFile locations = new CSVFile(locationFile); - locations.loadData(); - Iterator> records = locations.iterator(); - while (records.hasNext()) { - String name = null; - String iconName = null; - ImageIcon icon = null; - Vector record = records.next(); - - if (record.isEmpty()) { - continue; - } - - name = (String) record.elementAt(nameIndex); - - if (iconIndex != -1) { - iconName = (String) record.elementAt(iconIndex); - - icon = iconLibrary.get(iconName); - - if (icon == null) { - URL icURL = PropUtils.getResourceOrFileOrURL(iconName); - if (icURL != null) { - icon = new ImageIcon(icURL); - if (icon != null) { - iconLibrary.put(iconName, icon); - } - } - } - } - - if (name != null) { - TemporalOMGraphic location; - if (icon == null) { - location = new TemporalOMPoint(name, OMGraphic.RENDERTYPE_LATLON, true); - } else { - location = new TemporalOMScalingIcon(name, OMGraphic.RENDERTYPE_LATLON, true, icon, 4000000); - } - // location.setShowName(showNames); - drawingAttributes.setTo(location); - library.put(name.intern(), location); - list.add(location); - } else { - logger.warning("no name to use to create location: " - + name); - } - } - } catch (MalformedURLException murle) { - logger.warning("problem finding the location file: " - + locationFile); - return list; - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.warning("problem with parsing location file: " - + locationFile); - if (logger.isLoggable(Level.FINE)) { - logger.fine("The problem is with one of the indexes into the file: \n" - + aioobe.getMessage()); - aioobe.printStackTrace(); - } - } catch (NullPointerException npe) { - logger.warning("null pointer exception, most likely a problem finding the organization data file"); - } - } else { - logger.warning("Location file (" + locationFile - + ") not configured."); - return list; - } - - // OK, got the TemporalOMGraphics built up, need to fill up the - // events - // - if (activityFile != null && activityNameIndex != -1 && latIndex != -1 - && lonIndex != -1 && timeIndex != -1) { - logger.fine("Reading activity file..."); - - try { - CSVFile activities = new CSVFile(activityFile); - activities.loadData(); // numbers as strings == false - Iterator> records = activities.iterator(); - while (records.hasNext()) { - String name = null; - float lat; - float lon; - - Vector record = records.next(); - - if (record.isEmpty()) { - continue; - } - - name = record.elementAt(activityNameIndex) - .toString() - .intern(); - - try { - lat = ((Double) record.elementAt(latIndex)).floatValue(); - lon = ((Double) record.elementAt(lonIndex)).floatValue(); - - // parse time from string, ending up with - // milliseconds from time epoch. - String timeString = (String) record.elementAt(timeIndex); - Date timeDate = timeFormat.parse(timeString); - long time = timeDate.getTime(); - - // BOTH IMPORTANT - timeBounds.addTimeToBounds(time); - dataBounds.add((double) lon, (double) lat); - - if (name != null) { - TemporalOMGraphic point = library.get(name); - if (point != null) { - LatLonPoint location = new LatLonPoint.Double(lat, lon); - TemporalPoint ts = new TemporalPoint(location, time); - point.addTimeStamp(ts); - - OMEvent event = new OMEvent(ts, name - + " moving", time, location); - - // IMPORTANT - callback.events.add(event); - - } else { - logger.warning("ScenarioPoint not found for " - + name + ", entry: " + record); - } - } else { - logger.warning("no name to use to create activity point: " - + name); - } - - } catch (ClassCastException cce) { - - Object obj0 = record.elementAt(activityNameIndex); - Object obj1 = record.elementAt(latIndex); - Object obj2 = record.elementAt(lonIndex); - Object obj3 = record.elementAt(timeIndex); - - logger.warning("Problem with indexes in activity file for " - + obj0 - + " (" - + obj0.getClass().getName() - + ")" - + ":\n\tlat index = " - + latIndex - + ", value = " - + obj1 - + " (" - + obj1.getClass().getName() - + ")\n\t lon index = " - + lonIndex - + ", value = " - + obj2 - + " (" - + obj2.getClass().getName() - + ")\n\t time index = " - + timeIndex - + ", value = " - + obj3 - + " (" - + obj3.getClass().getName() + ")"); - } catch (ParseException pe) { - logger.fine("Problem with time format. " - + pe.getMessage()); - } - } - } catch (MalformedURLException murle) { - logger.warning("problem with activity file: " + activityFile); - return list; - } catch (NullPointerException npe) { - logger.warning("null pointer exception, most likely a problem finding the activites data file"); - } - } else { - logger.warning("Activity file (" + activityFile - + ") not configured."); - return list; - } - - logger.fine("Reading files OK"); - - // IMPORTANT! - callback.setTimeBounds(timeBounds); - - // Time will get updated automatically when the TimeEvent gets sent from - // the clock. - return list; - } - - /** - * The properties and prefix are managed and decoded here, for the standard uses of the EventLayer. - * - * @param prefix string prefix used in the properties file for this layer. - * @param properties the properties set in the properties file. - */ - public void setProperties(String prefix, Properties properties) { - super.setProperties(prefix, properties); - - drawingAttributes.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - locationFile = properties.getProperty(prefix + LocationFileProperty); - iconIndex = PropUtils.intFromProperties(properties, prefix - + IconIndexProperty, -1); - nameIndex = PropUtils.intFromProperties(properties, prefix - + NameIndexProperty, -1); - activityNameIndex = PropUtils.intFromProperties(properties, prefix - + ActivityNameIndexProperty, -1); - activityFile = properties.getProperty(prefix + ActivityFileProperty); - latIndex = PropUtils.intFromProperties(properties, prefix - + LatIndexProperty, -1); - lonIndex = PropUtils.intFromProperties(properties, prefix - + LonIndexProperty, -1); - timeIndex = PropUtils.intFromProperties(properties, prefix - + TimeIndexProperty, -1); - eastIsNeg = PropUtils.booleanFromProperties(properties, prefix - + EastIsNegProperty, eastIsNeg); - showNames = PropUtils.booleanFromProperties(properties, prefix - + ShowNamesProperty, showNames); - defaultIconURL = properties.getProperty(prefix + DefaultIconURLProperty); - locationHeader = PropUtils.booleanFromProperties(properties, prefix - + LocationHeaderProperty, false); - activityHeader = PropUtils.booleanFromProperties(properties, prefix - + ActivityHeaderProperty, false); - - String timeFormatString = properties.getProperty(prefix - + TimeFormatProperty, - ((SimpleDateFormat) timeFormat).toPattern()); - - timeFormat = new SimpleDateFormat(timeFormatString); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("EventLayer indexes:" + "\n\tlocation file: " - + locationFile + "\n\tlocation file has header: " - + locationHeader + "\n\tnameIndex = " + nameIndex - + "\n\ticonIndex = " + iconIndex + "\n\tactivity file: " - + activityFile + "\n\tactivity file has header: " - + activityHeader + "\n\tlatIndex = " + latIndex - + "\n\tlonIndex = " + lonIndex + "\n\ttimeIndex = " - + timeIndex); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the current values of the layer. If the layer - * has a propertyPrefix set, the property keys should have that prefix plus a separating '.' prepended to each - * property key it uses for configuration. - * - * @param props a Properties object to load the PropertyConsumer properties into. - * @return Properties object containing PropertyConsumer property values. If getList was not null, this should equal - * getList. Otherwise, it should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - drawingAttributes.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - props.put(prefix + LocationFileProperty, PropUtils.unnull(locationFile)); - props.put(prefix + LocationHeaderProperty, - new Boolean(locationHeader).toString()); - props.put(prefix + NameIndexProperty, - (nameIndex != -1 ? Integer.toString(nameIndex) : "")); - - props.put(prefix + ActivityFileProperty, PropUtils.unnull(activityFile)); - props.put(prefix + ActivityHeaderProperty, - new Boolean(activityHeader).toString()); - props.put(prefix + ActivityNameIndexProperty, - (activityNameIndex != -1 ? Integer.toString(activityNameIndex) - : "")); - props.put(prefix + EastIsNegProperty, new Boolean(eastIsNeg).toString()); - props.put(prefix + ShowNamesProperty, new Boolean(showNames).toString()); - props.put(prefix + LatIndexProperty, - (latIndex != -1 ? Integer.toString(latIndex) : "")); - props.put(prefix + LonIndexProperty, - (lonIndex != -1 ? Integer.toString(lonIndex) : "")); - props.put(prefix + TimeIndexProperty, - (timeIndex != -1 ? Integer.toString(timeIndex) : "")); - props.put(prefix + IconIndexProperty, - (iconIndex != -1 ? Integer.toString(iconIndex) : "")); - props.put(prefix + DefaultIconURLProperty, - PropUtils.unnull(defaultIconURL)); - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). This method takes care of the basic - * LocationHandler parameters, so any LocationHandlers that extend the - * AbstractLocationHandler should call this method, too, before adding any - * specific properties. - * - * @param list a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object should - * be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - - list.put(LocationFileProperty, - "URL of file containing location information."); - list.put(LocationFileProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - list.put(LocationHeaderProperty, - "Location file has a header row to be ignored."); - list.put(LocationHeaderProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(ActivityFileProperty, - "URL of file containing scenario activity information."); - list.put(ActivityFileProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.FUPropertyEditor"); - list.put(ActivityHeaderProperty, - "Activity file has a header row to be ignored."); - list.put(ActivityHeaderProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(EastIsNegProperty, - "Flag to note that negative latitude are over the eastern hemisphere."); - list.put(EastIsNegProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(ShowNamesProperty, - "Flag to note that locations should display their names."); - list.put(ShowNamesProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.YesNoPropertyEditor"); - list.put(NameIndexProperty, - "The column index, in the location file, of the location label text."); - - list.put(ActivityNameIndexProperty, - "The column index, in the activity file, of the location label text."); - - list.put(LatIndexProperty, - "The column index, in the activity file, of the latitudes."); - list.put(LonIndexProperty, - "The column index, in the activity file, of the longitudes."); - list.put(TimeIndexProperty, - "The column index, in the activity file, of the time of the activity."); - list.put(IconIndexProperty, - "The column index, in the location file, of the icon for locations (optional)."); - list.put(DefaultIconURLProperty, - "The URL of an image file to use as a default for the location markers (optional)."); - - drawingAttributes.getPropertyInfo(list); - - return list; - } - -} diff --git a/src/openmap/com/bbn/openmap/layer/imageTile/MapTileLayer.java b/src/openmap/com/bbn/openmap/layer/imageTile/MapTileLayer.java deleted file mode 100644 index 8358fecc5..000000000 --- a/src/openmap/com/bbn/openmap/layer/imageTile/MapTileLayer.java +++ /dev/null @@ -1,498 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.layer.imageTile; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.event.ActionEvent; -import java.net.MalformedURLException; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSlider; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.mapTile.MapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.MapTileRequester; -import com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory; -import com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.PropUtils; - -/** - * A Layer that uses a MapTileFactory to display information (tiles) on the map. - * Properties for this layer look like this: - * - *
- * 
- * tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer
- * tiles.prettyName=TILES
- * tiles.tileFactory=com.bbn.openmap.dataAccess.mapTile.StandardMapTileFactory
- * tiles.rootDir=root_directory_of_tiles
- * #optional, .png is default
- * tiles.fileExt=.png
- * tiles.cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # transform for naming convention of tiles default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * tiles.mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * 
- * 
- * - * You can use a server that provides image tiles: - * - *
- * 
- * tiles.class=com.bbn.openmap.layer.imageTile.MapTileLayer
- * tiles.prettyName=TILES
- * tiles.tileFactory=com.bbn.openmap.dataAccess.mapTile.ServerMapTileFactory
- * tiles.rootDir=URL root directory of tiles
- * # a local location to cache tiles, to reduce load on server.
- * tiles.localCacheRootDir=/data/tiles/osmtiles
- * # save cache when layer is done (true by default)
- * tiles.saveCache=true
- * 
- * # other properties are the same.
- * tiles.fileExt=.png
- * tiles.cacheSize=the number of mapTiles the factory should hold on to. The default is 100.
- * # transform for naming convention of tiles default is OSMMapTileCoordinateTransform, but it depends on the source of tiles.  GDAL is TSMMapTileCoordinateTransform
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.OSMMapTileCoordinateTransform, or com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * 
- * 
- * - * The rootDir property can be defined as a pattern, with the zoom level z, x - * tile coordinate and y tile coordinate set using {z}{x}{y} for however the - * tiles are stored or retrieved: - * - *
- * rootDir=/data/tiles/{z}/{x}/{y}.png
- * 
- * #or, for the ServerMapTileFactory:
- * rootDir=http://someserver.com/tileset/{z}/{x}/{y}.png
- * 
- * 
- * - * In this case, the fileExt won't be used as the code will assume you are - * setting that. - * - * To make things simpler, you can define a tiles.omp file that sits under the - * tile root directory or at the top level of the jar file, and let it specify - * the properties for the tile set. The properties in that file should be - * unscoped: - * - *
- * 
- * fileExt=.png
- * #for instance, for GDAL processed images you need this transform since tiles have difference reference coordinates
- * mapTileTransform=com.bbn.openmap.dataAccess.mapTile.TMSMapTileCoordinateTransform
- * #in jar file, should specify rootDir inside jar to tiles (don't need this for layers accessing local file system rootDirs, unless you want to specify z,x,y order differently):
- * rootDir=mytiles
- * 
- * #optional
- * attribution=map data 2013 OpenStreetMap
- * 
- * 
- * - * If you do this last configuration, all you need to define is rootDir (and - * prettyName, class) property for layer, and then define all other props with - * data. - * - * @author dietrick - */ -public class MapTileLayer extends OMGraphicHandlerLayer implements MapTileRequester { - - private static final long serialVersionUID = 1L; - - public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.imageTile.TileLayer"); - - /** - * Property that sets the class name of the MapTileFactory to use for this - * layer. - */ - public final static String TILE_FACTORY_CLASS_PROPERTY = "tileFactory"; - /** - * Property to allow the MapTileFactory to call repaint on this layer as map - * tiles become available. Default is false, enabling it will not allow this - * layer to be used with an ImageServer (renderDataForProjection won't - * work). - */ - public final static String INCREMENTAL_UPDATES_PROPERTY = "incrementalUpdates"; - - /** - * A property to set if you want to force the layer to use tiles of a - * certain zoom level. - */ - public final static String ZOOM_LEVEL_PROPERTY = "zoomLevel"; - - /** - * A property to set for displaying attribution for the data used by the - * layer. - */ - public final static String DATA_ATTRIBUTION_PROPERTY = "attribution"; - - /** - * A property to save or destroy the tile factory cache when the layer is - * removed. - */ - public final static String SAVE_CACHE_PROPERTY = "saveCache"; - /** - * The MapTileFactory that knows how to fetch image files and create - * OMRasters for them. - */ - protected MapTileFactory tileFactory; - /** - * Flag to allow this layer to set itself as a repaint callback object on - * the tile factory. - */ - protected boolean incrementalUpdates = false; - /** - * The zoomLevel to use when requesting tiles from the MapTileFactory. Is -1 - * for default, which lets the factory choose the zoom level based on the - * current scale setting. You can choose 1-20 if you want to force the layer - * to use something else. - */ - protected int zoomLevel = -1; - - /** - * Attribution for the map data. If it exists, it will be displayed on the - * lower left corner of the map. - */ - protected String attribution = null; - - /** - * Flag to save tile factory cache when the layer is no longer used. - */ - protected boolean saveCache = true; - - /** - * Rendering parameters for attribution string. - */ - protected DrawingAttributes attributionAttributes = DrawingAttributes.getDefaultClone(); - - public MapTileLayer() { - setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this)); - setTileFactory(new StandardMapTileFactory()); - // We need to make this layer uninterruptable, because that messes with - // the image file loading. - setInterruptable(false); - } - - public MapTileLayer(MapTileFactory tileFactory) { - this(); - this.tileFactory = tileFactory; - } - - /** - * OMGraphicHandlerLayer method, called with projection changes or whenever - * else doPrepare() is called. Calls getTiles on the map tile factory. - * - * @return OMGraphicList that contains tiles to be displayed for the current - * projection. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - - if (projection == null) { - return null; - } - - if (tileFactory != null) { - return tileFactory.getTiles(projection, zoomLevel, new OMGraphicList()); - } - return null; - } - - public void paint(java.awt.Graphics g) { - super.paint(g); - - OMText attrib = getAttributionGraphic(); - if (attrib != null) { - attrib.render(g); - } - } - - /** - * @return OMText for attribution text - */ - protected OMText getAttributionGraphic() { - Projection proj = getProjection(); - if (attribution != null && proj != null) { - OMText attText = new OMText(10, proj.getHeight() - 10, attribution, OMText.JUSTIFY_LEFT); - if (attributionAttributes != null) { - attributionAttributes.setTo(attText); - } - attText.generate(proj); - return attText; - } - - return null; - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - attribution = props.getProperty(prefix + DATA_ATTRIBUTION_PROPERTY, attribution); - attributionAttributes.setProperties(prefix, props); - - String tileFactoryClassString = props.getProperty(prefix + TILE_FACTORY_CLASS_PROPERTY); - if (tileFactoryClassString != null) { - MapTileFactory itf = (MapTileFactory) ComponentFactory.create(tileFactoryClassString, prefix, props); - if (itf != null) { - setTileFactory(itf); - } - } else { - // Let's see if we can figure out what kind of MapTileFactory is - // needed based on rootDir - String rootDirString = props.getProperty(prefix + StandardMapTileFactory.ROOT_DIR_PROPERTY); - if (rootDirString != null) { - try { - // We build URL here to test if the rootDir location exists. - // Comment out url to avoid dead store findbugs problem. - /* URL url = */new java.net.URL(rootDirString); - // If we get here, we have a protocol, looks remote, so we - // should make sure the - // ServerMapTileFactory is used. - if (!(getTileFactory() instanceof ServerMapTileFactory)) { - setTileFactory(new ServerMapTileFactory(rootDirString)); - } - - } catch (MalformedURLException e) { - // no protocol or something, use default - // StandardMapTileFactory - if (!(getTileFactory() instanceof StandardMapTileFactory)) { - setTileFactory(new StandardMapTileFactory()); - } - } - } - } - - if (tileFactory instanceof PropertyConsumer) { - ((PropertyConsumer) tileFactory).setProperties(prefix, props); - } - - incrementalUpdates = PropUtils.booleanFromProperties(props, prefix + INCREMENTAL_UPDATES_PROPERTY, - incrementalUpdates); - - setZoomLevel(PropUtils.intFromProperties(props, prefix + ZOOM_LEVEL_PROPERTY, zoomLevel)); - - saveCache = PropUtils.booleanFromProperties(props, prefix + SAVE_CACHE_PROPERTY, saveCache); - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - if (tileFactory != null) { - props.put(prefix + TILE_FACTORY_CLASS_PROPERTY, tileFactory.getClass().getName()); - if (tileFactory instanceof PropertyConsumer) { - ((PropertyConsumer) tileFactory).getProperties(props); - } - } - - props.put(prefix + INCREMENTAL_UPDATES_PROPERTY, Boolean.toString(incrementalUpdates)); - props.put(prefix + ZOOM_LEVEL_PROPERTY, Integer.toString(zoomLevel)); - props.put(prefix + DATA_ATTRIBUTION_PROPERTY, PropUtils.unnull(attribution)); - props.put(prefix + SAVE_CACHE_PROPERTY, Boolean.toString(saveCache)); - - attributionAttributes.getProperties(props); - - return props; - } - - public Properties getPropertyInfo(Properties props) { - props = super.getPropertyInfo(props); - - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), ZOOM_LEVEL_PROPERTY, "Zoom Level", - "Force zoom level for queries (-1 is no forcing)", null); - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), DATA_ATTRIBUTION_PROPERTY, "Attribution", - "Attribution for data source", null); - PropUtils.setI18NPropertyInfo(i18n, props, this.getClass(), SAVE_CACHE_PROPERTY, "Disable Tile Factory Reset", "Disable tile factory reset on layer remove", null); - if (tileFactory instanceof StandardMapTileFactory) { - ((StandardMapTileFactory) tileFactory).getPropertyInfo(props); - props.put(initPropertiesProperty, ((StandardMapTileFactory) tileFactory).getInitPropertiesOrder() - + " " + ZOOM_LEVEL_PROPERTY + " " + DATA_ATTRIBUTION_PROPERTY + " " - + SAVE_CACHE_PROPERTY); - } else { - props.put(initPropertiesProperty, StandardMapTileFactory.ROOT_DIR_PROPERTY + " " - + StandardMapTileFactory.FILE_EXT_PROPERTY + " " + ZOOM_LEVEL_PROPERTY + " " - + DATA_ATTRIBUTION_PROPERTY + " " + SAVE_CACHE_PROPERTY); - } - - return props; - } - - /** - * Called when the layer has been turned off and the projection changes, - * signifying that the layer can clean up. - */ - public void removed(Container cont) { - MapTileFactory tileFactory = getTileFactory(); - if (tileFactory != null && !saveCache) { - tileFactory.reset(); - } - } - - public MapTileFactory getTileFactory() { - return tileFactory; - } - - public void setTileFactory(MapTileFactory tileFactory) { - logger.fine("setting tile factory to: " + tileFactory.getClass().getName()); - // This allows for general faster response, but causes the map to jump - // around a little bit when used with the BufferedImageRenderPolicy and - // when the projection changes occur rapidly, like when zooming and - // panning several times in a second. The generation/positioning can't - // keep up. It'll settle out, but it might be better to be slower and - // less confusing to the user. - - tileFactory.setMapTileRequester(this); - - this.tileFactory = tileFactory; - - doPrepare(); - } - - public boolean isIncrementalUpdates() { - return incrementalUpdates; - } - - public void setIncrementalUpdates(boolean incrementalUpdates) { - this.incrementalUpdates = incrementalUpdates; - } - - public int getZoomLevel() { - return zoomLevel; - } - - public void setZoomLevel(int zoomLevel) { - this.zoomLevel = zoomLevel; - } - - public java.awt.Component getGUI() { - // Only allow delete cache button if the source of the tiles are from a - // server. - - JPanel panel = new JPanel(); - panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - - if (getTileFactory() instanceof ServerMapTileFactory) { - JPanel clearCachePanel = new JPanel(new BorderLayout()); - clearCachePanel.add(new JPanel(), BorderLayout.WEST); - clearCachePanel.add(new JPanel(), BorderLayout.EAST); - JButton clearButton = new JButton(i18n.get(MapTileLayer.class, "clearCacheLabel", "Clear Tile Cache")); - clearCachePanel.add(clearButton, BorderLayout.CENTER); - clearButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - String query = i18n.get(MapTileLayer.class, "mapTileLayerDeleteCacheQuery", "Delete tiles on disk? Click OK to delete..."); - - int dialogResult = JOptionPane.showConfirmDialog(null, query, "Warning", JOptionPane.OK_CANCEL_OPTION); - if (dialogResult == JOptionPane.OK_OPTION) { - clearCache(); - } - } - }); - - panel.add(clearCachePanel); - } - - panel.add(getDefaultSettingsPanel(this.getClass(), getTransparency())); - return panel; - } - - /** - * @return the attribution - */ - public String getAttribution() { - return attribution; - } - - /** - * @param attribution the attribution to set - */ - public void setAttribution(String attribution) { - this.attribution = attribution; - } - - /** - * @return the attributionAttributes - */ - public DrawingAttributes getAttributionAttributes() { - return attributionAttributes; - } - - /** - * @param attributionAttributes the attributionAttributes to set - */ - public void setAttributionAttributes(DrawingAttributes attributionAttributes) { - this.attributionAttributes = attributionAttributes; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.MapTileRequestor#shouldContinue() - */ - public boolean shouldContinue() { - return !isInterruptable() || !isCancelled(); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.dataAccess.mapTile.MapTileRequestor#listUpdated() - */ - public void listUpdated() { - if (incrementalUpdates) { - repaint(); - } - } - - /** - * Clear the MapTileFactory cache. - */ - public void clearCache() { - MapTileFactory mtf = getTileFactory(); - if (mtf != null) { - mtf.reset(); - } - } - -} diff --git a/src/openmap/com/bbn/openmap/layer/link/amp/AmpLinkLayer.java b/src/openmap/com/bbn/openmap/layer/link/amp/AmpLinkLayer.java deleted file mode 100644 index aae320e77..000000000 --- a/src/openmap/com/bbn/openmap/layer/link/amp/AmpLinkLayer.java +++ /dev/null @@ -1,390 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/amp/AmpLinkLayer.java,v $ -// $RCSfile: AmpLinkLayer.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/03/06 16:14:00 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.amp; - -import java.awt.Color; -import java.awt.Container; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.net.UnknownHostException; - -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.SwingConstants; - -import com.bbn.openmap.gui.Tool; -import com.bbn.openmap.layer.link.ClientLink; -import com.bbn.openmap.layer.link.Link; -import com.bbn.openmap.layer.link.LinkActionList; -import com.bbn.openmap.layer.link.LinkGraphic; -import com.bbn.openmap.layer.link.LinkLayer; -import com.bbn.openmap.layer.link.LinkOMGraphicList; -import com.bbn.openmap.layer.link.LinkProperties; -import com.bbn.openmap.omGraphics.GraphicAttributes; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMRangeRings; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.tools.drawing.DrawingTool; -import com.bbn.openmap.util.Debug; - -/** - * The AmpLinkLayer is an extension to the LinkLayer. The difference - * is that this layer provides some components to the ToolBar for the - * creation of certain graphics to be sent to the LinkServer. This - * layer also wants access to the DrawingTool. - *

- * - * The entry in the openmap.properties file looks like this: - *

- * - *

- * 
- *  
- *   
- *    # port number of server
- *    link.port=3031
- *    # host name of server
- *    link.host=host.com
- *    # URL of properties file for server attributes
- *    link.propertiesURL=http://location.of.properties.file.com
- *    
- *   
- *  
- * 
- */ -public class AmpLinkLayer extends LinkLayer implements Tool { - - public final static String RRIntervalUnitsProperty = ".rangeRingIntervalUnits"; - public final static String RRIntervalProperty = ".rangeRingInterval"; - - protected OMGraphicList extraGraphics = new OMGraphicList(); - - protected DrawingTool drawingTool = null; - protected int orientation = SwingConstants.HORIZONTAL; - - /** - * The default constructor for the Layer. All of the attributes - * are set to their default values. - */ - public AmpLinkLayer() {} - - /** - * Constructor to use when LinkLayer is not being used with - * OpenMap application. - * - * @param host the hostname of the server's computer. - * @param port the port number of the server. - * @param propertiesURL the URL of a properties file that contains - * parameters for the server. - */ - public AmpLinkLayer(String host, int port, String propertiesURL) { - super(host, port, propertiesURL); - } - - /** - * Set all the Link properties from a properties object. - * - * @param prefix the prefix to the properties that might - * individualize it to a particular layer. - * @param properties the properties for the layer. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - setAddToBeanContext(true); - } - - /** - * Prepares the graphics for the layer. This is where the - * getRectangle() method call is made on the link. - *

- * Occasionally it is necessary to abort a prepare call. When this - * happens, the map will set the cancel bit in the LayerThread, - * (the thread that is running the prepare). If this Layer needs - * to do any cleanups during the abort, it should do so, but - * return out of the prepare asap. - * - * @return a list of graphics. - */ - public synchronized OMGraphicList prepare() { - Projection projection = getProjection(); - if (projection != null) { - extraGraphics.generate(projection); - } - return super.prepare(); - } - - /** - * Paints the layer. - * - * @param g the Graphics context for painting - */ - public void paint(java.awt.Graphics g) { - if (Debug.debugging("link")) { - System.out.println(getName() + "|AmpLinkLayer.paint()"); - } - - if (extraGraphics != null) { - extraGraphics.render(g); - } - - super.paint(g); - } - - /** - * Just need to check here if one of the new extra graphics (range - * ring) was clicked on, so that it can be sent to the drawing - * tool for modification if desired. - */ - public boolean mouseClicked(MouseEvent e) { - Debug.message("link", "AmpLinkLayer mouseClicked"); - LinkOMGraphicList graphics = getGraphicList(); // Get old list - OMGraphic gesGraphic = null; - - gesGraphic = graphics.findClosest(e.getX(), e.getY(), distanceLimit); - if (gesGraphic == null) { - gesGraphic = extraGraphics.findClosest(e.getX(), - e.getY(), - distanceLimit); - } - - if (gesGraphic != null && drawingTool != null) { - DrawingTool dt = getDrawingTool(); - OMGraphic graphic = null; - if (dt != null) { - graphic = dt.edit(gesGraphic, layer); - } - - if (graphic != null) { - Debug.message("link", "AmpLinkLayer editing graphic"); - return true; - } else { - Debug.message("link", "AmpLinkLayer unable to edit graphic"); - } - } - return super.mouseClicked(e); - } - - protected final com.bbn.openmap.tools.drawing.DrawingToolRequestor layer = this; - - // DrawingToolRequestor method - public void drawingComplete(OMGraphic omg, OMAction action) { - ////////////// send the new graphic, along with instructions - //on what to do with it, to the server. - String id = null; // unknown - - Object obj = omg.getAttribute(OMGraphic.APP_OBJECT); - LinkProperties lp = null; - - if (obj instanceof LinkProperties) { - lp = (LinkProperties) obj; - id = lp.getProperty(LPC_GRAPHICID); - Debug.message("link", - "AmpLinkLayer: received modified server graphic " + lp); - } else { - Debug.message("link", "AmpLinkLayer: received new graphic from dt"); - } - - if (id == null) { - // Doesn't look like it was a modified graphic already - // received from the server, so we should tell the server - // to add it to its list. - action.setMask(OMAction.ADD_GRAPHIC_MASK); - } else { - action.setMask(OMAction.UPDATE_GRAPHIC_MASK); - } - - if (omg instanceof OMRangeRings) { - extraGraphics.doAction(omg, action); - repaint(); - return; - } - - try { - // We do want the link object here... If another thread is - // using the link, wait. - ClientLink l = linkManager.getLink(true); - - if (l == null) { - System.err.println("LinkLayer.drawingComplete: unable to get link."); - return; - } - - synchronized (l) { - LinkActionList lal = new LinkActionList(l, new LinkProperties()); - - if (action.isMask(OMAction.ADD_GRAPHIC_MASK) - || action.isMask(OMAction.UPDATE_GRAPHIC_MASK)) { - lal.writeGraphicGestureHeader(action.getValue()); - LinkGraphic.write(omg, l); - } else { - // This shouldn't ever get called with a null lp - // properties object. If the object is new or - // doesn't have an ID, the upper paragraph will - // get called. - lal.modifyGraphic(action.getValue(), lp); - } - lal.end(Link.END_TOTAL); - } - - l.readAndParse(getProjection(), currentGenerator); - linkManager.finLink(); - - } catch (UnknownHostException uhe) { - Debug.error("LinkLayer: unknown host!"); - } catch (java.io.IOException ioe) { - Debug.error("LinkLayer: Communication error between " + getName() - + " layer\nand Link Server: Host: " + host + ", Port: " - + port + "LinkLayer: IOException contacting server!\n" - + ioe.getMessage()); - - linkManager.resetLink(); - - if (!quiet) { - fireRequestMessage("Communication error between " + getName() - + " layer\nand Link Server: Host: " + host + ", Port: " - + port); - } - - } - doPrepare(); - } - - /////////////////////////////////////////////////// - // Tool interface - to put controls for the layer - // on the tool bar. - protected Container gui; - protected JButton rrButton, eZone; - - /** - * The retrieval tool's interface. This is added to the tool bar. - * - * @return String The key for this tool. - */ - public Container getFace() { - if (gui == null) { - gui = new JPanel(); - - rrButton = new JButton("RR"); - rrButton.setToolTipText("Create Range Ring"); - rrButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - DrawingTool dt = getDrawingTool(); - GraphicAttributes ga = new GraphicAttributes(); - ga.setLinePaint(Color.yellow); - if (dt != null) { - OMRangeRings rr = (OMRangeRings) getDrawingTool().create("com.bbn.openmap.omGraphics.OMRangeRings", - ga, - layer); - if (rr != null) { - // rr.setInterval(25, Length.MILE); - } else { - Debug.error("AmpLinkLayer: Drawing tool can't create OMRangeRings"); - } - } else { - Debug.output("AmpLinkLayer can't find a drawing tool"); - } - } - }); - - eZone = new JButton("EZ"); - eZone.setToolTipText("Create Exclusion Zone"); - eZone.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - DrawingTool dt = getDrawingTool(); - GraphicAttributes ga = new GraphicAttributes(); - ga.setRenderType(OMGraphic.RENDERTYPE_LATLON); - ga.setLinePaint(Color.red); - if (dt != null) { - OMCircle circle = (OMCircle) getDrawingTool().create("com.bbn.openmap.omGraphics.OMCircle", - ga, - layer); - if (circle == null) { - Debug.error("AmpLinkLayer: Drawing tool can't create Exclusion Zones"); - } - } else { - Debug.output("AmpLinkLayer can't find a drawing tool"); - } - } - }); - - gui.add(rrButton); - gui.add(eZone); - } - return gui; - } - - protected String key = "AMPControls"; - - /** - * The retrieval key for this tool - * - * @return String The key for this tool. - */ - public String getKey() { - return key; - } - - /** - * Set the retrieval key for this tool - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - key = aKey; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof DrawingTool) { - Debug.message("link", "AmpLinkLayer: found a drawing tool"); - setDrawingTool((DrawingTool) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof DrawingTool) { - if (getDrawingTool() == (DrawingTool) someObj) { - setDrawingTool(null); - } - } - } - - public void setDrawingTool(DrawingTool dt) { - drawingTool = dt; - } - - public DrawingTool getDrawingTool() { - return drawingTool; - } - - public int getOrientation() { - return orientation; - } - - public void setOrientation(int orientation) { - this.orientation = orientation; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/link/draw/DrawLinkLayer.java b/src/openmap/com/bbn/openmap/layer/link/draw/DrawLinkLayer.java deleted file mode 100644 index bf7a02d30..000000000 --- a/src/openmap/com/bbn/openmap/layer/link/draw/DrawLinkLayer.java +++ /dev/null @@ -1,311 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/link/draw/DrawLinkLayer.java,v $ -// $RCSfile: DrawLinkLayer.java,v $ -// $Revision: 1.2 $ -// $Date: 2007/02/26 17:12:47 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.link.draw; - -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.util.Iterator; -import java.util.Properties; - -import com.bbn.openmap.layer.link.ClientLink; -import com.bbn.openmap.layer.link.LinkActionRequest; -import com.bbn.openmap.layer.link.LinkLayer; -import com.bbn.openmap.layer.link.LinkOMGraphicList; -import com.bbn.openmap.layer.link.LinkProperties; -import com.bbn.openmap.layer.link.LinkUtil; -import com.bbn.openmap.omGraphics.EditableOMGraphic; -import com.bbn.openmap.omGraphics.OMAction; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.tools.drawing.OMDrawingTool; -import com.bbn.openmap.util.Debug; - -/** - * The DrawLinkLayer is an extension to the LinkLayer. It allows to selectively - * disable interacting with graphics in the LinkLayer and to selectively enable - * using the drawing tool to modify graphics in the LinkLayer. - *

- * - * The entry in the openmap.properties file looks like this: - *

- * - *

- * 
- * 
- * 
- *      # port number of server
- *      link.port=3031
- *      # host name of server
- *      link.host=host.com
- *      # URL of properties file for server attributes
- *      link.propertiesURL=http://location.of.properties.file.com
- * 
- * 
- * 
- * 
- */ -public class DrawLinkLayer extends LinkLayer { - - public final static String LPC_EDITABLE = "editable"; - public final static String LPC_SELECTABLE = "selectable"; - - protected OMDrawingTool drawingTool = null; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public DrawLinkLayer() { - } - - /** - * Constructor to use when LinkLayer is not being used with OpenMap - * application. - * - * @param host the hostname of the server's computer. - * @param port the port number of the server. - * @param propertiesURL the URL of a properties file that contains - * parameters for the server. - */ - public DrawLinkLayer(String host, int port, String propertiesURL) { - super(host, port, propertiesURL); - } - - /** - * Set all the Link properties from a properties object. - * - * @param prefix the prefix to the properties that might individualize it to - * a particular layer. - * @param properties the properties for the layer. - */ - public void setProperties(String prefix, java.util.Properties properties) { - super.setProperties(prefix, properties); - setAddToBeanContext(true); - } - - /** - * Modify the behavior of LinkLayer::mouseClicked to only interact with - * graphics that have the "selectable" property set to true. If the - * "editable" property is set then use the drawing tool to edit the graphic. - */ - public boolean mouseClicked(MouseEvent e) { - - int descriptor = MOUSE_CLICKED_MASK; - - LinkOMGraphicList graphics = getGraphicList(); - - if (graphics == null) { - Debug.message("link", "DrawLinkLayer.mouseClicked: null LinkOMGraphicList, making new one..."); - // If the graphic list is null then LinkLayer::mouseClicked will - // not report the mouse click to the server. Set it to an empty - // list to continue processing. - graphics = new LinkOMGraphicList(); - setGraphicList(graphics); - } - - Debug.message("link", "DrawLinkLayer mouseClicked"); - OMGraphic gesGraphic = null; - - LinkOMGraphicList selectableList = new LinkOMGraphicList(); - OMGraphic g; - Properties p; - String selectable; - for (Iterator it = graphics.iterator(); it.hasNext();) { - g = (OMGraphic) it.next(); - p = (Properties) g.getAttribute(OMGraphic.APP_OBJECT); - selectable = p.getProperty(LPC_SELECTABLE); - if (selectable.equals("true")) { - selectableList.add(g); - } - } - - try { - - if (e == null) { - graphics.deselect(); - return false; - } - - gesGraphic = selectableList.findClosest(e.getX(), e.getY(), distanceLimit); - - String id = null; - - // If there was a graphic, set the mask to indicate that, - // and keep track of the graphic and the list index of the - // graphic for the response. If a graphic modify command - // comes back without an ID, then we'll assume the server - // was referring to this graphic. - if (gesGraphic != null) { - Debug.message("link", "LinkLayer: found gesture graphic"); - - boolean tellServer = graphicGestureReaction(gesGraphic, descriptor, e); - - if (!tellServer) { - repaint(); - return true; - } - - descriptor = LinkUtil.setMask(descriptor, GRAPHIC_ID_MASK); - id = ((LinkProperties) gesGraphic.getAttribute(OMGraphic.APP_OBJECT)).getProperty(LPC_GRAPHICID); - } else { - Debug.message("link", "LinkLayer: gesture graphic NOT FOUND"); - // clear out info line - fireRequestInfoLine(""); - } - - // server inform - if (!LinkUtil.isMask(getGestureDescriptor(), SERVER_NOTIFICATION_MASK)) { - return false; - } - - // Get the lat/lon point of the event - Point2D llpoint = getProjection().inverse(e.getX(), e.getY()); - - // Don't need these anymore, look below for explaination - // for asynchronous operation. - // LinkActionList lal; - // LinkActionRequest lar; - - ClientLink l = linkManager.getLink(false); - - // We'll check this here because we don't want to wait if - // it is not available - it could be used for another - // graphics or gui fetch. - if (l == null) { - Debug.message("link", "LinkLayer: unable to get link in handleGesture()."); - return false; - } - - // Using the link - carefully prevent others from using it - // too! - synchronized (l) { - if (id != null) { - args.setProperty(LPC_GRAPHICID, id); - } else { - // Reset this to prevent sending the id of a graphic - // that is not being clicked on. - args.remove(LPC_GRAPHICID); - } - - // Send the query - LinkActionRequest.write(descriptor, e, (float) llpoint.getY(), (float) llpoint.getX(), args, l); - - } - - linkManager.finLink(); - - } catch (IOException ioe) { - System.err.println("LinkLayer: IOException contacting server during gesture handling!"); - System.err.println(ioe); - linkManager.resetLink(); - return false; - } - - OMDrawingTool dt = getDrawingTool(); - if (dt != null) { - // Stop editing any graphic currently being edited - dt.setMask(OMDrawingTool.DEACTIVATE_ASAP_BEHAVIOR_MASK); - EditableOMGraphic egraphic = dt.getCurrentEditable(); - if (egraphic != null) { - OMGraphic graphic = egraphic.getGraphic(); - - OMAction action = new OMAction(UPDATE_GRAPHIC_MASK); - drawingComplete(graphic, action); - dt.setCurrentEditable(null); - } - } - - // FIXME - we could operate on a subset of graphics by either having - // multiple graphics lists or by filtering the graphics list - // to only detect/edit the graphics we want. - if (gesGraphic != null && drawingTool != null) { - OMGraphic graphic = null; - if (dt != null) { - - Properties prop = (Properties) gesGraphic.getAttribute(OMGraphic.APP_OBJECT); - String editable = prop.getProperty(LPC_EDITABLE); - Debug.message("link", "DrawLinkLayer: editable: " + editable); - if (editable.equals("false")) { - Debug.message("link", "DrawLinkLayer not editing graphic. editable = false"); - } else { - Debug.message("link", "DrawLinkLayer trying to edit graphic"); - graphic = dt.edit(gesGraphic, layer); - } - } else { - Debug.message("link", "Error: DrawLinkLayer has not drawing tool"); - } - - if (graphic != null) { - Debug.message("link", "DrawLinkLayer editing graphic"); - } else { - Debug.message("link", "DrawLinkLayer unable to edit graphic"); - } - } - return true; - } - - protected final com.bbn.openmap.tools.drawing.DrawingToolRequestor layer = this; - - protected String key = "MapToolDrawing"; - - /** - * The retrieval key for this tool - * - * @return String The key for this tool. - */ - public String getKey() { - return key; - } - - /** - * Set the retrieval key for this tool - * - * @param aKey The key for this tool. - */ - public void setKey(String aKey) { - key = aKey; - } - - public void findAndInit(Object someObj) { - if (someObj instanceof OMDrawingTool) { - Debug.message("link", "DrawLinkLayer: found a drawing tool"); - setDrawingTool((OMDrawingTool) someObj); - } - } - - public void findAndUndo(Object someObj) { - if (someObj instanceof OMDrawingTool) { - if (getDrawingTool() == (OMDrawingTool) someObj) { - setDrawingTool(null); - } - } - } - - public void setDrawingTool(OMDrawingTool dt) { - drawingTool = dt; - } - - public OMDrawingTool getDrawingTool() { - return drawingTool; - } -} diff --git a/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBESite.java b/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBESite.java deleted file mode 100644 index 9da59ac37..000000000 --- a/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBESite.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/plotLayer/GLOBESite.java,v -// $ -// $RCSfile: GLOBESite.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/08/09 18:44:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.plotLayer; - -import java.awt.Color; -import java.util.Enumeration; -import java.util.Hashtable; - -import com.bbn.openmap.omGraphics.OMCircle; -import com.bbn.openmap.omGraphics.OMGraphic; - -public class GLOBESite { - - private float longitude_, latitude_; - - private float max_year_ = -9999; - private float min_year_ = 99999; - private float max_temp_ = -99999; - private float min_temp_ = 99999; - - private Hashtable temp_table_ = null; - // private Hashtable max_temp_table_ = null; - // private Hashtable min_temp_table_ = null; - - private String name_; - -// private static final byte[] default_bits_ = { (byte) 0x00, (byte) 0x00, -// (byte) 0x00, (byte) 0x00, (byte) 0x70, (byte) 0x00, (byte) 0xf8, -// (byte) 0x00, (byte) 0xfc, (byte) 0x01, (byte) 0xfc, (byte) 0x01, -// (byte) 0xfc, (byte) 0x01, (byte) 0xf8, (byte) 0x00, (byte) 0x70, -// (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - - private OMGraphic graphic_; - - public GLOBESite(float lat, float lon) { - longitude_ = lon; - latitude_ = lat; - - name_ = "(" + latitude_ + ", " + longitude_ + ")"; - - // graphic_ = new OMCircle(lat, lon, 5,5, 11, 11, - // default_bits_); - graphic_ = new OMCircle(lat, lon, 5, 5); - graphic_.setLinePaint(Color.red); - graphic_.setFillPaint(Color.red); - graphic_.setSelectPaint(Color.yellow); - graphic_.putAttribute(OMGraphic.APP_OBJECT, this); - - temp_table_ = new Hashtable(); - // max_temp_table_ = new Hashtable(); - // min_temp_table_ = new Hashtable(); - } - - public String hash() { - return name_; - } - - public void addCurrentTemp(float year, float temp) { - temp_table_.put(new Float(year), new Float(temp)); - } - - public float getCurrentTemp(float year) { - return ((Number) temp_table_.get(new Float(year))).floatValue(); - } - - // public void addMaxTemp(float year, float temp) - // {max_temp_table_.put(new Float(year), new Float(temp));} - // public float getMaxTemp(float year) - // {return ((Number)max_temp_table_.get(new - // Float(year))).floatValue();} - - // public void addMinTemp(float year, float temp) - // {min_temp_table_.put(new Float(year), new Float(temp));} - // public float getMinTemp(float year) - // {return ((Number)min_temp_table_.get(new - // Float(year))).floatValue();} - - public float getLatitude() { - return latitude_; - } - - public float getLongitude() { - return longitude_; - } - - public final OMGraphic getGraphic() { - return graphic_; - } - - public String getName() { - return name_; - } - - public Enumeration getAllYears() { - return temp_table_.keys(); - } - - public float getMaxTemp() { - return max_temp_; - } - - public float getMinTemp() { - return min_temp_; - } - - public float getMaxYear() { - return max_year_; - } - - public float getMinYear() { - return min_year_; - } - - public float getValueForYear(float year) { - if (temp_table_.containsKey(new Float(year))) { - return ((Float) temp_table_.get(new Float(year))).floatValue(); - } - return -99; - } - - protected void recalcLimits() { - Enumeration all_years = temp_table_.keys(); - while (all_years.hasMoreElements()) { - float year = ((Float) all_years.nextElement()).floatValue(); - float temp = ((Float) temp_table_.get(new Float(year))).floatValue(); - if (year > max_year_) - max_year_ = year; - if (year < min_year_) - min_year_ = year; - - if (temp > max_temp_) - max_temp_ = temp; - if (temp < min_temp_) - max_temp_ = temp; - } - } - - public String getInfo() { - int numpoints = temp_table_.size(); - return name_ + " -- " + numpoints + " datapoints available"; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfConstants.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfConstants.java deleted file mode 100644 index 8bbfe1c33..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfConstants.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfConstants.java,v $ -// $RCSfile: RpfConstants.java,v $ -// $Revision: 1.3 $ -// $Date: 2004/10/14 18:06:03 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.layer.rpf; - -/** - * The properties and constants used for RPF data and RPF Coverages. - */ -public interface RpfConstants { - - /** - * Property to use for images or rectangles (when java supports it). - * "opaque" - */ - public static final String OpaquenessProperty = "opaque"; - /** - * Property to use to fill rectangles. "fill" - */ - public static final String FillProperty = "fill"; - /** - * Paths to the A.TOC properties. "paths" - */ - public static final String RpfPathsProperty = "paths"; - /** - * Number of colors to use in images. "numberColors" - */ - public static final String NumColorsProperty = "numberColors"; - /** - * Show the images. "showMaps" - */ - public static final String ShowMapsProperty = "showMaps"; - /** - * Show the attribute information for the RPF data. "showInfo" - */ - public static final String ShowInfoProperty = "showInfo"; - /** - * Scale toe images to match the map scale. "scaleImages" - */ - public static final String ScaleImagesProperty = "scaleImages"; - /** - * Delete the cache is the layer is removed from the map. "killCache" - */ - public static final String KillCacheProperty = "killCache"; - /** - * Set a limit on which chart types are displayed. "chartSeries" - */ - public static final String ChartSeriesProperty = "chartSeries"; - /** - * Tell the RpfLayer you want the coverage tool available. "coverage" - */ - public static final String CoverageProperty = "coverage"; - /** - * Tell the RpfLayer which colormodel to use (INDEXED or DIRECT (default)). - * "colormodel" - */ - public static final String ColormodelProperty = "colormodel"; - /** - * Tell the RpfLayer how big to make the subframe cache.. - * "subframeCacheSize" - */ - public static final String CacheSizeProperty = "subframeCacheSize"; - /** - * Tell the RpfLayer how big to make the subframe cache.. - * "auxSubframeCacheSize" - */ - public static final String AuxCacheSizeProperty = "auxSubframeCacheSize"; - /** - * Tell the RpfLayer to get the detailed subframe attributes for each - * subframe. - */ - public static final String AutoFetchAttributeProperty = "autofetchAttributes"; - /** - * The amount of scaling to allow on images. Default is 4x, which also means - * 1/4th - */ - public static final String ImageScaleFactorProperty = "imageScaleFactor"; - /** - * Property to specify that matching scale is more important that maximizing - * coverage. Default is true, so you can see the smaller coverage that might - * match map scale. This setting is more important for layer being used to - * create smaller tile images, and you might prefer fill coverage over small - * blank spaces. - */ - public static final String ScaleOverCoverageProperty = "scaleOverCoverage"; - - // GUI button commands - public static final String showMapsCommand = "mapsCheckCmd"; - public static final String showInfoCommand = "infoCheckCmd"; - public static final String lockSeriesCommand = "lockSeriesCmd"; - public static final String showCoverageCommand = "coverageCheckCmd"; - public final static String showCGCommand = "showCG"; - - public final static String unlockedButtonTitle = "Limit Chart Selection"; - public final static String lockedButtonTitle = "Displaying Only"; - - /** - * Used to turn a particular coverage on or off. Well, off, really. All - * coverages are turned on by default. - */ - public final static String ShowCoverageProperty = "showcov"; - /** - * Use this property to change the color used for a particular chart type, - * i.e. propertyPrefix.chartSeriesAbbr.color = hexColorValue. - */ - public final static String ColorProperty = "color"; - - public static final String DefaultRPFCoveragePrefix = "rpfcov"; - - public final static float Various = -1f; - public final static String BLANK = ""; - public final static String VARIOUS = "Various"; - public final static String CADRG = "CADRG"; - public final static String CIB = "CIB"; - public final static String CDTED = "CDTED"; - public final static String CITYGRAPHICS = "City Graphics"; - public final static String TOPOLINEMAP = "Topographic Line Map"; - -} diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverage.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverage.java deleted file mode 100644 index 18cdd7406..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverage.java +++ /dev/null @@ -1,641 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverage.java,v $ -// $RCSfile: RpfCoverage.java,v $ -// $Revision: 1.9 $ -// $Date: 2005/12/09 21:09:05 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -/* Java Core */ -import java.awt.Color; -import java.awt.Component; -import java.awt.Paint; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ColorFactory; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * This is a tool that provides coverage information on the Rpf data. It is - * supposed to be a simple tool that lets you see the general location of data, - * to guide you to the right place and scale of coverage. The layer really uses - * the properties passed in to it to determine which RPF/A.TOC should be scanned - * for the data. There is a palette for this layer, that lets you turn off the - * coverage for different levels of Rpf. Right now, only City Graphics, TLM, - * JOG, TPC, ONC, JNC, GNC and 5/10 meter CIB scales are are handled. All other - * scales are tossed together under the misc setting. The City Graphics setting - * shows all charts for scales greater than than 1:15k. - *

- * - *

- *       The properties for this file are:
- *        # Java Rpf properties
- *        # Number between 0-255: 0 is transparent, 255 is opaque
- *        jrpf.coverageOpaque=255
- *        #Default is true, don't need this entry if you like it...
- *        jrpf.CG.showcov=true
- *        #Default colors don't need this entry
- *        jrpf.CG.color=CE4F3F
- *        # Other types can be substituted for CG (TLM, JOG, TPC, ONC, JNC, GNC, CIB10, CIB5, MISC)
- *        # Fill the rectangle, default is true
- *        jrpf.coverageFill=true
- * 
- */ -public class RpfCoverage extends OMGraphicList implements RpfConstants, PropertyConsumer { - - /** Property to use for filled rectangles (when java supports it). */ - public static final String CoverageOpaquenessProperty = "coverageOpaque"; - /** Property to use to fill rectangles. */ - public static final String FillProperty = "coverageFill"; - - /** - * - */ - private static final long serialVersionUID = 1L; - protected RpfCoverageManager coverageManager = null; - protected RpfFrameProvider frameProvider = null; - protected Map coverages = new TreeMap( - new RCCScaleComparator()); - protected String propertyPrefix = null; - /** - * A setting for how transparent to make the images. The default is 255, - * which is totally opaque. Not used right now. - */ - protected int opaqueness = RpfColortable.DEFAULT_OPAQUENESS; - /** Flag to fill the coverage rectangles. */ - protected boolean fillRects = true; - /** The parent layer. */ - protected Layer layer; - /** Flag to track when the RpfCoverage is active. */ - protected boolean inUse = false; - /** - * Show the palette when showing coverage. Probably not needed for layers - * limiting chart seriestypes for display. - */ - protected boolean showPalette = true; - - protected I18n i18n = Environment.getI18n(); - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - */ - public RpfCoverage(Layer l, RpfFrameProvider frameProvider) { - this.layer = l; - setFrameProvider(frameProvider); - - super.setTraverseMode(LAST_ADDED_ON_TOP); - } - - public void setFrameProvider(RpfFrameProvider frameProvider) { - this.frameProvider = frameProvider; - - if (frameProvider != null) { - List rpfCoverages = frameProvider.getCatalogCoverage(90f, -180f, -90f, 180f, - new CADRG(new LatLonPoint.Double(), 10000000f, 200, 200), null); - for (RpfCoverageBox rcb : rpfCoverages) { - RpfProductInfo rpfPI = RpfProductInfo.get(rcb.chartCode); - if (rpfPI != null) { - RpfCoverageControl control = coverages.get(RpfProductInfo.get(rcb.chartCode)); - if (control == null) { - control = new RpfCoverageControl(rpfPI, layer); - coverages.put(rpfPI, control); - control.setFilled(fillRects); - control.setFillPaint(getModifiedColor((Color) control.getFillPaint())); - } - } - - } - } - } - - /** Method that sets all the variables to the default values. */ - protected void setDefaultValues() { - allCoveragesOn(); - opaqueness = RpfColortable.DEFAULT_OPAQUENESS / 2; - fillRects = true; - } - - public boolean isInUse() { - return inUse; - } - - public void setInUse(boolean iu) { - inUse = iu; - this.setVisible(iu); // Show OMGraphics or not - if (showPalette || !inUse) { - // Always want it hidden if not in use. - JFrame covPalette = getPaletteWindow(); - covPalette.setLocationRelativeTo(layer.getPalette()); - covPalette.setVisible(inUse); - } - } - - public boolean isShowPalette() { - return showPalette; - } - - public void setShowPalette(boolean sp) { - showPalette = sp; - if (!showPalette) { - allCoveragesOn(); - } - } - - public void allCoveragesOn() { - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setVisible(true); - } - } - - public void setProperties(java.util.Properties props) { - setProperties(null, props); - } - - /** - * Set all the Rpf properties from a properties object. - * - * @param prefix - * string prefix used in the properties file for this layer. - * @param properties - * the properties set in the properties file. - */ - public void setProperties(String prefix, java.util.Properties properties) { - setPropertyPrefix(prefix); - - setDefaultValues(); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - fillRects = PropUtils.booleanFromProperties(properties, prefix + FillProperty, fillRects); - - showPalette = PropUtils.booleanFromProperties(properties, prefix + CoverageProperty, showPalette); - - opaqueness = PropUtils.intFromProperties(properties, prefix + CoverageOpaquenessProperty, opaqueness); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbrdot = PropUtils.getScopedPropertyPrefix(rcc.rpfProduct.abbr.replace(' ', '_')); - rcc.setColorValue(properties.getProperty(prefix + abbrdot + ColorProperty, rcc.getColorValue())); - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - rcc.setVisible(PropUtils.booleanFromProperties(properties, prefix + abbrdot + ShowCoverageProperty, - rcc.isVisible())); - } - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props - * a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - if (props == null) { - props = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(propertyPrefix); - - props.put(prefix + FillProperty, new Boolean(fillRects).toString()); - props.put(prefix + CoverageProperty, new Boolean(showPalette).toString()); - props.put(prefix + CoverageOpaquenessProperty, Integer.toString(opaqueness)); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbr = rcc.rpfProduct.abbr.replace(' ', '_'); - String abbrdot = PropUtils.getScopedPropertyPrefix(abbr); - props.put(prefix + abbrdot + ColorProperty, Integer.toHexString(((Color) rcc.getLinePaint()).getRGB())); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list - * a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, FillProperty, "Fill Coverage Rectangles", - "Flag to set if the coverage rectangles should be filled.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, CoverageProperty, "Show Coverage Palette", - "Flag to set the coverage palette should be shown.", - "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, CoverageOpaquenessProperty, "Coverage Opaqueness", - "Integer representing opaqueness level (0-255, 0 is clear) of coverage rectangles.", null); - - for (RpfCoverageControl rcc : coverages.values()) { - String abbr = rcc.rpfProduct.abbr.replace(' ', '_'); - String abbrdot = PropUtils.getScopedPropertyPrefix(abbr); - PropUtils.setI18NPropertyInfo(i18n, list, RpfLayer.class, abbrdot + ColorProperty, - rcc.rpfProduct.abbr + " Coverage Color", "Color for " + abbr + " chart coverage.", - "com.bbn.openmap.util.propertyEditor.ColorPropertyEditor"); - } - - return list; - } - - /** - * Specify what order properties should be presented in an editor. - */ - public String getInitPropertiesOrder() { - StringBuilder sb = new StringBuilder(" " + FillProperty + " " + CoverageOpaquenessProperty); - for (RpfProductInfo rpi : coverages.keySet()) { - sb.append(" ").append(rpi.abbr.replace(' ', '_')).append(".").append(ColorProperty); - } - return sb.toString(); - } - - /** - * Set the property key prefix that should be used by the PropertyConsumer. - * The prefix, along with a '.', should be prepended to the property keys - * known by the PropertyConsumer. - * - * @param prefix - * the prefix String. - */ - public void setPropertyPrefix(String prefix) { - propertyPrefix = prefix; - } - - /** - * Get the property key prefix that is being used to prepend to the property - * keys for Properties lookups. - * - * @return the property prefix - */ - public String getPropertyPrefix() { - return propertyPrefix; - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the rpfcov. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - */ - public void prepare(Projection projection, String chartSeries) { - - double ullat = 90; - double ullon = -180; - double lrlat = -90; - double lrlon = 180; - - if (projection != null) { - ullat = projection.getUpperLeft().getY(); - ullon = projection.getUpperLeft().getX(); - lrlat = projection.getLowerRight().getY(); - lrlon = projection.getLowerRight().getX(); - } - - Debug.message("basic", "RpfCoverage.prepare(): doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // IF the data arrays have not been set up yet, do it! - if (coverageManager == null) { - coverageManager = new RpfCoverageManager(frameProvider); - } - - clearLayerAndCoverages(); - coverageManager.getCatalogCoverage(ullat, ullon, lrlat, lrlon, projection, chartSeries, coverages); - resetCoveragesOnLayer(); - } - - protected void clearLayerAndCoverages() { - this.clear(); - for (RpfCoverageControl rcc : coverages.values()) { - rcc.clear(); - } - } - - protected void resetCoveragesOnLayer() { - this.clear(); - for (RpfCoverageControl rcc : coverages.values()) { - if (rcc.getVisibilityToggle().isSelected()) { - this.addAll(rcc); - } - } - } - - /** - * @return Returns the opaqueness. - */ - public int getOpaqueness() { - return opaqueness; - } - - /** - * @param opaqueness - * The opaqueness to set. - */ - public void setOpaqueness(int opaqueness) { - this.opaqueness = opaqueness; - - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - } - - } - - /** - * @return the fillRects - */ - public boolean isFillRects() { - return fillRects; - } - - /** - * @param fillRects - * the fillRects to set - */ - public void setFillRects(boolean fillRects) { - this.fillRects = fillRects; - - if (coverages != null) { - for (RpfCoverageControl rcc : coverages.values()) { - rcc.setFilled(fillRects); - rcc.setFillPaint(getModifiedColor((Color) rcc.getFillPaint())); - } - } - } - - protected Color getModifiedColor(Color color) { - if (opaqueness < 255) { - int opa = opaqueness << 24; - return ColorFactory.createColor(((color.getRGB() & 0x00FFFFFF) | opa), true); - } else { - return ColorFactory.createColor(color.getRGB(), true); - } - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - Box box = Box.createVerticalBox(); - - box.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Coverage Controls")); - - if (coverages != null) { - for (RpfProductInfo rpi : coverages.keySet()) { - box.add(coverages.get(rpi).getVisibilityToggle()); - } - } - - return box; - } - - public static class RpfCoverageControl extends OMGraphicList { - - private static final long serialVersionUID = 1L; - - RpfProductInfo rpfProduct; - Layer layer; - JCheckBox controlToggle; - String colorValue; - - public RpfCoverageControl(RpfProductInfo rpfPro, Layer layer) { - this.rpfProduct = rpfPro; - this.layer = layer; - - Color c = DefaultColors.getColor(rpfPro); - setLinePaint(c); - setColorValue(Integer.toHexString(c.getRGB())); - } - - public JCheckBox getVisibilityToggle() { - if (controlToggle == null) { - StringBuilder title = new StringBuilder("Show "); - title.append(rpfProduct.abbr).append(" Coverage"); - - controlToggle = new JCheckBox(title.toString(), true); - controlToggle.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - RpfCoverageControl.this.setVisible(((JCheckBox) ae.getSource()).isSelected()); - if (layer != null) { - if (layer instanceof RpfLayer && ((RpfLayer)layer).coverage != null) { - ((RpfLayer)layer).coverage.resetCoveragesOnLayer(); - } - layer.repaint(); - } - } - }); - - } - return controlToggle; - } - - public boolean add(OMGraphic omg) { - omg.setLinePaint(getLinePaint()); - omg.setFillPaint(getFillPaint()); - return super.add(omg); - } - - public void setFilled(boolean filled) { - if (filled) { - setFillPaint(getLinePaint()); - } else { - setFillPaint(OMColor.clear); - } - } - - public boolean isFilled() { - Paint fPaint = getFillPaint(); - return fPaint == null || fPaint == OMColor.clear; - } - - public void setVisible(boolean set) { - super.setVisible(set); - if (controlToggle != null) { - controlToggle.setSelected(set); - } - } - - /** - * @return the colorValue - */ - public String getColorValue() { - return colorValue; - } - - /** - * @param colorValue - * the colorValue to set - */ - public void setColorValue(String colorValue) { - try { - this.colorValue = colorValue; - setLinePaint(PropUtils.parseColor(colorValue)); - } catch (NumberFormatException nfe) { - } - } - - } - - public static class RCCScaleComparator implements Comparator { - public int compare(RpfProductInfo c1, RpfProductInfo c2) { - double diff = c1.scale - c2.scale; - if (diff == 0) { - return 0; - } else if (diff < 0) { - return 1; - } else { - return -1; - } - } - } - - protected JFrame paletteWindow = null; - - /** - * Get RpfCoverage's associated palette as a top-level window - * - * @return the frame that the palette is in - */ - public JFrame getPaletteWindow() { - - if (paletteWindow == null) { - // create the palette's scroll pane - Component pal = getGUI(); - - if (pal == null) { - pal = new JLabel("No Coverage Information Available."); - } - - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - p.setAlignmentX(Component.LEFT_ALIGNMENT); - p.setAlignmentY(Component.BOTTOM_ALIGNMENT); - p.add(pal); - - JScrollPane scrollPane = new JScrollPane(p, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); - scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); - - // create the palette internal window - paletteWindow = new JFrame("RPF Coverage Palette"); - - paletteWindow.setContentPane(scrollPane); - paletteWindow.pack();// layout all the components - } - return paletteWindow; - } - - protected enum DefaultColors { - - CG(RpfProductInfo.CG, 0xAC4853), - TLM(RpfProductInfo.TL, 0xCE4F3F), - JOG(RpfProductInfo.JG, 0xAC7D74), - TPC(RpfProductInfo.TP, 0xACCD10), - ONC(RpfProductInfo.ON, 0xFCCDE5), - JNC(RpfProductInfo.JN, 0x7386E5), - GNC(RpfProductInfo.GN, 0x55866B), - CIB10(RpfProductInfo.I1, 0x07516B), - CIB5(RpfProductInfo.I2, 0x071CE0), - MISC(RpfProductInfo.MM, 0xF2C921); - - private RpfProductInfo rpi; - private int defaultColorInt; - - DefaultColors(RpfProductInfo rpi, int defaultColorInt) { - this.rpi = rpi; - this.defaultColorInt = defaultColorInt; - } - - static int getColorInt(RpfProductInfo rpi) { - for (DefaultColors dc : DefaultColors.values()) { - if (dc.rpi.equals(rpi)) { - return dc.defaultColorInt; - } - } - return MISC.defaultColorInt; - } - - static Color getColor(RpfProductInfo rpi) { - return new Color(DefaultColors.getColorInt(rpi)); - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageManager.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageManager.java deleted file mode 100644 index ea6803485..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageManager.java +++ /dev/null @@ -1,124 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfCoverageManager.java,v $ -// $RCSfile: RpfCoverageManager.java,v $ -// $Revision: 1.6 $ -// $Date: 2007/06/21 21:39:03 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMRect; -import com.bbn.openmap.proj.CADRG; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * This is an object that provides coverage information on the Rpf data. It is - * supposed to be a simple tool that lets you see the general location of data, - * to guide you to the right place and scale of coverage. The layer really uses - * the properties passed in to it to determine which RPF/A.TOC should be scanned - * for the data. There is a palette for this layer, that lets you turn off the - * coverage for different levels of Rpf. Right now, only City Graphics, TLM, - * JOG, TPC, ONC, JNC, GNC and 5/10 meter CIB scales are are handled. All other - * scales are tossed together under the misc setting. The City Graphics setting - * shows all charts for scales greater than than 1:15k. - */ -public class RpfCoverageManager { - - /** - * The last line type of the edge of the rectangles. Used to determine - * whether the line needs to be re-projected based on a projection change. - */ - protected int currentLineType = OMGraphic.LINETYPE_RHUMB; - - /** The place to get the coverage information, */ - protected RpfFrameProvider frameProvider; - - /** Don't use this. */ - public RpfCoverageManager(RpfFrameProvider rfp) { - frameProvider = rfp; - } - - /** - * Get the map coverage - * - * @param ullat - * @param ullon - * @param lrlat - * @param lrlon - * @param proj projection for display - * @param chartSeries the chart series to query for, may be null for all coverages - * @param coverages The Map to be modified - */ - protected void getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection proj, - String chartSeries, Map coverages) { - - Debug.message("rpfcov", "RpfCoverageManager: Getting catalog coverage from RpfFrameProvider"); - if (proj == null || frameProvider == null) { - return; - } - - CADRG cadrg; - if (proj instanceof CADRG) { - cadrg = (CADRG) proj; - } else { - cadrg = new CADRG((LatLonPoint) proj.getCenter(new LatLonPoint.Float()), proj.getScale(), proj.getWidth(), - proj.getHeight()); - } - - List hemisphereData = new ArrayList(); - - if (ProjMath.isCrossingDateline(ullon, lrlon, proj.getScale())) { - - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, ullon, lrlat, 180f, cadrg, chartSeries)); - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, -180f, lrlat, lrlon, cadrg, chartSeries)); - } else { - hemisphereData.addAll(frameProvider.getCatalogCoverage(ullat, ullon, lrlat, lrlon, cadrg, chartSeries)); - } - - boolean checkSeries = !(chartSeries == null || chartSeries.equals(RpfViewAttributes.ANY) || chartSeries.equals(RpfViewAttributes.ALL)); - - for (RpfCoverageBox box : hemisphereData) { - - OMRect rect = new OMRect(box.nw_lat, box.nw_lon, box.se_lat, box.se_lon, currentLineType); - - RpfProductInfo rpi = RpfProductInfo.get(box.chartCode); - - - if (rpi != null) { - - if (checkSeries && !rpi.seriesCode.equalsIgnoreCase(chartSeries)) { - continue; - } - - RpfCoverage.RpfCoverageControl control = coverages.get(rpi); - if (control != null) { - control.add(rect); - rect.generate(proj); - } - } - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameProvider.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameProvider.java deleted file mode 100644 index 1c9f154cd..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameProvider.java +++ /dev/null @@ -1,133 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfFrameProvider.java,v $ -// $RCSfile: RpfFrameProvider.java,v $ -// $Revision: 1.4 $ -// $Date: 2005/05/23 20:08:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.util.List; - -import com.bbn.openmap.proj.Projection; - -/** - * The RpfFrameProvider describes an interface to an object that can provide - * information about RPF coverage over a certain area, and also retrieve data - * from the RPF frame files. - */ -public interface RpfFrameProvider { - - /** - * Returns true if the view attributes should be set if they change at the - * RpfCacheHandler/RpfCacheManager. If the source of the data is a server, - * this should return yes. If the source is local, the view attributes will - * be a shared object and updates are not necessary. - */ - public boolean needViewAttributeUpdates(); - - /** - * Set the RpfViewAttribute object parameters, which describes a lot about - * what you'll be asking for later. - */ - public void setViewAttributes(RpfViewAttributes rva); - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know how to locate and ask for - * RpfSubframes. - */ - public List getCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p); - - /** - * Given a projection that describes a map or geographical area, return - * RpfCoverageBoxes that let you know what bounding boxes of data are - * available. - * - * @param ullat - * upper lat - * @param ullon - * left lon - * @param lrlat - * lower lat - * @param lrlon - * right lon - * @param chartSeries - * can be null to see all/any. - */ - public List getCatalogCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p, - String chartSeries); - - /** - * Given an area and a two-letter chart series code, find the percentage of - * coverage on the map that that chart series can offer. If you want - * specific coverage information, use the getCatalogCoverage call. - * - * @see #getCatalogCoverage(double, double, double, double, Projection, String) - */ - public float getCalculatedCoverage(double ullat, double ullon, double lrlat, double lrlon, Projection p, - String chartSeries); - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame/subframe data, decompress it, and return image pixels. The - * tocNumber and entryNumber are given within the RpfCoverageBox received - * from a getCoverage call. - * - * @param tocNumber - * the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber - * the RpfTocEntry id for a RpfTocHandler for a particular frame - * provider. - * @param x - * the horizontal subframe index, from the left side of a - * boundary rectangle of the entry. - * @param y - * the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(double, double, double, double, Projection) - * @return integer pixel data. - */ - public int[] getSubframeData(int tocNumber, int entryNumber, int x, int y); - - public RpfIndexedImageData getRawSubframeData(int tocNumber, int entryNumber, int x, int y); - - /** - * Given the indexes to a certain RpfTocEntry within a certain A.TOC, find - * the frame and return the attribute information. The tocNumber and - * entryNumber are given within the RpfCoverageBox received from a - * getCoverage call. - * - * @param tocNumber - * the toc id for a RpfTocHandler for a particular frame - * provider. - * @param entryNumber - * the RpfTocEntry id for a RpfTocHandler for a particular frame - * provider. - * @param x - * the horizontal subframe index, from the left side of a - * boundary rectangle of the entry. - * @param y - * the vertical subframe index, from the top side of a boundary - * rectangle of the entry. - * @see #getCoverage(double, double, double, double, Projection) - * @return string. - */ - public String getSubframeAttributes(int tocNumber, int entryNumber, int x, int y); -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfLayer.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfLayer.java deleted file mode 100644 index 265d60209..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfLayer.java +++ /dev/null @@ -1,801 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfLayer.java,v $ -// $RCSfile: RpfLayer.java,v $ -// $Revision: 1.23 $ -// $Date: 2008/09/17 20:47:51 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.rpf; - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.List; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JCheckBox; -import javax.swing.JPanel; - -import com.bbn.openmap.I18n; -import com.bbn.openmap.event.SelectMouseMode; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.layer.policy.ListResetPCPolicy; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMList; -import com.bbn.openmap.omGraphics.OMRaster; -import com.bbn.openmap.omGraphics.event.MapMouseInterpreter; -import com.bbn.openmap.proj.EqualArc; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; -import com.bbn.openmap.util.cacheHandler.CacheHandler; - -/** - * The RpfLayer fills the screen with RPF data. There is also a tool available - * that allows you to see the coverage of the available data. To view theimages, - * the projection of the map has to be set in the ARC projection, which OpenMap - * calls the CADRG projection. The RpfLayer can use several RPF directories at - * the same time, and doesn't require that the data actually be there at - * runtime. That way, you can give a location where the data may be mouted - * during runtime(i.e. CDROM) and the layer will still use the data. The scale - * of the projection does not necessarily have to match the scale of a map - * series for that series to be displayed. There are options, set in the - * RpfViewAttributes, that allow scaling of the RPF images to match the map - * scale. - *

- * - * The RpfLayer uses the RpfCacheManager to get the images it needs to display. - * Whenever the projection changes, the cache manager takes the new projection - * and creates a OMGraphicList with the new image frames and attribute text. - *

- * - * The RpfLayer gets its initial settings from properties. This should be done - * right after the RpfLayer is created. The properties list contains the - * location of the RPF directories, the opaqueness of the images, the number of - * colors to use, and whether to show the images and/or attributes by default. - * An example of the RpfLayer properties: - *

- * - *

- * 
- * 
- *           #-----------------------------
- *           # Properties for RpfLayer
- *           #-----------------------------
- *           # Mandatory properties
- *           # This property should reflect the paths to the RPF directories
- *           rpf.paths=/usr/local/matt/data/RPF;/usr/local/matt/data/CIB/RPF
- *           
- *           # Optional Properties - the default will be set if these are not 
- *           # included in the properties file: 
- *           # Number between 0-255: 0 is transparent, 255 is opaque.  255 is default.
- *           rpf.opaque=128
- *           
- *           # Number of colors to use on the maps - 16, 32, 216.  216 is default.
- *           rpf.numberColors=216
- *           
- *           # Display maps on startup.  Default is true.
- *           rpf.showMaps=true
- *           
- *           # Display attribute information on startup.  Default is false.
- *           rpf.showInfo=false
- *           
- *           # Scale charts to match display scale.  Default is true.
- *           rpf.scaleImages=true
- *           
- *           # The scale factor to allow when scaling images (2x, 4x, also mean 1/2, 1/4).  Default is 4.
- *           rpf.imageScaleFactor=4
- *           
- *           # Delete the cache if the layer is removed from the map.  Default is false.
- *           rpf.killCache=true
- *           # Limit the display to the chart code specified. (GN, JN, ON, TP, etc.).
- *           # Default is ANY
- *           rpf.chartSeries=ANY
- *           # Get the subframe attribute data from the Frame provider.
- *           rpf.autofetchAttributes=false
- *           # Set to true if you want the coverage tool available.
- *           rpf.coverage=true
- *           # Set the subframe cache size. (Number of subframes to hold on to, 256x256 pixels)
- *           rpf.subframeCacheSize=128
- *           # Then also include coverage properties, which are available in the RpfConstants.
- *           #------------------------------------
- *           # End of properties for RpfLayer
- *           #------------------------------------
- * 
- * 
- * 
- * - */ -public class RpfLayer extends OMGraphicHandlerLayer implements ActionListener, RpfConstants, Serializable { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.rpf.RpfLayer"); - protected static Logger rpfLogger = Logger.getLogger("RPF"); - - private static final long serialVersionUID = 1L; - /** - * The main source for the images and attribute information. All requests - * for graphic objects should go through this cache, and it will - * automatically handle getting the frame files, decoding them, and - * returning an object list. - */ - protected transient RpfCacheManager cache = null; - /** The paths to the RPF directories, telling where the data is. */ - protected String[] paths; - /** - * The display attributes for the maps. This object should not be replaced, - * because the caches all look at it, too. Just adjust the parameters within - * it. - * - * @see RpfViewAttributes - */ - protected RpfViewAttributes viewAttributes; - /** Flag to delete the cache if the layer is removed from the map. */ - protected boolean killCache = true; - /** The supplier of frame data. */ - protected RpfFrameProvider frameProvider; - /** The coverage tool for the layer. */ - protected RpfCoverage coverage; - /** Subframe cache size. Default is 40. */ - protected int subframeCacheSize = RpfCacheHandler.SUBFRAME_CACHE_SIZE; - /** Auxiliary subframe cache size. Default is 10. */ - protected int auxSubframeCacheSize = RpfCacheManager.SMALL_CACHE_SIZE; - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. Use this construct if you are going to use a - * standard properties file, which will set the paths. - */ - public RpfLayer() { - setName("RPF"); - viewAttributes = new RpfViewAttributes(); - setProjectionChangePolicy(new ListResetPCPolicy(this)); - // setRenderPolicy(new BufferedImageRenderPolicy(this)); - setMouseModeIDsForEvents(new String[] { SelectMouseMode.modeID }); - - showSubframes(false); - } - - /** - * The default constructor for the Layer. All of the attributes are set to - * their default values. - * - * @param pathsToRPFDirs - * paths to the RPF directories that hold A.TOC files. - */ - public RpfLayer(String[] pathsToRPFDirs) { - this(); - setPaths(pathsToRPFDirs); - } - - /** - * Set the paths to the RPF directories, which are by default the parents of - * the A.TOC table of contents files. Creates the RpfFrameProvider. - * - * @param pathsToRPFDirs - * Array of strings that list the paths to RPF directories. - */ - public void setPaths(String[] pathsToRPFDirs) { - if (paths != null && pathsToRPFDirs != null && paths.length == pathsToRPFDirs.length) { - // If the paths haven't changed, don't do anything. - boolean same = true; - for (int i = 0; i < paths.length; i++) { - same = same && paths[i].equals(pathsToRPFDirs[i]); - } - - if (same && frameProvider != null) { - return; - } - } - - if (pathsToRPFDirs != null) { - setFrameProvider(new RpfFrameCacheHandler(pathsToRPFDirs)); - } else { - logger.warning("Need RPF directory paths."); - frameProvider = null; - } - paths = pathsToRPFDirs; - - setCoverage(new RpfCoverage(this, frameProvider)); - - this.cache = null; - } - - /** - * Get the paths to the RPF directories. - * - * @return String[] - */ - public String[] getPaths() { - return paths; - } - - /** - * Called when the layer is no longer part of the map. In this case, we - * should disconnect from the server if we have a link. - */ - public void removed(java.awt.Container cont) { - if (killCache) { - rpfLogger.fine("emptying cache!"); - clearCache(); - } - - // need to reset this for when it gets added again, if it was - // removed without the projection actually changing. This - // helps when the cache needs to be rebuilt. - setProjection((Projection) null); - } - - protected void setDefaultValues() { - // defaults - paths = null; - } - - /** - * Set all the RPF properties from a properties object. - */ - public void setProperties(String prefix, java.util.Properties properties) { - - super.setProperties(prefix, properties); - - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - setPaths(PropUtils.initPathsFromProperties(properties, prefix + RpfPathsProperty, paths)); - - viewAttributes.setProperties(prefix, properties); - showSubframes(viewAttributes.showInfo); - - subframeCacheSize = PropUtils.intFromProperties(properties, prefix + CacheSizeProperty, subframeCacheSize); - - auxSubframeCacheSize = PropUtils.intFromProperties(properties, prefix + CacheSizeProperty, - auxSubframeCacheSize); - - if (viewAttributes.chartSeries == null) - viewAttributes.chartSeries = RpfViewAttributes.ANY; - - killCache = PropUtils.booleanFromProperties(properties, prefix + KillCacheProperty, killCache); - - if (coverage != null) { - coverage.setProperties(prefix, properties); - } - - resetPalette(); - } - - /** - * PropertyConsumer method, to fill in a Properties object, reflecting the - * current values of the layer. If the layer has a propertyPrefix set, the - * property keys should have that prefix plus a separating '.' prepended to - * each property key it uses for configuration. - * - * @param props - * a Properties object to load the PropertyConsumer properties - * into. If props equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - // find out paths... - String[] p = getPaths(); - StringBuffer pathString = new StringBuffer(); - if (p != null) { - for (int i = 0; i < p.length; i++) { - if (p[i] != null) { - pathString.append(p[i]); - if (i < p.length - 1) { - pathString.append(";"); // separate paths with - // ; - } - } - } - props.put(prefix + RpfPathsProperty, pathString.toString()); - } else { - props.put(prefix + RpfPathsProperty, ""); - } - - props.put(prefix + KillCacheProperty, new Boolean(killCache).toString()); - props.put(prefix + CacheSizeProperty, Integer.toString(subframeCacheSize)); - props.put(prefix + AuxCacheSizeProperty, Integer.toString(auxSubframeCacheSize)); - - viewAttributes.setPropertyPrefix(prefix); - viewAttributes.getProperties(props); - - if (coverage == null) { - RpfCoverage cov = new RpfCoverage(this, frameProvider); - cov.setProperties(prefix, new Properties()); - cov.getProperties(props); - } else { - coverage.getProperties(props); - } - - return props; - } - - /** - * Method to fill in a Properties object with values reflecting the - * properties able to be set on this PropertyConsumer. The key for each - * property should be the raw property name (without a prefix) with a value - * that is a String that describes what the property key represents, along - * with any other information about the property that would be helpful - * (range, default value, etc.). For Layer, this method should at least - * return the 'prettyName' property. - * - * @param list - * a Properties object to load the PropertyConsumer properties - * into. If getList equals null, then a new Properties object - * should be created. - * @return Properties object containing PropertyConsumer property values. If - * getList was not null, this should equal getList. Otherwise, it - * should be the Properties object created by the PropertyConsumer. - */ - public Properties getPropertyInfo(Properties list) { - list = super.getPropertyInfo(list); - String interString; - - interString = i18n.get(RpfLayer.class, RpfPathsProperty, I18n.TOOLTIP, - "Paths to RPF directories. Semi-colon separated paths."); - list.put(RpfPathsProperty, interString); - list.put(RpfPathsProperty + ScopedEditorProperty, - "com.bbn.openmap.util.propertyEditor.MultiDirectoryPropertyEditor"); - interString = i18n.get(RpfLayer.class, RpfPathsProperty, "Data Path"); - list.put(RpfPathsProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, KillCacheProperty, I18n.TOOLTIP, - "Flag to trigger the cache to be cleared when layer is removed from the map."); - list.put(KillCacheProperty, interString); - list.put(KillCacheProperty + ScopedEditorProperty, "com.bbn.openmap.util.propertyEditor.OnOffPropertyEditor"); - interString = i18n.get(RpfLayer.class, KillCacheProperty, "Clear Cache"); - list.put(KillCacheProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, CacheSizeProperty, I18n.TOOLTIP, - "Number of frames to hold in the frame cache."); - list.put(CacheSizeProperty, interString); - interString = i18n.get(RpfLayer.class, CacheSizeProperty, "Frame Cache Size"); - list.put(CacheSizeProperty + LabelEditorProperty, interString); - - interString = i18n.get(RpfLayer.class, AuxCacheSizeProperty, I18n.TOOLTIP, - "Number of frames to hold in aux. frame caches."); - list.put(AuxCacheSizeProperty, interString); - interString = i18n.get(RpfLayer.class, AuxCacheSizeProperty, "Aux Frame Cache Size"); - list.put(AuxCacheSizeProperty + LabelEditorProperty, interString); - - viewAttributes.getPropertyInfo(list); - - RpfCoverage tmpCov = coverage; - if (tmpCov == null) { - tmpCov = new RpfCoverage(this, frameProvider); - } - - tmpCov.getPropertyInfo(list); - - list.put(initPropertiesProperty, - RpfPathsProperty + " " + KillCacheProperty + " " + CacheSizeProperty + " " + AuxCacheSizeProperty + " " - + viewAttributes.getInitPropertiesOrder() + " " + AddToBeanContextProperty + " " - + AddAsBackgroundProperty + " " + RemovableProperty + " " + CoverageProperty + " " - + tmpCov.getInitPropertiesOrder()); - - return list; - } - - public void resetPalette() { - box = null; - // if (coverage != null) { - // if (coverage.isInUse()) { - // coverage.resetColors(); - // } - // } - - super.resetPalette(); - } - - /** - * Clear the frame cache. - */ - public void clearCache() { - - if (frameProvider instanceof CacheHandler) { - ((CacheHandler) frameProvider).resetCache(); - } - - if (this.cache != null) { - this.cache.setViewAttributes(null); - this.cache.setFrameProvider(null); - this.cache.clearCaches(); - } - - frameProvider = null; - - setList(null); - this.cache = null; - } - - /** - * Set the view attributes for the layer. The frame provider view attributes - * are updated, and the cache is cleared. - * - * @param rva - * the RpfViewAttributes used for the layer. - */ - public void setViewAttributes(RpfViewAttributes rva) { - viewAttributes = rva; - if (this.cache != null) { - this.cache.setViewAttributes(rva); - } - } - - /** - * Get the view attributes or the layer. - * - * @return RpfViewAttributes. - */ - public RpfViewAttributes getViewAttributes() { - return viewAttributes; - } - - /** - * Set the RpfCoverage tool used by the layer. If the view attributes chart - * series setting is not equal to RpfViewAttributes.ANY, then the palette of - * the tool is not shown. - * - * @param cov - * the RpfCoverage tool. - */ - public void setCoverage(RpfCoverage cov) { - coverage = cov; - if (coverage != null) { - if (viewAttributes != null && !viewAttributes.chartSeries.equalsIgnoreCase(RpfViewAttributes.ANY)) { - coverage.setShowPalette(false); - } - coverage.coverageManager = null; - } - } - - /** - * Return the coverage tool used by the layer. - * - * @return RpfCoverage tool. - */ - public RpfCoverage getCoverage() { - return coverage; - } - - /** - * Set the RpfFrameProvider for the layer. Clears out the cache, and the - * frame provider gets the RpfViewAttributes held by the layer. - * - * @param fp - * the frame provider. - */ - public void setFrameProvider(RpfFrameProvider fp) { - frameProvider = fp; - if (this.cache != null) { - this.cache.setFrameProvider(frameProvider); - } - } - - /** - * Return RpfFrameProvider used by the layer. - */ - public RpfFrameProvider getFrameProvider() { - return frameProvider; - } - - /** - * Returns the Vector containing RpfCoverageBoxes that was returned from the - * RpfFrameProvider as a result of the last setCache call. These provide - * rudimentary knowledge about what is being displayed. This vector is from - * the primary cache handler. - * - * @return Vector of RpfCoverageBoxes. - */ - public List getCoverageBoxes() { - return this.cache.getCoverageBoxes(); - } - - /** - * Prepares the graphics for the layer. This is where the getRectangle() - * method call is made on the rpf. - *

- * Occasionally it is necessary to abort a prepare call. When this happens, - * the map will set the cancel bit in the LayerThread, (the thread that is - * running the prepare). If this Layer needs to do any cleanups during the - * abort, it should do so, but return out of the prepare asap. - * - * @return graphics list of images and attributes. - */ - public synchronized OMGraphicList prepare() { - - Projection projection = getProjection(); - OMGraphicList retList = new OMGraphicList(); - retList.setTraverseMode(OMList.FIRST_ADDED_ON_TOP); - - if (frameProvider == null) { - // Assuming running locally - otherwise the - // frameProvider should be set before we get here, - // like in setProperties or in the constructor. - setPaths(paths); - if (frameProvider == null) { - // Doh! no paths were set! - logger.warning(getName() - + ": null frame provider - either no RPF paths were set, or no frame provider was assigned. The RpfLayer has no way to get RPF data."); - return retList; - } - } - - if (coverage != null && coverage.isInUse()) { - coverage.prepare(projection, viewAttributes.chartSeries); - retList.add(coverage); - } - - // Check the current minScale and maxScale set on the layer, ignore if - // projection scale is out of range. - if (!isProjectionOK(projection)) { - return retList; - } - - if (this.cache == null) { - rpfLogger.fine(getName() + ": Creating cache!"); - this.cache = new RpfCacheManager(frameProvider, viewAttributes, subframeCacheSize, auxSubframeCacheSize); - } - - // Check to make sure the projection is CADRG - if (!(projection instanceof EqualArc) && (viewAttributes.showMaps || viewAttributes.showInfo)) { - // fireRequestInfoLine("RpfLayer runs faster with an Equal Arc - // projection (CADRG/LLXY)."); - } - - rpfLogger.fine(getName() + " doing it"); - - // Setting the OMGraphicsList for this layer. Remember, the - // OMGraphicList is made up of OMGraphics, which are generated - // (projected) when the graphics are added to the list. So, - // after this call, the list is ready for painting. - - // call getRectangle(); - if (rpfLogger.isLoggable(Level.FINE)) { - rpfLogger.fine(getName() + "calling getRectangle " + " with projection: " + projection + " ul = " - + projection.getUpperLeft() + " lr = " + projection.getLowerRight()); - } - - if (frameProvider.needViewAttributeUpdates()) { - frameProvider.setViewAttributes(viewAttributes); - } - - try { - - // OMGraphics are generated by the RpfCacheHandlers when fetched - retList.addAll(this.cache.getRectangle(projection)); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(getName() + ": finished with " + retList.size() + " graphics"); - } - - } catch (java.lang.NullPointerException npe) { - logger.warning(getName() + ": Something really bad happened - \n " + npe); - npe.printStackTrace(); - retList = new OMGraphicList(); - this.cache = null; - } - - return retList; - } - - public boolean isHighlightable(OMGraphic omg) { - return viewAttributes.showInfo && omg instanceof OMRaster && omg.isSelected(); - } - - public String getToolTipTextFor(OMGraphic omg) { - return (String) omg.getAttribute(OMGraphic.TOOLTIP); - } - - /** - * Overridden to do nothing because we want nothing to happen. - */ - public void highlight(OMGraphic omg) { - - } - - /** - * Overridden to do nothing because we want nothing to happen. - */ - public void unhighlight(OMGraphic omg) { - - } - - // ---------------------------------------------------------------------- - // GUI - // ---------------------------------------------------------------------- - private transient JPanel box = null; - - /** - * Provides the palette widgets to control the options of showing maps, or - * attribute text. - * - * @return Component object representing the palette widgets. - */ - public java.awt.Component getGUI() { - if (box == null) { - JCheckBox showInfoCheck, lockSeriesCheck; - - box = new JPanel(); - GridBagLayout gridbag = new GridBagLayout(); - GridBagConstraints c = new GridBagConstraints(); - box.setLayout(gridbag); - - c.anchor = GridBagConstraints.NORTHWEST; - c.gridx = GridBagConstraints.REMAINDER; - - showInfoCheck = new JCheckBox("Show Attributes", viewAttributes.showInfo); - showInfoCheck.setActionCommand(showInfoCommand); - showInfoCheck.addActionListener(this); - - String tmpCS = viewAttributes.chartSeries; - if (tmpCS == null) { - tmpCS = RpfViewAttributes.ANY; - } - - boolean locked = !tmpCS.equalsIgnoreCase(RpfViewAttributes.ANY); - String lockedTitle = locked ? (lockedButtonTitle + " - " + tmpCS) : unlockedButtonTitle; - - lockSeriesCheck = new JCheckBox(lockedTitle, locked); - lockSeriesCheck.setActionCommand(lockSeriesCommand); - lockSeriesCheck.addActionListener(this); - - // box1.add(showMapsCheck); - gridbag.setConstraints(showInfoCheck, c); - box.add(showInfoCheck); - gridbag.setConstraints(lockSeriesCheck, c); - box.add(lockSeriesCheck); - - if (coverage != null) { - JCheckBox showCoverageCheck = new JCheckBox("Show Coverage", coverage.isInUse()); - showCoverageCheck.setActionCommand(showCoverageCommand); - showCoverageCheck.addActionListener(this); - gridbag.setConstraints(showCoverageCheck, c); - box.add(showCoverageCheck); - } - - JPanel layerStuff = getDefaultSettingsPanel(RpfLayer.class, viewAttributes.opaqueness / 255f); - gridbag.setConstraints(layerStuff, c); - box.add(layerStuff); - } - return box; - } - - // ---------------------------------------------------------------------- - // ActionListener interface implementation - // ---------------------------------------------------------------------- - - /** - * The Action Listener method, that reacts to the palette widgets actions. - */ - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - String cmd = e.getActionCommand(); - if (cmd == showMapsCommand) { - JCheckBox mapCheck = (JCheckBox) e.getSource(); - viewAttributes.showMaps = mapCheck.isSelected(); - repaint(); - } else if (cmd == showInfoCommand) { - JCheckBox infoCheck = (JCheckBox) e.getSource(); - boolean showInfo = infoCheck.isSelected(); - viewAttributes.showInfo = showInfo; - showSubframes(showInfo); - doPrepare(); - } else if (cmd == lockSeriesCommand) { - JCheckBox lockCheck = (JCheckBox) e.getSource(); - boolean locked = lockCheck.isSelected(); - if (locked) { - List coverageBoxes = getCoverageBoxes(); - String seriesName; - - if (coverageBoxes == null || coverageBoxes.isEmpty()) { - seriesName = RpfViewAttributes.ANY; - } else { - seriesName = coverageBoxes.get(0).chartCode; - } - - if (seriesName == null) { - seriesName = RpfViewAttributes.ANY; - fireRequestMessage("The " + getName() - + " Layer is having trouble determining what kind\nof charts are being displayed. Can't establish lock for charts\ncurrently being viewed."); - } - - lockCheck.setText(lockedButtonTitle + " - " + seriesName); - viewAttributes.chartSeries = seriesName; - - } else { - lockCheck.setText(unlockedButtonTitle); - viewAttributes.chartSeries = RpfViewAttributes.ANY; - } - - } else if (cmd == showCoverageCommand) { - if (coverage != null) { - JCheckBox coverageCheck = (JCheckBox) e.getSource(); - coverage.setInUse(coverageCheck.isSelected()); - doPrepare(); - } - } else { - // logger.warning("RpfLayer: Unknown action command \"" + cmd - // + - // "\" in RpfLayer.actionPerformed()."); - - // OK, not really sure what happened, just act like a - // reset. - doPrepare(); - } - } - - protected void showSubframes(boolean show) { - OMGraphicList list = getList(); - if (list != null) { - list.setSelected(show); - } - - MapMouseInterpreter mmi = getMouseEventInterpreter(); - if (mmi != null) { - mmi.setActive(show); - } - } - - /** Print out the contents of a properties file. */ - public static void main(String[] argv) { - System.out.println("#########################################"); - System.out.println("# Properties for the JAVA RpfLayer"); - System.out.println("# Mandatory properties:"); - System.out.println("layer.class=com.bbn.openmap.layer.rpf.RpfLayer"); - System.out.println("layer.prettyName=CADRG"); - System.out.println("# This property should reflect the paths to the RPF directories"); - System.out.println("layer.paths=;/cdrom/cdrom0/RPF"); - System.out.println( - "# Optional properties - Defaults will be set for properties not included (defaults are listed):"); - System.out.println("# Number between 0-255: 0 is transparent, 255 is opaque"); - System.out.println("layer.opaque=255"); - System.out.println("# Number of colors to use on the maps - 16, 32, 216"); - System.out.println("layer.numberColors=216"); - System.out.println("# Display maps on startup"); - System.out.println("layer.showMaps=true"); - System.out.println("# Display attribute information on startup"); - System.out.println("layer.showInfo=false"); - System.out.println("# Scale images to match map scale"); - System.out.println("layer.scaleImages=true"); - System.out.println( - "# The scale factor to allow when scaling images (2x, 4x, also mean 1/2, 1/4). Default is 4."); - System.out.println("rpf.imageScaleFactor=4"); - System.out.println("# Reset the cache if layer is removed from map"); - System.out.println("layer.killCache=false"); - System.out.println("# Limit the display to the chart code specified. (GN, JN, ON, TP, etc.)"); - System.out.println("layer.chartSeries=ANY"); - System.out.println("# Set the subframe cache size. (Number of subframes to hold on to, 256x256 pixels"); - System.out.println("layer.subframeCacheSize=128"); - System.out.println("# Get the subframe attribute data from the frame provider."); - System.out.println("rpf.autofetchAttributes=false"); - System.out.println("#If you want the coverage tool to be available"); - System.out.println("layer.coverage=true"); - System.out.println("#Then add coverage constants as needed."); - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfProductInfo.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfProductInfo.java deleted file mode 100644 index 68810d1ed..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfProductInfo.java +++ /dev/null @@ -1,317 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfProductInfo.java,v $ -// $RCSfile: RpfProductInfo.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/02/11 22:34:14 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * This class describes the attributes of the different RPF products available. - */ -package com.bbn.openmap.layer.rpf; - -/** - * Contains basic information about the different map and imagery types - * supported by the RPF format. This information is based on the specification - * released by NIMA and contains the conventions they have listed in the RPF - * specification. - */ -public enum RpfProductInfo implements RpfConstants { - - GN("GN", "GNC", "1:5,000,000", 5000000f, "Global Navigation Chart", CADRG), - JN("JN", "JNC", "1:2,000,000", 2000000f, "Jet Navigation Chart", CADRG), - ON("ON", "ONC", "1:1,000,000", 1000000f, "Operational Navigation Chart", CADRG), - TP("TP", "TPC", "1:500,000", 500000f, "Tactical Pilotage Chart", CADRG), - LF("LF", "LFC-FR (Day)", "1:500,000", 500000f, "Low Flying Chart (Day) - Host Nation", CADRG), - JG("JG", "JOG", "1:250,000", 250000f, "Joint Operations Graphic", CADRG), - JA("JA", "JOG-A", "1:250,000", 250000f, "Joint Operations Graphic - Air", CADRG), - JR("JR", "JOG-R", "1:250,000", 250000f, "Joint Operations Graphic - Radar", CADRG), - TF("TF", "TFC", "1:250,000", 250000f, "Transit Flying Chart (UK)", CADRG), - AT("AT", "ATC", "1:200,000", 200000f, "Series 200 Air Target Chart", CADRG), - TC("TC", "TLM 100", "1:100,000", 100000f, "Topographic Line Map 1:100,000 scale", CADRG), - TL("TL", "TLM 50", "1:50,000", 50000f, TOPOLINEMAP, CADRG), - TT("TT", "TLM 25", "1:25,000", 25000f, "Topographic Line Map 1:25,000 scale", CADRG), - TQ("TQ", "TLM 24", "1:24,000", 24000f, "Topographic Line Map 1:24,000 scale", CADRG), - HA("HA", "HA", VARIOUS, Various, "Harbor and Approach Charts", CADRG), - CO("CO", "CO", VARIOUS, Various, "Coastal Charts", CADRG), - OA("OA", "OPEAREA", VARIOUS, Various, "Naval Range Operating Area Chart", CADRG), - CG("CG", "CG", VARIOUS, Various, CITYGRAPHICS, CADRG), - C1("C1", "CG", "1:10,000", 10000f, CITYGRAPHICS, CADRG), - C2("C2", "CG", "1:10,560", 10560f, CITYGRAPHICS, CADRG), - C3("C3", "CG", "1:11,000", 11000f, CITYGRAPHICS, CADRG), - C4("C4", "CG", "1:11,800", 11800f, CITYGRAPHICS, CADRG), - C5("C5", "CG", "1:12,000", 12000f, CITYGRAPHICS, CADRG), - C6("C6", "CG", "1:12,500", 12500f, CITYGRAPHICS, CADRG), - C7("C7", "CG", "1:12,800", 12800f, CITYGRAPHICS, CADRG), - C8("C8", "CG", "1:14,000", 14000f, CITYGRAPHICS, CADRG), - C9("C9", "CG", "1:14,700", 14700f, CITYGRAPHICS, CADRG), - CA("CA", "CG", "1:15,000", 15000f, CITYGRAPHICS, CADRG), - CB("CB", "CG", "1:15,500", 15500f, CITYGRAPHICS, CADRG), - CC("CC", "CG", "1:16,000", 16000f, CITYGRAPHICS, CADRG), - CD("CD", "CG", "1:16,666", 16666f, CITYGRAPHICS, CADRG), - CE("CE", "CG", "1:17,000", 17000f, CITYGRAPHICS, CADRG), - CF("CF", "CG", "1:17,500", 17500f, CITYGRAPHICS, CADRG), - CH("CH", "CG", "1:18,000", 18000f, CITYGRAPHICS, CADRG), - CJ("CJ", "CG", "1:20,000", 20000f, CITYGRAPHICS, CADRG), - CK("CK", "CG", "1:21,000", 21000f, CITYGRAPHICS, CADRG), - CL("CL", "CG", "1:21,120", 21120f, CITYGRAPHICS, CADRG), - CN("CN", "CG", "1:22,000", 22000f, CITYGRAPHICS, CADRG), - CP("CP", "CG", "1:23,000", 23000f, CITYGRAPHICS, CADRG), - CQ("CQ", "CG", "1:25,000", 25000f, CITYGRAPHICS, CADRG), - CR("CR", "CG", "1:26,000", 26000f, CITYGRAPHICS, CADRG), - CS("CS", "CG", "1:35,000", 35000f, CITYGRAPHICS, CADRG), - CT("CT", "CG", "1:36,000", 36000f, CITYGRAPHICS, CADRG), - CM("CM", "CM", VARIOUS, Various, "Combat Charts", CADRG), - A1("A1", "CM", "1:10,000", 10000f, "Combat Graphics, 1:10,000 scale", CADRG), - A2("A2", "CM", "1:25,000", 25000f, "Combat Graphics, 1:25,000 scale", CADRG), - A3("A3", "CM", "1:50,000", 50000f, "Combat Graphics, 1:50,000 scale", CADRG), - A4("A4", "CM", "1:100,000", 100000f, "Combat Graphics, 1:100,000 scale", CADRG), - MM("MM", BLANK, VARIOUS, Various, "(Miscellaneous Maps & Charts)", CADRG), - IM("IM", BLANK, "10m", 66666f, "Imagery, 10 meter resolution", CIB), - I1("I1", BLANK, "10m", 66666f, "Imagery, 10 meter resolution", CIB), - I2("I2", BLANK, "5m", 33333f, "Imagery, 5 meter resolution", CIB), - I3("I3", BLANK, "2m", 13333.2f, "Imagery, 2 meter resolution", CIB), - I4("I4", BLANK, "1m", 6666f, "Imagery, 1 meter resolution", CIB), - D1("D1", BLANK, "100m", Various, "Elevation Data from DTED level 1", CDTED), - D2("D2", BLANK, "30m", Various, "Elevation Data from DTED level 2", CDTED), - OV("OV", "Overview", VARIOUS, Various, "Overview Image", CADRG), - OI("OI", "Overview", VARIOUS, Various, "Overview Image", CADRG), - LG("LG", "Legend", VARIOUS, Various, "Legend Data", CADRG), - UK("UK", "Unknown", VARIOUS, Various, "Unknown", CADRG), - DT("DT", "CDTED", "100M", 666666f, "Compressed DTED", CDTED), - - /** - * New as of MIL-STD-2411-1 Change 3 - */ - EG("EG", "NARC", "1:11M", 11000000f, "North Atlantic Route Chart", CADRG), - ES("ES", "SEC", "1:500,000", 500000f, "VFR Sectional", CADRG), - ET("ET", "SEC", "1:250,000", 250000f, "VFR Sectional Insets", CADRG), - F1("F1", "TFC-1", "1:250,000", 250000f, "Transit Flying Chart (TBD #1)", CADRG), - F2("F2", "TFC-2", "1:250,000", 250000f, "Transit Flying Chart (TBD #2)", CADRG), - F3("F3", "TFC-3", "1:250,000", 250000f, "Transit Flying Chart (TBD #3)", CADRG), - F4("F4", "TFC-4", "1:250,000", 250000f, "Transit Flying Chart (TBD #4)", CADRG), - F5("F5", "TFC-5", "1:250,000", 250000f, "Transit Flying Chart (TBD #5)", CADRG), - I5("I5", BLANK, ".5m", 3333f, "Imagery, .5 (half) meter resolution", CIB), - IV("IV", BLANK, VARIOUS, Various, "Imagery, > 10 meter resolution", CIB), - JO("JO", "OPG", "1:250,000", 250000f, "Operations Planning Graphic", CADRG), - K1("K1", "ICM", "1:8,000", 8000f, "Image City Maps", CADRG), - K2("K2", "ICM", "1:10,000", 10000f, "Image City Maps", CADRG), - K3("K3", "ICM", "1:10,560", 10560f, "Image City Maps", CADRG), - K7("K7", "ICM", "1:12,500", 12500f, "Image City Maps", CADRG), - K8("K8", "ICM", "1:12,800", 12000f, "Image City Maps", CADRG), - KB("KB", "ICM", "1:15,000", 15000f, "Image City Maps", CADRG), - KE("KE", "ICM", "1:16,666", 16666f, "Image City Maps", CADRG), - KM("KM", "ICM", "1:21,120", 21120f, "Image City Maps", CADRG), - KR("KR", "ICM", "1:25,000", 25000f, "Image City Maps", CADRG), - KS("KS", "ICM", "1:26,000", 26000f, "Image City Maps", CADRG), - KU("KU", "ICM", "1:36,000", 36000f, "Image City Maps", CADRG), - L1("L1", "LFC-1", "1:500,000", 500000f, "Low Flying Chart (TBD #1)", CADRG), - L2("L2", "LFC-2", "1:500,000", 500000f, "Low Flying Chart (TBD #2)", CADRG), - L3("L3", "LFC-3", "1:500,000", 500000f, "Low Flying Chart (TBD #3)", CADRG), - L4("L4", "LFC-4", "1:500,000", 500000f, "Low Flying Chart (TBD #4)", CADRG), - L5("L5", "LFC-5", "1:500,000", 500000f, "Low Flying Chart (TBD #5)", CADRG), - LN("LN", "LFC (Night)", "1:500,000", 500000f, "Low Flying Chart (Night) - Host Nation", CADRG), - M1("M1", "MIM", VARIOUS, Various, "Military Installation Map (TBD #1)", CADRG), - M2("M2", "MIM", VARIOUS, Various, "Military Installation Map (TBD #2)", CADRG), - MH("MH", "MIM", "1:25,000", 25000f, "Military Installation Maps", CADRG), - MI("MI", "MIM", "1:50,000", 50000f, "Military Installation Maps", CADRG), - MJ("MJ", "MIM", "1:100,000", 100000f, "Military Installation Maps", CADRG), - OH("OH", "VHRC", "1:1,000,000", 1000000f, "VFR Helicopter Route Chart", CADRG), - OW("OW", "WAC", "1:1,000,000", 1000000f, "High Flying Chart - Host Nation", CADRG), - P1("P1", BLANK, "1:25,000", 25000f, "Special Military Map - Overlay", CADRG), - P2("P2", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P3("P3", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P4("P4", BLANK, "1:25,000", 25000f, "Special Military Purpose", CADRG), - P5("P5", BLANK, "1:50,000", 50000f, "Special Military Map - Overlay", CADRG), - P6("P6", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P7("P7", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P8("P8", BLANK, "1:50,000", 50000f, "Special Military Purpose", CADRG), - P9("P9", BLANK, "1:100,000", 100000f, "Special Military Map - Overlay", CADRG), - PA("PA", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PB("PB", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PC("PC", BLANK, "1:100,000", 100000f, "Special Military Purpose", CADRG), - PD("PD", BLANK, "1:250,000", 250000f, "Special Military Map - Overlay", CADRG), - PE("PE", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PF("PF", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PG("PG", BLANK, "1:250,000", 250000f, "Special Military Purpose", CADRG), - PH("PH", BLANK, "1:500,000", 500000f, "Special Military Map - Overlay", CADRG), - PI("PI", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PJ("PJ", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PK("PK", BLANK, "1:500,000", 500000f, "Special Military Purpose", CADRG), - PL("PL", BLANK, "1:1,000,000", 1000000f, "Special Military Map - Overlay", CADRG), - PM("PM", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PN("PN", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PO("PO", BLANK, "1:1,000,000", 1000000f, "Special Military Purpose", CADRG), - PP("PP", BLANK, "1:2,000,000", 2000000f, "Special Military Map - Overlay", CADRG), - PQ("PQ", BLANK, "1:2,000,000", 2000000f, "Special Military Purpose", CADRG), - PR("PR", BLANK, "1:2,000,000", 2000000f, "Special Military Purpose", CADRG), - PS("PS", BLANK, "1:5,000,000", 5000000f, "Special Military Map - Overlay", CADRG), - PT("PT", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - PU("PU", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - PV("PV", BLANK, "1:5,000,000", 5000000f, "Special Military Purpose", CADRG), - R1("R1", BLANK, "1:50,000", 50000f, "Range Charts", CADRG), - R2("R2", BLANK, "1:100,000", 100000f, "Range Charts", CADRG), - R3("R3", BLANK, "1:250,000", 250000f, "Range Charts", CADRG), - R4("R4", BLANK, "1:500,000", 500000f, "Range Charts", CADRG), - R5("R5", BLANK, "1:1,000,000", 1000000f, "Range Charts", CADRG), - RC("RC", "RGS-100", "1:10,000", 10000f, "Russian General Staff Maps", CADRG), - RL("RL", "RGS-50", "1:50,000", 50000f, "Russian General Staff Maps", CADRG), - RR("RR", "RGS-200", "1:200,000", 200000f, "Russian General Staff Maps", CADRG), - RV("RV", "Riverine", "1:50,000", 50000f, "Riverine Map 1:50,000 scale", CADRG), - TN("TN", "TFC (Night)", "1:250,000", 250000f, "Transit Flying Chart (Night) - Host nation", CADRG), - TR("TR", "TLM 100", "1:200,000", 200000f, "Topographic Line Map 1:200,000 scale", CADRG), - UL("UL", "TLM50-Other", "1:50,000", 50000f, "Topographic Line Map (other 1:50,000 scale)", CADRG), - V1("V1", "HRC Inset", "1:50,000", 50000f, "Helicopter Route Chart Inset", CADRG), - V2("V2", "HRC Inset", "1:62,500", 62500f, "Helicopter Route Chart Inset", CADRG), - V3("V3", "HRC Inset", "1:90,000", 90000f, "Helicopter Route Chart Inset", CADRG), - V4("V4", "HRC Inset", "1:250,000", 250000f, "Helicopter Route Chart Inset", CADRG), - VH("VH", "HRC", "1:125,000", 125000f, "Helicopter Route Chart", CADRG), - VN("VN", "VNC", "1:500,000", 500000f, "Visual Navigation Charts", CADRG), - VT("VT", "VTAC", "1:250,000", 250000f, "VFR Terminal Area Chart", CADRG), - WA("WA", BLANK, "1:250,000", 250000f, "IFR Enroute Low", CADRG), - WB("WB", BLANK, "1:500,000", 500000f, "IFR Enroute Low", CADRG), - WC("WC", BLANK, "1:750,000", 750000f, "IFR Enroute Low", CADRG), - WD("WD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute Low", CADRG), - WE("WE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute Low", CADRG), - WF("WF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute Low", CADRG), - WG("WG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute Low", CADRG), - WH("WH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute Low", CADRG), - WI("WI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute Low", CADRG), - WK("WK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute Low", CADRG), - XD("XD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute High", CADRG), - XE("XE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute High", CADRG), - XF("XF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute High", CADRG), - XG("XG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute High", CADRG), - XH("XH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High", CADRG), - XI("XI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute High", CADRG), - XJ("XJ", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High", CADRG), - XK("XK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute High", CADRG), - Y9("Y9", BLANK, "1:16,500,000", 16500000f, "IFR Enroute Area", CADRG), - YA("YA", BLANK, "1:250,000", 250000f, "IFR Enroute Area", CADRG), - YB("YB", BLANK, "1:500,000", 500000f, "IFR Enroute Area", CADRG), - YC("YC", BLANK, "1:750,000", 750000f, "IFR Enroute Area", CADRG), - YD("YD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute Area", CADRG), - YE("YE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute Area", CADRG), - YF("YF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute Area", CADRG), - YI("YI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute Area", CADRG), - YJ("YJ", BLANK, "1:4,000,000", 4000000f, "IFR Enroute Area", CADRG), - YZ("YZ", BLANK, "1:12,000,000", 12000000f, "IFR Enroute Area", CADRG), - Z8("Z8", BLANK, "1:16,000,000", 16000000f, "IFR Enroute High/Low", CADRG), - ZA("ZA", BLANK, "1:250,000", 250000f, "IFR Enroute High/Low", CADRG), - ZB("ZB", BLANK, "1:500,000", 500000f, "IFR Enroute High/Low", CADRG), - ZC("ZC", BLANK, "1:750,000", 750000f, "IFR Enroute High/Low", CADRG), - ZD("ZD", BLANK, "1:1,000,000", 1000000f, "IFR Enroute High/Low", CADRG), - ZE("ZE", BLANK, "1:1,500,000", 1500000f, "IFR Enroute High/Low", CADRG), - ZF("ZF", BLANK, "1:2,000,000", 2000000f, "IFR Enroute High/Low", CADRG), - ZG("ZG", BLANK, "1:2,500,000", 2500000f, "IFR Enroute High/Low", CADRG), - ZH("ZH", BLANK, "1:3,000,000", 3000000f, "IFR Enroute High/Low", CADRG), - ZI("ZI", BLANK, "1:3,500,000", 3500000f, "IFR Enroute High/Low", CADRG), - ZJ("ZJ", BLANK, "1:4,000,000", 4000000f, "IFR Enroute High/Low", CADRG), - ZK("ZK", BLANK, "1:4,500,000", 4500000f, "IFR Enroute High/Low", CADRG), - ZT("ZT", BLANK, "1:9,000,000", 9000000f, "IFR Enroute High/Low", CADRG), - ZV("ZV", BLANK, "1:10,000,000", 10000000f, "IFR Enroute High/Low", CADRG), - ZZ("ZZ", BLANK, "1:12,000,000", 12000000f, "IFR Enroute High/Low", CADRG); - - /** The two-letter code for a particular map type. */ - public final String seriesCode; - /** The three-letter common abbreviation for the map type. */ - public final String abbr; - /** A String scale representation of the map type. */ - public final String scaleString; - /** The float number representation of the map type - 1:XXX . */ - public final float scale; - /** A Descriptive name for the map type. */ - public final String name; - /** The category of the map type - CADRG/CIB/DTED. */ - public final String dataType; - - /** - * Create a RpfProductInfo object. - * - * @param sc - * the two-letter series code. - * @param a - * the three letter acroynm. - * @param ss - * the scale string. - * @param s - * the display scale of the map. - * @param n - * descriptive name of the map. - * @param dt - * data type - CADRG-CIB-DTED. - */ - private RpfProductInfo(String sc, String a, String ss, float s, String n, String dt) { - seriesCode = sc; - abbr = a; - scaleString = ss; - scale = s; - name = n; - dataType = dt; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("RPF Product: ").append(name).append("\n"); - sb.append(" Series Code: ").append(seriesCode).append("\n"); - sb.append(" Abbreviation: ").append(abbr).append("\n"); - sb.append(" Scale: ").append(scaleString); - if (scale == RpfConstants.Various) { - sb.append(" (Various)\n"); - } else { - sb.append(" (").append(scale).append(")\n"); - } - sb.append(" Data Type: ").append(dataType).append("\n"); - return sb.toString(); - } - - /** - * Returns the RpfProductInfo that has the given two-letter series code. If - * the code passed in is not recognized by the catalog, the UNKNOWN - * RpfProductInfo is returned. - * - * @param seriesCode - * needs to be the two letter code, in uppercase. - */ - public static RpfProductInfo get(String seriesCode) { - - if (seriesCode == null) { - return UK; - } - - for (RpfProductInfo rpi : RpfProductInfo.values()) { - if (rpi.seriesCode.equalsIgnoreCase(seriesCode)) { - return rpi; - } - } - - return UK; - } - - /** - * The main function prints out the RPF catalog, describing all the - * different map types handled by the RPF package. - */ - public static void main(String[] argv) { - System.out.println("RPF Catalog:\n\n"); - for (RpfProductInfo rpi : RpfProductInfo.values()) { - System.out.println("----------------------"); - System.out.println(rpi); - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/layer/rpf/RpfTocEntry.java b/src/openmap/com/bbn/openmap/layer/rpf/RpfTocEntry.java deleted file mode 100644 index 493b93af3..000000000 --- a/src/openmap/com/bbn/openmap/layer/rpf/RpfTocEntry.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/rpf/RpfTocEntry.java,v $ -// $RCSfile: RpfTocEntry.java,v $ -// $Revision: 1.7 $ -// $Date: 2006/12/13 16:45:25 $ -// $Author: dietrick $ -// -// ********************************************************************** - -/* - * The meat of this code is based on source code provided by - * The MITRE Corporation, through the browse application source - * code. Many thanks to Nancy Markuson who provided BBN with the - * software, and to Theron Tock, who wrote the software, and - * Daniel Scholten, who revised it - (c) 1994 The MITRE - * Corporation for those parts, and used/distributed with permission. - */ - -package com.bbn.openmap.layer.rpf; - -import com.bbn.openmap.io.BinaryFile; -import com.bbn.openmap.io.FormatException; - -/** - * Reads and holds an entry in the RPF table of contents file. - */ -public class RpfTocEntry { - - /** Degrees/pixel. */ - public double vertInterval, horizInterval; - /** meters/pixel. */ - public double vertResolution, horizResolution; - public int horizFrames, vertFrames; - public RpfFrameEntry[][] frames; - public char zone; /* DKS new 7/94 */ - public char version; /* 1-9: DKS new 5/3/95 for Dchum */ - public boolean Cib; /* Cib vs. cadrg flag */ - public String compressionRatio; - public String producer; - public String scale; - public RpfCoverageBox coverage; - - /* - * Since RpfProductInfo changed to enum, there are times where the scale and - * scale string can be read out of the A.TOC file and set for entries where - * the chart series has those values as VARIOUS or UNDEFINED. They used to - * be stored in the RpfProductInfo class, but as it is now an enum, these are - * new member variables to hold the A.TOC values. - */ - public float altScale = 0f; - public String altScaleString; - - /** - * Not determined at read-time. RpfTocHandler sets this later, when the - * frames are evaluated for their existence. - */ - public RpfProductInfo info; - - public RpfTocEntry(BinaryFile binFile, int entryNumber) throws java.io.EOFException, FormatException { - this(binFile, 0, entryNumber); - } - - public RpfTocEntry(BinaryFile binFile, int TOCNumber, int entryNumber) - throws java.io.EOFException, FormatException { - coverage = new RpfCoverageBox(); - coverage.tocNumber = TOCNumber; - coverage.entryNumber = entryNumber; - read(binFile); - - // Figure out the CADRG projection zone for the coverage. - coverage.zone = com.bbn.openmap.proj.CADRG.getProjZone(zone); - } - - public void setInfo(String seriesCode) { - info = RpfProductInfo.get(seriesCode.toUpperCase()); - if (info != null) { - Cib = info.dataType.equalsIgnoreCase("CIB"); - coverage.chartCode = info.seriesCode; - } else { - info = RpfProductInfo.UK; - } - } - - public void read(BinaryFile binFile) throws java.io.EOFException, FormatException { - /* - * e.g. "CADRG" , for type - deduced later, via framename of entry, and - * using RpfProductInfo. - */ - /* String type = */binFile.readFixedLengthString(5); - compressionRatio = binFile.readFixedLengthString(5); - /* - * Same as type - deduced via RpfProductInfo. There is a float scale - * inside the info, and a scaleString. - */ - scale = binFile.readFixedLengthString(12); - coverage.scale = RpfTocHandler.textScaleToLong(scale); - - zone = binFile.readChar(); /* char: 1-9 A-J */ - producer = binFile.readFixedLengthString(5); - - coverage.nw_lat = binFile.readDouble(); - coverage.nw_lon = binFile.readDouble(); - /* double sw_lat = */binFile.readDouble(); - /* double sw_lon = */binFile.readDouble(); - /* double ne_lat = */binFile.readDouble(); - /* double ne_lon = */binFile.readDouble(); - coverage.se_lat = binFile.readDouble(); - coverage.se_lon = binFile.readDouble(); - vertResolution = binFile.readDouble(); - horizResolution = binFile.readDouble(); - vertInterval = binFile.readDouble(); - horizInterval = binFile.readDouble(); - vertFrames = binFile.readInteger(); - horizFrames = binFile.readInteger(); - - coverage.subframeLatInterval = vertInterval * 256.0; - coverage.subframeLonInterval = horizInterval * 256.0; - } - - protected boolean isFramesLoaded() { - return frames != null; - } - - protected RpfFrameEntry[][] getFrames() { - if (frames == null) { - frames = new RpfFrameEntry[vertFrames][horizFrames]; - - for (int j = 0; j < vertFrames; j++) { - for (int k = 0; k < horizFrames; k++) { - frames[j][k] = new RpfFrameEntry(); - } - } - } - - return frames; - } - - protected RpfFrameEntry getFrame(int row, int column) { - RpfFrameEntry[][] frames = getFrames(); - return frames[row][column]; - } - - public String toString() { - StringBuffer s = new StringBuffer(); - s.append("RpfTocEntry ##################").append("\n"); - s.append(" vertInterval ").append(vertInterval).append(", horizInterval ").append(horizInterval).append("\n"); - s.append(" vertResolution ").append(vertResolution).append(", horizResolution ").append(horizResolution) - .append("\n"); - s.append(" horizFrames ").append(horizFrames).append(", vertFrames ").append(vertFrames).append("\n"); - s.append(" zone ").append(zone).append("\n"); - s.append(" scale ").append(scale).append("\n"); - s.append(" version ").append(version).append("\n"); - s.append(" Cib ").append(Cib).append("\n"); - s.append(" compressionRatio ").append(compressionRatio).append("\n"); - s.append(" producer ").append(producer).append("\n"); - s.append(coverage); - return s.toString(); - } -} diff --git a/src/openmap/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java b/src/openmap/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java deleted file mode 100644 index 22cf3deb5..000000000 --- a/src/openmap/com/bbn/openmap/layer/vpf/VPFAutoFeatureGraphicWarehouse.java +++ /dev/null @@ -1,1325 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFFeatureGraphicWarehouse.java,v $ -// $RCSfile: VPFFeatureGraphicWarehouse.java,v $ -// $Revision: 1.9 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.layer.vpf; - -import java.awt.BasicStroke; -import java.awt.Component; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.dataAccess.cgm.CGM; -import com.bbn.openmap.dataAccess.cgm.CGMDisplay; -import com.bbn.openmap.io.CSVFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.omGraphics.OMColor; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.omGraphics.OMRasterObject; -import com.bbn.openmap.omGraphics.OMScalingIcon; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.ComponentFactory; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * Implement a graphic factory that builds OMGraphics from VPF. Designed to work - * closely with the VPFFeatureLayer, using GeoSymAttExpression objects to figure - * out how features are rendered. Uses two files to help manage features. The - * first file is a symbol lookup file that ties FACC codes and attribute - * settings with a set of CGM files. This file should cover entries for a - * particular data set. The second file is a priority file, that lists the order - * that features should be rendered, by feature type, facc code and attribute - * settings. If you want to change which features are displayed, or the order in - * which they are displayed, this is the file to modify. - *

- * - * Both of these files are CSV files, and their fields are important. The lookup - * file is of the format: - * - *

- * facc,type,symbol,conditions
- * AK160,A,0804,
- * AL005,A,0081 0734,
- * AL015,P,0002,bfc=81ANDsta=0or2or3or6or11
- * AL015,P,0010,bfc=7ANDhwt=0or2or3or4or7or22
- * AL015,P,0011,bfc=7ANDhwt=11or14or15or16or20or21
- * 
- * - * Note that the conditions field can be empty.The first field is the 5 - * character FACC code, the second field is the type (P, A, L) and the third - * field is the CGM file name. - *

- * - * The priority file is similar: - * - *

- * priority,type,facc,conditions,description
- * 0,Area,BA040,
- * 0,Area,BE010,cvl=99999
- * 0,Area,BE010,idsm=0 AND cvl>=msdcand<>99999
- * 0,Area,BE010,idsm=0 AND cvl>=ssdcand<msdc
- * 
- * - * The priority field really isn't important, the order of the overall file is. - * - * @see com.bbn.openmap.omGraphics.OMGraphic - */ -public class VPFAutoFeatureGraphicWarehouse - implements VPFFeatureWarehouse, PropertyConsumer { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFAutoFeatureGraphicWarehouse"); - - public final static String CGM_DIR_PROPERTY = "cgmDirectory"; - public final static String SYMBOL_LOOKUP_FILE_PROPERTY = "faccLookupFile"; - public final static String PRIORITY_FILE_PROPERTY = "priorityFile"; - public final static String FEATURE_INFO_HANDLER_PROPERTY = "featureInfoHandler"; - public final static String FACC_DEBUG_PROPERTY = "debug"; - public final static String ICON_SIZE_PROPERTY = "iconSize"; - - public final static int DEFAULT_ICON_SIZE = 20; - - protected List priorities; - protected Hashtable> faccLookup; - protected String priorityFilePath; - protected String faccLookupFilePath; - protected String geoSymDirectory; - protected VPFFeatureInfoHandler featInfoHandler; - protected int iconSize = DEFAULT_ICON_SIZE; - - protected String[] compositeFeatureFaccs = new String[] { - "BC010", - "BC020", - "BC040", - "BC070" - }; - - /** - * If set, the warehouse will limit visibility to specified facc and print - * out decision making process. - */ - protected String debugFacc = null; - - /** - * Set which library to use. If null, all applicable libraries in database - * will be searched. - */ - private List useLibrary = null; - /** - * The property prefix for scoping properties. - */ - protected String prefix; - - public final static String EV_ISDM = "isdm"; - public final static String EV_IDSM = "idsm"; - public final static String EV_SSDC = "ssdc"; - public final static String EV_MSDC = "msdc"; - public final static String EV_MSSC = "mssc"; - - /** - * Interactive Shallow Display Mode:ECDIS defines the display mode of - * shallow water areas (shallow depth zones) to be one of two symbology - * scenarios. The attribute values are 1 and 0, which toggle the shallow - * display mode to be on or off respectively. When ISDM is set on (1), the - * display of all depth zones shallower than the defined values of the Ships - * Safety Depth Contour (SSDC) are overprinted with a lattice pattern. This - * mode can be initiated in the four- or two-depth zone display modes (not - * including the drying line), defined by the Interactive Display Selection - * Mode, (IDSM). The shallow display mode is made available due to viewing - * limitations of the shallow depth zones in night displays. - */ - protected double isdm = 0; - /** - * Interactive Display Selection Mode:ECDIS defines the display of depth - * zones to be divided into two or four depth areas. This variable allows - * for the mariner to interactively set either display mode. The two-zone - * mode uses only the ships safety depth contour (SSDC) as a zone separator, - * whereas the four-zone mode further divides zones based on the mariner - * selected deep and shallow contours (MSDC, MSSC). Attribute values are 0 - * and 1 meaning four- and two-zone modes respectively. - */ - protected double idsm = 0; - /** - * Ship's Safety Depth Contour: The ships safety depth contour represents a - * safe contour based on the draft of the ship. This value must be entered - * by the mariner using an application interface. This interface must ensure - * that if a contour value does not exist within the data, that a next - * deeper value is specified as the SSDC. This checking must be dynamic as - * one traverses tile boundaries within the data.. - */ - protected double ssdc = 5; - /** - * Mariner Specified Deep Contour: The four-zone display mode requires the - * establishment of a deep contour that must be specified by the mariner - * through application inquiry. A default value may be implemented at 30m - * according to the ISO Color and Symbol Specification directives. - */ - protected double msdc = 30; - /** - * Mariner Specified Shallow Contour - The four-zone display mode requires - * the establishment of a shallow contour that must be specified by the - * mariner through application inquiry. A default value may be implemented - * at 2m according to the ISO Color and Symbol Specification directives. - */ - protected double mssc = 1; - - /** - * - */ - public VPFAutoFeatureGraphicWarehouse() { - - } - - /** - * The warehouse is initialized the first time features are fetched. - */ - protected void init() { - - CSVFile priorityFile; - CSVFile symbolLookupFile; - try { - - symbolLookupFile = new CSVFile(faccLookupFilePath); - symbolLookupFile.setHeadersExist(true); - symbolLookupFile.loadData(true); - - priorityFile = new CSVFile(priorityFilePath); - priorityFile.setHeadersExist(true); - priorityFile.loadData(true); - - faccLookup = new Hashtable>(); - Hashtable composites = new Hashtable(); - - // Build up the priority holder list - this keeps the features in - // proper rendering order, according to the priority csv file. - // composite features are just held once at the first location they - // are - // found. - - int numPriorities = priorityFile.getNumberOfRecords(); - priorities = new ArrayList(); - for (Vector row : priorityFile) { - String lineCheck = null; - String type = null; - String facc = null; - String conditions = null; - - try { - lineCheck = row.get(0).toString(); - - if (lineCheck.startsWith("#")) { - continue; - } - - type = row.get(1).toString(); - facc = row.get(2).toString(); - conditions = row.get(3).toString(); - - } catch (ArrayIndexOutOfBoundsException aioobe) { - logger.warning("Bad entry in priority file: " + lineCheck + "," + type + "," + facc + "," + conditions); - continue; - } - - // If the debugFacc is defined, just add that particular facc - // type - if (debugFacc != null && !debugFacc.equals(facc)) { - continue; - } - - // Now we need to check if the facc is a composite symbol, like - // a - // buoy. - boolean composite = false; - if (type.charAt(0) == CoverageTable.UPOINT_FEATURETYPE) { - for (String compFacc : compositeFeatureFaccs) { - if (compFacc.equals(facc)) { - composite = true; - break; - } - } - } - - FeaturePriorityHolder.Basic ph = new FeaturePriorityHolder.Basic(type, facc, conditions, this); - ph.setCGMPath(geoSymDirectory, ".cgm"); - - // If it is a composite, we need to add it to a - // FeaturePriorityHolder.Compound object, so that all the little - // parts will be added to any symbols, based on how the parts - // conditions match up to the feature entry in the attribute - // table. - if (composite) { - - FeaturePriorityHolder.Compound compound = composites.get(facc); - if (compound == null) { - compound = new FeaturePriorityHolder.Compound(type, facc, this); - composites.put(facc, compound); - priorities.add(compound); - - // faccLookup doesn't have this facc if we're here... - List list = new ArrayList(); - faccLookup.put(facc, list); - list.add(compound); - } - - compound.addPart(ph); - - } else { - priorities.add(ph); - - List list = faccLookup.get(facc); - if (list == null) { - list = new ArrayList(); - faccLookup.put(facc, list); - } - list.add(ph); - } - } - - // The priority file doesn't know anything about the symbol that is - // going to be used for the different conditions in the feature - // holders. Need to disperse the symbol information to the feature - // holders. - - // OK, time killer - loop through - int numSymbols = symbolLookupFile.getNumberOfRecords(); - int foundRecords = 0; - for (Vector row : symbolLookupFile) { - int numArgs = row.size(); - String facc = row.get(0).toString(); - if (numArgs != 7) { - logger.warning("Problem with facc entry, not correct number of args in csv file:" + facc); - continue; - } - - char type = getType(row.get(1).toString()); - String symbolCode = row.get(2).toString(); - String conditions = row.get(3).toString().trim(); - String size = row.get(4).toString().trim(); - String xoff = row.get(5).toString().trim(); - String yoff = row.get(6).toString().trim(); - - if (conditions.length() > 0) { - conditions = conditions.replace(" ", ""); - } - - List faccList = faccLookup.get(facc); - if (faccList != null) { - boolean found = false; - for (FeaturePriorityHolder ph : faccList) { - if (ph.matches(facc, type, conditions, symbolCode, size, xoff, yoff)) { - found = true; - foundRecords++; - break; - } - } - - if (!found) { - // This really shouldn't be triggered, if it is, - // something - // happened to the data files. But that might be - // intentional, - // to keep some feature types off the map. - if (logger.isLoggable(Level.FINE)) { - logger.fine("didn't find matching PriorityHolder for " + facc + "|" + type + "|" + symbolCode + "|" - + conditions); - } - } - - } else { - // Since we've turned off loading faccs for everything but - // the - // debug facc, of course other things will complain. - if (debugFacc == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("can't find faccLookup for " + facc + " for" + type + "|" + symbolCode + "|" + conditions); - } - } - } - - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("matched up " + foundRecords + " of " + numSymbols + " symbols, " + numPriorities + " priority entries"); - } - - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - public static char getType(String type) { - if (type == null) { - logger.warning("unknown type!"); - } else { - switch (type.charAt(0)) { - case 'P': - return CoverageTable.UPOINT_FEATURETYPE; - case 'A': - return CoverageTable.AREA_FEATURETYPE; - case 'L': - return CoverageTable.EDGE_FEATURETYPE; - default: - } - } - return CoverageTable.SKIP_FEATURETYPE; - } - - /** - * Set the VPF libraries to use, by name. If null, all libraries will be - * searched. Null is default. - */ - public void setUseLibraries(List libNames) { - useLibrary = libNames; - } - - /** - * Get a list of VPF library names that should be used, specified at - * configuration. - */ - public List getUseLibraries() { - return useLibrary; - } - - /** - * Utility method to check if the specified library name has been set by the - * configuration as one to use. - * - * @param libName the library name to test - * @return true if the useLibrary list has not been set, is empty, or if the - * provided name starts with the specified string entry (Good for - * specifying sets of like-libraries). - */ - public boolean checkLibraryForUsage(String libName) { - boolean useLibrary = true; - List libraryNames = getUseLibraries(); - if (libraryNames != null && !libraryNames.isEmpty()) { - useLibrary = false; - for (String libraryName : libraryNames) { - if (libName.startsWith(libraryName)) { - useLibrary = true; - break; - } - } - } - return useLibrary; - } - - /** - * Create an OMPoly for an area described by the facevec. - */ - public OMGraphic createArea(CoverageTable covtable, AreaTable areatable, List facevec, LatLonPoint ll1, - LatLonPoint ll2, double dpplat, double dpplon, String featureType, int primID) { - - List ipts = new ArrayList(); - - int totalSize = 0; - try { - totalSize = areatable.computeEdgePoints(facevec, ipts); - } catch (FormatException f) { - Debug.output("FormatException in computeEdgePoints: " + f); - return null; - } - if (totalSize == 0) { - return null; - } - - OMPoly py = - LayerGraphicWarehouseSupport.createAreaOMPoly(ipts, totalSize, ll1, ll2, dpplat, dpplon, - covtable.doAntarcticaWorkaround); - py.setIsPolygon(true); - return py; - } - - protected String info = null; - - /** - * - */ - public OMGraphic createEdge(CoverageTable c, EdgeTable edgetable, List edgevec, LatLonPoint ll1, LatLonPoint ll2, - double dpplat, double dpplon, CoordFloatString coords, String featureType, int primID) { - - OMPoly py = LayerGraphicWarehouseSupport.createEdgeOMPoly(coords, ll1, ll2, dpplat, dpplon); - py.setFillPaint(OMColor.clear); - py.setIsPolygon(false); - return py; - } - - /** - * - */ - public OMGraphic createText(CoverageTable c, TextTable texttable, List textvec, double latitude, double longitude, - String text, String featureType, int primID) { - - OMText txt = LayerGraphicWarehouseSupport.createOMText(text, latitude, longitude); - return txt; - } - - /** - * Method called by the VPF reader code to construct a node feature. - */ - public OMGraphic createNode(CoverageTable c, NodeTable t, List nodeprim, double latitude, double longitude, - boolean isEntityNode, String featureType, int primID) { - // OMPoint pt = new OMPoint.Image(latitude, longitude); - - OMScalingIcon pt = new OMScalingIcon(latitude, longitude, (Image) null); - pt.setBaseScale(500000); - pt.setMinScale(500000); - pt.setMaxScale(2000000); - return pt; - } - - public boolean needToFetchTileContents(String libraryName, String currentFeature, TileDirectory currentTile) { - return true; - } - - /** - * This is where the magic happens. - * - * @param lst LibrarySelectionTable that lets the warehouse know where the - * data is and what's in it. - * @param ll1 upper left coordinate of the desired area. - * @param ll2 lower right coordinate of the desired area. - * @param proj the projection for the area, used to generate OMGraphics - * added to the list. - * @param omgList the list to add OMGraphics to. One will be created and - * returned if this is null. - * @return the OMGraphicList with OMGraphics for features over desired area. - * @throws FormatException - */ - public OMGraphicList getFeatures(LibrarySelectionTable lst, LatLonPoint ll1, LatLonPoint ll2, Projection proj, - OMGraphicList omgList) - throws FormatException { - - if (priorities == null) { - init(); - } - - // handle Dateline - if (ll1.getX() > ll2.getX()) { - omgList = getFeatures(lst, ll1, new LatLonPoint.Double(ll2.getY(), 180 - .00001),// 180-epsilon - proj, omgList); - omgList = getFeatures(lst, new LatLonPoint.Double(ll1.getY(), -180f), ll2, proj, omgList); - return omgList; - } - - if (omgList == null) { - omgList = new OMGraphicList(); - } - - omgList.setTraverseMode(OMGraphicList.LAST_ADDED_ON_TOP); - - int screenheight = proj.getHeight(); - int screenwidth = proj.getWidth(); - double dpplat = Math.abs((ll1.getY() - ll2.getY()) / screenheight); - double dpplon = Math.abs((ll1.getX() - ll2.getX()) / screenwidth); - - /* - BoundingCircle screenBounds = new GeoSegment.Impl(new Geo[] { - new Geo(ll1.getLatitude(), ll1.getLongitude()), - new Geo(ll2.getLatitude(), ll2.getLongitude()) - }).getBoundingCircle(); - */ - - DataBounds screenBounds = new DataBounds(ll1, ll2); - - for (String libraryName : lst.getLibraryNames()) { - - if (!checkLibraryForUsage(libraryName)) { - continue; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("reading library: " + libraryName); - - } - - CoverageAttributeTable cat = lst.getCAT(libraryName); - - if (cat == null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("no CoverageAttributeTable for " + libraryName + ", skipping..."); - } - continue; - } - - // Do a quick bounds check, so we can just skip the tiles for this - // CAT - // if nothing is on the map. - DataBounds bounds = cat.getBounds(); - if (bounds != null) { - /* - Point2D min = bounds.getMin(); - Point2D max = bounds.getMax(); - BoundingCircle catCircle = new GeoSegment.Impl(new Geo[] { - new Geo(min.getY(), min.getX()), - new Geo(max.getY(), max.getX()) - }).getBoundingCircle(); - */ - if (!screenBounds.intersects(bounds)) { - logger.fine("CoverageAttributeTable for " + libraryName + " not on map, skipping..."); - continue; - } - } - - for (String covname : cat.getCoverageNames()) { - if (logger.isLoggable(Level.FINER)) { - logger.finer("for coverage: " + covname + ", coverage topology level: " + cat.getCoverageTopologyLevel(covname)); - } - - CoverageTable coverageTable = cat.getCoverageTable(covname); - - coverageTable.getFeatures(this, ll1, ll2, dpplat, dpplon, omgList); - - } - } - - // Go through PriorityHolders and build up OMGraphicList, in order for - // rendering to map. Moved this from inside the for loop above, so that - // feature order is preserved across libraries. - for (FeaturePriorityHolder ph : priorities) { - OMGraphicList list = ph.getList(); - if (list != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("Adding features from " + ph.toString() + ": " + list.size() + " features"); - } - list.generate(proj); - omgList.addAll(list); - - list.setVisible(debugFacc == null || ph.getDebugFacc() != null); - - // Now that the OMGraphics are part of the main list, clean them - // out for the next request. Doing it here saves from having to - // do another loop through at the beginning of getFeatures. - ph.resetList(); - } - } - - logger.fine("returning from prepare ************"); - - return omgList; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawEdgeFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawTextFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawAreaFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawEPointFeatures() { - return true; - } - - /** - * Return true, this is a NOOP for this warehouse. - */ - public boolean drawCPointFeatures() { - return true; - } - - /** - * @param rightSide the string pulled out of the VPF data for attribute - * comparisons. - * @return value greater than 0 for valid strings. - */ - public double getExternalAttribute(String rightSide) { - double ret = -1; - if (rightSide != null) { - if (rightSide.equals(EV_IDSM)) { - ret = idsm; - } else if (rightSide.equals(EV_ISDM)) { - ret = isdm; - } else if (rightSide.equals(EV_MSDC)) { - ret = msdc; - } else if (rightSide.equals(EV_MSSC)) { - ret = mssc; - } else if (rightSide.equals(EV_SSDC)) { - ret = ssdc; - } - } - - return ret; - } - - /** - * Given an OMGraphic that is going to be added to the map, use the - * FeatureClassInfo to gather attribute information from the fcirow - * contents. - * - * @param omg The OMGraphic representing a feature. - * @param fci The Description of the columns of the fcirow. - * @param fcirow The attributes for the feature. - */ - public void handleInformationForOMGraphic(OMGraphic omg, FeatureClassInfo fci, List fcirow) { - - if (featInfoHandler != null) { - featInfoHandler.updateInfoForOMGraphic(omg, fci, fcirow); - } - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#setProperties(java.util.Properties) - */ - public void setProperties(Properties setList) { - setProperties(null, setList); - } - - /** - * Set properties of the warehouse. - * - * @param prefix the prefix to use for looking up properties. - * @param props the properties file to look at. - */ - public void setProperties(String prefix, Properties props) { - setPropertyPrefix(prefix); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - faccLookupFilePath = props.getProperty(prefix + SYMBOL_LOOKUP_FILE_PROPERTY, faccLookupFilePath); - priorityFilePath = props.getProperty(prefix + PRIORITY_FILE_PROPERTY, priorityFilePath); - debugFacc = props.getProperty(prefix + FACC_DEBUG_PROPERTY, debugFacc); - geoSymDirectory = props.getProperty(prefix + CGM_DIR_PROPERTY, geoSymDirectory); - - iconSize = PropUtils.intFromProperties(props, prefix + ICON_SIZE_PROPERTY, iconSize); - - String fihString = props.getProperty(prefix + FEATURE_INFO_HANDLER_PROPERTY); - if (fihString != null) { - Object obj = ComponentFactory.create(fihString, prefix, props); - if (obj instanceof VPFFeatureInfoHandler) { - featInfoHandler = (VPFFeatureInfoHandler) obj; - } - } - - isdm = PropUtils.doubleFromProperties(props, prefix + EV_ISDM, isdm); - idsm = PropUtils.doubleFromProperties(props, prefix + EV_IDSM, idsm); - msdc = PropUtils.doubleFromProperties(props, prefix + EV_MSDC, msdc); - mssc = PropUtils.doubleFromProperties(props, prefix + EV_MSSC, mssc); - ssdc = PropUtils.doubleFromProperties(props, prefix + EV_SSDC, ssdc); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#getProperties(java.util.Properties) - */ - public Properties getProperties(Properties getList) { - if (getList == null) { - getList = new Properties(); - } - - String prefix = PropUtils.getScopedPropertyPrefix(this); - - getList.put(prefix + SYMBOL_LOOKUP_FILE_PROPERTY, faccLookupFilePath); - getList.put(prefix + PRIORITY_FILE_PROPERTY, priorityFilePath); - getList.put(prefix + CGM_DIR_PROPERTY, geoSymDirectory); - if (featInfoHandler != null) { - getList.put(prefix + FEATURE_INFO_HANDLER_PROPERTY, featInfoHandler.getClass().getName()); - - if (featInfoHandler instanceof PropertyConsumer) { - ((PropertyConsumer) featInfoHandler).getProperties(getList); - } - } - - getList.put(prefix + ICON_SIZE_PROPERTY, Integer.toString(iconSize)); - - if (debugFacc != null && debugFacc.length() > 0) { - getList.put(prefix + FACC_DEBUG_PROPERTY, debugFacc); - } - - getList.put(prefix + EV_ISDM, Double.toString(isdm)); - getList.put(prefix + EV_IDSM, Double.toString(idsm)); - getList.put(prefix + EV_MSDC, Double.toString(msdc)); - getList.put(prefix + EV_MSSC, Double.toString(mssc)); - getList.put(prefix + EV_SSDC, Double.toString(ssdc)); - - return getList; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.PropertyConsumer#getPropertyInfo(java.util.Properties) - */ - public Properties getPropertyInfo(Properties list) { - if (list == null) { - list = new Properties(); - } - I18n i18n = Environment.getI18n(); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, SYMBOL_LOOKUP_FILE_PROPERTY, - "Symbol Lookup File", "The path to the file containing symbol lookup information", - "com.bbn.openmap.util.propertyEditor.FilePropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, PRIORITY_FILE_PROPERTY, "Priority File", - "The path to the file containing feature type and order to use for display", - "com.bbn.openmap.util.propertyEditor.FilePropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, CGM_DIR_PROPERTY, "CGM Directory Path", - "The path to the directory containing GeoSym CGM files", - "com.bbn.openmap.util.propertyEditor.DirectoryPropertyEditor"); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, FACC_DEBUG_PROPERTY, "FACC Debug", - "A FACC code to use to debug problems with data set", null); - PropUtils.setI18NPropertyInfo(i18n, list, VPFAutoFeatureGraphicWarehouse.class, ICON_SIZE_PROPERTY, "Icon Size", - "The pixel size of icons for point features", null); - return list; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#setPropertyPrefix(java.lang.String) - */ - public void setPropertyPrefix(String prefix) { - this.prefix = prefix; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.PropertyConsumer#getPropertyPrefix() - */ - public String getPropertyPrefix() { - return prefix; - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.layer.vpf.VPFWarehouse#resetForCAT() - */ - public void resetForCAT() { - // NOOP - } - - public int getIconSize() { - return iconSize; - } - - public void setIconSize(int iconSize) { - this.iconSize = iconSize; - } - - /* - * (non-Javadoc) - * - * @see - * com.bbn.openmap.layer.vpf.VPFWarehouse#getGUI(com.bbn.openmap.layer.vpf - * .LibrarySelectionTable) - */ - public Component getGUI(LibrarySelectionTable lst) { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) NOOP - * - * @see com.bbn.openmap.layer.vpf.VPFWarehouse#getFeatures() - */ - public List getFeatures() { - return Collections.emptyList(); - } - - /** - * Set the object used to manage attribute formatting and display for - * features on the map. - * - * @return VPFFeatureInfoHandler being used. - */ - public VPFFeatureInfoHandler getFeatInfoHandler() { - return featInfoHandler; - } - - public void setFeatInfoHandler(VPFFeatureInfoHandler featInfoHandler) { - this.featInfoHandler = featInfoHandler; - } - - /** - * - * A FeaturePriorityHolder represents a rendering order slot in a list of - * feature types to be rendered. It is responsible for evaluating attributes - * of a VPF feature and determining if a particular feature matches what - * this priority holder represents. It can then provide an OMGraphicList for - * those features that match its attribute conditions. - * - * @author dietrick - */ - protected static abstract class FeaturePriorityHolder { - /** - * The type of the feature, i.e. point, line, area - */ - protected char type; - /** - * The feature code FACC for this kind of feature. - */ - protected String facc; - /** - * The OMGraphicList containing all the matching feature OMGraphics. - */ - protected OMGraphicList list; - /** - * The dimension of icons created for point OMGraphics. - */ - protected int dim = DEFAULT_ICON_SIZE; - - protected float sizePercent = 1f; - protected float xoffPercent = 0f; - protected float yoffPercent = 0f; - - /** - * A handle to any debug FACC code listed by the warehouse, so that a - * specific type of feature can be singled out for debugging. - */ - protected String debugFacc = null; - - protected FeaturePriorityHolder(String type, String facc, VPFAutoFeatureGraphicWarehouse warehouse) { - this.type = getType(type); - this.facc = facc; - this.dim = warehouse.getIconSize(); - - if (warehouse.debugFacc != null && warehouse.debugFacc.equals(facc)) { - debugFacc = warehouse.debugFacc; - } - } - - public OMGraphicList getList() { - if (debugFacc != null && list != null) { - if (logger.isLoggable(Level.FINE)) { - logger.fine(list.getDescription()); - } - } - return list; - } - - public String getFacc() { - return facc; - } - - String getDebugFacc() { - return debugFacc; - } - - public void resetList() { - if (list != null) { - list.clear(); - } - } - - public void updateLocation(String size, String xoff, String yoff) { - sizePercent = getValue(size, 1f); - xoffPercent = getValue(xoff, 0f); - yoffPercent = getValue(yoff, 0f); - } - - protected float getValue(String s, float def) { - float ret = def; - if (s != null) { - try { - ret = Float.parseFloat(s); - } catch (NumberFormatException nfe) { - } - } - return ret; - } - - /** - * Used to match feature entries with PriorityHolder. - * - * @param facc - * @param fci - * @param row - * @return true if feature entry matches PriorityHolder conditions. - */ - public abstract boolean matches(String facc, FeatureClassInfo fci, List row); - - /** - * Used to match symbol codes with PriorityHolder during initialization - * of PriorityHolders. - * - * @param facc - * @param type - * @param conditions - * @param size percent of dim setting to use for size of symbol (0-1f) - * @param xoff percent off center of dim setting to use for x origin of - * symbol (0 is centered, positive is right) - * @param yoff percent off center of dim setting to use for x origin of - * symbol (0 is centered, positive is down) - * @return true of feature entry matches PriorityHolder conditions. - */ - public abstract boolean matches(String facc, char type, String conditions, String symbolFileName, String size, String xoff, - String yoff); - - protected abstract void add(OMGraphic omg); - - protected static class Basic - extends FeaturePriorityHolder { - - protected GeoSymAttExpression expression; - protected String conditions; - protected String symbolParentDir; - protected String symbolExt; - - protected String[] cgmTitle; - protected CGMDisplay[] cgmDisplay; - protected BufferedImage icon; - - protected Basic(String type, String facc, String cond, VPFAutoFeatureGraphicWarehouse warehouse) { - super(type, facc, warehouse); - - if (cond != null && cond.trim().length() > 0) { - this.conditions = cond.replace(" ", ""); - expression = new GeoSymAttExpression(this.conditions, warehouse); - } - - } - - public String toString() { - return type + "|" + facc + "|" + conditions; - } - - /** - * Needs to be called before matches is called in init(). - */ - public void setCGMPath(String parent, String append) { - symbolParentDir = parent; - symbolExt = append; - } - - public Image getIcon() { - if (icon == null) { - try { - if (debugFacc != null) { - logger.info("initializing cgm for " + toString()); - } - - if (cgmTitle == null) { - logger.fine("no title for " + toString()); - } else { - - cgmDisplay = new CGMDisplay[cgmTitle.length]; - for (int i = 0; i < cgmTitle.length; i++) { - CGM cgm = new CGM(cgmTitle[i]); - if (debugFacc != null) { - logger.info(" using " + cgmTitle[i]); - } - cgmDisplay[i] = new CGMDisplay(cgm); - // Rendering the icon will load cgmDisplay with - // cgm - // parameters - // (fill paint, line paint, etc); - icon = cgmDisplay[i].getBufferedImage((int) (dim * sizePercent), (int) (dim * sizePercent)); - } - } - } catch (IOException ioe) { - logger.fine("Couldn't load CGM files: " + cgmTitle[0] + "; first of " + cgmTitle.length); - } - } - - return icon; - } - - /** - * Used to match feature entries with PriorityHolder. - * - * @param facc - * @param fci - * @param row - * @return true of feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, FeatureClassInfo fci, List row) { - boolean ret = false; - char type = fci.getFeatureType(); - if (type == CoverageTable.EPOINT_FEATURETYPE || type == CoverageTable.CPOINT_FEATURETYPE) { - type = CoverageTable.UPOINT_FEATURETYPE; - } - if (facc.equals(this.facc) && this.type == type) { - if (expression != null) { - ret = expression.evaluate(fci, row); - } else { - ret = true; - } - } - return ret; - } - - /** - * Used to match symbol codes with PriorityHolder. - * - * @param facc - * @param type - * @param conditions - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, char type, String conditions, String symbolFileName, String size, String xoff, - String yoff) { - boolean basicMatch = this.facc.equals(facc) && type == this.type; - - boolean conditionMatch = - ((this.conditions == null || this.conditions.trim().length() == 0) && (conditions == null || conditions.trim() - .length() == 0)) - || (this.conditions != null && this.conditions.equals(conditions)); - - boolean ret = basicMatch && conditionMatch; - - if (ret) { - Vector names = PropUtils.parseSpacedMarkers(symbolFileName); - cgmTitle = new String[names.size()]; - for (int i = 0; i < names.size(); i++) { - cgmTitle[i] = symbolParentDir + "/" + names.get(i) + symbolExt; - updateLocation(size, xoff, yoff); - } - } - - return ret; - } - - public void add(OMGraphic omg) { - if (list == null) { - list = new OMGraphicList(); - } - - // Also makes sure cgmDisplay is initialized - Image icon = getIcon(); - - if (cgmDisplay != null) { - if (omg instanceof OMPoint.Image) { - ((OMPoint.Image) omg).setImage(icon); - } else if (omg instanceof OMRasterObject) { - ((OMRasterObject) omg).setImage(icon); - } else if (omg instanceof OMPoly) { - OMPoly omp = (OMPoly) omg; - if (!omp.isPolygon()) { - // This check is necessary of the cgms are not found - if (cgmDisplay[0] != null) { - omp.setLinePaint(cgmDisplay[0].getLineColor()); - omp.setStroke(new BasicStroke(1)); - omp.setFillPaint(OMColor.clear); - } - } else { - - if (cgmDisplay.length == 1 && cgmDisplay[0] != null) { - omp.setFillPaint(cgmDisplay[0].getFillColor()); - omp.setLinePaint(cgmDisplay[0].getFillColor()); - } else if (cgmDisplay.length > 1 && cgmDisplay[1] != null) { - omp.setFillPaint(cgmDisplay[1].getFillColor()); - omp.setLinePaint(cgmDisplay[1].getFillColor()); - } - } - } - } - - list.add(omg); - } - - /* - * (non-Javadoc) - * - * @see com.bbn.openmap.layer.vpf.VPFAutoFeatureGraphicWarehouse. - * PriorityHolder #getConditions() - */ - public String getConditions() { - return conditions; - } - } - - /** - * A Compound FeaturePriorityHolder is used for buoys and other features - * that have parts added to their representation based on their feature - * attributes. It contains a list of Basic FeaturePriorityHolders, and - * each one adds its touch to the resulting OMGraphic as needed. - * - * @author dietrick - */ - protected static class Compound - extends FeaturePriorityHolder - implements ImageObserver { - - protected List parts = new ArrayList(); - protected BufferedImage icon; - - protected Compound(String type, String facc, VPFAutoFeatureGraphicWarehouse warehouse) { - super(type, facc, warehouse); - - } - - public String toString() { - return "Compound: " + type + "|" + facc; - } - - public void addPart(FeaturePriorityHolder.Basic part) { - parts.add(part); - } - - /** - * Used to match features with PriorityHolder. We need to do a - * little more work here, to build up an image that matches the all - * of the attributes set on this feature. So if the feature matches - * at the first level, walk through the parts and draw on top of it. - * - * @param facc - * @param fci - * @param row - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, FeatureClassInfo fci, List row) { - boolean ret = false; - int partCount = 0; - - char type = fci.getFeatureType(); - if (type == CoverageTable.EPOINT_FEATURETYPE || type == CoverageTable.CPOINT_FEATURETYPE) { - type = CoverageTable.UPOINT_FEATURETYPE; - } - - /** - * Building up the current image based on the attributes. Give - * each part a chance to evaluate whether it should be rendered - * into the image or not. - */ - if (facc.equals(this.facc) && this.type == type) { - - BufferedImage image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D) image.getGraphics(); - for (FeaturePriorityHolder.Basic part : parts) { - - if (part.expression != null) { - boolean partRet = part.expression.evaluate(fci, row); - - if (partRet) { - Image im = part.getIcon(); - g.drawImage(im, (int) (part.xoffPercent * dim), (int) (part.yoffPercent * dim), this); - ret = true; - partCount++; - } - - } else { - Image im = part.getIcon(); - g.drawImage(im, (int) (part.xoffPercent * dim), (int) (part.yoffPercent * dim), this); - ret = true; - partCount++; - } - - } - - icon = image; - } - - return ret; - } - - /** - * Used to match symbol codes with PriorityHolder. - * - * @param facc - * @param type - * @param conditions - * @return true if feature matches conditions of PriorityHolder. - */ - public boolean matches(String facc, char type, String conditions, String symbolFileName, String size, String xoff, - String yoff) { - boolean basicMatch = this.facc.equals(facc) && type == this.type; - - boolean conditionMatch = false; - - /** - * We need to step through each part so that each part can find - * it's symbol. - */ - for (FeaturePriorityHolder.Basic part : parts) { - - conditionMatch = part.matches(facc, type, conditions, symbolFileName, size, xoff, yoff); - - if (conditionMatch) { - break; - } - } - - return basicMatch && conditionMatch; - } - - public void add(OMGraphic omg) { - - if (list == null) { - list = new OMGraphicList(); - } - - if (icon != null) { - if (omg instanceof OMPoint.Image) { - ((OMPoint.Image) omg).setImage(icon); - list.add(omg); - } else if (omg instanceof OMRasterObject) { - ((OMRasterObject) omg).setImage(icon); - list.add(omg); - } - } - } - - /* - * (non-Javadoc) - * - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, - * int, int, int, int, int) - */ - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { - return false;// all set - } - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/EditableOMRangeRings.java b/src/openmap/com/bbn/openmap/omGraphics/EditableOMRangeRings.java deleted file mode 100755 index 8d2f70986..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/EditableOMRangeRings.java +++ /dev/null @@ -1,496 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/EditableOMRangeRings.java,v $ -// $RCSfile: EditableOMRangeRings.java,v $ -// $Revision: 1.15 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.text.DecimalFormat; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToolBar; -import javax.swing.SwingConstants; -import javax.swing.border.EmptyBorder; - -import com.bbn.openmap.I18n; -import com.bbn.openmap.event.UndoEvent; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PaletteHelper; - -/** - */ -public class EditableOMRangeRings - extends EditableOMCircle { - - // TODO need to update the memory mechanism between OMRangeRings that are - // being edited/created so that statics aren't being used. The only other - // place this info could be held is either in the drawing tool or in the - // OMRangeRingsLoader (OMCircleLoader), and I don't think we have a handle to - // either of them from here. Gah! I hate using statics, they make me feel - // dirty. - protected static int lastInterval; - protected static Length lastUnit; - protected static boolean snapToInterval = false; - - /** - * Create the EditableOMRangeRings, setting the state machine to create the - * circle off of the gestures. - */ - public EditableOMRangeRings() { - createGraphic(null); - } - - /** - * Create an EditableOMRangeRings with the circleType and renderType - * parameters in the GraphicAttributes object. - */ - public EditableOMRangeRings(GraphicAttributes ga) { - createGraphic(ga); - } - - /** - * Create the EditableOMRangeRings with an OMCircle already defined, ready - * for editing. - * - * @param omc OMCircle that should be edited. - */ - public EditableOMRangeRings(OMRangeRings omc) { - setGraphic(omc); - } - - /** - * Create and set the graphic within the state machine. The GraphicAttributes - * describe the type of circle to create. - */ - public void createGraphic(GraphicAttributes ga) { - init(); - stateMachine.setUndefined(); - int renderType = OMGraphic.RENDERTYPE_LATLON; - - if (ga != null) { - renderType = ga.getRenderType(); - } - - if (Debug.debugging("eomc")) { - Debug.output("EditableOMRangeRings.createGraphic(): rendertype = " + renderType); - } - - circle = new OMRangeRings(90f, -180f, 0f); - - if (ga != null) { - ga.setTo(circle, true); - } - } - - /** - * Modifies the gui to not include line type adjustments, and adds widgets to - * control range ring settings. - * - * @param graphicAttributes the GraphicAttributes to use to get the GUI - * widget from to control those parameters for this EOMG. - * @return java.awt.Component to use to control parameters for this EOMG. - */ - public Component getGUI(GraphicAttributes graphicAttributes) { - Debug.message("eomg", "EditableOMRangeRings.getGUI"); - if (graphicAttributes != null) { - // JComponent panel = graphicAttributes.getColorAndLineGUI(); - JComponent toolbar = createAttributePanel(graphicAttributes); - // panel.add(getRangeRingGUI()); - getRangeRingGUI(graphicAttributes.getOrientation(), toolbar); - return toolbar; - } else { - return getRangeRingGUI(); - } - } - - public void updateInterval(int val) { - int oldInterval = ((OMRangeRings) circle).getInterval(); - ((OMRangeRings) circle).setInterval(val); - lastInterval = val; - if (intervalField != null) { - intervalField.setText(Integer.toString(val)); - } - - if (snapToInterval) { - setRadius(circle.getRadius()); - } - if (oldInterval != val) { - updateCurrentState(null); - } - redraw(null, true); - } - - public void updateInterval(String intervalStr) { - int oldValue = ((OMRangeRings) circle).getInterval(); - int value = interpretValue(intervalStr); - - if (value <= 0) { - value = oldValue; - } - - updateInterval(value); - } - - public int interpretValue(String intervalStr) { - int value = -1; - try { - if (intervalStr.toLowerCase().endsWith("m")) { - intervalStr = intervalStr.substring(0, intervalStr.length() - 1); - value = (int) df.parse(intervalStr).intValue() * 1000000; - } else if (intervalStr.toLowerCase().endsWith("k")) { - intervalStr = intervalStr.substring(0, intervalStr.length() - 1); - value = df.parse(intervalStr).intValue() * 1000; - } else if (intervalStr.trim().length() == 0) { - // do nothing - } else { - value = df.parse(intervalStr).intValue(); - } - } catch (java.text.ParseException e) { - Debug.error("RangeRing interval value not valid: " + intervalStr); - } catch (NumberFormatException e) { - Debug.error("RangeRing interval value not valid: " + intervalStr); - } - return value; - } - - // Need these three for UndoEvents to be able to update them if an update - // event gets implemented. - protected JTextField intervalField = null; - protected JComboBox unitsCombo = null; - protected JCheckBox snapCheckBox = null; - - protected JToolBar rrToolBar = null; - protected transient DecimalFormat df = new DecimalFormat(); - protected JComponent attributeBox; - - protected JComponent getRangeRingGUI() { - return getRangeRingGUI(SwingConstants.HORIZONTAL, (JComponent) null); - } - - /** - * Get the GUI associated with changing the Text. - * - * @param orientation SwingConstants.HORIZONTAL/VERTICAL - * @param guiComp the JComponent to add stuff to. If the orientation is - * HORIZONTAL, the components will be added directly to this - * component, or to a new JComponent that is returned if null. If the - * orientation is Vertical, a button will be added to the guiComp, or - * returned. This button will call up a dialog box with the settings, - * since they don't really lay out vertically. - * @return JComponent for controlling range-ring specific attributes. - */ - protected JComponent getRangeRingGUI(int orientation, JComponent guiComp) { - attributeBox = null; - - if (guiComp == null || orientation == SwingConstants.VERTICAL) { - attributeBox = javax.swing.Box.createHorizontalBox(); - - attributeBox.setAlignmentX(Component.CENTER_ALIGNMENT); - attributeBox.setAlignmentY(Component.CENTER_ALIGNMENT); - - if (orientation == SwingConstants.HORIZONTAL) { - guiComp = attributeBox; - } - } else if (orientation == SwingConstants.HORIZONTAL) { - attributeBox = guiComp; - } - - if (guiComp == null) { - guiComp = new JPanel(); - } - - guiComp.add(PaletteHelper.getToolBarFill(orientation)); - - if (orientation == SwingConstants.VERTICAL) { - JButton launchButton = new JButton("RR"); - launchButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - if (attributeBox != null) { - JDialog dialog = new JDialog(); - dialog.setContentPane(attributeBox); - dialog.setModal(true); - dialog.pack(); - dialog.setLocationRelativeTo((JButton) ae.getSource()); - dialog.setVisible(true); - } - } - }); - guiComp.add(launchButton); - } - - configureRangeRings(); - intervalField = makeIntervalField(); - attributeBox.add(intervalField); - - unitsCombo = makeUnitsCombo(); - attributeBox.add(unitsCombo); - snapCheckBox = makeSnapCheckBox(); - attributeBox.add(snapCheckBox); - - return guiComp; - } - - private void configureRangeRings() { - ((OMRangeRings) circle).setInterval(getInterval()); - ((OMRangeRings) circle).setIntervalUnits(getUnits()); - } - - private int getInterval() { - return (!isNewRing()) ? ((OMRangeRings) circle).getInterval() : haveUserSpecifiedValue() ? lastInterval - : OMRangeRings.DEFAULT_INTERVAL; - } - - private Length getUnits() { - return (!isNewRing()) ? ((OMRangeRings) circle).getIntervalUnits() : haveUserSpecifiedValue() ? lastUnit : null; - } - - private boolean isNewRing() { - // we rely on interval units not being initialized during construction - return (((OMRangeRings) circle).getIntervalUnits() == null); - } - - private boolean haveUserSpecifiedValue() { - // lastUnit is not null if the user made a selection with the comboBox - return (lastUnit != null); - } - - private JTextField makeIntervalField() { - JTextField field = new JTextField(Integer.toString(((OMRangeRings) circle).getInterval()), 5); - field.setMargin(new Insets(0, 1, 0, 1)); - // without minimum size set, field can be too small to use - field.setMinimumSize(new Dimension(40, 18)); - field.setHorizontalAlignment(JTextField.RIGHT); - field.setToolTipText(i18n.get(this, "intervalField.tooltip", "Value for interval between rings.")); - field.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - updateInterval(((JTextField) (ae.getSource())).getText()); - } - }); - // Users forget to hit Enter, which is required for an action event, - // then wonder why the rings they draw don't have the desired value. - // Adding a focus listener addresses this issue. - field.addFocusListener(new FocusAdapter() { - public void focusLost(FocusEvent event) { - if (!event.isTemporary()) { - updateInterval(((JTextField) (event.getSource())).getText()); - } - } - }); - return field; - } - - private JComboBox makeUnitsCombo() { - Length[] available = Length.values(); - String[] unitStrings = new String[available.length + 1]; - - String current = null; - Length l = ((OMRangeRings) circle).getIntervalUnits(); - if (l != null) { - current = l.toString(); - } - - int currentIndex = unitStrings.length - 1; - - for (int i = 0; i < available.length; i++) { - unitStrings[i] = available[i].toString(); - if (unitStrings[i] != null && unitStrings[i].equals(current)) { - currentIndex = i; - } - } - unitStrings[unitStrings.length - 1] = i18n.get(this, "unitStrings.concentric", "concentric"); - - JComboBox combo = new JComboBox(unitStrings); - combo.setBorder(new EmptyBorder(0, 1, 0, 1)); - combo.setSelectedIndex(currentIndex); - combo.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JComboBox jcb = (JComboBox) e.getSource(); - OMRangeRings rr = (OMRangeRings) circle; - Length newLength = Length.get((String) jcb.getSelectedItem()); - Length oldLength = rr.getIntervalUnits(); - - /* - * If newLength is not null and oldLength is not null, just - * translate the distance that is current specified. If newLength is - * null, then find out how many rings are on the range ring and set - * the interval to that. If oldLength is null, find out the radius - * and divide it by the number of rings - 1. - */ - - int value = interpretValue(intervalField.getText()); - if (value <= 0) { - value = 4; - } - - if (newLength != null && oldLength != null) { - value = (int) newLength.fromRadians(oldLength.toRadians(value)); - } else { - int numSubCircles; - if (rr.subCircles == null || rr.subCircles.length == 0) { - numSubCircles = 1; - } else { - numSubCircles = rr.subCircles.length; - } - - if (newLength == null) { - value = numSubCircles; - } else if (oldLength == null) { - value = (int) Math.ceil(newLength.fromRadians(Length.DECIMAL_DEGREE.toRadians(rr.getRadius())) - / numSubCircles); - } - } - - ((OMRangeRings) circle).setIntervalUnits(newLength); - lastUnit = newLength; - updateInterval(value); - } - }); - return combo; - } - - private JCheckBox makeSnapCheckBox() { - String snapText = i18n.get(this, "snapToInterval", "Snap"); - JCheckBox snapBox = new JCheckBox(snapText, isSnapToInterval()); - snapText = i18n.get(this, "snapToInterval", I18n.TOOLTIP, "Round radius to nearest interval value."); - snapBox.setToolTipText(snapText); - snapBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { - setSnapToInterval(((JCheckBox) ae.getSource()).isSelected()); - if (snapToInterval) { - setRadius(circle.getRadius()); - } - updateCurrentState(null); - redraw(null, true); - } - }); - return snapBox; - } - - protected boolean drawLabelsHolder = true; - - /** - * A convenience method that gives an EditableOMGraphic a chance to modify - * the OMGraphic so it can be drawn quickly, by turning off labels, etc, - * right before the XORpainting happens. The OMGraphic should be configured - * so that the render method does the least amount of painting possible. Note - * that the DrawingAttributes for the OMGraphic have already been set to - * DrawingAttributes.DEFAULT (black line, clear fill). - */ - protected void modifyOMGraphicForEditRender() { - OMRangeRings omrr = (OMRangeRings) getGraphic(); - drawLabelsHolder = omrr.getDrawLabels(); - omrr.setDrawLabels(false); - } - - /** - * A convenience method that gives an EditableOMGraphic a chance to reset the - * OMGraphic so it can be rendered normally, after it has been modified for - * quick paints. The DrawingAttributes for the OMGraphic have already been - * reset to their normal settings, from the DrawingAttributes.DEFAULT - * settings that were used for the quick paint. - */ - protected void resetOMGraphicAfterEditRender() { - ((OMRangeRings) getGraphic()).setDrawLabels(drawLabelsHolder); - } - - public boolean isSnapToInterval() { - return snapToInterval; - } - - public void setSnapToInterval(boolean sti) { - snapToInterval = sti; - } - - protected void setRadius(double radius) { - if (circle != null) { - if (snapToInterval) { - OMRangeRings rr = (OMRangeRings) circle; - Length units = rr.getIntervalUnits(); - if (units != null) { - double rds = units.fromRadians(Length.DECIMAL_DEGREE.toRadians(radius)); - radius = Math.round(rds / rr.getInterval()) * rr.getInterval(); - radius = Length.DECIMAL_DEGREE.fromRadians(units.toRadians(radius)); - } - } - circle.setRadius(radius); - } - } - - /** - * Create an UndoEvent that can get an OMRangeRing back to what it looks like - * right now. - */ - protected UndoEvent createUndoEventForCurrentState(String whatHappened) { - if (whatHappened == null) { - whatHappened = i18n.get(this.getClass(), "rangeRingUndoString", "Edit"); - } - return new OMRangeRingUndoEvent(this, whatHappened); - } - - /** - * Subclass for undoing edits for OMRangeRing classes, handles events that - * may affect the extra GUI widgets. - * - * @author ddietrick - */ - public static class OMRangeRingUndoEvent - extends OMGraphicUndoEvent - implements UndoEvent { - - boolean snap; - - public OMRangeRingUndoEvent(EditableOMRangeRings eomp, String description) { - super(eomp, description); - snap = eomp.isSnapToInterval(); - } - - protected void setSubclassState() { - OMRangeRings rrStateHolder = (OMRangeRings) stateHolder; - EditableOMRangeRings eomrr = (EditableOMRangeRings) eomg; - if (eomrr.snapCheckBox != null) { - eomrr.snapCheckBox.setSelected(snap); - eomrr.setSnapToInterval(snap); - } - - if (eomrr.intervalField != null) { - eomrr.intervalField.setText(Integer.toString(rrStateHolder.getInterval())); - } - - Length intervalUnits = rrStateHolder.getIntervalUnits(); - if (eomrr.unitsCombo != null && intervalUnits != null) { - eomrr.unitsCombo.setSelectedItem(intervalUnits.toString()); - } - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/GraphicAttributes.java b/src/openmap/com/bbn/openmap/omGraphics/GraphicAttributes.java deleted file mode 100644 index ba9ef1c3c..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/GraphicAttributes.java +++ /dev/null @@ -1,315 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/GraphicAttributes.java,v $ -// $RCSfile: GraphicAttributes.java,v $ -// $Revision: 1.12 $ -// $Date: 2008/01/29 22:04:13 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -/* Java Core */ -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.Serializable; -import java.util.Properties; - -import javax.swing.ButtonGroup; -import javax.swing.JMenu; -import javax.swing.JPopupMenu; -import javax.swing.JRadioButtonMenuItem; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.proj.LineType; -import com.bbn.openmap.util.PropUtils; - -/** - * The GraphicAttributes provides an extension to DrawingAttributes by - * provideing a mechanism for loading and managing different graphic attributes - * that may be used, such as line type (LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE, - * LINETYPE_RHUMB, or LINETYPE_UNKNOWN), or render type (RENDERTYPE_XY, - * RENDERTYPE_LATLON, RENDERTYPE_OFFSET, or RENDERTYPE_UNKNOWN). The - * DrawingAttributes class fishes out the applicable properties for you, creates - * the objects needed, and then lets you get those objects when needed. - */ -public class GraphicAttributes extends DrawingAttributes implements ActionListener, Serializable, - OMGraphicConstants { - - /** - * The name of the property that holds the line type of the graphic. - */ - public final static String lineTypeProperty = "lineType"; - /** - * The name of the property that holds the render type of the graphic. - */ - public final static String renderTypeProperty = "renderType"; - - /** The line type of a graphic, defaults to LINETYPE_STRAIGHT. */ - protected int lineType = LINETYPE_STRAIGHT; - /** The rendertype of a graphic. Default is RENDERTYPE_XY. */ - protected int renderType = RENDERTYPE_XY; - /** Flag to disable choice of line type, from an external source. */ - protected boolean enableLineTypeChoice = true; - - public final static GraphicAttributes DEFAULT = new GraphicAttributes(); - - private I18n i18n = Environment.getI18n(); - - /** - * Create a GraphicAttributes with the default settings - clear fill paint - * and pattern, sold black edge line of width 1. - */ - public GraphicAttributes() { - super(); - } - - /** - * Create the GraphicAttributes and call init without a prefix for the - * properties. Call init without a prefix for the properties. - * - * @param props the Properties to look in. - */ - public GraphicAttributes(Properties props) { - super(props); - } - - /** - * Create the GraphicAttributes and call init with a prefix for the - * properties. - * - * @param prefix the prefix marker to use for a property, like - * prefix.propertyName. The period is added in this function. - * @param props the Properties to look in. - */ - public GraphicAttributes(String prefix, Properties props) { - super(prefix, props); - } - - /** - * If you want to get a DEFAULT DrawingAttributes object that you may - * modify, get your own copy. - */ - public static GraphicAttributes getGADefaultClone() { - return (GraphicAttributes) DEFAULT.clone(); - } - - /** - * PropertyConsumer method. - */ - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - if (props == null) { - return; - } - - // Set up the Graphic attributes. - lineType = PropUtils.intFromProperties(props, prefix + lineTypeProperty, lineType); - renderType = PropUtils.intFromProperties(props, prefix + renderTypeProperty, renderType); - } - - public Object clone() { - GraphicAttributes clone = new GraphicAttributes(); - setTo(clone); - return clone; - } - - public void setTo(GraphicAttributes clone) { - super.setTo(clone); - clone.renderType = renderType; - clone.lineType = lineType; - clone.enableLineTypeChoice = enableLineTypeChoice; - } - - /** - * Get the lineType. - */ - public int getLineType() { - return lineType; - } - - /** - * Set the line type. If it isn't straight, great circle or rhumb, it's set - * to unknown. - */ - public void setLineType(int lt) { - int oldLineType = lineType; - - if (lt == LINETYPE_STRAIGHT || lt == LINETYPE_GREATCIRCLE || lt == LINETYPE_RHUMB) { - lineType = lt; - } else { - lineType = LINETYPE_UNKNOWN; - } - - propertyChangeSupport.firePropertyChange("lineType", oldLineType, lineType); - } - - /** - * Get the renderType. - */ - public int getRenderType() { - return renderType; - } - - /** - * Set the render type. If it isn't xy, lat/lon, or lat/lon with offset, - * it's set to unknown. - */ - public void setRenderType(int rt) { - int oldRenderType = renderType; - - if (rt == RENDERTYPE_XY || rt == RENDERTYPE_LATLON || rt == RENDERTYPE_OFFSET) { - renderType = rt; - - } else { - renderType = RENDERTYPE_UNKNOWN; - } - - propertyChangeSupport.firePropertyChange("renderType", oldRenderType, renderType); - } - - /** - * Set the GraphicAttributes parameters based on the current settings of an - * OMGraphic. - */ - public void setFrom(OMGraphic graphic) { - setFrom(graphic, false); - } - - /** - * Set the GraphicAttributes parameters based on the current settings of an - * OMGraphic. - * - * @param graphic OMGraphic to gather settings from. - * @param resetGUI flag to cause GraphicAttribute GUI reset. - */ - public void setFrom(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) - return; - - super.setFrom(graphic, false); - lineType = graphic.getLineType(); - renderType = graphic.getRenderType(); - enableLineTypeChoice = graphic.hasLineTypeChoice(); - - if (resetGUI) { - resetGUI(); - } - } - - /** - * Set all the attributes for the graphic that are contained within this - * GraphicAttributes class. - * - * @param graphic OMGraphic. - */ - public void setTo(OMGraphic graphic) { - setTo(graphic, false); - } - - /** - * Set all the attributes for the graphic that are contained within this - * GraphicAttributes class. - * - * @param graphic OMGraphic. - * @param resetGUI reset the GraphicAttributes GUI if desired. - */ - public void setTo(OMGraphic graphic, boolean resetGUI) { - if (graphic == null) - return; - - super.setTo(graphic, false); - graphic.setLineType(lineType); - - // Render type is dictated by coordinate settings. Changing this messes - // with fundamental rendering location. Only set it if the graphic rendertype is unknown. - if (graphic.getRenderType() == RENDERTYPE_UNKNOWN && renderType != RENDERTYPE_UNKNOWN) { - graphic.setRenderType(renderType); - } - - if (resetGUI) { - // The GraphicAttribute might be rendering options for this graphic, - // needs to know if line type choices are available. - enableLineTypeChoice = graphic.hasLineTypeChoice(); - enableFillPaintChoice = !(graphic instanceof NonRegional); - resetGUI(); - } - } - - /** - * Method should be called on this GraphicAttributes object if the OMGraphic - * type doesn't support line types to disable the choice from the line menu. - * Circles, range rings, points, etc. are all examples of shapes that - * disable linetype choice. - */ - public void setEnableLineTypeChoice(boolean value) { - enableLineTypeChoice = value; - } - - public boolean getEnableLineTypeChoice() { - return enableLineTypeChoice; - } - - protected void setPreStrokeMenuOptions(JPopupMenu popup) { - super.setPreStrokeMenuOptions(popup); - JMenu ltm = getLineTypeMenu(); - if (ltm != null) { - popup.add(ltm); - } - } - - public JMenu getLineTypeMenu() { - JMenu lineTypeMenu = null; - - if (renderType == RENDERTYPE_LATLON && enableLineTypeChoice) { - lineTypeMenu = new JMenu(i18n.get(GraphicAttributes.class, "Line_Type", "Line Type")); - - ActionListener listener = new ActionListener() { - public void actionPerformed(ActionEvent ae) { - String command = ae.getActionCommand(); - try { - setLineType(Integer.parseInt(command)); - } catch (NumberFormatException e) { - } - } - }; - - ButtonGroup group = new ButtonGroup(); - JRadioButtonMenuItem button = new JRadioButtonMenuItem(i18n.get(DrawingAttributes.class, "Great_Circle", "Great Circle"), lineType == LineType.GreatCircle); - button.setActionCommand(String.valueOf(LineType.GreatCircle)); - button.addActionListener(listener); - lineTypeMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(GraphicAttributes.class, "Rhumb", "Rhumb"), lineType == LineType.Rhumb); - button.setActionCommand(String.valueOf(LineType.Rhumb)); - group.add(button); - button.addActionListener(listener); - lineTypeMenu.add(button); - - button = new JRadioButtonMenuItem(i18n.get(GraphicAttributes.class, "Straight", "Straight"), lineType == LineType.Straight); - button.setActionCommand(String.valueOf(LineType.Straight)); - group.add(button); - button.addActionListener(listener); - lineTypeMenu.add(button); - } - return lineTypeMenu; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/NatCubicSpline.java b/src/openmap/com/bbn/openmap/omGraphics/NatCubicSpline.java deleted file mode 100644 index 09138d014..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/NatCubicSpline.java +++ /dev/null @@ -1,526 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/NatCubicSpline.java,v $ -//$RCSfile: NatCubicSpline.java,v $ -//$Revision: 1.5 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Polygon; - -import com.bbn.openmap.MoreMath; - -/** - * A natural cubic spline calculation. - * - * @author Eric LEPICIER - * @see Splines - * @version 21 juil. 2002 - */ -public class NatCubicSpline { - - /** - * The proper access for these classes, using default steps. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static float[][] calc(int[] xpoints, int[] ypoints, boolean geometryClosed) { - return calc(xpoints, ypoints, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static float[][] calc(int[] xpoints, int[] ypoints, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(xpoints, ypoints); - } - return new NatCubicSpline().withSteps(steps).calc(xpoints, ypoints); - } - - /** - * The proper access for these classes, using default steps. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static float[][] calc(float[] xpoints, float[] ypoints, boolean geometryClosed) { - return calc(xpoints, ypoints, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param xpoints projected x points - * @param ypoints projected y points - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static float[][] calc(float[] xpoints, float[] ypoints, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(xpoints, ypoints); - } - return new NatCubicSpline().withSteps(steps).calc(xpoints, ypoints); - } - - /** - * The proper access for these classes, using default steps. - * - * @param llpoints - * @param precision - * @param geometryClosed whether the spline is a closed shape - * @return - */ - public static double[] calc(double[] llpoints, double precision, boolean geometryClosed) { - return calc(llpoints, precision, geometryClosed, 12); - } - - /** - * The proper access for these classes. - * - * @param llpoints - * @param precision - * @param geometryClosed whether the spline is a closed shape - * @param steps the number of segments the spline curve should be broken - * into (default 12) - * @return - */ - public static double[] calc(double[] llpoints, double precision, boolean geometryClosed, int steps) { - if (geometryClosed) { - return new NatCubicSpline.CLOSED().withSteps(steps).calc(llpoints, precision); - } - return new NatCubicSpline().withSteps(steps).calc(llpoints, precision); - } - - /** - * Calculates the natural cubic spline that interpolates y[0], y[1], ... - * y[n]. The first segment is returned as C[0].a + C[0].b*u + C[0].c*u^2 + - * C[0].d*u^3 0 <=u <1 the other segments are in C[1], C[2], ... C[n-1] - * - * @param n - * @param x - * @return Cubic[] - */ - Cubic[] calcNaturalCubic(int n, int[] x) { - float[] gamma = new float[n + 1]; - float[] delta = new float[n + 1]; - float[] D = new float[n + 1]; - int i; - /* - * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| - * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 - * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] by using - * row operations to convert the matrix to upper triangular and then - * back substitution. The D[i] are the derivatives at the knots. - */ - - gamma[0] = 1.0f / 2.0f; - for (i = 1; i < n; i++) { - gamma[i] = 1 / (4 - gamma[i - 1]); - } - gamma[n] = 1 / (2 - gamma[n - 1]); - - delta[0] = 3 * (x[1] - x[0]) * gamma[0]; - for (i = 1; i < n; i++) { - delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i]; - } - delta[n] = (3 * (x[n] - x[n - 1]) - delta[n - 1]) * gamma[n]; - - D[n] = delta[n]; - for (i = n - 1; i >= 0; i--) { - D[i] = delta[i] - gamma[i] * D[i + 1]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n]; - for (i = 0; i < n; i++) { - C[i] = new Cubic((float) x[i], D[i], 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1], - 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1]); - } - return C; - } - - /** - * Calculates the natural cubic spline that interpolates y[0], y[1], ... - * y[n]. The first segment is returned as C[0].a + C[0].b*u + C[0].c*u^2 + - * C[0].d*u^3 0 <=u <1 the other segments are in C[1], C[2], ... C[n-1] - * - * @param n - * @param x - * @return Cubic[] - */ - Cubic[] calcNaturalCubic(int n, float[] x) { - float[] gamma = new float[n + 1]; - float[] delta = new float[n + 1]; - float[] D = new float[n + 1]; - int i; - /* - * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| - * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 - * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] by using - * row operations to convert the matrix to upper triangular and then - * back substitution. The D[i] are the derivatives at the knots. - */ - - gamma[0] = 1.0f / 2.0f; - for (i = 1; i < n; i++) { - gamma[i] = 1 / (4 - gamma[i - 1]); - } - gamma[n] = 1 / (2 - gamma[n - 1]); - - delta[0] = 3 * (x[1] - x[0]) * gamma[0]; - for (i = 1; i < n; i++) { - delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i]; - } - delta[n] = (3 * (x[n] - x[n - 1]) - delta[n - 1]) * gamma[n]; - - D[n] = delta[n]; - for (i = n - 1; i >= 0; i--) { - D[i] = delta[i] - gamma[i] * D[i + 1]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n]; - for (i = 0; i < n; i++) { - C[i] = new Cubic((float) x[i], D[i], 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1], - 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1]); - } - return C; - } - - /** - * Calculates a cubic spline polyline - * - * @param xpoints - * @param ypoints - * @return float[][] - */ - public float[][] calc(int[] xpoints, int[] ypoints) { - float[][] res = new float[2][0]; - if (xpoints.length > 2) { - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - // copy polygon points to the return array - res[0] = new float[p.npoints]; - res[1] = new float[p.npoints]; - - for (int i = 0; i < p.npoints; i++) { - res[0][i] = p.xpoints[i]; - res[1][i] = p.ypoints[i]; - } - - p = null; - } else { - // Need to convert to float[] - float[] xfs = new float[xpoints.length]; - float[] yfs = new float[ypoints.length]; - - for (int i = 0; i < xpoints.length; i++) { - xfs[i] = xpoints[i]; - yfs[i] = ypoints[i]; - } - - res[0] = xfs; - res[1] = yfs; - } - return res; - } - - /** - * Calculates a cubic spline polyline - * - * @param xpoints in float precision. - * @param ypoints in float precision. - * @return float[][] - */ - public float[][] calc(float[] xpoints, float[] ypoints) { - float[][] res = new float[2][0]; - if (xpoints.length > 2) { - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - // copy polygon points to the return array - res[0] = new float[p.npoints]; - res[1] = new float[p.npoints]; - - for (int i = 0; i < p.npoints; i++) { - res[0][i] = p.xpoints[i]; - res[1][i] = p.ypoints[i]; - } - - p = null; - } else { - res[0] = xpoints; - res[1] = ypoints; - } - return res; - } - - /** - * Calculates a float lat/lon cubic spline - * - * @param llpoints - * @param precision for dividing floating coordinates to become int, e.g - * 0.01 means spline to be calculated with coordinates * 100 - * @return float[] - */ - public double[] calc(double[] llpoints, double precision) { - double[] res; - if (llpoints.length > 4) { // 2 points - - int[] xpoints = new int[(int) (llpoints.length / 2)]; - int[] ypoints = new int[xpoints.length]; - for (int i = 0, j = 0; i < llpoints.length; i += 2, j++) { - xpoints[j] = (int) (llpoints[i] / precision); - ypoints[j] = (int) (llpoints[i + 1] / precision); - } - - Cubic[] X = calcNaturalCubic(xpoints.length - 1, xpoints); - Cubic[] Y = calcNaturalCubic(ypoints.length - 1, ypoints); - - /* - * very crude technique just break each segment up into steps lines - */ - Polygon p = new Polygon(); - p.addPoint((int) Math.round(X[0].eval(0)), (int) Math.round(Y[0].eval(0))); - for (int i = 0; i < X.length; i++) { - for (int j = 1; j <= steps; j++) { - float u = j / (float) steps; - p.addPoint(Math.round(X[i].eval(u)), Math.round(Y[i].eval(u))); - } - } - - res = new double[p.npoints * 2]; - for (int i = 0, j = 0; i < p.npoints; i++, j += 2) { - res[j] = (double) p.xpoints[i] * precision; - res[j + 1] = (double) p.ypoints[i] * precision; - } - - p = null; - } else { - res = llpoints; - } - return res; - } - - /** - * Returns the steps. - * - * @return int - */ - public int getSteps() { - return steps; - } - - /** - * Sets the number of points (steps) interpolated on the curve between the - * original points to draw it as a polyline. - * - * @param steps The steps to set - */ - public void setSteps(int steps) { - this.steps = steps > 0 ? steps : 12; - } - - /** - * Set the steps and return this object. - * - * @param steps - * @return this - */ - public NatCubicSpline withSteps(int steps) { - setSteps(steps); - return this; - } - - private int steps = 12; - - /** - * Moved from an outside class, the closed case of a NatCubicSpline. - */ - public static class CLOSED extends NatCubicSpline { - - /** - * Calculates the closed natural cubic spline that interpolates x[0], - * x[1], ... x[n]. The first segment is returned as C[0].a + C[0].b*u + - * C[0].c*u^2 + C[0].d*u^3 0 <=u <1 the other segments are in C[1], - * C[2], ... C[n] - * - * @see com.bbn.openmap.omGraphics.NatCubicSpline#calcNaturalCubic(int, - * int[]) - */ - Cubic[] calcNaturalCubic(int n, int[] x) { - float[] w = new float[n + 1]; - float[] v = new float[n + 1]; - float[] y = new float[n + 1]; - float[] D = new float[n + 1]; - float z, F, G, H; - int k; - /* - * We solve the equation [4 1 1] [D[0]] [3(x[1] - x[n]) ] |1 4 1 | - * |D[1]| |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | - * | . | | 1 4 1| | . | |3(x[n] - x[n-2])| [1 1 4] [D[n]] [3(x[0] - - * x[n-1])] by decomposing the matrix into upper triangular and - * lower matrices and then back substitution. See Spath "Spline - * Algorithms for Curves and Surfaces" pp 19--21. The D[i] are the - * derivatives at the knots. - */ - w[1] = v[1] = z = 1.0f / 4.0f; - y[0] = z * 3 * (x[1] - x[n]); - H = 4; - F = 3 * (x[0] - x[n - 1]); - G = 1; - for (k = 1; k < n; k++) { - v[k + 1] = z = 1 / (4 - v[k]); - w[k + 1] = -z * w[k]; - y[k] = z * (3 * (x[k + 1] - x[k - 1]) - y[k - 1]); - H -= G * w[k]; - F -= G * y[k - 1]; - G = -v[k] * G; - } - H -= (G + 1) * (v[n] + w[n]); - y[n] = F - (G + 1) * y[n - 1]; - - D[n] = y[n] / H; - D[n - 1] = y[n - 1] - (v[n] + w[n]) * D[n]; - /* This equation is WRONG! in my copy of Spath */ - for (k = n - 2; k >= 0; k--) { - D[k] = y[k] - v[k + 1] * D[k + 1] - w[k + 1] * D[n]; - } - - /* now compute the coefficients of the cubics */ - Cubic[] C = new Cubic[n + 1]; - for (k = 0; k < n; k++) { - C[k] = new Cubic((float) x[k], D[k], 3 * (x[k + 1] - x[k]) - 2 * D[k] - D[k + 1], - 2 * (x[k] - x[k + 1]) + D[k] + D[k + 1]); - } - C[n] = new Cubic((float) x[n], D[n], 3 * (x[0] - x[n]) - 2 * D[n] - D[0], 2 * (x[n] - x[0]) + D[n] + D[0]); - return C; - } - - /** - * @see com.bbn.openmap.omGraphics.NatCubicSpline#calc(int[], int[]) - */ - public float[][] calc(int[] xpoints, int[] ypoints) { - - int[] xpts = xpoints; - int[] ypts = ypoints; - int l = xpoints.length; - if (xpoints.length > 2) { - if (xpoints[0] == xpoints[l - 1] && ypoints[0] == ypoints[l - 1]) { - xpts = new int[l - 1]; - System.arraycopy(xpoints, 0, xpts, 0, l - 1); - ypts = new int[l - 1]; - System.arraycopy(ypoints, 0, ypts, 0, l - 1); - } - } - return super.calc(xpts, ypts); - } - - /** - * @see NatCubicSpline#calc(double[], double) - */ - public double[] calc(double[] llpoints, double precision) { - - double[] llpts = llpoints; - int l = llpoints.length; - if (l > 4) { - if (MoreMath.approximately_equal(llpoints[0], llpoints[l - 2]) - && MoreMath.approximately_equal(llpoints[1], llpoints[l - 1])) { - llpts = new double[l - 2]; - System.arraycopy(llpoints, 0, llpts, 0, l - 2); - } - } - - return super.calc(llpts, precision); - } - } - - /** - * A cubic polynomial - */ - class Cubic { - - float a, b, c, d; /* a + b*u + c*u^2 +d*u^3 */ - - /** - * Constructor. - * - * @param a - * @param b - * @param c - * @param d - */ - public Cubic(float a, float b, float c, float d) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - } - - /** - * evaluate cubic for this value. - * - * @param u - * @return float - */ - public float eval(float u) { - return (((d * u) + c) * u + b) * u + a; - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMDistance.java b/src/openmap/com/bbn/openmap/omGraphics/OMDistance.java deleted file mode 100644 index 60e7b991f..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMDistance.java +++ /dev/null @@ -1,369 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMDistance.java,v $ -// $RCSfile: OMDistance.java,v $ -// $Revision: 1.12 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Paint; -import java.awt.geom.AffineTransform; -import java.text.DecimalFormat; -import java.util.Iterator; - -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.proj.Length; -import com.bbn.openmap.proj.LineCoordinateGenerator; -import com.bbn.openmap.proj.ProjMath; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * OMGraphic object that represents a polyline, labeled with distances. - */ -public class OMDistance extends OMPoly { - - protected OMGraphicList labels = new OMGraphicList(); - protected OMGraphicList points = new OMGraphicList(); - - protected Length distUnits = Length.NM; - public DecimalFormat df = new DecimalFormat("0.#"); - /** - * Paint used for labels - */ - protected Paint labelPaint; - /** - * Font used for labels - */ - protected Font labelFont; - - /** - * Construct a default OMDistance. - */ - public OMDistance() { - super(); - setRenderType(RENDERTYPE_LATLON); - } - - /** - * Create an OMDistance from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public OMDistance(double[] llPoints, int units, int lType, Length distanceUnits) { - this(llPoints, units, lType, -1, distanceUnits); - } - - /** - * Create an OMDistance from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the poly to be connected (as a polygon), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is generated - * internally) - */ - public OMDistance(double[] llPoints, int units, int lType, int nsegs, Length distanceUnits) { - super(llPoints, units, lType, nsegs); - setDistUnits(distanceUnits); - } - - /** - * Set the Length object used to represent distances. - */ - public void setDistUnits(Length distanceUnits) { - distUnits = distanceUnits; - } - - /** - * Get the Length object used to represent distances. - */ - public Length getDistUnits() { - return distUnits; - } - - public void setLocation(double[] llPoints, int units) { - this.units = OMGraphic.RADIANS; - if (units == OMGraphic.DECIMAL_DEGREES) { - ProjMath.arrayDegToRad(llPoints); - } - rawllpts = llPoints; - setNeedToRegenerate(true); - setRenderType(RENDERTYPE_LATLON); - } - - public void createLabels() { - labels.clear(); - points.clear(); - - if (rawllpts == null) { - return; - } - if (rawllpts.length < 4) { - return; - } - - Geo lastGeo = new Geo(rawllpts[0], rawllpts[1], units == DECIMAL_DEGREES); - double latpnt = rawllpts[0]; - double lonpnt = rawllpts[1]; - if (units == RADIANS) { - latpnt = ProjMath.radToDeg(latpnt); - lonpnt = ProjMath.radToDeg(lonpnt); - } - points.add(new OMPoint(latpnt, lonpnt, 1)); - Geo curGeo = null; - double cumulativeDist = 0.0; - for (int p = 2; p < rawllpts.length; p += 2) { - if (curGeo == null) { - curGeo = new Geo(rawllpts[p], rawllpts[p + 1], units == DECIMAL_DEGREES); - } else { - if (units == DECIMAL_DEGREES) { - curGeo.initialize(rawllpts[p], rawllpts[p + 1]); - } else { - curGeo.initializeRadians(rawllpts[p], rawllpts[p + 1]); - } - } - - double dist = getDist(lastGeo, curGeo); - cumulativeDist += dist; - - labels.add(createLabel(lastGeo, curGeo, dist, cumulativeDist, distUnits)); - latpnt = rawllpts[p]; - lonpnt = rawllpts[p + 1]; - if (units == RADIANS) { - latpnt = ProjMath.radToDeg(latpnt); - lonpnt = ProjMath.radToDeg(lonpnt); - } - - points.add(new OMPoint(latpnt, lonpnt, 1)); - lastGeo.initialize(curGeo); - } - } - - /** - * Get an OMText label for a segments between the given lat/lon points whose - * given distance and cumulative distance is specified. - */ - public OMText createLabel(Geo g1, Geo g2, double dist, double cumulativeDist, Length distanceUnits) { - Geo mid; - switch (getLineType()) { - case LINETYPE_STRAIGHT: - double lat = (g1.getLatitude() + g2.getLatitude()) / 2.0; - double lon = (g1.getLongitude() + g2.getLongitude()) / 2.0; - mid = new Geo(lat, lon); - break; - case LINETYPE_RHUMB: - System.err.println("Rhumb distance calculation not implemented."); - case LINETYPE_GREATCIRCLE: - case LINETYPE_UNKNOWN: - default: - mid = g1.midPoint(g2); - } - - // String text = ((int)dist) + " (" + ((int)cumulativeDist) + - // ")"; - - String text = (df.format(distanceUnits.fromRadians(dist))) + " (" - + (df.format(distanceUnits.fromRadians(cumulativeDist))) + ") " + distanceUnits.getAbbr(); - OMText omtext = new OMText(mid.getLatitude(), mid.getLongitude(), text, OMText.JUSTIFY_LEFT); - // omtext.setLinePaint(new Color(200, 200, 255)); - return omtext; - } - - /** - * Return the distance between that lat/lons defined in radians. The - * returned value is in radians and LINETYPE is taken into consideration. - * LINETYPE_STRAIGHT returns same as LINETYPE_GREATCIRCLE, the ground - * distance between all nodes and not the degree distance of the lines. - */ - public double getDist(Geo g1, Geo g2) { - switch (getLineType()) { - case LINETYPE_RHUMB: - - double[] coords = new double[] { g1.getLatitudeRadians(), g1.getLongitudeRadians(), g2.getLatitudeRadians(), - g2.getLongitudeRadians() }; - return ProjMath.distance(LineCoordinateGenerator.fromRadians(coords).rhumbLineDoubles()); - - case LINETYPE_STRAIGHT: - case LINETYPE_GREATCIRCLE: - case LINETYPE_UNKNOWN: - default: - return g1.distance(g2); - } - } - - /** - * Prepare the poly for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - boolean ret = super.generate(proj); - createLabels(); - labels.generate(proj); - points.generate(proj); - return ret; - } - - /** - * Flag used by the EditableOMDistance to do quick movement paints in a - * cleaner way. - */ - protected boolean paintOnlyPoly = false; - - /** - * Paint the poly. This works if generate() has been successful. - * - * @param g java.awt.Graphics to paint the poly onto. - */ - public void render(Graphics g) { - super.render(g); - - if (!paintOnlyPoly) { - renderPoints(g); - renderLabels(g); - } - } - - /** - * render points - */ - protected void renderPoints(Graphics g) { - Paint pointPaint = getLabelPaint(); - - for (Iterator it = points.iterator(); it.hasNext();) { - OMGraphic point = (OMPoint) it.next(); - point.setLinePaint(pointPaint); - point.setFillPaint(pointPaint); - point.render(g); - } - } - - /** - * render labels - */ - protected void renderLabels(Graphics g) { - Font f = getFont(); - Paint labelPaint = getLabelPaint(); - Paint mattingPaint = getMattingPaint(); - boolean isMatted = isMatted(); - for (Iterator it = labels.iterator(); it.hasNext();) { - OMText text = (OMText) it.next(); - text.setFont(f); - text.setLinePaint(labelPaint); - if (isMatted) { - text.setFillPaint(mattingPaint); - } - text.render(g); - } - } - - /** - * Set paint used for labels - * - * @param lPaint paint used for labels - */ - public void setLabelPaint(Paint lPaint) { - labelPaint = lPaint; - } - - /** - * @return normal paint used for labels - */ - public Paint getLabelPaint() { - if (labelPaint == null) { - return getLinePaint(); - } - return labelPaint; - } - - /** - * @param font font used for labels - */ - public void setFont(Font font) { - if (font == null) { - labelFont = OMText.DEFAULT_FONT; - } else { - labelFont = font; - } - } - - /** - * @return font used for labels - */ - public Font getFont() { - if (labelFont == null) { - labelFont = OMText.DEFAULT_FONT; - } - return labelFont; - } - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - stream.defaultWriteObject(); - stream.writeObject(distUnits.getAbbr()); - } - - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - stream.defaultReadObject(); - distUnits = Length.get((String) stream.readObject()); - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMDistance) { - OMDistance dist = (OMDistance) source; - this.labels = DeepCopyUtil.deepCopy(dist.labels); - this.points = DeepCopyUtil.deepCopy(dist.points); - this.distUnits = dist.distUnits; - this.df = new DecimalFormat(dist.df.toLocalizedPattern()); - this.labelPaint = dist.labelPaint; - if (dist.labelFont != null) { - this.labelFont = dist.labelFont.deriveFont(AffineTransform.TYPE_IDENTITY); - } - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMLine.java b/src/openmap/com/bbn/openmap/omGraphics/OMLine.java deleted file mode 100644 index 1edf6785b..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMLine.java +++ /dev/null @@ -1,495 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMLine.java,v $ -// $RCSfile: OMLine.java,v $ -// $Revision: 1.15 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.omGraphics.geom.NonRegional; -import com.bbn.openmap.omGraphics.util.ArcCalc; -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.DeepCopyUtil; - -/** - * Graphic object that represents a simple line. - *

- * The OMLine is used to create simple lines, from one point on the window to - * the other. If you want to have a line with several parts, use OMPoly as a - * polyline with no fillColor. - *

NOTE:

See the - * RESTRICTIONS on - * Lat/Lon lines. Not following the guidelines listed may result in - * ambiguous/undefined shapes! Similar assumptions apply to the other vector - * graphics that we define: circles, ellipses, rects, polys. - *

- * - * @see OMPoly - */ -public class OMLine extends OMAbstractLine implements Serializable, NonRegional { - - /** - * Figured out after generation, based on what's going on with the map. - */ - protected transient boolean isPolyline = false; - - /** latlons is a array of 4 doubles - lat1, lon1, lat2, lon2. */ - protected double[] latlons = null; - - /** pts is an array of 4 ints - px1, py1, px2, py2. */ - protected int[] pts = null; - - /** - * For x-y and offset lines, there is the ability to put a curve in the - * line. This setting is the amount of an angle, limited to a semi-circle - * (PI) that the curve will represent. In other words, the arc between the - * two end points is going to look like a 0 degrees of a circle (straight - * line, which is the default), or 180 degrees of a circle (full - * semi-circle). Given in radians, though, not degrees. The ArcCalc object - * handles all the details. - */ - protected ArcCalc arc = null; - - public final static int STRAIGHT_LINE = 0; - public final static int CURVED_LINE = 1; - - /** Generic constructor, attributes need to filled later. */ - public OMLine() { - super(RENDERTYPE_UNKNOWN, LINETYPE_UNKNOWN, DECLUTTERTYPE_NONE); - } - - /** - * Create a line from lat lon points. - * - * @param lat_1 latitude of first point, decimal degrees. - * @param lon_1 longitude of first point, decimal degrees. - * @param lat_2 latitude of second point, decimal degrees. - * @param lon_2 longitude of second point, decimal degrees. - * @param lineType a choice between LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE - * or LINETYPE_RHUMB. - */ - public OMLine(double lat_1, double lon_1, double lat_2, double lon_2, int lineType) { - this(lat_1, lon_1, lat_2, lon_2, lineType, -1); - } - - /** - * Create a line from lat lon points. - * - * @param lat_1 latitude of first point, decimal degrees. - * @param lon_1 longitude of first point, decimal degrees. - * @param lat_2 latitude of second point, decimal degrees. - * @param lon_2 longitude of second point, decimal degrees. - * @param lineType a choice between LINETYPE_STRAIGHT, LINETYPE_GREATCIRCLE - * or LINETYPE_RHUMB. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is generated - * internally) - */ - public OMLine(double lat_1, double lon_1, double lat_2, double lon_2, int lineType, int nsegs) { - super(RENDERTYPE_LATLON, lineType, DECLUTTERTYPE_NONE); - latlons = new double[4]; - latlons[0] = lat_1; - latlons[2] = lat_2; - latlons[1] = lon_1; - latlons[3] = lon_2; - this.nsegs = nsegs; - } - - /** - * Create a line between two xy points on the window. - * - * @param x1 the x location of the first point, in pixels from the left of - * the window. - * @param y1 the y location of the first point, in pixels from the top of - * the window. - * @param x2 the x location of the second point, in pixels from the left of - * the window. - * @param y2 the y location of the second point, in pixels from the top of - * the window. - */ - public OMLine(int x1, int y1, int x2, int y2) { - super(RENDERTYPE_XY, LINETYPE_STRAIGHT, DECLUTTERTYPE_NONE); - pts = new int[4]; - pts[0] = x1; - pts[1] = y1; - pts[2] = x2; - pts[3] = y2; - } - - /** - * Create a line between two x-y points on the window, where the x-y points - * are offsets from a lat-lon point. It assumes that you'll want a straight - * window line between the points, so if you don't, use the setLineType() - * method to change it. - * - * @param lat_1 the latitude of the reference point of the line, in decimal - * degrees. - * @param lon_1 the longitude of the reference point of the line, in decimal - * degrees. - * @param x1 the x location of the first point, in pixels from the longitude - * point. - * @param y1 the y location of the first point, in pixels from the latitude - * point. - * @param x2 the x location of the second point, in pixels from the - * longitude point. - * @param y2 the y location of the second point, in pixels from the latitude - * point. - */ - public OMLine(double lat_1, double lon_1, int x1, int y1, int x2, int y2) { - - super(RENDERTYPE_OFFSET, LINETYPE_STRAIGHT, DECLUTTERTYPE_NONE); - latlons = new double[4]; - pts = new int[4]; - latlons[0] = lat_1; - latlons[1] = lon_1; - pts[0] = x1; - pts[1] = y1; - pts[2] = x2; - pts[3] = y2; - } - - /** - * Set the lat lon values of the end points of the line from an array of - * doubles - lat1, lon1, lat2, lon2. This does not look at the line render - * type, so it acts accordingly. LL1 is only used in RENDERTYPE_LATLON, - * RENDERTYPE_OFFSET, and LL2 is only used in RENDERTYPE_LATLON. - * - * @param lls array of doubles - lat1, lon1, lat2, lon2 - */ - public void setLL(double[] lls) { - latlons = lls; - setNeedToRegenerate(true); - } - - /** - * Get the lat lon values of the end points of the line in an array of - * doubles - lat1, lon1, lat2, lon2. Again, this does not look at the line - * render type, so it acts accordingly. LL1 is only used in - * RENDERTYPE_LATLON, RENDERTYPE_OFFSET, and LL2 is only used in - * RENDERTYPE_LATLON. - * - * @return the lat lon array, and all are decimal degrees. - */ - public double[] getLL() { - return latlons; - } - - /** - * Set the xy values of the end points of the line from an array of ints - - * x1, y1, x2, y2 . This does not look at the line render type, so it acts - * accordingly. p1 and p2 are only used in RENDERTYPE_XY, RENDERTYPE_OFFSET. - * - * @param xys array of ints for the points - x1, y1, x2, y2 - */ - public void setPts(int[] xys) { - pts = xys; - setNeedToRegenerate(true); - } - - /** - * Get the xy values of the end points of the line in an array of ints - x1, - * y1, x2, y2 . This does not look at the line render type, so it acts - * accordingly. p1 and p2 are only used in RENDERTYPE_XY, RENDERTYPE_OFFSET. - * - * @return the array of x-y points, and all are pixel values - */ - public int[] getPts() { - return pts; - } - - /** - * Check to see if this line is a polyline. This is a polyline if it is - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB for RENDERTYPE_LATLON polys. - * - * @return true if polyline false if not - */ - public boolean isPolyline() { - return isPolyline; - } - - /** - * Set the number of segments of the lat/lon line. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types, and if < 1, this - * value is generated internally). - * - * @param nsegs number of segment points - */ - public void setNumSegs(int nsegs) { - this.nsegs = nsegs; - } - - /** - * Get the number of segments of the lat/lon line. (This is only for - * LINETYPE_GREATCIRCLE or LINETYPE_RHUMB line types). - * - * @return int number of segment points - */ - public int getNumSegs() { - return nsegs; - } - - /** - * Set the arc that is drawn between the points of a x-y or offset line. - */ - public void setArc(ArcCalc ac) { - arc = ac; - } - - /** - * Return the arc angle set for this line. Will only be set if it was set - * externally. - * - * @return arc angle in radians. - */ - public ArcCalc getArc() { - return arc; - } - - /** - * Prepare the line for rendering. - * - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omgraphic", "OMLine: null projection in generate!"); - return false; - } - - // reset the internals - isPolyline = false; - initLabelingDuringGenerate(); - GeneralPath projectedShape = null; - - switch (renderType) { - case RENDERTYPE_XY: - - if (pts == null) { - return false; - } - - if (arc != null) { - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(pts[0], pts[1], pts[2], pts[3]); - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - } else { - xpoints = new float[1][2]; - ypoints = new float[1][2]; - - xpoints[0][0] = pts[0]; - ypoints[0][0] = pts[1]; - xpoints[0][1] = pts[2]; - ypoints[0][1] = pts[3]; - } - projectedShape = createShape(xpoints[0], ypoints[0], false); - break; - case RENDERTYPE_OFFSET: - if (pts == null || latlons == null || !proj.isPlotable(latlons[0], latlons[1])) { - setNeedToRegenerate(true); - return false; - } - - Point p1 = (Point) proj.forward(latlons[0], latlons[1], new Point()); - if (arc != null) { - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(p1.x + pts[0], p1.y + pts[1], p1.x + pts[2], p1.y + pts[3]); - - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - } else { - xpoints = new float[1][2]; - ypoints = new float[1][2]; - - xpoints[0][0] = p1.x + pts[0]; - ypoints[0][0] = p1.y + pts[1]; - xpoints[0][1] = p1.x + pts[2]; - ypoints[0][1] = p1.y + pts[3]; - } - projectedShape = createShape(xpoints[0], ypoints[0], false); - break; - case RENDERTYPE_LATLON: - if (latlons == null) { - setNeedToRegenerate(true); - return false; - } - - if (arc != null) { - p1 = (Point) proj.forward(latlons[0], latlons[1], new Point()); - Point p2 = (Point) proj.forward(latlons[2], latlons[3], new Point()); - xpoints = new float[1][]; - ypoints = new float[1][]; - arc.generate(p1.x, p1.y, p2.x, p2.y); - - xpoints[0] = arc.getXPoints(); - ypoints[0] = arc.getYPoints(); - - projectedShape = createShape(xpoints[0], ypoints[0], false); - - isPolyline = true; - - } else { - ArrayList lines = null; - if (proj instanceof GeoProj) { - lines = - ((GeoProj) proj).forwardLine(new LatLonPoint.Double(latlons[0], latlons[1]), - new LatLonPoint.Double(latlons[2], latlons[3]), lineType, nsegs); - } else { - lines = - proj.forwardLine(new Point2D.Double(latlons[1], latlons[0]), new Point2D.Double(latlons[3], - latlons[2])); - } - - int size = lines.size(); - - xpoints = new float[(int) (size / 2)][0]; - ypoints = new float[xpoints.length][0]; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - float[] xps = (float[]) lines.get(i); - float[] yps = (float[]) lines.get(i + 1); - - xpoints[j] = xps; - ypoints[j] = yps; - - GeneralPath gp = createShape(xps, yps, false); - - projectedShape = appendShapeEdge(projectedShape, gp, false); - } - - isPolyline = (lineType != LINETYPE_STRAIGHT); - } - break; - case RENDERTYPE_UNKNOWN: - System.err.println("OMLine.generate: invalid RenderType"); - setNeedToRegenerate(true); - return false; - } - - // label location is set in setShape - setShape(projectedShape); - setLabelLocation(projectedShape, proj); - - if (arrowhead != null) { - arrowhead.generate(this); - } - - if (arc != null) { - // This will only do something if debugging is on. - arc.generate(proj); - } - - setNeedToRegenerate(false); - return true; - } - - /** - * Paint the line. - * - * @param g Graphics context to render into - */ - public void render(Graphics g) { - - if (!isRenderable(getShape())) { - return; - } - - // Just to draw the matting for the arrowhead. The matting - // for the rest of the line will be taken care of in - // super.render(). - if (arrowhead != null && isMatted() && g instanceof Graphics2D && stroke instanceof BasicStroke) { - ((Graphics2D) g).setStroke(new BasicStroke(((BasicStroke) stroke).getLineWidth() + 2f)); - setGraphicsColor(g, Color.black); - arrowhead.render(g); - } - - super.render(g); - - if (arrowhead != null) { - setGraphicsForEdge(g); - arrowhead.render(g); - } - - if (arc != null) { - // This is a debugging thing, most times does nothing. - arc.render(g); - } - - } - - /** - * The OMLine should never render fill. It can think it does, if the - * geometry turns out to be curved. Returning false affects distance() and - * contains() methods. - */ - public boolean shouldRenderFill() { - return false; - } - - /** - * This takes the area out of OMLines that may look like they have area, - * depending on their shape. Checks to see what shouldRenderFill() returns - * (false by default) to decide how to measure this. If shouldRenderFill == - * true, the super.contains() method is returned, which assumes the line - * shape has area if it is curved. Otherwise, it returns true if the point - * is on the line. - */ - public boolean contains(double x, double y) { - if (shouldRenderFill()) { - return super.contains(x, y); - } else { - return (distance(x, y) == 0); - } - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMLine) { - OMLine line = (OMLine) source; - - this.latlons = DeepCopyUtil.deepCopy(line.latlons); - this.pts = DeepCopyUtil.deepCopy(line.pts); - if (line.arc != null) { - this.arc = new ArcCalc(line.arc.getArcAngle(), line.arc.isArcUp()); - } else { - this.arc = null; - } - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMShape.java b/src/openmap/com/bbn/openmap/omGraphics/OMShape.java deleted file mode 100644 index 3026a666d..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMShape.java +++ /dev/null @@ -1,107 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMShape.java,v $ -// $RCSfile: OMShape.java,v $ -// $Revision: 1.3 $ -// $Date: 2006/04/07 15:38:59 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.BasicStroke; -import java.awt.Shape; -import java.awt.geom.FlatteningPathIterator; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; - -import com.bbn.openmap.proj.Projection; - -/** - * The OMShape object is an OMGraphic intended to be used with non-GeoProj - * projections, defining projected map object to be modified for different - * views. You can use it to provide OMGraphic functionality, with respect to - * colors and strokes and OMGraphicLists, to java.awt.Shape objects. - *

- * GeoProj projections will be able to display them, but they will be rendered - * as OMGraphic.RENDERTYPE_LATLON with OMGraphic.LINETYPE_STRAIGHT settings. - * Rendering can be unpredictable for large coordinate values. - */ -public class OMShape extends OMGraphicAdapter implements OMGraphic { - private static final long serialVersionUID = 1L; - protected Shape origShape = null; - - protected OMShape() { - } - - public OMShape(Shape shapeIn) { - origShape = shapeIn; - } - - public Shape getOrigShape() { - return origShape; - } - - public void setOrigShape(Shape origShape) { - this.origShape = origShape; - setNeedToRegenerate(true); - } - - public boolean generate(Projection proj) { - setNeedToRegenerate(true); - - if (origShape != null) { - setShape(new GeneralPath(proj.forwardShape(origShape))); - setLabelLocation(getShape(), proj); - setNeedToRegenerate(false); - return true; - } - - return false; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMShape) { - OMShape shape = (OMShape) source; - - this.origShape = new GeneralPath(shape.origShape); - } - } - - /** - * This is a subclass that uses the provided shape as the generated shape. - * Takes advantage of the rendering mechanism of OMGraphics. Mainly used for - * rendering features already projected for vector tiles. - * - * @author dietrick - * - */ - public static class PROJECTED extends OMShape { - private static final long serialVersionUID = 1L; - - public PROJECTED(Shape s) { - super(s); - setShape(new GeneralPath(origShape)); - setNeedToRegenerate(false); - } - - public boolean generate(Projection proj) { - // NOOP - return true; - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMSpline.java b/src/openmap/com/bbn/openmap/omGraphics/OMSpline.java deleted file mode 100644 index a6d268e29..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMSpline.java +++ /dev/null @@ -1,278 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/OMSpline.java,v $ -//$RCSfile: OMSpline.java,v $ -//$Revision: 1.11 $ -//$Date: 2009/01/21 01:24:41 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Point; -import java.util.ArrayList; - -import com.bbn.openmap.proj.GeoProj; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; - -/** - * A splined OMPoly. With RENDERTYPE_LATLON mode, spline is computed on - * geographic locations, and then projected. Very few changes from OMPoly source - * code, just needed to calculate the spline before projecting in generate(). - * Look for HACK in source code ... - * - * @author Eric LEPICIER - * @version 15 juil. 2002 - */ -public class OMSpline extends OMPoly { - - /** - * Default constructor. - */ - public OMSpline() { - super(); - } - - /** - * Create an OMSpline from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the curve to be connected (as a potato), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - */ - public OMSpline(double[] llPoints, int units, int lType) { - super(llPoints, units, lType); - } - - /** - * Create an OMSpline from a list of float lat/lon pairs. - *

- * NOTES: - *

    - *
  • llPoints array is converted into radians IN PLACE for more efficient - * handling internally if it's not already in radians! For even better - * performance, you should send us an array already in radians format! - *
  • If you want the curve to be connected (as a potato), you need to - * ensure that the first and last coordinate pairs are the same. - *
- * - * @param llPoints array of lat/lon points, arranged lat, lon, lat, lon, - * etc. - * @param units radians or decimal degrees. Use OMGraphic.RADIANS or - * OMGraphic.DECIMAL_DEGREES - * @param lType line type, from a list defined in OMGraphic. - * @param nsegs number of segment points (only for LINETYPE_GREATCIRCLE or - * LINETYPE_RHUMB line types, and if < 1, this value is - * generated internally) - */ - public OMSpline(double[] llPoints, int units, int lType, int nsegs) { - super(llPoints, units, lType, nsegs); - } - - /** - * Create an OMSpline from a list of xy pairs. If you want the curve to be - * connected, you need to ensure that the first and last coordinate pairs - * are the same. - * - * @param xypoints array of x/y points, arranged x, y, x, y, etc. - */ - public OMSpline(int[] xypoints) { - super(xypoints); - } - - /** - * Create an x/y OMSpline. If you want the curve to be connected, you need - * to ensure that the first and last coordinate pairs are the same. - * - * @param xPoints int[] of x coordinates - * @param yPoints int[] of y coordinates - */ - public OMSpline(int[] xPoints, int[] yPoints) { - super(xPoints, yPoints); - } - - /** - * Create an x/y OMSpline at an offset from lat/lon. If you want the curve - * to be connected, you need to ensure that the first and last coordinate - * pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xypoints int[] of x,y pairs - * @param cMode offset coordinate mode - */ - public OMSpline(double latPoint, double lonPoint, int[] xypoints, int cMode) { - super(latPoint, lonPoint, xypoints, cMode); - } - - /** - * Create an x/y OMSpline at an offset from lat/lon. If you want the curve - * to be connected, you need to ensure that the first and last coordinate - * pairs are the same. - * - * @param latPoint latitude in decimal degrees - * @param lonPoint longitude in decimal degrees - * @param xPoints int[] of x coordinates - * @param yPoints int[] of y coordinates - * @param cMode offset coordinate mode - */ - public OMSpline(double latPoint, double lonPoint, int[] xPoints, int[] yPoints, int cMode) { - super(latPoint, lonPoint, xPoints, yPoints, cMode); - } - - /** - * Prepare the spline for rendering. - * - * @see com.bbn.openmap.omGraphics.OMGeometry#generate(Projection) - * @param proj Projection - * @return true if generate was successful - */ - public boolean generate(Projection proj) { - - setNeedToRegenerate(true); - - if (proj == null) { - Debug.message("omspline", "OMSpline: null projection in generate!"); - return false; - } - - // NatCubicSpline spline = isGeometryClosed() ? natCubicClosed : - // natCubic; - // HACK : should use something else than nsegs - // spline.setSteps(nsegs); - - float[][] splinePoints; - - switch (renderType) { - - case RENDERTYPE_XY: - if (xs == null) { - Debug.message("omspline", "OMSpline x/y rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - splinePoints = NatCubicSpline.calc(xs, ys, isGeometryClosed(), nsegs); - xpoints = new float[1][0]; - xpoints[0] = splinePoints[0]; - ypoints = new float[1][0]; - ypoints[0] = splinePoints[1]; - - break; - - case RENDERTYPE_OFFSET: - if (xs == null) { - Debug.message("omspline", "OMSpline offset rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - int npts = xs.length; - float[] _x = new float[npts]; - float[] _y = new float[npts]; - - // forward project the radian point - Point origin = new Point(); - if (proj instanceof GeoProj) { - ((GeoProj) proj).forward(lat, lon, origin, true);// radians - } else { - proj.forward(Math.toDegrees(lat), Math.toDegrees(lon), origin); - } - - if (coordMode == COORDMODE_ORIGIN) { - for (int i = 0; i < npts; i++) { - _x[i] = (float) (xs[i] + origin.getX()); - _y[i] = (float) (ys[i] + origin.getY()); - } - } else { // CModePrevious offset deltas - _x[0] = xs[0] + origin.x; - _y[0] = ys[0] + origin.y; - - for (int i = 1; i < npts; i++) { - _x[i] = xs[i] + _x[i - 1]; - _y[i] = ys[i] + _y[i - 1]; - } - } - - splinePoints = NatCubicSpline.calc(_x, _y, isGeometryClosed(), nsegs); - - xpoints = new float[1][0]; - xpoints[0] = splinePoints[0]; - ypoints = new float[1][0]; - ypoints[0] = splinePoints[1]; - - break; - - case RENDERTYPE_LATLON: - if (rawllpts == null) { - Debug.message("omspline", "OMSpline latlon rendertype null coordinates"); - setNeedToRegenerate(true); - return false; - } - - // spline creation ; precision 1e-8 rad = 0.002" - double[] splinellpts = NatCubicSpline.calc(rawllpts, 1e-8f, isGeometryClosed(), nsegs); - - // polygon/polyline project the polygon/polyline. - // Vertices should already be in radians. - ArrayList vector; - if (proj instanceof GeoProj) { - vector = ((GeoProj) proj).forwardPoly(splinellpts, lineType, nsegs, isPolygon()); - } else { - vector = proj.forwardPoly(rawllpts, isPolygon()); - } - int size = vector.size(); - - xpoints = new float[(int) (size / 2)][0]; - ypoints = new float[xpoints.length][0]; - - for (int i = 0, j = 0; i < size; i += 2, j++) { - xpoints[j] = vector.get(i); - ypoints[j] = vector.get(i + 1); - } - - if (!doShapes && size > 1) { - setNeedToRegenerate(false); - initLabelingDuringGenerate(); - setLabelLocation(xpoints[0], ypoints[0], proj); - return true; - } - - break; - - case RENDERTYPE_UNKNOWN: - Debug.error("OMSpline.generate: invalid RenderType"); - return false; - } - - setNeedToRegenerate(false); - setShape(createShape()); - setLabelLocation(getShape(), proj); - return true; - } -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMTextLabeler.java b/src/openmap/com/bbn/openmap/omGraphics/OMTextLabeler.java deleted file mode 100644 index f3e178514..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMTextLabeler.java +++ /dev/null @@ -1,245 +0,0 @@ -// ********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: OMTextLabeler.java,v $ -//$Revision: 1.4 $ -//$Date: 2007/06/21 21:38:59 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Font; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; - -/** - * A default implementation of OMLabeler that extends from OMText. One thing - * going on with OMTextLabelers is that they are set to be non-rotating by - * default, which means they preserve their set orientation even when the map - * rotates. If you want them to rotate with the map, unset the - * OMGraphicConstants.NO_ROTATE attribute, or set it to Boolean.FALSE. - * - *
- * Usage:
- * 
- *  OMTextLabeler label = new OMTextLabeler(labelString, OMText.JUSTIFY_CENTER);
- *  omgraphic.putAttribute(OMGraphicConstants.LABEL, label);
- * 
- * - * @author dietrick - */ -public class OMTextLabeler extends OMText implements OMLabeler { - - public final static int ANCHOR_TOPLEFT = 0; - public final static int ANCHOR_TOP = 1; - public final static int ANCHOR_TOPRIGHT = 2; - public final static int ANCHOR_LEFT = 3; - public final static int ANCHOR_CENTER = 4; - public final static int ANCHOR_RIGHT = 5; - public final static int ANCHOR_BOTTOMLEFT = 6; - public final static int ANCHOR_BOTTOM = 7; - public final static int ANCHOR_BOTTOMRIGHT = 8; - - protected int anchor = ANCHOR_CENTER; - - /** - * - */ - public OMTextLabeler(String stuff) { - this(stuff, DEFAULT_FONT, JUSTIFY_LEFT); - } - - /** - * @param stuff - * @param just - */ - public OMTextLabeler(String stuff, int just) { - this(stuff, DEFAULT_FONT, just, ANCHOR_CENTER); - } - - public OMTextLabeler(String stuff, int just, int loc) { - this(stuff, DEFAULT_FONT, just, loc); - } - - /** - * @param stuff - * @param font - * @param just - */ - public OMTextLabeler(String stuff, Font font, int just) { - this(stuff, font, just, ANCHOR_CENTER); - } - - public OMTextLabeler(String stuff, Font font, int just, int loc) { - setRenderType(RENDERTYPE_XY); - setData(stuff); - setFont(font); - setJustify(just); - setAnchor(loc); - - putAttribute(OMGraphicConstants.NO_ROTATE, Boolean.TRUE); - } - - public void setLocation(GeneralPath gp) { - if (gp != null) { - Rectangle rect = gp.getBounds(); - - double x = rect.getX(); - double y = rect.getY(); - - if (anchor == ANCHOR_TOP || anchor == ANCHOR_CENTER || anchor == ANCHOR_BOTTOM) { - x += rect.getWidth() / 2; - } else if (anchor == ANCHOR_TOPRIGHT || anchor == ANCHOR_RIGHT || anchor == ANCHOR_BOTTOMRIGHT) { - x += rect.getWidth(); - } - - if (anchor == ANCHOR_LEFT || anchor == ANCHOR_CENTER || anchor == ANCHOR_RIGHT) { - y += rect.getHeight() / 2; - } else if (anchor == ANCHOR_BOTTOMLEFT || anchor == ANCHOR_BOTTOM || anchor == ANCHOR_BOTTOMRIGHT) { - y += rect.getHeight(); - } - - setLocation(new Point((int) x, (int) y)); - } - } - - /* - * (non-Javadoc) - * @see - * com.bbn.openmap.omGraphics.OMLabeler#setLocation(java.awt.geom.Point2D) - */ - public void setLocation(Point2D p) { - polyBounds = null; - setX((int) p.getX()); - setY((int) p.getY()); - setMapLocation(p); - polyBounds = computeBounds(null); - setNeedToRegenerate(false); - } - - /* - * (non-Javadoc) - * @see com.bbn.openmap.omGraphics.OMLabeler#setLocation(int[][], int[][]) - */ - public void setLocation(int[] xpoints, int[] ypoints) { - setLocation(getCenter(xpoints, ypoints)); - } - - /** - * Calculate the projected area of the poly. Algorithm used is from some - * australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - protected static double calculateProjectedArea(int[] xpts, int[] ypts) { - int j = 0; - double area = 0.0; - - int npoints = xpts.length; - - for (int i = 0; i < npoints; ++i) { - j = (i + 1) % npoints; - area += xpts[i] * ypts[j]; - area -= ypts[i] * xpts[j]; - } - - return area / 2.0; - } - - /** - * Get the calculated center where the label string is drawn. Algorithm used - * is from some australian astronomy website =) - * http://astronomy.swin.edu.au/~pbourke/geometry/polyarea - */ - protected static Point getCenter(int[] xpts, int[] ypts) { - - int npoints = xpts.length; - if (npoints == 1) { - Point center = new Point(xpts[0], ypts[0]); - return center; - } - if (npoints == 2) { - // rmcneil - two points, A=0, div zero below - int x; - if (xpts[1] > xpts[0]) - x = xpts[0] + ((xpts[1] - xpts[0]) / 2); - else - x = xpts[1] + ((xpts[0] - xpts[1]) / 2); - int y; - if (ypts[1] > ypts[0]) - y = ypts[0] + ((ypts[1] - ypts[0]) / 2); - else - y = ypts[1] + ((ypts[0] - ypts[1]) / 2); - Point center = new Point(x, y); - return center; - } - - double factor = 0; - double cx = 0.0f; - double cy = 0.0f; - - for (int i = 0; i < npoints; ++i) { - int j = (i + 1) % npoints; - - factor = xpts[i] * ypts[j] - xpts[j] * ypts[i]; - cx += (xpts[i] + xpts[j]) * factor; - cy += (ypts[i] + ypts[j]) * factor; - } - - double A = calculateProjectedArea(xpts, ypts); - A *= 6.0; - factor = 1.0 / A; - - // bbenyo: take the absolute value cause I was getting - // negative values - // for polys with all positive vertices - // cx = Math.abs(cx * factor); - // cy = Math.abs(cy * factor); - - // DFD and RS - let the area calculation return negative - // values, and don't do this absolute value calculation. - // Negative values get returned when the points are - // counterclockwise, indicating holes. We may want labels - // offscreen however, and the abs pushes them onscreen. - - cx *= factor; - cy *= factor; - - Point center = new Point((int) Math.round(cx), (int) Math.round(cy)); - return center; - } - - public int getAnchor() { - return anchor; - } - - public void setAnchor(int anchor) { - this.anchor = anchor; - } - - public void restore(OMGeometry source) { - super.restore(source); - if (source instanceof OMTextLabeler) { - OMTextLabeler labeler = (OMTextLabeler) source; - this.anchor = labeler.anchor; - } - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/OMWarpingImage.java b/src/openmap/com/bbn/openmap/omGraphics/OMWarpingImage.java deleted file mode 100644 index a9f58a277..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/OMWarpingImage.java +++ /dev/null @@ -1,343 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: MissionHandler.java,v $ -//$Revision: 1.10 $ -//$Date: 2004/10/21 20:08:31 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.omGraphics; - -import java.awt.Graphics; -import java.awt.image.BufferedImage; -import java.net.MalformedURLException; -import java.net.URL; - -import com.bbn.openmap.dataAccess.image.WorldFile; -import com.bbn.openmap.image.BufferedImageHelper; -import com.bbn.openmap.omGraphics.util.ImageWarp; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.util.DataBounds; -import com.bbn.openmap.util.PropUtils; - -/** - * An OMGraphic that wraps an ImageWarp object to display the resulting - * OMRaster, in any projection. For use as a background object, doesn't react to - * mouse events, distance queries, etc. - * - *
- * try {
- *     String imageFile = "/data/geoimages/NBenguela.2004357.aqua.250m.jpg";
- *     WorldFile worldFile = WorldFile.get(PropUtils.getResourceOrFileOrURL(imageFile));
- *     OMWarpingImage omwi = new OMWarpingImage(imageFile, LatLonGCT.INSTANCE, worldFile);
- *     omList.add(omwi);
- * } catch (MalformedURLException e) {
- *     e.printStackTrace();
- * } catch (InterruptedException e) {
- *     e.printStackTrace();
- * }
- * 
- * try {
- *     String imageFile = "/data/images/earthmap4k.jpg";
- *     OMWarpingImage omwi = new OMWarpingImage(imageFile);
- *     omList.add(omwi);
- * } catch (MalformedURLException e) {
- *     e.printStackTrace();
- * } catch (InterruptedException e) {
- *     e.printStackTrace();
- * }
- * 
- * 
- * - * @author dietrick - */ -public class OMWarpingImage extends OMGraphicAdapter implements OMGraphic { - - private static final long serialVersionUID = 1L; - protected ImageWarp warp; - protected OMRaster raster; - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath) throws MalformedURLException, InterruptedException { - setWarp(imagePath, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath, GeoCoordTransformation transform, DataBounds imageBounds) - throws MalformedURLException, InterruptedException { - setWarp(imagePath, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from path to image (resource, file or URL). - * - * @param imagePath - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - * @throws MalformedURLException - * @throws InterruptedException - */ - public OMWarpingImage(String imagePath, GeoCoordTransformation transform, WorldFile worldfile) - throws MalformedURLException, InterruptedException { - setWarp(imagePath, transform, worldfile); - } - - /** - * Takes an image, assumed to be a world image in the LLXY projection (equal - * arc) covering -180, 180 longitude to -90, 90 latitude. - * - * @param bi - */ - public OMWarpingImage(BufferedImage bi) { - setWarp(bi, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param bi a BufferedImage - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - */ - public OMWarpingImage(BufferedImage bi, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(bi, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param bi BufferedImage - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - */ - public OMWarpingImage(BufferedImage bi, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(bi, transform, worldfile); - } - - /** - * Takes an array of ARGB integer values representing an image, assumed to - * be a world image in the LLXY projection (equal arc) covering -180, 180 - * longitude to -90, 90 latitude. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - */ - public OMWarpingImage(int[] pix, int width, int height) { - setWarp(pix, width, height, LatLonGCT.INSTANCE, new DataBounds(-180, -90, 180, 90)); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform the transform describing the image's projection. - * @param imageBounds the bounds of the image, in its coordinate system. - */ - public OMWarpingImage(int[] pix, int width, int height, GeoCoordTransformation transform, - DataBounds imageBounds) { - setWarp(pix, width, height, transform, imageBounds); - } - - /** - * Create an OMWarpingImage from a BufferedImage. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform transform the transform describing the image's - * projection. - * @param worldfile The WorldFile describing the image's location. - */ - public OMWarpingImage(int[] pix, int width, int height, GeoCoordTransformation transform, - WorldFile worldfile) { - setWarp(pix, width, height, transform, worldfile); - } - - /** - * Create an OMWarpingImage from an OMScalingRaster - useful for when the - * projection being used on the map doesn't match the projection of the - * raster, and it needs to be transformed. - * - * @param omsr OMScalingRaster - * @param transform a GeoCoordTransform if the OMScalingRaster image isn't a - * WGS84 image. - */ - public OMWarpingImage(OMScalingRaster omsr, GeoCoordTransformation transform) { - if (omsr != null) { - ImageWarp iw = omsr.getImageWarp(transform); - if (iw != null) { - setWarp(iw); - } - } - } - - /** - * Set all the information needed. - * - * @param imagePath - * @param transform - * @param imageBounds - * @throws MalformedURLException - * @throws InterruptedException - */ - public void setWarp(String imagePath, GeoCoordTransformation transform, DataBounds imageBounds) - throws MalformedURLException, InterruptedException { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - setWarp(new ImageWarp(bi, transform, imageBounds)); - } - - public void setWarp(String imagePath, GeoCoordTransformation transform, WorldFile worldfile) - throws MalformedURLException, InterruptedException { - URL imageURL = PropUtils.getResourceOrFileOrURL(imagePath); - BufferedImage bi = BufferedImageHelper.getBufferedImage(imageURL); - setWarp(new ImageWarp(bi, transform, worldfile)); - } - - /** - * Set all the information needed. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform - * @param imageBounds - */ - public void setWarp(int[] pix, int width, int height, GeoCoordTransformation transform, - DataBounds imageBounds) { - setWarp(new ImageWarp(pix, width, height, transform, imageBounds)); - } - - /** - * Set all the information needed. - * - * @param pix int[] ARGB pixel array for image - * @param width pixel width of image - * @param height pixel height of image - * @param transform - * @param worldfile describes projection of image - */ - public void setWarp(int[] pix, int width, int height, GeoCoordTransformation transform, - WorldFile worldfile) { - setWarp(new ImageWarp(pix, width, height, transform, worldfile)); - } - - public void setWarp(BufferedImage bi, GeoCoordTransformation transform, DataBounds imageBounds) { - setWarp(new ImageWarp(bi, transform, imageBounds)); - } - - public void setWarp(BufferedImage bi, GeoCoordTransformation transform, WorldFile worldfile) { - setWarp(new ImageWarp(bi, transform, worldfile)); - } - - public void setWarp(ImageWarp wrp) { - warp = wrp; - setNeedToRegenerate(true); - } - - public ImageWarp getWarp() { - return warp; - } - - @Override - public boolean generate(Projection proj) { - if (warp != null) { - if (updateImageForProjection(proj) || raster == null) { - raster = warp.getOMRaster(proj); - DrawingAttributes.sTransfer(this, raster); - } - } - - setNeedToRegenerate(false); - return true; - } - - protected Projection lastProjection = null; - - /** - * Called from within generate. Some render buffering calls generate to make - * sure the latest projection is called on an OMGraphic before it's put into - * a buffer. We're keeping track of the last projection used to generate the - * warped image, and if it's the same, don't bother regenerating, use the - * raster we have. - * - * @param proj current projection. - * @return false if the rest of generate() should be skipped. - */ - protected boolean updateImageForProjection(Projection proj) { - boolean ret = proj.equals(lastProjection); - lastProjection = proj; - return !ret; - } - - @Override - public void render(Graphics g) { - if (raster != null && isRenderable(raster.getShape())) { - raster.setSelected(isSelected()); - raster.setMatted(isMatted()); - raster.render(g); - } - } - - @Override - public float distance(double x, double y) { - if (raster != null) { - return raster.distance(x, y); - } - return super.distance(x, y); - } - - @Override - public float distanceToEdge(double x, double y) { - if (raster != null) { - return raster.distanceToEdge(x, y); - } - return super.distanceToEdge(x, y); - } - - @Override - public boolean contains(double x, double y) { - if (raster != null) { - return raster.contains(x, y); - } - return super.contains(x, y); - } - -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java b/src/openmap/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java deleted file mode 100644 index 060776aaf..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/awt/ShapeDecoration.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.bbn.openmap.omGraphics.awt; - -import java.awt.Graphics; -import java.awt.geom.Point2D; - -/** - * A ShapeDecoration is a basic element to be drawn along a path by a - * ShapeDecorator. The decoration length is measured along the path to decorate, - * the width, on a normal to the path. The decoration may be on the left or on - * the right of the path. - * - * - * @author Eric LEPICIER - * @version 26 juil. 2002 - */ -public interface ShapeDecoration extends Revertable { - - /** - * The right orientation constant - */ - public static final int RIGHT = 1; - /** - * The left orientation constant - */ - public static final int LEFT = 2; - - /** - * Returns the length. - * - * @return float - */ - public float getLength(); - - /** - * Returns the width. - * - * @return float - */ - public float getWidth(); - - /** - * Returns the orientation. - * - * @return int - */ - public int getOrientation(); - - /** - * Sets the orientation. - * - * @param orientation The orientation to set - */ - public void setOrientation(int orientation); - - /** - * reverts the orientation - */ - public void revert(); - - /** - * Draws itself along the specified polyline Called by - * ShapeDecorator - * - * @see com.bbn.openmap.omGraphics.awt.ShapeDecorator#draw(Graphics, Point2D[]) - * @param g - * @param points the polyline - * @param complete true if the polyline length equals the - * decoration length - */ - public void draw(Graphics g, Point2D[] points, boolean complete); -} - diff --git a/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java b/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java deleted file mode 100644 index e2cb50f96..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java +++ /dev/null @@ -1,948 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/event/StandardMapMouseInterpreter.java,v $ -// $RCSfile: StandardMapMouseInterpreter.java,v $ -// $Revision: 1.18 $ -// $Date: 2007/10/01 21:43:38 $ -// $Author: epgordon $ -// -// ********************************************************************** - -package com.bbn.openmap.omGraphics.event; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.util.List; - -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.ToolTipManager; - -import com.bbn.openmap.event.MapMouseEvent; -import com.bbn.openmap.layer.OMGraphicHandlerLayer; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.util.Debug; - -/** - * The StandardMapMouseInterpreter is a basic implementation of the - * MapMouseInterpreter, working with an OMGraphicHandlerLayer to handle - * MouseEvents on it. This class allows the OMGraphicHandlerLayer, which - * implements the GestureResponsePolicy, to not have to deal with MouseEvents - * and the OMGraphicList, but to just react to the meanings of the user's - * gestures. - *

- * - * The StandardMapMouseInterpreter uses highlighting to indicate that mouse - * movement is occurring over an OMGraphic, and gives the layer three ways to - * react to that movement. After finding out if the OMGraphic is highlightable, - * the SMMI will tell the layer to highlight the OMGraphic (which usually means - * to call select() on it), provide a tool tip string for the OMGraphic, and - * provide a string to use on the InformationDelegator info line. The layer can - * reply or ignore any and all of these notifications, depending on how it's - * supposed to act. - *

- * - * For left mouse clicks, the SMMI uses selection as a notification that the - * user is choosing an OMGraphic, and that the OMGraphic should be prepared to - * be moved, modified or deleted. For a single OMGraphic, this is usually - * handled by handing the OMGraphic off to the OMDrawingTool. However the - * GestureResponsPolicy handles the situation where the selection is of multiple - * OMGraphics, and the layer should prepare to handle those situations as - * movement or deletion notifications. This usually means to change the - * OMGraphic's display to indicate that the OMGraphics have been selected. - * Selection notifications can come in series, and the GestureResponsePolicy is - * expected to keep track of which OMGraphics it has been told are selected. - * Deselection notifications may come as well, or other action notifications - * such as cut or copy may arrive. For cut and copy notifications, the - * OMGraphics should be removed from any selection list. For pastings, the - * OMGraphics should be added to the selection list. - *

- * - * For right mouse clicks, the layer will be provided with a JPopupMenu to use - * to populate with options for actions over a OMGraphic or over the map. - *

- * - * The StandardMapMouseInterpreter uses a timer to pace how mouse movement - * actions are responded to. Highlight reactions only occur after the mouse has - * paused over the map for the timer interval, so the application doesn't try to - * respond to constantly changing mouse locations. You can disable this delay by - * setting the timer interval to zero. - */ -public class StandardMapMouseInterpreter - implements MapMouseInterpreter { - - protected boolean DEBUG = false; - protected OMGraphicHandlerLayer layer = null; - protected String[] mouseModeServiceList = null; - protected String lastToolTip = null; - protected GestureResponsePolicy grp = null; - protected GeometryOfInterest clickInterest = null; - protected GeometryOfInterest movementInterest = null; - protected boolean consumeEvents = false; - - protected boolean active = true; - - /** - * The OMGraphicLayer should be set at some point before use. - */ - public StandardMapMouseInterpreter() { - DEBUG = Debug.debugging("grp"); - } - - /** - * The standard constructor. - */ - public StandardMapMouseInterpreter(OMGraphicHandlerLayer l) { - this(); - setLayer(l); - } - - /** - * Helper class used to keep track of OMGraphics of interest. Interest means - * that a MouseEvent that occurred over an OMGraphic that combined with - * another MouseEvent, may be interpreted as a significant event. - */ - public class GeometryOfInterest { - OMGraphic omg; - int button; - boolean leftButton; - - /** - * Create a Geometry of Interest with the OMGraphic and the first mouse - * event. - */ - public GeometryOfInterest(OMGraphic geom, MouseEvent me) { - omg = geom; - button = getButton(me); - leftButton = isLeftMouseButton(me); - } - - /** - * A check to see if an OMGraphic is the same as the one of interest. - */ - public boolean appliesTo(OMGraphic geom) { - return (geom != null && geom.equals(omg)); - } - - /** - * A check to see if a mouse event that is occurring over an OMGraphic - * is infact occurring over the one of interest, and with the same mouse - * button. - */ - public boolean appliesTo(OMGraphic geom, MouseEvent me) { - return (geom != null && geom.equals(omg) && sameButton(me)); - } - - /** - * A check to see if the current mouse event concerns the same mouse - * button as the original. - */ - public boolean sameButton(MouseEvent me) { - return button == getButton(me); - } - - /** - * Return the OMGraphic of interest. - */ - public OMGraphic getGeometry() { - return omg; - } - - /** - * Return the button that caused the interest. - */ - public int getButton() { - return button; - } - - /** - * Utility method to get around MouseEvent.getButton 1.4 requirement. - */ - protected int getButton(MouseEvent me) { - // jdk 1.4 version - // return me.getButton(); - - // jdk 1.3 version Don't know if the numbers are the same - // as in me.getButton, shouldn't make a difference. - if (me.isControlDown() /* PopupTrigger() */ - || SwingUtilities.isRightMouseButton(me)) { - return 1; - } else if (SwingUtilities.isLeftMouseButton(me)) { - return 0; - } else { - return 2; - } - } - - /** - * Return if the current button is the left one. - */ - public boolean isLeftButton() { - return leftButton; - } - - /** - * Called when the popup trigger is known to have been triggered and a - * click interest has been set by it. - * - * @param b - */ - public void setLeftButton(boolean b) { - leftButton = b; - } - } - - /** - * A flag to tell the interpreter to be selfish about consuming MouseEvents - * it receives. If set to true, it will consume events so that other - * MapMouseListeners will not receive the events. If false, lower layers - * will also receive events, which will let them react too. Intended to let - * other layers provide information about what the mouse is over when - * editing is occurring. - */ - public void setConsumeEvents(boolean consume) { - consumeEvents = consume; - } - - public boolean getConsumeEvents() { - return consumeEvents; - } - - public void setLayer(OMGraphicHandlerLayer l) { - layer = l; - } - - public OMGraphicHandlerLayer getLayer() { - return layer; - } - - /** - * Set the ID's of the mouse modes that this interpreter should be listening - * to. If set to null, this SMMI won't receive MouseEvents. - */ - public void setMouseModeServiceList(String[] list) { - mouseModeServiceList = list; - } - - /** - * A method to set how a left mouse button is interpreted. We count - * control-clicks as not a left mouse click. - */ - public boolean isLeftMouseButton(MouseEvent me) { - return SwingUtilities.isLeftMouseButton(me); - } - - /** - * Return a list of the modes that are interesting to the MapMouseListener. - * You MUST override this with the modes you're interested in, or set the - * mouse mode service list, or you won't receive mouse events. - */ - public String[] getMouseModeServiceList() { - return mouseModeServiceList; - } - - /** - * Set the GeometryOfInterest as one that could possibly be in the process - * of being clicked upon. - */ - protected void setClickInterest(GeometryOfInterest goi) { - clickInterest = goi; - } - - /** - * Get the GeometryOfInterest as one that could possibly be in the process - * of being clicked upon. - */ - protected GeometryOfInterest getClickInterest() { - return clickInterest; - } - - /** - * Set the GeometryOfInterest for something that the mouse is over. Prevents - * excessive modifications of the GUI if this remains constant. - */ - protected void setMovementInterest(GeometryOfInterest goi) { - movementInterest = goi; - } - - /** - * Get the GeometryOfInterest for something that the mouse is over. Prevents - * excessive modifications of the GUI if this remains constant. - */ - protected GeometryOfInterest getMovementInterest() { - return movementInterest; - } - - /** - * Return the OMGraphic object that is under a mouse event occurrence on the - * map, null if nothing applies. - */ - public OMGraphic getGeometryUnder(MouseEvent me) { - OMGraphic omg = null; - OMGraphicList list = null; - if (layer != null) { - list = layer.getList(); - if (list != null) { - int x = me.getX(); - int y = me.getY(); - if (me instanceof MapMouseEvent) { - Point2D pnt = ((MapMouseEvent) me).getProjectedLocation(); - x = (int) pnt.getX(); - y = (int) pnt.getY(); - } - - omg = list.findClosest(x, y, 4); - } else { - if (DEBUG) { - Debug.output("SMMI: no layer to evaluate mouse event"); - } - } - } else { - if (DEBUG) { - Debug.output("SMMI: no layer to evaluate mouse event"); - } - } - - return omg; - } - - // Mouse Listener events - // ////////////////////// - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e MouseEvent - * @return false if nothing was pressed over, or the consumeEvents setting - * if something was. - */ - public boolean mousePressed(MouseEvent e) { - if (DEBUG) { - Debug.output("SMMI:mousePressed()"); - } - return setClickInterestFromMouseEvent(e); - } - - /** - * Set the GeometryOfInterest based on MouseEvent. The default behavior of - * mousePressed. - * - * @param e MouseEvent - * @return whether mouse event was consumed. - */ - protected boolean setClickInterestFromMouseEvent(MouseEvent e) { - if (!active) { - return false; - } - - if (DEBUG) { - Debug.output("SMMI: setClickInterestFromMouseEvent()"); - } - setCurrentMouseEvent(e); - boolean ret = false; - - GeometryOfInterest goi = getClickInterest(); - OMGraphic omg = getGeometryUnder(e); - - if (goi != null && !goi.appliesTo(omg, e)) { - // If the click doesn't match the geometry or button - // of the geometry of interest, need to tell the goi - // that is was clicked off, and set goi to null. - if (goi.isLeftButton()) { - leftClickOff(goi.getGeometry(), e); - } else { - rightClickOff(goi.getGeometry(), e); - } - setClickInterest(null); - } - - if (omg != null) { - setClickInterest(new GeometryOfInterest(omg, e)); - } - - ret = testForAndHandlePopupTrigger(e); - - if (omg != null && !ret) { - select(omg); - ret = true; - } - - return ret && consumeEvents; - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e MouseEvent - * @return false - */ - public boolean mouseReleased(MouseEvent e) { - if (!active) { - return false; - } - - setCurrentMouseEvent(e); - return testForAndHandlePopupTrigger(e) && consumeEvents; - } - - /** - * Tests the MouseEvent to see if it's a popup trigger, and calls rightClick - * appropriately if there is an OMGraphic involved. - * - * @param e MouseEvent - * @return true if the MouseEvent is a popup trigger and has been consumed. - */ - public boolean testForAndHandlePopupTrigger(MouseEvent e) { - boolean ret = false; - if (e.isPopupTrigger()) { - GeometryOfInterest goi = getClickInterest(); - // If there is a click interest - if (goi != null) { - // Tell the policy it an OMGraphic was clicked. - goi.setLeftButton(false); - ret = rightClick(goi.getGeometry(), e); - } else { - ret = rightClick(e); - } - } - return ret; - } - - /** - * Invoked when the mouse has been clicked. Notifies the left click methods - * for the applicable OMGraphic or the map. Right click methods are handled - * when the testForAndHandlePopupTrigger method is called in mousePressed - * and mouseReleased. - * - * @param e MouseEvent - * @return the consumeEvents setting. - */ - public boolean mouseClicked(MouseEvent e) { - if (!active) { - return false; - } - - // Should have been done already from the MousePressed, but different - // OS Java implementations have the pressed occur after click. Gah! - setClickInterestFromMouseEvent(e); - - if (isLeftMouseButton(e)) { - GeometryOfInterest goi = getClickInterest(); - // If there is a click interest - if (goi != null) { - // Tell the policy it an OMGraphic was clicked. - if (goi.isLeftButton()) { - leftClick(goi.getGeometry(), e); - } else { - rightClick(goi.getGeometry(), e); - } - } else { - leftClick(e); - } - - return consumeEvents; - } - - return false; - } - - /** - * Invoked when the mouse enters a component. - * - * @param e MouseEvent - */ - public void mouseEntered(MouseEvent e) { - if (!active) { - return; - } - setCurrentMouseEvent(e); - } - - /** - * Invoked when the mouse exits a component. - * - * @param e MouseEvent - */ - public void mouseExited(MouseEvent e) { - if (!active) { - return; - } - setCurrentMouseEvent(e); - } - - // Mouse Motion Listener events - // ///////////////////////////// - - /** - * Invoked when a mouse button has been pressed and is moving. Resets the - * click geometry of interest to null. - * - * @param e MouseEvent - * @return the result from mouseMoved (also called from this method) - * combined with the consumeEvents setting. - */ - public boolean mouseDragged(MouseEvent e) { - if (!active) { - return false; - } - setCurrentMouseEvent(e); - GeometryOfInterest goi = getClickInterest(); - if (goi != null) { - setClickInterest(null); - } - - return mouseMoved(e) && consumeEvents; - } - - /** - * Invoked when the mouse has been moved. Sets the movement geometry of - * interest and updates the movement timer. - * - * @param e MouseEvent - * @return the result of updateMouseMoved() if the timer isn't being used, - * or false. - */ - public boolean mouseMoved(MouseEvent e) { - if (!active) { - return false; - } - setCurrentMouseEvent(e); - - if (getMovementInterest() == null || noTimerOverOMGraphic || mouseTimerInterval <= 0) { - return updateMouseMoved(e); - } else { - if (mouseTimer == null) { - mouseTimer = new Timer(mouseTimerInterval, mouseTimerListener); - mouseTimer.setRepeats(false); - } - - mouseTimerListener.setEvent(e); - mouseTimer.restart(); - return false; - } - } - - protected boolean noTimerOverOMGraphic = true; - - /** - * Set whether to ignore the timer when movement is occurring over an - * OMGraphic. Sometimes unhighlight can be inappropriately delayed when - * timer is enabled. - */ - public void setNoTimerOverOMGraphic(boolean val) { - noTimerOverOMGraphic = val; - } - - /** - * Get whether the timer should be ignored when movement is occurring over - * an OMGraphic. - */ - public boolean getNoTimerOverOMGraphic() { - return noTimerOverOMGraphic; - } - - /** - * The wait interval before a mouse over event gets triggered. - */ - protected int mouseTimerInterval = 150; - - /** - * Set the time interval that the mouse timer waits before calling - * upateMouseMoved. A negative number or zero will disable the timer. - */ - public void setMouseTimerInterval(int interval) { - mouseTimerInterval = interval; - } - - public int getMouseTimerInterval() { - return mouseTimerInterval; - } - - /** - * The timer used to track the wait interval. - */ - protected Timer mouseTimer = null; - - /** - * The timer listener that calls updateMouseMoved. - */ - protected MouseTimerListener mouseTimerListener = new MouseTimerListener(); - - /** - * The definition of the listener that calls updateMouseMoved when the timer - * goes off. - */ - protected class MouseTimerListener - implements ActionListener { - - private MouseEvent event; - - public synchronized void setEvent(MouseEvent e) { - event = e; - } - - public synchronized void actionPerformed(ActionEvent ae) { - if (event != null) { - updateMouseMoved(event); - } - } - } - - /** - * The real mouseMoved call, called when mouseMoved is called and, if there - * is a mouse timer interval set, that interval time has passed. - * - * @return the consumeEvents setting of the mouse event concerns an - * OMGraphic, false if it didn't. - */ - protected boolean updateMouseMoved(MouseEvent e) { - boolean ret = false; - OMGraphic omg = getGeometryUnder(e); - GeometryOfInterest goi = getMovementInterest(); - - boolean mouseOverCurrentGOI = (goi != null && goi.appliesTo(omg)); - - if (goi != null && !mouseOverCurrentGOI) { - // We already had a GOI from preious event, but it's not under the event now... - mouseNotOver(goi.getGeometry()); - setMovementInterest(null); - } else { - ret = (goi != null); - } - - if (omg != null) { - // Mouse over OMGraphic - if (!mouseOverCurrentGOI) { - // We get in here if the GOI should be changed to a new OMGraphic. - setMovementInterest(new GeometryOfInterest(omg, e)); - - // Add a specialized check for OMPoint because it shouldn't have a delayed unhighlight. - setNoTimerOverOMGraphic(!omg.shouldRenderFill() || omg instanceof OMPoint); - ret = mouseOver(omg, e); - } - } else { - // Current mouse event not over an OMGraphic - ret = mouseOver(e); - } - - ret = ret && consumeEvents; - - if (ret) { - e.consume(); - } - - return ret; - } - - /** - * Handle notification that another layer consumed a mouse moved event. Sets - * movement interest to null. - */ - public void mouseMoved() { - if (!active) { - return; - } - GeometryOfInterest goi = getMovementInterest(); - if (goi != null) { - mouseNotOver(goi.getGeometry()); - setMovementInterest(null); - } - } - - /** - * Handle a left-click on the map. Does nothing by default. - * - * @return false - */ - public boolean leftClick(MouseEvent me) { - if (DEBUG) { - Debug.output("leftClick(MAP) at " + me.getX() + ", " + me.getY()); - } - - if (grp != null && grp.receivesMapEvents() && me instanceof MapMouseEvent) { - return grp.leftClick((MapMouseEvent) me); - } - - return false; - } - - /** - * Handle a left-click on an OMGraphic. Does nothing by default. - * - * @return true - */ - public boolean leftClick(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("leftClick(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - return false; - } - - /** - * Notification that the user clicked on something else other than the - * provided OMGraphic that was previously left-clicked on. Calls - * deselect(omg). - * - * @return false - */ - public boolean leftClickOff(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("leftClickOff(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - deselect(omg); - - return false; - } - - /** - * Notification that the map was right-clicked on. - * - * @return false - */ - public boolean rightClick(MouseEvent me) { - if (DEBUG) { - Debug.output("rightClick(MAP) at " + me.getX() + ", " + me.getY()); - } - - if (me instanceof MapMouseEvent && grp != null) { - return displayPopup(grp.getItemsForMapMenu((MapMouseEvent) me), me); - } - - return false; - } - - /** - * Notification that an OMGraphic was right-clicked on. - * - * @return true - */ - public boolean rightClick(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("rightClick(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - if (grp != null) { - return displayPopup(grp.getItemsForOMGraphicMenu(omg), me); - } - - return false; - } - - /** - * Create a pop-up menu from GRP requests, over the mouse event location. - * - * @return true if pop-up was presented, false if not. - */ - protected boolean displayPopup(List contents, MouseEvent me) { - if (DEBUG) { - Debug.output("displayPopup(" + contents + ") " + me); - } - if (contents != null && !contents.isEmpty()) { - JPopupMenu jpm = new JPopupMenu(); - for (Component comp : contents) { - jpm.add(comp); - } - jpm.show((Component) me.getSource(), me.getX(), me.getY()); - return true; - } - return false; - } - - /** - * Notification that the user clicked on something else other than the - * provided OMGraphic that was previously right-clicked on. - * - * @return false - */ - public boolean rightClickOff(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("rightClickOff(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - return false; - } - - /** - * Notification that the mouse is not over an OMGraphic, but over the map at - * some location. - * - * @return false - */ - public boolean mouseOver(MouseEvent me) { - if (DEBUG) { - Debug.output("mouseOver(MAP) at " + me.getX() + ", " + me.getY()); - } - if (grp != null && grp.receivesMapEvents() && me instanceof MapMouseEvent) { - return grp.mouseOver((MapMouseEvent) me); - } - - return false; - } - - /** - * Notification that the mouse is over an OMGraphic. Makes all the highlight - * calls. - * - * @return true - */ - public boolean mouseOver(OMGraphic omg, MouseEvent me) { - if (DEBUG) { - Debug.output("mouseOver(" + omg.getClass().getName() + ") at " + me.getX() + ", " + me.getY()); - } - - if (grp != null && !me.isConsumed()) { - handleToolTip(grp.getToolTipTextFor(omg), me); - handleInfoLine(grp.getInfoText(omg)); - if (grp.isHighlightable(omg)) { - grp.highlight(omg); - } - } - return true; - } - - /** - * Given a tool tip String, use the layer to get it displayed. - */ - protected void handleToolTip(String tip, MouseEvent me) { - if (lastToolTip != null && lastToolTip.equals(tip)) { - return; - } - lastToolTip = tip; - if (layer != null) { - if (lastToolTip != null && lastToolTip.trim().length() > 0) { - layer.fireRequestToolTip(lastToolTip); - // forward the event to the tool tip manager so it will popup - // the tool tip right away, otherwise an additional event is - // required to trigger it - ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); - toolTipManager.mouseMoved(me); - } else { - layer.fireHideToolTip(); - } - } - } - - /** - * Given an information line, use the layer to get it displayed on the - * InformationDelegator. - */ - protected void handleInfoLine(String line) { - if (layer != null) { - layer.fireRequestInfoLine((line == null) ? "" : line); - } - } - - /** - * Notification that the mouse has moved off of an OMGraphic. - */ - public boolean mouseNotOver(OMGraphic omg) { - if (DEBUG) { - Debug.output("mouseNotOver(" + omg.getClass().getName() + ")"); - } - - if (grp != null) { - grp.unhighlight(omg); - } - handleToolTip(null, null); - handleInfoLine(null); - return false; - } - - /** - * Notify the GRP that the OMGraphic has been selected. Wraps the OMGraphic - * in an OMGraphicList. - */ - public void select(OMGraphic omg) { - if (grp != null && grp.isSelectable(omg)) { - OMGraphicList omgl = new OMGraphicList(); - omgl.add(omg); - grp.select(omgl); - } - } - - /** - * Notify the GRP that the OMGraphic has been deselected. Wraps the - * OMGraphic in an OMGraphicList. - */ - public void deselect(OMGraphic omg) { - if (grp != null && grp.isSelectable(omg)) { - OMGraphicList omgl = new OMGraphicList(); - omgl.add(omg); - grp.deselect(omgl); - } - } - - /** - * The last MouseEvent received, for later reference. - */ - protected MouseEvent currentMouseEvent; - - /** - * Set the last MouseEvent received. - */ - protected void setCurrentMouseEvent(MouseEvent me) { - currentMouseEvent = me; - } - - /** - * Get the last MouseEvent received. - */ - public MouseEvent getCurrentMouseEvent() { - return currentMouseEvent; - } - - /** - * Set the GestureResponsePolicy to notify of the mouse actions over the - * layer's OMGraphicList. - */ - public void setGRP(GestureResponsePolicy grp) { - this.grp = grp; - } - - /** - * Get the GestureResponsePolicy that is being notified of the mouse actions - * over the layer's OMGraphicList. - */ - public GestureResponsePolicy getGRP() { - return grp; - } - - /** - * Check whether the MapMouseInterpreter is responding to events. - * - * @return true if willing to respond to MouseEvents. - */ - public boolean isActive() { - return active; - } - - /** - * Set whether the MapMouseInterpreter responds - * - * @param active - */ - public void setActive(boolean active) { - this.active = active; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/omGraphics/rule/IndexRule.java b/src/openmap/com/bbn/openmap/omGraphics/rule/IndexRule.java deleted file mode 100644 index 5f889d6dc..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/rule/IndexRule.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Properties; - -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * A Rule is an attribute inspector that makes decisions about rendering - * attributes, information line contents, tooltips and visibility based on - * scale. - * - * @author dietrick - */ -public abstract class IndexRule extends Rule> { - /** - * The column index where the testing value can be found for the rule to - * compare against the value. - */ - protected int keyIndex = -1; - protected int[] tooltipIndicies; - protected int[] infolineIndicies; - protected int[] labelIndicies; - - /** - * A record List for the attributes of an OMGraphic might have a name for - * each entry. Given a name, provide the index into the List to get that - * attribute value. NOTE: This method will be overridden by subclasses that - * read data and create attribute data structures. - * - * @param columnName name of a attribute in a List, like a column name of a - * list of lists. - * @return the int index of the entry in the record List. - */ - public abstract int getRecordColumnIndexForName(String columnName); - - /** - * Provide the title of the attribute at a specific entry. NOTE: This method - * will be overridden by subclasses that read data and create attribute data - * structures. - * - * @param index into the record List. - * @return the record List name for that index. - */ - public abstract String getRecordColumnName(int index); - - /** - * Asks the Op class to evaluate the provided value against the Rules value. - * - * @param record list of objects to evaluate, the keyIndex will be used to - * fetch the appropriate object from the List. - * @return true of the operation passed - */ - public boolean evaluate(List record) { - Object recVal = record.get(keyIndex); - return op.evaluate(this.val, recVal); - } - - /** - * Returns a String of concatenated record values. This method will work, - * but another method can be called that takes indices that will save a - * lookup step. - * - * @param fieldNames name of columns - * @param record List to use for return value - * @return String of content - */ - public String getContent(List fieldNames, List record) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - int index = getRecordColumnIndexForName(field); - buf.append(PropUtils.unnull(record.get(index))).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String key = props.getProperty(prefix + RuleKeyProperty); - keyIndex = getRecordColumnIndexForName(key); - - tooltipIndicies = getIndicies(tooltipFields); - infolineIndicies = getIndicies(infolineFields); - labelIndicies = getIndicies(labelFields); - } - - /** - * Evaluate the record against this rule. - * - * @param record A List of attributes for a particular OMGraphic/map object. - * The indices for the rule are indexes into this record. - * @param omg The OMGraphic to evaluate. - * @param proj The current map projection. - * @return the OMGraphic if it should be drawn, null if it shouldn't. - */ - public OMGraphic evaluate(List record, OMGraphic omg, Projection proj) { - - if (evaluate(record)) { - - float scale = 0f; - - if (proj != null) { - scale = proj.getScale(); - - if (scale < displayMinScale || scale > displayMaxScale) { - // We met the rule, it's telling us not to display. - return null; - } - } - - if (infolineIndicies != null) { - omg.putAttribute(OMGraphicConstants.INFOLINE, getContentFromIndicies(infolineIndicies, record)); - } - if (tooltipIndicies != null) { - omg.putAttribute(OMGraphicConstants.TOOLTIP, getContentFromIndicies(tooltipIndicies, record)); - } - if (labelIndicies != null && scale >= labelMinScale && scale <= labelMaxScale) { - String curLabel = getContentFromIndicies(labelIndicies, record); - - OMTextLabeler label = new OMTextLabeler(curLabel, OMText.JUSTIFY_CENTER); - // Needs to get added to the OMGraphic so it gets - // generated with the projection at the right point. - omg.putAttribute(OMGraphicConstants.LABEL, label); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(omg); - } - omg.setVisible(drawingAttributes != null); - - return omg; - } - - return null; - } - - /** - * Returns a String of concatenated record values. - * - * @param indicies column indexes of values to be concatenated in return - * value - * @param record List to use for return value - * @return String of content - */ - public String getContentFromIndicies(int[] indicies, List record) { - int numIndicies = indicies.length; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < numIndicies; i++) { - int val = indicies[i]; - if (val != -1) { - buf.append((String) record.get(val)).append(" "); - } - } - return buf.toString().trim(); - } - - /** - * Given a prefix + ActionProperty, get the column names listed as the - * property value and figure out what the indexes of the columns are. - * - * @param fieldNames a List of Strings for property title - * @return int array of column indexes in the dbf file reflecting the order - * and number of column names listed as the property value. - */ - public int[] getIndicies(List fieldNames) { - int[] indicies = null; - if (fieldNames != null) { - int numCols = fieldNames.size(); - indicies = new int[numCols]; - int i = 0; - for (String columnName : fieldNames) { - indicies[i++] = getRecordColumnIndexForName(columnName); - } - } - - return indicies; - } - - /** - * Given a prefix + ActionProperty, get the column names listed as the - * property value and figure out what the indexes of the columns are. - * - * @param indicies int[] of column indexes in the dbf file reflecting the - * order and number of column names to be listed as a property - * value. - * @return String for use in properties of space-separated column names. - */ - public String getColumnNamesFromIndicies(int[] indicies) { - StringBuffer buf = new StringBuffer(); - int numCols = indicies.length; - for (int i = 0; i < numCols; i++) { - buf.append(getRecordColumnName(indicies[i])).append(" "); - } - - return buf.toString().trim(); - } - - public int[] getInfolineIndicies() { - return infolineIndicies; - } - - public void setInfolineIndicies(int[] infolineIndicies) { - this.infolineIndicies = infolineIndicies; - } - - public int getKeyIndex() { - return keyIndex; - } - - public void setKeyIndex(int keyIndex) { - this.keyIndex = keyIndex; - } - - public int[] getLabelIndicies() { - return labelIndicies; - } - - public void setLabelIndicies(int[] labelIndicies) { - this.labelIndicies = labelIndicies; - } - - public int[] getTooltipIndicies() { - return tooltipIndicies; - } - - public void setTooltipIndicies(int[] tooltipIndicies) { - this.tooltipIndicies = tooltipIndicies; - } -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/rule/MapRule.java b/src/openmap/com/bbn/openmap/omGraphics/rule/MapRule.java deleted file mode 100644 index 8f229886a..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/rule/MapRule.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.util.PropUtils; - -/** - * Implementation of Rule that uses a Map for attributes. - * - * @author dietrick - */ -public class MapRule extends Rule { - - /** - * Asks the Op class to evaluate the provided value against the Rules value. - * - * @param record - * @return true of the operation passed - */ - public boolean evaluate(Map record) { - Object recVal = record.get(keyField); - return op.evaluate(this.val, recVal); - } - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames column names - * @param record Map to use to fetch values - * @return String of content - */ - public String getContent(List fieldNames, Map record) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - buf.append(PropUtils.unnull(record.get(field))).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/rule/Rule.java b/src/openmap/com/bbn/openmap/omGraphics/rule/Rule.java deleted file mode 100644 index 3d1823220..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/rule/Rule.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.DrawingAttributes; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicConstants; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.Debug; -import com.bbn.openmap.util.PropUtils; - -/** - * A Rule is an attribute inspector that makes decisions about rendering - * attributes, information line contents, tooltips and visibility based on - * scale. - * - * @author dietrick - */ -public abstract class Rule extends OMComponent { - /** - * The property name where the testing value can be found for the rule to - * compare against the value. - */ - protected String keyField; - protected List tooltipFields; - protected List infolineFields; - protected List labelFields; - - /** - * The value that the query runs the operation against. - */ - protected Object val; - protected RuleOp op = RuleOp.NONE; - - protected DrawingAttributes drawingAttributes = new DrawingAttributes(); - - protected float displayMinScale = Float.MIN_VALUE; - protected float displayMaxScale = Float.MAX_VALUE; - protected float labelMinScale = Float.MIN_VALUE; - protected float labelMaxScale = Float.MAX_VALUE; - - /** - *

-     * layer.rules=rule1 rule2 rule3 
-     * layer.rule1.key=CAPITAL
-     * layer.rule1.op=equals
-     * layer.rule1.val=Y
-     * layer.rule1.actions=render tooltip infoline 
-     * layer.rule1.lineColor=FFFF0000
-     * layer.rule1.minScale=10000
-     * layer.rule1.maxScale=50000
-     * layer.rule1.infoline=CITY_NAME
-     * layer.rule1.tooltip=ELEVATION
-     * 
- */ - public final static String RuleListProperty = "rules"; - public final static String RuleKeyProperty = "key"; - public final static String RuleOperatorProperty = "op"; - public final static String RuleValueProperty = "val"; - - public final static String RuleActionRender = "render"; - public final static String RuleActionTooltip = "tooltip"; - public final static String RuleActionInfoline = "infoline"; - public final static String RuleActionLabel = "label"; - public final static String RuleActionMinScale = "minScale"; - public final static String RuleActionMaxScale = "maxScale"; - - /** - * Asks the Op class to evaluate the retrieved value against the Rules - * value. The implementation will use the key to pull the testing value out - * of the record. - * - * @param record object to evaluate - * @return true of the operation passed - */ - public abstract boolean evaluate(T record); - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames a list of string keys for fields to be used. - * @param record The record object to look up values for the list of keys. - * @return String of content - */ - public abstract String getContent(List fieldNames, T record); - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - keyField = props.getProperty(prefix + RuleKeyProperty, keyField); - tooltipFields = getStringFromFields(props.getProperty(prefix + RuleActionTooltip)); - infolineFields = getStringFromFields(props.getProperty(prefix + RuleActionInfoline)); - labelFields = getStringFromFields(props.getProperty(prefix + RuleActionLabel)); - - RuleOp op = RuleOp.resolve(props.getProperty(prefix + RuleOperatorProperty)); - if (op != null) { - this.op = op; - } - - Object newVal = props.getProperty(prefix + RuleValueProperty); - if (newVal != null) { - val = newVal; - } - - if (keyField == null) { - Debug.output("No key for rule (" + prefix + ") found in properties."); - } - - displayMinScale = PropUtils.floatFromProperties(props, prefix + RuleActionRender + "." - + RuleActionMinScale, displayMinScale); - displayMaxScale = PropUtils.floatFromProperties(props, prefix + RuleActionRender + "." - + RuleActionMaxScale, displayMaxScale); - labelMinScale = PropUtils.floatFromProperties(props, prefix + RuleActionLabel + "." - + RuleActionMinScale, labelMinScale); - labelMaxScale = PropUtils.floatFromProperties(props, prefix + RuleActionLabel + "." - + RuleActionMaxScale, labelMaxScale); - - // Assume that the OMGraphic will be rendered, with defaults if not - // specified. render has to be set to false to hide OMGraphic - boolean renderProperties = PropUtils.booleanFromProperties(props, prefix + RuleActionRender, drawingAttributes != null); - if (renderProperties) { - if (drawingAttributes == null) { - drawingAttributes = new DrawingAttributes(); - } - drawingAttributes.setProperties(prefix, props); - } else { - drawingAttributes = null; - } - - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - - String prefix = PropUtils.getScopedPropertyPrefix(this); - props.put(prefix + RuleKeyProperty, PropUtils.unnull(keyField)); - - if (tooltipFields != null && !tooltipFields.isEmpty()) { - props.put(prefix + RuleActionTooltip, getFieldsAsString(tooltipFields)); - } - if (infolineFields != null && !infolineFields.isEmpty()) { - props.put(prefix + RuleActionInfoline, getFieldsAsString(infolineFields)); - } - if (labelFields != null && !labelFields.isEmpty()) { - props.put(prefix + RuleActionLabel, getFieldsAsString(labelFields)); - } - - if (this.op != null) { - props.put(prefix + RuleOperatorProperty, this.op.getPropertyNotation()); - } - if (val != null) { - props.put(prefix + RuleValueProperty, PropUtils.unnull(val.toString())); - } - - if (displayMinScale != Float.MIN_VALUE) { - props.put(prefix + RuleActionRender + "." + RuleActionMinScale, Float.toString(displayMinScale)); - } - if (displayMaxScale != Float.MAX_VALUE) { - props.put(prefix + RuleActionRender + "." + RuleActionMaxScale, Float.toString(displayMaxScale)); - } - if (labelMinScale != Float.MIN_VALUE) { - props.put(prefix + RuleActionLabel + "." + RuleActionMinScale, Float.toString(labelMinScale)); - } - if (labelMaxScale != Float.MAX_VALUE) { - props.put(prefix + RuleActionLabel + "." + RuleActionMaxScale, Float.toString(labelMaxScale)); - } - - if (drawingAttributes != null) { - props.put(prefix + RuleActionRender, Boolean.toString(true)); - drawingAttributes.getProperties(props); - } - - return props; - } - - /** - * Evaluate the record against this rule. - * - * @param record A Map of attributes for a particular OMGraphic/map object. - * The indices for the rule are indexes into this record. - * @param omg The OMGraphic to evaluate. - * @param proj The current map projection. - * @return the OMGraphic if it should be drawn, null if it shouldn't. - */ - public OMGraphic evaluate(T record, OMGraphic omg, Projection proj) { - - if (evaluate(record)) { - - float scale = 0f; - - if (proj != null) { - scale = proj.getScale(); - - if (scale < displayMinScale || scale > displayMaxScale) { - // We met the rule, it's telling us not to display. - return null; - } - } - - if (infolineFields != null) { - omg.putAttribute(OMGraphicConstants.INFOLINE, getContent(infolineFields, record)); - } - if (tooltipFields != null) { - omg.putAttribute(OMGraphicConstants.TOOLTIP, getContent(tooltipFields, record)); - } - if (labelFields != null && scale >= labelMinScale && scale <= labelMaxScale) { - String curLabel = getContent(labelFields, record); - - OMTextLabeler label = new OMTextLabeler(curLabel, OMText.JUSTIFY_CENTER); - // Needs to get added to the OMGraphic so it gets - // generated with the projection at the right point. - omg.putAttribute(OMGraphicConstants.LABEL, label); - } - - if (drawingAttributes != null) { - drawingAttributes.setTo(omg); - } - omg.setVisible(drawingAttributes != null); - - if (getLogger().isLoggable(Level.FINE)) { - getLogger().fine(this.getPropertyPrefix() + " being assigned to " - + op.getClass().getName() + " " + keyField + " " + val + " vs " - + ((Map) record).get(keyField)); - - omg.putAttribute("RULE", getPropertyPrefix()); - } - - return omg; - } - - return null; - } - - /** - * Returns a String of concatenated record values. - * - * @param fieldNames names of field properties - * @return fields as single string - */ - public String getFieldsAsString(List fieldNames) { - StringBuffer buf = new StringBuffer(); - if (fieldNames != null) { - for (String field : fieldNames) { - buf.append(PropUtils.unnull(field)).append(" "); - } - } - // Might be more than just that last "" - return buf.toString().trim(); - } - - /** - * Create a List of Strings from a list of space separated strings. - * - * @param fieldString - * @return List if fieldString can be parsed, null if fieldString is null. - */ - public List getStringFromFields(String fieldString) { - if (fieldString != null && !fieldString.isEmpty()) { - return PropUtils.parseSpacedMarkers(fieldString); - } - return null; - } - - public DrawingAttributes getDrawingAttribtues() { - return drawingAttributes; - } - - public void setDrawingAttributes(DrawingAttributes da) { - this.drawingAttributes = da; - } - - public float getDisplayMaxScale() { - return displayMaxScale; - } - - public void setDisplayMaxScale(float displayMaxScale) { - this.displayMaxScale = displayMaxScale; - } - - public float getDisplayMinScale() { - return displayMinScale; - } - - public void setDisplayMinScale(float displayMinScale) { - this.displayMinScale = displayMinScale; - } - - public String getKeyName() { - return keyField; - } - - public void setKeyName(String keyName) { - this.keyField = keyName; - } - - public List getLabelFields() { - return labelFields; - } - - public void setLabelFields(List labelFields) { - this.labelFields = labelFields; - } - - public List getInfolineFields() { - return infolineFields; - } - - public void setInfolineFields(List infolineFields) { - this.infolineFields = infolineFields; - } - - public List getTooltipFields() { - return tooltipFields; - } - - public void setTooltipFields(List tooltipFields) { - this.tooltipFields = tooltipFields; - } - - public float getLabelMaxScale() { - return labelMaxScale; - } - - public void setLabelMaxScale(float labelMaxScale) { - this.labelMaxScale = labelMaxScale; - } - - public float getLabelMinScale() { - return labelMinScale; - } - - public void setLabelMinScale(float labelMinScale) { - this.labelMinScale = labelMinScale; - } - - public RuleOp getOp() { - return op; - } - - public void setOp(RuleOp op) { - this.op = op; - } - - public Object getVal() { - return val; - } - - public void setVal(Object val) { - this.val = val; - } - - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Rule.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("This should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/rule/RuleHandler.java b/src/openmap/com/bbn/openmap/omGraphics/rule/RuleHandler.java deleted file mode 100644 index 400d5907f..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/rule/RuleHandler.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.Vector; - -import com.bbn.openmap.OMComponent; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.omGraphics.OMTextLabeler; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.util.PropUtils; - -/** - * The RuleHandler manages a set of Rules and will evaluate OMGraphics against - * them for a current projection. - *

- * For List rules, something like this: - * - *

- * # Rule marker names specified in space-separated list
- * neroads.rules=rule0 rule1
- * # global scale settings can be used so work is only performed within scale range of minScale/maxScale
- * neroads.maxScale=1000000f
- * 
- * # rule0 definition:
- * # CLASS_RTE is a DBF column name
- * neroads.rule0.key=CLASS_RTE
- * # operation, if key value is less than 2
- * neroads.rule0.op=lt
- * neroads.rule0.val=2
- * # If rule is met, then actions can be performed:
- * # Column names can be added together in a label by specifying them in a space-separated list
- * neroads.rule0.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * # Labels can have scale limits imposed, so they don't appear if map scale is 
- * # greater than maxScale or less than minScale
- * neroads.rule0.label.maxScale=1000000
- * # Visibility can be controlled with respect to scale as well
- * neroads.rule0.render.maxScale=1000000
- * # Rendering attributes can be specified.
- * neroads.rule0.lineColor=FFFA73
- * neroads.rule0.lineWidth=4
- * neroads.rule0.mattingColor=55AAAAAA
- * 
- * # rule1 definition:
- * neroads.rule1.key=CLASS_RTE
- * neroads.rule1.op=all
- * neroads.rule1.label=PREFIX PRETYPE NAME TYPE SUFFIX
- * neroads.rule1.label.maxScale=200000
- * neroads.rule1.render.maxScale=500000
- * neroads.rule1.lineColor=FFFFFF
- * neroads.rule1.lineWidth=3
- * neroads.rule1.mattingColor=55AAAAAA
- * 
- * # The render attribute is assumed to be true.  You can hide OMGraphics by setting it to false.
- * 
- * - * @author dietrick - */ -public abstract class RuleHandler extends OMComponent { - - List rules; - - /** - * Create a Rule object that knows how to interpret properties to create the - * proper indices into the record List. - */ - public abstract Rule createRule(); - - /** - * Return a record Map for a particular OMGraphic, like a properties table. - * - * @param omg OMGraphic being queried - * @return Map of objects as attributes for the OMGraphic. - */ - public abstract T getRecordDataForOMGraphic(OMGraphic omg); - - public void setProperties(String prefix, Properties props) { - super.setProperties(prefix, props); - prefix = PropUtils.getScopedPropertyPrefix(prefix); - - String rulesString = props.getProperty(prefix + Rule.RuleListProperty); - Vector keysV = PropUtils.parseSpacedMarkers(rulesString); - - if (keysV != null && !keysV.isEmpty()) { - List rules = Collections.synchronizedList(new LinkedList()); - - for (String ruleMarker : keysV) { - Rule rule = createRule(); - rule.setProperties(prefix + ruleMarker, props); - rules.add(rule); - } - - setRules(rules); - } - } - - public Properties getProperties(Properties props) { - props = super.getProperties(props); - String prefix = PropUtils.getScopedPropertyPrefix(this); - - StringBuffer ruleList = new StringBuffer(); - int createdRuleNum = 1; - - for (Rule rule : getRules()) { - String rulePrefix = rule.getPropertyPrefix(); - - // For rules created programmatically without a prefix, need to - // create one. - if (rulePrefix == null) { - rulePrefix = "createdRulePrefix" + (createdRuleNum++); - rule.setPropertyPrefix(prefix + rulePrefix); - } - - if (rulePrefix.startsWith(prefix)) { - rulePrefix = rulePrefix.substring(prefix.length()); - if (rulePrefix.startsWith(".")) { - rulePrefix = rulePrefix.substring(1); - } - } - - ruleList.append(rulePrefix).append(" "); - - rule.getProperties(props); - } - - if (ruleList.length() > 0) { - props.put(prefix + Rule.RuleListProperty, ruleList.toString()); - } - - return props; - } - - public void setRules(List rules) { - this.rules = rules; - } - - public void addRule(Rule rule) { - if (rule != null) { - getRules().add(rule); - } - } - - public boolean removeRule(Rule rule) { - if (rule != null) { - return getRules().remove(rule); - } - - return false; - } - - public void clearRules() { - getRules().clear(); - } - - public List getRules() { - if (rules == null) { - rules = Collections.synchronizedList(new LinkedList()); - } - return rules; - } - - /** - * Used to help prevent consecutive repeat label values. - */ - protected String lastLabel; - - /** - * This is the main call that a layer would use to modify/update an - * OMGraphic based on dbf file contents. Tries to retrieve the index from - * the attributes of the OMGraphic, and then checks the index and OMGraphic - * to see how/if it should be rendered, as determined by the rules. - * - * @param omg the OMGraphic in question - * @param labelList an OMGraphicList to add the label to, so it gets - * rendered on top. - * @param proj the current map projection, for scale appropriateness - * determinations. - * @return OMGraphic if it should be displayed, null if it shouldn't. - */ - public OMGraphic evaluate(OMGraphic omg, OMGraphicList labelList, Projection proj) { - - // Just check for rules first - if no rules defined, don't bother - // reading the attributes. - List rules = getRules(); - if (rules.isEmpty()) { - return omg; - } - - T record = getRecordDataForOMGraphic(omg); - if (record == null) { - return omg; - } - - OMGraphic passedEval = null; - - for (Rule rule : rules) { - - passedEval = rule.evaluate(record, omg, proj); - - if (passedEval != null) { - - /** - * Let's do some stuff with a label to minimize the number of - * labels that might show up. - */ - Object labelObj = omg.getAttribute(OMGraphic.LABEL); - if (labelObj instanceof OMTextLabeler) { - String curLabel = ((OMTextLabeler) labelObj).getData(); - - if (lastLabel == null - || (lastLabel != null && !lastLabel.equalsIgnoreCase(curLabel))) { - labelList.add((OMTextLabeler) labelObj); - } else { - // The Rule adds the label to the OMGraphic, we'll - // remove it so it doesn't get rendered underneath - omg.removeAttribute(OMGraphic.LABEL); - } - - lastLabel = curLabel; - } - break; - } - - } - - // Might be null - return passedEval; - } - -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/rule/RuleOp.java b/src/openmap/com/bbn/openmap/omGraphics/rule/RuleOp.java deleted file mode 100644 index faf1ec72f..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/rule/RuleOp.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * Copyright 2015 BBN Technologies - * - */ -package com.bbn.openmap.omGraphics.rule; - -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -/** - * The RuleOp class (operation) is used by the Rules to evaluate a rule key - * value against a OMGraphics key value. - * - * @author dietrick - */ -public enum RuleOp { - - /** - * equals: equals - */ - EQUALS("equals", "equals") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - }, - /** - * lt: less than - */ - LESS_THAN("less than", "lt") { - public boolean compare(int kvcr) { - return kvcr > 0; - } - }, - /** - * lte: less than or equals - */ - LESS_THAN_EQUALS("less than or equals", "lte") { - public boolean compare(int kvcr) { - return kvcr == 0 || kvcr > 0; - } - }, - /** - * gt: greater than - */ - GREATER_THAN("greater than", "gt") { - public boolean compare(int kvcr) { - return kvcr < 0; - } - }, - /** - * gte: greater than or equals - */ - GREATER_THAN_EQUALS("greater than or equals", "gte") { - public boolean compare(int kvcr) { - return kvcr == 0 || kvcr < 0; - } - }, - /** - * ne: not equals - */ - NOT_EQUALS("not equals", "ne") { - public boolean compare(int kvcr) { - return kvcr != 0; - } - }, - /** - * noop: no-op (nothing passes rule) - */ - NONE("no-op", "noop") { - public boolean compare(int kvcr) { - return false; - } - }, - /** - * all: all (everything passes rule) - */ - ALL("all", "all") { - public boolean compare(int kvcr) { - return true; - } - }, - /** - * starts: starts with - */ - STARTS_WITH("starts with", "starts") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - - public boolean evaluate(Object key, Object val) { - return (val.toString()).startsWith(key.toString()); - } - }, - /** - * ends: ends with - */ - ENDS_WITH("ends with", "ends") { - public boolean compare(int kvcr) { - return kvcr == 0; - } - - public boolean evaluate(Object key, Object val) { - return (val.toString()).endsWith(key.toString()); - } - }; - - protected String description; - protected String propertyNotation; - - private RuleOp(String desc, String propNotation) { - this.description = desc; - this.propertyNotation = propNotation; - } - - public boolean evaluate(Object key, Object val) { - if (key == null) { - return compare(-1); - } - - if (val instanceof Number) { - if (!(key instanceof Double)) { - java.text.DecimalFormat df = new java.text.DecimalFormat(); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH); - df.setDecimalFormatSymbols(dfs); - try { - key = new Double(df.parse(key.toString()).doubleValue()); - } catch (java.text.ParseException pe) { - return compare(-1); - } - } - - return compare(((Double) key).compareTo(((Number) val).doubleValue())); - } - - return compare(((String) key.toString()).compareTo(val.toString())); - } - - public abstract boolean compare(int keyValcompareResult); - - public static RuleOp resolve(String opString) { - if (opString != null) { - for (RuleOp op : values()) { - if (op.propertyNotation.equalsIgnoreCase(opString)) { - return op; - } - } - } - return null; - } - - public String getDescription() { - return description; - } - - public String getPropertyNotation() { - return propertyNotation; - } -} diff --git a/src/openmap/com/bbn/openmap/omGraphics/util/RibbonMaker.java b/src/openmap/com/bbn/openmap/omGraphics/util/RibbonMaker.java deleted file mode 100644 index 7db750336..000000000 --- a/src/openmap/com/bbn/openmap/omGraphics/util/RibbonMaker.java +++ /dev/null @@ -1,601 +0,0 @@ -package com.bbn.openmap.omGraphics.util; - -import java.util.LinkedList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.MoreMath; -import com.bbn.openmap.geo.Geo; -import com.bbn.openmap.geo.GeoArray; -import com.bbn.openmap.geo.Intersection; -import com.bbn.openmap.geo.Ribbon; -import com.bbn.openmap.geo.RibbonIterator; -import com.bbn.openmap.omGraphics.OMAreaList; -import com.bbn.openmap.omGraphics.OMGraphic; -import com.bbn.openmap.omGraphics.OMPoly; -import com.bbn.openmap.proj.Length; - -/** - * The RibbonMaker class takes polygon coordinates and creates another polygon - * from it, a buffer region based on ground distance, around the original poly. - * It assumes that the polygon coordinates are going in a clockwise direction. - * The returned polygon is actually an OMAreaList made up of OMPolys, OMArcs and - * OMLines, depending on the shape of the original polygon. - *

- * - * The RibbonMaker is created from one of the factory methods that designates - * whether the coordinates are radians or decimal degrees. FYI - OMPoly - * coordinates retrieved from the getLatLonArray method are in radians. After - * the RibbonMaker is created, call the method that creates the appropriate - * shape. For now, getOuterRing is your only option. To use: - * - *

- * 
- * llPoints = new double[] { 40.0f, -92.0f, 42.0f, -87.0f, 38.57, -90.825, 37.0f, -89.0f, 35.0f, -94.0f, 40.0f,
- * 		-92.0f };
- * 
- * OMGraphic omg = RibbonMaker.createFromDecimalDegrees(llPoints).getOuterRing(Length.MILE.toRadians(100));
- * 
- * 
- * - * - * @author ddietrick - */ -public class RibbonMaker { - - protected GeoArray geoCoords; - // If a negative distance is passed to getOuterRing, then we'll construct - // this with opposite winding - protected GeoArray geoCoords_reversed = null; - private static final Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.util.RibbonMaker"); - protected final static int STRAIGHT = 0; - protected final static int BENDS_LEFT = -1; - protected final static int BENDS_RIGHT = 1; - protected double bufferLimit = 4.778825E-10; - - protected RibbonMaker(GeoArray gCoords) { - geoCoords = gCoords; - } - - /** - * Create a RibbonMaker from decimal degree coordinates. - * - * @param coords lat,lon,lat,lon in decimal degrees. - * @return RibbonMaker - */ - public static RibbonMaker createFromDecimalDegrees(double[] coords) { - return new RibbonMaker(GeoArray.Double.createFromLatLonDegrees(coords)); - } - - /** - * Create a RibbonMaker from radian coordinates. - * - * @param coords lat,lon,lat,lon in radians. - * @return RibbonMaker - */ - public static RibbonMaker createFromRadians(double[] coords) { - return new RibbonMaker(GeoArray.Double.createFromLatLonRadians(coords)); - } - - /** - * Assumes coords represent a polygon, returns an OMAreaList representing - * buffer zone around the outside of a polygon. - * - * @param dist distance of buffer area, in radians. Use Length to convert. - * @return OMAreaList of a polygon that is a distance away from the - * coordinate polygon's edges. - */ - public OMAreaList getOuterRing(double dist) { - OMAreaList ret = new OMAreaList(); - - if (Math.abs(dist) <= bufferLimit) { - return ret; - } - - GeoArray localGeoCoords = this.geoCoords; - if (dist < 0) { - // Construct a version of this shape wound the other way - dist = -dist; - if (geoCoords_reversed == null) { - double[] reversed = new double[2 * geoCoords.getSize()]; - for (int i = geoCoords.getSize() - 1; i >= 0; i--) { - Geo thisGeo = geoCoords.get(geoCoords.getSize() - i - 1); - reversed[2 * i] = thisGeo.getLatitudeRadians(); - reversed[2 * i + 1] = thisGeo.getLongitudeRadians(); - } - geoCoords_reversed = GeoArray.Double.createFromLatLonRadians(reversed); - } - localGeoCoords = geoCoords_reversed; - } - - int numCoords = localGeoCoords.getSize(); - - if (numCoords >= 3) { - - Geo g1 = localGeoCoords.get(0); - Geo g2 = localGeoCoords.get(1); - Geo g3 = localGeoCoords.get(2); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - - for (int i = 3; i < numCoords; i++) { - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(i); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - } - - // test, and close it off if needed - if (!localGeoCoords.get(0).equals(localGeoCoords.get(numCoords - 1))) { - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(0); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - } - - // Now round out the first and last segment, centering on the first - // coordinate - g1 = g2; - g2 = g3; - g3 = localGeoCoords.get(1); - - handlePointsForOuterRing(g1, g2, g3, dist, ret); - - } - return ret; - } - - /** - * Takes a corner represented by the three geos, and adds OMGraphics to the - * OMAreaList depending on which way the corner bends - for right turns, - * it'll add an OMLine, OMArc and OMLine. The OMLines will go from half the - * distance of the legs to the rounded corner. The left turn will have a - * polygon added. - * - * @param g1 point 1 - * @param g2 point 2 - * @param g3 point 3 - * @param dist buffer distance in radians - * @param ret OMAreaList to add OMGraphics to. - */ - protected void handlePointsForOuterRing(Geo g1, Geo g2, Geo g3, double dist, OMAreaList ret) { - int bend = bends(g1, g2, g3); - - Geo gret = g3; - RibbonIterator leg1 = new RibbonIterator(g1, g2, dist); - OMPoly poly1 = getHalfPoly(leg1, Ribbon.LEFT, false); - - RibbonIterator leg2 = new RibbonIterator(g2, g3, dist); - OMPoly poly2 = getHalfPoly(leg2, Ribbon.LEFT, true); - - // Oh dear... - if (poly1 == null || poly2 == null) { - return; - } - - if (bend == STRAIGHT || g2.equals(g3)) { - ret.add(poly1); - ret.add(poly2); - } else { - if (bend == BENDS_LEFT) { - // short, need to find intersection of two legs and remove - // points - // from polys to only go to intersection - - double dg12 = g1.distance(g2); - double dg23 = g2.distance(g3); - double legTestDist = dist * 2; - - if (dg12 < legTestDist || dg23 < legTestDist) { - addShortLegPolyForIntersection(g1, g2, g3, Ribbon.LEFT, dist, ret); - } else { - addPolyForIntersection(poly1, poly2, dist, ret); - } - - } else { - OMGraphic omp = getPushbackPoly(poly1, dist); - if (omp != null) { - ret.add(omp); - } - // Add OMArc in the middle, rounding around a corner - OMGraphic oma = getArc(g2, poly1, poly2); - if (oma != null) { - ret.add(oma); - } - omp = getPushbackPoly(poly2, dist); - if (omp != null) { - ret.add(omp); - } - } - } - - } - - /** - * Method that determines which way the angle between the three points - * bends. - * - * @param g1 - * @param g2 - * @param g3 - * @return STRAIGHT if no bend, BENDS_LEFT if bends less than PI, - * BENDS_RIGHT if bends more than PI. - */ - protected int bends(Geo g1, Geo g2, Geo g3) { - double bend = g1.crossNormalize(g2).distance(g3) - (Math.PI / 2.0); - - if (Math.abs(bend) < .0001) { - return STRAIGHT; // essentially straight - } else { - if (bend < 0) { - return BENDS_LEFT; - } - } - - return BENDS_RIGHT; - } - - /** - * Checks to see if a point is too close to any side of the original - * polygon. - * - * @param pnt - * @param distance - * @return true if is too close and should not be added to the buffer - * polygon. - */ - protected boolean tooClose(Geo pnt, double distance) { - return Intersection.isPointNearPoly(pnt, geoCoords, distance - bufferLimit); - } - - /** - * Takes a poly that's going to be added to the buffer and removes any - * points that may be too close to the original poly. - * - * @param omp the buffer poly to be added later - * @param dist the distance all points should be from the original - * @return the OMGraphic with good points. - */ - protected OMGraphic getPushbackPoly(OMPoly omp, double dist) { - double[] coords = omp.getLatLonArray(); - List results = new LinkedList(); - for (int i = 0; i < coords.length - 2; i += 2) { - Geo g = new Geo(coords[i], coords[i + 1], false); - if (!tooClose(g, dist)) { - results.add(g); - } - } - - if (results.size() == 1) { - results.add(new Geo(results.get(0))); - } - - if (results.size() > 1) { - return getOMPolyFromGeos(results); - } - - return null; - - } - - /** - * Called when it's known that one of the legs between the corner is smaller - * than the buffer depth. Does some extra work to figure out what points - * should be added to the buffer. - * - * @param g1 point 1 - * @param g2 point 2, the corner - * @param g3 point 3 - * @param ribbonSide which side of the ribbon should be calculated. - * @param dist the distance the buffer should be from the legs - * @param ret the OMGraphicList to add the resulting poly to. - */ - protected void addShortLegPolyForIntersection(Geo g1, Geo g2, Geo g3, int ribbonSide, double dist, OMAreaList ret) { - - /** - * We need to do some extra work here. Since one of the legs is shorter - * than 2*dist of the buffer, half of the buffer polygon won't reach the - * intersection point between the two legs. So, we need to recalculate - * the polys so the represent the entire legs, in order to find the - * intersection point. - * - * Once we have that, we can go back to the half polygons, and test for - * that intersection point against each little segment. If any of those - * points are further away than buffer distance to the opposite poly, - * they should be included on the polygon added to the list. If a point - * is inside that distance, it should be disregarded. If there is only - * one point (i.e. the original intersection point), then a duplicate - * intersection point should be added, so the OMAreaList will handle it - * properly. - */ - List results = new LinkedList(); - RibbonIterator leg1 = new RibbonIterator(g1, g2, dist); - OMPoly fullPoly1 = getPoly(leg1, ribbonSide); - - RibbonIterator leg2 = new RibbonIterator(g2, g3, dist); - OMPoly fullPoly2 = getPoly(leg2, ribbonSide); - - if (fullPoly1 == null || fullPoly2 == null) { - return; - } - - // Intersection is the point on both polys that is buffer distance away - // from corner - Geo intersection = getPolyIntersection(fullPoly1, fullPoly2); - - if (intersection == null) { - // GAAH! This shouldn't happen - return; - } - - leg1 = new RibbonIterator(g1, g2, dist); - OMPoly halfPoly1 = getHalfPoly(leg1, ribbonSide, false); - if (halfPoly1 != null) { - GeoArray geoPoly2 = GeoArray.Double.createFromLatLonRadians(fullPoly2.getLatLonArray()); - - double[] leg1Coords = halfPoly1.getLatLonArray(); - for (int i = 0; i < leg1Coords.length - 1; i += 2) { - Geo pnt = new Geo(leg1Coords[i], leg1Coords[i + 1], false); - - if (!tooClose(pnt, dist)) { - results.add(pnt); - } - } - - if (!tooClose(intersection, dist)) { - results.add(intersection); - } - } - - leg2 = new RibbonIterator(g2, g3, dist); - OMPoly halfPoly2 = getHalfPoly(leg2, ribbonSide, true); - if (halfPoly2 != null) { - GeoArray geoPoly1 = GeoArray.Double.createFromLatLonRadians(fullPoly1.getLatLonArray()); - - double[] leg2Coords = halfPoly2.getLatLonArray(); - for (int i = 0; i < leg2Coords.length - 1; i += 2) { - Geo pnt = new Geo(leg2Coords[i], leg2Coords[i + 1], false); - - if (!tooClose(pnt, dist)) { - results.add(pnt); - } - } - } - - if (results.size() == 1 && !tooClose(intersection, dist)) { - results.add(intersection); - } - - if (results.size() > 1) { - ret.add(getOMPolyFromGeos(results)); - } - } - - /** - * Just return the point where the two polygons cross. - * - * @param poly1 - * @param poly2 - * @return null if no point found. - */ - protected Geo getPolyIntersection(OMPoly poly1, OMPoly poly2) { - double[] p1Coords = poly1.getLatLonArray(); - double[] p2Coords = poly2.getLatLonArray(); - - Geo a1, a2, b1, b2; - Geo intersect = null; - int index1 = 0, index2 = 0; - for (; index2 + 3 < p2Coords.length; index2 += 2) { - b1 = new Geo(p2Coords[index2], p2Coords[index2 + 1], false); - b2 = new Geo(p2Coords[index2 + 2], p2Coords[index2 + 3], false); - - if (intersect == null) { - for (; index1 + 3 < p1Coords.length; index1 += 2) { - - a1 = new Geo(p1Coords[index1], p1Coords[index1 + 1], false); - a2 = new Geo(p1Coords[index1 + 2], p1Coords[index1 + 3], false); - - intersect = Intersection.segmentsIntersect(a1, a2, b1, b2); - - if (intersect != null) { - return intersect; - } - } - } - } - - return intersect; - } - - /** - * Converts Vector of Geos to an OMPoly with linetype great_circle. Assumes - * that the List has valid coordinates on it. Does not do a closeness check - * to the original poly, expected that's been done. - * - * @param geos a set of coordinates - * @return OMPoly - */ - protected OMPoly getOMPolyFromGeos(List geos) { - double[] tmpCoords = new double[geos.size() * 2]; - int index = 0; - for (Geo geo : geos) { - tmpCoords[index++] = geo.getLatitudeRadians(); - tmpCoords[index++] = geo.getLongitudeRadians(); - } - - return new OMPoly(tmpCoords, OMPoly.RADIANS, OMGraphic.LINETYPE_GREATCIRCLE); - } - - /** - * Called to handle BENDS_LEFT, concave corners. RuntimeException is thrown - * when one of the legs is much shorter than the other and the mid-point is - * still in the buffer of one of the legs. In that special case, the - * intersection point is not found. - * - * @param poly1 - * @param poly2 - * @param ret - */ - protected void addPolyForIntersection(OMPoly poly1, OMPoly poly2, double dist, OMAreaList ret) { - double[] p1Coords = poly1.getLatLonArray(); - double[] p2Coords = poly2.getLatLonArray(); - - List results = new LinkedList(); - - Geo a1, a2, b1, b2; - Geo intersect = null; - int index1 = 0, index2 = 0; - for (; index2 + 3 < p2Coords.length; index2 += 2) { - b1 = new Geo(p2Coords[index2], p2Coords[index2 + 1], false); - b2 = new Geo(p2Coords[index2 + 2], p2Coords[index2 + 3], false); - - if (intersect == null) { - for (; index1 + 3 < p1Coords.length; index1 += 2) { - - a1 = new Geo(p1Coords[index1], p1Coords[index1 + 1], false); - a2 = new Geo(p1Coords[index1 + 2], p1Coords[index1 + 3], false); - - intersect = Intersection.segmentsIntersect(a1, a2, b1, b2); - - if (!tooClose(a1, dist)) { - results.add(a1); - } - - if (intersect != null) { - if (!tooClose(intersect, dist)) { - results.add(intersect); - } - break; - } - } - } - - if (intersect != null && !tooClose(b2, dist)) { - results.add(b2); - } - } - - if (results.size() > 1) { - ret.add(getOMPolyFromGeos(results)); - } - } - - /** - * Given a RibbonIterator created from two Geos, create a poly from half of - * that buffer path. Points are not checked for closeness to original poly. - * - * @param rIterator RibbonIterator for one of the legs of corner - * @param side which RibbonIterator side - * @param first which half you want, true for first part - * @return OMPoly that represents half of the buffered path. - */ - protected OMPoly getHalfPoly(RibbonIterator rIterator, int side, boolean first) { - List results = new LinkedList(); - for (Ribbon rib : rIterator) { - Geo g = rib.get(side); - results.add(g); - } - - int numCoords = results.size(); - - if (numCoords > 0) { - - int startingIndex = 0; - int copyLength = numCoords / 2; - - if (numCoords % 2 == 0) { - if (!first) { - startingIndex = copyLength; // middle - } - } else { - if (!first) { - startingIndex = copyLength; - } - copyLength++; - } - - List newGeoCoords = new LinkedList(); - for (int index = 0; index < copyLength; index++) { - Geo g = results.get(startingIndex + index); - newGeoCoords.add(g); - } - - return getOMPolyFromGeos(newGeoCoords); - } - return null; - } - - /** - * Given a RibbonIterator created from two Geos, create a poly from that - * buffer path. - * - * @param rIterator RibbonIterator for one of the legs of corner - * @param side which RibbonIterator side - * @return OMPoly that represents buffered path between geos. - */ - protected OMPoly getPoly(RibbonIterator rIterator, int side) { - List bufferCoords = new LinkedList(); - for (Ribbon rib : rIterator) { - bufferCoords.add(rib.get(side)); - } - - if (bufferCoords.size() > 1) { - return getOMPolyFromGeos(bufferCoords); - } - return null; - } - - /** - * Given two polylines, with the end point of poly1 being the same distance - * from a point as the starting point of poly2, create an arc that connects - * them. - * - * @param gc point - * @param poly1 polyline where the last end point is used - * @param poly2 polyline where the first end point is used. - * @return OMArc - */ - public OMGraphic getArc(Geo gc, OMPoly poly1, OMPoly poly2) { - - double[] poly1Coords = poly1.getLatLonArray(); - Geo pt1 = new Geo(poly1Coords[poly1Coords.length - 2], poly1Coords[poly1Coords.length - 1], false); - double radAngle1 = gc.azimuth(pt1); - - double[] poly2Coords = poly2.getLatLonArray(); - Geo pt2 = new Geo(poly2Coords[0], poly2Coords[1], false); - double radAngle2 = gc.azimuth(pt2); - - double dist = gc.distance(pt1); - - if (radAngle2 < radAngle1) { - radAngle2 += MoreMath.TWO_PI_D; - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine( - new StringBuilder("Making arg starting at ").append(Length.DECIMAL_DEGREE.fromRadians(radAngle1)) - .append(", ").append(Length.DECIMAL_DEGREE.fromRadians(radAngle2 - radAngle1)).toString()); - } - - List points = new LinkedList(); - double inc = Length.DECIMAL_DEGREE.toRadians(2.0); - double angle = radAngle1 + inc; - - while (angle < radAngle2 - inc) { - Geo g = gc.offset(dist, angle); - if (!tooClose(g, dist)) { - points.add(g); - } - angle += inc; - } - - return getOMPolyFromGeos(points); - // return new OMArc(gc.getLatitude(), gc.getLongitude(), dist, - // Length.RADIAN, 100, Length.DECIMAL_DEGREE.fromRadians(radAngle1), - // Length.DECIMAL_DEGREE.fromRadians(radAngle2 - radAngle1)); - - } -} diff --git a/src/openmap/com/bbn/openmap/proj/GeoProj.java b/src/openmap/com/bbn/openmap/proj/GeoProj.java deleted file mode 100644 index 45bbf09c0..000000000 --- a/src/openmap/com/bbn/openmap/proj/GeoProj.java +++ /dev/null @@ -1,1567 +0,0 @@ -//********************************************************************** -// -// -// -//BBN Technologies, a Verizon Company -//10 Moulton Street -//Cambridge, MA 02138 -//(617) 873-8000 -// -//Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -//********************************************************************** -// -//$Source: -///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v -//$ -//$RCSfile: GeoProj.java,v $ -//$Revision: 1.7 $ -//$Date: 2009/02/25 22:34:04 $ -//$Author: dietrick $ -// -//********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Arc2D; -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.MoreMath; -import com.bbn.openmap.proj.coords.GeoCoordTransformation; -import com.bbn.openmap.proj.coords.LatLonGCT; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.Debug; - -/** - * GeoProj is the base class of all Projections that deal with coordinates on - * the world sphere. - *

- * You probably don't want to use this class unless you are hacking your own - * projections, or need extended functionality. To be safe you will want to use - * the Projection interface. - * - *

Notes:

- * - *
    - * - *
  • We deal in radians internally. The outside world usually deals in decimal - * degrees. If you have data in radians, DON'T bother converting it into DD's - * since we'll convert it right back into radians for the projection step. For - * more optimization tips, see the OMPoly class. - * - *
  • We default to projecting our data using the WGS84 datum. You can change - * the appropriate parameters of the projection after construction if you need - * to use a different datum. And of course you can derive your own projections - * from this class as you see fit. - * - *
  • The forward() and inverse() methods are currently implemented using the - * algorithms given in John Synder's Map Projections --A Working Manual - * for the sphere. This is sufficient for display purposes, but you should use - * ellipsoidal algorithms in the GreatCircle class to calculate distance and - * azimuths on the ellipsoid. See each projection individually for more - * information. - * - *
  • This class is not thread safe. If two or more threads are using the same - * Proj, then they could disrupt each other. Occasionally you may need to call a - * set method of this class. This might interfere with another - * thread that's using the same projection for forwardPoly or - * another Projection interface method. In general, you should not need to call - * any of the set methods directly, but let the MapBean do it for - * you. - * - *
  • All the various forwardOBJ() methods for ArrayList graphics - * ultimately go through forwardPoly(). - * - *
- * - * @see Projection - * @see Cylindrical - * @see Mercator - * @see CADRG - * @see Azimuth - * @see Orthographic - * @see Planet - * @see GreatCircle - * @see com.bbn.openmap.omGraphics.OMPoly - * - */ -public abstract class GeoProj extends Proj { - // Used for generating segments of List objects - protected static transient int NUM_DEFAULT_CIRCLE_VERTS = 64; - - // SOUTH_POLE <= phi <= NORTH_POLE (radians) - // -DATELINE <= lambda <= DATELINE (radians) - - /** - * North pole latitude in radians. - */ - public final static transient float NORTH_POLE = ProjMath.NORTH_POLE_F; - - /** - * South pole latitude in radians. - */ - public final static transient float SOUTH_POLE = ProjMath.SOUTH_POLE_F; - - /** - * Dateline longitude in radians. - */ - public final static transient float DATELINE = ProjMath.DATELINE_F; - - // Used for generating segments of ArrayList objects - protected static transient int NUM_DEFAULT_GREAT_SEGS = 512; - - // pixels per meter (an extra scaling factor). - protected double pixelsPerMeter; // PPM - protected double planetRadius;// EARTH_RADIUS - protected double planetPixelRadius; // EARTH_PIX_RADIUS - protected double planetPixelCircumference; // EARTH_PIX_CIRCUMFERENCE - protected double scaled_radius; - - protected Mercator mercator = null; // for rhumbline calculations - - public GeoProj(LatLonPoint center, float s, int w, int h) { - super(center, s, w, h); - - // for rhumbline projecting - if (!(this instanceof Mercator)) { - mercator = new Mercator(center, (float) scale, width, height); - } - } - - protected void init() { - - centerX = wrapLongitude(Math.toRadians(centerX)); - centerY = normalizeLatitude(Math.toRadians(centerY)); - - // pixels per meter (an extra scaling factor). - pixelsPerMeter = Planet.defaultPixelsPerMeter; // PPM - planetRadius = Planet.wgs84_earthEquatorialRadiusMeters_D;// EARTH_RADIUS - planetPixelRadius = planetRadius * pixelsPerMeter; // EARTH_PIX_RADIUS - planetPixelCircumference = MoreMath.TWO_PI_D * planetPixelRadius; // EARTH_PIX_CIRCUMFERENCE - // the scaled_radius should also be set in computeParameters with the - // scale that has been checked against min/max scale - scaled_radius = planetPixelRadius / scale; - /* good for cylindrical */ - maxscale = planetPixelCircumference / width; - } - - /** - * Set the pixels per meter constant. - * - * @param ppm int Pixels Per Meter scale-factor constant - */ - public void setPPM(double ppm) { - pixelsPerMeter = ppm; - if (pixelsPerMeter < 1) { - pixelsPerMeter = 1; - } - computeParameters(); - } - - /** - * Get the pixels-per-meter constant. - * - * @return int Pixels Per Meter scale-factor constant - */ - public double getPPM() { - return pixelsPerMeter; - } - - /** - * Set the planet radius. - * - * @param radius float planet radius in meters - */ - public void setPlanetRadius(double radius) { - planetRadius = radius; - if (planetRadius < 1.0f) { - planetRadius = 1.0f; - } - computeParameters(); - } - - /** - * Get the planet radius. - * - * @return float radius of planet in meters - */ - public double getPlanetRadius() { - return planetRadius; - } - - /** - * Get the planet pixel radius. - * - * @return float radius of planet in pixels - */ - public double getPlanetPixelRadius() { - return planetPixelRadius; - } - - /** - * Get the planet pixel circumference. - * - * @return float circumference of planet in pixels - */ - public double getPlanetPixelCircumference() { - return planetPixelCircumference; - } - - /** - * Set center point of projection. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - */ - public void setCenter(float lat, float lon) { - setCenter((double) lat, (double) lon, false); - } - - /** - * Set center point of projection. - * - * @param lat double latitude in decimal degrees - * @param lon double longitude in decimal degrees - */ - public void setCenter(double lat, double lon) { - setCenter(lat, lon, false); - } - - /** - * Set center point of projection. - * - * @param lat double latitude in decimal degrees - * @param lon double longitude in decimal degrees - */ - public void setCenter(double lat, double lon, boolean isRadians) { - if (!isRadians) { - lat = Math.toRadians(lat); - lon = Math.toRadians(lon); - } - - centerX = wrapLongitude(lon); - centerY = normalizeLatitude(lat); - computeParameters(); - projID = null; - } - - /** - * Get center point of projection. - * - * @return LatLonPoint center of projection, created just for you. - */ - public LatLonPoint getCenter() { - return new LatLonPoint.Double(centerY, centerX, true); - } - - /** - * Returns a center LatLonPoint that was provided, with the location filled - * into the LatLonPoint object. Calls Point2D.setLocation(x, y). - */ - public T getCenter(T center) { - center.setLocation(Math.toDegrees(centerX), Math.toDegrees(centerY)); - return center; - } - - /** - * Sets radian latitude to something sane. - *

- * Normalizes the latitude according to the particular projection. - * - * @param lat float latitude in radians - * @return float latitude (-PI/2 <= y <= PI/2) - * @see ProjMath#normalizeLatitude(float, float) - * @see LatLonPoint#normalizeLatitude(float) - */ - public float normalizeLatitude(float lat) { - return (float) normalizeLatitude((double) lat); - } - - abstract public double normalizeLatitude(double lat); - - /** - * Sets radian longitude to something sane. - * - * @param lon float longitude in radians - * @return float longitude (-PI <= x < PI) - * @see ProjMath#wrapLongitude(float) - * @see LatLonPoint#wrapLongitude(float) - */ - public final static float wrapLongitude(float lon) { - return ProjMath.wrapLongitude(lon); - } - - public final static double wrapLongitude(double lon) { - return ProjMath.wrapLongitude(lon); - } - - public final static double wrapLongitudeDeg(double lon) { - return ProjMath.wrapLongitudeDeg(lon); - } - - /** - * @deprecated use normalizeLatitude() instead. - */ - public final double normalize_latitude(double lat) { - return normalizeLatitude(lat); - } - - /** - * @deprecated use wrapLongitude() instead. - */ - public final static double wrap_longitude(double lon) { - return wrapLongitude(lon); - } - - /** - * Pan the map/projection. - *

- * Example pans: - *

    - *
  • pan(180, c) pan south `c' degrees - *
  • pan(-90, c) pan west `c' degrees - *
  • pan(0, c) pan north `c' degrees - *
  • pan(90, c) pan east `c' degrees - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees - */ - public void pan(double Az, double c) { - setCenter(RhumbCalculator.calculatePointOnRhumbLine(getCenter(), Math.toRadians(Az), Math.toRadians(c))); - } - - /** - * Pan the map/projection. Figures on an ellipse based around the center of - * the map in the direction provided. - * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - public void pan(double Az) { - double angle = Math.toRadians(90 - Az); - int w2 = getWidth() / 2; - int h2 = getHeight() / 2; - LatLonPoint newLoc = inverse(w2 + (w2 * Math.cos(angle)), h2 + (h2 * Math.sin(angle))); - double dist = RhumbCalculator.getDistanceBetweenPoints(getCenter(), newLoc); - pan(Az, Math.toDegrees(dist)); - } - - /** - * Stringify the projection. - * - * @return stringified projection - * @see #getProjectionID - */ - public String toString() { - return (" radius=" + planetRadius + " ppm=" + pixelsPerMeter + " center(" + centerY + ":" - + centerX + ") scale=" + scale + " maxscale=" + maxscale + " minscale=" + minscale - + " width=" + width + " height=" + height + "]"); - } - - /** - * Copies this projection. - * - * @return a copy of this projection. - */ - public Object clone() { - GeoProj proj = (GeoProj) super.clone(); - if (mercator != null) { - proj.mercator = (Mercator) mercator.clone(); - } - return proj; - } - - public boolean isPlotable(Point2D point) { - if (point instanceof LatLonPoint) { - return isPlotable(point.getY(), point.getX()); - } - - // Well, then, what is it? - return false; - } - - /** - * Forward project a rhumbline poly. - *

- * Draws rhumb lines between vertices of poly. Remember to specify vertices - * in radians! Check in-code comments for details about the algorithm. - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardRhumbPoly(float[] rawllpts, int nsegs, boolean isFilled) { - - // IDEA: - // Rhumblines are straight in the Mercator projection. - // So we can use the Mercator projection to calculate - // vertices along the rhumbline between two points. But - // if there's a better way to calculate loxodromes, - // someone please chime in (openmap@bbn.com)... - // - // ALG: - // Project pairs of vertices through the Mercator - // projection into screen XY space, pick intermediate - // segment points along the straight XY line, then - // convert all vertices back into LatLon space. Pass the - // augmented vertices to _forwardPoly() to be drawn as - // straight segments. - // - // WARNING: - // The algorithm fixes the Cylindrical-wrapping - // problem, and thus duplicates some code in - // Cylindrical._forwardPoly() - - if (this instanceof Mercator) {// simple - return _forwardPoly(rawllpts, LineType.Straight, nsegs, isFilled); - } - - int i, n, xp, flag = 0, xadj = 0, totalpts = 0; - Point from = new Point(0, 0); - Point to = new Point(0, 0); - int len = rawllpts.length; - - float[][] augllpts = new float[len >>> 1][0]; - - // lock access to object global, since this is probably not - // cloned and different layers may be accessing this. - // synchronized (mercator) { - - // we now create a clone of the mercator variable in - // makeClone(), so since different objects should be using - // their clone instead of the main projection, the - // synchronization should be unneeded. - - // use mercator projection to calculate rhumblines. - // mercator.setParms( - // new LatLonPoint(ctrLat, ctrLon, true), - // scale, width, height); - - // Unnecessary to set parameters !! ^^^^^ - - // project everything through the Mercator projection, - // building up lat/lon points along the original rhumb - // line between vertices. - mercator.forward(rawllpts[0], rawllpts[1], from, true); - xp = from.x; - for (i = 0, n = 2; n < len; i++, n += 2) { - mercator.forward(rawllpts[n], rawllpts[n + 1], to, true); - // segment crosses longitude along screen edge - if (Math.abs(xp - to.x) >= mercator.half_world) { - flag += (xp < to.x) ? -1 : 1;// inc/dec the wrap - // count - xadj = flag * mercator.world.x;// adjustment to x - // coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = to.x; - if (flag != 0) { - to.x += xadj;// adjust x coordinate - } - - augllpts[i] = mercator.rhumbProject(from, to, false, nsegs); - totalpts += augllpts[i].length; - from.x = to.x; - from.y = to.y; - } - - LatLonPoint llp = new LatLonPoint.Double(); - mercator.inverse(from.x, from.y, llp); - // }// end synchronized around mercator - - augllpts[i] = new float[2]; - augllpts[i][0] = (float) llp.getRadLat(); - augllpts[i][1] = (float) llp.getRadLon(); - totalpts += 2; - - // put together all the points - float[] newllpts = new float[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - // Debug.output("copying " + augllpts[i].length + " - // floats"); - System.arraycopy( - /* src */augllpts[i], 0, - /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - // Debug.output("done copying " + totalpts + " total floats"); - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a rhumbline poly. - *

- * Draws rhumb lines between vertices of poly. Remember to specify vertices - * in radians! Check in-code comments for details about the algorithm. - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardRhumbPoly(double[] rawllpts, int nsegs, boolean isFilled) { - - // IDEA: - // Rhumblines are straight in the Mercator projection. - // So we can use the Mercator projection to calculate - // vertices along the rhumbline between two points. But - // if there's a better way to calculate loxodromes, - // someone please chime in (openmap@bbn.com)... - // - // ALG: - // Project pairs of vertices through the Mercator - // projection into screen XY space, pick intermediate - // segment points along the straight XY line, then - // convert all vertices back into LatLon space. Pass the - // augmented vertices to _forwardPoly() to be drawn as - // straight segments. - // - // WARNING: - // The algorithm fixes the Cylindrical-wrapping - // problem, and thus duplicates some code in - // Cylindrical._forwardPoly() - - if (this instanceof Mercator) {// simple - return _forwardPoly(rawllpts, LineType.Straight, nsegs, isFilled); - } - - int i, n, xp, flag = 0, xadj = 0, totalpts = 0; - Point from = new Point(0, 0); - Point to = new Point(0, 0); - int len = rawllpts.length; - - double[][] augllpts = new double[len >>> 1][0]; - - // lock access to object global, since this is probably not - // cloned and different layers may be accessing this. - // synchronized (mercator) { - - // we now create a clone of the mercator variable in - // makeClone(), so since different objects should be using - // their clone instead of the main projection, the - // synchronization should be unneeded. - - // use mercator projection to calculate rhumblines. - // mercator.setParms( - // new LatLonPoint(ctrLat, ctrLon, true), - // scale, width, height); - - // Unnecessary to set parameters !! ^^^^^ - - // project everything through the Mercator projection, - // building up lat/lon points along the original rhumb - // line between vertices. - mercator.forward(rawllpts[0], rawllpts[1], from, true); - xp = from.x; - for (i = 0, n = 2; n < len; i++, n += 2) { - mercator.forward(rawllpts[n], rawllpts[n + 1], to, true); - // segment crosses longitude along screen edge - if (Math.abs(xp - to.x) >= mercator.half_world) { - flag += (xp < to.x) ? -1 : 1;// inc/dec the wrap - // count - xadj = flag * mercator.world.x;// adjustment to x - // coordinates - // Debug.output("flag=" + flag + " xadj=" + xadj); - } - xp = to.x; - if (flag != 0) { - to.x += xadj;// adjust x coordinate - } - - augllpts[i] = mercator.rhumbProjectDouble(from, to, false, nsegs); - totalpts += augllpts[i].length; - from.x = to.x; - from.y = to.y; - } - - LatLonPoint llp = new LatLonPoint.Double(); - mercator.inverse(from, llp); - // }// end synchronized around mercator - - augllpts[i] = new double[2]; - augllpts[i][0] = llp.getRadLat(); - augllpts[i][1] = llp.getRadLon(); - totalpts += 2; - - // put together all the points - double[] newllpts = new double[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - // Debug.output("copying " + augllpts[i].length + " - // floats"); - System.arraycopy( - /* src */augllpts[i], 0, - /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - // Debug.output("done copying " + totalpts + " total floats"); - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a greatcircle poly. - *

- * Draws great circle lines between vertices of poly. Remember to specify - * vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardGreatPoly(float[] rawllpts, int nsegs, boolean isFilled) { - int i, j, k, totalpts = 0; - - Point from = new Point(); - Point to = new Point(); - - int end = rawllpts.length >>> 1; - float[][] augllpts = new float[end][0]; - end -= 1;// stop before last segment - - // calculate extra vertices between all the original segments. - forward(rawllpts[0], rawllpts[1], from, true); - for (i = 0, j = 0, k = 2; i < end; i++, j += 2, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], to, true); - augllpts[i] = getGreatVertices(rawllpts[j], rawllpts[j + 1], rawllpts[k], rawllpts[k + 1], from, to, false, nsegs); - from.x = to.x; - from.y = to.y; - totalpts += augllpts[i].length; - } - augllpts[i] = new float[2]; - augllpts[i][0] = rawllpts[j]; - augllpts[i][1] = rawllpts[j + 1]; - totalpts += 2; - - // put together all the points - float[] newllpts = new float[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - System.arraycopy( - /* src */augllpts[i], 0, - /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Forward project a greatcircle poly. - *

- * Draws great circle lines between vertices of poly. Remember to specify - * vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList float[] of x[], y[], x[], y[], ... projected poly - */ - protected ArrayList forwardGreatPoly(double[] rawllpts, int nsegs, boolean isFilled) { - int i, j, k, totalpts = 0; - - Point from = new Point(); - Point to = new Point(); - - int end = rawllpts.length >>> 1; - double[][] augllpts = new double[end][0]; - end -= 1;// stop before last segment - - // calculate extra vertices between all the original segments. - forward(rawllpts[0], rawllpts[1], from, true); - for (i = 0, j = 0, k = 2; i < end; i++, j += 2, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], to, true); - augllpts[i] = getGreatVertices(rawllpts[j], rawllpts[j + 1], rawllpts[k], rawllpts[k + 1], from, to, false, nsegs); - from.x = to.x; - from.y = to.y; - totalpts += augllpts[i].length; - } - augllpts[i] = new double[2]; - augllpts[i][0] = rawllpts[j]; - augllpts[i][1] = rawllpts[j + 1]; - totalpts += 2; - - // put together all the points - double[] newllpts = new double[totalpts]; - int pos = 0; - for (i = 0; i < augllpts.length; i++) { - System.arraycopy( - /* src */augllpts[i], 0, - /* dest */newllpts, pos, augllpts[i].length); - pos += augllpts[i].length; - } - - // free unused variables - augllpts = null; - - // now delegate the work to the regular projection code. - return _forwardPoly(newllpts, LineType.Straight, -1, isFilled); - } - - /** - * Get the vertices along the great circle between two points. - * - * @param latp previous float latitude - * @param lonp previous float longitude - * @param latn next float latitude - * @param lonn next float longitude - * @param from Point - * @param to Point - * @param include_last include n or n+1 points of the n segments? - * @return float[] lat/lon points in RADIANS! - * - */ - private float[] getGreatVertices(float latp, float lonp, float latn, float lonn, Point from, - Point to, boolean include_last, int nsegs) { - if (nsegs < 1) { - // calculate pixel distance - int dist = DrawUtil.pixel_distance(from.x, from.y, to.x, to.y); - - /* - * determine what would be a decent number of segments to draw. - * HACK: this is hardcoded calculated by what might look ok on - * screen. We also put a cap on the number of extra segments we - * draw. - */ - nsegs = dist >> 3;// dist/8 - if (nsegs == 0) { - nsegs = 1; - } else if (nsegs > NUM_DEFAULT_GREAT_SEGS) { - nsegs = NUM_DEFAULT_GREAT_SEGS; - } - - // Debug.output( - // "("+from.x+","+from.y+")("+to.x+","+to.y+") - // dist="+dist+" nsegs="+nsegs); - } - - // both of these return float[] radian coordinates! - return GreatCircle.greatCircle(latp, lonp, latn, lonn, nsegs, include_last); - } - - /** - * Get the vertices along the great circle between two points. - * - * @param latp previous double latitude - * @param lonp previous double longitude - * @param latn next double latitude - * @param lonn next double longitude - * @param from Point - * @param to Point - * @param include_last include n or n+1 points of the n segments? - * @param nsegs number of segments to create, or -1 to let algorithm figure - * it out - * @return double[] lat/lon points in RADIANS! - * - */ - private double[] getGreatVertices(double latp, double lonp, double latn, double lonn, - Point from, Point to, boolean include_last, int nsegs) { - if (nsegs < 1) { - // calculate pixel distance - int dist = DrawUtil.pixel_distance(from.x, from.y, to.x, to.y); - - /* - * determine what would be a decent number of segments to draw. - * HACK: this is hardcoded calculated by what might look ok on - * screen. We also put a cap on the number of extra segments we - * draw. - */ - nsegs = dist >> 3;// dist/8 - if (nsegs == 0) { - nsegs = 1; - } else if (nsegs > NUM_DEFAULT_GREAT_SEGS) { - nsegs = NUM_DEFAULT_GREAT_SEGS; - } - - // Debug.output( - // "("+from.x+","+from.y+")("+to.x+","+to.y+") - // dist="+dist+" nsegs="+nsegs); - } - - // both of these return float[] radian coordinates! - return GreatCircle.greatCircle(latp, lonp, latn, lonn, nsegs, include_last); - } - - /** - * Check for complicated linetypes. - *

- * This depends on the line and this projection. - * - * @param ltype int LineType - * @return boolean - */ - public boolean isComplicatedLineType(int ltype) { - switch (ltype) { - case LineType.Straight: - return false; - case LineType.Rhumb: - return (getClass() == Mercator.class) ? false : true; - case LineType.GreatCircle: - return true/* - * (getProjectionType() == Gnomonic.GnomonicType) ? false - * : true - */; - default: - Debug.error("Proj.isComplicatedLineType: invalid LineType!"); - return false; - } - } - - /** - * Generates a complicated poly. - * - * @param rawllpts LatLonPofloat[] - * @param ltype line type - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList - */ - protected ArrayList doPolyDispatch(float[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - switch (ltype) { - case LineType.Rhumb: - return forwardRhumbPoly(rawllpts, nsegs, isFilled); - case LineType.GreatCircle: - return forwardGreatPoly(rawllpts, nsegs, isFilled); - case LineType.Straight: - Debug.error("Proj.doPolyDispatch: Bad Dispatch!\n"); - return new ArrayList(0); - default: - Debug.error("Proj.doPolyDispatch: Invalid LType!\n"); - return new ArrayList(0); - } - } - - /** - * Generates a complicated poly. - * - * @param rawllpts LatLonPofloat[] - * @param ltype line type - * @param nsegs number of segments to draw for greatcircle or rhumb lines - * (if < 1, this value is generated internally). - * @param isFilled filled poly? - * @return ArrayList int[] - */ - protected ArrayList doPolyDispatch(double[] rawllpts, int ltype, int nsegs, - boolean isFilled) { - switch (ltype) { - case LineType.Rhumb: - return forwardRhumbPoly(rawllpts, nsegs, isFilled); - case LineType.GreatCircle: - return forwardGreatPoly(rawllpts, nsegs, isFilled); - case LineType.Straight: - Debug.error("Proj.doPolyDispatch: Bad Dispatch!\n"); - return new ArrayList(0); - default: - Debug.error("Proj.doPolyDispatch: Invalid LType!\n"); - return new ArrayList(0); - } - } - - // /** - // * Given a couple of points representing a bounding box, find out what the - // * scale should be in order to make those points appear at the corners of - // * the projection. - // * - // * @param ll1 the upper left coordinates of the bounding box. - // * @param ll2 the lower right coordinates of the bounding box. - // * @param point1 a java.awt.Point reflecting a pixel spot on the - // projection - // * that matches the ll1 coordinate, the upper left corner of the area - // * of interest. - // * @param point2 a java.awt.Point reflecting a pixel spot on the - // projection - // * that matches the ll2 coordinate, usually the lower right corner of - // * the area of interest. - // */ - // public float getScale(Point2D ll1, Point2D ll2, Point2D point1, - // Point2D point2) { - // if (ll1 instanceof LatLonPoint && ll2 instanceof LatLonPoint) { - // return getScale(LatLonPoint.getDouble(ll1), - // LatLonPoint.getDouble(ll2), - // point1, - // point2); - // } - // - // return getScale(); - // } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll1 coordinate, the upper left corner of the area - * of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll2 coordinate, usually the lower right corner of - * the area of interest. - */ - public float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2) { - - try { - - double deltaDegrees; - double pixPerDegree; - //double deltaPix; - //double dx = Math.abs(point2.getX() - point1.getX()); - //double dy = Math.abs(point2.getY() - point1.getY()); - - // TODO: mercator getScale is wrong for screens in portrait mode, - // that is dx point2.getX()) { - lat1 = ll1.getY(); - lon1 = ll1.getX(); - ll1.setLocation(ll2); - ll2.setLocation(lon1, lat1); - } - - lon1 = ll1.getX(); - lon2 = ll2.getX(); - - // allow for crossing dateline - if (lon1 > lon2) { - dlon = (180 - lon1) + (180 + lon2); - } else { - dlon = lon2 - lon1; - } - - deltaDegrees = dlon; - //deltaPix = dx; - - // This might not be correct for all projection types - pixPerDegree = getPlanetPixelCircumference() / 360.0; - // } - - // The new scale, need it to match the current projection width. - return (float) (pixPerDegree / (getWidth() / deltaDegrees)); - } catch (NullPointerException npe) { - com.bbn.openmap.util.Debug.error("ProjMath.getScale(): caught null pointer exception."); - return Float.MAX_VALUE; - } - } - - /** - * Forward project a point. - */ - public Point2D forward(Point2D llp, Point2D pt) { - return forward(llp.getY(), llp.getX(), pt, false); - } - - /** - * Forward project a LatLonPoint. - *

- * Forward projects a LatLon point into XY space. Returns a Point. - * - * @param llp LatLonPoint to be projected - * @return Point (new) - */ - public Point2D forward(Point2D llp) { - return forward(llp.getY(), llp.getX(), new Point2D.Double(), false); - } - - /** - * Project the point into view space. - * - * @param lat latitude in decimal degrees. - * @param lon longitue in decimal degrees. - */ - public Point2D forward(double lat, double lon, Point2D pt) { - return forward(lat, lon, pt, false); - } - - /** - * Project the point into view space. - * - * @param lat latitude - * @param lon longitude - * @param pt return point - * @param isRadian true if lat/lon are radians instead of decimal degrees - * @return Point2D for projected point - */ - public Point2D forward(float lat, float lon, Point2D pt, boolean isRadian) { - return forward((double) lat, (double) lon, pt, isRadian); - } - - /** - * Project the point into view space. - * - * @param lat latitude - * @param lon longitude - * @param pt return point - * @param isRadian true if lat/lon are radians instead of decimal degrees - * @return Point2D for projected point - */ - abstract public Point2D forward(double lat, double lon, Point2D pt, boolean isRadian); - - /** - * Inverse project a Point from x,y space to LatLon space. - * - * @param point x,y Point - * @return LatLonPoint (new) - */ - public LatLonPoint inverse(Point2D point) { - return inverse(point.getX(), point.getY(), new LatLonPoint.Double()); - } - - /** - * Inverse project x,y coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @return LatLonPoint (new) - * @see #inverse(Point2D) - */ - public LatLonPoint inverse(double x, double y) { - return inverse(x, y, new LatLonPoint.Double()); - } - - /** - * Returns the Point2D provided if it is a LatLonPoint, otherwise it creates - * a LatLonPoint.Double and transfers the values from the provided Point2D - * object. - */ - protected LatLonPoint assertLatLonPoint(Point2D p2d) { - if (p2d instanceof LatLonPoint) { - return (LatLonPoint) p2d; - } else { - return new LatLonPoint.Double(p2d.getY(), p2d.getX()); - } - } - - /** - * Forward project a LatLon Line. - *

- * Returns a ArrayList of (x[], y[]) coordinate pair(s) of the projected - * line(s). - * - * - * RESTRICTIONS: - * A line segment must be less than 180 degrees of arc (half the - * circumference of the world). If you need to draw a longer line, then draw - * several several individual segments of less than 180 degrees, or draw a - * single polyline of those segments. - *

- * We make this restriction because from any point on a sphere, you can - * reach any other point with a maximum traversal of 180degrees of arc. - *

- * Furthermore, for the Cylindrical family of projections, a line must be - * < 180 degrees of arc in longitudinal extent. In other words, the - * difference of longitudes between both vertices must be < 180 degrees. - * Same as above: if you need a long line, you must break it into several - * segments. - * - * @param ll1 LatLonPoint - * @param ll2 LatLonPoint - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @return ArrayList int[] - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - * - */ - public ArrayList forwardLine(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs) { - double[] rawllpts = { ll1.getRadLat(), ll1.getRadLon(), ll2.getRadLat(), ll2.getRadLon() }; - return forwardPoly(rawllpts, ltype, nsegs, false); - } - - /** - * Forward project a lat/lon Line. - * - * @see #forwardLine(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardLine(LatLonPoint ll1, LatLonPoint ll2, int ltype) { - return forwardLine(ll1, ll2, ltype, -1); - } - - /** - * Forward project a rectangle defined by an upper left point and a lower - * right point. - *

- * Returns a ArrayList of (x[], y[]) coordinate pairs of the projected - * points. - *

- * Rects have the same restrictions as polys - * and lines . - * - * @param ll1 LatLonPoint of northwest corner - * @param ll2 LatLonPoint of southeast corner - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @see #forwardPoly - * @return ArrayList int[] - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs, - boolean isFilled) { - double[] rawllpts = { ll1.getRadLat(), ll1.getRadLon(), ll1.getRadLat(), ll2.getRadLon(), - ll2.getRadLat(), ll2.getRadLon(), ll2.getRadLat(), ll1.getRadLon(), - // connect: - ll1.getRadLat(), ll1.getRadLon() }; - return forwardPoly(rawllpts, ltype, nsegs, isFilled); - } - - /** - * Forward project a lat/lon Rectangle. - * - * @see #forwardRect(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype) { - return forwardRect(ll1, ll2, ltype, -1, false); - } - - /** - * Forward project a lat/lon Rectangle. * - * - * @param ll1 LatLonPoint of northwest corner - * @param ll2 LatLonPoint of southeast corner - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @see #forwardRect(LatLonPoint, LatLonPoint, int, int) - */ - public ArrayList forwardRect(LatLonPoint ll1, LatLonPoint ll2, int ltype, int nsegs) { - return forwardRect(ll1, ll2, ltype, nsegs, false); - } - - /** - * Forward project an arc. - * - * @param c LatLonPoint center - * @param radians boolean radius in radians? - * @param radius radius in radians or decimal degrees - * @param start the starting angle of the arc, zero being North up. Units - * are dependent on radians parameter - the start parameter is in - * radians if radians equals true, decimal degrees if not. - * @param extent the angular extent angle of the arc, zero being no length. - * Units are dependent on radians parameter - the extent parameter is - * in radians if radians equals true, decimal degrees if not. - */ - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, - double start, double extent) { - return forwardArc(c, radians, radius, -1, start, extent, java.awt.geom.Arc2D.OPEN); - } - - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, int nverts, - double start, double extent) { - return forwardArc(c, radians, radius, nverts, start, extent, java.awt.geom.Arc2D.OPEN); - } - - /** - * Forward project a Lat/Lon Arc. - *

- * Arcs have the same restrictions as polys - * . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - * @param start the starting angle of the arc, zero being North up. Units - * are dependent on radians parameter - the start parameter is in - * radians if radians equals true, decimal degrees if not. - * @param extent the angular extent angle of the arc, zero being no length. - * Units are dependent on radians parameter - the extent parameter is - * in radians if radians equals true, decimal degrees if not. - * @param arcType type of arc to create - see java.awt.geom.Arc2D for (OPEN, - * CHORD, PIE). Arc2D.OPEN means that the just the points for the - * curved edge will be provided. Arc2D.PIE means that addition lines - * from the edge of the curve to the center point will be added. - * Arc2D.CHORD means a single line from each end of the curve will be - * drawn. - */ - public ArrayList forwardArc(LatLonPoint c, boolean radians, double radius, int nverts, - double start, double extent, int arcType) { - // HACK-need better decision for number of vertices. - if (nverts < 3) - nverts = NUM_DEFAULT_CIRCLE_VERTS; - - double[] rawllpts; - - switch (arcType) { - case Arc2D.PIE: - rawllpts = new double[(nverts << 1) + 4];// *2 for pairs +4 - // connect - break; - case Arc2D.CHORD: - rawllpts = new double[(nverts << 1) + 2];// *2 for pairs +2 - // connect - break; - default: - rawllpts = new double[(nverts << 1)];// *2 for pairs, no - // connect - } - - GreatCircle.earthCircle(c.getRadLat(), c.getRadLon(), (radians) ? radius - : ProjMath.degToRad(radius), (radians) ? start : ProjMath.degToRad(start), (radians) ? extent - : ProjMath.degToRad(extent), nverts, rawllpts); - - int linetype = LineType.Straight; - boolean isFilled = false; - - switch (arcType) { - case Arc2D.PIE: - rawllpts[rawllpts.length - 4] = c.getRadLat(); - rawllpts[rawllpts.length - 3] = c.getRadLon(); - // Fall through... - case Arc2D.CHORD: - rawllpts[rawllpts.length - 2] = rawllpts[0]; - rawllpts[rawllpts.length - 1] = rawllpts[1]; - // Need to do this for the sides, not the arc part. - linetype = LineType.GreatCircle; - isFilled = true; - break; - default: - // Don't need to do anything, defaults are already set. - } - - // forward project the arc-poly. - return forwardPoly(rawllpts, linetype, -1, isFilled); - } - - /** - * Forward project a circle. - * - * @param c LatLonPoint center - * @param radians boolean radius in radians? - * @param radius radius in radians or decimal degrees - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius) { - return forwardCircle(c, radians, radius, -1, false); - } - - /** - * Forward project a Lat/Lon Circle. - *

- * Circles have the same restrictions as - * polys. . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius, - int nverts) { - return forwardCircle(c, radians, radius, nverts, false); - } - - /** - * Forward project a Lat/Lon Circle. - *

- * Circles have the same restrictions as - * polys. . - * - * @param c LatLonPoint center of circle - * @param radians radius in radians or decimal degrees? - * @param radius radius of circle (0 < radius < 180) - * @param nverts number of vertices of the circle poly. - * @param isFilled filled poly? - */ - public ArrayList forwardCircle(LatLonPoint c, boolean radians, double radius, - int nverts, boolean isFilled) { - // HACK-need better decision for number of vertices. - if (nverts < 3) - nverts = NUM_DEFAULT_CIRCLE_VERTS; - - double[] rawllpts = new double[(nverts << 1) + 2];// *2 for - // pairs +2 - // connect - GreatCircle.earthCircle(c.getRadLat(), c.getRadLon(), (radians) ? radius - : ProjMath.degToRad(radius), nverts, rawllpts); - // connect the vertices. - rawllpts[rawllpts.length - 2] = rawllpts[0]; - rawllpts[rawllpts.length - 1] = rawllpts[1]; - - // forward project the circle-poly - return forwardPoly(rawllpts, LineType.Straight, -1, isFilled); - } - - // HACK - protected transient static int XTHRESHOLD = 16384;// half range - protected transient int XSCALE_THRESHOLD = 1000000;// dynamically - - /** - * Forward project a LatLon Poly. - *

- * Returns a ArrayList of (x[], y[]) coordinate pair(s) of the projected - * poly. - * - * RESTRICTIONS: - * All the following restrictions apply to LatLon polygons (either - * filled or non-filled). Many of these restrictions apply to other - * poly-like ArrayList graphics (Lines, Rectangles, Circles, Ellipses, ...). - * See also restrictions on LatLon lines. - *

- * For the cylindrical projections, (e.g. - * Mercator), your polygons should not include or touch the poles. This is - * because a polygon or polyline that includes a pole becomes a - * non-continuous straight line on the map. "So what about Antarctica", you - * say, "after all it's a polygon that is draped over the South Pole". Well, - * if you want to see it in a cylindrical projection, you will need to - * "augment" the vertices to turn it into a valid x-y polygon. You could do - * this by removing the segment which crosses the dateline, and instead add - * two extra edges down along both sides of the dateline to very near the - * south pole and then connect these ends back the other way around the - * world (not across the dateline) with a few extra line segments (remember - * the line length restrictions ). This way - * you've removed the polar anomaly from the data set. On the screen, all - * you see is a sliver artifact down along the dateline. This is the very - * method that our DCW data server shows Antarctica. - *

- * There is a fundamental ambiguity with filled polygons on a sphere: which - * side do you draw the fill-color? The Cylindrical family will draw the - * polygon as if it were in x-y space. For the Azimuthal projections, (e.g. - * Orthographic), you can have polygons that cover the pole, but it's - * important to specify the vertices in a clockwise order so that we can do - * the correct clipping along the hemisphere edge. We traverse the vertices - * assuming that the fill will be to the right hand side if the polygon - * straddles the edge of the projection. (This default can be changed). - *

- *

To Be (Mostly) Safe:

- *
    - *
  • Polygons should not touch or encompass the poles unless you will be - * viewing them with azimuthal projections, such as Orthographic.
    - *
  • Polygons should not encompass more area than one hemisphere.
    - *
  • Polygon vertices should be specified in "clockwise", fill-on-right - * order to ensure proper filling.
    - *
  • Polygon edges are also restricted by the restrictions on LatLon lines . - *
- *

- *

Optimization Notes:

- * The projection library deals internally in radians, and so you're - * required to pass in an array of radian points. See - * ProjMath.arrayDegToRad(float[]) for an efficient in-place - * conversion. - *

- * For no-frills, no-assumptions, fast and efficient projecting, see forwardRaw() . - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled poly is filled? or not - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardPoly(float[] rawllpts, int ltype, int nsegs, boolean isFilled) { - ArrayList stuff = _forwardPoly(rawllpts, ltype, nsegs, isFilled); - // @HACK: workaround XWindows bug. simple clip to a boundary. - // this is ugly. - if (Environment.doingXWindowsWorkaround && (scale <= XSCALE_THRESHOLD)) { - int i, j, size = stuff.size(); - float[] xpts, ypts; - for (i = 0; i < size; i += 2) { - xpts = (float[]) stuff.get(i); - ypts = (float[]) stuff.get(i + 1); - for (j = 0; j < xpts.length; j++) { - if (xpts[j] <= -XTHRESHOLD) { - xpts[j] = -XTHRESHOLD; - } else if (xpts[j] >= XTHRESHOLD) { - xpts[j] = XTHRESHOLD; - } - if (ypts[j] <= -XTHRESHOLD) { - ypts[j] = -XTHRESHOLD; - } else if (ypts[j] >= XTHRESHOLD) { - ypts[j] = XTHRESHOLD; - } - } - stuff.set(i, xpts); - stuff.set(i + 1, ypts); - } - } - return stuff; - } - - /** - * Forward project a lat/lon Poly. - *

- * Delegates to _forwardPoly(), and may do additional clipping for Java - * XWindows problem. Remember to specify vertices in radians! - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardPoly(double[] rawllpts, int ltype, int nsegs, boolean isFilled) { - ArrayList stuff = _forwardPoly(rawllpts, ltype, nsegs, isFilled); - // @HACK: workaround XWindows bug. simple clip to a boundary. - // this is ugly. - if (Environment.doingXWindowsWorkaround && (scale <= XSCALE_THRESHOLD)) { - int i, j, size = stuff.size(); - float[] xpts, ypts; - for (i = 0; i < size; i += 2) { - xpts = stuff.get(i); - ypts = stuff.get(i + 1); - for (j = 0; j < xpts.length; j++) { - if (xpts[j] <= -XTHRESHOLD) { - xpts[j] = -XTHRESHOLD; - } else if (xpts[j] >= XTHRESHOLD) { - xpts[j] = XTHRESHOLD; - } - if (ypts[j] <= -XTHRESHOLD) { - ypts[j] = -XTHRESHOLD; - } else if (ypts[j] >= XTHRESHOLD) { - ypts[j] = XTHRESHOLD; - } - } - stuff.set(i, xpts); - stuff.set(i + 1, ypts); - } - } - return stuff; - } - - /** - * Forward project a lat/lon Poly defined as decimal degree lat/lons. - *

- * Delegates to _forwardPoly(), and may do additional clipping for Java - * XWindows problem. Remember to specify vertices in decimal degrees. If you - * have radians, use them and call forwardPoly, it's faster. This method - * will convert the coords to radians before calling the fowardPoly method. - * - * @param llpts double[] of lat,lon,lat,lon,... in decimal degree lat/lon! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - * @see #forwardRaw - * @see LineType#Straight - * @see LineType#Rhumb - * @see LineType#GreatCircle - */ - public ArrayList forwardLLPoly(double[] llpts, int ltype, int nsegs, boolean isFilled) { - double[] rawllpts = new double[llpts.length]; - System.arraycopy(llpts, 0, rawllpts, 0, llpts.length); - ProjMath.arrayDegToRad(rawllpts); - return forwardPoly(rawllpts, ltype, nsegs, isFilled); - } - - /** - * Forward project a lat/lon Poly. Remember to specify vertices in radians! - * - * @param rawllpts float[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - */ - protected abstract ArrayList _forwardPoly(float[] rawllpts, int ltype, int nsegs, - boolean isFilled); - - /** - * Forward project a lat/lon Poly. Remember to specify vertices in radians! - * - * @param rawllpts double[] of lat,lon,lat,lon,... in RADIANS! - * @param ltype line type (straight, rhumbline, greatcircle) - * @param nsegs number of segment points (only for greatcircle or rhumbline - * line types, and if < 1, this value is generated internally) - * @param isFilled filled poly? - * @return ArrayList of x[], y[], x[], y[], ... projected poly - */ - protected abstract ArrayList _forwardPoly(double[] rawllpts, int ltype, int nsegs, - boolean isFilled); - - /** - * Get the unprojected coordinates units of measure. - * - * @return Length.DECIMAL_DEGREE - */ - public Length getUcuom() { - return Length.DECIMAL_DEGREE; - } - - /** - * Can't set the unprojected coordinates units of measure for a GeoProj, - * it's always Length.DECIMAL_DEGREE. - * - * @param ucuom - */ - public void setUcuom(Length ucuom) { - // no-op - } - - /** - * Convenience method to create a GCT for this projection. For projections - * that start with lat/lon coordinates, this will return a LatLonGCT. For - * projections that have world coordinates in meters, the GCT will provide a - * way to get to those meter coordinates. For instance, a UTMProjection will - * return a UTMGCT. - * - * @return GeoCoordTransformation for this projection - */ - @SuppressWarnings("unchecked") - public T getGCTForProjection() { - return (T) new LatLonGCT(); - } - - /** - * @return the reference longitude of the projection. For most projections, - * it'll just be the center point longitude. For LLC, it'll be the - * reference meridian. - */ - public double getReferenceLon() { - return getCenter().getX(); - } - -} diff --git a/src/openmap/com/bbn/openmap/proj/Proj.java b/src/openmap/com/bbn/openmap/proj/Proj.java deleted file mode 100644 index bba621fed..000000000 --- a/src/openmap/com/bbn/openmap/proj/Proj.java +++ /dev/null @@ -1,1010 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/Proj.java,v $ -// $RCSfile: Proj.java,v $ -// $Revision: 1.14 $ -// $Date: 2009/01/21 01:24:41 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; - -import com.bbn.openmap.util.Debug; - -/** - * Proj is the base class of all Projections. - *

- * You probably don't want to use this class unless you are hacking your own - * projections, or need extended functionality. To be safe you will want to use - * the Projection interface. - * - *

Notes:

- * - *
    - * - *
  • There are no assumption made as to the units of the values provided to - * the projection, each projection type has its own interpretation of what the - * values are. - * - *
  • The order of coordinate parameters changes, depending on the convention - * of the superclass object of the one being referred to. Coordinate tuples - * referring to projected coordinates are generally x, y, those referring to - * unprojected coordinates are y, x (lat/lon). - * - *
  • This class is not thread safe. If two or more threads are using the same - * Proj, then they could disrupt each other. Occasionally you may need to call a - * set method of this class. This might interfere with another - * thread that's using the same projection for forwardPoly or - * another Projection interface method. In general, you should not need to call - * any of the set methods directly, but let the MapBean do it for - * you. - * - *
  • All the various forwardOBJ() methods for ArrayList graphics - * ultimately go through forwardPoly(). - * - *
- * - * @see Cartesian - * @see GeoProj - * - */ -public abstract class Proj implements Projection, Cloneable, Serializable { - - /** - * Minimum width of projection. - */ - public final static transient int MIN_WIDTH = 10; // pixels - - /** - * Minimum height of projection. - */ - public final static transient int MIN_HEIGHT = 10; // pixels - - protected int width = 640, height = 480; - protected double minscale = 1.0; // 1:minscale - protected double maxscale = Double.MAX_VALUE; - protected double scale = maxscale; - protected double centerX; - protected double centerY; - protected String projID = null; // identifies this projection (if needed) - /** - * The rotation angle of the map is stored here so that non-rotating things - * can correct themselves. Is not used for equality checks. - */ - protected double rotationAngle = 0; - - /** - * The unprojected coordinates units of measure. - */ - protected Length ucuom = null; - - /** - * Construct a projection. - * - * @param center LatLonPoint center of projection - * @param s float scale of projection - * @param w width of screen - * @param h height of screen - * @see ProjectionFactory - */ - public Proj(Point2D center, float s, int w, int h) { - if (Debug.debugging("proj")) { - Debug.output("Proj()"); - } - - setParms(center, s, w, h); - projID = null; - - } - - /** - * Set the scale of the projection. - *

- * Sets the projection to the scale 1:s iff minscale < s < maxscale. - *
- * If s < minscale, sets the projection to minscale.
- * If s > maxscale, sets the projection to maxscale.
- * - * @param s float scale - */ - public void setScale(float s) { - scale = s; - if (scale < minscale) { - scale = minscale; - } else if (scale > maxscale) { - scale = maxscale; - } - computeParameters(); - projID = null; - } - - /** - * Set the minscale of the projection. - *

- * Usually you will not need to do this. - * - * @param s float minscale - */ - public void setMinScale(float s) { - if (s > maxscale) - return; - - minscale = s; - if (scale < minscale) { - scale = minscale; - } - computeParameters(); - projID = null; - } - - /** - * Set the maximum scale of the projection. - *

- * Usually you will not need to do this. - * - * @param s float minscale - */ - public void setMaxScale(float s) { - if (s < minscale) - return; - - maxscale = s; - if (scale > maxscale) { - scale = maxscale; - } - computeParameters(); - projID = null; - } - - /** - * Get the scale of the projection. - * - * @return double scale value - */ - public float getScale() { - return (float) scale; - } - - /** - * Get the maximum scale of the projection. - * - * @return double max scale value - */ - public float getMaxScale() { - return (float) maxscale; - } - - /** - * Get minimum scale of the projection. - * - * @return double min scale value - */ - public float getMinScale() { - return (float) minscale; - } - - /** - * Set center point of projection. - * - * @param pt Point2D for center. Point2D values will be copied. - */ - public void setCenter(Point2D pt) { - setCenter(pt.getY(), pt.getX()); - } - - /** - * Set center point of projection. - * - * @param y vertical value of center. - * @param x horizontal value of center. - */ - public void setCenter(double y, double x) { - // Since we need to re-run computeParameters and the projID, - // we better make a clone of the center, so whoever sets the - // center can't change it by simply changing the center's - // parameters without recalculating the parameters. - centerX = x; - centerY = y; - computeParameters(); - projID = null; - } - - /** - * Get center point of projection. - * - * @return Point2D center of projection, created just for you. - */ - public Point2D getCenter() { - return getCenter(new Point2D.Double()); - } - - /** - * Returns a center Point2D that was provided, with the location filled into - * the Point2D object. Calls Point2D.setLocation(x, y). - */ - public T getCenter(T center) { - center.setLocation(centerX, centerY); - return center; - } - - /** - * Set projection width. - * - * @param width width of projection screen - */ - public void setWidth(int width) { - this.width = width; - - if (this.width < MIN_WIDTH) { - Debug.message("proj", "Proj.setWidth: width too small!"); - this.width = MIN_WIDTH; - } - computeParameters(); - projID = null; - } - - /** - * Set projection height. - * - * @param height height of projection screen - */ - public void setHeight(int height) { - this.height = height; - if (this.height < MIN_HEIGHT) { - Debug.message("proj", "Proj.setHeight: height too small!"); - this.height = MIN_HEIGHT; - } - computeParameters(); - projID = null; - } - - /** - * Get projection width. - * - * @return width of projection screen - */ - public int getWidth() { - return width; - } - - /** - * Get projection height. - * - * @return height of projection screen - */ - public int getHeight() { - return height; - } - - /** - * Sets all the projection variables at once before calling - * computeParameters(). - * - * @param center LatLonPoint center - * @param scale float scale - * @param width width of screen - * @param height height of screen - */ - protected void setParms(Point2D center, float scale, int width, int height) { - centerX = center.getX(); - centerY = center.getY(); - this.scale = scale; - - this.width = width; - if (this.width < MIN_WIDTH) { - Debug.message("proj", "Proj.setParms: width too small!"); - this.width = MIN_WIDTH; - } - this.height = height; - if (this.height < MIN_HEIGHT) { - Debug.message("proj", "Proj.setParms: height too small!"); - this.height = MIN_HEIGHT; - } - - init(); - - if (this.scale < minscale) { - this.scale = minscale; - } else if (this.scale > maxscale) { - this.scale = maxscale; - } - - computeParameters(); - projID = null; - } - - /** - * Called after the center and scale is set in setParams, but before the - * scale is checked for legitimacy. This is an opportunity to set constants - * in subclasses before anything else gets called or checked for validity. - * This is different than computeParameters() which is called after some - * checks. This is a good time to pre-calculate constants and set maxscale - * and minscale. - *

- * Make sure you call super.init() if you override this method. - */ - protected void init() { - } - - /** - * Sets the projection ID used for determining equality. The projection ID - * String is interned for efficient comparison. - */ - protected void setProjectionID() { - projID = (getClass().getName() + ":" + scale + ":" + centerX + ":" + centerY + ":" + width - + ":" + height + ":" + rotationAngle); - } - - /** - * Gets the projection ID used for determining equality. - * - * @return the projection ID, as an intern()ed String - */ - public String getProjectionID() { - if (projID == null) - setProjectionID(); - return projID; - } - - /** - * Called when some fundamental parameters change. - *

- * Each projection will decide how to respond to this change. For instance, - * they may need to recalculate "constant" parameters used in the forward() - * and inverse() calls. - */ - protected abstract void computeParameters(); - - /** - * Stringify the projection. - * - * @return stringified projection - * @see #getProjectionID - */ - public String toString() { - return (" center(" + centerX + ":" + centerY + ") scale=" + scale + " maxscale=" + maxscale - + " minscale=" + minscale + " width=" + width + " height=" + height + "]"); - } - - /** - * Test for equality. - * - * @param o Object to compare. - * @return boolean comparison - */ - public boolean equals(Object o) { - if (o == null) - return false; - if (getClass() != o.getClass()) { - return false; - } - return getProjectionID().equals(((Projection) o).getProjectionID()); - } - - /** - * Return hashcode value of projection. - * - * @return int hashcode - */ - public int hashCode() { - return getProjectionID().hashCode(); - } - - /** - * Clone the projection. - * - * @return Projection clone of this one. - */ - public Projection makeClone() { - return (Projection) this.clone(); - } - - /** - * Copies this projection. - * - * @return a copy of this projection. - */ - public Object clone() { - try { - return (Proj) super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } - } - - /** - * Forward project a LatLonPoint. - *

- * Forward projects a LatLon point into XY space. Returns a Point2D. - * - * @param llp LatLonPoint to be projected - * @return Point2D (new) - */ - public Point2D forward(Point2D llp) { - return forward(llp.getY(), llp.getX(), new Point2D.Float()); - } - - /** - * Forward projects a LatLonPoint into XY space and return a - * java.awt.geom.Point2D. - * - * @param llp LatLonPoint to be projected - * @param pt Resulting XY Point2D - * @return Point2D pt - */ - public Point2D forward(Point2D llp, Point2D pt) { - return forward(llp.getY(), llp.getX(), pt); - } - - /** - * Forward project lat,lon coordinates. - * - * @param lat float latitude in decimal degrees - * @param lon float longitude in decimal degrees - * @return Point2D (new) - */ - public Point2D forward(float lat, float lon) { - return forward((double) lat, (double) lon, new Point2D.Float()); - } - - public Point2D forward(float lat, float lon, Point2D pt) { - return forward((double) lat, (double) lon, pt); - } - - public Point2D forward(double lat, double lon) { - return forward(lat, lon, new Point2D.Double()); - } - - public abstract Point2D forward(double lat, double lon, Point2D pt); - - public T inverse(Point2D point, T llpt) { - return inverse(point.getX(), point.getY(), llpt); - } - - /** - * Inverse project a Point2D from x,y space to coordinate space. - * - * @param point x,y Point2D - * @return LatLonPoint (new) - */ - public Point2D inverse(Point2D point) { - return inverse(point.getX(), point.getY(), new Point2D.Double()); - } - - /** - * Inverse project x,y coordinates. - * - * @param x integer x coordinate - * @param y integer y coordinate - * @return LatLonPoint (new) - * @see #inverse(Point2D) - */ - public Point2D inverse(double x, double y) { - return inverse(x, y, new Point2D.Double()); - } - - public abstract T inverse(double x, double y, T llpt); - - /** - * Simple shape inverse projection, converts the x,y values in the shape to - * the x, y values of the projection. - * - * @param shape projected shape. - * @return Shape containing source coordinates inversely projected. - */ - public Shape inverseShape(Shape shape) { - PathIterator pi = shape.getPathIterator(null); - double[] coords = new double[6]; - Point2D world = new Point2D.Double(); - Point2D world2 = new Point2D.Double(); - Point2D world3 = new Point2D.Double(); - Point2D screen = new Point2D.Double(); - Point2D screen2 = new Point2D.Double(); - Point2D screen3 = new Point2D.Double(); - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - screen.setLocation(coords[0], coords[1]); - inverse(screen, world); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(world.getX(), world.getY()); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(world.getX(), world.getY()); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - screen2.setLocation(coords[2], coords[3]); - inverse(screen2, world2); - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(world.getX(), world.getY(), world2.getX(), world2.getY()); - } else if (type == PathIterator.SEG_CUBICTO) { - screen3.setLocation(coords[4], coords[5]); - inverse(screen3, world3); - path.curveTo(world.getX(), world.getY(), world2.getX(), world2.getY(), world3.getX(), world3.getY()); - } - } - - pi.next(); - } - - return path; - } - - /** - * Simple shape projection, doesn't take into account what kind of lines - * should be drawn between shape points, assumes they should be 2D lines as - * rendered in 2D space, not interpolated for accuracy as Great Circle/Rhumb - * lines on a globe.. - */ - public Shape forwardShape(Shape shape) { - PathIterator pi = shape.getPathIterator(null); - double[] coords = new double[6]; - Point2D world = new Point2D.Double(); - Point2D world2 = new Point2D.Double(); - Point2D world3 = new Point2D.Double(); - Point screen = new Point(); - Point screen2 = new Point(); - Point screen3 = new Point(); - - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - - while (!pi.isDone()) { - int type = pi.currentSegment(coords); - - world.setLocation(coords[0], coords[1]); - forward(world, screen); - - if (type == PathIterator.SEG_MOVETO) { - path.moveTo(screen.x, screen.y); - } else if (type == PathIterator.SEG_LINETO) { - path.lineTo(screen.x, screen.y); - } else if (type == PathIterator.SEG_CLOSE) { - path.closePath(); - } else { - world2.setLocation(coords[2], coords[3]); - forward(world2, screen2); - if (type == PathIterator.SEG_QUADTO) { - path.quadTo(screen.x, screen.y, screen2.x, screen2.y); - } else if (type == PathIterator.SEG_CUBICTO) { - world3.setLocation(coords[4], coords[5]); - forward(world3, screen3); - path.curveTo(screen.x, screen.y, screen2.x, screen2.y, screen3.x, screen3.y); - } - } - - pi.next(); - } - - return path; - } - - /** - * Forward project a raw array of points. This assumes nothing about the - * array of coordinates. In no way does it assume the points are connected - * or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of y, x world coordinates. - * @param rawoff offset into rawllpts. - * @param xcoords x projected horizontal map coordinates. - * @param ycoords y projected vertical map coordinates. - * @param visible coordinates visible? - * @param copyoff offset into x,y visible arrays. - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(float[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, - boolean[] visible, int copyoff, int copylen) { - Point temp = new Point(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - visible[i] = true; - } - return true; - } - - /** - * Forward project a raw array of points. This assumes nothing about the - * array of coordinates. In no way does it assume the points are connected - * or that the composite figure is to be filled. - *

- * It does populate a visible array indicating whether the points are - * visible on the projected view of the world. - *

- * - * @param rawllpts array of y, x world coordinates. - * @param rawoff offset into rawllpts. - * @param xcoords x projected horizontal map coordinates. - * @param ycoords y projected vertical map coordinates. - * @param visible coordinates visible? - * @param copyoff offset into x,y visible arrays. - * @param copylen number of coordinates (coordinate arrays should be at - * least this long, rawllpts should be at least twice as long). - * @return boolean true if all points visible, false if some points not - * visible. - */ - public boolean forwardRaw(double[] rawllpts, int rawoff, float[] xcoords, float[] ycoords, - boolean[] visible, int copyoff, int copylen) { - Point temp = new Point(); - int end = copylen + copyoff; - for (int i = copyoff, j = rawoff; i < end; i++, j += 2) { - forward(rawllpts[j], rawllpts[j + 1], temp); - xcoords[i] = temp.x; - ycoords[i] = temp.y; - visible[i] = true; - } - return true; - } - - public ArrayList forwardLine(Point2D ll1, Point2D ll2) { - double[] rawllpts = { ll1.getY(), ll1.getX(), ll2.getY(), ll2.getX() }; - return forwardPoly(rawllpts, false); - } - - /** - * Forward project a rectangle. - * - * @param ll1 LatLonPoint - * @param ll2 LatLonPoint - * @return ArrayList - */ - public ArrayList forwardRect(Point2D ll1, Point2D ll2) { - double[] rawllpts = { ll1.getY(), ll1.getX(), ll1.getY(), ll2.getX(), ll2.getY(), - ll2.getX(), ll2.getY(), ll1.getX(), - // connect: - ll1.getY(), ll1.getX() }; - return forwardPoly(rawllpts, true); - } - - public ArrayList forwardPoly(float[] rawllpts, boolean isFilled) { - // For regular OMGraphics, some of the rawllpts are in radians and must - // be translated into decimal degrees before they really are able to be - // displayed here, i.e.: - // wx = Math.toDegrees(wx); - // wy = Math.toDegrees(wy); - - int n, k; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp); - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp); - xs[n] = temp.x; - ys[n] = temp.y; - } - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - - return ret_val; - } - - public ArrayList forwardPoly(double[] rawllpts, boolean isFilled) { - int n, k; - - // determine length of pairs list - int len = rawllpts.length >> 1; // len/2, chop off extra - if (len < 2) - return new ArrayList(0); - - // determine when to stop - Point temp = new Point(0, 0); - float[] xs = new float[len]; - float[] ys = new float[len]; - - // forward project the first point - forward(rawllpts[0], rawllpts[1], temp); - xs[0] = temp.x; - ys[0] = temp.y; - // forward project the other points - for (n = 1, k = 2; n < len; n++, k += 2) { - forward(rawllpts[k], rawllpts[k + 1], temp); - xs[n] = temp.x; - ys[n] = temp.y; - } - - // now create the return list - ArrayList ret_val = null; - ret_val = new ArrayList(2); - ret_val.add(xs); - ret_val.add(ys); - return ret_val; - } - - /** - * Pan the map/projection. - *

- * Example pans: - *

    - *
  • pan(180, c) pan south `c' degrees - *
  • pan(-90, c) pan west `c' degrees - *
  • pan(0, c) pan north `c' degrees - *
  • pan(90, c) pan east `c' degrees - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - * @param c arc distance in decimal degrees - */ - abstract public void pan(double Az, double c); - - /** - * Pan the map/projection. - *
    - *
  • pan(180, c) pan south - *
  • pan(-90, c) pan west - *
  • pan(0, c) pan north - *
  • pan(90, c) pan east - *
- * - * @param Az azimuth "east of north" in decimal degrees: - * -180 <= Az <= 180 - */ - abstract public void pan(double Az); - - /** - * pan the map northwest. - */ - final public void panNW() { - pan(-45f); - } - - final public void panNW(double c) { - pan(-45f); - } - - /** - * pan the map north. - */ - final public void panN() { - pan(0f); - } - - final public void panN(double c) { - pan(0f); - } - - /** - * pan the map northeast. - */ - final public void panNE() { - pan(45f); - } - - final public void panNE(double c) { - pan(45f); - } - - /** - * pan the map east. - */ - final public void panE() { - pan(90f); - } - - final public void panE(double c) { - pan(90f); - } - - /** - * pan the map southeast. - */ - final public void panSE() { - pan(135f); - } - - final public void panSE(double c) { - pan(135f); - } - - /** - * pan the map south. - */ - final public void panS() { - pan(180f); - } - - final public void panS(double c) { - pan(180f); - } - - /** - * pan the map southwest. - */ - final public void panSW() { - pan(-135f); - } - - final public void panSW(double c) { - pan(-135f); - } - - /** - * pan the map west. - */ - final public void panW() { - pan(-90f); - } - - final public void panW(double c) { - pan(-90f); - } - - /** - */ - public boolean isPlotable(double lat, double lon) { - return isPlotable(lat, lon); - } - - public boolean isPlotable(Point2D point) { - return isPlotable(point.getY(), point.getX()); - } - - /** - * Draw the background for the projection. - * - * @param g Graphics2D - * @param paint java.awt.Paint to use for the background - */ - public void drawBackground(Graphics2D g, java.awt.Paint paint) { - g.setPaint(paint); - drawBackground(g); - } - - /** - * Draw the background for the projection. Assume that the Graphics has been - * set with the Paint/Color needed, just render the shape of the background. - * - * @param g Graphics - */ - public void drawBackground(Graphics g) { - g.fillRect(0, 0, getWidth(), getHeight()); - } - - /** - * Get the name string of the projection. - */ - public String getName() { - return "Proj"; - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll1 coordinate, the upper left corner - * of the area of interest. Note that this is the location where you - * want ll1 to go in the new projection scale, not where it is now. - * @param point2 a java.awt.geom.Point2D reflecting a pixel spot on the - * projection that matches the ll2 coordinate, usually the lower - * right corner of the area of interest. Note that this is the - * location where you want ll2 to go in the new projection, not where - * it is now. - */ - public abstract float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2); - - /** - * Overridden to ensure that setParameters() are called with the read - * values. - * - * @param in - * @throws IOException - * @throws ClassNotFoundException - */ - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - computeParameters(); - projID = null; - } - - /** - * Get the unprojected coordinates units of measure. - * - * @return Length. May be null if unknown. - * @see Length - */ - public Length getUcuom() { - return ucuom; - } - - /** - * Set the unprojected coordinates units of measure. - * - * @param ucuom - */ - public void setUcuom(Length ucuom) { - this.ucuom = ucuom; - } - - /** - * Get the world coordinate of the upper left corner of the map. - */ - public Point2D getUpperLeft() { - return inverse(0, 0, new Point2D.Double()); - } - - /** - * Get the world coordinate of the lower right corner of the map. - */ - public Point2D getLowerRight() { - return inverse(width, height, new Point2D.Double()); - } - - /** - * @return the rotationAngle - */ - public double getRotationAngle() { - return rotationAngle; - } - - /** - * This setting is purely for informational purposes, as a way for the - * projection to pass along any rotation activity of the MapBean to - * OMGraphics. Setting this value will not rotate the map. Rotating the map - * should be done directly to the MapBean. - * - * @param rotationAngle the rotationAngle to set, in RADIANS - */ - public void setRotationAngle(double rotationAngle) { - this.rotationAngle = rotationAngle; - } - -} diff --git a/src/openmap/com/bbn/openmap/proj/ProjMath.java b/src/openmap/com/bbn/openmap/proj/ProjMath.java deleted file mode 100644 index e38f62649..000000000 --- a/src/openmap/com/bbn/openmap/proj/ProjMath.java +++ /dev/null @@ -1,796 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/proj/ProjMath.java,v $ -// $RCSfile: ProjMath.java,v $ -// $Revision: 1.9 $ -// $Date: 2007/06/21 21:39:02 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.proj; - -import java.awt.Point; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; - -import com.bbn.openmap.MoreMath; -import com.bbn.openmap.geo.Geo; - -/** - * Math functions used by projection code. - */ -public final class ProjMath { - - /** - * North pole latitude in radians. - */ - public final static transient float NORTH_POLE_F = MoreMath.HALF_PI; - - /** - * South pole latitude in radians. - */ - public final static transient float SOUTH_POLE_F = -NORTH_POLE_F; - - /** - * North pole latitude in radians. - */ - public final static transient double NORTH_POLE_D = MoreMath.HALF_PI_D; - - /** - * North pole latitude in degrees. - */ - public final static transient double NORTH_POLE_DEG_D = 90d; - - /** - * South pole latitude in radians. - */ - public final static transient double SOUTH_POLE_D = -NORTH_POLE_D; - - /** - * South pole latitude in degrees. - */ - public final static transient double SOUTH_POLE_DEG_D = -NORTH_POLE_DEG_D; - - /** - * Dateline longitude in radians. - */ - public final static transient float DATELINE_F = (float) Math.PI; - - /** - * Dateline longitude in radians. - */ - public final static transient double DATELINE_D = Math.PI; - - /** - * Dateline longitude in degrees. - */ - public final static transient double DATELINE_DEG_D = 180d; - - /** - * Longitude range in radians. - */ - public final static transient float LON_RANGE_F = (float) MoreMath.TWO_PI; - - /** - * Longitude range in radians. - */ - public final static transient double LON_RANGE_D = MoreMath.TWO_PI_D; - - /** - * Longitude range in degrees. - */ - public final static transient double LON_RANGE_DEG_D = 360d; - - // cannot construct - private ProjMath() { - } - - /** - * rounds the quantity away from 0. - * - * @param x in value - * @return double - * @see #qint(double) - */ - public final static double roundAdjust(double x) { - return qint_old(x); - } - - /** - * Rounds the quantity away from 0. - * - * @param x value - * @return double - */ - public final static double qint(double x) { - return qint_new(x); - } - - final private static double qint_old(double x) { - return (((int) x) < 0) ? (x - 0.5) : (x + 0.5); - } - - final private static double qint_new(double x) { - // -1 or +1 away from zero - return (x <= 0.0) ? (x - 1.0) : (x + 1.0); - } - - /** - * Calculate the shortest arc distance between two lons. - * - * @param lon1 radians - * @param lon2 radians - * @return float distance - */ - public final static float lonDistance(float lon1, float lon2) { - return (float) Math.min(Math.abs(lon1 - lon2), ((lon1 < 0) ? lon1 + Math.PI : Math.PI - - lon1) - + ((lon2 < 0) ? lon2 + Math.PI : Math.PI - lon2)); - } - - /** - * Convert between decimal degrees and scoords. - * - * @param deg degrees - * @return long scoords - * - */ - public final static long DEG_TO_SC(double deg) { - return (long) (deg * 3600000); - } - - /** - * Convert between decimal degrees and scoords. - * - * @param sc scoords - * @return double decimal degrees - */ - public final static double SC_TO_DEG(int sc) { - return ((double) (sc) / (60.0 * 60.0 * 1000.0)); - } - - /** - * Convert radians to degrees. - * - * @param rad radians - * @return double decimal degrees - */ - public final static double radToDeg(double rad) { - return Math.toDegrees(rad); - } - - /** - * Convert radians to degrees. - * - * @param rad radians - * @return float decimal degrees - */ - public final static float radToDeg(float rad) { - return (float) Math.toDegrees((double) rad); - } - - /** - * Convert degrees to radians. - * - * @param deg degrees - * @return double radians - */ - public final static double degToRad(double deg) { - return Math.toRadians(deg); - } - - /** - * Convert degrees to radians. - * - * @param deg degrees - * @return float radians - */ - public final static float degToRad(float deg) { - return (float) Math.toRadians((double) deg); - } - - /** - * Generate a hashCode value for a lat/lon pair. - * - * @param lat latitude - * @param lon longitude - * @return int hashcode - * - */ - public final static int hashLatLon(float lat, float lon) { - if (lat == -0f) - lat = 0f;// handle negative zero (anything else?) - if (lon == -0f) - lon = 0f; - int tmp = Float.floatToIntBits(lat); - int hash = (tmp << 5) | (tmp >> 27);// rotate the lat bits - return hash ^ Float.floatToIntBits(lon);// XOR with lon - } - - /** - * Converts an array of decimal degrees float lat/lons to float radians in - * place. - * - * @param degs float[] lat/lons in decimal degrees - * @return float[] lat/lons in radians - */ - public final static float[] arrayDegToRad(float[] degs) { - for (int i = 0; i < degs.length; i++) { - degs[i] = degToRad(degs[i]); - } - return degs; - } - - /** - * Converts an array of radian float lat/lons to decimal degrees in place. - * - * @param rads float[] lat/lons in radians - * @return float[] lat/lons in decimal degrees - */ - public final static float[] arrayRadToDeg(float[] rads) { - for (int i = 0; i < rads.length; i++) { - rads[i] = radToDeg(rads[i]); - } - return rads; - } - - /** - * Converts an array of decimal degrees double lat/lons to double radians in - * place. - * - * @param degs double[] lat/lons in decimal degrees - * @return double[] lat/lons in radians - */ - public final static double[] arrayDegToRad(double[] degs) { - for (int i = 0; i < degs.length; i++) { - degs[i] = degToRad(degs[i]); - } - return degs; - } - - /** - * Converts an array of radian double lat/lons to decimal degrees in place. - * - * @param rads double[] lat/lons in radians - * @return double[] lat/lons in decimal degrees - */ - public final static double[] arrayRadToDeg(double[] rads) { - for (int i = 0; i < rads.length; i++) { - rads[i] = radToDeg(rads[i]); - } - return rads; - } - - /** - * @deprecated use normalizeLatitude instead. - */ - public final static float normalize_latitude(float lat, float epsilon) { - return normalizeLatitude(lat, epsilon); - } - - /** - * Normalizes radian latitude. Normalizes latitude if at or exceeds epsilon - * distance from a pole. - * - * @param lat float latitude in radians - * @param epsilon epsilon (>= 0) radians distance from pole - * @return float latitude (-PI/2 <= phi <= PI/2) - * @see com.bbn.openmap.proj.coords.LatLonPoint#normalizeLatitude(double) - */ - public final static float normalizeLatitude(float lat, float epsilon) { - if (lat > NORTH_POLE_F - epsilon) { - return NORTH_POLE_F - epsilon; - } else if (lat < SOUTH_POLE_F + epsilon) { - return SOUTH_POLE_F + epsilon; - } - return lat; - } - - /** - * @deprecated use normalizeLatitude instead. - */ - public final static double normalize_latitude(double lat, double epsilon) { - return normalizeLatitude(lat, epsilon); - } - - /** - * Normalizes radian latitude. Normalizes latitude if at or exceeds epsilon - * distance from a pole. - * - * @param lat double latitude in radians - * @param epsilon epsilon (>= 0) radians distance from pole - * @return double latitude (-PI/2 <= phi <= PI/2) - * @see com.bbn.openmap.proj.coords.LatLonPoint#normalizeLatitude(double) - */ - public final static double normalizeLatitude(double lat, double epsilon) { - if (lat > NORTH_POLE_D - epsilon) { - return NORTH_POLE_D - epsilon; - } else if (lat < SOUTH_POLE_D + epsilon) { - return SOUTH_POLE_D + epsilon; - } - return lat; - } - - /** - * @deprecated use wrapLongitde instead. - */ - public final static float wrap_longitude(float lon) { - return wrapLongitude(lon); - } - - /** - * Sets radian longitude to something sane. - * - * @param lon float longitude in radians - * @return float longitude (-PI <= lambda < PI) - */ - public final static float wrapLongitude(float lon) { - if ((lon < -DATELINE_F) || (lon > DATELINE_F)) { - lon += DATELINE_F; - lon %= LON_RANGE_F; - lon += (lon < 0) ? DATELINE_F : -DATELINE_F; - } - return lon; - } - - /** - * @deprecated use wrapLongitude instead. - */ - public final static double wrap_longitude(double lon) { - return wrapLongitude(lon); - } - - /** - * Sets radian longitude to something sane. - * - * @param lon double longitude in radians - * @return double longitude (-PI <= lambda < PI) - */ - public final static double wrapLongitude(double lon) { - if ((lon < -DATELINE_D) || (lon > DATELINE_D)) { - lon += DATELINE_D; - lon %= LON_RANGE_D; - lon += (lon < 0) ? DATELINE_D : -DATELINE_D; - } - return lon; - } - - /** - * Sets degree longitude to something sane. - * - * @param lon double longitude in degrees - * @return double longitude (-180 <= lambda < 180) - */ - public final static double wrapLongitudeDeg(double lon) { - if ((lon < -DATELINE_DEG_D) || (lon > DATELINE_DEG_D)) { - lon += DATELINE_DEG_D; - lon %= LON_RANGE_DEG_D; - lon += (lon < 0) ? DATELINE_DEG_D : -DATELINE_DEG_D; - } - return lon; - } - - /** - * Converts units (km, nm, miles, etc) to decimal degrees for a spherical - * planet. This does not check for arc distances > 1/2 planet - * circumference, which are better represented as (2pi - calculated arc). - * - * @param u units float value - * @param uCircumference units circumference of planet - * @return float decimal degrees - */ - public final static float sphericalUnitsToDeg(float u, float uCircumference) { - return 360f * (u / uCircumference); - } - - /** - * Converts units (km, nm, miles, etc) to arc radians for a spherical - * planet. This does not check for arc distances > 1/2 planet - * circumference, which are better represented as (2pi - calculated arc). - * - * @param u units float value - * @param uCircumference units circumference of planet - * @return float arc radians - */ - public final static float sphericalUnitsToRad(float u, float uCircumference) { - return MoreMath.TWO_PI * (u / uCircumference); - } - - /** - * @deprecated use geocentricLatitude instead. - */ - public final static float geocentric_latitude(float lat, float lon) { - return geocentricLatitude(lat, lon); - } - - /** - * Calculate the geocentric latitude given a geographic latitude. According - * to John Synder:
- * "The geographic or geodetic latitude is the angle which a line - * perpendicular to the surface of the ellipsoid at the given point makes - * with the plane of the equator. ...The geocentric latitude is the angle - * made by a line to the center of the ellipsoid with the equatorial plane". - * ( Map Projections --A Working Manual , p 13) - *

- * Translated from Ken Anderson's lisp code Freeing the Essence of - * Computation - * - * @param lat float geographic latitude in radians - * @param flat float flatening factor - * @return float geocentric latitude in radians - * @see #geographic_latitude - */ - public final static float geocentricLatitude(float lat, float flat) { - float f = 1.0f - flat; - return (float) Math.atan((f * f) * (float) Math.tan(lat)); - } - - /** - * @deprecated use geographicLoatitude instead. - */ - public final static float geographic_latitude(float lat, float lon) { - return geographicLatitude(lat, lon); - } - - /** - * Calculate the geographic latitude given a geocentric latitude. Translated - * from Ken Anderson's lisp code Freeing the Essence of Computation - * - * @param lat float geocentric latitude in radians - * @param flat float flatening factor - * @return float geographic latitude in radians - * @see #geocentric_latitude - */ - public final static float geographicLatitude(float lat, float flat) { - float f = 1.0f - flat; - return (float) Math.atan((float) Math.tan(lat) / (f * f)); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScale(Point2D ll1, Point2D ll2, Projection projection) { - if (projection == null) { - return Float.MAX_VALUE; - } - - Point2D point1 = projection.forward(ll1); - Point2D point2 = projection.forward(ll2); - - return getScale(ll1, ll2, point1, point2, projection); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. This method is generally called from objects dealing with - * MouseEvents. - * - * @param point1 a java.awt.Point reflecting a pixel spot on the projection, - * usually the upper left corner of the area of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection, - * usually the lower right corner of the area of interest. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScale(Point point1, Point point2, Projection projection) { - - return getScaleFromProjected(point1, point2, projection); - } - - /** - * Given a couple of points representing a bounding box of projected - * coordinates, find out what the scale should be in order to make those - * points appear at the corners of the projection, with the intention that - * the bounding box will then fill the projected space. - * - * @param point1 a java.awt.Point reflecting a pixel spot on the projection, - * usually the upper left corner of the area of interest. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection, - * usually the lower right corner of the area of interest. - * @param projection the projection to use for other projection parameters, - * like map width and map height. - */ - public static float getScaleFromProjected(Point2D point1, Point2D point2, Projection projection) { - if (projection == null) { - return Float.MAX_VALUE; - } - - /** - * Just to make sure of the order for upper left and lower right, which - * seems to make a difference for the projection calculation. - */ - Point2D upperLeft = new Point2D.Double(Math.min(point1.getX(), point2.getX()), Math.min(point1.getY(), point2.getY())); - Point2D lowerRight = new Point2D.Double(Math.max(point1.getX(), point2.getX()), Math.max(point1.getY(), point2.getY())); - - Point2D ll1 = projection.inverse(upperLeft); - Point2D ll2 = projection.inverse(lowerRight); - - return getScale(ll1, ll2, upperLeft, lowerRight, projection); - } - - /** - * Given a couple of points representing a bounding box, find out what the - * scale should be in order to make those points appear at the corners of - * the projection. - * - * @param ll1 the upper left coordinates of the bounding box. - * @param ll2 the lower right coordinates of the bounding box. - * @param point1 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll1 coordinate in the new space, the upper left - * corner of the area of interest. Where the ll1 is going to go in - * the new projection. - * @param point2 a java.awt.Point reflecting a pixel spot on the projection - * that matches the ll2 coordinate in the new space, usually the - * lower right corner of the area of interest. Where the ll2 is going - * to go in the new projection. - * @param projection the projection to use to query to get the scale for, - * for projection type and height and width. - */ - protected static float getScale(Point2D ll1, Point2D ll2, Point2D point1, Point2D point2, - Projection projection) { - - return projection.getScale(ll1, ll2, point1, point2); - } - - /* - * public static void main(String[] args) { float degs = - * sphericalUnitsToRad( Planet.earthEquatorialRadius/2, - * Planet.earthEquatorialRadius); Debug.output("degs = " + degs); float - * LAT_DEC_RANGE = 90.0f; float LON_DEC_RANGE = 360.0f; float lat, lon; for - * (int i = 0; i < 100; i++) { lat = - * com.bbn.openmap.LatLonPoint.normalize_latitude( - * (float)Math.random()*LAT_DEC_RANGE); lon = - * com.bbn.openmap.LatLonPoint.wrap_longitude( - * (float)Math.random()*LON_DEC_RANGE); Debug.output( "(" + lat + "," + lon - * + ") : (" + degToRad(lat) + "," + degToRad(lon) + ") : (" + - * radToDeg(degToRad(lat)) + "," + radToDeg(degToRad(lon)) + ")"); } } - */ - - /** - * Generic test for seeing if an left longitude value and a right longitude - * value seem to constitute crossing the dateline. - * - * @param leftLon the leftmost longitude, in decimal degrees. Expected to - * represent the location of the left side of a map window. - * @param rightLon the rightmost longitude, in decimal degrees. Expected to - * represent the location of the right side of a map window. - * @param projScale the projection scale, considered if the two values are - * very close to each other and leftLon less than rightLon. - * @return true if it seems like these two longitude values represent a - * dateline crossing. - */ - public static boolean isCrossingDateline(double leftLon, double rightLon, float projScale) { - // if the left longitude is greater than the right, we're obviously - // crossing the dateline. If they are approximately equal, we could be - // showing the whole earth, but only if the scale is significantly - // large. If the scale is small, we could be really zoomed in. - return ((leftLon > rightLon) || (MoreMath.approximately_equal(leftLon, rightLon, .001f) && projScale > 1000000f)); - } - - /** - * Given a projection and the starting point of a box (pt1), look at pt2 to - * see if it represents the ratio of the projection map size. If it doesn't, - * provide a point that does. You need to make sure that the proj, pt1 and - * pt2 is not null. - * - * @param proj the projection to use for the calculations. - * @param pt1 upper left point in pixel space - * @param pt2 second point in pixel space. - * @return new pt that matches projection h/w ratio. - */ - public static Point getRatioPoint(Projection proj, Point pt1, Point pt2) { - float mapRatio = (float) proj.getHeight() / (float) proj.getWidth(); - - float boxHeight = (float) (pt1.y - pt2.y); - float boxWidth = (float) (pt1.x - pt2.x); - float boxRatio = Math.abs(boxHeight / boxWidth); - int isNegative = -1; - if (boxRatio > mapRatio) { - // box is too tall, adjust boxHeight - if (boxHeight < 0) { - isNegative = 1; - } - boxHeight = Math.abs(mapRatio * boxWidth); - pt2.y = pt1.y + (isNegative * (int) boxHeight); - - } else if (boxRatio < mapRatio) { - // box is too wide, adjust boxWidth - if (boxWidth < 0) { - isNegative = 1; - } - boxWidth = Math.abs(boxHeight / mapRatio); - pt2.x = pt1.x + (isNegative * (int) boxWidth); - } - return pt2; - } - - /** - * Given a projection to match against and the starting point of a box - * (pt1), look at pt2 to see if it represents the ratio of the projection - * map size. Return a rectangle for the resulting zoom area. - * - * @param proj the current projection. - * @param pt1 first point, where mouse down happened, for instance. - * @param pt2 latest point, where mouse released happened, for instance. - * @param zoomOnCenter whether the first point represents the center of the - * zoom box, or one of the corners. - * @return Rectangle2D representing the new zoom box. - */ - public static Rectangle2D getRatioBox(Projection proj, Point2D pt1, Point2D pt2, - boolean zoomOnCenter) { - double mapRatio = (double) proj.getHeight() / (double) proj.getWidth(); - - double boxHeight = Math.abs(pt1.getY() - pt2.getY()); - double boxWidth = Math.abs(pt1.getX() - pt2.getX()); - double boxRatio = Math.abs(boxHeight / boxWidth); - - if (boxRatio > mapRatio) { - boxHeight = Math.abs(mapRatio * boxWidth); - } else if (boxRatio < mapRatio) { - boxWidth = Math.abs(boxHeight / mapRatio); - } - - if (zoomOnCenter) { - double anchorx = pt1.getX() - boxWidth; - double anchory = pt1.getY() - boxHeight; - - return new Rectangle2D.Double(anchorx, anchory, 2 * boxWidth, 2 * boxHeight); - } else { - - double anchorx = pt1.getX(); - if (pt2.getX() < anchorx) { - anchorx -= boxWidth; - } - double anchory = pt1.getY(); - if (pt2.getY() < anchory) { - anchory -= boxHeight; - } - - return new Rectangle2D.Double(anchorx, anchory, boxWidth, boxHeight); - } - } - - /** - * Walks around the perimeter of the sourceMapProjection and returns the - * lat/lon coords of the outline. - * - * @param sourceMapProjection the source map's projection. - * @return double[] in y, x order, in whatever units the source map - * projection's inverse function returns. - */ - public static double[] getProjectionScreenOutlineCoords(Projection sourceMapProjection) { - - // Sourge projection not yet set - if (sourceMapProjection == null) { - return null; - } - - // Would have used ArrayList here but didn't for - // backward compatibility. - ArrayList l = new ArrayList(); - - // Get the parameters needed for building the coverage polygon - int width = sourceMapProjection.getWidth(); - int height = sourceMapProjection.getHeight(); - double xinc = ((double) width) / 10.0; - double yinc = ((double) height) / 10.0; - - Point2D center = sourceMapProjection.getCenter(new Point2D.Double()); - Point2D tmpllp; - - // Walk the top edge of the source projection's screen bounds - for (int i = 0; i <= 10; i++) { - tmpllp = sourceMapProjection.inverse(xinc * i, 0, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the right edge of the source projection's screen bounds - for (int i = 0; i <= 10; i++) { - tmpllp = sourceMapProjection.inverse(width, yinc * i, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the south edge of the source projection's screen bounds - for (int i = 10; i >= 0; i--) { - tmpllp = sourceMapProjection.inverse(xinc * i, height, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // Walk the left edge of the source projection's screen bounds - for (int i = 10; i >= 0; i--) { - tmpllp = sourceMapProjection.inverse(0, yinc * i, new Point2D.Double()); - if (!tmpllp.equals(center)) { - l.add(tmpllp); - } - } - - // populate the coordinate array for the polygon - double[] llarr = new double[l.size() * 2]; - int i = 0; - for (Point2D pnt : l) { - llarr[i] = pnt.getY(); - llarr[i + 1] = pnt.getX(); - i += 2; - } - - return llarr; - } - - /** - * Returns true if the Point is visible on the provided projection. - * - * @param sourceMapProjection - * @param llp - * @return true if the Point is visible on the provided projection. - */ - public static boolean isVisible(Projection sourceMapProjection, Point2D llp) { - boolean ret = false; - if (sourceMapProjection != null) { - if (sourceMapProjection.isPlotable(llp)) { - Point2D p = sourceMapProjection.forward(llp); - double x = p.getX(); - double y = p.getY(); - if (x >= 0 && x <= sourceMapProjection.getWidth() && y >= 0 - && y <= sourceMapProjection.getWidth()) { - ret = true; - } - } - } - return ret; - } - - /** - * Cumulative distance calculated between coords. - * @param radianCoords lat, lon, lat, lon order - * @return distance in radians - */ - public static double distance(double[] radianCoords) { - if (radianCoords != null && radianCoords.length >= 4) { - double totalDist = 0.0; - int len = radianCoords.length; - double y1 = radianCoords[0]; - double x1 = radianCoords[1]; - for (int i = 2; i < len - 1; i += 2) { - double y2 = radianCoords[i]; - double x2 = radianCoords[i + 1]; - - totalDist += Geo.distance(y1, x1, y2, x2); - - y1 = y2; - x1 = x2; - } - return totalDist; - } - - return 0.0; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java b/src/openmap/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java deleted file mode 100644 index e775db108..000000000 --- a/src/openmap/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java +++ /dev/null @@ -1,177 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/icon/OpenMapAppPartCollection.java,v -// $ -// $RCSfile: OpenMapAppPartCollection.java,v $ -// $Revision: 1.5 $ -// $Date: 2006/08/29 23:07:53 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.icon; - -import java.awt.Polygon; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Line2D; - -public class OpenMapAppPartCollection extends IconPartCollection { - - static OpenMapAppPartCollection omparts; - - protected OpenMapAppPartCollection() { - super("OpenMap", "Common parts used in OpenMap Application Icons"); - init(); - } - - public synchronized static OpenMapAppPartCollection getInstance() { - if (omparts == null) { - omparts = new OpenMapAppPartCollection(); - } - return omparts; - } - - protected void init() { - add(BIG_BOX); - add(SMALL_BOX); - add(FILL_BOX); - add(UL_TRI); - add(LR_TRI); - add(LL_UR_LINE); - add(UL_LR_LINE); - add(BIG_ARROW); - add(MED_ARROW); - add(SMALL_ARROW); - add(CORNER_TRI); - add(OPP_CORNER_TRI); - add(CIRCLE); - } - - public final static OpenMapAppPart BIG_BOX = new OpenMapAppPart.Poly("BIG_BOX", "BIG_BOX", new int[] { - 10, 10, 90, 90, 10 }, new int[] { 10, 90, 90, 10, 10 }); - public final static OpenMapAppPart SMALL_BOX = new OpenMapAppPart.Poly("SMALL_BOX", "SMALL_BOX", new int[] { - 30, 30, 70, 70, 30 }, new int[] { 30, 70, 70, 30, 30 }); - public final static OpenMapAppPart FILL_BOX = new OpenMapAppPart.Poly("FILL_BOX", "FILL_BOX", new int[] { - 10, 10, 50, 50, 30, 30, 70, 70, 50, 50, 90, 90, 10 }, new int[] { - 10, 90, 90, 70, 70, 30, 30, 70, 70, 90, 90, 10, 10 }); - public final static OpenMapAppPart UL_TRI = new OpenMapAppPart.Poly("UL_TRI", "UL_TRI", new int[] { - 10, 10, 75, 10 }, new int[] { 10, 75, 10, 10 }); - public final static OpenMapAppPart LR_TRI = new OpenMapAppPart.Poly("LR_TRI", "LR_TRI", new int[] { - 25, 90, 90, 25 }, new int[] { 90, 90, 25, 90 }); - public final static OpenMapAppPart LL_UR_LINE = new OpenMapAppPart.Poly("LL_UR_LINE", "LL_UR_LINE", new int[] { - 10, 90 }, new int[] { 90, 10 }); - public final static OpenMapAppPart UL_LR_LINE = new OpenMapAppPart.Poly("UL_LR_LINE", "UL_LR_LINE", new int[] { - 10, 90 }, new int[] { 10, 90 }); - public final static OpenMapAppPart BIG_ARROW = new OpenMapAppPart.Poly("BIG_ARROW", "BIG_ARROW", new int[] {50,90,80,80,20,20,10,50}, new int[] {10,40,40,90,90,40,40,10}); - public final static OpenMapAppPart MED_ARROW = new OpenMapAppPart.Poly("MED_ARROW", "MED_ARROW", new int[] {50,90,70,70,30,30,10,50}, new int[] {10,50,50,90,90,50,50,10}); - public final static OpenMapAppPart SMALL_ARROW = new OpenMapAppPart.Poly("SMALL_ARROW", "SMALL_ARROW", new int[] {50,80,60,60,40,40,20,50}, new int[] {10,50,50,90,90,50,50,10}); - public final static OpenMapAppPart CORNER_TRI = new OpenMapAppPart.Poly("CORNER_TRI", "CORNER_TRI", new int[] {10,50,10}, new int[] {10,10,50}); - public final static OpenMapAppPart OPP_CORNER_TRI = new OpenMapAppPart.Poly("OPP_CORNER_TRI", "OPP_CORNER_TRI", new int[] {50,90,50}, new int[] {50,50,90}); - public final static OpenMapAppPart CIRCLE = new OpenMapAppPart.Circle("CIRCLE", "CIRCLE", 50, 50, 46); - public final static OpenMapAppPart DOT = new OpenMapAppPart.Circle("DOT", "DOT", 50, 50, 6); - public final static OpenMapAppPart PLUS = new OpenMapAppPart.Poly("PLUS", "PLUS", new int[] {25,50,50,50,50,75,75,50,50,50,50,25,25}, new int[] {50,50,25,25,50,50,50,50,75,75,50,50,50}); - public final static OpenMapAppPart ADD_PLUS = new OpenMapAppPart.Poly("ADD_PLUS", "ADD_PLUS", new int[] {70,80,80,80,80,90}, new int[] {20,20,10,30,20,20}); - public final static OpenMapAppPart MINUS = new OpenMapAppPart.Poly("MINUS", "MINUS", new int[] {25,75}, new int[] {50,50}); - public final static OpenMapAppPart MAP_PIN_HEAD = new OpenMapAppPart.Circle("MAP_PIN_HEAD", "MAP_PIN_HEAD", 50, 33, 30); - public final static OpenMapAppPart MAP_PIN_BOTTOM = new OpenMapAppPart.Poly("MAP_PIN_BOTTOM", "MAP_PIN_BOTTOM", new int[] {50,30,70,50}, new int[] {90,50,50,90}); - - public static class OpenMapAppPart extends IconPartCollectionEntry { - - public OpenMapAppPart(String n, String d, Shape shape) { - this(n, d, shape, (AffineTransform) null); - } - - public OpenMapAppPart(String n, String d, Shape shape, - AffineTransform affTrans) { - super(n, d, new BasicIconPart(shape, affTrans)); - } - - public static class Poly extends OpenMapAppPart { - public Poly(String n, String d, int[] xp, int[] yp) { - this(n, d, xp, yp, (AffineTransform) null); - } - - public Poly(String n, String d, int[] xp, int[] yp, - AffineTransform af) { - super(n, d, new Polygon(xp, yp, xp.length), af); - } - } - - public static class Circle extends OpenMapAppPart { - public Circle(String n, String d, double x, double y, double radius) { - this(n, d, x, y, radius, (AffineTransform) null); - } - - public Circle(String n, String d, double x, double y, - double radius, AffineTransform af) { - super(n, - d, - new Ellipse2D.Double(x - radius, y - radius, radius * 2, radius * 2), - af); - } - } - - /** - * type = Arc2D.OPEN, Arc2D.CHORD, Arc2D.PIE - * @author dietrick - * - */ - public static class Arc extends OpenMapAppPart { - public Arc(String n, String d, double x, double y, double radius, double start, double end, int type) { - this(n, d, x, y, radius, start, end, type, null); - } - - public Arc(String n, String d, double x, double y, double radius, double start, double end, int type, AffineTransform af) { - super(n, d, new Arc2D.Double(type), af); - Arc2D arc = (Arc2D) super.getIconPart().getGeometry(); - arc.setArcByCenter(x, y, radius, start, end, type); - } - } - } - - public static IconPart getReloadSymbol() { - IconPartList ipList = new IconPartList(); - ipList.add(new OpenMapAppPartCollection.OpenMapAppPart.Arc("RELOAD_ARC", "RELOAD_ARC", 50, 50, 30, 90, 270, Arc2D.OPEN) - .getIconPart()); - ipList.add(new OpenMapAppPartCollection.OpenMapAppPart.Poly("RELOAD_POINT", "RELOAD_POINT", - new int[] { 43, 65, 49 }, new int[] { 15, 20, 37 }).getIconPart()); - return ipList; - } - - public static IconPart getSettingsSymbol() { - IconPartList ipList = new IconPartList(); - ipList.add(new OpenMapAppPartCollection.OpenMapAppPart.Circle("SETTINGS_CIRCLE", "SETTINGS_CIRCLE", 50, 50, 30).getIconPart()); - - for (int i = 0; i < 360; i+= 30) { - double angle = Math.toRadians(i); - double cos = Math.cos(angle); - double sin = Math.sin(angle); - double x1 = 30.0 * cos + 50; - double y1 = 30.0 * sin + 50; - double x2 = 40.0 * cos + 50; - double y2 = 40.0 * sin + 50; - - Line2D.Double line = new Line2D.Double(x1, y1, x2, y2); - ipList.add(new OpenMapAppPartCollection.OpenMapAppPart("RELOAD_POINT", "RELOAD_POINT", line).getIconPart()); - } - - return ipList; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/tools/roads/Road.java b/src/openmap/com/bbn/openmap/tools/roads/Road.java deleted file mode 100644 index 06311e186..000000000 --- a/src/openmap/com/bbn/openmap/tools/roads/Road.java +++ /dev/null @@ -1,445 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Road.java,v -// $ -// $RCSfile: Road.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.awt.Point; -import java.io.Serializable; -import java.util.logging.Logger; - -import com.bbn.openmap.omGraphics.OMGraphicList; -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class Road implements RoadObject, Serializable { - - transient Logger logger = Logger.getLogger(this.getClass().getName()); - - /** - * The points along the road. The first and last points are always - * Intersections. - */ - private Waypoint[] points; - - /** - * The lines between the points. - */ - private RoadLine[] lines; - - /** - * The class of this road. A Road's class implies what kind of road it is. - * For now this governs its visual appearance of color and width. - */ - private RoadClass roadClass; - - private boolean isRoute = false; - - private boolean blocked = false; - - /** - * The id of this road. - */ - private int id; - - /** - * The name of this road. - */ - private String name; - - /** - * True if this road has been modified (points added or removed). - */ - private boolean modified = false; - - /** - * The RoadLayer we belong to so we can invoke its services. - */ - private transient RoadLayer roadLayer; - - /** - * Selection flag for this road. - */ - private boolean selected = false; - - /** - * Blink flag for this road. - */ - private boolean blinkState = false; - - /** - * Create a road between two Intersections. The detailed segments between - * the intersections may be filled in later. - * - * @param id a unique, integer identifier of this road. - * @param name a name for this road. - * @param from the intersection from which this road leaves. - * @param to the intersection to which this road goes. - * @param roadClass the class of this road. - * @param roadLayer the RoadLayer we belong to. - */ - public Road(int id, String name, Intersection from, Intersection to, RoadClass roadClass, - RoadLayer roadLayer) { - this.id = id; - this.name = name; - this.roadLayer = roadLayer; - points = new Waypoint[2]; - setIntersections(from, to); - this.roadClass = roadClass; - createLines(); - modified = false; - } - - public double getLengthInKilometers() { - double kilometers = 0.0; - LatLonPoint prevPoint = points[0].getLocation(); - // logger.warning ("" + this + " pt 0 " + points[0] + " pt 1 " - // + points[1] + " getSecondInter " + getSecondIntersection - // ()); - for (int i = 1; i < points.length; i++) { - LatLonPoint thisPoint = points[i].getLocation(); - kilometers += GreatCircle.sphericalDistance(prevPoint.getY(), prevPoint.getX(), thisPoint.getY(), thisPoint.getX()); - prevPoint = thisPoint; - } - return kilometers; - } - - public double getTraverseHours() { - if (isBlocked()) - return Float.MAX_VALUE; - return getLengthInKilometers() / getRoadClass().getConvoySpeed(); - } - - public LatLonPoint getLocationAtKilometer(double kilometers) { - LatLonPoint prevPoint = points[0].getLocation(); - double prevLat = prevPoint.getY(); - double prevLon = prevPoint.getX(); - for (int i = 1; i < points.length; i++) { - LatLonPoint thisPoint = points[i].getLocation(); - double thisLat = thisPoint.getY(); - double thisLon = thisPoint.getX(); - double thisLength = GreatCircle.sphericalDistance(prevLat, prevLon, thisLat, thisLon); - if (thisLength >= kilometers) { - double fraction = kilometers / thisLength; - double deltaLat = thisLat - prevLat; - double deltaLon = thisLon - prevLon; - if (deltaLon < -180f) - deltaLon += 360f; - else if (deltaLon > 180f) - deltaLon -= 360f; - return new LatLonPoint.Double(prevLat + fraction * deltaLat, prevLon + fraction - * deltaLon); - } - kilometers -= thisLength; - prevPoint = thisPoint; - prevLat = thisLat; - prevLon = thisLon; - } - return prevPoint; - } - - private void createLines() { - lines = new RoadLine[points.length - 1]; - for (int i = 0; i < lines.length; i++) { - lines[i] = new RoadLine(this, i); - } - blinkLines(); - } - - private void blinkLines() { - for (int i = 0; i < lines.length; i++) - lines[i].blink(blinkState); - } - - /** - * Set the state of the modified flag. Setting the modified flag to false - * also sets the modified flag of all the points to false as well. - * - * @param newValue the new setting. - */ - public void setModified(boolean newValue) { - modified = newValue; - if (newValue == false) { - for (int i = 0; i < points.length; i++) - points[i].setModified(false); - } - } - - /** - * Get the state of the modified flag. - * - * @return true if the road or its points have been modified. - */ - public boolean getModified() { - if (modified) - return true; - for (int i = 0; i < points.length; i++) - if (points[i].getModified()) - return true; - return false; - } - - public void block() { - blocked = true; - updateLines(); - } - - public void unblock() { - blocked = false; - updateLines(); - } - - public boolean isBlocked() { - return blocked; - } - - public void blink(boolean newState) { - blinkState = newState; - if (lines != null) - blinkLines(); - blinkPoints(); - } - - /** - * Accessor for the ID property. - * - * @return the road ID. - */ - public int getID() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String newName) { - name = newName; - } - - public RoadClass getRoadClass() { - return roadClass; - } - - public void setRoadClass(RoadClass newClass) { - roadClass = newClass; - setModified(true); - updateLines(); - } - - public String getRoadClassName() { - return roadClass.getName().toString(); - } - - public void isRoute(boolean yes) { - isRoute = yes; - updateLines(); - } - - public boolean isRoute() { - return isRoute; - } - - public RoadLayer getRoadLayer() { - return roadLayer; - } - - public void setIntersections(Intersection from, Intersection to) { - if (from == null) { - logger.warning("from is null."); - Thread.dumpStack(); - } - if (to == null) { - logger.warning("to is null."); - Thread.dumpStack(); - } - - points[0] = from; - points[points.length - 1] = to; - checkPoints(); - createLines(); - setModified(true); - } - - public void setRoadPoints(RoadPoint[] innerPoints) { - Waypoint[] oldPoints = points; - points = new Waypoint[2 + innerPoints.length]; - points[0] = oldPoints[0]; - System.arraycopy(innerPoints, 0, points, 1, innerPoints.length); - points[points.length - 1] = oldPoints[oldPoints.length - 1]; - - if (points[points.length - 1] == null) { - logger.warning("to is null."); - Thread.dumpStack(); - } - - checkPoints(); - - createLines(); - // blinkPoints(); - setModified(true); - } - - public void checkPoints() { - for (int i = 0; i < points.length; i++) { - if (points[i] == null) { - logger.warning("found null point at " + i); - Thread.dumpStack(); - } - } - } - - public RoadPoint[] getRoadPoints() { - RoadPoint[] innerPoints = new RoadPoint[points.length - 2]; - System.arraycopy(points, 1, innerPoints, 0, innerPoints.length); - return innerPoints; - } - - public void insertRoadPointAt(RoadPoint wp, int ix) { - Waypoint[] oldPoints = points; - points = new Waypoint[1 + oldPoints.length]; - System.arraycopy(oldPoints, 0, points, 0, ix); - points[ix] = wp; - if (wp == null) { - logger.warning("wp is null."); - Thread.dumpStack(); - } - checkPoints(); - System.arraycopy(oldPoints, ix, points, ix + 1, oldPoints.length - ix); - createLines(); - // blinkPoints(); - setModified(true); - } - - public void deleteRoadPoint(RoadPoint rp) { - for (int ix = 1; ix < points.length - 1; ix++) { - if (points[ix] == rp) { - Waypoint[] oldPoints = points; - points = new Waypoint[oldPoints.length - 1]; - System.arraycopy(oldPoints, 0, points, 0, ix); - System.arraycopy(oldPoints, ix + 1, points, ix, oldPoints.length - ix - 1); - createLines(); - setModified(true); - return; - } - } - checkPoints(); - - } - - public Intersection getFirstIntersection() { - return (Intersection) points[0]; - } - - public Intersection getSecondIntersection() { - return (Intersection) points[points.length - 1]; - } - - public Intersection getOtherIntersection(Intersection intersection) { - if (intersection == points[0]) - return (Intersection) points[points.length - 1]; - return (Intersection) points[0]; - } - - public void changeIntersection(Intersection oldIntersection, Intersection newIntersection) { - if (oldIntersection == points[0]) { - setIntersections(newIntersection, getSecondIntersection()); - } else if (oldIntersection == points[points.length - 1]) { - setIntersections(getFirstIntersection(), newIntersection); - } - checkPoints(); - - } - - public Waypoint getWaypoint(int ix) { - return points[ix]; - } - - public Waypoint[] getPoints() { - return points; - } - - public RoadPoint[] getPointsBefore(RoadPoint wp) { - for (int i = 1; i < points.length - 1; i++) { - if (points[i] == wp) { - RoadPoint[] answer = new RoadPoint[i - 1]; - System.arraycopy(points, 1, answer, 0, answer.length); - return answer; - } - } - return new RoadPoint[0]; - } - - public RoadPoint[] getPointsAfter(RoadPoint wp) { - for (int i = 1; i < points.length - 1; i++) { - if (points[i] == wp) { - RoadPoint[] answer = new RoadPoint[points.length - i - 2]; - System.arraycopy(points, i + 1, answer, 0, answer.length); - return answer; - } - } - RoadPoint[] answer = new RoadPoint[points.length - 2]; - System.arraycopy(points, 1, answer, 0, answer.length); - return answer; - } - - private void blinkPoints() { - for (int i = 1; i < points.length - 1; i++) { - points[i].blink(blinkState); - } - } - - /** - * Mark this Road as needing a new visual representation. - */ - public synchronized void updateLines() { - for (int i = 0; i < lines.length; i++) - lines[i].update(); - } - - public void moveTo(Point loc) { - } - - public synchronized void render(OMGraphicList gl, boolean projectionIsNew) { - if (roadLayer.isEditing()) { - for (int i = 1; i < points.length - 1; i++) { - points[i].render(gl, projectionIsNew); - } - } - for (int i = 0; i < lines.length; i++) - lines[i].render(gl, projectionIsNew); - } - - public String toString() { - return name + " from " + getFirstIntersection() + " to " + getSecondIntersection() + " " - + points.length + " points."; - } - - public boolean isSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/tools/roads/RoadFinder.java b/src/openmap/com/bbn/openmap/tools/roads/RoadFinder.java deleted file mode 100644 index ea29d4eb9..000000000 --- a/src/openmap/com/bbn/openmap/tools/roads/RoadFinder.java +++ /dev/null @@ -1,1253 +0,0 @@ -/* ********************************************************************** - * - * Use, duplication, or disclosure by the Government is subject to - * restricted rights as set forth in the DFARS. - * - * BBN Technologies - * A Division of - * BBN Corporation - * 10 Moulton Street - * Cambridge, MA 02138 - * (617) 873-3000 - * - * Copyright 1998 by BBN Technologies, A Division of - * BBN Corporation, all rights reserved. - * - * ********************************************************************** - * - * $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadFinder.java,v $ - * $RCSfile: RoadFinder.java,v $ - * $Revision: 1.7 $ - * $Date: 2006/02/16 16:22:48 $ - * $Author: dietrick $ - * - * ********************************************************************** - */ - -package com.bbn.openmap.tools.roads; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.PathIterator; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.event.ProjectionEvent; -import com.bbn.openmap.event.ProjectionListener; -import com.bbn.openmap.omGraphics.OMGeometry; -import com.bbn.openmap.omGraphics.OMLine; -import com.bbn.openmap.omGraphics.OMPoint; -import com.bbn.openmap.omGraphics.OMText; -import com.bbn.openmap.proj.Projection; -import com.bbn.openmap.proj.coords.LatLonPoint; -import com.bbn.openmap.util.quadtree.QuadTree; - -/** - * Gives road access to a shape or vpf layer. - */ -public class RoadFinder - implements RoadServices, ProjectionListener, RoadLayer { - - protected RoadClasses roadClasses = new RoadClasses(); - - protected RoadClass defaultRoadClass; - - protected LayerView layer; - - protected Intersections intersections = new Intersections(); - - protected RoadVector roads = new RoadVector(); - - protected Vector removedRoads = new Vector(); - - /** - * how far (in lat-lon space) from lat,lon point to look in quad tree for - * nearest road * - */ - protected float halo; - - Logger logger = Logger.getLogger(this.getClass().getName()); - boolean drawIntersections = false; - boolean drawResults = false; - boolean doLoopCheck = false; - protected QuadTree interQuadTree; - protected Map graphicToRoad; - boolean doInterp = true; - - /** list of extra graphics to display */ - List toDraw = new ArrayList(); - boolean showLines = true; - int roadsMade = 0; - - public RoadFinder(LayerView layer, boolean drawIntersections, boolean drawResults) { - initRoadClasses(); - - this.drawIntersections = drawIntersections; - this.drawResults = drawResults; - logger.info("drawIntersections is " + drawIntersections); - logger.info("drawResults is " + drawResults); - this.layer = layer; - } - - protected void initRoadClasses() { - roadClasses.put(new RoadClass("1", Color.magenta, 2, 25.0f)); - defaultRoadClass = findRoadClass("1"); - } - - /** - * Implemented for ProtectionListener - */ - public void projectionChanged(ProjectionEvent e) { - try { - getData(); - } catch (Exception ee) { - logger.warning("Got exception " + ee); - ee.printStackTrace(); - } - } - - /** - * Take the shape data on the layer and use it to populate our roads and - * intersections. - * - * Clears lists of roads and intersections first, and after calculating the - * roads, tells the RoadLayer what extra graphics to display, if any. - */ - protected synchronized void getData() - throws Exception { - logger.info("get Data called."); - intersections.clear(); - removedRoads.setSize(0); - roads.clear(); - toDraw.clear(); - getRoads(); - checkIntegrity(); - logger.info("showing " + toDraw.size() + " extra graphics."); - layer.setExtraGraphics(toDraw); - halo = 0.05f * (getProjection().getScale() / 20000f); - } - - /** - * Take the shape data on the layer and use it to populate our roads and - * intersections. - * - */ - protected void getRoads() - throws Exception { - roadsMade = 0; - List rectangle = layer.getGraphicList(); - int[] xPoints = new int[1024]; - int[] yPoints = new int[1024]; - interQuadTree = new QuadTree(); - graphicToRoad = new HashMap(); - - int height = getProjection().getHeight(); - int width = getProjection().getWidth(); - int skipped = 0; - - synchronized (rectangle) { - double[] points = new double[6]; - if (logger.isLoggable(Level.INFO)) - logger.info("iterating over rectangle contents."); - - int num = 0; - int made = 0; - for (Iterator iter = rectangle.iterator(); iter.hasNext();) { - double lastXOff = 0; - double lastYOff = 0; - - num++; - OMGeometry graphic = (OMGeometry) iter.next(); - - if (logger.isLoggable(Level.FINE)) - logger.fine("examining " + graphic); - - Shape shape = graphic.getShape(); - if (shape == null) - continue; - - PathIterator path = shape.getPathIterator(new AffineTransform()); - int segment = 0; - int itemsInPath = 0; - boolean pathValid = true; - - for (; !path.isDone() && pathValid; path.next()) { - int type = path.currentSegment(points); - itemsInPath++; - boolean offScreen = false; - if (points[0] < 0 || points[0] >= width) { - // logger.warning("skipping x point " + - // points[0] + " b/c it's off the map."); - offScreen = true; - } - if (points[1] < 0 || points[1] >= height) { - // logger.warning("skipping y point " + - // points[1] + " b/c it's off the map."); - offScreen = true; - } - - switch (type) { - case PathIterator.SEG_CLOSE: - logger.warning("got close"); - break; - case PathIterator.SEG_CUBICTO: - logger.warning("got cubic to"); - break; - case PathIterator.SEG_LINETO: - if (offScreen) { - if (segment > 0) { - // BOZO - // should reexamine whether this is - // legal - there should be - // a one-to-one mapping between - // graphic and road object, - // but this will throw away the - // original entry - - if (doInterp) { - Point interpPt = - interp(xPoints[segment - 1], yPoints[segment - 1], points[0], points[1], width, height); - xPoints[segment] = interpPt.x; - yPoints[segment++] = interpPt.y; - - makeRoad(shape, graphic, made++, xPoints, yPoints, segment); - lastXOff = 0; - lastYOff = 0; - segment = 0; - } - } else { - lastXOff = points[0]; - lastYOff = points[1]; - } - } else { // onscreen - if (lastXOff != 0 || lastYOff != 0) { - Point interpPt = interp(points[0], points[1], lastXOff, lastYOff, width, height); - xPoints[segment] = interpPt.x; - yPoints[segment++] = interpPt.y; - } - - xPoints[segment] = (int) points[0]; - yPoints[segment++] = (int) points[1]; - lastXOff = 0; - lastYOff = 0; - } - - if (logger.isLoggable(Level.FINE)) - logger.fine(" line to " + points[0] + ", " + points[1]); - - break; - case PathIterator.SEG_MOVETO: - if (offScreen) { - lastXOff = points[0]; - lastYOff = points[1]; - } else { - if (segment == 0) { - xPoints[segment] = (int) points[0]; - yPoints[segment++] = (int) points[1]; - } else { - // we got a second move to in the list - // - this is not valid - pathValid = false; - logger.info("got invalid path."); - } - - lastXOff = 0; - lastYOff = 0; - } - - if (logger.isLoggable(Level.FINE)) - logger.fine(" moving to " + points[0] + ", " + points[1]); - - break; - case PathIterator.SEG_QUADTO: - logger.warning("got quad to"); - break; - default: - logger.warning("got another type : " + type); - break; - } - } - - if (segment < 2) { - skipped++; - logger.fine("Skipping line that doesn't have an end point"); - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("items in path " + itemsInPath); - - makeRoad(shape, graphic, made++, xPoints, yPoints, segment); - } - segment = 0; - } - - if (logger.isLoggable(Level.INFO)) - logger.info("num items " + num + " skipped " + skipped); - } - } - - /** - * find a point between x1,y1 and x2, y2 that is within the visible map - * - * @param width of visible map - * @param height of visible map - * @return Point between x1,y1 and x2, y2 - */ - protected Point interp(double x1, double y1, double x2, double y2, int width, int height) { - double deltaY = y2 - y1; - double deltaX = x2 - x1; - double slope = deltaY / deltaX; - double newX = x2; - double newY = y2; - - if (newX < 0) { - newX = 0; - newY = Math.round(slope * (newX - x1) + y1); - } else if (newX >= width) { - newX = width - 1; - newY = Math.round(slope * (newX - x1) + y1); - } - - if (newY < 0) { - newY = 0; - newX = Math.round(x1 + (newY - y1) / slope); - } else if (newY >= height) { - newY = height - 1; - newX = Math.round(x1 + (newY - y1) / slope); - } - - int intX = (int) newX; - int intY = (int) newY; - - if (intX < 0) { - logger.warning("new x is " + intX); - intX = 0; - } - if (intX >= width) { - logger.warning("new x is " + intX); - intX = width - 1; - } - if (intY < 0) { - logger.warning("new y is " + intY); - intY = 0; - } - if (intY >= height) { - logger.warning("new y is " + intY); - intY = height - 1; - } - - if (logger.isLoggable(Level.INFO)) { - logger.info("from " + x1 + "," + y1 + " to " + x2 + "," + y2 + "w " + width + " h " + height + " interp " + intX + "," - + intY); - } - - return new Point(intX, intY); - } - - /** - * Makes a road object given the points on the shape that are within the - * visible box - * - * Stores it in a quadTree - */ - protected void makeRoad(Shape shape, OMGeometry graphic, int num, int[] xPoints, int[] yPoints, int segment) { - createRoadFromPoints(num, xPoints, yPoints, segment); - } - - /** - * Makes a road object given the points on the shape that are within the - * visible box - * - * @param nPoints in the xpoints and ypoints arrays - */ - protected RoadObject createRoadFromPoints(int id, int[] xpoints, int[] ypoints, int nPoints) { - RoadPoint[] roadPoints = new RoadPoint[nPoints - 2]; - Intersection from = findIntersection(xpoints[0], ypoints[0]); - int fromBefore = from.getRoadCount(); - Intersection to = findIntersection(xpoints[nPoints - 1], ypoints[nPoints - 1]); - int toBefore = to.getRoadCount(); - - if (from == null) { - logger.warning("no from intersection for " + xpoints[0] + ", " + ypoints[0]); - } - if (to == null) { - logger.warning("no to intersection for " + xpoints[nPoints - 1] + ", " + ypoints[nPoints - 1]); - } - - String name = "road"; - Road road = createRoad(id, name + "-" + id, from, to, defaultRoadClass); - if (fromBefore + 1 != from.getRoadCount()) - logger.severe("huh? " + from + " had " + fromBefore + " roads before and now " + from.getRoadCount()); - if (toBefore + 1 != to.getRoadCount()) - logger.severe("huh? " + to + " had " + toBefore + " roads before and now " + to.getRoadCount()); - int width = roadsMade % 5; - roadsMade++; - - if (logger.isLoggable(Level.INFO)) { - logger.info("road # " + roadsMade + " " + road + " has " + nPoints + " points"); - } - - if (!showLines && drawIntersections) { - OMPoint point = new YellowPoint(xpoints[0], ypoints[0], 10); - toDraw.add(point); - } - - for (int i = 1; i < nPoints - 1; i++) { - roadPoints[i - 1] = new RoadPoint(road, createLatLonPoint(xpoints[i], ypoints[i]), this); - if (drawIntersections) { - if (showLines) { - OMLine line = new YellowLine(xpoints[i - 1], ypoints[i - 1], xpoints[i], ypoints[i], width); - toDraw.add(line); - toDraw.add(new OMText((xpoints[i - 1] - xpoints[i]) / 2 + xpoints[i - 1], (ypoints[i - 1] - ypoints[i]) / 2 - + ypoints[i - 1] - 5, "" + roadsMade, 0)); - } else { - OMPoint point = new YellowPoint(xpoints[i], ypoints[i], 10); - toDraw.add(point); - } - } - } - - if (drawIntersections) { - if (showLines) { - OMLine line = - new YellowLine(xpoints[nPoints - 2], ypoints[nPoints - 2], xpoints[nPoints - 1], ypoints[nPoints - 1], width); - toDraw.add(line); - toDraw.add(new OMText((xpoints[nPoints - 2] - xpoints[nPoints - 1]) / 2 + xpoints[nPoints - 2], - (ypoints[nPoints - 2] - ypoints[nPoints - 1]) / 2 + ypoints[nPoints - 2] - 5, "" + roadsMade, 0)); - line.addArrowHead(true); - } else { - OMPoint point = new YellowPoint(xpoints[nPoints - 1], ypoints[nPoints - 1], 10); - toDraw.add(point); - } - } - - if (to == from && nPoints == 2) { - deleteRoad(road); - return null; - } - - road.setRoadPoints(roadPoints); - - if (!road.getFirstIntersection().equals(from)) - logger.severe("huh? " + road + " first inter " + road.getFirstIntersection() + " not " + from); - - if (!road.getSecondIntersection().equals(to)) - logger.severe("huh? " + road + " second inter " + road.getSecondIntersection() + " not " + to); - - if (road.getPoints().length < 2) - logger.warning("Error : somehow made a road " + road + " with too few points."); - else if (logger.isLoggable(Level.INFO)) { - // logger.info("made " + road); - } - - return road; - } - - /** a yellow point for displaying intersections */ - protected class YellowPoint - extends OMPoint { - public YellowPoint(int x, int y, int radius) { - super(x, y, radius); - } - - public void render(Graphics g) { - setGraphicsColor(g, Color.YELLOW); - draw(g, getShape()); - } - } - - /** a yellow line for display routes between intersections */ - protected class YellowLine - extends OMLine { - int width; - - public YellowLine(int x, int y, int x2, int y2, int width) { - super(x, y, x2, y2); - this.width = width; - } - - public void render(Graphics g) { - float[] dash1 = new float[width + 1]; - dash1[0] = 10.f; - - for (int i = 1; i < width; i++) { - dash1[i] = 2.0f; - } - - BasicStroke dashed = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f); - ((Graphics2D) g).setStroke(dashed); - setGraphicsColor(g, Color.YELLOW); - draw(g, getShape()); - } - } - - protected LatLonPoint createLatLonPoint(int x, int y) { - return getProjection().inverse(x, y, new LatLonPoint.Double()); - } - - protected Intersection findIntersection(LatLonPoint loc, String name) { - if (name == null) - return findIntersection(loc); - Intersection intersection = intersections.get(name); - if (intersection != null) { - LatLonPoint foundLoc = intersection.getLocation(); - float distance = - (Math.abs(foundLoc.getLatitude() - loc.getLatitude()) + Math.abs(foundLoc.getLongitude() - loc.getLongitude())); - if (distance * Intersection.GRID > 0.1f) { - intersection = findIntersection(loc); // Ignore the - // name, it's - // too far away. - System.out.println("Using " + intersection.getName() + " instead of " + name + " distance = " + distance); - return intersection; - } - } else { - intersection = new Intersection(loc, name, this); - intersections.put(intersection); - interQuadTree.put(intersection.getLatitude(), intersection.getLongitude(), intersection); - } - return intersection; - } - - protected Intersection findIntersection(int x, int y) { - LatLonPoint fromLoc = createLatLonPoint(x, y); - Intersection from = findIntersection(fromLoc); - return from; - } - - protected Intersection findIntersection(LatLonPoint loc) { - String name = Intersection.getLatLonPointName(loc); - Intersection intersection = intersections.get(name); - if (intersection == null) { - if (logger.isLoggable(Level.FINE)) - logger.fine("making new intersection for " + loc); - intersection = new Intersection(loc, name, this); - interQuadTree.put(intersection.getLatitude(), intersection.getLongitude(), intersection); - intersections.put(intersection); - } else { - if (logger.isLoggable(Level.FINE)) - logger.fine("found existing intersection for " + loc + " with " + intersection.getRoadCount() - + " roads coming out of it."); - } - return intersection; - } - - protected void deleteIntersection(Intersection intersection) { - if (intersection.getRoadCount() > 0) - throw new IllegalArgumentException("Attempt to delete connected intersection"); - intersections.remove(intersection); - } - - /** - * called from Intersection Implemented for RoadLayer interface - */ - public Road createRoad(Intersection from) { - return createRoad(-1, null, from, null, null); - } - - protected Road createRoad(int id, String name, Intersection from, Intersection to, RoadClass cl_ss) { - if (id < 0) - id = findUnusedRoadID(); - if (name == null) - name = "Road_" + id; - if (from == null) - from = findIntersection(to.getLocation(), to.getName() + ".drag"); - if (to == null) - to = findIntersection(from.getLocation(), from.getName() + ".drag"); - if (cl_ss == null) - cl_ss = defaultRoadClass; - Road road = new Road(id, name, from, to, cl_ss, this); - road.setModified(true); - from.addRoad(road); - to.addRoad(road); - roads.add(road); - return road; - } - - public void deleteRoad(Road road) { - Intersection intersection1 = road.getFirstIntersection(); - Intersection intersection2 = road.getSecondIntersection(); - intersection1.removeRoad(road); - intersection2.removeRoad(road); - if (intersection1.getRoadCount() == 0) - deleteIntersection(intersection1); - if (intersection2.getRoadCount() == 0) - deleteIntersection(intersection2); - if (intersection1.getRoadCount() == 2 && intersection1.getRoad(0).getRoadClass() == intersection1.getRoad(1).getRoadClass()) - joinRoads(intersection1); - if (intersection2.getRoadCount() == 2 && intersection2.getRoad(0).getRoadClass() == intersection2.getRoad(1).getRoadClass()) - joinRoads(intersection2); - removedRoads.addElement(road); - roads.remove(road); - } - - /** - * Split a road into two roads at one of its corners. An intersection is - * created where the corner was and the segments before the corner become the - * segments of the original road. The segments after the corner become the - * segments of a new road between the new intersection and the - */ - public Intersection splitRoad(Road road, RoadPoint rp) { - RoadPoint[] pointsBefore = road.getPointsBefore(rp); - RoadPoint[] pointsAfter = road.getPointsAfter(rp); - Intersection newIntersection = findIntersection(rp.getLocation(), null); - Intersection firstIntersection = road.getFirstIntersection(); - Intersection secondIntersection = road.getSecondIntersection(); - road.setIntersections(firstIntersection, newIntersection); - road.setRoadPoints(pointsBefore); - secondIntersection.removeRoad(road); - newIntersection.addRoad(road); - Road newRoad = createRoad(-1, null, newIntersection, secondIntersection, road.getRoadClass()); - newRoad.setRoadPoints(pointsAfter); - return newIntersection; - } - - /** - * Join two roads into one. The roads must be the only two roads at the - * intersection and must be of the same class. If the roads are not distinct, - * then we quietly delete the road and remove the intersection. The roads - * might not be distinct if they form an isolated loop (such as a racetrack). - * Thus situation is particularly problematic if the road has no inner - * points. The RoadPoints of both roads are concatenated with a new RoadPoint - * where the intersection was between them. This code is a little complicated - * because the RoadPoints must be assembled in a valid order. The order used - * is to start from the other intersection of the first road to the given - * intersection and from the given intersection of the second road to the - * other intersection of the second road. - */ - public void joinRoads(Intersection intersection) { - if (intersection.getRoadCount() != 2) - throw new IllegalArgumentException("Illegal intersection conversion"); - Road road0 = intersection.getRoad(0); - Road road1 = intersection.getRoad(1); - if (road0 == road1) { - roads.remove(road1); - intersections.remove(intersection); - return; - } - if (road0.getRoadClass() != road1.getRoadClass()) - throw new IllegalArgumentException("Illegal intersection conversion"); - intersections.remove(intersection); - roads.remove(road1); - RoadPoint[] road0Points = road0.getRoadPoints(); - RoadPoint[] road1Points = road1.getRoadPoints(); - RoadPoint[] innerPoints = new RoadPoint[road0Points.length + road1Points.length + 1]; - int j = 0; - Intersection firstIntersection; - if (intersection == road0.getFirstIntersection()) { - firstIntersection = road0.getSecondIntersection(); - for (int i = road0Points.length; --i >= 0;) - innerPoints[j++] = road0Points[i]; - } else { - firstIntersection = road0.getFirstIntersection(); - System.arraycopy(road0Points, 0, innerPoints, j, road0Points.length); - j += road0Points.length; - } - Intersection otherIntersection = road1.getOtherIntersection(intersection); - otherIntersection.removeRoad(road1); - road0.setIntersections(firstIntersection, otherIntersection); - otherIntersection.addRoad(road0); - innerPoints[j++] = new RoadPoint(road0, intersection.getLocation(), this); - if (intersection == road1.getFirstIntersection()) { - System.arraycopy(road1Points, 0, innerPoints, j, road1Points.length); - j += road1Points.length; - } else { - for (int i = road1Points.length; --i >= 0;) - innerPoints[j++] = road1Points[i]; - } - road0.setRoadPoints(innerPoints); - road0.setName(mergeRoadNames(road0.getName(), road1.getName())); - } - - protected String mergeRoadNames(String name0, String name1) { - return name0 + "+" + name1; - } - - public RoadClass findRoadClass(Object className) { - RoadClass cl_ss = (RoadClass) roadClasses.get(className); - if (cl_ss == null) - return defaultRoadClass; - return cl_ss; - } - - public int findUnusedRoadID() { - return roads.findUnusedID(); - } - - /** - * Displays a Route between two points on the map. - *

- * - * @param start start from start point on map - * @param end to end point on map - * @param route the Route to travel from start to end - * @param segments as side effect, populated with PathSegments between - * returned WayPoints - * @return List of WayPoints - */ - public List displayPathOnRoad(Point start, Point end, Route route, List segments) { - List newPoints; - try { - if (route == null) { - OMPoint point = new RedPoint(start.x, start.y, 5); - toDraw.add(point); - point = new RedPoint(end.x, end.y, 5); - toDraw.add(point); - - return null; - } - - if (drawResults) { - OMPoint point = new YellowPoint(start.x, start.y, 10); - toDraw.add(point); - point = new YellowPoint(end.x, end.y, 10); - toDraw.add(point); - } - - newPoints = new ArrayList(); - populatePointsAndSegments(route, newPoints, segments); - - if (drawResults) { - Point last = null; - Point first = null; - for (Iterator iter = newPoints.iterator(); iter.hasNext();) { - Point pt = (Point) iter.next(); - if (last != null) { - OMLine line = new BlueLine(last.x, last.y, pt.x, pt.y); - toDraw.add(line); - } - if (first == null) - first = pt; - last = pt; - } - - if (first != null && last != null) { - // draw line from start to beginning intersection - OMLine line = new YellowLine(start.x, start.y, first.x, first.y, 10); - toDraw.add(line); - line = new YellowLine(last.x, last.y, end.x, end.y, 10); - toDraw.add(line); - } - } - } catch (Exception e) { - logger.warning("Got exception " + e); - e.printStackTrace(); - return null; - } - - return newPoints; - - } - - /** - * Finds closest intersection to start and end find path from start - * intersection to end intersection - *

- * - * This method works on screen coordinates. - * - * @param start from start point on map - * @param end to end point on map - * @param segments as side effect, populated with PathSegments between - * returned WayPoints - * @return List of WayPoints - */ - public List getPathOnRoad(Point start, Point end, List segments) { - List newPoints; - try { - Route bestRoute = getRouteBetweenPoints(start, end); - newPoints = displayPathOnRoad(start, end, bestRoute, segments); - } catch (Exception e) { - logger.warning("Got exception " + e); - e.printStackTrace(); - return null; - } - - return newPoints; - } - - /** - * a red point for displaying when we can't find a route between two points - */ - protected class RedPoint - extends OMPoint { - public RedPoint(int x, int y, int radius) { - super(x, y, radius); - } - - public void render(Graphics g) { - setGraphicsColor(g, Color.RED); - draw(g, getShape()); - } - } - - /** a blue line to indicate the found route */ - protected class BlueLine - extends OMLine { - int width; - - public BlueLine(int x, int y, int x2, int y2) { - super(x, y, x2, y2); - this.width = 5; - } - - public void render(Graphics g) { - float[] dash1 = new float[width + 1]; - dash1[0] = 10.f; - - for (int i = 1; i < width; i++) { - dash1[i] = 2.0f; - } - - BasicStroke dashed = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f); - ((Graphics2D) g).setStroke(dashed); - setGraphicsColor(g, Color.BLUE); - draw(g, getShape()); - } - } - - /** - * Returns best Route between two points specified by latitude and longitude. - *

- * - * This method works on latitude/longitude coordinates. - * - * @return Route between two points - */ - public Route getPathOnRoad(LatLonPoint start, LatLonPoint end) { - Intersection startTemp = findClosestIntersection(start); - Intersection endTemp = findClosestIntersection(end); - - Route bestRoute = null; - - if (startTemp != null && endTemp != null) { - if (roadClasses == null) { - logger.warning("huh? road classes is null???"); - return bestRoute; - } - - bestRoute = Route.getBestRoute(startTemp, endTemp, roadClasses.getBestConvoySpeed(), roadClasses.getWorstConvoySpeed()); - } - - if (bestRoute == null) { - if (logger.isLoggable(Level.INFO)) - logger.info("no route from " + startTemp + " to " + endTemp); - } else { - if (logger.isLoggable(Level.INFO)) - logger.info("route from " + startTemp + " to " + endTemp + " is " + bestRoute); - } - - // post condition check - if (logger.isLoggable(Level.INFO) && bestRoute != null) { - float length = 0; - for (int i = 0; i < bestRoute.getRoads().length; i++) { - Road road = bestRoute.getRoads()[i]; - length += road.getLengthInKilometers(); - } - - logger.info("best route from " + bestRoute.getOriginIntersection() + " - start " + start + " to " - + bestRoute.getDestinationIntersection() + " - end " + end + " was " + length + " kilometers."); - } - - return bestRoute; - } - - /** - * Returns best Route between two points - * - * This method works on latitude/longitude coordinates. - * - * @return Route between two points - */ - public Route getRouteBetweenPoints(Point start, Point end) { - return getPathOnRoad(createLatLonPoint(start.x, start.y), createLatLonPoint(end.x, end.y)); - } - - /** - * Look in intersection Quad Tree for closest intersection to point x,y - * - * @return Intersection closest - */ - protected Intersection findClosestIntersection(int x, int y) { - return findClosestIntersection(createLatLonPoint(x, y)); - } - - /** - * Look in intersection Quad Tree for closest intersection to point at - * specified latitude and longitude. - *

- * - * @return Intersection closest - */ - protected Intersection findClosestIntersection(LatLonPoint latLon) { - Intersection inter = (Intersection) interQuadTree.get(latLon.getY(), latLon.getX()); - if (inter == null) - logger.warning("no intersection at " + latLon); - - return inter; - } - - /** - * Iterates over route, populating points and segments lists. Worries about - * sequence order of from and to points, i.e. end of one road should be the - * start of the next. This is not guaranteed by the route, so we have to - * check. - * - * @param bestRoute route to iterate over. - * @param newPoints populated with points on the route. - * @param segments populated with Segments. - */ - protected void populatePointsAndSegments(Route bestRoute, List newPoints, List segments) { - Projection proj = getProjection(); - - Intersection origin = bestRoute.getOriginIntersection(); - // Intersection dest = bestRoute.getDestinationIntersection(); - - if (logger.isLoggable(Level.INFO)) - logger.info("adding " + bestRoute.roads.length + " new roads."); - - Road road = null; - - Intersection from = origin, to = null; - - Set loopSet = new HashSet(); - if (doLoopCheck) - loopSet.add(origin); - Set ptSet = new HashSet(); - for (int i = 0; i < bestRoute.roads.length; i++) { - road = bestRoute.roads[i]; - - if (!from.equals(road.getFirstIntersection()) && !from.equals(road.getSecondIntersection())) { - logger.severe("huh? " + from + " is not an intersection on road " + road); - } - - Point pt = createPoint((Point) proj.forward(from.getLocation(), new Point())); - - if (doLoopCheck) { - if (ptSet.contains(pt)) { - logger.warning("pt set has duplicate at " + pt); - } - ptSet.add(pt); - } - - newPoints.add(pt); - to = road.getOtherIntersection(from); - if (doLoopCheck) { - if (loopSet.contains(to)) { - logger.warning("road has a cycle at " + to); - } - loopSet.add(to); - } - - // check to see if we need to reverse the order of the - // road points, - // which may not be ordered the same as the previous road - - boolean reverse = from.equals(road.getSecondIntersection()); - Segment path = getPathSegment(proj, road, reverse); - - if (logger.isLoggable(Level.INFO)) - logger.info("created path " + path); - - segments.add(path); - - from = to; - } - - if (to != null) { - Point pt = createPoint((Point) proj.forward(to.getLocation(), new Point())); - if (ptSet.contains(pt)) { - logger.warning("pt set has duplicate at " + pt); - } - - newPoints.add(pt); - - if (logger.isLoggable(Level.INFO)) - logger.info(" now " + newPoints.size() + " points and " + segments.size() + " segments."); - } - } - - /** - * Converts a road into a path segment - reverse parameter guarantees the - * ordering of the points is consistent across multiple path segments in the - * whole route. - * - * @return PathSegment converted from a road - */ - protected Segment getPathSegment(Projection proj, Road road, boolean reverse) { - RoadPoint[] roadPoints = road.getRoadPoints(); - - List newPoints = new ArrayList(); - if (reverse) { - for (int i = roadPoints.length - 1; i > 0; i--) { - newPoints.add(createPoint((Point) proj.forward(roadPoints[i].getLocation(), new Point()))); - } - } else { - for (int i = 0; i < roadPoints.length; i++) { - newPoints.add(createPoint((Point) proj.forward(roadPoints[i].getLocation(), new Point()))); - } - } - - return createSegment(newPoints); - } - - /** - * Allows subclasses to redefine segments - */ - protected Segment createSegment(List newPoints) { - return new Segment(newPoints); - } - - /** - * Allows subclasses to redefine points returned - */ - protected Point createPoint(Point pt) { - return new Point(pt); - } - - public Projection getProjection() { - return layer.getProjection(); - } - - /** - * Check the integrity of our data structures. - * - * Scan the known intersections. Note intersections with no roads. Scan the - * roads of the intersection: Each road has two intersections. If the road - * has already been encountered, then we recorded its "other" intersection - * and that must match this intersection. If it doesn't match, record an - * error. If it does match reset its recorded other intersection to be a - * special marker indicating that both ends of the road have been accounted - * for. If the road has not already been encountered, then record its "other" - * intersection. Scan the known roads. Every road should accounted for in the - * "other" intersection table and should be marked as having both - * intersections accounted for. Note the roads which were not found in the - * first scan and the roads which were found, but for which both - * intersections were not found. Remark every road. Finally scan the other - * intersection table for entries which were not marked as being in the roads - * vector. - */ - protected void checkIntegrity() { - // CharArrayWriter errorWriter = new CharArrayWriter(); - // PrintWriter errors = new PrintWriter(errorWriter); - PrintStream errors = System.err; - Hashtable otherIntersections = new Hashtable(); - Object bothIntersections = new Object(); - Object inRoadsVector = new Object(); - for (Enumeration e = intersections.elements(); e.hasMoreElements();) { - Intersection intersection = (Intersection) e.nextElement(); - int nRoads = intersection.getRoadCount(); - if (nRoads == 0) { - errors.println("Dangling intersection"); - errors.println(" Intersection = " + intersection); - continue; - } - for (int i = 0; i < nRoads; i++) { - Road road = intersection.getRoad(i); - Object other = otherIntersections.get(road); - if (other == null) { - otherIntersections.put(road, road.getOtherIntersection(intersection)); - } else if (other == intersection) { - otherIntersections.put(road, bothIntersections); - } else { - errors.println("Misconnected"); - errors.println(" Road = " + road); - errors.println(" Road.Other = " + other); - errors.println(" Intersection = " + intersection); - } - } - } - - for (Enumeration e = roads.elements(); e.hasMoreElements();) { - Road road = (Road) e.nextElement(); - Object other = otherIntersections.get(road); - if (other == null) { - errors.println("Road not found in intersections"); - errors.println(" Road = " + road); - } else if (other != bothIntersections) { - errors.println("Road incompletely connected"); - errors.println(" Road = " + road); - errors.println(" Road.Other = " + other); - } else if (other == inRoadsVector) { - errors.println("Road doubly listed"); - errors.println(" Road = " + road); - } - otherIntersections.put(road, inRoadsVector); - } - for (Enumeration e = otherIntersections.keys(); e.hasMoreElements();) { - Road road = (Road) e.nextElement(); - Object other = otherIntersections.get(road); - if (other != inRoadsVector) { - errors.println("Road not listed"); - errors.println(" Road = " + road); - } - } - // String errString = errorWriter.toString(); - // if (errString.isEmpty()) - // return; - // JTextArea text = new JTextArea(errString); - // JScrollPane scrollPane = new JScrollPane(text); - // final JFrame dialog = new JFrame("Errors"); - // JButton ok = new JButton("OK"); - // ok.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent e) { - // dialog.dispose(); - // } - // }); - // dialog.getContentPane().add(scrollPane, - // BorderLayout.CENTER); - // dialog.getContentPane().add(ok, BorderLayout.SOUTH); - // dialog.setSize(new java.awt.Dimension(640, 480)); - // dialog.setVisible(true); - } - - static class RoadVector { - Road[] roads = new Road[0]; - private int look = 0; - private int roadCount = 0; - - public void clear() { - for (int i = 0; i < roads.length; i++) - roads[i] = null; - look = 0; - roadCount = 0; - } - - public void add(Road r) { - int id = r.getID(); - if (id >= roads.length) { - Road[] oldRoads = roads; - roads = new Road[id + 100 + roads.length]; - System.arraycopy(oldRoads, 0, roads, 0, oldRoads.length); - for (int i = oldRoads.length; i < roads.length; i++) - roads[i] = null; - } - if (roads[id] == null) - roadCount++; - roads[id] = r; - } - - public void remove(Road r) { - int id = r.getID(); - if (roads[id] != null) { - roads[id] = null; - if (id < look) - look = id; - --roadCount; - } - } - - public int findUnusedID() { - while (look < roads.length && roads[look] != null) { - look++; - } - return look; - } - - public Road elementAt(int n) { - return roads[n]; - } - - public Enumeration elements() { - return new Enumeration() { - private int i = 0; - - public boolean hasMoreElements() { - for (; i < roads.length; i++) { - if (roads[i] != null) - return true; - } - return false; - } - - public Object nextElement() { - return roads[i++]; - } - }; - } - - public int size() { - return roadCount; - } - } - - public static class Intersections { - private Hashtable intersections = new Hashtable(); - - public void put(Intersection intersection) { - int suffix = 0; - String name = intersection.getName(); - while (intersections.containsKey(name)) { - suffix++; - name = intersection.getName() + "," + suffix; - } - intersection.setName(name); - intersections.put(name, intersection); - } - - public void remove(Intersection intersection) { - intersections.remove(intersection.getName()); - } - - public Intersection get(String name) { - return (Intersection) intersections.get(name); - } - - public Enumeration elements() { - return intersections.elements(); - } - - public boolean contains(Intersection intersection) { - return intersections.get(intersection.getName()) == intersection; - } - - public void clear() { - intersections.clear(); - } - - public int size() { - return intersections.size(); - } - } - - public static class RoadClasses - extends Hashtable { - float bestConvoySpeed = 0.0f; - float worstConvoySpeed = Float.MAX_VALUE; - - public void put(RoadClass roadClass) { - put(roadClass.getName(), roadClass); - if (roadClass.getConvoySpeed() > bestConvoySpeed) - bestConvoySpeed = roadClass.getConvoySpeed(); - if (roadClass.getConvoySpeed() < worstConvoySpeed) - worstConvoySpeed = roadClass.getConvoySpeed(); - } - - public float getBestConvoySpeed() { - return bestConvoySpeed; - } - - public float getWorstConvoySpeed() { - return worstConvoySpeed; - } - } - - /** BOZO remove me */ - public boolean isEditing() { - return false; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/tools/roads/Route.java b/src/openmap/com/bbn/openmap/tools/roads/Route.java deleted file mode 100644 index 6e3674522..000000000 --- a/src/openmap/com/bbn/openmap/tools/roads/Route.java +++ /dev/null @@ -1,259 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/Route.java,v -// $ -// $RCSfile: Route.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/12/09 21:09:11 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.tools.roads; - -import java.io.Serializable; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; -import java.util.logging.Logger; - -import com.bbn.openmap.proj.GreatCircle; -import com.bbn.openmap.proj.coords.LatLonPoint; - -public class Route implements Cloneable, Serializable { - - private static float MSEC_PER_HOUR = 3600000.0f; - - private String name = null; - - Road[] roads; - - private boolean startWithFirstIntersection; - // private boolean endWithFirstIntersection; - - transient Logger logger = Logger.getLogger(this.getClass().getName()); - - static class NodeInfo { - Intersection intersection; - Road bestRoad = null; - double time; - double crowsPathHours; - - NodeInfo(Intersection intersection, Road road, double time, double crowsPathHours) { - this.intersection = intersection; - this.bestRoad = road; - this.time = time; - this.crowsPathHours = crowsPathHours; - } - } - - public synchronized static Route getBestRoute(Intersection from, Intersection to, - double bestConvoySpeed, double worstConvoySpeed) { - Hashtable marks = new Hashtable(); - boolean haveRoute = false; - LatLonPoint toLoc = to.getLocation(); - double toLat = toLoc.getY(); - double toLon = toLoc.getX(); - LatLonPoint fromLoc = from.getLocation(); - double fromLat = fromLoc.getY(); - double fromLon = fromLoc.getX(); - double timeLimitBase = GreatCircle.sphericalDistance(toLat, toLon, fromLat, fromLon) - / worstConvoySpeed; - double bestTime = Double.MAX_VALUE; - for (float snakeFactor = 1.0f; snakeFactor < 40f; snakeFactor *= 2f) { - // if (logger.isLoggable(Level.INFO)) - // logger.info ("Snake factor " + snakeFactor); - - double timeLimit = timeLimitBase * snakeFactor; - Vector toDo = new Vector(); - toDo.addElement(from); - marks.clear(); - marks.put(from, new NodeInfo(from, null, 0.0f, 0.0f)); - while (!toDo.isEmpty()) { - Vector newToDo = new Vector(); - for (Enumeration e = toDo.elements(); e.hasMoreElements();) { - Intersection thisIntersection = (Intersection) e.nextElement(); - NodeInfo thisInfo = (NodeInfo) marks.get(thisIntersection); - // System.out.println ("examining " + - // thisIntersection); - for (Enumeration e2 = thisIntersection.getRoads(); e2.hasMoreElements();) { - Road road = (Road) e2.nextElement(); - // System.out.println (" - road " + road); - double roadTime = road.getTraverseHours(); - double newTime = thisInfo.time + roadTime; - if (newTime > timeLimit) - continue; - Intersection nextIntersection = road.getOtherIntersection(thisIntersection); - // System.out.println (" - next inter " + - // nextIntersection); - - NodeInfo nextInfo = (NodeInfo) marks.get(nextIntersection); - if (nextInfo == null) { - LatLonPoint nextLoc = nextIntersection.getLocation(); - double crowsPathDistance = GreatCircle.sphericalDistance(toLat, toLon, nextLoc.getY(), nextLoc.getX()); - double crowsPathHours = crowsPathDistance / bestConvoySpeed; - nextInfo = new NodeInfo(nextIntersection, road, newTime, crowsPathHours); - marks.put(nextIntersection, nextInfo); - if (newTime + nextInfo.crowsPathHours > bestTime) - continue; - newToDo.addElement(nextIntersection); - // System.out.println (" - best road for " - // + nextIntersection + " is " + road); - } else if (nextInfo.time > newTime) { - if (!nextInfo.intersection.equals(nextIntersection)) { - System.err.println("huh? lookup of " + nextIntersection - + " gets node info with inter " + nextInfo.intersection); - } - nextInfo.time = newTime; - nextInfo.bestRoad = road; - // System.out.println (" - (redo) best - // road for " + nextIntersection + " is " - // + road); - if (newTime + nextInfo.crowsPathHours > bestTime) - continue; - newToDo.addElement(nextIntersection); - } else { - continue; - } - if (nextIntersection == to) { - // System.err.println ("found end " + to); - bestTime = nextInfo.time; - haveRoute = true; - } - } - } - toDo = newToDo; - } - if (haveRoute) - break; - } - Vector roadVector = new Vector(); - Route result = null; - if (haveRoute) { - for (NodeInfo info = (NodeInfo) marks.get(to); result == null;) { - roadVector.addElement(info.bestRoad); - // System.err.println ("adding Road #" + (i++) + " - " - // + info.bestRoad); - Intersection prevIntersection = info.bestRoad.getOtherIntersection(info.intersection); - if (prevIntersection == from) - result = new Route(roadVector, info.bestRoad.getFirstIntersection() == prevIntersection); - else - info = (NodeInfo) marks.get(prevIntersection); - } - } - marks = null; - return result; - } - - public Route(String name, Road[] roads, boolean startWithFirstIntersection) { - this.name = name; - this.roads = roads; - this.startWithFirstIntersection = startWithFirstIntersection; - } - - private Route(Vector roadVector, boolean startWithFirstIntersection) { - int nRoads = roadVector.size(); - roads = new Road[nRoads]; - for (int i = 0; i < nRoads; i++) - roads[i] = (Road) roadVector.elementAt(nRoads - 1 - i); - this.startWithFirstIntersection = startWithFirstIntersection; - } - - public Object clone() { - return new Route(null, roads, startWithFirstIntersection); - } - - public String getName() { - return name; - } - - public void setName(String newName) { - name = newName; - } - - public Road[] getRoads() { - return roads; - } - - public int getBlockedRoadCount() { - int blockedRoadCount = 0; - for (int i = 0; i < roads.length; i++) { - if (roads[i].isBlocked()) - blockedRoadCount++; - } - return blockedRoadCount; - } - - public void unblockBlockedRoads() { - for (int i = 0; i < roads.length; i++) { - if (roads[i].isBlocked()) - roads[i].unblock(); - } - } - - public Intersection getOriginIntersection() { - if (startWithFirstIntersection) - return roads[0].getFirstIntersection(); - else - return roads[0].getSecondIntersection(); - } - - public Intersection getDestinationIntersection() { - Intersection x = getOriginIntersection(); - for (int i = 0; i < roads.length; i++) { - x = roads[i].getOtherIntersection(x); - } - return x; - } - - public long getTravelTime() { - double hours = 0.0f; - for (int i = 0; i < roads.length; i++) { - Road road = roads[i]; - double roadLength = road.getLengthInKilometers(); - double convoySpeed = road.getRoadClass().getConvoySpeed(); - double timeToTraverse = roadLength / convoySpeed; - hours += timeToTraverse; - } - return (long) (hours * MSEC_PER_HOUR); - } - - public LatLonPoint location(long time) { - double hours = time / MSEC_PER_HOUR; - Intersection from = (startWithFirstIntersection ? roads[0].getFirstIntersection() - : roads[0].getSecondIntersection()); - - for (int i = 0; i < roads.length; i++) { - Road road = roads[i]; - boolean forward = road.getFirstIntersection() == from; - double roadLength = road.getLengthInKilometers(); - double convoySpeed = road.getRoadClass().getConvoySpeed(); - double timeToTraverse = roadLength / convoySpeed; - if (timeToTraverse > hours) { - float fraction = (float) hours / (float) timeToTraverse; - if (!forward) - fraction = 1.0f - fraction; - return road.getLocationAtKilometer(roadLength * fraction); - } - hours -= timeToTraverse; - if (forward) - from = road.getSecondIntersection(); - else - from = road.getFirstIntersection(); - } - return from.getLocation(); - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/ColorFactory.java b/src/openmap/com/bbn/openmap/util/ColorFactory.java deleted file mode 100644 index 502a74449..000000000 --- a/src/openmap/com/bbn/openmap/util/ColorFactory.java +++ /dev/null @@ -1,335 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/ColorFactory.java,v $ -// $RCSfile: ColorFactory.java,v $ -// $Revision: 1.7 $ -// $Date: 2005/08/11 20:39:15 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.awt.Color; -import java.awt.Paint; -import java.lang.reflect.Field; -import java.util.Properties; - -/** - * ColorFactory creates instances of colors. This class has methods which create - * java.awt.Color or - * com.bbn.openmap.omGraphics.OMColor objects. This class handles - * creation of Color objects in a Java version-neutral way by using reflection - * to create the java.awt.Color object. This way we support the extended Java 2 - * platform without sacrificing support for JDK 1.1.X. - *

- * NOTE: For general RGB-colored graphics, you should directly use the - * java.awt.Color 1.1.X constructors. If you are interested in using - * alpha-valued colors, or using colors in a (JDK) version-neutral way, then - * read on... - *

- * You may want to use this class because: - *

    - *
  • You want to use alpha-valued colors in your images under both JDK 1.1 and - * JDK 1.2. (JDK1.1 has limited support for alpha-valued images). You can use - * the appropriate createColor() methods in this class with the - * forceAlpha set to true and you are guaranteed - * (almost!) to get back an alpha-valued color. - *

    - *

  • You want to use alpha-valued colors for generic graphics, but only in a - * version-neutral way and if the support is available (e.g., you're running - * under the Java 2 platform). In this case you can call the appropriate - * createColor() methods without the forceAlpha - * argument, or with forceAlpha set to false. - *
- * - * @see com.bbn.openmap.omGraphics.OMColor - */ -public class ColorFactory { - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color to use if the property value doesn't work - * @return java.awt.Color - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault) - throws NumberFormatException { - String colorString = p.getProperty(propName, dfault); - return parseColor(colorString, true); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color to use if the property value doesn't work - * @param forceAlpha - * force using alpha value - * @return java.awt.Color - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault, boolean forceAlpha) - throws NumberFormatException { - String colorString = p.getProperty(propName, dfault); - return parseColor(colorString, forceAlpha); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p - * properties - * @param propName - * the name of the property - * @param dfault - * color to use if the property value doesn't work - * @return java.awt.Color - * @see #parseColor(String, boolean) - */ - public static Paint parseColorFromProperties(Properties p, String propName, Paint dfault) { - try { - String colorString = p.getProperty(propName); - if (colorString != null) { - return parseColor(colorString, true); - } - } catch (NumberFormatException nfe) { - } - return dfault; - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. - * - * @param colorString - * the 24/32bit hex string value (ARGB) - * @return java.awt.Color 24bit RGB, 24/32bit ARGB - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #parseColor(String, boolean) - */ - public static Color parseColor(String colorString) throws NumberFormatException { - return parseColor(colorString, true); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString - * the 24/32bit hex string value (ARGB) - * @param forceAlpha - * force using alpha value - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException - * if the specified string cannot be interpreted as a - * hexidecimal integer - * @see #createColor(int, boolean) - */ - public static Color parseColor(String colorString, boolean forceAlpha) throws NumberFormatException { - - int value; - - // If we come across people who do one letter per color. - if (colorString.length() == 3) { - colorString = new StringBuilder().append(colorString.charAt(0)).append(colorString.charAt(0)) - .append(colorString.charAt(1)).append(colorString.charAt(1)).append(colorString.charAt(2)) - .append(colorString.charAt(2)).toString(); - } - - try { - value = (int) Long.parseLong(colorString, 16); - } catch (NumberFormatException nfe) { - value = Long.decode(colorString).intValue(); - // If decode can't catch it, throw an Exception... - } - - // We want to test for this - if the length of the colorString - // is less than 7, then the caller probably doesn't care about - // transparency and wants the color to be opaque. However, - // "0" is a common number for clear, and should be - // transparent. - if (colorString.length() < 7 && !colorString.equals("0")) { - // Just a RGB value, use regular JDK1.1 constructor - return new Color(value); - } - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param red - * red component (0.0-1.0) - * @param green - * green component (0.0-1.0) - * @param blue - * blue component (0.0-1.0) - * @param alpha - * alpha component (0.0-1.0) - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(float red, float green, float blue, float alpha) { - return createColor(red, green, blue, alpha, true); - } - - /** - * Create a Color. - * - * @param red - * red component (0.0-1.0) - * @param green - * green component (0.0-1.0) - * @param blue - * blue component (0.0-1.0) - * @param alpha - * alpha component (0.0-1.0) - * @param forceAlpha - * force using alpha value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(float red, float green, float blue, float alpha, boolean forceAlpha) { - int value = (((int) (alpha * 255) & 0xff) << 24) | (((int) (red * 255) & 0xff) << 16) - | (((int) (green * 255) & 0xff) << 8) | (int) (blue * 255) & 0xff; - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param red - * red component (0-255) - * @param green - * green component (0-255) - * @param blue - * blue component (0-255) - * @param alpha - * alpha component (0-255) - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int red, int green, int blue, int alpha) { - return createColor(red, green, blue, alpha, true); - } - - /** - * Create a Color. - * - * @param red - * red component (0-255) - * @param green - * green component (0-255) - * @param blue - * blue component (0-255) - * @param alpha - * alpha component (0-255) - * @param forceAlpha - * force using alpha value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int red, int green, int blue, int alpha, boolean forceAlpha) { - int value = ((alpha & 0xff) << 24) | ((red & 0xff) << 16) | ((green & 0xff) << 8) | blue & 0xff; - return createColor(value, forceAlpha); - } - - /** - * Create a Color. - * - * @param value - * 32bit ARGB color value - * @return Color or OMColor that has an ARGB value - * @see #createColor(int, boolean) - */ - public static Color createColor(int value) { - return createColor(value, true); - } - - /** - * Create a Color. - * - * @param value - * 32bit ARGB color value - * @param forceAlpha - * force using alpha value the underlying java.awt.Color supports - * it - * @return Color or OMColor that has an ARGB value - */ - public static Color createColor(int value, boolean forceAlpha) { - return new Color(value, forceAlpha); - } - - public static String getHexColorString(Color color) { - return Integer.toHexString((color.getRGB() & 0x00FFFFFF) | (color.getAlpha() << 24)); - } - - /** - * Method that returns a java.awt.Color object given the name of the color. - * Depends on the static instances of color provided by the java.awt.Color - * class. - * - * @param name - * @param defaultColor - * @return Color that reflects the name, or the default color. - */ - public static Color getNamedColor(String name, Color defaultColor) { - if (name != null) { - Field[] colorFields = Color.class.getDeclaredFields(); - for (int i = 0; i < colorFields.length; i++) { - Field f = colorFields[i]; - try { - if (name.equalsIgnoreCase(f.getName())) { - return (Color) f.get((Object) null); - } - } catch (IllegalAccessException iae) { - // Whoa, shouldn't happen, but hey - } catch (ClassCastException cce) { - // Shouldn't ask for anything other than colors, - // either. - } - } - } - - return defaultColor; - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/ComponentFactory.java b/src/openmap/com/bbn/openmap/util/ComponentFactory.java deleted file mode 100644 index 0a80957cc..000000000 --- a/src/openmap/com/bbn/openmap/util/ComponentFactory.java +++ /dev/null @@ -1,660 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/ComponentFactory.java,v $ -// $RCSfile: ComponentFactory.java,v $ -// $Revision: 1.15 $ -// $Date: 2006/05/19 15:26:26 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Properties; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.BasicI18n; -import com.bbn.openmap.PropertyConsumer; -import com.bbn.openmap.event.ProgressEvent; -import com.bbn.openmap.event.ProgressSupport; - -/** - * The OpenMap ComponentFactory is a class that can construct objects from class - * names, with the added capability of passing the new object a Properties - * object to initialize itself. The new object may also receive a property - * prefix to use to scope its properties from the Properties object. It is - * sensitive to the OpenMap paradigm of marker names in a list: That a list of - * objects can be defined as a space separated names (marker names) within a - * String. Those marker names can serve as a prefix for other properties within - * a Properties object, as well as the prefix for a '.class' property to define - * the class name for the new object. - */ -public class ComponentFactory { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.util.ComponentFactory"); - - /** - * The property to use for the class name of new objects - ".class". Expects - * that a prefix will be prepended to it. - */ - public static final String DotClassNameProperty = ".class"; - /** - * A property to use for the class name of new objects - "class". Can be - * used with the PropUtils.objectsFromProperties method as the defining - * property. - */ - public static final String ClassNameProperty = "class"; - - /** - * The singleton instance of the ComponentFactory. - */ - private static ComponentFactory singleton; - - protected ComponentFactory() { - } - - /** - * Method call to retrieve the singleton instance of the ComponentFactory. - * - * @return ComponentFactory. - */ - protected static ComponentFactory getInstance() { - if (singleton == null) { - singleton = new ComponentFactory(); - } - return singleton; - } - - /** - * Set the singleton instance of the ComponentFactory. - * - * @param cf - */ - protected static void setInstance(ComponentFactory cf) { - singleton = cf; - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @return Vector containing the new Objects. - */ - public static Vector create(Vector markerNames, Properties properties) { - return getInstance()._create(markerNames, null, properties, null, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker names. - * @param properties Properties object containing the details. - * @return Vector containing the new Objects. - */ - public static Vector create(Vector markerNames, String prefix, Properties properties) { - return getInstance()._create(markerNames, prefix, properties, null, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates - * to. It's OK if this is null to not have progress events sent. - * @return Vector containing the new Objects. - */ - public static Vector create(Vector markerNames, String prefix, Properties properties, ProgressSupport progressSupport) { - return getInstance()._create(markerNames, prefix, properties, progressSupport, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates - * to. It's OK if this is null to not have progress events sent. - * @return Vector containing the new Objects. - */ - public static Vector create(Vector markerNames, Properties properties, ProgressSupport progressSupport) { - return getInstance()._create(markerNames, null, properties, progressSupport, false); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates - * to. It's OK if this is null to not have progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble - * creating an object, it's marker name will be placed in the - * returned vector instead of a component. If false, only valid - * objects will be returned in the vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can - * figure out which one couldn't be created. In any case, the size - * of the returned vector is the same size as the markerNames - * vector, so you can figure out which markerNames go with which - * objects. - */ - public static Vector create(Vector markerNames, Properties properties, ProgressSupport progressSupport, - boolean matchInOutVectorSize) { - return getInstance()._create(markerNames, null, properties, progressSupport, matchInOutVectorSize); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates - * to. It's OK if this is null to not have progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble - * creating an object, it's marker name will be placed in the - * returned vector instead of a component. If false, only valid - * objects will be returned in the vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can - * figure out which one couldn't be created. In any case, the size - * of the returned vector is the same size as the markerNames - * vector, so you can figure out which markerNames go with which - * objects. - */ - public static Vector create(Vector markerNames, String prefix, Properties properties, - ProgressSupport progressSupport, boolean matchInOutVectorSize) { - - return getInstance()._create(markerNames, prefix, properties, progressSupport, matchInOutVectorSize); - } - - /** - * Given a Vector of marker name Strings, and a Properties object, look in - * the Properties object for the markerName.class property to get a class - * name to create each object. Then, if the new objects are - * PropertyConsumers, use the marker name as a property prefix to get - * properties for that object out of the Properties. - * - * @param markerNames String of space separated marker names. - * @param prefix The prefix that should be prepended to the marker names. - * @param properties Properties object containing the details. - * @param progressSupport ProgressSupport object to provide progress updates - * to. It's OK if this is null to not have progress events sent. - * @param matchInOutVectorSize if true, then if there is any trouble - * creating an object, it's marker name will be placed in the - * returned vector instead of a component. If false, only valid - * objects will be returned in the vector. - * @return Vector containing the new Objects. If a component could not be - * created, the markerName is returned in its place, so you can - * figure out which one couldn't be created. In any case, the size - * of the returned vector is the same size as the markerNames - * vector, so you can figure out which markerNames go with which - * objects. - */ - protected Vector _create(Vector markerNames, String prefix, Properties properties, ProgressSupport progressSupport, - boolean matchInOutVectorSize) { - - int size = markerNames.size(); - Vector vector = new Vector(size); - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Creating Components", 100, 0); - } - - for (int i = 0; i < size; i++) { - String componentName = PropUtils.getScopedPropertyPrefix(prefix) + markerNames.elementAt(i); - - String classProperty = componentName + DotClassNameProperty; - String className = properties.getProperty(classProperty); - - if (className == null) { - logger.warning("Failed to locate property \"" + componentName + "\" with class \"" + classProperty - + "\"\n Skipping component \"" + componentName + "\""); - if (matchInOutVectorSize) { - vector.add(componentName); - } - continue; - } - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Creating Components", size, i); - } - - Object component = create(className, componentName, properties); - - if (component != null) { - vector.add(component); - if (logger.isLoggable(Level.FINE)) { - logger.fine("ComponentFactory: [" + className + "(" + i + ")] created"); - } - } else { - if (matchInOutVectorSize) { - vector.add(componentName); - } - logger.info("[" + componentName + " : " + className + "(" + i - + ")] NOT created. -- Set logging flag to FINE/FINER for details."); - } - } - - if (progressSupport != null) { - progressSupport.fireUpdate(ProgressEvent.UPDATE, "Configuring...", size, size); - } - return vector; - } - - /** - * Create a single object. - * - * @param className Class name to instantiate, empty constructor. - * @return object if all goes well, null if not. - */ - public static Object create(String className) { - return create(className, (Object[]) null, null, null); - } - - /** - * Create a single object. - * - * @param className Class name to instantiate. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if not. - */ - public static Object create(String className, Properties properties) { - return create(className, (Object[]) null, null, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return Object or null if it couldn't be created - */ - public static Object create(String className, String prefix, Properties properties) { - - return create(className, (Object[]) null, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the - * constructor of the component. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs) { - return create(className, constructorArgs, null, null, null); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the - * constructor of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, Class[] argClasses) { - return create(className, constructorArgs, argClasses, null, null); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the - * constructor of the component. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, String prefix, Properties properties) { - return create(className, constructorArgs, null, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the - * constructor of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - public static Object create(String className, Object[] constructorArgs, Class[] argClasses, String prefix, - Properties properties) { - return getInstance()._create(className, constructorArgs, argClasses, prefix, properties); - } - - /** - * Create a single object. If you want it to complain about classes it can't - * find, then set the 'basic' debug flag. - * - * @param className Class name to instantiate. - * @param constructorArgs an Object array of arguments to use in the - * constructor of the component. - * @param argClasses an array of classes to use to scope which constructor - * to use. If null, then an array will be built from the - * constructorArgs. - * @param prefix Properties prefix to use by the object to scope its - * properties. - * @param properties Properties to use to initialize the object, if the - * object is a PropertyConsumer. - * @return object if all goes well, null if anything bad happens. - */ - protected Object _create(String className, Object[] constructorArgs, Class[] argClasses, String prefix, Properties properties) { - String errorMessage = null; - Throwable exceptionCaught = null; - boolean DEBUG = false; - try { - - if (logger.isLoggable(Level.FINER)) { - DEBUG = true; - logger.finer("creating: " + className); - } - - // Apparently, this fails in certain cases where OpenMap is being - // used as a plugin in a NetBeans or Eclipse architecture and the - // application classloader isn't aware of the plugins classes. It - // limits the creation of the object to classes in the caller's - // classloader. - // Class newObjClass = Class.forName(className.trim()); - // replaced with: - - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if (cl == null) { - cl = this.getClass().getClassLoader(); - } - Class newObjClass = Class.forName(className.trim(), true, cl); - - if (DEBUG) - logger.finer(" - got class for " + className); - - if (argClasses == null) { - if (constructorArgs != null && constructorArgs.length > 0) { - - argClasses = new Class[constructorArgs.length]; - for (int i = 0; i < argClasses.length; i++) { - argClasses[i] = constructorArgs[i].getClass(); - } - } else { - // If empty, make null - constructorArgs = null; - } - } - - if (DEBUG) { - StringBuffer sb = new StringBuffer(); - if (constructorArgs == null) { - sb.append("null"); - } else { - for (int i = 0; i < constructorArgs.length; i++) { - sb.append(constructorArgs[i].getClass().getName()); - if (i < constructorArgs.length - 1) - sb.append(", "); - } - } - logger.finer(" - created class arguments [" + sb.toString() + "]"); - } - - Constructor constructor = null; - Object obj = null; - - try { - constructor = newObjClass.getConstructor(argClasses); - - if (DEBUG) - logger.finer(" - got constructor"); - - // Create component - obj = constructor.newInstance(constructorArgs); - if (DEBUG) - logger.finer(" - got object"); - - } catch (NoSuchMethodException nsmei) { - /* - * The argClasses may have subclasses of what the desired - * constructor needs, so we need to check explicitly. - */ - obj = createWithSubclassConstructorArgs(newObjClass, argClasses, constructorArgs); - if (DEBUG && obj != null) - logger.finer(" - got object on try #2"); - } - - if (obj instanceof PropertyConsumer && properties != null) { - if (DEBUG) { - logger.finer(" setting properties with prefix \"" + prefix + "\""); - } - ((PropertyConsumer) obj).setProperties(prefix, properties); - - if (Debug.debugging(BasicI18n.DEBUG_CREATE)) { - /* - * If we're interested in creating resource bundle files, we - * should cause these PropertyConsumers to ask for their - * property info, since this is where most of the elective - * GUI strings are queried and found. - */ - ((PropertyConsumer) obj).getPropertyInfo(null); - } - - if (DEBUG) - logger.finer(" - set properties"); - } - return obj; - - } catch (NoSuchMethodException nsme) { - exceptionCaught = nsme; - errorMessage = "NoSuchMethodException: " + nsme.getMessage(); - } catch (InstantiationException ie) { - exceptionCaught = ie; - errorMessage = "InstantiationException: " + ie.getMessage() + " - Might be trying to create an abstract class"; - } catch (IllegalAccessException iae) { - if (DEBUG) - iae.printStackTrace(); - exceptionCaught = iae; - errorMessage = "IllegalAccessException: " + iae.getMessage(); - } catch (IllegalArgumentException iae2) { - if (DEBUG) - iae2.printStackTrace(); - exceptionCaught = iae2; - errorMessage = "IllegalArgumentException: " + iae2.getMessage(); - } catch (InvocationTargetException ite) { - if (DEBUG) - ite.printStackTrace(); - exceptionCaught = ite; - errorMessage = "InvocationTargetException: " + ite.getMessage(); - } catch (ClassNotFoundException cnfe) { - exceptionCaught = cnfe; - errorMessage = "ClassNotFoundException: " + cnfe.getMessage(); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("Failed to create \"" + className - + (prefix != null ? "\" using component marker name \"" + prefix + "\"" : "") + " - error message: " - + errorMessage); - - if (exceptionCaught != null) { - logger.log(Level.WARNING, "Exception reported is as follows:", exceptionCaught); - } - } - - return null; - } - - /** - * Method to create Object with arguments. - * - * @param newObjClass the Class to be created. - * @param argClasses an array of Classes describing the arguments. - * @param constructorArgs an array of Objects for arguments. - * @return Object created from the Class and arguments. - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - protected Object createWithSubclassConstructorArgs(Class newObjClass, Class[] argClasses, Object[] constructorArgs) - throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException { - - boolean DEBUG = logger.isLoggable(Level.FINER); - - int numArgClasses = 0; - - if (argClasses != null) { - numArgClasses = argClasses.length; - } - - Constructor[] constructors = newObjClass.getConstructors(); - int numConstructors = constructors.length; - - if (DEBUG) { - logger.finer(" - searching " + numConstructors + " possible constructor" + (numConstructors == 1 ? "" : "s")); - } - - for (int i = 0; i < numConstructors; i++) { - Constructor constructor = constructors[i]; - - Class[] arguments = constructor.getParameterTypes(); - int numArgs = arguments.length; - - // First, check the number of arguments for a match - if (numArgs != numArgClasses) { - if (DEBUG) { - logger.finer(" - constructor " + i + " with " + numArgs + " arguments not a match"); - } - - continue; // Nope, not it. - } - - // OK, empty constructor desired, punch... - // If argClasses == null, then numArgs will equal zero. Makes the - // compiler happy. - if (numArgs == 0 || argClasses == null) { - if (DEBUG) { - logger.finer(" - constructor " + i + " with no arguments is a match"); - } - return constructor; - } - - // Check to see if the argument classes of the Constructor - // are assignable to the desired argClasses being sought. - boolean good = false; - for (int j = 0; j < numArgs; j++) { - if (arguments[j] == argClasses[j]) { - if (DEBUG) { - logger.finer(" - direct arg class match, arg " + j); - } - good = true; // Maintain true... - } else if (arguments[j].isAssignableFrom(argClasses[j])) { - - // Doesn't work quite yet. May have to check for - // super-super class,etc, and we still get an - // IllegalArgumentException due to argument type - // mismatch. - - // Is this even necessary? Don't think so... - argClasses[j] = argClasses[j].getSuperclass(); - if (DEBUG) { - logger.finer(" - superclass arg class match, arg " + j + " reassigning to " + argClasses[j].toString()); - } - good = true; // Maintain true... - // } else if (constructorArgs[j] instanceof - // Number) { - // if (DEBUG) { - // Debug.output(" - Number type match, arg " + j); - // } - // good = true; // Maintain true... - - } else { - if (DEBUG) { - logger.finer(" - arg class mismatch on arg " + j + ", bailing (" + arguments[j].getName() + " vs. " - + argClasses[j].getName() + ")"); - } - good = false; // Punch with false - break; - } - } - - if (good) { - if (DEBUG) { - logger.finer(" - creating object"); - } - Object obj = constructor.newInstance(constructorArgs); - if (DEBUG) { - logger.finer(" - created object"); - } - return obj; - } - } - - return null; - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/DataBounds.java b/src/openmap/com/bbn/openmap/util/DataBounds.java deleted file mode 100644 index e016bb542..000000000 --- a/src/openmap/com/bbn/openmap/util/DataBounds.java +++ /dev/null @@ -1,224 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/DataBounds.java,v $ -// $RCSfile: DataBounds.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:30 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.awt.geom.Point2D; - -/** - * A simple utility class that holds a min, max for a group of points. - */ -public class DataBounds { - - protected Point2D min; - protected Point2D max; - - protected DataBounds hardLimits; - - /** - * True if the direction of the y coordinates increase in the up direction. - * Should be set to false if larger y values are actually lower pixel values - * on the map. - */ - boolean yDirUp = true; - - public DataBounds() { - } - - public DataBounds(double minx, double miny, double maxx, double maxy) { - add(minx, miny); - add(maxx, maxy); - } - - public DataBounds(Point2D minP, Point2D maxP) { - add(minP); - add(maxP); - } - - /** - * @return a point set to the average of the min and max values. May return - * null if no points have been added - */ - public Point2D getCenter() { - if (min != null) { - double minx = min.getX(); - double miny = min.getY(); - double maxx = max.getX(); - double maxy = max.getY(); - return new Point2D.Double((minx + maxx) / 2, (miny + maxy) / 2); - } else - return null; - } - - public String toString() { - return "DataBounds| min:" + min + " max:" + max; - } - - /** - * @return upper right point - */ - public Point2D getMax() { - return max; - } - - /** - * @return lower left point - */ - public Point2D getMin() { - return min; - } - - public void add(double x, double y) { - if (min == null) { - min = new Point2D.Double(x, y); - max = new Point2D.Double(x, y); - } else { - double minx = min.getX(); - double miny = min.getY(); - double maxx = max.getX(); - double maxy = max.getY(); - - if (minx > x) - minx = x; - if (miny > y) - miny = y; - if (maxx < x) - maxx = x; - if (maxy < y) - maxy = y; - - if (hardLimits != null) { - double hlminx = hardLimits.min.getX(); - double hlminy = hardLimits.min.getY(); - double hlmaxx = hardLimits.max.getX(); - double hlmaxy = hardLimits.max.getY(); - - minx = setInRange(hlmaxx, hlminx, minx); - maxx = setInRange(hlmaxx, hlminx, maxx); - miny = setInRange(hlmaxy, hlminy, miny); - maxy = setInRange(hlmaxy, hlminy, maxy); - - } - - min.setLocation(minx, miny); - max.setLocation(maxx, maxy); - } - } - - /** - * Make sure the value is within the range. - * - * @param hi high range value - * @param lo low range value - * @param val testing value - * @return the value, adjusted if necessary. - */ - protected double setInRange(double hi, double lo, double val) { - if (val > hi) { - val = hi; - } - - if (val < lo) { - val = lo; - } - - return val; - } - - public void add(Point2D point) { - add((double) point.getX(), (double) point.getY()); - } - - public boolean contains(Point2D query) { - double x = query.getX(); - double y = query.getY(); - return x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY(); - } - - public double getWidth() { - return max.getX() - min.getX(); - } - - public double getHeight() { - return max.getY() - min.getY(); - } - - public DataBounds getHardLimits() { - return hardLimits; - } - - public void setHardLimits(DataBounds hardLimits) { - this.hardLimits = hardLimits; - } - - public boolean isyDirUp() { - return yDirUp; - } - - public void setyDirUp(boolean yDirUp) { - this.yDirUp = yDirUp; - } - - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof DataBounds) { - DataBounds dobj = (DataBounds) obj; - boolean match = (min == null && dobj.getMin() == null && max == null && dobj.getMax() == null); - boolean match2 = false; - try { - match2 = getMin().equals(dobj.getMin()) && getMax().equals(dobj.getMax()); - } catch (NullPointerException npe) { - - } - - return this.yDirUp == dobj.yDirUp && (match || match2); - } - - return false; - } - - public int hashCode() { - int result = HashCodeUtil.SEED; - // collect the contributions of various fields - if (max != null) { - result = HashCodeUtil.hash(result, max.getY()); - result = HashCodeUtil.hash(result, max.getX()); - } - if (min != null) { - result = HashCodeUtil.hash(result, min.getY()); - result = HashCodeUtil.hash(result, min.getX()); - } - result = HashCodeUtil.hash(result, yDirUp); - return result; - } - - public boolean intersects(DataBounds db2) { - if (db2 == null) { - return false; - } - Point2D min2 = db2.getMin(); - Point2D max2 = db2.getMax(); - return !(min2 == null || (min2.getY() > max.getY() || max2.getY() < min.getY()) || (min2.getX() > max.getX() || max2.getX() < min.getX())); - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/FileUtils.java b/src/openmap/com/bbn/openmap/util/FileUtils.java deleted file mode 100644 index cf9591e30..000000000 --- a/src/openmap/com/bbn/openmap/util/FileUtils.java +++ /dev/null @@ -1,455 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/FileUtils.java,v -// $ -// $RCSfile: FileUtils.java,v $ -// $Revision: 1.6 $ -// $Date: 2006/07/10 23:22:28 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.Adler32; -import java.util.zip.CheckedOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import javax.swing.filechooser.FileFilter; - -import com.bbn.openmap.Environment; - -public class FileUtils { - - protected static Logger logger = Logger.getLogger("com.bbn.openmap.util.FileUtils"); - - public static String getFilePathToSaveFromUser(String title) { - OpenFileRunnable runnable = new OpenFileRunnable(title, null) { - public void run() { - JFileChooser chooser = getChooser(title); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showSaveDialog(null); - result = handleResponse(chooser, state); - } - }; - runnable.invoke(); - return runnable.getResult(); - } - - public static String getFilePathToOpenFromUser(String title) { - return getFilePathToOpenFromUser(title, null); - } - - public static String getFilePathToOpenFromUser(String title, FileFilter ff) { - OpenFileRunnable runnable = new OpenFileRunnable(title, ff); - runnable.invoke(); - return runnable.getResult(); - } - - public static String getPathToOpenFromUser(String title, FileFilter ff, int fileSelectionMode, - String acceptButtonText) { - OpenPathRunnable runnable = new OpenPathRunnable(title, ff, fileSelectionMode, acceptButtonText); - runnable.invoke(); - return runnable.getResult(); - } - - static class OpenFileRunnable implements Runnable { - - String title; - FileFilter fileFilter; - String result; - - OpenFileRunnable(String title, FileFilter ff) { - this.title = title; - this.fileFilter = ff; - } - - public void run() { - JFileChooser chooser = getChooser(title); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showOpenDialog(null); - this.result = handleResponse(chooser, state); - } - - String getResult() { - return result; - } - - void invoke() { - try { - if (!SwingUtilities.isEventDispatchThread()) { - SwingUtilities.invokeAndWait(OpenFileRunnable.this); - } else { - run(); - } - } catch (Exception e) { - if (logger.isLoggable(Level.FINE)) { - e.printStackTrace(); - } - } - } - } - - static class OpenPathRunnable extends OpenFileRunnable { - - int fileSelectionMode; - String acceptButtonText; - - OpenPathRunnable(String title, FileFilter ff, int fileSelectionMode, String acceptButtonText) { - super(title, ff); - this.fileSelectionMode = fileSelectionMode; - this.acceptButtonText = acceptButtonText; - } - - public void run() { - JFileChooser chooser = getChooser(title); - chooser.setFileSelectionMode(fileSelectionMode); - if (fileFilter != null) { - chooser.setFileFilter(fileFilter); - } - int state = chooser.showDialog(null, acceptButtonText); - this.result = handleResponse(chooser, state); - } - } - - public static JFileChooser getChooser(String title) { - // setup the file chooser - File startingPoint = new File(Environment.get("lastchosendirectory", System.getProperty("user.home"))); - JFileChooser chooser = new JFileChooser(startingPoint); - chooser.setDialogTitle(title); - return chooser; - } - - public static String handleResponse(JFileChooser chooser, int state) { - String ret = null; - try { - // only bother trying to read the file if there is one - // for some reason, the APPROVE_OPTION said it was a - // boolean during compile and didn't work in this next - // statement - if ((state != JFileChooser.CANCEL_OPTION) && (state != JFileChooser.ERROR_OPTION)) { - - ret = chooser.getSelectedFile().getCanonicalPath(); - - int dirIndex = ret.lastIndexOf(File.separator); - if (dirIndex >= 0) { - // store the selected file for later - Environment.set("lastchosendirectory", ret.substring(0, dirIndex)); - } - } - } catch (IOException ioe) { - JOptionPane.showMessageDialog(null, ioe.getMessage(), "Error picking file", JOptionPane.ERROR_MESSAGE); - ioe.printStackTrace(); - } - return ret; - } - - /** - * Copy a file to another location, byte-wise. - * - * @param fromFile - * the File to copy from. - * @param toFile - * the File to copy to. - * @param bufSize - * the byte size of the transfer buffer. - * @throws IOException - * Thrown if anything goes wrong. - */ - public static void copy(File fromFile, File toFile, int bufSize) throws IOException { - - FileInputStream fis = new FileInputStream(fromFile); - FileOutputStream fos = new FileOutputStream(toFile); - - if (bufSize <= 0) { - bufSize = 1024; - } - - byte[] bytes = new byte[bufSize]; - - int numRead; - - while ((numRead = fis.read(bytes)) > 0) { - fos.write(bytes, 0, numRead); - } - - fis.close(); - fos.close(); - } - - /** - * Delete a file or a directory, including its content. - * - * @param file file to delete - * @throws IOException if there's a problem - */ - public static void deleteFile(File file) throws IOException { - - if (file.isDirectory()) { - - // directory is empty, then delete it - if (file.list().length == 0) { - - file.delete(); - System.out.println("Directory is deleted : " + file.getAbsolutePath()); - - } else { - - // list all the directory contents - String files[] = file.list(); - - for (String temp : files) { - // construct the file structure - File fileDelete = new File(file, temp); - - // recursive delete - deleteFile(fileDelete); - } - - // check the directory again, if empty then delete it - if (file.list().length == 0) { - file.delete(); - - } - } - - } else { - // if file, then delete it - file.delete(); - - } - } - - /** - * Create a zip file containing the given File. - * - * @param zipFileName The path to the zip file. If it doesn't end in .zip, - * .zip will be added to it. - * @param toBeZipped The Path of the file/directory to be zipped. - * @throws IOException if there's a problem - * @throws FileNotFoundException if there's a problem - */ - public static void saveZipFile(String zipFileName, File toBeZipped) throws IOException, FileNotFoundException { - - try { - - if (!zipFileName.endsWith(".zip")) { - zipFileName += ".zip"; - } - - File zipFile = new File(zipFileName); - if (!zipFile.getParentFile().exists()) { - zipFile.getParentFile().mkdirs(); - } - FileOutputStream fos = new FileOutputStream(zipFile); - ZipOutputStream zoStream = new ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.STORED); - writeZipEntry(toBeZipped, zoStream, toBeZipped.getParent().length() + 1); - zoStream.close(); - } catch (SecurityException se) { - logger.warning("Security Exception caught while creating " + zipFileName); - } - } - - /** - * Create a zip file containing the files in the list. The entries will not - * have their parent's file names in their path, they are stored with the - * given file at the root of the zip/jar. - * - * @param zipFileName The path to the zip/jar file. - * @param toBeZipped The List of files to be placed in the zip/jar. - * @throws IOException if there's a problem - * @throws FileNotFoundException if there's a problem - */ - public static void saveZipFile(String zipFileName, List toBeZipped) - throws IOException, FileNotFoundException { - - try { - - File zipFile = new File(zipFileName); - if (!zipFile.getParentFile().exists()) { - zipFile.getParentFile().mkdirs(); - } - FileOutputStream fos = new FileOutputStream(zipFile); - CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32()); - ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(checksum)); - // ZipOutputStream zoStream = new ZipOutputStream(fos); - // zoStream.setMethod(ZipOutputStream.STORED); - for (File file : toBeZipped) { - writeZipEntry(file, zoStream, file.getParent().length() + 1); - } - zoStream.close(); - } catch (SecurityException se) { - logger.warning("Security Exception caught while creating " + zipFileName); - } - } - - /** - * Writes a file to the jar stream. - * - * @param toBeZipped the file to be written - * @param zoStream the stream to write it to, prepared for the - * ZipFile/JarFile - * @param prefixTrimLength The number of characters to trim off the absolute - * path of the file to be zipped. Can be useful to adjust this to - * adjust the directory depth of the entry for when it is unpacked. - * If less than 0, only the file name will be used. - * @throws IOException if there's a problem - */ - public static void writeZipEntry(File toBeZipped, ZipOutputStream zoStream, int prefixTrimLength) - throws IOException { - - if (toBeZipped.isDirectory()) { - File[] files = toBeZipped.listFiles(); - for (int i = 0; i < files.length; i++) { - writeZipEntry(files[i], zoStream, prefixTrimLength); - } - } else { - - if (logger.isLoggable(Level.FINE)) { - logger.fine(toBeZipped + ", " + toBeZipped.getAbsolutePath().substring(prefixTrimLength) + ")"); - } - - writeZipEntry(toBeZipped, zoStream, prefixTrimLength < 0 ? toBeZipped.getName() - : toBeZipped.getAbsolutePath().substring(prefixTrimLength)); - } - } - - protected static void writeZipEntry(File fromFile, ZipOutputStream zoStream, String entryName) throws IOException { - - entryName = entryName.replace('\\', '/'); - - // long size = fromFile.length(); - ZipEntry zEntry = new ZipEntry(entryName); - // zEntry.setSize(size); - // zEntry.setCrc(0);// Don't know what it these values are - // right now, but zero works... - zoStream.putNextEntry(zEntry); - - FileInputStream fis = new FileInputStream(fromFile); - - byte[] bytes = new byte[1024]; - - int numRead; - // CRC32 checksum = new CRC32(); - while ((numRead = fis.read(bytes)) > 0) { - zoStream.write(bytes, 0, numRead); - // checksum.update(bytes, 0, numRead); - } - // zEntry.setCrc(checksum.getValue()); - zoStream.closeEntry(); - fis.close(); - } - - /** - * Unpack a zip file. - * - * @param zipFileName - * The path name of the zip file to unpack. - * @param toDir - * the directory to put the unpacked files in. - * @param deleteAfter - * flag to delete the zip file when complete. - */ - public static void openZipFile(String zipFileName, File toDir, boolean deleteAfter) { - if (zipFileName != null) { - try { - InputStream in; - - if (!toDir.exists()) { - toDir.mkdirs(); - } - - URL zipurl = PropUtils.getResourceOrFileOrURL(zipFileName); - if (zipurl != null) { - - in = new BufferedInputStream(zipurl.openStream()); - - if (logger.isLoggable(Level.FINE)) { - logger.fine(" unzipping " + zipFileName); - } - ZipInputStream zin = new ZipInputStream(in); - ZipEntry e; - - while ((e = zin.getNextEntry()) != null) { - - if (e.isDirectory()) { - new File(toDir, e.getName()).mkdirs(); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine(" unzipping " + e.getName()); - } - unzip(zin, new File(toDir, e.getName())); - } - } - zin.close(); - if (deleteAfter) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("unzipping complete, deleting zip file"); - } - - File file = new File(zipurl.getFile()); - if (file.exists()) { - file.delete(); - } - } else if (logger.isLoggable(Level.FINE)) { - logger.fine("unzipping complete, leaving zip file"); - } - return; - } - } catch (FileNotFoundException e1) { - e1.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - protected static void unzip(ZipInputStream zin, File f) throws IOException { - final int BUFFER = 2048; - FileOutputStream out = new FileOutputStream(f); - byte[] b = new byte[BUFFER]; - int len = 0; - BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER); - while ((len = zin.read(b, 0, BUFFER)) != -1) { - dest.write(b, 0, len); - } - dest.flush(); - dest.close(); - } - -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/HashCodeUtil.java b/src/openmap/com/bbn/openmap/util/HashCodeUtil.java deleted file mode 100644 index 18bbb2a40..000000000 --- a/src/openmap/com/bbn/openmap/util/HashCodeUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.bbn.openmap.util; - -import java.lang.reflect.Array; - -/** - * Collected methods which allow easy implementation of hashCode. - * Algorithm from Effective Java by Joshua Bloch. Implementation found at - * http://www.javapractices.com. - * - * Example use case: - * - *
- * public int hashCode() {
- *     int result = HashCodeUtil.SEED;
- *     // collect the contributions of various fields
- *     result = HashCodeUtil.hash(result, fPrimitive);
- *     result = HashCodeUtil.hash(result, fObject);
- *     result = HashCodeUtil.hash(result, fArray);
- *     return result;
- * }
- * 
- */ -public final class HashCodeUtil { - - /** - * An initial value for a hashCode, to which is added - * contributions from fields. Using a non-zero value decreases collisons of - * hashCode values. - */ - public static final int SEED = 17; - - /** - * hash booleans. - * - * @param aSeed seeding int to start with - * @param aBoolean object to hash - * @return hash for boolean - */ - public static int hash(int aSeed, boolean aBoolean) { - return firstTerm(aSeed) + (aBoolean ? 1 : 0); - } - - /** - * hash chars. - * - * @param aSeed seeding int to start with - * @param aChar object to hash - * @return hash for char - */ - public static int hash(int aSeed, char aChar) { - return firstTerm(aSeed) + (int) aChar; - } - - /** - * hash ints. - * - * @param aSeed seeding int to start with - * @param aInt object to hash - * @return hash for int - */ - public static int hash(int aSeed, int aInt) { - /* - * Implementation Note Note that byte and short are handled by this - * method, through implicit conversion. - */ - return firstTerm(aSeed) + aInt; - } - - /** - * hash longs. - * - * @param aSeed seeding int to start with - * @param aLong object to hash - * @return hash for long - */ - public static int hash(int aSeed, long aLong) { - return firstTerm(aSeed) + (int) (aLong ^ (aLong >>> 32)); - } - - /** - * hash floats. - * - * @param aSeed seeding int to start with - * @param aFloat object to hash - * @return hash for float - */ - public static int hash(int aSeed, float aFloat) { - return hash(aSeed, Float.floatToIntBits(aFloat)); - } - - /** - * hash for doubles - * - * @param aSeed seeding int to start with - * @param aDouble to hash - * @return hash for double - */ - public static int hash(int aSeed, double aDouble) { - return hash(aSeed, Double.doubleToLongBits(aDouble)); - } - - /** - * aObject is a possibly-null object field, and possibly an - * array. - * - * If aObject is an array, then each element may be a primitive - * or a possibly-null object. - * - * @param aSeed seeding int to start with - * @param aObject object to hash - * @return hash for aObject - */ - public static int hash(int aSeed, Object aObject) { - int result = aSeed; - if (aObject == null) { - result = hash(result, 0); - } else if (!isArray(aObject)) { - result = hash(result, aObject.hashCode()); - } else { - int length = Array.getLength(aObject); - for (int idx = 0; idx < length; ++idx) { - Object item = Array.get(aObject, idx); - // recursive call! - result = hash(result, item); - } - } - return result; - } - - // / PRIVATE /// - private static final int fODD_PRIME_NUMBER = 31; - - private static int firstTerm(int aSeed) { - return fODD_PRIME_NUMBER * aSeed; - } - - private static boolean isArray(Object aObject) { - return aObject.getClass().isArray(); - } -} diff --git a/src/openmap/com/bbn/openmap/util/PropUtils.java b/src/openmap/com/bbn/openmap/util/PropUtils.java deleted file mode 100644 index 772de3778..000000000 --- a/src/openmap/com/bbn/openmap/util/PropUtils.java +++ /dev/null @@ -1,1056 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: -// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/PropUtils.java,v -// $ -// $RCSfile: PropUtils.java,v $ -// $Revision: 1.16 $ -// $Date: 2008/09/26 12:07:56 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util; - -/* Java Core */ -import java.awt.Color; -import java.awt.Paint; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.swing.JFileChooser; - -import com.bbn.openmap.Environment; -import com.bbn.openmap.I18n; -import com.bbn.openmap.Layer; -import com.bbn.openmap.PropertyConsumer; - -public class PropUtils { - - public static Logger logger = Logger.getLogger("com.bbn.openmap.util.PropUtils"); - - /** - * Parse a list of marker names from a space separated list within a String. - *

- * - * @param markerList a string containing a space delimited list of marker - * names. - * @return Vector of marker names. - */ - public static Vector parseSpacedMarkers(String markerList) { - return parseMarkers(markerList, " "); - } - - /** - * Parse a list of marker names from a space separated list within a String. - *

- * - * @param markerList a string containing a list of things to be parsed. - * @param delim the list of tokens to look for which separate the list - * elements. - * @return Vector of marker names. - */ - public static Vector parseMarkers(String markerList, String delim) { - Vector vector = null; - - if (markerList == null) { - logger.fine("marker list null!"); - return new Vector(0); - } - - if (logger.isLoggable(Level.FINE)) { - logger.fine("parsing marker list |" + markerList + "|"); - } - - // First, get rid of the quotation marks; - markerList = markerList.replace('\"', '\0'); - // Next, tokenize the space delimited string - StringTokenizer tokens = new StringTokenizer(markerList, delim); - vector = new Vector(tokens.countTokens()); - while (tokens.hasMoreTokens()) { - String name = tokens.nextToken().trim(); - vector.addElement(name); - } - return vector; - } - - /** - * A string used in marker names for property editors, when a custom editor - * used by an Inspector can set several top-level properties. - */ - public final static String DUMMY_MARKER_NAME = "DUMMY_MARKER_NAME"; - /** Borrowed from Properties.java */ - public static final String keyValueSeparators = "=: \t\r\n\f"; - /** Borrowed from Properties.java */ - public static final String strictKeyValueSeparators = "=:"; - /** Borrowed from Properties.java */ - public static final String whiteSpaceChars = " \t\r\n\f"; - /** As defined in the OGC Web Mapping Test bed. */ - public static final String propertySeparators = "&"; - - /** - * Take a property list, defined in a single string, and return a Properties - * object. The properties, as key-value pairs, are separated by another type - * of symbol. In this method, the key-values are assumed to be separated - * from other key-value pairs by PropUtils.propertySeparators String - * characters, and each key is separated from its value by any character in - * the PropUtils.keyValueSeparators list. - * - * @param list the properties list string. - * @return Properties object containing keys and values. - * @throws PropertyStringFormatException if a key doesn't have a value. - */ - public static Properties parsePropertyList(String list) throws PropertyStringFormatException { - return parsePropertyList(list, propertySeparators, keyValueSeparators); - } - - /** - * Take a property list, defined in a single string, and return a Properties - * object. The properties, as key-value pairs, are separated by another type - * of symbol. - * - * @param list the properties list string. - * @return Properties object containing keys and values. - * @param propertySeparators the key-values are assumed to be separated from - * other key-value pairs by any character in this String. - * @param keyValueSeparators each key is separated from its value by any - * character in this String. - * @throws PropertyStringFormatException if a key doesn't have a value. - */ - public static Properties parsePropertyList(String list, String propertySeparators, - String keyValueSeparators) - throws PropertyStringFormatException { - - Properties props = new Properties(); - - Vector keyValuePairs = parseMarkers(list, propertySeparators); - for (int i = 0; i < keyValuePairs.size(); i++) { - // Next, tokenize the space delimited string - StringTokenizer tokens = new StringTokenizer(keyValuePairs.elementAt(i), keyValueSeparators); - - try { - String key = tokens.nextToken().trim(); - String value = tokens.nextToken().trim(); - props.put(key, value); - } catch (NoSuchElementException nsee) { - throw new PropertyStringFormatException(list); - } - } - return props; - } - - /** - * Copy the contents from one properties object to another. - * - * @param from the source Properties object. - * @param to the destination Properties object. - */ - public static void copyProperties(Properties from, Properties to) { - Enumeration keys = from.keys(); - - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - to.put(key, from.getProperty(key)); - } - } - - /** - * Load the named file from the named directory into the given - * Properties instance. If the file is not found a warning is - * issued. If an IOException occurs, a fatal error is printed. - * - * @param props the instance to receive the loaded properties - * @param dir the directory where the properties file resides - * @param file the name of the file - * @return true if the properties file exists and was loaded. - */ - public static boolean loadProperties(Properties props, String dir, String file) { - File propsFile = new File(dir, file); - - try { - InputStream propsStream = new FileInputStream(propsFile); - props.load(propsStream); - if (logger.isLoggable(Level.FINE)) { - logger.fine("Found " + propsFile); - } - return true; - - } catch (java.io.FileNotFoundException e) { - if (logger.isLoggable(Level.FINE)) { - logger.fine("File not found - \"" + propsFile + "\""); - } - } catch (java.io.IOException e) { - logger.warning("Caught IO Exception reading \"" + propsFile + "\""); - e.printStackTrace(); - } catch (java.security.AccessControlException ace) { - } - return false; - } - - /** - * Loads properties from a java resource. This will load the named resource - * identifier into the given properties instance. - * - * @param properties the Properties instance to receive the properties. - * @param propsIn an InputStream to read properties from - * @return true if the properties file exists and was loaded. - */ - public static boolean loadProperties(Properties properties, InputStream propsIn) { - try { - properties.load(propsIn); - return true; - } catch (java.io.IOException e) { - if (logger.isLoggable(Level.FINE)) { - logger.warning("Caught IOException loading properties from InputStream."); - } - return false; - } - } - - /** - * A function that brings up a file chooser window in order to have the user - * look for a valid Java properties file. - * - * @return properties object with selected file contents. - */ - public static Properties promptUserForProperties() { - JFileChooser fileChooser = new JFileChooser(); - int retvalue = fileChooser.showOpenDialog(null); - Properties props = new Properties(); - if (retvalue != JFileChooser.APPROVE_OPTION) { - return props; - } - try { - FileInputStream inputStream = new FileInputStream(fileChooser.getSelectedFile()); - props.load(inputStream); - return props; - } catch (Exception ioe) { - System.err.println("PropUtils.promptUserForProperties: Exception reading properties file."); - System.err.println(ioe.getMessage()); - ioe.printStackTrace(); - return props; - } - } - - /** - * It seems like every PropertyConsumer wrestles with having a prefix or - * not. This method lets you just get the prefix with a period on the end - * (for scoping purposes), or just returns an empty String. Either way, you - * get a String you can slap on the beginning of your defined property names - * to get a valid property based on what the prefix is. - * - * @param pc the PropertyConsumer to fetch from - * @return an empty string if no prefix, or the prefix with a period at the - * end - */ - public static String getScopedPropertyPrefix(PropertyConsumer pc) { - return getScopedPropertyPrefix(pc.getPropertyPrefix()); - } - - /** - * Given the string, check if it's null. If it isn't, check to see if it - * ends with a period, and do nothing if it does. If it doesn't end in a - * period, add one, and then return that. The returned string should be good - * for prepending to other properties. - * - * @param pre the string to check - * @return an empty string or one that ends with a period - */ - public static String getScopedPropertyPrefix(String pre) { - if (pre == null || pre.length() == 0) { - return ""; - } else if (pre.endsWith(".")) { - return pre; - } else { - return pre + "."; - } - } - - /** - * Should be called by a PropertyConsumer in the - * getPropertiesInfo(Properties) method to create a property marker name for - * a custom PropertyEditor that will modify several top-level properties, - * i.e. the com.bbn.openmap.omGraphics.DrawingAttributesPropertyEditor. - * - * @param realComponentPropertyPrefix the top-level prefix that the - * PropertyConsumer being set with the properties has. Can be null. - * @param anyDesiredScoper an additional scoping mechanism if there are more - * than one custom editors being used for a given getPropertyInfo - * call. - * @return The string that is used for a marker for a custom editor. - */ - public static String getDummyMarkerForPropertyInfo(String realComponentPropertyPrefix, - String anyDesiredScoper) { - return DUMMY_MARKER_NAME + (anyDesiredScoper != null ? anyDesiredScoper : "") + "." - + (realComponentPropertyPrefix != null ? realComponentPropertyPrefix : ""); - } - - /** - * Should be used inside a - * PropertyConsumerPropertyEditor.setProperties(String, Properties) method - * to set the real property prefix. The PropertyConsumer that the Inspector - * is looking at should use the getDummyMarker() call to create the marker - * for the getPropertyInfor(Properties) call. - * - * @param possibleDummyMarker string to check for DUMMY_MARKER_NAME, - * indicating that's a dummy - * @return the encoded 'real' property prefix for the PropertyConsumer - * embedded in the dummy marker, or the possibleDummyMarker if it's - * not a dummy marker. - */ - public static String decodeDummyMarkerFromPropertyInfo(String possibleDummyMarker) { - if (possibleDummyMarker != null && possibleDummyMarker.startsWith(DUMMY_MARKER_NAME)) { - int lastDot = possibleDummyMarker.lastIndexOf("."); - if (lastDot != -1) { - possibleDummyMarker = possibleDummyMarker.substring(lastDot + 1); - } - } - return possibleDummyMarker; - } - - /** - * It kills Properties to have null values set. You can wrap a property - * value in this in PropertyConsumer.getProperties() to not worry about it. - * - * @param prop property value to be set in properties after this call - * @return empty string if prop equals null, else returns what was passed in - */ - public static String unnull(Object prop) { - if (prop == null) { - return ""; - } - return prop.toString(); - } - - /** - * Takes a string of `;' separated paths and returns an array of parsed - * strings. NOTE: this method currently doesn't support appropriate quoting - * of the `;' character, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @return Array of strings representing paths. - */ - public static String[] initPathsFromProperties(Properties p, String propName) { - return initPathsFromProperties(p, propName, null); - } - - /** - * Takes a string of `;' separated paths and returns an array of parsed - * strings. NOTE: this method currently doesn't support appropriate quoting - * of the `;' character, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @param defaultPaths the value of the paths to set if the property doesn't - * exist, or if is doesn't contain anything. - * @return Array of strings representing paths. - */ - public static String[] initPathsFromProperties(Properties p, String propName, - String[] defaultPaths) { - String[] ret = stringArrayFromProperties(p, propName, ";"); - - if (ret == null) { - ret = defaultPaths; - } - - return ret; - } - - /** - * Return the first letter of the property specified by propName. If that - * value is null or has length of zero, the default char is returned. - * - * @param p properties to load from - * @param propName property name - * @param defaultValue default to use if property isn't found - * @return first char from property, or default. - */ - public static char charFromProperties(Properties p, String propName, char defaultValue) { - char ret = defaultValue; - String charString = p.getProperty(propName); - if (charString != null && charString.length() > 0) { - return charString.charAt(0); - } - return ret; - } - - /** - * Gets an integer out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return integer value associated with the property. - */ - public static int intFromProperties(Properties p, String propName, int defaultValue) { - int ret = defaultValue; - String intString = p.getProperty(propName); - - if (intString != null) { - try { - ret = Integer.parseInt(intString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets an float out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return float value associated with the property. - */ - public static float floatFromProperties(Properties p, String propName, float defaultValue) { - float ret = defaultValue; - String floatString = p.getProperty(propName); - - if (floatString != null) { - try { - ret = Float.parseFloat(floatString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets an boolean out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return boolean value associated with the property. - */ - public static boolean booleanFromProperties(Properties p, String propName, boolean defaultValue) { - boolean ret = defaultValue; - String booleanString = p.getProperty(propName); - if (booleanString != null) { - ret = booleanString.trim().equalsIgnoreCase("true"); - } - - return ret; - } - - /** - * Creates an object out of a property name. If anything fails, return null. - * - * @param p properties - * @param propName name of class to instantiate. - * @return null on failure, otherwise, a default constructed instance of the - * class named in the property. - */ - public static Object objectFromProperties(Properties p, String propName) { - - Object ret = null; - String objectName = p.getProperty(propName); - if (objectName != null) { - ret = ComponentFactory.create(objectName); - } - return ret; - } - - /** - * Takes a string of representing token separated properties and returns an - * array of parsed strings. NOTE: this method currently doesn't support - * appropriate quoting of the token, although it probably should... - * - * @param p properties - * @param propName the name of the property - * @param tok the characters separating the strings. - * @return Array of strings between the tokens. - */ - public static String[] stringArrayFromProperties(Properties p, String propName, String tok) { - - String[] ret = null; - String raw = p.getProperty(propName); - - if (raw != null && raw.length() > 0) { - - try { - StringTokenizer token = new StringTokenizer(raw, tok); - int numPaths = token.countTokens(); - - ret = new String[numPaths]; - for (int i = 0; i < numPaths; i++) { - ret[i] = token.nextToken(); - } - return ret; - } catch (java.util.NoSuchElementException e) { - e.printStackTrace(); - } - } - return ret; - } - - /** - * Gets a double out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return double value associated with the property. - */ - public static double doubleFromProperties(Properties p, String propName, double defaultValue) { - double ret = defaultValue; - String doubleString = p.getProperty(propName); - - if (doubleString != null) { - try { - ret = Double.parseDouble(doubleString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Gets a long out of a properties object. Returns the default value if - * something goes wrong. - * - * @param p properties - * @param propName name of the property associated with the wanted value. - * @param defaultValue what to return if the property name doesn't exist, or - * if the value isn't a numerical value. - * @return long value associated with the property. - */ - public static long longFromProperties(Properties p, String propName, long defaultValue) { - long ret = defaultValue; - String longString = p.getProperty(propName); - - if (longString != null) { - try { - ret = Long.parseLong(longString.trim()); - } catch (NumberFormatException e) { - ret = defaultValue; - } - } - return ret; - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color to use if the property value doesn't work - * @return java.awt.Color - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault) - throws NumberFormatException { - return ColorFactory.parseColorFromProperties(p, propName, dfault, false); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color to use if the property value doesn't work - * @param forceAlpha force using alpha value - * @return java.awt.Color - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static Color parseColorFromProperties(Properties p, String propName, String dfault, - boolean forceAlpha) - throws NumberFormatException { - return ColorFactory.parseColorFromProperties(p, propName, dfault, forceAlpha); - } - - /** - * Take a string from a properties file, representing the 24bit RGB or 32bit - * ARGB hex values for a color, and convert it to a java.awt.Color. - * - * @param p properties - * @param propName the name of the property - * @param dfault color to use if the property value doesn't work - * @return java.awt.Color - * @see ColorFactory#parseColorFromProperties(Properties, String, String, - * boolean) - */ - public static Paint parseColorFromProperties(Properties p, String propName, Paint dfault) { - return ColorFactory.parseColorFromProperties(p, propName, dfault); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString the 24/32bit hex string value (ARGB) - * @param forceAlpha force using alpha value - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColor(String, boolean) - */ - public static Color parseColor(String colorString, boolean forceAlpha) - throws NumberFormatException { - return ColorFactory.parseColor(colorString, forceAlpha); - } - - /** - * Convert a string representing a 24/32bit hex color value into a Color - * value. NOTE: - *
    - *
  • Only 24bit (RGB) java.awt.Color is supported on the JDK 1.1 platform. - *
  • Both 24/32bit (ARGB) java.awt.Color is supported on the Java 2 - * platform. - *
- * - * @param colorString the 24/32bit hex string value (ARGB) - * @return java.awt.Color (24bit RGB on JDK 1.1, 24/32bit ARGB on JDK1.2) - * @exception NumberFormatException if the specified string cannot be - * interpreted as a hexidecimal integer - * @see ColorFactory#parseColor(String, boolean) - */ - public static Color parseColor(String colorString) throws NumberFormatException { - return ColorFactory.parseColor(colorString, false); - } - - /** - * Returns a string representing a color, properly buffered for zeros for - * different alpha values. - * - * @param color the source Color - * @return string for color with alpha values. - */ - public static String getProperty(Color color) { - StringBuffer hexstring = new StringBuffer(Integer.toHexString(color.getRGB())); - while (hexstring.length() < 8) { - hexstring.insert(0, '0'); - } - return hexstring.toString(); - } - - /** - * Converts a properties object to an array of Strings. The resulting array - * will consist of alternating key-value strings. - * - * @param props the properties object to convert. - * @return an array of Strings representing key-value pairs. - */ - public static String[] getPropertiesAsStringArray(Properties props) { - - int size = props.size(); - String[] ret = new String[size * 2]; // key and value - int count = 0; - Enumeration things = props.propertyNames(); - while (things.hasMoreElements()) { - ret[count] = (String) things.nextElement(); - ret[count + 1] = (String) props.getProperty(ret[count]); - count += 2; - } - return ret; - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. Resources are checked for in the general classpath. - * - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(String name) throws java.net.MalformedURLException { - return getResourceOrFileOrURL(null, name); - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. - * - * @param askingClass the object asking for the URL. - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(Object askingClass, String name) - throws java.net.MalformedURLException { - - return getResourceOrFileOrURL(askingClass.getClass(), name); - } - - /** - * Returns a URL that names either a resource, a local file, or an internet - * URL. - * - * @param askingClass the class asking for the URL. Can be null. - * @param name name of the resource, file or URL. - * @throws java.net.MalformedURLException if there's a problem finding the - * thingy - * @return URL - */ - public static URL getResourceOrFileOrURL(Class askingClass, String name) - throws java.net.MalformedURLException { - - boolean DEBUG = logger.isLoggable(Level.FINE); - - if (name == null) { - if (DEBUG) - logger.fine("null file name"); - return null; - } - - URL retval = null; - if (DEBUG) - logger.fine("looking for " + name); - - if (askingClass != null) { - // First see if we have a resource by that name - if (DEBUG) - logger.fine("checking as resource"); - - retval = askingClass.getResource(name); - } - if (retval == null) { - // Check the general classpath... - if (DEBUG) - logger.fine("checking in general classpath"); - retval = Thread.currentThread().getContextClassLoader().getResource(name); - } - - // if (retval == null && !Environment.isApplet()) { - // // Check the classpath plus the share directory, which may - // // be in the openmap.jar file or in the development - // // environment. - // if (DEBUG) - // logger.fine("checking with ClassLoader"); - // retval = ClassLoader.getSystemResource("share/" + name); - // } - - if (retval == null && Environment.isApplet()) { - if (DEBUG) - logger.fine("checking with URLClassLoader"); - URL[] cba = new URL[1]; - cba[0] = Environment.getApplet().getCodeBase(); - URLClassLoader ucl = URLClassLoader.newInstance(cba); - retval = ucl.getResource(name); - } - - // If there was no resource by that name available - if (retval == null) { - if (DEBUG) - logger.fine("not found as resource"); - - try { - java.io.File file = new java.io.File(name); - if (file.exists()) { - retval = file.toURI().toURL(); - if (DEBUG) - logger.fine("found as file :)"); - } else { - // Otherwise treat it as a raw URL. - if (DEBUG) - logger.fine("Not a file, checking as URL"); - retval = new URL(name); - java.io.InputStream is = retval.openStream(); - is.close(); - if (DEBUG) - logger.fine("OK as URL :)"); - } - } catch (java.io.IOException ioe) { - retval = null; - } catch (java.security.AccessControlException ace) { - logger.warning("AccessControlException trying to access " + name); - retval = null; - } catch (Exception e) { - logger.warning("caught exception " + e.getMessage()); - retval = null; - } - } - - if (DEBUG) { - if (retval != null) { - logger.fine("Resource " + name + "=" + retval.toString()); - } else { - logger.fine("Resource " + name + " can't be found..."); - } - } - - return retval; - } - - /** - * Simple space saving implementation of common I18n Property Info setting. - * - * @param i18n i18n object to use to search for internationalized strings. - * @param info the properties class being used to set information into. - * @param classToSetFor class to use for i18n search. - * @param propertyName property to set for. - * @param label label to use for GUI (can be null if N/A). - * @param tooltip tooltip to use for GUI (can be null if N/A). - * @param editor editor class string to use for GUI (can be null if N/A). - * @return Properties object passed in, or new one if null Properties passed - * in. - */ - public static Properties setI18NPropertyInfo(I18n i18n, Properties info, - Class classToSetFor, - String propertyName, String label, String tooltip, - String editor) { - if (info == null) { - info = new Properties(); - } - if (i18n != null) { - if (tooltip != null) { - String internString = i18n.get(classToSetFor, propertyName, I18n.TOOLTIP, tooltip); - info.put(propertyName, internString); - } - if (label != null) { - String internString = i18n.get(classToSetFor, propertyName, label); - info.put(propertyName + PropertyConsumer.LabelEditorProperty, internString); - } - if (editor != null) { - info.put(propertyName + PropertyConsumer.ScopedEditorProperty, editor); - } - } - return info; - } - - /** - * If the layer has a dataPathPrefix attribute set, that attribute value can - * be used as a common path to prepend to any layer's data path. This allows - * you to set a relative path to files in the layer's properties, and then - * prepend the absolute path later at runtime. - *

- * - * The dataPathPrefix can be set in the properties for a layer, where it is - * pushed to the layer's attributes in Layer.setProperties(). This method is - * intended for layers that have sub-layers, so the parent layer can set - * that dataPathPrefix property on it's children automatically. - * - * @param layer the parent layer to retrieve the attribute from - * @param props the properties that define the children, and also passed to - * them for configuration - * @param layerListProperty the property for the parent that lists the - * marker names for the children - */ - public static void putDataPrefixToLayerList(Layer layer, Properties props, - String layerListProperty) { - String dataPrefix = (String) layer.getAttribute(Layer.DataPathPrefixProperty); - if (dataPrefix != null && dataPrefix.length() > 0) { - putDataPrefixToLayerList(dataPrefix, props, layerListProperty); - } - } - - /** - * If the layer has a dataPathPrefix attribute set, that attribute value can - * be used as a common path to prepend to any layer's data path. This allows - * you to set a relative path to files in the layer's properties, and then - * prepend the absolute path later at runtime. - *

- * - * The dataPathPrefix can be set in the properties for a layer, where it is - * pushed to the layer's attributes in Layer.setProperties(). This method is - * intended for layers that have sub-layers, so the parent layer can set - * that dataPathPrefix property on it's children automatically. - * - * @param dataPrefix the dataPathPrefix retrieved from the parent attributes - * @param props the properties that define the children, and also passed to - * them for configuration - * @param layerListProperty the property for the parent that lists the - * marker names for the children - */ - public static void putDataPrefixToLayerList(String dataPrefix, Properties props, - String layerListProperty) { - Vector layersValue = parseSpacedMarkers(props.getProperty(layerListProperty)); - - for (Iterator it = layersValue.iterator(); it.hasNext();) { - String markerName = getScopedPropertyPrefix(it.next()); - props.setProperty(markerName + Layer.DataPathPrefixProperty, dataPrefix); - } - } - - /** - * Get a List of Objects defined by marker names listed in a property. If - * the objects are PropertyConsumers, they will be given the properties and - * their scoped property prefix so they can configure themselves. - * - *

-     * 
-     * listProperty=markername1 markername2 markername3
-     * markername1.definingProperty=classname1
-     * markername2.definingProperty=classname2
-     * markername3.definingProperty=classname3
-     * 
-     * 
- * - * @param p Properties object containing all properties - * @param markerListProperty listProperty in example above - * @param definingProperty definingProperty in example above, scoped - * property when combined with marker name to define the class that - * should be created for an object. - * @return List of objects created from properties - */ - public static List objectsFromProperties(Properties p, String markerListProperty, - String definingProperty) { - return objectsFromScopedProperties(p, markerListProperty, definingProperty, null); - // - // String markerList = p.getProperty(markerListProperty); - // List ret = new LinkedList(); - // - // if (markerList != null) { - // Vector markerNames = parseSpacedMarkers(markerList); - // for (String markerName : markerNames) { - // String classname = p.getProperty(markerName + "." - // + definingProperty); - // if (classname != null) { - // Object obj = ComponentFactory.create(classname, markerName, - // p); - // - // if (obj != null) { - // ret.add(obj); - // } - // } - // } - // - // } - // - // return ret; - } - - /** - * Get a List of Objects defined by marker names listed in a property, when - * this list property has been scoped by a parent object definition. If the - * objects are PropertyConsumers, they will be given the properties and - * their scoped property prefix so they can configure themselves. - * - *
-     * 
-     * parentMarker.listProperty=markername1 markername2 markername3
-     * parentMarker.markername1.definingProperty=classname1
-     * parentMarker.markername2.definingProperty=classname2
-     * parentMarker.markername3.definingProperty=classname3
-     * 
-     * 
- * - * @param p Properties object containing all properties - * @param markerListProperty listProperty in example above - * @param definingProperty definingProperty in example above, scoped - * property when combined with marker name to define the class that - * should be created for an object. - * @param parentMarker the string that should be used as the prefix for the - * defining property - * @return List of objects created from properties, where properties are - * scoped for each object. - */ - public static List objectsFromScopedProperties(Properties p, String markerListProperty, - String definingProperty, - String parentMarker) { - String markerList = p.getProperty(markerListProperty); - List ret = new LinkedList(); - parentMarker = PropUtils.getScopedPropertyPrefix(parentMarker); - - if (markerList != null) { - Vector markerNames = parseSpacedMarkers(markerList); - for (String markerName : markerNames) { - String classname = p.getProperty(parentMarker + markerName + "." - + definingProperty); - if (classname != null) { - Object obj = ComponentFactory.create(classname, markerName, p); - - if (obj != null) { - ret.add(obj); - } - } - } - } - - return ret; - } - - /** - * Add the object property value to properties if it's not null or empty, - * which assumes it should be set to the default value. - * - * @param props Properties to write to - * @param propertyName the scoped property to enter value under - * @param value the object to get property from - toString() will be called - * if not null. - * @param class for property - */ - public static void putIfNotDefault(Properties props, String propertyName, - T value) { - putIfNotDefault(props, propertyName, value, null); - } - - /** - * Add the object property value to properties if it's not null or default - * value. - * - * @param props Properties to write to - * @param propertyName the scoped property to enter value under - * @param value the object to get property from - toString() will be called - * if not null. - * @param def the default value of the property. If not null and value not - * null, toString().equals() will be used to determine equality. If - * not equal, then value will be set in props. - * @param matching class types for the property - */ - public static void putIfNotDefault(Properties props, String propertyName, - T value, T def) { - if (value != null) { - String valString = value.toString().trim(); - if (def == null || (def != null && !def.toString().trim().equals(valString))) { - // empty property strings are a pain... - if (valString.length() != 0) { - props.put(propertyName, valString); - } - } - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/wanderer/DataPathWanderer.java b/src/openmap/com/bbn/openmap/util/wanderer/DataPathWanderer.java deleted file mode 100644 index f7a40f4bf..000000000 --- a/src/openmap/com/bbn/openmap/util/wanderer/DataPathWanderer.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.bbn.openmap.util.wanderer; - -import java.util.ArrayList; -import java.util.List; - -/** - * A DataPathWanderer provides a list of valid data paths found from a parent - * directory. This class is intended to be provided by a layer to report which - * data files or directories can be used for that layer, given some parent - * directory or file. - * - * @author dfdietrick - */ -public abstract class DataPathWanderer extends Wanderer implements WandererCallback { - - protected List dataPaths; - - /** - * Which component class, like a specific layer type, will be using the data - * path. - * - * @return Class of using component. - */ - public abstract Class getDataUserClass(); - - /** - * @return pretty name of the using component.x - */ - public abstract String getPrettyName(); - - public DataPathWanderer() { - - } - - /** - * Returns a list of file/directory paths. - * - * @return a list of file/directory paths. If null, no required data paths - * were found and the layer is indicating that it needs paths. If a - * list is returned and its empty, then the layer doesn't require a - * data file. - */ - public List getDataPaths() { - return dataPaths; - } - - /** - * Adds a data path to the path repository. Creates the repository list if it - * doesn't yet exist. A call with a null path will get the repository list - * created. - * - * @param path - */ - protected void addDataPath(String path) { - if (dataPaths == null) { - dataPaths = new ArrayList(); - } - - if (path != null) { - dataPaths.add(path); - } - } - - /** - * True if layer being described can handle more than one data path, i.e. all - * the data paths found can be added to a single layer. - * - * @return false by default - */ - public boolean isMultiPathLayer() { - return false; - } - -} diff --git a/src/openmap/com/bbn/openmap/util/wanderer/OneWaySync.java b/src/openmap/com/bbn/openmap/util/wanderer/OneWaySync.java deleted file mode 100644 index b1058394e..000000000 --- a/src/openmap/com/bbn/openmap/util/wanderer/OneWaySync.java +++ /dev/null @@ -1,498 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/OneWaySync.java,v $ -// $RCSfile: OneWaySync.java,v $ -// $Revision: 1.3 $ -// $Date: 2005/08/09 18:41:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.ArgParser; - -/** - * The OneWaySync is a class that copies files from one directory to another, - * skipping specified extensions or only copying files and directories with - * specified extensions. It's used by the OpenMap team to keep the internal CVS - * tree in sync with the external one. The main() function has the avoid/limit - * suffixes hard-coded, you can extend or change the settings in a different - * class. - */ -public class OneWaySync extends Wanderer implements WandererCallback { - - /** The source directory. */ - protected File src; - /** The target directory. */ - protected File tgt; - /** The suffixes to skip over for directories. */ - public String[] dirSuffixAvoids = null; - /** The suffixes to skip over for files. */ - public String[] fileSuffixAvoids = null; - /** The suffixes to limit copying to for directories. */ - public String[] dirSuffixLimits = null; - /** The suffixes to limit copying to for files. */ - public String[] fileSuffixLimits = null; - /** The list of stuff skipped over. */ - protected LinkedList notCopiedList = new LinkedList(); - /** Flag for printing out activities. */ - protected boolean verbose = false; - /** Flag for not doing the changes, just saying what would happen. */ - protected boolean fakeit = false; - /** Flag to not have files that exist overwritten. */ - protected boolean overwrite = true; - - public OneWaySync(String srcDirName, String targetDirName) { - super(); - setCallback(this); - - src = new File(srcDirName); - tgt = new File(targetDirName); - } - - /** - * Check to see if a source directory name should be skipped, based on the - * avoid and limit list. - */ - protected boolean checkToSkipDirectory(String name) { - if (dirSuffixAvoids != null) { - for (int i = 0; i < dirSuffixAvoids.length; i++) { - if (name.endsWith(dirSuffixAvoids[i])) { - // Was on avoid list, skip it. - return true; - } - } - } - - if (dirSuffixLimits != null) { - for (int i = 0; i < dirSuffixLimits.length; i++) { - if (name.endsWith(dirSuffixLimits[i])) { - return false; - } - } - // Wasn't on limit list, skip it. - return true; - } - - return false; - } - - /** - * Check to see if a source file name should be skipped, based on the avoid - * and limit list. - */ - protected boolean checkToSkipFile(String name) { - if (fileSuffixAvoids != null) { - for (int i = 0; i < fileSuffixAvoids.length; i++) { - if (name.endsWith(fileSuffixAvoids[i])) { - // Was on avoid list, skip it. - return true; - } - } - } - - if (fileSuffixLimits != null) { - for (int i = 0; i < fileSuffixLimits.length; i++) { - if (name.endsWith(fileSuffixLimits[i])) { - return false; - } - } - // Wasn't on limit list, skip it. - return true; - } - - return false; - } - - /** - * Wanderer method handing directories. - */ - public boolean handleDirectory(File directory, String[] contentNames) { - String newDirName = getRelativePathFromSource(directory); - - if (newDirName == null) { - if (directory != src) { - notCopiedList.add(directory); - } - super.handleDirectory(directory, contentNames); - return true; - } - - if (!checkToSkipDirectory(newDirName)) { - File newDir = getTargetFile(newDirName); - if (!newDir.exists()) { - if (verbose) { - getLogger().info("Creating " + newDir); - } - if (!fakeit && overwrite) - newDir.mkdir(); - } - super.handleDirectory(directory, contentNames); - } else { - notCopiedList.add(directory); - } - - return true; - } - - /** - * WandererCallback method handing directories, not used. - */ - public boolean handleDirectory(File file) { - return true; - } - - /** - * WandererCallback method handing files, check and copy those that fit the - * avoid and limit parameters. - */ - public boolean handleFile(File file) { - String newFileName = getRelativePathFromSource(file); - - if (!checkToSkipFile(newFileName)) { - File newFile = getTargetFile(newFileName); - if (verbose) { - getLogger().info("Copying " + file + " to " + newFile); - } - if (!fakeit && overwrite) - copy(file, newFile); - } else { - notCopiedList.add(file); - } - return true; - } - - /** - * Copy files. - */ - public void copy(File fromFile, File toFile) { - try { - FileInputStream fis = new FileInputStream(fromFile); - FileOutputStream fos = new FileOutputStream(toFile); - - int num = 0; - byte[] stuff = new byte[4096]; - while ((num = fis.read(stuff)) > 0) { - fos.write(stuff, 0, num); - } - fis.close(); - fos.close(); - - } catch (IOException ioe) { - getLogger().warning("Exception reading from " + fromFile + " and writing to " + toFile); - } - } - - /** - * Strip the source directory part of the path from the file, return what - * remains. - */ - public String getRelativePathFromSource(File file) { - return subtractPathFromDirectory(src, file); - } - - /** - * Strip the target directory part of the path from the file, return what - * remains. - */ - public String getRelativePathFromTarget(File file) { - return subtractPathFromDirectory(tgt, file); - } - - /** - * Tack the file path onto the source directory. - */ - public File getSourceFile(String relativePath) { - return new File(src, relativePath); - } - - /** - * Tack the file path onto the target directory. - */ - public File getTargetFile(String relativePath) { - return new File(tgt, relativePath); - } - - /** - * Print out the files/directories not copied. - */ - public void writeUnsynched() { - for (Iterator it = notCopiedList.iterator(); it.hasNext();) { - getLogger().info(" " + it.next()); - } - } - - /** - * Create a BackCheck object that looks to see what files are in the target - * but not in the source. - */ - public void checkTargetSolos() { - new BackCheck(tgt.getPath(), src.getPath()); - } - - /** - * Take the source directory out of the path to the directory. - */ - protected String subtractPathFromDirectory(File dir, File file) { - String name = file.getPath(); - String dirName = dir.getPath(); - - if (name.equals(dirName)) { - if (verbose) { - getLogger().info("OneWaySync avoiding subtraction operation on top-level directory"); - } - return null; - } - - int index = name.indexOf(dirName); - if (index != -1) { - try { - String relative = name.substring(index + dirName.length() + 1); - if (verbose) { - getLogger().info("From " + file + ", returning " + relative); - } - return relative; - } catch (StringIndexOutOfBoundsException sioobe) { - getLogger().warning("Problem clipping first " + (dirName.length() + 1) + " characters off " + file); - return null; - } - } else { - getLogger().warning("File " + file + " is not in directory " + dir); - return null; - } - } - - /** - * Start copying files from the source directory to the target directory. - */ - public void start() { - String errorMessage = null; - if (src == null) { - errorMessage = "OneWaySync: Source directory unspecified"; - } else if (!src.exists()) { - errorMessage = "OneWaySync: Source directory (" + src + ") doesn't exist!"; - } - - if (tgt != null) { - if (!tgt.exists()) { - if (verbose) { - getLogger().info("OneWaySync: target directory (" + tgt + ") doesn't exist, creating..."); - } - - try { - if (!fakeit && !tgt.mkdir()) { - errorMessage = "OneWaySync: target directory (" + tgt + ") can't be created."; - } - } catch (SecurityException se) { - errorMessage = "OneWaySync: creating target directory (" + tgt - + ") isn't allowed, Security Exception: " + se.getMessage(); - se.printStackTrace(); - } - } - } else { - errorMessage = "OneWaySync: target directory unspecified"; - } - - if (errorMessage != null) { - getLogger().warning(errorMessage); - System.exit(0); - } - - handleEntry(src); - } - - public void setVerbose(boolean val) { - verbose = val; - } - - public boolean getVerbose() { - return verbose; - } - - public void setFakeit(boolean val) { - fakeit = val; - } - - public boolean getFakeit() { - return fakeit; - } - - public void setDirSuffixAvoids(String[] avoids) { - dirSuffixAvoids = avoids; - } - - public void setFileSuffixAvoids(String[] avoids) { - fileSuffixAvoids = avoids; - } - - public void setDirSuffixLimits(String[] limits) { - dirSuffixLimits = limits; - } - - public void setFileSuffixLimits(String[] limits) { - fileSuffixLimits = limits; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(OneWaySync.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - /** - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("OneWaySync"); - ap.add("source", "The source directory to copy files and directories from.", 1); - ap.add("target", "The target directory to receive the updated files and directories.", 1); - ap.add("verbose", "Announce all changes, failures will still be reported."); - ap.add("fakeit", "Just print what would happen, don't really do anything."); - ap.add("report", "Print out what didn't get copied, and what files exist only on the target side."); - - if (argv.length < 4) { - ap.bail("", true); - } - - ap.parse(argv); - - boolean verbose = false; - String[] verb = ap.getArgValues("verbose"); - if (verb != null) { - verbose = true; - } - - boolean fakeit = false; - verb = ap.getArgValues("fakeit"); - if (verb != null) { - verbose = true; - fakeit = true; - } - - boolean report = false; - verb = ap.getArgValues("report"); - if (verb != null) { - report = true; - } - - String[] sourceDir; - sourceDir = ap.getArgValues("source"); - if (sourceDir != null && sourceDir.length >= 1) { - if (verbose) { - getLogger().info("Source directory is " + sourceDir[0]); - } - } else { - ap.bail("OneWaySync needs path to source directory", false); - } - - String[] targetDir; - targetDir = ap.getArgValues("target"); - if (targetDir != null && targetDir.length >= 1) { - if (verbose) { - getLogger().info("Target directory is " + targetDir[0]); - } - } else { - ap.bail("OneWaySync needs path to source directory", false); - } - - // Should be 'since' instead of 'if' - if (sourceDir != null && targetDir != null) { - - OneWaySync cc = new OneWaySync(sourceDir[0], targetDir[0]); - cc.setVerbose(verbose); - cc.setFakeit(fakeit); - cc.setDirSuffixAvoids(new String[] { "CVS" }); - cc.setFileSuffixLimits(new String[] { ".java", "Makefile", ".cvsignore", ".html", ".properties", ".txt", - ".c", ".h", ".png" }); - cc.start(); - if (report) { - getLogger().info("-------- Not Copied --------"); - cc.writeUnsynched(); - getLogger().info("----------------------------"); - cc.checkTargetSolos(); - } - } - } - - public static class BackCheck extends OneWaySync { - - public BackCheck(String targetDirName, String srcDirName) { - super(targetDirName, srcDirName); - fakeit = true; - overwrite = false; - if (getLogger().isLoggable(Level.FINE)) { - verbose = true; - } - start(); - - getLogger().info("-------- Only In Target Directory--------"); - writeUnsynched(); - getLogger().info("-----------------------------------------"); - } - - public boolean handleDirectory(File directory, String[] contentNames) { - String newDirName = getRelativePathFromSource(directory); - if (newDirName == null) { - return super.handleDirectory(directory, contentNames); - } - - File newDir = getTargetFile(newDirName); - if (!newDir.exists()) { - notCopiedList.add(directory); - } - return super.handleDirectory(directory, contentNames); - } - - public boolean handleFile(File file) { - if (!getTargetFile(getRelativePathFromSource(file)).exists()) { - notCopiedList.add(file); - } - return true; - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/wanderer/Purge.java b/src/openmap/com/bbn/openmap/util/wanderer/Purge.java deleted file mode 100644 index 2a0caa93c..000000000 --- a/src/openmap/com/bbn/openmap/util/wanderer/Purge.java +++ /dev/null @@ -1,173 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/Purge.java,v $ -// $RCSfile: Purge.java,v $ -// $Revision: 1.5 $ -// $Date: 2005/08/09 18:41:09 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.util.ArgParser; - -/** - * PURGE deletes files that start with, or end with, certain strings. Good for - * cleaning up backup leftover from various editors. - * - *
- * 
- *  Usage: java com.bbn.openmap.util.wanderer.Purge (dir path) ...
- * 
- * 
- */ -public class Purge extends Wanderer implements WandererCallback { - - boolean DETAIL = false; - String[][] purgeables = new String[2][]; - - public Purge(String[] startsWith, String[] endsWith) { - super(); - purgeables[0] = startsWith; - purgeables[1] = endsWith; - - if (purgeables[0] == null) { - purgeables[0] = new String[0]; - } - - if (purgeables[1] == null) { - purgeables[1] = new String[0]; - } - - DETAIL = getLogger().isLoggable(Level.FINE); - setCallback(this); - - if (DETAIL) { - StringBuffer sb = new StringBuffer("Deleting files that "); - boolean sw = false; - if (startsWith != null && startsWith.length > 0) { - sb.append("start with "); - for (int i = 0; i < startsWith.length; i++) { - sb.append(startsWith[i]).append(" "); - } - sw = true; - } - - if (endsWith != null && endsWith.length > 0) { - if (sw) { - sb.append("and "); - } - sb.append("end with "); - for (int i = 0; i < endsWith.length; i++) { - sb.append(endsWith[i]).append(" "); - } - } - getLogger().info(sb.toString()); - } - - } - - public boolean handleDirectory(File directory) { - // Do nothing to directories - return true; - } - - public boolean handleFile(File file) { - String fileName = file.getName(); - int i; - - for (i = 0; i < purgeables[0].length; i++) { - if (fileName.startsWith(purgeables[0][i])) { - if (DETAIL) { - getLogger().info("Deleting " + fileName); - } - file.delete(); - return true; - } - } - - for (i = 0; i < purgeables[1].length; i++) { - if (fileName.endsWith(purgeables[1][i])) { - if (DETAIL) { - getLogger().info("Deleting " + fileName); - } - file.delete(); - return true; - } - } - - return true; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(Purge.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - /** - * Given a set of files or directories, parade through them to find files - * that end with '`', or files that start with '.#', and delete them. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("Purge"); - - if (argv.length == 0) { - ap.bail("Wanders through directory tree pruning '~' files.\nUsage: java com.bbn.openmap.util.wanderer.Purge ", - false); - } - - Purge purge = new Purge(new String[] { ".#" }, new String[] { "~" }); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < argv.length; i++) { - purge.handleEntry(new File(argv[i])); - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/wanderer/SLOC.java b/src/openmap/com/bbn/openmap/util/wanderer/SLOC.java deleted file mode 100644 index 284a65c51..000000000 --- a/src/openmap/com/bbn/openmap/util/wanderer/SLOC.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/SLOC.java,v $ -// $RCSfile: SLOC.java,v $ -// $Revision: 1.4 $ -// $Date: 2004/10/14 18:06:32 $ -// $Author: dietrick $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.bbn.openmap.io.BinaryBufferedFile; -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.util.ArgParser; - -/** - * Count the source lines of code but going through the directory and counting ; - * and }. - */ -public class SLOC implements WandererCallback { - - int sloc = 0; - boolean DETAIL = false; - - public void setSLOC(int num) { - sloc = num; - DETAIL = getLogger().isLoggable(Level.FINE); - } - - public int getSLOC() { - return sloc; - } - - // do nothing on directories - public boolean handleDirectory(File directory) { - return true; - } - - // count the ; and } in each file. - public boolean handleFile(File file) { - if (!file.getName().endsWith(".java")) { - return true; - } - - if (DETAIL) { - getLogger().info("Counting code in " + file.getName()); - } - - int count = 0; - - try { - BinaryBufferedFile bbf = new BinaryBufferedFile(file); - - try { - while (true) { - char c = bbf.readChar(); - if (c == ';' || c == '}') { - count++; - } - } - } catch (EOFException eofe) { - } catch (FormatException fe) { - } - bbf.close(); - - if (DETAIL) { - getLogger().info(file.getName() + " has " + count + " LOC"); - } - - sloc += count; - - } catch (IOException ioe) { - } - return true; - } - - // - /** - * Holder for this class's Logger. This allows for lazy initialization of - * the logger. - */ - private static final class LoggerHolder { - /** - * The logger for this class - */ - private static final Logger LOGGER = Logger.getLogger(SLOC.class.getName()); - - /** - * Prevent instantiation - */ - private LoggerHolder() { - throw new AssertionError("The LoggerHolder should never be instantiated"); - } - } - - /** - * Get the logger for this class. - * - * @return logger for this class - */ - private static Logger getLogger() { - return LoggerHolder.LOGGER; - } - - // - - /** - * Given a set of files or directories, parade through them to change their - * case. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - - ArgParser ap = new ArgParser("SLOC"); - - if (argv.length == 0) { - ap.bail("Counts ';' and '}' to sum up Source Lines Of Code\nUsage: java com.bbn.openmap.util.wanderer.SLOC ", - false); - } - - ap.parse(argv); - - String[] dirs = argv; - - SLOC sloc = new SLOC(); - Wanderer wanderer = new Wanderer(sloc); - - int runningTotal = 0; - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - sloc.setSLOC(0); - wanderer.handleEntry(new File(dirs[i])); - getLogger().info("Source Lines of Code in " + dirs[i] + " = " + sloc.getSLOC()); - runningTotal += sloc.getSLOC(); - } - - if (dirs.length > 1) { - getLogger().info("Total Source Lines of Code in all directories = " + runningTotal); - } - } -} \ No newline at end of file diff --git a/src/openmap/com/bbn/openmap/util/wanderer/Wanderer.java b/src/openmap/com/bbn/openmap/util/wanderer/Wanderer.java deleted file mode 100644 index fe88f5278..000000000 --- a/src/openmap/com/bbn/openmap/util/wanderer/Wanderer.java +++ /dev/null @@ -1,201 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/wanderer/Wanderer.java,v $ -// $RCSfile: Wanderer.java,v $ -// $Revision: 1.8 $ -// $Date: 2006/07/17 17:31:46 $ -// $Author: mthome $ -// -// ********************************************************************** - -package com.bbn.openmap.util.wanderer; - -import java.io.File; - -import com.bbn.openmap.util.ArgParser; - -/** - * A Wanderer is a class that traverses a directory tree and finds files and - * directories. It then makes a method call on the WandererCallback class to - * have something done on those directories or files. Subclasses can set whether - * the search is exhaustive (ignoring returns from handleDirectory that the - * search was successful) and/or runs top to bottom of the directory structure, - * or bottom to top. - */ -public class Wanderer { - - WandererCallback callback = null; - protected boolean exhaustiveSearch = false; - protected boolean topToBottom = true; - - public Wanderer() { - - } - - public Wanderer(WandererCallback callback) { - this(); - this.callback = callback; - } - - public void setCallback(WandererCallback cb) { - callback = cb; - } - - public WandererCallback getCallback() { - return callback; - } - - /** - * Given a file representing a top-level directory, start wandering the tree - * and call handleDirectory or handleFile on the WandererCallback. - * - * @param file File (directory) to start at. - * @return true if the wandering should continue. - */ - public boolean handleEntry(File file) { - boolean continueWandering = true; - try { - String[] filenames = file.list(); - boolean dirTest = false; - boolean not14 = false; - - try { - java.lang.reflect.Method method = file.getClass().getDeclaredMethod("isDirectory", (Class[]) null); - Object obj = method.invoke(file, (Object[]) null); - if (obj instanceof Boolean) { - dirTest = ((Boolean) obj).booleanValue(); - } - } catch (NoSuchMethodException nsme) { - not14 = true; - } catch (SecurityException se) { - not14 = true; - } catch (IllegalAccessException iae) { - not14 = true; - } catch (IllegalArgumentException iae2) { - not14 = true; - } catch (java.lang.reflect.InvocationTargetException ite) { - not14 = true; - } - - if (not14) { - dirTest = (filenames != null); - } - - if (dirTest) { - - if (isTopToBottom()) { - // It's a directory... - continueWandering = callback.handleDirectory(file); - - if (continueWandering) { - continueWandering = handleDirectory(file, filenames); - } - } else { - handleDirectory(file, filenames); - callback.handleDirectory(file); - } - - } else { - continueWandering = callback.handleFile(file); - } - } catch (NullPointerException npe) { - System.out.println("null pointer exception"); - } catch (SecurityException se) { - } - - return continueWandering; - } - - /** - * Management method for the wanderer, that steps through the children of - * the directory and calls handleEntry for them. - * - * @param directory - * the directory to handle - * @param contentNames - * an array of Strings representing children of the directory - * @return true if the wandering should continue. - * @throws SecurityException - */ - protected boolean handleDirectory(File directory, String[] contentNames) throws SecurityException { - - boolean continueWandering = true; - - for (String child : contentNames) { - boolean keepGoing = handleEntry(new File(directory.getAbsolutePath() + File.separator, child)); - if (!keepGoing) { - continueWandering = exhaustiveSearch; - - if (!continueWandering) { - break; - } - } - } - - return continueWandering; - } - - public boolean isExhaustiveSearch() { - return exhaustiveSearch; - } - - /** - * @param exhaustiveSearch set to true if you want to ignore the - * handleDirectory and handleFile return values. - */ - public void setExhaustiveSearch(boolean exhaustiveSearch) { - this.exhaustiveSearch = exhaustiveSearch; - } - - public boolean isTopToBottom() { - return topToBottom; - } - - /** - * Set to true if handleDirectory is called before moving to - * handleFile/handleDirectory for child files. - * - * @param topToBottom - */ - public void setTopToBottom(boolean topToBottom) { - this.topToBottom = topToBottom; - } - - /** - * Given a set of files or directories, parade through them to change their - * case. - * - * @param argv - * paths to files or directories, use -h to get a usage - * statement. - */ - public static void main(String[] argv) { - ArgParser ap = new ArgParser("Wanderer"); - - if (argv.length == 0) { - ap.bail("", true); - } - - String[] dirs = argv; - - Wanderer wanderer = new Wanderer(new TestWandererCallback()); - - // Assume that the arguments are paths to directories or - // files. - for (int i = 0; i < dirs.length; i++) { - wanderer.handleEntry(new File(dirs[i])); - } - } -} \ No newline at end of file diff --git a/src/vpfbrowseservlet/.gitignore b/src/vpfbrowseservlet/.gitignore deleted file mode 100644 index dc5353ef0..000000000 --- a/src/vpfbrowseservlet/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/.classpath -/.settings/ diff --git a/src/vpfbrowseservlet/.project b/src/vpfbrowseservlet/.project deleted file mode 100644 index 6e9d3ac3f..000000000 --- a/src/vpfbrowseservlet/.project +++ /dev/null @@ -1,42 +0,0 @@ - - - openmap-vpfbrowseservlet - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/src/vpfbrowseservlet/README b/src/vpfbrowseservlet/README deleted file mode 100644 index 18b31a041..000000000 --- a/src/vpfbrowseservlet/README +++ /dev/null @@ -1,69 +0,0 @@ -A basic set of JSP/Servlet code to display VPF data in a web browser. -All of the data is presented as text, not on a map. It is intended to -help someone trying to understand how VPF tables are constructed, and -how they relate to one another. It may also be helpful to someone -looking at what attributes are available for particular feature types -in a specific VPF database. - -The packages uses J2EE capabilities, and has only been tested under -the Apache Software Foundation's Jakarta Tomcat J2EE engine (4.0). - -http://jakarta.apache.org - -The package is still fairly basic, and needs some serious redesign. -Much of the package is laid out the way it is because the author went -out of his way to learn about specific J2EE capabilities. - -Each installation will need to modify web.xml to reflect the database -name and path to the data for their server. - -To build the code, the build.xml file needs to be modified so the -tomcat home directory is set. You might have to set the servlet.jar -file name (servlet-api.jar for tomcat 5) depending on the version of -tomcat you are using. - -Next, you need to modify the WEB-INF/web.xml file so it points to -your VPF data. This is done by modifying/adding these sections: - - - com.bbn.openmap.vpfservlet.vpf_library.noamer - /data/vpf/vmaplv0/disk0 - - VMAP Level 0 North America Data. - - - -where the param-value parameter should point to the same directory -that the VPFLayer does, the parent of the .lat file for the dataset. -From the instructions in the web.xml file: - - Any parameter with a name beginning with - "com.bbn.openmap.vpfservlet.vpf_library." will be interpreted as a path to - the root of a VPF database. The servlets will first try and resolve the - path within the webapp directory, and if not found there, will try the - path as an absolute path. If either of these paths are found, the library - will be added to the list of available databases on the servlet home page. - If neither of the paths work, the library will not be listed, and an error - logged in the servlet logs. - -Finally, run ant on your build.xml file, and a vbfbrowse.war file will -be created. This war file needs to be moved into the tomcat webapps -directory. - -The servlet can then be accessed by connecting to: - -http://localhost:tomcat_port/vpfbrowse - - -Among the improvements needed: - HTML generation code should move to JSPs wherever possible, java -code should just provide access to the JSP layer. - The separation into schema and table data into separate servlets -needs to be reconsidered. For basic tables it works, but when joining -multiple tables, the schema section doesn't display this. Probably -the schema output should be added to the RowMaker classes, since these -classes are what perform the joins. - Need to be more aggressive about rejecting bad URLs, it might be -possible to get the servlet code to return data not in a database -path, and thus not intended to be shared. - diff --git a/src/vpfbrowseservlet/build.xml b/src/vpfbrowseservlet/build.xml deleted file mode 100644 index f1146d165..000000000 --- a/src/vpfbrowseservlet/build.xml +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/vpfbrowseservlet/nb-configuration.xml b/src/vpfbrowseservlet/nb-configuration.xml deleted file mode 100644 index 14918b9c9..000000000 --- a/src/vpfbrowseservlet/nb-configuration.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - /less:/css - false - false - - - /scss:/css - js/libs - true - none - 4 - 4 - 4 - 120 - false - none - 4 - 4 - 4 - 120 - false - project - - diff --git a/src/vpfbrowseservlet/pom.xml b/src/vpfbrowseservlet/pom.xml deleted file mode 100644 index 23f2477fd..000000000 --- a/src/vpfbrowseservlet/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - 4.0.0 - openmap-vpfbrowseservlet - war - openmap-vpfbrowseservlet - OpenMap is a Java Beans based toolkit for building applications and applets needing geographic information. This project contains components that can create a server to browse the contents of VPF libraries. - - - - javax.servlet - servlet-api - 2.5 - - - org.openmap-java - openmap - 6.0 - - - - - org.openmap-java - openmap-all - 6.0 - ../.. - - diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ApplyIterator.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ApplyIterator.java deleted file mode 100644 index d0dae1cf7..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ApplyIterator.java +++ /dev/null @@ -1,52 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ApplyIterator.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.util.Iterator; - -/** - * An Iterator subclass that wraps another iterator. Each element - * returned by the iterator is the result of calling Applyable.apply() - * on the current element of the underlying iterator. - */ -public class ApplyIterator implements Iterator { - /** the iterator to be wrapped */ - final private Iterator wrapped; - /** the Applyable object to use before returning each element */ - final private Applyable applier; - - /** - * Constructor - * - * @param iter the iterator to wrap, may not be null - * @param apply the Applyable object to use in next(), may not be - * null - */ - public ApplyIterator(Iterator iter, Applyable apply) { - wrapped = iter; - applier = apply; - } - - public boolean hasNext() { - return wrapped.hasNext(); - } - - public Object next() { - return applier.apply(wrapped.next()); - } - - public void remove() { - wrapped.remove(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Applyable.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Applyable.java deleted file mode 100644 index de4ef1643..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Applyable.java +++ /dev/null @@ -1,24 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/Applyable.java,v $ -// $Revision: 1.2 $ $Date: 2004/10/14 18:06:32 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -/** - * Applyable interface for use with ApplyIterator. - */ -public interface Applyable { - /** - * The apply method - */ - Object apply(Object obj); -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexFeatureJoinRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexFeatureJoinRowMaker.java deleted file mode 100644 index f518758cc..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexFeatureJoinRowMaker.java +++ /dev/null @@ -1,112 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ComplexFeatureJoinRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.VPFUtil; -import com.bbn.openmap.util.html.TableDataElement; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker that performs the join in a feature index table. - */ -public class ComplexFeatureJoinRowMaker extends PlainRowMaker { - /** a list reused to load primitive rows */ - final List primRow = new ArrayList(); - /** a list reused to load feature rows */ - final List featureRow = new ArrayList(); - - /** the array of feature tables, each index is lazy-initialized */ - final DcwRecordFile[] featureTables; - - /** - * Construct a rowmaker for a complex feature join. - * @param drf the table - * @throws FormatException some error was encountered - */ - public ComplexFeatureJoinRowMaker(DcwRecordFile drf) throws FormatException { - featureTables = getTables(drf); - } - - public void addToRow(TableRowElement row, List l) { - try { - boolean color1 = false; - int i = 0; - for (Iterator li = l.iterator(); li.hasNext(); ) { - Object o = li.next(); - DcwRecordFile featureTable = featureTables[i++]; - if ((featureTable != null) && - featureTable.getRow(featureRow, VPFUtil.objectToInt(o))) { - color1 = !color1; - for (Iterator fi = featureRow.iterator(); fi.hasNext(); ) { - row.addElement(new TableDataElement(color1 ? "CLASS=JoinColumn" : "CLASS=Join2Column", - fi.next().toString())); - } - } else { - row.addElement(o.toString()); - } - } - } catch (FormatException fe) { - row.addElement(fe.toString()); - } - } - - public DcwRecordFile[] getTables(DcwRecordFile drf) throws FormatException { - DcwRecordFile[] retval = new DcwRecordFile[drf.getColumnCount()]; - File dirPath = new File(drf.getTableFile()).getParentFile(); - File fcsfile = new File(dirPath, "fcs"); - if (!fcsfile.canRead()) { - fcsfile = new File(dirPath, "fcs."); - } - DcwRecordFile fcs = new DcwRecordFile(fcsfile.toString()); - List l = new ArrayList(fcs.getColumnCount()); - String tableName = drf.getTableName(); - - int table1Column = fcs.whatColumn("table1"); - int table1_keyColumn = fcs.whatColumn("table1_key"); - int table2Column = fcs.whatColumn("table2"); - int table2_keyColumn = fcs.whatColumn("table2_key"); - - while (fcs.parseRow(l)) { - String table1 = (String)l.get(table1Column); - String table1_key = (String)l.get(table1_keyColumn); - String table2 = (String)l.get(table2Column); - String table2_key = (String)l.get(table2_keyColumn); - if (table1.equalsIgnoreCase(tableName) && - table2_key.equalsIgnoreCase("id")) { - int indexCol = drf.whatColumn(table1_key); - retval[indexCol] = new DcwRecordFile(dirPath + File.separator + table2); - } - } - - fcs.close(); - return retval; - } - - public void close() { - for (int i = 0; i < featureTables.length; i++) { - DcwRecordFile drf = featureTables[i]; - if (drf != null) { - drf.close(); - } - } - } -} - diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexJoinRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexJoinRowMaker.java deleted file mode 100644 index 9635478a3..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ComplexJoinRowMaker.java +++ /dev/null @@ -1,102 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ComplexJoinRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.FeatureClassInfo; -import com.bbn.openmap.util.html.TableDataElement; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker subclass that handles joins between tables, where the - * column guiding the join of the second table is not "id", and thus - * not simply the row identifier. - */ -public class ComplexJoinRowMaker extends PlainRowMaker { - /** the column that contains the foreign key to the primitive table */ - final int theColumn; - /** the column that contains the tile identifier */ - final int tileColumn; - /** a list reused to load join rows */ - final List jtrow = new ArrayList(); - - /** a map from the table key to row id */ - final Map keyMap; - /** the table we're joining with */ - final DcwRecordFile joinTable; - - public ComplexJoinRowMaker(DcwRecordFile table, String joinColumnName, - String tableName, String tableKeyColumn, boolean isTiled) - throws FormatException { - theColumn = table.whatColumn(joinColumnName); - tileColumn = table.whatColumn(FeatureClassInfo.TILE_ID_COLUMN_NAME); - if (isTiled) { - throw new FormatException("can't complex join with tiling (yet)"); - } - joinTable = new DcwRecordFile(new File(table.getTableFile()).getParentFile() - + File.separator + tableName); - keyMap = getKeyMap(tableKeyColumn); - } - - HashMap getKeyMap(String keyColumn) throws FormatException { - int jcol = joinTable.whatColumn(keyColumn); - HashMap retmap = new HashMap(); - while (joinTable.parseRow(jtrow)) { - retmap.put(jtrow.get(jcol), jtrow.get(0)); - } - return retmap; - } - - public void addToRow(TableRowElement row, List l) { - int i = 0; - for (Iterator li = l.iterator(); li.hasNext();) { - Object elt = li.next(); - if (i == theColumn) { - Number wrow = (Number) keyMap.get(elt); -// int tileId = (tileColumn == -1) ? -1 -// : VPFUtil.objectToInt(l.get(tileColumn)); - - try { - if (wrow == null) { - row.addElement("[" + elt + "]"); - } else if (joinTable.getRow(jtrow, wrow.intValue())) { - for (Iterator it = jtrow.iterator(); it.hasNext();) { - row.addElement(new TableDataElement("CLASS=JoinColumn", it.next() - .toString())); - } - } else { - row.addElement("Join failed!"); - } - } catch (FormatException fe) { - row.addElement(fe.toString()); - } - } else { - row.addElement(elt.toString()); - } - i++; - } - } - - public void close() { - joinTable.close(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ContextInfo.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ContextInfo.java deleted file mode 100644 index 76707b106..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ContextInfo.java +++ /dev/null @@ -1,203 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ContextInfo.java,v $ -// $Revision: 1.8 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import com.bbn.openmap.layer.vpf.LibrarySelectionTable; -import java.io.File; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import javax.servlet.ServletContext; - -/** - * This class holds information retrieved from the ServletContext. - */ -public class ContextInfo { - - /** - * the name of the attribute where ContextInfo objects are in the ServletContext - */ - public static final String CONTEXT_INFO = ContextInfo.class.getPackage().getName() + ".contextInfo"; - /** - * the prefix used to configure VPF libraries in web.xml - */ - public static final String LIBRARY_PREFIX = ContextInfo.class.getPackage().getName() + ".vpf_library."; - - /** - * a map from library name to (String) library path - */ - private Map lib_pathmap; - /** - * a map from library name to LibrarySelectionTable - */ - private Map lib_lstmap; - - /** - * A constructor - use getContextInfo to get one. - * - * @param context the ServletContext to use to initialize - * @see #getContextInfo - */ - private ContextInfo(ServletContext context) { - lib_pathmap = createLibrariesMap(context); - lib_lstmap = new HashMap(); - } - - /** - * Returns the ContextInfo object for the ServletContext. - * - * @param context the ServletContext to either get an existing ContextInfo from, or the context to use to initialize - * a new ContextInfo, if one doesn't already exist for the context. - */ - public static synchronized ContextInfo getContextInfo(ServletContext context) { - ContextInfo ci = (ContextInfo) context.getAttribute(CONTEXT_INFO); - if (ci == null) { - ci = new ContextInfo(context); - context.setAttribute(CONTEXT_INFO, ci); - } - return ci; - } - - /** - * Grovels through the ServletContext initialization parameters and creates a map from library name to library path. - * - * @param context the context to grovel through - */ - private Map createLibrariesMap(ServletContext context) { - HashMap library_map = new HashMap(); - for (Enumeration en = context.getInitParameterNames(); en.hasMoreElements();) { - String s = (String) en.nextElement(); - if (s.startsWith(LIBRARY_PREFIX)) { - String libname = s.substring(LIBRARY_PREFIX.length()); - String path = getPath(context, context.getInitParameter(s)); - if (path != null) { - library_map.put(libname, path); - } else { - context.log("Excluding " + libname - + " from database list, can't resolve path"); - } - - } - } - return Collections.unmodifiableMap(library_map); - } - - /** - * Try and find an absolute path from an init parameter - * - * @param context the context to use to resolve paths - * @param path the path to try and resolve - * @return an absolute path to a file (hopefully a directory) on the system, or null indicating the resolve failed - * to find anything useful. - */ - private String getPath(ServletContext context, String path) { - // try to resolve as a relative path in the war file - try { - String p2 = context.getRealPath(path); - if (p2 != null) { - File f = new File(p2); - if (f.exists()) { - return p2; - } - } - } catch (java.security.AccessControlException jsace) { - // ignore, nothing to do but press on - } - // try to resolve as an absolute path on the system - try { - File f = new File(path); - if (f.exists()) { - return path; - } - } catch (java.security.AccessControlException jsace) { - // ignore, nothing to do - } - return null; - } - - /** - * Return a file object that the path resolves to. Performs some minimal checks to try and prevent an attacker from - * feeding in urls that cause the servlets to climb out of their sandbox. A better option is to use a servlet - * container with the ability to restrict servlet file access. For example, Apache Software Foundation's Tomcat 5 - * Servlet/JSP Container running with the -security flag. - * - * @param pathInfo the path to resolve (expected to be of the form "/library_name_in_web_xml/path/to/file") - * @return a File if it could be resolved, null otherwise - */ - public String resolvePath(String pathInfo) { - if ((pathInfo == null) || (pathInfo.indexOf("..") != -1)) { // don't - // climb - // out - // of - // sandbox - return null; - } - int libStart = pathInfo.indexOf('/') + 1; - int libEnd = pathInfo.indexOf('/', libStart); - if (libEnd == -1) { - libEnd = pathInfo.length(); - } - String libname = pathInfo.substring(libStart, libEnd); - String subpath = pathInfo.substring(libEnd); - - String lib_home = getPath(libname); - if (lib_home == null) { - return null; - } - - return lib_home + "/" + subpath; - } - - /** - * Returns a Set whose values are the (String) names of the configured libraries. - * - * @return a set of library names - */ - public Set keySet() { - return new TreeSet(lib_pathmap.keySet()); - } - - /** - * Returns the path (or null) for the library - * - * @param libname the library name - * @return the path or null - */ - public String getPath(String libname) { - return (String) lib_pathmap.get(libname); - } - - /** - * Returns the LibrarySelectionTable (or null) for the library - * - * @param libname the library name - * @return the LST or null - */ - public LibrarySelectionTable getLST(String libname) { - return (LibrarySelectionTable) lib_lstmap.get(libname); - } - - /** - * Adds an LST for a library - * - * @param libname the library name - * @param lst the LibrarySelectionTable for libname - */ - public void putLST(String libname, LibrarySelectionTable lst) { - lib_lstmap.put(libname, lst); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Data.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Data.java deleted file mode 100644 index cb497d620..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Data.java +++ /dev/null @@ -1,418 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/Data.java,v $ -// $Revision: 1.6 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.StringTokenizer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.Constants; -import com.bbn.openmap.layer.vpf.DcwColumnInfo; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.StringElement; -import com.bbn.openmap.util.html.TableHeaderElement; -import com.bbn.openmap.util.html.TableRowElement; -import com.bbn.openmap.util.html.WrapElement; - -/** - * A servlet class that will output table data. - */ -public class Data extends VPFHttpServlet { - /** the name of the http parameter with the table name */ - public static final String VDTParam = "vdt"; - /** the possible values of the rowselect parameter */ - public static final String RowSelectParam = "show"; - public static final String RowSelectAll = "all"; - public static final String RowSelectNone = "none"; - public static final String RowSelectTest = "test"; - /** other parameters that the servlet takes */ - public static final String JoinColumnParam = "colname"; - public static final String JoinOtherTableParam = "othertable"; - public static final String JoinOtherTableKeyParam = "othertablekey"; - public static final String IsTiledParam = "isTiled"; - - /** - * A do-nothing constructor - init does all the work. - */ - public Data() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - DcwRecordFile foo = (DcwRecordFile) request.getAttribute(DispatchServlet.RECORD_FILE_OBJ); - if (foo == null) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - try { - doWork(request, response, foo); - } catch (FormatException fe) { - response.getWriter().println("FormatException dealing with table: " - + fe); - } - } - - /** - * Generates the heading used for each HTML table - */ - protected TableRowElement generateHeader(HttpServletRequest req, - HttpServletResponse resp, - DcwColumnInfo[] dci) { - TableRowElement thr = new TableRowElement(); - for (int i = 0; i < dci.length; i++) { - DcwColumnInfo dc = dci[i]; - String colName = dc.getColumnName(); - if (dc.getValueDescriptionTable() == null) { - thr.addElement(new TableHeaderElement(colName)); - } else { - StringBuffer baseurl = new StringBuffer(); - baseurl.append(req.getContextPath()); - baseurl.append(req.getServletPath()); - baseurl.append(req.getPathInfo()).append("?"); - String show = req.getParameter(RowSelectParam); - String vdtl = req.getParameter(VDTParam); - if (show != null) { - baseurl.append(RowSelectParam).append("="); - baseurl.append(show).append("&"); - } - baseurl.append(VDTParam).append("="); - if (vdtl == null) { - vdtl = ""; - } - boolean appendCol = true; - boolean needSep = false; - StringTokenizer st = new StringTokenizer(vdtl, ","); - while (st.hasMoreTokens()) { - String sname = st.nextToken(); - if (colName.equals(sname)) { - appendCol = false; - } else { - append(baseurl, sname, needSep); - needSep = true; - } - } - if (appendCol) { - append(baseurl, colName, needSep); - } - thr.addElement(THE(colName, baseurl.toString())); - } - } - return thr; - } - - public static StringBuffer append(StringBuffer base, String app, - boolean needSep) { - return (needSep ? base.append(",") : base).append(app); - } - - public static final String ROWLIST_OBJECT = Data.class.getPackage() - .getName() - + ".rowlist"; - - protected void doWork(HttpServletRequest request, - HttpServletResponse response, DcwRecordFile drf) - throws FormatException, IOException { - DcwColumnInfo dci[] = drf.getColumnInfo(); - - int rowlist[] = (int[]) request.getAttribute(ROWLIST_OBJECT); - - ListElement rows = new ListElement(); - WrapElement table = new WrapElement("table", "BORDER=1 ALIGN=CENTER", rows); - TableRowElement thr = generateHeader(request, response, dci); - rows.addElement(thr); - - String row_show = request.getParameter(RowSelectParam); - boolean printall = RowSelectAll.equals(row_show); - boolean parseall = RowSelectTest.equals(row_show); - boolean schemaonly = RowSelectNone.equals(row_show); - - String baseurl = request.getContextPath() + request.getServletPath() - + request.getPathInfo(); - String all = baseurl + "?" + RowSelectParam + "=" + RowSelectAll; - String none = baseurl + "?" + RowSelectParam + "=" + RowSelectNone; - String some = baseurl; - String test = baseurl + "?" + RowSelectParam + "=" + RowSelectTest; - String qstr = request.getQueryString(); - if (rowlist != null) { - qstr = null; - } - if (qstr == null) { - qstr = VDTParam + "=ALL"; - } - if (qstr.indexOf(VDTParam + "=") == -1) { - qstr += "&" + VDTParam + "=ALL"; - } - String vdtlookup = baseurl + "?" + qstr; - - response.getWriter().println("

Table Data

"); - String redisplay = "Redisplay " + buildHREF(response, all, "All") - + "\r\n|" + buildHREF(response, none, "None") + "\r\n|" - + buildHREF(response, some, "Some") + "\r\n|" - + buildHREF(response, test, "Test") + "\r\n|" - + buildHREF(response, vdtlookup, "All VDT Columns") + "\r\n"; - - if (schemaonly) { - response.getWriter().println("Data Omitted: " + redisplay); - return; - } - - RowMaker rm; - String basepath = getRootDir(request); - String joincol = request.getParameter(JoinColumnParam); - String jointable = request.getParameter(JoinOtherTableParam); - String jointablekey = request.getParameter(JoinOtherTableKeyParam); - if ((joincol != null) && (jointable != null)) { - String isTiledJoin = request.getParameter(IsTiledParam); - boolean isTiled = Boolean.valueOf(isTiledJoin).booleanValue(); - if (Constants.ID.equals(jointablekey)) { - rm = new JoinRowMaker(drf, joincol, jointable, isTiled); - } else { - rm = new ComplexJoinRowMaker(drf, joincol, jointable, jointablekey, isTiled); - } - } else if (drf.getTableName().equals(Constants.charVDTTableName) - || drf.getTableName().equals(Constants.intVDTTableName)) { - rm = new VDTRowMaker(request, response, basepath, drf); - } else if (drf.getTableName().equals("fcs")) { - rm = new FCSRowMaker(request, response, basepath, drf); - } else if (request.getParameter(VDTParam) != null) { - String subsetmarkup = request.getParameter(VDTParam); - String[] ss = null; - if (subsetmarkup != null) { - StringTokenizer st = new StringTokenizer(subsetmarkup, ",", false); - ss = new String[st.countTokens()]; - for (int i = 0; i < ss.length; i++) { - ss[i] = st.nextToken(); - if ("ALL".equals(ss[i])) { - ss = null; // null array gets all VDT lookups - break; - } - } - } - rm = new DetailRowMaker(drf, ss); - } else if (drf.getTableName().endsWith(".fit")) { - rm = new FITRowMaker(drf); - } else if (drf.getTableName().endsWith(".cft") - || drf.getTableName().endsWith(".cjt")) { - rm = new ComplexFeatureJoinRowMaker(drf); - } else { - rm = new PlainRowMaker(); - } - - Iterator rowiter; - if (rowlist != null) { - rowiter = new TableSubsetRecordIterator(rowlist, drf); - } else if (printall) { - rowiter = new TableListIterator(drf); - } else if (parseall) { - rowiter = new TableTestParseIterator(drf); - } else { - rowiter = new TableSampleIterator(drf); - } - // response.getWriter().println("
Tn = " + - // drf.getTableName() + - // "
" + rm.getClass().getName() + " " + - // rowiter.getClass().getName() + "
"); - int rowcount = 0; - while (rowiter.hasNext()) { - if (rowcount++ >= 99) { - response.getWriter().println(redisplay); - table.generate(response.getWriter()); - rows = new ListElement(); - table = new WrapElement("table", "BORDER=1 ALIGN=CENTER", rows); - rows.addElement(new WrapElement("CAPTION", new StringElement("table data"))); - rows.addElement(thr); - - rowcount = 0; - } - rows.addElement(rm.generateRow((List) rowiter.next())); - } - rm.close(); - response.getWriter().println(redisplay); - table.generate(response.getWriter()); - } - - public ContextInfo getContextInfo() { - return contextInfo; - } - - public static String joinURL(HttpServletRequest request, - HttpServletResponse response, int tag, - String filename, String colname, - String othertable, String othertablekey, - boolean isTiled) { - String pathInfo = request.getPathInfo(); - int index = pathInfo.lastIndexOf('/'); - String subpath = pathInfo.substring(0, index + 1); - String url = request.getContextPath() + request.getServletPath() - + subpath + filename + "?" + JoinColumnParam + "=" + colname - + "&" + JoinOtherTableParam + "=" + othertable + "&" - + JoinOtherTableKeyParam + "=" + othertablekey + "&" - + IsTiledParam + "=" + isTiled; - String value = "" + tag - + "\r\n"; - return value; - } - - /** - * An iterator that returns a subset of the table rows - */ - private static class TableSampleIterator implements Iterator { - private final int recordCount; - private final int columnCount; - private int curRow = 0; - private final DcwRecordFile drf; - - public TableSampleIterator(DcwRecordFile drf) throws FormatException { - this.drf = drf; - recordCount = drf.getRecordCount(); - columnCount = drf.getColumnCount(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - public boolean hasNext() { - return (curRow < recordCount); - } - - public Object next() { - if (curRow < 10) { - curRow++; - } else if (curRow == 10) { - curRow = 100; - } else { - curRow += 100; - } - if (curRow > recordCount) { - curRow = recordCount; - } - ArrayList al = new ArrayList(columnCount); - try { - if (!drf.getRow(al, curRow)) { - throw new NoSuchElementException(); - } - } catch (FormatException fe) { - throw new NoSuchElementException(); - } - return al; - } - } - - /** - * An iterator that returns a subset of the table rows, but parses - * every record in the table. - */ - private static class TableTestParseIterator implements Iterator { - final ListIterator base; - - public TableTestParseIterator(DcwRecordFile drf) throws FormatException { - base = new TableListIterator(drf); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - public boolean hasNext() { - return base.hasNext(); - } - - public Object next() { - int index; - Object ret; - do { - index = base.nextIndex(); - ret = base.next(); - } while ((index > 10) && ((index % 100) != 0) && base.hasNext()); - return ret; - } - } - - /** - * An iterator that will return every row in the table. - */ - private static class TableListIterator implements java.util.ListIterator { - private int curRow = 1; - private final DcwRecordFile drf; - private final int columnCount; - private final int recordCount; - - public TableListIterator(DcwRecordFile drf) throws FormatException { - this.drf = drf; - columnCount = drf.getColumnCount(); - recordCount = drf.getRecordCount(); - } - - public void add(Object o) { - throw new UnsupportedOperationException(); - } - - public boolean hasPrevious() { - return (curRow > 1); - } - - public boolean hasNext() { - return (curRow <= recordCount); - } - - private ArrayList getRow(int row) { - ArrayList al = new ArrayList(columnCount); - try { - if (!drf.getRow(al, row)) { - throw new NoSuchElementException(); - } - } catch (FormatException fe) { - throw new NoSuchElementException(); - } - return al; - } - - public Object next() { - return getRow(curRow++); - } - - public Object previous() { - return getRow(--curRow); - } - - public int nextIndex() { - return curRow; - } - - public int previousIndex() { - return (curRow - 1); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - public void set(Object o) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DescribeDBServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DescribeDBServlet.java deleted file mode 100644 index 495b3f137..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DescribeDBServlet.java +++ /dev/null @@ -1,311 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/DescribeDBServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.CoverageAttributeTable; -import com.bbn.openmap.layer.vpf.CoverageTable; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.FeatureClassInfo; -import com.bbn.openmap.layer.vpf.LibrarySelectionTable; -import com.bbn.openmap.util.html.HtmlListElement; -import com.bbn.openmap.util.html.ListBodyElement; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.WrapElement; - -/** - * This class prints out a description of a VPF database, listing the available - * libraries, coverage types and feature types. - */ - -public class DescribeDBServlet - extends VPFHttpServlet { - /** - * Takes path arguments, and prints the DB it finds - */ - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - out.println(HTML_DOCTYPE); - out.println(getStylesheetHTML(request)); - - String pathInfo = request.getPathInfo(); - if (pathInfo == null) { - selectDB(request, response); - return; - } - int findex = pathInfo.indexOf('/', 1); - if (findex < 0) { - findex = pathInfo.length(); - } - String libname = pathInfo.substring(1, findex); - - try { - LibrarySelectionTable lst = getLST(libname); - if (lst == null) { - out.println("VPF Database not configured: " + libname); - return; - } - String dbname = lst.getDatabaseName(); - out.println("\nDescribe VPF Database " + dbname + "\n\n

VPF Database " - + dbname + "

\n"); - ListElement dble = new ListBodyElement(); - WrapElement dblist = new WrapElement("ul", dble); - dble.addElement("Database Description: " + lst.getDatabaseDescription()); - dble.addElement("Database Description Table: " + buildURL(request, response, libname, "dht")); - List libraries = lst.getLibraryNames(); - StringBuffer libnames = new StringBuffer("Database Libraries: "); - for (String libName : libraries) { - libnames.append("").append(libName); - libnames.append("").append(" "); - } - libnames.append("(from "); - libnames.append(buildURL(request, response, libname, "lat")); - libnames.append(")"); - - dble.addElement(libnames.toString()); - dblist.generate(out); - for (String libName : libraries) { - // String prefix = libraries[i] + ":"; - printLibrary(request, response, libname, lst.getCAT(libName)); - } - out.println(""); - } catch (FormatException fe) { - throw new ServletException("FormatException: ", fe); - } - } - - public void selectDB(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - PrintWriter out = response.getWriter(); - - Set databases = contextInfo.keySet(); - - out.println("\nSelect VPF Database" + "\n\n

Available VPF Databases" + "

\n"); - HtmlListElement dblist = new HtmlListElement(); - for (Iterator dbi = databases.iterator(); dbi.hasNext();) { - String db = (String) dbi.next(); - String url = request.getContextPath() + "/DescribeVPF/" + db; - dblist.addElement("" + db + "\r\n"); - } - dblist.generate(out); - out.println("\r\n"); - } - - public static String buildURL(HttpServletRequest request, HttpServletResponse response, String filepref, String filename, - String tag) { - String url = request.getContextPath() + "/UnknownType/" + filepref + "/" + filename; - return "" + tag + ""; - } - - public static String buildURL(HttpServletRequest request, HttpServletResponse response, String filepref, String filename) { - return buildURL(request, response, filepref, filename, filename); - } - - /** - * Prints a VPF Library. - * - * @param request the HttpServletRequest. - * @param response the HTTPServletResponse. - * @param pathPrefix lines get printed with this prefix - * @param cat the CoverageAttributeTable (Library) to print - */ - public void printLibrary(HttpServletRequest request, HttpServletResponse response, String pathPrefix, CoverageAttributeTable cat) - throws ServletException, IOException { - PrintWriter out = response.getWriter(); - - if (cat == null) { - out.println("

Catalog doesn't exist

"); - return; - } - String libName = cat.getLibraryName(); - String libpath = pathPrefix + "/" + libName; - - out.println("

Library " + buildURL(request, response, pathPrefix, libName, libName) - + "

"); - String[] coverages = cat.getCoverageNames(); - Arrays.sort(coverages); - - HtmlListElement list = new HtmlListElement(); - list.addElement("Library uses " + (cat.isTiledData() ? "tiled" : "untiled") + " data"); - HtmlListElement clist = new HtmlListElement("Coverage names (from " + buildURL(request, response, libpath, "cat") + ")"); - - list.addElement(clist); - for (int i = 0; i < coverages.length; i++) { - clist.addElement("" + coverages[i] + ""); - } - list.addElement("Library Header Table: " + buildURL(request, response, libpath, "lht")); - list.addElement("Geographic Reference Table: " + buildURL(request, response, libpath, "grt")); - list.generate(out); - for (int i = 0; i < coverages.length; i++) { - printCoverage(request, response, libpath + "/" + coverages[i], libName, cat, coverages[i]); - } - } - - /** - * Prints a VPF Coverage - * - * @param pathPrefix lines get printed with this prefix - * @param cat the CoverageAttributeTable to get the Coverage from - * @param covname the name of the coverage to print - */ - public void printCoverage(HttpServletRequest request, HttpServletResponse response, String pathPrefix, String libName, - CoverageAttributeTable cat, String covname) - throws ServletException, IOException { - PrintWriter out = response.getWriter(); - out.println("

Coverage " - + buildURL(request, response, pathPrefix, "", covname) + " for Library " + libName - + "

"); - HtmlListElement list = new HtmlListElement(); - list.addElement("Description: " + cat.getCoverageDescription(covname)); - list.addElement("Topology Level: " + cat.getCoverageTopologyLevel(covname)); - String fcsURL = buildURL(request, response, pathPrefix, "fcs?" + Data.RowSelectParam + "=" + Data.RowSelectAll, "fcs"); - list.addElement("Feature Class Schema: " + fcsURL); - CoverageTable ct = cat.getCoverageTable(covname); - // CoverageTable opens alot of files, go through and close - // them - for (Iterator i = ct.getFeatureClasses().values().iterator(); i.hasNext();) { - FeatureClassInfo fci = (FeatureClassInfo) i.next(); - fci.close(); - } - - Map ftypeinfo = new TreeMap(ct.getFeatureTypeInfo()); - if (ftypeinfo.size() == 0) { - list.addElement("No Feature Types in FCA"); - } else { - HtmlListElement flist = - new HtmlListElement("Feature Types (from " + buildURL(request, response, pathPrefix, "fca") + ")"); - list.addElement(flist); - for (Iterator i = ftypeinfo.values().iterator(); i.hasNext();) { - CoverageTable.FeatureClassRec fcr = (CoverageTable.FeatureClassRec) i.next(); - String name = fcr.feature_class.toLowerCase(); - // char t = fcr.type; - String desc = fcr.description; - String tstring = "[unknown] "; - String suffix = ""; - switch (fcr.type) { - case CoverageTable.TEXT_FEATURETYPE: - tstring = "[text feature] "; - suffix = ".tft"; - break; - case CoverageTable.EDGE_FEATURETYPE: - tstring = "[edge feature] "; - suffix = ".lft"; - break; - case CoverageTable.AREA_FEATURETYPE: - tstring = "[area feature] "; - suffix = ".aft"; - break; - case CoverageTable.UPOINT_FEATURETYPE: - FeatureClassInfo fci = ct.getFeatureClassInfo(name); - char type = (fci != null) ? fci.getFeatureType() : CoverageTable.SKIP_FEATURETYPE; - if (type == CoverageTable.EPOINT_FEATURETYPE) { - tstring = "[entity point feature] "; - } else if (type == CoverageTable.CPOINT_FEATURETYPE) { - tstring = "[connected point feature] "; - } else { - tstring = "[missing point feature] "; - } - suffix = ".pft"; - break; - case CoverageTable.COMPLEX_FEATURETYPE: - tstring = "[complex feature] "; - suffix = ".cft"; - break; - default: - tstring = "[unknown] "; - suffix = ""; - } - String url = buildURL(request, response, pathPrefix, name + suffix, name); - flist.addElement(url + ": " + tstring + desc); - } - } - try { - HtmlListElement flist = new HtmlListElement("Feature Types (from " + fcsURL + ")"); - boolean generateflist = false; - DcwRecordFile fcs = new DcwRecordFile(ct.getDataPath() + File.separator + "fcs" + (ct.appendDot ? "." : "")); - int featureClassColumn = fcs.whatColumn("feature_class"); - int table1Column = fcs.whatColumn("table1"); - // int table1_keyColumn = fcs.whatColumn("table1_key"); - // int table2Column = fcs.whatColumn("table2"); - // int table2_keyColumn = fcs.whatColumn("table2_key"); - - List fcsl = new ArrayList(fcs.getColumnCount()); - while (fcs.parseRow(fcsl)) { - String featureclass = ((String) fcsl.get(featureClassColumn)).toLowerCase(); - String table1 = ((String) fcsl.get(table1Column)).toLowerCase(); - if (!ftypeinfo.containsKey(featureclass)) { - ftypeinfo.put(featureclass, null); - String type = null; - if (table1.endsWith(".cft")) { - type = "complex feature"; - } else if (table1.endsWith(".pft")) { - type = "point feature"; - } else if (table1.endsWith(".lft")) { - type = "line feature"; - } else if (table1.endsWith(".aft")) { - type = "area feature"; - } else if (table1.endsWith(".tft")) { - type = "text feature"; - } - if (type != null) { - generateflist = true; - flist.addElement(type + " " + buildURL(request, response, pathPrefix, table1, featureclass)); - } - } - } - if (generateflist) { - list.addElement(flist); - } - fcs.close(); - } catch (FormatException fe) { - list.addElement("no fcs"); - } - list.generate(out); - } - - public LibrarySelectionTable getLST(String libname) - throws FormatException { - LibrarySelectionTable lst = contextInfo.getLST(libname); - if (lst == null) { - String lib_home = contextInfo.getPath(libname); - if (lib_home == null) { - return null; - } - // File flib_home = new File(lib_home); - - lst = new LibrarySelectionTable(lib_home); - contextInfo.putLST(libname, lst); - } - return lst; - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DetailRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DetailRowMaker.java deleted file mode 100644 index 2944a67b5..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DetailRowMaker.java +++ /dev/null @@ -1,247 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/DetailRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.Constants; -import com.bbn.openmap.layer.vpf.CoverageTable; -import com.bbn.openmap.layer.vpf.DcwColumnInfo; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker class that will perform VDT (value description table) - * lookups on selected columns in the table. - */ -public class DetailRowMaker extends PlainRowMaker { - final HashMap intvdt; - final HashMap charvdt; - final DcwColumnInfo dcia[]; - - /** - * Constructor - * - * @param drf the table being parsed - * @param markupCols the column names of the columns to attempt - * lookups for - */ - public DetailRowMaker(DcwRecordFile drf, String[] markupCols) { - File pfile = new File(drf.getTableFile()).getParentFile(); - String tableName = drf.getTableName(); - intvdt = loadIntVDT(pfile, tableName); - charvdt = loadCharVDT(pfile, tableName); - DcwColumnInfo dc[] = drf.getColumnInfo(); - if (markupCols == null) { - dcia = dc; - } else { - dcia = new DcwColumnInfo[dc.length]; - for (int i = 0; i < markupCols.length; i++) { - int col = drf.whatColumn(markupCols[i]); - if (col != -1) { - dcia[col] = dc[col]; - } - } - } - } - - public void addToRow(TableRowElement row, List l) { - int i = 0; - for (Iterator vals = l.listIterator(); vals.hasNext();) { - Object rval = vals.next(); - String vdt = (dcia[i] != null) ? dcia[i].getVDT() : null; - if (vdt == null) { - row.addElement(rval.toString()); - } else if (Constants.intVDTTableName.equals(vdt) - && (rval instanceof Number)) { - int val = ((Number) rval).intValue(); - CoverageIntVdt civ = new CoverageIntVdt(dcia[i].getColumnName(), val); - String lval = (String) intvdt.get(civ); - row.addElement((lval == null) ? ("[" + val + "]") : lval); - } else if (Constants.charVDTTableName.equals(vdt) - && (rval instanceof String)) { - String val = (String) rval; - CoverageCharVdt civ = new CoverageCharVdt(dcia[i].getColumnName(), val); - String lval = (String) charvdt.get(civ); - row.addElement((lval == null) ? ("[" + val + "]") : lval); - } else { - row.addElement("Table Data Error!"); - } - i++; - } - } - - private HashMap loadIntVDT(File path, String tableName) { - HashMap hm = new HashMap(); - try { - File vdt = new File(path, Constants.intVDTTableName); - if (vdt.canRead()) { - DcwRecordFile intvdt = new DcwRecordFile(vdt.toString()); - int intcols[] = intvdt.lookupSchema(CoverageTable.VDTColumnNames, - true, - CoverageTable.intVDTschematype, - CoverageTable.intVDTschemalength, - false); - - List al = new ArrayList(intvdt.getColumnCount()); - while (intvdt.parseRow(al)) { - String tab = (String) al.get(intcols[0]); - if (!tableName.equalsIgnoreCase(tab)) { - continue; - } - String attr = (String) al.get(intcols[1]); - int val = ((Number) al.get(intcols[2])).intValue(); - String desc = ((String) al.get(intcols[3])).intern(); - hm.put(new CoverageIntVdt(attr, val), desc); - } - intvdt.close(); - } - } catch (FormatException f) { - } - return hm; - } - - private HashMap loadCharVDT(File path, String tableName) { - HashMap hm = new HashMap(); - try { - File vdt = new File(path, Constants.charVDTTableName); - if (vdt.canRead()) { - DcwRecordFile charvdt = new DcwRecordFile(vdt.toString()); - int charcols[] = charvdt.lookupSchema(CoverageTable.VDTColumnNames, - true, - CoverageTable.charVDTschematype, - CoverageTable.charVDTschemalength, - false); - - ArrayList al = new ArrayList(charvdt.getColumnCount()); - while (charvdt.parseRow(al)) { - String tab = (String) al.get(charcols[0]); - if (!tableName.equalsIgnoreCase(tab)) { - continue; - } - String attr = (String) al.get(charcols[1]); - String val = (String) al.get(charcols[2]); - String desc = ((String) al.get(charcols[3])).intern(); - hm.put(new CoverageCharVdt(attr, val), desc); - } - charvdt.close(); - } - } catch (FormatException f) { - } - return hm; - } -} - -/** - * A utility class used to map information from a VPF feature table to - * its associated value in an int.vdt file. - */ -class CoverageIntVdt { - /** - * the name of the attribute we are looking up (attribute is - * interned) - */ - final String attribute; - /** the integer value we are looking up */ - final int value; - - /** - * Construct a new object - * - * @param a the value for the attribute member - * @param v the value for the value member - */ - public CoverageIntVdt(String a, int v) { - attribute = a.toLowerCase().intern(); - value = v; - } - - /** - * Override the equals method. Two CoverageIntVdts are equal if - * and only iff their respective attribute and value members are - * equal. - */ - public boolean equals(Object o) { - if (o instanceof CoverageIntVdt) { - CoverageIntVdt civ = (CoverageIntVdt) o; - // we can use == rather than String.equals(String) since - // attribute is interned. - return ((attribute == civ.attribute) && (value == civ.value)); - } else { - return false; - } - } - - /** - * Override hashcode. Compute a hashcode based on our member - * values, rather than our (base class) object identity. - */ - public int hashCode() { - return (attribute.hashCode() ^ value); - } -} - -/** - * A utility class used to map information from a VPF feature table to - * its associated value in an char.vdt file. - */ -class CoverageCharVdt { - /** - * the name of the attribute we are looking up (attribute is - * interned) - */ - final String attribute; - /** the character value we are looking up (value is interned) */ - final String value; - - /** - * Construct a new object - * - * @param a the value for the attribute member - * @param v the value for the value member - */ - public CoverageCharVdt(String a, String v) { - attribute = a.toLowerCase().intern(); - value = v.intern(); - } - - /** - * Override the equals method. Two CoverageIntVdts are equal if - * and only iff their respective attribute and value members are - * equal. - */ - public boolean equals(Object o) { - if (o instanceof CoverageCharVdt) { - CoverageCharVdt civ = (CoverageCharVdt) o; - // we can use == rather than String.equals(String) since - // attribute, and value are interned. - return ((attribute == civ.attribute) && (value == civ.value)); - } else { - return false; - } - } - - /** - * Override hashcode. Compute a hashcode based on our member - * values, rather than our (base class) object identity. - */ - public int hashCode() { - return (attribute.hashCode() ^ value.hashCode()); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DirectoryServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DirectoryServlet.java deleted file mode 100644 index c719e823d..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DirectoryServlet.java +++ /dev/null @@ -1,124 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/DirectoryServlet.java,v $ -// $Revision: 1.5 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.util.html.HtmlListElement; - -/** - * This servlet lists the files in a directory of a configured VPF database. - * Directory listing can be disabled, see the listDirectories servlet parameter - * in the deployment descriptor. (web.xml) - */ -public class DirectoryServlet - extends VPFHttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public DirectoryServlet() { - super(); - } - - /** - * false if this servlet should generate a "disabled by administrator" - * method rather than a directory list. - */ - private boolean listFiles; - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String filePath = (String) request.getAttribute(DispatchServlet.ROOTPATH_FILENAME); - if (filePath == null) { - String path = setPathInfo(request); - filePath = contextInfo.resolvePath(path); - if (!pathOkay(filePath, path, response)) { - return; - } - } - File fp = new File(filePath); - String pathInfo = getPathInfo(request); - - PrintWriter out = response.getWriter(); - - String filename = fp.getName().toLowerCase(); - - // This was never used!!! - String end = ""; - - response.setContentType("text/html"); - out.println(HTML_DOCTYPE + "\n" + filename + "\r\n\r\n

Directory " + filename - + "

\r\n"); - out.println(getStylesheetHTML(request)); - - if (!listFiles) { - out.println("Directory listing disabled by administrator."); - } else if (!fp.isDirectory()) { - out.println("Requested path is not a directory."); - } else { - out.println(""); - File files[] = fp.listFiles(); - ArrayList filenames = new ArrayList(); - ArrayList directories = new ArrayList(); - for (int i = 0; i < files.length; i++) { - String name = files[i].getName(); - if (files[i].isDirectory()) { - directories.add(name); - } else { - filenames.add(name); - } - } - Collections.sort(directories); - Collections.sort(filenames); - - if (!pathInfo.endsWith("/")) { - pathInfo += '/'; - } - - HtmlListElement filelist = new HtmlListElement("Sub-Directories"); - - for (Iterator dir = directories.iterator(); dir.hasNext();) { - String url = fileURL(request, response, pathInfo, (String) dir.next()); - filelist.addElement(url); - } - filelist.generate(out); - - filelist = new HtmlListElement("Files"); - for (Iterator file = filenames.iterator(); file.hasNext();) { - String url = fileURL(request, response, pathInfo, (String) file.next()); - filelist.addElement(url); - } - filelist.generate(out); - } - out.println(end); - } - - public void init(ServletConfig config) - throws ServletException { - super.init(config); - listFiles = Boolean.valueOf(config.getInitParameter("listDirectories")).booleanValue(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DispatchServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DispatchServlet.java deleted file mode 100644 index 293e2d8d0..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DispatchServlet.java +++ /dev/null @@ -1,120 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/DispatchServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; - -/** - * This class infers the format of a VPF file from the name of the file, and - * dispatches to the appropriate servlet for that type. - * - * This could probably also be handled by a long set of servlet-mapping tags in - * the deployment descriptor. (web.xml) - */ -public class DispatchServlet - extends VPFHttpServlet { - public static final String RECORD_FILE_OBJ = "com.bbn.openmap.vpf_tools.table_obj"; - public static final String ROOTPATH_FILENAME = "com.bbn.openmap.vpf_tools.url_path"; - - /** - * A do-nothing constructor - init does all the work. - */ - public DispatchServlet() { - super(); - } - - /** - * Just a test main to parse vpf datafiles - * - * param args files to parse, plus other command line flags - */ - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String pathInfo = setPathInfo(request); - String rootpath = contextInfo.resolvePath(pathInfo); - if (!pathOkay(rootpath, pathInfo, response)) { - return; - } - - PrintWriter out = response.getWriter(); - File rp = new File(rootpath); - String filename = rp.getName().toLowerCase(); - - String end = "\r\n"; - - // ByteArrayOutputStream bos = new ByteArrayOutputStream(); - // PrintStream s = new PrintStream(bos); - // System.setOut(s); - - request.setAttribute(ROOTPATH_FILENAME, rootpath); - - try { - if (rp.isDirectory()) { - RequestDispatcher rd = request.getRequestDispatcher("/DirectoryList"); - rd.forward(request, response); - return; - } else if (filename.endsWith("x") || filename.endsWith("x.")) { - response.setContentType("text/html"); - out.println(HTML_DOCTYPE + "" + filename + "\r\n\r\n

Table " + filename - + "

\r\n"); - out.println(getStylesheetHTML(request)); - out.println("Skipping VLI format - this format is simply an index to find rows in a corresponding table file, it isn't very interesting to look at so its getting skipped."); - } else if (filename.endsWith("ti")) { - RequestDispatcher rd = request.getRequestDispatcher("/Thematic"); - rd.forward(request, response); - } else if (filename.endsWith("si") || filename.endsWith("si.")) { - RequestDispatcher rd = request.getRequestDispatcher("/SpatialIndex"); - rd.forward(request, response); - } else if (filename.endsWith(".doc")) { - RequestDispatcher rd = request.getRequestDispatcher("/DocFile"); - rd.forward(request, response); - } else { - response.setContentType("text/html"); - out.println(HTML_DOCTYPE + "\n" + filename + "\r\n\r\n

Table " - + filename + "

\r\n"); - out.println(getStylesheetHTML(request)); - DcwRecordFile foo = new DcwRecordFile(rootpath); - request.setAttribute(RECORD_FILE_OBJ, foo); - RequestDispatcher rd = request.getRequestDispatcher("/Schema"); - rd.include(request, response); - RequestDispatcher rd2 = request.getRequestDispatcher("/Data"); - rd2.include(request, response); - - foo.close(); - } - } catch (FormatException f) { - throw new ServletException("Format Error: ", f); - } - // s.close(); - out.println("
");
-        out.println("Context Path: " + request.getContextPath());
-        out.println("PathInfo: " + request.getPathInfo());
-        out.println("ServletPath: " + request.getServletPath());
-        out.println("Query String: " + request.getQueryString());
-        // out.print(bos.toString());
-        out.println("
" + end); - } - -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DocFileServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DocFileServlet.java deleted file mode 100644 index dca4f3c08..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/DocFileServlet.java +++ /dev/null @@ -1,109 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/DocFileServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; - -/** - * This class handles displaying VPF .doc files - */ -public class DocFileServlet - extends VPFHttpServlet { - /** the columns we need from a VPF doc file */ - static final String FieldColumns[] = { - "text" - }; - /** the fields in a VPF doc file we need */ - static final char[] FieldTypeSchema = { - 'T' - }; - /** the field lengths in a VPF doc file we need */ - static final int[] FieldLengthSchema = { - -1 - }; - - /** - * A do-nothing constructor - init does all the work. - */ - public DocFileServlet() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String filePath = (String) request.getAttribute(DispatchServlet.ROOTPATH_FILENAME); - if (filePath == null) { - String pathInfo = setPathInfo(request); - filePath = contextInfo.resolvePath(pathInfo); - if (!pathOkay(filePath, pathInfo, response)) { - return; - } - } - - DcwRecordFile docfile = null; - try { - docfile = new DcwRecordFile(filePath); - } catch (FormatException fe) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, " docfile not found"); - return; - } - - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.println(HTML_DOCTYPE); - out.println(getStylesheetHTML(request)); - - String tableName = docfile.getTableName(); - out.println(""); - String title = "VPF Documentation File " + tableName; - out.println("" + title + ""); - out.println("

" + title + "

"); - - try { - docfile.lookupSchema(FieldColumns, true, FieldTypeSchema, FieldLengthSchema, false); - } catch (FormatException fe) { - out.println("The documentation file appears to be invalid."); - RequestDispatcher rd = request.getRequestDispatcher("/Schema"); - rd.include(request, response); - out.println(""); - docfile.close(); - return; - } - - ArrayList al = new ArrayList(FieldTypeSchema.length); - out.println("
");
-        try {
-            while (docfile.parseRow(al)) {
-                out.println("   " + al.get(1).toString());
-            }
-            out.println("
"); - } catch (FormatException fe) { - out.println("/pre>"); - out.println("File Format Exception processing data: " + fe); - } - out.println(""); - docfile.close(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FCSRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FCSRowMaker.java deleted file mode 100644 index fe15bd797..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FCSRowMaker.java +++ /dev/null @@ -1,97 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/FCSRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.layer.vpf.Constants; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker class specifically for the markup of VPF feature class schema - * (fcs) files. - */ -public class FCSRowMaker extends ReferenceRowMaker { - /** the length of a row (number of columns) */ - final int rowLen; - /** the directory of the file being read */ - final File drfp; - final String basepath; - final int idCol; - final int featureClassCol; - final int table1Col; - final int table1keyCol; - final int table2Col; - final int table2keyCol; - - public FCSRowMaker(HttpServletRequest request, - HttpServletResponse response, - String basepath, DcwRecordFile drf) { - super(request, response); - this.rowLen = drf.getColumnCount(); - this.basepath = basepath; - this.drfp = new File(drf.getTableFile()).getParentFile(); - idCol = drf.whatColumn(Constants.ID); - featureClassCol = drf.whatColumn(Constants.FCS_FEATURECLASS); - table1Col = drf.whatColumn(Constants.FCS_TABLE1); - table1keyCol = drf.whatColumn(Constants.FCS_TABLE1KEY); - table2Col = drf.whatColumn(Constants.FCS_TABLE2); - table2keyCol = drf.whatColumn(Constants.FCS_TABLE2KEY); - } - - public void addToRow(TableRowElement row, List l) { - int rv = ((Number)l.get(idCol)).intValue(); - String table1 = ((String)l.get(table1Col)).toLowerCase(); - String table1key = ((String)l.get(table1keyCol)).toLowerCase(); - String table2 = ((String)l.get(table2Col)).toLowerCase(); - String table2key = ((String)l.get(table2keyCol)).toLowerCase(); - File fn = new File(drfp, table1); - File otf = new File(drfp, table2); - boolean tiled = !otf.exists(); - for (int i = 0; i < rowLen; i++) { - if (i == idCol) { - if (fn.exists()) { - row.addElement(Data.joinURL(request, response, - rv, table1, - table1key, table2, - table2key, - tiled)); - } else { - row.addElement(Integer.toString(rv)); - } - } else if ((i==table1Col) || (i==table2Col)) { - String tablename = ((String)l.get(i)).toLowerCase(); - if (new File(drfp, tablename).exists()) { - row.addElement(fileURL(basepath, tablename)); -// } else if (Constants.endTableName.equals(tablename) || -// Constants.cndTableName.equals(tablename) || -// Constants.faceTableName.equals(tablename) || -// "edg".equals(tablename) || -// "txt".equals(tablename)) { -// TileHolder ta = new TileHolder(new File(basepath), tablename, true); -// row.addElement(tablename); - } else { - row.addElement(tablename); - } - } else { - row.addElement(l.get(i).toString().toLowerCase()); - } - } - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FITRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FITRowMaker.java deleted file mode 100644 index 98c9af09e..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/FITRowMaker.java +++ /dev/null @@ -1,167 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/FITRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.VPFUtil; -import com.bbn.openmap.util.html.TableDataElement; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker that performs the join in a feature index table. - */ -public class FITRowMaker extends PlainRowMaker { - /** a list reused to load primitive rows */ - final List primRow = new ArrayList(); - /** a list reused to load feature rows */ - final List featureRow = new ArrayList(); - - /** the array of feature tables, each index is lazy-initialized */ - final DcwRecordFile[] featureTables; - /** the array of feature names for the coverage */ - final String[] featureNames; - - /** the utility class that understands tiled and untiled data */ - final TileHolder tiler; - - /** the column in the FIT that specifies the primitive id */ - final int primIdColumn; - /** the column in the FIT that specifies the tile id (may be -1) */ - final int tileIdColumn; - /** the column in the FIT that specifies the feature class id */ - final int fcIdColumn; - /** the column in the FIT that specifies the feature id */ - final int featureIdColumn; - /** the path for the coverage */ - final File dirPath; - /** the extension (e.g. .lft) used for feature table names */ - final String featureTableExt; - - /** - * Construct a rowmaker for a feature index table. - * - * @param drf the feature index table - * @throws FormatException some error was encountered - */ - public FITRowMaker(DcwRecordFile drf) throws FormatException { - String tableName = drf.getTableName().substring(0, 3); - dirPath = new File(drf.getTableFile()).getParentFile(); - - featureTableExt = getExtensionForTable(tableName); - - primIdColumn = drf.whatColumn("prim_id"); - tileIdColumn = drf.whatColumn("tile_id"); - fcIdColumn = drf.whatColumn("fc_id"); - featureIdColumn = drf.whatColumn("feature_id"); - - tiler = new TileHolder(dirPath, tableName, (tileIdColumn != -1)); - featureNames = getFeatureNames(dirPath); - featureTables = new DcwRecordFile[featureNames.length]; - } - - /** - * Returns the feature table that corresponds to the feature class - * ID. - * - * @param fcId the feature class ID - * @return the feature table - * @throws FormatException the feature table couldn't be created - */ - public DcwRecordFile getFeatureTable(int fcId) throws FormatException { - fcId -= 1; // array is 0-based, table ids are 1-based - DcwRecordFile retval = featureTables[fcId]; - if (retval == null) { - retval = new DcwRecordFile(dirPath + File.separator - + featureNames[fcId].toLowerCase() + featureTableExt); - featureTables[fcId] = retval; - } - return retval; - } - - public void addToRow(TableRowElement row, List l) { - int primId = VPFUtil.objectToInt(l.get(primIdColumn)); - int tileId = (tileIdColumn == -1) ? -1 - : VPFUtil.objectToInt(l.get(tileIdColumn)); - int fcId = VPFUtil.objectToInt(l.get(fcIdColumn)); - int featureId = VPFUtil.objectToInt(l.get(featureIdColumn)); - int id = VPFUtil.objectToInt(l.get(0)); - row.addElement("" + id + " (" + tileId + "," + primId + ") (" + fcId - + ", " + featureId + ")"); - try { - tiler.getRow(tileId, primId, primRow); - DcwRecordFile featureTable = getFeatureTable(fcId); - featureTable.getRow(featureRow, featureId); - for (Iterator i = primRow.iterator(); i.hasNext();) { - row.addElement(new TableDataElement("CLASS=JoinColumn", i.next() - .toString())); - } - for (Iterator i = featureRow.iterator(); i.hasNext();) { - row.addElement(new TableDataElement("CLASS=Join2Column", i.next() - .toString())); - } - } catch (FormatException fe) { - row.addElement(fe.toString()); - } - } - - public String[] getFeatureNames(File dirPath) throws FormatException { - File fcafile = new File(dirPath, "fca"); - if (!fcafile.canRead()) { - fcafile = new File(dirPath, "fca."); - } - DcwRecordFile fca = new DcwRecordFile(fcafile.toString()); - List l = new ArrayList(fca.getColumnCount()); - int fclassColumn = fca.whatColumn("fclass"); - List fclassnames = new ArrayList(); - while (fca.parseRow(l)) { - fclassnames.add(l.get(fclassColumn)); - } - fca.close(); - String retval[] = new String[fclassnames.size()]; - fclassnames.toArray(retval); - return retval; - } - - public static String getExtensionForTable(String tablename) { - - if (tablename.equals("fac")) { - return ".aft"; - } else if (tablename.equals("cnd")) { - return ".pft"; - } else if (tablename.equals("end")) { - return ".pft"; - } else if (tablename.equals("txt")) { - return ".tft"; - } else if (tablename.equals("edg")) { - return ".lft"; - } - return null; - } - - public void close() { - tiler.close(); - for (int i = 0; i < featureTables.length; i++) { - DcwRecordFile drf = featureTables[i]; - if (drf != null) { - drf.close(); - } - } - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/HelloWWW.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/HelloWWW.java deleted file mode 100644 index 1991fa7c5..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/HelloWWW.java +++ /dev/null @@ -1,36 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/HelloWWW.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Test class, not used - */ -public class HelloWWW extends HttpServlet { - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.setContentType("text/html"); - PrintWriter out = resp.getWriter(); - String docType = "\n"; - out.println(docType - + "\nHello WWW\n\n

Hello WWW

\n\n"); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/JoinRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/JoinRowMaker.java deleted file mode 100644 index f84fba926..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/JoinRowMaker.java +++ /dev/null @@ -1,83 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/JoinRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.FeatureClassInfo; -import com.bbn.openmap.layer.vpf.TilingAdapter; -import com.bbn.openmap.util.html.TableDataElement; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker subclass that handles simple joins between tables. - */ -public class JoinRowMaker extends PlainRowMaker { - /** the column that contains the foreign key to the primitive table */ - final int theColumn; - /** the column that contains the tile identifier */ - final int tileColumn; - /** a list reused to load primitive rows */ - final List jtrow = new ArrayList(); - - /** the utility class that understands tiled and untiled data */ - final TileHolder tiler; - final TilingAdapter ta; - - public JoinRowMaker(DcwRecordFile table, String joinColumnName, - String tableName, boolean isTiled) throws FormatException { - theColumn = table.whatColumn(joinColumnName); - tileColumn = isTiled ? table.whatColumn(FeatureClassInfo.TILE_ID_COLUMN_NAME) - : -1; - ta = table.getTilingAdapter(tileColumn, theColumn); - tiler = new TileHolder(new File(table.getTableFile()).getParentFile(), tableName, isTiled); - } - - public void addToRow(TableRowElement row, List l) { - int i = 0; - for (Iterator li = l.iterator(); li.hasNext();) { - Object elt = li.next(); - if (i == theColumn) { - int whatrow = ta.getTilePrimId(l); - int tileId = ta.getTileId(l); - try { - if (tiler.getRow(ta, l, jtrow)) { - for (Iterator it = jtrow.iterator(); it.hasNext();) { - row.addElement(new TableDataElement("CLASS=JoinColumn", it.next() - .toString())); - } - } else { - row.addElement("Join failed! [" + elt + "]" + "(" - + tileId + "," + whatrow + ")"); - } - } catch (FormatException fe) { - row.addElement(fe.toString() + "(" + tileId + "," + whatrow - + ")"); - } - } else { - row.addElement(elt.toString()); - } - i++; - } - } - - public void close() { - tiler.close(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/LibraryBean.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/LibraryBean.java deleted file mode 100644 index 7ceb6f2b5..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/LibraryBean.java +++ /dev/null @@ -1,128 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/LibraryBean.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.LibrarySelectionTable; - -/** - * This class prints out a description of a VPF database, listing the - * available libraries, coverage types and feature types. - */ -public class LibraryBean { - private LibrarySelectionTable lst; - private HttpServletRequest request; - private HttpServletResponse response; - - public void setContext(ServletContext c) { - contextInfo = ContextInfo.getContextInfo(c); - } - - public void setResponse(HttpServletResponse r) { - response = r; - } - - public HttpServletRequest getRequest() { - return request; - } - - public void setRequest(HttpServletRequest request) { - this.request = request; - } - - public HttpServletResponse getResponse() { - return response; - } - - public LibrarySelectionTable getLst() { - return lst; - } - - public String getLibName() { - return (lst == null) ? "unknown" : lst.getDatabaseName(); - } - - public void setPath(String pathInfo) { - if (pathInfo == null) { - return; - } - int findex = pathInfo.indexOf('/', 1); - if (findex < 0) { - findex = pathInfo.length(); - } - String libname = pathInfo.substring(0, findex); - - try { - lst = getLST(libname); - if (lst == null) { - return; - } - // String dbname = lst.getDatabaseName(); - // out.println("\nDescribe VPF Database - // " + - // dbname + "\n\n

VPF Database " + - // dbname + "

\n"); - // ListElement dble = new ListBodyElement(); - // WrapElement dblist = new WrapElement("ul", dble); - // dble.addElement("Database Description: " + - // lst.getDatabaseDescription()); - // dble.addElement("Database Description Table: " + - // buildURL(request, response, libname, "dht")); - // String[] libraries = lst.getLibraryNames(); - // StringBuffer libnames = new StringBuffer("Database - // Libraries: "); - // for (int i = 0; i < libraries.length; i++) { - // libnames.append("").append(libraries[i]); - // libnames.append("").append(" "); - // } - // libnames.append("(from "); - // libnames.append(buildURL(request, response, libname, - // "lat")); - // libnames.append(")"); - - // dble.addElement(libnames.toString()); - // dblist.generate(out); - // for (int i = 0; i < libraries.length; i++) { - // String prefix = libraries[i] + ":"; - // printLibrary(request, response, libname, - // lst.getCAT(libraries[i])); - // } - // out.println(""); - } catch (FormatException fe) { - // throw new ServletException("FormatException: " , fe); - } - } - - /** the context object used for config info */ - protected ContextInfo contextInfo; - - public LibrarySelectionTable getLST(String libname) throws FormatException { - LibrarySelectionTable lst = contextInfo.getLST(libname); - if (lst == null) { - String lib_home = contextInfo.getPath(libname); - if (lib_home == null) { - return null; - } - - lst = new LibrarySelectionTable(lib_home); - contextInfo.putLST(libname, lst); - } - return lst; - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/PlainRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/PlainRowMaker.java deleted file mode 100644 index 38a90137a..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/PlainRowMaker.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/PlainRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A basic RowMaker that makes rows. - */ -public class PlainRowMaker implements RowMaker { - - /** - * A basic constructor that doesn't do anything special. - */ - public PlainRowMaker() {} - - /** - * Generates a TableRowElement from a table by creating a new - * TableRow and passing it and the list to addToRow, then - * returning the new row. - * - * @param l the VPF table row - * @return a HTML representation of the VPF row - */ - public TableRowElement generateRow(List l) { - TableRowElement tr = new TableRowElement(); - addToRow(tr, l); - return tr; - } - - /** - * Adds the elements of the list to the table row - * - * @param row the HTML row - * @param l the VPF row - */ - public void addToRow(TableRowElement row, List l) { - for (Iterator li = l.iterator(); li.hasNext();) { - row.addElement(li.next().toString()); - } - } - - /** - * An empty implementation, since this class doesn't hold any - * resources. - */ - public void close() {} -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ReferenceRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ReferenceRowMaker.java deleted file mode 100644 index 2e1703bb6..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ReferenceRowMaker.java +++ /dev/null @@ -1,46 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ReferenceRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * A RowMaker class that retains references to the HttpServletRequest - * and HttpServletResponse instances of the request. - */ -public abstract class ReferenceRowMaker extends PlainRowMaker { - /** the servlet request object */ - final protected HttpServletRequest request; - /** the servlet response object */ - final protected HttpServletResponse response; - - public ReferenceRowMaker(HttpServletRequest request, - HttpServletResponse response) { - this.request = request; - this.response = response; - } - - public String toURL(String servletName, String pathname, String filename) { - return VPFHttpServlet.toURL(request, - response, - servletName, - pathname, - filename); - } - - public String fileURL(String pathname, String filename) { - return VPFHttpServlet.fileURL(request, response, pathname, filename); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/RowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/RowMaker.java deleted file mode 100644 index b4322b8d0..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/RowMaker.java +++ /dev/null @@ -1,39 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/RowMaker.java,v $ -// $Revision: 1.3 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.util.List; - -import com.bbn.openmap.util.html.TableRowElement; - -/** - * An interface used to generate rows of an (html) table from a (VPF) - * table. - */ -public interface RowMaker { - /** - * Generate an HTML table row from a vpf table row - * - * @param row the VPF table row - * @return the HTML representation - */ - public TableRowElement generateRow(List row); - - /** - * Used to indicate that no more calls to addList will be made. - * (implementation may want to reclaim resources without waiting - * for the finalizer to run.) - */ - public void close(); -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Schema.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Schema.java deleted file mode 100644 index 56065a281..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/Schema.java +++ /dev/null @@ -1,126 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/Schema.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.layer.vpf.DcwColumnInfo; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.util.html.HtmlListElement; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.StringElement; -import com.bbn.openmap.util.html.TableRowElement; -import com.bbn.openmap.util.html.WrapElement; - -/** - * A servlet class that will print the schema for a VPF table. - */ -public class Schema extends VPFHttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public Schema() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - DcwRecordFile foo = (DcwRecordFile) request.getAttribute(DispatchServlet.RECORD_FILE_OBJ); - if (foo == null) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - String basepath = getRootDir(request); - String url = response.encodeURL(request.getContextPath() - + "/VPFHelp.jsp?topic=table_schema"); - PrintWriter out = response.getWriter(); - out.println("

Table Schema

"); - out.println("

General Table Information

"); - HtmlListElement list = new HtmlListElement(); - list.addElement("Table Name: " + foo.getTableName()); - list.addElement("Table Description: " + foo.getDescription()); - list.addElement("DocFile Name: " - + fileURL(request, - response, - basepath, - foo.getDocumentationFilename())); - int reclen = foo.getRecordLength(); - String reclenstr = (reclen == -1) ? ("variable") - : (Integer.toString(reclen) + " bytes"); - list.addElement("Record Length: " + reclenstr); - try { - list.addElement("Record Count: " + foo.getRecordCount()); - } catch (com.bbn.openmap.io.FormatException fe) { - list.addElement("Record Count Error: " + fe.toString()); - } - list.generate(out); - - // out.println("

Column Schema

"); - ListElement rows = new ListElement(); - WrapElement table = new WrapElement("table", "BORDER=1", rows); - TableRowElement thr = new TableRowElement(); - rows.addElement(new WrapElement("CAPTION", new StringElement("Column Schema"))); - rows.addElement(thr); - thr.addElement(THE("#", url)); - thr.addElement(THE("Name", url)); - thr.addElement(THE("Type", url)); - thr.addElement(THE("Count", url)); - thr.addElement(THE("Key Type", url)); - thr.addElement(THE("Description", url)); - thr.addElement(THE("VDT", url)); - thr.addElement(THE("Thematic Index", url)); - thr.addElement(THE("DocFile", url)); - DcwColumnInfo dci[] = foo.getColumnInfo(); - for (int i = 0; i < dci.length; i++) { - TableRowElement tr = new TableRowElement(); - rows.addElement(tr); - tr.addElement(Integer.toString(i)); - tr.addElement(dci[i].getColumnName()); - tr.addElement(String.valueOf(dci[i].getFieldType())); - int elts = dci[i].getNumberOfElements(); - tr.addElement(elts == -1 ? "*" : Integer.toString(elts)); - tr.addElement(String.valueOf(dci[i].getKeyType())); - tr.addElement(dci[i].getColumnDescription()); - tr.addElement(fileURL(request, response, basepath, dci[i].getVDT())); - tr.addElement(thematicURL(request, - response, - basepath, - dci[i].getThematicIndexName())); - tr.addElement(docURL(request, - response, - basepath, - dci[i].getNarrativeTable())); - } - table.generate(response.getWriter()); - } - - public static String thematicURL(HttpServletRequest request, - HttpServletResponse response, - String pathname, String filename) { - return toURL(request, response, "/Thematic", pathname, filename); - } - - public static String docURL(HttpServletRequest request, - HttpServletResponse response, String pathname, - String filename) { - return toURL(request, response, "/DocFile", pathname, filename); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialGraphicServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialGraphicServlet.java deleted file mode 100644 index f0b402a1b..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialGraphicServlet.java +++ /dev/null @@ -1,177 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/SpatialGraphicServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.HashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwSpatialIndex; -import com.bbn.openmap.util.html.HtmlListElement; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.TableHeaderElement; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * This servlet generates HTML for VPF files in spatial index format. - */ -public class SpatialGraphicServlet extends VPFHttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public SpatialGraphicServlet() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String filePath = (String) request.getAttribute(DispatchServlet.ROOTPATH_FILENAME); - if (filePath == null) { - String pathInfo = setPathInfo(request); - filePath = contextInfo.resolvePath(pathInfo); - if (!pathOkay(filePath, pathInfo, response)) { - return; - } - } - - response.setContentType("image/gif"); - - int width = 200; - int height = 200; - int imageType = BufferedImage.TYPE_INT_ARGB; - BufferedImage bufferedImage = new BufferedImage(width, height, imageType); - Graphics2D g2d = bufferedImage.createGraphics(); - g2d.setClip(0, 0, width, height); - g2d.setColor(Color.red); - g2d.drawLine(10, 10, 95, 95); - g2d.drawLine(105, 105, 190, 190); - g2d.drawRect(1, 1, 198, 198); - g2d.dispose(); - // byte [] imageData = AcmeGifHelper.encodeGif(bufferedImage); - - // ServletOutputStream sos = response.getOutputStream(); - // sos.write(imageData); - - String filename = filePath; - String tableMatch = getIndexedTable(filename); - if (tableMatch == null) { - tableMatch = "non-standard spatial index"; - } else { - tableMatch = fileURL(request, - response, - getRootDir(request), - tableMatch); - } - - try { - DcwSpatialIndex ff = new DcwSpatialIndex(filePath.toString(), false); - printSpatial(request, response, ff); - ff.close(); - } catch (FormatException fe) { - } - } - - public void printSpatial(HttpServletRequest request, - HttpServletResponse response, DcwSpatialIndex si) - throws com.bbn.openmap.io.FormatException, IOException { - int width = 200; - int height = 200; - int imageType = BufferedImage.TYPE_INT_ARGB; - BufferedImage bufferedImage = new BufferedImage(width, height, imageType); - Graphics2D g2d = bufferedImage.createGraphics(); - g2d.setClip(0, 0, width, height); - g2d.setColor(Color.red); - g2d.drawLine(10, 10, 95, 95); - g2d.drawLine(105, 105, 190, 190); - g2d.drawRect(1, 1, 198, 198); - g2d.dispose(); - // byte [] imageData = AcmeGifHelper.encodeGif(bufferedImage); - - // ServletOutputStream sos = response.getOutputStream(); - // sos.write(imageData); - - HtmlListElement list = new HtmlListElement(); - list.addElement("Number Of Primitives: " + si.getNumberOfPrimitives()); - int nodesInTree = si.getNodesInTree(); - list.addElement("Nodes in Tree: " + nodesInTree); - list.addElement("Bounding Rectangle: (" + si.getBoundingX1() + ", " - + si.getBoundingY1() + ") - (" + si.getBoundingX2() + ", " - + si.getBoundingY2() + ")"); - TableRowElement columnNames = new TableRowElement(); - columnNames.addElement(new TableHeaderElement("Primitive ID")); - columnNames.addElement(new TableHeaderElement("x1")); - columnNames.addElement(new TableHeaderElement("x2")); - columnNames.addElement(new TableHeaderElement("y1")); - columnNames.addElement(new TableHeaderElement("y2")); - for (int i = 0; i < nodesInTree; i++) { - int count = si.getPrimitiveCount(i); - //int offset = si.getPrimitiveOffset(i); - DcwSpatialIndex.PrimitiveRecord pr[] = si.getPrimitiveRecords(i); - - if (count == 0) { - } else { - ListElement rows = new ListElement(); - //WrapElement table = new WrapElement("table", "BORDER=1", rows); - rows.addElement(columnNames); - for (int j = 0; j < pr.length; j++) { - DcwSpatialIndex.PrimitiveRecord pr1 = pr[j]; - TableRowElement datarow = new TableRowElement(); - rows.addElement(datarow); - datarow.addElement(Integer.toString(pr1.primId)); - datarow.addElement(Short.toString(pr1.x1)); - datarow.addElement(Short.toString(pr1.x2)); - datarow.addElement(Short.toString(pr1.y1)); - datarow.addElement(Short.toString(pr1.y2)); - } - } - } - } - - /** a map from spatial index name to primitive file indexed */ - private HashMap indexTableMap; - - /** - * Returns the name of the primitive file that the spatial index - * is for. - * - * @param indexName the name of the index - * @return the name of the primitive file - */ - public String getIndexedTable(String indexName) { - if (indexTableMap == null) { - HashMap newMap = new HashMap(); - newMap.put("esi", "edg"); - newMap.put("esi.", "edg."); - newMap.put("fsi", "fac"); - newMap.put("fsi.", "fac."); - newMap.put("csi", "cnd"); - newMap.put("csi.", "cnd."); - newMap.put("nsi", "end"); - newMap.put("nsi.", "end."); - newMap.put("tsi", "txt"); - newMap.put("tsi.", "txt."); - indexTableMap = newMap; - } - return (String) indexTableMap.get(indexName); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialIndexServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialIndexServlet.java deleted file mode 100644 index ddfc10526..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/SpatialIndexServlet.java +++ /dev/null @@ -1,165 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/SpatialIndexServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwSpatialIndex; -import com.bbn.openmap.util.html.HtmlListElement; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.TableHeaderElement; -import com.bbn.openmap.util.html.TableRowElement; -import com.bbn.openmap.util.html.WrapElement; - -/** - * This servlet generates HTML for VPF files in spatial index format. - */ -public class SpatialIndexServlet extends VPFHttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public SpatialIndexServlet() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String filePath = (String) request.getAttribute(DispatchServlet.ROOTPATH_FILENAME); - if (filePath == null) { - String pathInfo = setPathInfo(request); - filePath = contextInfo.resolvePath(pathInfo); - if (!pathOkay(filePath, pathInfo, response)) { - return; - } - } - - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - File fp = new File(filePath); - String filename = fp.getName(); - String tableMatch = getIndexedTable(filename); - if (tableMatch == null) { - tableMatch = "non-standard spatial index"; - } else { - tableMatch = fileURL(request, - response, - getRootDir(request), - tableMatch); - } - - out.println(HTML_DOCTYPE + "VPF Spatial Index " - + filename + "\r\n\r\n

Spatial Index " - + filename + " for Table " + tableMatch + "

\r\n"); - - out.println(getStylesheetHTML(request)); - - try { - DcwSpatialIndex ff = new DcwSpatialIndex(filePath, false); - printSpatial(request, response, ff); - ff.close(); - } catch (FormatException fe) { - out.println("FormatException while reading spatial index: " - + fe.getMessage()); - } - out.println("\r\n"); - } - - public void printSpatial(HttpServletRequest request, - HttpServletResponse response, DcwSpatialIndex si) - throws FormatException, IOException { - PrintWriter out = response.getWriter(); - out.println("

General Spatial Index Information

"); - HtmlListElement list = new HtmlListElement(); - list.addElement("Number Of Primitives: " + si.getNumberOfPrimitives()); - int nodesInTree = si.getNodesInTree(); - list.addElement("Nodes in Tree: " + nodesInTree); - list.addElement("Bounding Rectangle: (" + si.getBoundingX1() + ", " - + si.getBoundingY1() + ") - (" + si.getBoundingX2() + ", " - + si.getBoundingY2() + ")"); - list.generate(out); - out.println("

Spatial Index Data

"); - TableRowElement columnNames = new TableRowElement(); - columnNames.addElement(new TableHeaderElement("Primitive ID")); - columnNames.addElement(new TableHeaderElement("x1")); - columnNames.addElement(new TableHeaderElement("x2")); - columnNames.addElement(new TableHeaderElement("y1")); - columnNames.addElement(new TableHeaderElement("y2")); - for (int i = 0; i < nodesInTree; i++) { - int count = si.getPrimitiveCount(i); - int offset = si.getPrimitiveOffset(i); - DcwSpatialIndex.PrimitiveRecord pr[] = si.getPrimitiveRecords(i); - - out.println("

Node " + i); - if (count == 0) { - out.println("(no primitives)

\r\n"); - } else { - out.println("Primitive Count:" + count - + " Relative Offset:" + offset + "\n"); - - ListElement rows = new ListElement(); - WrapElement table = new WrapElement("table", "BORDER=1", rows); - rows.addElement(columnNames); - for (int j = 0; j < pr.length; j++) { - DcwSpatialIndex.PrimitiveRecord pr1 = pr[j]; - TableRowElement datarow = new TableRowElement(); - rows.addElement(datarow); - datarow.addElement(Integer.toString(pr1.primId)); - datarow.addElement(Short.toString(pr1.x1)); - datarow.addElement(Short.toString(pr1.x2)); - datarow.addElement(Short.toString(pr1.y1)); - datarow.addElement(Short.toString(pr1.y2)); - } - table.generate(out); - } - } - } - - /** a map from spatial index name to primitive file indexed */ - private HashMap indexTableMap; - - /** - * Returns the name of the primitive file that the spatial index - * is for. - * - * @param indexName the name of the index - * @return the name of the primitive file - */ - public String getIndexedTable(String indexName) { - if (indexTableMap == null) { - HashMap newMap = new HashMap(); - newMap.put("esi", "edg"); - newMap.put("esi.", "edg."); - newMap.put("fsi", "fac"); - newMap.put("fsi.", "fac."); - newMap.put("csi", "cnd"); - newMap.put("csi.", "cnd."); - newMap.put("nsi", "end"); - newMap.put("nsi.", "end."); - newMap.put("tsi", "txt"); - newMap.put("tsi.", "txt."); - indexTableMap = newMap; - } - return (String) indexTableMap.get(indexName); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TableSubsetRecordIterator.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TableSubsetRecordIterator.java deleted file mode 100644 index cfa70688f..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TableSubsetRecordIterator.java +++ /dev/null @@ -1,66 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/TableSubsetRecordIterator.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; - -/** - * An iterator that will return a subset of the rows in a table. - */ -public class TableSubsetRecordIterator implements Iterator { - final private int vals[]; - final DcwRecordFile drf; - final List l; - private int current = 0; - - public TableSubsetRecordIterator(int vals[], DcwRecordFile drf, List l) { - this.vals = vals; - this.drf = drf; - this.l = l; - } - - /** - * Constructor - * - * @param drf the table to parse - * @param vals the row numbers to be returned - */ - public TableSubsetRecordIterator(int vals[], DcwRecordFile drf) { - this(vals, drf, new ArrayList(drf.getColumnCount())); - } - - public boolean hasNext() { - return (current < vals.length); - } - - public Object next() { - boolean gotit; - try { - gotit = drf.getRow(l, vals[current++]); - } catch (FormatException fe) { - System.out.println("fe: " + fe); - gotit = false; - } - return gotit ? l : null; - } - - public void remove() { - throw new UnsupportedOperationException(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ThematicIndexServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ThematicIndexServlet.java deleted file mode 100644 index e754c2dda..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/ThematicIndexServlet.java +++ /dev/null @@ -1,172 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/ThematicIndexServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwThematicIndex; -import com.bbn.openmap.util.html.Element; -import com.bbn.openmap.util.html.HtmlListElement; -import com.bbn.openmap.util.html.ListElement; -import com.bbn.openmap.util.html.TableHeaderElement; -import com.bbn.openmap.util.html.TableRowElement; -import com.bbn.openmap.util.html.WrapElement; - -/** - * This servlet generates HTML for VPF files in thematic index format. - */ -public class ThematicIndexServlet - extends VPFHttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public ThematicIndexServlet() { - super(); - } - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - String filePath = (String) request.getAttribute(DispatchServlet.ROOTPATH_FILENAME); - if (filePath == null) { - String pathInfo = setPathInfo(request); - filePath = contextInfo.resolvePath(pathInfo); - if (!pathOkay(filePath, pathInfo, response)) { - return; - } - } - - DcwThematicIndex ti; - try { - ti = new DcwThematicIndex(filePath, false); - } catch (FormatException fe) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, fe.toString()); - return; - } - - String valIndex = request.getParameter("valIndex"); - if (valIndex != null) { - showTableIndexed(request, response, valIndex, ti); - } else { - showTableData(request, response, ti, filePath); - } - try { - ti.close(); - } catch (FormatException fe) { - // ignore - } - } - - protected void showTableData(HttpServletRequest request, HttpServletResponse response, DcwThematicIndex ti, String filePath) - throws ServletException, IOException { - - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - String title = "VPF Thematic Index for " + new File(filePath).getName(); - String basepath = getRootDir(request); - out.println("" + title + ""); - out.println(getStylesheetHTML(request)); - out.println("

" + title + "

"); - - out.println("

General Thematic Index Information

"); - HtmlListElement list = new HtmlListElement(); - list.addElement("Number of Codes: " + ti.getNumberOfCodes()); - list.addElement("Number of Rows: " + ti.getNumberOfRows()); - list.addElement("Type Of Index: " + ti.getTypeOfIndex()); - list.addElement("Field Type of Index: " + ti.getFieldTypeOfIndex()); - list.addElement("Number of Data Elements: " + ti.getNumberOfDataElements()); - list.addElement("Data Type Specifier: " + ti.getDataTypeSpecifier()); - list.addElement("Table Indexed: " + fileURL(request, response, basepath, ti.getTableIndexed())); - list.addElement("Column Indexed: " + ti.getColumnIndexed()); - list.addElement("Fields Sorted: " + ti.getSorted()); - list.generate(out); - - out.println("

Thematic Index Data

"); - Object[] values = ti.getValueIndexes(); - ListElement rows = null; - Element table = null; - TableRowElement th = new TableRowElement(); - th.addElement(new TableHeaderElement("CLASS=NavBarCell2", "Index Value")); - th.addElement(new TableHeaderElement("Count")); - th.addElement(new TableHeaderElement("Rows...")); - String valStr = "" + values[i] + ""); - try { - int[] intvals = ti.get(values[i]); - tr.addElement(Integer.toString(intvals.length)); - StringBuffer sb = new StringBuffer(); - sb.append(intvals[0]); - for (int j = 1; j < intvals.length; j++) { - sb.append(", ").append(intvals[j]); - } - tr.addElement(sb.toString()); - } catch (FormatException fe) { - tr.addElement(fe.toString()); - } - } - if (table != null) { - table.generate(out); - } - } - - protected void showTableIndexed(HttpServletRequest request, HttpServletResponse response, String valIndex, DcwThematicIndex ti) - throws IOException, ServletException { - Object val = null; - switch (ti.getFieldTypeOfIndex()) { - case 'I': - val = Integer.valueOf(valIndex); - break; - case 'S': - val = Short.valueOf(valIndex); - break; - case 'T': - val = valIndex; - break; - } - try { - int[] vals = ti.get(val); - request.setAttribute(Data.ROWLIST_OBJECT, vals); - } catch (FormatException fe) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, fe.toString()); - } - String pi = request.getPathInfo(); - int lin = pi.lastIndexOf('/') + 1; - RequestDispatcher rd = request.getRequestDispatcher("/UnknownType" + pi.substring(0, lin) + ti.getTableIndexed()); - rd.forward(request, response); - } - -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TileHolder.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TileHolder.java deleted file mode 100644 index daf47519d..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/TileHolder.java +++ /dev/null @@ -1,202 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/TileHolder.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.File; -import java.util.List; -import java.util.Vector; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwCrossTileID; -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.layer.vpf.TilingAdapter; -import com.bbn.openmap.layer.vpf.VPFUtil; - -/** - * This class provides easy access to tiled data. - */ -public class TileHolder { - /** the name of the primitive file */ - private final String fileName; - /** the current open tile */ - private DcwRecordFile currentTileFile; - /** the index (into tileStuff) of the current open tile */ - private int curTile; - /** an array of tile paths */ - private String tileStuff[]; - /** the directory which has tile subdirectories */ - private final File basepath; - - /** - * Construct a TileHolder. close() should be called when you are - * done with the object. - * - * @param basepath the directory which has tile subdirectories - * @param fileName the name of the primitive file - * @param isTiled if the coverage is tiled or not. If it is, - * tiling information is assumed to be located in - * $basepath/../tileref - * @throws FormatException something went wrong - */ - public TileHolder(File basepath, String fileName, boolean isTiled) - throws FormatException { - this.fileName = fileName; - this.basepath = basepath; - curTile = -1; - if (isTiled) { - tileStuff = doTileRefStuff(basepath); - } else { - currentTileFile = new DcwRecordFile(basepath + File.separator - + fileName); - } - } - - /** - * Gets a row from a primitive file in a coverage. - * - * @param tileColumn the column index used to get the tile id - * @param rowColumn the column index used to get the row id - * @param tileRow the row to retrieve the tile and row IDs from - * @param retrow the row gotten from the file - * @return true if the row was fetched, false otherwise - * @throws FormatException - */ - public boolean getRow(int tileColumn, int rowColumn, List tileRow, - List retrow) throws FormatException { - int tileId = (tileColumn == -1) ? -1 - : VPFUtil.objectToInt(tileRow.get(tileColumn)); - int rowId = VPFUtil.objectToInt(tileRow.get(rowColumn)); - return getRow(tileId, rowId, retrow); - } - - public boolean getRow(TilingAdapter ta, List tileRow, List retrow) - throws FormatException { - return getRow(ta.getTileId(tileRow), ta.getTilePrimId(tileRow), retrow); - } - - public boolean getRow(DcwCrossTileID prim, List retrow) - throws FormatException { - return getRow(prim.nextTileID, prim.nextTileKey, retrow); - } - - /** - * Gets a row from a primitive file in a coverage. - * - * @param tileId the tile identifier - * @param rowId the row identifier - * @param retrow the row gotten from the file - * @return true if the row was fetched, false otherwise - * @throws FormatException - */ - public boolean getRow(int tileId, int rowId, List retrow) - throws FormatException { - if (rowId <= 0) { - return false; - } - if (tileId != curTile) { - File joinfile = new File(basepath + File.separator - + tileStuff[tileId]); - close(); - currentTileFile = new DcwRecordFile(joinfile + File.separator - + fileName); - curTile = tileId; - } - return currentTileFile.getRow(retrow, rowId); - } - - /** - * Closes any related tables. - */ - public void close() { - if (currentTileFile != null) { - currentTileFile.close(); - } - currentTileFile = null; - } - - /** - * Loads tiling information for the coverage. - * - * @param path the path to the coverage. tiling info is in - * ../tileref - * @return an array of tile paths - */ - private static String[] doTileRefStuff(File path) throws FormatException { - File pathname = new File(path.getParentFile(), "tileref"); - String faceIDColumnName = null; - // read fcs to figure out what column in tileref.aft we need - // to use to - // read the fbr (face bounding rectangle) table - File fcsFile = new File(pathname, "fcs"); - if (!fcsFile.canRead()) { - fcsFile = new File(pathname, "fcs."); - } - DcwRecordFile fcs = new DcwRecordFile(fcsFile.toString()); - Vector fcsv = new Vector(fcs.getColumnCount()); - while (fcs.parseRow(fcsv)) { - String fclass = ((String) fcsv.elementAt(1)).toLowerCase(); - String table1 = ((String) fcsv.elementAt(2)).toLowerCase(); - if ((fclass.equals("tileref")) && (table1.equals("tileref.aft"))) { - faceIDColumnName = (String) fcsv.elementAt(3); - break; - } - } - fcs.close(); - - if (faceIDColumnName == null) { - throw new FormatException("no faceIDColumn"); - // won't be able to read the tiling info. abort - } - - // Okay, we've got info on what column we use from tileref.aft - // to index - // into the fbr. - DcwRecordFile aft = new DcwRecordFile(pathname + File.separator - + "tileref.aft"); - int faceIDColumn = aft.whatColumn(faceIDColumnName.toLowerCase()); - int tileNameColumn = aft.whatColumn("tile_name"); - - if ((faceIDColumn == -1) || (tileNameColumn == -1)) { - aft.close(); - throw new FormatException("no faceIDColumn"); - } - - Vector aftv = new Vector(aft.getColumnCount()); - - // set the array size to record count + 1, to be able to - // use the tileID as the index into the array - String containedTiles[] = new String[aft.getRecordCount() + 1]; - - int tileid = 1; - while (aft.parseRow(aftv)) { - //int fac_num = ((Number) aftv.elementAt(faceIDColumn)).intValue(); - String tilename = (String) aftv.elementAt(tileNameColumn); - - char chs[] = tilename.toCharArray(); - boolean goodTile = false; - for (int i = 0; i < chs.length; i++) { - if ((chs[i] != '\\') && (chs[i] != ' ')) { - goodTile = true; - chs[i] = Character.toLowerCase(chs[i]); - } - if (chs[i] == '\\') { - chs[i] = File.separatorChar; - } - } - containedTiles[tileid++] = (goodTile) ? new String(chs) : null; - } - aft.close(); - return containedTiles; - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/URLCheck.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/URLCheck.java deleted file mode 100644 index 3b1f25a96..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/URLCheck.java +++ /dev/null @@ -1,136 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/URLCheck.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.TreeSet; - -/** - * Command line program to wander the vpfservlet pages, to make sure - * all URLs generated are valid. - */ -public class URLCheck { - public static Set check(String surl, PrintStream out) throws IOException { - Set urls = new TreeSet(); - out.println("URL " + surl); - Reader r; - URL url; - try { - url = new URL(surl); - r = new InputStreamReader(url.openStream()); - } catch (MalformedURLException mue) { - out.println(" bad URL"); - return urls; - } - Set names = new HashSet(); - Set localrefs = new HashSet(); - StringBuffer sb = new StringBuffer(); - char buf[] = new char[8096]; - int len; - while ((len = r.read(buf)) != -1) { - sb.append(buf, 0, len); - String str = sb.toString(); - int fromIx = 0; - int gt; - while ((gt = str.indexOf('>', fromIx)) != -1) { - int lt = str.indexOf('<', fromIx); - fromIx = gt + 1; - char firstChar = str.charAt(lt + 1); - if ((firstChar != 'A') && (firstChar != 'a')) { - continue; - } - String substr = str.substring(lt + 1, gt); - String lsubstr = substr.toLowerCase(); - - int hquote = lsubstr.indexOf(href); - if (hquote != -1) { - hquote += href.length(); - int lquote = substr.indexOf('"', hquote); - String rurl = substr.substring(hquote, lquote); - if (rurl.charAt(0) == '#') { - names.add(rurl.substring(1)); - } else { - try { - urls.add(new URL(url, rurl).toExternalForm()); - } catch (MalformedURLException mue) { - out.println(" MUE: " + mue.getMessage()); - } - } - } else { - int nquote = lsubstr.indexOf(name); - if (nquote != -1) { - nquote += name.length(); - int lquote = substr.indexOf('"', nquote); - String n = substr.substring(nquote, lquote); - localrefs.add(n); - } - } - - } - sb.delete(0, fromIx); - } - for (Iterator i = localrefs.iterator(); i.hasNext();) { - String localref = (String) i.next(); - if (!names.contains(localref)) { - out.println("MISSING REF: " + localref); - } - } - return urls; - } - final static String href = "href=\""; - final static String name = "name=\""; - - public static Set workOn(Set master, Set urls, PrintStream out) { - Set newurls = null; - for (Iterator i = urls.iterator(); i.hasNext();) { - String surl = (String) i.next(); - if (master.add(surl)) { - try { - Set rets = check(surl, out); - if (newurls == null) { - newurls = rets; - } else { - newurls.addAll(rets); - } - } catch (FileNotFoundException fnfe) { - out.println("Bogus URL: " + surl); - } catch (IOException ioe) { - out.println(" " + surl + " " + ioe.getClass() + " " - + ioe.getMessage()); - } - } - } - return newurls; - } - - public static void main(String[] args) { - Set master = new HashSet(); - Set workon = new HashSet(); - workon.addAll(Arrays.asList(args)); - do { - workon = workOn(master, workon, System.out); - } while (workon != null); - System.out.println("Done."); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VDTRowMaker.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VDTRowMaker.java deleted file mode 100644 index 0b68255f8..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VDTRowMaker.java +++ /dev/null @@ -1,55 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/VDTRowMaker.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.layer.vpf.DcwRecordFile; -import com.bbn.openmap.util.html.TableRowElement; - -/** - * A RowMaker class for int.vdt and char.vdt tables. It generates a - * URL for columns that reference another table. - */ -public class VDTRowMaker extends ReferenceRowMaker { - - /** the path to the coverage */ - final String basepath; - /** the column with the table name */ - final int tableCol; - - public VDTRowMaker(HttpServletRequest request, - HttpServletResponse response, String basepath, DcwRecordFile drf) { - super(request, response); - this.basepath = basepath; - tableCol = drf.whatColumn("table"); - } - - public void addToRow(TableRowElement row, List l) { - int i = 0; - for (Iterator li = l.iterator(); li.hasNext();) { - Object elt = li.next(); - if (i == tableCol) { - row.addElement(fileURL(basepath, ((String) elt).toLowerCase())); - } else { - row.addElement(elt.toString()); - } - i++; - } - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFHttpServlet.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFHttpServlet.java deleted file mode 100644 index cdf45d457..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFHttpServlet.java +++ /dev/null @@ -1,210 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/VPFHttpServlet.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:15 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import com.bbn.openmap.util.html.TableHeaderElement; -import java.io.File; -import java.io.IOException; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * A base class useful for servlets that use the VPF tools context object. This class also defines some utility methods - * used in the package. - */ -public abstract class VPFHttpServlet extends HttpServlet { - - /** - * html doctype for HTML 4.0 - */ - public static final String HTML_DOCTYPE = ""; - - /** - * the context object used for config info - */ - protected ContextInfo contextInfo; - - /** - * A do-nothing constructor - init does all the work. - */ - public VPFHttpServlet() { - super(); - } - - public void init(ServletConfig config) throws ServletException { - super.init(config); - contextInfo = ContextInfo.getContextInfo(config.getServletContext()); - } - - /** - * Checks if a path refers to a file. If its not, reports an error. - * - * @param rootpath the path to check (can be null) - * @param pathInfo used in the error message if rootpath is null - * @param response used to send the error - * @return true if the file can be read, false otherwise - * @see HttpServletResponse#sendError - */ - public static boolean pathOkay(String rootpath, String pathInfo, - HttpServletResponse response) - throws IOException { - if (rootpath == null) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST, pathInfo - + " (invalid path)"); - return false; - } else if (!new File(rootpath).canRead()) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, - rootpath.toString() + " not found"); - return false; - } - return true; - } - - /** - * Returns the HTML to reference the common stylesheet - * - * @return the stylesheet HTML - */ - public String getStylesheetHTML(HttpServletRequest request) { - return (""); - } - - /** - * Returns a TableHeaderElement that contains a URL - * - * @param text the text for the reference - * @param url the URL for the reference - * @return a table cell containing a URL - */ - public TableHeaderElement THE(String text, String url) { - return new TableHeaderElement(buildHREF(url, text)); - } - - /** - * Returns a TableHeaderElement that contains a URL - * - * @param text the text for the reference - * @param url the URL for the reference - * @param response the HttpServletResponse object used to encode the url - * @return a table cell containing a URL - */ - public TableHeaderElement THE(String text, String url, - HttpServletResponse response) { - return new TableHeaderElement(buildHREF(response, url, text)); - } - - /** - * Returns a string usable as an HTML HREF element - * - * @param tag the text for the reference - * @param url the URL for the reference - * @return a string containing an HTML HREF - */ - public static String buildHREF(String url, String tag) { - return "" + tag + ""; - } - - /** - * Returns a string usable as an HTML HREF element - * - * @param tag the text for the reference - * @param url the URL for the reference - * @param response the HttpServletResponse object used to encode the url - * @return a string containing an HTML HREF - */ - public static String buildHREF(HttpServletResponse response, String url, - String tag) { - return buildHREF(response.encodeURL(url), tag); - } - - /** - * Returns an HTML HREF based on the parameters. This method is equivelent to toURL(request, response, - * "/UnknownType", pathname, filename); - * - * @see #toURL - * @param request the request to use for context info - * @param response the response to use to encode the URL - * @param pathname the path of the file - * @param filename the name of the file - * @return a string HREF - */ - public static String fileURL(HttpServletRequest request, - HttpServletResponse response, String pathname, - String filename) { - return toURL(request, response, "/UnknownType", pathname, filename); - } - - /** - * Returns an HTML HREF based on the parameters. - * - * @param request the request to use for context info - * @param response the response to use to encode the URL - * @param pathname the path of the file - * @param filename the name of the file (may be null) - * @param servletName the servlet name to use in the URL - * @return a string HREF - */ - public static String toURL(HttpServletRequest request, - HttpServletResponse response, - String servletName, String pathname, - String filename) { - String value; - if (filename == null) { - value = "---"; - } else { - String url = request.getContextPath() + servletName + pathname - + filename; - value = "" + filename - + "\r\n"; - - } - return value; - } - - public static final String ROOT_PATHDIR = VPFHttpServlet.class.getName() - + ".rootPathDir"; - public static final String ROOT_PATH = VPFHttpServlet.class.getName() - + ".rootPath"; - - public static void setRootDir(HttpServletRequest request, String path) { - request.setAttribute(ROOT_PATHDIR, path); - } - - public static String getRootDir(HttpServletRequest request) { - return (String) request.getAttribute(ROOT_PATHDIR); - } - - public static void setPathInfo(HttpServletRequest request, String path) { - request.setAttribute(ROOT_PATH, path); - } - - public static String getPathInfo(HttpServletRequest request) { - return (String) request.getAttribute(ROOT_PATH); - } - - protected static String setPathInfo(HttpServletRequest request) { - String pathInfo = request.getPathInfo(); - setPathInfo(request, pathInfo); - if (pathInfo != null) { - int index = pathInfo.lastIndexOf('/'); - String subpath = pathInfo.substring(0, index + 1); - setRootDir(request, subpath); - } - return pathInfo; - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFTable.java b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFTable.java deleted file mode 100644 index 9995029c3..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/VPFTable.java +++ /dev/null @@ -1,49 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/vpfservlet/WEB-INF/src/com/bbn/openmap/vpfservlet/VPFTable.java,v $ -// $Revision: 1.4 $ $Date: 2005/08/11 20:39:16 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.vpfservlet; - -import com.bbn.openmap.io.FormatException; -import com.bbn.openmap.layer.vpf.DcwRecordFile; - -/** - * Wrapper for DcwRecordFile objects, to give JSPs a way to interact - * with them directly. - */ -public class VPFTable { - - private DcwRecordFile table; - - public VPFTable() {} - - public void setFile(String file) { - try { - if ((file == null) && (table != null)) { - table.close(); - table = null; - } - if (file != null) { - table = new DcwRecordFile(file); - } - } catch (FormatException fe) { - } - } - - public String getTablename() { - return (table == null) ? "default" : table.getTableName(); - } - - public String getDescription() { - return (table == null) ? "default" : table.getDescription(); - } -} diff --git a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/package.html b/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/package.html deleted file mode 100644 index c2fdf8983..000000000 --- a/src/vpfbrowseservlet/src/main/java/com/bbn/openmap/vpfservlet/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - -This package is the Java source code to view VPF data through web -pages generated by servlets. - \ No newline at end of file diff --git a/src/vpfbrowseservlet/src/main/webapp/PrintTable.jsp b/src/vpfbrowseservlet/src/main/webapp/PrintTable.jsp deleted file mode 100644 index bae778d04..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/PrintTable.jsp +++ /dev/null @@ -1,20 +0,0 @@ -<%@ page session="false" %> - - - - - -<% table.setFile(request.getParameter("table")); %> - - - - -VPF Table <%= table.getTablename() %> - -

VPF Table Help

- -This is help text rambling on about , whose description is . - - diff --git a/src/vpfbrowseservlet/src/main/webapp/VPFHelp.jsp b/src/vpfbrowseservlet/src/main/webapp/VPFHelp.jsp deleted file mode 100644 index a501fb5f1..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/VPFHelp.jsp +++ /dev/null @@ -1,63 +0,0 @@ -<%@ page session="false" %> - - -VPF Help - -

VPF Help

- -This is help text. -<% String helpTopic = request.getParameter("topic"); %> -<% if (helpTopic == null) { %> -No help topic was specified. - -<% } else if ("test".equals(helpTopic)) { %> -
    -
  • Current time: <%= new java.util.Date() %> -
  • Hostname: <%= request.getRemoteHost() %> -
  • Param file: <%= request.getParameter("topic") %> -
-<% } else if ("table_schema".equals(helpTopic)) { %> -

Table Schema Help

-This data is extracted from the VPF Standard Section 5. (MIL-STD-2407) -
    -
  • #: The position of the column in the record -
  • Name: The name of the column -
  • Type: The field type of the column. Valid values are - - - - - - - - - - - - - - - - - - -
    Type CodeDatatype Description
    TASCII Text
    LISO Latin-1 Text
    MISO Full Latin Text
    NISO Multilingual Text
    S2-byte integer
    I4-byte integer
    F4-byte floating point (float)
    D8-byte floating point (double)
    CArray of 2-coord (Lat,Lon) floats
    BArray of 2-coord (Lat,Lon) doubles
    ZArray of 3-coord (Lat,Lon,Elev) floats
    YArray of 3-coord (Lat,Lon,Elev) double
    DDate Field
    XNull (no value) field
    KCross-Tile identifier
    -
  • Count: The number of values (* indicates variable number). - Types I,S,R,F,D,X,K are always 1. (e.g type T count 12 would be a - twelve character ascii string) -
  • Key Type: 'P'-primary key, 'F'-foreign key, 'N'-not a key -
  • Description: a description of the column -
  • VDT: int.vdt or char.vdt if the value refers to additional info, - --- otherwise -
  • Thematic Index: the name of the thematic index for this column, - --- otherwise -
  • Documentation File: the name of the file with additional information - about what the column is for, --- otherwise -
-<% } else { %> -Other VPF help. -<% } %> - - diff --git a/src/vpfbrowseservlet/src/main/webapp/VPFText.html b/src/vpfbrowseservlet/src/main/webapp/VPFText.html deleted file mode 100644 index fc1344ca7..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/VPFText.html +++ /dev/null @@ -1,21 +0,0 @@ - - -VPF Help - -

VPF Help

- -This is help text. - -Here we are. -
    -
  • Current time: -
  • Hostname: -
  • Param file: -
-

Table Schema Help

-Other VPF help. - - - - - diff --git a/src/vpfbrowseservlet/src/main/webapp/VPFText.jsp b/src/vpfbrowseservlet/src/main/webapp/VPFText.jsp deleted file mode 100644 index c54a77f81..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/VPFText.jsp +++ /dev/null @@ -1,33 +0,0 @@ -<%@ page import="com.bbn.openmap.layer.vpf.*" %> -<%@ page session="false" %> - - -VPF Help - -

VPF Help

- -This is help text. - -Here we are. -
    -
  • Hostname: - - <% lst.setContext(application); %> - <% lst.setResponse(response); %> - - -
  • DB: -<% - LibrarySelectionTable lstt = lst.getLst(); - java.util.List items = lstt.getLibraryNames(); - for (String item : items) { -%> -
  • library <%= item %> -<% - } -%> -
  • dbname <%= lstt.getDatabaseName() %> -
  • description <%= lstt.getDatabaseDescription() %> -
- - diff --git a/src/vpfbrowseservlet/src/main/webapp/WEB-INF/.gitignore b/src/vpfbrowseservlet/src/main/webapp/WEB-INF/.gitignore deleted file mode 100644 index 165caec40..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/WEB-INF/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/classes -/lib diff --git a/src/vpfbrowseservlet/src/main/webapp/WEB-INF/web.xml b/src/vpfbrowseservlet/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 218a815f0..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - Development Tools for VPF Data - - These are some test code I wrote to familiarize myself - with servlets, and to hopefully do something vaguely - useful at the same time. The included servlet code can - print VPF data. - - - - - webmaster - myaddress@mycompany.com - - The EMAIL address of the administrator to whom questions - and comments about this application should be addressed. - - - - - - - - - com.bbn.openmap.vpfservlet.vpf_library.dnc17 - /Volumes/data/vpf/dnc/dnc17 - - DNC17 data, East Coast US. - - - - - com.bbn.openmap.vpfservlet.vpf_library.noamer - /Volumes/data/vpf/vmaplv0/disk0 - - VMAP Level 0 North America Data. - - - - - - Dispatch - - This servlet is the entry doing for most of the work, it looks at file - names and redirects to the appropriate specialized servlet class. - - com.bbn.openmap.vpfservlet.DispatchServlet - - - - DirectoryList - - This servlet generates directory listings. It should be constrained to - listing directories within the configured libraries in this file, - but feel free to set the listDirectories parameter below to false if - the capability makes you nervous. - - com.bbn.openmap.vpfservlet.DirectoryServlet - - listDirectories - true - - - - - DescribeVPF - - This servlet describes a VPF database, roughly the html equivelent of - the DescribeDB class in the VPF layer. - - com.bbn.openmap.vpfservlet.DescribeDBServlet - - - - Schema - - This servlet displays schema info. - - com.bbn.openmap.vpfservlet.Schema - - - - Data - - This servlet displays table data. - - com.bbn.openmap.vpfservlet.Data - - - - DocFile - - This servlet displays documentation file data. - - com.bbn.openmap.vpfservlet.DocFileServlet - - - - Thematic - - This servlet displays thematic index file data. - - com.bbn.openmap.vpfservlet.ThematicIndexServlet - - - - SpatialIndex - - This servlet displays spatial index file data. - - com.bbn.openmap.vpfservlet.SpatialIndexServlet - - - SpatialGraphic - - This servlet was intended to provide a graphical representation of the - data in a spatial index file. For now it doesnt do anything useful. - - com.bbn.openmap.vpfservlet.SpatialGraphicServlet - - - - - - - Dispatch - /UnknownType/* - - - - Dispatch - /UnknownType - - - - DescribeVPF - /DescribeVPF/* - - - - DescribeVPF - / - - - - Schema - /Schema - - - - DocFile - /DocFile - - - - DocFile - /DocFile/* - - - - DirectoryList - /DirectoryList - - - - DirectoryList - /DirectoryList/* - - - - Thematic - /Thematic - - - - Thematic - /Thematic/* - - - - SpatialIndex - /SpatialIndex - - - SpatialGraphic - /SpatialGraphic - - - - SpatialIndex - /SpatialIndex/* - - - SpatialGraphic - /SpatialGraphic/* - - - - Data - /Data - - - - - - - 30 - - - diff --git a/src/vpfbrowseservlet/src/main/webapp/stylesheet.css b/src/vpfbrowseservlet/src/main/webapp/stylesheet.css deleted file mode 100644 index 1cd67ec35..000000000 --- a/src/vpfbrowseservlet/src/main/webapp/stylesheet.css +++ /dev/null @@ -1,33 +0,0 @@ -/* Javadoc style sheet */ - -/* Define colors, fonts and other style attributes here to override the defaults */ - -/* Page background color */ -body { background-color: #FFFFFF } -/* th { background-color: #FFFFFF } */ -/* td { background-color: #FFFFFF } */ - -/* Table colors */ -.TableHeadingColor { background: #CCCCFF } /* Dark mauve */ -.TableSubHeadingColor { background: #EEEEFF } /* Light mauve */ -.TableRowColor { background: #FFFFFF } /* White */ - -/* Font used in left-hand frame lists */ -.FrameTitleFont { font-size: normal; font-family: normal } -.FrameHeadingFont { font-size: normal; font-family: normal } -.FrameItemFont { font-size: normal; font-family: normal } - -/* Example of smaller, sans-serif font in frames */ -/* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */ -.JoinColumn { font-family: Arial, Helvetica, sans-serif; color:#CCCCFF;} -.Join2Column { font-family: Arial, Helvetica, sans-serif; color:#00008B;} - -/* Navigation bar fonts and colors */ -.NavBarCell1 { background-color:#EEEEFF;}/* Light mauve */ -.NavBarCell1Rev { background-color:#00008B;}/* Dark Blue */ -.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} -.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} - -.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} -.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} - diff --git a/src/wmsservlet/.gitignore b/src/wmsservlet/.gitignore deleted file mode 100644 index dc5353ef0..000000000 --- a/src/wmsservlet/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/.classpath -/.settings/ diff --git a/src/wmsservlet/.project b/src/wmsservlet/.project deleted file mode 100644 index 1ce3dab21..000000000 --- a/src/wmsservlet/.project +++ /dev/null @@ -1,42 +0,0 @@ - - - openmap-wmsservlet - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/src/wmsservlet/README.txt b/src/wmsservlet/README.txt deleted file mode 100644 index 7138020ee..000000000 --- a/src/wmsservlet/README.txt +++ /dev/null @@ -1,21 +0,0 @@ -WMSServlet Package README - -This package, built separately, creates a war file that can be loaded into tomcat or -glassfish to provide a OGC WMS server. The servlet code in the war file contains -everything you need, but it must be configured for your data and system configuration. - -- The build.xml file controls the creation of the war file. You may want to modify -what gets added to the war, data files and such, and where the servlet-api.jar file -can be found to compile the servlet classes. It can be found in the tomcat/glassfish -installations. - -- Before you create the war file (using ant), you need to modify the WEB-INF/web.xml file, -setting the port your server is running on (8080 is the default port of tomcat/glassfish), -your URL request path, and the path to the properties file you are using to configure the -servlet map layers. If you want to upload the properties file and have it found in the war -file by simply naming the file with no path, it should work if you put it in the -WEB-INF/classes directory. Otherwise, you can store the properties file anywhere on your system -and specify the path in the web.xml file. - -A sample properties file is in this directory, wms.properties. It works like the layer -section of a standard openmap.properties file with a couple of extra properties. \ No newline at end of file diff --git a/src/wmsservlet/build.xml b/src/wmsservlet/build.xml deleted file mode 100644 index b7318d564..000000000 --- a/src/wmsservlet/build.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/wmsservlet/pom.xml b/src/wmsservlet/pom.xml deleted file mode 100644 index 174c564d3..000000000 --- a/src/wmsservlet/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - 4.0.0 - openmap-wmsservlet - war - openmap-wmsservlet - OpenMap is a Java Beans based toolkit for building applications and applets needing geographic information. This project encapsulates the wms servlet components that can be used with Tomcat/Glassfish to create a Web Mapping Service. - - - - javax.servlet - servlet-api - 2.5 - - - org.openmap-java - openmap - 6.0 - - - - - org.openmap-java - openmap-all - 6.0 - ../.. - - diff --git a/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/HttpResponse.java b/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/HttpResponse.java deleted file mode 100644 index 0ba8aa056..000000000 --- a/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/HttpResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -// ********************************************************************** -// -// -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// -// ********************************************************************** -// -// $Source: /cvs/distapps/openmap/src/wmsservlet/WEB-INF/src/com/bbn/openmap/wmsservlet/HttpResponse.java,v $ -// $RCSfile: HttpResponse.java,v $ -// $Revision: 1.3 $ -// $Date: 2008/02/20 01:41:08 $ -// $Author: dietrick $ -// -// ********************************************************************** -package com.bbn.openmap.wmsservlet; - -import java.io.IOException; -import java.io.OutputStream; - -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.util.http.IHttpResponse; - -/** - */ -public class HttpResponse implements IHttpResponse { - - protected HttpServletResponse httpResponse; - - /** - * Initialize the input Reader and output Writer - * and start the connection thread. - * - * @param response the response object - */ - public HttpResponse(HttpServletResponse response) { - this.httpResponse = response; - } - - /** - * Write a String response encoded as UTF-8 to the OutputStream. - * - * @param contentType the content type of the response. - * @param response the string containing the response. - */ - public void writeHttpResponse(String contentType, String response) throws IOException { - writeHttpResponse(contentType, response.getBytes("UTF-8")); - } - - /** - * Write a byte[] response to the OutputStream. - * - * @param contentType the content type of the response. - * @param response the byte array containing the response. - */ - public void writeHttpResponse(String contentType, byte[] response) throws IOException { - httpResponse.setContentType(contentType); - httpResponse.setContentLength(response.length); - OutputStream out = httpResponse.getOutputStream(); - out.write(response, 0, response.length); - out.flush(); - } - -} diff --git a/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/OgcWmsServlet.java b/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/OgcWmsServlet.java deleted file mode 100644 index 8f4a10a71..000000000 --- a/src/wmsservlet/src/main/java/com/bbn/openmap/wmsservlet/OgcWmsServlet.java +++ /dev/null @@ -1,154 +0,0 @@ -// ********************************************************************** -// -// BBN Technologies -// 10 Moulton Street -// Cambridge, MA 02138 -// (617) 873-8000 -// -// Copyright (C) BBNT Solutions LLC. All rights reserved. -// -// ********************************************************************** -// $Source: /cvs/distapps/openmap/src/wmsservlet/WEB-INF/src/com/bbn/openmap/wmsservlet/OgcWmsServlet.java,v $ -// $Revision: 1.5 $ $Date: 2008/09/19 14:20:14 $ $Author: dietrick $ -// ********************************************************************** -package com.bbn.openmap.wmsservlet; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Properties; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.bbn.openmap.PropertyHandler; -import com.bbn.openmap.image.wms.WMSException; -import com.bbn.openmap.image.wms.WmsRequestHandler; -import com.bbn.openmap.util.Debug; - -/** - * - */ -public class OgcWmsServlet extends HttpServlet { - - /** - * A do-nothing constructor - init does all the work. - */ - public OgcWmsServlet() { - super(); - } - - /** - * @param request the request argument - * @return Properties - */ - protected Properties parsePropertiesFromRequest(HttpServletRequest request) { - Properties props = new Properties(); - java.util.Enumeration keys = request.getParameterNames(); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - String value = request.getParameter(key); - if (value != null) { - // A wms client can send lowercase request parameters. - key = key.toUpperCase(); - props.put(key, value); - } - } - return props; - } - - /** - * Get a {@link Properties} object with the content of openmap.properties. - * No request specific properties are included. - * - * @return Properties - * @throws MalformedURLException - * @throws IOException - */ - protected Properties getProperties() throws MalformedURLException, - IOException { - - // use context parameter "mapDefinition" for path to openmap.properties. - // default to "openmap.properties". - String mapDefinition = getServletContext().getInitParameter( - "mapDefinition"); - if (mapDefinition == null) { - mapDefinition = "openmap.properties"; - } - Debug.message("wms", "Using map definition:" + mapDefinition); - - PropertyHandler propHandler = new PropertyHandler(mapDefinition); - Properties props = propHandler.getProperties(); - - return props; - } - - protected WmsRequestHandler createRequestHandler(HttpServletRequest request) throws ServletException, - IOException { - Debug.message("wms", "OgcWmsServlet.createRequestHandler : "); - - - String schema = request.getScheme(); - if (schema == null) { - throw new ServletException("schema is not specified"); - } - - String hostName = request.getServerName(); - if (hostName == null) { - throw new ServletException("server name not specified"); - } - - int serverPort = request.getServerPort(); - - String contextPath = request.getContextPath(); - if (contextPath == null) { - throw new ServletException("context path is not specified"); - } - - String servletPath = request.getServletPath(); - if (servletPath == null) { - throw new ServletException("servlet path is not specified"); - } - - // can be used to encode extra things in the path info. only usable by - // subclassing OgcWmsServlet - String servletPathInfo = request.getPathInfo(); - if (servletPathInfo == null) { - servletPathInfo = ""; - } - - try { - WmsRequestHandler wmsRequestHandler = new WmsRequestHandler(schema, hostName, - serverPort, contextPath + servletPath + servletPathInfo, getProperties()); - return wmsRequestHandler; - } catch (java.net.MalformedURLException me) { - Debug.message("wms", "MS: caught MalformedURLException - \n" + me.getMessage()); - throw me; - } catch (java.io.IOException ioe) { - Debug.message("wms", "MS: caught IOException - \n" + ioe.getMessage()); - throw ioe; - } catch (WMSException wmse) { - Debug.message("wms", "MS: caught WMSException - \n" + wmse.getMessage()); - throw new ServletException(wmse); - } - - } - - /** - * @param request - * @param response - * @throws ServletException - * @throws IOException - */ - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - Debug.message("wms", "OgcWmsServlet.doGet"); - WmsRequestHandler wmsRequestHandler = createRequestHandler(request); - - Properties properties = parsePropertiesFromRequest(request); - HttpResponse httpResponse = new HttpResponse(response); - wmsRequestHandler.handleRequest(properties, httpResponse); - } - -} diff --git a/src/wmsservlet/src/main/resources/wms.properties b/src/wmsservlet/src/main/resources/wms.properties deleted file mode 100644 index 74dba32fb..000000000 --- a/src/wmsservlet/src/main/resources/wms.properties +++ /dev/null @@ -1,254 +0,0 @@ -## Sample properties file for WMS servlet - -# Antialiased map [optional] -openmap.wms.antialiasing=true -# Class that handles Feature Info Requests [optional] -openmap.wms.featureInfoResponse.class= -# Special WMS layers that follow com.bbn.openmap.image.wms.iWMSLayer interface, they -# are handled a little differently and can respond to more metadata requests. [optional] -wms.layers= - -# Image formatters, notice that the formatters list provide scoping words for actual -# formatters class properties. -formatters=gif jpeg png png8 png32 -gif.class =com.bbn.openmap.image.AcmeGifFormatter -jpeg.class=com.bbn.openmap.image.SunJPEGFormatter -png.class=com.bbn.openmap.image.PNGImageIOFormatter -png8.class=com.bbn.openmap.image.PNG8ImageFormatter -png32.class=com.bbn.openmap.image.PNG32ImageFormatter - -# OpenMap layers, these are general layer definitions. These keywords are -# used for the layer name by the client in the WMS request. -openmap.layers=daynight graticule shapePolitical - -### -daynight- layer properties -daynight.addToBeanContext=true -daynight.autoPalette=false -daynight.background=false -daynight.class=com.bbn.openmap.layer.daynight.DayNightLayer -daynight.consumeEvents=false -daynight.currentTime=true -daynight.daytimeColor=ffffff -daynight.doPolyTerminator=true -daynight.interruptable=true -daynight.nighttimeColor=64000000 -daynight.overlayTime=0 -daynight.pcp.class=com.bbn.openmap.layer.policy.StandardPCPolicy -daynight.prettyName=Day/Night Shading -daynight.projectionChangePolicy=pcp -daynight.removable=true -daynight.renderPolicy=rp -daynight.rp.class=com.bbn.openmap.layer.policy.StandardRenderPolicy -daynight.termFade=0.1 -daynight.terminatorVerts=512 -daynight.transparency=1.0 -daynight.updateInterval=300000 -daynight.useCurrentTime=true -### end of -daynight- properties - -### -graticule- layer properties -graticule.10DegreeColor=99000000 -graticule.1DegreeColor=99003300 -graticule.5DegreeColor=99009900 -graticule.Below1DegreeColor=9900ff00 -graticule.addToBeanContext=true -graticule.autoPalette=false -graticule.background=false -graticule.class=com.bbn.openmap.layer.GraticuleLayer -graticule.consumeEvents=false -graticule.dateLineColor=99000000 -graticule.datelineColor=ff000099 -graticule.equatorColor=99ff0000 -graticule.fontSize=10 -graticule.interruptable=true -graticule.pcp.class=com.bbn.openmap.layer.policy.StandardPCPolicy -graticule.prettyName=Graticule -graticule.projectionChangePolicy=pcp -graticule.removable=true -graticule.renderPolicy=rp -graticule.rp.class=com.bbn.openmap.layer.policy.BufferedImageRenderPolicy -graticule.show1And5Lines=true -graticule.showBelow1Lines=false -graticule.showRuler=true -graticule.specialLineColor=99000000 -graticule.textColor=99000000 -graticule.threshold=2 -graticule.transparency=1.0 -### end of -graticule- properties - -### -shapePolitical- layer properties -shapePolitical.1.cap=2 -shapePolitical.1.dashPattern= -shapePolitical.1.dashPhase= -shapePolitical.1.fillColor=fff0f0f0 -shapePolitical.1.fillPattern= -shapePolitical.1.join=0 -shapePolitical.1.key=COLOR_MAP -shapePolitical.1.lineColor=ff000000 -shapePolitical.1.lineWidth=1.0 -shapePolitical.1.matted=false -shapePolitical.1.mattingColor=ff000000 -shapePolitical.1.miterLimit=10.0 -shapePolitical.1.op=equals -shapePolitical.1.pointOval=false -shapePolitical.1.pointRadius=2 -shapePolitical.1.render=true -shapePolitical.1.selectColor=ff000000 -shapePolitical.1.val=1 -shapePolitical.2.cap=2 -shapePolitical.2.dashPattern= -shapePolitical.2.dashPhase= -shapePolitical.2.fillColor=ffe9e9e9 -shapePolitical.2.fillPattern= -shapePolitical.2.join=0 -shapePolitical.2.key=COLOR_MAP -shapePolitical.2.lineColor=ff000000 -shapePolitical.2.lineWidth=1.0 -shapePolitical.2.matted=false -shapePolitical.2.mattingColor=ff000000 -shapePolitical.2.miterLimit=10.0 -shapePolitical.2.op=equals -shapePolitical.2.pointOval=false -shapePolitical.2.pointRadius=2 -shapePolitical.2.render=true -shapePolitical.2.selectColor=ff000000 -shapePolitical.2.val=2 -shapePolitical.3.cap=2 -shapePolitical.3.dashPattern= -shapePolitical.3.dashPhase= -shapePolitical.3.fillColor=ffe0e0e0 -shapePolitical.3.fillPattern= -shapePolitical.3.join=0 -shapePolitical.3.key=COLOR_MAP -shapePolitical.3.lineColor=ff000000 -shapePolitical.3.lineWidth=1.0 -shapePolitical.3.matted=false -shapePolitical.3.mattingColor=ff000000 -shapePolitical.3.miterLimit=10.0 -shapePolitical.3.op=equals -shapePolitical.3.pointOval=false -shapePolitical.3.pointRadius=2 -shapePolitical.3.render=true -shapePolitical.3.selectColor=ff000000 -shapePolitical.3.val=3 -shapePolitical.4.cap=2 -shapePolitical.4.dashPattern= -shapePolitical.4.dashPhase= -shapePolitical.4.fillColor=ffd9d9d9 -shapePolitical.4.fillPattern= -shapePolitical.4.join=0 -shapePolitical.4.key=COLOR_MAP -shapePolitical.4.lineColor=ff000000 -shapePolitical.4.lineWidth=1.0 -shapePolitical.4.matted=false -shapePolitical.4.mattingColor=ff000000 -shapePolitical.4.miterLimit=10.0 -shapePolitical.4.op=equals -shapePolitical.4.pointOval=false -shapePolitical.4.pointRadius=2 -shapePolitical.4.render=true -shapePolitical.4.selectColor=ff000000 -shapePolitical.4.val=4 -shapePolitical.5.cap=2 -shapePolitical.5.dashPattern= -shapePolitical.5.dashPhase= -shapePolitical.5.fillColor=ffd0d0d0 -shapePolitical.5.fillPattern= -shapePolitical.5.join=0 -shapePolitical.5.key=COLOR_MAP -shapePolitical.5.lineColor=ff000000 -shapePolitical.5.lineWidth=1.0 -shapePolitical.5.matted=false -shapePolitical.5.mattingColor=ff000000 -shapePolitical.5.miterLimit=10.0 -shapePolitical.5.op=equals -shapePolitical.5.pointOval=false -shapePolitical.5.pointRadius=2 -shapePolitical.5.render=true -shapePolitical.5.selectColor=ff000000 -shapePolitical.5.val=5 -shapePolitical.6.cap=2 -shapePolitical.6.dashPattern= -shapePolitical.6.dashPhase= -shapePolitical.6.fillColor=ffc9c9c9 -shapePolitical.6.fillPattern= -shapePolitical.6.join=0 -shapePolitical.6.key=COLOR_MAP -shapePolitical.6.lineColor=ff000000 -shapePolitical.6.lineWidth=1.0 -shapePolitical.6.matted=false -shapePolitical.6.mattingColor=ff000000 -shapePolitical.6.miterLimit=10.0 -shapePolitical.6.op=equals -shapePolitical.6.pointOval=false -shapePolitical.6.pointRadius=2 -shapePolitical.6.render=true -shapePolitical.6.selectColor=ff000000 -shapePolitical.6.val=6 -shapePolitical.7.cap=2 -shapePolitical.7.dashPattern= -shapePolitical.7.dashPhase= -shapePolitical.7.fillColor=ffc0c0c0 -shapePolitical.7.fillPattern= -shapePolitical.7.join=0 -shapePolitical.7.key=COLOR_MAP -shapePolitical.7.lineColor=ff000000 -shapePolitical.7.lineWidth=1.0 -shapePolitical.7.matted=false -shapePolitical.7.mattingColor=ff000000 -shapePolitical.7.miterLimit=10.0 -shapePolitical.7.op=equals -shapePolitical.7.pointOval=false -shapePolitical.7.pointRadius=2 -shapePolitical.7.render=true -shapePolitical.7.selectColor=ff000000 -shapePolitical.7.val=7 -shapePolitical.8.cap=2 -shapePolitical.8.dashPattern= -shapePolitical.8.dashPhase= -shapePolitical.8.fillColor=ffb9b9b9 -shapePolitical.8.fillPattern= -shapePolitical.8.join=0 -shapePolitical.8.key=COLOR_MAP -shapePolitical.8.lineColor=ff000000 -shapePolitical.8.lineWidth=1.0 -shapePolitical.8.matted=false -shapePolitical.8.mattingColor=ff000000 -shapePolitical.8.miterLimit=10.0 -shapePolitical.8.op=equals -shapePolitical.8.pointOval=false -shapePolitical.8.pointRadius=2 -shapePolitical.8.render=true -shapePolitical.8.selectColor=ff000000 -shapePolitical.8.val=8 -shapePolitical.addToBeanContext=true -shapePolitical.autoPalette=false -shapePolitical.background=true -shapePolitical.cap=2 -shapePolitical.class=com.bbn.openmap.layer.shape.ShapeLayer -shapePolitical.consumeEvents=false -shapePolitical.dashPattern= -shapePolitical.dashPhase= -shapePolitical.fillColor=ffdad5cb -shapePolitical.fillPattern= -shapePolitical.interruptable=true -shapePolitical.join=0 -shapePolitical.lineColor=ff000000 -shapePolitical.lineWidth=1.0 -shapePolitical.matted=false -shapePolitical.mattingColor=ff000000 -shapePolitical.miterLimit=10.0 -shapePolitical.pcp.class=com.bbn.openmap.layer.policy.ListResetPCPolicy -shapePolitical.pointImageURL= -shapePolitical.pointOval=false -shapePolitical.pointRadius=2 -shapePolitical.prettyName=Political Boundaries -shapePolitical.projectionChangePolicy=pcp -shapePolitical.removable=true -shapePolitical.rules=1 2 3 4 5 6 7 8 -shapePolitical.selectColor=ff000000 -shapePolitical.shadowX=0 -shapePolitical.shadowY=0 -shapePolitical.shapeFile=/Volumes/data/shape/world/cntry02/cntry02.shp -shapePolitical.transparency=1.0 -### end of -shapePolitical- properties diff --git a/src/wmsservlet/src/main/webapp/WEB-INF/.gitignore b/src/wmsservlet/src/main/webapp/WEB-INF/.gitignore deleted file mode 100644 index 840e7d312..000000000 --- a/src/wmsservlet/src/main/webapp/WEB-INF/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/classes/ diff --git a/src/wmsservlet/src/main/webapp/WEB-INF/web.xml b/src/wmsservlet/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 5ef2631aa..000000000 --- a/src/wmsservlet/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - OGC Web Map Server Servlet - - - - - - mapDefinition - wms.properties - - Configuration file for openmap. Default value is "openmap.properties" - - - - - - port - 8080 - - Server port number - - - - - - path - /omwms - - Path on servlet container - - - - - OgcWmsServlet - - This servlet is the entry doing for most of the work. - - com.bbn.openmap.wmsservlet.OgcWmsServlet - - - - - OgcWmsServlet - /* - - - - 30 - - - diff --git a/version.txt b/version.txt deleted file mode 100644 index 366e52229..000000000 --- a/version.txt +++ /dev/null @@ -1,2 +0,0 @@ -OpenMap 6.0 -Nov, 2020